@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,179 @@
|
|
|
1
|
+
import { contextScopeLabel } from "../scope.js"
|
|
2
|
+
import { errorMessage, oneLine } from "../util.js"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Read-only space, grant, and member tools. The control plane decides access;
|
|
6
|
+
* these tools only render its answer and never expose an upstream container id.
|
|
7
|
+
*
|
|
8
|
+
* @param {any} editor
|
|
9
|
+
* @param {ReturnType<import("./shared.js").createToolkit>} toolkit
|
|
10
|
+
*/
|
|
11
|
+
export function registerSpaces(editor, toolkit) {
|
|
12
|
+
const { config, control, log, text, fail, resolveSpace, describeSpace, describeCollection } = toolkit
|
|
13
|
+
|
|
14
|
+
editor.add({
|
|
15
|
+
name: "spaces",
|
|
16
|
+
description:
|
|
17
|
+
"List the spaces you can use, or show the active space context. Call this before choosing a space for recall or remember when more than one space is available. Read-only: membership and sharing are managed by the control plane, not by the agent.",
|
|
18
|
+
input: {
|
|
19
|
+
type: "object",
|
|
20
|
+
properties: {
|
|
21
|
+
action: {
|
|
22
|
+
type: "string",
|
|
23
|
+
enum: ["list", "current"],
|
|
24
|
+
description: "list personal and shared spaces, or show the active context",
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
required: ["action"],
|
|
28
|
+
additionalProperties: false,
|
|
29
|
+
},
|
|
30
|
+
options: { namespace: "mem" },
|
|
31
|
+
execute: async (input, context) => {
|
|
32
|
+
if (!control) return text("control plane not configured; set MEMORY_CONTROL_URL to use spaces")
|
|
33
|
+
try {
|
|
34
|
+
if (input?.action === "current") {
|
|
35
|
+
const spaceContext = await toolkit.resolveContext({
|
|
36
|
+
sessionID: context?.sessionID,
|
|
37
|
+
agent: context?.agent,
|
|
38
|
+
})
|
|
39
|
+
if (!spaceContext) return fail("the control plane returned no space context")
|
|
40
|
+
const scoped = toolkit.scopeFor(spaceContext, { sessionID: context?.sessionID, agent: context?.agent })
|
|
41
|
+
const lines = ["<space_context>"]
|
|
42
|
+
lines.push(`space: ${describeSpace(spaceContext)}`)
|
|
43
|
+
const collection = describeCollection(spaceContext)
|
|
44
|
+
if (collection) lines.push(`collection: ${collection}`)
|
|
45
|
+
if (spaceContext.role) lines.push(`role: ${spaceContext.role}`)
|
|
46
|
+
lines.push(`agent: ${scoped.agent_id}`)
|
|
47
|
+
lines.push(`scope: ${contextScopeLabel(spaceContext, scoped)}`)
|
|
48
|
+
// The active space is not always the session's space. A shared
|
|
49
|
+
// default that is not bound to this session is shown here, but
|
|
50
|
+
// recall, remember, capture, and the pinned block use the personal
|
|
51
|
+
// space. Say so, so the two answers do not look contradictory.
|
|
52
|
+
if (spaceContext.space_kind === "shared") {
|
|
53
|
+
if (toolkit.isSessionBound(spaceContext)) {
|
|
54
|
+
lines.push("session: bound to this space; recall without a space argument searches it")
|
|
55
|
+
} else {
|
|
56
|
+
const personal = spaceContext.personal_space_id ? oneLine(spaceContext.personal_space_id, 80) : "your personal space"
|
|
57
|
+
lines.push(
|
|
58
|
+
`session: not bound to this space; recall, remember, capture, and the pinned block use ${personal}. Pass space to read this one.`,
|
|
59
|
+
)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
lines.push("</space_context>")
|
|
63
|
+
return text(lines.join("\n"))
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const spaces = await control.listSpaces({ userId: config.user })
|
|
67
|
+
if (spaces.length === 0) return text("the control plane returned no spaces for this user")
|
|
68
|
+
const groups = [
|
|
69
|
+
["personal", "Personal"],
|
|
70
|
+
["shared", "Shared"],
|
|
71
|
+
["unknown", "Other"],
|
|
72
|
+
]
|
|
73
|
+
const lines = ["<spaces>"]
|
|
74
|
+
for (const [kind, title] of groups) {
|
|
75
|
+
const group = spaces.filter((space) => space.kind === kind)
|
|
76
|
+
if (group.length === 0) continue
|
|
77
|
+
lines.push(`## ${title}`)
|
|
78
|
+
for (const space of group) {
|
|
79
|
+
const role = space.role ? ` (${space.role})` : ""
|
|
80
|
+
lines.push(`- ${space.space_id} [${space.kind}] ${oneLine(space.name || space.space_id, 120)}${role}`)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
lines.push("</spaces>")
|
|
84
|
+
return text(lines.join("\n"))
|
|
85
|
+
} catch (error) {
|
|
86
|
+
log.warn("spaces failed", error)
|
|
87
|
+
return fail(errorMessage(error))
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
editor.add({
|
|
93
|
+
name: "grants",
|
|
94
|
+
description:
|
|
95
|
+
"Read the grants that apply to you in a space. Use this to answer who can see or edit a space, collection, or resource. Read-only: the control plane decides access, and this tool only reports role, principal, target, inheritance, and expiry.",
|
|
96
|
+
input: {
|
|
97
|
+
type: "object",
|
|
98
|
+
properties: {
|
|
99
|
+
action: { type: "string", enum: ["list"], description: "list grants visible to you" },
|
|
100
|
+
space: { type: "string", description: "Space id to inspect (control plane); defaults to the active space" },
|
|
101
|
+
},
|
|
102
|
+
required: ["action"],
|
|
103
|
+
additionalProperties: false,
|
|
104
|
+
},
|
|
105
|
+
options: { namespace: "mem" },
|
|
106
|
+
execute: async (input, context) => {
|
|
107
|
+
if (input?.action !== "list") return text('unsupported action: use action="list"')
|
|
108
|
+
if (!control) return text("control plane not configured; set MEMORY_CONTROL_URL to read grants")
|
|
109
|
+
const resolved = await resolveSpace(input, context)
|
|
110
|
+
if (resolved.error) return fail(resolved.error)
|
|
111
|
+
const spaceContext = resolved.context
|
|
112
|
+
if (!spaceContext?.space_id) return fail("the control plane returned no space context")
|
|
113
|
+
try {
|
|
114
|
+
const grants = await control.listGrants({
|
|
115
|
+
userId: config.user,
|
|
116
|
+
spaceId: spaceContext.space_id,
|
|
117
|
+
})
|
|
118
|
+
const lines = ["<grants>", `space: ${describeSpace(spaceContext)}`]
|
|
119
|
+
if (spaceContext.role) lines.push(`role: ${oneLine(spaceContext.role, 40)}`)
|
|
120
|
+
if (grants.length === 0) lines.push("(no grants visible to you in this space)")
|
|
121
|
+
for (const grant of grants) {
|
|
122
|
+
const principal = [grant.principal_type, grant.principal_id].filter(Boolean).join(":")
|
|
123
|
+
const target = [grant.target_type, grant.target_id].filter(Boolean).join(":")
|
|
124
|
+
lines.push(
|
|
125
|
+
`- role=${oneLine(grant.role || "unknown", 40)} principal=${oneLine(principal || "unknown", 160)} target=${oneLine(target || "unknown", 160)} inherit=${grant.inherit ? "yes" : "no"} expires=${oneLine(grant.expires_at || "never", 80)}`,
|
|
126
|
+
)
|
|
127
|
+
}
|
|
128
|
+
lines.push("</grants>")
|
|
129
|
+
return text(lines.join("\n"))
|
|
130
|
+
} catch (error) {
|
|
131
|
+
log.warn("grants failed", error)
|
|
132
|
+
return fail(errorMessage(error))
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
editor.add({
|
|
138
|
+
name: "members",
|
|
139
|
+
description:
|
|
140
|
+
"Read the member roster for a space. Read-only: members and roles are managed by the control plane, not by the agent.",
|
|
141
|
+
input: {
|
|
142
|
+
type: "object",
|
|
143
|
+
properties: {
|
|
144
|
+
action: { type: "string", enum: ["list"], description: "list space members" },
|
|
145
|
+
space: { type: "string", description: "Space id to inspect (control plane); defaults to the active space" },
|
|
146
|
+
},
|
|
147
|
+
required: ["action"],
|
|
148
|
+
additionalProperties: false,
|
|
149
|
+
},
|
|
150
|
+
options: { namespace: "mem" },
|
|
151
|
+
execute: async (input, context) => {
|
|
152
|
+
if (input?.action !== "list") return text('unsupported action: use action="list"')
|
|
153
|
+
if (!control) return text("control plane not configured; set MEMORY_CONTROL_URL to read members")
|
|
154
|
+
const resolved = await resolveSpace(input, context)
|
|
155
|
+
if (resolved.error) return fail(resolved.error)
|
|
156
|
+
const spaceContext = resolved.context
|
|
157
|
+
if (!spaceContext?.space_id) return fail("the control plane returned no space context")
|
|
158
|
+
try {
|
|
159
|
+
const members = await control.listMembers({
|
|
160
|
+
userId: config.user,
|
|
161
|
+
spaceId: spaceContext.space_id,
|
|
162
|
+
})
|
|
163
|
+
const lines = ["<members>", `space: ${describeSpace(spaceContext)}`]
|
|
164
|
+
if (members.length === 0) lines.push("(no members visible to you in this space)")
|
|
165
|
+
for (const member of members) {
|
|
166
|
+
const identity = member.name || member.email || member.user_id
|
|
167
|
+
lines.push(
|
|
168
|
+
`- ${oneLine(identity, 160)} (${oneLine(member.role || "member", 40)}) user_id=${oneLine(member.user_id, 120)}`,
|
|
169
|
+
)
|
|
170
|
+
}
|
|
171
|
+
lines.push("</members>")
|
|
172
|
+
return text(lines.join("\n"))
|
|
173
|
+
} catch (error) {
|
|
174
|
+
log.warn("members failed", error)
|
|
175
|
+
return fail(errorMessage(error))
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
})
|
|
179
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { describeBootstrap, describeSpool, errorMessage, oneLine } from "../util.js"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `mem_status`: backend health, active scope, layer counts, skills, and spool.
|
|
5
|
+
*
|
|
6
|
+
* @param {any} editor
|
|
7
|
+
* @param {ReturnType<import("./shared.js").createToolkit>} toolkit
|
|
8
|
+
*/
|
|
9
|
+
export function registerStatus(editor, toolkit) {
|
|
10
|
+
const { text, fail, resolveSpace } = toolkit
|
|
11
|
+
|
|
12
|
+
editor.add({
|
|
13
|
+
name: "status",
|
|
14
|
+
description:
|
|
15
|
+
"Report memory backend health, active scope, per-layer counts (L0-L3), mirrored skills, knowledge assets, and queued captures. Use it when recall returns nothing and you need to know whether the store is empty, extraction has not run yet, or the backend is unreachable.",
|
|
16
|
+
input: {
|
|
17
|
+
type: "object",
|
|
18
|
+
properties: {
|
|
19
|
+
space: { type: "string", description: "Space id to report on (control plane); defaults to the active space" },
|
|
20
|
+
},
|
|
21
|
+
additionalProperties: false,
|
|
22
|
+
},
|
|
23
|
+
options: { namespace: "mem" },
|
|
24
|
+
execute: async (input, context) => {
|
|
25
|
+
const resolved = await resolveSpace(input, context)
|
|
26
|
+
if (resolved.error) return fail(resolved.error)
|
|
27
|
+
const spaceContext = resolved.context
|
|
28
|
+
try {
|
|
29
|
+
const status = await toolkit.runtime.status({
|
|
30
|
+
sessionID: input?.space ? undefined : context?.sessionID,
|
|
31
|
+
agent: context?.agent,
|
|
32
|
+
context: spaceContext,
|
|
33
|
+
})
|
|
34
|
+
const lines = [
|
|
35
|
+
`backend: ${status.health}`,
|
|
36
|
+
`scope: ${status.scope}`,
|
|
37
|
+
`capture: ${status.capture}`,
|
|
38
|
+
`credential: ${status.credential}`,
|
|
39
|
+
]
|
|
40
|
+
if (status.space) {
|
|
41
|
+
const kind = status.spaceKind && status.spaceKind !== "unknown" ? ` [${status.spaceKind}]` : ""
|
|
42
|
+
const name = status.spaceName ? ` ${oneLine(status.spaceName, 120)}` : ""
|
|
43
|
+
lines.splice(2, 0, `space: ${oneLine(status.space, 80)}${kind}${name}`)
|
|
44
|
+
if (status.collection) lines.splice(3, 0, `collection: ${oneLine(status.collection, 120)}`)
|
|
45
|
+
}
|
|
46
|
+
lines.push(
|
|
47
|
+
`L0 conversations: ${status.layers.l0 ?? "?"}`,
|
|
48
|
+
`L1 atoms: ${status.layers.l1 ?? "?"}`,
|
|
49
|
+
`L2 scenarios: ${status.layers.l2 ?? "?"}`,
|
|
50
|
+
`L3 persona: ${status.layers.l3 ? "present" : "empty"}`,
|
|
51
|
+
`skills: ${status.layers.skills ?? "?"}`,
|
|
52
|
+
`source spaces: ${status.sourceSpaces}`,
|
|
53
|
+
`mirrored skills: ${status.mirroredSkills}`,
|
|
54
|
+
`knowledge assets: ${status.layers.knowledge ?? "?"}`,
|
|
55
|
+
`pinned sessions: ${status.pinned}`,
|
|
56
|
+
`bootstrap: ${describeBootstrap(status.bootstrap)}`,
|
|
57
|
+
`spooled captures: ${describeSpool(status.spool)}`,
|
|
58
|
+
)
|
|
59
|
+
return text(lines.join("\n"))
|
|
60
|
+
} catch (error) {
|
|
61
|
+
return fail(errorMessage(error))
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
})
|
|
65
|
+
}
|
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
import { errorMessage, neutralizeFenceClosers, oneLine } from "../util.js"
|
|
2
|
+
import { discoverKnowledge, searchKnowledge } from "./knowledge.js"
|
|
3
|
+
|
|
4
|
+
const MAX_FILE_BYTES = 512 * 1024
|
|
5
|
+
const DEFAULT_FILE = "README.md"
|
|
6
|
+
/** Plugin guidance after search hits, outside the untrusted fence. */
|
|
7
|
+
const READ_HINT =
|
|
8
|
+
"To read a wiki hit in full: mem_wiki with action \"read\", wiki_id = the hit's source, ref = the hit's path."
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* `mem_wiki`: read, search, and write durable knowledge pages.
|
|
12
|
+
*
|
|
13
|
+
* Memory is for atomic decisions and constraints; the wiki is for the coherent
|
|
14
|
+
* synthesis that would otherwise be re-derived: architecture, runbooks,
|
|
15
|
+
* decision records, onboarding, domain maps, and project overviews. Tasks and
|
|
16
|
+
* status stay in the tracker that owns them.
|
|
17
|
+
*
|
|
18
|
+
* @param {any} editor
|
|
19
|
+
* @param {ReturnType<import("./shared.js").createToolkit>} toolkit
|
|
20
|
+
*/
|
|
21
|
+
export function registerWiki(editor, toolkit) {
|
|
22
|
+
const {
|
|
23
|
+
backend,
|
|
24
|
+
log,
|
|
25
|
+
control,
|
|
26
|
+
text,
|
|
27
|
+
fail,
|
|
28
|
+
sharedScope,
|
|
29
|
+
config,
|
|
30
|
+
resolveSpace,
|
|
31
|
+
resolvePrivateSpace,
|
|
32
|
+
resolveWriteSpace,
|
|
33
|
+
assertTeamWrite,
|
|
34
|
+
runtime,
|
|
35
|
+
} = toolkit
|
|
36
|
+
|
|
37
|
+
function visibilityOf(input) {
|
|
38
|
+
return input?.visibility === "private" ? "private" : "team"
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function filenameOf(input) {
|
|
42
|
+
const raw = String(input?.filename ?? DEFAULT_FILE)
|
|
43
|
+
.replace(/^\/+/, "")
|
|
44
|
+
.replace(/\\/g, "/")
|
|
45
|
+
if (!raw || raw.split("/").some((part) => part === ".." || part === "")) return ""
|
|
46
|
+
return oneLine(raw, 240)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function resolveWrite(input, context, visibility) {
|
|
50
|
+
const resolved = await resolveWriteSpace(input, context, visibility)
|
|
51
|
+
if (resolved.invalid) return { invalid: resolved.invalid }
|
|
52
|
+
if (resolved.error) return { error: resolved.error }
|
|
53
|
+
const spaceContext = resolved.context
|
|
54
|
+
const scoped = spaceContext
|
|
55
|
+
? toolkit.scopeFor(spaceContext, { sessionID: context?.sessionID, agent: context?.agent })
|
|
56
|
+
: toolkit.scope({ sessionID: context?.sessionID, agent: context?.agent })
|
|
57
|
+
// Every team-visible write asks for approval, in local mode too: mem_remember
|
|
58
|
+
// and mem_forget already do, and the wiki is the more durable of the three.
|
|
59
|
+
if (visibility === "team") {
|
|
60
|
+
try {
|
|
61
|
+
await assertTeamWrite(context, "wiki.write", [spaceContext?.space_id ?? "team"], { kind: "wiki" })
|
|
62
|
+
} catch (error) {
|
|
63
|
+
return { denied: errorMessage(error) }
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return { spaceContext, scoped }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Register a new wiki in its space's control catalog. A gateway that has
|
|
71
|
+
* the create hook (issue #2) already did it and says so with `resource_id`
|
|
72
|
+
* on the create response; an older gateway did not, so the plugin still
|
|
73
|
+
* registers explicitly there. The gateway's route is idempotent either way.
|
|
74
|
+
*/
|
|
75
|
+
async function registerWikiResource(spaceContext, wiki, name) {
|
|
76
|
+
const registered = typeof wiki?.resource_id === "string" ? wiki.resource_id.trim() : ""
|
|
77
|
+
if (registered) return { id: registered }
|
|
78
|
+
const wikiID = String(wiki?.wiki_id ?? "")
|
|
79
|
+
if (!control || !spaceContext?.space_id) return null
|
|
80
|
+
const userId = spaceContext.user_id || runtime.config.user
|
|
81
|
+
if (!userId) throw new Error("a control user id is required to register a wiki resource")
|
|
82
|
+
return control.createResource({
|
|
83
|
+
userId,
|
|
84
|
+
spaceId: spaceContext.space_id,
|
|
85
|
+
resource: { kind: "wiki", upstream_id: wikiID, name },
|
|
86
|
+
})
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function writeRaw(scope, wikiID, filename, content, ingest) {
|
|
90
|
+
await backend.writeWikiRaw({ scope, wikiID, files: [{ filename, content }] })
|
|
91
|
+
if (ingest === false) return { ingested: false }
|
|
92
|
+
try {
|
|
93
|
+
await backend.ingestWiki({ scope, wikiID })
|
|
94
|
+
return { ingested: true }
|
|
95
|
+
} catch (error) {
|
|
96
|
+
return { ingested: false, ingestError: errorMessage(error) }
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The wiki a read or status names. Without `wiki_id`, the only wiki visible
|
|
102
|
+
* in the scope is used and the answer says so; with several, the refusal
|
|
103
|
+
* lists them.
|
|
104
|
+
*/
|
|
105
|
+
async function wikiFor(input, scoped, action) {
|
|
106
|
+
const given = String(input?.wiki_id ?? "").trim()
|
|
107
|
+
if (given) return { wikiID: given, note: "" }
|
|
108
|
+
const ids = [...new Set(await discoverKnowledge(backend, log, "llm_wiki", scoped))]
|
|
109
|
+
if (ids.length === 1) return { wikiID: ids[0], note: `(wiki_id not given; using the only visible wiki, ${oneLine(ids[0], 80)})\n` }
|
|
110
|
+
if (ids.length === 0) return { error: `wiki_id is required for ${action}; no wiki is visible in this scope` }
|
|
111
|
+
return {
|
|
112
|
+
error: `wiki_id is required for ${action}; visible wikis: ${ids
|
|
113
|
+
.slice(0, 10)
|
|
114
|
+
.map((id) => oneLine(id, 80))
|
|
115
|
+
.join(", ")}${ids.length > 10 ? ", …" : ""}`,
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** An upstream 404 means "not there"; any other failure is an error. */
|
|
120
|
+
async function orNull(promise) {
|
|
121
|
+
try {
|
|
122
|
+
return await promise
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (Number(error?.status) === 404) return null
|
|
125
|
+
throw error
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** One extracted page by id or path. The hub answers a missing ref with `not_found`. */
|
|
130
|
+
async function readPage(scoped, wikiID, ref) {
|
|
131
|
+
const data = await orNull(backend.readWikiPage({ scope: scoped, wikiID, refs: [ref] }))
|
|
132
|
+
const item = (data?.items ?? [])[0]
|
|
133
|
+
if (!item || item.not_found || typeof (item.content ?? item.text) !== "string") return null
|
|
134
|
+
return { source: `${wikiID}/${ref}`, content: String(item.content ?? item.text) }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** One source file. */
|
|
138
|
+
async function readSource(scoped, wikiID, filename) {
|
|
139
|
+
if (!filenameOf({ filename })) return null
|
|
140
|
+
const data = await orNull(backend.readWikiRaw({ scope: scoped, wikiID, filenames: [filename] }))
|
|
141
|
+
const item = (data?.items ?? []).find((entry) => entry?.filename === filename)
|
|
142
|
+
if (!item || item.not_found || typeof item.content !== "string") return null
|
|
143
|
+
return { source: `${wikiID}/${filename}`, content: item.content }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** What exists, so the next read can name it. */
|
|
147
|
+
async function notFound(scoped, wikiID, name) {
|
|
148
|
+
const [pages, sources] = await Promise.all([
|
|
149
|
+
orNull(backend.listWikiPages({ scope: scoped, wikiID })).catch(() => null),
|
|
150
|
+
orNull(backend.knowledgeCall({ knowledgeID: wikiID, toolName: "list_raw", params: {}, scope: scoped })).catch(() => null),
|
|
151
|
+
])
|
|
152
|
+
const pageNames = (pages?.items ?? []).map((item) => item?.path ?? item?.id).filter(Boolean).slice(0, 15)
|
|
153
|
+
const sourceNames = (Array.isArray(sources) ? sources : sources?.items ?? [])
|
|
154
|
+
.map((item) => (typeof item === "string" ? item : item?.filename))
|
|
155
|
+
.filter(Boolean)
|
|
156
|
+
.slice(0, 15)
|
|
157
|
+
const list = (names) => (names.length ? names.map((entry) => oneLine(entry, 120)).join(", ") : "none")
|
|
158
|
+
return (
|
|
159
|
+
`not found in ${oneLine(wikiID, 80)}: ${oneLine(name, 120)}\n` +
|
|
160
|
+
`pages (pass as ref): ${list(pageNames)}\n` +
|
|
161
|
+
`source files (pass as filename): ${list(sourceNames)}`
|
|
162
|
+
)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
editor.add({
|
|
166
|
+
name: "wiki",
|
|
167
|
+
description:
|
|
168
|
+
"Read, search, or write durable knowledge. Use list/search for documentation, architecture, ownership, runbooks, and call-graph questions. Use create/write/append to save a coherent page (not a task list) and status to check ingestion. Tasks, owners, and status belong in Linear, Jira, GitHub Issues, or the tracker that owns them; this tool is for durable knowledge, not a second task board.",
|
|
169
|
+
input: {
|
|
170
|
+
type: "object",
|
|
171
|
+
properties: {
|
|
172
|
+
action: {
|
|
173
|
+
type: "string",
|
|
174
|
+
enum: ["list", "search", "create", "write", "append", "read", "status"],
|
|
175
|
+
description: "list/search read; create/write/append save knowledge; read/status inspect a wiki",
|
|
176
|
+
},
|
|
177
|
+
query: { type: "string", description: "Search query (required for action=search)" },
|
|
178
|
+
knowledge_id: {
|
|
179
|
+
type: "string",
|
|
180
|
+
description: "Restrict a search to one id returned by action=list (the wiki/code-graph id, not an ACL asset id)",
|
|
181
|
+
},
|
|
182
|
+
wiki_id: { type: "string", description: "Wiki id for write/append/read/status; defaults to a wiki created earlier" },
|
|
183
|
+
name: { type: "string", description: "Human-readable wiki name for action=create" },
|
|
184
|
+
filename: { type: "string", description: `Source filename (default ${DEFAULT_FILE}); path traversal is rejected` },
|
|
185
|
+
content: { type: "string", description: "Markdown content for create/write/append" },
|
|
186
|
+
ingest: { type: "boolean", description: "Trigger extraction after write/append (default true)" },
|
|
187
|
+
ref: {
|
|
188
|
+
type: "string",
|
|
189
|
+
description: "Page to read (action=read): the `path` a search hit shows, or a page id from status",
|
|
190
|
+
},
|
|
191
|
+
path: { type: "string", description: "Same as ref: the page path a search hit shows" },
|
|
192
|
+
visibility: {
|
|
193
|
+
type: "string",
|
|
194
|
+
enum: ["team", "private"],
|
|
195
|
+
description: "team (default) uses shared knowledge; private uses your personal knowledge space. A list without visibility shows both",
|
|
196
|
+
},
|
|
197
|
+
type: { type: "string", enum: ["wiki", "code-graph", "all"] },
|
|
198
|
+
space: { type: "string", description: "Space id to browse or write (control plane); defaults to the active space" },
|
|
199
|
+
},
|
|
200
|
+
required: ["action"],
|
|
201
|
+
additionalProperties: false,
|
|
202
|
+
},
|
|
203
|
+
options: { namespace: "mem" },
|
|
204
|
+
execute: async (input, context) => {
|
|
205
|
+
const action = String(input?.action ?? "list")
|
|
206
|
+
const visibility = visibilityOf(input)
|
|
207
|
+
|
|
208
|
+
if (["create", "write", "append"].includes(action)) {
|
|
209
|
+
const content = String(input?.content ?? "")
|
|
210
|
+
if (action !== "create" && !content.trim()) return text(`nothing to ${action}: content is empty`)
|
|
211
|
+
if (Buffer.byteLength(content) > MAX_FILE_BYTES) return text("wiki content is too large (max 512 KB)")
|
|
212
|
+
|
|
213
|
+
const resolved = await resolveWrite(input, context, visibility)
|
|
214
|
+
if (resolved.invalid) return text(resolved.invalid)
|
|
215
|
+
if (resolved.error) return fail(resolved.error)
|
|
216
|
+
if (resolved.denied) return text(`wiki write denied: ${resolved.denied}`)
|
|
217
|
+
|
|
218
|
+
try {
|
|
219
|
+
if (action === "create") {
|
|
220
|
+
const name = oneLine(input?.name, 200).trim()
|
|
221
|
+
if (!name) return text("wiki name is required")
|
|
222
|
+
const filename = filenameOf(input)
|
|
223
|
+
if (!filename) return text("invalid filename")
|
|
224
|
+
const wiki = await backend.createWiki({ scope: resolved.scoped, name })
|
|
225
|
+
const wikiID = String(wiki?.wiki_id ?? "")
|
|
226
|
+
if (!wikiID) throw new Error("wiki/create returned no wiki_id")
|
|
227
|
+
let resource = null
|
|
228
|
+
try {
|
|
229
|
+
resource = await registerWikiResource(resolved.spaceContext, wiki, name)
|
|
230
|
+
} catch (error) {
|
|
231
|
+
return fail(
|
|
232
|
+
`wiki ${wikiID} was created but resource registration failed: ${errorMessage(error)}. An operator must register it before the gateway can expose it.`,
|
|
233
|
+
)
|
|
234
|
+
}
|
|
235
|
+
const written = await writeRaw(
|
|
236
|
+
resolved.scoped,
|
|
237
|
+
wikiID,
|
|
238
|
+
filename,
|
|
239
|
+
content || `# ${name}\n`,
|
|
240
|
+
input?.ingest !== false,
|
|
241
|
+
)
|
|
242
|
+
log.info("wiki created", { wikiID, visibility, resource: resource?.id ?? null })
|
|
243
|
+
return text(
|
|
244
|
+
`created wiki ${wikiID} (${name}); wrote ${filename}; ${
|
|
245
|
+
written.ingested ? "ingestion started (asynchronous)" : "ingestion not started"
|
|
246
|
+
}${resource?.id ? `; resource ${resource.id}` : ""}`,
|
|
247
|
+
)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const wikiID = String(input?.wiki_id ?? "").trim()
|
|
251
|
+
if (!wikiID) return text("wiki_id is required for write/append")
|
|
252
|
+
const filename = filenameOf(input)
|
|
253
|
+
if (!filename) return text("invalid filename")
|
|
254
|
+
|
|
255
|
+
let body = content
|
|
256
|
+
if (action === "append") {
|
|
257
|
+
const existing = await backend.readWikiRaw({ scope: resolved.scoped, wikiID, filenames: [filename] })
|
|
258
|
+
const current = (existing?.items ?? []).find((item) => item?.filename === filename)?.content ?? ""
|
|
259
|
+
body = current ? `${current.replace(/\s+$/, "")}\n\n${content}` : content
|
|
260
|
+
if (Buffer.byteLength(body) > MAX_FILE_BYTES) return text("wiki file is too large after append")
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const written = await writeRaw(resolved.scoped, wikiID, filename, body, input?.ingest !== false)
|
|
264
|
+
return text(
|
|
265
|
+
`${action === "append" ? "appended to" : "wrote"} ${filename} in wiki ${wikiID}; ${
|
|
266
|
+
written.ingested ? "ingestion started (asynchronous)" : "ingestion not started"
|
|
267
|
+
}${written.ingestError ? ` (${written.ingestError})` : ""}`,
|
|
268
|
+
)
|
|
269
|
+
} catch (error) {
|
|
270
|
+
log.warn("wiki write failed", error)
|
|
271
|
+
return fail(errorMessage(error))
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const resolved =
|
|
276
|
+
visibility === "private" && control
|
|
277
|
+
? await resolvePrivateSpace(input, context)
|
|
278
|
+
: await resolveSpace(input, context)
|
|
279
|
+
if (resolved.invalid) return text(resolved.invalid)
|
|
280
|
+
if (resolved.error) return fail(resolved.error)
|
|
281
|
+
const spaceContext = resolved.context
|
|
282
|
+
const scoped = spaceContext
|
|
283
|
+
? toolkit.scopeFor(spaceContext, {
|
|
284
|
+
sessionID: input?.space ? undefined : context?.sessionID,
|
|
285
|
+
agent: context?.agent,
|
|
286
|
+
})
|
|
287
|
+
: visibility === "private"
|
|
288
|
+
? toolkit.scope({ sessionID: context?.sessionID, agent: context?.agent })
|
|
289
|
+
: sharedScope()
|
|
290
|
+
const assetType = input?.type === "code-graph" ? "code_graph" : input?.type === "wiki" ? "llm_wiki" : undefined
|
|
291
|
+
|
|
292
|
+
try {
|
|
293
|
+
if (action === "list") {
|
|
294
|
+
const [assets, wikis, graphs] = await Promise.all([
|
|
295
|
+
backend.listAccessibleAssets({ scope: scoped, assetType }).catch(() => null),
|
|
296
|
+
!assetType || assetType === "llm_wiki" ? backend.listWiki({ scope: scoped }).catch(() => null) : null,
|
|
297
|
+
!assetType || assetType === "code_graph" ? backend.listCodeGraph({ scope: scoped }).catch(() => null) : null,
|
|
298
|
+
])
|
|
299
|
+
|
|
300
|
+
// The ACL asset list, the wiki list, and the code-graph list can
|
|
301
|
+
// describe the same knowledge object. Emit each searchable id once:
|
|
302
|
+
// duplicates cost tokens and invite the agent to search twice.
|
|
303
|
+
const lines = []
|
|
304
|
+
const seen = new Set()
|
|
305
|
+
for (const asset of assets?.items ?? []) {
|
|
306
|
+
if (asset.asset_type !== "llm_wiki" && asset.asset_type !== "code_graph") continue
|
|
307
|
+
if (!spaceContext && visibility === "private" && asset.visibility !== "private") continue
|
|
308
|
+
// An explicit "team" lists team assets only. With no visibility a
|
|
309
|
+
// read lists everything the caller may read, as control mode does
|
|
310
|
+
// (the active context is the personal space unless one is bound):
|
|
311
|
+
// hiding the caller's own private wiki sent agents guessing ids.
|
|
312
|
+
if (!spaceContext && input?.visibility === "team" && asset.visibility === "private") continue
|
|
313
|
+
// The asset id is the ACL row; the knowledge id is what
|
|
314
|
+
// mem_wiki search accepts. Show the searchable id first so an
|
|
315
|
+
// agent that copies an id from this list gets a hit, not a 404.
|
|
316
|
+
const knowledgeID = String(asset.content_ref ?? asset.asset_id ?? "")
|
|
317
|
+
if (!knowledgeID || seen.has(knowledgeID)) continue
|
|
318
|
+
seen.add(knowledgeID)
|
|
319
|
+
const assetNote =
|
|
320
|
+
asset.content_ref && asset.asset_id && String(asset.content_ref) !== String(asset.asset_id)
|
|
321
|
+
? ` (asset ${asset.asset_id})`
|
|
322
|
+
: ""
|
|
323
|
+
lines.push(
|
|
324
|
+
`- ${neutralizeFenceClosers(oneLine(knowledgeID, 120))} [${neutralizeFenceClosers(
|
|
325
|
+
oneLine(asset.asset_type, 40),
|
|
326
|
+
)}] ${neutralizeFenceClosers(oneLine(asset.name ?? "", 200))}${neutralizeFenceClosers(
|
|
327
|
+
oneLine(assetNote, 140),
|
|
328
|
+
)}`,
|
|
329
|
+
)
|
|
330
|
+
}
|
|
331
|
+
for (const wiki of wikis?.items ?? []) {
|
|
332
|
+
const wikiID = String(wiki.wiki_id ?? "")
|
|
333
|
+
if (!wikiID || seen.has(wikiID)) continue
|
|
334
|
+
seen.add(wikiID)
|
|
335
|
+
lines.push(
|
|
336
|
+
`- ${neutralizeFenceClosers(oneLine(wikiID, 120))} [wiki] ${neutralizeFenceClosers(
|
|
337
|
+
oneLine(wiki.name ?? "", 200),
|
|
338
|
+
)} (${neutralizeFenceClosers(oneLine(wiki.status ?? "?", 40))}${wiki.page_count ? `, ${wiki.page_count} pages` : ""})`,
|
|
339
|
+
)
|
|
340
|
+
}
|
|
341
|
+
for (const graph of graphs?.items ?? []) {
|
|
342
|
+
const graphID = String(graph.code_graph_id ?? "")
|
|
343
|
+
if (!graphID || seen.has(graphID)) continue
|
|
344
|
+
seen.add(graphID)
|
|
345
|
+
lines.push(
|
|
346
|
+
`- ${neutralizeFenceClosers(oneLine(graphID, 120))} [code-graph] ${neutralizeFenceClosers(
|
|
347
|
+
oneLine(graph.name ?? "", 200),
|
|
348
|
+
)} (${neutralizeFenceClosers(oneLine(graph.status ?? "?", 40))})`,
|
|
349
|
+
)
|
|
350
|
+
}
|
|
351
|
+
if (lines.length === 0) return text("no accessible knowledge assets")
|
|
352
|
+
return text(["<knowledge_assets>", ...lines, "</knowledge_assets>"].join("\n"))
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
if (action === "read") {
|
|
356
|
+
const target = await wikiFor(input, scoped, "read")
|
|
357
|
+
if (target.error) return text(target.error)
|
|
358
|
+
const { wikiID, note } = target
|
|
359
|
+
const ref = String(input?.ref ?? input?.path ?? "").trim()
|
|
360
|
+
const name = ref || filenameOf(input)
|
|
361
|
+
if (!name) return text("invalid filename")
|
|
362
|
+
// A page first when a ref was given, a source file first otherwise;
|
|
363
|
+
// then the other kind, so the name a search hit or a list showed works.
|
|
364
|
+
const order = ref ? [readPage, readSource] : [readSource, readPage]
|
|
365
|
+
for (const read of order) {
|
|
366
|
+
const found = await read(scoped, wikiID, name)
|
|
367
|
+
if (found) {
|
|
368
|
+
return text(
|
|
369
|
+
`${note}<knowledge source="${neutralizeFenceClosers(oneLine(found.source, 120))}">\n${neutralizeFenceClosers(
|
|
370
|
+
found.content.slice(0, 12_000),
|
|
371
|
+
)}\n</knowledge>`,
|
|
372
|
+
)
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return text(`${note}${await notFound(scoped, wikiID, name)}`)
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
if (action === "status") {
|
|
379
|
+
const target = await wikiFor(input, scoped, "status")
|
|
380
|
+
if (target.error) return text(target.error)
|
|
381
|
+
const { wikiID } = target
|
|
382
|
+
const [wiki, pages] = await Promise.all([
|
|
383
|
+
backend.getWiki({ scope: scoped, wikiID }),
|
|
384
|
+
backend.listWikiPages({ scope: scoped, wikiID }).catch(() => null),
|
|
385
|
+
])
|
|
386
|
+
const pageCount = Array.isArray(pages?.items) ? pages.items.length : wiki?.page_count ?? 0
|
|
387
|
+
return text(
|
|
388
|
+
`wiki: ${oneLine(wiki?.wiki_id ?? wikiID, 120)}\nname: ${oneLine(wiki?.name ?? "", 200)}\nstatus: ${oneLine(
|
|
389
|
+
wiki?.status ?? "unknown",
|
|
390
|
+
40,
|
|
391
|
+
)}\npages: ${pageCount}`,
|
|
392
|
+
)
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const query = String(input?.query ?? "").trim()
|
|
396
|
+
if (!query) return text("nothing to search: query is empty")
|
|
397
|
+
const ids = input?.knowledge_id
|
|
398
|
+
? [String(input.knowledge_id)]
|
|
399
|
+
: await discoverKnowledge(backend, log, assetType, scoped)
|
|
400
|
+
if (ids.length === 0) return text("no accessible knowledge assets")
|
|
401
|
+
const result = await searchKnowledge(backend, ids.slice(0, 8), query, scoped, {
|
|
402
|
+
maxChars: config.recallChars,
|
|
403
|
+
})
|
|
404
|
+
if (!result) return text("no knowledge results")
|
|
405
|
+
return text(assetType === "code_graph" ? result : `${result}\n\n${READ_HINT}`)
|
|
406
|
+
} catch (error) {
|
|
407
|
+
log.warn("wiki failed", error)
|
|
408
|
+
return fail(errorMessage(error))
|
|
409
|
+
}
|
|
410
|
+
},
|
|
411
|
+
})
|
|
412
|
+
}
|