@cmodjs/core 4.2.0 → 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 (59) hide show
  1. package/docs/commands.md +4 -4
  2. package/docs/install-steps.md +4 -3
  3. package/docs/mod.md +9 -8
  4. package/docs/permissions.md +3 -3
  5. package/docs/testing.md +2 -0
  6. package/docs/ui.md +12 -3
  7. package/hotkeys.d.ts +1 -1
  8. package/hotkeys.d.ts.map +1 -1
  9. package/hotkeys.js +2 -0
  10. package/jobs/program.js +1 -1
  11. package/package.json +1 -1
  12. package/records.d.ts +9 -1
  13. package/records.d.ts.map +1 -1
  14. package/records.js +27 -6
  15. package/register.d.ts.map +1 -1
  16. package/register.js +1 -0
  17. package/runtime/announce.d.ts +2 -7
  18. package/runtime/announce.d.ts.map +1 -1
  19. package/runtime/announce.js +13 -52
  20. package/runtime/claude.d.ts +2 -1
  21. package/runtime/claude.d.ts.map +1 -1
  22. package/runtime/conversations.d.ts.map +1 -1
  23. package/runtime/conversations.js +24 -4
  24. package/runtime/grants.d.ts +1 -0
  25. package/runtime/grants.d.ts.map +1 -1
  26. package/runtime/grants.js +1 -1
  27. package/runtime/hotkeys.js +1 -1
  28. package/runtime/lifecycle.d.ts.map +1 -1
  29. package/runtime/lifecycle.js +27 -20
  30. package/runtime/sessions.d.ts +2 -1
  31. package/runtime/sessions.d.ts.map +1 -1
  32. package/runtime/sessions.js +5 -6
  33. package/runtime/toaster.d.ts +22 -1
  34. package/runtime/toaster.d.ts.map +1 -1
  35. package/runtime/toaster.js +69 -24
  36. package/runtime/ui.js +1 -1
  37. package/src/hotkeys.ts +2 -1
  38. package/src/jobs/program.ts +1 -1
  39. package/src/records.ts +29 -5
  40. package/src/register.ts +1 -0
  41. package/src/runtime/announce.ts +14 -56
  42. package/src/runtime/claude.ts +2 -0
  43. package/src/runtime/conversations.ts +25 -4
  44. package/src/runtime/grants.ts +1 -1
  45. package/src/runtime/hotkeys.ts +1 -1
  46. package/src/runtime/lifecycle.ts +27 -21
  47. package/src/runtime/sessions.ts +4 -5
  48. package/src/runtime/toaster.ts +68 -25
  49. package/src/runtime/ui.ts +1 -1
  50. package/src/testing/fake-claude.ts +2 -1
  51. package/src/testing.ts +7 -2
  52. package/src/utils/changelog.ts +0 -15
  53. package/testing/fake-claude.d.ts.map +1 -1
  54. package/testing/fake-claude.js +2 -1
  55. package/testing.d.ts.map +1 -1
  56. package/testing.js +7 -2
  57. package/utils/changelog.d.ts +0 -1
  58. package/utils/changelog.d.ts.map +1 -1
  59. package/utils/changelog.js +0 -15
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.2.0'
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 {}
@@ -8,14 +8,14 @@ import { homePrefix, ifMissing, relativePath } from '../utils/paths.js'
8
8
  import { firstLine, formatExit, messageOf } from '../utils/text.js'
9
9
  import type { Claude } from './claude.js'
10
10
  import { beforeDeadline } from './deadline.js'
11
- import { announcedOf, announcementMs, announcementOf } from './announce.js'
11
+ import { announcementMs, announcementOf } from './announce.js'
12
12
  import { bind } from './bound.js'
13
13
  import { serveConversations } from './conversations.js'
14
14
  import { answerCall, answeringOwnCalls, cmodPluginName, dependencyCalls, withBareRefusals } from './dependencies.js'
15
15
  import { keepEngine } from './engine.js'
16
16
  import { classicFailure, classicHook, userSkillHook, type Hook, type HookFields, type HookListener, type RoutedEvent } from './hooks.js'
17
17
  import type { PermissionRoutes } from './permission-check.js'
18
- import { checkedAnswer, checkingGrants, checkRun, checkSettings, checksAnswers, checkWrite, isCovered, itemOf, passedDown, programAddresses, type AnswerCheck, type Grants } from './grants.js'
18
+ import { checkedAnswer, checkingGrants, checkRun, checkSettings, checksAnswers, checkWrite, isCovered, itemOf, passedDown, programAddresses, refusal, type AnswerCheck, type Grants } from './grants.js'
19
19
  import { cmodError, locatingPrograms, readLines, spawnCmod, type Programs } from './programs.js'
20
20
  import { createModFiles, resolvedPath, type Places } from './metadata.js'
21
21
  import { fitsOption } from '../options.js'
@@ -33,7 +33,7 @@ import { createHotkeys } from './hotkeys.js'
33
33
  import { servePages, type Pages } from './pages.js'
34
34
  import { drawnParts, type DrawnParts } from './parts.js'
35
35
  import { createWatches } from './watches.js'
36
- import { createUi, partMethods, type BorrowedMarkdown, type PartDraw, type PartPress, type PartsUpdate, type SettingsTab, type ShownPages, type UiArea } from './ui.js'
36
+ import { createUi, partMethods, type BorrowedMarkdown, type PartDraw, type PartPress, type PartsUpdate, type ShownPages, type UiArea } from './ui.js'
37
37
  import { serveWidgets } from './widgets.js'
38
38
  import { Progress } from '../ui/components.js'
39
39
  import { Box, Text } from '../ui/elements.js'
@@ -192,8 +192,8 @@ export function createLifecycle<State extends object, Declared extends Options =
192
192
  const granted = new Set<string>()
193
193
  let activation: Promise<void> | undefined
194
194
  let mod: Mod<State> | undefined
195
- const openSettings = async (tab?: SettingsTab) => {
196
- await claude().cmod.call({ to: cmodPluginName, method: partMethods.changed, input: { requests: [{ settings: true, ...(tab === undefined ? {} : { tab }) }], isAsked: true } })
195
+ const openSettings = async () => {
196
+ await claude().cmod.call({ to: cmodPluginName, method: partMethods.changed, input: { requests: [{ settings: true }], isAsked: true } })
197
197
  }
198
198
  let imports: Imports | undefined
199
199
  let raise: SessionsClient['raise'] | undefined
@@ -233,7 +233,7 @@ export function createLifecycle<State extends object, Declared extends Options =
233
233
  phase = 'failed'
234
234
  failure ??= new Error(`${definition.name}: ${reason}${/[.!?]$/.test(reason) ? '' : '.'}${fix === undefined ? '' : ` ${fix}`}`, { cause: error })
235
235
  const again = retry === undefined ? {} : { retry: () => ((failure = undefined), stopRetrying(), retry().catch(report)) }
236
- toastFailure({ id: installId, message: reason, ...(fix === undefined ? {} : { description: fix }), ...(error === undefined ? {} : { error }), ...again })
236
+ toastFailure({ id: installId, message: reason, ...(fix === undefined ? {} : { description: fix }), ...(error === undefined ? {} : { error }), ...again, isCritical: true })
237
237
  watchRecord()
238
238
  }
239
239
 
@@ -293,7 +293,7 @@ export function createLifecycle<State extends object, Declared extends Options =
293
293
  runtime?.toaster.toast.dismiss(recordId)
294
294
  return programs?.refresh()
295
295
  }
296
- if (failed !== undefined) return void toastFailure({ id: recordId, message: failed, retry: record })
296
+ if (failed !== undefined) return void toastFailure({ id: recordId, message: failed, retry: record, isCritical: true })
297
297
  throw new Error(`cmod setup ${formatExit(code, lastError)}`)
298
298
  }
299
299
 
@@ -384,19 +384,17 @@ export function createLifecycle<State extends object, Declared extends Options =
384
384
  stopWatchingRecord()
385
385
  runtime.claude.ui.invalidate('ui.render')
386
386
  if (definition.name === cmodPluginName) runtime.claude.ui.invalidate('command.describe')
387
- void runSteps(active.mod).catch((error: unknown) => toastFailure({ id: 'cmod:steps', message: 'Its installer stopped', error }))
387
+ void runSteps(active.mod).catch((error: unknown) => toastFailure({ id: 'cmod:steps', message: 'Its installer stopped', error, isCritical: true }))
388
388
  const missed = missedSessionStart
389
389
  missedSessionStart = undefined
390
390
  if (missed !== undefined) await replaySessionStart(missed)
391
- const version = plugin.version ?? ''
392
- const announced = announcedOf(await runtime.claude.store.get(announcedKey))
393
- if (announced?.version === version) {
391
+ if ((await runtime.claude.store.get(announcedKey)) !== undefined) {
394
392
  runtime.toaster.toast.dismiss(installId)
395
393
  return
396
394
  }
397
- await runtime.claude.store.set(announcedKey, { version, added })
395
+ await runtime.claude.store.set(announcedKey, { version: plugin.version ?? '' })
398
396
  const { toaster } = runtime
399
- void announcementOf(runtime.claude, plugin, granted, added, announced, openSettings)
397
+ void announcementOf(runtime.claude, plugin, granted, added, openSettings)
400
398
  .then(({ message, ...options }) => toaster.toast.success(message, { id: installId, duration: announcementMs, ...options }))
401
399
  .catch((error: unknown) => toastFailure({ id: installId, message: 'Could not say what it installed', error }))
402
400
  }
@@ -631,13 +629,11 @@ export function createLifecycle<State extends object, Declared extends Options =
631
629
  dropped(item, part) {
632
630
  if (droppedParts.has(item)) return
633
631
  droppedParts.add(item)
634
- const declared = plugin?.steps.permissions ?? []
635
- const isDeclared = declared.includes(item)
636
- runtime?.toaster.toast.warning(`Answered ${part} without your grant to "${permissionWords(item)}", so cmod dropped it`, {
632
+ const isDeclared = (plugin?.steps.permissions ?? []).includes(item)
633
+ toastFailure({
637
634
  id: `dropped:${item}`,
635
+ message: `Answered ${part} without your grant to "${permissionWords(item)}", so cmod dropped it`,
638
636
  description: isDeclared ? grantFix : `It needs "permissions": { "${item}": true } in package.json "cmod".`,
639
- duration: Infinity,
640
- ...(isDeclared ? { action: { label: 'Settings', onClick: () => openSettings('permissions') } } : {}),
641
637
  })
642
638
  },
643
639
  }
@@ -686,7 +682,16 @@ export function createLifecycle<State extends object, Declared extends Options =
686
682
  async start(claudeCalls, read) {
687
683
  if (runtime !== undefined) return
688
684
  programs = locatingPrograms(claudeCalls)
689
- runtime = { claude: programs.claude, toaster: createToaster(claudeCalls, definition.name, () => plugin?.version, () => openSettings('permissions')) }
685
+ const callingCmod: Claude = {
686
+ ...claudeCalls,
687
+ cmod: {
688
+ async call(input) {
689
+ if (input.to === definition.name) await holdUntilStarted()
690
+ return answeringOwnCalls(claudeCalls, router).cmod.call(input)
691
+ },
692
+ },
693
+ }
694
+ runtime = { claude: programs.claude, toaster: createToaster(callingCmod, definition.name, () => plugin?.version) }
690
695
  readStarted = read
691
696
  try {
692
697
  drawCount = (await claudeCalls.clock.now()) * drawsPerMs
@@ -732,7 +737,7 @@ export function createLifecycle<State extends object, Declared extends Options =
732
737
  if (call.method === pendingStepsMethod) return { value: await pendingSteps(mod) } as EventResult<N>
733
738
  if (call.method === finishStepsMethod) {
734
739
  const active = mod
735
- const opened = await installer.collect(() => Promise.race([runSteps(active).catch((error: unknown) => void toastFailure({ id: 'cmod:steps', message: 'Could not finish the setup', error })), installer.shown()]))
740
+ const opened = await installer.collect(() => Promise.race([runSteps(active).catch((error: unknown) => void toastFailure({ id: 'cmod:steps', message: 'Could not finish the setup', error, isCritical: true })), installer.shown()]))
736
741
  return { value: opened } as EventResult<N>
737
742
  }
738
743
  }
@@ -780,7 +785,7 @@ async function createMod<State extends object, Declared extends Options>(definit
780
785
  home,
781
786
  configRoot,
782
787
  projectRoot: () => modState.root,
783
- freeFolders: () => [modState.root, runtime.dataFolder],
788
+ freeFolders: () => [modState.root, definition.name === cmodPluginName ? runtime.store : runtime.dataFolder],
784
789
  freeAddresses: () => programAddresses(mod),
785
790
  }
786
791
  const checked = checkingGrants(claude, grants)
@@ -838,6 +843,7 @@ async function createMod<State extends object, Declared extends Options>(definit
838
843
  claude: checked,
839
844
  report: (id, message, error) => report({ id, message, error }),
840
845
  isGranted: (permission) => flag(permission),
846
+ permissionRefusal: (call, permission) => refusal(grants, call, permission),
841
847
  hookOn: (hook, listener, failed) => hookOn(hook as Hook, listener as HookListener<Hook>, failed),
842
848
  routeOn: (event: RoutedEvent, hook: unknown, failed?: unknown) => router.add(event, hook as never, failed as never),
843
849
  permissionRoutes: runtime.permissionRoutes,
@@ -16,7 +16,6 @@ import { beforeAnswerKeys, foldAnswers, foldBefore, methodOf, takenAnswer, type
16
16
  import type { Claude } from './claude.js'
17
17
  import { cmodPluginName } from './dependencies.js'
18
18
  import { messageOf } from '../utils/text.js'
19
- import { grantFix, permissionWords } from '../records.js'
20
19
  import { listenerOf, PassedTimeout, withinTime, type ListenOptions, type ListenTime } from './deadline.js'
21
20
  import { callFiles, type HomeFolders, type HookFields } from './hooks.js'
22
21
  import type { PermissionRoutes } from './permission-check.js'
@@ -159,7 +158,7 @@ export function withoutPermissionCheck(name: string, hearer: string): string {
159
158
 
160
159
  export type HookOn = (hook: string, listener: (input: unknown) => HookFields | undefined | Promise<HookFields | undefined>, failed?: (input: unknown, error: Error) => HookFields | undefined) => Subscription
161
160
 
162
- export function createSessionsClient({ name, claude, report, isGranted, hookOn, routeOn, permissionRoutes }: { readonly name: string; readonly claude: Claude; readonly report: (id: string, message: string, error: unknown) => void; readonly isGranted: (permission: string) => boolean; readonly hookOn?: HookOn; readonly routeOn?: RouteOn; readonly permissionRoutes?: () => PermissionRoutes | undefined }): SessionsClient {
161
+ export function createSessionsClient({ name, claude, report, isGranted, permissionRefusal, hookOn, routeOn, permissionRoutes }: { readonly name: string; readonly claude: Claude; readonly report: (id: string, message: string, error: unknown) => void; readonly isGranted: (permission: string) => boolean; readonly permissionRefusal: (call: string, permission: string) => string; readonly hookOn?: HookOn; readonly routeOn?: RouteOn; readonly permissionRoutes?: () => PermissionRoutes | undefined }): SessionsClient {
163
162
  const call = <Answer>(method: string, input: unknown) => claude.cmod.call({ to: cmodPluginName, method, input }) as Promise<Answer>
164
163
  const listening = new Map<string, Set<Listening>>()
165
164
  const deciding = new Map<string, Set<Listening>>()
@@ -181,6 +180,7 @@ export function createSessionsClient({ name, claude, report, isGranted, hookOn,
181
180
  const heard = (from: Map<string, Set<Listening>>): Listened[] =>
182
181
  [...(from.get(key) ?? [])].map(({ event, matcher, options, scope }) => ({ event, matcher: matcher === undefined ? undefined : sentMatcher(matcher), ...(options.onFailure === 'refuse' ? { onFailure: 'refuse' as const, scope } : {}) }))
183
182
  const tracksTasks = [...(listening.get(key) ?? []), ...(deciding.get(key) ?? [])].some(({ scope }) => scope.task !== undefined || scope.isGoal === true)
183
+ if (tracksTasks) void learnTasks(key).catch((error: unknown) => report(`tasks:${key}`, 'Could not read the tasks it listens under', error))
184
184
  const subscriptions = [...heard(listening), ...(tracksTasks ? [{ event: TaskStart }] : [])]
185
185
  await call(conversationMethods.subscribe, { session: key, subscriptions }).catch((error: unknown) => report(`sessions:${key}`, `Hears nothing from ${key === everySession ? 'the other sessions' : `session ${key}`}`, error))
186
186
  await call(conversationMethods.watchBefore, { session: key, subscriptions: heard(deciding) }).catch((error: unknown) => report(`before:${key}`, `Changes nothing in ${key === everySession ? 'the other sessions' : `session ${key}`}`, error))
@@ -210,7 +210,6 @@ export function createSessionsClient({ name, claude, report, isGranted, hookOn,
210
210
  const set = into.get(key) ?? new Set()
211
211
  set.add(entry)
212
212
  into.set(key, set)
213
- if (scope.task !== undefined || scope.isGoal === true) void learnTasks(scope.session ?? current.id).catch((error: unknown) => report(`tasks:${key}`, 'Could not read the tasks it listens under', error))
214
213
  onChange(key)
215
214
  return {
216
215
  remove() {
@@ -248,7 +247,7 @@ export function createSessionsClient({ name, claude, report, isGranted, hookOn,
248
247
  if (answer === undefined || answer === null || (typeof answer === 'object' && 'refuse' in answer)) return answer
249
248
  const missing = answerPermissions(event, answer as Partial<Answers>).find((permission) => !isGranted(permission))
250
249
  if (missing === undefined) return answer
251
- throw new Error(`Its ${entry.method} answer changes nothing until you grant ${name} "${permissionWords(missing)}". ${grantFix}`)
250
+ throw new Error(permissionRefusal(`${entry.method} with the answer { ${Object.keys(answer).join(', ')} }`, missing))
252
251
  })
253
252
  const answer = await foldBefore(event, change, askers, (error) => report(`session:${methodOf('before', event)}`, `The ${methodOf('before', event)} listener failed`, error))
254
253
  return answer?.note === undefined ? answer : { ...answer, note: modNote(name, answer.note) }
@@ -507,7 +506,7 @@ export function createSessionsClient({ name, claude, report, isGranted, hookOn,
507
506
  const answer = commandListeners.beforeRun.size === 0 ? undefined : await raise('beforeRun', run)
508
507
  if (typeof answer?.['refuse'] === 'string') return { text: answer['refuse'] }
509
508
  const changes = answer !== undefined && isGranted('prompt') ? answer : undefined
510
- if (answer !== undefined && changes === undefined) report('session:beforeRun', 'The beforeRun listener failed', new Error(`${name}: its answer changes a command, which needs the prompt permission.`))
509
+ if (answer !== undefined && changes === undefined) report('session:beforeRun', 'The beforeRun listener failed', new Error(permissionRefusal(`beforeRun with the answer { ${Object.keys(answer).join(', ')} }`, 'prompt')))
511
510
  if (typeof changes?.['result'] === 'string') return { text: changes['result'], ...(typeof changes['exitCode'] === 'number' ? { exitCode: changes['exitCode'] } : {}) }
512
511
  const args = typeof changes?.['args'] === 'string' ? changes['args'] : e.args
513
512
  const ran = await next(args === e.args ? e : { ...e, args })