@cmodjs/core 4.3.4 → 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 (60) hide show
  1. package/README.md +1 -1
  2. package/docs/commands.md +19 -30
  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 +3 -3
  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/src/jobs/program.ts +3 -17
  42. package/src/mod.ts +0 -18
  43. package/src/records.ts +20 -55
  44. package/src/runtime/announce.ts +2 -3
  45. package/src/runtime/conversations.ts +3 -45
  46. package/src/runtime/engine.ts +2 -2
  47. package/src/runtime/installer.ts +1 -37
  48. package/src/runtime/lifecycle.ts +38 -188
  49. package/src/runtime/metadata.ts +0 -3
  50. package/src/runtime/sessions.ts +10 -39
  51. package/src/runtime/toaster.ts +6 -9
  52. package/src/testing.ts +9 -14
  53. package/testing.d.ts +0 -1
  54. package/testing.d.ts.map +1 -1
  55. package/testing.js +9 -13
  56. package/docs/permissions.md +0 -97
  57. package/runtime/grants.d.ts +0 -34
  58. package/runtime/grants.d.ts.map +0 -1
  59. package/runtime/grants.js +0 -326
  60. package/src/runtime/grants.ts +0 -348
@@ -1,9 +1,9 @@
1
1
  import type { Args, Caught, ClassicHookInputs, EventResult, Frozen, HookBudget, PluginOptions, RenderElement, Timer } from 'claude-code'
2
2
  import type { Step } from '../installer.js'
3
3
 
4
- import type { Allowed, Imports, Mod, ModDefinition, Reservation, SettingsFile, SettingsFileChange, SettingsFileChangeListener, Subscription, Timer as ModTimer } from '../mod.js'
4
+ import type { Imports, Mod, ModDefinition, Reservation, SettingsFile, SettingsFileChange, SettingsFileChangeListener, Subscription, Timer as ModTimer } from '../mod.js'
5
5
  import type { Options, OptionValues } from '../options.js'
6
- import { consentPath, dataFolder, finishStepsMethod, grantFix, coreVersion, isAtLeast, isProgramNewer, marketplaceOf, parseConsent, pendingStepsMethod, parseEvent, permissionWords, programPath, readCmodVersion, readRecord, readSteps, recordPath, scriptsSha256, storeFolder, updatesToTurnOn, type ReadFile, type RunnerEvent, type Steps } from '../records.js'
6
+ import { dataFolder, finishStepsMethod, isAtLeast, isProgramNewer, oldestCmodVersion, pendingStepsMethod, parseEvent, programPath, readCmodVersion, readRecord, readSteps, recordPath, scriptsSha256, storeFolder, type ReadFile, type RunnerEvent, type Steps } from '../records.js'
7
7
  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'
@@ -15,7 +15,6 @@ import { answerCall, answeringOwnCalls, cmodPluginName, dependencyCalls, withBar
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, refusal, type AnswerCheck, type Grants } from './grants.js'
19
18
  import { cmodError, locatingPrograms, readLines, spawnCmod, type Programs } from './programs.js'
20
19
  import { createModFiles, resolvedPath, type Places } from './metadata.js'
21
20
  import { fitsOption } from '../options.js'
@@ -46,10 +45,9 @@ export type Plugin = {
46
45
  readonly isInstalled: boolean
47
46
  readonly shouldRecord: boolean
48
47
  readonly steps: Steps
49
- readonly granted: readonly string[]
50
48
  }
51
49
 
52
- export type Phase = 'starting' | 'installing' | 'waiting' | 'declined' | 'failed' | 'ready' | 'active'
50
+ export type Phase = 'starting' | 'installing' | 'waiting' | 'failed' | 'ready' | 'active'
53
51
 
54
52
  export type Lifecycle<State extends object> = {
55
53
  readonly phase: Phase
@@ -68,9 +66,6 @@ type ModRuntime = {
68
66
  readonly toaster: Toaster
69
67
  readonly dataFolder: string
70
68
  readonly store: string
71
- readonly steps: Steps
72
- readonly granted: ReadonlySet<string>
73
- readonly refreshGrants: () => Promise<void>
74
69
  readonly permissionRoutes: () => PermissionRoutes | undefined
75
70
  readonly options: PluginOptions
76
71
  readonly nextDraw: () => number
@@ -125,13 +120,11 @@ export async function readPlugin(claude: Claude): Promise<Plugin> {
125
120
  const version = typeof manifest?.version === 'string' ? manifest.version : undefined
126
121
  const store = storeFolder({ HOME: await claude.env.home(), XDG_DATA_HOME: await claude.env.dataHome() })
127
122
  const steps = readSteps(await readJson(read, `${root}/package.json`)) ?? {}
128
- const declared = steps.permissions ?? []
129
123
  if (name === cmodPluginName) {
130
124
  const installed = await cmodVersion(claude)
131
- return { name, root, version, store, steps, granted: declared, isInstalled: version !== undefined && installed !== undefined && isAtLeast(installed, version), shouldRecord: false }
125
+ return { name, root, version, store, steps, isInstalled: version !== undefined && installed !== undefined && isAtLeast(installed, version), shouldRecord: false }
132
126
  }
133
- const approved = parseConsent(await readJson(read, consentPath(store)), consentPath(store))[name] ?? []
134
- const plugin = { name, root, version, store, steps, granted: declared.filter((item) => approved.includes(item)) }
127
+ const plugin = { name, root, version, store, steps }
135
128
  const record = await readRecord(read, store, name)
136
129
  if (Object.keys(steps).length === 0) return { ...plugin, isInstalled: true, shouldRecord: record?.version !== version }
137
130
  const scripts = await scriptsSha256(steps, {
@@ -188,7 +181,6 @@ export function createLifecycle<State extends object, Declared extends Options =
188
181
  let runtime: Pick<ModRuntime, 'claude' | 'toaster'> | undefined
189
182
  let programs: Programs | undefined
190
183
  let plugin: Plugin | undefined
191
- const granted = new Set<string>()
192
184
  let activation: Promise<void> | undefined
193
185
  let mod: Mod<State> | undefined
194
186
  const openSettings = async () => {
@@ -236,8 +228,7 @@ export function createLifecycle<State extends object, Declared extends Options =
236
228
  watchRecord()
237
229
  }
238
230
 
239
- let consented: string | undefined
240
- const installAgain = () => install(consented)
231
+ const installAgain = () => install()
241
232
  const updateAgain = () => claude().store.delete(cmodUpdatedKey).then(installAgain)
242
233
 
243
234
  type Retrying = { readonly when: 'changed' | 'later'; readonly tries: number; readonly reason: string; readonly timer: Timer }
@@ -269,7 +260,7 @@ export function createLifecycle<State extends object, Declared extends Options =
269
260
  stopRetrying()
270
261
  return whenActive()
271
262
  }
272
- await install(consented, true)
263
+ await install(true)
273
264
  await whenActive()
274
265
  }
275
266
 
@@ -367,7 +358,7 @@ export function createLifecycle<State extends object, Declared extends Options =
367
358
  const activate = async (): Promise<void> => {
368
359
  if (runtime === undefined || plugin === undefined) return
369
360
  const activeRouter = createRouter()
370
- const active = await createMod(definition, { ...runtime, router: activeRouter, dataFolder: dataFolder(plugin.store, plugin.name), store: plugin.store, steps: plugin.steps, granted, refreshGrants, permissionRoutes, options: pluginOptions, nextDraw }).catch(async (error: unknown) => {
361
+ const active = await createMod(definition, { ...runtime, router: activeRouter, dataFolder: dataFolder(plugin.store, plugin.name), store: plugin.store, permissionRoutes, options: pluginOptions, nextDraw }).catch(async (error: unknown) => {
371
362
  if (error instanceof MissingOptions && (await askOptions(error))) return undefined
372
363
  await installer.close()
373
364
  fail(messageOf(error), error instanceof MissingOptions ? `Retry asks for ${error.keys.length === 1 ? 'it' : 'them'}.` : undefined, begin, error)
@@ -393,15 +384,14 @@ export function createLifecycle<State extends object, Declared extends Options =
393
384
  }
394
385
  await runtime.claude.store.set(announcedKey, { version: plugin.version ?? '' })
395
386
  const { toaster } = runtime
396
- void announcementOf(runtime.claude, plugin, granted, added, openSettings)
387
+ void announcementOf(runtime.claude, plugin, added, openSettings)
397
388
  .then(({ message, ...options }) => toaster.toast.success(message, { id: installId, duration: announcementMs, ...options }))
398
389
  .catch((error: unknown) => toastFailure({ id: installId, message: 'Could not say what it installed', error }))
399
390
  }
400
391
 
401
392
  const replaySessionStart = async (e: Frozen<Args<'classic.SessionStart'>>) => {
402
393
  hasHeardSessionStart = true
403
- const ran = definition.name === cmodPluginName ? router.dispatch('classic.SessionStart', e, async () => ({})) : checkedRoute('classic.SessionStart', e, async () => ({}))
404
- const answer = await ran.catch((error: unknown) => {
394
+ const answer = await router.dispatch('classic.SessionStart', e, async () => ({})).catch((error: unknown) => {
405
395
  toastFailure({ id: 'classic.SessionStart', message: 'The SessionStart hook failed', error })
406
396
  return {}
407
397
  })
@@ -415,42 +405,7 @@ export function createLifecycle<State extends object, Declared extends Options =
415
405
  }
416
406
  }
417
407
 
418
- const updatesToShow = async () => {
419
- const [home, configHome] = await Promise.all([claude().env.home(), claude().env.configHome()])
420
- const configRoot = configHome ?? `${home ?? ''}/.claude`
421
- const known = await claude()
422
- .fs.read(`${configRoot}/plugins/known_marketplaces.json`)
423
- .then((text): unknown => JSON.parse(text))
424
- .catch(ifMissing(undefined))
425
- return updatesToTurnOn(marketplaceOf(claude().plugin.root, claude().plugin.name), await claude().settings.read({ source: 'user' }), known)
426
- }
427
-
428
- const askConsent = async (event: Extract<RunnerEvent, { type: 'needs-consent' }>) => {
429
- const name = definition.name
430
- if ((await claude().session.surfaces()).length === 0) {
431
- claude().ui.log(`${name} waits for consent to run ${event.install}. Run cmod install ${name} in a terminal.`)
432
- return
433
- }
434
- const updates = await updatesToShow().catch((error: unknown) => {
435
- toastFailure({ id: 'cmod:updates', message: 'Could not read whether its marketplace updates automatically', error })
436
- return undefined
437
- })
438
- const installedElsewhere = new Promise<'installed'>((resolve) => (settleAsked = () => resolve('installed')))
439
- watchRecord()
440
- const answer = await Promise.race([installer.consent({ ...event, program: plugin?.steps.program ?? '', updates }), installedElsewhere]).finally(() => {
441
- settleAsked = undefined
442
- })
443
- await installer.close()
444
- if (answer === 'installed') return startInstalled()
445
- if (answer) {
446
- consented = event.sha256
447
- return install(consented)
448
- }
449
- phase = 'declined'
450
- runtime?.toaster.toast('Not installed', { id: installId, description: 'Install it whenever you like.', duration: Infinity, action: { label: 'Install', onClick: () => install().catch(report) } })
451
- }
452
-
453
- const install = async (consent?: string, isQuiet = false): Promise<void> => {
408
+ const install = async (isQuiet = false): Promise<void> => {
454
409
  if (plugin === undefined) return
455
410
  if (plugin.name === cmodPluginName) return bootstrap(plugin.root)
456
411
  phase = 'installing'
@@ -459,23 +414,20 @@ export function createLifecycle<State extends object, Declared extends Options =
459
414
  if (!isQuiet) installing()
460
415
  let outcome: RunnerEvent | undefined
461
416
  let retries: 'changed' | 'later' | undefined
462
- const argv = ['cmod', 'setup', plugin.root, '--events', ...(consent === undefined ? [] : ['--consent', consent])]
463
- const { code, lastError } = await readLines(claude().process.spawn({ argv }), (text) => {
417
+ const { code, lastError } = await readLines(claude().process.spawn({ argv: ['cmod', 'setup', plugin.root, '--events'] }), (text) => {
464
418
  const event = parseEvent(text)
465
419
  if (event.type === 'progress' && !isQuiet) installing(progressOf(event))
466
420
  if (event.type === 'retries') retries = event.when
467
- if (event.type === 'done' || event.type === 'failed' || event.type === 'needs-consent') outcome = event
421
+ if (event.type === 'done' || event.type === 'failed') outcome = event
468
422
  })
469
423
  if (outcome?.type === 'done') {
470
424
  stopRetrying()
471
- for (const item of plugin.steps.permissions ?? []) granted.add(item)
472
425
  return finish()
473
426
  }
474
- if (outcome?.type === 'needs-consent') return askConsent(outcome)
475
427
  return failInstall(outcome?.type === 'failed' ? outcome.message : `cmod setup ${formatExit(code, lastError)}`, retries)
476
428
  }
477
429
 
478
- const fits = (found: string | undefined): found is string => found !== undefined && isAtLeast(found, coreVersion)
430
+ const fits = (found: string | undefined): found is string => found !== undefined && isAtLeast(found, oldestCmodVersion)
479
431
 
480
432
  const waitForcmod = (found: string | undefined) => {
481
433
  phase = 'waiting'
@@ -507,20 +459,20 @@ export function createLifecycle<State extends object, Declared extends Options =
507
459
  timer = poll(cmodSlowCheckMs)
508
460
  if (latest === undefined) return installing("Still waiting for cmod to download cmod. See cmod's own line.")
509
461
  const found = latest
510
- const tried = `${found} to ${coreVersion}`
462
+ const tried = `${found} to ${oldestCmodVersion}`
511
463
  return claude()
512
464
  .store.get(cmodUpdatedKey)
513
465
  .then(async (updated) => {
514
466
  if (updated === tried) {
515
467
  stop()
516
- return fail(`${definition.name} needs cmod ${coreVersion} or later, and the newest cmod is ${found}.`, undefined, updateAgain)
468
+ return fail(`${definition.name} needs cmod ${oldestCmodVersion} or later, and the newest cmod is ${found}.`, undefined, updateAgain)
517
469
  }
518
470
  await claude().store.set(cmodUpdatedKey, tried)
519
- installing(`${definition.name} needs cmod ${coreVersion} or later, and this computer has cmod ${found}, so cmod is updating itself.`)
471
+ installing(`${definition.name} needs cmod ${oldestCmodVersion} or later, and this computer has cmod ${found}, so cmod is updating itself.`)
520
472
  const { code, lastError } = await readLines(claude().process.spawn({ argv: ['cmod', 'update', 'cmod'] }), () => undefined)
521
473
  if (code === 0) return
522
474
  stop()
523
- fail(`${definition.name} needs cmod ${coreVersion} or later, and updating cmod ${found} ${formatExit(code, lastError)}`, undefined, updateAgain)
475
+ fail(`${definition.name} needs cmod ${oldestCmodVersion} or later, and updating cmod ${found} ${formatExit(code, lastError)}`, undefined, updateAgain)
524
476
  })
525
477
  .catch(report)
526
478
  })
@@ -541,8 +493,6 @@ export function createLifecycle<State extends object, Declared extends Options =
541
493
  if (readStarted === undefined) return
542
494
  const started = await readStarted(claude())
543
495
  plugin = started
544
- for (const item of started.granted) granted.add(item)
545
- consentMs = await stampOf(consentPath(started.store))
546
496
  recordMs = await stampOf(recordPath(started.store, started.name))
547
497
  if (started.isInstalled) {
548
498
  shouldRecord = started.shouldRecord
@@ -559,7 +509,6 @@ export function createLifecycle<State extends object, Declared extends Options =
559
509
  if (phase !== 'failed') fail(messageOf(error), undefined, begin, error)
560
510
  }
561
511
 
562
- let consentMs = 0
563
512
  const stampOf = async (path: string) => {
564
513
  const stat = await claude().fs.stat(path).catch(ifMissing(undefined))
565
514
  return stat?.kind === 'file' ? stat.mtimeMs : 0
@@ -576,17 +525,11 @@ export function createLifecycle<State extends object, Declared extends Options =
576
525
  plugin = current
577
526
  return true
578
527
  }
579
- const startInstalled = async () => {
528
+ const recover = async (): Promise<boolean> => {
529
+ if (phase !== 'failed' || !(await isNewlyInstalled())) return false
580
530
  failure = undefined
581
531
  activation = undefined
582
- await refreshGrants()
583
532
  await finish()
584
- }
585
- let settleAsked: (() => void) | undefined
586
- const recover = async (): Promise<boolean> => {
587
- if ((settleAsked === undefined && phase !== 'failed' && phase !== 'declined') || !(await isNewlyInstalled())) return false
588
- if (settleAsked === undefined) await startInstalled()
589
- else settleAsked()
590
533
  return true
591
534
  }
592
535
  let recordCheck: Timer | undefined
@@ -606,44 +549,6 @@ export function createLifecycle<State extends object, Declared extends Options =
606
549
  recordCheck = undefined
607
550
  }
608
551
 
609
- const refreshGrants = async () => {
610
- if (plugin === undefined || plugin.name === cmodPluginName) return
611
- const path = consentPath(plugin.store)
612
- const modifiedMs = await stampOf(path)
613
- if (modifiedMs === consentMs) return
614
- consentMs = modifiedMs
615
- const approved = modifiedMs === 0 ? [] : (parseConsent(JSON.parse(await claude().fs.read(path)), path)[plugin.name] ?? [])
616
- granted.clear()
617
- for (const item of plugin.steps.permissions ?? []) {
618
- if (approved.includes(item)) granted.add(item)
619
- }
620
- }
621
-
622
- const droppedParts = new Set<string>()
623
- const answerCheck: AnswerCheck = {
624
- get plugin() {
625
- return plugin?.name ?? definition.name
626
- },
627
- isGranted: (item) => isCovered(granted, item, undefined),
628
- dropped(item, part) {
629
- if (droppedParts.has(item)) return
630
- droppedParts.add(item)
631
- const isDeclared = (plugin?.steps.permissions ?? []).includes(item)
632
- toastFailure({
633
- id: `dropped:${item}`,
634
- message: `Answered ${part} without your grant to "${permissionWords(item)}", so cmod dropped it`,
635
- description: isDeclared ? grantFix : `It needs "permissions": { "${item}": true } in package.json "cmod".`,
636
- })
637
- },
638
- }
639
-
640
- const checkedRoute = async <N extends RoutedEvent>(event: N, e: Frozen<Args<N>>, next: RouterNext<N>): Promise<EventResult<N>> => {
641
- let below: Promise<EventResult<N>> | undefined
642
- const passOn: RouterNext<N> = (passed) => (below ??= next(passedDown(event, e, passed, answerCheck) as Frozen<Args<N>>))
643
- const answer = await router.dispatch(event, e, passOn)
644
- return (await checkedAnswer(event, e, answer, () => passOn(e), answerCheck)) as EventResult<N>
645
- }
646
-
647
552
  const whenActive = async () => {
648
553
  if (phase === 'ready') activation ??= activate().catch(report)
649
554
  if (activation !== undefined && phase !== 'active') await activation
@@ -728,8 +633,7 @@ export function createLifecycle<State extends object, Declared extends Options =
728
633
  return next(e)
729
634
  }
730
635
  if (isCallToThisMod && phase !== 'active') {
731
- const isStopped = phase === 'declined' || phase === 'failed'
732
- return { deny: isStopped ? `${definition.name} is not set up. Its toast says why.` : `${definition.name} is installing. Try again when it's ready.` } as EventResult<N>
636
+ return { deny: phase === 'failed' ? `${definition.name} is not set up. Its toast says why.` : `${definition.name} is installing. Try again when it's ready.` } as EventResult<N>
733
637
  }
734
638
  const call = e as Frozen<Args<'cmod.call'>>
735
639
  if (event === 'cmod.call' && call.to === definition.name && mod !== undefined) {
@@ -740,12 +644,10 @@ export function createLifecycle<State extends object, Declared extends Options =
740
644
  return { value: opened } as EventResult<N>
741
645
  }
742
646
  }
743
- if (event === 'classic.UserPromptSubmit' || event === 'classic.SessionStart') await refreshGrants().catch((error: unknown) => claude().ui.log(`${definition.name} keeps its grants from before: ${messageOf(error)}`, { to: 'debug' }))
744
647
  if (event === 'classic.UserPromptSubmit' && phase === 'active' && !hasHeardSessionStart) {
745
648
  const { session_id, transcript_path, cwd } = e as Frozen<Args<'classic.UserPromptSubmit'>>
746
649
  await replaySessionStart({ session_id, transcript_path, cwd, hook_event_name: 'SessionStart', source: 'resume' })
747
650
  }
748
- if (checksAnswers(event) && phase === 'active' && definition.name !== cmodPluginName) return checkedRoute(event, e, next)
749
651
  const answer = router.dispatch(event, e, next)
750
652
  const render = e as Frozen<Args<'ui.render'>>
751
653
  if (event !== 'ui.render' || render.component !== 'AbovePrompt' || runtime === undefined) return answer
@@ -774,28 +676,9 @@ async function createMod<State extends object, Declared extends Options>(definit
774
676
  added.push(feature)
775
677
  }
776
678
  const [session, root, startCwd, home, configHome] = await Promise.all([claude.session.id(), claude.session.root(), claude.session.cwd(), claude.env.home(), claude.env.configHome()])
777
- const { granted } = runtime
778
679
  const configRoot = configHome ?? (home === undefined ? undefined : `${home}/.claude`)
779
- const grants: Grants = {
780
- name: definition.name,
781
- declared: runtime.steps.permissions ?? [],
782
- granted: () => granted,
783
- refresh: runtime.refreshGrants,
784
- home,
785
- configRoot,
786
- projectRoot: () => modState.root,
787
- freeFolders: () => [modState.root, definition.name === cmodPluginName ? runtime.store : runtime.dataFolder],
788
- freeAddresses: () => programAddresses(mod),
789
- }
790
- const checked = checkingGrants(claude, grants)
791
680
  const places: Places = { home, configRoot, projectRoot: () => modState.root }
792
- const files = createModFiles({
793
- name: definition.name,
794
- claude,
795
- places,
796
- checkWrite: (path) => checkWrite(grants, `metadata.update(${path})`, path),
797
- report,
798
- })
681
+ const files = createModFiles({ name: definition.name, claude, places, report })
799
682
  let cwd = startCwd
800
683
  let loadedCwd = startCwd
801
684
  let staleCwd: string | undefined
@@ -831,18 +714,15 @@ async function createMod<State extends object, Declared extends Options>(definit
831
714
  router.add(`classic.${hook}`, classicHook(hook, listener, report), failed === undefined ? undefined : classicFailure(failed))
832
715
  const expand = (path: string) => (homePrefix.test(path) ? resolvedPath(path, places) : path)
833
716
  const settingsFile = (source: 'user' | 'project' | 'local'): SettingsFile => ({
834
- read: () => checked.settings.read({ source }),
717
+ read: () => claude.settings.read({ source }),
835
718
  async update(values) {
836
- await checkSettings(grants, source, values)
837
719
  await claude.cmod.call({ to: cmodPluginName, method: 'updateSettings', input: { mod: definition.name, source, project: modState.root, values } })
838
720
  },
839
721
  })
840
722
  const client = createSessionsClient({
841
723
  name: definition.name,
842
- claude: checked,
724
+ claude,
843
725
  report: (id, message, error) => report({ id, message, error }),
844
- isGranted: (permission) => flag(permission),
845
- permissionRefusal: (call, permission) => refusal(grants, call, permission),
846
726
  hookOn: (hook, listener, failed) => hookOn(hook as Hook, listener as HookListener<Hook>, failed),
847
727
  routeOn: (event: RoutedEvent, hook: unknown, failed?: unknown) => router.add(event, hook as never, failed as never),
848
728
  permissionRoutes: runtime.permissionRoutes,
@@ -857,9 +737,9 @@ async function createMod<State extends object, Declared extends Options>(definit
857
737
  const imports: Imports = {
858
738
  sessions: client.sessions,
859
739
  commands: {
860
- list: async () => (await checked.command.list()).map(({ name, description, source, plugin }) => ({ name, description, source, ...(plugin === undefined ? {} : { plugin }) })),
740
+ list: async () => (await claude.command.list()).map(({ name, description, source, plugin }) => ({ name, description, source, ...(plugin === undefined ? {} : { plugin }) })),
861
741
  run: async (command, args) => {
862
- const { text, context } = await checked.command.run({ command, ...(args === undefined ? {} : { args }) })
742
+ const { text, context } = await claude.command.run({ command, ...(args === undefined ? {} : { args }) })
863
743
  return { ...(text === undefined ? {} : { text }), ...(context === undefined || context.length === 0 ? {} : { note: context.join('\n') }) }
864
744
  },
865
745
  beforeRun: (...args: unknown[]) => client.listen('beforeRun', args),
@@ -867,7 +747,7 @@ async function createMod<State extends object, Declared extends Options>(definit
867
747
  },
868
748
  config: {
869
749
  list: async () =>
870
- (await checked.config.list()).map(({ key, label, description, kind, value, options, provider, isLocked }) => ({
750
+ (await claude.config.list()).map(({ key, label, description, kind, value, options, provider, isLocked }) => ({
871
751
  key,
872
752
  label,
873
753
  kind,
@@ -893,15 +773,15 @@ async function createMod<State extends object, Declared extends Options>(definit
893
773
  })
894
774
  },
895
775
  },
896
- model: { complete: (completion, options) => checked.model.complete(completion, options) },
776
+ model: { complete: (completion, options) => claude.model.complete(completion, options) },
897
777
  fs: {
898
- read: (path) => checked.fs.read(expand(path)),
899
- write: (path, text) => checked.fs.write(expand(path), text),
900
- exists: (path) => checked.fs.exists(expand(path)),
778
+ read: (path) => claude.fs.read(expand(path)),
779
+ write: (path, text) => claude.fs.write(expand(path), text),
780
+ exists: (path) => claude.fs.exists(expand(path)),
901
781
  find: (glob) => files.find(glob),
902
- list: async (path) => (await checked.fs.list(path === undefined ? undefined : expand(path))).map(({ name, kind, size, mtimeMs, isLink }) => ({ name, isFile: kind === 'file', isFolder: kind === 'dir', isLink, size, modifiedAt: mtimeMs })),
782
+ list: async (path) => (await claude.fs.list(path === undefined ? undefined : expand(path))).map(({ name, kind, size, mtimeMs, isLink }) => ({ name, isFile: kind === 'file', isFolder: kind === 'dir', isLink, size, modifiedAt: mtimeMs })),
903
783
  async stat(path, options) {
904
- const { kind, size, mtimeMs, isLink, realPath } = await checked.fs.stat(expand(path), options)
784
+ const { kind, size, mtimeMs, isLink, realPath } = await claude.fs.stat(expand(path), options)
905
785
  return { isFile: kind === 'file', isFolder: kind === 'dir', isLink, size, modifiedAt: mtimeMs, ...(realPath === undefined ? {} : { realPath }) }
906
786
  },
907
787
  onChange: ({ path }, listener) => watches.add([path].flat().map((each) => resolvedPath(each, places)), (change) => {
@@ -914,18 +794,16 @@ async function createMod<State extends object, Declared extends Options>(definit
914
794
  update: (path, change) => files.update(path, change),
915
795
  },
916
796
  process: {
917
- run: (argv, init) => checked.process.run(argv, init),
918
- spawn: (argv, init) => checked.process.spawn({ ...init, argv }),
797
+ run: (argv, init) => claude.process.run(argv, init),
798
+ spawn: (argv, init) => claude.process.spawn({ ...init, argv }),
919
799
  },
920
- http: { fetch: (url, init) => checked.http.fetch(url, init) },
800
+ http: { fetch: (url, init) => claude.http.fetch(url, init) },
921
801
  clipboard: {
922
802
  async write(text) {
923
803
  await toaster.copy(text)
924
804
  },
925
805
  },
926
806
  }
927
- const allowed = (permission: string): Allowed => ({ allows: (value) => isCovered(granted, itemOf(permission, value), home) })
928
- const flag = (permission: string) => isCovered(granted, permission, home)
929
807
  const timer = (ms: number, subject: string, repeats: boolean, listener: () => unknown): ModTimer => {
930
808
  let isFiring = false
931
809
  let isRunning = true
@@ -964,30 +842,6 @@ async function createMod<State extends object, Declared extends Options>(definit
964
842
  get options() {
965
843
  return modOptions.values as OptionValues<Declared>
966
844
  },
967
- permissions: {
968
- get conversation() {
969
- return flag('conversation')
970
- },
971
- get prompt() {
972
- return flag('prompt')
973
- },
974
- get model() {
975
- return flag('model')
976
- },
977
- get tasks() {
978
- return flag('tasks')
979
- },
980
- get tools() {
981
- return flag('tools')
982
- },
983
- get approve() {
984
- return flag('approve')
985
- },
986
- network: allowed('network'),
987
- run: allowed('run'),
988
- files: allowed('files'),
989
- config: allowed('config'),
990
- },
991
845
  hotkeys,
992
846
  every: (ms, listener) => timer(ms, 'every', true, listener),
993
847
  after: (ms, listener) => timer(ms, 'after', false, listener),
@@ -1098,7 +952,6 @@ async function createMod<State extends object, Declared extends Options>(definit
1098
952
  const call = e as typeof e & { readonly caller?: string }
1099
953
  if (e.method === conversationMethods.changed && call.caller === cmodPluginName) {
1100
954
  const { session: changedSession, change, isInProject } = e.input as { readonly session: string; readonly change: SessionChange; readonly isInProject?: boolean }
1101
- if (changedSession !== client.sessions.current.id && !flag('conversation')) return { value: null }
1102
955
  client.changed(changedSession, change, isInProject !== false)
1103
956
  return { value: null }
1104
957
  }
@@ -1127,16 +980,13 @@ async function createMod<State extends object, Declared extends Options>(definit
1127
980
  })
1128
981
  const agents = toolCalls(claude, router)
1129
982
  keepEngine(mod, {
1130
- claude: checked,
983
+ claude,
1131
984
  router,
1132
985
  toolCalls: agents,
1133
986
  report,
1134
987
  hasPermissionCheck: () => runtime.permissionRoutes() !== undefined,
1135
988
  answerInput: area.answerInput,
1136
- spawnCmod: async (args, program) => {
1137
- await checkRun(grants, 'process.spawn', program.argv)
1138
- return spawnCmod(claude, args, session, program.env)
1139
- },
989
+ spawnCmod: (args, env) => spawnCmod(claude, args, session, env),
1140
990
  ...(widgets === undefined ? {} : { widgets }),
1141
991
  ...(pages === undefined ? {} : { pages }),
1142
992
  })
@@ -41,13 +41,11 @@ export function createModFiles({
41
41
  name,
42
42
  claude,
43
43
  places,
44
- checkWrite,
45
44
  report,
46
45
  }: {
47
46
  readonly name: string
48
47
  readonly claude: Claude
49
48
  readonly places: Places
50
- readonly checkWrite: (path: string) => Promise<void>
51
49
  readonly report: (failure: Failure) => void
52
50
  }): ModFiles {
53
51
  const prefix = `${name}.`
@@ -146,7 +144,6 @@ export function createModFiles({
146
144
  },
147
145
  async update(path, change) {
148
146
  const given = resolvedPath(path, places)
149
- await checkWrite(given)
150
147
  const located = await locate(given)
151
148
  const text = await textOf(located.holder)
152
149
  let all: Metadata
@@ -50,30 +50,11 @@ export function pickedColor(args: string): string | undefined {
50
50
  return resetColors.includes(picked) ? undefined : picked
51
51
  }
52
52
 
53
- export type Act = 'send' | 'startTask' | 'fork' | 'clone' | 'startBackgroundTask' | 'callTool' | 'usage' | 'surfaces' | 'abort'
53
+ const acts = ['send', 'startTask', 'fork', 'clone', 'startBackgroundTask', 'callTool', 'usage', 'surfaces', 'abort'] as const
54
54
 
55
- const actPermissions: Readonly<Record<Exclude<Act, 'callTool'>, string>> = { send: 'prompt', startTask: 'tasks', fork: 'tasks', clone: 'tasks', startBackgroundTask: 'tasks', usage: 'conversation', surfaces: 'conversation', abort: 'prompt' }
55
+ export type Act = (typeof acts)[number]
56
56
 
57
- const startsTurns: readonly string[] = ['CronCreate']
58
-
59
- const ownSchedule: readonly string[] = ['CronDelete', 'CronList']
60
-
61
- export const beforePermission = (event: BeforeEvent): string => (event === 'toolCall' ? 'tools' : event === TaskStart ? 'tasks' : 'prompt')
62
-
63
- const answerPermissions = (event: BeforeEvent, answer: Partial<Answers>): string[] => [
64
- ...(Object.keys(answer).some((key) => key !== 'note') ? [beforePermission(event)] : []),
65
- ...(answer.note === undefined ? [] : ['prompt']),
66
- ]
67
-
68
- export const isAct = (action: string): action is Act => action === 'callTool' || action in actPermissions
69
-
70
- export function toolPermission(tool: string): string | undefined {
71
- return startsTurns.includes(tool) ? 'prompt' : ownSchedule.includes(tool) ? undefined : 'tools'
72
- }
73
-
74
- export function actPermission(action: Act, input: unknown): string | undefined {
75
- return action === 'callTool' ? (toolPermission(String((input as Partial<ToolCallArgs> | null)?.name)) ?? 'tools') : actPermissions[action]
76
- }
57
+ export const isAct = (action: string): action is Act => (acts as readonly string[]).includes(action)
77
58
 
78
59
  export type Scope = { readonly session?: string; readonly context?: number; readonly turn?: string; readonly task?: string; readonly isGoal?: true; readonly isAgent?: true }
79
60
 
@@ -158,7 +139,7 @@ export function withoutPermissionCheck(name: string, hearer: string): string {
158
139
 
159
140
  export type HookOn = (hook: string, listener: (input: unknown) => HookFields | undefined | Promise<HookFields | undefined>, failed?: (input: unknown, error: Error) => HookFields | undefined) => Subscription
160
141
 
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 {
142
+ export function createSessionsClient({ name, claude, report, hookOn, routeOn, permissionRoutes }: { readonly name: string; readonly claude: Claude; readonly report: (id: string, message: string, error: unknown) => void; readonly hookOn?: HookOn; readonly routeOn?: RouteOn; readonly permissionRoutes?: () => PermissionRoutes | undefined }): SessionsClient {
162
143
  const call = <Answer>(method: string, input: unknown) => claude.cmod.call({ to: cmodPluginName, method, input }) as Promise<Answer>
163
144
  const listening = new Map<string, Set<Listening>>()
164
145
  const deciding = new Map<string, Set<Listening>>()
@@ -236,18 +217,12 @@ export function createSessionsClient({ name, claude, report, isGranted, permissi
236
217
 
237
218
  const decides = (entry: Listening, session: string, change: SessionChange) => isInScope(entry.scope, session, change, isUnderIn(session)) && (entry.matcher === undefined || matches(payloadOf(change), entry.matcher))
238
219
 
239
- const mayDecide = (session: string) => session === current.id || isGranted('conversation')
240
-
241
220
  const combined = async (session: string, event: BeforeEvent, change: SessionChange, isInProject: boolean): Promise<Partial<Answers> | undefined> => {
242
221
  const askers = decidersOf(session, event, isInProject)
243
222
  .map((entry) => async (latest: SessionChange) => {
244
223
  if (!decides(entry, session, latest)) return undefined
245
224
  const payload = await payloadFor(session, latest)
246
- const answer = await invoke(entry.method, entry.options, async (time) => takenAnswer(entry.method, beforeAnswerKeys[event], await entry.listener(payload as never, time)), beforeAnswerKeys[event])
247
- if (answer === undefined || answer === null || (typeof answer === 'object' && 'refuse' in answer)) return answer
248
- const missing = answerPermissions(event, answer as Partial<Answers>).find((permission) => !isGranted(permission))
249
- if (missing === undefined) return answer
250
- throw new Error(permissionRefusal(`${entry.method} with the answer { ${Object.keys(answer).join(', ')} }`, missing))
225
+ return invoke(entry.method, entry.options, async (time) => takenAnswer(entry.method, beforeAnswerKeys[event], await entry.listener(payload as never, time)), beforeAnswerKeys[event])
251
226
  })
252
227
  const answer = await foldBefore(event, change, askers, (error) => report(`session:${methodOf('before', event)}`, `The ${methodOf('before', event)} listener failed`, error))
253
228
  return answer?.note === undefined ? answer : { ...answer, note: modNote(name, answer.note) }
@@ -505,13 +480,11 @@ export function createSessionsClient({ name, claude, report, isGranted, permissi
505
480
  const run = await commandRun(e)
506
481
  const answer = commandListeners.beforeRun.size === 0 ? undefined : await raise('beforeRun', run)
507
482
  if (typeof answer?.['refuse'] === 'string') return { text: answer['refuse'] }
508
- const changes = answer !== undefined && isGranted('prompt') ? answer : undefined
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')))
510
- if (typeof changes?.['result'] === 'string') return { text: changes['result'], ...(typeof changes['exitCode'] === 'number' ? { exitCode: changes['exitCode'] } : {}) }
511
- const args = typeof changes?.['args'] === 'string' ? changes['args'] : e.args
483
+ if (typeof answer?.['result'] === 'string') return { text: answer['result'], ...(typeof answer['exitCode'] === 'number' ? { exitCode: answer['exitCode'] } : {}) }
484
+ const args = typeof answer?.['args'] === 'string' ? answer['args'] : e.args
512
485
  const ran = await next(args === e.args ? e : { ...e, args })
513
486
  void raise('onRun', { ...run, args })
514
- return typeof changes?.['note'] === 'string' ? { ...ran, context: [...(ran.context ?? []), modNote(name, changes['note'])] } : ran
487
+ return typeof answer?.['note'] === 'string' ? { ...ran, context: [...(ran.context ?? []), modNote(name, answer['note'])] } : ran
515
488
  }, async (e, error) => {
516
489
  const refusal = commandListeners.beforeRun.size === 0 ? undefined : refusalFor('beforeRun', await commandRun(e), error)
517
490
  return refusal === undefined ? undefined : { text: refusal.refuse }
@@ -603,10 +576,8 @@ export function createSessionsClient({ name, claude, report, isGranted, permissi
603
576
  })
604
577
  const every = eventMethods(() => ({}), false)
605
578
 
606
- const answerBefore = async (session: string, event: BeforeEvent, change: SessionChange, isInProject: boolean) => (mayDecide(session) ? combined(session, event, change, isInProject) : undefined)
607
-
608
579
  const failedBefore = (session: string, event: BeforeEvent, change: SessionChange, isInProject: boolean, error: Error) => {
609
- const asked = mayDecide(session) ? decidersOf(session, event, isInProject).filter((entry) => decides(entry, session, change)) : []
580
+ const asked = decidersOf(session, event, isInProject).filter((entry) => decides(entry, session, change))
610
581
  return asked.map((entry) => refusalOf(entry.options, beforeAnswerKeys[event], error)).find((answer) => answer !== undefined)
611
582
  }
612
583
 
@@ -640,7 +611,7 @@ export function createSessionsClient({ name, claude, report, isGranted, permissi
640
611
  }
641
612
  }
642
613
  },
643
- answerBefore,
614
+ answerBefore: combined,
644
615
  failedBefore,
645
616
  raise,
646
617
  listen,
@@ -1,7 +1,7 @@
1
1
  import type { ElementTable, RenderElement, RenderPropsOf, Timer } from 'claude-code'
2
2
  import type { Toast, ToastId, ToastOptions, ToastType } from '../mod.js'
3
3
  import { Box, Button, drawWith, Link, Text } from '../ui/elements.js'
4
- import { coreVersion, grantFix, installFix, isObject, secretFix } from '../records.js'
4
+ import { coreVersion, installFix, isObject, secretFix } from '../records.js'
5
5
  import { firstLine, messageOf } from '../utils/text.js'
6
6
  import type { Claude } from './claude.js'
7
7
  import { beforeDeadline } from './deadline.js'
@@ -224,15 +224,12 @@ export function createToaster(claude: Claude, name: string, version: () => strin
224
224
  .catch((failure: unknown) => `unknown (${messageOf(failure)})`)
225
225
  return `${name} ${modVersion}, @cmodjs/core ${coreVersion}, at ${failedAt.toISOString()}\n${message}${description === undefined ? '' : `\n${description}`}${stack}`
226
226
  }
227
- const text = `${message}\n${description ?? ''}`
228
- const isGrantRefusal = text.includes(grantFix)
229
- const isShownAtOnce = isCritical && !isGrantRefusal
230
227
  const logged = async () => {
231
228
  const contact = await contactOf(claude)
232
229
  const failure: LoggedFailure = { mod: name, id, message, details: await details(at), at: at.toISOString(), isCritical, root: claude.plugin.root, ...(contact === undefined ? {} : { contact }) }
233
- const shows = await showsToast(failure, isShownAtOnce)
234
- if (isShownAtOnce) return
235
- if (shows === undefined || (shows && !isGrantRefusal)) return show()
230
+ const shows = await showsToast(failure, isCritical)
231
+ if (isCritical) return
232
+ if (shows !== false) return show()
236
233
  claude.ui.log(`${name}: ${message}${description === undefined ? '' : `: ${description}`}`, { to: 'debug' })
237
234
  }
238
235
  const show = () => {
@@ -275,8 +272,8 @@ export function createToaster(claude: Claude, name: string, version: () => strin
275
272
  const fixes = [
276
273
  { sentence: installFix, label: 'Plugins', onClick: () => claude.command.run({ command: 'plugin' }) },
277
274
  { sentence: secretFix, label: 'Open /config', onClick: () => claude.command.run({ command: 'config' }) },
278
- ].filter(({ sentence }) => text.includes(sentence))
279
- if (isShownAtOnce) show()
275
+ ].filter(({ sentence }) => `${message}\n${description ?? ''}`.includes(sentence))
276
+ if (isCritical) show()
280
277
  claude.clock.after(0, () => void logged())
281
278
  return id
282
279
  }