@mantyx/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@mantyx/sdk` are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.1.0] — 2026-05-02
11
+
12
+ ### Added
13
+
14
+ - Initial release of `@mantyx/sdk`.
15
+ - `RunSpec.agentId` / `SessionSpec.agentId` — trigger a persisted MANTYX
16
+ agent by id instead of defining an ephemeral one inline. The server
17
+ hydrates the system prompt, model, and the agent's own tools (memory,
18
+ skills, plugin tools, …) from the `Agent` row at run time. Any extra
19
+ `tools` you pass on the request are merged on top — typically local
20
+ tools the agent should call back into for that run. `systemPrompt` is
21
+ now optional whenever `agentId` is set.
22
+ - `MantyxClient` for the public agent-runs HTTP/SSE protocol.
23
+ - `runAgent`, `streamAgent` for one-shot ephemeral agent runs.
24
+ - `createSession`, `resumeSession`, `endSession` for multi-turn sessions.
25
+ - `listModels` for the workspace's model catalog (BYOK + platform offerings).
26
+ - `defineLocalTool`, `mantyxTool`, `mantyxPluginTool` tool helpers.
27
+ - Zod → JSON Schema conversion for local tool parameters.
28
+ - Inline SSE parser (no extra deps) with `Last-Event-ID` reconnect support.
29
+ - Custom error hierarchy: `MantyxError`, `MantyxAuthError`,
30
+ `MantyxNetworkError`, `MantyxRunError`, `MantyxToolError`.
31
+ - Self-contained example projects under `examples/`.
32
+ - Vitest-driven mock server tests for runs, sessions, and the model catalog.
33
+
34
+ [Unreleased]: https://github.com/mantyx/aos/compare/sdk-typescript-v0.1.0...HEAD
35
+ [0.1.0]: https://github.com/mantyx/aos/releases/tag/sdk-typescript-v0.1.0
@@ -0,0 +1,78 @@
1
+ # Contributing to `@mantyx/sdk`
2
+
3
+ Thanks for considering a contribution! This SDK is a small, dependency-light
4
+ client for the [MANTYX](https://mantyx.com) agent-runs HTTP/SSE protocol; the
5
+ goal is to keep it that way.
6
+
7
+ ## Ground rules
8
+
9
+ 1. **Public-protocol only.** The SDK MUST NOT depend on any MANTYX-internal
10
+ package, type, or repository layout. Anything it does is a side effect of
11
+ sending HTTP requests against the public protocol documented in
12
+ [`docs/agent-runs-protocol.md`](./docs/agent-runs-protocol.md).
13
+ 2. **No `workspace:*`.** The SDK ships to npm as a standalone package. Pull
14
+ requests that introduce a `workspace:*` dependency in `package.json` will
15
+ not be merged.
16
+ 3. **Tiny dep tree.** The only runtime dependency today is `zod`. Adding a
17
+ new runtime dependency requires a strong justification.
18
+ 4. **Standalone tests.** `pnpm test` must pass with `node_modules/` populated
19
+ from this package's own `package.json`, with no MANTYX server running.
20
+ 5. **Backwards compatibility.** Bump the SDK version per
21
+ [SemVer](https://semver.org/spec/v2.0.0.html). Breaking changes need a
22
+ major version bump and a `CHANGELOG.md` entry.
23
+
24
+ ## Local setup
25
+
26
+ ```bash
27
+ pnpm install
28
+ pnpm test
29
+ pnpm typecheck
30
+ pnpm build
31
+ ```
32
+
33
+ The repository is a pnpm monorepo, but this package is a leaf with no
34
+ internal consumers, so it is safe to develop in isolation.
35
+
36
+ ## Adding tests
37
+
38
+ Tests live under [`test/`](./test) and use Vitest. Network calls are routed
39
+ through the in-process mock server in
40
+ [`test/helpers/mock-server.ts`](./test/helpers/mock-server.ts) — extend it
41
+ when you need to exercise a new server behaviour rather than reaching out to
42
+ a real MANTYX instance.
43
+
44
+ When fixing a bug, prefer a regression test against the mock server. When
45
+ adding a feature, add an example under [`examples/`](./examples) that
46
+ exercises it end-to-end.
47
+
48
+ ## Style
49
+
50
+ - TypeScript strict mode. No `any` unless there's no choice.
51
+ - Public types are re-exported from [`src/index.ts`](./src/index.ts). Keep
52
+ the public surface minimal and well-typed.
53
+ - Use `MantyxError` (and its subclasses) for thrown errors so callers can
54
+ branch on `instanceof`.
55
+ - Prefer the Web `fetch` / `ReadableStream` APIs over Node-only modules so
56
+ the SDK keeps working in edge / browser-like runtimes.
57
+
58
+ ## Pull requests
59
+
60
+ 1. Fork and create a feature branch.
61
+ 2. Add or update tests.
62
+ 3. `pnpm test && pnpm typecheck && pnpm build`.
63
+ 4. Update `CHANGELOG.md` under `## [Unreleased]`.
64
+ 5. Open a PR. Describe the change and any protocol implications.
65
+
66
+ ## Releasing
67
+
68
+ Releases happen out-of-band by a MANTYX maintainer:
69
+
70
+ 1. Move `## [Unreleased]` content into a new version section in
71
+ `CHANGELOG.md`.
72
+ 2. Bump `package.json` `version`.
73
+ 3. `pnpm build && pnpm publish --access public`.
74
+ 4. Tag the commit `sdk-typescript-vX.Y.Z` and push.
75
+
76
+ ## Code of Conduct
77
+
78
+ Be kind. Assume good intent. Be patient with reviewers and maintainers.
package/EXTRACT.md ADDED
@@ -0,0 +1,70 @@
1
+ # Extracting `@mantyx/sdk` into its own repository
2
+
3
+ The `@mantyx/sdk` package is intentionally self-contained. Lifting it out of
4
+ the MANTYX monorepo into a public repository is a five-minute job:
5
+
6
+ ## Steps
7
+
8
+ 1. Copy this folder verbatim:
9
+
10
+ ```bash
11
+ cp -r packages/mantyx-sdk/ts ~/code/mantyx-sdk
12
+ cd ~/code/mantyx-sdk
13
+ ```
14
+
15
+ 2. Initialize git:
16
+
17
+ ```bash
18
+ git init -b main
19
+ git add .
20
+ git commit -m "Import @mantyx/sdk from monorepo"
21
+ ```
22
+
23
+ 3. Re-generate the lockfile against npm:
24
+
25
+ ```bash
26
+ rm -rf node_modules
27
+ pnpm install # or: npm install
28
+ ```
29
+
30
+ 4. Update `examples/*/package.json` so each example installs `@mantyx/sdk`
31
+ from npm rather than via the monorepo's pnpm workspace symlink. Each
32
+ example already sets the dep to `"@mantyx/sdk": "*"`; replace `"*"` with
33
+ the published version once you've cut a release.
34
+
35
+ 5. Confirm the test suite still passes:
36
+
37
+ ```bash
38
+ pnpm test
39
+ pnpm typecheck
40
+ pnpm build
41
+ ```
42
+
43
+ 6. Push to a new GitHub repo and (optionally) wire up CI by copying
44
+ `.github/workflows/sdk-typescript.yml` from the monorepo into
45
+ `.github/workflows/ci.yml` in the new repo.
46
+
47
+ ## What you can leave behind
48
+
49
+ The following monorepo-only files do **not** apply to a standalone repo:
50
+
51
+ - The MANTYX monorepo's root `pnpm-workspace.yaml`, `AGENTS.md`, `run.sh`,
52
+ `infra/`, `mobile/`, etc. None of them are required by the SDK.
53
+
54
+ ## Things to update once extracted
55
+
56
+ - `package.json` `repository`, `homepage`, and `bugs` URLs.
57
+ - `README.md` install instructions if the package name changes (e.g. you
58
+ publish under a different scope).
59
+ - The `DEFAULT_BASE_URL` constant in `src/client.ts` if you intend to talk to
60
+ a non-default MANTYX deployment.
61
+
62
+ ## What stays the same
63
+
64
+ - The wire protocol the SDK speaks (`docs/agent-runs-protocol.md`).
65
+ - The `MantyxClient` API surface.
66
+ - The example projects.
67
+ - Tests and the mock server (zero MANTYX dependencies).
68
+
69
+ That's it. The extracted package can be built, tested, and published from
70
+ any environment with Node.js 18.17+ installed.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 MANTYX
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,304 @@
1
+ # @mantyx/sdk
2
+
3
+ The official TypeScript SDK for the [MANTYX](https://mantyx.com) agent
4
+ runtime. Define ephemeral agents that mix server-side MANTYX tools with
5
+ locally-executed tools, run them remotely, and stream events back into your
6
+ process.
7
+
8
+ - LLM loop runs on MANTYX (BYOK or platform-hosted models).
9
+ - Server-side tools (`mantyx`, `mantyx_plugin`) execute inside MANTYX.
10
+ - Local tools execute inside *your* process; the SDK shuttles inputs and
11
+ outputs over an SSE stream + a tool-result POST.
12
+ - One-shot runs and multi-turn sessions, both with persisted observability.
13
+ - Authenticated with a single workspace API key.
14
+
15
+ For background, see the [agent-runs protocol spec](./docs/agent-runs-protocol.md).
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ npm install @mantyx/sdk zod
21
+ # or: pnpm add @mantyx/sdk zod
22
+ # or: yarn add @mantyx/sdk zod
23
+ ```
24
+
25
+ Requires Node.js 18.17+ (for `fetch` and `ReadableStream`). `zod` is the only
26
+ runtime dependency the SDK adds; the rest is the standard library and your
27
+ own modules.
28
+
29
+ ## Quickstart
30
+
31
+ ```ts
32
+ import { z } from "zod";
33
+ import fs from "node:fs/promises";
34
+ import { MantyxClient, defineLocalTool, mantyxTool } from "@mantyx/sdk";
35
+
36
+ const client = new MantyxClient({
37
+ apiKey: process.env.MANTYX_API_KEY!,
38
+ workspaceSlug: process.env.MANTYX_WORKSPACE_SLUG!,
39
+ // baseUrl: "https://api.mantyx.com", // override for self-hosted
40
+ });
41
+
42
+ const result = await client.runAgent({
43
+ systemPrompt: "You are a helpful assistant.",
44
+ prompt: "Read /etc/hostname and summarize what it says.",
45
+ tools: [
46
+ // Local tool — defined and executed in this process.
47
+ defineLocalTool({
48
+ name: "read_file",
49
+ description: "Read a file from the local filesystem.",
50
+ parameters: z.object({ path: z.string() }),
51
+ execute: async ({ path }) => fs.readFile(path, "utf8"),
52
+ }),
53
+ // Reference to an existing MANTYX workspace tool.
54
+ mantyxTool("tool_cm6abc123"),
55
+ ],
56
+ });
57
+
58
+ console.log(result.text);
59
+ ```
60
+
61
+ The SDK opens an SSE stream to MANTYX, listens for `local_tool_call` events,
62
+ runs the matching local handler, and POSTs the result back. The server keeps
63
+ running the agent loop until it produces a final reply.
64
+
65
+ ## Triggering a persisted MANTYX agent
66
+
67
+ Pass `agentId` to run an agent that already exists in your workspace. The
68
+ server hydrates the agent's system prompt, model, and server-side tools
69
+ (memory, skills, plugin tools, …) from the `Agent` row at run time. Anything
70
+ you pass in `tools` is **merged on top** — typically `local` tools you want
71
+ the agent to be able to call back into for this specific run.
72
+
73
+ ```ts
74
+ import { defineLocalTool, MantyxClient } from "@mantyx/sdk";
75
+ import { z } from "zod";
76
+
77
+ const client = new MantyxClient({ apiKey: "...", workspaceSlug: "acme" });
78
+
79
+ const result = await client.runAgent({
80
+ agentId: "agent_cm6abc123", // workspace agent id
81
+ prompt: "Pull the latest deploy logs and summarise them.",
82
+ tools: [
83
+ defineLocalTool({
84
+ name: "read_local_file",
85
+ parameters: z.object({ path: z.string() }),
86
+ execute: ({ path }) => readFileSync(path, "utf8"),
87
+ }),
88
+ ],
89
+ });
90
+ console.log(result.text);
91
+ ```
92
+
93
+ Notes:
94
+
95
+ - `systemPrompt` becomes optional when `agentId` is set; if both are sent,
96
+ the agent's stored prompt wins.
97
+ - `modelId` is also optional: omit it to use the agent's configured LLM
98
+ provider, or pass it to override the model for this run.
99
+ - The API key must be authorized for the agent (an empty `agentIds` allowlist
100
+ on the key counts as "all agents in the workspace"). Otherwise the call
101
+ returns `403`.
102
+
103
+ The same `agentId` field works on `client.createSession({ ... })` for
104
+ multi-turn conversations against a persisted agent.
105
+
106
+ ## Picking a model
107
+
108
+ ```ts
109
+ const { models, defaultModelId } = await client.listModels();
110
+ console.log(models.map((m) => `${m.id}\t${m.label}`).join("\n"));
111
+
112
+ await client.runAgent({
113
+ systemPrompt: "...",
114
+ prompt: "Hi!",
115
+ modelId: "platform:cm6abc123", // or "provider:<id>", or "<vendorModelId>"
116
+ });
117
+ ```
118
+
119
+ `modelId` accepts:
120
+
121
+ - `platform:<offeringId>` — a platform-hosted model offering.
122
+ - `provider:<llmProviderId>` — your own BYOK provider's default model.
123
+ - `provider:<llmProviderId>:<vendorModelId>` — your provider, override model.
124
+ - `<vendorModelId>` — bare vendor id; only resolves when one workspace
125
+ provider can run it.
126
+ - omitted — workspace default.
127
+
128
+ ## Streaming tokens
129
+
130
+ ```ts
131
+ for await (const event of client.streamAgent({
132
+ systemPrompt: "...",
133
+ prompt: "Tell me a story.",
134
+ })) {
135
+ if (event.type === "assistant_delta") process.stdout.write(event.text);
136
+ if (event.type === "result") process.stdout.write("\n");
137
+ }
138
+ ```
139
+
140
+ Or use the `onAssistantDelta` callback on `runAgent`:
141
+
142
+ ```ts
143
+ await client.runAgent({
144
+ systemPrompt: "...",
145
+ prompt: "...",
146
+ onAssistantDelta: (delta) => process.stdout.write(delta),
147
+ });
148
+ ```
149
+
150
+ ## Multi-turn sessions
151
+
152
+ Sessions own the agent spec (system prompt, model, tool defs) and the full
153
+ message history. Each `send` is a run scoped to the session.
154
+
155
+ ```ts
156
+ const session = await client.createSession({
157
+ systemPrompt: "You are a friendly REPL.",
158
+ tools: [
159
+ defineLocalTool({
160
+ name: "today",
161
+ description: "Get today's date as ISO 8601.",
162
+ parameters: z.object({}),
163
+ execute: () => new Date().toISOString().slice(0, 10),
164
+ }),
165
+ ],
166
+ });
167
+
168
+ const r1 = await session.send("What day is it?");
169
+ console.log(r1.text);
170
+
171
+ const r2 = await session.send("And what about tomorrow?");
172
+ console.log(r2.text);
173
+
174
+ await session.end();
175
+ ```
176
+
177
+ ### Tagging runs and sessions with `metadata`
178
+
179
+ Attach a flat string→string KV to runs and sessions so your team can filter
180
+ the dashboard by it (Agent runs → "Metadata" filter):
181
+
182
+ ```ts
183
+ // One-shot run
184
+ await client.runAgent({
185
+ systemPrompt: "...",
186
+ prompt: "...",
187
+ metadata: { customer: "acme", env: "prod", workflow: "support_triage" },
188
+ });
189
+
190
+ // Session — every run created via `session.send` inherits these tags
191
+ const session = await client.createSession({
192
+ systemPrompt: "...",
193
+ metadata: { customer: "acme", env: "prod" },
194
+ });
195
+
196
+ // Per-message override; merged on top of the session's metadata
197
+ // (run-level keys win)
198
+ await session.send("trace this turn", {
199
+ metadata: { trace_id: "trace_abc" },
200
+ });
201
+ ```
202
+
203
+ Limits enforced server-side: max 16 entries; keys match `[A-Za-z0-9._-]{1,64}`;
204
+ values are strings ≤ 256 chars; serialized JSON ≤ 4 KB. Bigger payloads return
205
+ `400 invalid_request`.
206
+
207
+ Resuming a session from a different process re-binds your local tool
208
+ handlers; pass them in via `resumeSession`:
209
+
210
+ ```ts
211
+ const session = await client.resumeSession(sessionId, {
212
+ tools: [
213
+ defineLocalTool({
214
+ name: "today",
215
+ description: "Get today's date as ISO 8601.",
216
+ parameters: z.object({}),
217
+ execute: () => new Date().toISOString().slice(0, 10),
218
+ }),
219
+ ],
220
+ });
221
+ ```
222
+
223
+ ## API reference
224
+
225
+ ### `new MantyxClient(options)`
226
+
227
+ ```ts
228
+ interface MantyxClientOptions {
229
+ apiKey: string;
230
+ workspaceSlug: string;
231
+ baseUrl?: string; // default: https://api.mantyx.com
232
+ fetch?: typeof fetch;
233
+ timeoutMs?: number; // default: 60_000
234
+ }
235
+ ```
236
+
237
+ ### Methods
238
+
239
+ | Method | Returns |
240
+ | --------------------------------------------- | ------------------------------------ |
241
+ | `listModels()` | `Promise<ModelCatalog>` |
242
+ | `runAgent(spec)` | `Promise<RunResult>` |
243
+ | `streamAgent(spec)` | `AsyncIterable<RunEvent>` |
244
+ | `createSession(spec)` | `Promise<AgentSession>` |
245
+ | `resumeSession(sessionId, { tools? })` | `Promise<AgentSession>` |
246
+ | `endSession(sessionId)` | `Promise<void>` |
247
+ | `cancelRun(runId)` | `Promise<void>` |
248
+
249
+ ### Tools
250
+
251
+ | Helper | Use case |
252
+ | -------------------------- | ------------------------------------------------------------ |
253
+ | `defineLocalTool(opts)` | Define a local tool with a Zod parameter schema and handler. |
254
+ | `mantyxTool(id)` | Reference an existing MANTYX tool by id. |
255
+ | `mantyxPluginTool(name)` | Reference an installed platform plugin tool by name. |
256
+
257
+ ### Errors
258
+
259
+ All thrown errors extend `MantyxError`. Common subclasses:
260
+
261
+ - `MantyxAuthError` — 401/403 from the server (bad API key, wrong workspace).
262
+ - `MantyxNetworkError` — transport-layer failures.
263
+ - `MantyxRunError` — the agent loop terminated with an error.
264
+ - `MantyxToolError` — a local tool handler threw or timed out.
265
+
266
+ ## Examples
267
+
268
+ Self-contained example projects live under [`examples/`](./examples/):
269
+
270
+ - `examples/oneshot-local-tool` — minimal one-shot run with a local tool.
271
+ - `examples/session-chat` — interactive REPL on top of a session.
272
+ - `examples/mixed-tools` — combines local, MANTYX, and plugin tools.
273
+ - `examples/streaming` — token streaming to stdout.
274
+ - `examples/list-models` — model catalog + pick-and-run.
275
+
276
+ Each example is its own project (`package.json`, `tsconfig.json`, `README.md`)
277
+ so you can copy any one of them out of the repo and run it standalone.
278
+
279
+ ## Wire protocol
280
+
281
+ This SDK is a thin client over a stable HTTP/SSE protocol. The full
282
+ specification ships with the package at
283
+ [`docs/agent-runs-protocol.md`](./docs/agent-runs-protocol.md). Anyone can
284
+ implement a compatible client in another language.
285
+
286
+ ## Development
287
+
288
+ ```bash
289
+ pnpm install
290
+ pnpm test # unit + mock-server tests
291
+ pnpm typecheck
292
+ pnpm build # emits dist/ (ESM + CJS + d.ts)
293
+ ```
294
+
295
+ The SDK has zero internal `workspace:*` dependencies. `pnpm build` produces a
296
+ self-contained `dist/` ready for `npm publish`.
297
+
298
+ See [`CONTRIBUTING.md`](./CONTRIBUTING.md) for the contribution flow and
299
+ [`EXTRACT.md`](./EXTRACT.md) for the (very small) steps to lift this folder
300
+ into its own public repository.
301
+
302
+ ## License
303
+
304
+ [Apache-2.0](./LICENSE)