@cmodjs/core 5.6.0 → 5.7.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.
@@ -1,4 +1,4 @@
1
- import { dataFolder, finishStepsMethod, isAtLeast, isProgramNewer, oldestCmodVersion, pendingStepsMethod, parseEvent, programPath, readCmodVersion, readRecord, readSteps, recordPath, scriptsSha256, storeFolder } from '../records.js';
1
+ import { dataFolder, finishStepsMethod, isAtLeast, isProgramNewer, oldestCmodVersion, pendingStepsMethod, parseEvent, programPath, readRecord, readSteps, recordPath, scriptsSha256, storeFolder } from '../records.js';
2
2
  import { homePrefix, ifMissing, relativePath } from '../utils/paths.js';
3
3
  import { firstLine, formatExit, messageOf } from '../utils/text.js';
4
4
  import { beforeDeadline, settledAfterAbort } from './deadline.js';
@@ -8,7 +8,7 @@ import { serveConversations } from './conversations.js';
8
8
  import { answerCall, answeringOwnCalls, cmodPluginName, dependencyCalls, loadedMethod, withBareRefusals } from './dependencies.js';
9
9
  import { keepEngine } from './engine.js';
10
10
  import { classicFailure, classicHook, userSkillHook } from './hooks.js';
11
- import { cmodError, locatingPrograms, readLines, spawnCmod } from './programs.js';
11
+ import { cmodError, locatingPrograms, newestCmodVersion, readLines, spawnCmod } from './programs.js';
12
12
  import { createModFiles, resolvedPath } from './metadata.js';
13
13
  import { fitsOption } from '../options.js';
14
14
  import { createInstaller } from './installer.js';
@@ -56,7 +56,7 @@ export async function readPlugin(claude) {
56
56
  const store = storeFolder({ HOME: await claude.env.home(), XDG_DATA_HOME: await claude.env.dataHome() });
57
57
  const steps = readSteps(await readJson(read, `${root}/package.json`)) ?? {};
58
58
  if (name === cmodPluginName) {
59
- const installed = await cmodVersion(claude);
59
+ const installed = await newestCmodVersion(claude);
60
60
  return { name, root, version, store, steps, isInstalled: version !== undefined && installed !== undefined && isAtLeast(installed, version), shouldRecord: false };
61
61
  }
62
62
  const plugin = { name, root, version, store, steps };
@@ -95,15 +95,9 @@ async function readJson(read, path) {
95
95
  throw new Error(`${path} is not JSON (${messageOf(error)}). Fix it, then press Retry.`);
96
96
  }
97
97
  }
98
- async function cmodVersion(claude) {
99
- const store = storeFolder({ HOME: await claude.env.home(), XDG_DATA_HOME: await claude.env.dataHome() });
100
- return readCmodVersion({
101
- list: async (folder) => (await claude.fs.list(folder).catch(ifMissing([]))).map((entry) => entry.name),
102
- exists: async (path) => (await claude.fs.stat(path).catch(ifMissing(undefined))) !== undefined,
103
- }, store);
104
- }
105
98
  export function createLifecycle(definition, permissionRoutes = () => undefined, options = {}, asksPerson = true) {
106
99
  let router = createRouter();
100
+ let startingRouter;
107
101
  let phase = 'starting';
108
102
  let runtime;
109
103
  let programs;
@@ -190,7 +184,7 @@ export function createLifecycle(definition, permissionRoutes = () => undefined,
190
184
  claude().ui.invalidate('ui.render');
191
185
  };
192
186
  const recordThroughCmod = async () => {
193
- if (plugin === undefined || (await cmodVersion(claude())) === undefined)
187
+ if (plugin === undefined || (await newestCmodVersion(claude())) === undefined)
194
188
  return;
195
189
  let failed;
196
190
  const { code, lastError } = await readLines(claude().process.spawn({ argv: ['cmod', 'setup', plugin.root, '--events'] }), (text) => {
@@ -283,12 +277,17 @@ export function createLifecycle(definition, permissionRoutes = () => undefined,
283
277
  if (runtime === undefined || plugin === undefined)
284
278
  return;
285
279
  const activeRouter = createRouter();
286
- const active = await createMod(definition, { ...runtime, router: activeRouter, dataFolder: dataFolder(plugin.store, plugin.name), store: plugin.store, permissionRoutes, options: pluginOptions, nextDraw }).catch(async (error) => {
280
+ startingRouter = activeRouter;
281
+ const active = await createMod(definition, { ...runtime, router: activeRouter, dataFolder: dataFolder(plugin.store, plugin.name), store: plugin.store, permissionRoutes, options: pluginOptions, nextDraw })
282
+ .catch(async (error) => {
287
283
  if (error instanceof MissingOptions && (await askOptions(error)))
288
284
  return undefined;
289
285
  await installer.close();
290
286
  fail(messageOf(error), error instanceof MissingOptions ? `Retry asks for ${error.keys.length === 1 ? 'it' : 'them'}.` : undefined, begin, error);
291
287
  throw error;
288
+ })
289
+ .finally(() => {
290
+ startingRouter = undefined;
292
291
  });
293
292
  if (active === undefined)
294
293
  return activate();
@@ -345,7 +344,7 @@ export function createLifecycle(definition, permissionRoutes = () => undefined,
345
344
  if (plugin.name === cmodPluginName)
346
345
  return bootstrap(plugin.root);
347
346
  phase = 'installing';
348
- const found = await cmodVersion(claude());
347
+ const found = await newestCmodVersion(claude());
349
348
  if (!fits(found))
350
349
  return waitForcmod(found);
351
350
  if (!isQuiet)
@@ -378,7 +377,7 @@ export function createLifecycle(definition, permissionRoutes = () => undefined,
378
377
  longWait.cancel();
379
378
  };
380
379
  const poll = (ms) => claude().clock.every(ms, () => {
381
- check ??= cmodVersion(claude())
380
+ check ??= newestCmodVersion(claude())
382
381
  .then((version) => {
383
382
  check = undefined;
384
383
  latest = version;
@@ -503,21 +502,21 @@ export function createLifecycle(definition, permissionRoutes = () => undefined,
503
502
  await activation;
504
503
  };
505
504
  const held = (work, signal) => runtime === undefined
506
- ? work
505
+ ? work.then(() => false)
507
506
  : new Promise((resolve) => {
508
- const limit = claude().clock.after(startHoldMs, resolve);
507
+ const limit = claude().clock.after(startHoldMs, () => resolve(true));
509
508
  if (signal?.aborted === true)
510
- resolve();
511
- signal?.addEventListener('abort', () => resolve(), { once: true });
509
+ resolve(false);
510
+ signal?.addEventListener('abort', () => resolve(false), { once: true });
512
511
  void work.then(() => {
513
512
  limit.cancel();
514
- resolve();
513
+ resolve(false);
515
514
  });
516
515
  });
517
516
  const holdUntilStarted = (signal) => held(startSettled.then(whenActive), signal);
518
517
  const holdUntilActive = (signal) => {
519
518
  const activating = whenActive();
520
- return activation !== undefined && phase !== 'active' ? held(activating, signal) : activating;
519
+ return activation !== undefined && phase !== 'active' ? held(activating, signal) : activating.then(() => false);
521
520
  };
522
521
  const routed = async (event, e, next, signal) => {
523
522
  if (imports !== undefined)
@@ -548,7 +547,7 @@ export function createLifecycle(definition, permissionRoutes = () => undefined,
548
547
  const isCallToThisMod = (event === 'cmod.call' && e.to === definition.name) || (event === 'tool.call' && typeof tool === 'string' && tool.startsWith(`mcp__${definition.name}__`));
549
548
  if (event === 'cmod.call' && !isCallToThisMod)
550
549
  return next(e);
551
- await (event === 'classic.SessionStart' || event === 'session.append' || isCallToThisMod ? holdUntilStarted(signal) : holdUntilActive(signal));
550
+ const isLate = await (event === 'classic.SessionStart' || event === 'session.append' || isCallToThisMod ? holdUntilStarted(signal) : holdUntilActive(signal));
552
551
  if (event === 'classic.SessionStart' && phase !== 'active') {
553
552
  missedSessionStart = e;
554
553
  return next(e);
@@ -560,6 +559,8 @@ export function createLifecycle(definition, permissionRoutes = () => undefined,
560
559
  }
561
560
  return { deny: phase === 'failed' ? notSetUp() : `${definition.name} is installing. Try again when it's ready.` };
562
561
  }
562
+ if (isLate && phase !== 'active')
563
+ return (startingRouter ?? router).dispatchFailure(event, e, new Error(`it was still starting after ${startHoldMs / 1000} s`), next, false);
563
564
  const call = e;
564
565
  if (event === 'cmod.call' && call.to === definition.name && mod !== undefined) {
565
566
  if (call.method === pendingStepsMethod)
@@ -653,7 +654,7 @@ export function createLifecycle(definition, permissionRoutes = () => undefined,
653
654
  const failedBeneath = called && kind === 'throw' ? await next(e).then(() => undefined, messageOf) : undefined;
654
655
  if (failedBeneath === undefined || failedBeneath !== message)
655
656
  toastFailure({ id: `stopped:${event}`, message: `Claude Code stopped its ${event.replace(/^classic\./, '')} hook`, error });
656
- return router.dispatchFailure(event, e, error, next);
657
+ return (startingRouter ?? router).dispatchFailure(event, e, error, next, called);
657
658
  },
658
659
  };
659
660
  }
@@ -12,6 +12,7 @@ export declare function readLines(stream: HookStream<ProcessSpawnChunk, ProcessS
12
12
  }>;
13
13
  export declare function spawnCmod(claude: Claude, args: readonly string[], session: string, env?: Readonly<Record<string, string>>): HookStream<ProcessSpawnChunk, ProcessSpawnResult>;
14
14
  export declare function isHeld(claude: Claude, lock: string, staleMs: number): Promise<boolean>;
15
+ export declare function newestCmodVersion(claude: Claude): Promise<string | undefined>;
15
16
  export declare function runCmod(claude: Claude, args: readonly string[], session: string): Promise<string>;
16
17
  export declare function locatingPrograms(claude: Claude): Programs;
17
18
  //# sourceMappingURL=programs.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"programs.d.ts","sourceRoot":"","sources":["../src/runtime/programs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAIpF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAEzC,MAAM,MAAM,QAAQ,GAAG;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CAAA;AAE5E,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAG3D;AAED,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAI7E;AAED,wBAAsB,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC,iBAAiB,EAAE,kBAAkB,CAAC,EAAE,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC,CAgB9K;AAED,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAM,GAAG,UAAU,CAAC,iBAAiB,EAAE,kBAAkB,CAAC,CAEjL;AAED,wBAAsB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,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AEjL;AAED,wBAAsB,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAK5F;AAED,wBAAsB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CASnF;AAED,wBAAsB,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAKvG;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,QAAQ,CAsBzD"}
@@ -1,4 +1,4 @@
1
- import { storeFolder } from '../records.js';
1
+ import { readCmodVersion, storeFolder } from '../records.js';
2
2
  import { ifMissing } from '../utils/paths.js';
3
3
  import { formatExit } from '../utils/text.js';
4
4
  export function lastLineOf(text) {
@@ -39,6 +39,13 @@ export async function isHeld(claude, lock, staleMs) {
39
39
  const touched = await Promise.all(holders.map(async ({ name }) => (await claude.fs.stat(`${lock}/${name}`).catch(ifMissing(undefined)))?.mtimeMs ?? 0));
40
40
  return touched.some((at) => now - at < staleMs);
41
41
  }
42
+ export async function newestCmodVersion(claude) {
43
+ const store = storeFolder({ HOME: await claude.env.home(), XDG_DATA_HOME: await claude.env.dataHome() });
44
+ return readCmodVersion({
45
+ list: async (folder) => (await claude.fs.list(folder).catch(ifMissing([]))).map((entry) => entry.name),
46
+ exists: async (path) => (await claude.fs.stat(path).catch(ifMissing(undefined))) !== undefined,
47
+ }, store);
48
+ }
42
49
  export async function runCmod(claude, args, session) {
43
50
  const lines = [];
44
51
  const { code, lastError } = await readLines(spawnCmod(claude, args, session), (line) => void lines.push(line));
@@ -6,11 +6,13 @@ export type RoutedNext<N extends RoutedEvent> = RouterNext<N> & {
6
6
  readonly signal: AbortSignal;
7
7
  };
8
8
  export type RoutedHook<N extends RoutedEvent> = (e: Frozen<Args<N>>, next: RoutedNext<N>) => EventResult<N> | Promise<EventResult<N>>;
9
- export type RoutedFailure<N extends RoutedEvent> = (e: Frozen<Args<N>>, error: Error, next: RoutedNext<N>) => EventResult<N> | undefined | Promise<EventResult<N> | undefined>;
9
+ export type RoutedFailure<N extends RoutedEvent> = (e: Frozen<Args<N>>, error: Error, next: RoutedNext<N> & {
10
+ readonly called: boolean;
11
+ }) => EventResult<N> | undefined | Promise<EventResult<N> | undefined>;
10
12
  export type Router = {
11
13
  add<N extends RoutedEvent>(event: N, hook: RoutedHook<N>, failed?: RoutedFailure<N>): Subscription;
12
14
  dispatch<N extends RoutedEvent>(event: N, e: Frozen<Args<N>>, next: RouterNext<N>, signal?: AbortSignal): Promise<EventResult<N>>;
13
- dispatchFailure<N extends RoutedEvent>(event: N, e: Frozen<Args<N>>, error: Error, next: RouterNext<N>): Promise<EventResult<N>>;
15
+ dispatchFailure<N extends RoutedEvent>(event: N, e: Frozen<Args<N>>, error: Error, next: RouterNext<N>, called: boolean): Promise<EventResult<N>>;
14
16
  };
15
17
  export declare const unaborted: AbortSignal;
16
18
  export declare function createRouter(): Router;
@@ -1 +1 @@
1
- {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/runtime/router.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAC5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AAC5D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAE7C,MAAM,MAAM,UAAU,CAAC,CAAC,SAAS,WAAW,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAA;AAE/F,MAAM,MAAM,UAAU,CAAC,CAAC,SAAS,WAAW,IAAI,UAAU,CAAC,CAAC,CAAC,GAA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G,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,CAAA;AAE7M,MAAM,MAAM,MAAM,GAAG;IACnB,GAAG,CAAC,CAAC,SAAS,WAAW,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,YAAY,CAAA;IAClG,QAAQ,CAAC,CAAC,SAAS,WAAW,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAA;IACjI,eAAe,CAAC,CAAC,SAAS,WAAW,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAA;CAClJ,CAAA;AAMD,eAAO,MAAM,SAAS,aAA+B,CAAA;AAErD,wBAAgB,YAAY,IAAI,MAAM,CAmCrC"}
package/runtime/router.js CHANGED
@@ -25,14 +25,16 @@ export function createRouter() {
25
25
  };
26
26
  return call(0, e);
27
27
  },
28
- async dispatchFailure(event, e, error, next) {
29
- const signalled = Object.assign((passed) => next(passed), { signal: unaborted });
30
- for (const route of routes.get(event) ?? []) {
31
- const answer = await route.failed?.(e, error, signalled);
32
- if (answer !== undefined)
33
- return answer;
34
- }
35
- return next(e);
28
+ dispatchFailure(event, e, error, next, called) {
29
+ const chain = routes.get(event);
30
+ const fail = async (index, current) => {
31
+ const route = chain?.[index];
32
+ if (route === undefined)
33
+ return next(current);
34
+ const answer = await route.failed?.(current, error, Object.assign((passed) => fail(index + 1, passed), { signal: unaborted, called }));
35
+ return answer === undefined ? fail(index + 1, current) : answer;
36
+ };
37
+ return fail(0, e);
36
38
  },
37
39
  };
38
40
  }
@@ -1 +1 @@
1
- {"version":3,"file":"toaster.d.ts","sourceRoot":"","sources":["../src/runtime/toaster.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,aAAa,EAAS,MAAM,aAAa,CAAA;AACpF,OAAO,KAAK,EAAE,KAAK,EAAE,OAAO,EAAgB,SAAS,EAAE,MAAM,WAAW,CAAA;AAExE,OAAO,EAAgD,KAAK,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,eAAe,CAAA;AAEzG,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAIzC,MAAM,MAAM,UAAU,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,CAAA;AAE9G,MAAM,MAAM,OAAO,GAAG;IAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,OAAO,CAAC;IAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,OAAO,CAAA;CAAE,CAAA;AAE/L,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,OAAO,EAAE,MAAM,C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const row = (entry) => {
258
+ const row = (entry, columns) => {
259
259
  const { description } = entry.options;
260
260
  const isText = typeof description === 'string';
261
261
  const icon = entry.type === 'loading' || entry.trying !== undefined ? { glyph: isSpinning(entry) ? spinner[frame % spinner.length] : still, color: 'claude' } : icons[entry.type];
@@ -264,17 +264,25 @@ export function createToaster(claude, name, version) {
264
264
  const fixed = (child) => Box({ flexShrink: 0, children: child });
265
265
  const close = Button({ plain: true, dimColor: true, key: `toast:${entry.id}:close`, label: entry.hides === undefined ? '✕' : 'Hide', onPress: () => hide(entry) });
266
266
  const actions = entry.actions.map((action, index) => Button({ plain: true, key: `toast:${entry.id}:${index === 0 ? 'action' : `action-${index}`}`, label: action.label, onPress: press(entry, action.onClick) }));
267
- const buttons = Box({ gap: 2, flexWrap: 'wrap', children: [...actions, close, Text({ dimColor: true, children: clockTime(entry.at) })].map(fixed) });
267
+ const buttons = Box({ gap: 2, flexWrap: 'wrap', children: [...actions, Text({ dimColor: true, children: clockTime(entry.at) })].map(fixed) });
268
268
  const trying = entry.trying === undefined ? undefined : Box({ gap: 1, children: [Text({ dimColor: true, children: 'Trying again:' }), typeof entry.trying === 'string' ? Text({ dimColor: true, wrap: 'truncate-end', children: entry.trying }) : entry.trying] });
269
269
  const text = details === undefined ? [message] : [message, trying ?? details];
270
270
  const under = trying !== undefined && details === undefined ? [trying] : entry.reporting === undefined ? [buttons] : reportChoices(entry, entry.reporting);
271
271
  return Box({
272
+ width: columns,
272
273
  gap: 2,
274
+ justifyContent: 'space-between',
273
275
  children: [
274
- fixed(Text({ ...(icon.color === undefined ? {} : { color: icon.color }), children: icon.glyph })),
275
- fixed(Text({ dimColor: true, children: name })),
276
- Box({ flexDirection: 'column', flexGrow: 1, flexShrink: 1, children: entry.hides === undefined ? text : [...text, ...under] }),
277
- ...(entry.hides === undefined ? [...actions.map(fixed), fixed(close)] : []),
276
+ Box({
277
+ gap: 2,
278
+ flexShrink: 1,
279
+ children: [
280
+ fixed(Text({ ...(icon.color === undefined ? {} : { color: icon.color }), children: icon.glyph })),
281
+ fixed(Text({ dimColor: true, children: name })),
282
+ Box({ flexDirection: 'column', flexShrink: 1, children: entry.hides === undefined ? text : [...text, ...under] }),
283
+ ],
284
+ }),
285
+ Box({ gap: 2, flexShrink: 0, alignSelf: 'flex-end', children: entry.hides === undefined ? [...actions, close] : [close] }),
278
286
  ],
279
287
  });
280
288
  };
@@ -338,7 +346,7 @@ export function createToaster(claude, name, version) {
338
346
  changed();
339
347
  },
340
348
  });
341
- return drawWith(table, () => Box({ flexDirection: 'column', children: [drawn, ...(hidden > 0 ? [more] : []), ...all.slice(hidden).map(row)] }));
349
+ return drawWith(table, () => Box({ flexDirection: 'column', children: [drawn, ...(hidden > 0 ? [more] : []), ...all.slice(hidden).map((entry) => row(entry, band.bodyColumns))] }));
342
350
  },
343
351
  };
344
352
  }
package/src/records.ts CHANGED
@@ -236,6 +236,14 @@ export function pluginsChangedPath(store: string): string {
236
236
  return `${store}/plugins-changed`
237
237
  }
238
238
 
239
+ export function pluginsChangedMark(at: number, pid: number, checkout?: string): string {
240
+ return `${at} ${pid}\n${checkout === undefined ? '' : `${checkout}\n`}`
241
+ }
242
+
243
+ export function markedCheckout(mark: string): string | undefined {
244
+ return mark.split('\n')[1] || undefined
245
+ }
246
+
239
247
  export function storeChangedPath(store: string): string {
240
248
  return `${store}/store-changed`
241
249
  }
@@ -361,7 +369,7 @@ function readHotkeys(hotkeys: unknown): Steps {
361
369
  return { hotkeys: checkHotkeys('package.json "cmod"', hotkeys as Record<string, HotkeyInit>) }
362
370
  }
363
371
 
364
- export const coreVersion = '5.6.0'
372
+ export const coreVersion = '5.7.0'
365
373
 
366
374
  export const oldestCmodVersion = '5.4.0'
367
375
 
@@ -13,7 +13,7 @@ import { Skill } from '../session/context/turn/message/skill.js'
13
13
  import { ToolCall } from '../session/context/turn/message/tool-call.js'
14
14
  import { ToolResult } from '../session/context/turn/message/tool-result.js'
15
15
  import { TurnEnd } from '../session/context/turn/turn.js'
16
- import { ownerOfSpawn, type ContextData, type ConversationState, type RunningTask, type SessionChange, type TaskData, type TurnData } from '../session/conversation.js'
16
+ import { ownerOfSpawn, type ContextData, type ConversationState, type RunningTask, type SessionChange, type TurnData } from '../session/conversation.js'
17
17
  import { Task, TaskStart } from '../session/goal/task.js'
18
18
  import { sessionEvents, type BeforeEvent, type SessionEvent } from '../session/session.js'
19
19
  import type { Claude } from './claude.js'
@@ -41,7 +41,12 @@ export type Answers = {
41
41
  readonly summary: string
42
42
  }
43
43
 
44
- export type BeforeHooks = { readonly place: () => Promise<Place>; readonly wants: (event: BeforeEvent) => Promise<boolean>; readonly fold: (cancel: AbortSignal) => Decide }
44
+ export type BeforeHooks = {
45
+ readonly place: () => Promise<Place>
46
+ readonly wants: (event: BeforeEvent) => Promise<boolean>
47
+ readonly fold: (cancel: AbortSignal) => Decide
48
+ readonly failedBefore: (event: BeforeEvent, change: (where: Place) => SessionChange | undefined, error: Error) => { readonly refuse: string } | undefined
49
+ }
45
50
 
46
51
  const appended: readonly BeforeEvent[] = [Note, Reply, Notice]
47
52
 
@@ -63,7 +68,7 @@ export function relayOf(e: Frozen<Args<'session.receive'>>): string | undefined
63
68
  }
64
69
 
65
70
  export function installBefore({ claude, router, hooks }: { readonly claude: Claude; readonly router: Router; readonly hooks: BeforeHooks }): Subscription {
66
- const { place, wants, fold } = hooks
71
+ const { place, wants, fold, failedBefore } = hooks
67
72
  const now = () => new Date().toISOString()
68
73
  const asked = async (event: BeforeEvent, change: SessionChange, decide: Decide) => (await decide(event, change)) ?? {}
69
74
  const message = (where: Place, unplaced: Unplaced, task: string | undefined, isInTurn = true): SessionChange => {
@@ -72,6 +77,22 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
72
77
  const call = unplaced.type === ToolResult ? where.openCalls?.[unplaced.callId] : undefined
73
78
  return { type: Message, message: { ...unplaced, ...call, session: where.session, context, ...(turn === undefined ? {} : { turn: turn.prompt.id }), ...(task === undefined ? {} : { task }) } as Message }
74
79
  }
80
+ const submitted = (e: Frozen<Args<'prompt.submit'>>) => (where: Place) => message(where, { id: '', at: now(), type: Prompt, text: e.text, from: senderOf(e.origin, false) }, undefined, false)
81
+ const received = (e: Frozen<Args<'session.receive'>>) => (where: Place) => message(where, { id: '', at: now(), type: Prompt, text: e.text, from: { type: 'session' } }, e.agentId, false)
82
+ const refusedOnFailure = (event: BeforeEvent, change: (where: Place) => SessionChange | undefined, error: Error, next: { readonly called: boolean }) => (next.called ? undefined : failedBefore(event, change, error)?.refuse)
83
+ const toolCalled = (e: Frozen<Args<'tool.call'>>, cwd: string) => (where: Place) => message(where, { id: e.tool_use_id, at: now(), type: ToolCall, callId: e.tool_use_id, name: e.tool, input: toolInputOf(e), cwd, files: noFiles }, e.agentId)
84
+ const cwdOf = async (agentId: string | undefined) => (agentId === undefined ? undefined : agentFolders.get(agentId)) ?? (await claude.session.cwd())
85
+ const startedTask = (e: Frozen<Args<'agent.spawn'>>, where: Place): RunningTask => ({ id: '', title: e.description, ...ownerOfSpawn(e.subagentType, where.session), model: e.model ?? e.parentModel, openedBy: e.tool_use_id, openedAt: now(), ...(e.parentAgentId === undefined ? {} : { parent: e.parentAgentId }), context: where.context })
86
+ const attachmentOf = (e: Frozen<Args<'prompt.attachment'>>): { readonly event: BeforeEvent; readonly found: Unplaced } | undefined => {
87
+ if (e.type === 'nested_memory') return { event: InstructionFile, found: { id: '', at: now(), type: InstructionFile, path: instructionPathOf(e.text), text: e.text, isRule: isRulePath(instructionPathOf(e.text)) } }
88
+ const attachmentType = attachmentTypeOf(e.type)
89
+ return attachmentType === undefined ? undefined : { event: AttachedFile, found: { id: '', at: now(), type: AttachedFile, path: attachedPathOf(e.text), attachmentType, text: e.text } }
90
+ }
91
+ const contextClosed = (e: Frozen<Args<'session.compact'>>) => (where: Place): SessionChange | undefined => {
92
+ const task = e.agentId === undefined ? undefined : where.tasks[e.agentId]
93
+ return e.agentId !== undefined && task === undefined ? undefined : { type: ContextEnd, context: closingContext(where, task, now()) }
94
+ }
95
+ const turnEnded = (turn: TurnData | undefined): SessionChange | undefined => (turn === undefined ? undefined : { type: TurnEnd, turn: { ...turn, closedAt: now() } })
75
96
  const titles = new Map<string, string>()
76
97
  const spawned = new Map<string, { readonly prompt: string; readonly agentType: string }>()
77
98
  const startedBy = new Map<string, string>()
@@ -82,12 +103,12 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
82
103
  return waiting.length === 1 ? waiting[0]?.[0] : undefined
83
104
  }
84
105
  const agentFolders = new Map<string, string>()
85
- const askedAtStop = (turn: TurnData, signal: AbortSignal) =>
106
+ const askedAtStop = (change: SessionChange, signal: AbortSignal) =>
86
107
  new Promise<Partial<Answers>>((resolve, reject) => {
87
108
  if (signal.aborted) return resolve({})
88
109
  const cancelled = () => resolve({})
89
110
  signal.addEventListener('abort', cancelled, { once: true })
90
- asked(TurnEnd, { type: TurnEnd, turn: { ...turn, closedAt: now() } }, fold(signal))
111
+ asked(TurnEnd, change, fold(signal))
91
112
  .then(resolve, reject)
92
113
  .finally(() => signal.removeEventListener('abort', cancelled))
93
114
  })
@@ -112,8 +133,7 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
112
133
  const added: Subscription[] = [
113
134
  router.add('prompt.submit', async (e, next) => {
114
135
  if (!(await wants(Prompt))) return next(e)
115
- const where = await place()
116
- const answer = await asked(Prompt, message(where, { id: '', at: now(), type: Prompt, text: e.text, from: senderOf(e.origin, false) }, undefined, false), fold(next.signal))
136
+ const answer = await asked(Prompt, submitted(e)(await place()), fold(next.signal))
117
137
  if (answer.refuse !== undefined) return { drop: answer.refuse }
118
138
  const text = answer.text ?? e.text
119
139
  if (answer.title !== undefined) titles.set(text, answer.title)
@@ -125,6 +145,9 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
125
145
  if (!('drop' in ran) && typeof ran.text === 'string') titles.set(ran.text, passed)
126
146
  }
127
147
  return ran
148
+ }, (e, error, next) => {
149
+ const refusal = refusedOnFailure(Prompt, submitted(e), error, next)
150
+ return refusal === undefined ? undefined : { drop: refusal }
128
151
  }),
129
152
  router.add('classic.UserPromptSubmit', async (e, next) => {
130
153
  const named = titles.get(e.prompt)
@@ -136,10 +159,12 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
136
159
  router.add('classic.PostToolUseFailure', toolResultHook(true) as never),
137
160
  router.add('session.receive', async (e, next) => {
138
161
  if (!(await wants(Prompt)) || relayOf(e) !== undefined) return next(e)
139
- const where = await place()
140
- const answer = await asked(Prompt, message(where, { id: '', at: now(), type: Prompt, text: e.text, from: { type: 'session' } }, e.agentId, false), fold(next.signal))
162
+ const answer = await asked(Prompt, received(e)(await place()), fold(next.signal))
141
163
  if (answer.refuse !== undefined) return { consumed: answer.refuse }
142
164
  return next(answer.text === undefined ? e : { ...e, text: answer.text })
165
+ }, (e, error, next) => {
166
+ const refusal = relayOf(e) === undefined ? refusedOnFailure(Prompt, received(e), error, next) : undefined
167
+ return refusal === undefined ? undefined : { consumed: refusal }
143
168
  }),
144
169
  router.add('skill.prompt', async (e, next) => {
145
170
  if (!(await wants(Skill))) return next(e)
@@ -148,17 +173,15 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
148
173
  return answer.text === undefined ? next(e) : { text: answer.text }
149
174
  }),
150
175
  router.add('prompt.attachment', async (e, next) => {
151
- const attachmentType = attachmentTypeOf(e.type)
152
- const event = e.type === 'nested_memory' ? InstructionFile : attachmentType === undefined ? undefined : AttachedFile
153
- if (event === undefined || !(await wants(event))) return next(e)
154
- const where = await place()
155
- const found: Unplaced =
156
- attachmentType === undefined
157
- ? { id: '', at: now(), type: InstructionFile, path: instructionPathOf(e.text), text: e.text, isRule: isRulePath(instructionPathOf(e.text)) }
158
- : { id: '', at: now(), type: AttachedFile, path: attachedPathOf(e.text), attachmentType, text: e.text }
159
- const answer = await asked(event, message(where, found, e.agentId), fold(next.signal))
176
+ const attachment = attachmentOf(e)
177
+ if (attachment === undefined || !(await wants(attachment.event))) return next(e)
178
+ const answer = await asked(attachment.event, message(await place(), attachment.found, e.agentId), fold(next.signal))
160
179
  if (answer.refuse !== undefined) return { text: null }
161
180
  return answer.text === undefined ? next(e) : { text: answer.text }
181
+ }, (e, error, next) => {
182
+ const attachment = attachmentOf(e)
183
+ const refusal = attachment === undefined ? undefined : refusedOnFailure(attachment.event, (where) => message(where, attachment.found, e.agentId), error, next)
184
+ return refusal === undefined ? undefined : { text: null }
162
185
  }),
163
186
  router.add('session.append', async (e, next) => {
164
187
  const wanted = new Set((await Promise.all(appended.map(async (event) => ((await wants(event)) ? [event] : [])))).flat())
@@ -179,14 +202,16 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
179
202
  router.add('tool.call', async (e, next) => {
180
203
  if (!(await wants(ToolCall))) return next(e)
181
204
  const where = await place()
182
- const input = toolInputOf(e)
183
- const cwd = (e.agentId === undefined ? undefined : agentFolders.get(e.agentId)) ?? (await claude.session.cwd())
184
- const answer = await asked(ToolCall, message(where, { id: e.tool_use_id, at: now(), type: ToolCall, callId: e.tool_use_id, name: e.tool, input, cwd, files: noFiles }, e.agentId), fold(next.signal))
205
+ const answer = await asked(ToolCall, toolCalled(e, await cwdOf(e.agentId))(where), fold(next.signal))
185
206
  if (answer.refuse !== undefined) return { deny: answer.refuse }
186
207
  if (answer.result !== undefined) return withContext({ result: answer.result }, answer.note)
187
208
  if (answer.input === undefined) return withContext(await next(e), answer.note)
209
+ const input = toolInputOf(e)
188
210
  const reserved = Object.fromEntries(Object.entries(e).filter(([key]) => !(key in input)))
189
211
  return withContext(await next({ ...reserved, ...answer.input } as Frozen<Args<'tool.call'>>), answer.note)
212
+ }, async (e, error, next) => {
213
+ const refusal = refusedOnFailure(ToolCall, toolCalled(e, await cwdOf(e.agentId)), error, next)
214
+ return refusal === undefined ? undefined : { deny: refusal }
190
215
  }),
191
216
  router.add('agent.spawn', async (e, next) => {
192
217
  spawned.set(e.tool_use_id, { prompt: e.prompt, agentType: e.subagentType })
@@ -199,9 +224,8 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
199
224
  return started
200
225
  }
201
226
  if (!(await wants(TaskStart))) return start(e)
202
- const where = await place()
203
- const task: TaskData = { id: '', title: e.description, ...ownerOfSpawn(e.subagentType, where.session), model: e.model ?? e.parentModel, openedBy: e.tool_use_id, openedAt: now(), ...(e.parentAgentId === undefined ? {} : { parent: e.parentAgentId }) }
204
- const answer = await asked(TaskStart, { type: TaskStart, task: { ...task, context: where.context } }, fold(next.signal))
227
+ const task = startedTask(e, await place())
228
+ const answer = await asked(TaskStart, { type: TaskStart, task }, fold(next.signal))
205
229
  if (answer.refuse !== undefined) {
206
230
  spawned.delete(e.tool_use_id)
207
231
  return { deny: answer.refuse }
@@ -221,6 +245,11 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
221
245
  }
222
246
  spawned.set(e.tool_use_id, { prompt: answered.prompt, agentType: answered.subagentType })
223
247
  return start(answered)
248
+ }, (e, error, next) => {
249
+ const refusal = refusedOnFailure(TaskStart, (where) => ({ type: TaskStart, task: startedTask(e, where) }), error, next)
250
+ if (refusal === undefined) return undefined
251
+ spawned.delete(e.tool_use_id)
252
+ return { deny: refusal }
224
253
  }),
225
254
  router.add('classic.SubagentStart', async (e, next) => {
226
255
  const where = await place()
@@ -241,26 +270,34 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
241
270
  return answer
242
271
  }
243
272
  if (next.signal.aborted || !(await wants(TurnEnd))) return stopped(await next(e))
244
- const turn = (await place()).taskTurns[e.agent_id]
245
- if (turn === undefined) return stopped(await next(e))
246
- const answer = await askedAtStop(turn, next.signal)
273
+ const change = turnEnded((await place()).taskTurns[e.agent_id])
274
+ if (change === undefined) return stopped(await next(e))
275
+ const answer = await askedAtStop(change, next.signal)
247
276
  return stopped(answeredStop(await next(e), answer, next.signal))
277
+ }, async (e, error, next) => {
278
+ const refusal = refusedOnFailure(TurnEnd, (where) => turnEnded(where.taskTurns[e.agent_id]), error, next)
279
+ return refusal === undefined ? undefined : { ...(await next(e)), block: refusal }
248
280
  }),
249
281
  router.add('classic.Stop', async (e, next) => {
250
282
  if (next.signal.aborted || !(await wants(TurnEnd))) return next(e)
251
- const { turn } = await place()
252
- if (turn === undefined) return next(e)
253
- const answer = await askedAtStop(turn, next.signal)
283
+ const change = turnEnded((await place()).turn)
284
+ if (change === undefined) return next(e)
285
+ const answer = await askedAtStop(change, next.signal)
254
286
  return answeredStop(await next(e), answer, next.signal)
287
+ }, async (e, error, next) => {
288
+ const refusal = refusedOnFailure(TurnEnd, (where) => turnEnded(where.turn), error, next)
289
+ return refusal === undefined ? undefined : { ...(await next(e)), block: refusal }
255
290
  }),
256
291
  router.add('session.compact', async (e, next) => {
257
292
  if (!(await wants(ContextEnd)) || e.trigger === 'precompute') return next(e)
258
- const where = await place()
259
- const task = e.agentId === undefined ? undefined : where.tasks[e.agentId]
260
- if (e.agentId !== undefined && task === undefined) return next(e)
261
- const answer = await asked(ContextEnd, { type: ContextEnd, context: closingContext(where, task, now()) }, fold(next.signal))
293
+ const change = contextClosed(e)(await place())
294
+ if (change === undefined) return next(e)
295
+ const answer = await asked(ContextEnd, change, fold(next.signal))
262
296
  if (answer.refuse !== undefined) return { skip: answer.refuse }
263
297
  return answer.summary === undefined ? next(e) : { messages: [{ role: 'user', text: answer.summary, toolUses: [] }] }
298
+ }, (e, error, next) => {
299
+ const refusal = e.trigger === 'precompute' ? undefined : refusedOnFailure(ContextEnd, contextClosed(e), error, next)
300
+ return refusal === undefined ? undefined : { skip: refusal }
264
301
  }),
265
302
  ]
266
303
  return { remove: () => added.forEach((each) => each.remove()) }