@specstream/ai-sdk 0.0.0-stage → 0.1.1

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SpecStream SAS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,116 @@
1
- # Temporary Holding Version
1
+ # @specstream/ai-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Search tools hand your agent pages to read. SpecStream hands it the finished list: ask in plain words – "dental clinics in Lisbon with online booking", "US startups that filed a $5M+ Form D this week" – and the agent gets back every matching row, each with the page it was read from. The price is set before anything runs, in your code, and the model can't raise it.
4
+
5
+ ```bash
6
+ npm install @specstream/ai-sdk ai zod
7
+ export SPECSTREAM_API_KEY=ss_live_... # Agents & API in your SpecStream workspace
8
+ ```
9
+
10
+ A free account comes with $10 of work to use within 30 days and needs no card: [specstream.ai](https://specstream.ai/signup).
11
+
12
+ ## An agent that can find lists
13
+
14
+ ```ts
15
+ import { generateText, stepCountIs } from "ai";
16
+ import { specstreamTools } from "@specstream/ai-sdk";
17
+
18
+ const { text } = await generateText({
19
+ model: "openai/gpt-5-mini",
20
+ tools: specstreamTools({ maxPriceUsd: 5 }),
21
+ stopWhen: stepCountIs(5),
22
+ prompt: "Find US startups that raised $5M or more in a Form D filed after October 8, 2026. Which industries lead?",
23
+ });
24
+
25
+ console.log(text);
26
+ ```
27
+
28
+ The agent writes the request and picks how many rows. You decide what one list may cost. `streamText` and `ToolLoopAgent` take the same `tools`.
29
+
30
+ ## What comes back
31
+
32
+ One flat row per match: the list's own columns, then where the row was read. This is a real row from the request above.
33
+
34
+ ```json
35
+ {
36
+ "list_id": "fnd_gk5y3d0r97bvyz0t08zzh75kr6",
37
+ "position": 26,
38
+ "Organization": "RapidCanvas Inc",
39
+ "Published address": "801 BARTON SPRINGS RD, AUSTIN, TEXAS, 78704",
40
+ "Source industry classification": "Other Technology",
41
+ "Amount sold (USD)": "28999988",
42
+ "Funding filing date": "2026-10-14",
43
+ "source_url": "https://www.sec.gov/Archives/edgar/data/2052031/000205203126000006/primary_doc.xml",
44
+ "checked_at": "2026-10-14T19:56:02.016693Z",
45
+ "list_link": "https://specstream.ai/workspace/collections/fnd_gk5y3d0r97bvyz0t08zzh75kr6"
46
+ }
47
+ ```
48
+
49
+ Columns follow the request. Ask for "breweries in Portland, Oregon that host events, with their website" and the rows carry the brewery and its website instead. A fact a source doesn't publish comes back empty, never guessed.
50
+
51
+ The tool's result wraps the rows with `status`, `list_id`, `list_link`, `row_count` and `maximum_price_usd`, so the agent can cite the list and hand your user a link to it.
52
+
53
+ ## The two tools
54
+
55
+ | Tool | The model gives | What happens | Cost |
56
+ | --- | --- | --- | --- |
57
+ | `specstream_find_list` | `request`, `maxResults` (1 to 1000, default 25) | Reads the request, prices it, starts it only within `maxPriceUsd`, waits up to `waitSeconds` (7 minutes by default) and returns every row | Only the rows that match |
58
+ | `specstream_get_list_results` | `listId` | Every row found so far, for a list that was still running | Free |
59
+
60
+ When the price is above your maximum, nothing runs: the tool returns `status: "over_maximum"` and the price, so the agent can ask for fewer rows or tell the user. When a request is too vague to price ("clinics"), it returns `status: "needs_edit"` and how SpecStream read it, so the agent can add the place or the conditions.
61
+
62
+ Settings, all optional except the price:
63
+
64
+ | Option | Default | What it does |
65
+ | --- | --- | --- |
66
+ | `maxPriceUsd` | required | The most one list may cost, in US dollars. Not a tool input |
67
+ | `apiKey` | `SPECSTREAM_API_KEY` | Your SpecStream API key |
68
+ | `waitSeconds` | `420` | How long `specstream_find_list` waits before returning the rows found so far |
69
+ | `pollIntervalSeconds` | `3` | Seconds between checks while a list runs |
70
+ | `locale` | `en-US` | The language and region the request is written in |
71
+ | `baseUrl` | `https://api.specstream.ai` | The SpecStream API address |
72
+ | `fetch` | global `fetch` | Your own `fetch`, for a proxy or a test |
73
+
74
+ Running on a serverless function? Set `waitSeconds` below the function's time limit. A list that's still running when the wait ends comes back with its `list_id`, and the agent reads the rest with `specstream_get_list_results`.
75
+
76
+ ## Without a model
77
+
78
+ The client the tools are built on is exported, for the same calls from your own code:
79
+
80
+ ```ts
81
+ import { SpecStreamClient } from "@specstream/ai-sdk";
82
+
83
+ const client = new SpecStreamClient({ apiKey: process.env.SPECSTREAM_API_KEY });
84
+
85
+ const list = await client.findList("Breweries in Portland, Oregon that host events, with their website", {
86
+ maxResults: 25,
87
+ maxPriceUsd: 3,
88
+ });
89
+
90
+ if ("rows" in list) console.log(list.row_count, list.rows[0].source_url);
91
+ else console.log(list.message); // "over_maximum" or "needs_edit": nothing ran
92
+ ```
93
+
94
+ ## Money, plainly
95
+
96
+ - `maxPriceUsd` lives in your code. The model never sees it and can't change it.
97
+ - You pay for rows that match. Candidates SpecStream couldn't confirm are left out and aren't billed.
98
+ - A retried step asking for the same list within the hour gets the list it already started, not a second bill. Agents retry. Your card shouldn't notice.
99
+ - Rates and plans: [specstream.ai/pricing](https://specstream.ai/pricing).
100
+
101
+ ## When to reach for it
102
+
103
+ When the answer is many things that meet conditions: companies in a city, clinics with a service, funding filings, open grants, tenders, repositories, people in a role. For a single fact or a summary of one page, a search tool fits better.
104
+
105
+ ## Versions
106
+
107
+ Works with AI SDK 6 and 7 (`ai` ^6 or ^7) and zod 3.25.76 or 4. Node 18 or newer to run it; AI SDK 7 itself needs Node 22.
108
+
109
+ ## More
110
+
111
+ - [SpecStream docs](https://specstream.ai/docs) and the [AI SDK page](https://specstream.ai/docs/vercel-ai-sdk)
112
+ - Agents outside the AI SDK: the [MCP server](https://specstream.ai/docs/mcp) at `https://api.specstream.ai/mcp`
113
+ - The [TypeScript SDK](https://www.npmjs.com/package/@specstream/sdk) for everything else in the API
114
+ - Questions: support@specstream.ai
115
+
116
+ MIT licensed. Made by [SpecStream](https://specstream.ai), the live web data engine for teams and agents.
@@ -0,0 +1,107 @@
1
+ /** The SpecStream REST calls the tools share: read a request, price it, start it within a maximum, read its rows. */
2
+ export declare const DEFAULT_BASE_URL = "https://api.specstream.ai";
3
+ export declare const USER_AGENT = "@specstream/ai-sdk/0.1.1";
4
+ /** A list runs for up to about five minutes, so the tools wait a little longer than that by default. */
5
+ export declare const DEFAULT_WAIT_SECONDS = 420;
6
+ export declare const DEFAULT_POLL_INTERVAL_SECONDS = 3;
7
+ export declare const DEFAULT_LOCALE = "en-US";
8
+ export declare const MAX_RESULTS = 1000;
9
+ export declare const MISSING_KEY_MESSAGE = "Set SPECSTREAM_API_KEY or pass apiKey. Create a key under Agents & API in your SpecStream workspace.";
10
+ /** SpecStream refused a call or answered with something this package can't read. */
11
+ export declare class SpecStreamError extends Error {
12
+ constructor(message: string);
13
+ }
14
+ /** One row as flat fields: the list's own columns, then where the row was read. */
15
+ export type ListRow = {
16
+ list_id: string;
17
+ position: number | null;
18
+ source_url: string;
19
+ checked_at: string;
20
+ list_link: string;
21
+ [column: string]: unknown;
22
+ };
23
+ export type ListResults = {
24
+ list_id: string;
25
+ status: string;
26
+ list_link: string;
27
+ row_count: number;
28
+ rows: ListRow[];
29
+ };
30
+ export type FoundList = ListResults & {
31
+ request: string;
32
+ maximum_price_usd: number;
33
+ /** Set when the list was still running at the end of the wait. */
34
+ message?: string;
35
+ };
36
+ export type NeedsEdit = {
37
+ status: "needs_edit";
38
+ request: string;
39
+ message: string;
40
+ };
41
+ export type OverMaximum = {
42
+ status: "over_maximum";
43
+ request: string;
44
+ maximum_price_usd: number;
45
+ message: string;
46
+ };
47
+ export type FindListResult = FoundList | NeedsEdit | OverMaximum;
48
+ export type FindListOptions = {
49
+ /** How many rows to find. Held to 1 through 1000. */
50
+ maxResults: number;
51
+ /** The most one list may cost, in US dollars. Above it, nothing runs. */
52
+ maxPriceUsd: number;
53
+ waitSeconds?: number;
54
+ pollIntervalSeconds?: number;
55
+ locale?: string;
56
+ /** Stops waiting for the list. The list itself keeps running and can be read later. */
57
+ abortSignal?: AbortSignal;
58
+ };
59
+ export type SpecStreamClientOptions = {
60
+ /** A SpecStream API key. Defaults to the SPECSTREAM_API_KEY environment variable. */
61
+ apiKey?: string;
62
+ baseUrl?: string;
63
+ /** Replaces the global fetch, for tests or a proxy. */
64
+ fetch?: typeof fetch;
65
+ /** Replaces the wait between polls, for tests. Receives milliseconds. */
66
+ sleep?: (ms: number) => Promise<void>;
67
+ /** Replaces the clock, for tests. Returns epoch milliseconds. */
68
+ now?: () => number;
69
+ /** Starts every idempotency key. Defaults to "aisdk". */
70
+ keyPrefix?: string;
71
+ };
72
+ export declare function listLink(findId: string): string;
73
+ type Cell = {
74
+ label?: unknown;
75
+ column_id?: unknown;
76
+ absence?: unknown;
77
+ display?: unknown;
78
+ value?: unknown;
79
+ provenance?: {
80
+ source_url?: unknown;
81
+ observed_at?: unknown;
82
+ } | null;
83
+ };
84
+ type RawRecord = {
85
+ ordinal?: number | null;
86
+ details?: Cell[] | null;
87
+ cells?: Cell[] | null;
88
+ };
89
+ /** One row as flat fields: each column's label holds what the list shows, plus where the row was read. */
90
+ export declare function flattenRow(findId: string, record: RawRecord): ListRow;
91
+ /** The low-level client the tools are built on. Use it directly when you want the calls without a model. */
92
+ export declare class SpecStreamClient {
93
+ readonly baseUrl: string;
94
+ private readonly apiKey;
95
+ private readonly fetchImpl;
96
+ private readonly sleep;
97
+ private readonly now;
98
+ private readonly keyPrefix;
99
+ constructor(options?: SpecStreamClientOptions);
100
+ get hasKey(): boolean;
101
+ private request;
102
+ /** Every row found so far for a list, following the pages. Reading is free. */
103
+ results(findId: string, abortSignal?: AbortSignal): Promise<ListResults>;
104
+ /** Reads the request, prices it, and runs it only if the most it can cost is within `maxPriceUsd`. */
105
+ findList(request: string, options: FindListOptions): Promise<FindListResult>;
106
+ }
107
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,253 @@
1
+ /** The SpecStream REST calls the tools share: read a request, price it, start it within a maximum, read its rows. */
2
+ export const DEFAULT_BASE_URL = "https://api.specstream.ai";
3
+ export const USER_AGENT = "@specstream/ai-sdk/0.1.1";
4
+ /** A list runs for up to about five minutes, so the tools wait a little longer than that by default. */
5
+ export const DEFAULT_WAIT_SECONDS = 420;
6
+ export const DEFAULT_POLL_INTERVAL_SECONDS = 3;
7
+ export const DEFAULT_LOCALE = "en-US";
8
+ export const MAX_RESULTS = 1000;
9
+ const REQUEST_TIMEOUT_MS = 150_000;
10
+ const FINISHED = new Set(["completed", "partial"]);
11
+ const STOPPED = new Set(["failed", "cancelled", "canceled", "expired"]);
12
+ /** Fields every row carries; a column with the same name is renamed so it can't overwrite them. */
13
+ const RESERVED = new Set(["list_id", "list_link", "position", "source_url", "checked_at"]);
14
+ export const MISSING_KEY_MESSAGE = "Set SPECSTREAM_API_KEY or pass apiKey. Create a key under Agents & API in your SpecStream workspace.";
15
+ /** SpecStream refused a call or answered with something this package can't read. */
16
+ export class SpecStreamError extends Error {
17
+ constructor(message) {
18
+ super(message);
19
+ this.name = "SpecStreamError";
20
+ }
21
+ }
22
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
23
+ function envKey() {
24
+ return (typeof process !== "undefined" && process.env?.SPECSTREAM_API_KEY) || "";
25
+ }
26
+ function dollars(cents) {
27
+ return `$${(cents / 100).toFixed(2)}`;
28
+ }
29
+ export function listLink(findId) {
30
+ return `https://specstream.ai/workspace/collections/${encodeURIComponent(findId)}`;
31
+ }
32
+ /** One row as flat fields: each column's label holds what the list shows, plus where the row was read. */
33
+ export function flattenRow(findId, record) {
34
+ const row = { list_id: findId, position: record.ordinal ?? null };
35
+ let source = null;
36
+ const cells = record.details?.length ? record.details : (record.cells ?? []);
37
+ for (const cell of cells) {
38
+ let label = String(cell.label || cell.column_id || "").trim();
39
+ if (!label)
40
+ continue;
41
+ if (RESERVED.has(label))
42
+ label = `${label} (column)`;
43
+ let value;
44
+ if (cell.absence)
45
+ value = "";
46
+ else if (cell.display != null)
47
+ value = cell.display;
48
+ else
49
+ value = cell.value ?? "";
50
+ row[label] = value;
51
+ const provenance = cell.provenance || {};
52
+ if (source === null && String(provenance.source_url || "").startsWith("http"))
53
+ source = provenance;
54
+ }
55
+ row.source_url = source ? (source.source_url ?? "") : "";
56
+ row.checked_at = source ? (source.observed_at ?? "") : "";
57
+ row.list_link = listLink(findId);
58
+ return row;
59
+ }
60
+ async function sha256Hex(text) {
61
+ const bytes = new TextEncoder().encode(text);
62
+ if (globalThis.crypto?.subtle) {
63
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
64
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
65
+ }
66
+ const { createHash } = await import("node:crypto");
67
+ return createHash("sha256").update(text).digest("hex");
68
+ }
69
+ /** The low-level client the tools are built on. Use it directly when you want the calls without a model. */
70
+ export class SpecStreamClient {
71
+ baseUrl;
72
+ apiKey;
73
+ fetchImpl;
74
+ sleep;
75
+ now;
76
+ keyPrefix;
77
+ constructor(options = {}) {
78
+ this.apiKey = (options.apiKey ?? envKey()).trim();
79
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
80
+ this.fetchImpl = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
81
+ this.sleep = options.sleep ?? wait;
82
+ this.now = options.now ?? Date.now;
83
+ this.keyPrefix = options.keyPrefix ?? "aisdk";
84
+ }
85
+ get hasKey() {
86
+ return this.apiKey.length > 0;
87
+ }
88
+ async request(method, path, body, options = {}) {
89
+ if (!this.apiKey)
90
+ throw new SpecStreamError(MISSING_KEY_MESSAGE);
91
+ const controller = new AbortController();
92
+ const timer = setTimeout(() => controller.abort(new Error("timed out")), REQUEST_TIMEOUT_MS);
93
+ const outer = options.abortSignal;
94
+ const onAbort = () => controller.abort(outer?.reason);
95
+ if (outer?.aborted)
96
+ onAbort();
97
+ else
98
+ outer?.addEventListener("abort", onAbort, { once: true });
99
+ let response;
100
+ let raw;
101
+ try {
102
+ response = await this.fetchImpl(this.baseUrl + path, {
103
+ method,
104
+ body: body === undefined ? undefined : JSON.stringify(body),
105
+ headers: {
106
+ Authorization: /^bearer /i.test(this.apiKey) ? this.apiKey : `Bearer ${this.apiKey}`,
107
+ Accept: "application/json",
108
+ "Content-Type": "application/json",
109
+ "User-Agent": USER_AGENT,
110
+ },
111
+ signal: controller.signal,
112
+ });
113
+ raw = await response.text();
114
+ }
115
+ catch (error) {
116
+ if (outer?.aborted)
117
+ throw error;
118
+ const reason = error instanceof Error ? (error.cause instanceof Error ? error.cause.message : error.message) : String(error);
119
+ throw new SpecStreamError(`Couldn't reach SpecStream: ${reason}`);
120
+ }
121
+ finally {
122
+ clearTimeout(timer);
123
+ outer?.removeEventListener("abort", onAbort);
124
+ }
125
+ if (!response.ok) {
126
+ if (options.allow404 && response.status === 404)
127
+ return null;
128
+ throw new SpecStreamError(errorMessage(response, raw));
129
+ }
130
+ let payload;
131
+ try {
132
+ payload = JSON.parse(raw || "{}");
133
+ }
134
+ catch {
135
+ payload = null;
136
+ }
137
+ const data = isObject(payload) ? payload.data : undefined;
138
+ if (!isObject(data))
139
+ throw new SpecStreamError("SpecStream returned a response this package couldn't read.");
140
+ return data;
141
+ }
142
+ /** Every row found so far for a list, following the pages. Reading is free. */
143
+ async results(findId, abortSignal) {
144
+ const rows = [];
145
+ let cursor = null;
146
+ let status = "running";
147
+ for (;;) {
148
+ const query = new URLSearchParams({ limit: "100", ...(cursor ? { cursor } : {}) });
149
+ const page = (await this.request("GET", `/v1/finds/${encodeURIComponent(findId)}/rows?${query}`, undefined, { abortSignal })) ?? {};
150
+ status = typeof page.status === "string" && page.status ? page.status : status;
151
+ for (const record of Array.isArray(page.rows) ? page.rows : [])
152
+ rows.push(flattenRow(findId, record));
153
+ const next = typeof page.next_cursor === "string" && page.next_cursor ? page.next_cursor : null;
154
+ if (!next || next === cursor)
155
+ break;
156
+ cursor = next;
157
+ }
158
+ return { list_id: findId, status, list_link: listLink(findId), row_count: rows.length, rows };
159
+ }
160
+ /** Reads the request, prices it, and runs it only if the most it can cost is within `maxPriceUsd`. */
161
+ async findList(request, options) {
162
+ const q = (request ?? "").trim();
163
+ if (!q)
164
+ throw new Error("Describe the list to find.");
165
+ const maxResults = options.maxResults;
166
+ if (!Number.isInteger(maxResults) || maxResults < 1)
167
+ throw new Error("maxResults must be 1 or more.");
168
+ const maxCents = Math.round(Number(options.maxPriceUsd) * 100);
169
+ if (!(maxCents > 0))
170
+ throw new Error("maxPriceUsd must be greater than 0.");
171
+ const { abortSignal } = options;
172
+ // The same request with the same limits gets the run it already started in this hour or the one before,
173
+ // so a retried agent step never buys the list twice, even across the turn of the hour.
174
+ const keyFor = async (at) => {
175
+ const hour = new Date(at).toISOString().slice(0, 13);
176
+ return `${this.keyPrefix}-${(await sha256Hex(`${q}|${maxResults}|${maxCents}|${hour}`)).slice(0, 32)}`;
177
+ };
178
+ const at = this.now();
179
+ const requestKey = await keyFor(at);
180
+ let existing = null;
181
+ for (const candidate of [requestKey, await keyFor(at - 3_600_000)]) {
182
+ existing = await this.request("GET", `/v1/capacity/requests/${encodeURIComponent(candidate)}`, undefined, {
183
+ allow404: true,
184
+ abortSignal,
185
+ });
186
+ if (existing?.find_id)
187
+ break;
188
+ }
189
+ let findId;
190
+ let maximumCents;
191
+ if (existing?.find_id) {
192
+ findId = String(existing.find_id);
193
+ maximumCents = Math.trunc(Number(existing.maximum_cents)) || maxCents;
194
+ }
195
+ else {
196
+ const reading = (await this.request("POST", "/v1/parse", { q, locale: options.locale ?? DEFAULT_LOCALE }, { abortSignal })) ?? {};
197
+ if (reading.status !== "runnable") {
198
+ const readAs = reading.canonical_sentence || q;
199
+ return {
200
+ status: "needs_edit",
201
+ request: q,
202
+ message: `SpecStream needs a clearer request before it can price it. It read: "${readAs}". Add the place or what every row must meet.`,
203
+ };
204
+ }
205
+ const quote = (await this.request("POST", "/v1/capacity/quotes", { ast_hash: reading.ast_hash, operation: "find", requested_units: maxResults }, { abortSignal })) ?? {};
206
+ maximumCents = Math.trunc(Number(quote.maximum_cents)) || 0;
207
+ if (maximumCents > maxCents) {
208
+ return {
209
+ status: "over_maximum",
210
+ request: q,
211
+ maximum_price_usd: maximumCents / 100,
212
+ message: `Nothing ran: this list can cost up to ${dollars(maximumCents)}, above the maximum of ${dollars(maxCents)}. Ask for fewer results or raise maxPriceUsd.`,
213
+ };
214
+ }
215
+ const run = (await this.request("POST", "/v1/capacity/executions", { quote_id: quote.quote_id, quote_hash: quote.quote_hash, confirm_max_cents: maximumCents, idempotency_key: requestKey }, { abortSignal })) ?? {};
216
+ if (!run.find_id)
217
+ throw new SpecStreamError("SpecStream returned a response this package couldn't read.");
218
+ findId = String(run.find_id);
219
+ }
220
+ const waitMs = Math.max(0, options.waitSeconds ?? DEFAULT_WAIT_SECONDS) * 1000;
221
+ const pollMs = Math.max(0, options.pollIntervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS) * 1000;
222
+ const deadline = this.now() + waitMs;
223
+ let result;
224
+ for (;;) {
225
+ result = await this.results(findId, abortSignal);
226
+ if (FINISHED.has(result.status) || STOPPED.has(result.status) || this.now() >= deadline)
227
+ break;
228
+ if (abortSignal?.aborted)
229
+ throw abortSignal.reason ?? new Error("aborted");
230
+ await this.sleep(pollMs);
231
+ }
232
+ const found = { ...result, request: q, maximum_price_usd: maximumCents / 100 };
233
+ if (!FINISHED.has(result.status) && !STOPPED.has(result.status)) {
234
+ found.message = "Still running. Call specstream_get_list_results with this list_id for the rest.";
235
+ }
236
+ return found;
237
+ }
238
+ }
239
+ function isObject(value) {
240
+ return typeof value === "object" && value !== null && !Array.isArray(value);
241
+ }
242
+ function errorMessage(response, raw) {
243
+ let payload = {};
244
+ try {
245
+ payload = JSON.parse(raw || "{}");
246
+ }
247
+ catch {
248
+ payload = {};
249
+ }
250
+ const detail = isObject(payload) ? payload.error : undefined;
251
+ const message = isObject(detail) ? detail.message : typeof detail === "string" ? detail : undefined;
252
+ return `SpecStream answered ${response.status}: ${message || response.statusText}`;
253
+ }
@@ -0,0 +1,2 @@
1
+ export { specstreamTools, type SpecStreamToolsOptions } from "./tools.js";
2
+ export { SpecStreamClient, SpecStreamError, flattenRow, listLink, DEFAULT_BASE_URL, DEFAULT_WAIT_SECONDS, USER_AGENT, type FindListOptions, type FindListResult, type FoundList, type ListResults, type ListRow, type NeedsEdit, type OverMaximum, type SpecStreamClientOptions, } from "./client.js";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { specstreamTools } from "./tools.js";
2
+ export { SpecStreamClient, SpecStreamError, flattenRow, listLink, DEFAULT_BASE_URL, DEFAULT_WAIT_SECONDS, USER_AGENT, } from "./client.js";
@@ -0,0 +1,464 @@
1
+ import { type FindListResult, type ListResults } from "./client.js";
2
+ export type SpecStreamToolsOptions = {
3
+ /** The most one list may cost, in US dollars. Set in code; the model can't see it or raise it. Above it, nothing runs. */
4
+ maxPriceUsd: number;
5
+ /** A SpecStream API key. Defaults to the SPECSTREAM_API_KEY environment variable. */
6
+ apiKey?: string;
7
+ /** The SpecStream API address. */
8
+ baseUrl?: string;
9
+ /** How long `specstream_find_list` waits for the list before returning the rows found so far. Defaults to 420. */
10
+ waitSeconds?: number;
11
+ /** Seconds between checks while a list is running. Defaults to 3. */
12
+ pollIntervalSeconds?: number;
13
+ /** The language and region the request is written in. Defaults to "en-US". */
14
+ locale?: string;
15
+ /** Replaces the global fetch. */
16
+ fetch?: typeof fetch;
17
+ };
18
+ /**
19
+ * The two SpecStream tools for an AI SDK agent: find a list on the live web, and read a list's rows.
20
+ *
21
+ * The price cap is set here, in code, and is not a tool input, so the model can't raise it.
22
+ *
23
+ * @example
24
+ * const { text } = await generateText({
25
+ * model,
26
+ * tools: specstreamTools({ maxPriceUsd: 5 }),
27
+ * stopWhen: stepCountIs(5),
28
+ * prompt: "Find dental clinics in Lisbon with online booking.",
29
+ * });
30
+ */
31
+ export declare function specstreamTools(options: SpecStreamToolsOptions): {
32
+ specstream_find_list: ({
33
+ deferLoading?: boolean;
34
+ title?: string;
35
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
36
+ metadata?: import("@ai-sdk/provider").JSONObject;
37
+ inputSchema: import("ai").FlexibleSchema<{
38
+ request: string;
39
+ maxResults: number;
40
+ }>;
41
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
42
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
43
+ request: string;
44
+ maxResults: number;
45
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
46
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
47
+ onInputDelta?: ((options: {
48
+ inputTextDelta: string;
49
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
50
+ onInputAvailable?: ((options: {
51
+ input: {
52
+ request: string;
53
+ maxResults: number;
54
+ };
55
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
56
+ toModelOutput?: ((options: {
57
+ toolCallId: string;
58
+ input: {
59
+ request: string;
60
+ maxResults: number;
61
+ };
62
+ output: NoInfer<FindListResult>;
63
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
64
+ } & {
65
+ outputSchema?: import("ai").FlexibleSchema<FindListResult> | undefined;
66
+ execute: import("ai").ToolExecuteFunction<{
67
+ request: string;
68
+ maxResults: number;
69
+ }, FindListResult, NoInfer<import("@ai-sdk/provider-utils").Context>>;
70
+ } & {
71
+ description?: string | ((options: {
72
+ context: NoInfer<import("@ai-sdk/provider-utils").Context>;
73
+ experimental_sandbox?: import("ai").Experimental_SandboxSession;
74
+ }) => string) | undefined;
75
+ strict?: boolean;
76
+ inputExamples?: {
77
+ input: NoInfer<{
78
+ request: string;
79
+ maxResults: number;
80
+ }>;
81
+ }[] | undefined;
82
+ id?: never;
83
+ isProviderExecuted?: never;
84
+ args?: never;
85
+ supportsDeferredResults?: never;
86
+ } & {
87
+ type?: undefined | "function";
88
+ } & {
89
+ execute: import("ai").ToolExecuteFunction<{
90
+ request: string;
91
+ maxResults: number;
92
+ }, FindListResult, NoInfer<import("@ai-sdk/provider-utils").Context>>;
93
+ }) | ({
94
+ deferLoading?: boolean;
95
+ title?: string;
96
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
97
+ metadata?: import("@ai-sdk/provider").JSONObject;
98
+ inputSchema: import("ai").FlexibleSchema<{
99
+ request: string;
100
+ maxResults: number;
101
+ }>;
102
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
103
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
104
+ request: string;
105
+ maxResults: number;
106
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
107
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
108
+ onInputDelta?: ((options: {
109
+ inputTextDelta: string;
110
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
111
+ onInputAvailable?: ((options: {
112
+ input: {
113
+ request: string;
114
+ maxResults: number;
115
+ };
116
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
117
+ toModelOutput?: ((options: {
118
+ toolCallId: string;
119
+ input: {
120
+ request: string;
121
+ maxResults: number;
122
+ };
123
+ output: NoInfer<FindListResult>;
124
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
125
+ } & {
126
+ outputSchema?: import("ai").FlexibleSchema<FindListResult> | undefined;
127
+ execute: import("ai").ToolExecuteFunction<{
128
+ request: string;
129
+ maxResults: number;
130
+ }, FindListResult, NoInfer<import("@ai-sdk/provider-utils").Context>>;
131
+ } & {
132
+ description?: string | ((options: {
133
+ context: NoInfer<import("@ai-sdk/provider-utils").Context>;
134
+ experimental_sandbox?: import("ai").Experimental_SandboxSession;
135
+ }) => string) | undefined;
136
+ strict?: boolean;
137
+ inputExamples?: {
138
+ input: NoInfer<{
139
+ request: string;
140
+ maxResults: number;
141
+ }>;
142
+ }[] | undefined;
143
+ id?: never;
144
+ isProviderExecuted?: never;
145
+ args?: never;
146
+ supportsDeferredResults?: never;
147
+ } & {
148
+ type: "dynamic";
149
+ } & {
150
+ execute: import("ai").ToolExecuteFunction<{
151
+ request: string;
152
+ maxResults: number;
153
+ }, FindListResult, NoInfer<import("@ai-sdk/provider-utils").Context>>;
154
+ }) | ({
155
+ deferLoading?: boolean;
156
+ title?: string;
157
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
158
+ metadata?: import("@ai-sdk/provider").JSONObject;
159
+ inputSchema: import("ai").FlexibleSchema<{
160
+ request: string;
161
+ maxResults: number;
162
+ }>;
163
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
164
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
165
+ request: string;
166
+ maxResults: number;
167
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
168
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
169
+ onInputDelta?: ((options: {
170
+ inputTextDelta: string;
171
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
172
+ onInputAvailable?: ((options: {
173
+ input: {
174
+ request: string;
175
+ maxResults: number;
176
+ };
177
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
178
+ toModelOutput?: ((options: {
179
+ toolCallId: string;
180
+ input: {
181
+ request: string;
182
+ maxResults: number;
183
+ };
184
+ output: NoInfer<FindListResult>;
185
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
186
+ } & {
187
+ outputSchema?: import("ai").FlexibleSchema<FindListResult> | undefined;
188
+ execute: import("ai").ToolExecuteFunction<{
189
+ request: string;
190
+ maxResults: number;
191
+ }, FindListResult, NoInfer<import("@ai-sdk/provider-utils").Context>>;
192
+ } & {
193
+ type: "provider";
194
+ id: `${string}.${string}`;
195
+ args: Record<string, unknown>;
196
+ description?: never;
197
+ strict?: never;
198
+ inputExamples?: never;
199
+ } & {
200
+ isProviderExecuted: false;
201
+ supportsDeferredResults?: never;
202
+ } & {
203
+ execute: import("ai").ToolExecuteFunction<{
204
+ request: string;
205
+ maxResults: number;
206
+ }, FindListResult, NoInfer<import("@ai-sdk/provider-utils").Context>>;
207
+ }) | ({
208
+ deferLoading?: boolean;
209
+ title?: string;
210
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
211
+ metadata?: import("@ai-sdk/provider").JSONObject;
212
+ inputSchema: import("ai").FlexibleSchema<{
213
+ request: string;
214
+ maxResults: number;
215
+ }>;
216
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
217
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
218
+ request: string;
219
+ maxResults: number;
220
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
221
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
222
+ onInputDelta?: ((options: {
223
+ inputTextDelta: string;
224
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
225
+ onInputAvailable?: ((options: {
226
+ input: {
227
+ request: string;
228
+ maxResults: number;
229
+ };
230
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
231
+ toModelOutput?: ((options: {
232
+ toolCallId: string;
233
+ input: {
234
+ request: string;
235
+ maxResults: number;
236
+ };
237
+ output: NoInfer<FindListResult>;
238
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
239
+ } & {
240
+ outputSchema?: import("ai").FlexibleSchema<FindListResult> | undefined;
241
+ execute: import("ai").ToolExecuteFunction<{
242
+ request: string;
243
+ maxResults: number;
244
+ }, FindListResult, NoInfer<import("@ai-sdk/provider-utils").Context>>;
245
+ } & {
246
+ type: "provider";
247
+ id: `${string}.${string}`;
248
+ args: Record<string, unknown>;
249
+ description?: never;
250
+ strict?: never;
251
+ inputExamples?: never;
252
+ } & {
253
+ isProviderExecuted: true;
254
+ supportsDeferredResults?: boolean;
255
+ } & {
256
+ execute: import("ai").ToolExecuteFunction<{
257
+ request: string;
258
+ maxResults: number;
259
+ }, FindListResult, NoInfer<import("@ai-sdk/provider-utils").Context>>;
260
+ });
261
+ specstream_get_list_results: ({
262
+ deferLoading?: boolean;
263
+ title?: string;
264
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
265
+ metadata?: import("@ai-sdk/provider").JSONObject;
266
+ inputSchema: import("ai").FlexibleSchema<{
267
+ listId: string;
268
+ }>;
269
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
270
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
271
+ listId: string;
272
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
273
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
274
+ onInputDelta?: ((options: {
275
+ inputTextDelta: string;
276
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
277
+ onInputAvailable?: ((options: {
278
+ input: {
279
+ listId: string;
280
+ };
281
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
282
+ toModelOutput?: ((options: {
283
+ toolCallId: string;
284
+ input: {
285
+ listId: string;
286
+ };
287
+ output: NoInfer<ListResults>;
288
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
289
+ } & {
290
+ outputSchema?: import("ai").FlexibleSchema<ListResults> | undefined;
291
+ execute: import("ai").ToolExecuteFunction<{
292
+ listId: string;
293
+ }, ListResults, NoInfer<import("@ai-sdk/provider-utils").Context>>;
294
+ } & {
295
+ description?: string | ((options: {
296
+ context: NoInfer<import("@ai-sdk/provider-utils").Context>;
297
+ experimental_sandbox?: import("ai").Experimental_SandboxSession;
298
+ }) => string) | undefined;
299
+ strict?: boolean;
300
+ inputExamples?: {
301
+ input: NoInfer<{
302
+ listId: string;
303
+ }>;
304
+ }[] | undefined;
305
+ id?: never;
306
+ isProviderExecuted?: never;
307
+ args?: never;
308
+ supportsDeferredResults?: never;
309
+ } & {
310
+ type?: undefined | "function";
311
+ } & {
312
+ execute: import("ai").ToolExecuteFunction<{
313
+ listId: string;
314
+ }, ListResults, NoInfer<import("@ai-sdk/provider-utils").Context>>;
315
+ }) | ({
316
+ deferLoading?: boolean;
317
+ title?: string;
318
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
319
+ metadata?: import("@ai-sdk/provider").JSONObject;
320
+ inputSchema: import("ai").FlexibleSchema<{
321
+ listId: string;
322
+ }>;
323
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
324
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
325
+ listId: string;
326
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
327
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
328
+ onInputDelta?: ((options: {
329
+ inputTextDelta: string;
330
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
331
+ onInputAvailable?: ((options: {
332
+ input: {
333
+ listId: string;
334
+ };
335
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
336
+ toModelOutput?: ((options: {
337
+ toolCallId: string;
338
+ input: {
339
+ listId: string;
340
+ };
341
+ output: NoInfer<ListResults>;
342
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
343
+ } & {
344
+ outputSchema?: import("ai").FlexibleSchema<ListResults> | undefined;
345
+ execute: import("ai").ToolExecuteFunction<{
346
+ listId: string;
347
+ }, ListResults, NoInfer<import("@ai-sdk/provider-utils").Context>>;
348
+ } & {
349
+ description?: string | ((options: {
350
+ context: NoInfer<import("@ai-sdk/provider-utils").Context>;
351
+ experimental_sandbox?: import("ai").Experimental_SandboxSession;
352
+ }) => string) | undefined;
353
+ strict?: boolean;
354
+ inputExamples?: {
355
+ input: NoInfer<{
356
+ listId: string;
357
+ }>;
358
+ }[] | undefined;
359
+ id?: never;
360
+ isProviderExecuted?: never;
361
+ args?: never;
362
+ supportsDeferredResults?: never;
363
+ } & {
364
+ type: "dynamic";
365
+ } & {
366
+ execute: import("ai").ToolExecuteFunction<{
367
+ listId: string;
368
+ }, ListResults, NoInfer<import("@ai-sdk/provider-utils").Context>>;
369
+ }) | ({
370
+ deferLoading?: boolean;
371
+ title?: string;
372
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
373
+ metadata?: import("@ai-sdk/provider").JSONObject;
374
+ inputSchema: import("ai").FlexibleSchema<{
375
+ listId: string;
376
+ }>;
377
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
378
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
379
+ listId: string;
380
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
381
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
382
+ onInputDelta?: ((options: {
383
+ inputTextDelta: string;
384
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
385
+ onInputAvailable?: ((options: {
386
+ input: {
387
+ listId: string;
388
+ };
389
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
390
+ toModelOutput?: ((options: {
391
+ toolCallId: string;
392
+ input: {
393
+ listId: string;
394
+ };
395
+ output: NoInfer<ListResults>;
396
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
397
+ } & {
398
+ outputSchema?: import("ai").FlexibleSchema<ListResults> | undefined;
399
+ execute: import("ai").ToolExecuteFunction<{
400
+ listId: string;
401
+ }, ListResults, NoInfer<import("@ai-sdk/provider-utils").Context>>;
402
+ } & {
403
+ type: "provider";
404
+ id: `${string}.${string}`;
405
+ args: Record<string, unknown>;
406
+ description?: never;
407
+ strict?: never;
408
+ inputExamples?: never;
409
+ } & {
410
+ isProviderExecuted: false;
411
+ supportsDeferredResults?: never;
412
+ } & {
413
+ execute: import("ai").ToolExecuteFunction<{
414
+ listId: string;
415
+ }, ListResults, NoInfer<import("@ai-sdk/provider-utils").Context>>;
416
+ }) | ({
417
+ deferLoading?: boolean;
418
+ title?: string;
419
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
420
+ metadata?: import("@ai-sdk/provider").JSONObject;
421
+ inputSchema: import("ai").FlexibleSchema<{
422
+ listId: string;
423
+ }>;
424
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
425
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
426
+ listId: string;
427
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
428
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
429
+ onInputDelta?: ((options: {
430
+ inputTextDelta: string;
431
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
432
+ onInputAvailable?: ((options: {
433
+ input: {
434
+ listId: string;
435
+ };
436
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
437
+ toModelOutput?: ((options: {
438
+ toolCallId: string;
439
+ input: {
440
+ listId: string;
441
+ };
442
+ output: NoInfer<ListResults>;
443
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
444
+ } & {
445
+ outputSchema?: import("ai").FlexibleSchema<ListResults> | undefined;
446
+ execute: import("ai").ToolExecuteFunction<{
447
+ listId: string;
448
+ }, ListResults, NoInfer<import("@ai-sdk/provider-utils").Context>>;
449
+ } & {
450
+ type: "provider";
451
+ id: `${string}.${string}`;
452
+ args: Record<string, unknown>;
453
+ description?: never;
454
+ strict?: never;
455
+ inputExamples?: never;
456
+ } & {
457
+ isProviderExecuted: true;
458
+ supportsDeferredResults?: boolean;
459
+ } & {
460
+ execute: import("ai").ToolExecuteFunction<{
461
+ listId: string;
462
+ }, ListResults, NoInfer<import("@ai-sdk/provider-utils").Context>>;
463
+ });
464
+ };
package/dist/tools.js ADDED
@@ -0,0 +1,75 @@
1
+ import { tool } from "ai";
2
+ import { z } from "zod";
3
+ import { DEFAULT_BASE_URL, DEFAULT_LOCALE, DEFAULT_POLL_INTERVAL_SECONDS, DEFAULT_WAIT_SECONDS, MAX_RESULTS, MISSING_KEY_MESSAGE, SpecStreamClient, } from "./client.js";
4
+ const findListInput = z.object({
5
+ request: z
6
+ .string()
7
+ .min(1)
8
+ .describe("The list in plain words: what to find, where, what every row must meet, and the facts to bring back. " +
9
+ 'Example: "Dental clinics in Lisbon with online booking, with their website and phone".'),
10
+ maxResults: z
11
+ .number()
12
+ .int()
13
+ .min(1)
14
+ .max(MAX_RESULTS)
15
+ .default(25)
16
+ .describe("How many rows to find, from 1 to 1000. Ask for what the task needs; the price grows with the matches."),
17
+ });
18
+ const getListResultsInput = z.object({
19
+ listId: z.string().min(1).describe('The list_id that specstream_find_list returned, like "fnd_gk5y3d0r97bvyz0t08zzh75kr6".'),
20
+ });
21
+ const FIND_LIST_DESCRIPTION = [
22
+ "Find a list of real things on the live web and return every matching row, each with the page it was read from.",
23
+ "Use it when the answer is many things that meet conditions: companies in a city, local businesses with a service, funding filings, open grants, tenders, clinical trials, repositories, people in a role.",
24
+ "For one fact or a summary of one page, use a search tool instead.",
25
+ "Rows that couldn't be confirmed are left out and aren't charged.",
26
+ "Returns JSON with status, list_id, list_link and rows (one object per match: its columns, source_url and checked_at).",
27
+ 'status "over_maximum" means nothing ran because the price was above the cap: ask for fewer rows or tell the user.',
28
+ 'status "needs_edit" means the request was too vague to price: add the place or the conditions.',
29
+ "If the list is still running, call specstream_get_list_results with its list_id for the rest.",
30
+ ].join(" ");
31
+ const GET_LIST_RESULTS_DESCRIPTION = [
32
+ "Read every row found so far for a SpecStream list, such as one that was still running. Reading is free.",
33
+ "Returns JSON with status, list_id, list_link and rows, each with its columns, source_url and checked_at.",
34
+ ].join(" ");
35
+ /**
36
+ * The two SpecStream tools for an AI SDK agent: find a list on the live web, and read a list's rows.
37
+ *
38
+ * The price cap is set here, in code, and is not a tool input, so the model can't raise it.
39
+ *
40
+ * @example
41
+ * const { text } = await generateText({
42
+ * model,
43
+ * tools: specstreamTools({ maxPriceUsd: 5 }),
44
+ * stopWhen: stepCountIs(5),
45
+ * prompt: "Find dental clinics in Lisbon with online booking.",
46
+ * });
47
+ */
48
+ export function specstreamTools(options) {
49
+ const { maxPriceUsd } = options;
50
+ if (typeof maxPriceUsd !== "number" || !Number.isFinite(maxPriceUsd) || maxPriceUsd <= 0) {
51
+ throw new Error("maxPriceUsd must be greater than 0.");
52
+ }
53
+ const client = new SpecStreamClient({ apiKey: options.apiKey, baseUrl: options.baseUrl ?? DEFAULT_BASE_URL, fetch: options.fetch });
54
+ if (!client.hasKey)
55
+ throw new Error(MISSING_KEY_MESSAGE);
56
+ return {
57
+ specstream_find_list: tool({
58
+ description: FIND_LIST_DESCRIPTION,
59
+ inputSchema: findListInput,
60
+ execute: async ({ request, maxResults }, { abortSignal }) => client.findList(request, {
61
+ maxResults: Math.max(1, Math.min(Math.trunc(Number(maxResults ?? 25)) || 25, MAX_RESULTS)),
62
+ maxPriceUsd,
63
+ waitSeconds: options.waitSeconds ?? DEFAULT_WAIT_SECONDS,
64
+ pollIntervalSeconds: options.pollIntervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS,
65
+ locale: options.locale ?? DEFAULT_LOCALE,
66
+ abortSignal,
67
+ }),
68
+ }),
69
+ specstream_get_list_results: tool({
70
+ description: GET_LIST_RESULTS_DESCRIPTION,
71
+ inputSchema: getListResultsInput,
72
+ execute: async ({ listId }, { abortSignal }) => client.results(listId.trim(), abortSignal),
73
+ }),
74
+ };
75
+ }
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "@specstream/ai-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Give a Vercel AI SDK agent any list from the live web: every matching row with the page it was read from, priced per match before anything runs.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "sideEffects": false,
21
+ "scripts": {
22
+ "build": "tsc -p tsconfig.json",
23
+ "typecheck": "tsc -p tsconfig.test.json",
24
+ "test": "vitest run",
25
+ "prepack": "npm run build"
26
+ },
27
+ "peerDependencies": {
28
+ "ai": "^6.0.0 || ^7.0.0",
29
+ "zod": "^3.25.76 || ^4.1.8"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^22.0.0",
33
+ "ai": "^7.0.140",
34
+ "typescript": "5.9.3",
35
+ "vitest": "^5.0.4",
36
+ "zod": "^4.6.7"
37
+ },
38
+ "engines": {
39
+ "node": ">=18"
40
+ },
41
+ "keywords": [
42
+ "ai-sdk",
43
+ "vercel-ai-sdk",
44
+ "ai",
45
+ "tools",
46
+ "agents",
47
+ "specstream",
48
+ "web-data",
49
+ "live-web",
50
+ "lead-lists",
51
+ "enrichment",
52
+ "ai-agents"
53
+ ],
54
+ "author": {
55
+ "name": "SpecStream",
56
+ "email": "support@specstream.ai",
57
+ "url": "https://specstream.ai"
58
+ },
59
+ "license": "MIT",
60
+ "homepage": "https://specstream.ai/docs/vercel-ai-sdk",
61
+ "repository": {
62
+ "type": "git",
63
+ "url": "git+https://github.com/Specstreamai/specstream-tools.git",
64
+ "directory": "packages/ai-sdk"
65
+ },
66
+ "bugs": {
67
+ "url": "https://github.com/Specstreamai/specstream-tools/issues"
68
+ },
69
+ "publishConfig": {
70
+ "access": "public"
71
+ }
72
+ }