@specstream/ai-sdk 0.2.2 → 0.4.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/README.md +79 -2
- package/dist/client.d.ts +150 -2
- package/dist/client.js +254 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/tools.d.ts +2339 -15
- package/dist/tools.js +162 -22
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -54,7 +54,7 @@ The tool's result wraps the rows with `status`, `list_id`, `list_link`, `row_cou
|
|
|
54
54
|
|
|
55
55
|
| Tool | The model gives | What happens | Cost |
|
|
56
56
|
| --- | --- | --- | --- |
|
|
57
|
-
| `specstream_web_search` | `q`, `passages` | Calls `GET /v1/web-search` and returns the answer, matching rows, ranked sources and optional page passages | $5 per 1,000 searches |
|
|
57
|
+
| `specstream_web_search` | `q`, `passages` | Calls `GET /v1/web-search` and returns the answer, matching rows, ranked sources and optional page passages | $5 per 1,000 searches of up to 10 results, $1 per 1,000 with `speed=fast` |
|
|
58
58
|
| `specstream_extract_pages` | `urls`, `format` | Calls `POST /v1/extract` and returns the clean main text, title and published date of 1 to 20 web pages, PDFs, Word or Excel files | $0.80 per 1,000 pages (empty pages free) |
|
|
59
59
|
| `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 delivered rows |
|
|
60
60
|
| `specstream_get_list_results` | `listId` | Every row found so far, for a list that was still running | Free |
|
|
@@ -72,9 +72,41 @@ Settings, all optional except the price:
|
|
|
72
72
|
| `locale` | `en-US` | The language and region the request is written in |
|
|
73
73
|
| `baseUrl` | `https://api.specstream.ai` | The SpecStream API address |
|
|
74
74
|
| `fetch` | global `fetch` | Your own `fetch`, for a proxy or a test |
|
|
75
|
+
| `monitorMaxPricePerRunUsd` | not set | The most one check of a monitored list may cost. Set it to give the model the two monitor tools |
|
|
76
|
+
| `monitorMaxPricePerMonthUsd` | per check × checks in 31 days | The most one monitor may spend in a UTC calendar month |
|
|
75
77
|
|
|
76
78
|
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`.
|
|
77
79
|
|
|
80
|
+
## Browser sessions
|
|
81
|
+
|
|
82
|
+
Some pages show nothing until a button is clicked, a form is filled in or their JavaScript runs. For those, the agent opens a real browser that SpecStream runs, drives it step by step and closes it.
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { generateText, stepCountIs } from "ai";
|
|
86
|
+
import { specstreamBrowserTools } from "@specstream/ai-sdk";
|
|
87
|
+
|
|
88
|
+
const { text } = await generateText({
|
|
89
|
+
model: "openai/gpt-5-mini",
|
|
90
|
+
tools: specstreamBrowserTools({ timeoutSeconds: 300, allowedDomains: ["example.com"] }),
|
|
91
|
+
stopWhen: stepCountIs(12),
|
|
92
|
+
prompt: "Open example.com, accept the cookie banner and read the pricing table.",
|
|
93
|
+
});
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
| Tool | Input | What it does | Price |
|
|
97
|
+
| --- | --- | --- | --- |
|
|
98
|
+
| `specstream_open_browser` | `url` (optional) | Calls `POST /v1/browser/sessions` with the limits you set in code and returns the `session_id` | $0.10 an hour of browser time, charged by the second |
|
|
99
|
+
| `specstream_browser_navigate` | `session_id`, `url` | Opens the address | $1 per 1,000 steps |
|
|
100
|
+
| `specstream_browser_read` | `session_id`, `format` | The page's text as it stands after its JavaScript ran, in Markdown or plain text | $1 per 1,000 steps |
|
|
101
|
+
| `specstream_browser_snapshot` | `session_id` | The page's links, buttons and fields, each with a reference | $1 per 1,000 steps |
|
|
102
|
+
| `specstream_browser_click`, `specstream_browser_type` | `session_id`, `target`, `text` | Clicks an element or types into a field, by its reference | $1 per 1,000 steps |
|
|
103
|
+
| `specstream_browser_action` | `session_id`, `tool`, `arguments` | Any other Playwright MCP step: a key press, a select, a wait, a form | $1 per 1,000 steps |
|
|
104
|
+
| `specstream_close_browser` | `session_id` | Calls `POST /v1/browser/sessions/{id}/release` and returns the seconds, the steps and the charge | Free |
|
|
105
|
+
|
|
106
|
+
`timeoutSeconds` (60 to 3600, default 300) is set in your code and is not a tool input: the browser ends then, whatever the model does, so 300 seconds is at most $0.0084 of time. `idleTimeoutSeconds` (default 120) ends a browser no step has touched. `allowedDomains` keeps the browser on the hosts you name, `blockMedia` skips images, video and fonts. A page a site or your own list refuses comes back as an `error` the agent can read, not an exception. Spread both sets into one agent with `tools: { ...specstreamTools({ maxPriceUsd: 5 }), ...specstreamBrowserTools() }`.
|
|
107
|
+
|
|
108
|
+
Without a model, the same calls are on the client: `openBrowser()`, `browserStep(sessionId, tool, args)`, `browserSession(sessionId)` and `closeBrowser(sessionId)`.
|
|
109
|
+
|
|
78
110
|
## Without a model
|
|
79
111
|
|
|
80
112
|
The client the tools are built on is exported, for the same calls from your own code:
|
|
@@ -93,9 +125,54 @@ if ("rows" in list) console.log(list.row_count, list.rows[0].source_url);
|
|
|
93
125
|
else console.log(list.message); // "over_maximum" or "needs_edit": nothing ran
|
|
94
126
|
```
|
|
95
127
|
|
|
128
|
+
## Keep a list current on a schedule
|
|
129
|
+
|
|
130
|
+
A monitor checks a list again on the live web every hour, day, week or month.
|
|
131
|
+
Each check is a refresh: half the row rate for a row that changed or is new, and 1¢ for a row that comes back unchanged.
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
import { SpecStreamClient } from "@specstream/ai-sdk";
|
|
135
|
+
|
|
136
|
+
const client = new SpecStreamClient();
|
|
137
|
+
|
|
138
|
+
const monitor = await client.monitorList("fnd_gk5y3d0r97bvyz0t08zzh75kr6", {
|
|
139
|
+
every: "week",
|
|
140
|
+
maxPricePerRunUsd: 2,
|
|
141
|
+
maxPricePerMonthUsd: 8,
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
if (monitor.status === "saved") console.log(monitor.monitor_id, monitor.next_run_at);
|
|
145
|
+
else console.log(monitor.message); // "over_maximum": one check costs more than maxPricePerRunUsd, nothing was saved
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
The client prices one check before it saves anything.
|
|
149
|
+
When one check can cost more than `maxPricePerRunUsd`, nothing is saved.
|
|
150
|
+
`maxPricePerMonthUsd` is the most the monitor spends in one UTC calendar month, checks run on demand included.
|
|
151
|
+
Without it, the limit is `maxPricePerRunUsd` times the checks in 31 days.
|
|
152
|
+
The first check runs one interval after the current hour began, and the monitor ends a year after it, unless you set `firstRunAt` and `until`.
|
|
153
|
+
|
|
154
|
+
| Call | What it does | Cost |
|
|
155
|
+
| --- | --- | --- |
|
|
156
|
+
| `monitorList(listId, options)` | Prices one check of the list and saves the schedule within your limits | Each check, within the limits |
|
|
157
|
+
| `monitors()` | Every monitor of the account, with its state, next check and last list | Free |
|
|
158
|
+
| `monitorRuns(monitorId)` | The recent checks, newest first: when, the outcome, the reason and the list each one made | Free |
|
|
159
|
+
| `runMonitorNow(monitorId)` | One check now, inside the monitor's limits. The regular times stay as they are | One check |
|
|
160
|
+
| `pauseMonitor(monitorId)`, `resumeMonitor(monitorId)` | Stops and starts the checks. A missed check is never bought later | Free |
|
|
161
|
+
| `deleteMonitor(monitorId)` | Ends the monitor. The lists it made stay yours | Free |
|
|
162
|
+
|
|
163
|
+
To let an agent start monitors, give the tools a maximum per check.
|
|
164
|
+
The model then gets `specstream_monitor_list` (it picks the list and how often) and `specstream_list_monitors`.
|
|
165
|
+
Without `monitorMaxPricePerRunUsd`, the model can't start recurring work.
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
const tools = specstreamTools({ maxPriceUsd: 5, monitorMaxPricePerRunUsd: 2, monitorMaxPricePerMonthUsd: 20 });
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Where each check's new and changed rows go (Slack, email, a sheet, a CRM or a webhook) is set on the monitor in your SpecStream workspace.
|
|
172
|
+
|
|
96
173
|
## Money, plainly
|
|
97
174
|
|
|
98
|
-
- `maxPriceUsd`
|
|
175
|
+
- `maxPriceUsd` and the monitor limits live in your code. The model never sees them and can't change them.
|
|
99
176
|
- You pay for rows that match. Candidates SpecStream couldn't confirm are left out and aren't billed.
|
|
100
177
|
- 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.
|
|
101
178
|
- Rates and plans: [specstream.ai/pricing](https://specstream.ai/pricing).
|
package/dist/client.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** The SpecStream REST calls the tools share: read a request, price it, start it within a maximum, read its rows. */
|
|
2
2
|
export declare const DEFAULT_BASE_URL = "https://api.specstream.ai";
|
|
3
|
-
export declare const USER_AGENT = "@specstream/ai-sdk/0.
|
|
3
|
+
export declare const USER_AGENT = "@specstream/ai-sdk/0.4.0";
|
|
4
4
|
/** A list runs for up to about five minutes, so the tools wait a little longer than that by default. */
|
|
5
5
|
export declare const DEFAULT_WAIT_SECONDS = 420;
|
|
6
6
|
export declare const DEFAULT_POLL_INTERVAL_SECONDS = 3;
|
|
@@ -106,9 +106,14 @@ export declare class SpecStreamClient {
|
|
|
106
106
|
constructor(options?: SpecStreamClientOptions);
|
|
107
107
|
get hasKey(): boolean;
|
|
108
108
|
private request;
|
|
109
|
-
/**
|
|
109
|
+
/**
|
|
110
|
+
* Search the live web with GET /v1/web-search ($5 per 1,000 searches of up to 10 results, no quote needed).
|
|
111
|
+
* speed "fast" returns the engines' first ranked results in about a second, at $1 per 1,000 searches;
|
|
112
|
+
* left out, the API's default search runs.
|
|
113
|
+
*/
|
|
110
114
|
webSearch(query: string, options?: {
|
|
111
115
|
passages?: boolean;
|
|
116
|
+
speed?: "fast" | "default";
|
|
112
117
|
abortSignal?: AbortSignal;
|
|
113
118
|
}): Promise<Record<string, unknown>>;
|
|
114
119
|
/** Extract the main text of 1 to 20 URLs live with POST /v1/extract ($0.80 per 1,000 pages, empty pages free). */
|
|
@@ -116,9 +121,152 @@ export declare class SpecStreamClient {
|
|
|
116
121
|
format?: "markdown" | "text";
|
|
117
122
|
abortSignal?: AbortSignal;
|
|
118
123
|
}): Promise<Record<string, unknown>>;
|
|
124
|
+
/**
|
|
125
|
+
* Open a real browser that SpecStream runs, with POST /v1/browser/sessions. Time costs $0.10 an hour,
|
|
126
|
+
* charged by the second while it is open, and each step costs $0.001. The browser ends by itself
|
|
127
|
+
* after `timeoutSeconds`. The steps hold no connection, so the session is kept alive between them.
|
|
128
|
+
*/
|
|
129
|
+
openBrowser(options?: OpenBrowserOptions): Promise<BrowserSessionView>;
|
|
130
|
+
/**
|
|
131
|
+
* Run one step in the session's browser with POST /v1/browser/sessions/{id}/actions ($0.001 a step).
|
|
132
|
+
* `tool` is a Playwright MCP tool name (browser_navigate, browser_snapshot, browser_click, browser_type and
|
|
133
|
+
* the others) or browser_read for the page's text. A page the site or your allowed hosts refuse comes back
|
|
134
|
+
* in `error`, not as an exception.
|
|
135
|
+
*/
|
|
136
|
+
browserStep(sessionId: string, tool: string, args?: Record<string, unknown>, abortSignal?: AbortSignal): Promise<BrowserStepView>;
|
|
137
|
+
/** A session's state, its seconds, steps and charge so far, with GET /v1/browser/sessions/{id}. Reading is free. */
|
|
138
|
+
browserSession(sessionId: string, abortSignal?: AbortSignal): Promise<BrowserSessionView>;
|
|
139
|
+
/** End the session with POST /v1/browser/sessions/{id}/release, so its time stops being charged. */
|
|
140
|
+
closeBrowser(sessionId: string, abortSignal?: AbortSignal): Promise<BrowserSessionView>;
|
|
119
141
|
/** Every row found so far for a list, following the pages. Reading is free. */
|
|
120
142
|
results(findId: string, abortSignal?: AbortSignal): Promise<ListResults>;
|
|
121
143
|
/** Reads the request, prices it, and runs it only if the most it can cost is within `maxPriceUsd`. */
|
|
122
144
|
findList(request: string, options: FindListOptions): Promise<FindListResult>;
|
|
145
|
+
/**
|
|
146
|
+
* Checks a list again on a schedule. Each check reads the live web for the list's rows.
|
|
147
|
+
* Nothing is saved when one check can cost more than `maxPricePerRunUsd`.
|
|
148
|
+
*/
|
|
149
|
+
monitorList(listId: string, options: MonitorListOptions): Promise<MonitorListResult>;
|
|
150
|
+
/** Every monitor of the account, running, paused or ended. Reading is free. */
|
|
151
|
+
monitors(abortSignal?: AbortSignal): Promise<Monitor[]>;
|
|
152
|
+
/** A monitor's recent checks, newest first: each one's time, outcome, reason and the list it made. Reading is free. */
|
|
153
|
+
monitorRuns(monitorId: string, options?: {
|
|
154
|
+
limit?: number;
|
|
155
|
+
abortSignal?: AbortSignal;
|
|
156
|
+
}): Promise<MonitorRun[]>;
|
|
157
|
+
/** Checks the list once now, inside the monitor's own limits. Its regular times stay as they are. */
|
|
158
|
+
runMonitorNow(monitorId: string, abortSignal?: AbortSignal): Promise<{
|
|
159
|
+
monitor_id: string;
|
|
160
|
+
list_id: string;
|
|
161
|
+
started_at: string;
|
|
162
|
+
}>;
|
|
163
|
+
/** Stops the checks until `resumeMonitor`. Missed checks are never bought later. */
|
|
164
|
+
pauseMonitor(monitorId: string, abortSignal?: AbortSignal): Promise<Monitor>;
|
|
165
|
+
/** Starts the checks again from the next time due. */
|
|
166
|
+
resumeMonitor(monitorId: string, abortSignal?: AbortSignal): Promise<Monitor>;
|
|
167
|
+
/** Ends the monitor for good. The lists it made stay yours. */
|
|
168
|
+
deleteMonitor(monitorId: string, abortSignal?: AbortSignal): Promise<Monitor>;
|
|
169
|
+
private setMonitorState;
|
|
123
170
|
}
|
|
171
|
+
export type MonitorEvery = "hour" | "day" | "week" | "month";
|
|
172
|
+
export type MonitorListOptions = {
|
|
173
|
+
/** How often to check the list. "month" is every 30 days. Defaults to "day". */
|
|
174
|
+
every?: MonitorEvery;
|
|
175
|
+
/** The most one check may cost, in US dollars. Above it, nothing is saved. */
|
|
176
|
+
maxPricePerRunUsd: number;
|
|
177
|
+
/** The most the monitor may spend in one UTC calendar month, checks run on demand included. Defaults to the per-check maximum times the checks in 31 days. */
|
|
178
|
+
maxPricePerMonthUsd?: number;
|
|
179
|
+
/** The first check. Defaults to one interval after the current hour began. */
|
|
180
|
+
firstRunAt?: Date;
|
|
181
|
+
/** The monitor ends here. Defaults to one year after the first check. */
|
|
182
|
+
until?: Date;
|
|
183
|
+
abortSignal?: AbortSignal;
|
|
184
|
+
};
|
|
185
|
+
/** A saved monitor, as the API reports it. */
|
|
186
|
+
export type Monitor = {
|
|
187
|
+
status: "saved";
|
|
188
|
+
monitor_id: string;
|
|
189
|
+
list_id: string | null;
|
|
190
|
+
/** "active", "paused", "deleted" or another state the API reports, such as a monitor out of credit. */
|
|
191
|
+
state: string;
|
|
192
|
+
every_seconds: number;
|
|
193
|
+
next_run_at: string | null;
|
|
194
|
+
last_run_at: string | null;
|
|
195
|
+
last_list_id: string | null;
|
|
196
|
+
last_reason: string | null;
|
|
197
|
+
max_price_per_run_usd: number;
|
|
198
|
+
max_price_per_month_usd: number;
|
|
199
|
+
valid_until: string | null;
|
|
200
|
+
version: number;
|
|
201
|
+
list_link: string | null;
|
|
202
|
+
};
|
|
203
|
+
export type MonitorOverMaximum = {
|
|
204
|
+
status: "over_maximum";
|
|
205
|
+
list_id: string;
|
|
206
|
+
maximum_price_usd: number;
|
|
207
|
+
message: string;
|
|
208
|
+
};
|
|
209
|
+
export type MonitorListResult = Monitor | MonitorOverMaximum;
|
|
210
|
+
export type MonitorRun = {
|
|
211
|
+
due_at: string;
|
|
212
|
+
/** "started", "completed", "blocked", "missed" or another outcome the API reports. */
|
|
213
|
+
status: string;
|
|
214
|
+
reason: string | null;
|
|
215
|
+
list_id: string | null;
|
|
216
|
+
};
|
|
217
|
+
export declare const BROWSER_DEFAULT_TIMEOUT_SECONDS = 300;
|
|
218
|
+
export declare const BROWSER_DEFAULT_IDLE_SECONDS = 120;
|
|
219
|
+
export type OpenBrowserOptions = {
|
|
220
|
+
/** The most seconds the browser runs, from 60 to 3600. Defaults to 300: at $0.10 an hour, at most $0.0084 of time. */
|
|
221
|
+
timeoutSeconds?: number;
|
|
222
|
+
/** The browser ends after this many seconds with no step, from 10 to 600. Defaults to 120. */
|
|
223
|
+
idleTimeoutSeconds?: number;
|
|
224
|
+
/** Hosts the browser may open, such as example.com or *.example.com. Left out, every public host is allowed. */
|
|
225
|
+
allowedDomains?: string[];
|
|
226
|
+
/** true skips images, video, audio and fonts, so pages load faster. */
|
|
227
|
+
blockMedia?: boolean;
|
|
228
|
+
/** false runs the browser with a screen, for sites that act differently without one. */
|
|
229
|
+
headless?: boolean;
|
|
230
|
+
/** Your own labels for the session, returned as sent. */
|
|
231
|
+
metadata?: Record<string, string | number | boolean>;
|
|
232
|
+
abortSignal?: AbortSignal;
|
|
233
|
+
};
|
|
234
|
+
/** A browser session as a model reads it. The connect address is left out: it carries the session's token. */
|
|
235
|
+
export type BrowserSessionView = {
|
|
236
|
+
session_id: string;
|
|
237
|
+
status?: string;
|
|
238
|
+
ended_reason?: string;
|
|
239
|
+
live_url?: string;
|
|
240
|
+
expires_at?: string;
|
|
241
|
+
timeout_s?: number;
|
|
242
|
+
seconds?: number;
|
|
243
|
+
actions?: number;
|
|
244
|
+
charged_usd?: number;
|
|
245
|
+
price?: {
|
|
246
|
+
per_second_usd: number;
|
|
247
|
+
per_action_usd: number;
|
|
248
|
+
};
|
|
249
|
+
/** Set by `specstream_open_browser` when it was given a first page. */
|
|
250
|
+
page?: BrowserStepView;
|
|
251
|
+
message?: string;
|
|
252
|
+
};
|
|
253
|
+
/** One step as a model reads it: the step's text, where the page is, and what the step cost. */
|
|
254
|
+
export type BrowserStepView = {
|
|
255
|
+
session_id: string;
|
|
256
|
+
text?: string;
|
|
257
|
+
/** An image's base64 is left out: it is large and of no use to a model that reads text. */
|
|
258
|
+
images?: {
|
|
259
|
+
mime_type: string | null;
|
|
260
|
+
base64_chars: number;
|
|
261
|
+
}[];
|
|
262
|
+
url?: string;
|
|
263
|
+
title?: string;
|
|
264
|
+
read_at?: string;
|
|
265
|
+
price_usd?: number;
|
|
266
|
+
error?: {
|
|
267
|
+
code: string;
|
|
268
|
+
reason?: string | null;
|
|
269
|
+
message: string;
|
|
270
|
+
};
|
|
271
|
+
};
|
|
124
272
|
export {};
|
package/dist/client.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** The SpecStream REST calls the tools share: read a request, price it, start it within a maximum, read its rows. */
|
|
2
2
|
export const DEFAULT_BASE_URL = "https://api.specstream.ai";
|
|
3
|
-
export const USER_AGENT = "@specstream/ai-sdk/0.
|
|
3
|
+
export const USER_AGENT = "@specstream/ai-sdk/0.4.0";
|
|
4
4
|
/** A list runs for up to about five minutes, so the tools wait a little longer than that by default. */
|
|
5
5
|
export const DEFAULT_WAIT_SECONDS = 420;
|
|
6
6
|
export const DEFAULT_POLL_INTERVAL_SECONDS = 3;
|
|
@@ -150,14 +150,23 @@ export class SpecStreamClient {
|
|
|
150
150
|
throw new SpecStreamError("SpecStream returned a response this package couldn't read.");
|
|
151
151
|
return data;
|
|
152
152
|
}
|
|
153
|
-
/**
|
|
153
|
+
/**
|
|
154
|
+
* Search the live web with GET /v1/web-search ($5 per 1,000 searches of up to 10 results, no quote needed).
|
|
155
|
+
* speed "fast" returns the engines' first ranked results in about a second, at $1 per 1,000 searches;
|
|
156
|
+
* left out, the API's default search runs.
|
|
157
|
+
*/
|
|
154
158
|
async webSearch(query, options = {}) {
|
|
155
159
|
const q = (query ?? "").trim();
|
|
156
160
|
if (!q || q.length > 2000)
|
|
157
161
|
throw new Error("q must be between 1 and 2,000 characters.");
|
|
162
|
+
if (options.speed !== undefined && options.speed !== "fast" && options.speed !== "default") {
|
|
163
|
+
throw new Error('speed must be "default" or "fast".');
|
|
164
|
+
}
|
|
158
165
|
const params = new URLSearchParams({ q });
|
|
159
166
|
if (options.passages)
|
|
160
167
|
params.set("passages", "true");
|
|
168
|
+
if (options.speed)
|
|
169
|
+
params.set("speed", options.speed);
|
|
161
170
|
return (await this.request("GET", `/v1/web-search?${params}`, undefined, { abortSignal: options.abortSignal })) ?? {};
|
|
162
171
|
}
|
|
163
172
|
/** Extract the main text of 1 to 20 URLs live with POST /v1/extract ($0.80 per 1,000 pages, empty pages free). */
|
|
@@ -168,6 +177,53 @@ export class SpecStreamClient {
|
|
|
168
177
|
const format = options.format === "text" ? "text" : "markdown";
|
|
169
178
|
return (await this.request("POST", "/v1/extract", { urls: cleaned, format }, { abortSignal: options.abortSignal })) ?? {};
|
|
170
179
|
}
|
|
180
|
+
/**
|
|
181
|
+
* Open a real browser that SpecStream runs, with POST /v1/browser/sessions. Time costs $0.10 an hour,
|
|
182
|
+
* charged by the second while it is open, and each step costs $0.001. The browser ends by itself
|
|
183
|
+
* after `timeoutSeconds`. The steps hold no connection, so the session is kept alive between them.
|
|
184
|
+
*/
|
|
185
|
+
async openBrowser(options = {}) {
|
|
186
|
+
const timeout = options.timeoutSeconds ?? BROWSER_DEFAULT_TIMEOUT_SECONDS;
|
|
187
|
+
if (!Number.isInteger(timeout) || timeout < 60 || timeout > 3600)
|
|
188
|
+
throw new Error("timeoutSeconds must be a whole number from 60 to 3600.");
|
|
189
|
+
const idle = options.idleTimeoutSeconds ?? BROWSER_DEFAULT_IDLE_SECONDS;
|
|
190
|
+
if (!Number.isInteger(idle) || idle < 10 || idle > 600)
|
|
191
|
+
throw new Error("idleTimeoutSeconds must be a whole number from 10 to 600.");
|
|
192
|
+
const body = { timeout_s: timeout, idle_timeout_s: idle, keep_alive: true };
|
|
193
|
+
if (options.allowedDomains?.length)
|
|
194
|
+
body.allowed_domains = options.allowedDomains;
|
|
195
|
+
if (options.blockMedia)
|
|
196
|
+
body.block_media = true;
|
|
197
|
+
if (options.headless === false)
|
|
198
|
+
body.headless = false;
|
|
199
|
+
if (options.metadata && Object.keys(options.metadata).length)
|
|
200
|
+
body.metadata = options.metadata;
|
|
201
|
+
return sessionView((await this.request("POST", "/v1/browser/sessions", body, { abortSignal: options.abortSignal })) ?? {});
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Run one step in the session's browser with POST /v1/browser/sessions/{id}/actions ($0.001 a step).
|
|
205
|
+
* `tool` is a Playwright MCP tool name (browser_navigate, browser_snapshot, browser_click, browser_type and
|
|
206
|
+
* the others) or browser_read for the page's text. A page the site or your allowed hosts refuse comes back
|
|
207
|
+
* in `error`, not as an exception.
|
|
208
|
+
*/
|
|
209
|
+
async browserStep(sessionId, tool, args = {}, abortSignal) {
|
|
210
|
+
const id = requireSessionId(sessionId);
|
|
211
|
+
if (!BROWSER_TOOL_NAME.test(tool ?? ""))
|
|
212
|
+
throw new Error("tool must be a browser step name such as browser_navigate or browser_click.");
|
|
213
|
+
const cleaned = Object.fromEntries(Object.entries(args ?? {}).filter(([, value]) => value !== undefined && value !== null));
|
|
214
|
+
const answer = (await this.request("POST", `/v1/browser/sessions/${encodeURIComponent(id)}/actions`, { tool, arguments: cleaned }, { abortSignal })) ?? {};
|
|
215
|
+
return stepView(id, answer);
|
|
216
|
+
}
|
|
217
|
+
/** A session's state, its seconds, steps and charge so far, with GET /v1/browser/sessions/{id}. Reading is free. */
|
|
218
|
+
async browserSession(sessionId, abortSignal) {
|
|
219
|
+
const id = requireSessionId(sessionId);
|
|
220
|
+
return sessionView((await this.request("GET", `/v1/browser/sessions/${encodeURIComponent(id)}`, undefined, { abortSignal })) ?? {});
|
|
221
|
+
}
|
|
222
|
+
/** End the session with POST /v1/browser/sessions/{id}/release, so its time stops being charged. */
|
|
223
|
+
async closeBrowser(sessionId, abortSignal) {
|
|
224
|
+
const id = requireSessionId(sessionId);
|
|
225
|
+
return sessionView((await this.request("POST", `/v1/browser/sessions/${encodeURIComponent(id)}/release`, undefined, { abortSignal })) ?? {});
|
|
226
|
+
}
|
|
171
227
|
/** Every row found so far for a list, following the pages. Reading is free. */
|
|
172
228
|
async results(findId, abortSignal) {
|
|
173
229
|
const rows = [];
|
|
@@ -266,6 +322,161 @@ export class SpecStreamClient {
|
|
|
266
322
|
}
|
|
267
323
|
return found;
|
|
268
324
|
}
|
|
325
|
+
/**
|
|
326
|
+
* Checks a list again on a schedule. Each check reads the live web for the list's rows.
|
|
327
|
+
* Nothing is saved when one check can cost more than `maxPricePerRunUsd`.
|
|
328
|
+
*/
|
|
329
|
+
async monitorList(listId, options) {
|
|
330
|
+
const findId = (listId ?? "").trim();
|
|
331
|
+
if (!findId)
|
|
332
|
+
throw new Error("Give the list_id of the list to monitor.");
|
|
333
|
+
const every = options.every ?? "day";
|
|
334
|
+
const cadenceSeconds = CADENCE_SECONDS[every];
|
|
335
|
+
if (!cadenceSeconds)
|
|
336
|
+
throw new Error('every must be "hour", "day", "week" or "month".');
|
|
337
|
+
const perRunCents = Math.round(Number(options.maxPricePerRunUsd) * 100);
|
|
338
|
+
if (!(perRunCents > 0))
|
|
339
|
+
throw new Error("maxPricePerRunUsd must be greater than 0.");
|
|
340
|
+
const periodCents = options.maxPricePerMonthUsd === undefined
|
|
341
|
+
? perRunCents * Math.ceil((31 * 86_400) / cadenceSeconds)
|
|
342
|
+
: Math.round(Number(options.maxPricePerMonthUsd) * 100);
|
|
343
|
+
if (!(periodCents >= perRunCents))
|
|
344
|
+
throw new Error("maxPricePerMonthUsd must cover at least one check.");
|
|
345
|
+
const { abortSignal } = options;
|
|
346
|
+
// Times come from the start of the hour, so a retried step sends the same schedule and gets the one it saved.
|
|
347
|
+
const hourStart = Math.floor(this.now() / 3_600_000) * 3_600_000;
|
|
348
|
+
const first = options.firstRunAt ? options.firstRunAt.getTime() : hourStart + cadenceSeconds * 1000;
|
|
349
|
+
const until = options.until ? options.until.getTime() : first + 365 * 86_400_000;
|
|
350
|
+
if (!Number.isFinite(first) || !Number.isFinite(until) || until <= first) {
|
|
351
|
+
throw new Error("until must come after the first check.");
|
|
352
|
+
}
|
|
353
|
+
const list = (await this.request("GET", `/v1/finds/${encodeURIComponent(findId)}`, undefined, { abortSignal })) ?? {};
|
|
354
|
+
if (typeof list.ast_hash !== "string" || !list.ast_hash) {
|
|
355
|
+
throw new SpecStreamError("SpecStream returned a response this package couldn't read.");
|
|
356
|
+
}
|
|
357
|
+
const units = Math.max(1, Math.min(Math.trunc(Number(list.requested_count)) || 25, 10_000));
|
|
358
|
+
// A list in a project is checked in that project; the API refuses any other.
|
|
359
|
+
const scope = {
|
|
360
|
+
ast_hash: list.ast_hash,
|
|
361
|
+
operation: "refresh",
|
|
362
|
+
parent_find_id: findId,
|
|
363
|
+
requested_units: units,
|
|
364
|
+
...(typeof list.project_id === "string" && list.project_id ? { project_id: list.project_id } : {}),
|
|
365
|
+
};
|
|
366
|
+
const quote = (await this.request("POST", "/v1/capacity/quotes", scope, { abortSignal })) ?? {};
|
|
367
|
+
const maximumCents = Math.trunc(Number(quote.maximum_cents)) || 0;
|
|
368
|
+
if (maximumCents > perRunCents) {
|
|
369
|
+
return {
|
|
370
|
+
status: "over_maximum",
|
|
371
|
+
list_id: findId,
|
|
372
|
+
maximum_price_usd: maximumCents / 100,
|
|
373
|
+
message: `Nothing was saved: one check of this list can cost up to ${dollars(maximumCents)}, above the maximum of ${dollars(perRunCents)} per check. Raise maxPricePerRunUsd.`,
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
const firstDueAt = new Date(first).toISOString();
|
|
377
|
+
const validUntil = new Date(until).toISOString();
|
|
378
|
+
const digest = await sha256Hex(`${findId}|${cadenceSeconds}|${perRunCents}|${periodCents}|${firstDueAt}|${validUntil}`);
|
|
379
|
+
const schedule = (await this.request("POST", "/v1/capacity/schedules", {
|
|
380
|
+
idempotency_key: `${this.keyPrefix}-monitor-${digest.slice(0, 32)}`,
|
|
381
|
+
scope,
|
|
382
|
+
cadence_seconds: cadenceSeconds,
|
|
383
|
+
first_due_at: firstDueAt,
|
|
384
|
+
per_run_cents: perRunCents,
|
|
385
|
+
period_cents: periodCents,
|
|
386
|
+
valid_until: validUntil,
|
|
387
|
+
}, { abortSignal })) ?? {};
|
|
388
|
+
return monitorView(schedule);
|
|
389
|
+
}
|
|
390
|
+
/** Every monitor of the account, running, paused or ended. Reading is free. */
|
|
391
|
+
async monitors(abortSignal) {
|
|
392
|
+
const found = [];
|
|
393
|
+
let after = null;
|
|
394
|
+
for (;;) {
|
|
395
|
+
const query = new URLSearchParams({ limit: "100", ...(after ? { after } : {}) });
|
|
396
|
+
const page = (await this.request("GET", `/v1/capacity/schedules?${query}`, undefined, { abortSignal })) ?? {};
|
|
397
|
+
for (const item of Array.isArray(page.schedules) ? page.schedules : []) {
|
|
398
|
+
if (isObject(item))
|
|
399
|
+
found.push(monitorView(item));
|
|
400
|
+
}
|
|
401
|
+
const next = typeof page.next_after === "string" && page.next_after ? page.next_after : null;
|
|
402
|
+
if (!next || next === after)
|
|
403
|
+
break;
|
|
404
|
+
after = next;
|
|
405
|
+
}
|
|
406
|
+
return found;
|
|
407
|
+
}
|
|
408
|
+
/** A monitor's recent checks, newest first: each one's time, outcome, reason and the list it made. Reading is free. */
|
|
409
|
+
async monitorRuns(monitorId, options = {}) {
|
|
410
|
+
const limit = Math.max(1, Math.min(Math.trunc(Number(options.limit ?? 50)) || 50, 100));
|
|
411
|
+
const page = (await this.request("GET", `/v1/capacity/schedules/${encodeURIComponent(requireId(monitorId))}/occurrences?limit=${limit}`, undefined, { abortSignal: options.abortSignal })) ?? {};
|
|
412
|
+
return (Array.isArray(page.occurrences) ? page.occurrences : []).filter(isObject).map((item) => ({
|
|
413
|
+
due_at: String(item.due_at ?? ""),
|
|
414
|
+
status: String(item.status ?? ""),
|
|
415
|
+
reason: item.reason == null ? null : String(item.reason),
|
|
416
|
+
list_id: item.find_id == null ? null : String(item.find_id),
|
|
417
|
+
}));
|
|
418
|
+
}
|
|
419
|
+
/** Checks the list once now, inside the monitor's own limits. Its regular times stay as they are. */
|
|
420
|
+
async runMonitorNow(monitorId, abortSignal) {
|
|
421
|
+
const id = requireId(monitorId);
|
|
422
|
+
const run = (await this.request("POST", `/v1/capacity/schedules/${encodeURIComponent(id)}/run`, undefined, { abortSignal })) ?? {};
|
|
423
|
+
if (!run.find_id)
|
|
424
|
+
throw new SpecStreamError("SpecStream returned a response this package couldn't read.");
|
|
425
|
+
return { monitor_id: id, list_id: String(run.find_id), started_at: String(run.started_at ?? "") };
|
|
426
|
+
}
|
|
427
|
+
/** Stops the checks until `resumeMonitor`. Missed checks are never bought later. */
|
|
428
|
+
pauseMonitor(monitorId, abortSignal) {
|
|
429
|
+
return this.setMonitorState(monitorId, "paused", abortSignal);
|
|
430
|
+
}
|
|
431
|
+
/** Starts the checks again from the next time due. */
|
|
432
|
+
resumeMonitor(monitorId, abortSignal) {
|
|
433
|
+
return this.setMonitorState(monitorId, "active", abortSignal);
|
|
434
|
+
}
|
|
435
|
+
/** Ends the monitor for good. The lists it made stay yours. */
|
|
436
|
+
deleteMonitor(monitorId, abortSignal) {
|
|
437
|
+
return this.setMonitorState(monitorId, "deleted", abortSignal);
|
|
438
|
+
}
|
|
439
|
+
async setMonitorState(monitorId, state, abortSignal) {
|
|
440
|
+
const id = requireId(monitorId);
|
|
441
|
+
const current = (await this.monitors(abortSignal)).find((monitor) => monitor.monitor_id === id);
|
|
442
|
+
if (!current)
|
|
443
|
+
throw new SpecStreamError(`No monitor ${id} on this account.`);
|
|
444
|
+
const changed = (await this.request("PATCH", `/v1/capacity/schedules/${encodeURIComponent(id)}`, { expected_version: current.version, state }, { abortSignal })) ?? {};
|
|
445
|
+
return monitorView(changed);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
const CADENCE_SECONDS = { hour: 3_600, day: 86_400, week: 604_800, month: 2_592_000 };
|
|
449
|
+
function requireId(monitorId) {
|
|
450
|
+
const id = (monitorId ?? "").trim();
|
|
451
|
+
if (!id)
|
|
452
|
+
throw new Error("Give the monitor_id.");
|
|
453
|
+
return id;
|
|
454
|
+
}
|
|
455
|
+
function optionalText(value) {
|
|
456
|
+
return typeof value === "string" && value ? value : null;
|
|
457
|
+
}
|
|
458
|
+
function monitorView(data) {
|
|
459
|
+
if (typeof data.schedule_id !== "string" || !data.schedule_id) {
|
|
460
|
+
throw new SpecStreamError("SpecStream returned a response this package couldn't read.");
|
|
461
|
+
}
|
|
462
|
+
const scope = isObject(data.scope) ? data.scope : {};
|
|
463
|
+
const listId = optionalText(scope.parent_find_id);
|
|
464
|
+
return {
|
|
465
|
+
status: "saved",
|
|
466
|
+
monitor_id: data.schedule_id,
|
|
467
|
+
list_id: listId,
|
|
468
|
+
state: String(data.state ?? ""),
|
|
469
|
+
every_seconds: Math.trunc(Number(data.cadence_seconds)) || 0,
|
|
470
|
+
next_run_at: optionalText(data.next_due_at),
|
|
471
|
+
last_run_at: optionalText(data.last_occurrence_at),
|
|
472
|
+
last_list_id: optionalText(data.last_find_id),
|
|
473
|
+
last_reason: optionalText(data.last_reason),
|
|
474
|
+
max_price_per_run_usd: (Math.trunc(Number(data.per_run_cents)) || 0) / 100,
|
|
475
|
+
max_price_per_month_usd: (Math.trunc(Number(data.monthly_maximum_cents ?? data.period_cents)) || 0) / 100,
|
|
476
|
+
valid_until: optionalText(data.valid_until),
|
|
477
|
+
version: Math.trunc(Number(data.version)) || 0,
|
|
478
|
+
list_link: listId ? listLink(listId) : null,
|
|
479
|
+
};
|
|
269
480
|
}
|
|
270
481
|
function isObject(value) {
|
|
271
482
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -282,3 +493,44 @@ function errorMessage(response, raw) {
|
|
|
282
493
|
const message = isObject(detail) ? detail.message : typeof detail === "string" ? detail : undefined;
|
|
283
494
|
return `SpecStream answered ${response.status}: ${message || response.statusText}`;
|
|
284
495
|
}
|
|
496
|
+
export const BROWSER_DEFAULT_TIMEOUT_SECONDS = 300;
|
|
497
|
+
export const BROWSER_DEFAULT_IDLE_SECONDS = 120;
|
|
498
|
+
const BROWSER_TOOL_NAME = /^browser_[a-z][a-z0-9_]{0,62}$/;
|
|
499
|
+
const SESSION_KEYS = ["status", "ended_reason", "live_url", "expires_at", "timeout_s", "seconds", "actions", "charged_usd", "price"];
|
|
500
|
+
function requireSessionId(sessionId) {
|
|
501
|
+
const id = String(sessionId ?? "").trim();
|
|
502
|
+
if (!id)
|
|
503
|
+
throw new Error("Pass the session_id that specstream_open_browser returned.");
|
|
504
|
+
return id;
|
|
505
|
+
}
|
|
506
|
+
function sessionView(session) {
|
|
507
|
+
const out = { session_id: String(session.id ?? "") };
|
|
508
|
+
for (const key of SESSION_KEYS)
|
|
509
|
+
if (session[key] !== undefined && session[key] !== null)
|
|
510
|
+
out[key] = session[key];
|
|
511
|
+
return out;
|
|
512
|
+
}
|
|
513
|
+
function stepView(sessionId, step) {
|
|
514
|
+
const out = { session_id: sessionId };
|
|
515
|
+
const texts = [];
|
|
516
|
+
const images = [];
|
|
517
|
+
for (const part of Array.isArray(step.result) ? step.result : []) {
|
|
518
|
+
if (!isObject(part))
|
|
519
|
+
continue;
|
|
520
|
+
if (part.type === "text" && typeof part.text === "string" && part.text)
|
|
521
|
+
texts.push(part.text);
|
|
522
|
+
else if (part.type === "image") {
|
|
523
|
+
images.push({ mime_type: typeof part.mime_type === "string" ? part.mime_type : null, base64_chars: typeof part.data === "string" ? part.data.length : 0 });
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
if (texts.length)
|
|
527
|
+
out.text = texts.join("\n\n");
|
|
528
|
+
if (images.length)
|
|
529
|
+
out.images = images;
|
|
530
|
+
for (const key of ["url", "title", "read_at", "price_usd"])
|
|
531
|
+
if (step[key] !== undefined && step[key] !== null)
|
|
532
|
+
out[key] = step[key];
|
|
533
|
+
if (isObject(step.error))
|
|
534
|
+
out.error = step.error;
|
|
535
|
+
return out;
|
|
536
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +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";
|
|
1
|
+
export { specstreamTools, specstreamBrowserTools, type SpecStreamToolsOptions, type SpecStreamBaseTools, type SpecStreamMonitorTools, type SpecStreamBrowserTools, type SpecStreamBrowserToolsOptions, } from "./tools.js";
|
|
2
|
+
export { SpecStreamClient, SpecStreamError, flattenRow, listLink, DEFAULT_BASE_URL, DEFAULT_WAIT_SECONDS, BROWSER_DEFAULT_TIMEOUT_SECONDS, BROWSER_DEFAULT_IDLE_SECONDS, USER_AGENT, type BrowserSessionView, type BrowserStepView, type FindListOptions, type FindListResult, type FoundList, type ListResults, type ListRow, type Monitor, type MonitorEvery, type MonitorListOptions, type MonitorListResult, type MonitorOverMaximum, type MonitorRun, type NeedsEdit, type OpenBrowserOptions, type OverMaximum, type SpecStreamClientOptions, } from "./client.js";
|
package/dist/index.js
CHANGED
|
@@ -1,2 +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";
|
|
1
|
+
export { specstreamTools, specstreamBrowserTools, } from "./tools.js";
|
|
2
|
+
export { SpecStreamClient, SpecStreamError, flattenRow, listLink, DEFAULT_BASE_URL, DEFAULT_WAIT_SECONDS, BROWSER_DEFAULT_TIMEOUT_SECONDS, BROWSER_DEFAULT_IDLE_SECONDS, USER_AGENT, } from "./client.js";
|