@citeark/agent 0.3.20

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 (347) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +128 -0
  3. package/data/dataset-source-registry.v1.json +300 -0
  4. package/dist/arkgraph/boot.js +6 -0
  5. package/dist/arkgraph/index.html +1 -0
  6. package/dist/arkgraph/viewer.css +1 -0
  7. package/dist/arkgraph/viewer.en.css +1 -0
  8. package/dist/arkgraph/viewer.en.js +49 -0
  9. package/dist/arkgraph/viewer.en.js.LEGAL.txt +56 -0
  10. package/dist/arkgraph/viewer.js +49 -0
  11. package/dist/arkgraph/viewer.js.LEGAL.txt +56 -0
  12. package/docker/claude-code/Dockerfile +97 -0
  13. package/docker/claude-code/codex-pro-relay.mjs +466 -0
  14. package/docker/claude-code/runtime-contract-check.mjs +79 -0
  15. package/docs/arkgraph-reading.md +79 -0
  16. package/docs/configuration.md +100 -0
  17. package/docs/integration.md +92 -0
  18. package/docs/maturity-plan.md +27 -0
  19. package/docs/npm-release.md +44 -0
  20. package/docs/paper-reading.md +40 -0
  21. package/docs/research-plan-granularity.md +27 -0
  22. package/docs/terminal.md +49 -0
  23. package/examples/toy-evaluation/compile-task.json +27 -0
  24. package/examples/toy-evaluation/paper.md +5 -0
  25. package/examples/toy-evaluation/repository/README.md +9 -0
  26. package/examples/toy-evaluation/repository/checkpoint.json +4 -0
  27. package/examples/toy-evaluation/repository/evaluate.py +17 -0
  28. package/examples/toy-evaluation/task.json +81 -0
  29. package/package.json +59 -0
  30. package/prompts/compile-research.md +58 -0
  31. package/prompts/execute-contract.md +72 -0
  32. package/prompts/execute-workspace-simple.md +51 -0
  33. package/prompts/execute-workspace.md +34 -0
  34. package/prompts/prepare-reproduction.md +82 -0
  35. package/prompts/repair-research.md +45 -0
  36. package/protocol/CAP.md +129 -0
  37. package/protocol/LICENSE +12 -0
  38. package/protocol/MAPPINGS.md +72 -0
  39. package/protocol/README.md +38 -0
  40. package/protocol/conformance-v2.0-alpha.1.json +36 -0
  41. package/protocol/examples/arkgraph/checkpoint-evaluation.json +309 -0
  42. package/protocol/examples/arkgraph/fixtures.mjs +49 -0
  43. package/protocol/examples/arkgraph/paper-free.json +291 -0
  44. package/protocol/examples/arkgraph/partial-failure.json +344 -0
  45. package/protocol/examples/arkgraph/training-evaluation.json +443 -0
  46. package/protocol/profiles/agent-trace.md +16 -0
  47. package/protocol/profiles/computational-run.md +16 -0
  48. package/protocol/profiles/core.md +15 -0
  49. package/protocol/profiles/public-bundle.md +18 -0
  50. package/protocol/profiles/reproduction.md +29 -0
  51. package/protocol/profiles/research-compilation.md +44 -0
  52. package/protocol/profiles/research-plan.md +39 -0
  53. package/protocol/profiles/restricted-evidence.md +15 -0
  54. package/runtime/bootstrap-autodl-runtime.sh +314 -0
  55. package/runtime/create-runtime-venv.sh +41 -0
  56. package/runtime/install-local-cpu-runtime.sh +23 -0
  57. package/runtime/install-scientific-runtime.sh +153 -0
  58. package/runtime/mineru/parse.py +62 -0
  59. package/runtime/mineru/requirements.txt +4 -0
  60. package/runtime/requirements-baseline.txt +38 -0
  61. package/schemas/cap/v2/activity.schema.json +47 -0
  62. package/schemas/cap/v2/agent.schema.json +32 -0
  63. package/schemas/cap/v2/assertion.schema.json +110 -0
  64. package/schemas/cap/v2/descriptor.schema.json +243 -0
  65. package/schemas/cap/v2/entity.schema.json +64 -0
  66. package/schemas/cap/v2/manifest.schema.json +67 -0
  67. package/schemas/cap/v2/relation.schema.json +82 -0
  68. package/schemas/compute-catalog.schema.json +63 -0
  69. package/schemas/compute-decision.schema.json +27 -0
  70. package/schemas/execution-contract.schema.json +1024 -0
  71. package/schemas/research-card.schema.json +30 -0
  72. package/schemas/research-inventory-draft.schema.json +366 -0
  73. package/schemas/research.schema.json +1044 -0
  74. package/schemas/result.schema.json +173 -0
  75. package/schemas/verification-policy.schema.json +47 -0
  76. package/schemas/verified-conclusion.schema.json +58 -0
  77. package/schemas/workspace-summary.schema.json +24 -0
  78. package/scripts/build-arkgraph-view.mjs +12 -0
  79. package/scripts/check-execution-feasibility.mjs +24 -0
  80. package/scripts/check-syntax.mjs +15 -0
  81. package/scripts/deterministic-asset-preparation.py +438 -0
  82. package/scripts/package-cap.mjs +23 -0
  83. package/scripts/package-local-agent.mjs +23 -0
  84. package/scripts/preview-arkgraph.mjs +25 -0
  85. package/scripts/replay-research-compiler-candidate.mjs +134 -0
  86. package/scripts/review-compiler-sources.mjs +44 -0
  87. package/scripts/run-asset-preparation.sh +17 -0
  88. package/scripts/run-research-plan.mjs +98 -0
  89. package/scripts/validate-asset-preparation.py +290 -0
  90. package/scripts/verify-local-runtime.mjs +57 -0
  91. package/scripts/verify-npm-package.mjs +57 -0
  92. package/src/adapters/paper2agent.mjs +107 -0
  93. package/src/assets/cache.mjs +159 -0
  94. package/src/assets/compute.mjs +98 -0
  95. package/src/assets/executor.mjs +145 -0
  96. package/src/assets/lifecycle.mjs +213 -0
  97. package/src/assets/manifest.mjs +242 -0
  98. package/src/assets/opportunistic-preparation.mjs +81 -0
  99. package/src/assets/plan.mjs +411 -0
  100. package/src/assets/prompts.mjs +29 -0
  101. package/src/assets/public-asset-probe.mjs +525 -0
  102. package/src/assets/qualification.mjs +119 -0
  103. package/src/assets/readiness.mjs +130 -0
  104. package/src/assets/reproduction-admission.mjs +355 -0
  105. package/src/assets/requirements.mjs +152 -0
  106. package/src/assets/source-grounding.mjs +341 -0
  107. package/src/assets/source-policy.mjs +118 -0
  108. package/src/autodl/client.mjs +260 -0
  109. package/src/autodl/ssh.mjs +380 -0
  110. package/src/autodl/tools.mjs +129 -0
  111. package/src/cap/redaction.mjs +38 -0
  112. package/src/cap/v2/archive.mjs +152 -0
  113. package/src/cap/v2/attestation.mjs +204 -0
  114. package/src/cap/v2/canonical-json.mjs +114 -0
  115. package/src/cap/v2/compilation-artifact.mjs +240 -0
  116. package/src/cap/v2/core.mjs +282 -0
  117. package/src/cap/v2/measurement-assessment-records.mjs +23 -0
  118. package/src/cap/v2/pipeline-artifact.mjs +922 -0
  119. package/src/cap/v2/read.mjs +41 -0
  120. package/src/cap/v2/reassessment-artifact.mjs +383 -0
  121. package/src/cap/v2/research-artifact.mjs +231 -0
  122. package/src/cap/v2/research-map-records.mjs +46 -0
  123. package/src/cap/v2/research-object-records.mjs +163 -0
  124. package/src/cap/v2/research-records.mjs +187 -0
  125. package/src/cap/v2/verify.mjs +642 -0
  126. package/src/cli.mjs +1146 -0
  127. package/src/compute/autodl-pro-compiler.mjs +347 -0
  128. package/src/compute/autodl-pro-executor.mjs +459 -0
  129. package/src/compute/autodl-pro-job.mjs +843 -0
  130. package/src/compute/autodl-pro-network.mjs +295 -0
  131. package/src/compute/autodl-pro-remote.mjs +810 -0
  132. package/src/compute/autodl-pro-staging.mjs +117 -0
  133. package/src/compute/campaign.mjs +110 -0
  134. package/src/compute/catalog.mjs +123 -0
  135. package/src/compute/checkpoint-protocol.mjs +154 -0
  136. package/src/compute/codex-account-lock.mjs +111 -0
  137. package/src/compute/codex-account-session.mjs +107 -0
  138. package/src/compute/compiler-profile.mjs +38 -0
  139. package/src/compute/compiler-router.mjs +23 -0
  140. package/src/compute/coordinator-recovery.mjs +210 -0
  141. package/src/compute/executor-router.mjs +29 -0
  142. package/src/compute/gcp-batch-compiler.mjs +685 -0
  143. package/src/compute/gcp-batch-executor.mjs +1215 -0
  144. package/src/compute/gcp-batch-failure.mjs +92 -0
  145. package/src/compute/gcp-batch-job.mjs +527 -0
  146. package/src/compute/gcp-batch-lifecycle.mjs +81 -0
  147. package/src/compute/gcp-checkpoint-worker.mjs +1633 -0
  148. package/src/compute/local-codex-compiler.mjs +52 -0
  149. package/src/compute/measurement-hardware.mjs +128 -0
  150. package/src/compute/remote-attempt.mjs +226 -0
  151. package/src/compute/requirements.mjs +124 -0
  152. package/src/compute/research-phases.mjs +48 -0
  153. package/src/compute/scheduler.mjs +452 -0
  154. package/src/compute/shared-workloads.mjs +26 -0
  155. package/src/compute/stage-archive.mjs +79 -0
  156. package/src/contracts/campaign-contract.mjs +52 -0
  157. package/src/contracts/execution-contract.mjs +819 -0
  158. package/src/contracts/execution-mode.mjs +19 -0
  159. package/src/contracts/execution-timeouts.mjs +45 -0
  160. package/src/contracts/execution-workload.mjs +68 -0
  161. package/src/contracts/preflight-schema.mjs +25 -0
  162. package/src/contracts/public-contract.mjs +63 -0
  163. package/src/contracts/subject-tags.mjs +31 -0
  164. package/src/dashboard/data.mjs +898 -0
  165. package/src/dashboard/server.mjs +79 -0
  166. package/src/dashboard/static/dashboard.css +366 -0
  167. package/src/dashboard/static/dashboard.js +560 -0
  168. package/src/dashboard/static/index.html +85 -0
  169. package/src/deployment/community-policy.mjs +9 -0
  170. package/src/deployment/environment.mjs +112 -0
  171. package/src/deployment/guided.mjs +98 -0
  172. package/src/deployment/handoff.mjs +102 -0
  173. package/src/deployment/local-contract.mjs +31 -0
  174. package/src/deployment/local.mjs +100 -0
  175. package/src/deployment/prepare.mjs +46 -0
  176. package/src/deployment/recipe.mjs +108 -0
  177. package/src/deployment/supplement.mjs +51 -0
  178. package/src/deployment/terminal.mjs +43 -0
  179. package/src/diagnosis/renderer.mjs +75 -0
  180. package/src/diagnosis/target-failure.mjs +46 -0
  181. package/src/evidence/parser-registry.mjs +54 -0
  182. package/src/evidence/parsers/fasttext-classification.mjs +82 -0
  183. package/src/evidence/parsers/json-scalar.mjs +96 -0
  184. package/src/evidence/parsers/simcse-senteval.mjs +104 -0
  185. package/src/evidence/parsers/starspace-classification.mjs +78 -0
  186. package/src/evidence/registry.mjs +147 -0
  187. package/src/execution/runner-audit.mjs +473 -0
  188. package/src/gcp/auth.mjs +106 -0
  189. package/src/gcp/batch-client.mjs +120 -0
  190. package/src/gcp/resource-discovery.mjs +177 -0
  191. package/src/gcp/rest.mjs +82 -0
  192. package/src/gcp/secret-manager.mjs +34 -0
  193. package/src/gcp/signed-url.mjs +133 -0
  194. package/src/gcp/storage.mjs +220 -0
  195. package/src/graph/command.mjs +41 -0
  196. package/src/graph/execution.mjs +97 -0
  197. package/src/graph/model.mjs +37 -0
  198. package/src/graph/presentation.mjs +110 -0
  199. package/src/graph/query.mjs +159 -0
  200. package/src/graph/research-relations.mjs +69 -0
  201. package/src/graph/source-page.mjs +12 -0
  202. package/src/graph/source-preview.mjs +34 -0
  203. package/src/graph/validate.mjs +76 -0
  204. package/src/job.mjs +496 -0
  205. package/src/network/autodl-routing-proxy.mjs +462 -0
  206. package/src/network/egress-proxy.mjs +158 -0
  207. package/src/observability/event-contract.mjs +230 -0
  208. package/src/observability/pipeline-monitor.mjs +166 -0
  209. package/src/pipeline/orchestrator.mjs +1281 -0
  210. package/src/pipeline/recovery-error.mjs +11 -0
  211. package/src/pipeline/replay.mjs +304 -0
  212. package/src/pipeline/shared-execution.mjs +115 -0
  213. package/src/pipeline/stage-checkpoint.mjs +86 -0
  214. package/src/pipeline/stage-recovery.mjs +101 -0
  215. package/src/pipeline/targets.mjs +110 -0
  216. package/src/process.mjs +143 -0
  217. package/src/protocol.mjs +312 -0
  218. package/src/provider/codex-account.mjs +44 -0
  219. package/src/provider/codex-completion.mjs +49 -0
  220. package/src/provider/completion.mjs +292 -0
  221. package/src/provider/model-client.mjs +44 -0
  222. package/src/provider/model-route.mjs +29 -0
  223. package/src/provider/openrouter-readiness.mjs +189 -0
  224. package/src/provider/reader-bridge.mjs +35 -0
  225. package/src/provider/relay.mjs +263 -0
  226. package/src/provider/runtime-auth.mjs +40 -0
  227. package/src/public/cap.d.mts +90 -0
  228. package/src/public/cap.mjs +12 -0
  229. package/src/public/contracts.d.mts +2 -0
  230. package/src/public/host.mjs +171 -0
  231. package/src/public/operations.d.mts +11 -0
  232. package/src/public/presentation.d.mts +4 -0
  233. package/src/records/views.mjs +26 -0
  234. package/src/remote/command.mjs +178 -0
  235. package/src/remote/ssh.mjs +59 -0
  236. package/src/repository-origin.mjs +81 -0
  237. package/src/reproduction/evidence-feedback.mjs +96 -0
  238. package/src/reproduction/incomplete-initialization.mjs +25 -0
  239. package/src/reproduction/lifecycle.mjs +253 -0
  240. package/src/reproduction/plan.mjs +132 -0
  241. package/src/reproduction/prompts.mjs +70 -0
  242. package/src/reproduction/runner.mjs +188 -0
  243. package/src/reproduction/summary.mjs +130 -0
  244. package/src/reproduction/workspace-mode.mjs +7 -0
  245. package/src/research/automatic-admission.mjs +156 -0
  246. package/src/research/compiler-coverage.mjs +85 -0
  247. package/src/research/compiler-failure.mjs +24 -0
  248. package/src/research/compiler-normalization-guards.mjs +112 -0
  249. package/src/research/compiler-repair.mjs +3 -0
  250. package/src/research/compiler.mjs +853 -0
  251. package/src/research/continuation-selection.mjs +26 -0
  252. package/src/research/execution-graph-context.mjs +43 -0
  253. package/src/research/experiment-importance.mjs +15 -0
  254. package/src/research/inventory-handoff.mjs +104 -0
  255. package/src/research/inventory-revisions.mjs +32 -0
  256. package/src/research/mineru-local.mjs +73 -0
  257. package/src/research/paper-command.mjs +19 -0
  258. package/src/research/paper-markdown.mjs +180 -0
  259. package/src/research/paper-source-map.mjs +69 -0
  260. package/src/research/planning-policy.mjs +88 -0
  261. package/src/research/reference-materials.mjs +11 -0
  262. package/src/research/reproduction-scope.mjs +30 -0
  263. package/src/research/research-map.mjs +94 -0
  264. package/src/research/research-objects.mjs +88 -0
  265. package/src/research/source-discovery.mjs +646 -0
  266. package/src/research/source-observations.mjs +75 -0
  267. package/src/research/source-review-cli-mcp.mjs +26 -0
  268. package/src/research/source-review-input.mjs +209 -0
  269. package/src/research/source-review-local-codex.mjs +36 -0
  270. package/src/research/source-review-model.mjs +70 -0
  271. package/src/research/source-review.mjs +173 -0
  272. package/src/research/structure.mjs +3163 -0
  273. package/src/research-card/renderer.mjs +277 -0
  274. package/src/research-card/verified-conclusion.mjs +143 -0
  275. package/src/results/output-registry.mjs +183 -0
  276. package/src/runtime/claude-code.mjs +52 -0
  277. package/src/runtime/codex-capacity-retry.mjs +87 -0
  278. package/src/runtime/codex.mjs +64 -0
  279. package/src/runtime/config.mjs +157 -0
  280. package/src/runtime/final-output.mjs +40 -0
  281. package/src/runtime/index.mjs +21 -0
  282. package/src/runtime/local-codex.mjs +74 -0
  283. package/src/runtime/opencode.mjs +95 -0
  284. package/src/runtime/prompt.mjs +13 -0
  285. package/src/sandbox/docker.mjs +363 -0
  286. package/src/settings/command.mjs +297 -0
  287. package/src/settings/store.mjs +119 -0
  288. package/src/telemetry/pricing.mjs +68 -0
  289. package/src/telemetry/usage.mjs +265 -0
  290. package/src/terminal/events.mjs +97 -0
  291. package/src/terminal/input.mjs +40 -0
  292. package/src/terminal/plain.mjs +40 -0
  293. package/src/terminal/remote-stream.mjs +22 -0
  294. package/src/terminal/screen.mjs +214 -0
  295. package/src/terminal/transcript.mjs +69 -0
  296. package/src/util.mjs +107 -0
  297. package/src/verification/ai-assessor.mjs +534 -0
  298. package/src/verification/claim-evaluator.mjs +242 -0
  299. package/src/verification/evidence-context.mjs +165 -0
  300. package/src/verification/evidence-reader.mjs +95 -0
  301. package/src/verification/integrity.mjs +570 -0
  302. package/src/verification/tolerance.mjs +32 -0
  303. package/src/workloads/cpu-research-preparation.mjs +56 -0
  304. package/src/workloads/definition.mjs +74 -0
  305. package/src/workloads/phase-aware-reproduction.mjs +46 -0
  306. package/src/workloads/reproduction.mjs +85 -0
  307. package/src/workspace/command.mjs +242 -0
  308. package/src/workspace/control.mjs +49 -0
  309. package/src/workspace/entry.mjs +28 -0
  310. package/src/workspace/input.mjs +93 -0
  311. package/src/workspace/interactive.mjs +94 -0
  312. package/src/workspace/jobs.mjs +418 -0
  313. package/src/workspace/session.mjs +97 -0
  314. package/src/workspace/worker.mjs +137 -0
  315. package/ui/arkgraph/ambient-motion.mjs +10 -0
  316. package/ui/arkgraph/app.jsx +153 -0
  317. package/ui/arkgraph/boot.js +6 -0
  318. package/ui/arkgraph/camera-motion.mjs +20 -0
  319. package/ui/arkgraph/context-reveal.mjs +39 -0
  320. package/ui/arkgraph/details.css +3 -0
  321. package/ui/arkgraph/entry.jsx +28 -0
  322. package/ui/arkgraph/experiment-curves.mjs +17 -0
  323. package/ui/arkgraph/experiment-selection.mjs +15 -0
  324. package/ui/arkgraph/experiment-style.css +26 -0
  325. package/ui/arkgraph/experiment-ui.jsx +32 -0
  326. package/ui/arkgraph/frame.html +1 -0
  327. package/ui/arkgraph/graph-gestures.mjs +62 -0
  328. package/ui/arkgraph/label-layout.mjs +57 -0
  329. package/ui/arkgraph/locales/en.json +229 -0
  330. package/ui/arkgraph/locales/source-types.json +15 -0
  331. package/ui/arkgraph/localization-build.mjs +27 -0
  332. package/ui/arkgraph/material-build.mjs +23 -0
  333. package/ui/arkgraph/material-colors.mjs +39 -0
  334. package/ui/arkgraph/material-style.css +15 -0
  335. package/ui/arkgraph/open-graph.jsx +326 -0
  336. package/ui/arkgraph/outline.jsx +49 -0
  337. package/ui/arkgraph/package-lock.json +888 -0
  338. package/ui/arkgraph/package.json +17 -0
  339. package/ui/arkgraph/reading-layout.mjs +130 -0
  340. package/ui/arkgraph/reading-presentation.mjs +73 -0
  341. package/ui/arkgraph/record-detail.css +51 -0
  342. package/ui/arkgraph/record-details.jsx +29 -0
  343. package/ui/arkgraph/research-types.mjs +31 -0
  344. package/ui/arkgraph/selection-mark.jsx +6 -0
  345. package/ui/arkgraph/soft-spine.mjs +26 -0
  346. package/ui/arkgraph/steering-style.css +187 -0
  347. package/ui/arkgraph/style.css +272 -0
@@ -0,0 +1,459 @@
1
+ import { recordResearchCleanup } from '../workspace/control.mjs';
2
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ import { readAgentInstructions, updateRunState } from "../job.mjs";
7
+ import { validateResultFile } from "../protocol.mjs";
8
+ import { agentInvocationPromptArgument, buildAgentInvocation } from "../runtime/index.mjs";
9
+ import {
10
+ CODEX_FINAL_MESSAGE_PATH,
11
+ recoverJsonFromFinalMessage,
12
+ } from "../runtime/final-output.mjs";
13
+ import { CiteArkError, printableCommand, writeJson } from "../util.mjs";
14
+ import {
15
+ finalizeReproduction,
16
+ prepareReproduction,
17
+ recoverInvalidExecutionResult,
18
+ } from "../reproduction/lifecycle.mjs";
19
+ import {
20
+ initialReproductionPrompt,
21
+ retryReproductionPrompt,
22
+ } from "../reproduction/prompts.mjs";
23
+ import { infrastructureResumePrompt } from "./checkpoint-protocol.mjs";
24
+ import { remoteProviderSession } from "./gcp-batch-job.mjs";
25
+ import {
26
+ describeRemoteAgentFailure,
27
+ readRemoteAttempt,
28
+ reconcileRemoteAgentOutcome,
29
+ } from "./remote-attempt.mjs";
30
+ import {
31
+ acquireAutoDlProLease,
32
+ autoDlInstanceRequest,
33
+ resolveAutoDlProConfig,
34
+ } from "./autodl-pro-job.mjs";
35
+ import {
36
+ createAutoDlStageArchive,
37
+ executeAutoDlRemoteAttempt,
38
+ } from "./autodl-pro-remote.mjs";
39
+
40
+ export async function executeAutoDlProReproduction({
41
+ taskPath,
42
+ referenceMaterialsPath,
43
+ runsDirectory,
44
+ imageOverride,
45
+ repositoryOverride,
46
+ paperOverride,
47
+ computeDecision,
48
+ runId,
49
+ agentRuntime,
50
+ executorOptions = {},
51
+ dryRun = false,
52
+ progress = () => {},
53
+ }) {
54
+ const autoDlOptions = executorOptions.autoDl ?? {};
55
+ const bundle = await prepareReproduction({
56
+ taskPath,
57
+ referenceMaterialsPath,
58
+ runsDirectory,
59
+ imageOverride,
60
+ repositoryOverride,
61
+ paperOverride,
62
+ computeDecision,
63
+ runId,
64
+ agentRuntime,
65
+ requireApi: false,
66
+ sandboxProvider: "autodl-pro",
67
+ });
68
+ const config = resolveAutoDlProConfig({
69
+ bundle,
70
+ options: autoDlOptions,
71
+ requireToken: !dryRun,
72
+ });
73
+ const instructions = await readAgentInstructions(bundle.runtimeTask);
74
+ await mkdir(path.join(bundle.directories.execution, "prompts"), { recursive: true });
75
+
76
+ let validation = { result: null, issues: ["尚未运行 Agent"], protocolVerification: null };
77
+ const firstInvocation = await buildRemoteInvocation({
78
+ bundle,
79
+ attempt: 1,
80
+ validation,
81
+ instructions,
82
+ });
83
+ await writeFile(
84
+ path.join(bundle.directories.execution, "prompts", "attempt-1.txt"),
85
+ `${agentInvocationPromptArgument(firstInvocation)}\n`,
86
+ );
87
+ const preview = {
88
+ schemaVersion: "0.1",
89
+ executor: "autodl-pro",
90
+ instanceRequest: autoDlInstanceRequest(config, bundle.runId),
91
+ ssh: {
92
+ authentication: "instance-password-from-autodl-api",
93
+ hostKeyPolicy: "sha256-tofu-per-lease",
94
+ },
95
+ };
96
+ await writeJson(
97
+ path.join(bundle.directories.execution, "autodl-instance-request.json"),
98
+ preview,
99
+ );
100
+ if (dryRun) {
101
+ const cloudExecution = publicAutoDlExecution(config, null, []);
102
+ await updateRunState(bundle, { status: "prepared", cloudExecution });
103
+ return {
104
+ dryRun: true,
105
+ bundle,
106
+ invocation: {
107
+ printable: printableCommand("POST", [
108
+ `${config.apiBaseUrl}/api/v1/dev/instance/pro/create`,
109
+ ]),
110
+ executor: "autodl-pro",
111
+ instanceRequest: preview.instanceRequest,
112
+ },
113
+ cloud: cloudExecution,
114
+ };
115
+ }
116
+
117
+ let lease = null;
118
+ const attempts = [];
119
+ const records = [];
120
+ const temporaryDirectory = await mkdtemp(
121
+ path.join(os.tmpdir(), "citeark-autodl-pro-"),
122
+ );
123
+ let timedOut = false;
124
+ let successful = false;
125
+ let leaseReusable = true;
126
+ const leasePool = autoDlOptions.leasePool ?? null;
127
+ try {
128
+ await updateRunState(bundle, {
129
+ status: "running",
130
+ startedAt: new Date().toISOString(),
131
+ cloudExecution: publicAutoDlExecution(config, null, records),
132
+ });
133
+ await autoDlOptions.assertActive?.();
134
+ lease = leasePool
135
+ ? await leasePool.acquire({
136
+ config,
137
+ runId: bundle.runId,
138
+ clients: autoDlOptions.clients,
139
+ progress,
140
+ })
141
+ : await acquireAutoDlProLease({
142
+ config,
143
+ runId: bundle.runId,
144
+ clients: autoDlOptions.clients,
145
+ progress,
146
+ });
147
+ try {
148
+ await autoDlOptions.assertActive?.();
149
+ } catch (error) {
150
+ if (error?.processingLeaseLost === true) leaseReusable = false;
151
+ throw error;
152
+ }
153
+ await updateRunState(bundle, {
154
+ cloudExecution: publicAutoDlExecution(config, lease, records),
155
+ });
156
+ const maxAttempts = 1 + bundle.runtimeAgent.validationRetries;
157
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
158
+ const invocation = attempt === 1
159
+ ? firstInvocation
160
+ : await buildRemoteInvocation({ bundle, attempt, validation, instructions });
161
+ const resumeInvocation = await buildAgentInvocation({
162
+ bundle,
163
+ attempt: 2,
164
+ prompt: infrastructureResumePrompt(bundle),
165
+ instructions,
166
+ providerSession: remoteProviderSession(bundle.runtimeAgent),
167
+ });
168
+ await writeFile(
169
+ path.join(bundle.directories.execution, "prompts", `attempt-${attempt}.txt`),
170
+ `${agentInvocationPromptArgument(invocation)}\n`,
171
+ );
172
+ await writeFile(
173
+ path.join(bundle.directories.execution, "prompts", `attempt-${attempt}-resume.txt`),
174
+ `${agentInvocationPromptArgument(resumeInvocation)}\n`,
175
+ );
176
+ const stageArchive = path.join(temporaryDirectory, `stage-a${attempt}.tar.gz`);
177
+ const resultArchive = path.join(temporaryDirectory, `result-a${attempt}.tar.gz`);
178
+ await createAutoDlStageArchive(bundle, stageArchive);
179
+ const liveRecord = {
180
+ attempt,
181
+ instanceUuid: lease.instanceUuid,
182
+ state: "RUNNING",
183
+ startedAt: new Date().toISOString(),
184
+ checkpoint: null,
185
+ };
186
+ records.push(liveRecord);
187
+ let remote;
188
+ try {
189
+ const infrastructureExecution = await executeAutoDlRemoteAttemptWithLeaseRetry({
190
+ lease,
191
+ runId: bundle.runId,
192
+ maximumRetries: config.remoteInfrastructureRetries,
193
+ progress,
194
+ execute: async (infrastructureAttempt) => {
195
+ if (infrastructureAttempt > 1) await rm(resultArchive, { force: true });
196
+ return await executeAutoDlRemoteAttempt({
197
+ bundle,
198
+ lease,
199
+ config,
200
+ invocation,
201
+ resumeInvocation,
202
+ attempt,
203
+ stageArchive,
204
+ resultArchive,
205
+ checkpointPolicy: config.checkpointing,
206
+ restoreCheckpointOnStart: attempt > 1 || infrastructureAttempt > 1,
207
+ reuseCompletedResultOnRestore: false,
208
+ secretManager: autoDlOptions.secretManager,
209
+ stageTransfer: autoDlOptions.stageTransfer,
210
+ stageClients: autoDlOptions.clients,
211
+ assertActive: autoDlOptions.assertActive,
212
+ progress,
213
+ onCheckpoint: async (checkpoint) => {
214
+ liveRecord.checkpoint = publicCheckpoint(checkpoint);
215
+ await updateRunState(bundle, {
216
+ cloudExecution: publicAutoDlExecution(config, lease, records),
217
+ });
218
+ },
219
+ });
220
+ },
221
+ });
222
+ remote = infrastructureExecution.remote;
223
+ liveRecord.infrastructureRetryCount = infrastructureExecution.retryCount;
224
+ } catch (error) {
225
+ leaseReusable = false;
226
+ liveRecord.state = "FAILED";
227
+ liveRecord.finishedAt = new Date().toISOString();
228
+ liveRecord.error = error instanceof Error ? error.message : String(error);
229
+ if (error?.processingLeaseLost === true) throw error;
230
+ throw new CiteArkError(
231
+ `AutoDL 第 ${attempt} 次执行没有返回可恢复的运行包:${error instanceof Error ? error.message : String(error)}`,
232
+ { cause: error },
233
+ );
234
+ }
235
+ Object.assign(liveRecord, remote.record);
236
+ timedOut ||= remote.record.timedOut;
237
+ const remoteAttempt = await readRemoteAttempt(bundle, attempt);
238
+ attempts.push({
239
+ attempt,
240
+ startedAt: remote.record.startedAt,
241
+ finishedAt: remote.record.finishedAt,
242
+ exitCode: remoteAttempt?.exitCode ?? remote.record.exitCode,
243
+ signal: remote.record.signal,
244
+ timedOut: remote.record.timedOut,
245
+ executor: "autodl-pro",
246
+ instanceUuid: lease.instanceUuid,
247
+ checkpoint: remote.record.checkpoint,
248
+ });
249
+ await recoverJsonFromFinalMessage({
250
+ finalMessagePath: hostRuntimePath(bundle, CODEX_FINAL_MESSAGE_PATH),
251
+ outputPath: path.join(bundle.directories.output, "result.json"),
252
+ });
253
+ const submittedValidation = await validateResultFile(
254
+ path.join(bundle.directories.output, "result.json"),
255
+ bundle.runtimeTask,
256
+ bundle.directories.output,
257
+ );
258
+ const remoteFailure = await describeRemoteAgentFailure(bundle, attempt);
259
+ const reconciled = reconcileRemoteAgentOutcome({
260
+ validation: submittedValidation,
261
+ remoteFailure,
262
+ });
263
+ if (reconciled.blockingFailure) throw new CiteArkError(reconciled.blockingFailure.message);
264
+ validation = reconciled.validation;
265
+ await updateRunState(bundle, {
266
+ cloudExecution: publicAutoDlExecution(config, lease, records),
267
+ });
268
+ if (validation.issues.length === 0) break;
269
+ if (attempt < maxAttempts) {
270
+ progress(`结果协议校验失败,将在同一 AutoDL 实例继续:${validation.issues.join(";")}`);
271
+ }
272
+ }
273
+
274
+ const cloudExecution = publicAutoDlExecution(config, lease, records);
275
+ await writeJson(path.join(bundle.directories.execution, "autodl-runs.json"), {
276
+ schemaVersion: "0.1",
277
+ executor: "autodl-pro",
278
+ ...cloudExecution,
279
+ });
280
+ await writeInvocation(bundle, cloudExecution, records);
281
+ validation = await recoverInvalidExecutionResult({
282
+ bundle,
283
+ validation,
284
+ attempts,
285
+ timedOut,
286
+ });
287
+ const result = await finalizeReproduction({
288
+ bundle,
289
+ validation,
290
+ attempts,
291
+ timedOut,
292
+ sandboxImageIdentity: {
293
+ id: config.imageUuid,
294
+ repositoryDigests: [],
295
+ },
296
+ cloudExecution,
297
+ });
298
+ successful = validation.issues.length === 0;
299
+ return result;
300
+ } catch (error) {
301
+ if (bundle.state.status === "running") {
302
+ await updateRunState(bundle, {
303
+ status: "failed",
304
+ finishedAt: new Date().toISOString(),
305
+ error: error instanceof Error ? error.message : String(error),
306
+ cloudExecution: publicAutoDlExecution(config, lease, records),
307
+ });
308
+ }
309
+ throw error;
310
+ } finally {
311
+ if (lease) {
312
+ const cleanup = await (
313
+ leasePool
314
+ ? leasePool.release(lease, { reusable: leaseReusable, runId: bundle.runId })
315
+ : lease.close({ successful })
316
+ ).then((value) => value ?? { released: false }).catch((error) => ({
317
+ released: false,
318
+ error: error instanceof Error ? error.message : String(error),
319
+ }));
320
+ for (const record of records) record.instanceReleased = cleanup.released;
321
+ await recordResearchCleanup({ provider: 'autodl', resource: lease.instanceUuid, status: cleanup.released ? 'released' : leasePool && leaseReusable ? 'pooled' : 'failed', ...(cleanup.error ? { error: cleanup.error } : {}) });
322
+ }
323
+ await rm(temporaryDirectory, { recursive: true, force: true });
324
+ }
325
+ }
326
+
327
+ export async function executeAutoDlRemoteAttemptWithLeaseRetry({
328
+ lease,
329
+ runId,
330
+ maximumRetries = 2,
331
+ execute,
332
+ progress = () => {},
333
+ }) {
334
+ const retries = Math.max(0, Number.parseInt(String(maximumRetries), 10) || 0);
335
+ for (let infrastructureAttempt = 1; ; infrastructureAttempt += 1) {
336
+ try {
337
+ return {
338
+ remote: await execute(infrastructureAttempt),
339
+ retryCount: infrastructureAttempt - 1,
340
+ };
341
+ } catch (error) {
342
+ if (
343
+ infrastructureAttempt > retries
344
+ || !isRetryableAutoDlRemoteInfrastructureError(error)
345
+ || !(await lease.isHealthy())
346
+ ) {
347
+ throw error;
348
+ }
349
+ progress(
350
+ `AutoDL ${runId}: 瞬时网络或传输故障,实例 ${lease.instanceUuid} 仍健康;保留已拉取镜像并在同一租约进行第 ${infrastructureAttempt + 1}/${retries + 1} 次基础设施尝试`,
351
+ );
352
+ }
353
+ }
354
+ }
355
+
356
+ export function isRetryableAutoDlRemoteInfrastructureError(error) {
357
+ const message = error instanceof Error ? error.message : String(error);
358
+ if (/远程运行.*已超时|执行超时|timed out after/i.test(message)) return false;
359
+ return /网络预检|network.?preflight|HTTP\s*5\d\d|\b50[234]\b|SSH|SFTP|GCS|连接|connect|ECONN|EPIPE|socket|上传|下载|transfer/i.test(message);
360
+ }
361
+
362
+ async function buildRemoteInvocation({ bundle, attempt, validation, instructions }) {
363
+ return await buildAgentInvocation({
364
+ bundle,
365
+ attempt,
366
+ prompt: attempt === 1
367
+ ? initialReproductionPrompt(bundle)
368
+ : retryReproductionPrompt(validation.issues, bundle.runtimeTask),
369
+ instructions,
370
+ providerSession: remoteProviderSession(bundle.runtimeAgent),
371
+ });
372
+ }
373
+
374
+ function hostRuntimePath(bundle, containerPath) {
375
+ return path.join(bundle.directories.run, containerPath.replace(/^\/job\//, ""));
376
+ }
377
+
378
+ function publicAutoDlExecution(config, lease, records) {
379
+ const runSeconds = records.reduce(
380
+ (total, record) => total + (Number(record.durationSeconds) || 0),
381
+ 0,
382
+ );
383
+ const observedHourlyCny = lease?.observedHourlyCny ?? config.hourlyCny;
384
+ return {
385
+ provider: "autodl",
386
+ service: "container-instance-pro",
387
+ instance: lease?.publicRecord() ?? null,
388
+ gpuSpecUuid: lease?.config.gpuSpecUuid ?? config.gpuSpecUuid,
389
+ imageUuid: config.imageUuid,
390
+ inputStaging: {
391
+ preferred: config.stagingBucket && config.stageSigningServiceAccount
392
+ ? "gcs-signed-url"
393
+ : "sftp",
394
+ fallback: "sftp",
395
+ signedUrlExpiresSeconds: config.stageSignedUrlExpiresSeconds,
396
+ },
397
+ checkpointing: {
398
+ ...config.checkpointing,
399
+ storage: "instance-system-disk",
400
+ durabilityBoundary: "instance-lease",
401
+ },
402
+ temporaryResources: {
403
+ cleanupPolicy: {
404
+ releaseOnSuccess: !config.keepInstance,
405
+ keepFailedInstance: config.keepFailedInstance,
406
+ },
407
+ },
408
+ credentialInjection: {
409
+ mode: config.credentialSource === "task-key" ? "authorized-task-key-to-ephemeral-ssh-environment" : "secret-manager-to-ephemeral-ssh-environment",
410
+ valueRecorded: false,
411
+ },
412
+ computeUsage: {
413
+ runSeconds,
414
+ observedHourlyCny: observedHourlyCny ?? null,
415
+ estimatedCostCny: typeof observedHourlyCny === "number"
416
+ ? Number(((runSeconds / 3600) * observedHourlyCny).toFixed(6))
417
+ : null,
418
+ estimatedCostUsd: typeof config.hourlyUsd === "number"
419
+ ? Number(((runSeconds / 3600) * config.hourlyUsd).toFixed(6))
420
+ : null,
421
+ invoiceReconciled: false,
422
+ },
423
+ runs: structuredClone(records),
424
+ };
425
+ }
426
+
427
+ async function writeInvocation(bundle, cloudExecution, records) {
428
+ await writeJson(path.join(bundle.directories.execution, "invocation.json"), {
429
+ schemaVersion: "0.1",
430
+ sandbox: "autodl-pro",
431
+ credentials: {
432
+ agent: bundle.runtimeAgent.runtime,
433
+ protocol: bundle.runtimeAgent.api.protocol,
434
+ source: "gcp-secret-manager",
435
+ mode: "ephemeral-ssh-environment",
436
+ injectedIntoSandbox: true,
437
+ valueRecorded: false,
438
+ },
439
+ networkEgress: {
440
+ mode: "direct",
441
+ allowedHosts: [new URL(bundle.runtimeAgent.api.baseUrl).hostname],
442
+ },
443
+ cloud: cloudExecution,
444
+ invocations: records.map((record) => ({
445
+ attempt: record.attempt,
446
+ instanceUuid: record.instanceUuid,
447
+ state: record.state,
448
+ })),
449
+ });
450
+ }
451
+
452
+ function publicCheckpoint(checkpoint) {
453
+ return {
454
+ schemaVersion: checkpoint.schemaVersion,
455
+ sequence: checkpoint.sequence,
456
+ kind: checkpoint.kind,
457
+ createdAt: checkpoint.createdAt,
458
+ };
459
+ }