@cmodjs/core 4.1.1 → 4.3.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/docs/commands.md +4 -4
  2. package/docs/install-steps.md +4 -3
  3. package/docs/jobs.md +2 -0
  4. package/docs/mod.md +9 -8
  5. package/docs/permissions.md +3 -3
  6. package/docs/testing.md +2 -0
  7. package/docs/ui.md +12 -3
  8. package/hotkeys.d.ts +1 -1
  9. package/hotkeys.d.ts.map +1 -1
  10. package/hotkeys.js +2 -0
  11. package/jobs/program.js +1 -1
  12. package/jobs/tool.d.ts +1 -0
  13. package/jobs/tool.d.ts.map +1 -1
  14. package/jobs/tool.js +2 -2
  15. package/package.json +1 -1
  16. package/records.d.ts +9 -1
  17. package/records.d.ts.map +1 -1
  18. package/records.js +27 -6
  19. package/register.d.ts.map +1 -1
  20. package/register.js +1 -0
  21. package/runtime/announce.d.ts +2 -7
  22. package/runtime/announce.d.ts.map +1 -1
  23. package/runtime/announce.js +13 -52
  24. package/runtime/claude.d.ts +2 -1
  25. package/runtime/claude.d.ts.map +1 -1
  26. package/runtime/conversations.d.ts.map +1 -1
  27. package/runtime/conversations.js +24 -4
  28. package/runtime/grants.d.ts +1 -0
  29. package/runtime/grants.d.ts.map +1 -1
  30. package/runtime/grants.js +1 -1
  31. package/runtime/hotkeys.js +1 -1
  32. package/runtime/lifecycle.d.ts.map +1 -1
  33. package/runtime/lifecycle.js +27 -20
  34. package/runtime/sessions.d.ts +2 -1
  35. package/runtime/sessions.d.ts.map +1 -1
  36. package/runtime/sessions.js +5 -6
  37. package/runtime/toaster.d.ts +22 -1
  38. package/runtime/toaster.d.ts.map +1 -1
  39. package/runtime/toaster.js +69 -24
  40. package/runtime/ui.js +1 -1
  41. package/src/hotkeys.ts +2 -1
  42. package/src/jobs/program.ts +1 -1
  43. package/src/jobs/tool.ts +3 -2
  44. package/src/records.ts +29 -5
  45. package/src/register.ts +1 -0
  46. package/src/runtime/announce.ts +14 -56
  47. package/src/runtime/claude.ts +2 -0
  48. package/src/runtime/conversations.ts +25 -4
  49. package/src/runtime/grants.ts +1 -1
  50. package/src/runtime/hotkeys.ts +1 -1
  51. package/src/runtime/lifecycle.ts +27 -21
  52. package/src/runtime/sessions.ts +4 -5
  53. package/src/runtime/toaster.ts +68 -25
  54. package/src/runtime/ui.ts +1 -1
  55. package/src/testing/fake-claude.ts +3 -1
  56. package/src/testing.ts +7 -2
  57. package/src/utils/changelog.ts +0 -15
  58. package/testing/fake-claude.d.ts.map +1 -1
  59. package/testing/fake-claude.js +3 -1
  60. package/testing.d.ts.map +1 -1
  61. package/testing.js +7 -2
  62. package/utils/changelog.d.ts +0 -1
  63. package/utils/changelog.d.ts.map +1 -1
  64. package/utils/changelog.js +0 -15
@@ -1,9 +1,13 @@
1
1
  import { Box, Button, drawWith, Link, Text } from '../ui/elements.js';
2
2
  import { coreVersion, grantFix, installFix, isObject, secretFix } from '../records.js';
3
3
  import { firstLine, messageOf } from '../utils/text.js';
4
+ import { beforeDeadline } from './deadline.js';
5
+ import { cmodPluginName } from './dependencies.js';
6
+ export const failedMethod = 'cmod:failed';
4
7
  const githubRepository = /^https:\/\/github\.com\/([^/]+\/[^/#?]+?)(?:\.git)?(?:\/issues)?\/?$/;
5
8
  const linkLimit = 2048;
6
9
  const hiddenKey = 'cmod:hidden-failures';
10
+ const failedCallMs = 30_000;
7
11
  const defaultDuration = 4000;
8
12
  const visibleToasts = 3;
9
13
  const spinner = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
@@ -17,9 +21,10 @@ const icons = {
17
21
  warning: { glyph: '⚠', color: 'warning' },
18
22
  error: { glyph: '✗', color: 'error' },
19
23
  };
20
- export function createToaster(claude, name, version, openPermissions) {
24
+ export function createToaster(claude, name, version) {
21
25
  const entries = new Map();
22
26
  const hidden = new Map();
27
+ const sent = new Map();
23
28
  void claude.store.get(hiddenKey).then((saved) => {
24
29
  if (typeof saved !== 'object' || saved === null)
25
30
  return;
@@ -70,6 +75,10 @@ export function createToaster(claude, name, version, openPermissions) {
70
75
  });
71
76
  };
72
77
  const dismiss = (id) => {
78
+ if (id === undefined)
79
+ sent.clear();
80
+ else
81
+ sent.delete(String(id));
73
82
  for (const entry of entries.values()) {
74
83
  if (id !== undefined && entry.id !== id)
75
84
  continue;
@@ -133,33 +142,69 @@ export function createToaster(claude, name, version, openPermissions) {
133
142
  };
134
143
  const press = (entry, run) => () => void Promise.resolve()
135
144
  .then(run)
136
- .catch((error) => fail({ id: `press:${entry.id}`, message: `${entry.message}: the press failed`, error }));
137
- const fail = ({ id, message, error, description = error === undefined || describe(error) === message ? undefined : describe(error), retry }) => {
145
+ .catch((error) => fail({ id: `press:${entry.id}`, message: `${entry.message}: the press failed`, error, isCritical: true }));
146
+ const logFailure = (failure) => claude.cmod.call({ to: cmodPluginName, method: failedMethod, input: failure });
147
+ const showsToast = async (failure, isShown) => {
148
+ try {
149
+ const logged = logFailure(failure);
150
+ const answer = await (isShown ? logged : beforeDeadline(claude, { ms: failedCallMs }, failedMethod, logged));
151
+ if (isObject(answer) && typeof answer['showsToast'] === 'boolean')
152
+ return answer['showsToast'];
153
+ throw new Error(`cmod answered ${answer === undefined ? 'nothing' : JSON.stringify(answer)}, not { showsToast: true or false }`);
154
+ }
155
+ catch (error) {
156
+ claude.ui.log(`${name}: cmod kept no Log of ${failure.id}, so it shows the toast: ${messageOf(error)}`, { to: 'debug' });
157
+ return undefined;
158
+ }
159
+ };
160
+ const fail = ({ id, message, error, description = error === undefined || describe(error) === message ? undefined : describe(error), retry, isCritical = false }) => {
138
161
  const hides = `${version() ?? ''}\n${message}\n${error === undefined ? '' : describe(error)}`;
139
- if (hidden.get(id) === hides)
140
- return id;
141
- hidden.delete(id);
142
- const shown = entries.get(id);
143
- if (shown?.hides === hides && shown.trying === undefined && shown.options.description === description) {
144
- const previous = clockTime(shown.at);
145
- shown.at = new Date();
146
- if (clockTime(shown.at) !== previous)
147
- changed();
162
+ const at = new Date();
163
+ const repeat = `${hides}\n${description ?? ''}\n${at.toISOString().slice(0, 16)}`;
164
+ if (sent.get(id) === repeat)
148
165
  return id;
149
- }
166
+ sent.set(id, repeat);
150
167
  const stack = error instanceof Error && error.stack !== undefined ? `\n\n${error.stack}` : '';
151
- const details = async () => {
168
+ const details = async (failedAt) => {
152
169
  const modVersion = await claude.fs
153
170
  .read(`${claude.plugin.root}/.claude-plugin/plugin.json`)
154
171
  .then((text) => String(JSON.parse(text).version))
155
172
  .catch((failure) => `unknown (${messageOf(failure)})`);
156
- return `${name} ${modVersion}, @cmodjs/core ${coreVersion}, at ${(entries.get(id)?.at ?? new Date()).toISOString()}\n${message}${description === undefined ? '' : `\n${description}`}${stack}`;
173
+ return `${name} ${modVersion}, @cmodjs/core ${coreVersion}, at ${failedAt.toISOString()}\n${message}${description === undefined ? '' : `\n${description}`}${stack}`;
174
+ };
175
+ const text = `${message}\n${description ?? ''}`;
176
+ const isGrantRefusal = text.includes(grantFix);
177
+ const isShownAtOnce = isCritical && !isGrantRefusal;
178
+ const logged = async () => {
179
+ const contact = await contactOf(claude);
180
+ const failure = { mod: name, id, message, details: await details(at), at: at.toISOString(), isCritical, root: claude.plugin.root, ...(contact === undefined ? {} : { contact }) };
181
+ const shows = await showsToast(failure, isShownAtOnce);
182
+ if (isShownAtOnce)
183
+ return;
184
+ if (shows === undefined || (shows && !isGrantRefusal))
185
+ return show();
186
+ claude.ui.log(`${name}: ${message}${description === undefined ? '' : `: ${description}`}`, { to: 'debug' });
187
+ };
188
+ const show = () => {
189
+ if (hidden.get(id) === hides)
190
+ return;
191
+ hidden.delete(id);
192
+ const shown = entries.get(id);
193
+ if (shown?.hides === hides && shown.trying === undefined && shown.options.description === description) {
194
+ const previous = clockTime(shown.at);
195
+ shown.at = new Date();
196
+ if (clockTime(shown.at) !== previous)
197
+ changed();
198
+ return;
199
+ }
200
+ const actions = [...fixes, ...(retry === undefined ? [] : [{ label: 'Retry', onClick: tryAgain }]), { label: 'Report', onClick: startReporting }];
201
+ put('error', message, { id, ...(description === undefined ? {} : { description }), duration: Infinity }, actions, hides);
157
202
  };
158
203
  const startReporting = async () => {
159
204
  const shown = entries.get(id);
160
205
  if (shown === undefined)
161
206
  return;
162
- shown.reporting = { contact: await contactOf(claude), details: await details() };
207
+ shown.reporting = { contact: await contactOf(claude), details: await details(shown.at) };
163
208
  disarm(shown);
164
209
  changed();
165
210
  if (bandId === undefined)
@@ -184,14 +229,14 @@ export function createToaster(claude, name, version, openPermissions) {
184
229
  }
185
230
  }
186
231
  };
187
- const text = `${message}\n${description ?? ''}`;
188
232
  const fixes = [
189
- { sentence: grantFix, label: 'Settings', onClick: openPermissions },
190
233
  { sentence: installFix, label: 'Plugins', onClick: () => claude.command.run({ command: 'plugin' }) },
191
234
  { sentence: secretFix, label: 'Open /config', onClick: () => claude.command.run({ command: 'config' }) },
192
235
  ].filter(({ sentence }) => text.includes(sentence));
193
- const actions = [...fixes, ...(retry === undefined ? [] : [{ label: 'Retry', onClick: tryAgain }]), { label: 'Report', onClick: startReporting }];
194
- return put('error', message, { id, ...(description === undefined ? {} : { description }), duration: Infinity }, actions, hides);
236
+ if (isShownAtOnce)
237
+ show();
238
+ claude.clock.after(0, () => void logged());
239
+ return id;
195
240
  };
196
241
  const toggle = (entry) => () => {
197
242
  entry.isOpen = !entry.isOpen;
@@ -238,7 +283,7 @@ export function createToaster(claude, name, version, openPermissions) {
238
283
  const copied = await claude.ui.copy({ text: details });
239
284
  say(copied.isCopied ? 'Copied the error.' : `Could not copy it: ${copied.reason}`);
240
285
  };
241
- const report = contact === undefined ? [] : [Link({ href: reportLink(contact, name, entry.message, details), label: contact.kind === 'github' ? 'Report it on GitHub (opens your browser)' : 'Email the author (opens your mail app)' })];
286
+ const report = contact === undefined ? [] : [reportLink(contact, name, entry.message, details)];
242
287
  return [
243
288
  Text({ dimColor: true, children: 'Claude writes up the problem and files it with your tools. You approve each step before anything is posted.' }),
244
289
  Box({
@@ -309,7 +354,7 @@ async function contactOf(claude) {
309
354
  const address = isObject(author) ? author['email'] : undefined;
310
355
  return typeof address === 'string' && address !== '' ? { kind: 'email', address } : undefined;
311
356
  }
312
- function reportLink(contact, name, message, details) {
357
+ export function reportLink(contact, name, message, details) {
313
358
  const title = `${name}: ${message}`.slice(0, 120);
314
359
  const linkOf = (body) => contact.kind === 'github'
315
360
  ? `https://github.com/${contact.repository}/issues/new?title=${encodeURIComponent(title)}&body=${encodeURIComponent(body)}`
@@ -317,9 +362,9 @@ function reportLink(contact, name, message, details) {
317
362
  let body = details;
318
363
  while (linkOf(body).length > linkLimit && body.length > 0)
319
364
  body = `${body.slice(0, Math.floor(body.length * 0.8))}…`;
320
- return linkOf(body);
365
+ return Link({ href: linkOf(body), label: contact.kind === 'github' ? 'Report it on GitHub (opens your browser)' : 'Email the author (opens your mail app)' });
321
366
  }
322
- function reportPrompt(name, contact, details) {
367
+ export function reportPrompt(name, contact, details) {
323
368
  const where = contact === undefined
324
369
  ? `${name} names no place to report it, so find its author from its plugin.json or its marketplace.`
325
370
  : contact.kind === 'github'
package/runtime/ui.js CHANGED
@@ -605,7 +605,7 @@ export function createUi({ name, claude, router, report, announce, mod, borrowed
605
605
  await run(...args);
606
606
  }
607
607
  catch (error) {
608
- report({ id: known.id, message: 'Its button failed', error });
608
+ report({ id: known.id, message: 'Its button failed', error, isCritical: true });
609
609
  }
610
610
  };
611
611
  if (caller === cmodPluginName)
package/src/hotkeys.ts CHANGED
@@ -14,7 +14,7 @@ type Modifiers = 'ctrl' | 'alt' | 'shift' | 'meta' | 'ctrl+alt' | 'ctrl+shift' |
14
14
 
15
15
  export type Combo = `${Modifiers}+${Key}`
16
16
 
17
- export type HotkeyInit = { readonly title: string; readonly default: Combo }
17
+ export type HotkeyInit = { readonly title: string; readonly default?: Combo }
18
18
 
19
19
  export type Hotkeys = Readonly<Record<string, HotkeyInit>>
20
20
 
@@ -42,6 +42,7 @@ export function checkHotkeys(name: string, hotkeys: Hotkeys): Hotkeys {
42
42
  const at = `${name}: hotkeys.${key}`
43
43
  if (!hotkeyName.test(key)) throw new Error(`${at} is not a hotkey name. Use letters, digits, and _, starting with a letter.`)
44
44
  if (declared.title.trim() === '') throw new Error(`${at} needs a title, the label Settings shows beside its combo.`)
45
+ if (declared.default === undefined) continue
45
46
  if (!isCombo(declared.default)) throw new Error(`${at} defaults to "${String(declared.default)}", which is not a combo. Give one or two of ctrl, alt, shift, meta in that order, then a key, such as "ctrl+q" or "ctrl+shift+k".`)
46
47
  const taken = combos.get(declared.default)
47
48
  if (taken !== undefined) throw new Error(`${at} defaults to ${declared.default}, which hotkeys.${taken} has too. Give each hotkey its own combo.`)
@@ -44,7 +44,7 @@ export function program(options: { readonly command: readonly string[]; readonly
44
44
  failure = undefined
45
45
  void start()
46
46
  }
47
- report({ id: `program:${executable}`, message: `The ${executable} program stopped`, description: reason, retry })
47
+ report({ id: `program:${executable}`, message: `The ${executable} program stopped`, description: reason, retry, isCritical: true })
48
48
  for (const waiter of waiting.splice(0)) waiter.reject(failure)
49
49
  }
50
50
 
package/src/jobs/tool.ts CHANGED
@@ -15,9 +15,10 @@ export function tool<const Schema extends object = { type: 'object' }, State ext
15
15
  readonly name: string
16
16
  readonly description: string
17
17
  readonly inputSchema?: Schema
18
+ readonly isDeferred?: boolean
18
19
  readonly execute: (input: Schema extends JSONSchema ? FromSchema<Schema> : never, mod: Mod<State>) => unknown
19
20
  }): Job<Tool, State> {
20
- const { name, description, inputSchema, execute } = options
21
+ const { name, description, inputSchema, isDeferred, execute } = options
21
22
  return (job) => {
22
23
  const { mod, announce, reserveName } = job
23
24
  const { claude, router, report } = engineOf(mod)
@@ -29,7 +30,7 @@ export function tool<const Schema extends object = { type: 'object' }, State ext
29
30
 
30
31
  const validator = new Validator(inputSchema ?? { type: 'object' }, '2020-12', false)
31
32
  let registered: string | undefined
32
- claude.tool.register({ name, description, ...(inputSchema === undefined ? {} : { inputSchema: inputSchema as Record<string, unknown> }) }).then(
33
+ claude.tool.register({ name, description, ...(inputSchema === undefined ? {} : { inputSchema: inputSchema as Record<string, unknown> }), ...(isDeferred === undefined ? {} : { isDeferred }) }).then(
33
34
  (answer) => {
34
35
  registered = answer.tool
35
36
  },
package/src/records.ts CHANGED
@@ -10,6 +10,8 @@ export type InstallRecord = {
10
10
  uninstall: string | null
11
11
  program: string | null
12
12
  keys: Readonly<Record<string, string>>
13
+ permissions: readonly string[] | null
14
+ grantedOnUpdate: readonly string[]
13
15
  }
14
16
 
15
17
  export type Steps = {
@@ -123,6 +125,10 @@ function parseRecord(text: string, path: string): InstallRecord {
123
125
  if (program !== null && typeof program !== 'string') throw new Error(`${path} has a "program" that is neither a command name nor null. ${fix}`)
124
126
  const keys = value['keys'] ?? {}
125
127
  if (!isObject(keys) || Object.values(keys).some((command) => typeof command !== 'string')) throw new Error(`${path} has "keys" that are not key bindings. ${fix}`)
128
+ const permissions = value['permissions'] ?? null
129
+ if (permissions !== null && !isTextList(permissions)) throw new Error(`${path} has "permissions" that are not a list of permissions. ${fix}`)
130
+ const grantedOnUpdate = value['grantedOnUpdate'] ?? []
131
+ if (!isTextList(grantedOnUpdate)) throw new Error(`${path} has a "grantedOnUpdate" that is not a list of permissions. ${fix}`)
126
132
  return {
127
133
  name: value['name'] as string,
128
134
  version: value['version'] as string,
@@ -132,6 +138,8 @@ function parseRecord(text: string, path: string): InstallRecord {
132
138
  uninstall,
133
139
  program,
134
140
  keys: keys as Record<string, string>,
141
+ permissions,
142
+ grantedOnUpdate,
135
143
  }
136
144
  }
137
145
 
@@ -296,9 +304,21 @@ export function widgetsPath(store: string): string {
296
304
  return `${store}/widgets.json`
297
305
  }
298
306
 
307
+ export function preferencesPath(store: string): string {
308
+ return `${store}/preferences.json`
309
+ }
310
+
311
+ export type Preferences = { readonly asksBeforeUpdatePermissions: boolean; readonly showsInstalledModErrors: boolean }
312
+
313
+ export function parsePreferences(value: unknown, path: string): Preferences {
314
+ if (value === undefined) return { asksBeforeUpdatePermissions: false, showsInstalledModErrors: false }
315
+ if (!isObject(value) || ['asksBeforeUpdatePermissions', 'showsInstalledModErrors'].some((key) => value[key] !== undefined && typeof value[key] !== 'boolean')) throw new Error(`${path} is not a map of cmod's preferences to true or false. Delete it, and cmod uses its defaults.`)
316
+ return { asksBeforeUpdatePermissions: value['asksBeforeUpdatePermissions'] === true, showsInstalledModErrors: value['showsInstalledModErrors'] === true }
317
+ }
318
+
299
319
  export function parseConsent(value: unknown, path: string): Record<string, string[]> {
300
320
  if (value === undefined) return Object.create(null)
301
- if (!isObject(value) || Object.values(value).some((items) => !Array.isArray(items) || items.some((item) => typeof item !== 'string'))) {
321
+ if (!isObject(value) || !Object.values(value).every(isTextList)) {
302
322
  throw new Error(`${path} is not a map of plugin names to what each was approved for. Delete it, and cmod asks again.`)
303
323
  }
304
324
  return Object.assign(Object.create(null), value) as Record<string, string[]>
@@ -307,18 +327,18 @@ export function parseConsent(value: unknown, path: string): Record<string, strin
307
327
  function readHotkeys(hotkeys: unknown): Steps {
308
328
  if (hotkeys === undefined) return {}
309
329
  const fix = 'cmod check writes it from the hotkeys defineMod declares, so run cmod check.'
310
- if (!isObject(hotkeys) || !Object.values(hotkeys).every((each) => isObject(each) && typeof each['title'] === 'string' && typeof each['default'] === 'string')) throw new Error(`package.json "cmod.hotkeys" is not a map of hotkeys to their title and default combo. ${fix}`)
330
+ if (!isObject(hotkeys) || !Object.values(hotkeys).every((each) => isObject(each) && typeof each['title'] === 'string' && (each['default'] === undefined || typeof each['default'] === 'string'))) throw new Error(`package.json "cmod.hotkeys" is not a map of hotkeys to their title and optional default combo. ${fix}`)
311
331
  return { hotkeys: checkHotkeys('package.json "cmod"', hotkeys as Record<string, HotkeyInit>) }
312
332
  }
313
333
 
314
- export const coreVersion = '4.1.1'
334
+ export const coreVersion = '4.3.0'
315
335
 
316
336
  export function hotkeyCommand(mod: string, hotkey: string): string {
317
337
  return `${mod}--${hotkey}`
318
338
  }
319
339
 
320
340
  export function hotkeyBindings(mod: string, hotkeys: Hotkeys | undefined): Record<string, string> {
321
- return Object.fromEntries(Object.entries(hotkeys ?? {}).map(([name, { default: combo }]) => [combo, hotkeyCommand(mod, name)]))
341
+ return Object.fromEntries(Object.entries(hotkeys ?? {}).flatMap(([name, { default: combo }]) => (combo === undefined ? [] : [[combo, hotkeyCommand(mod, name)]])))
322
342
  }
323
343
 
324
344
  export function boundCombos(keybindings: unknown): Map<string, string> {
@@ -332,7 +352,7 @@ export function boundCombos(keybindings: unknown): Map<string, string> {
332
352
  }
333
353
 
334
354
  export function hotkeyWords(hotkeys: Hotkeys | undefined): string {
335
- return listed(Object.values(hotkeys ?? {}).map(({ title, default: combo }) => `${combo} to ${title}`))
355
+ return listed(Object.values(hotkeys ?? {}).flatMap(({ title, default: combo }) => (combo === undefined ? [] : [`${combo} to ${title}`])))
336
356
  }
337
357
 
338
358
  function readCommand(steps: Record<string, unknown>, key: 'install' | 'uninstall'): Steps {
@@ -443,3 +463,7 @@ export function isAtLeast(version: string, minimum: string): boolean {
443
463
  export function isObject(value: unknown): value is Record<string, unknown> {
444
464
  return typeof value === 'object' && value !== null && !Array.isArray(value)
445
465
  }
466
+
467
+ function isTextList(value: unknown): value is string[] {
468
+ return Array.isArray(value) && value.every((item) => typeof item === 'string')
469
+ }
package/src/register.ts CHANGED
@@ -23,6 +23,7 @@ async function startMod($: EngineInterface, eventInput: Frozen<Args<'session.sta
23
23
  ui: {
24
24
  log: (text, options) => $.ui.log(text, options),
25
25
  notice: (toolUseId, text) => $.ui.notice(toolUseId, text),
26
+ toast: (text, options) => $.ui.toast(text, options),
26
27
  invalidate: (event) => $.ui.invalidate(event),
27
28
  ask: (question, options) => $.ui.ask(question, options),
28
29
  open: (pane) => $.ui.open(pane),
@@ -1,63 +1,26 @@
1
- import { isObject, marketplaceOf, permissionWords } from '../records.js'
2
- import { changeLines, changelogSections, unreleased } from '../utils/changelog.js'
1
+ import { isObject, permissionWords } from '../records.js'
3
2
  import { ifMissing } from '../utils/paths.js'
4
3
  import { listed } from '../utils/text.js'
5
4
  import type { Claude } from './claude.js'
6
5
  import type { Plugin } from './lifecycle.js'
7
6
 
8
- export type Announced = { readonly version: string; readonly added: readonly string[] }
9
-
10
- export type Announcement = { readonly message: string; readonly description?: string; readonly action?: { readonly label: string; readonly onClick: () => unknown } }
7
+ export type Announcement = { readonly message: string; readonly description?: string; readonly action: { readonly label: string; readonly onClick: () => unknown } }
11
8
 
12
9
  export const announcementMs = 10_000
13
10
 
14
- const shownChanges = 3
15
-
16
- export function announcedOf(saved: unknown): Announced | undefined {
17
- if (typeof saved === 'string') return { version: saved, added: [] }
18
- if (!isObject(saved) || typeof saved['version'] !== 'string') return undefined
19
- return { version: saved['version'], added: Array.isArray(saved['added']) ? saved['added'].map(String) : [] }
20
- }
21
-
22
- export async function announcementOf(claude: Claude, plugin: Plugin, granted: ReadonlySet<string>, added: readonly string[], previous: Announced | undefined, openSettings: (tab?: 'changelog') => Promise<void>): Promise<Announcement> {
23
- const read = (path: string) => claude.fs.read(`${plugin.root}/${path}`).catch(ifMissing(undefined))
24
- const manifest = jsonOf(await read('.claude-plugin/plugin.json'))
25
- const field = (key: string) => (isObject(manifest) && typeof manifest[key] === 'string' ? manifest[key] : undefined)
26
- const open = (tab?: 'changelog') => () => openSettings(tab)
27
- if (previous === undefined) {
28
- const { program, hotkeys } = plugin.steps
29
- const rules = (await claude.fs.list(`${plugin.root}/rules`).catch(ifMissing([]))).filter((entry) => entry.kind === 'file' && entry.name.endsWith('.md')).map((entry) => entry.name.slice(0, -'.md'.length)).toSorted()
30
- const lines = [
31
- field('description'),
32
- added.length > 0 ? `Adds ${listed(added)}.` : undefined,
33
- rules.length > 0 ? `Adds ${rules.length} ${rules.length === 1 ? 'rule' : 'rules'}: ${listed(rules)}.` : undefined,
34
- program === undefined ? undefined : `Installed the ${program} program.`,
35
- ...Object.values(hotkeys ?? {}).map(({ title, default: combo }) => `Binds ${combo} to ${title}.`),
36
- ...[...granted].map((item) => `${permissionWords(item)}.`),
37
- ]
38
- return { message: 'Installed', ...described(lines), action: { label: 'Settings', onClick: open() } }
39
- }
40
- const version = plugin.version ?? ''
41
- const isCheckout = marketplaceOf(plugin.root, plugin.name) === undefined
42
- const sections = changelogSections((await read('CHANGELOG.md')) ?? '')
43
- const section = sections.find((each) => each.version === version) ?? (isCheckout ? sections.find((each) => each.version === unreleased) : undefined)
44
- const changes = section === undefined ? [] : changeLines(section.text)
45
- const nowAdded = added.filter((each) => !previous.added.includes(each))
46
- const gone = previous.added.filter((each) => !added.includes(each))
47
- const fallback = previous.added.length === 0 ? [] : [nowAdded.length > 0 ? `Now adds ${listed(nowAdded)}.` : undefined, gone.length > 0 ? `No longer adds ${listed(gone)}.` : undefined]
48
- const home = await claude.env.home()
49
- const folder = home !== undefined && plugin.root.startsWith(`${home}/`) ? `~${plugin.root.slice(home.length)}` : plugin.root
50
- const repository = field('repository')
11
+ export async function announcementOf(claude: Claude, plugin: Plugin, granted: ReadonlySet<string>, added: readonly string[], openSettings: () => Promise<void>): Promise<Announcement> {
12
+ const manifest = jsonOf(await claude.fs.read(`${plugin.root}/.claude-plugin/plugin.json`).catch(ifMissing(undefined)))
13
+ const { program, hotkeys } = plugin.steps
14
+ const rules = (await claude.fs.list(`${plugin.root}/rules`).catch(ifMissing([]))).filter((entry) => entry.kind === 'file' && entry.name.endsWith('.md')).map((entry) => entry.name.slice(0, -'.md'.length)).toSorted()
51
15
  const lines = [
52
- ...(changes.length === 0 ? fallback : changes.length > shownChanges ? [...changes.slice(0, shownChanges), '…'] : changes),
53
- `From ${previous.version}${isCheckout ? `, loaded from ${folder}` : ''}.`,
54
- repository === undefined || isCheckout ? undefined : `Release notes: ${repository.replace(/\/$/, '')}/releases/tag/v${version}`,
55
- ]
56
- return {
57
- message: `Updated to ${version}`,
58
- ...described(lines),
59
- ...(sections.length > 0 ? { action: { label: 'Changelog', onClick: open('changelog') } } : {}),
60
- }
16
+ isObject(manifest) && typeof manifest['description'] === 'string' ? manifest['description'] : undefined,
17
+ added.length > 0 ? `Adds ${listed(added)}.` : undefined,
18
+ rules.length > 0 ? `Adds ${rules.length} ${rules.length === 1 ? 'rule' : 'rules'}: ${listed(rules)}.` : undefined,
19
+ program === undefined ? undefined : `Installed the ${program} program.`,
20
+ ...Object.values(hotkeys ?? {}).flatMap(({ title, default: combo }) => (combo === undefined ? [] : [`Binds ${combo} to ${title}.`])),
21
+ ...[...granted].map((item) => `${permissionWords(item)}.`),
22
+ ].filter((line) => line !== undefined)
23
+ return { message: 'Installed', ...(lines.length === 0 ? {} : { description: lines.join('\n') }), action: { label: 'Settings', onClick: () => openSettings() } }
61
24
  }
62
25
 
63
26
  function jsonOf(text: string | undefined): unknown {
@@ -68,8 +31,3 @@ function jsonOf(text: string | undefined): unknown {
68
31
  throw error
69
32
  }
70
33
  }
71
-
72
- function described(lines: readonly (string | undefined)[]): { readonly description?: string } {
73
- const kept = lines.filter((line) => line !== undefined)
74
- return kept.length === 0 ? {} : { description: kept.join('\n') }
75
- }
@@ -31,6 +31,7 @@ import type {
31
31
  Settings,
32
32
  SettingsReadArgs,
33
33
  Timer,
34
+ ToastOptions,
34
35
  ToolSpec,
35
36
  UiCopyArgs,
36
37
  UiFocusArgs,
@@ -48,6 +49,7 @@ export type Claude = {
48
49
  readonly ui: {
49
50
  log(text: string, options?: UiLogOptions): void
50
51
  notice(toolUseId: string, text: string | undefined): void
52
+ toast(text: string, options?: ToastOptions): void
51
53
  invalidate(event: InvalidatableEventName): void
52
54
  ask(question: string, options?: readonly string[] | AskOptions): Promise<string>
53
55
  open(pane: PaneOpenArgs): Promise<UiOpenResult>
@@ -1,5 +1,5 @@
1
1
  import type { Args, EventResult, Frozen } from 'claude-code'
2
- import { consentPath, coreVersion, dataFolder, grantFix, isObject, parseConsent } from '../records.js'
2
+ import { consentPath, coreVersion, dataFolder, isObject, parseConsent, readRecord, readSteps } from '../records.js'
3
3
  import { Message, rowOfAppend, type Row } from '../session/context/turn/message/message.js'
4
4
  import { modNote, Note } from '../session/context/turn/message/note.js'
5
5
  import { Person } from '../session/context/turn/message/sender.js'
@@ -15,6 +15,7 @@ import { formatExit, messageOf } from '../utils/text.js'
15
15
  import { beforeAnswerKeys, foldBefore, installBefore, relayOf, type Decide, type Place } from './before.js'
16
16
  import type { Claude } from './claude.js'
17
17
  import { cmodPluginName } from './dependencies.js'
18
+ import { conversationCalls, refusal } from './grants.js'
18
19
  import { readLines, runCmod, spawnCmod } from './programs.js'
19
20
  import type { RoutedHook, Router } from './router.js'
20
21
  import { PassedTimeout } from './deadline.js'
@@ -137,6 +138,26 @@ export function serveConversations({
137
138
  return (parseConsent(JSON.parse(text), path)[caller] ?? []).includes(item)
138
139
  }
139
140
 
141
+ const declaredBy = async (caller: string): Promise<readonly string[] | undefined> => {
142
+ const read = (path: string) => claude.fs.read(path).catch(ifMissing(undefined))
143
+ const record = await readRecord(read, store, caller)
144
+ if (record === undefined) return undefined
145
+ if (record.permissions !== null) return record.permissions
146
+ const pkg = await read(`${record.root}/package.json`)
147
+ return pkg === undefined ? undefined : (readSteps(JSON.parse(pkg))?.permissions ?? [])
148
+ }
149
+
150
+ const refused = async (caller: string | undefined, call: string, item: string) => {
151
+ const declared =
152
+ caller === undefined
153
+ ? undefined
154
+ : await declaredBy(caller).catch((error: unknown) => {
155
+ claude.ui.log(`cmod: its refusal of ${caller} names the grant, because the permissions ${caller} declares are unreadable: ${messageOf(error)}`, { to: 'debug' })
156
+ return undefined
157
+ })
158
+ return refusal({ name: caller ?? 'A mod', declared: declared ?? [item], home: undefined }, call, item)
159
+ }
160
+
140
161
 
141
162
  const ended = (id: string) => new Error(`session ${id} has ended`)
142
163
 
@@ -338,7 +359,7 @@ export function serveConversations({
338
359
  }
339
360
 
340
361
  const askHere = async (mod: string, event: BeforeEvent, change: SessionChange, from = session, isInProject = true) => {
341
- if (from !== session && !(await isGranted(mod, 'conversation'))) throw new Error(`${mod} needs the conversation permission to change what happens in another session. ${grantFix}`)
362
+ if (from !== session && !(await isGranted(mod, 'conversation'))) throw new Error(await refused(mod, 'before', 'conversation'))
342
363
  return claude.cmod.call({ to: mod, method: conversationMethods.before, input: { session: from, event, change, isInProject } })
343
364
  }
344
365
 
@@ -542,7 +563,7 @@ export function serveConversations({
542
563
 
543
564
  const checkAct = async (caller: string, action: Act, input: unknown) => {
544
565
  const needed = actPermission(action, input)
545
- if (needed !== undefined && !(await isGranted(caller, needed))) throw new Error(`${caller} needs the ${needed} permission for ${action}. ${grantFix}`)
566
+ if (needed !== undefined && !(await isGranted(caller, needed))) throw new Error(await refused(caller, action, needed))
546
567
  }
547
568
 
548
569
  const perform = async (caller: string, action: Act, input: unknown, task: string | undefined): Promise<unknown> => {
@@ -803,7 +824,7 @@ export function serveConversations({
803
824
  if (method === undefined) return undefined
804
825
  const input = isObject(e.input) ? e.input : {}
805
826
  const isDropping = (e.method === conversationMethods.subscribe || e.method === conversationMethods.watchBefore) && Array.isArray(input['subscriptions']) && input['subscriptions'].length === 0
806
- if (e.method !== conversationMethods.act && !isDropping && input['session'] !== (await claude.session.id()) && !(await isGranted(e.caller, 'conversation'))) return { deny: `${e.caller ?? 'A mod'} reads your conversations without your grant. ${grantFix}` }
827
+ if (e.method !== conversationMethods.act && !isDropping && input['session'] !== (await claude.session.id()) && !(await isGranted(e.caller, 'conversation'))) return { deny: await refused(e.caller, conversationCalls[e.method] ?? e.method, 'conversation') }
807
828
  try {
808
829
  return { value: await method(input, e.caller) }
809
830
  } catch (error) {
@@ -29,7 +29,7 @@ export function programAddresses(mod: object): Set<string> {
29
29
 
30
30
  const projectSettingsFiles: readonly string[] = ['.claude/settings.json', '.claude/settings.local.json', '.mcp.json']
31
31
 
32
- const conversationCalls: Readonly<Record<string, string>> = {
32
+ export const conversationCalls: Readonly<Record<string, string>> = {
33
33
  [conversationMethods.sessions]: 'sessions.list',
34
34
  [conversationMethods.search]: 'sessions.search',
35
35
  [conversationMethods.messages]: 'messages',
@@ -61,7 +61,7 @@ export async function createHotkeys({
61
61
  try {
62
62
  await listener()
63
63
  } catch (error) {
64
- report({ id: `hotkey:${hotkey}`, message: `The ${declared[hotkey]?.title ?? hotkey} hotkey failed`, error })
64
+ report({ id: `hotkey:${hotkey}`, message: `The ${declared[hotkey]?.title ?? hotkey} hotkey failed`, error, isCritical: true })
65
65
  }
66
66
  }
67
67
  return {}