@m8tes/sdk 0.1.0-alpha.1 → 0.1.0-alpha.3

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/CHANGELOG.md CHANGED
@@ -5,12 +5,213 @@ All notable changes to `@m8tes/sdk`.
5
5
  > **Release process** (mirrors `sdk/py`): every change to behaviour or public API
6
6
  > lands an entry under `## [Unreleased]` in the same commit. A RELEASE then bumps
7
7
  > `package.json` `version` (semver) and retitles that section. Entries are never
8
- > skipped — without one, a consumer cannot tell what changed. Publish via the `Publish @m8tes/sdk` workflow — never `npm publish` by
8
+ > skipped — without one, a consumer cannot tell what changed. A version bump
9
+ > merged to main publishes automatically (`Publish npm packages`); dry-run stays
10
+ > on the package-specific workflow. Never `npm publish` by
9
11
  > hand (it does not rewrite the pnpm `workspace:` protocol).
10
12
  >
11
13
  > While the version is a `-alpha.N` prerelease, publish with dist-tag `alpha`.
12
14
  > The first stable release is published with `--tag latest` deliberately.
13
15
 
16
+ ## [Unreleased]
17
+
18
+ ## [0.1.0-alpha.3] — 2026-08-19
19
+
20
+ ### Changed
21
+
22
+ - **`runs.get` / `poll` / `wait` / `createAndWait` forward `user_id`.** Strict
23
+ multi-tenant mode requires `?user_id=` on every by-ID GET; `createAndWait`
24
+ reuses the create body's `user_id`, then falls back to the created run's
25
+ stamped `user_id` (agent-inherited scope). A wait-only `options.user_id` is
26
+ folded into the create body when params omit it; conflicting scopes are
27
+ rejected before POST. After create, poll prefers the API-stamped owner when
28
+ it differs from the request scope.
29
+ - **`runs.cancel(id, { user_id })`** — same end-user scope as get (strict mode).
30
+ - **`ApproveParams.remember` docs match persistence.** `remember: true` on allow
31
+ stores a cross-run always-allow policy (not run-only); deny+remember stays
32
+ run-scoped.
33
+
34
+ ### Added
35
+
36
+ - **`Usage.unlimited_runs`.** Mirrors `GET /api/v2/usage` so clients can tell a
37
+ bypassed meter from a soft over-limit.
38
+ - **`Page.nextStartingAfter` / list envelope `next_starting_after`.** Cursor for the
39
+ next `starting_after` page when `hasMore` is true.
40
+ - **`PermissionRequest.can_remember` / `remember_default` and
41
+ `PermissionPolicy.source`.** `remember_default: false` tells a client the
42
+ Always-allow control must start unticked (force-ask floor: spend, access,
43
+ destroy); `source` names the surface that minted a standing grant
44
+ (`"run_approval"` / `"api"`; null on legacy rows).
45
+
46
+ - **`user_id` end-user scoping on agent and task sub-resource methods.**
47
+ `agents.enableWebhook` / `disableWebhook` / `enableEmailInbox` /
48
+ `disableEmailInbox`, `tasks.enableWebhook` / `disableWebhook`, and the full
49
+ `tasks.triggers` CRUD now accept `{ user_id }` and forward it as the query
50
+ param the API's strict end-user scope reads (mismatch → 404). On
51
+ `triggers.create`, `user_id` rides both the body (whose connected account an
52
+ app trigger arms) and the query (the scope gate on the task) deliberately.
53
+
54
+ ## [0.1.0-alpha.2] — 2026-08-16
55
+
56
+ ### Security
57
+
58
+ - **A caller-supplied id can no longer steer a request off its route.** Every
59
+ dynamic path segment (`agentId`, `taskId`, `runId`, `userId`, `appName`,
60
+ `filename`, …) now goes through one shared `seg()` helper, which **throws
61
+ `ValidationError`** — before anything is sent — on the empty string, `"."`,
62
+ `".."`, `null`/`undefined`, and any value containing `/`, and percent-encodes
63
+ everything else. Previously most ids were interpolated raw (the compile-time
64
+ `number` type is erased at runtime), so `runs.get("5/messages")` reached
65
+ `GET /runs/{id}/messages` and `tasks.delete("5/webhook")` would delete the
66
+ task's webhook token instead of archiving the task. Encoding is not a fix —
67
+ the server percent-decodes the path before routing — so these values are
68
+ refused outright, matching the Python SDK's `seg()` exactly (shared parity
69
+ corpus). `seg` is exported from `@m8tes/sdk/protocol` so `@m8tes/react`'s
70
+ proxy client applies the identical rule. Ordinary ids (numbers, plain
71
+ strings) are unaffected.
72
+
73
+ ### Added
74
+
75
+ - **`client.modelConnections.completeAuthorization("gemini", state, { code })`** —
76
+ paste-code completion for Gemini CLI OAuth. `authorize("gemini")` starts the Google
77
+ PKCE session (`user_code` is null). `authorizationStatus` remains OpenAI/xAI device
78
+ poll only — GET for Gemini 404s.
79
+ - **`billing.usageTimeseries({ surface, settled_meter })`** — same query params as
80
+ `GET /api/v2/usage/timeseries`. `surface` is creation intent (`api` / `platform`);
81
+ `settled_meter` is where the run actually settled (`wallet` is the prepaid ledger).
82
+
83
+ - **`client.modelConnections`** — list account model plans, start and poll native
84
+ OpenAI/Codex or xAI/Grok device authorization, complete Gemini paste-code
85
+ authorization, and disconnect a provider.
86
+
87
+ - **`Idempotency-Key` on every run-creating call, so a retry cannot bill you twice.**
88
+ `runs.create()`, `runs.createAsync()`, `runs.reply()`, `tasks.run()` and
89
+ `tasks.runAsync()` now send one automatically — which is what makes those POSTs
90
+ safe for the transport to retry at all. Previously they were never retried: a
91
+ request that timed out might already have started a billable run, so re-sending
92
+ risked charging twice, and the SDK chose the opposite failure (a dropped request)
93
+ on your behalf. With a key the server returns the run the first attempt created.
94
+
95
+ Pass `idempotencyKey` on `RunCreateParams`, `RunStreamOptions` or `TaskRunParams`
96
+ to supply your own when a retry must survive a process restart — a job runner
97
+ should pass its job id. Reusing a key with a *different* request is a `409`
98
+ (`ConflictError`, `code: "idempotency_key_reuse"`), never a silent replay.
99
+
100
+ New exported type: `TaskRunParams` (the params object `tasks.run` /
101
+ `tasks.runAsync` accept). The header constants and replay helpers stay internal —
102
+ the SDK handles them for you.
103
+
104
+ ### Changed
105
+
106
+ - **POSTs carrying an `Idempotency-Key` are now retried** on network errors and
107
+ `429`/`5xx`, with the same backoff as `GET` — but only on the five routes the
108
+ server actually makes idempotent. A key on any other POST (including one set at
109
+ client level via `headers`) does **not** enable retry, because the header is not
110
+ evidence the server will honour it; retrying `tasks.create` on a timeout would
111
+ simply duplicate the task.
112
+ - A replayed streaming `create`/`reply`/`tasks.run` is answered as JSON rather than
113
+ SSE — a run that already exists has no fresh stream — and the SDK transparently
114
+ joins that run's stream instead, so you still get a `RunStream`. If the run has
115
+ already finished there is nothing to join, so it throws `ConflictError` with
116
+ `code: "idempotent_replay_terminal"` and the run id in `details`; fetch the result
117
+ with `runs.get(id)`. You are charged once either way.
118
+
119
+ - **`runs.createAndWait()`, `runs.poll()`, `runs.wait()`** — start a run and get
120
+ the result, for the worker/cron path where streaming is not what you want. This
121
+ was the biggest ergonomic hole: every user was hand-rolling the same loop with
122
+ their own terminal-status list and usually no timeout. `wait()` also resolves
123
+ human-in-the-loop pauses through `onApproval`/`onQuestion` callbacks. A run that
124
+ does not finish throws `RunTimeoutError`; one that pauses with no handler throws
125
+ `RunPausedError` naming the tool, because waiting out the timeout in silence
126
+ looks identical to a slow run. Same terminal set, interval, and
127
+ transient-error tolerance as the Python SDK.
128
+ - **File attachments** — `runs.create({ files: [{ name, data }] })` posts multipart
129
+ to `/runs/with-files`. `data` takes a Blob, bytes, or a string, and the content
130
+ type is inferred from the extension: the endpoint validates against an allowlist
131
+ and rejects the batch on a miss, so a typeless Blob would arrive as
132
+ `application/octet-stream` and fail every upload. Pass `type` for an unknown
133
+ extension; the SDK refuses rather than guessing.
134
+ - **`runs.retry()`** — returns a NEW run (poll that id). `confirm: true` for a run
135
+ that already took visible actions.
136
+ - **New resources: `memories`, `permissions`, `models`, `billing`, `account`.**
137
+ `/docs/users` documents memories and permissions, so the TypeScript SDK could
138
+ not reach half of the multi-tenancy story it advertised. `models.list()` is how
139
+ you discover valid `model` values instead of guessing; `billing` covers usage,
140
+ balance, receipts, plans, and the overage cap.
141
+ - `isPlanApproval()` / `planText()` for reading a plan-mode pause before approving it.
142
+
143
+ ### Fixed
144
+
145
+ - **A cancelled `createAndWait` no longer starts a billable run.** It POSTed
146
+ first and checked the abort signal afterwards, so an operation the caller had
147
+ already cancelled still created — and billed — a run. Reproduced against the
148
+ packed tarball: one POST, then `RunWaitAbortedError`.
149
+ - **`"closed"` is terminal.** The backend's canonical `TERMINAL_RUN_STATUSES`
150
+ includes it (a user-closed chat that cannot resume) and its own comment warns
151
+ these lists drift: "a 'closed' chat run burned tokens too". Both SDKs omitted
152
+ it, so a closed run polled until the timeout.
153
+ - **The deadline now bounds every awaited operation, not just the gaps between
154
+ them.** An `onApproval` that never settled hung `wait()` forever, one that
155
+ settled late could approve a gate after the caller had given up, and a slow
156
+ request could return success past the deadline.
157
+ - **`interval`/`timeout` reject `NaN`, negatives, and `Infinity`.** `NaN` made
158
+ every deadline check false and turned the sleep into an immediate timer: an
159
+ infinite hot loop against the API.
160
+ - `engines.node` is `>=18.17`, the first release with `AbortSignal.any`. The
161
+ package claimed `>=18`, so any request carrying a caller signal failed on
162
+ 18.0-18.16.
163
+ - `Model.zdr_supported` is documented as "at least one provider supports ZDR",
164
+ which is what the backend actually promises — not "your request will not be
165
+ retained", which could induce a real data-retention mistake.
166
+ - **`createAndWait` and `apps.isConnected` broke when destructured.** They were
167
+ the only methods depending on `this`, so the ordinary
168
+ `const { createAndWait } = client.runs` threw
169
+ `Cannot read properties of undefined`. Both close over a local now, and a test
170
+ drives every method detached from its resource.
171
+ - **A permanent failure no longer polls for the full timeout.** A revoked key,
172
+ a missing run, or a bad id can never reach a terminal status, so waiting
173
+ spent ~150 authenticated requests over 300s and then reported a timeout whose
174
+ advice ("raise the timeout, or stream instead") was wrong for all three. 401,
175
+ 403, 404 and 422 now surface immediately — measured live, 66ms instead of 60s.
176
+ A genuine transient failure still keeps polling, and now rides along on
177
+ `RunTimeoutError.cause` so a timeout no longer hides what caused it.
178
+ - **`Model` exposes the retention fields.** `GET /models/` tells callers to check
179
+ `zdr_supported` before sending customer data; the SDK typed none of them, so
180
+ reading the flag needed an `as any`.
181
+ - `billing.usageTimeseries` types `group_by` as the single literal the route
182
+ accepts, and `setAutoReload` allows amounts alongside `enabled: false` (the
183
+ API applies them).
184
+ - **Waiting on a run now honours abort and the deadline properly.** The abort
185
+ signal reaches every request (not just the sleep), so cancelling a wait cancels
186
+ the in-flight HTTP call; an aborted wait rejects with `RunWaitAbortedError`
187
+ rather than resolving with a still-running run, which read as success. The
188
+ sleep is capped at the remaining time, so a long interval with a short timeout
189
+ no longer overshoots by a whole interval. Deadlines use a monotonic clock, so
190
+ an NTP correction backwards mid-wait cannot extend or defeat the timeout.
191
+ - **A permission is answered exactly once.** A request already answered can come
192
+ back as `pending` on the next poll before the backend flips its status; the
193
+ caller's `onApproval`/`onQuestion` fired again each time (measured: 3 calls for
194
+ one gate), repeating whatever side effect it had.
195
+ - **Headers merge case-insensitively.** A caller passing `Content-Type` plus the
196
+ SDK's own `content-type` produced both, and fetch joins duplicates into
197
+ `application/json, application/json`, which the server rejects with a 422. Any
198
+ header set in a different casing had the same problem.
199
+ - **An explicit attachment `type` beats a Blob's own**, so correcting a
200
+ badly-typed Blob works instead of being silently ignored.
201
+ - `runs.retry()` sends `confirm` as a query param with no body, matching the route.
202
+ - `Run` types `email_address` (the API sends it for a run with an email inbox).
203
+ - `AutoReloadParams` is a discriminated union: `{ enabled: true }` without the
204
+ amounts is now a compile error rather than a 422.
205
+ - The cross-language route parity guard extracted routes by matching a list of
206
+ known path prefixes, so anything outside the list silently stopped being
207
+ checked: renaming `/memories/` to `/memory/` passed. It now extracts from the
208
+ `http.request(...)` call sites AND `pager(http, ...)` calls — the first rewrite
209
+ still missed anything routed through the shared list helper, so a typo'd
210
+ `/billing/receipts` passed. Negative-tested on both call shapes.
211
+ - The polling module's exports are verified by DERIVING the list from the module
212
+ rather than hardcoding it: a hardcoded list missed a newly added export twice,
213
+ each time surfacing as a `SyntaxError` at import in a real consumer.
214
+
14
215
  ## [0.1.0-alpha.1]
15
216
 
16
217
  Initial release. TypeScript client for the m8tes V2 API, at parity with the
package/README.md CHANGED
@@ -45,13 +45,46 @@ await client.users.create({ user_id: "customer_42", run_limit: 50, rate_per_minu
45
45
 
46
46
  ## Not streaming
47
47
 
48
+ For a worker or a cron job that just wants the answer, `createAndWait` starts the run and polls until it finishes:
49
+
50
+ ```ts
51
+ const run = await client.runs.createAndWait({ message: "Prep the weekly recap" });
52
+ console.log(run.status, run.output, run.output_data);
53
+ ```
54
+
55
+ It throws `RunTimeoutError` if the run does not finish in time (default 300s, `{ timeout }` to change it), and `RunPausedError` if the run stops for a human without a handler — a silent wait would look identical to a slow run. Already have a run id? `runs.poll(id)`. Need to answer gates while waiting? `runs.wait(id, { onApproval, onQuestion })`.
56
+
57
+ Fire and forget instead:
58
+
48
59
  ```ts
49
60
  const run = await client.runs.createAsync({ message: "Prep the weekly recap" });
50
- // poll, or receive a webhook
51
- const done = await client.runs.get(run.id);
61
+ const done = await client.runs.get(run.id); // or receive a webhook
52
62
  console.log(done.status, done.output);
53
63
  ```
54
64
 
65
+ Retry a failed run (returns a NEW run, so poll that id):
66
+
67
+ ```ts
68
+ const retried = await client.runs.retry(runId, { confirm: true });
69
+ console.log(retried.id, retried.status);
70
+ ```
71
+
72
+ ## Attachments
73
+
74
+ Give the agent files to work with. The content type comes from the extension, so a `.csv` just works:
75
+
76
+ ```ts
77
+ import { readFile } from "node:fs/promises";
78
+
79
+ const run = await client.runs.createAndWait({
80
+ message: "Which region had the highest churn last quarter?",
81
+ files: [{ name: "churn.csv", data: await readFile("./churn.csv") }],
82
+ });
83
+ console.log(run.output);
84
+ ```
85
+
86
+ Pass `type` explicitly for an extension the SDK does not recognise. It refuses rather than guessing `application/octet-stream`, which the upload endpoint rejects.
87
+
55
88
  ## Agents and scheduled tasks
56
89
 
57
90
  ```ts
@@ -148,6 +181,23 @@ for await (const run of await client.runs.list({ user_id: "customer_42" })) {
148
181
 
149
182
  This package is **server-only** — it holds your secret key. To render an agent in a browser, use [`@m8tes/react`](https://www.npmjs.com/package/@m8tes/react), which ships a `<MateChat>` component plus a locked-down server proxy so the key never reaches the client. Both packages share this one wire-protocol implementation, exported separately as the browser-safe `@m8tes/sdk/protocol`.
150
183
 
184
+ ## Own provider subscription
185
+
186
+ Connect a personal Claude, Codex, Grok, or Gemini plan so matching account-scoped runs bill that provider instead of prepaid credits. The credential never attaches to a `user_id` run.
187
+
188
+ ```ts
189
+ import { M8tes } from "@m8tes/sdk";
190
+
191
+ const client = new M8tes();
192
+ const auth = await client.modelConnections.authorize("gemini");
193
+ console.log(auth.authorization_url); // user_code is null
194
+ await client.modelConnections.completeAuthorization("gemini", auth.state, {
195
+ code: "4/...",
196
+ });
197
+ ```
198
+
199
+ Codex and Grok use `authorize("openai")` / `authorize("xai")` plus `authorizationStatus` until `status` is `"connected"`.
200
+
151
201
  ## Docs
152
202
 
153
203
  - [TypeScript SDK guide](https://www.m8tes.ai/docs/typescript-sdk)
@@ -155,6 +205,10 @@ This package is **server-only** — it holds your secret key. To render an agent
155
205
  - [Multi-tenancy](https://www.m8tes.ai/docs/users)
156
206
  - [Streaming & events](https://www.m8tes.ai/docs/streaming)
157
207
 
208
+ ## Contributing
209
+
210
+ Bug reports and feature requests are welcome — [open an issue](https://github.com/m8tes-ai/m8tes/issues); we review weekly. We don't currently accept external pull requests: this package is developed in our internal monorepo and synced out. If something blocks you, an issue (or support@m8tes.ai) is the fastest path to a fix.
211
+
158
212
  ## License
159
213
 
160
- MIT
214
+ MIT — see [LICENSE](./LICENSE). The m8tes name and logo are trademarks of m8tes; the MIT license does not grant trademark rights.
@@ -1078,6 +1078,29 @@ async function errorFromResponse(res, opts = {}) {
1078
1078
  return new Cls(message, fields);
1079
1079
  }
1080
1080
 
1081
- export { APIError, AuthenticationError, BillingError, ConflictError, M8tesApiError, NotFoundError, PROTOCOL_VERSION, PermissionDeniedError, RateLimitError, RunFailedError, RunNotStreamingError, TERMINAL_EVENT_TYPES, ValidationError, accumulate, createAccumulator, createNormalizer, createSseDecoder, errorClassForStatus, errorFromResponse, initialConversationState, isTerminalEvent, parseErrorEnvelope, parseRetryAfter, parseSse, splitConcatenatedJson };
1082
- //# sourceMappingURL=chunk-UFQQNUFE.js.map
1083
- //# sourceMappingURL=chunk-UFQQNUFE.js.map
1081
+ // src/protocol/seg.ts
1082
+ var UNADDRESSABLE = /* @__PURE__ */ new Set(["", ".", ".."]);
1083
+ var SEPARATOR = "/";
1084
+ function reject(value, reason) {
1085
+ throw new ValidationError(
1086
+ `${JSON.stringify(value)} cannot be used as a URL path segment: ${reason}. Percent-encoding does not help \u2014 the server decodes the path before routing it.`,
1087
+ { type: "invalid_request_error", code: 0, status: 0 }
1088
+ );
1089
+ }
1090
+ function seg(value) {
1091
+ if (value === null || value === void 0) {
1092
+ reject(String(value), "an id of null or undefined is a caller bug, not a resource name");
1093
+ }
1094
+ const text = String(value);
1095
+ if (UNADDRESSABLE.has(text)) {
1096
+ reject(text, "it addresses the parent or the collection, not a resource");
1097
+ }
1098
+ if (text.includes(SEPARATOR)) {
1099
+ reject(text, "a '/' becomes a real path separator once the server decodes it");
1100
+ }
1101
+ return encodeURIComponent(text);
1102
+ }
1103
+
1104
+ export { APIError, AuthenticationError, BillingError, ConflictError, M8tesApiError, NotFoundError, PROTOCOL_VERSION, PermissionDeniedError, RateLimitError, RunFailedError, RunNotStreamingError, TERMINAL_EVENT_TYPES, ValidationError, accumulate, createAccumulator, createNormalizer, createSseDecoder, errorClassForStatus, errorFromResponse, initialConversationState, isTerminalEvent, parseErrorEnvelope, parseRetryAfter, parseSse, seg, splitConcatenatedJson };
1105
+ //# sourceMappingURL=chunk-CURNMC4F.js.map
1106
+ //# sourceMappingURL=chunk-CURNMC4F.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/protocol/events.ts","../src/protocol/sse-parser.ts","../src/protocol/normalizer.ts","../src/protocol/accumulator.ts","../src/protocol/errors.ts","../src/protocol/seg.ts"],"names":["key","p","str"],"mappings":";AA6BO,IAAM,gBAAA,GAAmB;AAyUzB,IAAM,oBAAA,GAAuB;AAAA,EAClC,YAAA;AAAA,EACA,WAAA;AAAA,EACA;AACF;AAIO,SAAS,gBACd,KAAA,EAC6D;AAC7D,EAAA,OAAQ,oBAAA,CAA2C,QAAA,CAAS,KAAA,CAAM,IAAI,CAAA;AACxE;;;ACnVO,SAAS,sBAAsB,OAAA,EAA2B;AAC/D,EAAA,MAAM,MAAgB,EAAC;AACvB,EAAA,IAAI,KAAA,GAAQ,CAAA;AACZ,EAAA,IAAI,QAAA,GAAW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AAA,EAAM,GAAA,CAAI,OAAO,CAAA;AAC5E,EAAA,MAAM,GAAA,GAAM,mBAAA,CAAoB,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAA;AAChD,EAAA,OAAO,IAAI,GAAA,CAAI,OAAA,EAAS,MAAM,CAAA;AAChC;;;AClNA,IAAM,gCAAgB,IAAI,GAAA,CAAI,CAAC,EAAA,EAAI,GAAA,EAAK,IAAI,CAAC,CAAA;AAO7C,IAAM,SAAA,GAAY,GAAA;AAElB,SAAS,MAAA,CAAO,OAAe,MAAA,EAAuB;AACpD,EAAA,MAAM,IAAI,eAAA;AAAA,IACR,GAAG,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,0CAA0C,MAAM,CAAA,sFAAA,CAAA;AAAA,IAExE,EAAE,IAAA,EAAM,uBAAA,EAAyB,IAAA,EAAM,CAAA,EAAG,QAAQ,CAAA;AAAE,GACtD;AACF;AAGO,SAAS,IAAI,KAAA,EAAwB;AAC1C,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,KAAA,KAAU,MAAA,EAAW;AACzC,IAAA,MAAA,CAAO,MAAA,CAAO,KAAK,CAAA,EAAG,iEAAiE,CAAA;AAAA,EACzF;AACA,EAAA,MAAM,IAAA,GAAO,OAAO,KAAK,CAAA;AACzB,EAAA,IAAI,aAAA,CAAc,GAAA,CAAI,IAAI,CAAA,EAAG;AAC3B,IAAA,MAAA,CAAO,MAAM,2DAA2D,CAAA;AAAA,EAC1E;AACA,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,SAAS,CAAA,EAAG;AAC5B,IAAA,MAAA,CAAO,MAAM,gEAAgE,CAAA;AAAA,EAC/E;AACA,EAAA,OAAO,mBAAmB,IAAI,CAAA;AAChC","file":"chunk-CURNMC4F.js","sourcesContent":["/**\n * @m8tes/react — normalized PUBLIC stream event model.\n *\n * The m8tes V2 backend emits Claude-native FLAT SSE frames (`content_block_delta`,\n * `tool_use`, `permission_request`, `done`, ...). The normalizer (`normalizer.ts`)\n * maps each wire frame to ZERO or MORE events of this stable, versioned\n * discriminated union, keyed on `type`.\n *\n * Type discriminants follow the Vercel AI SDK v5 kebab-case idiom where semantics\n * align (`text-*`, `reasoning-*`, `tool-input-*`, `tool-output-available`) so a\n * future `@m8tes/ai-sdk` adapter maps cleanly. They DIVERGE where m8tes semantics\n * are first-class and have no vanilla-`useChat` analog: human-in-the-loop\n * `approval-request` / `question`, and run rejoin/replay (`run-start` carries\n * runId/runUuid; every terminal path is explicit).\n *\n * Every event carries:\n * - `seq`: a client-assigned monotonic counter. The wire exposes NO SSE `id:`\n * and NO per-event sequence number, so this is assigned by the normalizer and\n * is NOT a dedupe key (see `normalizer.ts` for the domain-id dedupe strategy).\n * - `raw`: the unmodified wire frame, for forward-compatibility.\n *\n * Frames that normalize to nothing renderable (`: keep-alive`, `keep-alive`,\n * `ping`, the duplicate `metadata` preamble frame, `RUNNER_DIAG`, etc.) are\n * dropped by the normalizer and never enter this union.\n *\n * This is a PUBLIC PROTOCOL: once shipped, names are semver-stable. Bump\n * `PROTOCOL_VERSION` on any breaking change to the shape.\n */\n\nexport const PROTOCOL_VERSION = \"m8tes.stream.v2\" as const;\nexport type ProtocolVersion = typeof PROTOCOL_VERSION;\n\n/** Tool/approval state machine (superset of AI SDK v5 tool-part states + HITL). */\nexport type ToolState =\n | \"input-streaming\" // tool-input-start/-delta seen; args still partial JSON\n | \"input-available\" // full input object resolved (standalone tool_use)\n | \"awaiting-approval\" // paused on the m8tes permission gate (HITL)\n | \"output-available\" // tool_result received, not an error\n | \"output-error\" // tool_result with is_error === true\n | \"denied\"; // approval was denied; tool never executed\n\n/** Coarse run status surfaced to the UI. */\nexport type RunStatus =\n | \"connecting\" // sandbox-connecting\n | \"running\" // metadata / message stream flowing\n | \"awaiting_approval\" // paused on a tool permission gate\n | \"awaiting_input\" // paused on AskUserQuestion\n | \"complete\" // done, completion_state === \"complete\"\n | \"incomplete\" // done, completion_state !== \"complete\"\n | \"error\" // terminal error\n | \"cancelled\"; // terminal cancellation\n\nexport interface BaseEvent {\n type: string;\n /** Client-assigned, monotonic per stream. There is NO wire sequence id. */\n seq: number;\n /** The unmodified wire frame this event was normalized from. */\n raw: Record<string, unknown>;\n}\n\n/* ---------- Run lifecycle (m8tes-first-class) ---------- */\n\n/** From the first `metadata` frame. Re-applied (idempotently) on every rejoin. */\nexport interface RunStartEvent extends BaseEvent {\n type: \"run-start\";\n protocolVersion: ProtocolVersion;\n runId: number | null;\n runUuid: string | null;\n mode: \"task\" | \"chat\";\n agentName?: string;\n instanceId?: number;\n taskId?: number;\n status?: string;\n sandbox?: { id: string | null; enabled: boolean };\n}\n\n/** Coarse status transitions (sandbox connect, metadata.status, pause entry). */\nexport interface RunStatusEvent extends BaseEvent {\n type: \"run-status\";\n status: RunStatus;\n message?: string;\n sandboxId?: string | null;\n durationMs?: number;\n}\n\n/** From `run_metrics`. */\nexport interface RunMetricsEvent extends BaseEvent {\n type: \"run-metrics\";\n model: string;\n executionTimeMs: number;\n inputTokens: number;\n outputTokens: number;\n costUsd: number | null; // claude_token_cost_usd\n sdkCostUsd: number | null; // sdk_total_cost_usd (authoritative)\n stopReason: string | null;\n completionState: string;\n unresolvedToolUseIds: string[];\n messageCount: number;\n /** present only when completionState !== \"complete\" */\n diagnostics?: Record<string, unknown>;\n}\n\n/** Terminal success path. From `done`. completionState !== \"complete\" => incomplete run. */\nexport interface RunFinishEvent extends BaseEvent {\n type: \"run-finish\";\n status: \"complete\" | \"incomplete\";\n completionState: string;\n unresolvedToolUseIds: string[];\n stopReason: string | null;\n terminalCompletionSeen: boolean;\n messageCount: number;\n}\n\n/** Structured failure codes carried on the wire as a dedicated `type`. */\nexport type RunErrorCode =\n | \"SANDBOX_BOOT_TIMEOUT\"\n | \"SANDBOX_QUOTA_EXHAUSTED\"\n | \"SANDBOX_UNAVAILABLE\"\n | \"SNAPSHOT_VERSION_MISMATCH\"\n | \"AGENT_RUNNER_DIED\"\n | \"RUNNER_LIFECYCLE_ERROR\";\n\n/** Terminal failure path. From `error`, `sdk_error`, `AGENT_RUNNER_DIED`, SANDBOX_*, SNAPSHOT_VERSION_MISMATCH. */\nexport interface RunErrorEvent extends BaseEvent {\n type: \"run-error\";\n error: string;\n message: string;\n /** structured failure code when the wire type was a coded failure, else null */\n code: RunErrorCode | null;\n fatal: true;\n /** HTTP status when the failure was an API (non-stream) error, e.g. 402/429 */\n apiStatus?: number;\n /** v2 envelope `error.details` — carries machine codes like\n * `error_code: \"END_USER_RATE_LIMITED\"` plus `retry_after`/`period_end` */\n apiDetails?: Record<string, unknown>;\n}\n\n/** Terminal cancellation. From `cancelled`. */\nexport interface RunCancelledEvent extends BaseEvent {\n type: \"run-cancelled\";\n runId?: number | null;\n}\n\n/* ---------- Message lifecycle ---------- */\n\nexport interface MessageStartEvent extends BaseEvent {\n type: \"message-start\";\n messageId: string;\n role: \"assistant\";\n usage?: { inputTokens: number; outputTokens: number };\n}\n\n/** From `message_stop` or `message_complete`. */\nexport interface MessageEndEvent extends BaseEvent {\n type: \"message-end\";\n messageId: string;\n usage?: { inputTokens: number; outputTokens: number };\n}\n\n/* ---------- Text ---------- */\n\nexport interface TextStartEvent extends BaseEvent {\n type: \"text-start\";\n id: string; // canonical block id (dedupe key)\n messageId: string;\n}\nexport interface TextDeltaEvent extends BaseEvent {\n type: \"text-delta\";\n id: string; // block id\n delta: string;\n messageId: string;\n}\nexport interface TextEndEvent extends BaseEvent {\n type: \"text-end\"; // inferred from content_block_stop on a text block\n id: string;\n messageId: string;\n}\n\n/* ---------- Reasoning (thinking + reasoning, one first-class part) ---------- */\n\nexport interface ReasoningStartEvent extends BaseEvent {\n type: \"reasoning-start\";\n id: string;\n messageId: string;\n}\nexport interface ReasoningDeltaEvent extends BaseEvent {\n type: \"reasoning-delta\";\n id: string;\n delta: string;\n messageId: string;\n}\nexport interface ReasoningEndEvent extends BaseEvent {\n type: \"reasoning-end\";\n id: string;\n messageId: string;\n}\n\n/* ---------- Plan (m8tes plan-mode; no AI SDK analog) ---------- */\n\nexport interface PlanStartEvent extends BaseEvent {\n type: \"plan-start\";\n id: string;\n messageId: string;\n}\nexport interface PlanDeltaEvent extends BaseEvent {\n type: \"plan-delta\";\n id: string;\n delta: string;\n messageId: string;\n}\nexport interface PlanEndEvent extends BaseEvent {\n type: \"plan-end\";\n id: string;\n messageId: string;\n}\n\n/* ---------- Tool-call lifecycle (AI SDK v5 idiom) ---------- */\n\nexport interface ToolInputStartEvent extends BaseEvent {\n type: \"tool-input-start\";\n toolCallId: string; // dedupe key\n toolName: string;\n messageId: string;\n state: \"input-streaming\";\n}\nexport interface ToolInputDeltaEvent extends BaseEvent {\n type: \"tool-input-delta\";\n toolCallId: string;\n inputTextDelta: string; // incremental partial-JSON STRING\n state: \"input-streaming\";\n}\nexport interface ToolInputAvailableEvent extends BaseEvent {\n type: \"tool-input-available\";\n toolCallId: string;\n toolName: string;\n input: unknown; // parsed object (from standalone tool_use.input)\n state: \"input-available\";\n}\nexport interface ToolOutputAvailableEvent extends BaseEvent {\n type: \"tool-output-available\";\n toolCallId: string; // from tool_result.tool_use_id\n output: unknown; // content (preferred) or result\n isError: boolean; // from is_error\n state: \"output-available\" | \"output-error\";\n}\n\n/* ---------- Human-in-the-loop (first-class, unlike vanilla useChat) ---------- */\n\n/** Tool approval gate. From `awaiting_approval` (toolName !== \"AskUserQuestion\") or `permission_request`. */\nexport interface ApprovalRequestEvent extends BaseEvent {\n type: \"approval-request\";\n requestId: string; // dedupe key\n toolCallId?: string; // the paused tool_use id when correlatable\n toolName: string;\n toolInput: unknown;\n timeoutSeconds: number;\n}\n/** Derived on resume / from the answer round-trip; surfaced for state reconciliation. */\nexport interface ApprovalResolvedEvent extends BaseEvent {\n type: \"approval-resolved\";\n requestId: string;\n resolved: \"approved\" | \"denied\";\n}\n\n/** AskUserQuestion gate. From `awaiting_approval` where toolName === \"AskUserQuestion\". */\nexport interface QuestionOption {\n label: string;\n description?: string;\n}\nexport interface QuestionItem {\n question: string;\n /** Real wire options are `{label, description}` objects; the normalizer also\n * coerces bare-string options into `{label}` defensively. */\n options?: QuestionOption[];\n [k: string]: unknown;\n}\nexport interface QuestionEvent extends BaseEvent {\n type: \"question\";\n requestId: string; // dedupe key\n toolCallId: string; // AskUserQuestion tool_use id; answer returns as tool-output-available for this id\n questions: QuestionItem[];\n timeoutSeconds: number;\n}\n\n/* ---------- Sandbox + non-fatal notices ---------- */\n\n/** From `sandbox-connecting` / `sandbox-connected`. (Fatal sandbox failures => RunErrorEvent with `code`.) */\nexport interface SandboxStatusEvent extends BaseEvent {\n type: \"sandbox-status\";\n phase: \"connecting\" | \"connected\";\n message: string;\n runId: number | null;\n sandboxId?: string | null;\n durationMs?: number;\n}\n\n/** Non-fatal diagnostics: stderr, mcp_error/mcp_auth_failed (warning), rate_limit, system_message. */\nexport interface NoticeEvent extends BaseEvent {\n type: \"notice\";\n level: \"info\" | \"warning\";\n source: \"stderr\" | \"mcp\" | \"rate_limit\" | \"system\";\n message: string;\n detail?: string;\n}\n\n/** From `compact_boundary`: the SDK summarized the conversation history. */\nexport interface CompactBoundaryEvent extends BaseEvent {\n type: \"compact-boundary\";\n trigger: \"manual\" | \"auto\";\n preTokens: number;\n}\n\n/* ---------- Passthrough ---------- */\n\n/**\n * Any wire type with no normalized mapping (`sdk_content_snapshot`, `user_message`,\n * `compact_boundary`, and future/unknown types). `raw` is preserved so consumers\n * and a newer normalizer can recover the original. Forward-compat: a new backend\n * event surfaces here instead of crashing.\n */\nexport interface UnknownEvent extends BaseEvent {\n type: \"unknown\";\n wireType: string; // the original wire `type` string (\"\" if absent)\n}\n\nexport type M8tesStreamEvent =\n | RunStartEvent\n | RunStatusEvent\n | RunMetricsEvent\n | RunFinishEvent\n | RunErrorEvent\n | RunCancelledEvent\n | MessageStartEvent\n | MessageEndEvent\n | TextStartEvent\n | TextDeltaEvent\n | TextEndEvent\n | ReasoningStartEvent\n | ReasoningDeltaEvent\n | ReasoningEndEvent\n | PlanStartEvent\n | PlanDeltaEvent\n | PlanEndEvent\n | ToolInputStartEvent\n | ToolInputDeltaEvent\n | ToolInputAvailableEvent\n | ToolOutputAvailableEvent\n | ApprovalRequestEvent\n | ApprovalResolvedEvent\n | QuestionEvent\n | SandboxStatusEvent\n | NoticeEvent\n | CompactBoundaryEvent\n | UnknownEvent;\n\nexport type M8tesStreamEventType = M8tesStreamEvent[\"type\"];\n\n/** Terminal events end a stream. */\nexport const TERMINAL_EVENT_TYPES = [\n \"run-finish\",\n \"run-error\",\n \"run-cancelled\",\n] as const satisfies readonly M8tesStreamEventType[];\nexport type TerminalEventType = (typeof TERMINAL_EVENT_TYPES)[number];\n\n/** True for the three terminal event types. */\nexport function isTerminalEvent(\n event: M8tesStreamEvent,\n): event is RunFinishEvent | RunErrorEvent | RunCancelledEvent {\n return (TERMINAL_EVENT_TYPES as readonly string[]).includes(event.type);\n}\n","/**\n * SSE wire decoder: raw bytes/text -> wire frame objects.\n *\n * Layer 1 of the pipeline (Layer 2 is `normalizer.ts`). This module ONLY knows\n * the SSE envelope + JSON, never the m8tes event semantics.\n *\n * chunk(s) ─push─► [ frame split on blank line ] ─► [ data: lines ]\n * ─► [ concatenated-JSON split ] ─► JSON.parse ─► wire object\n *\n * Wire facts it handles (from the streaming contract):\n * - Frames are separated by a blank line; `\\r\\n` is normalized to `\\n`.\n * - A line starting with `:` is an SSE comment (keepalive) — ignored.\n * - A frame may carry one or more `data:` lines (joined with `\\n` per spec).\n * - A single `data:` payload may glue MULTIPLE complete JSON objects together\n * (observed in the app stream); they are split with a string-aware brace\n * scanner — NOT a naive `}{` regex, which breaks on braces inside strings.\n * - Invalid JSON in a completed frame is DROPPED (reported via `onMalformed`),\n * never thrown — a corrupt frame must not kill the stream (contract §7).\n */\n\nexport interface SseParserOptions {\n /**\n * Called for each `data:` payload (or split piece) that fails to parse as JSON.\n * Default: no-op. Wire this to telemetry; do NOT throw from it.\n */\n onMalformed?: (rawPayload: string, error: unknown) => void;\n}\n\ntype WireFrame = Record<string, unknown>;\n\n/** Split a payload into top-level JSON object/array substrings, string-aware. */\nexport function splitConcatenatedJson(payload: string): string[] {\n const out: string[] = [];\n let depth = 0;\n let inString = false;\n let escaped = false;\n let start = -1;\n let lastEnd = 0; // index just past the last emitted top-level value\n\n for (let i = 0; i < payload.length; i++) {\n const ch = payload.charAt(i);\n if (start === -1) {\n if (ch === \"{\" || ch === \"[\") {\n start = i;\n depth = 1;\n inString = false;\n escaped = false;\n }\n continue; // skip whitespace/junk before a value\n }\n if (inString) {\n if (escaped) escaped = false;\n else if (ch === \"\\\\\") escaped = true;\n else if (ch === '\"') inString = false;\n continue;\n }\n if (ch === '\"') {\n inString = true;\n } else if (ch === \"{\" || ch === \"[\") {\n depth++;\n } else if (ch === \"}\" || ch === \"]\") {\n depth--;\n if (depth === 0) {\n out.push(payload.slice(start, i + 1));\n start = -1;\n lastEnd = i + 1;\n }\n }\n }\n\n if (start !== -1) {\n // Unterminated trailing object: emit so it fails parse loudly (reported).\n out.push(payload.slice(start));\n } else {\n // Residue after the last complete value (or a bare primitive when no value\n // was found): emit it so corruption reaches onMalformed instead of vanishing.\n const tail = payload.slice(lastEnd).trim();\n if (tail !== \"\") out.push(tail);\n }\n return out;\n}\n\n/** Extract the joined `data:` payload from one SSE frame, or null if it has none. */\nfunction frameDataPayload(frameText: string): string | null {\n const dataLines: string[] = [];\n for (const rawLine of frameText.split(\"\\n\")) {\n const line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n if (line === \"\" || line.charAt(0) === \":\") continue; // blank / comment\n if (line.startsWith(\"data:\")) {\n let value = line.slice(5);\n if (value.charAt(0) === \" \") value = value.slice(1); // drop one space\n dataLines.push(value);\n }\n // other SSE fields (event:/id:/retry:) are unused by m8tes — ignore.\n }\n if (dataLines.length === 0) return null;\n return dataLines.join(\"\\n\");\n}\n\nfunction parsePayload(\n payload: string,\n onMalformed: SseParserOptions[\"onMalformed\"],\n): WireFrame[] {\n const out: WireFrame[] = [];\n for (const candidate of splitConcatenatedJson(payload)) {\n try {\n const parsed: unknown = JSON.parse(candidate);\n if (parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n out.push(parsed as WireFrame);\n } else {\n // Arrays / primitives are not valid wire frames (flat objects only).\n onMalformed?.(candidate, new Error(\"frame is not a JSON object\"));\n }\n } catch (err) {\n onMalformed?.(candidate, err);\n }\n }\n return out;\n}\n\n/**\n * Stateful streaming decoder. Feed it response-body chunks (any size, split\n * mid-frame); it returns the wire frames completed by each chunk. Call `flush()`\n * once the stream ends to drain a trailing frame that had no closing blank line.\n */\nexport function createSseDecoder(opts: SseParserOptions = {}) {\n // `buf` holds normalized text plus, possibly, a single trailing raw `\\r` that\n // we cannot yet normalize: a CRLF can be split across chunk boundaries\n // (`...\\r` | `\\n...`). Eagerly turning a lone trailing `\\r` into `\\n` would\n // fabricate a `\\n\\n` frame boundary and corrupt a multi-line frame.\n let buf = \"\";\n\n function ingest(chunk: string): void {\n buf += chunk;\n let tail = \"\";\n if (buf.endsWith(\"\\r\")) {\n tail = \"\\r\"; // hold it for the next chunk\n buf = buf.slice(0, -1);\n }\n buf = buf.replace(/\\r\\n?/g, \"\\n\") + tail;\n }\n\n function drain(final: boolean): WireFrame[] {\n const frames: WireFrame[] = [];\n let sep = buf.indexOf(\"\\n\\n\");\n while (sep !== -1) {\n const frameText = buf.slice(0, sep);\n buf = buf.slice(sep + 2);\n const payload = frameDataPayload(frameText);\n if (payload !== null) frames.push(...parsePayload(payload, opts.onMalformed));\n sep = buf.indexOf(\"\\n\\n\");\n }\n if (final && buf.trim() !== \"\") {\n const payload = frameDataPayload(buf);\n if (payload !== null) frames.push(...parsePayload(payload, opts.onMalformed));\n buf = \"\";\n }\n return frames;\n }\n\n return {\n /** Feed a chunk; returns the wire frames it completed. */\n push(chunk: string): WireFrame[] {\n ingest(chunk);\n return drain(false);\n },\n /** Flush a trailing unterminated frame at end-of-stream. */\n flush(): WireFrame[] {\n if (buf.endsWith(\"\\r\")) buf = `${buf.slice(0, -1)}\\n`; // EOL at end-of-stream\n return drain(true);\n },\n };\n}\n\n/** Convenience: parse a whole SSE string into wire frames (used by fixtures/tests). */\nexport function parseSse(text: string, opts: SseParserOptions = {}): WireFrame[] {\n const dec = createSseDecoder(opts);\n return [...dec.push(text), ...dec.flush()];\n}\n","/**\n * Normalizer: wire frames -> public M8tesStreamEvent[].\n *\n * Layer 2 of the pipeline (Layer 1 = `sse-parser.ts`). Each wire frame maps to\n * ZERO or MORE public events. The normalizer owns:\n * - `seq`: a monotonic counter stamped on every emitted event (no wire seq id).\n * - dedupe: a domain-id `open`/`seen` ledger so a `/stream` rejoin that\n * re-streams blocks + re-sends a message_snapshot + re-sends a pending\n * permission_request renders EXACTLY ONCE (streaming contract §dedupeStrategy).\n *\n * One normalizer instance is kept ALIVE across a reconnect (the hook reuses it),\n * so `seen` persists and replayed content is dropped. Idempotent-apply rules:\n * - START events: skip if the key is already open or seen.\n * - DELTA events: drop if the key is in `seen` (finalized) — a replayed delta\n * for a closed block. A bare key not yet seen is lazily opened (tolerates a\n * trimmed replay prefix).\n * - END / result / terminal / approval events: finalize, move key to `seen`;\n * a second occurrence is a no-op.\n *\n * Unknown/unmapped wire types pass through as `UnknownEvent` (never throw).\n */\n\nimport {\n PROTOCOL_VERSION,\n type M8tesStreamEvent,\n type QuestionItem,\n type QuestionOption,\n type RunErrorCode,\n} from \"./events\";\n\ntype WireFrame = Record<string, unknown>;\n/** Distributive Omit — preserves each union member's discriminant-specific\n * fields (plain `Omit<Union, K>` collapses a union to its common keys). */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\ntype Emitted = DistributiveOmit<M8tesStreamEvent, \"seq\" | \"raw\">;\n\nconst ASK_USER_QUESTION = \"AskUserQuestion\";\n\nconst SANDBOX_ERROR_CODES: ReadonlySet<string> = new Set<RunErrorCode>([\n \"SANDBOX_BOOT_TIMEOUT\",\n \"SANDBOX_QUOTA_EXHAUSTED\",\n \"SANDBOX_UNAVAILABLE\",\n \"SNAPSHOT_VERSION_MISMATCH\",\n \"AGENT_RUNNER_DIED\",\n \"RUNNER_LIFECYCLE_ERROR\",\n]);\n\n/* ---- tiny safe field accessors over the loosely-typed wire ---- */\nconst str = (o: WireFrame, k: string): string | undefined =>\n typeof o[k] === \"string\" ? (o[k] as string) : undefined;\nconst num = (o: WireFrame, k: string): number | undefined =>\n typeof o[k] === \"number\" ? (o[k] as number) : undefined;\nconst bool = (o: WireFrame, k: string): boolean | undefined =>\n typeof o[k] === \"boolean\" ? (o[k] as boolean) : undefined;\nconst obj = (o: WireFrame, k: string): WireFrame | undefined => {\n const v = o[k];\n return v !== null && typeof v === \"object\" && !Array.isArray(v)\n ? (v as WireFrame)\n : undefined;\n};\nconst arr = (o: WireFrame, k: string): unknown[] | undefined =>\n Array.isArray(o[k]) ? (o[k] as unknown[]) : undefined;\n\ntype BlockKind = \"text\" | \"reasoning\" | \"plan\" | \"tool_use\" | \"other\";\n\nfunction blockKindFromType(t: string | undefined): BlockKind {\n switch (t) {\n case \"text\":\n return \"text\";\n case \"thinking\":\n case \"reasoning\":\n return \"reasoning\";\n case \"plan\":\n return \"plan\";\n case \"tool_use\":\n case \"server_tool_use\":\n return \"tool_use\";\n default:\n return \"other\";\n }\n}\n\nconst blockEndType = {\n text: \"text-end\",\n reasoning: \"reasoning-end\",\n plan: \"plan-end\",\n} as const;\nconst blockStartType = {\n text: \"text-start\",\n reasoning: \"reasoning-start\",\n plan: \"plan-start\",\n} as const;\nconst blockDeltaType = {\n text: \"text-delta\",\n reasoning: \"reasoning-delta\",\n plan: \"plan-delta\",\n} as const;\n\nexport interface Normalizer {\n /** Map one wire frame to zero+ public events (seq-stamped, in order). */\n push(frame: WireFrame): M8tesStreamEvent[];\n /** Discard all dedupe/lifecycle state (e.g. starting a brand-new run). */\n reset(): void;\n}\n\nexport function createNormalizer(): Normalizer {\n let seq = 0;\n let open = new Set<string>();\n let seen = new Set<string>();\n let blockKind = new Map<string, BlockKind>();\n let currentMessageId: string | null = null;\n let activeTextBlockId: string | null = null;\n let lastToolId: string | null = null; // last non-question tool_use block id\n let lastQuestionToolId: string | null = null;\n // Whether any text/reasoning/plan content streamed this run — an id-less\n // snapshot block then duplicates it (the runtime only synthesizes a content\n // snapshot when nothing streamed). Run-global on purpose: replayed blocks can\n // arrive before their message_start, so a per-message key can mismatch.\n let anyContentStreamed = false;\n let runStartEmitted = false;\n let terminalEmitted = false;\n\n function reset() {\n seq = 0;\n open = new Set();\n seen = new Set();\n blockKind = new Map();\n currentMessageId = null;\n activeTextBlockId = null;\n lastToolId = null;\n lastQuestionToolId = null;\n anyContentStreamed = false;\n runStartEmitted = false;\n terminalEmitted = false;\n }\n\n function emitContentBlockStart(f: WireFrame, out: Emitted[]): void {\n const id = str(f, \"id\");\n if (!id) return;\n const kind = blockKindFromType(str(f, \"block_type\") ?? str(f, \"type\"));\n const key = kind === \"tool_use\" ? `tool:${id}` : `block:${id}`;\n if (open.has(key) || seen.has(key)) return; // replayed start\n blockKind.set(id, kind);\n if (kind === \"tool_use\") {\n const name = str(f, \"name\") ?? \"\";\n if (name === ASK_USER_QUESTION) lastQuestionToolId = id;\n else lastToolId = id;\n open.add(key);\n out.push({\n type: \"tool-input-start\",\n toolCallId: id,\n toolName: name,\n messageId: currentMessageId ?? \"\",\n state: \"input-streaming\",\n });\n } else if (kind === \"text\" || kind === \"reasoning\" || kind === \"plan\") {\n open.add(key);\n if (kind === \"text\") activeTextBlockId = id;\n anyContentStreamed = true;\n out.push({\n type: blockStartType[kind],\n id,\n messageId: currentMessageId ?? \"\",\n });\n }\n // kind \"other\" (tool_result block start, etc.): no public start event.\n }\n\n function emitContentBlockDelta(f: WireFrame, out: Emitted[]): void {\n const id = str(f, \"id\");\n if (!id) return;\n const delta = obj(f, \"delta\");\n if (!delta) return;\n const dType = str(delta, \"type\");\n\n if (dType === \"input_json_delta\") {\n const key = `tool:${id}`;\n if (seen.has(key)) return; // finalized tool, replayed delta\n const partial = str(delta, \"partial_json\") ?? \"\";\n if (partial === \"\") return;\n if (!open.has(key)) {\n // tolerate a trimmed tool start: lazily open so content_block_stop\n // finalizes tool:{id} into `seen` and a rejoin's replayed deltas drop.\n open.add(key);\n blockKind.set(id, \"tool_use\");\n }\n out.push({\n type: \"tool-input-delta\",\n toolCallId: id,\n inputTextDelta: partial,\n state: \"input-streaming\",\n });\n return;\n }\n\n let kind: \"text\" | \"reasoning\" | \"plan\" | null = null;\n if (dType === \"text_delta\") kind = \"text\";\n else if (dType === \"thinking_delta\" || dType === \"reasoning_delta\")\n kind = \"reasoning\";\n else if (dType === \"plan_delta\") kind = \"plan\";\n if (!kind) return; // signature_delta, output_json_delta, etc. -> ignore\n\n const key = `block:${id}`;\n if (seen.has(key)) return; // finalized block, replayed delta\n // Content key varies by delta type on the real wire (mirrors the runtime\n // accumulator): thinking_delta carries `thinking`, plan_delta carries\n // `text` or `plan`, text_delta carries `text`.\n const text =\n kind === \"reasoning\"\n ? (str(delta, \"thinking\") ?? str(delta, \"text\") ?? \"\")\n : kind === \"plan\"\n ? (str(delta, \"text\") ?? str(delta, \"plan\") ?? \"\")\n : (str(delta, \"text\") ?? \"\");\n if (text === \"\") return; // empty delta is a no-op\n if (!open.has(key)) {\n // tolerate a trimmed replay prefix: lazily open the block\n open.add(key);\n blockKind.set(id, kind);\n if (kind === \"text\") activeTextBlockId = id;\n anyContentStreamed = true;\n }\n out.push({ type: blockDeltaType[kind], id, delta: text, messageId: currentMessageId ?? \"\" });\n }\n\n function emitContentBlockStop(f: WireFrame, out: Emitted[]): void {\n const id = str(f, \"id\");\n if (!id) return;\n const kind = blockKind.get(id) ?? \"other\";\n if (kind === \"tool_use\") {\n seen.add(`tool:${id}`);\n open.delete(`tool:${id}`);\n return; // input streaming closed; resolved input arrives via standalone tool_use\n }\n if (kind === \"text\" || kind === \"reasoning\" || kind === \"plan\") {\n const key = `block:${id}`;\n open.delete(key);\n if (seen.has(key)) return; // replayed stop for an already-finalized block\n seen.add(key);\n if (activeTextBlockId === id) activeTextBlockId = null;\n out.push({ type: blockEndType[kind], id, messageId: currentMessageId ?? \"\" });\n }\n }\n\n function emitMessageDelta(f: WireFrame, out: Emitted[]): void {\n const delta = obj(f, \"delta\");\n if (!delta) return;\n const text = str(delta, \"text\") ?? \"\";\n if (text === \"\" || !activeTextBlockId) return; // empty / no active block (replay)\n const key = `block:${activeTextBlockId}`;\n if (seen.has(key)) return;\n out.push({\n type: \"text-delta\",\n id: activeTextBlockId,\n delta: text,\n messageId: currentMessageId ?? \"\",\n });\n }\n\n function emitStandaloneToolUse(f: WireFrame, out: Emitted[]): void {\n const id = str(f, \"id\");\n if (!id) return;\n const name = str(f, \"name\") ?? \"\";\n if (name === ASK_USER_QUESTION) lastQuestionToolId = id;\n else if (name) lastToolId = id;\n if (\"input\" in f) {\n const key = `toolinput:${id}`;\n if (seen.has(key)) return;\n seen.add(key);\n out.push({\n type: \"tool-input-available\",\n toolCallId: id,\n toolName: name,\n input: f[\"input\"],\n state: \"input-available\",\n });\n } else {\n const partial = str(f, \"input_text\");\n if (partial && !seen.has(`tool:${id}`)) {\n out.push({\n type: \"tool-input-delta\",\n toolCallId: id,\n inputTextDelta: partial,\n state: \"input-streaming\",\n });\n }\n }\n }\n\n function emitToolResult(f: WireFrame, out: Emitted[]): void {\n const id = str(f, \"tool_use_id\");\n if (!id) return;\n const key = `tool_result:${id}`;\n if (seen.has(key)) return;\n seen.add(key);\n const isError = bool(f, \"is_error\") ?? false;\n const output = \"content\" in f ? f[\"content\"] : f[\"result\"];\n out.push({\n type: \"tool-output-available\",\n toolCallId: id,\n output,\n isError,\n state: isError ? \"output-error\" : \"output-available\",\n });\n }\n\n /** awaiting_approval / permission_request -> approval-request OR question. */\n function emitApprovalGate(f: WireFrame, out: Emitted[]): void {\n const requestId = str(f, \"request_id\");\n if (!requestId) return;\n const toolName = str(f, \"tool_name\") ?? \"\";\n const timeoutSeconds = num(f, \"timeout_seconds\") ?? 0;\n const toolInput = f[\"tool_input\"];\n if (toolName === ASK_USER_QUESTION) {\n const key = `question:${requestId}`;\n if (seen.has(key)) return;\n seen.add(key);\n const ti = obj(f, \"tool_input\");\n const questions = ((ti && arr(ti, \"questions\")) ?? []).flatMap((q): QuestionItem[] => {\n if (q === null || typeof q !== \"object\") return [];\n const qq = q as WireFrame;\n // Real wire options are `{label, description}` objects; coerce bare\n // strings defensively and drop anything without a label.\n const options = (arr(qq, \"options\") ?? []).flatMap((o): QuestionOption[] => {\n if (typeof o === \"string\") return [{ label: o }];\n if (o === null || typeof o !== \"object\") return [];\n const label = str(o as WireFrame, \"label\");\n if (!label) return [];\n const description = str(o as WireFrame, \"description\");\n return [description === undefined ? { label } : { label, description }];\n });\n return [{ ...qq, question: str(qq, \"question\") ?? \"\", options }];\n });\n out.push({\n type: \"question\",\n requestId,\n toolCallId: str(f, \"tool_use_id\") ?? lastQuestionToolId ?? \"\",\n questions,\n timeoutSeconds,\n });\n } else {\n const key = `approval:${requestId}`;\n if (seen.has(key)) return;\n seen.add(key);\n out.push({\n type: \"approval-request\",\n requestId,\n // The frame's own tool_use_id is authoritative (live awaiting_approval\n // carries it; rejoin permission_request does too as of the run_join\n // fix). The last-tool inference is only a fallback — with PARALLEL tool\n // calls it can name the wrong tool.\n toolCallId: str(f, \"tool_use_id\") ?? lastToolId ?? undefined,\n toolName,\n toolInput,\n timeoutSeconds,\n });\n }\n }\n\n /** message_snapshot: reconstruct ONLY blocks not already rendered. Real\n * snapshot text/thinking/plan blocks carry NO `id` (they're the runtime\n * accumulator's typed blocks, e.g. `{\"type\":\"thinking\",\"thinking\":...}`) —\n * for those we synthesize a stable positional key and reconstruct only when\n * this message streamed no content (the synthetic final snapshot on the\n * CLI-error path, or a fully-trimmed rejoin); if content DID stream, an\n * id-less snapshot block is a copy of it and is dropped. */\n function emitSnapshot(f: WireFrame, out: Emitted[]): void {\n const messageId = str(f, \"message_id\") ?? currentMessageId ?? \"\";\n const blocks = arr(f, \"content_blocks\") ?? [];\n for (let i = 0; i < blocks.length; i++) {\n const raw = blocks[i];\n if (raw === null || typeof raw !== \"object\") continue;\n const b = raw as WireFrame;\n const bType = str(b, \"type\");\n const kind = blockKindFromType(bType);\n if (kind === \"text\" || kind === \"reasoning\" || kind === \"plan\") {\n let id = str(b, \"id\");\n if (!id) {\n if (anyContentStreamed) continue; // copy of already-streamed content\n id = `${messageId}:snap:${i}`; // stable across a replayed snapshot\n }\n const key = `block:${id}`;\n if (seen.has(key)) continue; // already finalized -> drop the snapshot copy\n if (open.has(key)) {\n // streamed but not yet closed (orphan / trimmed stop): finalize ONLY,\n // do not re-emit start+content on top of what already rendered.\n open.delete(key);\n seen.add(key);\n if (activeTextBlockId === id) activeTextBlockId = null;\n out.push({ type: blockEndType[kind], id, messageId });\n continue;\n }\n // never seen: reconstruct from the snapshot (trimmed-prefix replay or\n // snapshot-only output). Content key varies by block type (runtime\n // accumulator shape): text -> `text`, thinking -> `thinking`, plan -> `plan`.\n seen.add(key);\n out.push({ type: blockStartType[kind], id, messageId });\n const text =\n kind === \"reasoning\"\n ? (str(b, \"thinking\") ?? str(b, \"text\") ?? \"\")\n : kind === \"plan\"\n ? (str(b, \"plan\") ?? str(b, \"text\") ?? \"\")\n : (str(b, \"text\") ?? \"\");\n if (text !== \"\") out.push({ type: blockDeltaType[kind], id, delta: text, messageId });\n out.push({ type: blockEndType[kind], id, messageId });\n } else if (bType === \"tool_use\") {\n const id = str(b, \"id\");\n if (!id || seen.has(`toolinput:${id}`)) continue;\n seen.add(`toolinput:${id}`);\n out.push({\n type: \"tool-input-available\",\n toolCallId: id,\n toolName: str(b, \"name\") ?? \"\",\n input: b[\"input\"],\n state: \"input-available\",\n });\n } else if (bType === \"tool_result\") {\n const id = str(b, \"tool_use_id\");\n if (!id || seen.has(`tool_result:${id}`)) continue;\n seen.add(`tool_result:${id}`);\n const isError = bool(b, \"is_error\") ?? false;\n out.push({\n type: \"tool-output-available\",\n toolCallId: id,\n output: \"content\" in b ? b[\"content\"] : b[\"result\"],\n isError,\n state: isError ? \"output-error\" : \"output-available\",\n });\n }\n }\n }\n\n function emitNotice(\n out: Emitted[],\n level: \"info\" | \"warning\",\n source: \"stderr\" | \"mcp\" | \"rate_limit\" | \"system\",\n message: string,\n detail?: string,\n ): void {\n out.push(detail === undefined ? { type: \"notice\", level, source, message } : { type: \"notice\", level, source, message, detail });\n }\n\n function handle(frame: WireFrame, out: Emitted[]): void {\n const type = str(frame, \"type\") ?? \"\";\n\n switch (type) {\n /* ---- dropped no-ops ---- */\n case \"keep-alive\":\n case \"ping\":\n case \"RUNNER_DIAG\":\n case \"sdk_init\":\n case \"sandbox_metrics\":\n return;\n\n /* ---- run lifecycle ---- */\n case \"metadata\": {\n if (runStartEmitted) return; // duplicate preamble / rejoin re-synth\n runStartEmitted = true;\n const sandboxId = str(frame, \"sandbox_id\") ?? null;\n const sandboxEnabled = bool(frame, \"sandbox_enabled\") ?? false;\n out.push({\n type: \"run-start\",\n protocolVersion: PROTOCOL_VERSION,\n runId: num(frame, \"run_id\") ?? null,\n runUuid: str(frame, \"run_uuid\") ?? null,\n mode: str(frame, \"mode\") === \"task\" ? \"task\" : \"chat\",\n ...(str(frame, \"agent_name\") ? { agentName: str(frame, \"agent_name\") } : {}),\n ...(num(frame, \"instance_id\") !== undefined ? { instanceId: num(frame, \"instance_id\") } : {}),\n ...(num(frame, \"task_id\") !== undefined ? { taskId: num(frame, \"task_id\") } : {}),\n ...(str(frame, \"status\") ? { status: str(frame, \"status\") } : {}),\n sandbox: { id: sandboxId, enabled: sandboxEnabled },\n });\n return;\n }\n case \"run_metrics\": {\n out.push({\n type: \"run-metrics\",\n model: str(frame, \"model\") ?? \"\",\n executionTimeMs: num(frame, \"execution_time_ms\") ?? 0,\n inputTokens: num(frame, \"input_tokens_used\") ?? 0,\n outputTokens: num(frame, \"output_tokens_used\") ?? 0,\n costUsd: num(frame, \"claude_token_cost_usd\") ?? null,\n sdkCostUsd: num(frame, \"sdk_total_cost_usd\") ?? null,\n stopReason: str(frame, \"stop_reason\") ?? null,\n completionState: str(frame, \"completion_state\") ?? \"\",\n unresolvedToolUseIds: (arr(frame, \"unresolved_tool_use_ids\") ?? []).filter(\n (x): x is string => typeof x === \"string\",\n ),\n messageCount: num(frame, \"message_count\") ?? 0,\n ...(obj(frame, \"diagnostics\") ? { diagnostics: obj(frame, \"diagnostics\") } : {}),\n });\n return;\n }\n case \"done\": {\n if (terminalEmitted) return;\n terminalEmitted = true;\n const completionState = str(frame, \"completion_state\") ?? \"complete\";\n out.push({\n type: \"run-finish\",\n status: completionState === \"complete\" ? \"complete\" : \"incomplete\",\n completionState,\n unresolvedToolUseIds: (arr(frame, \"unresolved_tool_use_ids\") ?? []).filter(\n (x): x is string => typeof x === \"string\",\n ),\n stopReason: str(frame, \"stop_reason\") ?? null,\n terminalCompletionSeen: bool(frame, \"terminal_completion_seen\") ?? false,\n messageCount: num(frame, \"message_count\") ?? 0,\n });\n return;\n }\n case \"cancelled\": {\n if (terminalEmitted) return;\n terminalEmitted = true;\n out.push({ type: \"run-cancelled\", runId: num(frame, \"run_id\") ?? null });\n return;\n }\n case \"error\":\n case \"AGENT_RUNNER_DIED\":\n case \"RUNNER_LIFECYCLE_ERROR\":\n case \"SANDBOX_BOOT_TIMEOUT\":\n case \"SANDBOX_QUOTA_EXHAUSTED\":\n case \"SANDBOX_UNAVAILABLE\":\n case \"SNAPSHOT_VERSION_MISMATCH\": {\n if (terminalEmitted) return;\n terminalEmitted = true;\n const code = SANDBOX_ERROR_CODES.has(type) ? (type as RunErrorCode) : null;\n out.push({\n type: \"run-error\",\n error: str(frame, \"error\") ?? str(frame, \"message\") ?? type,\n message: str(frame, \"message\") ?? \"Agent execution failed\",\n code,\n fatal: true,\n });\n return;\n }\n case \"sdk_error\": {\n // Ambiguous terminality in the legacy parser — treat as a non-fatal\n // warning notice so the UI doesn't dead-end on a recoverable error.\n emitNotice(out, \"warning\", \"system\", str(frame, \"error\") ?? \"SDK error\");\n return;\n }\n case \"sdk_success\": {\n // The SDK ResultMessage. On an Anthropic-side failure (quota exhausted,\n // oauth revoked, model unavailable, ...) the wire STILL ends with\n // `done` + completion_state \"complete\", but the backend marks the run\n // failed from `is_error` — surface the failure here so the client\n // doesn't report a failed run as complete. (terminalEmitted then\n // suppresses the misleading `done`.) Non-error results stay unknown\n // passthrough bookkeeping.\n if (bool(frame, \"is_error\") !== true) {\n out.push({ type: \"unknown\", wireType: type }); // bookkeeping passthrough (as before)\n return;\n }\n if (terminalEmitted) return;\n terminalEmitted = true;\n out.push({\n type: \"run-error\",\n error: str(frame, \"subtype\") ?? \"sdk_error\",\n message: str(frame, \"result\") ?? \"The model provider returned an error.\",\n code: null,\n fatal: true,\n });\n return;\n }\n\n /* ---- message lifecycle ---- */\n case \"message_start\": {\n const msg = obj(frame, \"message\");\n const id = (msg && str(msg, \"id\")) ?? str(frame, \"message_id\");\n if (!id) return;\n currentMessageId = id;\n const key = `message:${id}`;\n if (seen.has(key)) return;\n seen.add(key);\n const usage = msg && obj(msg, \"usage\");\n out.push({\n type: \"message-start\",\n messageId: id,\n role: \"assistant\",\n ...(usage\n ? { usage: { inputTokens: num(usage, \"input_tokens\") ?? 0, outputTokens: num(usage, \"output_tokens\") ?? 0 } }\n : {}),\n });\n return;\n }\n case \"message_stop\":\n case \"message_complete\": {\n const id = str(frame, \"message_id\") ?? currentMessageId;\n if (!id) return;\n const key = `message:${id}:end`;\n if (seen.has(key)) return;\n seen.add(key);\n const usage = obj(frame, \"usage\");\n out.push({\n type: \"message-end\",\n messageId: id,\n ...(usage\n ? { usage: { inputTokens: num(usage, \"input_tokens\") ?? 0, outputTokens: num(usage, \"output_tokens\") ?? 0 } }\n : {}),\n });\n return;\n }\n case \"message_snapshot\":\n emitSnapshot(frame, out);\n return;\n\n /* ---- content blocks ---- */\n case \"content_block_start\":\n emitContentBlockStart(frame, out);\n return;\n case \"content_block_delta\":\n emitContentBlockDelta(frame, out);\n return;\n case \"content_block_stop\":\n emitContentBlockStop(frame, out);\n return;\n case \"message_delta\":\n emitMessageDelta(frame, out);\n return;\n\n /* ---- tools ---- */\n case \"tool_use\":\n emitStandaloneToolUse(frame, out);\n return;\n case \"tool_result\":\n emitToolResult(frame, out);\n return;\n\n /* ---- standalone reasoning / plan: passthrough as `unknown` for v1 ----\n * These top-level (non-content_block) frames carry full content with no\n * wire id, so they cannot be deduped across a rejoin and two bursts would\n * collide on a synthetic id. Block-based reasoning (content_block\n * reasoning_delta) is the dedupe-safe path and IS handled. Surface these\n * raw until their real wire behavior is confirmed (CONTRACT.md open Q). */\n\n /* ---- HITL ---- */\n case \"awaiting_approval\":\n case \"permission_request\":\n emitApprovalGate(frame, out);\n return;\n\n /* ---- sandbox + notices ---- */\n case \"sandbox-connecting\":\n out.push({\n type: \"sandbox-status\",\n phase: \"connecting\",\n message: str(frame, \"message\") ?? \"Connecting to sandbox\",\n runId: num(frame, \"run_id\") ?? null,\n });\n return;\n case \"sandbox-connected\":\n out.push({\n type: \"sandbox-status\",\n phase: \"connected\",\n message: str(frame, \"message\") ?? \"Connected to sandbox\",\n runId: num(frame, \"run_id\") ?? null,\n ...(str(frame, \"sandbox_id\") !== undefined ? { sandboxId: str(frame, \"sandbox_id\") } : {}),\n ...(num(frame, \"duration_ms\") !== undefined ? { durationMs: num(frame, \"duration_ms\") } : {}),\n });\n return;\n case \"stderr\":\n emitNotice(out, \"info\", \"stderr\", str(frame, \"message\") ?? \"\");\n return;\n case \"mcp_error\":\n case \"mcp_auth_failed\":\n emitNotice(out, \"warning\", \"mcp\", str(frame, \"message\") ?? str(frame, \"error\") ?? \"MCP error\", str(frame, \"detail\"));\n return;\n case \"rate_limit\": {\n const info = obj(frame, \"rate_limit_info\");\n const status = (info && str(info, \"status\")) ?? \"allowed\";\n emitNotice(out, status === \"rejected\" ? \"warning\" : \"info\", \"rate_limit\", `Rate limit: ${status}`);\n return;\n }\n case \"compact_boundary\":\n out.push({\n type: \"compact-boundary\",\n trigger: str(frame, \"trigger\") === \"manual\" ? \"manual\" : \"auto\",\n preTokens: num(frame, \"pre_tokens\") ?? 0,\n });\n return;\n\n /* ---- passthrough ---- */\n default:\n out.push({ type: \"unknown\", wireType: type });\n return;\n }\n }\n\n return {\n push(frame: WireFrame): M8tesStreamEvent[] {\n const partials: Emitted[] = [];\n handle(frame, partials);\n return partials.map(\n (e) => ({ ...e, seq: seq++, raw: frame }) as M8tesStreamEvent,\n );\n },\n reset,\n };\n}\n","/**\n * Accumulator: the normalized event stream -> renderable conversation state.\n *\n * Pure + immutable (new state object on every change) so React can re-render via\n * useState/useSyncExternalStore. Framework-agnostic — `useMate` wraps it. It\n * assumes the normalizer has already deduped (so each event is \"new\"); it only\n * folds events into messages/parts + run status + pending HITL.\n *\n * Lazy creation: a `text-delta`/`tool-*` with no preceding start (a trimmed\n * replay prefix) lazily creates its message/part, so a partial rejoin still\n * renders rather than dropping content.\n */\n\nimport type {\n ApprovalRequestEvent,\n M8tesStreamEvent,\n QuestionEvent,\n RunStatus,\n ToolState,\n} from \"./events\";\n\nexport type TextLikeKind = \"text\" | \"reasoning\" | \"plan\";\n\nexport interface TextPart {\n kind: TextLikeKind;\n id: string;\n text: string;\n}\nexport interface ToolPart {\n kind: \"tool\";\n toolCallId: string;\n toolName: string;\n state: ToolState;\n inputText: string; // accumulated partial-JSON while streaming\n input?: unknown; // resolved input object\n output?: unknown; // tool result\n isError?: boolean;\n}\n/** Non-fatal diagnostics rendered as a quiet inline row (mcp auth failures,\n * rate limits) — the platform surfaces these; silence hides real failures. */\nexport interface NoticePart {\n kind: \"notice\";\n id: string;\n level: \"info\" | \"warning\";\n source: string;\n message: string;\n}\n/** Sandbox lifecycle pill (\"connecting to environment\" -> \"environment ready\"). */\nexport interface SandboxPart {\n kind: \"sandbox\";\n id: string;\n phase: \"connecting\" | \"connected\";\n durationMs?: number;\n}\n/** Conversation-summarized divider (SDK auto/manual compaction). */\nexport interface CompactPart {\n kind: \"compact\";\n id: string;\n trigger: \"manual\" | \"auto\";\n preTokens: number;\n}\nexport type MatePart = TextPart | ToolPart | NoticePart | SandboxPart | CompactPart;\n\nexport interface MateMessage {\n id: string;\n role: \"assistant\" | \"user\";\n parts: MatePart[];\n}\n\nexport type MateStatus = \"idle\" | RunStatus;\n\nexport interface ConversationState {\n runId: number | null;\n runUuid: string | null;\n agentName: string | null;\n status: MateStatus;\n messages: MateMessage[];\n pendingApproval: ApprovalRequestEvent | null;\n pendingQuestion: QuestionEvent | null;\n /** From run-metrics: \"refusal\" | \"max_tokens\" render a quiet outcome row\n * (\"Request declined\" / \"Response truncated\"); anything else is null. */\n finishStopReason: \"refusal\" | \"max_tokens\" | null;\n error: {\n message: string;\n code: string | null;\n /** HTTP status for API errors (402 limit / 429 rate) */\n apiStatus?: number;\n /** v2 `error.details` (machine `error_code`, `retry_after`, `period_end`, ...) */\n apiDetails?: Record<string, unknown>;\n } | null;\n}\n\nexport const initialConversationState: ConversationState = {\n runId: null,\n runUuid: null,\n agentName: null,\n status: \"idle\",\n messages: [],\n pendingApproval: null,\n pendingQuestion: null,\n finishStopReason: null,\n error: null,\n};\n\nfunction lastAssistantIndex(messages: MateMessage[]): number {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]!.role === \"assistant\") return i;\n }\n return -1;\n}\n\n/** Get-or-create a message and replace its parts via `fn`. */\nfunction withMessageParts(\n state: ConversationState,\n messageId: string,\n role: \"assistant\" | \"user\",\n fn: (parts: MatePart[]) => MatePart[],\n): ConversationState {\n const messages = state.messages.slice();\n let idx = messageId\n ? messages.findIndex((m) => m.id === messageId)\n : lastAssistantIndex(messages);\n if (idx === -1) {\n messages.push({ id: messageId || `m:${messages.length}`, role, parts: [] });\n idx = messages.length - 1;\n }\n const msg = messages[idx]!;\n messages[idx] = { ...msg, parts: fn(msg.parts) };\n return { ...state, messages };\n}\n\nconst isTextLike = (p: MatePart): p is TextPart =>\n p.kind === \"text\" || p.kind === \"reasoning\" || p.kind === \"plan\";\n\nfunction ensureTextPart(parts: MatePart[], kind: TextLikeKind, id: string): MatePart[] {\n if (parts.some((p) => isTextLike(p) && p.id === id)) return parts;\n return [...parts, { kind, id, text: \"\" }];\n}\n\nfunction applyTextDelta(\n parts: MatePart[],\n kind: TextLikeKind,\n id: string,\n delta: string,\n): MatePart[] {\n const i = parts.findIndex((p) => isTextLike(p) && p.id === id);\n if (i === -1) return [...parts, { kind, id, text: delta }];\n const p = parts[i] as TextPart;\n const next = parts.slice();\n next[i] = { ...p, text: p.text + delta };\n return next;\n}\n\n/** Find a tool part by id across ALL messages (results pair across messages). */\nfunction updateToolPart(\n state: ConversationState,\n toolCallId: string,\n toolName: string | undefined,\n patch: (p: ToolPart) => ToolPart,\n): ConversationState {\n const messages = state.messages.slice();\n for (let mi = 0; mi < messages.length; mi++) {\n const parts = messages[mi]!.parts;\n const pi = parts.findIndex((p) => p.kind === \"tool\" && p.toolCallId === toolCallId);\n if (pi !== -1) {\n const np = parts.slice();\n np[pi] = patch(parts[pi] as ToolPart);\n messages[mi] = { ...messages[mi]!, parts: np };\n return { ...state, messages };\n }\n }\n // not found: lazily create in the last assistant message (or a new one)\n let idx = lastAssistantIndex(messages);\n if (idx === -1) {\n messages.push({ id: `m:${messages.length}`, role: \"assistant\", parts: [] });\n idx = messages.length - 1;\n }\n const base: ToolPart = {\n kind: \"tool\",\n toolCallId,\n toolName: toolName ?? \"\",\n state: \"input-streaming\",\n inputText: \"\",\n };\n messages[idx] = { ...messages[idx]!, parts: [...messages[idx]!.parts, patch(base)] };\n return { ...state, messages };\n}\n\n/** A paused run resumes the moment content flows again. */\nfunction resume(status: MateStatus): MateStatus {\n return status === \"awaiting_approval\" || status === \"awaiting_input\" ? \"running\" : status;\n}\n\nexport function accumulate(\n state: ConversationState,\n e: M8tesStreamEvent,\n): ConversationState {\n switch (e.type) {\n case \"run-start\":\n return {\n ...state,\n runId: e.runId,\n runUuid: e.runUuid,\n agentName: e.agentName ?? state.agentName ?? null,\n status: \"running\",\n error: null,\n // A retry re-drives the turn: the previous attempt's outcome row\n // (\"Response truncated\", \"Request declined\") must not survive it.\n finishStopReason: null,\n };\n case \"run-status\":\n return { ...state, status: e.status };\n case \"message-start\":\n return withMessageParts(state, e.messageId, e.role, (p) => p);\n case \"text-start\":\n return {\n ...withMessageParts(state, e.messageId, \"assistant\", (p) => ensureTextPart(p, \"text\", e.id)),\n status: resume(state.status),\n };\n case \"text-delta\":\n return {\n ...withMessageParts(state, e.messageId, \"assistant\", (p) => applyTextDelta(p, \"text\", e.id, e.delta)),\n status: resume(state.status),\n };\n case \"reasoning-start\":\n return withMessageParts(state, e.messageId, \"assistant\", (p) => ensureTextPart(p, \"reasoning\", e.id));\n case \"reasoning-delta\":\n return withMessageParts(state, e.messageId, \"assistant\", (p) => applyTextDelta(p, \"reasoning\", e.id, e.delta));\n case \"plan-start\":\n return withMessageParts(state, e.messageId, \"assistant\", (p) => ensureTextPart(p, \"plan\", e.id));\n case \"plan-delta\":\n return withMessageParts(state, e.messageId, \"assistant\", (p) => applyTextDelta(p, \"plan\", e.id, e.delta));\n case \"text-end\":\n case \"reasoning-end\":\n case \"plan-end\":\n case \"message-end\":\n return state;\n case \"tool-input-start\":\n return {\n ...withMessageParts(state, e.messageId, \"assistant\", (p) =>\n p.some((x) => x.kind === \"tool\" && x.toolCallId === e.toolCallId)\n ? p\n : [\n ...p,\n {\n kind: \"tool\",\n toolCallId: e.toolCallId,\n toolName: e.toolName,\n state: \"input-streaming\",\n inputText: \"\",\n },\n ],\n ),\n status: resume(state.status),\n };\n case \"tool-input-delta\":\n return updateToolPart(state, e.toolCallId, undefined, (t) => ({\n ...t,\n inputText: t.inputText + e.inputTextDelta,\n state: \"input-streaming\",\n }));\n case \"tool-input-available\":\n return updateToolPart(state, e.toolCallId, e.toolName, (t) => ({\n ...t,\n input: e.input,\n state: \"input-available\",\n }));\n case \"tool-output-available\": {\n const s = updateToolPart(state, e.toolCallId, undefined, (t) => ({\n ...t,\n output: e.output,\n isError: e.isError,\n state: e.state,\n }));\n const pendingApproval =\n s.pendingApproval && s.pendingApproval.toolCallId === e.toolCallId ? null : s.pendingApproval;\n const pendingQuestion =\n s.pendingQuestion && s.pendingQuestion.toolCallId === e.toolCallId ? null : s.pendingQuestion;\n return { ...s, pendingApproval, pendingQuestion, status: resume(s.status) };\n }\n case \"approval-request\":\n return { ...state, pendingApproval: e, status: \"awaiting_approval\" };\n case \"approval-resolved\":\n return state.pendingApproval && state.pendingApproval.requestId === e.requestId\n ? { ...state, pendingApproval: null }\n : state;\n case \"question\":\n return { ...state, pendingQuestion: e, status: \"awaiting_input\" };\n case \"run-finish\":\n return { ...state, status: e.status, pendingApproval: null, pendingQuestion: null };\n case \"run-error\":\n return {\n ...state,\n status: \"error\",\n error: {\n message: e.message,\n code: e.code,\n ...(e.apiStatus !== undefined ? { apiStatus: e.apiStatus } : {}),\n ...(e.apiDetails !== undefined ? { apiDetails: e.apiDetails } : {}),\n },\n pendingApproval: null,\n pendingQuestion: null,\n };\n case \"run-cancelled\":\n return { ...state, status: \"cancelled\", pendingApproval: null, pendingQuestion: null };\n case \"sandbox-status\": {\n // Inline lifecycle pill: \"connecting\" appends; \"connected\" upgrades the\n // open connecting pill in place (adding the boot duration) so one boot\n // renders as one row, platform-style.\n const withStatus =\n e.phase === \"connecting\" && state.status === \"idle\" ? { ...state, status: \"connecting\" as const } : state;\n if (e.phase === \"connecting\") {\n return withMessageParts(withStatus, \"\", \"assistant\", (p) => [\n ...p,\n { kind: \"sandbox\", id: `sb:${p.length}`, phase: \"connecting\" },\n ]);\n }\n const messages = withStatus.messages.slice();\n for (let mi = messages.length - 1; mi >= 0; mi--) {\n const parts = messages[mi]!.parts;\n for (let pi = parts.length - 1; pi >= 0; pi--) {\n const part = parts[pi]!;\n if (part.kind === \"sandbox\" && part.phase === \"connecting\") {\n const np = parts.slice();\n np[pi] = { ...part, phase: \"connected\", ...(e.durationMs !== undefined ? { durationMs: e.durationMs } : {}) };\n messages[mi] = { ...messages[mi]!, parts: np };\n return { ...withStatus, messages };\n }\n }\n }\n return withMessageParts(withStatus, \"\", \"assistant\", (p) => [\n ...p,\n { kind: \"sandbox\", id: `sb:${p.length}`, phase: \"connected\", ...(e.durationMs !== undefined ? { durationMs: e.durationMs } : {}) },\n ]);\n }\n case \"notice\":\n // Platform parity: only WARNING diagnostics surface (MCP auth failures,\n // rejected rate limits). Info chatter (stderr, allowed rate limits) is\n // dropped HERE rather than hidden in the view — a part that renders null\n // still occupies a row in the thread's flex column and injects a phantom\n // gap. Raw `notice` events still reach headless consumers via `onEvent`.\n if (e.level !== \"warning\") return state;\n return withMessageParts(state, \"\", \"assistant\", (p) => [\n ...p,\n { kind: \"notice\", id: `n:${p.length}`, level: e.level, source: e.source, message: e.message },\n ]);\n case \"compact-boundary\":\n return withMessageParts(state, \"\", \"assistant\", (p) => [\n ...p,\n { kind: \"compact\", id: `c:${p.length}`, trigger: e.trigger, preTokens: e.preTokens },\n ]);\n case \"run-metrics\":\n return e.stopReason === \"refusal\" || e.stopReason === \"max_tokens\"\n ? { ...state, finishStopReason: e.stopReason }\n : state;\n case \"unknown\":\n return state;\n default:\n return state;\n }\n}\n\n/** Stateful convenience wrapper for the hook (holds the running snapshot). */\nexport interface Accumulator {\n readonly state: ConversationState;\n apply(event: M8tesStreamEvent): ConversationState;\n /** Optimistically append the user's own message (shown immediately on send). */\n addUserMessage(text: string): ConversationState;\n reset(): void;\n}\n\nexport function createAccumulator(): Accumulator {\n let state = initialConversationState;\n return {\n get state() {\n return state;\n },\n apply(event) {\n state = accumulate(state, event);\n return state;\n },\n addUserMessage(text) {\n const id = `u:${state.messages.length}`;\n state = {\n ...state,\n messages: [...state.messages, { id, role: \"user\", parts: [{ kind: \"text\", id, text }] }],\n };\n return state;\n },\n reset() {\n state = initialConversationState;\n },\n };\n}\n","/**\n * Typed error hierarchy for the m8tes V2 API — ONE implementation shared by\n * `@m8tes/sdk` (API-key client) and `@m8tes/react` (browser proxy client).\n *\n * Mirrors the Python SDK's `sdk/py/m8tes/_exceptions.py` so the two languages\n * behave identically: same status→class map, same `docUrl`/`errorCode`/\n * `retryAfter`/`details` fields, just camelCase.\n *\n * The wire envelope is standardized across every /api/v2 route\n * (`fastapi/app/routers/v2/_errors.py`):\n *\n * { \"error\": { \"message\", \"type\", \"code\", \"request_id\", \"doc_url\",\n * \"details\": { \"error_code\": \"...\", ...context } } }\n *\n * Note `error.code` is the int HTTP status by design; the machine-readable app\n * code (e.g. \"RUN_LIMIT_REACHED\", \"END_USER_RATE_LIMITED\") lives at\n * `error.details.error_code` and is surfaced here as `errorCode`.\n *\n * No auth and no `node:` imports live in this file — it ships in browser\n * bundles via `@m8tes/sdk/protocol`.\n */\n\nexport interface ApiErrorFields {\n /** Envelope `error.type`, e.g. \"authentication_error\". */\n type: string;\n /** Envelope `error.code` — the int HTTP status (kept for wire fidelity). */\n code: number;\n /** HTTP status of the response. */\n status: number;\n /** `error.request_id`, else the `x-request-id` response header. Quote this in bug reports. */\n requestId?: string;\n /** Full `error.details` object: actionable context (runs_used, period_end, ...). */\n details?: unknown;\n /** `error.doc_url` — docs deep link for this error type. */\n docUrl?: string;\n /** `error.details.error_code` — machine-readable app code for branching. */\n errorCode?: string;\n /** Seconds from the `Retry-After` header. Set on 429; undefined when absent or an HTTP-date. */\n retryAfter?: number;\n}\n\n/** Base class for every API error. Catch this to catch them all. */\nexport class M8tesApiError extends Error {\n readonly type: string;\n readonly code: number;\n readonly status: number;\n readonly requestId?: string;\n readonly details?: unknown;\n readonly docUrl?: string;\n readonly errorCode?: string;\n readonly retryAfter?: number;\n\n constructor(message: string, f: ApiErrorFields) {\n super(message);\n this.name = \"M8tesApiError\";\n this.type = f.type;\n this.code = f.code;\n this.status = f.status;\n this.requestId = f.requestId;\n this.details = f.details;\n this.docUrl = f.docUrl;\n this.errorCode = f.errorCode;\n this.retryAfter = f.retryAfter;\n }\n}\n\n/** 400 or 422 — invalid request. Check `.status` to tell them apart. */\nexport class ValidationError extends M8tesApiError {\n constructor(message: string, f: ApiErrorFields) {\n super(message, f);\n this.name = \"ValidationError\";\n }\n}\n\n/** 401 — missing, malformed, or revoked API key. */\nexport class AuthenticationError extends M8tesApiError {\n constructor(message: string, f: ApiErrorFields) {\n super(message, f);\n this.name = \"AuthenticationError\";\n }\n}\n\n/** 402 — billing limit reached or subscription issue. `.details` carries the caps. */\nexport class BillingError extends M8tesApiError {\n constructor(message: string, f: ApiErrorFields) {\n super(message, f);\n this.name = \"BillingError\";\n }\n}\n\n/** 403 — authenticated but not allowed. */\nexport class PermissionDeniedError extends M8tesApiError {\n constructor(message: string, f: ApiErrorFields) {\n super(message, f);\n this.name = \"PermissionDeniedError\";\n }\n}\n\n/** 404 — no such resource, or it belongs to another account/end-user. */\nexport class NotFoundError extends M8tesApiError {\n constructor(message: string, f: ApiErrorFields) {\n super(message, f);\n this.name = \"NotFoundError\";\n }\n}\n\n/** 409 — conflicting state. */\nexport class ConflictError extends M8tesApiError {\n constructor(message: string, f: ApiErrorFields) {\n super(message, f);\n this.name = \"ConflictError\";\n }\n}\n\n/**\n * 409 from `GET /runs/{id}/stream` — the run is no longer executing, so there is\n * nothing to join. The caller should fall back to `runs.get(id)` for the final\n * result rather than treating this as a failure.\n */\nexport class RunNotStreamingError extends ConflictError {\n constructor(message: string, f: ApiErrorFields) {\n super(message, f);\n this.name = \"RunNotStreamingError\";\n }\n}\n\n/** 429 — too many requests. Honour `.retryAfter` before retrying. */\nexport class RateLimitError extends M8tesApiError {\n constructor(message: string, f: ApiErrorFields) {\n super(message, f);\n this.name = \"RateLimitError\";\n }\n}\n\n/** 500+ — server-side error. Safe to retry idempotent requests. */\nexport class APIError extends M8tesApiError {\n constructor(message: string, f: ApiErrorFields) {\n super(message, f);\n this.name = \"APIError\";\n }\n}\n\n/**\n * A stream completed but emitted error events (expired credential, provider rate\n * limit, quota exhaustion). Raised so a failed run is never mistaken for a\n * successful empty one. `.details.errors` holds the raw messages.\n */\nexport class RunFailedError extends M8tesApiError {\n constructor(message: string, f: ApiErrorFields) {\n super(message, f);\n this.name = \"RunFailedError\";\n }\n}\n\n/** Status → class. Mirrors `STATUS_MAP` in the Python SDK. */\nconst STATUS_MAP: Record<number, new (message: string, f: ApiErrorFields) => M8tesApiError> = {\n 400: ValidationError,\n 401: AuthenticationError,\n 402: BillingError,\n 403: PermissionDeniedError,\n 404: NotFoundError,\n 409: ConflictError,\n 422: ValidationError,\n 429: RateLimitError,\n};\n\n/** `Retry-After` in seconds. An HTTP-date (or garbage) yields undefined, matching Python. */\nexport function parseRetryAfter(raw: string | null | undefined): number | undefined {\n if (!raw) return undefined;\n const seconds = Number(raw);\n return Number.isFinite(seconds) ? seconds : undefined;\n}\n\nfunction str(o: Record<string, unknown>, key: string): string | undefined {\n return typeof o[key] === \"string\" ? (o[key] as string) : undefined;\n}\n\n/**\n * Pull the standardized envelope out of a parsed error body.\n *\n * Tolerant by design: a proxy, a CDN, or a non-v2 route can return HTML, an\n * empty body, or a bare `{detail: ...}`, and callers still get a usable error\n * with the right status rather than a SyntaxError.\n */\nexport function parseErrorEnvelope(\n status: number,\n body: unknown,\n headers?: { get(name: string): string | null },\n): { message: string; fields: ApiErrorFields } {\n const e =\n body !== null && typeof body === \"object\" && \"error\" in body && typeof (body as { error: unknown }).error === \"object\"\n ? ((body as { error: Record<string, unknown> }).error ?? {})\n : {};\n const details = e[\"details\"];\n const errorCode =\n details !== null && typeof details === \"object\"\n ? str(details as Record<string, unknown>, \"error_code\")\n : undefined;\n return {\n message: str(e, \"message\") ?? `Request failed (${status})`,\n fields: {\n type: str(e, \"type\") ?? \"api_error\",\n code: typeof e[\"code\"] === \"number\" ? (e[\"code\"] as number) : status,\n status,\n requestId: str(e, \"request_id\") ?? headers?.get(\"x-request-id\") ?? undefined,\n details,\n docUrl: str(e, \"doc_url\"),\n errorCode,\n retryAfter: parseRetryAfter(headers?.get(\"retry-after\")),\n },\n };\n}\n\nexport interface ErrorFromResponseOptions {\n /**\n * Map 409 to `RunNotStreamingError` (the \"run already finished, fall back to\n * runs.get()\" signal) instead of the generic `ConflictError`. Set on stream\n * requests, where 409 has exactly that meaning.\n */\n conflictIsNotStreaming?: boolean;\n}\n\n/** The error class a status maps to. Exported so clients that build their own\n * message (e.g. the SDK's base-URL diagnostics) still get the right type. */\nexport function errorClassForStatus(\n status: number,\n opts: ErrorFromResponseOptions = {},\n): new (message: string, f: ApiErrorFields) => M8tesApiError {\n if (status === 409 && opts.conflictIsNotStreaming) return RunNotStreamingError;\n // Python: `STATUS_MAP.get(status, APIError)` — ANY unmapped status (405, 418,\n // 5xx) becomes APIError. Falling back to the bare base class here would mean a\n // 405 caught as APIError in Python slips through the same `catch` in\n // TypeScript. Pinned by test/parity.test.ts.\n return STATUS_MAP[status] ?? APIError;\n}\n\n/**\n * Build the right typed error from a non-OK `Response`. Consumes the body.\n */\nexport async function errorFromResponse(\n res: Response,\n opts: ErrorFromResponseOptions = {},\n): Promise<M8tesApiError> {\n let body: unknown;\n try {\n body = await res.json();\n } catch {\n body = undefined;\n }\n const { message, fields } = parseErrorEnvelope(res.status, body, res.headers);\n const Cls = errorClassForStatus(res.status, opts);\n return new Cls(message, fields);\n}\n","/**\n * `seg()` — turn ONE caller-supplied value into a single, inescapable URL path\n * segment. Mirrors the Python SDK's `sdk/py/m8tes/_http.py::seg` exactly; the\n * shared corpus `sdk/py/tests/data/path_encoding_parity.json` pins both halves.\n *\n * Every dynamic `/`-delimited segment this SDK (and `@m8tes/react`) puts in a\n * path goes through this. The values are frequently tenant-controlled (an\n * end-user id, an app slug, a run's filename), and interpolating one straight\n * into a template literal lets it steer the request somewhere the method never\n * named — the compile-time `number` type is erased at runtime, so a JS\n * consumer, a value off `JSON.parse`, or one `as any` reaches it. Measured\n * before this landed: `runs.get(\"5/messages\")` reached `GET /runs/{id}/messages`,\n * and `tasks.delete(\"5/webhook\")` would destroy a webhook token instead of\n * archiving the task.\n *\n * Two mechanisms, because percent-encoding alone does NOT confine the route:\n *\n * 1. REFUSE anything that would still be structural after the server decodes.\n * uvicorn sets the ASGI path to the percent-DECODED path and Starlette\n * routes on that, so `%2F` is a separator to the server even though it is\n * not one to `fetch`. `/` is therefore rejected, as are `\"\"`, `\".\"` and\n * `\"..\"`, which address the collection or the parent rather than a resource.\n * 2. PERCENT-ENCODE the rest, so the value stays one opaque segment: `?` and\n * `#` would otherwise start a query or a fragment.\n *\n * It throws `ValidationError` (nothing was sent, so `.status` is 0), keeping an\n * existing `catch (e) { if (e instanceof M8tesApiError) ... }` working.\n *\n * Known cosmetic divergence from Python: `encodeURIComponent` leaves `!*'()`\n * literal where Python's `quote(safe=\"\")` escapes them. Both decode to the same\n * segment server-side and neither can leave it — asserted route-aware by the\n * parity corpus rather than waved through.\n *\n * Lives under `protocol/` because it is browser-safe (no credential, no\n * `node:*`) and `@m8tes/react`'s proxy client builds the same paths.\n */\n\nimport { ValidationError } from \"./errors\";\n\n// A segment that is one of these cannot name a resource, and each one silently\n// addresses a DIFFERENT one instead — `\"\"` and `\".\"` collapse onto the\n// collection route, `\"..\"` onto the parent.\nconst UNADDRESSABLE = new Set([\"\", \".\", \"..\"]);\n\n// The one character that becomes a path SEPARATOR at the server. Escaping it is\n// not enough (see above), so it is refused. A BACKSLASH is deliberately NOT\n// refused — it is a legal character in a filename and an id, and measured\n// against this stack it stays inside its segment; it is percent-encoded like\n// any other reserved character (same call as Python).\nconst SEPARATOR = \"/\";\n\nfunction reject(value: string, reason: string): never {\n throw new ValidationError(\n `${JSON.stringify(value)} cannot be used as a URL path segment: ${reason}. ` +\n \"Percent-encoding does not help — the server decodes the path before routing it.\",\n { type: \"invalid_request_error\", code: 0, status: 0 },\n );\n}\n\n/** One caller-supplied value → one safe path segment, or a `ValidationError`. */\nexport function seg(value: unknown): string {\n if (value === null || value === undefined) {\n reject(String(value), \"an id of null or undefined is a caller bug, not a resource name\");\n }\n const text = String(value);\n if (UNADDRESSABLE.has(text)) {\n reject(text, \"it addresses the parent or the collection, not a resource\");\n }\n if (text.includes(SEPARATOR)) {\n reject(text, \"a '/' becomes a real path separator once the server decodes it\");\n }\n return encodeURIComponent(text);\n}\n"]}