@joe-broadhead/opencode-mem 0.8.5 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +512 -0
- package/README.md +127 -61
- package/docs/agent-protocol.md +67 -177
- package/package.json +1453 -100
- package/skills/mem.pages/SKILL.md +146 -0
- package/skills/mem.sharing/SKILL.md +91 -0
- package/skills/mem.sources/SKILL.md +94 -0
- package/skills/mem.usage/SKILL.md +129 -492
- package/src/backend/records.js +285 -0
- package/src/backend/v3.js +3 -0
- package/src/bootstrap.js +49 -45
- package/src/call-shapes.js +41 -10
- package/src/collector-lock.js +162 -0
- package/src/collector-service.js +441 -0
- package/src/collector.js +381 -0
- package/src/commands.js +3 -3
- package/src/config.js +15 -1
- package/src/credentials.js +26 -1
- package/src/curation.js +1 -1
- package/src/permissions.js +87 -10
- package/src/protocol.js +29 -20
- package/src/recall.js +104 -27
- package/src/records-store.js +267 -121
- package/src/records.js +63 -11
- package/src/runtime.js +23 -14
- package/src/skills.js +44 -18
- package/src/sources.js +58 -0
- package/src/spaces.js +93 -10
- package/src/tools/aliases.js +164 -0
- package/src/tools/commitments.js +12 -9
- package/src/tools/held-write.js +82 -0
- package/src/tools/index.js +100 -23
- package/src/tools/ingest.js +277 -0
- package/src/tools/knowledge.js +6 -1
- package/src/tools/memory.js +722 -229
- package/src/tools/page.js +423 -0
- package/src/tools/recall.js +371 -113
- package/src/tools/records-kit.js +142 -0
- package/src/tools/share.js +1042 -0
- package/src/tools/shared.js +16 -2
- package/src/tools/spaces.js +431 -143
- package/src/tools/status.js +87 -58
- package/src/tools/wiki.js +8 -4
- package/src/views/contracts.js +293 -3
- package/src/views/inbox-decision.js +59 -0
- package/src/views/recall-result.js +12 -0
- package/src/views/records-reads.js +675 -0
- package/src/views/rpc.js +58 -99
- package/src/views/shape.js +61 -0
- package/views/commitments.html +4 -0
- package/views/graph.html +753 -0
- package/views/home.html +11 -5
- package/views/journal.html +621 -0
- package/views/memory.html +7 -1
- package/views/pages.html +636 -0
- package/views/recall.html +123 -0
- package/views/review.html +406 -0
- package/views/today.html +309 -0
package/src/tools/spaces.js
CHANGED
|
@@ -1,179 +1,467 @@
|
|
|
1
1
|
import { contextScopeLabel } from "../scope.js"
|
|
2
|
-
import {
|
|
2
|
+
import { DEFAULT_ACCOUNT, isAccountName, isSourceName } from "../collector.js"
|
|
3
|
+
import { knownSources, sourceEntry } from "../sources.js"
|
|
4
|
+
import { errorMessage, isPlainObject, oneLine } from "../util.js"
|
|
5
|
+
import { RECORDS_MISSING, recordsFailure, recordsOf } from "./share.js"
|
|
6
|
+
import { renderHealth } from "./status.js"
|
|
7
|
+
|
|
8
|
+
export const SPACES_ACTIONS = Object.freeze(["current", "list", "members", "access", "health", "sources", "review"])
|
|
9
|
+
const DECISIONS = Object.freeze(["accept", "reject", "edit"])
|
|
10
|
+
const REVIEW_LIMIT = 20
|
|
3
11
|
|
|
4
12
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
13
|
+
* `mem_spaces` (docs/design/memory-v1-contracts.md §4.1): where memory lives
|
|
14
|
+
* and what flows into it.
|
|
15
|
+
*
|
|
16
|
+
* - `current`, `list`, `members`, `access`: read from the control plane, which
|
|
17
|
+
* decides access; nothing here derives a role or names a container.
|
|
18
|
+
* - `health`: the backend, the layers, the records service's counts and the
|
|
19
|
+
* collector (it absorbs `mem_status`).
|
|
20
|
+
* - `sources`: the funnel's bindings (memory-funnel-v1.md §10). Listing reads
|
|
21
|
+
* them; `bind` shows the signed-in account and asks (`sources.bind`) before
|
|
22
|
+
* collection may start; `unbind` previews unless `confirm`, then stops
|
|
23
|
+
* collection and deletes the source's events.
|
|
24
|
+
* - `review`: the routines' proposals; `decide` accepts, edits or rejects one.
|
|
7
25
|
*
|
|
8
26
|
* @param {any} editor
|
|
9
27
|
* @param {ReturnType<import("./shared.js").createToolkit>} toolkit
|
|
10
28
|
*/
|
|
11
29
|
export function registerSpaces(editor, toolkit) {
|
|
12
|
-
const
|
|
13
|
-
|
|
30
|
+
const actions = createSpacesActions(toolkit)
|
|
14
31
|
editor.add({
|
|
15
32
|
name: "spaces",
|
|
16
33
|
description:
|
|
17
|
-
"
|
|
34
|
+
"See where memory lives and what flows into it: spaces, members, access, health, sources and review. current: the active space and whether this session is bound to it. list: every space you can use. members: who is in a space, with user ids. access: your role and the grants that name you. health: whether memory is reachable, what each layer holds, and whether the collector runs; use it when memory itself may be down, not to explain an ordinary recall miss. Do not inspect spaces or health to verify a successful read or write; use the answer already returned. sources: the accounts Memory collects from (mail, chat, meetings); bind one only when the person asks: it shows the signed-in account and asks the person to confirm it before anything is collected; unbind previews unless confirm is true, then stops collection and deletes that source's events. review: proposals the daily routine made; decide accepts, edits or rejects one, only when the person says (in a shared space it asks). current, list, members and access need a control plane; health, sources and review work without one. It says who can see what, never what the rules are: \"am I allowed\" is a mem_recall question. Never bind an account or decide a proposal the person did not ask for. Membership and roles are the control plane's: this tool never changes them.",
|
|
18
35
|
input: {
|
|
19
36
|
type: "object",
|
|
20
37
|
properties: {
|
|
21
38
|
action: {
|
|
22
39
|
type: "string",
|
|
23
|
-
enum: [
|
|
24
|
-
description:
|
|
40
|
+
enum: [...SPACES_ACTIONS],
|
|
41
|
+
description:
|
|
42
|
+
'Required. Read-only: current, list, members, access, health. sources and review read unless given bind, unbind or decide. Example: {"action": "health"}',
|
|
43
|
+
},
|
|
44
|
+
space: { type: "string", description: "Space id (control plane) for members, access, health, sources and review; defaults to the session's space (sources: your personal space). Never rebinds the session" },
|
|
45
|
+
bind: {
|
|
46
|
+
type: "object",
|
|
47
|
+
description: 'sources: start collecting from one account after the person confirms its owner. Example: {"action": "sources", "bind": {"source": "gmail", "account": "work"}}',
|
|
48
|
+
properties: {
|
|
49
|
+
source: { type: "string", description: "The source plugin's Code Mode namespace, such as gmail or slack" },
|
|
50
|
+
account: { type: "string", description: 'The account within it; default "default"' },
|
|
51
|
+
},
|
|
52
|
+
required: ["source"],
|
|
53
|
+
additionalProperties: false,
|
|
54
|
+
},
|
|
55
|
+
unbind: {
|
|
56
|
+
type: "object",
|
|
57
|
+
description: "sources: stop collecting from one account and delete its events; previews unless confirm is true",
|
|
58
|
+
properties: {
|
|
59
|
+
source: { type: "string", description: "The source, as sources lists it" },
|
|
60
|
+
account: { type: "string", description: 'The account; default "default"' },
|
|
61
|
+
},
|
|
62
|
+
required: ["source"],
|
|
63
|
+
additionalProperties: false,
|
|
25
64
|
},
|
|
65
|
+
confirm: { type: "boolean", description: "unbind: true deletes; omitted or false previews and changes nothing" },
|
|
66
|
+
decide: {
|
|
67
|
+
type: "object",
|
|
68
|
+
description: 'review: answer one proposal. Example: {"action": "review", "decide": {"id": "rec_...", "decision": "reject", "reason": "vendor newsletters are noise"}}',
|
|
69
|
+
properties: {
|
|
70
|
+
id: { type: "string", description: "The proposal id review listed" },
|
|
71
|
+
decision: { type: "string", enum: [...DECISIONS], description: "accept applies it; edit applies payload instead; reject drops it (a reason becomes a preference the next run reads)" },
|
|
72
|
+
reason: { type: "string", description: "Why; for a reject, the rule the routine should learn" },
|
|
73
|
+
payload: { type: "string", description: "edit: the text to apply instead of the proposal's" },
|
|
74
|
+
},
|
|
75
|
+
required: ["id", "decision"],
|
|
76
|
+
additionalProperties: false,
|
|
77
|
+
},
|
|
78
|
+
limit: { type: "integer", minimum: 1, maximum: 100, description: `review: proposals to list (default ${REVIEW_LIMIT}, at most 100)` },
|
|
26
79
|
},
|
|
27
80
|
required: ["action"],
|
|
28
81
|
additionalProperties: false,
|
|
29
82
|
},
|
|
30
83
|
options: { namespace: "mem" },
|
|
31
|
-
execute:
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
const spaceContext = await toolkit.resolveContext({
|
|
36
|
-
sessionID: context?.sessionID,
|
|
37
|
-
agent: context?.agent,
|
|
38
|
-
})
|
|
39
|
-
if (!spaceContext) return fail("the control plane returned no space context")
|
|
40
|
-
const scoped = toolkit.scopeFor(spaceContext, { sessionID: context?.sessionID, agent: context?.agent })
|
|
41
|
-
const lines = ["<space_context>"]
|
|
42
|
-
lines.push(`space: ${describeSpace(spaceContext)}`)
|
|
43
|
-
const collection = describeCollection(spaceContext)
|
|
44
|
-
if (collection) lines.push(`collection: ${collection}`)
|
|
45
|
-
if (spaceContext.role) lines.push(`role: ${spaceContext.role}`)
|
|
46
|
-
lines.push(`agent: ${scoped.agent_id}`)
|
|
47
|
-
lines.push(`scope: ${contextScopeLabel(spaceContext, scoped)}`)
|
|
48
|
-
// The active space is not always the session's space. A shared
|
|
49
|
-
// default that is not bound to this session is shown here, but
|
|
50
|
-
// recall, remember, capture, and the pinned block use the personal
|
|
51
|
-
// space. Say so, so the two answers do not look contradictory.
|
|
52
|
-
if (spaceContext.space_kind === "shared") {
|
|
53
|
-
if (toolkit.isSessionBound(spaceContext)) {
|
|
54
|
-
lines.push("session: bound to this space; recall without a space argument searches it")
|
|
55
|
-
} else {
|
|
56
|
-
const personal = spaceContext.personal_space_id ? oneLine(spaceContext.personal_space_id, 80) : "your personal space"
|
|
57
|
-
lines.push(
|
|
58
|
-
`session: not bound to this space; recall, remember, capture, and the pinned block use ${personal}. Pass space to read this one.`,
|
|
59
|
-
)
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
lines.push("</space_context>")
|
|
63
|
-
return text(lines.join("\n"))
|
|
64
|
-
}
|
|
84
|
+
execute: (input, context) => actions.run(input, context),
|
|
85
|
+
})
|
|
86
|
+
return actions
|
|
87
|
+
}
|
|
65
88
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
89
|
+
/**
|
|
90
|
+
* The spaces actions, shared by `mem_spaces` and the deprecated `mem_status`,
|
|
91
|
+
* `mem_grants` and `mem_members`.
|
|
92
|
+
*
|
|
93
|
+
* @param {ReturnType<import("./shared.js").createToolkit>} toolkit
|
|
94
|
+
*/
|
|
95
|
+
export function createSpacesActions(toolkit) {
|
|
96
|
+
const { config, control, log, text, fail, resolveSpace, describeSpace, describeCollection } = toolkit
|
|
97
|
+
const records = () => recordsOf(toolkit)
|
|
98
|
+
const noControl = (what) => text(`control plane not configured; set MEMORY_CONTROL_URL to ${what}`)
|
|
99
|
+
|
|
100
|
+
async function current(context) {
|
|
101
|
+
if (!control) return noControl("use spaces")
|
|
102
|
+
const spaceContext = await toolkit.resolveContext({ sessionID: context?.sessionID, agent: context?.agent })
|
|
103
|
+
if (!spaceContext) return fail("the control plane returned no space context")
|
|
104
|
+
const scoped = toolkit.scopeFor(spaceContext, { sessionID: context?.sessionID, agent: context?.agent })
|
|
105
|
+
const lines = ["<space_context>", `space: ${describeSpace(spaceContext)}`]
|
|
106
|
+
const collection = describeCollection(spaceContext)
|
|
107
|
+
if (collection) lines.push(`collection: ${collection}`)
|
|
108
|
+
if (spaceContext.role) lines.push(`role: ${spaceContext.role}`)
|
|
109
|
+
lines.push(`agent: ${scoped.agent_id}`)
|
|
110
|
+
lines.push(`scope: ${contextScopeLabel(spaceContext, scoped)}`)
|
|
111
|
+
// The active space is not always the session's space: a shared default
|
|
112
|
+
// that is not bound to this session is shown, but recall, remember,
|
|
113
|
+
// capture and the pinned block use the personal space. Say so.
|
|
114
|
+
if (spaceContext.space_kind === "shared") {
|
|
115
|
+
if (toolkit.isSessionBound(spaceContext)) {
|
|
116
|
+
lines.push("session: bound to this space; recall without a space argument searches it")
|
|
117
|
+
} else {
|
|
118
|
+
const personal = spaceContext.personal_space_id ? oneLine(spaceContext.personal_space_id, 80) : "your personal space"
|
|
119
|
+
lines.push(`session: not bound to this space; recall, remember, capture, and the pinned block use ${personal}. Pass space to read this one.`)
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
lines.push("</space_context>")
|
|
123
|
+
return text(lines.join("\n"))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function list() {
|
|
127
|
+
if (!control) return noControl("use spaces")
|
|
128
|
+
const spaces = await control.listSpaces({ userId: config.user })
|
|
129
|
+
if (spaces.length === 0) return text("the control plane returned no spaces for this user")
|
|
130
|
+
const lines = ["<spaces>"]
|
|
131
|
+
for (const [kind, title] of [
|
|
132
|
+
["personal", "Personal"],
|
|
133
|
+
["shared", "Shared"],
|
|
134
|
+
["unknown", "Other"],
|
|
135
|
+
]) {
|
|
136
|
+
const group = spaces.filter((space) => space.kind === kind)
|
|
137
|
+
if (group.length === 0) continue
|
|
138
|
+
lines.push(`## ${title}`)
|
|
139
|
+
for (const space of group) lines.push(`- ${space.space_id} [${space.kind}] ${oneLine(space.name || space.space_id, 120)}${space.role ? ` (${space.role})` : ""}`)
|
|
140
|
+
}
|
|
141
|
+
lines.push("</spaces>")
|
|
142
|
+
return text(lines.join("\n"))
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function members(input, context) {
|
|
146
|
+
if (!control) return noControl("read members")
|
|
147
|
+
const resolved = await resolveSpace(input, context)
|
|
148
|
+
if (resolved.error) return fail(resolved.error)
|
|
149
|
+
const spaceContext = resolved.context
|
|
150
|
+
if (!spaceContext?.space_id) return fail("the control plane returned no space context")
|
|
151
|
+
const roster = await control.listMembers({ userId: config.user, spaceId: spaceContext.space_id })
|
|
152
|
+
const lines = ["<members>", `space: ${describeSpace(spaceContext)}`]
|
|
153
|
+
if (roster.length === 0) lines.push("(no members visible to you in this space)")
|
|
154
|
+
for (const member of roster) {
|
|
155
|
+
lines.push(`- ${oneLine(member.name || member.email || member.user_id, 160)} (${oneLine(member.role || "member", 40)}) user_id=${oneLine(member.user_id, 120)}`)
|
|
156
|
+
}
|
|
157
|
+
lines.push("</members>")
|
|
158
|
+
return text(lines.join("\n"))
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function access(input, context) {
|
|
162
|
+
if (!control) return noControl("read grants")
|
|
163
|
+
const resolved = await resolveSpace(input, context)
|
|
164
|
+
if (resolved.error) return fail(resolved.error)
|
|
165
|
+
const spaceContext = resolved.context
|
|
166
|
+
if (!spaceContext?.space_id) return fail("the control plane returned no space context")
|
|
167
|
+
const grants = await control.listGrants({ userId: config.user, spaceId: spaceContext.space_id })
|
|
168
|
+
const lines = ["<access>", `space: ${describeSpace(spaceContext)}`]
|
|
169
|
+
if (spaceContext.role) lines.push(`role: ${oneLine(spaceContext.role, 40)}`)
|
|
170
|
+
if (grants.length === 0) lines.push("(no grants visible to you in this space)")
|
|
171
|
+
for (const grant of grants) {
|
|
172
|
+
const principal = [grant.principal_type, grant.principal_id].filter(Boolean).join(":")
|
|
173
|
+
const target = [grant.target_type, grant.target_id].filter(Boolean).join(":")
|
|
174
|
+
lines.push(
|
|
175
|
+
`- role=${oneLine(grant.role || "unknown", 40)} principal=${oneLine(principal || "unknown", 160)} target=${oneLine(target || "unknown", 160)} inherit=${grant.inherit ? "yes" : "no"} expires=${oneLine(grant.expires_at || "never", 80)}`,
|
|
176
|
+
)
|
|
177
|
+
}
|
|
178
|
+
lines.push("</access>")
|
|
179
|
+
return text(lines.join("\n"))
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function health(input, context) {
|
|
183
|
+
const report = await renderHealth(toolkit, input, context)
|
|
184
|
+
return report.failure ? fail(report.failure) : text(report.text)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Where a records call goes for sources (personal by default) or review (the session's space by default). */
|
|
188
|
+
async function recordsSpace(input, context, { personalDefault }) {
|
|
189
|
+
const requested = String(input?.space ?? "").trim()
|
|
190
|
+
if (!control) {
|
|
191
|
+
if (requested) return { message: "control plane not configured; set MEMORY_CONTROL_URL to select a space" }
|
|
192
|
+
return { where: { sessionID: context?.sessionID }, label: "the local scope", shared: false }
|
|
193
|
+
}
|
|
194
|
+
try {
|
|
195
|
+
let spaceContext
|
|
196
|
+
if (requested) spaceContext = await toolkit.resolveContext({ space: requested, agent: context?.agent })
|
|
197
|
+
else if (personalDefault) {
|
|
198
|
+
const resolved = await toolkit.resolvePrivateSpace({}, context)
|
|
199
|
+
if (resolved.invalid) return { message: resolved.invalid }
|
|
200
|
+
if (resolved.error) return { error: resolved.error }
|
|
201
|
+
spaceContext = resolved.context
|
|
202
|
+
} else spaceContext = await toolkit.runtime.sessionContext(context?.sessionID, context?.agent)
|
|
203
|
+
if (!spaceContext?.space_id) return { error: "the control plane returned no space context" }
|
|
204
|
+
return {
|
|
205
|
+
where: requested || personalDefault ? { space: spaceContext.space_id } : { sessionID: context?.sessionID, space: spaceContext.space_id },
|
|
206
|
+
label: describeSpace(spaceContext),
|
|
207
|
+
shared: spaceContext.space_kind === "shared",
|
|
208
|
+
spaceId: spaceContext.space_id,
|
|
209
|
+
}
|
|
210
|
+
} catch (error) {
|
|
211
|
+
return { error: errorMessage(error) }
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** A bind or unbind's source and account; `known` requires a source in the registry (src/sources.js). */
|
|
216
|
+
function bindingOf(value, { known = false } = {}) {
|
|
217
|
+
const source = String(value?.source ?? "").trim()
|
|
218
|
+
const asked = String(value?.account ?? "").trim()
|
|
219
|
+
const account = asked || DEFAULT_ACCOUNT
|
|
220
|
+
if (!isSourceName(source)) return { error: `"${oneLine(source || "(none)", 60)}" is not a source name: one of ${knownSources().join(", ")}.` }
|
|
221
|
+
if (known && !sourceEntry(source)) return { error: `"${oneLine(source, 60)}" is not a source Memory knows: one of ${knownSources().join(", ")}.` }
|
|
222
|
+
if (!isAccountName(account)) return { error: `"${oneLine(account, 60)}" is not an account name.` }
|
|
223
|
+
return { source, account, asked: Boolean(asked) }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const describeBinding = (row) => {
|
|
227
|
+
const owner = row.owner_label || row.owner_id ? `${oneLine(row.owner_label || row.owner_id, 120)}${row.owner_id && row.owner_label && row.owner_label !== row.owner_id ? ` (${oneLine(row.owner_id, 120)})` : ""}` : "owner unknown"
|
|
228
|
+
const state = [row.status || "unknown", row.enabled === true || row.enabled === 1 ? "enabled" : "disabled"].join(", ")
|
|
229
|
+
const cursor = row.cursor_at ? `, last collected ${oneLine(row.cursor_at, 40)}` : ""
|
|
230
|
+
return `- ${oneLine(row.source, 64)}:${oneLine(row.account || DEFAULT_ACCOUNT, 128)} ${owner}: ${state}${cursor}`
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function listSources(where) {
|
|
234
|
+
const answer = await records().call("sources.list", {}, where)
|
|
235
|
+
return Array.isArray(answer?.sources) ? answer.sources.filter(isPlainObject) : []
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Keep a host schedule (where there is one) in step with the sources; one line on how collection runs. */
|
|
239
|
+
async function syncCollector(rows) {
|
|
240
|
+
if (!toolkit.collector) return ""
|
|
241
|
+
const result = await toolkit.collector.sync(rows)
|
|
242
|
+
if (result.action === "failed") return `Collection: the memory-collect schedule could not be updated (${oneLine(result.error, 200)}).`
|
|
243
|
+
if (result.mode === "schedule" && result.action === "removed") return "Collection: no source is enabled, so the memory-collect schedule was removed."
|
|
244
|
+
if (result.mode === "schedule" && (result.action === "created" || result.action === "rewritten")) {
|
|
245
|
+
return `Collection: the host's memory-collect schedule was ${result.action}; it runs every 30 minutes for ${result.sources} source(s).`
|
|
246
|
+
}
|
|
247
|
+
if (result.sources === 0) return ""
|
|
248
|
+
const every = Number(toolkit.config?.collectEveryMinutes ?? toolkit.runtime?.config?.collectEveryMinutes) || 30
|
|
249
|
+
const on = (toolkit.config ?? toolkit.runtime?.config)?.collect !== false
|
|
250
|
+
return on
|
|
251
|
+
? `Collection: Memory collects every ${every} minutes while OpenCode runs (one process per machine); /mem-collect collects now.`
|
|
252
|
+
: "Collection: the collection timer is off (collect: false); /mem-collect collects now."
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* The signed-in account a source reports, with the source and account its
|
|
257
|
+
* own answer names (contract §4.5): through the host's RPC first; else the
|
|
258
|
+
* owner the collector's last refused delivery reported; else a binding the
|
|
259
|
+
* records service holds. An answer that breaks the source contract is
|
|
260
|
+
* refused, never worked around.
|
|
261
|
+
*/
|
|
262
|
+
async function ownerOf(binding, rows, context) {
|
|
263
|
+
const lister = toolkit.collector?.lister
|
|
264
|
+
const notes = []
|
|
265
|
+
if (lister) {
|
|
266
|
+
try {
|
|
267
|
+
const session = await toolkit.collector.rpcSession(context?.sessionID)
|
|
268
|
+
const answer = await lister(binding.source, { limit: 1, ...(binding.asked ? { account: binding.account } : {}) }, session)
|
|
269
|
+
if (answer?.owner?.id) return { owner: answer.owner, source: answer.source, account: answer.account, from: "the source's events_list" }
|
|
270
|
+
notes.push("its events_list named no owner")
|
|
85
271
|
} catch (error) {
|
|
86
|
-
|
|
87
|
-
|
|
272
|
+
if (error?.code === "source_contract") return { refused: errorMessage(error) }
|
|
273
|
+
notes.push(`its events_list could not be reached through the host (${oneLine(errorMessage(error), 160)})`)
|
|
88
274
|
}
|
|
89
|
-
}
|
|
90
|
-
|
|
275
|
+
}
|
|
276
|
+
const reported = toolkit.collector?.ownerFor(binding.source, binding.asked ? binding.account : "")
|
|
277
|
+
if (reported?.id) return { owner: reported, source: binding.source, account: reported.account || binding.account, from: "the collector's last refused delivery" }
|
|
278
|
+
const pending = rows.find((row) => row.source === binding.source && (!binding.asked || (row.account || DEFAULT_ACCOUNT) === binding.account) && row.owner_id)
|
|
279
|
+
if (pending) return { owner: { id: pending.owner_id, label: pending.owner_label || pending.owner_id }, source: binding.source, account: pending.account || DEFAULT_ACCOUNT, from: "the binding the records service holds" }
|
|
280
|
+
return { notes }
|
|
281
|
+
}
|
|
91
282
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
if (
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
if (
|
|
111
|
-
|
|
112
|
-
|
|
283
|
+
async function sources(input, context) {
|
|
284
|
+
if (!records()) return text(RECORDS_MISSING)
|
|
285
|
+
if (input?.bind && input?.unbind) return text("pass bind or unbind, not both.")
|
|
286
|
+
const space = await recordsSpace(input, context, { personalDefault: true })
|
|
287
|
+
if (space.message) return text(space.message)
|
|
288
|
+
if (space.error) return fail(space.error)
|
|
289
|
+
let rows
|
|
290
|
+
try {
|
|
291
|
+
rows = await listSources(space.where)
|
|
292
|
+
} catch (error) {
|
|
293
|
+
return fail(recordsFailure(error))
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
if (input?.bind) {
|
|
297
|
+
const asked = bindingOf(input.bind, { known: true })
|
|
298
|
+
if (asked.error) return text(`not bound: ${asked.error}`)
|
|
299
|
+
const known = await ownerOf(asked, rows, context)
|
|
300
|
+
if (known.refused) return text(`not bound: ${known.refused}`)
|
|
301
|
+
if (!known.owner) {
|
|
302
|
+
const why = known.notes?.length ? ` (${known.notes.join("; ")})` : ""
|
|
303
|
+
return text(
|
|
304
|
+
`not bound: Memory could not learn which account ${asked.source}${asked.asked ? `:${asked.account}` : ""} is signed in to${why}. Sign in to that source in its own plugin, then try again; Memory shows the account and asks the person before anything is collected.`,
|
|
305
|
+
)
|
|
306
|
+
}
|
|
307
|
+
const owner = { id: oneLine(known.owner.id, 300), label: oneLine(known.owner.label ?? known.owner.email ?? known.owner.id, 300) }
|
|
308
|
+
// The binding is the one the source's own answer names (§4.5).
|
|
309
|
+
const binding = { source: known.source, account: known.account }
|
|
113
310
|
try {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
311
|
+
await toolkit.assert({
|
|
312
|
+
sessionID: context?.sessionID,
|
|
313
|
+
agent: context?.agent,
|
|
314
|
+
source: { type: "tool", messageID: context?.messageID, id: context?.id },
|
|
315
|
+
action: "sources.bind",
|
|
316
|
+
resources: [`${binding.source}:${binding.account}`],
|
|
317
|
+
save: [],
|
|
318
|
+
metadata: { space: space.spaceId ?? "local", source: binding.source, account: binding.account, owner: `${owner.label} (${owner.id})`, from: known.from },
|
|
117
319
|
})
|
|
118
|
-
const lines = ["<grants>", `space: ${describeSpace(spaceContext)}`]
|
|
119
|
-
if (spaceContext.role) lines.push(`role: ${oneLine(spaceContext.role, 40)}`)
|
|
120
|
-
if (grants.length === 0) lines.push("(no grants visible to you in this space)")
|
|
121
|
-
for (const grant of grants) {
|
|
122
|
-
const principal = [grant.principal_type, grant.principal_id].filter(Boolean).join(":")
|
|
123
|
-
const target = [grant.target_type, grant.target_id].filter(Boolean).join(":")
|
|
124
|
-
lines.push(
|
|
125
|
-
`- role=${oneLine(grant.role || "unknown", 40)} principal=${oneLine(principal || "unknown", 160)} target=${oneLine(target || "unknown", 160)} inherit=${grant.inherit ? "yes" : "no"} expires=${oneLine(grant.expires_at || "never", 80)}`,
|
|
126
|
-
)
|
|
127
|
-
}
|
|
128
|
-
lines.push("</grants>")
|
|
129
|
-
return text(lines.join("\n"))
|
|
130
320
|
} catch (error) {
|
|
131
|
-
|
|
132
|
-
return fail(errorMessage(error))
|
|
321
|
+
return text(`not bound (approval): ${errorMessage(error)}`)
|
|
133
322
|
}
|
|
134
|
-
|
|
135
|
-
|
|
323
|
+
try {
|
|
324
|
+
await records().call("sources.bind", { source: binding.source, account: binding.account, owner, enabled: true }, space.where)
|
|
325
|
+
} catch (error) {
|
|
326
|
+
log.warn("sources bind failed", error)
|
|
327
|
+
return fail(`not bound: ${recordsFailure(error)}`)
|
|
328
|
+
}
|
|
329
|
+
let after = rows
|
|
330
|
+
try {
|
|
331
|
+
after = await listSources(space.where)
|
|
332
|
+
} catch {
|
|
333
|
+
/* the schedule is brought in step at the next list */
|
|
334
|
+
}
|
|
335
|
+
const sync = await syncCollector(after)
|
|
336
|
+
log.info("sources bind", { source: binding.source })
|
|
337
|
+
return text(
|
|
338
|
+
`bound ${binding.source}:${binding.account} in ${space.label} to ${owner.label} (${owner.id}), as the person confirmed. Memory accepts its events only while that account is the one signed in. Raw events stay private to this space for 30 days; the daily routine turns them into journal pages and proposals for review.${sync ? ` ${sync}` : ""}`,
|
|
339
|
+
)
|
|
340
|
+
}
|
|
136
341
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
additionalProperties: false,
|
|
149
|
-
},
|
|
150
|
-
options: { namespace: "mem" },
|
|
151
|
-
execute: async (input, context) => {
|
|
152
|
-
if (input?.action !== "list") return text('unsupported action: use action="list"')
|
|
153
|
-
if (!control) return text("control plane not configured; set MEMORY_CONTROL_URL to read members")
|
|
154
|
-
const resolved = await resolveSpace(input, context)
|
|
155
|
-
if (resolved.error) return fail(resolved.error)
|
|
156
|
-
const spaceContext = resolved.context
|
|
157
|
-
if (!spaceContext?.space_id) return fail("the control plane returned no space context")
|
|
342
|
+
if (input?.unbind) {
|
|
343
|
+
const binding = bindingOf(input.unbind)
|
|
344
|
+
if (binding.error) return text(`not unbound: ${binding.error}`)
|
|
345
|
+
const row = rows.find((entry) => entry.source === binding.source && (entry.account || DEFAULT_ACCOUNT) === binding.account)
|
|
346
|
+
if (!row) return text(`not unbound: ${binding.source}:${binding.account} is not a source in ${space.label}.`)
|
|
347
|
+
if (input?.confirm !== true) {
|
|
348
|
+
return text(
|
|
349
|
+
`preview, nothing changed: unbinding ${binding.source}:${binding.account} (${oneLine(row.owner_label || row.owner_id || "owner unknown", 120)}) stops its collection and deletes every event collected from it in ${space.label}. Journal pages and memories already made from them stay. Call again with "confirm": true to unbind.`,
|
|
350
|
+
)
|
|
351
|
+
}
|
|
352
|
+
let answer
|
|
158
353
|
try {
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
})
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
354
|
+
answer = await records().call("sources.unbind", { source: binding.source, account: binding.account }, space.where)
|
|
355
|
+
} catch (error) {
|
|
356
|
+
log.warn("sources unbind failed", error)
|
|
357
|
+
return fail(`not unbound: ${recordsFailure(error)}`)
|
|
358
|
+
}
|
|
359
|
+
let after = rows.filter((entry) => entry !== row)
|
|
360
|
+
try {
|
|
361
|
+
after = await listSources(space.where)
|
|
362
|
+
} catch {
|
|
363
|
+
/* as above */
|
|
364
|
+
}
|
|
365
|
+
const sync = await syncCollector(after)
|
|
366
|
+
return text(
|
|
367
|
+
`unbound ${binding.source}:${binding.account} in ${space.label}: collection stopped and ${Number(answer?.deleted_events) || 0} event(s) were deleted.${sync ? ` ${sync}` : ""}`,
|
|
368
|
+
)
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
const sync = await syncCollector(rows)
|
|
372
|
+
const lines = ["<sources>", `space: ${space.label}`]
|
|
373
|
+
if (rows.length === 0) lines.push('(no sources: Memory collects nothing. When the person asks, bind one with {"action": "sources", "bind": {"source": "<namespace>"}}.)')
|
|
374
|
+
for (const row of rows) lines.push(describeBinding(row))
|
|
375
|
+
lines.push("</sources>")
|
|
376
|
+
if (toolkit.collector) lines.push(toolkit.collector.describe())
|
|
377
|
+
else if (sync) lines.push(sync)
|
|
378
|
+
return text(lines.join("\n"))
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const describeProposal = (proposal) => {
|
|
382
|
+
const fields = isPlainObject(proposal?.fields) ? proposal.fields : {}
|
|
383
|
+
const target = fields.target_path || fields.target_id || ""
|
|
384
|
+
const evidence = Array.isArray(fields.evidence) ? fields.evidence.length : 0
|
|
385
|
+
const what = oneLine(proposal?.title || (typeof fields.payload === "string" ? fields.payload : proposal?.body) || "", 200)
|
|
386
|
+
return `- ${oneLine(proposal?.id ?? "?", 40)} ${oneLine(fields.action || proposal?.type || "?", 30)}${target ? ` ${oneLine(target, 120)}` : ""}: ${what}${fields.reason ? ` (why: ${oneLine(fields.reason, 160)})` : ""}${evidence ? ` [${evidence} cited]` : ""}${fields.expires ? `, expires ${oneLine(fields.expires, 20)}` : ""}`
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
async function review(input, context) {
|
|
390
|
+
if (!records()) return text(RECORDS_MISSING)
|
|
391
|
+
const space = await recordsSpace(input, context, { personalDefault: false })
|
|
392
|
+
if (space.message) return text(space.message)
|
|
393
|
+
if (space.error) return fail(space.error)
|
|
394
|
+
|
|
395
|
+
if (input?.decide) {
|
|
396
|
+
const id = String(input.decide.id ?? "").trim()
|
|
397
|
+
const decision = String(input.decide.decision ?? "").trim()
|
|
398
|
+
if (!id) return text("not decided: decide needs the proposal id.")
|
|
399
|
+
if (!DECISIONS.includes(decision)) return text(`not decided: decision is accept, edit or reject, not ${oneLine(decision || "(none)", 40)}.`)
|
|
400
|
+
const payload = String(input.decide.payload ?? "").trim()
|
|
401
|
+
if (decision === "edit" && !payload) return text("not decided: an edit needs payload, the text to apply instead.")
|
|
402
|
+
const reason = String(input.decide.reason ?? "").trim()
|
|
403
|
+
// A decision in a shared space changes what every member reads, so it
|
|
404
|
+
// asks, as any team-visible revise does.
|
|
405
|
+
if (space.shared) {
|
|
406
|
+
try {
|
|
407
|
+
await toolkit.assert({
|
|
408
|
+
sessionID: context?.sessionID,
|
|
409
|
+
agent: context?.agent,
|
|
410
|
+
source: { type: "tool", messageID: context?.messageID, id: context?.id },
|
|
411
|
+
action: "memory.revise",
|
|
412
|
+
resources: [id],
|
|
413
|
+
save: [],
|
|
414
|
+
metadata: { space: space.spaceId, proposal: id, decision, ...(reason ? { reason: oneLine(reason, 300) } : {}), ...(payload ? { payload: oneLine(payload, 300) } : {}) },
|
|
415
|
+
})
|
|
416
|
+
} catch (error) {
|
|
417
|
+
return text(`not decided (approval): ${errorMessage(error)}`)
|
|
170
418
|
}
|
|
171
|
-
|
|
172
|
-
|
|
419
|
+
}
|
|
420
|
+
let answer
|
|
421
|
+
try {
|
|
422
|
+
answer = await records().call("review.decide", { id, decision, ...(payload ? { payload } : {}), ...(reason ? { reason } : {}) }, space.where)
|
|
173
423
|
} catch (error) {
|
|
174
|
-
log.warn("
|
|
175
|
-
return fail(
|
|
424
|
+
log.warn("review decide failed", error)
|
|
425
|
+
return fail(`not decided: ${recordsFailure(error)}`)
|
|
176
426
|
}
|
|
177
|
-
|
|
178
|
-
|
|
427
|
+
const applied = answer?.applied
|
|
428
|
+
const appliedText = isPlainObject(applied) && applied.id ? ` Applied as ${oneLine(applied.id, 40)}${applied.path ? ` (${oneLine(applied.path, 120)})` : ""}.` : ""
|
|
429
|
+
const learned = decision === "reject" && reason ? " The reason was kept as a preference the next routine run reads." : ""
|
|
430
|
+
return text(`${decision === "reject" ? "rejected" : decision === "edit" ? "edited and applied" : "accepted"} proposal ${oneLine(id, 40)} in ${space.label}.${appliedText}${learned}`)
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
const limit = Math.min(100, Math.max(1, Number.parseInt(input?.limit, 10) || REVIEW_LIMIT))
|
|
434
|
+
let proposals
|
|
435
|
+
try {
|
|
436
|
+
proposals = (await records().call("review.list", { limit }, space.where))?.proposals ?? []
|
|
437
|
+
} catch (error) {
|
|
438
|
+
return fail(recordsFailure(error))
|
|
439
|
+
}
|
|
440
|
+
const lines = ["<review>", `space: ${space.label}`]
|
|
441
|
+
if (proposals.length === 0) lines.push("(nothing waits for review)")
|
|
442
|
+
for (const proposal of proposals) lines.push(describeProposal(proposal))
|
|
443
|
+
lines.push("</review>")
|
|
444
|
+
if (proposals.length > 0) lines.push('Proposals are the routine\'s suggestions, not facts: decide each with {"action": "review", "decide": {"id": "...", "decision": "accept" | "edit" | "reject"}} when the person says.')
|
|
445
|
+
return text(lines.join("\n"))
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
async function run(input, context) {
|
|
449
|
+
// No action lists, as the tool did before 0.9 (old calls passed none).
|
|
450
|
+
const action = String(input?.action ?? "").trim() || "list"
|
|
451
|
+
if (!SPACES_ACTIONS.includes(action)) return text(`unknown action ${oneLine(action || "(none)", 40)}: use ${SPACES_ACTIONS.join(", ")}.`)
|
|
452
|
+
try {
|
|
453
|
+
if (action === "current") return await current(context)
|
|
454
|
+
if (action === "list") return await list()
|
|
455
|
+
if (action === "members") return await members(input, context)
|
|
456
|
+
if (action === "access") return await access(input, context)
|
|
457
|
+
if (action === "health") return await health(input, context)
|
|
458
|
+
if (action === "sources") return await sources(input, context)
|
|
459
|
+
return await review(input, context)
|
|
460
|
+
} catch (error) {
|
|
461
|
+
log.warn(`spaces ${action} failed`, error)
|
|
462
|
+
return fail(errorMessage(error))
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
return { run, current, list, members, access, health, sources, review }
|
|
179
467
|
}
|