@clicksmith/daemon 0.1.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/LICENSE +21 -0
- package/README.md +81 -0
- package/dist/chunk-FY7JGOX6.js +540 -0
- package/dist/chunk-FY7JGOX6.js.map +1 -0
- package/dist/chunk-UVRW6O46.js +542 -0
- package/dist/chunk-UVRW6O46.js.map +1 -0
- package/dist/cli.js +95 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +416 -0
- package/dist/index.js +55 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp.js +10 -0
- package/dist/mcp.js.map +1 -0
- package/package.json +44 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mcp.ts","../src/config.ts","../src/git.ts","../src/paths.ts","../src/logger.ts","../src/store.ts","../src/mcp-tools.ts","../src/version.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';\nimport { resolveDaemonConfig } from './config.js';\nimport { FileStore } from './store.js';\nimport { callTool, readerFromStore, TOOL_DEFINITIONS, type McpReader } from './mcp-tools.js';\nimport { version } from './version.js';\n\n/**\n * Create an MCP {@link Server} exposing ClickSmith's read-only tools over the\n * given reader. The daemon and a standalone `clicksmith mcp` process both use\n * this; state is shared via the on-disk store, so the MCP process never needs\n * to talk to the HTTP daemon directly.\n */\nexport function createMcpServer(reader: McpReader): Server {\n const server = new Server(\n { name: 'clicksmith', version },\n { capabilities: { tools: {} } },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: TOOL_DEFINITIONS.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n })),\n }));\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n const result = await callTool(name, args ?? {}, reader);\n if (!result.ok) {\n return { content: [{ type: 'text', text: result.error }], isError: true };\n }\n return { content: [{ type: 'text', text: result.text }] };\n });\n\n return server;\n}\n\n/** Entry point for `clicksmith mcp`: connect the stdio transport. */\nexport async function startMcp(): Promise<void> {\n const config = await resolveDaemonConfig({ logLevel: 'silent' });\n const store = new FileStore(config.storageRoot);\n await store.init();\n const server = createMcpServer(readerFromStore(store));\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\n// Allow running this file directly as the MCP server.\nif (import.meta.url === `file://${process.argv[1]}`) {\n startMcp().catch((err) => {\n process.stderr.write(`clicksmith mcp failed: ${err instanceof Error ? err.stack : String(err)}\\n`);\n process.exit(1);\n });\n}\n","import { readFile } from 'node:fs/promises';\nimport {\n DEFAULT_AGENTS_CONFIG,\n mergeAgentsConfig,\n parseAgentsConfig,\n type AgentsConfig,\n} from '@clicksmith/agent-config';\nimport { DEFAULT_DAEMON_HOST, DEFAULT_DAEMON_PORT, DEFAULT_SESSION_TTL_MS } from '@clicksmith/core';\nimport { Git } from './git.js';\nimport { resolveStorageRoot, storagePaths } from './paths.js';\nimport { createLogger, type LogLevel, type Logger } from './logger.js';\n\nexport interface DaemonConfigInput {\n cwd?: string;\n host?: string;\n port?: number;\n ttlMs?: number;\n logLevel?: LogLevel;\n /** Override the storage root (mainly for tests). */\n storageRoot?: string;\n /** Override repo detection (mainly for tests). */\n repoRoot?: string | null;\n}\n\nexport interface DaemonConfig {\n host: string;\n port: number;\n ttlMs: number;\n cwd: string;\n repoRoot: string | null;\n storageRoot: string;\n agents: AgentsConfig;\n logger: Logger;\n}\n\n/**\n * Resolve the full daemon configuration: detect the repo, choose a storage\n * root, and layer agent configs (shipped defaults → project `agents.config.json`).\n */\nexport async function resolveDaemonConfig(input: DaemonConfigInput = {}): Promise<DaemonConfig> {\n const cwd = input.cwd ?? process.cwd();\n const repoRoot = input.repoRoot !== undefined ? input.repoRoot : await Git.findRepoRoot(cwd);\n const storageRoot = input.storageRoot ?? resolveStorageRoot(repoRoot);\n const agents = await loadAgentsConfig(storageRoot);\n\n return {\n host: input.host ?? DEFAULT_DAEMON_HOST,\n port: input.port ?? DEFAULT_DAEMON_PORT,\n ttlMs: input.ttlMs ?? DEFAULT_SESSION_TTL_MS,\n cwd,\n repoRoot,\n storageRoot,\n agents,\n logger: createLogger(input.logLevel ?? 'info'),\n };\n}\n\n/** Load `agents.config.json` from the storage root and merge over defaults. */\nexport async function loadAgentsConfig(storageRoot: string): Promise<AgentsConfig> {\n const file = storagePaths(storageRoot).config;\n let raw: string | undefined;\n try {\n raw = await readFile(file, 'utf8');\n } catch {\n return DEFAULT_AGENTS_CONFIG;\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return DEFAULT_AGENTS_CONFIG;\n }\n const parsed = parseAgentsConfig(json);\n if (!parsed.ok) return DEFAULT_AGENTS_CONFIG;\n return mergeAgentsConfig(DEFAULT_AGENTS_CONFIG, parsed.config);\n}\n","import { execa } from 'execa';\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport type { Isolation, SandboxInfo } from '@clicksmith/core';\n\nexport class GitError extends Error {}\n\n/** Thin wrapper around the `git` CLI, scoped to a working directory. */\nexport class Git {\n constructor(private readonly cwd: string) {}\n\n private async run(args: string[], opts: { reject?: boolean } = {}) {\n const result = await execa('git', args, { cwd: this.cwd, reject: false });\n if (opts.reject !== false && result.exitCode !== 0) {\n throw new GitError(`git ${args.join(' ')} failed: ${result.stderr || result.stdout}`);\n }\n return result;\n }\n\n /** Absolute repo root, or `null` if `cwd` is not inside a git repo. */\n static async findRepoRoot(cwd: string): Promise<string | null> {\n const result = await execa('git', ['rev-parse', '--show-toplevel'], { cwd, reject: false });\n return result.exitCode === 0 ? result.stdout.trim() : null;\n }\n\n async headCommit(): Promise<string> {\n return (await this.run(['rev-parse', 'HEAD'])).stdout.trim();\n }\n\n async currentBranch(): Promise<string> {\n return (await this.run(['rev-parse', '--abbrev-ref', 'HEAD'])).stdout.trim();\n }\n\n /**\n * Whether the working tree has uncommitted (tracked or untracked) changes,\n * ignoring any paths under `exclude` prefixes (e.g. ClickSmith's own\n * `.clicksmith/` state directory).\n */\n async isDirty(opts: { exclude?: string[] } = {}): Promise<boolean> {\n const result = await this.run(['status', '--porcelain']);\n const exclude = opts.exclude ?? [];\n return result.stdout\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n .some((line) => {\n const path = line.slice(2).trim();\n const actual = path.includes(' -> ') ? path.split(' -> ')[1]! : path;\n return !exclude.some((prefix) => actual.startsWith(prefix));\n });\n }\n\n /** Whether this git supports worktrees (>= 2.5). */\n async supportsWorktree(): Promise<boolean> {\n const result = await execa('git', ['worktree', 'list'], { cwd: this.cwd, reject: false });\n return result.exitCode === 0;\n }\n\n /**\n * Create a throwaway worktree on a fresh branch for a run. The worktree lives\n * outside the main tree so the agent's edits never touch it.\n */\n async createWorktree(path: string, branch: string, baseRef: string): Promise<void> {\n await this.run(['worktree', 'add', '-b', branch, path, baseRef]);\n }\n\n async removeWorktree(path: string, branch?: string): Promise<void> {\n await this.run(['worktree', 'remove', '--force', path], { reject: false });\n if (branch) await this.run(['branch', '-D', branch], { reject: false });\n }\n\n /** Create + checkout a dedicated branch (the worktree fallback). */\n async createBranch(branch: string, baseRef: string): Promise<void> {\n await this.run(['switch', '-c', branch, baseRef]);\n }\n\n async switchTo(ref: string): Promise<void> {\n await this.run(['switch', ref]);\n }\n\n async deleteBranch(branch: string): Promise<void> {\n await this.run(['branch', '-D', branch], { reject: false });\n }\n\n /**\n * Capture every change in a sandbox (relative to its HEAD) as a single\n * binary-safe patch, including new and deleted files. Returns '' if clean.\n */\n static async captureDiff(sandboxPath: string): Promise<string> {\n await execa('git', ['add', '-A'], { cwd: sandboxPath, reject: false });\n const result = await execa('git', ['diff', '--cached', '--binary'], {\n cwd: sandboxPath,\n reject: false,\n });\n return result.exitCode === 0 ? result.stdout : '';\n }\n\n /**\n * Apply a captured patch onto the main working tree using a 3-way merge,\n * staging the result. Returns the list of conflicted files (empty on success).\n */\n async applyPatch(patch: string): Promise<{ ok: boolean; conflicts: string[] }> {\n if (!patch.trim()) return { ok: true, conflicts: [] };\n const tmp = await mkdtemp(join(tmpdir(), 'clicksmith-patch-'));\n const patchFile = join(tmp, 'run.patch');\n try {\n await writeFile(patchFile, patch.endsWith('\\n') ? patch : `${patch}\\n`, 'utf8');\n const result = await this.run(['apply', '--index', '--3way', patchFile], { reject: false });\n if (result.exitCode === 0) return { ok: true, conflicts: [] };\n const unmerged = (await this.run(['diff', '--name-only', '--diff-filter=U'], { reject: false }))\n .stdout.split(/\\r?\\n/)\n .map((s) => s.trim())\n .filter(Boolean);\n const conflicts = [...new Set([...unmerged, ...parseConflicts(result.stderr)])];\n return { ok: false, conflicts: conflicts.length ? conflicts : ['(unresolved — see git status)'] };\n } finally {\n await rm(tmp, { recursive: true, force: true });\n }\n }\n\n /** Commit the currently staged changes; returns the new commit sha. */\n async commit(message: string): Promise<string> {\n await this.run(['commit', '-m', message, '--no-verify']);\n return this.headCommit();\n }\n\n /** Whether there is anything staged or unstaged to commit. */\n async hasChanges(): Promise<boolean> {\n return this.isDirty();\n }\n\n /**\n * Merge a branch into the current branch with `--no-ff`. On conflict, the\n * merge is aborted and the conflicted files are returned.\n */\n async merge(branch: string, message: string): Promise<{ ok: boolean; conflicts: string[] }> {\n const result = await this.run(['merge', '--no-ff', '-m', message, branch], { reject: false });\n if (result.exitCode === 0) return { ok: true, conflicts: [] };\n const conflicts = (await this.run(['diff', '--name-only', '--diff-filter=U'], { reject: false }))\n .stdout.split(/\\r?\\n/)\n .map((s) => s.trim())\n .filter(Boolean);\n await this.run(['merge', '--abort'], { reject: false });\n return { ok: false, conflicts };\n }\n\n async resetHard(ref: string): Promise<void> {\n await this.run(['reset', '--hard', ref]);\n }\n}\n\nfunction parseConflicts(stderr: string): string[] {\n const files = new Set<string>();\n for (const line of stderr.split(/\\r?\\n/)) {\n // `error: <path>: already exists in working directory`\n const errColon = line.match(/^error:\\s*(.+?):\\s/);\n if (errColon?.[1]) files.add(errColon[1].trim());\n // Quoted paths, e.g. `Applied patch to 'foo.ts' with conflicts.`\n for (const q of line.matchAll(/'([^']+)'/g)) files.add(q[1]!.trim());\n // Porcelain unmerged lines.\n const u = line.match(/^U\\s+(.+)$/);\n if (u?.[1]) files.add(u[1].trim());\n }\n return [...files];\n}\n\n/** Build the sandbox descriptor for a prepared run. */\nexport function describeSandbox(\n isolation: Isolation,\n path: string,\n branch: string | null,\n baseCommit: string,\n): SandboxInfo {\n return { isolation, path, branch, baseCommit };\n}\n","import { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n/** OS-appropriate cache root used when not inside a git repo. */\nexport function osCacheRoot(): string {\n if (process.platform === 'win32') {\n return join(process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'), 'clicksmith', 'Cache');\n }\n if (process.platform === 'darwin') {\n return join(homedir(), 'Library', 'Caches', 'clicksmith');\n }\n return join(process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache'), 'clicksmith');\n}\n\n/**\n * The storage root for sessions/runs: the project's `.clicksmith/` when inside\n * a repo, otherwise the OS cache directory.\n */\nexport function resolveStorageRoot(repoRoot: string | null): string {\n return repoRoot ? join(repoRoot, '.clicksmith') : osCacheRoot();\n}\n\n/** Well-known sub-paths within a storage root. */\nexport function storagePaths(root: string) {\n return {\n root,\n sessions: join(root, 'sessions'),\n runs: join(root, 'runs'),\n screenshots: join(root, 'screenshots'),\n config: join(root, 'agents.config.json'),\n runDir: (runId: string) => join(root, 'runs', runId),\n sandboxDir: (runId: string) => join(root, 'worktrees', runId),\n };\n}\n\nexport type StoragePaths = ReturnType<typeof storagePaths>;\n","/* Minimal leveled logger. Writes to stderr so it never corrupts MCP stdio. */\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';\n\nconst ORDER: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3, silent: 4 };\n\nexport interface Logger {\n debug(msg: string, ...rest: unknown[]): void;\n info(msg: string, ...rest: unknown[]): void;\n warn(msg: string, ...rest: unknown[]): void;\n error(msg: string, ...rest: unknown[]): void;\n}\n\nexport function createLogger(level: LogLevel = 'info', prefix = 'clicksmith'): Logger {\n const min = ORDER[level];\n const emit = (lvl: LogLevel, msg: string, rest: unknown[]) => {\n if (ORDER[lvl] < min) return;\n const line = `[${prefix}] ${lvl.toUpperCase()} ${msg}`;\n // Always stderr — stdout is reserved for MCP's JSON-RPC transport.\n process.stderr.write(rest.length ? `${line} ${rest.map(fmt).join(' ')}\\n` : `${line}\\n`);\n };\n return {\n debug: (m, ...r) => emit('debug', m, r),\n info: (m, ...r) => emit('info', m, r),\n warn: (m, ...r) => emit('warn', m, r),\n error: (m, ...r) => emit('error', m, r),\n };\n}\n\nfunction fmt(v: unknown): string {\n if (typeof v === 'string') return v;\n if (v instanceof Error) return v.stack ?? v.message;\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n","import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport {\n deserializeBundle,\n isExpired,\n serializeBundle,\n type CaptureBundle,\n type Session,\n} from '@clicksmith/core';\nimport { storagePaths, type StoragePaths } from './paths.js';\nimport type { RunRecord } from './types.js';\n\n/**\n * File-backed persistence for sessions, runs, and run artifacts. Everything is\n * stored as JSON/markdown/patch files under the storage root — no database, no\n * network. Writes are atomic (temp file + rename) to survive crashes.\n */\nexport class FileStore {\n readonly paths: StoragePaths;\n\n constructor(root: string) {\n this.paths = storagePaths(root);\n }\n\n async init(): Promise<void> {\n await Promise.all([\n mkdir(this.paths.sessions, { recursive: true }),\n mkdir(this.paths.runs, { recursive: true }),\n mkdir(this.paths.screenshots, { recursive: true }),\n ]);\n }\n\n /* ----------------------------- sessions ------------------------------ */\n\n private sessionFile(id: string): string {\n return join(this.paths.sessions, `${sanitize(id)}.json`);\n }\n\n async saveSession(session: Session): Promise<void> {\n await atomicWrite(this.sessionFile(session.id), JSON.stringify(session, null, 2));\n }\n\n async getSession(id: string): Promise<Session | undefined> {\n return readJson<Session>(this.sessionFile(id));\n }\n\n async listSessions(): Promise<Session[]> {\n const out: Session[] = [];\n for (const file of await listJson(this.paths.sessions)) {\n const s = await readJson<Session>(join(this.paths.sessions, file));\n if (s) out.push(s);\n }\n return out;\n }\n\n async deleteSession(id: string): Promise<void> {\n await rm(this.sessionFile(id), { force: true });\n }\n\n /* -------------------------------- runs -------------------------------- */\n\n private runDir(runId: string): string {\n return this.paths.runDir(runId);\n }\n\n private runFile(runId: string): string {\n return join(this.runDir(runId), 'run.json');\n }\n\n async saveRun(run: RunRecord): Promise<void> {\n await mkdir(this.runDir(run.runId), { recursive: true });\n await atomicWrite(this.runFile(run.runId), JSON.stringify(run, null, 2));\n }\n\n async getRun(runId: string): Promise<RunRecord | undefined> {\n return readJson<RunRecord>(this.runFile(runId));\n }\n\n async listRuns(): Promise<RunRecord[]> {\n let dirs: string[];\n try {\n dirs = await readdir(this.paths.runs);\n } catch {\n return [];\n }\n const out: RunRecord[] = [];\n for (const dir of dirs) {\n const run = await readJson<RunRecord>(join(this.paths.runs, dir, 'run.json'));\n if (run) out.push(run);\n }\n return out.sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n }\n\n /** The most recent run that has a persisted bundle (for `get_latest_request`). */\n async latestRun(): Promise<RunRecord | undefined> {\n const runs = await this.listRuns();\n return runs.at(-1);\n }\n\n /* ----------------------------- artifacts ------------------------------ */\n\n async saveBundle(runId: string, bundle: CaptureBundle): Promise<string> {\n await mkdir(this.runDir(runId), { recursive: true });\n const file = join(this.runDir(runId), 'bundle.json');\n await atomicWrite(file, serializeBundle(bundle));\n return file;\n }\n\n async getBundle(runId: string): Promise<CaptureBundle | undefined> {\n const raw = await readText(join(this.runDir(runId), 'bundle.json'));\n return raw ? deserializeBundle(raw) : undefined;\n }\n\n bundlePath(runId: string): string {\n return join(this.runDir(runId), 'bundle.json');\n }\n\n async writeArtifact(runId: string, name: string, content: string): Promise<string> {\n await mkdir(this.runDir(runId), { recursive: true });\n const file = join(this.runDir(runId), name);\n await atomicWrite(file, content);\n return file;\n }\n\n async readArtifact(runId: string, name: string): Promise<string | undefined> {\n return readText(join(this.runDir(runId), name));\n }\n\n async appendLog(runId: string, chunk: string): Promise<void> {\n const file = join(this.runDir(runId), 'agent.log');\n await mkdir(this.runDir(runId), { recursive: true });\n const existing = (await readText(file)) ?? '';\n await writeFile(file, existing + chunk, 'utf8');\n }\n\n /* ----------------------------- maintenance ----------------------------- */\n\n /** Delete expired, unsubmitted sessions. Returns the ids removed. */\n async cleanupExpired(now: Date = new Date()): Promise<string[]> {\n const removed: string[] = [];\n for (const session of await this.listSessions()) {\n if (isExpired(session, now)) {\n await this.deleteSession(session.id);\n removed.push(session.id);\n }\n }\n return removed;\n }\n}\n\n/* -------------------------------- helpers --------------------------------- */\n\nfunction sanitize(id: string): string {\n return id.replace(/[^a-zA-Z0-9._-]/g, '_');\n}\n\nasync function atomicWrite(file: string, content: string): Promise<void> {\n const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;\n await writeFile(tmp, content, 'utf8');\n const { rename } = await import('node:fs/promises');\n await rename(tmp, file);\n}\n\nasync function readText(file: string): Promise<string | undefined> {\n try {\n return await readFile(file, 'utf8');\n } catch {\n return undefined;\n }\n}\n\nasync function readJson<T>(file: string): Promise<T | undefined> {\n const raw = await readText(file);\n if (raw == null) return undefined;\n try {\n return JSON.parse(raw) as T;\n } catch {\n return undefined;\n }\n}\n\nasync function listJson(dir: string): Promise<string[]> {\n try {\n return (await readdir(dir)).filter((f) => f.endsWith('.json'));\n } catch {\n return [];\n }\n}\n","import type { CaptureBundle, CapturedElement, Session } from '@clicksmith/core';\nimport type { FileStore } from './store.js';\n\n/** Read-only view the MCP tools operate over, backed by daemon persistence. */\nexport interface McpReader {\n getSession(id: string): Promise<Session | undefined>;\n /** The bundle from the most recent submission, if any. */\n latestBundle(): Promise<CaptureBundle | undefined>;\n}\n\n/** Build an {@link McpReader} from a {@link FileStore}. */\nexport function readerFromStore(store: FileStore): McpReader {\n return {\n getSession: (id) => store.getSession(id),\n latestBundle: async () => {\n const run = await store.latestRun();\n return run ? store.getBundle(run.runId) : undefined;\n },\n };\n}\n\n/**\n * Tool definitions exposed over MCP. The **descriptions** deliberately teach the\n * agent the three ClickSmith conventions: `#N` references, locator priority, and\n * the plan/worktree safety contract.\n */\nexport const TOOL_DEFINITIONS = [\n {\n name: 'get_latest_request',\n description:\n 'Get the most recently submitted ClickSmith capture bundle (the latest UI change request). ' +\n 'Returns the prompt, the app route, and the captured elements numbered #1, #2, … . ' +\n 'The user prompt refers to elements by these numbers. Trust each element’s locator in the ' +\n 'order source → attr → behavioral → dom (source = exact file:line). You are running in an ' +\n 'isolated git worktree; in plan mode propose changes — the human clicks Apply to ship them.',\n inputSchema: { type: 'object', properties: {}, additionalProperties: false },\n },\n {\n name: 'get_session',\n description:\n 'Get a ClickSmith capture session by id, including all captured elements (#1, #2, …) and the ' +\n 'app/route context. Use this to resolve which concrete elements the user’s #N references mean.',\n inputSchema: {\n type: 'object',\n properties: { sessionId: { type: 'string', description: 'The session id.' } },\n required: ['sessionId'],\n additionalProperties: false,\n },\n },\n {\n name: 'list_elements',\n description:\n 'List the captured elements for a session (or the latest request if no sessionId is given). ' +\n 'Each element has an id (its #N), a ranked locator (source → attr → behavioral → dom), the ' +\n 'tag/text/role/label, and nearby context for disambiguation.',\n inputSchema: {\n type: 'object',\n properties: { sessionId: { type: 'string', description: 'Optional session id.' } },\n additionalProperties: false,\n },\n },\n {\n name: 'get_element_by_id',\n description:\n 'Resolve a single captured element by its #N id (e.g. 1 for #1), within a session or the ' +\n 'latest request. Returns its locator (prefer source over attr over behavioral over dom), the ' +\n 'element descriptor, and near context.',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'number', description: 'The element’s #N number.' },\n sessionId: { type: 'string', description: 'Optional session id; defaults to latest.' },\n },\n required: ['id'],\n additionalProperties: false,\n },\n },\n] as const;\n\nexport type ToolResult = { ok: true; text: string } | { ok: false; error: string };\n\n/** Execute a read-only tool by name. Pure with respect to the reader. */\nexport async function callTool(\n name: string,\n args: Record<string, unknown>,\n reader: McpReader,\n): Promise<ToolResult> {\n switch (name) {\n case 'get_latest_request': {\n const bundle = await reader.latestBundle();\n if (!bundle) return { ok: false, error: 'No request has been submitted yet.' };\n return { ok: true, text: json(bundle) };\n }\n case 'get_session': {\n const session = await reader.getSession(String(args.sessionId));\n if (!session) return { ok: false, error: `Unknown session: ${String(args.sessionId)}` };\n return { ok: true, text: json(session) };\n }\n case 'list_elements': {\n const elements = await resolveElements(reader, args.sessionId as string | undefined);\n if (!elements) return { ok: false, error: 'No session or latest request found.' };\n return { ok: true, text: json(elements) };\n }\n case 'get_element_by_id': {\n const id = Number(args.id);\n const elements = await resolveElements(reader, args.sessionId as string | undefined);\n if (!elements) return { ok: false, error: 'No session or latest request found.' };\n const element = elements.find((e) => e.id === id);\n if (!element) return { ok: false, error: `No element #${id} in this session.` };\n return { ok: true, text: json(element) };\n }\n default:\n return { ok: false, error: `Unknown tool: ${name}` };\n }\n}\n\nasync function resolveElements(\n reader: McpReader,\n sessionId?: string,\n): Promise<CapturedElement[] | undefined> {\n if (sessionId) return (await reader.getSession(sessionId))?.elements;\n return (await reader.latestBundle())?.elements;\n}\n\nfunction json(value: unknown): string {\n return JSON.stringify(value, null, 2);\n}\n","/** The daemon's semantic version, surfaced via /health and MCP. */\nexport const version = '0.1.0';\n"],"mappings":";AACA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,uBAAuB,8BAA8B;;;ACH9D,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,qBAAqB,qBAAqB,8BAA8B;;;ACPjF,SAAS,aAAa;AACtB,SAAS,SAAS,IAAI,iBAAiB;AACvC,SAAS,cAAc;AACvB,SAA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AAI;AACd,aAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,OAAO,MAAM,CAAC,GAAG,SAAS,KAAK;AAAA,IAC1E;AACA,WAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,OAAO,KAAK,CAAC,EAAE;AAAA,EAC1D,CAAC;AAED,SAAO;AACT;AAGA,eAAsB,WAA0B;AAC9C,QAAM,SAAS,MAAM,oBAAoB,EAAE,UAAU,SAAS,CAAC;AAC/D,QAAM,QAAQ,IAAI,UAAU,OAAO,WAAW;AAC9C,QAAM,MAAM,KAAK;AACjB,QAAM,SAAS,gBAAgB,gBAAgB,KAAK,CAAC;AACrD,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;AAGA,IAAI,YAAY,QAAQ,UAAU,QAAQ,KAAK,CAAC,CAAC,IAAI;AACnD,WAAS,EAAE,MAAM,CAAC,QAAQ;AACxB,YAAQ,OAAO,MAAM,0BAA0B,eAAe,QAAQ,IAAI,QAAQ,OAAO,GAAG,CAAC;AAAA,CAAI;AACjG,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["join","json","readFile","rm","writeFile","join","join","rm","writeFile","readFile"]}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
DaemonService,
|
|
4
|
+
buildServer
|
|
5
|
+
} from "./chunk-FY7JGOX6.js";
|
|
6
|
+
import {
|
|
7
|
+
resolveDaemonConfig,
|
|
8
|
+
startMcp,
|
|
9
|
+
version
|
|
10
|
+
} from "./chunk-UVRW6O46.js";
|
|
11
|
+
|
|
12
|
+
// src/cli.ts
|
|
13
|
+
var HELP = `clicksmith ${version}
|
|
14
|
+
|
|
15
|
+
Usage:
|
|
16
|
+
clicksmith daemon [--port <n>] [--host <h>] [--log <level>]
|
|
17
|
+
clicksmith mcp Run the read-only MCP stdio server
|
|
18
|
+
clicksmith version
|
|
19
|
+
clicksmith help
|
|
20
|
+
|
|
21
|
+
The daemon binds loopback only and stores state under .clicksmith/ (in a repo)
|
|
22
|
+
or your OS cache directory otherwise.
|
|
23
|
+
`;
|
|
24
|
+
async function runDaemon(args) {
|
|
25
|
+
const opts = parseFlags(args);
|
|
26
|
+
const config = await resolveDaemonConfig({
|
|
27
|
+
...opts.port ? { port: Number(opts.port) } : {},
|
|
28
|
+
...opts.host ? { host: opts.host } : {},
|
|
29
|
+
...opts.log ? { logLevel: opts.log } : {}
|
|
30
|
+
});
|
|
31
|
+
const service = new DaemonService({ config });
|
|
32
|
+
await service.init();
|
|
33
|
+
const app = await buildServer(service);
|
|
34
|
+
await app.listen({ host: config.host, port: config.port });
|
|
35
|
+
config.logger.info(`daemon listening on http://${config.host}:${config.port}`);
|
|
36
|
+
config.logger.info(`storage: ${config.storageRoot}`);
|
|
37
|
+
config.logger.info(`repo: ${config.repoRoot ?? "(none \u2014 using OS cache)"}`);
|
|
38
|
+
config.logger.info(`agents: ${config.agents.agents.map((a) => a.id).join(", ")}`);
|
|
39
|
+
const shutdown = async () => {
|
|
40
|
+
config.logger.info("shutting down");
|
|
41
|
+
await app.close();
|
|
42
|
+
process.exit(0);
|
|
43
|
+
};
|
|
44
|
+
process.on("SIGINT", shutdown);
|
|
45
|
+
process.on("SIGTERM", shutdown);
|
|
46
|
+
}
|
|
47
|
+
function parseFlags(args) {
|
|
48
|
+
const out = {};
|
|
49
|
+
for (let i = 0; i < args.length; i++) {
|
|
50
|
+
const arg = args[i];
|
|
51
|
+
if (arg.startsWith("--")) {
|
|
52
|
+
const key = arg.slice(2);
|
|
53
|
+
const next = args[i + 1];
|
|
54
|
+
if (next && !next.startsWith("--")) {
|
|
55
|
+
out[key] = next;
|
|
56
|
+
i++;
|
|
57
|
+
} else {
|
|
58
|
+
out[key] = "true";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
async function main() {
|
|
65
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
66
|
+
switch (command) {
|
|
67
|
+
case "daemon":
|
|
68
|
+
return runDaemon(rest);
|
|
69
|
+
case "mcp":
|
|
70
|
+
return startMcp();
|
|
71
|
+
case "version":
|
|
72
|
+
case "--version":
|
|
73
|
+
case "-v":
|
|
74
|
+
process.stdout.write(`${version}
|
|
75
|
+
`);
|
|
76
|
+
return;
|
|
77
|
+
case void 0:
|
|
78
|
+
case "help":
|
|
79
|
+
case "--help":
|
|
80
|
+
case "-h":
|
|
81
|
+
process.stdout.write(HELP);
|
|
82
|
+
return;
|
|
83
|
+
default:
|
|
84
|
+
process.stderr.write(`Unknown command: ${command}
|
|
85
|
+
|
|
86
|
+
${HELP}`);
|
|
87
|
+
process.exit(1);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
main().catch((err) => {
|
|
91
|
+
process.stderr.write(`clicksmith failed: ${err instanceof Error ? err.stack : String(err)}
|
|
92
|
+
`);
|
|
93
|
+
process.exit(1);
|
|
94
|
+
});
|
|
95
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { resolveDaemonConfig } from './config.js';\nimport { DaemonService } from './daemon-service.js';\nimport { buildServer } from './server.js';\nimport { startMcp } from './mcp.js';\nimport { version } from './version.js';\n\nconst HELP = `clicksmith ${version}\n\nUsage:\n clicksmith daemon [--port <n>] [--host <h>] [--log <level>]\n clicksmith mcp Run the read-only MCP stdio server\n clicksmith version\n clicksmith help\n\nThe daemon binds loopback only and stores state under .clicksmith/ (in a repo)\nor your OS cache directory otherwise.\n`;\n\nasync function runDaemon(args: string[]): Promise<void> {\n const opts = parseFlags(args);\n const config = await resolveDaemonConfig({\n ...(opts.port ? { port: Number(opts.port) } : {}),\n ...(opts.host ? { host: opts.host } : {}),\n ...(opts.log ? { logLevel: opts.log as never } : {}),\n });\n const service = new DaemonService({ config });\n await service.init();\n const app = await buildServer(service);\n\n await app.listen({ host: config.host, port: config.port });\n config.logger.info(`daemon listening on http://${config.host}:${config.port}`);\n config.logger.info(`storage: ${config.storageRoot}`);\n config.logger.info(`repo: ${config.repoRoot ?? '(none — using OS cache)'}`);\n config.logger.info(`agents: ${config.agents.agents.map((a) => a.id).join(', ')}`);\n\n const shutdown = async () => {\n config.logger.info('shutting down');\n await app.close();\n process.exit(0);\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n}\n\nfunction parseFlags(args: string[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (let i = 0; i < args.length; i++) {\n const arg = args[i]!;\n if (arg.startsWith('--')) {\n const key = arg.slice(2);\n const next = args[i + 1];\n if (next && !next.startsWith('--')) {\n out[key] = next;\n i++;\n } else {\n out[key] = 'true';\n }\n }\n }\n return out;\n}\n\nasync function main(): Promise<void> {\n const [command, ...rest] = process.argv.slice(2);\n switch (command) {\n case 'daemon':\n return runDaemon(rest);\n case 'mcp':\n return startMcp();\n case 'version':\n case '--version':\n case '-v':\n process.stdout.write(`${version}\\n`);\n return;\n case undefined:\n case 'help':\n case '--help':\n case '-h':\n process.stdout.write(HELP);\n return;\n default:\n process.stderr.write(`Unknown command: ${command}\\n\\n${HELP}`);\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n process.stderr.write(`clicksmith failed: ${err instanceof Error ? err.stack : String(err)}\\n`);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;AAOA,IAAM,OAAO,cAAc,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYlC,eAAe,UAAU,MAA+B;AACtD,QAAM,OAAO,WAAW,IAAI;AAC5B,QAAM,SAAS,MAAM,oBAAoB;AAAA,IACvC,GAAI,KAAK,OAAO,EAAE,MAAM,OAAO,KAAK,IAAI,EAAE,IAAI,CAAC;AAAA,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AAM,CAAC,SAAS,GAAG,IAAI,IAAI,QAAQ,KAAK,MAAM,CAAC;AAC/C,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,aAAO,UAAU,IAAI;AAAA,IACvB,KAAK;AACH,aAAO,SAAS;AAAA,IAClB,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,cAAQ,OAAO,MAAM,GAAG,OAAO;AAAA,CAAI;AACnC;AAAA,IACF,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,cAAQ,OAAO,MAAM,IAAI;AACzB;AAAA,IACF;AACE,cAAQ,OAAO,MAAM,oBAAoB,OAAO;AAAA;AAAA,EAAO,IAAI,EAAE;AAC7D,cAAQ,KAAK,CAAC;AAAA,EAClB;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,OAAO,MAAM,sBAAsB,eAAe,QAAQ,IAAI,QAAQ,OAAO,GAAG,CAAC;AAAA,CAAI;AAC7F,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":[]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
import { ServerEvent, RunStatus, ExecutionMode, Isolation, SandboxInfo, CaptureBundle, Session, Enrichment, ApplyResponse, CaptureRequest, CaptureResponse, RemoveElementResponse, SubmitRequest, SubmitResponse, HealthResponse } from '@clicksmith/core';
|
|
2
|
+
import { AgentsConfig, CommandSpec } from '@clicksmith/agent-config';
|
|
3
|
+
import { FastifyInstance } from 'fastify';
|
|
4
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
5
|
+
|
|
6
|
+
type Listener = (event: ServerEvent) => void;
|
|
7
|
+
/**
|
|
8
|
+
* A tiny synchronous pub/sub for {@link ServerEvent}s. The Fastify WebSocket
|
|
9
|
+
* layer subscribes to fan events out to connected extension clients; the run
|
|
10
|
+
* manager publishes. Kept dependency-free and ordered (listeners fire in
|
|
11
|
+
* registration order, events in emit order).
|
|
12
|
+
*/
|
|
13
|
+
declare class EventBus {
|
|
14
|
+
private readonly listeners;
|
|
15
|
+
private readonly history;
|
|
16
|
+
private readonly maxHistory;
|
|
17
|
+
constructor(maxHistory?: number);
|
|
18
|
+
subscribe(listener: Listener): () => void;
|
|
19
|
+
emit(event: ServerEvent): void;
|
|
20
|
+
/** Replay buffered events, optionally filtered to a run id. */
|
|
21
|
+
replay(runId?: string): ServerEvent[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** OS-appropriate cache root used when not inside a git repo. */
|
|
25
|
+
declare function osCacheRoot(): string;
|
|
26
|
+
/**
|
|
27
|
+
* The storage root for sessions/runs: the project's `.clicksmith/` when inside
|
|
28
|
+
* a repo, otherwise the OS cache directory.
|
|
29
|
+
*/
|
|
30
|
+
declare function resolveStorageRoot(repoRoot: string | null): string;
|
|
31
|
+
/** Well-known sub-paths within a storage root. */
|
|
32
|
+
declare function storagePaths(root: string): {
|
|
33
|
+
root: string;
|
|
34
|
+
sessions: string;
|
|
35
|
+
runs: string;
|
|
36
|
+
screenshots: string;
|
|
37
|
+
config: string;
|
|
38
|
+
runDir: (runId: string) => string;
|
|
39
|
+
sandboxDir: (runId: string) => string;
|
|
40
|
+
};
|
|
41
|
+
type StoragePaths = ReturnType<typeof storagePaths>;
|
|
42
|
+
|
|
43
|
+
/** Metadata enabling a run to be reverted after apply. */
|
|
44
|
+
interface RevertMeta {
|
|
45
|
+
/** The repo HEAD before applying this run. */
|
|
46
|
+
previousHead: string;
|
|
47
|
+
/** The commit created by applying, if any. */
|
|
48
|
+
appliedCommit?: string;
|
|
49
|
+
/** Human-readable revert instructions. */
|
|
50
|
+
instructions: string;
|
|
51
|
+
}
|
|
52
|
+
/** A persisted run record (`runs/<runId>/run.json`). */
|
|
53
|
+
interface RunRecord {
|
|
54
|
+
runId: string;
|
|
55
|
+
sessionId: string;
|
|
56
|
+
agentId: string;
|
|
57
|
+
status: RunStatus;
|
|
58
|
+
createdAt: string;
|
|
59
|
+
updatedAt: string;
|
|
60
|
+
mode: ExecutionMode;
|
|
61
|
+
isolation: Isolation;
|
|
62
|
+
prompt: string;
|
|
63
|
+
repoRoot: string | null;
|
|
64
|
+
baseCommit: string | null;
|
|
65
|
+
/** The branch HEAD was on at prepare time (for branch-isolation apply). */
|
|
66
|
+
baseBranch: string | null;
|
|
67
|
+
sandbox: SandboxInfo | null;
|
|
68
|
+
revert: RevertMeta | null;
|
|
69
|
+
exitCode?: number;
|
|
70
|
+
error?: string;
|
|
71
|
+
hasPlan?: boolean;
|
|
72
|
+
hasDiff?: boolean;
|
|
73
|
+
applied?: {
|
|
74
|
+
commit?: string;
|
|
75
|
+
at: string;
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
interface RunArtifacts {
|
|
79
|
+
bundle: CaptureBundle;
|
|
80
|
+
plan?: string;
|
|
81
|
+
diff?: string;
|
|
82
|
+
log?: string;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* File-backed persistence for sessions, runs, and run artifacts. Everything is
|
|
87
|
+
* stored as JSON/markdown/patch files under the storage root — no database, no
|
|
88
|
+
* network. Writes are atomic (temp file + rename) to survive crashes.
|
|
89
|
+
*/
|
|
90
|
+
declare class FileStore {
|
|
91
|
+
readonly paths: StoragePaths;
|
|
92
|
+
constructor(root: string);
|
|
93
|
+
init(): Promise<void>;
|
|
94
|
+
private sessionFile;
|
|
95
|
+
saveSession(session: Session): Promise<void>;
|
|
96
|
+
getSession(id: string): Promise<Session | undefined>;
|
|
97
|
+
listSessions(): Promise<Session[]>;
|
|
98
|
+
deleteSession(id: string): Promise<void>;
|
|
99
|
+
private runDir;
|
|
100
|
+
private runFile;
|
|
101
|
+
saveRun(run: RunRecord): Promise<void>;
|
|
102
|
+
getRun(runId: string): Promise<RunRecord | undefined>;
|
|
103
|
+
listRuns(): Promise<RunRecord[]>;
|
|
104
|
+
/** The most recent run that has a persisted bundle (for `get_latest_request`). */
|
|
105
|
+
latestRun(): Promise<RunRecord | undefined>;
|
|
106
|
+
saveBundle(runId: string, bundle: CaptureBundle): Promise<string>;
|
|
107
|
+
getBundle(runId: string): Promise<CaptureBundle | undefined>;
|
|
108
|
+
bundlePath(runId: string): string;
|
|
109
|
+
writeArtifact(runId: string, name: string, content: string): Promise<string>;
|
|
110
|
+
readArtifact(runId: string, name: string): Promise<string | undefined>;
|
|
111
|
+
appendLog(runId: string, chunk: string): Promise<void>;
|
|
112
|
+
/** Delete expired, unsubmitted sessions. Returns the ids removed. */
|
|
113
|
+
cleanupExpired(now?: Date): Promise<string[]>;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Pluggable, best-effort enrichment. When configured (e.g. backed by the
|
|
118
|
+
* code-review-graph MCP), it resolves source locators to attach review context
|
|
119
|
+
* and impact radius per element. Failures must be **non-blocking**: the run
|
|
120
|
+
* manager catches errors and records them as warnings on the bundle.
|
|
121
|
+
*/
|
|
122
|
+
interface EnrichmentProvider {
|
|
123
|
+
id: string;
|
|
124
|
+
enrich(bundle: CaptureBundle): Promise<Enrichment | null>;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Apply an enrichment provider to a bundle, swallowing failures into warnings.
|
|
128
|
+
* Returns a (possibly) new bundle; never throws.
|
|
129
|
+
*/
|
|
130
|
+
declare function enrichBundle(bundle: CaptureBundle, provider: EnrichmentProvider | undefined): Promise<CaptureBundle>;
|
|
131
|
+
|
|
132
|
+
type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
|
|
133
|
+
interface Logger {
|
|
134
|
+
debug(msg: string, ...rest: unknown[]): void;
|
|
135
|
+
info(msg: string, ...rest: unknown[]): void;
|
|
136
|
+
warn(msg: string, ...rest: unknown[]): void;
|
|
137
|
+
error(msg: string, ...rest: unknown[]): void;
|
|
138
|
+
}
|
|
139
|
+
declare function createLogger(level?: LogLevel, prefix?: string): Logger;
|
|
140
|
+
|
|
141
|
+
interface DaemonConfigInput {
|
|
142
|
+
cwd?: string;
|
|
143
|
+
host?: string;
|
|
144
|
+
port?: number;
|
|
145
|
+
ttlMs?: number;
|
|
146
|
+
logLevel?: LogLevel;
|
|
147
|
+
/** Override the storage root (mainly for tests). */
|
|
148
|
+
storageRoot?: string;
|
|
149
|
+
/** Override repo detection (mainly for tests). */
|
|
150
|
+
repoRoot?: string | null;
|
|
151
|
+
}
|
|
152
|
+
interface DaemonConfig {
|
|
153
|
+
host: string;
|
|
154
|
+
port: number;
|
|
155
|
+
ttlMs: number;
|
|
156
|
+
cwd: string;
|
|
157
|
+
repoRoot: string | null;
|
|
158
|
+
storageRoot: string;
|
|
159
|
+
agents: AgentsConfig;
|
|
160
|
+
logger: Logger;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Resolve the full daemon configuration: detect the repo, choose a storage
|
|
164
|
+
* root, and layer agent configs (shipped defaults → project `agents.config.json`).
|
|
165
|
+
*/
|
|
166
|
+
declare function resolveDaemonConfig(input?: DaemonConfigInput): Promise<DaemonConfig>;
|
|
167
|
+
/** Load `agents.config.json` from the storage root and merge over defaults. */
|
|
168
|
+
declare function loadAgentsConfig(storageRoot: string): Promise<AgentsConfig>;
|
|
169
|
+
|
|
170
|
+
/** Raised when a non-inplace run is requested against a dirty working tree. */
|
|
171
|
+
declare class RefusalError extends Error {
|
|
172
|
+
readonly code = "DIRTY_TREE";
|
|
173
|
+
}
|
|
174
|
+
interface RunManagerDeps {
|
|
175
|
+
store: FileStore;
|
|
176
|
+
config: DaemonConfig;
|
|
177
|
+
bus: EventBus;
|
|
178
|
+
logger: Logger;
|
|
179
|
+
enrichment?: EnrichmentProvider;
|
|
180
|
+
/** Override PATH probing (tests inject a fake). */
|
|
181
|
+
binExists?: (bin: string) => Promise<boolean>;
|
|
182
|
+
}
|
|
183
|
+
declare class RunManager {
|
|
184
|
+
private readonly deps;
|
|
185
|
+
constructor(deps: RunManagerDeps);
|
|
186
|
+
/**
|
|
187
|
+
* Prepare a sandbox and start an agent run. The sandbox is prepared
|
|
188
|
+
* synchronously so a dirty-tree refusal surfaces as an error to the caller;
|
|
189
|
+
* the agent itself runs in the background, emitting WebSocket events.
|
|
190
|
+
*/
|
|
191
|
+
createRun(input: CaptureBundle): Promise<{
|
|
192
|
+
run: RunRecord;
|
|
193
|
+
}>;
|
|
194
|
+
private prepareSandbox;
|
|
195
|
+
private execute;
|
|
196
|
+
private fail;
|
|
197
|
+
/**
|
|
198
|
+
* Merge a finished run's sandbox changes back into the working tree. Reports
|
|
199
|
+
* conflicts, commits on success, records revert metadata, and cleans up the
|
|
200
|
+
* sandbox.
|
|
201
|
+
*/
|
|
202
|
+
apply(runId: string): Promise<ApplyResponse>;
|
|
203
|
+
private applyConflict;
|
|
204
|
+
private cleanupSandbox;
|
|
205
|
+
/**
|
|
206
|
+
* Resolve the instruction file passed to the agent. Prefer the project's
|
|
207
|
+
* rendered file if it exists; otherwise write a run-local one from the shared
|
|
208
|
+
* template so every agent always has instructions.
|
|
209
|
+
*/
|
|
210
|
+
private resolveInstructionFile;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
interface DaemonServiceOptions {
|
|
214
|
+
config: DaemonConfig;
|
|
215
|
+
enrichment?: EnrichmentProvider;
|
|
216
|
+
binExists?: RunManagerDeps['binExists'];
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The framework-agnostic core of the daemon. The HTTP/WS server and tests both
|
|
220
|
+
* drive this; it owns sessions, runs, the event bus, and persistence.
|
|
221
|
+
*/
|
|
222
|
+
declare class DaemonService {
|
|
223
|
+
readonly config: DaemonConfig;
|
|
224
|
+
readonly store: FileStore;
|
|
225
|
+
readonly bus: EventBus;
|
|
226
|
+
readonly runs: RunManager;
|
|
227
|
+
constructor(opts: DaemonServiceOptions);
|
|
228
|
+
init(): Promise<void>;
|
|
229
|
+
/** Create or append to the active session for an app/route. */
|
|
230
|
+
capture(req: CaptureRequest): Promise<CaptureResponse>;
|
|
231
|
+
removeElement(sessionId: string, elementId: number): Promise<RemoveElementResponse>;
|
|
232
|
+
getSession(id: string): Promise<Session | undefined>;
|
|
233
|
+
/** Finalize a session into a bundle and start a run. */
|
|
234
|
+
submit(req: SubmitRequest): Promise<SubmitResponse>;
|
|
235
|
+
apply(runId: string): Promise<ApplyResponse>;
|
|
236
|
+
health(): Promise<HealthResponse>;
|
|
237
|
+
}
|
|
238
|
+
declare class NotFoundError extends Error {
|
|
239
|
+
readonly code = "NOT_FOUND";
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Build the Fastify app exposing ClickSmith's HTTP + WebSocket surface on top
|
|
244
|
+
* of a {@link DaemonService}. Binds loopback only; CORS is opened for localhost
|
|
245
|
+
* so the browser extension can talk to it.
|
|
246
|
+
*/
|
|
247
|
+
declare function buildServer(service: DaemonService): Promise<FastifyInstance>;
|
|
248
|
+
|
|
249
|
+
declare class GitError extends Error {
|
|
250
|
+
}
|
|
251
|
+
/** Thin wrapper around the `git` CLI, scoped to a working directory. */
|
|
252
|
+
declare class Git {
|
|
253
|
+
private readonly cwd;
|
|
254
|
+
constructor(cwd: string);
|
|
255
|
+
private run;
|
|
256
|
+
/** Absolute repo root, or `null` if `cwd` is not inside a git repo. */
|
|
257
|
+
static findRepoRoot(cwd: string): Promise<string | null>;
|
|
258
|
+
headCommit(): Promise<string>;
|
|
259
|
+
currentBranch(): Promise<string>;
|
|
260
|
+
/**
|
|
261
|
+
* Whether the working tree has uncommitted (tracked or untracked) changes,
|
|
262
|
+
* ignoring any paths under `exclude` prefixes (e.g. ClickSmith's own
|
|
263
|
+
* `.clicksmith/` state directory).
|
|
264
|
+
*/
|
|
265
|
+
isDirty(opts?: {
|
|
266
|
+
exclude?: string[];
|
|
267
|
+
}): Promise<boolean>;
|
|
268
|
+
/** Whether this git supports worktrees (>= 2.5). */
|
|
269
|
+
supportsWorktree(): Promise<boolean>;
|
|
270
|
+
/**
|
|
271
|
+
* Create a throwaway worktree on a fresh branch for a run. The worktree lives
|
|
272
|
+
* outside the main tree so the agent's edits never touch it.
|
|
273
|
+
*/
|
|
274
|
+
createWorktree(path: string, branch: string, baseRef: string): Promise<void>;
|
|
275
|
+
removeWorktree(path: string, branch?: string): Promise<void>;
|
|
276
|
+
/** Create + checkout a dedicated branch (the worktree fallback). */
|
|
277
|
+
createBranch(branch: string, baseRef: string): Promise<void>;
|
|
278
|
+
switchTo(ref: string): Promise<void>;
|
|
279
|
+
deleteBranch(branch: string): Promise<void>;
|
|
280
|
+
/**
|
|
281
|
+
* Capture every change in a sandbox (relative to its HEAD) as a single
|
|
282
|
+
* binary-safe patch, including new and deleted files. Returns '' if clean.
|
|
283
|
+
*/
|
|
284
|
+
static captureDiff(sandboxPath: string): Promise<string>;
|
|
285
|
+
/**
|
|
286
|
+
* Apply a captured patch onto the main working tree using a 3-way merge,
|
|
287
|
+
* staging the result. Returns the list of conflicted files (empty on success).
|
|
288
|
+
*/
|
|
289
|
+
applyPatch(patch: string): Promise<{
|
|
290
|
+
ok: boolean;
|
|
291
|
+
conflicts: string[];
|
|
292
|
+
}>;
|
|
293
|
+
/** Commit the currently staged changes; returns the new commit sha. */
|
|
294
|
+
commit(message: string): Promise<string>;
|
|
295
|
+
/** Whether there is anything staged or unstaged to commit. */
|
|
296
|
+
hasChanges(): Promise<boolean>;
|
|
297
|
+
/**
|
|
298
|
+
* Merge a branch into the current branch with `--no-ff`. On conflict, the
|
|
299
|
+
* merge is aborted and the conflicted files are returned.
|
|
300
|
+
*/
|
|
301
|
+
merge(branch: string, message: string): Promise<{
|
|
302
|
+
ok: boolean;
|
|
303
|
+
conflicts: string[];
|
|
304
|
+
}>;
|
|
305
|
+
resetHard(ref: string): Promise<void>;
|
|
306
|
+
}
|
|
307
|
+
/** Build the sandbox descriptor for a prepared run. */
|
|
308
|
+
declare function describeSandbox(isolation: Isolation, path: string, branch: string | null, baseCommit: string): SandboxInfo;
|
|
309
|
+
|
|
310
|
+
interface LaunchHandlers {
|
|
311
|
+
onLog: (stream: 'stdout' | 'stderr', chunk: string) => void;
|
|
312
|
+
signal?: AbortSignal;
|
|
313
|
+
}
|
|
314
|
+
interface LaunchResult {
|
|
315
|
+
exitCode: number;
|
|
316
|
+
stdout: string;
|
|
317
|
+
canceled: boolean;
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Spawn a resolved {@link CommandSpec} with execa, streaming stdout/stderr to
|
|
321
|
+
* the caller as they arrive. Never rejects on non-zero exit — the run manager
|
|
322
|
+
* decides what a non-zero code means.
|
|
323
|
+
*/
|
|
324
|
+
declare function launchAgent(spec: CommandSpec, handlers: LaunchHandlers): Promise<LaunchResult>;
|
|
325
|
+
|
|
326
|
+
/** Read-only view the MCP tools operate over, backed by daemon persistence. */
|
|
327
|
+
interface McpReader {
|
|
328
|
+
getSession(id: string): Promise<Session | undefined>;
|
|
329
|
+
/** The bundle from the most recent submission, if any. */
|
|
330
|
+
latestBundle(): Promise<CaptureBundle | undefined>;
|
|
331
|
+
}
|
|
332
|
+
/** Build an {@link McpReader} from a {@link FileStore}. */
|
|
333
|
+
declare function readerFromStore(store: FileStore): McpReader;
|
|
334
|
+
/**
|
|
335
|
+
* Tool definitions exposed over MCP. The **descriptions** deliberately teach the
|
|
336
|
+
* agent the three ClickSmith conventions: `#N` references, locator priority, and
|
|
337
|
+
* the plan/worktree safety contract.
|
|
338
|
+
*/
|
|
339
|
+
declare const TOOL_DEFINITIONS: readonly [{
|
|
340
|
+
readonly name: "get_latest_request";
|
|
341
|
+
readonly description: string;
|
|
342
|
+
readonly inputSchema: {
|
|
343
|
+
readonly type: "object";
|
|
344
|
+
readonly properties: {};
|
|
345
|
+
readonly additionalProperties: false;
|
|
346
|
+
};
|
|
347
|
+
}, {
|
|
348
|
+
readonly name: "get_session";
|
|
349
|
+
readonly description: string;
|
|
350
|
+
readonly inputSchema: {
|
|
351
|
+
readonly type: "object";
|
|
352
|
+
readonly properties: {
|
|
353
|
+
readonly sessionId: {
|
|
354
|
+
readonly type: "string";
|
|
355
|
+
readonly description: "The session id.";
|
|
356
|
+
};
|
|
357
|
+
};
|
|
358
|
+
readonly required: readonly ["sessionId"];
|
|
359
|
+
readonly additionalProperties: false;
|
|
360
|
+
};
|
|
361
|
+
}, {
|
|
362
|
+
readonly name: "list_elements";
|
|
363
|
+
readonly description: string;
|
|
364
|
+
readonly inputSchema: {
|
|
365
|
+
readonly type: "object";
|
|
366
|
+
readonly properties: {
|
|
367
|
+
readonly sessionId: {
|
|
368
|
+
readonly type: "string";
|
|
369
|
+
readonly description: "Optional session id.";
|
|
370
|
+
};
|
|
371
|
+
};
|
|
372
|
+
readonly additionalProperties: false;
|
|
373
|
+
};
|
|
374
|
+
}, {
|
|
375
|
+
readonly name: "get_element_by_id";
|
|
376
|
+
readonly description: string;
|
|
377
|
+
readonly inputSchema: {
|
|
378
|
+
readonly type: "object";
|
|
379
|
+
readonly properties: {
|
|
380
|
+
readonly id: {
|
|
381
|
+
readonly type: "number";
|
|
382
|
+
readonly description: "The element’s #N number.";
|
|
383
|
+
};
|
|
384
|
+
readonly sessionId: {
|
|
385
|
+
readonly type: "string";
|
|
386
|
+
readonly description: "Optional session id; defaults to latest.";
|
|
387
|
+
};
|
|
388
|
+
};
|
|
389
|
+
readonly required: readonly ["id"];
|
|
390
|
+
readonly additionalProperties: false;
|
|
391
|
+
};
|
|
392
|
+
}];
|
|
393
|
+
type ToolResult = {
|
|
394
|
+
ok: true;
|
|
395
|
+
text: string;
|
|
396
|
+
} | {
|
|
397
|
+
ok: false;
|
|
398
|
+
error: string;
|
|
399
|
+
};
|
|
400
|
+
/** Execute a read-only tool by name. Pure with respect to the reader. */
|
|
401
|
+
declare function callTool(name: string, args: Record<string, unknown>, reader: McpReader): Promise<ToolResult>;
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Create an MCP {@link Server} exposing ClickSmith's read-only tools over the
|
|
405
|
+
* given reader. The daemon and a standalone `clicksmith mcp` process both use
|
|
406
|
+
* this; state is shared via the on-disk store, so the MCP process never needs
|
|
407
|
+
* to talk to the HTTP daemon directly.
|
|
408
|
+
*/
|
|
409
|
+
declare function createMcpServer(reader: McpReader): Server;
|
|
410
|
+
/** Entry point for `clicksmith mcp`: connect the stdio transport. */
|
|
411
|
+
declare function startMcp(): Promise<void>;
|
|
412
|
+
|
|
413
|
+
/** The daemon's semantic version, surfaced via /health and MCP. */
|
|
414
|
+
declare const version = "0.1.0";
|
|
415
|
+
|
|
416
|
+
export { type DaemonConfig, type DaemonConfigInput, DaemonService, type DaemonServiceOptions, type EnrichmentProvider, EventBus, FileStore, Git, GitError, type LaunchHandlers, type LaunchResult, type LogLevel, type Logger, type McpReader, NotFoundError, RefusalError, type RevertMeta, type RunArtifacts, RunManager, type RunManagerDeps, type RunRecord, TOOL_DEFINITIONS, type ToolResult, buildServer, callTool, createLogger, createMcpServer, describeSandbox, enrichBundle, launchAgent, loadAgentsConfig, osCacheRoot, readerFromStore, resolveDaemonConfig, resolveStorageRoot, startMcp, storagePaths, version };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DaemonService,
|
|
3
|
+
EventBus,
|
|
4
|
+
NotFoundError,
|
|
5
|
+
RefusalError,
|
|
6
|
+
RunManager,
|
|
7
|
+
buildServer,
|
|
8
|
+
enrichBundle,
|
|
9
|
+
launchAgent
|
|
10
|
+
} from "./chunk-FY7JGOX6.js";
|
|
11
|
+
import {
|
|
12
|
+
FileStore,
|
|
13
|
+
Git,
|
|
14
|
+
GitError,
|
|
15
|
+
TOOL_DEFINITIONS,
|
|
16
|
+
callTool,
|
|
17
|
+
createLogger,
|
|
18
|
+
createMcpServer,
|
|
19
|
+
describeSandbox,
|
|
20
|
+
loadAgentsConfig,
|
|
21
|
+
osCacheRoot,
|
|
22
|
+
readerFromStore,
|
|
23
|
+
resolveDaemonConfig,
|
|
24
|
+
resolveStorageRoot,
|
|
25
|
+
startMcp,
|
|
26
|
+
storagePaths,
|
|
27
|
+
version
|
|
28
|
+
} from "./chunk-UVRW6O46.js";
|
|
29
|
+
export {
|
|
30
|
+
DaemonService,
|
|
31
|
+
EventBus,
|
|
32
|
+
FileStore,
|
|
33
|
+
Git,
|
|
34
|
+
GitError,
|
|
35
|
+
NotFoundError,
|
|
36
|
+
RefusalError,
|
|
37
|
+
RunManager,
|
|
38
|
+
TOOL_DEFINITIONS,
|
|
39
|
+
buildServer,
|
|
40
|
+
callTool,
|
|
41
|
+
createLogger,
|
|
42
|
+
createMcpServer,
|
|
43
|
+
describeSandbox,
|
|
44
|
+
enrichBundle,
|
|
45
|
+
launchAgent,
|
|
46
|
+
loadAgentsConfig,
|
|
47
|
+
osCacheRoot,
|
|
48
|
+
readerFromStore,
|
|
49
|
+
resolveDaemonConfig,
|
|
50
|
+
resolveStorageRoot,
|
|
51
|
+
startMcp,
|
|
52
|
+
storagePaths,
|
|
53
|
+
version
|
|
54
|
+
};
|
|
55
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|