page-agent-sdk 1.1.3 → 1.1.4

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
@@ -40,9 +40,13 @@ At its core, it gives the AI a **standardized, safe JSON-operation channel**. AI
40
40
  | 📰 **CMS ops** | "Prefix these products with 'Limited', mark under ¥100 red" | JSONPath filter + sandbox script batch edit |
41
41
  | 🖥 **Ops console** | "Raise A's threshold to 30%, turn off switch B" | Whitelist + human-confirm to edit config, read-back verify |
42
42
  | 🤖 **AI-native assistant** | "Change this chart's legend to bars" | Conversational ops on product data, no UI needed |
43
+ | 🔬 **Research agent** | "Compare 3 solutions and recommend one" | Parallel subagents investigate each, return only conclusions |
44
+ | 🧩 **Headless / server-side** | "Run the agent in Node.js" | `ui:false` + `storage:'memory'`, drive via `sdk.send` |
43
45
 
44
46
  > `examples/nested-demo` is a full low-code example: nested block tree + human confirm + one-click rollback.
45
47
 
48
+ **Full end-to-end scenarios with copy-paste code** (9 cases: low-code builder / form designer / CMS batch / ops console / AI-native / research / server-side / multi-agent / MCP) live in the bundled Agent Skill at `skills/page-agent-sdk-integrate/references/use-cases.md` (also shipped in the npm package). See [Skills for AI tools](#skills-for-ai-tools-for-integrators) below to install the skill.
49
+
46
50
  ## 30-second quickstart
47
51
 
48
52
  ```bash
package/README.zh-CN.md CHANGED
@@ -40,9 +40,13 @@
40
40
  | 📰 **CMS 运营** | 「这批商品标题加『限时』前缀、低于 100 元的标红」 | JSONPath 筛选 + 沙箱脚本批量改 |
41
41
  | 🖥 **运维配置台** | 「A 实验阈值调到 30%、关掉 B 开关」 | 白名单 + 人工确认改配置,写后读回校验 |
42
42
  | 🤖 **AI 原生助手** | 「把这张看板的图例改成柱状」 | 对话操作产品自有数据,免做 UI |
43
+ | 🔬 **调研 agent** | 「对比 3 个方案,推荐哪个」 | 并行子 agent 各调研一个,只回结论 |
44
+ | 🧩 **Headless / 服务端** | 「在 Node.js 里跑 agent」 | `ui:false` + `storage:'memory'`,用 `sdk.send` 驱动 |
43
45
 
44
46
  > 仓库 `examples/nested-demo` 即低代码场景完整示例:嵌套区块树 + 人工确认 + 一键回退。
45
47
 
48
+ **完整端到端场景(含可复制代码,共 9 例:低代码搭建 / 表单设计器 / CMS 批量 / 运维配置台 / AI 原生 / 调研 / 服务端 / 多 agent / MCP)** 见随包附带的 Agent Skill:`skills/page-agent-sdk-integrate/references/use-cases.md`(npm 包内同样包含)。安装 skill 见下文[给 AI 工具使用者的 Skills](#给-ai-工具使用者的-skills集成方安装)。
49
+
46
50
  ## 30 秒上手
47
51
 
48
52
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "page-agent-sdk",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "type": "module",
5
5
  "description": "框架无关的页面内 Agent JS SDK —— 以对话框形态挂载到任意网页,通过自定义 tool 读写宿主 window 属性(GET 抓文档),具备 planning/skills/虚拟工作区/快照回退/context 管理能力。Vue 打包进库,使用者无需安装 Vue。",
6
6
  "main": "./dist/page-agent-sdk.umd.cjs",
@@ -77,6 +77,22 @@ Event types: `window_prop_change` / `message_update` / `tool_call` / `tool_resul
77
77
  - `capabilities: { windowOps:false, fetch:false, planning:false, skills:false, vfs:false, summarization:false, memory:false, subagent:false }` — turn off unused built-ins to save tokens/size. `verify` is the reverse (off by default; `capabilities.verify:true` enables write-back self-check).
78
78
  - `presets.pageBuilder` / `researcher` / `minimal` — spread into `createChatSdk` for common scenarios.
79
79
 
80
+ ## Common use cases (match the user's scenario, then read [references/use-cases.md](references/use-cases.md) for full code)
81
+
82
+ | Scenario | Key setup |
83
+ |---|---|
84
+ | **Low-code page builder** | `windowProps` = component tree; `edit_window_prop` jsonPath patches; `onEvent` → canvas refresh; `checkpoint` + `approval` |
85
+ | **Form designer** | `windowProps` = field definitions with enum/required schemas; schema validation prevents malformed forms |
86
+ | **CMS batch ops** | `eval_window_script` for bulk loops; `search_window_prop` to filter; `edit_window_prop` for targeted edits |
87
+ | **Ops config console** | `approval:{tools:[set,edit]}` human-confirm; `capabilities.verify:true` write-back read; `checkpoint` |
88
+ | **AI-native assistant** | `capabilities:{windowOps:false,fetch:false}` + custom `tools` (your product API) |
89
+ | **Research agent** | `capabilities:{windowOps:false}`; `subagent:{allowedTools:['fetch_document']}`; `contextPreset:'conservative'` |
90
+ | **Headless / server-side** | `ui:false` + `storage:'memory'` + `capabilities:{windowOps:false,fetch:false}`; drive via `sdk.send` |
91
+ | **Multi-agent on one page** | same `id` + `shareContext:true` → multiple dialogs share one `AgentCore` |
92
+ | **MCP integration** | `mcp:[{transport,url}]` remote tool servers; `@modelcontextprotocol/sdk` optional peerDep |
93
+
94
+ When the user describes a scenario, map it to the row above and load `references/use-cases.md` for the matching numbered case (1→9) with copy-paste code.
95
+
80
96
  ## References (read as needed)
81
97
 
82
98
  Detailed docs live in this skill's `references/` folder — load the one matching the user's question:
@@ -85,6 +101,7 @@ Detailed docs live in this skill's `references/` folder — load the one matchin
85
101
  - **[references/options.md](references/options.md)** — every `createChatSdk` option: type, default, purpose & when to use. Read when the user asks "what does option X do" or needs to tune behavior.
86
102
  - **[references/api.md](references/api.md)** — instance methods (`mount`/`send`/`stream`/`inspect`/`switchSession`/`hook`/checkpoints), `defineTool`/`defineSkill`/`presets`, built-in window tools, and the full `SdkEvent` type table. Read when the user asks about APIs, tools, or events.
87
103
  - **[references/use-cases.md](references/use-cases.md)** — 9 end-to-end scenarios (low-code builder / form designer / CMS batch / ops console / AI-native / research / server-side / multi-agent / MCP). Read when the user wants a concrete pattern for their use case.
104
+ - **[references/advanced.md](references/advanced.md)** — detailed examples for the four extensibility surfaces: custom `defineTool` (with error handling + coexisting with windowOps), `defineSkill` (inline content + remote doc), subagents (ad-hoc `spawn_agent`/`spawn_agents` + pre-declared `subagents` → `use_<id>`), MCP (http/sse/websocket + auth + dev gotcha). Read when the user asks "how to add custom tools / skills / subagents / MCP".
88
105
 
89
106
  Project-level docs (in the repo, not bundled in this skill):
90
107
  - `doc/usage-guide.md` (zh) / `doc/usage-guide.en.md` — full options reference
@@ -0,0 +1,215 @@
1
+ # Advanced examples — custom tools, skills, subagents, MCP
2
+
3
+ Detailed, copy-paste examples for the four extensibility surfaces. Read the section matching the user's need.
4
+
5
+ ## 1. Custom tools (`defineTool`)
6
+
7
+ Custom tools extend the agent beyond built-in `windowOps`/`fetch`. Use them to expose your product's API to the AI.
8
+
9
+ ### Minimal
10
+
11
+ ```ts
12
+ import { createChatSdk, defineTool, z } from 'page-agent-sdk'
13
+
14
+ const lookupOrder = defineTool({
15
+ name: 'lookup_order',
16
+ description: '查询订单 by id',
17
+ schema: z.object({ orderId: z.string() }),
18
+ handler: async ({ orderId }) => JSON.stringify(await api.getOrder(orderId)),
19
+ })
20
+ ```
21
+
22
+ ### With error handling
23
+
24
+ Return structured errors via `toolError` so the AI can react:
25
+
26
+ ```ts
27
+ import { defineTool, toolError, z } from 'page-agent-sdk'
28
+
29
+ const updatePrice = defineTool({
30
+ name: 'update_price',
31
+ description: '更新商品价格',
32
+ schema: z.object({ sku: z.string(), price: z.number().positive() }),
33
+ handler: async ({ sku, price }) => {
34
+ const ok = await api.setPrice(sku, price)
35
+ if (!ok) return toolError({ path: sku, code: 'NOT_FOUND', message: `SKU ${sku} 不存在` })
36
+ return `已更新 ${sku} 价格为 ${price}`
37
+ },
38
+ })
39
+ ```
40
+
41
+ ### Coexisting with windowOps
42
+
43
+ Mix custom tools with built-in window tools:
44
+
45
+ ```ts
46
+ createChatSdk({
47
+ container: '#chat', llm: { ... },
48
+ windowProps: [{ path: 'app.config', description: '配置', schema: z.record(z.any()) }],
49
+ tools: [lookupOrder, updatePrice], // custom + built-in windowOps together
50
+ }).mount()
51
+ ```
52
+
53
+ ### Pure custom-tool agent (no windowOps)
54
+
55
+ ```ts
56
+ createChatSdk({
57
+ container: '#chat', llm: { ... },
58
+ tools: [lookupOrder, updatePrice],
59
+ capabilities: { windowOps: false, fetch: false }, // drop built-ins
60
+ }).mount()
61
+ ```
62
+
63
+ ## 2. Skills (`defineSkill`) — progressive disclosure
64
+
65
+ Skills are **loaded on demand** by the agent (not always in context) → saves tokens. The agent sees an index of `name`+`description`, calls `load_skill` to pull the full content when needed.
66
+
67
+ ### Inline content skill
68
+
69
+ ```ts
70
+ import { createChatSdk, defineSkill } from 'page-agent-sdk'
71
+
72
+ const apiDesignSkill = defineSkill({
73
+ name: 'api-design',
74
+ description: '本项目 REST API 设计规范(何时用:设计/评审新接口)',
75
+ getContent: () => `
76
+ - URL 用 kebab-case,统一 /v1 前缀
77
+ - 列表接口必须分页(page+pageSize)
78
+ - 错误返回 { code, message, data: null }
79
+ - 写操作记审计日志
80
+ `,
81
+ })
82
+
83
+ createChatSdk({ container: '#chat', llm: { ... }, skills: [apiDesignSkill] }).mount()
84
+ ```
85
+
86
+ ### Remote doc skill (auto-fetched + cached to vfs)
87
+
88
+ ```ts
89
+ const brandSkill = defineSkill({
90
+ name: 'brand-guide',
91
+ description: '品牌视觉规范(何时用:涉及 UI/文案/配色)',
92
+ doc: 'https://my-wiki/brand.md', // SDK fetches + caches to vfs; large docs stay out of context
93
+ })
94
+
95
+ createChatSdk({ container: '#chat', llm: { ... }, skills: [brandSkill] }).mount()
96
+ ```
97
+
98
+ > `SkillSpec = { name, description, doc?, getContent? }`. `doc` (http(s):// or `vfs://path`) takes precedence over `getContent`. Write `description` as "what it is + when to use" so the agent knows when to load it.
99
+
100
+ ## 3. Subagents — ad-hoc spawn vs pre-declared
101
+
102
+ Subagents run isolated sub-tasks; **only their final conclusion** returns to the main context (saves tokens). Two flavors coexist.
103
+
104
+ ### 3a. Ad-hoc `spawn_agent` / `spawn_agents` (default enabled)
105
+
106
+ The main agent decides when to delegate via `spawn_agent` (one) / `spawn_agents` (parallel). Configure the subagent tool subset:
107
+
108
+ ```ts
109
+ createChatSdk({
110
+ container: '#chat', llm: { ... },
111
+ systemPrompt: '多源对比时用 spawn_agents 并行委派。',
112
+ subagent: {
113
+ allowedTools: ['fetch_document', 'get_window_prop'], // read-only subset (no spawn → no recursion)
114
+ maxDepth: 1, // physical recursion cut (default 1)
115
+ maxParallel: 3, // max parallel subagents in spawn_agents
116
+ temperature: 0.2, // subagent temperature (default inherits main)
117
+ },
118
+ }).mount()
119
+ ```
120
+
121
+ User: "对比 A/B/C 三个方案" → main agent calls `spawn_agents` with 3 tasks → 3 subagents research in parallel → only conclusions return.
122
+
123
+ ### 3b. Pre-declared named subagents (`subagents`) — Claude-Code style
124
+
125
+ Declare fixed roles; each auto-generates a `use_<id>({ task })` delegation tool. The main agent sees the tool description and knows who to delegate to:
126
+
127
+ ```ts
128
+ createChatSdk({
129
+ container: '#chat', llm: { ... },
130
+ systemPrompt: '复杂任务委派给专家子 agent。',
131
+ subagents: [
132
+ {
133
+ id: 'researcher',
134
+ description: '调研专家:搜集资料、对比方案(只读)',
135
+ tools: ['fetch_document', 'get_window_prop'], // read-only
136
+ temperature: 0.2,
137
+ },
138
+ {
139
+ id: 'reviewer',
140
+ description: '审查专家:检查代码/配置的安全与性能问题',
141
+ tools: ['get_window_prop', 'search_window_prop'],
142
+ systemPrompt: '你是审查专家,只报告问题不改数据。',
143
+ temperature: 0.1,
144
+ },
145
+ ],
146
+ }).mount()
147
+ ```
148
+
149
+ Now the main agent has `use_researcher({ task })` and `use_reviewer({ task })` tools. Each subagent inherits main config where omitted (`llm`, `maxTokens`, `skills`...).
150
+
151
+ > Pre-declared = fixed roles (research/review); ad-hoc `spawn` = temporary free delegation. Both can coexist. `maxDepth` (default 1) physically cuts recursion: at depth+1 ≥ maxDepth, subagents get no spawn tools.
152
+
153
+ ## 4. MCP (external tool servers)
154
+
155
+ Connect remote MCP servers; their tools auto-inject into the agent. `Promise.allSettled` → one server down doesn't break others.
156
+
157
+ ### HTTP (StreamableHTTP) — recommended
158
+
159
+ ```ts
160
+ createChatSdk({
161
+ container: '#chat', llm: { ... },
162
+ mcp: [
163
+ { transport: 'http', url: 'https://my-mcp-server/mcp', name: 'my-tools' },
164
+ ],
165
+ }).mount()
166
+ ```
167
+
168
+ ### SSE / WebSocket
169
+
170
+ ```ts
171
+ mcp: [
172
+ { transport: 'sse', url: 'https://another/sse' },
173
+ { transport: 'websocket', url: 'wss://ws-server/mcp' },
174
+ ]
175
+ ```
176
+
177
+ ### With request init (auth headers)
178
+
179
+ ```ts
180
+ mcp: [
181
+ {
182
+ transport: 'http', url: 'https://my-mcp/mcp',
183
+ requestInit: { headers: { Authorization: `Bearer ${token}` } },
184
+ },
185
+ ]
186
+ ```
187
+
188
+ ### Notes
189
+
190
+ - `@modelcontextprotocol/sdk` is an **optional peerDep** — install it only if you use `mcp`. It's dynamically imported (zero cost when unused).
191
+ - Browser supports **only remote transports** (http/sse/websocket), not stdio.
192
+ - MCP `inputSchema` (JSON Schema) is passed directly to LangChain `tool()` — no conversion.
193
+ - `inspect().mcp.servers` lists connected servers; each tool's `source` shows `mcp:<name>`.
194
+
195
+ ### Dev gotcha
196
+
197
+ If you fork `vite.config.ts`, keep `optimizeDeps.include` pre-declaring the SDK sub-paths (`/client`, `/client/streamableHttp.js`, `/client/sse.js`, `/client/websocket.js`). Otherwise the **first cold visit** to an MCP page injects 0 tools (reload fixes it). The default config already has these.
198
+
199
+ ## 5. Combining everything
200
+
201
+ ```ts
202
+ createChatSdk({
203
+ container: '#chat',
204
+ llm: { apiKey, baseUrl, model },
205
+ systemPrompt: '...',
206
+ windowProps: [{ path: 'app.data', description: '...', schema: z.record(z.any()) }],
207
+ tools: [lookupOrder, updatePrice], // custom tools
208
+ skills: [apiDesignSkill, brandSkill], // progressive skills
209
+ subagents: [{ id: 'researcher', description: '...', tools: ['fetch_document'] }], // pre-declared
210
+ mcp: [{ transport: 'http', url: '...' }], // external tools
211
+ capabilities: { verify: true }, // self-check
212
+ approval: { tools: ['set_window_prop'] }, // human confirm writes
213
+ checkpoint: true, // rollback
214
+ }).mount()
215
+ ```
@@ -39,8 +39,8 @@ import { defineSkill } from 'page-agent-sdk'
39
39
 
40
40
  const apiSkill = defineSkill({
41
41
  name: 'api-design',
42
- description: 'REST API design conventions for this project',
43
- prompt: 'Use kebab-case URLs; version under /v1; ...',
42
+ description: 'REST API design conventions for this project (load when designing/reviewing APIs)',
43
+ getContent: () => 'Use kebab-case URLs; version under /v1; ...', // or `doc: 'https://...'` for remote
44
44
  })
45
45
 
46
46
  createChatSdk({ skills: [apiSkill], /* ... */ }).mount()