@cmodjs/core 5.1.1 → 5.2.1
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 +24 -12
- package/docs/dependencies.md +5 -5
- package/docs/index.md +2 -1
- package/docs/install-steps.md +1 -1
- package/docs/mod.md +44 -1
- package/docs/options.md +1 -1
- package/docs/session.md +5 -1
- package/docs/testing.md +7 -3
- package/mod.d.ts +11 -0
- package/mod.d.ts.map +1 -1
- package/mod.js +3 -0
- package/package.json +1 -1
- package/records.d.ts +2 -2
- package/records.d.ts.map +1 -1
- package/records.js +5 -4
- package/register.d.ts.map +1 -1
- package/register.js +4 -2
- package/runtime/before.d.ts +1 -1
- package/runtime/before.d.ts.map +1 -1
- package/runtime/before.js +33 -21
- package/runtime/claude.d.ts +4 -0
- package/runtime/claude.d.ts.map +1 -1
- package/runtime/conversations.d.ts.map +1 -1
- package/runtime/conversations.js +58 -26
- package/runtime/deadline.d.ts +1 -1
- package/runtime/deadline.d.ts.map +1 -1
- package/runtime/deadline.js +7 -2
- package/runtime/device.d.ts +6 -0
- package/runtime/device.d.ts.map +1 -0
- package/runtime/device.js +58 -0
- package/runtime/hooks.d.ts +1 -1
- package/runtime/hooks.d.ts.map +1 -1
- package/runtime/hooks.js +1 -1
- package/runtime/lifecycle.d.ts +1 -1
- package/runtime/lifecycle.d.ts.map +1 -1
- package/runtime/lifecycle.js +30 -7
- package/runtime/permission-check.d.ts +1 -1
- package/runtime/permission-check.d.ts.map +1 -1
- package/runtime/permission-check.js +5 -5
- package/runtime/router.d.ts +7 -3
- package/runtime/router.d.ts.map +1 -1
- package/runtime/router.js +5 -3
- package/runtime/sessions.d.ts +10 -6
- package/runtime/sessions.d.ts.map +1 -1
- package/runtime/sessions.js +60 -37
- package/session/context/turn/device.d.ts +10 -0
- package/session/context/turn/device.d.ts.map +1 -0
- package/session/context/turn/device.js +11 -0
- package/session/context/turn/turn.d.ts +2 -0
- package/session/context/turn/turn.d.ts.map +1 -1
- package/session/conversation.d.ts +4 -1
- package/session/conversation.d.ts.map +1 -1
- package/session/conversation.js +8 -3
- package/src/mod.ts +12 -0
- package/src/records.ts +5 -4
- package/src/register.ts +5 -3
- package/src/runtime/before.ts +35 -24
- package/src/runtime/claude.ts +2 -0
- package/src/runtime/conversations.ts +63 -34
- package/src/runtime/deadline.ts +7 -2
- package/src/runtime/device.ts +65 -0
- package/src/runtime/hooks.ts +3 -3
- package/src/runtime/lifecycle.ts +33 -8
- package/src/runtime/permission-check.ts +6 -6
- package/src/runtime/router.ts +14 -7
- package/src/runtime/sessions.ts +67 -39
- package/src/session/context/turn/device.ts +21 -0
- package/src/session/context/turn/turn.ts +2 -0
- package/src/session/conversation.ts +10 -5
- package/src/testing/claude-code.ts +2 -2
- package/src/testing/fake-claude.ts +6 -1
- package/src/testing.ts +50 -13
- package/testing/claude-code.d.ts +2 -2
- package/testing/claude-code.d.ts.map +1 -1
- package/testing/fake-claude.d.ts +3 -0
- package/testing/fake-claude.d.ts.map +1 -1
- package/testing/fake-claude.js +3 -1
- package/testing.d.ts +1 -0
- package/testing.d.ts.map +1 -1
- package/testing.js +53 -12
- package/vendor-markdown.js +744 -738
- package/vendor.js +122 -106
package/session/conversation.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ContextEnd, ContextStart } from './context/context.js';
|
|
2
|
+
import { deviceOf } from './context/turn/device.js';
|
|
2
3
|
import { Message, messagesOf, tagOf, textOf } from './context/turn/message/message.js';
|
|
3
4
|
import { Note } from './context/turn/message/note.js';
|
|
4
5
|
import { Prompt } from './context/turn/message/prompt.js';
|
|
@@ -25,7 +26,7 @@ export function emptyConversation(session) {
|
|
|
25
26
|
return { session, context: 0, contextOpenedAt: '', agentCalls: [], endedCalls: {}, tasks: {}, taskTurns: {} };
|
|
26
27
|
}
|
|
27
28
|
export function createConversation(start) {
|
|
28
|
-
let { context, contextOpenedAt, turn, goal } = start;
|
|
29
|
+
let { context, contextOpenedAt, turn, goal, device } = start;
|
|
29
30
|
const agentCalls = new Set(start.agentCalls);
|
|
30
31
|
const endedCalls = new Map(Object.entries(start.endedCalls));
|
|
31
32
|
const tasks = new Map(Object.entries(start.tasks));
|
|
@@ -95,9 +96,12 @@ export function createConversation(start) {
|
|
|
95
96
|
const owner = task === undefined ? undefined : tasks.get(task);
|
|
96
97
|
const placedIn = owner?.context ?? context;
|
|
97
98
|
for (const unplaced of messagesOf(row, task !== undefined)) {
|
|
99
|
+
if (task === undefined && unplaced.type === Note)
|
|
100
|
+
device = deviceOf(unplaced) ?? device;
|
|
98
101
|
if (unplaced.type === Prompt) {
|
|
99
102
|
changes.push(...(task === undefined ? endTurn(row.at) : endTaskTurn(task, row.at)));
|
|
100
|
-
const
|
|
103
|
+
const ranOn = task === undefined ? device : owner?.device;
|
|
104
|
+
const opened = { prompt: { ...unplaced, session: start.session, context: placedIn, turn: unplaced.id, ...(task === undefined ? {} : { task }) }, context: placedIn, openedAt: row.at, ...(owner?.closedAt === undefined ? {} : { closedAt: owner.closedAt }), ...(ranOn === undefined ? {} : { device: ranOn }) };
|
|
101
105
|
if (task === undefined)
|
|
102
106
|
turn = opened;
|
|
103
107
|
else
|
|
@@ -136,7 +140,7 @@ export function createConversation(start) {
|
|
|
136
140
|
startTask(data) {
|
|
137
141
|
if (tasks.has(data.id))
|
|
138
142
|
return [];
|
|
139
|
-
const started = { ...data, context };
|
|
143
|
+
const started = { ...data, context, ...(device === undefined ? {} : { device }) };
|
|
140
144
|
tasks.set(data.id, started);
|
|
141
145
|
agentCalls.add(data.openedBy);
|
|
142
146
|
const changes = [{ type: TaskStart, task: started }];
|
|
@@ -163,6 +167,7 @@ export function createConversation(start) {
|
|
|
163
167
|
contextOpenedAt,
|
|
164
168
|
...(turn === undefined ? {} : { turn }),
|
|
165
169
|
...(goal === undefined ? {} : { goal }),
|
|
170
|
+
...(device === undefined ? {} : { device }),
|
|
166
171
|
agentCalls: [...agentCalls],
|
|
167
172
|
endedCalls: Object.fromEntries(endedCalls),
|
|
168
173
|
tasks: Object.fromEntries(tasks),
|
package/src/mod.ts
CHANGED
|
@@ -21,6 +21,7 @@ import { checkHotkeys, type Hotkey, type HotkeyInit, type Hotkeys } from './hotk
|
|
|
21
21
|
import { checkSteps, type Step } from './installer.js'
|
|
22
22
|
import { checkOptions, type Option, type Options, type OptionValues } from './options.js'
|
|
23
23
|
import { bound } from './runtime/bound.js'
|
|
24
|
+
import type { Device } from './session/context/turn/device.js'
|
|
24
25
|
import { Mod as modSender } from './session/context/turn/message/sender.js'
|
|
25
26
|
import { sessionEvents, type BeforeMethod, type CommandRun, type CommandRunAnswer, type OnMethod, type OnMethods, type Sessions } from './session/session.js'
|
|
26
27
|
import type { Widget, WidgetInit } from './ui/areas.js'
|
|
@@ -137,6 +138,7 @@ export type Imports = {
|
|
|
137
138
|
spawn(argv: readonly string[], init?: Omit<ProcessSpawnRequest, 'argv'>): HookStream<ProcessSpawnChunk, ProcessSpawnResult>
|
|
138
139
|
}
|
|
139
140
|
readonly http: { fetch(url: string, init?: HttpInit): Promise<HttpResponse> }
|
|
141
|
+
readonly device: { read(): Promise<Device> }
|
|
140
142
|
readonly clipboard: { write(text: string): Promise<void> }
|
|
141
143
|
}
|
|
142
144
|
|
|
@@ -195,6 +197,10 @@ export const http: Imports['http'] = {
|
|
|
195
197
|
fetch: (url, init) => bound().http.fetch(url, init),
|
|
196
198
|
}
|
|
197
199
|
|
|
200
|
+
export const device: Imports['device'] = {
|
|
201
|
+
read: () => bound().device.read(),
|
|
202
|
+
}
|
|
203
|
+
|
|
198
204
|
export const clipboard: Imports['clipboard'] = {
|
|
199
205
|
write: (text) => bound().clipboard.write(text),
|
|
200
206
|
}
|
|
@@ -203,6 +209,11 @@ export type Mod<State extends object = Record<never, never>, Declared extends Op
|
|
|
203
209
|
readonly name: string
|
|
204
210
|
readonly folder: string
|
|
205
211
|
readonly dataFolder: string
|
|
212
|
+
readonly secrets: {
|
|
213
|
+
get(key: string): Promise<string | undefined>
|
|
214
|
+
store(key: string, value: string): Promise<void>
|
|
215
|
+
delete(key: string): Promise<void>
|
|
216
|
+
}
|
|
206
217
|
readonly state: Readonly<State>
|
|
207
218
|
readonly options: OptionValues<Declared>
|
|
208
219
|
readonly hotkeys: { readonly [Key in keyof Keys]: Hotkey }
|
|
@@ -280,6 +291,7 @@ export type { Tool } from './jobs/tool.js'
|
|
|
280
291
|
export { Session, type AnswerOptions, type BeforeMethods, type Surface, type Listener, type ListenerTime, type OnMethods, type ReadOptions, type RecordPart, type Refusal, type SearchOptions, type SessionScope, type SessionSend, type Sessions, type CurrentSession, type Placement, type ProjectSetup, type SessionStartAsked, type SessionStarted, type SessionEnded, type ModelChange, type CwdChange, type DirectoryAdd, type Worktree, type Notification, type Elicitation, type ElicitationResponse, type McpServer, type PermissionUpdate, type PermissionCheck, type PermissionRequest, type PermissionDenial, type BatchedCall, type ToolBatch, type Todo, type ReplyDisplay, type TaskOwner, type TaskStartArgs, type ToolCallArgs, type Usage, type RateLimit, type CommandRun, type CommandRunAnswer } from './session/session.js'
|
|
281
292
|
export type { Context } from './session/context/context.js'
|
|
282
293
|
export type { Turn } from './session/context/turn/turn.js'
|
|
294
|
+
export type { Device } from './session/context/turn/device.js'
|
|
283
295
|
export type { Message, MessageType } from './session/context/turn/message/message.js'
|
|
284
296
|
export { Prompt } from './session/context/turn/message/prompt.js'
|
|
285
297
|
export { Note } from './session/context/turn/message/note.js'
|
package/src/records.ts
CHANGED
|
@@ -223,8 +223,9 @@ export function updatesToTurnOn(marketplace: string | undefined, settings: unkno
|
|
|
223
223
|
const declared = isObject(settings) && isObject(settings['extraKnownMarketplaces']) ? settings['extraKnownMarketplaces'][marketplace] : undefined
|
|
224
224
|
const fetched = isObject(known) ? known[marketplace] : undefined
|
|
225
225
|
const isDecided = [declared, fetched].some((entry) => isObject(entry) && typeof entry['autoUpdate'] === 'boolean')
|
|
226
|
-
const
|
|
227
|
-
|
|
226
|
+
const sources = [declared, fetched].flatMap((entry) => (isObject(entry) && isObject(entry['source']) ? [entry['source']] : []))
|
|
227
|
+
const isFolder = sources.some((source) => source['source'] === 'directory')
|
|
228
|
+
return isDecided || isFolder || sources.length === 0 ? undefined : marketplace
|
|
228
229
|
}
|
|
229
230
|
|
|
230
231
|
export function consentPath(store: string): string {
|
|
@@ -306,9 +307,9 @@ function readHotkeys(hotkeys: unknown): Steps {
|
|
|
306
307
|
return { hotkeys: checkHotkeys('package.json "cmod"', hotkeys as Record<string, HotkeyInit>) }
|
|
307
308
|
}
|
|
308
309
|
|
|
309
|
-
export const coreVersion = '5.
|
|
310
|
+
export const coreVersion = '5.2.1'
|
|
310
311
|
|
|
311
|
-
export const oldestCmodVersion = '5.
|
|
312
|
+
export const oldestCmodVersion = '5.2.0'
|
|
312
313
|
|
|
313
314
|
export function hotkeyCommand(mod: string, hotkey: string): string {
|
|
314
315
|
return `${mod}--${hotkey}`
|
package/src/register.ts
CHANGED
|
@@ -4,6 +4,7 @@ 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
6
|
import { cmodPluginName } from './runtime/dependencies.js'
|
|
7
|
+
import { readDevice } from './runtime/device.js'
|
|
7
8
|
import { createLifecycle, readPlugin, type Lifecycle } from './runtime/lifecycle.js'
|
|
8
9
|
import { permissionRoutes, type PermissionRoutes } from './runtime/permission-check.js'
|
|
9
10
|
|
|
@@ -84,16 +85,17 @@ async function startMod($: EngineInterface, eventInput: Frozen<Args<'session.sta
|
|
|
84
85
|
dataHome: () => $.env.get('XDG_DATA_HOME'),
|
|
85
86
|
configHome: () => $.env.get('CLAUDE_CONFIG_DIR'),
|
|
86
87
|
},
|
|
88
|
+
device: { read: () => readDevice(claude) },
|
|
87
89
|
cmod: { call: (input) => $.cmod.call(input) },
|
|
88
90
|
}
|
|
89
91
|
const [, answer] = await Promise.all([lifecycle.start(claude, readPlugin), passOn(eventInput)])
|
|
90
92
|
return answer
|
|
91
93
|
}
|
|
92
94
|
|
|
93
|
-
type PassOn<N extends RoutedEvent> = { readonly event: N; (e: never): Promise<EventResult<N>> }
|
|
95
|
+
type PassOn<N extends RoutedEvent> = { readonly event: N; readonly signal: AbortSignal; (e: never): Promise<EventResult<N>> }
|
|
94
96
|
|
|
95
97
|
function routeToMod<N extends RoutedEvent>(_$: EngineInterface, eventInput: Frozen<Args<N>>, passOn: PassOn<N>): Promise<EventResult<N>> {
|
|
96
|
-
return lifecycle.route(passOn.event, eventInput, (passed: unknown) => passOn(passed as never))
|
|
98
|
+
return lifecycle.route(passOn.event, eventInput, (passed: unknown) => passOn(passed as never), passOn.signal)
|
|
97
99
|
}
|
|
98
100
|
|
|
99
101
|
function routeFailure<N extends RoutedEvent>(_$: EngineInterface, eventInput: Frozen<Args<N>>, passOn: PassOn<N> & Caught): Promise<EventResult<N>> {
|
|
@@ -105,7 +107,7 @@ const withCaller = (eventInput: Frozen<Args<'cmod.call'>>, passOn: Next<'cmod.ca
|
|
|
105
107
|
const withoutCaller = (passOn: Next<'cmod.call'>) => (passed: Frozen<Args<'cmod.call'>>) => passOn(Object.fromEntries(Object.entries(passed).filter(([key]) => key !== 'caller')) as Args<'cmod.call'>)
|
|
106
108
|
|
|
107
109
|
function routeCallToMod(_$: EngineInterface, eventInput: Frozen<Args<'cmod.call'>>, passOn: Next<'cmod.call'>): Promise<EventResult<'cmod.call'>> {
|
|
108
|
-
return lifecycle.route('cmod.call', withCaller(eventInput, passOn), withoutCaller(passOn))
|
|
110
|
+
return lifecycle.route('cmod.call', withCaller(eventInput, passOn), withoutCaller(passOn), passOn.signal)
|
|
109
111
|
}
|
|
110
112
|
|
|
111
113
|
function routeCallFailure(_$: EngineInterface, eventInput: Frozen<Args<'cmod.call'>>, passOn: Next<'cmod.call'> & Caught): Promise<EventResult<'cmod.call'>> {
|
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 TaskData } from '../session/conversation.js'
|
|
16
|
+
import { ownerOfSpawn, type ContextData, type ConversationState, type RunningTask, type SessionChange, type TaskData, 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,7 @@ 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: () => Decide }
|
|
44
|
+
export type BeforeHooks = { readonly place: () => Promise<Place>; readonly wants: (event: BeforeEvent) => Promise<boolean>; readonly fold: (cancel: AbortSignal) => Decide }
|
|
45
45
|
|
|
46
46
|
const appended: readonly BeforeEvent[] = [Note, Reply, Notice]
|
|
47
47
|
|
|
@@ -65,7 +65,7 @@ export function relayOf(e: Frozen<Args<'session.receive'>>): string | undefined
|
|
|
65
65
|
export function installBefore({ claude, router, hooks }: { readonly claude: Claude; readonly router: Router; readonly hooks: BeforeHooks }): Subscription {
|
|
66
66
|
const { place, wants, fold } = hooks
|
|
67
67
|
const now = () => new Date().toISOString()
|
|
68
|
-
const asked = async (event: BeforeEvent, change: SessionChange, decide: Decide
|
|
68
|
+
const asked = async (event: BeforeEvent, change: SessionChange, decide: Decide) => (await decide(event, change)) ?? {}
|
|
69
69
|
const message = (where: Place, unplaced: Unplaced, task: string | undefined, isInTurn = true): SessionChange => {
|
|
70
70
|
const turn = isInTurn ? (task === undefined ? where.turn : where.taskTurns[task]) : undefined
|
|
71
71
|
const context = task === undefined ? where.context : (where.tasks[task]?.context ?? where.context)
|
|
@@ -82,7 +82,20 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
82
82
|
return waiting.length === 1 ? waiting[0]?.[0] : undefined
|
|
83
83
|
}
|
|
84
84
|
const agentFolders = new Map<string, string>()
|
|
85
|
-
const
|
|
85
|
+
const askedAtStop = (turn: TurnData, signal: AbortSignal) =>
|
|
86
|
+
new Promise<Partial<Answers>>((resolve, reject) => {
|
|
87
|
+
if (signal.aborted) return resolve({})
|
|
88
|
+
const cancelled = () => resolve({})
|
|
89
|
+
signal.addEventListener('abort', cancelled, { once: true })
|
|
90
|
+
asked(TurnEnd, { type: TurnEnd, turn: { ...turn, closedAt: now() } }, fold(signal))
|
|
91
|
+
.then(resolve, reject)
|
|
92
|
+
.finally(() => signal.removeEventListener('abort', cancelled))
|
|
93
|
+
})
|
|
94
|
+
const answeredStop = (below: ClassicFields, answer: Partial<Answers>, signal: AbortSignal): ClassicFields => {
|
|
95
|
+
if (signal.aborted) return below
|
|
96
|
+
return answer.refuse === undefined ? withNote(below, answer.note) : { ...below, block: answer.refuse }
|
|
97
|
+
}
|
|
98
|
+
const toolResultHook = (isFailure: boolean) => async (e: Readonly<Record<string, unknown>>, next: ((e: never) => Promise<unknown>) & { readonly signal: AbortSignal }) => {
|
|
86
99
|
if (!(await wants(ToolResult))) return next(e as never)
|
|
87
100
|
const where = await place()
|
|
88
101
|
const name = String(e['tool_name'])
|
|
@@ -90,7 +103,7 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
90
103
|
const input = (typeof e['tool_input'] === 'object' && e['tool_input'] !== null ? e['tool_input'] : {}) as Readonly<Record<string, unknown>>
|
|
91
104
|
const task = typeof e['agent_id'] === 'string' ? e['agent_id'] : undefined
|
|
92
105
|
const result = { id: callId, at: now(), type: ToolResult, callId, name, input, cwd: String(e['cwd']), files: noFiles, output: isFailure ? e['error'] : e['tool_response'], isError: isFailure } as const
|
|
93
|
-
const answer = await asked(ToolResult, message(where, result, task))
|
|
106
|
+
const answer = await asked(ToolResult, message(where, result, task), fold(next.signal))
|
|
94
107
|
const below = await next(e as never)
|
|
95
108
|
const rewritten = answer.output === undefined || isFailure ? {} : name.startsWith('mcp__') ? { updatedMCPToolOutput: answer.output } : { updatedToolOutput: answer.output }
|
|
96
109
|
const failed = answer.isError === true && !isFailure ? { block: answer.note === undefined ? `${name} failed.` : untagged(answer.note) } : {}
|
|
@@ -100,7 +113,7 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
100
113
|
router.add('prompt.submit', async (e, next) => {
|
|
101
114
|
if (!(await wants(Prompt))) return next(e)
|
|
102
115
|
const where = await place()
|
|
103
|
-
const answer = await asked(Prompt, message(where, { id: '', at: now(), type: Prompt, text: e.text, from: senderOf(e.origin, false) }, undefined, false))
|
|
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))
|
|
104
117
|
if (answer.refuse !== undefined) return { drop: answer.refuse }
|
|
105
118
|
const text = answer.text ?? e.text
|
|
106
119
|
if (answer.title !== undefined) titles.set(text, answer.title)
|
|
@@ -124,14 +137,14 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
124
137
|
router.add('session.receive', async (e, next) => {
|
|
125
138
|
if (!(await wants(Prompt)) || relayOf(e) !== undefined) return next(e)
|
|
126
139
|
const where = await place()
|
|
127
|
-
const answer = await asked(Prompt, message(where, { id: '', at: now(), type: Prompt, text: e.text, from: { type: 'session' } }, e.agentId, false))
|
|
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))
|
|
128
141
|
if (answer.refuse !== undefined) return { consumed: answer.refuse }
|
|
129
142
|
return next(answer.text === undefined ? e : { ...e, text: answer.text })
|
|
130
143
|
}),
|
|
131
144
|
router.add('skill.prompt', async (e, next) => {
|
|
132
145
|
if (!(await wants(Skill))) return next(e)
|
|
133
146
|
const where = await place()
|
|
134
|
-
const answer = await asked(Skill, message(where, { id: '', at: now(), type: Skill, name: e.skill, text: e.text }, undefined))
|
|
147
|
+
const answer = await asked(Skill, message(where, { id: '', at: now(), type: Skill, name: e.skill, text: e.text }, undefined), fold(next.signal))
|
|
135
148
|
return answer.text === undefined ? next(e) : { text: answer.text }
|
|
136
149
|
}),
|
|
137
150
|
router.add('prompt.attachment', async (e, next) => {
|
|
@@ -143,7 +156,7 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
143
156
|
attachmentType === undefined
|
|
144
157
|
? { id: '', at: now(), type: InstructionFile, path: instructionPathOf(e.text), text: e.text, isRule: isRulePath(instructionPathOf(e.text)) }
|
|
145
158
|
: { id: '', at: now(), type: AttachedFile, path: attachedPathOf(e.text), attachmentType, text: e.text }
|
|
146
|
-
const answer = await asked(event, message(where, found, e.agentId))
|
|
159
|
+
const answer = await asked(event, message(where, found, e.agentId), fold(next.signal))
|
|
147
160
|
if (answer.refuse !== undefined) return { text: null }
|
|
148
161
|
return answer.text === undefined ? next(e) : { text: answer.text }
|
|
149
162
|
}),
|
|
@@ -155,7 +168,7 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
155
168
|
if (!found.some((each) => wanted.has(each.type))) return next(e)
|
|
156
169
|
const where = await place()
|
|
157
170
|
const texts = new Map<number, string>()
|
|
158
|
-
const decide = fold()
|
|
171
|
+
const decide = fold(next.signal)
|
|
159
172
|
for (const [part, unplaced] of found.entries()) {
|
|
160
173
|
if (!wanted.has(unplaced.type)) continue
|
|
161
174
|
const answer = await asked(unplaced.type, message(where, unplaced, e.agentId), decide)
|
|
@@ -168,7 +181,7 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
168
181
|
const where = await place()
|
|
169
182
|
const input = toolInputOf(e)
|
|
170
183
|
const cwd = (e.agentId === undefined ? undefined : agentFolders.get(e.agentId)) ?? (await claude.session.cwd())
|
|
171
|
-
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))
|
|
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))
|
|
172
185
|
if (answer.refuse !== undefined) return { deny: answer.refuse }
|
|
173
186
|
if (answer.result !== undefined) return withContext({ result: answer.result }, answer.note)
|
|
174
187
|
if (answer.input === undefined) return withContext(await next(e), answer.note)
|
|
@@ -188,7 +201,7 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
188
201
|
if (!(await wants(TaskStart))) return start(e)
|
|
189
202
|
const where = await place()
|
|
190
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 }) }
|
|
191
|
-
const answer = await asked(TaskStart, { type: TaskStart, task: { ...task, context: where.context } })
|
|
204
|
+
const answer = await asked(TaskStart, { type: TaskStart, task: { ...task, context: where.context } }, fold(next.signal))
|
|
192
205
|
if (answer.refuse !== undefined) {
|
|
193
206
|
spawned.delete(e.tool_use_id)
|
|
194
207
|
return { deny: answer.refuse }
|
|
@@ -219,7 +232,7 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
219
232
|
const open = where.taskTurns[e.agent_id]?.prompt
|
|
220
233
|
const text = open?.text ?? prompt
|
|
221
234
|
if (text === undefined) return next(e)
|
|
222
|
-
const answer = await asked(Prompt, message(where, { id: open?.id ?? '', at: now(), type: Prompt, text, from: open?.from ?? { type: Task } }, e.agent_id, false))
|
|
235
|
+
const answer = await asked(Prompt, message(where, { id: open?.id ?? '', at: now(), type: Prompt, text, from: open?.from ?? { type: Task } }, e.agent_id, false), fold(next.signal))
|
|
223
236
|
return withNote(await next(e), answer.note)
|
|
224
237
|
}),
|
|
225
238
|
router.add('classic.SubagentStop', async (e, next) => {
|
|
@@ -227,27 +240,25 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
227
240
|
if (answer.block === undefined) agentFolders.delete(e.agent_id)
|
|
228
241
|
return answer
|
|
229
242
|
}
|
|
230
|
-
if (!(await wants(TurnEnd))) return stopped(await next(e))
|
|
243
|
+
if (next.signal.aborted || !(await wants(TurnEnd))) return stopped(await next(e))
|
|
231
244
|
const turn = (await place()).taskTurns[e.agent_id]
|
|
232
245
|
if (turn === undefined) return stopped(await next(e))
|
|
233
|
-
const answer = await
|
|
234
|
-
|
|
235
|
-
return stopped(answer.refuse === undefined ? withNote(below, answer.note) : { ...below, block: answer.refuse })
|
|
246
|
+
const answer = await askedAtStop(turn, next.signal)
|
|
247
|
+
return stopped(answeredStop(await next(e), answer, next.signal))
|
|
236
248
|
}),
|
|
237
249
|
router.add('classic.Stop', async (e, next) => {
|
|
238
|
-
if (!(await wants(TurnEnd))) return next(e)
|
|
239
|
-
const
|
|
240
|
-
if (
|
|
241
|
-
const answer = await
|
|
242
|
-
|
|
243
|
-
return answer.refuse === undefined ? withNote(below, answer.note) : { ...below, block: answer.refuse }
|
|
250
|
+
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)
|
|
254
|
+
return answeredStop(await next(e), answer, next.signal)
|
|
244
255
|
}),
|
|
245
256
|
router.add('session.compact', async (e, next) => {
|
|
246
257
|
if (!(await wants(ContextEnd)) || e.trigger === 'precompute') return next(e)
|
|
247
258
|
const where = await place()
|
|
248
259
|
const task = e.agentId === undefined ? undefined : where.tasks[e.agentId]
|
|
249
260
|
if (e.agentId !== undefined && task === undefined) return next(e)
|
|
250
|
-
const answer = await asked(ContextEnd, { type: ContextEnd, context: closingContext(where, task, now()) })
|
|
261
|
+
const answer = await asked(ContextEnd, { type: ContextEnd, context: closingContext(where, task, now()) }, fold(next.signal))
|
|
251
262
|
if (answer.refuse !== undefined) return { skip: answer.refuse }
|
|
252
263
|
return answer.summary === undefined ? next(e) : { messages: [{ role: 'user', text: answer.summary, toolUses: [] }] }
|
|
253
264
|
}),
|
package/src/runtime/claude.ts
CHANGED
|
@@ -43,6 +43,7 @@ import type {
|
|
|
43
43
|
UiScrollArgs,
|
|
44
44
|
UiScrollResult,
|
|
45
45
|
} from 'claude-code'
|
|
46
|
+
import type { Device } from '../session/context/turn/device.js'
|
|
46
47
|
|
|
47
48
|
export type Claude = {
|
|
48
49
|
readonly plugin: { readonly name: string; readonly root: string }
|
|
@@ -110,5 +111,6 @@ export type Claude = {
|
|
|
110
111
|
dataHome(): Promise<string | undefined>
|
|
111
112
|
configHome(): Promise<string | undefined>
|
|
112
113
|
}
|
|
114
|
+
readonly device: { read(): Promise<Device> }
|
|
113
115
|
readonly cmod: { call(input: Args<'cmod.call'>): Promise<unknown> }
|
|
114
116
|
}
|
|
@@ -91,7 +91,7 @@ export function serveConversations({
|
|
|
91
91
|
const listeners = `${folder}/listeners`
|
|
92
92
|
const heard = new Map<string, Map<string, readonly Heard[]>>()
|
|
93
93
|
const subscribed = new Map<string, Map<string, readonly Listened[]>>()
|
|
94
|
-
let
|
|
94
|
+
let listenerFiles: Promise<unknown> = Promise.resolve()
|
|
95
95
|
const asked = new Map<string, Asked>()
|
|
96
96
|
const ownWatches = new Map<string, Watch>()
|
|
97
97
|
let watchers: readonly Watcher[] = []
|
|
@@ -112,18 +112,18 @@ export function serveConversations({
|
|
|
112
112
|
engineTurns.set(agent, e.turnId)
|
|
113
113
|
return next(e)
|
|
114
114
|
})
|
|
115
|
-
const endTurn = (ending: TurnEnding, task?: string) => <Below extends { readonly block?: string }>(below: Below): Below => {
|
|
115
|
+
const endTurn = (ending: TurnEnding, task?: string) => <Below extends { readonly block?: string }>(below: Below, isInterrupted = false): Below => {
|
|
116
116
|
if (below.block !== undefined) return below
|
|
117
117
|
engineTurns.delete(task ?? '')
|
|
118
|
-
dispatch(session, conversation.endTurn(new Date().toISOString(), ending, task))
|
|
118
|
+
if (!isInterrupted) dispatch(session, conversation.endTurn(new Date().toISOString(), ending, task))
|
|
119
119
|
return below
|
|
120
120
|
}
|
|
121
|
-
router.add('classic.Stop', async (e, next) => endTurn({ reason: 'answer', ...(e.last_assistant_message === undefined ? {} : { answer: e.last_assistant_message }) })(await next(e)))
|
|
121
|
+
router.add('classic.Stop', async (e, next) => endTurn({ reason: 'answer', ...(e.last_assistant_message === undefined ? {} : { answer: e.last_assistant_message }) })(await next(e), next.signal.aborted))
|
|
122
122
|
router.add('classic.StopFailure', async (e, next) => endTurn({ reason: 'error', failure: { type: String(e.error), text: e.error_details ?? e.last_assistant_message ?? String(e.error) } })(await next(e)))
|
|
123
|
-
router.add('classic.SubagentStop', async (e, next) => endTurn({ reason: 'answer', ...(e.last_assistant_message === undefined ? {} : { answer: e.last_assistant_message }) }, e.agent_id)(await next(e)))
|
|
123
|
+
router.add('classic.SubagentStop', async (e, next) => endTurn({ reason: 'answer', ...(e.last_assistant_message === undefined ? {} : { answer: e.last_assistant_message }) }, e.agent_id)(await next(e), next.signal.aborted))
|
|
124
124
|
router.add('classic.Stop', async (e, next) => {
|
|
125
125
|
const below = await next(e)
|
|
126
|
-
if (below.block === undefined) void answerTask().catch((error: unknown) => report('task', 'Could not record that this session answered its task', error))
|
|
126
|
+
if (below.block === undefined && !next.signal.aborted) void answerTask().catch((error: unknown) => report('task', 'Could not record that this session answered its task', error))
|
|
127
127
|
return below
|
|
128
128
|
})
|
|
129
129
|
|
|
@@ -265,8 +265,12 @@ export function serveConversations({
|
|
|
265
265
|
|
|
266
266
|
const publishNow = async (isEnding: boolean) => {
|
|
267
267
|
if (session === '') return
|
|
268
|
-
const
|
|
269
|
-
await
|
|
268
|
+
const at = session
|
|
269
|
+
const list = await onListenerFiles(async () => {
|
|
270
|
+
const kept = isEnding ? [] : [...ownWatches.values()].filter((watch) => watch.events.length > 0)
|
|
271
|
+
await claude.fs.write(`${watches}/${at}.json`, JSON.stringify(kept))
|
|
272
|
+
return kept
|
|
273
|
+
})
|
|
270
274
|
const targets = new Set([...published, ...list.map((watch) => watch.target)])
|
|
271
275
|
published = new Set(list.map((watch) => watch.target))
|
|
272
276
|
const running = targets.has(everySession) ? (await json<SessionData[]>(['history', 'sessions', '--running'])).map((each) => each.id) : []
|
|
@@ -283,34 +287,56 @@ export function serveConversations({
|
|
|
283
287
|
subscribed.set(caller, lists)
|
|
284
288
|
}
|
|
285
289
|
|
|
290
|
+
const onListenerFiles = <Value>(work: () => Promise<Value>) => {
|
|
291
|
+
const next = listenerFiles.then(work)
|
|
292
|
+
listenerFiles = next.catch((error: unknown) => claude.ui.log(`cmod: reading or writing the mods' listeners failed: ${messageOf(error)}`, { to: 'debug' }))
|
|
293
|
+
return next
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const clearListeners = (at: string) => onListenerFiles(() => claude.fs.write(`${listeners}/${at}.json`, '{}'))
|
|
297
|
+
|
|
298
|
+
const clearWatches = (at: string) => onListenerFiles(() => claude.fs.write(`${watches}/${at}.json`, '[]'))
|
|
299
|
+
|
|
286
300
|
const saveListeners = (isEnding = false) => {
|
|
287
301
|
const at = session
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
return next
|
|
302
|
+
if (at === '') return Promise.resolve()
|
|
303
|
+
if (isEnding) return clearListeners(at)
|
|
304
|
+
return onListenerFiles(() => claude.fs.write(`${listeners}/${at}.json`, JSON.stringify(Object.fromEntries([...subscribed].map(([caller, lists]) => [caller, Object.fromEntries(lists)])))))
|
|
292
305
|
}
|
|
293
306
|
|
|
294
|
-
const restoreListeners =
|
|
295
|
-
const
|
|
296
|
-
|
|
307
|
+
const restoreListeners = () => {
|
|
308
|
+
const at = session
|
|
309
|
+
return onListenerFiles(async () => {
|
|
310
|
+
const kept = JSON.parse(await claude.fs.read(`${listeners}/${at}.json`).catch(ifMissing('{}'))) as Readonly<Record<string, Readonly<Record<string, readonly Listened[]>>>>
|
|
311
|
+
for (const [caller, lists] of Object.entries(kept)) if (!subscribed.has(caller)) for (const [id, list] of Object.entries(lists)) hear(caller, id, list)
|
|
312
|
+
})
|
|
297
313
|
}
|
|
298
314
|
|
|
299
|
-
const readWatchers =
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
const
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
315
|
+
const readWatchers = () =>
|
|
316
|
+
onListenerFiles(async () => {
|
|
317
|
+
const files = await claude.fs.list(watches).catch(ifMissing([]))
|
|
318
|
+
const found: Watcher[] = []
|
|
319
|
+
for (const file of files) {
|
|
320
|
+
const from = file.name.replace(/\.json$/, '')
|
|
321
|
+
if (!file.name.endsWith('.json')) continue
|
|
322
|
+
const text = await claude.fs.read(`${watches}/${file.name}`).catch(ifMissing('[]'))
|
|
323
|
+
let list: readonly Watch[]
|
|
324
|
+
try {
|
|
325
|
+
list = JSON.parse(text) as readonly Watch[]
|
|
326
|
+
} catch (error) {
|
|
327
|
+
if (from === session || !(error instanceof SyntaxError)) throw error
|
|
328
|
+
claude.ui.log(`cmod: session ${from} was writing its before listeners, so it keeps the ones from before until it relays that it changed them`, { to: 'debug' })
|
|
329
|
+
found.push(...watchers.filter((watch) => watch.from === from))
|
|
330
|
+
continue
|
|
331
|
+
}
|
|
332
|
+
if (from === session) {
|
|
333
|
+
for (const watch of list) if (!ownWatches.has(`${watch.mod}\n${watch.target}`)) ownWatches.set(`${watch.mod}\n${watch.target}`, watch)
|
|
334
|
+
continue
|
|
335
|
+
}
|
|
336
|
+
found.push(...list.filter((watch) => watch.target === session || (watch.target === everySession && watch.project === project())).map((watch) => ({ ...watch, from })))
|
|
309
337
|
}
|
|
310
|
-
|
|
311
|
-
}
|
|
312
|
-
watchers = found
|
|
313
|
-
}
|
|
338
|
+
watchers = found
|
|
339
|
+
})
|
|
314
340
|
|
|
315
341
|
const changeGoal = (task: string | undefined, text: string) => dispatch(session, task === undefined ? conversation.changeGoal(text) : [{ type: GoalChange, goal: { text, task } }])
|
|
316
342
|
|
|
@@ -350,7 +376,7 @@ export function serveConversations({
|
|
|
350
376
|
}
|
|
351
377
|
watchers = watchers.filter((each) => each.from !== watcher.from)
|
|
352
378
|
claude.ui.log(`cmod: session ${watcher.from} ended without clearing its before listeners, so they are cleared now`, { to: 'debug' })
|
|
353
|
-
await
|
|
379
|
+
await clearWatches(watcher.from)
|
|
354
380
|
return undefined
|
|
355
381
|
}
|
|
356
382
|
}
|
|
@@ -360,18 +386,21 @@ export function serveConversations({
|
|
|
360
386
|
return deciders(event).length > 0
|
|
361
387
|
}
|
|
362
388
|
|
|
363
|
-
const decide = (): Decide => {
|
|
389
|
+
const decide = (cancel?: AbortSignal): Decide => {
|
|
364
390
|
let endsAt: Promise<number> | undefined
|
|
365
391
|
return (event, change) =>
|
|
366
392
|
foldBefore(
|
|
367
393
|
event,
|
|
368
394
|
change,
|
|
369
395
|
deciders(event).map((watcher) => async (latest: SessionChange) => {
|
|
396
|
+
if (cancel?.aborted === true) return undefined
|
|
370
397
|
if (watcher.from === session) return askHere(watcher.mod, event, latest)
|
|
371
398
|
endsAt ??= claude.clock.now().then((now) => now + awayFoldMs)
|
|
372
399
|
return askAway(watcher, event, latest, await endsAt)
|
|
373
400
|
}),
|
|
374
|
-
(error) =>
|
|
401
|
+
(error) => {
|
|
402
|
+
if (cancel?.aborted !== true) report(`before:${event}`, `Passed the ${event} on without a mod's answer`, error)
|
|
403
|
+
},
|
|
375
404
|
)
|
|
376
405
|
}
|
|
377
406
|
|
|
@@ -422,9 +451,9 @@ export function serveConversations({
|
|
|
422
451
|
.then(follow)
|
|
423
452
|
starting = Promise.all([starting, restored]).then(() => undefined)
|
|
424
453
|
reloadWatchers()
|
|
425
|
-
if (subscribed.size > 0) void Promise.all([previous === '' ? undefined :
|
|
454
|
+
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))
|
|
426
455
|
if (ownWatches.size === 0) return
|
|
427
|
-
void Promise.all([previous === '' ? undefined :
|
|
456
|
+
void Promise.all([previous === '' ? undefined : clearWatches(previous), publishWatches()]).catch((error: unknown) => report('before', 'Kept its before listeners on the session from before', error))
|
|
428
457
|
}
|
|
429
458
|
|
|
430
459
|
const take = async (row: Row, task: string | undefined) => {
|
package/src/runtime/deadline.ts
CHANGED
|
@@ -27,20 +27,25 @@ export function listenerOf(name: string, method: string, args: readonly unknown[
|
|
|
27
27
|
return { matcher: hasMatcher ? args[0] : undefined, listener, options }
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
export async function withinTime<Value>(clock: Pick<Claude['clock'], 'now'>, method: string, { timeoutMs = listenerMs }: ListenOptions, run: (time: ListenTime) => Value | Promise<Value>): Promise<Value> {
|
|
30
|
+
export async function withinTime<Value>(clock: Pick<Claude['clock'], 'now'>, method: string, { timeoutMs = listenerMs }: ListenOptions, cancel: AbortSignal, run: (time: ListenTime) => Value | Promise<Value>): Promise<Value> {
|
|
31
31
|
const controller = new AbortController()
|
|
32
32
|
const deadline = (await clock.now()) + timeoutMs
|
|
33
|
+
cancel.throwIfAborted()
|
|
33
34
|
let timer: unknown
|
|
35
|
+
let cancelled: () => void = () => undefined
|
|
34
36
|
const passed = new Promise<never>((_resolve, reject) => {
|
|
35
37
|
timer = timers.setTimeout(() => {
|
|
36
38
|
controller.abort()
|
|
37
39
|
reject(new PassedTimeout(`${method} passed its ${timeoutMs / 1000} s timeout`))
|
|
38
40
|
}, timeoutMs)
|
|
41
|
+
cancelled = () => reject(cancel.reason)
|
|
42
|
+
cancel.addEventListener('abort', cancelled, { once: true })
|
|
39
43
|
})
|
|
40
44
|
try {
|
|
41
|
-
return await Promise.race([Promise.resolve().then(() => run({ deadline, signal: controller.signal })), passed])
|
|
45
|
+
return await Promise.race([Promise.resolve().then(() => run({ deadline, signal: AbortSignal.any([controller.signal, cancel]) })), passed])
|
|
42
46
|
} finally {
|
|
43
47
|
timers.clearTimeout(timer)
|
|
48
|
+
cancel.removeEventListener('abort', cancelled)
|
|
44
49
|
}
|
|
45
50
|
}
|
|
46
51
|
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { Device } from '../session/context/turn/device.js'
|
|
2
|
+
import { ifMissing } from '../utils/paths.js'
|
|
3
|
+
import { formatExit } from '../utils/text.js'
|
|
4
|
+
import type { Claude } from './claude.js'
|
|
5
|
+
|
|
6
|
+
const cmodAppId = '1fd8a8ee972047c4a89640fd51048522'
|
|
7
|
+
|
|
8
|
+
const sha256Block = 64
|
|
9
|
+
|
|
10
|
+
const systems: Readonly<Record<string, Device['os']>> = { Darwin: 'darwin', Linux: 'linux' }
|
|
11
|
+
|
|
12
|
+
const machines: Readonly<Record<string, Device['arch']>> = { arm64: 'arm64', aarch64: 'arm64', x86_64: 'x64', amd64: 'x64' }
|
|
13
|
+
|
|
14
|
+
const platformUuid = /"IOPlatformUUID" = "([0-9A-Fa-f-]{36})"/
|
|
15
|
+
|
|
16
|
+
const machineId = /^[0-9a-f]{32}$/
|
|
17
|
+
|
|
18
|
+
const machineIdFiles = ['/etc/machine-id', '/var/lib/dbus/machine-id'] as const
|
|
19
|
+
|
|
20
|
+
export class MissingMachineId extends Error {}
|
|
21
|
+
|
|
22
|
+
export async function readDevice(claude: Pick<Claude, 'process' | 'fs'>): Promise<Device> {
|
|
23
|
+
const output = async (argv: readonly string[]) => {
|
|
24
|
+
const { exitCode, stdout, stderr } = await claude.process.run(argv)
|
|
25
|
+
if (exitCode !== 0) throw new Error(`cmod could not read this computer: ${argv.join(' ')} ${formatExit(exitCode, stderr)}`)
|
|
26
|
+
return stdout.trim()
|
|
27
|
+
}
|
|
28
|
+
const [system = '', node = '', machine = ''] = (await output(['uname', '-snm'])).split(/\s+/)
|
|
29
|
+
const os = systems[system]
|
|
30
|
+
const arch = machines[machine]
|
|
31
|
+
if (os === undefined) throw new Error(`cmod reads the device of macOS and Linux, and this computer runs ${system}.`)
|
|
32
|
+
if (arch === undefined) throw new Error(`cmod reads the device of arm64 and x64 computers, and this one is ${machine}.`)
|
|
33
|
+
if (os === 'linux') return { id: await appSpecific(await linuxMachineId(claude.fs)), name: node, os, arch }
|
|
34
|
+
const [platform, name] = await Promise.all([output(['ioreg', '-rd1', '-c', 'IOPlatformExpertDevice']), output(['scutil', '--get', 'LocalHostName'])])
|
|
35
|
+
const uuid = platformUuid.exec(platform)?.[1]
|
|
36
|
+
if (uuid === undefined) throw new Error('cmod could not read this computer: ioreg -rd1 -c IOPlatformExpertDevice names no IOPlatformUUID.')
|
|
37
|
+
return { id: await appSpecific(uuid.replaceAll('-', '').toLowerCase()), name, os, arch }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function linuxMachineId(fs: Pick<Claude['fs'], 'read'>): Promise<string> {
|
|
41
|
+
for (const path of machineIdFiles) {
|
|
42
|
+
const id = (await fs.read(path).catch(ifMissing(''))).trim()
|
|
43
|
+
if (machineId.test(id)) return id
|
|
44
|
+
}
|
|
45
|
+
throw new MissingMachineId(`cmod could not read this computer: neither ${machineIdFiles.join(' nor ')} holds a machine id.`)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function appSpecific(machine: string): Promise<string> {
|
|
49
|
+
if (!machineId.test(machine)) throw new Error('cmod could not read this computer: its machine id is not 32 hex digits.')
|
|
50
|
+
const id = (await hmacSha256(bytesOf(machine), bytesOf(cmodAppId))).slice(0, 16)
|
|
51
|
+
id[6] = ((id[6] ?? 0) & 0x0f) | 0x40
|
|
52
|
+
id[8] = ((id[8] ?? 0) & 0x3f) | 0x80
|
|
53
|
+
return [...id].map((byte) => byte.toString(16).padStart(2, '0')).join('')
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function hmacSha256(key: Uint8Array, message: Uint8Array): Promise<Uint8Array> {
|
|
57
|
+
const sha256 = async (...parts: readonly Uint8Array[]) => new Uint8Array(await crypto.subtle.digest('SHA-256', Uint8Array.from(parts.flatMap((part) => [...part]))))
|
|
58
|
+
const padded = new Uint8Array(sha256Block)
|
|
59
|
+
padded.set(key)
|
|
60
|
+
return sha256(padded.map((byte) => byte ^ 0x5c), await sha256(padded.map((byte) => byte ^ 0x36), message))
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function bytesOf(hex: string): Uint8Array {
|
|
64
|
+
return Uint8Array.from(hex.match(/../g) ?? [], (pair) => Number.parseInt(pair, 16))
|
|
65
|
+
}
|
package/src/runtime/hooks.ts
CHANGED
|
@@ -12,7 +12,7 @@ export type Hook = Exclude<ClassicHookEvent, 'PreToolUse'>
|
|
|
12
12
|
|
|
13
13
|
export type HookFields = Readonly<Record<string, unknown>>
|
|
14
14
|
|
|
15
|
-
export type HookListener<H extends Hook> = (input: ClassicHookInputs[H]) => HookFields | undefined | Promise<HookFields | undefined>
|
|
15
|
+
export type HookListener<H extends Hook> = (input: ClassicHookInputs[H], signal: AbortSignal) => HookFields | undefined | Promise<HookFields | undefined>
|
|
16
16
|
|
|
17
17
|
export type RoutedEvent =
|
|
18
18
|
| `classic.${Hook}`
|
|
@@ -39,9 +39,9 @@ export type RoutedEvent =
|
|
|
39
39
|
type CallFiles = { readonly read: string[]; readonly changed: string[] }
|
|
40
40
|
|
|
41
41
|
export function classicHook<H extends Hook>(event: H, hook: HookListener<H>, report: (failure: Failure) => void): RoutedHook<RoutedEvent> {
|
|
42
|
-
const routed = async (e: unknown, next: (e: unknown) => Promise<unknown>) => {
|
|
42
|
+
const routed = async (e: unknown, next: ((e: unknown) => Promise<unknown>) & { readonly signal: AbortSignal }) => {
|
|
43
43
|
const ours = await Promise.resolve()
|
|
44
|
-
.then(() => hook(e as ClassicHookInputs[H]))
|
|
44
|
+
.then(() => hook(e as ClassicHookInputs[H], next.signal))
|
|
45
45
|
.catch((error: unknown) => {
|
|
46
46
|
report({ id: `hook:${event}`, message: `The ${event} listener failed`, error })
|
|
47
47
|
return undefined
|