@technomoron/agent-brain 0.0.0-stage → 0.1.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.
Files changed (39) hide show
  1. package/CHANGES.md +14 -0
  2. package/LICENSE +21 -0
  3. package/README.md +852 -2
  4. package/dist/agent-brain.js +6 -0
  5. package/dist/brain/built-in-skills.js +24 -0
  6. package/dist/brain/cli.js +265 -0
  7. package/dist/brain/config.js +92 -0
  8. package/dist/brain/connectors.js +63 -0
  9. package/dist/brain/consolidation-skill.js +5 -0
  10. package/dist/brain/consolidation.js +134 -0
  11. package/dist/brain/git.js +139 -0
  12. package/dist/brain/github-reviews.js +174 -0
  13. package/dist/brain/projects.js +136 -0
  14. package/dist/brain/remote-policy.js +126 -0
  15. package/dist/brain/remote-server.js +211 -0
  16. package/dist/brain/repositories.js +28 -0
  17. package/dist/brain/repository-discovery.js +76 -0
  18. package/dist/brain/server.js +283 -0
  19. package/dist/brain/skills.js +54 -0
  20. package/dist/brain/store.js +499 -0
  21. package/dist/brain/todos.js +155 -0
  22. package/dist/brain/windows-pipe.js +19 -0
  23. package/dist/version.js +22 -0
  24. package/examples/brain.jsonc +7 -0
  25. package/examples/remote.jsonc +22 -0
  26. package/ops/config-deploy-entry.sh +3 -0
  27. package/ops/config-deploy-root.cjs +111 -0
  28. package/ops/config-deploy.cjs +176 -0
  29. package/ops/config-policy.cjs +220 -0
  30. package/ops/config-sync.cjs +72 -0
  31. package/ops/systemd/agent-brain.service +14 -0
  32. package/package.json +55 -4
  33. package/skills/brain-consolidate/SKILL.md +42 -0
  34. package/skills/brain-import/SKILL.md +56 -0
  35. package/skills/brain-memory/SKILL.md +73 -0
  36. package/skills/brain-review/SKILL.md +38 -0
  37. package/skills/code-review-organizer/SKILL.md +150 -0
  38. package/skills/review-items/SKILL.md +43 -0
  39. package/skills/todo-manager/SKILL.md +8 -0
@@ -0,0 +1,211 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createRemoteApi = createRemoteApi;
4
+ exports.serveRemote = serveRemote;
5
+ const fs = require("node:fs");
6
+ const path = require("node:path");
7
+ const node_child_process_1 = require("node:child_process");
8
+ const node_crypto_1 = require("node:crypto");
9
+ const apicore_server_1 = require("@technomoron/apicore-server");
10
+ const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
11
+ const store_1 = require("./store");
12
+ const server_1 = require("./server");
13
+ const remote_policy_1 = require("./remote-policy");
14
+ const repositories_1 = require("./repositories");
15
+ const repository_discovery_1 = require("./repository-discovery");
16
+ function secret(name) {
17
+ const value = process.env[name];
18
+ if (!value)
19
+ throw new Error('Missing environment variable ' + name);
20
+ return value;
21
+ }
22
+ function privateDirectory(directory) {
23
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
24
+ const stat = fs.lstatSync(directory);
25
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (process.platform !== 'win32' &&
26
+ ((stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.())))
27
+ throw new Error('Runtime directory must be private and owned by the server user');
28
+ }
29
+ /** A single process behind an HTTPS reverse proxy. Paths and identities come only from administrator configuration. */
30
+ async function createRemoteApi(configFile) {
31
+ const initial = (0, remote_policy_1.readRemoteConfig)(configFile);
32
+ privateDirectory(initial.runtime);
33
+ // Canonical roots prevent two configured repository IDs sharing storage through symlinks.
34
+ (0, remote_policy_1.validateRepositoryRoots)(initial, true);
35
+ for (const repo of initial.repositories) {
36
+ if (!fs.statSync(repo.cwd).isDirectory())
37
+ throw new Error('Repository working directory is missing');
38
+ const store = new store_1.BrainStore(repo.configRoot, repo.cwd);
39
+ try {
40
+ if ((repo.group && store.profile !== 'projects/' + repo.id) || (initial.dataRoot && store.pool !== repo.group))
41
+ throw new Error('Grouped repository requires its own registered project profile: ' + repo.id);
42
+ }
43
+ finally {
44
+ store.close();
45
+ }
46
+ }
47
+ // Policy edits apply immediately. Storage locations, signing keys and client registration require a restart.
48
+ const policy = () => {
49
+ const current = (0, remote_policy_1.readRemoteConfig)(configFile);
50
+ if (JSON.stringify(current.repositories) !== JSON.stringify(initial.repositories) || JSON.stringify(current.groups) !== JSON.stringify(initial.groups) || current.dataRoot !== initial.dataRoot || JSON.stringify(current.gitSync) !== JSON.stringify(initial.gitSync) || current.issuer !== initial.issuer || current.resource !== initial.resource) {
51
+ throw new Error('Restart the remote server after changing repository locations or endpoints');
52
+ }
53
+ return current;
54
+ };
55
+ const sessions = new apicore_server_1.JsonTokenStore(path.join(initial.runtime, 'sessions.json'));
56
+ const credentials = new apicore_server_1.MemAuthStore({ passkeys: false, tokenStore: sessions });
57
+ class ConfigAuth extends apicore_server_1.BaseAuthAdapter {
58
+ async getUser(identifier) { return policy().users.find((u) => !u.disabled && (u.subject === String(identifier) || u.login === identifier)) ?? null; }
59
+ getUserId(user) { return user.subject; }
60
+ getUserPasswordHash(user) { return user.kind === 'human' && user.passwordHashEnv ? secret(user.passwordHashEnv) : ''; }
61
+ filterUser(user) { return { subject: user.subject }; }
62
+ verifyPassword(password, hash) { return credentials.verifyPassword(password, hash); }
63
+ getClient(id) { return credentials.getClient(id); }
64
+ verifyClientSecret(client, value) { return credentials.verifyClientSecret(client, value); }
65
+ createAuthCode(input) { return credentials.createAuthCode(input); }
66
+ consumeAuthCode(code, client) { return credentials.consumeAuthCode(code, client); }
67
+ }
68
+ for (const client of initial.clients) {
69
+ await credentials.oauthStore.createClient({ clientId: client.id, redirectUris: client.redirectUris,
70
+ ...(client.secretEnv ? { clientSecret: secret(client.secretEnv) } : {}),
71
+ scope: [...client.permissions, ...new Set([...initial.clients.flatMap((c) => c.repos), ...initial.repositories.map((r) => r.id)]
72
+ .filter((repo) => client.repos.some((pattern) => (0, repositories_1.coversPattern)(pattern, repo))).map((repo) => 'repo:' + repo))] });
73
+ }
74
+ const api = new apicore_server_1.ApiServer({ authApi: false, origins: [], devMode: false }).authStorage(new ConfigAuth()).setTokenStore(sessions);
75
+ const login = new apicore_server_1.OAuthPasswordLogin(api, { issuer: initial.issuer,
76
+ allow: (subject, client, scopes, resources) => resources.length === 1 && resources[0] === initial.resource && (0, remote_policy_1.allowedGrant)(policy(), String(subject), client, scopes),
77
+ verifySecondFactor: (value, code) => {
78
+ const user = value;
79
+ if (!user.totpSecretEnv)
80
+ return true;
81
+ const file = path.join(initial.runtime, 'mfa.json');
82
+ const counters = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
83
+ const counter = (0, apicore_server_1.verifyTotp)(secret(user.totpSecretEnv), code, { after: counters[user.subject] });
84
+ if (counter === null)
85
+ return false;
86
+ counters[user.subject] = counter;
87
+ const temporary = file + '.' + (0, node_crypto_1.randomUUID)();
88
+ fs.writeFileSync(temporary, JSON.stringify(counters), { flag: 'wx', mode: 0o600 });
89
+ fs.renameSync(temporary, file);
90
+ return true;
91
+ }
92
+ }).register();
93
+ const attempts = new Map();
94
+ const provider = new apicore_server_1.OAuthAuthorizationServer(api, { issuer: initial.issuer, resources: [initial.resource],
95
+ rateLimit: (request) => {
96
+ for (const [key, entry] of attempts)
97
+ if (entry.expires <= Date.now())
98
+ attempts.delete(key);
99
+ const entry = attempts.get(request.ip) ?? { count: 0, expires: Date.now() + 300000 };
100
+ entry.count++;
101
+ if (entry.count > 100 || attempts.size >= 10000)
102
+ throw new apicore_server_1.OAuthProtocolError('slow_down', 'Too many authorization requests', 429);
103
+ attempts.set(request.ip, entry);
104
+ },
105
+ scopes: [...new Set([...initial.clients.flatMap((c) => [...c.permissions, ...c.repos.map((p) => 'repo:' + p)]), ...initial.repositories.map((r) => 'repo:' + r.id)])],
106
+ accessSecret: secret(initial.accessSecretEnv), refreshSecret: secret(initial.refreshSecretEnv),
107
+ authorize: login.authorize,
108
+ serviceAccounts: Object.fromEntries(initial.clients.filter((c) => c.kind === 'service').map((c) => [c.id, c.subject])),
109
+ validateGrant: (grant) => grant.resources.length === 1 && grant.resources[0] === initial.resource && (0, remote_policy_1.allowedGrant)(policy(), grant.userId, grant.clientId, grant.scopes) }).register();
110
+ const resource = new URL(initial.resource);
111
+ const endpoint = resource.pathname || '/';
112
+ const metadataPath = '/.well-known/oauth-protected-resource' + (endpoint === '/' ? '' : endpoint);
113
+ api.fastify.get(metadataPath, async () => provider.resourceMetadata(initial.resource));
114
+ api.fastify.post(endpoint, async (request, reply) => {
115
+ if (request.headers.origin && request.headers.origin !== resource.origin)
116
+ return reply.code(403).send({ error: 'Invalid origin' });
117
+ const authorization = request.headers.authorization;
118
+ let claims;
119
+ try {
120
+ if (!authorization?.startsWith('Bearer '))
121
+ throw new Error('Missing bearer token');
122
+ claims = await provider.verifyAccessToken(authorization.slice(7), initial.resource, ['read']);
123
+ }
124
+ catch {
125
+ return reply.header('WWW-Authenticate', 'Bearer resource_metadata="' + resource.origin + metadataPath + '"').code(401).send({ error: 'invalid_token' });
126
+ }
127
+ const repository = request.headers['x-agent-repository'];
128
+ if (repository !== undefined && typeof repository !== 'string')
129
+ return reply.code(400).send({ error: 'Invalid X-Agent-Repository' });
130
+ const current = policy();
131
+ const user = current.users.find((u) => u.subject === claims.sub && !u.disabled);
132
+ const client = current.clients.find((c) => c.id === claims.client_id);
133
+ if (!user || !client || (user.kind === 'service' ? client.kind !== 'service' || client.subject !== user.subject : client.kind === 'service'))
134
+ return reply.code(403).send({ error: 'Identity access denied' });
135
+ const catalog = () => (0, repository_discovery_1.remoteRepositoryCatalog)(policy(), claims.sub, claims.client_id, claims.scope.split(' '));
136
+ let store;
137
+ let server;
138
+ if (repository === undefined) {
139
+ server = (0, repository_discovery_1.createRepositoryDiscoveryServer)(catalog);
140
+ }
141
+ else {
142
+ const permissions = (0, remote_policy_1.repositoryPermissions)(current, claims.sub, claims.client_id, claims.scope.split(' '), repository);
143
+ if (!permissions.has('read'))
144
+ return reply.code(403).send({ error: 'Repository access denied' });
145
+ const repo = initial.repositories.find((item) => item.id === repository);
146
+ store = new store_1.BrainStore(repo.configRoot, repo.cwd);
147
+ if ((repo.group && store.profile !== 'projects/' + repo.id) || (initial.dataRoot && store.pool !== repo.group)) {
148
+ store.close();
149
+ return reply.code(503).send({ error: 'Repository profile changed; restore its registration before continuing' });
150
+ }
151
+ const canWriteScope = (scope) => {
152
+ const scopes = claims.scope.split(' ');
153
+ if (scope === 'project')
154
+ return permissions.has('write');
155
+ if (scope === 'global')
156
+ return scopes.includes('repo:*') && (0, remote_policy_1.allowedGrant)(policy(), claims.sub, claims.client_id, ['read', 'write', 'repo:*']);
157
+ return !!repo.group && initial.repositories.filter(member => member.group === repo.group).every(member => (0, remote_policy_1.repositoryPermissions)(policy(), claims.sub, claims.client_id, scopes, member.id).has('write'));
158
+ };
159
+ server = (0, server_1.createBrainServer)(store, { sync: async (message) => {
160
+ if (!initial.gitSync || !initial.dataRoot)
161
+ throw new Error('Brain Git synchronization is not configured; changes remain on the server.');
162
+ const scopes = ['projects/' + repository];
163
+ if (repo.group && canWriteScope('pool'))
164
+ scopes.push('pools/' + repo.group);
165
+ if (canWriteScope('global'))
166
+ scopes.push('global');
167
+ return new Promise((resolve, reject) => {
168
+ const child = (0, node_child_process_1.execFile)(process.execPath, [path.resolve(__dirname, '../../ops/config-sync.cjs')], { timeout: 180000, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {
169
+ if (error)
170
+ reject(new Error(stderr.trim() || error.message));
171
+ else {
172
+ try {
173
+ resolve(JSON.parse(stdout));
174
+ }
175
+ catch {
176
+ reject(new Error('Invalid Brain sync response'));
177
+ }
178
+ }
179
+ });
180
+ child.stdin?.end(JSON.stringify({ ...initial.gitSync, dataRoot: initial.dataRoot, scopes, reviews: permissions.has('review'), message }));
181
+ });
182
+ }, repository, group: repo.group, repositories: catalog, allowScopeWrite: (scope) => {
183
+ if (!initial.dataRoot || scope === 'project')
184
+ return true;
185
+ const scopes = claims.scope.split(' ');
186
+ if (scope === 'global')
187
+ return scopes.includes('repo:*') && (0, remote_policy_1.allowedGrant)(policy(), claims.sub, claims.client_id, ['read', 'write', 'repo:*']);
188
+ return scope === 'pool' && initial.repositories.filter((member) => member.group === repo.group).every((member) => (0, remote_policy_1.repositoryPermissions)(policy(), claims.sub, claims.client_id, scopes, member.id).has('write'));
189
+ }, allowTool: (name) => { const required = (0, remote_policy_1.toolPermission)(name); return required !== null && permissions.has(required); } });
190
+ }
191
+ const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
192
+ reply.hijack();
193
+ try {
194
+ await server.connect(transport);
195
+ await transport.handleRequest(request.raw, reply.raw, request.body);
196
+ }
197
+ finally {
198
+ await server.close();
199
+ store?.close();
200
+ }
201
+ });
202
+ api.fastify.route({ method: ['GET', 'DELETE'], url: endpoint, handler: async (_request, reply) => reply.code(405).send() });
203
+ return { api, provider, config: initial, close: () => api.fastify.close() };
204
+ }
205
+ async function serveRemote(configFile) {
206
+ const service = await createRemoteApi(configFile);
207
+ await service.api.fastify.listen(service.config.listen.socket ? { path: service.config.listen.socket } : { host: '127.0.0.1', port: service.config.listen.port });
208
+ if (service.config.listen.socket && process.platform !== 'win32')
209
+ fs.chmodSync(service.config.listen.socket, 0o600);
210
+ return service;
211
+ }
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.repositoryPattern = exports.repositoryId = void 0;
4
+ exports.matchesRepository = matchesRepository;
5
+ exports.coversPattern = coversPattern;
6
+ exports.githubRepository = githubRepository;
7
+ const zod_1 = require("zod");
8
+ exports.repositoryId = zod_1.z.string().max(200).regex(/^[a-zA-Z0-9][a-zA-Z0-9-]*\/[a-zA-Z0-9_.-]+$/)
9
+ .refine((value) => !['.', '..'].includes(value.split('/')[1])).transform((value) => value.toLowerCase());
10
+ exports.repositoryPattern = zod_1.z.string().refine((value) => value === '*' ||
11
+ (value.endsWith('/*') ? exports.repositoryId.safeParse(value.slice(0, -1) + 'repository').success : exports.repositoryId.safeParse(value).success), 'Use owner/repo, owner/* or *')
12
+ .transform((value) => value.toLowerCase());
13
+ function matchesRepository(pattern, repository) {
14
+ return pattern === '*' || pattern === repository || (pattern.endsWith('/*') && repository.startsWith(pattern.slice(0, -1)));
15
+ }
16
+ function coversPattern(allowed, requested) {
17
+ if (requested === '*')
18
+ return allowed === '*';
19
+ if (requested.endsWith('/*'))
20
+ return allowed === '*' || allowed === requested;
21
+ return matchesRepository(allowed, requested);
22
+ }
23
+ function githubRepository(remote) {
24
+ const match = /^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/)([^?#]+?)(?:\.git)?\/?$/.exec(remote);
25
+ if (!match)
26
+ throw new Error('Expected a GitHub repository remote');
27
+ return exports.repositoryId.parse(match[1]);
28
+ }
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.localRepositoryCatalog = localRepositoryCatalog;
4
+ exports.remoteRepositoryCatalog = remoteRepositoryCatalog;
5
+ exports.registerRepositoryTools = registerRepositoryTools;
6
+ exports.createRepositoryDiscoveryServer = createRepositoryDiscoveryServer;
7
+ const path = require("node:path");
8
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
9
+ const version_1 = require("../version");
10
+ const config_1 = require("./config");
11
+ const remote_policy_1 = require("./remote-policy");
12
+ const repositories_1 = require("./repositories");
13
+ function localRepositoryCatalog(configRoot) {
14
+ return (0, config_1.listBrainProjects)(configRoot).map((project) => ({
15
+ id: (project.repository?.url ? (0, repositories_1.githubRepository)(project.repository.url) : null) ?? project.name,
16
+ name: project.display_name ?? project.name, group: project.pool,
17
+ permissions: ['read', 'write', 'review'], configuration: 'project'
18
+ }));
19
+ }
20
+ /** Scan server-side profiles, but expose only registered repositories allowed by all three grants. */
21
+ function remoteRepositoryCatalog(config, subject, clientId, scopes) {
22
+ const projects = new Map();
23
+ return config.repositories.flatMap((repo) => {
24
+ const permissions = (0, remote_policy_1.repositoryPermissions)(config, subject, clientId, scopes, repo.id);
25
+ if (!permissions.has('read'))
26
+ return [];
27
+ let entries = projects.get(repo.configRoot);
28
+ try {
29
+ if (!entries) {
30
+ entries = (0, config_1.listBrainProjects)(repo.configRoot);
31
+ projects.set(repo.configRoot, entries);
32
+ }
33
+ const registration = (0, config_1.registeredBrainProject)(repo.configRoot, repo.cwd);
34
+ const project = entries.find((entry) => entry.profile === registration?.profile);
35
+ if ((repo.group && project?.name !== repo.id) || (config.dataRoot && project?.pool !== repo.group))
36
+ return [];
37
+ if (project && !project.roots.some((root) => path.resolve(root) === path.resolve(registration.root)))
38
+ return [];
39
+ return [{ id: repo.id, name: project?.display_name ?? repo.id, group: repo.group,
40
+ permissions: [...permissions].sort(), configuration: project ? 'project' : 'default' }];
41
+ }
42
+ catch {
43
+ throw new Error('Cannot read the configured repository catalog; ask the server administrator to check its project files');
44
+ }
45
+ }).sort((a, b) => a.id.localeCompare(b.id));
46
+ }
47
+ function registerRepositoryTools(server, catalog, allow = () => true) {
48
+ for (const name of ['list_repositories', 'list_repository_groups']) {
49
+ if (!allow(name))
50
+ continue;
51
+ server.registerTool(name, {
52
+ description: name === 'list_repositories'
53
+ ? 'List configured repositories accessible to this authenticated identity and token, with effective permissions. No filesystem paths or Git credentials are returned.'
54
+ : 'List repository groups containing repositories accessible to this identity and token. Hidden members and empty groups are omitted.',
55
+ inputSchema: {}, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }
56
+ }, async () => {
57
+ try {
58
+ const repositories = catalog();
59
+ const result = name === 'list_repositories' ? { repositories } : {
60
+ groups: [...new Set(repositories.flatMap((repo) => repo.group ? [repo.group] : []))].sort().map((id) => ({
61
+ id, repositories: repositories.filter((repo) => repo.group === id)
62
+ }))
63
+ };
64
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
65
+ }
66
+ catch (error) {
67
+ return { isError: true, content: [{ type: 'text', text: error instanceof Error ? error.message : 'Repository discovery failed' }] };
68
+ }
69
+ });
70
+ }
71
+ }
72
+ function createRepositoryDiscoveryServer(catalog) {
73
+ const server = new mcp_js_1.McpServer({ name: 'agent-brain', version: (0, version_1.packageVersion)() });
74
+ registerRepositoryTools(server, catalog);
75
+ return server;
76
+ }
@@ -0,0 +1,283 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultSocketPath = void 0;
4
+ exports.createBrainServer = createBrainServer;
5
+ exports.serveApiCore = serveApiCore;
6
+ exports.proxyStdio = proxyStdio;
7
+ const fs = require("node:fs");
8
+ const path = require("node:path");
9
+ const http = require("node:http");
10
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
11
+ const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
12
+ const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
13
+ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
14
+ const apicore_server_1 = require("@technomoron/apicore-server");
15
+ const zod_1 = require("zod");
16
+ const version_1 = require("../version");
17
+ const store_1 = require("./store");
18
+ const consolidation_1 = require("./consolidation");
19
+ const skills_1 = require("./skills");
20
+ const todos_1 = require("./todos");
21
+ const connectors_1 = require("./connectors");
22
+ const git_1 = require("./git");
23
+ const github_reviews_1 = require("./github-reviews");
24
+ const windows_pipe_1 = require("./windows-pipe");
25
+ const repository_discovery_1 = require("./repository-discovery");
26
+ var config_1 = require("./config");
27
+ Object.defineProperty(exports, "defaultSocketPath", { enumerable: true, get: function () { return config_1.defaultSocketPath; } });
28
+ function createBrainServer(store, options = {}) {
29
+ const github = (0, github_reviews_1.githubReviews)(store);
30
+ if (github && options.repository && github.repository !== options.repository)
31
+ throw new Error('Review backend repository does not match the authenticated repository');
32
+ const server = new mcp_js_1.McpServer({ name: 'agent-brain', version: (0, version_1.packageVersion)() });
33
+ (0, repository_discovery_1.registerRepositoryTools)(server, options.repositories ?? (() => (0, repository_discovery_1.localRepositoryCatalog)(store.configRoot)), options.allowTool);
34
+ function tool(name, description, shape, readOnly, handler) {
35
+ if (options.allowTool && !options.allowTool(name))
36
+ return;
37
+ const schema = zod_1.z.object(shape).strict();
38
+ server.registerTool(name, { description, inputSchema: schema, annotations: { readOnlyHint: readOnly, destructiveHint: false, openWorldHint: false } }, async (input) => {
39
+ store.knowledgeErrors.length = 0;
40
+ store.todoErrors.length = 0;
41
+ try {
42
+ if (!readOnly && options.allowScopeWrite) {
43
+ const data = input;
44
+ const scopes = [data.scope, ...((['amend_knowledge', 'promote', 'deprecate_knowledge'].includes(name) || (!github && ['resolve_review', 'review_update'].includes(name))) && data.id ? [store.get(data.id).scope] : [])].filter(Boolean);
45
+ if (scopes.some((scope) => !options.allowScopeWrite(scope)))
46
+ throw new Error('Write access to the entire target scope is required');
47
+ }
48
+ if (!readOnly && options.allowTool && !options.allowTool('review_update')) {
49
+ const data = input;
50
+ if (data.type === 'review' || (data.id && ['amend_knowledge', 'promote', 'deprecate_knowledge'].includes(name) && store.get(data.id).type === 'review')) {
51
+ throw new Error('Review permission is required to change findings');
52
+ }
53
+ }
54
+ const result = await handler(zod_1.z.object(shape).strict().parse(input));
55
+ return { content: [{ type: 'text', text: JSON.stringify(store.withDiagnostics(result)) }] };
56
+ }
57
+ catch (error) {
58
+ return { isError: true, content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }] };
59
+ }
60
+ });
61
+ }
62
+ const id = zod_1.z.string().min(1).max(200);
63
+ const revision = zod_1.z.string().regex(/^[a-f0-9]{64}$/);
64
+ tool('brain_status', 'Show the active project and available scopes. Global is server-wide; pool is shared only by members of the active pool.', {}, true, () => ({ profile: store.profile, pool: store.pool, scopes: store.scopes.map((entry) => entry.scope), reviewBackend: github ? 'github' : 'internal', repository: github?.repository ?? options.repository, group: options.group }));
65
+ tool('sync_status', 'Preview Git state and the canonical files eligible for saving. Runtime files, indexes, credentials, and native agent state are excluded.', {}, true, () => (0, git_1.gitPreview)(store));
66
+ for (const name of ['brain_sync', 'brain_flush', 'sync', 'flush']) {
67
+ if (options.allowTool && !options.allowTool(name))
68
+ continue;
69
+ server.registerTool(name, { description: 'When the user explicitly asks "brain sync" or "brain flush", commit and push canonical Brain changes to its configuration repository. Messages are generated. Report errors and unsynced changes to the user. This does not commit project source code.',
70
+ inputSchema: { action: zod_1.z.enum(['init', 'save', 'pull', 'push', 'sync']).default('sync'), confirmed: zod_1.z.literal(true).optional(), message: zod_1.z.string().min(1).max(1000).optional() },
71
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
72
+ }, async ({ action, message }) => {
73
+ try {
74
+ if (options.sync && !['save', 'sync'].includes(action))
75
+ throw new Error('Remote Brain supports sync/save/flush only.');
76
+ const result = options.sync ? await options.sync(message) : (0, git_1.syncGit)(store, action, message);
77
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
78
+ }
79
+ catch (error) {
80
+ return { isError: true, content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }] };
81
+ }
82
+ });
83
+ }
84
+ tool('get_context', 'Retrieve relevant constraints and knowledge before substantial work. Check omitted; explicitly fetch required knowledge if the budget excluded it.', {
85
+ task: zod_1.z.string().max(10000), files: zod_1.z.array(zod_1.z.string()).max(100).optional(), symbols: zod_1.z.array(zod_1.z.string()).max(100).optional()
86
+ }, false, ({ task, files, symbols }) => store.context(task, files, symbols));
87
+ tool('search_knowledge', 'Search Markdown knowledge in the active scopes using SQLite FTS.', {
88
+ query: zod_1.z.string().max(10000), scopes: zod_1.z.array(store_1.scopeSchema).optional(), types: zod_1.z.array(store_1.typeSchema).optional(),
89
+ includeDeprecated: zod_1.z.boolean().optional(), limit: zod_1.z.number().int().min(1).max(100).optional()
90
+ }, false, ({ query, ...options }) => store.search(query, options));
91
+ tool('list_knowledge', 'Inventory knowledge metadata with scope/type filters and pagination. Includes the context budget; read full records before consolidation.', consolidation_1.inventoryOptions.shape, true, (input) => (0, consolidation_1.listKnowledge)(store, input));
92
+ tool('knowledge_history', 'Look up archived knowledge and replacement IDs. Pass an old id to retrieve its exact original file text. Excluded from normal retrieval.', consolidation_1.historyOptions.shape, true, (input) => (0, consolidation_1.knowledgeHistory)(store, input));
93
+ tool('archive_knowledge', 'After authorized consolidation and verified coverage, archive exact source files and replacement references before removing the files. Same scope and authority only; revisions are required for sources and replacements. Identical retries finish interrupted deletion.', consolidation_1.archiveInput.shape, false, (input) => (0, consolidation_1.archiveKnowledge)(store, input));
94
+ tool('get_knowledge', 'Read a complete knowledge item and its current revision.', { id }, true, ({ id }) => store.get(id));
95
+ tool('remember', 'Persist durable knowledge when authorized by the user. Choose scope and a singular type; the server stores it in the matching directory (for example constraint in constraints/, preference in preferences/). Explicit user instructions have authority=user; deductions remain inferred observations. Global writes require explicit global intent. Use todo tools for tasks; skills and templates are separate files.', store_1.knowledgeInput.shape, false, (input) => { if (github && input.type === 'review')
96
+ throw new Error('Use review_create for the configured GitHub review backend'); return store.remember(input); });
97
+ tool('amend_knowledge', 'Revise an active item in place using its last-read revision, keeping its id, file name, scope, type, authority, and history. Use this to correct or extend existing knowledge instead of writing a near-duplicate. Scope, type, authority, and review severity cannot be changed this way.', {
98
+ id, revision, changes: store_1.knowledgeChanges
99
+ }, false, ({ id, revision, changes }) => store.amend(id, revision, changes));
100
+ tool('promote', 'Copy active knowledge to another available scope with user authority. Requires explicit user approval; the original is preserved.', {
101
+ id, scope: store_1.scopeSchema, revision, confirmed: zod_1.z.literal(true)
102
+ }, false, ({ id, scope, revision }) => store.promote(id, scope, revision));
103
+ tool('deprecate_knowledge', 'Deprecate outdated knowledge without deleting its history.', { id, revision, reason: zod_1.z.string().max(2000).optional() }, false, ({ id, revision, reason }) => store.deprecate(id, revision, reason));
104
+ tool('list_skills', 'List available skills and descriptions. Local skills override global skills with the same name.', {}, true, () => (0, skills_1.listSkills)(store));
105
+ tool('get_skill', 'Load a full skill only when it applies to the current task.', { name: zod_1.z.string().max(100) }, true, ({ name }) => (0, skills_1.getSkill)(store, name));
106
+ tool('review_context', 'Retrieve constraints, decisions, prior review findings, and path-specific knowledge for a code review.', {
107
+ task: zod_1.z.string().max(10000), files: zod_1.z.array(zod_1.z.string()).max(100).optional()
108
+ }, false, ({ task, files }) => store.context(`review constraint decision ${task}`, files));
109
+ tool('review_get', 'Read a finding from the configured internal or per-repository GitHub backend.', { id }, true, ({ id }) => github ? github.get(id) : store.get(id));
110
+ tool('review_create', 'Record an authorized review finding in the configured backend. GitHub requires enabled writes and explicit confirmation; key deduplicates retries.', github_reviews_1.reviewInput.shape, false, (input) => github ? github.create(input) : store.remember({ scope: store.profile ? 'project' : 'default', type: 'review', authority: 'inferred', title: input.title, content: input.content, severity: input.severity, applies_to: input.applies_to }));
111
+ tool('review_update', 'Revise a finding using its last-read revision. GitHub preserves text outside its managed block.', {
112
+ id, revision, confirmed: zod_1.z.literal(true), changes: zod_1.z.object({ title: zod_1.z.string().min(1).max(250).optional(), content: zod_1.z.string().min(1).max(40000).optional(), severity: store_1.severitySchema.optional(), applies_to: zod_1.z.array(zod_1.z.string().max(500)).max(100).optional() }).strict()
113
+ }, false, ({ id, revision, changes }) => {
114
+ if (github)
115
+ return github.update(id, revision, changes);
116
+ if (changes.severity)
117
+ throw new Error('Internal finding severity changes require the existing review workflow');
118
+ return store.amend(id, revision, changes);
119
+ });
120
+ tool('review_list', 'List open findings from the configured backend. GitHub issues belong to this repository; PRs are excluded.', {
121
+ severity: zod_1.z.array(store_1.severitySchema).optional(), state: zod_1.z.array(store_1.reviewStateSchema).optional()
122
+ }, true, async ({ severity, state }) => {
123
+ if (github)
124
+ return (await github.list(state ? 'all' : 'open')).filter((item) => (!severity || severity.includes(item.severity)) && (!state || state.includes(item.state)));
125
+ return store.reviews({ severity, state }).map((item) => ({ finding: item.finding, severity: item.severity, state: item.state ?? 'open', title: item.title, applies_to: item.applies_to, id: item.id, revision: item.revision }));
126
+ });
127
+ tool('review_history', 'Recall closed findings from the configured backend, with pagination.', {
128
+ scope: store_1.scopeSchema.optional(), query: zod_1.z.string().max(1000).optional(), state: zod_1.z.enum(['fixed', 'wontfix']).optional(),
129
+ offset: zod_1.z.number().int().min(0).optional(), limit: zod_1.z.number().int().min(1).max(1000).optional()
130
+ }, true, async (options) => {
131
+ if (!github)
132
+ return store.reviewHistory(options);
133
+ const items = (await github.list('closed')).filter((item) => (!options.state || item.state === options.state) && (!options.query || JSON.stringify(item).toLowerCase().includes(options.query.toLowerCase())));
134
+ return { total: items.length, items: items.slice(options.offset ?? 0, (options.offset ?? 0) + (options.limit ?? 50)) };
135
+ });
136
+ tool('review_archive', 'Compact internal closed finding files. GitHub retains its own issue history.', { scope: store_1.scopeSchema }, false, ({ scope }) => { if (github)
137
+ throw new Error('GitHub owns review history; no internal archive is needed'); return store.archiveReviews(scope); });
138
+ tool('resolve_review', 'Close an authorized fix or explicitly dropped finding in the configured backend. GitHub writes must be enabled. Deferred findings stay open.', {
139
+ id, revision, state: zod_1.z.enum(['fixed', 'wontfix']), reason: zod_1.z.string().min(1).max(2000).optional()
140
+ }, false, ({ id, revision, state, reason }) => github ? github.resolve(id, revision, state, reason ?? state) : store.resolveReview(id, revision, state, reason));
141
+ tool('todo_list', 'List structured tasks in the active scopes.', { status: todos_1.todoInput.shape.status.optional() }, true, ({ status }) => (0, todos_1.listTodos)(store).filter((item) => !status || item.status === status));
142
+ tool('todo_get', 'Read a task and its revision.', { id }, true, ({ id }) => (0, todos_1.getTodo)(store, id));
143
+ tool('todo_add', 'Create a local task. Reimporting the same external task returns the existing task.', todos_1.todoInput.shape, false, (input) => (0, todos_1.addTodo)(store, input));
144
+ tool('todo_update', 'Update a local task using its last-read revision. Does not change remote tasks.', { id, revision, changes: todos_1.todoChanges }, false, ({ id, revision, changes }) => (0, todos_1.updateTodo)(store, id, revision, changes));
145
+ tool('todo_complete', 'Mark a local task done. Does not change remote tasks.', { id, revision }, false, ({ id, revision }) => (0, todos_1.updateTodo)(store, id, revision, { status: 'done' }));
146
+ for (const name of ['todo_import', 'todo_sync']) {
147
+ if (options.allowTool && !options.allowTool(name))
148
+ continue;
149
+ server.registerTool(name, { description: 'Import tasks from a configured connector. Merge remote changes only when they do not conflict with local edits; report conflicting task IDs. Remote tasks are never modified.',
150
+ inputSchema: { source: zod_1.z.string().max(100), scope: store_1.scopeSchema }, annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
151
+ }, async ({ source, scope }) => {
152
+ try {
153
+ return { content: [{ type: 'text', text: JSON.stringify(await (0, connectors_1.syncConnector)(store, source, scope)) }] };
154
+ }
155
+ catch (error) {
156
+ return { isError: true, content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }] };
157
+ }
158
+ });
159
+ }
160
+ return server;
161
+ }
162
+ function requirePrivateSocketDirectory(socketPath) {
163
+ const stat = fs.lstatSync(path.dirname(socketPath));
164
+ if (!stat.isDirectory() || stat.uid !== process.getuid() || (stat.mode & 0o077) !== 0)
165
+ throw new Error(`The socket directory ${path.dirname(socketPath)} must be owned by the current user with mode 0700 (current uid ${process.getuid()}, owner uid ${stat.uid}, mode ${(stat.mode & 0o777).toString(8)}). Run agent-run and agent-brain as the same user.`);
166
+ }
167
+ async function serveApiCore(configRoot, socketPath) {
168
+ if (process.platform !== 'win32') {
169
+ const directory = path.dirname(socketPath);
170
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
171
+ requirePrivateSocketDirectory(socketPath);
172
+ if (fs.existsSync(socketPath))
173
+ throw new Error(`Socket already exists: ${socketPath}. Stop the running service, or remove the socket after confirming it is stale.`);
174
+ }
175
+ else if (!/^\\\\\.\\pipe\\[a-zA-Z0-9._-]+$/.test(socketPath)) {
176
+ throw new Error('On Windows, --socket must be a local named pipe (\\\\.\\pipe\\name).');
177
+ }
178
+ let ready = false;
179
+ const api = new apicore_server_1.ApiServer({ authApi: false, origins: [], devMode: false });
180
+ api.fastify.post('/mcp', async (request, reply) => {
181
+ if (!ready)
182
+ return reply.code(503).send();
183
+ if (request.headers.origin)
184
+ return reply.code(403).send({ error: 'Browser requests are not supported' });
185
+ if (request.headers['x-agent-brain-root'] !== encodeURIComponent(path.resolve(configRoot)))
186
+ return reply.code(409).send({ error: 'This service uses a different configuration directory' });
187
+ const cwdHeader = request.headers['x-agent-brain-cwd'];
188
+ if (typeof cwdHeader !== 'string')
189
+ return reply.code(400).send({ error: 'Missing project directory' });
190
+ let cwd;
191
+ try {
192
+ cwd = decodeURIComponent(cwdHeader);
193
+ }
194
+ catch {
195
+ return reply.code(400).send({ error: 'Invalid project directory' });
196
+ }
197
+ if (!path.isAbsolute(cwd) || !fs.statSync(cwd, { throwIfNoEntry: false })?.isDirectory())
198
+ return reply.code(400).send({ error: 'Invalid project directory' });
199
+ const store = new store_1.BrainStore(configRoot, cwd);
200
+ const server = createBrainServer(store);
201
+ const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
202
+ reply.hijack();
203
+ try {
204
+ await server.connect(transport);
205
+ await transport.handleRequest(request.raw, reply.raw, request.body);
206
+ }
207
+ finally {
208
+ await server.close();
209
+ store.close();
210
+ }
211
+ });
212
+ api.fastify.route({ method: ['GET', 'DELETE'], url: '/mcp', handler: async (_request, reply) => reply.code(405).send() });
213
+ await api.fastify.listen({ path: socketPath });
214
+ try {
215
+ if (process.platform === 'win32')
216
+ await (0, windows_pipe_1.checkWindowsPipe)(socketPath, true);
217
+ else
218
+ fs.chmodSync(socketPath, 0o600);
219
+ ready = true;
220
+ }
221
+ catch (error) {
222
+ await api.fastify.close();
223
+ throw error;
224
+ }
225
+ return { close: () => api.fastify.close() };
226
+ }
227
+ async function proxyStdio(socketPath, cwd, configRoot) {
228
+ if (process.platform === 'win32') {
229
+ try {
230
+ await (0, windows_pipe_1.checkWindowsPipe)(socketPath);
231
+ }
232
+ catch (error) {
233
+ throw new Error(`Agent-brain service is not running or its pipe is not private at ${socketPath}. Start agent-brain serve with the same --configdir and --socket. ${String(error)}`);
234
+ }
235
+ }
236
+ else {
237
+ const socket = fs.lstatSync(socketPath, { throwIfNoEntry: false });
238
+ if (!socket)
239
+ throw new Error(`Agent-brain service is not running at ${socketPath}. Start agent-brain serve with the same --configdir and --socket, or enable its systemd user service.`);
240
+ requirePrivateSocketDirectory(socketPath);
241
+ if (!socket.isSocket() || socket.uid !== process.getuid() || (socket.mode & 0o077) !== 0)
242
+ throw new Error('The brain socket must belong to the current user with mode 0600.');
243
+ }
244
+ const stdio = new stdio_js_1.StdioServerTransport();
245
+ let protocolVersion;
246
+ async function send(message) {
247
+ const response = await new Promise((resolve, reject) => {
248
+ const request = http.request({ socketPath, path: '/mcp', method: 'POST', headers: {
249
+ 'content-type': 'application/json', accept: 'application/json, text/event-stream',
250
+ 'x-agent-brain-cwd': encodeURIComponent(cwd), 'x-agent-brain-root': encodeURIComponent(path.resolve(configRoot)),
251
+ ...(protocolVersion ? { 'mcp-protocol-version': protocolVersion } : {})
252
+ } }, (response) => {
253
+ const chunks = [];
254
+ let bytes = 0;
255
+ response.on('data', (chunk) => { bytes += chunk.length; if (bytes > 4 * 1024 * 1024)
256
+ response.destroy(new Error('Brain response exceeds 4 MiB'));
257
+ else
258
+ chunks.push(chunk); });
259
+ response.on('error', reject);
260
+ response.on('end', () => response.statusCode && response.statusCode >= 200 && response.statusCode < 300
261
+ ? resolve(Buffer.concat(chunks).toString('utf8')) : reject(new Error(`Brain service returned HTTP ${response.statusCode}`)));
262
+ });
263
+ request.setTimeout(30000, () => request.destroy(new Error('Brain service request timed out')));
264
+ request.on('error', reject);
265
+ request.end(JSON.stringify(message));
266
+ });
267
+ if (response) {
268
+ const parsed = types_js_1.JSONRPCMessageSchema.parse(JSON.parse(response));
269
+ if ('result' in parsed && typeof parsed.result.protocolVersion === 'string')
270
+ protocolVersion = parsed.result.protocolVersion;
271
+ await stdio.send(parsed);
272
+ }
273
+ }
274
+ stdio.onmessage = (message) => {
275
+ void send(message).catch(async (error) => {
276
+ if ('id' in message && 'method' in message)
277
+ await stdio.send({ jsonrpc: '2.0', id: message.id, error: { code: -32603, message: error instanceof Error ? error.message : String(error) } });
278
+ else
279
+ process.stderr.write(`${String(error)}\n`);
280
+ });
281
+ };
282
+ await stdio.start();
283
+ }