@microvac/adapter-claude-local 0.0.0-stage → 0.1.0-rc.14

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 (242) hide show
  1. package/dist/cli/format-event.d.ts +2 -0
  2. package/dist/cli/format-event.d.ts.map +1 -0
  3. package/dist/cli/format-event.js +141 -0
  4. package/dist/cli/format-event.js.map +1 -0
  5. package/dist/cli/index.d.ts +2 -0
  6. package/dist/cli/index.d.ts.map +1 -0
  7. package/dist/cli/index.js +2 -0
  8. package/dist/cli/index.js.map +1 -0
  9. package/dist/cli/quota-probe.d.ts +3 -0
  10. package/dist/cli/quota-probe.d.ts.map +1 -0
  11. package/dist/cli/quota-probe.js +106 -0
  12. package/dist/cli/quota-probe.js.map +1 -0
  13. package/dist/index.d.ts +13 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +99 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/index.test.d.ts +2 -0
  18. package/dist/index.test.d.ts.map +1 -0
  19. package/dist/index.test.js +72 -0
  20. package/dist/index.test.js.map +1 -0
  21. package/dist/server/acp-billing.d.ts +13 -0
  22. package/dist/server/acp-billing.d.ts.map +1 -0
  23. package/dist/server/acp-billing.js +28 -0
  24. package/dist/server/acp-billing.js.map +1 -0
  25. package/dist/server/acp.auth.test.d.ts +2 -0
  26. package/dist/server/acp.auth.test.d.ts.map +1 -0
  27. package/dist/server/acp.auth.test.js +588 -0
  28. package/dist/server/acp.auth.test.js.map +1 -0
  29. package/dist/server/acp.d.ts +69 -0
  30. package/dist/server/acp.d.ts.map +1 -0
  31. package/dist/server/acp.js +882 -0
  32. package/dist/server/acp.js.map +1 -0
  33. package/dist/server/acp.quota.test.d.ts +2 -0
  34. package/dist/server/acp.quota.test.d.ts.map +1 -0
  35. package/dist/server/acp.quota.test.js +168 -0
  36. package/dist/server/acp.quota.test.js.map +1 -0
  37. package/dist/server/acp.test.d.ts +2 -0
  38. package/dist/server/acp.test.d.ts.map +1 -0
  39. package/dist/server/acp.test.js +1645 -0
  40. package/dist/server/acp.test.js.map +1 -0
  41. package/dist/server/auth-check.d.ts +8 -0
  42. package/dist/server/auth-check.d.ts.map +1 -0
  43. package/dist/server/auth-check.js +8 -0
  44. package/dist/server/auth-check.js.map +1 -0
  45. package/dist/server/claude-config.d.ts +73 -0
  46. package/dist/server/claude-config.d.ts.map +1 -0
  47. package/dist/server/claude-config.js +408 -0
  48. package/dist/server/claude-config.js.map +1 -0
  49. package/dist/server/claude-config.test.d.ts +2 -0
  50. package/dist/server/claude-config.test.d.ts.map +1 -0
  51. package/dist/server/claude-config.test.js +376 -0
  52. package/dist/server/claude-config.test.js.map +1 -0
  53. package/dist/server/cli-capabilities.d.ts +39 -0
  54. package/dist/server/cli-capabilities.d.ts.map +1 -0
  55. package/dist/server/cli-capabilities.js +149 -0
  56. package/dist/server/cli-capabilities.js.map +1 -0
  57. package/dist/server/cli-capabilities.test.d.ts +2 -0
  58. package/dist/server/cli-capabilities.test.d.ts.map +1 -0
  59. package/dist/server/cli-capabilities.test.js +35 -0
  60. package/dist/server/cli-capabilities.test.js.map +1 -0
  61. package/dist/server/config-schema.d.ts +3 -0
  62. package/dist/server/config-schema.d.ts.map +1 -0
  63. package/dist/server/config-schema.js +67 -0
  64. package/dist/server/config-schema.js.map +1 -0
  65. package/dist/server/engine-availability.test.d.ts +2 -0
  66. package/dist/server/engine-availability.test.d.ts.map +1 -0
  67. package/dist/server/engine-availability.test.js +70 -0
  68. package/dist/server/engine-availability.test.js.map +1 -0
  69. package/dist/server/execute.acp-fallback.test.d.ts +2 -0
  70. package/dist/server/execute.acp-fallback.test.d.ts.map +1 -0
  71. package/dist/server/execute.acp-fallback.test.js +104 -0
  72. package/dist/server/execute.acp-fallback.test.js.map +1 -0
  73. package/dist/server/execute.d.ts +23 -0
  74. package/dist/server/execute.d.ts.map +1 -0
  75. package/dist/server/execute.js +1212 -0
  76. package/dist/server/execute.js.map +1 -0
  77. package/dist/server/execute.max-turns-classification.test.d.ts +2 -0
  78. package/dist/server/execute.max-turns-classification.test.d.ts.map +1 -0
  79. package/dist/server/execute.max-turns-classification.test.js +82 -0
  80. package/dist/server/execute.max-turns-classification.test.js.map +1 -0
  81. package/dist/server/execute.remote.test.d.ts +2 -0
  82. package/dist/server/execute.remote.test.d.ts.map +1 -0
  83. package/dist/server/execute.remote.test.js +830 -0
  84. package/dist/server/execute.remote.test.js.map +1 -0
  85. package/dist/server/index.d.ts +16 -0
  86. package/dist/server/index.d.ts.map +1 -0
  87. package/dist/server/index.js +97 -0
  88. package/dist/server/index.js.map +1 -0
  89. package/dist/server/model-order.d.ts +14 -0
  90. package/dist/server/model-order.d.ts.map +1 -0
  91. package/dist/server/model-order.js +87 -0
  92. package/dist/server/model-order.js.map +1 -0
  93. package/dist/server/model-order.test.d.ts +2 -0
  94. package/dist/server/model-order.test.d.ts.map +1 -0
  95. package/dist/server/model-order.test.js +82 -0
  96. package/dist/server/model-order.test.js.map +1 -0
  97. package/dist/server/models.d.ts +13 -0
  98. package/dist/server/models.d.ts.map +1 -0
  99. package/dist/server/models.js +163 -0
  100. package/dist/server/models.js.map +1 -0
  101. package/dist/server/parse.d.ts +101 -0
  102. package/dist/server/parse.d.ts.map +1 -0
  103. package/dist/server/parse.js +504 -0
  104. package/dist/server/parse.js.map +1 -0
  105. package/dist/server/parse.test.d.ts +2 -0
  106. package/dist/server/parse.test.d.ts.map +1 -0
  107. package/dist/server/parse.test.js +432 -0
  108. package/dist/server/parse.test.js.map +1 -0
  109. package/dist/server/permissions.d.ts +14 -0
  110. package/dist/server/permissions.d.ts.map +1 -0
  111. package/dist/server/permissions.js +13 -0
  112. package/dist/server/permissions.js.map +1 -0
  113. package/dist/server/permissions.test.d.ts +2 -0
  114. package/dist/server/permissions.test.d.ts.map +1 -0
  115. package/dist/server/permissions.test.js +22 -0
  116. package/dist/server/permissions.test.js.map +1 -0
  117. package/dist/server/probe-diagnostics.d.ts +102 -0
  118. package/dist/server/probe-diagnostics.d.ts.map +1 -0
  119. package/dist/server/probe-diagnostics.js +140 -0
  120. package/dist/server/probe-diagnostics.js.map +1 -0
  121. package/dist/server/probe-diagnostics.test.d.ts +2 -0
  122. package/dist/server/probe-diagnostics.test.d.ts.map +1 -0
  123. package/dist/server/probe-diagnostics.test.js +114 -0
  124. package/dist/server/probe-diagnostics.test.js.map +1 -0
  125. package/dist/server/probe-env.d.ts +42 -0
  126. package/dist/server/probe-env.d.ts.map +1 -0
  127. package/dist/server/probe-env.js +149 -0
  128. package/dist/server/probe-env.js.map +1 -0
  129. package/dist/server/probe-env.test.d.ts +2 -0
  130. package/dist/server/probe-env.test.d.ts.map +1 -0
  131. package/dist/server/probe-env.test.js +135 -0
  132. package/dist/server/probe-env.test.js.map +1 -0
  133. package/dist/server/probe-redaction.test.d.ts +2 -0
  134. package/dist/server/probe-redaction.test.d.ts.map +1 -0
  135. package/dist/server/probe-redaction.test.js +86 -0
  136. package/dist/server/probe-redaction.test.js.map +1 -0
  137. package/dist/server/prompt-cache.d.ts +17 -0
  138. package/dist/server/prompt-cache.d.ts.map +1 -0
  139. package/dist/server/prompt-cache.js +126 -0
  140. package/dist/server/prompt-cache.js.map +1 -0
  141. package/dist/server/quota-keychain.test.d.ts +2 -0
  142. package/dist/server/quota-keychain.test.d.ts.map +1 -0
  143. package/dist/server/quota-keychain.test.js +83 -0
  144. package/dist/server/quota-keychain.test.js.map +1 -0
  145. package/dist/server/quota.d.ts +30 -0
  146. package/dist/server/quota.d.ts.map +1 -0
  147. package/dist/server/quota.js +544 -0
  148. package/dist/server/quota.js.map +1 -0
  149. package/dist/server/sandbox-cli-version.d.ts +10 -0
  150. package/dist/server/sandbox-cli-version.d.ts.map +1 -0
  151. package/dist/server/sandbox-cli-version.js +62 -0
  152. package/dist/server/sandbox-cli-version.js.map +1 -0
  153. package/dist/server/sandbox-cli-version.test.d.ts +2 -0
  154. package/dist/server/sandbox-cli-version.test.d.ts.map +1 -0
  155. package/dist/server/sandbox-cli-version.test.js +107 -0
  156. package/dist/server/sandbox-cli-version.test.js.map +1 -0
  157. package/dist/server/setup-token-characterization.test.d.ts +2 -0
  158. package/dist/server/setup-token-characterization.test.d.ts.map +1 -0
  159. package/dist/server/setup-token-characterization.test.js +123 -0
  160. package/dist/server/setup-token-characterization.test.js.map +1 -0
  161. package/dist/server/setup-token-parse.d.ts +50 -0
  162. package/dist/server/setup-token-parse.d.ts.map +1 -0
  163. package/dist/server/setup-token-parse.js +553 -0
  164. package/dist/server/setup-token-parse.js.map +1 -0
  165. package/dist/server/setup-token-parse.test.d.ts +2 -0
  166. package/dist/server/setup-token-parse.test.d.ts.map +1 -0
  167. package/dist/server/setup-token-parse.test.js +684 -0
  168. package/dist/server/setup-token-parse.test.js.map +1 -0
  169. package/dist/server/setup-token-runner.d.ts +117 -0
  170. package/dist/server/setup-token-runner.d.ts.map +1 -0
  171. package/dist/server/setup-token-runner.js +346 -0
  172. package/dist/server/setup-token-runner.js.map +1 -0
  173. package/dist/server/setup-token-runner.test.d.ts +2 -0
  174. package/dist/server/setup-token-runner.test.d.ts.map +1 -0
  175. package/dist/server/setup-token-runner.test.js +424 -0
  176. package/dist/server/setup-token-runner.test.js.map +1 -0
  177. package/dist/server/skills.d.ts +8 -0
  178. package/dist/server/skills.d.ts.map +1 -0
  179. package/dist/server/skills.js +42 -0
  180. package/dist/server/skills.js.map +1 -0
  181. package/dist/server/test.d.ts +3 -0
  182. package/dist/server/test.d.ts.map +1 -0
  183. package/dist/server/test.js +454 -0
  184. package/dist/server/test.js.map +1 -0
  185. package/dist/server/test.probe.test.d.ts +2 -0
  186. package/dist/server/test.probe.test.d.ts.map +1 -0
  187. package/dist/server/test.probe.test.js +609 -0
  188. package/dist/server/test.probe.test.js.map +1 -0
  189. package/dist/server/test.remote.test.d.ts +2 -0
  190. package/dist/server/test.remote.test.d.ts.map +1 -0
  191. package/dist/server/test.remote.test.js +189 -0
  192. package/dist/server/test.remote.test.js.map +1 -0
  193. package/dist/ui/build-config.d.ts +3 -0
  194. package/dist/ui/build-config.d.ts.map +1 -0
  195. package/dist/ui/build-config.js +82 -0
  196. package/dist/ui/build-config.js.map +1 -0
  197. package/dist/ui/build-config.test.d.ts +2 -0
  198. package/dist/ui/build-config.test.d.ts.map +1 -0
  199. package/dist/ui/build-config.test.js +82 -0
  200. package/dist/ui/build-config.test.js.map +1 -0
  201. package/dist/ui/index.d.ts +3 -0
  202. package/dist/ui/index.d.ts.map +1 -0
  203. package/dist/ui/index.js +3 -0
  204. package/dist/ui/index.js.map +1 -0
  205. package/dist/ui/parse-stdout.d.ts +3 -0
  206. package/dist/ui/parse-stdout.d.ts.map +1 -0
  207. package/dist/ui/parse-stdout.js +153 -0
  208. package/dist/ui/parse-stdout.js.map +1 -0
  209. package/package.json +57 -4
  210. package/skills/agentmail/SKILL.md +70 -0
  211. package/skills/complain/LICENSE +27 -0
  212. package/skills/complain/SKILL.md +68 -0
  213. package/skills/paperclip/SKILL.md +864 -0
  214. package/skills/paperclip/references/api-reference.md +1814 -0
  215. package/skills/paperclip/references/artifacts.md +163 -0
  216. package/skills/paperclip/references/cases.md +570 -0
  217. package/skills/paperclip/references/company-skills.md +266 -0
  218. package/skills/paperclip/references/issue-documents.md +58 -0
  219. package/skills/paperclip/references/issue-workspaces.md +94 -0
  220. package/skills/paperclip/references/routines.md +249 -0
  221. package/skills/paperclip/references/run-diagnostics.md +28 -0
  222. package/skills/paperclip/references/workflows.md +141 -0
  223. package/skills/paperclip/scripts/paperclip-issue-update.sh +166 -0
  224. package/skills/paperclip/scripts/paperclip-upload-artifact.sh +603 -0
  225. package/skills/paperclip/scripts/submit-agent-commentary.mjs +52 -0
  226. package/skills/paperclip-board/SKILL.md +633 -0
  227. package/skills/paperclip-converting-plans-to-tasks/SKILL.md +28 -0
  228. package/skills/paperclip-create-agent/SKILL.md +213 -0
  229. package/skills/paperclip-create-agent/references/agent-instruction-templates.md +24 -0
  230. package/skills/paperclip-create-agent/references/agents/coder.md +18 -0
  231. package/skills/paperclip-create-agent/references/agents/qa.md +18 -0
  232. package/skills/paperclip-create-agent/references/agents/securityengineer.md +26 -0
  233. package/skills/paperclip-create-agent/references/agents/uxdesigner.md +18 -0
  234. package/skills/paperclip-create-agent/references/api-reference.md +110 -0
  235. package/skills/paperclip-create-agent/references/baseline-role-guide.md +22 -0
  236. package/skills/paperclip-create-agent/references/draft-review-checklist.md +29 -0
  237. package/skills/para-memory-files/SKILL.md +100 -0
  238. package/skills/para-memory-files/references/schemas.md +35 -0
  239. package/skills/slack/SKILL.md +92 -0
  240. package/skills/suggestion-box/LICENSE +27 -0
  241. package/skills/suggestion-box/SKILL.md +77 -0
  242. package/README.md +0 -3
@@ -0,0 +1,882 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { parseLocalProcessFilesystemScope, parseLocalProcessNetworkScope, } from "@paperclipai/adapter-utils/local-process-sandbox";
5
+ import { ensureAdapterExecutionTargetCommandResolvable, ensureAdapterExecutionTargetDirectory, readAdapterExecutionTarget, resolveAdapterExecutionTargetCwd, runAdapterExecutionTargetProcess, } from "@paperclipai/adapter-utils/execution-target";
6
+ import { DEFAULT_ACP_ENGINE_MODE, DEFAULT_ACP_ENGINE_NON_INTERACTIVE_PERMISSIONS, DEFAULT_ACP_ENGINE_PERMISSION_MODE, DEFAULT_ACP_ENGINE_WARM_HANDLE_IDLE_MS, } from "@paperclipai/adapter-utils/acpx-engine/constants";
7
+ import { asBoolean, asNumber, asString, parseObject, } from "@paperclipai/adapter-utils/server-utils";
8
+ import { resolveEnvBillingIdentity, resolveManagedApiKeyBilling } from "./acp-billing.js";
9
+ import { materializeRemoteClaudeConfig, overrideRemoteClaudeLocalPermissionMode, prepareClaudeConfigSeed, prepareSandboxClaudeProbeRuntime, resolveRemoteClaudeToolShellPrefixPath, } from "./claude-config.js";
10
+ import { buildAdapterTestTargetCheck, buildClaudeLoginRequiredHint, classifyThrownErrorClass, logSandboxProbeDiagnostic, } from "./probe-diagnostics.js";
11
+ import { createWorkspaceRestoreTeardown } from "@paperclipai/adapter-utils/workspace-restore-teardown";
12
+ import { buildLocalAdapterTestProbeEnv } from "./probe-env.js";
13
+ import { detectClaudeLoginRequired, extractClaudeRetryNotBefore, isClaudeProviderQuotaError, parseClaudeStreamJson } from "./parse.js";
14
+ import { buildClaudeProbePermissionArgs, claudeSandboxPermissionEnv } from "./permissions.js";
15
+ import { ADAPTER_AUTH_MISSING_CHECK_CODE } from "./auth-check.js";
16
+ import { claudeCliVersionAtLeast, minimumClaudeCliVersionForModel, readBundledClaudeCodeVersion, } from "./cli-capabilities.js";
17
+ import { resolveClaudeModel, SANDBOX_INSTALL_COMMAND } from "../index.js";
18
+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));
19
+ const packageRootDir = path.resolve(moduleDir, "../..");
20
+ const MIN_ACP_NODE_VERSION = "24.11.0";
21
+ function normalizeEngine(value) {
22
+ const raw = typeof value === "string" ? value.trim().toLowerCase() : "";
23
+ if (raw === "acp")
24
+ return { engine: "acp", explicit: true };
25
+ if (raw === "cli")
26
+ return { engine: "cli", explicit: true };
27
+ return { engine: "acp", explicit: false };
28
+ }
29
+ export function resolveClaudeExecutionEngine(config) {
30
+ return normalizeEngine(config.engine);
31
+ }
32
+ export async function resolveClaudeExecutionEngineForRun(input) {
33
+ const selection = normalizeEngine(input.config.engine);
34
+ // Engine availability must never change the agent's execution or permission contract.
35
+ if (selection.engine === "cli")
36
+ return selection;
37
+ const unavailable = (reason) => ({
38
+ ...selection,
39
+ unavailableReason: `${reason} Repair the ACP setup, or explicitly set engine=cli to use the CLI engine.`,
40
+ });
41
+ const filesystemScope = parseLocalProcessFilesystemScope(input.config.filesystemScope);
42
+ const networkScope = parseLocalProcessNetworkScope(input.config.networkScope);
43
+ if (filesystemScope || networkScope) {
44
+ return unavailable("Local filesystem/network confinement requires the Claude CLI engine; ACP confinement is not supported.");
45
+ }
46
+ const reason = await claudeAcpUnavailableReason(input);
47
+ return reason ? unavailable(reason) : selection;
48
+ }
49
+ function firstNonEmptyString(...values) {
50
+ for (const value of values) {
51
+ if (typeof value !== "string")
52
+ continue;
53
+ const trimmed = value.trim();
54
+ if (trimmed.length > 0)
55
+ return trimmed;
56
+ }
57
+ return undefined;
58
+ }
59
+ function resolveAcpPermissionMode(config) {
60
+ const requested = firstNonEmptyString(config.permissionMode);
61
+ return requested === undefined || requested === "default" ? DEFAULT_ACP_ENGINE_PERMISSION_MODE : requested;
62
+ }
63
+ export function buildClaudeAcpConfig(config, inheritedEnv = {}) {
64
+ const env = parseObject(config.env);
65
+ const model = resolveClaudeModel(config.model, { ...inheritedEnv, ...env });
66
+ const agentCommand = firstNonEmptyString(config.agentCommand, config.acpAgentCommand);
67
+ const stateDir = firstNonEmptyString(config.stateDir, config.acpStateDir);
68
+ const mode = firstNonEmptyString(config.mode, config.acpMode) ?? DEFAULT_ACP_ENGINE_MODE;
69
+ const permissionMode = firstNonEmptyString(config.permissionMode, config.acpPermissionMode) ??
70
+ DEFAULT_ACP_ENGINE_PERMISSION_MODE;
71
+ const nonInteractivePermissions = firstNonEmptyString(config.nonInteractivePermissions, config.acpNonInteractivePermissions) ??
72
+ DEFAULT_ACP_ENGINE_NON_INTERACTIVE_PERMISSIONS;
73
+ const warmHandleIdleMs = config.warmHandleIdleMs ??
74
+ config.acpWarmHandleIdleMs ??
75
+ DEFAULT_ACP_ENGINE_WARM_HANDLE_IDLE_MS;
76
+ return {
77
+ ...config,
78
+ model,
79
+ // ACP reads ANTHROPIC_MODEL at startup; keep it aligned with CLI precedence.
80
+ ...(model ? { env: { ...env, ANTHROPIC_MODEL: model } } : {}),
81
+ agent: "claude",
82
+ mode,
83
+ permissionMode,
84
+ nonInteractivePermissions,
85
+ warmHandleIdleMs,
86
+ ...(agentCommand ? { agentCommand } : {}),
87
+ ...(stateDir ? { stateDir } : {}),
88
+ };
89
+ }
90
+ /**
91
+ * Classify billing the same way the Claude CLI lane does so ACP runs land in
92
+ * the cost ledger with a real provider/billingType instead of acpx/unknown.
93
+ * Host env only counts for local execution targets; remote targets see just
94
+ * the adapter-config env.
95
+ */
96
+ export function resolveClaudeAcpBillingIdentity(ctx) {
97
+ const connection = resolveManagedApiKeyBilling(ctx.config);
98
+ if (connection)
99
+ return connection;
100
+ const envConfig = parseObject(parseObject(ctx.config).env);
101
+ const target = readAdapterExecutionTarget({
102
+ executionTarget: ctx.executionTarget,
103
+ legacyRemoteExecution: ctx.executionTransport?.remoteExecution,
104
+ });
105
+ const considerHostEnv = target?.kind !== "remote";
106
+ const readEnvValue = (key) => {
107
+ const fromConfig = envConfig[key];
108
+ if (typeof fromConfig === "string" && fromConfig.trim())
109
+ return fromConfig.trim();
110
+ const fromHost = considerHostEnv ? process.env[key] : undefined;
111
+ return typeof fromHost === "string" ? fromHost.trim() : "";
112
+ };
113
+ return resolveEnvBillingIdentity(readEnvValue);
114
+ }
115
+ /**
116
+ * Claude remote managed-home seed for the runner-backed remote sandbox ACP lane.
117
+ * Mirrors the Claude CLI lane (`claude-local/execute.ts`): ship a sanitized
118
+ * config seed (settings.json + CLAUDE.md, no credentials) as the `config-seed`
119
+ * asset, materialize it into an in-sandbox config dir (copying the sandbox's own
120
+ * `$HOME/.claude` credentials in), then repoint `CLAUDE_CONFIG_DIR` onto that
121
+ * in-sandbox config dir. Claude has no credential copy-back (its CLI lane has
122
+ * none — mirroring the CLI is the contract). The teardown hook therefore only
123
+ * syncs the sandbox workspace back to the host; it does not touch credentials.
124
+ *
125
+ * An explicit `CLAUDE_CONFIG_DIR` (user-managed) is honored only if it can reach
126
+ * the remote sandbox; a host-only path cannot, so we do NOT forward it verbatim
127
+ * (that would start remote Claude with no config/credentials). See the branch
128
+ * below for the two portable dispositions. The engine's `useRemoteProcessSession`
129
+ * gate already guarantees the remote sandbox (managed-home) target.
130
+ */
131
+ async function prepareClaudeRemoteManagedHome(input) {
132
+ const { env, runId, onLog, executionTarget } = input;
133
+ // Fail-open workspace sync-back for every exit path (mirrors the Claude CLI
134
+ // lane's restore-hook finally and the Codex ACP seam's teardown). Claude has no
135
+ // credential copy-back, so the teardown only syncs the sandbox workspace back to
136
+ // the host. A restore miss is logged and never fails the run.
137
+ const registerWorkspaceSyncBack = (stagedRuntime) => createWorkspaceRestoreTeardown({
138
+ stagedRuntime,
139
+ onLog,
140
+ startMessage: "[paperclip] Restoring workspace changes from the sandbox.\n",
141
+ failurePrefix: "[paperclip] Claude ACP teardown workspace restore failed",
142
+ });
143
+ const envConfig = parseObject(input.config.env);
144
+ const explicitClaudeConfigDir = typeof envConfig.CLAUDE_CONFIG_DIR === "string" && envConfig.CLAUDE_CONFIG_DIR.trim().length > 0
145
+ ? envConfig.CLAUDE_CONFIG_DIR.trim()
146
+ : "";
147
+ if (explicitClaudeConfigDir && !input.config.managedAiConnection) {
148
+ // User-managed escape hatch. Unlike the Claude CLI lane
149
+ // (`claude-local/execute.ts`), which runs the process on the same host and can
150
+ // forward the operator's path verbatim, the remote ACP lane spawns Claude
151
+ // inside a sandbox that CANNOT see host paths. Forwarding an absolute host
152
+ // path unchanged would leave remote Claude without the requested config or
153
+ // credentials, so we choose one of two portable dispositions:
154
+ // 1. The path lives INSIDE the staged workspace → remap its prefix onto the
155
+ // in-sandbox workspace dir so it resolves against the copied files.
156
+ // 2. The path is host-only (outside the workspace) → it cannot cross into
157
+ // the sandbox, so ignore the un-portable override and seed the managed
158
+ // config instead (falling through below), which guarantees working
159
+ // config/credentials. Logged loudly so the substitution is diagnosable.
160
+ const relativeToWorkspace = path.relative(input.workspaceLocalDir, explicitClaudeConfigDir);
161
+ const isUnderWorkspace = relativeToWorkspace.length > 0 &&
162
+ !relativeToWorkspace.startsWith("..") &&
163
+ !path.isAbsolute(relativeToWorkspace);
164
+ if (isUnderWorkspace) {
165
+ const stagedRuntime = await input.stage([]);
166
+ const remoteWorkspaceDir = stagedRuntime.workspaceRemoteDir ?? input.workspaceLocalDir;
167
+ const remappedConfigDir = path.posix.join(remoteWorkspaceDir, relativeToWorkspace.split(path.sep).join(path.posix.sep));
168
+ env.CLAUDE_CONFIG_DIR = remappedConfigDir;
169
+ await onLog("stdout", `[paperclip] Remapped operator CLAUDE_CONFIG_DIR from host path ${explicitClaudeConfigDir} onto the in-sandbox workspace path ${remappedConfigDir} for the remote ACP run.\n`);
170
+ return { stagedRuntime, teardown: registerWorkspaceSyncBack(stagedRuntime) };
171
+ }
172
+ await onLog("stderr", `[paperclip] operator-provided CLAUDE_CONFIG_DIR=${explicitClaudeConfigDir} is outside the staged workspace and cannot reach the remote sandbox; ignoring the host-only path and seeding the managed Claude config instead.\n`);
173
+ }
174
+ // Content-addressed sanitized seed (managed cache under the instance root, not
175
+ // a temp dir — reused across runs, so no teardown cleanup).
176
+ const bypassPermissions = resolveAcpPermissionMode(input.config) === "approve-all";
177
+ const claudeConfigSeedDir = input.config.managedAiConnection
178
+ ? explicitClaudeConfigDir
179
+ : await prepareClaudeConfigSeed(process.env, onLog, input.companyId, {
180
+ permissionDefaultMode: bypassPermissions ? "bypassPermissions" : "default",
181
+ });
182
+ // Ship the per-run skill bundle, staged only when the run selected at
183
+ // least one skill. The bundle directory holds a plain copy of each
184
+ // selected skill's files (`materializePaperclipSkillCopy` never copies a
185
+ // symbolic link, at the root or at any depth). So the bundle asset stages
186
+ // with `followSymlinks: false`: staging never needs to carry a symbolic
187
+ // link's target content, and refusing to follow one stops a link planted
188
+ // in the bundle directory after materialization (for example by a
189
+ // concurrent writer) from pulling an arbitrary host file into the sandbox.
190
+ // The engine rewrites the prompt onto the in-sandbox copy once this asset
191
+ // is staged.
192
+ const stagedRuntime = await input.stage([
193
+ { key: "config-seed", localDir: claudeConfigSeedDir, followSymlinks: true },
194
+ ...(input.skillsBundleDir
195
+ ? [{ key: "skills", localDir: input.skillsBundleDir, followSymlinks: false }]
196
+ : []),
197
+ ]);
198
+ const remoteClaudeRuntimeRoot = stagedRuntime.runtimeRootDir ??
199
+ path.posix.join(stagedRuntime.workspaceRemoteDir ?? input.workspaceLocalDir, ".paperclip-runtime", "claude");
200
+ const remoteClaudeConfigSeedDir = stagedRuntime.assetDirs["config-seed"] ?? path.posix.join(remoteClaudeRuntimeRoot, "config-seed");
201
+ const remoteClaudeConfigDir = path.posix.join(remoteClaudeRuntimeRoot, "config");
202
+ const remoteToolShellPrefixPath = resolveRemoteClaudeToolShellPrefixPath(env, remoteClaudeRuntimeRoot);
203
+ await onLog("stdout", `[paperclip] Materializing Claude auth/config into ${remoteClaudeConfigDir}.\n`);
204
+ const { toolShellPrefixInstalled } = await materializeRemoteClaudeConfig({
205
+ allowHostCredentials: !input.config.managedAiConnection,
206
+ runId,
207
+ target: executionTarget,
208
+ remoteClaudeConfigDir,
209
+ remoteClaudeConfigSeedDir,
210
+ remoteToolShellPrefixPath,
211
+ options: {
212
+ cwd: stagedRuntime.workspaceRemoteDir ?? input.workspaceLocalDir,
213
+ env,
214
+ timeoutSec: Math.max(input.timeoutSec, 15),
215
+ graceSec: 20,
216
+ onLog,
217
+ },
218
+ });
219
+ // Repoint CLAUDE_CONFIG_DIR onto the in-sandbox config dir.
220
+ env.CLAUDE_CONFIG_DIR = remoteClaudeConfigDir;
221
+ const localPermissionOverride = bypassPermissions && !input.config.managedAiConnection
222
+ ? await overrideRemoteClaudeLocalPermissionMode({
223
+ runId,
224
+ target: executionTarget,
225
+ workspaceLocalDir: input.workspaceLocalDir,
226
+ workspaceRemoteDir: stagedRuntime.workspaceRemoteDir ?? input.workspaceLocalDir,
227
+ defaultMode: "bypassPermissions",
228
+ options: {
229
+ cwd: stagedRuntime.workspaceRemoteDir ?? input.workspaceLocalDir,
230
+ env,
231
+ timeoutSec: Math.max(input.timeoutSec, 15),
232
+ graceSec: 20,
233
+ onLog,
234
+ },
235
+ })
236
+ : null;
237
+ if (bypassPermissions && !input.config.managedAiConnection) {
238
+ Object.assign(env, claudeSandboxPermissionEnv({ dangerouslySkipPermissions: true, targetIsSandbox: true }));
239
+ }
240
+ if (toolShellPrefixInstalled && remoteToolShellPrefixPath) {
241
+ env.CLAUDE_CODE_SHELL_PREFIX = remoteToolShellPrefixPath;
242
+ }
243
+ const syncBack = registerWorkspaceSyncBack(stagedRuntime);
244
+ const teardown = localPermissionOverride && syncBack
245
+ ? async () => {
246
+ await localPermissionOverride.beforeRestore();
247
+ const outcome = await syncBack();
248
+ await localPermissionOverride.afterRestore();
249
+ return outcome;
250
+ }
251
+ : syncBack;
252
+ return { stagedRuntime, teardown };
253
+ }
254
+ export function classifyClaudeTerminalSessionFailure(failure, now) {
255
+ // Claude's typed AIR access category is emitted for auth_required. This is
256
+ // a provider signal, including its generic fallback, not a tool permission
257
+ // error inferred from text. Keep it on the existing sign-in recovery path.
258
+ if (failure.category === "access")
259
+ return { errorCode: "acpx_auth_required" };
260
+ // `limit` also includes context, turn, rate and configured budget limits.
261
+ // Only the provider's quota wording qualifies for a quota wait.
262
+ if (failure.category !== "limit")
263
+ return null;
264
+ const surface = { errorMessage: [failure.title, failure.details].filter(Boolean).join("\n") };
265
+ // claude-agent-acp uses this exact quota_exhausted fallback when no provider
266
+ // title is available. It does not match the CLI's usage-limit wording.
267
+ const isQuotaFallback = failure.title === "The Claude account has no available quota.";
268
+ if (!isQuotaFallback && !isClaudeProviderQuotaError(surface))
269
+ return null;
270
+ const retryNotBefore = extractClaudeRetryNotBefore(surface, now)?.toISOString();
271
+ return {
272
+ errorCode: "provider_quota",
273
+ errorFamily: "provider_quota",
274
+ ...(retryNotBefore ? { retryNotBefore } : {}),
275
+ };
276
+ }
277
+ function withClaudeAcpDefaults(options) {
278
+ return {
279
+ resolveBillingIdentity: resolveClaudeAcpBillingIdentity,
280
+ prepareRemoteManagedHome: prepareClaudeRemoteManagedHome,
281
+ classifyTerminalSessionFailure: classifyClaudeTerminalSessionFailure,
282
+ ...options,
283
+ adapterType: "claude_local",
284
+ moduleDir,
285
+ packageRootDir,
286
+ };
287
+ }
288
+ /**
289
+ * The generic error code the shared acpx engine emits when a run fails because
290
+ * the agent has no ready authentication. The shared engine stays vendor-neutral,
291
+ * so it keeps this generic code. See `adapter-utils/acpx-engine/execute.ts`.
292
+ */
293
+ const ACPX_AUTH_REQUIRED_ERROR_CODE = "acpx_auth_required";
294
+ /**
295
+ * The Claude-specific error code the user interface reads to show the Claude
296
+ * login affordance on a run. The Claude CLI lane already emits this code. See
297
+ * `execute.ts` and the user interface gate in `ui/src/pages/AgentDetail.tsx`.
298
+ */
299
+ const CLAUDE_AUTH_REQUIRED_ERROR_CODE = "claude_auth_required";
300
+ /**
301
+ * Translate the generic acpx auth-required code into the Claude-specific code at
302
+ * the claude-local boundary. The shared acpx engine reports the generic
303
+ * `acpx_auth_required` code for every adapter. The user interface run gate reads
304
+ * the Claude-specific `claude_auth_required` code, the same code the Claude CLI
305
+ * lane emits. Without this translation the default ACP run never shows the login
306
+ * prompt. Provider diagnostics stay intact; the generic terminal-access
307
+ * fallback instead explains that Claude needs sign-in.
308
+ */
309
+ export function mapClaudeAcpAuthErrorCode(result) {
310
+ if (result.errorCode !== ACPX_AUTH_REQUIRED_ERROR_CODE)
311
+ return result;
312
+ return {
313
+ ...result,
314
+ errorCode: CLAUDE_AUTH_REQUIRED_ERROR_CODE,
315
+ ...(result.errorMessage === "ACP agent reported a terminal access failure."
316
+ ? { errorMessage: "Claude sign-in failed. Sign in again and try again." }
317
+ : {}),
318
+ };
319
+ }
320
+ /**
321
+ * Mirror the CLI lane's minimum-version check (`execute.ts`) for the Claude
322
+ * Code bundled with the local ACP bridge. Without it an unsupported model
323
+ * fails only as a generic terminal service failure. A remote target, a custom
324
+ * agentCommand, or CLAUDE_CODE_EXECUTABLE brings its own Claude Code.
325
+ */
326
+ async function bundledClaudeCodeVersionFailure(ctx, config, target) {
327
+ const model = asString(config.model, "");
328
+ const minimumCliVersion = minimumClaudeCliVersionForModel(model);
329
+ if (!minimumCliVersion ||
330
+ target?.kind === "remote" ||
331
+ firstNonEmptyString(config.agentCommand) ||
332
+ firstNonEmptyString(parseObject(config.env).CLAUDE_CODE_EXECUTABLE)) {
333
+ return null;
334
+ }
335
+ const bundledCliVersion = await readBundledClaudeCodeVersion();
336
+ if (!bundledCliVersion || claudeCliVersionAtLeast(bundledCliVersion, minimumCliVersion))
337
+ return null;
338
+ const errorMessage = `${model} requires Claude Code ${minimumCliVersion} or newer; the ACP lane runs the bundled Claude Code ${bundledCliVersion}. ` +
339
+ "Set CLAUDE_CODE_EXECUTABLE in the agent env to a newer Claude Code, or set engine=cli, before retrying.";
340
+ await ctx.onLog("stderr", `[paperclip] ${errorMessage}\n`);
341
+ return {
342
+ exitCode: 1,
343
+ signal: null,
344
+ timedOut: false,
345
+ errorMessage,
346
+ errorCode: "claude_cli_version_incompatible",
347
+ ...resolveClaudeAcpBillingIdentity(ctx),
348
+ model,
349
+ resultJson: {
350
+ stopReason: "claude_cli_version_incompatible",
351
+ requiredClaudeCodeVersion: minimumCliVersion,
352
+ detectedClaudeCodeVersion: bundledCliVersion,
353
+ },
354
+ };
355
+ }
356
+ export function createClaudeAcpExecutor(options = {}) {
357
+ let executor = null;
358
+ return async (ctx) => {
359
+ let currentExecutor = executor;
360
+ if (!currentExecutor) {
361
+ const { createAcpxEngineExecutor } = await import("@paperclipai/adapter-utils/acpx-engine/execute");
362
+ currentExecutor = createAcpxEngineExecutor(withClaudeAcpDefaults(options));
363
+ executor = currentExecutor;
364
+ }
365
+ const target = readAdapterExecutionTarget({
366
+ executionTarget: ctx.executionTarget,
367
+ legacyRemoteExecution: ctx.executionTransport?.remoteExecution,
368
+ });
369
+ const config = buildClaudeAcpConfig(ctx.config, target?.kind === "remote" ? {} : process.env);
370
+ const versionFailure = await bundledClaudeCodeVersionFailure(ctx, config, target);
371
+ if (versionFailure)
372
+ return versionFailure;
373
+ const result = await currentExecutor({ ...ctx, config });
374
+ return mapClaudeAcpAuthErrorCode(result);
375
+ };
376
+ }
377
+ function parseVersion(version) {
378
+ const match = version.match(/^v?(\d+)\.(\d+)\.(\d+)/);
379
+ if (!match)
380
+ return [0, 0, 0];
381
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
382
+ }
383
+ export function nodeVersionMeetsClaudeAcpMinimum(version = process.version) {
384
+ const [major, minor, patch] = parseVersion(version);
385
+ const [minMajor, minMinor, minPatch] = parseVersion(MIN_ACP_NODE_VERSION);
386
+ if (major !== minMajor)
387
+ return major > minMajor;
388
+ if (minor !== minMinor)
389
+ return minor > minMinor;
390
+ return patch >= minPatch;
391
+ }
392
+ async function pathExists(candidate) {
393
+ return fs.access(candidate).then(() => true).catch(() => false);
394
+ }
395
+ function hasPathSeparator(command) {
396
+ return command.includes("/") || command.includes("\\");
397
+ }
398
+ function looksLikeShellCommand(command) {
399
+ return /\s/.test(command.trim());
400
+ }
401
+ async function findCommandOnPath(binName) {
402
+ const pathValue = process.env.PATH ?? "";
403
+ for (const segment of pathValue.split(path.delimiter)) {
404
+ if (!segment)
405
+ continue;
406
+ const candidate = path.join(segment, binName);
407
+ if (await pathExists(candidate))
408
+ return candidate;
409
+ }
410
+ return null;
411
+ }
412
+ async function findAncestorBin(startDir, binName) {
413
+ let current = path.resolve(startDir);
414
+ while (true) {
415
+ const candidate = path.join(current, "node_modules", ".bin", binName);
416
+ if (await pathExists(candidate))
417
+ return candidate;
418
+ const parent = path.dirname(current);
419
+ if (parent === current)
420
+ return null;
421
+ current = parent;
422
+ }
423
+ }
424
+ async function commandIsResolvable(command, input) {
425
+ const trimmed = command.trim();
426
+ if (!trimmed)
427
+ return false;
428
+ if (looksLikeShellCommand(trimmed))
429
+ return true;
430
+ const target = readAdapterExecutionTarget({
431
+ executionTarget: input?.executionTarget,
432
+ legacyRemoteExecution: input?.executionTransport?.remoteExecution,
433
+ });
434
+ if (target?.kind === "remote") {
435
+ try {
436
+ await ensureAdapterExecutionTargetCommandResolvable(trimmed, target, resolveAdapterExecutionTargetCwd(target, asString(input?.config.cwd, ""), process.cwd()), target.transport === "ssh" ? { PATH: process.env.PATH } : {}, {
437
+ // Fresh sandboxes need the same ACP server that ships with this
438
+ // adapter. Only bootstrap our default command; an operator's custom
439
+ // command must remain an actionable setup failure.
440
+ ...(target.transport === "sandbox" && trimmed === "claude-agent-acp" &&
441
+ !firstNonEmptyString(input?.config.agentCommand, input?.config.acpAgentCommand)
442
+ ? { installCommand: "npm install -g @agentclientprotocol/claude-agent-acp@0.73.0", timeoutSec: 120 }
443
+ : {}),
444
+ });
445
+ return true;
446
+ }
447
+ catch {
448
+ return false;
449
+ }
450
+ }
451
+ if (path.isAbsolute(trimmed) || hasPathSeparator(trimmed))
452
+ return pathExists(trimmed);
453
+ return (await findCommandOnPath(trimmed)) !== null;
454
+ }
455
+ async function resolveClaudeAcpCommand(config) {
456
+ const configured = firstNonEmptyString(config.agentCommand, config.acpAgentCommand);
457
+ if (configured)
458
+ return configured;
459
+ return ((await findAncestorBin(packageRootDir, "claude-agent-acp")) ??
460
+ (await findCommandOnPath("claude-agent-acp")) ??
461
+ path.join(packageRootDir, "node_modules", ".bin", "claude-agent-acp"));
462
+ }
463
+ function sandboxTargetHasProcessSessionBridge(target) {
464
+ return target?.kind === "remote" && target.transport === "sandbox" && Boolean(target.runner);
465
+ }
466
+ async function resolveClaudeAcpCommandForTarget(config, target) {
467
+ const configured = firstNonEmptyString(config.agentCommand, config.acpAgentCommand);
468
+ if (configured)
469
+ return configured;
470
+ if (target?.kind === "remote")
471
+ return "claude-agent-acp";
472
+ return resolveClaudeAcpCommand(config);
473
+ }
474
+ async function claudeAcpUnavailableReason(input) {
475
+ const target = readAdapterExecutionTarget({
476
+ executionTarget: input.executionTarget,
477
+ legacyRemoteExecution: input.executionTransport?.remoteExecution,
478
+ });
479
+ const managedSsh = target?.kind === "remote" && target.transport === "ssh"
480
+ && target.spec.useHostAuth === false && Boolean(input.config.managedAiConnection);
481
+ if (target?.kind === "remote" && !sandboxTargetHasProcessSessionBridge(target) && !managedSsh) {
482
+ if (target.transport === "sandbox") {
483
+ return "Claude ACP requires a bidirectional remote process target; this sandbox exposes only one-shot command execution.";
484
+ }
485
+ return "Claude ACP requires an agent-managed SSH account; host authentication is supported by the CLI engine.";
486
+ }
487
+ if (!nodeVersionMeetsClaudeAcpMinimum()) {
488
+ return `Node ${process.version} (${process.execPath}) does not satisfy Claude ACP's Node >=${MIN_ACP_NODE_VERSION} prerequisite.`;
489
+ }
490
+ const command = await resolveClaudeAcpCommandForTarget(input.config, target);
491
+ if (!(await commandIsResolvable(command, input))) {
492
+ return `Claude ACP server command is not available: ${command}.`;
493
+ }
494
+ return null;
495
+ }
496
+ function summarizeStatus(checks) {
497
+ if (checks.some((check) => check.level === "error"))
498
+ return "fail";
499
+ if (checks.some((check) => check.level === "warn"))
500
+ return "warn";
501
+ return "pass";
502
+ }
503
+ function isNonEmpty(value) {
504
+ return typeof value === "string" && value.trim().length > 0;
505
+ }
506
+ /**
507
+ * Build the checks that tell the user the probed target has no ready Claude
508
+ * authentication. Every target gets the descriptive warn check, so
509
+ * `summarizeStatus` never reports a pass without auth. Only a sandbox target
510
+ * gets the neutral canonical `adapter_auth_missing` code, because only a
511
+ * sandbox target can start an in-place login. The user interface reads the
512
+ * canonical code to offer login and gates that affordance to sandbox targets.
513
+ */
514
+ function buildAcpAuthMissingChecks(input) {
515
+ const checks = [
516
+ {
517
+ code: "claude_hello_probe_auth_required",
518
+ level: "warn",
519
+ message: "Claude ACP is available, but login is required.",
520
+ hint: buildClaudeLoginRequiredHint(input.loginUrl),
521
+ },
522
+ ];
523
+ if (input.targetIsSandbox) {
524
+ checks.push({
525
+ code: ADAPTER_AUTH_MISSING_CHECK_CODE,
526
+ level: "warn",
527
+ message: "This environment has no ready authentication for this adapter.",
528
+ hint: "Provide credentials for this adapter, or start login in the environment.",
529
+ });
530
+ }
531
+ return checks;
532
+ }
533
+ /**
534
+ * Build the check that tells the user a Claude login probe could not run on the
535
+ * ACP path. The check is a warn, not an info, so `summarizeStatus` never
536
+ * reports a pass. The check code is distinct from `adapter_auth_missing`, so the
537
+ * user interface never shows the login affordance for a probe that could not
538
+ * confirm the login state. A Test without available auth must not report a
539
+ * success.
540
+ */
541
+ function buildAcpLoginProbeUnavailableCheck(message, targetIsSandbox = false) {
542
+ return {
543
+ code: "claude_acp_login_probe_unavailable",
544
+ level: "warn",
545
+ message,
546
+ hint: targetIsSandbox
547
+ ? "Verify that the environment can run `claude` and retry the Test. Set engine=cli to use the Claude CLI lane."
548
+ : "Verify that `claude` can run in this environment and retry the Test. Set engine=cli to use the Claude CLI lane.",
549
+ };
550
+ }
551
+ /**
552
+ * Probe the stored Claude login for the probed target on the ACP path. The ACP
553
+ * engine and the Claude CLI share the same stored Claude login, so the probe
554
+ * runs the `claude` command with a short hello turn. The probe runs against any
555
+ * target: a local host, an SSH remote, or a sandbox. On a local target the
556
+ * probe builds the child env and the executable from the shared
557
+ * deny-by-default builder, so a hostile caller value can neither select the
558
+ * executable nor reach the child. On a remote target the caller passes the
559
+ * prepared `env`, so the probe reads the managed `CLAUDE_CONFIG_DIR` the same
560
+ * way the CLI lane does.
561
+ *
562
+ * When the probe reports that login is required, the function returns the
563
+ * auth-required checks. Only a sandbox target also gets the canonical
564
+ * `adapter_auth_missing` code, so the user interface offers login for sandbox
565
+ * targets only.
566
+ *
567
+ * The function keeps two signals distinct. It returns the auth-required check
568
+ * only when the probe ran and login is required. It returns a separate warn
569
+ * check when the probe could not run, timed out, or did not complete. It never
570
+ * maps "probe could not run" to a silent pass.
571
+ */
572
+ export async function probeClaudeAcpSandboxLogin(input) {
573
+ const { config, target } = input;
574
+ const targetIsRemote = target?.kind === "remote";
575
+ const targetIsSandbox = target?.kind === "remote" && target.transport === "sandbox";
576
+ // The caller-derived env. On a local target the shared builder filters it to
577
+ // a deny-by-default allowlist. On a remote target the prepared env is used
578
+ // directly, because the remote transport owns its own env sanitization.
579
+ let callerEnv;
580
+ if (input.env) {
581
+ callerEnv = input.env;
582
+ }
583
+ else {
584
+ const envConfig = parseObject(config.env);
585
+ callerEnv = {};
586
+ for (const [key, value] of Object.entries(envConfig)) {
587
+ if (typeof value === "string")
588
+ callerEnv[key] = value;
589
+ }
590
+ }
591
+ let command;
592
+ let env;
593
+ let cwd;
594
+ if (targetIsRemote && target) {
595
+ command = "claude";
596
+ env = callerEnv;
597
+ cwd = target.kind === "remote" ? target.remoteCwd : process.cwd();
598
+ }
599
+ else {
600
+ const built = await buildLocalAdapterTestProbeEnv({
601
+ callerEnv,
602
+ trustedEnv: process.env,
603
+ });
604
+ if (!built.command) {
605
+ return [buildAcpLoginProbeUnavailableCheck("Claude is not installed on the Paperclip host.")];
606
+ }
607
+ command = built.command;
608
+ env = built.env;
609
+ cwd = asString(config.cwd, process.cwd());
610
+ }
611
+ Object.assign(env, claudeSandboxPermissionEnv({
612
+ dangerouslySkipPermissions: asBoolean(config.dangerouslySkipPermissions, true), targetIsSandbox,
613
+ }));
614
+ const args = ["--print", "-", "--output-format", "stream-json", "--verbose"];
615
+ if (config.managedAiConnection)
616
+ args.push("--setting-sources", "user");
617
+ args.push(...buildClaudeProbePermissionArgs({
618
+ dangerouslySkipPermissions: asBoolean(config.dangerouslySkipPermissions, true),
619
+ targetIsRemote,
620
+ localProcessUid: process.getuid?.() ?? null,
621
+ }));
622
+ const timeoutSec = Math.max(1, asNumber(config.helloProbeTimeoutSec, targetIsSandbox ? 90 : 45));
623
+ const runId = `claude-acp-authprobe-${Date.now()}-${Math.random().toString(16).slice(2)}`;
624
+ let probe;
625
+ try {
626
+ probe = await runAdapterExecutionTargetProcess(runId, target, command, args, {
627
+ cwd,
628
+ env,
629
+ timeoutSec,
630
+ graceSec: 5,
631
+ stdin: "Respond with hello.",
632
+ onLog: async () => { },
633
+ });
634
+ }
635
+ catch (err) {
636
+ // Keep the raw error out of the Test-result check and the server log. Log
637
+ // only the fixed context, the allowlisted classification, and a safe error
638
+ // class name.
639
+ logSandboxProbeDiagnostic("Claude ACP login probe could not run", "spawn_error", {
640
+ errorClass: classifyThrownErrorClass(err),
641
+ });
642
+ return [
643
+ buildAcpLoginProbeUnavailableCheck(targetIsSandbox
644
+ ? "The Claude login probe could not run in the sandbox."
645
+ : "The Claude login probe could not run.", targetIsSandbox),
646
+ ];
647
+ }
648
+ if (probe.timedOut) {
649
+ return [buildAcpLoginProbeUnavailableCheck("The Claude login probe timed out.", targetIsSandbox)];
650
+ }
651
+ const parsedStream = parseClaudeStreamJson(probe.stdout);
652
+ const loginMeta = detectClaudeLoginRequired({
653
+ parsed: parsedStream.resultJson,
654
+ stdout: probe.stdout,
655
+ stderr: probe.stderr,
656
+ });
657
+ if (loginMeta.requiresLogin) {
658
+ return buildAcpAuthMissingChecks({ targetIsSandbox, loginUrl: loginMeta.loginUrl });
659
+ }
660
+ if ((probe.exitCode ?? 1) !== 0) {
661
+ // Keep the raw stderr and stdout out of the Test-result check and the
662
+ // server log. Log only the fixed context, the allowlisted classification,
663
+ // and the safe exit code.
664
+ logSandboxProbeDiagnostic("Claude ACP login probe did not complete", "nonzero_exit", {
665
+ exitCode: probe.exitCode ?? null,
666
+ });
667
+ return [buildAcpLoginProbeUnavailableCheck("The Claude login probe did not complete.", targetIsSandbox)];
668
+ }
669
+ if (!/\bhello\b/i.test(parsedStream.summary)) {
670
+ return [buildAcpLoginProbeUnavailableCheck("The Claude login probe did not return hello.", targetIsSandbox)];
671
+ }
672
+ return [{ code: "claude_hello_probe_passed", level: "info", message: "Claude login probe succeeded." }];
673
+ }
674
+ export async function testClaudeAcpEnvironment(ctx) {
675
+ const checks = [];
676
+ const config = parseObject(ctx.config);
677
+ const target = ctx.executionTarget ?? null;
678
+ const targetIsRemote = target?.kind === "remote";
679
+ const targetIsSandbox = target?.kind === "remote" && target.transport === "sandbox";
680
+ checks.push({
681
+ code: "claude_engine_selected",
682
+ level: "info",
683
+ message: "Execution engine selected: ACP.",
684
+ hint: "Set engine=cli to use the existing Claude Code CLI lane.",
685
+ });
686
+ // Always name the target the Test probed, so a pass result never hides which
687
+ // target it checked. A local probe reports the fixed host label.
688
+ checks.push(buildAdapterTestTargetCheck({ targetIsRemote, environmentName: ctx.environmentName }));
689
+ if (targetIsRemote) {
690
+ checks.push({
691
+ code: "claude_acp_remote_target",
692
+ level: "info",
693
+ message: "Claude ACP will run against the remote execution environment.",
694
+ hint: "Remote ACP requires a bidirectional process target such as SSH or Paperclip's sandbox process-session bridge.",
695
+ });
696
+ }
697
+ const cwd = resolveAdapterExecutionTargetCwd(target, asString(config.cwd, ""), process.cwd());
698
+ try {
699
+ await ensureAdapterExecutionTargetDirectory(`claude-acp-envtest-${Date.now()}`, target, cwd, {
700
+ cwd,
701
+ env: {},
702
+ createIfMissing: true,
703
+ });
704
+ checks.push({
705
+ code: "claude_acp_cwd_valid",
706
+ level: "info",
707
+ message: `Working directory is valid: ${cwd}`,
708
+ });
709
+ }
710
+ catch (err) {
711
+ checks.push({
712
+ code: "claude_acp_cwd_invalid",
713
+ level: "error",
714
+ message: err instanceof Error ? err.message : "Invalid working directory",
715
+ detail: cwd,
716
+ });
717
+ }
718
+ checks.push({
719
+ code: nodeVersionMeetsClaudeAcpMinimum() ? "claude_acp_node_supported" : "claude_acp_node_unsupported",
720
+ level: nodeVersionMeetsClaudeAcpMinimum() ? "info" : "error",
721
+ message: nodeVersionMeetsClaudeAcpMinimum()
722
+ ? `Node ${process.version} satisfies Claude ACP runtime requirements.`
723
+ : `Node ${process.version} (${process.execPath}) does not satisfy Claude ACP runtime requirements.`,
724
+ hint: nodeVersionMeetsClaudeAcpMinimum()
725
+ ? undefined
726
+ : `Run Claude ACP with Node >=${MIN_ACP_NODE_VERSION} or switch engine=cli.`,
727
+ });
728
+ const command = await resolveClaudeAcpCommandForTarget(config, target);
729
+ const commandResolvable = await commandIsResolvable(command, {
730
+ config,
731
+ executionTarget: ctx.executionTarget,
732
+ });
733
+ checks.push({
734
+ code: commandResolvable ? "claude_acp_command_resolvable" : "claude_acp_command_missing",
735
+ level: commandResolvable ? "info" : "error",
736
+ message: commandResolvable
737
+ ? `Claude ACP server command is executable: ${command}`
738
+ : `Claude ACP server command is not available: ${command}`,
739
+ hint: commandResolvable
740
+ ? undefined
741
+ : "Install dependencies so @agentclientprotocol/claude-agent-acp is present, or set agentCommand to a valid Claude ACP server command.",
742
+ });
743
+ const envConfig = parseObject(config.env);
744
+ const considerHostEnv = !targetIsRemote && !config.managedAiConnection;
745
+ const hasBedrock = envConfig.CLAUDE_CODE_USE_BEDROCK === "1" ||
746
+ envConfig.CLAUDE_CODE_USE_BEDROCK === "true" ||
747
+ (considerHostEnv && process.env.CLAUDE_CODE_USE_BEDROCK === "1") ||
748
+ (considerHostEnv && process.env.CLAUDE_CODE_USE_BEDROCK === "true") ||
749
+ isNonEmpty(envConfig.ANTHROPIC_BEDROCK_BASE_URL) ||
750
+ (considerHostEnv && isNonEmpty(process.env.ANTHROPIC_BEDROCK_BASE_URL));
751
+ const configApiKey = envConfig.ANTHROPIC_API_KEY;
752
+ const hostApiKey = considerHostEnv ? process.env.ANTHROPIC_API_KEY : undefined;
753
+ const hostOauthToken = considerHostEnv ? process.env.CLAUDE_CODE_OAUTH_TOKEN : undefined;
754
+ const hostAuthToken = considerHostEnv ? process.env.ANTHROPIC_AUTH_TOKEN : undefined;
755
+ const hostConfigDir = considerHostEnv ? process.env.CLAUDE_CONFIG_DIR : undefined;
756
+ if (hasBedrock) {
757
+ checks.push({
758
+ code: "claude_acp_bedrock_auth",
759
+ level: "info",
760
+ message: "AWS Bedrock auth detected. Claude ACP will use Bedrock for inference.",
761
+ hint: "Ensure AWS credentials and AWS_REGION are configured in this environment.",
762
+ });
763
+ }
764
+ else if (isNonEmpty(configApiKey) || isNonEmpty(hostApiKey)) {
765
+ const source = isNonEmpty(configApiKey) ? "adapter config env" : "server environment";
766
+ const selectedApiKey = Boolean(config.managedAiConnection) || isNonEmpty(configApiKey);
767
+ checks.push({
768
+ code: "claude_acp_anthropic_api_key_detected",
769
+ level: selectedApiKey ? "info" : "warn",
770
+ message: selectedApiKey ? "Using the selected Claude API connection." : "ANTHROPIC_API_KEY is set. Claude ACP will use API-key auth instead of subscription credentials.",
771
+ detail: `Detected in ${source}.`,
772
+ hint: selectedApiKey ? undefined : "Unset ANTHROPIC_API_KEY if you want subscription-based Claude login behavior.",
773
+ });
774
+ }
775
+ else if (isNonEmpty(envConfig.CLAUDE_CODE_OAUTH_TOKEN) ||
776
+ (considerHostEnv && isNonEmpty(process.env.CLAUDE_CODE_OAUTH_TOKEN))) {
777
+ const source = isNonEmpty(envConfig.CLAUDE_CODE_OAUTH_TOKEN)
778
+ ? "configured environment variables"
779
+ : "server environment";
780
+ checks.push({
781
+ code: "claude_oauth_token_configured",
782
+ level: "info",
783
+ message: "CLAUDE_CODE_OAUTH_TOKEN is set. Claude ACP will authenticate with the configured subscription token; no stored login is needed on the execution target.",
784
+ detail: `Detected in ${source}.`,
785
+ });
786
+ }
787
+ else if (!targetIsRemote) {
788
+ checks.push({
789
+ code: "claude_acp_subscription_mode_possible",
790
+ level: "info",
791
+ message: "ANTHROPIC_API_KEY is not set; subscription-based auth can be used if Claude is logged in.",
792
+ });
793
+ }
794
+ // Run a real hello probe for every target when Bedrock and a config API key
795
+ // are both absent. A local target inherits the host environment, so the real
796
+ // ACP run authenticates with a host ANTHROPIC_API_KEY. The probe seeds the
797
+ // same host key below when the config sets none, so the probe uses the
798
+ // credential the real run receives and does not report a false auth-required.
799
+ // A remote target does not inherit the host env, so considerHostEnv is false
800
+ // and the probe never reads the host key. The CLI lane already probes every
801
+ // target; the ACP lane now matches it, so a local or SSH target no longer
802
+ // reports a pass without a credential check. Prepare the sandbox the same way
803
+ // the CLI lane does — install the Claude CLI when it is absent and materialize
804
+ // the managed CLAUDE_CONFIG_DIR. The preparation is a no-op for a local or SSH
805
+ // target. The probe returns the canonical adapter_auth_missing signal only for
806
+ // a sandbox target, and a distinct warn check when the probe cannot run. The
807
+ // user interface reads the canonical signal to offer login on the sandbox ACP
808
+ // path.
809
+ if (!hasBedrock && !isNonEmpty(configApiKey)) {
810
+ const probeEnv = {};
811
+ for (const [key, value] of Object.entries(envConfig)) {
812
+ if (typeof value === "string")
813
+ probeEnv[key] = value;
814
+ }
815
+ // Seed the host ANTHROPIC_API_KEY when the config sets no key, so the probe
816
+ // env matches the credential the real local run inherits from the host.
817
+ if (isNonEmpty(hostApiKey) && !isNonEmpty(probeEnv.ANTHROPIC_API_KEY)) {
818
+ probeEnv.ANTHROPIC_API_KEY = hostApiKey.trim();
819
+ }
820
+ // Seed the host CLAUDE_CODE_OAUTH_TOKEN the same way. A local ACP run
821
+ // inherits a host subscription OAuth token, so the probe must receive the
822
+ // same token. Without this seed a valid host OAuth-token setup reports a
823
+ // false claude_hello_probe_auth_required and fails the Test lane.
824
+ if (isNonEmpty(hostOauthToken) && !isNonEmpty(probeEnv.CLAUDE_CODE_OAUTH_TOKEN)) {
825
+ probeEnv.CLAUDE_CODE_OAUTH_TOKEN = hostOauthToken.trim();
826
+ }
827
+ // Seed the host ANTHROPIC_AUTH_TOKEN the same way. A local ACP run inherits
828
+ // a host bearer auth token, so the probe must receive the same token.
829
+ // Without this seed a valid host ANTHROPIC_AUTH_TOKEN setup reports a false
830
+ // claude_hello_probe_auth_required and fails the Test lane.
831
+ if (isNonEmpty(hostAuthToken) && !isNonEmpty(probeEnv.ANTHROPIC_AUTH_TOKEN)) {
832
+ probeEnv.ANTHROPIC_AUTH_TOKEN = hostAuthToken.trim();
833
+ }
834
+ // Seed the host CLAUDE_CONFIG_DIR the same way. A local ACP run reads the
835
+ // stored Claude login from the host CLAUDE_CONFIG_DIR, so the probe must
836
+ // read the same stored login. Without this seed a valid host stored login
837
+ // reports a false claude_hello_probe_auth_required and fails the Test lane.
838
+ if (isNonEmpty(hostConfigDir) && !isNonEmpty(probeEnv.CLAUDE_CONFIG_DIR)) {
839
+ probeEnv.CLAUDE_CONFIG_DIR = hostConfigDir.trim();
840
+ }
841
+ const runId = `claude-acp-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`;
842
+ let cleanupManagedProbe;
843
+ try {
844
+ checks.push(...(await prepareSandboxClaudeProbeRuntime({
845
+ registerCleanup: (cleanup) => { cleanupManagedProbe = cleanup; },
846
+ managedAiConnection: Boolean(config.managedAiConnection),
847
+ runId,
848
+ target,
849
+ cwd,
850
+ companyId: ctx.companyId,
851
+ env: probeEnv,
852
+ installCommand: SANDBOX_INSTALL_COMMAND,
853
+ detectCommand: "claude",
854
+ targetIsRemote,
855
+ targetIsSandbox,
856
+ helloProbeTimeoutSec: asNumber(config.helloProbeTimeoutSec, targetIsSandbox ? 90 : 45),
857
+ })));
858
+ const canProbe = !checks.some((check) => check.code === "claude_managed_config_dir_failed");
859
+ if (canProbe) {
860
+ checks.push(...(await probeClaudeAcpSandboxLogin({ config, target, env: probeEnv })));
861
+ }
862
+ }
863
+ finally {
864
+ await cleanupManagedProbe?.();
865
+ }
866
+ }
867
+ const mode = firstNonEmptyString(config.mode, config.acpMode) ?? DEFAULT_ACP_ENGINE_MODE;
868
+ const warmHandleIdleMs = asNumber(config.warmHandleIdleMs ?? config.acpWarmHandleIdleMs, DEFAULT_ACP_ENGINE_WARM_HANDLE_IDLE_MS);
869
+ checks.push({
870
+ code: "claude_acp_runtime_scaffold",
871
+ level: "info",
872
+ message: "Claude ACP runtime execution is available through the shared ACP engine.",
873
+ detail: `mode=${mode}; warmHandleIdleMs=${warmHandleIdleMs}`,
874
+ });
875
+ return {
876
+ adapterType: ctx.adapterType,
877
+ status: summarizeStatus(checks),
878
+ checks,
879
+ testedAt: new Date().toISOString(),
880
+ };
881
+ }
882
+ //# sourceMappingURL=acp.js.map