@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/LICENSE +21 -0
- package/README.md +381 -2
- package/SECURITY.md +135 -0
- package/assets/icon.svg +14 -0
- package/docs/agent-protocol.md +190 -0
- package/index.js +4 -0
- package/package.json +186 -4
- package/skills/mem-usage/SKILL.md +427 -0
- package/src/backend/v3.js +562 -0
- package/src/bootstrap.js +85 -0
- package/src/capture.js +143 -0
- package/src/commands.js +152 -0
- package/src/compaction.js +402 -0
- package/src/config.js +193 -0
- package/src/copies.js +322 -0
- package/src/credentials.js +430 -0
- package/src/curation.js +240 -0
- package/src/erase.js +36 -0
- package/src/events.js +394 -0
- package/src/hooks.js +182 -0
- package/src/index.js +189 -0
- package/src/limits.js +90 -0
- package/src/log.js +161 -0
- package/src/protocol.js +48 -0
- package/src/recall.js +368 -0
- package/src/runtime.js +870 -0
- package/src/scope.js +127 -0
- package/src/sessions.js +62 -0
- package/src/skill-contexts.js +168 -0
- package/src/skills.js +252 -0
- package/src/spaces.js +478 -0
- package/src/spool.js +520 -0
- package/src/tools/index.js +51 -0
- package/src/tools/knowledge.js +90 -0
- package/src/tools/memory.js +1239 -0
- package/src/tools/recall.js +273 -0
- package/src/tools/shared.js +339 -0
- package/src/tools/spaces.js +179 -0
- package/src/tools/status.js +65 -0
- package/src/tools/wiki.js +412 -0
- package/src/util.js +176 -0
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { isCheckpointMessage, renderRecallBlock } from "../recall.js"
|
|
2
|
+
import { addWithheld, partitionAtoms, partitionTurns } from "../curation.js"
|
|
3
|
+
import { errorMessage } from "../util.js"
|
|
4
|
+
import { discoverKnowledge, searchKnowledge } from "./knowledge.js"
|
|
5
|
+
import { TASK_INPUT } from "./shared.js"
|
|
6
|
+
|
|
7
|
+
/** Upper bound on atoms per recall; the character budget still applies. */
|
|
8
|
+
const MAX_LIMIT = 25
|
|
9
|
+
/** Raw turns rendered per recall. Atoms carry the distilled answer. */
|
|
10
|
+
const MAX_TURNS = 4
|
|
11
|
+
/**
|
|
12
|
+
* Upstream L1 types a caller may restrict a search to. `work_task` is absent on
|
|
13
|
+
* purpose: task descriptions are withheld from recall (see curation.js).
|
|
14
|
+
*/
|
|
15
|
+
const ATOM_TYPES = Object.freeze(["persona", "episodic", "instruction", "work_fact", "work_method", "work_artifact"])
|
|
16
|
+
|
|
17
|
+
/** Whether upstream returned a task field for this row (L1 hits do, L0 search hits do not). */
|
|
18
|
+
function hasTaskField(row) {
|
|
19
|
+
return Boolean(row) && (Object.hasOwn(row, "task_id") || Object.hasOwn(row, "taskId"))
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The task a row was written under, as upstream returns it. */
|
|
23
|
+
function rowTask(row) {
|
|
24
|
+
const value = row?.task_id ?? row?.taskId
|
|
25
|
+
return value === undefined || value === null || value === "" ? undefined : String(value)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* `mem_recall`: pull-based retrieval across memory, wiki, and code graph.
|
|
30
|
+
*
|
|
31
|
+
* @param {any} editor
|
|
32
|
+
* @param {ReturnType<import("./shared.js").createToolkit>} toolkit
|
|
33
|
+
*/
|
|
34
|
+
export function registerRecall(editor, toolkit) {
|
|
35
|
+
const { backend, config, log, control, text, fail, sharedScope, resolveReadSpace, displayScope, noteLocations } = toolkit
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Reads describe the whole space, not one session. L0 writes from
|
|
39
|
+
* `mem_remember` and capture live under synthetic session ids, so scoping a
|
|
40
|
+
* recall query by the current session hides the very memories just written.
|
|
41
|
+
*/
|
|
42
|
+
function readScope(scoped) {
|
|
43
|
+
const { session_id, ...rest } = scoped
|
|
44
|
+
return rest
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
editor.add({
|
|
48
|
+
name: "recall",
|
|
49
|
+
description:
|
|
50
|
+
"Search durable memory (L1 atoms and L0 turns of one space; optionally wiki and code graph) before re-deriving context: when the user refers to past work, decisions, constraints, or preferences, when you start work in an area with history, or before asking something already answered. With a task it searches that task first and widens to the whole space only on a miss; hits are labelled scope=task or scope=space. It cannot see the L2 scenarios or L3 persona. Task descriptions, status, and instruction-shaped records are withheld and counted. Results may be stale: verify before acting.",
|
|
51
|
+
input: {
|
|
52
|
+
type: "object",
|
|
53
|
+
properties: {
|
|
54
|
+
query: { type: "string", description: "Natural-language description of what to look for, e.g. \"auth refactor constraints\"" },
|
|
55
|
+
task: TASK_INPUT,
|
|
56
|
+
visibility: {
|
|
57
|
+
type: "string",
|
|
58
|
+
enum: ["auto", "private", "team"],
|
|
59
|
+
description:
|
|
60
|
+
"auto (default): the session's space, a bound shared space or else personal; private: your personal space; team: a shared space, bound or passed with space",
|
|
61
|
+
},
|
|
62
|
+
limit: {
|
|
63
|
+
type: "number",
|
|
64
|
+
description: `Atoms to return (default ${config.recallLimit}, max ${MAX_LIMIT}); up to ${MAX_TURNS} turns are added; the character budget applies`,
|
|
65
|
+
},
|
|
66
|
+
type: {
|
|
67
|
+
type: "string",
|
|
68
|
+
enum: [...ATOM_TYPES],
|
|
69
|
+
description: "Only atoms of this upstream L1 type; turns are then not searched",
|
|
70
|
+
},
|
|
71
|
+
sources: {
|
|
72
|
+
type: "string",
|
|
73
|
+
enum: ["memory", "knowledge", "all"],
|
|
74
|
+
description: "memory (default) searches stored memories; knowledge searches wiki/code-graph; all searches both",
|
|
75
|
+
},
|
|
76
|
+
knowledge_id: { type: "string", description: "Wiki or code-graph asset id; discovered automatically when omitted" },
|
|
77
|
+
space: { type: "string", description: "Space id to search (control plane); does not rebind the session" },
|
|
78
|
+
},
|
|
79
|
+
required: ["query"],
|
|
80
|
+
additionalProperties: false,
|
|
81
|
+
},
|
|
82
|
+
options: { namespace: "mem" },
|
|
83
|
+
execute: async (input, context) => {
|
|
84
|
+
const query = String(input?.query ?? "").trim()
|
|
85
|
+
if (!query) return text("nothing to recall: query is empty")
|
|
86
|
+
const limit = Math.max(1, Math.min(Math.floor(Number(input?.limit)) || config.recallLimit, MAX_LIMIT))
|
|
87
|
+
const visibility = ["auto", "private", "team"].includes(String(input?.visibility)) ? String(input.visibility) : "auto"
|
|
88
|
+
const sources = input?.sources ?? "memory"
|
|
89
|
+
const type = input?.type === undefined || input?.type === null || input?.type === "" ? undefined : String(input.type)
|
|
90
|
+
if (type && !ATOM_TYPES.includes(type)) {
|
|
91
|
+
return text(
|
|
92
|
+
type === "work_task"
|
|
93
|
+
? "work_task atoms are task descriptions; recall withholds them. Read the tracker for tasks."
|
|
94
|
+
: `unknown atom type ${type}; use one of ${ATOM_TYPES.join(", ")}.`,
|
|
95
|
+
)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const task = toolkit.taskFor(input, context)
|
|
99
|
+
if (task.invalid) return text(task.invalid)
|
|
100
|
+
|
|
101
|
+
const resolved = await resolveReadSpace(input, context, visibility)
|
|
102
|
+
if (resolved.invalid) return text(resolved.invalid)
|
|
103
|
+
if (resolved.error) return fail(resolved.error)
|
|
104
|
+
const spaceContext = resolved.context
|
|
105
|
+
const scoped = spaceContext
|
|
106
|
+
? toolkit.scopeFor(spaceContext, { agent: context?.agent })
|
|
107
|
+
: toolkit.scope({ agent: context?.agent })
|
|
108
|
+
|
|
109
|
+
try {
|
|
110
|
+
// Over-fetch atoms: curation can withhold part of a page, and the
|
|
111
|
+
// caller asked for `limit` servable atoms, not `limit` candidates.
|
|
112
|
+
const scope = readScope(scoped)
|
|
113
|
+
const key = task.key
|
|
114
|
+
async function searchIn(searchScope) {
|
|
115
|
+
let failed = false
|
|
116
|
+
const [atomPage, turnPage] = await Promise.all([
|
|
117
|
+
backend.searchAtoms({ query, limit: Math.min(MAX_LIMIT, limit * 2), scope: searchScope, type }).catch(() => {
|
|
118
|
+
failed = true
|
|
119
|
+
return null
|
|
120
|
+
}),
|
|
121
|
+
type
|
|
122
|
+
? Promise.resolve(null)
|
|
123
|
+
: backend.searchConversations({ query, limit: Math.min(MAX_TURNS * 2, limit * 2), scope: searchScope }).catch(() => {
|
|
124
|
+
failed = true
|
|
125
|
+
return null
|
|
126
|
+
}),
|
|
127
|
+
])
|
|
128
|
+
// Remember where each hit was written, so mem_forget can address the
|
|
129
|
+
// delete to the row's own agent and session.
|
|
130
|
+
noteLocations(spaceContext, "l1", atomPage?.items, { agent_id: scope.agent_id })
|
|
131
|
+
noteLocations(spaceContext, "l0", turnPage?.messages, { agent_id: scope.agent_id })
|
|
132
|
+
// A hit that carries its task is labelled by it, so a backend that
|
|
133
|
+
// ignored the header cannot make another task's record look like this
|
|
134
|
+
// one's. Upstream L0 search hits carry no task field at all (only id,
|
|
135
|
+
// role, content, score, timestamp); for those the request decides:
|
|
136
|
+
// upstream filters a search sent with x-tdai-task-id to that task, so
|
|
137
|
+
// its hits are the task's, and a widened search's hits are not.
|
|
138
|
+
const filtered = Boolean(searchScope.task_id)
|
|
139
|
+
const bucketOf = (row) => {
|
|
140
|
+
if (!hasTaskField(row)) return filtered ? "task" : "space"
|
|
141
|
+
return rowTask(row) === key ? "task" : "space"
|
|
142
|
+
}
|
|
143
|
+
const label = (row) => (key ? { ...row, _bucket: bucketOf(row) } : row)
|
|
144
|
+
const atomPart = partitionAtoms(atomPage?.items ?? [])
|
|
145
|
+
const turnPart = partitionTurns(turnPage?.messages ?? [], { isCheckpoint: isCheckpointMessage })
|
|
146
|
+
return {
|
|
147
|
+
atoms: atomPart.served.map(label),
|
|
148
|
+
conversations: turnPart.served.map(label),
|
|
149
|
+
withheld: addWithheld(atomPart.withheld, turnPart.withheld),
|
|
150
|
+
failed,
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let result = { atoms: [], conversations: [], withheld: addWithheld(), failed: false }
|
|
155
|
+
let scopeNote
|
|
156
|
+
if (sources !== "knowledge") {
|
|
157
|
+
if (key) {
|
|
158
|
+
const first = await searchIn({ ...scope, task_id: key })
|
|
159
|
+
const rows = [...first.atoms, ...first.conversations]
|
|
160
|
+
if (rows.some((row) => row._bucket === "task")) {
|
|
161
|
+
result = first
|
|
162
|
+
scopeNote = rows.some((row) => row._bucket === "space")
|
|
163
|
+
? `Searched task "${key}". scope=task hits belong to it; scope=space hits were recorded outside it and are still valid memory of this space.`
|
|
164
|
+
: `Searched task "${key}"; every hit belongs to it.`
|
|
165
|
+
} else {
|
|
166
|
+
result = await searchIn(scope)
|
|
167
|
+
result.failed = result.failed || first.failed
|
|
168
|
+
scopeNote =
|
|
169
|
+
result.atoms.length + result.conversations.length > 0
|
|
170
|
+
? `No match in task "${key}"; widened to the whole space. scope=space hits were recorded outside this task and are still valid memory of this space: use them, and say where they came from.`
|
|
171
|
+
: `Searched task "${key}", then the whole space.`
|
|
172
|
+
}
|
|
173
|
+
} else {
|
|
174
|
+
result = await searchIn(scope)
|
|
175
|
+
scopeNote = task.wholeSpace ? "Searched the whole space." : "No task declared; searched the whole space."
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const { atoms, conversations, failed, withheld } = result
|
|
179
|
+
|
|
180
|
+
for (const atom of atoms) {
|
|
181
|
+
if (atom?.asset_id) void backend.touchAsset({ assetID: atom.asset_id, scope: sharedScope(spaceContext) }).catch(() => {})
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// An empty result is ambiguous: nothing stored, nothing matching these
|
|
185
|
+
// words, everything withheld, or a failed search. Say which one, so the
|
|
186
|
+
// agent can stop instead of fanning out across spaces, grants, and the
|
|
187
|
+
// wiki.
|
|
188
|
+
const BROWSE_MAX_RECORDS = 12
|
|
189
|
+
const BROWSE_ATOMS = 6
|
|
190
|
+
const BROWSE_TURNS = 4
|
|
191
|
+
let census
|
|
192
|
+
let browse
|
|
193
|
+
if (sources !== "knowledge" && atoms.length === 0 && conversations.length === 0) {
|
|
194
|
+
const [atomsCount, conversationsCount] = await Promise.all([
|
|
195
|
+
backend.countAtoms({ scope }).then((data) => Number(data?.total) || 0).catch(() => null),
|
|
196
|
+
backend.countConversations({ scope }).then((data) => Number(data?.total) || 0).catch(() => null),
|
|
197
|
+
])
|
|
198
|
+
census = {
|
|
199
|
+
atoms: atomsCount ?? 0,
|
|
200
|
+
conversations: conversationsCount ?? 0,
|
|
201
|
+
failed: failed || atomsCount === null || conversationsCount === null,
|
|
202
|
+
otherScopesSearched: !(control && spaceContext),
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// A small scope can be described when a query misses: a question and a
|
|
206
|
+
// record often share no word at all. Above the cap, report the count
|
|
207
|
+
// and do not dump the store. Nothing here is scored for relevance, and
|
|
208
|
+
// it stays inside the space that was searched.
|
|
209
|
+
const totalRecords = census.atoms + census.conversations
|
|
210
|
+
if (!census.failed && totalRecords > 0 && totalRecords <= BROWSE_MAX_RECORDS) {
|
|
211
|
+
// A backend older than the query endpoints simply has no browse;
|
|
212
|
+
// that must not turn a miss into an error.
|
|
213
|
+
const listRecent = (read) => Promise.resolve().then(read).catch(() => null)
|
|
214
|
+
const [recentAtoms, recentTurns] = await Promise.all([
|
|
215
|
+
listRecent(() => backend.queryAtoms({ scope, limit: BROWSE_ATOMS, type })),
|
|
216
|
+
type ? Promise.resolve(null) : listRecent(() => backend.queryConversations({ scope, limit: BROWSE_TURNS })),
|
|
217
|
+
])
|
|
218
|
+
// The browse path reads the scope directly, so it applies the same
|
|
219
|
+
// curation guards as the search path. Without this, a withheld
|
|
220
|
+
// record returns through atomic/query and the filter is decorative.
|
|
221
|
+
noteLocations(spaceContext, "l1", recentAtoms?.items, { agent_id: scope.agent_id })
|
|
222
|
+
noteLocations(spaceContext, "l0", recentTurns?.messages, { agent_id: scope.agent_id })
|
|
223
|
+
const browseAtoms = partitionAtoms(recentAtoms?.items ?? []).served.slice(0, BROWSE_ATOMS)
|
|
224
|
+
const browseConversations = partitionTurns(recentTurns?.messages ?? [], { isCheckpoint: isCheckpointMessage })
|
|
225
|
+
.served.slice(0, BROWSE_TURNS)
|
|
226
|
+
if (browseAtoms.length + browseConversations.length > 0) browse = { atoms: browseAtoms, conversations: browseConversations }
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
let block = renderRecallBlock({
|
|
231
|
+
atoms,
|
|
232
|
+
conversations,
|
|
233
|
+
scope: scoped,
|
|
234
|
+
scopeLabel: spaceContext ? displayScope(spaceContext, scoped) : undefined,
|
|
235
|
+
maxChars: config.recallChars,
|
|
236
|
+
maxAtoms: limit,
|
|
237
|
+
maxTurns: MAX_TURNS,
|
|
238
|
+
query,
|
|
239
|
+
census,
|
|
240
|
+
browse,
|
|
241
|
+
withheld,
|
|
242
|
+
scopeNote,
|
|
243
|
+
})
|
|
244
|
+
|
|
245
|
+
if (sources === "knowledge" || sources === "all") {
|
|
246
|
+
const knowledgeScope = sharedScope(spaceContext)
|
|
247
|
+
const ids = input?.knowledge_id
|
|
248
|
+
? [String(input.knowledge_id)]
|
|
249
|
+
: await discoverKnowledge(backend, log, undefined, knowledgeScope)
|
|
250
|
+
const knowledge =
|
|
251
|
+
ids.length === 0
|
|
252
|
+
? ""
|
|
253
|
+
: await searchKnowledge(backend, ids.slice(0, 2), query, knowledgeScope, {
|
|
254
|
+
maxChars: Math.max(1500, Math.floor(config.recallChars * 0.5)),
|
|
255
|
+
})
|
|
256
|
+
block += knowledge ? `\n\n${knowledge}` : "\n\n(no accessible wiki assets found)"
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
log.debug("recall", {
|
|
260
|
+
scope: displayScope(spaceContext, scoped),
|
|
261
|
+
task: Boolean(key),
|
|
262
|
+
atoms: atoms.length,
|
|
263
|
+
conversations: conversations.length,
|
|
264
|
+
withheld,
|
|
265
|
+
})
|
|
266
|
+
return text(block)
|
|
267
|
+
} catch (error) {
|
|
268
|
+
log.warn("recall failed", error)
|
|
269
|
+
return fail(errorMessage(error))
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
})
|
|
273
|
+
}
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import { contextScopeLabel, scopeLabel, taskKey } from "../scope.js"
|
|
2
|
+
import { errorMessage, oneLine } from "../util.js"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Roles that may write to a shared space. The plugin reads this from the
|
|
6
|
+
* control plane's context answer; it never derives or upgrades a grant.
|
|
7
|
+
*/
|
|
8
|
+
export const SHARED_WRITE_ROLES = Object.freeze(["editor", "admin", "owner"])
|
|
9
|
+
|
|
10
|
+
/** A per-call `task` value meaning "the whole space, not one task". */
|
|
11
|
+
export const WHOLE_SPACE = "*"
|
|
12
|
+
|
|
13
|
+
/** The shared description of the `task` input on recall, remember, and forget. */
|
|
14
|
+
export const TASK_INPUT = Object.freeze({
|
|
15
|
+
type: "string",
|
|
16
|
+
description:
|
|
17
|
+
'One line naming the work, not the topic ("fix the migration ordering"). Kept for the session: later calls and captured turns use it. "*" means the whole space for this call',
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
/** True when a control-plane role may write to a shared space. */
|
|
21
|
+
export function canWriteShared(role) {
|
|
22
|
+
return SHARED_WRITE_ROLES.includes(String(role ?? "").trim().toLowerCase())
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Helpers shared by the memory tool modules. The control plane is the only
|
|
27
|
+
* source of a space, its placement, and the caller's role.
|
|
28
|
+
*/
|
|
29
|
+
export function createToolkit(ctx, runtime) {
|
|
30
|
+
const { backend, config, log } = runtime
|
|
31
|
+
const control = runtime.control
|
|
32
|
+
|
|
33
|
+
const text = (content) => ({ content })
|
|
34
|
+
const fail = (message) => text(`memory unavailable: ${message}`)
|
|
35
|
+
|
|
36
|
+
/** Shared-asset scope (skills, wiki). Agent is intentionally absent. */
|
|
37
|
+
function sharedScope(context) {
|
|
38
|
+
const scoped = runtime.scope({ context })
|
|
39
|
+
delete scoped.agent_id
|
|
40
|
+
return scoped
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Resolve the optional space argument. In control-plane mode an omitted space
|
|
45
|
+
* means the active context. In local direct mode an explicit space is an error
|
|
46
|
+
* rather than a silent no-op, because there is nothing that could resolve it.
|
|
47
|
+
*/
|
|
48
|
+
async function resolveSpace(input, context, { bind = false } = {}) {
|
|
49
|
+
const requested = String(input?.space ?? "").trim()
|
|
50
|
+
if (!control) {
|
|
51
|
+
if (requested) return { error: "control plane not configured; set MEMORY_CONTROL_URL to select a space" }
|
|
52
|
+
return { context: null }
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
const resolved = await runtime.resolveContext({
|
|
56
|
+
space: requested || undefined,
|
|
57
|
+
// A read with an explicit space must not rebind the session. A read
|
|
58
|
+
// without a space follows the session's existing binding. Only an
|
|
59
|
+
// explicit write binds the session to the requested space.
|
|
60
|
+
sessionID: requested ? (bind ? context?.sessionID : undefined) : context?.sessionID,
|
|
61
|
+
agent: context?.agent,
|
|
62
|
+
})
|
|
63
|
+
if (!resolved) return { error: "the control plane returned no space context" }
|
|
64
|
+
return { context: resolved }
|
|
65
|
+
} catch (error) {
|
|
66
|
+
return { error: errorMessage(error) }
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Resolve the personal space for a private read. An explicit shared space is
|
|
72
|
+
* a caller error, not a request to search shared memory, so it fails closed.
|
|
73
|
+
*/
|
|
74
|
+
async function resolvePrivateSpace(input, context) {
|
|
75
|
+
const requested = String(input?.space ?? "").trim()
|
|
76
|
+
if (!control) {
|
|
77
|
+
if (requested) return { error: "control plane not configured; set MEMORY_CONTROL_URL to select a space" }
|
|
78
|
+
return { context: null }
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
if (requested) {
|
|
82
|
+
const resolved = await runtime.resolveContext({ space: requested, agent: context?.agent })
|
|
83
|
+
if (!resolved) throw new Error("the control plane returned no space context")
|
|
84
|
+
if (resolved.space_kind !== "personal") {
|
|
85
|
+
return {
|
|
86
|
+
invalid: `visibility=private uses your personal space; ${oneLine(requested, 80)} is not personal. Omit space or pass your personal space.`,
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return { context: resolved }
|
|
90
|
+
}
|
|
91
|
+
const personal = await runtime.captureContext(context?.sessionID, context?.agent, "private")
|
|
92
|
+
if (!personal || personal.space_kind !== "personal") {
|
|
93
|
+
throw new Error("the control plane returned no personal space")
|
|
94
|
+
}
|
|
95
|
+
return { context: personal }
|
|
96
|
+
} catch (error) {
|
|
97
|
+
return { error: errorMessage(error) }
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Resolve the space a memory read searches. An explicit space is read as
|
|
103
|
+
* given and never rebinds the session. Without one, a read follows the rule
|
|
104
|
+
* the pinned block and capture already use: a shared space bound to this
|
|
105
|
+
* session, otherwise the personal space. A shared default that is not bound
|
|
106
|
+
* is not a selection, for reads as for writes; reading it would make recall
|
|
107
|
+
* and the pinned block describe different spaces in one session.
|
|
108
|
+
*
|
|
109
|
+
* `team` requires the resolved space to be shared, so it never silently
|
|
110
|
+
* searches the personal space under a team label.
|
|
111
|
+
*/
|
|
112
|
+
async function resolveReadSpace(input, context, visibility = "auto") {
|
|
113
|
+
const requested = String(input?.space ?? "").trim()
|
|
114
|
+
if (!control) {
|
|
115
|
+
if (requested) return { error: "control plane not configured; set MEMORY_CONTROL_URL to select a space" }
|
|
116
|
+
return { context: null }
|
|
117
|
+
}
|
|
118
|
+
if (visibility === "private") return resolvePrivateSpace(input, context)
|
|
119
|
+
let spaceContext
|
|
120
|
+
try {
|
|
121
|
+
spaceContext = requested
|
|
122
|
+
? await runtime.resolveContext({ space: requested, agent: context?.agent })
|
|
123
|
+
: await runtime.sessionContext(context?.sessionID, context?.agent)
|
|
124
|
+
} catch (error) {
|
|
125
|
+
return { error: errorMessage(error) }
|
|
126
|
+
}
|
|
127
|
+
if (!spaceContext) return { error: "the control plane returned no space context" }
|
|
128
|
+
if (visibility === "team" && spaceContext.space_kind !== "shared") {
|
|
129
|
+
return {
|
|
130
|
+
invalid: requested
|
|
131
|
+
? `visibility=team searches a shared space; ${oneLine(requested, 80)} is personal.`
|
|
132
|
+
: "visibility=team needs a shared space bound to this session; pass a shared space with the space argument.",
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { context: spaceContext }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Resolve the space a write or delete belongs to. Private is always personal.
|
|
140
|
+
* Team needs a shared space that was explicitly selected or is bound to the
|
|
141
|
+
* session, and the control plane must report an editor-or-higher role. In
|
|
142
|
+
* local direct mode the fixed local scope is the only target.
|
|
143
|
+
*/
|
|
144
|
+
async function resolveWriteSpace(input, context, visibility) {
|
|
145
|
+
const requested = String(input?.space ?? "").trim()
|
|
146
|
+
if (!control) {
|
|
147
|
+
if (requested) {
|
|
148
|
+
return { invalid: "control plane not configured; set MEMORY_CONTROL_URL to select a space" }
|
|
149
|
+
}
|
|
150
|
+
return { context: null }
|
|
151
|
+
}
|
|
152
|
+
if (visibility === "private") return resolvePrivateSpace(input, context)
|
|
153
|
+
|
|
154
|
+
let spaceContext
|
|
155
|
+
try {
|
|
156
|
+
if (requested) {
|
|
157
|
+
spaceContext = await runtime.resolveContext({
|
|
158
|
+
space: requested,
|
|
159
|
+
sessionID: context?.sessionID,
|
|
160
|
+
agent: context?.agent,
|
|
161
|
+
})
|
|
162
|
+
} else {
|
|
163
|
+
// A shared default is not a selection. captureContext only returns a
|
|
164
|
+
// shared space when the control plane reports a session binding.
|
|
165
|
+
spaceContext = await runtime.captureContext(context?.sessionID, context?.agent, "team")
|
|
166
|
+
}
|
|
167
|
+
} catch (error) {
|
|
168
|
+
return { error: errorMessage(error) }
|
|
169
|
+
}
|
|
170
|
+
if (!spaceContext) return { error: "the control plane returned no space context" }
|
|
171
|
+
|
|
172
|
+
if (spaceContext.space_kind !== "shared") {
|
|
173
|
+
return {
|
|
174
|
+
invalid: requested
|
|
175
|
+
? `visibility=team needs a shared space; ${oneLine(requested, 80)} is personal.`
|
|
176
|
+
: "visibility=team needs a shared space bound to this session; pass a shared space explicitly.",
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (!requested && !runtime.isSessionBound(spaceContext)) {
|
|
180
|
+
return {
|
|
181
|
+
invalid: "visibility=team needs a shared space bound to this session; pass a shared space explicitly.",
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const role = String(spaceContext.role ?? "").trim().toLowerCase()
|
|
185
|
+
if (!canWriteShared(role)) {
|
|
186
|
+
return {
|
|
187
|
+
invalid: `writing to ${oneLine(spaceContext.space_id, 80)} requires editor, admin, or owner access; the control plane reports role ${
|
|
188
|
+
role || "unknown"
|
|
189
|
+
}.`,
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return { context: spaceContext }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The task for one tool call. A declared task is stored for the session and
|
|
197
|
+
* returned; "*" selects the whole space for this call without changing the
|
|
198
|
+
* session's task; no input falls back to the session's declared task.
|
|
199
|
+
*
|
|
200
|
+
* @returns {{ key?: string, declared?: boolean, wholeSpace?: boolean, invalid?: string }}
|
|
201
|
+
*/
|
|
202
|
+
function taskFor(input, context) {
|
|
203
|
+
runtime.noteAgent?.(context?.sessionID, context?.agent)
|
|
204
|
+
const raw = input?.task
|
|
205
|
+
if (raw === undefined || raw === null || String(raw).trim() === "") {
|
|
206
|
+
return { key: runtime.taskFor?.(context?.sessionID) || undefined, declared: false }
|
|
207
|
+
}
|
|
208
|
+
if (String(raw).trim() === WHOLE_SPACE) return { wholeSpace: true, declared: false }
|
|
209
|
+
const key = taskKey(raw)
|
|
210
|
+
if (!key) return { invalid: "task needs at least one letter or digit, for example \"fix the migration ordering\"." }
|
|
211
|
+
runtime.setSessionTask?.(context?.sessionID, key)
|
|
212
|
+
return { key, declared: true }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Team-visible writes and deletes pass through the host approval gate. */
|
|
216
|
+
async function assertTeamWrite(context, action, resources, metadata) {
|
|
217
|
+
await ctx.permission.assert({
|
|
218
|
+
sessionID: context?.sessionID,
|
|
219
|
+
agent: context?.agent,
|
|
220
|
+
source: { type: "tool", messageID: context?.messageID, id: context?.id },
|
|
221
|
+
action,
|
|
222
|
+
resources,
|
|
223
|
+
save: [],
|
|
224
|
+
metadata,
|
|
225
|
+
})
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Where each record id the agent has seen was written: its layer, agent, and
|
|
230
|
+
* (for L0) session. Upstream deletes match a row only under the agent and
|
|
231
|
+
* session it was written with, and mem_forget is used with ids that
|
|
232
|
+
* mem_recall or mem_remember just showed. Bounded and per process; keyed by
|
|
233
|
+
* space so an id never resolves against another space's placement.
|
|
234
|
+
*/
|
|
235
|
+
const LOCATIONS_MAX = 2_000
|
|
236
|
+
/** Text kept per cached record: enough for the specific tokens of a fact. */
|
|
237
|
+
const LOCATION_TEXT_CHARS = 1_000
|
|
238
|
+
const locations = new Map()
|
|
239
|
+
const locationKey = (spaceContext, id) => `${spaceContext?.space_id || "local"}::${id}`
|
|
240
|
+
const field = (value) => (value === undefined || value === null || value === "" ? undefined : String(value))
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Read a row's write coordinates, tolerating upstream field-name variants.
|
|
244
|
+
* The text is kept, capped, so mem_forget can look for other copies of a
|
|
245
|
+
* record it deletes even when the record is older than its scan window.
|
|
246
|
+
*/
|
|
247
|
+
function rowLocation(layer, row, fallback = {}) {
|
|
248
|
+
const content = row?.content ?? row?.text
|
|
249
|
+
return {
|
|
250
|
+
layer,
|
|
251
|
+
agent_id: field(row?.agent_id ?? row?.agentId) ?? fallback.agent_id,
|
|
252
|
+
session_id: layer === "l0" ? (field(row?.session_id ?? row?.session_key ?? row?.sessionId) ?? fallback.session_id) : undefined,
|
|
253
|
+
...(typeof content === "string" && content ? { text: content.slice(0, LOCATION_TEXT_CHARS) } : {}),
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function noteLocations(spaceContext, layer, rows, fallback = {}) {
|
|
258
|
+
for (const row of rows ?? []) {
|
|
259
|
+
const id = field(row?.id ?? row?.record_id ?? row?.message_id)
|
|
260
|
+
if (!id) continue
|
|
261
|
+
const location = rowLocation(layer, row, fallback)
|
|
262
|
+
// Upstream L0 search hits carry no session. An L0 delete needs the row's
|
|
263
|
+
// own session, so such a hit is not a usable location: leave it out and
|
|
264
|
+
// let mem_forget look the id up with conversation/query.
|
|
265
|
+
if (layer === "l0" && !location.session_id) continue
|
|
266
|
+
const key = locationKey(spaceContext, id)
|
|
267
|
+
locations.delete(key)
|
|
268
|
+
locations.set(key, location)
|
|
269
|
+
if (locations.size > LOCATIONS_MAX) locations.delete(locations.keys().next().value)
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function locate(spaceContext, id) {
|
|
274
|
+
return locations.get(locationKey(spaceContext, id))
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Drop deleted records, and the text kept with them, from the cache. */
|
|
278
|
+
function forgetLocations(spaceContext, ids) {
|
|
279
|
+
for (const id of ids ?? []) locations.delete(locationKey(spaceContext, id))
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Agents seen writing in this space, most recent first. */
|
|
283
|
+
function knownAgents(spaceContext) {
|
|
284
|
+
const prefix = `${spaceContext?.space_id || "local"}::`
|
|
285
|
+
const agents = []
|
|
286
|
+
for (const [key, entry] of [...locations.entries()].reverse()) {
|
|
287
|
+
if (key.startsWith(prefix) && entry.agent_id && !agents.includes(entry.agent_id)) agents.push(entry.agent_id)
|
|
288
|
+
}
|
|
289
|
+
return agents
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** A human-facing scope label that never contains the upstream container id. */
|
|
293
|
+
function displayScope(spaceContext, scoped) {
|
|
294
|
+
return spaceContext ? contextScopeLabel(spaceContext, scoped) : scopeLabel(scoped)
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function describeSpace(spaceContext) {
|
|
298
|
+
const bits = [oneLine(spaceContext.space_id || "space", 80)]
|
|
299
|
+
if (spaceContext.space_kind && spaceContext.space_kind !== "unknown") bits.push(`[${spaceContext.space_kind}]`)
|
|
300
|
+
if (spaceContext.space_name) bits.push(oneLine(spaceContext.space_name, 120))
|
|
301
|
+
return bits.join(" ")
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function describeCollection(spaceContext) {
|
|
305
|
+
if (!spaceContext.collection_id) return ""
|
|
306
|
+
const id = oneLine(spaceContext.collection_id, 80)
|
|
307
|
+
return spaceContext.collection_name ? `${id} ${oneLine(spaceContext.collection_name, 120)}` : id
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
return {
|
|
311
|
+
backend,
|
|
312
|
+
config,
|
|
313
|
+
log,
|
|
314
|
+
control,
|
|
315
|
+
runtime,
|
|
316
|
+
scope: runtime.scope,
|
|
317
|
+
scopeFor: runtime.scopeFor,
|
|
318
|
+
resolveContext: runtime.resolveContext,
|
|
319
|
+
isSessionBound: runtime.isSessionBound,
|
|
320
|
+
assert: ctx.permission.assert,
|
|
321
|
+
text,
|
|
322
|
+
fail,
|
|
323
|
+
sharedScope,
|
|
324
|
+
resolveSpace,
|
|
325
|
+
resolveReadSpace,
|
|
326
|
+
resolvePrivateSpace,
|
|
327
|
+
resolveWriteSpace,
|
|
328
|
+
assertTeamWrite,
|
|
329
|
+
taskFor,
|
|
330
|
+
rowLocation,
|
|
331
|
+
noteLocations,
|
|
332
|
+
locate,
|
|
333
|
+
forgetLocations,
|
|
334
|
+
knownAgents,
|
|
335
|
+
displayScope,
|
|
336
|
+
describeSpace,
|
|
337
|
+
describeCollection,
|
|
338
|
+
}
|
|
339
|
+
}
|