@tangle-network/agent-eval 0.120.2 → 0.120.3

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 (171) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/analyst/index.d.ts +3111 -0
  3. package/dist/analyst/index.js +403 -0
  4. package/dist/analyst/index.js.map +1 -0
  5. package/dist/authenticity/index.d.ts +161 -0
  6. package/dist/authenticity/index.js +215 -0
  7. package/dist/authenticity/index.js.map +1 -0
  8. package/dist/belief-state/index.d.ts +1301 -0
  9. package/dist/belief-state/index.js +2152 -0
  10. package/dist/belief-state/index.js.map +1 -0
  11. package/dist/benchmarks/index.d.ts +974 -0
  12. package/dist/benchmarks/index.js +60 -0
  13. package/dist/benchmarks/index.js.map +1 -0
  14. package/dist/builder-eval/index.d.ts +695 -0
  15. package/dist/builder-eval/index.js +366 -0
  16. package/dist/builder-eval/index.js.map +1 -0
  17. package/dist/campaign/index.d.ts +7454 -0
  18. package/dist/campaign/index.js +272 -0
  19. package/dist/campaign/index.js.map +1 -0
  20. package/dist/chunk-3CDFMEMO.js +3878 -0
  21. package/dist/chunk-3CDFMEMO.js.map +1 -0
  22. package/dist/chunk-3RF76KTD.js +84 -0
  23. package/dist/chunk-3RF76KTD.js.map +1 -0
  24. package/dist/chunk-3XH4Y2SS.js +750 -0
  25. package/dist/chunk-3XH4Y2SS.js.map +1 -0
  26. package/dist/chunk-3YYRZDON.js +45 -0
  27. package/dist/chunk-3YYRZDON.js.map +1 -0
  28. package/dist/chunk-5BYTIDZ7.js +550 -0
  29. package/dist/chunk-5BYTIDZ7.js.map +1 -0
  30. package/dist/chunk-5CVUPHJ4.js +2668 -0
  31. package/dist/chunk-5CVUPHJ4.js.map +1 -0
  32. package/dist/chunk-ARU2PZFM.js +312 -0
  33. package/dist/chunk-ARU2PZFM.js.map +1 -0
  34. package/dist/chunk-BOD4O7OF.js +40 -0
  35. package/dist/chunk-BOD4O7OF.js.map +1 -0
  36. package/dist/chunk-CVJP5TMD.js +766 -0
  37. package/dist/chunk-CVJP5TMD.js.map +1 -0
  38. package/dist/chunk-DPZAEKA6.js +880 -0
  39. package/dist/chunk-DPZAEKA6.js.map +1 -0
  40. package/dist/chunk-DTJ6QUQB.js +131 -0
  41. package/dist/chunk-DTJ6QUQB.js.map +1 -0
  42. package/dist/chunk-GGE4NNQT.js +65 -0
  43. package/dist/chunk-GGE4NNQT.js.map +1 -0
  44. package/dist/chunk-H5UD2323.js +286 -0
  45. package/dist/chunk-H5UD2323.js.map +1 -0
  46. package/dist/chunk-HHWE3POT.js +94 -0
  47. package/dist/chunk-HHWE3POT.js.map +1 -0
  48. package/dist/chunk-HKUCJ437.js +787 -0
  49. package/dist/chunk-HKUCJ437.js.map +1 -0
  50. package/dist/chunk-JHCHEVET.js +274 -0
  51. package/dist/chunk-JHCHEVET.js.map +1 -0
  52. package/dist/chunk-K4DBDHLK.js +158 -0
  53. package/dist/chunk-K4DBDHLK.js.map +1 -0
  54. package/dist/chunk-K6N6XJJX.js +306 -0
  55. package/dist/chunk-K6N6XJJX.js.map +1 -0
  56. package/dist/chunk-MA6HLL3S.js +65 -0
  57. package/dist/chunk-MA6HLL3S.js.map +1 -0
  58. package/dist/chunk-MAZ26DC7.js +99 -0
  59. package/dist/chunk-MAZ26DC7.js.map +1 -0
  60. package/dist/chunk-MOXWMGPC.js +577 -0
  61. package/dist/chunk-MOXWMGPC.js.map +1 -0
  62. package/dist/chunk-NJC7U437.js +626 -0
  63. package/dist/chunk-NJC7U437.js.map +1 -0
  64. package/dist/chunk-NMN4WGSJ.js +1030 -0
  65. package/dist/chunk-NMN4WGSJ.js.map +1 -0
  66. package/dist/chunk-NPCTHQIO.js +91 -0
  67. package/dist/chunk-NPCTHQIO.js.map +1 -0
  68. package/dist/chunk-ONWEPEDO.js +57 -0
  69. package/dist/chunk-ONWEPEDO.js.map +1 -0
  70. package/dist/chunk-OYZAPX5G.js +1526 -0
  71. package/dist/chunk-OYZAPX5G.js.map +1 -0
  72. package/dist/chunk-P5MGQ2FY.js +7958 -0
  73. package/dist/chunk-P5MGQ2FY.js.map +1 -0
  74. package/dist/chunk-PC4UYEBM.js +166 -0
  75. package/dist/chunk-PC4UYEBM.js.map +1 -0
  76. package/dist/chunk-PJQFMIOX.js +1182 -0
  77. package/dist/chunk-PJQFMIOX.js.map +1 -0
  78. package/dist/chunk-PXD6ZFNY.js +1107 -0
  79. package/dist/chunk-PXD6ZFNY.js.map +1 -0
  80. package/dist/chunk-PXE2VKMX.js +140 -0
  81. package/dist/chunk-PXE2VKMX.js.map +1 -0
  82. package/dist/chunk-PZ5AY32C.js +10 -0
  83. package/dist/chunk-PZ5AY32C.js.map +1 -0
  84. package/dist/chunk-QBRSJK47.js +622 -0
  85. package/dist/chunk-QBRSJK47.js.map +1 -0
  86. package/dist/chunk-S3UZOQ5Y.js +328 -0
  87. package/dist/chunk-S3UZOQ5Y.js.map +1 -0
  88. package/dist/chunk-SQQED7ZH.js +998 -0
  89. package/dist/chunk-SQQED7ZH.js.map +1 -0
  90. package/dist/chunk-SYV364BL.js +1266 -0
  91. package/dist/chunk-SYV364BL.js.map +1 -0
  92. package/dist/chunk-T4SQEITX.js +95 -0
  93. package/dist/chunk-T4SQEITX.js.map +1 -0
  94. package/dist/chunk-TT4KNT67.js +124 -0
  95. package/dist/chunk-TT4KNT67.js.map +1 -0
  96. package/dist/chunk-U5CHZ5M3.js +357 -0
  97. package/dist/chunk-U5CHZ5M3.js.map +1 -0
  98. package/dist/chunk-ULOKLHIQ.js +1937 -0
  99. package/dist/chunk-ULOKLHIQ.js.map +1 -0
  100. package/dist/chunk-VI2UW6B6.js +162 -0
  101. package/dist/chunk-VI2UW6B6.js.map +1 -0
  102. package/dist/chunk-VQMK5FMP.js +247 -0
  103. package/dist/chunk-VQMK5FMP.js.map +1 -0
  104. package/dist/chunk-VSMTAMNK.js +53 -0
  105. package/dist/chunk-VSMTAMNK.js.map +1 -0
  106. package/dist/chunk-VZSRQ272.js +149 -0
  107. package/dist/chunk-VZSRQ272.js.map +1 -0
  108. package/dist/chunk-WW2A73HW.js +159 -0
  109. package/dist/chunk-WW2A73HW.js.map +1 -0
  110. package/dist/chunk-X4UCIOTZ.js +136 -0
  111. package/dist/chunk-X4UCIOTZ.js.map +1 -0
  112. package/dist/chunk-XJYR7XFV.js +317 -0
  113. package/dist/chunk-XJYR7XFV.js.map +1 -0
  114. package/dist/chunk-ZET2UAYW.js +89 -0
  115. package/dist/chunk-ZET2UAYW.js.map +1 -0
  116. package/dist/chunk-ZMXDQ4K7.js +870 -0
  117. package/dist/chunk-ZMXDQ4K7.js.map +1 -0
  118. package/dist/chunk-ZZUXHH3R.js +99 -0
  119. package/dist/chunk-ZZUXHH3R.js.map +1 -0
  120. package/dist/cli.d.ts +1 -0
  121. package/dist/cli.js +112 -0
  122. package/dist/cli.js.map +1 -0
  123. package/dist/contract/index.d.ts +4972 -0
  124. package/dist/contract/index.js +1654 -0
  125. package/dist/contract/index.js.map +1 -0
  126. package/dist/control.d.ts +1013 -0
  127. package/dist/control.js +34 -0
  128. package/dist/control.js.map +1 -0
  129. package/dist/fuzz.d.ts +759 -0
  130. package/dist/fuzz.js +714 -0
  131. package/dist/fuzz.js.map +1 -0
  132. package/dist/hosted/index.d.ts +730 -0
  133. package/dist/hosted/index.js +14 -0
  134. package/dist/hosted/index.js.map +1 -0
  135. package/dist/index.d.ts +16780 -0
  136. package/dist/index.js +12168 -0
  137. package/dist/index.js.map +1 -0
  138. package/dist/matrix/index.d.ts +155 -0
  139. package/dist/matrix/index.js +8 -0
  140. package/dist/matrix/index.js.map +1 -0
  141. package/dist/meta-eval/index.d.ts +1030 -0
  142. package/dist/meta-eval/index.js +417 -0
  143. package/dist/meta-eval/index.js.map +1 -0
  144. package/dist/multishot/index.d.ts +579 -0
  145. package/dist/multishot/index.js +589 -0
  146. package/dist/multishot/index.js.map +1 -0
  147. package/dist/openapi.json +992 -0
  148. package/dist/pipelines/index.d.ts +567 -0
  149. package/dist/pipelines/index.js +515 -0
  150. package/dist/pipelines/index.js.map +1 -0
  151. package/dist/reporting.d.ts +1277 -0
  152. package/dist/reporting.js +48 -0
  153. package/dist/reporting.js.map +1 -0
  154. package/dist/rl.d.ts +4092 -0
  155. package/dist/rl.js +1724 -0
  156. package/dist/rl.js.map +1 -0
  157. package/dist/run-campaign-75RTPVV5.js +14 -0
  158. package/dist/run-campaign-75RTPVV5.js.map +1 -0
  159. package/dist/storyboard/index.d.ts +279 -0
  160. package/dist/storyboard/index.js +767 -0
  161. package/dist/storyboard/index.js.map +1 -0
  162. package/dist/trace-attributes.d.ts +52 -0
  163. package/dist/trace-attributes.js +62 -0
  164. package/dist/trace-attributes.js.map +1 -0
  165. package/dist/traces.d.ts +2343 -0
  166. package/dist/traces.js +249 -0
  167. package/dist/traces.js.map +1 -0
  168. package/dist/wire/index.d.ts +1252 -0
  169. package/dist/wire/index.js +81 -0
  170. package/dist/wire/index.js.map +1 -0
  171. package/package.json +1 -1
@@ -0,0 +1,1030 @@
1
+ import {
2
+ callLlmJson,
3
+ costReceiptFromLlm,
4
+ costReceiptFromLlmError,
5
+ maximumChargeForLlmRequest
6
+ } from "./chunk-NJC7U437.js";
7
+ import {
8
+ CostLedger
9
+ } from "./chunk-ZMXDQ4K7.js";
10
+
11
+ // src/wire/schemas.ts
12
+ import { extendZodWithOpenApi } from "@asteasolutions/zod-to-openapi";
13
+ import { z } from "zod";
14
+ extendZodWithOpenApi(z);
15
+ var RubricDimensionSchema = z.object({
16
+ id: z.string().min(1).describe('Short stable id like "buyer_quality" \u2014 used as the key in scoring output.'),
17
+ description: z.string().min(1).describe("One-line plain-English meaning. Read by humans reviewing low scores."),
18
+ weight: z.number().min(0).default(1).describe("Relative weight in the composite score. Default 1; 0 disables."),
19
+ min: z.number().default(0).describe("Lower bound of valid score for this dimension."),
20
+ max: z.number().default(1).describe("Upper bound of valid score for this dimension.")
21
+ }).openapi("RubricDimension");
22
+ var FailureModeSchema = z.object({
23
+ id: z.string().min(1).describe('Short stable id like "ai-cadence" \u2014 used in detection lists.'),
24
+ description: z.string().min(1).describe("Plain-English description of the failure pattern.")
25
+ }).openapi("FailureMode");
26
+ var RubricSchema = z.object({
27
+ name: z.string().min(1).describe('Stable name like "anti-slop" \u2014 used by clients to invoke this rubric.'),
28
+ description: z.string().min(1).describe("What this rubric measures. Shown in /v1/rubrics listing."),
29
+ systemPrompt: z.string().min(1).describe(
30
+ 'Instructs the judging LLM. Should explain the persona (e.g. "senior engineer reviewing voice"), what to score on, and what to return.'
31
+ ),
32
+ dimensions: z.array(RubricDimensionSchema).min(1).describe("Scoring axes. The composite score is a weighted sum of these."),
33
+ failureModes: z.array(FailureModeSchema).default([]).describe("Patterns to detect; each detected mode appears in the result.failureModes list."),
34
+ wins: z.array(FailureModeSchema).default([]).describe("Positive patterns; each detected one appears in the result.wins list.")
35
+ }).openapi("Rubric");
36
+ var JudgeRequestSchema = z.object({
37
+ rubricName: z.string().optional().describe("Use a built-in rubric by name. Mutually exclusive with `rubric`."),
38
+ rubric: RubricSchema.optional().describe(
39
+ "Inline rubric definition. Mutually exclusive with `rubricName`."
40
+ ),
41
+ content: z.string().min(1).describe("The text being judged \u2014 a tweet, a blog post, a code snippet, anything stringly."),
42
+ context: z.record(z.string(), z.unknown()).optional().describe(
43
+ "Free-form metadata for the rubric to use \u2014 analytics, source URL, author, etc. Surfaced to the LLM."
44
+ ),
45
+ model: z.string().optional().describe('Override the judge model (default routes via tcloud). e.g. "claude-opus-4-7".')
46
+ }).refine((v) => Boolean(v.rubricName) !== Boolean(v.rubric), {
47
+ message: "Provide exactly one of `rubricName` or `rubric`."
48
+ }).openapi("JudgeRequest");
49
+ var JudgeResultSchema = z.object({
50
+ composite: z.number().min(0).max(1).describe("Weighted combination of dimension scores in 0..1. The single number to gate on."),
51
+ dimensions: z.record(z.string(), z.number()).describe("Per-dimension score, keyed by RubricDimension.id."),
52
+ failureModes: z.array(z.string()).default([]).describe("Failure-mode ids detected in the content (subset of rubric.failureModes ids)."),
53
+ wins: z.array(z.string()).default([]).describe("Win ids detected in the content (subset of rubric.wins ids)."),
54
+ rationale: z.string().describe("Plain-English explanation of the score. Surfaced to the human reviewer."),
55
+ rubricVersion: z.string().describe(
56
+ "Stable hash of the rubric used. Scores are only comparable across runs when this matches."
57
+ ),
58
+ model: z.string().describe("Model that produced the judgement, for reproducibility."),
59
+ durationMs: z.number().int().nonnegative().describe("End-to-end wall time for this call.")
60
+ }).openapi("JudgeResult");
61
+ var RubricInfoSchema = z.object({
62
+ name: z.string().describe("Pass this to /v1/judge as `rubricName`."),
63
+ description: z.string().describe("What this rubric measures."),
64
+ dimensions: z.array(z.object({ id: z.string(), description: z.string(), weight: z.number() })).describe("The scoring axes this rubric uses, with weights."),
65
+ failureModes: z.array(z.string()).default([]).describe("Failure-mode ids this rubric detects."),
66
+ rubricVersion: z.string().describe("Stable hash \u2014 match this to compare scores across runs.")
67
+ }).openapi("RubricInfo");
68
+ var ListRubricsResponseSchema = z.object({
69
+ rubrics: z.array(RubricInfoSchema)
70
+ }).openapi("ListRubricsResponse");
71
+ var VersionResponseSchema = z.object({
72
+ package: z.string().describe('Package name (always "@tangle-network/agent-eval").'),
73
+ version: z.string().describe("Semver of the running server. Match your client to this."),
74
+ wireVersion: z.string().describe(
75
+ "Wire-protocol semver. Bumps separately from package version when the schema changes."
76
+ ),
77
+ apiSurface: z.array(z.string()).describe("List of supported method names.")
78
+ }).openapi("VersionResponse");
79
+ var HealthResponseSchema = z.object({
80
+ status: z.literal("ok"),
81
+ uptimeSec: z.number()
82
+ }).openapi("HealthResponse");
83
+ var TraceEventSchema = z.object({
84
+ eventId: z.string().min(1).describe("Stable id for the event. Use ULID or UUID."),
85
+ runId: z.string().min(1).describe("Run this event belongs to."),
86
+ spanId: z.string().optional().describe("Span that emitted the event, if any."),
87
+ kind: z.enum([
88
+ "log",
89
+ "error",
90
+ "budget_decrement",
91
+ "budget_breach",
92
+ "state_mutation",
93
+ "policy_violation",
94
+ "redaction_applied",
95
+ "custom"
96
+ ]).describe("Coarse event category \u2014 matches the TraceSchema v1 EventKind enum."),
97
+ timestamp: z.number().int().nonnegative().describe("Unix millis. Must be monotonically non-decreasing within a span."),
98
+ payload: z.record(z.string(), z.unknown()).describe("Free-form payload \u2014 the runtime owns the shape.")
99
+ }).openapi("TraceEvent");
100
+ var TracesIngestRequestSchema = z.object({
101
+ events: z.array(TraceEventSchema).min(1).max(1e4).describe("Batch of events. Max 10k per call \u2014 bigger streams should be chunked.")
102
+ }).openapi("TracesIngestRequest");
103
+ var TracesIngestResponseSchema = z.object({
104
+ accepted: z.number().int().nonnegative().describe("Number of events persisted."),
105
+ rejected: z.number().int().nonnegative().describe("Number of events the store refused \u2014 see `errors[]` for reasons."),
106
+ errors: z.array(
107
+ z.object({
108
+ eventId: z.string().describe("Event id this error applies to."),
109
+ message: z.string().describe("Why the event was rejected.")
110
+ })
111
+ ).default([])
112
+ }).openapi("TracesIngestResponse");
113
+ var FeedbackLabelSchema = z.object({
114
+ id: z.string().optional(),
115
+ source: z.enum(["user", "judge", "environment", "metric", "policy", "system"]),
116
+ kind: z.enum([
117
+ "approve",
118
+ "reject",
119
+ "select",
120
+ "edit",
121
+ "rank",
122
+ "rate",
123
+ "comment",
124
+ "metric_outcome",
125
+ "policy_block",
126
+ "revision_request"
127
+ ]),
128
+ value: z.unknown(),
129
+ reason: z.string().optional(),
130
+ severity: z.enum(["info", "warning", "error", "critical"]).optional(),
131
+ createdAt: z.string().describe("ISO-8601 UTC."),
132
+ metadata: z.record(z.string(), z.unknown()).optional()
133
+ }).openapi("FeedbackLabel");
134
+ var FeedbackAttemptSchema = z.object({
135
+ id: z.string().min(1),
136
+ stepIndex: z.number().int().nonnegative(),
137
+ artifactType: z.enum([
138
+ "text",
139
+ "code",
140
+ "plan",
141
+ "research",
142
+ "action",
143
+ "ui",
144
+ "decision",
145
+ "data",
146
+ "other"
147
+ ]),
148
+ artifact: z.unknown(),
149
+ options: z.array(z.unknown()).optional(),
150
+ proposedAction: z.object({
151
+ type: z.string(),
152
+ risk: z.enum(["low", "medium", "high"]).optional(),
153
+ costUsd: z.number().optional(),
154
+ externalSideEffect: z.boolean().optional(),
155
+ requiresApproval: z.boolean().optional(),
156
+ metadata: z.record(z.string(), z.unknown()).optional()
157
+ }).optional(),
158
+ feedback: z.array(FeedbackLabelSchema).optional(),
159
+ createdAt: z.string(),
160
+ metadata: z.record(z.string(), z.unknown()).optional()
161
+ }).openapi("FeedbackAttempt");
162
+ var FeedbackTrajectorySchema = z.object({
163
+ id: z.string().min(1).describe("Stable id; idempotency key for the trajectory."),
164
+ projectId: z.string().optional(),
165
+ scenarioId: z.string().optional(),
166
+ task: z.object({
167
+ intent: z.string().min(1),
168
+ context: z.unknown().optional()
169
+ }),
170
+ attempts: z.array(FeedbackAttemptSchema).default([]),
171
+ labels: z.array(FeedbackLabelSchema).default([]),
172
+ outcome: z.object({
173
+ success: z.boolean().optional(),
174
+ score: z.number().optional(),
175
+ metrics: z.record(z.string(), z.number()).optional(),
176
+ costUsd: z.number().optional(),
177
+ detail: z.string().optional(),
178
+ observedAt: z.string().optional(),
179
+ metadata: z.record(z.string(), z.unknown()).optional()
180
+ }).optional(),
181
+ split: z.enum(["train", "dev", "test", "holdout"]).optional(),
182
+ tags: z.record(z.string(), z.string()).optional(),
183
+ createdAt: z.string().describe("ISO-8601 UTC."),
184
+ updatedAt: z.string().optional(),
185
+ metadata: z.record(z.string(), z.unknown()).optional()
186
+ }).openapi("FeedbackTrajectory");
187
+ var FeedbackIngestResponseSchema = z.object({
188
+ id: z.string().describe("Trajectory id that was persisted."),
189
+ persisted: z.boolean().describe("True when the trajectory was saved (idempotent on id).")
190
+ }).openapi("FeedbackIngestResponse");
191
+ var ErrorResponseSchema = z.object({
192
+ error: z.object({
193
+ code: z.string().describe(
194
+ 'Machine-readable code: "validation_error", "rubric_not_found", "judge_error".'
195
+ ),
196
+ message: z.string().describe("Human-readable message."),
197
+ details: z.unknown().optional().describe("Optional structured detail.")
198
+ }).describe("Errors are always wrapped in this shape across all endpoints.")
199
+ }).openapi("ErrorResponse");
200
+ var WIRE_VERSION = "1.0.0";
201
+ function hashRubric(rubric) {
202
+ const stable = stableStringify(rubric);
203
+ let h = 5381;
204
+ for (let i = 0; i < stable.length; i++) {
205
+ h = h * 33 ^ stable.charCodeAt(i);
206
+ }
207
+ return `${rubric.name}@${(h >>> 0).toString(16).padStart(8, "0")}`;
208
+ }
209
+ function stableStringify(value) {
210
+ if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(",")}]`;
211
+ if (value && typeof value === "object") {
212
+ const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`);
213
+ return `{${entries.join(",")}}`;
214
+ }
215
+ return JSON.stringify(value);
216
+ }
217
+
218
+ // src/wire/rubrics.ts
219
+ var ANTI_SLOP = {
220
+ name: "anti-slop",
221
+ description: "Voice and signal quality for content aimed at senior engineers. Catches AI cadence, marketing tone, and engagement-bait shapes.",
222
+ systemPrompt: `You are evaluating a piece of content written for senior engineers and technical founders.
223
+
224
+ You score three things:
225
+ - buyer_quality (0..1): would a senior engineer in the target ICP find this worth their attention? High = specific, earned, technically interesting. Low = generic, hyped, off-target.
226
+ - voice (0..1): does it read like a person who built the thing, or like AI/marketing copy?
227
+ - signal (0..1): does it contain a non-obvious detail, constraint, or claim a reader couldn't get from the public docs?
228
+
229
+ Detect failure modes (return ids matching):
230
+ - ai-cadence: rule-of-three openings, em-dash flourish, "Let me explain", "Here's the thing", AI rhythm
231
+ - marketing-tone: "We're excited to announce", "thrilled", "delighted", "game-changer", buzzword stack
232
+ - vague-claim: technical claim without a specific component, file, or measurement
233
+ - no-hook: opening doesn't earn attention from the target reader
234
+ - engagement-bait: "agree?", "thoughts?", listicles, controversy-fishing, hook-detail-pitch
235
+ - off-icp: content shape would attract motivational/grift/hype audiences instead of buyers
236
+ - stale-claim: repeats a positioning line we've used many times this month
237
+
238
+ Detect wins (return ids matching):
239
+ - specific-component: names a real file, component, or measurement
240
+ - earned-detail: shares a non-obvious detail not derivable from public docs
241
+ - constraint-articulated: names a real tradeoff and the side chosen
242
+ - honest-failure: describes a real failure mode and what was done about it
243
+
244
+ Return ONLY JSON matching the response schema. Be conservative \u2014 most content has 0-1 wins and 1-2 failure modes, not many of each.`,
245
+ dimensions: [
246
+ {
247
+ id: "buyer_quality",
248
+ description: "Would the target buyer find this worth attention?",
249
+ weight: 0.5,
250
+ min: 0,
251
+ max: 1
252
+ },
253
+ {
254
+ id: "voice",
255
+ description: "Does it sound like a builder, not AI or marketing?",
256
+ weight: 0.3,
257
+ min: 0,
258
+ max: 1
259
+ },
260
+ {
261
+ id: "signal",
262
+ description: "Non-obvious detail, constraint, or claim?",
263
+ weight: 0.2,
264
+ min: 0,
265
+ max: 1
266
+ }
267
+ ],
268
+ failureModes: [
269
+ { id: "ai-cadence", description: "AI-rhythm openings and transitions" },
270
+ { id: "marketing-tone", description: "Buzzwords, hype, corporate-PR voice" },
271
+ { id: "vague-claim", description: "Technical claim without specifics" },
272
+ { id: "no-hook", description: "Opening fails to earn attention" },
273
+ { id: "engagement-bait", description: "Listicle/controversy/agree-pattern" },
274
+ { id: "off-icp", description: "Voice attracts the wrong audience" },
275
+ { id: "stale-claim", description: "Reuses an over-used positioning line" }
276
+ ],
277
+ wins: [
278
+ { id: "specific-component", description: "Names a real file/component/number" },
279
+ { id: "earned-detail", description: "Detail not in public docs" },
280
+ { id: "constraint-articulated", description: "Names a real tradeoff" },
281
+ { id: "honest-failure", description: "Describes a real failure honestly" }
282
+ ]
283
+ };
284
+ var BUILTIN_RUBRICS = {
285
+ "anti-slop": ANTI_SLOP
286
+ };
287
+ function getBuiltinRubric(name) {
288
+ return BUILTIN_RUBRICS[name];
289
+ }
290
+ function listBuiltinRubrics() {
291
+ return Object.values(BUILTIN_RUBRICS).map((r) => ({
292
+ name: r.name,
293
+ description: r.description,
294
+ dimensions: r.dimensions.map((d) => ({
295
+ id: d.id,
296
+ description: d.description,
297
+ weight: d.weight
298
+ })),
299
+ failureModes: r.failureModes.map((f) => f.id),
300
+ rubricVersion: hashRubric(r)
301
+ }));
302
+ }
303
+
304
+ // src/wire/handlers.ts
305
+ import { readFileSync } from "fs";
306
+ import { dirname, resolve } from "path";
307
+ import { fileURLToPath } from "url";
308
+ var WireError = class extends Error {
309
+ constructor(code, message, status = 400, details) {
310
+ super(message);
311
+ this.code = code;
312
+ this.status = status;
313
+ this.details = details;
314
+ this.name = "WireError";
315
+ }
316
+ code;
317
+ status;
318
+ details;
319
+ };
320
+ function judgeOutputSchema(rubric) {
321
+ return {
322
+ name: "JudgeOutput",
323
+ schema: {
324
+ type: "object",
325
+ additionalProperties: false,
326
+ properties: {
327
+ dimensions: {
328
+ type: "object",
329
+ additionalProperties: false,
330
+ properties: Object.fromEntries(
331
+ rubric.dimensions.map((d) => [
332
+ d.id,
333
+ { type: "number", minimum: d.min, maximum: d.max }
334
+ ])
335
+ ),
336
+ required: rubric.dimensions.map((d) => d.id)
337
+ },
338
+ failureModes: {
339
+ type: "array",
340
+ items: { type: "string", enum: rubric.failureModes.map((f) => f.id) }
341
+ },
342
+ wins: {
343
+ type: "array",
344
+ items: { type: "string", enum: rubric.wins.map((w) => w.id) }
345
+ },
346
+ rationale: { type: "string" }
347
+ },
348
+ required: ["dimensions", "rationale"]
349
+ }
350
+ };
351
+ }
352
+ function validateJudgeOutput(value, rubric) {
353
+ if (!value || typeof value !== "object") {
354
+ throw new WireError("judge_error", "Judge returned malformed output.", 500, value);
355
+ }
356
+ const raw = value;
357
+ const rawDimensions = raw.dimensions;
358
+ if (!rawDimensions || typeof rawDimensions !== "object" || Array.isArray(rawDimensions)) {
359
+ throw new WireError("judge_error", "Judge returned malformed dimensions.", 500, value);
360
+ }
361
+ const dimensions = {};
362
+ const dimensionRecord = rawDimensions;
363
+ for (const dim of rubric.dimensions) {
364
+ const score = dimensionRecord[dim.id];
365
+ if (typeof score !== "number" || !Number.isFinite(score) || score < dim.min || score > dim.max) {
366
+ throw new WireError(
367
+ "judge_error",
368
+ `Judge returned invalid score for dimension "${dim.id}".`,
369
+ 500,
370
+ value
371
+ );
372
+ }
373
+ dimensions[dim.id] = score;
374
+ }
375
+ const allowedFailures = new Set(rubric.failureModes.map((mode) => mode.id));
376
+ const allowedWins = new Set(rubric.wins.map((win) => win.id));
377
+ const failureModes = validateIdArray(raw.failureModes, allowedFailures, "failureModes", value);
378
+ const wins = validateIdArray(raw.wins, allowedWins, "wins", value);
379
+ if (typeof raw.rationale !== "string" || raw.rationale.trim().length === 0) {
380
+ throw new WireError("judge_error", "Judge returned missing rationale.", 500, value);
381
+ }
382
+ return { dimensions, failureModes, wins, rationale: raw.rationale };
383
+ }
384
+ function validateIdArray(raw, allowed, field, original) {
385
+ if (raw === void 0) return [];
386
+ if (!Array.isArray(raw)) {
387
+ throw new WireError("judge_error", `Judge returned non-array ${field}.`, 500, original);
388
+ }
389
+ const out = [];
390
+ for (const item of raw) {
391
+ if (typeof item !== "string" || !allowed.has(item)) {
392
+ throw new WireError(
393
+ "judge_error",
394
+ `Judge returned unknown ${field} id "${String(item)}".`,
395
+ 500,
396
+ original
397
+ );
398
+ }
399
+ out.push(item);
400
+ }
401
+ return out;
402
+ }
403
+ function compositeScore(dimensions, rubric) {
404
+ let weighted = 0;
405
+ let totalWeight = 0;
406
+ for (const dim of rubric.dimensions) {
407
+ const raw = dimensions[dim.id] ?? 0;
408
+ const range = dim.max - dim.min || 1;
409
+ const normalized = Math.max(0, Math.min(1, (raw - dim.min) / range));
410
+ weighted += normalized * dim.weight;
411
+ totalWeight += dim.weight;
412
+ }
413
+ return totalWeight > 0 ? weighted / totalWeight : 0;
414
+ }
415
+ function buildJudgePrompt(content, context) {
416
+ const ctx = context && Object.keys(context).length ? JSON.stringify(context) : "";
417
+ return [
418
+ `CONTENT TO JUDGE:`,
419
+ content,
420
+ "",
421
+ ctx ? `CONTEXT (metadata, analytics, etc.):` : "",
422
+ ctx ? ctx : ""
423
+ ].filter(Boolean).join("\n");
424
+ }
425
+ var DEFAULT_JUDGE_MODEL = "claude-sonnet-4-6";
426
+ async function handleJudge(req, options = {}) {
427
+ let rubric;
428
+ if (req.rubricName) {
429
+ const found = getBuiltinRubric(req.rubricName);
430
+ if (!found) {
431
+ throw new WireError("rubric_not_found", `No built-in rubric named "${req.rubricName}".`, 404);
432
+ }
433
+ rubric = found;
434
+ } else if (req.rubric) {
435
+ rubric = req.rubric;
436
+ } else {
437
+ throw new WireError("validation_error", "Provide either `rubricName` or `rubric`.", 422);
438
+ }
439
+ const startedAt = Date.now();
440
+ const model = req.model ?? DEFAULT_JUDGE_MODEL;
441
+ const request = {
442
+ model,
443
+ messages: [
444
+ { role: "system", content: rubric.systemPrompt },
445
+ { role: "user", content: buildJudgePrompt(req.content, req.context) }
446
+ ],
447
+ jsonSchema: judgeOutputSchema(rubric),
448
+ temperature: 0,
449
+ maxTokens: 4e3,
450
+ timeoutMs: 6e4
451
+ };
452
+ const ledger = options.costLedger ?? new CostLedger();
453
+ const paid = await ledger.runPaidCall({
454
+ channel: "judge",
455
+ phase: options.costPhase ?? "wire.judge",
456
+ actor: `wire.${req.rubricName ?? "inline"}`,
457
+ model,
458
+ maximumCharge: maximumChargeForLlmRequest(request, options.llm),
459
+ signal: options.signal,
460
+ execute: (signal, callId) => callLlmJson(request, {
461
+ ...options.llm,
462
+ signal,
463
+ idempotencyKey: callId
464
+ }),
465
+ receipt: ({ result: result2 }) => costReceiptFromLlm(result2),
466
+ receiptFromError: costReceiptFromLlmError
467
+ });
468
+ if (!paid.succeeded) throw paid.error;
469
+ const { value, result } = paid.value;
470
+ const output = validateJudgeOutput(value, rubric);
471
+ const composite = compositeScore(output.dimensions, rubric);
472
+ const durationMs = Date.now() - startedAt;
473
+ return {
474
+ composite,
475
+ dimensions: output.dimensions,
476
+ failureModes: output.failureModes ?? [],
477
+ wins: output.wins ?? [],
478
+ rationale: output.rationale,
479
+ rubricVersion: hashRubric(rubric),
480
+ model: result.model,
481
+ durationMs
482
+ };
483
+ }
484
+ function handleListRubrics() {
485
+ return { rubrics: listBuiltinRubrics() };
486
+ }
487
+ var CACHED_VERSION;
488
+ function readPackageVersion() {
489
+ if (CACHED_VERSION) return CACHED_VERSION;
490
+ const here = dirname(fileURLToPath(import.meta.url));
491
+ const candidates = [
492
+ resolve(here, "..", "..", "package.json"),
493
+ // src/wire → repo root
494
+ resolve(here, "..", "package.json")
495
+ // dist → repo root
496
+ ];
497
+ for (const path of candidates) {
498
+ try {
499
+ const pkg = JSON.parse(readFileSync(path, "utf-8"));
500
+ if (pkg.version) {
501
+ CACHED_VERSION = pkg.version;
502
+ return pkg.version;
503
+ }
504
+ } catch {
505
+ }
506
+ }
507
+ return "0.0.0-unknown";
508
+ }
509
+ function handleVersion() {
510
+ return {
511
+ package: "@tangle-network/agent-eval",
512
+ version: readPackageVersion(),
513
+ wireVersion: WIRE_VERSION,
514
+ apiSurface: ["judge", "listRubrics", "version", "feedback.ingest", "traces.ingest"]
515
+ };
516
+ }
517
+ async function handleTracesIngest(req, stores) {
518
+ if (!stores.traceStore) {
519
+ throw new WireError(
520
+ "service_unavailable",
521
+ "No trace store configured on this server. Pass `traceStore` to `createApp`.",
522
+ 503
523
+ );
524
+ }
525
+ const errors = [];
526
+ let accepted = 0;
527
+ for (const event of req.events) {
528
+ try {
529
+ await stores.traceStore.appendEvent(event);
530
+ accepted++;
531
+ } catch (err) {
532
+ errors.push({
533
+ eventId: event.eventId,
534
+ message: err instanceof Error ? err.message : String(err)
535
+ });
536
+ }
537
+ }
538
+ return { accepted, rejected: errors.length, errors };
539
+ }
540
+ async function handleFeedbackIngest(req, stores) {
541
+ if (!stores.feedbackStore) {
542
+ throw new WireError(
543
+ "service_unavailable",
544
+ "No feedback store configured on this server. Pass `feedbackStore` to `createApp`.",
545
+ 503
546
+ );
547
+ }
548
+ await stores.feedbackStore.save(req);
549
+ return { id: req.id, persisted: true };
550
+ }
551
+
552
+ // src/wire/openapi.ts
553
+ import { OpenAPIRegistry, OpenApiGeneratorV31 } from "@asteasolutions/zod-to-openapi";
554
+ function buildOpenApi(packageVersion) {
555
+ const registry = new OpenAPIRegistry();
556
+ registry.register("JudgeRequest", JudgeRequestSchema);
557
+ registry.register("JudgeResult", JudgeResultSchema);
558
+ registry.register("ListRubricsResponse", ListRubricsResponseSchema);
559
+ registry.register("VersionResponse", VersionResponseSchema);
560
+ registry.register("HealthResponse", HealthResponseSchema);
561
+ registry.register("ErrorResponse", ErrorResponseSchema);
562
+ registry.register("TracesIngestRequest", TracesIngestRequestSchema);
563
+ registry.register("TracesIngestResponse", TracesIngestResponseSchema);
564
+ registry.register("FeedbackTrajectory", FeedbackTrajectorySchema);
565
+ registry.register("FeedbackIngestResponse", FeedbackIngestResponseSchema);
566
+ registry.registerPath({
567
+ method: "post",
568
+ path: "/v1/judge",
569
+ summary: "Score a piece of content against a rubric",
570
+ description: "Runs the judging LLM with the named (or inline) rubric and returns dimension scores, detected failure modes, wins, and a composite score in 0..1.",
571
+ request: {
572
+ body: {
573
+ content: {
574
+ "application/json": { schema: JudgeRequestSchema }
575
+ }
576
+ }
577
+ },
578
+ responses: {
579
+ 200: {
580
+ description: "Successful judgement",
581
+ content: { "application/json": { schema: JudgeResultSchema } }
582
+ },
583
+ 400: {
584
+ description: "Validation error",
585
+ content: { "application/json": { schema: ErrorResponseSchema } }
586
+ },
587
+ 404: {
588
+ description: "Rubric not found",
589
+ content: { "application/json": { schema: ErrorResponseSchema } }
590
+ },
591
+ 500: {
592
+ description: "Judge error",
593
+ content: { "application/json": { schema: ErrorResponseSchema } }
594
+ }
595
+ }
596
+ });
597
+ registry.registerPath({
598
+ method: "get",
599
+ path: "/v1/rubrics",
600
+ summary: "List built-in rubrics",
601
+ description: "Returns every rubric registered server-side, with their dimensions and stable rubricVersion hash.",
602
+ responses: {
603
+ 200: {
604
+ description: "Listing",
605
+ content: { "application/json": { schema: ListRubricsResponseSchema } }
606
+ }
607
+ }
608
+ });
609
+ registry.registerPath({
610
+ method: "get",
611
+ path: "/v1/version",
612
+ summary: "Server and wire-protocol version",
613
+ description: "Match your client version to `version`; check `wireVersion` for compatibility.",
614
+ responses: {
615
+ 200: {
616
+ description: "Version info",
617
+ content: { "application/json": { schema: VersionResponseSchema } }
618
+ }
619
+ }
620
+ });
621
+ registry.registerPath({
622
+ method: "get",
623
+ path: "/healthz",
624
+ summary: "Liveness check",
625
+ responses: {
626
+ 200: {
627
+ description: "OK",
628
+ content: { "application/json": { schema: HealthResponseSchema } }
629
+ }
630
+ }
631
+ });
632
+ registry.registerPath({
633
+ method: "post",
634
+ path: "/v1/traces/ingest",
635
+ summary: "Ingest a batch of production TraceEvents",
636
+ description: "Append a batch of TraceEvents to the configured TraceStore. Accepts application/json ({events:[...]}) or application/x-ndjson (one event per line). Returns counts of accepted + rejected events.",
637
+ request: {
638
+ body: {
639
+ content: {
640
+ "application/json": { schema: TracesIngestRequestSchema },
641
+ "application/x-ndjson": { schema: TracesIngestRequestSchema }
642
+ }
643
+ }
644
+ },
645
+ responses: {
646
+ 200: {
647
+ description: "Ingestion summary",
648
+ content: { "application/json": { schema: TracesIngestResponseSchema } }
649
+ },
650
+ 400: {
651
+ description: "Validation error",
652
+ content: { "application/json": { schema: ErrorResponseSchema } }
653
+ },
654
+ 401: {
655
+ description: "Unauthorized (when bearer auth is configured)",
656
+ content: { "application/json": { schema: ErrorResponseSchema } }
657
+ },
658
+ 503: {
659
+ description: "No trace store configured",
660
+ content: { "application/json": { schema: ErrorResponseSchema } }
661
+ }
662
+ }
663
+ });
664
+ registry.registerPath({
665
+ method: "post",
666
+ path: "/v1/feedback",
667
+ summary: "Ingest a FeedbackTrajectory from production",
668
+ description: "Persist a single FeedbackTrajectory. Idempotent on trajectory.id \u2014 re-posting replaces the prior record. Used by production runtimes to forward user \u{1F44D}/\u{1F44E}/edits into the eval substrate.",
669
+ request: {
670
+ body: {
671
+ content: {
672
+ "application/json": { schema: FeedbackTrajectorySchema }
673
+ }
674
+ }
675
+ },
676
+ responses: {
677
+ 200: {
678
+ description: "Persisted",
679
+ content: { "application/json": { schema: FeedbackIngestResponseSchema } }
680
+ },
681
+ 400: {
682
+ description: "Validation error",
683
+ content: { "application/json": { schema: ErrorResponseSchema } }
684
+ },
685
+ 401: {
686
+ description: "Unauthorized (when bearer auth is configured)",
687
+ content: { "application/json": { schema: ErrorResponseSchema } }
688
+ },
689
+ 503: {
690
+ description: "No feedback store configured",
691
+ content: { "application/json": { schema: ErrorResponseSchema } }
692
+ }
693
+ }
694
+ });
695
+ const generator = new OpenApiGeneratorV31(registry.definitions);
696
+ const doc = generator.generateDocument({
697
+ openapi: "3.1.0",
698
+ info: {
699
+ title: "@tangle-network/agent-eval \u2014 wire protocol",
700
+ version: packageVersion,
701
+ description: `HTTP and stdio RPC interface to agent-eval. The TypeScript runtime is the source of truth; this spec is the contract that cross-language clients (Python, Rust, Go) generate from.
702
+
703
+ Wire-protocol version: ${WIRE_VERSION}. Bumps on breaking changes to request/response schemas.`,
704
+ contact: { name: "Tangle Network", url: "https://github.com/tangle-network/agent-eval" },
705
+ license: { name: "MIT" }
706
+ },
707
+ servers: [{ url: "http://localhost:5005", description: "Local agent-eval serve" }]
708
+ });
709
+ const rubricRef = { $ref: "#/components/schemas/Rubric" };
710
+ const commonJudgeFields = {
711
+ content: { type: "string", minLength: 1 },
712
+ context: { type: "object", additionalProperties: true },
713
+ model: { type: "string" }
714
+ };
715
+ doc.components ??= {};
716
+ doc.components.schemas ??= {};
717
+ doc.components.schemas.JudgeRequest = {
718
+ oneOf: [
719
+ {
720
+ type: "object",
721
+ additionalProperties: false,
722
+ required: ["rubricName", "content"],
723
+ properties: {
724
+ rubricName: { type: "string", minLength: 1 },
725
+ ...commonJudgeFields
726
+ }
727
+ },
728
+ {
729
+ type: "object",
730
+ additionalProperties: false,
731
+ required: ["rubric", "content"],
732
+ properties: {
733
+ rubric: rubricRef,
734
+ ...commonJudgeFields
735
+ }
736
+ }
737
+ ],
738
+ description: "Judge request. Provide exactly one of rubricName or rubric."
739
+ };
740
+ return doc;
741
+ }
742
+
743
+ // src/wire/rpc.ts
744
+ async function dispatchRpc(req) {
745
+ try {
746
+ switch (req.method) {
747
+ case "judge": {
748
+ const parsed = JudgeRequestSchema.safeParse(req.params);
749
+ if (!parsed.success) {
750
+ return {
751
+ error: {
752
+ code: "validation_error",
753
+ message: "params did not match JudgeRequest schema.",
754
+ details: parsed.error.issues
755
+ }
756
+ };
757
+ }
758
+ return { result: await handleJudge(parsed.data) };
759
+ }
760
+ case "listRubrics":
761
+ return { result: handleListRubrics() };
762
+ case "version":
763
+ return { result: handleVersion() };
764
+ default:
765
+ return {
766
+ error: {
767
+ code: "unknown_method",
768
+ message: `No such method: ${req.method}`
769
+ }
770
+ };
771
+ }
772
+ } catch (err) {
773
+ if (err instanceof WireError) {
774
+ return { error: { code: err.code, message: err.message, details: err.details } };
775
+ }
776
+ const message = err instanceof Error ? err.message : String(err);
777
+ return { error: { code: "internal_error", message } };
778
+ }
779
+ }
780
+ async function readAll(stream) {
781
+ const chunks = [];
782
+ for await (const chunk of stream) {
783
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
784
+ }
785
+ return Buffer.concat(chunks).toString("utf-8");
786
+ }
787
+ async function runRpcOnce(method) {
788
+ const raw = await readAll(process.stdin);
789
+ let req;
790
+ try {
791
+ const body = JSON.parse(raw);
792
+ req = method ? { method, params: body } : body;
793
+ } catch (err) {
794
+ process.stdout.write(
795
+ `${JSON.stringify({
796
+ error: {
797
+ code: "parse_error",
798
+ message: `stdin was not valid JSON: ${err instanceof Error ? err.message : String(err)}`
799
+ }
800
+ })}
801
+ `
802
+ );
803
+ return 1;
804
+ }
805
+ const out = await dispatchRpc(req);
806
+ process.stdout.write(`${JSON.stringify(out)}
807
+ `);
808
+ return "error" in out ? 1 : 0;
809
+ }
810
+ async function runRpcBatch(method) {
811
+ const raw = await readAll(process.stdin);
812
+ const lines = raw.split("\n").filter((l) => l.trim().length > 0);
813
+ let exitCode = 0;
814
+ for (const line of lines) {
815
+ let req;
816
+ try {
817
+ const body = JSON.parse(line);
818
+ req = method ? { method, params: body } : body;
819
+ } catch (err) {
820
+ process.stdout.write(
821
+ `${JSON.stringify({
822
+ error: {
823
+ code: "parse_error",
824
+ message: `line was not valid JSON: ${err instanceof Error ? err.message : String(err)}`
825
+ }
826
+ })}
827
+ `
828
+ );
829
+ exitCode = 1;
830
+ continue;
831
+ }
832
+ const out = await dispatchRpc(req);
833
+ process.stdout.write(`${JSON.stringify(out)}
834
+ `);
835
+ if ("error" in out) exitCode = 1;
836
+ }
837
+ return exitCode;
838
+ }
839
+
840
+ // src/wire/server.ts
841
+ import { serve } from "@hono/node-server";
842
+ import { Hono } from "hono";
843
+ import { cors } from "hono/cors";
844
+ var STARTED_AT = Date.now();
845
+ var AUTH_EXEMPT_PATHS = /* @__PURE__ */ new Set(["/healthz", "/v1/version", "/openapi.json"]);
846
+ function createApp(opts = {}) {
847
+ const app = new Hono();
848
+ app.use("*", cors());
849
+ if (opts.auth) {
850
+ const verify = opts.auth.bearer;
851
+ app.use("*", async (c, next) => {
852
+ const path = new URL(c.req.url).pathname;
853
+ if (AUTH_EXEMPT_PATHS.has(path)) return next();
854
+ const raw = c.req.header("authorization") ?? "";
855
+ const match = raw.match(/^Bearer\s+(.+)$/i);
856
+ if (!match) {
857
+ throw new WireError("unauthorized", "Missing or malformed Authorization header.", 401);
858
+ }
859
+ const token = match[1];
860
+ const ok = typeof verify === "string" ? token === verify : await verify(token);
861
+ if (!ok) {
862
+ throw new WireError("unauthorized", "Invalid bearer token.", 401);
863
+ }
864
+ return next();
865
+ });
866
+ }
867
+ app.onError((err, c) => {
868
+ if (err instanceof WireError) {
869
+ const status = err.status;
870
+ return c.json(
871
+ { error: { code: err.code, message: err.message, details: err.details } },
872
+ status
873
+ );
874
+ }
875
+ console.error("[agent-eval] unhandled error:", err);
876
+ return c.json({ error: { code: "internal_error", message: "Internal server error." } }, 500);
877
+ });
878
+ app.get(
879
+ "/healthz",
880
+ (c) => c.json({ status: "ok", uptimeSec: (Date.now() - STARTED_AT) / 1e3 })
881
+ );
882
+ app.get("/v1/version", (c) => c.json(handleVersion()));
883
+ app.get("/v1/rubrics", (c) => c.json(handleListRubrics()));
884
+ app.post("/v1/judge", async (c) => {
885
+ const raw = await c.req.json().catch(() => null);
886
+ if (raw == null) {
887
+ throw new WireError("validation_error", "Request body must be JSON.", 400);
888
+ }
889
+ const parsed = JudgeRequestSchema.safeParse(raw);
890
+ if (!parsed.success) {
891
+ throw new WireError(
892
+ "validation_error",
893
+ "Request did not match JudgeRequest schema.",
894
+ 400,
895
+ parsed.error.issues
896
+ );
897
+ }
898
+ const result = await handleJudge(parsed.data);
899
+ return c.json(result);
900
+ });
901
+ app.post("/v1/traces/ingest", async (c) => {
902
+ const contentType = c.req.header("content-type") ?? "";
903
+ let payload;
904
+ if (contentType.includes("application/x-ndjson")) {
905
+ const text = await c.req.text();
906
+ const events = text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0).map((line) => {
907
+ try {
908
+ return JSON.parse(line);
909
+ } catch {
910
+ throw new WireError(
911
+ "validation_error",
912
+ "NDJSON line did not parse as JSON.",
913
+ 400,
914
+ line.slice(0, 200)
915
+ );
916
+ }
917
+ });
918
+ payload = { events };
919
+ } else {
920
+ payload = await c.req.json().catch(() => null);
921
+ }
922
+ if (payload == null) {
923
+ throw new WireError("validation_error", "Request body must be JSON or NDJSON.", 400);
924
+ }
925
+ const parsed = TracesIngestRequestSchema.safeParse(payload);
926
+ if (!parsed.success) {
927
+ throw new WireError(
928
+ "validation_error",
929
+ "Request did not match TracesIngestRequest schema.",
930
+ 400,
931
+ parsed.error.issues
932
+ );
933
+ }
934
+ const result = await handleTracesIngest(parsed.data, opts.stores ?? {});
935
+ return c.json(result);
936
+ });
937
+ app.post("/v1/feedback", async (c) => {
938
+ const raw = await c.req.json().catch(() => null);
939
+ if (raw == null) {
940
+ throw new WireError("validation_error", "Request body must be JSON.", 400);
941
+ }
942
+ const parsed = FeedbackTrajectorySchema.safeParse(raw);
943
+ if (!parsed.success) {
944
+ throw new WireError(
945
+ "validation_error",
946
+ "Request did not match FeedbackTrajectory schema.",
947
+ 400,
948
+ parsed.error.issues
949
+ );
950
+ }
951
+ const result = await handleFeedbackIngest(parsed.data, opts.stores ?? {});
952
+ return c.json(result);
953
+ });
954
+ app.get("/openapi.json", (c) => c.json(buildOpenApi(handleVersion().version)));
955
+ return app;
956
+ }
957
+ function startServer(opts = {}) {
958
+ const app = createApp(opts);
959
+ const port = opts.port ?? 5005;
960
+ const host = opts.host ?? "127.0.0.1";
961
+ return serve({ fetch: app.fetch, port, hostname: host }, ({ address, port: actualPort }) => {
962
+ console.log(`[agent-eval] serving on http://${address}:${actualPort}`);
963
+ });
964
+ }
965
+ function startServerAsync(opts = {}) {
966
+ const app = createApp(opts);
967
+ const port = opts.port ?? 5005;
968
+ const host = opts.host ?? "127.0.0.1";
969
+ return new Promise((resolve2, reject) => {
970
+ let settled = false;
971
+ let server;
972
+ server = serve({ fetch: app.fetch, port, hostname: host }, ({ address, port: actualPort }) => {
973
+ if (settled) return;
974
+ settled = true;
975
+ console.log(`[agent-eval] serving on http://${address}:${actualPort}`);
976
+ resolve2({
977
+ server,
978
+ port: actualPort,
979
+ host: address,
980
+ close: () => new Promise((res, rej) => {
981
+ server.close((err) => err ? rej(err) : res());
982
+ })
983
+ });
984
+ });
985
+ server.on("error", (err) => {
986
+ if (settled) return;
987
+ settled = true;
988
+ reject(err);
989
+ });
990
+ });
991
+ }
992
+
993
+ export {
994
+ RubricDimensionSchema,
995
+ FailureModeSchema,
996
+ RubricSchema,
997
+ JudgeRequestSchema,
998
+ JudgeResultSchema,
999
+ RubricInfoSchema,
1000
+ ListRubricsResponseSchema,
1001
+ VersionResponseSchema,
1002
+ HealthResponseSchema,
1003
+ TraceEventSchema,
1004
+ TracesIngestRequestSchema,
1005
+ TracesIngestResponseSchema,
1006
+ FeedbackLabelSchema,
1007
+ FeedbackAttemptSchema,
1008
+ FeedbackTrajectorySchema,
1009
+ FeedbackIngestResponseSchema,
1010
+ ErrorResponseSchema,
1011
+ WIRE_VERSION,
1012
+ hashRubric,
1013
+ BUILTIN_RUBRICS,
1014
+ getBuiltinRubric,
1015
+ listBuiltinRubrics,
1016
+ WireError,
1017
+ handleJudge,
1018
+ handleListRubrics,
1019
+ handleVersion,
1020
+ handleTracesIngest,
1021
+ handleFeedbackIngest,
1022
+ buildOpenApi,
1023
+ dispatchRpc,
1024
+ runRpcOnce,
1025
+ runRpcBatch,
1026
+ createApp,
1027
+ startServer,
1028
+ startServerAsync
1029
+ };
1030
+ //# sourceMappingURL=chunk-NMN4WGSJ.js.map