@isomorph.ai/app-sdk 1.38.1 → 1.40.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 CHANGED
@@ -397,9 +397,10 @@ const computerUse = createComputerUseTool({ runKey: ctx.runId ?? `my-job/${ctx.s
397
397
  ```
398
398
 
399
399
  - The tool calls the task API at `ISOMORPH_COMPUTER_USE_URL` (region `ISOMORPH_COMPUTER_USE_REGION`, default `us-east-1`); Provision sets both when the cell has the API. Each request is signed with SigV4 (`execute-api`) as the runtime's own role: the Lambda environment's credentials, or on a cluster pod its ServiceAccount role through STS `AssumeRoleWithWebIdentity`.
400
- - It starts the task with `POST /tasks`, then checks `POST /tasks/check` every 5 s until the task is `done` or `failed`.
400
+ - It starts the task with `POST /tasks`, then checks `POST /tasks/check` every 5 s until the task is `done`, `failed` or `waiting_for_input`. Waiting returns immediately; end the app job rather than holding a worker while a person signs in.
401
401
  - It calls `progress(step count, note)` on every new step and at least once a minute, so the job's lease does not run out.
402
402
  - When `cancelled()` turns true it sends `POST /tasks/cancel` once and keeps checking until the task has `failed`.
403
+ - While the task is `queued` and the CUA reports `waiting` (no computer is free), the progress note says so with the minutes waited. After `maxQueueMs` (20 minutes unless set) the tool cancels the task and returns `failed` with `No computer was free within N minutes; the task was cancelled before it started.`
403
404
  - One task record per `runKey`: a retried job run sends the same key and gets the queued, running or finished task back. Only a failed task starts a new attempt.
404
405
  - `finalUrl` is the page the browser ended on. A website's sign-in page there means a saved sign-in has expired: ask the person to sign in again.
405
406
 
@@ -407,13 +408,56 @@ Options the app passes, never the model:
407
408
 
408
409
  - `files`: PDFs the task may upload, at most five and 2 MiB in all.
409
410
  - `session`: the name of a runtime secret a sign-in was saved under (`finishSignIn`'s `saveAs`, below). The task starts signed in and can use only that sign-in's websites. When the task is `done` the refreshed session is saved back to the same secret. A missing one fails with `No saved sign-in named <name>.` Run one task per saved sign-in at a time: two tasks would both save back, and some websites sign out the older copy.
410
- - `secrets`: `{ name: value }`, at most 10, names `^[A-Za-z][A-Za-z0-9_-]{0,63}$`, values up to 4096 bytes. The computer types a value into a password field by its name; the model sees only the names. Never put a password or any other credential in the task text; pass it here and say "sign in with the `password` secret".
411
+ - `secrets`: `{ name: value }`, at most 10, names `^[A-Za-z][A-Za-z0-9_-]{0,63}$`, values up to 4096 bytes. The computer types a value into a password field by its name, and only there: it refuses to type a secret into a visible field, since the model reads the page after every step. The model sees only the names. Never put a password or any other credential in the task text; pass it here and say "sign in with the `password` secret". A user ID, customer ID or email is not a secret: give it in the task text.
412
+ - `maxQueueMs`: how long the task may wait for a free computer before the tool cancels it (20 minutes unless set).
411
413
  - `allowedHosts`: the websites (1 to 10 lower-case hostnames) a task with `secrets` and no `session` may use. A saved sign-in carries its own.
412
414
  - `onDownload({ name, contentType, size, blob })`: called once for each file a `done` task downloaded, one at a time, before the tool returns (at most 10 files, 100 MiB each). Store the `blob` yourself; the CUA keeps the files for a day at most. Without it nothing is fetched. A link that does not answer 200 fails the tool. The model only sees `downloads: [{ name, size }]`.
413
415
 
414
416
  A task with `session` or `secrets` works the page through clicks and typing only. `connectionId` is gone: pass `session`.
415
417
 
416
- (1.25.0, 1.36.0, 1.37.0; data plane ADR 0078, ADR 0090, ADR 0091)
418
+ (1.25.0, 1.36.0, 1.37.0, 1.39.0; data plane ADR 0078, ADR 0090, ADR 0091, ADR 0092)
419
+
420
+ ## Help on the task's existing computer
421
+
422
+ `dist/computer-use-handoff.js` adds short server calls for a paused task. It does not start another computer and does not import `ai`. It requires `runKey` and `authorize`, a server callback checked before **every** call. The callback must check the current authenticated person's access to the app's task row. An app-role signature, client-supplied task ID or pause ID alone does not prove that person owns the task.
423
+
424
+ ```text
425
+ Job's browser tool → waiting_for_input → job ends
426
+ │
427
+ App action → authorized screen/input or private login
428
+ │
429
+ User/app explicitly requests resume → new job attaches to original runKey
430
+ ```
431
+
432
+ The app keeps the original `runKey`, task ownership and returned pause metadata in its existing task row. Neither model nor browser chooses the backend `runKey`. For example, in an action backed by an app-owned `computer_tasks` table with `id`, `owner_id` and `run_key` columns:
433
+
434
+ ```ts
435
+ import { createClient } from '@isomorph.ai/app-sdk';
436
+ import { createComputerUseHandoff } from '@isomorph.ai/app-sdk/dist/computer-use-handoff.js';
437
+
438
+ export default async function viewComputer(input: { taskId: string; pauseId: string }, ctx: { user: { id: string } }) {
439
+ const app = createClient();
440
+ const owned = async () => (await app.data.from('computer_tasks').select('run_key')
441
+ .eq('id', input.taskId).eq('owner_id', ctx.user.id).single()).data;
442
+ const task = await owned();
443
+ if (!task) throw new Error('Unknown task.');
444
+ const computer = createComputerUseHandoff({ runKey: task.run_key, authorize: async () => Boolean(await owned()) });
445
+ return computer.view(input.pauseId);
446
+ }
447
+ ```
448
+
449
+ Keep that table protected by the app's user row rules. A trusted action must still check `owner_id` against `ctx.user.id`; never use workload identity as proof of human ownership.
450
+
451
+ - `requestTakeover(reason, requiredInput?)` requests a pause; `requiredInput` is `human` (default) or `login`. Poll `check()` until `waiting_for_input` gives `taskId`, `pauseId`, `reason`, `requiredInput` and optional login result.
452
+ - `view(pauseId)` returns `{status:'pausing'}` or `{status:'ready', screenshot, url}`. Reuse the existing sign-in screenshot UI: display the base64 PNG as an image, map clicks to image pixels, and forward keyboard/scroll events through app actions. Viewing does not itself resume the agent.
453
+ - `input(pauseId, action)` sends the same `SignInAction` click/type/key/scroll commands used by `sendSignInInput`. The CUA accepts human input only while the task is paused; it blocks the helper and main agent from acting at the same time.
454
+ - `completeLogin(pauseId, {allowedHosts, username, password})`, or `completeLogin(pauseId, {otp})`, queues the separate browser-action-only login agent on this computer. **Call only from private server code, never expose this method or credentials as model tool inputs, prompts, progress, logs or job input/results.** Poll `check()` for `login.status: success | needs_input | human_help_needed`, with `input:'otp'` when another code is needed. Helper success leaves the main agent paused.
455
+ - `resume(pauseId)` explicitly resumes; it does not wait for completion. On Continue, call this from the authorized app action, then enqueue the app's continuation job. That job creates `createComputerUseTool({...jobOptions, runKey: originalRunKey, attach:true})`: it polls the same task without sending `/tasks` again. Keep the original saved-session and download options if needed. Stale/duplicate resumes fail with 409; do not silently retry with a new pause ID. If enqueue fails, retry attaching to the already resumed task, not another resume.
456
+ - `cancel()` stops the task, including while waiting.
457
+
458
+ The outer agent may use app-defined tools for takeover and opening the authorized view. Resume requires an explicit user or app decision. Keep any outer-agent conversation in the app's existing job/task storage when ending a waiting job; this SDK does not persist the outer model's messages. The CUA persists its own conversation/resume state under the same task folder as screenshots and progress in its existing result bucket, without passwords or OTPs.
459
+
460
+ P0 `getSavedLogin(accountRef, website)` and `getOtp(taskId, website)` return `{status:'unavailable'}` and call no integration. Use human takeover when no approved backend input is supplied. Governance saved-login/website storage and email/SMS OTP lookup are P0.5, not part of this SDK change. These task helpers require the matching CUA handoff release; existing new-computer sign-in helpers below remain separate.
417
461
 
418
462
  ## Browser sign-in for computer use
419
463
 
@@ -431,7 +475,7 @@ await sendSignInInput(handle, { op: 'click', x: 640, y: 400 });
431
475
  await finishSignIn(handle, { saveAs: `vendor-central/${ctx.user.id}` }); // { url }
432
476
  ```
433
477
 
434
- - `startSignIn` starts a computer that may open only `allowedHosts` and returns an opaque handle for the calls that follow; the computer answers only this app's role and stops after 30 minutes.
478
+ - `startSignIn` starts a computer that may open only `allowedHosts` and returns an opaque handle for the calls that follow; the computer answers only this app's role and stops after 30 minutes. It opens `startUrl`, an HTTPS page on one of those websites, or the first website's front page: an account on `accounts.zoho.in` lists that host first or passes it as `startUrl`.
435
479
  - `showSignIn` gives `{ status: 'starting' }` until the browser is up, then `{ status: 'ready', screenshot, url }`: a base64 PNG of the 1280×800 screen and the page's address.
436
480
  - `sendSignInInput` takes `{ op: 'click', x, y }` (screen pixels), `{ op: 'typeText', value }` (up to 512 characters), `{ op: 'pressKey', key }` (such as `Enter` or `Tab`) or `{ op: 'scroll', direction: 'up' | 'down' }`.
437
481
  - `finishSignIn` saves the session (cookies and site storage of the allowed websites, at most 60 KB) as the runtime secret `saveAs`, stops the computer and returns the page it was on. App code never holds the cookies.
@@ -652,3 +696,61 @@ keep the workflow run ID and tool-call ID stable across retries. Direct writes
652
696
  must supply their own persisted UUID `idempotencyKey`. A tool marked read-only
653
697
  does not require a key. An incomplete replay requires reconciliation, not a new
654
698
  write. Account consent and app permissions are enforced by the platform.
699
+
700
+ ### Tools for the outer app agent
701
+
702
+ `createComputerUseHandoffTools` from `dist/computer-use-handoff-tool.js` creates
703
+ `request_computer_input` and `resume_computer_task`. Register these beside the
704
+ existing computer-use tool. Bind them to the original task's `runKey` in server
705
+ code; the model supplies only the current `pauseId`.
706
+
707
+ ```ts
708
+ import { generateText, hasToolCall, stepCountIs } from 'ai';
709
+ import { createComputerUseHandoffTools } from '@isomorph.ai/app-sdk/dist/computer-use-handoff-tool.js';
710
+
711
+ const handoffTools = createComputerUseHandoffTools({
712
+ runKey: task.run_key,
713
+ progress: ctx.progress,
714
+ cancelled: ctx.cancelled,
715
+ authorize: () => userOwnsTask(ctx.user.id, task.id),
716
+ onInputRequired: (pause, page) => showComputerInApp(task.id, pause, page),
717
+ canResume: pauseId => userPressedContinue(ctx.user.id, task.id, pauseId),
718
+ });
719
+ const result = await generateText({
720
+ model,
721
+ messages: savedMessages,
722
+ tools: { computer_use: computerUse, ...handoffTools },
723
+ stopWhen: [stepCountIs(10), hasToolCall('request_computer_input')],
724
+ });
725
+ await saveOuterMessages(task.id, [...savedMessages, ...result.response.messages]);
726
+ ```
727
+
728
+ The ownership, screen, Continue and conversation functions in this example are
729
+ app-provided functions, not SDK exports. The app must save the completed tool
730
+ result before returning its waiting response to the UI. The stop condition ends
731
+ the outer loop after the input request; creating tools alone does not stop a loop.
732
+
733
+ The request tool checks the current pause and calls `view()`. Its callback receives
734
+ the screenshot privately, so the app can show its existing computer view. The
735
+ model receives `human_input_required`, task/pause references, reason and required
736
+ input, without screenshot bytes or a computer endpoint. Screen refreshes and human
737
+ input still use authorized backend `view()` and `input()` calls.
738
+
739
+ When the human presses Continue, the app records approval for that user, task and
740
+ pause and queues its outer-agent continuation with the saved conversation and
741
+ original run key. Only this trusted user action may make `canResume` return true;
742
+ never derive approval from model arguments or a chat string. Retain that approval
743
+ for retries of the same continuation. A new pause needs new approval. The resume
744
+ tool checks approval, calls resume and follows the existing task with `attach:true`.
745
+ If an earlier attempt already resumed the task, it attaches without resuming twice.
746
+ It may return another waiting result; use the input tool again for that new pause.
747
+ Credentials and OTPs remain private backend `completeLogin()` inputs, not model tools.
748
+
749
+ `onMessage` on the computer-use tool receives allowlisted CUA progress/handoff
750
+ messages when they change; the progress callback also receives their text. Waiting
751
+ results and handoff `check()` preserve the latest valid `message`. This is latest
752
+ message delivery, not a full message history.
753
+
754
+ This SDK does not supply an app-specific screen, conversation database or job
755
+ scheduler. It supplies the tools and waiting contract; the example wires them to
756
+ an app's existing actions, task rows, screen and job runner.
@@ -0,0 +1,590 @@
1
+ import { type ComputerUseHandoffOptions, type ComputerUsePage, type ComputerUseWaiting } from './computer-use-handoff.js';
2
+ import { type ComputerUseOptions } from './computer-use.js';
3
+ export interface ComputerUseHandoffToolOptions extends ComputerUseHandoffOptions, ComputerUseOptions {
4
+ onInputRequired(input: ComputerUseWaiting, page: ComputerUsePage): Promise<void> | void;
5
+ canResume(pauseId: string): Promise<boolean> | boolean;
6
+ }
7
+ export declare function createComputerUseHandoffTools(options: ComputerUseHandoffToolOptions): {
8
+ request_computer_input: ({
9
+ deferLoading?: boolean;
10
+ title?: string;
11
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
12
+ metadata?: import("@ai-sdk/provider").JSONObject;
13
+ inputSchema: import("ai").FlexibleSchema<{
14
+ pauseId: string;
15
+ }>;
16
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
17
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
18
+ pauseId: string;
19
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
20
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
21
+ onInputDelta?: ((options: {
22
+ inputTextDelta: string;
23
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
24
+ onInputAvailable?: ((options: {
25
+ input: {
26
+ pauseId: string;
27
+ };
28
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
29
+ toModelOutput?: ((options: {
30
+ toolCallId: string;
31
+ input: {
32
+ pauseId: string;
33
+ };
34
+ output: NoInfer<{
35
+ status: "human_input_required";
36
+ taskId: string;
37
+ pauseId: string;
38
+ reason: string;
39
+ requiredInput: "login" | "otp" | "human";
40
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
41
+ login?: {
42
+ status: "success" | "needs_input" | "human_help_needed";
43
+ input?: "otp";
44
+ };
45
+ }>;
46
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
47
+ } & {
48
+ outputSchema?: import("ai").FlexibleSchema<{
49
+ status: "human_input_required";
50
+ taskId: string;
51
+ pauseId: string;
52
+ reason: string;
53
+ requiredInput: "login" | "otp" | "human";
54
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
55
+ login?: {
56
+ status: "success" | "needs_input" | "human_help_needed";
57
+ input?: "otp";
58
+ };
59
+ }> | undefined;
60
+ execute: import("ai").ToolExecuteFunction<{
61
+ pauseId: string;
62
+ }, {
63
+ status: "human_input_required";
64
+ taskId: string;
65
+ pauseId: string;
66
+ reason: string;
67
+ requiredInput: "login" | "otp" | "human";
68
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
69
+ login?: {
70
+ status: "success" | "needs_input" | "human_help_needed";
71
+ input?: "otp";
72
+ };
73
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>>;
74
+ } & {
75
+ description?: string | ((options: {
76
+ context: NoInfer<import("@ai-sdk/provider-utils").Context>;
77
+ experimental_sandbox?: import("ai").Experimental_SandboxSession;
78
+ }) => string) | undefined;
79
+ strict?: boolean;
80
+ inputExamples?: {
81
+ input: NoInfer<{
82
+ pauseId: string;
83
+ }>;
84
+ }[] | undefined;
85
+ id?: never;
86
+ isProviderExecuted?: never;
87
+ args?: never;
88
+ supportsDeferredResults?: never;
89
+ } & {
90
+ type?: undefined | "function";
91
+ } & {
92
+ execute: import("ai").ToolExecuteFunction<{
93
+ pauseId: string;
94
+ }, {
95
+ status: "human_input_required";
96
+ taskId: string;
97
+ pauseId: string;
98
+ reason: string;
99
+ requiredInput: "login" | "otp" | "human";
100
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
101
+ login?: {
102
+ status: "success" | "needs_input" | "human_help_needed";
103
+ input?: "otp";
104
+ };
105
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>>;
106
+ }) | ({
107
+ deferLoading?: boolean;
108
+ title?: string;
109
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
110
+ metadata?: import("@ai-sdk/provider").JSONObject;
111
+ inputSchema: import("ai").FlexibleSchema<{
112
+ pauseId: string;
113
+ }>;
114
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
115
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
116
+ pauseId: string;
117
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
118
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
119
+ onInputDelta?: ((options: {
120
+ inputTextDelta: string;
121
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
122
+ onInputAvailable?: ((options: {
123
+ input: {
124
+ pauseId: string;
125
+ };
126
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
127
+ toModelOutput?: ((options: {
128
+ toolCallId: string;
129
+ input: {
130
+ pauseId: string;
131
+ };
132
+ output: NoInfer<{
133
+ status: "human_input_required";
134
+ taskId: string;
135
+ pauseId: string;
136
+ reason: string;
137
+ requiredInput: "login" | "otp" | "human";
138
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
139
+ login?: {
140
+ status: "success" | "needs_input" | "human_help_needed";
141
+ input?: "otp";
142
+ };
143
+ }>;
144
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
145
+ } & {
146
+ outputSchema?: import("ai").FlexibleSchema<{
147
+ status: "human_input_required";
148
+ taskId: string;
149
+ pauseId: string;
150
+ reason: string;
151
+ requiredInput: "login" | "otp" | "human";
152
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
153
+ login?: {
154
+ status: "success" | "needs_input" | "human_help_needed";
155
+ input?: "otp";
156
+ };
157
+ }> | undefined;
158
+ execute: import("ai").ToolExecuteFunction<{
159
+ pauseId: string;
160
+ }, {
161
+ status: "human_input_required";
162
+ taskId: string;
163
+ pauseId: string;
164
+ reason: string;
165
+ requiredInput: "login" | "otp" | "human";
166
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
167
+ login?: {
168
+ status: "success" | "needs_input" | "human_help_needed";
169
+ input?: "otp";
170
+ };
171
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>>;
172
+ } & {
173
+ description?: string | ((options: {
174
+ context: NoInfer<import("@ai-sdk/provider-utils").Context>;
175
+ experimental_sandbox?: import("ai").Experimental_SandboxSession;
176
+ }) => string) | undefined;
177
+ strict?: boolean;
178
+ inputExamples?: {
179
+ input: NoInfer<{
180
+ pauseId: string;
181
+ }>;
182
+ }[] | undefined;
183
+ id?: never;
184
+ isProviderExecuted?: never;
185
+ args?: never;
186
+ supportsDeferredResults?: never;
187
+ } & {
188
+ type: "dynamic";
189
+ } & {
190
+ execute: import("ai").ToolExecuteFunction<{
191
+ pauseId: string;
192
+ }, {
193
+ status: "human_input_required";
194
+ taskId: string;
195
+ pauseId: string;
196
+ reason: string;
197
+ requiredInput: "login" | "otp" | "human";
198
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
199
+ login?: {
200
+ status: "success" | "needs_input" | "human_help_needed";
201
+ input?: "otp";
202
+ };
203
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>>;
204
+ }) | ({
205
+ deferLoading?: boolean;
206
+ title?: string;
207
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
208
+ metadata?: import("@ai-sdk/provider").JSONObject;
209
+ inputSchema: import("ai").FlexibleSchema<{
210
+ pauseId: string;
211
+ }>;
212
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
213
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
214
+ pauseId: string;
215
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
216
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
217
+ onInputDelta?: ((options: {
218
+ inputTextDelta: string;
219
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
220
+ onInputAvailable?: ((options: {
221
+ input: {
222
+ pauseId: string;
223
+ };
224
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
225
+ toModelOutput?: ((options: {
226
+ toolCallId: string;
227
+ input: {
228
+ pauseId: string;
229
+ };
230
+ output: NoInfer<{
231
+ status: "human_input_required";
232
+ taskId: string;
233
+ pauseId: string;
234
+ reason: string;
235
+ requiredInput: "login" | "otp" | "human";
236
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
237
+ login?: {
238
+ status: "success" | "needs_input" | "human_help_needed";
239
+ input?: "otp";
240
+ };
241
+ }>;
242
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
243
+ } & {
244
+ outputSchema?: import("ai").FlexibleSchema<{
245
+ status: "human_input_required";
246
+ taskId: string;
247
+ pauseId: string;
248
+ reason: string;
249
+ requiredInput: "login" | "otp" | "human";
250
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
251
+ login?: {
252
+ status: "success" | "needs_input" | "human_help_needed";
253
+ input?: "otp";
254
+ };
255
+ }> | undefined;
256
+ execute: import("ai").ToolExecuteFunction<{
257
+ pauseId: string;
258
+ }, {
259
+ status: "human_input_required";
260
+ taskId: string;
261
+ pauseId: string;
262
+ reason: string;
263
+ requiredInput: "login" | "otp" | "human";
264
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
265
+ login?: {
266
+ status: "success" | "needs_input" | "human_help_needed";
267
+ input?: "otp";
268
+ };
269
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>>;
270
+ } & {
271
+ type: "provider";
272
+ id: `${string}.${string}`;
273
+ args: Record<string, unknown>;
274
+ description?: never;
275
+ strict?: never;
276
+ inputExamples?: never;
277
+ } & {
278
+ isProviderExecuted: false;
279
+ supportsDeferredResults?: never;
280
+ } & {
281
+ execute: import("ai").ToolExecuteFunction<{
282
+ pauseId: string;
283
+ }, {
284
+ status: "human_input_required";
285
+ taskId: string;
286
+ pauseId: string;
287
+ reason: string;
288
+ requiredInput: "login" | "otp" | "human";
289
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
290
+ login?: {
291
+ status: "success" | "needs_input" | "human_help_needed";
292
+ input?: "otp";
293
+ };
294
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>>;
295
+ }) | ({
296
+ deferLoading?: boolean;
297
+ title?: string;
298
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
299
+ metadata?: import("@ai-sdk/provider").JSONObject;
300
+ inputSchema: import("ai").FlexibleSchema<{
301
+ pauseId: string;
302
+ }>;
303
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
304
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
305
+ pauseId: string;
306
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
307
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
308
+ onInputDelta?: ((options: {
309
+ inputTextDelta: string;
310
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
311
+ onInputAvailable?: ((options: {
312
+ input: {
313
+ pauseId: string;
314
+ };
315
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
316
+ toModelOutput?: ((options: {
317
+ toolCallId: string;
318
+ input: {
319
+ pauseId: string;
320
+ };
321
+ output: NoInfer<{
322
+ status: "human_input_required";
323
+ taskId: string;
324
+ pauseId: string;
325
+ reason: string;
326
+ requiredInput: "login" | "otp" | "human";
327
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
328
+ login?: {
329
+ status: "success" | "needs_input" | "human_help_needed";
330
+ input?: "otp";
331
+ };
332
+ }>;
333
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
334
+ } & {
335
+ outputSchema?: import("ai").FlexibleSchema<{
336
+ status: "human_input_required";
337
+ taskId: string;
338
+ pauseId: string;
339
+ reason: string;
340
+ requiredInput: "login" | "otp" | "human";
341
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
342
+ login?: {
343
+ status: "success" | "needs_input" | "human_help_needed";
344
+ input?: "otp";
345
+ };
346
+ }> | undefined;
347
+ execute: import("ai").ToolExecuteFunction<{
348
+ pauseId: string;
349
+ }, {
350
+ status: "human_input_required";
351
+ taskId: string;
352
+ pauseId: string;
353
+ reason: string;
354
+ requiredInput: "login" | "otp" | "human";
355
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
356
+ login?: {
357
+ status: "success" | "needs_input" | "human_help_needed";
358
+ input?: "otp";
359
+ };
360
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>>;
361
+ } & {
362
+ type: "provider";
363
+ id: `${string}.${string}`;
364
+ args: Record<string, unknown>;
365
+ description?: never;
366
+ strict?: never;
367
+ inputExamples?: never;
368
+ } & {
369
+ isProviderExecuted: true;
370
+ supportsDeferredResults?: boolean;
371
+ } & {
372
+ execute: import("ai").ToolExecuteFunction<{
373
+ pauseId: string;
374
+ }, {
375
+ status: "human_input_required";
376
+ taskId: string;
377
+ pauseId: string;
378
+ reason: string;
379
+ requiredInput: "login" | "otp" | "human";
380
+ message?: import("./computer-use-handoff.js").ComputerUseMessage;
381
+ login?: {
382
+ status: "success" | "needs_input" | "human_help_needed";
383
+ input?: "otp";
384
+ };
385
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>>;
386
+ });
387
+ resume_computer_task: ({
388
+ deferLoading?: boolean;
389
+ title?: string;
390
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
391
+ metadata?: import("@ai-sdk/provider").JSONObject;
392
+ inputSchema: import("ai").FlexibleSchema<{
393
+ pauseId: string;
394
+ }>;
395
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
396
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
397
+ pauseId: string;
398
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
399
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
400
+ onInputDelta?: ((options: {
401
+ inputTextDelta: string;
402
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
403
+ onInputAvailable?: ((options: {
404
+ input: {
405
+ pauseId: string;
406
+ };
407
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
408
+ toModelOutput?: ((options: {
409
+ toolCallId: string;
410
+ input: {
411
+ pauseId: string;
412
+ };
413
+ output: NoInfer<import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>>;
414
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
415
+ } & {
416
+ outputSchema?: import("ai").FlexibleSchema<import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>> | undefined;
417
+ execute: import("ai").ToolExecuteFunction<{
418
+ pauseId: string;
419
+ }, import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>, NoInfer<import("@ai-sdk/provider-utils").Context>>;
420
+ } & {
421
+ description?: string | ((options: {
422
+ context: NoInfer<import("@ai-sdk/provider-utils").Context>;
423
+ experimental_sandbox?: import("ai").Experimental_SandboxSession;
424
+ }) => string) | undefined;
425
+ strict?: boolean;
426
+ inputExamples?: {
427
+ input: NoInfer<{
428
+ pauseId: string;
429
+ }>;
430
+ }[] | undefined;
431
+ id?: never;
432
+ isProviderExecuted?: never;
433
+ args?: never;
434
+ supportsDeferredResults?: never;
435
+ } & {
436
+ type?: undefined | "function";
437
+ } & {
438
+ execute: import("ai").ToolExecuteFunction<{
439
+ pauseId: string;
440
+ }, import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>, NoInfer<import("@ai-sdk/provider-utils").Context>>;
441
+ }) | ({
442
+ deferLoading?: boolean;
443
+ title?: string;
444
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
445
+ metadata?: import("@ai-sdk/provider").JSONObject;
446
+ inputSchema: import("ai").FlexibleSchema<{
447
+ pauseId: string;
448
+ }>;
449
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
450
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
451
+ pauseId: string;
452
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
453
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
454
+ onInputDelta?: ((options: {
455
+ inputTextDelta: string;
456
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
457
+ onInputAvailable?: ((options: {
458
+ input: {
459
+ pauseId: string;
460
+ };
461
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
462
+ toModelOutput?: ((options: {
463
+ toolCallId: string;
464
+ input: {
465
+ pauseId: string;
466
+ };
467
+ output: NoInfer<import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>>;
468
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
469
+ } & {
470
+ outputSchema?: import("ai").FlexibleSchema<import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>> | undefined;
471
+ execute: import("ai").ToolExecuteFunction<{
472
+ pauseId: string;
473
+ }, import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>, NoInfer<import("@ai-sdk/provider-utils").Context>>;
474
+ } & {
475
+ description?: string | ((options: {
476
+ context: NoInfer<import("@ai-sdk/provider-utils").Context>;
477
+ experimental_sandbox?: import("ai").Experimental_SandboxSession;
478
+ }) => string) | undefined;
479
+ strict?: boolean;
480
+ inputExamples?: {
481
+ input: NoInfer<{
482
+ pauseId: string;
483
+ }>;
484
+ }[] | undefined;
485
+ id?: never;
486
+ isProviderExecuted?: never;
487
+ args?: never;
488
+ supportsDeferredResults?: never;
489
+ } & {
490
+ type: "dynamic";
491
+ } & {
492
+ execute: import("ai").ToolExecuteFunction<{
493
+ pauseId: string;
494
+ }, import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>, NoInfer<import("@ai-sdk/provider-utils").Context>>;
495
+ }) | ({
496
+ deferLoading?: boolean;
497
+ title?: string;
498
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
499
+ metadata?: import("@ai-sdk/provider").JSONObject;
500
+ inputSchema: import("ai").FlexibleSchema<{
501
+ pauseId: string;
502
+ }>;
503
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
504
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
505
+ pauseId: string;
506
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
507
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
508
+ onInputDelta?: ((options: {
509
+ inputTextDelta: string;
510
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
511
+ onInputAvailable?: ((options: {
512
+ input: {
513
+ pauseId: string;
514
+ };
515
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
516
+ toModelOutput?: ((options: {
517
+ toolCallId: string;
518
+ input: {
519
+ pauseId: string;
520
+ };
521
+ output: NoInfer<import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>>;
522
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
523
+ } & {
524
+ outputSchema?: import("ai").FlexibleSchema<import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>> | undefined;
525
+ execute: import("ai").ToolExecuteFunction<{
526
+ pauseId: string;
527
+ }, import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>, NoInfer<import("@ai-sdk/provider-utils").Context>>;
528
+ } & {
529
+ type: "provider";
530
+ id: `${string}.${string}`;
531
+ args: Record<string, unknown>;
532
+ description?: never;
533
+ strict?: never;
534
+ inputExamples?: never;
535
+ } & {
536
+ isProviderExecuted: false;
537
+ supportsDeferredResults?: never;
538
+ } & {
539
+ execute: import("ai").ToolExecuteFunction<{
540
+ pauseId: string;
541
+ }, import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>, NoInfer<import("@ai-sdk/provider-utils").Context>>;
542
+ }) | ({
543
+ deferLoading?: boolean;
544
+ title?: string;
545
+ providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
546
+ metadata?: import("@ai-sdk/provider").JSONObject;
547
+ inputSchema: import("ai").FlexibleSchema<{
548
+ pauseId: string;
549
+ }>;
550
+ contextSchema?: import("ai").FlexibleSchema<import("@ai-sdk/provider-utils").Context> | undefined;
551
+ needsApproval?: boolean | import("@ai-sdk/provider-utils").ToolNeedsApprovalFunction<{
552
+ pauseId: string;
553
+ }, NoInfer<import("@ai-sdk/provider-utils").Context>> | undefined;
554
+ onInputStart?: ((options: import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
555
+ onInputDelta?: ((options: {
556
+ inputTextDelta: string;
557
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
558
+ onInputAvailable?: ((options: {
559
+ input: {
560
+ pauseId: string;
561
+ };
562
+ } & import("ai").ToolExecutionOptions<NoInfer<import("@ai-sdk/provider-utils").Context>>) => void | PromiseLike<void>) | undefined;
563
+ toModelOutput?: ((options: {
564
+ toolCallId: string;
565
+ input: {
566
+ pauseId: string;
567
+ };
568
+ output: NoInfer<import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>>;
569
+ }) => import("@ai-sdk/provider-utils").ToolResultOutput | PromiseLike<import("@ai-sdk/provider-utils").ToolResultOutput>) | undefined;
570
+ } & {
571
+ outputSchema?: import("ai").FlexibleSchema<import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>> | undefined;
572
+ execute: import("ai").ToolExecuteFunction<{
573
+ pauseId: string;
574
+ }, import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>, NoInfer<import("@ai-sdk/provider-utils").Context>>;
575
+ } & {
576
+ type: "provider";
577
+ id: `${string}.${string}`;
578
+ args: Record<string, unknown>;
579
+ description?: never;
580
+ strict?: never;
581
+ inputExamples?: never;
582
+ } & {
583
+ isProviderExecuted: true;
584
+ supportsDeferredResults?: boolean;
585
+ } & {
586
+ execute: import("ai").ToolExecuteFunction<{
587
+ pauseId: string;
588
+ }, import("./computer-use.js").ComputerUseResult | AsyncIterable<import("./computer-use.js").ComputerUseResult>, NoInfer<import("@ai-sdk/provider-utils").Context>>;
589
+ });
590
+ };
@@ -0,0 +1,45 @@
1
+ import { jsonSchema, tool } from 'ai';
2
+ import { createComputerUseHandoff } from './computer-use-handoff.js';
3
+ import { createComputerUseTool } from './computer-use.js';
4
+ export function createComputerUseHandoffTools(options) {
5
+ if (typeof options.onInputRequired !== 'function' || typeof options.canResume !== 'function') {
6
+ throw new Error('Computer use handoff tools need onInputRequired and canResume callbacks.');
7
+ }
8
+ const handoff = createComputerUseHandoff(options);
9
+ const schema = jsonSchema({
10
+ type: 'object', properties: { pauseId: { type: 'string', minLength: 1 } }, required: ['pauseId'], additionalProperties: false,
11
+ });
12
+ return {
13
+ request_computer_input: tool({
14
+ description: 'Show the paused task computer to the user and request outside input. Use the current pauseId from the computer-use result. This returns human_input_required: end this agent turn and wait for the user. Never ask for passwords or one-time codes in chat.',
15
+ inputSchema: schema,
16
+ execute: async ({ pauseId }) => {
17
+ const input = await handoff.check();
18
+ if (input.status !== 'waiting_for_input' || !('pauseId' in input) || input.pauseId !== pauseId)
19
+ throw new Error('The task is not waiting at this pause.');
20
+ const page = await handoff.view(pauseId);
21
+ await options.onInputRequired(input, page);
22
+ return { ...input, status: 'human_input_required' };
23
+ },
24
+ }),
25
+ resume_computer_task: tool({
26
+ description: 'Resume the original computer-use task only after the user has supplied input and explicitly pressed Continue. Server approval is required. Follow that same task until it finishes or needs more input; never start a new task.',
27
+ inputSchema: schema,
28
+ execute: async ({ pauseId }, execution) => {
29
+ const current = await handoff.check();
30
+ if (await options.canResume(pauseId) !== true)
31
+ throw new Error('The user has not approved continuing this pause.');
32
+ if (current.status === 'waiting_for_input') {
33
+ if (!('pauseId' in current) || current.pauseId !== pauseId)
34
+ throw new Error('The task is waiting at a different pause.');
35
+ await handoff.resume(pauseId);
36
+ }
37
+ else if (!['resume_starting', 'resume_queued', 'resuming', 'running', 'done', 'failed'].includes(current.status)) {
38
+ throw new Error('The task cannot continue in its current state.');
39
+ }
40
+ const follow = createComputerUseTool({ ...options, attach: true });
41
+ return follow.execute({ task: 'Continue the original task.' }, execution);
42
+ },
43
+ }),
44
+ };
45
+ }
@@ -0,0 +1,78 @@
1
+ import { type ComputerUseTransport } from './computer-use-api.js';
2
+ import type { SignInAction } from './computer-use-sign-in.js';
3
+ export interface ComputerUseMessage {
4
+ type: 'progress' | 'handoff';
5
+ text: string;
6
+ required_input?: 'login' | 'human';
7
+ }
8
+ export declare function computerUseMessage(value: unknown): ComputerUseMessage | undefined;
9
+ export interface ComputerUseWaiting {
10
+ status: 'waiting_for_input';
11
+ taskId: string;
12
+ pauseId: string;
13
+ reason: string;
14
+ requiredInput: 'login' | 'otp' | 'human';
15
+ message?: ComputerUseMessage;
16
+ login?: {
17
+ status: 'success' | 'needs_input' | 'human_help_needed';
18
+ input?: 'otp';
19
+ };
20
+ }
21
+ export declare function waitingInput(answer: {
22
+ taskId?: unknown;
23
+ pauseId?: unknown;
24
+ reason?: unknown;
25
+ requiredInput?: unknown;
26
+ login?: unknown;
27
+ message?: unknown;
28
+ }): ComputerUseWaiting;
29
+ export type ComputerUsePage = {
30
+ status: 'pausing';
31
+ } | {
32
+ status: 'ready';
33
+ screenshot: string;
34
+ url: string;
35
+ };
36
+ export type ComputerUseLoginInput = {
37
+ allowedHosts: readonly string[];
38
+ username: string;
39
+ password: string;
40
+ otp?: never;
41
+ } | {
42
+ otp: string;
43
+ allowedHosts?: never;
44
+ username?: never;
45
+ password?: never;
46
+ };
47
+ export interface ComputerUseHandoffOptions extends ComputerUseTransport {
48
+ runKey: string;
49
+ authorize(): Promise<boolean> | boolean;
50
+ }
51
+ export declare function createComputerUseHandoff(options: ComputerUseHandoffOptions): {
52
+ requestTakeover(reason: string, requiredInput?: "login" | "human"): Promise<{
53
+ status: string;
54
+ }>;
55
+ view(pauseId: string): Promise<ComputerUsePage>;
56
+ input(pauseId: string, action: SignInAction): Promise<{
57
+ status: "accepted";
58
+ }>;
59
+ completeLogin(pauseId: string, input: ComputerUseLoginInput): Promise<{
60
+ status: "login_queued";
61
+ }>;
62
+ check(): Promise<ComputerUseWaiting | {
63
+ message?: ComputerUseMessage | undefined;
64
+ status: string;
65
+ }>;
66
+ resume(pauseId: string): Promise<{
67
+ status: "resume_queued";
68
+ }>;
69
+ cancel(): Promise<{
70
+ status: string;
71
+ }>;
72
+ };
73
+ export declare function getSavedLogin(_accountRef: string, _website: string): Promise<{
74
+ status: 'unavailable';
75
+ }>;
76
+ export declare function getOtp(_taskId: string, _website: string): Promise<{
77
+ status: 'unavailable';
78
+ }>;
@@ -0,0 +1,109 @@
1
+ import { allowedHostsOf, computerUseApi, refused } from './computer-use-api.js';
2
+ export function computerUseMessage(value) {
3
+ if (!value || typeof value !== 'object')
4
+ return undefined;
5
+ const message = value;
6
+ if (!['progress', 'handoff'].includes(message.type) || typeof message.text !== 'string' || !message.text.trim() || message.text.length > 500)
7
+ return undefined;
8
+ return { type: message.type, text: message.text,
9
+ ...(message.type === 'handoff' && ['login', 'human'].includes(message.required_input ?? '') ? { required_input: message.required_input } : {}) };
10
+ }
11
+ export function waitingInput(answer) {
12
+ if (typeof answer.taskId !== 'string' || !answer.taskId || typeof answer.pauseId !== 'string' || !answer.pauseId
13
+ || !['login', 'otp', 'human'].includes(String(answer.requiredInput)))
14
+ throw new Error('The computer use API returned an incomplete pause.');
15
+ const result = {
16
+ status: 'waiting_for_input', taskId: answer.taskId, pauseId: answer.pauseId,
17
+ reason: typeof answer.reason === 'string' ? answer.reason : 'Outside input needed.',
18
+ requiredInput: answer.requiredInput,
19
+ };
20
+ const message = computerUseMessage(answer.message);
21
+ if (message)
22
+ result.message = message;
23
+ const login = answer.login;
24
+ if (login && ['success', 'needs_input', 'human_help_needed'].includes(login.status)) {
25
+ result.login = { status: login.status, ...(login.input === 'otp' ? { input: 'otp' } : {}) };
26
+ }
27
+ return result;
28
+ }
29
+ export function createComputerUseHandoff(options) {
30
+ if (typeof options.runKey !== 'string' || !options.runKey || typeof options.authorize !== 'function')
31
+ throw new Error('Computer use handoff needs runKey and an authorize check for the current user.');
32
+ const api = computerUseApi(options);
33
+ const post = async (path, body = {}, privateInput = false) => {
34
+ if (await options.authorize() !== true)
35
+ throw new Error('You cannot access this computer use task.');
36
+ let answer;
37
+ try {
38
+ answer = await api.call(path, { run_key: options.runKey, ...body });
39
+ }
40
+ catch (error) {
41
+ if (privateInput)
42
+ throw new Error('The computer use login request could not be completed.');
43
+ throw error;
44
+ }
45
+ if (answer.status !== 200)
46
+ throw refused(path, answer.status, privateInput ? undefined : answer.body);
47
+ return answer.body;
48
+ };
49
+ const paused = (pauseId) => {
50
+ if (!pauseId || typeof pauseId !== 'string')
51
+ throw new Error('Computer use handoff needs the current pauseId.');
52
+ return { pauseId };
53
+ };
54
+ return {
55
+ requestTakeover(reason, requiredInput = 'human') {
56
+ if (!reason.trim() || !['login', 'human'].includes(requiredInput))
57
+ throw new Error('Takeover needs a reason and login or human input.');
58
+ return post('/tasks/takeover', { reason, requiredInput });
59
+ },
60
+ async view(pauseId) {
61
+ const page = await post('/tasks/view', paused(pauseId));
62
+ if (page.status === 'pausing')
63
+ return { status: 'pausing' };
64
+ if (page.status !== 'ready' || typeof page.screenshot !== 'string' || typeof page.url !== 'string')
65
+ throw new Error('The computer use API returned an incomplete screen.');
66
+ return { status: 'ready', screenshot: page.screenshot, url: page.url };
67
+ },
68
+ input(pauseId, action) {
69
+ return post('/tasks/input', { ...paused(pauseId), action });
70
+ },
71
+ completeLogin(pauseId, input) {
72
+ let body;
73
+ if ('otp' in input && input.otp !== undefined) {
74
+ if (Object.keys(input).some(key => key !== 'otp') || !validSecret(input.otp))
75
+ throw new Error('Pass only a non-empty OTP of at most 4096 bytes.');
76
+ body = { otp: input.otp };
77
+ }
78
+ else {
79
+ if (!validSecret(input.username) || !validSecret(input.password))
80
+ throw new Error('Login needs a non-empty username and password of at most 4096 bytes.');
81
+ body = { allowedHosts: allowedHostsOf(input.allowedHosts), username: input.username, password: input.password };
82
+ }
83
+ return post('/tasks/login', { ...paused(pauseId), ...body }, true)
84
+ .then(() => ({ status: 'login_queued' }));
85
+ },
86
+ async check() {
87
+ const answer = await post('/tasks/check');
88
+ if (answer.status === 'waiting_for_input')
89
+ return waitingInput(answer);
90
+ const message = computerUseMessage(answer.message);
91
+ return { status: String(answer.status), ...(message ? { message } : {}) };
92
+ },
93
+ resume(pauseId) {
94
+ return post('/tasks/resume', paused(pauseId));
95
+ },
96
+ cancel() {
97
+ return post('/tasks/cancel');
98
+ },
99
+ };
100
+ }
101
+ function validSecret(value) {
102
+ return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= 4096;
103
+ }
104
+ export async function getSavedLogin(_accountRef, _website) {
105
+ return { status: 'unavailable' };
106
+ }
107
+ export async function getOtp(_taskId, _website) {
108
+ return { status: 'unavailable' };
109
+ }
@@ -22,9 +22,13 @@ export type SignInPage = {
22
22
  screenshot: string;
23
23
  url: string;
24
24
  };
25
- /** Starts a sign-in computer limited to `allowedHosts`; the handle names it in the calls that follow. */
26
- export declare function startSignIn({ allowedHosts, ...transport }: {
25
+ /**
26
+ * Starts a sign-in computer limited to `allowedHosts`; the handle names it in the calls that follow. The
27
+ * computer opens `startUrl`, an HTTPS page on one of those websites, or the first website's front page.
28
+ */
29
+ export declare function startSignIn({ allowedHosts, startUrl, ...transport }: {
27
30
  allowedHosts: readonly string[];
31
+ startUrl?: string;
28
32
  } & ComputerUseTransport): Promise<string>;
29
33
  export declare function showSignIn(handle: string, transport?: ComputerUseTransport): Promise<SignInPage>;
30
34
  export declare function sendSignInInput(handle: string, action: SignInAction, transport?: ComputerUseTransport): Promise<void>;
@@ -5,6 +5,19 @@
5
5
  // jobs. The computer answers only the app role that started it.
6
6
  import { allowedHostsOf, computerUseApi } from './computer-use-api.js';
7
7
  import { runtimeSecretLocation, runtimeSecrets } from './secrets.js';
8
+ function startUrlOf(startUrl, hosts) {
9
+ let url;
10
+ try {
11
+ url = new URL(String(startUrl));
12
+ }
13
+ catch {
14
+ url = undefined;
15
+ }
16
+ if (typeof startUrl !== 'string' || !url || url.protocol !== 'https:' || url.username || url.password || !hosts.includes(url.hostname)) {
17
+ throw new Error('startUrl must be an HTTPS address on one of the allowedHosts.');
18
+ }
19
+ return startUrl;
20
+ }
8
21
  function computerOf(handle) {
9
22
  let computer;
10
23
  try {
@@ -17,10 +30,13 @@ function computerOf(handle) {
17
30
  throw new Error('This is not a sign-in handle from startSignIn.');
18
31
  return { computerId: computer.computerId, endpoint: computer.endpoint };
19
32
  }
20
- /** Starts a sign-in computer limited to `allowedHosts`; the handle names it in the calls that follow. */
21
- export async function startSignIn({ allowedHosts, ...transport }) {
33
+ /**
34
+ * Starts a sign-in computer limited to `allowedHosts`; the handle names it in the calls that follow. The
35
+ * computer opens `startUrl`, an HTTPS page on one of those websites, or the first website's front page.
36
+ */
37
+ export async function startSignIn({ allowedHosts, startUrl, ...transport }) {
22
38
  const hosts = allowedHostsOf(allowedHosts);
23
- const { computerId, endpoint } = await computerUseApi(transport).post('/computers/start', { allowedHosts: hosts });
39
+ const { computerId, endpoint } = await computerUseApi(transport).post('/computers/start', { allowedHosts: hosts, ...(startUrl === undefined ? {} : { startUrl: startUrlOf(startUrl, hosts) }) });
24
40
  return Buffer.from(JSON.stringify({ computerId, endpoint })).toString('base64url');
25
41
  }
26
42
  export async function showSignIn(handle, transport = {}) {
@@ -1,3 +1,4 @@
1
+ import { type ComputerUseWaiting, type ComputerUseMessage } from './computer-use-handoff.js';
1
2
  export interface ComputerUseFile {
2
3
  name: string;
3
4
  contentType: "application/pdf";
@@ -21,24 +22,32 @@ export interface ComputerUseOptions {
21
22
  allowedHosts?: readonly string[];
22
23
  /**
23
24
  * Values the computer types into a password field by name, at most 10; the model sees only the names.
24
- * Never put a credential in the task text.
25
+ * Never put a credential in the task text. A user ID, customer ID or email is not a secret: the
26
+ * computer refuses to type a secret into a visible field, so give those in the task text.
25
27
  */
26
28
  secrets?: Readonly<Record<string, string>>;
27
29
  /** The app's code gets each file the task downloaded, one at a time, when the task is done. Never seen by the model. */
28
30
  onDownload?(download: ComputerUseDownload): Promise<void> | void;
29
31
  /** The job's runId, or `<job name>/<scheduledAt>` for a scheduled job: one task record per job run. */
30
32
  runKey: string;
33
+ attach?: boolean;
34
+ onMessage?(message: ComputerUseMessage): Promise<void> | void;
31
35
  /** The job's progress: called on each new step and at least once a minute, which renews the job's lease. */
32
36
  progress(percent: number, note?: string): Promise<void> | void;
33
37
  /** The job's cancelled(): when true the tool cancels the task and waits until the CUA stops. */
34
38
  cancelled(): Promise<boolean> | boolean;
35
39
  env?: NodeJS.ProcessEnv;
36
40
  fetch?: typeof fetch;
41
+ /**
42
+ * How long the task may wait for a free computer before the tool cancels it and returns `failed`;
43
+ * 20 minutes unless set. The wait is reported through `progress` while it lasts.
44
+ */
45
+ maxQueueMs?: number;
37
46
  /** The pause between checks; the tests shorten it. */
38
47
  pollIntervalMs?: number;
39
48
  now?: () => number;
40
49
  }
41
- export interface ComputerUseResult {
50
+ export interface ComputerUseFinished {
42
51
  status: 'done' | 'failed';
43
52
  summary: string | null;
44
53
  /** The page the browser was on when the task ended; a sign-in page there means the saved sign-in has expired. */
@@ -49,6 +58,7 @@ export interface ComputerUseResult {
49
58
  size: number;
50
59
  }[];
51
60
  }
61
+ export type ComputerUseResult = ComputerUseFinished | ComputerUseWaiting;
52
62
  export declare function createComputerUseTool(options: ComputerUseOptions): ({
53
63
  deferLoading?: boolean;
54
64
  title?: string;
@@ -8,9 +8,20 @@ import { setTimeout as sleep } from 'node:timers/promises';
8
8
  import { jsonSchema, tool } from 'ai';
9
9
  import { allowedHostsOf, computerUseApi, refused } from './computer-use-api.js';
10
10
  import { runtimeSecretLocation, runtimeSecrets } from './secrets.js';
11
+ import { computerUseMessage, waitingInput } from './computer-use-handoff.js';
11
12
  const HEARTBEAT_MS = 60_000;
13
+ const DEFAULT_MAX_QUEUE_MS = 20 * 60_000;
12
14
  // Checks the API did not answer (a throttle, a 5xx, no connection) before the tool gives up: about a minute.
13
15
  const MAX_MISSED_CHECKS = 12;
16
+ /** The progress note of a task that has not started: the wait and its reason when the CUA names one. */
17
+ function queueNote(answer, waitedMs) {
18
+ if (answer.status !== 'queued' || !answer.waiting)
19
+ return `Computer use task ${answer.status}.`;
20
+ const minutes = Math.max(1, Math.round(waitedMs / 60_000));
21
+ return answer.waiting.reason === 'capacity'
22
+ ? `Computer use task queued: no computer is free yet (${minutes} min).`
23
+ : `Computer use task queued: ${answer.waiting.reason} (${minutes} min).`;
24
+ }
14
25
  function secretsOf(secrets) {
15
26
  const entries = secrets && typeof secrets === 'object' && !Array.isArray(secrets) ? Object.entries(secrets) : [];
16
27
  if (entries.length < 1 || entries.length > 10)
@@ -72,18 +83,23 @@ export function createComputerUseTool(options) {
72
83
  }
73
84
  };
74
85
  return tool({
75
- description: 'Do one task in a web browser, such as filling in and submitting a form on a website. Describe the whole task in plain words, with the website address and any details it needs. Waits until the task ends and returns its status and a summary. Files the task downloads go to the app; the result lists their names.',
86
+ description: 'Do one task in a web browser, such as filling in and submitting a form on a website. Describe the whole task in plain words, with the website address and any details it needs. Returns when the task ends or pauses for outside input. When waiting_for_input, ask the app or human for help; do not start another task or resume without their explicit request. Files the task downloads go to the app; the result lists their names.',
76
87
  inputSchema: jsonSchema({ type: 'object', properties: { task: { type: 'string', minLength: 1 } }, required: ['task'], additionalProperties: false }),
77
88
  execute: async ({ task }) => {
78
- await api.post('/tasks', {
79
- run_key: options.runKey, task, ...(files?.length ? { files } : {}), ...(session === undefined ? {} : { session: await savedSession(session) }),
80
- ...(allowedHosts ? { allowedHosts } : {}), ...(secrets ? { secrets } : {}),
81
- });
82
- await options.progress(0, 'Computer use task started.');
89
+ if (!options.attach)
90
+ await api.post('/tasks', {
91
+ run_key: options.runKey, task, ...(files?.length ? { files } : {}), ...(session === undefined ? {} : { session: await savedSession(session) }),
92
+ ...(allowedHosts ? { allowedHosts } : {}), ...(secrets ? { secrets } : {}),
93
+ });
94
+ await options.progress(0, options.attach ? 'Computer use task reattached.' : 'Computer use task started.');
95
+ const queuedAt = now();
96
+ const maxQueueMs = options.maxQueueMs ?? DEFAULT_MAX_QUEUE_MS;
83
97
  let reported = now();
84
98
  let steps = 0;
85
99
  let cancelSent = false;
100
+ let queueExpired = false;
86
101
  let missed = 0;
102
+ let lastMessage = "";
87
103
  for (;;) {
88
104
  if (!cancelSent && await options.cancelled()) {
89
105
  await api.post('/tasks/cancel', { run_key: options.runKey });
@@ -99,7 +115,19 @@ export function createComputerUseTool(options) {
99
115
  if (check?.status === 200) {
100
116
  missed = 0;
101
117
  const answer = check.body;
118
+ const message = computerUseMessage(answer.message);
119
+ if (message && JSON.stringify(message) !== lastMessage) {
120
+ await options.onMessage?.(message);
121
+ await options.progress(Math.min(steps, 99), message.text);
122
+ reported = now();
123
+ lastMessage = JSON.stringify(message);
124
+ }
125
+ if (answer.status === 'waiting_for_input' && !cancelSent)
126
+ return waitingInput(answer);
102
127
  if (answer.status === 'done' || answer.status === 'failed') {
128
+ if (queueExpired && answer.status === 'failed') {
129
+ return { status: 'failed', summary: `No computer was free within ${Math.round(maxQueueMs / 60_000)} minutes; the task was cancelled before it started.`, finalUrl: null, downloads: [] };
130
+ }
103
131
  if (answer.status === 'done' && session !== undefined && answer.session)
104
132
  await runtimeSecrets.put(session, JSON.stringify(answer.session), transport);
105
133
  const downloads = answer.downloads ?? [];
@@ -114,9 +142,14 @@ export function createComputerUseTool(options) {
114
142
  }
115
143
  return { status: answer.status, summary: answer.summary ?? null, finalUrl: answer.final_url ?? null, downloads: downloads.map(({ name, size }) => ({ name, size })) };
116
144
  }
145
+ if (answer.status === 'queued' && !cancelSent && now() - queuedAt >= maxQueueMs) {
146
+ await api.post('/tasks/cancel', { run_key: options.runKey });
147
+ cancelSent = true;
148
+ queueExpired = true;
149
+ }
117
150
  if (answer.steps > steps || now() - reported >= HEARTBEAT_MS) {
118
151
  steps = Math.max(steps, answer.steps);
119
- await options.progress(Math.min(steps, 99), answer.last_step ? `Computer use step ${steps}: ${answer.last_step}` : `Computer use task ${answer.status}.`);
152
+ await options.progress(Math.min(steps, 99), answer.last_step ? `Computer use step ${steps}: ${answer.last_step}` : queueNote(answer, now() - queuedAt));
120
153
  reported = now();
121
154
  }
122
155
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@isomorph.ai/app-sdk",
3
- "version": "1.38.1",
3
+ "version": "1.40.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",