@mojoaar/opencode-mimir 0.0.0-stage → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/select.ts ADDED
@@ -0,0 +1,113 @@
1
+ import { readdir, stat } from 'node:fs/promises'
2
+ import { posix, join } from 'node:path'
3
+
4
+ /**
5
+ * What an import is for: the knowledge a reader would have to dig out of the
6
+ * repository, not a second copy of the code the agent already has on disk.
7
+ */
8
+ export const IGNORED_DIRS = new Set([
9
+ 'node_modules',
10
+ '.git',
11
+ 'dist',
12
+ 'build',
13
+ '.next',
14
+ 'coverage',
15
+ '.venv',
16
+ 'venv',
17
+ '__pycache__',
18
+ '.idea',
19
+ '.vscode',
20
+ 'vendor',
21
+ 'target',
22
+ 'tmp',
23
+ ])
24
+
25
+ export const IGNORED_EXTENSIONS = new Set([
26
+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'ico', 'pdf', 'zip', 'gz', 'tar', 'bz2', '7z', 'rar',
27
+ 'exe', 'dll', 'so', 'dylib', 'o', 'a', 'class', 'jar', 'wasm',
28
+ 'mp3', 'mp4', 'mov', 'avi', 'woff', 'woff2', 'ttf', 'eot',
29
+ ])
30
+
31
+ const CONFIG_FILES = new Set([
32
+ 'package.json',
33
+ 'tsconfig.json',
34
+ 'docker-compose.yml',
35
+ 'docker-compose.yaml',
36
+ 'compose.yml',
37
+ 'compose.yaml',
38
+ 'Dockerfile',
39
+ 'Makefile',
40
+ 'pyproject.toml',
41
+ 'go.mod',
42
+ 'Cargo.toml',
43
+ '.env.example',
44
+ 'renovate.json',
45
+ 'turbo.json',
46
+ ])
47
+
48
+ const PROSE = /\.(md|mdx)$/i
49
+ const ROOT_PROSE = /^(readme|changelog|contributing|license)/i
50
+ // A guard against a symlinked home directory, not a product limit: a real
51
+ // repository of 250 000 files is still walked, and hitting the cap is reported.
52
+ const MAX_ENTRIES = 250_000
53
+
54
+ export type WalkEntry = { path: string; bytes: number }
55
+ export type WalkResult = {
56
+ files: WalkEntry[]
57
+ skipped: { path: string; reason: string }[]
58
+ /** True when the walk stopped early, so the caller must not report success. */
59
+ truncated: boolean
60
+ }
61
+ export type WalkOptions = { all?: boolean; maxFileBytes?: number; maxEntries?: number }
62
+
63
+ function depth(path: string): number {
64
+ return path.split('/').length - 1
65
+ }
66
+
67
+ function wanted(path: string): boolean {
68
+ const base = posix.basename(path)
69
+ if (ROOT_PROSE.test(base) && depth(path) <= 1) return true
70
+ if (path.startsWith('docs/') || path.startsWith('doc/')) return PROSE.test(base)
71
+ if (PROSE.test(base) && depth(path) <= 3) return true
72
+ return CONFIG_FILES.has(base) && depth(path) <= 2
73
+ }
74
+
75
+ export async function selectFiles(root: string, options: WalkOptions = {}): Promise<WalkResult> {
76
+ const maxFileBytes = options.maxFileBytes ?? 262_144
77
+ const maxEntries = options.maxEntries ?? MAX_ENTRIES
78
+ const files: WalkEntry[] = []
79
+ const skipped: { path: string; reason: string }[] = []
80
+ let seen = 0
81
+ let truncated = false
82
+
83
+ async function walk(relative: string): Promise<void> {
84
+ const entries = await readdir(join(root, relative), { withFileTypes: true })
85
+ for (const entry of entries) {
86
+ if (++seen > maxEntries) {
87
+ truncated = true
88
+ return
89
+ }
90
+ const path = relative ? `${relative}/${entry.name}` : entry.name
91
+ if (entry.isDirectory()) {
92
+ if (IGNORED_DIRS.has(entry.name)) continue
93
+ await walk(path)
94
+ continue
95
+ }
96
+ if (!entry.isFile()) continue
97
+
98
+ const extension = posix.extname(entry.name).slice(1).toLowerCase()
99
+ if (IGNORED_EXTENSIONS.has(extension)) continue
100
+ if (options.all !== true && !wanted(path)) continue
101
+
102
+ const { size } = await stat(join(root, path))
103
+ if (size > maxFileBytes) {
104
+ skipped.push({ path, reason: `too large (${size} bytes)` })
105
+ continue
106
+ }
107
+ files.push({ path, bytes: size })
108
+ }
109
+ }
110
+
111
+ await walk('')
112
+ return { files, skipped, truncated }
113
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,123 @@
1
+ import { callTool } from './client.js'
2
+ import type { MimirConfig } from './config.js'
3
+
4
+ export type Registration = { dispose: () => Promise<void> }
5
+
6
+ type ToolExecutor = (input: any, context: any) => Promise<{ content: string }>
7
+ type ToolDefinition = {
8
+ name: string
9
+ description: string
10
+ input: Record<string, unknown>
11
+ execute: ToolExecutor
12
+ }
13
+
14
+ type ToolsContext = {
15
+ tool: { transform: (callback: (editor: { add: (tool: ToolDefinition) => void }) => void) => Promise<Registration> }
16
+ mcp: {
17
+ transform: (
18
+ callback: (editor: { list: () => readonly [string, { type?: string; url?: string; disabled?: boolean }][] }) => void,
19
+ ) => Promise<Registration>
20
+ }
21
+ }
22
+
23
+ /**
24
+ * The two tools exist for someone running the plugin without the MCP server.
25
+ * When an MCP server already answers at the same endpoint they would only
26
+ * duplicate its tools, so `auto` leaves them out.
27
+ */
28
+ export async function registerTools(
29
+ ctx: ToolsContext,
30
+ config: MimirConfig,
31
+ repo: string | null,
32
+ ): Promise<Registration> {
33
+ if (config.tools === 'never') return IDLE
34
+ if (config.tools === 'auto' && (await servedByMcp(ctx, config.url))) return IDLE
35
+
36
+ return ctx.tool.transform((editor) => {
37
+ editor.add(digestTool(repo))
38
+ editor.add(rememberTool(repo))
39
+ })
40
+ }
41
+
42
+ const IDLE: Registration = { dispose: async () => {} }
43
+
44
+ async function servedByMcp(ctx: ToolsContext, url: string): Promise<boolean> {
45
+ let found = false
46
+ try {
47
+ const registration = await ctx.mcp.transform((editor) => {
48
+ found = editor
49
+ .list()
50
+ .some(([, server]) => server.type === 'remote' && !server.disabled && sameEndpoint(server.url, `${url}/mcp`))
51
+ })
52
+ await registration.dispose()
53
+ } catch {
54
+ // A broken MCP entry must not cost the session its tools.
55
+ return false
56
+ }
57
+ return found
58
+ }
59
+
60
+ function sameEndpoint(actual: string | undefined, expected: string): boolean {
61
+ return strip(actual) === strip(expected)
62
+ }
63
+
64
+ function strip(value: string | undefined): string {
65
+ return (value ?? '').replace(/\/+$/, '')
66
+ }
67
+
68
+ function digestTool(repo: string | null): ToolDefinition {
69
+ return {
70
+ name: 'mimir_digest',
71
+ description:
72
+ 'Load what this project already knows from Mimir. Call once at the start of a session, before searching for anything.',
73
+ input: {
74
+ type: 'object',
75
+ properties: {
76
+ budget_tokens: {
77
+ type: 'integer',
78
+ minimum: 1,
79
+ description: 'Rough size cap, default 800',
80
+ },
81
+ },
82
+ additionalProperties: false,
83
+ },
84
+ async execute(input) {
85
+ const result = await callTool(
86
+ 'memory_digest',
87
+ { budget_tokens: input?.budget_tokens ?? 800, repo: repo ?? undefined },
88
+ { timeoutMs: 5000 },
89
+ )
90
+ if (!result.ok) return { content: `Mimir is unavailable (${result.error}). Carry on without it.` }
91
+ const digest = result.result as { text?: string }
92
+ return { content: digest.text?.trim() || 'Mimir has nothing stored for this project yet.' }
93
+ },
94
+ }
95
+ }
96
+
97
+ function rememberTool(repo: string | null): ToolDefinition {
98
+ return {
99
+ name: 'mimir_remember',
100
+ description:
101
+ 'Store one durable fact in Mimir. Use a path like "deploy/rollback" or "auth/token-rotation"; rewriting the same path replaces what was there.',
102
+ input: {
103
+ type: 'object',
104
+ properties: {
105
+ path: { type: 'string', description: 'Slash-separated memory path, e.g. deploy/rollback' },
106
+ body: { type: 'string', description: 'What to remember, written so it reads without the conversation' },
107
+ kind: { type: 'string', enum: ['note', 'fact', 'decision', 'gotcha', 'snippet'] },
108
+ },
109
+ required: ['path', 'body'],
110
+ additionalProperties: false,
111
+ },
112
+ async execute(input) {
113
+ const result = await callTool(
114
+ 'memory_write',
115
+ { path: input.path, body: input.body, kind: input.kind, repo: repo ?? undefined },
116
+ { timeoutMs: 8000 },
117
+ )
118
+ if (!result.ok) return { content: `Could not store that (${result.error}).` }
119
+ const written = result.result as { path?: string; created?: boolean }
120
+ return { content: `${written.created ? 'Stored' : 'Updated'} ${written.path ?? input.path}.` }
121
+ },
122
+ }
123
+ }