@niwa-labs/memory 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +107 -2
- package/package.json +33 -4
- package/src/cockpit/actions.ts +95 -0
- package/src/cockpit/index.tsx +23 -0
- package/src/cockpit/notes.ts +78 -0
- package/src/cockpit/page.tsx +191 -0
- package/src/consolidate.ts +113 -0
- package/src/context.ts +41 -0
- package/src/fold.ts +308 -0
- package/src/holds.ts +13 -0
- package/src/index.ts +775 -0
- package/src/records.ts +538 -0
- package/src/same.ts +15 -0
- package/src/search.ts +48 -0
- package/src/share-question.ts +27 -0
- package/src/top.ts +44 -0
- package/test/cockpit-actions.test.ts +53 -0
- package/test/cockpit-notes.test.ts +89 -0
- package/test/consolidate.test.ts +171 -0
- package/test/context.test.ts +241 -0
- package/test/corroboration.test.ts +61 -0
- package/test/delegate-context.test.ts +16 -0
- package/test/fixtures/host.ts +229 -0
- package/test/intake.test.ts +69 -0
- package/test/notes.test.ts +124 -0
- package/test/projects.test.ts +37 -0
- package/test/recovery.test.ts +174 -0
- package/test/search.test.ts +88 -0
- package/test/top.test.ts +84 -0
- package/tsconfig.json +15 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Niwa Labs contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,108 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @niwa-labs/memory
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A plugin for agent memory: notes with sources and confirmation, pages, a top layer, consolidation and intake of session digests.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { agents } from "@niwa-labs/agent";
|
|
7
|
+
import { memory } from "@niwa-labs/memory";
|
|
8
|
+
|
|
9
|
+
const sessionsModule = sessions({ harnesses });
|
|
10
|
+
const agentsModule = agents({ agents: [rin] });
|
|
11
|
+
const bind = agentsModule.bind(sessionsModule.bind());
|
|
12
|
+
host.use(messages({ bind }), requests({ bind }), sessionsModule, agentsModule, memory({ bind }));
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Install it after the agents module, which reads its briefing and prompt sections, and on
|
|
16
|
+
a host with the requests module, which asks the owner.
|
|
17
|
+
|
|
18
|
+
There is one memory module on a host and a memory in it for every agent,
|
|
19
|
+
named by the agent. The binding says which address a caller speaks as: a
|
|
20
|
+
session of an agent reaches that agent's memory and no other, the owner
|
|
21
|
+
reaches every memory, and the host and other plugins' handlers name the
|
|
22
|
+
memory they mean. Another agent's memory is asked through
|
|
23
|
+
`memory.context`.
|
|
24
|
+
|
|
25
|
+
## Notes
|
|
26
|
+
|
|
27
|
+
A note is one conclusion (`text`) with what backs it (`detail`), whom it is
|
|
28
|
+
about (`owner` or `work`), the project it holds for (an absolute directory,
|
|
29
|
+
kept in its canonical form: `/a/b/../c/` is `/a/c`) and its
|
|
30
|
+
source: the owner's own word, the writer's conclusion, a session up to a
|
|
31
|
+
locator, or a record. Only the owner gives a note the owner as its source;
|
|
32
|
+
his confirmation or correction makes a note his word, and a correction by
|
|
33
|
+
anyone else makes it unconfirmed again. A corrected note stands on its new
|
|
34
|
+
text alone: the corrector is its only source, and it earns its place in the
|
|
35
|
+
top layer again unless it was placed by hand. A note written again in the
|
|
36
|
+
same words, in the same order, gains a source instead of a copy.
|
|
37
|
+
|
|
38
|
+
A note stops being shown first (`memory.drop`), is taken back
|
|
39
|
+
(`memory.retract`), or is erased (`memory.erase`). The journal is written
|
|
40
|
+
once, so erasing hides the text from every read, including reads at an
|
|
41
|
+
earlier position, while the record that first held it stays.
|
|
42
|
+
|
|
43
|
+
## Reading
|
|
44
|
+
|
|
45
|
+
- `memory.get`, `memory.list`, `memory.page.get` and `memory.search` read
|
|
46
|
+
the memory now or at a journal position (`at`). `memory.page.list` lists the
|
|
47
|
+
pages by name, with the revision of each and without the text.
|
|
48
|
+
- `memory.search` ranks notes, pages and the latest digests by words with
|
|
49
|
+
BM25. A word matches whole or as the start of a longer word. No model or
|
|
50
|
+
external service is used.
|
|
51
|
+
- `memory.top` is the top layer for a project: lifted notes about the
|
|
52
|
+
owner, for the project and in general, newest first, within 4000
|
|
53
|
+
characters. The agent's briefing carries it as "What it remembers", and
|
|
54
|
+
so does the prompt a new session of the agent starts with, for the agent's
|
|
55
|
+
project or the directory of the session attached to it last.
|
|
56
|
+
|
|
57
|
+
## Context requests
|
|
58
|
+
|
|
59
|
+
`memory.context` names the memory, the query, the purpose and, for a
|
|
60
|
+
handler, the addressee; a bound caller always asks for itself. The memory's
|
|
61
|
+
own agent and the owner get notes whole. Any other addressee gets only the
|
|
62
|
+
conclusion, whom it is about and where it holds:
|
|
63
|
+
|
|
64
|
+
- a note about the owner leaves only after the owner says yes for that
|
|
65
|
+
addressee, that revision of the note and the purpose he was told. He is
|
|
66
|
+
asked once for each (`request.ask`); an answer found by a resolver lets
|
|
67
|
+
nothing leave, and `memory.share` gives his word without a question, for
|
|
68
|
+
the purpose he names or, naming none, for every purpose. A request read at a
|
|
69
|
+
position (`at`) asks nobody, and says `not-asked` for a note he was never
|
|
70
|
+
asked of, `asked` only when his question stood at that position.
|
|
71
|
+
The question names the note and its revision and the purpose, never the
|
|
72
|
+
note's text, which anyone reading the open requests would read. The
|
|
73
|
+
cockpit page reads the note when it shows the question, and shows the text
|
|
74
|
+
only while the note holds as it was asked; a question about a note that is
|
|
75
|
+
corrected, taken back or erased is cancelled;
|
|
76
|
+
- a project note goes to agents whose project contains it, and is not so
|
|
77
|
+
much as named to any other;
|
|
78
|
+
- other work notes go to anyone who asks.
|
|
79
|
+
|
|
80
|
+
Only what the addressee may be told is ranked, and `limit` counts only that;
|
|
81
|
+
the notes about the owner that match are ranked apart and listed as
|
|
82
|
+
withheld.
|
|
83
|
+
|
|
84
|
+
Every conclusion names its source: the memory's address, the note, and the
|
|
85
|
+
journal position it stood at. The memory is read once, at one position
|
|
86
|
+
(`at` in the answer), so a request repeated with that `at` reads the memory
|
|
87
|
+
as it was then.
|
|
88
|
+
|
|
89
|
+
## Intake and consolidation
|
|
90
|
+
|
|
91
|
+
Each digest of an attached session (`SessionDigestTaken`) is recorded as a
|
|
92
|
+
pointer to the turn that carried it, with the session and, as the project,
|
|
93
|
+
the directory the session was attached in when the digest was told (none if
|
|
94
|
+
it had been attached to another agent or let go of since). The digest is searchable, but no note is made from it
|
|
95
|
+
automatically. Notes are written by the agent itself, which receives the
|
|
96
|
+
digest as a turn.
|
|
97
|
+
|
|
98
|
+
Consolidation merges notes that came to say the same thing. It lifts notes
|
|
99
|
+
the owner confirmed, or notes with three sources, while each part of the top
|
|
100
|
+
layer has room (twelve notes), dropping weaker automatic lifts to make room.
|
|
101
|
+
It retires unconfirmed single-source notes unchanged for thirty days, and
|
|
102
|
+
the oldest unplaced notes past 500. Notes placed by hand and confirmed notes
|
|
103
|
+
are never retired. A digest arriving triggers consolidation once twenty
|
|
104
|
+
records have changed the memory since the last one; `memory.consolidate`
|
|
105
|
+
runs it on demand. All of these limits are set with `memory({ limits })`.
|
|
106
|
+
|
|
107
|
+
`./cockpit` is the plugin's page: for each agent, the top layer by part, every note with its source and standing, the
|
|
108
|
+
pages, and the share questions that wait for the owner.
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@niwa-labs/memory",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./src/index.ts",
|
|
8
|
+
"./records": "./src/records.ts",
|
|
9
|
+
"./cockpit": "./src/cockpit/index.tsx"
|
|
10
|
+
},
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"@niwa-labs/agent": "*",
|
|
13
|
+
"@niwa-labs/cockpit-sdk": "*",
|
|
14
|
+
"@niwa-labs/core": "*",
|
|
15
|
+
"@niwa-labs/plugin": "*",
|
|
16
|
+
"@niwa-labs/requests": "*",
|
|
17
|
+
"@niwa-labs/script": "*",
|
|
18
|
+
"@niwa-labs/ui-kit": "*",
|
|
19
|
+
"zod": "^4.6.7"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"@niwa-labs/delegate": "0.0.0",
|
|
23
|
+
"@niwa-labs/testing": "*",
|
|
24
|
+
"@tanstack/react-query": "^5.108.2",
|
|
25
|
+
"@types/react": "^19.3.0",
|
|
26
|
+
"@types/react-dom": "^19.3.0",
|
|
27
|
+
"react": "^19.3.1",
|
|
28
|
+
"react-dom": "^19.3.1"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@tanstack/react-query": "^5.108.2",
|
|
32
|
+
"react": "^19.3.1",
|
|
33
|
+
"react-dom": "^19.3.1"
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The actions the memory page calls, as the cockpit calls them: name and the part of each schema the page reads.
|
|
3
|
+
*
|
|
4
|
+
* The module runs in the browser and cannot import the host-side schemas, which reach for Node. A field the host
|
|
5
|
+
* stopped sending fails the page that reads it, which `test/cockpit-actions.test.ts` checks against the real actions.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
|
|
10
|
+
export const Address = z.object({ kind: z.string(), id: z.string().optional(), harness: z.string().optional() }).loose();
|
|
11
|
+
export type Address = z.infer<typeof Address>;
|
|
12
|
+
|
|
13
|
+
/** The memories are those of the agents, named by the agent. */
|
|
14
|
+
export const agentListAction = {
|
|
15
|
+
name: "agent.list",
|
|
16
|
+
input: z.object({}),
|
|
17
|
+
output: z.object({ items: z.array(z.object({ name: z.string() })) }),
|
|
18
|
+
} as const;
|
|
19
|
+
|
|
20
|
+
export const NoteAbout = z.enum(["owner", "work"]);
|
|
21
|
+
export type NoteAbout = z.infer<typeof NoteAbout>;
|
|
22
|
+
|
|
23
|
+
export const NoteSource = z.discriminatedUnion("kind", [
|
|
24
|
+
z.object({ kind: z.literal("owner") }),
|
|
25
|
+
z.object({ kind: z.literal("inferred") }),
|
|
26
|
+
z.object({ kind: z.literal("session"), session: z.string() }),
|
|
27
|
+
z.object({ kind: z.literal("record"), record: z.string() }),
|
|
28
|
+
]);
|
|
29
|
+
export type NoteSource = z.infer<typeof NoteSource>;
|
|
30
|
+
|
|
31
|
+
export const Note = z.object({
|
|
32
|
+
note: z.string(),
|
|
33
|
+
text: z.string(),
|
|
34
|
+
detail: z.string().optional(),
|
|
35
|
+
about: NoteAbout,
|
|
36
|
+
project: z.string().optional(),
|
|
37
|
+
source: NoteSource,
|
|
38
|
+
confirmed: z.boolean(),
|
|
39
|
+
sources: z.number(),
|
|
40
|
+
top: z.boolean(),
|
|
41
|
+
pinned: z.boolean(),
|
|
42
|
+
revision: z.number(),
|
|
43
|
+
written: z.number(),
|
|
44
|
+
});
|
|
45
|
+
export type Note = z.infer<typeof Note>;
|
|
46
|
+
|
|
47
|
+
export const MAX_NOTES = 500;
|
|
48
|
+
|
|
49
|
+
export const noteListAction = {
|
|
50
|
+
name: "memory.list",
|
|
51
|
+
input: z.object({ memory: z.string(), limit: z.number().int().positive().max(MAX_NOTES).optional() }),
|
|
52
|
+
output: z.object({ memory: z.string(), notes: z.array(Note) }),
|
|
53
|
+
} as const;
|
|
54
|
+
|
|
55
|
+
/** One note, as the page reads it to show the text of a question's note: only while it holds as the question named it. */
|
|
56
|
+
export const noteGetAction = {
|
|
57
|
+
name: "memory.get",
|
|
58
|
+
input: z.object({ memory: z.string(), note: z.string() }),
|
|
59
|
+
output: z.object({ note: z.string(), text: z.string(), status: z.string(), revision: z.number() }),
|
|
60
|
+
} as const;
|
|
61
|
+
|
|
62
|
+
export const PageSummary = z.object({ page: z.string(), title: z.string(), project: z.string().optional(), revision: z.number() });
|
|
63
|
+
export type PageSummary = z.infer<typeof PageSummary>;
|
|
64
|
+
|
|
65
|
+
export const pageListAction = {
|
|
66
|
+
name: "memory.page.list",
|
|
67
|
+
input: z.object({ memory: z.string() }),
|
|
68
|
+
output: z.object({ memory: z.string(), pages: z.array(PageSummary) }),
|
|
69
|
+
} as const;
|
|
70
|
+
|
|
71
|
+
export const pageGetAction = {
|
|
72
|
+
name: "memory.page.get",
|
|
73
|
+
input: z.object({ memory: z.string(), page: z.string() }),
|
|
74
|
+
output: z.object({ page: z.string(), title: z.string(), text: z.string(), project: z.string().optional(), revision: z.number() }),
|
|
75
|
+
} as const;
|
|
76
|
+
|
|
77
|
+
const OpenRequest = z.object({
|
|
78
|
+
id: z.string(),
|
|
79
|
+
to: Address,
|
|
80
|
+
question: z.string(),
|
|
81
|
+
input: z.object({ kind: z.string(), title: z.string(), detail: z.string().optional() }).loose(),
|
|
82
|
+
from: Address.optional(),
|
|
83
|
+
});
|
|
84
|
+
export type OpenRequest = z.infer<typeof OpenRequest>;
|
|
85
|
+
|
|
86
|
+
const OpenPaused = z.object({ kind: z.literal("paused"), invocation: z.string() });
|
|
87
|
+
|
|
88
|
+
/** What waits for the owner: the share questions of the memories are among it. */
|
|
89
|
+
export const openAction = {
|
|
90
|
+
name: "request.open",
|
|
91
|
+
input: z.object({}),
|
|
92
|
+
output: z.object({ requests: z.array(z.union([OpenPaused, OpenRequest])) }),
|
|
93
|
+
} as const;
|
|
94
|
+
|
|
95
|
+
export type Open = z.infer<typeof openAction.output>["requests"][number];
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** The cockpit module of the memory plugin: what an agent remembers, its pages, and the questions waiting for the owner. */
|
|
2
|
+
|
|
3
|
+
import { definePlugin } from "@niwa-labs/cockpit-sdk";
|
|
4
|
+
|
|
5
|
+
import { MemoryPage } from "./page.tsx";
|
|
6
|
+
|
|
7
|
+
export default definePlugin({
|
|
8
|
+
id: "memory",
|
|
9
|
+
setup(ctx) {
|
|
10
|
+
ctx.pages.add({
|
|
11
|
+
path: "/memory",
|
|
12
|
+
title: "Память",
|
|
13
|
+
commandHeading: true,
|
|
14
|
+
nav: { order: 65 },
|
|
15
|
+
commands: [
|
|
16
|
+
{ action: "memory.note", label: "Добавить заметку" },
|
|
17
|
+
{ action: "memory.page.write", label: "Записать страницу" },
|
|
18
|
+
{ action: "memory.search", label: "Найти запись" },
|
|
19
|
+
],
|
|
20
|
+
component: MemoryPage,
|
|
21
|
+
});
|
|
22
|
+
},
|
|
23
|
+
});
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/** What the memory page makes of notes and of the questions that wait: the top layer by part, sources, and share questions. */
|
|
2
|
+
|
|
3
|
+
import { SHARE_QUESTION, shareReferenceOf } from "../share-question.ts";
|
|
4
|
+
import type { ShareReference } from "../share-question.ts";
|
|
5
|
+
import type { Note, NoteSource, Open, OpenRequest } from "./actions.ts";
|
|
6
|
+
|
|
7
|
+
export { SHARE_QUESTION };
|
|
8
|
+
|
|
9
|
+
/** A part of the top layer: what it is called and the notes in it. */
|
|
10
|
+
export type TopPart = { heading: string; notes: Note[] };
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The top layer by part, as the memory shows it to an agent: the lifted notes about the owner, then those for one project
|
|
14
|
+
* each, then the ones that hold in general; the newest first in each part. A part with no note is left out.
|
|
15
|
+
*/
|
|
16
|
+
export function topParts(notes: readonly Note[]): TopPart[] {
|
|
17
|
+
const lifted = notes.filter((note) => note.top).sort((a, b) => b.written - a.written);
|
|
18
|
+
const projects = [...new Set(lifted.filter((note) => note.about === "work" && note.project !== undefined).map((note) => note.project!))].sort();
|
|
19
|
+
const parts: TopPart[] = [
|
|
20
|
+
{ heading: "О владельце", notes: lifted.filter((note) => note.about === "owner") },
|
|
21
|
+
...projects.map((project) => ({ heading: `Проект ${project}`, notes: lifted.filter((note) => note.about === "work" && note.project === project) })),
|
|
22
|
+
{ heading: "Общее", notes: lifted.filter((note) => note.about === "work" && note.project === undefined) },
|
|
23
|
+
];
|
|
24
|
+
return parts.filter((part) => part.notes.length > 0);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The notes in the order of the page: newest first. */
|
|
28
|
+
export function newestFirst(notes: readonly Note[]): Note[] {
|
|
29
|
+
return [...notes].sort((a, b) => b.written - a.written);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Where a note comes from, in a few words. */
|
|
33
|
+
export function sourceText(source: NoteSource): string {
|
|
34
|
+
switch (source.kind) {
|
|
35
|
+
case "owner":
|
|
36
|
+
return "слова владельца";
|
|
37
|
+
case "inferred":
|
|
38
|
+
return "вывод автора";
|
|
39
|
+
case "session":
|
|
40
|
+
return `сессия ${source.session}`;
|
|
41
|
+
case "record":
|
|
42
|
+
return `запись ${source.record}`;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** How much a note stands on: подтверждено владельцем, or by how many sources. */
|
|
47
|
+
export function standingText(note: Pick<Note, "confirmed" | "sources">): string {
|
|
48
|
+
if (note.confirmed) return "подтверждено владельцем";
|
|
49
|
+
return note.sources === 1 ? "один источник" : `источников: ${String(note.sources)}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The memory the page shows: the one asked for when it is one of the agents', else the first. */
|
|
53
|
+
export function memoryChoice(asked: string | undefined, names: readonly string[]): string | undefined {
|
|
54
|
+
return asked !== undefined && names.includes(asked) ? asked : names[0];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A question waiting for the owner about what a memory may tell: the note it is about, when its detail names one. */
|
|
58
|
+
export type ShareQuestion = { id: string; title: string; detail: string | undefined; reference: ShareReference | undefined; purpose: string | undefined };
|
|
59
|
+
|
|
60
|
+
function isOpenRequest(open: Open): open is OpenRequest {
|
|
61
|
+
return "question" in open;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The share questions that wait for one memory: those it asked, which name it as the asker. */
|
|
65
|
+
export function shareQuestions(open: readonly Open[], memory: string): ShareQuestion[] {
|
|
66
|
+
return open
|
|
67
|
+
.filter(isOpenRequest)
|
|
68
|
+
.filter((one) => one.question === SHARE_QUESTION && one.from?.kind === "agent" && one.from.id === memory)
|
|
69
|
+
.map((one) => {
|
|
70
|
+
const named = shareReferenceOf(one.input.detail);
|
|
71
|
+
return { id: one.id, title: one.input.title, detail: one.input.detail, reference: named?.reference, purpose: named?.purpose };
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** What a question's note shows now: the owner is shown its text only while the note still holds as the question named it. */
|
|
76
|
+
export function shownText(reference: ShareReference, note: Pick<Note, "text" | "revision"> & { status: string }): string | undefined {
|
|
77
|
+
return note.status === "live" && note.revision === reference.revision ? note.text : undefined;
|
|
78
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/** The memory of an agent: what is shown first, every note it holds, its pages, and the questions waiting for the owner. */
|
|
2
|
+
|
|
3
|
+
import { EntityLink, PageLink, pathFor, useCall, type PageProps } from "@niwa-labs/cockpit-sdk";
|
|
4
|
+
import { CopyValue, DataValue, Markdown } from "@niwa-labs/ui-kit";
|
|
5
|
+
|
|
6
|
+
import { MAX_NOTES, agentListAction, noteGetAction, noteListAction, openAction, pageGetAction, pageListAction, type Note, type PageSummary } from "./actions.ts";
|
|
7
|
+
import { memoryChoice, newestFirst, shareQuestions, shownText, sourceText, standingText, topParts, type ShareQuestion } from "./notes.ts";
|
|
8
|
+
|
|
9
|
+
const NOTES = { refreshOn: { types: ["memory.note.*", "memory.consolidated"] } };
|
|
10
|
+
const PAGES = { refreshOn: { types: ["memory.page.written"] } };
|
|
11
|
+
const SHARES = { refreshOn: { types: ["request.*", "memory.share.*"] } };
|
|
12
|
+
|
|
13
|
+
function memoryPath(memory: string, page?: string): string {
|
|
14
|
+
return pathFor("/memory", {}, { memory, page });
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function Failed({ what, message }: { what: string; message: string }) {
|
|
18
|
+
return <p role="alert" className="text-sm text-destructive">Не удалось загрузить {what}. {message}</p>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function NoteRow({ note }: { note: Note }) {
|
|
22
|
+
return (
|
|
23
|
+
<li data-slot="note-row" data-about={note.about} data-top={note.top} className="flex min-w-0 flex-col gap-1 py-2">
|
|
24
|
+
<span className="text-sm">{note.text}</span>
|
|
25
|
+
<div className="flex min-w-0 flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
|
26
|
+
<span>{note.about === "owner" ? "О владельце" : "О работе"}</span>
|
|
27
|
+
{note.project === undefined ? null : <DataValue value={note.project} />}
|
|
28
|
+
<span>{standingText(note)}</span>
|
|
29
|
+
<span>Источник</span>
|
|
30
|
+
{note.source.kind === "session" ? <CopyValue value={note.source.session} label={sourceText(note.source)} /> :
|
|
31
|
+
note.source.kind === "record" ? <CopyValue value={note.source.record} label={sourceText(note.source)} /> : <span>{sourceText(note.source)}</span>}
|
|
32
|
+
{note.top ? <span>{note.pinned ? "Закреплено вручную" : "Показывается агенту первой"}</span> : null}
|
|
33
|
+
{note.revision > 1 ? <span>версия {note.revision}</span> : null}
|
|
34
|
+
</div>
|
|
35
|
+
</li>
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function TopLayer({ notes }: { notes: readonly Note[] }) {
|
|
40
|
+
const parts = topParts(notes);
|
|
41
|
+
if (parts.length === 0) return <p className="text-sm text-muted-foreground">В приоритетных заметках пока пусто.</p>;
|
|
42
|
+
return (
|
|
43
|
+
<div data-slot="top-layer" className="flex min-w-0 flex-col gap-3">
|
|
44
|
+
{parts.map((part) => (
|
|
45
|
+
<section key={part.heading} data-slot="top-part" className="flex min-w-0 flex-col gap-1">
|
|
46
|
+
<h4 className="truncate text-xs font-semibold text-muted-foreground">{part.heading}</h4>
|
|
47
|
+
<ul className="divide-y rounded-lg border bg-card px-3 text-card-foreground">
|
|
48
|
+
{part.notes.map((note) => (
|
|
49
|
+
<NoteRow key={note.note} note={note} />
|
|
50
|
+
))}
|
|
51
|
+
</ul>
|
|
52
|
+
</section>
|
|
53
|
+
))}
|
|
54
|
+
</div>
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function PageBody({ memory, page }: { memory: string; page: string }) {
|
|
59
|
+
const got = useCall(pageGetAction, { memory, page }, PAGES);
|
|
60
|
+
if (got.isPending) return <p className="text-sm text-muted-foreground">Загружаем страницу…</p>;
|
|
61
|
+
if (got.isError) return <Failed what="страницу" message={got.error.message} />;
|
|
62
|
+
return (
|
|
63
|
+
<article data-slot="memory-page" className="flex min-w-0 flex-col gap-2 rounded-lg border bg-card p-3 text-card-foreground">
|
|
64
|
+
<h4 className="text-sm font-semibold">{got.data.title}</h4>
|
|
65
|
+
<Markdown text={got.data.text} />
|
|
66
|
+
</article>
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function Pages({ memory, open }: { memory: string; open: string | undefined }) {
|
|
71
|
+
const pages = useCall(pageListAction, { memory }, PAGES);
|
|
72
|
+
if (pages.isPending) return <p className="text-sm text-muted-foreground">Загружаем страницы…</p>;
|
|
73
|
+
if (pages.isError) return <Failed what="страницы" message={pages.error.message} />;
|
|
74
|
+
if (pages.data.pages.length === 0) return <p className="text-sm text-muted-foreground">Для этой памяти пока нет страниц.</p>;
|
|
75
|
+
return (
|
|
76
|
+
<div className="flex min-w-0 flex-col gap-2">
|
|
77
|
+
<ul data-slot="pages" className="divide-y rounded-lg border bg-card px-3 text-card-foreground">
|
|
78
|
+
{pages.data.pages.map((page: PageSummary) => (
|
|
79
|
+
<li key={page.page} data-slot="page-row" className="flex min-w-0 flex-wrap items-center gap-2 py-2">
|
|
80
|
+
<PageLink to={memoryPath(memory, page.page)} className="min-w-0 truncate text-sm font-medium hover:underline">
|
|
81
|
+
{page.title}
|
|
82
|
+
</PageLink>
|
|
83
|
+
<span className="text-xs"><CopyValue value={page.page} /></span>
|
|
84
|
+
{page.project === undefined ? null : <span className="text-xs text-muted-foreground"><DataValue value={page.project} /></span>}
|
|
85
|
+
<span className="ml-auto shrink-0 text-xs text-muted-foreground">версия {page.revision}</span>
|
|
86
|
+
</li>
|
|
87
|
+
))}
|
|
88
|
+
</ul>
|
|
89
|
+
{open === undefined ? null : <PageBody memory={memory} page={open} />}
|
|
90
|
+
</div>
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The note a question is about, read when it is shown: its text only while it holds as the question named it. */
|
|
95
|
+
function QuestionNote({ reference }: { reference: NonNullable<ShareQuestion["reference"]> }) {
|
|
96
|
+
const got = useCall(noteGetAction, { memory: reference.memory, note: reference.note }, NOTES);
|
|
97
|
+
if (got.isPending) return <span className="text-xs text-muted-foreground">Загружаем заметку…</span>;
|
|
98
|
+
if (got.isError) return <span className="text-xs text-muted-foreground">Заметка больше недоступна.</span>;
|
|
99
|
+
const text = shownText(reference, got.data);
|
|
100
|
+
return text === undefined ? (
|
|
101
|
+
<span className="text-xs text-muted-foreground">После отправки вопроса заметка изменилась.</span>
|
|
102
|
+
) : (
|
|
103
|
+
<span className="whitespace-pre-wrap text-sm">{text}</span>
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function ShareQuestions({ memory }: { memory: string }) {
|
|
108
|
+
const open = useCall(openAction, {}, SHARES);
|
|
109
|
+
if (open.isPending) return <p className="text-sm text-muted-foreground">Загружаем вопросы…</p>;
|
|
110
|
+
if (open.isError) return <Failed what="вопросы" message={open.error.message} />;
|
|
111
|
+
const questions = shareQuestions(open.data.requests, memory);
|
|
112
|
+
if (questions.length === 0) return <p className="text-sm text-muted-foreground">Нет вопросов о доступе к этой памяти.</p>;
|
|
113
|
+
return (
|
|
114
|
+
<ul data-slot="share-questions" className="divide-y rounded-lg border bg-card px-3 text-card-foreground">
|
|
115
|
+
{questions.map((question) => (
|
|
116
|
+
<li key={question.id} data-slot="share-question" className="flex min-w-0 flex-col gap-1 py-2">
|
|
117
|
+
<div className="flex min-w-0 items-center gap-2">
|
|
118
|
+
<span className="min-w-0 break-words text-sm font-medium">{question.title}</span>
|
|
119
|
+
<EntityLink entity={{ kind: "request", id: question.id }} short />
|
|
120
|
+
</div>
|
|
121
|
+
{question.reference === undefined ? null : <QuestionNote reference={question.reference} />}
|
|
122
|
+
{question.purpose === undefined ? null : <span className="whitespace-pre-wrap text-xs text-muted-foreground">Цель запроса · {question.purpose}</span>}
|
|
123
|
+
</li>
|
|
124
|
+
))}
|
|
125
|
+
</ul>
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function MemoryView({ memory, page }: { memory: string; page: string | undefined }) {
|
|
130
|
+
const notes = useCall(noteListAction, { memory, limit: MAX_NOTES }, NOTES);
|
|
131
|
+
return (
|
|
132
|
+
<div className="flex min-w-0 flex-col gap-4">
|
|
133
|
+
<section className="flex min-w-0 flex-col gap-2">
|
|
134
|
+
<h3 className="text-sm font-semibold text-muted-foreground">Вопросы о доступе к памяти</h3>
|
|
135
|
+
<ShareQuestions memory={memory} />
|
|
136
|
+
</section>
|
|
137
|
+
<section className="flex min-w-0 flex-col gap-2">
|
|
138
|
+
<h3 className="text-sm font-semibold text-muted-foreground">Приоритетные заметки</h3>
|
|
139
|
+
{notes.isPending ? <p className="text-sm text-muted-foreground">Загружаем заметки…</p> : notes.isError ? <Failed what="заметки" message={notes.error.message} /> : <TopLayer notes={notes.data.notes} />}
|
|
140
|
+
</section>
|
|
141
|
+
<section className="flex min-w-0 flex-col gap-2">
|
|
142
|
+
<h3 className="text-sm font-semibold text-muted-foreground">Все заметки</h3>
|
|
143
|
+
{notes.isPending ? (
|
|
144
|
+
<p className="text-sm text-muted-foreground">Загружаем заметки…</p>
|
|
145
|
+
) : notes.isError ? (
|
|
146
|
+
<Failed what="заметки" message={notes.error.message} />
|
|
147
|
+
) : notes.data.notes.length === 0 ? (
|
|
148
|
+
<p className="text-sm text-muted-foreground">У этого агента пока нет заметок.</p>
|
|
149
|
+
) : (
|
|
150
|
+
<ul data-slot="notes" className="divide-y rounded-lg border bg-card px-3 text-card-foreground">
|
|
151
|
+
{newestFirst(notes.data.notes).map((note) => (
|
|
152
|
+
<NoteRow key={note.note} note={note} />
|
|
153
|
+
))}
|
|
154
|
+
</ul>
|
|
155
|
+
)}
|
|
156
|
+
</section>
|
|
157
|
+
<section className="flex min-w-0 flex-col gap-2">
|
|
158
|
+
<h3 className="text-sm font-semibold text-muted-foreground">Страницы</h3>
|
|
159
|
+
<Pages memory={memory} open={page} />
|
|
160
|
+
</section>
|
|
161
|
+
</div>
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function MemoryPage({ search }: PageProps<"/memory">) {
|
|
166
|
+
const agents = useCall(agentListAction, {});
|
|
167
|
+
const names = agents.data?.items.map((one) => one.name) ?? [];
|
|
168
|
+
const memory = memoryChoice(search["memory"], names);
|
|
169
|
+
return (
|
|
170
|
+
<div className="desk-page">
|
|
171
|
+
{agents.isPending ? (
|
|
172
|
+
<p className="text-sm text-muted-foreground">Загружаем список агентов…</p>
|
|
173
|
+
) : agents.isError ? (
|
|
174
|
+
<Failed what="список агентов" message={agents.error.message} />
|
|
175
|
+
) : memory === undefined ? (
|
|
176
|
+
<p className="text-sm text-muted-foreground">Добавьте агента, чтобы открыть его память.</p>
|
|
177
|
+
) : (
|
|
178
|
+
<>
|
|
179
|
+
<nav aria-label="Агенты" data-slot="memories" className="flex flex-wrap items-center gap-1 text-sm">
|
|
180
|
+
{names.map((name) => (
|
|
181
|
+
<PageLink key={name} to={memoryPath(name)} className={name === memory ? "rounded bg-muted px-2 py-0.5 font-semibold" : "rounded px-2 py-0.5 hover:bg-muted"}>
|
|
182
|
+
{name}
|
|
183
|
+
</PageLink>
|
|
184
|
+
))}
|
|
185
|
+
</nav>
|
|
186
|
+
<MemoryView key={memory} memory={memory} page={search["page"]} />
|
|
187
|
+
</>
|
|
188
|
+
)}
|
|
189
|
+
</div>
|
|
190
|
+
);
|
|
191
|
+
}
|