@cirtium/acent-connect 0.0.0-stage → 0.2.2

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.
Files changed (39) hide show
  1. package/.agents/plugins/marketplace.json +10 -0
  2. package/.claude-plugin/marketplace.json +5 -0
  3. package/README.md +109 -2
  4. package/acent/.claude-plugin/plugin.json +7 -0
  5. package/acent/.codex-plugin/plugin.json +32 -0
  6. package/acent/.cursor-plugin/plugin.json +13 -0
  7. package/acent/README.md +35 -0
  8. package/acent/assets/logo-dark.svg +7 -0
  9. package/acent/assets/logo.svg +7 -0
  10. package/acent/hooks/claude.json +26 -0
  11. package/acent/hooks/codex.json +26 -0
  12. package/acent/hooks/cursor.json +15 -0
  13. package/acent/mcp-claude.json +12 -0
  14. package/acent/mcp-codex.json +11 -0
  15. package/acent/mcp-cursor.json +15 -0
  16. package/acent/scripts/acent-connect.mjs +440 -0
  17. package/acent/scripts/antigravity-capture.mjs +105 -0
  18. package/acent/scripts/antigravity-hook.mjs +26 -0
  19. package/acent/scripts/capture-attachments.mjs +112 -0
  20. package/acent/scripts/capture-images.mjs +106 -0
  21. package/acent/scripts/clarification.mjs +105 -0
  22. package/acent/scripts/codex-capture.mjs +38 -0
  23. package/acent/scripts/connection-context.mjs +76 -0
  24. package/acent/scripts/connection-result.mjs +30 -0
  25. package/acent/scripts/extract-attachment.swift +19 -0
  26. package/acent/scripts/hook.mjs +32 -0
  27. package/acent/scripts/mcp-proxy.mjs +258 -0
  28. package/acent/scripts/memory-instructions.mjs +14 -0
  29. package/acent/scripts/provide-diff.mjs +200 -0
  30. package/acent/skills/acent-connect/SKILL.md +14 -0
  31. package/acent/skills/acent-memory/SKILL.md +49 -0
  32. package/antigravity/README.md +25 -0
  33. package/antigravity/build.mjs +49 -0
  34. package/antigravity/mcp-local.example.json +12 -0
  35. package/antigravity/mcp.example.json +1 -0
  36. package/antigravity/plugin.json +15 -0
  37. package/package.json +19 -4
  38. package/scripts/acent.mjs +156 -0
  39. package/scripts/install-plugin.mjs +267 -0
@@ -0,0 +1,106 @@
1
+ import { constants } from "node:fs"
2
+ import { open, realpath } from "node:fs/promises"
3
+ import { basename, dirname } from "node:path"
4
+ import { tmpdir } from "node:os"
5
+ import { crc32, deflateSync, inflateSync } from "node:zlib"
6
+
7
+ // Recompress only the PNG pixel stream. Color profiles, bit depth and alpha stay intact.
8
+ export function compactPng(bytes) {
9
+ if (bytes.subarray(0, 8).toString("hex") !== "89504e470d0a1a0a")
10
+ throw Error("Expected PNG")
11
+ const parts = []
12
+ const pixels = []
13
+ for (let pos = 8; pos < bytes.length;) {
14
+ const size = bytes.readUInt32BE(pos)
15
+ const end = pos + 12 + size
16
+ if (end > bytes.length) throw Error("Invalid PNG")
17
+ const type = bytes.toString("ascii", pos + 4, pos + 8)
18
+ if (type === "IDAT") {
19
+ if (!pixels.length) parts.push(null)
20
+ pixels.push(bytes.subarray(pos + 8, end - 4))
21
+ } else parts.push(bytes.subarray(pos, end))
22
+ pos = end
23
+ }
24
+ if (!pixels.length) throw Error("Missing PNG pixels")
25
+ const raw = inflateSync(Buffer.concat(pixels), {
26
+ maxOutputLength: 64 * 1024 * 1024,
27
+ })
28
+ const compressed = deflateSync(raw, { level: 9 })
29
+ const chunk = Buffer.alloc(compressed.length + 12)
30
+ chunk.writeUInt32BE(compressed.length)
31
+ chunk.write("IDAT", 4)
32
+ compressed.copy(chunk, 8)
33
+ chunk.writeUInt32BE(crc32(chunk.subarray(4, -4)), chunk.length - 4)
34
+ const output = Buffer.concat([
35
+ bytes.subarray(0, 8),
36
+ ...parts.map((part) => part ?? chunk),
37
+ ])
38
+ return output.length < bytes.length ? output : bytes
39
+ }
40
+
41
+ export async function attachScreenshots(payload, config, access, request) {
42
+ if (
43
+ config.tool !== "Codex" ||
44
+ payload.hook_event_name !== "UserPromptSubmit" ||
45
+ typeof payload.prompt !== "string"
46
+ )
47
+ return payload
48
+ const header = payload.prompt.trimStart().split(/^## My request:/m)[0]
49
+ if (!header.startsWith("# Files mentioned by the user:")) return payload
50
+ const paths = [
51
+ ...header.matchAll(
52
+ /^## (codex-clipboard-[0-9a-f-]{36}\.png): ([^\r\n]+)\r?\nImage attachment: true\s*$/gim
53
+ ),
54
+ ]
55
+ if (!paths.length) return payload
56
+ const headers = { Authorization: "Bearer " + access }
57
+ const settings = await request(config, "/api/external/images", { headers })
58
+ if (!settings.enabled) return payload
59
+ const root = await realpath(tmpdir())
60
+ const ids = new Set()
61
+ for (const [, name, path] of paths.slice(0, 10)) {
62
+ if (
63
+ basename(path) !== name ||
64
+ (await realpath(dirname(path)).catch(() => null)) !== root
65
+ )
66
+ continue
67
+ let bytes
68
+ try {
69
+ const file = await open(
70
+ path,
71
+ constants.O_RDONLY |
72
+ (constants.O_NOFOLLOW || 0) |
73
+ (constants.O_NONBLOCK || 0)
74
+ )
75
+ try {
76
+ const info = await file.stat()
77
+ if (
78
+ !info.isFile() ||
79
+ info.size > 8388608 ||
80
+ (process.getuid && info.uid !== process.getuid())
81
+ )
82
+ continue
83
+ bytes = compactPng(await file.readFile())
84
+ } finally {
85
+ await file.close()
86
+ }
87
+ } catch {
88
+ continue
89
+ }
90
+ const result = await request(config, "/api/external/images", {
91
+ method: "POST",
92
+ headers: { ...headers, "Content-Type": "image/png" },
93
+ body: bytes,
94
+ })
95
+ if (/^[0-9a-f]{64}$/.test(result.id)) ids.add(result.id)
96
+ }
97
+ return ids.size
98
+ ? {
99
+ ...payload,
100
+ prompt:
101
+ payload.prompt +
102
+ "\n" +
103
+ [...ids].map((id) => "[acent-image:" + id + "]").join("\n"),
104
+ }
105
+ : payload
106
+ }
@@ -0,0 +1,105 @@
1
+ // Runs in the local MCP host connection: answers never go to an Acent web page.
2
+ export const clarificationInstructions = "For requests to resume recent work without a specific topic, start with get_recent_work when available. Read its references and check current files before coding; recency alone does not establish an unfinished task. When saved context leaves multiple plausible tasks or an unclear next step after focused search, call request_clarification with one short question and 2–3 evidence-based choices in the user's language. Do not invent candidates or treat the newest hit as approval. If needs_user_input is returned, ask its question in the current agent chat (prefer the host's native question tool) and wait for the user. Never answer on the user's behalf, repeat a cancelled question, or modify code dependent on an unresolved choice. After an answer, read the selected evidence and compare it with current code before continuing."
3
+
4
+ export const clarificationTool = {
5
+ name: "request_clarification",
6
+ description: "Ask the user in their current coding agent to clarify ambiguous Acent search results or unfinished work. Use after focused retrieval leaves uncertainty. Supply a concise question and 2–3 grounded choices; never request secrets or authorization. Wait for the answer before dependent code changes. If native input is unavailable, the result tells you to ask in this same chat.",
7
+ inputSchema: {
8
+ type: "object",
9
+ properties: {
10
+ question: { type: "string", minLength: 1, maxLength: 500 },
11
+ choices: { type: "array", minItems: 2, maxItems: 3, uniqueItems: true, items: { type: "string", minLength: 1, maxLength: 200 } },
12
+ },
13
+ required: ["question", "choices"],
14
+ additionalProperties: false,
15
+ },
16
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false },
17
+ }
18
+
19
+ export function validateClarification(input) {
20
+ if (!input || typeof input.question !== "string" || !input.question.trim() || input.question.length > 500 ||
21
+ !Array.isArray(input.choices) || input.choices.length < 2 || input.choices.length > 3 ||
22
+ input.choices.some((choice) => typeof choice !== "string" || !choice.trim() || choice.length > 200) ||
23
+ new Set(input.choices).size !== input.choices.length ||
24
+ Object.keys(input).some((key) => !["question", "choices"].includes(key)))
25
+ throw new Error("Supply one question and 2–3 distinct choices from the retrieved context.")
26
+ return input
27
+ }
28
+
29
+ export function chatClarification(input, reason = "native_input_unavailable") {
30
+ return { status: "needs_user_input", ...input, reason,
31
+ nextAction: "Ask this question and its choices in the current agent chat, using the host's native question tool when available. Allow a free-text answer. Wait for the user's reply before dependent work. Do not choose an answer yourself or retry this tool automatically." }
32
+ }
33
+
34
+ export function supportsForm(capabilities, protocol) {
35
+ const elicitation = capabilities?.elicitation
36
+ return ["2025-06-18", "2025-11-25"].includes(protocol) &&
37
+ !!elicitation && typeof elicitation === "object" &&
38
+ (Object.keys(elicitation).length === 0 || !!elicitation.form)
39
+ }
40
+
41
+ export async function clarify(input, capabilities, protocol, request) {
42
+ validateClarification(input)
43
+ if (!supportsForm(capabilities, protocol)) return chatClarification(input)
44
+ try {
45
+ const result = await request({
46
+ ...(protocol === "2025-11-25" ? { mode: "form" } : {}),
47
+ message: `${input.question}\n${input.choices.map((choice, index) => `${index + 1}. ${choice}`).join("\n")}\nYou can also describe another task in your answer.`,
48
+ requestedSchema: {
49
+ type: "object",
50
+ properties: { answer: { type: "string", title: input.question, description: "Enter your choice or clarify in your own words.", minLength: 1, maxLength: 2000 } },
51
+ required: ["answer"],
52
+ },
53
+ })
54
+ if (result?.action === "decline" || result?.action === "cancel")
55
+ return { status: result.action === "decline" ? "declined" : "cancelled", nextAction: "The user did not choose a task. Stop dependent work. Do not repeat the question unless the user asks." }
56
+ const answer = result?.content?.answer
57
+ if (result?.action === "accept" && typeof answer === "string" && answer.trim() && answer.length <= 2000)
58
+ return { status: "answered", answer, nextAction: "Use this answer only to resolve the task ambiguity. Read the relevant evidence and check current code before continuing; this is not approval for unrelated actions." }
59
+ return chatClarification(input, "invalid_answer")
60
+ } catch {
61
+ return chatClarification(input, "native_input_failed_or_timed_out")
62
+ }
63
+ }
64
+
65
+ export function createQuestionChannel(write, timeoutMs = 120000) {
66
+ let sequence = 0
67
+ const pending = new Map()
68
+ return {
69
+ request(params, relatedRequestId) {
70
+ const id = `acent-question-${++sequence}`
71
+ return new Promise((resolve, reject) => {
72
+ const timer = setTimeout(() => {
73
+ pending.delete(id)
74
+ reject(new Error("Question timed out"))
75
+ }, timeoutMs)
76
+ pending.set(id, { resolve, reject, timer, relatedRequestId })
77
+ write({ jsonrpc: "2.0", id, method: "elicitation/create", params })
78
+ })
79
+ },
80
+ receive(message) {
81
+ if (message.method || !pending.has(message.id)) return false
82
+ const entry = pending.get(message.id)
83
+ pending.delete(message.id)
84
+ clearTimeout(entry.timer)
85
+ if (message.error) entry.reject(new Error("Host declined the request"))
86
+ else entry.resolve(message.result)
87
+ return true
88
+ },
89
+ cancel(requestId) {
90
+ for (const [id, entry] of pending) {
91
+ if (entry.relatedRequestId !== requestId) continue
92
+ clearTimeout(entry.timer)
93
+ pending.delete(id)
94
+ entry.resolve({ action: "cancel" })
95
+ }
96
+ },
97
+ close() {
98
+ for (const entry of pending.values()) {
99
+ clearTimeout(entry.timer)
100
+ entry.resolve({ action: "cancel" })
101
+ }
102
+ pending.clear()
103
+ },
104
+ }
105
+ }
@@ -0,0 +1,38 @@
1
+ // Internal suggestion sessions can emit the same two hooks as interactive chats.
2
+ // Keep only a hash of the last eligible turn per session, never its prompt text.
3
+ import { createHash, randomUUID } from "node:crypto"
4
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"
5
+ import { join } from "node:path"
6
+
7
+ const generatedHeader =
8
+ /^This is an app-generated request\b[^\n]{0,500}The user did not write this message\.(?:\s|$)/i
9
+
10
+ export async function captureCodexEvent(payload, directory) {
11
+ const session = payload.session_id
12
+ if (typeof session !== "string" || !session) return false
13
+ const digest = (value) => createHash("sha256").update(value).digest("hex")
14
+ const root = join(directory, "interactive-turns")
15
+ const marker = join(root, digest(session))
16
+ const turn = digest(JSON.stringify([session, payload.turn_id ?? null]))
17
+ if (
18
+ payload.hook_event_name === "UserPromptSubmit" ||
19
+ (!payload.hook_event_name && typeof payload.prompt === "string")
20
+ ) {
21
+ const prompt = payload.prompt
22
+ if (
23
+ typeof prompt !== "string" ||
24
+ !prompt.trim() ||
25
+ generatedHeader.test(prompt.trimStart())
26
+ ) {
27
+ await rm(marker, { force: true })
28
+ return false
29
+ }
30
+ await mkdir(root, { recursive: true, mode: 0o700 })
31
+ const temp = marker + "." + randomUUID()
32
+ await writeFile(temp, turn, { mode: 0o600 })
33
+ await rename(temp, marker)
34
+ return true
35
+ }
36
+ if (payload.hook_event_name !== "Stop") return false
37
+ return (await readFile(marker, "utf8").catch(() => null)) === turn
38
+ }
@@ -0,0 +1,76 @@
1
+ import { realpathSync } from "node:fs"
2
+ import { isAbsolute } from "node:path"
3
+ import { fileURLToPath } from "node:url"
4
+
5
+ export function projectFolder(value) {
6
+ return typeof value === "string" &&
7
+ isAbsolute(value) &&
8
+ !value.includes("${") &&
9
+ !/[\x00-\x1f]/.test(value)
10
+ ? value
11
+ : undefined
12
+ }
13
+
14
+ // A process cwd alone is not evidence that the user selected a project.
15
+ /** @param {{ roots?: unknown, explicitFolder?: string, bound?: { bindingKnown?: boolean, general?: boolean, folder?: string, contextFolder?: string } }} context */
16
+ export function connectionContext({ roots, explicitFolder, bound }) {
17
+ if (roots !== undefined) {
18
+ if (!Array.isArray(roots)) return { scope: "unknown" }
19
+ if (roots.length === 0) return { scope: "general" }
20
+ if (roots.length !== 1) return { scope: "unknown" }
21
+ try {
22
+ const folder = projectFolder(fileURLToPath(roots[0].uri))
23
+ let canonical = folder
24
+ try {
25
+ canonical = realpathSync(folder)
26
+ } catch {
27
+ /* Missing roots are still host context. */
28
+ }
29
+ if (
30
+ bound?.bindingKnown &&
31
+ bound.general &&
32
+ canonical === bound.contextFolder
33
+ )
34
+ return { scope: "general" }
35
+ return folder ? { scope: "folder", folder } : { scope: "unknown" }
36
+ } catch {
37
+ return { scope: "unknown" }
38
+ }
39
+ }
40
+ if (bound?.bindingKnown)
41
+ return bound.general
42
+ ? { scope: "general" }
43
+ : { scope: "folder", folder: bound.folder }
44
+ const folder = projectFolder(explicitFolder)
45
+ return folder ? { scope: "folder", folder } : { scope: "unknown" }
46
+ }
47
+
48
+ export function createRootsChannel(write, timeout = 2000) {
49
+ let sequence = 0
50
+ const pending = new Map()
51
+ return {
52
+ request() {
53
+ return new Promise((resolve) => {
54
+ const id = `acent-roots-${++sequence}`
55
+ const finish = (value) => {
56
+ clearTimeout(pending.get(id)?.timer)
57
+ pending.delete(id)
58
+ resolve(value)
59
+ }
60
+ const timer = setTimeout(() => finish(undefined), timeout)
61
+ pending.set(id, { finish, timer })
62
+ write({ jsonrpc: "2.0", id, method: "roots/list" })
63
+ })
64
+ },
65
+ receive(message) {
66
+ if (message.method || !pending.has(message.id)) return false
67
+ pending
68
+ .get(message.id)
69
+ .finish(message.error ? undefined : message.result?.roots)
70
+ return true
71
+ },
72
+ close() {
73
+ for (const { finish } of pending.values()) finish(undefined)
74
+ },
75
+ }
76
+ }
@@ -0,0 +1,30 @@
1
+ /** Self-contained callback page: works offline without fonts, scripts or remote assets. */
2
+ export const connectionResultPolicy = "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'"
3
+
4
+ export function connectionResultPage({ status = "success", tool = "your tool", preview = false } = {}) {
5
+ const safeTool = ["Codex", "Claude Code", "Cursor", "Antigravity"].includes(tool) ? tool : "your tool"
6
+ const title = status === "success" ? "Acent is connected" : status === "cancelled" ? "Connection cancelled" : "Unable to connect"
7
+ const message = status === "success"
8
+ ? "Open Acent to view your connections."
9
+ : status === "cancelled"
10
+ ? "Nothing was connected. You can close this tab and try again anytime."
11
+ : `Return to ${safeTool} and try connecting again.`
12
+ return `<!doctype html>
13
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light dark"><title>${title} — Acent</title>
14
+ <style>
15
+ :root{color-scheme:light dark;--background:#fff;--foreground:#171717;--muted:#737373;--border:#e5e5e5}
16
+ @media(prefers-color-scheme:dark){:root{--background:#0a0a0a;--foreground:#fafafa;--muted:#a3a3a3;--border:#292929}}
17
+ *{box-sizing:border-box}body{margin:0;background:var(--background);color:var(--foreground);font-family:Arial,Helvetica,sans-serif;-webkit-font-smoothing:antialiased}
18
+ main{min-height:100vh;min-height:100svh;display:flex;align-items:center;justify-content:center;padding:48px 24px}
19
+ section{width:100%;max-width:384px;text-align:center;display:flex;flex-direction:column;align-items:center;gap:28px}
20
+ .mark{width:64px;height:64px;border:1px solid var(--border);border-radius:18px;display:grid;place-items:center;position:relative}.mark svg{width:30px;height:32px}
21
+ .badge{position:absolute;right:-5px;bottom:-5px;width:24px;height:24px;display:grid;place-items:center;background:var(--foreground);color:var(--background);border:3px solid var(--background);border-radius:50%}.badge svg{width:12px;height:12px}
22
+ h1{margin:0;font-size:24px;line-height:32px;font-weight:600;letter-spacing:-.6px}p{margin:8px 0 0;color:var(--muted);font-size:14px;line-height:24px;text-wrap:balance}
23
+ a{display:inline-flex;align-items:center;justify-content:center;min-height:40px;padding:0 20px;border:1px solid var(--border);border-radius:999px;color:var(--foreground);font-size:14px;text-decoration:none}a:hover{background:var(--border)}a:focus-visible{outline:2px solid var(--foreground);outline-offset:4px}
24
+ </style></head><body><main><section aria-labelledby="result-title">
25
+ <div class="mark"><svg viewBox="0 0 60 64" aria-label="Acent" role="img"><path fill="currentColor" d="M0 30a30 30 0 0 1 60 0H0Zm0 4h60a30 30 0 0 1-60 0Z"/></svg>${status === "success" ? '<span class="badge"><svg viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="m3 8 3 3 7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></span>' : ""}</div>
26
+ <div><h1 id="result-title">${title}</h1><p>${message}</p></div>
27
+ ${status === "success" && !preview ? '<a href="acent://open">Open Acent</a>' : ""}
28
+ ${preview ? '<a href="/preview/connection">Back to preview</a>' : ""}
29
+ </section></main></body></html>`
30
+ }
@@ -0,0 +1,19 @@
1
+ // macOS system frameworks keep attachment extraction on the user's machine.
2
+ import Foundation
3
+ import PDFKit
4
+ import Vision
5
+
6
+ let file = URL(fileURLWithPath: CommandLine.arguments[1])
7
+ if file.pathExtension.lowercased() == "pdf" {
8
+ guard let document = PDFDocument(url: file), !document.isLocked else { exit(1) }
9
+ print(document.string ?? "")
10
+ } else {
11
+ let request = VNRecognizeTextRequest()
12
+ request.recognitionLevel = .accurate
13
+ let supported = try request.supportedRecognitionLanguages()
14
+ request.recognitionLanguages = ["ko-KR", "en-US"].filter { supported.contains($0) }
15
+ try VNImageRequestHandler(url: file).perform([request])
16
+ for line in request.results ?? [] {
17
+ print(line.topCandidates(1).first?.string ?? "")
18
+ }
19
+ }
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ import { isAbsolute } from "node:path"
3
+ import { main } from "./acent-connect.mjs"
4
+ // Use the documented hook cwd, never a plugin cache folder or another binding.
5
+ let text = ""
6
+ try {
7
+ for await (const chunk of process.stdin) {
8
+ text += chunk
9
+ if (Buffer.byteLength(text) > 2 * 1024 * 1024)
10
+ throw new Error("Hook event exceeds 2 MiB")
11
+ }
12
+ const payload = JSON.parse(text)
13
+ const cursor = process.argv.includes("Cursor")
14
+ const antigravity = process.argv.includes("Antigravity")
15
+ const roots = cursor ? payload.workspace_roots : antigravity ? payload.workspacePaths : undefined
16
+ if (roots !== undefined && (!Array.isArray(roots) || roots.length > 1))
17
+ throw new Error("Hook has ambiguous workspace roots")
18
+ const folder = cursor || antigravity
19
+ ? (roots !== undefined ? roots[0] : cursor ? process.env.CURSOR_PROJECT_DIR : payload.cwd)
20
+ : payload.cwd
21
+ if (folder != null && folder !== "" && (typeof folder !== "string" || !isAbsolute(folder)))
22
+ throw new Error("Hook has an invalid working folder")
23
+ const session = payload.session_id || payload.conversation_id || payload.conversationId
24
+ if (typeof session !== "string" || !session.trim())
25
+ throw new Error("Hook is missing a conversation identifier")
26
+ await main(["collect", ...process.argv.slice(2),
27
+ ...(folder ? ["--folder", folder] : ["--general"])], text)
28
+
29
+ } catch (error) {
30
+ // Acent outages must not block or mark a successful AI turn as failed.
31
+ console.error(`Acent saving: ${error.message}`)
32
+ }
@@ -0,0 +1,258 @@
1
+ #!/usr/bin/env node
2
+ // Folder-scoped MCP with setup available even before the first authorization.
3
+ import { clarificationInstructions, clarificationTool, clarify, createQuestionChannel } from "./clarification.mjs"
4
+ import { connectionContext, createRootsChannel, projectFolder } from "./connection-context.mjs"
5
+ import { memoryInstructions } from "./memory-instructions.mjs"
6
+ import { attachmentTool, saveAttachments } from "./capture-attachments.mjs"
7
+ import { createInterface } from "node:readline"
8
+ import { mkdir } from "node:fs/promises"
9
+ import {
10
+ options,
11
+ boundConfig,
12
+ configDirectory,
13
+ accessToken,
14
+ request,
15
+ connect,
16
+ } from "./acent-connect.mjs"
17
+ const launchArgs = process.argv.slice(2)
18
+ // Hosts can leave workspaceFolder unsubstituted in a projectless window.
19
+ const folderIndex = launchArgs.indexOf("--folder")
20
+ const launchFolder = folderIndex < 0 ? undefined : launchArgs[folderIndex + 1]
21
+ if (folderIndex >= 0 && !projectFolder(launchFolder)) launchArgs.splice(folderIndex, 2)
22
+ let activeConfig = await boundConfig(["flush", ...launchArgs])
23
+ let clientCapabilities = {}
24
+ let protocol
25
+ let pendingConnection
26
+ let connectionUrl
27
+ const setupTool = {
28
+ name: "acent_connect",
29
+ description:
30
+ "Connect or reconnect Acent. Omit scope to detect the current project or general conversation automatically. If the host explicitly identifies this as a projectless chat, use general; use folder for an explicitly selected project. Never infer a project from process cwd alone. Returns a browser link to sign in, choose an Acent project and optionally enable conversation saving. Call when the user asks to connect or when memory access needs setup. Show the link to the user; only the user may approve access. After approval, retry tools/list without restarting the session.",
31
+ inputSchema: {
32
+ type: "object",
33
+ properties: { reconnect: { type: "boolean", description: "Only true when the user explicitly wants to change the connected project or saving consent. Otherwise reuse or refresh the existing connection." }, scope: { type: "string", enum: ["auto", "folder", "general"],
34
+ description: "Defaults to auto. Users do not need to name a mode. Override only from explicit host project context or their answer to a clarification." } },
35
+ additionalProperties: false,
36
+ },
37
+ }
38
+ const write = (value) => process.stdout.write(JSON.stringify(value) + "\n")
39
+ const questions = createQuestionChannel(write)
40
+ const rootRequests = createRootsChannel(write)
41
+ const content = (text, isError = false) => ({
42
+ content: [{ type: "text", text }],
43
+ isError,
44
+ })
45
+ async function startConnection(config) {
46
+ const directory = configDirectory(config)
47
+ if (pendingConnection) return connectionUrl
48
+ await mkdir(directory, { recursive: true, mode: 0o700 })
49
+ const ready = Promise.withResolvers()
50
+ pendingConnection = connect(config, directory, (url) => {
51
+ connectionUrl = url.toString()
52
+ ready.resolve(connectionUrl)
53
+ })
54
+ .then(() => {
55
+ config.bindingKnown = true
56
+ write({ jsonrpc: "2.0", method: "notifications/tools/list_changed" })
57
+ })
58
+ .catch((error) => {
59
+ ready.reject(error)
60
+ console.error(`Acent: ${error.message}`)
61
+ })
62
+ .finally(() => {
63
+ pendingConnection = undefined
64
+ connectionUrl = undefined
65
+ })
66
+ return ready.promise
67
+ }
68
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity })
69
+ async function handleLine(line) {
70
+ if (!line.trim()) return
71
+ let message
72
+ try {
73
+ let config = activeConfig
74
+ if (Buffer.byteLength(line) > 64 * 1024)
75
+ throw new Error("MCP request exceeds 64 KiB")
76
+ message = JSON.parse(line)
77
+ if (rootRequests.receive(message) || questions.receive(message)) return
78
+ if (message.method === "notifications/cancelled") {
79
+ questions.cancel(message.params?.requestId)
80
+ return
81
+ }
82
+ // Responses are never forwarded to the HTTP tool endpoint.
83
+ if (!message.method) return
84
+ const reply = (result) => write({ jsonrpc: "2.0", id: message.id, result })
85
+ if (message.method === "initialize") {
86
+ clientCapabilities = message.params?.capabilities ?? {}
87
+ protocol = [
88
+ "2025-11-25",
89
+ "2025-06-18",
90
+ "2025-03-26",
91
+ "2024-11-05",
92
+ ].includes(message.params?.protocolVersion)
93
+ ? message.params.protocolVersion
94
+ : "2025-03-26"
95
+ reply({
96
+ protocolVersion: protocol,
97
+ capabilities: { tools: { listChanged: true } },
98
+ serverInfo: { name: "acent", version: "0.2.0" },
99
+ instructions:
100
+ "Use acent_connect to connect Acent when setup is needed; its default scope is auto. If it returns needs_user_input, ask its question once in the user’s language and wait for their answer. Show its authorization link to the user. After approval, refresh tools/list and continue the original request. Never approve on the user's behalf. " + memoryInstructions + "\n\n" + clarificationInstructions,
101
+ })
102
+ return
103
+ }
104
+ if (message.id === undefined) return
105
+ if (message.method === "ping") {
106
+ reply({})
107
+ return
108
+ }
109
+ if (
110
+ message.method === "tools/call" &&
111
+ message.params?.name === setupTool.name
112
+ ) {
113
+ let scope = message.params.arguments?.scope ?? "auto"
114
+ let detectedFolder
115
+ let projectlessRoots = false
116
+ const resumePending = scope === "auto" && !!pendingConnection
117
+ if (scope !== "auto" && scope !== "folder" && scope !== "general")
118
+ throw new Error("Choose folder or general scope")
119
+ if (resumePending) scope = config.general ? "general" : "folder"
120
+ if (scope === "auto") {
121
+ const roots = clientCapabilities.roots ? await rootRequests.request() : undefined
122
+ const detected = connectionContext({ roots,
123
+ explicitFolder: launchFolder || (config.tool === "Cursor" ? process.env.CURSOR_PROJECT_DIR : undefined),
124
+ bound: config })
125
+ if (detected.scope === "unknown") {
126
+ const value = {
127
+ status: "needs_user_input",
128
+ question: "Connect Acent to this project's conversations or to general conversations outside projects?",
129
+ choices: ["This project", "General conversations"],
130
+ nextAction: "Ask once in the user's language using the host chat UI. Do not ask for a technical mode name. Wait for their answer, then call acent_connect with scope=folder or scope=general. No authorization link has been created yet.",
131
+ }
132
+ reply({ ...content(JSON.stringify(value)), structuredContent: value })
133
+ return
134
+ }
135
+ projectlessRoots = Array.isArray(roots) && roots.length === 0
136
+ scope = detected.scope
137
+ detectedFolder = detected.folder
138
+ }
139
+ if (!resumePending) {
140
+ const folder = detectedFolder || config.contextFolder || config.folder || process.cwd()
141
+ config = options(["flush", "--tool", config.tool, "--server", config.server,
142
+ ...(scope === "general" ? ["--general"] : []),
143
+ ...(projectlessRoots ? [] : ["--folder", folder]),
144
+ ])
145
+ if (pendingConnection && configDirectory(config) !== configDirectory(activeConfig))
146
+ throw new Error("Finish the pending connection before changing its scope")
147
+ activeConfig = config
148
+ }
149
+ if (message.params.arguments?.reconnect !== true) {
150
+ try {
151
+ await accessToken(config, configDirectory(config))
152
+ reply(content("Acent is connected. Refresh tools/list and use the available memory tools. No new approval is needed."))
153
+ write({ jsonrpc: "2.0", method: "notifications/tools/list_changed" })
154
+ return
155
+ } catch (error) {
156
+ if (error.code !== "ENOENT" && error.status !== 401 && error.status !== 400) throw error
157
+ }
158
+ }
159
+ const url = await startConnection(config)
160
+ reply(
161
+ content(
162
+ `Connect ${config.tool} ${config.folder ? `folder ${config.folder}` : "general conversations"} to Acent: ${url}\nOpen this link, choose your Acent project, and click Connect. Conversation saving is optional. If you closed the page, call acent_connect again to resume. After approval, refresh tools/list and retry your request.`
163
+ )
164
+ )
165
+ return
166
+ }
167
+ const directory = configDirectory(config)
168
+ let access
169
+ try {
170
+ access = await accessToken(config, directory)
171
+ } catch (error) {
172
+ if (message.method === "tools/list") {
173
+ reply({ tools: [setupTool] })
174
+ return
175
+ }
176
+ throw error
177
+ }
178
+ if (message.method === "tools/call" && message.params?.name === clarificationTool.name) {
179
+ try {
180
+ const value = await clarify(message.params.arguments, clientCapabilities, protocol,
181
+ (params) => questions.request(params, message.id))
182
+ reply({ ...content(JSON.stringify(value)), structuredContent: value })
183
+ } catch (error) {
184
+ reply(content(error.message, true))
185
+ }
186
+ return
187
+ }
188
+ if (message.method === "tools/call" && message.params?.name === attachmentTool.name) {
189
+ try {
190
+ const value = await saveAttachments(message.params.arguments?.paths, config, access, request)
191
+ reply({ ...content(JSON.stringify(value), !value.enabled || value.files.some(file => file.status !== "saved")), structuredContent: value })
192
+ } catch (error) { reply(content(error.message, true)) }
193
+ return
194
+ }
195
+ const response = await fetch(`${config.server}/mcp`, {
196
+ method: "POST",
197
+ headers: {
198
+ Authorization: `Bearer ${access}`,
199
+ "Content-Type": "application/json",
200
+ Accept: "application/json, text/event-stream",
201
+ ...(protocol ? { "MCP-Protocol-Version": protocol } : {}),
202
+ },
203
+ body: JSON.stringify(message),
204
+ signal: AbortSignal.timeout(60_000),
205
+ })
206
+ if (!response.ok) {
207
+ if (
208
+ message.method === "tools/list" &&
209
+ [401, 403].includes(response.status)
210
+ ) {
211
+ reply({ tools: [setupTool] })
212
+ return
213
+ }
214
+ const failure = await response.json().catch(() => ({}))
215
+ if (["subscription_required", "capacity_exceeded"].includes(failure.error)) {
216
+ throw Object.assign(new Error(failure.error_description), { entitlementFailure: true })
217
+ }
218
+ throw new Error(`Acent request failed (${response.status}).`)
219
+ }
220
+ if (response.status === 202 || response.status === 204) return
221
+ const result = await response.json()
222
+ if (message.method === "tools/list" && result.result?.tools)
223
+ result.result.tools = [...result.result.tools.filter((tool) => tool.name !== clarificationTool.name), setupTool, clarificationTool, attachmentTool]
224
+ write(result)
225
+ } catch (error) {
226
+ console.error(`Acent: ${error.message}`)
227
+ if (message?.id !== undefined)
228
+ write({
229
+ jsonrpc: "2.0",
230
+ id: message.id,
231
+ ...(message.method === "tools/call"
232
+ ? {
233
+ result: content(
234
+ error.entitlementFailure ? error.message : "Acent needs a connection for this folder. Call acent_connect and show the user its link, then retry after approval.",
235
+ true
236
+ ),
237
+ }
238
+ : {
239
+ error: {
240
+ code: -32000,
241
+ message:
242
+ error.entitlementFailure ? error.message : "Acent is unavailable. Use acent_connect to connect or retry.",
243
+ },
244
+ }),
245
+ })
246
+ }
247
+ }
248
+
249
+ // Keep reading while a tool waits for an elicitation response on this same pipe.
250
+ const active = new Set()
251
+ for await (const line of lines) {
252
+ const task = handleLine(line)
253
+ active.add(task)
254
+ void task.finally(() => active.delete(task))
255
+ }
256
+ rootRequests.close()
257
+ questions.close()
258
+ await Promise.allSettled(active)