@cmodjs/core 5.6.0 → 5.8.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.
- package/docs/commands.md +7 -5
- package/docs/dependencies.md +2 -2
- package/docs/install-steps.md +1 -1
- package/docs/mod.md +1 -1
- package/docs/ui.md +5 -3
- package/package.json +2 -2
- package/records.d.ts +15 -2
- package/records.d.ts.map +1 -1
- package/records.js +15 -3
- package/register.d.ts +3 -0
- package/register.d.ts.map +1 -1
- package/register.js +25 -15
- package/runtime/before.d.ts +3 -0
- package/runtime/before.d.ts.map +1 -1
- package/runtime/before.js +66 -31
- package/runtime/conversations.d.ts.map +1 -1
- package/runtime/conversations.js +29 -9
- package/runtime/lifecycle.d.ts +24 -2
- package/runtime/lifecycle.d.ts.map +1 -1
- package/runtime/lifecycle.js +36 -31
- package/runtime/pages.d.ts +2 -1
- package/runtime/pages.d.ts.map +1 -1
- package/runtime/pages.js +3 -6
- package/runtime/programs.d.ts +1 -0
- package/runtime/programs.d.ts.map +1 -1
- package/runtime/programs.js +8 -1
- package/runtime/router.d.ts +4 -2
- package/runtime/router.d.ts.map +1 -1
- package/runtime/router.js +10 -8
- package/runtime/toaster.d.ts.map +1 -1
- package/runtime/toaster.js +15 -7
- package/runtime/ui.d.ts.map +1 -1
- package/runtime/ui.js +27 -24
- package/src/records.ts +17 -3
- package/src/register.ts +29 -13
- package/src/runtime/before.ts +71 -34
- package/src/runtime/conversations.ts +26 -8
- package/src/runtime/lifecycle.ts +61 -43
- package/src/runtime/pages.ts +4 -3
- package/src/runtime/programs.ts +12 -1
- package/src/runtime/router.ts +11 -9
- package/src/runtime/toaster.ts +15 -7
- package/src/runtime/ui.ts +24 -21
- package/src/testing/fake-elements.ts +15 -3
- package/src/testing.ts +6 -3
- package/testing/fake-elements.js +15 -3
- package/testing.d.ts.map +1 -1
- package/testing.js +6 -3
- package/vendor-markdown.js +4 -8698
- package/vendor.js +7 -3384
package/runtime/ui.js
CHANGED
|
@@ -586,37 +586,39 @@ export function createUi({ name, claude, router, report, announce, mod, borrowed
|
|
|
586
586
|
draws.delete(draw);
|
|
587
587
|
latestDraws.delete(key);
|
|
588
588
|
};
|
|
589
|
-
const drawPart = (key, title, input, render) => {
|
|
589
|
+
const drawPart = (key, title, input, render, drawFailure = () => undefined) => {
|
|
590
|
+
let handlers = [];
|
|
591
|
+
let tree;
|
|
590
592
|
try {
|
|
591
|
-
|
|
592
|
-
const tree = treeOf(render, pressed);
|
|
593
|
+
tree = treeOf(render, handlers);
|
|
593
594
|
failedDraws.delete(key);
|
|
594
|
-
const number = nextDraw();
|
|
595
|
-
const inputs = latestDraws.get(key) ?? new Map();
|
|
596
|
-
latestDraws.set(key, inputs);
|
|
597
|
-
const drawnFor = JSON.stringify('turn' in input ? { ...input, turn: input.turn.prompt.id } : input);
|
|
598
|
-
const earlier = inputs.get(drawnFor)?.draws ?? [];
|
|
599
|
-
const kept = [...earlier, number].slice(-2);
|
|
600
|
-
for (const draw of earlier)
|
|
601
|
-
if (!kept.includes(draw))
|
|
602
|
-
draws.delete(draw);
|
|
603
|
-
inputs.delete(drawnFor);
|
|
604
|
-
inputs.set(drawnFor, { draws: kept, tree: JSON.stringify(tree), render });
|
|
605
|
-
const [oldest] = inputs;
|
|
606
|
-
if (inputs.size > keptDrawInputs && oldest !== undefined) {
|
|
607
|
-
for (const draw of oldest[1].draws)
|
|
608
|
-
draws.delete(draw);
|
|
609
|
-
inputs.delete(oldest[0]);
|
|
610
|
-
}
|
|
611
|
-
draws.set(number, { id: key, handlers: pressed });
|
|
612
|
-
return { draw: number, tree };
|
|
613
595
|
}
|
|
614
596
|
catch (error) {
|
|
615
597
|
if (!failedDraws.has(key))
|
|
616
598
|
report({ id: key, message: `The ${title} could not draw`, error });
|
|
617
599
|
failedDraws.add(key);
|
|
618
|
-
|
|
600
|
+
handlers = [];
|
|
601
|
+
tree = treeOf(() => drawFailure(error), handlers);
|
|
602
|
+
}
|
|
603
|
+
const number = nextDraw();
|
|
604
|
+
const inputs = latestDraws.get(key) ?? new Map();
|
|
605
|
+
latestDraws.set(key, inputs);
|
|
606
|
+
const drawnFor = JSON.stringify('turn' in input ? { ...input, turn: input.turn.prompt.id } : input);
|
|
607
|
+
const earlier = inputs.get(drawnFor)?.draws ?? [];
|
|
608
|
+
const kept = [...earlier, number].slice(-2);
|
|
609
|
+
for (const draw of earlier)
|
|
610
|
+
if (!kept.includes(draw))
|
|
611
|
+
draws.delete(draw);
|
|
612
|
+
inputs.delete(drawnFor);
|
|
613
|
+
inputs.set(drawnFor, { draws: kept, tree: JSON.stringify(tree), render });
|
|
614
|
+
const [oldest] = inputs;
|
|
615
|
+
if (inputs.size > keptDrawInputs && oldest !== undefined) {
|
|
616
|
+
for (const draw of oldest[1].draws)
|
|
617
|
+
draws.delete(draw);
|
|
618
|
+
inputs.delete(oldest[0]);
|
|
619
619
|
}
|
|
620
|
+
draws.set(number, { id: key, handlers });
|
|
621
|
+
return { draw: number, tree };
|
|
620
622
|
};
|
|
621
623
|
const draw = (input) => {
|
|
622
624
|
if ('markdown' in input)
|
|
@@ -625,7 +627,8 @@ export function createUi({ name, claude, router, report, announce, mod, borrowed
|
|
|
625
627
|
const added = pages.get(input.page);
|
|
626
628
|
if (added === undefined)
|
|
627
629
|
throw new Error(`${name} has no ${input.page} page.`);
|
|
628
|
-
|
|
630
|
+
const title = `${added.init.title} page`;
|
|
631
|
+
return drawPart(`page:${input.page}`, title, input, () => added.init.render(mod(), { params: input.params, isFocused: input.isFocused, columns: input.columns }), (error) => Text({ color: 'error', children: `The ${title} could not draw: ${messageOf(error)}` }));
|
|
629
632
|
}
|
|
630
633
|
const widget = widgets.get(input.widget);
|
|
631
634
|
if (widget === undefined || !widget.areas.includes(input.area))
|
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.
|
|
372
|
+
export const coreVersion = '5.8.0'
|
|
365
373
|
|
|
366
374
|
export const oldestCmodVersion = '5.4.0'
|
|
367
375
|
|
|
@@ -393,8 +401,14 @@ function readCommand(steps: Record<string, unknown>, key: 'install' | 'uninstall
|
|
|
393
401
|
return { [key]: command }
|
|
394
402
|
}
|
|
395
403
|
|
|
396
|
-
export function
|
|
397
|
-
return
|
|
404
|
+
export function bundleOptions(steps: Steps) {
|
|
405
|
+
return {
|
|
406
|
+
format: 'esm' as const,
|
|
407
|
+
target: 'browser' as const,
|
|
408
|
+
external: ['claude-code'],
|
|
409
|
+
define: steps.approve === true ? {} : { 'globalThis.cmodWithoutApprove': 'true' },
|
|
410
|
+
minify: { whitespace: true, identifiers: true },
|
|
411
|
+
}
|
|
398
412
|
}
|
|
399
413
|
|
|
400
414
|
export function scriptPaths(command: string): string[] {
|
package/src/register.ts
CHANGED
|
@@ -3,11 +3,13 @@ import type { ModDefinition } from './mod.js'
|
|
|
3
3
|
import type { Options } from './options.js'
|
|
4
4
|
import type { Claude } from './runtime/claude.js'
|
|
5
5
|
import type { RoutedEvent } from './runtime/hooks.js'
|
|
6
|
+
import { serveConversations } from './runtime/conversations.js'
|
|
6
7
|
import { settledAfterAbort } from './runtime/deadline.js'
|
|
7
|
-
import { cmodPluginName } from './runtime/dependencies.js'
|
|
8
8
|
import { readDevice } from './runtime/device.js'
|
|
9
|
-
import { createLifecycle, readPlugin, type Lifecycle } from './runtime/lifecycle.js'
|
|
9
|
+
import { createLifecycle, readPlugin, type Lifecycle, type ServeCmodPlugin } from './runtime/lifecycle.js'
|
|
10
|
+
import { servePages } from './runtime/pages.js'
|
|
10
11
|
import { permissionRoutes, type PermissionRoutes } from './runtime/permission-check.js'
|
|
12
|
+
import { serveWidgets } from './runtime/widgets.js'
|
|
11
13
|
import { messageOf } from './utils/text.js'
|
|
12
14
|
|
|
13
15
|
let lifecycle: Lifecycle<object>
|
|
@@ -136,10 +138,34 @@ function routeCallFailure(_$: EngineInterface, eventInput: Frozen<Args<'cmod.cal
|
|
|
136
138
|
return lifecycle.caught('cmod.call', withCaller(eventInput, passOn), withoutCaller(passOn), passOn)
|
|
137
139
|
}
|
|
138
140
|
|
|
141
|
+
export const serveCmodPlugin: ServeCmodPlugin = ({ claude, router, store, project, report, clear, tellRefusedPress, parts, markdownIn, tellStylers }) => {
|
|
142
|
+
const conversations = serveConversations({ claude, router, store, project, report, clear })
|
|
143
|
+
const widgets = serveWidgets({ claude, router, store, report, turnClosedBy: (rowId) => conversations.turnClosedBy(rowId), parts, markdownIn })
|
|
144
|
+
const pages = servePages({ claude, router, report, tellRefusedPress, widgets, parts, tellStylers })
|
|
145
|
+
return { conversations, widgets, pages }
|
|
146
|
+
}
|
|
147
|
+
|
|
139
148
|
export function registerMod<State extends object, Declared extends Options>(addHook: On, definition: ModDefinition<State, string, Declared>, options: PluginOptions): void {
|
|
149
|
+
registerHooks(addHook, definition, options)
|
|
150
|
+
addHook('ui.render', routeToMod).catch(routeFailure)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function registerCmodPlugin<State extends object, Declared extends Options>(addHook: On, definition: ModDefinition<State, string, Declared>, options: PluginOptions): void {
|
|
154
|
+
registerHooks(addHook, definition, options, serveCmodPlugin)
|
|
155
|
+
addHook('ui.render', { component: ['AbovePrompt', 'PromptHint', 'SessionMode', 'Spinner', 'TurnDuration', 'Pane'] }, routeToMod).catch(routeFailure)
|
|
156
|
+
addHook('command.describe', { command: /--/ }, routeToMod).catch(routeFailure)
|
|
157
|
+
addHook('session.append', routeToMod).catch(routeFailure)
|
|
158
|
+
addHook('session.receive', routeToMod).catch(routeFailure)
|
|
159
|
+
addHook('agent.spawn', routeToMod).catch(routeFailure)
|
|
160
|
+
addHook('prompt.attachment', routeToMod).catch(routeFailure)
|
|
161
|
+
addHook('turn.start', routeToMod).catch(routeFailure)
|
|
162
|
+
addHook('turn.complete', routeToMod).catch(routeFailure)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function registerHooks<State extends object, Declared extends Options>(addHook: On, definition: ModDefinition<State, string, Declared>, options: PluginOptions, serve?: ServeCmodPlugin): void {
|
|
140
166
|
permissionCheck = undefined
|
|
141
167
|
registered = definition
|
|
142
|
-
lifecycle = createLifecycle(definition, () => permissionCheck, options)
|
|
168
|
+
lifecycle = createLifecycle(definition, () => permissionCheck, options, true, serve)
|
|
143
169
|
addHook('session.start', startMod)
|
|
144
170
|
addHook('classic.Setup', routeToMod).catch(routeFailure)
|
|
145
171
|
addHook('classic.SessionStart', routeToMod).catch(routeFailure)
|
|
@@ -176,21 +202,11 @@ export function registerMod<State extends object, Declared extends Options>(addH
|
|
|
176
202
|
addHook('command.run', routeToMod).catch(routeFailure)
|
|
177
203
|
addHook('session.measure', routeToMod).catch(routeFailure)
|
|
178
204
|
addHook('skill.prompt', routeToMod).catch(routeFailure)
|
|
179
|
-
if (definition.name === cmodPluginName) addHook('ui.render', { component: ['AbovePrompt', 'PromptHint', 'SessionMode', 'Spinner', 'TurnDuration', 'Pane'] }, routeToMod).catch(routeFailure)
|
|
180
|
-
else addHook('ui.render', routeToMod).catch(routeFailure)
|
|
181
205
|
addHook('ui.press', routeToMod).catch(routeFailure)
|
|
182
206
|
addHook('ui.scroll', routeToMod).catch(routeFailure)
|
|
183
207
|
addHook('ui.close', routeToMod).catch(routeFailure)
|
|
184
208
|
addHook('cmod.call', { to: definition.name }, routeCallToMod).catch(routeCallFailure)
|
|
185
209
|
addHook('session.compact', routeToMod).catch(routeFailure)
|
|
186
|
-
if (definition.name !== cmodPluginName) return
|
|
187
|
-
addHook('command.describe', { command: /--/ }, routeToMod).catch(routeFailure)
|
|
188
|
-
addHook('session.append', routeToMod).catch(routeFailure)
|
|
189
|
-
addHook('session.receive', routeToMod).catch(routeFailure)
|
|
190
|
-
addHook('agent.spawn', routeToMod).catch(routeFailure)
|
|
191
|
-
addHook('prompt.attachment', routeToMod).catch(routeFailure)
|
|
192
|
-
addHook('turn.start', routeToMod).catch(routeFailure)
|
|
193
|
-
addHook('turn.complete', routeToMod).catch(routeFailure)
|
|
194
210
|
}
|
|
195
211
|
|
|
196
212
|
export function registerPermissionCheck(addHook: On): void {
|
package/src/runtime/before.ts
CHANGED
|
@@ -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
|
|
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 = {
|
|
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 = (
|
|
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,
|
|
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
|
|
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
|
|
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
|
|
152
|
-
|
|
153
|
-
|
|
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
|
|
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
|
|
203
|
-
const
|
|
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
|
|
245
|
-
if (
|
|
246
|
-
const answer = await askedAtStop(
|
|
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
|
|
252
|
-
if (
|
|
253
|
-
const answer = await askedAtStop(
|
|
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
|
|
259
|
-
|
|
260
|
-
|
|
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()) }
|
|
@@ -15,7 +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, isNotInstalled } from './dependencies.js'
|
|
18
|
-
import { readLines, runCmod, spawnCmod } from './programs.js'
|
|
18
|
+
import { newestCmodVersion, readLines, runCmod, spawnCmod } from './programs.js'
|
|
19
19
|
import type { RoutedHook, Router } from './router.js'
|
|
20
20
|
import { PassedTimeout } from './deadline.js'
|
|
21
21
|
import { conversationMethods, everySession, isAct, isHeardBy, isInScope, pickedColor, resultOf, spawnTask, usageOf, type Act, type Listened, type SessionColor } from './sessions.js'
|
|
@@ -98,6 +98,7 @@ export function serveConversations({
|
|
|
98
98
|
const ownWatches = new Map<string, Watch>()
|
|
99
99
|
let watchers: readonly Watcher[] = []
|
|
100
100
|
let watching: Promise<void> = Promise.resolve()
|
|
101
|
+
let hasReadWatchers = false
|
|
101
102
|
let published = new Set<string>()
|
|
102
103
|
let publishing: Promise<unknown> = Promise.resolve()
|
|
103
104
|
let session = ''
|
|
@@ -190,22 +191,27 @@ export function serveConversations({
|
|
|
190
191
|
follower?.stop()
|
|
191
192
|
follower = undefined
|
|
192
193
|
if (args.length === 0) return
|
|
194
|
+
const version = newestCmodVersion(claude)
|
|
193
195
|
const stream = spawnCmod(claude, ['history', 'follow', ...args, '--json', '--project', project()], session)
|
|
194
196
|
const started = { sessions: wanted, stop: () => void stream.return(undefined as never) }
|
|
195
197
|
follower = started
|
|
196
|
-
|
|
198
|
+
const followed = readLines(stream, (line) => {
|
|
197
199
|
if (line.trim() === '') return
|
|
198
200
|
const parsed = JSON.parse(line) as { readonly session: string; readonly isInProject: boolean; readonly change: SessionChange }
|
|
199
201
|
dispatch(parsed.session, [parsed.change], parsed.isInProject)
|
|
200
202
|
})
|
|
201
|
-
|
|
203
|
+
void Promise.all([version, followed])
|
|
204
|
+
.then(([, { code, lastError }]) => {
|
|
202
205
|
if (follower === started) throw new Error(`cmod history follow ${formatExit(code, lastError)}`)
|
|
203
206
|
})
|
|
204
|
-
.catch((error: unknown) => {
|
|
207
|
+
.catch(async (error: unknown) => {
|
|
205
208
|
if (follower !== started) return
|
|
206
209
|
follower = undefined
|
|
207
|
-
|
|
210
|
+
started.stop()
|
|
211
|
+
if ((await newestCmodVersion(claude)) === (await version)) throw error
|
|
212
|
+
follow()
|
|
208
213
|
})
|
|
214
|
+
.catch((error: unknown) => report('follow', 'Stopped hearing the other sessions', error))
|
|
209
215
|
}
|
|
210
216
|
|
|
211
217
|
const follow = () => void restartFollower().catch((error: unknown) => report('follow', 'Stopped hearing the other sessions', error))
|
|
@@ -391,8 +397,8 @@ export function serveConversations({
|
|
|
391
397
|
return false
|
|
392
398
|
}
|
|
393
399
|
|
|
394
|
-
const refuses = (watcher: Watcher, event: BeforeEvent, change: SessionChange) =>
|
|
395
|
-
beforeAnswerKeys[event].includes('refuse') && (watcher.refusing ?? []).some(({ event: heard, matcher, scope }) => isInScope(scope ?? {}, session, change, isUnderHere) && isHeardBy(heard, matcher === undefined ? undefined : receivedMatcher(matcher), change))
|
|
400
|
+
const refuses = (watcher: Watcher, event: BeforeEvent, change: SessionChange | undefined) =>
|
|
401
|
+
beforeAnswerKeys[event].includes('refuse') && (watcher.refusing ?? []).some(({ event: heard, matcher, scope }) => (change === undefined ? heard === event : isInScope(scope ?? {}, session, change, isUnderHere) && isHeardBy(heard, matcher === undefined ? undefined : receivedMatcher(matcher), change)))
|
|
396
402
|
|
|
397
403
|
const askAway = async (watcher: Watcher, event: BeforeEvent, change: SessionChange, endsAt: number) => {
|
|
398
404
|
try {
|
|
@@ -416,10 +422,17 @@ export function serveConversations({
|
|
|
416
422
|
}
|
|
417
423
|
|
|
418
424
|
const wants = async (event: BeforeEvent) => {
|
|
419
|
-
await
|
|
425
|
+
await watching
|
|
420
426
|
return deciders(event).length > 0
|
|
421
427
|
}
|
|
422
428
|
|
|
429
|
+
const failedBefore = (event: BeforeEvent, change: (where: Place) => SessionChange | undefined, error: Error) => {
|
|
430
|
+
if (!hasReadWatchers) return { refuse: `${cmodPluginName}: ${error.message}` }
|
|
431
|
+
const changed = change(place())
|
|
432
|
+
const refusing = deciders(event).find((watcher) => refuses(watcher, event, changed))
|
|
433
|
+
return refusing === undefined ? undefined : { refuse: `${refusing.mod}: ${error.message}` }
|
|
434
|
+
}
|
|
435
|
+
|
|
423
436
|
const decide = (cancel?: AbortSignal): Decide => {
|
|
424
437
|
let endsAt: Promise<number> | undefined
|
|
425
438
|
return (event, change) =>
|
|
@@ -458,6 +471,7 @@ export function serveConversations({
|
|
|
458
471
|
},
|
|
459
472
|
wants,
|
|
460
473
|
fold: decide,
|
|
474
|
+
failedBefore,
|
|
461
475
|
},
|
|
462
476
|
})
|
|
463
477
|
|
|
@@ -487,6 +501,10 @@ export function serveConversations({
|
|
|
487
501
|
.then(follow)
|
|
488
502
|
starting = Promise.all([starting, restored]).then(() => undefined)
|
|
489
503
|
reloadWatchers()
|
|
504
|
+
hasReadWatchers = false
|
|
505
|
+
void watching.then(() => {
|
|
506
|
+
if (session === id) hasReadWatchers = true
|
|
507
|
+
})
|
|
490
508
|
if (subscribed.size > 0) void Promise.all([previous === '' ? undefined : clearListeners(previous), saveListeners()]).catch((error: unknown) => report('follow', 'Kept telling the mods about the session from before', error))
|
|
491
509
|
if (ownWatches.size === 0) return
|
|
492
510
|
void Promise.all([previous === '' ? undefined : clearWatches(previous), publishWatches()]).catch((error: unknown) => report('before', 'Kept its before listeners on the session from before', error))
|