@joe-broadhead/opencode-mem 0.8.5 → 0.9.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/CHANGELOG.md +429 -0
- package/README.md +114 -61
- package/docs/agent-protocol.md +67 -177
- package/package.json +1351 -98
- package/skills/mem.pages/SKILL.md +143 -0
- package/skills/mem.sharing/SKILL.md +82 -0
- package/skills/mem.sources/SKILL.md +93 -0
- package/skills/mem.usage/SKILL.md +118 -492
- package/src/backend/records.js +285 -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 +12 -1
- package/src/curation.js +1 -1
- package/src/permissions.js +18 -2
- package/src/protocol.js +29 -20
- package/src/recall.js +104 -27
- package/src/records-store.js +280 -120
- 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 +163 -0
- package/src/tools/commitments.js +12 -9
- package/src/tools/index.js +88 -19
- package/src/tools/ingest.js +277 -0
- package/src/tools/knowledge.js +6 -1
- package/src/tools/memory.js +640 -210
- package/src/tools/page.js +411 -0
- package/src/tools/recall.js +363 -112
- package/src/tools/records-kit.js +142 -0
- package/src/tools/share.js +1012 -0
- package/src/tools/shared.js +8 -1
- package/src/tools/spaces.js +431 -143
- package/src/tools/status.js +87 -58
- package/src/tools/wiki.js +2 -2
- package/src/views/contracts.js +273 -3
- package/src/views/records-reads.js +675 -0
- package/src/views/rpc.js +17 -100
- 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/review.html +406 -0
- package/views/today.html +309 -0
|
@@ -0,0 +1,1012 @@
|
|
|
1
|
+
import { writeRefusal } from "../curation.js"
|
|
2
|
+
import { REMEMBER_WRAPPER } from "../copies.js"
|
|
3
|
+
import { errorMessage, isPlainObject, oneLine, redactSecrets } from "../util.js"
|
|
4
|
+
import { isCoded } from "../errors.js"
|
|
5
|
+
import { canWriteShared } from "./shared.js"
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* `mem_share` (docs/design/memory-v1-contracts.md §4.1; memory-tools-v1.md §10):
|
|
9
|
+
*
|
|
10
|
+
* - `list`: the grants on the space's shared pages and folders;
|
|
11
|
+
* - `grant`: register a page or folder as a control resource of kind
|
|
12
|
+
* `wiki_page` (`upstream_id` `records:<path>` or `records:<prefix>/`), then
|
|
13
|
+
* grant it to a user (email or id), group or org role, as viewer or editor,
|
|
14
|
+
* with an optional expiry;
|
|
15
|
+
* - `revoke`: delete a grant, delete copies, or (a path alone) unshare a page
|
|
16
|
+
* or folder entirely, then read back;
|
|
17
|
+
* - `transfer`: give a page or folder to another person (control, then the
|
|
18
|
+
* records' `owner`);
|
|
19
|
+
* - `copy`: private memories into a shared space as new records with
|
|
20
|
+
* `fields.copied_from`, one record per memory.
|
|
21
|
+
*
|
|
22
|
+
* Every call that changes something asks: `share.grant`, `share.revoke`,
|
|
23
|
+
* `share.transfer`, or `memory.promote` for a copy (the plugin's default rules
|
|
24
|
+
* make each ask in plain OpenCode; `jelly.asks` makes Jelly ask). The control
|
|
25
|
+
* plane and the records service decide access; the plugin only asks, calls,
|
|
26
|
+
* and reports what they answered.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** The records client (`createRecordsClient(...).call(method, body, { sessionID, space })`), wherever the runtime keeps it. */
|
|
30
|
+
export function recordsOf(toolkit) {
|
|
31
|
+
const candidates = [toolkit?.recordsClient, toolkit?.runtime?.recordsClient, toolkit?.records, toolkit?.runtime?.records]
|
|
32
|
+
return candidates.find((candidate) => typeof candidate?.call === "function") ?? null
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const RECORDS_MISSING =
|
|
36
|
+
"RECORDS_UNAVAILABLE: this plugin build has no records client, so records, pages, sources and review are not reachable. Next step: update opencode-mem, or ask the Memory server's operator whether the cell has a records service."
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* True when the server has no records service: the gateway's 503
|
|
40
|
+
* `records_unavailable` (a cell without `records_url`, or one whose records
|
|
41
|
+
* service is down), whether it arrives as a RecordsError or a plain error.
|
|
42
|
+
*/
|
|
43
|
+
export function recordsServiceMissing(error) {
|
|
44
|
+
return String(error?.code ?? error?.error?.code ?? "") === "records_unavailable"
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* What a share answers when the server has no records service (lane PLUG-A's
|
|
49
|
+
* finding): one plain sentence that names what sharing needs, not a raw code.
|
|
50
|
+
*
|
|
51
|
+
* @param {"copy" | "revoke" | "grant" | "transfer"} what
|
|
52
|
+
*/
|
|
53
|
+
export function sharingNeedsRecords(what) {
|
|
54
|
+
const doing = {
|
|
55
|
+
copy: "copying memories into a shared space",
|
|
56
|
+
revoke: "revoking copies",
|
|
57
|
+
grant: "sharing a page or folder",
|
|
58
|
+
transfer: "transferring a page or folder",
|
|
59
|
+
}[what]
|
|
60
|
+
const verb = { copy: "not copied", revoke: "not revoked", grant: "not granted", transfer: "not transferred" }[what]
|
|
61
|
+
return `${verb}: ${doing} needs the records service on this Memory server, and it isn't enabled there (503 records_unavailable). Nothing changed. Next step: tell the person; the Memory server's operator enables it (the cell's records_url). Until then your memories stay private.`
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A records service failure as one line: its code, what happened, and the next step it gave. */
|
|
65
|
+
export function recordsFailure(error) {
|
|
66
|
+
const message = errorMessage(error)
|
|
67
|
+
if (isCoded(message)) return message
|
|
68
|
+
const code = String(error?.code ?? error?.error?.code ?? "").trim()
|
|
69
|
+
const next = String(error?.next ?? error?.error?.next ?? "").trim()
|
|
70
|
+
const status = Number(error?.status)
|
|
71
|
+
const label = code ? code.toUpperCase() : status ? `RECORDS_${status}` : "RECORDS_ERROR"
|
|
72
|
+
return `${label}: ${oneLine(message, 300)}${next ? ` Next step: ${oneLine(next, 300)}` : ""}`
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A page path, as the records service accepts it (contract §2.3). */
|
|
76
|
+
const PAGE_PATH = /^[a-z0-9][a-z0-9-]{0,63}(\/[a-z0-9][a-z0-9-]{0,63}){0,3}$/
|
|
77
|
+
/** A folder: a page path's prefix with a trailing slash. */
|
|
78
|
+
const FOLDER_PATH = /^[a-z0-9][a-z0-9-]{0,63}(\/[a-z0-9][a-z0-9-]{0,63}){0,2}\/$/
|
|
79
|
+
const GRANT_ROLES = Object.freeze(["viewer", "editor"])
|
|
80
|
+
const RECORD_ID = /^rec_[0-9A-HJKMNP-TV-Z]{26}$/
|
|
81
|
+
const LEGACY_ID = /^(m_|msg[-_])/
|
|
82
|
+
const MAX_COPY_IDS = 20
|
|
83
|
+
const MAX_COPY_CHARS = 8_000
|
|
84
|
+
/** Records whose owner a folder transfer changes at most. */
|
|
85
|
+
const MAX_TRANSFER_RECORDS = 1_000
|
|
86
|
+
/** The legacy copy scan: newest rows per layer and agent (as mem_forget). */
|
|
87
|
+
const SCAN_PAGE = 100
|
|
88
|
+
const SCAN_PAGES = 3
|
|
89
|
+
/** 0.8.x shares (mem_promote): one wiki per share, its SHARE.md first line. */
|
|
90
|
+
const LEGACY_SHARE_FILE = "SHARE.md"
|
|
91
|
+
const LEGACY_SHARE_MARKER = "<!-- opencode-mem:share v1 -->"
|
|
92
|
+
|
|
93
|
+
export const SHARE_ACTIONS = Object.freeze(["list", "grant", "revoke", "transfer", "copy"])
|
|
94
|
+
/** The share actions that change something; each asks. */
|
|
95
|
+
export const SHARE_WRITE_ACTIONS = Object.freeze(["grant", "revoke", "transfer", "copy"])
|
|
96
|
+
|
|
97
|
+
/** `{ kind: "page" | "folder", path }` for a page or folder path, or `{ error }`. */
|
|
98
|
+
export function readSharePath(value) {
|
|
99
|
+
const path = String(value ?? "").trim()
|
|
100
|
+
if (!path) return { error: 'path is required: a page path such as "projects/harbour", or a folder ending in "/" such as "projects/".' }
|
|
101
|
+
if (PAGE_PATH.test(path)) return { kind: "page", path }
|
|
102
|
+
if (FOLDER_PATH.test(path)) return { kind: "folder", path }
|
|
103
|
+
return {
|
|
104
|
+
error: `"${oneLine(path, 120)}" is not a page or folder path: lowercase words joined by "-", up to four segments ("projects/harbour"); a folder ends in "/" ("projects/").`,
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The control resource's upstream id for a page or folder (contract §3). */
|
|
109
|
+
export function upstreamIdFor(target) {
|
|
110
|
+
return `records:${target.path}`
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Who a grant names: `user:<id>`, `group:<id>`, `org_role:<id>` (or `role:`),
|
|
115
|
+
* an email (looked up among the members of the spaces you can see), or a bare
|
|
116
|
+
* user id.
|
|
117
|
+
*/
|
|
118
|
+
export function readPrincipal(value) {
|
|
119
|
+
const raw = String(value ?? "").trim()
|
|
120
|
+
if (!raw) return { error: "to is required: an email, a user id, group:<id>, or org_role:<id>." }
|
|
121
|
+
const prefixed = raw.match(/^(user|group|org_role|role):(.*)$/)
|
|
122
|
+
if (prefixed) {
|
|
123
|
+
const id = prefixed[2].trim()
|
|
124
|
+
if (!id) return { error: `to "${oneLine(raw, 120)}" names no id after the colon.` }
|
|
125
|
+
return { type: prefixed[1] === "role" ? "org_role" : prefixed[1], id }
|
|
126
|
+
}
|
|
127
|
+
if (raw.includes("@")) return { type: "user", email: raw.toLowerCase() }
|
|
128
|
+
return { type: "user", id: raw }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** An expiry as control takes it: an ISO date-time in the future. A bare date means the end of that day (UTC). */
|
|
132
|
+
export function readExpiry(value, now = Date.now()) {
|
|
133
|
+
const raw = String(value ?? "").trim()
|
|
134
|
+
if (!raw) return { expires: undefined }
|
|
135
|
+
const iso = /^\d{4}-\d{2}-\d{2}$/.test(raw) ? `${raw}T23:59:59Z` : raw
|
|
136
|
+
const at = Date.parse(iso)
|
|
137
|
+
if (!/^\d{4}-\d{2}-\d{2}/.test(raw) || !Number.isFinite(at)) {
|
|
138
|
+
return { error: `expires "${oneLine(raw, 60)}" is not a date: use YYYY-MM-DD or an ISO date-time with an offset.` }
|
|
139
|
+
}
|
|
140
|
+
if (at <= now) return { error: `expires ${oneLine(raw, 60)} is not in the future.` }
|
|
141
|
+
return { expires: new Date(at).toISOString() }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* @param {any} editor
|
|
146
|
+
* @param {ReturnType<import("./shared.js").createToolkit>} toolkit
|
|
147
|
+
*/
|
|
148
|
+
export function registerShare(editor, toolkit) {
|
|
149
|
+
const actions = createShareActions(toolkit)
|
|
150
|
+
editor.add({
|
|
151
|
+
name: "share",
|
|
152
|
+
description:
|
|
153
|
+
"Only when the person asks: grant a page or folder to others, or copy private memories into a shared space. Before deciding whether sharing is allowed, recall the relevant recorded rule; do not decide from a default. grant: give a user (email or id), group (group:<id>) or org role (org_role:<id>) viewer or editor access to a page or folder (a path ending in \"/\"), with an optional expiry; the page stays where it is, its owner keeps it, and a folder grant covers pages added later. copy: copy private memories (rec_ ids) into a shared space as new records that name their source; later edits to the originals do not reach the copies. revoke: a grant_id, the ids of copies, or a path alone to unshare that page or folder entirely; then reads back, and cannot take back what someone already read. transfer: give a page or folder to another person (they must already be able to edit it). list: the space's shared pages and folders, and who each is shared with. Every change asks the person first; each answer gives the grant or copy ids and the call that revokes them. Never share anything the person has not seen and approved. Sharing needs the records service on the Memory server: without it the answer says so and nothing changes.",
|
|
154
|
+
input: {
|
|
155
|
+
type: "object",
|
|
156
|
+
properties: {
|
|
157
|
+
action: {
|
|
158
|
+
type: "string",
|
|
159
|
+
enum: [...SHARE_ACTIONS],
|
|
160
|
+
description:
|
|
161
|
+
'Required. Read-only: list. Writes (each asks): grant (path, to, role), revoke (grant_id; ids of copies; or path alone to unshare), transfer (path, to), copy (ids, rationale). Example: {"action": "grant", "path": "projects/harbour", "to": "ama@example.com", "role": "viewer"}',
|
|
162
|
+
},
|
|
163
|
+
path: {
|
|
164
|
+
type: "string",
|
|
165
|
+
description: 'A page path ("projects/harbour") or a folder ending in "/" ("projects/"): for grant and transfer; for revoke alone, unshares it entirely; narrows list and a grant_id revoke',
|
|
166
|
+
},
|
|
167
|
+
ids: {
|
|
168
|
+
type: "array",
|
|
169
|
+
items: { type: "string" },
|
|
170
|
+
description: "copy: your private memory ids (rec_…, or m_…/msg-… from before 0.9), at most 20. revoke: the ids of copies a copy returned",
|
|
171
|
+
},
|
|
172
|
+
to: {
|
|
173
|
+
type: "string",
|
|
174
|
+
description: "grant: an email, a user id, group:<id> or org_role:<id>. transfer: the new owner's email or user id",
|
|
175
|
+
},
|
|
176
|
+
role: { type: "string", enum: [...GRANT_ROLES], description: "grant: viewer (default) or editor" },
|
|
177
|
+
expires: { type: "string", description: "grant: when access ends, YYYY-MM-DD (end of that day, UTC) or an ISO date-time; omit for no end" },
|
|
178
|
+
space: {
|
|
179
|
+
type: "string",
|
|
180
|
+
description:
|
|
181
|
+
"The space the page or the copies are in (control plane). Defaults to the session's space; copy needs a shared space, passed here or bound to the session. Applies to this call only",
|
|
182
|
+
},
|
|
183
|
+
rationale: { type: "string", description: "copy: why the shared space should see these; required, recorded on each copy" },
|
|
184
|
+
grant_id: { type: "string", description: "revoke: the grant id grant or list returned" },
|
|
185
|
+
},
|
|
186
|
+
required: ["action"],
|
|
187
|
+
additionalProperties: false,
|
|
188
|
+
},
|
|
189
|
+
options: { namespace: "mem" },
|
|
190
|
+
execute: (input, context) => actions.run(input, context),
|
|
191
|
+
})
|
|
192
|
+
return actions
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The share actions, shared by `mem_share` and the deprecated `mem_promote`.
|
|
197
|
+
*
|
|
198
|
+
* @param {ReturnType<import("./shared.js").createToolkit>} toolkit
|
|
199
|
+
*/
|
|
200
|
+
export function createShareActions(toolkit) {
|
|
201
|
+
const { control, text, fail, log } = toolkit
|
|
202
|
+
const config = toolkit.config ?? toolkit.runtime?.config ?? {}
|
|
203
|
+
|
|
204
|
+
const userOf = (spaceContext) => spaceContext?.user_id || config.user
|
|
205
|
+
const records = () => recordsOf(toolkit)
|
|
206
|
+
const callRecords = (method, body, where) => records().call(method, body, where)
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The space a page or folder is in, and where a records call goes: an
|
|
210
|
+
* explicit space applies to this call only (no session, so nothing
|
|
211
|
+
* rebinds); otherwise the session's space (a bound shared space, else the
|
|
212
|
+
* personal one).
|
|
213
|
+
*/
|
|
214
|
+
async function pageSpace(input, context) {
|
|
215
|
+
const requested = String(input?.space ?? "").trim()
|
|
216
|
+
if (!control) {
|
|
217
|
+
if (requested) return { message: "control plane not configured; set MEMORY_CONTROL_URL to select a space" }
|
|
218
|
+
return { message: "sharing needs the control plane (MEMORY_CONTROL_URL): in local mode there is one scope and no one to share with." }
|
|
219
|
+
}
|
|
220
|
+
try {
|
|
221
|
+
const spaceContext = requested
|
|
222
|
+
? await toolkit.resolveContext({ space: requested, agent: context?.agent })
|
|
223
|
+
: await toolkit.runtime.sessionContext(context?.sessionID, context?.agent)
|
|
224
|
+
if (!spaceContext?.space_id) return { error: "the control plane returned no space context" }
|
|
225
|
+
return { spaceContext, where: requested ? { space: spaceContext.space_id } : { sessionID: context?.sessionID, space: spaceContext.space_id } }
|
|
226
|
+
} catch (error) {
|
|
227
|
+
return { error: errorMessage(error) }
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** The shared space copies go to: passed, or bound to the session; editor access or more. */
|
|
232
|
+
async function copyTarget(input, context) {
|
|
233
|
+
const requested = String(input?.space ?? "").trim()
|
|
234
|
+
if (!control) {
|
|
235
|
+
if (requested) return { message: "control plane not configured; set MEMORY_CONTROL_URL to select a space" }
|
|
236
|
+
return { message: "copy needs the control plane (MEMORY_CONTROL_URL): in local mode there is one scope and no shared space." }
|
|
237
|
+
}
|
|
238
|
+
let spaceContext
|
|
239
|
+
try {
|
|
240
|
+
spaceContext = await toolkit.resolveContext({
|
|
241
|
+
space: requested || undefined,
|
|
242
|
+
sessionID: requested ? undefined : context?.sessionID,
|
|
243
|
+
agent: context?.agent,
|
|
244
|
+
})
|
|
245
|
+
} catch (error) {
|
|
246
|
+
return { error: errorMessage(error) }
|
|
247
|
+
}
|
|
248
|
+
if (!spaceContext) return { error: "the control plane returned no space context" }
|
|
249
|
+
if (spaceContext.space_kind !== "shared") {
|
|
250
|
+
return {
|
|
251
|
+
message: requested
|
|
252
|
+
? `copy needs a shared space; ${oneLine(spaceContext.space_id || requested, 80)} is personal.`
|
|
253
|
+
: "no shared space is bound to this session; pass a shared space with the space argument.",
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (!requested && !toolkit.isSessionBound(spaceContext)) {
|
|
257
|
+
return { message: "the active shared space is not bound to this session; pass a shared space with the space argument." }
|
|
258
|
+
}
|
|
259
|
+
const role = String(spaceContext.role ?? "").trim().toLowerCase()
|
|
260
|
+
if (!canWriteShared(role)) {
|
|
261
|
+
return { message: `copying into ${oneLine(spaceContext.space_id, 80)} needs editor access; the control plane reports role ${role || "unknown"}.` }
|
|
262
|
+
}
|
|
263
|
+
return { spaceContext, where: { space: spaceContext.space_id } }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Ask the person (`ctx.permission.assert`); null when approved, else the answer to return. */
|
|
267
|
+
async function approve(context, ask, deniedText) {
|
|
268
|
+
try {
|
|
269
|
+
await toolkit.assert({
|
|
270
|
+
sessionID: context?.sessionID,
|
|
271
|
+
agent: context?.agent,
|
|
272
|
+
source: { type: "tool", messageID: context?.messageID, id: context?.id },
|
|
273
|
+
action: ask.action,
|
|
274
|
+
resources: ask.resources,
|
|
275
|
+
save: [],
|
|
276
|
+
metadata: ask.metadata,
|
|
277
|
+
})
|
|
278
|
+
return null
|
|
279
|
+
} catch (error) {
|
|
280
|
+
return text(`${deniedText}: ${errorMessage(error)}`)
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Find a user id by email among the members of the spaces you can see, the page's space first. */
|
|
285
|
+
async function userByEmail(email, spaceContext) {
|
|
286
|
+
const userId = userOf(spaceContext)
|
|
287
|
+
const tried = new Set()
|
|
288
|
+
const spaces = [spaceContext.space_id]
|
|
289
|
+
try {
|
|
290
|
+
for (const space of await control.listSpaces({ userId })) if (space.space_id) spaces.push(space.space_id)
|
|
291
|
+
} catch {
|
|
292
|
+
/* the page's own space is still searched */
|
|
293
|
+
}
|
|
294
|
+
for (const spaceId of spaces.slice(0, 11)) {
|
|
295
|
+
if (tried.has(spaceId)) continue
|
|
296
|
+
tried.add(spaceId)
|
|
297
|
+
try {
|
|
298
|
+
const member = (await control.listMembers({ userId, spaceId })).find((entry) => entry.email.toLowerCase() === email)
|
|
299
|
+
if (member) return { id: member.user_id, label: member.name || email }
|
|
300
|
+
} catch {
|
|
301
|
+
/* a space whose roster is not visible is skipped */
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return null
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async function principalFor(input, spaceContext, { usersOnly = false } = {}) {
|
|
308
|
+
const principal = readPrincipal(input?.to)
|
|
309
|
+
if (principal.error) return { message: principal.error }
|
|
310
|
+
if (usersOnly && principal.type !== "user") return { message: "transfer gives a page to one person: pass their email or user id." }
|
|
311
|
+
if (principal.email) {
|
|
312
|
+
const found = await userByEmail(principal.email, spaceContext)
|
|
313
|
+
if (!found) {
|
|
314
|
+
return {
|
|
315
|
+
message: `nothing changed: no member of the spaces you can see has the email ${oneLine(principal.email, 120)}. Pass their user id (from mem_spaces with "action": "members"), or ask an admin to add them to your organisation.`,
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return { principal: { type: "user", id: found.id, label: `${found.label} (${found.id})` } }
|
|
319
|
+
}
|
|
320
|
+
return { principal: { type: principal.type, id: principal.id, label: `${principal.type}:${principal.id}` } }
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** The page (or the folder's first pages) the path names, read from the records service. */
|
|
324
|
+
async function readTarget(target, where) {
|
|
325
|
+
if (target.kind === "page") {
|
|
326
|
+
const answer = await callRecords("records.get", { paths: [target.path] }, where)
|
|
327
|
+
const record = (answer?.records ?? []).find((entry) => entry?.path === target.path)
|
|
328
|
+
return { records: record ? [record] : [], title: record?.title }
|
|
329
|
+
}
|
|
330
|
+
const answer = await callRecords("records.list", { kind: "page", path_prefix: target.path, limit: 200 }, where)
|
|
331
|
+
return { records: answer?.records ?? [], cursor: answer?.cursor }
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Register the page or folder as a `wiki_page` resource (idempotent) and return its id. */
|
|
335
|
+
async function registerTarget(target, spaceContext, title) {
|
|
336
|
+
const resource = await control.createResource({
|
|
337
|
+
userId: userOf(spaceContext),
|
|
338
|
+
spaceId: spaceContext.space_id,
|
|
339
|
+
resource: {
|
|
340
|
+
kind: "wiki_page",
|
|
341
|
+
upstream_id: upstreamIdFor(target),
|
|
342
|
+
name: oneLine(target.kind === "page" ? `${title || target.path} (${target.path})` : `Folder ${target.path}`, 200),
|
|
343
|
+
},
|
|
344
|
+
})
|
|
345
|
+
return String(resource?.id ?? "").trim()
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** The space's shared pages and folders (`wiki_page` resources with a `records:` id). */
|
|
349
|
+
async function sharedResources(spaceContext) {
|
|
350
|
+
const rows = await control.listResources({ userId: userOf(spaceContext), spaceId: spaceContext.space_id, kind: "wiki_page" })
|
|
351
|
+
return rows.filter((row) => row.upstream_id.startsWith("records:")).map((row) => ({ ...row, path: row.upstream_id.slice("records:".length) }))
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Who one shared page or folder is shared with, or why that is not visible. */
|
|
355
|
+
async function grantsOn(spaceContext, resource) {
|
|
356
|
+
try {
|
|
357
|
+
return { grants: await control.listGrants({ userId: userOf(spaceContext), spaceId: spaceContext.space_id, resourceId: resource.id }) }
|
|
358
|
+
} catch (error) {
|
|
359
|
+
if ([403, 404].includes(Number(error?.status))) return { hidden: "its grants are visible to its owner and space admins" }
|
|
360
|
+
throw error
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** At most this many shared pages and folders are listed with their grants. */
|
|
365
|
+
const LIST_RESOURCES = 50
|
|
366
|
+
|
|
367
|
+
async function list(input, context) {
|
|
368
|
+
const space = await pageSpace(input, context)
|
|
369
|
+
if (space.message) return text(space.message)
|
|
370
|
+
if (space.error) return fail(space.error)
|
|
371
|
+
let target = null
|
|
372
|
+
if (String(input?.path ?? "").trim()) {
|
|
373
|
+
target = readSharePath(input.path)
|
|
374
|
+
if (target.error) return text(target.error)
|
|
375
|
+
}
|
|
376
|
+
const { spaceContext } = space
|
|
377
|
+
const lines = ["<shares>", `space: ${toolkit.describeSpace(spaceContext)}`]
|
|
378
|
+
let resources
|
|
379
|
+
try {
|
|
380
|
+
resources = (await sharedResources(spaceContext)).filter((row) => !target || row.path === target.path)
|
|
381
|
+
} catch (error) {
|
|
382
|
+
log.warn("share list failed", error)
|
|
383
|
+
return fail(errorMessage(error))
|
|
384
|
+
}
|
|
385
|
+
if (resources.length === 0) lines.push(target ? `(${target.path} is not shared)` : "(no page or folder in this space is shared)")
|
|
386
|
+
for (const resource of resources.slice(0, LIST_RESOURCES)) {
|
|
387
|
+
const owner = resource.owner_user_id ? `, owner ${oneLine(resource.owner_user_id, 80)}` : ""
|
|
388
|
+
lines.push(`- ${oneLine(resource.path, 120)}${resource.path.endsWith("/") ? " (folder)" : ""} (resource ${oneLine(resource.id, 80)}${owner})`)
|
|
389
|
+
let seen
|
|
390
|
+
try {
|
|
391
|
+
seen = await grantsOn(spaceContext, resource)
|
|
392
|
+
} catch (error) {
|
|
393
|
+
lines.push(` (grants could not be read: ${oneLine(errorMessage(error), 160)})`)
|
|
394
|
+
continue
|
|
395
|
+
}
|
|
396
|
+
if (seen.hidden) lines.push(` (${seen.hidden})`)
|
|
397
|
+
else if (seen.grants.length === 0) lines.push(" (no grants: registered, shared with no one)")
|
|
398
|
+
for (const grant of seen.grants ?? []) {
|
|
399
|
+
const principal = [grant.principal_type, grant.principal_id].filter(Boolean).join(":")
|
|
400
|
+
lines.push(` - ${oneLine(grant.grant_id, 80)} → ${oneLine(principal || "unknown", 160)} ${oneLine(grant.role || "?", 20)}, expires ${oneLine(grant.expires_at || "never", 40)}`)
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (resources.length > LIST_RESOURCES) lines.push(`(${resources.length - LIST_RESOURCES} more; pass path to see one)`)
|
|
404
|
+
lines.push("</shares>")
|
|
405
|
+
return text(lines.join("\n"))
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
async function grant(input, context) {
|
|
409
|
+
const target = readSharePath(input?.path)
|
|
410
|
+
if (target.error) return text(`not granted: ${target.error}`)
|
|
411
|
+
const role = String(input?.role ?? "viewer").trim().toLowerCase()
|
|
412
|
+
if (!GRANT_ROLES.includes(role)) return text(`not granted: role is viewer or editor, not ${oneLine(role, 40)}.`)
|
|
413
|
+
const expiry = readExpiry(input?.expires)
|
|
414
|
+
if (expiry.error) return text(`not granted: ${expiry.error}`)
|
|
415
|
+
if (!records()) return text(RECORDS_MISSING)
|
|
416
|
+
const space = await pageSpace(input, context)
|
|
417
|
+
if (space.message) return text(space.message)
|
|
418
|
+
if (space.error) return fail(space.error)
|
|
419
|
+
const { spaceContext, where } = space
|
|
420
|
+
|
|
421
|
+
let found
|
|
422
|
+
try {
|
|
423
|
+
found = await readTarget(target, where)
|
|
424
|
+
} catch (error) {
|
|
425
|
+
if (recordsServiceMissing(error)) return text(sharingNeedsRecords("grant"))
|
|
426
|
+
return fail(recordsFailure(error))
|
|
427
|
+
}
|
|
428
|
+
if (target.kind === "page" && found.records.length === 0) {
|
|
429
|
+
return text(`not granted: there is no page ${target.path} in ${toolkit.describeSpace(spaceContext)}. Check the path with mem_page ("action": "list").`)
|
|
430
|
+
}
|
|
431
|
+
const who = await principalFor(input, spaceContext)
|
|
432
|
+
if (who.message) return text(who.message)
|
|
433
|
+
const { principal } = who
|
|
434
|
+
|
|
435
|
+
const denied = await approve(
|
|
436
|
+
context,
|
|
437
|
+
{
|
|
438
|
+
action: "share.grant",
|
|
439
|
+
resources: [upstreamIdFor(target)],
|
|
440
|
+
metadata: {
|
|
441
|
+
space: spaceContext.space_id,
|
|
442
|
+
path: target.path,
|
|
443
|
+
kind: target.kind,
|
|
444
|
+
to: principal.label,
|
|
445
|
+
role,
|
|
446
|
+
expires: expiry.expires ?? "never",
|
|
447
|
+
...(target.kind === "folder" ? { pages: found.records.length } : { title: oneLine(found.title ?? "", 160) }),
|
|
448
|
+
},
|
|
449
|
+
},
|
|
450
|
+
"not granted (approval)",
|
|
451
|
+
)
|
|
452
|
+
if (denied) return denied
|
|
453
|
+
|
|
454
|
+
let resourceId
|
|
455
|
+
try {
|
|
456
|
+
resourceId = await registerTarget(target, spaceContext, found.title)
|
|
457
|
+
} catch (error) {
|
|
458
|
+
log.warn("share register failed", error)
|
|
459
|
+
return fail(`${target.path} could not be registered for sharing (${errorMessage(error)}). Nothing was granted.`)
|
|
460
|
+
}
|
|
461
|
+
if (!resourceId) return fail(`registering ${target.path} returned no resource id. Nothing was granted.`)
|
|
462
|
+
let row
|
|
463
|
+
try {
|
|
464
|
+
row = await control.createGrant({
|
|
465
|
+
userId: userOf(spaceContext),
|
|
466
|
+
grant: {
|
|
467
|
+
target_type: "resource",
|
|
468
|
+
target_id: resourceId,
|
|
469
|
+
principal_type: principal.type,
|
|
470
|
+
principal_id: principal.id,
|
|
471
|
+
role,
|
|
472
|
+
...(expiry.expires ? { expires_at: expiry.expires } : {}),
|
|
473
|
+
},
|
|
474
|
+
})
|
|
475
|
+
} catch (error) {
|
|
476
|
+
log.warn("share grant failed", error)
|
|
477
|
+
return fail(`${target.path} is registered (resource ${resourceId}), but the grant failed (${errorMessage(error)}). Nothing was shared.`)
|
|
478
|
+
}
|
|
479
|
+
const grantId = row?.grant_id || "(no id returned)"
|
|
480
|
+
log.info("share grant", { space: spaceContext.space_id, kind: target.kind, role })
|
|
481
|
+
const folderNote = target.kind === "folder" ? ` It covers every page under ${target.path} (${found.records.length}${found.cursor ? "+" : ""} now), including pages added later.` : ""
|
|
482
|
+
return text(
|
|
483
|
+
`granted ${role} on ${target.kind} ${target.path} in ${toolkit.describeSpace(spaceContext)} to ${principal.label}: grant ${grantId} (resource ${resourceId}), expires ${expiry.expires ?? "never"}.${folderNote} They read it with mem_page or mem_recall; it is not copied. To revoke: mem_share({"action": "revoke", "grant_id": "${grantId}"${input?.space ? `, "space": "${oneLine(spaceContext.space_id, 80)}"` : ""}}).`,
|
|
484
|
+
)
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** The shared page or folder that holds a grant, looked for among the space's (narrowed by path when given). */
|
|
488
|
+
async function holderOf(spaceContext, grantId, path) {
|
|
489
|
+
const resources = (await sharedResources(spaceContext)).filter((row) => !path || row.path === path)
|
|
490
|
+
for (const resource of resources.slice(0, LIST_RESOURCES)) {
|
|
491
|
+
const seen = await grantsOn(spaceContext, resource)
|
|
492
|
+
if (seen.grants?.some((row) => row.grant_id === grantId)) return resource
|
|
493
|
+
}
|
|
494
|
+
return null
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
async function revokeGrant(input, context) {
|
|
498
|
+
const grantId = String(input?.grant_id ?? "").trim()
|
|
499
|
+
let path = ""
|
|
500
|
+
if (String(input?.path ?? "").trim()) {
|
|
501
|
+
const target = readSharePath(input.path)
|
|
502
|
+
if (target.error) return text(`not revoked: ${target.error}`)
|
|
503
|
+
path = target.path
|
|
504
|
+
}
|
|
505
|
+
const space = await pageSpace(input, context)
|
|
506
|
+
if (space.message) return text(space.message)
|
|
507
|
+
if (space.error) return fail(space.error)
|
|
508
|
+
const { spaceContext } = space
|
|
509
|
+
let holder = null
|
|
510
|
+
try {
|
|
511
|
+
holder = await holderOf(spaceContext, grantId, path)
|
|
512
|
+
} catch {
|
|
513
|
+
holder = null
|
|
514
|
+
}
|
|
515
|
+
const denied = await approve(
|
|
516
|
+
context,
|
|
517
|
+
{ action: "share.revoke", resources: [grantId], metadata: { space: spaceContext.space_id, grant: grantId, ...(holder ? { path: holder.path } : {}) } },
|
|
518
|
+
"not revoked (approval)",
|
|
519
|
+
)
|
|
520
|
+
if (denied) return denied
|
|
521
|
+
try {
|
|
522
|
+
await control.deleteGrant({ userId: userOf(spaceContext), grantId })
|
|
523
|
+
} catch (error) {
|
|
524
|
+
const status = Number(error?.status)
|
|
525
|
+
if ([400, 403, 404].includes(status)) return text(`not revoked: ${errorMessage(error)}`)
|
|
526
|
+
log.warn("share revoke failed", error)
|
|
527
|
+
return fail(`grant ${oneLine(grantId, 80)} was not revoked: ${errorMessage(error)}`)
|
|
528
|
+
}
|
|
529
|
+
let back
|
|
530
|
+
if (!holder) {
|
|
531
|
+
back = `Read back: control does not show you which page holds grant ${grantId}, so only its delete answer (204) confirms it.`
|
|
532
|
+
} else {
|
|
533
|
+
try {
|
|
534
|
+
const seen = await grantsOn(spaceContext, holder)
|
|
535
|
+
if (seen.grants?.some((row) => row.grant_id === grantId)) {
|
|
536
|
+
return fail(`control answered the delete, but grant ${grantId} is still listed on ${holder.path}. Report this to the Memory server's operator.`)
|
|
537
|
+
}
|
|
538
|
+
back = `Read back: ${holder.path} no longer lists grant ${grantId}.`
|
|
539
|
+
} catch (error) {
|
|
540
|
+
back = `Read back failed (${errorMessage(error)}); control confirmed the delete.`
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
log.info("share revoke", { space: spaceContext.space_id })
|
|
544
|
+
return text(
|
|
545
|
+
`revoked grant ${oneLine(grantId, 80)}${holder ? ` on ${holder.path}` : ""} in ${toolkit.describeSpace(spaceContext)}. ${back} Anyone who already read the page may still have what they read in their own memory or transcripts.`,
|
|
546
|
+
)
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** Unshare a page or folder entirely: its catalog row and every grant on it go; the page stays. */
|
|
550
|
+
async function unshare(input, context) {
|
|
551
|
+
const target = readSharePath(input?.path)
|
|
552
|
+
if (target.error) return text(`not revoked: ${target.error}`)
|
|
553
|
+
const space = await pageSpace(input, context)
|
|
554
|
+
if (space.message) return text(space.message)
|
|
555
|
+
if (space.error) return fail(space.error)
|
|
556
|
+
const { spaceContext } = space
|
|
557
|
+
let resource
|
|
558
|
+
try {
|
|
559
|
+
resource = (await sharedResources(spaceContext)).find((row) => row.path === target.path)
|
|
560
|
+
} catch (error) {
|
|
561
|
+
return fail(errorMessage(error))
|
|
562
|
+
}
|
|
563
|
+
if (!resource) return text(`not revoked: ${target.path} is not shared in ${toolkit.describeSpace(spaceContext)}. Nothing changed.`)
|
|
564
|
+
const denied = await approve(
|
|
565
|
+
context,
|
|
566
|
+
{ action: "share.revoke", resources: [upstreamIdFor(target)], metadata: { space: spaceContext.space_id, path: target.path, unshare: "every grant on it" } },
|
|
567
|
+
"not revoked (approval)",
|
|
568
|
+
)
|
|
569
|
+
if (denied) return denied
|
|
570
|
+
let result
|
|
571
|
+
try {
|
|
572
|
+
result = await control.deleteResource({ userId: userOf(spaceContext), spaceId: spaceContext.space_id, resourceId: resource.id })
|
|
573
|
+
} catch (error) {
|
|
574
|
+
const status = Number(error?.status)
|
|
575
|
+
if ([400, 403, 404].includes(status)) return text(`not revoked: ${errorMessage(error)}`)
|
|
576
|
+
return fail(`${target.path} was not unshared: ${errorMessage(error)}`)
|
|
577
|
+
}
|
|
578
|
+
if (result?.deleted !== true) return fail(`${target.path} was not unshared: control did not confirm the delete.`)
|
|
579
|
+
let back
|
|
580
|
+
try {
|
|
581
|
+
const still = (await sharedResources(spaceContext)).some((row) => row.id === resource.id)
|
|
582
|
+
if (still) return fail(`control answered the delete, but ${target.path} is still listed as shared. Report this to the Memory server's operator.`)
|
|
583
|
+
back = `Read back: ${target.path} is no longer listed as shared.`
|
|
584
|
+
} catch (error) {
|
|
585
|
+
back = `Read back failed (${errorMessage(error)}).`
|
|
586
|
+
}
|
|
587
|
+
const removed = Number.isInteger(result?.grants_removed) ? ` and its ${result.grants_removed} grant(s)` : " and its grants"
|
|
588
|
+
return text(
|
|
589
|
+
`unshared ${target.kind} ${target.path} in ${toolkit.describeSpace(spaceContext)}: its catalog entry${removed} were deleted; the ${target.kind === "folder" ? "pages stay" : "page stays"} where ${target.kind === "folder" ? "they are" : "it is"}. ${back}`,
|
|
590
|
+
)
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/** `legacy`: the deprecated mem_promote revoke, which keeps asking `memory.promote.revoke`. */
|
|
594
|
+
async function revokeCopies(input, context, { legacy = false } = {}) {
|
|
595
|
+
const ids = uniqueIds(input?.ids)
|
|
596
|
+
if (ids.length === 0) return text("not revoked: pass grant_id, or the ids of copies.")
|
|
597
|
+
if (ids.length > MAX_COPY_IDS) return text(`not revoked: at most ${MAX_COPY_IDS} ids per call.`)
|
|
598
|
+
if (!records()) return text(RECORDS_MISSING)
|
|
599
|
+
const space = await pageSpace(input, context)
|
|
600
|
+
if (space.message) return text(space.message)
|
|
601
|
+
if (space.error) return fail(space.error)
|
|
602
|
+
const { spaceContext, where } = space
|
|
603
|
+
let found
|
|
604
|
+
try {
|
|
605
|
+
found = await callRecords("records.get", { ids }, where)
|
|
606
|
+
} catch (error) {
|
|
607
|
+
if (recordsServiceMissing(error)) return text(sharingNeedsRecords("revoke"))
|
|
608
|
+
return fail(recordsFailure(error))
|
|
609
|
+
}
|
|
610
|
+
const byId = new Map((found?.records ?? []).map((record) => [String(record?.id), record]))
|
|
611
|
+
const missing = ids.filter((id) => !byId.has(id))
|
|
612
|
+
if (missing.length > 0) return text(`not revoked: ${missing.join(", ")} not found in ${toolkit.describeSpace(spaceContext)}. Nothing was deleted.`)
|
|
613
|
+
const notCopies = ids.filter((id) => !isPlainObject(byId.get(id)?.fields?.copied_from))
|
|
614
|
+
if (notCopies.length > 0) {
|
|
615
|
+
return text(`not revoked: ${notCopies.join(", ")} ${notCopies.length === 1 ? "is not a copy" : "are not copies"}; revoke deletes only copies. To forget a memory use mem_revise ("action": "forget"). Nothing was deleted.`)
|
|
616
|
+
}
|
|
617
|
+
const metadata = { space: spaceContext.space_id, copies: ids.map((id) => `${id}: ${oneLine(byId.get(id)?.title ?? byId.get(id)?.body ?? "", 120)}`) }
|
|
618
|
+
const denied = await approve(
|
|
619
|
+
context,
|
|
620
|
+
legacy ? { action: "memory.promote.revoke", resources: ids, metadata } : { action: "share.revoke", resources: ids, metadata },
|
|
621
|
+
"not revoked (approval)",
|
|
622
|
+
)
|
|
623
|
+
if (denied) return denied
|
|
624
|
+
try {
|
|
625
|
+
await callRecords("records.delete", { ids }, where)
|
|
626
|
+
} catch (error) {
|
|
627
|
+
log.warn("copy revoke failed", error)
|
|
628
|
+
return fail(`the copies were not deleted: ${recordsFailure(error)}`)
|
|
629
|
+
}
|
|
630
|
+
let back
|
|
631
|
+
try {
|
|
632
|
+
const again = await callRecords("records.get", { ids }, where)
|
|
633
|
+
const still = (again?.records ?? []).map((record) => String(record?.id)).filter((id) => ids.includes(id))
|
|
634
|
+
if (still.length > 0) return fail(`the records service answered the delete, but ${still.join(", ")} can still be read. Report this to the Memory server's operator.`)
|
|
635
|
+
back = `Read back: ${ids.length === 1 ? "it is" : "they are"} no longer readable.`
|
|
636
|
+
} catch (error) {
|
|
637
|
+
back = `Read back failed (${recordsFailure(error)}).`
|
|
638
|
+
}
|
|
639
|
+
log.info("copy revoke", { space: spaceContext.space_id, count: ids.length })
|
|
640
|
+
return text(
|
|
641
|
+
`revoked ${ids.length} cop${ids.length === 1 ? "y" : "ies"} in ${toolkit.describeSpace(spaceContext)}: ${ids.join(", ")} deleted. ${back} Your private originals are unchanged. Anyone who already read a copy may still have it in their own memory or transcripts.`,
|
|
642
|
+
)
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
async function transfer(input, context) {
|
|
646
|
+
const target = readSharePath(input?.path)
|
|
647
|
+
if (target.error) return text(`not transferred: ${target.error}`)
|
|
648
|
+
if (!records()) return text(RECORDS_MISSING)
|
|
649
|
+
const space = await pageSpace(input, context)
|
|
650
|
+
if (space.message) return text(space.message)
|
|
651
|
+
if (space.error) return fail(space.error)
|
|
652
|
+
const { spaceContext, where } = space
|
|
653
|
+
const who = await principalFor(input, spaceContext, { usersOnly: true })
|
|
654
|
+
if (who.message) return text(who.message)
|
|
655
|
+
const { principal } = who
|
|
656
|
+
|
|
657
|
+
let found
|
|
658
|
+
try {
|
|
659
|
+
found = await readTarget(target, where)
|
|
660
|
+
} catch (error) {
|
|
661
|
+
if (recordsServiceMissing(error)) return text(sharingNeedsRecords("transfer"))
|
|
662
|
+
return fail(recordsFailure(error))
|
|
663
|
+
}
|
|
664
|
+
if (found.records.length === 0) return text(`not transferred: there is no ${target.kind === "page" ? "page" : "page under"} ${target.path} in ${toolkit.describeSpace(spaceContext)}.`)
|
|
665
|
+
|
|
666
|
+
const denied = await approve(
|
|
667
|
+
context,
|
|
668
|
+
{
|
|
669
|
+
action: "share.transfer",
|
|
670
|
+
resources: [upstreamIdFor(target)],
|
|
671
|
+
metadata: { space: spaceContext.space_id, path: target.path, kind: target.kind, to: principal.label, pages: found.records.length },
|
|
672
|
+
},
|
|
673
|
+
"not transferred (approval)",
|
|
674
|
+
)
|
|
675
|
+
if (denied) return denied
|
|
676
|
+
|
|
677
|
+
let resourceId
|
|
678
|
+
try {
|
|
679
|
+
resourceId = await registerTarget(target, spaceContext, found.title)
|
|
680
|
+
if (!resourceId) throw new Error("registration returned no resource id")
|
|
681
|
+
const moved = await control.transferResource({ userId: userOf(spaceContext), spaceId: spaceContext.space_id, resourceId, toUserId: principal.id })
|
|
682
|
+
if (moved?.transferred === false) throw new Error("control did not transfer it")
|
|
683
|
+
} catch (error) {
|
|
684
|
+
log.warn("share transfer failed", error)
|
|
685
|
+
return fail(`${target.path} was not transferred: ${errorMessage(error)}. Nothing changed.`)
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// Control now names the new owner; the records under the path follow
|
|
689
|
+
// (contract §3: records.put with the new owner).
|
|
690
|
+
const pages = target.kind === "page" ? found.records : await allUnder(target, where, found)
|
|
691
|
+
const failed = []
|
|
692
|
+
for (const record of pages.slice(0, MAX_TRANSFER_RECORDS)) {
|
|
693
|
+
try {
|
|
694
|
+
await putOwner(record, principal.id, where)
|
|
695
|
+
} catch (error) {
|
|
696
|
+
failed.push(`${record.path || record.id} (${recordsFailure(error)})`)
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
const over = pages.length > MAX_TRANSFER_RECORDS ? pages.length - MAX_TRANSFER_RECORDS : 0
|
|
700
|
+
log.info("share transfer", { space: spaceContext.space_id, kind: target.kind, pages: pages.length, failed: failed.length })
|
|
701
|
+
const done = `transferred ${target.kind} ${target.path} in ${toolkit.describeSpace(spaceContext)} to ${principal.label}: control's resource ${resourceId} names them as owner`
|
|
702
|
+
if (failed.length > 0 || over > 0) {
|
|
703
|
+
return fail(
|
|
704
|
+
`${done}, but ${failed.length + over} of ${pages.length} page(s) still name the old owner${failed.length ? `: ${failed.slice(0, 5).join("; ")}` : ""}${over ? `; ${over} past the ${MAX_TRANSFER_RECORDS}-page limit` : ""}. Repeat the same call to finish.`,
|
|
705
|
+
)
|
|
706
|
+
}
|
|
707
|
+
return text(`${done}, and ${pages.length} page(s) now name them as owner. You keep the access your space role gives you.`)
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
async function allUnder(target, where, first) {
|
|
711
|
+
const out = [...first.records]
|
|
712
|
+
let cursor = first.cursor
|
|
713
|
+
while (cursor && out.length < MAX_TRANSFER_RECORDS + 1) {
|
|
714
|
+
const answer = await callRecords("records.list", { kind: "page", path_prefix: target.path, limit: 200, cursor }, where)
|
|
715
|
+
out.push(...(answer?.records ?? []))
|
|
716
|
+
cursor = answer?.cursor
|
|
717
|
+
}
|
|
718
|
+
return out
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** Set a record's owner; on a version conflict, read it again once and retry. */
|
|
722
|
+
async function putOwner(record, owner, where) {
|
|
723
|
+
if (record.owner === owner) return
|
|
724
|
+
const put = (current) => callRecords("records.put", { record: { ...current, owner, base_version: current.version } }, where)
|
|
725
|
+
try {
|
|
726
|
+
await put(record)
|
|
727
|
+
} catch (error) {
|
|
728
|
+
if (String(error?.code) !== "version_conflict") throw error
|
|
729
|
+
const fresh = (await callRecords("records.get", { ids: [record.id] }, where))?.records?.[0]
|
|
730
|
+
if (!fresh) throw error
|
|
731
|
+
if (fresh.owner !== owner) await put(fresh)
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/**
|
|
736
|
+
* Read the memories a copy takes, from the personal space only: `rec_` ids
|
|
737
|
+
* from the records service, and `m_`/`msg-` ids (written before 0.9) from
|
|
738
|
+
* the core's newest rows, as mem_forget finds them.
|
|
739
|
+
*/
|
|
740
|
+
async function readSources(ids, personal, context) {
|
|
741
|
+
const found = new Map()
|
|
742
|
+
const problems = []
|
|
743
|
+
const recordIds = ids.filter((id) => RECORD_ID.test(id))
|
|
744
|
+
const legacyIds = ids.filter((id) => LEGACY_ID.test(id))
|
|
745
|
+
const unknown = ids.filter((id) => !RECORD_ID.test(id) && !LEGACY_ID.test(id))
|
|
746
|
+
if (unknown.length > 0) problems.push(`${unknown.join(", ")} ${unknown.length === 1 ? "is not a memory id" : "are not memory ids"} (rec_…, or m_…/msg-… from before 0.9)`)
|
|
747
|
+
if (recordIds.length > 0) {
|
|
748
|
+
const answer = await callRecords("records.get", { ids: recordIds }, { space: personal.space_id })
|
|
749
|
+
for (const record of answer?.records ?? []) {
|
|
750
|
+
const id = String(record?.id ?? "")
|
|
751
|
+
if (!recordIds.includes(id)) continue
|
|
752
|
+
if (record.kind !== "memory") {
|
|
753
|
+
problems.push(`${id} is a ${record.kind}, not a memory: pages are shared with grant, not copied`)
|
|
754
|
+
continue
|
|
755
|
+
}
|
|
756
|
+
if (record.status === "superseded" || record.status === "retired") {
|
|
757
|
+
problems.push(`${id} is ${record.status}; copy the current memory instead`)
|
|
758
|
+
continue
|
|
759
|
+
}
|
|
760
|
+
found.set(id, { id, type: record.type || "fact", title: record.title, text: String(record.body ?? record.title ?? "").trim(), stated_by: record.stated_by })
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
if (legacyIds.length > 0) {
|
|
764
|
+
const legacy = await readLegacy(legacyIds, personal, context)
|
|
765
|
+
for (const [id, record] of legacy.found) found.set(id, record)
|
|
766
|
+
if (legacy.failed) problems.push("the core did not answer the row listing for the m_/msg- ids")
|
|
767
|
+
}
|
|
768
|
+
const missing = ids.filter((id) => !found.has(id) && !problems.some((problem) => problem.includes(id)))
|
|
769
|
+
if (missing.length > 0) problems.push(`${missing.join(", ")} not found in your personal space`)
|
|
770
|
+
return { found, problems }
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
async function readLegacy(ids, personal, context) {
|
|
774
|
+
const found = new Map()
|
|
775
|
+
const backend = toolkit.backend
|
|
776
|
+
if (!backend?.queryAtoms || !backend?.queryConversations) return { found, failed: true }
|
|
777
|
+
const { session_id: _session, ...base } = toolkit.scopeFor(personal, { agent: context?.agent })
|
|
778
|
+
const agents = [...new Set([...ids.map((id) => toolkit.locate?.(personal, id)?.agent_id), base.agent_id, ...(toolkit.knownAgents?.(personal) ?? [])].filter(Boolean))].slice(0, 4)
|
|
779
|
+
let failed = false
|
|
780
|
+
for (const layer of ["l1", "l0"]) {
|
|
781
|
+
for (const agent of agents) {
|
|
782
|
+
for (let page = 0; page < SCAN_PAGES && ids.some((id) => !found.has(id)); page += 1) {
|
|
783
|
+
let data
|
|
784
|
+
try {
|
|
785
|
+
const scope = { ...base, agent_id: agent }
|
|
786
|
+
data =
|
|
787
|
+
layer === "l0"
|
|
788
|
+
? await backend.queryConversations({ scope, limit: SCAN_PAGE, offset: page * SCAN_PAGE })
|
|
789
|
+
: await backend.queryAtoms({ scope, limit: SCAN_PAGE, offset: page * SCAN_PAGE })
|
|
790
|
+
} catch {
|
|
791
|
+
failed = true
|
|
792
|
+
break
|
|
793
|
+
}
|
|
794
|
+
const rows = (layer === "l0" ? (data?.messages ?? data?.items) : (data?.items ?? data?.records)) ?? []
|
|
795
|
+
for (const row of rows) {
|
|
796
|
+
const id = String(row?.id ?? "")
|
|
797
|
+
if (!ids.includes(id) || found.has(id)) continue
|
|
798
|
+
const raw = String(row?.content ?? row?.text ?? "").trim()
|
|
799
|
+
const type = ["fact", "preference", "constraint", "decision", "procedure"].includes(row?.type) ? row.type : "fact"
|
|
800
|
+
found.set(id, { id, type, text: layer === "l0" ? raw.replace(REMEMBER_WRAPPER, "").trim() : raw, stated_by: "person" })
|
|
801
|
+
}
|
|
802
|
+
if (rows.length < SCAN_PAGE) break
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
return { found, failed }
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* Copy private memories into a shared space: one new record per memory,
|
|
811
|
+
* with `fields.copied_from` ({ space, id, by, at, rationale }). The person
|
|
812
|
+
* approves the exact text first (`memory.promote`). A write that fails part
|
|
813
|
+
* way deletes the copies it made, so a copy is all or nothing.
|
|
814
|
+
*/
|
|
815
|
+
async function copy(input, context) {
|
|
816
|
+
const ids = uniqueIds(input?.ids)
|
|
817
|
+
if (ids.length === 0) return text("nothing to copy: ids is empty.")
|
|
818
|
+
if (ids.length > MAX_COPY_IDS) return text(`not copied: at most ${MAX_COPY_IDS} ids per call.`)
|
|
819
|
+
const rationale = String(input?.rationale ?? "").trim()
|
|
820
|
+
if (!rationale) return text("not copied: rationale is required; it is recorded on each copy.")
|
|
821
|
+
const rationaleRefusal = writeRefusal(rationale)
|
|
822
|
+
if (rationaleRefusal) return text(`not copied (rationale): ${rationaleRefusal.replace(/^not stored: /, "")}`)
|
|
823
|
+
if (!records()) return text(RECORDS_MISSING)
|
|
824
|
+
|
|
825
|
+
const target = await copyTarget(input, context)
|
|
826
|
+
if (target.message) return text(target.message)
|
|
827
|
+
if (target.error) return fail(target.error)
|
|
828
|
+
const resolved = await toolkit.resolvePrivateSpace({}, context)
|
|
829
|
+
if (resolved.invalid) return text(resolved.invalid)
|
|
830
|
+
if (resolved.error) return fail(resolved.error)
|
|
831
|
+
const personal = resolved.context
|
|
832
|
+
|
|
833
|
+
let read
|
|
834
|
+
try {
|
|
835
|
+
read = await readSources(ids, personal, context)
|
|
836
|
+
} catch (error) {
|
|
837
|
+
if (recordsServiceMissing(error)) return text(sharingNeedsRecords("copy"))
|
|
838
|
+
return fail(recordsFailure(error))
|
|
839
|
+
}
|
|
840
|
+
if (read.problems.length > 0) return text(`not copied: ${read.problems.join("; ")}. Nothing was created.`)
|
|
841
|
+
const sources = ids.map((id) => read.found.get(id))
|
|
842
|
+
for (const source of sources) {
|
|
843
|
+
if (!source.text) return text(`not copied: ${source.id} has no text. Nothing was created.`)
|
|
844
|
+
if (source.text.length > MAX_COPY_CHARS) return text(`not copied: ${source.id} is ${source.text.length} characters, over the ${MAX_COPY_CHARS} a copy takes. Nothing was created.`)
|
|
845
|
+
const refusal = writeRefusal(source.text)
|
|
846
|
+
if (refusal) return text(`not copied: ${source.id}: ${refusal.replace(/^not stored: /, "")} Nothing was created.`)
|
|
847
|
+
source.text = redactSecrets(source.text)
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
const { spaceContext, where } = target
|
|
851
|
+
const denied = await approve(
|
|
852
|
+
context,
|
|
853
|
+
{
|
|
854
|
+
action: "memory.promote",
|
|
855
|
+
resources: ids,
|
|
856
|
+
metadata: { space: spaceContext.space_id, rationale, copies: sources.map((source) => `${source.id} (${source.type}): ${oneLine(source.text, 160)}`) },
|
|
857
|
+
},
|
|
858
|
+
"not copied (approval)",
|
|
859
|
+
)
|
|
860
|
+
if (denied) return denied
|
|
861
|
+
|
|
862
|
+
const by = userOf(personal) || userOf(spaceContext) || "unknown"
|
|
863
|
+
const at = new Date().toISOString()
|
|
864
|
+
const made = []
|
|
865
|
+
for (const source of sources) {
|
|
866
|
+
try {
|
|
867
|
+
const answer = await callRecords(
|
|
868
|
+
"records.put",
|
|
869
|
+
{
|
|
870
|
+
record: {
|
|
871
|
+
kind: "memory",
|
|
872
|
+
type: source.type,
|
|
873
|
+
title: oneLine(source.title || source.text, 300),
|
|
874
|
+
body: source.text,
|
|
875
|
+
stated_by: source.stated_by || "person",
|
|
876
|
+
fields: { copied_from: { space: personal.space_id, id: source.id, by, at, rationale: oneLine(rationale, 500) } },
|
|
877
|
+
source: { session: context?.sessionID },
|
|
878
|
+
},
|
|
879
|
+
},
|
|
880
|
+
where,
|
|
881
|
+
)
|
|
882
|
+
const id = String(answer?.record?.id ?? "")
|
|
883
|
+
if (!id) throw new Error("records.put returned no id")
|
|
884
|
+
made.push({ from: source.id, id })
|
|
885
|
+
} catch (error) {
|
|
886
|
+
log.warn("copy write failed", error)
|
|
887
|
+
// The records service is missing on this server (legacy m_/msg- ids
|
|
888
|
+
// are read from the core, so the first write is where it shows).
|
|
889
|
+
if (recordsServiceMissing(error) && made.length === 0) return text(sharingNeedsRecords("copy"))
|
|
890
|
+
let cleanup = "nothing was left behind"
|
|
891
|
+
if (made.length > 0) {
|
|
892
|
+
try {
|
|
893
|
+
await callRecords("records.delete", { ids: made.map((entry) => entry.id) }, where)
|
|
894
|
+
cleanup = `the ${made.length} cop${made.length === 1 ? "y" : "ies"} already written ${made.length === 1 ? "was" : "were"} deleted`
|
|
895
|
+
} catch (cleanupError) {
|
|
896
|
+
cleanup = `${made.map((entry) => entry.id).join(", ")} remain (${recordsFailure(cleanupError)}); revoke them with mem_share ("action": "revoke", "ids")`
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
return fail(`copying ${source.id} failed (${recordsFailure(error)}); ${cleanup}. Nothing was shared.`)
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
log.info("copy", { space: spaceContext.space_id, count: made.length })
|
|
903
|
+
const list = made.map((entry) => `${entry.from} → ${entry.id}`).join(", ")
|
|
904
|
+
return text(
|
|
905
|
+
`copied ${made.length} memor${made.length === 1 ? "y" : "ies"} to ${toolkit.describeSpace(spaceContext)}: ${list}. Each copy names its source (copied_from). They are copies: your private originals are unchanged, and later edits to them do not reach the copies. Members find them with mem_recall in that space. To revoke: mem_share({"action": "revoke", "ids": [${made.map((entry) => `"${entry.id}"`).join(", ")}], "space": "${oneLine(spaceContext.space_id, 80)}"}).`,
|
|
906
|
+
)
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/**
|
|
910
|
+
* Revoke a 0.8.x share (`mem_promote`): one wiki per share, registered as a
|
|
911
|
+
* `wiki` resource. Kept for the deprecated alias for one release: dry run,
|
|
912
|
+
* marker check, approval (`memory.promote.revoke`), delete, read back.
|
|
913
|
+
*/
|
|
914
|
+
async function revokeLegacyShare(input, context) {
|
|
915
|
+
const shareID = String(input?.revoke ?? "").trim()
|
|
916
|
+
const backend = toolkit.backend
|
|
917
|
+
if (!control) return text("revoking a 0.8 share needs the control plane (MEMORY_CONTROL_URL).")
|
|
918
|
+
const target = await copyTargetForRevoke(input, context)
|
|
919
|
+
if (target.message) return text(target.message)
|
|
920
|
+
if (target.error) return fail(target.error)
|
|
921
|
+
const { spaceContext, scoped } = target
|
|
922
|
+
const userId = userOf(spaceContext)
|
|
923
|
+
const refused = (error) => [400, 403, 404].includes(Number(error?.status))
|
|
924
|
+
let dry
|
|
925
|
+
try {
|
|
926
|
+
dry = await control.deleteResource({ userId, spaceId: spaceContext.space_id, resourceId: shareID, dryRun: true })
|
|
927
|
+
} catch (error) {
|
|
928
|
+
return refused(error) ? text(`revoke refused: ${errorMessage(error)}`) : fail(errorMessage(error))
|
|
929
|
+
}
|
|
930
|
+
const wikiID = String(dry?.resource?.upstream_id ?? "").trim()
|
|
931
|
+
if (dry?.resource?.kind !== "wiki" || !wikiID) return text(`${oneLine(shareID, 80)} is not a share; mem_promote revoke deletes only shares. Nothing was deleted.`)
|
|
932
|
+
let state
|
|
933
|
+
try {
|
|
934
|
+
const raw = await backend.readWikiRaw({ scope: scoped, wikiID, filenames: [LEGACY_SHARE_FILE] })
|
|
935
|
+
const item = (raw?.items ?? []).find((entry) => entry?.filename === LEGACY_SHARE_FILE)
|
|
936
|
+
state = String(item?.content ?? "").startsWith(LEGACY_SHARE_MARKER) ? "share" : "other"
|
|
937
|
+
} catch (error) {
|
|
938
|
+
state = Number(error?.status) === 404 ? "absent" : { error: errorMessage(error) }
|
|
939
|
+
}
|
|
940
|
+
if (state === "other") return text(`${oneLine(shareID, 80)} is not a share made by mem_promote; nothing was deleted.`)
|
|
941
|
+
if (typeof state === "object") return fail(`could not confirm that ${oneLine(shareID, 80)} is a share (${state.error}). Nothing was deleted.`)
|
|
942
|
+
const denied = await approve(
|
|
943
|
+
context,
|
|
944
|
+
{ action: "memory.promote.revoke", resources: [shareID], metadata: { space: spaceContext.space_id, wiki: wikiID } },
|
|
945
|
+
"revoke denied",
|
|
946
|
+
)
|
|
947
|
+
if (denied) return denied
|
|
948
|
+
let result
|
|
949
|
+
try {
|
|
950
|
+
result = await control.deleteResource({ userId, spaceId: spaceContext.space_id, resourceId: shareID })
|
|
951
|
+
} catch (error) {
|
|
952
|
+
log.warn("share revoke failed", error)
|
|
953
|
+
return refused(error) ? text(`revoke refused: ${errorMessage(error)}`) : fail(`share ${oneLine(shareID, 80)} was not revoked: ${errorMessage(error)}`)
|
|
954
|
+
}
|
|
955
|
+
if (result?.deleted !== true) return fail(`share ${oneLine(shareID, 80)} was not revoked: the gateway did not confirm the delete.`)
|
|
956
|
+
let back
|
|
957
|
+
try {
|
|
958
|
+
await backend.getWiki({ scope: scoped, wikiID })
|
|
959
|
+
return fail(`share ${oneLine(shareID, 80)}: the gateway reported a delete, but wiki ${oneLine(wikiID, 120)} is still readable. Report this to an operator.`)
|
|
960
|
+
} catch (error) {
|
|
961
|
+
const status = Number(error?.status)
|
|
962
|
+
back = status === 403 || status === 404 ? `Read back: wiki ${oneLine(wikiID, 120)} is no longer reachable (${status}).` : `Read back failed (${errorMessage(error)}).`
|
|
963
|
+
}
|
|
964
|
+
const where = toolkit.displayScope(spaceContext, scoped)
|
|
965
|
+
return text(
|
|
966
|
+
`revoked share ${oneLine(shareID, 80)} in ${where}: the copy (wiki ${oneLine(wikiID, 120)}) and its catalog entry were deleted. ${back} Your private originals are unchanged. Anyone who already read the share may still have it in their own memory or transcripts.`,
|
|
967
|
+
)
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
async function copyTargetForRevoke(input, context) {
|
|
971
|
+
const requested = String(input?.space ?? "").trim()
|
|
972
|
+
let spaceContext
|
|
973
|
+
try {
|
|
974
|
+
spaceContext = await toolkit.resolveContext({ space: requested || undefined, sessionID: requested ? undefined : context?.sessionID, agent: context?.agent })
|
|
975
|
+
} catch (error) {
|
|
976
|
+
return { error: errorMessage(error) }
|
|
977
|
+
}
|
|
978
|
+
if (!spaceContext) return { error: "the control plane returned no space context" }
|
|
979
|
+
if (spaceContext.space_kind !== "shared") {
|
|
980
|
+
return { message: requested ? `mem_promote cannot use personal space ${oneLine(spaceContext.space_id || "personal", 80)}; pass the shared space the share was made in.` : "no shared space is bound to this session; pass the shared space the share was made in with the space argument." }
|
|
981
|
+
}
|
|
982
|
+
if (!requested && !toolkit.isSessionBound(spaceContext)) return { message: "the active shared space is not bound to this session; pass the shared space the share was made in with the space argument." }
|
|
983
|
+
return { spaceContext, scoped: toolkit.scopeFor(spaceContext, { sessionID: requested ? undefined : context?.sessionID, agent: context?.agent }) }
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
async function run(input, context) {
|
|
987
|
+
const action = String(input?.action ?? "").trim()
|
|
988
|
+
if (!SHARE_ACTIONS.includes(action)) return text(`unknown action ${oneLine(action || "(none)", 40)}: use list, grant, revoke, transfer, or copy.`)
|
|
989
|
+
try {
|
|
990
|
+
if (action === "list") return await list(input, context)
|
|
991
|
+
if (action === "grant") return await grant(input, context)
|
|
992
|
+
if (action === "transfer") return await transfer(input, context)
|
|
993
|
+
if (action === "copy") return await copy(input, context)
|
|
994
|
+
const hasIds = Array.isArray(input?.ids) && input.ids.length > 0
|
|
995
|
+
if (String(input?.grant_id ?? "").trim()) {
|
|
996
|
+
if (hasIds) return text("not revoked: pass grant_id or ids, not both.")
|
|
997
|
+
return await revokeGrant(input, context)
|
|
998
|
+
}
|
|
999
|
+
if (!hasIds && String(input?.path ?? "").trim()) return await unshare(input, context)
|
|
1000
|
+
return await revokeCopies(input, context)
|
|
1001
|
+
} catch (error) {
|
|
1002
|
+
log.warn("share failed", error)
|
|
1003
|
+
return fail(errorMessage(error))
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
return { run, copy, revokeCopies, revokeLegacyShare, list, grant, revokeGrant, unshare, transfer }
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
function uniqueIds(value) {
|
|
1011
|
+
return [...new Set((Array.isArray(value) ? value : []).map((id) => String(id).trim()).filter(Boolean))]
|
|
1012
|
+
}
|