@cmodjs/core 4.3.3 → 5.0.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 (64) hide show
  1. package/README.md +1 -1
  2. package/docs/commands.md +20 -31
  3. package/docs/dependencies.md +7 -5
  4. package/docs/index.md +4 -5
  5. package/docs/install-steps.md +12 -14
  6. package/docs/jobs.md +3 -11
  7. package/docs/mod.md +18 -21
  8. package/docs/session.md +11 -11
  9. package/docs/state.md +1 -1
  10. package/docs/testing.md +3 -5
  11. package/docs/ui.md +4 -4
  12. package/jobs/program.d.ts.map +1 -1
  13. package/jobs/program.js +3 -17
  14. package/mod.d.ts +0 -16
  15. package/mod.d.ts.map +1 -1
  16. package/package.json +1 -1
  17. package/records.d.ts +4 -11
  18. package/records.d.ts.map +1 -1
  19. package/records.js +17 -48
  20. package/runtime/announce.d.ts +1 -1
  21. package/runtime/announce.d.ts.map +1 -1
  22. package/runtime/announce.js +2 -3
  23. package/runtime/conversations.d.ts.map +1 -1
  24. package/runtime/conversations.js +3 -46
  25. package/runtime/engine.d.ts +2 -2
  26. package/runtime/engine.d.ts.map +1 -1
  27. package/runtime/installer.d.ts +0 -9
  28. package/runtime/installer.d.ts.map +1 -1
  29. package/runtime/installer.js +1 -15
  30. package/runtime/lifecycle.d.ts +1 -2
  31. package/runtime/lifecycle.d.ts.map +1 -1
  32. package/runtime/lifecycle.js +37 -191
  33. package/runtime/metadata.d.ts +1 -2
  34. package/runtime/metadata.d.ts.map +1 -1
  35. package/runtime/metadata.js +1 -2
  36. package/runtime/sessions.d.ts +3 -7
  37. package/runtime/sessions.d.ts.map +1 -1
  38. package/runtime/sessions.js +10 -34
  39. package/runtime/toaster.d.ts.map +1 -1
  40. package/runtime/toaster.js +6 -9
  41. package/runtime/ui.d.ts +1 -0
  42. package/runtime/ui.d.ts.map +1 -1
  43. package/runtime/ui.js +31 -12
  44. package/src/jobs/program.ts +3 -17
  45. package/src/mod.ts +0 -18
  46. package/src/records.ts +20 -55
  47. package/src/runtime/announce.ts +2 -3
  48. package/src/runtime/conversations.ts +3 -45
  49. package/src/runtime/engine.ts +2 -2
  50. package/src/runtime/installer.ts +1 -37
  51. package/src/runtime/lifecycle.ts +38 -188
  52. package/src/runtime/metadata.ts +0 -3
  53. package/src/runtime/sessions.ts +10 -39
  54. package/src/runtime/toaster.ts +6 -9
  55. package/src/runtime/ui.ts +32 -13
  56. package/src/testing.ts +11 -16
  57. package/testing.d.ts +0 -1
  58. package/testing.d.ts.map +1 -1
  59. package/testing.js +11 -15
  60. package/docs/permissions.md +0 -97
  61. package/runtime/grants.d.ts +0 -34
  62. package/runtime/grants.d.ts.map +0 -1
  63. package/runtime/grants.js +0 -326
  64. package/src/runtime/grants.ts +0 -348
package/runtime/grants.js DELETED
@@ -1,326 +0,0 @@
1
- import { grantFix, isObject, isSettingCovered, permissionWords, settingPaths } from '../records.js';
2
- import { relativePath } from '../utils/paths.js';
3
- import { cmodPluginName } from './dependencies.js';
4
- import { actPermission, conversationMethods, isAct, toolPermission } from './sessions.js';
5
- export class PermissionRefused extends Error {
6
- }
7
- const addressesOfPrograms = new WeakMap();
8
- export function programAddresses(mod) {
9
- const known = addressesOfPrograms.get(mod) ?? new Set();
10
- addressesOfPrograms.set(mod, known);
11
- return known;
12
- }
13
- const projectSettingsFiles = ['.claude/settings.json', '.claude/settings.local.json', '.mcp.json'];
14
- export const conversationCalls = {
15
- [conversationMethods.sessions]: 'sessions.list',
16
- [conversationMethods.search]: 'sessions.search',
17
- [conversationMethods.messages]: 'messages',
18
- [conversationMethods.turns]: 'turns',
19
- [conversationMethods.contexts]: 'contexts',
20
- [conversationMethods.tasks]: 'tasks',
21
- [conversationMethods.goal]: 'goal',
22
- [conversationMethods.updateGoal]: 'goal.update',
23
- [conversationMethods.subscribe]: 'on',
24
- [conversationMethods.watchBefore]: 'before',
25
- [conversationMethods.act]: 'act',
26
- };
27
- export async function checkGrant(grants, call, item) {
28
- if (item === undefined)
29
- return;
30
- await grants.refresh();
31
- if (!isCovered(grants.granted(), item, grants.home))
32
- throw new PermissionRefused(refusal(grants, call, item));
33
- }
34
- export async function checkRun(grants, call, argv) {
35
- await checkGrant(grants, `${call}(${argv.join(' ')})`, `run:${programOf(argv)}`);
36
- }
37
- export async function checkWrite(grants, call, path) {
38
- await checkGrant(grants, call, writeItem(grants, path));
39
- }
40
- export async function checkSettings(grants, source, values) {
41
- for (const path of settingPaths(values).map((each) => each.join('.')))
42
- await checkGrant(grants, `settings.${source}.update(${path})`, `config:${path}`);
43
- }
44
- export function checkingGrants(claude, grants) {
45
- const gate = (call, item) => checkGrant(grants, call, item);
46
- return {
47
- ...claude,
48
- process: {
49
- async run(argv, init) {
50
- await checkRun(grants, 'process.run', argv);
51
- return claude.process.run(argv, init);
52
- },
53
- spawn(request) {
54
- const started = checkRun(grants, 'process.spawn', request.argv).then(() => claude.process.spawn(request));
55
- return spawned(started);
56
- },
57
- },
58
- fs: {
59
- ...claude.fs,
60
- async read(path) {
61
- await gate(`fs.read(${path})`, readItem(grants, path));
62
- return claude.fs.read(path);
63
- },
64
- async write(path, text) {
65
- await gate(`fs.write(${path})`, writeItem(grants, path));
66
- return claude.fs.write(path, text);
67
- },
68
- },
69
- http: {
70
- async fetch(url, init) {
71
- if (!grants.freeAddresses().has(init?.socketPath ?? addressOf(url)))
72
- await gate(`http.fetch(${url})`, `network:${init?.socketPath ?? hostOf(url)}`);
73
- return claude.http.fetch(url, init);
74
- },
75
- },
76
- session: {
77
- ...claude.session,
78
- append: async (args) => {
79
- await gate('send', 'prompt');
80
- return claude.session.append(args);
81
- },
82
- send: async (args) => {
83
- await gate('send', 'prompt');
84
- return claude.session.send(args);
85
- },
86
- },
87
- prompt: {
88
- submit: async (args) => {
89
- await gate('send', 'prompt');
90
- return claude.prompt.submit(args);
91
- },
92
- },
93
- command: {
94
- ...claude.command,
95
- run: async (args) => {
96
- await gate(`commands.run(${args.command})`, 'prompt');
97
- return claude.command.run(args);
98
- },
99
- },
100
- cmod: {
101
- async call(args) {
102
- const named = args.to === cmodPluginName ? conversationCalls[args.method] : undefined;
103
- const given = args.method === conversationMethods.act && isObject(args.input) ? String(args.input['action']) : undefined;
104
- const action = given !== undefined && isAct(given) ? given : undefined;
105
- const isThisSession = isObject(args.input) && args.input['session'] === (await claude.session.id());
106
- const isDropping = (args.method === conversationMethods.subscribe || args.method === conversationMethods.watchBefore) && isObject(args.input) && Array.isArray(args.input['subscriptions']) && args.input['subscriptions'].length === 0;
107
- if (named !== undefined && action !== undefined)
108
- await gate(action, actPermission(action, isObject(args.input) ? args.input['input'] : undefined));
109
- else if (named !== undefined && !isThisSession && !isDropping)
110
- await gate(named, 'conversation');
111
- return claude.cmod.call(args);
112
- },
113
- },
114
- model: {
115
- complete: async (...args) => {
116
- await gate('model.complete', 'model');
117
- return claude.model.complete(...args);
118
- },
119
- },
120
- agent: {
121
- ...claude.agent,
122
- async spawn(args) {
123
- await gate('startTask', 'tasks');
124
- return claude.agent.spawn(args);
125
- },
126
- },
127
- tool: {
128
- ...claude.tool,
129
- call: async (input) => {
130
- await gate(`tool.call(${input.tool})`, toolPermission(input.tool));
131
- return claude.tool.call(input);
132
- },
133
- },
134
- };
135
- }
136
- function spawned(started) {
137
- const result = started.then((stream) => stream.result);
138
- result.catch(() => undefined);
139
- const stream = {
140
- next: async () => (await started).next(),
141
- async return(value) {
142
- const [start] = await Promise.allSettled([started]);
143
- return start.status === 'fulfilled' ? start.value.return(value) : { done: true, value };
144
- },
145
- [Symbol.asyncIterator]: () => stream,
146
- result,
147
- };
148
- return stream;
149
- }
150
- export function itemOf(name, value) {
151
- return value === undefined ? name : `${name}:${value}`;
152
- }
153
- export function isCovered(granted, item, home) {
154
- if (granted.has(item))
155
- return true;
156
- const split = item.indexOf(':');
157
- if (split === -1)
158
- return false;
159
- const name = item.slice(0, split);
160
- if (name === 'config')
161
- return isSettingCovered(granted, item.slice(split + 1));
162
- const target = expanded(item.slice(split + 1), home);
163
- const values = [...granted].filter((each) => each.startsWith(`${name}:`)).map((each) => expanded(each.slice(name.length + 1), home));
164
- if (name === 'run')
165
- return values.includes('*') || values.includes(target);
166
- if (name === 'files')
167
- return values.some((each) => relativePath(each, target) !== undefined);
168
- return values.includes(target);
169
- }
170
- function readItem(grants, path) {
171
- if (grants.configRoot === undefined)
172
- return undefined;
173
- return relativePath(`${grants.configRoot}/projects`, path) === undefined ? undefined : 'conversation';
174
- }
175
- function writeItem(grants, path) {
176
- const root = grants.projectRoot();
177
- const settingsFiles = [...projectSettingsFiles.map((file) => `${root}/${file}`), ...(grants.configRoot === undefined ? [] : [`${grants.configRoot}/settings.json`])];
178
- if (settingsFiles.includes(path)) {
179
- throw new PermissionRefused(`${grants.name} writes ${path} by hand. Change Claude Code's settings with settings.user.update, settings.project.update, or settings.local.update, which keep the person's own edits and take the mod's values out when it is removed.`);
180
- }
181
- if (grants.freeFolders().some((folder) => relativePath(folder, path) !== undefined))
182
- return undefined;
183
- return `files:${path}`;
184
- }
185
- export function refusal(grants, call, item) {
186
- const { name } = grants;
187
- if (isCovered(new Set(grants.declared), item, grants.home))
188
- return `${name} calls ${call} without your grant to "${permissionWords(item)}". ${grantFix}`;
189
- return `${name} calls ${call}, which needs ${declaration(item, grants.home)} in package.json "cmod".`;
190
- }
191
- function declaration(item, home) {
192
- const split = item.indexOf(':');
193
- if (split === -1)
194
- return `"permissions": { "${item}": true }`;
195
- const name = item.slice(0, split);
196
- const target = item.slice(split + 1);
197
- const fromHome = home === undefined ? undefined : relativePath(home, target);
198
- const shown = name !== 'run' && fromHome !== undefined ? `~/${fromHome}` : target;
199
- return `"permissions": { "${name}": ["${shown}"] }`;
200
- }
201
- const classicParts = {
202
- additionalContext: 'prompt',
203
- initialUserMessage: 'prompt',
204
- updatedToolOutput: 'prompt',
205
- updatedMCPToolOutput: 'prompt',
206
- retry: 'approve',
207
- };
208
- const blocksKeepWorking = ['classic.Stop', 'classic.PostToolUse'];
209
- const reservedToolKeys = ['tool', 'tool_use_id'];
210
- export function checksAnswers(event) {
211
- return event.startsWith('classic.') || event === 'tool.check' || event === 'tool.call' || event === 'prompt.context' || event === 'prompt.submit';
212
- }
213
- export function passedDown(event, original, passed, check) {
214
- if (passed === original)
215
- return passed;
216
- if (event === 'tool.call') {
217
- if (sameExcept(original, passed, reservedToolKeys) || check.isGranted('tools'))
218
- return passed;
219
- check.dropped('tools', 'a changed tool input');
220
- return original;
221
- }
222
- if (event === 'prompt.context' || event === 'prompt.submit') {
223
- if (same(original, passed) || check.isGranted('prompt'))
224
- return passed;
225
- check.dropped('prompt', event === 'prompt.submit' ? 'a rewritten prompt' : 'changed context');
226
- return original;
227
- }
228
- return passed;
229
- }
230
- export async function checkedAnswer(event, e, answer, below, check) {
231
- if (!isFields(answer))
232
- return answer;
233
- if (event === 'tool.check')
234
- return decided(answer['decision'], answer, below, check);
235
- if (event === 'classic.PermissionRequest') {
236
- const decision = isFields(answer['decision']) ? answer['decision']['behavior'] : undefined;
237
- return decided(decision, answer, below, check);
238
- }
239
- if (event.startsWith('classic.'))
240
- return classicAnswer(event, answer, below, check);
241
- if (event === 'tool.call') {
242
- if (answer['deny'] !== undefined || check.isGranted('prompt'))
243
- return answer;
244
- const tool = isFields(e) ? e['tool'] : undefined;
245
- if (typeof tool === 'string' && tool.startsWith(`mcp__${check.plugin}__`)) {
246
- if (answer['context'] === undefined)
247
- return answer;
248
- check.dropped('prompt', 'context after a tool call');
249
- const { context: _context, ...rest } = answer;
250
- return rest;
251
- }
252
- const theirs = await below();
253
- if (same(answer, theirs))
254
- return answer;
255
- check.dropped('prompt', same(contextOf(answer), contextOf(theirs)) ? 'a changed tool result' : 'context after a tool call');
256
- return theirs;
257
- }
258
- if (event === 'prompt.submit' && answer['drop'] !== undefined)
259
- return answer;
260
- if (event === 'prompt.context' || event === 'prompt.submit') {
261
- if (check.isGranted('prompt'))
262
- return answer;
263
- const theirs = await below();
264
- if (same(answer, theirs))
265
- return answer;
266
- check.dropped('prompt', event === 'prompt.submit' ? 'a rewritten prompt' : 'changed context');
267
- return theirs;
268
- }
269
- return answer;
270
- }
271
- async function decided(decision, answer, below, check) {
272
- if ((decision !== 'allow' && decision !== 'ask') || check.isGranted('approve'))
273
- return answer;
274
- const theirs = await below();
275
- if (same(answer, theirs))
276
- return answer;
277
- check.dropped('approve', `${decision} on a tool call`);
278
- return theirs;
279
- }
280
- async function classicAnswer(event, answer, below, check) {
281
- const blocks = blocksKeepWorking.includes(event) ? [['block', 'prompt']] : [];
282
- const parts = [...Object.entries(classicParts), ...blocks].filter(([part, item]) => answer[part] !== undefined && !check.isGranted(item));
283
- if (parts.length === 0)
284
- return answer;
285
- const theirs = await below();
286
- const kept = { ...answer };
287
- const theirFields = isFields(theirs) ? theirs : {};
288
- for (const [part, item] of parts) {
289
- if (same(answer[part], theirFields[part]))
290
- continue;
291
- check.dropped(item, part);
292
- if (theirFields[part] === undefined)
293
- delete kept[part];
294
- else
295
- kept[part] = theirFields[part];
296
- }
297
- return kept;
298
- }
299
- function contextOf(answer) {
300
- return isFields(answer) ? answer['context'] : undefined;
301
- }
302
- function same(left, right) {
303
- return left === right || JSON.stringify(left) === JSON.stringify(right);
304
- }
305
- function sameExcept(left, right, keys) {
306
- if (!isFields(left) || !isFields(right))
307
- return same(left, right);
308
- const without = (fields) => Object.fromEntries(Object.entries(fields).filter(([key]) => !keys.includes(key)));
309
- return same(without(left), without(right));
310
- }
311
- function isFields(value) {
312
- return typeof value === 'object' && value !== null && !Array.isArray(value);
313
- }
314
- function programOf(argv) {
315
- const command = argv[0] ?? '';
316
- return command.slice(command.lastIndexOf('/') + 1);
317
- }
318
- function hostOf(url) {
319
- return URL.canParse(url) ? new URL(url).hostname : url;
320
- }
321
- function addressOf(url) {
322
- return URL.canParse(url) ? new URL(url).host : url;
323
- }
324
- function expanded(path, home) {
325
- return path.startsWith('~/') && home !== undefined ? `${home}${path.slice(1)}` : path;
326
- }
@@ -1,348 +0,0 @@
1
- import { grantFix, isObject, isSettingCovered, permissionWords, settingPaths } from '../records.js'
2
- import { relativePath } from '../utils/paths.js'
3
- import type { Claude } from './claude.js'
4
- import { cmodPluginName } from './dependencies.js'
5
- import type { RoutedEvent } from './hooks.js'
6
- import { actPermission, conversationMethods, isAct, toolPermission } from './sessions.js'
7
-
8
- export type Grants = {
9
- readonly name: string
10
- readonly declared: readonly string[]
11
- readonly granted: () => ReadonlySet<string>
12
- readonly refresh: () => Promise<void>
13
- readonly home: string | undefined
14
- readonly configRoot: string | undefined
15
- readonly projectRoot: () => string
16
- readonly freeFolders: () => readonly string[]
17
- readonly freeAddresses: () => ReadonlySet<string>
18
- }
19
-
20
- export class PermissionRefused extends Error {}
21
-
22
- const addressesOfPrograms = new WeakMap<object, Set<string>>()
23
-
24
- export function programAddresses(mod: object): Set<string> {
25
- const known = addressesOfPrograms.get(mod) ?? new Set<string>()
26
- addressesOfPrograms.set(mod, known)
27
- return known
28
- }
29
-
30
- const projectSettingsFiles: readonly string[] = ['.claude/settings.json', '.claude/settings.local.json', '.mcp.json']
31
-
32
- export const conversationCalls: Readonly<Record<string, string>> = {
33
- [conversationMethods.sessions]: 'sessions.list',
34
- [conversationMethods.search]: 'sessions.search',
35
- [conversationMethods.messages]: 'messages',
36
- [conversationMethods.turns]: 'turns',
37
- [conversationMethods.contexts]: 'contexts',
38
- [conversationMethods.tasks]: 'tasks',
39
- [conversationMethods.goal]: 'goal',
40
- [conversationMethods.updateGoal]: 'goal.update',
41
- [conversationMethods.subscribe]: 'on',
42
- [conversationMethods.watchBefore]: 'before',
43
- [conversationMethods.act]: 'act',
44
- }
45
-
46
- export async function checkGrant(grants: Grants, call: string, item: string | undefined): Promise<void> {
47
- if (item === undefined) return
48
- await grants.refresh()
49
- if (!isCovered(grants.granted(), item, grants.home)) throw new PermissionRefused(refusal(grants, call, item))
50
- }
51
-
52
- export async function checkRun(grants: Grants, call: 'process.run' | 'process.spawn', argv: readonly string[]): Promise<void> {
53
- await checkGrant(grants, `${call}(${argv.join(' ')})`, `run:${programOf(argv)}`)
54
- }
55
-
56
- export async function checkWrite(grants: Grants, call: string, path: string): Promise<void> {
57
- await checkGrant(grants, call, writeItem(grants, path))
58
- }
59
-
60
- export async function checkSettings(grants: Grants, source: 'user' | 'project' | 'local', values: Readonly<Record<string, unknown>>): Promise<void> {
61
- for (const path of settingPaths(values).map((each) => each.join('.'))) await checkGrant(grants, `settings.${source}.update(${path})`, `config:${path}`)
62
- }
63
-
64
- export function checkingGrants(claude: Claude, grants: Grants): Claude {
65
- const gate = (call: string, item: string | undefined) => checkGrant(grants, call, item)
66
- return {
67
- ...claude,
68
- process: {
69
- async run(argv, init) {
70
- await checkRun(grants, 'process.run', argv)
71
- return claude.process.run(argv, init)
72
- },
73
- spawn(request) {
74
- const started = checkRun(grants, 'process.spawn', request.argv).then(() => claude.process.spawn(request))
75
- return spawned(started)
76
- },
77
- },
78
- fs: {
79
- ...claude.fs,
80
- async read(path) {
81
- await gate(`fs.read(${path})`, readItem(grants, path))
82
- return claude.fs.read(path)
83
- },
84
- async write(path, text) {
85
- await gate(`fs.write(${path})`, writeItem(grants, path))
86
- return claude.fs.write(path, text)
87
- },
88
- },
89
- http: {
90
- async fetch(url, init) {
91
- if (!grants.freeAddresses().has(init?.socketPath ?? addressOf(url))) await gate(`http.fetch(${url})`, `network:${init?.socketPath ?? hostOf(url)}`)
92
- return claude.http.fetch(url, init)
93
- },
94
- },
95
- session: {
96
- ...claude.session,
97
- append: async (args: Parameters<Claude['session']['append']>[0]) => {
98
- await gate('send', 'prompt')
99
- return claude.session.append(args)
100
- },
101
- send: async (args: Parameters<Claude['session']['send']>[0]) => {
102
- await gate('send', 'prompt')
103
- return claude.session.send(args)
104
- },
105
- },
106
- prompt: {
107
- submit: async (args: Parameters<Claude['prompt']['submit']>[0]) => {
108
- await gate('send', 'prompt')
109
- return claude.prompt.submit(args)
110
- },
111
- },
112
- command: {
113
- ...claude.command,
114
- run: async (args: Parameters<Claude['command']['run']>[0]) => {
115
- await gate(`commands.run(${args.command})`, 'prompt')
116
- return claude.command.run(args)
117
- },
118
- },
119
- cmod: {
120
- async call(args) {
121
- const named = args.to === cmodPluginName ? conversationCalls[args.method] : undefined
122
- const given = args.method === conversationMethods.act && isObject(args.input) ? String(args.input['action']) : undefined
123
- const action = given !== undefined && isAct(given) ? given : undefined
124
- const isThisSession = isObject(args.input) && args.input['session'] === (await claude.session.id())
125
- const isDropping = (args.method === conversationMethods.subscribe || args.method === conversationMethods.watchBefore) && isObject(args.input) && Array.isArray(args.input['subscriptions']) && args.input['subscriptions'].length === 0
126
- if (named !== undefined && action !== undefined) await gate(action, actPermission(action, isObject(args.input) ? args.input['input'] : undefined))
127
- else if (named !== undefined && !isThisSession && !isDropping) await gate(named, 'conversation')
128
- return claude.cmod.call(args)
129
- },
130
- },
131
- model: {
132
- complete: async (...args: Parameters<Claude['model']['complete']>) => {
133
- await gate('model.complete', 'model')
134
- return claude.model.complete(...args)
135
- },
136
- },
137
- agent: {
138
- ...claude.agent,
139
- async spawn(args) {
140
- await gate('startTask', 'tasks')
141
- return claude.agent.spawn(args)
142
- },
143
- },
144
- tool: {
145
- ...claude.tool,
146
- call: async (input: Parameters<Claude['tool']['call']>[0]) => {
147
- await gate(`tool.call(${input.tool})`, toolPermission(input.tool))
148
- return claude.tool.call(input)
149
- },
150
- },
151
- }
152
- }
153
-
154
- type Stream = ReturnType<Claude['process']['spawn']>
155
-
156
- function spawned(started: Promise<Stream>): Stream {
157
- const result = started.then((stream) => stream.result)
158
- result.catch(() => undefined)
159
- const stream = {
160
- next: async () => (await started).next(),
161
- async return(value: never) {
162
- const [start] = await Promise.allSettled([started])
163
- return start.status === 'fulfilled' ? start.value.return(value) : { done: true as const, value }
164
- },
165
- [Symbol.asyncIterator]: () => stream,
166
- result,
167
- }
168
- return stream as unknown as Stream
169
- }
170
-
171
- export function itemOf(name: string, value?: string): string {
172
- return value === undefined ? name : `${name}:${value}`
173
- }
174
-
175
- export function isCovered(granted: ReadonlySet<string>, item: string, home: string | undefined): boolean {
176
- if (granted.has(item)) return true
177
- const split = item.indexOf(':')
178
- if (split === -1) return false
179
- const name = item.slice(0, split)
180
- if (name === 'config') return isSettingCovered(granted, item.slice(split + 1))
181
- const target = expanded(item.slice(split + 1), home)
182
- const values = [...granted].filter((each) => each.startsWith(`${name}:`)).map((each) => expanded(each.slice(name.length + 1), home))
183
- if (name === 'run') return values.includes('*') || values.includes(target)
184
- if (name === 'files') return values.some((each) => relativePath(each, target) !== undefined)
185
- return values.includes(target)
186
- }
187
-
188
- function readItem(grants: Grants, path: string): string | undefined {
189
- if (grants.configRoot === undefined) return undefined
190
- return relativePath(`${grants.configRoot}/projects`, path) === undefined ? undefined : 'conversation'
191
- }
192
-
193
- function writeItem(grants: Grants, path: string): string | undefined {
194
- const root = grants.projectRoot()
195
- const settingsFiles = [...projectSettingsFiles.map((file) => `${root}/${file}`), ...(grants.configRoot === undefined ? [] : [`${grants.configRoot}/settings.json`])]
196
- if (settingsFiles.includes(path)) {
197
- throw new PermissionRefused(`${grants.name} writes ${path} by hand. Change Claude Code's settings with settings.user.update, settings.project.update, or settings.local.update, which keep the person's own edits and take the mod's values out when it is removed.`)
198
- }
199
- if (grants.freeFolders().some((folder) => relativePath(folder, path) !== undefined)) return undefined
200
- return `files:${path}`
201
- }
202
-
203
- export function refusal(grants: Pick<Grants, 'name' | 'declared' | 'home'>, call: string, item: string): string {
204
- const { name } = grants
205
- if (isCovered(new Set(grants.declared), item, grants.home)) return `${name} calls ${call} without your grant to "${permissionWords(item)}". ${grantFix}`
206
- return `${name} calls ${call}, which needs ${declaration(item, grants.home)} in package.json "cmod".`
207
- }
208
-
209
- function declaration(item: string, home: string | undefined): string {
210
- const split = item.indexOf(':')
211
- if (split === -1) return `"permissions": { "${item}": true }`
212
- const name = item.slice(0, split)
213
- const target = item.slice(split + 1)
214
- const fromHome = home === undefined ? undefined : relativePath(home, target)
215
- const shown = name !== 'run' && fromHome !== undefined ? `~/${fromHome}` : target
216
- return `"permissions": { "${name}": ["${shown}"] }`
217
- }
218
-
219
- type Fields = Record<string, unknown>
220
-
221
- const classicParts: Readonly<Record<string, string>> = {
222
- additionalContext: 'prompt',
223
- initialUserMessage: 'prompt',
224
- updatedToolOutput: 'prompt',
225
- updatedMCPToolOutput: 'prompt',
226
- retry: 'approve',
227
- }
228
-
229
- const blocksKeepWorking: readonly RoutedEvent[] = ['classic.Stop', 'classic.PostToolUse']
230
-
231
- const reservedToolKeys: readonly string[] = ['tool', 'tool_use_id']
232
-
233
- export type AnswerCheck = {
234
- readonly plugin: string
235
- isGranted(item: string): boolean
236
- dropped(item: string, part: string): void
237
- }
238
-
239
- export function checksAnswers(event: RoutedEvent): boolean {
240
- return event.startsWith('classic.') || event === 'tool.check' || event === 'tool.call' || event === 'prompt.context' || event === 'prompt.submit'
241
- }
242
-
243
- export function passedDown(event: RoutedEvent, original: unknown, passed: unknown, check: AnswerCheck): unknown {
244
- if (passed === original) return passed
245
- if (event === 'tool.call') {
246
- if (sameExcept(original, passed, reservedToolKeys) || check.isGranted('tools')) return passed
247
- check.dropped('tools', 'a changed tool input')
248
- return original
249
- }
250
- if (event === 'prompt.context' || event === 'prompt.submit') {
251
- if (same(original, passed) || check.isGranted('prompt')) return passed
252
- check.dropped('prompt', event === 'prompt.submit' ? 'a rewritten prompt' : 'changed context')
253
- return original
254
- }
255
- return passed
256
- }
257
-
258
- export async function checkedAnswer(event: RoutedEvent, e: unknown, answer: unknown, below: () => Promise<unknown>, check: AnswerCheck): Promise<unknown> {
259
- if (!isFields(answer)) return answer
260
- if (event === 'tool.check') return decided(answer['decision'], answer, below, check)
261
- if (event === 'classic.PermissionRequest') {
262
- const decision = isFields(answer['decision']) ? answer['decision']['behavior'] : undefined
263
- return decided(decision, answer, below, check)
264
- }
265
- if (event.startsWith('classic.')) return classicAnswer(event, answer, below, check)
266
- if (event === 'tool.call') {
267
- if (answer['deny'] !== undefined || check.isGranted('prompt')) return answer
268
- const tool = isFields(e) ? e['tool'] : undefined
269
- if (typeof tool === 'string' && tool.startsWith(`mcp__${check.plugin}__`)) {
270
- if (answer['context'] === undefined) return answer
271
- check.dropped('prompt', 'context after a tool call')
272
- const { context: _context, ...rest } = answer
273
- return rest
274
- }
275
- const theirs = await below()
276
- if (same(answer, theirs)) return answer
277
- check.dropped('prompt', same(contextOf(answer), contextOf(theirs)) ? 'a changed tool result' : 'context after a tool call')
278
- return theirs
279
- }
280
- if (event === 'prompt.submit' && answer['drop'] !== undefined) return answer
281
- if (event === 'prompt.context' || event === 'prompt.submit') {
282
- if (check.isGranted('prompt')) return answer
283
- const theirs = await below()
284
- if (same(answer, theirs)) return answer
285
- check.dropped('prompt', event === 'prompt.submit' ? 'a rewritten prompt' : 'changed context')
286
- return theirs
287
- }
288
- return answer
289
- }
290
-
291
- async function decided(decision: unknown, answer: Fields, below: () => Promise<unknown>, check: AnswerCheck): Promise<unknown> {
292
- if ((decision !== 'allow' && decision !== 'ask') || check.isGranted('approve')) return answer
293
- const theirs = await below()
294
- if (same(answer, theirs)) return answer
295
- check.dropped('approve', `${decision} on a tool call`)
296
- return theirs
297
- }
298
-
299
- async function classicAnswer(event: RoutedEvent, answer: Fields, below: () => Promise<unknown>, check: AnswerCheck): Promise<unknown> {
300
- const blocks = blocksKeepWorking.includes(event) ? ([['block', 'prompt']] as const) : []
301
- const parts = [...Object.entries(classicParts), ...blocks].filter(([part, item]) => answer[part] !== undefined && !check.isGranted(item))
302
- if (parts.length === 0) return answer
303
- const theirs = await below()
304
- const kept: Fields = { ...answer }
305
- const theirFields = isFields(theirs) ? theirs : {}
306
- for (const [part, item] of parts) {
307
- if (same(answer[part], theirFields[part])) continue
308
- check.dropped(item, part)
309
- if (theirFields[part] === undefined) delete kept[part]
310
- else kept[part] = theirFields[part]
311
- }
312
- return kept
313
- }
314
-
315
- function contextOf(answer: unknown): unknown {
316
- return isFields(answer) ? answer['context'] : undefined
317
- }
318
-
319
- function same(left: unknown, right: unknown): boolean {
320
- return left === right || JSON.stringify(left) === JSON.stringify(right)
321
- }
322
-
323
- function sameExcept(left: unknown, right: unknown, keys: readonly string[]): boolean {
324
- if (!isFields(left) || !isFields(right)) return same(left, right)
325
- const without = (fields: Fields) => Object.fromEntries(Object.entries(fields).filter(([key]) => !keys.includes(key)))
326
- return same(without(left), without(right))
327
- }
328
-
329
- function isFields(value: unknown): value is Fields {
330
- return typeof value === 'object' && value !== null && !Array.isArray(value)
331
- }
332
-
333
- function programOf(argv: readonly string[]): string {
334
- const command = argv[0] ?? ''
335
- return command.slice(command.lastIndexOf('/') + 1)
336
- }
337
-
338
- function hostOf(url: string): string {
339
- return URL.canParse(url) ? new URL(url).hostname : url
340
- }
341
-
342
- function addressOf(url: string): string {
343
- return URL.canParse(url) ? new URL(url).host : url
344
- }
345
-
346
- function expanded(path: string, home: string | undefined): string {
347
- return path.startsWith('~/') && home !== undefined ? `${home}${path.slice(1)}` : path
348
- }