@openwop/openwop 1.0.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/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @openwop/openwop — TypeScript reference SDK for OpenWOP-compliant servers.
3
+ *
4
+ * Public surface:
5
+ * - OpenwopClient (auth + endpoint methods)
6
+ * - WopError (typed error wrapping ErrorEnvelope)
7
+ * - All request/response types mirroring the OpenAPI spec
8
+ * - streamEvents helper for advanced SSE use cases
9
+ *
10
+ * See README.md for usage examples.
11
+ */
12
+ export { OpenwopClient } from './client.js';
13
+ export { WopError } from './types.js';
14
+ export { streamEvents } from './sse.js';
15
+ // Run-status + run-error helpers (added in 1). Forward-compat predicates
16
+ // over the wire-format unions declared above; full design + rationale in
17
+ // `run-helpers.ts`.
18
+ export { ACTIVE_RUN_STATUSES, TERMINAL_RUN_STATUSES, isTerminalRunStatus, HTTP_ERROR_CODES, isHttpErrorCode, RUN_ERROR_CODES, isRunErrorCode, } from './run-helpers.js';
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAqBtC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAGxC,yEAAyE;AACzE,yEAAyE;AACzE,oBAAoB;AACpB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,mBAAmB,EACnB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,cAAc,GACf,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Run-status + error-code helpers — additive utilities over the wire-format
3
+ * `RunStatus` union, HTTP error envelopes, and run-level error shape
4
+ * declared in `types.ts`.
5
+ *
6
+ * **Why these live here.** `types.ts` declares the canonical wire shapes
7
+ * (mirroring `api/openapi.yaml` + `schemas/run-snapshot.schema.json`).
8
+ * This module adds the constants + predicates SDK consumers need to act
9
+ * on those shapes without redefining them locally. Pulling them into the
10
+ * SDK makes the protocol vocabulary single-sourced for application,
11
+ * integration, and test code.
12
+ *
13
+ * **Forward-compatibility design.** The spec's `RunStatus` enum is
14
+ * intentionally narrower than what host engines may emit: the schema
15
+ * declares *"future statuses MAY be added; readers SHOULD treat unknown
16
+ * values as terminal-unknown rather than throw"*. So `isTerminalRunStatus`
17
+ * accepts `string` and uses a **negative-set** check — anything NOT in
18
+ * the small known-non-terminal set is treated as terminal. This keeps
19
+ * the helper correct against:
20
+ *
21
+ * - the canonical 8-member spec union (`pending` / `running` / `paused`
22
+ * / `waiting-approval` / `waiting-input` / `completed` / `failed` /
23
+ * `cancelled`)
24
+ * - host extensions like `'planned'`, `'executing'`, `'waiting-external'`,
25
+ * `'timed-out'`, `'interrupted'` which the OpenWOP engine emits
26
+ * - any future spec additions before the SDK ships an updated minor
27
+ *
28
+ * @module @openwop/openwop/run-helpers
29
+ */
30
+ import type { RunStatus } from './types.js';
31
+ /**
32
+ * Run statuses considered active — the run MAY still transition. A reader
33
+ * who does not recognize a status string MUST treat it as terminal-unknown
34
+ * (per the spec's forward-compat clause). This list is the narrow,
35
+ * spec-stable enumeration used to derive that decision.
36
+ */
37
+ export declare const ACTIVE_RUN_STATUSES: readonly ["pending", "running", "paused", "waiting-approval", "waiting-input"];
38
+ /**
39
+ * Spec-known terminal statuses. Hosts MAY emit additional terminal values
40
+ * (e.g., `'timed-out'`, `'interrupted'`); use {@link isTerminalRunStatus}
41
+ * for forward-compatible checks instead of literal-set membership.
42
+ */
43
+ export declare const TERMINAL_RUN_STATUSES: readonly ["completed", "failed", "cancelled"];
44
+ export type ActiveRunStatus = (typeof ACTIVE_RUN_STATUSES)[number];
45
+ export type TerminalRunStatus = (typeof TERMINAL_RUN_STATUSES)[number];
46
+ /**
47
+ * Returns true if the status indicates the run will not transition further.
48
+ *
49
+ * Implemented as a negative check against {@link ACTIVE_RUN_STATUSES}: any
50
+ * value NOT in the spec's known-active set is treated as terminal. This
51
+ * implements the schema's forward-compat clause — a host that emits a
52
+ * status the SDK doesn't know about is assumed to be reporting a terminal
53
+ * state, NOT that the run is still active. The alternative (positive check
54
+ * against {@link TERMINAL_RUN_STATUSES}) would loop polling forever on any
55
+ * unknown value, which is the documented worst-case the clause prevents.
56
+ *
57
+ * Accepts `string` (not just `RunStatus`) so callers can pass values from
58
+ * extended host emissions without casting.
59
+ */
60
+ export declare function isTerminalRunStatus(status: RunStatus | string): boolean;
61
+ /**
62
+ * Canonical REST/MCP error-envelope codes from `auth.md`,
63
+ * `rest-endpoints.md`, and adjacent v1 specs. The HTTP envelope's `error`
64
+ * field remains string-typed for forward compatibility, but this list
65
+ * gives SDK consumers a stable set for common branching.
66
+ *
67
+ * Codes here describe request/transport failures. Run execution failures
68
+ * live in `RUN_ERROR_CODES` below as `RunSnapshot.error.code`.
69
+ */
70
+ export declare const HTTP_ERROR_CODES: readonly ["unauthenticated", "forbidden", "key_expired", "key_revoked", "validation_error", "not_found", "rate_limited", "run_already_active", "idempotency_in_flight", "idempotency_key_mismatch", "unsupported_stream_mode", "force_engine_version_forbidden", "mock_provider_forbidden", "capability_not_provided", "credential_required", "credential_forbidden", "credential_unavailable", "interrupt_not_found", "approval_token_invalid", "approval_token_expired", "approval_token_consumed", "internal_error"];
71
+ export type HttpErrorCode = (typeof HTTP_ERROR_CODES)[number];
72
+ /**
73
+ * Type guard that narrows a string to a known canonical HTTP error code.
74
+ * Returns false for host extensions and future spec additions; callers
75
+ * should still render a fallback from the envelope's `message`.
76
+ */
77
+ export declare function isHttpErrorCode(value: unknown): value is HttpErrorCode;
78
+ /**
79
+ * Run-document error codes — stable identifiers used in
80
+ * `RunSnapshot.error.code` when a run reaches `failed`. These are distinct
81
+ * from the HTTP-level `ErrorEnvelope.error` codes above: a request can fail
82
+ * with `unauthenticated` before a run exists, while a run can fail later
83
+ * with `node_execution_failed` or `recursion_limit_exceeded`.
84
+ *
85
+ * Add a new code here when adding a new run failure mode that crosses the
86
+ * network boundary. Do NOT add codes for purely internal engine errors.
87
+ *
88
+ * **Drift risk note.** This list is canonical for SDK consumers but is
89
+ * NOT yet pinned by `conformance/src/scenarios/errors.test.ts` against
90
+ * host emission. A future conformance addition (tracked separately)
91
+ * SHOULD compare host-emitted error codes against this set and fail on
92
+ * unrecognized values. Until that lands, drift between this list + the
93
+ * engine's actual emission set is detectable only by manual review.
94
+ */
95
+ export declare const RUN_ERROR_CODES: readonly ["auth_required", "forbidden", "workspace_not_found", "run_already_active", "run_not_found", "run_terminal", "engine_version_mismatch", "invalid_workflow_definition", "invalid_trigger_input", "node_type_not_found", "config_validation_failed", "token_budget_exceeded", "concurrent_run_limit_reached", "rate_limited", "node_timeout", "global_timeout", "node_execution_failed", "external_call_failed", "recursion_limit_exceeded", "capability_not_provided", "approval_timeout", "approval_token_invalid", "approval_token_expired", "approval_token_consumed", "persistence_failed", "doc_budget_exceeded"];
96
+ export type RunErrorCode = (typeof RUN_ERROR_CODES)[number];
97
+ /**
98
+ * Type guard that narrows a string to a known {@link RunErrorCode}.
99
+ * Returns false for unknown / malformed values rather than throwing —
100
+ * SDK consumers usually want to display a fallback for unknown codes
101
+ * rather than crash the render pipeline.
102
+ */
103
+ export declare function isRunErrorCode(value: unknown): value is RunErrorCode;
104
+ /**
105
+ * Run-level error shape — the structured `error` field on a `failed` run
106
+ * document. Distinct from the HTTP-level {@link import('./types.js').ErrorEnvelope}:
107
+ *
108
+ * - `RunError` lives on the run document; describes WHY the run failed.
109
+ * `code` is from the typed {@link RunErrorCode} vocabulary.
110
+ * - `ErrorEnvelope` lives on HTTP error responses; describes WHY the
111
+ * request failed. `error` is a free string code (often from
112
+ * {@link HTTP_ERROR_CODES}, but not type-pinned, to permit host
113
+ * extensions and future protocol additions).
114
+ *
115
+ * The shapes share `message` and `details` but diverge on the code field
116
+ * name (`code` vs `error`) by design — they represent different layers.
117
+ */
118
+ export interface RunError {
119
+ code: RunErrorCode;
120
+ message: string;
121
+ /** Optional node-id where the error originated. */
122
+ nodeId?: string;
123
+ /** Optional structured context — implementations MAY extend. */
124
+ details?: Record<string, unknown>;
125
+ }
126
+ //# sourceMappingURL=run-helpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-helpers.d.ts","sourceRoot":"","sources":["../src/run-helpers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAI5C;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,gFAMtB,CAAC;AAEX;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,+CAIxB,CAAC;AAEX,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,mBAAmB,CAAC,CAAC,MAAM,CAAC,CAAC;AACnE,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,qBAAqB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEvE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,GAAG,OAAO,CAEvE;AAID;;;;;;;;GAQG;AACH,eAAO,MAAM,gBAAgB,yfAoCnB,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE9D;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAEtE;AAID;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,eAAe,gmBAwClB,CAAC;AAEX,MAAM,MAAM,YAAY,GAAG,CAAC,OAAO,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC;AAE5D;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,YAAY,CAEpE;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,YAAY,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,mDAAmD;IACnD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,gEAAgE;IAChE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC"}
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Run-status + error-code helpers — additive utilities over the wire-format
3
+ * `RunStatus` union, HTTP error envelopes, and run-level error shape
4
+ * declared in `types.ts`.
5
+ *
6
+ * **Why these live here.** `types.ts` declares the canonical wire shapes
7
+ * (mirroring `api/openapi.yaml` + `schemas/run-snapshot.schema.json`).
8
+ * This module adds the constants + predicates SDK consumers need to act
9
+ * on those shapes without redefining them locally. Pulling them into the
10
+ * SDK makes the protocol vocabulary single-sourced for application,
11
+ * integration, and test code.
12
+ *
13
+ * **Forward-compatibility design.** The spec's `RunStatus` enum is
14
+ * intentionally narrower than what host engines may emit: the schema
15
+ * declares *"future statuses MAY be added; readers SHOULD treat unknown
16
+ * values as terminal-unknown rather than throw"*. So `isTerminalRunStatus`
17
+ * accepts `string` and uses a **negative-set** check — anything NOT in
18
+ * the small known-non-terminal set is treated as terminal. This keeps
19
+ * the helper correct against:
20
+ *
21
+ * - the canonical 8-member spec union (`pending` / `running` / `paused`
22
+ * / `waiting-approval` / `waiting-input` / `completed` / `failed` /
23
+ * `cancelled`)
24
+ * - host extensions like `'planned'`, `'executing'`, `'waiting-external'`,
25
+ * `'timed-out'`, `'interrupted'` which the OpenWOP engine emits
26
+ * - any future spec additions before the SDK ships an updated minor
27
+ *
28
+ * @module @openwop/openwop/run-helpers
29
+ */
30
+ // ─── Run statuses ────────────────────────────────────────────────────────
31
+ /**
32
+ * Run statuses considered active — the run MAY still transition. A reader
33
+ * who does not recognize a status string MUST treat it as terminal-unknown
34
+ * (per the spec's forward-compat clause). This list is the narrow,
35
+ * spec-stable enumeration used to derive that decision.
36
+ */
37
+ export const ACTIVE_RUN_STATUSES = [
38
+ 'pending',
39
+ 'running',
40
+ 'paused',
41
+ 'waiting-approval',
42
+ 'waiting-input',
43
+ ];
44
+ /**
45
+ * Spec-known terminal statuses. Hosts MAY emit additional terminal values
46
+ * (e.g., `'timed-out'`, `'interrupted'`); use {@link isTerminalRunStatus}
47
+ * for forward-compatible checks instead of literal-set membership.
48
+ */
49
+ export const TERMINAL_RUN_STATUSES = [
50
+ 'completed',
51
+ 'failed',
52
+ 'cancelled',
53
+ ];
54
+ /**
55
+ * Returns true if the status indicates the run will not transition further.
56
+ *
57
+ * Implemented as a negative check against {@link ACTIVE_RUN_STATUSES}: any
58
+ * value NOT in the spec's known-active set is treated as terminal. This
59
+ * implements the schema's forward-compat clause — a host that emits a
60
+ * status the SDK doesn't know about is assumed to be reporting a terminal
61
+ * state, NOT that the run is still active. The alternative (positive check
62
+ * against {@link TERMINAL_RUN_STATUSES}) would loop polling forever on any
63
+ * unknown value, which is the documented worst-case the clause prevents.
64
+ *
65
+ * Accepts `string` (not just `RunStatus`) so callers can pass values from
66
+ * extended host emissions without casting.
67
+ */
68
+ export function isTerminalRunStatus(status) {
69
+ return !ACTIVE_RUN_STATUSES.includes(status);
70
+ }
71
+ // ─── HTTP error-envelope codes ───────────────────────────────────────────
72
+ /**
73
+ * Canonical REST/MCP error-envelope codes from `auth.md`,
74
+ * `rest-endpoints.md`, and adjacent v1 specs. The HTTP envelope's `error`
75
+ * field remains string-typed for forward compatibility, but this list
76
+ * gives SDK consumers a stable set for common branching.
77
+ *
78
+ * Codes here describe request/transport failures. Run execution failures
79
+ * live in `RUN_ERROR_CODES` below as `RunSnapshot.error.code`.
80
+ */
81
+ export const HTTP_ERROR_CODES = [
82
+ // Auth / access
83
+ 'unauthenticated',
84
+ 'forbidden',
85
+ 'key_expired',
86
+ 'key_revoked',
87
+ // Request / routing
88
+ 'validation_error',
89
+ 'not_found',
90
+ 'rate_limited',
91
+ // Idempotency / run creation conflicts
92
+ 'run_already_active',
93
+ 'idempotency_in_flight',
94
+ 'idempotency_key_mismatch',
95
+ // Streaming / protocol negotiation
96
+ 'unsupported_stream_mode',
97
+ 'force_engine_version_forbidden',
98
+ 'mock_provider_forbidden',
99
+ // Capability / credential negotiation
100
+ 'capability_not_provided',
101
+ 'credential_required',
102
+ 'credential_forbidden',
103
+ 'credential_unavailable',
104
+ // HITL / interrupt callbacks
105
+ 'interrupt_not_found',
106
+ 'approval_token_invalid',
107
+ 'approval_token_expired',
108
+ 'approval_token_consumed',
109
+ // Generic server failure
110
+ 'internal_error',
111
+ ];
112
+ /**
113
+ * Type guard that narrows a string to a known canonical HTTP error code.
114
+ * Returns false for host extensions and future spec additions; callers
115
+ * should still render a fallback from the envelope's `message`.
116
+ */
117
+ export function isHttpErrorCode(value) {
118
+ return typeof value === 'string' && HTTP_ERROR_CODES.includes(value);
119
+ }
120
+ // ─── Run error codes ─────────────────────────────────────────────────────
121
+ /**
122
+ * Run-document error codes — stable identifiers used in
123
+ * `RunSnapshot.error.code` when a run reaches `failed`. These are distinct
124
+ * from the HTTP-level `ErrorEnvelope.error` codes above: a request can fail
125
+ * with `unauthenticated` before a run exists, while a run can fail later
126
+ * with `node_execution_failed` or `recursion_limit_exceeded`.
127
+ *
128
+ * Add a new code here when adding a new run failure mode that crosses the
129
+ * network boundary. Do NOT add codes for purely internal engine errors.
130
+ *
131
+ * **Drift risk note.** This list is canonical for SDK consumers but is
132
+ * NOT yet pinned by `conformance/src/scenarios/errors.test.ts` against
133
+ * host emission. A future conformance addition (tracked separately)
134
+ * SHOULD compare host-emitted error codes against this set and fail on
135
+ * unrecognized values. Until that lands, drift between this list + the
136
+ * engine's actual emission set is detectable only by manual review.
137
+ */
138
+ export const RUN_ERROR_CODES = [
139
+ // Authorization / access
140
+ 'auth_required',
141
+ 'forbidden',
142
+ 'workspace_not_found',
143
+ // Run-state conflicts
144
+ 'run_already_active',
145
+ 'run_not_found',
146
+ 'run_terminal',
147
+ 'engine_version_mismatch',
148
+ // Validation
149
+ 'invalid_workflow_definition',
150
+ 'invalid_trigger_input',
151
+ 'node_type_not_found',
152
+ 'config_validation_failed',
153
+ // Quota / budget
154
+ 'token_budget_exceeded',
155
+ 'concurrent_run_limit_reached',
156
+ 'rate_limited',
157
+ // Execution
158
+ 'node_timeout',
159
+ 'global_timeout',
160
+ 'node_execution_failed',
161
+ 'external_call_failed',
162
+ 'recursion_limit_exceeded',
163
+ 'capability_not_provided',
164
+ // Approval
165
+ 'approval_timeout',
166
+ 'approval_token_invalid',
167
+ 'approval_token_expired',
168
+ 'approval_token_consumed',
169
+ // Persistence
170
+ 'persistence_failed',
171
+ 'doc_budget_exceeded',
172
+ ];
173
+ /**
174
+ * Type guard that narrows a string to a known {@link RunErrorCode}.
175
+ * Returns false for unknown / malformed values rather than throwing —
176
+ * SDK consumers usually want to display a fallback for unknown codes
177
+ * rather than crash the render pipeline.
178
+ */
179
+ export function isRunErrorCode(value) {
180
+ return typeof value === 'string' && RUN_ERROR_CODES.includes(value);
181
+ }
182
+ //# sourceMappingURL=run-helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-helpers.js","sourceRoot":"","sources":["../src/run-helpers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAIH,4EAA4E;AAE5E;;;;;GAKG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,SAAS;IACT,SAAS;IACT,QAAQ;IACR,kBAAkB;IAClB,eAAe;CACP,CAAC;AAEX;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,WAAW;IACX,QAAQ;IACR,WAAW;CACH,CAAC;AAKX;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAA0B;IAC5D,OAAO,CAAE,mBAAyC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AACtE,CAA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CAAC,KAAc;IAC3C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAK,eAAqC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAC7F,CAAC"}
package/dist/sse.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * SSE consumer for `GET /v1/runs/{runId}/events`. Async-iterable shape so
3
+ * consumers can write `for await (const event of client.runs.events(...))`.
4
+ *
5
+ * Implementation parses event:/data:/id: lines per RFC 8895. Native fetch +
6
+ * ReadableStream — zero third-party deps.
7
+ *
8
+ * Designed to be cancellable: pass an AbortSignal via options, or break out
9
+ * of the for-await loop and the underlying connection is torn down on the
10
+ * next tick.
11
+ */
12
+ import type { RunEventDoc, StreamMode } from './types.js';
13
+ export interface EventsStreamOptions {
14
+ /**
15
+ * Single mode (e.g., 'updates') OR array of modes (S4 mixed-mode,
16
+ * e.g., ['updates', 'messages']). Arrays serialize to a comma-
17
+ * separated `?streamMode=updates,messages` query.
18
+ */
19
+ readonly streamMode?: StreamMode | readonly StreamMode[];
20
+ readonly lastEventId?: string;
21
+ readonly signal?: AbortSignal;
22
+ /**
23
+ * S3 batching hint. When set, server batches events for up to N ms;
24
+ * the SDK transparently flattens batched arrays back into individual
25
+ * RunEventDoc yields, so consumers see the same per-event surface as
26
+ * unbuffered streams. Range 0..5000.
27
+ */
28
+ readonly bufferMs?: number;
29
+ }
30
+ export interface EventsStreamContext {
31
+ readonly baseUrl: string;
32
+ readonly apiKey: string;
33
+ }
34
+ export declare function streamEvents(ctx: EventsStreamContext, runId: string, opts?: EventsStreamOptions): AsyncGenerator<RunEventDoc, void, void>;
35
+ //# sourceMappingURL=sse.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE1D,MAAM,WAAW,mBAAmB;IAClC;;;;OAIG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,UAAU,GAAG,SAAS,UAAU,EAAE,CAAC;IACzD,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;IAC9B;;;;;OAKG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED,wBAAuB,YAAY,CACjC,GAAG,EAAE,mBAAmB,EACxB,KAAK,EAAE,MAAM,EACb,IAAI,GAAE,mBAAwB,GAC7B,cAAc,CAAC,WAAW,EAAE,IAAI,EAAE,IAAI,CAAC,CA6HzC"}
package/dist/sse.js ADDED
@@ -0,0 +1,137 @@
1
+ /**
2
+ * SSE consumer for `GET /v1/runs/{runId}/events`. Async-iterable shape so
3
+ * consumers can write `for await (const event of client.runs.events(...))`.
4
+ *
5
+ * Implementation parses event:/data:/id: lines per RFC 8895. Native fetch +
6
+ * ReadableStream — zero third-party deps.
7
+ *
8
+ * Designed to be cancellable: pass an AbortSignal via options, or break out
9
+ * of the for-await loop and the underlying connection is torn down on the
10
+ * next tick.
11
+ */
12
+ export async function* streamEvents(ctx, runId, opts = {}) {
13
+ const params = new URLSearchParams();
14
+ if (opts.streamMode) {
15
+ const modeParam = typeof opts.streamMode === 'string' ? opts.streamMode : opts.streamMode.join(',');
16
+ params.set('streamMode', modeParam);
17
+ }
18
+ if (opts.bufferMs !== undefined) {
19
+ params.set('bufferMs', String(opts.bufferMs));
20
+ }
21
+ const qs = params.toString();
22
+ const url = `${ctx.baseUrl}/v1/runs/${encodeURIComponent(runId)}/events${qs ? `?${qs}` : ''}`;
23
+ const headers = {
24
+ Accept: 'text/event-stream',
25
+ Authorization: `Bearer ${ctx.apiKey}`,
26
+ 'Cache-Control': 'no-cache',
27
+ };
28
+ if (opts.lastEventId) {
29
+ headers['Last-Event-ID'] = opts.lastEventId;
30
+ }
31
+ const internalAbort = new AbortController();
32
+ const externalSignal = opts.signal;
33
+ if (externalSignal) {
34
+ if (externalSignal.aborted)
35
+ internalAbort.abort();
36
+ else
37
+ externalSignal.addEventListener('abort', () => internalAbort.abort(), { once: true });
38
+ }
39
+ const res = await fetch(url, { method: 'GET', headers, signal: internalAbort.signal });
40
+ if (!res.ok || res.body === null) {
41
+ throw new Error(`SSE subscribe failed: HTTP ${res.status}`);
42
+ }
43
+ const reader = res.body.getReader();
44
+ const decoder = new TextDecoder('utf-8');
45
+ let buffer = '';
46
+ let pendingEvent = 'message';
47
+ let pendingData = [];
48
+ let pendingId = null;
49
+ /**
50
+ * Flush the buffered event. Returns an array of RunEventDoc:
51
+ * - 0 elements when the buffer is empty or non-JSON (skip).
52
+ * - 1 element for a normal `event: <type>` event.
53
+ * - N elements when the server batched per S3 — `event: batch` with
54
+ * `data:` as a JSON array of RunEventDoc.
55
+ */
56
+ const flushAndYield = () => {
57
+ if (pendingData.length === 0) {
58
+ pendingEvent = 'message';
59
+ pendingId = null;
60
+ return [];
61
+ }
62
+ const dataStr = pendingData.join('\n');
63
+ const eventType = pendingEvent;
64
+ pendingEvent = 'message';
65
+ pendingData = [];
66
+ pendingId = null;
67
+ try {
68
+ const parsed = JSON.parse(dataStr);
69
+ // S3 batched envelope — `event: batch` carries an array of events.
70
+ if (eventType === 'batch' && Array.isArray(parsed)) {
71
+ return parsed;
72
+ }
73
+ // Normal single-event payload.
74
+ return [parsed];
75
+ }
76
+ catch {
77
+ // Skip non-JSON events (keep-alive payloads, vendor extensions).
78
+ return [];
79
+ }
80
+ };
81
+ try {
82
+ while (true) {
83
+ const { done, value } = await reader.read();
84
+ if (done)
85
+ break;
86
+ buffer += decoder.decode(value, { stream: true });
87
+ let nlIdx;
88
+ while ((nlIdx = buffer.indexOf('\n')) !== -1) {
89
+ const rawLine = buffer.slice(0, nlIdx).replace(/\r$/, '');
90
+ buffer = buffer.slice(nlIdx + 1);
91
+ if (rawLine === '') {
92
+ for (const event of flushAndYield())
93
+ yield event;
94
+ continue;
95
+ }
96
+ if (rawLine.startsWith(':'))
97
+ continue; // keep-alive comment
98
+ const colon = rawLine.indexOf(':');
99
+ const field = colon === -1 ? rawLine : rawLine.slice(0, colon);
100
+ const valueRaw = colon === -1 ? '' : rawLine.slice(colon + 1);
101
+ const fieldValue = valueRaw.startsWith(' ') ? valueRaw.slice(1) : valueRaw;
102
+ switch (field) {
103
+ case 'event':
104
+ pendingEvent = fieldValue;
105
+ break;
106
+ case 'data':
107
+ pendingData.push(fieldValue);
108
+ break;
109
+ case 'id':
110
+ pendingId = fieldValue;
111
+ break;
112
+ default:
113
+ break;
114
+ }
115
+ }
116
+ }
117
+ // Flush any final unterminated event.
118
+ for (const final of flushAndYield())
119
+ yield final;
120
+ }
121
+ finally {
122
+ try {
123
+ reader.releaseLock();
124
+ }
125
+ catch {
126
+ // best-effort
127
+ }
128
+ if (!internalAbort.signal.aborted)
129
+ internalAbort.abort();
130
+ }
131
+ // Reference pendingEvent/pendingId so the linter doesn't flag them as
132
+ // unused; they're consumed via flushAndYield's closure but TS can't see
133
+ // that across a generator boundary.
134
+ void pendingEvent;
135
+ void pendingId;
136
+ }
137
+ //# sourceMappingURL=sse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse.js","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AA2BH,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,YAAY,CACjC,GAAwB,EACxB,KAAa,EACb,OAA4B,EAAE;IAE9B,MAAM,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;IACrC,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;QACpB,MAAM,SAAS,GACb,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,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