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/halt.d.ts ADDED
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Hard-halt primitives — TypeScript port of the Python `mesedi/halt.py`.
3
+ *
4
+ * Three exports:
5
+ *
6
+ * - `Budget` — interface describing the per-execution limits
7
+ * (wall-clock seconds, step count, input/output
8
+ * tokens). Any subset of fields can be set; unset
9
+ * fields are "no limit on that axis."
10
+ *
11
+ * - `MesediHalt` — Error subclass that the runtime throws when a
12
+ * `Budget` is exceeded. Carries a `reason` and a
13
+ * `trigger` so callers / dashboards can tell which
14
+ * axis blew the budget. Marked with an internal
15
+ * `Symbol` property so `wrap()` can reliably detect
16
+ * a halt-throw even if the user's agent code did
17
+ * `try { ... } catch (err) { ... }` and re-threw
18
+ * something else.
19
+ *
20
+ * - `BudgetTracker` — runtime counter struct. One per execution.
21
+ * Tracks wall-clock start (via `performance.now()`
22
+ * — JS's monotonic clock equivalent of Python's
23
+ * `time.monotonic()`), step count, token totals.
24
+ * `check()` throws MesediHalt if any limit is
25
+ * exceeded; the wrap()'d entry points call it as
26
+ * a halt-safe boundary BEFORE doing work, so the
27
+ * halt always fires between tool/llm/checkpoint
28
+ * calls — never mid-call.
29
+ *
30
+ * Cross-language wire-format parity:
31
+ *
32
+ * - `crash_signature` on the execution = `halt:<trigger>`, exact
33
+ * same shape as the Python SDK emits, so TS-halted executions
34
+ * cluster into the same failure_group as Python-halted ones with
35
+ * the same trigger.
36
+ *
37
+ * - `status = "halted"` matches Status.HALTED in events.ts.
38
+ *
39
+ * - The wrapped function returns `undefined` when halted (no
40
+ * re-throw), mirroring Python's "return None" behavior. The halt
41
+ * is recorded as a controlled stop, not as an error the caller
42
+ * needs to handle.
43
+ *
44
+ * Why a marker Symbol on MesediHalt:
45
+ *
46
+ * In Python, `MesediHalt(BaseException)` evades `except Exception:`
47
+ * handlers — broad except blocks miss it. JavaScript has no
48
+ * equivalent of BaseException; `catch (err)` always catches
49
+ * everything. So we mark MesediHalt with a hidden Symbol-keyed
50
+ * property and `wrap()` looks for that symbol, not just an
51
+ * `instanceof` check. Even if the user's agent does
52
+ * `try { ... } catch (err) { throw new Error("wrapped: " + err) }`
53
+ * and accidentally re-wraps the halt as a plain Error, our `wrap()`
54
+ * can still detect the halt by walking the error chain looking for
55
+ * the symbol. Belt-and-suspenders.
56
+ */
57
+ /**
58
+ * Per-execution budget envelope. Pass to `wrap({ budget: ... }, fn)`.
59
+ * Any combination of fields can be set; unset fields impose no limit
60
+ * on that axis.
61
+ */
62
+ export interface Budget {
63
+ /** Wall-clock seconds from execution start. Real elapsed time. */
64
+ maxWallClockSeconds?: number;
65
+ /**
66
+ * Number of halt-safe boundary crossings allowed. Currently
67
+ * incremented at `tool()` entry, `instrumentAnthropic`'s patched
68
+ * `Messages.create` entry, and each `checkpoint()` call. Equivalent
69
+ * of Python's `max_steps`.
70
+ */
71
+ maxSteps?: number;
72
+ /**
73
+ * Total input tokens across all LLM calls. Updated when the
74
+ * Anthropic patch sees a successful response with token usage.
75
+ */
76
+ maxTokensIn?: number;
77
+ /** Total output tokens across all LLM calls. */
78
+ maxTokensOut?: number;
79
+ }
80
+ /**
81
+ * Symbol-keyed marker that identifies a MesediHalt even after
82
+ * unintended re-wrapping. Keep this private to the module so user
83
+ * code can't forge it.
84
+ */
85
+ declare const MESEDI_HALT_MARKER: unique symbol;
86
+ /**
87
+ * Trigger that caused a halt — embedded in the crash_signature
88
+ * (`halt:wall_clock`) so the dashboard groups halts by cause.
89
+ */
90
+ export type HaltTrigger = "wall_clock" | "step_count" | "token_total" | "remote_signal";
91
+ /**
92
+ * Error thrown when a Budget is exceeded. Extends Error so standard
93
+ * stack traces work; carries a marker Symbol so `wrap()` can detect a
94
+ * halt even if the user's catch block re-wraps it.
95
+ */
96
+ export declare class MesediHalt extends Error {
97
+ readonly reason: string;
98
+ readonly trigger: HaltTrigger;
99
+ readonly [MESEDI_HALT_MARKER]: true;
100
+ constructor(reason: string, trigger: HaltTrigger);
101
+ }
102
+ /**
103
+ * Type guard: was this thrown by Mesedi's halt machinery?
104
+ *
105
+ * Walks the error chain via `.cause` (and a couple of common
106
+ * re-wrap shapes) looking for the symbol marker. This is the function
107
+ * `wrap()` uses to decide "treat as controlled halt → status=halted,
108
+ * return undefined" vs "treat as crash → re-throw, status=crashed."
109
+ */
110
+ export declare function isMesediHalt(err: unknown): err is MesediHalt;
111
+ /**
112
+ * Runtime counter struct. One instance per execution, lives on the
113
+ * ExecutionContext. Thread-safety isn't a concern in Node — the
114
+ * single-threaded event loop guarantees serial access — but the
115
+ * counter writes still need to be coherent across async boundaries,
116
+ * which AsyncLocalStorage gives us for free.
117
+ *
118
+ * `check()` is the halt-safe boundary. Callers (tool, anthropic
119
+ * patch, checkpoint) call it FIRST, then increment counters. If any
120
+ * limit is already exceeded at the time of check, a MesediHalt is
121
+ * thrown — the caller's work is never started.
122
+ */
123
+ export declare class BudgetTracker {
124
+ private readonly budget;
125
+ private readonly startMs;
126
+ private steps;
127
+ private tokensIn;
128
+ private tokensOut;
129
+ private remoteHaltReason?;
130
+ constructor(budget: Budget);
131
+ /**
132
+ * Mark this execution as having a pending remote halt.
133
+ *
134
+ * Called by the SSE halt-stream reader (see halt_stream.ts) when
135
+ * the backend publishes a halt event for this execution. The next
136
+ * `check()` call will throw `MesediHalt(trigger='remote_signal')`
137
+ * with the supplied reason.
138
+ *
139
+ * Idempotent — multiple signals overwrite the reason (last one
140
+ * wins). Concurrency is fine: Node's single-threaded event loop
141
+ * means the reader thread's write and the agent thread's read
142
+ * can't interleave at the JS level.
143
+ */
144
+ signalRemoteHalt(reason: string): void;
145
+ /**
146
+ * Halt-safe boundary check. Call before doing work; if any budget
147
+ * is already exceeded, this throws MesediHalt and the caller's
148
+ * work never runs.
149
+ *
150
+ * Priority: remote halt FIRST. If the dashboard or a detector
151
+ * explicitly told us to halt, operator intent beats any budget
152
+ * axis. Local budgets only trip when no remote halt is pending.
153
+ */
154
+ check(): void;
155
+ /** Increment the step counter. Call AFTER `check()`. */
156
+ incrementSteps(): void;
157
+ /** Add token usage from an LLM-call response. */
158
+ addTokens(tokensIn: number, tokensOut: number): void;
159
+ get currentSteps(): number;
160
+ get currentTokensIn(): number;
161
+ get currentTokensOut(): number;
162
+ get elapsedMs(): number;
163
+ }
164
+ export {};
165
+ //# sourceMappingURL=halt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"halt.d.ts","sourceRoot":"","sources":["../src/halt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuDG;AAEH;;;;GAIG;AACH,MAAM,WAAW,MAAM;IACrB,kEAAkE;IAClE,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,gDAAgD;IAChD,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;GAIG;AACH,QAAA,MAAM,kBAAkB,eAAmC,CAAC;AAE5D;;;GAGG;AACH,MAAM,MAAM,WAAW,GACnB,YAAY,GACZ,YAAY,GACZ,aAAa,GACb,eAAe,CAAC;AAEpB;;;;GAIG;AACH,qBAAa,UAAW,SAAQ,KAAK;IACnC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC;IAG9B,QAAQ,CAAC,CAAC,kBAAkB,CAAC,EAAE,IAAI,CAAQ;gBAE/B,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW;CAQjD;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,UAAU,CAoB5D;AAED;;;;;;;;;;;GAWG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,KAAK,CAAK;IAClB,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,SAAS,CAAK;IAMtB,OAAO,CAAC,gBAAgB,CAAC,CAAS;gBAEtB,MAAM,EAAE,MAAM;IAQ1B;;;;;;;;;;;;OAYG;IACH,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAItC;;;;;;;;OAQG;IACH,KAAK,IAAI,IAAI;IAoDb,wDAAwD;IACxD,cAAc,IAAI,IAAI;IAItB,iDAAiD;IACjD,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,IAAI;IAMpD,IAAI,YAAY,IAAI,MAAM,CAEzB;IACD,IAAI,eAAe,IAAI,MAAM,CAE5B;IACD,IAAI,gBAAgB,IAAI,MAAM,CAE7B;IACD,IAAI,SAAS,IAAI,MAAM,CAEtB;CACF"}
package/dist/halt.js ADDED
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Hard-halt primitives — TypeScript port of the Python `mesedi/halt.py`.
3
+ *
4
+ * Three exports:
5
+ *
6
+ * - `Budget` — interface describing the per-execution limits
7
+ * (wall-clock seconds, step count, input/output
8
+ * tokens). Any subset of fields can be set; unset
9
+ * fields are "no limit on that axis."
10
+ *
11
+ * - `MesediHalt` — Error subclass that the runtime throws when a
12
+ * `Budget` is exceeded. Carries a `reason` and a
13
+ * `trigger` so callers / dashboards can tell which
14
+ * axis blew the budget. Marked with an internal
15
+ * `Symbol` property so `wrap()` can reliably detect
16
+ * a halt-throw even if the user's agent code did
17
+ * `try { ... } catch (err) { ... }` and re-threw
18
+ * something else.
19
+ *
20
+ * - `BudgetTracker` — runtime counter struct. One per execution.
21
+ * Tracks wall-clock start (via `performance.now()`
22
+ * — JS's monotonic clock equivalent of Python's
23
+ * `time.monotonic()`), step count, token totals.
24
+ * `check()` throws MesediHalt if any limit is
25
+ * exceeded; the wrap()'d entry points call it as
26
+ * a halt-safe boundary BEFORE doing work, so the
27
+ * halt always fires between tool/llm/checkpoint
28
+ * calls — never mid-call.
29
+ *
30
+ * Cross-language wire-format parity:
31
+ *
32
+ * - `crash_signature` on the execution = `halt:<trigger>`, exact
33
+ * same shape as the Python SDK emits, so TS-halted executions
34
+ * cluster into the same failure_group as Python-halted ones with
35
+ * the same trigger.
36
+ *
37
+ * - `status = "halted"` matches Status.HALTED in events.ts.
38
+ *
39
+ * - The wrapped function returns `undefined` when halted (no
40
+ * re-throw), mirroring Python's "return None" behavior. The halt
41
+ * is recorded as a controlled stop, not as an error the caller
42
+ * needs to handle.
43
+ *
44
+ * Why a marker Symbol on MesediHalt:
45
+ *
46
+ * In Python, `MesediHalt(BaseException)` evades `except Exception:`
47
+ * handlers — broad except blocks miss it. JavaScript has no
48
+ * equivalent of BaseException; `catch (err)` always catches
49
+ * everything. So we mark MesediHalt with a hidden Symbol-keyed
50
+ * property and `wrap()` looks for that symbol, not just an
51
+ * `instanceof` check. Even if the user's agent does
52
+ * `try { ... } catch (err) { throw new Error("wrapped: " + err) }`
53
+ * and accidentally re-wraps the halt as a plain Error, our `wrap()`
54
+ * can still detect the halt by walking the error chain looking for
55
+ * the symbol. Belt-and-suspenders.
56
+ */
57
+ /**
58
+ * Symbol-keyed marker that identifies a MesediHalt even after
59
+ * unintended re-wrapping. Keep this private to the module so user
60
+ * code can't forge it.
61
+ */
62
+ const MESEDI_HALT_MARKER = Symbol.for("mesedi.halt.marker");
63
+ /**
64
+ * Error thrown when a Budget is exceeded. Extends Error so standard
65
+ * stack traces work; carries a marker Symbol so `wrap()` can detect a
66
+ * halt even if the user's catch block re-wraps it.
67
+ */
68
+ export class MesediHalt extends Error {
69
+ reason;
70
+ trigger;
71
+ // Symbol-keyed marker — invisible to JSON.stringify, hard for user
72
+ // code to spoof.
73
+ [MESEDI_HALT_MARKER] = true;
74
+ constructor(reason, trigger) {
75
+ super(reason);
76
+ this.name = "MesediHalt";
77
+ this.reason = reason;
78
+ this.trigger = trigger;
79
+ // Make the stack point at the throw site, not at the constructor.
80
+ Error.captureStackTrace?.(this, MesediHalt);
81
+ }
82
+ }
83
+ /**
84
+ * Type guard: was this thrown by Mesedi's halt machinery?
85
+ *
86
+ * Walks the error chain via `.cause` (and a couple of common
87
+ * re-wrap shapes) looking for the symbol marker. This is the function
88
+ * `wrap()` uses to decide "treat as controlled halt → status=halted,
89
+ * return undefined" vs "treat as crash → re-throw, status=crashed."
90
+ */
91
+ export function isMesediHalt(err) {
92
+ if (!err || typeof err !== "object")
93
+ return false;
94
+ // Direct marker.
95
+ if (err[MESEDI_HALT_MARKER]) {
96
+ return true;
97
+ }
98
+ // Walk Error.cause chain — ES2022 standard for wrapped errors.
99
+ let cursor = err.cause;
100
+ let safety = 0;
101
+ while (cursor && safety < 10) {
102
+ if (typeof cursor === "object" &&
103
+ cursor[MESEDI_HALT_MARKER]) {
104
+ return true;
105
+ }
106
+ cursor = cursor.cause;
107
+ safety += 1;
108
+ }
109
+ return false;
110
+ }
111
+ /**
112
+ * Runtime counter struct. One instance per execution, lives on the
113
+ * ExecutionContext. Thread-safety isn't a concern in Node — the
114
+ * single-threaded event loop guarantees serial access — but the
115
+ * counter writes still need to be coherent across async boundaries,
116
+ * which AsyncLocalStorage gives us for free.
117
+ *
118
+ * `check()` is the halt-safe boundary. Callers (tool, anthropic
119
+ * patch, checkpoint) call it FIRST, then increment counters. If any
120
+ * limit is already exceeded at the time of check, a MesediHalt is
121
+ * thrown — the caller's work is never started.
122
+ */
123
+ export class BudgetTracker {
124
+ budget;
125
+ startMs;
126
+ steps = 0;
127
+ tokensIn = 0;
128
+ tokensOut = 0;
129
+ // Sub-slice 21e: when the SSE halt-stream reader receives a halt
130
+ // event for this execution, it sets this field via
131
+ // signalRemoteHalt(). The next check() call reads it FIRST (before
132
+ // any budget-axis check) and throws MesediHalt with
133
+ // trigger='remote_signal'. undefined means no remote halt pending.
134
+ remoteHaltReason;
135
+ constructor(budget) {
136
+ this.budget = budget;
137
+ // performance.now() returns a monotonic millisecond timer that
138
+ // doesn't jump backward on NTP adjustments — the JS equivalent
139
+ // of Python's time.monotonic().
140
+ this.startMs = performance.now();
141
+ }
142
+ /**
143
+ * Mark this execution as having a pending remote halt.
144
+ *
145
+ * Called by the SSE halt-stream reader (see halt_stream.ts) when
146
+ * the backend publishes a halt event for this execution. The next
147
+ * `check()` call will throw `MesediHalt(trigger='remote_signal')`
148
+ * with the supplied reason.
149
+ *
150
+ * Idempotent — multiple signals overwrite the reason (last one
151
+ * wins). Concurrency is fine: Node's single-threaded event loop
152
+ * means the reader thread's write and the agent thread's read
153
+ * can't interleave at the JS level.
154
+ */
155
+ signalRemoteHalt(reason) {
156
+ this.remoteHaltReason = reason || "remote halt";
157
+ }
158
+ /**
159
+ * Halt-safe boundary check. Call before doing work; if any budget
160
+ * is already exceeded, this throws MesediHalt and the caller's
161
+ * work never runs.
162
+ *
163
+ * Priority: remote halt FIRST. If the dashboard or a detector
164
+ * explicitly told us to halt, operator intent beats any budget
165
+ * axis. Local budgets only trip when no remote halt is pending.
166
+ */
167
+ check() {
168
+ // Remote halt check — runs even when the budget is unbounded,
169
+ // so a wrap()'d agent without explicit local limits can still
170
+ // be remote-halted (dashboard panic-stop semantics).
171
+ if (this.remoteHaltReason !== undefined) {
172
+ const reason = this.remoteHaltReason;
173
+ // Clear so successive check() calls don't repeat-raise after
174
+ // the first MesediHalt escapes to wrap(). wrap() catches and
175
+ // returns immediately, so this shouldn't matter in practice,
176
+ // but it costs nothing.
177
+ this.remoteHaltReason = undefined;
178
+ throw new MesediHalt(reason, "remote_signal");
179
+ }
180
+ // Wall-clock — checked first among the local axes because it's
181
+ // the most common trigger in practice. A runaway agent burns
182
+ // time before it burns steps or tokens.
183
+ if (this.budget.maxWallClockSeconds !== undefined) {
184
+ const elapsedSec = (performance.now() - this.startMs) / 1000;
185
+ if (elapsedSec >= this.budget.maxWallClockSeconds) {
186
+ throw new MesediHalt(`wall-clock budget exceeded (${elapsedSec.toFixed(2)}s ≥ ${this.budget.maxWallClockSeconds}s)`, "wall_clock");
187
+ }
188
+ }
189
+ if (this.budget.maxSteps !== undefined &&
190
+ this.steps >= this.budget.maxSteps) {
191
+ throw new MesediHalt(`step-count budget exceeded (${this.steps} ≥ ${this.budget.maxSteps})`, "step_count");
192
+ }
193
+ if (this.budget.maxTokensIn !== undefined) {
194
+ if (this.tokensIn >= this.budget.maxTokensIn) {
195
+ throw new MesediHalt(`input-token budget exceeded (${this.tokensIn} ≥ ${this.budget.maxTokensIn})`, "token_total");
196
+ }
197
+ }
198
+ if (this.budget.maxTokensOut !== undefined) {
199
+ if (this.tokensOut >= this.budget.maxTokensOut) {
200
+ throw new MesediHalt(`output-token budget exceeded (${this.tokensOut} ≥ ${this.budget.maxTokensOut})`, "token_total");
201
+ }
202
+ }
203
+ }
204
+ /** Increment the step counter. Call AFTER `check()`. */
205
+ incrementSteps() {
206
+ this.steps += 1;
207
+ }
208
+ /** Add token usage from an LLM-call response. */
209
+ addTokens(tokensIn, tokensOut) {
210
+ if (tokensIn > 0)
211
+ this.tokensIn += tokensIn;
212
+ if (tokensOut > 0)
213
+ this.tokensOut += tokensOut;
214
+ }
215
+ // Read-only accessors for testing / observability.
216
+ get currentSteps() {
217
+ return this.steps;
218
+ }
219
+ get currentTokensIn() {
220
+ return this.tokensIn;
221
+ }
222
+ get currentTokensOut() {
223
+ return this.tokensOut;
224
+ }
225
+ get elapsedMs() {
226
+ return performance.now() - this.startMs;
227
+ }
228
+ }
229
+ //# sourceMappingURL=halt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"halt.js","sourceRoot":"","sources":["../src/halt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuDG;AA0BH;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,MAAM,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;AAY5D;;;;G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IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IACD,IAAI,gBAAgB;QAClB,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IACD,IAAI,SAAS;QACX,OAAO,WAAW,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC;IAC1C,CAAC;CACF"}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * SSE halt-stream reader — sub-slice 21e (TS port of 21b.2).
3
+ *
4
+ * When `wrap()` is entered with a `budget` configured, the wrap layer
5
+ * spawns a HaltStreamReader that opens an HTTP stream against
6
+ * `GET /executions/{id}/halt-stream` (the SSE endpoint shipped in
7
+ * sub-slice 21b.1). When the backend pushes an `event: halt` frame,
8
+ * the reader parses the reason and calls `tracker.signalRemoteHalt(reason)`.
9
+ * The next halt-safe boundary check inside the wrapped agent then
10
+ * throws `MesediHalt` with `trigger='remote_signal'`.
11
+ *
12
+ * Implementation notes vs the Python version:
13
+ *
14
+ * - **No thread.** JavaScript is single-threaded; the reader is
15
+ * just an async function returning a Promise that we kick off
16
+ * without awaiting. The fetch's underlying I/O runs on Node's
17
+ * libuv pool — same effective concurrency as a Python daemon
18
+ * thread.
19
+ *
20
+ * - **AbortController for stop().** We can't "interrupt" an async
21
+ * iteration the way Python's `_stop` event lets us bail out of
22
+ * `iter_lines()`. Instead the controller's signal is wired into
23
+ * fetch; calling `.stop()` aborts the underlying HTTP connection,
24
+ * the response stream throws on its next read, and the reader
25
+ * exits via the catch block.
26
+ *
27
+ * - **Native fetch + ReadableStream.** Node 18+ ships fetch in
28
+ * stdlib. We pull bytes off `response.body.getReader()`, decode
29
+ * UTF-8 chunks via TextDecoder, accumulate into a buffer, and
30
+ * split on newlines to get SSE lines. The SSE spec uses `\n` or
31
+ * `\r\n` or `\r` as line separators — we normalize all three.
32
+ *
33
+ * - **Fail-open posture.** If subscription fails (connect error,
34
+ * non-200 response, parse error), the reader logs at debug-level
35
+ * via `console.debug` and exits. The wrapped agent continues
36
+ * running on whatever local budget it has. Remote halt is a
37
+ * nice-to-have on top of local budgets, never a hard requirement.
38
+ *
39
+ * - **One-shot semantics.** After dispatching a halt event, the
40
+ * reader exits. The backend closes the SSE connection at the
41
+ * same moment — both sides agree halt is one signal per
42
+ * subscription.
43
+ *
44
+ * No public API surface: customers don't construct HaltStreamReader.
45
+ * It's used only by wrap.ts.
46
+ */
47
+ export interface HaltStreamReaderOptions {
48
+ executionId: string;
49
+ baseUrl: string;
50
+ apiKey: string;
51
+ onHalt: (reason: string) => void;
52
+ schemaVersion?: string;
53
+ }
54
+ export declare class HaltStreamReader {
55
+ private readonly executionId;
56
+ private readonly baseUrl;
57
+ private readonly apiKey;
58
+ private readonly onHalt;
59
+ private readonly schemaVersion;
60
+ private readonly controller;
61
+ private started;
62
+ private stopped;
63
+ constructor(opts: HaltStreamReaderOptions);
64
+ /**
65
+ * Kick off the async read loop. Idempotent — second call is a no-op.
66
+ * Does NOT await — the wrap layer fires this and continues.
67
+ */
68
+ start(): void;
69
+ /**
70
+ * Signal the reader to stop and abort any in-flight fetch.
71
+ * Safe to call multiple times.
72
+ */
73
+ stop(): void;
74
+ private _run;
75
+ private _dispatchHalt;
76
+ }
77
+ //# sourceMappingURL=halt_stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"halt_stream.d.ts","sourceRoot":"","sources":["../src/halt_stream.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AAIH,MAAM,WAAW,uBAAuB;IACtC,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IACjC,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA2B;IAClD,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAkB;IAC7C,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,OAAO,CAAS;gBAEZ,IAAI,EAAE,uBAAuB;IASzC;;;OAGG;IACH,KAAK,IAAI,IAAI;IAQb;;;OAGG;IACH,IAAI,IAAI,IAAI;YAUE,IAAI;IA4GlB,OAAO,CAAC,aAAa;CAsBtB"}