@capybara-hq/plugin-memory 0.0.0-stage → 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,88 @@
1
+ {
2
+ "$schema": "https://capybarahq.com/schemas/plugin.v1.schema.json",
3
+ "schemaVersion": 1,
4
+ "name": "memory",
5
+ "version": "0.1.0-rc.1",
6
+ "publisher": "Capybara",
7
+ "description": {
8
+ "en": "Memory for agents: each agent remembers each member across conversations, with an index at run start, memory tools, hybrid search and a memory page",
9
+ "zh": "智能体记忆:每个智能体跨会话记住每位成员,运行开始时给出记忆索引,提供记忆工具、混合检索和记忆页面"
10
+ },
11
+ "displayName": {
12
+ "zh": "记忆",
13
+ "en": "Memory"
14
+ },
15
+ "icon": "./icon.svg",
16
+ "homepage": "https://github.com/capybara-hq/plugins/tree/main/plugins/memory#readme",
17
+ "extension": {
18
+ "entry": "./dist/index.mjs",
19
+ "manifest": {
20
+ "name": "memory",
21
+ "version": "0.1.0-rc.1",
22
+ "sdk": "^0.1.0-rc.19",
23
+ "provides": [
24
+ "context@1"
25
+ ],
26
+ "requires": [],
27
+ "optional": [],
28
+ "permissions": {
29
+ "client": true,
30
+ "ui": {
31
+ "components": [
32
+ "overview"
33
+ ]
34
+ },
35
+ "tools": [
36
+ "view",
37
+ "search",
38
+ "write",
39
+ "edit",
40
+ "delete"
41
+ ],
42
+ "hooks": [
43
+ "org.member_removed",
44
+ "agent.deleted",
45
+ "org.deleted"
46
+ ],
47
+ "models": [
48
+ {
49
+ "purpose": "memory.embed",
50
+ "kind": "embedding",
51
+ "label": {
52
+ "zh": "记忆检索",
53
+ "en": "Memory search"
54
+ }
55
+ }
56
+ ]
57
+ },
58
+ "config": {
59
+ "deployment": [],
60
+ "org": []
61
+ },
62
+ "ui": [
63
+ {
64
+ "id": "overview",
65
+ "title": {
66
+ "zh": "记忆",
67
+ "en": "Memory"
68
+ },
69
+ "slot": "org.page",
70
+ "kind": "component",
71
+ "icon": "book"
72
+ }
73
+ ]
74
+ },
75
+ "migrations": "./migrations",
76
+ "client": {
77
+ "entry": "./dist/client/client.mjs",
78
+ "styles": [
79
+ "./dist/client/styles/memory.css"
80
+ ],
81
+ "integrity": {
82
+ "./dist/client/client.mjs": "sha384-39CF00+4BxW9NA/1lgHdooTHvsjSoUGrB1sler9LxvdALiV/pFBoyhOJO/e1Xx5L",
83
+ "./dist/client/styles/memory.css": "sha384-2kJzQZ84fDCzoeEsCBBIVXZcy8pzq+mUhMQZCOYt2shNPqxY0y+JeMCHqOuVIb8a"
84
+ },
85
+ "apiVersion": 1
86
+ }
87
+ }
88
+ }
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ Capybara
2
+ Copyright 2026 Meta-1 (Tianjin Yuanyilian Technology Co., Ltd.)
package/README.md CHANGED
@@ -1,3 +1,146 @@
1
- # Temporary Holding Version
1
+ # @capybara-hq/plugin-memory
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Memory for Capybara agents, modelled on Claude Code's memory: each agent remembers each member
4
+ across conversations. A memory is one note about one thing at `<type>/…/<name>.md`, where the type
5
+ is `user` (who the person is), `feedback` (how they want work done, and why), `project` (ongoing
6
+ work and constraints) or `reference` (where external things live). Each memory has a one-line
7
+ description and a Markdown body; bodies link to other memories with `[[name]]` or
8
+ `[[type/…/name.md]]` (a link to a memory not written yet is allowed and becomes live when it is).
9
+
10
+ What the plugin does:
11
+
12
+ - **An index at run start** (`context@1`): a fixed English block that explains the memory system to
13
+ the model (what to save, what not to save, check before writing, recalled memories are background
14
+ and may be stale), then one line per memory, `- <path> — <description>`, grouped by type (user,
15
+ feedback, project, reference) and ordered by path within a type. At most 200 lines (the "N more"
16
+ line included) or 16 KB; past that the index ends with "N more memories not listed". The text
17
+ has no timestamps, no recall counts and a stable order, so it only changes when a memory is
18
+ written, edited or deleted (the kernel appends a new context event only then).
19
+
20
+ > **Ruling (2026-11-13), a deviation from spec §5.2 the maintainer may overturn:** the spec
21
+ > orders each type by recall count. That would let every recall change the index text and so
22
+ > cause a new `plugin_context` event and a prompt-cache miss at the next run. The index orders by
23
+ > path instead (`COLLATE "C"`); recall counts are kept for the memory page's graph only.
24
+ - **Five tools** the model uses on its own, like Claude Code saves memories without asking.
25
+ - **Hybrid search**: keyword and semantic, merged by reciprocal rank fusion.
26
+ - **A memory page** (记忆 / Memory, under the org's pages): the directory neural tree.
27
+ - **Cleanup** when a member leaves the org, an agent is deleted or the org is deleted.
28
+
29
+ ## Whose memory, and where
30
+
31
+ - A memory belongs to one **(agent, member)** pair in one org. Members of the same agent never see
32
+ each other's memories; the same member with another agent starts from nothing. Every query
33
+ filters on the org, the agent and the member taken from the call, never from model or page input.
34
+ - "The member" is the **conversation's owner**. Memory is on only in **one-to-one conversations**:
35
+ web chat and channel DMs (a scheduled task's conversation, run as its creator, too; one bound
36
+ into a group does not). It is off, with no
37
+ index and no tools, in **channel groups**, in **sub-agent** conversations, for **guests**
38
+ (including anonymous channel guests) and in any run where someone other than the owner acts in
39
+ the conversation. The tools declare `sources: ["web", "channel_dm"]`, so the kernel hides them
40
+ elsewhere; the handlers refuse again (defence in depth).
41
+ - An agent stops using memory when its memory tools are disabled, and an org admin can switch the
42
+ tools off: with no memory tool available in a run the plugin provides no index.
43
+
44
+ ## Tools
45
+
46
+ | Tool | Does | Default policy |
47
+ |---|---|---|
48
+ | `plugin__memory__view` | A directory (`/` for the root) with its entries, or a memory in full with its links (resolved or not written yet). Counts as a recall. | `allow` (read only) |
49
+ | `plugin__memory__search` | Hybrid search, `limit` up to 20 (default 10): path, description and a snippet per hit. Each hit counts as a recall. | `allow` (read only) |
50
+ | `plugin__memory__write` | Creates or replaces a memory; the type is the path's first segment. | `allow` |
51
+ | `plugin__memory__edit` | Exact string replacement in the body, optionally a new description. | `allow` |
52
+ | `plugin__memory__delete` | Deletes a memory; links to it become dangling. | `allow` (`destructiveHint`) |
53
+
54
+ Every tool defaults to `allow` **on purpose**: memory is meant to be saved and tidied without asking,
55
+ as in Claude Code. An org admin can set any of them to `ask` or `deny` like any other tool policy;
56
+ `delete` carries `destructiveHint` so policies and reviews can tell it apart.
57
+
58
+ Limits: paths at most 200 characters (lowercase `[a-z0-9-_.]` or CJK segments, the first one the
59
+ type), descriptions one line of at most 200 characters, bodies at most 8 KB (UTF-8), 1,000 memories
60
+ per (agent, member) pair. A write over a limit fails with an error that tells the model what to do
61
+ (shorten, or consolidate memories).
62
+
63
+ ## Permissions
64
+
65
+ The extension's manifest asks for:
66
+
67
+ | Permission | Why |
68
+ |---|---|
69
+ | `client: true`, `ui.components: ["memory-page"]` | The memory page is client code (a React component drawing a canvas). Both keys are sensitive at review and block loading until approved. |
70
+ | `tools: view, search, write, edit, delete` | The memory tools. |
71
+ | `models: memory.embed` (`kind: "embedding"`, 记忆检索 / Memory search) | Embeddings for semantic search and the graph's semantic edges (below). |
72
+ | `hooks: org.member_removed, agent.deleted, org.deleted` | Cleanup: deletes the memories of the member, the agent or the org. Idempotent. |
73
+ | `provides: context@1` | The index at run start. |
74
+
75
+ The migration `0001_init.sql` contains one `DO` block, which the import review shows as a
76
+ **`dynamic_sql` warning**. It only adds the `embedding` column, typed pgvector's `vector` when that
77
+ type is visible from the plugin's search path (`plugin_memory, public`) and `real[]` otherwise; it
78
+ cannot pick the type in plain DDL. Nothing else in the migration is dynamic.
79
+
80
+ ## Embeddings, pgvector and search
81
+
82
+ - **The embedding model is a model purpose, not plugin config.** The plugin declares `memory.embed`
83
+ (`kind: "embedding"`). An org admin maps it to any enabled embedding model on the org's model
84
+ settings, or the super admin sets the deployment default for it. Memories are embedded on write
85
+ (a failure saves the memory without a vector and retries through the `memory-embed` queue);
86
+ vectors made by an earlier model are re-embedded lazily when a search finds them.
87
+ - **Without a model for the purpose** the plugin still works: search is keyword only (no error), and
88
+ the page shows no semantic edges.
89
+ - **Keyword search** segments text with `Intl.Segmenter` (Chinese without spaces included: "回复用中文"
90
+ is found by "中文") into a `simple` `tsvector`; no PG extension needed.
91
+ - **pgvector is optional.** With it, cosine distance runs in PG (`<=>`); without it, vectors are
92
+ `real[]` and the plugin computes cosine similarity itself. Search is always within one (agent,
93
+ member) pair (at most 1,000 rows), so no ANN index is needed. **The column type is fixed when the
94
+ migration first runs**: installing pgvector later does not convert an existing `real[]` column
95
+ (both paths keep working; the plugin reads the column's type, not whether pgvector is installed).
96
+ - **Thresholds are model-dependent.** A memory found only by its vector must reach cosine
97
+ similarity 0.3 to be a hit (`MIN_SIMILARITY`); semantic neighbours on the page need 0.75 (top 3
98
+ per memory). Both suit common embedding models; a model with a very different similarity
99
+ distribution may need other values.
100
+
101
+ ## The memory page
102
+
103
+ `org.page` "记忆 / Memory", for members and above (guests get no page). The top bar picks the agent
104
+ (the agents the viewer has memories with; admins: every agent of the org the plugin has seen),
105
+ for admins the member, and searches with the same hybrid search.
106
+
107
+ The **directory neural tree** draws one agent's memories about one member: the agent at the centre,
108
+ the four type directories as branches (deeper directories as sub-branches), memories as leaves.
109
+ Node size is the recall count, brightness how recently it was recalled (fading over about a month),
110
+ colour the type (theme tokens, so the page follows the theme). Solid edges are the `[[links]]` the
111
+ model wrote, faint dashed ones semantic neighbours. Hover lights a node's neighbours; click (or
112
+ arrow keys and Enter) opens the side panel with the memory's body, links, recalls, dates and the
113
+ conversation it was written in; nodes can be dragged, the view panned and zoomed. Recently recalled
114
+ memories pulse; with reduced motion nothing moves and the layout settles once. A list view shows
115
+ every memory as a table (the default past 300 memories).
116
+
117
+ Members edit and delete their own memories. **Org admins and owners** can view and delete any
118
+ member's memories but never edit them, and the page says so while they look. Every admin view of
119
+ another member's memories (select, open, search) and every delete is written to the plugin's
120
+ **admin access log** (`plugin_memory.admin_access_log`: who, whose, which agent, what, when). The
121
+ log is not shown in the UI yet; it is there for audit questions.
122
+
123
+ The page's data arrives in pages under the 32 KB limit of a component view: the first view carries
124
+ the nodes and edges that fit, and the page fetches the rest with the `more` action until it has
125
+ every memory. Viewing the page does not count as a recall.
126
+
127
+ ## Deleting memories
128
+
129
+ Deleting a memory, or a member leaving the org, removes rows from the plugin's tables only. A
130
+ conversation's event log is append-only: the next run gets a new index without the deleted memory,
131
+ but earlier index events and tool results that showed it stay in those conversations' history (and
132
+ in their trajectories and evals), as in Claude Code. The page's delete confirmation says so:
133
+
134
+ > 已删除的记忆不会再出现在新的索引里,但之前对话中已出现的内容仍保留在那些对话的记录中。
135
+ >
136
+ > Deleted memories no longer appear in new indexes, but what earlier conversations already showed
137
+ > stays in those conversations' records.
138
+
139
+ ## Development
140
+
141
+ ```bash
142
+ pnpm exec vitest run plugins/memory # from the repository root; needs Docker for PostgreSQL
143
+ ```
144
+
145
+ The page's component tests (`test/client.test.ts`) run on the plugin-client fake host in jsdom; the
146
+ graph (`src/client/graph.ts`) is framework-free and tested on its own (`test/graph.test.ts`).
@@ -0,0 +1,26 @@
1
+ This package bundles the third-party software listed below. Their license notices follow.
2
+
3
+ ------------------------------------------------------------------------
4
+ kysely@0.29.8 (MIT)
5
+
6
+ The MIT License (MIT)
7
+
8
+ Copyright (c) 2022 Sami Koskimäki
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ import{defineClientExtension as $n,defineComponent as Gn}from"@capybara-hq/plugin-client";import{Badge as gn,Button as V,Icon as Q,KeyValue as pn,Select as Ke,Spinner as nn,Stack as Te,Text as W,useAccess as fn,useAction as bn,useClientStorage as vn,useLocale as ae,usePrefersReducedMotion as xn,useView as kn}from"@capybara-hq/plugin-client";import{useCallback as q,useEffect as U,useMemo as Nn,useRef as $,useState as F}from"react";var ye=["user","feedback","project","reference"],ln="agent",_e=e=>`dir:${e}`;function cn(e){return Math.min(18,4+1.2*Math.sqrt(Math.max(0,e)))}function dn(e,n){if(e===null)return .25;let t=Date.parse(e);if(Number.isNaN(t))return .25;let l=Math.max(0,(n-t)/864e5);return Math.max(.25,Math.exp(-l/30))}function Me(e){let n=2166136261;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return(n>>>0)/4294967296}var un=e=>e<=0?0:120+(e-1)*80;function Ge(e,n){let t=[],l=new Map,d=[],a=o=>{let i=t.length;return t.push({...o,x:0,y:0,vx:0,vy:0,ring:0}),l.set(o.id,i),d.push([]),o.parent>=0&&d[o.parent]?.push(i),i};a({id:ln,kind:"agent",label:e.agentLabel,path:"",type:null,parent:-1,depth:0,pinned:!0,r:13,brightness:1,recent:!1,phase:0,memory:null});let s=o=>{let i=l.get(_e(o));if(i!==void 0)return i;let y=o.lastIndexOf("/"),g=y===-1?0:s(o.slice(0,y)),S=o.split("/")[0];return a({id:_e(o),kind:"dir",label:o.slice(y+1),path:o,type:ye.includes(S)?S:null,parent:g,depth:o.split("/").length,pinned:!1,r:4.5,brightness:1,recent:!1,phase:Me(o),memory:null})};for(let o of ye)s(o);let M=[...e.nodes].sort((o,i)=>o.path<i.path?-1:o.path>i.path?1:0);for(let o of M){if(l.has(o.id))continue;let i=o.dir===""?0:s(o.dir),y=o.path.slice(o.path.lastIndexOf("/")+1).replace(/\.md$/,""),g=dn(o.lastRecalledAt,n.now),S=o.lastRecalledAt===null?Number.NaN:Date.parse(o.lastRecalledAt);a({id:o.id,kind:"memory",label:y,path:o.path,type:o.type,parent:i,depth:(t[i]?.depth??0)+1,pinned:!1,r:cn(o.recalls),brightness:g,recent:!Number.isNaN(S)&&n.now-S<7*864e5,phase:Me(o.id),memory:o})}let I=[];for(let o=1;o<t.length;o++){let i=t[o];I.push({a:i.parent,b:o,kind:"tree",phase:i.phase})}let x=new Set;for(let o of e.edges){let i=l.get(o.from),y=l.get(o.to);if(i===void 0||y===void 0||i===y)continue;let g=o.kind==="semantic"?`s${Math.min(i,y)}~${Math.max(i,y)}`:`l${i}>${y}`;x.has(g)||(x.add(g),I.push({a:i,b:y,kind:o.kind,phase:Me(g)}))}let C=t.map(()=>new Set);for(let o of I)C[o.a]?.add(o.b),C[o.b]?.add(o.a);let v=new Array(t.length).fill(0);for(let o=t.length-1;o>=0;o--){let i=t[o]?.kind==="memory"?1:0,y=(d[o]??[]).reduce((g,S)=>g+(v[S]??0),0);v[o]=Math.max(1,i+y)}let h=(o,i,y)=>{let g=t[o],S=d[o]??[],R=i,X=S.reduce((Y,B)=>Y+(v[B]??1),0);S.forEach((Y,B)=>{let j=(y-i)*(v[Y]??1)/Math.max(1,X),_=t[Y],K=R+j/2+(_.phase-.5)*j*.3;_.ring=_.kind==="dir"?un(_.depth):(g.kind==="agent"?70:g.ring)+46+B%3*20+_.r,_.x=Math.cos(K)*_.ring,_.y=Math.sin(K)*_.ring,h(Y,R,R+j),R+=j})};h(0,-Math.PI/2,3*Math.PI/2);let r=n.previous??null;if(r!==null)for(let o of t){let i=r.index.get(o.id),y=i===void 0?void 0:r.nodes[i];y!==void 0&&(o.x=y.x,o.y=y.y)}return{nodes:t,edges:I,index:l,adjacency:C,alpha:r===null?1:.4}}function Se(e){let{nodes:n}=e,t=e.alpha,l=110,d=new Map;n.forEach((a,s)=>{let M=`${Math.floor(a.x/l)},${Math.floor(a.y/l)}`,I=d.get(M);I===void 0?d.set(M,[s]):I.push(s)});for(let a=0;a<n.length;a++){let s=n[a],M=Math.floor(s.x/l),I=Math.floor(s.y/l);for(let x=-1;x<=1;x++)for(let C=-1;C<=1;C++)for(let v of d.get(`${M+x},${I+C}`)??[]){if(v<=a)continue;let h=n[v],r=h.x-s.x,o=h.y-s.y,i=r*r+o*o;if(i===0&&(r=(s.phase-h.phase)*.1+.01,o=.01,i=r*r+o*o),i>l*l)continue;let y=Math.sqrt(i),g=60*t/y,S=s.r+h.r+6;y<S&&(g+=(S-y)*.5);let R=r/y*g,X=o/y*g;s.vx-=R,s.vy-=X,h.vx+=R,h.vy+=X}}for(let a of e.edges){if(a.kind==="semantic")continue;let s=n[a.a],M=n[a.b],I=M.x-s.x,x=M.y-s.y,C=Math.sqrt(I*I+x*x)||1,v=a.kind==="tree"?Math.max(30,M.ring-s.ring):90,h=(C-v)/C*t*(a.kind==="tree"?.12:.015);s.vx+=I*h*.5,s.vy+=x*h*.5,M.vx-=I*h*.5,M.vy-=x*h*.5}for(let a of n){if(a.kind==="agent")continue;let s=Math.sqrt(a.x*a.x+a.y*a.y)||1,M=(a.ring-s)/s*.08*t;a.vx+=a.x*M,a.vy+=a.y*M}for(let a of n){if(a.pinned){a.vx=0,a.vy=0,a.kind==="agent"&&(a.x=0,a.y=0);continue}a.vx*=.6,a.vy*=.6,a.x+=a.vx,a.y+=a.vy}return e.alpha+=(0-e.alpha)*.03,e.alpha}function Be(e,n=240){for(let t=0;t<n&&e.alpha>=.005;t++)Se(e);e.alpha=0}function Ie(e,n,t,l=3){let d=-1,a=Number.POSITIVE_INFINITY;for(let s=e.nodes.length-1;s>=0;s--){let M=e.nodes[s],I=Math.hypot(M.x-n,M.y-t);I<=M.r+l&&I<a&&(d=s,a=I)}return d}var Fe=.15,mn=4,ie=(e,n,t)=>({x:(n-e.x)/e.k,y:(t-e.y)/e.k});function Pe(e,n,t,l=48){let d=Number.POSITIVE_INFINITY,a=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,M=Number.NEGATIVE_INFINITY;for(let v of e.nodes)d=Math.min(d,v.x-v.r),a=Math.min(a,v.y-v.r),s=Math.max(s,v.x+v.r),M=Math.max(M,v.y+v.r);let I=Math.max(1,s-d),x=Math.max(1,M-a),C=Math.min(1.6,Math.max(Fe,Math.min((n-2*l)/I,(t-2*l)/x)));return{k:C,x:n/2-(d+s)/2*C,y:t/2-(a+M)/2*C}}function Ye(e,n,t,l){let d=Math.min(mn,Math.max(Fe,e.k*l)),a=ie(e,n,t);return{k:d,x:n-a.x*d,y:t-a.y*d}}function He(e){let n=getComputedStyle(e),t=(a,s)=>n.getPropertyValue(a).trim()||s,l=t("--cb-ink","CanvasText"),d=t("--cb-accent",l);return{type:{user:t("--cx-memory-type-user",d),feedback:t("--cx-memory-type-feedback",t("--cb-warn",l)),project:t("--cx-memory-type-project",t("--cb-ok",l)),reference:t("--cx-memory-type-reference",l)},agent:t("--cx-memory-agent",d),ink:l,muted:t("--cb-muted","GrayText"),faint:t("--cb-faint","GrayText"),bg:t("--cb-bg","Canvas"),font:t("--cb-font","monospace")}}function $e(e,n){let t=Math.hypot(e.x,e.y),l=Math.atan2(n.y,n.x);return t<1?{x:(e.x+n.x)/2,y:(e.y+n.y)/2}:{x:Math.cos(l)*t,y:Math.sin(l)*t}}function hn(e,n,t,l){let d=1-l;return{x:d*d*e.x+2*d*l*n.x+l*l*t.x,y:d*d*e.y+2*d*l*n.y+l*l*t.y}}var we=(e,n)=>n.kind==="agent"?e.agent:n.type===null?e.muted:e.type[n.type];function je(e,n,t,l,d){let{nodes:a}=n,s=t.k;e.setTransform(d.dpr,0,0,d.dpr,0,0),e.clearRect(0,0,d.width,d.height),e.translate(t.x,t.y),e.scale(s,s);let M=new Set;if(d.hover>=0){M.add(d.hover);for(let r of n.adjacency[d.hover]??[])M.add(r)}let I=r=>d.highlight===null||d.highlight.has(r.id),x=r=>{let o=a[r];return M.size>0?M.has(r)?1:.15:d.highlight!==null?o.kind!=="memory"||I(o)?1:.15:1},C=r=>{if(!d.motion||r.kind!=="memory")return{x:r.x,y:r.y};let o=r.phase*Math.PI*2;return{x:r.x+Math.sin(d.time/1700+o)*1.4,y:r.y+Math.cos(d.time/2100+o)*1.4}},v=a.map(C),h=1/s;e.setLineDash([3*h,4*h]),e.lineWidth=h,e.strokeStyle=l.muted;for(let r of n.edges){if(r.kind!=="semantic")continue;let o=v[r.a],i=v[r.b];e.globalAlpha=.28*Math.min(x(r.a),x(r.b)),e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(i.x,i.y),e.stroke()}e.setLineDash([]);for(let r of n.edges){if(r.kind!=="tree")continue;let o=a[r.a],i=a[r.b],y=v[r.a],g=v[r.b],S=$e(o,i);e.globalAlpha=(i.kind==="dir"?.45:.22+.25*i.brightness)*Math.min(x(r.a),x(r.b)),e.strokeStyle=we(l,i),e.lineWidth=(i.kind==="dir"?1.4:1)*h,e.beginPath(),e.moveTo(y.x,y.y),e.quadraticCurveTo(S.x,S.y,g.x,g.y),e.stroke()}e.strokeStyle=l.ink,e.lineWidth=1.2*h;for(let r of n.edges){if(r.kind!=="link")continue;let o=v[r.a],i=v[r.b];e.globalAlpha=.5*Math.min(x(r.a),x(r.b)),e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(i.x,i.y),e.stroke()}if(d.motion)for(let r of n.edges){let o=a[r.b];if(r.kind==="semantic"||r.kind==="tree"&&!o.recent)continue;let i=(d.time/(r.kind==="link"?3200:2600)+r.phase)%1,y=v[r.a],g=v[r.b],S=r.kind==="tree"?hn(y,$e(a[r.a],o),g,i):{x:y.x+(g.x-y.x)*i,y:y.y+(g.y-y.y)*i};e.globalAlpha=Math.sin(Math.PI*i)*.9*Math.min(x(r.a),x(r.b)),e.fillStyle=r.kind==="link"?l.ink:we(l,o),e.beginPath(),e.arc(S.x,S.y,1.8*h,0,Math.PI*2),e.fill()}if(a.forEach((r,o)=>{let i=v[o],y=x(o),g=we(l,r);if(r.kind==="dir"){e.globalAlpha=y,e.fillStyle=l.bg,e.strokeStyle=g,e.lineWidth=1.4*h,e.beginPath(),e.arc(i.x,i.y,r.r,0,Math.PI*2),e.fill(),e.stroke();return}if(r.kind==="agent"){let S=d.motion?Math.sin(d.time/900)*2:0;e.fillStyle=g,e.globalAlpha=.12*y,e.beginPath(),e.arc(i.x,i.y,r.r*2.4+S,0,Math.PI*2),e.fill(),e.globalAlpha=.35*y,e.strokeStyle=g,e.lineWidth=h,e.beginPath(),e.arc(i.x,i.y,r.r+6+S/2,0,Math.PI*2),e.stroke(),e.globalAlpha=y,e.beginPath(),e.arc(i.x,i.y,r.r,0,Math.PI*2),e.fill();return}if(r.brightness>.4&&(e.globalAlpha=.14*r.brightness*y,e.fillStyle=g,e.beginPath(),e.arc(i.x,i.y,r.r*2.2,0,Math.PI*2),e.fill()),d.motion&&r.recent){let S=(d.time/2400+r.phase)%1;e.globalAlpha=(1-S)*.5*y,e.strokeStyle=g,e.lineWidth=h,e.beginPath(),e.arc(i.x,i.y,r.r+2+S*10,0,Math.PI*2),e.stroke()}e.globalAlpha=(.3+.7*r.brightness)*y,e.fillStyle=g,e.beginPath(),e.arc(i.x,i.y,r.r,0,Math.PI*2),e.fill(),d.highlight?.has(r.id)===!0&&(e.globalAlpha=.9,e.strokeStyle=g,e.lineWidth=1.5*h,e.beginPath(),e.arc(i.x,i.y,r.r+4,0,Math.PI*2),e.stroke()),r.id===d.selectedId&&(e.globalAlpha=1,e.strokeStyle=l.ink,e.lineWidth=2*h,e.beginPath(),e.arc(i.x,i.y,r.r+3.5,0,Math.PI*2),e.stroke())}),d.focus>=0){let r=a[d.focus],o=v[d.focus];r!==void 0&&o!==void 0&&(e.globalAlpha=1,e.strokeStyle=l.agent,e.setLineDash([3*h,3*h]),e.lineWidth=1.5*h,e.beginPath(),e.arc(o.x,o.y,r.r+7,0,Math.PI*2),e.stroke(),e.setLineDash([]))}e.textBaseline="middle",a.forEach((r,o)=>{let i=v[o],y=x(o);if(!(r.kind!=="memory"||s>=1.35||M.has(o)||o===d.focus||r.id===d.selectedId||(d.highlight?.has(r.id)??!1)))return;let S=r.kind==="agent"?12:11;if(e.font=`${r.kind==="dir"?"":"500 "}${S*h}px ${l.font}`,e.globalAlpha=(r.kind==="memory"?.9:r.kind==="dir"?.75:1)*y,e.fillStyle=r.kind==="dir"?l.muted:l.ink,r.kind==="agent")e.textAlign="center",e.fillText(r.label,i.x,i.y+r.r+18*h);else{e.textAlign="left";let R=r.kind==="dir"?`${r.label}/`:r.label;e.fillText(R,i.x+r.r+5*h,i.y)}}),e.globalAlpha=1}var Ve={zh:"已删除的记忆不会再出现在新的索引里,但之前对话中已出现的内容仍保留在那些对话的记录中。",en:"Deleted memories no longer appear in new indexes, but what earlier conversations already showed stays in those conversations' records."},Ce={user:{zh:"用户",en:"User"},feedback:{zh:"反馈",en:"Feedback"},project:{zh:"项目",en:"Project"},reference:{zh:"参考",en:"Reference"}},m={agent:{zh:"智能体",en:"Agent"},member:{zh:"成员",en:"Member"},search:{zh:"搜索记忆",en:"Search memories"},clearSearch:{zh:"清除搜索",en:"Clear search"},noHits:{zh:"没有找到相关的记忆。",en:"No matching memories."},graph:{zh:"图谱",en:"Graph"},list:{zh:"列表",en:"List"},view:{zh:"显示方式",en:"View"},fit:{zh:"适配视图",en:"Fit to view"},fullscreen:{zh:"全屏",en:"Full screen"},exitFullscreen:{zh:"退出全屏",en:"Exit full screen"},loading:{zh:"正在载入记忆…",en:"Loading memories…"},failed:{zh:"记忆载入失败。",en:"Could not load the memories."},retry:{zh:"重试",en:"Retry"},noAccess:{zh:"只有组织成员可以查看记忆。",en:"Only org members can see memories."},emptyTitle:{zh:"还没有记忆",en:"No memories yet"},emptyBody:{zh:"智能体在一对一对话中记下关于你的事情后,会出现在这里。",en:"When an agent remembers something about you in a one-to-one conversation, it shows up here."},emptyAgent:{zh:"这个智能体还没有关于你的记忆。",en:"This agent has no memories about you yet."},emptyOther:{zh:"这位成员和这个智能体之间还没有记忆。",en:"This member has no memories with this agent yet."},sizeLegend:{zh:"大小:被想起的次数",en:"Size: times recalled"},glowLegend:{zh:"亮度:最近一次被想起",en:"Brightness: last recalled"},linkLegend:{zh:"实线:记忆里写下的链接",en:"Solid: links written in memories"},semanticLegend:{zh:"虚线:语义相近",en:"Dashed: semantically close"},hint:{zh:"拖动节点 · 拖动空白处平移 · 滚轮缩放 · 方向键逐条浏览",en:"Drag nodes · drag the background to pan · scroll to zoom · arrow keys to step through"},path:{zh:"路径",en:"Path"},description:{zh:"描述",en:"Description"},body:{zh:"正文",en:"Body"},recalled:{zh:"被想起",en:"Recalled"},lastRecalled:{zh:"最近想起",en:"Last recalled"},never:{zh:"从未",en:"Never"},created:{zh:"创建于",en:"Created"},updated:{zh:"更新于",en:"Updated"},createdIn:{zh:"来自对话",en:"Written in"},openConversation:{zh:"打开对话",en:"Open the conversation"},links:{zh:"链接",en:"Links"},dangling:{zh:"尚未写下",en:"not written yet"},edit:{zh:"编辑",en:"Edit"},save:{zh:"保存",en:"Save"},cancel:{zh:"取消",en:"Cancel"},delete:{zh:"删除",en:"Delete"},close:{zh:"关闭",en:"Close"},confirmTitle:{zh:"删除这条记忆?",en:"Delete this memory?"},actionFailed:{zh:"操作没有完成:",en:"The action did not complete: "},readOnly:{zh:"管理员不能编辑其他成员的记忆。",en:"Admins cannot edit another member's memories."}},Ee=e=>({zh:`${e} 条记忆`,en:e===1?"1 memory":`${e} memories`}),We=(e,n)=>({zh:`正在载入 ${e} / ${n}`,en:`Loading ${e} of ${n}`}),ze=e=>({zh:`${e} 次`,en:e===1?"once":`${e} times`}),Xe=e=>({zh:`你正在查看 ${e} 的记忆。每次查看和删除都会记入审计日志;管理员不能编辑其他成员的记忆。`,en:`You are viewing ${e}'s memories. Every view and delete is recorded in the audit log; admins cannot edit another member's memories.`}),qe=e=>({zh:`记忆图谱,共 ${e} 条记忆。用方向键逐条浏览,回车打开,Esc 关闭。`,en:`Memory graph with ${e} memories. Use the arrow keys to step through them, Enter to open one and Escape to close it.`}),Ue=(e,n)=>({zh:`${e} / ${n} 字节`,en:`${e} / ${n} bytes`});function ge(e,n,t=Date.now()){if(e===null)return m.never[n];let l=Date.parse(e);if(Number.isNaN(l))return m.never[n];let d=new Intl.RelativeTimeFormat(n==="zh"?"zh-CN":"en",{numeric:"auto"}),a=Math.round((l-t)/1e3),s=Math.abs(a);return s<60?d.format(a,"second"):s<3600?d.format(Math.round(a/60),"minute"):s<86400?d.format(Math.round(a/3600),"hour"):s<86400*30?d.format(Math.round(a/86400),"day"):s<86400*365?d.format(Math.round(a/(86400*30)),"month"):d.format(Math.round(a/(86400*365)),"year")}function Ae(e,n){let t=Date.parse(e);return Number.isNaN(t)?e:new Intl.DateTimeFormat(n==="zh"?"zh-CN":"en",{dateStyle:"medium",timeStyle:"short"}).format(t)}import{Fragment as _n,jsx as c,jsxs as N}from"react/jsx-runtime";var De=8192,Ze=200,Mn=300,wn=200,Sn=300,oe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function pe(e){return oe(e)&&Array.isArray(e.nodes)&&Array.isArray(e.edges)&&Array.isArray(e.agents)&&typeof e.canAdmin=="boolean"&&oe(e.selection)?e:null}function In(e){return oe(e)&&Array.isArray(e.nodes)&&Array.isArray(e.edges)&&!("selection"in e)?e:null}var Qe=e=>oe(e)&&oe(e.detail)?e.detail:null,Pn=e=>oe(e)&&Array.isArray(e.hits)?e.hits:null,Je=e=>`${e.kind}:${e.from}>${e.to}`;function Cn(e,n){let t=new Map(e.map(l=>[l.id,l]));for(let l of n)t.set(l.id,l);return[...t.values()]}function En(e,n){let t=new Map(e.map(l=>[Je(l),l]));for(let l of n)t.set(Je(l),l);return[...t.values()]}var en=(e,n)=>e.selection.agentId===n.selection.agentId&&e.selection.accountId===n.selection.accountId;function le(e){let n={accountId:e.selection.accountId};return e.selection.agentId!==null&&(n.agentId=e.selection.agentId),n}var zn=e=>e instanceof Error?e.message:String(e);function tn(){let{view:e,status:n,retry:t}=kn(),l=bn(),d=fn(),{locale:a,t:s}=ae(),M=xn(),I=vn(),[x,C]=F(null),v=$(0),h=$(null);h.current=x;let[r,o]=F(!1),[i,y]=F(null),[g,S]=F(null),[R,X]=F(null),[Y,B]=F(""),[j,_]=F(null),[K,ce]=F(()=>{let u=I.get("view");return u==="graph"||u==="list"?u:null}),[ve,de]=F(0),J=$(null),[ee,xe]=F(!1);U(()=>{let u=()=>xe(document.fullscreenElement===J.current);return document.addEventListener("fullscreenchange",u),()=>document.removeEventListener("fullscreenchange",u)},[]);let b=()=>{if(document.fullscreenElement===J.current){document.exitFullscreen();return}J.current?.requestFullscreen?.().catch(()=>{})},p=q((u,A)=>{C(E=>E!==null&&E.source===u||!A&&E!==null&&!en(E.source,u)?E:(v.current+=1,{source:u,nodes:u.nodes,edges:u.edges,cursor:u.cursor,pages:1,gen:v.current}))},[]),k=$(s);k.current=s;let f=q(u=>y(k.current(m.actionFailed)+zn(u)),[]),P=$(!1),T=$(void 0);U(()=>{if(T.current===e&&e!==null)return;T.current=e;let u=pe(e?.data);if(u!==null){p(u,!1);return}n==="ready"&&h.current===null&&!P.current&&(P.current=!0,l("select",{payload:{}}).then(A=>{let E=pe(A.view?.data);E!==null&&p(E,!0)}).catch(f))},[e,n,p,l,f]);let D=x?.gen,z=x?.cursor??null;U(()=>{let u=h.current;if(u===null||z===null||u.gen!==D)return;let A=!0,E=()=>C(L=>L!==null&&L.gen===u.gen?{...L,cursor:null}:L);return l("more",{payload:{...le(u.source),cursor:z}}).then(L=>{if(!A)return;let G=In(L.view?.data);if(G===null)return E();C(O=>{if(O===null||O.gen!==u.gen)return O;let re=G.cursor===O.cursor||O.pages+1>=wn?null:G.cursor;return{...O,nodes:Cn(O.nodes,G.nodes),edges:En(O.edges,G.edges),cursor:re,pages:O.pages+1}})}).catch(L=>{A&&(f(L),E())}),()=>{A=!1}},[D,z,l,f]);let w=x?.source??null,H=w?.editable??!1,Z=$(null),ne=q(()=>{Z.current=null,X(null),S(null)},[]),ue=$(0),Le=q(async u=>{ue.current+=1,o(!0),y(null);try{let A=await l("select",{payload:u}),E=pe(A.view?.data);E!==null&&(p(E,!0),ne(),_(null),B(""),de(L=>L+1))}catch(A){f(A)}finally{o(!1)}},[l,p,ne,f]),me=q(async u=>{let A=h.current;if(A!==null){Z.current=u,X(u),y(null);try{let E=await l("open",{payload:{...le(A.source),memoryId:u}});if(Z.current!==u)return;let L=Qe(E.view?.data);if(L===null){Z.current=null,X(null);return}S(L)}catch(E){f(E)}}},[l,f]),rn=q(async(u,A,E)=>{let L=h.current;if(L===null)return!1;try{let G=await l("edit",{payload:{...le(L.source),memoryId:u,description:A,body:E}}),O=Qe(G.view?.data);return O===null?!1:(S(O),C(re=>re===null?re:{...re,nodes:re.nodes.map(Ne=>Ne.id===O.id?{...Ne,description:O.description}:Ne)}),!0)}catch(G){return f(G),!1}},[l,f]),on=q(async u=>{let A=h.current;if(A!==null)try{let E=await l("delete",{payload:{...le(A.source),memoryId:u}}),L=pe(E.view?.data);if(L===null)return;p(L,!0),ne(),_(G=>G===null?G:G.filter(O=>O.id!==u))}catch(E){f(E)}},[l,p,ne,f]),ke=q(async u=>{let A=h.current;if(A===null||A.source.selection.agentId===null)return;let E=++ue.current;if(u.trim()===""){_(null);return}let L=()=>E!==ue.current||h.current===null||!en(h.current.source,A.source);try{let G=await l("search",{payload:{...le(A.source),query:u}});if(L())return;let O=Pn(G.view?.data);O!==null&&_(O)}catch(G){L()||f(G)}},[l,f]);if(U(()=>{if(Y.trim()===""){ue.current+=1,_(null);return}let u=setTimeout(()=>{ke(Y)},Sn);return()=>clearTimeout(u)},[Y,ke]),!d.atLeast("member"))return c(fe,{icon:"lock",title:s(m.noAccess)});if(x===null||w===null)return n==="failed"?c(fe,{icon:"circle-alert",title:s(m.failed),children:c(V,{onClick:t,children:s(m.retry)})}):N("div",{className:"cx-memory-state",children:[c(nn,{label:s(m.loading)}),c(W,{tone:"muted",children:s(m.loading)})]});if(w.selection.agentId===null&&w.agents.length===0&&!w.canAdmin)return c(fe,{icon:"empty",title:s(m.emptyTitle),body:s(m.emptyBody)});let te=x.nodes,he=K??(w.total>Mn?"list":"graph"),Re=u=>{ce(u),I.set("view",u)},an=w.agents.find(u=>u.id===w.selection.agentId)?.name??"",sn=w.members?.find(u=>u.id===w.selection.accountId)?.name??w.selection.accountId,Oe=j===null?null:new Set(j.map(u=>u.id)),se=te.length===0;return N("div",{ref:J,className:"cx-memory-page","data-panel":R!==null?"open":"closed","data-empty":se&&j===null?"true":"false","data-fullscreen":ee?"true":"false",children:[N("form",{className:"cx-memory-toolbar",onSubmit:u=>{u.preventDefault(),ke(Y)},children:[N("div",{className:"cx-memory-field",children:[c("span",{className:"cx-memory-field-label",children:s(m.agent)}),c(Ke,{value:w.selection.agentId??"","aria-label":s(m.agent),placeholder:"—",disabled:r||w.agents.length===0,options:w.agents.map(u=>({value:u.id,label:u.name})),onChange:u=>{Le({agentId:u.target.value,accountId:w.selection.accountId})}})]}),w.canAdmin&&w.members!==void 0?N("div",{className:"cx-memory-field",children:[c("span",{className:"cx-memory-field-label",children:s(m.member)}),c(Ke,{value:w.selection.accountId,"aria-label":s(m.member),disabled:r,options:w.members.map(u=>({value:u.id,label:u.name})),onChange:u=>{Le({accountId:u.target.value})}})]}):null,se?null:N("div",{className:"cx-memory-search",children:[c(Q,{name:"search",size:14}),c("input",{className:"cx-memory-input",type:"search",value:Y,placeholder:s(m.search),"aria-label":s(m.search),maxLength:500,disabled:w.selection.agentId===null,onChange:u=>B(u.target.value),onKeyDown:u=>{u.key==="Escape"&&B("")}})]}),N("div",{className:"cx-memory-toolbar-end",children:[c(W,{variant:"small",tone:"muted",children:x.cursor!==null?s(We(te.length,w.total)):s(Ee(Math.max(w.total,te.length)))}),se?null:N("fieldset",{className:"cx-memory-toggle",children:[c("legend",{className:"cx-memory-sr",children:s(m.view)}),c("button",{type:"button",className:"cx-memory-toggle-item","aria-pressed":he==="graph",onClick:()=>Re("graph"),children:s(m.graph)}),c("button",{type:"button",className:"cx-memory-toggle-item","aria-pressed":he==="list",onClick:()=>Re("list"),children:s(m.list)})]}),he==="graph"&&!se?c(V,{variant:"ghost",title:s(m.fit),"aria-label":s(m.fit),onClick:()=>de(u=>u+1),children:c(Q,{name:"zoom-in",size:14})}):null,c(V,{variant:"ghost",title:s(ee?m.exitFullscreen:m.fullscreen),"aria-label":s(ee?m.exitFullscreen:m.fullscreen),onClick:b,children:c(Q,{name:ee?"minimize-2":"maximize-2",size:14})})]})]}),H?null:N("div",{className:"cx-memory-banner",role:"note",children:[c(Q,{name:"admin",size:14}),c(W,{variant:"small",children:s(Xe(sn))})]}),i!==null?c("div",{className:"cx-memory-banner","data-tone":"fail",role:"alert",children:c(W,{variant:"small",tone:"fail",children:i})}):null,N("div",{className:"cx-memory-body",children:[N("div",{className:"cx-memory-main",children:[j!==null?c(Ln,{hits:j,onOpen:me,onClear:()=>B("")}):null,se?c(fe,{icon:"empty",title:s(m.emptyTitle),body:s(w.selection.agentId===null?m.emptyBody:H?m.emptyAgent:m.emptyOther)}):he==="graph"?c(Tn,{nodes:te,edges:x.edges,agentLabel:an,motion:!M,selectedId:R,highlight:Oe,fitSignal:ve,onOpen:u=>{me(u)},onEscape:ne,label:s(qe(te.length))}):c(Dn,{nodes:te,highlight:Oe,selectedId:R,onOpen:u=>{me(u)}})]}),R!==null?c(On,{detail:g?.id===R?g:null,editable:H,canDelete:H||w.canAdmin,locale:a,onClose:ne,onOpen:u=>{me(u)},onSave:rn,onDelete:on},R):null]})]})}function fe(e){return N("div",{className:"cx-memory-state",children:[c("span",{className:"cx-memory-state-icon","aria-hidden":"true",children:c(Q,{name:e.icon,size:16})}),c(W,{variant:"h3",children:e.title}),e.body!==void 0?c(W,{tone:"muted",children:e.body}):null,e.children]})}function be({type:e}){return c("span",{className:"cx-memory-dot","data-type":e,"aria-hidden":"true"})}function An(){let{t:e}=ae();return N("div",{className:"cx-memory-legend","aria-hidden":"true",children:[c("div",{className:"cx-memory-legend-row",children:ye.map(n=>N("span",{className:"cx-memory-legend-item",children:[c(be,{type:n}),e(Ce[n])]},n))}),N("div",{className:"cx-memory-legend-row",children:[N("span",{className:"cx-memory-legend-item",children:[c("span",{className:"cx-memory-legend-line","data-kind":"link"}),e(m.linkLegend)]}),N("span",{className:"cx-memory-legend-item",children:[c("span",{className:"cx-memory-legend-line","data-kind":"semantic"}),e(m.semanticLegend)]})]}),N("div",{className:"cx-memory-legend-row",children:[c("span",{className:"cx-memory-legend-item",children:e(m.sizeLegend)}),c("span",{className:"cx-memory-legend-item",children:e(m.glowLegend)})]})]})}function Tn(e){let{locale:n,t}=ae(),l=$(null),d=$(null),a=$(null),s=$({x:0,y:0,k:1}),M=$({w:0,h:0,dpr:1}),I=$(-1),x=$(-1),C=$(!1),v=$(null),h=$(e);h.current=e;let[r,o]=F(null),[i,y]=F(null),g=q((b=0)=>{let p=d.current,k=a.current;if(p===null||k===null)return;let f=p.getContext("2d");if(f===null)return;let{w:P,h:T,dpr:D}=M.current,z=h.current;je(f,k,s.current,He(p),{width:P,height:T,dpr:D,time:b,motion:z.motion,hover:I.current>=0?I.current:x.current,focus:x.current,selectedId:z.selectedId,highlight:z.highlight})},[]),S=q(()=>{let b=a.current,{w:p,h:k}=M.current;b===null||p===0||k===0||(s.current=Pe(b,p,k))},[]),{nodes:R,edges:X,agentLabel:Y,motion:B}=e;U(()=>{let b=a.current,p=Ge({nodes:R,edges:X,agentLabel:Y},{now:Date.now(),previous:b});B||Be(p),a.current=p,I.current=-1,x.current=-1,(b===null||!C.current)&&S(),B||g()},[R,X,Y,B,S,g]);let{fitSignal:j}=e;U(()=>{j!==0&&(C.current=!1,S(),g())},[j,S,g]);let{selectedId:_,highlight:K}=e;U(()=>{B||g()},[_,K,B,g]),U(()=>{let b=l.current,p=d.current;if(b===null||p===null)return;let k=()=>{let P=Math.max(1,Math.min(3,globalThis.devicePixelRatio||1)),T=b.clientWidth,D=b.clientHeight;M.current={w:T,h:D,dpr:P},p.width=Math.round(T*P),p.height=Math.round(D*P),C.current||S(),g()};if(k(),typeof ResizeObserver>"u")return;let f=new ResizeObserver(k);return f.observe(b),()=>f.disconnect()},[S,g]),U(()=>{if(!B)return;let b=0,p=k=>{let f=a.current;if(f!==null&&f.alpha>=.005){Se(f);let{w:P,h:T}=M.current;if(!C.current&&P>0&&T>0){let D=Pe(f,P,T),z=s.current;s.current={x:z.x+(D.x-z.x)*.12,y:z.y+(D.y-z.y)*.12,k:z.k+(D.k-z.k)*.12}}}g(k),b=requestAnimationFrame(p)};return b=requestAnimationFrame(p),()=>cancelAnimationFrame(b)},[B,g]),U(()=>{let b=d.current;if(b===null)return;let p=k=>{k.preventDefault();let f=b.getBoundingClientRect();C.current=!0,s.current=Ye(s.current,k.clientX-f.left,k.clientY-f.top,Math.exp(-k.deltaY*.0015)),h.current.motion||g()};return b.addEventListener("wheel",p,{passive:!1}),()=>b.removeEventListener("wheel",p)},[g]);let ce=b=>{let p=b.currentTarget.getBoundingClientRect();return{sx:b.clientX-p.left,sy:b.clientY-p.top}},ve=b=>{let p=a.current;if(p===null)return;let{sx:k,sy:f}=ce(b),P=ie(s.current,k,f),T=Ie(p,P.x,P.y,4/s.current.k);v.current={node:T,sx:k,sy:f,lastX:k,lastY:f,moved:!1},b.currentTarget.setPointerCapture?.(b.pointerId)},de=b=>{let p=a.current;if(p===null)return;let{sx:k,sy:f}=ce(b),P=v.current,T=h.current.motion;if(P!==null){if(!P.moved&&Math.hypot(k-P.sx,f-P.sy)<4)return;P.moved=!0,o(null);let w=P.node>=0?p.nodes[P.node]:void 0;if(w!==void 0&&w.kind!=="agent"){let H=ie(s.current,k,f);w.x=H.x,w.y=H.y,w.pinned=!0,T&&(p.alpha=Math.max(p.alpha,.25))}else{C.current=!0;let H=s.current;s.current={...H,x:H.x+k-P.lastX,y:H.y+f-P.lastY}}P.lastX=k,P.lastY=f,T||g();return}let D=ie(s.current,k,f),z=Ie(p,D.x,D.y,4/s.current.k);if(z!==I.current){I.current=z;let w=z>=0?p.nodes[z]?.memory??null:null;o(w===null?null:{x:k,y:f,node:w}),T||g()}},J=b=>{let p=v.current;v.current=null;let k=a.current;if(p===null||k===null)return;let f=p.node>=0?k.nodes[p.node]:void 0;if(p.moved){f!==void 0&&f.kind!=="agent"&&h.current.motion&&(f.pinned=!1);return}f?.memory&&h.current.onOpen(f.memory.id)},ee=()=>{v.current===null&&(I.current=-1,o(null),h.current.motion||g())},xe=b=>{let p=a.current;if(p===null)return;let k=p.nodes.flatMap((D,z)=>D.kind==="memory"?[z]:[]);if(k.length===0)return;let f=k.indexOf(x.current),P=-1;if(b.key==="ArrowRight"||b.key==="ArrowDown")P=k[(f+1)%k.length]??-1;else if(b.key==="ArrowLeft"||b.key==="ArrowUp")P=k[(f-1+k.length)%k.length]??-1;else if(b.key==="Home")P=k[0]??-1;else if(b.key==="End")P=k[k.length-1]??-1;else if(b.key==="Enter"||b.key===" "){let D=p.nodes[x.current]?.memory;D&&(b.preventDefault(),h.current.onOpen(D.id));return}else if(b.key==="Escape"){h.current.onEscape();return}else return;b.preventDefault(),x.current=P;let T=p.nodes[P];if(y(T?.memory??null),T!==void 0){let{w:D,h:z}=M.current,w=s.current,H=T.x*w.k+w.x,Z=T.y*w.k+w.y;D>0&&(H<40||Z<40||H>D-40||Z>z-40)&&(C.current=!0,s.current={...w,x:D/2-T.x*w.k,y:z/2-T.y*w.k})}h.current.motion||g()};return N("div",{className:"cx-memory-stage",ref:l,children:[c("canvas",{ref:d,className:"cx-memory-canvas",tabIndex:0,"aria-label":e.label,onPointerDown:ve,onPointerMove:de,onPointerUp:J,onPointerCancel:()=>{v.current=null},onPointerLeave:ee,onKeyDown:xe,onBlur:()=>{x.current=-1,y(null),h.current.motion||g()}}),c("div",{className:"cx-memory-sr cx-memory-live","aria-live":"polite",children:i!==null?`${i.path} — ${i.description}`:""}),r!==null?N("div",{className:"cx-memory-tip",style:{left:r.x+14,top:r.y+14},"aria-hidden":"true",children:[N("span",{className:"cx-memory-tip-path",children:[c(be,{type:r.node.type}),r.node.path]}),c("span",{className:"cx-memory-tip-desc",children:r.node.description}),N("span",{className:"cx-memory-tip-meta",children:[t(m.recalled)," ",t(ze(r.node.recalls))," · ",t(m.lastRecalled)," ",ge(r.node.lastRecalledAt,n)]})]}):null,c(An,{}),c("div",{className:"cx-memory-hint","aria-hidden":"true",children:t(m.hint)})]})}function Dn(e){let{locale:n,t}=ae(),l=Nn(()=>[...e.nodes].sort((a,s)=>a.path<s.path?-1:a.path>s.path?1:0),[e.nodes]),d=e.highlight===null?l:l.filter(a=>e.highlight?.has(a.id));return N("div",{className:"cx-memory-list",children:[N("div",{className:"cx-memory-list-head","aria-hidden":"true",children:[c("span",{children:t(m.path)}),c("span",{children:t(m.description)}),c("span",{children:t(m.recalled)}),c("span",{children:t(m.lastRecalled)})]}),c("ul",{className:"cx-memory-rows",children:d.map(a=>c("li",{children:N("button",{type:"button",className:"cx-memory-row","data-memory-id":a.id,"aria-current":a.id===e.selectedId?"true":void 0,onClick:()=>e.onOpen(a.id),children:[N("span",{className:"cx-memory-row-path",children:[c(be,{type:a.type}),a.path]}),c("span",{className:"cx-memory-row-desc",children:a.description}),c("span",{className:"cx-memory-row-num",children:a.recalls}),c("span",{className:"cx-memory-row-num",children:ge(a.lastRecalledAt,n)})]})},a.id))})]})}function Ln(e){let{t:n}=ae();return N("section",{className:"cx-memory-hits","aria-label":n(m.search),children:[N("div",{className:"cx-memory-hits-head",children:[c(W,{variant:"small",tone:"muted",children:e.hits.length===0?n(m.noHits):n(Ee(e.hits.length))}),c(V,{variant:"ghost",onClick:e.onClear,children:n(m.clearSearch)})]}),e.hits.map(t=>N("button",{type:"button",className:"cx-memory-hit",onClick:()=>e.onOpen(t.id),children:[c("span",{className:"cx-memory-hit-path",children:t.path}),c("span",{className:"cx-memory-hit-desc",children:t.description}),t.snippet!==""?c("span",{className:"cx-memory-hit-snippet",children:t.snippet}):null]},t.id))]})}var Rn=e=>new TextEncoder().encode(e).length;function On(e){let{t:n}=ae(),{detail:t,locale:l}=e,[d,a]=F("view"),[s,M]=F(""),[I,x]=F(""),[C,v]=F(!1);if(t===null)return c("aside",{className:"cx-memory-panel","aria-busy":"true",children:N("div",{className:"cx-memory-panel-head",children:[c(nn,{size:12}),c("span",{className:"cx-memory-grow"}),c(V,{variant:"ghost","aria-label":n(m.close),onClick:e.onClose,children:c(Q,{name:"x",size:14})})]})});let h=i=>i[l],r=Rn(I),o=s.trim()===""||s.length>Ze||/[\r\n]/.test(s)||r>De;return N("aside",{className:"cx-memory-panel","aria-label":t.path,children:[N("div",{className:"cx-memory-panel-head",children:[c(be,{type:t.type}),c("span",{className:"cx-memory-panel-path",children:t.path}),c(gn,{children:h(Ce[t.type])}),c("span",{className:"cx-memory-grow"}),c(V,{variant:"ghost","aria-label":n(m.close),onClick:e.onClose,children:c(Q,{name:"x",size:14})})]}),c("div",{className:"cx-memory-panel-body",children:d==="edit"?N("form",{className:"cx-memory-edit",onSubmit:i=>{i.preventDefault(),!o&&(v(!0),e.onSave(t.id,s,I).then(y=>{v(!1),y&&a("view")}))},children:[N("label",{className:"cx-memory-field","data-block":"true",children:[c("span",{className:"cx-memory-field-label",children:n(m.description)}),c("input",{className:"cx-memory-input",value:s,maxLength:Ze,onChange:i=>M(i.target.value)})]}),N("label",{className:"cx-memory-field","data-block":"true",children:[c("span",{className:"cx-memory-field-label",children:n(m.body)}),c("textarea",{className:"cx-memory-textarea",value:I,rows:12,onChange:i=>x(i.target.value)}),c("span",{className:"cx-memory-field-note","data-over":r>De,children:n(Ue(r,De))})]}),N(Te,{direction:"row",gap:8,justify:"end",children:[c(V,{onClick:()=>a("view"),children:n(m.cancel)}),c(V,{type:"submit",variant:"primary",loading:C,disabled:o,children:n(m.save)})]})]}):N(_n,{children:[c(W,{children:t.description}),c("div",{className:"cx-memory-markdown",children:t.body}),t.links.length>0?N("div",{className:"cx-memory-links",children:[c(W,{variant:"small",tone:"muted",children:n(m.links)}),t.links.map(i=>i.targetId!==null?N("button",{type:"button",className:"cx-memory-link",onClick:()=>e.onOpen(i.targetId),children:["[[",i.path,"]]"]},i.path):N("span",{className:"cx-memory-link","data-dangling":"true",children:["[[",i.path,"]] · ",n(m.dangling)]},i.path))]}):null,c(pn,{keyWidth:"12ch",rows:[{k:n(m.recalled),v:n(ze(t.recalls))},{k:n(m.lastRecalled),v:ge(t.lastRecalledAt,l)},{k:n(m.created),v:Ae(t.createdAt,l)},{k:n(m.updated),v:Ae(t.updatedAt,l)},...t.createdIn!==null?[{k:n(m.createdIn),v:e.editable?c("a",{className:"cx-memory-anchor",href:`/chat/${encodeURIComponent(t.createdIn)}`,children:n(m.openConversation)}):t.createdIn}]:[]]}),d==="confirm"?N("div",{className:"cx-memory-confirm",role:"alertdialog","aria-label":n(m.confirmTitle),children:[c(W,{variant:"h3",children:n(m.confirmTitle)}),c(W,{variant:"small",children:n(Ve)}),N(Te,{direction:"row",gap:8,justify:"end",children:[c(V,{onClick:()=>a("view"),children:n(m.cancel)}),c(V,{variant:"danger-solid",loading:C,onClick:()=>{v(!0),e.onDelete(t.id).finally(()=>v(!1))},children:n(m.delete)})]})]}):N(Te,{direction:"row",gap:8,justify:"end",children:[e.editable?c(V,{onClick:()=>{M(t.description),x(t.body),a("edit")},children:n(m.edit)}):null,e.canDelete?c(V,{variant:"danger",onClick:()=>a("confirm"),children:n(m.delete)}):null]}),e.editable?null:c(W,{variant:"small",tone:"muted",children:n(m.readOnly)})]})})]})}var Kn=$n({name:"memory",components:{overview:Gn("org.page",tn)}});export{Kn as default};