@sontoriyama/mcp-code-mode 0.0.0-stage → 0.4.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/CHANGELOG.md +148 -0
- package/LICENSE +21 -0
- package/README.md +207 -3
- package/SKILL.md +42 -0
- package/docs/pig.md +131 -0
- package/examples/codemode.tools.json +23 -0
- package/examples/pr-status.program.mjs +64 -0
- package/package.json +60 -6
- package/skills/pig/SKILL.md +48 -0
- package/src/core.mjs +135 -0
- package/src/executor.mjs +447 -0
- package/src/manifest.mjs +154 -0
- package/src/mcp-client.mjs +891 -0
- package/src/mcp-server.mjs +593 -0
- package/src/plugins/engram.mjs +32 -0
- package/src/plugins/gh.mjs +83 -0
- package/src/run.mjs +347 -0
- package/src/tools.mjs +136 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// Optional GitHub CLI (gh) read-only plugin.
|
|
2
|
+
import {
|
|
3
|
+
assertFields,
|
|
4
|
+
assertPositiveInt,
|
|
5
|
+
assertRepo,
|
|
6
|
+
execJson,
|
|
7
|
+
SAFE_TOKEN_RE,
|
|
8
|
+
ToolCallError,
|
|
9
|
+
} from '../core.mjs';
|
|
10
|
+
|
|
11
|
+
const ALLOWED_PR_STATES = new Set(['open', 'closed', 'merged', 'all']);
|
|
12
|
+
|
|
13
|
+
export const PR_FIELDS = [
|
|
14
|
+
'number', 'state', 'isDraft', 'reviewDecision', 'mergeable', 'mergeStateStatus',
|
|
15
|
+
'createdAt', 'updatedAt', 'labels', 'reviews', 'comments',
|
|
16
|
+
'statusCheckRollup', 'reviewRequests',
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
export const ISSUE_FIELDS = ['number', 'state', 'labels', 'createdAt', 'updatedAt', 'comments'];
|
|
20
|
+
|
|
21
|
+
export const gh = {
|
|
22
|
+
async prStatus({ repo, number, fields = PR_FIELDS } = {}, opts) {
|
|
23
|
+
const signal = opts?.signal;
|
|
24
|
+
const validRepo = assertRepo('gh.prStatus', repo);
|
|
25
|
+
const validNumber = assertPositiveInt('gh.prStatus', 'number', number);
|
|
26
|
+
const validFields = assertFields('gh.prStatus', fields);
|
|
27
|
+
return execJson('gh.prStatus', 'gh', [
|
|
28
|
+
'pr', 'view', String(validNumber), '-R', validRepo, '--json', validFields.join(','),
|
|
29
|
+
], { signal });
|
|
30
|
+
},
|
|
31
|
+
|
|
32
|
+
async issueStatus({ repo, number, fields = ISSUE_FIELDS } = {}, opts) {
|
|
33
|
+
const signal = opts?.signal;
|
|
34
|
+
const validRepo = assertRepo('gh.issueStatus', repo);
|
|
35
|
+
const validNumber = assertPositiveInt('gh.issueStatus', 'number', number);
|
|
36
|
+
const validFields = assertFields('gh.issueStatus', fields);
|
|
37
|
+
return execJson('gh.issueStatus', 'gh', [
|
|
38
|
+
'issue', 'view', String(validNumber), '-R', validRepo, '--json', validFields.join(','),
|
|
39
|
+
], { signal });
|
|
40
|
+
},
|
|
41
|
+
|
|
42
|
+
async searchPRs({ author, state = 'open', limit = 50 } = {}, opts) {
|
|
43
|
+
const signal = opts?.signal;
|
|
44
|
+
if (typeof author !== 'string' || (author !== '@me' && !SAFE_TOKEN_RE.test(author))) {
|
|
45
|
+
throw new ToolCallError('gh.searchPRs', 'author must be @me or a valid non-flag username');
|
|
46
|
+
}
|
|
47
|
+
if (!ALLOWED_PR_STATES.has(state)) {
|
|
48
|
+
throw new ToolCallError('gh.searchPRs', 'state must be one of: open, closed, merged, all');
|
|
49
|
+
}
|
|
50
|
+
const validLimit = assertPositiveInt('gh.searchPRs', 'limit', limit);
|
|
51
|
+
const args = [
|
|
52
|
+
'search', 'prs', '--author', author, '--limit', String(validLimit),
|
|
53
|
+
'--json', 'repository,number,title,state,closedAt,url',
|
|
54
|
+
];
|
|
55
|
+
if (state === 'merged') args.push('--merged');
|
|
56
|
+
else if (state !== 'all') args.push('--state', state);
|
|
57
|
+
return execJson('gh.searchPRs', 'gh', args, { signal });
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
export const ghCatalog = [
|
|
62
|
+
{
|
|
63
|
+
name: 'gh.prStatus',
|
|
64
|
+
source: 'plugin:gh',
|
|
65
|
+
description: 'Fetch GitHub PR status, reviews, comments, and CI rollup via gh CLI',
|
|
66
|
+
params: { repo: 'owner/name (required)', number: 'positive int (required)', fields: 'string[] (optional)' },
|
|
67
|
+
parse: 'json',
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
name: 'gh.issueStatus',
|
|
71
|
+
source: 'plugin:gh',
|
|
72
|
+
description: 'Fetch GitHub issue status, labels, and comments via gh CLI',
|
|
73
|
+
params: { repo: 'owner/name (required)', number: 'positive int (required)', fields: 'string[] (optional)' },
|
|
74
|
+
parse: 'json',
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
name: 'gh.searchPRs',
|
|
78
|
+
source: 'plugin:gh',
|
|
79
|
+
description: 'Search GitHub PRs by author and state via gh CLI',
|
|
80
|
+
params: { author: '@me or username (required)', state: 'open|closed|merged|all', limit: 'positive int' },
|
|
81
|
+
parse: 'json',
|
|
82
|
+
},
|
|
83
|
+
];
|
package/src/run.mjs
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Local code-mode runner: one fresh Node process per program or inline snippet.
|
|
3
|
+
// Supports file mode (<program.mjs>), inline mode (--code / -e), stdin (- / --stdin),
|
|
4
|
+
// progressive discovery (--list-tools) and MCP server mode (--serve-mcp).
|
|
5
|
+
// Only the program's returned value and console.log output are captured into the envelope.
|
|
6
|
+
// Full output is spilled to CODEMODE_OUT_DIR (default: .agent/out/).
|
|
7
|
+
// NOTE: This is a workflow/output-bounding runner, NOT a security sandbox.
|
|
8
|
+
import { readFileSync, realpathSync } from 'node:fs';
|
|
9
|
+
import { basename, resolve } from 'node:path';
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
11
|
+
import { runMcpServer } from './mcp-server.mjs';
|
|
12
|
+
import { createMcpBridge, loadMcpConfig, parseMcpInlineSpec } from './mcp-client.mjs';
|
|
13
|
+
import { createRegistry } from './tools.mjs';
|
|
14
|
+
import {
|
|
15
|
+
boundOutput,
|
|
16
|
+
createSpillHelper,
|
|
17
|
+
DEFAULT_MAX_CHARS,
|
|
18
|
+
executeProgram,
|
|
19
|
+
parseMaxChars,
|
|
20
|
+
safeJsonStringify,
|
|
21
|
+
} from './executor.mjs';
|
|
22
|
+
|
|
23
|
+
export { boundOutput, createSpillHelper, DEFAULT_MAX_CHARS, executeProgram, parseMaxChars, safeJsonStringify };
|
|
24
|
+
|
|
25
|
+
export const DEFAULT_MAX_STDIN_BYTES = 1024 * 1024;
|
|
26
|
+
export const DEFAULT_MCP_TIMEOUT_MS = 120000;
|
|
27
|
+
|
|
28
|
+
export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
29
|
+
|
|
30
|
+
export function parseMaxStdinBytes(raw = process.env.CODEMODE_MAX_STDIN_BYTES) {
|
|
31
|
+
if (raw === undefined || raw === null || String(raw).trim() === '') {
|
|
32
|
+
return DEFAULT_MAX_STDIN_BYTES;
|
|
33
|
+
}
|
|
34
|
+
const n = Number(raw);
|
|
35
|
+
return Number.isFinite(n) && n >= 1 ? Math.floor(n) : DEFAULT_MAX_STDIN_BYTES;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function parseCliArgs(argv, env = process.env) {
|
|
39
|
+
const opts = {
|
|
40
|
+
mode: null, // 'file' | 'code' | 'stdin' | 'list-tools' | 'serve-mcp'
|
|
41
|
+
programPath: null,
|
|
42
|
+
code: null,
|
|
43
|
+
argsJson: undefined,
|
|
44
|
+
manifestPath: env.CODEMODE_MANIFEST || null,
|
|
45
|
+
mcpConfigPath: env.CODEMODE_MCP_CONFIG || null,
|
|
46
|
+
mcpSpecs: [],
|
|
47
|
+
plugins: env.CODEMODE_PLUGINS
|
|
48
|
+
? env.CODEMODE_PLUGINS.split(',').map((s) => s.trim()).filter(Boolean)
|
|
49
|
+
: ['gh', 'engram'],
|
|
50
|
+
pluginsExplicit: Boolean(env.CODEMODE_PLUGINS),
|
|
51
|
+
listFilter: null,
|
|
52
|
+
allowTools: null,
|
|
53
|
+
timeoutMs: DEFAULT_MCP_TIMEOUT_MS,
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const positional = [];
|
|
57
|
+
for (let i = 0; i < argv.length; i++) {
|
|
58
|
+
const arg = argv[i];
|
|
59
|
+
if (arg === '--code' || arg === '-e') {
|
|
60
|
+
if (i + 1 >= argv.length) throw new Error(`${arg} requires a code string`);
|
|
61
|
+
opts.mode = 'code';
|
|
62
|
+
opts.code = argv[++i];
|
|
63
|
+
} else if (arg.startsWith('--code=')) {
|
|
64
|
+
opts.mode = 'code';
|
|
65
|
+
opts.code = arg.slice('--code='.length);
|
|
66
|
+
} else if (arg === '--stdin' || (arg === '-' && opts.mode === null && positional.length === 0)) {
|
|
67
|
+
opts.mode = 'stdin';
|
|
68
|
+
} else if (arg === '--manifest') {
|
|
69
|
+
if (i + 1 >= argv.length) throw new Error('--manifest requires a file path');
|
|
70
|
+
opts.manifestPath = argv[++i];
|
|
71
|
+
} else if (arg.startsWith('--manifest=')) {
|
|
72
|
+
opts.manifestPath = arg.slice('--manifest='.length);
|
|
73
|
+
} else if (arg === '--mcp-config') {
|
|
74
|
+
if (i + 1 >= argv.length) throw new Error('--mcp-config requires a file path');
|
|
75
|
+
opts.mcpConfigPath = argv[++i];
|
|
76
|
+
} else if (arg.startsWith('--mcp-config=')) {
|
|
77
|
+
opts.mcpConfigPath = arg.slice('--mcp-config='.length);
|
|
78
|
+
} else if (arg === '--mcp') {
|
|
79
|
+
if (i + 1 >= argv.length) throw new Error('--mcp requires "alias=command [args...]"');
|
|
80
|
+
opts.mcpSpecs.push(argv[++i]);
|
|
81
|
+
} else if (arg.startsWith('--mcp=')) {
|
|
82
|
+
opts.mcpSpecs.push(arg.slice('--mcp='.length));
|
|
83
|
+
} else if (arg === '--plugins') {
|
|
84
|
+
if (i + 1 >= argv.length) throw new Error('--plugins requires a comma-separated list');
|
|
85
|
+
opts.plugins = argv[++i].split(',').map((s) => s.trim()).filter(Boolean);
|
|
86
|
+
opts.pluginsExplicit = true;
|
|
87
|
+
} else if (arg.startsWith('--plugins=')) {
|
|
88
|
+
opts.plugins = arg.slice('--plugins='.length).split(',').map((s) => s.trim()).filter(Boolean);
|
|
89
|
+
opts.pluginsExplicit = true;
|
|
90
|
+
} else if (arg === '--no-default-plugins') {
|
|
91
|
+
opts.plugins = [];
|
|
92
|
+
opts.pluginsExplicit = true;
|
|
93
|
+
} else if (arg === '--serve-mcp') {
|
|
94
|
+
opts.mode = 'serve-mcp';
|
|
95
|
+
} else if (arg === '--allow-tools') {
|
|
96
|
+
if (i + 1 >= argv.length) throw new Error('--allow-tools requires a comma-separated list');
|
|
97
|
+
opts.allowTools = argv[++i].split(',').map((s) => s.trim()).filter(Boolean);
|
|
98
|
+
} else if (arg.startsWith('--allow-tools=')) {
|
|
99
|
+
opts.allowTools = arg.slice('--allow-tools='.length).split(',').map((s) => s.trim()).filter(Boolean);
|
|
100
|
+
} else if (arg === '--timeout-ms') {
|
|
101
|
+
if (i + 1 >= argv.length) throw new Error('--timeout-ms requires a positive integer');
|
|
102
|
+
opts.timeoutMs = parsePositiveIntFlag('--timeout-ms', argv[++i]);
|
|
103
|
+
} else if (arg.startsWith('--timeout-ms=')) {
|
|
104
|
+
opts.timeoutMs = parsePositiveIntFlag('--timeout-ms', arg.slice('--timeout-ms='.length));
|
|
105
|
+
} else if (arg === '--list-tools') {
|
|
106
|
+
opts.mode = 'list-tools';
|
|
107
|
+
if (i + 1 < argv.length && !argv[i + 1].startsWith('-')) {
|
|
108
|
+
opts.listFilter = argv[++i];
|
|
109
|
+
}
|
|
110
|
+
} else if (arg.startsWith('--list-tools=')) {
|
|
111
|
+
opts.mode = 'list-tools';
|
|
112
|
+
opts.listFilter = arg.slice('--list-tools='.length) || null;
|
|
113
|
+
} else if (arg === '--version' || arg === '-v') {
|
|
114
|
+
opts.mode = 'version';
|
|
115
|
+
} else if (arg === '--help' || arg === '-h') {
|
|
116
|
+
opts.mode = 'help';
|
|
117
|
+
} else if (arg.startsWith('--')) {
|
|
118
|
+
throw new Error(`unknown flag: ${arg}`);
|
|
119
|
+
} else {
|
|
120
|
+
positional.push(arg);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (opts.mode === 'version' || opts.mode === 'help') {
|
|
125
|
+
return opts;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (opts.mode === 'serve-mcp') {
|
|
129
|
+
if (positional.length > 0) {
|
|
130
|
+
throw new Error('--serve-mcp does not take a program argument');
|
|
131
|
+
}
|
|
132
|
+
if (!opts.pluginsExplicit) opts.plugins = [];
|
|
133
|
+
return opts;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (opts.mode === 'list-tools') {
|
|
137
|
+
if (!opts.listFilter && positional.length > 0) opts.listFilter = positional[0];
|
|
138
|
+
return opts;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (opts.mode === 'code' || opts.mode === 'stdin') {
|
|
142
|
+
if (positional.length > 0) opts.argsJson = positional[0];
|
|
143
|
+
return opts;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (positional.length > 0) {
|
|
147
|
+
opts.mode = 'file';
|
|
148
|
+
opts.programPath = positional[0];
|
|
149
|
+
opts.argsJson = positional[1];
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return opts;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function parsePositiveIntFlag(flag, raw) {
|
|
156
|
+
const n = Number(raw);
|
|
157
|
+
if (!Number.isInteger(n) || n <= 0) {
|
|
158
|
+
throw new Error(`${flag} requires a positive integer, got: ${raw}`);
|
|
159
|
+
}
|
|
160
|
+
return n;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function readStdin(maxBytes = parseMaxStdinBytes()) {
|
|
164
|
+
const chunks = [];
|
|
165
|
+
let total = 0;
|
|
166
|
+
for await (const chunk of process.stdin) {
|
|
167
|
+
const buf = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
|
|
168
|
+
total += buf.length;
|
|
169
|
+
if (total > maxBytes) {
|
|
170
|
+
throw new Error(`stdin exceeds limit of ${maxBytes} bytes`);
|
|
171
|
+
}
|
|
172
|
+
chunks.push(buf);
|
|
173
|
+
}
|
|
174
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function isDirectCliRun() {
|
|
178
|
+
if (!process.argv[1]) return false;
|
|
179
|
+
try {
|
|
180
|
+
return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
|
|
181
|
+
} catch {
|
|
182
|
+
return pathToFileURL(resolve(process.argv[1])).href === import.meta.url;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function usageText() {
|
|
187
|
+
return [
|
|
188
|
+
'usage:',
|
|
189
|
+
' mcp-code-mode <program.mjs> [jsonArgs] [--manifest <file>] [--mcp-config <file>] [--mcp "alias=cmd args"] [--plugins <csv>|--no-default-plugins]',
|
|
190
|
+
' mcp-code-mode --code|-e <jsBody> [jsonArgs] [--manifest <file>] [--mcp-config <file>] [--mcp "alias=cmd args"]',
|
|
191
|
+
' mcp-code-mode -|--stdin [jsonArgs] [--manifest <file>] [--mcp-config <file>] [--mcp "alias=cmd args"]',
|
|
192
|
+
' mcp-code-mode --list-tools [filter] [--manifest <file>] [--mcp-config <file>] [--mcp "alias=cmd args"]',
|
|
193
|
+
' mcp-code-mode --serve-mcp [--mcp-config <file>] [--mcp "alias=cmd args"] [--allow-tools <csv>] [--timeout-ms <n>]',
|
|
194
|
+
' mcp-code-mode --version|-v',
|
|
195
|
+
' mcp-code-mode --help|-h',
|
|
196
|
+
].join('\n');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function printUsage() {
|
|
200
|
+
console.error(usageText());
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export function buildRuntime(opts) {
|
|
204
|
+
const mcpServers = Object.create(null);
|
|
205
|
+
if (opts.mcpConfigPath) {
|
|
206
|
+
Object.assign(mcpServers, loadMcpConfig(opts.mcpConfigPath));
|
|
207
|
+
}
|
|
208
|
+
for (const spec of opts.mcpSpecs) {
|
|
209
|
+
const { alias, config } = parseMcpInlineSpec(spec);
|
|
210
|
+
mcpServers[alias] = config;
|
|
211
|
+
}
|
|
212
|
+
const mcpBridge = Object.keys(mcpServers).length > 0 ? createMcpBridge(mcpServers) : null;
|
|
213
|
+
const registry = createRegistry({
|
|
214
|
+
plugins: opts.plugins,
|
|
215
|
+
manifestPath: opts.manifestPath || undefined,
|
|
216
|
+
mcpBridge: mcpBridge || undefined,
|
|
217
|
+
});
|
|
218
|
+
return { mcpBridge, registry };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async function main() {
|
|
222
|
+
let opts;
|
|
223
|
+
try {
|
|
224
|
+
opts = parseCliArgs(process.argv.slice(2));
|
|
225
|
+
} catch (e) {
|
|
226
|
+
console.error(`[codemode] ${e instanceof Error ? e.message : String(e)}`);
|
|
227
|
+
printUsage();
|
|
228
|
+
process.exit(2);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (opts.mode === 'version') {
|
|
232
|
+
console.log(VERSION);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (opts.mode === 'help') {
|
|
237
|
+
console.log(usageText());
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (!opts.mode) {
|
|
242
|
+
printUsage();
|
|
243
|
+
process.exit(2);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
let mcpBridge = null;
|
|
247
|
+
let registry;
|
|
248
|
+
try {
|
|
249
|
+
({ mcpBridge, registry } = buildRuntime(opts));
|
|
250
|
+
} catch (e) {
|
|
251
|
+
await mcpBridge?.closeAll();
|
|
252
|
+
console.error(`[codemode] registry-init-failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
253
|
+
process.exit(2);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (opts.mode === 'serve-mcp') {
|
|
257
|
+
await runMcpServer({
|
|
258
|
+
version: VERSION,
|
|
259
|
+
registry,
|
|
260
|
+
mcpBridge,
|
|
261
|
+
outDir: resolve(process.env.CODEMODE_OUT_DIR ?? '.agent/out'),
|
|
262
|
+
allowTools: opts.allowTools,
|
|
263
|
+
timeoutMs: opts.timeoutMs,
|
|
264
|
+
});
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (opts.mode === 'list-tools') {
|
|
269
|
+
try {
|
|
270
|
+
const staticTools = registry.describe(opts.listFilter);
|
|
271
|
+
const mcpTools = mcpBridge ? await mcpBridge.listAll(opts.listFilter) : [];
|
|
272
|
+
console.log(safeJsonStringify({ tools: [...staticTools, ...mcpTools] }, 2));
|
|
273
|
+
} catch (e) {
|
|
274
|
+
console.error(`[codemode] list-tools-failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
275
|
+
process.exitCode = 1;
|
|
276
|
+
} finally {
|
|
277
|
+
await mcpBridge?.closeAll();
|
|
278
|
+
}
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
let args = {};
|
|
283
|
+
if (opts.argsJson !== undefined) {
|
|
284
|
+
try {
|
|
285
|
+
const parsed = JSON.parse(opts.argsJson);
|
|
286
|
+
args = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : { value: parsed };
|
|
287
|
+
} catch {
|
|
288
|
+
console.error('[codemode] invalid jsonArgs');
|
|
289
|
+
process.exit(2);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const programLabel = opts.mode === 'file' ? basename(opts.programPath) : opts.mode === 'code' ? 'inline' : 'stdin';
|
|
294
|
+
const spillStem = opts.mode === 'file' ? basename(opts.programPath, '.mjs') : programLabel;
|
|
295
|
+
const outDir = resolve(process.env.CODEMODE_OUT_DIR ?? '.agent/out');
|
|
296
|
+
const maxChars = parseMaxChars();
|
|
297
|
+
|
|
298
|
+
let source;
|
|
299
|
+
let sourceError;
|
|
300
|
+
if (opts.mode === 'code') {
|
|
301
|
+
source = opts.code;
|
|
302
|
+
} else if (opts.mode === 'stdin') {
|
|
303
|
+
try {
|
|
304
|
+
source = await readStdin();
|
|
305
|
+
} catch (e) {
|
|
306
|
+
sourceError = e instanceof Error ? e : new Error(String(e));
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
let outcome;
|
|
311
|
+
try {
|
|
312
|
+
outcome = await executeProgram({
|
|
313
|
+
mode: opts.mode === 'file' ? 'file' : 'code',
|
|
314
|
+
source,
|
|
315
|
+
programPath: opts.programPath,
|
|
316
|
+
args,
|
|
317
|
+
registry,
|
|
318
|
+
spill: createSpillHelper(outDir),
|
|
319
|
+
outDir,
|
|
320
|
+
label: programLabel,
|
|
321
|
+
spillStem,
|
|
322
|
+
version: VERSION,
|
|
323
|
+
maxChars,
|
|
324
|
+
emptySourceMessage: opts.mode === 'stdin' ? 'stdin program is empty' : undefined,
|
|
325
|
+
sourceError,
|
|
326
|
+
});
|
|
327
|
+
} finally {
|
|
328
|
+
await mcpBridge?.closeAll();
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
const { text: shown, truncated } = boundOutput(outcome.text, maxChars);
|
|
332
|
+
console.log(shown);
|
|
333
|
+
const outPath = outcome.spillPath;
|
|
334
|
+
if (truncated || outcome.truncated) {
|
|
335
|
+
console.error(`[codemode] v${VERSION} output-limit: ${outcome.text.length} chars > ${maxChars}${outPath ? `; full output: ${outPath}` : ''}`);
|
|
336
|
+
} else {
|
|
337
|
+
console.error(`[codemode] v${VERSION} ${outcome.text.length} chars${outPath ? `; full output: ${outPath}` : ''}`);
|
|
338
|
+
}
|
|
339
|
+
if (!outcome.ok) process.exitCode = 1;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
if (isDirectCliRun()) {
|
|
343
|
+
main().catch((e) => {
|
|
344
|
+
console.error(`[codemode] fatal: ${e instanceof Error ? e.message : String(e)}`);
|
|
345
|
+
process.exitCode = 1;
|
|
346
|
+
});
|
|
347
|
+
}
|
package/src/tools.mjs
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// Tool registry and public exports for mcp-code-mode.
|
|
2
|
+
// Built-in plugins (gh, engram) are decoupled into src/plugins/ and can be
|
|
3
|
+
// selectively enabled or replaced via declarative CLI manifests.
|
|
4
|
+
import {
|
|
5
|
+
assertFields,
|
|
6
|
+
assertPositiveInt,
|
|
7
|
+
assertRepo,
|
|
8
|
+
clampConcurrency,
|
|
9
|
+
execJson,
|
|
10
|
+
execTool,
|
|
11
|
+
mapBounded,
|
|
12
|
+
MAX_CONCURRENCY,
|
|
13
|
+
REPO_RE,
|
|
14
|
+
SAFE_TOKEN_RE,
|
|
15
|
+
ToolCallError,
|
|
16
|
+
} from './core.mjs';
|
|
17
|
+
import { createManifestTools, loadManifest } from './manifest.mjs';
|
|
18
|
+
import { engram, engramCatalog } from './plugins/engram.mjs';
|
|
19
|
+
import { gh, ghCatalog, ISSUE_FIELDS, PR_FIELDS } from './plugins/gh.mjs';
|
|
20
|
+
|
|
21
|
+
const BUILTIN_PLUGINS = {
|
|
22
|
+
gh: { namespace: 'gh', api: gh, catalog: ghCatalog },
|
|
23
|
+
engram: { namespace: 'engram', api: engram, catalog: engramCatalog },
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
function setNested(root, dottedName, fn) {
|
|
27
|
+
const parts = dottedName.split('.');
|
|
28
|
+
let cursor = root;
|
|
29
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
30
|
+
const seg = parts[i];
|
|
31
|
+
if (!Object.prototype.hasOwnProperty.call(cursor, seg) || typeof cursor[seg] !== 'object' || cursor[seg] === null) {
|
|
32
|
+
cursor[seg] = Object.create(null);
|
|
33
|
+
}
|
|
34
|
+
cursor = cursor[seg];
|
|
35
|
+
}
|
|
36
|
+
cursor[parts.at(-1)] = fn;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function deepFreeze(obj) {
|
|
40
|
+
if (!obj || typeof obj !== 'object' || Object.isFrozen(obj)) return obj;
|
|
41
|
+
for (const key of Object.keys(obj)) {
|
|
42
|
+
deepFreeze(obj[key]);
|
|
43
|
+
}
|
|
44
|
+
return Object.freeze(obj);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function createRegistry({ plugins = ['gh', 'engram'], manifestPath, manifest, mcpBridge } = {}) {
|
|
48
|
+
const registry = Object.create(null);
|
|
49
|
+
const flat = new Map();
|
|
50
|
+
const catalog = [];
|
|
51
|
+
|
|
52
|
+
for (const name of plugins) {
|
|
53
|
+
const key = String(name).trim();
|
|
54
|
+
if (!key || key === 'none') continue;
|
|
55
|
+
const plugin = BUILTIN_PLUGINS[key];
|
|
56
|
+
if (!plugin) {
|
|
57
|
+
throw new Error(`unknown plugin: ${key} (available: ${Object.keys(BUILTIN_PLUGINS).join(', ')})`);
|
|
58
|
+
}
|
|
59
|
+
registry[plugin.namespace] = Object.assign(Object.create(null), plugin.api);
|
|
60
|
+
for (const [fnName, fn] of Object.entries(plugin.api)) {
|
|
61
|
+
flat.set(`${plugin.namespace}.${fnName}`, fn);
|
|
62
|
+
}
|
|
63
|
+
catalog.push(...plugin.catalog);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const loadedManifest = manifest
|
|
67
|
+
? createManifestTools(manifest, 'manifest:inline')
|
|
68
|
+
: manifestPath
|
|
69
|
+
? loadManifest(manifestPath)
|
|
70
|
+
: null;
|
|
71
|
+
|
|
72
|
+
if (loadedManifest) {
|
|
73
|
+
for (const [dottedName, fn] of loadedManifest.flat.entries()) {
|
|
74
|
+
setNested(registry, dottedName, fn);
|
|
75
|
+
flat.set(dottedName, fn);
|
|
76
|
+
}
|
|
77
|
+
catalog.push(...loadedManifest.catalog);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (mcpBridge) {
|
|
81
|
+
registry.mcp = mcpBridge.namespace;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
registry.describe = (filter) => {
|
|
85
|
+
if (!filter) return catalog.map((item) => ({ ...item }));
|
|
86
|
+
const needle = String(filter).toLowerCase();
|
|
87
|
+
return catalog
|
|
88
|
+
.filter((item) =>
|
|
89
|
+
item.name.toLowerCase().includes(needle)
|
|
90
|
+
|| item.description.toLowerCase().includes(needle)
|
|
91
|
+
|| item.source.toLowerCase().includes(needle),
|
|
92
|
+
)
|
|
93
|
+
.map((item) => ({ ...item }));
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
registry.call = async (toolName, input = {}, opts) => {
|
|
97
|
+
const fn = flat.get(toolName);
|
|
98
|
+
if (fn) {
|
|
99
|
+
return opts == null ? fn(input) : fn(input, opts);
|
|
100
|
+
}
|
|
101
|
+
if (mcpBridge && typeof toolName === 'string' && toolName.startsWith('mcp.')) {
|
|
102
|
+
const rest = toolName.slice(4);
|
|
103
|
+
const dot = rest.indexOf('.');
|
|
104
|
+
if (dot > 0 && dot < rest.length - 1) {
|
|
105
|
+
const alias = rest.slice(0, dot);
|
|
106
|
+
const rawTool = rest.slice(dot + 1);
|
|
107
|
+
return mcpBridge.getClient(alias).callTool(rawTool, input, opts ?? undefined);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
throw new ToolCallError(String(toolName), `unknown tool: ${toolName}`);
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
return deepFreeze(registry);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export const tools = createRegistry();
|
|
117
|
+
|
|
118
|
+
export {
|
|
119
|
+
assertFields,
|
|
120
|
+
assertPositiveInt,
|
|
121
|
+
assertRepo,
|
|
122
|
+
clampConcurrency,
|
|
123
|
+
createManifestTools,
|
|
124
|
+
engram,
|
|
125
|
+
execJson,
|
|
126
|
+
execTool,
|
|
127
|
+
gh,
|
|
128
|
+
ISSUE_FIELDS,
|
|
129
|
+
loadManifest,
|
|
130
|
+
mapBounded,
|
|
131
|
+
MAX_CONCURRENCY,
|
|
132
|
+
PR_FIELDS,
|
|
133
|
+
REPO_RE,
|
|
134
|
+
SAFE_TOKEN_RE,
|
|
135
|
+
ToolCallError,
|
|
136
|
+
};
|