@cmodjs/core 8.2.0 → 8.3.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 +1 -1
- package/docs/dependencies.md +9 -2
- package/docs/session.md +7 -2
- package/docs/testing.md +2 -0
- package/jobs/program.d.ts.map +1 -1
- package/jobs/program.js +10 -7
- package/mod.d.ts +282 -0
- package/mod.d.ts.map +1 -1
- package/package.json +1 -1
- package/records.d.ts +1 -1
- package/records.js +1 -1
- package/register.d.ts.map +1 -1
- package/register.js +1 -0
- package/runtime/before.d.ts +1 -1
- package/runtime/before.d.ts.map +1 -1
- package/runtime/before.js +8 -13
- package/runtime/claude.d.ts +2 -1
- package/runtime/claude.d.ts.map +1 -1
- package/runtime/conversations.d.ts.map +1 -1
- package/runtime/conversations.js +19 -9
- package/runtime/interfaces.d.ts +17 -2
- package/runtime/interfaces.d.ts.map +1 -1
- package/runtime/interfaces.js +64 -15
- package/runtime/lifecycle.js +3 -3
- package/runtime/permission-check.d.ts +1 -0
- package/runtime/permission-check.d.ts.map +1 -1
- package/runtime/permission-check.js +20 -2
- package/runtime/rpc.d.ts.map +1 -1
- package/runtime/rpc.js +49 -28
- package/runtime/sessions.d.ts +3 -1
- package/runtime/sessions.d.ts.map +1 -1
- package/runtime/sessions.js +8 -3
- package/session/context/turn/message/message.d.ts +2 -1
- package/session/context/turn/message/message.d.ts.map +1 -1
- package/session/context/turn/turn.d.ts +1 -0
- package/session/context/turn/turn.d.ts.map +1 -1
- package/session/conversation.d.ts +6 -1
- package/session/conversation.d.ts.map +1 -1
- package/session/conversation.js +15 -2
- package/session/session.d.ts +6 -1
- package/session/session.d.ts.map +1 -1
- package/src/jobs/program.ts +8 -4
- package/src/mod.ts +55 -0
- package/src/records.ts +1 -1
- package/src/register.ts +1 -0
- package/src/runtime/before.ts +9 -14
- package/src/runtime/claude.ts +2 -0
- package/src/runtime/conversations.ts +20 -11
- package/src/runtime/interfaces.ts +70 -11
- package/src/runtime/lifecycle.ts +3 -3
- package/src/runtime/permission-check.ts +20 -2
- package/src/runtime/rpc.ts +49 -31
- package/src/runtime/sessions.ts +11 -4
- package/src/session/context/turn/message/message.ts +2 -1
- package/src/session/context/turn/turn.ts +1 -0
- package/src/session/conversation.ts +22 -3
- package/src/session/session.ts +2 -1
- package/src/testing/fake-claude.ts +1 -0
- package/src/testing/fake-serve.ts +14 -5
- package/src/testing/fake-sessions.ts +2 -4
- package/src/testing.ts +33 -15
- package/testing/fake-claude.d.ts.map +1 -1
- package/testing/fake-claude.js +1 -0
- package/testing/fake-serve.d.ts.map +1 -1
- package/testing/fake-serve.js +15 -7
- package/testing/fake-sessions.d.ts.map +1 -1
- package/testing/fake-sessions.js +2 -4
- package/testing.d.ts +4 -1
- package/testing.d.ts.map +1 -1
- package/testing.js +31 -8
package/src/mod.ts
CHANGED
|
@@ -115,6 +115,61 @@ export type CommandInfo = { readonly name: string; readonly description: string;
|
|
|
115
115
|
|
|
116
116
|
export type CommandRunResult = { readonly text?: string; readonly note?: string }
|
|
117
117
|
|
|
118
|
+
declare module 'claude-code' {
|
|
119
|
+
interface CmodInterfaces {
|
|
120
|
+
'cmod/Sessions': {
|
|
121
|
+
methods: {
|
|
122
|
+
sessions(scope?: { project?: string; everyProject?: boolean; running?: boolean; since?: string }): { id: string; title: string; color?: string; project: string; cwd: string; model: string; startedAt: string; lastAt: string; forkedFrom?: string; isRunning: boolean; agentType?: string; transcriptPath?: string; visitedAt?: string; device?: { id: string; name: string }; status?: 'busy' | 'shell' | 'idle' | 'waiting'; waitingFor?: { dialog: string; tool?: string; input?: Record<string, unknown>; question?: string }; contextPercent?: number; lastTurn?: { reason: 'answered' | 'stopped' | 'failed'; at: string; failure?: string } }[]
|
|
123
|
+
search(text: string, options?: { project?: string; everyProject?: boolean; running?: boolean; since?: string; limit?: number; before?: { session: string; id: string }; record?: { session?: string; task?: string; turn?: string; context?: number; isAgent?: true } }): unknown[]
|
|
124
|
+
read(session: string, part: 'messages' | 'turns' | 'contexts' | 'tasks' | 'goal' | 'usage' | 'state', options?: { project?: string; task?: string; turn?: string; context?: number; after?: string; last?: number; all?: true }): unknown
|
|
125
|
+
send(session: string, message: { type: 'prompt' | 'note'; text: string; as?: 'person' | 'session' }, context?: { project?: string; caller?: string; task?: string }): void
|
|
126
|
+
abort(session: string, input: { turn?: string } | null, context?: { project?: string; caller?: string; task?: string }): void
|
|
127
|
+
end(session: string, input: null, context?: { project?: string; caller?: string }): void
|
|
128
|
+
fork(session: string, task: { prompt: string; title: string; isBackground?: boolean; at?: string }, context?: { project?: string; caller?: string }): { id: string; title: string; openedBy: string; openedAt: string; forkedFrom?: string; isBackground?: true }
|
|
129
|
+
startTask(session: string, task: { prompt: string; title: string; agentType?: string; model?: string; name?: string; cwd?: string; isBackground?: boolean; device?: string }, context?: { project?: string; caller?: string }): { id: string; title: string; openedBy: string; openedAt: string; agentType?: string; model?: string; isBackground?: true }
|
|
130
|
+
callTool(session: string, call: { name: string; input: Record<string, unknown> }, context?: { project?: string; caller?: string }): unknown
|
|
131
|
+
usage(session: string, input: null, context?: { project?: string; caller?: string; task?: string }): { model: string; contextWindow: { tokenCount?: number; size?: number; percent?: number } }
|
|
132
|
+
surfaces(session: string, input: null, context?: { project?: string; caller?: string; task?: string }): ('terminal' | 'desktop' | 'mobile' | 'vscode')[]
|
|
133
|
+
visit(session: string, at?: string): void
|
|
134
|
+
delete(session: string, input?: null, context?: { project?: string; caller?: string }): void
|
|
135
|
+
}
|
|
136
|
+
events: { Change: { readonly session: string; readonly part: 'visit' | 'running' | 'tasks' | 'goal' | 'status' | 'deleted' } }
|
|
137
|
+
}
|
|
138
|
+
'cmod/Devices': {
|
|
139
|
+
methods: {
|
|
140
|
+
devices(): { id: string; name: string; address?: string }[]
|
|
141
|
+
send(device: string, message: unknown): void
|
|
142
|
+
}
|
|
143
|
+
events: { Change: { readonly device: string }; Message: { readonly device: string; readonly message: unknown } }
|
|
144
|
+
}
|
|
145
|
+
'cmod/Terminal': {
|
|
146
|
+
methods: {
|
|
147
|
+
screen(session: string): string
|
|
148
|
+
press(session: string, keys: string): void
|
|
149
|
+
show(session: string, place: 'focus' | 'peek' | 'tab' | 'right' | 'down' | 'hide'): void
|
|
150
|
+
}
|
|
151
|
+
events: { Shown: { readonly session: string; readonly place: 'focus' | 'peek' | 'tab' | 'right' | 'down' | 'hide' }; Pressed: { readonly session: string } }
|
|
152
|
+
}
|
|
153
|
+
'cmod/Providers': {
|
|
154
|
+
methods: {}
|
|
155
|
+
events: { Change: { readonly interface: string; readonly device: { id: string; name: string } } }
|
|
156
|
+
}
|
|
157
|
+
'cmod/UI': {
|
|
158
|
+
methods: {
|
|
159
|
+
widgets(session: string): { mod: string; id: string; areas: ('abovePrompt' | 'belowPrompt' | 'working' | 'turnEnd' | 'dashboard')[] }[]
|
|
160
|
+
views(session: string): { mod: string; id: string; title: string }[]
|
|
161
|
+
pages(session: string): { mod: string; id: string; title: string }[]
|
|
162
|
+
draw(session: string, part: { mod: string; id: string }, at: { columns: number; surface: 'terminal' | 'desktop' | 'mobile' | 'vscode' | 'browser' | 'herdr' }): unknown
|
|
163
|
+
press(session: string, handler: number, input: { surface: 'terminal' | 'desktop' | 'mobile' | 'vscode' | 'browser' | 'herdr'; key?: string; value?: string; kind?: 'change' | 'submit'; link?: { href: string } }): void
|
|
164
|
+
open(session: string, part: { mod: string; id: string }): void
|
|
165
|
+
close(session: string, part: { mod: string; id: string }): void
|
|
166
|
+
show(session: string, client: string, parts: { mod: string; id: string }[], options?: { isHost?: boolean }): void
|
|
167
|
+
}
|
|
168
|
+
events: { Change: { readonly session: string; readonly part: 'widgets' | 'views' | 'pages' }; Redraw: { readonly session: string; readonly mod: string; readonly id: string }; Open: { readonly session: string; readonly mod: string; readonly id: string; readonly isAsked?: true }; Close: { readonly session: string; readonly mod: string; readonly id: string } }
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
118
173
|
export type InterfaceName = Extract<keyof CmodInterfaces, string>
|
|
119
174
|
|
|
120
175
|
type MethodsOf<Name extends InterfaceName> = CmodInterfaces[Name] extends { readonly methods: infer Methods } ? Methods : Record<never, never>
|
package/src/records.ts
CHANGED
|
@@ -493,7 +493,7 @@ function readHotkeys(hotkeys: unknown): Steps {
|
|
|
493
493
|
return { hotkeys: checkHotkeys('package.json "cmod"', hotkeys as Record<string, HotkeyInit>) }
|
|
494
494
|
}
|
|
495
495
|
|
|
496
|
-
export const coreVersion = '8.
|
|
496
|
+
export const coreVersion = '8.3.1'
|
|
497
497
|
|
|
498
498
|
export const oldestCmodVersion = '8.0.0'
|
|
499
499
|
|
package/src/register.ts
CHANGED
|
@@ -91,6 +91,7 @@ async function startMod($: EngineInterface, eventInput: Frozen<Args<'session.sta
|
|
|
91
91
|
usage: () => $.session.usage(),
|
|
92
92
|
surfaces: () => $.session.surfaces(),
|
|
93
93
|
version: async () => (await $.session.version()).version,
|
|
94
|
+
info: () => $.session.info(),
|
|
94
95
|
messages: ((args?: Parameters<Claude['session']['messages']>[0]) => (args === undefined ? $.session.messages() : $.session.messages(args))) as Claude['session']['messages'],
|
|
95
96
|
append: (args) => $.session.append(args),
|
|
96
97
|
send: (args) => $.session.send(args),
|
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 TurnData } from '../session/conversation.js'
|
|
16
|
+
import { ownerOfSpawn, placedMessage, 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'
|
|
@@ -22,7 +22,7 @@ import type { Router } from './router.js'
|
|
|
22
22
|
import { toolInputOf } from './tool-calls.js'
|
|
23
23
|
import { resolve } from '../vendor.js'
|
|
24
24
|
|
|
25
|
-
export type Place = Pick<ConversationState, 'session' | 'context' | 'contextOpenedAt' | 'turn' | 'tasks' | 'taskTurns' | 'openCalls'>
|
|
25
|
+
export type Place = Pick<ConversationState, 'session' | 'agentType' | 'context' | 'contextOpenedAt' | 'turn' | 'tasks' | 'taskTurns' | 'openCalls'>
|
|
26
26
|
|
|
27
27
|
export type Decide = (event: BeforeEvent, change: SessionChange) => Promise<Partial<Answers> | undefined>
|
|
28
28
|
|
|
@@ -71,12 +71,7 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
71
71
|
const { place, wants, fold, failedBefore } = hooks
|
|
72
72
|
const now = () => new Date().toISOString()
|
|
73
73
|
const asked = async (event: BeforeEvent, change: SessionChange, decide: Decide) => (await decide(event, change)) ?? {}
|
|
74
|
-
const message = (where: Place, unplaced: Unplaced, task: string | undefined, isInTurn = true): SessionChange => {
|
|
75
|
-
const turn = isInTurn ? (task === undefined ? where.turn : where.taskTurns[task]) : undefined
|
|
76
|
-
const context = task === undefined ? where.context : (where.tasks[task]?.context ?? where.context)
|
|
77
|
-
const call = unplaced.type === ToolResult ? where.openCalls?.[unplaced.callId] : undefined
|
|
78
|
-
return { type: Message, message: { ...unplaced, ...call, session: where.session, context, ...(turn === undefined ? {} : { turn: turn.prompt.id }), ...(task === undefined ? {} : { task }) } as Message }
|
|
79
|
-
}
|
|
74
|
+
const message = (where: Place, unplaced: Unplaced, task: string | undefined, isInTurn = true, agentType?: string): SessionChange => ({ type: Message, message: placedMessage(where, unplaced, task, isInTurn, agentType ?? (task === undefined ? where.agentType : where.tasks[task]?.agentType)) })
|
|
80
75
|
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
76
|
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
77
|
const refusedOnFailure = (event: BeforeEvent, change: (where: Place) => SessionChange | undefined, error: Error, next: { readonly called: boolean }) => (next.called ? undefined : failedBefore(event, change, error)?.refuse)
|
|
@@ -92,7 +87,7 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
92
87
|
const task = e.agentId === undefined ? undefined : where.tasks[e.agentId]
|
|
93
88
|
return e.agentId !== undefined && task === undefined ? undefined : { type: ContextEnd, context: closingContext(where, task, now()) }
|
|
94
89
|
}
|
|
95
|
-
const turnEnded = (turn: TurnData | undefined): SessionChange | undefined => (turn === undefined ? undefined : { type: TurnEnd, turn: { ...turn, closedAt: now() } })
|
|
90
|
+
const turnEnded = (turn: TurnData | undefined, isAfterRefusal = false): SessionChange | undefined => (turn === undefined ? undefined : { type: TurnEnd, turn: { ...turn, closedAt: now(), ...(isAfterRefusal ? { isAfterRefusal } : {}) } })
|
|
96
91
|
const titles = new Map<string, string>()
|
|
97
92
|
const spawned = new Map<string, { readonly prompt: string; readonly agentType: string }>()
|
|
98
93
|
const startedBy = new Map<string, string>()
|
|
@@ -262,7 +257,7 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
262
257
|
const open = where.taskTurns[e.agent_id]?.prompt
|
|
263
258
|
const text = open?.text ?? prompt
|
|
264
259
|
if (text === undefined) return next(e)
|
|
265
|
-
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))
|
|
260
|
+
const answer = await asked(Prompt, message(where, { id: open?.id ?? '', at: now(), type: Prompt, text, from: open?.from ?? { type: Task } }, e.agent_id, false, where.tasks[e.agent_id]?.agentType ?? e.agent_type), fold(next.signal))
|
|
266
261
|
return withNote(await next(e), answer.note)
|
|
267
262
|
}),
|
|
268
263
|
router.add('classic.SubagentStop', async (e, next) => {
|
|
@@ -271,22 +266,22 @@ export function installBefore({ claude, router, hooks }: { readonly claude: Clau
|
|
|
271
266
|
return answer
|
|
272
267
|
}
|
|
273
268
|
if (next.signal.aborted || !(await wants(TurnEnd))) return stopped(await next(e))
|
|
274
|
-
const change = turnEnded((await place()).taskTurns[e.agent_id])
|
|
269
|
+
const change = turnEnded((await place()).taskTurns[e.agent_id], e.stop_hook_active)
|
|
275
270
|
if (change === undefined) return stopped(await next(e))
|
|
276
271
|
const answer = await askedAtStop(change, next.signal)
|
|
277
272
|
return stopped(answeredStop(await next(e), answer, next.signal))
|
|
278
273
|
}, async (e, error, next) => {
|
|
279
|
-
const refusal = refusedOnFailure(TurnEnd, (where) => turnEnded(where.taskTurns[e.agent_id]), error, next)
|
|
274
|
+
const refusal = refusedOnFailure(TurnEnd, (where) => turnEnded(where.taskTurns[e.agent_id], e.stop_hook_active), error, next)
|
|
280
275
|
return refusal === undefined ? undefined : { ...(await next(e)), block: refusal }
|
|
281
276
|
}),
|
|
282
277
|
router.add('classic.Stop', async (e, next) => {
|
|
283
278
|
if (next.signal.aborted || !(await wants(TurnEnd))) return next(e)
|
|
284
|
-
const change = turnEnded((await place()).turn)
|
|
279
|
+
const change = turnEnded((await place()).turn, e.stop_hook_active)
|
|
285
280
|
if (change === undefined) return next(e)
|
|
286
281
|
const answer = await askedAtStop(change, next.signal)
|
|
287
282
|
return answeredStop(await next(e), answer, next.signal)
|
|
288
283
|
}, async (e, error, next) => {
|
|
289
|
-
const refusal = refusedOnFailure(TurnEnd, (where) => turnEnded(where.turn), error, next)
|
|
284
|
+
const refusal = refusedOnFailure(TurnEnd, (where) => turnEnded(where.turn, e.stop_hook_active), error, next)
|
|
290
285
|
return refusal === undefined ? undefined : { ...(await next(e)), block: refusal }
|
|
291
286
|
}),
|
|
292
287
|
router.add('session.compact', async (e, next) => {
|
package/src/runtime/claude.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type {
|
|
2
|
+
SessionInfo,
|
|
2
3
|
AgentInfo,
|
|
3
4
|
AgentSpawnArgs,
|
|
4
5
|
AgentSpawnResult,
|
|
@@ -97,6 +98,7 @@ export type Claude = {
|
|
|
97
98
|
usage(): Promise<SessionUsage>
|
|
98
99
|
surfaces(): Promise<readonly RenderSurface[]>
|
|
99
100
|
version(): Promise<string>
|
|
101
|
+
info(): Promise<Pick<SessionInfo, 'transcriptPath'>>
|
|
100
102
|
messages: EngineInterface['session']['messages']
|
|
101
103
|
append: EngineInterface['session']['append']
|
|
102
104
|
send: EngineInterface['session']['send']
|
|
@@ -16,7 +16,7 @@ import { beforeAnswerKeys, foldBefore, installBefore, relayOf, type Decide, type
|
|
|
16
16
|
import type { Claude } from './claude.js'
|
|
17
17
|
import { cmodPluginName, isNotInstalled } from './dependencies.js'
|
|
18
18
|
import { MissingMachineId } from './device.js'
|
|
19
|
-
import { interfaceListeners, interfaceMethods, providerActs, providerPeer, serveProviders, sessionActs, sessionsInterface, uiInterface, type HeldStatus, type Implementation, type Provided, type ProvidedHeard, type ProviderIdentity, type StoreChange, type HeldSession } from './interfaces.js'
|
|
19
|
+
import { interfaceListeners, interfaceMethods, providerActs, providerPeer, serveProviders, sessionActs, sessionsInterface, uiInterface, type HeldStatus, type Implementation, type Provided, type KeptListen, type ProvidedHeard, type ProviderIdentity, type StoreChange, type HeldSession } from './interfaces.js'
|
|
20
20
|
import { runCmod } from './programs.js'
|
|
21
21
|
import { addressCall, connectRpc, RpcError, rpcCodes, type RpcClient } from './rpc.js'
|
|
22
22
|
import type { RoutedHook, Router } from './router.js'
|
|
@@ -64,7 +64,9 @@ const keptClosings = 200
|
|
|
64
64
|
|
|
65
65
|
const keptMessages = 200
|
|
66
66
|
|
|
67
|
-
type Kept = { readonly subscribed: Readonly<Record<string, Readonly<Record<string, readonly Listened[]>>>>; readonly watched: Readonly<Record<string, Readonly<Record<string, readonly Listened[]
|
|
67
|
+
type Kept = { readonly subscribed: Readonly<Record<string, Readonly<Record<string, readonly Listened[]>>>>; readonly watched: Readonly<Record<string, Readonly<Record<string, readonly Listened[]>>>>; readonly provided?: readonly KeptListen[] }
|
|
68
|
+
|
|
69
|
+
const noneKept: Kept = { subscribed: {}, watched: {}, provided: [] }
|
|
68
70
|
|
|
69
71
|
type Registered = { remove(): void }
|
|
70
72
|
|
|
@@ -274,6 +276,7 @@ export function serveConversations({
|
|
|
274
276
|
},
|
|
275
277
|
after: (ms, run) => claude.clock.after(ms, run),
|
|
276
278
|
report: (error) => report('providers', 'A provider listener failed', error),
|
|
279
|
+
changed: () => void saveListeners().catch((error: unknown) => report('listeners', 'Could not keep the provider listeners of this session', error)),
|
|
277
280
|
})
|
|
278
281
|
|
|
279
282
|
const others = new Map<string, OtherProvider>()
|
|
@@ -388,12 +391,13 @@ export function serveConversations({
|
|
|
388
391
|
const keptOf = (): Kept => ({
|
|
389
392
|
subscribed: Object.fromEntries([...subscribed].map(([caller, lists]) => [caller, Object.fromEntries(lists)])),
|
|
390
393
|
watched: [...watched.values()].reduce<Record<string, Record<string, readonly Listened[]>>>((all, watch) => ({ ...all, [watch.mod]: { ...all[watch.mod], [watch.target]: watch.list } }), {}),
|
|
394
|
+
provided: served.listened(),
|
|
391
395
|
})
|
|
392
396
|
|
|
393
397
|
const saveListeners = (isEnding = false) => {
|
|
394
398
|
const at = session
|
|
395
399
|
if (at === '') return Promise.resolve()
|
|
396
|
-
return onListenerFiles(() => claude.fs.write(`${listeners}/${at}.json`, JSON.stringify(isEnding ?
|
|
400
|
+
return onListenerFiles(() => claude.fs.write(`${listeners}/${at}.json`, JSON.stringify(isEnding ? noneKept : keptOf())))
|
|
397
401
|
}
|
|
398
402
|
|
|
399
403
|
const restoreListeners = () => {
|
|
@@ -402,6 +406,8 @@ export function serveConversations({
|
|
|
402
406
|
const read = JSON.parse(await claude.fs.read(`${listeners}/${at}.json`).catch(ifMissing('{}'))) as Partial<Kept>
|
|
403
407
|
for (const [caller, lists] of Object.entries(read.subscribed ?? {})) if (!subscribed.has(caller)) for (const [id, list] of Object.entries(lists)) hear(caller, id, list)
|
|
404
408
|
for (const [caller, targets] of Object.entries(read.watched ?? {})) for (const [target, list] of Object.entries(targets)) if (!watched.has(`${caller}\n${target}`)) watch(caller, target, list)
|
|
409
|
+
const listening = served.listened()
|
|
410
|
+
for (const { caller, listen } of read.provided ?? []) if (!listening.some((each) => each.caller === caller && each.listen.id === listen.id)) void served.answer(interfaceMethods.listen, listen, caller)?.catch((error: unknown) => report('listeners', `Could not listen again for ${caller} on ${listen.interface}`, error))
|
|
405
411
|
})
|
|
406
412
|
}
|
|
407
413
|
|
|
@@ -421,7 +427,9 @@ export function serveConversations({
|
|
|
421
427
|
}
|
|
422
428
|
|
|
423
429
|
const forgetMod = (mod: string) => {
|
|
424
|
-
const
|
|
430
|
+
const wasProvided = served.listened().some((each) => each.caller === mod)
|
|
431
|
+
served.forget(mod)
|
|
432
|
+
const wasHeard = heard.delete(mod) || wasProvided
|
|
425
433
|
subscribed.delete(mod)
|
|
426
434
|
clear(`changed:${mod}`)
|
|
427
435
|
const wasWatching = [...watched.keys()].filter((key) => key.startsWith(`${mod}\n`))
|
|
@@ -511,14 +519,15 @@ export function serveConversations({
|
|
|
511
519
|
})
|
|
512
520
|
}
|
|
513
521
|
|
|
514
|
-
const start = (id: string, source: string) => {
|
|
522
|
+
const start = (id: string, source: string, agentType: string | undefined) => {
|
|
515
523
|
if (id === session) return
|
|
516
524
|
const previous = session
|
|
517
525
|
session = id
|
|
518
526
|
live = []
|
|
519
527
|
liveIds.clear()
|
|
520
528
|
waitingRows.clear()
|
|
521
|
-
|
|
529
|
+
const runsAs = agentType === undefined ? {} : { agentType }
|
|
530
|
+
conversation = createConversation({ ...emptyConversation(id), ...runsAs })
|
|
522
531
|
contextPercent = undefined
|
|
523
532
|
endedTurn = undefined
|
|
524
533
|
failedWith = undefined
|
|
@@ -529,7 +538,7 @@ export function serveConversations({
|
|
|
529
538
|
? Promise.resolve(dispatch(conversation.startContext(new Date().toISOString())))
|
|
530
539
|
: read<ConversationState | null>(id, 'state').then(
|
|
531
540
|
(state) => {
|
|
532
|
-
if (session === id && state !== null) conversation = createConversation({ ...emptyConversation(id), ...state })
|
|
541
|
+
if (session === id && state !== null) conversation = createConversation({ ...emptyConversation(id), ...state, ...runsAs })
|
|
533
542
|
},
|
|
534
543
|
(error: unknown) => report('state', `Starts session ${id} without its earlier turns`, error),
|
|
535
544
|
)
|
|
@@ -547,8 +556,8 @@ export function serveConversations({
|
|
|
547
556
|
listening = Promise.all([restored, holding]).then(() => undefined)
|
|
548
557
|
listenToServe()
|
|
549
558
|
void starting.then(reconcileTasks)
|
|
550
|
-
if (heard.size === 0 && watched.size === 0) return
|
|
551
|
-
void Promise.all([previous === '' ? undefined : onListenerFiles(() => claude.fs.write(`${listeners}/${previous}.json`, JSON.stringify(
|
|
559
|
+
if (heard.size === 0 && watched.size === 0 && served.listened().length === 0) return
|
|
560
|
+
void Promise.all([previous === '' ? undefined : onListenerFiles(() => claude.fs.write(`${listeners}/${previous}.json`, JSON.stringify(noneKept))), saveListeners()]).catch((error: unknown) => report('follow', 'Kept telling the mods about the session from before', error))
|
|
552
561
|
}
|
|
553
562
|
|
|
554
563
|
const reconcileTasks = async () => {
|
|
@@ -608,11 +617,11 @@ export function serveConversations({
|
|
|
608
617
|
}
|
|
609
618
|
|
|
610
619
|
router.add('classic.SessionStart', async (e, next) => {
|
|
611
|
-
start(e.session_id, e.source)
|
|
620
|
+
start(e.session_id, e.source, e.agent_type)
|
|
612
621
|
return next(e)
|
|
613
622
|
})
|
|
614
623
|
router.add('classic.SessionEnd', async (e, next) => {
|
|
615
|
-
if (subscribed.size > 0 || watched.size > 0) await saveListeners(true).catch((error: unknown) => report('follow', 'Left its listeners registered', error))
|
|
624
|
+
if (subscribed.size > 0 || watched.size > 0 || served.listened().length > 0) await saveListeners(true).catch((error: unknown) => report('follow', 'Left its listeners registered', error))
|
|
616
625
|
return next(e)
|
|
617
626
|
})
|
|
618
627
|
|
|
@@ -43,6 +43,12 @@ export const sessionActs = {
|
|
|
43
43
|
|
|
44
44
|
export const terminalInterface = 'cmod/Terminal'
|
|
45
45
|
|
|
46
|
+
export const providersInterface = 'cmod/Providers'
|
|
47
|
+
|
|
48
|
+
export type ProvidersChange = { readonly interface: string; readonly device: Pick<Device, 'id' | 'name'> }
|
|
49
|
+
|
|
50
|
+
type ChangedProviders = (name: string | undefined, device: Pick<Device, 'id' | 'name'> | undefined) => void
|
|
51
|
+
|
|
46
52
|
export type HerdrTerminal = { readonly id: string; readonly socket: string }
|
|
47
53
|
|
|
48
54
|
export type TerminalPlace = 'focus' | 'peek' | 'tab' | 'right' | 'down' | 'hide'
|
|
@@ -466,7 +472,7 @@ export function routeSessions({
|
|
|
466
472
|
}
|
|
467
473
|
|
|
468
474
|
const interfaces = interfaceServer({
|
|
469
|
-
implementations: { ...Object.fromEntries(names.map((name) => [name, implementation])), [uiInterface]: ui, ...(terminal === undefined ? {} : { [terminalInterface]: terminal }) },
|
|
475
|
+
implementations: { ...Object.fromEntries(names.map((name) => [name, implementation])), [uiInterface]: ui, [providersInterface]: {}, ...(terminal === undefined ? {} : { [terminalInterface]: terminal }) },
|
|
470
476
|
onListen: (_connection, listening) => {
|
|
471
477
|
if (listening.interface === uiInterface) {
|
|
472
478
|
if (!uiEvents.includes(listening.event)) throw new RpcError(rpcCodes.methodNotFound, `${uiInterface} tells only Change, Redraw, Open, and Close.`)
|
|
@@ -476,7 +482,7 @@ export function routeSessions({
|
|
|
476
482
|
if (!terminalEvents.includes(listening.event)) throw new RpcError(rpcCodes.methodNotFound, `${terminalInterface} tells only ${terminalEvents.join(' and ')}.`)
|
|
477
483
|
return
|
|
478
484
|
}
|
|
479
|
-
if (listening.event !== 'Change') throw new RpcError(rpcCodes.methodNotFound, `${listening.interface} tells only Change, because a mod hears only the session it runs in.`)
|
|
485
|
+
if (listening.event !== 'Change') throw new RpcError(rpcCodes.methodNotFound, listening.interface === providersInterface ? `${providersInterface} tells only Change.` : `${listening.interface} tells only Change, because a mod hears only the session it runs in.`)
|
|
480
486
|
},
|
|
481
487
|
extraMethod: (connection, method, params) => {
|
|
482
488
|
if (method === sessionActs.uiEvent) {
|
|
@@ -511,7 +517,18 @@ export function routeSessions({
|
|
|
511
517
|
},
|
|
512
518
|
})
|
|
513
519
|
|
|
514
|
-
const
|
|
520
|
+
const toldNames = new Set<string>()
|
|
521
|
+
const providersChanged: ChangedProviders = (name, from) =>
|
|
522
|
+
void (async () => {
|
|
523
|
+
const at = from ?? (await device())
|
|
524
|
+
const listened = interfaces.listeners(providersInterface, 'Change').map(({ matcher }) => (isObject(matcher) ? (matcher as Readonly<Record<string, unknown>>)['interface'] : undefined))
|
|
525
|
+
for (const each of name === undefined ? new Set([...toldNames, ...listened.filter((named): named is string => typeof named === 'string')]) : [name]) {
|
|
526
|
+
toldNames.add(each)
|
|
527
|
+
interfaces.emit(providersInterface, 'Change', { interface: each, device: at } satisfies ProvidersChange)
|
|
528
|
+
}
|
|
529
|
+
})().catch(report)
|
|
530
|
+
|
|
531
|
+
const providers = routeProviders({ isOwn: (name) => names.includes(name) || name === uiInterface || name === providersInterface || (terminal !== undefined && name === terminalInterface), listsSelf: (name) => name === providersInterface || (terminal !== undefined && name === terminalInterface), changed: providersChanged, own: (connection) => interfaces.handler(connection), device, report, channel: (send) => routes.channel(send), ...(programs === undefined ? {} : { programs }) })
|
|
515
532
|
|
|
516
533
|
const routes = rpcRoutes({
|
|
517
534
|
handle: (connection) => {
|
|
@@ -596,9 +613,11 @@ export function routeProviders({
|
|
|
596
613
|
report,
|
|
597
614
|
channel,
|
|
598
615
|
programs,
|
|
616
|
+
changed,
|
|
599
617
|
}: {
|
|
600
618
|
readonly isOwn: (name: string) => boolean
|
|
601
619
|
readonly listsSelf: (name: string) => boolean
|
|
620
|
+
readonly changed: ChangedProviders
|
|
602
621
|
readonly own: (connection: RpcConnection) => RpcHandler
|
|
603
622
|
readonly device: () => Promise<Pick<Device, 'id' | 'name'>>
|
|
604
623
|
readonly report: (error: unknown) => void
|
|
@@ -656,7 +675,7 @@ export function routeProviders({
|
|
|
656
675
|
const here = await device()
|
|
657
676
|
const stamped = (identities: readonly ProviderIdentity[]) => identities.map((identity) => ({ ...identity, device: here }))
|
|
658
677
|
const self = { mod: cmodPluginName, program: cmodPluginName }
|
|
659
|
-
if (asked !== undefined) return asked === here.id ? stamped([...(await ownOf(name)), ...(isOwn(name) ? [self] : [])]) : []
|
|
678
|
+
if (asked !== undefined) return asked === here.id ? stamped([...(await ownOf(name)), ...(isOwn(name) && name !== providersInterface ? [self] : [])]) : []
|
|
660
679
|
await following
|
|
661
680
|
const carried = await Promise.all(
|
|
662
681
|
[...devices.entries()]
|
|
@@ -693,8 +712,19 @@ export function routeProviders({
|
|
|
693
712
|
return listeners
|
|
694
713
|
}
|
|
695
714
|
|
|
715
|
+
const followedDevices = new Set<string>()
|
|
716
|
+
|
|
717
|
+
const forward = (id: string, peer: Pick<Peer, 'request'>) => {
|
|
718
|
+
if (followedDevices.has(id)) return
|
|
719
|
+
followedDevices.add(id)
|
|
720
|
+
listenersOf(id).listen(peer, listeningOf(providersInterface, 'on', 'Change', [], undefined), (told: unknown) => {
|
|
721
|
+
if (isObject(told) && typeof told['interface'] === 'string' && isObject(told['device']) && told['device']['id'] === id) changed(told['interface'], { id, name: String(told['device']['name']) })
|
|
722
|
+
})
|
|
723
|
+
}
|
|
724
|
+
|
|
696
725
|
const drop = (id: string, each: DeviceServe) => {
|
|
697
726
|
devices.delete(id)
|
|
727
|
+
changed(undefined, { id, name: each.name })
|
|
698
728
|
if (!isLinked(each)) return each.client.close()
|
|
699
729
|
each.link.close(new Error(`cmod serve dropped ${each.name}`))
|
|
700
730
|
return undefined
|
|
@@ -712,8 +742,11 @@ export function routeProviders({
|
|
|
712
742
|
})
|
|
713
743
|
const each: MessageServe = { name, listeners: listenersOf(id), carrier, link, theirs }
|
|
714
744
|
devices.set(id, each)
|
|
745
|
+
forward(id, peerOf(each))
|
|
715
746
|
link.notify(providerActs.link, { link: link.id, ...(theirs === undefined ? {} : { answers: theirs }) } satisfies Hello)
|
|
716
|
-
if (theirs
|
|
747
|
+
if (theirs === undefined) return
|
|
748
|
+
changed(undefined, { id, name })
|
|
749
|
+
void each.listeners.replay(peerOf(each))
|
|
717
750
|
}
|
|
718
751
|
|
|
719
752
|
const greeted = (id: string, known: MessageServe | undefined, carrier: ProviderEnd, hello: Hello) => {
|
|
@@ -725,6 +758,7 @@ export function routeProviders({
|
|
|
725
758
|
if (known.theirs === hello.link) return
|
|
726
759
|
known.theirs = hello.link
|
|
727
760
|
if (hello.answers !== known.link.id) known.link.notify(providerActs.link, { link: known.link.id, answers: hello.link } satisfies Hello)
|
|
761
|
+
changed(undefined, { id, name: known.name })
|
|
728
762
|
void known.listeners.replay(peerOf(known))
|
|
729
763
|
}
|
|
730
764
|
|
|
@@ -753,6 +787,7 @@ export function routeProviders({
|
|
|
753
787
|
handle: heardBy(listeners, `the cmod serve of ${name}`),
|
|
754
788
|
onConnect: async (connected) => {
|
|
755
789
|
reached()
|
|
790
|
+
changed(undefined, { id, name })
|
|
756
791
|
await listeners.replay(connected)
|
|
757
792
|
},
|
|
758
793
|
onError: () => reached(),
|
|
@@ -760,6 +795,7 @@ export function routeProviders({
|
|
|
760
795
|
keepsConnecting: true,
|
|
761
796
|
})
|
|
762
797
|
devices.set(id, { name, address, client, listeners })
|
|
798
|
+
forward(id, client)
|
|
763
799
|
await isReached
|
|
764
800
|
}
|
|
765
801
|
|
|
@@ -831,12 +867,14 @@ export function routeProviders({
|
|
|
831
867
|
if (!isObject(params) || typeof params['interface'] !== 'string' || typeof params['mod'] !== 'string' || (params['program'] !== undefined && typeof params['program'] !== 'string')) throw new RpcError(rpcCodes.invalidParams, `${providerActs.provide} takes { interface, mod, program }.`)
|
|
832
868
|
checkInterfaceName(params['interface'])
|
|
833
869
|
const end = endOf({ mod: params['mod'], ...(typeof params['program'] === 'string' ? { program: params['program'] } : {}) })
|
|
870
|
+
const isNew = end.connection !== connection || !end.names.has(params['interface'])
|
|
834
871
|
if (end.connection !== connection) {
|
|
835
872
|
end.connection = connection
|
|
836
873
|
end.names = new Set()
|
|
837
874
|
void end.listeners.replay(end.link)
|
|
838
875
|
}
|
|
839
876
|
end.names.add(params['interface'])
|
|
877
|
+
if (isNew) changed(params['interface'], undefined)
|
|
840
878
|
for (const each of end.awaited) if (each.name === undefined || each.name === params['interface']) each.provided()
|
|
841
879
|
if (params['interface'] === devicesInterface) follow(end)
|
|
842
880
|
return {}
|
|
@@ -871,7 +909,7 @@ export function routeProviders({
|
|
|
871
909
|
|
|
872
910
|
const unprovide = (connection: RpcConnection, params: unknown) => {
|
|
873
911
|
const name = isObject(params) ? params['interface'] : undefined
|
|
874
|
-
for (const end of ends.values()) if (end.connection === connection && typeof name === 'string'
|
|
912
|
+
for (const end of ends.values()) if (end.connection === connection && typeof name === 'string' && end.names.delete(name)) changed(name, undefined)
|
|
875
913
|
if (name === devicesInterface) followDevices()
|
|
876
914
|
return {}
|
|
877
915
|
}
|
|
@@ -932,6 +970,7 @@ export function routeProviders({
|
|
|
932
970
|
for (const end of ends.values()) {
|
|
933
971
|
if (end.connection !== connection) continue
|
|
934
972
|
listedDevices ||= end.names.has(devicesInterface)
|
|
973
|
+
for (const name of end.names) changed(name, undefined)
|
|
935
974
|
end.connection = undefined
|
|
936
975
|
end.names = new Set()
|
|
937
976
|
}
|
|
@@ -1074,7 +1113,11 @@ export function createProviders({ name, call, changed, after, report }: { readon
|
|
|
1074
1113
|
}
|
|
1075
1114
|
}
|
|
1076
1115
|
|
|
1116
|
+
export type KeptListen = { readonly caller: string; readonly listen: ProvidedListen }
|
|
1117
|
+
|
|
1077
1118
|
export type ServedProviders = {
|
|
1119
|
+
listened(): readonly KeptListen[]
|
|
1120
|
+
forget(caller: string): void
|
|
1078
1121
|
answer(method: string, input: unknown, caller: string | undefined): Promise<unknown> | undefined
|
|
1079
1122
|
provide(name: string, methods: Implementation): Provided
|
|
1080
1123
|
tell(name: string, event: string, payload: unknown): void
|
|
@@ -1092,8 +1135,10 @@ export function serveProviders({
|
|
|
1092
1135
|
device,
|
|
1093
1136
|
after,
|
|
1094
1137
|
report,
|
|
1138
|
+
changed = () => undefined,
|
|
1095
1139
|
}: {
|
|
1096
1140
|
readonly serve: Pick<Peer, 'request' | 'notify'>
|
|
1141
|
+
readonly changed?: () => void
|
|
1097
1142
|
readonly listeners: InterfaceListeners
|
|
1098
1143
|
readonly provider?: ProviderIdentity
|
|
1099
1144
|
readonly tell: (caller: string, heard: ProvidedHeard, signal: AbortSignal) => Promise<unknown>
|
|
@@ -1125,6 +1170,19 @@ export function serveProviders({
|
|
|
1125
1170
|
return null
|
|
1126
1171
|
}
|
|
1127
1172
|
const sessionListeners = sessionCodeListeners(tell, after, report)
|
|
1173
|
+
const kept = new Map<string, KeptListen>()
|
|
1174
|
+
const listenFor = (caller: string | undefined, listening: ProvidedListen) => {
|
|
1175
|
+
const answer = listening.program === undefined ? sessionListeners.listen(String(caller), listening) : listen(caller, listening)
|
|
1176
|
+
kept.set(`${caller}\n${listening.id}`, { caller: String(caller), listen: listening })
|
|
1177
|
+
changed()
|
|
1178
|
+
return answer
|
|
1179
|
+
}
|
|
1180
|
+
const stopListening = (caller: string | undefined, id: string) => {
|
|
1181
|
+
sessionListeners.unlisten(String(caller), id)
|
|
1182
|
+
unlisten(caller, id)
|
|
1183
|
+
if (kept.delete(`${caller}\n${id}`)) changed()
|
|
1184
|
+
return null
|
|
1185
|
+
}
|
|
1128
1186
|
const ask = (name: string, event: string, payload: unknown) =>
|
|
1129
1187
|
askInTurn(
|
|
1130
1188
|
server.listeners(name, event).filter((listening) => listening.kind === 'before' && isHeardAt(listening, [], payload)).map((listening) => ({ ...listening, ask: (signal: AbortSignal) => listening.connection.request(beforeMethod, { id: listening.id, payload } satisfies Heard, signal) })),
|
|
@@ -1154,11 +1212,8 @@ export function serveProviders({
|
|
|
1154
1212
|
const asked = isObject(input) ? input : {}
|
|
1155
1213
|
if (method === interfaceMethods.providers) return listed(String(asked['name']))
|
|
1156
1214
|
if (method === interfaceMethods.provider) return waitForProvider(asked)
|
|
1157
|
-
if (method === interfaceMethods.listen) return new Promise((resolve) => resolve(
|
|
1158
|
-
if (method === interfaceMethods.unlisten)
|
|
1159
|
-
sessionListeners.unlisten(String(caller), String(asked['id']))
|
|
1160
|
-
return Promise.resolve(unlisten(caller, String(asked['id'])))
|
|
1161
|
-
}
|
|
1215
|
+
if (method === interfaceMethods.listen) return new Promise((resolve) => resolve(listenFor(caller, input as ProvidedListen)))
|
|
1216
|
+
if (method === interfaceMethods.unlisten) return Promise.resolve(stopListening(caller, String(asked['id'])))
|
|
1162
1217
|
if (method === interfaceMethods.tell) return Promise.resolve(sessionListeners.tell(String(caller), input as ProvidedTell))
|
|
1163
1218
|
if (method === interfaceMethods.ask) return sessionListeners.ask(String(caller), input as ProvidedTell)
|
|
1164
1219
|
const call = asked as Partial<ProvidedCall>
|
|
@@ -1182,6 +1237,10 @@ export function serveProviders({
|
|
|
1182
1237
|
},
|
|
1183
1238
|
tell: (name, event, payload) => server.emit(name, event, payload),
|
|
1184
1239
|
ask,
|
|
1240
|
+
listened: () => [...kept.values()],
|
|
1241
|
+
forget(caller) {
|
|
1242
|
+
for (const each of [...kept.values()].filter((listened) => listened.caller === caller)) stopListening(caller, each.listen.id)
|
|
1243
|
+
},
|
|
1185
1244
|
handler(method, params, signal) {
|
|
1186
1245
|
const isProvided = method === listenMethod || method === unlistenMethod || (!method.startsWith('$/') && method.includes('.'))
|
|
1187
1246
|
return isProvided ? Promise.resolve(handle(method, params, signal)) : undefined
|
package/src/runtime/lifecycle.ts
CHANGED
|
@@ -332,7 +332,7 @@ export function createLifecycle<State extends object, Declared extends Options =
|
|
|
332
332
|
|
|
333
333
|
const isInstalledCopy = async () => {
|
|
334
334
|
await recording
|
|
335
|
-
if (plugin === undefined) return true
|
|
335
|
+
if (plugin === undefined || plugin.name === cmodPluginName) return true
|
|
336
336
|
const recorded = await readRecord((path) => claude().fs.read(path).catch(ifMissing(undefined)), plugin.store, plugin.name)
|
|
337
337
|
return recorded === undefined || recorded.root === plugin.root
|
|
338
338
|
}
|
|
@@ -1086,8 +1086,8 @@ async function createMod<State extends object, Declared extends Options>(definit
|
|
|
1086
1086
|
}
|
|
1087
1087
|
}
|
|
1088
1088
|
const followCurrent = async (id: string, title: string | undefined) => {
|
|
1089
|
-
const [model, usage] = await Promise.all([claude.session.model(), claude.session.usage()])
|
|
1090
|
-
followed = { id, title: title ?? '', project: modState.root, cwd, model, startedAt: new Date(usage.startedAt).toISOString(), ...(forkedFrom === undefined ? {} : { forkedFrom }), ...(agentType === undefined ? {} : { agentType }) }
|
|
1089
|
+
const [model, usage, { transcriptPath }] = await Promise.all([claude.session.model(), claude.session.usage(), claude.session.info()])
|
|
1090
|
+
followed = { id, title: title ?? '', project: modState.root, cwd, ...(transcriptPath === '' ? {} : { transcriptPath }), model, startedAt: new Date(usage.startedAt).toISOString(), ...(forkedFrom === undefined ? {} : { forkedFrom }), ...(agentType === undefined ? {} : { agentType }) }
|
|
1091
1091
|
client.follow(followed)
|
|
1092
1092
|
}
|
|
1093
1093
|
router.add('classic.SessionStart', async (e, next) => {
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { modNote } from '../session/context/turn/message/note.js'
|
|
1
2
|
import type { Subscription } from '../utils/subscription.js'
|
|
2
3
|
import type { HookFields } from './hooks.js'
|
|
3
4
|
import { defined, processPayloadOf, recordOf, type HookOn, type RouteOn, type ToolCheck } from './sessions.js'
|
|
4
5
|
|
|
5
6
|
export type PermissionUse = {
|
|
7
|
+
readonly name: string
|
|
6
8
|
readonly raise: (method: string, payload: HookFields, cancel: AbortSignal) => Promise<HookFields | undefined>
|
|
7
9
|
readonly refusalFor: (method: string, payload: HookFields, error: Error) => { readonly refuse: string } | undefined
|
|
8
10
|
readonly hookOn: HookOn
|
|
@@ -18,7 +20,7 @@ const verdictName = (decision: Verdict['decision']) => (decision === 'deny' ? 'r
|
|
|
18
20
|
|
|
19
21
|
type BuildFlags = { readonly cmodWithoutApprove?: true }
|
|
20
22
|
|
|
21
|
-
export const permissionRoutes: PermissionRoutes = (method, { raise, refusalFor, hookOn, routeOn, current }) => {
|
|
23
|
+
export const permissionRoutes: PermissionRoutes = (method, { name, raise, refusalFor, hookOn, routeOn, current }) => {
|
|
22
24
|
const isBefore = method.startsWith('before')
|
|
23
25
|
if (method.endsWith('PermissionCheck')) {
|
|
24
26
|
const payloadOf = (e: ToolCheck, below: Verdict) => {
|
|
@@ -29,7 +31,16 @@ export const permissionRoutes: PermissionRoutes = (method, { raise, refusalFor,
|
|
|
29
31
|
const refusal = refusalFor(method, payloadOf(e, (await next(e)) as Verdict), error)
|
|
30
32
|
return refusal === undefined ? undefined : { decision: 'deny' as const, reason: refusal.refuse }
|
|
31
33
|
}
|
|
32
|
-
|
|
34
|
+
const notes = new Map<string, string>()
|
|
35
|
+
const delivered = isBefore
|
|
36
|
+
? routeOn('tool.call', async (e, next) => {
|
|
37
|
+
const ran = await next(e)
|
|
38
|
+
const note = notes.get(e.tool_use_id)
|
|
39
|
+
notes.delete(e.tool_use_id)
|
|
40
|
+
return note === undefined || ran.deny !== undefined ? ran : { ...ran, context: [...(ran.context ?? []), note] }
|
|
41
|
+
})
|
|
42
|
+
: undefined
|
|
43
|
+
const checked = routeOn(
|
|
33
44
|
'tool.check',
|
|
34
45
|
async (e: ToolCheck, next) => {
|
|
35
46
|
const below = (await next(e)) as Verdict
|
|
@@ -40,6 +51,7 @@ export const permissionRoutes: PermissionRoutes = (method, { raise, refusalFor,
|
|
|
40
51
|
}
|
|
41
52
|
const answer = await raise(method, payload, next.signal)
|
|
42
53
|
if (answer === undefined || below.decision === 'deny') return below
|
|
54
|
+
if (typeof answer['note'] === 'string' && e.tool_use_id !== undefined) notes.set(e.tool_use_id, modNote(name, answer['note']))
|
|
43
55
|
if (typeof answer['refuse'] === 'string') return { decision: 'deny', reason: answer['refuse'] }
|
|
44
56
|
if (!(globalThis as BuildFlags).cmodWithoutApprove) {
|
|
45
57
|
if (typeof answer['ask'] === 'string') return { decision: 'ask', reason: answer['ask'] }
|
|
@@ -49,6 +61,12 @@ export const permissionRoutes: PermissionRoutes = (method, { raise, refusalFor,
|
|
|
49
61
|
},
|
|
50
62
|
isBefore ? failed : undefined,
|
|
51
63
|
)
|
|
64
|
+
return {
|
|
65
|
+
remove() {
|
|
66
|
+
checked.remove()
|
|
67
|
+
delivered?.remove()
|
|
68
|
+
},
|
|
69
|
+
}
|
|
52
70
|
}
|
|
53
71
|
const refused = (refuse: string, interrupt?: unknown) => ({ decision: defined({ behavior: 'deny', message: refuse, interrupt }) })
|
|
54
72
|
return hookOn(
|