From 79213315c6f9f7390becf6ac61ad1fa2527506ee Mon Sep 17 00:00:00 2001 From: olibaron Date: Tue, 24 Nov 2026 14:10:43 +0100 Subject: [PATCH] feat(memory): ship preset procedures recalled like learned ones The aeven preset ships procedures/linkedin-post.md, a browser procedure for LinkedIn's composer (link-card removal before media, content types, limits) recorded live from drafts. tool-capability reads the preset's procedure files and registers them through ctx.memory.ship(); the memos provider scores them beside the owner's learned procedures, a same-named user procedure supersedes a shipped one, and shipped hits lead the recall block so the unjudged budget cannot drop them. memory_get answers shipped ids; edit, forget and status changes decline them; the learner offers them for revision into the user's own copy. The browser send guard no longer asks for approval when plain Enter types a line break in a post composer; Cmd/Ctrl+Enter and send composers still ask, and the approval card names the triggering key or click. Co-Authored-By: Claude Opus 5.5 --- ...dures-recalled-like-learned-ones.i18n.yaml | 6 ++ ...d-procedures-recalled-like-learned-ones.md | 38 ++++++++ ...rocedures-recalled-like-learned-ones.zh.md | 38 ++++++++ docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 6 ++ docs/config-catalog.zh.md | 6 ++ docs/event-producer-consumer.i18n.yaml | 4 +- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/subsystems/memory.i18n.yaml | 4 +- docs/subsystems/memory.md | 18 +++- docs/subsystems/memory.zh.md | 18 +++- .../tool-capability/README.i18n.yaml | 4 +- packages/capability/tool-capability/README.md | 1 + .../capability/tool-capability/README.zh.md | 1 + .../capability/tool-capability/package.json | 3 +- .../capability/tool-capability/src/index.ts | 14 +++ .../capability/tool-capability/src/learner.ts | 30 +++--- .../capability/tool-capability/src/shipped.ts | 81 ++++++++++++++++ .../ui-approval/src/client/ApprovalPanel.tsx | 5 +- .../client/ui-approval/src/client/locales.ts | 9 ++ .../extensions/tool-cordis/src/api-catalog.ts | 21 +++- .../interaction/user-approval/src/index.ts | 2 +- .../interaction/user-approval/src/types.ts | 7 ++ packages/memory/memory-memos/README.i18n.yaml | 4 +- packages/memory/memory-memos/README.md | 2 +- packages/memory/memory-memos/README.zh.md | 2 +- packages/memory/memory-memos/src/runtime.ts | 95 ++++++++++++++----- packages/memory/memory/README.i18n.yaml | 4 +- packages/memory/memory/README.md | 2 +- packages/memory/memory/README.zh.md | 2 +- packages/memory/memory/src/index.ts | 77 ++++++++++++++- packages/memory/memory/src/types.ts | 24 +++++ .../presets/aeven/agent.cordis.yml | 8 +- .../presets/aeven/procedures/linkedin-post.md | 71 ++++++++++++++ .../browser-chromium/src/outbound-probe.ts | 29 +++++- packages/web/tool-browser/README.i18n.yaml | 4 +- packages/web/tool-browser/README.md | 2 +- packages/web/tool-browser/README.zh.md | 2 +- packages/web/tool-browser/src/index.ts | 15 ++- pnpm-lock.yaml | 3 + scripts/gen-cordis-catalog.ts | 1 + 42 files changed, 596 insertions(+), 75 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-11-24-shipped-procedures-recalled-like-learned-ones.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-11-24-shipped-procedures-recalled-like-learned-ones.md create mode 100644 .agents/notes/implemented/architecture/2026-11-24-shipped-procedures-recalled-like-learned-ones.zh.md create mode 100644 packages/capability/tool-capability/src/shipped.ts create mode 100644 packages/preset/agent-presets/presets/aeven/procedures/linkedin-post.md diff --git a/.agents/notes/implemented/architecture/2026-11-24-shipped-procedures-recalled-like-learned-ones.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-24-shipped-procedures-recalled-like-learned-ones.i18n.yaml new file mode 100644 index 0000000000..4cc8241eea --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-24-shipped-procedures-recalled-like-learned-ones.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-24-shipped-procedures-recalled-like-learned-ones.md +2026-11-24-shipped-procedures-recalled-like-learned-ones.md: 3e240dcafbfc7405ec45fc3c012579ad7bdc5d09 +2026-11-24-shipped-procedures-recalled-like-learned-ones.zh.md: b35d703921e7e4c824a20338cf9ac9d4ed38e1ec diff --git a/.agents/notes/implemented/architecture/2026-11-24-shipped-procedures-recalled-like-learned-ones.md b/.agents/notes/implemented/architecture/2026-11-24-shipped-procedures-recalled-like-learned-ones.md new file mode 100644 index 0000000000..3e240dcafb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-24-shipped-procedures-recalled-like-learned-ones.md @@ -0,0 +1,38 @@ +# Agent Note: Shipped procedures are recalled like learned ones, and Enter in a post composer is not a send + +Status: implemented + +English | [中文](2026-11-24-shipped-procedures-recalled-like-learned-ones.zh.md) + +## Problem + +Aeven needed site know-how for every user, starting with LinkedIn posting: the link preview card hides the Media button, two different controls are both labelled `Dismiss`, and one video never goes with images. A preset skill would carry it, but every skill puts its description into every session's catalog, so each new site makes every conversation longer. Learned procedures avoid that cost because memory recall offers only the ones a request matches, but they exist only per owner, as what that owner's agents learned. + +Recording the LinkedIn procedure also showed the send guard misreading the post composer: Enter there adds a line, yet the guard asked "Send this message on linkedin.com", and the approval card read the same for that Enter as for a click on Post, so the person could not tell a line break from publishing. + +## Decision + +### Shipped procedures + +- `ctx.memory.ship(procedures)` registers procedures a composition ships for every owner and returns the disposer; `shipped()` lists them, one per name, earliest live registration first. Each carries the id `shipped:` (`shippedProcedureId`), a description, a summary of at most 950 characters, the full procedure, and a domain. +- The memory service adds them to every turn-start `recall` as `shipped`. `@aeven/memory-memos` scores them with the owner's procedures (embedding of name and description, then shared words) and delivers a chosen one as an `active` procedure hit with its summary, except one whose name a non-archived procedure of the owner uses. When a shipped procedure qualifies but none ranks among the first `procedureCandidates`, the best one takes the last place: in the recorded check, an owner's own single-run LinkedIn procedure otherwise outranked the shipped one. An offered shipped procedure then leads the recall's hits: in the same check the unjudged block filled its 16,000 characters with retrieval hits and left out the shipped procedure, which arrived after them. +- The service answers a `trace` `detail` of a shipped id itself, so `memory_get` reads the full procedure, and declines `edit`, `forget`, and `setProcedureStatus` for one without reaching the provider. `procedures()` still lists only the owner's own, so Settings → Memory shows no shipped procedure. +- `@aeven/tool-capability` reads them from `shippedProcedures` (absolute directories, one Markdown file per procedure with `name`, `description`, `summary`, optional `domain` frontmatter) at load, fails the load on a malformed file, and registers them. The learner offers a shipped procedure the owner has no procedure of its name for as an active one it may update; an update is stored as the owner's own procedure of that name and supersedes the shipped one for that owner, with the status an update of an active procedure gets. +- The Aeven preset ships `procedures/` beside its composition; `linkedin-post` is the first procedure. Its steps come from a recorded run of every composer case in the sidebar browser, with nothing published. + +### Send guard and approval card + +- The outbound probe treats a plain Enter in a multi-line editor (`textarea` or `contenteditable`) as adding a line when the editor's dialog, form, or article shows a control whose label opens with a Post verb and none with a Send verb. Chat composers show Send and single-line inputs submit their form, so both keep asking, and so does Enter with Control, Meta, or Alt, which publishes in X's composer; `preview_press` passes that chord to the probe. +- `ApprovalOutbound.trigger` names the input that publishes, `{ kind: 'key', key }` or `{ kind: 'click', label }`; `preview_*` approvals set it from the probe, and the approval card shows it as an Action line in zh, en, and es. + +## Alternatives considered + +- **One preset skill per site.** Rejected because each skill's description enters every session's catalog, whatever the request. +- **Copying shipped procedures into each owner's memory.** Rejected because every account would hold a copy, Settings → Memory would list procedures the owner never made, and a shipped update would have to tell an untouched copy from one the learner revised. +- **Delivering a procedure when the sidebar browser shows its site.** Rejected because a request such as "post this on LinkedIn" made while the browser shows another page would get nothing. + +## Consequences + +- A shipped procedure costs a turn nothing unless recall chooses it; adding one is a Markdown file in the preset's `procedures/`. +- A shipped procedure changes only with a release, and an owner's learned copy of the same name stops receiving those changes. +- Enter in a post composer whose Post control is not labelled with a known Post verb in the page language still asks. diff --git a/.agents/notes/implemented/architecture/2026-11-24-shipped-procedures-recalled-like-learned-ones.zh.md b/.agents/notes/implemented/architecture/2026-11-24-shipped-procedures-recalled-like-learned-ones.zh.md new file mode 100644 index 0000000000..b35d703921 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-24-shipped-procedures-recalled-like-learned-ones.zh.md @@ -0,0 +1,38 @@ +# Agent Note:内置流程像已学流程一样被召回,发帖输入框中的 Enter 不算发送 + +Status: implemented + +[English](2026-11-24-shipped-procedures-recalled-like-learned-ones.md) | 中文 + +## Problem + +Aeven 需要为每个用户提供网站操作知识,先从 LinkedIn 发帖开始:链接预览卡会隐藏 Media 按钮,两个不同的控件都标为 `Dismiss`,一条视频从不与图片同发。预设技能可以承载这些内容,但每个技能都会把描述放进每个会话的目录,每多一个网站,每场对话就更长。已学流程没有这项开销,因为记忆召回只提供与请求匹配的流程,但它们只按所有者存在,是该所有者的代理学到的内容。 + +录制 LinkedIn 流程时还发现发送守卫误判发帖输入框:在那里按 Enter 只会换行,守卫却询问"Send this message on linkedin.com",而且审批卡对这次 Enter 和点击 Post 的显示完全相同,用户无法分辨换行与发布。 + +## Decision + +### 内置流程 + +- `ctx.memory.ship(procedures)` 注册组合为每个所有者内置的流程并返回 disposer;`shipped()` 按名称各列出一条,以最早仍有效的注册为准。每条带有 id `shipped:`(`shippedProcedureId`)、描述、最多 950 字符的摘要、完整流程和领域。 +- 记忆服务把它们作为 `shipped` 加入每次轮次开始的 `recall`。`@aeven/memory-memos` 把它们与所有者的流程一起评分(名称与描述的嵌入,再看共有词语),并把选中的一条作为带摘要的 `active` 流程命中提供;所有者有同名且未归档流程的除外。当有内置流程符合条件、但没有一条排进前 `procedureCandidates` 名时,最佳的一条占据最后一个位置:在记录的检查中,所有者自己从单次运行学到的 LinkedIn 流程原本会排在内置流程之前。被提供的内置流程随后排在召回命中的最前面:在同一次检查中,未经判定的召回块用检索命中填满了 16,000 字符,排在其后的内置流程被排除在外。 +- 服务自行回答对内置 id 的 `trace` `detail`,因此 `memory_get` 能读到完整流程;对内置流程的 `edit`、`forget` 和 `setProcedureStatus` 不触及提供方即拒绝。`procedures()` 仍只列出所有者自己的流程,所以 Settings → Memory 不显示内置流程。 +- `@aeven/tool-capability` 在加载时从 `shippedProcedures`(绝对目录,每条流程一个 Markdown 文件,frontmatter 含 `name`、`description`、`summary`、可选 `domain`)读取,文件格式错误即加载失败,然后注册。对所有者没有同名流程的内置流程,学习器把它当作可更新的 active 流程提供;更新结果存为所有者自己的同名流程,对该所有者取代内置流程,状态与更新一条 active 流程时相同。 +- Aeven 预设在其组合旁提供 `procedures/`;`linkedin-post` 是第一条流程。其步骤来自在侧栏浏览器中逐一录制的全部发帖输入框情形,期间未发布任何内容。 + +### 发送守卫与审批卡 + +- 当多行编辑器(`textarea` 或 `contenteditable`)所在的对话框、表单或文章显示一个标签以 Post 类动词开头的控件、且没有以 Send 类动词开头的控件时,外发探测把其中单独按下的 Enter 视为换行。聊天输入框显示 Send,单行输入框会提交表单,因此两者仍会询问;同时按住 Control、Meta 或 Alt 的 Enter 在 X 的输入框中会发布,同样仍会询问,`preview_press` 会把这种组合键交给探测。 +- `ApprovalOutbound.trigger` 指明发布所用的输入:`{ kind: 'key', key }` 或 `{ kind: 'click', label }`;`preview_*` 的审批根据探测结果设置它,审批卡以中、英、西三种语言将其显示为"操作"一行。 + +## Alternatives considered + +- **每个网站一个预设技能。** 否决,因为无论请求是什么,每个技能的描述都会进入每个会话的目录。 +- **把内置流程复制到每个所有者的记忆中。** 否决,因为每个账户都会持有一份副本,Settings → Memory 会列出所有者从未创建的流程,而内置流程更新时还得区分未改动的副本和学习器修订过的副本。 +- **在侧栏浏览器显示某网站时提供对应流程。** 否决,因为浏览器正显示其他页面时,像"把这条发到 LinkedIn"这样的请求将得不到任何流程。 + +## Consequences + +- 内置流程只有在召回选中它时才占用轮次开销;新增一条流程就是在预设的 `procedures/` 中加一个 Markdown 文件。 +- 内置流程只随发布版本更新,而所有者学到的同名副本不再接收这些更新。 +- 若发帖输入框的 Post 控件在页面语言中不以已知的 Post 类动词标注,其中的 Enter 仍会询问。 diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index a4c8b65c19..5f7d2284f0 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: 6a1e3b0f72bae01c7e14a0ce3412d1d145147e07 -config-catalog.zh.md: fbae5ec2bec5ad19f590c967d709d8bd8888294b +config-catalog.md: d7b952e5de52699e70e2f4d636713fa554236be0 +config-catalog.zh.md: fd00494bae237ecb100f482b5390c4a3c1560e35 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 6a1e3b0f72..d7b952e5de 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -5739,6 +5739,12 @@ export interface Config { maintenanceRenewMs: number /** Memory store: days an unconfirmed candidate procedure waits before it is archived. */ candidateTtlDays: number + /** + * Absolute directories of procedures this composition ships for every owner, one Markdown file each (see + * `readShippedProcedures`). They are registered with the memory service, which recalls them beside each owner's + * learned procedures; an owner's learned procedure with the same name supersedes one. Requires the memory service. + */ + shippedProcedures: string[] } ``` diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index fbae5ec2be..fd00494bae 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -5741,6 +5741,12 @@ export interface Config { maintenanceRenewMs: number /** Memory store: days an unconfirmed candidate procedure waits before it is archived. */ candidateTtlDays: number + /** + * Absolute directories of procedures this composition ships for every owner, one Markdown file each (see + * `readShippedProcedures`). They are registered with the memory service, which recalls them beside each owner's + * learned procedures; an owner's learned procedure with the same name supersedes one. Requires the memory service. + */ + shippedProcedures: string[] } ``` diff --git a/docs/event-producer-consumer.i18n.yaml b/docs/event-producer-consumer.i18n.yaml index e24e1cc484..4aa3c9a6b9 100644 --- a/docs/event-producer-consumer.i18n.yaml +++ b/docs/event-producer-consumer.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/event-producer-consumer.md -event-producer-consumer.md: 07e14eb88e60c6a2725f738450d7c5877c393088 -event-producer-consumer.zh.md: f355f6dd0aaaba059bfd80296c01216033227a1a +event-producer-consumer.md: c002b4d3e6e0169a1c11f86691c00ca454dd8a59 +event-producer-consumer.zh.md: 46d12f685a11153fb612652f42e03624c518a7a9 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 07e14eb88e..c002b4d3e6 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -26,7 +26,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:741`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:720`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:727`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:148`](../packages/interaction/user-approval/src/types.ts) | `session-controller` (`waterfall`), [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), [`automations`](../packages/core/automations), `remotes`, `session-controller` | +| `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:155`](../packages/interaction/user-approval/src/types.ts) | `session-controller` (`waterfall`), [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), [`automations`](../packages/core/automations), `remotes`, `session-controller` | | `attachment/missing` | `waterfall` | [`packages/attachment/attachment/src/index.ts:30`](../packages/attachment/attachment/src/index.ts) | [`attachment-local`](../packages/attachment/attachment-local) (`waterfall`) | [`hosted-app`](../packages/bundle/hosted-app) | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization) | | `browser/automation` | `waterfall` | [`packages/web/tool-browser/src/types.ts:37`](../packages/web/tool-browser/src/types.ts) | [`tool-browser`](../packages/web/tool-browser) (`waterfall`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index f355f6dd0a..46d12f685a 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -28,7 +28,7 @@ | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:741`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:720`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:727`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:148`](../packages/interaction/user-approval/src/types.ts) | `session-controller` (`waterfall`), [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), [`automations`](../packages/core/automations), `remotes`, `session-controller` | +| `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:155`](../packages/interaction/user-approval/src/types.ts) | `session-controller` (`waterfall`), [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), [`automations`](../packages/core/automations), `remotes`, `session-controller` | | `attachment/missing` | `waterfall` | [`packages/attachment/attachment/src/index.ts:30`](../packages/attachment/attachment/src/index.ts) | [`attachment-local`](../packages/attachment/attachment-local) (`waterfall`) | [`hosted-app`](../packages/bundle/hosted-app) | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization) | | `browser/automation` | `waterfall` | [`packages/web/tool-browser/src/types.ts:37`](../packages/web/tool-browser/src/types.ts) | [`tool-browser`](../packages/web/tool-browser) (`waterfall`) | `remotes` | diff --git a/docs/subsystems/memory.i18n.yaml b/docs/subsystems/memory.i18n.yaml index f769c2299b..d2a6f7f601 100644 --- a/docs/subsystems/memory.i18n.yaml +++ b/docs/subsystems/memory.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/memory.md -memory.md: d08e8339f41581ff7dae5d089231ede7da18dc64 -memory.zh.md: 0db41971f53f2810a2fb188914163d018b33d3d3 +memory.md: 5b9c612eb5d819864cf63494a67a9278cd49c259 +memory.zh.md: 7c628aed31eb55d2afc0ff8e00fa78ef26f18427 diff --git a/docs/subsystems/memory.md b/docs/subsystems/memory.md index d08e8339f4..5b9c612eb5 100644 --- a/docs/subsystems/memory.md +++ b/docs/subsystems/memory.md @@ -34,6 +34,22 @@ register(provider: MemoryProvider): () => void */ whileActive(setup: () => () => void): () => void +/** + * Register procedures a composition ships for every owner. Each name may appear once per registration; across + * registrations the earliest live one of a name is served. + * @param procedures - the procedures, each with the id {@link shippedProcedureId} gives its name. + * @returns idempotent disposer that withdraws them. + * @throws Error when a name repeats or an id does not match its name. + */ +ship(procedures: readonly ShippedProcedure[]): () => void + +/** + * The procedures registered with {@link ship}, one per name. An owner's learned procedure with the same name + * supersedes one in recall; callers that list procedures for an owner apply the same rule. + * @returns the shipped procedures. + */ +shipped(): readonly ShippedProcedure[] + /** * Retrieve memory relevant to a query within the request's foreground budget. * @param request - query, scope, and foreground budget. @@ -76,7 +92,7 @@ setProcedureStatus(request: Parameters[0]) async turnDomain(request: Parameters[0]): Promise /** - * Read one memory item. + * Read one memory item. A `trace` read of a shipped procedure's id answers with the procedure, without the provider. * @param request - scope, item kind, and id. * @returns the item, or undefined when the scope holds no such item. */ diff --git a/docs/subsystems/memory.zh.md b/docs/subsystems/memory.zh.md index 0db41971f5..7c628aed31 100644 --- a/docs/subsystems/memory.zh.md +++ b/docs/subsystems/memory.zh.md @@ -34,6 +34,22 @@ register(provider: MemoryProvider): () => void */ whileActive(setup: () => () => void): () => void +/** + * Register procedures a composition ships for every owner. Each name may appear once per registration; across + * registrations the earliest live one of a name is served. + * @param procedures - the procedures, each with the id {@link shippedProcedureId} gives its name. + * @returns idempotent disposer that withdraws them. + * @throws Error when a name repeats or an id does not match its name. + */ +ship(procedures: readonly ShippedProcedure[]): () => void + +/** + * The procedures registered with {@link ship}, one per name. An owner's learned procedure with the same name + * supersedes one in recall; callers that list procedures for an owner apply the same rule. + * @returns the shipped procedures. + */ +shipped(): readonly ShippedProcedure[] + /** * Retrieve memory relevant to a query within the request's foreground budget. * @param request - query, scope, and foreground budget. @@ -76,7 +92,7 @@ setProcedureStatus(request: Parameters[0]) async turnDomain(request: Parameters[0]): Promise /** - * Read one memory item. + * Read one memory item. A `trace` read of a shipped procedure's id answers with the procedure, without the provider. * @param request - scope, item kind, and id. * @returns the item, or undefined when the scope holds no such item. */ diff --git a/packages/capability/tool-capability/README.i18n.yaml b/packages/capability/tool-capability/README.i18n.yaml index dc077eb8d4..9f95dabb7b 100644 --- a/packages/capability/tool-capability/README.i18n.yaml +++ b/packages/capability/tool-capability/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/capability/tool-capability/README.md -README.md: eb7a0d334f790c174d4bc51fda19beecfe4a3176 -README.zh.md: 0c7998688ceb777d66ff6b975eb790ce8c592671 +README.md: 7983c5bd726c84153285c54bd933485b60698e33 +README.zh.md: 6d247b21dbce29b6ba02b67895940cf7dac51893 diff --git a/packages/capability/tool-capability/README.md b/packages/capability/tool-capability/README.md index eb7a0d334f..7983c5bd72 100644 --- a/packages/capability/tool-capability/README.md +++ b/packages/capability/tool-capability/README.md @@ -42,6 +42,7 @@ Mount it per agent beside a host `capability` registry (the `standard`, `cordis` | `maxInputTokens` | `32000` | Input budget of one learning model call, estimated at four characters per token; a longer transcript is condensed, then cut | | `consolidateAbove` | `40` | Memory store: distinct procedures a session sees above which procedures of one kind of task are merged in the background; `0` never merges | | `candidateTtlDays` | `30` | Memory store: days an unconfirmed `candidate` procedure waits before it is archived; archived procedures are kept for restoring but neither recalled nor merged into | +| `shippedProcedures` | `[]` | Absolute directories of procedures the composition ships for every user, one Markdown file each with `name`, `description`, `summary` (at most 950 characters), and an optional `domain` (`experience` or `world`) in its frontmatter and the procedure as its body. They are read at load, a malformed file fails the load, and they are registered with `ctx.memory.ship`: memory recall offers them beside each owner's learned procedures, and the learner offers one it may update, storing the update as the owner's own procedure of that name, which supersedes it for that owner. Requires the memory service | | `provider`, `model` | — | Explicit learning route; absent uses each session's route | With the memory store, learning waits for the person's next message and reads it as feedback: a correction or complaint about time shapes the procedure, and a reply that rejects or disputes the answer means nothing is learned. A turn memory filed as being about the person is never learned from. A written procedure is a `candidate` unless it replaces an `active` one without a correction; memory recall promotes a candidate once it informs work the person does not correct, and a correction or negative rating returns it to `candidate`. An update extends the procedure it rewrites: the learner keeps the steps, variants, facts, and recoveries the work did not show to be wrong, and gives each variant of the task its own steps. A procedure is rewritten or forgotten in favour of another only when the learner read its full text; when its first decision covers one it read clipped or by its one-line description, it decides again with those procedures in full, and one it still did not read whole is kept. A merge keeps each variant its members cover and stays `active` when one member was. A procedure saved because the person asked, or imported, is `active` at once. diff --git a/packages/capability/tool-capability/README.zh.md b/packages/capability/tool-capability/README.zh.md index 0c7998688c..6d247b21db 100644 --- a/packages/capability/tool-capability/README.zh.md +++ b/packages/capability/tool-capability/README.zh.md @@ -43,6 +43,7 @@ kind: "package-reference" | `maxInputTokens` | `32000` | 一次学习模型调用的输入预算,按每 token 四个字符估算;更长的 transcript(文本记录)先被精简,再被截断 | | `consolidateAbove` | `40` | memory 存储:会话能看到的不同流程超过此数时,同一类任务的流程会在后台合并;`0` 表示从不合并 | | `candidateTtlDays` | `30` | memory 存储:未获确认的 `candidate` 流程在归档前等待的天数;已归档的流程保留下来以便恢复,但既不被召回也不被合并 | +| `shippedProcedures` | `[]` | 组合为每个用户内置的流程所在的绝对目录,每条流程一个 Markdown 文件,frontmatter 含 `name`、`description`、`summary`(最多 950 字符)和可选的 `domain`(`experience` 或 `world`),正文为流程本身。加载时读取,格式错误的文件使加载失败,读取后经 `ctx.memory.ship` 注册:记忆召回将它们与每个所有者的已学流程一并提供,学习器也把它作为可更新的流程,更新结果存为所有者自己的同名流程,对该所有者取代内置流程。需要记忆服务 | | `provider`、`model` | — | 显式的学习路由;缺省时使用各会话自己的路由 | 使用 memory 存储时,学习会等到人的下一条消息,并把它读作反馈:一次纠正或对耗时的抱怨会改变流程,而一条否定或质疑答案的回复意味着什么都不学。被记录为关于这个人本身的轮次记忆永远不会成为学习素材。写下的流程是 `candidate`,除非它在没有纠正的情况下替换掉一条 `active` 流程;当它支撑了人未予纠正的工作后,记忆召回会把它提升为 `active`,而一次纠正或负面评价会把它退回 `candidate`。更新是对被重写流程的扩展:学习器保留这次工作未证明有误的步骤、变体、事实和恢复办法,并为任务的每个变体各写一组步骤。只有当学习器读过某条流程的全文时,该流程才会被重写或被另一条流程取代而遗忘;如果它的第一次决定涉及一条只读到截断文本或一行描述的流程,它会带着这些流程的全文重新决定,仍未读到全文的流程会被保留。合并会保留其成员覆盖的每个变体,只要有一个成员是 `active`,合并结果就是 `active`。因为这个人要求而保存或导入的流程立刻就是 `active`。 diff --git a/packages/capability/tool-capability/package.json b/packages/capability/tool-capability/package.json index f0d70de573..d8c2bcda21 100644 --- a/packages/capability/tool-capability/package.json +++ b/packages/capability/tool-capability/package.json @@ -28,7 +28,8 @@ "license": "Apache-2.0", "dependencies": { "@aeven/util-values": "workspace:^", - "@deepseek-ai/schemastery": "workspace:^" + "@deepseek-ai/schemastery": "workspace:^", + "yaml": "^2.4.2" }, "peerDependencies": { "@aeven/agent": "workspace:^", diff --git a/packages/capability/tool-capability/src/index.ts b/packages/capability/tool-capability/src/index.ts index 883da5fa01..53aab8792a 100644 --- a/packages/capability/tool-capability/src/index.ts +++ b/packages/capability/tool-capability/src/index.ts @@ -15,6 +15,7 @@ import { correctionOf, ExecutionTracker, slownessOf } from './executions.ts' import { CapabilityLearner, MIN_INPUT_TOKENS } from './learner.ts' import { condenseProcedure, forgetLearnedProcedures, LEARNED_DOMAINS, learnedIdsNamed, readProcedureImport, storeLearnedProcedure } from './memory-learning.ts' import { recallProcedures, PROCEDURE_GUIDANCE } from './recall.ts' +import { readShippedProcedures } from './shipped.ts' import { LEARNED_PROCEDURE_PREFIX, MEMORY_TOOL, memoryScopeOf, type MemoryDomain } from '@aeven/memory' import { defineTool, textOutput, textResult } from '@aeven/tools' import type {} from '@aeven/system-prompt' @@ -72,6 +73,12 @@ export interface Config { maintenanceRenewMs: number /** Memory store: days an unconfirmed candidate procedure waits before it is archived. */ candidateTtlDays: number + /** + * Absolute directories of procedures this composition ships for every owner, one Markdown file each (see + * `readShippedProcedures`). They are registered with the memory service, which recalls them beside each owner's + * learned procedures; an owner's learned procedure with the same name supersedes one. Requires the memory service. + */ + shippedProcedures: string[] } export const Config: z = z.object({ @@ -92,6 +99,7 @@ export const Config: z = z.object({ maintenanceTtlMs: z.natural().min(1_000).default(180_000), maintenanceRenewMs: z.natural().min(100).default(60_000), candidateTtlDays: z.natural().min(1).default(30), + shippedProcedures: z.array(z.string()).default([]), }) const TOOL = 'capability_manage' @@ -160,6 +168,12 @@ export function apply(ctx: Context, config: Config): void { if (inMemory && ctx.get('memory') === undefined) { throw new Error(`${name}: store "memory" requires the memory service; mount @aeven/memory or set store: capabilities`) } + if (config.shippedProcedures.length > 0) { + const memory = ctx.get('memory') + if (memory === undefined) throw new Error(`${name}: shippedProcedures requires the memory service; mount @aeven/memory`) + const shipped = readShippedProcedures(config.shippedProcedures) + ctx.effect(() => memory.ship(shipped), 'tool-capability.shipped') + } const learner = config.learn ? new CapabilityLearner(ctx, config) : undefined ctx.effect(() => () => learner?.dispose(), 'tool-capability.learner') /** Recorded executions of each session by turn, for corrections and ratings that arrive later. */ diff --git a/packages/capability/tool-capability/src/learner.ts b/packages/capability/tool-capability/src/learner.ts index 35b5204690..6713a734c5 100644 --- a/packages/capability/tool-capability/src/learner.ts +++ b/packages/capability/tool-capability/src/learner.ts @@ -373,24 +373,27 @@ const DAY_MS = 86_400_000 * Status of a procedure written from new work. Writing never proves a procedure: it is `active` only when it replaces * an active procedure without a correction, because an update extends what that procedure already proved. Anything * new or corrected is a `candidate`, which memory recall promotes once it informs work the user does not correct. - * @param previous - the stored procedures the new one replaces. + * @param previous - the stored and shipped procedures the new one replaces. * @param feedback - the user's next message after the work. * @returns the status to store. */ function procedureStatusAfter( - previous: readonly LearnedProcedure[], + previous: readonly Pick[], feedback: LearnerFeedback | undefined, ): ProcedureStatus { if (feedback?.kind === 'correction') return 'candidate' return previous.some(procedure => procedure.status === 'active') ? 'active' : 'candidate' } -function latestByName(procedures: readonly LearnedProcedure[]): Map { - const latest = new Map() +function latestByName(procedures: readonly T[]): Map { + const latest = new Map() for (const procedure of procedures) if (!latest.has(procedure.name)) latest.set(procedure.name, procedure) return latest } +/** What a distillation reads of a procedure it may update: an owner's learned procedure or a shipped one. */ +type ProcedureView = Pick + function overlap(a: ReadonlySet, b: ReadonlySet): number { let count = 0 for (const word of a) if (b.has(word)) count++ @@ -631,13 +634,18 @@ export class CapabilityLearner { await this.archiveStaleCandidates(owner, all, signal) const cutoff = Date.now() - this.config.candidateTtlDays * DAY_MS // Archived and expiring candidates are not offered for merging; work of their kind starts a fresh candidate. - const latest = latestByName(all.filter(procedure => procedure.status === 'active' + const owned = latestByName(all.filter(procedure => procedure.status === 'active' || (procedure.status === 'candidate' && procedure.time >= cutoff))) // The backlog is merged whether or not this work teaches anything new. - this.consolidateWhenNeeded(recent, latest.size) + this.consolidateWhenNeeded(recent, owned.size) + // A shipped procedure the owner has no procedure of its name for is offered like an active one: an update of it is + // stored as the owner's own procedure of that name, which supersedes it for this owner. + const shipped = this.ctx.memory.shipped().filter(procedure => !all.some(own => own.name === procedure.name)) + .map((procedure): ProcedureView => ({ ...procedure, time: 0, status: 'active' })) + const latest = new Map([...owned, ...shipped.map(procedure => [procedure.name, procedure] as const)]) const recalled = await recallLearnedNames(this.ctx, scope, `${work.request}\n\n${work.answer.slice(0, 600)}`, signal) const requestWords = words(work.request) - const rank = (procedure: LearnedProcedure): number => { + const rank = (procedure: ProcedureView): number => { // The procedure this work was already learned into is the one feedback refines, then what recall ranks. if (procedure.name === recent.learned?.name) return Number.MAX_SAFE_INTEGER const recalledAt = recalled.indexOf(procedure.name) @@ -648,16 +656,16 @@ export class CapabilityLearner { .sort((a, b) => b.score - a.score || b.procedure.time - a.procedure.time) const existing = ordered.slice(0, MAX_EXISTING_PROCEDURES) .map(({ procedure }) => `- ${procedure.name}: ${clip(procedure.description, EXISTING_LINE_CHARS)}`).join('\n') || '(none)' - const shown = (procedures: readonly LearnedProcedure[], maxChars: number) => procedures.map(procedure => ({ + const shown = (procedures: readonly ProcedureView[], maxChars: number) => procedures.map(procedure => ({ name: procedure.name, description: procedure.description, content: clip(procedure.content, maxChars), })) const related = ordered.filter(item => item.score >= 2).slice(0, MAX_RELATED_PROCEDURES).map(item => item.procedure) /** Names of the procedures a distillation read whole; only these may be rewritten or replaced. */ - const readWhole = (procedures: readonly LearnedProcedure[], maxChars: number): Set => + const readWhole = (procedures: readonly ProcedureView[], maxChars: number): Set => new Set(procedures.filter(procedure => procedure.content.length <= maxChars).map(procedure => procedure.name)) - const coveredBy = (made: Decision & { decision: 'create' | 'update' }): LearnedProcedure[] => { + const coveredBy = (made: Decision & { decision: 'create' | 'update' }): ProcedureView[] => { const names = new Set([made.name, ...made.replaces ?? []]) return [...latest.values()].filter(procedure => names.has(procedure.name)) } @@ -689,7 +697,7 @@ export class CapabilityLearner { const covered = new Set([decision.name, ...(decision.replaces ?? []).filter(name => whole.has(name))]) const previous = all.filter(procedure => covered.has(procedure.name)) const replaced = previous.map(procedure => procedure.id) - const status = procedureStatusAfter(previous, feedback) + const status = procedureStatusAfter([...previous, ...shipped.filter(procedure => covered.has(procedure.name))], feedback) const id = await storeLearnedProcedure(this.ctx, scope, { name: decision.name, description: decision.description, diff --git a/packages/capability/tool-capability/src/shipped.ts b/packages/capability/tool-capability/src/shipped.ts new file mode 100644 index 0000000000..89fc472e19 --- /dev/null +++ b/packages/capability/tool-capability/src/shipped.ts @@ -0,0 +1,81 @@ +/** + * Procedures a composition ships for every owner: one Markdown file each, read from the configured directories when + * the plugin loads and registered with the memory service, which recalls them beside each owner's learned procedures. + * + * @module @aeven/tool-capability/shipped + */ +import { readdirSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { parse } from 'yaml' +import { shippedProcedureId, type MemoryDomain, type ShippedProcedure } from '@aeven/memory' + +/** Kebab-case procedure name, as learned procedures use. */ +const NAME = /^[a-z0-9][a-z0-9-]{0,63}$/ + +/** YAML frontmatter between `---` lines, then the Markdown procedure. */ +const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/ + +/** Longest summary recall may deliver: the bound learned procedure summaries keep. */ +const SUMMARY_MAX = 950 + +/** Domains a shipped procedure may declare; one never belongs to a workspace, so `project` is excluded. */ +const DOMAINS = ['experience', 'world'] as const satisfies readonly MemoryDomain[] + +/** + * Read every `.md` file of the given directories as a shipped procedure. The frontmatter holds `name` (kebab-case), + * `description` (one line), `summary` (the condensed procedure recall delivers, at most 950 characters), and an + * optional `domain` (`experience`, the default, or `world`); the body is the full procedure. + * @param directories - absolute directories, read in order. + * @returns the procedures. + * @throws Error naming the file when a directory cannot be read, a file is malformed, or a name repeats. + */ +export function readShippedProcedures(directories: readonly string[]): ShippedProcedure[] { + const procedures: ShippedProcedure[] = [] + const names = new Set() + for (const directory of directories) { + for (const file of readdirSync(directory).filter(entry => entry.endsWith('.md')).sort()) { + const path = join(directory, file) + const procedure = parseShippedProcedure(readFileSync(path, 'utf8'), path) + if (names.has(procedure.name)) throw new Error(`${path}: shipped procedure ${procedure.name} is defined twice`) + names.add(procedure.name) + procedures.push(procedure) + } + } + return procedures +} + +/** + * Parse one shipped procedure file. + * @param text - the file's text. + * @param path - the file, for error messages. + * @returns the procedure. + * @throws Error naming the file and the field when the file is malformed. + */ +function parseShippedProcedure(text: string, path: string): ShippedProcedure { + const match = FRONTMATTER.exec(text) + if (match === null) throw new Error(`${path}: a shipped procedure starts with --- frontmatter`) + const meta: unknown = parse(match[1] ?? '') + const field = (key: string): string => { + const value = typeof meta === 'object' && meta !== null ? (meta as Record)[key] : undefined + if (typeof value !== 'string' || value.trim() === '') throw new Error(`${path}: frontmatter needs a non-empty ${key}`) + return value.trim() + } + const name = field('name') + if (!NAME.test(name)) throw new Error(`${path}: name ${name} is not kebab-case`) + const description = field('description') + if (description.includes('\n')) throw new Error(`${path}: description is one line`) + const summary = field('summary') + if (summary.length > SUMMARY_MAX) throw new Error(`${path}: summary is ${summary.length} characters; the limit is ${SUMMARY_MAX}`) + const declared = typeof meta === 'object' && meta !== null ? (meta as Record).domain : undefined + if (declared !== undefined && !(DOMAINS as readonly unknown[]).includes(declared)) throw new Error(`${path}: domain is one of ${DOMAINS.join(', ')}`) + const content = (match[2] ?? '').trim() + if (content === '') throw new Error(`${path}: the procedure body is empty`) + return { + id: shippedProcedureId(name), + name, + description, + summary, + content, + domain: (declared as MemoryDomain | undefined) ?? 'experience', + } +} diff --git a/packages/client/ui-approval/src/client/ApprovalPanel.tsx b/packages/client/ui-approval/src/client/ApprovalPanel.tsx index 194ca8ee16..36af2a523a 100644 --- a/packages/client/ui-approval/src/client/ApprovalPanel.tsx +++ b/packages/client/ui-approval/src/client/ApprovalPanel.tsx @@ -19,10 +19,13 @@ const SESSION_NOTES: Record void', + description: 'Register procedures a composition ships for every owner. Each name may appear once per registration; across registrations the earliest live one of a name is served.', + parameters: [{ name: 'procedures', description: 'the procedures, each with the id {@link shippedProcedureId} gives its name.' }], + returns: 'idempotent disposer that withdraws them.', + throws: ['Error when a name repeats or an id does not match its name.'], + }, + { + signature: 'shipped(): readonly ShippedProcedure[]', + description: 'The procedures registered with ship, one per name. An owner\'s learned procedure with the same name supersedes one in recall; callers that list procedures for an owner apply the same rule.', + parameters: [], + returns: 'the shipped procedures.', + }, { signature: 'recall(request: MemoryRecallRequest): Promise', description: 'Retrieve memory relevant to a query within the request\'s foreground budget.', @@ -2257,7 +2270,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'detail(request: Parameters[0]): Promise', - description: 'Read one memory item.', + description: 'Read one memory item. A `trace` read of a shipped procedure\'s id answers with the procedure, without the provider.', parameters: [{ name: 'request', description: 'scope, item kind, and id.' }], returns: 'the item, or undefined when the scope holds no such item.', }, @@ -8331,7 +8344,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'MemoryRecallRequest', - declaration: 'export interface MemoryRecallRequest {\n readonly scope: MemoryScope;\n readonly query: string;\n readonly request?: string;\n readonly context?: string;\n readonly recent?: {\n readonly hours: number;\n readonly items: number;\n readonly perSession: number;\n readonly sharingOnly: boolean;\n };\n readonly purpose: \'turn-start\' | \'tool\';\n readonly sessionOnly?: boolean;\n readonly limits?: MemoryRecallLimits;\n readonly timeoutMs: number;\n readonly signal: AbortSignal;\n}', + declaration: 'export interface MemoryRecallRequest {\n readonly scope: MemoryScope;\n readonly query: string;\n readonly request?: string;\n readonly context?: string;\n readonly recent?: {\n readonly hours: number;\n readonly items: number;\n readonly perSession: number;\n readonly sharingOnly: boolean;\n };\n readonly purpose: \'turn-start\' | \'tool\';\n readonly sessionOnly?: boolean;\n readonly limits?: MemoryRecallLimits;\n readonly shipped?: readonly ShippedProcedure[];\n readonly timeoutMs: number;\n readonly signal: AbortSignal;\n}', }, { name: 'MemoryRecord', @@ -9673,6 +9686,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ShellSandboxInfo', declaration: 'export interface ShellSandboxInfo {\n mode: SandboxMode;\n denied: boolean;\n enforcement?: SandboxEnforcement;\n runnerFailed?: boolean;\n}', }, + { + name: 'ShippedProcedure', + declaration: 'export interface ShippedProcedure {\n readonly id: MemoryItemId;\n readonly name: string;\n readonly description: string;\n readonly summary: string;\n readonly content: string;\n readonly domain: MemoryDomain;\n}', + }, { name: 'SkillCandidate', declaration: 'export interface SkillCandidate extends SkillSummary {\n readonly rank: number;\n readonly locator: unknown;\n readonly path?: string;\n readonly metadata?: Readonly>;\n}', diff --git a/packages/interaction/user-approval/src/index.ts b/packages/interaction/user-approval/src/index.ts index 8925f8940d..a267ca569f 100644 --- a/packages/interaction/user-approval/src/index.ts +++ b/packages/interaction/user-approval/src/index.ts @@ -43,7 +43,7 @@ import { ApprovalRequestId } from './types.ts' import type { ApprovalAnswer, ApprovalOutcome, ApprovalRequestEvent } from './types.ts' export { ApprovalRequestId } from './types.ts' -export type { ApprovalOutbound, ApprovalOutboundKind, ApprovalOutcome, SessionGrantCoverage } from './types.ts' +export type { ApprovalOutbound, ApprovalOutboundKind, ApprovalOutboundTrigger, ApprovalOutcome, SessionGrantCoverage } from './types.ts' /** Every {@link ApprovalOutcome}, for runtime normalization of answerer returns. */ const OUTCOMES: readonly ApprovalAnswer[] = ['allowed-session', 'allowed-once', 'rejected', 'cancelled', 'unavailable'] diff --git a/packages/interaction/user-approval/src/types.ts b/packages/interaction/user-approval/src/types.ts index de8a1c1310..92eac52e66 100644 --- a/packages/interaction/user-approval/src/types.ts +++ b/packages/interaction/user-approval/src/types.ts @@ -75,8 +75,15 @@ export interface ApprovalOutbound { readonly subject?: string /** The text that goes out. */ readonly text?: string + /** The input that publishes: a key pressed in the composer, or a click on the control with this label; absent when unknown. */ + readonly trigger?: ApprovalOutboundTrigger } +/** The input that publishes an outbound action. */ +export type ApprovalOutboundTrigger = + | { readonly kind: 'key'; readonly key: string } + | { readonly kind: 'click'; readonly label: string } + declare module '@aeven/session/types' { interface SessionEventMap { /** diff --git a/packages/memory/memory-memos/README.i18n.yaml b/packages/memory/memory-memos/README.i18n.yaml index 4c2166f67f..9b89b00d61 100644 --- a/packages/memory/memory-memos/README.i18n.yaml +++ b/packages/memory/memory-memos/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/memory/memory-memos/README.md -README.md: b736a69dadc014de2d46e17f7eac8f5453b88ee3 -README.zh.md: 20e0353c2a755cc9c9ad4f17f326dc8f32b6caf4 +README.md: 8317a1e20e7ee9e6d2e15f0afec842d9b7cb364b +README.zh.md: a054d7db451d9d253413752af12a7813039c0317 diff --git a/packages/memory/memory-memos/README.md b/packages/memory/memory-memos/README.md index b736a69dad..8317a1e20e 100644 --- a/packages/memory/memory-memos/README.md +++ b/packages/memory/memory-memos/README.md @@ -48,7 +48,7 @@ Mount it on the host plane beside `@aeven/memory`. The web bundle ships the row | — | — | Each account's `memory-recall` settings section (per account, registered here) holds `judge`, off by default: with it off, turn-start recall runs no relevance judgment and delivers every candidate, learned procedures included, marked `unjudged`, and a later turn receives no recent memories, which only a judgment can call personal. On 47 recorded turns, answers given every candidate were graded better than judged ones 23 times and worse 14 times, and the judgment's call adds about a second before each answer. | | `relevanceTimeoutMs` | `4000` | Longest the turn-start relevance judgment may take; it gets what retrieval left of the recall budget, capped by this value. On failure or timeout at most two mechanically ranked memories are delivered and the recall is marked degraded | | `relevanceHedgeMs` | `2000` | Milliseconds after which an unanswered judgment is sent once more with the same prompt; a request that fails or answers unusably before then is resent at once. The first usable answer wins and the other request is cancelled. `0` sends one request only | -| `procedureCandidates` | `3` | Most learned procedures a turn-start recall offers the relevance judgment beside what retrieval found. Procedures are few among all memories and written as steps, so retrieval on the person's words seldom returns them; recall instead embeds each procedure's name and description once, embeds the request, and offers the closest ones that clear `procedureMinMargin`, then those whose name and description share words with the request and the conversation before it (a word more than three procedure names share does not count). The owner's procedure list is kept in memory until a memory write or ten minutes retire it. `0` offers none | +| `procedureCandidates` | `3` | Most learned procedures a turn-start recall offers the relevance judgment beside what retrieval found. Procedures are few among all memories and written as steps, so retrieval on the person's words seldom returns them; recall instead embeds each procedure's name and description once, embeds the request, and offers the closest ones that clear `procedureMinMargin`, then those whose name and description share words with the request and the conversation before it (a word more than three procedure names share does not count). Procedures the composition ships (the request's `shipped`) compete in the same way, except one whose name a procedure of the owner uses; each is delivered as an `active` procedure under its `shipped:` id, and the best one that qualifies takes the last offered place when none ranks among the first `procedureCandidates`. An offered shipped procedure leads the recall's hits, ahead of the retrieval hits, so a block's character budget never leaves it out. The owner's procedure list is kept in memory until a memory write or ten minutes retire it. `0` offers none | | `procedureMinMargin` | `0.035` | How far above the median cosine similarity of the owner's procedures a procedure must stand to be offered; relative because the model's similarities sit in a narrow band. Applies with the local embedding provider and at least six procedures; otherwise shared words decide alone | | `relevanceMinMs` | `3500` | Shortest window the judgment gets even when retrieval used most of the recall budget, capped by `relevanceTimeoutMs`; the recall then finishes up to this long after its budget. `0` gives the judgment only what retrieval left | | `profile` | enabled, `maxChars` 6000, `batchFacts` 150, `refreshMs` 600000, `timeoutMs` 180000 | Person profile distilled from all of the owner's person memories regardless of age; needs `hostLlm`. | diff --git a/packages/memory/memory-memos/README.zh.md b/packages/memory/memory-memos/README.zh.md index 20e0353c2a..a054d7db45 100644 --- a/packages/memory/memory-memos/README.zh.md +++ b/packages/memory/memory-memos/README.zh.md @@ -49,7 +49,7 @@ kind: "package-reference" | — | — | 每个账户的 `memory-recall` 设置分区(按账户,由本包注册)保存 `judge`,默认关闭:关闭时轮次开始召回不运行相关性判定,交付全部候选(包括已学流程),标记为 `unjudged`,且后续轮次不接收近期记忆,因为只有判定才能断定一个轮次是个人话题。在 47 个记录的轮次上,拿到全部候选的回答有 23 次被评为优于经判定的回答,14 次较差;判定调用让每个回答晚大约一秒开始。 | | `relevanceTimeoutMs` | `4000` | 轮次开始相关性判定的最长时间;它获得检索剩下的召回预算,以此值为上限。失败或超时最多返回两个机械排序结果并标记降级 | | `relevanceHedgeMs` | `2000` | 判定在这么多毫秒后仍未答复时,用相同提示词再发送一次;在此之前失败或答复不可用的请求会立即重发。第一个可用答复胜出,另一个请求被取消。`0` 只发送一次请求 | -| `procedureCandidates` | `3` | 轮次开始的召回在检索结果之外,最多向相关性判定提供的已学流程数。流程在全部记忆中数量很少且以步骤写成,按此人的用词检索很少能返回它们;召回因此把每条流程的名称和描述嵌入一次,再嵌入请求,提供超过 `procedureMinMargin` 的最接近的流程,然后是名称和描述与请求及此前对话共有词语的流程(出现在三个以上流程名称中的词不计入)。所有者的流程列表保存在内存中,直到一次记忆写入或十分钟后失效。`0` 不提供 | +| `procedureCandidates` | `3` | 轮次开始的召回在检索结果之外,最多向相关性判定提供的已学流程数。流程在全部记忆中数量很少且以步骤写成,按此人的用词检索很少能返回它们;召回因此把每条流程的名称和描述嵌入一次,再嵌入请求,提供超过 `procedureMinMargin` 的最接近的流程,然后是名称和描述与请求及此前对话共有词语的流程(出现在三个以上流程名称中的词不计入)。组合内置的流程(请求中的 `shipped`)以同样方式参与竞争,所有者已有同名流程的除外;每条以 `active` 流程的身份、用其 `shipped:` id 提供;若没有一条排进前 `procedureCandidates` 名,符合条件的最佳内置流程占据最后一个提供位置。被提供的内置流程排在召回命中的最前面、位于检索命中之前,因此召回块的字符预算不会把它排除在外。所有者的流程列表保存在内存中,直到一次记忆写入或十分钟后失效。`0` 不提供 | | `procedureMinMargin` | `0.035` | 一条流程与请求的余弦相似度必须高出所有者全部流程相似度中位数多少才会被提供;采用相对值是因为模型的相似度集中在很窄的范围内。仅在使用本地嵌入提供方且至少有六条流程时生效;否则只由共有词语决定 | | `relevanceMinMs` | `3500` | 即使检索用掉了召回预算的大部分,判定也至少获得的窗口,以 `relevanceTimeoutMs` 为上限;召回因此最多可在预算之后这么久才结束。`0` 只给判定检索剩下的时间 | | `profile` | enabled、`maxChars` 6000、`batchFacts` 150、`refreshMs` 600000、`timeoutMs` 180000 | 从该所有者全部 person 记忆中不分记录早晚蒸馏出的画像;需要 `hostLlm`。 | diff --git a/packages/memory/memory-memos/src/runtime.ts b/packages/memory/memory-memos/src/runtime.ts index 5ae34e3da0..3be3db1370 100644 --- a/packages/memory/memory-memos/src/runtime.ts +++ b/packages/memory/memory-memos/src/runtime.ts @@ -2,7 +2,7 @@ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { brandString } from '@aeven/brand' -import { LEARNED_PROCEDURE_PREFIX, MEMORY_TOOL, memoryOriginLabel, mergeRankedHits } from '@aeven/memory' +import { isShippedProcedureId, LEARNED_PROCEDURE_PREFIX, MEMORY_TOOL, memoryOriginLabel, mergeRankedHits, type ShippedProcedure } from '@aeven/memory' import type { MemoryDetail, MemoryDomain, @@ -194,11 +194,10 @@ const PROCEDURE_LIST_TTL_MS = 600_000 const PROCEDURE_MEDIAN_MIN = 6 /** One current learned procedure. */ -interface ProcedureEntry { - readonly trace: TraceDTO - readonly name: string - readonly description: string -} +/** One procedure a recall may offer: the owner's learned procedure, read from its trace, or one the composition ships. */ +type ProcedureEntry = + | { readonly source: 'owner'; readonly id: string; readonly trace: TraceDTO; readonly name: string; readonly description: string } + | { readonly source: 'shipped'; readonly id: string; readonly procedure: ShippedProcedure; readonly name: string; readonly description: string } /** The procedures one recall may offer and, when the request was embedded, each one's similarity to it by trace id. */ interface ProcedureScan { @@ -581,7 +580,12 @@ export class MemosMemory implements MemoryProvider { const topic = withoutExactIdentifiers(request.query) if (topic !== request.query && topic.length > 0) hits = await this.search({ ...request, query: topic }, deadlineAt, turnStart) } - if (procedureScan !== undefined) hits = [...hits, ...this.procedureHits(request, hits, await procedureScan)] + if (procedureScan !== undefined) { + const offered = this.procedureHits(request, hits, await procedureScan) + // A shipped procedure is written for its kind of task, so it leads: the block's character budget then never + // drops it in favour of the retrieval hits that fill the block before the procedures. + hits = [...offered.filter(hit => isShippedProcedureId(hit.id)), ...hits, ...offered.filter(hit => !isShippedProcedureId(hit.id))] + } if (!judged && this.options.relevance !== undefined) { // No judgment decides whether a later turn is personal, so recent memories join only where they always do. const recent = recentScan === undefined || request.recent?.sharingOnly === true @@ -662,7 +666,7 @@ export class MemosMemory implements MemoryProvider { if (header === null) continue const [, name = '', description = ''] = header const known = newest.get(name) - if (known === undefined || known.trace.ts < trace.ts) newest.set(name, { trace, name, description }) + if (known === undefined || (known.source === 'owner' && known.trace.ts < trace.ts)) newest.set(name, { source: 'owner', id: trace.id, trace, name, description }) } return [...newest.values()] })() @@ -693,26 +697,26 @@ export class MemosMemory implements MemoryProvider { this.procedureVectors.set(owner, vectors) } const text = (entry: ProcedureEntry): string => `${entry.name.replaceAll('-', ' ')}: ${entry.description}` - const missing = entries.filter(entry => vectors.get(entry.trace.id)?.text !== text(entry)) + const missing = entries.filter(entry => vectors.get(entry.id)?.text !== text(entry)) const [query, documents] = await Promise.all([ embed(owner, [{ text: asked, role: 'query' }], signal), missing.length === 0 ? [] : embed(owner, missing.map(entry => ({ text: text(entry), role: 'document' as const })), signal), ]) for (const [index, entry] of missing.entries()) { const vector = documents[index] - if (vector !== undefined) vectors.set(entry.trace.id, { text: text(entry), vector }) + if (vector !== undefined) vectors.set(entry.id, { text: text(entry), vector }) } - const current = new Set(entries.map(entry => entry.trace.id)) + const current = new Set(entries.map(entry => entry.id)) for (const id of vectors.keys()) if (!current.has(id)) vectors.delete(id) const asking = query[0] if (asking === undefined) return undefined const scores = new Map() for (const entry of entries) { - const vector = vectors.get(entry.trace.id)?.vector + const vector = vectors.get(entry.id)?.vector if (vector === undefined || vector.length !== asking.length) continue let dot = 0 for (let index = 0; index < vector.length; index++) dot += (vector[index] ?? 0) * (asking[index] ?? 0) - scores.set(entry.trace.id, dot) + scores.set(entry.id, dot) } return scores } @@ -727,10 +731,14 @@ export class MemosMemory implements MemoryProvider { const { scope } = request const late = `Memory recall exceeded ${request.timeoutMs}ms` const workspace = this.workspaceOf(scope.cwd) + const owned = await withDeadline(this.procedureList(scope.owner), deadlineAt, request.signal, late) + // A shipped procedure stands aside for the owner's own procedure of its name. + const ownNames = new Set(owned.map(entry => entry.name)) + const shipped = (request.shipped ?? []).filter(procedure => !ownNames.has(procedure.name)) + .map((procedure): ProcedureEntry => ({ source: 'shipped', id: procedure.id, procedure, name: procedure.name, description: procedure.description })) // Project procedures stay in their project, as project memories do. - const entries = (await withDeadline(this.procedureList(scope.owner), deadlineAt, request.signal, late)) - .filter(entry => scope.cwd === undefined || traceDomain(entry.trace.tags, entry.trace.ownerWorkspaceId) !== 'project' - || entry.trace.ownerWorkspaceId === workspace) + const entries = [...owned.filter(entry => entry.source !== 'owner' || scope.cwd === undefined + || traceDomain(entry.trace.tags, entry.trace.ownerWorkspaceId) !== 'project' || entry.trace.ownerWorkspaceId === workspace), ...shipped] try { const similarity = await withDeadline( this.procedureSimilarity(scope.owner, entries, request.request ?? request.query, request.signal), deadlineAt, request.signal, late, @@ -768,15 +776,30 @@ export class MemosMemory implements MemoryProvider { // With few procedures the median is one of the candidates, so the margin says nothing. const floor = sorted.length < PROCEDURE_MEDIAN_MIN ? Number.POSITIVE_INFINITY : (sorted[Math.floor(sorted.length / 2)] ?? 0) + (this.options.procedureEmbedding?.minMargin ?? 0) - return entries - .map(({ trace, name, description }) => { - const close = similarity?.get(trace.id) ?? 0 - return { trace, close: close >= floor ? close : 0, words: procedureMatch(asked, name, description, common) } + const ranked = entries + .map((entry) => { + const close = similarity?.get(entry.id) ?? 0 + return { entry, close: close >= floor ? close : 0, words: procedureMatch(asked, entry.name, entry.description, common) } }) - .filter(({ trace, close, words }) => (close > 0 || words >= PROCEDURE_MATCH_MIN) && !seen.has(trace.id)) - .sort((a, b) => b.close - a.close || b.words - a.words || b.trace.ts - a.trace.ts) - .slice(0, this.options.procedureCandidates ?? 0) - .map(({ trace }) => { + .filter(({ entry, close, words }) => (close > 0 || words >= PROCEDURE_MATCH_MIN) && !seen.has(entry.id)) + // A shipped procedure has no recorded time, so among equals the owner's newest procedures come first. + .sort((a, b) => b.close - a.close || b.words - a.words || procedureTime(b.entry) - procedureTime(a.entry)) + return withShippedSlot(ranked, this.options.procedureCandidates ?? 0) + .map(({ entry }) => { + if (entry.source === 'shipped') { + const memory: MemoryHit = { + kind: 'trace', + id: entry.procedure.id, + domain: entry.procedure.domain, + tier: 2, + score: 0, + snippet: `${LEARNED_PROCEDURE_PREFIX} ${entry.name}: ${entry.procedure.summary}`, + procedureStatus: 'active', + } + this.candidateKinds.set(memory, 'procedure') + return memory + } + const { trace } = entry const domain = traceDomain(trace.tags, trace.ownerWorkspaceId) const memory: MemoryHit = { kind: 'trace', @@ -1838,6 +1861,30 @@ function withOriginLabel(text: string, trace: TraceDTO): string { /** Tag of an imported fact whose original time is unknown; its trace time is the import time, not its age. */ const UNDATED_TAG = 'imported:undated' +/** + * The first `limit` ranked candidates, with the best qualifying shipped procedure in the last place when none made + * the cut: an owner's many procedures of one subject, learned from single runs, would otherwise always outrank the + * one the composition ships for it. + * @param ranked - the qualifying candidates, best first. + * @param limit - how many to offer. + * @returns at most `limit` candidates, best first. + */ +function withShippedSlot(ranked: readonly T[], limit: number): T[] { + const top = ranked.slice(0, limit) + if (limit === 0 || top.some(({ entry }) => entry.source === 'shipped')) return top + const shipped = ranked.find(({ entry }) => entry.source === 'shipped') + return shipped === undefined ? top : [...top.slice(0, limit - 1), shipped] +} + +/** + * When a procedure was recorded, for ordering equally close candidates. + * @param entry - an owner's or a shipped procedure. + * @returns the trace time, or 0 for a shipped procedure. + */ +function procedureTime(entry: ProcedureEntry): number { + return entry.source === 'owner' ? entry.trace.ts : 0 +} + /** Tag prefix of a learned procedure's status, as in `procedure:active`. */ const PROCEDURE_TAG = 'procedure:' diff --git a/packages/memory/memory/README.i18n.yaml b/packages/memory/memory/README.i18n.yaml index 8b4ae1be9d..599a787336 100644 --- a/packages/memory/memory/README.i18n.yaml +++ b/packages/memory/memory/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/memory/memory/README.md -README.md: 4839e11bebcfa796314914d6b8d83c6184c11c0f -README.zh.md: f0fc5af06a6379dd3cbc5e41ac330e7751f75363 +README.md: 0fdf6ab19895d86402687b297abdc8d246f9379d +README.zh.md: 69746355c329d764e7c7920a8818754db8d46789 diff --git a/packages/memory/memory/README.md b/packages/memory/memory/README.md index 4839e11beb..0fdf6ab198 100644 --- a/packages/memory/memory/README.md +++ b/packages/memory/memory/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -`avn-memory` provides `ctx.memory`, a slot for one long-term memory provider. Consumers call `recall`, `profile`, `capture`, `closeSession`, the read operations (`detail`, `timeline`, `environments`, `skills`, `useSkill`), and the owner's memory operations (`list`, `remember`, `edit`, `forget`, `feedback`) without knowing the backing implementation. `list` takes an optional `domains` filter; its page, offset, and total then count only memories in those domains. With `cwd`, `list` leaves out the project memory of every other workspace, as recall does. `procedures({ owner, cwd? })` lists the owner's learned procedures, newest first: memories whose text is `Learned procedure : ` followed by the Markdown procedure, written by `@aeven/tool-capability`. `profile({ scope })` returns lasting knowledge drawn from all of the owner's person memories regardless of age: every recorded yearly date (`MemoryDate`: birth, wedding, death, or anniversary, with its year when known) and, once the provider distilled one, a profile text; the provider brings the profile up to date in the background on the scope's route. `memoryOriginLabel(hit, now)` adds how long ago a memory was recorded. `LEARNED_PROCEDURE_PREFIX` and `learnedProcedureOf(record)` expose that text form to the Settings manager. `edit` and `forget` act only on memories of the scope's owner. Every memory has a domain (`MemoryDomain`): `person` and `world` and `experience` memories are recalled in every session of the owner, `project` memories only in sessions of the workspace they were captured in, and providers return no other workspace's project memory. Memory belongs to one signed-in user: every `MemoryScope` carries the owning account id from `SessionHeader.owner`. It also exports `memoryScopeOf(agent)`, which derives that scope and the session's model route, and returns undefined for a session without an owner, so such a session has no memory; and `MEMORY_TOOL`, the model-facing tool names that provider-rendered recall context may reference. +`avn-memory` provides `ctx.memory`, a slot for one long-term memory provider. Consumers call `recall`, `profile`, `capture`, `closeSession`, the read operations (`detail`, `timeline`, `environments`, `skills`, `useSkill`), and the owner's memory operations (`list`, `remember`, `edit`, `forget`, `feedback`) without knowing the backing implementation. `list` takes an optional `domains` filter; its page, offset, and total then count only memories in those domains. With `cwd`, `list` leaves out the project memory of every other workspace, as recall does. `procedures({ owner, cwd? })` lists the owner's learned procedures, newest first: memories whose text is `Learned procedure : ` followed by the Markdown procedure, written by `@aeven/tool-capability`. `ship(procedures)` registers procedures a composition ships for every owner and returns the disposer; `shipped()` lists them, one per name. A turn-start `recall` hands them to the provider as `shipped`, which offers each beside the owner's learned procedures unless a non-archived procedure of the owner uses its name; a `trace` `detail` of a shipped id (`shipped:`, from `shippedProcedureId`) answers with the procedure, and `edit`, `forget`, and `setProcedureStatus` decline one without reaching the provider. `procedures` lists only the owner's own. `profile({ scope })` returns lasting knowledge drawn from all of the owner's person memories regardless of age: every recorded yearly date (`MemoryDate`: birth, wedding, death, or anniversary, with its year when known) and, once the provider distilled one, a profile text; the provider brings the profile up to date in the background on the scope's route. `memoryOriginLabel(hit, now)` adds how long ago a memory was recorded. `LEARNED_PROCEDURE_PREFIX` and `learnedProcedureOf(record)` expose that text form to the Settings manager. `edit` and `forget` act only on memories of the scope's owner. Every memory has a domain (`MemoryDomain`): `person` and `world` and `experience` memories are recalled in every session of the owner, `project` memories only in sessions of the workspace they were captured in, and providers return no other workspace's project memory. Memory belongs to one signed-in user: every `MemoryScope` carries the owning account id from `SessionHeader.owner`. It also exports `memoryScopeOf(agent)`, which derives that scope and the session's model route, and returns undefined for a session without an owner, so such a session has no memory; and `MEMORY_TOOL`, the model-facing tool names that provider-rendered recall context may reference. ## Table of Contents diff --git a/packages/memory/memory/README.zh.md b/packages/memory/memory/README.zh.md index f0fc5af06a..69746355c3 100644 --- a/packages/memory/memory/README.zh.md +++ b/packages/memory/memory/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -`avn-memory` 提供 `ctx.memory`,即单一长期记忆提供方的槽位。消费方调用 `recall`、`profile`、`capture`、`closeSession`,读取类操作(`detail`、`timeline`、`environments`、`skills`、`useSkill`),以及所有者的记忆操作(`list`、`remember`、`edit`、`forget`、`feedback`),完全不需要知道背后的实现。`list` 接受可选的 `domains` 过滤;它的分页、偏移与总数随后只统计这些领域中的记忆。给出 `cwd` 时,`list` 与召回一样,略去其他每个工作区的项目记忆。`procedures({ owner, cwd? })` 按从新到旧列出所有者的已学流程:文本为 `Learned procedure : ` 后接 Markdown 流程的记忆,由 `@aeven/tool-capability` 写入。`profile({ scope })` 返回从该所有者全部 person 记忆中不分记录早晚取得的长期知识:每一条有记录的年度日期(`MemoryDate`:出生、婚礼、离世或纪念日,已知时带年份),以及提供方蒸馏出画像后的画像文本;提供方在作用域的路由上于后台把画像更新到最新。`memoryOriginLabel(hit, now)` 额外给出这条记忆是多久以前记录的。`LEARNED_PROCEDURE_PREFIX` 与 `learnedProcedureOf(record)` 向 Settings 管理器公开这种文本形式。`edit` 与 `forget` 只作用于该作用域所有者的记忆。每条记忆都有一个领域(`MemoryDomain`):`person`、`world` 与 `experience` 记忆在该所有者的每个会话中都被召回,`project` 记忆只在捕获它的那个工作区的会话中被召回,提供方不返回其他工作区的项目记忆。记忆属于一个已登录用户:每个 `MemoryScope` 都携带来自 `SessionHeader.owner` 的所有者账户 id。它还导出 `memoryScopeOf(agent)`,由它推导该作用域与该会话的模型路由,并对没有所有者的会话返回 undefined,因此这样的会话没有记忆;此外还导出 `MEMORY_TOOL`,即提供方渲染的召回上下文可以引用的、面向模型的工具名。 +`avn-memory` 提供 `ctx.memory`,即单一长期记忆提供方的槽位。消费方调用 `recall`、`profile`、`capture`、`closeSession`,读取类操作(`detail`、`timeline`、`environments`、`skills`、`useSkill`),以及所有者的记忆操作(`list`、`remember`、`edit`、`forget`、`feedback`),完全不需要知道背后的实现。`list` 接受可选的 `domains` 过滤;它的分页、偏移与总数随后只统计这些领域中的记忆。给出 `cwd` 时,`list` 与召回一样,略去其他每个工作区的项目记忆。`procedures({ owner, cwd? })` 按从新到旧列出所有者的已学流程:文本为 `Learned procedure : ` 后接 Markdown 流程的记忆,由 `@aeven/tool-capability` 写入。`ship(procedures)` 注册组合为每个所有者内置的流程并返回 disposer;`shipped()` 按名称各列出一条。轮次开始的 `recall` 把它们作为 `shipped` 交给提供方,提供方将每条与所有者的已学流程一并提供,除非所有者有同名且未归档的流程;对内置流程 id(`shipped:`,由 `shippedProcedureId` 生成)的 `trace` `detail` 直接返回该流程,`edit`、`forget` 和 `setProcedureStatus` 不触及提供方即拒绝它。`procedures` 只列出所有者自己的流程。`profile({ scope })` 返回从该所有者全部 person 记忆中不分记录早晚取得的长期知识:每一条有记录的年度日期(`MemoryDate`:出生、婚礼、离世或纪念日,已知时带年份),以及提供方蒸馏出画像后的画像文本;提供方在作用域的路由上于后台把画像更新到最新。`memoryOriginLabel(hit, now)` 额外给出这条记忆是多久以前记录的。`LEARNED_PROCEDURE_PREFIX` 与 `learnedProcedureOf(record)` 向 Settings 管理器公开这种文本形式。`edit` 与 `forget` 只作用于该作用域所有者的记忆。每条记忆都有一个领域(`MemoryDomain`):`person`、`world` 与 `experience` 记忆在该所有者的每个会话中都被召回,`project` 记忆只在捕获它的那个工作区的会话中被召回,提供方不返回其他工作区的项目记忆。记忆属于一个已登录用户:每个 `MemoryScope` 都携带来自 `SessionHeader.owner` 的所有者账户 id。它还导出 `memoryScopeOf(agent)`,由它推导该作用域与该会话的模型路由,并对没有所有者的会话返回 undefined,因此这样的会话没有记忆;此外还导出 `MEMORY_TOOL`,即提供方渲染的召回上下文可以引用的、面向模型的工具名。 ## 目录 diff --git a/packages/memory/memory/src/index.ts b/packages/memory/memory/src/index.ts index ed77d5d637..804d1eedc8 100644 --- a/packages/memory/memory/src/index.ts +++ b/packages/memory/memory/src/index.ts @@ -5,6 +5,7 @@ * @module @aeven/memory */ import { Context, Service } from '@deepseek-ai/cordis' +import { brandString } from '@aeven/brand' import type { Agent } from '@aeven/agent' import type { SessionId } from '@aeven/session' import type { @@ -25,6 +26,7 @@ import type { MemorySkill, MemoryTimelineEntry, MemoryTurn, + ShippedProcedure, } from './types.ts' export type * from './types.ts' @@ -144,6 +146,27 @@ export function learnedProcedureOf(record: MemoryRecord): LearnedProcedure | und } } +/** Id prefix of a {@link ShippedProcedure}. */ +const SHIPPED_ID_PREFIX = 'shipped:' + +/** + * The id a shipped procedure is recalled and read under. + * @param name - the procedure's kebab-case name. + * @returns `shipped:`. + */ +export function shippedProcedureId(name: string): MemoryItemId { + return brandString(`${SHIPPED_ID_PREFIX}${name}`) +} + +/** + * Whether an id names a shipped procedure rather than one of an owner's memories. + * @param id - a memory id. + * @returns true for `shipped:`. + */ +export function isShippedProcedureId(id: MemoryItemId): boolean { + return id.startsWith(SHIPPED_ID_PREFIX) +} + /** Thrown when a memory operation runs while no provider is registered. */ /** * Account sync lease name of an account's memory maintenance: work that derives new memory from all stored memory, @@ -192,6 +215,7 @@ interface ActiveHolder { export default class Memory extends Service { private provider: MemoryProvider | undefined private readonly holders = new Set() + private readonly shipments = new Set() constructor(ctx: Context) { super(ctx, 'memory') @@ -242,6 +266,40 @@ export default class Memory extends Service { } } + /** + * Register procedures a composition ships for every owner. Each name may appear once per registration; across + * registrations the earliest live one of a name is served. + * @param procedures - the procedures, each with the id {@link shippedProcedureId} gives its name. + * @returns idempotent disposer that withdraws them. + * @throws Error when a name repeats or an id does not match its name. + */ + ship(procedures: readonly ShippedProcedure[]): () => void { + const names = new Set() + for (const procedure of procedures) { + if (names.has(procedure.name)) throw new Error(`Shipped procedure ${procedure.name} is registered twice`) + if (procedure.id !== shippedProcedureId(procedure.name)) throw new Error(`Shipped procedure ${procedure.name} must use id ${shippedProcedureId(procedure.name)}`) + names.add(procedure.name) + } + const shipment = [...procedures] + this.shipments.add(shipment) + return () => { + this.shipments.delete(shipment) + } + } + + /** + * The procedures registered with {@link ship}, one per name. An owner's learned procedure with the same name + * supersedes one in recall; callers that list procedures for an owner apply the same rule. + * @returns the shipped procedures. + */ + shipped(): readonly ShippedProcedure[] { + const byName = new Map() + for (const shipment of this.shipments) { + for (const procedure of shipment) if (!byName.has(procedure.name)) byName.set(procedure.name, procedure) + } + return [...byName.values()] + } + private current(): MemoryProvider { if (this.provider === undefined) throw new MemoryUnavailableError() return this.provider @@ -253,7 +311,8 @@ export default class Memory extends Service { * @returns ranked hits visible to the scope. */ recall(request: MemoryRecallRequest): Promise { - return this.current().recall(request) + const shipped = request.purpose === 'turn-start' ? this.shipped() : [] + return this.current().recall(shipped.length === 0 ? request : { ...request, shipped }) } /** @@ -288,6 +347,8 @@ export default class Memory extends Service { * @returns true when a procedure of the owner was updated. */ setProcedureStatus(request: Parameters[0]): Promise { + // A shipped procedure belongs to no owner, so it has no status to change. + if (isShippedProcedureId(request.id)) return Promise.resolve(false) return this.current().setProcedureStatus(request) } @@ -301,11 +362,21 @@ export default class Memory extends Service { } /** - * Read one memory item. + * Read one memory item. A `trace` read of a shipped procedure's id answers with the procedure, without the provider. * @param request - scope, item kind, and id. * @returns the item, or undefined when the scope holds no such item. */ detail(request: Parameters[0]): Promise { + if (isShippedProcedureId(request.id)) { + const procedure = this.shipped().find(shipped => shipped.id === request.id) + return Promise.resolve(procedure === undefined || request.kind !== 'trace' ? undefined : { + kind: 'trace', + id: procedure.id, + title: `${LEARNED_PROCEDURE_PREFIX} ${procedure.name}: ${procedure.description}`, + body: procedure.content, + facts: { shipped: true }, + }) + } return this.current().detail(request) } @@ -404,6 +475,7 @@ export default class Memory extends Service { * @returns the updated memory, or undefined when the owner has no such memory. */ edit(request: Parameters[0]): Promise { + if (isShippedProcedureId(request.id)) return Promise.resolve(undefined) return this.current().edit(request) } @@ -413,6 +485,7 @@ export default class Memory extends Service { * @returns true when a memory of this owner was deleted. */ forget(request: Parameters[0]): Promise { + if (isShippedProcedureId(request.id)) return Promise.resolve(false) return this.current().forget(request) } diff --git a/packages/memory/memory/src/types.ts b/packages/memory/memory/src/types.ts index b21867630b..b611b84807 100644 --- a/packages/memory/memory/src/types.ts +++ b/packages/memory/memory/src/types.ts @@ -112,6 +112,12 @@ export interface MemoryRecallRequest { readonly sessionOnly?: boolean /** Per-tier limits; absent uses the provider's configured limits. */ readonly limits?: MemoryRecallLimits + /** + * Turn-start only: procedures the composition ships, set by the memory service from its registrations. A provider + * offers them beside the owner's learned procedures, except one whose name a non-archived procedure of the owner + * already uses, and delivers each as a hit with its `id` and `summary`. + */ + readonly shipped?: readonly ShippedProcedure[] /** * Foreground budget in milliseconds: the provider resolves with `timedOut` instead of retrieving past it. A relevance * judgment that follows retrieval may finish past it by at most the provider's documented minimum judgment window. @@ -306,6 +312,24 @@ export interface LearnedProcedure { readonly status: ProcedureStatus } +/** + * A procedure a composition ships for every owner: read-only, recalled like a learned procedure, and superseded for + * an owner by a learned procedure with the same name. + */ +export interface ShippedProcedure { + /** `shipped:`; {@link MemoryProvider.detail} and the owner's write operations never receive it. */ + readonly id: MemoryItemId + /** Kebab-case name of the kind of task the procedure does. */ + readonly name: string + /** One line: what the procedure does and when to use it. */ + readonly description: string + /** The condensed procedure recall delivers. */ + readonly summary: string + /** The full Markdown procedure. */ + readonly content: string + readonly domain: MemoryDomain +} + /** Request for the owner's learned procedures. */ export interface LearnedProceduresRequest { readonly owner: string diff --git a/packages/preset/agent-presets/presets/aeven/agent.cordis.yml b/packages/preset/agent-presets/presets/aeven/agent.cordis.yml index 27dd82dfa3..64ad93340e 100644 --- a/packages/preset/agent-presets/presets/aeven/agent.cordis.yml +++ b/packages/preset/agent-presets/presets/aeven/agent.cordis.yml @@ -394,11 +394,17 @@ # Learning: completed multi-step work is distilled into a procedure and kept # in long-term memory, which memory recall brings back when a request needs -# it. Nothing learned becomes a skill or a capability file. +# it. Nothing learned becomes a skill or a capability file. `procedures/` +# beside this composition holds the procedures Aeven ships for every user: +# memory recall offers them only when a request matches, unlike skills, which +# every session lists, and a user's own learned procedure of the same name +# supersedes one. - id: tool-capability name: '@aeven/tool-capability' config: store: memory + shippedProcedures: + - !!js "process.getBuiltinModule('node:url').fileURLToPath(new URL('./procedures/', baseUrl))" # The `web` service and its search provider stay in the host composition; only # the model-facing tool is per-session. diff --git a/packages/preset/agent-presets/presets/aeven/procedures/linkedin-post.md b/packages/preset/agent-presets/presets/aeven/procedures/linkedin-post.md new file mode 100644 index 0000000000..ba5e9e10fd --- /dev/null +++ b/packages/preset/agent-presets/presets/aeven/procedures/linkedin-post.md @@ -0,0 +1,71 @@ +--- +name: linkedin-post +description: Draft, publish, or schedule a LinkedIn post in the in-app browser, with links, images, video, polls, documents, events, or celebrations. +summary: >- + On linkedin.com/feed click role=button[name="Start a post"]; type the whole text into dialog[open] div[role="textbox"] with one preview_type. Never click Post or the schedule Confirm unless the user asked to publish this exact post. A URL followed by a space, line break, or more text gets a preview card after 1-2 s, and the card hides Media and +. To use own media instead: remove the card with dialog[open] button[aria-label="Dismiss"]:not([data-dialog-dismiss]) (the Dismiss WITH data-dialog-dismiss closes the composer), check the text survived, click Media, preview_upload the files, Next. Media added first means no card. One video per post, never with images. 3,000 characters max; past it Post is disabled. Close: composer Dismiss, then Discard or Save as draft. Read memory_get for the content types, editor tools, and every trap. +--- + +# LinkedIn post + +Drive linkedin.com in the in-app browser with the `preview_*` tools (load the `in-app-browser` skill first). The user must already be signed in; a sign-in page is a `preview_handoff`. + +## Ground rules + +- Click Post, or Confirm in Schedule post, only when the user asked to publish this exact post. Drafting or "prepare a post" ends with the draft open in the composer and a summary to the user. +- Type the whole text, line breaks included, in one `preview_type` call. Enter in the post editor only adds a line; the Post button is the one control that publishes. +- Prefer structural selectors (`dialog[open]`, `div[role="textbox"]`, attribute presence). Labels such as `Media` and `Dismiss` follow the user's LinkedIn UI language; when one does not match, take a `preview_snapshot` and match the control by role and position. +- Read the composer back after every step; a click that reported `ok` has not necessarily changed it. + +## Open the composer + +1. On `https://www.linkedin.com/feed/`, click `role=button[name="Start a post"]`. The composer opens as `dialog[open]` and the address becomes `/sharing/compose`. +2. The editor is `dialog[open] div[role="textbox"]` (ProseMirror). Click it, then `preview_type` the text. +3. Author, visibility (`Post to Anyone`), comment setting, and `Add collaborators` sit above the editor; change them only when asked. + +## Links and the preview card + +- A URL gets a preview card only once something follows it: a space, a line break, or more text. Text that ends right after the URL shows no card until the next keystroke. The card appears 1–2 seconds later. +- While a card is shown, the toolbar hides `Media` and `Expand content types` (+): no image, video, or other content can be added until the card is removed. +- The card's ✕ and the composer's close button are both labelled `Dismiss`. Remove the card with `dialog[open] button[aria-label="Dismiss"]:not([data-dialog-dismiss])`; the button with `data-dialog-dismiss` closes the whole composer. +- After removing the card, read the editor text back; once it came back empty, so retype it if that happens. +- A removed card stays away while typing continues, even for a new URL, but it can return after opening a content panel (Celebration, Job) and pressing Back. Check for it again before finishing. + +## Text with a link plus an image or video + +1. Type the text with the link. +2. If a card appeared, remove it and check the text. +3. Add the media (next section). +4. Confirm: the text holds the URL, the media is attached, no card is shown. + +Adding the media first and typing the link afterwards never produces a card. Removing all media later brings the card back on the next keystroke unless it was removed before. + +## Images and video + +1. Click `dialog[open] button[aria-label="Media"]`. LinkedIn opens a file chooser, sometimes only after an `Editor` panel's `Upload from computer` button. Use `preview_upload` with the absolute paths and the Media button (or `text=Upload from computer`) as the selector; never the native picker. +2. The chooser accepts several files; images keep the order given. The `Editor` panel shows `1 of N` and, per image, `Edit`, `Tag`, `Alternative text`, `Duplicate`, `Delete`, and `Add`. Add alternative text when the user supplies it. +3. A video gets `Play video`, `Captions`, and `Thumbnail`. One video per post, never with images: `Add` is disabled while a video is attached. +4. `Next` returns to the composer. Attached media shows `Edit` and `Close`; `Close` removes all of it at once. While media is attached, `Media` and `+` are hidden. + +## Other content types + +`Expand content types` (+) shows these; each replaces the composer panel and has `Back`: + +| Option | Panel | +| --- | --- | +| Celebration | Select occasion: Project launch, Work anniversary, New position, New educational milestone, New certification | +| Event | Create an event: cover image (min 480 px wide, 16:9), Online / In person, format*, name* (75 chars), timezone*, start date* and time*, optional end, description, speakers | +| Job | Select company (pages the user manages) | +| Poll | Question* (140 chars), two or more options* (30 chars each), `Add option`, duration 1 day / 3 days / 1 week / 2 weeks | +| Document | Share a document: `Choose file`, then `Done`; viewers can download it as PDF | + +The clock beside Post (`Scheduled`) opens Schedule post with date*, time*, and `Confirm`; scheduling publishes later and needs the same explicit request as Post. + +## Limits + +- 3,000 characters. Past it LinkedIn shows "You have exceeded the maximum character limit" with the overflow and disables Post; shorten the text with the user. +- The `n/120` counter tracks the opening shown before "…see more". +- The web composer needs no escaping; type the text as the user wrote it. + +## Close or discard + +The composer's `Dismiss` (`button[data-dialog-dismiss]`) asks "Save this post as a draft?" with `Discard` and `Save as draft`. Save as draft only when the user asked to keep it. diff --git a/packages/web/browser-chromium/src/outbound-probe.ts b/packages/web/browser-chromium/src/outbound-probe.ts index 8c87797bdb..79f7ddcea9 100644 --- a/packages/web/browser-chromium/src/outbound-probe.ts +++ b/packages/web/browser-chromium/src/outbound-probe.ts @@ -11,7 +11,11 @@ * article, dialog, or form that holds the control. Reply, comment, and Save * controls publish only when that composer holds text, so the "Reply" that * opens an empty reply box does not count; Send, Post, Repost, Invite, and - * Submit always do. + * Submit always do. Enter in a field that holds text counts as sending it, + * except a plain Enter in a multi-line post composer: an editor whose dialog, + * form, or article shows a Post control and no Send control, where Enter adds + * a line. Enter with Control, Meta, or Alt still counts, because post + * composers such as X's publish on Cmd+Enter. * * The script guard stops a page script from publishing at all: while armed it * refuses programmatic clicks, synthetic click and Enter events, and form @@ -49,6 +53,8 @@ export interface OutboundProbe { readonly url: string /** False when the selector is not plain CSS or does not match exactly one element; the caller then decides without the page. */ readonly found: boolean + /** True when the probe read Enter pressed in the focused element rather than a click. */ + readonly key?: boolean /** What the action publishes, or null when it publishes nothing. */ readonly outbound: PageOutbound | null } @@ -125,7 +131,7 @@ const LIBRARY = `(() => { while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement; return element; }; - const describeKey = () => { + const describeKey = (chord) => { const element = focused(); if (!element || element === document.body || element === document.documentElement) return null; if (element.closest(CONTROL)) return describe(element); @@ -137,7 +143,19 @@ const LIBRARY = `(() => { || SEARCH.test([editor.name, editor.id, editor.getAttribute("aria-label"), editor.placeholder].join(" "))) return null; } const text = textOf(editor); - return text === "" ? null : { kind: "message", label: "Enter", text: cap(text) }; + // Ctrl or Cmd with Enter publishes in post composers (X posts on Cmd+Enter), so only a plain Enter adds a line. + if (text === "" || (!chord && postComposer(editor))) return null; + return { kind: "message", label: "Enter", text: cap(text) }; + }; + const visible = (element) => element.getClientRects().length > 0; + // A multi-line editor whose dialog, form, or article shows a Post button and no Send button publishes only through + // that button; Enter adds a line, as in the LinkedIn, X, and Facebook post composers. Chat boxes show Send. + const postComposer = (editor) => { + if (editor.tagName === "INPUT") return false; + const owner = editor.closest(OWNER); + if (!owner) return false; + const verbs = [...owner.querySelectorAll(CONTROL)].filter(visible).map((control) => verbOf(labelOf(control))); + return verbs.includes("post") && !verbs.includes("send"); }; return { describe, describeKey, CONTROL, EDITABLE, textOf }; })()` @@ -146,12 +164,13 @@ const LIBRARY = `(() => { * Build the expression that reports what a click on a CSS selector's element, * or Enter in the focused element, would publish. * @param selector - the click target's selector, or null for Enter pressed in the focused element. + * @param chord - Enter is pressed with Control, Meta, or Alt, which publishes even in a multi-line post composer. * @returns an expression evaluating to an {@link OutboundProbe}. */ -export function outboundProbe(selector: string | null): string { +export function outboundProbe(selector: string | null, chord = false): string { return `(() => { const lib = ${LIBRARY}; - if (${JSON.stringify(selector)} === null) return { url: location.href, found: true, outbound: lib.describeKey() }; + if (${JSON.stringify(selector)} === null) return { url: location.href, found: true, key: true, outbound: lib.describeKey(${JSON.stringify(chord)}) }; const all = (root, css) => { const found = [...root.querySelectorAll(css)]; for (const element of root.querySelectorAll("*")) if (element.shadowRoot) found.push(...all(element.shadowRoot, css)); diff --git a/packages/web/tool-browser/README.i18n.yaml b/packages/web/tool-browser/README.i18n.yaml index 40fca749ac..40ebcfe8e5 100644 --- a/packages/web/tool-browser/README.i18n.yaml +++ b/packages/web/tool-browser/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/web/tool-browser/README.md -README.md: 481a66c2c4430559707fcf309f9c93ab4d2bb066 -README.zh.md: 31aa7cc4358ac8131ba7709554f729fb64a6e208 +README.md: 5937b18e82fbeea37e3772eafa3f0fd3b7ee01f5 +README.zh.md: e6d169f9adcd152f4a60722692a7220c6e495dae diff --git a/packages/web/tool-browser/README.md b/packages/web/tool-browser/README.md index 481a66c2c4..5937b18e82 100644 --- a/packages/web/tool-browser/README.md +++ b/packages/web/tool-browser/README.md @@ -25,7 +25,7 @@ English | [中文](README.zh.md) Mount the plugin in an agent composition whose Client can host a browser, such as the right-sidebar browser of `@aeven/client-ui-sidebar-browser`. The shipped `cordis`, `standard`, and `ptc` presets mount it. -`preview_upload` takes absolute paths on the Electron computer and a file-input or Upload-button selector; an omitted selector requires exactly one file input. Remote uploads request approval scoped to the destination origin and paths, while localhost is exempt. A send-like call on a website asks first, and the approval names what goes out ("Post this reply on linkedin.com", "Send this email") with its text: a `preview_click` on a CSS selector and a `preview_press` Enter are read in the page first, which reports the clicked control's publishing verb and the text in the composer beside it; Reply, Comment, and Save ask only when that composer holds text, while Send, Post, Repost, Invite, and Submit always ask. A click on an accessibility token or a non-CSS locator is judged by its label, and a click by coordinates or on a target it cannot read asks. Sequential `preview_type` with a line break asks and shows the text, and so does a `preview_evaluate` that sends a writing request. Every other page script on a website runs behind a guard that refuses a click, synthetic Enter, or form submission that would publish, marks the control with `data-aeven-send`, and fails the call with an instruction to click it with `preview_click`, so a script never posts unasked. A `preview_sequence` holding any of these asks for the first. Approval offers "Allow for this session" per site, shared with the Chrome DevTools tools; a refusal fails the call with `BROWSER_SEND_DENIED`, which tells the model nothing was sent and not to send it another way. The classification is `@aeven/browser-chromium`'s. `preview_sequence` runs 1–20 typed actions locally, with condition-based waits and a first-failure result. Upload and sequence execution require write access. These operations are implemented for Electron; embedded-frame upload choosers are unsupported. +`preview_upload` takes absolute paths on the Electron computer and a file-input or Upload-button selector; an omitted selector requires exactly one file input. Remote uploads request approval scoped to the destination origin and paths, while localhost is exempt. A send-like call on a website asks first, and the approval names what goes out ("Post this reply on linkedin.com", "Send this email") with its text: a `preview_click` on a CSS selector and a `preview_press` Enter are read in the page first, which reports the clicked control's publishing verb and the text in the composer beside it; Reply, Comment, and Save ask only when that composer holds text, while Send, Post, Repost, Invite, and Submit always ask. A plain Enter in a multi-line post composer, one whose dialog, form, or article shows a Post control and no Send control, adds a line and does not ask; Enter with Control, Meta, or Alt still asks, because composers such as X's publish on Cmd+Enter. The approval's `outbound.trigger` names the input that publishes: the key pressed, or the clicked control's label. A click on an accessibility token or a non-CSS locator is judged by its label, and a click by coordinates or on a target it cannot read asks. Sequential `preview_type` with a line break asks and shows the text, and so does a `preview_evaluate` that sends a writing request. Every other page script on a website runs behind a guard that refuses a click, synthetic Enter, or form submission that would publish, marks the control with `data-aeven-send`, and fails the call with an instruction to click it with `preview_click`, so a script never posts unasked. A `preview_sequence` holding any of these asks for the first. Approval offers "Allow for this session" per site, shared with the Chrome DevTools tools; a refusal fails the call with `BROWSER_SEND_DENIED`, which tells the model nothing was sent and not to send it another way. The classification is `@aeven/browser-chromium`'s. `preview_sequence` runs 1–20 typed actions locally, with condition-based waits and a first-failure result. Upload and sequence execution require write access. These operations are implemented for Electron; embedded-frame upload choosers are unsupported. `preview_snapshot` accepts `mode: dom` (the default) or `mode: ax`. The accessibility mode reads Chromium's accessibility tree, including shadow DOM, and returns `snapshotId`, indexed `nodes`, and `truncated`. Nodes use the desktop element fields `index`, `token`, `role`, `title`, `value`, and `editable`. Pass a returned token to `preview_click` or `preview_type` instead of a selector. Tokens expire on the next observation or browser action, and navigation or detached, hidden, or disabled targets are refused. Re-observe after acting; accessibility targets inside frames remain outside this milestone. diff --git a/packages/web/tool-browser/README.zh.md b/packages/web/tool-browser/README.zh.md index 31aa7cc435..e6d169f9ad 100644 --- a/packages/web/tool-browser/README.zh.md +++ b/packages/web/tool-browser/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" 在其 Client 能够承载浏览器的代理组合中挂载本插件,例如 `@aeven/client-ui-sidebar-browser` 的右侧边栏浏览器。随附的 `cordis`、`standard` 与 `ptc` 预设都会挂载它。 -`preview_upload` 接受 Electron 所在计算机上的绝对路径,以及文件输入框或上传按钮的选择器;省略选择器时页面必须恰好有一个文件输入框。远程上传会请求以目标源和路径为范围的审批,localhost 除外。网站上类似发送的调用会先请求审批,审批会写明要发出的内容(「在 linkedin.com 发布这条回复」「发送这封邮件」)并附上文本:对 CSS 选择器的 `preview_click` 和 Enter `preview_press` 会先在页面中读取,页面报告被点击控件的发布动词以及旁边输入框中的文本;Reply、Comment 和 Save 只在该输入框有文本时询问,Send、Post、Repost、Invite 和 Submit 总是询问。点击无障碍 token 或非 CSS 定位器时按标签判定,按坐标或点击无法读取的目标时直接询问。含换行的逐字 `preview_type` 会询问并显示文本,发送写入请求的 `preview_evaluate` 同样询问。网站上的其他页面脚本都在一个防护下运行:会发布内容的点击、合成 Enter 或表单提交会被拒绝,控件被标上 `data-aeven-send`,调用失败并提示改用 `preview_click` 点击它,因此脚本绝不会未经询问就发布。包含上述任一操作的 `preview_sequence` 对第一个这样的操作询问。审批按站点提供「本会话允许」,与 Chrome DevTools 工具共享;拒绝会以 `BROWSER_SEND_DENIED` 使调用失败,告诉模型没有发送任何内容,且不要换一种方式发送。判定规则由 `@aeven/browser-chromium` 提供。`preview_sequence` 在本地运行 1–20 个类型化操作,按条件等待,并返回第一个失败。上传和序列执行需要写权限。这些操作为 Electron 实现;嵌入框架中的上传选择器不受支持。 +`preview_upload` 接受 Electron 所在计算机上的绝对路径,以及文件输入框或上传按钮的选择器;省略选择器时页面必须恰好有一个文件输入框。远程上传会请求以目标源和路径为范围的审批,localhost 除外。网站上类似发送的调用会先请求审批,审批会写明要发出的内容(「在 linkedin.com 发布这条回复」「发送这封邮件」)并附上文本:对 CSS 选择器的 `preview_click` 和 Enter `preview_press` 会先在页面中读取,页面报告被点击控件的发布动词以及旁边输入框中的文本;Reply、Comment 和 Save 只在该输入框有文本时询问,Send、Post、Repost、Invite 和 Submit 总是询问。在多行发帖输入框(其所在对话框、表单或文章显示 Post 控件而没有 Send 控件)中单独按 Enter 只换行,不询问;同时按住 Control、Meta 或 Alt 的 Enter 仍会询问,因为 X 等输入框按 Cmd+Enter 即发布。审批的 `outbound.trigger` 指明发布所用的输入:按下的键,或所点击控件的标签。点击无障碍 token 或非 CSS 定位器时按标签判定,按坐标或点击无法读取的目标时直接询问。含换行的逐字 `preview_type` 会询问并显示文本,发送写入请求的 `preview_evaluate` 同样询问。网站上的其他页面脚本都在一个防护下运行:会发布内容的点击、合成 Enter 或表单提交会被拒绝,控件被标上 `data-aeven-send`,调用失败并提示改用 `preview_click` 点击它,因此脚本绝不会未经询问就发布。包含上述任一操作的 `preview_sequence` 对第一个这样的操作询问。审批按站点提供「本会话允许」,与 Chrome DevTools 工具共享;拒绝会以 `BROWSER_SEND_DENIED` 使调用失败,告诉模型没有发送任何内容,且不要换一种方式发送。判定规则由 `@aeven/browser-chromium` 提供。`preview_sequence` 在本地运行 1–20 个类型化操作,按条件等待,并返回第一个失败。上传和序列执行需要写权限。这些操作为 Electron 实现;嵌入框架中的上传选择器不受支持。 `preview_snapshot` 接受 `mode: dom`(默认)或 `mode: ax`。无障碍模式读取 Chromium 的无障碍树,包括 shadow DOM,并返回 `snapshotId`、带索引的 `nodes` 和 `truncated`。节点采用桌面元素字段 `index`、`token`、`role`、`title`、`value` 和 `editable`。将返回的令牌传给 `preview_click` 或 `preview_type`,代替选择器。令牌在下一次观察或浏览器操作时过期;导航后以及目标已分离、隐藏或禁用时会拒绝操作。操作后重新观察;框架内的无障碍目标不属于本阶段。 diff --git a/packages/web/tool-browser/src/index.ts b/packages/web/tool-browser/src/index.ts index c33f7b760c..94306b63b9 100644 --- a/packages/web/tool-browser/src/index.ts +++ b/packages/web/tool-browser/src/index.ts @@ -492,14 +492,16 @@ export function apply(ctx: Context, config: Config): void { * @param selector - the click target, or null for Enter. * @param frame - the iframe selector the action runs in, when it names one. * @param exec - the running tool call. + * @param chord - Enter is pressed with Control, Meta, or Alt. * @returns the page's answer, or undefined when the page could not tell. */ const probeOutbound = async ( selector: string | null, frame: JsonValue | undefined, exec: ToolRunContext, + chord = false, ): Promise => { - const result = await run('evaluate', { expression: outboundProbe(selector), ...typeof frame === 'string' ? { frame } : {} }, exec).catch(() => undefined) + const result = await run('evaluate', { expression: outboundProbe(selector, chord), ...typeof frame === 'string' ? { frame } : {} }, exec).catch(() => undefined) const value = typeof result === 'object' && result !== null && !Array.isArray(result) ? result.value : undefined if (typeof value !== 'object' || value === null || Array.isArray(value) || value.found !== true || typeof value.url !== 'string') return undefined // The probe is this package's own page script; its answer has the OutboundProbe fields. @@ -524,6 +526,7 @@ export function apply(ctx: Context, config: Config): void { ...page.to === undefined ? {} : { to: page.to }, ...page.subject === undefined ? {} : { subject: page.subject }, ...page.text === undefined ? {} : { text: page.text }, + trigger: probe.key === true ? { kind: 'key', key: 'Enter' } : { kind: 'click', label: page.label }, }, } } @@ -559,8 +562,14 @@ export function apply(ctx: Context, config: Config): void { } case 'press': { if (typeof values.key !== 'string' || !isSendKey(values.key, modifiers(values.modifiers))) return undefined - const probe = await probeOutbound(null, undefined, exec) - return probe === undefined ? { action: `Press ${values.key}` } : probedStep(probe) ?? undefined + const held = [...values.key.split('+').slice(0, -1), ...modifiers(values.modifiers)].map(part => part.trim().toLowerCase()) + const chord = held.some(part => ['control', 'ctrl', 'meta', 'cmd', 'command', 'alt', 'option'].includes(part)) + const probe = await probeOutbound(null, undefined, exec, chord) + if (probe === undefined) return { action: `Press ${values.key}` } + const probed = probedStep(probe) + if (probed?.outbound === undefined) return probed ?? undefined + const pressed = [...modifiers(values.modifiers), values.key].join('+') + return { ...probed, outbound: { ...probed.outbound, trigger: { kind: 'key', key: pressed } } } } case 'type': return values.sequential === true && typeof values.text === 'string' && values.text.includes('\n') diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e1bfe212cd..7b164fe388 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2697,6 +2697,9 @@ importers: '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery + yaml: + specifier: ^2.4.2 + version: 2.9.0 devDependencies: '@aeven/agent': specifier: workspace:^ diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index af5046d9bd..276f4b2d8c 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -910,6 +910,7 @@ export const TYPE_LINK_EXEMPTIONS: Readonly> = { MemoryPage: 'package-owned type is documented in packages/memory/memory/src/types.ts', LearnedProcedure: 'package-owned type is documented in packages/memory/memory/src/types.ts', LearnedProceduresRequest: 'package-owned type is documented in packages/memory/memory/src/types.ts', + ShippedProcedure: 'package-owned type is documented in packages/memory/memory/src/types.ts', MemoryProfile: 'package-owned type is documented in packages/memory/memory/src/types.ts', MemoryProvider: 'package-owned type is documented in packages/memory/memory/src/types.ts', MemoryRecall: 'package-owned type is documented in packages/memory/memory/src/types.ts',