page-agent-sdk 2.12.2 → 2.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "page-agent-sdk",
3
- "version": "2.12.2",
3
+ "version": "2.14.0",
4
4
  "type": "module",
5
5
  "description": "Browser-native AI agent SDK: chat dialog + ReAct tool-calling + schema-validated JSON ops. Vue bundled, framework-agnostic. Works with DeepSeek/OpenAI/MCP.",
6
6
  "main": "./dist/page-agent-sdk.umd.cjs",
@@ -17,6 +17,18 @@
17
17
  "import": "./dist/page-agent-sdk.js",
18
18
  "require": "./dist/page-agent-sdk.umd.cjs"
19
19
  },
20
+ "./storage": {
21
+ "types": "./types/index.d.ts",
22
+ "import": "./dist/page-agent-sdk.js"
23
+ },
24
+ "./query": {
25
+ "types": "./types/index.d.ts",
26
+ "import": "./dist/page-agent-sdk.js"
27
+ },
28
+ "./llm": {
29
+ "types": "./types/index.d.ts",
30
+ "import": "./dist/page-agent-sdk.js"
31
+ },
20
32
  "./style.css": "./dist/page-agent-sdk.css"
21
33
  },
22
34
  "files": [
@@ -76,6 +88,7 @@
76
88
  },
77
89
  "devDependencies": {
78
90
  "@modelcontextprotocol/sdk": "^1.29.0",
91
+ "@playwright/test": "^1.62.1",
79
92
  "@vitejs/plugin-vue": "^6.0.7",
80
93
  "tsx": "^4.23.1",
81
94
  "typescript": "^7.0.2",
@@ -296,6 +296,20 @@ sdk.setLlm(otherChatModel) // or pass a BaseChatModel i
296
296
  sdk.setMemory('User is VIP; prefer concise answers; use incremental patch when editing.')
297
297
  sdk.setMemory('') // clear (empty string skips injection)
298
298
 
299
+ // 3.5 Memory async function source (RAG): load knowledge base doc asynchronously
300
+ // - Async fn evaluated in background on first beforeAgent, cached afterwards
301
+ // - refreshMemory() forces re-evaluation (e.g. after KB doc updated)
302
+ createChatSdk({
303
+ memory: async () => await fetch('/kb/faq.md').then((r) => r.text()),
304
+ /* ... */
305
+ })
306
+ sdk.setMemory(async () => await fetch('/kb/faq-v2.md').then((r) => r.text())) // switch KB
307
+ await sdk.refreshMemory() // force re-fetch after KB doc updated
308
+ // Sync fn reads runtime variable (cached on first eval; refresh to re-evaluate)
309
+ let lang = 'zh'
310
+ sdk.setMemory(() => `请用${lang}回答。`)
311
+ lang = 'en'; await sdk.refreshMemory() // re-evaluate with new lang
312
+
299
313
  // 4. Subagents: runtime add/remove pre-declared subagents (requires subagents:[] at creation)
300
314
  // Pass subagents: [] (empty array) at creation to enable the controller for dynamic add later.
301
315
  sdk.addSubagent({ id: 'translator', description: '中英互译子 agent', systemPrompt: '你是翻译助手。' })
@@ -23,7 +23,8 @@
23
23
  | `addTool(tool)` | `(tool: StructuredToolInterface) => void` | Append user tool at runtime (dedup by name; built-ins untouched). |
24
24
  | `removeTool(name)` | `(name: string) => boolean` | Remove user tool at runtime (built-ins untouched). Returns whether removed. |
25
25
  | `setLlm(llm)` | `(llm: BaseChatModel \| LLMConfig) => void` | Switch LLM at runtime (quota-exhausted→cheaper model / complex task→stronger model / switch provider). Param `BaseChatModel` or `LLMConfig` (constructs `ChatOpenAI` internally). Rebinds tools + re-resolves model caps (`contextWindow`/`maxOutputTokens`). `summaryLlm` unaffected. If new model lacks `bindTools`, tool-calling degrades (agent stays up). |
26
- | `setMemory(text)` | `(text: string) => void` | Update persistent memory directive at runtime (next `augmentPrompt` injects latest; `setMemory('')` clears). |
26
+ | `setMemory(source)` | `(source: string \| (() => string \| Promise<string>)) => void` | Update memory at runtime. Supports `string` and sync/async function (async fn evaluated in background, fits RAG doc loading). `setMemory('')` clears. |
27
+ | `refreshMemory()` | `() => Promise<string>` | Re-evaluate current memory function source (force refresh after RAG doc update). String source returns current value. |
27
28
  | `setSubagents(configs)` | `(configs: SubagentConfig[]) => void` | Runtime swap pre-declared subagents (regenerates `use_<id>` delegation tools + triggers rebind). Requires `subagents:[]` at creation (else controller is null, setter warns, no throw). |
28
29
  | `addSubagent(config)` | `(config: SubagentConfig) => void` | Append pre-declared subagent at runtime (duplicate id warns & skips). Requires `subagents:[]` at creation. |
29
30
  | `removeSubagent(id)` | `(id: string) => boolean` | Remove pre-declared subagent at runtime (by id). Returns whether removed. Requires `subagents:[]` at creation. |
@@ -175,7 +176,7 @@ createChatSdk({
175
176
  - **Runtime dynamic reconfiguration (zero-breakage; not calling = current behavior)**: beyond data/skills, you can also dynamically reconfigure tools / LLM / memory / subagents at runtime without rebuilding the agent:
176
177
  - `sdk.setTools(tools)` / `addTool(tool)` / `removeTool(name)` — swap/append/remove user tools (built-ins untouched; internal `rebindTools` re-binds to LLM; next round uses new set). Use cases: per-permission tool groups, business-stage gating, A/B experiments.
177
178
  - `sdk.setLlm(llm)` — switch LLM at runtime (quota-exhausted→cheaper model / complex task→stronger model / switch provider). Param `BaseChatModel` or `LLMConfig`. Rebinds tools + re-resolves model caps. `summaryLlm` unaffected.
178
- - `sdk.setMemory(text)` — update the persistent memory directive at runtime (next `augmentPrompt` injects latest).
179
+ - `sdk.setMemory(source)` — update memory at runtime; supports `string` and sync/async function (async fn evaluated in background, fits RAG doc loading). `sdk.refreshMemory()` re-evaluates the current function source (force refresh after RAG doc update).
179
180
  - `sdk.setSubagents(configs)` / `addSubagent(config)` / `removeSubagent(id)` — swap/append/remove pre-declared subagents (regenerates `use_<id>` delegation tools + triggers rebind). Requires `subagents:[]` at creation.
180
181
  - All setters trigger `infoTick++` → DebugDrawer refreshes; `inspect()` reflects the latest tools/model/memory/subagent.subagents.
181
182
 
package/types/index.d.ts CHANGED
@@ -413,7 +413,8 @@ export interface ChatSdkOptions {
413
413
  skills?: SkillSpec[];
414
414
  /** 用户创建 skill 的独立持久化存储(与 storage 选项分离)。默认 `{ backend: 'indexed' }`(即使 storage:false 也持久化);`false` 关闭;`id` 手动指定同一 id 可跨页面/跨 agent 复用 */
415
415
  skillStorage?: SkillStoreConfig | false;
416
- memory?: string;
416
+ /** AGENTS.md 风格持久指令。支持 string 与同步/异步函数(异步函数适合加载 RAG 文档) */
417
+ memory?: string | (() => string | Promise<string>);
417
418
  data?: DataConfig;
418
419
  permissions?: PermissionRule[];
419
420
  /** 自定义中间件(注入到内置中间件之后;可拦截/观察模型调用、工具、prompt) */
@@ -559,8 +560,10 @@ export interface ChatSdk {
559
560
  removeTool(name: string): boolean;
560
561
  /** 运行时切换 LLM(BaseChatModel 或 LLMConfig);rebind + 重解析能力 + infoTick */
561
562
  setLlm(llm: ChatModelLike | LLMConfig): void;
562
- /** 运行时更新 memory 文本;立即生效 + infoTick */
563
- setMemory(text: string): void;
563
+ /** 运行时更新 memory;支持 string 与同步/异步函数(异步函数后台求值,下一轮 beforeAgent 前就绪) */
564
+ setMemory(source: string | (() => string | Promise<string>)): void;
565
+ /** 重新求值当前 memory 函数 source(RAG 文档更新后强制刷新);返回最新文本 */
566
+ refreshMemory(): Promise<string>;
564
567
  /** 运行时替换预声明子 agent 列表(重新生成委派工具 + rebind);需创建时配 subagents:[] */
565
568
  setSubagents(configs: SubagentConfig[]): void;
566
569
  /** 运行时追加预声明子 agent(id 重复 warn 跳过);需创建时配 subagents:[] */
@@ -598,6 +601,16 @@ export interface ConflictInfo {
598
601
  }
599
602
 
600
603
  export declare function createChatSdk(options: ChatSdkOptions): ChatSdk;
604
+ // ============ system prompt 构建(promptBuilder,refactor-module-extraction 从 createChatSdk 抽离)============
605
+ /** 默认 systemPrompt(用户未传 systemPrompt 时用);含身份 + 能力概述 + 可靠写入规则 */
606
+ export declare const DEFAULT_SYSTEM_PROMPT: string;
607
+ /** 拼接「可操作数据」段(从 data schema .describe() 自动提取注入) */
608
+ export declare function buildDataPrompt(data: DataConfig | undefined): string;
609
+ /**
610
+ * 统一 systemPrompt base 段入口:处理 appendReliableWriteRules 分支 + '---' 分割线。
611
+ * 传 systemPrompt 默认追加 reliableWriteRules(设 appendReliableWriteRules:false 关闭);不传用 DEFAULT_SYSTEM_PROMPT(已内置)。纯函数。
612
+ */
613
+ export declare function buildSystemPrompt(opts: { systemPrompt?: string; appendReliableWriteRules?: boolean }): string;
601
614
  export declare function defineTool(opts: {
602
615
  name: string;
603
616
  description: string;
@@ -606,6 +619,57 @@ export declare function defineTool(opts: {
606
619
  }): any;
607
620
  export declare function createDataOps(config: DataConfig, opts?: DataOpsOptions): any[];
608
621
  export declare function filterByToolMode(tools: any[], mode?: 'simple' | 'advanced' | 'minimal'): any[];
622
+ // ============ 通用 JSON 操作纯函数(jsonUtils,refactor-module-extraction 从 dataOps 抽离;零依赖,经 ./query subpath 按需引入)============
623
+ export type EditOp = 'set' | 'remove' | 'merge' | 'append';
624
+ export declare const UNSAFE_KEYS: Set<string>;
625
+ export declare function isUnsafePath(path: string): boolean;
626
+ export declare function safeMerge(target: Record<string, any>, src: unknown): void;
627
+ export declare function getByPath(obj: unknown, path: string): unknown;
628
+ export declare function setByPath(obj: unknown, path: string, value: unknown): void;
629
+ export declare function deleteByPath(obj: unknown, path: string): boolean;
630
+ export declare function deepClone<T>(v: T): T;
631
+ export declare function maybeParseValue(v: unknown): { parsed?: unknown; parseError?: unknown };
632
+ export declare function projectFields(obj: unknown, fields: string[]): unknown;
633
+ export declare function limitDepth(obj: unknown, depth: number): unknown;
634
+ export declare function safeStringify(value: unknown, maxLen?: number): string;
635
+ export declare function hashValue(value: unknown): string;
636
+ export declare function applyPatchToClone(clone: any, op: EditOp, jsonPath: string, value: unknown): string | null;
637
+ export declare function applyPatchToLive(bind: any, op: EditOp, jsonPath: string, value: unknown): void;
638
+ export declare function restoreLive(bind: any, snapshotVal: unknown): void;
639
+ export declare function restoreInPlace(live: Record<string, unknown> | unknown[], snapshotVal: unknown): void;
640
+ // ============ schema 白名单投影纯函数(schemaUtils,refactor-module-extraction 从 dataOps 抽离)============
641
+ export declare function getSchemaTopKeys(schema: any): string[] | null;
642
+ export declare function isPathAllowed(jsonPath: string, schema: any | null, allowKeys: string[] | null): boolean;
643
+ export declare function unwrapSchema(schema: any): any;
644
+ export declare function getSchemaAtPath(schema: any, jsonPath: string): any | null;
645
+ export declare function projectBySchemaDeep(obj: unknown, schema: any | null): unknown;
646
+ export declare function projectBySchema(obj: unknown, allowKeys: string[] | null): unknown;
647
+ // ============ 上下文索引纯函数(contextIndex,refactor-module-extraction 期二 从 useContextManager 抽离)============
648
+ export declare const STOP_WORDS: Set<string>;
649
+ export declare function tokenize(text: string): string[];
650
+ export declare function estimateMessageTokens(m: any): number;
651
+ export declare function estimateRoundTokens(r: any): number;
652
+ export declare function indexSummarize(older: any[], preserve?: Set<string>): string;
653
+ export declare function recallRounds(older: any[], query: string, topK: number): any[];
654
+ // ============ LLM 解析(llmResolver,refactor-module-extraction 期二 从 createChatSdk 抽离)============
655
+ export declare function isChatModel(v: unknown): boolean;
656
+ export declare function resolveLlm(options: any): { modelCaps: any; summaryLlmInvoke: ((prompt: string) => Promise<string>) | undefined };
657
+ // ============ 乐观锁冲突管理器(conflictManager,refactor-module-extraction 期二 从 createChatSdk 抽离)============
658
+ export interface ConflictManager {
659
+ pendingConflict: import('vue').Ref<any | null>;
660
+ set(info: any): Promise<any>;
661
+ resolve(action: any): void;
662
+ }
663
+ export declare function createConflictManager(getEmit?: () => (((e: any) => void) | undefined)): ConflictManager;
664
+ // ============ 配置解析 + 事件系统(optionsResolver/events,refactor-module-extraction 期三)============
665
+ export declare function resolveStorage(storage: any): any | null;
666
+ export declare function resolveDialogConfig(opts: any): any;
667
+ export interface SdkEvents {
668
+ listeners: Set<(e: any) => void>;
669
+ emit: (e: any) => void;
670
+ hook(handler: (e: any) => void): () => void;
671
+ }
672
+ export declare function createSdkEvents(onEvent?: (e: any) => void): SdkEvents;
609
673
  export declare function selectBuiltinTools(caps: { dataOps?: boolean; fetch?: boolean } | undefined, dataOps: any[], fetchDocs: any[]): any[];
610
674
  export declare function createUsageHintsMiddleware(caps: { planning?: boolean; dataOps?: boolean; subagent?: boolean } | undefined, hasDataOps: boolean, toolMode?: 'simple' | 'advanced' | 'minimal'): any;
611
675
  export declare const fetchDocTools: any[];
@@ -618,6 +682,8 @@ export declare function detectGarbledToolCall(content: string): boolean;
618
682
  export declare function createSubagentMiddleware(opts: any): any;
619
683
  export declare function createVerifyMiddleware(opts: VerifyMiddlewareOptions): any;
620
684
  export declare function createWriteBackCheck(opts?: WriteBackCheckOptions): VerifyCheck;
685
+ export declare function createMemoryMiddleware(memory?: string | (() => string | Promise<string>)): any;
686
+ export type MemorySource = string | (() => string | Promise<string>);
621
687
  export declare const presets: Record<string, any>;
622
688
  /** systemPrompt 辅助片段(标准化最佳实践,拼进 systemPrompt 降低写错门槛) */
623
689
  export declare const systemPromptHelpers: {