@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/events.ts","../src/launcher.ts","../src/enrichment.ts","../src/run-manager.ts","../src/daemon-service.ts","../src/server.ts"],"sourcesContent":["import type { ServerEvent } from '@clicksmith/core';\n\ntype Listener = (event: ServerEvent) => void;\n\n/**\n * A tiny synchronous pub/sub for {@link ServerEvent}s. The Fastify WebSocket\n * layer subscribes to fan events out to connected extension clients; the run\n * manager publishes. Kept dependency-free and ordered (listeners fire in\n * registration order, events in emit order).\n */\nexport class EventBus {\n private readonly listeners = new Set<Listener>();\n private readonly history: ServerEvent[] = [];\n private readonly maxHistory: number;\n\n constructor(maxHistory = 500) {\n this.maxHistory = maxHistory;\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n emit(event: ServerEvent): void {\n this.history.push(event);\n if (this.history.length > this.maxHistory) this.history.shift();\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch {\n // A misbehaving listener must never break the emit loop.\n }\n }\n }\n\n /** Replay buffered events, optionally filtered to a run id. */\n replay(runId?: string): ServerEvent[] {\n if (!runId) return [...this.history];\n return this.history.filter((e) => 'runId' in e && e.runId === runId);\n }\n}\n","import { execa } from 'execa';\nimport type { CommandSpec } from '@clicksmith/agent-config';\n\nexport interface LaunchHandlers {\n onLog: (stream: 'stdout' | 'stderr', chunk: string) => void;\n signal?: AbortSignal;\n}\n\nexport interface LaunchResult {\n exitCode: number;\n stdout: string;\n canceled: boolean;\n}\n\n/**\n * Spawn a resolved {@link CommandSpec} with execa, streaming stdout/stderr to\n * the caller as they arrive. Never rejects on non-zero exit — the run manager\n * decides what a non-zero code means.\n */\nexport async function launchAgent(spec: CommandSpec, handlers: LaunchHandlers): Promise<LaunchResult> {\n const subprocess = execa(spec.command, spec.args, {\n cwd: spec.cwd,\n env: { ...process.env, ...spec.env },\n reject: false,\n all: false,\n cancelSignal: handlers.signal,\n });\n\n let stdout = '';\n subprocess.stdout?.on('data', (data: Buffer) => {\n const chunk = data.toString();\n stdout += chunk;\n handlers.onLog('stdout', chunk);\n });\n subprocess.stderr?.on('data', (data: Buffer) => {\n handlers.onLog('stderr', data.toString());\n });\n\n const result = await subprocess;\n return {\n exitCode: result.exitCode ?? (result.isCanceled ? 130 : 0),\n stdout,\n canceled: Boolean(result.isCanceled),\n };\n}\n","import type { CaptureBundle, Enrichment } from '@clicksmith/core';\n\n/**\n * Pluggable, best-effort enrichment. When configured (e.g. backed by the\n * code-review-graph MCP), it resolves source locators to attach review context\n * and impact radius per element. Failures must be **non-blocking**: the run\n * manager catches errors and records them as warnings on the bundle.\n */\nexport interface EnrichmentProvider {\n id: string;\n enrich(bundle: CaptureBundle): Promise<Enrichment | null>;\n}\n\n/**\n * Apply an enrichment provider to a bundle, swallowing failures into warnings.\n * Returns a (possibly) new bundle; never throws.\n */\nexport async function enrichBundle(\n bundle: CaptureBundle,\n provider: EnrichmentProvider | undefined,\n): Promise<CaptureBundle> {\n if (!provider) return bundle;\n try {\n const enrichment = await provider.enrich(bundle);\n if (!enrichment) return bundle;\n return { ...bundle, enrichment };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return {\n ...bundle,\n enrichment: {\n source: 'code-review-graph',\n perElement: bundle.enrichment?.perElement ?? [],\n warnings: [...(bundle.enrichment?.warnings ?? []), `enrichment failed: ${message}`],\n },\n };\n }\n}\n","import { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport {\n configToAdapter,\n defaultBinExists,\n renderInstructionBody,\n resolveAgent,\n type AgentConfig,\n type AgentLaunchContext,\n} from '@clicksmith/agent-config';\nimport {\n newRunId,\n type ApplyResponse,\n type CaptureBundle,\n type SandboxInfo,\n} from '@clicksmith/core';\nimport { describeSandbox, Git } from './git.js';\nimport { launchAgent } from './launcher.js';\nimport { enrichBundle, type EnrichmentProvider } from './enrichment.js';\nimport type { EventBus } from './events.js';\nimport type { FileStore } from './store.js';\nimport type { Logger } from './logger.js';\nimport type { DaemonConfig } from './config.js';\nimport type { RunRecord } from './types.js';\n\n/** Raised when a non-inplace run is requested against a dirty working tree. */\nexport class RefusalError extends Error {\n readonly code = 'DIRTY_TREE';\n}\n\nexport interface RunManagerDeps {\n store: FileStore;\n config: DaemonConfig;\n bus: EventBus;\n logger: Logger;\n enrichment?: EnrichmentProvider;\n /** Override PATH probing (tests inject a fake). */\n binExists?: (bin: string) => Promise<boolean>;\n}\n\nconst COMMIT_PREFIX = 'ClickSmith';\n\nexport class RunManager {\n constructor(private readonly deps: RunManagerDeps) {}\n\n /**\n * Prepare a sandbox and start an agent run. The sandbox is prepared\n * synchronously so a dirty-tree refusal surfaces as an error to the caller;\n * the agent itself runs in the background, emitting WebSocket events.\n */\n async createRun(input: CaptureBundle): Promise<{ run: RunRecord }> {\n const { store, config, bus, logger } = this.deps;\n const agentConfig = resolveAgent(config.agents, input.execution.agentId);\n if (!agentConfig) {\n throw new RefusalError(`No agent configured (requested: ${input.execution.agentId ?? 'default'}).`);\n }\n\n const runId = newRunId();\n const now = new Date();\n const repoRoot = config.repoRoot;\n const isolation = repoRoot ? input.execution.isolation : 'inplace';\n\n let sandbox: SandboxInfo | null = null;\n let baseCommit: string | null = null;\n let baseBranch: string | null = null;\n\n if (repoRoot) {\n const git = new Git(repoRoot);\n baseCommit = await git.headCommit();\n baseBranch = await safe(() => git.currentBranch());\n const baseRef = input.execution.baseRef ?? baseCommit;\n\n if (isolation !== 'inplace' && (await git.isDirty({ exclude: ['.clicksmith/', '.clicksmith'] }))) {\n throw new RefusalError(\n `Refusing to run in ${isolation} isolation: the working tree has uncommitted changes. ` +\n `Commit or stash them, or use inplace isolation explicitly.`,\n );\n }\n sandbox = await this.prepareSandbox(git, runId, isolation, baseRef, repoRoot, baseCommit, logger);\n }\n\n const enriched = await enrichBundle(input, this.deps.enrichment);\n await store.saveBundle(runId, enriched);\n\n const run: RunRecord = {\n runId,\n sessionId: enriched.sessionId,\n agentId: agentConfig.id,\n status: 'running',\n createdAt: now.toISOString(),\n updatedAt: now.toISOString(),\n mode: enriched.execution.mode,\n isolation,\n prompt: enriched.prompt,\n repoRoot,\n baseCommit,\n baseBranch,\n sandbox,\n revert: null,\n };\n await store.saveRun(run);\n\n bus.emit({ type: 'agent-started', runId, sessionId: run.sessionId, agentId: run.agentId, sandbox });\n\n // Fire-and-forget the actual agent execution.\n void this.execute(run, enriched, agentConfig).catch((err) => {\n logger.error(`run ${runId} crashed`, err);\n });\n\n return { run };\n }\n\n private async prepareSandbox(\n git: Git,\n runId: string,\n isolation: SandboxInfo['isolation'],\n baseRef: string,\n repoRoot: string,\n baseCommit: string,\n logger: Logger,\n ): Promise<SandboxInfo> {\n const branch = `clicksmith/${runId}`;\n if (isolation === 'inplace') {\n return describeSandbox('inplace', repoRoot, null, baseCommit);\n }\n if (isolation === 'worktree') {\n if (await git.supportsWorktree()) {\n const path = this.deps.store.paths.sandboxDir(runId);\n await mkdir(join(path, '..'), { recursive: true });\n await git.createWorktree(path, branch, baseRef);\n return describeSandbox('worktree', path, branch, baseCommit);\n }\n logger.warn('git worktrees unavailable; falling back to a dedicated branch');\n }\n // branch isolation (explicit or worktree fallback)\n await git.createBranch(branch, baseRef);\n return describeSandbox('branch', repoRoot, branch, baseCommit);\n }\n\n private async execute(run: RunRecord, bundle: CaptureBundle, agentConfig: AgentConfig): Promise<void> {\n const { store, config, bus, logger } = this.deps;\n const sandboxPath = run.sandbox?.path ?? config.cwd;\n\n const instructionFile = await this.resolveInstructionFile(run, agentConfig);\n const ctx: AgentLaunchContext = {\n bundlePath: store.bundlePath(run.runId),\n prompt: bundle.prompt,\n instructionFile,\n mode: bundle.execution.mode,\n mcpServer: 'clicksmith',\n cwd: sandboxPath,\n isolation: run.isolation,\n agentId: agentConfig.id,\n binExists: this.deps.binExists ?? defaultBinExists,\n };\n\n const adapter = configToAdapter(agentConfig);\n if (!(await adapter.isAvailable(ctx))) {\n await this.fail(run, `Agent \"${agentConfig.id}\" is not available on PATH.`);\n return;\n }\n\n const spec = adapter.buildCommand(ctx);\n logger.info(`run ${run.runId}: ${spec.command} ${spec.args.join(' ')}`);\n\n let result;\n try {\n result = await launchAgent(spec, {\n onLog: (stream, chunk) => {\n void store.appendLog(run.runId, chunk);\n bus.emit({ type: 'agent-log', runId: run.runId, stream, chunk });\n },\n });\n } catch (err) {\n await this.fail(run, err instanceof Error ? err.message : String(err));\n return;\n }\n\n // Capture artifacts from the sandbox.\n const plan = result.stdout.trim();\n let diff = '';\n if (run.sandbox && run.repoRoot) {\n diff = await Git.captureDiff(run.sandbox.path);\n }\n if (plan) await store.writeArtifact(run.runId, 'plan.md', plan);\n if (diff) await store.writeArtifact(run.runId, 'diff.patch', diff);\n\n run.exitCode = result.exitCode;\n run.hasPlan = plan.length > 0;\n run.hasDiff = diff.length > 0;\n\n if (result.exitCode !== 0) {\n await this.fail(run, `Agent exited with code ${result.exitCode}.`);\n return;\n }\n\n run.status = 'plan-ready';\n run.updatedAt = new Date().toISOString();\n await store.saveRun(run);\n bus.emit({\n type: 'plan-ready',\n runId: run.runId,\n ...(plan ? { plan } : {}),\n ...(diff ? { diff } : {}),\n });\n bus.emit({ type: 'agent-done', runId: run.runId, exitCode: result.exitCode });\n\n if (bundle.execution.autoApply) {\n logger.info(`run ${run.runId}: autoApply enabled, applying`);\n await this.apply(run.runId);\n }\n }\n\n private async fail(run: RunRecord, message: string): Promise<void> {\n run.status = 'error';\n run.error = message;\n run.updatedAt = new Date().toISOString();\n await this.deps.store.saveRun(run);\n this.deps.bus.emit({ type: 'agent-error', runId: run.runId, message });\n }\n\n /**\n * Merge a finished run's sandbox changes back into the working tree. Reports\n * conflicts, commits on success, records revert metadata, and cleans up the\n * sandbox.\n */\n async apply(runId: string): Promise<ApplyResponse> {\n const { store, bus, logger } = this.deps;\n const run = await store.getRun(runId);\n if (!run) throw new Error(`Unknown run: ${runId}`);\n if (!run.repoRoot || !run.sandbox) {\n throw new Error(`Run ${runId} has no git sandbox to apply.`);\n }\n\n bus.emit({ type: 'apply-started', runId });\n const git = new Git(run.repoRoot);\n const previousHead = await git.headCommit();\n const message = `${COMMIT_PREFIX} run ${runId}: ${truncate(run.prompt, 72)}`;\n\n try {\n let commit: string | undefined;\n\n if (run.sandbox.isolation === 'worktree') {\n const diff = (await store.readArtifact(runId, 'diff.patch')) ?? '';\n const applied = await git.applyPatch(diff);\n if (!applied.ok) return await this.applyConflict(run, applied.conflicts);\n commit = diff.trim() ? await git.commit(message) : previousHead;\n await this.cleanupSandbox(run);\n } else if (run.sandbox.isolation === 'branch') {\n // Changes are already staged in the repo on the clicksmith branch.\n if (await git.hasChanges()) await git.commit(message);\n if (run.baseBranch) await git.switchTo(run.baseBranch);\n const merged = await git.merge(run.sandbox.branch!, message);\n if (!merged.ok) return await this.applyConflict(run, merged.conflicts);\n commit = await git.headCommit();\n await git.deleteBranch(run.sandbox.branch!);\n } else {\n // inplace: commit whatever the agent changed in the working tree.\n commit = (await git.hasChanges()) ? await git.commit(message) : previousHead;\n }\n\n run.status = 'applied';\n run.applied = { ...(commit ? { commit } : {}), at: new Date().toISOString() };\n run.revert = {\n previousHead,\n ...(commit && commit !== previousHead ? { appliedCommit: commit } : {}),\n instructions:\n commit && commit !== previousHead\n ? `git revert ${commit} # or: git reset --hard ${previousHead}`\n : 'No commit was created; nothing to revert.',\n };\n run.updatedAt = new Date().toISOString();\n await store.saveRun(run);\n\n bus.emit({ type: 'apply-done', runId, ...(commit ? { commit } : {}) });\n return { applied: true, ...(commit ? { commit } : {}) };\n } catch (err) {\n const messageText = err instanceof Error ? err.message : String(err);\n logger.error(`apply ${runId} failed`, messageText);\n run.status = 'apply-error';\n run.error = messageText;\n await store.saveRun(run);\n bus.emit({ type: 'apply-error', runId, message: messageText });\n return { applied: false };\n }\n }\n\n private async applyConflict(run: RunRecord, conflicts: string[]): Promise<ApplyResponse> {\n run.status = 'apply-error';\n run.error = `Apply conflicts in: ${conflicts.join(', ') || 'unknown files'}`;\n run.updatedAt = new Date().toISOString();\n await this.deps.store.saveRun(run);\n this.deps.bus.emit({\n type: 'apply-error',\n runId: run.runId,\n message: run.error,\n conflicts,\n });\n return { applied: false, conflicts };\n }\n\n private async cleanupSandbox(run: RunRecord): Promise<void> {\n if (!run.repoRoot || !run.sandbox) return;\n if (run.sandbox.isolation === 'worktree') {\n const git = new Git(run.repoRoot);\n await git.removeWorktree(run.sandbox.path, run.sandbox.branch ?? undefined);\n }\n }\n\n /**\n * Resolve the instruction file passed to the agent. Prefer the project's\n * rendered file if it exists; otherwise write a run-local one from the shared\n * template so every agent always has instructions.\n */\n private async resolveInstructionFile(run: RunRecord, agentConfig: AgentConfig): Promise<string> {\n const { config, store } = this.deps;\n if (config.repoRoot && agentConfig.instructions) {\n const projectFile = join(config.repoRoot, agentConfig.instructions.file);\n if (await fileExists(projectFile)) return projectFile;\n }\n const body = renderInstructionBody({ daemonPort: config.port });\n return store.writeArtifact(run.runId, 'AGENT_INSTRUCTIONS.md', body);\n }\n}\n\nasync function fileExists(path: string): Promise<boolean> {\n const { access } = await import('node:fs/promises');\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function safe<T>(fn: () => Promise<T>): Promise<T | null> {\n try {\n return await fn();\n } catch {\n return null;\n }\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`;\n}\n","import {\n appendElement,\n createSession,\n ExecutionOptionsSchema,\n finalizeSession,\n removeElement,\n touchSession,\n type ApplyResponse,\n type CaptureRequest,\n type CaptureResponse,\n type HealthResponse,\n type RemoveElementResponse,\n type Session,\n type SubmitRequest,\n type SubmitResponse,\n} from '@clicksmith/core';\nimport { EventBus } from './events.js';\nimport { FileStore } from './store.js';\nimport { RunManager, type RunManagerDeps } from './run-manager.js';\nimport type { DaemonConfig } from './config.js';\nimport type { EnrichmentProvider } from './enrichment.js';\nimport { version as DAEMON_VERSION } from './version.js';\n\nexport interface DaemonServiceOptions {\n config: DaemonConfig;\n enrichment?: EnrichmentProvider;\n binExists?: RunManagerDeps['binExists'];\n}\n\n/**\n * The framework-agnostic core of the daemon. The HTTP/WS server and tests both\n * drive this; it owns sessions, runs, the event bus, and persistence.\n */\nexport class DaemonService {\n readonly config: DaemonConfig;\n readonly store: FileStore;\n readonly bus: EventBus;\n readonly runs: RunManager;\n\n constructor(opts: DaemonServiceOptions) {\n this.config = opts.config;\n this.store = new FileStore(opts.config.storageRoot);\n this.bus = new EventBus();\n this.runs = new RunManager({\n store: this.store,\n config: opts.config,\n bus: this.bus,\n logger: opts.config.logger,\n ...(opts.enrichment ? { enrichment: opts.enrichment } : {}),\n ...(opts.binExists ? { binExists: opts.binExists } : {}),\n });\n }\n\n async init(): Promise<void> {\n await this.store.init();\n await this.store.cleanupExpired();\n }\n\n /* ------------------------------- capture ------------------------------ */\n\n /** Create or append to the active session for an app/route. */\n async capture(req: CaptureRequest): Promise<CaptureResponse> {\n const now = new Date();\n let session = req.sessionId ? await this.store.getSession(req.sessionId) : undefined;\n if (!session) {\n session = createSession({ app: req.app, now, ttlMs: this.config.ttlMs });\n } else {\n session = touchSession(session, now, this.config.ttlMs);\n }\n\n const { session: next, element } = appendElement(session, req.element, now);\n await this.store.saveSession(next);\n\n this.bus.emit({ type: 'capture-ack', sessionId: next.id, element });\n return { sessionId: next.id, element };\n }\n\n async removeElement(sessionId: string, elementId: number): Promise<RemoveElementResponse> {\n const session = await this.store.getSession(sessionId);\n if (!session) return { removed: false };\n const { session: next, removed } = removeElement(session, elementId);\n if (removed) {\n await this.store.saveSession(next);\n this.bus.emit({ type: 'element-removed', sessionId, elementId });\n }\n return { removed };\n }\n\n async getSession(id: string): Promise<Session | undefined> {\n return this.store.getSession(id);\n }\n\n /* ------------------------------- submit ------------------------------- */\n\n /** Finalize a session into a bundle and start a run. */\n async submit(req: SubmitRequest): Promise<SubmitResponse> {\n const session = await this.store.getSession(req.sessionId);\n if (!session) throw new NotFoundError(`Unknown session: ${req.sessionId}`);\n\n const execution = ExecutionOptionsSchema.parse(req.execution ?? {});\n const bundle = finalizeSession(session, {\n prompt: req.prompt,\n execution,\n ...(req.enrichment ? { enrichment: req.enrichment } : {}),\n });\n\n const submitted: Session = { ...session, status: 'submitted', prompt: req.prompt };\n await this.store.saveSession(submitted);\n\n const { run } = await this.runs.createRun(bundle);\n return { runId: run.runId, bundle };\n }\n\n async apply(runId: string): Promise<ApplyResponse> {\n return this.runs.apply(runId);\n }\n\n /* ------------------------------- health ------------------------------- */\n\n async health(): Promise<HealthResponse> {\n const sessions = await this.store.listSessions();\n return {\n ok: true,\n name: 'clicksmith-daemon',\n version: DAEMON_VERSION,\n host: this.config.host,\n port: this.config.port,\n repoRoot: this.config.repoRoot,\n activeSessions: sessions.filter((s) => s.status === 'active').length,\n };\n }\n}\n\nexport class NotFoundError extends Error {\n readonly code = 'NOT_FOUND';\n}\n","import Fastify, { type FastifyInstance } from 'fastify';\nimport websocket from '@fastify/websocket';\nimport {\n CaptureRequestSchema,\n SubmitRequestSchema,\n type ClientMessage,\n type ServerEvent,\n} from '@clicksmith/core';\nimport { type DaemonService, NotFoundError } from './daemon-service.js';\nimport { RefusalError } from './run-manager.js';\n\n/**\n * Build the Fastify app exposing ClickSmith's HTTP + WebSocket surface on top\n * of a {@link DaemonService}. Binds loopback only; CORS is opened for localhost\n * so the browser extension can talk to it.\n */\nexport async function buildServer(service: DaemonService): Promise<FastifyInstance> {\n const app = Fastify({ logger: false });\n\n // Minimal CORS for the extension (loopback only).\n app.addHook('onRequest', async (req, reply) => {\n reply.header('Access-Control-Allow-Origin', '*');\n reply.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,OPTIONS');\n reply.header('Access-Control-Allow-Headers', 'content-type');\n if (req.method === 'OPTIONS') {\n reply.code(204).send();\n }\n });\n\n await app.register(websocket);\n\n /* ------------------------------- HTTP -------------------------------- */\n\n app.get('/health', async () => service.health());\n\n app.post('/capture', async (req, reply) => {\n const parsed = CaptureRequestSchema.safeParse(req.body);\n if (!parsed.success) return reply.code(400).send({ error: parsed.error.message });\n return service.capture(parsed.data);\n });\n\n app.post('/submit', async (req, reply) => {\n const parsed = SubmitRequestSchema.safeParse(req.body);\n if (!parsed.success) return reply.code(400).send({ error: parsed.error.message });\n try {\n return await service.submit(parsed.data);\n } catch (err) {\n if (err instanceof NotFoundError) return reply.code(404).send({ error: err.message });\n if (err instanceof RefusalError) return reply.code(409).send({ error: err.message, code: err.code });\n throw err;\n }\n });\n\n app.post<{ Params: { runId: string } }>('/apply/:runId', async (req, reply) => {\n try {\n return await service.apply(req.params.runId);\n } catch (err) {\n return reply.code(404).send({ error: err instanceof Error ? err.message : String(err) });\n }\n });\n\n app.get<{ Params: { id: string } }>('/session/:id', async (req, reply) => {\n const session = await service.getSession(req.params.id);\n if (!session) return reply.code(404).send({ error: `Unknown session: ${req.params.id}` });\n return session;\n });\n\n app.delete<{ Params: { sessionId: string; elementId: string } }>(\n '/element/:sessionId/:elementId',\n async (req) => {\n const elementId = Number.parseInt(req.params.elementId, 10);\n return service.removeElement(req.params.sessionId, elementId);\n },\n );\n\n /* ----------------------------- WebSocket ----------------------------- */\n\n app.get('/ws', { websocket: true }, (socket) => {\n const send = (event: ServerEvent) => {\n if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(event));\n };\n const unsubscribe = service.bus.subscribe(send);\n\n socket.on('message', (raw: Buffer) => {\n let msg: ClientMessage;\n try {\n msg = JSON.parse(raw.toString()) as ClientMessage;\n } catch {\n return;\n }\n if (msg.type === 'ping') socket.send(JSON.stringify({ type: 'pong' }));\n else if (msg.type === 'subscribe') {\n // Replay buffered events so a reconnecting client catches up.\n for (const event of service.bus.replay(msg.sessionId)) send(event);\n }\n });\n\n socket.on('close', unsubscribe);\n socket.on('error', unsubscribe);\n });\n\n return app;\n}\n"],"mappings":";;;;;;;;AAUO,IAAM,WAAN,MAAe;AAAA,EACH,YAAY,oBAAI,IAAc;AAAA,EAC9B,UAAyB,CAAC;AAAA,EAC1B;AAAA,EAEjB,YAAY,aAAa,KAAK;AAC5B,SAAK,aAAa;AAAA,EACpB;AAAA,EAEA,UAAU,UAAgC;AACxC,SAAK,UAAU,IAAI,QAAQ;AAC3B,WAAO,MAAM,KAAK,UAAU,OAAO,QAAQ;AAAA,EAC7C;AAAA,EAEA,KAAK,OAA0B;AAC7B,SAAK,QAAQ,KAAK,KAAK;AACvB,QAAI,KAAK,QAAQ,SAAS,KAAK,WAAY,MAAK,QAAQ,MAAM;AAC9D,eAAW,YAAY,KAAK,WAAW;AACrC,UAAI;AACF,iBAAS,KAAK;AAAA,MAChB,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,OAAO,OAA+B;AACpC,QAAI,CAAC,MAAO,QAAO,CAAC,GAAG,KAAK,OAAO;AACnC,WAAO,KAAK,QAAQ,OAAO,CAAC,MAAM,WAAW,KAAK,EAAE,UAAU,KAAK;AAAA,EACrE;AACF;;;ACzCA,SAAS,aAAa;AAmBtB,eAAsB,YAAY,MAAmB,UAAiD;AACpG,QAAM,aAAa,MAAM,KAAK,SAAS,KAAK,MAAM;AAAA,IAChD,KAAK,KAAK;AAAA,IACV,KAAK,EAAE,GAAG,QAAQ,KAAK,GAAG,KAAK,IAAI;AAAA,IACnC,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,cAAc,SAAS;AAAA,EACzB,CAAC;AAED,MAAI,SAAS;AAC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AO,MAAM,KAAK,GAAG,EAAE,KAAK,EAAE,OAAO,oBAAoB,IAAI,OAAO,EAAE,GAAG,CAAC;AACxF,WAAO;AAAA,EACT,CAAC;AAED,MAAI;AAAA,IACF;AAAA,IACA,OAAO,QAAQ;AACb,YAAM,YAAY,OAAO,SAAS,IAAI,OAAO,WAAW,EAAE;AAC1D,aAAO,QAAQ,cAAc,IAAI,OAAO,WAAW,SAAS;AAAA,IAC9D;AAAA,EACF;AAIA,MAAI,IAAI,OAAO,EAAE,WAAW,KAAK,GAAG,CAAC,WAAW;AAC9C,UAAM,OAAO,CAAC,UAAuB;AACnC,UAAI,OAAO,eAAe,OAAO,KAAM,QAAO,KAAK,KAAK,UAAU,KAAK,CAAC;AAAA,IAC1E;AACA,UAAM,cAAc,QAAQ,IAAI,UAAU,IAAI;AAE9C,WAAO,GAAG,WAAW,CAAC,QAAgB;AACpC,UAAI;AACJ,UAAI;AACF,cAAM,KAAK,MAAM,IAAI,SAAS,CAAC;AAAA,MACjC,QAAQ;AACN;AAAA,MACF;AACA,UAAI,IAAI,SAAS,OAAQ,QAAO,KAAK,KAAK,UAAU,EAAE,MAAM,OAAO,CAAC,CAAC;AAAA,eAC5D,IAAI,SAAS,aAAa;AAEjC,mBAAW,SAAS,QAAQ,IAAI,OAAO,IAAI,SAAS,EAAG,MAAK,KAAK;AAAA,MACnE;AAAA,IACF,CAAC;AAED,WAAO,GAAG,SAAS,WAAW;AAC9B,WAAO,GAAG,SAAS,WAAW;AAAA,EAChC,CAAC;AAED,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
// src/mcp.ts
|
|
2
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
5
|
+
|
|
6
|
+
// src/config.ts
|
|
7
|
+
import { readFile } from "fs/promises";
|
|
8
|
+
import {
|
|
9
|
+
DEFAULT_AGENTS_CONFIG,
|
|
10
|
+
mergeAgentsConfig,
|
|
11
|
+
parseAgentsConfig
|
|
12
|
+
} from "@clicksmith/agent-config";
|
|
13
|
+
import { DEFAULT_DAEMON_HOST, DEFAULT_DAEMON_PORT, DEFAULT_SESSION_TTL_MS } from "@clicksmith/core";
|
|
14
|
+
|
|
15
|
+
// src/git.ts
|
|
16
|
+
import { execa } from "execa";
|
|
17
|
+
import { mkdtemp, rm, writeFile } from "fs/promises";
|
|
18
|
+
import { tmpdir } from "os";
|
|
19
|
+
import { join } from "path";
|
|
20
|
+
var GitError = class extends Error {
|
|
21
|
+
};
|
|
22
|
+
var Git = class {
|
|
23
|
+
constructor(cwd) {
|
|
24
|
+
this.cwd = cwd;
|
|
25
|
+
}
|
|
26
|
+
cwd;
|
|
27
|
+
async run(args, opts = {}) {
|
|
28
|
+
const result = await execa("git", args, { cwd: this.cwd, reject: false });
|
|
29
|
+
if (opts.reject !== false && result.exitCode !== 0) {
|
|
30
|
+
throw new GitError(`git ${args.join(" ")} failed: ${result.stderr || result.stdout}`);
|
|
31
|
+
}
|
|
32
|
+
return result;
|
|
33
|
+
}
|
|
34
|
+
/** Absolute repo root, or `null` if `cwd` is not inside a git repo. */
|
|
35
|
+
static async findRepoRoot(cwd) {
|
|
36
|
+
const result = await execa("git", ["rev-parse", "--show-toplevel"], { cwd, reject: false });
|
|
37
|
+
return result.exitCode === 0 ? result.stdout.trim() : null;
|
|
38
|
+
}
|
|
39
|
+
async headCommit() {
|
|
40
|
+
return (await this.run(["rev-parse", "HEAD"])).stdout.trim();
|
|
41
|
+
}
|
|
42
|
+
async currentBranch() {
|
|
43
|
+
return (await this.run(["rev-parse", "--abbrev-ref", "HEAD"])).stdout.trim();
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Whether the working tree has uncommitted (tracked or untracked) changes,
|
|
47
|
+
* ignoring any paths under `exclude` prefixes (e.g. ClickSmith's own
|
|
48
|
+
* `.clicksmith/` state directory).
|
|
49
|
+
*/
|
|
50
|
+
async isDirty(opts = {}) {
|
|
51
|
+
const result = await this.run(["status", "--porcelain"]);
|
|
52
|
+
const exclude = opts.exclude ?? [];
|
|
53
|
+
return result.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).some((line) => {
|
|
54
|
+
const path = line.slice(2).trim();
|
|
55
|
+
const actual = path.includes(" -> ") ? path.split(" -> ")[1] : path;
|
|
56
|
+
return !exclude.some((prefix) => actual.startsWith(prefix));
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
/** Whether this git supports worktrees (>= 2.5). */
|
|
60
|
+
async supportsWorktree() {
|
|
61
|
+
const result = await execa("git", ["worktree", "list"], { cwd: this.cwd, reject: false });
|
|
62
|
+
return result.exitCode === 0;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Create a throwaway worktree on a fresh branch for a run. The worktree lives
|
|
66
|
+
* outside the main tree so the agent's edits never touch it.
|
|
67
|
+
*/
|
|
68
|
+
async createWorktree(path, branch, baseRef) {
|
|
69
|
+
await this.run(["worktree", "add", "-b", branch, path, baseRef]);
|
|
70
|
+
}
|
|
71
|
+
async removeWorktree(path, branch) {
|
|
72
|
+
await this.run(["worktree", "remove", "--force", path], { reject: false });
|
|
73
|
+
if (branch) await this.run(["branch", "-D", branch], { reject: false });
|
|
74
|
+
}
|
|
75
|
+
/** Create + checkout a dedicated branch (the worktree fallback). */
|
|
76
|
+
async createBranch(branch, baseRef) {
|
|
77
|
+
await this.run(["switch", "-c", branch, baseRef]);
|
|
78
|
+
}
|
|
79
|
+
async switchTo(ref) {
|
|
80
|
+
await this.run(["switch", ref]);
|
|
81
|
+
}
|
|
82
|
+
async deleteBranch(branch) {
|
|
83
|
+
await this.run(["branch", "-D", branch], { reject: false });
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Capture every change in a sandbox (relative to its HEAD) as a single
|
|
87
|
+
* binary-safe patch, including new and deleted files. Returns '' if clean.
|
|
88
|
+
*/
|
|
89
|
+
static async captureDiff(sandboxPath) {
|
|
90
|
+
await execa("git", ["add", "-A"], { cwd: sandboxPath, reject: false });
|
|
91
|
+
const result = await execa("git", ["diff", "--cached", "--binary"], {
|
|
92
|
+
cwd: sandboxPath,
|
|
93
|
+
reject: false
|
|
94
|
+
});
|
|
95
|
+
return result.exitCode === 0 ? result.stdout : "";
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Apply a captured patch onto the main working tree using a 3-way merge,
|
|
99
|
+
* staging the result. Returns the list of conflicted files (empty on success).
|
|
100
|
+
*/
|
|
101
|
+
async applyPatch(patch) {
|
|
102
|
+
if (!patch.trim()) return { ok: true, conflicts: [] };
|
|
103
|
+
const tmp = await mkdtemp(join(tmpdir(), "clicksmith-patch-"));
|
|
104
|
+
const patchFile = join(tmp, "run.patch");
|
|
105
|
+
try {
|
|
106
|
+
await writeFile(patchFile, patch.endsWith("\n") ? patch : `${patch}
|
|
107
|
+
`, "utf8");
|
|
108
|
+
const result = await this.run(["apply", "--index", "--3way", patchFile], { reject: false });
|
|
109
|
+
if (result.exitCode === 0) return { ok: true, conflicts: [] };
|
|
110
|
+
const unmerged = (await this.run(["diff", "--name-only", "--diff-filter=U"], { reject: false })).stdout.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
|
111
|
+
const conflicts = [.../* @__PURE__ */ new Set([...unmerged, ...parseConflicts(result.stderr)])];
|
|
112
|
+
return { ok: false, conflicts: conflicts.length ? conflicts : ["(unresolved \u2014 see git status)"] };
|
|
113
|
+
} finally {
|
|
114
|
+
await rm(tmp, { recursive: true, force: true });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** Commit the currently staged changes; returns the new commit sha. */
|
|
118
|
+
async commit(message) {
|
|
119
|
+
await this.run(["commit", "-m", message, "--no-verify"]);
|
|
120
|
+
return this.headCommit();
|
|
121
|
+
}
|
|
122
|
+
/** Whether there is anything staged or unstaged to commit. */
|
|
123
|
+
async hasChanges() {
|
|
124
|
+
return this.isDirty();
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Merge a branch into the current branch with `--no-ff`. On conflict, the
|
|
128
|
+
* merge is aborted and the conflicted files are returned.
|
|
129
|
+
*/
|
|
130
|
+
async merge(branch, message) {
|
|
131
|
+
const result = await this.run(["merge", "--no-ff", "-m", message, branch], { reject: false });
|
|
132
|
+
if (result.exitCode === 0) return { ok: true, conflicts: [] };
|
|
133
|
+
const conflicts = (await this.run(["diff", "--name-only", "--diff-filter=U"], { reject: false })).stdout.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
|
134
|
+
await this.run(["merge", "--abort"], { reject: false });
|
|
135
|
+
return { ok: false, conflicts };
|
|
136
|
+
}
|
|
137
|
+
async resetHard(ref) {
|
|
138
|
+
await this.run(["reset", "--hard", ref]);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
function parseConflicts(stderr) {
|
|
142
|
+
const files = /* @__PURE__ */ new Set();
|
|
143
|
+
for (const line of stderr.split(/\r?\n/)) {
|
|
144
|
+
const errColon = line.match(/^error:\s*(.+?):\s/);
|
|
145
|
+
if (errColon?.[1]) files.add(errColon[1].trim());
|
|
146
|
+
for (const q of line.matchAll(/'([^']+)'/g)) files.add(q[1].trim());
|
|
147
|
+
const u = line.match(/^U\s+(.+)$/);
|
|
148
|
+
if (u?.[1]) files.add(u[1].trim());
|
|
149
|
+
}
|
|
150
|
+
return [...files];
|
|
151
|
+
}
|
|
152
|
+
function describeSandbox(isolation, path, branch, baseCommit) {
|
|
153
|
+
return { isolation, path, branch, baseCommit };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// src/paths.ts
|
|
157
|
+
import { homedir } from "os";
|
|
158
|
+
import { join as join2 } from "path";
|
|
159
|
+
function osCacheRoot() {
|
|
160
|
+
if (process.platform === "win32") {
|
|
161
|
+
return join2(process.env.LOCALAPPDATA ?? join2(homedir(), "AppData", "Local"), "clicksmith", "Cache");
|
|
162
|
+
}
|
|
163
|
+
if (process.platform === "darwin") {
|
|
164
|
+
return join2(homedir(), "Library", "Caches", "clicksmith");
|
|
165
|
+
}
|
|
166
|
+
return join2(process.env.XDG_CACHE_HOME ?? join2(homedir(), ".cache"), "clicksmith");
|
|
167
|
+
}
|
|
168
|
+
function resolveStorageRoot(repoRoot) {
|
|
169
|
+
return repoRoot ? join2(repoRoot, ".clicksmith") : osCacheRoot();
|
|
170
|
+
}
|
|
171
|
+
function storagePaths(root) {
|
|
172
|
+
return {
|
|
173
|
+
root,
|
|
174
|
+
sessions: join2(root, "sessions"),
|
|
175
|
+
runs: join2(root, "runs"),
|
|
176
|
+
screenshots: join2(root, "screenshots"),
|
|
177
|
+
config: join2(root, "agents.config.json"),
|
|
178
|
+
runDir: (runId) => join2(root, "runs", runId),
|
|
179
|
+
sandboxDir: (runId) => join2(root, "worktrees", runId)
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// src/logger.ts
|
|
184
|
+
var ORDER = { debug: 0, info: 1, warn: 2, error: 3, silent: 4 };
|
|
185
|
+
function createLogger(level = "info", prefix = "clicksmith") {
|
|
186
|
+
const min = ORDER[level];
|
|
187
|
+
const emit = (lvl, msg, rest) => {
|
|
188
|
+
if (ORDER[lvl] < min) return;
|
|
189
|
+
const line = `[${prefix}] ${lvl.toUpperCase()} ${msg}`;
|
|
190
|
+
process.stderr.write(rest.length ? `${line} ${rest.map(fmt).join(" ")}
|
|
191
|
+
` : `${line}
|
|
192
|
+
`);
|
|
193
|
+
};
|
|
194
|
+
return {
|
|
195
|
+
debug: (m, ...r) => emit("debug", m, r),
|
|
196
|
+
info: (m, ...r) => emit("info", m, r),
|
|
197
|
+
warn: (m, ...r) => emit("warn", m, r),
|
|
198
|
+
error: (m, ...r) => emit("error", m, r)
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
function fmt(v) {
|
|
202
|
+
if (typeof v === "string") return v;
|
|
203
|
+
if (v instanceof Error) return v.stack ?? v.message;
|
|
204
|
+
try {
|
|
205
|
+
return JSON.stringify(v);
|
|
206
|
+
} catch {
|
|
207
|
+
return String(v);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// src/config.ts
|
|
212
|
+
async function resolveDaemonConfig(input = {}) {
|
|
213
|
+
const cwd = input.cwd ?? process.cwd();
|
|
214
|
+
const repoRoot = input.repoRoot !== void 0 ? input.repoRoot : await Git.findRepoRoot(cwd);
|
|
215
|
+
const storageRoot = input.storageRoot ?? resolveStorageRoot(repoRoot);
|
|
216
|
+
const agents = await loadAgentsConfig(storageRoot);
|
|
217
|
+
return {
|
|
218
|
+
host: input.host ?? DEFAULT_DAEMON_HOST,
|
|
219
|
+
port: input.port ?? DEFAULT_DAEMON_PORT,
|
|
220
|
+
ttlMs: input.ttlMs ?? DEFAULT_SESSION_TTL_MS,
|
|
221
|
+
cwd,
|
|
222
|
+
repoRoot,
|
|
223
|
+
storageRoot,
|
|
224
|
+
agents,
|
|
225
|
+
logger: createLogger(input.logLevel ?? "info")
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
async function loadAgentsConfig(storageRoot) {
|
|
229
|
+
const file = storagePaths(storageRoot).config;
|
|
230
|
+
let raw;
|
|
231
|
+
try {
|
|
232
|
+
raw = await readFile(file, "utf8");
|
|
233
|
+
} catch {
|
|
234
|
+
return DEFAULT_AGENTS_CONFIG;
|
|
235
|
+
}
|
|
236
|
+
let json2;
|
|
237
|
+
try {
|
|
238
|
+
json2 = JSON.parse(raw);
|
|
239
|
+
} catch {
|
|
240
|
+
return DEFAULT_AGENTS_CONFIG;
|
|
241
|
+
}
|
|
242
|
+
const parsed = parseAgentsConfig(json2);
|
|
243
|
+
if (!parsed.ok) return DEFAULT_AGENTS_CONFIG;
|
|
244
|
+
return mergeAgentsConfig(DEFAULT_AGENTS_CONFIG, parsed.config);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// src/store.ts
|
|
248
|
+
import { mkdir, readFile as readFile2, readdir, rm as rm2, writeFile as writeFile2 } from "fs/promises";
|
|
249
|
+
import { join as join3 } from "path";
|
|
250
|
+
import {
|
|
251
|
+
deserializeBundle,
|
|
252
|
+
isExpired,
|
|
253
|
+
serializeBundle
|
|
254
|
+
} from "@clicksmith/core";
|
|
255
|
+
var FileStore = class {
|
|
256
|
+
paths;
|
|
257
|
+
constructor(root) {
|
|
258
|
+
this.paths = storagePaths(root);
|
|
259
|
+
}
|
|
260
|
+
async init() {
|
|
261
|
+
await Promise.all([
|
|
262
|
+
mkdir(this.paths.sessions, { recursive: true }),
|
|
263
|
+
mkdir(this.paths.runs, { recursive: true }),
|
|
264
|
+
mkdir(this.paths.screenshots, { recursive: true })
|
|
265
|
+
]);
|
|
266
|
+
}
|
|
267
|
+
/* ----------------------------- sessions ------------------------------ */
|
|
268
|
+
sessionFile(id) {
|
|
269
|
+
return join3(this.paths.sessions, `${sanitize(id)}.json`);
|
|
270
|
+
}
|
|
271
|
+
async saveSession(session) {
|
|
272
|
+
await atomicWrite(this.sessionFile(session.id), JSON.stringify(session, null, 2));
|
|
273
|
+
}
|
|
274
|
+
async getSession(id) {
|
|
275
|
+
return readJson(this.sessionFile(id));
|
|
276
|
+
}
|
|
277
|
+
async listSessions() {
|
|
278
|
+
const out = [];
|
|
279
|
+
for (const file of await listJson(this.paths.sessions)) {
|
|
280
|
+
const s = await readJson(join3(this.paths.sessions, file));
|
|
281
|
+
if (s) out.push(s);
|
|
282
|
+
}
|
|
283
|
+
return out;
|
|
284
|
+
}
|
|
285
|
+
async deleteSession(id) {
|
|
286
|
+
await rm2(this.sessionFile(id), { force: true });
|
|
287
|
+
}
|
|
288
|
+
/* -------------------------------- runs -------------------------------- */
|
|
289
|
+
runDir(runId) {
|
|
290
|
+
return this.paths.runDir(runId);
|
|
291
|
+
}
|
|
292
|
+
runFile(runId) {
|
|
293
|
+
return join3(this.runDir(runId), "run.json");
|
|
294
|
+
}
|
|
295
|
+
async saveRun(run) {
|
|
296
|
+
await mkdir(this.runDir(run.runId), { recursive: true });
|
|
297
|
+
await atomicWrite(this.runFile(run.runId), JSON.stringify(run, null, 2));
|
|
298
|
+
}
|
|
299
|
+
async getRun(runId) {
|
|
300
|
+
return readJson(this.runFile(runId));
|
|
301
|
+
}
|
|
302
|
+
async listRuns() {
|
|
303
|
+
let dirs;
|
|
304
|
+
try {
|
|
305
|
+
dirs = await readdir(this.paths.runs);
|
|
306
|
+
} catch {
|
|
307
|
+
return [];
|
|
308
|
+
}
|
|
309
|
+
const out = [];
|
|
310
|
+
for (const dir of dirs) {
|
|
311
|
+
const run = await readJson(join3(this.paths.runs, dir, "run.json"));
|
|
312
|
+
if (run) out.push(run);
|
|
313
|
+
}
|
|
314
|
+
return out.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
315
|
+
}
|
|
316
|
+
/** The most recent run that has a persisted bundle (for `get_latest_request`). */
|
|
317
|
+
async latestRun() {
|
|
318
|
+
const runs = await this.listRuns();
|
|
319
|
+
return runs.at(-1);
|
|
320
|
+
}
|
|
321
|
+
/* ----------------------------- artifacts ------------------------------ */
|
|
322
|
+
async saveBundle(runId, bundle) {
|
|
323
|
+
await mkdir(this.runDir(runId), { recursive: true });
|
|
324
|
+
const file = join3(this.runDir(runId), "bundle.json");
|
|
325
|
+
await atomicWrite(file, serializeBundle(bundle));
|
|
326
|
+
return file;
|
|
327
|
+
}
|
|
328
|
+
async getBundle(runId) {
|
|
329
|
+
const raw = await readText(join3(this.runDir(runId), "bundle.json"));
|
|
330
|
+
return raw ? deserializeBundle(raw) : void 0;
|
|
331
|
+
}
|
|
332
|
+
bundlePath(runId) {
|
|
333
|
+
return join3(this.runDir(runId), "bundle.json");
|
|
334
|
+
}
|
|
335
|
+
async writeArtifact(runId, name, content) {
|
|
336
|
+
await mkdir(this.runDir(runId), { recursive: true });
|
|
337
|
+
const file = join3(this.runDir(runId), name);
|
|
338
|
+
await atomicWrite(file, content);
|
|
339
|
+
return file;
|
|
340
|
+
}
|
|
341
|
+
async readArtifact(runId, name) {
|
|
342
|
+
return readText(join3(this.runDir(runId), name));
|
|
343
|
+
}
|
|
344
|
+
async appendLog(runId, chunk) {
|
|
345
|
+
const file = join3(this.runDir(runId), "agent.log");
|
|
346
|
+
await mkdir(this.runDir(runId), { recursive: true });
|
|
347
|
+
const existing = await readText(file) ?? "";
|
|
348
|
+
await writeFile2(file, existing + chunk, "utf8");
|
|
349
|
+
}
|
|
350
|
+
/* ----------------------------- maintenance ----------------------------- */
|
|
351
|
+
/** Delete expired, unsubmitted sessions. Returns the ids removed. */
|
|
352
|
+
async cleanupExpired(now = /* @__PURE__ */ new Date()) {
|
|
353
|
+
const removed = [];
|
|
354
|
+
for (const session of await this.listSessions()) {
|
|
355
|
+
if (isExpired(session, now)) {
|
|
356
|
+
await this.deleteSession(session.id);
|
|
357
|
+
removed.push(session.id);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return removed;
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
function sanitize(id) {
|
|
364
|
+
return id.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
365
|
+
}
|
|
366
|
+
async function atomicWrite(file, content) {
|
|
367
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
368
|
+
await writeFile2(tmp, content, "utf8");
|
|
369
|
+
const { rename } = await import("fs/promises");
|
|
370
|
+
await rename(tmp, file);
|
|
371
|
+
}
|
|
372
|
+
async function readText(file) {
|
|
373
|
+
try {
|
|
374
|
+
return await readFile2(file, "utf8");
|
|
375
|
+
} catch {
|
|
376
|
+
return void 0;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
async function readJson(file) {
|
|
380
|
+
const raw = await readText(file);
|
|
381
|
+
if (raw == null) return void 0;
|
|
382
|
+
try {
|
|
383
|
+
return JSON.parse(raw);
|
|
384
|
+
} catch {
|
|
385
|
+
return void 0;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
async function listJson(dir) {
|
|
389
|
+
try {
|
|
390
|
+
return (await readdir(dir)).filter((f) => f.endsWith(".json"));
|
|
391
|
+
} catch {
|
|
392
|
+
return [];
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// src/mcp-tools.ts
|
|
397
|
+
function readerFromStore(store) {
|
|
398
|
+
return {
|
|
399
|
+
getSession: (id) => store.getSession(id),
|
|
400
|
+
latestBundle: async () => {
|
|
401
|
+
const run = await store.latestRun();
|
|
402
|
+
return run ? store.getBundle(run.runId) : void 0;
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
var TOOL_DEFINITIONS = [
|
|
407
|
+
{
|
|
408
|
+
name: "get_latest_request",
|
|
409
|
+
description: "Get the most recently submitted ClickSmith capture bundle (the latest UI change request). Returns the prompt, the app route, and the captured elements numbered #1, #2, \u2026 . The user prompt refers to elements by these numbers. Trust each element\u2019s locator in the order source \u2192 attr \u2192 behavioral \u2192 dom (source = exact file:line). You are running in an isolated git worktree; in plan mode propose changes \u2014 the human clicks Apply to ship them.",
|
|
410
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false }
|
|
411
|
+
},
|
|
412
|
+
{
|
|
413
|
+
name: "get_session",
|
|
414
|
+
description: "Get a ClickSmith capture session by id, including all captured elements (#1, #2, \u2026) and the app/route context. Use this to resolve which concrete elements the user\u2019s #N references mean.",
|
|
415
|
+
inputSchema: {
|
|
416
|
+
type: "object",
|
|
417
|
+
properties: { sessionId: { type: "string", description: "The session id." } },
|
|
418
|
+
required: ["sessionId"],
|
|
419
|
+
additionalProperties: false
|
|
420
|
+
}
|
|
421
|
+
},
|
|
422
|
+
{
|
|
423
|
+
name: "list_elements",
|
|
424
|
+
description: "List the captured elements for a session (or the latest request if no sessionId is given). Each element has an id (its #N), a ranked locator (source \u2192 attr \u2192 behavioral \u2192 dom), the tag/text/role/label, and nearby context for disambiguation.",
|
|
425
|
+
inputSchema: {
|
|
426
|
+
type: "object",
|
|
427
|
+
properties: { sessionId: { type: "string", description: "Optional session id." } },
|
|
428
|
+
additionalProperties: false
|
|
429
|
+
}
|
|
430
|
+
},
|
|
431
|
+
{
|
|
432
|
+
name: "get_element_by_id",
|
|
433
|
+
description: "Resolve a single captured element by its #N id (e.g. 1 for #1), within a session or the latest request. Returns its locator (prefer source over attr over behavioral over dom), the element descriptor, and near context.",
|
|
434
|
+
inputSchema: {
|
|
435
|
+
type: "object",
|
|
436
|
+
properties: {
|
|
437
|
+
id: { type: "number", description: "The element\u2019s #N number." },
|
|
438
|
+
sessionId: { type: "string", description: "Optional session id; defaults to latest." }
|
|
439
|
+
},
|
|
440
|
+
required: ["id"],
|
|
441
|
+
additionalProperties: false
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
];
|
|
445
|
+
async function callTool(name, args, reader) {
|
|
446
|
+
switch (name) {
|
|
447
|
+
case "get_latest_request": {
|
|
448
|
+
const bundle = await reader.latestBundle();
|
|
449
|
+
if (!bundle) return { ok: false, error: "No request has been submitted yet." };
|
|
450
|
+
return { ok: true, text: json(bundle) };
|
|
451
|
+
}
|
|
452
|
+
case "get_session": {
|
|
453
|
+
const session = await reader.getSession(String(args.sessionId));
|
|
454
|
+
if (!session) return { ok: false, error: `Unknown session: ${String(args.sessionId)}` };
|
|
455
|
+
return { ok: true, text: json(session) };
|
|
456
|
+
}
|
|
457
|
+
case "list_elements": {
|
|
458
|
+
const elements = await resolveElements(reader, args.sessionId);
|
|
459
|
+
if (!elements) return { ok: false, error: "No session or latest request found." };
|
|
460
|
+
return { ok: true, text: json(elements) };
|
|
461
|
+
}
|
|
462
|
+
case "get_element_by_id": {
|
|
463
|
+
const id = Number(args.id);
|
|
464
|
+
const elements = await resolveElements(reader, args.sessionId);
|
|
465
|
+
if (!elements) return { ok: false, error: "No session or latest request found." };
|
|
466
|
+
const element = elements.find((e) => e.id === id);
|
|
467
|
+
if (!element) return { ok: false, error: `No element #${id} in this session.` };
|
|
468
|
+
return { ok: true, text: json(element) };
|
|
469
|
+
}
|
|
470
|
+
default:
|
|
471
|
+
return { ok: false, error: `Unknown tool: ${name}` };
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
async function resolveElements(reader, sessionId) {
|
|
475
|
+
if (sessionId) return (await reader.getSession(sessionId))?.elements;
|
|
476
|
+
return (await reader.latestBundle())?.elements;
|
|
477
|
+
}
|
|
478
|
+
function json(value) {
|
|
479
|
+
return JSON.stringify(value, null, 2);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// src/version.ts
|
|
483
|
+
var version = "0.1.0";
|
|
484
|
+
|
|
485
|
+
// src/mcp.ts
|
|
486
|
+
function createMcpServer(reader) {
|
|
487
|
+
const server = new Server(
|
|
488
|
+
{ name: "clicksmith", version },
|
|
489
|
+
{ capabilities: { tools: {} } }
|
|
490
|
+
);
|
|
491
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
492
|
+
tools: TOOL_DEFINITIONS.map((t) => ({
|
|
493
|
+
name: t.name,
|
|
494
|
+
description: t.description,
|
|
495
|
+
inputSchema: t.inputSchema
|
|
496
|
+
}))
|
|
497
|
+
}));
|
|
498
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
499
|
+
const { name, arguments: args } = request.params;
|
|
500
|
+
const result = await callTool(name, args ?? {}, reader);
|
|
501
|
+
if (!result.ok) {
|
|
502
|
+
return { content: [{ type: "text", text: result.error }], isError: true };
|
|
503
|
+
}
|
|
504
|
+
return { content: [{ type: "text", text: result.text }] };
|
|
505
|
+
});
|
|
506
|
+
return server;
|
|
507
|
+
}
|
|
508
|
+
async function startMcp() {
|
|
509
|
+
const config = await resolveDaemonConfig({ logLevel: "silent" });
|
|
510
|
+
const store = new FileStore(config.storageRoot);
|
|
511
|
+
await store.init();
|
|
512
|
+
const server = createMcpServer(readerFromStore(store));
|
|
513
|
+
const transport = new StdioServerTransport();
|
|
514
|
+
await server.connect(transport);
|
|
515
|
+
}
|
|
516
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
517
|
+
startMcp().catch((err) => {
|
|
518
|
+
process.stderr.write(`clicksmith mcp failed: ${err instanceof Error ? err.stack : String(err)}
|
|
519
|
+
`);
|
|
520
|
+
process.exit(1);
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
export {
|
|
525
|
+
GitError,
|
|
526
|
+
Git,
|
|
527
|
+
describeSandbox,
|
|
528
|
+
osCacheRoot,
|
|
529
|
+
resolveStorageRoot,
|
|
530
|
+
storagePaths,
|
|
531
|
+
createLogger,
|
|
532
|
+
resolveDaemonConfig,
|
|
533
|
+
loadAgentsConfig,
|
|
534
|
+
FileStore,
|
|
535
|
+
version,
|
|
536
|
+
readerFromStore,
|
|
537
|
+
TOOL_DEFINITIONS,
|
|
538
|
+
callTool,
|
|
539
|
+
createMcpServer,
|
|
540
|
+
startMcp
|
|
541
|
+
};
|
|
542
|
+
//# sourceMappingURL=chunk-UVRW6O46.js.map
|