@cydm/pie 2.7.20 → 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +18 -0
  2. package/dist/builtin/extensions/ask-user/README.md +117 -0
  3. package/dist/builtin/extensions/ask-user/index.js +4 -3
  4. package/dist/builtin/extensions/cron/index.js +299 -39
  5. package/dist/builtin/extensions/im-forward/README.md +297 -0
  6. package/dist/builtin/extensions/im-forward/index.js +315 -27
  7. package/dist/builtin/extensions/mcp-adapter/README.md +27 -0
  8. package/dist/builtin/extensions/memory/index.js +515 -0
  9. package/dist/builtin/extensions/memory/package.json +19 -0
  10. package/dist/builtin/extensions/pie-ipc/README.md +21 -0
  11. package/dist/builtin/extensions/plan-mode/METHOD.md +70 -0
  12. package/dist/builtin/extensions/plan-mode/index.js +150 -82
  13. package/dist/builtin/extensions/subagent/README.md +315 -0
  14. package/dist/builtin/extensions/subagent/index.js +8 -5
  15. package/dist/builtin/extensions/todo/index.js +4 -3
  16. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +1 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  18. package/dist/builtin/skills/chrome-devtools-axi/{chunk-U75F4DPF.js → chunk-BNSAEVRT.js} +201 -77
  19. package/dist/builtin/skills/chrome-devtools-axi/{cli-4ITIR57L.js → cli-AO2ZTPRM.js} +57 -202
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +6 -1
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +6 -1
  22. package/dist/chunks/auth-storage-3EGM3VTK.js +13 -0
  23. package/dist/chunks/{chunk-X7UO6BA6.js → chunk-3BC5KGDQ.js} +451 -162
  24. package/dist/chunks/chunk-3NHP7HK5.js +298 -0
  25. package/dist/chunks/chunk-6DNYGVZP.js +278 -0
  26. package/dist/chunks/{chunk-TGCI5M6R.js → chunk-GDIYSMTS.js} +22 -142
  27. package/dist/chunks/{chunk-2H2DD22Z.js → chunk-GH4VW2OT.js} +1 -1
  28. package/dist/chunks/chunk-ILUHTKF3.js +149 -0
  29. package/dist/chunks/{chunk-UDCGB3LZ.js → chunk-PK72LVWQ.js} +11841 -16501
  30. package/dist/chunks/chunk-RSL7E4R7.js +9634 -0
  31. package/dist/chunks/chunk-YRR6C43W.js +1740 -0
  32. package/dist/chunks/config-74AUVDLT.js +46 -0
  33. package/dist/chunks/model-registry-LI5THXV4.js +17 -0
  34. package/dist/chunks/src-66XSMIAM.js +134 -0
  35. package/dist/chunks/src-BPSQMSSC.js +431 -0
  36. package/dist/chunks/src-OPPYTPWG.js +285 -0
  37. package/dist/chunks/{src-GX4UBAYF.js → src-YG5M2H44.js} +2 -2
  38. package/dist/chunks/{test-stream-AKIZNFCM.js → test-stream-JBWXKOQA.js} +1 -1
  39. package/dist/cli.js +986 -2292
  40. package/package.json +3 -3
@@ -0,0 +1,315 @@
1
+ # Subagent Extension for Pie - Transparent Parallel Execution
2
+
3
+ Spawn child AI agents that run in **parallel** with **full visibility** via Ctrl+O.
4
+
5
+ ## 🚀 What's New: Transparent Parallelism
6
+
7
+ ### Problem with Old Approach
8
+ ```
9
+ 串行执行: A(5s) → B(5s) → C(5s) = 15s
10
+ 轮询等待: 污染上下文,多次 tool call
11
+ ```
12
+
13
+ ### New Approach: Parallel + Transparent
14
+ ```
15
+ 有界并行: 默认最多 4 个运行,其余排队;耗时取决于任务和服务限制
16
+ 透明可见: 每个子 agent 在独立 Tool 组件中,Ctrl+O 展开查看
17
+ 工具继承: 从父 agent 当前工具集继承,再由 runtime 过滤高风险写入/副作用工具
18
+ ```
19
+
20
+ ## Recommended Tool: `spawn_subagents_parallel`
21
+
22
+ Spawn multiple subagents that run in parallel with real-time progress updates.
23
+
24
+ ### Usage
25
+
26
+ ```typescript
27
+ spawn_subagents_parallel({
28
+ tasks: [
29
+ { name: "Beijing", task: "Query current weather in Beijing" },
30
+ { name: "Shanghai", task: "Query current weather in Shanghai" },
31
+ { name: "Shenzhen", task: "Query current weather in Shenzhen" }
32
+ ]
33
+ })
34
+ ```
35
+
36
+ ### What You See
37
+
38
+ **In the UI (collapsed)**:
39
+ ```
40
+ 🚀 Launching 3 parallel subagents...
41
+ ```
42
+
43
+ **Press Ctrl+O to expand**:
44
+ ```
45
+ 🚀 Launching 3 parallel subagents...
46
+ ├── [Beijing] 🚀 Starting...
47
+ ├── [Beijing] 💭 Thinking...
48
+ ├── [Beijing] 🔧 Using weather_query...
49
+ ├── [Beijing] ✅ Completed (2456ms, 1 tools)
50
+ ├── [Shanghai] 🚀 Starting...
51
+ ├── [Shanghai] 💭 Thinking...
52
+ ├── [Shanghai] 🔧 Using weather_query...
53
+ ├── [Shanghai] ✅ Completed (2890ms, 1 tools)
54
+ ├── [Shenzhen] 🚀 Starting...
55
+ ├── [Shenzhen] 💭 Thinking...
56
+ ├── [Shenzhen] 🔧 Using weather_query...
57
+ └── [Shenzhen] ✅ Completed (2100ms, 1 tools)
58
+ ```
59
+
60
+ **Final Result**:
61
+ ```
62
+ 📊 Parallel Subagent Results (3 tasks, 5200ms)
63
+ ============================================================
64
+
65
+ ✅ **Beijing** (2456ms, 1 tools)
66
+ Current weather in Beijing: 22°C, partly cloudy, humidity 45%.
67
+
68
+ ✅ **Shanghai** (2890ms, 1 tools)
69
+ Current weather in Shanghai: 25°C, sunny, humidity 60%.
70
+
71
+ ✅ **Shenzhen** (2100ms, 1 tools)
72
+ Current weather in Shenzhen: 28°C, sunny, humidity 75%.
73
+
74
+ ============================================================
75
+ Summary: 3 completed, 0 failed, 5200ms total
76
+ ```
77
+
78
+ ### Features
79
+
80
+ | Feature | Description |
81
+ |---------|-------------|
82
+ | ⚡ **Parallel Execution** | Bounded worker pool: default 4 concurrent tasks; remaining tasks queue |
83
+ | 👁️ **Full Transparency** | Press Ctrl+O to see each subagent's progress |
84
+ | 🛠️ **Tool Inheritance** | Subagents inherit parent tools, with write/high-risk tools filtered by runtime policy |
85
+ | 📊 **Real-time Updates** | Progress shown via `reportProgress` (no context pollution) |
86
+ | 🎯 **Named Tasks** | Each subagent has a name for easy tracking |
87
+ | ⚠️ **Error Isolation** | One subagent failing doesn't affect others |
88
+
89
+ ### Parameters
90
+
91
+ ```typescript
92
+ {
93
+ tasks: Array<{
94
+ task: string; // The bounded task for this subagent
95
+ mode?: "read" | "edit"; // Default read; edit calls contain exactly one task
96
+ name?: string; // Short name (shown in progress)
97
+ priority?: "fast" | "thorough"; // Optional routing hint
98
+ model?: string; // Optional explicit model override, e.g. "anthropic/claude-..." (user-requested only)
99
+ thinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh"; // Reasoning level; default "medium"
100
+ timeout?: number; // Timeout in seconds; default 1200s
101
+ sessionId?: string; // Resume a previous subagent session (from an earlier result's Session line)
102
+ resumeMode?: "full" | "report"; // Default full; report carries only the latest valid historical report
103
+ }>;
104
+ }
105
+ ```
106
+
107
+ ### Sessions (Resumable Subagents)
108
+
109
+ Every started task's result ends with a `Session: <id>` line. Pass that id as
110
+ `sessionId` in a later call to **continue the same subagent**. The default
111
+ `resumeMode: "full"` retains its accumulated transcript; `"report"` rebuilds
112
+ with current tools/model/credentials and only the latest valid historical
113
+ report as data plus the new task:
114
+
115
+ ```typescript
116
+ // Round 1: investigation
117
+ spawn_subagents_parallel({ tasks: [{ name: "Review", task: "Review the auth module" }] });
118
+ // → Session: subagent-abc-1 (resumable ...)
119
+
120
+ // Round 2: the SAME subagent, full context retained, applies its own findings
121
+ spawn_subagents_parallel({
122
+ tasks: [{ task: "Apply the fix you recommended", sessionId: "subagent-abc-1", mode: "edit" }]
123
+ });
124
+ ```
125
+
126
+ Semantics:
127
+
128
+ - **Recall modes**: `full` is the default and retains historical input with
129
+ unknown cost. `report` excludes the old transcript and fails closed when no
130
+ latest valid report is available; it never silently falls back to an older
131
+ report or full history. Historical reports are data to re-verify, not
132
+ instructions.
133
+ - **Reconfigure on recall**: `mode` (including read→edit upgrades), `model`,
134
+ and `thinkingLevel` passed on a recall REPLACE the session's config; tools
135
+ and credentials are re-resolved from the parent's CURRENT state (an edit
136
+ upgrade re-runs the full edit guard — plan mode blocks it). An unresolvable
137
+ model override keeps the session's previous model and reports a fallback.
138
+ - **Persistence**: sessions are kept in memory (LRU, 8) and persisted to
139
+ `~/.pie/subagent-sessions/<id>.json`, so a sessionId survives restarts and
140
+ `/resume`. Records older than 7 days or beyond 64 are swept. Only the
141
+ transcript and config are stored — never API keys or tool instances.
142
+ - **No whole-task replay**: fresh and recalled tasks never automatically
143
+ restart on failure. Recovery retries only the current response. A session
144
+ runs one task at a time; duplicate `sessionId`s in one batch are rejected.
145
+ - **When NOT to recall**: full recall carries the whole transcript, so cost
146
+ grows per round, and accumulated context anchors judgment — prefer a fresh
147
+ task for independent reviews. Report recall is a lower-context continuation,
148
+ not an independent review. Results include a growth warning when a session's
149
+ transcript passes 240,000 JSON characters (not billing tokens).
150
+
151
+ ### Thinking Level
152
+
153
+ Subagents reason at `medium` by default (non-reasoning models ignore the
154
+ setting). Pass `thinkingLevel` per task when the user asks — `"xhigh"` for
155
+ deep review or debugging work, `"off"` for cheap lookup-style tasks:
156
+
157
+ ```typescript
158
+ spawn_subagents_parallel({
159
+ tasks: [
160
+ { name: "Deep review", task: "Review the auth module", thinkingLevel: "xhigh" },
161
+ { name: "Quick scan", task: "List TODO markers", thinkingLevel: "off" }
162
+ ]
163
+ })
164
+ ```
165
+
166
+ The effective level is recorded in the task plan and echoed in the result
167
+ header when it differs from the default (`thinking=xhigh`).
168
+
169
+ ### Model Override
170
+
171
+ By default Pie picks each subagent's model automatically from the task's
172
+ complexity (`priority` → model class `light`/`balanced`/`strong` from
173
+ `models.json` `defaults.modelClasses`). When the **user explicitly asks for a
174
+ specific model**, pass it as a per-task `model` override:
175
+
176
+ ```typescript
177
+ spawn_subagents_parallel({
178
+ tasks: [
179
+ { name: "Deep review", task: "Review the auth module", model: "anthropic/claude-sonnet-4" },
180
+ { name: "Quick scan", task: "List TODO markers", priority: "fast" }
181
+ ]
182
+ })
183
+ ```
184
+
185
+ - `"provider/model-id"` resolves against the configured profiles in
186
+ `models.json`; a bare model id works only when it is unambiguous across
187
+ providers.
188
+ - The override is applied only when both the model **and its own API key**
189
+ resolve, so a model is never paired with another provider's credentials.
190
+ - If the override cannot be resolved (missing model, no key, ambiguous id),
191
+ the task falls back to automatic selection and the result explains why
192
+ (`model=<ref> (unresolved, fell back)` plus a `model_fallback` signal).
193
+
194
+ ## How It Works
195
+
196
+ ```
197
+ Parent Agent
198
+ │
199
+ ▼ calls spawn_subagents_parallel
200
+ │
201
+ ├─► Bounded worker pool (default 4 slots)
202
+ │ pending tasks → available slot → next pending task
203
+ │ host maxConcurrentSubagents can override the limit
204
+ │
205
+ Each subagent (pending → running → completed/failed):
206
+ - Own Agent instance and context
207
+ - Inherits parent tools after runtime policy filtering
208
+ - Reports progress via onUpdate
209
+ - Visible in Tool component (Ctrl+O)
210
+ │
211
+ ▼
212
+ Merged result returned
213
+ ```
214
+
215
+ ## Progress Icons
216
+
217
+ | Icon | Meaning |
218
+ |------|---------|
219
+ | 🚀 | Starting |
220
+ | 💭 | Thinking/Generating |
221
+ | 🔧 | Using a tool |
222
+ | ✅ | Completed |
223
+ | ❌ | Failed |
224
+
225
+ ## Performance
226
+
227
+ | Scenario | Serial (Old) | Parallel (New) | Speedup |
228
+ |----------|-------------|----------------|---------|
229
+ | 3 weather queries | ~15s | ~5s | **3x** |
230
+ | 5 file analysis | ~50s | ~12s | **4x** |
231
+ | 10 code reviews (4 slots) | ~100s | ~30s | **~3.3x** |
232
+
233
+ *Illustrative estimates, not measured guarantees. Actual speedup depends on task duration, the concurrency limit and API response times.*
234
+
235
+ ## Error Handling
236
+
237
+ If one subagent fails, others continue:
238
+ ```
239
+ ✅ **Task A** - Success
240
+ ✅ **Task B** - Success
241
+ ❌ **Task C** - Failed: API timeout
242
+ ```
243
+
244
+ ## Best Practices
245
+
246
+ 1. **Use descriptive names**: `{ name: "AuthAnalysis", ... }` not `{ name: "Task1", ... }`
247
+ 2. **Bound concurrency**: Up to 10 tasks per call by default, but only 4 run concurrently by default (host-configurable); remaining tasks queue
248
+ 3. **Keep tasks focused**: Each subagent should have one clear goal
249
+ 4. **Batch in one call**: Submit all tasks in a single `spawn_subagents_parallel` call instead of one call per task
250
+ 5. **Check results**: Always verify the merged output
251
+
252
+ ## Common Patterns
253
+
254
+ **Parallel analysis of several files**
255
+ ```typescript
256
+ spawn_subagents_parallel({
257
+ tasks: [
258
+ { name: "auth", task: "Audit src/auth.ts for security issues" },
259
+ { name: "user", task: "Audit src/user.ts for security issues" },
260
+ { name: "api", task: "Audit src/api.ts for security issues" }
261
+ ]
262
+ })
263
+ ```
264
+
265
+ **Split a test suite**
266
+ ```typescript
267
+ spawn_subagents_parallel({
268
+ tasks: [
269
+ { name: "unit", task: "Run the unit tests and summarize failures" },
270
+ { name: "integration", task: "Run the integration tests and summarize failures" },
271
+ { name: "e2e", task: "Run the E2E tests and summarize failures" }
272
+ ]
273
+ })
274
+ ```
275
+
276
+ **Batch code review**: list the target files first, then spawn one review task per file in a single call, and merge the findings.
277
+
278
+ ## Migration from the old single-task API
279
+
280
+ Use the parallel API directly:
281
+ ```typescript
282
+ const results = await spawn_subagents_parallel({
283
+ tasks: [
284
+ { name: "Analysis-A", task: "Analyze A" },
285
+ { name: "Analysis-B", task: "Analyze B" }
286
+ ]
287
+ });
288
+ // results.content contains merged output
289
+ ```
290
+
291
+ ## Technical Details
292
+
293
+ - **Task Limit**: 1-10 tasks per call (configurable)
294
+ - **Tool Inheritance**: Default `mode: "read"` cannot edit source. Explicit `mode: "edit"` inherits parent editing/test permissions; an edit call must contain exactly one task, and the parent must wait before editing or launching another edit task. Workspaces are shared, not isolated; review changes and reported tests, with no automatic rollback or edit-task retry.
295
+ - **Concurrency**: Bounded pool, default 4; host `maxConcurrentSubagents` can override it
296
+ - **Timeout**: Default 1200 seconds. For unusually long tasks, set `timeout` in seconds, for example `{ timeout: 3600 }`
297
+ - **Memory**: Each subagent creates its own Agent instance with its own context
298
+ - **Network recovery**: CLI children use the same structured failure classification and bounded retry policy as the main CLI session, including `replayEligible`, `remoteFailure`, one-confirmation semantics, per-kind/shared-total budgets and `Retry-After`. Compatible hosts without an injected policy retain a two-retry default. Recovery retries only the current response with the same committed child/context in read, edit and recall modes; no whole task is automatically replayed. Failed-response tool calls never execute, earlier completed tools/edits are preserved, and actual attempts plus recovery outcome are reported. Cancellation, hard deadlines and deterministic length/config failures are not retried.
299
+ - **Streaming tradeoff**: Child responses are consumed privately until terminal completion; incremental token/tool-argument events are suppressed. Only the terminal response reaches agent-core, so failed partial tool calls cannot execute or leak into child history. Tool progress and task heartbeats remain available. Custom `createAgent` hosts must install the supplied `config.streamFn` to opt in (Unity does); ignoring it disables recovery but does not enable task replay.
300
+ - **Cancellation**: Aborts all subagents if parent tool call is cancelled
301
+
302
+ ## Troubleshooting
303
+
304
+ **Q: Subagent can't find tool X**
305
+ A: Check the parent's tools and the task's runtime policy; read mode filters write/high-risk tools.
306
+
307
+ **Q: Progress not showing**
308
+ A: Press Ctrl+O to expand the tool component. Progress is shown via reportProgress.
309
+
310
+ **Q: Too many API calls**
311
+ A: Reduce the number of parallel tasks or use `priority: "fast"` for lightweight work.
312
+
313
+ ---
314
+
315
+ **Enjoy transparent parallel execution! 🚀**
@@ -4,17 +4,20 @@ import {
4
4
  createCliHostCapabilities,
5
5
  createCliRetryPolicy,
6
6
  formatTransportLifecycle,
7
- getConfigDir,
8
7
  logTransportLifecycle
9
- } from "../../../chunks/chunk-TGCI5M6R.js";
8
+ } from "../../../chunks/chunk-GDIYSMTS.js";
9
+ import {
10
+ getConfigDir
11
+ } from "../../../chunks/chunk-ILUHTKF3.js";
10
12
  import {
11
13
  SUBAGENT_SESSION_RECORD_VERSION,
12
14
  createPolicyEnforcedTools,
13
15
  createSharedFileSystemTools,
14
16
  createSubagentCapability
15
- } from "../../../chunks/chunk-UDCGB3LZ.js";
16
- import "../../../chunks/chunk-2H2DD22Z.js";
17
- import "../../../chunks/chunk-X7UO6BA6.js";
17
+ } from "../../../chunks/chunk-PK72LVWQ.js";
18
+ import "../../../chunks/chunk-RSL7E4R7.js";
19
+ import "../../../chunks/chunk-GH4VW2OT.js";
20
+ import "../../../chunks/chunk-3BC5KGDQ.js";
18
21
  import "../../../chunks/chunk-XXGYUYXI.js";
19
22
  import "../../../chunks/chunk-LZQXQOPJ.js";
20
23
 
@@ -8,9 +8,10 @@ import {
8
8
  executeManageTodoList,
9
9
  executionStateToTodos,
10
10
  restoreExecutionState
11
- } from "../../../chunks/chunk-UDCGB3LZ.js";
12
- import "../../../chunks/chunk-2H2DD22Z.js";
13
- import "../../../chunks/chunk-X7UO6BA6.js";
11
+ } from "../../../chunks/chunk-PK72LVWQ.js";
12
+ import "../../../chunks/chunk-RSL7E4R7.js";
13
+ import "../../../chunks/chunk-GH4VW2OT.js";
14
+ import "../../../chunks/chunk-3BC5KGDQ.js";
14
15
  import "../../../chunks/chunk-XXGYUYXI.js";
15
16
  import "../../../chunks/chunk-LZQXQOPJ.js";
16
17
 
@@ -8,7 +8,7 @@ import {
8
8
  resolveSessionName,
9
9
  resolveSessionPidFile,
10
10
  resolveSessionPort
11
- } from "./chunk-U75F4DPF.js";
11
+ } from "./chunk-BNSAEVRT.js";
12
12
  import {
13
13
  __commonJS,
14
14
  __export,
@@ -21,6 +21,6 @@ function tryFastPath(argv, options) {
21
21
 
22
22
  // vendor/chrome-devtools-axi/bin/chrome-devtools-axi.ts
23
23
  if (!tryFastPath(process.argv.slice(2), { version: VERSION })) {
24
- const { main } = await import("./cli-4ITIR57L.js");
24
+ const { main } = await import("./cli-AO2ZTPRM.js");
25
25
  await main(process.argv.slice(2));
26
26
  }
@@ -1,5 +1,196 @@
1
1
  import { createRequire as __axiRequire } from "node:module"; const require = __axiRequire(import.meta.url);
2
2
 
3
+ // vendor/chrome-devtools-axi/src/pages.ts
4
+ var PAGE_SCOPED_TOOLS = /* @__PURE__ */ new Set([
5
+ "click",
6
+ "drag",
7
+ "emulate",
8
+ "evaluate_script",
9
+ "fill",
10
+ "fill_form",
11
+ "get_console_message",
12
+ "get_network_request",
13
+ "handle_dialog",
14
+ "hover",
15
+ "lighthouse_audit",
16
+ "list_console_messages",
17
+ "list_network_requests",
18
+ "navigate_page",
19
+ "performance_analyze_insight",
20
+ "performance_start_trace",
21
+ "performance_stop_trace",
22
+ "press_key",
23
+ "resize_page",
24
+ "take_heapsnapshot",
25
+ "take_screenshot",
26
+ "take_snapshot",
27
+ "type_text",
28
+ "upload_file",
29
+ "wait_for"
30
+ ]);
31
+ function needsPageId(name, args = {}) {
32
+ if (typeof args.pageId === "number") return false;
33
+ if (name === "evaluate_script" && typeof args.serviceWorkerId === "string" && args.serviceWorkerId.length > 0) {
34
+ return false;
35
+ }
36
+ return PAGE_SCOPED_TOOLS.has(name);
37
+ }
38
+ var GENERIC_SCHEME_SLASH_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
39
+ var COLON_ONLY_SCHEME_URL = /^(?:about:|data:|view-source:|blob:)/i;
40
+ function isPageSchemeUrl(label) {
41
+ return GENERIC_SCHEME_SLASH_URL.test(label) || COLON_ONLY_SCHEME_URL.test(label);
42
+ }
43
+ var MCP_SECTION_HEADER = /^##\s+(Pages|Extension Pages|Extension Service Workers|Third-party developer tools|WebMCP tools)$/;
44
+ var PAGE_ID_LINE = /^\d+:(?:\s+|$)/;
45
+ var OPEN_DIALOG_HEADER = /^# Open dialog$/;
46
+ var HANDLE_DIALOG_FOOTER = /^Call handle_dialog to handle it before continuing\.$/;
47
+ function stripTrailingIsolatedContext(label) {
48
+ const match = label.match(/^(.*)\s+isolatedContext=.*$/);
49
+ if (!match) return label;
50
+ const before = match[1];
51
+ const withoutSelected = before.replace(/\s*\[selected\]\s*$/, "").trimEnd();
52
+ if (matchTrailingUrl(withoutSelected) !== null) return before;
53
+ if (isPageSchemeUrl(withoutSelected)) return before;
54
+ return label;
55
+ }
56
+ function stripPageSuffixes(rest) {
57
+ let label = stripTrailingIsolatedContext(rest);
58
+ if (/(?:^|\s)\[selected\]\s*$/.test(label)) {
59
+ label = label.replace(/\s*\[selected\]\s*$/, "").trimEnd();
60
+ }
61
+ return label;
62
+ }
63
+ function matchTrailingUrl(label) {
64
+ const trimmed = label.trimEnd();
65
+ if (!trimmed.endsWith(")")) return null;
66
+ const close = trimmed.length - 1;
67
+ let from = close;
68
+ while (from > 0) {
69
+ const open = trimmed.lastIndexOf(" (", from - 1);
70
+ if (open === -1) return null;
71
+ const url = trimmed.slice(open + 2, close);
72
+ if (isPageSchemeUrl(url)) {
73
+ return { title: trimmed.slice(0, open), url };
74
+ }
75
+ from = open;
76
+ }
77
+ return null;
78
+ }
79
+ function hasSchemeUrl(label) {
80
+ const rest = stripPageSuffixes(label);
81
+ return matchTrailingUrl(rest) !== null || isPageSchemeUrl(rest);
82
+ }
83
+ function isCompletePageRow(row) {
84
+ return hasSchemeUrl(row.replace(/^\d+:\s*/, ""));
85
+ }
86
+ function isTitleContinuationLine(line) {
87
+ const m = line.match(/^(\d+):\s+(.+)$/);
88
+ if (!m) return false;
89
+ const rest = stripPageSuffixes(m[2]);
90
+ if (matchTrailingUrl(rest) !== null) return false;
91
+ if (isPageSchemeUrl(rest)) return false;
92
+ return /(?:^|\s)\[selected\]\s*$/.test(stripTrailingIsolatedContext(m[2]));
93
+ }
94
+ function extractPageUrl(label) {
95
+ const match = matchTrailingUrl(label);
96
+ return match ? match.url : label.trim();
97
+ }
98
+ function pageRowRest(row) {
99
+ return stripPageSuffixes(row.replace(/^\d+:\s*/, ""));
100
+ }
101
+ function stripDialogPreamble(text) {
102
+ const lines = text.split(/\r?\n/);
103
+ const kept = [];
104
+ for (let i = 0; i < lines.length; ) {
105
+ if (OPEN_DIALOG_HEADER.test(lines[i].trim())) {
106
+ let end = -1;
107
+ for (let idx = i + 1; idx < lines.length; idx++) {
108
+ if (HANDLE_DIALOG_FOOTER.test(lines[idx].trim())) end = idx;
109
+ }
110
+ if (end !== -1) {
111
+ i = end + 1;
112
+ continue;
113
+ }
114
+ }
115
+ kept.push(lines[i]);
116
+ i++;
117
+ }
118
+ return kept.join("\n");
119
+ }
120
+ function followingLinesCompleteTitle(rawLines, headerIndex, currentRow) {
121
+ let acc = `${currentRow} ## Pages`;
122
+ for (let i = headerIndex + 1; i < rawLines.length; i++) {
123
+ const next = rawLines[i].trim();
124
+ if (next.length === 0) continue;
125
+ if (next.match(MCP_SECTION_HEADER) !== null) return false;
126
+ if (PAGE_ID_LINE.test(next)) {
127
+ const rest = stripPageSuffixes(next.replace(/^\d+:\s*/, ""));
128
+ if (isPageSchemeUrl(rest) && matchTrailingUrl(rest) === null) {
129
+ return false;
130
+ }
131
+ }
132
+ acc += ` ${next}`;
133
+ if (matchTrailingUrl(pageRowRest(acc)) !== null) return true;
134
+ }
135
+ return false;
136
+ }
137
+ function collapsePageRows(text) {
138
+ const rows = [];
139
+ let inPageBlock = false;
140
+ const rawLines = stripDialogPreamble(text).split(/\r?\n/);
141
+ for (let index = 0; index < rawLines.length; index++) {
142
+ const line = rawLines[index].trim();
143
+ if (line.length === 0) continue;
144
+ const section = line.match(MCP_SECTION_HEADER)?.[1];
145
+ if (section !== void 0) {
146
+ const prev = rows[rows.length - 1];
147
+ if (section === "Pages" && inPageBlock && prev !== void 0 && !isCompletePageRow(prev) && followingLinesCompleteTitle(rawLines, index, prev)) {
148
+ rows[rows.length - 1] += ` ${line}`;
149
+ continue;
150
+ }
151
+ if (section === "Pages") {
152
+ rows.length = 0;
153
+ inPageBlock = true;
154
+ } else if (section === "Extension Pages") {
155
+ inPageBlock = true;
156
+ } else {
157
+ inPageBlock = false;
158
+ }
159
+ continue;
160
+ }
161
+ if (!inPageBlock) continue;
162
+ if (PAGE_ID_LINE.test(line)) {
163
+ const prev = rows[rows.length - 1];
164
+ if (prev !== void 0 && (!isCompletePageRow(prev) || isTitleContinuationLine(line))) {
165
+ rows[rows.length - 1] += ` ${line}`;
166
+ } else {
167
+ rows.push(line);
168
+ }
169
+ continue;
170
+ }
171
+ if (rows.length > 0) {
172
+ rows[rows.length - 1] += ` ${line}`;
173
+ }
174
+ }
175
+ return rows.map((row) => row.replace(/\s+/g, " "));
176
+ }
177
+ function parsePagesList(text) {
178
+ const pages = [];
179
+ for (const line of collapsePageRows(text)) {
180
+ const m = line.match(/^(\d+):\s+(.+)$/);
181
+ if (!m) continue;
182
+ const id = Number.parseInt(m[1], 10);
183
+ let rest = stripTrailingIsolatedContext(m[2]);
184
+ const selected = /(?:^|\s)\[selected\]\s*$/.test(rest);
185
+ if (selected) {
186
+ rest = rest.replace(/\s*\[selected\]\s*$/, "").trimEnd();
187
+ }
188
+ const url = extractPageUrl(rest);
189
+ pages.push({ id, url, selected });
190
+ }
191
+ return pages;
192
+ }
193
+
3
194
  // vendor/chrome-devtools-axi/src/selected-page.ts
4
195
  import {
5
196
  existsSync,
@@ -98,90 +289,19 @@ function overlaySessionSelected(pages, selectedId = getSelectedPageId()) {
98
289
  selected: selectedId !== null && page.id === selectedId
99
290
  }));
100
291
  }
101
- function rememberToolRouting(name, args, result) {
292
+ function rememberToolRouting(name, args) {
102
293
  if (name === "select_page" && typeof args.pageId === "number") {
103
294
  setSelectedPageId(args.pageId);
104
295
  return;
105
296
  }
106
- if (name === "new_page") {
107
- const requested = typeof args.url === "string" ? args.url : "";
108
- const created = createdPageIdFromNewPageDump(result, requested);
109
- if (created !== null) setSelectedPageId(created);
110
- else clearSelectedPageId();
111
- return;
112
- }
113
297
  if (name === "close_page" && typeof args.pageId === "number") {
114
298
  if (getSelectedPageId() === args.pageId) clearSelectedPageId();
115
299
  }
116
300
  }
117
- var MCP_PAGES_HEADER = /^## Pages$/;
118
- var MCP_OTHER_SECTION = /^##\s+(Extension Pages|Extension Service Workers|Third-party developer tools|WebMCP tools)$/;
119
- var GENERIC_SCHEME_SLASH_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
120
- var COLON_ONLY_SCHEME_URL = /^(?:about:|data:|view-source:|blob:)/i;
121
- var PAGE_ID_LINE = /^(\d+):\s*(.*)$/;
122
- function isSchemeUrl(label) {
123
- return GENERIC_SCHEME_SLASH_URL.test(label) || COLON_ONLY_SCHEME_URL.test(label);
124
- }
125
- function stripMcpSuffixes(rest) {
126
- let label = rest.replace(/\s+isolatedContext=.*$/, "");
127
- label = label.replace(/\s*\[selected\]\s*$/, "").trimEnd();
128
- return label;
129
- }
130
- function isCompletePageLabel(rest) {
131
- const body = stripMcpSuffixes(rest);
132
- if (isSchemeUrl(body)) return true;
133
- if (!body.endsWith(")")) return false;
134
- const open = body.lastIndexOf(" (");
135
- if (open === -1) return false;
136
- return isSchemeUrl(body.slice(open + 2, -1));
137
- }
138
- function pageUrlFromLabel(rest) {
139
- const body = stripMcpSuffixes(rest);
140
- if (isSchemeUrl(body)) return body;
141
- const open = body.lastIndexOf(" (");
142
- if (open !== -1 && body.endsWith(")")) {
143
- return body.slice(open + 2, -1);
144
- }
145
- return body;
146
- }
147
- function urlsMatch(pageUrl, requested) {
148
- if (!requested) return false;
149
- if (pageUrl === requested) return true;
150
- const trimSlash = (url) => url.length > 1 && url.endsWith("/") ? url.slice(0, -1) : url;
151
- return trimSlash(pageUrl) === trimSlash(requested);
152
- }
153
- function createdPageIdFromNewPageDump(text, requestedUrl) {
154
- let inPages = false;
155
- let matchedIds = [];
156
- let incomplete = false;
157
- for (const raw of text.split(/\r?\n/)) {
158
- const line = raw.trim();
159
- if (MCP_PAGES_HEADER.test(line)) {
160
- inPages = true;
161
- matchedIds = [];
162
- incomplete = false;
163
- continue;
164
- }
165
- if (MCP_OTHER_SECTION.test(line)) {
166
- inPages = false;
167
- continue;
168
- }
169
- if (!inPages) continue;
170
- const m = line.match(PAGE_ID_LINE);
171
- if (!m) continue;
172
- const id = Number.parseInt(m[1], 10);
173
- const rest = m[2];
174
- if (!isCompletePageLabel(rest)) {
175
- incomplete = true;
176
- continue;
177
- }
178
- const pageUrl = pageUrlFromLabel(rest);
179
- if (pageUrl.startsWith("chrome-extension:")) continue;
180
- if (urlsMatch(pageUrl, requestedUrl)) matchedIds.push(id);
181
- }
182
- if (incomplete) return null;
183
- if (matchedIds.length !== 1) return null;
184
- return matchedIds[0];
301
+ function createdPageIdFromPageLists(beforeText, afterText) {
302
+ const beforeIds = new Set(parsePagesList(beforeText).map((page) => page.id));
303
+ const createdIds = parsePagesList(afterText).filter((page) => !beforeIds.has(page.id)).map((page) => page.id);
304
+ return createdIds.length === 1 ? createdIds[0] : null;
185
305
  }
186
306
 
187
307
  // vendor/chrome-devtools-axi/src/bridge-script.ts
@@ -262,6 +382,8 @@ export {
262
382
  resolveBridgeScript,
263
383
  BRIDGE_PORT_IN_USE_EXIT_CODE,
264
384
  PAGE_IDENTITY_CHANGED_ERROR,
385
+ needsPageId,
386
+ parsePagesList,
265
387
  inspectProcessIdentity,
266
388
  readSelfStartTime,
267
389
  resolveSessionName,
@@ -269,7 +391,9 @@ export {
269
391
  resolveSessionStateDir,
270
392
  resolveSessionPidFile,
271
393
  getSelectedPageId,
394
+ setSelectedPageId,
272
395
  clearSelectedPageId,
273
396
  overlaySessionSelected,
274
- rememberToolRouting
397
+ rememberToolRouting,
398
+ createdPageIdFromPageLists
275
399
  };