micro-models-agent 0.28.0 → 0.28.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.
Files changed (167) hide show
  1. package/dist/main.js +314 -208
  2. package/package.json +1 -1
  3. package/dist/cli/commands.js +0 -220
  4. package/dist/cli/completer.js +0 -168
  5. package/dist/cli/index.js +0 -2
  6. package/dist/cli/main.js +0 -113
  7. package/dist/cli/repl.js +0 -987
  8. package/dist/cli/security-commands.js +0 -166
  9. package/dist/cli/setup.js +0 -229
  10. package/dist/config/config.js +0 -186
  11. package/dist/config/defaults.js +0 -91
  12. package/dist/config/experts.js +0 -15
  13. package/dist/config/index.js +0 -3
  14. package/dist/config/security.js +0 -193
  15. package/dist/config/types.js +0 -1
  16. package/dist/core/agent-moe.js +0 -98
  17. package/dist/core/agent.js +0 -461
  18. package/dist/core/bootstrap.js +0 -321
  19. package/dist/core/index.js +0 -2
  20. package/dist/core/prompt-builder.js +0 -55
  21. package/dist/core/session-logger.js +0 -122
  22. package/dist/core/types.js +0 -1
  23. package/dist/i18n/en.json +0 -461
  24. package/dist/i18n/index.js +0 -43
  25. package/dist/i18n/ru.json +0 -461
  26. package/dist/index.js +0 -22
  27. package/dist/llm/image-utils.js +0 -144
  28. package/dist/llm/index.js +0 -4
  29. package/dist/llm/model-loader.js +0 -78
  30. package/dist/llm/openai-compat.js +0 -324
  31. package/dist/llm/orchestrator.js +0 -194
  32. package/dist/llm/provider.js +0 -10
  33. package/dist/llm/response.js +0 -39
  34. package/dist/llm/token-counter.js +0 -39
  35. package/dist/llm/types.js +0 -1
  36. package/dist/logger/app-logger.js +0 -76
  37. package/dist/logger/index.js +0 -1
  38. package/dist/migration/backup.js +0 -45
  39. package/dist/migration/detect.js +0 -50
  40. package/dist/migration/index.js +0 -2
  41. package/dist/modules/browser/actions.js +0 -46
  42. package/dist/modules/browser/cookie-store.js +0 -24
  43. package/dist/modules/browser/index.js +0 -5
  44. package/dist/modules/browser/module.js +0 -28
  45. package/dist/modules/browser/session.js +0 -287
  46. package/dist/modules/browser/snapshot.js +0 -114
  47. package/dist/modules/browser/types.js +0 -9
  48. package/dist/modules/context/history.js +0 -15
  49. package/dist/modules/context/index.js +0 -1
  50. package/dist/modules/context/manager.js +0 -240
  51. package/dist/modules/execution/auditor.js +0 -72
  52. package/dist/modules/execution/index.js +0 -6
  53. package/dist/modules/execution/module.js +0 -337
  54. package/dist/modules/execution/moe-executor.js +0 -209
  55. package/dist/modules/execution/plan-validator.js +0 -153
  56. package/dist/modules/execution/planner.js +0 -35
  57. package/dist/modules/execution/stuck-detector.js +0 -134
  58. package/dist/modules/execution/tracker.js +0 -53
  59. package/dist/modules/execution/types.js +0 -1
  60. package/dist/modules/execution/verifier.js +0 -149
  61. package/dist/modules/hallucination/confidence.js +0 -54
  62. package/dist/modules/hallucination/consistency.js +0 -60
  63. package/dist/modules/hallucination/detector.js +0 -41
  64. package/dist/modules/hallucination/factual.js +0 -170
  65. package/dist/modules/hallucination/index.js +0 -4
  66. package/dist/modules/index.js +0 -5
  67. package/dist/modules/indexer/cache.js +0 -38
  68. package/dist/modules/indexer/index.js +0 -3
  69. package/dist/modules/indexer/module.js +0 -192
  70. package/dist/modules/indexer/walker.js +0 -101
  71. package/dist/modules/mcp/client.js +0 -393
  72. package/dist/modules/mcp/index.js +0 -3
  73. package/dist/modules/mcp/module.js +0 -146
  74. package/dist/modules/mcp/registry.js +0 -15
  75. package/dist/modules/memory/index.js +0 -1
  76. package/dist/modules/memory/module.js +0 -48
  77. package/dist/modules/memory/search.js +0 -40
  78. package/dist/modules/memory/store.js +0 -65
  79. package/dist/modules/pipelines/engine.js +0 -60
  80. package/dist/modules/pipelines/index.js +0 -3
  81. package/dist/modules/pipelines/parser.js +0 -53
  82. package/dist/modules/pipelines/template.js +0 -14
  83. package/dist/modules/plugins/builtin/lint-on-write.js +0 -121
  84. package/dist/modules/plugins/builtin/notify.js +0 -8
  85. package/dist/modules/plugins/index.js +0 -1
  86. package/dist/modules/plugins/loader.js +0 -28
  87. package/dist/modules/plugins/manager.js +0 -161
  88. package/dist/modules/plugins/types.js +0 -1
  89. package/dist/modules/processes/detect.js +0 -34
  90. package/dist/modules/processes/index.js +0 -3
  91. package/dist/modules/processes/registry.js +0 -148
  92. package/dist/modules/processes/runner.js +0 -124
  93. package/dist/modules/registry.js +0 -45
  94. package/dist/modules/security/audit-log.js +0 -116
  95. package/dist/modules/security/audit-notifier.js +0 -292
  96. package/dist/modules/security/command-validator.js +0 -185
  97. package/dist/modules/security/content-scanner.js +0 -52
  98. package/dist/modules/security/data-sanitizer.js +0 -97
  99. package/dist/modules/security/encryption.js +0 -240
  100. package/dist/modules/security/index.js +0 -14
  101. package/dist/modules/security/network-validator.js +0 -79
  102. package/dist/modules/security/path-validator.js +0 -155
  103. package/dist/modules/security/rate-limiter.js +0 -119
  104. package/dist/modules/security/security-policies.js +0 -393
  105. package/dist/modules/security/session-encryption.js +0 -193
  106. package/dist/modules/security/session-isolation.js +0 -95
  107. package/dist/modules/session/index.js +0 -3
  108. package/dist/modules/session/manager.js +0 -167
  109. package/dist/modules/session/module.js +0 -24
  110. package/dist/modules/session/store.js +0 -174
  111. package/dist/modules/session/types.js +0 -1
  112. package/dist/modules/skills/index.js +0 -3
  113. package/dist/modules/skills/loader.js +0 -72
  114. package/dist/modules/skills/matcher.js +0 -27
  115. package/dist/modules/skills/module.js +0 -143
  116. package/dist/modules/types.js +0 -1
  117. package/dist/modules/updater/checker.js +0 -32
  118. package/dist/modules/updater/index.js +0 -1
  119. package/dist/modules/user-profile/compressor.js +0 -16
  120. package/dist/modules/user-profile/index.js +0 -1
  121. package/dist/modules/user-profile/profile.js +0 -68
  122. package/dist/tools/approve.js +0 -32
  123. package/dist/tools/attach-image.js +0 -89
  124. package/dist/tools/bash.js +0 -140
  125. package/dist/tools/browser.js +0 -97
  126. package/dist/tools/create-dir.js +0 -56
  127. package/dist/tools/delete-file.js +0 -63
  128. package/dist/tools/edit-file.js +0 -77
  129. package/dist/tools/executor.js +0 -95
  130. package/dist/tools/file-info.js +0 -45
  131. package/dist/tools/filter-tools.js +0 -10
  132. package/dist/tools/glob-tool.js +0 -26
  133. package/dist/tools/grep-tool.js +0 -64
  134. package/dist/tools/index.js +0 -52
  135. package/dist/tools/list-dir.js +0 -47
  136. package/dist/tools/load-skill.js +0 -48
  137. package/dist/tools/mcp-call.js +0 -68
  138. package/dist/tools/move-file.js +0 -84
  139. package/dist/tools/path-utils.js +0 -51
  140. package/dist/tools/pipeline-run.js +0 -144
  141. package/dist/tools/preview.js +0 -2
  142. package/dist/tools/process-kill.js +0 -29
  143. package/dist/tools/process-list.js +0 -38
  144. package/dist/tools/process-log.js +0 -41
  145. package/dist/tools/question.js +0 -142
  146. package/dist/tools/read-file.js +0 -73
  147. package/dist/tools/recall.js +0 -110
  148. package/dist/tools/registry.js +0 -36
  149. package/dist/tools/remember.js +0 -67
  150. package/dist/tools/scope-check.js +0 -30
  151. package/dist/tools/search-history.js +0 -64
  152. package/dist/tools/subagent.js +0 -142
  153. package/dist/tools/types.js +0 -1
  154. package/dist/tools/user-input.js +0 -123
  155. package/dist/tools/web-browse.js +0 -57
  156. package/dist/tools/web-fetch.js +0 -72
  157. package/dist/tools/web-search.js +0 -59
  158. package/dist/tools/write-file.js +0 -80
  159. package/dist/ui/box.js +0 -81
  160. package/dist/ui/colors.js +0 -4
  161. package/dist/ui/diff.js +0 -185
  162. package/dist/ui/index.js +0 -6
  163. package/dist/ui/md-formatter.js +0 -212
  164. package/dist/ui/output.js +0 -13
  165. package/dist/ui/renderer.js +0 -141
  166. package/dist/ui/spinner.js +0 -70
  167. package/dist/ui/table.js +0 -144
@@ -1,144 +0,0 @@
1
- import { t } from '../i18n/index';
2
- import { PipelineEngine } from '../modules/pipelines/engine';
3
- import { PipelineParser } from '../modules/pipelines/parser';
4
- import { TemplateEngine } from '../modules/pipelines/template';
5
- import { Agent } from '../core/agent';
6
- import { ContextManager } from '../modules/context/manager';
7
- import { PluginManager } from '../modules/plugins/manager';
8
- import { HallucinationDetector } from '../modules/hallucination/detector';
9
- import { logSecurityBlock } from '../modules/security/audit-log';
10
- import { getSessionSecurityConfig } from '../modules/security/session-isolation';
11
- const engine = new PipelineEngine();
12
- const MAX_CONCURRENT = 3;
13
- const MAX_ATTEMPTS = 3;
14
- async function runStep(ctx, step, params, outputs) {
15
- const prompt = TemplateEngine.render(step.prompt, params, outputs);
16
- let lastError = "";
17
- for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
18
- try {
19
- const subContextManager = new ContextManager(ctx.config.contextWindow, ctx.config.contextBudget);
20
- const subPluginManager = new PluginManager();
21
- const systemPrompt = {
22
- content: `You are a pipeline step agent ("${step.agent}"). Complete the given task using the available tools.`,
23
- priority: "critical",
24
- essential: true,
25
- estimatedTokens: 80,
26
- };
27
- const subDeps = {
28
- config: ctx.config,
29
- llmProvider: ctx.llmProvider,
30
- toolExecutor: ctx.toolExecutor,
31
- pluginManager: subPluginManager,
32
- contextManager: subContextManager,
33
- hallucinationDetector: new HallucinationDetector(),
34
- logger: ctx.logger,
35
- baseDir: ctx.baseDir,
36
- scope: ctx.scope,
37
- recursionDepth: (ctx.recursionDepth ?? 0) + 1,
38
- promptBlocks: [systemPrompt],
39
- };
40
- const subAgent = new Agent(subDeps);
41
- const result = await subAgent.run(prompt);
42
- if (result.success) {
43
- return { ok: true, output: result.text };
44
- }
45
- lastError = result.error || "no output";
46
- }
47
- catch (e) {
48
- lastError = e.message;
49
- }
50
- await new Promise((r) => setTimeout(r, 500 * attempt));
51
- }
52
- return { ok: false, output: "", error: lastError };
53
- }
54
- export const pipelineRunTool = {
55
- name: 'pipeline_run',
56
- description: 'Run a named pipeline with YAML definition. Creates a DAG of sub-agents that execute in dependency order.',
57
- tags: ['shell', 'code'],
58
- parameters: {
59
- type: 'object',
60
- properties: {
61
- name: { type: 'string', description: 'Pipeline name' },
62
- yaml: { type: 'string', description: 'Pipeline YAML definition with steps' },
63
- params: { type: 'object', description: 'Template params for {key} placeholders' },
64
- },
65
- required: ['name', 'yaml'],
66
- },
67
- handler: async (ctx, args) => {
68
- const name = String(args.name || '');
69
- const yaml = String(args.yaml || '');
70
- const params = args.params || {};
71
- if (!yaml) {
72
- return { success: false, output: t('pipeline.invalid') };
73
- }
74
- if (!ctx.llmProvider || !ctx.toolExecutor) {
75
- return {
76
- success: false,
77
- output: 'Pipeline cannot run: missing llmProvider or toolExecutor in context',
78
- };
79
- }
80
- const securityConfig = ctx.sessionContext
81
- ? getSessionSecurityConfig(ctx.config, ctx.sessionContext)
82
- : ctx.config.security;
83
- const maxDepth = securityConfig?.maxRecursionDepth ?? 3;
84
- const currentDepth = ctx.recursionDepth ?? 0;
85
- if (currentDepth >= maxDepth) {
86
- logSecurityBlock(ctx.sessionId, "bash_command", `Maximum recursion depth (${maxDepth}) exceeded`, name);
87
- return {
88
- success: false,
89
- output: `[SECURITY BLOCKED] Maximum pipeline recursion depth (${maxDepth}) exceeded`,
90
- };
91
- }
92
- try {
93
- const pipeline = PipelineParser.parse(yaml);
94
- engine.reset();
95
- const order = engine.resolveDependencies(pipeline.steps);
96
- const completed = new Set();
97
- const outputs = {};
98
- const logs = [];
99
- const failed = new Set();
100
- while (completed.size < pipeline.steps.length) {
101
- const ready = engine
102
- .getReadySteps(pipeline.steps, completed)
103
- .filter((s) => !failed.has(s.id));
104
- if (ready.length === 0) {
105
- if (failed.size > 0)
106
- break;
107
- throw new Error(t('pipeline.circular', { stepId: order.join(', ') }));
108
- }
109
- const batch = ready.slice(0, MAX_CONCURRENT);
110
- const results = await Promise.all(batch.map((step) => runStep(ctx, step, params, outputs)));
111
- for (let i = 0; i < batch.length; i++) {
112
- const step = batch[i];
113
- const result = results[i];
114
- if (result.ok) {
115
- completed.add(step.id);
116
- outputs[step.id] = { output: result.output };
117
- engine.setStepStatus(step.id, 'done');
118
- logs.push(` ✓ ${step.id}: ${result.output.split("\n")[0]}`);
119
- }
120
- else {
121
- failed.add(step.id);
122
- engine.setStepStatus(step.id, 'failed');
123
- logs.push(` ✗ ${step.id}: ${result.error}`);
124
- }
125
- }
126
- if (failed.size > 0)
127
- break;
128
- }
129
- if (failed.size > 0) {
130
- return {
131
- success: false,
132
- output: `Pipeline "${pipeline.name}" failed. Executed ${completed.size}/${pipeline.steps.length} steps.\n${logs.join("\n")}`,
133
- };
134
- }
135
- return {
136
- success: true,
137
- output: `Pipeline "${pipeline.name}" completed successfully (${completed.size} steps).\n${logs.join("\n")}`,
138
- };
139
- }
140
- catch (e) {
141
- return { success: false, output: `Pipeline error: ${e.message}` };
142
- }
143
- },
144
- };
@@ -1,2 +0,0 @@
1
- /** Maximum number of lines shown in tool output previews. */
2
- export const MAX_PREVIEW_LINES = 15;
@@ -1,29 +0,0 @@
1
- import { processRegistry } from '../modules/processes';
2
- import { t } from '../i18n/index';
3
- export const processKillTool = {
4
- name: 'process_kill',
5
- description: 'Stop a background process started via bash (dev server, watcher). Kills the whole process tree (children included). Use the id returned by bash or process_list.',
6
- tags: ['shell'],
7
- parameters: {
8
- type: 'object',
9
- properties: {
10
- id: { type: 'string', description: 'Process id from bash output or process_list' },
11
- },
12
- required: ['id'],
13
- },
14
- handler: async (ctx, args) => {
15
- const id = String(args.id);
16
- const entry = processRegistry.get(id);
17
- if (!entry) {
18
- return { success: false, output: t('proc.not_found', { id }) };
19
- }
20
- const killed = processRegistry.kill(id);
21
- if (!killed) {
22
- return { success: false, output: t('proc.kill_failed', { id }) };
23
- }
24
- return {
25
- success: true,
26
- output: t('proc.killed', { id, pid: entry.pid }),
27
- };
28
- },
29
- };
@@ -1,38 +0,0 @@
1
- import { processRegistry } from '../modules/processes';
2
- import { t } from '../i18n/index';
3
- export const processListTool = {
4
- name: 'process_list',
5
- description: 'List background processes started via the bash tool (dev servers, watchers, long-running commands). Shows id, pid, command, status, and recent output. Use with process_log and process_kill to inspect or stop them.',
6
- tags: ['shell'],
7
- parameters: {
8
- type: 'object',
9
- properties: {},
10
- },
11
- handler: async (ctx) => {
12
- const list = processRegistry.list(ctx.sessionId);
13
- if (list.length === 0) {
14
- return { success: true, output: t('proc.none') };
15
- }
16
- const statusLabel = (status) => {
17
- if (status === 'running')
18
- return t('proc.status_running');
19
- if (status === 'exited')
20
- return t('proc.status_exited');
21
- return t('proc.status_killed');
22
- };
23
- const lines = [`${t('proc.list_header')} (${list.length}):`];
24
- for (const entry of list) {
25
- const tail = entry.log.length > 0 ? entry.log[entry.log.length - 1] : '';
26
- const detail = tail
27
- ? ` — ${tail.slice(0, 80)}${tail.length > 80 ? '…' : ''}`
28
- : '';
29
- lines.push(` ${entry.id} PID ${entry.pid} ${statusLabel(entry.status)} ${entry.command}${detail}`);
30
- }
31
- lines.push(`\n${t('proc.hint', {
32
- list: 'process_list',
33
- log: 'process_log',
34
- kill: 'process_kill',
35
- })}`);
36
- return { success: true, output: lines.join('\n') };
37
- },
38
- };
@@ -1,41 +0,0 @@
1
- import { processRegistry } from '../modules/processes';
2
- import { t } from '../i18n/index';
3
- import { MAX_PREVIEW_LINES } from './preview';
4
- const DEFAULT_TAIL = MAX_PREVIEW_LINES;
5
- export const processLogTool = {
6
- name: 'process_log',
7
- description: `Show the buffered output of a background process started via bash. Shows the last ${DEFAULT_TAIL} lines by default. Use after starting a dev server to verify it came up without errors, and while it runs to check its state.`,
8
- tags: ['shell'],
9
- parameters: {
10
- type: 'object',
11
- properties: {
12
- id: { type: 'string', description: 'Process id from bash output or process_list' },
13
- tail: { type: 'number', description: `Number of trailing lines to show (default: ${DEFAULT_TAIL}, max 300)` },
14
- },
15
- required: ['id'],
16
- },
17
- handler: async (ctx, args) => {
18
- const id = String(args.id);
19
- const entry = processRegistry.get(id);
20
- if (!entry) {
21
- return { success: false, output: t('proc.not_found', { id }) };
22
- }
23
- const status = entry.status === 'running'
24
- ? t('proc.status_running')
25
- : entry.status === 'exited'
26
- ? t('proc.status_exited')
27
- : t('proc.status_killed');
28
- const tail = typeof args.tail === 'number' ? args.tail : DEFAULT_TAIL;
29
- const log = processRegistry.getLog(id, tail);
30
- if (!log) {
31
- return {
32
- success: true,
33
- output: `${t('proc.log_header', { id, status })} ${t('proc.log_empty')}`,
34
- };
35
- }
36
- return {
37
- success: true,
38
- output: `${t('proc.log_header', { id, status })}\n${log}`,
39
- };
40
- },
41
- };
@@ -1,142 +0,0 @@
1
- import { t } from "../i18n/index";
2
- import { askUser } from "./user-input";
3
- const DESCRIPTION = `Use this tool when you need to ask the user questions during execution. This allows you to:
4
- 1. Gather user preferences or requirements
5
- 2. Clarify ambiguous instructions
6
- 3. Get decisions on implementation choices as you work
7
- 4. Offer choices to the user about what direction to take.
8
-
9
- Usage notes:
10
- - When "custom" is enabled (default), a "Type your own answer" option is added automatically; don't include "Other" or catch-all options
11
- - Answers are returned as arrays of labels; set "multiple": true to allow selecting more than one
12
- - If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label
13
- - Execution blocks until the user answers every question
14
- - Omit "options" for a free-text question`;
15
- function isOption(val) {
16
- if (!val || typeof val !== "object")
17
- return false;
18
- const opt = val;
19
- return typeof opt.label === "string" && typeof opt.description === "string";
20
- }
21
- function normalizeQuestions(args) {
22
- const raw = args.questions;
23
- if (Array.isArray(raw)) {
24
- const specs = [];
25
- for (const item of raw) {
26
- if (!item || typeof item !== "object")
27
- continue;
28
- const q = item;
29
- if (typeof q.question !== "string" || !q.question.trim())
30
- continue;
31
- const options = Array.isArray(q.options)
32
- ? q.options.filter(isOption)
33
- : undefined;
34
- // An explicitly provided options array with no valid entries is a
35
- // malformed call — skip the question instead of blocking on stdin.
36
- if (Array.isArray(q.options) && options.length === 0)
37
- continue;
38
- specs.push({
39
- question: q.question,
40
- header: typeof q.header === "string" ? q.header : undefined,
41
- options,
42
- multiple: q.multiple === true,
43
- custom: q.custom === false ? false : undefined,
44
- });
45
- }
46
- return specs;
47
- }
48
- // Legacy format: { question: "..." } — plain free-text question.
49
- if (typeof args.question === "string" && args.question.trim()) {
50
- return [{ question: args.question }];
51
- }
52
- return [];
53
- }
54
- export const questionTool = {
55
- name: "question",
56
- description: DESCRIPTION,
57
- tags: ["core"],
58
- interactive: true,
59
- parameters: {
60
- type: "object",
61
- properties: {
62
- questions: {
63
- type: "array",
64
- description: "Questions to ask",
65
- items: {
66
- type: "object",
67
- properties: {
68
- question: { type: "string", description: "Complete question" },
69
- header: {
70
- type: "string",
71
- description: "Very short label (max 30 chars)",
72
- },
73
- options: {
74
- type: "array",
75
- description: "Available choices; omit for a free-text question",
76
- items: {
77
- type: "object",
78
- properties: {
79
- label: {
80
- type: "string",
81
- description: "Display text (1-5 words, concise)",
82
- },
83
- description: {
84
- type: "string",
85
- description: "Explanation of choice",
86
- },
87
- },
88
- required: ["label", "description"],
89
- },
90
- },
91
- multiple: {
92
- type: "boolean",
93
- description: "Allow selecting multiple choices",
94
- },
95
- custom: {
96
- type: "boolean",
97
- description: "Allow typing a custom answer (default: true)",
98
- },
99
- },
100
- required: ["question"],
101
- },
102
- },
103
- question: {
104
- type: "string",
105
- description: "Legacy single free-text question",
106
- },
107
- },
108
- },
109
- handler: async (ctx, args) => {
110
- if (ctx.exitOnComplete) {
111
- return { success: false, output: t("tool.interactive_disabled") };
112
- }
113
- const questions = normalizeQuestions(args);
114
- if (questions.length === 0) {
115
- return { success: false, output: t("tool.question.no_questions") };
116
- }
117
- const answers = [];
118
- for (let i = 0; i < questions.length; i++) {
119
- const q = questions[i];
120
- const progress = questions.length > 1
121
- ? t("tool.question.progress", {
122
- current: i + 1,
123
- total: questions.length,
124
- })
125
- : undefined;
126
- answers.push(await askUser(q.question, {
127
- header: q.header,
128
- options: q.options,
129
- multiple: q.multiple,
130
- custom: q.custom,
131
- progress,
132
- }));
133
- }
134
- const formatted = questions
135
- .map((q, i) => `"${q.question}"="${answers[i].length ? answers[i].join(", ") : t("tool.question.unanswered")}"`)
136
- .join(", ");
137
- return {
138
- success: true,
139
- output: t("tool.question.answered", { formatted }),
140
- };
141
- },
142
- };
@@ -1,73 +0,0 @@
1
- import { readFileSync, existsSync } from "fs";
2
- import { extname } from "path";
3
- import { t } from "../i18n/index";
4
- import { isPathInScope } from "../modules/security/path-validator";
5
- import { DEFAULT_SECURITY_CONFIG } from "../config/security";
6
- import { logSecurityBlock } from "../modules/security/audit-log";
7
- import { safeResolvePath } from "./path-utils";
8
- import { MAX_PREVIEW_LINES } from "./preview";
9
- const DEFAULT_LIMIT = MAX_PREVIEW_LINES;
10
- export const readFileTool = {
11
- name: "read_file",
12
- description: `Read a file from the filesystem. Reads up to ${DEFAULT_LIMIT} lines at a time by default; use offset to page through large files.`,
13
- tags: ["file", "code"],
14
- parameters: {
15
- type: "object",
16
- properties: {
17
- path: { type: "string", description: "File path to read" },
18
- offset: {
19
- type: "number",
20
- description: `Starting line (1-indexed). Use offset=<next> from a truncated result to continue reading.`,
21
- },
22
- limit: {
23
- type: "number",
24
- description: `Number of lines to read (default ${DEFAULT_LIMIT})`,
25
- },
26
- },
27
- required: ["path"],
28
- },
29
- handler: async (ctx, args) => {
30
- const path = String(args.path);
31
- const resolved = safeResolvePath(ctx.baseDir, path);
32
- const securityPaths = ctx.config?.security?.paths || DEFAULT_SECURITY_CONFIG.paths;
33
- const scopeCheck = isPathInScope(ctx.baseDir, resolved, ctx.scope, securityPaths);
34
- if (!scopeCheck.allowed) {
35
- const pathStr = path;
36
- logSecurityBlock(ctx.sessionId || undefined, "file_read", scopeCheck.reason || "Path not allowed", pathStr);
37
- return {
38
- success: false,
39
- output: t("file.path_not_allowed", {
40
- path: `${path} — ${scopeCheck.reason}`,
41
- }),
42
- };
43
- }
44
- if (!existsSync(resolved)) {
45
- return { success: false, output: t("file.notfound", { path }) };
46
- }
47
- ctx.trackReadPath?.(path);
48
- const content = readFileSync(resolved, "utf-8");
49
- // Track file paths mentioned in the document (e.g. structure.md, README)
50
- ctx.trackDocumentContent?.(content);
51
- const lines = content.split("\n");
52
- const total = lines.length;
53
- const offset = args.offset || 1;
54
- const limit = args.limit || DEFAULT_LIMIT;
55
- const end = Math.min(offset - 1 + limit, total);
56
- const selected = lines.slice(offset - 1, end).join("\n");
57
- const ext = extname(resolved) || "(no extension)";
58
- const header = t("file.read_header", {
59
- path,
60
- ext,
61
- total: String(total),
62
- from: String(offset),
63
- to: String(end),
64
- });
65
- const truncated = end < total
66
- ? t("file.read_truncated", {
67
- remaining: String(total - end),
68
- next: String(end + 1),
69
- })
70
- : "";
71
- return { success: true, output: `${header}\n${selected}${truncated}` };
72
- },
73
- };
@@ -1,110 +0,0 @@
1
- import { homedir } from 'os';
2
- import { join } from 'path';
3
- import { t } from '../i18n/index';
4
- import { MemoryStore } from '../modules/memory/store';
5
- const CATEGORIES = ['preferences', 'conventions', 'decisions', 'errors', 'facts'];
6
- export const recallTool = {
7
- name: 'recall',
8
- description: 'Recall stored information from memory. Search across preferences, facts, conventions, decisions, errors.',
9
- tags: ['memory'],
10
- parameters: {
11
- type: 'object',
12
- properties: {
13
- query: {
14
- type: 'string',
15
- description: 'Search query (full-text search across all memory)',
16
- },
17
- category: {
18
- type: 'string',
19
- description: 'Limit to specific category: preferences, conventions, decisions, errors, facts',
20
- enum: CATEGORIES,
21
- },
22
- },
23
- },
24
- handler: async (_ctx, args) => {
25
- const query = args.query ? String(args.query) : '';
26
- const category = args.category ? String(args.category) : '';
27
- const memoryDir = join(homedir(), '.mma', 'memory');
28
- const store = new MemoryStore(memoryDir);
29
- try {
30
- // No query, no category → show everything
31
- if (!query && !category) {
32
- return { success: true, output: formatAll(store) };
33
- }
34
- // Category only → show that category
35
- if (!query && category) {
36
- return { success: true, output: formatCategory(store, category) };
37
- }
38
- // Query with optional category → search
39
- if (category) {
40
- const results = searchCategory(store, category, query);
41
- if (results.length === 0) {
42
- return { success: true, output: t('tool.recall.empty', { query }) };
43
- }
44
- return { success: true, output: t('tool.recall.search_results', { category, results: results.join('\n') }) };
45
- }
46
- // Query across all
47
- const results = store.search(query);
48
- if (results.length === 0) {
49
- return { success: true, output: t('tool.recall.empty', { query }) };
50
- }
51
- const formatted = results.map(r => `[${r.file}] ${r.match}`).join('\n');
52
- return { success: true, output: t('tool.recall.search_results', { category: 'all', results: formatted }) };
53
- }
54
- catch (err) {
55
- return { success: true, output: t('tool.memory_error', { error: String(err) }) };
56
- }
57
- },
58
- };
59
- function formatAll(store) {
60
- const parts = [];
61
- const prefs = store.getPreferences();
62
- if (Object.keys(prefs).length > 0) {
63
- parts.push('Preferences:');
64
- for (const [k, v] of Object.entries(prefs)) {
65
- parts.push(` ${k} = ${v}`);
66
- }
67
- }
68
- for (const cat of ['facts', 'conventions', 'decisions', 'errors']) {
69
- const content = store.read(cat);
70
- const entries = content.split('\n').filter(l => l.startsWith('- '));
71
- if (entries.length > 0) {
72
- parts.push(`\n${cat.charAt(0).toUpperCase() + cat.slice(1)} (last 5):`);
73
- for (const e of entries.slice(-5)) {
74
- parts.push(` ${e}`);
75
- }
76
- }
77
- }
78
- return parts.length > 0 ? parts.join('\n') : t('tool.recall.no_memory');
79
- }
80
- function formatCategory(store, category) {
81
- if (category === 'preferences') {
82
- const prefs = store.getPreferences();
83
- if (Object.keys(prefs).length === 0)
84
- return t('tool.recall.no_memory');
85
- const lines = ['Preferences:'];
86
- for (const [k, v] of Object.entries(prefs)) {
87
- lines.push(` ${k} = ${v}`);
88
- }
89
- return lines.join('\n');
90
- }
91
- const content = store.read(category);
92
- const entries = content.split('\n').filter(l => l.startsWith('- '));
93
- if (entries.length === 0)
94
- return t('tool.recall.no_memory');
95
- return `${category.charAt(0).toUpperCase() + category.slice(1)} (${entries.length} entries):\n${entries.join('\n')}`;
96
- }
97
- function searchCategory(store, category, query) {
98
- if (category === 'preferences') {
99
- const prefs = store.getPreferences();
100
- const lower = query.toLowerCase();
101
- return Object.entries(prefs)
102
- .filter(([k, v]) => k.toLowerCase().includes(lower) || v.toLowerCase().includes(lower))
103
- .map(([k, v]) => ` ${k} = ${v}`);
104
- }
105
- const content = store.read(category);
106
- const lower = query.toLowerCase();
107
- return content.split('\n')
108
- .filter(l => l.startsWith('- ') && l.toLowerCase().includes(lower))
109
- .map(l => ` ${l}`);
110
- }
@@ -1,36 +0,0 @@
1
- export class ToolRegistry {
2
- tools = new Map();
3
- register(tool) {
4
- if (this.tools.has(tool.name)) {
5
- throw new Error(`Tool already registered: ${tool.name}`);
6
- }
7
- this.tools.set(tool.name, tool);
8
- }
9
- get(name) {
10
- return this.tools.get(name);
11
- }
12
- has(name) {
13
- return this.tools.has(name);
14
- }
15
- list() {
16
- return Array.from(this.tools.keys()).sort();
17
- }
18
- getAll() {
19
- return Array.from(this.tools.values());
20
- }
21
- getByTags(tags) {
22
- return this.getAll().filter(t => {
23
- if (!t.tags || t.tags.length === 0)
24
- return false;
25
- return tags.some(tag => t.tags.includes(tag));
26
- });
27
- }
28
- getAllForLLM(tags) {
29
- const tools = tags ? this.getByTags(tags) : this.getAll();
30
- return tools.map(t => ({
31
- name: t.name,
32
- description: t.description,
33
- parameters: t.parameters,
34
- }));
35
- }
36
- }