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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Robert J. Canario
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,137 @@
1
+ # Mesedi TypeScript SDK
2
+
3
+ **Status:** Phase 11 alpha (v0.0.1). Local-only development; not yet on npm.
4
+
5
+ The TypeScript companion to `sdk-python/`. Feature parity for the v1
6
+ surface — `configure()`, `wrap()`, `tool()`, async event shipper,
7
+ fail-open posture — built on Node 18+ native `fetch` and
8
+ `AsyncLocalStorage`. **Zero runtime dependencies.**
9
+
10
+ ## Quickstart (local development)
11
+
12
+ Prerequisites: Mesedi backend running on `localhost:8080`. See
13
+ `../backend/README.md` if not yet running.
14
+
15
+ ```bash
16
+ cd ~/mesedi/sdk-typescript
17
+ npm install # installs only devDeps (TypeScript)
18
+ npm run build # compile src/ → dist/
19
+ node sandbox/real_agent.js
20
+ ```
21
+
22
+ Or run the sandbox in one shot:
23
+
24
+ ```bash
25
+ npm run test:sandbox
26
+ ```
27
+
28
+ ## API
29
+
30
+ ```typescript
31
+ import { configure, wrap, tool, flush } from "mesedi";
32
+
33
+ configure({
34
+ apiKey: "mesedi_sk_...",
35
+ baseUrl: "http://localhost:8080",
36
+ });
37
+
38
+ // Define a tool — observed when called from inside a wrap()'d function
39
+ const searchWeb = tool({ name: "search_web" }, async (q: string) => {
40
+ return ["result1", "result2"];
41
+ });
42
+
43
+ // Wrap an agent function — records start/complete/crash automatically
44
+ const runAgent = wrap(async (query: string) => {
45
+ const results = await searchWeb(query);
46
+ return `found ${results.length} results`;
47
+ });
48
+
49
+ await runAgent("pickleball");
50
+
51
+ // At end-of-script, flush any in-flight events:
52
+ await flush();
53
+ ```
54
+
55
+ ## What lands at the backend
56
+
57
+ For each `wrap()`-decorated call:
58
+
59
+ - **On entry:** `POST /executions` (status=started, sdk_language=typescript,
60
+ sdk_version=0.0.1).
61
+ - **On normal return:** `PATCH /executions/{id}` (status=completed,
62
+ duration_ms, ended_at).
63
+ - **On thrown error:** `PATCH /executions/{id}` (status=crashed,
64
+ crash_signature). The original error is then re-thrown with its
65
+ original stack.
66
+
67
+ For each `tool()`-decorated call (from inside a `wrap()`):
68
+
69
+ - `POST /events` with event_type=tool_call, sequence number from the
70
+ surrounding execution's context, payload includes tool_name +
71
+ sanitized args + status + result_summary (or exception fields).
72
+
73
+ All HTTP is async via a single in-process queue + a `setInterval`
74
+ drainer. Network failures during observation NEVER throw back into the
75
+ wrapped agent — the SDK is fail-open: a Mesedi outage degrades to
76
+ invisibility, not to broken production code.
77
+
78
+ ## Framework integrations
79
+
80
+ ### Vercel AI SDK
81
+
82
+ If your agent uses Vercel's `ai` package (`generateText`, multi-step
83
+ ReAct with `tools` + `maxSteps`), you don't have to wrap every tool by
84
+ hand. `wrapGenerateText` is a one-line higher-order function that
85
+ returns a drop-in replacement for `generateText` with Mesedi telemetry
86
+ side effects.
87
+
88
+ ```typescript
89
+ import { configure, wrap, flush } from "mesedi";
90
+ import { wrapGenerateText } from "mesedi/integrations/vercel_ai";
91
+ import { generateText } from "ai";
92
+ import { openai } from "@ai-sdk/openai";
93
+
94
+ configure({ apiKey: process.env.MESEDI_API_KEY! });
95
+
96
+ const generateTextM = wrapGenerateText(generateText);
97
+
98
+ export const runAgent = wrap(
99
+ { name: "support-triage" },
100
+ async (question: string) => {
101
+ const result = await generateTextM({
102
+ model: openai("gpt-4o"),
103
+ prompt: question,
104
+ tools: { lookup, search },
105
+ maxSteps: 5,
106
+ });
107
+ return result.text;
108
+ },
109
+ );
110
+ ```
111
+
112
+ Per invocation, the wrapper emits:
113
+
114
+ - One `llm_call` event per step (Vercel's multi-step ReAct surfaces
115
+ intermediate reasoning + final answer on `result.steps`). Model id,
116
+ user message, system prompt, token usage, response text — all
117
+ captured in the standard Mesedi wire format.
118
+ - One `tool_call` event per tool invocation in each step. Pairs
119
+ `result.toolCalls[i]` to `result.toolResults` by `toolCallId`,
120
+ detects failure mode (missing result OR `result.error` field) and
121
+ records `status=failed` with `exception_type` / `exception_message`.
122
+
123
+ Detectors — drift, identical / similar-call loops, tool-failures,
124
+ cost-velocity, prompt-injection — see the same wire format as a
125
+ hand-written `mesedi` instrumentation produces.
126
+
127
+ `ai` is declared as an **optional peer dependency** — installing
128
+ `mesedi` doesn't require it. If your project already has `ai`
129
+ installed for `generateText`, the integration just works.
130
+
131
+ `streamText` and `generateObject` ship in a later slice.
132
+
133
+ ## Posture
134
+
135
+ Same local-only posture as `sdk-python/`. npm publication via the
136
+ trusted-publishing flow ships post-LOI alongside the SDK ecosystem
137
+ work in Phase 16.
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Anthropic SDK monkey-patch — auto-emit llm_call events for every
3
+ * messages.create() call inside a wrap()'d execution.
4
+ *
5
+ * Activation is opt-in (call instrumentAnthropic() once at startup),
6
+ * matching the Python SDK and the Datadog/Sentry/OpenTelemetry
7
+ * pattern for observability instrumentation.
8
+ *
9
+ * What gets captured per call:
10
+ * - model (e.g. "claude-opus-4-6")
11
+ * - system_prompt — truncated to 1000 chars
12
+ * - user_message — the LAST user-role message, truncated to 1000
13
+ * - response_text — concatenated text-block content, truncated
14
+ * - input_tokens / output_tokens — from response.usage
15
+ * - duration_ms — wall-clock of the API call
16
+ * - status — "ok" / "failed"
17
+ * - exception_type + exception_message on failure
18
+ *
19
+ * Dependency injection: instrumentAnthropic accepts an optional
20
+ * `messagesClass` argument so this code path is testable without
21
+ * installing the actual `@anthropic-ai/sdk` package. Production
22
+ * callers pass the real Messages class; tests pass a hand-rolled
23
+ * fake.
24
+ */
25
+ /**
26
+ * Minimal duck-typed interfaces for the parts of the Anthropic SDK
27
+ * shape we depend on. Defined here so the SDK has zero direct
28
+ * dependency on @anthropic-ai/sdk — at runtime we just call .create()
29
+ * on whatever class was passed.
30
+ *
31
+ * `create` typed as `(...args: any[]) => Promise<any>` rather than a
32
+ * tighter signature because we monkey-patch external code whose
33
+ * shape varies across SDK versions and test doubles. This is the
34
+ * standard pattern for instrumentation libraries (cf. OpenTelemetry's
35
+ * patcher types). The runtime check is duck-typing on the args we
36
+ * actually read (model, system, messages).
37
+ */
38
+ export interface MessagesClassLike {
39
+ prototype: {
40
+ create: (...args: any[]) => Promise<any>;
41
+ };
42
+ }
43
+ /**
44
+ * Patch the given Messages class's `create()` method to emit
45
+ * llm_call events. Returns true on success or no-op (already
46
+ * patched). Returns false if no class was supplied and the
47
+ * @anthropic-ai/sdk package isn't installed (best-effort dynamic
48
+ * import — kept optional so the SDK stays dependency-free at install
49
+ * time).
50
+ */
51
+ export declare function instrumentAnthropic(messagesClass?: MessagesClassLike): Promise<boolean>;
52
+ //# sourceMappingURL=anthropic_integration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic_integration.d.ts","sourceRoot":"","sources":["../src/anthropic_integration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAgBH;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,iBAAiB;IAEhC,SAAS,EAAE;QAAE,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,CAAA;KAAE,CAAC;CACzD;AAkBD;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,CACvC,aAAa,CAAC,EAAE,iBAAiB,GAChC,OAAO,CAAC,OAAO,CAAC,CAkIlB"}
@@ -0,0 +1,226 @@
1
+ /**
2
+ * Anthropic SDK monkey-patch — auto-emit llm_call events for every
3
+ * messages.create() call inside a wrap()'d execution.
4
+ *
5
+ * Activation is opt-in (call instrumentAnthropic() once at startup),
6
+ * matching the Python SDK and the Datadog/Sentry/OpenTelemetry
7
+ * pattern for observability instrumentation.
8
+ *
9
+ * What gets captured per call:
10
+ * - model (e.g. "claude-opus-4-6")
11
+ * - system_prompt — truncated to 1000 chars
12
+ * - user_message — the LAST user-role message, truncated to 1000
13
+ * - response_text — concatenated text-block content, truncated
14
+ * - input_tokens / output_tokens — from response.usage
15
+ * - duration_ms — wall-clock of the API call
16
+ * - status — "ok" / "failed"
17
+ * - exception_type + exception_message on failure
18
+ *
19
+ * Dependency injection: instrumentAnthropic accepts an optional
20
+ * `messagesClass` argument so this code path is testable without
21
+ * installing the actual `@anthropic-ai/sdk` package. Production
22
+ * callers pass the real Messages class; tests pass a hand-rolled
23
+ * fake.
24
+ */
25
+ import { getClient } from "./client.js";
26
+ import { currentExecutionContext, newEventId } from "./context.js";
27
+ import { EventType, utcNowRfc3339 } from "./events.js";
28
+ const MAX_SYSTEM = 1000;
29
+ const MAX_USER_MSG = 1000;
30
+ const MAX_RESPONSE = 1000;
31
+ const MAX_EXC_MSG = 500;
32
+ /** Already-patched classes — keyed by class identity to make
33
+ * instrumentAnthropic() idempotent and to allow distinct fake classes
34
+ * to be patched in tests without falsely tripping the check. */
35
+ const _patched = new WeakSet();
36
+ /**
37
+ * Patch the given Messages class's `create()` method to emit
38
+ * llm_call events. Returns true on success or no-op (already
39
+ * patched). Returns false if no class was supplied and the
40
+ * @anthropic-ai/sdk package isn't installed (best-effort dynamic
41
+ * import — kept optional so the SDK stays dependency-free at install
42
+ * time).
43
+ */
44
+ export async function instrumentAnthropic(messagesClass) {
45
+ let cls = messagesClass;
46
+ if (!cls) {
47
+ try {
48
+ // Dynamic import so the SDK doesn't take a hard runtime
49
+ // dependency on @anthropic-ai/sdk. If the user has it
50
+ // installed, we auto-locate Messages; otherwise instrumentation
51
+ // is a no-op.
52
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
53
+ // @ts-ignore — the package may not be installed; this is by design
54
+ const mod = (await import("@anthropic-ai/sdk"));
55
+ cls = mod?.Anthropic?.Messages;
56
+ }
57
+ catch {
58
+ console.warn("mesedi: @anthropic-ai/sdk not installed; instrumentAnthropic() is a no-op. " +
59
+ "Install with `npm install @anthropic-ai/sdk` to enable, or pass the Messages class explicitly.");
60
+ return false;
61
+ }
62
+ if (!cls) {
63
+ console.warn("mesedi: located @anthropic-ai/sdk but couldn't find Anthropic.Messages — SDK version mismatch?");
64
+ return false;
65
+ }
66
+ }
67
+ if (_patched.has(cls))
68
+ return true;
69
+ const originalCreate = cls.prototype.create;
70
+ cls.prototype.create = async function patchedCreate(...args) {
71
+ const ctx = currentExecutionContext();
72
+ if (!ctx) {
73
+ // Outside wrap() — pass through unobserved.
74
+ return originalCreate.apply(this, args);
75
+ }
76
+ // Halt-safe boundary: check the budget BEFORE the actual LLM
77
+ // call. If a budget exists and is exceeded, this throws
78
+ // MesediHalt which propagates up to wrap()'s catch block. We
79
+ // count this as a step now (after the check passes) so the
80
+ // counter advances even though the LLM call hasn't run yet —
81
+ // matches the Python SDK's pattern (check, then count, then act).
82
+ ctx.checkBudget();
83
+ if (ctx.budgetTracker) {
84
+ ctx.budgetTracker.incrementSteps();
85
+ }
86
+ const client = getClient();
87
+ const sequence = ctx.nextSequence();
88
+ const eventId = newEventId();
89
+ const firstArg = (args[0] ?? {});
90
+ const model = firstArg.model ?? "unknown";
91
+ const system = firstArg.system ?? "";
92
+ const messages = Array.isArray(firstArg.messages) ? firstArg.messages : [];
93
+ const systemText = typeof system === "string" ? system : safeStringify(system);
94
+ const userMessage = extractLastUserMessage(messages);
95
+ const start = performance.now();
96
+ try {
97
+ const response = await originalCreate.apply(this, args);
98
+ const durationMs = Math.round(performance.now() - start);
99
+ const { responseText, inputTokens, outputTokens } = extractResponseFields(response);
100
+ // Token-budget accounting: feeds into BudgetTracker so future
101
+ // halt-safe boundary checks know how many tokens this execution
102
+ // has consumed. Tokens from FAILED LLM calls don't get
103
+ // accounted (we don't reach this code path on the error
104
+ // branch) — that matches the Python SDK behavior.
105
+ if (ctx.budgetTracker) {
106
+ ctx.budgetTracker.addTokens(inputTokens, outputTokens);
107
+ }
108
+ const event = {
109
+ event_id: eventId,
110
+ execution_id: ctx.executionId,
111
+ event_type: EventType.LLM_CALL,
112
+ sequence,
113
+ timestamp: utcNowRfc3339(),
114
+ duration_ms: durationMs,
115
+ payload: {
116
+ model,
117
+ system_prompt: truncate(systemText, MAX_SYSTEM),
118
+ user_message: truncate(userMessage, MAX_USER_MSG),
119
+ response_text: truncate(responseText, MAX_RESPONSE),
120
+ status: "ok",
121
+ input_tokens: inputTokens,
122
+ output_tokens: outputTokens,
123
+ },
124
+ };
125
+ client.submitEvent(event);
126
+ return response;
127
+ }
128
+ catch (err) {
129
+ const durationMs = Math.round(performance.now() - start);
130
+ const event = {
131
+ event_id: eventId,
132
+ execution_id: ctx.executionId,
133
+ event_type: EventType.LLM_CALL,
134
+ sequence,
135
+ timestamp: utcNowRfc3339(),
136
+ duration_ms: durationMs,
137
+ payload: {
138
+ model,
139
+ system_prompt: truncate(systemText, MAX_SYSTEM),
140
+ user_message: truncate(userMessage, MAX_USER_MSG),
141
+ status: "failed",
142
+ exception_type: err instanceof Error && err.constructor.name
143
+ ? err.constructor.name
144
+ : typeof err,
145
+ exception_message: truncate(err instanceof Error ? err.message : String(err), MAX_EXC_MSG),
146
+ },
147
+ };
148
+ client.submitEvent(event);
149
+ throw err;
150
+ }
151
+ };
152
+ _patched.add(cls);
153
+ return true;
154
+ }
155
+ function extractLastUserMessage(messages) {
156
+ if (!messages || messages.length === 0)
157
+ return "";
158
+ // Walk backwards to find the most recent user-role message.
159
+ for (let i = messages.length - 1; i >= 0; i--) {
160
+ const m = messages[i];
161
+ if (!m || m.role !== "user")
162
+ continue;
163
+ const content = m.content;
164
+ if (typeof content === "string")
165
+ return content;
166
+ if (Array.isArray(content)) {
167
+ const parts = [];
168
+ for (const block of content) {
169
+ if (block?.type === "text" && typeof block.text === "string") {
170
+ parts.push(block.text);
171
+ }
172
+ }
173
+ return parts.join("\n");
174
+ }
175
+ return safeStringify(content);
176
+ }
177
+ return "";
178
+ }
179
+ function extractResponseFields(response) {
180
+ let responseText = "";
181
+ let inputTokens = 0;
182
+ let outputTokens = 0;
183
+ try {
184
+ if (Array.isArray(response.content)) {
185
+ const parts = [];
186
+ for (const block of response.content) {
187
+ if (block && typeof block.text === "string")
188
+ parts.push(block.text);
189
+ }
190
+ responseText = parts.join("\n");
191
+ }
192
+ }
193
+ catch {
194
+ // best effort — leave responseText empty
195
+ }
196
+ try {
197
+ if (response.usage) {
198
+ inputTokens = Number(response.usage.input_tokens ?? 0) || 0;
199
+ outputTokens = Number(response.usage.output_tokens ?? 0) || 0;
200
+ }
201
+ }
202
+ catch {
203
+ // best effort — leave token counts at 0
204
+ }
205
+ return { responseText, inputTokens, outputTokens };
206
+ }
207
+ function safeStringify(v) {
208
+ if (v === undefined)
209
+ return "";
210
+ if (v === null)
211
+ return "";
212
+ if (typeof v === "string")
213
+ return v;
214
+ try {
215
+ return JSON.stringify(v);
216
+ }
217
+ catch {
218
+ return String(v);
219
+ }
220
+ }
221
+ function truncate(s, max) {
222
+ if (s.length <= max)
223
+ return s;
224
+ return s.slice(0, max - 3) + "...";
225
+ }
226
+ //# sourceMappingURL=anthropic_integration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic_integration.js","sourceRoot":"","sources":["../src/anthropic_integration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;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,UAAU,GAAG,IAAI,CAAC;AACxB,MAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,MAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,MAAM,WAAW,GAAG,GAAG,CAAC;AAExB;;gEAEgE;AAChE,MAAM,QAAQ,GAAG,IAAI,OAAO,EAAU,CAAC;AAoCvC;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACvC,aAAiC;IAEjC,IAAI,GAAG,GAAG,aAAa,CAAC;IACxB,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,IAAI,CAAC;YACH,wDAAwD;YACxD,sDAAsD;YACtD,gEAAgE;YAChE,cAAc;YACd,6DAA6D;YAC7D,mEAAmE;YACnE,MAAM,GAAG,GAAG,CAAC,MAAM,MAAM,CAAC,mBAAmB,CAAC,CAE7C,CAAC;YACF,GAAG,GAAG,GAAG,EAAE,SAAS,EAAE,QAAQ,CAAC;QACjC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,CAAC,IAAI,CACV,6EAA6E;gBAC3E,gGAAgG,CACnG,CAAC;YACF,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IAAI,CAAC,GAAG,EAAE,CAAC;YACT,OAAO,CAAC,IAAI,CACV,gGAAgG,CACjG,CAAC;YACF,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED,IAAI,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC;Q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yC;IAC3C,CAAC;IACD,IAAI,CAAC;QACH,IAAI,QAAQ,CAAC,KAAK,EAAE,CAAC;YACnB,WAAW,GAAG,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,YAAY,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC;YAC5D,YAAY,GAAG,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,aAAa,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC;QAChE,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,wCAAwC;IAC1C,CAAC;IACD,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,CAAC;AACrD,CAAC;AAED,SAAS,aAAa,CAAC,CAAU;IAC/B,IAAI,CAAC,KAAK,SAAS;QAAE,OAAO,EAAE,CAAC;IAC/B,IAAI,CAAC,KAAK,IAAI;QAAE,OAAO,EAAE,CAAC;IAC1B,IAAI,OAAO,CAAC,KAAK,QAAQ;QAAE,OAAO,CAAC,CAAC;IACpC,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IAC3B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC;IACnB,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,CAAS,EAAE,GAAW;IACtC,IAAI,CAAC,CAAC,MAAM,IAAI,GAAG;QAAE,OAAO,CAAC,CAAC;IAC9B,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC;AACrC,CAAC"}
@@ -0,0 +1,99 @@
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 { Event, Execution } from "./events.js";
20
+ export declare const DEFAULT_BASE_URL = "http://localhost:8080";
21
+ export declare const DEFAULT_TIMEOUT_MS = 10000;
22
+ export declare const SCHEMA_VERSION = "1";
23
+ /** Configuration accepted by `configure()`. */
24
+ export interface ConfigureOptions {
25
+ /**
26
+ * Bearer token (`mesedi_sk_...`). If omitted, the module reads
27
+ * `MESEDI_API_KEY` from `process.env`.
28
+ */
29
+ apiKey?: string;
30
+ /**
31
+ * Backend URL. Defaults to `MESEDI_BASE_URL` env var, then to
32
+ * "http://localhost:8080" for local dev.
33
+ */
34
+ baseUrl?: string;
35
+ /** Per-request timeout in milliseconds. Default 10s. */
36
+ timeoutMs?: number;
37
+ /** How often the shipper drains the queue. Default 250ms. */
38
+ flushIntervalMs?: number;
39
+ /** Max items per /events POST batch. Default 100. */
40
+ batchSize?: number;
41
+ /** Max queue depth before drop-on-full kicks in. Default 10_000. */
42
+ maxQueue?: number;
43
+ }
44
+ export declare class MesediClient {
45
+ readonly apiKey: string;
46
+ readonly baseUrl: string;
47
+ readonly timeoutMs: number;
48
+ private readonly flushIntervalMs;
49
+ private readonly batchSize;
50
+ private readonly maxQueue;
51
+ private queue;
52
+ private pendingEvents;
53
+ private lastFlush;
54
+ private droppedCount;
55
+ private stopped;
56
+ private timer;
57
+ private inflight;
58
+ constructor(opts: ConfigureOptions);
59
+ submitExecutionStart(execution: Execution): void;
60
+ submitExecutionEnd(execution: Execution): void;
61
+ submitEvent(event: Event): void;
62
+ /**
63
+ * Block-style: returns a promise that resolves when everything
64
+ * submitted SO FAR has been sent. Doesn't wait for items submitted
65
+ * after this call. Useful in tests and end-of-script sync.
66
+ */
67
+ flush(timeoutMs?: number): Promise<boolean>;
68
+ /**
69
+ * Stop the shipper. Drains queue with a short blocking sleep; any
70
+ * items not sent in time are lost.
71
+ */
72
+ shutdown(timeoutMs?: number): Promise<void>;
73
+ private enqueue;
74
+ /**
75
+ * Single tick of the shipper loop — called by setInterval. Drains
76
+ * the queue, dispatches non-event items, and flushes the pending-
77
+ * events batch if it's full OR the flush interval has elapsed.
78
+ */
79
+ private tick;
80
+ private processOnce;
81
+ private flushPendingEvents;
82
+ private sendCreateExecution;
83
+ private sendUpdateExecution;
84
+ /**
85
+ * One HTTP call with up to 3 retries on transient failure
86
+ * (network errors, 5xx). 4xx responses drop with a warning — the
87
+ * request is malformed and retrying won't help.
88
+ */
89
+ private sendWithRetry;
90
+ /**
91
+ * Drain everything currently queued with a deadline. Called from
92
+ * shutdown(). Returns once queue is empty or timeout elapses.
93
+ */
94
+ private drainAll;
95
+ }
96
+ export declare function configure(opts?: ConfigureOptions): MesediClient;
97
+ export declare function getClient(): MesediClient;
98
+ export declare function flush(timeoutMs?: number): Promise<boolean>;
99
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EACL,KAAK,EACL,SAAS,EAIV,MAAM,aAAa,CAAC;AAErB,eAAO,MAAM,gBAAgB,0BAA0B,CAAC;AACxD,eAAO,MAAM,kBAAkB,QAAS,CAAC;AACzC,eAAO,MAAM,cAAc,MAAM,CAAC;AAElC,+CAA+C;AAC/C,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wDAAwD;IACxD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,6DAA6D;IAC7D,e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