page-agent-sdk 1.0.2 → 1.1.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "page-agent-sdk",
3
- "version": "1.0.2",
3
+ "version": "1.1.1",
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",
@@ -21,7 +21,8 @@
21
21
  },
22
22
  "files": [
23
23
  "dist",
24
- "types"
24
+ "types",
25
+ "skills"
25
26
  ],
26
27
  "scripts": {
27
28
  "dev": "vite",
@@ -0,0 +1,93 @@
1
+ ---
2
+ name: page-agent-sdk-integrate
3
+ description: Integrate the page-agent-sdk npm package into a web app so an AI agent can read/write structured page data (window props) via schema-validated tools. Use when the user wants to add/embed the SDK, declare windowProps + zod schemas, configure the LLM, mount the chat dialog, subscribe to events (onEvent / sdk.hook), run headless (ui:false) with a custom UI, or troubleshoot common integration issues (DeepSeek 400 tool_call_id, MCP injecting 0 tools, etc).
4
+ ---
5
+
6
+ # Integrate page-agent-sdk
7
+
8
+ Help the user embed `page-agent-sdk` so an AI agent safely edits their page's structured JSON via tools.
9
+
10
+ ## Core concept
11
+
12
+ The SDK is a **standardized JSON-operation agent**: the integrator declares writable `window` paths + zod schemas; the agent edits them via `set_window_prop` / `edit_window_prop` (jsonPath patches), validated by schema, scoped to the registry, with snapshot rollback. "Editing JSON" becomes structured + validatable + rollbackable, NOT free-form LLM text.
13
+
14
+ ## Workflow
15
+
16
+ ### 1. Choose install method
17
+
18
+ | Method | When | How |
19
+ |---|---|---|
20
+ | **npm** | module project, tree-shake ok | `npm i page-agent-sdk zod @langchain/openai @langchain/core` → `import { createChatSdk, z } from 'page-agent-sdk'` |
21
+ | **CDN · ESM** (esm.sh) | modular, small, peer auto-resolved | `import { createChatSdk, z } from 'https://esm.sh/page-agent-sdk'` |
22
+ | **CDN · IIFE** (unpkg) | one-line, no build, ~1.4MB all-in | `<script src="https://unpkg.com/page-agent-sdk"></script>` → `ChatSdk.createChatSdk`, `ChatSdk.z` |
23
+
24
+ See `demo/plain.html` for a framework-agnostic importmap + esm.sh example.
25
+
26
+ ### 2. Declare windowProps + schemas (the key step)
27
+
28
+ Put the page data on `window` (e.g. `window.app = { title, theme }`), then declare each writable path with a zod schema. The agent can ONLY touch declared paths; `set`/`edit` are schema-validated (invalid → structured error, no write).
29
+
30
+ ```ts
31
+ import { createChatSdk, z } from 'page-agent-sdk'
32
+ import 'page-agent-sdk/style.css'
33
+
34
+ window.app = { title: 'Demo', theme: 'light', items: [] }
35
+
36
+ createChatSdk({
37
+ container: '#root',
38
+ llm: { apiKey, baseUrl: 'https://api.deepseek.com/v1', model: 'deepseek-chat' },
39
+ systemPrompt: 'You are a page assistant; read/write window.app via tools.',
40
+ windowProps: [
41
+ { path: 'app.title', description: '页面标题', schema: z.string() },
42
+ { path: 'app.theme', description: '主题', schema: z.enum(['light','dark']) },
43
+ { path: 'app.items', description: '列表项数组', schema: z.array(z.object({ name: z.string(), price: z.number() })) },
44
+ ],
45
+ }).mount()
46
+ ```
47
+
48
+ For large JSON, prefer `edit_window_prop` (jsonPath patch: set/remove/merge/append) over `set_window_prop` (whole value) — avoids re-sending the entire blob.
49
+
50
+ ### 3. Configure the LLM
51
+
52
+ `llm` accepts an `LLMConfig` object (`{ apiKey, baseUrl, model, temperature?, maxTokens? }`) or any LangChain `BaseChatModel` instance. Default protocol is OpenAI-compatible (DeepSeek works out of the box). For large JSON edits use low temperature (~0.3).
53
+
54
+ ### 4. Subscribe to events (replace polling)
55
+
56
+ Two complementary ways to react to SDK changes from the host page:
57
+
58
+ ```ts
59
+ const sdk = createChatSdk({
60
+ onEvent(e) { if (e.type === 'window_prop_change') renderUI() }, // constructor-time, single
61
+ // ...
62
+ }).mount()
63
+
64
+ // runtime, multiple listeners, cancellable
65
+ const off = sdk.hook((e) => { if (e.type === 'tool_call') analytics.track(e.name) })
66
+ // off() to unsubscribe
67
+ ```
68
+
69
+ Event types: `window_prop_change` / `message_update` / `tool_call` / `tool_result` / `text` / `round_start` / `done` / `error` (+ stream events in stream mode). `approval_request` is NOT forwarded (UI handles it).
70
+
71
+ ### 5. Headless mode (custom UI, framework-agnostic)
72
+
73
+ `ui: false` → no built-in dialog; use the reactive `sdk.messages` array + `sdk.send`/`sdk.stream` to build your own UI. Reusable `ChatDialog` / `MessageContent` / `CodePreview` components and `useChat` composable are exported from the entry for custom UIs.
74
+
75
+ ### 6. Capabilities & presets
76
+
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
+ - `presets.pageBuilder` / `researcher` / `minimal` — spread into `createChatSdk` for common scenarios.
79
+
80
+ ## References (read as needed)
81
+
82
+ - `doc/usage-guide.md` (zh) / `doc/usage-guide.en.md` — full options reference (onEvent/hook/server-side/checkpoint/approval/verify/subagent/MCP)
83
+ - `examples/<demo>/` — runnable demos (page-demo, nested-demo, subagent-demo, mcp-demo, planner-demo, toolsets-demo, human-confirm-demo)
84
+ - `demo/plain.html` — framework-agnostic CDN integration
85
+ - `CLAUDE.md` — internal dev guide (architecture, conventions)
86
+
87
+ ## Common pitfalls
88
+
89
+ - **DeepSeek/OpenAI 400 `missing field tool_call_id`**: `ToolMessage` must use snake_case `tool_call_id` (not camelCase). Already handled internally; only relevant if writing custom tool plumbing.
90
+ - **ChatOpenAI params**: use `apiKey` (not `openAIApiKey`), `model` (not `modelName`); `baseUrl` goes via `configuration.baseURL`.
91
+ - **MCP injects 0 tools on first cold visit**: `vite.config.ts` `optimizeDeps.include` pre-declares the SDK sub-paths; if you fork the config, keep those entries or the first MCP page load injects nothing (reload fixes it).
92
+ - **`.env` `VITE_AI_SYSTEM_PROMPT` must be single-line** (dotenv doesn't support multi-line values).
93
+ - **Server-side (Node.js)**: works with `ui:false` + `storage:'memory'` + `capabilities:{windowOps:false,fetch:false}`; `mount()`/`unmount()` guard `window`/`document` access. Provide `globalThis.window` if you enable windowOps in Node.
@@ -0,0 +1,44 @@
1
+ ---
2
+ name: page-agent-sdk-release
3
+ description: Release a new version of the page-agent-sdk npm package and push to its two git remotes (Gitee + GitHub). Use when the user wants to publish/ship a new version, bump the version, build + test before release, push to gitee/github, or follow the project's release checklist. Covers the full flow: code changes → sync zh/en docs → bump semver → build + self-test → commit → push Gitee → push GitHub → npm publish → verify.
4
+ ---
5
+
6
+ # Release page-agent-sdk
7
+
8
+ Execute the project's release checklist end-to-end. The authoritative, detailed checklist lives in `CLAUDE.md` → "发布流程 checklist"; read that section first, then follow the steps below.
9
+
10
+ ## Two remotes (do NOT mix them up)
11
+
12
+ | remote | URL | role |
13
+ |---|---|---|
14
+ | `origin` | gitee.com/whyymj/**chat-agent**.git | daily storage, keeps all granular commits |
15
+ | `github` | github.com/whyymj/**chat-sdk**.git | official open-source, receives curated commits |
16
+
17
+ Personal notes (`doc/待确认问题.md`) are gitignored — Gitee only, never GitHub.
18
+
19
+ ## Release checklist (in order)
20
+
21
+ 1. **Code**: edit `src/`, sync `types/index.d.ts` (hand-maintained), update exports in `src/core/index.ts`.
22
+ 2. **Docs (sync zh + en, never single-side)**:
23
+ - `README.md` (en) / `README.zh-CN.md` (zh) — features, usage, scenarios
24
+ - `doc/README.md` (zh) / `doc/README.en.md` (en) — doc index
25
+ - `doc/usage-guide.md` (zh) / `doc/usage-guide.en.md` (en) — usage guide
26
+ - `CLAUDE.md` — internal dev guide/architecture
27
+ - Keep language toggle links bidirectional.
28
+ 3. **Bump version**: `npm version patch|minor|major --no-git-tag-version` (semver: minor for new API, major for breaking, patch for fix). Never republish the same version.
29
+ 4. **Build + self-test**: `npm run build` (= `build:lib` + `build:iife`) then `npm test` (341 assertions must pass). Run `npm pack --dry-run` to confirm the tarball excludes `.env` / `src` / `examples` / notes.
30
+ 5. **Commit**: `git add -A && git commit -m "feat/fix/docs: ..."` (conventional style).
31
+ 6. **Push Gitee** (daily storage): `git push origin master`. If you just rebased and rewrote history → `git push --force-with-lease origin master` (personal repo, safe).
32
+ 7. **Push GitHub** (official): `git push github master`. If rejected as `non-fast-forward` → `git fetch github master && git pull --rebase github master` then push again.
33
+ 8. **Publish to npm**: `npm publish` (`publishConfig.registry` is locked to the official npm registry, unaffected by the machine's default private registry).
34
+ 9. **Verify**: `npm view page-agent-sdk version` (confirm latest) + a temp dir `npm i page-agent-sdk` to confirm it installs + imports.
35
+
36
+ ## npm credentials gotchas
37
+
38
+ - Account `whyymj` has 2FA enabled. Use an **Automation Access Token** (npmjs.com → Access Tokens → Classic → Automation, bypasses OTP); write to user-level `~/.npmrc` via `npm config set //registry.npmjs.org/:_authToken <token> --location=user`. Revoke after use. Never commit tokens or store them in the project dir.
39
+ - `npm login` / `npm whoami` require `--registry=https://registry.npmjs.org/` (machine default may be a private registry).
40
+
41
+ ## References
42
+
43
+ - `CLAUDE.md` → "发布流程 checklist" / "双远程仓库与发布约定" / "npm 发布约定" — authoritative details.
44
+ - `package.json` → `publishConfig`, `exports`, `files`, `peerDependencies`.
package/types/index.d.ts CHANGED
@@ -42,6 +42,25 @@ export type StreamEvent =
42
42
 
43
43
  export type StreamHandler = (event: StreamEvent) => void;
44
44
 
45
+ /**
46
+ * SDK 事件(供 createChatSdk({ onEvent }) 订阅常用时机)。
47
+ * 复用 StreamEvent(round_start/reasoning/text/tool_call/tool_result/subagent/done;approval_request 不外发)
48
+ * + 额外时机:window_prop_change / message_update / error。
49
+ */
50
+ export type SdkEvent =
51
+ | { type: 'round_start'; round: number }
52
+ | { type: 'reasoning'; delta: string }
53
+ | { type: 'text'; delta: string }
54
+ | { type: 'tool_call'; name: string; args: any }
55
+ | { type: 'tool_result'; name: string; result: string; status: 'done' | 'error' }
56
+ | { type: 'subagent'; taskId: string; label: string; kind: 'tool_call' | 'tool_result'; name: string; args?: any; result?: string; status?: 'done' | 'error' }
57
+ | { type: 'done'; content: string }
58
+ | { type: 'window_prop_change'; path: string; operation: 'set' | 'edit' | 'delete' | 'restore'; value?: unknown }
59
+ | { type: 'message_update'; count: number }
60
+ | { type: 'error'; message: string };
61
+
62
+ export type SdkEventHandler = (event: SdkEvent) => void;
63
+
45
64
  /** 调试日志(与 harness/createAgent 的 DebugLog 一致) */
46
65
  export interface DebugLog {
47
66
  timestamp: number;
@@ -336,6 +355,12 @@ export interface ChatSdkOptions {
336
355
  summaryMaxTokens?: number;
337
356
  /** 摘要 LLM 超时毫秒(默认 15000;超时回退索引摘要) */
338
357
  summaryTimeoutMs?: number;
358
+ /**
359
+ * SDK 事件回调:订阅常用时机(window 属性变化 / 消息更新 / 工具调用 / 流式文本 / 轮次 / 错误)。
360
+ * UI 与 headless 模式均生效;用于外部联动(宿主页面响应式刷新、埋点、日志),替代轮询。
361
+ * approval_request 不外发(UI 已处理)。
362
+ */
363
+ onEvent?: SdkEventHandler;
339
364
  /** 流式输出(默认 true);false 时等整段回复再显示 */
340
365
  streaming?: boolean;
341
366
  title?: string;
@@ -356,6 +381,8 @@ export interface ChatSdk {
356
381
  restoreLastCheckpoint(): boolean;
357
382
  /** 列出可用 checkpoint(回退点);需开启 checkpoint,未开启返回空数组 */
358
383
  listCheckpoints(): CheckpointMeta[];
384
+ /** 运行时订阅 SDK 事件(可多个监听器,返回取消函数);与构造时 onEvent 互补 */
385
+ hook(handler: SdkEventHandler): () => void;
359
386
  }
360
387
 
361
388
  export declare function createChatSdk(options: ChatSdkOptions): ChatSdk;