qz-browser-agent 0.1.1 → 0.1.3

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
@@ -1,467 +1,132 @@
1
- # qz command line and MCP
1
+ # qz
2
2
 
3
- Run browser tasks, manage results, and connect external agents to qz through CLI or MCP.
4
- Requires Node.js 24 or later and Chrome. CLI and MCP share the same browser connection.
3
+ An open-source browser agent for humans and coding agents.
5
4
 
6
- ## Quick start
7
-
8
- Install [qz from the Chrome Web Store](https://chromewebstore.google.com/detail/dknbdgkgoinlgjpfebapkklbmjjgdblm)
9
- with **Add to Chrome**. Open the qz side panel, complete its first-use data notice, and configure
10
- your provider and model in Settings.
11
-
12
- Run the published package with npx:
13
-
14
- ```bash
15
- npx qz-browser-agent@latest connect
16
- npx qz-browser-agent@latest create "Summarize the current page." --stream
17
- ```
18
-
19
- `npx qz-browser-agent@latest install` opens the same Chrome Web Store page. For a manual ZIP
20
- installation, download the [latest GitHub release](https://github.com/alibaba/qz-browser-agent/releases/latest)
21
- and follow the [manual installation steps](https://github.com/alibaba/qz-browser-agent/blob/main/README.md#manual-installation).
22
-
23
- `connect` starts the local MCP service and opens its connection page for first pairing. Use the
24
- Chrome profile where qz is installed. The first new profile is named `default`;
25
- accepting the data notice alone does not enable the local connection. Repeating `connect` reuses
26
- an online browser. Add further profiles with a [pairing URL](#pair-a-selected-browser-from-the-shell)
27
- or from their own qz Settings.
28
-
29
- The examples and suggested next commands use `qz`. Replace it with
30
- `npx qz-browser-agent@latest`, or install the command globally:
31
-
32
- ```sh
33
- npm install --global qz-browser-agent@latest
34
- qz --version
35
- ```
36
-
37
- On Windows, use PowerShell 7.3 or newer with its default native argument passing. After a global
38
- install, use `qz.ps1` for commands containing JSON or quoted names; Windows command suggestions
39
- use that wrapper. For automation, pin a compatible release version verified with your extension.
5
+ qz is a local-first extension for Chrome and Edge.
6
+ People use it from the side panel; agents such as Claude Code, Codex, and pi hand it web tasks
7
+ through this CLI or MCP. qz works in your own browser, with your existing logins, and returns
8
+ tables, files, or reports with sources. Everything runs locally, and your data goes only to the
9
+ model you choose.
40
10
 
41
- ## Connect and stop
42
-
43
- ```bash
44
- qz connect
45
- qz status
46
- qz browsers
47
- qz mcp
48
- qz stop
49
- ```
11
+ [Website](https://alibaba.github.io/qz-browser-agent/) ·
12
+ [GitHub](https://github.com/alibaba/qz-browser-agent) ·
13
+ [Chrome Web Store](https://chromewebstore.google.com/detail/dknbdgkgoinlgjpfebapkklbmjjgdblm) ·
14
+ [Full CLI and MCP reference](https://github.com/alibaba/qz-browser-agent/blob/main/docs/cli.md)
50
15
 
51
- `connect` reuses the healthy service already running for this installation. It prefers port 18765;
52
- if that port belongs to another program, the service chooses a free port. `status` shows the actual
53
- service address, and `mcp` prints its MCP URL. Both commands are read-only. To request a custom port,
54
- run `qz connect --port 18766`; an existing service on another port remains running and the command
55
- reports its address. The extension connects only to its configured address.
16
+ ![A coding agent handing a GitHub research task to qz](https://raw.githubusercontent.com/alibaba/qz-browser-agent/main/docs/images/examples/en/pi-delegate-en.gif)
56
17
 
57
- The connection page can be closed once `qz browsers` shows the profile online. Connections start
58
- only through `qz connect` or **qz Settings → Advanced → CLI → Connect CLI**. For ordinary connection
59
- failures, the extension makes at most three recovery attempts, 30 seconds apart, then pauses.
60
- After a browser or background restart, it may first wait once for the previous connection to expire.
61
- The saved retry budget survives worker restarts. Click **Connect CLI** in that browser's settings to retry.
62
-
63
- To disconnect one browser, click **Disconnect: NAME** in its qz Settings. `qz stop` stops the local
64
- service and disconnects every browser and MCP client using it. Browser tasks already running
65
- remain in the extension; stopping the service does not cancel them. Use `qz cancel TASK_ID` to stop
66
- a task, adding `--client NAME|UUID` when needed.
67
-
68
- ### Pair a selected browser from the shell
69
-
70
- Get a pairing URL without opening the default browser or waiting for a connection:
71
-
72
- ```bash
73
- qz connect --no-open --json
74
- qz connect --no-open --name work --json
75
- ```
76
-
77
- The JSON envelope contains `result.endpoint`, `result.url`, `result.mcpUrl`, and
78
- `result.opened: false`. The command starts or reuses the service even when other browsers are
79
- already connected. Open the exact returned URL in the intended browser Profile with qz installed.
80
-
81
- Set `QZ_PAIRING_URL` to that URL and `QZ_PROFILE_DIRECTORY` to the selected profile's directory
82
- name, such as `Default` or `Profile 2`. These are directory names, not Chrome's display labels.
83
- Use a Profile already chosen by the user. On macOS:
84
-
85
- ```sh
86
- open -na "Google Chrome" --args --profile-directory="$QZ_PROFILE_DIRECTORY" "$QZ_PAIRING_URL"
87
- ```
88
-
89
- For Chrome on Linux:
18
+ ## Quick start
90
19
 
91
- ```sh
92
- google-chrome --profile-directory="$QZ_PROFILE_DIRECTORY" "$QZ_PAIRING_URL"
93
- ```
20
+ Requires Node.js 22 or later.
94
21
 
95
- For Chrome installed under Program Files on Windows, set `$QzProfileDirectory` and
96
- `$QzPairingUrl` to those same values in PowerShell:
22
+ 1. **Install the extension.** Click **Add to Chrome** on the
23
+ [Chrome Web Store](https://chromewebstore.google.com/detail/dknbdgkgoinlgjpfebapkklbmjjgdblm),
24
+ open the qz side panel, and choose a provider and model in **Settings**.
25
+ 2. **Connect.** This starts the local service and pairs automatically with your default browser.
97
26
 
98
- ```powershell
99
- & "$env:ProgramFiles\Google\Chrome\Application\chrome.exe" "--profile-directory=$QzProfileDirectory" $QzPairingUrl
100
- ```
27
+ ```bash
28
+ npx qz-browser-agent@latest connect
29
+ ```
101
30
 
102
- Use the installed browser's executable or app name. For an existing custom data directory, also
103
- pass `--user-data-dir` with its exact path; for example on macOS:
31
+ 3. **Run your first task.**
104
32
 
105
- ```sh
106
- open -na "Google Chrome" --args --user-data-dir="$QZ_USER_DATA_DIR" --profile-directory="$QZ_PROFILE_DIRECTORY" "$QZ_PAIRING_URL"
107
- ```
33
+ ```bash
34
+ npx qz-browser-agent@latest create "Find this year's Nobel Prize winners in every category and put them in a table with source links." --stream
35
+ ```
108
36
 
109
- The [Chrome profile documentation](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md)
110
- distinguishes the data directory from the Profile inside it. A new data directory needs its own
111
- extension installation and first-use setup.
37
+ `--stream` shows progress, any questions qz needs you to answer, and the final result.
112
38
 
113
- `--name work` adds `?name=work` to the URL. The Profile opening it receives that identifier,
114
- including when it already has a connection. Without `--name`, a registered Profile keeps its name;
115
- a new Profile receives the next available name: `default`, `browser-2`, and so on. A name conflict
116
- requires another name. `qz connect --name work` opens the URL automatically and returns immediately.
117
- These URL-returning commands do not confirm that a browser connected. Verify it with:
39
+ For regular use, install the `qz` command globally and use it in place of
40
+ `npx qz-browser-agent@latest`:
118
41
 
119
42
  ```bash
120
- qz browsers --json
121
- qz create "Summarize the current page." --client UUID --stream
43
+ npm install --global qz-browser-agent@latest
44
+ qz --version
122
45
  ```
123
46
 
124
- Read `result.browsers`, then use the intended online entry's `clientId` UUID. `--client` selects an
125
- existing connection and cannot be combined with `--no-open` or `--name`. `--port` works with either
126
- pairing mode and follows the existing-service behavior above.
127
-
128
- ### Add and select browsers
129
-
130
- You can also pair from **qz Settings → Advanced → CLI** in the intended Profile. Enter a distinct
131
- browser identifier and connect. Use the service address printed by `qz status` in **Local service address** if
132
- its port differs from 18765. Names use 1–64 letters, digits, underscores, or hyphens, beginning with
133
- a letter or digit; names are case-sensitive. UUID-shaped names are reserved for profile IDs.
134
-
135
- ```bash
136
- qz browsers
137
- qz create "Summarize the current page." --client work --stream
138
- qz show TASK_ID --client work
139
- qz data --client work
140
- ```
47
+ To let your agent learn when and how to use qz, install the Skill with
48
+ `npx skills add alibaba/qz-browser-agent -g`.
141
49
 
142
- `--client NAME|UUID` and `-c NAME|UUID` select a profile. With exactly one online browser, the CLI
143
- selects it automatically. With several online browsers, a selection is required; `default` is a
144
- name, not a routing preference. An unknown or offline selection fails without opening or using
145
- another browser. Each command resolves its name once and carries the UUID through subsequent
146
- requests. JSON task results and suggested next commands include that UUID.
50
+ ## Connect an MCP client
147
51
 
148
- Names remain registered while their browsers are offline and across service restarts. To release
149
- an offline name, remove its registration explicitly:
52
+ After `connect`, print the MCP URL:
150
53
 
151
54
  ```bash
152
- qz browsers forget work
55
+ npx qz-browser-agent@latest mcp
153
56
  ```
154
57
 
155
- An online browser must first disconnect in its settings. Forgetting a registration leaves the
156
- browser's tasks and data intact. A browser can then explicitly pair using the released name.
157
-
158
- ### Update the connection
58
+ The default is `http://127.0.0.1:18765/mcp`; use the URL your command prints if the port differs.
159
59
 
160
- Use the current CLI and extension together. Source edits and a newer npm package leave a healthy
161
- running service in place; `qz status` reports an available update. An incompatible service returns
162
- an update instruction instead of being stopped automatically.
163
-
164
- 1. Use the latest CLI and let current tasks finish.
165
- 2. Run `npx --yes qz-browser-agent@latest stop`. This disconnects all browsers using that service.
166
- 3. Update qz from the [Chrome Web Store](https://chromewebstore.google.com/detail/dknbdgkgoinlgjpfebapkklbmjjgdblm).
167
- For a manual ZIP installation, replace its extracted files with the
168
- [latest release](https://github.com/alibaba/qz-browser-agent/releases/latest) and reload it at `chrome://extensions`.
169
- 4. Run `npx --yes qz-browser-agent@latest connect`, then reconnect additional profiles using their
170
- pairing URL or settings.
171
-
172
- ## Connect an MCP client
173
-
174
- Run `qz connect`, then `qz mcp`. Copy the returned URL into your MCP client's HTTP configuration:
60
+ **Codex** (`~/.codex/config.toml`):
175
61
 
176
62
  ```toml
177
63
  [mcp_servers.qz]
178
64
  url = "http://127.0.0.1:18765/mcp"
179
65
  ```
180
66
 
181
- Use the URL printed by your command if its port differs. `qz mcp --json` returns the URL as JSON
182
- for scripts. The `qingzhou_*` MCP tool names and extension protocol remain available. Responses
183
- to pending input bind to an explicit `waitId`. Use `qingzhou_bridge_status` to list browser names
184
- and UUIDs, then pass `clientId: "work"` or a UUID to browser tools. Selection is required with
185
- multiple online browsers. Task results include the resolved `clientId`. MCP initialization and streaming are handled by your
186
- client's MCP implementation.
187
-
188
- ### Task and resource operations
189
-
190
- CLI and MCP use the same task observer and browser operations. The task and resource commands map to these MCP operations:
191
-
192
- | CLI | MCP tool |
193
- | --- | --- |
194
- | `browsers`, `browsers forget` | `qingzhou_bridge_status`, `qingzhou_forget_browser` |
195
- | `create`, `send`, `cancel` | `qingzhou_create_session`, `qingzhou_send_message`, `qingzhou_stop_session` |
196
- | `tasks`, `show`, `watch` | `qingzhou_list_sessions`, `qingzhou_get_session_snapshot`, `qingzhou_watch_task` |
197
- | `show`, `submit` / `approve` / `reject` | `qingzhou_get_session_snapshot`, `qingzhou_respond_to_user_input` |
198
- | `data list` / `delete` / `export` | `qingzhou_list_data_tables`, `qingzhou_delete_data_table`, `qingzhou_export_data_table` |
199
- | `images list` / `delete` / `export` | `qingzhou_list_image_collections`, `qingzhou_delete_image_collection`, `qingzhou_export_image_collection` |
200
- | `skills list` / `show` / `read` / `tools` / `export` | `qingzhou_list_skills`, `qingzhou_get_skill`, `qingzhou_get_skill_resource`, `qingzhou_list_plugins`, `qingzhou_export_skill` |
201
- | `settings get` / `set` | `qingzhou_get_settings`, `qingzhou_update_settings` |
202
- | `automations list` / `run` | `qingzhou_list_automations`, `qingzhou_run_automation` |
203
-
204
- MCP creation, message submission, and input responses accept `wait: true` to wait for completion;
205
- `stream: true` also sends assistant text through standard MCP progress notifications. A watch call
206
- always waits. For example, call `qingzhou_create_session` with:
207
-
208
- ```json
209
- {"firstMessage":"Summarize the current page.","stream":true}
210
- ```
211
-
212
- Supply `_meta.progressToken` on the MCP request to receive progress. Each notification includes a
213
- readable `message` and its structured event in `params._meta["qz/task-event"]`. Events include
214
- `created`, `status`, `text`, `replace`, and `input`. Input events include the current form, exact
215
- field IDs, option values, and `responseTemplate`. Fill that template and pass it to
216
- `qingzhou_respond_to_user_input`; another CLI or MCP connection can answer while the original call
217
- keeps waiting. Native Chrome permissions still require the user's click in the side panel.
218
-
219
- MCP `timeoutSeconds` bounds each browser request (180 seconds by default).
220
- `waitTimeoutSeconds` bounds the whole observation; omit it for no overall deadline. Configure your
221
- MCP client's own request deadline for long tasks. On timeout or cancellation, the browser task
222
- continues; error details include the task ID and a recovery tool call. `send_message` supports
223
- `steer: true` and follows its returned `clientMessageId`, including when steering stays in the same
224
- run. A long observation stays bound to the browser selected when it started.
225
-
226
- ## Run a task
227
-
228
- ```bash
229
- qz create "Compare these two laptops."
230
- qz create "Summarize the current page." --title "Research" --wait
231
- qz create "Find the main differences between these pages." --stream
232
- qz send TASK_ID "Add the source links." --stream
233
- qz send TASK_ID "Focus on open-source options." --steer --stream
234
- qz tasks
235
- qz show TASK_ID
236
- qz cancel TASK_ID
237
- ```
238
-
239
- `create` starts a task and returns its ID. The title is optional. `--wait` waits for the result;
240
- `--stream` also displays progress as it arrives. Both stay connected while the task waits for user
241
- input and continue automatically after you respond. Task observation has no default time limit.
242
- Add `--timeout SECONDS` to set a total deadline, including time spent waiting for input. Each
243
- individual connection request remains bounded (180 seconds by default). A timeout or Ctrl-C ends
244
- watching; `qz watch TASK_ID --stream` resumes observation and `qz cancel TASK_ID` stops the task.
245
- Each CLI command initializes one MCP connection on its first tool call and reuses it for subsequent
246
- reads and responses. Completion, errors, and Ctrl-C close that connection. Transport failures are
247
- reported without automatically repeating browser actions.
248
-
249
- Provide the task text directly after `create`, or read it from stdin with `qz create -`.
250
- Use `--parent TASK_ID` to create a child task, and `qz tasks --limit N` to limit the task list.
251
- `send TASK_ID MESSAGE` sends a follow-up to the specified task; `qz send TASK_ID -` reads the message
252
- from stdin. A busy task queues a follow-up for its next run. Add `--steer` to deliver the message
253
- to the current run at its next safe boundary. Both start a new run when the task is idle. Pending
254
- questions and permissions still require a response.
255
-
256
- `--wait` and `--stream` track the submitted message. Streaming starts after that message, including
257
- when steering continues the same run. Pending questions from the preceding run remain visible so
258
- you can answer them and let a queued follow-up proceed. A connection failure never resends a message
259
- automatically.
260
-
261
- ## Respond to a task
262
-
263
- ```bash
264
- qz show TASK_ID
265
- qz submit TASK_ID '{"selectedIds":["option-a"]}' --stream
266
- qz approve TASK_ID --wait
267
- qz reject TASK_ID
268
- qz watch TASK_ID --stream
269
- ```
270
-
271
- `show` and pending-input notices include the current question, labeled field IDs,
272
- option values, descriptions, image URLs, and a submission template with the actual field IDs.
273
- Edit its placeholder values and run the displayed command to respond. `submit` takes a JSON object
274
- keyed by field IDs; use option values for choices and arrays for multiple choices. Use
275
- `qz submit TASK_ID -` to read answers from stdin. Invalid or stale submissions return the current
276
- input and its template so you can correct the response directly.
277
- `approve` continues a confirmation after you finish the requested action. `reject` declines the
278
- current request; `cancel` stops the whole task.
279
-
280
- Each response reads the current wait ID before sending. To answer a specific request you already
281
- read, pass `--wait-id WAIT_ID` to `submit`, `approve`, or `reject`. A stale or invalid response
282
- leaves the request pending. Review the application consent notice included in the pending input,
283
- such as location sharing, before approving. Native Chrome permissions require a click in the qz side panel; CLI
284
- approval reports that action is needed and preserves the wait without opening a browser page.
285
- With `--wait` or `--stream`, the command stays connected while you grant permission in Chrome.
286
- Location approval reads the current disclosure version and includes it in the response. Human
287
- terminal output shows the notice before submitting the explicit approval; JSON output remains a
288
- single final result. MCP callers should show the notice to the user before sending approval with
289
- the returned `consentVersion`.
290
-
291
- `submit`, `approve`, and `reject` accept `--wait` and `--stream` to follow the task until it finishes, including
292
- further questions and permission requests. Each new request is shown once. Respond in the side
293
- panel or another terminal; the original command continues automatically. `watch` follows an
294
- existing task without resubmitting anything. Timeouts and Ctrl-C stop watching, while the task
295
- continues in the browser.
296
-
297
- ## Browser selection and MCP tools
298
-
299
- Use `--client NAME|UUID` or `-c NAME|UUID` to select a browser. `qz browsers` lists registered names,
300
- UUIDs, and online status. See [browser selection](#add-and-select-browsers) for pairing and name reuse.
301
- Use `-t` for `--title`. Run `qz help COMMAND` or `qz COMMAND --help` for command-specific options.
302
-
303
- MCP clients can inspect browser tool schemas with `qingzhou_list_tools` and `qingzhou_get_tool`,
304
- then call `qingzhou_execute_tool` in a task. Set `wait: false` to receive a job ID and read the result
305
- with `qingzhou_get_tool_job`. Pass `runId` to bind execution to a particular task run. MCP also
306
- provides `qingzhou_get_trace` and `qingzhou_clear_trace` for diagnostics.
307
-
308
- If a request times out or its connection is interrupted, an operation already started in the
309
- browser may still be running. Check the task before repeating it. Disconnected MCP requests are
310
- cancelled in the service, and reconnecting does not replay their browser actions.
311
-
312
- ## Data, images, and Skills
313
-
314
- ```bash
315
- qz data
316
- qz data export TABLE
317
- qz data export TABLE --format csv
318
- qz data delete TABLE
319
- qz images
320
- qz images export COLLECTION
321
- qz images delete COLLECTION
322
- qz skills --query research
323
- qz skills show NAME
324
- qz skills read NAME scripts/run.js --limit 20000
325
- qz skills tools --session TASK_ID
326
- qz skills export NAME
327
- ```
328
-
329
- Use the exact names printed by each list; quote names containing spaces. Data exports default to
330
- Excel (`xlsx`); `--format csv` selects CSV. Image collections export as a ZIP containing available
331
- image files and metadata. Missing local images are reported in the result. Skill exports contain
332
- one user-installed Skill and its resources; built-in Skills require the extension and cannot be
333
- exported independently.
334
-
335
- `skills show` includes the resource paths. `skills read NAME PATH` reads one resource, with a
336
- default limit of 20,000 characters. Use `--start` and `--limit` to select a chunk; truncated text
337
- includes the command for the next chunk. `skills tools` lists contributed tools and whether they
338
- are active in the selected task's context.
339
- `skills --scope all|global|site|resident` filters by activation scope. Exports accept `--filename NAME`.
340
- `automations --limit N` limits the automation list.
341
-
342
- Exports use Chrome downloads. The result includes the download status, ID, filename, and path when
343
- Chrome provides it. Check pending downloads in `chrome://downloads`. `delete` removes the named table
344
- or image collection and its rows. Image blobs shared by other collections or task history remain
345
- in the asset store.
346
-
347
- ## Settings and automations
67
+ **Claude Code**:
348
68
 
349
69
  ```bash
350
- qz settings
351
- qz settings get model
352
- qz settings set model MODEL_ID
353
- qz settings set vision true
354
- qz settings set '{"modelParameters":{"temperature":0.5}}'
355
- qz settings set - < settings.json
356
- qz automations
357
- qz automations run AUTOMATION_ID
70
+ claude mcp add --transport http qz http://127.0.0.1:18765/mcp
358
71
  ```
359
72
 
360
- `settings` returns current values, editable fields, provider IDs, and protocol IDs. Credentials are
361
- redacted; `qz settings get apiKey` reports whether a key is configured. `set KEY VALUE` parses JSON
362
- values such as booleans, numbers, objects, and arrays; other values are strings. `set JSON` applies
363
- a patch containing the supplied top-level fields. Follow the field descriptions for values that
364
- replace an entire object, such as `modelParameters`.
365
-
366
- Read credential patches from stdin to keep them out of shell history. JSON is validated before
367
- connecting. The extension validates field names and values before saving. Browser commands accept
368
- `--client NAME|UUID` to select a profile. `automations run` starts an existing automation and
369
- returns its task ID.
370
-
371
- The CLI uses the same browser operations as MCP. Its commands correspond to tasks, data,
372
- images, Skills, settings, and automations. `qz mcp` only returns the connection URL for MCP
373
- clients.
374
-
375
- ## Terminal output
376
-
377
- Interactive terminals show readable text; pipes and redirected output receive JSON. Use `--json`
378
- to request JSON explicitly or `--plain` to keep text when redirecting output. `--no-color` or the
379
- `NO_COLOR` environment variable disables color. `qz mcp` prints only the MCP URL by default;
380
- `qz mcp --json` returns a JSON result.
381
-
382
- In JSON mode, `--wait` and `--stream` emit one final JSON result on stdout. Complete pending-input
383
- notices and submission templates appear on stderr so you can respond while preserving
384
- machine-readable output. MCP snapshots and rejected responses include `input`, with a
385
- `responseTemplate` that binds answers to the current session and wait. Chrome-native permission
386
- requests provide user instructions instead of an approval template.
387
- Exit codes are `0` for success (including reading pending input), `1` for an operation or
388
- task failure or a rejected submission, `2` for invalid arguments, and `130` for Ctrl-C.
389
- Connection errors include the GitHub setup guide and installation link.
390
-
391
- ## Local access
392
-
393
- The service listens on loopback. It validates Host and Origin, rejects redirects, and accepts
394
- extension polling only from extension origins or local clients. Ordinary websites cannot send
395
- requests through the MCP endpoint. Local programs can control connected qz tasks while the
396
- service is running. Run `qz stop` to disconnect.
397
-
398
- Connection metadata and browser registrations are stored in `~/.qz-browser-agent/run/`;
399
- `QZ_STATE_DIR` selects another local directory for isolated tests. Registration writes are atomic;
400
- a failed write leaves the previous registration active. Private pairing proofs stay in local storage
401
- and are omitted from status output. Atomic startup locks prevent duplicate services. Development copies
402
- and published installations use separate identities. The client verifies the service identity,
403
- protocol version, instance, and process before reusing or stopping it. Editing source files or
404
- running a newer package keeps the healthy service and its connections alive. `status` reports
405
- when a different build is available. To load the new service code, finish active work, run
406
- `qz stop`, then `qz connect`.
407
-
408
- ## Package development
409
-
410
- The npm package name is `qz-browser-agent`; the executable name is `qz`. Local development uses
411
- this same package name. The repository root stays private, and this service directory is the
412
- publishable package. Publishing requires separate authorization and ownership of the npm name.
413
-
414
- From the repository root, install the locked dependencies and run the local source:
73
+ **Clients with an `mcpServers` JSON config**, such as Cursor:
415
74
 
416
- ```bash
417
- npm ci
418
- npm run qz -- --version
419
- npm run qz -- connect
420
- npm run qz -- create "Summarize the current page." --stream
421
- ```
422
-
423
- Keep the `--` separator when forwarding options through npm. For a local `qz` executable,
424
- run `npm link` in `services/mcp-bridge`. JavaScript runs directly on Node.js. The published
425
- package contains the runtime files, tool catalog, README, and license.
426
-
427
- ```bash
428
- npm test -- services --match node
429
- node tests/release/npm-package.mjs
75
+ ```json
76
+ {
77
+ "mcpServers": {
78
+ "qz": { "url": "http://127.0.0.1:18765/mcp" }
79
+ }
80
+ }
430
81
  ```
431
82
 
432
- The package check packs the service and installs that tarball in two clean temporary directories
433
- using the public npm registry. It checks the installed command, versions, MCP tools, service reuse,
434
- and shutdown on an isolated port. The test owns its npm configuration, cache, connection state,
435
- and service process. It requires network access to download dependencies.
436
-
437
- Use `--output tests/results/npm/qz-browser-agent-0.1.1.tgz` to retain the verified tarball.
438
- Use `--tarball PATH` to check an existing tarball. The check also runs through
439
- `npm test -- release --match npm-package`.
440
-
441
- ## Publish to npm
442
-
443
- Choose the package version in `services/mcp-bridge/package.json`, complete the repository checks,
444
- and commit the intended source before publishing. CLI and MCP report that same package version.
445
- Each published version identifies immutable package contents; use a new version for updates.
446
-
447
- The **npm package** GitHub Actions workflow tests the CLI and the installed package on Linux,
448
- macOS, and Windows. On a manual run, provide the expected version. With **publish** left unchecked,
449
- it only validates the package and retains the tested tarball. Publishing requires a manual run
450
- from `main` with **publish** checked; all three platforms must pass first.
83
+ CLI and MCP share the same browser connection. The MCP tool list is in the
84
+ [reference](https://github.com/alibaba/qz-browser-agent/blob/main/docs/cli.md#task-and-resource-operations).
451
85
 
452
- Configure the npm package's trusted publisher for the `alibaba/qz-browser-agent` repository,
453
- workflow `npm-package.yml`, and GitHub environment `npm`. Enable direct publishing in that
454
- trusted publisher configuration. The publish job uses OIDC and uploads the exact Linux-tested
455
- tarball. The npm package must be created under an account with publishing rights before this
456
- trusted publisher can be configured. See [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/).
86
+ ## Common commands
457
87
 
458
- For the first manual release, log in with npm, verify the saved tarball, and publish it:
459
-
460
- ```bash
461
- npm login --registry=https://registry.npmjs.org
462
- node tests/release/npm-package.mjs --output tests/results/npm/qz-browser-agent-0.1.1.tgz
463
- npm publish tests/results/npm/qz-browser-agent-0.1.1.tgz --access public --registry=https://registry.npmjs.org
464
- ```
465
-
466
- The root package stays private. Publishing the service does not publish the Chrome extension.
467
- After publication, check `npx qz-browser-agent@0.1.1 --version` from a directory outside the repository.
88
+ | Command | What it does |
89
+ | --- | --- |
90
+ | `qz connect` | Start the local service and pair a browser |
91
+ | `qz status` | Check the connection and service address |
92
+ | `qz browsers` | List paired browsers, or `forget` an offline one |
93
+ | `qz create "PROMPT"` | Start a task; add `--stream` or `--wait` to follow it |
94
+ | `qz send TASK_ID "MESSAGE"` | Send a follow-up, or `--steer` the current run |
95
+ | `qz tasks` | List tasks |
96
+ | `qz show TASK_ID` | Read a task's status, response, or pending question |
97
+ | `qz watch TASK_ID` | Follow a task until its work and queued messages finish |
98
+ | `qz submit` / `approve` / `reject` | Answer a question or permission request |
99
+ | `qz cancel TASK_ID` | Stop a task |
100
+ | `qz data` | List, export, or delete data tables |
101
+ | `qz images` | List, export, or delete image collections |
102
+ | `qz skills` | Find, read, or export Skills |
103
+ | `qz settings` | Read or update settings |
104
+ | `qz automations` | List or run automations |
105
+ | `qz stop` | Stop the local service and disconnect all browsers |
106
+
107
+ With several browser profiles connected, choose one with `--client NAME|UUID` (or `-c`).
108
+ Run `qz COMMAND --help` for options. Interactive terminals show readable text; pipes receive JSON.
109
+
110
+ `watch`, `--wait`, and `--stream` follow the same task across runs until its current work and
111
+ accepted follow-ups and steering messages have completed and its queues are empty. Questions
112
+ and permission requests keep observation open. Task failure or stopping ends observation.
113
+ Timeout or Ctrl-C ends observation while the browser task continues; execute the returned
114
+ `watch` command with the same task ID and browser UUID to resume. Observation never resends messages.
115
+
116
+ ## Privacy and local access
117
+
118
+ The service accepts connections only on your computer, and ordinary websites cannot use its MCP
119
+ endpoint. Local programs can control connected qz tasks while the service is running. `qz stop`
120
+ disconnects all browsers and MCP clients; tasks already running in the browser keep going.
121
+ Connection settings are stored in `~/.qz-browser-agent/run/`, and pairing credentials never
122
+ leave your computer.
123
+
124
+ ## Reference
125
+
126
+ See the [qz CLI and MCP reference](https://github.com/alibaba/qz-browser-agent/blob/main/docs/cli.md)
127
+ for pairing a specific browser profile, Windows PowerShell notes, updates, task responses,
128
+ exports, output formats, exit codes, and the MCP tool mapping.
129
+
130
+ ## License
131
+
132
+ [Apache-2.0](https://github.com/alibaba/qz-browser-agent/blob/main/LICENSE)
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "qz-browser-agent",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Local browser tools and MCP access for the qz extension",
5
5
  "type": "module",
6
- "engines": { "node": ">=24" },
6
+ "engines": { "node": ">=22" },
7
7
  "bin": { "qz": "src/bin.mjs" },
8
8
  "files": ["src/*.mjs", "src/catalog.json", "README.md", "LICENSE"],
9
9
  "license": "Apache-2.0",
package/src/bin.mjs CHANGED
@@ -7,19 +7,17 @@ let isEntry = false;
7
7
  try { isEntry = realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); } catch {}
8
8
  if (isEntry) {
9
9
  const argv = process.argv.slice(2);
10
- if (Number(process.versions.node.split(".")[0]) < 24) {
10
+ if (Number(process.versions.node.split(".")[0]) < 22) {
11
11
  const error = {
12
12
  code: "unsupported_node_version",
13
- message: `qz requires Node.js 24 or later. Current version: ${process.versions.node}.`,
14
- hint: "Install Node.js 24 or later, then run qz again.",
13
+ message: `qz requires Node.js 22 or later. Current version: ${process.versions.node}.`,
14
+ hint: "Install Node.js 22 or later, then run qz again.",
15
15
  };
16
16
  if (argv.includes("--json")) process.stdout.write(`${JSON.stringify({ ok: false, error })}\n`);
17
17
  else process.stderr.write(`${error.message}\n${error.hint}\n`);
18
18
  process.exitCode = 1;
19
19
  } else {
20
- const { main } = await import("./cli.mjs");
21
- const controller = new AbortController();
22
- process.once("SIGINT", () => controller.abort());
23
- process.exitCode = await main(argv, { signal: controller.signal });
20
+ const { runMain } = await import("./cli.mjs");
21
+ process.exitCode = await runMain(argv);
24
22
  }
25
23
  }
package/src/catalog.json CHANGED
@@ -62,10 +62,10 @@
62
62
  },
63
63
  {
64
64
  "name": "qingzhou_create_session",
65
- "description": "Create a task with an optional first message. Set wait=true to return its completed snapshot, or stream=true for progress events. User-input waits keep observation open. Cancellation stops observing; the browser task continues.",
65
+ "description": "Create a task with an optional first message. Set wait=true to follow the same task across runs until its current work and accepted follow-ups and steering messages have completed and its queues are empty. stream=true adds progress events. User-input waits keep observation open. Task failure or stopping ends observation. Timeout or cancellation ends observation while the browser task continues; use the returned watch recovery call without resubmitting.",
66
66
  "inputSchema": {
67
67
  "properties": {
68
- "wait": {"type": "boolean", "default": false, "description": "Keep observing until the task finishes, including user-input waits."},
68
+ "wait": {"type": "boolean", "default": false, "description": "Follow the same task across runs until its work completes and its accepted follow-up and steering queues are empty. User-input waits keep observation open; task failure or stopping ends it."},
69
69
  "stream": {"type": "boolean", "default": false, "description": "Implies wait. Send task text, status, and input events through MCP progress notifications when a progressToken is supplied."},
70
70
  "waitTimeoutSeconds": {"type": ["number", "null"], "exclusiveMinimum": 0, "maximum": 86400, "default": null, "description": "Optional total observation deadline; null waits indefinitely. timeoutSeconds bounds each browser request."},
71
71
  "title": {"default": "", "title": "Title", "type": "string"},
@@ -80,10 +80,10 @@
80
80
  },
81
81
  {
82
82
  "name": "qingzhou_send_message",
83
- "description": "Send a message to the specified task. By default, a busy task queues a follow-up for its next run. Set steer=true to guide its current run at the next safe boundary. An idle task starts with either mode. Returns deliveryMode, disposition, and clientMessageId for tracking. Set wait=true to observe the submitted message through completion, including queued follow-ups and user-input waits. stream=true also emits text through MCP progress notifications.",
83
+ "description": "Send a message to the specified task. By default, a busy task queues a follow-up for its next run. Set steer=true to guide its current run at the next safe boundary. An idle task starts with either mode. Returns deliveryMode, disposition, and clientMessageId to confirm acceptance. Set wait=true to follow the same task across runs until its work completes and its follow-up and steering queues are empty. A queued message removed before execution no longer blocks completion. stream=true emits text from the submitted message onward through MCP progress notifications. Timeout or cancellation ends observation; use the returned watch recovery call without resubmitting.",
84
84
  "inputSchema": {
85
85
  "properties": {
86
- "wait": {"type": "boolean", "default": false, "description": "Keep observing until the task finishes, including user-input waits."},
86
+ "wait": {"type": "boolean", "default": false, "description": "Follow the same task across runs until its work completes and its accepted follow-up and steering queues are empty. User-input waits keep observation open; task failure or stopping ends it."},
87
87
  "stream": {"type": "boolean", "default": false, "description": "Implies wait. Send task text, status, and input events through MCP progress notifications when a progressToken is supplied."},
88
88
  "waitTimeoutSeconds": {"type": ["number", "null"], "exclusiveMinimum": 0, "maximum": 86400, "default": null, "description": "Optional total observation deadline; null waits indefinitely. timeoutSeconds bounds each browser request."},
89
89
  "text": {"title": "Text", "type": "string"},
@@ -150,7 +150,7 @@
150
150
  "description": "Respond using the pending input's responseTemplate: fill answers keyed by field IDs with option values for choices (arrays for multi_choice), then submit; approve a completed action or application consent, or reject. Show location disclosures and obtain explicit user consent before approving with consentVersion. Native Chrome permissions require the user's click in qz. Invalid or stale replies return the current input for correction and keep the request pending.",
151
151
  "inputSchema": {
152
152
  "properties": {
153
- "wait": {"type": "boolean", "default": false, "description": "Keep observing until the task finishes, including user-input waits."},
153
+ "wait": {"type": "boolean", "default": false, "description": "Follow the same task across runs until its work completes and its accepted follow-up and steering queues are empty. User-input waits keep observation open; task failure or stopping ends it."},
154
154
  "stream": {"type": "boolean", "default": false, "description": "Implies wait. Send task text, status, and input events through MCP progress notifications when a progressToken is supplied."},
155
155
  "waitTimeoutSeconds": {"type": ["number", "null"], "exclusiveMinimum": 0, "maximum": 86400, "default": null, "description": "Optional total observation deadline; null waits indefinitely. timeoutSeconds bounds each browser request."},
156
156
  "sessionId": {"type": "string", "minLength": 1},
@@ -357,7 +357,7 @@
357
357
  },
358
358
  {
359
359
  "name": "qingzhou_watch_task",
360
- "description": "Observe an existing task until it finishes without resubmitting it. Questions and Chrome permission requests keep observation open; MCP progress notifications include their full input and responseTemplate. stream=true includes text updates. Cancellation stops observing while the task continues.",
360
+ "description": "Observe an existing task across runs until its current work and accepted follow-ups and steering messages have completed and its queues are empty, without resubmitting anything. Questions and Chrome permission requests keep observation open; MCP progress notifications include their full input and responseTemplate. stream=true includes text updates. Task failure or stopping ends observation. Timeout or cancellation ends observation while the browser task continues; resume with the returned recovery call using the same sessionId and clientId.",
361
361
  "inputSchema": {
362
362
  "type": "object",
363
363
  "properties": {
package/src/cli.mjs CHANGED
@@ -7,7 +7,7 @@ import { ensureDaemon, findDaemon, stopDaemon } from "./daemon.mjs";
7
7
  import { openBrowser } from "./open-browser.mjs";
8
8
  import { parseCommand } from "./args.mjs";
9
9
  import { renderError, renderHelp, renderResult, renderInputNotice, sanitizeTerminalText } from "./terminal.mjs";
10
- import { waitForTask } from "./task-stream.mjs";
10
+ import { TASK_NOT_FOUND_MESSAGE, waitForTask } from "./task-stream.mjs";
11
11
  import { createLiveOutput, outputMode } from "./output.mjs";
12
12
  import { resourceRequest, settingsPatch } from "./cli-resources.mjs";
13
13
  import { PACKAGE_NAME, PACKAGE_VERSION } from "./package-info.mjs";
@@ -73,11 +73,18 @@ function recoveryCommand(command, sessionId, clientId, stream = false) {
73
73
  if (clientId && sanitizeTerminalText(clientId) !== String(clientId)) clientId = "CLIENT_ID";
74
74
  const client = clientId ? ` --client${String(clientId).startsWith("-") ? "=" : " "}${shellArgument(clientId)}` : "";
75
75
  const options = `${client}${stream ? " --stream" : ""}`;
76
+ if (!sessionId) return `qz ${command}${options}`;
76
77
  return String(sessionId).startsWith("-")
77
78
  ? `qz ${command}${options} ${optionTerminator()} ${shellArgument(sessionId)}`
78
79
  : `qz ${command} ${shellArgument(sessionId)}${options}`;
79
80
  }
80
81
 
82
+ function missingTaskDetails(sessionId, clientId) {
83
+ return { sessionId, ...(clientId ? { clientId } : {}),
84
+ hint: "Check the task ID and selected browser. Run qz browsers to inspect browser names and UUIDs. List tasks in the selected browser:",
85
+ command: recoveryCommand("tasks", "", clientId) };
86
+ }
87
+
81
88
  export async function runCli(argv, dependencies = {}) {
82
89
  return executeCommand(parseCommand(argv), dependencies);
83
90
  }
@@ -206,19 +213,20 @@ async function dispatchCommand(parsed, dependencies) {
206
213
  throw error;
207
214
  }
208
215
  };
209
- const observe = async (sessionId, { runId = "", expectedMessageId = "", previousRunId = "", ignoreWaitId = "", allowIdle = false } = {}) => {
216
+ const observe = async (sessionId, { runId = "", expectedMessageId = "", messageWasQueued = false, ignoreWaitId = "", allowIdle = false } = {}) => {
210
217
  try {
211
218
  const remaining = waitTimeoutSeconds == null ? null : waitTimeoutSeconds - (Date.now() - startedAt) / 1000;
212
219
  if (remaining !== null && remaining <= 0) throw new DOMException("Stopped watching after the configured --timeout. The browser task may still be running.", "TimeoutError");
213
220
  return await waitForTask({
214
221
  sessionId, clientId: common.clientId, timeoutSeconds: remaining, signal: dependencies.signal,
215
222
  requestTimeoutSeconds: timeoutSeconds,
216
- expectedRunId: runId, expectedMessageId, previousRunId, ignoreWaitId, allowIdle,
223
+ expectedRunId: runId, expectedMessageId, messageWasQueued, ignoreWaitId, allowIdle,
217
224
  onUpdate: dependencies.onTaskUpdate,
218
225
  getSnapshot: ({ timeoutSeconds: seconds, signal }) => readSnapshot(sessionId, seconds, signal),
219
226
  });
220
227
  } catch (error) {
221
228
  const code = error.name === "TimeoutError" ? "timeout" : error.name === "AbortError" ? "interrupted" : error.code || "task_wait_failed";
229
+ if (code === "task_deleted") throw new QzError(code, error.message, { ...error.details, ...missingTaskDetails(sessionId, clientId) });
222
230
  const changed = code === "task_changed";
223
231
  throw new QzError(code, code === "timeout"
224
232
  ? "Stopped watching after the configured --timeout. The browser task may still be running." : error.message,
@@ -237,7 +245,9 @@ async function dispatchCommand(parsed, dependencies) {
237
245
  sessionId: id, hint: "Continue watching the same task:", command: recoveryCommand("watch", id, clientId, true),
238
246
  });
239
247
  }
240
- result = { ...result, snapshot: await observe(id, { expectedMessageId: result.clientMessageId }) };
248
+ result = { ...result, snapshot: await observe(id, {
249
+ expectedMessageId: result.clientMessageId, messageWasQueued: result.disposition === "queued",
250
+ }) };
241
251
  }
242
252
  return { result };
243
253
  }
@@ -283,6 +293,9 @@ async function dispatchCommand(parsed, dependencies) {
283
293
  ...(action === "list" && options.limit !== undefined ? { limit: Number(options.limit) } : {}) };
284
294
  }
285
295
  let result = await call(running.endpoint, name, parameters, requestOptions);
296
+ if (command === "tasks" && action === "get" && result?.session === null) {
297
+ throw new QzError("task_not_found", TASK_NOT_FOUND_MESSAGE, missingTaskDetails(id, clientId));
298
+ }
286
299
  if (command === "tasks" && action === "create" && options.wait) {
287
300
  const sessionId = result?.session?.id || result?.sessionId;
288
301
  if (!sessionId) throw new QzError("invalid_response", "The task was created without an ID. Run qz tasks to find it before retrying.");
@@ -351,10 +364,30 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
351
364
  }
352
365
  }
353
366
 
367
+ /** Keep handlers installed while npm forwards duplicate signals and MCP closes. */
368
+ export async function runMain(argv = process.argv.slice(2), dependencies = {}) {
369
+ const controller = new AbortController();
370
+ let interruptedExitCode;
371
+ const interrupt = code => {
372
+ if (controller.signal.aborted) return;
373
+ interruptedExitCode = code;
374
+ controller.abort();
375
+ };
376
+ const onSigint = () => interrupt(130);
377
+ const onSigterm = () => interrupt(143);
378
+ process.on("SIGINT", onSigint);
379
+ process.on("SIGTERM", onSigterm);
380
+ try {
381
+ const code = await main(argv, { ...dependencies, signal: controller.signal });
382
+ return interruptedExitCode ?? code;
383
+ } finally {
384
+ process.removeListener("SIGINT", onSigint);
385
+ process.removeListener("SIGTERM", onSigterm);
386
+ }
387
+ }
388
+
354
389
  let isEntry = false;
355
390
  try { isEntry = realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); } catch {}
356
391
  if (isEntry) {
357
- const controller = new AbortController();
358
- process.once("SIGINT", () => controller.abort());
359
- process.exitCode = await main(process.argv.slice(2), { signal: controller.signal });
392
+ process.exitCode = await runMain();
360
393
  }
package/src/client.mjs CHANGED
@@ -1,5 +1,4 @@
1
1
  import { request } from "node:http";
2
- import { Readable } from "node:stream";
3
2
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
3
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
5
4
  import { PACKAGE_VERSION } from "./package-info.mjs";
@@ -27,6 +26,19 @@ export function localUrl(value) {
27
26
  return url;
28
27
  }
29
28
 
29
+ function responseBody(response) {
30
+ const iterator = response[Symbol.asyncIterator]();
31
+ return {
32
+ [Symbol.asyncIterator]() { return this; },
33
+ next: () => iterator.next(),
34
+ return() {
35
+ // An iterator return waits behind a pending read. Destroy the HTTP stream first.
36
+ response.destroy();
37
+ return iterator.return();
38
+ },
39
+ };
40
+ }
41
+
30
42
  // node:http does not inherit proxy environment settings. Every MCP request stays on loopback.
31
43
  export async function localFetch(input, init) {
32
44
  const prepared = new Request(input, init);
@@ -42,7 +54,7 @@ export async function localFetch(input, init) {
42
54
  return;
43
55
  }
44
56
  try {
45
- resolve(new Response([204, 304].includes(res.statusCode) ? null : Readable.toWeb(res), {
57
+ resolve(new Response([204, 304].includes(res.statusCode) ? null : responseBody(res), {
46
58
  status: res.statusCode, headers: new Headers(Object.entries(res.headers)
47
59
  .flatMap(([key, value]) => Array.isArray(value) ? value.map(item => [key, item]) : value === undefined ? [] : [[key, value]])),
48
60
  }));
package/src/commands.mjs CHANGED
@@ -14,7 +14,7 @@ export const COMMANDS = {
14
14
  create: { options: [...waiting, "title", "parent"], summary: "Start a task",
15
15
  help: ['qz create "PROMPT" [--title TITLE] [--wait | --stream]', "Start a browser task. The title is optional.",
16
16
  "--title, -t Set the task title. --parent TASK_ID creates a child task.",
17
- "--wait Wait for completion, including pauses for user input.", "--stream Show responses as they arrive; also wait.",
17
+ "--wait Follow the task across runs until its work completes and accepted message queues are empty; user-input pauses keep waiting.", "--stream Show responses as they arrive; also wait.",
18
18
  "Use - as the prompt to read stdin.",
19
19
  'qz create "Compare these two pages." --stream', 'qz create "Summarize this page." --title Research --wait'],
20
20
  },
@@ -22,7 +22,8 @@ export const COMMANDS = {
22
22
  help: ['qz send TASK_ID "MESSAGE" [--steer] [--wait | --stream]', "Send a follow-up or steer a specific task.",
23
23
  "A busy task queues a follow-up for its next run. --steer delivers the message to the current run at its next safe boundary.",
24
24
  "Both start a new run when the task is idle. Pending questions and permissions still require a response.",
25
- "Use - as the message to read stdin. --wait follows the submitted message; --stream also shows its responses.",
25
+ "Use - as the message to read stdin. --wait follows the task until its work completes and queues are empty; removed queued messages no longer block completion.",
26
+ "--stream also shows responses from this message onward, including later runs.",
26
27
  'qz send TASK_ID "Add the source links." --stream', 'qz send TASK_ID "Focus on open-source options." --steer --stream'],
27
28
  },
28
29
  tasks: { options: [...request, "limit"], summary: "List tasks",
@@ -32,19 +33,20 @@ export const COMMANDS = {
32
33
  help: ["qz show TASK_ID", "Show task status, the latest response, and any pending form or permission request.", "Pending input includes field IDs, option values, and a submission template. Use --json for the complete snapshot.", "qz show TASK_ID --json"],
33
34
  },
34
35
  watch: { options: [...request, "stream"], summary: "Wait for a task",
35
- help: ["qz watch TASK_ID [--stream]", "Wait for an existing task to finish, including pauses for user input.", "--stream Show assistant responses as they arrive.", "Timeout or Ctrl-C ends watching without cancelling the task."],
36
+ help: ["qz watch TASK_ID [--stream]", "Follow an existing task across runs until its work completes and accepted message queues are empty; user-input pauses keep waiting.", "--stream Show assistant responses as they arrive.", "Task failure or stopping ends observation. Timeout or Ctrl-C ends watching without cancelling the task.", "Resume with the returned watch command for the same task and browser; observation never resends messages."],
36
37
  },
37
38
  submit: { options: [...waiting, "wait-id"], summary: "Answer a form",
38
39
  help: ["qz submit TASK_ID JSON [--wait | --stream]", "Submit answers to the current form. Use - to read JSON from stdin.",
39
40
  "--wait-id ID Bind the response to a previously read wait. Otherwise qz reads the current wait before submitting.",
41
+ "--wait and --stream follow the task across runs until its work completes and accepted message queues are empty.",
40
42
  'qz submit TASK_ID \'{"selectedIds":["option-a"]}\' --stream'],
41
43
  },
42
44
  approve: { options: [...waiting, "wait-id"], summary: "Continue a waiting task",
43
45
  help: ["qz approve TASK_ID [--wait | --stream]", "Continue after completing a requested action.",
44
- "Review app consent notices with qz show before approving. Native browser permissions require a click in the qz side panel.", "--wait-id ID Respond only to this wait."],
46
+ "Review app consent notices with qz show before approving. Native browser permissions require a click in the qz side panel.", "--wait-id ID Respond only to this wait.", "--wait and --stream follow the task across runs until its work completes and accepted message queues are empty."],
45
47
  },
46
48
  reject: { options: [...waiting, "wait-id"], summary: "Decline a pending request",
47
- help: ["qz reject TASK_ID [--wait-id ID] [--wait | --stream]", "Decline the pending request and optionally follow the task's next step. Use qz cancel TASK_ID to stop the whole task."],
49
+ help: ["qz reject TASK_ID [--wait-id ID] [--wait | --stream]", "Decline the pending request. --wait and --stream follow the task across runs until its work completes and accepted message queues are empty. Use qz cancel TASK_ID to stop the whole task."],
48
50
  },
49
51
  cancel: { options: request, summary: "Stop a task",
50
52
  help: ["qz cancel TASK_ID", "Stop a task's active run.", "qz stop stops the local service instead."],
@@ -1,16 +1,24 @@
1
1
  import { setTimeout as delay } from "node:timers/promises";
2
2
 
3
- const STOP_STATUSES = new Set(["completed", "error", "failed", "aborted", "cancelled", "interrupted"]);
3
+ const FAILURE_STATUSES = new Set(["error", "failed", "aborted", "cancelled", "interrupted"]);
4
4
  const ACTIVE_STATUSES = new Set(["pending", "running", "waiting_user", "paused"]);
5
5
  const INPUT_STATUSES = new Set(["waiting_user", "paused"]);
6
+ const QUEUE_FIELDS = ["pendingFollowUps", "pendingFollowUpMessages", "pendingSteerings", "pendingSteeringMessages"];
6
7
  const record = value => value && typeof value === "object" && !Array.isArray(value) ? value : {};
7
8
 
9
+ export const TASK_NOT_FOUND_MESSAGE = "The task was not found in the selected browser. It may have been deleted, the task ID may be incorrect, or a different browser may be selected.";
10
+
8
11
  function taskStatus(snapshot) {
9
12
  const status = String(snapshot.status || snapshot.runtime?.status || snapshot.state?.status || "").trim();
10
13
  if (status === "waitingUser") return "waiting_user";
11
14
  return status.toLowerCase() === "canceled" ? "cancelled" : status.toLowerCase();
12
15
  }
13
16
 
17
+ function hasPendingWork(runtime) {
18
+ return runtime.running === true || runtime.pendingStart === true
19
+ || QUEUE_FIELDS.some(key => Array.isArray(runtime[key]) && runtime[key].length > 0);
20
+ }
21
+
14
22
  function assistantText(content) {
15
23
  if (typeof content === "string") return content;
16
24
  return Array.isArray(content) ? content.filter(part => part?.type === "text")
@@ -35,12 +43,13 @@ function abortable(operation, signal) {
35
43
  }
36
44
 
37
45
  /** Observe snapshots only: timeout, interruption, and polling failures never cancel or restart a browser task.
46
+ * Follow one Session across runs until execution and its accepted queues are finished.
38
47
  * User input pauses execution, not observation; input events expose each pending request.
39
48
  * Total observation is unlimited by default; each snapshot request has its own finite deadline.
40
49
  * getSnapshot must request compact:false and tail:false so transcript identities and streaming text survive.
41
50
  */
42
51
  export async function waitForTask({ sessionId, clientId, timeoutSeconds = null, requestTimeoutSeconds = 180, signal, getSnapshot, onUpdate,
43
- pollIntervalMs = 750, expectedRunId = "", expectedMessageId = "", previousRunId = "", ignoreWaitId = "", allowIdle = false } = {}) {
52
+ pollIntervalMs = 750, expectedRunId = "", expectedMessageId = "", messageWasQueued = false, ignoreWaitId = "", allowIdle = false } = {}) {
44
53
  if (!String(sessionId || "").trim()) throw new TypeError("sessionId is required");
45
54
  if (typeof getSnapshot !== "function") throw new TypeError("getSnapshot is required");
46
55
  if (timeoutSeconds !== null && (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0)) throw new TypeError("timeoutSeconds must be positive or null");
@@ -55,8 +64,8 @@ export async function waitForTask({ sessionId, clientId, timeoutSeconds = null,
55
64
  if (deadline !== null && Date.now() >= deadline) controller.abort(timeout);
56
65
  activeSignal.throwIfAborted();
57
66
  };
58
- const pollingDelay = () => delay(deadline === null ? pollIntervalMs : Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())),
59
- undefined, { signal: activeSignal });
67
+ // The total deadline cancels this sleep; shortening it can wake before that deadline.
68
+ const pollingDelay = () => delay(pollIntervalMs, undefined, { signal: activeSignal });
60
69
  const readSnapshot = async () => {
61
70
  checkActive();
62
71
  const milliseconds = Math.max(1, Math.ceil(requestTimeoutSeconds * 1000));
@@ -84,12 +93,11 @@ export async function waitForTask({ sessionId, clientId, timeoutSeconds = null,
84
93
  }
85
94
  };
86
95
  const messages = new Map();
87
- let selectedRunId = String(expectedRunId || "");
88
- let observedRun = false;
96
+ let firstRunId = String(expectedRunId || "");
97
+ let trackingReady = false;
89
98
  let observedActivity = false;
90
99
  let awaitingMessage = Boolean(expectedMessageId);
91
- let messageRunId = "";
92
- let awaitingResume = Boolean(ignoreWaitId);
100
+ let observedQueuedMessage = messageWasQueued;
93
101
  let lastStatus = "";
94
102
  let lastInput = "";
95
103
  const emit = async update => {
@@ -122,7 +130,7 @@ export async function waitForTask({ sessionId, clientId, timeoutSeconds = null,
122
130
  throw Object.assign(new Error("The task snapshot belongs to a different session."), { code: "task_changed" });
123
131
  }
124
132
  if (Object.hasOwn(snapshot, "session") && snapshot.session === null) {
125
- throw Object.assign(new Error("The task was deleted while waiting for its result."), { code: "task_deleted" });
133
+ throw Object.assign(new Error(TASK_NOT_FOUND_MESSAGE), { code: "task_deleted" });
126
134
  }
127
135
  const runtime = record(snapshot.runtime);
128
136
  const canonicalInput = Object.hasOwn(snapshot, "input") ? record(snapshot.input) : null;
@@ -135,67 +143,63 @@ export async function waitForTask({ sessionId, clientId, timeoutSeconds = null,
135
143
  const transcript = Array.isArray(snapshot.transcript) ? snapshot.transcript : Array.isArray(snapshot.tail) ? snapshot.tail : [];
136
144
  const submittedMessageIndex = expectedMessageId
137
145
  ? transcript.findIndex(entry => entry?.type === "user" && entry.clientMessageId === expectedMessageId) : -1;
138
- if (awaitingMessage) {
139
- const message = transcript[submittedMessageIndex];
140
- if (message?.runId) {
141
- messageRunId = String(message.runId);
142
- selectedRunId = messageRunId;
143
- awaitingMessage = false;
144
- } else {
145
- // A queued message may wait behind an earlier run's question or permission.
146
- // Keep that input actionable, but never mistake its answer for this message's result.
147
- if (status !== "completed") await emitStatus(status, runId, runtime);
148
- await emitInput(status, runId, runtime, canonicalInput);
149
- if (STOP_STATUSES.has(status) && status !== "completed") return snapshot;
150
- await pollingDelay();
151
- continue;
152
- }
146
+ if (awaitingMessage && QUEUE_FIELDS.some(key => Array.isArray(runtime[key])
147
+ && runtime[key].some(message => message?.clientMessageId === expectedMessageId))) observedQueuedMessage = true;
148
+ const submittedMessage = transcript[submittedMessageIndex];
149
+ if (awaitingMessage && submittedMessage?.runId) {
150
+ firstRunId = String(submittedMessage.runId);
151
+ awaitingMessage = false;
153
152
  }
154
- const previous = previousRunId && (!runId || runId === previousRunId);
155
- const awaitedRunId = messageRunId || expectedRunId;
156
- const awaitingExpected = awaitedRunId && runId !== awaitedRunId;
157
153
  const targetIndex = submittedMessageIndex >= 0 ? submittedMessageIndex
158
- : awaitedRunId ? transcript.findIndex(entry => entry?.runId === awaitedRunId) : -1;
159
- // A fast queued run can finish before the first poll. A later accepted user message
160
- // distinguishes that replacement from an older runtime snapshot still catching up.
161
- const passedTarget = awaitingExpected && runId && targetIndex >= 0
154
+ : firstRunId ? transcript.findIndex(entry => entry?.runId === firstRunId) : -1;
155
+ // The runtime can lag the transcript or skip whole runs between polls. Admit the
156
+ // target run or a proven successor once, then follow the Session without a run fence.
157
+ const passedTarget = runId && targetIndex >= 0
162
158
  && transcript.slice(targetIndex + 1).some(entry => entry?.type === "user" && entry.runId === runId);
163
- if ((observedRun && runId && selectedRunId !== runId) || passedTarget) {
164
- throw Object.assign(new Error("A different run replaced the task being watched. Use qz show to inspect its conversation."), {
165
- code: "task_changed", details: { expectedRunId: selectedRunId || awaitedRunId, actualRunId: runId },
166
- });
159
+ // Resolving a wait and persisting its updated snapshot are separate operations.
160
+ // Ignore that exact old wait even while its runtime lags the acknowledged run.
161
+ const oldWait = !trackingReady && ignoreWaitId && status === "waiting_user" && String(canonicalInput?.waitId || runtime.waitId || "") === ignoreWaitId;
162
+ if (oldWait) {
163
+ await pollingDelay();
164
+ continue;
167
165
  }
168
- if (!previous && !awaitingExpected) {
169
- if (runId) { selectedRunId = runId; observedRun = true; }
170
- // Resolving a wait and persisting its updated snapshot are separate operations.
171
- // Ignore that exact old wait until the resumed run or its next wait is visible.
172
- const oldWait = awaitingResume && status === "waiting_user" && String(canonicalInput?.waitId || runtime.waitId || "") === ignoreWaitId;
173
- if (oldWait) {
174
- await pollingDelay();
175
- continue;
176
- }
177
- awaitingResume = false;
178
- if (ACTIVE_STATUSES.has(status)) observedActivity = true;
179
- await emitStatus(status, runId, runtime);
180
- for (const [index, entry] of transcript.entries()) {
181
- // Steering can continue the same run. Only stream responses after this submitted message.
182
- if (expectedMessageId && (submittedMessageIndex < 0 || index <= submittedMessageIndex)) continue;
183
- if (entry?.type !== "assistant" || (entry.runId && selectedRunId && entry.runId !== selectedRunId)) continue;
184
- const messageId = messageIdentity(entry, index, selectedRunId);
185
- const fullText = assistantText(entry.content);
186
- const seen = messages.has(messageId);
187
- const previousText = messages.get(messageId) || "";
188
- if (fullText === previousText) continue;
189
- messages.set(messageId, fullText);
190
- const append = fullText.startsWith(previousText);
191
- await emit({ type: append ? "text" : "replace", sessionId, runId: String(entry.runId || runId), messageId,
192
- text: append ? fullText.slice(previousText.length) : fullText, fullText,
193
- newMessage: !seen, streaming: entry.streaming === true });
194
- }
166
+ if (!trackingReady && (awaitingMessage || (firstRunId && runId !== firstRunId && !passedTarget))) {
167
+ // Queue acceptance precedes these reads; pending precedes dequeue. A settled
168
+ // task with no trace of an accepted queued message means it was removed.
169
+ const removedMessage = awaitingMessage && observedQueuedMessage && submittedMessageIndex < 0
170
+ && status === "completed" && !hasPendingWork(runtime);
171
+ // A queued message can wait behind another run's question. Keep it actionable,
172
+ // but do not emit its earlier answer or accept its successful completion.
173
+ if (status !== "completed" || removedMessage) await emitStatus(status, runId, runtime);
195
174
  await emitInput(status, runId, runtime, canonicalInput);
196
- // A newly created session can report idle before its first run starts.
197
- if (STOP_STATUSES.has(status) || (status === "idle" && (observedActivity || allowIdle))) return snapshot;
175
+ if (FAILURE_STATUSES.has(status) || removedMessage) return snapshot;
176
+ await pollingDelay();
177
+ continue;
178
+ }
179
+ trackingReady = true;
180
+ if (!firstRunId && runId) firstRunId = runId;
181
+ if (ACTIVE_STATUSES.has(status)) observedActivity = true;
182
+ await emitStatus(status, runId, runtime);
183
+ for (const [index, entry] of transcript.entries()) {
184
+ // Steering can continue the same run. Only stream responses after this submitted message.
185
+ if (expectedMessageId && (submittedMessageIndex < 0 || index <= submittedMessageIndex)) continue;
186
+ if (entry?.type !== "assistant") continue;
187
+ if (!expectedMessageId && (targetIndex >= 0 ? index < targetIndex : entry.runId && entry.runId !== runId)) continue;
188
+ const messageId = messageIdentity(entry, index, firstRunId);
189
+ const fullText = assistantText(entry.content);
190
+ const seen = messages.has(messageId);
191
+ const previousText = messages.get(messageId) || "";
192
+ if (fullText === previousText) continue;
193
+ messages.set(messageId, fullText);
194
+ const append = fullText.startsWith(previousText);
195
+ await emit({ type: append ? "text" : "replace", sessionId, runId: String(entry.runId || runId), messageId,
196
+ text: append ? fullText.slice(previousText.length) : fullText, fullText,
197
+ newMessage: !seen, streaming: entry.streaming === true });
198
198
  }
199
+ await emitInput(status, runId, runtime, canonicalInput);
200
+ // A newly created session can report idle before its first run starts.
201
+ if (FAILURE_STATUSES.has(status) || (!hasPendingWork(runtime)
202
+ && (status === "completed" || (status === "idle" && (observedActivity || allowIdle))))) return snapshot;
199
203
  await pollingDelay();
200
204
  }
201
205
  } catch (error) {
package/src/terminal.mjs CHANGED
@@ -7,7 +7,9 @@ const palette = { accent: 36, muted: 90, error: 31, waiting: 33 };
7
7
 
8
8
  // Remote pages and model responses are text, never terminal instructions.
9
9
  export function sanitizeTerminalText(value) {
10
- return stripVTControlCharacters(String(value ?? ""))
10
+ // Early Node 22 versions do not strip OSC strings terminated by ESC + backslash.
11
+ const text = String(value ?? "").replace(/(?:\u001b\]|\u009d)[\s\S]*?(?:\u0007|\u001b\\|\u009c|$)/g, "");
12
+ return stripVTControlCharacters(text)
11
13
  .replace(/\r\n?/g, "\n")
12
14
  .replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "")
13
15
  .replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "")
package/src/tools.mjs CHANGED
@@ -78,7 +78,7 @@ async function executeBrowserTool(state, name, args, { signal, connectionSignal,
78
78
  if (remaining !== null && remaining <= 0) throw new DOMException("Stopped watching after waitTimeoutSeconds. The browser task may still be running.", "TimeoutError");
79
79
  return await waitForTask({ sessionId, clientId: args.clientId, signal, timeoutSeconds: remaining,
80
80
  requestTimeoutSeconds: args.timeoutSeconds || state.requestTimeoutSeconds || 180,
81
- expectedRunId: tracking.runId, expectedMessageId: tracking.clientMessageId,
81
+ expectedRunId: tracking.runId, expectedMessageId: tracking.clientMessageId, messageWasQueued: tracking.disposition === "queued",
82
82
  ignoreWaitId: tracking.ignoreWaitId, allowIdle: tracking.allowIdle,
83
83
  onUpdate: onTaskUpdate && (event => args.stream || !["text", "replace"].includes(event.type) ? onTaskUpdate(event) : undefined),
84
84
  getSnapshot: async ({ signal: requestSignal, timeoutSeconds }) => bindInputClient("qingzhou_get_session_snapshot",
@@ -91,8 +91,10 @@ async function executeBrowserTool(state, name, args, { signal, connectionSignal,
91
91
  : cause.name === "TimeoutError" ? "timeout" : cause.name === "AbortError" ? "interrupted" : "task_wait_failed";
92
92
  const error = Object.assign(new Error(cause.message, { cause }), { code });
93
93
  error.details = { ...cause.details, sessionId, clientId: args.clientId,
94
- recovery: { tool: code === "task_changed" ? "qingzhou_get_session_snapshot" : "qingzhou_watch_task",
95
- arguments: { sessionId, clientId: args.clientId } } };
94
+ recovery: code === "task_deleted"
95
+ ? { tool: "qingzhou_list_sessions", arguments: { clientId: args.clientId } }
96
+ : { tool: code === "task_changed" ? "qingzhou_get_session_snapshot" : "qingzhou_watch_task",
97
+ arguments: { sessionId, clientId: args.clientId } } };
96
98
  throw error;
97
99
  }
98
100
  };
@@ -138,9 +140,11 @@ async function executeBrowserTool(state, name, args, { signal, connectionSignal,
138
140
  result = { ...result, snapshot: await watch(sessionId, { allowIdle: !args.firstMessage.trim() }) };
139
141
  } else if (name === "qingzhou_send_message" && result?.accepted === true) {
140
142
  if (typeof result.clientMessageId !== "string" || !result.clientMessageId.trim()) {
141
- throw new BridgeError("invalid_response", "The message was accepted without a tracking ID. Inspect the task before sending it again.");
143
+ throw Object.assign(new BridgeError("invalid_response", "The message was accepted without a tracking ID. Continue watching the same task before sending it again."), {
144
+ details: { sessionId, clientId, recovery: { tool: "qingzhou_watch_task", arguments: { sessionId, clientId } } },
145
+ });
142
146
  }
143
- result = { ...result, snapshot: await watch(sessionId, { clientMessageId: result.clientMessageId }) };
147
+ result = { ...result, snapshot: await watch(sessionId, { clientMessageId: result.clientMessageId, disposition: result.disposition }) };
144
148
  } else if (name === "qingzhou_respond_to_user_input" && (result?.accepted === true || result?.requiresUserAction)) {
145
149
  const snapshot = await watch(sessionId, { runId: result.runId || "", ignoreWaitId: result.requiresUserAction ? "" : args.waitId });
146
150
  result = result.requiresUserAction ? { sessionId, waitId: args.waitId, snapshot } : { ...result, snapshot };