orchajs 0.27.3 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +31 -0
  2. package/dist/amarsia/analytics.d.ts +37 -3
  3. package/dist/amarsia/analytics.js +57 -5
  4. package/dist/cli-agents-template.d.ts +1 -1
  5. package/dist/cli-agents-template.js +9 -0
  6. package/dist/errors.d.ts +1 -0
  7. package/dist/errors.js +7 -0
  8. package/dist/index.d.ts +1 -1
  9. package/dist/index.js +1 -1
  10. package/dist/orcha.js +14 -8
  11. package/dist/providers/index.js +7 -1
  12. package/dist/runtime/agent.js +22 -9
  13. package/dist/runtime/create-orcha.js +15 -5
  14. package/dist/runtime/node-module-loader.d.ts +11 -0
  15. package/dist/runtime/node-module-loader.js +18 -0
  16. package/dist/runtime/structured-output.d.ts +1 -0
  17. package/dist/runtime/structured-output.js +10 -1
  18. package/dist/storage/create-store.js +1 -1
  19. package/dist/storage/node-sqlite-facade.d.ts +20 -0
  20. package/dist/storage/node-sqlite-facade.js +48 -0
  21. package/dist/telemetry/open-telemetry.d.ts +19 -0
  22. package/dist/telemetry/open-telemetry.js +630 -0
  23. package/dist/types.d.ts +13 -0
  24. package/dist-cjs/amarsia/analytics.js +60 -5
  25. package/dist-cjs/cli-agents-template.js +9 -0
  26. package/dist-cjs/errors.js +7 -0
  27. package/dist-cjs/index.js +2 -2
  28. package/dist-cjs/orcha.js +19 -8
  29. package/dist-cjs/providers/index.js +7 -1
  30. package/dist-cjs/runtime/agent.js +16 -9
  31. package/dist-cjs/runtime/create-orcha.js +12 -2
  32. package/dist-cjs/runtime/node-module-loader.js +42 -0
  33. package/dist-cjs/runtime/structured-output.js +12 -1
  34. package/dist-cjs/storage/create-store.js +2 -2
  35. package/dist-cjs/storage/node-sqlite-facade.js +72 -0
  36. package/dist-cjs/telemetry/open-telemetry.js +635 -0
  37. package/package.json +36 -4
@@ -0,0 +1,630 @@
1
+ const MAX_QUEUED_RUNS = 1_000;
2
+ const MAX_CONCURRENT_EXPORTS = 2;
3
+ export class CompositeRunTelemetryClient {
4
+ #clients;
5
+ constructor(clients) {
6
+ this.#clients = clients;
7
+ }
8
+ enqueue(fact, details) {
9
+ for (const client of this.#clients) {
10
+ try {
11
+ client.enqueue(fact, details);
12
+ }
13
+ catch (error) {
14
+ console.warn("A telemetry exporter rejected an Orcha run.", error);
15
+ }
16
+ }
17
+ }
18
+ updateActiveRun(fact) {
19
+ for (const client of this.#clients) {
20
+ try {
21
+ client.updateActiveRun(fact);
22
+ }
23
+ catch (error) {
24
+ console.warn("A telemetry exporter rejected an Orcha update.", error);
25
+ }
26
+ }
27
+ }
28
+ trackProjection(projection) {
29
+ for (const client of this.#clients)
30
+ client.trackProjection(projection);
31
+ }
32
+ async drain(options) {
33
+ await Promise.allSettled(this.#clients.map((client) => client.drain(options)));
34
+ }
35
+ async close(options) {
36
+ await Promise.allSettled(this.#clients.map((client) => client.close(options)));
37
+ }
38
+ }
39
+ export function createOpenTelemetryClient(configuration) {
40
+ return configuration === true
41
+ ? new GlobalOpenTelemetryClient()
42
+ : new OtlpHttpTelemetryClient(configuration);
43
+ }
44
+ class GlobalOpenTelemetryClient {
45
+ #pendingProjections = new Set();
46
+ #pendingEmissions = new Set();
47
+ #emissionChains = new Map();
48
+ #activeSpans = new Map();
49
+ enqueue(fact, details) {
50
+ const previous = this.#emissionChains.get(fact.event_id) ?? Promise.resolve();
51
+ const emission = previous
52
+ .then(() => this.#emit(fact, details))
53
+ .catch((error) => {
54
+ console.warn("OpenTelemetry global-provider delivery failed.", error);
55
+ });
56
+ this.#emissionChains.set(fact.event_id, emission);
57
+ this.#pendingEmissions.add(emission);
58
+ void emission.finally(() => {
59
+ this.#pendingEmissions.delete(emission);
60
+ if (this.#emissionChains.get(fact.event_id) === emission) {
61
+ this.#emissionChains.delete(fact.event_id);
62
+ }
63
+ });
64
+ }
65
+ async #emit(fact, details) {
66
+ const api = await loadOpenTelemetryApi();
67
+ const tracer = api.trace.getTracer("orchajs");
68
+ const active = this.#activeSpans.get(fact.event_id) ??
69
+ this.#startSpan(api, tracer, fact, details);
70
+ if (fact.status === "running")
71
+ return;
72
+ const { span, context: parentContext } = active;
73
+ span.setAttributes(runAttributes(fact));
74
+ for (const modelCall of details?.modelCalls ?? []) {
75
+ const modelSpan = tracer.startSpan(`chat ${modelCall.model}`, {
76
+ kind: api.SpanKind.CLIENT,
77
+ startTime: new Date(modelCall.started_at),
78
+ attributes: modelCallAttributes(fact, modelCall),
79
+ }, parentContext);
80
+ modelSpan.setStatus({ code: api.SpanStatusCode.OK });
81
+ modelSpan.end(new Date(modelCall.ended_at));
82
+ }
83
+ for (const action of fact.actions) {
84
+ const actionSpan = tracer.startSpan(`execute_tool ${action.name}`, {
85
+ kind: api.SpanKind.INTERNAL,
86
+ startTime: new Date(action.started_at),
87
+ attributes: {
88
+ "gen_ai.operation.name": "execute_tool",
89
+ "gen_ai.tool.name": action.name,
90
+ "gen_ai.tool.type": "function",
91
+ "gen_ai.tool.call.id": action.call_id,
92
+ "gen_ai.agent.name": fact.agent_external_id,
93
+ "gen_ai.conversation.id": fact.session_id,
94
+ "orcha.span.type": "action",
95
+ "orcha.action.call_id": action.call_id,
96
+ "orcha.action.duration_ms": action.duration_ms,
97
+ },
98
+ }, parentContext);
99
+ if (action.status === "failed") {
100
+ actionSpan.addEvent("exception", {
101
+ "exception.type": action.error_code ?? "action_error",
102
+ "exception.message": action.error_message ?? "Action failed",
103
+ });
104
+ actionSpan.setStatus({
105
+ code: api.SpanStatusCode.ERROR,
106
+ message: action.error_message,
107
+ });
108
+ if (action.error_code) {
109
+ actionSpan.setAttribute("error.type", action.error_code);
110
+ }
111
+ }
112
+ else {
113
+ actionSpan.setStatus({ code: api.SpanStatusCode.OK });
114
+ }
115
+ actionSpan.end(new Date(action.ended_at));
116
+ }
117
+ for (const event of evaluationResultEvents(fact)) {
118
+ span.addEvent(event.name, event.attributes, new Date(fact.ended_at ?? fact.started_at));
119
+ }
120
+ if (fact.status === "failed") {
121
+ span.addEvent("exception", {
122
+ "exception.type": fact.error_code ?? "agent_run_error",
123
+ "exception.message": fact.error_message ?? "Agent run failed",
124
+ });
125
+ span.setStatus({
126
+ code: api.SpanStatusCode.ERROR,
127
+ message: fact.error_message,
128
+ });
129
+ if (fact.error_code)
130
+ span.setAttribute("error.type", fact.error_code);
131
+ }
132
+ else {
133
+ span.setStatus({ code: api.SpanStatusCode.OK });
134
+ }
135
+ span.end(new Date(fact.ended_at ?? fact.started_at));
136
+ this.#activeSpans.delete(fact.event_id);
137
+ }
138
+ #startSpan(api, tracer, fact, details) {
139
+ const parent = parentEventId(fact, details);
140
+ const parentContext = parent
141
+ ? this.#activeSpans.get(parent)?.context
142
+ : undefined;
143
+ const span = tracer.startSpan(`invoke_agent ${fact.agent_external_id}`, {
144
+ kind: api.SpanKind.INTERNAL,
145
+ startTime: new Date(fact.started_at),
146
+ attributes: runAttributes(fact),
147
+ }, parentContext);
148
+ const active = {
149
+ api,
150
+ span,
151
+ context: api.trace.setSpan(parentContext ?? api.context.active(), span),
152
+ };
153
+ this.#activeSpans.set(fact.event_id, active);
154
+ return active;
155
+ }
156
+ updateActiveRun(_fact) { }
157
+ trackProjection(projection) {
158
+ this.#pendingProjections.add(projection);
159
+ void projection.finally(() => this.#pendingProjections.delete(projection));
160
+ }
161
+ async drain(options = {}) {
162
+ if (this.#pendingProjections.size === 0 &&
163
+ this.#pendingEmissions.size === 0) {
164
+ return;
165
+ }
166
+ await withTimeout(Promise.allSettled([
167
+ ...this.#pendingProjections,
168
+ ...this.#pendingEmissions,
169
+ ]).then(() => undefined), options.timeoutMs ?? 2_000);
170
+ }
171
+ async close(options) {
172
+ await this.drain(options);
173
+ for (const { api, span } of this.#activeSpans.values()) {
174
+ span.setAttributes({
175
+ "orcha.run.status": "interrupted",
176
+ "error.type": "process_shutdown",
177
+ });
178
+ span.addEvent("exception", {
179
+ "exception.type": "process_shutdown",
180
+ "exception.message": "Orcha closed before the agent run emitted a terminal event.",
181
+ });
182
+ span.setStatus({
183
+ code: api.SpanStatusCode.ERROR,
184
+ message: "Agent run interrupted by process shutdown",
185
+ });
186
+ span.end();
187
+ }
188
+ this.#activeSpans.clear();
189
+ }
190
+ }
191
+ class OtlpHttpTelemetryClient {
192
+ #endpoint;
193
+ #headers;
194
+ #queue = new Map();
195
+ #activeRuns = new Map();
196
+ #pendingProjections = new Set();
197
+ #inFlight = new Set();
198
+ #timer;
199
+ #attempt = 0;
200
+ #closed = false;
201
+ constructor(options) {
202
+ const endpoint = options.endpoint.trim().replace(/\/+$/, "");
203
+ if (!endpoint) {
204
+ throw new Error("telemetry.otel.endpoint must be a non-empty URL.");
205
+ }
206
+ this.#endpoint = endpoint.endsWith("/v1/traces")
207
+ ? endpoint
208
+ : `${endpoint}/v1/traces`;
209
+ this.#headers = options.headers ?? {};
210
+ }
211
+ enqueue(fact, details) {
212
+ if (this.#closed)
213
+ return;
214
+ if (fact.status === "running") {
215
+ this.#activeRuns.set(fact.event_id, { fact, details });
216
+ return;
217
+ }
218
+ this.#activeRuns.delete(fact.event_id);
219
+ if (!this.#queue.has(fact.event_id) &&
220
+ this.#queue.size >= MAX_QUEUED_RUNS) {
221
+ const oldest = this.#queue.keys().next().value;
222
+ if (oldest)
223
+ this.#queue.delete(oldest);
224
+ console.warn("OpenTelemetry queue is full; dropping the oldest queued run.");
225
+ }
226
+ this.#queue.set(fact.event_id, otlpSpans(fact, details));
227
+ if (this.#queue.size >= 20) {
228
+ void this.#flush();
229
+ }
230
+ else {
231
+ this.#schedule();
232
+ }
233
+ }
234
+ updateActiveRun(fact) {
235
+ const active = this.#activeRuns.get(fact.event_id);
236
+ if (active)
237
+ this.#activeRuns.set(fact.event_id, { ...active, fact });
238
+ }
239
+ trackProjection(projection) {
240
+ this.#pendingProjections.add(projection);
241
+ void projection.finally(() => this.#pendingProjections.delete(projection));
242
+ }
243
+ async drain(options = {}) {
244
+ const timeoutMs = Math.max(0, options.timeoutMs ?? 2_000);
245
+ const operation = (async () => {
246
+ await Promise.allSettled([...this.#pendingProjections]);
247
+ if (this.#timer) {
248
+ clearTimeout(this.#timer);
249
+ this.#timer = undefined;
250
+ }
251
+ while (this.#queue.size > 0) {
252
+ if (this.#inFlight.size >= MAX_CONCURRENT_EXPORTS) {
253
+ await Promise.allSettled([...this.#inFlight]);
254
+ }
255
+ const queuedBeforeFlush = this.#queue.size;
256
+ await this.#flush();
257
+ if (this.#queue.size >= queuedBeforeFlush)
258
+ break;
259
+ }
260
+ await Promise.allSettled([...this.#inFlight]);
261
+ })();
262
+ await withTimeout(operation, timeoutMs);
263
+ }
264
+ async close(options) {
265
+ const endedAt = new Date().toISOString();
266
+ for (const [eventId, active] of this.#activeRuns) {
267
+ this.#queue.set(eventId, otlpSpans({
268
+ ...active.fact,
269
+ status: "failed",
270
+ ended_at: endedAt,
271
+ duration_ms: Math.max(0, new Date(endedAt).getTime() -
272
+ new Date(active.fact.started_at).getTime()),
273
+ error_code: "process_shutdown",
274
+ error_message: "Orcha closed before the agent run emitted a terminal event.",
275
+ error_retryable: true,
276
+ }, active.details));
277
+ }
278
+ this.#activeRuns.clear();
279
+ await this.drain(options);
280
+ this.#closed = true;
281
+ if (this.#timer) {
282
+ clearTimeout(this.#timer);
283
+ this.#timer = undefined;
284
+ }
285
+ }
286
+ #schedule(delay = 250) {
287
+ if (this.#closed || this.#timer)
288
+ return;
289
+ this.#timer = setTimeout(() => {
290
+ this.#timer = undefined;
291
+ void this.#flush();
292
+ }, delay);
293
+ const timer = this.#timer;
294
+ timer.unref?.();
295
+ }
296
+ async #flush() {
297
+ if (this.#queue.size === 0)
298
+ return;
299
+ if (this.#inFlight.size >= MAX_CONCURRENT_EXPORTS) {
300
+ this.#schedule();
301
+ return;
302
+ }
303
+ const entries = [...this.#queue.entries()].slice(0, 20);
304
+ for (const [id] of entries)
305
+ this.#queue.delete(id);
306
+ const spans = entries.flatMap(([, value]) => value);
307
+ const body = JSON.stringify(otlpRequest(spans));
308
+ const operation = fetch(this.#endpoint, {
309
+ method: "POST",
310
+ headers: {
311
+ "content-type": "application/json",
312
+ ...this.#headers,
313
+ },
314
+ body,
315
+ keepalive: utf8ByteLength(body) <= 48 * 1024,
316
+ })
317
+ .then((response) => {
318
+ if (!response.ok)
319
+ throw new Error(`HTTP ${response.status}`);
320
+ this.#attempt = 0;
321
+ })
322
+ .catch((error) => {
323
+ this.#attempt += 1;
324
+ if (this.#attempt <= 6) {
325
+ for (const [id, value] of entries)
326
+ this.#queue.set(id, value);
327
+ this.#schedule(Math.min(30_000, 500 * 2 ** this.#attempt));
328
+ }
329
+ else {
330
+ this.#attempt = 0;
331
+ console.warn(`OpenTelemetry delivery failed after 6 retries; dropping ${entries.length} run(s).`, error);
332
+ }
333
+ });
334
+ this.#inFlight.add(operation);
335
+ try {
336
+ await operation;
337
+ }
338
+ finally {
339
+ this.#inFlight.delete(operation);
340
+ if (this.#queue.size > 0)
341
+ this.#schedule();
342
+ }
343
+ }
344
+ }
345
+ function runAttributes(fact) {
346
+ return {
347
+ "gen_ai.operation.name": "invoke_agent",
348
+ "gen_ai.agent.id": fact.agent_external_id,
349
+ "gen_ai.agent.name": fact.agent_external_id,
350
+ "gen_ai.provider.name": fact.provider,
351
+ "gen_ai.request.model": fact.model,
352
+ "gen_ai.conversation.id": fact.session_id,
353
+ "gen_ai.usage.input_tokens": fact.input_tokens,
354
+ "gen_ai.usage.output_tokens": fact.output_tokens,
355
+ "orcha.run.number": fact.run_number,
356
+ "orcha.run.status": fact.status,
357
+ "orcha.span.type": "agent_run",
358
+ "orcha.agent.id": fact.agent_external_id,
359
+ "orcha.session.id": fact.session_id,
360
+ "orcha.run.duration_ms": fact.duration_ms ?? 0,
361
+ "orcha.run.model_duration_ms": fact.model_duration_ms,
362
+ "orcha.run.action_duration_ms": fact.action_duration_ms,
363
+ "orcha.usage.reasoning_tokens": fact.reasoning_tokens ?? 0,
364
+ "orcha.usage.cache_read_tokens": fact.cache_read_tokens,
365
+ "orcha.usage.cache_write_tokens": fact.cache_write_tokens,
366
+ "orcha.action.count": fact.action_count,
367
+ "orcha.action.success_count": fact.action_success_count,
368
+ "orcha.action.failure_count": fact.action_failure_count,
369
+ "orcha.subagent.count": fact.subagent_count,
370
+ "orcha.evaluation.count": fact.evaluation_count,
371
+ ...(fact.parent_agent_external_id
372
+ ? { "orcha.parent.agent_id": fact.parent_agent_external_id }
373
+ : {}),
374
+ ...(fact.parent_session_id
375
+ ? { "orcha.parent.session_id": fact.parent_session_id }
376
+ : {}),
377
+ ...(fact.stop_reason
378
+ ? { "gen_ai.response.finish_reasons": [fact.stop_reason] }
379
+ : {}),
380
+ };
381
+ }
382
+ function modelCallAttributes(fact, modelCall) {
383
+ return {
384
+ "gen_ai.operation.name": "chat",
385
+ "gen_ai.provider.name": modelCall.provider,
386
+ "gen_ai.request.model": modelCall.model,
387
+ "gen_ai.response.model": modelCall.model,
388
+ "gen_ai.conversation.id": fact.session_id,
389
+ "gen_ai.agent.name": fact.agent_external_id,
390
+ "gen_ai.usage.input_tokens": modelCall.input_tokens,
391
+ "gen_ai.usage.output_tokens": modelCall.output_tokens,
392
+ "orcha.usage.reasoning_tokens": modelCall.reasoning_tokens,
393
+ "orcha.usage.cache_read_tokens": modelCall.cache_read_tokens,
394
+ "orcha.usage.cache_write_tokens": modelCall.cache_write_tokens,
395
+ "orcha.model.duration_ms": modelCall.duration_ms,
396
+ ...(modelCall.response_id
397
+ ? { "gen_ai.response.id": modelCall.response_id }
398
+ : {}),
399
+ ...(modelCall.finish_reason
400
+ ? { "gen_ai.response.finish_reasons": [modelCall.finish_reason] }
401
+ : {}),
402
+ };
403
+ }
404
+ function evaluationResultEvents(fact) {
405
+ const events = [];
406
+ for (const evaluation of fact.evaluations) {
407
+ if (evaluation.metrics.length === 0) {
408
+ events.push({
409
+ name: "gen_ai.evaluation.result",
410
+ attributes: {
411
+ "gen_ai.evaluation.name": evaluation.name,
412
+ "gen_ai.evaluation.score.label": evaluation.status,
413
+ "orcha.evaluation.duration_ms": evaluation.duration_ms,
414
+ ...(evaluation.error_message
415
+ ? {
416
+ "error.type": "evaluation_error",
417
+ "orcha.evaluation.error_message": evaluation.error_message,
418
+ }
419
+ : {}),
420
+ },
421
+ });
422
+ continue;
423
+ }
424
+ for (const metric of evaluation.metrics) {
425
+ events.push({
426
+ name: "gen_ai.evaluation.result",
427
+ attributes: {
428
+ "gen_ai.evaluation.name": metric.name,
429
+ "gen_ai.evaluation.score.value": metric.score,
430
+ "gen_ai.evaluation.score.label": metric.passed ? "pass" : "fail",
431
+ "gen_ai.evaluation.explanation": metric.reasoning,
432
+ "orcha.evaluation.name": evaluation.name,
433
+ "orcha.evaluation.duration_ms": evaluation.duration_ms,
434
+ ...(metric.evidence.length > 0
435
+ ? { "orcha.evaluation.evidence": metric.evidence }
436
+ : {}),
437
+ },
438
+ });
439
+ }
440
+ }
441
+ return events;
442
+ }
443
+ function otlpSpans(fact, details) {
444
+ const rootSessionId = details?.lineage?.rootSessionId ??
445
+ fact.parent_session_id ??
446
+ fact.session_id;
447
+ const rootRunNumber = details?.lineage?.rootRunNumber ??
448
+ details?.lineage?.parentRunNumber ??
449
+ fact.run_number;
450
+ const traceId = stableHex(`trace:${rootSessionId}:${rootRunNumber}`, 32);
451
+ const rootSpanId = stableHex(`span:${fact.event_id}`, 16);
452
+ const parentId = parentEventId(fact, details);
453
+ const root = {
454
+ traceId,
455
+ spanId: rootSpanId,
456
+ ...(parentId
457
+ ? { parentSpanId: stableHex(`span:${parentId}`, 16) }
458
+ : {}),
459
+ name: `invoke_agent ${fact.agent_external_id}`,
460
+ kind: 1,
461
+ startTimeUnixNano: unixNanos(fact.started_at),
462
+ endTimeUnixNano: unixNanos(fact.ended_at ?? fact.started_at),
463
+ attributes: otlpAttributes(runAttributes(fact)),
464
+ events: [
465
+ ...evaluationResultEvents(fact).map((event) => ({
466
+ timeUnixNano: unixNanos(fact.ended_at ?? fact.started_at),
467
+ name: event.name,
468
+ attributes: otlpAttributes(event.attributes),
469
+ })),
470
+ ...(fact.status === "failed"
471
+ ? [
472
+ {
473
+ timeUnixNano: unixNanos(fact.ended_at ?? fact.started_at),
474
+ name: "exception",
475
+ attributes: otlpAttributes({
476
+ "exception.type": fact.error_code ?? "agent_run_error",
477
+ "exception.message": fact.error_message ?? "Agent run failed",
478
+ }),
479
+ },
480
+ ]
481
+ : []),
482
+ ],
483
+ status: fact.status === "failed"
484
+ ? { code: 2, message: fact.error_message }
485
+ : { code: 1 },
486
+ };
487
+ const modelCalls = (details?.modelCalls ?? []).map((modelCall, index) => ({
488
+ traceId,
489
+ spanId: stableHex(`model:${fact.event_id}:${index}`, 16),
490
+ parentSpanId: rootSpanId,
491
+ name: `chat ${modelCall.model}`,
492
+ kind: 3,
493
+ startTimeUnixNano: unixNanos(modelCall.started_at),
494
+ endTimeUnixNano: unixNanos(modelCall.ended_at),
495
+ attributes: otlpAttributes(modelCallAttributes(fact, modelCall)),
496
+ status: { code: 1 },
497
+ }));
498
+ const actions = fact.actions.map((action) => ({
499
+ traceId,
500
+ spanId: stableHex(`action:${fact.event_id}:${action.call_id}`, 16),
501
+ parentSpanId: rootSpanId,
502
+ name: `execute_tool ${action.name}`,
503
+ kind: 1,
504
+ startTimeUnixNano: unixNanos(action.started_at),
505
+ endTimeUnixNano: unixNanos(action.ended_at),
506
+ attributes: otlpAttributes({
507
+ "gen_ai.operation.name": "execute_tool",
508
+ "gen_ai.tool.name": action.name,
509
+ "gen_ai.tool.type": "function",
510
+ "gen_ai.tool.call.id": action.call_id,
511
+ "gen_ai.agent.name": fact.agent_external_id,
512
+ "gen_ai.conversation.id": fact.session_id,
513
+ "orcha.span.type": "action",
514
+ "orcha.action.call_id": action.call_id,
515
+ "orcha.action.duration_ms": action.duration_ms,
516
+ ...(action.error_code ? { "error.type": action.error_code } : {}),
517
+ }),
518
+ events: action.status === "failed"
519
+ ? [
520
+ {
521
+ timeUnixNano: unixNanos(action.ended_at),
522
+ name: "exception",
523
+ attributes: otlpAttributes({
524
+ "exception.type": action.error_code ?? "action_error",
525
+ "exception.message": action.error_message ?? "Action failed",
526
+ }),
527
+ },
528
+ ]
529
+ : undefined,
530
+ status: action.status === "failed"
531
+ ? { code: 2, message: action.error_message }
532
+ : { code: 1 },
533
+ }));
534
+ return [root, ...modelCalls, ...actions];
535
+ }
536
+ function parentEventId(fact, details) {
537
+ if (!fact.parent_agent_external_id ||
538
+ !fact.parent_session_id ||
539
+ !details?.lineage?.parentRunNumber) {
540
+ return undefined;
541
+ }
542
+ return `${fact.parent_agent_external_id}:${fact.parent_session_id}:${details.lineage.parentRunNumber}`;
543
+ }
544
+ function otlpRequest(spans) {
545
+ return {
546
+ resourceSpans: [
547
+ {
548
+ resource: {
549
+ attributes: otlpAttributes({
550
+ "service.name": "orchajs",
551
+ "telemetry.sdk.language": "nodejs",
552
+ }),
553
+ },
554
+ scopeSpans: [
555
+ {
556
+ scope: { name: "orchajs" },
557
+ spans,
558
+ },
559
+ ],
560
+ },
561
+ ],
562
+ };
563
+ }
564
+ function otlpAttributes(attributes) {
565
+ const output = [];
566
+ for (const [key, value] of Object.entries(attributes)) {
567
+ if (value === undefined || value === null)
568
+ continue;
569
+ if (Array.isArray(value)) {
570
+ output.push({
571
+ key,
572
+ value: {
573
+ arrayValue: {
574
+ values: value.map((item) => ({ stringValue: String(item) })),
575
+ },
576
+ },
577
+ });
578
+ }
579
+ else if (typeof value === "string") {
580
+ output.push({ key, value: { stringValue: value } });
581
+ }
582
+ else if (typeof value === "boolean") {
583
+ output.push({ key, value: { boolValue: value } });
584
+ }
585
+ else if (typeof value === "number") {
586
+ output.push({
587
+ key,
588
+ value: Number.isInteger(value)
589
+ ? { intValue: String(value) }
590
+ : { doubleValue: value },
591
+ });
592
+ }
593
+ }
594
+ return output;
595
+ }
596
+ function unixNanos(value) {
597
+ return (BigInt(new Date(value).getTime()) * 1000000n).toString();
598
+ }
599
+ function stableHex(value, length) {
600
+ let first = 0xcbf29ce484222325n;
601
+ let second = 0x84222325cbf29ce4n;
602
+ for (let index = 0; index < value.length; index += 1) {
603
+ const code = BigInt(value.charCodeAt(index));
604
+ first = BigInt.asUintN(64, (first ^ code) * 0x100000001b3n);
605
+ second = BigInt.asUintN(64, (second ^ (code + 31n)) * 0x100000001b3n);
606
+ }
607
+ return `${first.toString(16).padStart(16, "0")}${second
608
+ .toString(16)
609
+ .padStart(16, "0")}`.slice(0, length);
610
+ }
611
+ async function withTimeout(operation, timeoutMs) {
612
+ if (timeoutMs <= 0)
613
+ return;
614
+ await Promise.race([
615
+ operation,
616
+ new Promise((resolve) => setTimeout(resolve, timeoutMs)),
617
+ ]);
618
+ }
619
+ function utf8ByteLength(value) {
620
+ if (typeof TextEncoder !== "undefined") {
621
+ return new TextEncoder().encode(value).byteLength;
622
+ }
623
+ return value.length;
624
+ }
625
+ let openTelemetryApiPromise;
626
+ function loadOpenTelemetryApi() {
627
+ openTelemetryApiPromise ??= runtimeImport("@opentelemetry/api");
628
+ return openTelemetryApiPromise;
629
+ }
630
+ const runtimeImport = new Function("specifier", "return import(specifier)");
package/dist/types.d.ts CHANGED
@@ -71,6 +71,16 @@ export interface OrchaInitConfiguration {
71
71
  endpoint?: string;
72
72
  inference?: boolean;
73
73
  };
74
+ telemetry?: {
75
+ /**
76
+ * `true` uses the application's global OpenTelemetry provider.
77
+ * An endpoint sends OTLP/HTTP JSON directly to that collector.
78
+ */
79
+ otel?: true | {
80
+ endpoint: string;
81
+ headers?: Record<string, string>;
82
+ };
83
+ };
74
84
  actions?: LocalActionRuntimeConfiguration;
75
85
  mcp?: ProjectConfiguration["mcp"];
76
86
  storage?: ProjectConfiguration["storage"];
@@ -438,6 +448,9 @@ export interface SessionLineage {
438
448
  parentAgent: string;
439
449
  parentSessionId: string;
440
450
  parentCallId: string;
451
+ parentRunNumber?: number;
452
+ rootSessionId?: string;
453
+ rootRunNumber?: number;
441
454
  }
442
455
  export interface SessionSnapshot {
443
456
  sessionId: string;