capy-acp 0.1.0 → 0.2.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/README.md +83 -43
- package/dist/agent.js +118 -41
- package/dist/agent.js.map +1 -1
- package/dist/bin.js +54 -3
- package/dist/bin.js.map +1 -1
- package/dist/capy/client.js +9 -1
- package/dist/capy/client.js.map +1 -1
- package/dist/changes.js +64 -44
- package/dist/changes.js.map +1 -1
- package/dist/config.js +4 -2
- package/dist/config.js.map +1 -1
- package/dist/doctor.js +102 -0
- package/dist/doctor.js.map +1 -0
- package/dist/pricing.js +60 -0
- package/dist/pricing.js.map +1 -0
- package/dist/problems.js +108 -0
- package/dist/problems.js.map +1 -0
- package/dist/setup.js +2 -2
- package/dist/setup.js.map +1 -1
- package/dist/translate.js +35 -18
- package/dist/translate.js.map +1 -1
- package/dist/turn.js +32 -34
- package/dist/turn.js.map +1 -1
- package/dist/workspace.js +77 -42
- package/dist/workspace.js.map +1 -1
- package/package.json +4 -2
package/dist/turn.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"turn.js","sourceRoot":"","sources":["../src/turn.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AACnD,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAExC,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AACjE,OAAO,EAAE,UAAU,EAAkB,kBAAkB,EAAE,aAAa,EAAmB,WAAW,EAAyC,MAAM,kBAAkB,CAAA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C,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,UAAU,EAAE,CAAA;AAC/G,CAAC,CAAC,CAAA","sourcesContent":["/**\n * Runs one ACP prompt turn against a Capy thread: create or follow up, then stream until the\n * thread settles. Reconnects resume from the last transcript cursor, so nothing is shown twice.\n */\nimport { randomUUID } from \"node:crypto\"\nimport { existsSync } from \"node:fs\"\nimport { mkdir, writeFile } from \"node:fs/promises\"\nimport { basename, isAbsolute, join } from \"node:path\"\nimport { pathToFileURL } from \"node:url\"\nimport type { ContentBlock, SessionUpdate, StopReason } from \"@agentclientprotocol/sdk\"\nimport { Duration, Effect, Option, Result, Stream } from \"effect\"\nimport { CapyClient, type CapyError, CapyTransportError, describeError, type FileUpload, isTransient, type MessageFile, type ModelSelection } from \"./capy/client.js\"\nimport type { MessageAttachment } from \"./capy/events.js\"\nimport { type ChangeTracker, type FileChange, mergeChanges } from \"./changes.js\"\nimport type { DeviceWorkspace } from \"./workspace.js\"\nimport { closedTools, fileChangeUpdate, finishTools, initialTurn, step, turnComplete, type TurnSignal, type TurnState } from \"./translate.js\"\n\nexport interface ThreadTarget {\n readonly projectId: string\n readonly deviceId: string\n readonly workspace: DeviceWorkspace\n}\n\nexport interface TurnInput {\n readonly threadId: string | undefined\n readonly cursor: string | undefined\n readonly text: string\n /** Images and other media from the prompt, attached to the Capy message. */\n readonly files?: ReadonlyArray<FileUpload> | undefined\n /** Where a new thread's first-prompt files are saved for the agent to read (see below). */\n readonly attachmentsDir: string\n readonly model: ModelSelection\n readonly target: ThreadTarget\n readonly waitingLimitMs: number\n /** Resolves when the client cancels the prompt. */\n readonly cancelled: Effect.Effect<void>\n readonly emit: (update: SessionUpdate) => Effect.Effect<void>\n /** Linked mode only: watches the open folder so file edits reach the client as diffs. */\n readonly changes?: ChangeTracker | undefined\n /** Called whenever the resume cursor advances, so a restarted adapter picks up exactly there. */\n readonly onCursor?: ((threadId: string, cursor: string) => Effect.Effect<void>) | undefined\n}\n\nexport interface TurnResult {\n /** Undefined only when a first prompt was cancelled before its thread was created. */\n readonly threadId: string | undefined\n readonly cursor: string | undefined\n readonly stopReason: StopReason\n}\n\nconst MAX_IDLE_RECHECKS = 5\n/** How long an `until=run` connection may stay open after the turn ended before it is dropped. */\nconst END_GRACE_MS = 10_000\nconst CANCEL_GRACE = Duration.seconds(20)\n/** Failed reads in a row before the turn gives up on the connection: about four minutes of backoff. */\nconst MAX_FAILURES = 12\nconst backoff = (attempt: number) => Duration.millis(Math.min(30_000, 250 * 2 ** attempt))\n\nconst chunk = (text: string): SessionUpdate => ({ sessionUpdate: \"agent_message_chunk\", content: { type: \"text\", text } })\n\nconst asStopped = (update: SessionUpdate): SessionUpdate =>\n (update.sessionUpdate === \"tool_call\" || update.sessionUpdate === \"tool_call_update\") && update.status === \"completed\"\n ? { ...update, status: \"failed\" }\n : update\n\nexport const titleOf = (text: string) => {\n const line = text.split(\"\\n\").find((l) => l.trim() !== \"\")?.trim() ?? \"capy-acp session\"\n return line.length > 80 ? `${line.slice(0, 77)}…` : line\n}\n\ntype Outcome = \"ended\" | \"failed\" | \"archived\" | \"waiting-limit\" | \"cancelled\" | \"lost\" | \"not-started\"\n\nconst attachedLabel = (files: ReadonlyArray<{ readonly name: string }>) => `Attached: ${files.map((f) => f.name).join(\", \")}`\n\nconst savedNote = (paths: ReadonlyArray<string>) =>\n paths.length === 0 ? \"\" : `Attached files, saved on this machine:\\n${paths.map((path) => `- ${path}`).join(\"\\n\")}`\n\n/** Writes a prompt's files under a fresh directory (owner-only) and returns their paths. */\nconst saveAttachments = (dir: string, files: ReadonlyArray<FileUpload>): Effect.Effect<ReadonlyArray<string>, CapyTransportError> =>\n Effect.tryPromise({\n try: async () => {\n const folder = join(dir, randomUUID())\n await mkdir(folder, { recursive: true, mode: 0o700 })\n const used = new Set<string>()\n const paths: Array<string> = []\n for (const file of files) {\n // Names come from the client: keep the last path segment only, and never reuse one. Characters\n // Windows forbids go too (a `:` would write an NTFS alternate stream of another file).\n const base = basename(file.name.replace(/\\\\/g, \"/\")).replace(/[<>:\"|?*\\x00-\\x1f]/g, \"_\").replace(/^\\.+/, \"\") || \"attachment\"\n let name = base\n for (let n = 2; used.has(name); n++) name = `${n}-${base}`\n used.add(name)\n const path = join(folder, name)\n await writeFile(path, file.bytes, { mode: 0o600 })\n paths.push(path)\n }\n return paths\n },\n catch: (cause) => new CapyTransportError({ message: `Could not save the attachments for Capy: ${String(cause)}`, cause })\n })\n\nconst formatBytes = (n: number) => (n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1024 ** 2).toFixed(1)} MB`)\n\n/**\n * A link to a file on a transcript entry. A file the agent made on this machine links to its\n * path; anything else gets Capy's short-lived download URL. Never fails: without either, the\n * file is named in text.\n */\nexport const fileLink = (capy: CapyClient[\"Service\"], threadId: string, file: MessageAttachment): Effect.Effect<ContentBlock> =>\n Effect.gen(function*() {\n // Capy reports Windows paths with forward slashes (`C:/Users/…`); isAbsolute takes either form.\n const local = file.sourcePath !== undefined && isAbsolute(file.sourcePath) && existsSync(file.sourcePath)\n const uri = local\n ? pathToFileURL(file.sourcePath!).href\n : yield* capy.attachmentUrl(threadId, file.fileId).pipe(Effect.orElseSucceed(() => undefined))\n const details = [file.mediaType, file.sizeBytes === undefined ? undefined : formatBytes(file.sizeBytes)].filter((d) => d !== undefined)\n if (uri === undefined) return { type: \"text\", text: `\\n\\n[Capy attached ${file.name}]` }\n return {\n type: \"resource_link\",\n uri,\n name: file.name,\n ...(file.title === undefined ? {} : { title: file.title }),\n ...(file.mediaType === undefined ? {} : { mimeType: file.mediaType }),\n ...(file.sizeBytes === undefined ? {} : { size: file.sizeBytes }),\n ...(details.length > 0 ? { description: details.join(\", \") } : {})\n }\n })\n\nexport const runTurn = (input: TurnInput): Effect.Effect<TurnResult, CapyError, CapyClient> =>\n Effect.gen(function*() {\n const capy = yield* CapyClient\n const tracker = input.changes\n // Before the message goes out, so the user's own uncommitted edits are not credited to Capy.\n if (tracker !== undefined) yield* tracker.baseline\n\n let threadId = input.threadId\n const attachments = input.files ?? []\n // Thread create takes text only. Files sent right after it race the agent's first step (a\n // fast model answers \"no image came through\"), so the first message names copies saved on\n // this machine instead, which is where the device agent runs and can read them. Follow-ups\n // upload first, so a failed upload sends nothing.\n const prepare = threadId === undefined\n ? (attachments.length === 0 ? Effect.succeed([]) : saveAttachments(input.attachmentsDir, attachments)).pipe(\n Effect.map((saved) => ({ saved, uploaded: [] as ReadonlyArray<MessageFile> }))\n )\n : capy.uploadFiles(attachments).pipe(Effect.map((uploaded) => ({ saved: [] as ReadonlyArray<string>, uploaded })))\n // Uploads can take a while. A cancel before the message goes out sends nothing. The send itself\n // is not raced: a request Capy may already have accepted is followed through and interrupted.\n const prepared = yield* Effect.raceFirst(prepare.pipe(Effect.map(Option.some)), input.cancelled.pipe(Effect.as(Option.none())))\n if (Option.isNone(prepared)) return { threadId, cursor: input.cursor, stopReason: \"cancelled\" as const }\n const { saved, uploaded } = prepared.value\n\n if (threadId === undefined) {\n const text = [input.text, savedNote(saved)].filter((part) => part !== \"\").join(\"\\n\\n\")\n const thread = yield* capy.createThread({\n requestId: randomUUID(),\n projectId: input.target.projectId,\n title: titleOf(input.text !== \"\" ? input.text : attachments.map((f) => f.name).join(\", \")),\n message: text,\n model: input.model,\n device: { deviceId: input.target.deviceId, workspace: input.target.workspace }\n })\n threadId = thread.id\n } else {\n const text = input.text !== \"\" ? input.text : attachedLabel(uploaded)\n yield* capy.sendMessage(threadId, { text, clientKey: randomUUID(), model: input.model, ...(uploaded.length > 0 ? { files: uploaded } : {}) })\n }\n const id = threadId\n\n let state: TurnState = initialTurn(input.cursor)\n let waitingSince: number | undefined\n let idleRechecks = 0\n /** Stream events seen this turn (heartbeats aside): tells a productive read from an empty one. */\n let received = 0\n /** Failed reads or status checks in a row; any event resets it. */\n let failures = 0\n /** Reads in a row that closed without an event while the thread was still busy. */\n let emptyReads = 0\n /** Why the turn gave up on the connection, for the closing note. */\n let lost: CapyError | undefined\n /** Set once the client cancels; the loop keeps reading until the thread settles. */\n let cancelRequested = false\n\n // Diffs already shown per tool call. ACP `content` replaces rather than appends, so later\n // changes credited to the same call are merged into what it already shows.\n const shown = new Map<string, ReadonlyArray<FileChange>>()\n let lastTool: string | undefined\n\n const showChanges = (toolCallId: string | undefined, changes: ReadonlyArray<FileChange>, status: \"completed\" | \"failed\") => {\n if (changes.length === 0) return Effect.void\n const id = toolCallId ?? `capy-acp-changes-${randomUUID()}`\n const merged = mergeChanges(shown.get(id) ?? [], changes)\n shown.set(id, merged)\n if (merged.length === 0) return Effect.void\n return input.emit(fileChangeUpdate(id, merged, { create: toolCallId === undefined, status }))\n }\n\n const apply = (event: Parameters<typeof step>[1]): Effect.Effect<TurnSignal | undefined> =>\n Effect.gen(function*() {\n if (event._tag !== \"Heartbeat\") received++\n const before = state.cursor\n const result = step(state, event)\n state = result.state\n // Capy commits the call it stopped for a cancel like any finished call (seen live), so a call that\n // closes after the cancel is shown as not completed.\n const updates = cancelRequested ? result.updates.map(asStopped) : result.updates\n yield* Effect.forEach(updates, input.emit, { discard: true })\n for (const file of result.files ?? []) {\n yield* input.emit({ sessionUpdate: \"agent_message_chunk\", content: yield* fileLink(capy, id, file) })\n }\n if (state.cursor !== undefined && state.cursor !== before && input.onCursor !== undefined) {\n yield* input.onCursor(id, state.cursor)\n }\n const closed = closedTools(updates)\n if (closed.length > 0) {\n lastTool = closed.at(-1)\n // The call just finished, so whatever changed on disk since the last look is its doing.\n if (tracker !== undefined) yield* showChanges(lastTool, yield* tracker.collect, cancelRequested ? \"failed\" : \"completed\")\n }\n return result.signal\n })\n\n // Reads one stream connection; resolves with the signal that ended it, if any.\n // An `until=run` connection is read until the server closes it, even after `Ended`: entries\n // that streamed no fragments commit after `idle`, and the server sends them before `done`.\n // Should it not close, the next frame (a heartbeat comes every 15 s) after a grace ends it.\n const readOnce = (follow: boolean): Effect.Effect<TurnSignal | undefined, CapyError> => {\n let last: TurnSignal | undefined\n let endedAt: number | undefined\n const stream = capy.stream(id, { cursor: state.cursor, untilRun: !follow }).pipe(\n Stream.mapEffect(apply),\n Stream.takeUntil((signal) => {\n if (signal !== undefined) last = signal\n if (signal?._tag === \"Ended\") endedAt ??= Date.now()\n if (signal === undefined || signal._tag === \"Waiting\") return endedAt !== undefined && Date.now() - endedAt > END_GRACE_MS\n return follow || signal._tag !== \"Ended\"\n }),\n Stream.runDrain\n )\n if (!follow) return stream.pipe(Effect.map(() => last))\n // While the thread waits, hold a live stream open until it wakes or the waiting limit passes.\n const remaining = Math.max(0, input.waitingLimitMs - (Date.now() - (waitingSince ?? Date.now())))\n return stream.pipe(\n Effect.timeoutOption(Duration.millis(remaining)),\n Effect.map((done) => (Option.isNone(done) ? ({ _tag: \"Waiting\" } as const) : last))\n )\n }\n\n /**\n * A failed read or status check. Transient failures (a dropped connection, a 5xx) wait and try\n * again from the cursor, so nothing is shown twice; after too many in a row the turn ends with\n * a note instead of an error, since Capy keeps working either way. Anything else fails the turn.\n */\n const recover = (error: CapyError): Effect.Effect<boolean, CapyError> => {\n // A cursor Capy no longer accepts would fail every read. Reading without one can repeat\n // entries the client already has, which beats a session that can never stream again.\n const badCursor = error._tag === \"CapyApiError\" && error.status === 400 && /cursor/i.test(error.message)\n if (badCursor && state.cursor !== undefined) {\n state = { ...state, cursor: undefined }\n } else if (!isTransient(error)) {\n return Effect.fail(error)\n }\n if (++failures > MAX_FAILURES) {\n lost = error\n return Effect.succeed(false)\n }\n return Effect.sleep(backoff(failures)).pipe(Effect.as(true))\n }\n\n const loop: Effect.Effect<Outcome, CapyError> = Effect.gen(function*() {\n for (;;) {\n const follow = state.status === \"waiting\"\n const seen = received\n const read = yield* Effect.result(readOnce(follow))\n if (received > seen) failures = 0\n if (Result.isFailure(read)) {\n if (!(yield* recover(read.failure))) return \"lost\"\n continue\n }\n const signal = read.success\n switch (signal?._tag) {\n case \"Ended\":\n // A live (waiting) connection stops at `idle`; drain the rest with an `until=run` read.\n if (!follow) return \"ended\"\n state = { ...state, status: \"idle\" }\n continue\n case \"Failed\":\n return \"failed\"\n case \"Archived\":\n return \"archived\"\n case \"StreamError\":\n if (signal.code === \"unauthorized\" || signal.code === \"forbidden\") return \"failed\"\n break\n case \"Waiting\":\n waitingSince ??= Date.now()\n if (Date.now() - waitingSince >= input.waitingLimitMs) return \"waiting-limit\"\n break\n default:\n break\n }\n // The connection closed (run ended, `done`, or a drop): ask the thread where it stands.\n const checked = yield* Effect.result(capy.getThread(id))\n if (Result.isFailure(checked)) {\n if (!(yield* recover(checked.failure))) return \"lost\"\n continue\n }\n const thread = checked.success\n state = { ...state, status: thread.status }\n if (thread.status === \"idle\") {\n if (state.active && turnComplete(state)) return \"ended\"\n // Capy never started on the message: tell the user rather than end silently.\n if (++idleRechecks > MAX_IDLE_RECHECKS) return state.active ? \"ended\" : \"not-started\"\n // Not picked up yet, or a reply has not committed: read again from the cursor.\n yield* Effect.sleep(Duration.seconds(1))\n } else if (thread.status === \"failed\") {\n return \"failed\"\n } else if (thread.status === \"archived\") {\n return \"archived\"\n } else {\n if (thread.status === \"waiting\") {\n waitingSince ??= Date.now()\n if (Date.now() - waitingSince >= input.waitingLimitMs) return \"waiting-limit\"\n }\n // Still busy, but the stream closed with nothing new (or sent an error frame): don't spin.\n emptyReads = received > seen ? 0 : emptyReads + 1\n if (emptyReads > 0) yield* Effect.sleep(backoff(Math.min(emptyReads, 4)))\n }\n }\n })\n\n // Cancel = interrupt the Capy thread and let the one running loop settle, so the cursor stays right.\n // If the thread does not settle within the grace period, the loop is abandoned.\n const cancel = input.cancelled.pipe(\n Effect.tap(() => Effect.sync(() => (cancelRequested = true))),\n Effect.andThen(capy.interrupt(id).pipe(Effect.ignore)),\n Effect.andThen(Effect.sleep(CANCEL_GRACE)),\n Effect.as(\"cancelled\" as const)\n )\n\n // A failure after the message went out is reported in the reply, not as a request error: Capy\n // has the message and keeps working, and an error invites a resend that would duplicate it.\n const raced = yield* Effect.result(Effect.raceFirst(loop, cancel))\n if (Result.isFailure(raced)) lost = raced.failure\n const outcome: Outcome = cancelRequested ? \"cancelled\" : Result.isSuccess(raced) ? raced.success : \"lost\"\n\n const closeAs = outcome === \"ended\" || outcome === \"waiting-limit\" ? \"completed\" : \"failed\"\n const closed = finishTools(state, closeAs)\n state = closed.state\n yield* Effect.forEach(closed.updates, input.emit, { discard: true })\n // A last look catches edits from a call that never reported completing (interrupts, a final\n // entry that lagged). They join the latest tool call, or get their own when there was none.\n if (tracker !== undefined) {\n const stillOpen = closedTools(closed.updates).at(-1)\n yield* showChanges(stillOpen ?? lastTool, yield* tracker.collect, stillOpen === undefined ? \"completed\" : closeAs)\n }\n if (outcome === \"failed\") yield* input.emit(chunk(\"\\n\\nCapy reported that this run failed. The thread keeps its transcript; send another message to retry.\"))\n if (outcome === \"archived\") yield* input.emit(chunk(\"\\n\\nThe Capy thread was archived. Start a new session to continue.\"))\n if (outcome === \"lost\") {\n yield* input.emit(\n chunk(\n `\\n\\nLost the connection to Capy (${lost === undefined ? \"unknown error\" : describeError(lost)}). Capy may still be working in its ` +\n \"thread; your next message here continues from where this reply stopped.\"\n )\n )\n }\n if (outcome === \"not-started\") {\n yield* input.emit(\n chunk(\n \"Capy has not started on this message yet. Make sure that the Capy desktop app or `capy dock` runs on this machine \" +\n \"and is signed in. The message stays in the thread queue.\"\n )\n )\n }\n if (outcome === \"waiting-limit\") {\n yield* input.emit(\n chunk(\"\\n\\nCapy is still waiting on a background command or event. It will continue in its thread on its own; send a message here to check on it.\")\n )\n }\n return { threadId: id, cursor: state.cursor, stopReason: outcome === \"cancelled\" ? \"cancelled\" : \"end_turn\" }\n })\n"]}
|
|
1
|
+
{"version":3,"file":"turn.js","sourceRoot":"","sources":["../src/turn.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,k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FAA+F,CAClG,CACF,CAAA;IACH,CAAC;IACD,IAAI,OAAO,KAAK,eAAe,EAAE,CAAC;QAChC,KAAK,CAAC,CAAC,KAAK,CAAC,IAAI,CACf,KAAK,CACH,qHAAqH;YACnH,gGAAgG,CACnG,CACF,CAAA;IACH,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,UAAU,EAAE,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,UAAU,EAAE,CAAA;AAC/G,CAAC,CAAC,CAAA","sourcesContent":["/**\n * Runs one ACP prompt turn against a Capy thread: create or follow up, then stream until the\n * thread settles. Reconnects resume from the last transcript cursor, so nothing is shown twice.\n */\nimport { randomUUID } from \"node:crypto\"\nimport { existsSync } from \"node:fs\"\nimport { mkdir, writeFile } from \"node:fs/promises\"\nimport { basename, isAbsolute, join } from \"node:path\"\nimport { pathToFileURL } from \"node:url\"\nimport type { ContentBlock, SessionUpdate, StopReason, ToolKind } from \"@agentclientprotocol/sdk\"\nimport { Duration, Effect, Option, Result, Stream } from \"effect\"\nimport { CapyClient, type CapyError, CapyTransportError, describeError, type FileUpload, isTransient, type MessageFile, type ModelSelection } from \"./capy/client.js\"\nimport type { MessageAttachment } from \"./capy/events.js\"\nimport type { ChangeTracker, FileChange } from \"./changes.js\"\nimport type { DeviceWorkspace } from \"./workspace.js\"\nimport { closedTools, fileChangeUpdate, finishTools, initialTurn, step, turnComplete, type TurnSignal, type TurnState } from \"./translate.js\"\n\nexport interface ThreadTarget {\n readonly projectId: string\n readonly deviceId: string\n readonly workspace: DeviceWorkspace\n}\n\nexport interface TurnInput {\n readonly threadId: string | undefined\n readonly cursor: string | undefined\n readonly text: string\n /** Images and other media from the prompt, attached to the Capy message. */\n readonly files?: ReadonlyArray<FileUpload> | undefined\n /** Where a new thread's first-prompt files are saved for the agent to read (see below). */\n readonly attachmentsDir: string\n readonly model: ModelSelection\n readonly target: ThreadTarget\n readonly waitingLimitMs: number\n /** Resolves when the client cancels the prompt. */\n readonly cancelled: Effect.Effect<void>\n readonly emit: (update: SessionUpdate) => Effect.Effect<void>\n /** Watches the folder the thread works in (the open folder, or Capy's worktree) so edits reach the client as diffs. */\n readonly changes?: ChangeTracker | undefined\n /** Called whenever the resume cursor advances, so a restarted adapter picks up exactly there. */\n readonly onCursor?: ((threadId: string, cursor: string) => Effect.Effect<void>) | undefined\n}\n\nexport interface TurnResult {\n /** Undefined only when a first prompt was cancelled before its thread was created. */\n readonly threadId: string | undefined\n readonly cursor: string | undefined\n readonly stopReason: StopReason\n}\n\nconst MAX_IDLE_RECHECKS = 5\n/** How long an `until=run` connection may stay open after the turn ended before it is dropped. */\nconst END_GRACE_MS = 10_000\nconst CANCEL_GRACE = Duration.seconds(20)\n/** Failed reads in a row before the turn gives up on the connection: about four minutes of backoff. */\nconst MAX_FAILURES = 12\nconst backoff = (attempt: number) => Duration.millis(Math.min(30_000, 250 * 2 ** attempt))\n\nconst chunk = (text: string): SessionUpdate => ({ sessionUpdate: \"agent_message_chunk\", content: { type: \"text\", text } })\n\n/** Kinds of calls that cannot write files: changes seen while one ran are not its doing. */\nconst READ_ONLY: ReadonlySet<ToolKind | undefined> = new Set([\"read\", \"search\", \"fetch\", \"think\"])\n\nexport const titleOf = (text: string) => {\n const line = text.split(\"\\n\").find((l) => l.trim() !== \"\")?.trim() ?? \"capy-acp session\"\n return line.length > 80 ? `${line.slice(0, 77)}…` : line\n}\n\ntype Outcome = \"ended\" | \"failed\" | \"archived\" | \"waiting-limit\" | \"cancelled\" | \"lost\" | \"not-started\"\n\nconst attachedLabel = (files: ReadonlyArray<{ readonly name: string }>) => `Attached: ${files.map((f) => f.name).join(\", \")}`\n\nconst savedNote = (paths: ReadonlyArray<string>) =>\n paths.length === 0 ? \"\" : `Attached files, saved on this machine:\\n${paths.map((path) => `- ${path}`).join(\"\\n\")}`\n\n/** Writes a prompt's files under a fresh directory (owner-only) and returns their paths. */\nconst saveAttachments = (dir: string, files: ReadonlyArray<FileUpload>): Effect.Effect<ReadonlyArray<string>, CapyTransportError> =>\n Effect.tryPromise({\n try: async () => {\n const folder = join(dir, randomUUID())\n await mkdir(folder, { recursive: true, mode: 0o700 })\n const used = new Set<string>()\n const paths: Array<string> = []\n for (const file of files) {\n // Names come from the client: keep the last path segment only, and never reuse one. Characters\n // Windows forbids go too (a `:` would write an NTFS alternate stream of another file).\n const base = basename(file.name.replace(/\\\\/g, \"/\")).replace(/[<>:\"|?*\\x00-\\x1f]/g, \"_\").replace(/^\\.+/, \"\") || \"attachment\"\n let name = base\n for (let n = 2; used.has(name); n++) name = `${n}-${base}`\n used.add(name)\n const path = join(folder, name)\n await writeFile(path, file.bytes, { mode: 0o600 })\n paths.push(path)\n }\n return paths\n },\n catch: (cause) => new CapyTransportError({ message: `Could not save the attachments for Capy: ${String(cause)}`, cause })\n })\n\nconst formatBytes = (n: number) => (n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1024 ** 2).toFixed(1)} MB`)\n\n/**\n * A link to a file on a transcript entry. A file the agent made on this machine links to its\n * path; anything else gets Capy's short-lived download URL. Never fails: without either, the\n * file is named in text.\n */\nexport const fileLink = (capy: CapyClient[\"Service\"], threadId: string, file: MessageAttachment): Effect.Effect<ContentBlock> =>\n Effect.gen(function*() {\n // Capy reports Windows paths with forward slashes (`C:/Users/…`); isAbsolute takes either form.\n const local = file.sourcePath !== undefined && isAbsolute(file.sourcePath) && existsSync(file.sourcePath)\n const uri = local\n ? pathToFileURL(file.sourcePath!).href\n : yield* capy.attachmentUrl(threadId, file.fileId).pipe(Effect.orElseSucceed(() => undefined))\n const details = [file.mediaType, file.sizeBytes === undefined ? undefined : formatBytes(file.sizeBytes)].filter((d) => d !== undefined)\n if (uri === undefined) return { type: \"text\", text: `\\n\\n[Capy attached ${file.name}]` }\n return {\n type: \"resource_link\",\n uri,\n name: file.name,\n ...(file.title === undefined ? {} : { title: file.title }),\n ...(file.mediaType === undefined ? {} : { mimeType: file.mediaType }),\n ...(file.sizeBytes === undefined ? {} : { size: file.sizeBytes }),\n ...(details.length > 0 ? { description: details.join(\", \") } : {})\n }\n })\n\nexport const runTurn = (input: TurnInput): Effect.Effect<TurnResult, CapyError, CapyClient> =>\n Effect.gen(function*() {\n const capy = yield* CapyClient\n const tracker = input.changes\n // Before the message goes out, so the user's own uncommitted edits are not credited to Capy.\n if (tracker !== undefined) yield* tracker.baseline\n\n let threadId = input.threadId\n const attachments = input.files ?? []\n // Thread create takes text only. Files sent right after it race the agent's first step (a\n // fast model answers \"no image came through\"), so the first message names copies saved on\n // this machine instead, which is where the device agent runs and can read them. Follow-ups\n // upload first, so a failed upload sends nothing.\n const prepare = threadId === undefined\n ? (attachments.length === 0 ? Effect.succeed([]) : saveAttachments(input.attachmentsDir, attachments)).pipe(\n Effect.map((saved) => ({ saved, uploaded: [] as ReadonlyArray<MessageFile> }))\n )\n : capy.uploadFiles(attachments).pipe(Effect.map((uploaded) => ({ saved: [] as ReadonlyArray<string>, uploaded })))\n // Uploads can take a while. A cancel before the message goes out sends nothing. The send itself\n // is not raced: a request Capy may already have accepted is followed through and interrupted.\n const prepared = yield* Effect.raceFirst(prepare.pipe(Effect.map(Option.some)), input.cancelled.pipe(Effect.as(Option.none())))\n if (Option.isNone(prepared)) return { threadId, cursor: input.cursor, stopReason: \"cancelled\" as const }\n const { saved, uploaded } = prepared.value\n\n if (threadId === undefined) {\n const text = [input.text, savedNote(saved)].filter((part) => part !== \"\").join(\"\\n\\n\")\n const thread = yield* capy.createThread({\n requestId: randomUUID(),\n projectId: input.target.projectId,\n title: titleOf(input.text !== \"\" ? input.text : attachments.map((f) => f.name).join(\", \")),\n message: text,\n model: input.model,\n device: { deviceId: input.target.deviceId, workspace: input.target.workspace }\n })\n threadId = thread.id\n } else {\n const text = input.text !== \"\" ? input.text : attachedLabel(uploaded)\n yield* capy.sendMessage(threadId, { text, clientKey: randomUUID(), model: input.model, ...(uploaded.length > 0 ? { files: uploaded } : {}) })\n }\n const id = threadId\n\n let state: TurnState = initialTurn(input.cursor)\n let waitingSince: number | undefined\n let idleRechecks = 0\n /** Stream events seen this turn (heartbeats aside): tells a productive read from an empty one. */\n let received = 0\n /** Failed reads or status checks in a row; any event resets it. */\n let failures = 0\n /** Reads in a row that closed without an event while the thread was still busy. */\n let emptyReads = 0\n /** Why the turn gave up on the connection, for the closing note. */\n let lost: CapyError | undefined\n /** Set once the client cancels; the loop keeps reading until the thread settles. */\n let cancelRequested = false\n\n /**\n * Shows changes on the tool call that made them. Each call is credited once, when it closes (or at the\n * end of the turn if it never did), so its content is never replaced. Changes with no call to credit\n * (`undefined`) get an item of their own that says they came from outside Capy's tool calls.\n */\n const showChanges = (toolCallId: string | undefined, changes: ReadonlyArray<FileChange>, status: \"completed\" | \"failed\") => {\n if (changes.length === 0) return Effect.void\n return toolCallId === undefined\n ? input.emit(fileChangeUpdate(`capy-acp-changes-${randomUUID()}`, changes, { outside: true }))\n : input.emit(fileChangeUpdate(toolCallId, changes, { status }))\n }\n\n const apply = (event: Parameters<typeof step>[1]): Effect.Effect<TurnSignal | undefined> =>\n Effect.gen(function*() {\n if (event._tag !== \"Heartbeat\") received++\n const before = state.cursor\n const running = [...state.tools.values()].some((tool) => !tool.done)\n const result = step(cancelRequested ? { ...state, cancelled: true } : state, event)\n state = result.state\n const updates = result.updates\n // A call starts while none runs: the changes since the last look were not made by a Capy tool call.\n const starts = updates.some((u) => u.sessionUpdate === \"tool_call\" && u.status === \"in_progress\")\n if (starts && !running && tracker !== undefined) yield* showChanges(undefined, yield* tracker.collect, \"completed\")\n yield* Effect.forEach(updates, input.emit, { discard: true })\n for (const file of result.files ?? []) {\n yield* input.emit({ sessionUpdate: \"agent_message_chunk\", content: yield* fileLink(capy, id, file) })\n }\n if (state.cursor !== undefined && state.cursor !== before && input.onCursor !== undefined) {\n yield* input.onCursor(id, state.cursor)\n }\n const last = closedTools(updates).at(-1)\n if (last !== undefined && tracker !== undefined) {\n // The call just finished, so whatever changed on disk since the last look is its doing, unless it cannot write.\n yield* showChanges(READ_ONLY.has(last.kind) ? undefined : last.toolCallId, yield* tracker.collect, last.status)\n }\n return result.signal\n })\n\n // Reads one stream connection; resolves with the signal that ended it, if any.\n // An `until=run` connection is read until the server closes it, even after `Ended`: entries\n // that streamed no fragments commit after `idle`, and the server sends them before `done`.\n // Should it not close, the next frame (a heartbeat comes every 15 s) after a grace ends it.\n const readOnce = (follow: boolean): Effect.Effect<TurnSignal | undefined, CapyError> => {\n let last: TurnSignal | undefined\n let endedAt: number | undefined\n const stream = capy.stream(id, { cursor: state.cursor, untilRun: !follow }).pipe(\n Stream.mapEffect(apply),\n Stream.takeUntil((signal) => {\n if (signal !== undefined) last = signal\n if (signal?._tag === \"Ended\") endedAt ??= Date.now()\n if (signal === undefined || signal._tag === \"Waiting\") return endedAt !== undefined && Date.now() - endedAt > END_GRACE_MS\n return follow || signal._tag !== \"Ended\"\n }),\n Stream.runDrain\n )\n if (!follow) return stream.pipe(Effect.map(() => last))\n // While the thread waits, hold a live stream open until it wakes or the waiting limit passes.\n const remaining = Math.max(0, input.waitingLimitMs - (Date.now() - (waitingSince ?? Date.now())))\n return stream.pipe(\n Effect.timeoutOption(Duration.millis(remaining)),\n Effect.map((done) => (Option.isNone(done) ? ({ _tag: \"Waiting\" } as const) : last))\n )\n }\n\n /**\n * A failed read or status check. Transient failures (a dropped connection, a 5xx) wait and try\n * again from the cursor, so nothing is shown twice; after too many in a row the turn ends with\n * a note instead of an error, since Capy keeps working either way. Anything else fails the turn.\n */\n const recover = (error: CapyError): Effect.Effect<boolean, CapyError> => {\n // A cursor Capy no longer accepts would fail every read. Reading without one can repeat\n // entries the client already has, which beats a session that can never stream again.\n const badCursor = error._tag === \"CapyApiError\" && error.status === 400 && /cursor/i.test(error.message)\n if (badCursor && state.cursor !== undefined) {\n state = { ...state, cursor: undefined }\n } else if (!isTransient(error)) {\n return Effect.fail(error)\n }\n if (++failures > MAX_FAILURES) {\n lost = error\n return Effect.succeed(false)\n }\n return Effect.sleep(backoff(failures)).pipe(Effect.as(true))\n }\n\n const loop: Effect.Effect<Outcome, CapyError> = Effect.gen(function*() {\n for (;;) {\n const follow = state.status === \"waiting\"\n const seen = received\n const read = yield* Effect.result(readOnce(follow))\n if (received > seen) failures = 0\n if (Result.isFailure(read)) {\n if (!(yield* recover(read.failure))) return \"lost\"\n continue\n }\n const signal = read.success\n switch (signal?._tag) {\n case \"Ended\":\n // A live (waiting) connection stops at `idle`; drain the rest with an `until=run` read.\n if (!follow) return \"ended\"\n state = { ...state, status: \"idle\" }\n continue\n case \"Failed\":\n return \"failed\"\n case \"Archived\":\n return \"archived\"\n case \"StreamError\":\n if (signal.code === \"unauthorized\" || signal.code === \"forbidden\") return \"failed\"\n break\n case \"Waiting\":\n waitingSince ??= Date.now()\n if (Date.now() - waitingSince >= input.waitingLimitMs) return \"waiting-limit\"\n break\n default:\n break\n }\n // The connection closed (run ended, `done`, or a drop): ask the thread where it stands.\n const checked = yield* Effect.result(capy.getThread(id))\n if (Result.isFailure(checked)) {\n if (!(yield* recover(checked.failure))) return \"lost\"\n continue\n }\n const thread = checked.success\n state = { ...state, status: thread.status }\n if (thread.status === \"idle\") {\n if (state.active && turnComplete(state)) return \"ended\"\n // Capy never started on the message: tell the user rather than end silently.\n if (++idleRechecks > MAX_IDLE_RECHECKS) return state.active ? \"ended\" : \"not-started\"\n // Not picked up yet, or a reply has not committed: read again from the cursor.\n yield* Effect.sleep(Duration.seconds(1))\n } else if (thread.status === \"failed\") {\n return \"failed\"\n } else if (thread.status === \"archived\") {\n return \"archived\"\n } else {\n if (thread.status === \"waiting\") {\n waitingSince ??= Date.now()\n if (Date.now() - waitingSince >= input.waitingLimitMs) return \"waiting-limit\"\n }\n // Still busy, but the stream closed with nothing new (or sent an error frame): don't spin.\n emptyReads = received > seen ? 0 : emptyReads + 1\n if (emptyReads > 0) yield* Effect.sleep(backoff(Math.min(emptyReads, 4)))\n }\n }\n })\n\n // Cancel = interrupt the Capy thread and let the one running loop settle, so the cursor stays right.\n // If the thread does not settle within the grace period, the loop is abandoned.\n const cancel = input.cancelled.pipe(\n Effect.tap(() => Effect.sync(() => (cancelRequested = true))),\n Effect.andThen(capy.interrupt(id).pipe(Effect.ignore)),\n Effect.andThen(Effect.sleep(CANCEL_GRACE)),\n Effect.as(\"cancelled\" as const)\n )\n\n // A failure after the message went out is reported in the reply, not as a request error: Capy\n // has the message and keeps working, and an error invites a resend that would duplicate it.\n const raced = yield* Effect.result(Effect.raceFirst(loop, cancel))\n if (Result.isFailure(raced)) lost = raced.failure\n const outcome: Outcome = cancelRequested ? \"cancelled\" : Result.isSuccess(raced) ? raced.success : \"lost\"\n\n const closeAs = outcome === \"ended\" || outcome === \"waiting-limit\" ? \"completed\" : \"failed\"\n const closed = finishTools(state, closeAs)\n state = closed.state\n yield* Effect.forEach(closed.updates, input.emit, { discard: true })\n // A last look catches edits from a call that never reported completing (interrupts, a final\n // entry that lagged). With no call left open, the edits came after the last call finished.\n if (tracker !== undefined) {\n const stillOpen = closedTools(closed.updates).at(-1)?.toolCallId\n yield* showChanges(stillOpen, yield* tracker.collect, closeAs)\n }\n if (outcome === \"failed\") yield* input.emit(chunk(\"\\n\\n**Capy reported that this run failed.** The thread keeps its transcript. Send another message to retry.\"))\n if (outcome === \"archived\") yield* input.emit(chunk(\"\\n\\n**This Capy thread is archived.** Start a new chat to continue.\"))\n if (outcome === \"lost\") {\n yield* input.emit(\n chunk(\n `\\n\\n**Lost the connection to Capy** (${lost === undefined ? \"unknown error\" : describeError(lost)}). Capy may still be ` +\n \"working in its thread. Your next message here continues from where this reply stopped.\"\n )\n )\n }\n if (outcome === \"not-started\") {\n yield* input.emit(\n chunk(\n \"**Capy has not started on this message yet.** Check that the Capy desktop app or `capy dock` runs on this computer \" +\n \"and is signed in. The message stays in the queue, and Capy starts it when the device is back.\"\n )\n )\n }\n if (outcome === \"waiting-limit\") {\n yield* input.emit(\n chunk(\n \"\\n\\n**Capy is waiting on a background command.** It continues in its thread on its own, and the Capy app shows the \" +\n \"rest. A new message here stops the wait, so send one only when you want Capy to change course.\"\n )\n )\n }\n return { threadId: id, cursor: state.cursor, stopReason: outcome === \"cancelled\" ? \"cancelled\" : \"end_turn\" }\n })\n"]}
|
package/dist/workspace.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Session mapper: the folder an ACP client opens
|
|
2
|
+
* Session mapper: the folder an ACP client opens, then its git remotes, then a Capy project, then a device workspace.
|
|
3
3
|
*
|
|
4
|
-
* The device id
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* The device id comes from the files Capy keeps on this machine (desktop app or `capy dock`), read only: the
|
|
5
|
+
* API has no endpoint that lists devices. The list of linked folders comes from there too, but only as a
|
|
6
|
+
* hint. Capy itself checks the folder when the thread starts, so a list that is old, moved or unreadable
|
|
7
|
+
* costs at most one refused thread create, which the reply turns into the fix.
|
|
7
8
|
*/
|
|
8
9
|
import { execFile } from "node:child_process";
|
|
9
10
|
import { readFile, realpath } from "node:fs/promises";
|
|
10
|
-
import { join, posix, win32 } from "node:path";
|
|
11
|
+
import { join, posix, relative, resolve, win32 } from "node:path";
|
|
11
12
|
import { promisify } from "node:util";
|
|
13
|
+
import { manyOrganizations, noDevice, noGitHubRemote, notGit, notInProject, notLinked, ProblemError, unreadableDeviceFile } from "./problems.js";
|
|
12
14
|
const run = promisify(execFile);
|
|
13
15
|
/** Path equality across platforms: Windows and macOS file systems ignore case by default. */
|
|
14
16
|
export const samePath = (a, b, platform = process.platform) => {
|
|
@@ -18,25 +20,42 @@ export const samePath = (a, b, platform = process.platform) => {
|
|
|
18
20
|
};
|
|
19
21
|
return norm(a) === norm(b);
|
|
20
22
|
};
|
|
21
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* `owner/repo` from a remote URL, lowercased for matching. Any host name counts, because ssh configs often
|
|
25
|
+
* give github.com another name (`git@github-work:acme/app.git`). Only repositories of the user's Capy
|
|
26
|
+
* projects can match, and Capy works only with GitHub.com.
|
|
27
|
+
*/
|
|
22
28
|
export const parseRemote = (url) => {
|
|
23
|
-
const
|
|
24
|
-
|
|
29
|
+
const trimmed = url.trim();
|
|
30
|
+
// `scheme://host/path`, or scp style `user@host:path`.
|
|
31
|
+
const path = /^[a-z][a-z0-9+.-]*:\/\/[^/]*\/(.*)$/i.exec(trimmed)?.[1] ?? /^[^/:\s]+:(?!\/\/)(.*)$/.exec(trimmed)?.[1];
|
|
32
|
+
const parts = path?.replace(/\/+$/, "").replace(/\.git$/i, "").split("/").filter((part) => part !== "");
|
|
33
|
+
return parts !== undefined && parts.length >= 2 ? parts.slice(-2).join("/").toLowerCase() : undefined;
|
|
25
34
|
};
|
|
26
35
|
export const resolveWorkspace = (input) => {
|
|
27
|
-
const unresolved = (
|
|
28
|
-
if (input.gitRoot === undefined
|
|
29
|
-
return unresolved(
|
|
30
|
-
"capy-acp runs Capy threads on a repository that belongs to a Capy project.");
|
|
31
|
-
}
|
|
32
|
-
const repo = input.repo;
|
|
33
|
-
const project = input.projects.find((p) => p.repos.some((r) => r.repoFullName.toLowerCase() === repo));
|
|
34
|
-
if (project === undefined) {
|
|
35
|
-
return unresolved(`No Capy project includes ${repo}. Add the repository to a project at https://capy.ai, then retry.`);
|
|
36
|
-
}
|
|
37
|
-
const base = { projectId: project.id, projectName: project.name, repo };
|
|
36
|
+
const unresolved = (problem) => ({ _tag: "Unresolved", problem });
|
|
37
|
+
if (input.gitRoot === undefined)
|
|
38
|
+
return unresolved(notGit(input.cwd));
|
|
38
39
|
const gitRoot = input.gitRoot;
|
|
39
40
|
const here = input.linked.find((folder) => samePath(folder.realRoot ?? folder.root, gitRoot) || samePath(folder.root, gitRoot));
|
|
41
|
+
// A linked folder lists its repositories, so a clone whose remotes name none of them still matches.
|
|
42
|
+
const candidates = [...new Set([...input.repos, ...(here?.repos ?? []).map((r) => r.toLowerCase())])];
|
|
43
|
+
const matches = (repo) => input.projects.find((p) => p.repos.some((r) => r.repoFullName.toLowerCase() === repo));
|
|
44
|
+
const repo = candidates.find((candidate) => matches(candidate) !== undefined);
|
|
45
|
+
const project = repo === undefined ? undefined : matches(repo);
|
|
46
|
+
if (repo === undefined || project === undefined) {
|
|
47
|
+
return unresolved(candidates.length === 0 ? noGitHubRemote(gitRoot) : notInProject(candidates));
|
|
48
|
+
}
|
|
49
|
+
const sameRepo = input.linked.find((folder) => folder !== here && folder.repos.some((r) => r.toLowerCase() === repo));
|
|
50
|
+
const notLinkedHere = notLinked({
|
|
51
|
+
root: gitRoot,
|
|
52
|
+
repo,
|
|
53
|
+
projectId: project.id,
|
|
54
|
+
projectName: project.name,
|
|
55
|
+
device: input.device,
|
|
56
|
+
sameRepoRoot: sameRepo?.root
|
|
57
|
+
});
|
|
58
|
+
const base = { projectId: project.id, projectName: project.name, repo, notLinked: notLinkedHere };
|
|
40
59
|
if (here !== undefined) {
|
|
41
60
|
return input.mode === "linked"
|
|
42
61
|
? { _tag: "Resolved", value: { ...base, workspace: { kind: "linked", root: here.root }, note: undefined } }
|
|
@@ -45,11 +64,10 @@ export const resolveWorkspace = (input) => {
|
|
|
45
64
|
value: {
|
|
46
65
|
...base,
|
|
47
66
|
workspace: { kind: "worktree" },
|
|
48
|
-
note: "Capy is working in its own git worktree
|
|
67
|
+
note: "Capy is working in its own git worktree (in Capy's worktree folder, ~/.capy/worktrees by default), not in this folder (CAPY_ACP_WORKSPACE=worktree)."
|
|
49
68
|
}
|
|
50
69
|
};
|
|
51
70
|
}
|
|
52
|
-
const sameRepo = input.linked.find((folder) => folder.repos.some((r) => r.toLowerCase() === repo));
|
|
53
71
|
if (sameRepo !== undefined && input.allowWorktreeFallback) {
|
|
54
72
|
return {
|
|
55
73
|
_tag: "Resolved",
|
|
@@ -57,49 +75,55 @@ export const resolveWorkspace = (input) => {
|
|
|
57
75
|
...base,
|
|
58
76
|
workspace: { kind: "worktree" },
|
|
59
77
|
note: `${input.gitRoot} is not linked to this Capy device, so Capy is working in a new worktree of ${sameRepo.root} ` +
|
|
60
|
-
"
|
|
78
|
+
"in Capy's worktree folder (~/.capy/worktrees by default). Its edits will not appear in this folder."
|
|
61
79
|
}
|
|
62
80
|
};
|
|
63
81
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
82
|
+
if (input.mode === "worktree") {
|
|
83
|
+
// A worktree is made from a linked folder of the repository, and none is known.
|
|
84
|
+
return unresolved(notLinkedHere);
|
|
85
|
+
}
|
|
86
|
+
// Not in the local list, which can be older than Capy's own, or unreadable. Capy checks the root when
|
|
87
|
+
// the thread starts and refuses one it does not link; the reply then gives `notLinked`. Git prints
|
|
88
|
+
// Windows paths with forward slashes, so the root goes in the form Windows gives it.
|
|
89
|
+
const opened = input.openedRoot ?? gitRoot;
|
|
90
|
+
const root = (input.platform ?? process.platform) === "win32" ? win32.normalize(opened) : opened;
|
|
91
|
+
return { _tag: "Resolved", value: { ...base, workspace: { kind: "linked", root }, note: undefined } };
|
|
71
92
|
};
|
|
72
93
|
const readJson = async (path) => JSON.parse(await readFile(path, "utf8"));
|
|
73
94
|
/**
|
|
74
|
-
* The paired device
|
|
95
|
+
* The paired device. With several organizations, `CAPY_DEVICE_ID` picks one explicitly.
|
|
75
96
|
*
|
|
76
97
|
* A machine is paired either by the desktop app (`device-ids.json`, one id per organization) or by the headless
|
|
77
98
|
* `capy dock` daemon, which records its one device in `~/.capy/dock/status.json`. Both share `~/.capy/device`.
|
|
78
99
|
*/
|
|
79
|
-
export const
|
|
100
|
+
export const readDevice = async (config) => {
|
|
80
101
|
if (config.deviceIdOverride)
|
|
81
|
-
return config.deviceIdOverride;
|
|
102
|
+
return { id: config.deviceIdOverride, kind: undefined };
|
|
82
103
|
const desktop = join(config.capyDesktopConfigDir, "device-ids.json");
|
|
104
|
+
const checked = [];
|
|
83
105
|
let ids = [];
|
|
84
106
|
try {
|
|
85
107
|
const data = (await readJson(desktop));
|
|
86
108
|
ids = Object.values(data.orgs ?? {}).filter((id) => typeof id === "string" && id !== "");
|
|
109
|
+
checked.push({ path: desktop, found: "no device" });
|
|
87
110
|
}
|
|
88
111
|
catch (error) {
|
|
89
112
|
if (error.code !== "ENOENT") {
|
|
90
|
-
throw new
|
|
113
|
+
throw new ProblemError(unreadableDeviceFile(desktop, error instanceof Error ? error.message : String(error)));
|
|
91
114
|
}
|
|
115
|
+
checked.push({ path: desktop, found: "missing" });
|
|
92
116
|
}
|
|
93
117
|
if (ids.length === 1 && ids[0])
|
|
94
|
-
return ids[0];
|
|
118
|
+
return { id: ids[0], kind: "desktop" };
|
|
95
119
|
if (ids.length > 1)
|
|
96
|
-
throw new
|
|
120
|
+
throw new ProblemError(manyOrganizations(ids.length));
|
|
97
121
|
const dock = join(config.capyHome, "dock", "status.json");
|
|
98
|
-
const docked = await readJson(dock).then((data) => data.deviceId, () => undefined);
|
|
99
|
-
if (typeof docked === "string" && docked !== "")
|
|
100
|
-
return docked;
|
|
101
|
-
|
|
102
|
-
|
|
122
|
+
const docked = await readJson(dock).then((data) => ({ found: "no device", id: data.deviceId }), () => ({ found: "missing", id: undefined }));
|
|
123
|
+
if (typeof docked.id === "string" && docked.id !== "")
|
|
124
|
+
return { id: docked.id, kind: "dock" };
|
|
125
|
+
checked.push({ path: dock, found: docked.found });
|
|
126
|
+
throw new ProblemError(noDevice(checked));
|
|
103
127
|
};
|
|
104
128
|
export const readLinkedFolders = async (config) => {
|
|
105
129
|
try {
|
|
@@ -123,7 +147,18 @@ export const readGit = async (cwd) => {
|
|
|
123
147
|
}
|
|
124
148
|
};
|
|
125
149
|
const gitRoot = await git("rev-parse", "--show-toplevel");
|
|
126
|
-
|
|
127
|
-
|
|
150
|
+
// `git remote -v` prints URLs after `insteadOf` rewrites: "<name>\t<url> (fetch)".
|
|
151
|
+
const remotes = gitRoot === undefined ? [] : ((await git("remote", "-v")) ?? "").split("\n").flatMap((line) => {
|
|
152
|
+
const match = /^(\S+)\s+(\S+)\s+\(fetch\)$/.exec(line.trim());
|
|
153
|
+
return match ? [{ name: match[1], url: match[2] }] : [];
|
|
154
|
+
});
|
|
155
|
+
const ordered = [...remotes.filter((r) => r.name === "origin"), ...remotes.filter((r) => r.name !== "origin")];
|
|
156
|
+
const repos = [...new Set(ordered.flatMap((remote) => parseRemote(remote.url) ?? []))];
|
|
157
|
+
// Git resolves symlinks (macOS `/tmp` is `/private/tmp`), and Capy keeps the spelling the user linked,
|
|
158
|
+
// which is most likely the one the client opened.
|
|
159
|
+
const openedRoot = gitRoot === undefined
|
|
160
|
+
? undefined
|
|
161
|
+
: await realpath(cwd).then((real) => resolve(cwd, relative(real, gitRoot)), () => gitRoot);
|
|
162
|
+
return { gitRoot, openedRoot, repos };
|
|
128
163
|
};
|
|
129
164
|
//# sourceMappingURL=workspace.js.map
|
package/dist/workspace.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace.js","sourceRoot":"","sources":["../src/workspace.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAA;AAC7C,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AACrD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAGrC,MAAM,GAAG,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAA;AAU/B,6FAA6F;AAC7F,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,QAAQ,GAAoB,OAAO,CAAC,QAAQ,EAAW,EAAE;IACtG,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,EAAE;QACzB,MAAM,QAAQ,GAAG,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CA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,CAAA;QACnF,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,SAAS,CAAA;QAClB,CAAC;IACH,CAAC,CAAA;IACD,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,WAAW,EAAE,iBAAiB,CAAC,CAAA;IACzD,MAAM,MAAM,GAAG,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAA;IAC3F,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,MAAM,CAAC,EAAE,CAAA;AAClF,CAAC,CAAA","sourcesContent":["/**\n * Session mapper: the folder an ACP client opens → git remote → Capy project → device workspace.\n *\n * The device id and linked folders are read from the files Capy keeps on this machine (desktop app or\n * `capy dock`), read only. Capy owns those files (it rewrites them from server state), and the API has no\n * endpoint to list devices or link folders, so reading them is the only way to target this machine.\n */\nimport { execFile } from \"node:child_process\"\nimport { readFile, realpath } from \"node:fs/promises\"\nimport { join, posix, win32 } from \"node:path\"\nimport { promisify } from \"node:util\"\nimport type { AdapterConfig } from \"./config.js\"\n\nconst run = promisify(execFile)\n\nexport interface LinkedFolder {\n /** The root exactly as Capy stores it; thread creates must send this string. */\n readonly root: string\n readonly repos: ReadonlyArray<string>\n /** The root with symlinks resolved (macOS `/tmp` is `/private/tmp`), for matching only. */\n readonly realRoot?: string\n}\n\n/** Path equality across platforms: Windows and macOS file systems ignore case by default. */\nexport const samePath = (a: string, b: string, platform: NodeJS.Platform = process.platform): boolean => {\n const norm = (p: string) => {\n const resolved = (platform === \"win32\" ? win32 : posix).resolve(p)\n return platform === \"win32\" || platform === \"darwin\" ? resolved.toLowerCase() : resolved\n }\n return norm(a) === norm(b)\n}\n\nexport interface ProjectSummary {\n readonly id: string\n readonly name: string\n readonly repos: ReadonlyArray<{ readonly repoFullName: string }>\n}\n\nexport type DeviceWorkspace =\n | { readonly kind: \"linked\"; readonly root: string }\n | { readonly kind: \"worktree\" }\n\nexport interface ResolvedWorkspace {\n readonly projectId: string\n readonly projectName: string\n readonly repo: string\n readonly workspace: DeviceWorkspace\n /** Shown to the user once, in the first reply, when the thread will not edit the open folder. */\n readonly note: string | undefined\n}\n\nexport type Resolution =\n | { readonly _tag: \"Resolved\"; readonly value: ResolvedWorkspace }\n | { readonly _tag: \"Unresolved\"; readonly message: string }\n\n/** `owner/repo` from an https or ssh GitHub remote, lowercased for matching. */\nexport const parseRemote = (url: string): string | undefined => {\n const match = /github\\.com[:/]+([^/\\s]+)\\/([^/\\s]+?)(?:\\.git)?\\/?$/i.exec(url.trim())\n return match ? `${match[1]}/${match[2]}`.toLowerCase() : undefined\n}\n\nexport const resolveWorkspace = (input: {\n readonly cwd: string\n readonly gitRoot: string | undefined\n readonly repo: string | undefined\n readonly linked: ReadonlyArray<LinkedFolder>\n readonly projects: ReadonlyArray<ProjectSummary>\n readonly mode: AdapterConfig[\"workspaceMode\"]\n readonly allowWorktreeFallback: boolean\n}): Resolution => {\n const unresolved = (message: string): Resolution => ({ _tag: \"Unresolved\", message })\n if (input.gitRoot === undefined || input.repo === undefined) {\n return unresolved(\n `${input.cwd} is not a clone of a GitHub repository (no \"origin\" remote). ` +\n \"capy-acp runs Capy threads on a repository that belongs to a Capy project.\"\n )\n }\n const repo = input.repo\n const project = input.projects.find((p) => p.repos.some((r) => r.repoFullName.toLowerCase() === repo))\n if (project === undefined) {\n return unresolved(`No Capy project includes ${repo}. Add the repository to a project at https://capy.ai, then retry.`)\n }\n const base = { projectId: project.id, projectName: project.name, repo }\n const gitRoot = input.gitRoot\n const here = input.linked.find((folder) => samePath(folder.realRoot ?? folder.root, gitRoot) || samePath(folder.root, gitRoot))\n if (here !== undefined) {\n return input.mode === \"linked\"\n ? { _tag: \"Resolved\", value: { ...base, workspace: { kind: \"linked\", root: here.root }, note: undefined } }\n : {\n _tag: \"Resolved\",\n value: {\n ...base,\n workspace: { kind: \"worktree\" },\n note: \"Capy is working in its own git worktree under ~/.capy/worktrees, not in this folder (CAPY_ACP_WORKSPACE=worktree).\"\n }\n }\n }\n const sameRepo = input.linked.find((folder) => folder.repos.some((r) => r.toLowerCase() === repo))\n if (sameRepo !== undefined && input.allowWorktreeFallback) {\n return {\n _tag: \"Resolved\",\n value: {\n ...base,\n workspace: { kind: \"worktree\" },\n note:\n `${input.gitRoot} is not linked to this Capy device, so Capy is working in a new worktree of ${sameRepo.root} ` +\n \"under ~/.capy/worktrees. Its edits will not appear in this folder.\"\n }\n }\n }\n const fix =\n `Link ${input.gitRoot} to this device in Capy: open https://capy.ai/settings/projects, choose \"${project.name}\", ` +\n \"and add the folder under Project folders (or use Scan a folder in the Capy desktop app, or run `capy dock dirs add` \" +\n \"on a machine paired with capy dock). Then send your message again.\"\n const fallback =\n sameRepo === undefined\n ? \"\"\n : ` Or set CAPY_ACP_ALLOW_WORKTREE_FALLBACK=1 to work in a worktree of ${sameRepo.root} instead.`\n return unresolved(`${input.gitRoot} is not a linked folder on this Capy device. ${fix}${fallback}`)\n}\n\nconst readJson = async (path: string): Promise<unknown> => JSON.parse(await readFile(path, \"utf8\"))\n\n/**\n * The paired device's id. With several organizations, `CAPY_DEVICE_ID` picks one explicitly.\n *\n * A machine is paired either by the desktop app (`device-ids.json`, one id per organization) or by the headless\n * `capy dock` daemon, which records its one device in `~/.capy/dock/status.json`. Both share `~/.capy/device`.\n */\nexport const readDeviceId = async (config: AdapterConfig): Promise<string> => {\n if (config.deviceIdOverride) return config.deviceIdOverride\n const desktop = join(config.capyDesktopConfigDir, \"device-ids.json\")\n let ids: Array<string> = []\n try {\n const data = (await readJson(desktop)) as { orgs?: Record<string, unknown> }\n ids = Object.values(data.orgs ?? {}).filter((id): id is string => typeof id === \"string\" && id !== \"\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw new Error(`Could not read the Capy desktop app's device file ${desktop}: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n if (ids.length === 1 && ids[0]) return ids[0]\n if (ids.length > 1) throw new Error(`This machine is paired with ${ids.length} Capy organizations; set CAPY_DEVICE_ID to choose one.`)\n const dock = join(config.capyHome, \"dock\", \"status.json\")\n const docked = await readJson(dock).then(\n (data) => (data as { deviceId?: unknown }).deviceId,\n () => undefined\n )\n if (typeof docked === \"string\" && docked !== \"\") return docked\n throw new Error(\n `No paired Capy device found: neither ${desktop} nor ${dock} names one. Sign in to the Capy desktop app on this machine, ` +\n \"or pair it with `capy dock`, or set CAPY_DEVICE_ID (and CAPY_DESKTOP_CONFIG_DIR or CAPY_HOME if Capy keeps its files elsewhere).\"\n )\n}\n\nexport const readLinkedFolders = async (config: AdapterConfig): Promise<ReadonlyArray<LinkedFolder>> => {\n try {\n const data = (await readJson(join(config.capyHome, \"device\", \"workspaces.json\"))) as {\n folders?: ReadonlyArray<{ root?: unknown; repos?: unknown }>\n }\n const folders = (data.folders ?? []).flatMap((folder) =>\n typeof folder.root === \"string\"\n ? [{ root: folder.root, repos: Array.isArray(folder.repos) ? folder.repos.filter((r) => typeof r === \"string\") : [] }]\n : []\n )\n return Promise.all(\n folders.map(async (folder) => ({ ...folder, realRoot: await realpath(folder.root).catch(() => folder.root) }))\n )\n } catch {\n return []\n }\n}\n\nexport const readGit = async (cwd: string): Promise<{ gitRoot: string | undefined; repo: string | undefined }> => {\n const git = async (...args: Array<string>) => {\n try {\n return (await run(\"git\", [\"-C\", cwd, ...args], { timeout: 5_000 })).stdout.trim()\n } catch {\n return undefined\n }\n }\n const gitRoot = await git(\"rev-parse\", \"--show-toplevel\")\n const remote = gitRoot === undefined ? undefined : await git(\"remote\", \"get-url\", \"origin\")\n return { gitRoot, repo: remote === undefined ? undefined : parseRemote(remote) }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"workspace.js","sourceRoot":"","sources":["../src/workspace.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAA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CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAA;IAC9G,MAAM,KAAK,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAA;IACtF,uGAAuG;IACvG,kDAAkD;IAClD,MAAM,UAAU,GAAG,OAAO,KAAK,SAAS;QACtC,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,MAAM,QAAQ,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,CAAA;IAC5F,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,CAAA;AACvC,CAAC,CAAA","sourcesContent":["/**\n * Session mapper: the folder an ACP client opens, then its git remotes, then a Capy project, then a device workspace.\n *\n * The device id comes from the files Capy keeps on this machine (desktop app or `capy dock`), read only: the\n * API has no endpoint that lists devices. The list of linked folders comes from there too, but only as a\n * hint. Capy itself checks the folder when the thread starts, so a list that is old, moved or unreadable\n * costs at most one refused thread create, which the reply turns into the fix.\n */\nimport { execFile } from \"node:child_process\"\nimport { readFile, realpath } from \"node:fs/promises\"\nimport { join, posix, relative, resolve, win32 } from \"node:path\"\nimport { promisify } from \"node:util\"\nimport type { AdapterConfig } from \"./config.js\"\nimport {\n type DeviceFile,\n type DeviceKind,\n manyOrganizations,\n noDevice,\n noGitHubRemote,\n notGit,\n notInProject,\n notLinked,\n type Problem,\n ProblemError,\n unreadableDeviceFile\n} from \"./problems.js\"\n\nconst run = promisify(execFile)\n\nexport interface LinkedFolder {\n /** The root exactly as Capy stores it; thread creates must send this string. */\n readonly root: string\n readonly repos: ReadonlyArray<string>\n /** The root with symlinks resolved (macOS `/tmp` is `/private/tmp`), for matching only. */\n readonly realRoot?: string\n}\n\n/** Path equality across platforms: Windows and macOS file systems ignore case by default. */\nexport const samePath = (a: string, b: string, platform: NodeJS.Platform = process.platform): boolean => {\n const norm = (p: string) => {\n const resolved = (platform === \"win32\" ? win32 : posix).resolve(p)\n return platform === \"win32\" || platform === \"darwin\" ? resolved.toLowerCase() : resolved\n }\n return norm(a) === norm(b)\n}\n\nexport interface ProjectSummary {\n readonly id: string\n readonly name: string\n readonly repos: ReadonlyArray<{ readonly repoFullName: string }>\n}\n\nexport type DeviceWorkspace =\n | { readonly kind: \"linked\"; readonly root: string }\n | { readonly kind: \"worktree\" }\n\nexport interface ResolvedWorkspace {\n readonly projectId: string\n readonly projectName: string\n readonly repo: string\n readonly workspace: DeviceWorkspace\n /** Shown to the user once, in the first reply, when the thread will not edit the open folder. */\n readonly note: string | undefined\n /** What to show if Capy refuses the linked root: how to link the folder. */\n readonly notLinked: Problem\n}\n\nexport type Resolution =\n | { readonly _tag: \"Resolved\"; readonly value: ResolvedWorkspace }\n | { readonly _tag: \"Unresolved\"; readonly problem: Problem }\n\n/**\n * `owner/repo` from a remote URL, lowercased for matching. Any host name counts, because ssh configs often\n * give github.com another name (`git@github-work:acme/app.git`). Only repositories of the user's Capy\n * projects can match, and Capy works only with GitHub.com.\n */\nexport const parseRemote = (url: string): string | undefined => {\n const trimmed = url.trim()\n // `scheme://host/path`, or scp style `user@host:path`.\n const path = /^[a-z][a-z0-9+.-]*:\\/\\/[^/]*\\/(.*)$/i.exec(trimmed)?.[1] ?? /^[^/:\\s]+:(?!\\/\\/)(.*)$/.exec(trimmed)?.[1]\n const parts = path?.replace(/\\/+$/, \"\").replace(/\\.git$/i, \"\").split(\"/\").filter((part) => part !== \"\")\n return parts !== undefined && parts.length >= 2 ? parts.slice(-2).join(\"/\").toLowerCase() : undefined\n}\n\nexport const resolveWorkspace = (input: {\n readonly cwd: string\n readonly gitRoot: string | undefined\n /** The git root in the spelling of the opened folder, which git does not keep (see `readGit`). */\n readonly openedRoot?: string | undefined\n /** `owner/repo` of each git remote, `origin` first. */\n readonly repos: ReadonlyArray<string>\n readonly linked: ReadonlyArray<LinkedFolder>\n readonly projects: ReadonlyArray<ProjectSummary>\n readonly mode: AdapterConfig[\"workspaceMode\"]\n readonly allowWorktreeFallback: boolean\n /** How this computer is paired, for the steps that link a folder. */\n readonly device?: DeviceKind | undefined\n readonly platform?: NodeJS.Platform\n}): Resolution => {\n const unresolved = (problem: Problem): Resolution => ({ _tag: \"Unresolved\", problem })\n if (input.gitRoot === undefined) return unresolved(notGit(input.cwd))\n const gitRoot = input.gitRoot\n const here = input.linked.find((folder) => samePath(folder.realRoot ?? folder.root, gitRoot) || samePath(folder.root, gitRoot))\n // A linked folder lists its repositories, so a clone whose remotes name none of them still matches.\n const candidates = [...new Set([...input.repos, ...(here?.repos ?? []).map((r) => r.toLowerCase())])]\n const matches = (repo: string) => input.projects.find((p) => p.repos.some((r) => r.repoFullName.toLowerCase() === repo))\n const repo = candidates.find((candidate) => matches(candidate) !== undefined)\n const project = repo === undefined ? undefined : matches(repo)\n if (repo === undefined || project === undefined) {\n return unresolved(candidates.length === 0 ? noGitHubRemote(gitRoot) : notInProject(candidates))\n }\n const sameRepo = input.linked.find((folder) => folder !== here && folder.repos.some((r) => r.toLowerCase() === repo))\n const notLinkedHere = notLinked({\n root: gitRoot,\n repo,\n projectId: project.id,\n projectName: project.name,\n device: input.device,\n sameRepoRoot: sameRepo?.root\n })\n const base = { projectId: project.id, projectName: project.name, repo, notLinked: notLinkedHere }\n if (here !== undefined) {\n return input.mode === \"linked\"\n ? { _tag: \"Resolved\", value: { ...base, workspace: { kind: \"linked\", root: here.root }, note: undefined } }\n : {\n _tag: \"Resolved\",\n value: {\n ...base,\n workspace: { kind: \"worktree\" },\n note: \"Capy is working in its own git worktree (in Capy's worktree folder, ~/.capy/worktrees by default), not in this folder (CAPY_ACP_WORKSPACE=worktree).\"\n }\n }\n }\n if (sameRepo !== undefined && input.allowWorktreeFallback) {\n return {\n _tag: \"Resolved\",\n value: {\n ...base,\n workspace: { kind: \"worktree\" },\n note:\n `${input.gitRoot} is not linked to this Capy device, so Capy is working in a new worktree of ${sameRepo.root} ` +\n \"in Capy's worktree folder (~/.capy/worktrees by default). Its edits will not appear in this folder.\"\n }\n }\n }\n if (input.mode === \"worktree\") {\n // A worktree is made from a linked folder of the repository, and none is known.\n return unresolved(notLinkedHere)\n }\n // Not in the local list, which can be older than Capy's own, or unreadable. Capy checks the root when\n // the thread starts and refuses one it does not link; the reply then gives `notLinked`. Git prints\n // Windows paths with forward slashes, so the root goes in the form Windows gives it.\n const opened = input.openedRoot ?? gitRoot\n const root = (input.platform ?? process.platform) === \"win32\" ? win32.normalize(opened) : opened\n return { _tag: \"Resolved\", value: { ...base, workspace: { kind: \"linked\", root }, note: undefined } }\n}\n\nconst readJson = async (path: string): Promise<unknown> => JSON.parse(await readFile(path, \"utf8\"))\n\nexport interface Device {\n readonly id: string\n /** Undefined when `CAPY_DEVICE_ID` names the device. */\n readonly kind: DeviceKind | undefined\n}\n\n/**\n * The paired device. With several organizations, `CAPY_DEVICE_ID` picks one explicitly.\n *\n * A machine is paired either by the desktop app (`device-ids.json`, one id per organization) or by the headless\n * `capy dock` daemon, which records its one device in `~/.capy/dock/status.json`. Both share `~/.capy/device`.\n */\nexport const readDevice = async (config: AdapterConfig): Promise<Device> => {\n if (config.deviceIdOverride) return { id: config.deviceIdOverride, kind: undefined }\n const desktop = join(config.capyDesktopConfigDir, \"device-ids.json\")\n const checked: Array<DeviceFile> = []\n let ids: Array<string> = []\n try {\n const data = (await readJson(desktop)) as { orgs?: Record<string, unknown> }\n ids = Object.values(data.orgs ?? {}).filter((id): id is string => typeof id === \"string\" && id !== \"\")\n checked.push({ path: desktop, found: \"no device\" })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw new ProblemError(unreadableDeviceFile(desktop, error instanceof Error ? error.message : String(error)))\n }\n checked.push({ path: desktop, found: \"missing\" })\n }\n if (ids.length === 1 && ids[0]) return { id: ids[0], kind: \"desktop\" }\n if (ids.length > 1) throw new ProblemError(manyOrganizations(ids.length))\n const dock = join(config.capyHome, \"dock\", \"status.json\")\n const docked = await readJson(dock).then(\n (data) => ({ found: \"no device\" as const, id: (data as { deviceId?: unknown }).deviceId }),\n () => ({ found: \"missing\" as const, id: undefined })\n )\n if (typeof docked.id === \"string\" && docked.id !== \"\") return { id: docked.id, kind: \"dock\" }\n checked.push({ path: dock, found: docked.found })\n throw new ProblemError(noDevice(checked))\n}\n\nexport const readLinkedFolders = async (config: AdapterConfig): Promise<ReadonlyArray<LinkedFolder>> => {\n try {\n const data = (await readJson(join(config.capyHome, \"device\", \"workspaces.json\"))) as {\n folders?: ReadonlyArray<{ root?: unknown; repos?: unknown }>\n }\n const folders = (data.folders ?? []).flatMap((folder) =>\n typeof folder.root === \"string\"\n ? [{ root: folder.root, repos: Array.isArray(folder.repos) ? folder.repos.filter((r) => typeof r === \"string\") : [] }]\n : []\n )\n return Promise.all(\n folders.map(async (folder) => ({ ...folder, realRoot: await realpath(folder.root).catch(() => folder.root) }))\n )\n } catch {\n return []\n }\n}\n\nexport const readGit = async (\n cwd: string\n): Promise<{ gitRoot: string | undefined; openedRoot: string | undefined; repos: ReadonlyArray<string> }> => {\n const git = async (...args: Array<string>) => {\n try {\n return (await run(\"git\", [\"-C\", cwd, ...args], { timeout: 5_000 })).stdout.trim()\n } catch {\n return undefined\n }\n }\n const gitRoot = await git(\"rev-parse\", \"--show-toplevel\")\n // `git remote -v` prints URLs after `insteadOf` rewrites: \"<name>\\t<url> (fetch)\".\n const remotes = gitRoot === undefined ? [] : ((await git(\"remote\", \"-v\")) ?? \"\").split(\"\\n\").flatMap((line) => {\n const match = /^(\\S+)\\s+(\\S+)\\s+\\(fetch\\)$/.exec(line.trim())\n return match ? [{ name: match[1]!, url: match[2]! }] : []\n })\n const ordered = [...remotes.filter((r) => r.name === \"origin\"), ...remotes.filter((r) => r.name !== \"origin\")]\n const repos = [...new Set(ordered.flatMap((remote) => parseRemote(remote.url) ?? []))]\n // Git resolves symlinks (macOS `/tmp` is `/private/tmp`), and Capy keeps the spelling the user linked,\n // which is most likely the one the client opened.\n const openedRoot = gitRoot === undefined\n ? undefined\n : await realpath(cwd).then((real) => resolve(cwd, relative(real, gitRoot)), () => gitRoot)\n return { gitRoot, openedRoot, repos }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "capy-acp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Runs Capy coding-agent threads
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Runs Capy coding-agent threads from Agent Client Protocol (ACP) clients, such as Zed, JetBrains IDEs and T3 Code. A community project, not affiliated with Capy.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"acp",
|
|
7
7
|
"agent-client-protocol",
|
|
8
8
|
"capy",
|
|
9
9
|
"coding-agent",
|
|
10
|
+
"zed",
|
|
11
|
+
"jetbrains",
|
|
10
12
|
"t3-code"
|
|
11
13
|
],
|
|
12
14
|
"homepage": "https://github.com/yazcaleb/capy-acp#readme",
|