@cmodjs/core 7.0.0 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/commands.md +104 -70
- package/docs/dependencies.md +153 -23
- package/docs/index.md +54 -10
- package/docs/install-steps.md +20 -17
- package/docs/jobs.md +42 -17
- package/docs/mod.md +37 -30
- package/docs/options.md +2 -2
- package/docs/session.md +39 -29
- package/docs/testing.md +84 -23
- package/docs/ui.md +128 -58
- package/installer.d.ts +2 -2
- package/jobs/context.js +1 -1
- package/jobs/program.d.ts +2 -3
- package/jobs/program.d.ts.map +1 -1
- package/jobs/program.js +72 -23
- package/mod.d.ts +23 -8
- package/mod.d.ts.map +1 -1
- package/mod.js +3 -3
- package/package.json +1 -1
- package/records.d.ts +5 -3
- package/records.d.ts.map +1 -1
- package/records.js +18 -9
- package/register.d.ts.map +1 -1
- package/register.js +7 -15
- package/rpc.d.ts +7 -0
- package/rpc.d.ts.map +1 -0
- package/rpc.js +59 -0
- package/runtime/bound.d.ts +1 -0
- package/runtime/bound.d.ts.map +1 -1
- package/runtime/bound.js +10 -0
- package/runtime/bun.d.ts +20 -0
- package/runtime/bun.d.ts.map +1 -0
- package/runtime/bun.js +20 -0
- package/runtime/claude.d.ts +1 -0
- package/runtime/claude.d.ts.map +1 -1
- package/runtime/conversations.d.ts +9 -2
- package/runtime/conversations.d.ts.map +1 -1
- package/runtime/conversations.js +244 -185
- package/runtime/deadline.d.ts +4 -3
- package/runtime/deadline.d.ts.map +1 -1
- package/runtime/deadline.js +10 -4
- package/runtime/engine.d.ts +4 -4
- package/runtime/engine.d.ts.map +1 -1
- package/runtime/installer.d.ts +3 -3
- package/runtime/installer.d.ts.map +1 -1
- package/runtime/installer.js +10 -9
- package/runtime/interfaces.d.ts +108 -42
- package/runtime/interfaces.d.ts.map +1 -1
- package/runtime/interfaces.js +639 -143
- package/runtime/lifecycle.d.ts +3 -5
- package/runtime/lifecycle.d.ts.map +1 -1
- package/runtime/lifecycle.js +74 -63
- package/runtime/options.d.ts.map +1 -1
- package/runtime/options.js +2 -6
- package/runtime/parts.d.ts +64 -1
- package/runtime/parts.d.ts.map +1 -1
- package/runtime/parts.js +311 -4
- package/runtime/programs.d.ts +1 -0
- package/runtime/programs.d.ts.map +1 -1
- package/runtime/programs.js +5 -3
- package/runtime/rpc.d.ts +2 -0
- package/runtime/rpc.d.ts.map +1 -1
- package/runtime/rpc.js +30 -5
- package/runtime/sessions.d.ts +3 -3
- package/runtime/sessions.d.ts.map +1 -1
- package/runtime/sessions.js +38 -73
- package/runtime/toaster.js +1 -1
- package/runtime/ui.d.ts +19 -8
- package/runtime/ui.d.ts.map +1 -1
- package/runtime/ui.js +51 -47
- package/runtime/web.d.ts +0 -73
- package/runtime/web.d.ts.map +1 -1
- package/runtime/web.js +9 -5
- package/runtime/widgets.d.ts +4 -2
- package/runtime/widgets.d.ts.map +1 -1
- package/runtime/widgets.js +17 -16
- package/session/conversation.d.ts +6 -2
- package/session/conversation.d.ts.map +1 -1
- package/session/session.d.ts +22 -6
- package/session/session.d.ts.map +1 -1
- package/session/session.js +1 -0
- package/src/installer.ts +2 -2
- package/src/jobs/context.ts +1 -1
- package/src/jobs/program.ts +63 -23
- package/src/mod.ts +22 -11
- package/src/records.ts +21 -9
- package/src/register.ts +7 -15
- package/src/rpc.ts +67 -0
- package/src/runtime/bound.ts +10 -0
- package/src/runtime/bun.ts +40 -0
- package/src/runtime/claude.ts +1 -0
- package/src/runtime/conversations.ts +247 -182
- package/src/runtime/deadline.ts +13 -6
- package/src/runtime/engine.ts +4 -4
- package/src/runtime/installer.ts +13 -12
- package/src/runtime/interfaces.ts +753 -172
- package/src/runtime/lifecycle.ts +93 -67
- package/src/runtime/options.ts +2 -5
- package/src/runtime/parts.ts +364 -5
- package/src/runtime/programs.ts +6 -3
- package/src/runtime/rpc.ts +32 -5
- package/src/runtime/sessions.ts +39 -73
- package/src/runtime/toaster.ts +1 -1
- package/src/runtime/ui.ts +67 -55
- package/src/runtime/web.ts +10 -39
- package/src/runtime/widgets.ts +20 -18
- package/src/session/conversation.ts +7 -2
- package/src/session/session.ts +14 -6
- package/src/testing/fake-claude.ts +10 -4
- package/src/testing/fake-serve.ts +106 -6
- package/src/testing/fake-sessions.ts +6 -5
- package/src/testing.ts +149 -67
- package/src/ui/areas.ts +2 -2
- package/src/ui/elements.ts +21 -16
- package/src/ui/panes.ts +14 -7
- package/testing/fake-claude.d.ts +2 -0
- package/testing/fake-claude.d.ts.map +1 -1
- package/testing/fake-claude.js +10 -4
- package/testing/fake-serve.d.ts +32 -2
- package/testing/fake-serve.d.ts.map +1 -1
- package/testing/fake-serve.js +81 -6
- package/testing/fake-sessions.d.ts.map +1 -1
- package/testing/fake-sessions.js +6 -5
- package/testing.d.ts +21 -4
- package/testing.d.ts.map +1 -1
- package/testing.js +131 -55
- package/ui/areas.d.ts +3 -1
- package/ui/areas.d.ts.map +1 -1
- package/ui/elements.d.ts +18 -9
- package/ui/elements.d.ts.map +1 -1
- package/ui/elements.js +9 -8
- package/ui/panes.d.ts +10 -6
- package/ui/panes.d.ts.map +1 -1
- package/ui/panes.js +5 -3
- package/runtime/pages.d.ts +0 -34
- package/runtime/pages.d.ts.map +0 -1
- package/runtime/pages.js +0 -157
- package/src/runtime/pages.ts +0 -198
package/src/mod.ts
CHANGED
|
@@ -23,9 +23,9 @@ import { checkOptions, type Option, type Options, type OptionValues } from './op
|
|
|
23
23
|
import { bound } from './runtime/bound.js'
|
|
24
24
|
import type { Device } from './session/context/turn/device.js'
|
|
25
25
|
import { Mod as modSender } from './session/context/turn/message/sender.js'
|
|
26
|
-
import {
|
|
26
|
+
import type { BeforeMethod, CommandRun, CommandRunAnswer, OnMethod, Sessions } from './session/session.js'
|
|
27
27
|
import type { Widget, WidgetInit } from './ui/areas.js'
|
|
28
|
-
import type { Page, PageInit, Pane, PaneInit } from './ui/panes.js'
|
|
28
|
+
import type { Page, PageInit, Pane, PaneInit, View, ViewInit } from './ui/panes.js'
|
|
29
29
|
import type { Kind, Style, StyleInit } from './ui/styles.js'
|
|
30
30
|
import type { Matcher } from './utils/matcher.js'
|
|
31
31
|
import type { Subscription } from './utils/subscription.js'
|
|
@@ -135,7 +135,12 @@ export type ProviderBefore<Payload> = {
|
|
|
135
135
|
|
|
136
136
|
export type InterfaceMethods<Name extends InterfaceName> = { readonly [Method in keyof MethodsOf<Name>]: MethodsOf<Name>[Method] extends (...args: infer Args) => infer Result ? (...args: Args) => Result | Promise<Awaited<Result>> : never }
|
|
137
137
|
|
|
138
|
-
export type
|
|
138
|
+
export type Provided<Name extends InterfaceName> = Subscription & {
|
|
139
|
+
tell<Event extends keyof EventsOf<Name> & string>(event: Event, payload: EventsOf<Name>[Event]): void
|
|
140
|
+
ask<Event extends keyof EventsOf<Name> & string>(event: Event, payload: EventsOf<Name>[Event]): Promise<unknown[]>
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export type InterfaceProvider<Name extends InterfaceName> = { readonly mod: string; readonly program?: string; readonly device: { readonly id: string; readonly name: string } } & {
|
|
139
144
|
readonly [Method in keyof MethodsOf<Name>]: MethodsOf<Name>[Method] extends (...args: infer Args) => infer Result ? (...args: Args) => Promise<Awaited<Result>> : never
|
|
140
145
|
} & { readonly [Event in keyof EventsOf<Name> & string as `on${Event}`]: ProviderOn<EventsOf<Name>[Event]> } & { readonly [Event in keyof EventsOf<Name> & string as `before${Event}`]: ProviderBefore<EventsOf<Name>[Event]> }
|
|
141
146
|
|
|
@@ -152,8 +157,10 @@ export type Imports = {
|
|
|
152
157
|
readonly user: SettingsFile
|
|
153
158
|
readonly project: SettingsFile
|
|
154
159
|
readonly local: SettingsFile
|
|
155
|
-
|
|
156
|
-
|
|
160
|
+
beforeChange(listener: SettingsFileChangeListener): Subscription
|
|
161
|
+
beforeChange(matcher: Matcher<SettingsFileChange>, listener: SettingsFileChangeListener): Subscription
|
|
162
|
+
onChange(listener: (change: SettingsFileChange) => unknown): Subscription
|
|
163
|
+
onChange(matcher: Matcher<SettingsFileChange>, listener: (change: SettingsFileChange) => unknown): Subscription
|
|
157
164
|
}
|
|
158
165
|
readonly model: { complete(request: ModelCompleteRequest, options?: ModelCompleteOptions): Promise<ModelCompleteResult> }
|
|
159
166
|
readonly fs: {
|
|
@@ -177,6 +184,7 @@ export type Imports = {
|
|
|
177
184
|
readonly device: { read(): Promise<Device> }
|
|
178
185
|
readonly clipboard: { write(text: string): Promise<void> }
|
|
179
186
|
readonly mods: { isLoaded(name: string): Promise<boolean> }
|
|
187
|
+
provide<Name extends InterfaceName>(name: Name, methods: InterfaceMethods<Name>): Provided<Name>
|
|
180
188
|
providers<Name extends InterfaceName>(name: Name): Promise<InterfaceProvider<Name>[]>
|
|
181
189
|
}
|
|
182
190
|
|
|
@@ -187,14 +195,14 @@ export const sessions: Imports['sessions'] = {
|
|
|
187
195
|
list: (options) => bound().sessions.list(options),
|
|
188
196
|
get: (id) => bound().sessions.get(id),
|
|
189
197
|
search: (text, matcher, options) => bound().sessions.search(text, matcher, options),
|
|
190
|
-
...(Object.fromEntries(Object.keys(sessionEvents).map((named) => [`on${named}`, (...args: unknown[]) => (bound().sessions[`on${named}` as keyof OnMethods] as (...each: unknown[]) => Subscription)(...args)])) as OnMethods),
|
|
191
198
|
}
|
|
192
199
|
|
|
193
200
|
export const settings: Imports['settings'] = {
|
|
194
201
|
user: { read: () => bound().settings.user.read(), update: (values) => bound().settings.user.update(values) },
|
|
195
202
|
project: { read: () => bound().settings.project.read(), update: (values) => bound().settings.project.update(values) },
|
|
196
203
|
local: { read: () => bound().settings.local.read(), update: (values) => bound().settings.local.update(values) },
|
|
197
|
-
|
|
204
|
+
beforeChange: ((matcherOrListener: never, listener?: never) => bound().settings.beforeChange(matcherOrListener, listener as never)) as Imports['settings']['beforeChange'],
|
|
205
|
+
onChange: ((matcherOrListener: never, listener?: never) => bound().settings.onChange(matcherOrListener, listener as never)) as Imports['settings']['onChange'],
|
|
198
206
|
}
|
|
199
207
|
|
|
200
208
|
export const commands: Imports['commands'] = {
|
|
@@ -248,12 +256,15 @@ export const mods: Imports['mods'] = {
|
|
|
248
256
|
isLoaded: (name) => bound().mods.isLoaded(name),
|
|
249
257
|
}
|
|
250
258
|
|
|
259
|
+
export const provide: Imports['provide'] = (name, methods) => bound().provide(name, methods)
|
|
260
|
+
|
|
251
261
|
export const providers: Imports['providers'] = (name) => bound().providers(name)
|
|
252
262
|
|
|
253
263
|
export type Mod<State extends object = Record<never, never>, Declared extends Options = Options, Keys extends Hotkeys = Hotkeys> = {
|
|
254
264
|
readonly name: string
|
|
255
265
|
readonly folder: string
|
|
256
266
|
readonly dataFolder: string
|
|
267
|
+
readonly cacheFolder: string
|
|
257
268
|
readonly secrets: {
|
|
258
269
|
get(key: string): Promise<string | undefined>
|
|
259
270
|
store(key: string, value: string): Promise<void>
|
|
@@ -267,9 +278,10 @@ export type Mod<State extends object = Record<never, never>, Declared extends Op
|
|
|
267
278
|
use<Handle>(job: Job<Handle, State>): Handle
|
|
268
279
|
log(text: string, options?: { readonly to?: 'debug' | 'transcript'; readonly level?: 'warning' | 'error' }): void
|
|
269
280
|
readonly panes: { add<Params = undefined>(pane: PaneInit<State, Params>): Pane<Params> }
|
|
270
|
-
readonly
|
|
281
|
+
readonly views: { add<Params = undefined>(view: ViewInit<State, Params>): View<Params> }
|
|
282
|
+
readonly pages: { add<Params = undefined>(page: PageInit<State, Params>): Page<Params> }
|
|
271
283
|
readonly settings: {
|
|
272
|
-
add<Params = undefined>(
|
|
284
|
+
add<Params = undefined>(view: ViewInit<State, Params>): View<Params>
|
|
273
285
|
open(): Promise<void>
|
|
274
286
|
}
|
|
275
287
|
readonly widgets: { add(widget: WidgetInit<State>): Widget }
|
|
@@ -277,7 +289,6 @@ export type Mod<State extends object = Record<never, never>, Declared extends Op
|
|
|
277
289
|
readonly toast: Toast
|
|
278
290
|
ask(question: string, options?: readonly string[] | AskOptions): Promise<string>
|
|
279
291
|
readonly dependencies: CmodDependencies
|
|
280
|
-
provide<Name extends InterfaceName>(name: Name, methods: InterfaceMethods<Name>): Subscription
|
|
281
292
|
}
|
|
282
293
|
|
|
283
294
|
export const Mod = modSender
|
|
@@ -326,7 +337,7 @@ export function defineMod<State extends StateGroups = Record<never, never>, Name
|
|
|
326
337
|
|
|
327
338
|
export type { Matcher } from './utils/matcher.js'
|
|
328
339
|
export type { Combo, Hotkey, HotkeyInit, Key } from './hotkeys.js'
|
|
329
|
-
export type { OpenOptions, Page, PageInit, PageProps, Pane, PaneClose, PaneInit, PaneProps, PaneScroll, ScrollOptions, ScrollTarget } from './ui/panes.js'
|
|
340
|
+
export type { OpenOptions, Page, PageInit, PageProps, Pane, PaneClose, PaneInit, PaneProps, PaneScroll, ScrollOptions, ScrollTarget, View, ViewInit, ViewProps } from './ui/panes.js'
|
|
330
341
|
export type { Kind, Row, Style, StyleInit, StyleProps } from './ui/styles.js'
|
|
331
342
|
export type { Block } from './ui/markdown.js'
|
|
332
343
|
export { AskUserQuestion, CommandOutput, ToolGroup, ToolProgress } from './ui/styles.js'
|
package/src/records.ts
CHANGED
|
@@ -54,12 +54,16 @@ export type RunnerEvent =
|
|
|
54
54
|
|
|
55
55
|
export const pluginName = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
|
|
56
56
|
|
|
57
|
-
|
|
58
|
-
const
|
|
57
|
+
function xdgFolder(env: Record<string, string | undefined>, variable: 'XDG_DATA_HOME' | 'XDG_CACHE_HOME', underHome: string): string {
|
|
58
|
+
const base = env[variable]
|
|
59
59
|
const home = env['HOME']
|
|
60
|
-
if (
|
|
61
|
-
if (!home) throw new Error(
|
|
62
|
-
return `${home}
|
|
60
|
+
if (base) return `${base}/cmod`
|
|
61
|
+
if (!home) throw new Error(`Neither ${variable} nor HOME is set, so cmod has no folder there. Set HOME.`)
|
|
62
|
+
return `${home}/${underHome}/cmod`
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function storeFolder(env: Record<string, string | undefined>): string {
|
|
66
|
+
return xdgFolder(env, 'XDG_DATA_HOME', '.local/share')
|
|
63
67
|
}
|
|
64
68
|
|
|
65
69
|
export function recordPath(store: string, name: string): string {
|
|
@@ -96,6 +100,10 @@ export function dataFolder(store: string, name: string): string {
|
|
|
96
100
|
return `${store}/data/${checkedName(name)}`
|
|
97
101
|
}
|
|
98
102
|
|
|
103
|
+
export function cacheFolder(env: Record<string, string | undefined>, name: string): string {
|
|
104
|
+
return `${xdgFolder(env, 'XDG_CACHE_HOME', '.cache')}/${checkedName(name)}`
|
|
105
|
+
}
|
|
106
|
+
|
|
99
107
|
export function configFolder(env: Record<string, string | undefined>, name: string): string {
|
|
100
108
|
const configRoot = env['CLAUDE_CONFIG_DIR']
|
|
101
109
|
const home = env['HOME']
|
|
@@ -107,10 +115,14 @@ export function configFolder(env: Record<string, string | undefined>, name: stri
|
|
|
107
115
|
export function configFolders(env: Record<string, string | undefined>, name: string, root: string): { readonly tier: 'system' | 'project'; readonly folder: string }[] {
|
|
108
116
|
return [
|
|
109
117
|
{ tier: 'system', folder: configFolder(env, name) },
|
|
110
|
-
{ tier: 'project', folder:
|
|
118
|
+
{ tier: 'project', folder: projectConfigFolder(root, name) },
|
|
111
119
|
]
|
|
112
120
|
}
|
|
113
121
|
|
|
122
|
+
export function projectConfigFolder(root: string, name: string): string {
|
|
123
|
+
return `${root}/.claude/cmods/${checkedName(name)}`
|
|
124
|
+
}
|
|
125
|
+
|
|
114
126
|
function checkedName(name: string): string {
|
|
115
127
|
if (!pluginName.test(name) || name.includes('..')) {
|
|
116
128
|
throw new Error(`"${name}" is not a plugin name: use letters, digits, ".", "_", and "-", starting with a letter or digit.`)
|
|
@@ -293,7 +305,7 @@ export function serveSocketPath(store: string): string {
|
|
|
293
305
|
return `${store}/serve.sock`
|
|
294
306
|
}
|
|
295
307
|
|
|
296
|
-
export type ProgramInstance = { readonly
|
|
308
|
+
export type ProgramInstance = { readonly pid: number; readonly started: string; readonly address?: string; readonly tailnetUrl?: string; readonly provides?: readonly string[] }
|
|
297
309
|
|
|
298
310
|
export const processTypes = ['Interactive', 'Background'] as const
|
|
299
311
|
|
|
@@ -481,9 +493,9 @@ function readHotkeys(hotkeys: unknown): Steps {
|
|
|
481
493
|
return { hotkeys: checkHotkeys('package.json "cmod"', hotkeys as Record<string, HotkeyInit>) }
|
|
482
494
|
}
|
|
483
495
|
|
|
484
|
-
export const coreVersion = '
|
|
496
|
+
export const coreVersion = '8.0.0'
|
|
485
497
|
|
|
486
|
-
export const oldestCmodVersion = '
|
|
498
|
+
export const oldestCmodVersion = '8.0.0'
|
|
487
499
|
|
|
488
500
|
export function hotkeyCommand(mod: string, hotkey: string): string {
|
|
489
501
|
return `${mod}--${hotkey}`
|
package/src/register.ts
CHANGED
|
@@ -6,12 +6,10 @@ import type { RoutedEvent } from './runtime/hooks.js'
|
|
|
6
6
|
import { serveConversations } from './runtime/conversations.js'
|
|
7
7
|
import { settledAfterAbort } from './runtime/deadline.js'
|
|
8
8
|
import { readDevice } from './runtime/device.js'
|
|
9
|
-
import { interfaceMethods, servePrograms } from './runtime/interfaces.js'
|
|
10
9
|
import { createLifecycle, readPlugin, type Lifecycle, type ServeCmodPlugin } from './runtime/lifecycle.js'
|
|
11
|
-
import {
|
|
10
|
+
import { serveParts } from './runtime/parts.js'
|
|
12
11
|
import { permissionRoutes, type PermissionRoutes } from './runtime/permission-check.js'
|
|
13
12
|
import { serveWidgets } from './runtime/widgets.js'
|
|
14
|
-
import { ifMissing } from './utils/paths.js'
|
|
15
13
|
import { messageOf } from './utils/text.js'
|
|
16
14
|
|
|
17
15
|
let lifecycle: Lifecycle<object>
|
|
@@ -109,6 +107,7 @@ async function startMod($: EngineInterface, eventInput: Frozen<Args<'session.sta
|
|
|
109
107
|
env: {
|
|
110
108
|
home: () => $.env.get('HOME'),
|
|
111
109
|
dataHome: () => $.env.get('XDG_DATA_HOME'),
|
|
110
|
+
cacheHome: () => $.env.get('XDG_CACHE_HOME'),
|
|
112
111
|
configHome: () => $.env.get('CLAUDE_CONFIG_DIR'),
|
|
113
112
|
browser: () => $.env.get('BROWSER'),
|
|
114
113
|
sshConnection: () => $.env.get('SSH_CONNECTION'),
|
|
@@ -145,19 +144,12 @@ function routeCallFailure(_$: EngineInterface, eventInput: Frozen<Args<'cmod.cal
|
|
|
145
144
|
}
|
|
146
145
|
|
|
147
146
|
export const serveCmodPlugin: ServeCmodPlugin = ({ claude, router, store, project, report, clear, tellRefusedPress, parts, markdownIn, tellStylers }) => {
|
|
148
|
-
const conversations = serveConversations({ claude, router, store, project, report, clear })
|
|
147
|
+
const conversations = serveConversations({ claude, router, store, project, report, clear, sessionCode: (name) => served.providers(name) })
|
|
149
148
|
const widgets = serveWidgets({ claude, router, store, report, turnClosedBy: (rowId) => conversations.turnClosedBy(rowId), parts, markdownIn })
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
files: { list: (path) => claude.fs.list(path).catch(ifMissing([])), read: (path) => claude.fs.read(path).catch(ifMissing(undefined)) },
|
|
155
|
-
wait: (ms) => new Promise<void>((resolve) => void claude.clock.after(ms, resolve)),
|
|
156
|
-
report: (error) => report('programs', 'A program provider missed a listener', error),
|
|
157
|
-
tell: (caller, heard) => claude.cmod.call({ to: caller, method: interfaceMethods.heard, input: heard }),
|
|
158
|
-
sessionCode: (name) => pages.providers(name),
|
|
159
|
-
})
|
|
160
|
-
return { conversations, widgets, pages, programs }
|
|
149
|
+
const served = serveParts({ claude, router, report, tellRefusedPress, widgets, parts, tellStylers, tellUi: (event, payload) => conversations.tellUi(event, payload) })
|
|
150
|
+
conversations.serveUi(served.ui)
|
|
151
|
+
conversations.onTurnClosed((turn) => served.turnClosed(turn))
|
|
152
|
+
return { conversations, widgets, parts: served }
|
|
161
153
|
}
|
|
162
154
|
|
|
163
155
|
export type AddHook = On
|
package/src/rpc.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { serveSocketPath, storeFolder } from './records.js'
|
|
2
|
+
import { bind, importsOnly } from './runtime/bound.js'
|
|
3
|
+
import { connectServe } from './runtime/bun.js'
|
|
4
|
+
import { cmodPluginName } from './runtime/dependencies.js'
|
|
5
|
+
import { createProviders, interfaceListeners, interfaceMethods, programConnection, serveProviders, type Connection } from './runtime/interfaces.js'
|
|
6
|
+
import { RpcError, rpcCodes } from './runtime/rpc.js'
|
|
7
|
+
import { messageOf } from './utils/text.js'
|
|
8
|
+
|
|
9
|
+
declare const process: { readonly env: Readonly<Record<string, string | undefined>>; readonly stderr: { write(text: string): unknown } }
|
|
10
|
+
|
|
11
|
+
declare function setTimeout(run: () => void, ms: number): unknown
|
|
12
|
+
|
|
13
|
+
declare function clearTimeout(timer: unknown): void
|
|
14
|
+
|
|
15
|
+
export type { Connection }
|
|
16
|
+
|
|
17
|
+
export class NotHeld extends Error {
|
|
18
|
+
constructor(session: string) {
|
|
19
|
+
super(`This provider holds no session ${session}.`)
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const modVariable = 'CMOD_MOD'
|
|
24
|
+
|
|
25
|
+
const programVariable = 'CMOD_PROGRAM'
|
|
26
|
+
|
|
27
|
+
export async function connect(): Promise<Connection> {
|
|
28
|
+
const mod = process.env[modVariable]
|
|
29
|
+
if (mod === undefined || mod === '') throw new Error(`connect() names its mod by ${modVariable}, which cmod program sets for every program it starts, and ${modVariable} is not set. Start this program from a program job with singleInstance or isService.`)
|
|
30
|
+
const report = (error: unknown) => void process.stderr.write(`${mod}: ${messageOf(error)}\n`)
|
|
31
|
+
const socket = serveSocketPath(storeFolder(process.env))
|
|
32
|
+
const listeners = interfaceListeners({ report })
|
|
33
|
+
let isWaitTold = false
|
|
34
|
+
let connected: () => void = () => undefined
|
|
35
|
+
const isConnected = new Promise<void>((resolve) => {
|
|
36
|
+
connected = resolve
|
|
37
|
+
})
|
|
38
|
+
const client = connectServe({
|
|
39
|
+
handle: async (method, params, signal) => {
|
|
40
|
+
const answered = await listeners.handler(method, params, signal)
|
|
41
|
+
if (answered !== undefined) return answered.result
|
|
42
|
+
const provided = served.handler(method, params, signal)
|
|
43
|
+
if (provided !== undefined) return provided.catch((error: unknown) => Promise.reject(error instanceof NotHeld ? new RpcError(rpcCodes.notHeld, error.message) : error))
|
|
44
|
+
throw new RpcError(rpcCodes.methodNotFound, `${mod} answers no ${method}.`)
|
|
45
|
+
},
|
|
46
|
+
onConnect: async (connection) => {
|
|
47
|
+
await served.replay()
|
|
48
|
+
await listeners.replay(connection)
|
|
49
|
+
connected()
|
|
50
|
+
},
|
|
51
|
+
onError: (error) => {
|
|
52
|
+
if (isWaitTold) return
|
|
53
|
+
isWaitTold = true
|
|
54
|
+
report(new Error(`waits for cmod serve at ${socket}: ${messageOf(error)}`))
|
|
55
|
+
},
|
|
56
|
+
keepsConnecting: true,
|
|
57
|
+
})
|
|
58
|
+
const after = (ms: number, run: () => void) => {
|
|
59
|
+
const timer = setTimeout(run, ms)
|
|
60
|
+
return { cancel: () => clearTimeout(timer) }
|
|
61
|
+
}
|
|
62
|
+
const served = serveProviders({ serve: client, listeners, provider: { mod, program: process.env[programVariable] || mod }, tell: async (_caller, heard, signal) => provided.answer(interfaceMethods.heard, heard, cmodPluginName, signal), sessionCode: () => [], after, report })
|
|
63
|
+
const provided = createProviders({ name: mod, call: (_to, method, input) => served.answer(method, input, mod) ?? Promise.reject(new Error(`${mod}'s program reaches no ${method}.`)), changed: () => undefined, after, report })
|
|
64
|
+
bind(importsOnly({ provide: (name, methods) => served.provide(name, methods), providers: (name) => provided.providers(name) as never }, `${mod}'s program`))
|
|
65
|
+
await isConnected
|
|
66
|
+
return programConnection({ client, listeners, served, after })
|
|
67
|
+
}
|
package/src/runtime/bound.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Imports } from '../mod.js'
|
|
2
|
+
import { listed } from '../utils/text.js'
|
|
2
3
|
|
|
3
4
|
let current: Imports | undefined
|
|
4
5
|
|
|
@@ -10,3 +11,12 @@ export function bound(): Imports {
|
|
|
10
11
|
if (current === undefined) throw new Error("A mod's imports work once its setup runs. Call them from setup or from a hook, never at the top of a module.")
|
|
11
12
|
return current
|
|
12
13
|
}
|
|
14
|
+
|
|
15
|
+
export function importsOnly(granted: Partial<Imports>, holder: string): Imports {
|
|
16
|
+
return new Proxy(granted as Imports, {
|
|
17
|
+
get: (target, key) => {
|
|
18
|
+
if (typeof key === 'string' && Object.hasOwn(target, key)) return target[key as keyof Imports]
|
|
19
|
+
throw new Error(`${holder} imports only ${listed(Object.keys(granted))} from @cmodjs/core/mod.js, because ${String(key)} belongs to a Claude Code session.`)
|
|
20
|
+
},
|
|
21
|
+
})
|
|
22
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { serveSocketPath, storeFolder } from '../records.js'
|
|
2
|
+
import { addressCall, connectRpc, type RpcClient, type RpcHandler } from './rpc.js'
|
|
3
|
+
|
|
4
|
+
declare const process: { readonly env: Readonly<Record<string, string | undefined>> }
|
|
5
|
+
|
|
6
|
+
declare function fetch(url: string, init: { readonly method?: string; readonly body?: string; readonly headers?: Readonly<Record<string, string>>; readonly unix?: string }): Promise<{ readonly status: number; readonly ok: boolean; readonly headers: Iterable<[string, string]>; text(): Promise<string> }>
|
|
7
|
+
|
|
8
|
+
declare function setTimeout(run: () => void, ms: number): { unref(): unknown }
|
|
9
|
+
|
|
10
|
+
export type BunInit = { readonly method?: string; readonly body?: string; readonly headers?: Readonly<Record<string, string>>; readonly socketPath?: string }
|
|
11
|
+
|
|
12
|
+
export async function bunFetch(url: string, init: BunInit = {}): Promise<{ readonly status: number; readonly ok: boolean; readonly headers: Readonly<Record<string, string>>; readonly text: string }> {
|
|
13
|
+
const answer = await fetch(url, { ...(init.method === undefined ? {} : { method: init.method }), ...(init.body === undefined ? {} : { body: init.body }), ...(init.headers === undefined ? {} : { headers: init.headers }), ...(init.socketPath === undefined ? {} : { unix: init.socketPath }) })
|
|
14
|
+
return { status: answer.status, ok: answer.ok, headers: Object.fromEntries(answer.headers), text: await answer.text() }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function connectServe({
|
|
18
|
+
handle,
|
|
19
|
+
onConnect,
|
|
20
|
+
onError,
|
|
21
|
+
keepsConnecting = false,
|
|
22
|
+
}: {
|
|
23
|
+
readonly handle: RpcHandler
|
|
24
|
+
readonly onConnect?: (client: RpcClient) => unknown
|
|
25
|
+
readonly onError?: (error: unknown) => void
|
|
26
|
+
readonly keepsConnecting?: boolean
|
|
27
|
+
}): RpcClient {
|
|
28
|
+
return connectRpc({
|
|
29
|
+
call: addressCall(bunFetch, `unix:${serveSocketPath(storeFolder(process.env))}`),
|
|
30
|
+
handle,
|
|
31
|
+
...(onConnect === undefined ? {} : { onConnect }),
|
|
32
|
+
...(onError === undefined ? {} : { onError }),
|
|
33
|
+
wait: (ms) =>
|
|
34
|
+
new Promise<void>((resolve) => {
|
|
35
|
+
const timer = setTimeout(resolve, ms)
|
|
36
|
+
if (!keepsConnecting) timer.unref()
|
|
37
|
+
}),
|
|
38
|
+
keepsConnecting,
|
|
39
|
+
})
|
|
40
|
+
}
|
package/src/runtime/claude.ts
CHANGED
|
@@ -113,6 +113,7 @@ export type Claude = {
|
|
|
113
113
|
readonly env: {
|
|
114
114
|
home(): Promise<string | undefined>
|
|
115
115
|
dataHome(): Promise<string | undefined>
|
|
116
|
+
cacheHome(): Promise<string | undefined>
|
|
116
117
|
configHome(): Promise<string | undefined>
|
|
117
118
|
browser(): Promise<string | undefined>
|
|
118
119
|
sshConnection(): Promise<string | undefined>
|