@kortyx/agent 0.31.0 → 0.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -29,6 +29,1271 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
29
29
  ));
30
30
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
31
 
32
+ // ../telemetry-contracts/dist/index.js
33
+ var require_dist = __commonJS({
34
+ "../telemetry-contracts/dist/index.js"(exports2, module2) {
35
+ var __defProp2 = Object.defineProperty;
36
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
37
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
38
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
39
+ var __export2 = (target, all) => {
40
+ for (var name in all)
41
+ __defProp2(target, name, { get: all[name], enumerable: true });
42
+ };
43
+ var __copyProps2 = (to, from, except, desc) => {
44
+ if (from && typeof from === "object" || typeof from === "function") {
45
+ for (let key of __getOwnPropNames2(from))
46
+ if (!__hasOwnProp2.call(to, key) && key !== except)
47
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
48
+ }
49
+ return to;
50
+ };
51
+ var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
52
+ var index_exports2 = {};
53
+ __export2(index_exports2, {
54
+ ClearScoreResponseSchema: () => ClearScoreResponseSchema,
55
+ ClearUserFeedbackRequestSchema: () => ClearUserFeedbackRequestSchema,
56
+ DIAGNOSTIC_LIMITS: () => DIAGNOSTIC_LIMITS,
57
+ DiagnosticContentSchema: () => DiagnosticContentSchema,
58
+ DiagnosticCorrelationSchema: () => DiagnosticCorrelationSchema,
59
+ DiagnosticManifestSchema: () => DiagnosticManifestSchema,
60
+ DiagnosticNoteSchema: () => DiagnosticNoteSchema,
61
+ DiagnosticPartSchema: () => DiagnosticPartSchema,
62
+ DiagnosticResponseSchema: () => DiagnosticResponseSchema,
63
+ EnsureWorkflowTopologyRequestSchema: () => EnsureWorkflowTopologyRequestSchema,
64
+ EnsureWorkflowTopologyResponseSchema: () => EnsureWorkflowTopologyResponseSchema,
65
+ FEEDBACK_FILTERS: () => FEEDBACK_FILTERS,
66
+ FeedbackReasonSchema: () => FeedbackReasonSchema,
67
+ FeedbackSummarySchema: () => FeedbackSummarySchema,
68
+ ReviewVerdictSchema: () => ReviewVerdictSchema,
69
+ STUDIO_API_PROTOCOL_VERSION: () => STUDIO_API_PROTOCOL_VERSION,
70
+ STUDIO_TIME_RANGES: () => STUDIO_TIME_RANGES,
71
+ StudioCatalogsResponseSchema: () => StudioCatalogsResponseSchema,
72
+ StudioChangeResourceSchema: () => StudioChangeResourceSchema,
73
+ StudioChangeSchema: () => StudioChangeSchema,
74
+ StudioContextResponseSchema: () => StudioContextResponseSchema,
75
+ StudioDetailEventSchema: () => StudioDetailEventSchema,
76
+ StudioInterruptDetailResponseSchema: () => StudioInterruptDetailResponseSchema,
77
+ StudioInterruptInteractionModeSchema: () => StudioInterruptInteractionModeSchema,
78
+ StudioInterruptOptionSchema: () => StudioInterruptOptionSchema,
79
+ StudioInterruptSchema: () => StudioInterruptSchema,
80
+ StudioInterruptStatusSchema: () => StudioInterruptStatusSchema,
81
+ StudioInterruptTypeSchema: () => StudioInterruptTypeSchema,
82
+ StudioInterruptValueSchema: () => StudioInterruptValueSchema,
83
+ StudioInterruptsResponseSchema: () => StudioInterruptsResponseSchema,
84
+ StudioMetricSchema: () => StudioMetricSchema,
85
+ StudioPricingSourceSchema: () => StudioPricingSourceSchema,
86
+ StudioPricingStatusSchema: () => StudioPricingStatusSchema,
87
+ StudioReleaseDeploymentSchema: () => StudioReleaseDeploymentSchema,
88
+ StudioReleaseSchema: () => StudioReleaseSchema,
89
+ StudioReleaseVersionSchema: () => StudioReleaseVersionSchema,
90
+ StudioResumeOutcomeSchema: () => StudioResumeOutcomeSchema,
91
+ StudioReviewRequestSchema: () => StudioReviewRequestSchema,
92
+ StudioRunDetailResponseSchema: () => StudioRunDetailResponseSchema,
93
+ StudioRunSchema: () => StudioRunSchema,
94
+ StudioRunStatusSchema: () => StudioRunStatusSchema,
95
+ StudioRunsResponseSchema: () => StudioRunsResponseSchema,
96
+ StudioScoreResponseSchema: () => StudioScoreResponseSchema,
97
+ StudioScoreSchema: () => StudioScoreSchema,
98
+ StudioSessionDetailResponseSchema: () => StudioSessionDetailResponseSchema,
99
+ StudioSessionSchema: () => StudioSessionSchema,
100
+ StudioSessionsResponseSchema: () => StudioSessionsResponseSchema,
101
+ StudioTimeRangeContextSchema: () => StudioTimeRangeContextSchema,
102
+ StudioTimeRangeQuerySchema: () => StudioTimeRangeQuerySchema,
103
+ StudioTimeRangeSchema: () => StudioTimeRangeSchema,
104
+ StudioToolSchema: () => StudioToolSchema,
105
+ StudioUpdateOperationSchema: () => StudioUpdateOperationSchema,
106
+ StudioUpdateSettingsSchema: () => StudioUpdateSettingsSchema,
107
+ StudioUpdateStatusSchema: () => StudioUpdateStatusSchema,
108
+ StudioWorkflowHealthSchema: () => StudioWorkflowHealthSchema,
109
+ StudioWorkflowInternalEdgeSchema: () => StudioWorkflowInternalEdgeSchema,
110
+ StudioWorkflowNodeSchema: () => StudioWorkflowNodeSchema,
111
+ StudioWorkflowSchema: () => StudioWorkflowSchema,
112
+ StudioWorkflowTransitionSchema: () => StudioWorkflowTransitionSchema,
113
+ StudioWorkflowsResponseSchema: () => StudioWorkflowsResponseSchema,
114
+ TELEMETRY_EVENT_TYPES: () => TELEMETRY_EVENT_TYPES,
115
+ TelemetryEventBatchResponseSchema: () => TelemetryEventBatchResponseSchema,
116
+ TelemetryEventBatchSchema: () => TelemetryEventBatchSchema,
117
+ TelemetryEventSchema: () => TelemetryEventSchema,
118
+ TelemetryEventTypeSchema: () => TelemetryEventTypeSchema,
119
+ TelemetryPricingHintSchema: () => TelemetryPricingHintSchema,
120
+ TelemetryPricingLineItemSchema: () => TelemetryPricingLineItemSchema,
121
+ TelemetryPricingSourceSchema: () => TelemetryPricingSourceSchema,
122
+ TelemetryPricingUnitSchema: () => TelemetryPricingUnitSchema,
123
+ TelemetryPricingUsageTypeSchema: () => TelemetryPricingUsageTypeSchema,
124
+ TelemetryServiceSchema: () => TelemetryServiceSchema,
125
+ TelemetryUnitPriceSchema: () => TelemetryUnitPriceSchema,
126
+ TelemetryUsageItemSchema: () => TelemetryUsageItemSchema,
127
+ ToolDiscoverySchema: () => ToolDiscoverySchema,
128
+ ToolObservationSchema: () => ToolObservationSchema,
129
+ ToolOutcomeSchema: () => ToolOutcomeSchema,
130
+ UserFeedbackRequestSchema: () => UserFeedbackRequestSchema,
131
+ WorkflowToolSchema: () => WorkflowToolSchema,
132
+ WorkflowTopologyCallSchema: () => WorkflowTopologyCallSchema,
133
+ WorkflowTopologyEdgeSchema: () => WorkflowTopologyEdgeSchema,
134
+ WorkflowTopologyNodeSchema: () => WorkflowTopologyNodeSchema,
135
+ WorkflowTopologyTransitionSchema: () => WorkflowTopologyTransitionSchema,
136
+ isPrivateDiagnosticField: () => isPrivateDiagnosticField,
137
+ newerStudioVersion: () => newerStudioVersion,
138
+ projectWorkflowCalls: () => projectWorkflowCalls,
139
+ redactDiagnosticContent: () => redactDiagnosticContent,
140
+ redactDiagnosticText: () => redactDiagnosticText,
141
+ resolveStudioInterruptStatus: () => resolveStudioInterruptStatus,
142
+ resolveStudioTimeRange: () => resolveStudioTimeRange,
143
+ studioUpdateRunning: () => studioUpdateRunning,
144
+ summarizeDiagnostic: () => summarizeDiagnostic2,
145
+ summarizeUserFeedback: () => summarizeUserFeedback
146
+ });
147
+ module2.exports = __toCommonJS2(index_exports2);
148
+ var import_zod52 = require("zod");
149
+ var import_zod11 = require("zod");
150
+ var FEEDBACK_FILTERS = ["positive", "negative", "unrated"];
151
+ var FeedbackSummarySchema = import_zod11.z.object({
152
+ positive: import_zod11.z.number().int().nonnegative(),
153
+ negative: import_zod11.z.number().int().nonnegative()
154
+ }).strict();
155
+ var FeedbackReasonSchema = import_zod11.z.enum([
156
+ "incorrect",
157
+ "irrelevant",
158
+ "incomplete",
159
+ "unsafe",
160
+ "other"
161
+ ]);
162
+ var ReviewVerdictSchema = import_zod11.z.enum([
163
+ "correct",
164
+ "partially-correct",
165
+ "incorrect"
166
+ ]);
167
+ var runId = import_zod11.z.string().trim().min(1).max(512);
168
+ var actorId = import_zod11.z.string().trim().min(1).max(256);
169
+ var comment = import_zod11.z.string().trim().max(4e3).nullable().optional();
170
+ var UserFeedbackRequestSchema = import_zod11.z.object({
171
+ runId,
172
+ actorId,
173
+ value: import_zod11.z.union([import_zod11.z.literal(0), import_zod11.z.literal(1)]),
174
+ reasons: import_zod11.z.array(FeedbackReasonSchema).max(5).optional(),
175
+ comment
176
+ }).strict();
177
+ var ClearUserFeedbackRequestSchema = UserFeedbackRequestSchema.pick({
178
+ runId: true,
179
+ actorId: true
180
+ });
181
+ var StudioReviewRequestSchema = import_zod11.z.object({ value: ReviewVerdictSchema, comment }).strict();
182
+ var BaseScoreSchema = import_zod11.z.object({
183
+ id: import_zod11.z.string().uuid(),
184
+ target: import_zod11.z.object({ type: import_zod11.z.literal("run"), runId }).strict(),
185
+ environment: import_zod11.z.string().min(1),
186
+ name: import_zod11.z.string().min(1),
187
+ source: import_zod11.z.enum(["end-user", "human-review", "evaluator"]),
188
+ actorId,
189
+ reasons: import_zod11.z.array(FeedbackReasonSchema),
190
+ comment: import_zod11.z.string().nullable(),
191
+ createdAt: import_zod11.z.string().datetime({ offset: true }),
192
+ updatedAt: import_zod11.z.string().datetime({ offset: true })
193
+ }).strict();
194
+ var StudioScoreSchema = import_zod11.z.discriminatedUnion("dataType", [
195
+ BaseScoreSchema.extend({
196
+ dataType: import_zod11.z.literal("BOOLEAN"),
197
+ value: import_zod11.z.union([import_zod11.z.literal(0), import_zod11.z.literal(1)])
198
+ }),
199
+ BaseScoreSchema.extend({
200
+ dataType: import_zod11.z.literal("CATEGORICAL"),
201
+ value: import_zod11.z.string()
202
+ }),
203
+ BaseScoreSchema.extend({
204
+ dataType: import_zod11.z.literal("NUMERIC"),
205
+ value: import_zod11.z.number().finite()
206
+ })
207
+ ]);
208
+ var StudioScoreResponseSchema = import_zod11.z.object({ score: StudioScoreSchema }).strict();
209
+ var ClearScoreResponseSchema = import_zod11.z.object({ ok: import_zod11.z.literal(true) }).strict();
210
+ function summarizeUserFeedback(scores) {
211
+ const feedback = { positive: 0, negative: 0 };
212
+ for (const score of scores) {
213
+ if (score.source !== "end-user" || score.name !== "user-feedback" || score.dataType !== "BOOLEAN")
214
+ continue;
215
+ if (score.value === 1) feedback.positive += 1;
216
+ if (score.value === 0) feedback.negative += 1;
217
+ }
218
+ return feedback;
219
+ }
220
+ var import_zod22 = require("zod");
221
+ var DIAGNOSTIC_LIMITS = {
222
+ bytes: 8 * 1024 * 1024,
223
+ partBytes: 64 * 1024,
224
+ parts: 128,
225
+ nodes: 1e4,
226
+ depth: 128,
227
+ properties: 1e3
228
+ };
229
+ var DiagnosticNoteSchema = import_zod22.z.object({
230
+ path: import_zod22.z.string().max(4096),
231
+ reason: import_zod22.z.string().max(128),
232
+ originalBytes: import_zod22.z.number().int().nonnegative().optional(),
233
+ originalCount: import_zod22.z.number().int().nonnegative().optional()
234
+ }).strict();
235
+ var DiagnosticContentSchema = import_zod22.z.object({
236
+ schemaVersion: import_zod22.z.literal(1),
237
+ data: import_zod22.z.record(import_zod22.z.string(), import_zod22.z.unknown()),
238
+ capture: import_zod22.z.object({
239
+ status: import_zod22.z.enum(["complete", "partial", "failed"]),
240
+ omissions: import_zod22.z.array(DiagnosticNoteSchema).max(1e4),
241
+ redactions: import_zod22.z.array(DiagnosticNoteSchema).max(1e4)
242
+ }).strict()
243
+ }).strict();
244
+ var DiagnosticCorrelationSchema = import_zod22.z.object({
245
+ runId: import_zod22.z.string().optional(),
246
+ workflowId: import_zod22.z.string().optional(),
247
+ nodeId: import_zod22.z.string().optional(),
248
+ sessionId: import_zod22.z.string().optional(),
249
+ invocationId: import_zod22.z.string().optional(),
250
+ parentInvocationId: import_zod22.z.string().optional(),
251
+ branchId: import_zod22.z.string().optional(),
252
+ toolCallId: import_zod22.z.string().optional(),
253
+ attemptId: import_zod22.z.string().optional(),
254
+ workflowRevisionId: import_zod22.z.string().optional(),
255
+ traceId: import_zod22.z.string().optional(),
256
+ spanId: import_zod22.z.string().optional(),
257
+ parentSpanId: import_zod22.z.string().optional()
258
+ }).strict();
259
+ var DiagnosticManifestSchema = import_zod22.z.object({
260
+ schemaVersion: import_zod22.z.literal(1),
261
+ diagnosticId: import_zod22.z.string().uuid(),
262
+ occurrenceId: import_zod22.z.string().uuid(),
263
+ occurredAt: import_zod22.z.string().datetime({ offset: true }),
264
+ environment: import_zod22.z.string().min(1).max(256),
265
+ service: import_zod22.z.object({
266
+ name: import_zod22.z.string().min(1).max(256),
267
+ deploymentRef: import_zod22.z.string().max(1024).optional()
268
+ }).strict(),
269
+ correlation: DiagnosticCorrelationSchema,
270
+ handled: import_zod22.z.boolean(),
271
+ severity: import_zod22.z.enum(["warning", "error"]),
272
+ mechanism: import_zod22.z.enum(["span", "report", "tool"]),
273
+ summary: import_zod22.z.object({ type: import_zod22.z.string().max(256), message: import_zod22.z.string().max(8192) }).strict(),
274
+ captureStatus: import_zod22.z.enum(["complete", "partial", "failed"]),
275
+ checksum: import_zod22.z.string().regex(/^[a-f0-9]{64}$/),
276
+ byteLength: import_zod22.z.number().int().min(1).max(DIAGNOSTIC_LIMITS.bytes),
277
+ partCount: import_zod22.z.number().int().min(1).max(DIAGNOSTIC_LIMITS.parts)
278
+ }).strict().superRefine((value, ctx) => {
279
+ if (value.partCount !== Math.ceil(value.byteLength / DIAGNOSTIC_LIMITS.partBytes))
280
+ ctx.addIssue({
281
+ code: "custom",
282
+ path: ["partCount"],
283
+ message: "Part count does not match byte length."
284
+ });
285
+ });
286
+ var DiagnosticPartSchema = import_zod22.z.object({
287
+ index: import_zod22.z.number().int().min(0).max(DIAGNOSTIC_LIMITS.parts - 1),
288
+ data: import_zod22.z.string().max(Math.ceil(DIAGNOSTIC_LIMITS.partBytes / 3) * 4).regex(
289
+ /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/
290
+ )
291
+ }).strict();
292
+ var DiagnosticResponseSchema = import_zod22.z.object({
293
+ manifest: DiagnosticManifestSchema,
294
+ state: import_zod22.z.enum(["pending", "available", "incomplete", "expired"]),
295
+ receivedParts: import_zod22.z.number().int().nonnegative(),
296
+ expiresAt: import_zod22.z.string().datetime({ offset: true }),
297
+ content: DiagnosticContentSchema.nullable(),
298
+ contentChecksum: import_zod22.z.string().regex(/^[a-f0-9]{64}$/).nullable(),
299
+ contentByteLength: import_zod22.z.number().int().nonnegative().nullable()
300
+ }).strict();
301
+ var isPrivateDiagnosticField = (key) => /^(?:password|passwd|secret|clientsecret|privatekey|credential|credentials|authorization|proxyauthorization|bearer|bearertoken|jwt|token|accesstoken|refreshtoken|authtoken|apikey|xapikey|apitoken|xauthtoken|xaccesstoken|awsaccesskeyid|awssecretaccesskey|awssessiontoken|xamzsecuritytoken|apisecret|cookie|setcookie|resumehandle|resumetoken)$/.test(
302
+ key.toLowerCase().replace(/[^a-z0-9]/g, "")
303
+ );
304
+ function redactDiagnosticText(value) {
305
+ return value.replace(/\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi, "Bearer [REDACTED]").replace(
306
+ /\b(?:ktyx_(?:test|live)_[^\s"'<>]+|sk-(?:proj-|ant-)?[A-Za-z0-9_-]{12,}|AIza[A-Za-z0-9_-]{20,}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)/g,
307
+ "[REDACTED]"
308
+ ).replace(
309
+ /(["']?(?:api[_-]?key|access[_-]?token|refresh[_-]?token|password|passwd|secret|token|client[_-]?secret|authorization|cookie)["']?\s*[:=]\s*)(["'])(.*?)\2/gi,
310
+ "$1$2[REDACTED]$2"
311
+ ).replace(
312
+ /(\b(?:api[_-]?key|access[_-]?token|refresh[_-]?token|password|passwd|secret|token|client[_-]?secret)\s*[:=]\s*)(?!["'[])[^\s,;}&]+/gi,
313
+ "$1[REDACTED]"
314
+ ).replace(
315
+ /(\b(?:authorization|proxy-authorization)\s*:\s*Basic\s+)[A-Za-z0-9+/=]+/gi,
316
+ "$1[REDACTED]"
317
+ ).replace(
318
+ /([?&](?:api[_-]?key|token|access[_-]?token|password)=)[^&#\s]+/gi,
319
+ "$1[REDACTED]"
320
+ ).replace(/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/gi, "$1[REDACTED]@");
321
+ }
322
+ function summarizeDiagnostic2(data, depth = 0) {
323
+ return {
324
+ type: typeof data.type === "string" ? data.type.slice(0, 256) : "Error",
325
+ message: typeof data.message === "string" ? data.message.slice(0, 8192) : "Execution reported a fault.",
326
+ ...typeof data.stack === "string" ? { stack: data.stack.slice(0, 32768) } : {},
327
+ ...depth < 4 && data.cause && typeof data.cause === "object" && !Array.isArray(data.cause) ? {
328
+ cause: summarizeDiagnostic2(
329
+ data.cause,
330
+ depth + 1
331
+ )
332
+ } : {}
333
+ };
334
+ }
335
+ function redactDiagnosticContent(content) {
336
+ const redactions = [...content.capture.redactions];
337
+ const omissions = [...content.capture.omissions];
338
+ let nodes = 0;
339
+ const visit = (value, path, depth = 0) => {
340
+ if (++nodes > DIAGNOSTIC_LIMITS.nodes || depth > DIAGNOSTIC_LIMITS.depth) {
341
+ const reason = depth > DIAGNOSTIC_LIMITS.depth ? "server_depth_limit" : "server_node_limit";
342
+ if (omissions.length < 1e4)
343
+ omissions.push({ path: path.slice(0, 4096), reason });
344
+ return { $omitted: reason };
345
+ }
346
+ if (typeof value === "string") {
347
+ const clean = redactDiagnosticText(value);
348
+ if (clean !== value && redactions.length < 1e4)
349
+ redactions.push({
350
+ path: path.slice(0, 4096),
351
+ reason: "server_credential_text"
352
+ });
353
+ return clean;
354
+ }
355
+ if (Array.isArray(value)) {
356
+ if (value.length > DIAGNOSTIC_LIMITS.properties && omissions.length < 1e4)
357
+ omissions.push({
358
+ path: path.slice(0, 4096),
359
+ reason: "server_collection_limit",
360
+ originalCount: value.length
361
+ });
362
+ return value.slice(0, DIAGNOSTIC_LIMITS.properties).map((item, index) => visit(item, `${path}/${index}`, depth + 1));
363
+ }
364
+ if (value && typeof value === "object") {
365
+ const keys = Object.keys(value);
366
+ if (keys.length > DIAGNOSTIC_LIMITS.properties && omissions.length < 1e4)
367
+ omissions.push({
368
+ path: path.slice(0, 4096),
369
+ reason: "server_property_limit",
370
+ originalCount: keys.length
371
+ });
372
+ return Object.fromEntries(
373
+ keys.slice(0, DIAGNOSTIC_LIMITS.properties).map((key) => {
374
+ const nested = value[key];
375
+ if (isPrivateDiagnosticField(key)) {
376
+ if (redactions.length < 1e4 && nested !== "[REDACTED]")
377
+ redactions.push({
378
+ path: `${path}/${key}`.slice(0, 4096),
379
+ reason: "server_credential_field"
380
+ });
381
+ return [key, "[REDACTED]"];
382
+ }
383
+ return [key, visit(nested, `${path}/${key}`, depth + 1)];
384
+ })
385
+ );
386
+ }
387
+ return value;
388
+ };
389
+ return {
390
+ ...content,
391
+ data: visit(content.data, "#/data"),
392
+ capture: {
393
+ ...content.capture,
394
+ status: content.capture.status === "failed" ? "failed" : omissions.length ? "partial" : "complete",
395
+ omissions: omissions.map((note) => ({
396
+ ...note,
397
+ path: redactDiagnosticText(note.path),
398
+ reason: redactDiagnosticText(note.reason)
399
+ })),
400
+ redactions: redactions.map((note) => ({
401
+ ...note,
402
+ path: redactDiagnosticText(note.path),
403
+ reason: redactDiagnosticText(note.reason)
404
+ }))
405
+ }
406
+ };
407
+ }
408
+ var import_zod32 = require("zod");
409
+ var ToolOutcomeSchema = import_zod32.z.enum([
410
+ "success",
411
+ "denied",
412
+ "fault",
413
+ "cancelled"
414
+ ]);
415
+ var ToolObservationSchema = import_zod32.z.object({
416
+ version: import_zod32.z.literal(1),
417
+ name: import_zod32.z.string().min(1).max(256),
418
+ toolCallId: import_zod32.z.string().min(1),
419
+ attemptId: import_zod32.z.string().min(1),
420
+ callingMode: import_zod32.z.enum(["direct", "model"]),
421
+ executed: import_zod32.z.boolean(),
422
+ outcome: ToolOutcomeSchema.optional(),
423
+ denialCode: import_zod32.z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional(),
424
+ errorType: import_zod32.z.string().max(256).optional(),
425
+ errorMessage: import_zod32.z.string().max(8192).optional(),
426
+ diagnosticId: import_zod32.z.string().uuid().optional(),
427
+ durationMs: import_zod32.z.number().finite().nonnegative().optional(),
428
+ workflowId: import_zod32.z.string().optional(),
429
+ nodeId: import_zod32.z.string().optional(),
430
+ workflowRevisionId: import_zod32.z.string().optional(),
431
+ runId: import_zod32.z.string().optional(),
432
+ invocationId: import_zod32.z.string().optional(),
433
+ parentInvocationId: import_zod32.z.string().optional(),
434
+ branchId: import_zod32.z.string().optional(),
435
+ observationKind: import_zod32.z.enum(["reused", "waiting"]).optional(),
436
+ suspended: import_zod32.z.boolean().optional(),
437
+ source: import_zod32.z.object({
438
+ runId: import_zod32.z.string().optional(),
439
+ invocationId: import_zod32.z.string().optional(),
440
+ branchId: import_zod32.z.string().optional(),
441
+ toolCallId: import_zod32.z.string(),
442
+ attemptId: import_zod32.z.string()
443
+ }).strict().optional()
444
+ });
445
+ var WorkflowToolSchema = import_zod32.z.object({
446
+ name: import_zod32.z.string().min(1).max(256),
447
+ description: import_zod32.z.string().max(4096).optional(),
448
+ callingMode: import_zod32.z.enum(["direct", "model"]),
449
+ provenance: import_zod32.z.enum(["source", "observed"]),
450
+ inputFields: import_zod32.z.array(
451
+ import_zod32.z.object({ name: import_zod32.z.string(), type: import_zod32.z.string(), required: import_zod32.z.boolean() }).strict()
452
+ ).optional()
453
+ }).strict();
454
+ var ToolDiscoverySchema = import_zod32.z.object({
455
+ status: import_zod32.z.enum(["complete", "unresolved"]),
456
+ publishedAt: import_zod32.z.string().datetime().optional(),
457
+ warnings: import_zod32.z.array(import_zod32.z.string()).optional()
458
+ }).strict();
459
+ var StudioToolSchema = WorkflowToolSchema.extend({
460
+ callingMode: import_zod32.z.enum(["direct", "model", "unknown"]),
461
+ calls: import_zod32.z.number().nonnegative(),
462
+ replays: import_zod32.z.number().nonnegative(),
463
+ successes: import_zod32.z.number().nonnegative(),
464
+ denials: import_zod32.z.number().nonnegative(),
465
+ faults: import_zod32.z.number().nonnegative(),
466
+ cancellations: import_zod32.z.number().nonnegative(),
467
+ p50DurationMs: import_zod32.z.number().nonnegative().nullable(),
468
+ p95DurationMs: import_zod32.z.number().nonnegative().nullable()
469
+ }).strict();
470
+ var import_zod42 = require("zod");
471
+ var StudioReleaseVersionSchema = import_zod42.z.string().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/);
472
+ var StudioReleaseDeploymentSchema = import_zod42.z.object({
473
+ strategy: import_zod42.z.enum(["rolling", "recreate"])
474
+ });
475
+ var StudioReleaseSchema = import_zod42.z.object({
476
+ format: import_zod42.z.literal(1),
477
+ installer: import_zod42.z.literal(1),
478
+ version: StudioReleaseVersionSchema,
479
+ api: import_zod42.z.string().regex(/^ghcr\.io\/kortyx-io\/kortyx-api@sha256:[a-f0-9]{64}$/),
480
+ studio: import_zod42.z.string().regex(/^ghcr\.io\/kortyx-io\/kortyx-studio@sha256:[a-f0-9]{64}$/),
481
+ deployment: StudioReleaseDeploymentSchema.default({
482
+ strategy: "recreate"
483
+ })
484
+ });
485
+ var StudioUpdateSettingsSchema = import_zod42.z.object({
486
+ automatic: import_zod42.z.boolean(),
487
+ hourUtc: import_zod42.z.number().int().min(0).max(23)
488
+ });
489
+ var StudioUpdateOperationSchema = import_zod42.z.object({
490
+ id: import_zod42.z.uuid(),
491
+ from: import_zod42.z.string(),
492
+ release: StudioReleaseSchema,
493
+ phase: import_zod42.z.enum([
494
+ "starting",
495
+ "pulling",
496
+ "backup",
497
+ "installing",
498
+ "verifying",
499
+ "succeeded",
500
+ "failed"
501
+ ]),
502
+ startedAt: import_zod42.z.iso.datetime(),
503
+ updatedAt: import_zod42.z.iso.datetime(),
504
+ backup: import_zod42.z.string().nullable(),
505
+ messages: import_zod42.z.array(import_zod42.z.string()).max(100)
506
+ });
507
+ var StudioUpdateStatusSchema = import_zod42.z.object({
508
+ current: import_zod42.z.string().nullable(),
509
+ available: StudioReleaseSchema.nullable(),
510
+ checkedAt: import_zod42.z.iso.datetime().nullable(),
511
+ checkError: import_zod42.z.string().nullable(),
512
+ settings: StudioUpdateSettingsSchema,
513
+ operation: StudioUpdateOperationSchema.nullable()
514
+ });
515
+ function newerStudioVersion(candidate, current) {
516
+ const next = StudioReleaseVersionSchema.parse(candidate).split(".").map(BigInt);
517
+ const previous = StudioReleaseVersionSchema.parse(current).split(".").map(BigInt);
518
+ for (let i = 0; i < 3; i++) {
519
+ if (next[i] !== previous[i]) return (next[i] ?? 0n) > (previous[i] ?? 0n);
520
+ }
521
+ return false;
522
+ }
523
+ function studioUpdateRunning(operation) {
524
+ return !!operation && operation.phase !== "succeeded" && operation.phase !== "failed";
525
+ }
526
+ var str = (v, fallback = "") => typeof v === "string" ? v : fallback;
527
+ function projectWorkflowCalls(events) {
528
+ const groups = /* @__PURE__ */ new Map();
529
+ for (const event of events) {
530
+ if (!event.type.startsWith("workflow.call.") || !str(event.payload.invocationId) || !str(event.payload.targetWorkflowId))
531
+ continue;
532
+ const key = `${event.runId}:${str(event.payload.branchId, event.runId)}:${event.payload.invocationId}`;
533
+ const group = groups.get(key) ?? [];
534
+ if (!group.some((existing) => existing.id === event.id)) group.push(event);
535
+ groups.set(key, group);
536
+ }
537
+ return [...groups.entries()].map(([id2, group]) => {
538
+ group.sort(
539
+ (a, b) => Number(a.payload.sequence ?? 0) - Number(b.payload.sequence ?? 0) || a.occurredAt.localeCompare(b.occurredAt) || a.id.localeCompare(b.id)
540
+ );
541
+ const first = group[0];
542
+ const p = first.payload;
543
+ const call = {
544
+ id: id2,
545
+ invocationId: str(p.invocationId),
546
+ branchId: str(p.branchId, first.runId),
547
+ parentInvocationId: str(p.parentInvocationId) || null,
548
+ callId: str(p.callId),
549
+ callerNodeId: str(p.callerNodeId),
550
+ callerNodeExecutionId: str(p.callerNodeExecutionId),
551
+ sourceWorkflowId: str(p.sourceWorkflowId, first.workflowId),
552
+ targetWorkflowId: str(p.targetWorkflowId),
553
+ targetVersion: str(p.targetVersion) || null,
554
+ status: "incomplete",
555
+ startedAt: first.occurredAt,
556
+ endedAt: null,
557
+ activeMs: 0,
558
+ waitMs: 0,
559
+ attempts: 0,
560
+ reused: 0,
561
+ inherited: false,
562
+ sourceRunId: null,
563
+ leaf: null,
564
+ events: group
565
+ };
566
+ let active = null;
567
+ let waiting = null;
568
+ for (const event of group) {
569
+ const at = Date.parse(event.occurredAt);
570
+ const status2 = event.type.slice("workflow.call.".length);
571
+ for (const side of [
572
+ "input",
573
+ "output",
574
+ "inputOmitted",
575
+ "outputOmitted"
576
+ ])
577
+ if (side in event.payload) call[side] = event.payload[side];
578
+ if (status2 === "restored") {
579
+ call.inherited = true;
580
+ call.sourceRunId = str(event.payload.sourceRunId) || null;
581
+ call.status = event.payload.status === "completed" ? "completed" : event.payload.status === "failed" ? "failed" : "interrupted";
582
+ if (call.status === "interrupted") waiting = at;
583
+ } else if (status2 === "started" || status2 === "resumed") {
584
+ if (waiting !== null) call.waitMs += Math.max(0, at - waiting);
585
+ waiting = null;
586
+ active = at;
587
+ call.attempts++;
588
+ call.status = "running";
589
+ call.endedAt = null;
590
+ } else if (status2 === "reused") {
591
+ call.reused++;
592
+ call.status = "completed";
593
+ } else if (status2 === "suspended" || status2 === "completed" || status2 === "failed") {
594
+ if (active !== null) call.activeMs += Math.max(0, at - active);
595
+ active = null;
596
+ call.status = status2 === "suspended" ? "interrupted" : status2;
597
+ if (status2 === "suspended") {
598
+ waiting = at;
599
+ const leaf = event.payload.leaf;
600
+ if (leaf && typeof leaf === "object") {
601
+ const value = leaf;
602
+ call.leaf = {
603
+ workflowId: str(value.workflowId),
604
+ nodeId: str(value.nodeId),
605
+ invocationId: str(value.invocationId)
606
+ };
607
+ }
608
+ } else {
609
+ call.endedAt = event.occurredAt;
610
+ call.leaf = null;
611
+ }
612
+ }
613
+ }
614
+ const cancellation = events.find(
615
+ (event) => event.type === "run.cancelled" && event.runId === first.runId && (event.payload.branchId ?? event.runId) === call.branchId && event.occurredAt >= (group.at(-1)?.occurredAt ?? first.occurredAt)
616
+ );
617
+ if (cancellation && (call.status === "interrupted" || call.status === "running")) {
618
+ call.status = "cancelled";
619
+ call.endedAt = cancellation.occurredAt;
620
+ }
621
+ return call;
622
+ }).sort((a, b) => a.startedAt.localeCompare(b.startedAt));
623
+ }
624
+ var STUDIO_API_PROTOCOL_VERSION = "1";
625
+ var TELEMETRY_EVENT_TYPES = [
626
+ "span.started",
627
+ "span.ended",
628
+ "span.failed",
629
+ "error.reported",
630
+ "generation.completed",
631
+ "tool.started",
632
+ "tool.completed",
633
+ "tool.failed",
634
+ "tool.denied",
635
+ "tool.cancelled",
636
+ "tool.reused",
637
+ "tool.waiting",
638
+ "tool.suspended",
639
+ "response.completed",
640
+ "output.emitted",
641
+ "output.invalidated",
642
+ "interrupt.created",
643
+ "interrupt.resolved",
644
+ "interrupt.expired",
645
+ "interrupt.cancelled",
646
+ "run.cancelled",
647
+ "run.limit_reached",
648
+ "workflow.suspended",
649
+ "workflow.resumed",
650
+ "workflow.transitioned",
651
+ "workflow.call.started",
652
+ "workflow.call.suspended",
653
+ "workflow.call.resumed",
654
+ "workflow.call.completed",
655
+ "workflow.call.failed",
656
+ "workflow.call.reused",
657
+ "workflow.call.restored",
658
+ "session.checkpointed",
659
+ "session.forked",
660
+ "session.rolled_back"
661
+ ];
662
+ var TelemetryServiceSchema = import_zod52.z.object({
663
+ name: import_zod52.z.string().min(1),
664
+ deploymentRef: import_zod52.z.string().min(1).optional()
665
+ }).strict();
666
+ var WorkflowTopologyNodeSchema = import_zod52.z.object({
667
+ id: import_zod52.z.string().min(1),
668
+ label: import_zod52.z.string().optional(),
669
+ type: import_zod52.z.string().optional(),
670
+ provider: import_zod52.z.string().optional(),
671
+ model: import_zod52.z.string().optional(),
672
+ metadata: import_zod52.z.record(import_zod52.z.string(), import_zod52.z.unknown()).optional(),
673
+ tools: import_zod52.z.array(WorkflowToolSchema).optional(),
674
+ toolDiscovery: ToolDiscoverySchema.optional()
675
+ }).strict();
676
+ var WorkflowTopologyEdgeSchema = import_zod52.z.object({
677
+ sourceNodeId: import_zod52.z.string().min(1),
678
+ targetNodeId: import_zod52.z.string().min(1),
679
+ condition: import_zod52.z.string().optional()
680
+ }).strict();
681
+ var WorkflowTopologyCallSchema = import_zod52.z.object({
682
+ sourceNodeId: import_zod52.z.string().min(1),
683
+ targetWorkflowId: import_zod52.z.string().min(1)
684
+ }).strict();
685
+ var WorkflowTopologyTransitionSchema = import_zod52.z.object({
686
+ sourceNodeId: import_zod52.z.string().min(1).optional(),
687
+ targetWorkflowId: import_zod52.z.string().min(1),
688
+ condition: import_zod52.z.string().optional(),
689
+ intent: import_zod52.z.string().optional(),
690
+ kind: import_zod52.z.enum(["call", "handoff"]).optional()
691
+ }).strict();
692
+ var EnsureWorkflowTopologyRequestSchema = import_zod52.z.object({
693
+ schemaVersion: import_zod52.z.literal(1),
694
+ environment: import_zod52.z.string().min(1),
695
+ service: TelemetryServiceSchema,
696
+ workflow: import_zod52.z.object({
697
+ id: import_zod52.z.string().min(1),
698
+ declaredVersion: import_zod52.z.string().min(1),
699
+ description: import_zod52.z.string().optional(),
700
+ tags: import_zod52.z.array(import_zod52.z.string()).optional(),
701
+ topologyHash: import_zod52.z.string().regex(/^[a-f0-9]{64}$/),
702
+ nodes: import_zod52.z.array(WorkflowTopologyNodeSchema),
703
+ edges: import_zod52.z.array(WorkflowTopologyEdgeSchema),
704
+ transitions: import_zod52.z.array(WorkflowTopologyTransitionSchema).optional(),
705
+ calls: import_zod52.z.array(WorkflowTopologyCallSchema).optional()
706
+ }).strict()
707
+ }).strict();
708
+ var EnsureWorkflowTopologyResponseSchema = import_zod52.z.object({ workflowRevisionId: import_zod52.z.string().min(1), created: import_zod52.z.boolean() }).strict();
709
+ var TelemetryEventTypeSchema = import_zod52.z.enum(TELEMETRY_EVENT_TYPES);
710
+ var TelemetryEventSchema = import_zod52.z.object({
711
+ schemaVersion: import_zod52.z.literal(1),
712
+ eventId: import_zod52.z.string().min(1),
713
+ occurredAt: import_zod52.z.string().datetime({ offset: true }),
714
+ environment: import_zod52.z.string().min(1),
715
+ service: TelemetryServiceSchema,
716
+ correlation: import_zod52.z.object({
717
+ invocationId: import_zod52.z.string().optional(),
718
+ parentInvocationId: import_zod52.z.string().optional(),
719
+ branchId: import_zod52.z.string().optional(),
720
+ traceId: import_zod52.z.string().optional(),
721
+ spanId: import_zod52.z.string().optional(),
722
+ parentSpanId: import_zod52.z.string().optional(),
723
+ runId: import_zod52.z.string().min(1),
724
+ sessionId: import_zod52.z.string().optional(),
725
+ workflowId: import_zod52.z.string().min(1),
726
+ workflowRevisionId: import_zod52.z.string().optional(),
727
+ topologyHash: import_zod52.z.string().regex(/^[a-f0-9]{64}$/).optional(),
728
+ nodeId: import_zod52.z.string().optional()
729
+ }).strict(),
730
+ context: import_zod52.z.object({
731
+ userId: import_zod52.z.string().optional(),
732
+ tenantId: import_zod52.z.string().optional(),
733
+ tags: import_zod52.z.array(import_zod52.z.string()).optional(),
734
+ metadata: import_zod52.z.record(import_zod52.z.string(), import_zod52.z.unknown()).optional()
735
+ }).strict().optional(),
736
+ type: TelemetryEventTypeSchema,
737
+ payload: import_zod52.z.record(import_zod52.z.string(), import_zod52.z.unknown())
738
+ }).strict().superRefine((event, ctx) => {
739
+ if (!event.type.startsWith("tool.")) return;
740
+ const canonical2 = event.payload.version === 1 || [
741
+ "tool.denied",
742
+ "tool.cancelled",
743
+ "tool.reused",
744
+ "tool.waiting",
745
+ "tool.suspended"
746
+ ].includes(event.type);
747
+ if (!canonical2) return;
748
+ const parsed = ToolObservationSchema.strict().safeParse(event.payload);
749
+ if (!parsed.success)
750
+ for (const issue2 of parsed.error.issues)
751
+ ctx.addIssue({ ...issue2, path: ["payload", ...issue2.path] });
752
+ else {
753
+ if ((parsed.data.errorType !== void 0 || parsed.data.errorMessage !== void 0) && parsed.data.outcome !== "fault")
754
+ ctx.addIssue({
755
+ code: "custom",
756
+ path: ["payload"],
757
+ message: "Error diagnostics require a fault outcome."
758
+ });
759
+ const terminalOutcomes = {
760
+ "tool.completed": "success",
761
+ "tool.failed": "fault",
762
+ "tool.denied": "denied",
763
+ "tool.cancelled": "cancelled"
764
+ };
765
+ const expected = terminalOutcomes[event.type];
766
+ if (expected && parsed.data.outcome !== expected)
767
+ ctx.addIssue({
768
+ code: "custom",
769
+ path: ["payload", "outcome"],
770
+ message: "Outcome must match the tool event type."
771
+ });
772
+ if (event.type === "tool.reused" && (parsed.data.executed || !parsed.data.source))
773
+ ctx.addIssue({
774
+ code: "custom",
775
+ path: ["payload"],
776
+ message: "Reuse must be unexecuted and reference its source."
777
+ });
778
+ }
779
+ });
780
+ var TelemetryEventBatchSchema = import_zod52.z.object({ events: import_zod52.z.array(TelemetryEventSchema).min(1) }).strict();
781
+ var TelemetryEventBatchResponseSchema = import_zod52.z.object({
782
+ accepted: import_zod52.z.number().int().nonnegative(),
783
+ inserted: import_zod52.z.number().int().nonnegative(),
784
+ duplicates: import_zod52.z.number().int().nonnegative()
785
+ }).strict();
786
+ var TelemetryPricingSourceSchema = import_zod52.z.enum([
787
+ "sdk",
788
+ "provider",
789
+ "custom",
790
+ "project-rate-card",
791
+ "default-rate-card"
792
+ ]);
793
+ var TelemetryPricingUnitSchema = import_zod52.z.enum([
794
+ "token",
795
+ "character",
796
+ "request",
797
+ "image",
798
+ "audio_second",
799
+ "audio_minute",
800
+ "video_second",
801
+ "video_minute",
802
+ "second",
803
+ "minute",
804
+ "custom"
805
+ ]);
806
+ var TelemetryPricingUsageTypeSchema = import_zod52.z.enum([
807
+ "input",
808
+ "output",
809
+ "reasoning",
810
+ "cache_read",
811
+ "cache_write",
812
+ "embedding",
813
+ "image_input",
814
+ "image_output",
815
+ "audio_input",
816
+ "audio_output",
817
+ "video_input",
818
+ "video_output",
819
+ "request",
820
+ "custom"
821
+ ]);
822
+ var TelemetryUsageItemSchema = import_zod52.z.object({
823
+ usageType: TelemetryPricingUsageTypeSchema,
824
+ quantity: import_zod52.z.number().nonnegative(),
825
+ unit: TelemetryPricingUnitSchema,
826
+ label: import_zod52.z.string().optional()
827
+ }).strict();
828
+ var TelemetryUnitPriceSchema = import_zod52.z.object({
829
+ usageType: TelemetryPricingUsageTypeSchema,
830
+ unit: TelemetryPricingUnitSchema,
831
+ unitQuantity: import_zod52.z.number().positive().default(1),
832
+ priceMicros: import_zod52.z.number().int().nonnegative(),
833
+ label: import_zod52.z.string().optional()
834
+ }).strict();
835
+ var TelemetryPricingLineItemSchema = import_zod52.z.object({
836
+ usageType: TelemetryPricingUsageTypeSchema,
837
+ quantity: import_zod52.z.number().nonnegative(),
838
+ unit: TelemetryPricingUnitSchema,
839
+ unitQuantity: import_zod52.z.number().positive().default(1),
840
+ unitPriceMicros: import_zod52.z.number().int().nonnegative().optional(),
841
+ totalCostMicros: import_zod52.z.number().int().nonnegative().optional(),
842
+ label: import_zod52.z.string().optional()
843
+ }).strict().refine(
844
+ (value) => value.totalCostMicros !== void 0 || value.unitPriceMicros !== void 0,
845
+ "line item requires totalCostMicros or unitPriceMicros"
846
+ );
847
+ var TelemetryPricingHintSchema = import_zod52.z.object({
848
+ source: TelemetryPricingSourceSchema.extract(["sdk", "provider", "custom"]),
849
+ currency: import_zod52.z.string().min(3).max(12).default("USD"),
850
+ actualCostMicros: import_zod52.z.number().int().nonnegative().optional(),
851
+ lineItems: import_zod52.z.array(TelemetryPricingLineItemSchema).optional(),
852
+ unitPrices: import_zod52.z.array(TelemetryUnitPriceSchema).optional(),
853
+ usageItems: import_zod52.z.array(TelemetryUsageItemSchema).optional(),
854
+ pricingRef: import_zod52.z.string().min(1).optional(),
855
+ metadata: import_zod52.z.record(import_zod52.z.string(), import_zod52.z.unknown()).optional()
856
+ }).strict();
857
+ var StudioRunStatusSchema = import_zod52.z.enum([
858
+ "running",
859
+ "completed",
860
+ "interrupted",
861
+ "incomplete",
862
+ "failed",
863
+ "cancelled"
864
+ ]);
865
+ var STUDIO_TIME_RANGES = [
866
+ "Last hour",
867
+ "24 hours",
868
+ "7 days",
869
+ "30 days",
870
+ "All time",
871
+ "Custom range"
872
+ ];
873
+ var StudioTimeRangeSchema = import_zod52.z.enum(STUDIO_TIME_RANGES);
874
+ var StudioTimeRangeQuerySchema = import_zod52.z.object({
875
+ range: StudioTimeRangeSchema.optional(),
876
+ startedAfter: import_zod52.z.string().optional(),
877
+ startedBefore: import_zod52.z.string().optional()
878
+ }).strict();
879
+ var StudioTimeRangeContextSchema = import_zod52.z.object({
880
+ range: StudioTimeRangeSchema,
881
+ startedAfter: import_zod52.z.string().datetime({ offset: true }).nullable(),
882
+ startedBefore: import_zod52.z.string().datetime({ offset: true }).nullable()
883
+ }).strict();
884
+ var STUDIO_TIME_RANGE_MILLISECONDS = {
885
+ "Last hour": 60 * 60 * 1e3,
886
+ "24 hours": 24 * 60 * 60 * 1e3,
887
+ "7 days": 7 * 24 * 60 * 60 * 1e3,
888
+ "30 days": 30 * 24 * 60 * 60 * 1e3
889
+ };
890
+ var parseIsoBoundary = (value, label) => {
891
+ if (!value) {
892
+ return { ok: false, error: `${label} is required for a custom range.` };
893
+ }
894
+ if (!/(?:Z|[+-]\d{2}:\d{2})$/.test(value)) {
895
+ return {
896
+ ok: false,
897
+ error: `${label} must include an explicit UTC offset.`
898
+ };
899
+ }
900
+ const date = new Date(value);
901
+ return Number.isFinite(date.getTime()) ? { ok: true, date } : { ok: false, error: `${label} must be a valid ISO date and time.` };
902
+ };
903
+ var resolveStudioTimeRange = (input, now = /* @__PURE__ */ new Date()) => {
904
+ const parsedRange = StudioTimeRangeSchema.safeParse(
905
+ input.range || "24 hours"
906
+ );
907
+ if (!parsedRange.success) {
908
+ return {
909
+ ok: false,
910
+ error: `Unknown time range "${input.range}".`
911
+ };
912
+ }
913
+ if (!Number.isFinite(now.getTime())) {
914
+ return { ok: false, error: "The time range reference date is invalid." };
915
+ }
916
+ const range = parsedRange.data;
917
+ if (range === "All time") {
918
+ return {
919
+ ok: true,
920
+ value: { range, startedAfter: null, startedBefore: null }
921
+ };
922
+ }
923
+ if (range === "Custom range") {
924
+ const after = parseIsoBoundary(input.startedAfter, "Start time");
925
+ if ("error" in after) return { ok: false, error: after.error };
926
+ const before = parseIsoBoundary(input.startedBefore, "End time");
927
+ if ("error" in before) return { ok: false, error: before.error };
928
+ if (after.date.getTime() >= before.date.getTime()) {
929
+ return {
930
+ ok: false,
931
+ error: "Start time must be before end time."
932
+ };
933
+ }
934
+ return {
935
+ ok: true,
936
+ value: {
937
+ range,
938
+ startedAfter: after.date.toISOString(),
939
+ startedBefore: before.date.toISOString()
940
+ }
941
+ };
942
+ }
943
+ const duration = STUDIO_TIME_RANGE_MILLISECONDS[range];
944
+ if (!duration) {
945
+ return { ok: false, error: `Unknown time range "${range}".` };
946
+ }
947
+ return {
948
+ ok: true,
949
+ value: {
950
+ range,
951
+ startedAfter: new Date(now.getTime() - duration).toISOString(),
952
+ startedBefore: now.toISOString()
953
+ }
954
+ };
955
+ };
956
+ var StudioInterruptStatusSchema = import_zod52.z.enum([
957
+ "pending",
958
+ "resolved",
959
+ "expired",
960
+ "failed",
961
+ "cancelled"
962
+ ]);
963
+ var resolveStudioInterruptStatus = (input, now = Date.now()) => {
964
+ if (input.status !== "pending" || !input.expiresAt) return input.status;
965
+ const expiresAt = Date.parse(input.expiresAt);
966
+ const nowMs = typeof now === "number" ? now : now.getTime();
967
+ return Number.isFinite(expiresAt) && Number.isFinite(nowMs) && expiresAt <= nowMs ? "expired" : input.status;
968
+ };
969
+ var StudioInterruptTypeSchema = import_zod52.z.enum([
970
+ "choice",
971
+ "multi-choice",
972
+ "text",
973
+ "structured",
974
+ "unknown"
975
+ ]);
976
+ var StudioInterruptInteractionModeSchema = import_zod52.z.enum([
977
+ "static-options",
978
+ "dynamic-picker",
979
+ "freeform",
980
+ "unknown"
981
+ ]);
982
+ var StudioInterruptOptionSchema = import_zod52.z.object({
983
+ id: import_zod52.z.string().min(1),
984
+ label: import_zod52.z.string().min(1),
985
+ description: import_zod52.z.string().nullable()
986
+ }).strip();
987
+ var StudioInterruptValueSchema = import_zod52.z.union([
988
+ import_zod52.z.record(import_zod52.z.string(), import_zod52.z.unknown()),
989
+ import_zod52.z.array(import_zod52.z.unknown()),
990
+ import_zod52.z.string(),
991
+ import_zod52.z.number(),
992
+ import_zod52.z.boolean()
993
+ ]);
994
+ var StudioResumeOutcomeSchema = import_zod52.z.enum([
995
+ "resumed",
996
+ "resume failed",
997
+ "expired before resume",
998
+ "cancelled"
999
+ ]);
1000
+ var StudioWorkflowHealthSchema = import_zod52.z.enum([
1001
+ "unknown",
1002
+ "healthy",
1003
+ "degraded",
1004
+ "failing",
1005
+ "idle"
1006
+ ]);
1007
+ var StudioPricingStatusSchema = import_zod52.z.enum([
1008
+ "priced",
1009
+ "unpriced",
1010
+ "unknown"
1011
+ ]);
1012
+ var StudioPricingSourceSchema = TelemetryPricingSourceSchema.nullable();
1013
+ var StudioChangeResourceSchema = import_zod52.z.enum([
1014
+ "evals",
1015
+ "workflows",
1016
+ "runs",
1017
+ "sessions",
1018
+ "interrupts"
1019
+ ]);
1020
+ var StudioChangeSchema = import_zod52.z.object({
1021
+ schemaVersion: import_zod52.z.literal(1),
1022
+ changeId: import_zod52.z.string().min(1),
1023
+ emittedAt: import_zod52.z.string().datetime({ offset: true }),
1024
+ organizationId: import_zod52.z.string().min(1),
1025
+ projectId: import_zod52.z.string().min(1),
1026
+ environment: import_zod52.z.string().min(1).optional(),
1027
+ resources: import_zod52.z.array(StudioChangeResourceSchema).min(1)
1028
+ }).strict();
1029
+ var StudioMetricSchema = import_zod52.z.object({
1030
+ runCount: import_zod52.z.number().int().nonnegative(),
1031
+ successRate: import_zod52.z.number().min(0).max(100).nullable(),
1032
+ errorRate: import_zod52.z.number().min(0).max(100).nullable(),
1033
+ retryCount: import_zod52.z.number().int().nonnegative().nullable(),
1034
+ interruptRate: import_zod52.z.number().min(0).max(100).nullable(),
1035
+ p50DurationMs: import_zod52.z.number().nonnegative().nullable(),
1036
+ p95DurationMs: import_zod52.z.number().nonnegative().nullable(),
1037
+ averageTokens: import_zod52.z.number().nonnegative().nullable(),
1038
+ averageCost: import_zod52.z.number().nonnegative().nullable(),
1039
+ currency: import_zod52.z.string().nullable()
1040
+ }).strip();
1041
+ var StudioRunSchema = import_zod52.z.object({
1042
+ id: import_zod52.z.string().min(1),
1043
+ feedback: FeedbackSummarySchema.optional(),
1044
+ callerNodeId: import_zod52.z.string().optional(),
1045
+ parentRunId: import_zod52.z.string().optional(),
1046
+ parentWorkflowId: import_zod52.z.string().optional(),
1047
+ invocationId: import_zod52.z.string().optional(),
1048
+ branchId: import_zod52.z.string().optional(),
1049
+ callId: import_zod52.z.string().optional(),
1050
+ status: StudioRunStatusSchema,
1051
+ startedAt: import_zod52.z.string().datetime({ offset: true }),
1052
+ endedAt: import_zod52.z.string().datetime({ offset: true }).nullable(),
1053
+ workflowId: import_zod52.z.string().min(1),
1054
+ workflowIds: import_zod52.z.array(import_zod52.z.string().min(1)),
1055
+ workflowRefs: import_zod52.z.array(
1056
+ import_zod52.z.object({
1057
+ workflowId: import_zod52.z.string().min(1),
1058
+ workflowRevisionId: import_zod52.z.string().nullable(),
1059
+ declaredVersion: import_zod52.z.string().nullable()
1060
+ }).strip()
1061
+ ),
1062
+ workflowRevisionId: import_zod52.z.string().nullable(),
1063
+ declaredVersion: import_zod52.z.string().nullable(),
1064
+ transitionIds: import_zod52.z.array(import_zod52.z.string().min(1)),
1065
+ path: import_zod52.z.array(import_zod52.z.string()),
1066
+ sessionId: import_zod52.z.string().nullable(),
1067
+ provider: import_zod52.z.string().nullable(),
1068
+ model: import_zod52.z.string().nullable(),
1069
+ models: import_zod52.z.array(import_zod52.z.string()),
1070
+ durationMs: import_zod52.z.number().nonnegative().nullable(),
1071
+ tokens: import_zod52.z.number().int().nonnegative().nullable(),
1072
+ cost: import_zod52.z.number().nonnegative().nullable(),
1073
+ pricingStatus: StudioPricingStatusSchema,
1074
+ pricingSource: StudioPricingSourceSchema,
1075
+ currency: import_zod52.z.string().nullable(),
1076
+ result: import_zod52.z.string().nullable(),
1077
+ environment: import_zod52.z.string().min(1),
1078
+ userId: import_zod52.z.string().nullable(),
1079
+ tenantId: import_zod52.z.string().nullable(),
1080
+ hasTool: import_zod52.z.boolean(),
1081
+ hasRetry: import_zod52.z.boolean(),
1082
+ interruptNodeId: import_zod52.z.string().nullable(),
1083
+ interruptId: import_zod52.z.string().nullable().optional(),
1084
+ interruptStatus: StudioInterruptStatusSchema.nullable().optional(),
1085
+ interruptExpiresAt: import_zod52.z.string().datetime({ offset: true }).nullable().optional()
1086
+ }).strip();
1087
+ var StudioSessionSchema = import_zod52.z.object({
1088
+ id: import_zod52.z.string().min(1),
1089
+ status: StudioRunStatusSchema,
1090
+ lastActivityAt: import_zod52.z.string().datetime({ offset: true }),
1091
+ workflowIds: import_zod52.z.array(import_zod52.z.string()),
1092
+ workflowCount: import_zod52.z.number().int().nonnegative(),
1093
+ activeWorkflowId: import_zod52.z.string().nullable(),
1094
+ activeVersion: import_zod52.z.string().nullable(),
1095
+ userId: import_zod52.z.string().nullable(),
1096
+ tenantId: import_zod52.z.string().nullable(),
1097
+ runs: import_zod52.z.number().int().nonnegative(),
1098
+ succeeded: import_zod52.z.number().int().nonnegative(),
1099
+ failed: import_zod52.z.number().int().nonnegative(),
1100
+ interrupted: import_zod52.z.number().int().nonnegative(),
1101
+ checkpoints: import_zod52.z.number().int().nonnegative(),
1102
+ hasFork: import_zod52.z.boolean(),
1103
+ durationMs: import_zod52.z.number().nonnegative().nullable(),
1104
+ tokens: import_zod52.z.number().int().nonnegative().nullable(),
1105
+ cost: import_zod52.z.number().nonnegative().nullable(),
1106
+ pricingStatus: StudioPricingStatusSchema,
1107
+ pricingSource: StudioPricingSourceSchema,
1108
+ currency: import_zod52.z.string().nullable(),
1109
+ latestResult: import_zod52.z.string().nullable(),
1110
+ latestError: import_zod52.z.string().nullable(),
1111
+ pendingInterruptId: import_zod52.z.string().nullable(),
1112
+ interruptStatus: StudioInterruptStatusSchema.nullable().optional(),
1113
+ interruptExpiresAt: import_zod52.z.string().datetime({ offset: true }).nullable().optional(),
1114
+ providers: import_zod52.z.array(import_zod52.z.string()),
1115
+ models: import_zod52.z.array(import_zod52.z.string()),
1116
+ tags: import_zod52.z.array(import_zod52.z.string()),
1117
+ environment: import_zod52.z.string().min(1)
1118
+ }).strip();
1119
+ var StudioInterruptSchema = import_zod52.z.object({
1120
+ afterResponseCompleted: import_zod52.z.boolean().optional(),
1121
+ id: import_zod52.z.string().min(1),
1122
+ status: StudioInterruptStatusSchema,
1123
+ type: StudioInterruptTypeSchema,
1124
+ interactionMode: StudioInterruptInteractionModeSchema,
1125
+ contract: import_zod52.z.string().nullable().default(null),
1126
+ schemaId: import_zod52.z.string().nullable(),
1127
+ schemaVersion: import_zod52.z.string().nullable(),
1128
+ createdAt: import_zod52.z.string().datetime({ offset: true }),
1129
+ resolvedAt: import_zod52.z.string().datetime({ offset: true }).nullable(),
1130
+ expiresAt: import_zod52.z.string().datetime({ offset: true }).nullable(),
1131
+ question: import_zod52.z.string().nullable(),
1132
+ contentCaptured: import_zod52.z.boolean(),
1133
+ request: import_zod52.z.record(import_zod52.z.string(), import_zod52.z.unknown()).nullable().default(null),
1134
+ requestCaptured: import_zod52.z.boolean().default(false),
1135
+ optionCount: import_zod52.z.number().int().nonnegative().nullable(),
1136
+ options: import_zod52.z.array(StudioInterruptOptionSchema).nullable(),
1137
+ workflowId: import_zod52.z.string().min(1),
1138
+ nodeId: import_zod52.z.string().nullable(),
1139
+ sessionId: import_zod52.z.string().nullable(),
1140
+ userId: import_zod52.z.string().nullable(),
1141
+ tenantId: import_zod52.z.string().nullable(),
1142
+ response: import_zod52.z.string().nullable(),
1143
+ responseValue: StudioInterruptValueSchema.nullable().default(null),
1144
+ responseCaptured: import_zod52.z.boolean(),
1145
+ resumeOutcome: StudioResumeOutcomeSchema.nullable(),
1146
+ resumeError: import_zod52.z.string().nullable(),
1147
+ runId: import_zod52.z.string().min(1),
1148
+ resumeToken: import_zod52.z.string().nullable(),
1149
+ resolvedBy: import_zod52.z.string().nullable(),
1150
+ environment: import_zod52.z.string().min(1)
1151
+ }).strip();
1152
+ var StudioDetailEventSchema = import_zod52.z.object({
1153
+ id: import_zod52.z.string().min(1),
1154
+ // Studio readers must preserve future event kinds within the same API major.
1155
+ type: import_zod52.z.string().min(1),
1156
+ occurredAt: import_zod52.z.string().datetime({ offset: true }),
1157
+ receivedAt: import_zod52.z.string().datetime({ offset: true }),
1158
+ environment: import_zod52.z.string().min(1),
1159
+ serviceName: import_zod52.z.string().min(1),
1160
+ deploymentRef: import_zod52.z.string().nullable(),
1161
+ traceId: import_zod52.z.string().nullable(),
1162
+ spanId: import_zod52.z.string().nullable(),
1163
+ parentSpanId: import_zod52.z.string().nullable(),
1164
+ runId: import_zod52.z.string().min(1),
1165
+ sessionId: import_zod52.z.string().nullable(),
1166
+ workflowId: import_zod52.z.string().min(1),
1167
+ workflowRevisionId: import_zod52.z.string().nullable(),
1168
+ nodeId: import_zod52.z.string().nullable(),
1169
+ userId: import_zod52.z.string().nullable(),
1170
+ tenantId: import_zod52.z.string().nullable(),
1171
+ tags: import_zod52.z.array(import_zod52.z.string()),
1172
+ metadata: import_zod52.z.record(import_zod52.z.string(), import_zod52.z.unknown()).nullable(),
1173
+ payload: import_zod52.z.record(import_zod52.z.string(), import_zod52.z.unknown())
1174
+ }).strip();
1175
+ var StudioWorkflowNodeSchema = import_zod52.z.object({
1176
+ tools: import_zod52.z.array(StudioToolSchema).optional(),
1177
+ toolDiscovery: ToolDiscoverySchema.optional(),
1178
+ id: import_zod52.z.string().min(1),
1179
+ label: import_zod52.z.string(),
1180
+ type: import_zod52.z.string().nullable(),
1181
+ state: import_zod52.z.enum(["healthy", "warning", "failed", "interrupted", "retried"]).nullable(),
1182
+ provider: import_zod52.z.string().nullable(),
1183
+ model: import_zod52.z.string().nullable(),
1184
+ metrics: StudioMetricSchema
1185
+ }).strip();
1186
+ var StudioWorkflowInternalEdgeSchema = import_zod52.z.object({
1187
+ id: import_zod52.z.string().min(1),
1188
+ source: import_zod52.z.string().min(1),
1189
+ target: import_zod52.z.string().min(1),
1190
+ condition: import_zod52.z.string().nullable()
1191
+ }).strip();
1192
+ var StudioWorkflowTransitionSchema = import_zod52.z.object({
1193
+ kind: import_zod52.z.enum(["call", "handoff"]).optional(),
1194
+ id: import_zod52.z.string().min(1),
1195
+ sourceWorkflowId: import_zod52.z.string().min(1),
1196
+ sourceNodeId: import_zod52.z.string().nullable(),
1197
+ targetWorkflowId: import_zod52.z.string().min(1),
1198
+ condition: import_zod52.z.string().nullable(),
1199
+ volume: import_zod52.z.number().int().nonnegative(),
1200
+ successRate: import_zod52.z.number().min(0).max(100).nullable(),
1201
+ medianDurationMs: import_zod52.z.number().nonnegative().nullable(),
1202
+ errorRate: import_zod52.z.number().min(0).max(100).nullable()
1203
+ }).strip();
1204
+ var StudioWorkflowSchema = import_zod52.z.object({
1205
+ id: import_zod52.z.string().min(1),
1206
+ name: import_zod52.z.string().min(1),
1207
+ description: import_zod52.z.string().nullable(),
1208
+ versions: import_zod52.z.array(import_zod52.z.string()),
1209
+ activeVersion: import_zod52.z.string().nullable(),
1210
+ activeRevisionId: import_zod52.z.string().nullable(),
1211
+ health: StudioWorkflowHealthSchema,
1212
+ tags: import_zod52.z.array(import_zod52.z.string()),
1213
+ lastActivityAt: import_zod52.z.string().datetime({ offset: true }).nullable(),
1214
+ metrics: StudioMetricSchema,
1215
+ nodes: import_zod52.z.array(StudioWorkflowNodeSchema),
1216
+ internalEdges: import_zod52.z.array(StudioWorkflowInternalEdgeSchema)
1217
+ }).strip();
1218
+ var StudioRunsResponseSchema = import_zod52.z.object({
1219
+ runs: import_zod52.z.array(StudioRunSchema),
1220
+ totalCount: import_zod52.z.number().int().nonnegative()
1221
+ }).strip();
1222
+ var StudioSessionsResponseSchema = import_zod52.z.object({
1223
+ sessions: import_zod52.z.array(StudioSessionSchema),
1224
+ totalCount: import_zod52.z.number().int().nonnegative()
1225
+ }).strip();
1226
+ var StudioInterruptsResponseSchema = import_zod52.z.object({
1227
+ interrupts: import_zod52.z.array(StudioInterruptSchema),
1228
+ totalCount: import_zod52.z.number().int().nonnegative()
1229
+ }).strip();
1230
+ var StudioRunDetailResponseSchema = import_zod52.z.object({
1231
+ run: StudioRunSchema,
1232
+ scores: import_zod52.z.array(StudioScoreSchema).optional(),
1233
+ canReview: import_zod52.z.boolean().optional(),
1234
+ reviewActorId: import_zod52.z.string().optional(),
1235
+ events: import_zod52.z.array(StudioDetailEventSchema),
1236
+ session: StudioSessionSchema.nullable(),
1237
+ interrupts: import_zod52.z.array(StudioInterruptSchema),
1238
+ updatedAt: import_zod52.z.string().datetime({ offset: true })
1239
+ }).strip();
1240
+ var StudioSessionDetailResponseSchema = import_zod52.z.object({
1241
+ session: StudioSessionSchema,
1242
+ runs: import_zod52.z.array(StudioRunSchema),
1243
+ events: import_zod52.z.array(StudioDetailEventSchema),
1244
+ interrupts: import_zod52.z.array(StudioInterruptSchema),
1245
+ updatedAt: import_zod52.z.string().datetime({ offset: true })
1246
+ }).strip();
1247
+ var StudioInterruptDetailResponseSchema = import_zod52.z.object({
1248
+ interrupt: StudioInterruptSchema,
1249
+ events: import_zod52.z.array(StudioDetailEventSchema),
1250
+ run: StudioRunSchema.nullable(),
1251
+ session: StudioSessionSchema.nullable(),
1252
+ updatedAt: import_zod52.z.string().datetime({ offset: true })
1253
+ }).strip();
1254
+ var StudioWorkflowsResponseSchema = import_zod52.z.object({
1255
+ workflows: import_zod52.z.array(StudioWorkflowSchema),
1256
+ observedCalls: import_zod52.z.array(
1257
+ StudioWorkflowTransitionSchema.extend({
1258
+ runId: import_zod52.z.string(),
1259
+ invocationId: import_zod52.z.string(),
1260
+ branchId: import_zod52.z.string()
1261
+ })
1262
+ ).optional(),
1263
+ transitions: import_zod52.z.array(StudioWorkflowTransitionSchema),
1264
+ cohort: StudioTimeRangeContextSchema.extend({
1265
+ workflowId: import_zod52.z.string().nullable(),
1266
+ version: import_zod52.z.string().nullable()
1267
+ }).strip()
1268
+ }).strip();
1269
+ var StudioCatalogsResponseSchema = import_zod52.z.object({
1270
+ environments: import_zod52.z.array(import_zod52.z.string()),
1271
+ providers: import_zod52.z.array(import_zod52.z.string()),
1272
+ models: import_zod52.z.array(import_zod52.z.string()),
1273
+ workflows: import_zod52.z.array(import_zod52.z.string()),
1274
+ tags: import_zod52.z.array(import_zod52.z.string())
1275
+ }).strip();
1276
+ var StudioContextResponseSchema = import_zod52.z.object({
1277
+ organization: import_zod52.z.object({
1278
+ name: import_zod52.z.string().min(1)
1279
+ }).strip(),
1280
+ project: import_zod52.z.object({
1281
+ name: import_zod52.z.string().min(1)
1282
+ }).strip(),
1283
+ environments: import_zod52.z.array(import_zod52.z.string()),
1284
+ apiKey: import_zod52.z.object({
1285
+ mode: import_zod52.z.enum(["test", "live"]),
1286
+ scopes: import_zod52.z.array(import_zod52.z.string())
1287
+ }).strip().nullable(),
1288
+ api: import_zod52.z.object({
1289
+ status: import_zod52.z.literal("ok"),
1290
+ service: import_zod52.z.literal("kortyx-api"),
1291
+ version: import_zod52.z.string().min(1)
1292
+ }).strip()
1293
+ }).strip();
1294
+ }
1295
+ });
1296
+
32
1297
  // ../hooks/dist/internal.js
33
1298
  var require_internal = __commonJS({
34
1299
  "../hooks/dist/internal.js"(exports2, module2) {
@@ -51,6 +1316,7 @@ var require_internal = __commonJS({
51
1316
  var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
52
1317
  var internal_exports = {};
53
1318
  __export2(internal_exports, {
1319
+ captureDiagnosticContent: () => captureDiagnosticContent,
54
1320
  errorDiagnostics: () => errorDiagnostics,
55
1321
  exceptionDiagnostics: () => exceptionDiagnostics,
56
1322
  isModelTraceSpan: () => isModelTraceSpan,
@@ -58,55 +1324,258 @@ var require_internal = __commonJS({
58
1324
  safeSpan: () => safeSpan,
59
1325
  safeStartSpan: () => safeStartSpan2,
60
1326
  safeTelemetryMetadata: () => safeTelemetryMetadata2,
1327
+ summarizeDiagnostic: () => import_telemetry_contracts3.summarizeDiagnostic,
61
1328
  withSafeTraceSpan: () => withSafeTraceSpan2
62
1329
  });
63
1330
  module2.exports = __toCommonJS2(internal_exports);
1331
+ var import_telemetry_contracts3 = require_dist();
64
1332
  var import_errors8 = require("@kortyx/core/errors");
65
- var MAX_STACK_LENGTH = 32768;
66
- var MAX_CAUSE_DEPTH = 4;
67
- var projectDetails = (value, depth, seen) => {
68
- const objectValue = value && typeof value === "object" ? value : void 0;
69
- if (objectValue) {
70
- if (seen.has(objectValue))
71
- return { type: "Error", message: "Circular error cause." };
72
- seen.add(objectValue);
73
- }
74
- const name = (0, import_errors8.errorProperty)(value, "name") ?? (value instanceof Error ? value.name : void 0);
75
- const message = (0, import_errors8.errorProperty)(value, "message");
76
- const stack = (0, import_errors8.errorProperty)(value, "stack") ?? (value instanceof Error ? (() => {
1333
+ var import_telemetry_contracts = require_dist();
1334
+ var encoder = new TextEncoder();
1335
+ var nativeStackGetter = Object.getOwnPropertyDescriptor(
1336
+ new Error(),
1337
+ "stack"
1338
+ )?.get;
1339
+ function nativeStack(object, getter) {
1340
+ if (!getter || getter !== nativeStackGetter)
1341
+ throw new Error("Custom stack accessor");
1342
+ for (const key of ["name", "message"]) {
1343
+ let cursor = object;
1344
+ while (cursor) {
1345
+ const descriptor = Object.getOwnPropertyDescriptor(cursor, key);
1346
+ if (descriptor) {
1347
+ if (!("value" in descriptor) || typeof descriptor.value !== "string")
1348
+ throw new Error("Custom error formatting");
1349
+ break;
1350
+ }
1351
+ cursor = Object.getPrototypeOf(cursor);
1352
+ }
1353
+ }
1354
+ const formatter = Object.getOwnPropertyDescriptor(Error, "prepareStackTrace");
1355
+ if (formatter && (!("value" in formatter) || !formatter.writable))
1356
+ throw new Error("Custom stack formatter");
1357
+ Object.defineProperty(Error, "prepareStackTrace", {
1358
+ ...formatter ?? { configurable: true, writable: true },
1359
+ value: void 0
1360
+ });
1361
+ try {
1362
+ return getter.call(object);
1363
+ } finally {
1364
+ if (formatter) Object.defineProperty(Error, "prepareStackTrace", formatter);
1365
+ else Reflect.deleteProperty(Error, "prepareStackTrace");
1366
+ }
1367
+ }
1368
+ var pointer = (key) => key.replace(/~/g, "~0").replace(/\//g, "~1");
1369
+ function captureDiagnosticContent(error, project) {
1370
+ const omissions = [];
1371
+ const redactions = [];
1372
+ const seen = /* @__PURE__ */ new WeakMap();
1373
+ let nodes = 0;
1374
+ let remaining = import_telemetry_contracts.DIAGNOSTIC_LIMITS.bytes - 64 * 1024;
1375
+ const omit = (path, reason, extra = {}) => {
1376
+ if (omissions.length < 1e3)
1377
+ omissions.push({ path: path.slice(0, 4096), reason, ...extra });
1378
+ return { $omitted: reason };
1379
+ };
1380
+ const visit = (value, path, depth) => {
1381
+ if (++nodes > import_telemetry_contracts.DIAGNOSTIC_LIMITS.nodes) return omit(path, "node_limit");
1382
+ if (depth > import_telemetry_contracts.DIAGNOSTIC_LIMITS.depth) return omit(path, "depth_limit");
1383
+ if (typeof value === "string") {
1384
+ const clean = (0, import_telemetry_contracts.redactDiagnosticText)(value);
1385
+ if (clean !== value && redactions.length < 1e3)
1386
+ redactions.push({
1387
+ path: path.slice(0, 4096),
1388
+ reason: "credential_text"
1389
+ });
1390
+ const bytes = encoder.encode(JSON.stringify(clean)).length;
1391
+ if (bytes > remaining)
1392
+ return omit(path, "byte_limit", {
1393
+ originalBytes: encoder.encode(value).length
1394
+ });
1395
+ remaining -= bytes;
1396
+ return clean;
1397
+ }
1398
+ if (value === null || typeof value === "boolean") return value;
1399
+ if (typeof value === "number")
1400
+ return Number.isFinite(value) ? value : { $type: "number", value: String(value) };
1401
+ if (typeof value === "bigint")
1402
+ return { $type: "bigint", value: value.toString() };
1403
+ if (typeof value === "undefined") return { $type: "undefined" };
1404
+ if (typeof value === "function" || typeof value === "symbol")
1405
+ return omit(path, `unsupported_${typeof value}`);
1406
+ const object = value;
1407
+ const reference = seen.get(object);
1408
+ if (reference) return { $ref: reference };
1409
+ seen.set(object, path);
1410
+ remaining -= 32;
1411
+ if (remaining < 0) return omit(path, "byte_limit");
1412
+ try {
1413
+ if (value instanceof Date)
1414
+ return { $type: "Date", value: Date.prototype.toISOString.call(value) };
1415
+ if (value instanceof Map || value instanceof Set) {
1416
+ const isMap = value instanceof Map;
1417
+ const iterator = isMap ? Map.prototype.entries.call(value) : Set.prototype.values.call(value);
1418
+ const count = Object.getOwnPropertyDescriptor(
1419
+ isMap ? Map.prototype : Set.prototype,
1420
+ "size"
1421
+ )?.get?.call(value);
1422
+ const entries = [];
1423
+ for (let index = 0; index < Math.min(count, import_telemetry_contracts.DIAGNOSTIC_LIMITS.properties); index++)
1424
+ entries.push(iterator.next().value);
1425
+ if (count > entries.length)
1426
+ omissions.push({
1427
+ path,
1428
+ reason: "collection_limit",
1429
+ originalCount: count
1430
+ });
1431
+ return isMap ? {
1432
+ $type: "Map",
1433
+ entries: visit(entries, `${path}/entries`, depth + 1)
1434
+ } : {
1435
+ $type: "Set",
1436
+ values: visit(entries, `${path}/values`, depth + 1)
1437
+ };
1438
+ }
1439
+ if (Array.isArray(value)) {
1440
+ const count = Math.min(value.length, import_telemetry_contracts.DIAGNOSTIC_LIMITS.properties);
1441
+ const items = Array.from(
1442
+ { length: count },
1443
+ (_, index) => read(value, String(index), `${path}/${index}`, depth)
1444
+ );
1445
+ if (count < value.length)
1446
+ items.push(
1447
+ omit(path, "collection_limit", { originalCount: value.length })
1448
+ );
1449
+ return items;
1450
+ }
1451
+ const keys = Object.getOwnPropertyNames(object);
1452
+ const result = /* @__PURE__ */ Object.create(null);
1453
+ if (value instanceof Error) {
1454
+ const ownName = Object.getOwnPropertyDescriptor(object, "name");
1455
+ let type = ownName && "value" in ownName ? ownName.value : void 0;
1456
+ if (typeof type !== "string") {
1457
+ const name = Object.getOwnPropertyDescriptor(
1458
+ Object.getPrototypeOf(value),
1459
+ "name"
1460
+ );
1461
+ type = name && "value" in name ? name.value : "Error";
1462
+ }
1463
+ result.type = visit(
1464
+ typeof type === "string" ? type : "Error",
1465
+ `${path}/type`,
1466
+ depth + 1
1467
+ );
1468
+ }
1469
+ for (const key of keys.slice(0, import_telemetry_contracts.DIAGNOSTIC_LIMITS.properties)) {
1470
+ if (["__proto__", "constructor", "prototype"].includes(key)) {
1471
+ result[key] = omit(`${path}/${pointer(key)}`, "unsafe_key");
1472
+ continue;
1473
+ }
1474
+ remaining -= encoder.encode(key).length + 4;
1475
+ result[key] = read(object, key, `${path}/${pointer(key)}`, depth);
1476
+ }
1477
+ if (keys.length > import_telemetry_contracts.DIAGNOSTIC_LIMITS.properties)
1478
+ result.$omittedProperties = omit(path, "property_limit", {
1479
+ originalCount: keys.length
1480
+ });
1481
+ return result;
1482
+ } catch {
1483
+ return omit(path, "unreadable_object");
1484
+ }
1485
+ };
1486
+ const read = (object, key, path, depth) => {
1487
+ if ((0, import_telemetry_contracts.isPrivateDiagnosticField)(key)) {
1488
+ if (redactions.length < 1e3)
1489
+ redactions.push({
1490
+ path: path.slice(0, 4096),
1491
+ reason: "credential_field"
1492
+ });
1493
+ return "[REDACTED]";
1494
+ }
77
1495
  try {
78
- return value.stack;
1496
+ const property = Object.getOwnPropertyDescriptor(object, key);
1497
+ if (property && "value" in property)
1498
+ return visit(property.value, path, depth + 1);
1499
+ if (key === "stack" && object instanceof Error && property?.get && property.get === nativeStackGetter)
1500
+ return visit(nativeStack(object, property.get), path, depth + 1);
1501
+ return omit(
1502
+ path,
1503
+ property ? "accessor_not_evaluated" : "unavailable_property"
1504
+ );
79
1505
  } catch {
80
- return void 0;
1506
+ return omit(path, "unreadable_property");
81
1507
  }
82
- })() : void 0);
83
- const cause = depth < MAX_CAUSE_DEPTH ? (0, import_errors8.errorProperty)(value, "cause") : null;
84
- return {
85
- type: typeof name === "string" ? name.slice(0, 256) : "Error",
86
- message: (typeof value === "string" ? value : typeof message === "string" ? message : "Execution reported a fault.").slice(0, 8192),
87
- ...typeof stack === "string" ? { stack: stack.slice(0, MAX_STACK_LENGTH) } : {},
88
- ...cause !== null && cause !== void 0 ? { cause: projectDetails(cause, depth + 1, seen) } : {}
89
1508
  };
90
- };
91
- var sanitizeProjectedDetails = (details, depth = 0) => ({
92
- ...typeof details.type === "string" ? { type: details.type.slice(0, 256) } : {},
93
- message: typeof details.message === "string" ? details.message.slice(0, 8192) : "Execution reported a fault.",
94
- ...typeof details.stack === "string" ? { stack: details.stack.slice(0, MAX_STACK_LENGTH) } : {},
95
- ...depth < MAX_CAUSE_DEPTH && details.cause ? { cause: sanitizeProjectedDetails(details.cause, depth + 1) } : {}
96
- });
97
- function exceptionDiagnostics(error, project) {
98
1509
  try {
99
- const details = project ? project(error) : projectDetails(error, 0, /* @__PURE__ */ new WeakSet());
100
- return details ? sanitizeProjectedDetails(details) : null;
1510
+ const original = project ? project(error) : error;
1511
+ if (project && original === null) return null;
1512
+ const captured = visit(original, "#/data", 0);
1513
+ const upstreamOmissions = (0, import_errors8.errorProperty)(original, "diagnosticOmissions");
1514
+ if (Array.isArray(upstreamOmissions))
1515
+ for (const note of upstreamOmissions.slice(0, 1e3)) {
1516
+ const path = (0, import_errors8.errorProperty)(note, "path");
1517
+ const reason = (0, import_errors8.errorProperty)(note, "reason");
1518
+ if (typeof path === "string" && typeof reason === "string")
1519
+ omissions.push({
1520
+ path: (0, import_telemetry_contracts.redactDiagnosticText)(path).slice(0, 4096),
1521
+ reason: (0, import_telemetry_contracts.redactDiagnosticText)(reason).slice(0, 128)
1522
+ });
1523
+ }
1524
+ const data = captured && typeof captured === "object" && !Array.isArray(captured) ? captured : {
1525
+ type: "Error",
1526
+ message: typeof captured === "string" ? captured : "Execution reported a fault.",
1527
+ value: captured
1528
+ };
1529
+ if (typeof data.message !== "string" && !("message" in data))
1530
+ data.message = "Execution reported a fault.";
1531
+ if (!("type" in data))
1532
+ data.type = typeof data.name === "string" ? data.name : "Error";
1533
+ const content = {
1534
+ schemaVersion: 1,
1535
+ data,
1536
+ capture: {
1537
+ status: omissions.length ? "partial" : "complete",
1538
+ omissions,
1539
+ redactions
1540
+ }
1541
+ };
1542
+ if (encoder.encode(JSON.stringify(content)).length > import_telemetry_contracts.DIAGNOSTIC_LIMITS.bytes)
1543
+ return {
1544
+ schemaVersion: 1,
1545
+ data: {
1546
+ type: "Error",
1547
+ message: "Diagnostic exceeded the capture budget."
1548
+ },
1549
+ capture: {
1550
+ status: "partial",
1551
+ redactions: [],
1552
+ omissions: [{ path: "#/data", reason: "serialized_byte_limit" }]
1553
+ }
1554
+ };
1555
+ return content;
101
1556
  } catch {
102
- return null;
1557
+ return {
1558
+ schemaVersion: 1,
1559
+ data: { type: "Error", message: "Diagnostic capture failed." },
1560
+ capture: {
1561
+ status: "failed",
1562
+ redactions: [],
1563
+ omissions: [{ path: "#/data", reason: "projection_or_capture_failed" }]
1564
+ }
1565
+ };
103
1566
  }
104
1567
  }
1568
+ var import_telemetry_contracts2 = require_dist();
1569
+ function exceptionDiagnostics(error, project) {
1570
+ const content = captureDiagnosticContent(error, project);
1571
+ return !content || content.capture.status === "failed" ? null : content.data;
1572
+ }
105
1573
  function errorDiagnostics(error, project) {
106
- const details = exceptionDiagnostics(error, project);
1574
+ const captured = exceptionDiagnostics(error, project);
1575
+ const details = captured ? (0, import_telemetry_contracts2.summarizeDiagnostic)(captured) : null;
107
1576
  return details ? {
108
- errorMessage: details.message,
109
- ...details.type ? { errorType: details.type } : {}
1577
+ errorMessage: details.message.slice(0, 8192),
1578
+ ...details.type ? { errorType: details.type.slice(0, 256) } : {}
110
1579
  } : {};
111
1580
  }
112
1581
  function isModelTraceSpan(name) {
@@ -500,7 +1969,7 @@ var require_internal = __commonJS({
500
1969
  });
501
1970
 
502
1971
  // ../hooks/dist/index.js
503
- var require_dist = __commonJS({
1972
+ var require_dist2 = __commonJS({
504
1973
  "../hooks/dist/index.js"(exports2, module2) {
505
1974
  var __defProp2 = Object.defineProperty;
506
1975
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -1187,52 +2656,253 @@ var require_dist = __commonJS({
1187
2656
  var import_node_crypto32 = require("crypto");
1188
2657
  var import_core22 = require("@kortyx/core");
1189
2658
  var import_errors32 = require("@kortyx/core/errors");
2659
+ var import_telemetry_contracts2 = require_dist();
1190
2660
  var import_errors22 = require("@kortyx/core/errors");
1191
- var MAX_STACK_LENGTH = 32768;
1192
- var MAX_CAUSE_DEPTH = 4;
1193
- var projectDetails = (value, depth, seen) => {
1194
- const objectValue = value && typeof value === "object" ? value : void 0;
1195
- if (objectValue) {
1196
- if (seen.has(objectValue))
1197
- return { type: "Error", message: "Circular error cause." };
1198
- seen.add(objectValue);
1199
- }
1200
- const name = (0, import_errors22.errorProperty)(value, "name") ?? (value instanceof Error ? value.name : void 0);
1201
- const message = (0, import_errors22.errorProperty)(value, "message");
1202
- const stack = (0, import_errors22.errorProperty)(value, "stack") ?? (value instanceof Error ? (() => {
2661
+ var import_telemetry_contracts = require_dist();
2662
+ var encoder = new TextEncoder();
2663
+ var nativeStackGetter = Object.getOwnPropertyDescriptor(
2664
+ new Error(),
2665
+ "stack"
2666
+ )?.get;
2667
+ function nativeStack(object, getter) {
2668
+ if (!getter || getter !== nativeStackGetter)
2669
+ throw new Error("Custom stack accessor");
2670
+ for (const key of ["name", "message"]) {
2671
+ let cursor = object;
2672
+ while (cursor) {
2673
+ const descriptor = Object.getOwnPropertyDescriptor(cursor, key);
2674
+ if (descriptor) {
2675
+ if (!("value" in descriptor) || typeof descriptor.value !== "string")
2676
+ throw new Error("Custom error formatting");
2677
+ break;
2678
+ }
2679
+ cursor = Object.getPrototypeOf(cursor);
2680
+ }
2681
+ }
2682
+ const formatter = Object.getOwnPropertyDescriptor(Error, "prepareStackTrace");
2683
+ if (formatter && (!("value" in formatter) || !formatter.writable))
2684
+ throw new Error("Custom stack formatter");
2685
+ Object.defineProperty(Error, "prepareStackTrace", {
2686
+ ...formatter ?? { configurable: true, writable: true },
2687
+ value: void 0
2688
+ });
2689
+ try {
2690
+ return getter.call(object);
2691
+ } finally {
2692
+ if (formatter) Object.defineProperty(Error, "prepareStackTrace", formatter);
2693
+ else Reflect.deleteProperty(Error, "prepareStackTrace");
2694
+ }
2695
+ }
2696
+ var pointer = (key) => key.replace(/~/g, "~0").replace(/\//g, "~1");
2697
+ function captureDiagnosticContent(error, project) {
2698
+ const omissions = [];
2699
+ const redactions = [];
2700
+ const seen = /* @__PURE__ */ new WeakMap();
2701
+ let nodes = 0;
2702
+ let remaining = import_telemetry_contracts.DIAGNOSTIC_LIMITS.bytes - 64 * 1024;
2703
+ const omit = (path, reason, extra = {}) => {
2704
+ if (omissions.length < 1e3)
2705
+ omissions.push({ path: path.slice(0, 4096), reason, ...extra });
2706
+ return { $omitted: reason };
2707
+ };
2708
+ const visit = (value, path, depth) => {
2709
+ if (++nodes > import_telemetry_contracts.DIAGNOSTIC_LIMITS.nodes) return omit(path, "node_limit");
2710
+ if (depth > import_telemetry_contracts.DIAGNOSTIC_LIMITS.depth) return omit(path, "depth_limit");
2711
+ if (typeof value === "string") {
2712
+ const clean = (0, import_telemetry_contracts.redactDiagnosticText)(value);
2713
+ if (clean !== value && redactions.length < 1e3)
2714
+ redactions.push({
2715
+ path: path.slice(0, 4096),
2716
+ reason: "credential_text"
2717
+ });
2718
+ const bytes = encoder.encode(JSON.stringify(clean)).length;
2719
+ if (bytes > remaining)
2720
+ return omit(path, "byte_limit", {
2721
+ originalBytes: encoder.encode(value).length
2722
+ });
2723
+ remaining -= bytes;
2724
+ return clean;
2725
+ }
2726
+ if (value === null || typeof value === "boolean") return value;
2727
+ if (typeof value === "number")
2728
+ return Number.isFinite(value) ? value : { $type: "number", value: String(value) };
2729
+ if (typeof value === "bigint")
2730
+ return { $type: "bigint", value: value.toString() };
2731
+ if (typeof value === "undefined") return { $type: "undefined" };
2732
+ if (typeof value === "function" || typeof value === "symbol")
2733
+ return omit(path, `unsupported_${typeof value}`);
2734
+ const object = value;
2735
+ const reference = seen.get(object);
2736
+ if (reference) return { $ref: reference };
2737
+ seen.set(object, path);
2738
+ remaining -= 32;
2739
+ if (remaining < 0) return omit(path, "byte_limit");
2740
+ try {
2741
+ if (value instanceof Date)
2742
+ return { $type: "Date", value: Date.prototype.toISOString.call(value) };
2743
+ if (value instanceof Map || value instanceof Set) {
2744
+ const isMap = value instanceof Map;
2745
+ const iterator = isMap ? Map.prototype.entries.call(value) : Set.prototype.values.call(value);
2746
+ const count = Object.getOwnPropertyDescriptor(
2747
+ isMap ? Map.prototype : Set.prototype,
2748
+ "size"
2749
+ )?.get?.call(value);
2750
+ const entries = [];
2751
+ for (let index = 0; index < Math.min(count, import_telemetry_contracts.DIAGNOSTIC_LIMITS.properties); index++)
2752
+ entries.push(iterator.next().value);
2753
+ if (count > entries.length)
2754
+ omissions.push({
2755
+ path,
2756
+ reason: "collection_limit",
2757
+ originalCount: count
2758
+ });
2759
+ return isMap ? {
2760
+ $type: "Map",
2761
+ entries: visit(entries, `${path}/entries`, depth + 1)
2762
+ } : {
2763
+ $type: "Set",
2764
+ values: visit(entries, `${path}/values`, depth + 1)
2765
+ };
2766
+ }
2767
+ if (Array.isArray(value)) {
2768
+ const count = Math.min(value.length, import_telemetry_contracts.DIAGNOSTIC_LIMITS.properties);
2769
+ const items = Array.from(
2770
+ { length: count },
2771
+ (_, index) => read(value, String(index), `${path}/${index}`, depth)
2772
+ );
2773
+ if (count < value.length)
2774
+ items.push(
2775
+ omit(path, "collection_limit", { originalCount: value.length })
2776
+ );
2777
+ return items;
2778
+ }
2779
+ const keys = Object.getOwnPropertyNames(object);
2780
+ const result = /* @__PURE__ */ Object.create(null);
2781
+ if (value instanceof Error) {
2782
+ const ownName = Object.getOwnPropertyDescriptor(object, "name");
2783
+ let type = ownName && "value" in ownName ? ownName.value : void 0;
2784
+ if (typeof type !== "string") {
2785
+ const name = Object.getOwnPropertyDescriptor(
2786
+ Object.getPrototypeOf(value),
2787
+ "name"
2788
+ );
2789
+ type = name && "value" in name ? name.value : "Error";
2790
+ }
2791
+ result.type = visit(
2792
+ typeof type === "string" ? type : "Error",
2793
+ `${path}/type`,
2794
+ depth + 1
2795
+ );
2796
+ }
2797
+ for (const key of keys.slice(0, import_telemetry_contracts.DIAGNOSTIC_LIMITS.properties)) {
2798
+ if (["__proto__", "constructor", "prototype"].includes(key)) {
2799
+ result[key] = omit(`${path}/${pointer(key)}`, "unsafe_key");
2800
+ continue;
2801
+ }
2802
+ remaining -= encoder.encode(key).length + 4;
2803
+ result[key] = read(object, key, `${path}/${pointer(key)}`, depth);
2804
+ }
2805
+ if (keys.length > import_telemetry_contracts.DIAGNOSTIC_LIMITS.properties)
2806
+ result.$omittedProperties = omit(path, "property_limit", {
2807
+ originalCount: keys.length
2808
+ });
2809
+ return result;
2810
+ } catch {
2811
+ return omit(path, "unreadable_object");
2812
+ }
2813
+ };
2814
+ const read = (object, key, path, depth) => {
2815
+ if ((0, import_telemetry_contracts.isPrivateDiagnosticField)(key)) {
2816
+ if (redactions.length < 1e3)
2817
+ redactions.push({
2818
+ path: path.slice(0, 4096),
2819
+ reason: "credential_field"
2820
+ });
2821
+ return "[REDACTED]";
2822
+ }
1203
2823
  try {
1204
- return value.stack;
2824
+ const property = Object.getOwnPropertyDescriptor(object, key);
2825
+ if (property && "value" in property)
2826
+ return visit(property.value, path, depth + 1);
2827
+ if (key === "stack" && object instanceof Error && property?.get && property.get === nativeStackGetter)
2828
+ return visit(nativeStack(object, property.get), path, depth + 1);
2829
+ return omit(
2830
+ path,
2831
+ property ? "accessor_not_evaluated" : "unavailable_property"
2832
+ );
1205
2833
  } catch {
1206
- return void 0;
2834
+ return omit(path, "unreadable_property");
1207
2835
  }
1208
- })() : void 0);
1209
- const cause = depth < MAX_CAUSE_DEPTH ? (0, import_errors22.errorProperty)(value, "cause") : null;
1210
- return {
1211
- type: typeof name === "string" ? name.slice(0, 256) : "Error",
1212
- message: (typeof value === "string" ? value : typeof message === "string" ? message : "Execution reported a fault.").slice(0, 8192),
1213
- ...typeof stack === "string" ? { stack: stack.slice(0, MAX_STACK_LENGTH) } : {},
1214
- ...cause !== null && cause !== void 0 ? { cause: projectDetails(cause, depth + 1, seen) } : {}
1215
2836
  };
1216
- };
1217
- var sanitizeProjectedDetails = (details, depth = 0) => ({
1218
- ...typeof details.type === "string" ? { type: details.type.slice(0, 256) } : {},
1219
- message: typeof details.message === "string" ? details.message.slice(0, 8192) : "Execution reported a fault.",
1220
- ...typeof details.stack === "string" ? { stack: details.stack.slice(0, MAX_STACK_LENGTH) } : {},
1221
- ...depth < MAX_CAUSE_DEPTH && details.cause ? { cause: sanitizeProjectedDetails(details.cause, depth + 1) } : {}
1222
- });
1223
- function exceptionDiagnostics(error, project) {
1224
2837
  try {
1225
- const details = project ? project(error) : projectDetails(error, 0, /* @__PURE__ */ new WeakSet());
1226
- return details ? sanitizeProjectedDetails(details) : null;
2838
+ const original = project ? project(error) : error;
2839
+ if (project && original === null) return null;
2840
+ const captured = visit(original, "#/data", 0);
2841
+ const upstreamOmissions = (0, import_errors22.errorProperty)(original, "diagnosticOmissions");
2842
+ if (Array.isArray(upstreamOmissions))
2843
+ for (const note of upstreamOmissions.slice(0, 1e3)) {
2844
+ const path = (0, import_errors22.errorProperty)(note, "path");
2845
+ const reason = (0, import_errors22.errorProperty)(note, "reason");
2846
+ if (typeof path === "string" && typeof reason === "string")
2847
+ omissions.push({
2848
+ path: (0, import_telemetry_contracts.redactDiagnosticText)(path).slice(0, 4096),
2849
+ reason: (0, import_telemetry_contracts.redactDiagnosticText)(reason).slice(0, 128)
2850
+ });
2851
+ }
2852
+ const data = captured && typeof captured === "object" && !Array.isArray(captured) ? captured : {
2853
+ type: "Error",
2854
+ message: typeof captured === "string" ? captured : "Execution reported a fault.",
2855
+ value: captured
2856
+ };
2857
+ if (typeof data.message !== "string" && !("message" in data))
2858
+ data.message = "Execution reported a fault.";
2859
+ if (!("type" in data))
2860
+ data.type = typeof data.name === "string" ? data.name : "Error";
2861
+ const content = {
2862
+ schemaVersion: 1,
2863
+ data,
2864
+ capture: {
2865
+ status: omissions.length ? "partial" : "complete",
2866
+ omissions,
2867
+ redactions
2868
+ }
2869
+ };
2870
+ if (encoder.encode(JSON.stringify(content)).length > import_telemetry_contracts.DIAGNOSTIC_LIMITS.bytes)
2871
+ return {
2872
+ schemaVersion: 1,
2873
+ data: {
2874
+ type: "Error",
2875
+ message: "Diagnostic exceeded the capture budget."
2876
+ },
2877
+ capture: {
2878
+ status: "partial",
2879
+ redactions: [],
2880
+ omissions: [{ path: "#/data", reason: "serialized_byte_limit" }]
2881
+ }
2882
+ };
2883
+ return content;
1227
2884
  } catch {
1228
- return null;
2885
+ return {
2886
+ schemaVersion: 1,
2887
+ data: { type: "Error", message: "Diagnostic capture failed." },
2888
+ capture: {
2889
+ status: "failed",
2890
+ redactions: [],
2891
+ omissions: [{ path: "#/data", reason: "projection_or_capture_failed" }]
2892
+ }
2893
+ };
1229
2894
  }
1230
2895
  }
2896
+ function exceptionDiagnostics(error, project) {
2897
+ const content = captureDiagnosticContent(error, project);
2898
+ return !content || content.capture.status === "failed" ? null : content.data;
2899
+ }
1231
2900
  function errorDiagnostics(error, project) {
1232
- const details = exceptionDiagnostics(error, project);
2901
+ const captured = exceptionDiagnostics(error, project);
2902
+ const details = captured ? (0, import_telemetry_contracts2.summarizeDiagnostic)(captured) : null;
1233
2903
  return details ? {
1234
- errorMessage: details.message,
1235
- ...details.type ? { errorType: details.type } : {}
2904
+ errorMessage: details.message.slice(0, 8192),
2905
+ ...details.type ? { errorType: details.type.slice(0, 256) } : {}
1236
2906
  } : {};
1237
2907
  }
1238
2908
  var import_node_crypto22 = require("crypto");
@@ -1320,10 +2990,40 @@ var require_dist = __commonJS({
1320
2990
  function captureToolError(observation, error, policy, returned = false) {
1321
2991
  try {
1322
2992
  const reported = returned && error && typeof error === "object" && "isError" in error && error.isError === true && "content" in error && typeof error.content === "string" ? { name: "ToolError", message: error.content } : error;
2993
+ let projected = false;
2994
+ let projection;
2995
+ let projectionFailure;
2996
+ let projectionFailed = false;
2997
+ const project = policy?.error ? (original) => {
2998
+ if (!projected) {
2999
+ projected = true;
3000
+ try {
3001
+ projection = policy.error?.(original);
3002
+ } catch (error2) {
3003
+ projectionFailure = error2;
3004
+ projectionFailed = true;
3005
+ }
3006
+ }
3007
+ if (projectionFailed) throw projectionFailure;
3008
+ return projection ?? null;
3009
+ } : void 0;
1323
3010
  Object.assign(
1324
3011
  observation,
1325
- errorDiagnostics(policy?.error ? error : reported, policy?.error)
3012
+ errorDiagnostics(policy?.error ? error : reported, project)
3013
+ );
3014
+ const diagnosticId = getHookContext().reasonTrace?.reportError?.(
3015
+ policy?.error ? error : reported,
3016
+ {
3017
+ mechanism: "tool",
3018
+ ...project ? { error: project } : {},
3019
+ correlation: {
3020
+ toolCallId: observation.toolCallId,
3021
+ attemptId: observation.attemptId
3022
+ }
3023
+ }
1326
3024
  );
3025
+ if (typeof diagnosticId === "string")
3026
+ observation.diagnosticId = diagnosticId;
1327
3027
  } catch {
1328
3028
  }
1329
3029
  }
@@ -7511,7 +9211,7 @@ function createInterruptDiscovery(store) {
7511
9211
 
7512
9212
  // src/telemetry/workflow-call-branch.ts
7513
9213
  var import_node_crypto3 = require("crypto");
7514
- var import_hooks = __toESM(require_dist());
9214
+ var import_hooks = __toESM(require_dist2());
7515
9215
  function restoreWorkflowCallBranch(requests, telemetry, sourceRunId) {
7516
9216
  const branchId = (0, import_node_crypto3.randomUUID)();
7517
9217
  const emitted = /* @__PURE__ */ new Set();