@cslug/cli 0.4.1 → 0.5.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/README.md +17 -1
- package/docs/api.md +6 -2
- package/package.json +8 -2
- package/src/commands/add.ts +6 -0
- package/src/commands/agents-sync.ts +262 -0
- package/src/commands/builtin.ts +4 -0
- package/src/commands/describe.ts +18 -12
- package/src/commands/mcp-dev.ts +307 -0
- package/src/index.ts +3 -1
- package/src/supervisor.ts +48 -12
- package/stubs/add/ai.config.stub +11 -0
package/docs/README.md
CHANGED
|
@@ -8,7 +8,7 @@ Where commands come from:
|
|
|
8
8
|
|
|
9
9
|
| Source | How |
|
|
10
10
|
|---|---|
|
|
11
|
-
| built-in | `list`, `about`, `config:show`, `key:generate`, `add`, `describe`, `repl`, `start`, `dev`, `make:command/provider/event/listener/service/test` |
|
|
11
|
+
| built-in | `list`, `about`, `config:show`, `key:generate`, `add`, `describe`, `mcp:dev`, `agents:sync`, `repl`, `start`, `dev`, `make:command/provider/event/listener/service/test` |
|
|
12
12
|
| packages | their provider calls `this.commands([...])` in `register()`. @cslug/http: `serve`, `routes`, `make:controller/validator/middleware`. @cslug/database: `migrate`, `migrate:status/rollback/fresh`, `db:seed`, `make:migration/table/repository/factory/seeder` |
|
|
13
13
|
| your app | classes exported from `app/commands/**/*-command.ts`, imported only when needed. A file that fails to import is skipped with a warning |
|
|
14
14
|
|
|
@@ -27,6 +27,7 @@ under `bun --watch`. Roles whose command is not installed are skipped with a war
|
|
|
27
27
|
| `storage` | `@cslug/storage` | `StorageProvider`; `config/storage.ts` |
|
|
28
28
|
| `notification` | `@cslug/notification` | `NotificationProvider`; `config/notification.ts`; then `cslug migrate` |
|
|
29
29
|
| `webhook` | `@cslug/webhook` | `WebhookProvider`; `config/webhooks.ts`; then `cslug migrate` |
|
|
30
|
+
| `ai` | `@cslug/ai` | `AiProvider`; `config/ai.ts` (Anthropic, roles `fast` and `smart`) |
|
|
30
31
|
| `tailwind` | `tailwindcss`, `bun-plugin-tailwind` (dev) | `resources/styles/tailwind.css`, its import in `resources/client.ts`, `assets.tailwind: true` |
|
|
31
32
|
|
|
32
33
|
`@cslug/*` packages are installed at the CLI's own version (every package of a release shares it). Providers go into
|
|
@@ -40,6 +41,21 @@ it says what to add by hand. `--no-install` edits the files without running `bun
|
|
|
40
41
|
with `--json`. The CLI has `providers` and `config` (keys only); packages add theirs with `this.describe(name, fn)`
|
|
41
42
|
in a provider: `routes` (http), `tables` (database, from `app/tables/`), `jobs` and `schedules` (queue).
|
|
42
43
|
|
|
44
|
+
`cslug mcp:dev` serves development tools over MCP (stdio) for coding agents: `describe`, `routes`, `tables`,
|
|
45
|
+
`query` (read-only transaction, 5 s statement timeout, rows limited; needs @cslug/database), `logs` and `last_error`
|
|
46
|
+
(from `.cslug/dev.log`), `run_test` (`bun test [path] [-t name]` in the app, 3 min timeout) and `docs_search`
|
|
47
|
+
(sections of `node_modules/@cslug/*/docs`). Logs go to stderr; it refuses to run in production. `devTools(app)`
|
|
48
|
+
returns the tools (`McpTool[]` from @cslug/core). `cslug dev` writes every line its children print to
|
|
49
|
+
`.cslug/dev.log` as JSON lines (`{ t, role, stream, line }`), emptied at each start (`DEV_LOG`; the supervisor's
|
|
50
|
+
`logFile` option).
|
|
51
|
+
|
|
52
|
+
`cslug agents:sync [--check] [--file=AGENTS.md]` writes the generated sections of `AGENTS.md` between
|
|
53
|
+
`<!-- cslug:begin name -->` and `<!-- cslug:end name -->` markers: `stack`, `rules`, `layout`, `commands`, `app`
|
|
54
|
+
(routes, tables, jobs, schedules from the describe sections) and `tools`. Text outside the markers is kept as is; a
|
|
55
|
+
missing section is appended unless `<!-- cslug:off name -->` is in the file; a new file starts with a header for
|
|
56
|
+
hand-written notes. The output is deterministic, so `--check` (exit 1 when out of date, no write) suits CI.
|
|
57
|
+
`mergeAgents(existing, sections, title?)` and `agentsSections(app, commands)` are exported.
|
|
58
|
+
|
|
43
59
|
`cslug repl` boots the app and reads TypeScript lines: top-level `await`, declarations kept between lines, an open
|
|
44
60
|
brace continues on the next line. In scope: `app`, `resolve`, `config` and the exports of `app/tables/` and
|
|
45
61
|
`app/repositories/`. `evaluate(code, scope)` and `replScope(app)` are exported for tools.
|
package/docs/api.md
CHANGED
|
@@ -37,10 +37,14 @@ plus `app`, `clock`, `log`, `io`. When the session is not interactive, prompts r
|
|
|
37
37
|
| | |
|
|
38
38
|
|---|---|
|
|
39
39
|
| `CliKernel(app)` | `.run(argv)` → exit code; `.commands()` |
|
|
40
|
-
| `Supervisor(specs, options)` | `.start()`, `.stop(signal)` → exit code; `plannedProcesses(config, flags)` |
|
|
40
|
+
| `Supervisor(specs, options)` | `.start()`, `.stop(signal)` → exit code; options `cwd`, `bunFlags`, `env`, `shutdownTimeout`, `log`, `prefix`, `logFile`; `plannedProcesses(config, flags)` |
|
|
41
|
+
| `DEV_LOG` | `.cslug/dev.log`, where `cslug dev` appends what its processes print |
|
|
41
42
|
| `generator(kind, dir, description)` | a `make:<kind>` command from `stubs/<kind>.stub` |
|
|
42
43
|
| `AddCommand`, `ADDITIONS` | `cslug add <names>` and what each name installs and wires |
|
|
43
|
-
| `DescribeCommand` | `cslug describe [section] [--json]` |
|
|
44
|
+
| `DescribeCommand` | `cslug describe [section] [--json]`; `describeSections(app)` |
|
|
45
|
+
| `McpDevCommand`, `devTools(app)` | `cslug mcp:dev`; the tools it serves (`McpTool[]`) |
|
|
46
|
+
| `AgentsSyncCommand` | `cslug agents:sync [--check] [--file]` |
|
|
47
|
+
| `mergeAgents(existing, sections, title?)`, `agentsSections(app, commands)`, `AgentsSection` | Merge generated sections into an AGENTS.md (text outside the markers kept); build this app's sections |
|
|
44
48
|
| `ReplCommand`, `evaluate(code, scope)`, `replScope(app)` | `cslug repl` and its evaluator |
|
|
45
49
|
| `BufferedIO(answers?)` | capture output in tests: `app.instance(ConsoleIO, io)` |
|
|
46
50
|
| `defineCslugConfig()` | `cslug.config.ts`: `processes` (`web.instances`, `worker[]`, `scheduler`), `shutdownTimeout`, `assets` |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "The cslug command: generators, dev server, start supervisor, REPL.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -31,11 +31,17 @@
|
|
|
31
31
|
"cslug": "src/bin.ts"
|
|
32
32
|
},
|
|
33
33
|
"peerDependencies": {
|
|
34
|
-
"@cslug/core": "0.
|
|
34
|
+
"@cslug/core": "0.5.0",
|
|
35
|
+
"@cslug/database": "0.5.0"
|
|
35
36
|
},
|
|
36
37
|
"devDependencies": {
|
|
37
38
|
"@cslug/database": "workspace:*",
|
|
38
39
|
"@cslug/http": "workspace:*",
|
|
39
40
|
"@cslug/validation": "workspace:*"
|
|
41
|
+
},
|
|
42
|
+
"peerDependenciesMeta": {
|
|
43
|
+
"@cslug/database": {
|
|
44
|
+
"optional": true
|
|
45
|
+
}
|
|
40
46
|
}
|
|
41
47
|
}
|
package/src/commands/add.ts
CHANGED
|
@@ -41,6 +41,12 @@ export const ADDITIONS: Record<string, Addition> = {
|
|
|
41
41
|
config: 'webhooks',
|
|
42
42
|
next: 'cslug migrate (creates cslug_webhook_inbox)',
|
|
43
43
|
},
|
|
44
|
+
ai: {
|
|
45
|
+
packages: ['@cslug/ai'],
|
|
46
|
+
providers: { from: '@cslug/ai', names: ['AiProvider'] },
|
|
47
|
+
config: 'ai',
|
|
48
|
+
next: 'with @cslug/database: cslug migrate (creates cslug_ai_conversations, cslug_ai_messages and cslug_ai_runs)',
|
|
49
|
+
},
|
|
44
50
|
tailwind: {
|
|
45
51
|
packages: ['tailwindcss@^4.0.0', 'bun-plugin-tailwind'],
|
|
46
52
|
dev: true,
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { join, resolve } from 'node:path'
|
|
3
|
+
import { type Application, Command, flag } from '@cslug/core'
|
|
4
|
+
import { describeSections } from './describe'
|
|
5
|
+
|
|
6
|
+
/** A generated section: its marker name and Markdown body. */
|
|
7
|
+
export type AgentsSection = { name: string; body: string }
|
|
8
|
+
|
|
9
|
+
const begin = (name: string) => `<!-- cslug:begin ${name} -->`
|
|
10
|
+
const end = (name: string) => `<!-- cslug:end ${name} -->`
|
|
11
|
+
const off = (name: string) => `<!-- cslug:off ${name} -->`
|
|
12
|
+
|
|
13
|
+
const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Merge generated sections into an AGENTS.md: the text between `cslug:begin` / `cslug:end` markers is replaced,
|
|
17
|
+
* everything else is kept as written. A section without markers is appended (unless `<!-- cslug:off name -->` is
|
|
18
|
+
* in the file); a new file gets a short hand-editable header first.
|
|
19
|
+
*/
|
|
20
|
+
export function mergeAgents(existing: string | undefined, sections: AgentsSection[], title = 'this app'): string {
|
|
21
|
+
let text =
|
|
22
|
+
existing ??
|
|
23
|
+
`# AGENTS.md\n\nInstructions for AI coding agents working on ${title}.\n\n## Project notes\n\n` +
|
|
24
|
+
'<!-- Hand-written: domain glossary, decisions, things not to do. `cslug agents:sync` rewrites only the\n' +
|
|
25
|
+
' sections between cslug:begin and cslug:end markers; everything else in this file is kept. -->\n'
|
|
26
|
+
for (const { name, body } of sections) {
|
|
27
|
+
if (text.includes(off(name))) continue
|
|
28
|
+
const block = `${begin(name)}\n${body.trim()}\n${end(name)}`
|
|
29
|
+
const pattern = new RegExp(`${escapeRegExp(begin(name))}[\\s\\S]*?${escapeRegExp(end(name))}`)
|
|
30
|
+
text = pattern.test(text) ? text.replace(pattern, () => block) : `${text.trimEnd()}\n\n${block}\n`
|
|
31
|
+
}
|
|
32
|
+
return text.endsWith('\n') ? text : `${text}\n`
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
type Json = Record<string, unknown>
|
|
36
|
+
const readJson = (path: string): Json | undefined =>
|
|
37
|
+
existsSync(path) ? (JSON.parse(readFileSync(path, 'utf8')) as Json) : undefined
|
|
38
|
+
|
|
39
|
+
/** Folders cslug apps use, in the order they are listed, with what goes in them. */
|
|
40
|
+
const LAYOUT: [string, string][] = [
|
|
41
|
+
['app/controllers', 'HTTP controllers (`booking-controller.ts` → `BookingController`)'],
|
|
42
|
+
['app/validators', '`v` schemas shared by requests, jobs and agents'],
|
|
43
|
+
['app/tables', 'table definitions (columns, indexes): the source of `make:migration --from-tables`'],
|
|
44
|
+
['app/repositories', 'data access (`Repository` subclasses, the `sql` tag for joins)'],
|
|
45
|
+
['app/services', 'domain logic, `@inject()` classes'],
|
|
46
|
+
['app/policies', 'authorization (`auth.authorize(Policy, ability, row)`)'],
|
|
47
|
+
['app/jobs', 'queued jobs (`Job` subclasses, discovered)'],
|
|
48
|
+
['app/listeners', 'event listeners (discovered)'],
|
|
49
|
+
['app/events', 'events (`Event<Payload>(name)`)'],
|
|
50
|
+
['app/mail', 'mailables'],
|
|
51
|
+
['app/notifications', 'notifications'],
|
|
52
|
+
['app/agents', 'AI agents (`Agent` subclasses)'],
|
|
53
|
+
['app/tools', 'AI tools (`Tool` subclasses; `@mcp()` exposes them)'],
|
|
54
|
+
['app/commands', 'app commands (`*-command.ts`, discovered by `cslug`)'],
|
|
55
|
+
['app/providers', 'service providers'],
|
|
56
|
+
['config', 'one file per package (`config/database.ts`…), values from `env`'],
|
|
57
|
+
['routes', 'route files (`web.ts`, `api.ts`)'],
|
|
58
|
+
['resources/views', 'Vue pages rendered on the server'],
|
|
59
|
+
['resources/components', 'Vue components (islands where used with `hydrate`)'],
|
|
60
|
+
['resources/prompts', 'AI prompts (Markdown with `{{ variables }}`)'],
|
|
61
|
+
['database/migrations', 'SQL migrations (`-- up` / `-- down`)'],
|
|
62
|
+
['database/seeders', 'seeders'],
|
|
63
|
+
['tests', '`bun test` files (`testApp()`, fakes)'],
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
/** Rules that hold in every cslug app, plus those of the installed packages. */
|
|
67
|
+
function rules(installed: Set<string>): string[] {
|
|
68
|
+
const has = (p: string) => installed.has(`@cslug/${p}`)
|
|
69
|
+
return [
|
|
70
|
+
'Files are kebab-case and named after their export (`TripRepository` → `trip-repository.ts`); no dots except `.test.ts`.',
|
|
71
|
+
'Classes are wired with standard decorators: `@inject(A, B)` lists the constructor dependencies in order.',
|
|
72
|
+
'Errors are typed (`NotFoundError`, `ConflictError`, a `CslugError` code); never throw strings.',
|
|
73
|
+
'Time comes from an injected `Clock` (`clock.now()`, `clock.today()`); never `new Date()` in app code.',
|
|
74
|
+
'Money is integer minor units (`bigint`); ids are UUIDv7.',
|
|
75
|
+
'Input is validated with `v` schemas before use.',
|
|
76
|
+
...(has('database')
|
|
77
|
+
? [
|
|
78
|
+
'SQL goes through the query builder or the `sql` tag, never string concatenation; schema changes are migrations.',
|
|
79
|
+
]
|
|
80
|
+
: []),
|
|
81
|
+
...(has('http') ? ['Requests are validated with `await request.validate(Schema)`.'] : []),
|
|
82
|
+
...(has('auth')
|
|
83
|
+
? ["Check access with `auth.authorize(Policy, 'ability', row)` before touching another user's data."]
|
|
84
|
+
: []),
|
|
85
|
+
...(has('vue') ? ['Island props must be `Serialized<T>` (pass rows through `serialize()`).'] : []),
|
|
86
|
+
...(has('queue')
|
|
87
|
+
? ['Slow or retried work is a `Job`; jobs dispatched in a transaction run after it commits.']
|
|
88
|
+
: []),
|
|
89
|
+
...(has('ai')
|
|
90
|
+
? [
|
|
91
|
+
'Agents and tools are `@inject()` classes; tests answer agents with `t.ai.respond()` / `t.ai.fixture()`, never the real model.',
|
|
92
|
+
]
|
|
93
|
+
: []),
|
|
94
|
+
'Tests use `testApp()` and its fakes (`fakes: [...]`); a change is done when the typecheck and the tests pass.',
|
|
95
|
+
]
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const list = (items: string[], more = 0, hint = '') =>
|
|
99
|
+
items.length ? `${items.map((i) => `- ${i}`).join('\n')}${more ? `\n- … ${more} more (${hint})` : ''}` : '- none'
|
|
100
|
+
|
|
101
|
+
/** The generated sections of this app's AGENTS.md. */
|
|
102
|
+
export async function agentsSections(app: Application, commands: { signature: string }[]): Promise<AgentsSection[]> {
|
|
103
|
+
const root = app.rootDir
|
|
104
|
+
const pkg = readJson(join(root, 'package.json')) ?? {}
|
|
105
|
+
const declared = { ...(pkg.dependencies as Json), ...(pkg.devDependencies as Json) }
|
|
106
|
+
const cslug = Object.keys(declared)
|
|
107
|
+
.filter((name) => name.startsWith('@cslug/'))
|
|
108
|
+
.sort()
|
|
109
|
+
const installed = new Set(cslug)
|
|
110
|
+
const version = (name: string) =>
|
|
111
|
+
String(readJson(join(root, 'node_modules', name, 'package.json'))?.version ?? declared[name])
|
|
112
|
+
|
|
113
|
+
const stack = [
|
|
114
|
+
'cslug on Bun, TypeScript and PostgreSQL. Each installed package ships its docs for this version:',
|
|
115
|
+
'',
|
|
116
|
+
list(
|
|
117
|
+
cslug.map((name) => {
|
|
118
|
+
const docs = `node_modules/${name}/docs`
|
|
119
|
+
return existsSync(join(root, docs))
|
|
120
|
+
? `\`${name}\` ${version(name)}: \`${docs}/README.md\`, \`${docs}/api.md\``
|
|
121
|
+
: `\`${name}\` ${version(name)}`
|
|
122
|
+
}),
|
|
123
|
+
),
|
|
124
|
+
]
|
|
125
|
+
|
|
126
|
+
const scripts = Object.entries((pkg.scripts as Record<string, string> | undefined) ?? {}).sort(([a], [b]) =>
|
|
127
|
+
a.localeCompare(b),
|
|
128
|
+
)
|
|
129
|
+
const groups = new Map<string, string[]>()
|
|
130
|
+
for (const { signature } of commands) {
|
|
131
|
+
const group = signature.includes(':') ? (signature.split(':')[0] as string) : ''
|
|
132
|
+
groups.set(group, [...(groups.get(group) ?? []), signature])
|
|
133
|
+
}
|
|
134
|
+
const commandLines = [...groups]
|
|
135
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
136
|
+
.map(
|
|
137
|
+
([group, sigs]) =>
|
|
138
|
+
`${group ? `\`${group}:\`` : 'general'}: ${sigs
|
|
139
|
+
.sort()
|
|
140
|
+
.map((s) => `\`${s}\``)
|
|
141
|
+
.join(', ')}`,
|
|
142
|
+
)
|
|
143
|
+
const commandsBody = [
|
|
144
|
+
'## Commands',
|
|
145
|
+
'',
|
|
146
|
+
...(scripts.length
|
|
147
|
+
? ['Scripts (`bun run <name>`):', '', list(scripts.map(([name, cmd]) => `\`${name}\`: \`${cmd}\``)), '']
|
|
148
|
+
: []),
|
|
149
|
+
'`cslug` commands (`bunx cslug <command> --help` for their arguments):',
|
|
150
|
+
'',
|
|
151
|
+
list(commandLines),
|
|
152
|
+
]
|
|
153
|
+
|
|
154
|
+
const layout = LAYOUT.filter(([dir]) => existsSync(join(root, dir)))
|
|
155
|
+
const layoutBody = ['## Where things go', '', list(layout.map(([dir, what]) => `\`${dir}/\`: ${what}`))]
|
|
156
|
+
|
|
157
|
+
const sections = describeSections(app)
|
|
158
|
+
const collect = async <T>(name: string): Promise<T[]> => ((await sections.get(name)?.()) as T[] | undefined) ?? []
|
|
159
|
+
const routes = await collect<{ method: string; path: string; name?: string; action?: string }>('routes')
|
|
160
|
+
const tables = await collect<{ name: string; columns: { name: string; references?: string }[] }>('tables')
|
|
161
|
+
const jobs = await collect<{ name: string; queue?: string }>('jobs')
|
|
162
|
+
const schedules = await collect<{ name: string; when: string; job?: string }>('schedules')
|
|
163
|
+
const own = routes.filter((r) => !r.path.startsWith('/health/'))
|
|
164
|
+
const shown = own.slice(0, 60)
|
|
165
|
+
const appBody = [
|
|
166
|
+
'## This app',
|
|
167
|
+
'',
|
|
168
|
+
'From `cslug describe` (`--json` for every detail; `cslug mcp:dev` serves it live).',
|
|
169
|
+
'',
|
|
170
|
+
`Routes (${own.length}, besides /health/*):`,
|
|
171
|
+
'',
|
|
172
|
+
list(
|
|
173
|
+
shown.map(
|
|
174
|
+
(r) =>
|
|
175
|
+
`\`${r.method} ${r.path}\`${r.name ? ` ${r.name}` : ''}${r.action && r.action !== 'closure' ? ` → ${r.action}` : ''}`,
|
|
176
|
+
),
|
|
177
|
+
own.length - shown.length,
|
|
178
|
+
'cslug describe routes',
|
|
179
|
+
),
|
|
180
|
+
'',
|
|
181
|
+
`Tables (${tables.length}):`,
|
|
182
|
+
'',
|
|
183
|
+
list(
|
|
184
|
+
tables.map(
|
|
185
|
+
(t) =>
|
|
186
|
+
`\`${t.name}\`: ${t.columns.map((c) => (c.references ? `${c.name} → ${c.references}` : c.name)).join(', ')}`,
|
|
187
|
+
),
|
|
188
|
+
),
|
|
189
|
+
...(sections.has('jobs')
|
|
190
|
+
? [
|
|
191
|
+
'',
|
|
192
|
+
`Jobs (${jobs.length}):`,
|
|
193
|
+
'',
|
|
194
|
+
list(jobs.map((j) => `\`${j.name}\`${j.queue ? ` (queue ${j.queue})` : ''}`)),
|
|
195
|
+
]
|
|
196
|
+
: []),
|
|
197
|
+
...(sections.has('schedules')
|
|
198
|
+
? [
|
|
199
|
+
'',
|
|
200
|
+
`Schedules (${schedules.length}):`,
|
|
201
|
+
'',
|
|
202
|
+
list(schedules.map((s) => `\`${s.name}\`: ${s.when}${s.job ? ` → ${s.job}` : ''}`)),
|
|
203
|
+
]
|
|
204
|
+
: []),
|
|
205
|
+
]
|
|
206
|
+
|
|
207
|
+
const check = ['typecheck', 'test'].filter((s) => scripts.some(([name]) => name === s)).map((s) => `bun run ${s}`)
|
|
208
|
+
const toolsBody = [
|
|
209
|
+
'## Tools for agents',
|
|
210
|
+
'',
|
|
211
|
+
`- Before finishing: \`${check.length ? check.join(' && ') : 'bun test'}\`.`,
|
|
212
|
+
'- `cslug mcp:dev` is a development MCP server for this app: describe, routes, tables, read-only `query`, `logs` and',
|
|
213
|
+
' `last_error` (from `cslug dev`), `run_test`, `docs_search`:',
|
|
214
|
+
'',
|
|
215
|
+
' ```json',
|
|
216
|
+
' { "mcpServers": { "cslug": { "command": "bunx", "args": ["cslug", "mcp:dev"] } } }',
|
|
217
|
+
' ```',
|
|
218
|
+
'- Generators give each kind of class its canonical shape: prefer `cslug make:<kind> Name` to writing one from scratch.',
|
|
219
|
+
]
|
|
220
|
+
|
|
221
|
+
return [
|
|
222
|
+
{ name: 'stack', body: ['## Stack', '', ...stack].join('\n') },
|
|
223
|
+
{ name: 'rules', body: ['## Rules', '', list(rules(installed))].join('\n') },
|
|
224
|
+
{ name: 'layout', body: layoutBody.join('\n') },
|
|
225
|
+
{ name: 'commands', body: commandsBody.join('\n') },
|
|
226
|
+
{ name: 'app', body: appBody.join('\n') },
|
|
227
|
+
{ name: 'tools', body: toolsBody.join('\n') },
|
|
228
|
+
]
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* `cslug agents:sync`: writes the generated sections of AGENTS.md (stack, rules, layout, commands, the app's routes
|
|
233
|
+
* and tables, tools), keeping every hand-written line. `--check` only reports whether the file is up to date (CI).
|
|
234
|
+
*/
|
|
235
|
+
export class AgentsSyncCommand extends Command {
|
|
236
|
+
static signature = 'agents:sync'
|
|
237
|
+
static description = 'Update the generated sections of AGENTS.md (hand-written text is kept); --check for CI'
|
|
238
|
+
static args = {
|
|
239
|
+
check: flag.boolean().describe('Exit 1 if AGENTS.md is not up to date; write nothing'),
|
|
240
|
+
file: flag.string().optional().describe('Default: AGENTS.md'),
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async handle({ check, file = 'AGENTS.md' }: Command.Args<typeof AgentsSyncCommand>) {
|
|
244
|
+
const path = resolve(this.app.rootDir, file)
|
|
245
|
+
const existing = existsSync(path) ? readFileSync(path, 'utf8') : undefined
|
|
246
|
+
const { CliKernel } = await import('../kernel')
|
|
247
|
+
const commands = [...(await new CliKernel(this.app).commands()).values()]
|
|
248
|
+
const name = String(readJson(join(this.app.rootDir, 'package.json'))?.name ?? 'this app')
|
|
249
|
+
const next = mergeAgents(existing, await agentsSections(this.app, commands), `\`${name}\``)
|
|
250
|
+
if (next === existing) {
|
|
251
|
+
this.success(`${file} is up to date`)
|
|
252
|
+
return 0
|
|
253
|
+
}
|
|
254
|
+
if (check) {
|
|
255
|
+
this.error(`${file} is out of date: run \`cslug agents:sync\``)
|
|
256
|
+
return 1
|
|
257
|
+
}
|
|
258
|
+
writeFileSync(path, next)
|
|
259
|
+
this.success(`${existing === undefined ? 'Created' : 'Updated'} ${file}`)
|
|
260
|
+
return 0
|
|
261
|
+
}
|
|
262
|
+
}
|
package/src/commands/builtin.ts
CHANGED
|
@@ -3,7 +3,9 @@ import { join } from 'node:path'
|
|
|
3
3
|
import { arg, Command, type CommandClass, flag, names } from '@cslug/core'
|
|
4
4
|
import { DevCommand, StartCommand } from '../supervisor'
|
|
5
5
|
import { AddCommand } from './add'
|
|
6
|
+
import { AgentsSyncCommand } from './agents-sync'
|
|
6
7
|
import { DescribeCommand } from './describe'
|
|
8
|
+
import { McpDevCommand } from './mcp-dev'
|
|
7
9
|
import { ReplCommand } from './repl'
|
|
8
10
|
|
|
9
11
|
export const STUBS = join(import.meta.dir, '../../stubs')
|
|
@@ -171,6 +173,8 @@ export const builtinCommands: CommandClass[] = [
|
|
|
171
173
|
KeyGenerateCommand,
|
|
172
174
|
AddCommand,
|
|
173
175
|
DescribeCommand,
|
|
176
|
+
McpDevCommand,
|
|
177
|
+
AgentsSyncCommand,
|
|
174
178
|
ReplCommand,
|
|
175
179
|
StartCommand,
|
|
176
180
|
DevCommand,
|
package/src/commands/describe.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { arg, Command, DESCRIBE, type DescribeSection, flag } from '@cslug/core'
|
|
1
|
+
import { type Application, arg, Command, DESCRIBE, type DescribeSection, flag } from '@cslug/core'
|
|
2
2
|
|
|
3
3
|
const flat = (row: unknown): row is Record<string, unknown> =>
|
|
4
4
|
typeof row === 'object' && row !== null && !Array.isArray(row)
|
|
@@ -9,6 +9,22 @@ const cell = (value: unknown) =>
|
|
|
9
9
|
? JSON.stringify(value)
|
|
10
10
|
: value
|
|
11
11
|
|
|
12
|
+
/** The sections `describe` knows: those the installed packages contribute, plus `providers` and `config` (keys). */
|
|
13
|
+
export function describeSections(app: Application): Map<string, () => unknown> {
|
|
14
|
+
const sections = new Map<string, () => unknown>([
|
|
15
|
+
['providers', () => app.providers.map((p) => p.name)],
|
|
16
|
+
[
|
|
17
|
+
'config',
|
|
18
|
+
() =>
|
|
19
|
+
Object.fromEntries(
|
|
20
|
+
Object.entries(app.configs).map(([name, value]) => [name, flat(value) ? Object.keys(value) : []]),
|
|
21
|
+
),
|
|
22
|
+
],
|
|
23
|
+
])
|
|
24
|
+
for (const s of app.tagged<DescribeSection>(DESCRIBE)) sections.set(s.name, s.collect)
|
|
25
|
+
return sections
|
|
26
|
+
}
|
|
27
|
+
|
|
12
28
|
/**
|
|
13
29
|
* `cslug describe [section] [--json]`: the app as data, for people, scripts and AI coding agents. Sections come from
|
|
14
30
|
* the installed packages (routes, tables, jobs, schedules) plus `providers` and `config` (keys only, never values).
|
|
@@ -22,17 +38,7 @@ export class DescribeCommand extends Command {
|
|
|
22
38
|
}
|
|
23
39
|
|
|
24
40
|
async handle({ section, json }: Command.Args<typeof DescribeCommand>) {
|
|
25
|
-
const sections =
|
|
26
|
-
['providers', () => this.app.providers.map((p) => p.name)],
|
|
27
|
-
[
|
|
28
|
-
'config',
|
|
29
|
-
() =>
|
|
30
|
-
Object.fromEntries(
|
|
31
|
-
Object.entries(this.app.configs).map(([name, value]) => [name, flat(value) ? Object.keys(value) : []]),
|
|
32
|
-
),
|
|
33
|
-
],
|
|
34
|
-
])
|
|
35
|
-
for (const s of this.app.tagged<DescribeSection>(DESCRIBE)) sections.set(s.name, s.collect)
|
|
41
|
+
const sections = describeSections(this.app)
|
|
36
42
|
|
|
37
43
|
if (!section) {
|
|
38
44
|
const all: Record<string, unknown> = {}
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
2
|
+
import { join, relative, resolve as resolvePath } from 'node:path'
|
|
3
|
+
import { type Application, Command, Logger, type McpTool, serveMcpStdio, v } from '@cslug/core'
|
|
4
|
+
import { DEV_LOG } from '../supervisor'
|
|
5
|
+
import { describeSections } from './describe'
|
|
6
|
+
|
|
7
|
+
/** An MCP tool whose arguments are checked with a `v` schema. */
|
|
8
|
+
function tool<
|
|
9
|
+
S extends {
|
|
10
|
+
_output: unknown
|
|
11
|
+
toJSONSchema(): object
|
|
12
|
+
safeParse(x: unknown): { success: true; data: unknown } | { success: false; error: { issues: unknown } }
|
|
13
|
+
},
|
|
14
|
+
>(name: string, description: string, input: S, handle: (args: S['_output']) => unknown): McpTool {
|
|
15
|
+
return {
|
|
16
|
+
name,
|
|
17
|
+
description,
|
|
18
|
+
inputSchema: input.toJSONSchema() as Record<string, unknown>,
|
|
19
|
+
call: (args) => {
|
|
20
|
+
const parsed = input.safeParse(args)
|
|
21
|
+
if (!parsed.success) throw new Error(`Invalid arguments: ${JSON.stringify(parsed.error.issues)}`)
|
|
22
|
+
return handle(parsed.data as never)
|
|
23
|
+
},
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Query rows as JSON can carry them (bigint → string). */
|
|
28
|
+
const plain = (value: unknown): unknown =>
|
|
29
|
+
JSON.parse(JSON.stringify(value, (_k, x) => (typeof x === 'bigint' ? x.toString() : x)))
|
|
30
|
+
|
|
31
|
+
type LogEntry = { t: string; role: string; stream: 'stdout' | 'stderr'; line: string }
|
|
32
|
+
|
|
33
|
+
/** The last `.cslug/dev.log` entries (the file can be large: only its tail is read). */
|
|
34
|
+
function readLog(rootDir: string, maxBytes = 2_000_000): LogEntry[] {
|
|
35
|
+
const path = join(rootDir, DEV_LOG)
|
|
36
|
+
if (!existsSync(path))
|
|
37
|
+
throw new Error(`No ${DEV_LOG}: start the app with \`cslug dev\` (it writes what the app prints there)`)
|
|
38
|
+
const size = statSync(path).size
|
|
39
|
+
const text = readFileSync(path, 'utf8')
|
|
40
|
+
const tail = size > maxBytes ? text.slice(-maxBytes).replace(/^[^\n]*\n/, '') : text
|
|
41
|
+
return tail
|
|
42
|
+
.split('\n')
|
|
43
|
+
.filter(Boolean)
|
|
44
|
+
.flatMap((l) => {
|
|
45
|
+
try {
|
|
46
|
+
return [JSON.parse(l) as LogEntry]
|
|
47
|
+
} catch {
|
|
48
|
+
return []
|
|
49
|
+
}
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A log line's own JSON (the app's logger writes JSON lines), or undefined. */
|
|
54
|
+
const json = (line: string): Record<string, unknown> | undefined => {
|
|
55
|
+
if (!line.startsWith('{')) return undefined
|
|
56
|
+
try {
|
|
57
|
+
return JSON.parse(line) as Record<string, unknown>
|
|
58
|
+
} catch {
|
|
59
|
+
return undefined
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const isError = (e: LogEntry) => {
|
|
64
|
+
const level = json(e.line)?.level
|
|
65
|
+
return level === 'error' || level === 'fatal' || (e.stream === 'stderr' && /(error|exception)\b/i.test(e.line))
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Markdown files split into sections at their headings. */
|
|
69
|
+
function docSections(rootDir: string): { package: string; file: string; heading: string; text: string }[] {
|
|
70
|
+
const scope = join(rootDir, 'node_modules/@cslug')
|
|
71
|
+
if (!existsSync(scope)) return []
|
|
72
|
+
const sections: { package: string; file: string; heading: string; text: string }[] = []
|
|
73
|
+
for (const pkg of readdirSync(scope)) {
|
|
74
|
+
const docs = join(scope, pkg, 'docs')
|
|
75
|
+
if (!existsSync(docs)) continue
|
|
76
|
+
for (const file of (readdirSync(docs, { recursive: true }) as string[]).filter((f) => f.endsWith('.md'))) {
|
|
77
|
+
let heading = file
|
|
78
|
+
let lines: string[] = []
|
|
79
|
+
const flush = () => {
|
|
80
|
+
if (lines.join('').trim()) sections.push({ package: `@cslug/${pkg}`, file, heading, text: lines.join('\n') })
|
|
81
|
+
lines = []
|
|
82
|
+
}
|
|
83
|
+
for (const line of readFileSync(join(docs, file), 'utf8').split('\n')) {
|
|
84
|
+
const h = /^#{1,4}\s+(.*)/.exec(line)
|
|
85
|
+
if (h) {
|
|
86
|
+
flush()
|
|
87
|
+
heading = h[1] as string
|
|
88
|
+
}
|
|
89
|
+
lines.push(line)
|
|
90
|
+
}
|
|
91
|
+
flush()
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return sections
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The development tools `cslug mcp:dev` serves, for coding agents working on this app. */
|
|
98
|
+
export function devTools(app: Application): McpTool[] {
|
|
99
|
+
const sections = () => describeSections(app)
|
|
100
|
+
const section = async (name: string) => {
|
|
101
|
+
const collect = sections().get(name)
|
|
102
|
+
if (!collect)
|
|
103
|
+
throw new Error(
|
|
104
|
+
`No "${name}" section (its package is not installed); sections: ${[...sections().keys()].join(', ')}`,
|
|
105
|
+
)
|
|
106
|
+
return collect()
|
|
107
|
+
}
|
|
108
|
+
return [
|
|
109
|
+
tool(
|
|
110
|
+
'describe',
|
|
111
|
+
'The app as data (what `cslug describe` shows): routes, tables, jobs, schedules, providers, config keys. Without a section: the section names and sizes.',
|
|
112
|
+
v.object({ section: v.string().optional() }),
|
|
113
|
+
async ({ section: name }) => {
|
|
114
|
+
if (name) return { [name]: await section(name) }
|
|
115
|
+
const summary: Record<string, number> = {}
|
|
116
|
+
for (const [key, collect] of sections()) {
|
|
117
|
+
const data = await collect()
|
|
118
|
+
summary[key] = Array.isArray(data)
|
|
119
|
+
? data.length
|
|
120
|
+
: data && typeof data === 'object'
|
|
121
|
+
? Object.keys(data).length
|
|
122
|
+
: 0
|
|
123
|
+
}
|
|
124
|
+
return { sections: summary }
|
|
125
|
+
},
|
|
126
|
+
),
|
|
127
|
+
tool(
|
|
128
|
+
'routes',
|
|
129
|
+
'HTTP routes: method, path, name, action, middleware. `filter` keeps those whose path, name or action contains it.',
|
|
130
|
+
v.object({ filter: v.string().optional() }),
|
|
131
|
+
async ({ filter }) => {
|
|
132
|
+
const routes = (await section('routes')) as Record<string, unknown>[]
|
|
133
|
+
const kept = filter
|
|
134
|
+
? routes.filter((r) => [r.path, r.name, r.action].some((x) => String(x ?? '').includes(filter)))
|
|
135
|
+
: routes
|
|
136
|
+
return { routes: kept }
|
|
137
|
+
},
|
|
138
|
+
),
|
|
139
|
+
tool(
|
|
140
|
+
'tables',
|
|
141
|
+
'Database tables declared in app code: columns (type, nullable, unique, default, references) and indexes. `name` for one table.',
|
|
142
|
+
v.object({ name: v.string().optional() }),
|
|
143
|
+
async ({ name }) => {
|
|
144
|
+
const tables = (await section('tables')) as { name?: string }[]
|
|
145
|
+
return { tables: name ? tables.filter((t) => t.name === name) : tables }
|
|
146
|
+
},
|
|
147
|
+
),
|
|
148
|
+
tool(
|
|
149
|
+
'query',
|
|
150
|
+
'Run one read-only SQL query on the development database (a read-only transaction, rolled back; 5 s timeout). Inline values in the SQL. Returns at most `limit` rows (default 50, max 500).',
|
|
151
|
+
v.object({ sql: v.string().min(1), limit: v.int().min(1).max(500).optional() }),
|
|
152
|
+
async ({ sql: text, limit = 50 }) => {
|
|
153
|
+
const db = await import('@cslug/database').catch(() => undefined)
|
|
154
|
+
if (!db || !app.has(db.Database))
|
|
155
|
+
throw new Error('No database: @cslug/database is not installed or not configured')
|
|
156
|
+
const { sql } = db
|
|
157
|
+
const rollback = Symbol('rollback')
|
|
158
|
+
let rows: unknown[] = []
|
|
159
|
+
await app
|
|
160
|
+
.resolve(db.Database)
|
|
161
|
+
.transaction(async (tx) => {
|
|
162
|
+
await tx.exec(sql`set transaction read only`)
|
|
163
|
+
await tx.exec(sql`set local statement_timeout = '5s'`)
|
|
164
|
+
rows = await tx.many(sql`${sql.raw(text)}`)
|
|
165
|
+
throw rollback
|
|
166
|
+
})
|
|
167
|
+
.catch((e) => {
|
|
168
|
+
if (e !== rollback) throw e
|
|
169
|
+
})
|
|
170
|
+
return { rowCount: rows.length, truncated: rows.length > limit, rows: plain(rows.slice(0, limit)) }
|
|
171
|
+
},
|
|
172
|
+
),
|
|
173
|
+
tool(
|
|
174
|
+
'logs',
|
|
175
|
+
`What the app printed under \`cslug dev\` (${DEV_LOG}), newest last: its JSON log lines parsed. Filter by role (web, worker…), level or text.`,
|
|
176
|
+
v.object({
|
|
177
|
+
lines: v.int().min(1).max(1000).optional(),
|
|
178
|
+
role: v.string().optional(),
|
|
179
|
+
level: v.enum(['debug', 'info', 'warn', 'error', 'fatal']).optional(),
|
|
180
|
+
contains: v.string().optional(),
|
|
181
|
+
}),
|
|
182
|
+
({ lines = 100, role, level, contains }) => {
|
|
183
|
+
const entries = readLog(app.rootDir).filter(
|
|
184
|
+
(e) =>
|
|
185
|
+
(!role || e.role === role) &&
|
|
186
|
+
(!level || json(e.line)?.level === level) &&
|
|
187
|
+
(!contains || e.line.includes(contains)),
|
|
188
|
+
)
|
|
189
|
+
return {
|
|
190
|
+
entries: entries.slice(-lines).map((e) => ({
|
|
191
|
+
t: e.t,
|
|
192
|
+
role: e.role,
|
|
193
|
+
stream: e.stream,
|
|
194
|
+
...(json(e.line) ? { log: json(e.line) } : { line: e.line }),
|
|
195
|
+
})),
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
),
|
|
199
|
+
tool(
|
|
200
|
+
'last_error',
|
|
201
|
+
`The most recent error the app logged or printed under \`cslug dev\` (${DEV_LOG}), with the lines that followed it (a stack trace).`,
|
|
202
|
+
v.object({}),
|
|
203
|
+
() => {
|
|
204
|
+
const entries = readLog(app.rootDir)
|
|
205
|
+
let at = -1
|
|
206
|
+
for (let i = entries.length - 1; i >= 0; i--)
|
|
207
|
+
if (isError(entries[i] as LogEntry)) {
|
|
208
|
+
at = i
|
|
209
|
+
break
|
|
210
|
+
}
|
|
211
|
+
if (at < 0) return 'No error in the log since `cslug dev` started.'
|
|
212
|
+
const entry = entries[at] as LogEntry
|
|
213
|
+
const after = entries
|
|
214
|
+
.slice(at + 1)
|
|
215
|
+
.filter((e) => e.role === entry.role)
|
|
216
|
+
.slice(0, 30)
|
|
217
|
+
.map((e) => e.line)
|
|
218
|
+
return {
|
|
219
|
+
t: entry.t,
|
|
220
|
+
role: entry.role,
|
|
221
|
+
...(json(entry.line) ? { log: json(entry.line) } : { line: entry.line }),
|
|
222
|
+
after,
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
),
|
|
226
|
+
tool(
|
|
227
|
+
'run_test',
|
|
228
|
+
'Run `bun test` in the app (optionally one file or folder, and a test name pattern). Returns whether it passed and the end of the output.',
|
|
229
|
+
v.object({ path: v.string().optional(), name: v.string().optional() }),
|
|
230
|
+
async ({ path, name }) => {
|
|
231
|
+
if (path) {
|
|
232
|
+
const full = resolvePath(app.rootDir, path)
|
|
233
|
+
if (relative(app.rootDir, full).startsWith('..')) throw new Error('`path` must be inside the app')
|
|
234
|
+
}
|
|
235
|
+
const proc = Bun.spawn(['bun', 'test', ...(path ? [path] : []), ...(name ? ['-t', name] : [])], {
|
|
236
|
+
cwd: app.rootDir,
|
|
237
|
+
stdout: 'pipe',
|
|
238
|
+
stderr: 'pipe',
|
|
239
|
+
env: { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1' },
|
|
240
|
+
})
|
|
241
|
+
const timer = setTimeout(() => proc.kill(), 180_000)
|
|
242
|
+
const [out, err, code] = await Promise.all([
|
|
243
|
+
new Response(proc.stdout).text(),
|
|
244
|
+
new Response(proc.stderr).text(),
|
|
245
|
+
proc.exited,
|
|
246
|
+
])
|
|
247
|
+
clearTimeout(timer)
|
|
248
|
+
const output = `${out}${err}`
|
|
249
|
+
return {
|
|
250
|
+
passed: code === 0,
|
|
251
|
+
exitCode: code,
|
|
252
|
+
output: output.length > 12_000 ? `…${output.slice(-12_000)}` : output,
|
|
253
|
+
}
|
|
254
|
+
},
|
|
255
|
+
),
|
|
256
|
+
tool(
|
|
257
|
+
'docs_search',
|
|
258
|
+
'Search the docs of the installed @cslug packages (node_modules/@cslug/*/docs): the best matching sections, for the installed version.',
|
|
259
|
+
v.object({ query: v.string().min(2), limit: v.int().min(1).max(20).optional() }),
|
|
260
|
+
({ query, limit = 5 }) => {
|
|
261
|
+
const terms = query
|
|
262
|
+
.toLowerCase()
|
|
263
|
+
.split(/\W+/)
|
|
264
|
+
.filter((t) => t.length > 1)
|
|
265
|
+
const count = (text: string, term: string) => text.split(term).length - 1
|
|
266
|
+
return {
|
|
267
|
+
results: docSections(app.rootDir)
|
|
268
|
+
.map((s) => {
|
|
269
|
+
const heading = s.heading.toLowerCase()
|
|
270
|
+
const body = s.text.toLowerCase()
|
|
271
|
+
const score = terms.reduce((sum, t) => sum + 3 * count(heading, t) + count(body, t), 0)
|
|
272
|
+
const all = terms.every((t) => body.includes(t))
|
|
273
|
+
return { ...s, score: score * (all ? 2 : 1) }
|
|
274
|
+
})
|
|
275
|
+
.filter((s) => s.score > 0)
|
|
276
|
+
.sort((a, b) => b.score - a.score)
|
|
277
|
+
.slice(0, limit)
|
|
278
|
+
.map(({ text, score: _, ...s }) => ({
|
|
279
|
+
...s,
|
|
280
|
+
text: text.length > 2_000 ? `${text.slice(0, 2_000)}…` : text,
|
|
281
|
+
})),
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
),
|
|
285
|
+
]
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* `cslug mcp:dev`: a development MCP server over stdio for coding agents (Claude Code and others):
|
|
290
|
+
* `{"command": "bunx", "args": ["cslug", "mcp:dev"]}`. Refused in production.
|
|
291
|
+
*/
|
|
292
|
+
export class McpDevCommand extends Command {
|
|
293
|
+
static signature = 'mcp:dev'
|
|
294
|
+
static description =
|
|
295
|
+
'Development MCP server (stdio) for coding agents: describe, routes, tables, query, logs, tests, docs'
|
|
296
|
+
|
|
297
|
+
async handle() {
|
|
298
|
+
if (this.app.config('app.env') === 'production') {
|
|
299
|
+
this.error('mcp:dev is a development tool; it does not run when app.env is production')
|
|
300
|
+
return 1
|
|
301
|
+
}
|
|
302
|
+
this.app.swap(Logger, new Logger({ write: (line) => process.stderr.write(`${line}\n`) }))
|
|
303
|
+
const tools = devTools(this.app)
|
|
304
|
+
await serveMcpStdio(() => tools, { name: `${String(this.app.config('app.name') ?? 'cslug')} (dev)`, version: '1' })
|
|
305
|
+
return 0
|
|
306
|
+
}
|
|
307
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -7,10 +7,12 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export { arg, Command, type CommandClass, ConsoleIO, flag, names } from '@cslug/core'
|
|
9
9
|
export { ADDITIONS, AddCommand } from './commands/add'
|
|
10
|
+
export { type AgentsSection, AgentsSyncCommand, agentsSections, mergeAgents } from './commands/agents-sync'
|
|
10
11
|
export { generator, STUBS } from './commands/builtin'
|
|
11
12
|
export { DescribeCommand } from './commands/describe'
|
|
13
|
+
export { devTools, McpDevCommand } from './commands/mcp-dev'
|
|
12
14
|
export { type Evaluated, evaluate, ReplCommand, replScope } from './commands/repl'
|
|
13
15
|
export { type CslugConfig, defineCslugConfig } from './config'
|
|
14
16
|
export { BufferedIO, commandHelp } from './io'
|
|
15
17
|
export { CliKernel } from './kernel'
|
|
16
|
-
export { type ProcessSpec, plannedProcesses, Supervisor } from './supervisor'
|
|
18
|
+
export { DEV_LOG, type ProcessSpec, plannedProcesses, Supervisor } from './supervisor'
|
package/src/supervisor.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { existsSync } from 'node:fs'
|
|
2
|
-
import { join } from 'node:path'
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { dirname, join } from 'node:path'
|
|
3
3
|
import { COMMANDS, Command, type CommandClass, flag } from '@cslug/core'
|
|
4
4
|
import type { CslugConfig } from './config'
|
|
5
5
|
|
|
@@ -83,6 +83,11 @@ export class Supervisor {
|
|
|
83
83
|
/** Prefix child output with its role (default: when stdout is a terminal; plain JSON lines otherwise). */
|
|
84
84
|
prefix?: boolean
|
|
85
85
|
bin?: string
|
|
86
|
+
/**
|
|
87
|
+
* Also append every line the children print to this file, as JSON lines `{ t, role, stream, line }`
|
|
88
|
+
* (`cslug dev` → `.cslug/dev.log`, read by `cslug mcp:dev`).
|
|
89
|
+
*/
|
|
90
|
+
logFile?: string
|
|
86
91
|
},
|
|
87
92
|
) {
|
|
88
93
|
this.children = specs.map((spec) => ({ spec, startedAt: 0, restarts: 0 }))
|
|
@@ -103,6 +108,7 @@ export class Supervisor {
|
|
|
103
108
|
|
|
104
109
|
private spawn(child: Child): void {
|
|
105
110
|
const prefix = this.options.prefix ?? !!process.stdout.isTTY
|
|
111
|
+
const piped = prefix || !!this.options.logFile
|
|
106
112
|
child.startedAt = Date.now()
|
|
107
113
|
child.exited = undefined
|
|
108
114
|
const proc = Bun.spawn(
|
|
@@ -110,22 +116,36 @@ export class Supervisor {
|
|
|
110
116
|
{
|
|
111
117
|
cwd: this.options.cwd,
|
|
112
118
|
env: { ...process.env, ...this.options.env, CSLUG_ROLE: child.spec.name },
|
|
113
|
-
stdout:
|
|
114
|
-
stderr:
|
|
119
|
+
stdout: piped ? 'pipe' : 'inherit',
|
|
120
|
+
stderr: piped ? 'pipe' : 'inherit',
|
|
115
121
|
stdin: 'ignore',
|
|
116
122
|
},
|
|
117
123
|
)
|
|
118
124
|
child.proc = proc
|
|
119
|
-
if (
|
|
120
|
-
this.pipe(proc.stdout as ReadableStream<Uint8Array>, child.spec.name, process.stdout)
|
|
121
|
-
this.pipe(proc.stderr as ReadableStream<Uint8Array>, child.spec.name, process.stderr)
|
|
125
|
+
if (piped) {
|
|
126
|
+
this.pipe(proc.stdout as ReadableStream<Uint8Array>, child.spec.name, process.stdout, prefix)
|
|
127
|
+
this.pipe(proc.stderr as ReadableStream<Uint8Array>, child.spec.name, process.stderr, prefix)
|
|
122
128
|
}
|
|
123
129
|
this.log(` ➜ ${child.spec.name.padEnd(10)} pid ${proc.pid} cslug ${child.spec.argv.join(' ')}`)
|
|
124
130
|
proc.exited.then((code) => this.onExit(child, proc, code))
|
|
125
131
|
}
|
|
126
132
|
|
|
127
|
-
private async pipe(
|
|
133
|
+
private async pipe(
|
|
134
|
+
stream: ReadableStream<Uint8Array>,
|
|
135
|
+
name: string,
|
|
136
|
+
out: NodeJS.WriteStream,
|
|
137
|
+
prefix: boolean,
|
|
138
|
+
): Promise<void> {
|
|
128
139
|
const decoder = new TextDecoder()
|
|
140
|
+
const kind = out === process.stderr ? 'stderr' : 'stdout'
|
|
141
|
+
const emit = (line: string) => {
|
|
142
|
+
out.write(prefix ? `[${name}] ${line}\n` : `${line}\n`)
|
|
143
|
+
if (this.options.logFile)
|
|
144
|
+
appendFileSync(
|
|
145
|
+
this.options.logFile,
|
|
146
|
+
`${JSON.stringify({ t: new Date().toISOString(), role: name, stream: kind, line })}\n`,
|
|
147
|
+
)
|
|
148
|
+
}
|
|
129
149
|
let buffer = ''
|
|
130
150
|
// a reader, not `for await`: the app's tsconfig may use the DOM lib, whose ReadableStream is not async-iterable
|
|
131
151
|
const reader = stream.getReader()
|
|
@@ -133,9 +153,9 @@ export class Supervisor {
|
|
|
133
153
|
buffer += decoder.decode(r.value, { stream: true })
|
|
134
154
|
const lines = buffer.split('\n')
|
|
135
155
|
buffer = lines.pop() ?? ''
|
|
136
|
-
for (const line of lines)
|
|
156
|
+
for (const line of lines) emit(line)
|
|
137
157
|
}
|
|
138
|
-
if (buffer)
|
|
158
|
+
if (buffer) emit(buffer)
|
|
139
159
|
}
|
|
140
160
|
|
|
141
161
|
private onExit(child: Child, proc: Bun.Subprocess, code: number | null): void {
|
|
@@ -195,6 +215,7 @@ async function supervise(
|
|
|
195
215
|
bunFlags: string[],
|
|
196
216
|
banner: string,
|
|
197
217
|
env: Record<string, string> = {},
|
|
218
|
+
logFile?: string,
|
|
198
219
|
): Promise<number> {
|
|
199
220
|
const config = await loadConfig(cmd.app.rootDir)
|
|
200
221
|
const planned = plannedProcesses(config.processes, flags)
|
|
@@ -211,12 +232,17 @@ async function supervise(
|
|
|
211
232
|
return 1
|
|
212
233
|
}
|
|
213
234
|
cmd.line(` cslug ${banner} (supervisor pid ${process.pid})`)
|
|
235
|
+
if (logFile) {
|
|
236
|
+
mkdirSync(dirname(logFile), { recursive: true })
|
|
237
|
+
writeFileSync(logFile, '') // each `cslug dev` starts a fresh log
|
|
238
|
+
}
|
|
214
239
|
const supervisor = new Supervisor(specs, {
|
|
215
240
|
cwd: cmd.app.rootDir,
|
|
216
241
|
env,
|
|
217
242
|
bunFlags,
|
|
218
243
|
shutdownTimeout: config.shutdownTimeout,
|
|
219
244
|
log: (l) => cmd.line(l),
|
|
245
|
+
...(logFile ? { logFile } : {}),
|
|
220
246
|
}).start()
|
|
221
247
|
const onSignal = (signal: NodeJS.Signals) => {
|
|
222
248
|
cmd.line(` ${signal}: stopping ${specs.length} process(es)…`)
|
|
@@ -240,7 +266,10 @@ export class StartCommand extends Command {
|
|
|
240
266
|
}
|
|
241
267
|
}
|
|
242
268
|
|
|
243
|
-
/** `cslug dev
|
|
269
|
+
/** Where `cslug dev` writes what its processes print (JSON lines), for `cslug mcp:dev`. */
|
|
270
|
+
export const DEV_LOG = '.cslug/dev.log'
|
|
271
|
+
|
|
272
|
+
/** `cslug dev`: the same processes, restarted by `bun --watch` when a file changes; output also in `.cslug/dev.log`. */
|
|
244
273
|
export class DevCommand extends Command {
|
|
245
274
|
static signature = 'dev'
|
|
246
275
|
static description = 'Development: web, workers and scheduler, restarted when files change'
|
|
@@ -249,6 +278,13 @@ export class DevCommand extends Command {
|
|
|
249
278
|
static args = roleFlags
|
|
250
279
|
|
|
251
280
|
handle(flags: Command.Args<typeof DevCommand>) {
|
|
252
|
-
return supervise(
|
|
281
|
+
return supervise(
|
|
282
|
+
this,
|
|
283
|
+
flags,
|
|
284
|
+
['--watch', '--no-clear-screen'],
|
|
285
|
+
'dev',
|
|
286
|
+
{ CSLUG_DEV: '1' },
|
|
287
|
+
join(this.app.rootDir, DEV_LOG),
|
|
288
|
+
)
|
|
253
289
|
}
|
|
254
290
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { defineConfig } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
export default defineConfig({
|
|
4
|
+
default: 'anthropic', // the key is read from ANTHROPIC_API_KEY
|
|
5
|
+
providers: {
|
|
6
|
+
anthropic: { driver: 'anthropic' },
|
|
7
|
+
// local: { driver: 'openai-compatible', baseUrl: 'http://localhost:11434/v1' },
|
|
8
|
+
},
|
|
9
|
+
models: { fast: 'claude-haiku-5-5', smart: 'claude-opus-5-5' }, // code refers to roles, not model IDs
|
|
10
|
+
// budget: { perDay: { usd: 10 }, alertAt: 0.8 }, // estimated spend per day; AiBudgetError once it is reached
|
|
11
|
+
})
|