@joe-broadhead/opencode-mem 0.9.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +83 -0
- package/README.md +13 -0
- package/docs/agent-protocol.md +8 -8
- package/package.json +105 -5
- package/skills/mem.pages/SKILL.md +6 -3
- package/skills/mem.sharing/SKILL.md +12 -3
- package/skills/mem.sources/SKILL.md +2 -1
- package/skills/mem.usage/SKILL.md +17 -6
- package/src/backend/v3.js +3 -0
- package/src/call-shapes.js +2 -2
- package/src/config.js +3 -0
- package/src/credentials.js +26 -1
- package/src/permissions.js +69 -8
- package/src/protocol.js +1 -1
- package/src/records-store.js +16 -30
- package/src/tools/aliases.js +1 -0
- package/src/tools/held-write.js +82 -0
- package/src/tools/index.js +12 -4
- package/src/tools/memory.js +117 -54
- package/src/tools/page.js +16 -4
- package/src/tools/recall.js +8 -1
- package/src/tools/share.js +55 -25
- package/src/tools/shared.js +8 -1
- package/src/tools/wiki.js +6 -2
- package/src/views/contracts.js +20 -0
- package/src/views/inbox-decision.js +59 -0
- package/src/views/recall-result.js +12 -0
- package/src/views/rpc.js +44 -2
- package/views/recall.html +123 -0
package/src/tools/page.js
CHANGED
|
@@ -5,6 +5,7 @@ import { isInstructionShaped, quarantineNote, quarantineText } from "../curation
|
|
|
5
5
|
import { clampText, errorMessage, neutralizeFenceClosers, oneLine, redactSecrets } from "../util.js"
|
|
6
6
|
import { RecordsError } from "../backend/records.js"
|
|
7
7
|
import { canWriteShared } from "./shared.js"
|
|
8
|
+
import { holdTeamWrite } from "./held-write.js"
|
|
8
9
|
import { PAGE_PATH, PAGE_TYPES, RECORD_ID, callRecords, changeNote, dateOf, grantedSpace, noteRecordSpace, notWritten, pageTypeFor } from "./records-kit.js"
|
|
9
10
|
|
|
10
11
|
/** The actions of mem_page (contract §4.1). */
|
|
@@ -236,7 +237,11 @@ export function registerPage(editor, toolkit) {
|
|
|
236
237
|
if (write && spaceContext?.space_kind === "shared" && !canWriteShared(spaceContext.role)) {
|
|
237
238
|
return text(`changing pages in ${oneLine(spaceContext.space_id, 80)} requires editor, admin, or owner access; the control plane reports role ${oneLine(spaceContext.role || "unknown", 20)}. Nothing changed.`)
|
|
238
239
|
}
|
|
239
|
-
const askWrite = (resources, metadata) => assertTeamWrite(context, "page.write", [spaceContext?.space_id ?? "team", ...resources],
|
|
240
|
+
const askWrite = (resources, metadata) => assertTeamWrite(context, "page.write", [spaceContext?.space_id ?? "team", ...resources], {
|
|
241
|
+
...metadata,
|
|
242
|
+
...(spaceContext?.space_id ? { space_id: spaceContext.space_id } : {}),
|
|
243
|
+
...(spaceContext?.space_name ? { space_name: oneLine(spaceContext.space_name, 200) } : {}),
|
|
244
|
+
})
|
|
240
245
|
|
|
241
246
|
try {
|
|
242
247
|
if (verb === "list") {
|
|
@@ -269,9 +274,16 @@ export function registerPage(editor, toolkit) {
|
|
|
269
274
|
const title = String(input?.title ?? "").trim() || headingOf(content) || titleOfPath(pagePath)
|
|
270
275
|
const pageType = type ?? pageTypeFor(pagePath)
|
|
271
276
|
const known = seen.get(seenKey(spaceContext, pagePath))
|
|
277
|
+
if (spaceContext?.space_kind === "shared" && toolkit.config.heldTeamWrites) {
|
|
278
|
+
let id = known?.id
|
|
279
|
+
if (known?.version && !id) id = (await getPage(spaceContext, scoped, pagePath))?.id
|
|
280
|
+
if (known?.version && !id) return text(`not held: there is no page at ${pagePath} to update. Nothing was written.`)
|
|
281
|
+
const record = { kind: "page", type: pageType, path: pagePath, title, body: content, stated_by: "agent", source: context?.sessionID ? { session: String(context.sessionID) } : {}, ...(id ? { id, base_version: known.version } : {}) }
|
|
282
|
+
return text(await holdTeamWrite(toolkit, context, spaceContext, [record]))
|
|
283
|
+
}
|
|
272
284
|
if (shared) {
|
|
273
285
|
try {
|
|
274
|
-
await askWrite([pagePath], { page: pagePath, chars: content.length, excerpt: redactSecrets(
|
|
286
|
+
await askWrite([pagePath], { page: pagePath, chars: content.length, excerpt: oneLine(redactSecrets(content), 400) })
|
|
275
287
|
} catch (error) {
|
|
276
288
|
return text(`writing ${pagePath} denied: ${errorMessage(error)}. Nothing was written.`)
|
|
277
289
|
}
|
|
@@ -305,7 +317,7 @@ export function registerPage(editor, toolkit) {
|
|
|
305
317
|
const section = String(input.section).trim().replace(/^#+\s*/, "")
|
|
306
318
|
if (shared) {
|
|
307
319
|
try {
|
|
308
|
-
await askWrite([ref], { page: ref, section, excerpt: redactSecrets(
|
|
320
|
+
await askWrite([ref], { page: ref, section, excerpt: oneLine(redactSecrets(content), 400) })
|
|
309
321
|
} catch (error) {
|
|
310
322
|
return text(`appending to ${ref} denied: ${errorMessage(error)}. Nothing was written.`)
|
|
311
323
|
}
|
|
@@ -396,7 +408,7 @@ export function registerPage(editor, toolkit) {
|
|
|
396
408
|
const current = error.body?.error?.current
|
|
397
409
|
if (current) noteSeen(spaceContext, current)
|
|
398
410
|
return text(
|
|
399
|
-
`not written: ${ref} changed since it was read${current?.version ? ` (it is now version ${current.version})` : ""}, so nothing was overwritten. Read
|
|
411
|
+
`not written: ${ref} already exists or changed since it was read${current?.version ? ` (it is now version ${current.version})` : ""}, so nothing was overwritten. Read the page with mem_page read, merge your change into it, then write again.`,
|
|
400
412
|
)
|
|
401
413
|
}
|
|
402
414
|
if (error.code === "path_taken") return text(`not ${verb === "move" ? "moved" : "written"}: a page already exists at ${verb === "move" ? to : ref}. Read it, or pick another path.`)
|
package/src/tools/recall.js
CHANGED
|
@@ -5,6 +5,7 @@ import { discoverKnowledge, searchKnowledge } from "./knowledge.js"
|
|
|
5
5
|
import { TASK_INPUT } from "./shared.js"
|
|
6
6
|
import { MEMORY_TYPES, PAGE_TYPES, callRecords, grantedSpace, noteRecordSpace } from "./records-kit.js"
|
|
7
7
|
import { isRecordsUnavailable } from "../backend/records.js"
|
|
8
|
+
import { recallResultView } from "../views/recall-result.js"
|
|
8
9
|
|
|
9
10
|
/** Upper bound on hits per layer; the character budget still applies. */
|
|
10
11
|
const MAX_LIMIT = 25
|
|
@@ -467,6 +468,7 @@ export function registerRecall(editor, toolkit) {
|
|
|
467
468
|
if (layers.atoms && !result.failures.includes("atoms")) searched.push("atoms")
|
|
468
469
|
if (layers.turns && !result.failures.includes("past turns")) searched.push("past conversations")
|
|
469
470
|
let documentCoverage = ""
|
|
471
|
+
let documentIncomplete = false
|
|
470
472
|
let documents = ""
|
|
471
473
|
let documentsEmpty = false
|
|
472
474
|
if (layers.documents) {
|
|
@@ -490,6 +492,7 @@ export function registerRecall(editor, toolkit) {
|
|
|
490
492
|
? unavailable.length ? "Documents: no indexes found in available catalogs." : "Documents: no accessible wiki or code-graph indexes found."
|
|
491
493
|
: `Documents: searched ${searchedDocuments} of ${ids.length} accessible wiki or code-graph indexes.${searchedDocuments < ids.length ? " For a named document not covered, use mem_wiki." : ""}`
|
|
492
494
|
if (unavailable.length) documentCoverage += ` ${unavailable.join(", ")} unavailable (404).`
|
|
495
|
+
documentIncomplete = Boolean(discoveryFailures.length || documentFailures || unavailable.length || searchedDocuments < ids.length)
|
|
493
496
|
documentsEmpty = ids.length === 0 && discoveryFailures.length === 0 && unavailable.length === 0
|
|
494
497
|
}
|
|
495
498
|
|
|
@@ -511,7 +514,11 @@ export function registerRecall(editor, toolkit) {
|
|
|
511
514
|
conversations: conversations.length,
|
|
512
515
|
withheld,
|
|
513
516
|
})
|
|
514
|
-
|
|
517
|
+
const shownScopeNote = neutralizeFenceClosers(oneLine(scopeNote ?? "", 240))
|
|
518
|
+
return { ...text(block), metadata: { memoryRecall: recallResultView({
|
|
519
|
+
coverage, scopeNote: shownScopeNote && block.includes(shownScopeNote) ? shownScopeNote : "",
|
|
520
|
+
records, atoms, conversations, failures, documentIncomplete,
|
|
521
|
+
}) } }
|
|
515
522
|
} catch (error) {
|
|
516
523
|
log.warn("recall failed", error)
|
|
517
524
|
return fail(errorMessage(error))
|
package/src/tools/share.js
CHANGED
|
@@ -3,6 +3,7 @@ import { REMEMBER_WRAPPER } from "../copies.js"
|
|
|
3
3
|
import { errorMessage, isPlainObject, oneLine, redactSecrets } from "../util.js"
|
|
4
4
|
import { isCoded } from "../errors.js"
|
|
5
5
|
import { canWriteShared } from "./shared.js"
|
|
6
|
+
import { holdTeamWrite } from "./held-write.js"
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* `mem_share` (docs/design/memory-v1-contracts.md §4.1; memory-tools-v1.md §10):
|
|
@@ -82,7 +83,6 @@ const LEGACY_ID = /^(m_|msg[-_])/
|
|
|
82
83
|
const MAX_COPY_IDS = 20
|
|
83
84
|
const MAX_COPY_CHARS = 8_000
|
|
84
85
|
/** Records whose owner a folder transfer changes at most. */
|
|
85
|
-
const MAX_TRANSFER_RECORDS = 1_000
|
|
86
86
|
/** The legacy copy scan: newest rows per layer and agent (as mem_forget). */
|
|
87
87
|
const SCAN_PAGE = 100
|
|
88
88
|
const SCAN_PAGES = 3
|
|
@@ -331,18 +331,28 @@ export function createShareActions(toolkit) {
|
|
|
331
331
|
return { records: answer?.records ?? [], cursor: answer?.cursor }
|
|
332
332
|
}
|
|
333
333
|
|
|
334
|
-
/**
|
|
335
|
-
async function registerTarget(target, spaceContext, title) {
|
|
336
|
-
const
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
334
|
+
/** Look up or register the page/folder; control rejects duplicate registrations. */
|
|
335
|
+
async function registerTarget(target, spaceContext, title, { returnResource = false } = {}) {
|
|
336
|
+
const lookup = async () => (await sharedResources(spaceContext)).find((entry) => entry.upstream_id === upstreamIdFor(target))
|
|
337
|
+
let resource = await lookup()
|
|
338
|
+
if (!resource) {
|
|
339
|
+
try {
|
|
340
|
+
resource = await control.createResource({
|
|
341
|
+
userId: userOf(spaceContext),
|
|
342
|
+
spaceId: spaceContext.space_id,
|
|
343
|
+
resource: {
|
|
344
|
+
kind: "wiki_page",
|
|
345
|
+
upstream_id: upstreamIdFor(target),
|
|
346
|
+
name: oneLine(target.kind === "page" ? `${title || target.path} (${target.path})` : `Folder ${target.path}`, 200),
|
|
347
|
+
},
|
|
348
|
+
})
|
|
349
|
+
} catch (error) {
|
|
350
|
+
if (Number(error?.status) !== 409) throw error
|
|
351
|
+
resource = await lookup()
|
|
352
|
+
if (!resource) throw error
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return returnResource ? resource : String(resource?.id ?? "").trim()
|
|
346
356
|
}
|
|
347
357
|
|
|
348
358
|
/** The space's shared pages and folders (`wiki_page` resources with a `records:` id). */
|
|
@@ -657,6 +667,7 @@ export function createShareActions(toolkit) {
|
|
|
657
667
|
let found
|
|
658
668
|
try {
|
|
659
669
|
found = await readTarget(target, where)
|
|
670
|
+
if (target.kind === "folder") found.records = await allUnder(target, where, found)
|
|
660
671
|
} catch (error) {
|
|
661
672
|
if (recordsServiceMissing(error)) return text(sharingNeedsRecords("transfer"))
|
|
662
673
|
return fail(recordsFailure(error))
|
|
@@ -676,32 +687,34 @@ export function createShareActions(toolkit) {
|
|
|
676
687
|
|
|
677
688
|
let resourceId
|
|
678
689
|
try {
|
|
679
|
-
|
|
690
|
+
const resource = await registerTarget(target, spaceContext, found.title, { returnResource: true })
|
|
691
|
+
resourceId = String(resource?.id ?? "").trim()
|
|
680
692
|
if (!resourceId) throw new Error("registration returned no resource id")
|
|
681
|
-
|
|
682
|
-
|
|
693
|
+
if (resource.owner_user_id !== principal.id) {
|
|
694
|
+
const moved = await control.transferResource({ userId: userOf(spaceContext), spaceId: spaceContext.space_id, resourceId, toUserId: principal.id })
|
|
695
|
+
if (moved?.transferred === false && moved?.owner_user_id !== principal.id) throw new Error("control did not confirm the requested owner")
|
|
696
|
+
}
|
|
683
697
|
} catch (error) {
|
|
684
698
|
log.warn("share transfer failed", error)
|
|
685
|
-
return fail(`${target.path}
|
|
699
|
+
return fail(`${target.path}: control transfer did not complete or could not be confirmed (${errorMessage(error)}). Registration or ownership may have changed; check control before retrying. No page owners were changed by this call.`)
|
|
686
700
|
}
|
|
687
701
|
|
|
688
702
|
// Control now names the new owner; the records under the path follow
|
|
689
703
|
// (contract §3: records.put with the new owner).
|
|
690
|
-
const pages =
|
|
704
|
+
const pages = found.records
|
|
691
705
|
const failed = []
|
|
692
|
-
for (const record of pages
|
|
706
|
+
for (const record of pages) {
|
|
693
707
|
try {
|
|
694
708
|
await putOwner(record, principal.id, where)
|
|
695
709
|
} catch (error) {
|
|
696
710
|
failed.push(`${record.path || record.id} (${recordsFailure(error)})`)
|
|
697
711
|
}
|
|
698
712
|
}
|
|
699
|
-
const over = pages.length > MAX_TRANSFER_RECORDS ? pages.length - MAX_TRANSFER_RECORDS : 0
|
|
700
713
|
log.info("share transfer", { space: spaceContext.space_id, kind: target.kind, pages: pages.length, failed: failed.length })
|
|
701
714
|
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
|
|
715
|
+
if (failed.length > 0) {
|
|
703
716
|
return fail(
|
|
704
|
-
`${done}, but ${failed.length
|
|
717
|
+
`${done}, but ${failed.length} of ${pages.length} page owner update(s) failed or could not be confirmed: ${failed.slice(0, 5).join("; ")}. Retry the same transfer; an owner or space admin with access to the remaining pages may need to finish it.`,
|
|
705
718
|
)
|
|
706
719
|
}
|
|
707
720
|
return text(`${done}, and ${pages.length} page(s) now name them as owner. You keep the access your space role gives you.`)
|
|
@@ -710,7 +723,10 @@ export function createShareActions(toolkit) {
|
|
|
710
723
|
async function allUnder(target, where, first) {
|
|
711
724
|
const out = [...first.records]
|
|
712
725
|
let cursor = first.cursor
|
|
713
|
-
|
|
726
|
+
const seen = new Set()
|
|
727
|
+
while (cursor) {
|
|
728
|
+
if (seen.has(cursor)) throw new Error("records.list repeated a cursor; folder enumeration is incomplete")
|
|
729
|
+
seen.add(cursor)
|
|
714
730
|
const answer = await callRecords("records.list", { kind: "page", path_prefix: target.path, limit: 200, cursor }, where)
|
|
715
731
|
out.push(...(answer?.records ?? []))
|
|
716
732
|
cursor = answer?.cursor
|
|
@@ -721,7 +737,7 @@ export function createShareActions(toolkit) {
|
|
|
721
737
|
/** Set a record's owner; on a version conflict, read it again once and retry. */
|
|
722
738
|
async function putOwner(record, owner, where) {
|
|
723
739
|
if (record.owner === owner) return
|
|
724
|
-
const put = (current) => callRecords("records.put", { record: {
|
|
740
|
+
const put = (current) => callRecords("records.put", { record: { id: current.id, owner, base_version: current.version } }, where)
|
|
725
741
|
try {
|
|
726
742
|
await put(record)
|
|
727
743
|
} catch (error) {
|
|
@@ -848,12 +864,26 @@ export function createShareActions(toolkit) {
|
|
|
848
864
|
}
|
|
849
865
|
|
|
850
866
|
const { spaceContext, where } = target
|
|
867
|
+
if (config.heldTeamWrites) {
|
|
868
|
+
const by = userOf(personal) || userOf(spaceContext) || "unknown"
|
|
869
|
+
const proposed = sources.map((source) => ({
|
|
870
|
+
kind: "memory", type: source.type, title: oneLine(source.title || source.text, 300), body: source.text,
|
|
871
|
+
stated_by: source.stated_by || "person",
|
|
872
|
+
fields: { copied_from: { space: personal.space_id, id: source.id, by, rationale: oneLine(rationale, 500) } },
|
|
873
|
+
source: context?.sessionID ? { session: String(context.sessionID) } : {},
|
|
874
|
+
}))
|
|
875
|
+
try {
|
|
876
|
+
return text(await holdTeamWrite(toolkit, context, spaceContext, proposed))
|
|
877
|
+
} catch (error) {
|
|
878
|
+
return fail(`held write failed: ${errorMessage(error)}. No memories were copied.`)
|
|
879
|
+
}
|
|
880
|
+
}
|
|
851
881
|
const denied = await approve(
|
|
852
882
|
context,
|
|
853
883
|
{
|
|
854
884
|
action: "memory.promote",
|
|
855
885
|
resources: ids,
|
|
856
|
-
metadata: { space: spaceContext.space_id, rationale, copies: sources.map((source) => `${source.id} (${source.type}): ${oneLine(source.text, 160)}`) },
|
|
886
|
+
metadata: { space: spaceContext.space_id, space_id: spaceContext.space_id, ...(spaceContext.space_name ? { space_name: oneLine(spaceContext.space_name, 200) } : {}), rationale, copies: sources.map((source) => `${source.id} (${source.type}): ${oneLine(source.text, 160)}`) },
|
|
857
887
|
},
|
|
858
888
|
"not copied (approval)",
|
|
859
889
|
)
|
package/src/tools/shared.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { contextScopeLabel, scopeLabel, taskKey } from "../scope.js"
|
|
2
2
|
import { errorMessage, oneLine } from "../util.js"
|
|
3
3
|
import { isCoded } from "../errors.js"
|
|
4
|
+
import { hasSharedWritePolicy } from "../permissions.js"
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Roles that may write to a shared space. The plugin reads this from the
|
|
@@ -219,7 +220,7 @@ export function createToolkit(ctx, runtime) {
|
|
|
219
220
|
return { key, declared: true }
|
|
220
221
|
}
|
|
221
222
|
|
|
222
|
-
/**
|
|
223
|
+
/** An assertion enforces host policy, but does not prove a prompt appeared. */
|
|
223
224
|
async function assertTeamWrite(context, action, resources, metadata) {
|
|
224
225
|
await ctx.permission.assert({
|
|
225
226
|
sessionID: context?.sessionID,
|
|
@@ -230,6 +231,12 @@ export function createToolkit(ctx, runtime) {
|
|
|
230
231
|
save: [],
|
|
231
232
|
metadata,
|
|
232
233
|
})
|
|
234
|
+
// On older hosts a default * allow may pass with no action policy. Require
|
|
235
|
+
// a visible action-specific rule there; never infer that a prompt appeared.
|
|
236
|
+
if (["memory.remember", "memory.revise", "page.write", "wiki.write"].includes(action) &&
|
|
237
|
+
!(await hasSharedWritePolicy(ctx, context, action, resources))) {
|
|
238
|
+
throw new Error(`no explicit permission rule for ${action} is visible on this host; no write was made. Add an allow or ask rule for ${action} (or memory.* for memory actions), or update OpenCode`)
|
|
239
|
+
}
|
|
233
240
|
}
|
|
234
241
|
|
|
235
242
|
/**
|
package/src/tools/wiki.js
CHANGED
|
@@ -141,7 +141,7 @@ export function registerWiki(editor, toolkit) {
|
|
|
141
141
|
filename,
|
|
142
142
|
...(action === "create" ? { name: oneLine(input?.name, 200) } : {}),
|
|
143
143
|
bytes: Buffer.byteLength(content),
|
|
144
|
-
excerpt: redactSecrets(content.slice(0, APPROVAL_EXCERPT_CHARS)
|
|
144
|
+
excerpt: redactSecrets(content).slice(0, APPROVAL_EXCERPT_CHARS),
|
|
145
145
|
}
|
|
146
146
|
}
|
|
147
147
|
|
|
@@ -166,7 +166,11 @@ export function registerWiki(editor, toolkit) {
|
|
|
166
166
|
async function approveWrite(context, visibility, spaceContext, approval) {
|
|
167
167
|
if (visibility !== "team") return ""
|
|
168
168
|
try {
|
|
169
|
-
await assertTeamWrite(context, "wiki.write", [spaceContext?.space_id ?? "team"],
|
|
169
|
+
await assertTeamWrite(context, "wiki.write", [spaceContext?.space_id ?? "team"], {
|
|
170
|
+
...approval,
|
|
171
|
+
...(spaceContext?.space_id ? { space_id: spaceContext.space_id } : {}),
|
|
172
|
+
...(spaceContext?.space_name ? { space_name: oneLine(spaceContext.space_name, 200) } : {}),
|
|
173
|
+
})
|
|
170
174
|
return ""
|
|
171
175
|
} catch (error) {
|
|
172
176
|
return errorMessage(error)
|
package/src/views/contracts.js
CHANGED
|
@@ -134,6 +134,8 @@ const overviewOutput = {
|
|
|
134
134
|
/** Capture as this engine runs it now: the declared setting, read at start. */
|
|
135
135
|
capture: { type: "boolean" },
|
|
136
136
|
health: { type: "string", enum: ["ok", "unreachable", "unknown"] },
|
|
137
|
+
extraction: { type: "string", enum: ["healthy", "failing", "unknown"] },
|
|
138
|
+
failing_since: line(40),
|
|
137
139
|
/** Whether the records service answers (memories are records from 0.9); "unavailable" says the page shows `RECORDS_OFF`. */
|
|
138
140
|
records: { type: "string", enum: ["ok", "unavailable"] },
|
|
139
141
|
space,
|
|
@@ -387,6 +389,17 @@ const reviewListOutput = object({
|
|
|
387
389
|
more: flag,
|
|
388
390
|
})
|
|
389
391
|
|
|
392
|
+
const inboxOutput = object({
|
|
393
|
+
items: list(object({
|
|
394
|
+
key: line(200),
|
|
395
|
+
category: { type: "string", enum: ["request"] },
|
|
396
|
+
label: line(40),
|
|
397
|
+
name: line(120),
|
|
398
|
+
line: line(120),
|
|
399
|
+
at: line(40),
|
|
400
|
+
}), REVIEW_MAX),
|
|
401
|
+
})
|
|
402
|
+
|
|
390
403
|
const pagesListOutput = object({
|
|
391
404
|
space,
|
|
392
405
|
/** The folder listed, "" for the top. */
|
|
@@ -526,6 +539,13 @@ export const VIEW_METHODS = Object.freeze([
|
|
|
526
539
|
input: viewInput(spaceInput),
|
|
527
540
|
output: reviewListOutput,
|
|
528
541
|
},
|
|
542
|
+
{
|
|
543
|
+
name: "inbox.list",
|
|
544
|
+
label: "list proposals waiting for your review",
|
|
545
|
+
permission: "mem_spaces",
|
|
546
|
+
input: empty,
|
|
547
|
+
output: inboxOutput,
|
|
548
|
+
},
|
|
529
549
|
{
|
|
530
550
|
name: "pages.list",
|
|
531
551
|
label: "list your pages by folder",
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { asVerifiedView } from "../credentials.js"
|
|
2
|
+
import { decideProposal as decideHeldProposal } from "../tools/held-write.js"
|
|
3
|
+
|
|
4
|
+
/** Actions for a proposal read from the records service, not from the caller. */
|
|
5
|
+
export function proposalActions(proposal) {
|
|
6
|
+
return proposal?.type === "team_write" ? ["accept", "private", "decline"] : ["accept", "decline"]
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Integration seam, deliberately not registered as RPC. A future Jelly action
|
|
11
|
+
* handler must verify the action grant, bind `caller` to its signed member and
|
|
12
|
+
* input, and supply a proposal reader using that person's credentials. Never
|
|
13
|
+
* pass a caller or proposal supplied by a page as authority.
|
|
14
|
+
*/
|
|
15
|
+
export function createInboxDecision({ loadProposal, decideProposal } = {}) {
|
|
16
|
+
return async ({ key, decision, caller } = {}) => {
|
|
17
|
+
if (typeof key !== "string" || !/^proposal:rec_[0-9A-Za-z]{1,64}$/.test(key) || !["accept", "private", "decline"].includes(decision)) {
|
|
18
|
+
return { ok: false, code: "invalid_input" }
|
|
19
|
+
}
|
|
20
|
+
if (!caller || typeof loadProposal !== "function" || typeof decideProposal !== "function") return { ok: false, code: "unavailable" }
|
|
21
|
+
let proposal
|
|
22
|
+
try {
|
|
23
|
+
proposal = await loadProposal({ key, caller })
|
|
24
|
+
} catch {
|
|
25
|
+
return { ok: false, code: "unavailable" }
|
|
26
|
+
}
|
|
27
|
+
if (!proposal || (proposal.status !== "proposed" && !(proposal.status === "accepting" && decision === "accept"))) return { ok: false, code: "not_pending" }
|
|
28
|
+
if (!proposalActions(proposal).includes(decision)) return { ok: false, code: "invalid_decision" }
|
|
29
|
+
// J-HELD JOIN: the sole mutation call. J-HELD owns authorization, the
|
|
30
|
+
// shared-space ask, atomicity, replay and the returned decision result.
|
|
31
|
+
return decideProposal({ key, decision, caller })
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Join the public Inbox key to the authenticated author's personal store. */
|
|
36
|
+
export function createHeldInboxDecision(runtime) {
|
|
37
|
+
async function personal(caller) {
|
|
38
|
+
if (!runtime?.control || caller?.runtime !== runtime || !/^view_[A-Za-z0-9_-]{1,123}$/.test(caller?.speaker ?? "")) throw new Error("authenticated caller required")
|
|
39
|
+
if (typeof runtime.availability === "function" && await runtime.availability()) throw new Error("unavailable")
|
|
40
|
+
const active = await runtime.resolveContext({})
|
|
41
|
+
const space = active?.personal_space_id
|
|
42
|
+
if (!space) throw new Error("personal space unavailable")
|
|
43
|
+
const own = await runtime.resolveContext({ space })
|
|
44
|
+
if (own?.space_id !== space || own.space_kind !== "personal" || own.personal_space_id !== space || own.role !== "owner" || !own.user_id) throw new Error("personal space unverified")
|
|
45
|
+
return own
|
|
46
|
+
}
|
|
47
|
+
return createInboxDecision({
|
|
48
|
+
loadProposal: ({ key, caller }) => asVerifiedView(caller.speaker, async () => {
|
|
49
|
+
const own = await personal(caller)
|
|
50
|
+
const answer = await runtime.recordsClient.call("records.get", { ids: [key.slice("proposal:".length)] }, { space: own.space_id })
|
|
51
|
+
const proposal = answer?.records?.[0]
|
|
52
|
+
return proposal?.kind === "proposal" && proposal?.type === "team_write" && proposal?.author?.user === own.user_id ? proposal : null
|
|
53
|
+
}),
|
|
54
|
+
decideProposal: ({ key, decision, caller }) => asVerifiedView(caller.speaker, async () => {
|
|
55
|
+
const own = await personal(caller)
|
|
56
|
+
return decideHeldProposal({ key: `${own.space_id}:${key.slice("proposal:".length)}`, decision, caller })
|
|
57
|
+
}),
|
|
58
|
+
})
|
|
59
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Build the bounded metadata for a recall result; input is the curated search result. */
|
|
2
|
+
export function recallResultView({ coverage, scopeNote, records, atoms, conversations, failures, documentIncomplete } = {}) {
|
|
3
|
+
const text = (value) => typeof value === "string" ? value.replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 600) : ""
|
|
4
|
+
const count = (value) => Array.isArray(value) ? Math.min(value.length, 1000) : 0
|
|
5
|
+
return {
|
|
6
|
+
v: 1,
|
|
7
|
+
coverage: text(coverage),
|
|
8
|
+
scopeNote: text(scopeNote),
|
|
9
|
+
counts: { records: count(records), atoms: count(atoms), conversations: count(conversations) },
|
|
10
|
+
incomplete: Boolean(documentIncomplete || (Array.isArray(failures) && failures.length)),
|
|
11
|
+
}
|
|
12
|
+
}
|
package/src/views/rpc.js
CHANGED
|
@@ -11,6 +11,11 @@ import {
|
|
|
11
11
|
} from "./contracts.js"
|
|
12
12
|
import { createRecordsReads, recordsFailureWords } from "./records-reads.js"
|
|
13
13
|
import { SPACE_KINDS, ViewRefusal, clip, clipText, idOf, refuse, spaceOf } from "./shape.js"
|
|
14
|
+
import { createHeldInboxDecision } from "./inbox-decision.js"
|
|
15
|
+
|
|
16
|
+
// Jelly has no Inbox action route, signed-grant verifier, or ask bridge yet (#33).
|
|
17
|
+
// Never enable in production until all three are available and independently verified.
|
|
18
|
+
export const INBOX_ACTION_RPC_ENABLED = false
|
|
14
19
|
|
|
15
20
|
/**
|
|
16
21
|
* The RPC behind Memory's views in Jelly (`views/*.html`).
|
|
@@ -53,6 +58,14 @@ const AGENT_TTL_MS = 60_000
|
|
|
53
58
|
/** A page's text is held well under Jelly's 64 KB answer cap. */
|
|
54
59
|
const PAGE_TEXT_BYTES = 56_000
|
|
55
60
|
|
|
61
|
+
function inboxTime(value) {
|
|
62
|
+
const match = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:Z|([+-])(\d\d):(\d\d))$/.exec(value)
|
|
63
|
+
if (!match) return false
|
|
64
|
+
const [, year, month, day, hour, minute, second, , offsetHour, offsetMinute] = match
|
|
65
|
+
const date = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)))
|
|
66
|
+
return date.getUTCFullYear() === Number(year) && date.getUTCMonth() + 1 === Number(month) && date.getUTCDate() === Number(day) && Number(hour) < 24 && Number(minute) < 60 && Number(second) < 60 && Number(offsetHour ?? 0) < 24 && Number(offsetMinute ?? 0) < 60
|
|
67
|
+
}
|
|
68
|
+
|
|
56
69
|
const CREDENTIALS = Object.freeze({
|
|
57
70
|
[SOURCES.identity]: "jelly",
|
|
58
71
|
[SOURCES.secret]: "key",
|
|
@@ -145,6 +158,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
|
|
|
145
158
|
const base = {
|
|
146
159
|
capture: config.capture !== false,
|
|
147
160
|
health: "unknown",
|
|
161
|
+
extraction: "unknown",
|
|
148
162
|
...(address ? { address: clip(address, 300) } : {}),
|
|
149
163
|
}
|
|
150
164
|
const reason = await unavailableNow()
|
|
@@ -165,7 +179,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
|
|
|
165
179
|
// Memories are records from 0.9 (the space's count); conversations,
|
|
166
180
|
// summaries and the profile are still the core's, per agent.
|
|
167
181
|
const count = (read) => read.then((data) => Number(data?.total) || 0).catch(() => 0)
|
|
168
|
-
const [health, kept, perAgent] = await Promise.all([
|
|
182
|
+
const [health, kept, perAgent, extraction] = await Promise.all([
|
|
169
183
|
backend.probe().catch(() => ({ ok: false })),
|
|
170
184
|
recordsReads.memoryCount(scopes[0]).catch((error) => {
|
|
171
185
|
runtime.log?.warn?.("view overview: records count failed", error)
|
|
@@ -183,6 +197,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
|
|
|
183
197
|
]),
|
|
184
198
|
),
|
|
185
199
|
),
|
|
200
|
+
runtime.control && typeof backend.extractionHealth === "function" ? backend.extractionHealth().catch(() => null) : null,
|
|
186
201
|
])
|
|
187
202
|
const counts = { memories: kept.memories, conversations: 0, summaries: 0, profile: false }
|
|
188
203
|
for (const [conversations, summaries, profile] of perAgent) {
|
|
@@ -195,6 +210,8 @@ export function createViewReads({ runtime, agents = async () => [] }) {
|
|
|
195
210
|
...credentialState(),
|
|
196
211
|
...base,
|
|
197
212
|
health: health?.ok ? "ok" : "unreachable",
|
|
213
|
+
extraction: ["healthy", "failing", "unknown"].includes(extraction?.state) ? extraction.state : "unknown",
|
|
214
|
+
...(extraction?.state === "failing" && typeof extraction.failing_since === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(extraction.failing_since) ? { failing_since: extraction.failing_since } : {}),
|
|
198
215
|
...(kept.records ? { records: kept.records } : {}),
|
|
199
216
|
space: spaceOf(scopes[0]?.context),
|
|
200
217
|
counts,
|
|
@@ -318,8 +335,19 @@ export function createViewReads({ runtime, agents = async () => [] }) {
|
|
|
318
335
|
}
|
|
319
336
|
}
|
|
320
337
|
|
|
338
|
+
async function inboxList() {
|
|
339
|
+
const review = await recordsReads.methods["review.list"]({})
|
|
340
|
+
return { items: review.items.flatMap((item) => {
|
|
341
|
+
if (!/^rec_[0-9A-Za-z]{1,64}$/.test(item.id)) return []
|
|
342
|
+
if (!inboxTime(item.created)) return []
|
|
343
|
+
const title = String(item.title).replace(/[\p{Cc}\p{Cf}<>]/gu, " ").replace(/\s+/g, " ").trim().slice(0, 120)
|
|
344
|
+
return [{ key: `proposal:${item.id}`, category: "request", label: "Proposal", name: "Memory", line: title || "A proposal is waiting for review", at: item.created }]
|
|
345
|
+
}) }
|
|
346
|
+
}
|
|
347
|
+
|
|
321
348
|
return {
|
|
322
349
|
"commitments.list": commitmentsList,
|
|
350
|
+
"inbox.list": inboxList,
|
|
323
351
|
"memory.overview": overview,
|
|
324
352
|
"spaces.list": spacesList,
|
|
325
353
|
"wiki.list": wikiList,
|
|
@@ -411,7 +439,7 @@ export function splitSpeaker(input) {
|
|
|
411
439
|
* @param {any} ctx
|
|
412
440
|
* @param {any} runtime
|
|
413
441
|
*/
|
|
414
|
-
export async function registerViewRpc(ctx, runtime) {
|
|
442
|
+
export async function registerViewRpc(ctx, runtime, { enableInboxActions = INBOX_ACTION_RPC_ENABLED, verifyInboxAction } = {}) {
|
|
415
443
|
if (typeof ctx?.rpc?.register !== "function") return null
|
|
416
444
|
const reads = createViewReads({ runtime, agents: engineAgents(ctx) })
|
|
417
445
|
const methods = {}
|
|
@@ -432,5 +460,19 @@ export async function registerViewRpc(ctx, runtime) {
|
|
|
432
460
|
return typeof speaker === "string" ? asView(speaker, read) : read()
|
|
433
461
|
}
|
|
434
462
|
}
|
|
463
|
+
if (enableInboxActions) {
|
|
464
|
+
if (typeof verifyInboxAction !== "function") throw new Error("Inbox actions require a grant verifier and ask bridge")
|
|
465
|
+
const decide = createHeldInboxDecision(runtime)
|
|
466
|
+
methods["act.inbox.decide"] = {
|
|
467
|
+
input: { type: "object", additionalProperties: false, required: ["key", "decision"], properties: { key: { type: "string" }, decision: { type: "string", enum: ["accept", "private", "decline"] } } },
|
|
468
|
+
output: { type: "object" },
|
|
469
|
+
}
|
|
470
|
+
handlers["act.inbox.decide"] = async (input, call) => {
|
|
471
|
+
// The verifier must validate the signed, input-bound grant and enforce the
|
|
472
|
+
// separate memory.revise ask; page-provided identity is never accepted.
|
|
473
|
+
const speaker = await verifyInboxAction({ input, call })
|
|
474
|
+
return decide({ key: input?.key, decision: input?.decision, caller: { runtime, speaker } })
|
|
475
|
+
}
|
|
476
|
+
}
|
|
435
477
|
return ctx.rpc.register({ id: PACKAGE_NAME, events: {}, methods }, handlers)
|
|
436
478
|
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en-GB">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-5dtPKkjegOPG8bawdSzGBjixnIaSCLYcZOUAwbRWFAc=' 'sha256-LWSrwYvpjwYQwZdOGG46gdsMvGXpb6MbK0p4FgHUWDU='; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
|
|
6
|
+
<title>Recalled memory</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root { color: var(--jelly-text, CanvasText); background: var(--jelly-surface, Canvas); font: 14px/1.5 var(--jelly-font, system-ui, sans-serif); }
|
|
9
|
+
body { margin: 0; padding: 16px; }
|
|
10
|
+
h1 { font-size: 18px; margin: 0 0 12px; }
|
|
11
|
+
p { margin: 8px 0; }
|
|
12
|
+
.muted { color: var(--jelly-muted, GrayText); }
|
|
13
|
+
</style>
|
|
14
|
+
</head>
|
|
15
|
+
<body>
|
|
16
|
+
<main aria-live="polite"><h1>Recalled memory</h1><div id="coverage" class="muted">Loading…</div><div id="scope"></div><div id="counts"></div><div id="incomplete"></div></main>
|
|
17
|
+
<script>
|
|
18
|
+
// jelly-view.js: a client of Jelly's view bridge. Paste it into the page's own <script>:
|
|
19
|
+
// a sealed page loads no script by URL and is given no global. Call jellyView() as the
|
|
20
|
+
// script starts; it resolves with the client when the app says hello.
|
|
21
|
+
function jellyView() {
|
|
22
|
+
return new Promise((resolve) => {
|
|
23
|
+
addEventListener("message", function hello(event) {
|
|
24
|
+
const said = event.data;
|
|
25
|
+
if (event.source !== parent || said?.v !== 1 || said.kind !== "hello" || !event.ports[0])
|
|
26
|
+
return;
|
|
27
|
+
removeEventListener("message", hello);
|
|
28
|
+
const port = event.ports[0];
|
|
29
|
+
const listeners = new Set();
|
|
30
|
+
const latest = new Map();
|
|
31
|
+
const queue = [];
|
|
32
|
+
let sequence = 0;
|
|
33
|
+
let current;
|
|
34
|
+
const theme = (tokens) => {
|
|
35
|
+
const style = document.documentElement.style;
|
|
36
|
+
for (const [name, value] of Object.entries(tokens))
|
|
37
|
+
if (name === "scheme") style.colorScheme = value;
|
|
38
|
+
else style.setProperty(`--jelly-${name}`, value);
|
|
39
|
+
};
|
|
40
|
+
// The app answers one request at a time, so requests go in turn.
|
|
41
|
+
const next = () => {
|
|
42
|
+
if (current !== undefined || queue.length === 0) return;
|
|
43
|
+
current = queue.shift();
|
|
44
|
+
current.timer = setTimeout(
|
|
45
|
+
() => settle({ ok: false, error: "No answer from the app" }),
|
|
46
|
+
15000,
|
|
47
|
+
);
|
|
48
|
+
port.postMessage(current.message);
|
|
49
|
+
};
|
|
50
|
+
const settle = (answer) => {
|
|
51
|
+
const done = current;
|
|
52
|
+
current = undefined;
|
|
53
|
+
clearTimeout(done.timer);
|
|
54
|
+
if (answer.ok) done.resolve(answer.value);
|
|
55
|
+
else done.reject(new Error(answer.error));
|
|
56
|
+
next();
|
|
57
|
+
};
|
|
58
|
+
port.onmessage = ({ data }) => {
|
|
59
|
+
if (data?.v !== 1) return;
|
|
60
|
+
if (typeof data.kind !== "string") {
|
|
61
|
+
if (current !== undefined && data.re === current.message.id) settle(data);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
// A call waiting for the person is answered by `until`, not in 15 s.
|
|
65
|
+
if (data.kind === "rpc.waiting" && data.re === current?.message.id) {
|
|
66
|
+
clearTimeout(current.timer);
|
|
67
|
+
current.timer = setTimeout(
|
|
68
|
+
() => settle({ ok: false, error: "No answer from the app" }),
|
|
69
|
+
Math.max(0, Date.parse(data.until) - Date.now()) + 15000,
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
if (data.kind === "theme.changed") theme(data.theme);
|
|
73
|
+
// A wait is news only while it lasts, so a later listener is not told of it.
|
|
74
|
+
if (data.kind !== "rpc.waiting") latest.set(data.kind, data);
|
|
75
|
+
for (const listener of listeners) listener(data);
|
|
76
|
+
};
|
|
77
|
+
port.start();
|
|
78
|
+
theme(said.theme);
|
|
79
|
+
const request = (op, fields = {}) =>
|
|
80
|
+
new Promise((resolve, reject) => {
|
|
81
|
+
queue.push({ resolve, reject, message: { ...fields, v: 1, id: String(++sequence), op } });
|
|
82
|
+
next();
|
|
83
|
+
});
|
|
84
|
+
resolve({
|
|
85
|
+
hello: said,
|
|
86
|
+
// A listener first hears the latest push of each kind that came before it.
|
|
87
|
+
on(listener) {
|
|
88
|
+
for (const push of latest.values()) listener(push);
|
|
89
|
+
listeners.add(listener);
|
|
90
|
+
return () => listeners.delete(listener);
|
|
91
|
+
},
|
|
92
|
+
request,
|
|
93
|
+
data: () => request("data.get"),
|
|
94
|
+
state: () => request("state.get"),
|
|
95
|
+
setState: (revision, data) => request("state.set", { revision, data }),
|
|
96
|
+
call: (method, input = {}) => request("rpc.call", { method, input }),
|
|
97
|
+
openAgent: (prefill) => request("open-agent", prefill === undefined ? {} : { prefill }),
|
|
98
|
+
resize: (height) =>
|
|
99
|
+
request("resize", { height: Math.min(1200, Math.max(1, Math.ceil(height))) }),
|
|
100
|
+
decline: () => request("decline"),
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
</script>
|
|
106
|
+
<script>
|
|
107
|
+
jellyView().then(async (view) => {
|
|
108
|
+
const result = await view.data();
|
|
109
|
+
const data = result?.metadata?.memoryRecall;
|
|
110
|
+
const coverage = document.getElementById("coverage");
|
|
111
|
+
if (!data || data.v !== 1 || !data.counts || typeof data.incomplete !== "boolean") {
|
|
112
|
+
coverage.textContent = "Recall details are not available for this result.";
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
coverage.textContent = typeof data.coverage === "string" ? data.coverage : "";
|
|
116
|
+
document.getElementById("scope").textContent = typeof data.scopeNote === "string" ? data.scopeNote : "";
|
|
117
|
+
const count = (value) => Number.isSafeInteger(value) && value >= 0 ? value : 0;
|
|
118
|
+
document.getElementById("counts").textContent = `${count(data.counts.records)} records · ${count(data.counts.atoms)} atoms · ${count(data.counts.conversations)} conversations matched`;
|
|
119
|
+
document.getElementById("incomplete").textContent = data.incomplete ? "Search incomplete; do not infer absence." : "";
|
|
120
|
+
}).catch(() => { document.getElementById("coverage").textContent = "Recall details are not available for this result."; });
|
|
121
|
+
</script>
|
|
122
|
+
</body>
|
|
123
|
+
</html>
|