mesedi 0.1.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 (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -0
  3. package/dist/anthropic_integration.d.ts +52 -0
  4. package/dist/anthropic_integration.d.ts.map +1 -0
  5. package/dist/anthropic_integration.js +226 -0
  6. package/dist/anthropic_integration.js.map +1 -0
  7. package/dist/client.d.ts +99 -0
  8. package/dist/client.d.ts.map +1 -0
  9. package/dist/client.js +258 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/context.d.ts +63 -0
  12. package/dist/context.d.ts.map +1 -0
  13. package/dist/context.js +84 -0
  14. package/dist/context.js.map +1 -0
  15. package/dist/events.d.ts +95 -0
  16. package/dist/events.d.ts.map +1 -0
  17. package/dist/events.js +103 -0
  18. package/dist/events.js.map +1 -0
  19. package/dist/halt.d.ts +165 -0
  20. package/dist/halt.d.ts.map +1 -0
  21. package/dist/halt.js +229 -0
  22. package/dist/halt.js.map +1 -0
  23. package/dist/halt_stream.d.ts +77 -0
  24. package/dist/halt_stream.d.ts.map +1 -0
  25. package/dist/halt_stream.js +214 -0
  26. package/dist/halt_stream.js.map +1 -0
  27. package/dist/index.d.ts +41 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +34 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/integrations/vercel_ai.d.ts +120 -0
  32. package/dist/integrations/vercel_ai.d.ts.map +1 -0
  33. package/dist/integrations/vercel_ai.js +381 -0
  34. package/dist/integrations/vercel_ai.js.map +1 -0
  35. package/dist/observe.d.ts +50 -0
  36. package/dist/observe.d.ts.map +1 -0
  37. package/dist/observe.js +97 -0
  38. package/dist/observe.js.map +1 -0
  39. package/dist/tool.d.ts +27 -0
  40. package/dist/tool.d.ts.map +1 -0
  41. package/dist/tool.js +138 -0
  42. package/dist/tool.js.map +1 -0
  43. package/dist/wrap.d.ts +69 -0
  44. package/dist/wrap.d.ts.map +1 -0
  45. package/dist/wrap.js +168 -0
  46. package/dist/wrap.js.map +1 -0
  47. package/package.json +70 -0
package/dist/client.js ADDED
@@ -0,0 +1,258 @@
1
+ /**
2
+ * MesediClient — HTTP client + async event shipper for Node.
3
+ *
4
+ * Zero runtime dependencies: uses Node 18+ native `fetch` for HTTP
5
+ * and the event loop for async dispatch. No background threads (Node
6
+ * doesn't have them in the Python sense); instead a `setInterval`
7
+ * timer drains the queue periodically, and a `process.on("exit")`
8
+ * handler flushes any remaining items at shutdown.
9
+ *
10
+ * Auth: bearer token (`mesedi_sk_...`). Wire-format version pinned
11
+ * at "1" today; future breaking changes bump SCHEMA_VERSION and the
12
+ * backend tightens enforcement.
13
+ *
14
+ * Fail-open: every observation HTTP call wraps its promise in a
15
+ * try/catch — backend errors are logged via console.warn (configurable
16
+ * via a logger injection in a future polish slice) but NEVER bubble
17
+ * back to the wrapped agent code.
18
+ */
19
+ import { eventToWire, executionEndPayload, executionStartPayload, } from "./events.js";
20
+ export const DEFAULT_BASE_URL = "http://localhost:8080";
21
+ export const DEFAULT_TIMEOUT_MS = 10_000;
22
+ export const SCHEMA_VERSION = "1";
23
+ export class MesediClient {
24
+ apiKey;
25
+ baseUrl;
26
+ timeoutMs;
27
+ flushIntervalMs;
28
+ batchSize;
29
+ maxQueue;
30
+ queue = [];
31
+ pendingEvents = [];
32
+ lastFlush = Date.now();
33
+ droppedCount = 0;
34
+ stopped = false;
35
+ timer = null;
36
+ inflight = Promise.resolve();
37
+ constructor(opts) {
38
+ const apiKey = opts.apiKey ?? process.env["MESEDI_API_KEY"];
39
+ if (!apiKey) {
40
+ throw new Error("Mesedi API key not provided. Pass { apiKey: '...' } or set MESEDI_API_KEY in the environment.");
41
+ }
42
+ if (!apiKey.startsWith("mesedi_sk_")) {
43
+ // Mirror the backend's auth-middleware check — fail loudly on
44
+ // the SDK side rather than letting the backend return 401 on
45
+ // every call.
46
+ throw new Error("api_key must start with 'mesedi_sk_' (received an obviously-malformed key)");
47
+ }
48
+ this.apiKey = apiKey;
49
+ this.baseUrl = (opts.baseUrl ?? process.env["MESEDI_BASE_URL"] ?? DEFAULT_BASE_URL).replace(/\/$/, "");
50
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
51
+ this.flushIntervalMs = opts.flushIntervalMs ?? 250;
52
+ this.batchSize = opts.batchSize ?? 100;
53
+ this.maxQueue = opts.maxQueue ?? 10_000;
54
+ // Start the periodic flush timer. unref() so it doesn't keep the
55
+ // event loop alive on its own — the process can exit when the
56
+ // user's code is done, and our atexit handler drains anything left.
57
+ this.timer = setInterval(() => this.tick(), this.flushIntervalMs);
58
+ this.timer.unref();
59
+ // Atexit-equivalent: drain on graceful shutdown.
60
+ process.once("beforeExit", () => this.shutdown());
61
+ }
62
+ // ── producer-side API ────────────────────────────────────────────
63
+ submitExecutionStart(execution) {
64
+ this.enqueue({ kind: "create_execution", body: execution });
65
+ }
66
+ submitExecutionEnd(execution) {
67
+ this.enqueue({ kind: "update_execution", body: execution });
68
+ }
69
+ submitEvent(event) {
70
+ this.enqueue({ kind: "event", body: event });
71
+ }
72
+ /**
73
+ * Block-style: returns a promise that resolves when everything
74
+ * submitted SO FAR has been sent. Doesn't wait for items submitted
75
+ * after this call. Useful in tests and end-of-script sync.
76
+ */
77
+ flush(timeoutMs = 5_000) {
78
+ return new Promise((resolve) => {
79
+ const timer = setTimeout(() => resolve(false), timeoutMs);
80
+ this.enqueue({
81
+ kind: "barrier",
82
+ body: () => {
83
+ clearTimeout(timer);
84
+ resolve(true);
85
+ },
86
+ });
87
+ });
88
+ }
89
+ /**
90
+ * Stop the shipper. Drains queue with a short blocking sleep; any
91
+ * items not sent in time are lost.
92
+ */
93
+ async shutdown(timeoutMs = 5_000) {
94
+ if (this.stopped)
95
+ return;
96
+ this.stopped = true;
97
+ if (this.timer) {
98
+ clearInterval(this.timer);
99
+ this.timer = null;
100
+ }
101
+ await this.drainAll(timeoutMs);
102
+ }
103
+ // ── internals ────────────────────────────────────────────────────
104
+ enqueue(item) {
105
+ if (this.stopped) {
106
+ // Even after shutdown is invoked, the user's main code might
107
+ // continue running for a short tick. Best-effort: drop silently
108
+ // rather than throw — we're already past the contractual
109
+ // observation window.
110
+ return;
111
+ }
112
+ if (this.queue.length >= this.maxQueue) {
113
+ this.droppedCount++;
114
+ if (this.droppedCount === 1 || this.droppedCount % 100 === 0) {
115
+ console.warn(`mesedi: shipper queue full, dropped ${this.droppedCount} items so far`);
116
+ }
117
+ return;
118
+ }
119
+ this.queue.push(item);
120
+ }
121
+ /**
122
+ * Single tick of the shipper loop — called by setInterval. Drains
123
+ * the queue, dispatches non-event items, and flushes the pending-
124
+ * events batch if it's full OR the flush interval has elapsed.
125
+ */
126
+ async tick() {
127
+ if (this.queue.length === 0 && this.pendingEvents.length === 0)
128
+ return;
129
+ // Chain onto the previous tick's promise so we serialize HTTP
130
+ // calls — preserves ordering (POST /executions before PATCH for
131
+ // the same execution).
132
+ this.inflight = this.inflight.then(() => this.processOnce());
133
+ await this.inflight;
134
+ }
135
+ async processOnce() {
136
+ while (this.queue.length > 0) {
137
+ const item = this.queue.shift();
138
+ if (item.kind === "event") {
139
+ this.pendingEvents.push(item.body);
140
+ if (this.pendingEvents.length >= this.batchSize) {
141
+ await this.flushPendingEvents();
142
+ }
143
+ }
144
+ else {
145
+ // Non-event item — flush pending events first so the PATCH
146
+ // doesn't arrive before its preceding /events POST.
147
+ if (this.pendingEvents.length > 0) {
148
+ await this.flushPendingEvents();
149
+ }
150
+ if (item.kind === "create_execution") {
151
+ await this.sendCreateExecution(item.body);
152
+ }
153
+ else if (item.kind === "update_execution") {
154
+ await this.sendUpdateExecution(item.body);
155
+ }
156
+ else if (item.kind === "barrier") {
157
+ item.body();
158
+ }
159
+ }
160
+ }
161
+ // Time-based flush: if events have been waiting > flush interval,
162
+ // send them even if the batch isn't full.
163
+ if (this.pendingEvents.length > 0 &&
164
+ Date.now() - this.lastFlush >= this.flushIntervalMs) {
165
+ await this.flushPendingEvents();
166
+ }
167
+ }
168
+ async flushPendingEvents() {
169
+ if (this.pendingEvents.length === 0)
170
+ return;
171
+ const batch = this.pendingEvents.map(eventToWire);
172
+ this.pendingEvents = [];
173
+ this.lastFlush = Date.now();
174
+ await this.sendWithRetry("POST", "/events", batch, `send_events batch of ${batch.length}`);
175
+ }
176
+ async sendCreateExecution(e) {
177
+ await this.sendWithRetry("POST", "/executions", executionStartPayload(e), `create_execution ${e.execution_id}`);
178
+ }
179
+ async sendUpdateExecution(e) {
180
+ await this.sendWithRetry("PATCH", `/executions/${e.execution_id}`, executionEndPayload(e), `update_execution ${e.execution_id}`);
181
+ }
182
+ /**
183
+ * One HTTP call with up to 3 retries on transient failure
184
+ * (network errors, 5xx). 4xx responses drop with a warning — the
185
+ * request is malformed and retrying won't help.
186
+ */
187
+ async sendWithRetry(method, path, body, description) {
188
+ const backoffs = [100, 500, 2000];
189
+ let lastErr = null;
190
+ for (let attempt = 0; attempt <= backoffs.length; attempt++) {
191
+ try {
192
+ const controller = new AbortController();
193
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
194
+ const resp = await fetch(this.baseUrl + path, {
195
+ method,
196
+ headers: {
197
+ Authorization: `Bearer ${this.apiKey}`,
198
+ "Content-Type": "application/json",
199
+ "X-Mesedi-Schema-Version": SCHEMA_VERSION,
200
+ },
201
+ body: JSON.stringify(body),
202
+ signal: controller.signal,
203
+ });
204
+ clearTimeout(timer);
205
+ if (resp.status < 400)
206
+ return; // success
207
+ if (resp.status >= 400 && resp.status < 500) {
208
+ // Permanent failure — retrying won't help.
209
+ const text = await resp.text().catch(() => "");
210
+ console.warn(`mesedi: ${description} rejected with ${resp.status}: ${text.slice(0, 200)}`);
211
+ return;
212
+ }
213
+ lastErr = `HTTP ${resp.status}`;
214
+ }
215
+ catch (err) {
216
+ lastErr = err;
217
+ }
218
+ if (attempt < backoffs.length) {
219
+ await new Promise((r) => setTimeout(r, backoffs[attempt]));
220
+ }
221
+ }
222
+ console.warn(`mesedi: ${description} failed after ${backoffs.length + 1} attempts: ${String(lastErr)}`);
223
+ }
224
+ /**
225
+ * Drain everything currently queued with a deadline. Called from
226
+ * shutdown(). Returns once queue is empty or timeout elapses.
227
+ */
228
+ async drainAll(timeoutMs) {
229
+ const deadline = Date.now() + timeoutMs;
230
+ while ((this.queue.length > 0 || this.pendingEvents.length > 0) &&
231
+ Date.now() < deadline) {
232
+ await this.processOnce();
233
+ }
234
+ }
235
+ }
236
+ // ── module-level singleton (mirrors Python's mesedi.configure) ──────
237
+ let _defaultClient = null;
238
+ export function configure(opts = {}) {
239
+ if (_defaultClient) {
240
+ // shutdown previous client cleanly before replacing
241
+ _defaultClient.shutdown().catch(() => undefined);
242
+ }
243
+ _defaultClient = new MesediClient(opts);
244
+ return _defaultClient;
245
+ }
246
+ export function getClient() {
247
+ if (_defaultClient)
248
+ return _defaultClient;
249
+ // Auto-configure from env if MESEDI_API_KEY is set.
250
+ if (process.env["MESEDI_API_KEY"]) {
251
+ return configure();
252
+ }
253
+ throw new Error("Mesedi is not configured. Call configure({ apiKey: '...' }) or set MESEDI_API_KEY before using wrap()/tool().");
254
+ }
255
+ export async function flush(timeoutMs = 5_000) {
256
+ return getClient().flush(timeoutMs);
257
+ }
258
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAGL,WAAW,EACX,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AAErB,MAAM,CAAC,MAAM,gBAAgB,GAAG,uBAAuB,CAAC;AACxD,MAAM,CAAC,MAAM,kBAAkB,GAAG,MAAM,CAAC;AACzC,MAAM,CAAC,MAAM,cAAc,GAAG,GAAG,CAAC;AAkClC,MAAM,OAAO,YAAY;IACd,MAAM,CAAS;IACf,OAAO,CAAS;IAChB,SAAS,CAAS;IACV,eAAe,CAAS;IACxB,SAAS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extvars`.
4
+ *
5
+ * When `wrap()` is entered, it pushes a fresh `ExecutionContext`
6
+ * onto an AsyncLocalStorage instance. Inside the wrapped function
7
+ * (anywhere in the call tree, including across `await` boundaries),
8
+ * `tool()` and the (future) `checkpoint()` / `validatorResult()`
9
+ * helpers read the context to learn which execution to attach to.
10
+ *
11
+ * Why AsyncLocalStorage: it tracks "logical call context" across
12
+ * promise boundaries automatically — passing context through every
13
+ * await would be invasive and error-prone. AsyncLocalStorage is the
14
+ * Node-native way to do what Python contextvars does.
15
+ */
16
+ import { BudgetTracker } from "./halt.js";
17
+ export declare class ExecutionContext {
18
+ readonly executionId: string;
19
+ /**
20
+ * Optional budget tracker. Set when `wrap()` was invoked with a
21
+ * `budget` option; absent otherwise. The halt-safe boundary
22
+ * primitives (`tool()`, the Anthropic patch, `checkpoint()`) call
23
+ * `checkBudget()` at entry, which is a no-op when this is undefined.
24
+ */
25
+ readonly budgetTracker?: BudgetTracker;
26
+ private sequence;
27
+ constructor(executionId: string, budgetTracker?: BudgetTracker);
28
+ nextSequence(): number;
29
+ /**
30
+ * Halt-safe boundary check. Throws MesediHalt if a budget is
31
+ * exceeded; no-op if no budget is configured. Call this at the
32
+ * entry of any code path that's a natural halt boundary (start of
33
+ * a tool call, start of an LLM call, on a checkpoint).
34
+ */
35
+ checkBudget(): void;
36
+ }
37
+ /**
38
+ * Returns the currently-active execution context, or null if called
39
+ * outside any `wrap()`-decorated function.
40
+ */
41
+ export declare function currentExecutionContext(): ExecutionContext | null;
42
+ /**
43
+ * Runs `fn` inside a fresh execution context. The new context is
44
+ * automatically propagated through awaits inside `fn`. When `fn`
45
+ * resolves (or rejects), the previous context (which may be null)
46
+ * is restored.
47
+ *
48
+ * This is the workhorse `wrap()` calls internally.
49
+ */
50
+ export declare function runInExecutionContext<T>(executionId: string, fn: () => Promise<T>, budgetTracker?: BudgetTracker): Promise<T>;
51
+ /**
52
+ * Generate a fresh execution_id matching the Python SDK's format:
53
+ * `exec-<12 hex chars>`. UUID4-derived; the short-prefix variant is
54
+ * easier on the eyes in logs than a full UUID and collision-resistant
55
+ * at any plausible single-tenant scale.
56
+ */
57
+ export declare function newExecutionId(): string;
58
+ /**
59
+ * Generate a fresh event_id matching the Python SDK's format:
60
+ * `evt-<12 hex chars>`.
61
+ */
62
+ export declare function newEventId(): string;
63
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAE1C,qBAAa,gBAAgB;IAC3B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B;;;;;OAKG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,aAAa,CAAC;IACvC,OAAO,CAAC,QAAQ,CAAK;gBAET,WAAW,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,aAAa;IAK9D,YAAY,IAAI,MAAM;IAKtB;;;;;OAKG;IACH,WAAW,IAAI,IAAI;CAKpB;AAID;;;GAGG;AACH,wBAAgB,uBAAuB,IAAI,gBAAgB,GAAG,IAAI,CAEjE;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,EACrC,WAAW,EAAE,MAAM,EACnB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,aAAa,CAAC,EAAE,aAAa,GAC5B,OAAO,CAAC,CAAC,CAAC,CAGZ;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,IAAI,MAAM,CAEvC;AAED;;;GAGG;AACH,wBAAgB,UAAU,IAAI,MAAM,CAEnC"}
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Execution-context tracking using `AsyncLocalStorage` — Node's
3
+ * equivalent of Python's `contextvars`.
4
+ *
5
+ * When `wrap()` is entered, it pushes a fresh `ExecutionContext`
6
+ * onto an AsyncLocalStorage instance. Inside the wrapped function
7
+ * (anywhere in the call tree, including across `await` boundaries),
8
+ * `tool()` and the (future) `checkpoint()` / `validatorResult()`
9
+ * helpers read the context to learn which execution to attach to.
10
+ *
11
+ * Why AsyncLocalStorage: it tracks "logical call context" across
12
+ * promise boundaries automatically — passing context through every
13
+ * await would be invasive and error-prone. AsyncLocalStorage is the
14
+ * Node-native way to do what Python contextvars does.
15
+ */
16
+ import { AsyncLocalStorage } from "node:async_hooks";
17
+ import { randomUUID } from "node:crypto";
18
+ export class ExecutionContext {
19
+ executionId;
20
+ /**
21
+ * Optional budget tracker. Set when `wrap()` was invoked with a
22
+ * `budget` option; absent otherwise. The halt-safe boundary
23
+ * primitives (`tool()`, the Anthropic patch, `checkpoint()`) call
24
+ * `checkBudget()` at entry, which is a no-op when this is undefined.
25
+ */
26
+ budgetTracker;
27
+ sequence = 0;
28
+ constructor(executionId, budgetTracker) {
29
+ this.executionId = executionId;
30
+ this.budgetTracker = budgetTracker;
31
+ }
32
+ nextSequence() {
33
+ this.sequence += 1;
34
+ return this.sequence;
35
+ }
36
+ /**
37
+ * Halt-safe boundary check. Throws MesediHalt if a budget is
38
+ * exceeded; no-op if no budget is configured. Call this at the
39
+ * entry of any code path that's a natural halt boundary (start of
40
+ * a tool call, start of an LLM call, on a checkpoint).
41
+ */
42
+ checkBudget() {
43
+ if (this.budgetTracker) {
44
+ this.budgetTracker.check();
45
+ }
46
+ }
47
+ }
48
+ const storage = new AsyncLocalStorage();
49
+ /**
50
+ * Returns the currently-active execution context, or null if called
51
+ * outside any `wrap()`-decorated function.
52
+ */
53
+ export function currentExecutionContext() {
54
+ return storage.getStore() ?? null;
55
+ }
56
+ /**
57
+ * Runs `fn` inside a fresh execution context. The new context is
58
+ * automatically propagated through awaits inside `fn`. When `fn`
59
+ * resolves (or rejects), the previous context (which may be null)
60
+ * is restored.
61
+ *
62
+ * This is the workhorse `wrap()` calls internally.
63
+ */
64
+ export function runInExecutionContext(executionId, fn, budgetTracker) {
65
+ const ctx = new ExecutionContext(executionId, budgetTracker);
66
+ return storage.run(ctx, fn);
67
+ }
68
+ /**
69
+ * Generate a fresh execution_id matching the Python SDK's format:
70
+ * `exec-<12 hex chars>`. UUID4-derived; the short-prefix variant is
71
+ * easier on the eyes in logs than a full UUID and collision-resistant
72
+ * at any plausible single-tenant scale.
73
+ */
74
+ export function newExecutionId() {
75
+ return "exec-" + randomUUID().replace(/-/g, "").slice(0, 12);
76
+ }
77
+ /**
78
+ * Generate a fresh event_id matching the Python SDK's format:
79
+ * `evt-<12 hex chars>`.
80
+ */
81
+ export function newEventId() {
82
+ return "evt-" + randomUUID().replace(/-/g, "").slice(0, 12);
83
+ }
84
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,MAAM,OAAO,gBAAgB;IAClB,WAAW,CAAS;IAC7B;;;;;OAKG;IACM,aAAa,CAAiB;IAC/B,QAAQ,GAAG,CAAC,CAAC;IAErB,YAAY,WAAmB,EAAE,aAA6B;QAC5D,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACrC,CAAC;IAED,YAAY;QACV,IAAI,CAAC,QAAQ,IAAI,CAAC,CAAC;QACnB,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED;;;;;OAKG;IACH,WAAW;QACT,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;YACvB,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,CAAC;QAC7B,CAAC;IACH,CAAC;CACF;AAED,MAAM,OAAO,GAAG,IAAI,iBAAiB,EAAoB,CAAC;AAE1D;;;GAGG;AACH,MAAM,UAAU,uBAAuB;IACrC,OAAO,OAAO,CAAC,QAAQ,EAAE,IAAI,IAAI,CAAC;AACpC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,qBAAqB,CACnC,WAAmB,EACnB,EAAoB,EACpB,aAA6B;IAE7B,MAAM,GAAG,GAAG,IAAI,gBAAgB,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;IAC7D,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,cAAc;IAC5B,OAAO,OAAO,GAAG,UAAU,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAC/D,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,UAAU;IACxB,OAAO,MAAM,GAAG,UAAU,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAC9D,CAAC"}
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Event types and execution records — the TypeScript mirror of the Go
3
+ * backend's wire format and the Python SDK's data model.
4
+ *
5
+ * Source-of-truth lives in the Go backend at
6
+ * `backend/internal/events/types.go`. Any new EventType or Status
7
+ * added there MUST be added here too — strict-JSON decoding on the
8
+ * backend will reject events whose fields it doesn't recognize.
9
+ *
10
+ * The wire format uses RFC 3339 UTC timestamps for every time field.
11
+ */
12
+ /**
13
+ * RFC 3339 UTC timestamp with microsecond precision — the format the
14
+ * Go backend's time.Time RFC3339 marshaller accepts. Example:
15
+ * "2026-05-14T22:17:33.123456Z".
16
+ *
17
+ * JavaScript's `Date.prototype.toISOString()` produces millisecond
18
+ * precision; we pad to microseconds for byte-identical compatibility
19
+ * with the Python SDK's output (which uses Python's %f for
20
+ * microseconds).
21
+ */
22
+ export declare function utcNowRfc3339(): string;
23
+ /**
24
+ * Seven event types. Must match `EventType` constants in
25
+ * backend/internal/events/types.go exactly.
26
+ */
27
+ export declare const EventType: {
28
+ readonly LLM_CALL: "llm_call";
29
+ readonly TOOL_CALL: "tool_call";
30
+ readonly CHECKPOINT: "checkpoint";
31
+ readonly EXCEPTION: "exception";
32
+ readonly VALIDATOR_RESULT: "validator_result";
33
+ readonly DRIFT_SIGNAL: "drift_signal";
34
+ readonly INJECTION_ALERT: "injection_alert";
35
+ };
36
+ export type EventType = (typeof EventType)[keyof typeof EventType];
37
+ /**
38
+ * Execution lifecycle states. Must match `ExecutionStatus` constants
39
+ * in backend/internal/events/types.go exactly.
40
+ */
41
+ export declare const Status: {
42
+ readonly STARTED: "started";
43
+ readonly COMPLETED: "completed";
44
+ readonly CRASHED: "crashed";
45
+ readonly HALTED: "halted";
46
+ readonly TIMEOUT: "timeout";
47
+ readonly VALIDATION_FAILED: "validation_failed";
48
+ };
49
+ export type Status = (typeof Status)[keyof typeof Status];
50
+ /**
51
+ * An agent run as the Mesedi backend records it. Mirrors the Python
52
+ * SDK's `Execution` dataclass and the Go backend's struct.
53
+ */
54
+ export interface Execution {
55
+ execution_id: string;
56
+ status: Status;
57
+ started_at: string;
58
+ ended_at?: string;
59
+ duration_ms?: number;
60
+ total_tokens_in?: number;
61
+ total_tokens_out?: number;
62
+ estimated_cost_usd?: number;
63
+ sdk_language: "typescript";
64
+ sdk_version: string;
65
+ crash_signature?: string;
66
+ }
67
+ /**
68
+ * A single observation within an execution. Payload is opaque JSON —
69
+ * the backend stores it as a raw blob; per-event-type payload shapes
70
+ * are defined in the typed payload helpers below.
71
+ */
72
+ export interface Event {
73
+ event_id: string;
74
+ execution_id: string;
75
+ event_type: EventType;
76
+ sequence: number;
77
+ timestamp: string;
78
+ duration_ms?: number;
79
+ payload: Record<string, unknown>;
80
+ }
81
+ /**
82
+ * Build the body for POST /executions — only the fields valid at
83
+ * execution start.
84
+ */
85
+ export declare function executionStartPayload(e: Execution): Record<string, unknown>;
86
+ /**
87
+ * Build the body for PATCH /executions/{id} — omit any undefined
88
+ * fields so the backend's strict-decode doesn't reject them.
89
+ */
90
+ export declare function executionEndPayload(e: Execution): Record<string, unknown>;
91
+ /**
92
+ * Wire-format dict for POST /events (which accepts an array).
93
+ */
94
+ export declare function eventToWire(e: Event): Record<string, unknown>;
95
+ //# sourceMappingURL=events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH;;;;;;;;;GASG;AACH,wBAAgB,aAAa,IAAI,MAAM,CAMtC;AAED;;;GAGG;AACH,eAAO,MAAM,SAAS;;;;;;;;CAQZ,CAAC;AACX,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,SAAS,CAAC,CAAC,MAAM,OAAO,SAAS,CAAC,CAAC;AAEnE;;;GAGG;AACH,eAAO,MAAM,MAAM;;;;;;;CAOT,CAAC;AACX,MAAM,MAAM,MAAM,GAAG,CAAC,OAAO,MAAM,CAAC,CAAC,MAAM,OAAO,MAAM,CAAC,CAAC;AAE1D;;;GAGG;AACH,MAAM,WAAW,SAAS;IACxB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,YAAY,EAAE,YAAY,CAAC;IAC3B,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED;;;;GAIG;AACH,MAAM,WAAW,KAAK;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,SAAS,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,EAAE,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAQ3E;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CASzE;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAW7D"}
package/dist/events.js ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Event types and execution records — the TypeScript mirror of the Go
3
+ * backend's wire format and the Python SDK's data model.
4
+ *
5
+ * Source-of-truth lives in the Go backend at
6
+ * `backend/internal/events/types.go`. Any new EventType or Status
7
+ * added there MUST be added here too — strict-JSON decoding on the
8
+ * backend will reject events whose fields it doesn't recognize.
9
+ *
10
+ * The wire format uses RFC 3339 UTC timestamps for every time field.
11
+ */
12
+ /**
13
+ * RFC 3339 UTC timestamp with microsecond precision — the format the
14
+ * Go backend's time.Time RFC3339 marshaller accepts. Example:
15
+ * "2026-05-14T22:17:33.123456Z".
16
+ *
17
+ * JavaScript's `Date.prototype.toISOString()` produces millisecond
18
+ * precision; we pad to microseconds for byte-identical compatibility
19
+ * with the Python SDK's output (which uses Python's %f for
20
+ * microseconds).
21
+ */
22
+ export function utcNowRfc3339() {
23
+ const d = new Date();
24
+ // toISOString gives "...123Z" (millisecond precision). Strip the Z,
25
+ // add three zero-padded extra digits to reach microseconds, then
26
+ // re-attach Z. Matches the Python SDK formatter exactly.
27
+ return d.toISOString().replace(/Z$/, "000Z");
28
+ }
29
+ /**
30
+ * Seven event types. Must match `EventType` constants in
31
+ * backend/internal/events/types.go exactly.
32
+ */
33
+ export const EventType = {
34
+ LLM_CALL: "llm_call",
35
+ TOOL_CALL: "tool_call",
36
+ CHECKPOINT: "checkpoint",
37
+ EXCEPTION: "exception",
38
+ VALIDATOR_RESULT: "validator_result",
39
+ DRIFT_SIGNAL: "drift_signal",
40
+ INJECTION_ALERT: "injection_alert",
41
+ };
42
+ /**
43
+ * Execution lifecycle states. Must match `ExecutionStatus` constants
44
+ * in backend/internal/events/types.go exactly.
45
+ */
46
+ export const Status = {
47
+ STARTED: "started",
48
+ COMPLETED: "completed",
49
+ CRASHED: "crashed",
50
+ HALTED: "halted",
51
+ TIMEOUT: "timeout",
52
+ VALIDATION_FAILED: "validation_failed",
53
+ };
54
+ /**
55
+ * Build the body for POST /executions — only the fields valid at
56
+ * execution start.
57
+ */
58
+ export function executionStartPayload(e) {
59
+ return {
60
+ execution_id: e.execution_id,
61
+ status: e.status,
62
+ started_at: e.started_at,
63
+ sdk_language: e.sdk_language,
64
+ sdk_version: e.sdk_version,
65
+ };
66
+ }
67
+ /**
68
+ * Build the body for PATCH /executions/{id} — omit any undefined
69
+ * fields so the backend's strict-decode doesn't reject them.
70
+ */
71
+ export function executionEndPayload(e) {
72
+ const out = { status: e.status };
73
+ if (e.ended_at !== undefined)
74
+ out["ended_at"] = e.ended_at;
75
+ if (e.duration_ms !== undefined)
76
+ out["duration_ms"] = e.duration_ms;
77
+ if (e.total_tokens_in !== undefined)
78
+ out["total_tokens_in"] = e.total_tokens_in;
79
+ if (e.total_tokens_out !== undefined)
80
+ out["total_tokens_out"] = e.total_tokens_out;
81
+ if (e.estimated_cost_usd !== undefined)
82
+ out["estimated_cost_usd"] = e.estimated_cost_usd;
83
+ if (e.crash_signature !== undefined)
84
+ out["crash_signature"] = e.crash_signature;
85
+ return out;
86
+ }
87
+ /**
88
+ * Wire-format dict for POST /events (which accepts an array).
89
+ */
90
+ export function eventToWire(e) {
91
+ const out = {
92
+ event_id: e.event_id,
93
+ execution_id: e.execution_id,
94
+ event_type: e.event_type,
95
+ sequence: e.sequence,
96
+ timestamp: e.timestamp,
97
+ payload: e.payload,
98
+ };
99
+ if (e.duration_ms !== undefined)
100
+ out["duration_ms"] = e.duration_ms;
101
+ return out;
102
+ }
103
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH;;;;;;;;;GASG;AACH,MAAM,UAAU,aAAa;IAC3B,MAAM,CAAC,GAAG,IAAI,IAAI,EAAE,CAAC;IACrB,oEAAoE;IACpE,iEAAiE;IACjE,yDAAyD;IACzD,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC/C,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,QAAQ,EAAE,UAAU;IACpB,SAAS,EAAE,WAAW;IACtB,UAAU,EAAE,YAAY;IACxB,SAAS,EAAE,WAAW;IACtB,gBAAgB,EAAE,kBAAkB;IACpC,YAAY,EAAE,cAAc;IAC5B,eAAe,EAAE,iBAAiB;CAC1B,CAAC;AAGX;;;GAGG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB,OAAO,EAAE,SAAS;IAClB,SAAS,EAAE,WAAW;IACtB,OAAO,EAAE,SAAS;IAClB,MAAM,EAAE,QAAQ;IAChB,OAAO,EAAE,SAAS;IAClB,iBAAiB,EAAE,mBAAmB;CAC9B,CAAC;AAoCX;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,CAAY;IAChD,OAAO;QACL,YAAY,EAAE,CAAC,CAAC,YAAY;QAC5B,MAAM,EAAE,CAAC,CAAC,MAAM;QAChB,UAAU,EAAE,CAAC,CAAC,UAAU;QACxB,YAAY,EAAE,CAAC,CAAC,YAAY;QAC5B,WAAW,EAAE,CAAC,CAAC,WAAW;KAC3B,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,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