mesedi 0.2.0 → 0.7.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 (99) hide show
  1. package/README.md +57 -5
  2. package/dist/_errorClassesGenerated.d.ts +18 -0
  3. package/dist/_errorClassesGenerated.d.ts.map +1 -0
  4. package/dist/_errorClassesGenerated.js +24 -0
  5. package/dist/_errorClassesGenerated.js.map +1 -0
  6. package/dist/anthropic_integration.d.ts.map +1 -1
  7. package/dist/anthropic_integration.js +51 -10
  8. package/dist/anthropic_integration.js.map +1 -1
  9. package/dist/client.d.ts +26 -6
  10. package/dist/client.d.ts.map +1 -1
  11. package/dist/client.js +35 -7
  12. package/dist/client.js.map +1 -1
  13. package/dist/cohere_integration.d.ts +42 -0
  14. package/dist/cohere_integration.d.ts.map +1 -0
  15. package/dist/cohere_integration.js +456 -0
  16. package/dist/cohere_integration.js.map +1 -0
  17. package/dist/compress.d.ts +69 -0
  18. package/dist/compress.d.ts.map +1 -0
  19. package/dist/compress.js +75 -0
  20. package/dist/compress.js.map +1 -0
  21. package/dist/context.d.ts +11 -2
  22. package/dist/context.d.ts.map +1 -1
  23. package/dist/context.js +13 -3
  24. package/dist/context.js.map +1 -1
  25. package/dist/errors.d.ts +137 -0
  26. package/dist/errors.d.ts.map +1 -0
  27. package/dist/errors.js +462 -0
  28. package/dist/errors.js.map +1 -0
  29. package/dist/events.d.ts +13 -0
  30. package/dist/events.d.ts.map +1 -1
  31. package/dist/events.js +26 -1
  32. package/dist/events.js.map +1 -1
  33. package/dist/gemini_integration.d.ts +33 -0
  34. package/dist/gemini_integration.d.ts.map +1 -0
  35. package/dist/gemini_integration.js +334 -0
  36. package/dist/gemini_integration.js.map +1 -0
  37. package/dist/halt_stream.d.ts.map +1 -1
  38. package/dist/halt_stream.js +11 -1
  39. package/dist/halt_stream.js.map +1 -1
  40. package/dist/index.d.ts +15 -2
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +9 -1
  43. package/dist/index.js.map +1 -1
  44. package/dist/integrations/langchain.d.ts +95 -0
  45. package/dist/integrations/langchain.d.ts.map +1 -0
  46. package/dist/integrations/langchain.js +549 -0
  47. package/dist/integrations/langchain.js.map +1 -0
  48. package/dist/integrations/langgraph.d.ts +99 -0
  49. package/dist/integrations/langgraph.d.ts.map +1 -0
  50. package/dist/integrations/langgraph.js +572 -0
  51. package/dist/integrations/langgraph.js.map +1 -0
  52. package/dist/integrations/mastra.d.ts +114 -0
  53. package/dist/integrations/mastra.d.ts.map +1 -0
  54. package/dist/integrations/mastra.js +354 -0
  55. package/dist/integrations/mastra.js.map +1 -0
  56. package/dist/integrations/openai_agents.d.ts +66 -0
  57. package/dist/integrations/openai_agents.d.ts.map +1 -0
  58. package/dist/integrations/openai_agents.js +243 -0
  59. package/dist/integrations/openai_agents.js.map +1 -0
  60. package/dist/integrations/promptfoo.d.ts +62 -0
  61. package/dist/integrations/promptfoo.d.ts.map +1 -0
  62. package/dist/integrations/promptfoo.js +76 -0
  63. package/dist/integrations/promptfoo.js.map +1 -0
  64. package/dist/integrations/ragas.d.ts +65 -0
  65. package/dist/integrations/ragas.d.ts.map +1 -0
  66. package/dist/integrations/ragas.js +78 -0
  67. package/dist/integrations/ragas.js.map +1 -0
  68. package/dist/integrations/vectara.d.ts +60 -0
  69. package/dist/integrations/vectara.d.ts.map +1 -0
  70. package/dist/integrations/vectara.js +59 -0
  71. package/dist/integrations/vectara.js.map +1 -0
  72. package/dist/observe.d.ts +355 -0
  73. package/dist/observe.d.ts.map +1 -1
  74. package/dist/observe.js +532 -0
  75. package/dist/observe.js.map +1 -1
  76. package/dist/ollama_integration.d.ts +126 -0
  77. package/dist/ollama_integration.d.ts.map +1 -0
  78. package/dist/ollama_integration.js +404 -0
  79. package/dist/ollama_integration.js.map +1 -0
  80. package/dist/openai_integration.d.ts +67 -0
  81. package/dist/openai_integration.d.ts.map +1 -0
  82. package/dist/openai_integration.js +574 -0
  83. package/dist/openai_integration.js.map +1 -0
  84. package/dist/tool.d.ts.map +1 -1
  85. package/dist/tool.js +189 -6
  86. package/dist/tool.js.map +1 -1
  87. package/dist/truncate.d.ts +84 -0
  88. package/dist/truncate.d.ts.map +1 -0
  89. package/dist/truncate.js +134 -0
  90. package/dist/truncate.js.map +1 -0
  91. package/dist/vertex_gemini_integration.d.ts +27 -0
  92. package/dist/vertex_gemini_integration.d.ts.map +1 -0
  93. package/dist/vertex_gemini_integration.js +229 -0
  94. package/dist/vertex_gemini_integration.js.map +1 -0
  95. package/dist/wrap.d.ts +36 -0
  96. package/dist/wrap.d.ts.map +1 -1
  97. package/dist/wrap.js +5 -2
  98. package/dist/wrap.js.map +1 -1
  99. package/package.json +36 -3
package/dist/observe.js CHANGED
@@ -22,6 +22,11 @@ import { getClient } from "./client.js";
22
22
  import { currentExecutionContext, newEventId } from "./context.js";
23
23
  import { EventType, utcNowRfc3339 } from "./events.js";
24
24
  const MAX_VALIDATOR_MSG = 500;
25
+ // Granular-signature wave: customer-supplied validator category gets
26
+ // concatenated into the failure_group signature backend-side as
27
+ // "<name>:<category>". 80 chars matches the backend's
28
+ // signaturePartMaxLen helper; longer values are truncated client-side.
29
+ const MAX_VALIDATOR_CATEGORY = 80;
25
30
  /**
26
31
  * Emit a `checkpoint` event marking a notable point in execution.
27
32
  *
@@ -83,6 +88,12 @@ export function validatorResult(name, passed, opts = {}) {
83
88
  if (opts.message) {
84
89
  payload["message"] = opts.message.slice(0, MAX_VALIDATOR_MSG);
85
90
  }
91
+ if (opts.category) {
92
+ // Truncate client-side so the wire payload stays bounded;
93
+ // backend re-sanitizes (strips control chars + re-caps) as
94
+ // defense-in-depth.
95
+ payload["category"] = opts.category.slice(0, MAX_VALIDATOR_CATEGORY);
96
+ }
86
97
  const client = getClient();
87
98
  const event = {
88
99
  event_id: newEventId(),
@@ -94,4 +105,525 @@ export function validatorResult(name, passed, opts = {}) {
94
105
  };
95
106
  client.submitEvent(event);
96
107
  }
108
+ /**
109
+ * Canonical error_class values that signal per-tenant throttling — used
110
+ * by the instrument_* modules to decide whether to auto-emit an
111
+ * infrastructure_event alongside their failed llm_call event so the
112
+ * infrastructure_throttled detector picks up the pattern. Deliberately
113
+ * narrow: rate_limited and quota_exhausted are unambiguous throttling
114
+ * signals. Anthropic's OverloadedError (HTTP 529) is NOT here because
115
+ * the canonical error class set conflates it with service_unavailable
116
+ * (which also catches network outages and 5xx). A future wave that
117
+ * splits service_unavailable into separate classes can extend this
118
+ * set; for now we err toward false-negatives over false-positives.
119
+ */
120
+ const THROTTLING_ERROR_CLASSES = new Set([
121
+ "rate_limited",
122
+ "quota_exhausted",
123
+ ]);
124
+ const REASON_BY_ERROR_CLASS = {
125
+ rate_limited: "rate_limit",
126
+ quota_exhausted: "quota_exhausted",
127
+ };
128
+ /**
129
+ * If the canonical error_class is a throttling signal, emit an
130
+ * infrastructure_event alongside the failed llm_call so the backend's
131
+ * infrastructure_throttled detector picks up the per-tenant
132
+ * backpressure pattern. No-op for non-throttling errors. Internal
133
+ * helper used by the four instrument_* modules (anthropic, openai,
134
+ * cohere, gemini) so the throttling-class filter and reason mapping
135
+ * live in one place.
136
+ */
137
+ export function _maybeEmitThrottlingEvent(args) {
138
+ if (!THROTTLING_ERROR_CLASSES.has(args.errorClass))
139
+ return;
140
+ const reason = REASON_BY_ERROR_CLASS[args.errorClass] ?? args.errorClass;
141
+ const retryAfterMs = args.retryAfterSeconds && args.retryAfterSeconds > 0
142
+ ? Math.trunc(args.retryAfterSeconds * 1000)
143
+ : 0;
144
+ emitInfrastructureEvent(reason, {
145
+ provider: args.provider,
146
+ endpoint: args.endpoint,
147
+ statusCode: args.httpStatus,
148
+ retryAfterMs,
149
+ quotaDimension: args.quotaDimension,
150
+ });
151
+ }
152
+ /**
153
+ * Emit an `infrastructure_event` for transport-plane backpressure.
154
+ *
155
+ * Used when the SDK or caller observes an HTTP 429, hits a provider
156
+ * quota header, trips a local circuit breaker, or otherwise gets a
157
+ * signal from the network plane that the agent's logic is fine but
158
+ * the underlying infrastructure is pushing back. The Mesedi backend's
159
+ * `infrastructure_throttled` detector consumes these events and
160
+ * clusters them by (reason, provider, quota_dimension) so SRE teams
161
+ * get a single page per affected provider instead of one page per
162
+ * request.
163
+ *
164
+ * Typical caller pattern (Vercel AI SDK / OpenAI / Anthropic):
165
+ *
166
+ * try {
167
+ * const res = await fetch(endpoint, { method: "POST", body });
168
+ * if (res.status === 429) {
169
+ * emitInfrastructureEvent("rate_limit", {
170
+ * provider: "anthropic",
171
+ * endpoint: "/v1/messages",
172
+ * statusCode: 429,
173
+ * retryAfterMs: Number(
174
+ * res.headers.get("retry-after-ms") ?? 0,
175
+ * ),
176
+ * quotaDimension: "tokens_per_minute",
177
+ * quotaRemaining: Number(
178
+ * res.headers.get("x-ratelimit-remaining") ?? 0,
179
+ * ),
180
+ * });
181
+ * }
182
+ * } catch (err) {
183
+ * // ...
184
+ * }
185
+ *
186
+ * Outside `wrap()`: silent no-op. Mirrors the fail-open pattern of
187
+ * every other observe-layer primitive. The SDK does NOT retry on
188
+ * its own; emitting this event is purely observational.
189
+ */
190
+ export function emitInfrastructureEvent(reason, opts = {}) {
191
+ const ctx = currentExecutionContext();
192
+ if (!ctx)
193
+ return;
194
+ const payload = { event_type: reason };
195
+ if (opts.provider)
196
+ payload["provider"] = opts.provider;
197
+ if (opts.endpoint)
198
+ payload["endpoint"] = opts.endpoint;
199
+ if (opts.statusCode)
200
+ payload["status_code"] = Math.trunc(opts.statusCode);
201
+ if (opts.retryAfterMs)
202
+ payload["retry_after_ms"] = Math.trunc(opts.retryAfterMs);
203
+ if (opts.quotaRemaining)
204
+ payload["quota_remaining"] = Math.trunc(opts.quotaRemaining);
205
+ if (opts.quotaLimit)
206
+ payload["quota_limit"] = Math.trunc(opts.quotaLimit);
207
+ if (opts.quotaDimension)
208
+ payload["quota_dimension"] = opts.quotaDimension;
209
+ if (opts.backoffAppliedMs)
210
+ payload["backoff_applied_ms"] = Math.trunc(opts.backoffAppliedMs);
211
+ if (opts.circuitState)
212
+ payload["circuit_state"] = opts.circuitState;
213
+ const client = getClient();
214
+ const event = {
215
+ event_id: newEventId(),
216
+ execution_id: ctx.executionId,
217
+ event_type: EventType.INFRASTRUCTURE_EVENT,
218
+ sequence: ctx.nextSequence(),
219
+ timestamp: utcNowRfc3339(),
220
+ payload,
221
+ };
222
+ client.submitEvent(event);
223
+ }
224
+ /**
225
+ * Emit an `mcp_call` event for one Model Context Protocol server
226
+ * invocation.
227
+ *
228
+ * Use this when your agent talks to an MCP server (Anthropic's
229
+ * filesystem / github servers, a customer-hosted MCP server, etc.).
230
+ * The dashboard renders MCP calls in a distinct chip so cost
231
+ * attribution can break down by server identity, and the existing
232
+ * tool_failures detector picks up failed MCP calls when `error` or
233
+ * `errorClass` is non-empty.
234
+ *
235
+ * Outside `wrap()`: silent no-op.
236
+ */
237
+ export function emitMcpCall(serverName, method, opts = {}) {
238
+ const ctx = currentExecutionContext();
239
+ if (!ctx)
240
+ return;
241
+ const payload = {
242
+ server_name: serverName,
243
+ method,
244
+ };
245
+ if (opts.serverUrl)
246
+ payload["server_url"] = opts.serverUrl;
247
+ if (opts.arguments !== undefined)
248
+ payload["arguments"] = opts.arguments;
249
+ if (opts.returnValue !== undefined)
250
+ payload["return_value"] = opts.returnValue;
251
+ if (opts.latencyMs)
252
+ payload["latency_ms"] = Math.trunc(opts.latencyMs);
253
+ if (opts.error)
254
+ payload["error"] = opts.error;
255
+ if (opts.errorClass)
256
+ payload["error_class"] = opts.errorClass;
257
+ const client = getClient();
258
+ const event = {
259
+ event_id: newEventId(),
260
+ execution_id: ctx.executionId,
261
+ event_type: EventType.MCP_CALL,
262
+ sequence: ctx.nextSequence(),
263
+ timestamp: utcNowRfc3339(),
264
+ duration_ms: opts.latencyMs,
265
+ payload,
266
+ };
267
+ client.submitEvent(event);
268
+ }
269
+ /**
270
+ * Emit an `eval_score` event recording one external evaluator
271
+ * verdict on an execution's output.
272
+ *
273
+ * Use this when you run Ragas, Promptfoo, Vectara HHEM, or a custom
274
+ * judge against an execution's output and want Mesedi to track the
275
+ * score over time. Mesedi #14 aggregates these into
276
+ * grounding_failure clusters when scores trend below threshold.
277
+ *
278
+ * Outside `wrap()`: silent no-op.
279
+ */
280
+ export function emitEvalScore(evaluatorId, metricType, score, passed, opts = {}) {
281
+ const ctx = currentExecutionContext();
282
+ if (!ctx)
283
+ return;
284
+ const payload = {
285
+ evaluator_id: evaluatorId,
286
+ metric_type: metricType,
287
+ score,
288
+ passed,
289
+ higher_is_better: opts.higherIsBetter ?? true,
290
+ };
291
+ if (opts.threshold !== undefined)
292
+ payload["threshold"] = opts.threshold;
293
+ if (opts.reason)
294
+ payload["reason"] = opts.reason;
295
+ if (opts.confidence !== undefined)
296
+ payload["confidence"] = opts.confidence;
297
+ const client = getClient();
298
+ const event = {
299
+ event_id: newEventId(),
300
+ execution_id: ctx.executionId,
301
+ event_type: EventType.EVAL_SCORE,
302
+ sequence: ctx.nextSequence(),
303
+ timestamp: utcNowRfc3339(),
304
+ payload,
305
+ };
306
+ client.submitEvent(event);
307
+ }
308
+ /**
309
+ * Emit a `memory_operation` event for one external memory store
310
+ * read / write / search.
311
+ */
312
+ export function emitMemoryOperation(operation, opts = {}) {
313
+ const ctx = currentExecutionContext();
314
+ if (!ctx)
315
+ return;
316
+ const payload = { operation };
317
+ if (opts.storeType)
318
+ payload["store_type"] = opts.storeType;
319
+ if (opts.storeName)
320
+ payload["store_name"] = opts.storeName;
321
+ if (opts.query)
322
+ payload["query"] = opts.query.slice(0, 1000);
323
+ if (opts.documentCount)
324
+ payload["document_count"] = Math.trunc(opts.documentCount);
325
+ if (opts.tokenCount)
326
+ payload["token_count"] = Math.trunc(opts.tokenCount);
327
+ if (opts.topScore)
328
+ payload["top_score"] = opts.topScore;
329
+ if (opts.latencyMs)
330
+ payload["latency_ms"] = Math.trunc(opts.latencyMs);
331
+ if (opts.cacheHit)
332
+ payload["cache_hit"] = true;
333
+ if (opts.error)
334
+ payload["error"] = opts.error;
335
+ if (opts.errorClass)
336
+ payload["error_class"] = opts.errorClass;
337
+ const client = getClient();
338
+ const event = {
339
+ event_id: newEventId(),
340
+ execution_id: ctx.executionId,
341
+ event_type: EventType.MEMORY_OPERATION,
342
+ sequence: ctx.nextSequence(),
343
+ timestamp: utcNowRfc3339(),
344
+ duration_ms: opts.latencyMs,
345
+ payload,
346
+ };
347
+ client.submitEvent(event);
348
+ }
349
+ export function emitAgentHandoff(fromAgentOrArgs, maybeToAgent, maybeOpts = {}) {
350
+ // Normalize the two call shapes into (fromAgentRaw, toAgent, opts).
351
+ let fromAgentRaw;
352
+ let toAgent;
353
+ let opts;
354
+ if (typeof fromAgentOrArgs === "string") {
355
+ fromAgentRaw = fromAgentOrArgs;
356
+ toAgent = maybeToAgent ?? "";
357
+ opts = maybeOpts;
358
+ }
359
+ else {
360
+ const { fromAgent, toAgent: ta, ...rest } = fromAgentOrArgs;
361
+ fromAgentRaw = fromAgent;
362
+ toAgent = ta;
363
+ opts = rest;
364
+ }
365
+ const ctx = currentExecutionContext();
366
+ if (!ctx)
367
+ return;
368
+ // Resolve the effective source agent. Explicit wins; otherwise the
369
+ // wrap()'s agentName fallback. Missing both inside wrap() is a
370
+ // caller-side logic bug we surface loudly so the customer fixes it
371
+ // in dev rather than polluting the topology graph in prod.
372
+ const effectiveFrom = fromAgentRaw ?? ctx.agentName;
373
+ if (!effectiveFrom) {
374
+ throw new Error("emitAgentHandoff: no source agent identity available. " +
375
+ "Either pass fromAgent explicitly, or call " +
376
+ "wrap({ agentName: '...' }, fn).");
377
+ }
378
+ if (!toAgent) {
379
+ throw new Error("emitAgentHandoff: toAgent is required (cannot be empty).");
380
+ }
381
+ const payload = {
382
+ from_agent: effectiveFrom,
383
+ to_agent: toAgent,
384
+ };
385
+ if (opts.handoffKind)
386
+ payload["handoff_kind"] = opts.handoffKind;
387
+ if (opts.taskSummary)
388
+ payload["task_summary"] = opts.taskSummary.slice(0, 1000);
389
+ if (opts.childExecutionId)
390
+ payload["child_execution_id"] = opts.childExecutionId;
391
+ if (opts.latencyMs)
392
+ payload["latency_ms"] = Math.trunc(opts.latencyMs);
393
+ if (opts.error)
394
+ payload["error"] = opts.error;
395
+ if (opts.errorClass)
396
+ payload["error_class"] = opts.errorClass;
397
+ const client = getClient();
398
+ const event = {
399
+ event_id: newEventId(),
400
+ execution_id: ctx.executionId,
401
+ event_type: EventType.AGENT_HANDOFF,
402
+ sequence: ctx.nextSequence(),
403
+ timestamp: utcNowRfc3339(),
404
+ duration_ms: opts.latencyMs,
405
+ payload,
406
+ };
407
+ client.submitEvent(event);
408
+ }
409
+ /**
410
+ * Synchronously transition the current execution to
411
+ * `awaiting_human` (Mesedi #18).
412
+ *
413
+ * Call this from inside a `wrap()`-ed function at the moment the
414
+ * agent reaches a decision that requires a human in the loop. The
415
+ * backend records the pause timestamp, increments pause_count, and
416
+ * starts the HITL clock. A subsequent {@link resumeForAgent} call
417
+ * adds the elapsed time to total_paused_ms so a long HITL wait
418
+ * does not falsely trip the agent's time budget.
419
+ *
420
+ * The host application is responsible for actually blocking the
421
+ * agent until the human responds (typically the wrap()-ed function
422
+ * body itself awaits a queue / websocket / database row). This
423
+ * helper only updates Mesedi's lifecycle state; it does not block.
424
+ *
425
+ * Outside `wrap()`: no-op.
426
+ *
427
+ * Important: this is a SYNCHRONOUS PATCH (await) rather than the
428
+ * asynchronous shipper path that events take. The pause / resume
429
+ * transitions must be committed before the host application
430
+ * suspends the agent, so async-only delivery would race against
431
+ * the human responding.
432
+ */
433
+ export async function pauseForHuman() {
434
+ const ctx = currentExecutionContext();
435
+ if (!ctx)
436
+ return;
437
+ const client = getClient();
438
+ // Drain pending shipper traffic first so the POST /executions
439
+ // that opened this wrap() has landed on the backend. Without
440
+ // this, the synchronous PATCH races the async POST and
441
+ // returns 404 when pause is called immediately after the
442
+ // agent starts.
443
+ await client.flush(5_000);
444
+ const res = await fetch(`${client.baseUrl}/executions/${ctx.executionId}`, {
445
+ method: "PATCH",
446
+ headers: {
447
+ "Content-Type": "application/json",
448
+ Authorization: `Bearer ${client.apiKey}`,
449
+ },
450
+ body: JSON.stringify({ status: "awaiting_human" }),
451
+ });
452
+ if (!res.ok) {
453
+ const body = await res.text().catch(() => "");
454
+ throw new Error(`pauseForHuman: PATCH ${res.status} ${body}`);
455
+ }
456
+ }
457
+ /**
458
+ * Synchronously transition the current execution from
459
+ * `awaiting_human` back to `started` (Mesedi #18).
460
+ *
461
+ * Call this from the host application's HITL response handler the
462
+ * moment the human's decision lands and the agent is about to be
463
+ * unblocked. The backend computes the wait duration and adds it
464
+ * to total_paused_ms so the time-budget detector reads only the
465
+ * agent's actual working time.
466
+ *
467
+ * Outside `wrap()`: no-op.
468
+ */
469
+ export async function resumeForAgent() {
470
+ const ctx = currentExecutionContext();
471
+ if (!ctx)
472
+ return;
473
+ const client = getClient();
474
+ const res = await fetch(`${client.baseUrl}/executions/${ctx.executionId}`, {
475
+ method: "PATCH",
476
+ headers: {
477
+ "Content-Type": "application/json",
478
+ Authorization: `Bearer ${client.apiKey}`,
479
+ },
480
+ body: JSON.stringify({ status: "started" }),
481
+ });
482
+ if (!res.ok) {
483
+ const body = await res.text().catch(() => "");
484
+ throw new Error(`resumeForAgent: PATCH ${res.status} ${body}`);
485
+ }
486
+ }
487
+ /**
488
+ * Pause the current execution and return a handle (Mesedi #19).
489
+ *
490
+ * Synchronously transitions the execution into `awaiting_human`
491
+ * and returns a {@link HumanInterventionHandleData} carrying the
492
+ * correlation data needed to complete the cycle later. The host
493
+ * application is responsible for actually waiting on the human
494
+ * response (queue, websocket, DB poll) and then calling
495
+ * {@link completeHumanIntervention} with the answer.
496
+ *
497
+ * Outside `wrap()`: no-op, returns `null`.
498
+ *
499
+ * `slaSeconds` is optional metadata describing the customer's own
500
+ * SLA expectation. The hitl_timeout detector (#20) reads this to
501
+ * fire when the actual wait exceeds the configured SLA. Customers
502
+ * without an explicit SLA can omit it and #20 will fall back to a
503
+ * project-level default.
504
+ */
505
+ export async function requestHumanIntervention(question, options = {}) {
506
+ const ctx = currentExecutionContext();
507
+ if (!ctx)
508
+ return null;
509
+ const client = getClient();
510
+ const requestId = `hitl-${cryptoRandomId()}`;
511
+ const requestedAt = utcNowRfc3339();
512
+ // Drain pending shipper traffic so the POST /executions for
513
+ // this wrap() has landed. Without this, calling
514
+ // requestHumanIntervention immediately after the agent starts
515
+ // races the async POST and returns 404.
516
+ await client.flush(5_000);
517
+ const res = await fetch(`${client.baseUrl}/executions/${ctx.executionId}`, {
518
+ method: "PATCH",
519
+ headers: {
520
+ "Content-Type": "application/json",
521
+ Authorization: `Bearer ${client.apiKey}`,
522
+ },
523
+ body: JSON.stringify({ status: "awaiting_human" }),
524
+ });
525
+ if (!res.ok) {
526
+ const body = await res.text().catch(() => "");
527
+ throw new Error(`requestHumanIntervention: PATCH ${res.status} ${body}`);
528
+ }
529
+ return {
530
+ executionId: ctx.executionId,
531
+ requestId,
532
+ question,
533
+ slaSeconds: options.slaSeconds ?? 0,
534
+ requestedAt,
535
+ metadata: options.metadata,
536
+ };
537
+ }
538
+ /**
539
+ * Complete a HITL request (Mesedi #19).
540
+ *
541
+ * Emits the `human_intervention` event with the full ask/answer
542
+ * payload, then synchronously transitions the execution from
543
+ * `awaiting_human` back to `started` so the agent code can
544
+ * continue. Idempotent only insofar as a re-call from `started`
545
+ * is a no-op resume (the backend rejects illegal transitions).
546
+ */
547
+ export async function completeHumanIntervention(handle, opts) {
548
+ const client = getClient();
549
+ const decidedAtDate = new Date();
550
+ const decidedAt = decidedAtDate.toISOString();
551
+ let waitDurationMs = 0;
552
+ try {
553
+ const requestedAtDate = new Date(handle.requestedAt);
554
+ waitDurationMs = Math.max(0, decidedAtDate.getTime() - requestedAtDate.getTime());
555
+ }
556
+ catch {
557
+ waitDurationMs = 0;
558
+ }
559
+ const payload = {
560
+ request_id: handle.requestId,
561
+ question: handle.question,
562
+ requested_at: handle.requestedAt,
563
+ response_kind: opts.responseKind,
564
+ decided_at: decidedAt,
565
+ wait_duration_ms: waitDurationMs,
566
+ };
567
+ if (handle.slaSeconds > 0)
568
+ payload["sla_seconds"] = Math.trunc(handle.slaSeconds);
569
+ if (opts.responsePayload)
570
+ payload["response_payload"] = opts.responsePayload;
571
+ if (opts.decidedBy)
572
+ payload["decided_by"] = opts.decidedBy;
573
+ if (handle.metadata)
574
+ payload["metadata"] = handle.metadata;
575
+ // Send the human_intervention event synchronously so it lands
576
+ // before (or at worst at the same time as) the resume PATCH.
577
+ // The async shipper would risk losing it if the process exits
578
+ // immediately after resume.
579
+ const event = {
580
+ event_id: newEventId(),
581
+ execution_id: handle.executionId,
582
+ event_type: EventType.HUMAN_INTERVENTION,
583
+ sequence: 0,
584
+ timestamp: decidedAt,
585
+ duration_ms: waitDurationMs,
586
+ payload,
587
+ };
588
+ const eventsRes = await fetch(`${client.baseUrl}/events`, {
589
+ method: "POST",
590
+ headers: {
591
+ "Content-Type": "application/json",
592
+ Authorization: `Bearer ${client.apiKey}`,
593
+ },
594
+ body: JSON.stringify([event]),
595
+ });
596
+ if (!eventsRes.ok) {
597
+ const body = await eventsRes.text().catch(() => "");
598
+ throw new Error(`completeHumanIntervention event POST ${eventsRes.status} ${body}`);
599
+ }
600
+ // Resume the lifecycle.
601
+ const patchRes = await fetch(`${client.baseUrl}/executions/${handle.executionId}`, {
602
+ method: "PATCH",
603
+ headers: {
604
+ "Content-Type": "application/json",
605
+ Authorization: `Bearer ${client.apiKey}`,
606
+ },
607
+ body: JSON.stringify({ status: "started" }),
608
+ });
609
+ if (!patchRes.ok) {
610
+ const body = await patchRes.text().catch(() => "");
611
+ throw new Error(`completeHumanIntervention PATCH ${patchRes.status} ${body}`);
612
+ }
613
+ }
614
+ function cryptoRandomId() {
615
+ // Small helper for generating a 12-char hex correlation id. Uses
616
+ // Node's webcrypto when available; falls back to Math.random for
617
+ // older runtimes (still good enough for correlation, NOT for
618
+ // anything security-sensitive). Typed loose because the SDK
619
+ // targets both browser and Node runtimes and the tsconfig
620
+ // doesn't pull in the DOM lib.
621
+ const c = globalThis.crypto;
622
+ if (c && typeof c.getRandomValues === "function") {
623
+ const arr = new Uint8Array(6);
624
+ c.getRandomValues(arr);
625
+ return Array.from(arr).map((b) => b.toString(16).padStart(2, "0")).join("");
626
+ }
627
+ return Math.random().toString(16).slice(2, 14).padEnd(12, "0");
628
+ }
97
629
  //# sourceMappingURL=observe.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"observe.js","sourceRoot":"","sources":["../src/observe.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,uBAAuB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AACnE,OAAO,EAAS,SAAS,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE9D,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAE9B;;;;;;;;;;GAUG;AACH,MAAM,UAAU,UAAU,CACxB,IAAY,EACZ,WAAoC,EAAE;IAEtC,MAAM,GAAG,GAAG,uBAAuB,EAAE,CAAC;IACtC,IAAI,CAAC,GAAG;QAAE,OAAO;IAEjB,kEAAkE;IAClE,mEAAmE;IACnE,gEAAgE;IAChE,8DAA8D;IAC9D,GAAG,CAAC,WAAW,EAAE,CAAC;IAClB,IAAI,GAAG,CAAC,aAAa,EAAE,CAAC;QACtB,GAAG,CAAC,aAAa,CAAC,cAAc,EAAE,CAAC;IACrC,CAAC;IAED,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,KAAK,GAAU;QACnB,QAAQ,EAAE,UAAU,EAAE;QACtB,YAAY,EAAE,GAAG,CAAC,WAAW;QAC7B,UAAU,EAAE,SAAS,CAAC,UAAU;QAChC,QAAQ,EAAE,GAAG,CAAC,YAAY,EAAE;QAC5B,SAAS,EAAE,aAAa,EAAE;QAC1B,OAAO,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;KAC5B,CAAC;IACF,MAAM,CAAC,WAAW,CAAC,KAAK,CA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