@nimble-way/ai-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/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 Derivative
95
+ 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, excluding
103
+ those notices that do not pertain to any part of the Derivative
104
+ 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 do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ 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 reasonable and customary use in describing the
141
+ origin of the Work and 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 Nimble
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,132 @@
1
+ # @nimble-way/ai-sdk
2
+
3
+ Nimble Web Search as a ready-made [Vercel AI SDK](https://ai-sdk.dev) tool. Give any AI SDK agent the ability to search the web with [Nimble](https://nimbleway.com) in a few lines.
4
+
5
+ ## Features
6
+
7
+ - **Web Search** — a `nimbleSearch()` tool the model can call to retrieve ranked, real-time web results and ground its answers in them.
8
+ - **Model- and gateway-agnostic** — an app-side `tool()`; works the same with the Vercel AI Gateway or a direct provider.
9
+ - **Typed** — typed config and normalized output; an injectable client for testing.
10
+
11
+ > Extract, Map, and Crawl tools are planned follow-ups.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm install @nimble-way/ai-sdk ai
17
+ # pnpm add @nimble-way/ai-sdk ai
18
+ # yarn add @nimble-way/ai-sdk ai
19
+ ```
20
+
21
+ `ai` (v6) and `zod` are peer dependencies — you provide your app's copy.
22
+
23
+ ## Prerequisites
24
+
25
+ A Nimble API key (get one at [app.nimbleway.com](https://app.nimbleway.com)):
26
+
27
+ ```bash
28
+ export NIMBLE_API_KEY=... # picked up automatically
29
+ ```
30
+
31
+ Or pass it directly: `nimbleSearch({ apiKey: '...' })`.
32
+
33
+ ## Usage
34
+
35
+ ```ts
36
+ import { generateText, stepCountIs } from 'ai';
37
+ import { nimbleSearch } from '@nimble-way/ai-sdk';
38
+
39
+ const { text } = await generateText({
40
+ model: 'openai/gpt-4o-mini',
41
+ prompt: 'What are the latest developments in agentic web search? Cite sources.',
42
+ tools: {
43
+ webSearch: nimbleSearch({ searchDepth: 'lite', maxResults: 5 }),
44
+ },
45
+ stopWhen: stepCountIs(3),
46
+ });
47
+
48
+ console.log(text);
49
+ ```
50
+
51
+ `streamText` works the same way — register the tool under `tools`.
52
+
53
+ ### Next.js route handler
54
+
55
+ ```ts
56
+ // app/api/chat/route.ts
57
+ import { convertToModelMessages, streamText, stepCountIs, type UIMessage } from 'ai';
58
+ import { nimbleSearch } from '@nimble-way/ai-sdk';
59
+
60
+ export async function POST(req: Request) {
61
+ const { messages }: { messages: UIMessage[] } = await req.json();
62
+
63
+ const result = streamText({
64
+ model: 'openai/gpt-4o-mini',
65
+ messages: await convertToModelMessages(messages),
66
+ tools: {
67
+ webSearch: nimbleSearch({ searchDepth: 'lite', maxResults: 5 }),
68
+ },
69
+ stopWhen: stepCountIs(5),
70
+ });
71
+
72
+ return result.toUIMessageStreamResponse();
73
+ }
74
+ ```
75
+
76
+ ### With or without the Vercel AI Gateway
77
+
78
+ The tool runs **in your app** (an app-side `tool()`, not a provider/server-executed search). It is therefore **gateway-agnostic**: it behaves identically whether you route your model through the [Vercel AI Gateway](https://vercel.com/docs/ai-gateway) (plain-string model IDs like `'openai/gpt-4o-mini'`) or call a provider SDK directly. The gateway, if present, only routes the *model* call.
79
+
80
+ ## Options
81
+
82
+ `nimbleSearch(config)` — all fields optional:
83
+
84
+ | Option | Type | Default | Notes |
85
+ |---|---|---|---|
86
+ | `apiKey` | `string` | `process.env.NIMBLE_API_KEY` | Nimble API key. |
87
+ | `client` | `NimbleSearchClient` | — | Inject a pre-built/mock client (tests, advanced use). |
88
+ | `maxResults` | `number` | `5` | Results when the model doesn't specify. |
89
+ | `maxResultsCap` | `number` | `10` | Hard upper bound, regardless of model request. |
90
+ | `searchDepth` | `'lite' \| 'deep'` | `'lite'` | `lite` = fast metadata; `deep` = full page content. |
91
+ | `country` | `string` | `'US'` | Result localization. |
92
+ | `locale` | `string` | `'en'` | Result localization. |
93
+ | `maxContentLength` | `number` | `10_000` | Truncate each result body. |
94
+
95
+ The **model-facing input** is just `{ query: string, maxResults?: number }` — all policy above is developer-controlled, not model-controlled.
96
+
97
+ ## Output shape
98
+
99
+ ```ts
100
+ {
101
+ query: string;
102
+ requestId?: string;
103
+ totalResults?: number;
104
+ results: Array<{
105
+ title: string;
106
+ url: string;
107
+ description?: string;
108
+ content?: string; // present in `deep`
109
+ position?: number;
110
+ entityType?: string;
111
+ }>;
112
+ }
113
+ ```
114
+
115
+ ## Limitations
116
+
117
+ - **Search only.** Extract / Map / Crawl / Agents are follow-ups.
118
+ - **No answer generation.** `include_answer` is intentionally not exposed.
119
+ - **`searchDepth: 'fast'` is not available** (enterprise-gated).
120
+ - **Runtime:** targets the **Node.js runtime** (Node ≥ 18). Edge/serverless is expected to work but not yet verified — prefer the Node runtime.
121
+
122
+ ## Troubleshooting
123
+
124
+ | Symptom | Fix |
125
+ |---|---|
126
+ | `NimbleConfigError: missing API key` | Set `NIMBLE_API_KEY` or pass `apiKey`. |
127
+ | `NimbleSearchError` with a status | The Nimble API returned an error; the HTTP status is on `err.status`. |
128
+ | Tool never called | Ensure your prompt invites tool use and `stopWhen` allows multiple steps. |
129
+
130
+ ## License
131
+
132
+ Apache-2.0
package/dist/index.cjs ADDED
@@ -0,0 +1,144 @@
1
+ 'use strict';
2
+
3
+ var ai = require('ai');
4
+ var nimbleJs = require('@nimble-way/nimble-js');
5
+ var zod = require('zod');
6
+
7
+ // src/nimble-search.ts
8
+ var nimbleSearchInputSchema = zod.z.object({
9
+ query: zod.z.string().min(1).describe("The web search query."),
10
+ maxResults: zod.z.number().int().positive().optional().describe("How many results to return (clamped to the developer-configured cap).")
11
+ });
12
+
13
+ // src/normalize.ts
14
+ function isSerpMetadata(metadata) {
15
+ return "position" in metadata;
16
+ }
17
+ function truncate(text, max) {
18
+ return text.length > max ? text.slice(0, max) : text;
19
+ }
20
+ function normalizeSearchResponse(response, options) {
21
+ const results = [];
22
+ response.results.forEach((raw, index) => {
23
+ if (!raw.url) return;
24
+ const item = {
25
+ title: raw.title ?? "",
26
+ url: raw.url
27
+ };
28
+ if (raw.description) item.description = raw.description;
29
+ if (raw.content && raw.content.trim().length > 0) {
30
+ item.content = truncate(raw.content, options.maxContentLength);
31
+ }
32
+ if (isSerpMetadata(raw.metadata)) {
33
+ item.position = raw.metadata.position;
34
+ item.entityType = raw.metadata.entity_type;
35
+ } else {
36
+ item.position = index + 1;
37
+ }
38
+ results.push(item);
39
+ });
40
+ return {
41
+ query: options.query,
42
+ requestId: response.request_id,
43
+ totalResults: response.total_results,
44
+ results
45
+ };
46
+ }
47
+
48
+ // src/errors.ts
49
+ var NimbleConfigError = class extends Error {
50
+ constructor(message) {
51
+ super(message);
52
+ this.name = "NimbleConfigError";
53
+ }
54
+ };
55
+ var NimbleSearchError = class extends Error {
56
+ status;
57
+ constructor(message, options) {
58
+ super(message, options?.cause !== void 0 ? { cause: options.cause } : void 0);
59
+ this.name = "NimbleSearchError";
60
+ this.status = options?.status;
61
+ }
62
+ };
63
+
64
+ // src/nimble-search.ts
65
+ var NIMBLE_SEARCH_DEFAULTS = {
66
+ maxResults: 5,
67
+ maxResultsCap: 10,
68
+ searchDepth: "lite",
69
+ country: "US",
70
+ locale: "en",
71
+ maxContentLength: 1e4,
72
+ focus: "general"
73
+ };
74
+ function clamp(value, min, max) {
75
+ return Math.min(Math.max(value, min), max);
76
+ }
77
+ function readStatus(err) {
78
+ if (typeof err === "object" && err !== null && "status" in err) {
79
+ const status = err.status;
80
+ return typeof status === "number" ? status : void 0;
81
+ }
82
+ return void 0;
83
+ }
84
+ function toSearchError(err) {
85
+ if (err instanceof NimbleSearchError) return err;
86
+ const message = err instanceof Error ? err.message : String(err);
87
+ return new NimbleSearchError(`Nimble search failed: ${message}`, {
88
+ status: readStatus(err),
89
+ cause: err
90
+ });
91
+ }
92
+ function resolveClient(config) {
93
+ if (config.client) return config.client;
94
+ const apiKey = config.apiKey ?? process.env.NIMBLE_API_KEY;
95
+ if (!apiKey) {
96
+ throw new NimbleConfigError(
97
+ "Missing Nimble API key: set NIMBLE_API_KEY or pass { apiKey } to nimbleSearch()."
98
+ );
99
+ }
100
+ return new nimbleJs.Nimble({ apiKey });
101
+ }
102
+ function nimbleSearch(config = {}) {
103
+ const maxResults = config.maxResults ?? NIMBLE_SEARCH_DEFAULTS.maxResults;
104
+ const maxResultsCap = config.maxResultsCap ?? NIMBLE_SEARCH_DEFAULTS.maxResultsCap;
105
+ const searchDepth = config.searchDepth ?? NIMBLE_SEARCH_DEFAULTS.searchDepth;
106
+ const country = config.country ?? NIMBLE_SEARCH_DEFAULTS.country;
107
+ const locale = config.locale ?? NIMBLE_SEARCH_DEFAULTS.locale;
108
+ const maxContentLength = config.maxContentLength ?? NIMBLE_SEARCH_DEFAULTS.maxContentLength;
109
+ return ai.tool({
110
+ description: "Search the web with Nimble and return ranked results (title, url, snippet, and page content) for answering questions about current or factual information.",
111
+ inputSchema: nimbleSearchInputSchema,
112
+ execute: async (input) => {
113
+ const client = resolveClient(config);
114
+ const params = {
115
+ query: input.query,
116
+ max_results: clamp(input.maxResults ?? maxResults, 1, maxResultsCap),
117
+ search_depth: searchDepth,
118
+ focus: NIMBLE_SEARCH_DEFAULTS.focus,
119
+ // fixed 'general' in v1
120
+ country,
121
+ locale
122
+ };
123
+ let raw;
124
+ try {
125
+ raw = await client.search(params);
126
+ } catch (err) {
127
+ throw toSearchError(err);
128
+ }
129
+ return normalizeSearchResponse(raw, {
130
+ query: input.query,
131
+ maxContentLength
132
+ });
133
+ }
134
+ });
135
+ }
136
+
137
+ exports.NIMBLE_SEARCH_DEFAULTS = NIMBLE_SEARCH_DEFAULTS;
138
+ exports.NimbleConfigError = NimbleConfigError;
139
+ exports.NimbleSearchError = NimbleSearchError;
140
+ exports.nimbleSearch = nimbleSearch;
141
+ exports.nimbleSearchInputSchema = nimbleSearchInputSchema;
142
+ exports.normalizeSearchResponse = normalizeSearchResponse;
143
+ //# sourceMappingURL=index.cjs.map
144
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schemas.ts","../src/normalize.ts","../src/errors.ts","../src/nimble-search.ts"],"names":["z","Nimble","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AAuB,aAAA;AACrE,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,WAAA,IAAe,sBAAA,CAAuB,WAAA;AACjE,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,OAAA,IAAW,sBAAA,CAAuB,OAAA;AACzD,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,MAAA,IAAU,sBAAA,CAAuB,MAAA;AACvD,EAAA,MAAM,gBAAA,GAAmB,MAAA,CAAO,gBAAA,IAAoB,sBAAA,CAAuB,gBAAA;AAE3E,EAAA,OAAOC,OAAA,CAAK;AAAA,IACV,WAAA,EACE,4JAAA;AAAA,IAGF,WAAA,EAAa,uBAAA;AAAA,IACb,OAAA,EAAS,OAAO,KAAA,KAAuC;AACrD,MAAA,MAAM,MAAA,GAAS,cAAc,MAAM,CAAA;AAEnC,MAAA,MAAM,MAAA,GAA6B;AAAA,QACjC,OAAO,KAAA,CAAM,KAAA;AAAA,QACb,aAAa,KAAA,CAAM,KAAA,CAAM,UAAA,IAAc,UAAA,EAAY,GAAG,aAAa,CAAA;AAAA,QACnE,YAAA,EAAc,WAAA;AAAA,QACd,OAAO,sBAAA,CAAuB,KAAA;AAAA;AAAA,QAC9B,OAAA;AAAA,QACA;AAAA,OACF;AAEA,MAAA,IAAI,GAAA;AACJ,MAAA,IAAI;AACF,QAAA,GAAA,GAAM,MAAM,MAAA,CAAO,MAAA,CAAO,MAAM,CAAA;AAAA,MAClC,SAAS,GAAA,EAAK;AACZ,QAAA,MAAM,cAAc,GAAG,CAAA;AAAA,MACzB;AAEA,MAAA,OAAO,wBAAwB,GAAA,EAAK;AAAA,QAClC,OAAO,KAAA,CAAM,KAAA;AAAA,QACb;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH","file":"index.cjs","sourcesContent":["import { z } from 'zod';\n\n/**\n * The tool input the model fills in. Kept deliberately small: the model only\n * chooses the query and (optionally) how many results it wants. All policy\n * (depth, focus, region, caps) is fixed by the developer via the factory\n * config, not by the model.\n */\nexport const nimbleSearchInputSchema = z.object({\n query: z.string().min(1).describe('The web search query.'),\n maxResults: z\n .number()\n .int()\n .positive()\n .optional()\n .describe('How many results to return (clamped to the developer-configured cap).'),\n});\n\nexport type NimbleSearchInput = z.infer<typeof nimbleSearchInputSchema>;\n\n/**\n * v1 exposes only the two non-enterprise depths. `fast` is enterprise-gated and\n * intentionally not offered here.\n */\nexport type SearchDepth = 'lite' | 'deep';\n\n/**\n * Developer-facing factory config. `focus` is fixed to `general` in v1 and is\n * not exposed. `include_answer` and `search_depth: 'fast'` are intentionally\n * absent (enterprise / unverified-entitlement surface).\n */\nexport interface NimbleSearchToolConfig {\n /** Nimble API key. Defaults to `process.env.NIMBLE_API_KEY`. */\n apiKey?: string;\n /** Inject a pre-built / mock Nimble client (tests, advanced users). */\n client?: NimbleSearchClient;\n /** Default number of results when the model doesn't specify. Default 5. */\n maxResults?: number;\n /** Hard upper bound on results, regardless of model request. Default 10. */\n maxResultsCap?: number;\n /** Search depth. Default `lite`. */\n searchDepth?: SearchDepth;\n /** ISO country for result localization. Default `US`. */\n country?: string;\n /** Locale for result localization. Default `en`. */\n locale?: string;\n /** Truncate each result's body to this many characters. Default 10_000. */\n maxContentLength?: number;\n}\n\n/**\n * Structural surface of `@nimble-way/nimble-js`'s `client.search()` that this\n * package relies on. Declared structurally so the scaffold typechecks without\n * pinning to the SDK's generated type names, and so tests can inject a mock.\n *\n * Phase B: reconcile field casing/names against\n * `sdks/nimble-js/checkout/src/` after `./tools/sync-sdk.sh nimble-js`.\n */\nexport interface NimbleSearchParams {\n query: string;\n max_results?: number;\n search_depth?: SearchDepth;\n focus?: string;\n country?: string;\n locale?: string;\n}\n\n/** Metadata for SERP-based results (general/news/location focus). */\nexport interface NimbleSerpMetadata {\n country: string;\n entity_type: string;\n locale: string;\n position: number;\n driver?: string | null;\n}\n\n/** Metadata for WSA-based results (shopping/social/geo focus). */\nexport interface NimbleWsaMetadata {\n agent_name: string;\n}\n\nexport interface NimbleRawSearchResult {\n /** Full page text in `deep`; may be empty in `lite`. */\n content: string;\n description: string;\n title: string;\n url: string;\n /** SERP focus (v1 `general`) yields {@link NimbleSerpMetadata}. */\n metadata: NimbleSerpMetadata | NimbleWsaMetadata;\n /** Platform-specific extras (price, publish_date, …); omitted when none. */\n additional_data?: Record<string, unknown> | null;\n}\n\nexport interface NimbleRawSearchResponse {\n request_id: string;\n results: NimbleRawSearchResult[];\n total_results: number;\n /** Intentionally never surfaced in v1 (include_answer is off). */\n answer?: string | null;\n}\n\nexport interface NimbleSearchClient {\n search(params: NimbleSearchParams): Promise<NimbleRawSearchResponse>;\n}\n\n/** A single normalized result item returned to the model. */\nexport interface NimbleSearchResultItem {\n title: string;\n url: string;\n description?: string;\n content?: string;\n position?: number;\n entityType?: string;\n}\n\n/** The normalized tool output. `answer` is intentionally omitted in v1. */\nexport interface NimbleSearchOutput {\n query: string;\n requestId?: string;\n totalResults?: number;\n results: NimbleSearchResultItem[];\n}\n","import type {\n NimbleRawSearchResponse,\n NimbleRawSearchResult,\n NimbleSearchOutput,\n NimbleSearchResultItem,\n NimbleSerpMetadata,\n} from './schemas';\n\nexport interface NormalizeOptions {\n query: string;\n maxContentLength: number;\n}\n\n/** SERP focus (v1 `general`) carries position + entity_type; WSA does not. */\nfunction isSerpMetadata(\n metadata: NimbleRawSearchResult['metadata'],\n): metadata is NimbleSerpMetadata {\n return 'position' in metadata;\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? text.slice(0, max) : text;\n}\n\n/**\n * Map a raw `/v1/search` response into the package's normalized output shape.\n *\n * - `description` is the snippet (always present when the API returns one).\n * - `content` is the full page text, present only in `deep` depth (empty in\n * `lite`), truncated to `maxContentLength`.\n * - `position` / `entityType` come from SERP metadata; for WSA results\n * `position` falls back to the array index and `entityType` is omitted.\n * - Results without a URL are dropped (defensive).\n * - `response.answer` is never surfaced in v1.\n */\nexport function normalizeSearchResponse(\n response: NimbleRawSearchResponse,\n options: NormalizeOptions,\n): NimbleSearchOutput {\n const results: NimbleSearchResultItem[] = [];\n\n response.results.forEach((raw, index) => {\n if (!raw.url) return;\n\n const item: NimbleSearchResultItem = {\n title: raw.title ?? '',\n url: raw.url,\n };\n if (raw.description) item.description = raw.description;\n if (raw.content && raw.content.trim().length > 0) {\n item.content = truncate(raw.content, options.maxContentLength);\n }\n\n if (isSerpMetadata(raw.metadata)) {\n item.position = raw.metadata.position;\n item.entityType = raw.metadata.entity_type;\n } else {\n item.position = index + 1;\n }\n\n results.push(item);\n });\n\n return {\n query: options.query,\n requestId: response.request_id,\n totalResults: response.total_results,\n results,\n };\n}\n","/**\n * Thrown when the tool is invoked without a resolvable API key (no `apiKey`\n * config and no `NIMBLE_API_KEY` in the environment) and no injected client.\n * Raised at execute time, not at factory-construction time, so the tool can be\n * constructed in environments without a key (e.g. unit tests, type-checking).\n */\nexport class NimbleConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'NimbleConfigError';\n }\n}\n\n/**\n * Wraps an error surfaced by the Nimble client / API during a search call,\n * preserving the HTTP status when available. The AI SDK surfaces a thrown\n * tool error back to the model as a tool-call failure.\n */\nexport class NimbleSearchError extends Error {\n readonly status?: number;\n\n constructor(message: string, options?: { status?: number; cause?: unknown }) {\n super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = 'NimbleSearchError';\n this.status = options?.status;\n }\n}\n","import { tool } from 'ai';\nimport { Nimble } from '@nimble-way/nimble-js';\nimport { nimbleSearchInputSchema } from './schemas';\nimport type {\n NimbleSearchClient,\n NimbleSearchOutput,\n NimbleSearchParams,\n NimbleSearchToolConfig,\n} from './schemas';\nimport { normalizeSearchResponse } from './normalize';\nimport { NimbleConfigError, NimbleSearchError } from './errors';\n\n/** v1 factory defaults. `focus` is fixed to `general` and not user-exposed. */\nexport const NIMBLE_SEARCH_DEFAULTS = {\n maxResults: 5,\n maxResultsCap: 10,\n searchDepth: 'lite',\n country: 'US',\n locale: 'en',\n maxContentLength: 10_000,\n focus: 'general',\n} as const;\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(Math.max(value, min), max);\n}\n\nfunction readStatus(err: unknown): number | undefined {\n if (typeof err === 'object' && err !== null && 'status' in err) {\n const status = (err as { status?: unknown }).status;\n return typeof status === 'number' ? status : undefined;\n }\n return undefined;\n}\n\nfunction toSearchError(err: unknown): NimbleSearchError {\n if (err instanceof NimbleSearchError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new NimbleSearchError(`Nimble search failed: ${message}`, {\n status: readStatus(err),\n cause: err,\n });\n}\n\nfunction resolveClient(config: NimbleSearchToolConfig): NimbleSearchClient {\n if (config.client) return config.client;\n const apiKey = config.apiKey ?? process.env.NIMBLE_API_KEY;\n if (!apiKey) {\n throw new NimbleConfigError(\n 'Missing Nimble API key: set NIMBLE_API_KEY or pass { apiKey } to nimbleSearch().',\n );\n }\n return new Nimble({ apiKey }) as unknown as NimbleSearchClient;\n}\n\n/**\n * Create a ready-made Vercel AI SDK web-search tool backed by Nimble Search\n * (`@nimble-way/nimble-js` → `POST /v1/search`).\n *\n * The model only chooses `{ query, maxResults? }`; all policy (depth, focus,\n * region, caps) is fixed by `config` — mirroring the Exa `webSearch()` shape.\n *\n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { nimbleSearch } from '@nimble-way/ai-sdk';\n *\n * const { text } = await generateText({\n * model: 'anthropic/claude-sonnet-4.6',\n * prompt: 'What are the latest Nimble release notes?',\n * tools: { webSearch: nimbleSearch({ searchDepth: 'lite', maxResults: 5 }) },\n * });\n * ```\n */\nexport function nimbleSearch(config: NimbleSearchToolConfig = {}) {\n const maxResults = config.maxResults ?? NIMBLE_SEARCH_DEFAULTS.maxResults;\n const maxResultsCap = config.maxResultsCap ?? NIMBLE_SEARCH_DEFAULTS.maxResultsCap;\n const searchDepth = config.searchDepth ?? NIMBLE_SEARCH_DEFAULTS.searchDepth;\n const country = config.country ?? NIMBLE_SEARCH_DEFAULTS.country;\n const locale = config.locale ?? NIMBLE_SEARCH_DEFAULTS.locale;\n const maxContentLength = config.maxContentLength ?? NIMBLE_SEARCH_DEFAULTS.maxContentLength;\n\n return tool({\n description:\n 'Search the web with Nimble and return ranked results (title, url, ' +\n 'snippet, and page content) for answering questions about current or ' +\n 'factual information.',\n inputSchema: nimbleSearchInputSchema,\n execute: async (input): Promise<NimbleSearchOutput> => {\n const client = resolveClient(config);\n\n const params: NimbleSearchParams = {\n query: input.query,\n max_results: clamp(input.maxResults ?? maxResults, 1, maxResultsCap),\n search_depth: searchDepth,\n focus: NIMBLE_SEARCH_DEFAULTS.focus, // fixed 'general' in v1\n country,\n locale,\n };\n\n let raw;\n try {\n raw = await client.search(params);\n } catch (err) {\n throw toSearchError(err);\n }\n\n return normalizeSearchResponse(raw, {\n query: input.query,\n maxContentLength,\n });\n },\n });\n}\n"]}
@@ -0,0 +1,188 @@
1
+ import * as ai from 'ai';
2
+ import { z } from 'zod';
3
+
4
+ /**
5
+ * The tool input the model fills in. Kept deliberately small: the model only
6
+ * chooses the query and (optionally) how many results it wants. All policy
7
+ * (depth, focus, region, caps) is fixed by the developer via the factory
8
+ * config, not by the model.
9
+ */
10
+ declare const nimbleSearchInputSchema: z.ZodObject<{
11
+ query: z.ZodString;
12
+ maxResults: z.ZodOptional<z.ZodNumber>;
13
+ }, "strip", z.ZodTypeAny, {
14
+ query: string;
15
+ maxResults?: number | undefined;
16
+ }, {
17
+ query: string;
18
+ maxResults?: number | undefined;
19
+ }>;
20
+ type NimbleSearchInput = z.infer<typeof nimbleSearchInputSchema>;
21
+ /**
22
+ * v1 exposes only the two non-enterprise depths. `fast` is enterprise-gated and
23
+ * intentionally not offered here.
24
+ */
25
+ type SearchDepth = 'lite' | 'deep';
26
+ /**
27
+ * Developer-facing factory config. `focus` is fixed to `general` in v1 and is
28
+ * not exposed. `include_answer` and `search_depth: 'fast'` are intentionally
29
+ * absent (enterprise / unverified-entitlement surface).
30
+ */
31
+ interface NimbleSearchToolConfig {
32
+ /** Nimble API key. Defaults to `process.env.NIMBLE_API_KEY`. */
33
+ apiKey?: string;
34
+ /** Inject a pre-built / mock Nimble client (tests, advanced users). */
35
+ client?: NimbleSearchClient;
36
+ /** Default number of results when the model doesn't specify. Default 5. */
37
+ maxResults?: number;
38
+ /** Hard upper bound on results, regardless of model request. Default 10. */
39
+ maxResultsCap?: number;
40
+ /** Search depth. Default `lite`. */
41
+ searchDepth?: SearchDepth;
42
+ /** ISO country for result localization. Default `US`. */
43
+ country?: string;
44
+ /** Locale for result localization. Default `en`. */
45
+ locale?: string;
46
+ /** Truncate each result's body to this many characters. Default 10_000. */
47
+ maxContentLength?: number;
48
+ }
49
+ /**
50
+ * Structural surface of `@nimble-way/nimble-js`'s `client.search()` that this
51
+ * package relies on. Declared structurally so the scaffold typechecks without
52
+ * pinning to the SDK's generated type names, and so tests can inject a mock.
53
+ *
54
+ * Phase B: reconcile field casing/names against
55
+ * `sdks/nimble-js/checkout/src/` after `./tools/sync-sdk.sh nimble-js`.
56
+ */
57
+ interface NimbleSearchParams {
58
+ query: string;
59
+ max_results?: number;
60
+ search_depth?: SearchDepth;
61
+ focus?: string;
62
+ country?: string;
63
+ locale?: string;
64
+ }
65
+ /** Metadata for SERP-based results (general/news/location focus). */
66
+ interface NimbleSerpMetadata {
67
+ country: string;
68
+ entity_type: string;
69
+ locale: string;
70
+ position: number;
71
+ driver?: string | null;
72
+ }
73
+ /** Metadata for WSA-based results (shopping/social/geo focus). */
74
+ interface NimbleWsaMetadata {
75
+ agent_name: string;
76
+ }
77
+ interface NimbleRawSearchResult {
78
+ /** Full page text in `deep`; may be empty in `lite`. */
79
+ content: string;
80
+ description: string;
81
+ title: string;
82
+ url: string;
83
+ /** SERP focus (v1 `general`) yields {@link NimbleSerpMetadata}. */
84
+ metadata: NimbleSerpMetadata | NimbleWsaMetadata;
85
+ /** Platform-specific extras (price, publish_date, …); omitted when none. */
86
+ additional_data?: Record<string, unknown> | null;
87
+ }
88
+ interface NimbleRawSearchResponse {
89
+ request_id: string;
90
+ results: NimbleRawSearchResult[];
91
+ total_results: number;
92
+ /** Intentionally never surfaced in v1 (include_answer is off). */
93
+ answer?: string | null;
94
+ }
95
+ interface NimbleSearchClient {
96
+ search(params: NimbleSearchParams): Promise<NimbleRawSearchResponse>;
97
+ }
98
+ /** A single normalized result item returned to the model. */
99
+ interface NimbleSearchResultItem {
100
+ title: string;
101
+ url: string;
102
+ description?: string;
103
+ content?: string;
104
+ position?: number;
105
+ entityType?: string;
106
+ }
107
+ /** The normalized tool output. `answer` is intentionally omitted in v1. */
108
+ interface NimbleSearchOutput {
109
+ query: string;
110
+ requestId?: string;
111
+ totalResults?: number;
112
+ results: NimbleSearchResultItem[];
113
+ }
114
+
115
+ /** v1 factory defaults. `focus` is fixed to `general` and not user-exposed. */
116
+ declare const NIMBLE_SEARCH_DEFAULTS: {
117
+ readonly maxResults: 5;
118
+ readonly maxResultsCap: 10;
119
+ readonly searchDepth: "lite";
120
+ readonly country: "US";
121
+ readonly locale: "en";
122
+ readonly maxContentLength: 10000;
123
+ readonly focus: "general";
124
+ };
125
+ /**
126
+ * Create a ready-made Vercel AI SDK web-search tool backed by Nimble Search
127
+ * (`@nimble-way/nimble-js` → `POST /v1/search`).
128
+ *
129
+ * The model only chooses `{ query, maxResults? }`; all policy (depth, focus,
130
+ * region, caps) is fixed by `config` — mirroring the Exa `webSearch()` shape.
131
+ *
132
+ * @example
133
+ * ```ts
134
+ * import { generateText } from 'ai';
135
+ * import { nimbleSearch } from '@nimble-way/ai-sdk';
136
+ *
137
+ * const { text } = await generateText({
138
+ * model: 'anthropic/claude-sonnet-4.6',
139
+ * prompt: 'What are the latest Nimble release notes?',
140
+ * tools: { webSearch: nimbleSearch({ searchDepth: 'lite', maxResults: 5 }) },
141
+ * });
142
+ * ```
143
+ */
144
+ declare function nimbleSearch(config?: NimbleSearchToolConfig): ai.Tool<{
145
+ query: string;
146
+ maxResults?: number | undefined;
147
+ }, NimbleSearchOutput>;
148
+
149
+ interface NormalizeOptions {
150
+ query: string;
151
+ maxContentLength: number;
152
+ }
153
+ /**
154
+ * Map a raw `/v1/search` response into the package's normalized output shape.
155
+ *
156
+ * - `description` is the snippet (always present when the API returns one).
157
+ * - `content` is the full page text, present only in `deep` depth (empty in
158
+ * `lite`), truncated to `maxContentLength`.
159
+ * - `position` / `entityType` come from SERP metadata; for WSA results
160
+ * `position` falls back to the array index and `entityType` is omitted.
161
+ * - Results without a URL are dropped (defensive).
162
+ * - `response.answer` is never surfaced in v1.
163
+ */
164
+ declare function normalizeSearchResponse(response: NimbleRawSearchResponse, options: NormalizeOptions): NimbleSearchOutput;
165
+
166
+ /**
167
+ * Thrown when the tool is invoked without a resolvable API key (no `apiKey`
168
+ * config and no `NIMBLE_API_KEY` in the environment) and no injected client.
169
+ * Raised at execute time, not at factory-construction time, so the tool can be
170
+ * constructed in environments without a key (e.g. unit tests, type-checking).
171
+ */
172
+ declare class NimbleConfigError extends Error {
173
+ constructor(message: string);
174
+ }
175
+ /**
176
+ * Wraps an error surfaced by the Nimble client / API during a search call,
177
+ * preserving the HTTP status when available. The AI SDK surfaces a thrown
178
+ * tool error back to the model as a tool-call failure.
179
+ */
180
+ declare class NimbleSearchError extends Error {
181
+ readonly status?: number;
182
+ constructor(message: string, options?: {
183
+ status?: number;
184
+ cause?: unknown;
185
+ });
186
+ }
187
+
188
+ export { NIMBLE_SEARCH_DEFAULTS, NimbleConfigError, type NimbleRawSearchResponse, type NimbleRawSearchResult, type NimbleSearchClient, NimbleSearchError, type NimbleSearchInput, type NimbleSearchOutput, type NimbleSearchParams, type NimbleSearchResultItem, type NimbleSearchToolConfig, type NimbleSerpMetadata, type NimbleWsaMetadata, type NormalizeOptions, type SearchDepth, nimbleSearch, nimbleSearchInputSchema, normalizeSearchResponse };
@@ -0,0 +1,188 @@
1
+ import * as ai from 'ai';
2
+ import { z } from 'zod';
3
+
4
+ /**
5
+ * The tool input the model fills in. Kept deliberately small: the model only
6
+ * chooses the query and (optionally) how many results it wants. All policy
7
+ * (depth, focus, region, caps) is fixed by the developer via the factory
8
+ * config, not by the model.
9
+ */
10
+ declare const nimbleSearchInputSchema: z.ZodObject<{
11
+ query: z.ZodString;
12
+ maxResults: z.ZodOptional<z.ZodNumber>;
13
+ }, "strip", z.ZodTypeAny, {
14
+ query: string;
15
+ maxResults?: number | undefined;
16
+ }, {
17
+ query: string;
18
+ maxResults?: number | undefined;
19
+ }>;
20
+ type NimbleSearchInput = z.infer<typeof nimbleSearchInputSchema>;
21
+ /**
22
+ * v1 exposes only the two non-enterprise depths. `fast` is enterprise-gated and
23
+ * intentionally not offered here.
24
+ */
25
+ type SearchDepth = 'lite' | 'deep';
26
+ /**
27
+ * Developer-facing factory config. `focus` is fixed to `general` in v1 and is
28
+ * not exposed. `include_answer` and `search_depth: 'fast'` are intentionally
29
+ * absent (enterprise / unverified-entitlement surface).
30
+ */
31
+ interface NimbleSearchToolConfig {
32
+ /** Nimble API key. Defaults to `process.env.NIMBLE_API_KEY`. */
33
+ apiKey?: string;
34
+ /** Inject a pre-built / mock Nimble client (tests, advanced users). */
35
+ client?: NimbleSearchClient;
36
+ /** Default number of results when the model doesn't specify. Default 5. */
37
+ maxResults?: number;
38
+ /** Hard upper bound on results, regardless of model request. Default 10. */
39
+ maxResultsCap?: number;
40
+ /** Search depth. Default `lite`. */
41
+ searchDepth?: SearchDepth;
42
+ /** ISO country for result localization. Default `US`. */
43
+ country?: string;
44
+ /** Locale for result localization. Default `en`. */
45
+ locale?: string;
46
+ /** Truncate each result's body to this many characters. Default 10_000. */
47
+ maxContentLength?: number;
48
+ }
49
+ /**
50
+ * Structural surface of `@nimble-way/nimble-js`'s `client.search()` that this
51
+ * package relies on. Declared structurally so the scaffold typechecks without
52
+ * pinning to the SDK's generated type names, and so tests can inject a mock.
53
+ *
54
+ * Phase B: reconcile field casing/names against
55
+ * `sdks/nimble-js/checkout/src/` after `./tools/sync-sdk.sh nimble-js`.
56
+ */
57
+ interface NimbleSearchParams {
58
+ query: string;
59
+ max_results?: number;
60
+ search_depth?: SearchDepth;
61
+ focus?: string;
62
+ country?: string;
63
+ locale?: string;
64
+ }
65
+ /** Metadata for SERP-based results (general/news/location focus). */
66
+ interface NimbleSerpMetadata {
67
+ country: string;
68
+ entity_type: string;
69
+ locale: string;
70
+ position: number;
71
+ driver?: string | null;
72
+ }
73
+ /** Metadata for WSA-based results (shopping/social/geo focus). */
74
+ interface NimbleWsaMetadata {
75
+ agent_name: string;
76
+ }
77
+ interface NimbleRawSearchResult {
78
+ /** Full page text in `deep`; may be empty in `lite`. */
79
+ content: string;
80
+ description: string;
81
+ title: string;
82
+ url: string;
83
+ /** SERP focus (v1 `general`) yields {@link NimbleSerpMetadata}. */
84
+ metadata: NimbleSerpMetadata | NimbleWsaMetadata;
85
+ /** Platform-specific extras (price, publish_date, …); omitted when none. */
86
+ additional_data?: Record<string, unknown> | null;
87
+ }
88
+ interface NimbleRawSearchResponse {
89
+ request_id: string;
90
+ results: NimbleRawSearchResult[];
91
+ total_results: number;
92
+ /** Intentionally never surfaced in v1 (include_answer is off). */
93
+ answer?: string | null;
94
+ }
95
+ interface NimbleSearchClient {
96
+ search(params: NimbleSearchParams): Promise<NimbleRawSearchResponse>;
97
+ }
98
+ /** A single normalized result item returned to the model. */
99
+ interface NimbleSearchResultItem {
100
+ title: string;
101
+ url: string;
102
+ description?: string;
103
+ content?: string;
104
+ position?: number;
105
+ entityType?: string;
106
+ }
107
+ /** The normalized tool output. `answer` is intentionally omitted in v1. */
108
+ interface NimbleSearchOutput {
109
+ query: string;
110
+ requestId?: string;
111
+ totalResults?: number;
112
+ results: NimbleSearchResultItem[];
113
+ }
114
+
115
+ /** v1 factory defaults. `focus` is fixed to `general` and not user-exposed. */
116
+ declare const NIMBLE_SEARCH_DEFAULTS: {
117
+ readonly maxResults: 5;
118
+ readonly maxResultsCap: 10;
119
+ readonly searchDepth: "lite";
120
+ readonly country: "US";
121
+ readonly locale: "en";
122
+ readonly maxContentLength: 10000;
123
+ readonly focus: "general";
124
+ };
125
+ /**
126
+ * Create a ready-made Vercel AI SDK web-search tool backed by Nimble Search
127
+ * (`@nimble-way/nimble-js` → `POST /v1/search`).
128
+ *
129
+ * The model only chooses `{ query, maxResults? }`; all policy (depth, focus,
130
+ * region, caps) is fixed by `config` — mirroring the Exa `webSearch()` shape.
131
+ *
132
+ * @example
133
+ * ```ts
134
+ * import { generateText } from 'ai';
135
+ * import { nimbleSearch } from '@nimble-way/ai-sdk';
136
+ *
137
+ * const { text } = await generateText({
138
+ * model: 'anthropic/claude-sonnet-4.6',
139
+ * prompt: 'What are the latest Nimble release notes?',
140
+ * tools: { webSearch: nimbleSearch({ searchDepth: 'lite', maxResults: 5 }) },
141
+ * });
142
+ * ```
143
+ */
144
+ declare function nimbleSearch(config?: NimbleSearchToolConfig): ai.Tool<{
145
+ query: string;
146
+ maxResults?: number | undefined;
147
+ }, NimbleSearchOutput>;
148
+
149
+ interface NormalizeOptions {
150
+ query: string;
151
+ maxContentLength: number;
152
+ }
153
+ /**
154
+ * Map a raw `/v1/search` response into the package's normalized output shape.
155
+ *
156
+ * - `description` is the snippet (always present when the API returns one).
157
+ * - `content` is the full page text, present only in `deep` depth (empty in
158
+ * `lite`), truncated to `maxContentLength`.
159
+ * - `position` / `entityType` come from SERP metadata; for WSA results
160
+ * `position` falls back to the array index and `entityType` is omitted.
161
+ * - Results without a URL are dropped (defensive).
162
+ * - `response.answer` is never surfaced in v1.
163
+ */
164
+ declare function normalizeSearchResponse(response: NimbleRawSearchResponse, options: NormalizeOptions): NimbleSearchOutput;
165
+
166
+ /**
167
+ * Thrown when the tool is invoked without a resolvable API key (no `apiKey`
168
+ * config and no `NIMBLE_API_KEY` in the environment) and no injected client.
169
+ * Raised at execute time, not at factory-construction time, so the tool can be
170
+ * constructed in environments without a key (e.g. unit tests, type-checking).
171
+ */
172
+ declare class NimbleConfigError extends Error {
173
+ constructor(message: string);
174
+ }
175
+ /**
176
+ * Wraps an error surfaced by the Nimble client / API during a search call,
177
+ * preserving the HTTP status when available. The AI SDK surfaces a thrown
178
+ * tool error back to the model as a tool-call failure.
179
+ */
180
+ declare class NimbleSearchError extends Error {
181
+ readonly status?: number;
182
+ constructor(message: string, options?: {
183
+ status?: number;
184
+ cause?: unknown;
185
+ });
186
+ }
187
+
188
+ export { NIMBLE_SEARCH_DEFAULTS, NimbleConfigError, type NimbleRawSearchResponse, type NimbleRawSearchResult, type NimbleSearchClient, NimbleSearchError, type NimbleSearchInput, type NimbleSearchOutput, type NimbleSearchParams, type NimbleSearchResultItem, type NimbleSearchToolConfig, type NimbleSerpMetadata, type NimbleWsaMetadata, type NormalizeOptions, type SearchDepth, nimbleSearch, nimbleSearchInputSchema, normalizeSearchResponse };
package/dist/index.js ADDED
@@ -0,0 +1,137 @@
1
+ import { tool } from 'ai';
2
+ import { Nimble } from '@nimble-way/nimble-js';
3
+ import { z } from 'zod';
4
+
5
+ // src/nimble-search.ts
6
+ var nimbleSearchInputSchema = z.object({
7
+ query: z.string().min(1).describe("The web search query."),
8
+ maxResults: z.number().int().positive().optional().describe("How many results to return (clamped to the developer-configured cap).")
9
+ });
10
+
11
+ // src/normalize.ts
12
+ function isSerpMetadata(metadata) {
13
+ return "position" in metadata;
14
+ }
15
+ function truncate(text, max) {
16
+ return text.length > max ? text.slice(0, max) : text;
17
+ }
18
+ function normalizeSearchResponse(response, options) {
19
+ const results = [];
20
+ response.results.forEach((raw, index) => {
21
+ if (!raw.url) return;
22
+ const item = {
23
+ title: raw.title ?? "",
24
+ url: raw.url
25
+ };
26
+ if (raw.description) item.description = raw.description;
27
+ if (raw.content && raw.content.trim().length > 0) {
28
+ item.content = truncate(raw.content, options.maxContentLength);
29
+ }
30
+ if (isSerpMetadata(raw.metadata)) {
31
+ item.position = raw.metadata.position;
32
+ item.entityType = raw.metadata.entity_type;
33
+ } else {
34
+ item.position = index + 1;
35
+ }
36
+ results.push(item);
37
+ });
38
+ return {
39
+ query: options.query,
40
+ requestId: response.request_id,
41
+ totalResults: response.total_results,
42
+ results
43
+ };
44
+ }
45
+
46
+ // src/errors.ts
47
+ var NimbleConfigError = class extends Error {
48
+ constructor(message) {
49
+ super(message);
50
+ this.name = "NimbleConfigError";
51
+ }
52
+ };
53
+ var NimbleSearchError = class extends Error {
54
+ status;
55
+ constructor(message, options) {
56
+ super(message, options?.cause !== void 0 ? { cause: options.cause } : void 0);
57
+ this.name = "NimbleSearchError";
58
+ this.status = options?.status;
59
+ }
60
+ };
61
+
62
+ // src/nimble-search.ts
63
+ var NIMBLE_SEARCH_DEFAULTS = {
64
+ maxResults: 5,
65
+ maxResultsCap: 10,
66
+ searchDepth: "lite",
67
+ country: "US",
68
+ locale: "en",
69
+ maxContentLength: 1e4,
70
+ focus: "general"
71
+ };
72
+ function clamp(value, min, max) {
73
+ return Math.min(Math.max(value, min), max);
74
+ }
75
+ function readStatus(err) {
76
+ if (typeof err === "object" && err !== null && "status" in err) {
77
+ const status = err.status;
78
+ return typeof status === "number" ? status : void 0;
79
+ }
80
+ return void 0;
81
+ }
82
+ function toSearchError(err) {
83
+ if (err instanceof NimbleSearchError) return err;
84
+ const message = err instanceof Error ? err.message : String(err);
85
+ return new NimbleSearchError(`Nimble search failed: ${message}`, {
86
+ status: readStatus(err),
87
+ cause: err
88
+ });
89
+ }
90
+ function resolveClient(config) {
91
+ if (config.client) return config.client;
92
+ const apiKey = config.apiKey ?? process.env.NIMBLE_API_KEY;
93
+ if (!apiKey) {
94
+ throw new NimbleConfigError(
95
+ "Missing Nimble API key: set NIMBLE_API_KEY or pass { apiKey } to nimbleSearch()."
96
+ );
97
+ }
98
+ return new Nimble({ apiKey });
99
+ }
100
+ function nimbleSearch(config = {}) {
101
+ const maxResults = config.maxResults ?? NIMBLE_SEARCH_DEFAULTS.maxResults;
102
+ const maxResultsCap = config.maxResultsCap ?? NIMBLE_SEARCH_DEFAULTS.maxResultsCap;
103
+ const searchDepth = config.searchDepth ?? NIMBLE_SEARCH_DEFAULTS.searchDepth;
104
+ const country = config.country ?? NIMBLE_SEARCH_DEFAULTS.country;
105
+ const locale = config.locale ?? NIMBLE_SEARCH_DEFAULTS.locale;
106
+ const maxContentLength = config.maxContentLength ?? NIMBLE_SEARCH_DEFAULTS.maxContentLength;
107
+ return tool({
108
+ description: "Search the web with Nimble and return ranked results (title, url, snippet, and page content) for answering questions about current or factual information.",
109
+ inputSchema: nimbleSearchInputSchema,
110
+ execute: async (input) => {
111
+ const client = resolveClient(config);
112
+ const params = {
113
+ query: input.query,
114
+ max_results: clamp(input.maxResults ?? maxResults, 1, maxResultsCap),
115
+ search_depth: searchDepth,
116
+ focus: NIMBLE_SEARCH_DEFAULTS.focus,
117
+ // fixed 'general' in v1
118
+ country,
119
+ locale
120
+ };
121
+ let raw;
122
+ try {
123
+ raw = await client.search(params);
124
+ } catch (err) {
125
+ throw toSearchError(err);
126
+ }
127
+ return normalizeSearchResponse(raw, {
128
+ query: input.query,
129
+ maxContentLength
130
+ });
131
+ }
132
+ });
133
+ }
134
+
135
+ export { NIMBLE_SEARCH_DEFAULTS, NimbleConfigError, NimbleSearchError, nimbleSearch, nimbleSearchInputSchema, normalizeSearchResponse };
136
+ //# sourceMappingURL=index.js.map
137
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schemas.ts","../src/normalize.ts","../src/errors.ts","../src/nimble-search.ts"],"names":[],"mappings":";;;;;AAQO,IAAM,uBAAA,GAA0B,EAAE,MAAA,CAAO;AAAA,EAC9C,KAAA,EAAO,EAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA,CAAE,SAAS,uBAAuB,CAAA;AAAA,EACzD,UAAA,EAAY,CAAA,CACT,MAAA,EAAO,CACP,GAAA,EAAI,CACJ,QAAA,EAAS,CACT,QAAA,EAAS,CACT,QAAA,CAAS,uEAAuE;AACrF,CAAC;;;ACFD,SAAS,eACP,QAAA,EACgC;AAChC,EAAA,OAAO,UAAA,IAAc,QAAA;AACvB;AAEA,SAAS,QAAA,CAAS,MAAc,GAAA,EAAqB;AACnD,EAAA,OAAO,KAAK,M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A,KAAuC;AACrD,MAAA,MAAM,MAAA,GAAS,cAAc,MAAM,CAAA;AAEnC,MAAA,MAAM,MAAA,GAA6B;AAAA,QACjC,OAAO,KAAA,CAAM,KAAA;AAAA,QACb,aAAa,KAAA,CAAM,KAAA,CAAM,UAAA,IAAc,UAAA,EAAY,GAAG,aAAa,CAAA;AAAA,QACnE,YAAA,EAAc,WAAA;AAAA,QACd,OAAO,sBAAA,CAAuB,KAAA;AAAA;AAAA,QAC9B,OAAA;AAAA,QACA;AAAA,OACF;AAEA,MAAA,IAAI,GAAA;AACJ,MAAA,IAAI;AACF,QAAA,GAAA,GAAM,MAAM,MAAA,CAAO,MAAA,CAAO,MAAM,CAAA;AAAA,MAClC,SAAS,GAAA,EAAK;AACZ,QAAA,MAAM,cAAc,GAAG,CAAA;AAAA,MACzB;AAEA,MAAA,OAAO,wBAAwB,GAAA,EAAK;AAAA,QAClC,OAAO,KAAA,CAAM,KAAA;AAAA,QACb;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH","file":"index.js","sourcesContent":["import { z } from 'zod';\n\n/**\n * The tool input the model fills in. Kept deliberately small: the model only\n * chooses the query and (optionally) how many results it wants. All policy\n * (depth, focus, region, caps) is fixed by the developer via the factory\n * config, not by the model.\n */\nexport const nimbleSearchInputSchema = z.object({\n query: z.string().min(1).describe('The web search query.'),\n maxResults: z\n .number()\n .int()\n .positive()\n .optional()\n .describe('How many results to return (clamped to the developer-configured cap).'),\n});\n\nexport type NimbleSearchInput = z.infer<typeof nimbleSearchInputSchema>;\n\n/**\n * v1 exposes only the two non-enterprise depths. `fast` is enterprise-gated and\n * intentionally not offered here.\n */\nexport type SearchDepth = 'lite' | 'deep';\n\n/**\n * Developer-facing factory config. `focus` is fixed to `general` in v1 and is\n * not exposed. `include_answer` and `search_depth: 'fast'` are intentionally\n * absent (enterprise / unverified-entitlement surface).\n */\nexport interface NimbleSearchToolConfig {\n /** Nimble API key. Defaults to `process.env.NIMBLE_API_KEY`. */\n apiKey?: string;\n /** Inject a pre-built / mock Nimble client (tests, advanced users). */\n client?: NimbleSearchClient;\n /** Default number of results when the model doesn't specify. Default 5. */\n maxResults?: number;\n /** Hard upper bound on results, regardless of model request. Default 10. */\n maxResultsCap?: number;\n /** Search depth. Default `lite`. */\n searchDepth?: SearchDepth;\n /** ISO country for result localization. Default `US`. */\n country?: string;\n /** Locale for result localization. Default `en`. */\n locale?: string;\n /** Truncate each result's body to this many characters. Default 10_000. */\n maxContentLength?: number;\n}\n\n/**\n * Structural surface of `@nimble-way/nimble-js`'s `client.search()` that this\n * package relies on. Declared structurally so the scaffold typechecks without\n * pinning to the SDK's generated type names, and so tests can inject a mock.\n *\n * Phase B: reconcile field casing/names against\n * `sdks/nimble-js/checkout/src/` after `./tools/sync-sdk.sh nimble-js`.\n */\nexport interface NimbleSearchParams {\n query: string;\n max_results?: number;\n search_depth?: SearchDepth;\n focus?: string;\n country?: string;\n locale?: string;\n}\n\n/** Metadata for SERP-based results (general/news/location focus). */\nexport interface NimbleSerpMetadata {\n country: string;\n entity_type: string;\n locale: string;\n position: number;\n driver?: string | null;\n}\n\n/** Metadata for WSA-based results (shopping/social/geo focus). */\nexport interface NimbleWsaMetadata {\n agent_name: string;\n}\n\nexport interface NimbleRawSearchResult {\n /** Full page text in `deep`; may be empty in `lite`. */\n content: string;\n description: string;\n title: string;\n url: string;\n /** SERP focus (v1 `general`) yields {@link NimbleSerpMetadata}. */\n metadata: NimbleSerpMetadata | NimbleWsaMetadata;\n /** Platform-specific extras (price, publish_date, …); omitted when none. */\n additional_data?: Record<string, unknown> | null;\n}\n\nexport interface NimbleRawSearchResponse {\n request_id: string;\n results: NimbleRawSearchResult[];\n total_results: number;\n /** Intentionally never surfaced in v1 (include_answer is off). */\n answer?: string | null;\n}\n\nexport interface NimbleSearchClient {\n search(params: NimbleSearchParams): Promise<NimbleRawSearchResponse>;\n}\n\n/** A single normalized result item returned to the model. */\nexport interface NimbleSearchResultItem {\n title: string;\n url: string;\n description?: string;\n content?: string;\n position?: number;\n entityType?: string;\n}\n\n/** The normalized tool output. `answer` is intentionally omitted in v1. */\nexport interface NimbleSearchOutput {\n query: string;\n requestId?: string;\n totalResults?: number;\n results: NimbleSearchResultItem[];\n}\n","import type {\n NimbleRawSearchResponse,\n NimbleRawSearchResult,\n NimbleSearchOutput,\n NimbleSearchResultItem,\n NimbleSerpMetadata,\n} from './schemas';\n\nexport interface NormalizeOptions {\n query: string;\n maxContentLength: number;\n}\n\n/** SERP focus (v1 `general`) carries position + entity_type; WSA does not. */\nfunction isSerpMetadata(\n metadata: NimbleRawSearchResult['metadata'],\n): metadata is NimbleSerpMetadata {\n return 'position' in metadata;\n}\n\nfunction truncate(text: string, max: number): string {\n return text.length > max ? text.slice(0, max) : text;\n}\n\n/**\n * Map a raw `/v1/search` response into the package's normalized output shape.\n *\n * - `description` is the snippet (always present when the API returns one).\n * - `content` is the full page text, present only in `deep` depth (empty in\n * `lite`), truncated to `maxContentLength`.\n * - `position` / `entityType` come from SERP metadata; for WSA results\n * `position` falls back to the array index and `entityType` is omitted.\n * - Results without a URL are dropped (defensive).\n * - `response.answer` is never surfaced in v1.\n */\nexport function normalizeSearchResponse(\n response: NimbleRawSearchResponse,\n options: NormalizeOptions,\n): NimbleSearchOutput {\n const results: NimbleSearchResultItem[] = [];\n\n response.results.forEach((raw, index) => {\n if (!raw.url) return;\n\n const item: NimbleSearchResultItem = {\n title: raw.title ?? '',\n url: raw.url,\n };\n if (raw.description) item.description = raw.description;\n if (raw.content && raw.content.trim().length > 0) {\n item.content = truncate(raw.content, options.maxContentLength);\n }\n\n if (isSerpMetadata(raw.metadata)) {\n item.position = raw.metadata.position;\n item.entityType = raw.metadata.entity_type;\n } else {\n item.position = index + 1;\n }\n\n results.push(item);\n });\n\n return {\n query: options.query,\n requestId: response.request_id,\n totalResults: response.total_results,\n results,\n };\n}\n","/**\n * Thrown when the tool is invoked without a resolvable API key (no `apiKey`\n * config and no `NIMBLE_API_KEY` in the environment) and no injected client.\n * Raised at execute time, not at factory-construction time, so the tool can be\n * constructed in environments without a key (e.g. unit tests, type-checking).\n */\nexport class NimbleConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'NimbleConfigError';\n }\n}\n\n/**\n * Wraps an error surfaced by the Nimble client / API during a search call,\n * preserving the HTTP status when available. The AI SDK surfaces a thrown\n * tool error back to the model as a tool-call failure.\n */\nexport class NimbleSearchError extends Error {\n readonly status?: number;\n\n constructor(message: string, options?: { status?: number; cause?: unknown }) {\n super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = 'NimbleSearchError';\n this.status = options?.status;\n }\n}\n","import { tool } from 'ai';\nimport { Nimble } from '@nimble-way/nimble-js';\nimport { nimbleSearchInputSchema } from './schemas';\nimport type {\n NimbleSearchClient,\n NimbleSearchOutput,\n NimbleSearchParams,\n NimbleSearchToolConfig,\n} from './schemas';\nimport { normalizeSearchResponse } from './normalize';\nimport { NimbleConfigError, NimbleSearchError } from './errors';\n\n/** v1 factory defaults. `focus` is fixed to `general` and not user-exposed. */\nexport const NIMBLE_SEARCH_DEFAULTS = {\n maxResults: 5,\n maxResultsCap: 10,\n searchDepth: 'lite',\n country: 'US',\n locale: 'en',\n maxContentLength: 10_000,\n focus: 'general',\n} as const;\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(Math.max(value, min), max);\n}\n\nfunction readStatus(err: unknown): number | undefined {\n if (typeof err === 'object' && err !== null && 'status' in err) {\n const status = (err as { status?: unknown }).status;\n return typeof status === 'number' ? status : undefined;\n }\n return undefined;\n}\n\nfunction toSearchError(err: unknown): NimbleSearchError {\n if (err instanceof NimbleSearchError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new NimbleSearchError(`Nimble search failed: ${message}`, {\n status: readStatus(err),\n cause: err,\n });\n}\n\nfunction resolveClient(config: NimbleSearchToolConfig): NimbleSearchClient {\n if (config.client) return config.client;\n const apiKey = config.apiKey ?? process.env.NIMBLE_API_KEY;\n if (!apiKey) {\n throw new NimbleConfigError(\n 'Missing Nimble API key: set NIMBLE_API_KEY or pass { apiKey } to nimbleSearch().',\n );\n }\n return new Nimble({ apiKey }) as unknown as NimbleSearchClient;\n}\n\n/**\n * Create a ready-made Vercel AI SDK web-search tool backed by Nimble Search\n * (`@nimble-way/nimble-js` → `POST /v1/search`).\n *\n * The model only chooses `{ query, maxResults? }`; all policy (depth, focus,\n * region, caps) is fixed by `config` — mirroring the Exa `webSearch()` shape.\n *\n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { nimbleSearch } from '@nimble-way/ai-sdk';\n *\n * const { text } = await generateText({\n * model: 'anthropic/claude-sonnet-4.6',\n * prompt: 'What are the latest Nimble release notes?',\n * tools: { webSearch: nimbleSearch({ searchDepth: 'lite', maxResults: 5 }) },\n * });\n * ```\n */\nexport function nimbleSearch(config: NimbleSearchToolConfig = {}) {\n const maxResults = config.maxResults ?? NIMBLE_SEARCH_DEFAULTS.maxResults;\n const maxResultsCap = config.maxResultsCap ?? NIMBLE_SEARCH_DEFAULTS.maxResultsCap;\n const searchDepth = config.searchDepth ?? NIMBLE_SEARCH_DEFAULTS.searchDepth;\n const country = config.country ?? NIMBLE_SEARCH_DEFAULTS.country;\n const locale = config.locale ?? NIMBLE_SEARCH_DEFAULTS.locale;\n const maxContentLength = config.maxContentLength ?? NIMBLE_SEARCH_DEFAULTS.maxContentLength;\n\n return tool({\n description:\n 'Search the web with Nimble and return ranked results (title, url, ' +\n 'snippet, and page content) for answering questions about current or ' +\n 'factual information.',\n inputSchema: nimbleSearchInputSchema,\n execute: async (input): Promise<NimbleSearchOutput> => {\n const client = resolveClient(config);\n\n const params: NimbleSearchParams = {\n query: input.query,\n max_results: clamp(input.maxResults ?? maxResults, 1, maxResultsCap),\n search_depth: searchDepth,\n focus: NIMBLE_SEARCH_DEFAULTS.focus, // fixed 'general' in v1\n country,\n locale,\n };\n\n let raw;\n try {\n raw = await client.search(params);\n } catch (err) {\n throw toSearchError(err);\n }\n\n return normalizeSearchResponse(raw, {\n query: input.query,\n maxContentLength,\n });\n },\n });\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "@nimble-way/ai-sdk",
3
+ "version": "0.1.0",
4
+ "description": "Nimble Web Search as a ready-made tool for the Vercel AI SDK.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "author": "Nimble",
8
+ "homepage": "https://github.com/Nimbleway/ai-sdk",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/Nimbleway/ai-sdk.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/Nimbleway/ai-sdk/issues"
15
+ },
16
+ "keywords": [
17
+ "nimble",
18
+ "vercel",
19
+ "ai-sdk",
20
+ "ai",
21
+ "web-search",
22
+ "search",
23
+ "tool",
24
+ "llm",
25
+ "agent"
26
+ ],
27
+ "sideEffects": false,
28
+ "main": "./dist/index.cjs",
29
+ "module": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "import": "./dist/index.js",
35
+ "require": "./dist/index.cjs"
36
+ },
37
+ "./package.json": "./package.json"
38
+ },
39
+ "files": [
40
+ "dist",
41
+ "README.md",
42
+ "LICENSE"
43
+ ],
44
+ "scripts": {
45
+ "build": "tsup",
46
+ "typecheck": "tsc --noEmit",
47
+ "test": "vitest run",
48
+ "test:watch": "vitest",
49
+ "prepublishOnly": "pnpm run build"
50
+ },
51
+ "dependencies": {
52
+ "@nimble-way/nimble-js": "^0.14.0"
53
+ },
54
+ "peerDependencies": {
55
+ "ai": "^6",
56
+ "zod": "^3.25.76 || ^4.1.8"
57
+ },
58
+ "devDependencies": {
59
+ "@types/node": "^22.0.0",
60
+ "ai": "^6.0.0",
61
+ "tsup": "^8.3.0",
62
+ "tsx": "^4.19.0",
63
+ "typescript": "^5.6.0",
64
+ "vitest": "^2.1.0",
65
+ "zod": "^3.25.76"
66
+ },
67
+ "engines": {
68
+ "node": ">=18"
69
+ },
70
+ "publishConfig": {
71
+ "access": "public",
72
+ "provenance": true
73
+ }
74
+ }