@thegitai/cli 1.0.0-preview.9 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +301 -15
  3. package/dist/bin/ai.js +139 -111
  4. package/dist/bin/browser-host.js +284 -0
  5. package/dist/src/agent-mode.js +33 -7
  6. package/dist/src/api/auth.js +8 -2
  7. package/dist/src/api/browser-login.js +77 -34
  8. package/dist/src/api/chat.js +702 -173
  9. package/dist/src/api/contracts.js +55 -1
  10. package/dist/src/api/default-host.js +1 -0
  11. package/dist/src/api/http.js +168 -8
  12. package/dist/src/api/models.js +75 -10
  13. package/dist/src/api/startup-handshake.js +36 -0
  14. package/dist/src/api/turn-recovery.js +189 -0
  15. package/dist/src/background-jobs.js +14 -4
  16. package/dist/src/browser/bridge.js +268 -0
  17. package/dist/src/browser/chrome-profiles.js +73 -0
  18. package/dist/src/browser/framing.js +42 -0
  19. package/dist/src/browser/native-host.js +219 -0
  20. package/dist/src/browser/protocol.js +46 -0
  21. package/dist/src/browser/session-bridge.js +130 -0
  22. package/dist/src/cli-args.js +19 -5
  23. package/dist/src/client-environment.js +2 -0
  24. package/dist/src/core/clipboard.js +8 -14
  25. package/dist/src/core/image-limits.js +56 -0
  26. package/dist/src/core/image-path-extractor.js +70 -3
  27. package/dist/src/core/session-image-store.js +271 -0
  28. package/dist/src/edit-journal.js +33 -2
  29. package/dist/src/executor.js +26 -4
  30. package/dist/src/help-text.js +152 -41
  31. package/dist/src/install-id.js +32 -0
  32. package/dist/src/job-follow-up.js +40 -0
  33. package/dist/src/mcp-client.js +335 -0
  34. package/dist/src/mcp-command.js +176 -0
  35. package/dist/src/mcp-config.js +123 -0
  36. package/dist/src/mcp-sdk.js +3 -0
  37. package/dist/src/mcp-types.js +26 -0
  38. package/dist/src/patcher.js +46 -4
  39. package/dist/src/permissions.js +301 -0
  40. package/dist/src/preferences.js +39 -0
  41. package/dist/src/project-key.js +11 -0
  42. package/dist/src/project-model-preferences.js +74 -0
  43. package/dist/src/quota-notice.js +62 -0
  44. package/dist/src/reasoning-effort.js +27 -0
  45. package/dist/src/scratch-dir.js +6 -2
  46. package/dist/src/session-context.js +11 -0
  47. package/dist/src/session-safety.js +0 -12
  48. package/dist/src/session-store.js +76 -10
  49. package/dist/src/session.js +14 -4
  50. package/dist/src/signin.js +58 -0
  51. package/dist/src/skills/discovery.js +280 -0
  52. package/dist/src/skills/frontmatter.js +192 -0
  53. package/dist/src/skills/install.js +394 -0
  54. package/dist/src/skills/types.js +43 -0
  55. package/dist/src/skills-command.js +71 -0
  56. package/dist/src/todo-list.js +16 -9
  57. package/dist/src/tool-executor.js +42 -51
  58. package/dist/src/tools/browser.js +928 -0
  59. package/dist/src/tools/delete-file.js +21 -5
  60. package/dist/src/tools/index.js +34 -10
  61. package/dist/src/tools/patch-file.js +14 -29
  62. package/dist/src/tools/read-file.js +7 -1
  63. package/dist/src/tools/read-image-file.js +85 -0
  64. package/dist/src/tools/replace-document-text.js +28 -18
  65. package/dist/src/tools/restore-checkpoint.js +1 -2
  66. package/dist/src/tools/run-command.js +14 -71
  67. package/dist/src/tools/run-node-script.js +13 -82
  68. package/dist/src/tools/save-generated-image.js +120 -0
  69. package/dist/src/tools/shell-diagnostics.js +248 -72
  70. package/dist/src/tools/str-replace.js +14 -29
  71. package/dist/src/tools/undo-edit.js +2 -7
  72. package/dist/src/tools/use-skill.js +38 -0
  73. package/dist/src/tools/write-file.js +69 -14
  74. package/dist/src/ui/repl.js +1141 -299
  75. package/dist/src/ui/slash-commands.js +140 -0
  76. package/dist/src/ui/tui/attention.js +25 -0
  77. package/dist/src/ui/tui/bridge.js +38 -5
  78. package/dist/src/ui/tui/build-frame.js +858 -303
  79. package/dist/src/ui/tui/composer-layout.js +76 -0
  80. package/dist/src/ui/tui/desktop-notification.js +118 -0
  81. package/dist/src/ui/tui/markdown-render.js +21 -11
  82. package/dist/src/ui/tui/model-label.js +13 -0
  83. package/dist/src/ui/tui/shell-input.js +266 -61
  84. package/dist/src/ui/tui/shortcuts.js +61 -0
  85. package/dist/src/ui/tui/terminal-theme.js +28 -0
  86. package/dist/src/ui/tui/text.js +31 -6
  87. package/dist/src/ui/tui/user-input.js +593 -0
  88. package/dist/src/update-check.js +205 -0
  89. package/dist/src/usage-notice.js +52 -0
  90. package/dist/src/usage.js +25 -2
  91. package/dist/src/utils.js +4 -0
  92. package/dist/src/version.js +52 -2
  93. package/dist/vendor/mcp/LICENSES.txt +414 -0
  94. package/dist/vendor/mcp/client.cjs +82 -0
  95. package/package.json +22 -9
  96. package/dist/src/project-index.js +0 -233
  97. package/dist/src/tools/code-intel.js +0 -472
  98. package/dist/src/tools/find-symbol.js +0 -70
  99. package/dist/src/tools/hover-symbol.js +0 -95
  100. package/dist/src/tools/list-symbols.js +0 -55
  101. package/dist/src/tools/search-code.js +0 -37
  102. package/dist/src/tools/signature-help.js +0 -118
@@ -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
+ }
@@ -1,9 +1,10 @@
1
1
  import chalk from './colors.js';
2
- import { chmodSync, closeSync, constants, existsSync, fchmodSync, fstatSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeFileSync, } from 'fs';
2
+ import { chmodSync, closeSync, constants, existsSync, fchmodSync, fstatSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, unlinkSync, writeFileSync, } from 'fs';
3
3
  import path from 'path';
4
4
  import { createInterface } from 'readline';
5
5
  import { runCommand } from './executor.js';
6
6
  import { ensureSessionScratchDir, isInsideTheGitAiScratch, isWithinSessionScratchDir, } from './scratch-dir.js';
7
+ import { isInsidePersonalSkills } from './skills/discovery.js';
7
8
  import { isTuiMode } from './runtime-mode.js';
8
9
  import { truncate } from './utils.js';
9
10
  function parseUnifiedDiff(patchText) {
@@ -164,6 +165,8 @@ export function classifyProjectPath(rootDir, filePath) {
164
165
  if (!relative.startsWith('..') && !path.isAbsolute(relative)) {
165
166
  return 'project';
166
167
  }
168
+ if (isInsidePersonalSkills(absPath))
169
+ return 'skills';
167
170
  return 'outside';
168
171
  }
169
172
  export function resolveProjectPath(rootDir, filePath) {
@@ -271,22 +274,61 @@ export function writeProjectFileBuffer(rootDir, filePath, content) {
271
274
  }
272
275
  return { absPath, changed: true };
273
276
  }
277
+ const MAX_DELETED_CONTENT_BYTES = 64 * 1024;
278
+ const DELETED_BINARY_SNIFF_BYTES = 4096;
279
+ function headHasNulByte(absPath) {
280
+ const chunk = Buffer.allocUnsafe(DELETED_BINARY_SNIFF_BYTES);
281
+ let fd = null;
282
+ try {
283
+ fd = openSync(absPath, 'r');
284
+ const read = readSync(fd, chunk, 0, chunk.length, 0);
285
+ return read > 0 && chunk.subarray(0, read).includes(0);
286
+ }
287
+ catch {
288
+ return false;
289
+ }
290
+ finally {
291
+ if (fd !== null)
292
+ closeSync(fd);
293
+ }
294
+ }
274
295
  export function deleteProjectFile(rootDir, filePath) {
275
296
  const absPath = resolveProjectPath(rootDir, filePath);
276
297
  if (!existsSync(absPath)) {
277
298
  return { deleted: false, absPath };
278
299
  }
300
+ let bytes;
279
301
  let content;
302
+ let contentOmitted;
280
303
  try {
281
- if (!lstatSync(absPath).isSymbolicLink()) {
282
- content = readFileSync(absPath, 'utf-8');
304
+ const stat = lstatSync(absPath);
305
+ if (!stat.isSymbolicLink()) {
306
+ bytes = stat.size;
307
+ if (stat.size > MAX_DELETED_CONTENT_BYTES) {
308
+ contentOmitted = headHasNulByte(absPath) ? 'binary' : 'too_large';
309
+ }
310
+ else {
311
+ const buffer = readFileSync(absPath);
312
+ if (buffer.includes(0))
313
+ contentOmitted = 'binary';
314
+ else
315
+ content = buffer.toString('utf-8');
316
+ }
283
317
  }
284
318
  }
285
319
  catch {
320
+ bytes = undefined;
286
321
  content = undefined;
322
+ contentOmitted = undefined;
287
323
  }
288
324
  unlinkSync(absPath);
289
- return { deleted: true, absPath, content };
325
+ return {
326
+ deleted: true,
327
+ absPath,
328
+ ...(bytes === undefined ? {} : { bytes }),
329
+ ...(content === undefined ? {} : { content }),
330
+ ...(contentOmitted === undefined ? {} : { contentOmitted }),
331
+ };
290
332
  }
291
333
  export function readProjectFile(rootDir, filePath) {
292
334
  const absPath = resolveProjectPath(rootDir, filePath);
@@ -0,0 +1,301 @@
1
+ import { getUnquotedShellText } from './agent-mode.js';
2
+ export const PERMISSION_BUCKETS = ['create', 'edit', 'delete', 'run', 'browse', 'mcp'];
3
+ export function createSessionGrants() {
4
+ return { buckets: [], commandPrefixes: [], origins: [] };
5
+ }
6
+ export function bucketActionLabel(bucket) {
7
+ if (bucket === 'create')
8
+ return 'create files';
9
+ if (bucket === 'edit')
10
+ return 'edit files';
11
+ if (bucket === 'delete')
12
+ return 'delete files';
13
+ if (bucket === 'browse')
14
+ return 'act on any website';
15
+ if (bucket === 'mcp')
16
+ return 'use MCP tools';
17
+ return 'run commands';
18
+ }
19
+ export function originForUrl(url) {
20
+ const raw = String(url ?? '').trim();
21
+ if (!raw)
22
+ return null;
23
+ try {
24
+ const parsed = new URL(/^[a-z][a-z0-9+.-]*:/i.test(raw) ? raw : `https://${raw}`);
25
+ if (parsed.protocol === 'about:' || parsed.protocol === 'chrome:')
26
+ return null;
27
+ return parsed.origin;
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ export function isOriginGranted(grants, origin) {
34
+ if (!grants || !origin)
35
+ return false;
36
+ return grants.origins?.includes(origin) === true;
37
+ }
38
+ export function grantOrigin(grants, origin) {
39
+ const normalized = String(origin ?? '').trim();
40
+ if (!normalized)
41
+ return;
42
+ const origins = grants.origins ??= [];
43
+ if (!origins.includes(normalized))
44
+ origins.push(normalized);
45
+ }
46
+ const NO_PREFIX_GRANT_BINARIES = new Set([
47
+ 'rm',
48
+ 'rmdir',
49
+ 'mv',
50
+ 'dd',
51
+ 'mkfs',
52
+ 'shred',
53
+ 'sudo',
54
+ 'doas',
55
+ 'su',
56
+ 'chmod',
57
+ 'chown',
58
+ 'chgrp',
59
+ 'kill',
60
+ 'pkill',
61
+ 'killall',
62
+ 'shutdown',
63
+ 'reboot',
64
+ 'curl',
65
+ 'wget',
66
+ 'ssh',
67
+ 'scp',
68
+ 'nc',
69
+ 'eval',
70
+ 'exec',
71
+ 'source',
72
+ ]);
73
+ const INTERPRETER_OR_WRAPPER_BINARIES = new Set([
74
+ 'bash',
75
+ 'sh',
76
+ 'zsh',
77
+ 'fish',
78
+ 'dash',
79
+ 'ksh',
80
+ 'csh',
81
+ 'tcsh',
82
+ 'python',
83
+ 'python2',
84
+ 'python3',
85
+ 'node',
86
+ 'deno',
87
+ 'bun',
88
+ 'ruby',
89
+ 'perl',
90
+ 'php',
91
+ 'lua',
92
+ 'osascript',
93
+ 'awk',
94
+ 'gawk',
95
+ 'sed',
96
+ 'env',
97
+ 'timeout',
98
+ 'xargs',
99
+ 'nohup',
100
+ 'setsid',
101
+ 'watch',
102
+ 'script',
103
+ 'nice',
104
+ 'ionice',
105
+ 'stdbuf',
106
+ 'time',
107
+ 'sudo',
108
+ 'doas',
109
+ 'su',
110
+ 'find',
111
+ 'make',
112
+ ]);
113
+ const SCRIPT_RUNNER_VERBS = new Set(['run', 'exec', 'run-script', 'x', 'dlx']);
114
+ const VERB_PATTERN = /^[A-Za-z][A-Za-z0-9_:-]*$/;
115
+ const BINARY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/;
116
+ const SHELL_CONTROL_OPERATOR_PATTERN = /[&|;<>\n]/;
117
+ const COMMAND_SUBSTITUTION_PATTERN = /`|\$\(/;
118
+ function normalizeCommand(command) {
119
+ return String(command ?? '').trim().replace(/\s+/g, ' ');
120
+ }
121
+ function parseCommand(command) {
122
+ const raw = String(command ?? '');
123
+ if (!raw.trim())
124
+ return null;
125
+ if (COMMAND_SUBSTITUTION_PATTERN.test(raw))
126
+ return null;
127
+ if (SHELL_CONTROL_OPERATOR_PATTERN.test(getUnquotedShellText(raw)))
128
+ return null;
129
+ const all = normalizeCommand(raw).match(/\S+/g) ?? [];
130
+ const tokens = [];
131
+ for (const token of all) {
132
+ if (!tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(token))
133
+ continue;
134
+ if (!tokens.length && token === 'command')
135
+ continue;
136
+ tokens.push(token);
137
+ }
138
+ if (!tokens.length)
139
+ return null;
140
+ const binary = (tokens[0].split('/').pop() ?? '').trim();
141
+ if (!binary)
142
+ return null;
143
+ tokens[0] = binary;
144
+ return { canonical: tokens.join(' '), tokens };
145
+ }
146
+ function grantPrefixFromTokens(tokens) {
147
+ const binary = tokens[0];
148
+ if (!BINARY_PATTERN.test(binary))
149
+ return null;
150
+ if (NO_PREFIX_GRANT_BINARIES.has(binary))
151
+ return null;
152
+ if (INTERPRETER_OR_WRAPPER_BINARIES.has(binary))
153
+ return null;
154
+ const verb = tokens[1];
155
+ if (!verb || !VERB_PATTERN.test(verb))
156
+ return null;
157
+ if (SCRIPT_RUNNER_VERBS.has(verb)) {
158
+ const script = tokens[2];
159
+ if (!script || !VERB_PATTERN.test(script))
160
+ return null;
161
+ return `${binary} ${verb} ${script}`;
162
+ }
163
+ return `${binary} ${verb}`;
164
+ }
165
+ export function commandGrantPrefix(command) {
166
+ const parsed = parseCommand(command);
167
+ return parsed ? grantPrefixFromTokens(parsed.tokens) : null;
168
+ }
169
+ export function isBucketGranted(grants, bucket) {
170
+ return Boolean(grants?.buckets.includes(bucket));
171
+ }
172
+ export function isCommandGranted(grants, command) {
173
+ if (!grants)
174
+ return false;
175
+ if (grants.buckets.includes('run'))
176
+ return true;
177
+ if (!grants.commandPrefixes.length)
178
+ return false;
179
+ const parsed = parseCommand(command);
180
+ if (!parsed)
181
+ return false;
182
+ if (grantPrefixFromTokens(parsed.tokens) === null)
183
+ return false;
184
+ return grants.commandPrefixes.some((prefix) => parsed.canonical === prefix || parsed.canonical.startsWith(`${prefix} `));
185
+ }
186
+ export function grantBucket(grants, bucket) {
187
+ if (!grants.buckets.includes(bucket))
188
+ grants.buckets.push(bucket);
189
+ }
190
+ export function grantCommandPrefix(grants, prefix) {
191
+ const normalized = normalizeCommand(prefix);
192
+ if (!normalized)
193
+ return;
194
+ if (!grants.commandPrefixes.includes(normalized)) {
195
+ grants.commandPrefixes.push(normalized);
196
+ }
197
+ }
198
+ export function buildPermissionOptions(bucket, command, origin) {
199
+ const options = [
200
+ { label: 'Approve once', decision: { kind: 'once' } },
201
+ ];
202
+ const prefix = bucket === 'run' && command ? commandGrantPrefix(command) : null;
203
+ if (prefix) {
204
+ options.push({
205
+ label: `Always allow: ${prefix}`,
206
+ decision: { kind: 'always-prefix', prefix },
207
+ });
208
+ }
209
+ if (bucket === 'browse' && origin) {
210
+ options.push({
211
+ label: `Allow this site for the session: ${origin}`,
212
+ decision: { kind: 'always-origin', origin },
213
+ });
214
+ }
215
+ options.push({
216
+ label: `Always allow: ${bucketActionLabel(bucket)}`,
217
+ decision: { kind: 'always-bucket' },
218
+ });
219
+ options.push({ label: 'Deny', decision: { kind: 'deny' } });
220
+ return options;
221
+ }
222
+ function declinedSubject(bucket) {
223
+ if (bucket === 'mcp')
224
+ return { noun: 'MCP tool call', effect: 'The MCP tool was not called' };
225
+ if (bucket === 'run') {
226
+ return { noun: 'command', effect: 'Nothing was executed' };
227
+ }
228
+ if (bucket === 'create') {
229
+ return { noun: 'file creation', effect: 'Nothing was created' };
230
+ }
231
+ if (bucket === 'delete') {
232
+ return { noun: 'file deletion', effect: 'Nothing was deleted' };
233
+ }
234
+ if (bucket === 'browse') {
235
+ return { noun: 'browser action', effect: 'The page was not touched' };
236
+ }
237
+ return { noun: 'edit', effect: 'Nothing was changed' };
238
+ }
239
+ function declinedResponse(bucket, toolName, extra) {
240
+ const { noun, effect } = declinedSubject(bucket);
241
+ return {
242
+ ok: false,
243
+ skipped: true,
244
+ ...extra,
245
+ failureCategory: 'user_declined',
246
+ failureDetails: {
247
+ category: 'user_declined',
248
+ tool: toolName,
249
+ action: 'Respect the real user’s decision. Do not retry the same or an equivalent action; reconsider the approach or ask one specific question if needed.',
250
+ },
251
+ error: `The real user rejected this proposed ${noun}. ${effect}; this was not a tool failure or an automated system skip.`,
252
+ };
253
+ }
254
+ export async function ensurePermission(context, request, toolName, extra = {}) {
255
+ if (context.autoYes)
256
+ return null;
257
+ if (request.mcpTool && context.grants?.mcpTools?.includes(request.mcpTool))
258
+ return null;
259
+ if (isBucketGranted(context.grants, request.bucket))
260
+ return null;
261
+ if (request.bucket === 'run' &&
262
+ request.command &&
263
+ isCommandGranted(context.grants, request.command)) {
264
+ return null;
265
+ }
266
+ if (request.bucket === 'browse' &&
267
+ isOriginGranted(context.grants, request.origin ?? null)) {
268
+ return null;
269
+ }
270
+ if (!context.requestPermission) {
271
+ return {
272
+ ok: false,
273
+ ...extra,
274
+ error: `requestPermission is required when autoYes is false (${toolName})`,
275
+ };
276
+ }
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);
282
+ const decision = await context.requestPermission({ ...request, options });
283
+ if (decision.kind === 'deny') {
284
+ return declinedResponse(request.bucket, toolName, extra);
285
+ }
286
+ if (context.grants) {
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') {
291
+ grantBucket(context.grants, request.bucket);
292
+ }
293
+ else if (decision.kind === 'always-prefix') {
294
+ grantCommandPrefix(context.grants, decision.prefix);
295
+ }
296
+ else if (decision.kind === 'always-origin') {
297
+ grantOrigin(context.grants, decision.origin);
298
+ }
299
+ }
300
+ return null;
301
+ }
@@ -0,0 +1,39 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { getClientStateDir } from './client-state.js';
4
+ export const DEFAULT_PREFERENCES = {
5
+ notifications: true,
6
+ };
7
+ export function getPreferencesPath(env = process.env) {
8
+ return path.join(getClientStateDir(env), 'prefs.json');
9
+ }
10
+ export function readPreferences(env = process.env) {
11
+ const filePath = getPreferencesPath(env);
12
+ if (!existsSync(filePath))
13
+ return { ...DEFAULT_PREFERENCES };
14
+ try {
15
+ const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
16
+ return {
17
+ notifications: parsed.notifications === false ? false : DEFAULT_PREFERENCES.notifications,
18
+ };
19
+ }
20
+ catch {
21
+ return { ...DEFAULT_PREFERENCES };
22
+ }
23
+ }
24
+ export function writePreferences(preferences, env = process.env) {
25
+ const filePath = getPreferencesPath(env);
26
+ mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
27
+ const tempPath = `${filePath}.${process.pid}.tmp`;
28
+ try {
29
+ writeFileSync(tempPath, `${JSON.stringify(preferences, null, 2)}\n`, {
30
+ encoding: 'utf8',
31
+ mode: 0o600,
32
+ });
33
+ renameSync(tempPath, filePath);
34
+ }
35
+ catch (error) {
36
+ rmSync(tempPath, { force: true });
37
+ throw error;
38
+ }
39
+ }
@@ -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
+ }