@microvac/adapter-codex-local 0.0.0-stage → 0.1.0-rc.15

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 (300) 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 +218 -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 +104 -0
  12. package/dist/cli/quota-probe.js.map +1 -0
  13. package/dist/index.d.ts +41 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +268 -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 +125 -0
  20. package/dist/index.test.js.map +1 -0
  21. package/dist/server/acp.cli-version.test.d.ts +2 -0
  22. package/dist/server/acp.cli-version.test.d.ts.map +1 -0
  23. package/dist/server/acp.cli-version.test.js +151 -0
  24. package/dist/server/acp.cli-version.test.js.map +1 -0
  25. package/dist/server/acp.d.ts +31 -0
  26. package/dist/server/acp.d.ts.map +1 -0
  27. package/dist/server/acp.js +608 -0
  28. package/dist/server/acp.js.map +1 -0
  29. package/dist/server/acp.quota.test.d.ts +2 -0
  30. package/dist/server/acp.quota.test.d.ts.map +1 -0
  31. package/dist/server/acp.quota.test.js +176 -0
  32. package/dist/server/acp.quota.test.js.map +1 -0
  33. package/dist/server/acp.test.d.ts +2 -0
  34. package/dist/server/acp.test.d.ts.map +1 -0
  35. package/dist/server/acp.test.js +1263 -0
  36. package/dist/server/acp.test.js.map +1 -0
  37. package/dist/server/adapter-auth-promotion.d.ts +102 -0
  38. package/dist/server/adapter-auth-promotion.d.ts.map +1 -0
  39. package/dist/server/adapter-auth-promotion.js +210 -0
  40. package/dist/server/adapter-auth-promotion.js.map +1 -0
  41. package/dist/server/adapter-auth-promotion.test.d.ts +2 -0
  42. package/dist/server/adapter-auth-promotion.test.d.ts.map +1 -0
  43. package/dist/server/adapter-auth-promotion.test.js +615 -0
  44. package/dist/server/adapter-auth-promotion.test.js.map +1 -0
  45. package/dist/server/auth-check.d.ts +8 -0
  46. package/dist/server/auth-check.d.ts.map +1 -0
  47. package/dist/server/auth-check.js +8 -0
  48. package/dist/server/auth-check.js.map +1 -0
  49. package/dist/server/auth-precedence.d.ts +16 -0
  50. package/dist/server/auth-precedence.d.ts.map +1 -0
  51. package/dist/server/auth-precedence.js +20 -0
  52. package/dist/server/auth-precedence.js.map +1 -0
  53. package/dist/server/auth-precedence.test.d.ts +2 -0
  54. package/dist/server/auth-precedence.test.d.ts.map +1 -0
  55. package/dist/server/auth-precedence.test.js +100 -0
  56. package/dist/server/auth-precedence.test.js.map +1 -0
  57. package/dist/server/cli-version.d.ts +45 -0
  58. package/dist/server/cli-version.d.ts.map +1 -0
  59. package/dist/server/cli-version.js +95 -0
  60. package/dist/server/cli-version.js.map +1 -0
  61. package/dist/server/codex-args.d.ts +13 -0
  62. package/dist/server/codex-args.d.ts.map +1 -0
  63. package/dist/server/codex-args.js +64 -0
  64. package/dist/server/codex-args.js.map +1 -0
  65. package/dist/server/codex-args.test.d.ts +2 -0
  66. package/dist/server/codex-args.test.d.ts.map +1 -0
  67. package/dist/server/codex-args.test.js +257 -0
  68. package/dist/server/codex-args.test.js.map +1 -0
  69. package/dist/server/codex-auth-cache.d.ts +179 -0
  70. package/dist/server/codex-auth-cache.d.ts.map +1 -0
  71. package/dist/server/codex-auth-cache.js +520 -0
  72. package/dist/server/codex-auth-cache.js.map +1 -0
  73. package/dist/server/codex-auth-cache.test.d.ts +2 -0
  74. package/dist/server/codex-auth-cache.test.d.ts.map +1 -0
  75. package/dist/server/codex-auth-cache.test.js +530 -0
  76. package/dist/server/codex-auth-cache.test.js.map +1 -0
  77. package/dist/server/codex-auth-copyback.d.ts +53 -0
  78. package/dist/server/codex-auth-copyback.d.ts.map +1 -0
  79. package/dist/server/codex-auth-copyback.js +123 -0
  80. package/dist/server/codex-auth-copyback.js.map +1 -0
  81. package/dist/server/codex-auth-copyback.test.d.ts +2 -0
  82. package/dist/server/codex-auth-copyback.test.d.ts.map +1 -0
  83. package/dist/server/codex-auth-copyback.test.js +507 -0
  84. package/dist/server/codex-auth-copyback.test.js.map +1 -0
  85. package/dist/server/codex-auth-merge-decision.cjs +170 -0
  86. package/dist/server/codex-auth-merge-decision.d.ts +22 -0
  87. package/dist/server/codex-auth-merge-decision.d.ts.map +1 -0
  88. package/dist/server/codex-auth-merge-decision.js +58 -0
  89. package/dist/server/codex-auth-merge-decision.js.map +1 -0
  90. package/dist/server/codex-auth-merge-decision.test.d.ts +2 -0
  91. package/dist/server/codex-auth-merge-decision.test.d.ts.map +1 -0
  92. package/dist/server/codex-auth-merge-decision.test.js +215 -0
  93. package/dist/server/codex-auth-merge-decision.test.js.map +1 -0
  94. package/dist/server/codex-auth-merge-extract.sh +73 -0
  95. package/dist/server/codex-auth-merge-scripts.d.ts +21 -0
  96. package/dist/server/codex-auth-merge-scripts.d.ts.map +1 -0
  97. package/dist/server/codex-auth-merge-scripts.js +40 -0
  98. package/dist/server/codex-auth-merge-scripts.js.map +1 -0
  99. package/dist/server/codex-auth-merge.test.d.ts +2 -0
  100. package/dist/server/codex-auth-merge.test.d.ts.map +1 -0
  101. package/dist/server/codex-auth-merge.test.js +714 -0
  102. package/dist/server/codex-auth-merge.test.js.map +1 -0
  103. package/dist/server/codex-auth-seed-write.d.ts +30 -0
  104. package/dist/server/codex-auth-seed-write.d.ts.map +1 -0
  105. package/dist/server/codex-auth-seed-write.js +41 -0
  106. package/dist/server/codex-auth-seed-write.js.map +1 -0
  107. package/dist/server/codex-home.d.ts +169 -0
  108. package/dist/server/codex-home.d.ts.map +1 -0
  109. package/dist/server/codex-home.js +822 -0
  110. package/dist/server/codex-home.js.map +1 -0
  111. package/dist/server/codex-home.test.d.ts +2 -0
  112. package/dist/server/codex-home.test.d.ts.map +1 -0
  113. package/dist/server/codex-home.test.js +1287 -0
  114. package/dist/server/codex-home.test.js.map +1 -0
  115. package/dist/server/config-schema.d.ts +3 -0
  116. package/dist/server/config-schema.d.ts.map +1 -0
  117. package/dist/server/config-schema.js +67 -0
  118. package/dist/server/config-schema.js.map +1 -0
  119. package/dist/server/device-login-export.d.ts +56 -0
  120. package/dist/server/device-login-export.d.ts.map +1 -0
  121. package/dist/server/device-login-export.js +230 -0
  122. package/dist/server/device-login-export.js.map +1 -0
  123. package/dist/server/device-login-export.test.d.ts +2 -0
  124. package/dist/server/device-login-export.test.d.ts.map +1 -0
  125. package/dist/server/device-login-export.test.js +245 -0
  126. package/dist/server/device-login-export.test.js.map +1 -0
  127. package/dist/server/device-login-parse.d.ts +20 -0
  128. package/dist/server/device-login-parse.d.ts.map +1 -0
  129. package/dist/server/device-login-parse.js +155 -0
  130. package/dist/server/device-login-parse.js.map +1 -0
  131. package/dist/server/device-login-parse.test.d.ts +2 -0
  132. package/dist/server/device-login-parse.test.d.ts.map +1 -0
  133. package/dist/server/device-login-parse.test.js +269 -0
  134. package/dist/server/device-login-parse.test.js.map +1 -0
  135. package/dist/server/device-login-runner.d.ts +69 -0
  136. package/dist/server/device-login-runner.d.ts.map +1 -0
  137. package/dist/server/device-login-runner.js +110 -0
  138. package/dist/server/device-login-runner.js.map +1 -0
  139. package/dist/server/device-login-runner.test.d.ts +2 -0
  140. package/dist/server/device-login-runner.test.d.ts.map +1 -0
  141. package/dist/server/device-login-runner.test.js +201 -0
  142. package/dist/server/device-login-runner.test.js.map +1 -0
  143. package/dist/server/engine-availability.test.d.ts +2 -0
  144. package/dist/server/engine-availability.test.d.ts.map +1 -0
  145. package/dist/server/engine-availability.test.js +41 -0
  146. package/dist/server/engine-availability.test.js.map +1 -0
  147. package/dist/server/execute.acp-fallback.test.d.ts +2 -0
  148. package/dist/server/execute.acp-fallback.test.d.ts.map +1 -0
  149. package/dist/server/execute.acp-fallback.test.js +123 -0
  150. package/dist/server/execute.acp-fallback.test.js.map +1 -0
  151. package/dist/server/execute.auth-precedence.test.d.ts +2 -0
  152. package/dist/server/execute.auth-precedence.test.d.ts.map +1 -0
  153. package/dist/server/execute.auth-precedence.test.js +137 -0
  154. package/dist/server/execute.auth-precedence.test.js.map +1 -0
  155. package/dist/server/execute.auth.test.d.ts +2 -0
  156. package/dist/server/execute.auth.test.d.ts.map +1 -0
  157. package/dist/server/execute.auth.test.js +197 -0
  158. package/dist/server/execute.auth.test.js.map +1 -0
  159. package/dist/server/execute.d.ts +40 -0
  160. package/dist/server/execute.d.ts.map +1 -0
  161. package/dist/server/execute.js +1485 -0
  162. package/dist/server/execute.js.map +1 -0
  163. package/dist/server/execute.remote.test.d.ts +2 -0
  164. package/dist/server/execute.remote.test.d.ts.map +1 -0
  165. package/dist/server/execute.remote.test.js +851 -0
  166. package/dist/server/execute.remote.test.js.map +1 -0
  167. package/dist/server/execute.ssh-host-auth.test.d.ts +2 -0
  168. package/dist/server/execute.ssh-host-auth.test.d.ts.map +1 -0
  169. package/dist/server/execute.ssh-host-auth.test.js +214 -0
  170. package/dist/server/execute.ssh-host-auth.test.js.map +1 -0
  171. package/dist/server/execute.stderr-error.test.d.ts +2 -0
  172. package/dist/server/execute.stderr-error.test.d.ts.map +1 -0
  173. package/dist/server/execute.stderr-error.test.js +142 -0
  174. package/dist/server/execute.stderr-error.test.js.map +1 -0
  175. package/dist/server/execute.test.d.ts +2 -0
  176. package/dist/server/execute.test.d.ts.map +1 -0
  177. package/dist/server/execute.test.js +300 -0
  178. package/dist/server/execute.test.js.map +1 -0
  179. package/dist/server/index.d.ts +18 -0
  180. package/dist/server/index.d.ts.map +1 -0
  181. package/dist/server/index.js +84 -0
  182. package/dist/server/index.js.map +1 -0
  183. package/dist/server/output-inactivity-monitor.d.ts +62 -0
  184. package/dist/server/output-inactivity-monitor.d.ts.map +1 -0
  185. package/dist/server/output-inactivity-monitor.integration.test.d.ts +2 -0
  186. package/dist/server/output-inactivity-monitor.integration.test.d.ts.map +1 -0
  187. package/dist/server/output-inactivity-monitor.integration.test.js +136 -0
  188. package/dist/server/output-inactivity-monitor.integration.test.js.map +1 -0
  189. package/dist/server/output-inactivity-monitor.js +112 -0
  190. package/dist/server/output-inactivity-monitor.js.map +1 -0
  191. package/dist/server/output-inactivity-monitor.test.d.ts +2 -0
  192. package/dist/server/output-inactivity-monitor.test.d.ts.map +1 -0
  193. package/dist/server/output-inactivity-monitor.test.js +284 -0
  194. package/dist/server/output-inactivity-monitor.test.js.map +1 -0
  195. package/dist/server/parse.d.ts +69 -0
  196. package/dist/server/parse.d.ts.map +1 -0
  197. package/dist/server/parse.js +278 -0
  198. package/dist/server/parse.js.map +1 -0
  199. package/dist/server/parse.test.d.ts +2 -0
  200. package/dist/server/parse.test.d.ts.map +1 -0
  201. package/dist/server/parse.test.js +203 -0
  202. package/dist/server/parse.test.js.map +1 -0
  203. package/dist/server/process-activity-monitor.d.ts +21 -0
  204. package/dist/server/process-activity-monitor.d.ts.map +1 -0
  205. package/dist/server/process-activity-monitor.js +103 -0
  206. package/dist/server/process-activity-monitor.js.map +1 -0
  207. package/dist/server/process-activity-monitor.test.d.ts +2 -0
  208. package/dist/server/process-activity-monitor.test.d.ts.map +1 -0
  209. package/dist/server/process-activity-monitor.test.js +82 -0
  210. package/dist/server/process-activity-monitor.test.js.map +1 -0
  211. package/dist/server/quota-spawn-error.test.d.ts +2 -0
  212. package/dist/server/quota-spawn-error.test.d.ts.map +1 -0
  213. package/dist/server/quota-spawn-error.test.js +343 -0
  214. package/dist/server/quota-spawn-error.test.js.map +1 -0
  215. package/dist/server/quota.d.ts +66 -0
  216. package/dist/server/quota.d.ts.map +1 -0
  217. package/dist/server/quota.js +577 -0
  218. package/dist/server/quota.js.map +1 -0
  219. package/dist/server/runtime-config.d.ts +11 -0
  220. package/dist/server/runtime-config.d.ts.map +1 -0
  221. package/dist/server/runtime-config.js +389 -0
  222. package/dist/server/runtime-config.js.map +1 -0
  223. package/dist/server/runtime-config.test.d.ts +2 -0
  224. package/dist/server/runtime-config.test.d.ts.map +1 -0
  225. package/dist/server/runtime-config.test.js +389 -0
  226. package/dist/server/runtime-config.test.js.map +1 -0
  227. package/dist/server/skills.d.ts +8 -0
  228. package/dist/server/skills.d.ts.map +1 -0
  229. package/dist/server/skills.js +26 -0
  230. package/dist/server/skills.js.map +1 -0
  231. package/dist/server/ssh-host-runtime.d.ts +24 -0
  232. package/dist/server/ssh-host-runtime.d.ts.map +1 -0
  233. package/dist/server/ssh-host-runtime.js +84 -0
  234. package/dist/server/ssh-host-runtime.js.map +1 -0
  235. package/dist/server/ssh-session-state.d.ts +18 -0
  236. package/dist/server/ssh-session-state.d.ts.map +1 -0
  237. package/dist/server/ssh-session-state.js +11 -0
  238. package/dist/server/ssh-session-state.js.map +1 -0
  239. package/dist/server/test.d.ts +3 -0
  240. package/dist/server/test.d.ts.map +1 -0
  241. package/dist/server/test.js +531 -0
  242. package/dist/server/test.js.map +1 -0
  243. package/dist/server/test.remote.test.d.ts +2 -0
  244. package/dist/server/test.remote.test.d.ts.map +1 -0
  245. package/dist/server/test.remote.test.js +596 -0
  246. package/dist/server/test.remote.test.js.map +1 -0
  247. package/dist/ui/build-config.d.ts +10 -0
  248. package/dist/ui/build-config.d.ts.map +1 -0
  249. package/dist/ui/build-config.js +284 -0
  250. package/dist/ui/build-config.js.map +1 -0
  251. package/dist/ui/build-config.test.d.ts +2 -0
  252. package/dist/ui/build-config.test.d.ts.map +1 -0
  253. package/dist/ui/build-config.test.js +367 -0
  254. package/dist/ui/build-config.test.js.map +1 -0
  255. package/dist/ui/index.d.ts +4 -0
  256. package/dist/ui/index.d.ts.map +1 -0
  257. package/dist/ui/index.js +8 -0
  258. package/dist/ui/index.js.map +1 -0
  259. package/dist/ui/parse-stdout.d.ts +3 -0
  260. package/dist/ui/parse-stdout.d.ts.map +1 -0
  261. package/dist/ui/parse-stdout.js +265 -0
  262. package/dist/ui/parse-stdout.js.map +1 -0
  263. package/dist/ui/parse-stdout.test.d.ts +2 -0
  264. package/dist/ui/parse-stdout.test.d.ts.map +1 -0
  265. package/dist/ui/parse-stdout.test.js +77 -0
  266. package/dist/ui/parse-stdout.test.js.map +1 -0
  267. package/package.json +55 -4
  268. package/skills/agentmail/SKILL.md +70 -0
  269. package/skills/complain/LICENSE +27 -0
  270. package/skills/complain/SKILL.md +68 -0
  271. package/skills/paperclip/SKILL.md +864 -0
  272. package/skills/paperclip/references/api-reference.md +1814 -0
  273. package/skills/paperclip/references/artifacts.md +163 -0
  274. package/skills/paperclip/references/cases.md +570 -0
  275. package/skills/paperclip/references/company-skills.md +266 -0
  276. package/skills/paperclip/references/issue-documents.md +58 -0
  277. package/skills/paperclip/references/issue-workspaces.md +94 -0
  278. package/skills/paperclip/references/routines.md +249 -0
  279. package/skills/paperclip/references/run-diagnostics.md +28 -0
  280. package/skills/paperclip/references/workflows.md +141 -0
  281. package/skills/paperclip/scripts/paperclip-issue-update.sh +166 -0
  282. package/skills/paperclip/scripts/paperclip-upload-artifact.sh +603 -0
  283. package/skills/paperclip/scripts/submit-agent-commentary.mjs +52 -0
  284. package/skills/paperclip-board/SKILL.md +633 -0
  285. package/skills/paperclip-converting-plans-to-tasks/SKILL.md +28 -0
  286. package/skills/paperclip-create-agent/SKILL.md +213 -0
  287. package/skills/paperclip-create-agent/references/agent-instruction-templates.md +24 -0
  288. package/skills/paperclip-create-agent/references/agents/coder.md +18 -0
  289. package/skills/paperclip-create-agent/references/agents/qa.md +18 -0
  290. package/skills/paperclip-create-agent/references/agents/securityengineer.md +26 -0
  291. package/skills/paperclip-create-agent/references/agents/uxdesigner.md +18 -0
  292. package/skills/paperclip-create-agent/references/api-reference.md +110 -0
  293. package/skills/paperclip-create-agent/references/baseline-role-guide.md +22 -0
  294. package/skills/paperclip-create-agent/references/draft-review-checklist.md +29 -0
  295. package/skills/para-memory-files/SKILL.md +100 -0
  296. package/skills/para-memory-files/references/schemas.md +35 -0
  297. package/skills/slack/SKILL.md +92 -0
  298. package/skills/suggestion-box/LICENSE +27 -0
  299. package/skills/suggestion-box/SKILL.md +77 -0
  300. package/README.md +0 -3
@@ -0,0 +1,822 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { shellQuote } from "@paperclipai/adapter-utils/ssh";
5
+ import { buildCodexAuthInboundProvision, CODEX_AUTH_MERGE_EXTRACT_SCRIPT_NAME } from "./codex-auth-merge-scripts.js";
6
+ import { resolvePaperclipInstanceRootForAdapter } from "@paperclipai/adapter-utils/server-utils";
7
+ import { isCodexAuthCachePath, readSubscriptionAccountId } from "./codex-auth-cache.js";
8
+ const TRUTHY_ENV_RE = /^(1|true|yes|on)$/i;
9
+ const COPIED_SHARED_FILES = ["config.json", "config.toml", "instructions.md"];
10
+ const SYMLINKED_SHARED_FILES = ["auth.json"];
11
+ const MANAGED_MCP_BLOCK_START = "# BEGIN PAPERCLIP MANAGED MCP";
12
+ const MANAGED_MCP_BLOCK_END = "# END PAPERCLIP MANAGED MCP";
13
+ /**
14
+ * The allowlist of managed `CODEX_HOME` entries that the codex-local adapter
15
+ * stages into the sandbox `home` asset (see {@link stageCodexHomeForSync}).
16
+ * Derived from the seeding constants so it can never drift from what the adapter
17
+ * actually writes into the home: the copied static config files, the symlinked
18
+ * credential file, and the injected `skills/` directory. Everything else the
19
+ * stock upstream `codex` binary writes at runtime (`*.sqlite`, `*-wal`,
20
+ * `plugins/`, `cache/`, `sessions/`, `shell_snapshots/`, …) is intentionally
21
+ * excluded — it is large host-local runtime state the sandbox run never needs.
22
+ */
23
+ export const CODEX_SYNC_ALLOWLIST = [
24
+ ...COPIED_SHARED_FILES,
25
+ ...SYMLINKED_SHARED_FILES,
26
+ "skills",
27
+ ];
28
+ /** Refresh only managed entries; remote conversation files never leave their home.
29
+ * The staging lease and provider retirement precede this provisioning command. */
30
+ export function buildCodexHomeRefreshProvision(options) {
31
+ const auth = options.mergeAuth ? buildCodexAuthInboundProvision() : undefined;
32
+ return {
33
+ stageFiles: auth?.stageFiles,
34
+ postUploadCommand: ({ assetDir, assetTarPath, runtimeRootDir }) => {
35
+ const prepare = options.mergeAuth
36
+ ? `if [ -f "$home/auth.json" ]; then cp "$home/auth.json" "$incoming/auth.json"; fi
37
+ sh "$runtime_root/${CODEX_AUTH_MERGE_EXTRACT_SCRIPT_NAME}" "$incoming" "$asset_tar"`
38
+ : 'tar -xf "$asset_tar" -C "$incoming"\nrm -f "$asset_tar"';
39
+ // Paths arrive confined by the runtime staging layer. Only fixed managed
40
+ // names are replaced; sessions, archived sessions and native indexes stay.
41
+ const script = `set -eu
42
+ umask 077
43
+ home=$1
44
+ asset_tar=$2
45
+ runtime_root=$3
46
+ mkdir -p "$home"
47
+ chmod 700 "$home"
48
+ incoming=$(mktemp -d "$home/.paperclip-home-refresh.XXXXXX")
49
+ trap 'rm -rf -- "$incoming"' EXIT
50
+ trap 'exit 1' HUP INT TERM
51
+ ${prepare}
52
+ for name in ${CODEX_SYNC_ALLOWLIST.map(shellQuote).join(" ")}; do
53
+ if [ -e "$incoming/$name" ] || [ -L "$incoming/$name" ]; then
54
+ if [ -d "$home/$name" ] || [ -L "$home/$name" ]; then rm -rf -- "$home/$name"; fi
55
+ mv -f -- "$incoming/$name" "$home/$name"
56
+ else
57
+ rm -rf -- "$home/$name"
58
+ fi
59
+ done`;
60
+ return `sh -c ${shellQuote(script)} -- ${shellQuote(assetDir)} ${shellQuote(assetTarPath)} ${shellQuote(runtimeRootDir)}`;
61
+ },
62
+ };
63
+ }
64
+ export function mergeManagedCodexMcpGateways(primary, secondary) {
65
+ const merged = [...primary];
66
+ const names = new Set(primary.map((gateway) => gateway.name));
67
+ for (const gateway of secondary) {
68
+ if (names.has(gateway.name))
69
+ continue;
70
+ merged.push(gateway);
71
+ names.add(gateway.name);
72
+ }
73
+ return merged;
74
+ }
75
+ function nonEmpty(value) {
76
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
77
+ }
78
+ export async function pathExists(candidate) {
79
+ return fs.access(candidate).then(() => true).catch(() => false);
80
+ }
81
+ // Co-change notice: this function's logic is mirrored by parseAuth in
82
+ // packages/adapter-utils/src/sandbox-managed-runtime.ts (buildCodexAuthMergeDecisionScript).
83
+ // If the auth format changes (new shape, renamed field), update both sites together.
84
+ function hasUsableAuthPayload(authPayload) {
85
+ if (authPayload === null || typeof authPayload !== "object" || Array.isArray(authPayload)) {
86
+ return false;
87
+ }
88
+ const parsedPayload = authPayload;
89
+ const apiKey = parsedPayload.OPENAI_API_KEY;
90
+ if (typeof apiKey === "string" && apiKey.trim().length > 0) {
91
+ return true;
92
+ }
93
+ const tokens = parsedPayload.tokens;
94
+ if (tokens !== null && typeof tokens === "object" && !Array.isArray(tokens)) {
95
+ const parsedTokens = tokens;
96
+ const accountId = parsedTokens.account_id;
97
+ const hasAccountId = typeof accountId === "string" && accountId.trim().length > 0;
98
+ const hasTokenMaterial = ["id_token", "access_token", "refresh_token"].some((key) => {
99
+ const value = parsedTokens[key];
100
+ return typeof value === "string" && value.trim().length > 0;
101
+ });
102
+ if (hasAccountId && hasTokenMaterial)
103
+ return true;
104
+ }
105
+ return false;
106
+ }
107
+ function readApiKeyFromAuthPayload(authPayload) {
108
+ if (authPayload === null || typeof authPayload !== "object" || Array.isArray(authPayload)) {
109
+ return null;
110
+ }
111
+ const raw = authPayload.OPENAI_API_KEY;
112
+ return typeof raw === "string" && raw.trim().length > 0 ? raw.trim() : null;
113
+ }
114
+ /**
115
+ * The `last_refresh` timestamp of an auth.json payload, in epoch milliseconds,
116
+ * or null when the bytes are unreadable or carry no parseable timestamp. This is
117
+ * the same freshness field the shared merge decision predicate
118
+ * (`codex-auth-merge-decision.cjs`) compares, read the same way, so the seeding
119
+ * heal below and the credential writers agree on what "fresher" means.
120
+ */
121
+ function readAuthLastRefreshMs(bytes) {
122
+ if (!bytes)
123
+ return null;
124
+ let parsed;
125
+ try {
126
+ parsed = JSON.parse(bytes.toString("utf8"));
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
132
+ return null;
133
+ }
134
+ const raw = parsed.last_refresh;
135
+ const ms = typeof raw === "string" ? Date.parse(raw) : NaN;
136
+ return Number.isFinite(ms) ? ms : null;
137
+ }
138
+ export function resolveSharedCodexHomeDir(env = process.env) {
139
+ const fromEnv = nonEmpty(env.CODEX_HOME);
140
+ return fromEnv ? path.resolve(fromEnv) : path.join(os.homedir(), ".codex");
141
+ }
142
+ function isWorktreeMode(env) {
143
+ return TRUTHY_ENV_RE.test(env.PAPERCLIP_IN_WORKTREE ?? "");
144
+ }
145
+ export function resolveManagedCodexHomeDir(env, companyId) {
146
+ const instanceRoot = resolvePaperclipInstanceRootForAdapter({
147
+ homeDir: nonEmpty(env.PAPERCLIP_HOME) ?? undefined,
148
+ instanceId: nonEmpty(env.PAPERCLIP_INSTANCE_ID) ?? undefined,
149
+ env,
150
+ });
151
+ return companyId
152
+ ? path.resolve(instanceRoot, "companies", companyId, "codex-home")
153
+ : path.resolve(instanceRoot, "codex-home");
154
+ }
155
+ /**
156
+ * True when `homePath` lives under the Paperclip-managed company tree
157
+ * (`<instanceRoot>/companies/<companyId>/...`). This covers both the shared
158
+ * company `codex-home` and the per-agent `agents/<agentId>/codex-home` set by
159
+ * the server-side isolation guard. A path outside that tree is a genuine
160
+ * external/user-supplied override that Paperclip must not seed or overwrite.
161
+ */
162
+ export function isManagedCodexHomePath(env, companyId, homePath) {
163
+ if (!companyId)
164
+ return false;
165
+ const instanceRoot = resolvePaperclipInstanceRootForAdapter({
166
+ homeDir: nonEmpty(env.PAPERCLIP_HOME) ?? undefined,
167
+ instanceId: nonEmpty(env.PAPERCLIP_INSTANCE_ID) ?? undefined,
168
+ env,
169
+ });
170
+ const companyRoot = path.resolve(instanceRoot, "companies", companyId);
171
+ const resolved = path.resolve(homePath);
172
+ return resolved === companyRoot || resolved.startsWith(companyRoot + path.sep);
173
+ }
174
+ /**
175
+ * True when the Codex home has a usable `auth.json`. Uses `fs.access` (follows
176
+ * symlinks), so a dangling auth symlink whose source has been removed counts as
177
+ * no usable credentials.
178
+ */
179
+ export async function codexHomeHasUsableAuth(home) {
180
+ const authPath = path.join(home, "auth.json");
181
+ if (!(await pathExists(authPath)))
182
+ return false;
183
+ try {
184
+ const raw = await fs.readFile(authPath, "utf8");
185
+ const parsed = JSON.parse(raw);
186
+ return hasUsableAuthPayload(parsed);
187
+ }
188
+ catch {
189
+ return false;
190
+ }
191
+ }
192
+ async function codexHomeHasMatchingApiKeyAuth(home, apiKey) {
193
+ const authPath = path.join(home, "auth.json");
194
+ const existing = await fs.lstat(authPath).catch(() => null);
195
+ if (!existing || existing.isSymbolicLink())
196
+ return false;
197
+ try {
198
+ const raw = await fs.readFile(authPath, "utf8");
199
+ const parsed = JSON.parse(raw);
200
+ return readApiKeyFromAuthPayload(parsed) === apiKey.trim();
201
+ }
202
+ catch {
203
+ return false;
204
+ }
205
+ }
206
+ async function ensureParentDir(target) {
207
+ await fs.mkdir(path.dirname(target), { recursive: true });
208
+ }
209
+ async function isExpectedSymlink(target, source) {
210
+ const existing = await fs.lstat(target).catch(() => null);
211
+ if (!existing?.isSymbolicLink())
212
+ return false;
213
+ const linkedPath = await fs.readlink(target).catch(() => null);
214
+ if (!linkedPath)
215
+ return false;
216
+ return path.resolve(path.dirname(target), linkedPath) === path.resolve(source);
217
+ }
218
+ async function createExpectedSymlink(target, source) {
219
+ try {
220
+ await fs.symlink(source, target);
221
+ }
222
+ catch (error) {
223
+ const code = error.code;
224
+ if (code === "EEXIST" && await isExpectedSymlink(target, source))
225
+ return;
226
+ throw error;
227
+ }
228
+ }
229
+ export async function ensureSymlink(target, source) {
230
+ const existing = await fs.lstat(target).catch(() => null);
231
+ if (!existing) {
232
+ await ensureParentDir(target);
233
+ await createExpectedSymlink(target, source);
234
+ return;
235
+ }
236
+ if (!existing.isSymbolicLink()) {
237
+ // A previous Paperclip version copied this file into the managed home
238
+ // instead of symlinking it. Codex refresh tokens rotate and are
239
+ // single-use, so a stale copy fails with refresh_token_reused on the next
240
+ // run (#5028). Replace the regular file with a symlink so the CLI follows
241
+ // the live source. Safe to delete: target is always under the
242
+ // Paperclip-managed company home, never the user's real ~/.codex.
243
+ // Directories are left alone — `fs.unlink` would throw EISDIR on Unix
244
+ // (and behave inconsistently on Windows). A directory at this path is not
245
+ // a Paperclip-written stale copy and warrants operator inspection rather
246
+ // than silent removal.
247
+ if (existing.isDirectory())
248
+ return;
249
+ await fs.unlink(target);
250
+ await createExpectedSymlink(target, source);
251
+ return;
252
+ }
253
+ if (await isExpectedSymlink(target, source))
254
+ return;
255
+ await fs.unlink(target);
256
+ await createExpectedSymlink(target, source);
257
+ }
258
+ async function ensureCopiedFile(target, source) {
259
+ const existing = await fs.lstat(target).catch(() => null);
260
+ if (existing)
261
+ return;
262
+ await ensureParentDir(target);
263
+ await fs.copyFile(source, target);
264
+ }
265
+ function tomlString(value) {
266
+ return JSON.stringify(value);
267
+ }
268
+ function sanitizeMcpServerName(value, fallback) {
269
+ return value
270
+ .trim()
271
+ .toLowerCase()
272
+ .replace(/[^a-z0-9_-]+/g, "-")
273
+ .replace(/^-+|-+$/g, "")
274
+ .slice(0, 80) || fallback;
275
+ }
276
+ function stripManagedMcpBlock(config) {
277
+ const start = config.indexOf(MANAGED_MCP_BLOCK_START);
278
+ if (start < 0)
279
+ return config.trimEnd();
280
+ const end = config.indexOf(MANAGED_MCP_BLOCK_END, start);
281
+ if (end < 0)
282
+ return config.slice(0, start).trimEnd();
283
+ return `${config.slice(0, start)}${config.slice(end + MANAGED_MCP_BLOCK_END.length)}`.trimEnd();
284
+ }
285
+ function readCodexMcpServerNames(config) {
286
+ const names = new Set();
287
+ for (const match of config.matchAll(/^\s*\[\s*mcp_servers\s*\.\s*(?:"([^"]+)"|'([^']+)'|([^\]\s#]+))\s*\]/gm)) {
288
+ const name = match[1] ?? match[2] ?? match[3];
289
+ if (name)
290
+ names.add(name.trim());
291
+ }
292
+ return names;
293
+ }
294
+ function buildManagedMcpBlock(input) {
295
+ const warnings = [];
296
+ const usedNames = new Set();
297
+ const lines = [
298
+ MANAGED_MCP_BLOCK_START,
299
+ "# Written by Paperclip for governed MCP gateway access. Do not edit this block by hand.",
300
+ ];
301
+ input.gateways.forEach((gateway, index) => {
302
+ const baseName = sanitizeMcpServerName(gateway.name, `gateway-${index + 1}`);
303
+ const directOverlap = input.existingNames.has(gateway.name) || input.existingNames.has(baseName);
304
+ let managedName = directOverlap ? `paperclip-${baseName}` : baseName;
305
+ let suffix = 2;
306
+ while (usedNames.has(managedName) || input.existingNames.has(managedName)) {
307
+ managedName = `paperclip-${baseName}-${suffix}`;
308
+ suffix += 1;
309
+ }
310
+ usedNames.add(managedName);
311
+ if (directOverlap) {
312
+ warnings.push(`Found unmanaged Codex MCP server "${gateway.name}" overlapping a Paperclip-governed gateway; leaving the direct entry in place and adding managed gateway "${managedName}". Paperclip cannot enforce policies for that direct entry.`);
313
+ }
314
+ const url = new URL(gateway.endpointPath, input.apiBaseUrl).toString();
315
+ lines.push("", `[mcp_servers.${tomlString(managedName)}]`, `url = ${tomlString(url)}`, `http_headers = { Authorization = ${tomlString(`Bearer ${gateway.bearerToken}`)} }`);
316
+ });
317
+ lines.push(MANAGED_MCP_BLOCK_END);
318
+ return { block: lines.join("\n"), warnings };
319
+ }
320
+ export async function writeManagedCodexMcpConfig(input) {
321
+ const configPath = path.join(input.codexHome, "config.toml");
322
+ await fs.mkdir(input.codexHome, { recursive: true });
323
+ const existing = await fs.readFile(configPath, "utf8").catch((error) => {
324
+ if (error.code === "ENOENT")
325
+ return "";
326
+ throw error;
327
+ });
328
+ const unmanagedConfig = stripManagedMcpBlock(existing);
329
+ const { block, warnings } = buildManagedMcpBlock({
330
+ gateways: input.gateways,
331
+ apiBaseUrl: input.apiBaseUrl,
332
+ existingNames: readCodexMcpServerNames(unmanagedConfig),
333
+ });
334
+ const next = input.gateways.length > 0
335
+ ? `${unmanagedConfig}${unmanagedConfig ? "\n\n" : ""}${block}\n`
336
+ : `${unmanagedConfig}${unmanagedConfig ? "\n" : ""}`;
337
+ await fs.writeFile(configPath, next, { mode: 0o600 });
338
+ await fs.chmod(configPath, 0o600);
339
+ return { configPath, warnings };
340
+ }
341
+ /**
342
+ * Writes an `auth.json` containing only `OPENAI_API_KEY` so the codex CLI can
343
+ * authenticate via API key. Overwrites any existing file or symlink at that
344
+ * path. Required because the codex CLI (>= 0.122) ignores the `OPENAI_API_KEY`
345
+ * environment variable and only reads credentials from `$CODEX_HOME/auth.json`.
346
+ */
347
+ export async function writeApiKeyAuthJson(home, apiKey) {
348
+ await fs.mkdir(home, { recursive: true });
349
+ const target = path.join(home, "auth.json");
350
+ await fs.rm(target, { force: true });
351
+ await fs.writeFile(target, JSON.stringify({ OPENAI_API_KEY: apiKey }), { mode: 0o600 });
352
+ }
353
+ /**
354
+ * True when `candidate` is `root` itself or a descendant of it. Both arguments
355
+ * must be absolute, already-resolved (symlink-free) paths — callers pass
356
+ * `fs.realpath` output — so `path.relative` is a reliable containment test that
357
+ * is not fooled by `..` segments or a trailing-separator prefix collision
358
+ * (`/a/skills` vs `/a/skills-evil`).
359
+ */
360
+ function isResolvedPathInside(candidate, root) {
361
+ if (candidate === root)
362
+ return true;
363
+ const rel = path.relative(root, candidate);
364
+ return rel.length > 0 && !rel.startsWith("..") && !path.isAbsolute(rel);
365
+ }
366
+ /**
367
+ * Recursively copies one skill subtree — rooted at its real directory
368
+ * `containmentRoot` — into `targetDir`, dereferencing symlinks to bytes (so the
369
+ * sandbox receives real file content, not host-relative links) and normalizing
370
+ * regular files to owner-only access (`0700` for executables, `0600` otherwise).
371
+ * Created directories get mode `0700`.
372
+ *
373
+ * Two containment guards protect the staged upload:
374
+ *
375
+ * - **Allowlist escape (finding 2).** After dereferencing, a symlink whose real
376
+ * target falls *outside* `containmentRoot` is skipped. A malformed or
377
+ * compromised skill could otherwise smuggle host files that are not in
378
+ * `CODEX_SYNC_ALLOWLIST` (e.g. `~/.ssh/id_rsa`) into the upload by pointing a
379
+ * nested link at them. The skill's own top-level link into the shared skill
380
+ * store is still honoured — it is what establishes `containmentRoot` in
381
+ * {@link stageDirectorySecure}; only links that escape *that* root are cut.
382
+ * - **Directory cycles (finding 1).** A directory symlink such as `back -> .` or
383
+ * `back -> ..` resolves to an ancestor directory instead of raising `ELOOP`;
384
+ * recursing into it would traverse the same tree forever until disk/memory is
385
+ * exhausted. A resolved directory already on the active traversal path
386
+ * (`activePath`) is therefore skipped.
387
+ *
388
+ * Dangling symlinks (`ENOENT`) and self-referential links that do trip `ELOOP`
389
+ * are silently skipped, as are non-file/dir entries (sockets, devices).
390
+ */
391
+ async function stageContainedSubtree(sourceDir, targetDir, containmentRoot, activePath) {
392
+ await fs.mkdir(targetDir, { recursive: true, mode: 0o700 });
393
+ const entries = await fs.readdir(sourceDir, { withFileTypes: true });
394
+ for (const entry of entries) {
395
+ const entrySource = path.join(sourceDir, entry.name);
396
+ const entryTarget = path.join(targetDir, entry.name);
397
+ // Resolve the real path; dangling or self-referential (`ELOOP`) links skip.
398
+ const resolved = await fs.realpath(entrySource).catch((error) => {
399
+ const code = error.code;
400
+ if (code === "ENOENT" || code === "ELOOP")
401
+ return null;
402
+ throw error;
403
+ });
404
+ if (!resolved)
405
+ continue;
406
+ // Allowlist containment: never dereference a link that escapes this skill's
407
+ // real root (host files outside CODEX_SYNC_ALLOWLIST) into the upload.
408
+ if (!isResolvedPathInside(resolved, containmentRoot))
409
+ continue;
410
+ const entryStat = await fs.stat(resolved).catch((error) => {
411
+ if (error.code === "ENOENT")
412
+ return null;
413
+ throw error;
414
+ });
415
+ if (!entryStat)
416
+ continue;
417
+ if (entryStat.isDirectory()) {
418
+ // Cycle guard: a directory already open on the active path (reached via a
419
+ // `back -> .`-style link) would otherwise recurse forever.
420
+ if (activePath.has(resolved))
421
+ continue;
422
+ activePath.add(resolved);
423
+ await stageContainedSubtree(resolved, entryTarget, containmentRoot, activePath);
424
+ activePath.delete(resolved);
425
+ }
426
+ else if (entryStat.isFile()) {
427
+ const bytes = await fs.readFile(resolved);
428
+ const mode = entryStat.mode & 0o111 ? 0o700 : 0o600;
429
+ await fs.writeFile(entryTarget, bytes, { mode });
430
+ await fs.chmod(entryTarget, mode);
431
+ }
432
+ // Other types (sockets, devices) are silently skipped.
433
+ }
434
+ }
435
+ /**
436
+ * Recursively copies `sourceDir` (a directory allowlist entry — currently only
437
+ * `skills/`) into `targetDir`, dereferencing symlinks to bytes and normalizing
438
+ * regular files to owner-only access (`0700` for executables, `0600` otherwise).
439
+ * Created directories get mode `0700`.
440
+ *
441
+ * This replaces `fs.cp({ dereference: true })` which preserves source file modes,
442
+ * leaving `0644` documents and `0755` scripts group/other-readable in the staged
443
+ * asset; here skill files retain only their executable flag, with owner-only access.
444
+ *
445
+ * `sourceDir`'s *direct* children are the Paperclip-injected skill symlinks that
446
+ * intentionally point into a shared skill store *outside* `CODEX_HOME/skills/`,
447
+ * so each child is allowed to resolve anywhere — and when it resolves to a
448
+ * directory it becomes the containment root for its own subtree. Everything
449
+ * *below* that root is copied via {@link stageContainedSubtree}, which refuses to
450
+ * follow a nested symlink out of the skill (finding 2) and detects directory
451
+ * cycles (finding 1). A direct child that resolves to `sourceDir` itself or to
452
+ * an ancestor of it (a degenerate `-> .` / `-> ..` link at the top level) is
453
+ * skipped rather than used as a root, so it can never drag the wider home into
454
+ * the staged skills asset. The `0700` staged directory and per-file owner-only mode
455
+ * together ensure even externally-sourced skill content is not group/world-readable.
456
+ */
457
+ async function stageDirectorySecure(sourceDir, targetDir) {
458
+ await fs.mkdir(targetDir, { recursive: true, mode: 0o700 });
459
+ const realSourceDir = await fs.realpath(sourceDir);
460
+ const entries = await fs.readdir(sourceDir, { withFileTypes: true });
461
+ for (const entry of entries) {
462
+ const entrySource = path.join(sourceDir, entry.name);
463
+ const entryTarget = path.join(targetDir, entry.name);
464
+ // Resolve the real path; dangling or self-referential (`ELOOP`) links skip.
465
+ const resolved = await fs.realpath(entrySource).catch((error) => {
466
+ const code = error.code;
467
+ if (code === "ENOENT" || code === "ELOOP")
468
+ return null;
469
+ throw error;
470
+ });
471
+ if (!resolved)
472
+ continue;
473
+ // A top-level child that resolves to the skills dir itself or an ancestor
474
+ // of it (`back -> .` / `back -> ..`) is degenerate: using it as a root would
475
+ // re-stage the whole home under `skills/`. Skip it.
476
+ if (isResolvedPathInside(realSourceDir, resolved))
477
+ continue;
478
+ const entryStat = await fs.stat(resolved).catch((error) => {
479
+ if (error.code === "ENOENT")
480
+ return null;
481
+ throw error;
482
+ });
483
+ if (!entryStat)
484
+ continue;
485
+ if (entryStat.isDirectory()) {
486
+ // This child skill establishes its own containment root: nested links may
487
+ // not escape it, and the root seeds the cycle-detection active path.
488
+ await stageContainedSubtree(resolved, entryTarget, resolved, new Set([resolved]));
489
+ }
490
+ else if (entryStat.isFile()) {
491
+ const bytes = await fs.readFile(resolved);
492
+ const mode = entryStat.mode & 0o111 ? 0o700 : 0o600;
493
+ await fs.writeFile(entryTarget, bytes, { mode });
494
+ await fs.chmod(entryTarget, mode);
495
+ }
496
+ // Other types (sockets, devices) are silently skipped.
497
+ }
498
+ }
499
+ /**
500
+ * Copies a single allowlist entry from the managed home into the staged dir,
501
+ * dereferencing symlinks to bytes. Missing entries are skipped (keyring mode has
502
+ * no `auth.json`; some homes have no `config.json`). Every staged regular file is
503
+ * written `0600` (least privilege). Any non-`ENOENT` error propagates to the caller.
504
+ */
505
+ async function stageCodexHomeEntry(sourceHome, stagedHome, entry) {
506
+ const source = path.join(sourceHome, entry);
507
+ // `fs.stat` follows symlinks, so a dangling link (e.g. a removed auth source)
508
+ // reports ENOENT and is skipped exactly like a genuinely absent file.
509
+ const stat = await fs.stat(source).catch((error) => {
510
+ if (error.code === "ENOENT")
511
+ return null;
512
+ throw error;
513
+ });
514
+ if (!stat)
515
+ return;
516
+ const target = path.join(stagedHome, entry);
517
+ if (stat.isDirectory()) {
518
+ // Recursively copy with mode normalization — nested regular files land
519
+ // `0600` and dangling/circular symlinks are skipped.
520
+ await stageDirectorySecure(source, target);
521
+ return;
522
+ }
523
+ // `fs.readFile` follows the symlink into the shared source and returns the
524
+ // resolved bytes (the live single-use auth token), which we write as a plain
525
+ // regular file so copy-back and in-sandbox auth read real bytes.
526
+ const bytes = await fs.readFile(source);
527
+ // Stage every regular file `0600`, not just `auth.json`. The staged dir is a
528
+ // 0700 mkdtemp and each file is read back only by the owner (Codex in-sandbox +
529
+ // copy-back), so nothing needs group/other read. This is least privilege and,
530
+ // critically, keeps secret-bearing entries protected: `config.toml` embeds the
531
+ // managed MCP `Authorization = "Bearer …"` header (and the source writer
532
+ // persists it 0600), so a per-file credential allowlist would silently
533
+ // downgrade it to 0644 in a world-readable tmpdir.
534
+ await fs.writeFile(target, bytes, { mode: 0o600 });
535
+ // Explicit chmod so the mode is 0600 regardless of the process umask.
536
+ await fs.chmod(target, 0o600);
537
+ }
538
+ /**
539
+ * Stages exactly {@link CODEX_SYNC_ALLOWLIST} from `effectiveCodexHome` into a
540
+ * fresh private temp dir and returns its path, for registration as the sandbox
541
+ * `home` asset. This replaces syncing the whole managed home + a name denylist:
542
+ * only the files Codex actually needs are uploaded, so oversized runtime state
543
+ * (`sessions/`, `*.sqlite`, `plugins/`, …) never reaches the sandbox.
544
+ *
545
+ * - **Symlinks are dereferenced to bytes** — the single-use `auth.json`
546
+ * credential (a symlink into the shared source home) and each `skills/` entry
547
+ * land as real files, never dangling links.
548
+ * - **Missing-but-optional entries are skipped** — no `auth.json` in
549
+ * keyring-credential mode, or no `config.json`, is not an error.
550
+ * - **`mkdtemp` guarantees the staged dir is `0700`** on POSIX, and every staged
551
+ * regular file is written `0600` (least privilege), so staged credentials —
552
+ * `auth.json` (OAuth token) and `config.toml` (managed MCP bearer header) —
553
+ * are never group/other-readable.
554
+ * - **Fail-closed** — any *unexpected* I/O error removes the partial temp dir
555
+ * and re-throws, so a run never proceeds with a partial or empty home.
556
+ *
557
+ * The caller owns removing the returned dir on run teardown.
558
+ */
559
+ export async function stageCodexHomeForSync(effectiveCodexHome, options = {}) {
560
+ const runIdPart = nonEmpty(options.runId ?? undefined);
561
+ const stagedHome = await fs.mkdtemp(path.join(os.tmpdir(), `paperclip-codex-home-sync-${runIdPart ? `${runIdPart}-` : ""}`));
562
+ try {
563
+ for (const filename of options.additionalFiles ?? []) {
564
+ if (!/^paperclip-observability-[A-Za-z0-9_-]+\.config\.toml$/.test(filename))
565
+ throw new Error("Invalid managed observability profile");
566
+ const source = path.join(effectiveCodexHome, filename);
567
+ const stat = await fs.lstat(source);
568
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || (typeof process.getuid === "function" && stat.uid !== process.getuid()) || (stat.mode & 0o077) !== 0)
569
+ throw new Error("Managed observability profile must be an owned private regular file");
570
+ await fs.writeFile(path.join(stagedHome, filename), await fs.readFile(source), { mode: 0o600, flag: "wx" });
571
+ }
572
+ for (const entry of CODEX_SYNC_ALLOWLIST) {
573
+ await stageCodexHomeEntry(effectiveCodexHome, stagedHome, entry);
574
+ }
575
+ return stagedHome;
576
+ }
577
+ catch (error) {
578
+ // Fail-closed: never hand back a partial home. Remove the temp dir we
579
+ // created before propagating the failure.
580
+ await fs.rm(stagedHome, { recursive: true, force: true }).catch(() => { });
581
+ throw error;
582
+ }
583
+ }
584
+ /**
585
+ * Seeds auth/config into an explicit Paperclip-managed `targetHome`. Symlinks
586
+ * `auth.json` from the shared source home (so ChatGPT-subscription credentials
587
+ * stay live and single-use refresh tokens are not copied), copies the static
588
+ * shared config files, and — when an API key is supplied — writes an API-key
589
+ * `auth.json` instead. A promoted device-login credential — a regular-file
590
+ * `auth.json` holding a subscription identity the shared source does not hold,
591
+ * or the same identity with a `last_refresh` the shared source has not strictly
592
+ * moved past — is kept authoritative: it is neither removed nor replaced by the
593
+ * shared symlink. Used both for the default company home and for the per-agent
594
+ * home set by the server isolation guard.
595
+ */
596
+ export async function seedManagedCodexHome(targetHome, env, onLog, options = {}) {
597
+ const apiKey = nonEmpty(options.apiKey ?? undefined);
598
+ const sourceHome = resolveSharedCodexHomeDir(env);
599
+ const seedFromShared = path.resolve(sourceHome) !== path.resolve(targetHome);
600
+ // A per-identity credential-store entry is not a seedable home: its
601
+ // auth.json is the durable, identity-anchored result of a device login,
602
+ // maintained by the promotion, the vend, and the copy-back under their own
603
+ // locks. An agent can bind `CODEX_HOME` to an entry through the login's
604
+ // account-home secret, and this pass runs before every probe and execute —
605
+ // symlinking the entry to the shared source would silently swap the bound
606
+ // account for the host login, and an API-key rewrite would destroy the
607
+ // stored credential outright. The static shared config files still copy
608
+ // in below, so a bound run gets the same config a per-agent home gets.
609
+ const credentialStoreEntry = isCodexAuthCachePath(env, targetHome);
610
+ await fs.mkdir(targetHome, { recursive: true });
611
+ // A regular-file auth.json in the target home is one of two very different
612
+ // things. The device-login promotion writes the company credential as a
613
+ // regular file, and that file is the durable outcome of an interactive login,
614
+ // so it must survive re-seeding. Everything else — an apikey-mode file left by
615
+ // a previous run, a stale pre-symlink copy of the shared credential (#5028),
616
+ // or an unreadable payload — is residue, and removing it lets the chatgpt-mode
617
+ // symlink be restored (ensureSymlink would otherwise replace it and Codex
618
+ // would keep authenticating with the stale key).
619
+ //
620
+ // The discriminator is identity- and freshness-anchored, like the promotion
621
+ // and the cache vend: keep the file when it holds a usable subscription
622
+ // identity that the shared source does not also hold, and also when it holds
623
+ // the SAME identity but the shared source is not strictly fresher by
624
+ // `last_refresh`. A device login for the account the host is also signed in
625
+ // to promotes a file strictly newer than the host copy; swapping that file
626
+ // for the symlink would sign the company back in with the very credential the
627
+ // login just replaced — the failing one that made the user sign in. The
628
+ // #5028 stale copy is the strictly-older direction of the same comparison,
629
+ // and it still heals: the live host credential refreshes on use, so as soon
630
+ // as the shared source is strictly fresher the swap applies. Ties and
631
+ // unparseable freshness keep the file — the same fail-closed direction the
632
+ // shared merge decision predicate uses — because deleting a promoted
633
+ // credential is irreversible while keeping it self-corrects on the next seed
634
+ // once the source has provably moved past it. A different-identity (or
635
+ // source-less) subscription file is the promoted company credential; on a
636
+ // server with no shared login there is nothing to symlink at all, and
637
+ // deleting it would silently sign the company out right after a successful
638
+ // device login.
639
+ let keepPromotedAuth = false;
640
+ if (!apiKey && seedFromShared && !credentialStoreEntry) {
641
+ const authPath = path.join(targetHome, "auth.json");
642
+ const existing = await fs.lstat(authPath).catch(() => null);
643
+ if (existing && !existing.isSymbolicLink()) {
644
+ const targetBytes = await fs.readFile(authPath).catch(() => null);
645
+ const targetIdentity = targetBytes ? readSubscriptionAccountId(targetBytes) : null;
646
+ if (targetIdentity) {
647
+ // Any source read failure — absent or unreadable — keeps the usable
648
+ // target file. The alternative, removal plus the existence-only
649
+ // symlink pass below, links the home to a source this process just
650
+ // failed to read, and every downstream reader (the probe seeding, the
651
+ // sandbox stage sync, the CLI itself) runs with the same access, so
652
+ // that home is unusable in every scenario. Keeping the target is
653
+ // better or equal in each case: a promoted credential keeps working,
654
+ // and even a stale same-identity copy (#5028) can still work, while
655
+ // the unreadable symlink cannot. A transient read failure also
656
+ // self-corrects — the next seed with a readable source heals a
657
+ // same-identity copy into the symlink — whereas removing the promoted
658
+ // credential is irreversible. The #5028 heal therefore applies
659
+ // exactly when the source is readable and the identities match.
660
+ let sourceReadErrorCode = null;
661
+ const sourceBytes = await fs
662
+ .readFile(path.join(sourceHome, "auth.json"))
663
+ .catch((error) => {
664
+ if (error.code !== "ENOENT" && error.code !== "ENOTDIR") {
665
+ sourceReadErrorCode = error.code ?? "unknown";
666
+ }
667
+ return null;
668
+ });
669
+ const sourceIdentity = sourceBytes ? readSubscriptionAccountId(sourceBytes) : null;
670
+ if (sourceIdentity !== targetIdentity) {
671
+ keepPromotedAuth = true;
672
+ }
673
+ else {
674
+ // Same identity: swap to the symlink only when the shared source is
675
+ // strictly fresher. A tie or an unparseable timestamp keeps the file
676
+ // (see the freshness rationale above).
677
+ const sourceLastRefresh = readAuthLastRefreshMs(sourceBytes);
678
+ const targetLastRefresh = readAuthLastRefreshMs(targetBytes);
679
+ keepPromotedAuth = !(sourceLastRefresh !== null &&
680
+ targetLastRefresh !== null &&
681
+ sourceLastRefresh > targetLastRefresh);
682
+ }
683
+ if (keepPromotedAuth && sourceReadErrorCode) {
684
+ // Deferred heal, made visible: seeding runs before every probe and
685
+ // every execute, so the next call with a readable source applies
686
+ // the same-identity symlink heal this call could not decide.
687
+ await onLog("stdout", `[paperclip] Keeping the existing subscription auth.json in Codex home "${targetHome}" (shared source read failed: ${sourceReadErrorCode}); the next seed with a readable source reconciles it.\n`);
688
+ }
689
+ }
690
+ if (keepPromotedAuth) {
691
+ await onLog("stdout", `[paperclip] Keeping the promoted subscription auth.json in Codex home "${targetHome}".\n`);
692
+ }
693
+ else {
694
+ await fs.rm(authPath, { force: true });
695
+ }
696
+ }
697
+ }
698
+ if (seedFromShared) {
699
+ for (const name of SYMLINKED_SHARED_FILES) {
700
+ // The kept promoted credential is authoritative for this home; the shared
701
+ // symlink would silently swap the account back to the host login. A
702
+ // credential-store entry's auth.json is authoritative unconditionally.
703
+ if (name === "auth.json" && (keepPromotedAuth || credentialStoreEntry))
704
+ continue;
705
+ const source = path.join(sourceHome, name);
706
+ if (!(await pathExists(source)))
707
+ continue;
708
+ await ensureSymlink(path.join(targetHome, name), source);
709
+ }
710
+ for (const name of COPIED_SHARED_FILES) {
711
+ const source = path.join(sourceHome, name);
712
+ if (!(await pathExists(source)))
713
+ continue;
714
+ await ensureCopiedFile(path.join(targetHome, name), source);
715
+ }
716
+ await onLog("stdout", `[paperclip] Using ${isWorktreeMode(env) ? "worktree-isolated" : "Paperclip-managed"} Codex home "${targetHome}" (seeded from "${sourceHome}").\n`);
717
+ }
718
+ if (apiKey) {
719
+ if (credentialStoreEntry) {
720
+ // Refuse, loudly: overwriting a store entry's subscription credential
721
+ // with an API-key file would destroy the durable login the entry
722
+ // exists to hold. The operator combined an account binding with a
723
+ // configured OPENAI_API_KEY; the binding wins for this home.
724
+ await onLog("stdout", `[paperclip] Refusing to write an API-key auth.json into credential-store entry "${targetHome}"; the bound account's stored login stays authoritative.\n`);
725
+ }
726
+ else {
727
+ await writeApiKeyAuthJson(targetHome, apiKey);
728
+ await onLog("stdout", `[paperclip] Wrote API-key auth.json into Codex home "${targetHome}" from configured OPENAI_API_KEY.\n`);
729
+ }
730
+ }
731
+ }
732
+ export async function prepareManagedCodexHome(env, onLog, companyId, options = {}) {
733
+ const targetHome = resolveManagedCodexHomeDir(env, companyId);
734
+ await seedManagedCodexHome(targetHome, env, onLog, options);
735
+ return targetHome;
736
+ }
737
+ const noopOnLog = async () => { };
738
+ /**
739
+ * Idempotently reconciles a persisted `codex_local` agent home. Phase 1 seeds
740
+ * managed homes at execute time; this is the backfill for agents that already
741
+ * carry a persisted (but unseeded) per-agent `CODEX_HOME` and have not run
742
+ * since the seeding fix landed. Shares the managed-home detection
743
+ * (`isManagedCodexHomePath`) and seeding (`seedManagedCodexHome`) logic so a
744
+ * genuine external/user override is never touched. Safe to re-run: when a valid
745
+ * `auth.json` is already present (and no API-key rewrite is requested) it is a
746
+ * no-op and reports `already_seeded`.
747
+ */
748
+ export async function reconcileManagedCodexHome(input) {
749
+ const env = input.env ?? process.env;
750
+ const configured = nonEmpty(input.configuredCodexHome ?? undefined);
751
+ if (!configured)
752
+ return { status: "no_managed_home", home: null };
753
+ const resolved = path.resolve(configured);
754
+ if (!isManagedCodexHomePath(env, input.companyId, resolved)) {
755
+ return { status: "external_override", home: resolved };
756
+ }
757
+ const apiKey = nonEmpty(input.apiKey ?? undefined);
758
+ const hadUsableAuth = await codexHomeHasUsableAuth(resolved);
759
+ // A secret-bound OPENAI_API_KEY cannot be resolved here, so we cannot rewrite
760
+ // it into auth.json. If the home already has usable auth — typically an
761
+ // API-key auth.json written at execute time when the secret WAS resolved —
762
+ // preserve it. Re-seeding without the key would delete that file and restore
763
+ // the shared subscription symlink, silently changing the agent's credentials
764
+ // on every boot while the persisted config still says "use the secret key".
765
+ if (input.apiKeySecretBound && hadUsableAuth) {
766
+ return { status: "already_seeded", home: resolved };
767
+ }
768
+ if (apiKey && await codexHomeHasMatchingApiKeyAuth(resolved, apiKey)) {
769
+ return { status: "already_seeded", home: resolved };
770
+ }
771
+ await seedManagedCodexHome(resolved, env, input.onLog ?? noopOnLog, { apiKey });
772
+ if (!apiKey && !(await codexHomeHasUsableAuth(resolved))) {
773
+ return { status: "source_auth_missing", home: resolved };
774
+ }
775
+ // Without an API key, seeding only changes disk state when auth was missing.
776
+ // With an API key, the matching-file short-circuit above filters out the
777
+ // already-seeded case before this write path.
778
+ const status = !apiKey && hadUsableAuth ? "already_seeded" : "seeded";
779
+ return { status, home: resolved };
780
+ }
781
+ /**
782
+ * Read-only predictor for whether a `codex_local` run will be able to
783
+ * authenticate, without seeding or mutating any home. Mirrors the execute-time
784
+ * fail-fast in `execute.ts`, factored out so the control plane can run the same
785
+ * check *before* dispatch and surface a configuration-incomplete blocker instead
786
+ * of dispatching a run that is guaranteed to fail with "no Codex credentials".
787
+ *
788
+ * - An external/user-supplied `CODEX_HOME` override manages its own auth, so it
789
+ * is always treated as ready (Paperclip must not seed or inspect it).
790
+ * - A non-empty resolved `OPENAI_API_KEY` means API-key auth, always ready.
791
+ * - Otherwise (subscription mode) the run needs a usable `auth.json`. Because a
792
+ * managed home symlinks `auth.json` from the shared source home at seed time,
793
+ * we treat the run as ready when either the (possibly already-seeded) effective
794
+ * home or the shared source home carries usable auth.
795
+ */
796
+ export async function evaluateCodexCredentialReadiness(input) {
797
+ const env = input.env ?? process.env;
798
+ const configuredRaw = nonEmpty(input.configuredCodexHome ?? undefined);
799
+ const configuredCodexHome = configuredRaw ? path.resolve(configuredRaw) : null;
800
+ const configuredApiKey = nonEmpty(input.configuredApiKey ?? undefined);
801
+ const sharedSourceHome = resolveSharedCodexHomeDir(env);
802
+ const configuredHomeIsManaged = configuredCodexHome != null && isManagedCodexHomePath(env, input.companyId, configuredCodexHome);
803
+ const effectiveHomeIsManaged = configuredCodexHome == null || configuredHomeIsManaged;
804
+ const effectiveHome = configuredCodexHome ?? resolveManagedCodexHomeDir(env, input.companyId);
805
+ if (!effectiveHomeIsManaged) {
806
+ // Genuine external override: Paperclip never seeds or inspects it.
807
+ return {
808
+ managed: false,
809
+ authMode: configuredApiKey ? "api" : "subscription",
810
+ ready: true,
811
+ effectiveHome,
812
+ sharedSourceHome,
813
+ };
814
+ }
815
+ if (configuredApiKey) {
816
+ return { managed: true, authMode: "api", ready: true, effectiveHome, sharedSourceHome };
817
+ }
818
+ const ready = (await codexHomeHasUsableAuth(effectiveHome)) ||
819
+ (await codexHomeHasUsableAuth(sharedSourceHome));
820
+ return { managed: true, authMode: "subscription", ready, effectiveHome, sharedSourceHome };
821
+ }
822
+ //# sourceMappingURL=codex-home.js.map