@joe-broadhead/opencode-mem 0.9.12 → 0.11.2
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 +1934 -2
- package/README.md +29 -17
- package/SECURITY.md +3 -1
- package/docs/agent-instructions.md +17 -0
- package/docs/agent-protocol.md +8 -8
- package/docs/permissions.md +22 -4
- package/package.json +7923 -217
- package/shared/page-paths.js +44 -0
- package/skills/mem.pages/SKILL.md +8 -1
- package/skills/mem.usage/SKILL.md +15 -15
- package/src/action-grant-keys.js +159 -0
- package/src/action-grant.js +439 -0
- package/src/actions.js +1690 -0
- package/src/backend/records.js +25 -2
- package/src/backend/v3.js +76 -22
- package/src/call-shapes.js +17 -16
- package/src/collector-lock.js +533 -62
- package/src/collector-service.js +153 -26
- package/src/collector.js +627 -33
- package/src/config.js +79 -6
- package/src/connect.js +106 -8
- package/src/credentials.js +123 -25
- package/src/events.js +174 -3
- package/src/forget-turn.js +141 -0
- package/src/host-refusal.js +78 -0
- package/src/index.js +209 -22
- package/src/jobs/host.js +557 -0
- package/src/ops/codes.js +110 -0
- package/src/ops/copy-lineage.js +42 -0
- package/src/ops/index.js +28 -0
- package/src/ops/space-ops.js +1936 -0
- package/src/outlinks.js +103 -0
- package/src/p2-reservation.js +151 -0
- package/src/permissions.js +30 -0
- package/src/plugins/descriptor.js +62 -0
- package/src/plugins/discovery.js +318 -0
- package/src/plugins/grants.js +178 -0
- package/src/plugins/locate.js +319 -0
- package/src/plugins/manifest.js +1162 -0
- package/src/plugins/source-contract/index.js +34 -0
- package/src/plugins/source-contract/policy.js +102 -0
- package/src/plugins/source-contract/vendor/PROVENANCE.json +17 -0
- package/src/plugins/source-contract/vendor/RELEASE-SHA256SUMS +3 -0
- package/src/plugins/source-contract/vendor/RELEASE.json +17 -0
- package/src/plugins/source-contract/vendor/SHA256SUMS +41 -0
- package/src/plugins/source-contract/vendor/THIRD-PARTY-NOTICES.md +35 -0
- package/src/plugins/source-contract/vendor/broker-client.js +93 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-3M5PAKSS.js +84 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-4ERCA4TK.js +185 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-6HDIB2SA.js +183 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-ELPJD3ND.js +10 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-HLVAKAYG.js +10 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-I2RXJJJM.js +81 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-KWEWSZ4V.js +505 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-KYWBTAF4.js +182 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-Q3RQA5J2.js +249 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-RRUAIQ4I.js +156 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-RYNKNCPP.js +165 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-W5SHR7DQ.js +9477 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-ZUKF7P6U.js +653 -0
- package/src/plugins/source-contract/vendor/cursor.js +26 -0
- package/src/plugins/source-contract/vendor/descriptor.js +34 -0
- package/src/plugins/source-contract/vendor/events.js +257 -0
- package/src/plugins/source-contract/vendor/index.js +10 -0
- package/src/plugins/source-contract/vendor/params.js +22 -0
- package/src/plugins/source-contract/vendor/permission.js +28 -0
- package/src/plugins/source-contract/vendor/pick.js +22 -0
- package/src/plugins/source-contract/vendor/read.js +29 -0
- package/src/plugins/source-contract/vendor/registry.js +23 -0
- package/src/plugins/source-contract/vendor/schema.js +17 -0
- package/src/plugins/source-contract/vendor/schemas/output.agenda.json +96 -0
- package/src/plugins/source-contract/vendor/schemas/output.countdown.json +28 -0
- package/src/plugins/source-contract/vendor/schemas/output.image.json +28 -0
- package/src/plugins/source-contract/vendor/schemas/output.inbox.json +84 -0
- package/src/plugins/source-contract/vendor/schemas/output.links.json +46 -0
- package/src/plugins/source-contract/vendor/schemas/output.list.json +57 -0
- package/src/plugins/source-contract/vendor/schemas/output.metric.json +61 -0
- package/src/plugins/source-contract/vendor/schemas/output.note.json +14 -0
- package/src/plugins/source-contract/vendor/schemas/output.progress.json +50 -0
- package/src/plugins/source-contract/vendor/schemas/output.record.json +38 -0
- package/src/plugins/source-contract/vendor/schemas/output.table.json +61 -0
- package/src/plugins/source-contract/vendor/schemas/output.thread.json +62 -0
- package/src/plugins/source-contract/vendor/schemas/sources.json +819 -0
- package/src/plugins/source-contract/vendor/schemas.js +19 -0
- package/src/plugins/source-contract/vendor/tools-rpc.js +42 -0
- package/src/plugins/verify.js +56 -0
- package/src/protocol.js +21 -5
- package/src/recall.js +104 -5
- package/src/records.js +61 -2
- package/src/requests.js +216 -0
- package/src/runtime.js +89 -7
- package/src/setup-time.js +68 -0
- package/src/skills.js +230 -8
- package/src/source-ids.js +25 -0
- package/src/sources/declaration.js +365 -0
- package/src/sources/reads.js +772 -0
- package/src/sources/rpc.js +151 -0
- package/src/sources.js +409 -90
- package/src/spaces.js +283 -11
- package/src/spool.js +61 -4
- package/src/stated.js +10 -5
- package/src/storable.js +139 -0
- package/src/tools/commitments.js +47 -5
- package/src/tools/held-write.js +36 -13
- package/src/tools/index.js +27 -0
- package/src/tools/ingest.js +27 -2
- package/src/tools/memory.js +52 -14
- package/src/tools/page.js +95 -9
- package/src/tools/recall.js +208 -4
- package/src/tools/records-kit.js +2 -1
- package/src/tools/share.js +42 -3
- package/src/tools/shared.js +44 -4
- package/src/tools/space-lifecycle.js +278 -0
- package/src/tools/spaces.js +373 -29
- package/src/tools/status.js +9 -2
- package/src/tools/wiki.js +34 -4
- package/src/util.js +110 -6
- package/src/vendor/source-contract/README.md +24 -0
- package/src/vendor/source-contract/THIRD-PARTY-NOTICES.md +35 -0
- package/src/vendor/source-contract/VENDOR.json +81 -0
- package/src/vendor/source-contract/chunks/chunk-3M5PAKSS.js +84 -0
- package/src/vendor/source-contract/chunks/chunk-6HDIB2SA.js +183 -0
- package/src/vendor/source-contract/chunks/chunk-HLVAKAYG.js +10 -0
- package/src/vendor/source-contract/chunks/chunk-I2RXJJJM.js +81 -0
- package/src/vendor/source-contract/chunks/chunk-KWEWSZ4V.js +505 -0
- package/src/vendor/source-contract/chunks/chunk-W5SHR7DQ.js +9477 -0
- package/src/vendor/source-contract/chunks/chunk-ZUKF7P6U.js +653 -0
- package/src/vendor/source-contract/cursor.js +26 -0
- package/src/vendor/source-contract/events.js +257 -0
- package/src/vendor/source-contract/registry.js +23 -0
- package/src/vendor/source-contract/tools-rpc.js +42 -0
- package/src/views/access-reads.js +256 -0
- package/src/views/communities.js +77 -0
- package/src/views/contracts.js +1183 -36
- package/src/views/inbox-bytes.js +103 -0
- package/src/views/overdue.js +1 -1
- package/src/views/profile.js +31 -0
- package/src/views/receipt.js +81 -0
- package/src/views/records-reads.js +869 -37
- package/src/views/rpc.js +159 -11
- package/src/views/shape.js +8 -5
- package/views/memory.html +16 -3
- package/views/pages.html +2 -2
- package/views/remembered.html +130 -0
|
@@ -0,0 +1,772 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What Memory's declared sources answer (`package.json#sources`, contract
|
|
3
|
+
* version 1; app#2346 §2.1 and §2.3).
|
|
4
|
+
*
|
|
5
|
+
* Every read is made the way Memory's tools make one: the person is the
|
|
6
|
+
* session's own credential (`asSession`), the spaces are the ones the control
|
|
7
|
+
* plane lists for that person, and the records service scopes each call. A read
|
|
8
|
+
* never names a space the caller cannot list, so **a source never returns
|
|
9
|
+
* another person's private memory**; a shared space's members and grants are
|
|
10
|
+
* what that space's own access rules let the caller see, which is control's
|
|
11
|
+
* answer and not this file's.
|
|
12
|
+
*
|
|
13
|
+
* The result shapes are the contract's:
|
|
14
|
+
*
|
|
15
|
+
* - a snapshot `{ source, plugin, account, owner, asOf, trust, data, cost }`,
|
|
16
|
+
* `data` valid against the source's declared `output`;
|
|
17
|
+
* - an events page `{ …, events, cursor, more, refused, failed, gap?, cost }`;
|
|
18
|
+
* - a probe `{ account, owner, scopes }`, which reads no content.
|
|
19
|
+
*
|
|
20
|
+
* Every text field is untrusted data (`trust: "untrusted"`): it is what a
|
|
21
|
+
* person or a model wrote into memory, never an instruction.
|
|
22
|
+
*
|
|
23
|
+
* The events are built with the package's `makeEvent`, `screenEvents` and
|
|
24
|
+
* `fitPage`. The page itself is assembled here rather than with
|
|
25
|
+
* `eventsListResult`, because that module's `resultProblems` requires a page's
|
|
26
|
+
* `source` to be a bare word (`gmail`) while §2.2 and the conformance kit
|
|
27
|
+
* require the source's id (`mem.suggestions`); the kit's page checks are the
|
|
28
|
+
* ones this repository answers to.
|
|
29
|
+
*/
|
|
30
|
+
import os from "node:os"
|
|
31
|
+
import { PACKAGE_NAME } from "../credentials.js"
|
|
32
|
+
import { codedMessage } from "../errors.js"
|
|
33
|
+
import { oneLine } from "../util.js"
|
|
34
|
+
import { RECORD_ID } from "../tools/records-kit.js"
|
|
35
|
+
import { checkOutput } from "../vendor/source-contract/registry.js"
|
|
36
|
+
import { decodeBoundCursor, encodeBoundCursor } from "../vendor/source-contract/cursor.js"
|
|
37
|
+
import { makeEvent, screenEvents } from "../vendor/source-contract/events.js"
|
|
38
|
+
import { PROBE_ACTION, SOURCE_BY_ID } from "./declaration.js"
|
|
39
|
+
|
|
40
|
+
/** The plugin every result names: the package name its descriptor is read from. */
|
|
41
|
+
export const PLUGIN = PACKAGE_NAME
|
|
42
|
+
|
|
43
|
+
/** The source-id prefix of every declared source (`mem` in `mem.suggestions`): the plugin a cursor binds
|
|
44
|
+
* (the contract's D16 (b)), and the namespace an `x-mem/<kind>` event carries. */
|
|
45
|
+
export const NAMESPACE = "mem"
|
|
46
|
+
|
|
47
|
+
/** The account a read answers when the sign-in names nobody (local direct mode). */
|
|
48
|
+
export const DEFAULT_ACCOUNT = "default"
|
|
49
|
+
|
|
50
|
+
/** One answer holds at most this much, whatever the source declares (the contract's ceiling is 1 MB). */
|
|
51
|
+
const ANSWER_BYTES = 64 * 1024
|
|
52
|
+
/** Spaces one read covers, in the order control lists them. */
|
|
53
|
+
export const MAX_SPACES = 20
|
|
54
|
+
/** Records one `records.list` page holds. */
|
|
55
|
+
const LIST_LIMIT = 200
|
|
56
|
+
/** Pages one space's list read follows: 1,000 records, then the read says it was capped. */
|
|
57
|
+
const LIST_PAGES = 5
|
|
58
|
+
/** Events one page holds, and the most a caller may ask for. */
|
|
59
|
+
const PAGE_DEFAULT = 100
|
|
60
|
+
const PAGE_MAX = 500
|
|
61
|
+
/** Names one answer holds. */
|
|
62
|
+
const NAMES_MAX = 500
|
|
63
|
+
/** Titles one page search answers. */
|
|
64
|
+
const SEARCH_MAX = 50
|
|
65
|
+
|
|
66
|
+
/** A refusal in the contract's error table, in the family's words. */
|
|
67
|
+
export class SourceRefusal extends Error {
|
|
68
|
+
constructor(code, what, next) {
|
|
69
|
+
super(codedMessage(code, what, next))
|
|
70
|
+
this.name = "SourceRefusal"
|
|
71
|
+
this.code = code
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** @returns {never} */
|
|
76
|
+
const refuse = (code, what, next) => {
|
|
77
|
+
throw new SourceRefusal(code, what, next)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A source's name within the plugin: what its descriptor's `input.source` names, and what its page answers
|
|
81
|
+
* (the contract's page `source` is a lowercase word; the item's own id is dotted, `mem.names`). */
|
|
82
|
+
export const sourceNameOf = (item) => String(item?.input?.source ?? item?.id ?? "")
|
|
83
|
+
|
|
84
|
+
/** The descriptor item for an id or a source name, or a refusal. */
|
|
85
|
+
export function sourceItemOf(source) {
|
|
86
|
+
const asked = String(source ?? "")
|
|
87
|
+
const item = SOURCE_BY_ID.get(asked) ?? [...SOURCE_BY_ID.values()].find((entry) => sourceNameOf(entry) === asked)
|
|
88
|
+
if (!item) {
|
|
89
|
+
refuse(
|
|
90
|
+
"UNAVAILABLE",
|
|
91
|
+
`${PLUGIN} declares no source ${JSON.stringify(asked)}`,
|
|
92
|
+
"Read the descriptor from the installed package for the sources it declares.",
|
|
93
|
+
)
|
|
94
|
+
}
|
|
95
|
+
return item
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const plain = (value) => typeof value === "object" && value !== null && !Array.isArray(value)
|
|
99
|
+
|
|
100
|
+
/** A space, as every item names it. */
|
|
101
|
+
const spaceRef = (entry) => ({ id: String(entry?.space_id ?? entry?.id ?? "unknown"), name: oneLine(entry?.name ?? "", 200) })
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The source reads, over one runtime (the plugin's `src/runtime.js`).
|
|
105
|
+
*
|
|
106
|
+
* @param {{ runtime: any }} input
|
|
107
|
+
*/
|
|
108
|
+
export function createSourceReads({ runtime }) {
|
|
109
|
+
/**
|
|
110
|
+
* The caller's scope, without the session (a space and a session sent together
|
|
111
|
+
* would bind it), and **with the caller's own account**: the verified sign-in's,
|
|
112
|
+
* never the host's user, so the gateway and control scope by the person.
|
|
113
|
+
*/
|
|
114
|
+
function scopeOf(sessionID, account) {
|
|
115
|
+
const scope = runtime.scope({ sessionID, ...(account ? { user: account } : {}) })
|
|
116
|
+
delete scope.session_id
|
|
117
|
+
return scope
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Refuse before any request while memory cannot answer. */
|
|
121
|
+
function available() {
|
|
122
|
+
const reason = String(runtime.unavailable?.() ?? "")
|
|
123
|
+
if (!reason) return
|
|
124
|
+
// Already in the family's form (`CODE: … Next step: …`): keep its words.
|
|
125
|
+
const match = /^([A-Z][A-Z0-9_]*): (.*?) Next step: (.+)$/su.exec(reason)
|
|
126
|
+
if (match) throw new SourceRefusal(match[1], match[2], match[3])
|
|
127
|
+
refuse("UNAVAILABLE", reason, "Set Memory up, then read again.")
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The person a read and a probe both answer for: the account their own
|
|
132
|
+
* verified Jelly sign-in names (`runtime.verifiedAccount`, from the session's
|
|
133
|
+
* token), or, in local direct mode where there is no sign-in and Memory's own
|
|
134
|
+
* store serves the reads, this host's user with the synthetic owner
|
|
135
|
+
* `os-user:<user>@<host>` / `<user> on <host>`.
|
|
136
|
+
*
|
|
137
|
+
* Every owner id is **scheme-qualified** (source-contract#29): a gateway's
|
|
138
|
+
* sign-in answers `memory:<account>`, local direct mode `os-user:<user>@<host>`.
|
|
139
|
+
* The scheme says what the id's authority is, so two owners from different
|
|
140
|
+
* systems can never collide.
|
|
141
|
+
*
|
|
142
|
+
* **The probe and the reads agree:** a consumer binds the owner the probe named
|
|
143
|
+
* and then reads as that owner, in both modes. A gateway with no per-person
|
|
144
|
+
* sign-in refuses with `NEEDS_SIGN_IN`, because there the host is not the
|
|
145
|
+
* person and one host has many members.
|
|
146
|
+
*/
|
|
147
|
+
async function identityOf(sessionID) {
|
|
148
|
+
const account = oneLine((await runtime.verifiedAccount?.()) ?? "", 200)
|
|
149
|
+
if (account) return { account, owner: { id: `memory:${account}`, label: account } }
|
|
150
|
+
if (!runtime.control) {
|
|
151
|
+
const user = oneLine(String(runtime.config?.user ?? os.userInfo().username ?? ""), 60) || "local"
|
|
152
|
+
const host = os.hostname()
|
|
153
|
+
return { account: user, owner: { id: `os-user:${user}@${host}`, label: `${user} on ${host}` } }
|
|
154
|
+
}
|
|
155
|
+
refuse(
|
|
156
|
+
"NEEDS_SIGN_IN",
|
|
157
|
+
"no per-person Memory sign-in names the caller",
|
|
158
|
+
"Sign in to Jelly on this host as the person reading, then read again; a saved memory key is not a person.",
|
|
159
|
+
)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Refuse a read whose `account` is not this sign-in's: another account is another person. */
|
|
163
|
+
function checkAccount(input, account) {
|
|
164
|
+
const asked = typeof input?.account === "string" ? input.account.trim() : ""
|
|
165
|
+
if (asked && asked !== account) {
|
|
166
|
+
refuse(
|
|
167
|
+
"ACCOUNT_MISMATCH",
|
|
168
|
+
`${input?.source ?? "this source"} is signed in as ${account}, not ${asked}`,
|
|
169
|
+
"Read the account probe answers, or sign in to the account you mean.",
|
|
170
|
+
)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The person's spaces, as control lists them; local direct mode has the one store. */
|
|
175
|
+
async function spacesOf(account) {
|
|
176
|
+
if (!runtime.control) return [{ space_id: "local", name: "Local memory", kind: "personal", role: "owner" }]
|
|
177
|
+
const listed = (await runtime.control.listSpaces({ userId: account })) ?? []
|
|
178
|
+
return listed
|
|
179
|
+
.filter((entry) => typeof entry?.space_id === "string" && entry.space_id)
|
|
180
|
+
.slice(0, MAX_SPACES)
|
|
181
|
+
.map((entry) => ({ space_id: entry.space_id, name: entry.name ?? "", kind: entry.kind ?? "unknown", role: entry.role ?? "" }))
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* A source that only a control plane can answer: a space's members and its
|
|
186
|
+
* grants. Local direct mode holds one person's memory and no rosters or grants,
|
|
187
|
+
* so its read **and its probe** refuse with this one sentence — a consumer can
|
|
188
|
+
* never bind a source that its own mode cannot read.
|
|
189
|
+
*/
|
|
190
|
+
function controlOnly(item) {
|
|
191
|
+
refuse(
|
|
192
|
+
"UNAVAILABLE",
|
|
193
|
+
`${item.id} reads a memory service's members and grants, and local direct mode has none`,
|
|
194
|
+
"Set Memory's address, or run Memory as a signed-in service, then read this source again; local direct mode holds one person's memory and no rosters or grants.",
|
|
195
|
+
)
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** One space the caller named, checked against the spaces control lists for them. */
|
|
199
|
+
async function namedSpace(space, account) {
|
|
200
|
+
const wanted = String(space ?? "").trim()
|
|
201
|
+
const spaces = await spacesOf(account)
|
|
202
|
+
if (!wanted) {
|
|
203
|
+
if (spaces.length === 1) return spaces[0]
|
|
204
|
+
refuse("SCHEMA_VIOLATION", "this read needs a space", 'Pass the space its page shows, such as {"space": "spc_…"}.')
|
|
205
|
+
}
|
|
206
|
+
const found = spaces.find((entry) => entry.space_id === wanted)
|
|
207
|
+
if (!found) {
|
|
208
|
+
refuse("PERMISSION_DENIED", `space ${wanted} is not one of yours`, "Read the spaces Memory lists for you, then name one of those.")
|
|
209
|
+
}
|
|
210
|
+
return found
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** One records read, through the runtime's client, in the person's own credential. */
|
|
214
|
+
function records(method, body, space, sessionID, account) {
|
|
215
|
+
if (!["records.list", "records.search", "space.suggestion-optouts"].includes(method)) {
|
|
216
|
+
refuse("UNAVAILABLE", `${method} is not a read this plugin performs`, "Report this to Memory's maintainers.")
|
|
217
|
+
}
|
|
218
|
+
if (typeof runtime.recordsClient?.call !== "function") {
|
|
219
|
+
refuse("UNAVAILABLE", "this build has no records client", "Update opencode-mem.")
|
|
220
|
+
}
|
|
221
|
+
return runtime.recordsClient.call(method, body, { scope: scopeOf(sessionID, account), space: space?.space_id })
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* `records.list` over the spaces given, following each space's cursor up to
|
|
226
|
+
* `pages` pages (a list read answers 200 records at a time): a read that took
|
|
227
|
+
* only the newest page would silently miss older records. A space that failed
|
|
228
|
+
* is named, not thrown; `capped` says the bound cut a space short.
|
|
229
|
+
*/
|
|
230
|
+
async function listIn(spaces, body, sessionID, account, { pages = LIST_PAGES } = {}) {
|
|
231
|
+
const listed = []
|
|
232
|
+
const failed = []
|
|
233
|
+
let capped = false
|
|
234
|
+
for (const entry of spaces) {
|
|
235
|
+
const rows = []
|
|
236
|
+
let cursor = null
|
|
237
|
+
for (let page = 0; page < pages; page += 1) {
|
|
238
|
+
try {
|
|
239
|
+
const answer = await records("records.list", { ...body, ...(cursor ? { cursor } : {}) }, entry, sessionID, account)
|
|
240
|
+
rows.push(...(Array.isArray(answer?.records) ? answer.records : []))
|
|
241
|
+
cursor = typeof answer?.cursor === "string" && answer.cursor ? answer.cursor : null
|
|
242
|
+
} catch (error) {
|
|
243
|
+
failed.push({ space: entry, error })
|
|
244
|
+
break
|
|
245
|
+
}
|
|
246
|
+
if (!cursor) break
|
|
247
|
+
}
|
|
248
|
+
if (cursor) capped = true
|
|
249
|
+
listed.push({ space: entry, records: rows })
|
|
250
|
+
}
|
|
251
|
+
if (listed.length === 0 && failed.length > 0) throw failed[0].error
|
|
252
|
+
return { listed, failed, capped }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Add items while the whole answer fits its byte cap **and** the list's own
|
|
257
|
+
* most (the output schema's `maxItems`), never past either; true when some
|
|
258
|
+
* were left out. A cut is never silent: the answer's `more` says so.
|
|
259
|
+
*/
|
|
260
|
+
function fit(answer, key, items, most = Number.POSITIVE_INFINITY) {
|
|
261
|
+
for (const [index, item] of items.entries()) {
|
|
262
|
+
if (index >= most) return true
|
|
263
|
+
answer[key].push(item)
|
|
264
|
+
if (Buffer.byteLength(JSON.stringify(answer)) > ANSWER_BYTES) {
|
|
265
|
+
answer[key].pop()
|
|
266
|
+
return true
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return false
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** The envelope every answer carries. */
|
|
273
|
+
function envelope(item, identity, body, asOf = new Date().toISOString()) {
|
|
274
|
+
return { source: sourceNameOf(item), plugin: PLUGIN, account: identity.account, owner: identity.owner, asOf, trust: "untrusted", ...body }
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* A snapshot answer, its `data` held to its output before it is sent: the
|
|
279
|
+
* registry's schema for a registry name, or the item's own inline
|
|
280
|
+
* `outputSchema` for an `x-mem/<name>` output. The same check a consumer's
|
|
281
|
+
* `checkOutput` makes, so an answer is never shaped only for the tests.
|
|
282
|
+
*/
|
|
283
|
+
function snapshot(item, identity, data, asOf = new Date().toISOString()) {
|
|
284
|
+
const checked = checkOutput(String(item.output ?? ""), data, item.outputSchema)
|
|
285
|
+
if (!checked.ok) {
|
|
286
|
+
refuse(
|
|
287
|
+
"SCHEMA_VIOLATION",
|
|
288
|
+
`${item.id} would answer data its ${item.output} schema refuses: ${checked.problems.slice(0, 2).join("; ")}`,
|
|
289
|
+
"Report this to Memory's maintainers.",
|
|
290
|
+
)
|
|
291
|
+
}
|
|
292
|
+
return envelope(item, identity, { data }, asOf)
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** The declared item for a source id this read serves. */
|
|
296
|
+
function itemOf(source, kind) {
|
|
297
|
+
const item = sourceItemOf(source)
|
|
298
|
+
if (item.kind !== kind) refuse("UNAVAILABLE", `${item.id} is a ${item.kind} source, not a ${kind} one`, "Call the method its descriptor names.")
|
|
299
|
+
return item
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** The spaces a read covers: the one named, or all of the caller's. */
|
|
303
|
+
async function spacesFor(input, account) {
|
|
304
|
+
return input?.space ? [await namedSpace(input.space, account)] : spacesOf(account)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// ── S1: mem.turn-receipts ────────────────────────────────────────────────────
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* What Memory saved because of one turn: the records whose `source.session` is
|
|
311
|
+
* the session, and whose `source.turn` is the turn when one is named.
|
|
312
|
+
*/
|
|
313
|
+
async function receipts_read(input, call) {
|
|
314
|
+
available()
|
|
315
|
+
const item = itemOf("mem.turn-receipts", "snapshot")
|
|
316
|
+
const identity = await identityOf(call.sessionID)
|
|
317
|
+
checkAccount(input, identity.account)
|
|
318
|
+
const session = String(input?.session ?? "").trim()
|
|
319
|
+
if (!session) refuse("SCHEMA_VIOLATION", "this read needs a session", 'Pass the session whose turn to read, such as {"session": "ses_…"}.')
|
|
320
|
+
const turn = typeof input?.turn === "string" ? input.turn.trim() : ""
|
|
321
|
+
const { listed, failed } = await listIn(await spacesFor(input, identity.account), { source_session: session, limit: LIST_LIMIT }, call.sessionID, identity.account)
|
|
322
|
+
const saved = []
|
|
323
|
+
let at = ""
|
|
324
|
+
for (const entry of listed) {
|
|
325
|
+
for (const record of entry.records) {
|
|
326
|
+
const origin = plain(record?.source) ? record.source : {}
|
|
327
|
+
if (turn && origin.turn !== turn) continue
|
|
328
|
+
const id = String(record?.id ?? "")
|
|
329
|
+
if (!RECORD_ID.test(id)) continue
|
|
330
|
+
saved.push({
|
|
331
|
+
id,
|
|
332
|
+
kind: oneLine(record?.kind ?? "", 40),
|
|
333
|
+
text: oneLine(record?.title ?? "", 300),
|
|
334
|
+
space: spaceRef(entry.space),
|
|
335
|
+
})
|
|
336
|
+
if (typeof record?.updated === "string" && record.updated > at) at = record.updated
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (saved.length === 0 && failed.length > 0) throw failed[0].error
|
|
340
|
+
const asOf = at || new Date().toISOString()
|
|
341
|
+
const data = { session, turn: turn || null, at: asOf, saved: [], more: false }
|
|
342
|
+
data.more = fit(data, "saved", saved, 500)
|
|
343
|
+
return snapshot(item, identity, data, asOf)
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// ── S2: mem.names ────────────────────────────────────────────────────────────
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* The people and names Memory knows, as the registered `list` output: one item
|
|
350
|
+
* per person, project or team page, its type and any aliases in `note`.
|
|
351
|
+
*/
|
|
352
|
+
async function names_list(input, call) {
|
|
353
|
+
available()
|
|
354
|
+
const item = itemOf("mem.names", "snapshot")
|
|
355
|
+
const identity = await identityOf(call.sessionID)
|
|
356
|
+
checkAccount(input, identity.account)
|
|
357
|
+
const max = input?.max === undefined ? NAMES_MAX : Number(input.max)
|
|
358
|
+
if (!Number.isInteger(max) || max < 1 || max > NAMES_MAX) refuse("SCHEMA_VIOLATION", `max is a whole number from 1 to ${NAMES_MAX}`, "Pass a whole number in that range.")
|
|
359
|
+
const { listed, failed, capped } = await listIn(await spacesFor(input, identity.account), { kind: "page", limit: LIST_LIMIT }, call.sessionID, identity.account)
|
|
360
|
+
// A list output has no room to say "there is more", and a name list that
|
|
361
|
+
// silently stopped would teach a spell-checker half the names: refuse and
|
|
362
|
+
// say how to narrow it instead.
|
|
363
|
+
if (capped) {
|
|
364
|
+
refuse(
|
|
365
|
+
"TOO_LARGE",
|
|
366
|
+
`this memory holds more pages than one read covers (${LIST_PAGES} pages of ${LIST_LIMIT} records a space)`,
|
|
367
|
+
"Name one space with {space}, then read again.",
|
|
368
|
+
)
|
|
369
|
+
}
|
|
370
|
+
const seen = new Set()
|
|
371
|
+
const items = []
|
|
372
|
+
for (const entry of listed) {
|
|
373
|
+
for (const record of entry.records) {
|
|
374
|
+
const type = String(record?.type ?? "")
|
|
375
|
+
if (!["person", "project", "team"].includes(type)) continue
|
|
376
|
+
const name = oneLine(record?.title || String(record?.path ?? "").split("/").pop() || "", 200)
|
|
377
|
+
if (!name || seen.has(name.toLowerCase())) continue
|
|
378
|
+
seen.add(name.toLowerCase())
|
|
379
|
+
const aliases = (Array.isArray(record?.fields?.aliases) ? record.fields.aliases : []).map((alias) => oneLine(alias, 80)).filter(Boolean)
|
|
380
|
+
items.push({ id: name, text: name, note: oneLine([type, ...aliases].join(" · "), 300) })
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (items.length === 0 && failed.length > 0) throw failed[0].error
|
|
384
|
+
const data = { items: [], editable: false }
|
|
385
|
+
if (fit(data, "items", items.slice(0, max))) {
|
|
386
|
+
refuse("TOO_LARGE", "the names do not fit one answer", "Name one space with {space}, or ask for fewer with {max}.")
|
|
387
|
+
}
|
|
388
|
+
return snapshot(item, identity, data)
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// ── S3a: mem.members ─────────────────────────────────────────────────────────
|
|
392
|
+
|
|
393
|
+
/** Control's membership roles, in the contract's words. */
|
|
394
|
+
const ROLE = Object.freeze({
|
|
395
|
+
owner: "owner",
|
|
396
|
+
admin: "admin",
|
|
397
|
+
editor: "writer",
|
|
398
|
+
writer: "writer",
|
|
399
|
+
viewer: "reader",
|
|
400
|
+
reader: "reader",
|
|
401
|
+
member: "reader",
|
|
402
|
+
})
|
|
403
|
+
|
|
404
|
+
/** Who is in one space, as that space's own access rules let the caller see it. */
|
|
405
|
+
async function members_read(input, call) {
|
|
406
|
+
available()
|
|
407
|
+
const item = itemOf("mem.members", "snapshot")
|
|
408
|
+
const identity = await identityOf(call.sessionID)
|
|
409
|
+
checkAccount(input, identity.account)
|
|
410
|
+
if (!runtime.control) controlOnly(item)
|
|
411
|
+
const space = await namedSpace(input?.space, identity.account)
|
|
412
|
+
const roster = (await runtime.control.listMembers({ userId: identity.account, spaceId: space.space_id })) ?? []
|
|
413
|
+
const data = { space: spaceRef(space), members: [], more: false }
|
|
414
|
+
data.more = fit(
|
|
415
|
+
data,
|
|
416
|
+
"members",
|
|
417
|
+
roster
|
|
418
|
+
.filter((member) => typeof member?.user_id === "string" && member.user_id)
|
|
419
|
+
.map((member) => ({
|
|
420
|
+
person: member.user_id,
|
|
421
|
+
label: oneLine(member.name || member.email || member.user_id, 200),
|
|
422
|
+
role: ROLE[String(member.role ?? "").toLowerCase()] ?? "reader",
|
|
423
|
+
})),
|
|
424
|
+
500,
|
|
425
|
+
)
|
|
426
|
+
return snapshot(item, identity, data)
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// ── S3b: mem.grants ──────────────────────────────────────────────────────────
|
|
430
|
+
|
|
431
|
+
/** What a grant is attached to, in the contract's words. */
|
|
432
|
+
const VIA = Object.freeze({ space: "space", wiki: "wiki", wiki_page: "page", page: "page", folder: "folder", records: "page", resource: "page" })
|
|
433
|
+
|
|
434
|
+
/** Who a space, wiki, folder or page is shared with. */
|
|
435
|
+
async function grants_read(input, call) {
|
|
436
|
+
available()
|
|
437
|
+
const item = itemOf("mem.grants", "snapshot")
|
|
438
|
+
const identity = await identityOf(call.sessionID)
|
|
439
|
+
checkAccount(input, identity.account)
|
|
440
|
+
if (!runtime.control) controlOnly(item)
|
|
441
|
+
const space = await namedSpace(input?.space, identity.account)
|
|
442
|
+
const target = typeof input?.target === "string" ? input.target.trim() : ""
|
|
443
|
+
if (target && !RECORD_ID.test(target) && !/^[a-z0-9][a-z0-9/_-]{0,300}$/.test(target)) {
|
|
444
|
+
refuse("SCHEMA_VIOLATION", "target is not a resource id", "Pass the id its page shows, or leave it out for the whole space.")
|
|
445
|
+
}
|
|
446
|
+
// Control answers one target's grants (`target_type` with `target_id`), and
|
|
447
|
+
// for a key without one it answers **only the grants that name the caller**
|
|
448
|
+
// (`deploy/auth/space-admin-api.mjs`: "without resource_id: the grants naming
|
|
449
|
+
// the caller"). A space's every grant is the console's browser session, never
|
|
450
|
+
// a key's, so the no-target answer says `mine` and not `space`.
|
|
451
|
+
const ask = async (options) => (await runtime.control.listGrants({ userId: identity.account, spaceId: space.space_id, ...options })) ?? []
|
|
452
|
+
let grants
|
|
453
|
+
let scope = "mine"
|
|
454
|
+
if (target) {
|
|
455
|
+
scope = "target"
|
|
456
|
+
grants = await ask({ targetType: "resource", targetId: target })
|
|
457
|
+
} else {
|
|
458
|
+
grants = await ask({ scope: "mine" })
|
|
459
|
+
}
|
|
460
|
+
const data = { space: spaceRef(space), scope, grants: [], more: false }
|
|
461
|
+
data.more = fit(
|
|
462
|
+
data,
|
|
463
|
+
"grants",
|
|
464
|
+
grants
|
|
465
|
+
.filter((grant) => typeof grant?.principal_id === "string" && grant.principal_id)
|
|
466
|
+
.map((grant) => ({
|
|
467
|
+
subject: { [grant.principal_type === "team" ? "team" : "person"]: grant.principal_id },
|
|
468
|
+
access: ROLE[String(grant.role ?? "").toLowerCase()] ?? "reader",
|
|
469
|
+
via: VIA[String(grant.target_type ?? "space")] ?? "space",
|
|
470
|
+
// When it started, not when it ends: `expires_at` is not a `since`.
|
|
471
|
+
...(typeof grant?.created_at === "string" && grant.created_at ? { since: oneLine(grant.created_at, 40) } : {}),
|
|
472
|
+
})),
|
|
473
|
+
500,
|
|
474
|
+
)
|
|
475
|
+
return snapshot(item, identity, data)
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// ── S4: mem.spaces-to-join ───────────────────────────────────────────────────
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* The shared spaces the person may join, as control answers
|
|
482
|
+
* `GET /v1/spaces/joinable` (#58 A11): the organisation's open ones they are
|
|
483
|
+
* not in, marked `join: "open"` — a grant never lists a space, so an
|
|
484
|
+
* invite-only one is offered only as the request that still stands
|
|
485
|
+
* (`join: "request"`, `yourRequest: "pending"`, no name), and the gateway's
|
|
486
|
+
* read drops that unnamed row. Control decides all of it — visibility,
|
|
487
|
+
* archived spaces and membership — so this read never filters `listSpaces`
|
|
488
|
+
* itself. Local direct mode has one store and no one to ask, so it answers
|
|
489
|
+
* none.
|
|
490
|
+
*/
|
|
491
|
+
async function spaces_joinable_read(input, call) {
|
|
492
|
+
available()
|
|
493
|
+
const item = itemOf("mem.spaces-to-join", "snapshot")
|
|
494
|
+
const identity = await identityOf(call.sessionID)
|
|
495
|
+
checkAccount(input, identity.account)
|
|
496
|
+
const answer =
|
|
497
|
+
runtime.control && typeof runtime.control.joinableSpaces === "function"
|
|
498
|
+
? await runtime.control.joinableSpaces({ userId: identity.account })
|
|
499
|
+
: null
|
|
500
|
+
const rows = answer?.spaces ?? []
|
|
501
|
+
const data = { spaces: [], more: false }
|
|
502
|
+
const bounded = fit(
|
|
503
|
+
data,
|
|
504
|
+
"spaces",
|
|
505
|
+
rows
|
|
506
|
+
.filter((entry) => plain(entry) && typeof entry.space === "string" && entry.space && typeof entry.name === "string" && entry.name)
|
|
507
|
+
.map((entry) => ({
|
|
508
|
+
space: oneLine(entry.space, 200),
|
|
509
|
+
name: oneLine(entry.name, 200),
|
|
510
|
+
kind: entry.kind === "topic" ? "topic" : "team",
|
|
511
|
+
...(typeof entry.about === "string" && entry.about ? { about: oneLine(entry.about, 300) } : {}),
|
|
512
|
+
...(Number.isInteger(entry.members) && entry.members >= 0 ? { members: entry.members } : {}),
|
|
513
|
+
// `space.join` carries both ops (`join` and `request`) in the actions
|
|
514
|
+
// lane; this read passes control's own offer through.
|
|
515
|
+
join: entry.join === "open" ? "open" : "request",
|
|
516
|
+
...(entry.yourRequest === "pending" ? { yourRequest: "pending" } : {}),
|
|
517
|
+
})),
|
|
518
|
+
200,
|
|
519
|
+
)
|
|
520
|
+
// A cut by this read, or by control's own bound, is never called complete.
|
|
521
|
+
data.more = bounded || answer?.more === true
|
|
522
|
+
return snapshot(item, identity, data)
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// ── S5: mem.meeting-records ──────────────────────────────────────────────────
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* What one meeting produced: the records its items became (`kept`) and the
|
|
529
|
+
* proposals still waiting (`waiting`).
|
|
530
|
+
*
|
|
531
|
+
* A forgotten record is purged — its text is gone from the store and only a
|
|
532
|
+
* salted fingerprint stays — so Memory cannot say "forgotten" for one meeting,
|
|
533
|
+
* and this read does not invent that state.
|
|
534
|
+
*/
|
|
535
|
+
async function meeting_records_read(input, call) {
|
|
536
|
+
available()
|
|
537
|
+
const item = itemOf("mem.meeting-records", "snapshot")
|
|
538
|
+
const identity = await identityOf(call.sessionID)
|
|
539
|
+
checkAccount(input, identity.account)
|
|
540
|
+
const meeting = String(input?.meeting ?? "").trim()
|
|
541
|
+
if (!meeting) refuse("SCHEMA_VIOLATION", "this read needs a meeting", 'Pass the meeting the record names, such as {"meeting": "evt_…"}.')
|
|
542
|
+
const { listed, failed, capped } = await listIn(await spacesFor(input, identity.account), { limit: LIST_LIMIT }, call.sessionID, identity.account)
|
|
543
|
+
const records = []
|
|
544
|
+
for (const entry of listed) {
|
|
545
|
+
for (const record of entry.records) {
|
|
546
|
+
const origin = plain(record?.source) ? record.source : {}
|
|
547
|
+
const fields = plain(record?.fields) ? record.fields : {}
|
|
548
|
+
if (origin.event !== meeting && fields.meeting !== meeting) continue
|
|
549
|
+
const id = String(record?.id ?? "")
|
|
550
|
+
if (!RECORD_ID.test(id)) continue
|
|
551
|
+
records.push({
|
|
552
|
+
id,
|
|
553
|
+
text: oneLine(record?.title ?? "", 300),
|
|
554
|
+
state: record?.kind === "proposal" ? "waiting" : "kept",
|
|
555
|
+
space: spaceRef(entry.space),
|
|
556
|
+
})
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
if (records.length === 0 && failed.length > 0) throw failed[0].error
|
|
560
|
+
const data = { meeting, records: [], more: capped }
|
|
561
|
+
data.more = fit(data, "records", records, 500) || data.more
|
|
562
|
+
return snapshot(item, identity, data)
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/** One suggestion as an event, or null when the record has no readable time. */
|
|
566
|
+
function buildable(entry, account, named) {
|
|
567
|
+
const at = Date.parse(String(entry.record.created ?? ""))
|
|
568
|
+
if (Number.isNaN(at)) return null
|
|
569
|
+
return makeEvent({
|
|
570
|
+
source: named,
|
|
571
|
+
account,
|
|
572
|
+
external_id: String(entry.record.id),
|
|
573
|
+
kind: "x-mem/suggestion",
|
|
574
|
+
occurred_at: new Date(at).toISOString(),
|
|
575
|
+
thread: `mem-turn:${entry.session}:${entry.turn || "none"}`,
|
|
576
|
+
actors: [{ role: "memory", id: `memory:${account}` }],
|
|
577
|
+
title: oneLine(entry.record.title ?? "", 300),
|
|
578
|
+
text: oneLine(entry.record.body ?? "", 4096),
|
|
579
|
+
url: null,
|
|
580
|
+
labels: [`session:${entry.session}`, `turn:${entry.turn || "none"}`, `space:${entry.space}`, "x-mem/suggestion"],
|
|
581
|
+
})
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// ── S6: mem.suggestions ──────────────────────────────────────────────────────
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* A turn's record worth sharing, as events of kind `x-mem/suggestion`.
|
|
588
|
+
*
|
|
589
|
+
* A suggestion is what Memory proposes for a space: a held proposal that names
|
|
590
|
+
* the space it would help and the session and turn it came from. Agents never
|
|
591
|
+
* publish to a shared space themselves, so nothing else appears here.
|
|
592
|
+
*
|
|
593
|
+
* What the card draws rides the event: `thread` is the turn, `labels` name the
|
|
594
|
+
* session, turn and target space, `title` and `text` are the record's own.
|
|
595
|
+
*/
|
|
596
|
+
async function events_list(input, call) {
|
|
597
|
+
available()
|
|
598
|
+
const item = itemOf("mem.suggestions", "events")
|
|
599
|
+
const identity = await identityOf(call.sessionID)
|
|
600
|
+
checkAccount(input, identity.account)
|
|
601
|
+
const limit = input?.limit === undefined ? PAGE_DEFAULT : Number(input.limit)
|
|
602
|
+
if (!Number.isInteger(limit) || limit < 0 || limit > PAGE_MAX) refuse("SCHEMA_VIOLATION", `limit is a whole number from 0 to ${PAGE_MAX}`, "Pass a whole number in that range.")
|
|
603
|
+
const binding = { plugin: NAMESPACE, source: sourceNameOf(item), account: identity.account }
|
|
604
|
+
let at = ""
|
|
605
|
+
if (input?.cursor !== undefined && input.cursor !== "") {
|
|
606
|
+
const decoded = decodeBoundCursor(binding, String(input.cursor))
|
|
607
|
+
if (!decoded.ok) refuse("CURSOR_INVALID", `that cursor is not ${item.id}'s for ${identity.account}`, "Start again with no cursor.")
|
|
608
|
+
at = String(decoded.state.at ?? "")
|
|
609
|
+
// History older than the retention window is gone: a proposal is pruned
|
|
610
|
+
// after its TTL, so a cursor that old cannot be resumed truthfully.
|
|
611
|
+
const seen = Date.parse(String(decoded.state.seen ?? ""))
|
|
612
|
+
const retentionMs = (item.retentionDays ?? 30) * 24 * 60 * 60 * 1000
|
|
613
|
+
if (!Number.isNaN(seen) && Date.now() - seen > retentionMs) {
|
|
614
|
+
return envelope(item, identity, {
|
|
615
|
+
events: [],
|
|
616
|
+
cursor: encodeBoundCursor(binding, { at: "", seen: new Date().toISOString() }),
|
|
617
|
+
more: false,
|
|
618
|
+
refused: [],
|
|
619
|
+
gap: { reason: "expired", since: new Date(Date.now() - retentionMs).toISOString() },
|
|
620
|
+
})
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
const spaces = await spacesOf(identity.account)
|
|
624
|
+
const asked = plain(input?.scope) ? Object.keys(input.scope).filter((key) => (Array.isArray(input.scope[key]) ? input.scope[key].length > 0 : Boolean(input.scope[key]))) : []
|
|
625
|
+
if (asked.length > 0) {
|
|
626
|
+
refuse("SCHEMA_VIOLATION", `${item.id} reads no scope, and ${asked.join(", ")} was passed`, "Leave scope out: this source reads the person's own proposals.")
|
|
627
|
+
}
|
|
628
|
+
const since = typeof input?.since === "string" && input.since ? input.since : ""
|
|
629
|
+
if (since && Number.isNaN(Date.parse(since))) refuse("SCHEMA_VIOLATION", "since is not a time", 'Pass an ISO date-time, or leave since out.')
|
|
630
|
+
const { listed, failed } = await listIn(spaces, { kind: "proposal", limit: LIST_LIMIT, ...(since ? { created_after: new Date(since).toISOString() } : {}) }, call.sessionID, identity.account)
|
|
631
|
+
// What each space has stopped suggesting (#77): a person's "never suggest
|
|
632
|
+
// this" is a row in that space's meta, kinds only. A space that cannot
|
|
633
|
+
// answer is a hole like any other, and the page says so below.
|
|
634
|
+
const off = new Map()
|
|
635
|
+
for (const entry of spaces) {
|
|
636
|
+
try {
|
|
637
|
+
const answer = await records("space.suggestion-optouts", {}, entry, call.sessionID, identity.account)
|
|
638
|
+
off.set(entry.space_id, new Set(Array.isArray(answer?.kinds) ? answer.kinds.filter((kind) => typeof kind === "string") : []))
|
|
639
|
+
} catch {
|
|
640
|
+
// not read: the kind is not known to be off, and nothing is hidden wrongly
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
const waiting = []
|
|
644
|
+
for (const entry of listed) {
|
|
645
|
+
for (const record of entry.records) {
|
|
646
|
+
const origin = plain(record?.source) ? record.source : {}
|
|
647
|
+
const fields = plain(record?.fields) ? record.fields : {}
|
|
648
|
+
const session = typeof origin.session === "string" ? origin.session : ""
|
|
649
|
+
const space = typeof fields.space_id === "string" ? fields.space_id : ""
|
|
650
|
+
if (!session || !space) continue
|
|
651
|
+
if (!["proposed", "accepting"].includes(String(record?.status ?? ""))) continue
|
|
652
|
+
// "Not now" hides that one; "Never suggest this" hides its kind in this
|
|
653
|
+
// space. Neither decides the proposal: it still waits in review.
|
|
654
|
+
if (typeof fields.suggestion_dismissed_at === "string" && fields.suggestion_dismissed_at) continue
|
|
655
|
+
const kind = typeof record?.type === "string" ? record.type : ""
|
|
656
|
+
if (kind && off.get(entry.space.space_id)?.has(kind)) continue
|
|
657
|
+
waiting.push({ record, session, turn: typeof origin.turn === "string" ? origin.turn : "", space })
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
waiting.sort((a, b) => String(a.record.created ?? "").localeCompare(String(b.record.created ?? "")) || String(a.record.id).localeCompare(String(b.record.id)))
|
|
661
|
+
const fresh = waiting.filter((entry) => !at || String(entry.record.created ?? "") > at)
|
|
662
|
+
// The page is filled one event at a time, so an event is never half answered:
|
|
663
|
+
// the answer's byte cap decides where the page stops, not the caller's limit.
|
|
664
|
+
const page = []
|
|
665
|
+
const drafted = []
|
|
666
|
+
const unbuildable = []
|
|
667
|
+
for (const entry of fresh.slice(0, limit)) {
|
|
668
|
+
const event = buildable(entry, identity.account, sourceNameOf(item))
|
|
669
|
+
if (!event) {
|
|
670
|
+
// A record the page cannot turn into an event is a retryable drop: it is
|
|
671
|
+
// named, and the cursor stays where it was so the window is read again.
|
|
672
|
+
unbuildable.push({ external_id: String(entry.record.id), code: "SCHEMA_VIOLATION" })
|
|
673
|
+
continue
|
|
674
|
+
}
|
|
675
|
+
if (Buffer.byteLength(JSON.stringify([...drafted, event])) > ANSWER_BYTES) break
|
|
676
|
+
page.push(entry)
|
|
677
|
+
drafted.push(event)
|
|
678
|
+
}
|
|
679
|
+
// The contract's refusal: instruction-shaped text or a secret is dropped for
|
|
680
|
+
// good, with a reason and no content; the consumer may advance past it.
|
|
681
|
+
const screened = screenEvents(drafted)
|
|
682
|
+
const refused = screened.refused
|
|
683
|
+
const held = String(input?.cursor ?? "")
|
|
684
|
+
if (failed.length > 0 || unbuildable.length > 0) {
|
|
685
|
+
// A space that could not be read, or a record the page could not build, is a hole in the window. A page
|
|
686
|
+
// always carries a cursor (the contract's page shape), and an entry in `failed[]` holds it back, so a
|
|
687
|
+
// resumed read answers the cursor it was called with. A first read has none to hold: it says the window
|
|
688
|
+
// is truncated, and the consumer reads the window again from the fresh cursor.
|
|
689
|
+
return envelope(item, identity, {
|
|
690
|
+
events: screened.events,
|
|
691
|
+
cursor: held || encodeBoundCursor(binding, { at: "", seen: new Date().toISOString() }),
|
|
692
|
+
more: true,
|
|
693
|
+
refused,
|
|
694
|
+
// A drop holds the cursor back, but only a read that had one can answer it: a first page has none, so
|
|
695
|
+
// it names the hole as a truncated window and issues the cursor the person's next read resumes from.
|
|
696
|
+
...(held && unbuildable.length > 0 ? { failed: unbuildable } : {}),
|
|
697
|
+
...(!held || failed.length > 0 ? { gap: { reason: "window-truncated", since: new Date().toISOString() } } : {}),
|
|
698
|
+
})
|
|
699
|
+
}
|
|
700
|
+
const last = page.at(-1)
|
|
701
|
+
const next = last
|
|
702
|
+
? encodeBoundCursor(binding, { at: String(last.record.created ?? ""), seen: new Date().toISOString() })
|
|
703
|
+
: held || encodeBoundCursor(binding, { at: "", seen: new Date().toISOString() })
|
|
704
|
+
return envelope(item, identity, {
|
|
705
|
+
events: screened.events,
|
|
706
|
+
cursor: next,
|
|
707
|
+
more: fresh.length > page.length,
|
|
708
|
+
refused,
|
|
709
|
+
})
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// ── S7: mem.pages-search ─────────────────────────────────────────────────────
|
|
713
|
+
|
|
714
|
+
/** Page titles for a query, as the registered `list` output: the `id` is the page's ref. */
|
|
715
|
+
async function pages_search(input, call) {
|
|
716
|
+
available()
|
|
717
|
+
const item = itemOf("mem.pages-search", "snapshot")
|
|
718
|
+
const identity = await identityOf(call.sessionID)
|
|
719
|
+
checkAccount(input, identity.account)
|
|
720
|
+
const query = String(input?.q ?? "").trim()
|
|
721
|
+
if (!query) refuse("SCHEMA_VIOLATION", "this read needs a query", 'Pass the words to look for, such as {"q": "staging port"}.')
|
|
722
|
+
const limit = input?.limit === undefined ? SEARCH_MAX : Number(input.limit)
|
|
723
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > SEARCH_MAX) refuse("SCHEMA_VIOLATION", `limit is a whole number from 1 to ${SEARCH_MAX}`, "Pass a whole number in that range.")
|
|
724
|
+
const items = []
|
|
725
|
+
const failures = []
|
|
726
|
+
for (const entry of await spacesFor(input, identity.account)) {
|
|
727
|
+
try {
|
|
728
|
+
const answer = await records("records.search", { query, kinds: ["page"], limit }, entry, call.sessionID, identity.account)
|
|
729
|
+
for (const hit of Array.isArray(answer?.hits) ? answer.hits : []) {
|
|
730
|
+
const ref = oneLine(hit?.path || hit?.id || "", 300)
|
|
731
|
+
if (!ref) continue
|
|
732
|
+
items.push({
|
|
733
|
+
id: ref,
|
|
734
|
+
text: oneLine(hit?.title || ref, 300),
|
|
735
|
+
note: oneLine([entry.name, hit?.path ?? ref].filter(Boolean).join(" · "), 300),
|
|
736
|
+
})
|
|
737
|
+
}
|
|
738
|
+
} catch (error) {
|
|
739
|
+
failures.push(error)
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
if (items.length === 0 && failures.length > 0) throw failures[0]
|
|
743
|
+
const data = { items: [], editable: false }
|
|
744
|
+
if (fit(data, "items", items.slice(0, limit))) {
|
|
745
|
+
refuse("TOO_LARGE", "the titles do not fit one answer", "Ask for fewer with {limit}, or name one space with {space}.")
|
|
746
|
+
}
|
|
747
|
+
return snapshot(item, identity, data)
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// ── probe ────────────────────────────────────────────────────────────────────
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* The signed-in account and owner, per source. It reads no content: the account
|
|
754
|
+
* is the session's own scope, and `scopes` names what this sign-in can read.
|
|
755
|
+
*/
|
|
756
|
+
async function probe(input, call) {
|
|
757
|
+
available()
|
|
758
|
+
const item = sourceItemOf(input?.source)
|
|
759
|
+
// A source this mode cannot read refuses its probe too, with the same sentence: binding it would
|
|
760
|
+
// promise a read that can never arrive.
|
|
761
|
+
if (!runtime.control && (item.id === "mem.members" || item.id === "mem.grants")) controlOnly(item)
|
|
762
|
+
const identity = await identityOf(call.sessionID)
|
|
763
|
+
checkAccount(input, identity.account)
|
|
764
|
+
// The contract's probe answer: who, for which source, marked untrusted, and no content (D8).
|
|
765
|
+
return { source: sourceNameOf(item), account: identity.account, owner: identity.owner, trust: "untrusted", scopes: ["records"] }
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
return { receipts_read, names_list, members_read, grants_read, spaces_joinable_read, meeting_records_read, events_list, pages_search, probe }
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/** The action each source's read and probe assert, for the tests that hold them to the declaration. */
|
|
772
|
+
export { PROBE_ACTION }
|