@joe-broadhead/opencode-mem 0.0.0-stage → 0.6.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/src/spaces.js ADDED
@@ -0,0 +1,478 @@
1
+ import { errorMessage, isPlainObject, oneLine } from "./util.js"
2
+
3
+ const DEFAULT_TIMEOUT_MS = 10_000
4
+
5
+ /**
6
+ * A control-plane request failed. `status` is 0 for transport failures and 408
7
+ * for a timeout, so callers can tell "denied" from "unreachable".
8
+ */
9
+ export class ControlError extends Error {
10
+ /**
11
+ * @param {string} operation
12
+ * @param {number} status
13
+ * @param {string} message
14
+ */
15
+ constructor(operation, status, message) {
16
+ super(`${operation}: ${message}`)
17
+ this.name = "ControlError"
18
+ this.operation = operation
19
+ this.status = status
20
+ }
21
+ }
22
+
23
+ /**
24
+ * A small client for the spaces control plane.
25
+ *
26
+ * The plugin never decides access: it asks the control plane for a context and
27
+ * trusts the returned space, collection, and placement. `container_id` is the
28
+ * upstream team used for physical storage; it stays internal and is never put in
29
+ * a tool response.
30
+ *
31
+ * `controlURL` may be a function: inside Jelly the origin is read on every
32
+ * request (see `src/credentials.js`). The bearer comes from `credentials` on
33
+ * every request, else from `token`; a 401 is answered once with a different
34
+ * token from `credentials.refresh`, as in `src/backend/v3.js`.
35
+ *
36
+ * @param {{
37
+ * controlURL: string | (() => string),
38
+ * token?: string,
39
+ * credentials?: { bearer(): Promise<string>, refresh(rejected: string): Promise<string> },
40
+ * timeoutMs?: number,
41
+ * fetchImpl?: typeof fetch,
42
+ * log?: any,
43
+ * }} input
44
+ */
45
+ export function createControlClient(input) {
46
+ const configured = input?.controlURL
47
+ const controlURLOf = () => String((typeof configured === "function" ? configured() : configured) ?? "").replace(/\/+$/, "")
48
+ if (typeof configured !== "function" && !controlURLOf()) throw new Error("controlURL is required")
49
+ const token = String(input?.token ?? "")
50
+ const credentials = input?.credentials ?? null
51
+ const timeoutMs = positiveInt(input?.timeoutMs, DEFAULT_TIMEOUT_MS)
52
+ const fetchImpl = input?.fetchImpl ?? globalThis.fetch
53
+ const log = input?.log
54
+
55
+ async function bearer(operation) {
56
+ if (!credentials) return token
57
+ try {
58
+ return await credentials.bearer()
59
+ } catch (error) {
60
+ throw new ControlError(operation, Number(error?.status) || 0, oneLine(errorMessage(error)))
61
+ }
62
+ }
63
+
64
+ async function renewed(rejected) {
65
+ if (!credentials) return ""
66
+ try {
67
+ return await credentials.refresh(rejected)
68
+ } catch {
69
+ return ""
70
+ }
71
+ }
72
+
73
+ /**
74
+ * @param {string} operation
75
+ * @param {"GET" | "POST" | "DELETE"} method
76
+ * @param {string} route
77
+ * @param {{ query?: Record<string, string | undefined>, body?: unknown }} [options]
78
+ */
79
+ async function request(operation, method, route, options = {}) {
80
+ const controlURL = controlURLOf()
81
+ if (!controlURL) throw new ControlError(operation, 0, "no memory address is known (controlURL)")
82
+ const url = new URL(`${controlURL}${route}`)
83
+ for (const [key, value] of Object.entries(options.query ?? {})) {
84
+ if (value !== undefined && value !== null && value !== "") url.searchParams.set(key, String(value))
85
+ }
86
+
87
+ const headers = { accept: "application/json" }
88
+ if (options.body !== undefined) headers["content-type"] = "application/json"
89
+ let bearerToken = await bearer(operation)
90
+
91
+ const controller = new AbortController()
92
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
93
+ const send = (value) =>
94
+ fetchImpl(String(url), {
95
+ method,
96
+ headers: value ? { ...headers, authorization: `Bearer ${value}` } : headers,
97
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
98
+ signal: controller.signal,
99
+ })
100
+ try {
101
+ let response = await send(bearerToken)
102
+ if (response.status === 401 && bearerToken) {
103
+ const next = await renewed(bearerToken)
104
+ if (next) {
105
+ try {
106
+ await response.body?.cancel()
107
+ } catch {
108
+ /* the refused body is not read */
109
+ }
110
+ bearerToken = next
111
+ response = await send(next)
112
+ }
113
+ }
114
+ const raw = await response.text()
115
+ let json = {}
116
+ if (raw) {
117
+ try {
118
+ json = JSON.parse(raw)
119
+ } catch {
120
+ throw new ControlError(operation, response.status, `non-JSON response (${response.status})`)
121
+ }
122
+ }
123
+ if (!response.ok) {
124
+ const message = json?.error ?? json?.message ?? response.statusText ?? "request failed"
125
+ // The gateway's fixed messages are generic ("context request was
126
+ // rejected"); its code says why, for example space_role_required for
127
+ // a space reached only through a collection or resource grant.
128
+ const rawCode = json?.code ?? json?.error?.code
129
+ const code = typeof rawCode === "string" && /^[a-z][a-z0-9_]{1,63}$/.test(rawCode) ? rawCode : ""
130
+ const text = typeof message?.message === "string" ? message.message : String(message)
131
+ throw new ControlError(operation, response.status, oneLine(code && !text.includes(code) ? `${text} (${code})` : text))
132
+ }
133
+ return unwrap(json)
134
+ } catch (error) {
135
+ if (error instanceof ControlError) throw error
136
+ if (error?.name === "AbortError") {
137
+ throw new ControlError(operation, 408, `timeout after ${timeoutMs}ms`)
138
+ }
139
+ throw new ControlError(operation, 0, errorMessage(error))
140
+ } finally {
141
+ clearTimeout(timer)
142
+ }
143
+ }
144
+
145
+ /**
146
+ * List the spaces this user may see. Returns only public space fields: any
147
+ * upstream container or team identifier is dropped here.
148
+ *
149
+ * @param {{ userId: string }} input
150
+ */
151
+ async function listSpaces({ userId } = {}) {
152
+ if (!userId) throw new ControlError("spaces", 0, "user_id is required")
153
+ const payload = await request("spaces", "GET", "/v1/spaces", { query: { user_id: String(userId) } })
154
+ return extractSpaceList(payload).map(normalizeSpace).filter((space) => space.space_id)
155
+ }
156
+
157
+ /**
158
+ * Resolve the active context, or the context for one requested space.
159
+ *
160
+ * @param {{
161
+ * userId: string,
162
+ * spaceId?: string,
163
+ * sessionId?: string,
164
+ * agent?: string,
165
+ * }} input
166
+ */
167
+ async function resolveContext({ userId, spaceId, sessionId, agent } = {}) {
168
+ if (!userId) throw new ControlError("context", 0, "user_id is required")
169
+ const body = { user_id: String(userId) }
170
+ if (spaceId) body.space_id = String(spaceId)
171
+ if (sessionId) body.session_id = String(sessionId)
172
+ if (agent) body.agent = String(agent)
173
+
174
+ const payload = await request("context", "POST", "/v1/context", { body })
175
+ const context = normalizeContext(payload, { userId: body.user_id, spaceId })
176
+ log?.debug("space context resolved", { space: context.space_id, collection: context.collection_id })
177
+ return context
178
+ }
179
+
180
+ /**
181
+ * Ask the control plane for the caller's effective access to one resource.
182
+ * The plugin does not interpret the answer; it is exposed for future tools.
183
+ *
184
+ * @param {{ userId: string, resourceId: string }} input
185
+ */
186
+ async function effectiveAccess({ userId, resourceId } = {}) {
187
+ if (!userId) throw new ControlError("effective", 0, "user_id is required")
188
+ if (!resourceId) throw new ControlError("effective", 0, "resource_id is required")
189
+ const payload = await request("effective", "GET", "/v1/effective", {
190
+ query: { user_id: String(userId), resource_id: String(resourceId) },
191
+ })
192
+ return normalizeEffective(payload, resourceId)
193
+ }
194
+
195
+ /**
196
+ * Register a resource in a space. The control plane owns the role check and
197
+ * the row; the plugin only supplies the content identity.
198
+ *
199
+ * @param {{ userId: string, spaceId: string, resource: Record<string, unknown> }} input
200
+ */
201
+ async function createResource({ userId, spaceId, resource } = {}) {
202
+ if (!userId) throw new ControlError("resource", 0, "user_id is required")
203
+ if (!spaceId) throw new ControlError("resource", 0, "space_id is required")
204
+ const payload = await request("resource", "POST", `/v1/spaces/${encodeURIComponent(String(spaceId))}/resources`, {
205
+ body: resource ?? {},
206
+ })
207
+ return payload?.resource ?? payload
208
+ }
209
+
210
+ /**
211
+ * Delete a resource: its upstream content first, then its catalog row
212
+ * (share revocation). The gateway and control decide who may; only the
213
+ * resource's owner or a space owner or admin can. `dryRun` returns the row
214
+ * and changes nothing.
215
+ *
216
+ * @param {{ userId: string, spaceId: string, resourceId: string, dryRun?: boolean }} input
217
+ * @returns {Promise<{ resource?: object, deleted?: boolean, upstream?: string, dry_run?: boolean }>}
218
+ */
219
+ async function deleteResource({ userId, spaceId, resourceId, dryRun = false } = {}) {
220
+ if (!userId) throw new ControlError("resource", 0, "user_id is required")
221
+ if (!spaceId) throw new ControlError("resource", 0, "space_id is required")
222
+ if (!resourceId) throw new ControlError("resource", 0, "resource_id is required")
223
+ const route = `/v1/spaces/${encodeURIComponent(String(spaceId))}/resources/${encodeURIComponent(String(resourceId))}`
224
+ const payload = await request("resource", "DELETE", route, dryRun ? { query: { dry_run: "true" } } : {})
225
+ return isPlainObject(payload) ? payload : {}
226
+ }
227
+
228
+ /**
229
+ * List the grants that name the caller in one space.
230
+ *
231
+ * The public route is intentionally read-only: the control plane decides
232
+ * which grants the caller may see, and the plugin only renders the answer.
233
+ * Only display fields are retained so an upstream control response cannot
234
+ * leak a container, cell, or service id.
235
+ *
236
+ * @param {{ userId: string, spaceId: string }} input
237
+ */
238
+ async function listGrants({ userId, spaceId } = {}) {
239
+ if (!userId) throw new ControlError("grants", 0, "user_id is required")
240
+ if (!spaceId) throw new ControlError("grants", 0, "space_id is required")
241
+ const payload = await request("grants", "GET", "/v1/grants", {
242
+ query: { space_id: String(spaceId) },
243
+ })
244
+ return extractGrantList(payload).map(normalizeGrant).filter((grant) => grant.grant_id)
245
+ }
246
+
247
+ /**
248
+ * Read the member roster for one space. Membership and roles are never
249
+ * inferred by the plugin.
250
+ *
251
+ * @param {{ userId: string, spaceId: string }} input
252
+ */
253
+ async function listMembers({ userId, spaceId } = {}) {
254
+ if (!userId) throw new ControlError("members", 0, "user_id is required")
255
+ if (!spaceId) throw new ControlError("members", 0, "space_id is required")
256
+ const payload = await request(
257
+ "members",
258
+ "GET",
259
+ `/v1/spaces/${encodeURIComponent(String(spaceId))}/members`,
260
+ )
261
+ return extractMemberList(payload).map(normalizeMember).filter((member) => member.user_id)
262
+ }
263
+
264
+ return {
265
+ get controlURL() {
266
+ return controlURLOf()
267
+ },
268
+ listSpaces,
269
+ resolveContext,
270
+ effectiveAccess,
271
+ listGrants,
272
+ listMembers,
273
+ createResource,
274
+ deleteResource,
275
+ }
276
+ }
277
+
278
+ /** @param {unknown} value */
279
+ function positiveInt(value, fallback) {
280
+ const number = Number(value)
281
+ return Number.isFinite(number) && number > 0 ? Math.floor(number) : fallback
282
+ }
283
+
284
+ /** Most control routes answer either the object or `{ data: object | array }`. */
285
+ function unwrap(value) {
286
+ if (isPlainObject(value) && (isPlainObject(value.data) || Array.isArray(value.data))) return value.data
287
+ return value
288
+ }
289
+
290
+ function extractSpaceList(payload) {
291
+ if (Array.isArray(payload)) return payload
292
+ if (!isPlainObject(payload)) return []
293
+ if (Array.isArray(payload.spaces)) return payload.spaces
294
+ if (isPlainObject(payload.spaces)) return extractSpaceList(payload.spaces)
295
+ if (Array.isArray(payload.items)) return payload.items
296
+ if (Array.isArray(payload.personal) || Array.isArray(payload.shared)) {
297
+ return [
298
+ ...withKind(payload.personal ?? [], "personal"),
299
+ ...withKind(payload.shared ?? [], "shared"),
300
+ ]
301
+ }
302
+ return []
303
+ }
304
+
305
+ function extractGrantList(payload) {
306
+ if (Array.isArray(payload)) return payload
307
+ if (!isPlainObject(payload)) return []
308
+ if (Array.isArray(payload.grants)) return payload.grants
309
+ if (Array.isArray(payload.items)) return payload.items
310
+ return []
311
+ }
312
+
313
+ function extractMemberList(payload) {
314
+ if (Array.isArray(payload)) return payload
315
+ if (!isPlainObject(payload)) return []
316
+ if (Array.isArray(payload.members)) return payload.members
317
+ if (Array.isArray(payload.items)) return payload.items
318
+ return []
319
+ }
320
+
321
+ function withKind(items, kind) {
322
+ return items.map((item) => {
323
+ if (!isPlainObject(item)) return item
324
+ const space = isPlainObject(item.space) ? item.space : item
325
+ if (space.kind || space.space_kind || item.kind) return item
326
+ return { ...item, kind }
327
+ })
328
+ }
329
+
330
+ function normalizeSpace(item) {
331
+ const space = isPlainObject(item?.space) ? item.space : isPlainObject(item) ? item : {}
332
+ const id = space.space_id ?? space.id ?? space.spaceId ?? item?.space_id
333
+ const kind = String(space.kind ?? space.space_kind ?? item?.kind ?? "").toLowerCase()
334
+ const role = space.role ?? space.my_role ?? item?.role
335
+ return {
336
+ space_id: id === undefined || id === null ? "" : String(id),
337
+ name: text(space.name ?? space.title ?? item?.name),
338
+ kind: kind === "personal" || kind === "shared" ? kind : "unknown",
339
+ role: role === undefined || role === null ? "" : String(role),
340
+ }
341
+ }
342
+
343
+ function normalizeContext(payload, requested) {
344
+ const root = isPlainObject(payload?.context) ? payload.context : isPlainObject(payload) ? payload : {}
345
+ const space = isPlainObject(root.space)
346
+ ? root.space
347
+ : isPlainObject(root.active_space)
348
+ ? root.active_space
349
+ : typeof root.space === "string"
350
+ ? { id: root.space }
351
+ : typeof root.active_space === "string"
352
+ ? { id: root.active_space }
353
+ : {}
354
+ const collection = isPlainObject(root.collection) ? root.collection : {}
355
+ const session = isPlainObject(root.session) ? root.session : {}
356
+ const personalEntry = Array.isArray(root.spaces)
357
+ ? root.spaces.find((entry) => entry?.kind === "personal")
358
+ : undefined
359
+ const personal = isPlainObject(root.personal_space)
360
+ ? root.personal_space
361
+ : isPlainObject(personalEntry)
362
+ ? personalEntry
363
+ : {}
364
+ const placement = isPlainObject(root.placement)
365
+ ? root.placement
366
+ : Array.isArray(root.placement) && isPlainObject(root.placement[0])
367
+ ? root.placement[0]
368
+ : isPlainObject(root.placements)
369
+ ? root.placements
370
+ : Array.isArray(root.placements) && isPlainObject(root.placements[0])
371
+ ? root.placements[0]
372
+ : typeof root.placement === "string"
373
+ ? { container_id: root.placement }
374
+ : isPlainObject(root.container)
375
+ ? root.container
376
+ : {}
377
+
378
+ const routing = text(root.routing ?? root.context_routing)
379
+ const containerID = first(
380
+ placement.container_id,
381
+ placement.containerId,
382
+ placement.container,
383
+ placement.team_id,
384
+ placement.teamId,
385
+ root.container_id,
386
+ root.containerId,
387
+ root.container,
388
+ root.team_id,
389
+ root.teamId,
390
+ // A public gateway context deliberately omits the upstream container. Use
391
+ // the public space id as an opaque routing token; the gateway overwrites
392
+ // the upstream scope on every request.
393
+ space.id,
394
+ space.space_id,
395
+ root.space_id,
396
+ requested.spaceId,
397
+ )
398
+ if (!containerID) {
399
+ if (routing !== "gateway") {
400
+ throw new ControlError("context", 0, "control plane returned no container placement")
401
+ }
402
+ throw new ControlError("context", 0, "gateway context returned no space placement")
403
+ }
404
+
405
+ const collectionID = first(collection.id, collection.collection_id, root.collection_id, root.collectionId)
406
+ const agent = isPlainObject(root.agent) ? root.agent.name ?? root.agent.id : root.agent_name ?? root.agent_id ?? root.agent
407
+ const kind = String(space.kind ?? space.space_kind ?? root.space_kind ?? "").toLowerCase()
408
+
409
+ return {
410
+ user_id: text(root.user_id ?? requested.userId),
411
+ space_id: text(first(space.id, space.space_id, root.space_id, requested.spaceId)),
412
+ space_name: text(space.name ?? root.space_name),
413
+ space_kind: kind === "personal" || kind === "shared" ? kind : "unknown",
414
+ role: text(space.role ?? root.role),
415
+ collection_id: collectionID === undefined || collectionID === null ? "" : String(collectionID),
416
+ collection_name: text(collection.name ?? root.collection_name),
417
+ cell_id: text(first(placement.cell_id, placement.cellId, root.cell_id, root.cellId)),
418
+ service_id: text(first(placement.service_id, placement.serviceId, root.service_id, root.serviceId)),
419
+ container_id: String(containerID),
420
+ agent: text(agent),
421
+ // A session binding is the only proof that a shared space was selected for
422
+ // this session rather than being a global default. These two ids are space
423
+ // ids, never container ids, so they are safe to keep.
424
+ session_space_id: text(first(session.space_id, session.spaceId, root.session_space_id)),
425
+ personal_space_id: text(
426
+ first(personal.id, personal.space_id, personal.spaceId, root.personal_space_id, personalEntry?.id),
427
+ ),
428
+ }
429
+ }
430
+
431
+ function normalizeGrant(grant) {
432
+ return {
433
+ grant_id: text(grant?.id ?? grant?.grant_id),
434
+ target_type: text(grant?.target_type),
435
+ target_id: text(grant?.target_id),
436
+ principal_type: text(grant?.principal_type),
437
+ principal_id: text(grant?.principal_id),
438
+ role: text(grant?.role),
439
+ inherit: grant?.inherit === true || grant?.inherit === 1 || grant?.inherit === "1",
440
+ expires_at: text(grant?.expires_at),
441
+ created_at: text(grant?.created_at),
442
+ }
443
+ }
444
+
445
+ function normalizeMember(member) {
446
+ return {
447
+ user_id: text(member?.user_id ?? member?.userId ?? member?.id),
448
+ name: text(member?.name),
449
+ email: text(member?.email),
450
+ role: text(member?.role),
451
+ added_at: text(member?.added_at ?? member?.joined_at),
452
+ }
453
+ }
454
+
455
+ function normalizeEffective(payload, requestedResourceID) {
456
+ const root = isPlainObject(payload?.effective) ? payload.effective : isPlainObject(payload) ? payload : {}
457
+ const grants = Array.isArray(root.grants)
458
+ ? root.grants.map((grant) => ({
459
+ principal_type: text(grant?.principal_type),
460
+ principal_id: text(grant?.principal_id),
461
+ role: text(grant?.role),
462
+ }))
463
+ : []
464
+ return {
465
+ resource_id: text(root.resource_id ?? requestedResourceID),
466
+ role: text(root.role),
467
+ allowed: typeof root.allowed === "boolean" ? root.allowed : null,
468
+ grants,
469
+ }
470
+ }
471
+
472
+ function first(...values) {
473
+ return values.find((value) => value !== undefined && value !== null && value !== "")
474
+ }
475
+
476
+ function text(value) {
477
+ return value === undefined || value === null ? "" : String(value)
478
+ }