@thegitai/cli 1.0.0-preview.53 → 1.0.0-preview.55
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/README.md +119 -0
- package/dist/bin/ai.js +5 -0
- package/dist/src/api/chat.js +4 -0
- package/dist/src/help-text.js +16 -1
- package/dist/src/mcp-client.js +335 -0
- package/dist/src/mcp-command.js +176 -0
- package/dist/src/mcp-config.js +123 -0
- package/dist/src/mcp-sdk.js +3 -0
- package/dist/src/mcp-types.js +26 -0
- package/dist/src/permissions.js +16 -3
- package/dist/src/project-key.js +11 -0
- package/dist/src/project-model-preferences.js +74 -0
- package/dist/src/reasoning-effort.js +27 -0
- package/dist/src/session-store.js +2 -10
- package/dist/src/session.js +2 -1
- package/dist/src/tool-executor.js +10 -3
- package/dist/src/ui/repl.js +45 -16
- package/dist/src/ui/slash-commands.js +2 -1
- package/dist/src/ui/tui/build-frame.js +85 -34
- package/dist/src/ui/tui/model-label.js +13 -0
- package/dist/src/ui/tui/shell-input.js +19 -0
- package/dist/vendor/mcp/LICENSES.txt +414 -0
- package/dist/vendor/mcp/client.cjs +82 -0
- package/package.json +6 -6
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { mcpConfigPath, readMcpConfig, validateMcpServer, writeMcpConfig, } from './mcp-config.js';
|
|
2
|
+
export const MCP_HELP = `MCP servers (saved for your user account on this machine):
|
|
3
|
+
ai mcp add <name> -- <command> [args...]
|
|
4
|
+
ai mcp add --transport http <name> <url> [--header 'Name: value']
|
|
5
|
+
ai mcp add --env KEY=value <name> -- <command> [args...]
|
|
6
|
+
Options: -t/--transport, -e/--env, -H/--header, -s/--scope user
|
|
7
|
+
ai mcp add-json <name> '<JSON configuration>'
|
|
8
|
+
ai mcp list
|
|
9
|
+
ai mcp get <name>
|
|
10
|
+
ai mcp remove <name>
|
|
11
|
+
ai mcp enable <name>
|
|
12
|
+
ai mcp disable <name>
|
|
13
|
+
|
|
14
|
+
Use /mcp inside a session to check connections and available tools.
|
|
15
|
+
Local servers run on your machine. Add only servers you trust.
|
|
16
|
+
HTTP supports headers; browser-based OAuth sign-in is not supported yet.`;
|
|
17
|
+
export function runMcpCommand(args, env = process.env) {
|
|
18
|
+
const [action, ...input] = args;
|
|
19
|
+
const rest = [];
|
|
20
|
+
for (let index = 0; index < input.length; index++) {
|
|
21
|
+
const token = input[index];
|
|
22
|
+
if (token === '--') {
|
|
23
|
+
rest.push(...input.slice(index));
|
|
24
|
+
break;
|
|
25
|
+
}
|
|
26
|
+
if (token === '--scope' || token === '-s') {
|
|
27
|
+
const scope = input[++index];
|
|
28
|
+
if (scope !== 'user')
|
|
29
|
+
throw new Error('Only --scope user is supported. Project and local MCP scope are not available.');
|
|
30
|
+
}
|
|
31
|
+
else
|
|
32
|
+
rest.push(token);
|
|
33
|
+
}
|
|
34
|
+
if (!action || action === '--help' || action === '-h')
|
|
35
|
+
return MCP_HELP;
|
|
36
|
+
const config = readMcpConfig(env);
|
|
37
|
+
if (action === 'list' && rest.length === 0) {
|
|
38
|
+
return [
|
|
39
|
+
mcpConfigPath(env),
|
|
40
|
+
...Object.entries(config.mcpServers).map(([name, value]) => {
|
|
41
|
+
if (value && typeof value === 'object' && 'disabled' in value && value.disabled === true)
|
|
42
|
+
return `${name} · disabled`;
|
|
43
|
+
try {
|
|
44
|
+
const item = validateMcpServer(name, value);
|
|
45
|
+
return `${name} · ${item.type} · ${item.disabled ? 'disabled' : 'enabled'}`;
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
return `${name} · failed: ${String(error.message)}`;
|
|
49
|
+
}
|
|
50
|
+
}),
|
|
51
|
+
...(Object.keys(config.mcpServers).length
|
|
52
|
+
? []
|
|
53
|
+
: ['No MCP servers configured.']),
|
|
54
|
+
'Use /mcp in a session to check connections.',
|
|
55
|
+
].join('\n');
|
|
56
|
+
}
|
|
57
|
+
if (action === 'add' || action === 'add-json') {
|
|
58
|
+
let name;
|
|
59
|
+
let value;
|
|
60
|
+
if (action === 'add-json') {
|
|
61
|
+
if (rest.length !== 2)
|
|
62
|
+
throw new Error('Usage: ai mcp add-json <name> <JSON>');
|
|
63
|
+
name = rest[0];
|
|
64
|
+
try {
|
|
65
|
+
value = JSON.parse(rest[1]);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
throw new Error('Invalid MCP JSON configuration.');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
const positional = [];
|
|
73
|
+
const vars = {};
|
|
74
|
+
const headers = {};
|
|
75
|
+
let transport = 'stdio';
|
|
76
|
+
let command = [];
|
|
77
|
+
for (let i = 0; i < rest.length; i++) {
|
|
78
|
+
const token = rest[i];
|
|
79
|
+
const arg = {
|
|
80
|
+
'-t': '--transport',
|
|
81
|
+
'-e': '--env',
|
|
82
|
+
'-H': '--header',
|
|
83
|
+
'-s': '--scope',
|
|
84
|
+
}[token] ?? token;
|
|
85
|
+
if (arg === '--') {
|
|
86
|
+
command = rest.slice(i + 1);
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
if (['--transport', '--env', '--header'].includes(arg)) {
|
|
90
|
+
const value = rest[++i];
|
|
91
|
+
if (!value)
|
|
92
|
+
throw new Error(`Missing value for ${arg}.`);
|
|
93
|
+
if (arg === '--transport')
|
|
94
|
+
transport = value;
|
|
95
|
+
else {
|
|
96
|
+
const separator = arg === '--env' ? '=' : ':';
|
|
97
|
+
const at = value.indexOf(separator);
|
|
98
|
+
if (at < 1)
|
|
99
|
+
throw new Error(`Expected ${arg === '--env' ? 'KEY=value' : 'Name: value'} for ${arg}.`);
|
|
100
|
+
(arg === '--env' ? vars : headers)[value.slice(0, at).trim()] =
|
|
101
|
+
value.slice(at + 1).trim();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
else if (arg.startsWith('-'))
|
|
105
|
+
throw new Error(`Unknown MCP option: ${arg}`);
|
|
106
|
+
else
|
|
107
|
+
positional.push(arg);
|
|
108
|
+
}
|
|
109
|
+
name = positional[0] ?? '';
|
|
110
|
+
if (transport === 'http' &&
|
|
111
|
+
positional.length === 2 &&
|
|
112
|
+
!command.length &&
|
|
113
|
+
!Object.keys(vars).length)
|
|
114
|
+
value = { type: 'http', url: positional[1], headers };
|
|
115
|
+
else if (transport === 'stdio' &&
|
|
116
|
+
positional.length === 1 &&
|
|
117
|
+
command.length &&
|
|
118
|
+
!Object.keys(headers).length)
|
|
119
|
+
value = {
|
|
120
|
+
type: 'stdio',
|
|
121
|
+
command: command[0],
|
|
122
|
+
args: command.slice(1),
|
|
123
|
+
env: vars,
|
|
124
|
+
};
|
|
125
|
+
else
|
|
126
|
+
throw new Error(MCP_HELP);
|
|
127
|
+
}
|
|
128
|
+
if (Object.hasOwn(config.mcpServers, name))
|
|
129
|
+
throw new Error(`MCP server ${name} already exists. Remove it before replacing it.`);
|
|
130
|
+
Object.defineProperty(config.mcpServers, name, {
|
|
131
|
+
value: validateMcpServer(name, value),
|
|
132
|
+
enumerable: true,
|
|
133
|
+
configurable: true,
|
|
134
|
+
writable: true,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
const name = rest[0] ?? '';
|
|
139
|
+
if (rest.length !== 1 ||
|
|
140
|
+
!['get', 'remove', 'enable', 'disable'].includes(action))
|
|
141
|
+
throw new Error(MCP_HELP);
|
|
142
|
+
if (!Object.hasOwn(config.mcpServers, name))
|
|
143
|
+
throw new Error(`Unknown MCP server: ${name}`);
|
|
144
|
+
const raw = config.mcpServers[name];
|
|
145
|
+
if (action === 'remove') {
|
|
146
|
+
delete config.mcpServers[name];
|
|
147
|
+
}
|
|
148
|
+
else if (action === 'disable') {
|
|
149
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
150
|
+
throw new Error('This entry cannot be disabled. Remove it with ai mcp remove.');
|
|
151
|
+
config.mcpServers[name] = { ...raw, disabled: true };
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
const item = validateMcpServer(name, raw);
|
|
155
|
+
if (action === 'get')
|
|
156
|
+
return JSON.stringify({
|
|
157
|
+
name,
|
|
158
|
+
type: item.type,
|
|
159
|
+
disabled: item.disabled === true,
|
|
160
|
+
timeout: item.timeout ?? 60000,
|
|
161
|
+
...(item.type === 'stdio'
|
|
162
|
+
? {
|
|
163
|
+
command: item.command,
|
|
164
|
+
argumentCount: item.args?.length ?? 0,
|
|
165
|
+
environmentVariables: Object.keys(item.env ?? {}),
|
|
166
|
+
}
|
|
167
|
+
: { headerNames: Object.keys(item.headers ?? {}) }),
|
|
168
|
+
configFile: mcpConfigPath(env),
|
|
169
|
+
}, null, 2);
|
|
170
|
+
item.disabled = false;
|
|
171
|
+
config.mcpServers[name] = item;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
writeMcpConfig(config, env);
|
|
175
|
+
return `MCP configuration saved to ${mcpConfigPath(env)}. Changes apply on the next turn or /mcp.`;
|
|
176
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync, } from 'node:fs';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { getClientStateDir } from './client-state.js';
|
|
5
|
+
export function mcpConfigPath(env = process.env) {
|
|
6
|
+
return path.join(getClientStateDir(env), 'mcp.json');
|
|
7
|
+
}
|
|
8
|
+
function stringMap(value) {
|
|
9
|
+
return (!!value &&
|
|
10
|
+
typeof value === 'object' &&
|
|
11
|
+
!Array.isArray(value) &&
|
|
12
|
+
Object.values(value).every((item) => typeof item === 'string'));
|
|
13
|
+
}
|
|
14
|
+
export function validateMcpServer(name, value) {
|
|
15
|
+
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(name)) {
|
|
16
|
+
throw new Error('MCP server names must contain 1–64 letters, numbers, underscores or hyphens.');
|
|
17
|
+
}
|
|
18
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
19
|
+
throw new Error(`Invalid MCP configuration for ${name}.`);
|
|
20
|
+
}
|
|
21
|
+
const item = value;
|
|
22
|
+
const type = item.type ?? (item.command ? 'stdio' : 'http');
|
|
23
|
+
const allowed = new Set([
|
|
24
|
+
'type',
|
|
25
|
+
'disabled',
|
|
26
|
+
'timeout',
|
|
27
|
+
...(type === 'stdio' ? ['command', 'args', 'env'] : ['url', 'headers']),
|
|
28
|
+
]);
|
|
29
|
+
if (Object.keys(item).some((key) => !allowed.has(key))) {
|
|
30
|
+
throw new Error(`Unknown MCP configuration field for ${name}. Supported transports: stdio and http.`);
|
|
31
|
+
}
|
|
32
|
+
if (item.disabled !== undefined && typeof item.disabled !== 'boolean')
|
|
33
|
+
throw new Error(`Invalid disabled flag for ${name}.`);
|
|
34
|
+
if (item.timeout !== undefined &&
|
|
35
|
+
(!Number.isInteger(item.timeout) ||
|
|
36
|
+
Number(item.timeout) < 1000 ||
|
|
37
|
+
Number(item.timeout) > 300000)) {
|
|
38
|
+
throw new Error(`MCP timeout for ${name} must be 1000–300000 milliseconds.`);
|
|
39
|
+
}
|
|
40
|
+
const common = {
|
|
41
|
+
disabled: item.disabled,
|
|
42
|
+
timeout: item.timeout,
|
|
43
|
+
};
|
|
44
|
+
if (type === 'stdio' &&
|
|
45
|
+
typeof item.command === 'string' &&
|
|
46
|
+
item.command.trim()) {
|
|
47
|
+
if (item.args !== undefined &&
|
|
48
|
+
(!Array.isArray(item.args) ||
|
|
49
|
+
!item.args.every((arg) => typeof arg === 'string')))
|
|
50
|
+
throw new Error(`Invalid args for ${name}.`);
|
|
51
|
+
if (item.env !== undefined &&
|
|
52
|
+
(!stringMap(item.env) ||
|
|
53
|
+
Object.keys(item.env).some((key) => !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key))))
|
|
54
|
+
throw new Error(`Invalid env for ${name}.`);
|
|
55
|
+
return {
|
|
56
|
+
...common,
|
|
57
|
+
type,
|
|
58
|
+
command: item.command,
|
|
59
|
+
args: item.args,
|
|
60
|
+
env: item.env,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
if (type === 'http' && typeof item.url === 'string') {
|
|
64
|
+
const hasVariable = /\$\{[a-zA-Z_][a-zA-Z0-9_]*(?::-[^}]*)?\}/.test(item.url);
|
|
65
|
+
const url = hasVariable ? null : new URL(item.url);
|
|
66
|
+
if (url &&
|
|
67
|
+
(!['http:', 'https:'].includes(url.protocol) ||
|
|
68
|
+
url.username ||
|
|
69
|
+
url.password))
|
|
70
|
+
throw new Error(`Invalid HTTP URL for ${name}. Use headers for authentication.`);
|
|
71
|
+
if (item.headers !== undefined && !stringMap(item.headers))
|
|
72
|
+
throw new Error(`Invalid headers for ${name}.`);
|
|
73
|
+
return {
|
|
74
|
+
...common,
|
|
75
|
+
type,
|
|
76
|
+
url: item.url,
|
|
77
|
+
headers: item.headers,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
throw new Error(`MCP server ${name} needs a stdio command or HTTP URL.`);
|
|
81
|
+
}
|
|
82
|
+
export function readMcpConfig(env = process.env) {
|
|
83
|
+
let raw;
|
|
84
|
+
try {
|
|
85
|
+
raw = readFileSync(mcpConfigPath(env), 'utf8');
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
if (error.code === 'ENOENT')
|
|
89
|
+
return { mcpServers: {} };
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
let config;
|
|
93
|
+
try {
|
|
94
|
+
config = JSON.parse(raw);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
throw new Error(`Invalid JSON in ${mcpConfigPath(env)}.`);
|
|
98
|
+
}
|
|
99
|
+
if (!config?.mcpServers ||
|
|
100
|
+
typeof config.mcpServers !== 'object' ||
|
|
101
|
+
Array.isArray(config.mcpServers))
|
|
102
|
+
throw new Error('MCP configuration needs an mcpServers object.');
|
|
103
|
+
return config;
|
|
104
|
+
}
|
|
105
|
+
export function writeMcpConfig(config, env = process.env) {
|
|
106
|
+
const file = mcpConfigPath(env);
|
|
107
|
+
mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
108
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
109
|
+
writeFileSync(temporary, `${JSON.stringify(config, null, 2)}\n`, {
|
|
110
|
+
mode: 0o600,
|
|
111
|
+
flag: 'wx',
|
|
112
|
+
});
|
|
113
|
+
renameSync(temporary, file);
|
|
114
|
+
chmodSync(file, 0o600);
|
|
115
|
+
}
|
|
116
|
+
export function expandMcpValue(value, env) {
|
|
117
|
+
return value.replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)(?::-([^}]*))?\}/g, (_match, name, fallback) => {
|
|
118
|
+
const resolved = env[name] ?? fallback;
|
|
119
|
+
if (resolved === undefined)
|
|
120
|
+
throw new Error(`Missing environment variable ${name}.`);
|
|
121
|
+
return resolved;
|
|
122
|
+
});
|
|
123
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
const sdk = createRequire(import.meta.url)('../vendor/mcp/client.cjs');
|
|
3
|
+
export const { Client, StdioClientTransport, StreamableHTTPClientTransport, AjvJsonSchemaValidator, getDefaultEnvironment, ToolListChangedNotificationSchema, } = sdk;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
export function mcpToolName(serverName, toolName) {
|
|
3
|
+
const label = `${serverName}_${toolName}`
|
|
4
|
+
.replace(/[^a-zA-Z0-9_]/g, '_')
|
|
5
|
+
.slice(0, 36);
|
|
6
|
+
const digest = createHash('sha256')
|
|
7
|
+
.update(JSON.stringify([serverName, toolName]))
|
|
8
|
+
.digest('hex')
|
|
9
|
+
.slice(0, 16);
|
|
10
|
+
return `mcp_${label}_${digest}`;
|
|
11
|
+
}
|
|
12
|
+
export function isMcpToolName(value) {
|
|
13
|
+
return typeof value === 'string' && value.startsWith('mcp_');
|
|
14
|
+
}
|
|
15
|
+
export const MCP_MAX_TOOLS = 128;
|
|
16
|
+
export const MCP_MAX_CATALOGUE_BYTES = 100 * 1024;
|
|
17
|
+
export const MCP_MAX_DESCRIPTION_CHARS = 4096;
|
|
18
|
+
export function mcpCatalogueError(tools) {
|
|
19
|
+
if (tools.length > MCP_MAX_TOOLS)
|
|
20
|
+
return `More than ${MCP_MAX_TOOLS} MCP tools.`;
|
|
21
|
+
if (tools.some((tool) => tool.description.length > MCP_MAX_DESCRIPTION_CHARS))
|
|
22
|
+
return `An MCP tool description exceeds ${MCP_MAX_DESCRIPTION_CHARS} characters.`;
|
|
23
|
+
if (Buffer.byteLength(JSON.stringify(tools), 'utf8') > MCP_MAX_CATALOGUE_BYTES)
|
|
24
|
+
return 'MCP tool definitions exceed 100 KiB (approximately 25,600 tokens).';
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
package/dist/src/permissions.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { getUnquotedShellText } from './agent-mode.js';
|
|
2
|
-
export const PERMISSION_BUCKETS = ['create', 'edit', 'delete', 'run', 'browse'];
|
|
2
|
+
export const PERMISSION_BUCKETS = ['create', 'edit', 'delete', 'run', 'browse', 'mcp'];
|
|
3
3
|
export function createSessionGrants() {
|
|
4
4
|
return { buckets: [], commandPrefixes: [], origins: [] };
|
|
5
5
|
}
|
|
@@ -12,6 +12,8 @@ export function bucketActionLabel(bucket) {
|
|
|
12
12
|
return 'delete files';
|
|
13
13
|
if (bucket === 'browse')
|
|
14
14
|
return 'act on any website';
|
|
15
|
+
if (bucket === 'mcp')
|
|
16
|
+
return 'use MCP tools';
|
|
15
17
|
return 'run commands';
|
|
16
18
|
}
|
|
17
19
|
export function originForUrl(url) {
|
|
@@ -218,6 +220,8 @@ export function buildPermissionOptions(bucket, command, origin) {
|
|
|
218
220
|
return options;
|
|
219
221
|
}
|
|
220
222
|
function declinedSubject(bucket) {
|
|
223
|
+
if (bucket === 'mcp')
|
|
224
|
+
return { noun: 'MCP tool call', effect: 'The MCP tool was not called' };
|
|
221
225
|
if (bucket === 'run') {
|
|
222
226
|
return { noun: 'command', effect: 'Nothing was executed' };
|
|
223
227
|
}
|
|
@@ -250,6 +254,8 @@ function declinedResponse(bucket, toolName, extra) {
|
|
|
250
254
|
export async function ensurePermission(context, request, toolName, extra = {}) {
|
|
251
255
|
if (context.autoYes)
|
|
252
256
|
return null;
|
|
257
|
+
if (request.mcpTool && context.grants?.mcpTools?.includes(request.mcpTool))
|
|
258
|
+
return null;
|
|
253
259
|
if (isBucketGranted(context.grants, request.bucket))
|
|
254
260
|
return null;
|
|
255
261
|
if (request.bucket === 'run' &&
|
|
@@ -268,13 +274,20 @@ export async function ensurePermission(context, request, toolName, extra = {}) {
|
|
|
268
274
|
error: `requestPermission is required when autoYes is false (${toolName})`,
|
|
269
275
|
};
|
|
270
276
|
}
|
|
271
|
-
const options =
|
|
277
|
+
const options = request.mcpTool ? [
|
|
278
|
+
{ label: 'Approve once', decision: { kind: 'once' } },
|
|
279
|
+
{ label: 'Allow this MCP tool for the session', decision: { kind: 'always-mcp-tool', tool: request.mcpTool } },
|
|
280
|
+
{ label: 'Deny', decision: { kind: 'deny' } },
|
|
281
|
+
] : buildPermissionOptions(request.bucket, request.command, request.origin);
|
|
272
282
|
const decision = await context.requestPermission({ ...request, options });
|
|
273
283
|
if (decision.kind === 'deny') {
|
|
274
284
|
return declinedResponse(request.bucket, toolName, extra);
|
|
275
285
|
}
|
|
276
286
|
if (context.grants) {
|
|
277
|
-
if (decision.kind === 'always-
|
|
287
|
+
if (decision.kind === 'always-mcp-tool' && decision.tool === request.mcpTool) {
|
|
288
|
+
(context.grants.mcpTools ??= []).push(decision.tool);
|
|
289
|
+
}
|
|
290
|
+
else if (decision.kind === 'always-bucket') {
|
|
278
291
|
grantBucket(context.grants, request.bucket);
|
|
279
292
|
}
|
|
280
293
|
else if (decision.kind === 'always-prefix') {
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
export function getSessionProjectKey(rootDir) {
|
|
4
|
+
const resolvedRoot = path.resolve(rootDir);
|
|
5
|
+
const projectName = path.basename(resolvedRoot).replace(/[^a-zA-Z0-9._-]/g, '_') || 'project';
|
|
6
|
+
const hash = createHash('sha256')
|
|
7
|
+
.update(resolvedRoot)
|
|
8
|
+
.digest('hex')
|
|
9
|
+
.slice(0, 16);
|
|
10
|
+
return `${projectName}-${hash}`;
|
|
11
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { getClientStateDir } from './client-state.js';
|
|
5
|
+
import { getSessionProjectKey } from './project-key.js';
|
|
6
|
+
import { isReasoningEffort } from './reasoning-effort.js';
|
|
7
|
+
function preferencesPath(rootDir, env) {
|
|
8
|
+
return path.join(getClientStateDir(env), 'projects', getSessionProjectKey(rootDir), 'model-efforts.json');
|
|
9
|
+
}
|
|
10
|
+
function parseScopes(contents) {
|
|
11
|
+
const parsed = JSON.parse(contents);
|
|
12
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
13
|
+
throw new Error('Project model preferences must be an object.');
|
|
14
|
+
}
|
|
15
|
+
return Object.fromEntries(Object.entries(parsed).map(([scope, models]) => {
|
|
16
|
+
if (!models || typeof models !== 'object' || Array.isArray(models)) {
|
|
17
|
+
throw new Error('Project model preferences contain an invalid model selection.');
|
|
18
|
+
}
|
|
19
|
+
const entries = Object.entries(models).map(([id, effort]) => {
|
|
20
|
+
if (!/^[1-9]\d*$/.test(id) || !isReasoningEffort(effort)) {
|
|
21
|
+
throw new Error('Project model preferences contain an invalid effort selection.');
|
|
22
|
+
}
|
|
23
|
+
return [id, effort];
|
|
24
|
+
});
|
|
25
|
+
return [scope, Object.fromEntries(entries)];
|
|
26
|
+
}));
|
|
27
|
+
}
|
|
28
|
+
function readScopes(rootDir, env, onInvalid) {
|
|
29
|
+
const file = preferencesPath(rootDir, env);
|
|
30
|
+
if (!existsSync(file))
|
|
31
|
+
return {};
|
|
32
|
+
const contents = readFileSync(file, 'utf8');
|
|
33
|
+
try {
|
|
34
|
+
return parseScopes(contents);
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (onInvalid === 'throw')
|
|
38
|
+
throw error;
|
|
39
|
+
return {};
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function scopeKey(scope) {
|
|
43
|
+
return scope.trim().replace(/\/+$/, '') || 'local';
|
|
44
|
+
}
|
|
45
|
+
export function readProjectModelEfforts(rootDir, scope = '', env = process.env) {
|
|
46
|
+
return readScopes(rootDir, env, 'default')[scopeKey(scope)] ?? {};
|
|
47
|
+
}
|
|
48
|
+
export function projectModelEffort(efforts, modelId) {
|
|
49
|
+
return efforts[String(modelId)] ?? 'default';
|
|
50
|
+
}
|
|
51
|
+
export function saveProjectModelEffort(rootDir, modelId, effort, scope = '', env = process.env) {
|
|
52
|
+
if (!Number.isInteger(modelId) || modelId <= 0 || !isReasoningEffort(effort)) {
|
|
53
|
+
throw new Error('Invalid project model preference.');
|
|
54
|
+
}
|
|
55
|
+
const scopes = readScopes(rootDir, env, 'throw');
|
|
56
|
+
const key = scopeKey(scope);
|
|
57
|
+
const models = { ...scopes[key] };
|
|
58
|
+
if (effort === 'default')
|
|
59
|
+
delete models[String(modelId)];
|
|
60
|
+
else
|
|
61
|
+
models[String(modelId)] = effort;
|
|
62
|
+
const file = preferencesPath(rootDir, env);
|
|
63
|
+
mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
64
|
+
const temp = `${file}.${randomUUID()}.tmp`;
|
|
65
|
+
try {
|
|
66
|
+
writeFileSync(temp, `${JSON.stringify({ ...scopes, [key]: models }, null, 2)}\n`, { mode: 0o600 });
|
|
67
|
+
renameSync(temp, file);
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
rmSync(temp, { force: true });
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
return models;
|
|
74
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export const REASONING_EFFORTS = ['default', 'low', 'balanced', 'deep'];
|
|
2
|
+
export const REASONING_EFFORT_LABELS = {
|
|
3
|
+
default: 'Default',
|
|
4
|
+
low: 'Low',
|
|
5
|
+
balanced: 'Balanced',
|
|
6
|
+
deep: 'Deep',
|
|
7
|
+
};
|
|
8
|
+
export const REASONING_EFFORT_DESCRIPTIONS = {
|
|
9
|
+
default: 'Uses our recommended setting for this model.',
|
|
10
|
+
low: 'Favors quicker responses and lower reasoning cost.',
|
|
11
|
+
balanced: 'Balances reasoning depth, speed, and cost.',
|
|
12
|
+
deep: 'Favors thorough reasoning; may take longer and cost more.',
|
|
13
|
+
};
|
|
14
|
+
export function isReasoningEffort(value) {
|
|
15
|
+
return REASONING_EFFORTS.some((effort) => effort === value);
|
|
16
|
+
}
|
|
17
|
+
export function normalizeReasoningEffort(value) {
|
|
18
|
+
if (value === undefined)
|
|
19
|
+
return 'default';
|
|
20
|
+
if (isReasoningEffort(value))
|
|
21
|
+
return value;
|
|
22
|
+
throw new Error('Invalid reasoning effort. Choose Default, Low, Balanced, or Deep.');
|
|
23
|
+
}
|
|
24
|
+
export function cycleReasoningEffort(effort, direction) {
|
|
25
|
+
const index = REASONING_EFFORTS.indexOf(effort);
|
|
26
|
+
return REASONING_EFFORTS[(index + direction + REASONING_EFFORTS.length) % REASONING_EFFORTS.length];
|
|
27
|
+
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { spawnSync } from 'node:child_process';
|
|
2
|
-
import { createHash } from 'node:crypto';
|
|
3
2
|
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
|
|
4
3
|
import path from 'node:path';
|
|
5
4
|
import { getClientStateDir } from './client-state.js';
|
|
5
|
+
import { getSessionProjectKey } from './project-key.js';
|
|
6
6
|
import { findStoredImageByContent, pruneSessionImages, readSessionImage, sweepOrphanSessionImages, } from './core/session-image-store.js';
|
|
7
7
|
import { sweepGeneratedImages } from './tools/save-generated-image.js';
|
|
8
8
|
import { normalizeAssistantEditJournal } from './edit-journal.js';
|
|
@@ -11,6 +11,7 @@ import { cloneSessionSafetyState, createSessionSafetyState, mergeLocalSessionSaf
|
|
|
11
11
|
import { singleLinePreview } from './utils.js';
|
|
12
12
|
const SESSION_STORE_VERSION = 1;
|
|
13
13
|
export const MAX_RECENT_SESSIONS = 10;
|
|
14
|
+
export { getSessionProjectKey };
|
|
14
15
|
function cloneJson(value) {
|
|
15
16
|
return JSON.parse(JSON.stringify(value ?? null));
|
|
16
17
|
}
|
|
@@ -58,15 +59,6 @@ function safeSessionFileName(id) {
|
|
|
58
59
|
function getSessionBaseDir(env = process.env) {
|
|
59
60
|
return getClientStateDir(env);
|
|
60
61
|
}
|
|
61
|
-
export function getSessionProjectKey(rootDir) {
|
|
62
|
-
const resolvedRoot = path.resolve(rootDir);
|
|
63
|
-
const projectName = path.basename(resolvedRoot).replace(/[^a-zA-Z0-9._-]/g, '_') || 'project';
|
|
64
|
-
const hash = createHash('sha256')
|
|
65
|
-
.update(resolvedRoot)
|
|
66
|
-
.digest('hex')
|
|
67
|
-
.slice(0, 16);
|
|
68
|
-
return `${projectName}-${hash}`;
|
|
69
|
-
}
|
|
70
62
|
function getSessionProjectDir(rootDir, env = process.env) {
|
|
71
63
|
return path.join(getSessionBaseDir(env), 'sessions', 'projects', getSessionProjectKey(rootDir));
|
|
72
64
|
}
|
package/dist/src/session.js
CHANGED
|
@@ -99,8 +99,9 @@ export function clearConversation(session) {
|
|
|
99
99
|
safety: createSessionSafetyState(),
|
|
100
100
|
};
|
|
101
101
|
}
|
|
102
|
-
export async function disposeSession(
|
|
102
|
+
export async function disposeSession(session) {
|
|
103
103
|
closeBrowserBridge();
|
|
104
|
+
await session.mcp?.close();
|
|
104
105
|
}
|
|
105
106
|
export function switchModel(session, modelId) {
|
|
106
107
|
session.modelId = Number(modelId);
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { isMcpToolName } from './mcp-types.js';
|
|
2
|
+
import { sessionMcp } from './mcp-client.js';
|
|
1
3
|
import { drainBackgroundJobNotifications, getBackgroundJob, } from './background-jobs.js';
|
|
2
4
|
import { canStoreEditSnapshot, isEditToolName, isGitWorkTree, MAX_EDIT_JOURNAL_RECORDS, operationFromSnapshots, readFileEditSnapshot, } from './edit-journal.js';
|
|
3
5
|
import { clearEditFailure, collectCommandMutations, captureMutationBaseline, ensureActiveCheckpoint, recordEditFailure, recordSessionEdit, rememberCheckpointFiles, } from './session-safety.js';
|
|
@@ -42,9 +44,9 @@ function toolCallSummary(call) {
|
|
|
42
44
|
return args.query.slice(0, 120);
|
|
43
45
|
return '';
|
|
44
46
|
}
|
|
45
|
-
export function formatToolCallForStatus(call) {
|
|
47
|
+
export function formatToolCallForStatus(call, label = call.name) {
|
|
46
48
|
const summary = toolCallSummary(call);
|
|
47
|
-
return summary ? `Tool: ${
|
|
49
|
+
return summary ? `Tool: ${label} ${summary}` : `Tool: ${label}`;
|
|
48
50
|
}
|
|
49
51
|
function getEditToolFilePath(call) {
|
|
50
52
|
const args = call.args && typeof call.args === 'object' ? call.args : {};
|
|
@@ -214,7 +216,7 @@ function recordAssistantEdit(session, call, result, before) {
|
|
|
214
216
|
}
|
|
215
217
|
export async function executeLocalToolCall(session, call) {
|
|
216
218
|
session.turnAbortSignal?.throwIfAborted();
|
|
217
|
-
session.onStatus(formatToolCallForStatus(call));
|
|
219
|
+
session.onStatus(formatToolCallForStatus(call, session.mcp?.label(call.name)));
|
|
218
220
|
try {
|
|
219
221
|
const agentModeBlocked = buildAgentModeToolBlockedResult(session.agentMode, call);
|
|
220
222
|
if (agentModeBlocked) {
|
|
@@ -222,6 +224,11 @@ export async function executeLocalToolCall(session, call) {
|
|
|
222
224
|
session.onToolEvent?.({ call, result });
|
|
223
225
|
return result;
|
|
224
226
|
}
|
|
227
|
+
if (isMcpToolName(call.name)) {
|
|
228
|
+
const result = await sessionMcp(session).execute(session, call);
|
|
229
|
+
session.onToolEvent?.({ call, result });
|
|
230
|
+
return result;
|
|
231
|
+
}
|
|
225
232
|
const rawEditFilePath = isEditToolName(call.name)
|
|
226
233
|
? getEditToolFilePath(call)
|
|
227
234
|
: '';
|