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.
- package/LICENSE +21 -0
- package/README.md +137 -0
- package/dist/anthropic_integration.d.ts +52 -0
- package/dist/anthropic_integration.d.ts.map +1 -0
- package/dist/anthropic_integration.js +226 -0
- package/dist/anthropic_integration.js.map +1 -0
- package/dist/client.d.ts +99 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +258 -0
- package/dist/client.js.map +1 -0
- package/dist/context.d.ts +63 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +84 -0
- package/dist/context.js.map +1 -0
- package/dist/events.d.ts +95 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +103 -0
- package/dist/events.js.map +1 -0
- package/dist/halt.d.ts +165 -0
- package/dist/halt.d.ts.map +1 -0
- package/dist/halt.js +229 -0
- package/dist/halt.js.map +1 -0
- package/dist/halt_stream.d.ts +77 -0
- package/dist/halt_stream.d.ts.map +1 -0
- package/dist/halt_stream.js +214 -0
- package/dist/halt_stream.js.map +1 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +34 -0
- package/dist/index.js.map +1 -0
- package/dist/integrations/vercel_ai.d.ts +120 -0
- package/dist/integrations/vercel_ai.d.ts.map +1 -0
- package/dist/integrations/vercel_ai.js +381 -0
- package/dist/integrations/vercel_ai.js.map +1 -0
- package/dist/observe.d.ts +50 -0
- package/dist/observe.d.ts.map +1 -0
- package/dist/observe.js +97 -0
- package/dist/observe.js.map +1 -0
- package/dist/tool.d.ts +27 -0
- package/dist/tool.d.ts.map +1 -0
- package/dist/tool.js +138 -0
- package/dist/tool.js.map +1 -0
- package/dist/wrap.d.ts +69 -0
- package/dist/wrap.d.ts.map +1 -0
- package/dist/wrap.js +168 -0
- package/dist/wrap.js.map +1 -0
- package/package.json +70 -0
package/dist/tool.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tool() — wraps an async function as an instrumented agent tool.
|
|
3
|
+
*
|
|
4
|
+
* Mirrors the Python `@mesedi.tool` decorator, but as a higher-order
|
|
5
|
+
* function (TS doesn't have stable decorators yet). When the
|
|
6
|
+
* wrapped function is called from INSIDE a `wrap()`'d execution,
|
|
7
|
+
* each invocation emits a `tool_call` event with:
|
|
8
|
+
*
|
|
9
|
+
* - tool_name (from options or the function's .name)
|
|
10
|
+
* - arguments (sanitized + truncated)
|
|
11
|
+
* - status ("ok" or "failed")
|
|
12
|
+
* - result_summary (truncated) on success
|
|
13
|
+
* - exception_type / exception_message on failure
|
|
14
|
+
* - duration_ms
|
|
15
|
+
*
|
|
16
|
+
* Outside a wrap() context: runs unobserved (same fail-open as Python).
|
|
17
|
+
* Exceptions propagate to the caller unchanged.
|
|
18
|
+
*/
|
|
19
|
+
import { getClient } from "./client.js";
|
|
20
|
+
import { currentExecutionContext, newEventId, } from "./context.js";
|
|
21
|
+
import { EventType, utcNowRfc3339 } from "./events.js";
|
|
22
|
+
const MAX_ARG_REPR = 200;
|
|
23
|
+
const MAX_RESULT_REPR = 500;
|
|
24
|
+
const MAX_EXC_MSG = 500;
|
|
25
|
+
/**
|
|
26
|
+
* Decorate an async function as an observable agent tool.
|
|
27
|
+
*/
|
|
28
|
+
export function tool(fnOrOpts, maybeFn) {
|
|
29
|
+
let opts;
|
|
30
|
+
let fn;
|
|
31
|
+
if (typeof fnOrOpts === "function") {
|
|
32
|
+
opts = {};
|
|
33
|
+
// Cast: `typeof === "function"` narrows to the broad built-in
|
|
34
|
+
// `Function` type rather than to our specific signature.
|
|
35
|
+
fn = fnOrOpts;
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
opts = fnOrOpts;
|
|
39
|
+
if (!maybeFn) {
|
|
40
|
+
throw new TypeError("tool() requires a function — pass either tool(fn) or tool(options, fn).");
|
|
41
|
+
}
|
|
42
|
+
fn = maybeFn;
|
|
43
|
+
}
|
|
44
|
+
const toolName = opts.name ?? fn.name ?? "<unknown>";
|
|
45
|
+
return async function inner(...args) {
|
|
46
|
+
const ctx = currentExecutionContext();
|
|
47
|
+
if (!ctx) {
|
|
48
|
+
// No active execution — run unobserved.
|
|
49
|
+
return fn(...args);
|
|
50
|
+
}
|
|
51
|
+
// Halt-safe boundary: check the budget BEFORE doing any work.
|
|
52
|
+
// If a budget exists and is exceeded, this throws MesediHalt
|
|
53
|
+
// which propagates up to wrap()'s catch block. The user's tool
|
|
54
|
+
// code never runs — guarantees halt fires at the boundary, not
|
|
55
|
+
// mid-tool. wrap() also incrementing steps post-check matches
|
|
56
|
+
// the Python pattern (check, then count).
|
|
57
|
+
ctx.checkBudget();
|
|
58
|
+
if (ctx.budgetTracker) {
|
|
59
|
+
ctx.budgetTracker.incrementSteps();
|
|
60
|
+
}
|
|
61
|
+
const client = getClient();
|
|
62
|
+
const sequence = ctx.nextSequence();
|
|
63
|
+
const eventId = newEventId();
|
|
64
|
+
const argsSummary = summarizeArgs(args);
|
|
65
|
+
const start = performance.now();
|
|
66
|
+
try {
|
|
67
|
+
const result = await fn(...args);
|
|
68
|
+
const durationMs = Math.round(performance.now() - start);
|
|
69
|
+
const event = {
|
|
70
|
+
event_id: eventId,
|
|
71
|
+
execution_id: ctx.executionId,
|
|
72
|
+
event_type: EventType.TOOL_CALL,
|
|
73
|
+
sequence,
|
|
74
|
+
timestamp: utcNowRfc3339(),
|
|
75
|
+
duration_ms: durationMs,
|
|
76
|
+
payload: {
|
|
77
|
+
tool_name: toolName,
|
|
78
|
+
arguments: argsSummary,
|
|
79
|
+
status: "ok",
|
|
80
|
+
result_summary: truncate(safeRepr(result), MAX_RESULT_REPR),
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
client.submitEvent(event);
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
catch (err) {
|
|
87
|
+
const durationMs = Math.round(performance.now() - start);
|
|
88
|
+
const event = {
|
|
89
|
+
event_id: eventId,
|
|
90
|
+
execution_id: ctx.executionId,
|
|
91
|
+
event_type: EventType.TOOL_CALL,
|
|
92
|
+
sequence,
|
|
93
|
+
timestamp: utcNowRfc3339(),
|
|
94
|
+
duration_ms: durationMs,
|
|
95
|
+
payload: {
|
|
96
|
+
tool_name: toolName,
|
|
97
|
+
arguments: argsSummary,
|
|
98
|
+
status: "failed",
|
|
99
|
+
exception_type: err instanceof Error && err.constructor.name
|
|
100
|
+
? err.constructor.name
|
|
101
|
+
: typeof err,
|
|
102
|
+
exception_message: truncate(err instanceof Error ? err.message : String(err), MAX_EXC_MSG),
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
client.submitEvent(event);
|
|
106
|
+
throw err;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
function summarizeArgs(args) {
|
|
111
|
+
return {
|
|
112
|
+
args: args.map((a) => truncate(safeRepr(a), MAX_ARG_REPR)),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* JSON.stringify-with-fallback. Falls back to `String(x)` for values
|
|
117
|
+
* that JSON can't serialize (circular refs, BigInt, functions).
|
|
118
|
+
*/
|
|
119
|
+
function safeRepr(value) {
|
|
120
|
+
if (value === undefined)
|
|
121
|
+
return "undefined";
|
|
122
|
+
if (value === null)
|
|
123
|
+
return "null";
|
|
124
|
+
if (typeof value === "string")
|
|
125
|
+
return JSON.stringify(value);
|
|
126
|
+
try {
|
|
127
|
+
return JSON.stringify(value);
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return String(value);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function truncate(s, max) {
|
|
134
|
+
if (s.length <= max)
|
|
135
|
+
return s;
|
|
136
|
+
return s.slice(0, max - 3) + "...";
|
|
137
|
+
}
|
|
138
|
+
//# sourceMappingURL=tool.js.map
|
package/dist/tool.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool.js","sourceRoot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Q,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"}
|
package/dist/wrap.d.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* wrap() — Mesedi's primary observation primitive for TypeScript.
|
|
3
|
+
*
|
|
4
|
+
* TypeScript doesn't have stable decorators in regular JS, so wrap()
|
|
5
|
+
* is a HIGHER-ORDER FUNCTION rather than a decorator. The shape:
|
|
6
|
+
*
|
|
7
|
+
* const myAgent = wrap(
|
|
8
|
+
* { name: "ticket_handler" }, // optional config
|
|
9
|
+
* async (ticket: Ticket) => { // the actual agent function
|
|
10
|
+
* // ... agent logic ...
|
|
11
|
+
* return result;
|
|
12
|
+
* },
|
|
13
|
+
* );
|
|
14
|
+
*
|
|
15
|
+
* await myAgent(someTicket);
|
|
16
|
+
*
|
|
17
|
+
* Behavior matches the Python `@mesedi.wrap` decorator exactly:
|
|
18
|
+
* - On entry: enqueue POST /executions (status=started). Returns
|
|
19
|
+
* immediately; HTTP happens in the background shipper.
|
|
20
|
+
* - On normal return: enqueue PATCH /executions/{id}
|
|
21
|
+
* (status=completed, duration_ms, ended_at).
|
|
22
|
+
* - On rejection: enqueue PATCH /executions/{id}
|
|
23
|
+
* (status=crashed, crash_signature), then re-throw the original
|
|
24
|
+
* error with its original stack trace.
|
|
25
|
+
*
|
|
26
|
+
* **Async-by-default**: Submission to the shipper is fire-and-forget;
|
|
27
|
+
* actual HTTP happens in the background. Latency added to the
|
|
28
|
+
* wrapped call is the time to construct an Execution + push a single
|
|
29
|
+
* item onto an in-memory queue. Sub-millisecond.
|
|
30
|
+
*
|
|
31
|
+
* **Fail-open**: Mesedi outages NEVER block the wrapped agent.
|
|
32
|
+
* Observation failures are logged via console.warn but the wrapped
|
|
33
|
+
* function's behavior is preserved unchanged.
|
|
34
|
+
*
|
|
35
|
+
* **Nested wraps**: A wrap()'d function calling another wrap()'d
|
|
36
|
+
* function produces two distinct executions. The inner one becomes
|
|
37
|
+
* "current" while it runs; when it returns, the outer execution's
|
|
38
|
+
* context is automatically restored via AsyncLocalStorage.
|
|
39
|
+
*/
|
|
40
|
+
import { Budget } from "./halt.js";
|
|
41
|
+
/** Options accepted by `wrap()`. All optional. */
|
|
42
|
+
export interface WrapOptions {
|
|
43
|
+
/**
|
|
44
|
+
* Optional human-readable name. Not yet rendered on the dashboard
|
|
45
|
+
* but reserved for the future replay-UI; helps users distinguish
|
|
46
|
+
* "this execution was the ticket handler" from "this execution
|
|
47
|
+
* was the summarizer."
|
|
48
|
+
*/
|
|
49
|
+
name?: string;
|
|
50
|
+
/**
|
|
51
|
+
* Optional per-execution budget. When set, the wrapped function
|
|
52
|
+
* runs with halt-safe boundary checks at every `tool()` /
|
|
53
|
+
* `checkpoint()` / Anthropic LLM-call entry point. If any limit is
|
|
54
|
+
* exceeded between calls, a MesediHalt is thrown internally —
|
|
55
|
+
* wrap() catches it, marks the execution status=halted (with
|
|
56
|
+
* crash_signature=`halt:<trigger>`), and returns undefined.
|
|
57
|
+
*
|
|
58
|
+
* The wrapped function's normal try/finally cleanup runs as
|
|
59
|
+
* expected — halt is raised AT a safe boundary, never mid-tool /
|
|
60
|
+
* mid-LLM-call, so user resources release cleanly.
|
|
61
|
+
*/
|
|
62
|
+
budget?: Budget;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Wrap an async function so each call is recorded as an agent
|
|
66
|
+
* execution by Mesedi.
|
|
67
|
+
*/
|
|
68
|
+
export declare function wrap<TArgs extends unknown[], TResult>(fnOrOpts: WrapOptions | ((...args: TArgs) => Promise<TResult>), maybeFn?: (...args: TArgs) => Promise<TResult>): (...args: TArgs) => Promise<TResult | undefined>;
|
|
69
|
+
//# sourceMappingURL=wrap.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wrap.d.ts","sourceRoot":"","sources":["../src/wrap.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AAaH,OAAO,EAAE,MAAM,EAA+B,MAAM,WAAW,CAAC;AAGhE,kDAAkD;AAClD,MAAM,WAAW,WAAW;IAC1B;;;;;OAKG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,wBAAgB,IAAI,CAAC,KAAK,SAAS,OAAO,EAAE,EAAE,OAAO,EACnD,QAAQ,EAAE,WAAW,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,EAC9D,OAAO,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,OAAO,CAAC,GAC7C,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CA0GlD"}
|
package/dist/wrap.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* wrap() — Mesedi's primary observation primitive for TypeScript.
|
|
3
|
+
*
|
|
4
|
+
* TypeScript doesn't have stable decorators in regular JS, so wrap()
|
|
5
|
+
* is a HIGHER-ORDER FUNCTION rather than a decorator. The shape:
|
|
6
|
+
*
|
|
7
|
+
* const myAgent = wrap(
|
|
8
|
+
* { name: "ticket_handler" }, // optional config
|
|
9
|
+
* async (ticket: Ticket) => { // the actual agent function
|
|
10
|
+
* // ... agent logic ...
|
|
11
|
+
* return result;
|
|
12
|
+
* },
|
|
13
|
+
* );
|
|
14
|
+
*
|
|
15
|
+
* await myAgent(someTicket);
|
|
16
|
+
*
|
|
17
|
+
* Behavior matches the Python `@mesedi.wrap` decorator exactly:
|
|
18
|
+
* - On entry: enqueue POST /executions (status=started). Returns
|
|
19
|
+
* immediately; HTTP happens in the background shipper.
|
|
20
|
+
* - On normal return: enqueue PATCH /executions/{id}
|
|
21
|
+
* (status=completed, duration_ms, ended_at).
|
|
22
|
+
* - On rejection: enqueue PATCH /executions/{id}
|
|
23
|
+
* (status=crashed, crash_signature), then re-throw the original
|
|
24
|
+
* error with its original stack trace.
|
|
25
|
+
*
|
|
26
|
+
* **Async-by-default**: Submission to the shipper is fire-and-forget;
|
|
27
|
+
* actual HTTP happens in the background. Latency added to the
|
|
28
|
+
* wrapped call is the time to construct an Execution + push a single
|
|
29
|
+
* item onto an in-memory queue. Sub-millisecond.
|
|
30
|
+
*
|
|
31
|
+
* **Fail-open**: Mesedi outages NEVER block the wrapped agent.
|
|
32
|
+
* Observation failures are logged via console.warn but the wrapped
|
|
33
|
+
* function's behavior is preserved unchanged.
|
|
34
|
+
*
|
|
35
|
+
* **Nested wraps**: A wrap()'d function calling another wrap()'d
|
|
36
|
+
* function produces two distinct executions. The inner one becomes
|
|
37
|
+
* "current" while it runs; when it returns, the outer execution's
|
|
38
|
+
* context is automatically restored via AsyncLocalStorage.
|
|
39
|
+
*/
|
|
40
|
+
import { createHash } from "node:crypto";
|
|
41
|
+
import { getClient } from "./client.js";
|
|
42
|
+
import { newExecutionId, runInExecutionContext, } from "./context.js";
|
|
43
|
+
import { Status, utcNowRfc3339, } from "./events.js";
|
|
44
|
+
import { BudgetTracker, isMesediHalt } from "./halt.js";
|
|
45
|
+
import { HaltStreamReader } from "./halt_stream.js";
|
|
46
|
+
/**
|
|
47
|
+
* Wrap an async function so each call is recorded as an agent
|
|
48
|
+
* execution by Mesedi.
|
|
49
|
+
*/
|
|
50
|
+
export function wrap(fnOrOpts, maybeFn) {
|
|
51
|
+
// Support both call shapes:
|
|
52
|
+
// wrap(fn) — no options
|
|
53
|
+
// wrap({...opts}, fn) — with options
|
|
54
|
+
let opts;
|
|
55
|
+
let fn;
|
|
56
|
+
if (typeof fnOrOpts === "function") {
|
|
57
|
+
opts = {};
|
|
58
|
+
// Cast: `typeof === "function"` narrows to the broad built-in
|
|
59
|
+
// `Function` type rather than to our specific signature, but at
|
|
60
|
+
// runtime it IS our signature — the call site guarantees that
|
|
61
|
+
// shape since the function position is statically typed.
|
|
62
|
+
fn = fnOrOpts;
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
opts = fnOrOpts;
|
|
66
|
+
if (!maybeFn) {
|
|
67
|
+
throw new TypeError("wrap() requires a function — pass either wrap(fn) or wrap(options, fn).");
|
|
68
|
+
}
|
|
69
|
+
fn = maybeFn;
|
|
70
|
+
}
|
|
71
|
+
// `opts.name` is reserved for future use; touch it so the noUnusedLocals
|
|
72
|
+
// compiler check doesn't complain in this slice.
|
|
73
|
+
void opts.name;
|
|
74
|
+
return async function inner(...args) {
|
|
75
|
+
const client = getClient();
|
|
76
|
+
const executionId = newExecutionId();
|
|
77
|
+
const execution = {
|
|
78
|
+
execution_id: executionId,
|
|
79
|
+
status: Status.STARTED,
|
|
80
|
+
started_at: utcNowRfc3339(),
|
|
81
|
+
sdk_language: "typescript",
|
|
82
|
+
sdk_version: "0.0.4",
|
|
83
|
+
};
|
|
84
|
+
// Construct a budget tracker iff a budget was supplied. Stays
|
|
85
|
+
// undefined for un-budgeted wraps — checkBudget() then no-ops.
|
|
86
|
+
const tracker = opts.budget ? new BudgetTracker(opts.budget) : undefined;
|
|
87
|
+
// Sub-slice 21e: if a budget is configured, spawn an SSE reader
|
|
88
|
+
// subscribed to /executions/{id}/halt-stream. When the backend
|
|
89
|
+
// publishes a halt (e.g. via the dashboard's operator Halt
|
|
90
|
+
// button), the reader calls tracker.signalRemoteHalt(reason);
|
|
91
|
+
// the next halt-safe boundary check in tool()/checkpoint()/the
|
|
92
|
+
// Anthropic patch then throws MesediHalt(trigger='remote_signal').
|
|
93
|
+
// Fail-open: subscription failures log at debug and the agent
|
|
94
|
+
// continues with local-budget-only operation.
|
|
95
|
+
let haltReader;
|
|
96
|
+
if (tracker !== undefined) {
|
|
97
|
+
haltReader = new HaltStreamReader({
|
|
98
|
+
executionId,
|
|
99
|
+
baseUrl: client.baseUrl,
|
|
100
|
+
apiKey: client.apiKey,
|
|
101
|
+
onHalt: (reason) => tracker.signalRemoteHalt(reason),
|
|
102
|
+
});
|
|
103
|
+
haltReader.start();
|
|
104
|
+
}
|
|
105
|
+
client.submitExecutionStart(execution);
|
|
106
|
+
const startWall = performance.now();
|
|
107
|
+
try {
|
|
108
|
+
const result = await runInExecutionContext(executionId, () => fn(...args), tracker);
|
|
109
|
+
execution.status = Status.COMPLETED;
|
|
110
|
+
execution.duration_ms = Math.round(performance.now() - startWall);
|
|
111
|
+
execution.ended_at = utcNowRfc3339();
|
|
112
|
+
client.submitExecutionEnd(execution);
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
execution.duration_ms = Math.round(performance.now() - startWall);
|
|
117
|
+
execution.ended_at = utcNowRfc3339();
|
|
118
|
+
if (isMesediHalt(err)) {
|
|
119
|
+
// Controlled halt — record as halted, NOT crashed. The
|
|
120
|
+
// crash_signature carries the trigger so the dashboard can
|
|
121
|
+
// group halts by cause (`halt:wall_clock` etc.) — same wire
|
|
122
|
+
// format the Python SDK emits.
|
|
123
|
+
execution.status = Status.HALTED;
|
|
124
|
+
// err is narrowed to MesediHalt here by isMesediHalt's type
|
|
125
|
+
// guard, so the trigger access is type-safe.
|
|
126
|
+
execution.crash_signature = `halt:${err.trigger}`;
|
|
127
|
+
client.submitExecutionEnd(execution);
|
|
128
|
+
// Return undefined — DON'T re-throw. The halt is a
|
|
129
|
+
// controlled stop; the caller's downstream code should NOT
|
|
130
|
+
// see an exception. This matches Python's `return None`
|
|
131
|
+
// behavior in wrap.py.
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
execution.status = Status.CRASHED;
|
|
135
|
+
execution.crash_signature = crashSignature(err);
|
|
136
|
+
client.submitExecutionEnd(execution);
|
|
137
|
+
throw err; // re-throw real crashes with original stack
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
// Stop the halt-stream reader on every exit path so the
|
|
141
|
+
// in-flight fetch aborts and the background task exits. Safe
|
|
142
|
+
// to call multiple times.
|
|
143
|
+
haltReader?.stop();
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Stable 16-hex-char signature for grouping identical crashes.
|
|
149
|
+
*
|
|
150
|
+
* Matches the Python SDK formula: SHA-256 of (error class name +
|
|
151
|
+
* the first 5 lines of the formatted error). Truncates to 16 hex
|
|
152
|
+
* chars — collision-resistant at scale, easy to display in
|
|
153
|
+
* dashboards.
|
|
154
|
+
*
|
|
155
|
+
* The backend's Phase-3a crash grouper uses the same input shape, so
|
|
156
|
+
* Python-emitted and TS-emitted crashes with the same root cause
|
|
157
|
+
* cluster into the same failure_group.
|
|
158
|
+
*/
|
|
159
|
+
function crashSignature(err) {
|
|
160
|
+
const name = err instanceof Error && err.constructor.name
|
|
161
|
+
? err.constructor.name
|
|
162
|
+
: typeof err;
|
|
163
|
+
const stack = err instanceof Error && err.stack ? err.stack : String(err);
|
|
164
|
+
const top5 = stack.split("\n").slice(0, 5).join("\n");
|
|
165
|
+
const input = `${name}\n${top5}`;
|
|
166
|
+
return createHash("sha256").update(input, "utf8").digest("hex").slice(0, 16);
|
|
167
|
+
}
|
|
168
|
+
//# sourceMappingURL=wrap.js.map
|
package/dist/wrap.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wrap.js","sourceRoot":"","sources":["../src/wrap.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EACL,cAAc,EACd,qBAAqB,GACtB,MAAM,cAA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C,IAAI,CAAC,CAAC;IACtD,MAAM,KAAK,GAAG,GAAG,IAAI,KAAK,IAAI,EAAE,CAAC;IACjC,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAC/E,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "mesedi",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Mesedi SDK — guardians for autonomous AI agents. Detect failures, halt runaways, escalate first occurrence.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://mesedi.ai",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/mesedi-ai/mesedi.git",
|
|
10
|
+
"directory": "sdk-typescript"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/mesedi-ai/mesedi/issues"
|
|
14
|
+
},
|
|
15
|
+
"author": "Robert J. Canario <mesediai@gmail.com>",
|
|
16
|
+
"type": "module",
|
|
17
|
+
"main": "./dist/index.js",
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"import": "./dist/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./integrations/vercel_ai": {
|
|
25
|
+
"types": "./dist/integrations/vercel_ai.d.ts",
|
|
26
|
+
"import": "./dist/integrations/vercel_ai.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"peerDependencies": {
|
|
30
|
+
"ai": ">=3.0.0"
|
|
31
|
+
},
|
|
32
|
+
"peerDependenciesMeta": {
|
|
33
|
+
"ai": {
|
|
34
|
+
"optional": true
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"dist",
|
|
39
|
+
"README.md"
|
|
40
|
+
],
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsc",
|
|
43
|
+
"build:sandbox": "tsc -p tsconfig.sandbox.json",
|
|
44
|
+
"clean": "rm -rf dist dist-sandbox",
|
|
45
|
+
"test:sandbox": "npm run build:sandbox && node dist-sandbox/sandbox/real_agent.js",
|
|
46
|
+
"test:parity": "npm run build:sandbox && node dist-sandbox/sandbox/parity_test.js"
|
|
47
|
+
},
|
|
48
|
+
"engines": {
|
|
49
|
+
"node": ">=18.0.0"
|
|
50
|
+
},
|
|
51
|
+
"keywords": [
|
|
52
|
+
"ai",
|
|
53
|
+
"agents",
|
|
54
|
+
"observability",
|
|
55
|
+
"agent-monitoring",
|
|
56
|
+
"llm",
|
|
57
|
+
"vercel-ai-sdk",
|
|
58
|
+
"anthropic",
|
|
59
|
+
"openai",
|
|
60
|
+
"mesedi"
|
|
61
|
+
],
|
|
62
|
+
"publishConfig": {
|
|
63
|
+
"access": "public",
|
|
64
|
+
"provenance": true
|
|
65
|
+
},
|
|
66
|
+
"devDependencies": {
|
|
67
|
+
"typescript": "^5.4.0",
|
|
68
|
+
"@types/node": "^20.11.0"
|
|
69
|
+
}
|
|
70
|
+
}
|