@anyswarm/core 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/AGENTS.md +20 -5
  2. package/README.md +69 -55
  3. package/dist/examples/README.md +138 -77
  4. package/dist/examples/authoring/README.md +4 -4
  5. package/dist/examples/autoresearch/README.md +108 -16
  6. package/dist/examples/autoresearch/REQUIREMENTS.zh.md +13 -12
  7. package/dist/examples/autoresearch/config.d.ts +48 -5
  8. package/dist/examples/autoresearch/config.js +57 -23
  9. package/dist/examples/autoresearch/demo.d.ts +12 -4
  10. package/dist/examples/autoresearch/demo.js +65 -22
  11. package/dist/examples/autoresearch/eject.json +2 -0
  12. package/dist/examples/autoresearch/frontiercs2-config.d.ts +2 -0
  13. package/dist/examples/autoresearch/frontiercs2-config.js +14 -0
  14. package/dist/examples/autoresearch/frontiercs2.d.ts +18 -1
  15. package/dist/examples/autoresearch/frontiercs2.js +71 -14
  16. package/dist/examples/autoresearch/prepare-demo.d.ts +1 -0
  17. package/dist/examples/autoresearch/prepare-demo.js +46 -0
  18. package/dist/examples/autoresearch/prepare.d.ts +105 -53
  19. package/dist/examples/autoresearch/prepare.js +126 -57
  20. package/dist/examples/autoresearch/project.d.ts +6 -95
  21. package/dist/examples/autoresearch/project.js +131 -45
  22. package/dist/examples/autoresearch/research-service.d.ts +16 -1
  23. package/dist/examples/autoresearch/research-service.js +84 -44
  24. package/dist/examples/code/README.md +25 -17
  25. package/dist/examples/code/REQUIREMENTS.zh.md +3 -3
  26. package/dist/examples/code/config.d.ts +1 -0
  27. package/dist/examples/first-harness/AGENTS.md +25 -0
  28. package/dist/examples/first-harness/README.md +136 -0
  29. package/dist/examples/first-harness/config.d.ts +9 -8
  30. package/dist/examples/first-harness/config.js +33 -26
  31. package/dist/examples/first-harness/eject.json +14 -0
  32. package/dist/examples/first-harness/handoff.js +3 -3
  33. package/dist/examples/first-harness/harness.d.ts +14 -18
  34. package/dist/examples/first-harness/harness.js +102 -77
  35. package/dist/examples/first-harness/input/README.md +7 -0
  36. package/dist/examples/first-harness/session.js +2 -1
  37. package/dist/examples/first-harness/tsconfig.json +2 -1
  38. package/dist/examples/harness-session/README.md +4 -4
  39. package/dist/examples/lead-worker/README.md +1 -1
  40. package/dist/examples/lead-worker/project-config.d.ts +1 -0
  41. package/dist/examples/messages/README.md +2 -2
  42. package/dist/examples/notes/README.md +5 -5
  43. package/dist/examples/notes/config.d.ts +1 -0
  44. package/dist/examples/parallel-swarm/AGENTS.md +32 -0
  45. package/dist/examples/parallel-swarm/README.md +136 -0
  46. package/dist/examples/parallel-swarm/board-service.js +25 -8
  47. package/dist/examples/parallel-swarm/board.d.ts +31 -1
  48. package/dist/examples/parallel-swarm/board.js +98 -13
  49. package/dist/examples/parallel-swarm/config.d.ts +11 -0
  50. package/dist/examples/parallel-swarm/config.js +39 -0
  51. package/dist/examples/parallel-swarm/eject.json +5 -0
  52. package/dist/examples/parallel-swarm/harness.d.ts +26 -20
  53. package/dist/examples/parallel-swarm/harness.js +77 -76
  54. package/dist/examples/parallel-swarm/report.d.ts +12 -0
  55. package/dist/examples/parallel-swarm/report.js +30 -0
  56. package/dist/examples/peermesh/README.md +1 -1
  57. package/dist/examples/peermesh/project-config.d.ts +1 -0
  58. package/dist/examples/services/agent-control/README.md +1 -1
  59. package/dist/examples/services/mathlib-search/README.md +1 -1
  60. package/dist/examples/services/mcp-managed/README.md +1 -1
  61. package/dist/examples/services/persistent-board/README.md +6 -3
  62. package/dist/examples/subagents/AGENTS.md +35 -0
  63. package/dist/examples/subagents/README.md +129 -93
  64. package/dist/examples/subagents/config.d.ts +2 -10
  65. package/dist/examples/subagents/config.js +9 -16
  66. package/dist/examples/subagents/eject.json +17 -0
  67. package/dist/examples/subagents/handoff-config.d.ts +41 -0
  68. package/dist/examples/subagents/handoff-config.js +13 -0
  69. package/dist/examples/subagents/model.d.ts +3 -0
  70. package/dist/examples/subagents/model.js +19 -0
  71. package/dist/examples/substrate/README.md +12 -6
  72. package/dist/examples/substrate/config.d.ts +1 -0
  73. package/dist/examples/substrate/project-config.d.ts +1 -0
  74. package/dist/examples/super/README.md +34 -22
  75. package/dist/examples/super/actions.d.ts +1 -1
  76. package/dist/examples/super/actions.js +11 -11
  77. package/dist/examples/super/config.js +3 -3
  78. package/dist/examples/super/eject.json +1 -1
  79. package/dist/examples/super/location.js +1 -1
  80. package/dist/examples/super/operator.d.ts +1 -0
  81. package/dist/examples/super/operator.js +31 -0
  82. package/dist/examples/super/project.d.ts +0 -107
  83. package/dist/examples/super/project.js +1 -3
  84. package/dist/examples/taskpool/README.md +1 -1
  85. package/dist/examples/taskpool/config.d.ts +1 -0
  86. package/dist/examples/taskpool/deploy/service-hosts/service-authority-snapshot.d.ts +4 -4
  87. package/dist/scripts/anyswarm-arguments.d.ts +7 -25
  88. package/dist/scripts/anyswarm-arguments.js +69 -97
  89. package/dist/scripts/anyswarm-eject.js +1 -1
  90. package/dist/scripts/anyswarm-harnesses.d.ts +0 -1
  91. package/dist/scripts/anyswarm-harnesses.js +1 -22
  92. package/dist/scripts/anyswarm-installation.d.ts +7 -40
  93. package/dist/scripts/anyswarm-installation.js +17 -291
  94. package/dist/scripts/anyswarm-launch.d.ts +6 -36
  95. package/dist/scripts/anyswarm-launch.js +32 -81
  96. package/dist/scripts/anyswarm-progress.d.ts +6 -0
  97. package/dist/scripts/anyswarm-progress.js +133 -0
  98. package/dist/scripts/anyswarm-project.d.ts +1 -9
  99. package/dist/scripts/anyswarm-project.js +40 -127
  100. package/dist/scripts/anyswarm-source-runner.js +9 -41
  101. package/dist/scripts/anyswarm.js +6 -26
  102. package/dist/scripts/build-provenance.json +1 -1
  103. package/dist/scripts/generate-architecture-coverage.js +1 -1
  104. package/dist/scripts/generate-architecture-prompts.js +18 -10
  105. package/dist/scripts/local-environment.d.ts +13 -7
  106. package/dist/scripts/local-environment.js +73 -21
  107. package/dist/scripts/local-setup.d.ts +3 -0
  108. package/dist/scripts/local-setup.js +153 -118
  109. package/dist/scripts/pack-release.js +31 -4
  110. package/dist/src/core/index.js +1 -1
  111. package/dist/src/core/sandbox/opensandbox-backend.js +10 -4
  112. package/dist/src/core/sandbox/sandbox-connection.d.ts +9 -2
  113. package/dist/src/core/sandbox/sandbox-connection.js +22 -7
  114. package/dist/src/core/worker-image.js +1 -1
  115. package/dist/src/harness/project-harness.d.ts +1 -0
  116. package/dist/src/harness/project-harness.js +5 -4
  117. package/dist/src/harness/project-rpc-client.js +19 -0
  118. package/dist/src/harness/project-runtime.js +3 -1
  119. package/dist/src/harness/typescript-loader.d.ts +2 -0
  120. package/dist/src/harness/typescript-loader.js +26 -8
  121. package/dist/src/trace-viewer/command.mjs +6 -3
  122. package/dist/src/trace-viewer/public/app.js +239 -59
  123. package/dist/src/trace-viewer/public/index.html +5 -0
  124. package/dist/src/trace-viewer/public/style.css +22 -0
  125. package/dist/src/trace-viewer/reader.mjs +242 -26
  126. package/dist/src/trace-viewer/run-root.d.mts +1 -0
  127. package/dist/src/trace-viewer/run-root.mjs +7 -0
  128. package/dist/src/trace-viewer/server.mjs +3 -1
  129. package/docs/INDEX.md +11 -9
  130. package/docs/architecture/04-services.md +1 -1
  131. package/docs/architecture/06-observability-experiments.md +21 -7
  132. package/docs/architecture/07-run-configuration.md +118 -19
  133. package/docs/architecture/08-prompts.md +21 -2
  134. package/docs/architecture/10-service-api-reference.md +12 -5
  135. package/docs/architecture/12-code-coverage.md +157 -115
  136. package/docs/architecture/15-core-runtime.md +1 -1
  137. package/docs/architecture/16-pi-opensandbox-backend.md +2 -0
  138. package/docs/architecture/17-harness-reporting.md +79 -1
  139. package/docs/architecture/22-website.md +52 -20
  140. package/docs/architecture/23-project-harness.md +109 -37
  141. package/docs/architecture/26-code.md +20 -5
  142. package/docs/architecture/27-personal.md +23 -8
  143. package/docs/architecture/28-autoresearch.md +18 -12
  144. package/docs/architecture/INDEX.md +1 -2
  145. package/docs/architecture/prompts/11-first-sdk-harness.md +9 -9
  146. package/docs/architecture/prompts/16-parallel-swarm.md +46 -13
  147. package/docs/architecture/prompts/22-autoresearch.md +9 -2
  148. package/docs/architecture/prompts/source-manifest.json +76 -52
  149. package/docs/architecture/source-map.json +445 -105
  150. package/docs/designs/core-harness/01-core.md +2 -2
  151. package/docs/designs/core-harness/06-project-harness.md +3 -3
  152. package/docs/designs/core-harness/README.md +2 -2
  153. package/docs/en/agents.md +1 -1
  154. package/docs/en/autoresearch.md +41 -0
  155. package/docs/en/blog/100b-tokens.md +157 -0
  156. package/docs/en/build-your-harness.md +47 -22
  157. package/docs/en/changelog.md +29 -1
  158. package/docs/en/first-harness.md +40 -32
  159. package/docs/en/harnesses/index.md +23 -23
  160. package/docs/en/harnesses/lead-worker.md +1 -1
  161. package/docs/en/harnesses/peermesh.md +2 -2
  162. package/docs/en/harnesses/subagents.md +10 -31
  163. package/docs/en/harnesses/substrate.md +4 -4
  164. package/docs/en/harnesses/taskpool.md +2 -2
  165. package/docs/en/latest.md +30 -5
  166. package/docs/en/overview.md +22 -22
  167. package/docs/en/quickstart.md +69 -56
  168. package/docs/en/reference/api.md +1 -1
  169. package/docs/en/reference/cli.md +47 -85
  170. package/docs/en/sandbox.md +3 -3
  171. package/docs/en/trace-viewer.md +32 -12
  172. package/docs/operations/trace-viewer.md +26 -11
  173. package/docs/third-party-notices.md +0 -1
  174. package/docs/workflows/development.md +160 -118
  175. package/docs/workflows/release-and-docs-versioning.md +207 -54
  176. package/docs/workflows/release-cli-acceptance.md +162 -0
  177. package/docs/zh/agents.md +1 -1
  178. package/docs/zh/autoresearch.md +41 -0
  179. package/docs/zh/blog/100b-tokens.md +102 -0
  180. package/docs/zh/build-your-harness.md +48 -23
  181. package/docs/zh/changelog.md +29 -1
  182. package/docs/zh/first-harness.md +43 -35
  183. package/docs/zh/harnesses/index.md +23 -23
  184. package/docs/zh/harnesses/lead-worker.md +1 -1
  185. package/docs/zh/harnesses/peermesh.md +2 -2
  186. package/docs/zh/harnesses/subagents.md +10 -31
  187. package/docs/zh/harnesses/substrate.md +4 -4
  188. package/docs/zh/harnesses/taskpool.md +2 -2
  189. package/docs/zh/latest.md +30 -5
  190. package/docs/zh/overview.md +23 -23
  191. package/docs/zh/quickstart.md +66 -57
  192. package/docs/zh/reference/api.md +1 -1
  193. package/docs/zh/reference/cli.md +19 -79
  194. package/docs/zh/sandbox.md +3 -3
  195. package/docs/zh/trace-viewer.md +32 -12
  196. package/examples/README.md +138 -77
  197. package/examples/authoring/README.md +4 -4
  198. package/examples/autoresearch/README.md +108 -16
  199. package/examples/autoresearch/REQUIREMENTS.zh.md +13 -12
  200. package/examples/autoresearch/config.ts +64 -25
  201. package/examples/autoresearch/demo.ts +75 -22
  202. package/examples/autoresearch/eject.json +2 -0
  203. package/examples/autoresearch/frontiercs2-config.ts +15 -0
  204. package/examples/autoresearch/frontiercs2.ts +64 -11
  205. package/examples/autoresearch/prepare-demo.ts +44 -0
  206. package/examples/autoresearch/prepare.ts +134 -60
  207. package/examples/autoresearch/project.ts +120 -44
  208. package/examples/autoresearch/research-service.ts +91 -41
  209. package/examples/code/README.md +25 -17
  210. package/examples/code/REQUIREMENTS.zh.md +3 -3
  211. package/examples/first-harness/AGENTS.md +25 -0
  212. package/examples/first-harness/README.md +136 -0
  213. package/examples/first-harness/config.ts +41 -27
  214. package/examples/first-harness/eject.json +14 -0
  215. package/examples/first-harness/handoff.ts +3 -3
  216. package/examples/first-harness/harness.ts +104 -72
  217. package/examples/first-harness/input/README.md +7 -0
  218. package/examples/first-harness/session.ts +2 -1
  219. package/examples/first-harness/tsconfig.json +2 -1
  220. package/examples/harness-session/README.md +4 -4
  221. package/examples/lead-worker/README.md +1 -1
  222. package/examples/messages/README.md +2 -2
  223. package/examples/notes/README.md +5 -5
  224. package/examples/parallel-swarm/AGENTS.md +32 -0
  225. package/examples/parallel-swarm/README.md +136 -0
  226. package/examples/parallel-swarm/board-service.ts +28 -9
  227. package/examples/parallel-swarm/board.ts +107 -13
  228. package/examples/parallel-swarm/config.ts +47 -0
  229. package/examples/parallel-swarm/eject.json +5 -0
  230. package/examples/parallel-swarm/harness.ts +83 -71
  231. package/examples/parallel-swarm/report.ts +33 -0
  232. package/examples/peermesh/README.md +1 -1
  233. package/examples/services/agent-control/README.md +1 -1
  234. package/examples/services/mathlib-search/README.md +1 -1
  235. package/examples/services/mcp-managed/README.md +1 -1
  236. package/examples/services/persistent-board/README.md +6 -3
  237. package/examples/subagents/AGENTS.md +35 -0
  238. package/examples/subagents/README.md +129 -93
  239. package/examples/subagents/config.ts +9 -15
  240. package/examples/subagents/eject.json +17 -0
  241. package/examples/subagents/handoff-config.ts +14 -0
  242. package/examples/subagents/model.ts +20 -0
  243. package/examples/substrate/README.md +12 -6
  244. package/examples/super/README.md +34 -22
  245. package/examples/super/actions.ts +11 -11
  246. package/examples/super/config.ts +3 -3
  247. package/examples/super/eject.json +1 -1
  248. package/examples/super/location.ts +1 -1
  249. package/examples/super/operator.ts +28 -0
  250. package/examples/super/project.ts +1 -3
  251. package/examples/taskpool/README.md +1 -1
  252. package/npm-shrinkwrap.development.json +46 -1538
  253. package/npm-shrinkwrap.json +10 -43
  254. package/package.development.json +3 -6
  255. package/package.json +3 -5
  256. package/scripts/anyswarm-arguments.ts +67 -96
  257. package/scripts/anyswarm-eject.ts +1 -1
  258. package/scripts/anyswarm-harnesses.ts +1 -18
  259. package/scripts/anyswarm-installation.ts +18 -294
  260. package/scripts/anyswarm-launch.ts +30 -102
  261. package/scripts/anyswarm-progress.ts +125 -0
  262. package/scripts/anyswarm-project.ts +31 -123
  263. package/scripts/anyswarm-source-runner.ts +9 -36
  264. package/scripts/anyswarm.ts +4 -24
  265. package/scripts/generate-architecture-coverage.ts +1 -1
  266. package/scripts/generate-architecture-prompts.ts +21 -10
  267. package/scripts/local-environment.ts +79 -21
  268. package/scripts/local-setup.ts +150 -105
  269. package/scripts/pack-release.ts +28 -4
  270. package/src/core/index.ts +1 -1
  271. package/src/core/sandbox/opensandbox-backend.ts +10 -4
  272. package/src/core/sandbox/sandbox-connection.ts +22 -7
  273. package/src/core/worker-image.ts +1 -1
  274. package/src/harness/project-harness.ts +5 -4
  275. package/src/harness/project-rpc-client.ts +23 -0
  276. package/src/harness/project-runtime.ts +2 -1
  277. package/src/harness/typescript-loader.ts +28 -8
  278. package/src/trace-viewer/command.mjs +6 -3
  279. package/src/trace-viewer/public/app.js +239 -59
  280. package/src/trace-viewer/public/index.html +5 -0
  281. package/src/trace-viewer/public/style.css +22 -0
  282. package/src/trace-viewer/reader.mjs +242 -26
  283. package/src/trace-viewer/run-root.d.mts +1 -0
  284. package/src/trace-viewer/run-root.mjs +7 -0
  285. package/src/trace-viewer/server.mjs +3 -1
  286. package/dist/scripts/anyswarm-applications.d.ts +0 -19
  287. package/dist/scripts/anyswarm-applications.js +0 -19
  288. package/dist/scripts/anyswarm-tui-config.d.ts +0 -36
  289. package/dist/scripts/anyswarm-tui-config.js +0 -189
  290. package/dist/scripts/anyswarm-tui-session.d.ts +0 -66
  291. package/dist/scripts/anyswarm-tui-session.js +0 -304
  292. package/dist/scripts/anyswarm-tui-terminal.d.ts +0 -41
  293. package/dist/scripts/anyswarm-tui-terminal.js +0 -154
  294. package/dist/scripts/anyswarm-tui.d.ts +0 -2
  295. package/dist/scripts/anyswarm-tui.js +0 -1012
  296. package/docs/architecture/25-foreground-tui.md +0 -51
  297. package/scripts/anyswarm-applications.ts +0 -39
  298. package/scripts/anyswarm-tui-config.ts +0 -174
  299. package/scripts/anyswarm-tui-session.ts +0 -295
  300. package/scripts/anyswarm-tui-terminal.ts +0 -147
  301. package/scripts/anyswarm-tui.ts +0 -912
@@ -1,12 +1,12 @@
1
- import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
1
+ import { createReadStream } from 'node:fs';
2
+ import { createInterface } from 'node:readline';
3
+ import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises';
2
4
  import { join, resolve } from 'node:path';
3
5
  import { setTimeout as delay } from 'node:timers/promises';
4
6
  import { createRuntime, createSandbox, getExecutorCapabilities, observeProjectRuntime, ProjectPreflightError, runInput, ServiceRegistry,
5
7
  type CloseReceipt, type Harness, type Profile, type HarnessContext, type HarnessJson, type InterruptReceipt, type JsonValue, type Runtime } from '@anyswarm/core';
6
- import { checkBudget, demoGoal, type ResearchConfiguration } from './config.js';
7
- import { frontierDemo } from './demo.js';
8
- import { prepareFrontier } from './prepare.js';
9
- import { appendResearchEvent, candidatePath, createResearch, researchOperations, withDeadline } from './research-service.js';
8
+ import { checkBudget, modelConfigurationError, type ResearchConfiguration } from './config.js';
9
+ import { appendResearchEvent, candidatePath, createResearch, readFinalEvaluation, researchOperations, withDeadline } from './research-service.js';
10
10
 
11
11
  const instructions = `You are one of several equal research peers exploring the same goal. Choose your own concrete direction and coordinate directly with peers.
12
12
  Use the following CLI directly in your private project. The host already provides this Service.
@@ -41,13 +41,15 @@ function configuration(value: unknown): ResearchConfiguration {
41
41
  !config.evaluator || typeof config.evaluator.train !== 'function' || typeof config.evaluator.final !== 'function' ||
42
42
  !config.executor || !config.image || !config.model || !config.sandbox || !config.connection ||
43
43
  (config.targetScore !== undefined && !Number.isFinite(config.targetScore))) {
44
- throw new ProjectPreflightError('AUTORESEARCH_CONFIG_REQUIRED', 'Use anys -u autoresearch --config ./research.ts with a goal, trusted evaluator and runtime settings, or run /demo frontiercs2.');
44
+ throw new ProjectPreflightError('AUTORESEARCH_CONFIG_REQUIRED', 'Run anyswarm --harness autoresearch --config ./research.ts --prompt <goal> with a trusted evaluator and runtime settings.');
45
45
  }
46
46
  for (const ms of [config.evaluationTimeoutMs, config.closeTimeoutMs]) {
47
47
  if (ms !== undefined && (!Number.isSafeInteger(ms) || ms < 1 || ms > 2_147_483_647)) {
48
48
  throw new ProjectPreflightError('AUTORESEARCH_CONFIG_INVALID', 'Evaluator timeouts must be positive millisecond values.');
49
49
  }
50
50
  }
51
+ const problem = modelConfigurationError(config.model, config.executor);
52
+ if (problem) throw new ProjectPreflightError('AUTORESEARCH_MODEL_REQUIRED', problem);
51
53
  return { ...config, budget: checkBudget(config.budget) };
52
54
  }
53
55
 
@@ -56,20 +58,6 @@ export function resolveWorkspace({ cwd, configuration }: { cwd: string; configur
56
58
  return typeof target === 'string' && target.trim() ? resolve(cwd, target) : cwd;
57
59
  }
58
60
 
59
- export const slashActions = {
60
- async prepare({ args, signal, progress = console.error }: { args: string; signal: AbortSignal; progress?: (message: string) => void }) {
61
- if (args && args !== 'frontiercs2') throw new Error('Usage: /prepare [frontiercs2]');
62
- const result = await prepareFrontier({ signal, progress });
63
- return result.ok ? result : { kind: 'action-report' as const, exitCode: 2, result };
64
- },
65
- async demo({ args, signal }: { args: string; signal: AbortSignal }) {
66
- if (args !== 'frontiercs2') throw new Error('Usage: /demo frontiercs2');
67
- const { configuration, starter } = await frontierDemo();
68
- signal.throwIfAborted();
69
- return { kind: 'start-run' as const, cwd: starter, prompt: demoGoal, configuration };
70
- },
71
- };
72
-
73
61
  type PeerWork = {
74
62
  controller: AbortController;
75
63
  interrupt?: Promise<InterruptReceipt>;
@@ -89,6 +77,8 @@ async function modelUsage(directory: string, peers: { agentId: string; label: st
89
77
  let outputTokens = 0;
90
78
  let attemptsWithUsage = 0;
91
79
  const intervals: { agentId: string; start: number; end: number }[] = [];
80
+ const upstreamModels = new Map<string, number>();
81
+ const requestIntervals: { from: number; to: number; peers: number }[] = [];
92
82
  const summarized = new Map(peers.map(peer => [peer.agentId, { ...peer, dispatched: 0, succeeded: 0 }]));
93
83
  for (const id of attempts) {
94
84
  const attempt = (file: string) => readFile(join(trace, id, file), 'utf8').then(text => JSON.parse(text)).catch(() => null);
@@ -103,14 +93,36 @@ async function modelUsage(directory: string, peers: { agentId: string; label: st
103
93
  }
104
94
  if (result?.state !== 'completed' || result?.upstreamStatus !== 200) continue;
105
95
  peer.succeeded++;
96
+ const models = new Set<string>();
97
+ const stream = createReadStream(join(trace, id, 'response.txt'));
98
+ try {
99
+ for await (const line of createInterface({ input: stream, crlfDelay: Infinity })) {
100
+ if (!line.startsWith('data:')) continue;
101
+ try {
102
+ const event = JSON.parse(line.slice(5));
103
+ const model = event.type === 'response.completed' ? event.response?.model : event.model;
104
+ if (typeof model === 'string') models.add(model.slice(0, 160));
105
+ } catch { /* Incomplete or non-JSON SSE fields carry no model identity. */ }
106
+ }
107
+ } catch { /* The gateway can record the attempt even if the upstream bytes are unavailable. */ }
108
+ finally { stream.destroy(); }
109
+ if (models.size === 1) {
110
+ const model = [...models][0];
111
+ upstreamModels.set(model, (upstreamModels.get(model) ?? 0) + 1);
112
+ }
106
113
  const start = Date.parse(request.startedAt);
107
114
  const end = Date.parse(result.endedAt);
108
115
  if (start < end) intervals.push({ agentId: peer.agentId, start, end });
109
116
  }
110
117
  const current = new Map<string, number>();
111
118
  let peakConcurrentPeers = 0;
119
+ let lastAt: number | undefined;
112
120
  for (const point of intervals.flatMap(({ agentId, start, end }) =>
113
121
  [{ agentId, at: start, delta: 1 }, { agentId, at: end, delta: -1 }]).sort((a, b) => a.at - b.at || a.delta - b.delta)) {
122
+ if (lastAt !== undefined && lastAt < point.at && current.size > 1) {
123
+ requestIntervals.push({ from: lastAt, to: point.at, peers: current.size });
124
+ }
125
+ lastAt = point.at;
114
126
  const next = (current.get(point.agentId) ?? 0) + point.delta;
115
127
  if (next) current.set(point.agentId, next);
116
128
  else current.delete(point.agentId);
@@ -120,6 +132,13 @@ async function modelUsage(directory: string, peers: { agentId: string; label: st
120
132
  dispatched: attempts.length, attemptsWithUsage, attemptsWithoutUsage: attempts.length - attemptsWithUsage,
121
133
  inputTokens: attemptsWithUsage ? inputTokens : null, outputTokens: attemptsWithUsage ? outputTokens : null,
122
134
  peers: [...summarized.values()], peakConcurrentPeers,
135
+ upstreamModels: Object.fromEntries(upstreamModels),
136
+ requestsWithoutUpstreamModel: [...summarized.values()].reduce((sum, peer) => sum + peer.succeeded, 0) -
137
+ [...upstreamModels.values()].reduce((sum, count) => sum + count, 0),
138
+ peerOverlapMs: requestIntervals.reduce<Record<string, number>>((summary, { from, to, peers }) => {
139
+ summary[peers] = (summary[peers] ?? 0) + to - from;
140
+ return summary;
141
+ }, {}),
123
142
  };
124
143
  }
125
144
 
@@ -131,6 +150,7 @@ export default {
131
150
  async run(context: HarnessContext) {
132
151
  const config = configuration(context.configuration);
133
152
  const { budget } = config;
153
+ await config.validateStarter?.(context.initial);
134
154
  if (config.requiredFiles?.some(path => !Object.hasOwn(context.initial.files, path))) {
135
155
  throw new ProjectPreflightError('AUTORESEARCH_STARTER_INCOMPLETE', 'Project capture missed required starter files. Verify the prepared Git checkout and retry.');
136
156
  }
@@ -141,6 +161,11 @@ export default {
141
161
  : Promise.resolve('complete' as const);
142
162
  const registry = new ServiceRegistry();
143
163
  let deadlineAt = 0;
164
+ let workStartedAt: number | null = null;
165
+ let workEndedAt: number | null = null;
166
+ const startingAt = Date.now();
167
+ let runtimeAttempted = false;
168
+ let initFailure: { runtimeId?: string; reportPath?: string; cleanup?: CloseReceipt['cleanup']; details?: JsonValue } | undefined;
144
169
  let runtime: Runtime;
145
170
  const peerLabels = Array.from({ length: budget.workers }, (_, index) => `peer-${index + 1}`);
146
171
  const profile: Profile = { model: 'research', image: config.image, writable: true, services: { research: researchOperations }, addedSystemPrompt: instructions, ...(config.restrictNetwork ? { network: { allow: [] } } : {}) };
@@ -166,7 +191,7 @@ export default {
166
191
  }
167
192
  }
168
193
  const research = createResearch({
169
- outputDir: context.outputDir, direction: config.direction, maxEvaluations: budget.maxEvaluations, targetScore: config.targetScore,
194
+ get outputDir() { return join(context.outputDir, runtime.id); }, direction: config.direction, maxEvaluations: budget.maxEvaluations, targetScore: config.targetScore,
170
195
  get deadlineAt() { return deadlineAt; }, signal, trainSignal: context.signal, evaluator: config.evaluator, evaluationTimeoutMs: config.evaluationTimeoutMs ?? 190_000,
171
196
  stopWork: reason => controller.abort(reason),
172
197
  statusChanged: () => {
@@ -208,6 +233,9 @@ export default {
208
233
  let final: JsonValue | null = null;
209
234
  let judgeCleanup: 'complete' | 'pending' = 'complete';
210
235
  let error: string | null = null;
236
+ let finalStartedAt: number | null = null;
237
+ let finalEndedAt: number | null = null;
238
+ let cleanupStartedAt: number | null = null;
211
239
  let searchEnd = 'workers-settled';
212
240
  let selected: ReturnType<typeof research.selection>;
213
241
  try {
@@ -215,8 +243,7 @@ export default {
215
243
  const startSignal = AbortSignal.any([context.signal, AbortSignal.timeout(360_000)]);
216
244
  await withDeadline(startSignal, () => config.evaluator.start!(context.outputDir, startSignal));
217
245
  }
218
- deadlineAt = Date.now() + budget.workMs;
219
- deadline = setTimeout(() => controller.abort('work-deadline'), budget.workMs);
246
+ runtimeAttempted = true;
220
247
  runtime = await createRuntime({
221
248
  sandbox: createSandbox(config.sandbox), connection: { ...config.connection, modelGateway: {
222
249
  ...config.connection.modelGateway,
@@ -280,7 +307,6 @@ export default {
280
307
  : { status: 'unknown', requestId: request.requestId };
281
308
  },
282
309
  });
283
- context.emit({ kind: 'trace.request', runDirectory: context.outputDir });
284
310
  status = 'spawning peers';
285
311
  research.event('run.start');
286
312
  const setup = await Promise.allSettled(peerLabels.map(async label => {
@@ -298,6 +324,9 @@ export default {
298
324
  }
299
325
  signal.throwIfAborted();
300
326
  status = 'researching';
327
+ workStartedAt = Date.now();
328
+ deadlineAt = workStartedAt + budget.workMs;
329
+ deadline = setTimeout(() => controller.abort('work-deadline'), budget.workMs);
301
330
  context.markRunning();
302
331
  research.event('team.ready');
303
332
  await Promise.all(peers.map(async ({ peer, label, member }) => {
@@ -313,10 +342,14 @@ export default {
313
342
  const remaining = deadlineAt - Date.now();
314
343
  if (remaining <= 0) break;
315
344
  const review = member.reviewOfferedInTurn ? undefined : member.review;
316
- if (turn > 0 && !review && research.state().budget.evaluations >= budget.maxEvaluations) break;
345
+ const trainExhausted = research.state().budget.evaluations >= budget.maxEvaluations;
346
+ if (turn > 0 && !review && trainExhausted && !config.continueAfterTrainBudget) break;
347
+ const remainingWork = trainExhausted
348
+ ? 'Train capacity is exhausted. Review another peer’s candidate, run local checks and publish concrete findings.'
349
+ : 'Check updates, review or build on promising peers’ work, and propose the next evidence-backed improvement.';
317
350
  const prompt = turn === 0
318
351
  ? `You are ${label}. Team objective: ${config.goal}\n${context.input.prompt}\nRead the project task statement and the board, claim an open direction and work toward a first testable patch promptly.`
319
- : 'Check updates, review or build on promising peers’ work, and propose the next evidence-backed improvement.';
352
+ : remainingWork;
320
353
  const interrupting = new Error('Peer interrupt pending before dispatch.');
321
354
  try {
322
355
  await runInput(runtime, peer.id, review ? `${prompt}\n\n${reviewNotice(review)}` : prompt, {
@@ -335,8 +368,15 @@ export default {
335
368
  if (!peerSignal.aborted) research.event('peer.turn-ended', { agentId: peer.id, detail: (error as Error).message.slice(0, 250) });
336
369
  }
337
370
  }));
371
+ workEndedAt = Date.now();
338
372
  searchEnd = research.stopReason() ?? (context.signal.aborted ? 'stopped' : controller.signal.aborted ? 'deadline' :
339
- research.state().budget.evaluations >= budget.maxEvaluations ? 'evaluation-budget' : 'workers-settled');
373
+ !config.continueAfterTrainBudget && research.state().budget.evaluations >= budget.maxEvaluations ? 'evaluation-budget' : 'workers-settled');
374
+ if (searchEnd === 'workers-settled' && budget.maxModelRequests !== undefined) {
375
+ const attempts = await readdir(join(context.outputDir, runtime.id, 'model-trace')).catch(() => []);
376
+ if (attempts.length >= budget.maxModelRequests) searchEnd = 'model-request-budget';
377
+ }
378
+ if (!controller.signal.aborted) controller.abort(searchEnd);
379
+ research.event('research.stopped', { detail: searchEnd });
340
380
  // The host owns the judge independently of the Runtime. Stop native work
341
381
  // while the last admitted train call settles under its own deadline.
342
382
  [close] = await Promise.all([
@@ -351,14 +391,29 @@ export default {
351
391
  selected = research.selection();
352
392
  if (selected && !context.signal.aborted) {
353
393
  status = 'final evaluation';
394
+ finalStartedAt = Date.now();
354
395
  research.event('final.selected', { agentId: selected.agentId, candidate: selected.id });
355
396
  const finalSignal = AbortSignal.any([context.signal, AbortSignal.timeout(config.closeTimeoutMs ?? 240_000)]);
356
397
  final = await withDeadline(finalSignal, () => config.evaluator.final(research.patch(selected!), finalSignal));
357
- research.event('final.returned', { agentId: selected.agentId, candidate: selected.id });
398
+ finalEndedAt = Date.now();
399
+ const verdict = readFinalEvaluation(final);
400
+ const evidence = verdict?.evidence as { payload?: { digest?: string }; summary?: string } | undefined;
401
+ research.event('final.returned', { agentId: selected.agentId, candidate: selected.id,
402
+ score: verdict?.score, payloadDigest: evidence?.payload?.digest,
403
+ detail: evidence?.summary ?? verdict?.status ?? 'unverified evaluator result' });
358
404
  }
359
405
  } catch (failure) {
360
- error = (failure as Error).message?.slice(0, 500) ?? 'Research failed';
406
+ error = failure instanceof Error ? failure.message.slice(0, 500) : 'Research failed';
407
+ if (!runtime! && runtimeAttempted && failure instanceof Error && failure.name === 'ResourceError') {
408
+ initFailure = failure as typeof initFailure;
409
+ }
410
+ if (runtime!) research.event(finalStartedAt === null ? 'run.failed' : 'final.failed', {
411
+ ...(selected ? { agentId: selected.agentId, candidate: selected.id } : {}), detail: error,
412
+ });
361
413
  } finally {
414
+ cleanupStartedAt = Date.now();
415
+ workEndedAt ??= workStartedAt === null ? null : cleanupStartedAt;
416
+ finalEndedAt ??= finalStartedAt === null ? null : cleanupStartedAt;
362
417
  clearTimeout(deadline);
363
418
  controller.abort('closing');
364
419
  research.close();
@@ -369,29 +424,50 @@ export default {
369
424
  }
370
425
  observation?.close();
371
426
  judgeCleanup = await cleanupJudge();
427
+ if (runtime!) research.event('run.cleanup', {
428
+ detail: `Runtime ${close?.cleanup ?? 'pending'}; evaluator ${judgeCleanup}`,
429
+ });
372
430
  }
373
431
  const best = research.best();
374
432
  const peers = research.state().peers;
375
433
  const traceDirectory = runtime! ? join(context.outputDir, runtime.id) : null;
376
- const runtimeReport = close?.reportPath ? await readFile(close.reportPath, 'utf8').then(text => JSON.parse(text)).catch(() => null) : null;
434
+ const runtimeReceipt = close?.reportPath ?? initFailure?.reportPath ?? null;
435
+ const runtimeReport = runtimeReceipt ? await readFile(runtimeReceipt, 'utf8').then(text => JSON.parse(text)).catch(() => null) : null;
436
+ const usage = traceDirectory ? await modelUsage(traceDirectory, peers) : null;
437
+ const finalEvaluation = readFinalEvaluation(final);
438
+ const accepted = finalEvaluation?.status === 'valid' && finalEvaluation.meetsObjective !== false;
439
+ const reason = context.signal.aborted ? 'stopped'
440
+ : error ? searchEnd === 'train-outcome-unknown' ? searchEnd : finalStartedAt === null ? 'research-error' : 'final-error'
441
+ : !best ? 'no-valid-candidate'
442
+ : journalError ? 'trace-write-failed'
443
+ : !finalEvaluation || finalEvaluation.status === 'unknown' ? 'final-unconfirmed'
444
+ : finalEvaluation.status === 'rejected' ? 'final-rejected'
445
+ : !accepted ? 'objective-unmet'
446
+ : searchEnd;
447
+ const runtimeCleanup = close?.cleanup ?? initFailure?.cleanup ?? (runtimeAttempted ? 'pending' : 'complete');
448
+ const record = join(context.outputDir, 'research-result.json');
377
449
  const result = {
378
- runtimeId: runtime!?.id ?? null, budget, searchEnd,
379
- model: { provider: config.model.provider, id: config.model.model, usage: traceDirectory ? await modelUsage(traceDirectory, peers) : null, trace: runtimeReport?.modelTrace ?? null, cost: 'unknown' },
380
- peers,
381
- candidates: research.candidates(), best: best ?? null, selected: selected ?? null, final, journalError, error,
382
- record: join(context.outputDir, 'research-result.json'), judge: config.evaluator.evidence?.() ?? null,
383
- traceDirectory,
384
- cleanup: { runtime: close?.cleanup ?? 'pending', judge: judgeCleanup },
450
+ schemaVersion: 1, runId: context.runId, runtimeId: runtime!?.id ?? initFailure?.runtimeId ?? null, goal: config.goal, budget, searchEnd,
451
+ timing: { startingAt, workStartedAt, workEndedAt, finalStartedAt, finalEndedAt, cleanupStartedAt, completedAt: Date.now() },
452
+ executor: typeof config.executor === 'string' ? config.executor : config.executor.kind,
453
+ initial: { digest: context.initial.digest, files: context.initial.fileCount },
454
+ model: { provider: config.model.provider, id: config.model.model, usage, trace: runtimeReport?.modelTrace ?? null, cost: 'unknown' },
455
+ peers, candidates: research.candidates(), best: best ?? null, selected: selected ?? null, final, finalEvaluation: finalEvaluation ?? null, journalError, error,
456
+ record, judge: config.evaluator.evidence?.() ?? null, traceDirectory,
457
+ cleanup: { runtime: runtimeCleanup, judge: judgeCleanup, runtimePending: close?.pending ?? runtimeReport?.pending ?? [],
458
+ runtimeReceipt, runtimeInitializationDetails: initFailure?.details ?? null },
385
459
  };
386
460
  await mkdir(context.outputDir, { recursive: true, mode: 0o700 });
387
- await writeFile(result.record, JSON.stringify(result, null, 2) + '\n', { mode: 0o600 });
461
+ await writeFile(record + '.next', JSON.stringify(result, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
462
+ await rename(record + '.next', record);
463
+ const outcome = context.signal.aborted ? 'cancelled' : error || !best || !accepted || journalError ? 'failed' : 'completed';
388
464
  return {
389
- outcome: context.signal.aborted ? 'cancelled' : error || !best || final === null || journalError ? 'failed' : 'completed',
390
- reason: error ? 'research-error' : !best ? 'no-valid-candidate' : journalError ? 'trace-write-failed' : searchEnd,
391
- result: encode(result),
392
- acceptance: encode({ status: best && final !== null && !error ? 'verified' : 'unverified', final }),
393
- artifacts: [...(selected ? [{ path: selected.path, sha256: selected.sha256 }] : []), { path: result.record } as HarnessJson],
394
- cleanup: { status: close?.cleanup === 'complete' && judgeCleanup === 'complete' ? 'complete' : 'pending', ...(close?.pending.length ? { pending: encode(close.pending) } : {}) },
465
+ outcome, reason, result: encode(result),
466
+ acceptance: encode({ status: outcome === 'completed' ? 'verified' : finalEvaluation?.status === 'rejected' || finalEvaluation?.meetsObjective === false
467
+ ? 'rejected' : 'unverified', final: finalEvaluation ?? null }),
468
+ artifacts: [...research.candidates().map(candidate => ({ path: candidate.path, sha256: candidate.sha256 })), { path: record }],
469
+ cleanup: { status: runtimeCleanup === 'complete' && judgeCleanup === 'complete' ? 'complete' : 'pending',
470
+ ...(close?.pending.length ? { pending: encode(close.pending) } : {}) },
395
471
  };
396
472
  },
397
473
  } satisfies Harness;
@@ -1,18 +1,35 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { appendFileSync } from 'node:fs';
3
- import { mkdir, writeFile } from 'node:fs/promises';
3
+ import { mkdir, unlink, writeFile } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { inProcessService, type JsonValue, type Runtime, type ServiceInterface } from '@anyswarm/core';
6
6
 
7
7
  export const candidatePath = '.anyswarm-candidate.patch';
8
8
  const maxPatch = 1024 * 1024 - 1536;
9
9
  const patchChunk = 24 * 1024;
10
- const maxNotes = 512;
10
+ const maxMutations = 16_384;
11
11
 
12
12
  export interface Evaluation {
13
13
  valid: boolean;
14
14
  score: number | null;
15
15
  feedback: JsonValue;
16
+ payload?: { digest: string; size: number };
17
+ }
18
+
19
+ export type FinalEvaluation = {
20
+ status: 'valid' | 'rejected' | 'unknown';
21
+ score: number | null;
22
+ meetsObjective: boolean | null;
23
+ evidence: JsonValue;
24
+ };
25
+
26
+ export function readFinalEvaluation(value: JsonValue): FinalEvaluation | undefined {
27
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
28
+ !['valid', 'rejected', 'unknown'].includes(value.status as string) ||
29
+ (value.score !== null && (typeof value.score !== 'number' || !Number.isFinite(value.score))) ||
30
+ (value.meetsObjective !== null && typeof value.meetsObjective !== 'boolean') ||
31
+ value.evidence === undefined) return undefined;
32
+ return value as FinalEvaluation;
16
33
  }
17
34
 
18
35
  export interface Evaluator {
@@ -20,7 +37,7 @@ export interface Evaluator {
20
37
  close?(): Promise<'complete' | 'pending'>;
21
38
  evidence?(): JsonValue;
22
39
  train(candidate: Buffer, signal: AbortSignal, admitted: (reference: string | number) => void): Promise<Evaluation>;
23
- final(candidate: Buffer, signal: AbortSignal): Promise<JsonValue>;
40
+ final(candidate: Buffer, signal: AbortSignal): Promise<FinalEvaluation | JsonValue>;
24
41
  }
25
42
 
26
43
  export interface Candidate {
@@ -50,6 +67,8 @@ interface ResearchEvent {
50
67
  basedOnSha256?: string;
51
68
  score?: number | null;
52
69
  officialJob?: string | number;
70
+ payloadDigest?: string;
71
+ bytes?: number;
53
72
  label?: string;
54
73
  }
55
74
 
@@ -105,19 +124,41 @@ export function createResearch(options: {
105
124
  const claims = new Map<string, string>();
106
125
  let best: Candidate | undefined;
107
126
  let reserved = 0;
127
+ let nextCandidate = 0;
128
+ let storing = Promise.resolve();
129
+ const mutations = new Map<string, { fingerprint: string; receipt: Promise<JsonValue> }>();
108
130
  let closed = false;
109
131
  let stopReason: string | undefined;
110
132
  let queue = Promise.resolve();
111
133
  const project = (record: unknown) => record as JsonValue;
112
134
  const reached = (score: number, target: number) => options.direction === 'max' ? score >= target : score <= target;
113
135
  function event(operation: string, data: Omit<ResearchEvent, 'operation' | 'seq' | 'at' | 'type'> = {}) {
114
- const entry = { ...data, seq: events.length + 1, at: new Date().toISOString(), type: 'research' as const, operation };
136
+ const candidate = data.candidate && candidates.get(data.candidate);
137
+ const entry = { ...(candidate ? { sha256: candidate.sha256 } : {}), ...data, seq: events.length + 1, at: new Date().toISOString(), type: 'research' as const, operation };
115
138
  events.push(entry);
116
139
  options.traceEvent(entry);
117
140
  options.statusChanged();
118
141
  }
119
142
  function admit() {
120
- if (closed || stopReason || options.signal.aborted || events.length >= maxNotes) throw new Error('Research admissions are closed');
143
+ if (closed || stopReason || options.signal.aborted) throw new Error('Research admissions are closed');
144
+ }
145
+ type Handler = Parameters<typeof inProcessService>[1][string];
146
+ function mutation(operation: string, handler: Handler): Handler {
147
+ return (input, context) => {
148
+ context.assertAuthorized();
149
+ const key = JSON.stringify([context.caller.agentId, context.envelope.operation_id]);
150
+ const payload = input as Record<string, JsonValue>;
151
+ const fingerprint = JSON.stringify([operation, Object.entries(payload).sort(([left], [right]) => left.localeCompare(right))]);
152
+ const entry = mutations.get(key);
153
+ if (entry) {
154
+ if (entry.fingerprint !== fingerprint) throw new Error('Operation ID already identifies a different research action');
155
+ return entry.receipt;
156
+ }
157
+ if (mutations.size >= maxMutations) throw new Error('Research mutation receipt limit reached');
158
+ const receipt = Promise.resolve().then(() => handler(input, context));
159
+ mutations.set(key, { fingerprint, receipt });
160
+ return receipt;
161
+ };
121
162
  }
122
163
  function state() {
123
164
  return {
@@ -148,7 +189,8 @@ export function createResearch(options: {
148
189
  }));
149
190
  candidate.evaluation = evaluation;
150
191
  candidate.state = validScore(evaluation) ? 'scored' : 'invalid';
151
- event('train.returned', { agentId: candidate.agentId, candidate: candidate.id, score: evaluation.score });
192
+ event('train.returned', { agentId: candidate.agentId, candidate: candidate.id, score: evaluation.score,
193
+ officialJob: candidate.officialJob, payloadDigest: evaluation.payload?.digest });
152
194
  if (validScore(evaluation) && (!best || (evaluation.score !== best.evaluation!.score && reached(evaluation.score!, best.evaluation!.score!)))) {
153
195
  best = candidate;
154
196
  event('candidate.best', { agentId: candidate.agentId, candidate: candidate.id, score: evaluation.score });
@@ -173,7 +215,7 @@ export function createResearch(options: {
173
215
  candidates: [...candidates.values()].slice(-8).map(({ path: _, ...candidate }) => candidate),
174
216
  });
175
217
  },
176
- claim: (input, { caller, assertAuthorized }) => {
218
+ claim: mutation('claim', (input, { caller, assertAuthorized }) => {
177
219
  assertAuthorized();
178
220
  admit();
179
221
  const direction = (input as { direction: string }).direction.trim();
@@ -184,8 +226,8 @@ export function createResearch(options: {
184
226
  claims.set(key, caller.agentId);
185
227
  event('peer.claim', { agentId: caller.agentId, detail: direction });
186
228
  return { claimed: true, agentId: caller.agentId };
187
- },
188
- publish: (input, { caller, assertAuthorized }) => {
229
+ }),
230
+ publish: mutation('publish', (input, { caller, assertAuthorized }) => {
189
231
  assertAuthorized();
190
232
  admit();
191
233
  const { kind, summary, candidate } = input as { kind: 'finding' | 'review'; summary: string; candidate?: string };
@@ -197,15 +239,15 @@ export function createResearch(options: {
197
239
  event(`peer.${kind}`, { agentId: caller.agentId, detail: summary,
198
240
  ...(reviewed ? { candidate: reviewed.id, sha256: reviewed.sha256 } : {}) });
199
241
  return { published: true };
200
- },
201
- message: (input, { caller, assertAuthorized }) => {
242
+ }),
243
+ message: mutation('message', (input, { caller, assertAuthorized }) => {
202
244
  assertAuthorized();
203
245
  admit();
204
246
  const { peer, summary } = input as { peer: string; summary: string };
205
247
  if (peer === caller.agentId || !peers.has(peer)) throw new Error('Peer does not belong to this Run');
206
248
  event('peer.message', { agentId: caller.agentId, to: peer, detail: summary });
207
249
  return { sent: true };
208
- },
250
+ }),
209
251
  read_patch: (input, { caller, assertAuthorized }) => {
210
252
  assertAuthorized();
211
253
  admit();
@@ -225,42 +267,50 @@ export function createResearch(options: {
225
267
  }
226
268
  return { candidate, sha256, data: bytes.subarray(start, end).toString('base64'), nextOffset: end < bytes.length ? end : null };
227
269
  },
228
- submit: async (input, { caller, envelope, assertAuthorized }) => {
270
+ submit: mutation('submit', async (input, { caller, envelope, assertAuthorized }) => {
229
271
  assertAuthorized();
230
272
  admit();
231
273
  const { summary, basedOn } = input as { summary: string; basedOn?: string };
232
- if (basedOn && !readEntirePatch(caller.agentId, basedOn)) throw new Error('Read the referenced candidate before building on it');
274
+ const parent = basedOn ? candidates.get(basedOn) : undefined;
275
+ if (basedOn && (!parent || parent.agentId === caller.agentId || !readEntirePatch(caller.agentId, basedOn))) {
276
+ throw new Error('Read the referenced peer candidate before building on it');
277
+ }
233
278
  const bytes = await options.readPatch(caller.agentId, envelope.operation_id);
234
- assertAuthorized();
235
- admit();
236
279
  if (!bytes.length || bytes.length > maxPatch) throw new Error('Candidate patch is empty or exceeds the size limit');
237
280
  const sha256 = createHash('sha256').update(bytes).digest('hex');
238
- const previous = known.get(sha256);
239
- if (previous) return { candidate: previous.id, status: previous.state, duplicate: true, sha256 };
240
- if (reserved >= options.maxEvaluations) throw new Error('Shared evaluation budget is exhausted');
241
- reserved++;
242
- const id = `candidate-${reserved}`;
243
- const path = join(options.outputDir, 'candidates', `${id}.patch`);
244
- const candidate: Candidate = { id, agentId: caller.agentId, summary, basedOn: basedOn ?? null, path,
245
- sha256, bytes: bytes.length, state: 'queued' };
246
- known.set(sha256, candidate);
247
- try {
248
- await mkdir(join(options.outputDir, 'candidates'), { recursive: true, mode: 0o700 });
249
- await writeFile(path, bytes, { mode: 0o600, flag: 'wx' });
281
+ // Serialize the host file commit and quota admission, once the private
282
+ // workspace snapshot is available. No duplicate can observe a half write.
283
+ const result = storing.then(async () => {
250
284
  assertAuthorized();
251
285
  admit();
252
- } catch (error) {
253
- candidate.state = 'cancelled';
286
+ const previous = known.get(sha256);
287
+ if (previous) return { candidate: previous.id, status: previous.state, duplicate: true, sha256 };
288
+ if (reserved >= options.maxEvaluations) throw new Error('Shared evaluation budget is exhausted');
289
+ const id = `candidate-${++nextCandidate}`;
290
+ const path = join(options.outputDir, 'candidates', `${id}.patch`);
291
+ const candidate: Candidate = { id, agentId: caller.agentId, summary, basedOn: basedOn ?? null, path,
292
+ sha256, bytes: bytes.length, state: 'queued' };
293
+ await mkdir(join(options.outputDir, 'candidates'), { recursive: true, mode: 0o700 });
294
+ await writeFile(path, bytes, { mode: 0o600, flag: 'wx' });
295
+ try {
296
+ assertAuthorized();
297
+ admit();
298
+ } catch (error) {
299
+ await unlink(path);
300
+ throw error;
301
+ }
302
+ reserved++;
303
+ known.set(sha256, candidate);
304
+ patches.set(id, bytes);
254
305
  candidates.set(id, candidate);
255
- throw error;
256
- }
257
- patches.set(id, bytes);
258
- candidates.set(id, candidate);
259
- event(basedOn ? 'candidate.built-on' : 'candidate.queued', { agentId: caller.agentId, candidate: id, sha256, detail: summary,
260
- ...(basedOn ? { basedOn, basedOnSha256: candidates.get(basedOn)!.sha256 } : {}) });
261
- queue = queue.then(() => evaluate(candidate, bytes));
262
- return { candidate: id, status: candidate.state, duplicate: false, sha256 };
263
- },
306
+ event(parent ? 'candidate.built-on' : 'candidate.queued', { agentId: caller.agentId, candidate: id, sha256, bytes: bytes.length, detail: summary,
307
+ ...(parent ? { basedOn, basedOnSha256: parent.sha256 } : {}) });
308
+ queue = queue.then(() => evaluate(candidate, bytes));
309
+ return { candidate: id, status: 'queued', duplicate: false, sha256 };
310
+ });
311
+ storing = result.then(() => {}, () => {});
312
+ return result;
313
+ }),
264
314
  }, {
265
315
  readState: () => ({
266
316
  state: project(state()), capturedAt: new Date().toISOString(), revision: String(events.length),
@@ -277,10 +327,10 @@ export function createResearch(options: {
277
327
  addPeer: (id: string, label: string) => { peers.set(id, label); event('peer.ready', { agentId: id, label }); },
278
328
  close: () => { closed = true; },
279
329
  stopReason: () => stopReason,
280
- drained: () => queue,
330
+ drained: async () => { await storing; await queue; },
281
331
  best: () => best,
282
332
  peerLabel: (agentId: string) => peers.get(agentId),
283
- selection: () => best ?? [...candidates.values()].find(candidate => candidate.state === 'invalid'),
333
+ selection: () => best,
284
334
  patch: (candidate: Candidate) => Buffer.from(patches.get(candidate.id)!),
285
335
  candidates: () => [...candidates.values()],
286
336
  };
@@ -1,25 +1,33 @@
1
- # Code quickstart
1
+ # Code SDK example
2
2
 
3
- Prepare an OpenSandbox connection, a Pi or Codex Worker, and a model route using AnySwarm's CLI quickstart. On the Linux host that holds your project, open its directory and run:
3
+ Code runs a coding Agent in a writable Sandbox, verifies a candidate on the Linux
4
+ host and applies authorized edits to the project. Ask the lead Agent to delegate
5
+ a separable task when you want an editor to work in parallel. Between turns,
6
+ Code reconciles edits made by the user and returns conflicting paths for review.
4
7
 
5
- ```sh
6
- anys -u code
7
- anys -u code "Add a test for the empty-input case"
8
- ```
9
-
10
- You can also start `anys` and enter `/code`. Enter sends, Alt+Enter adds a line, Ctrl+C interrupts the current task, and `/quit` closes the team. `/diff` prints the latest completed turn's paths, patch preview and full patch location into the conversation. Use `/agents` for the member roster, `@<editor> <message>` to steer an active editor, and `/stop <editor>` to stop that editor. Answer inline verification confirmations with `/y` or `/n`, and editor questions with `/reply <id> <answer>`. Use `/config` and `/doctor` for setup information and `/trace` for Trace Viewer.
11
-
12
- The main Agent edits and tests a copy of your current project in one writable Sandbox. Follow-up requests reuse its conversation. AnySwarm reconciles your files before each turn, including edits you made between turns. To delegate, write a request such as “Ask a subagent to write the regression test while you fix the implementation.” The main Agent can continue while the child works in a separate Sandbox, then collect and review the result. The host checks the integrated changes before writeback. If an edit conflicts with yours, resolve the reported path before retrying.
13
-
14
- The default configuration reads `ANYSWARM_MODEL_URL`, optional `ANYSWARM_MODEL_TOKEN`, `ANYSWARM_MODEL_ID` and `ANYSWARM_MODEL_PROVIDER`. Code-specific `ANYSWARM_CODE_*` equivalents take precedence. Use `anys -u code --config ./trusted.ts` for an explicit model/Sandbox configuration. The application can ask before running a detected `npm test` or `make test`. Set `check` to an argv array in a trusted config to authorize it for each candidate, or set `check: false` to skip verification. Checks run locally with your permissions in a temporary copy. Code copies a supported existing Node dependency installation into that copy. Install the project's dependencies first if the checker reports an unavailable environment. A failed verification leaves the original project files in place. After a successful task, `/quit` returns 0 when cleanup completes and keeps the report location visible.
15
-
16
- To edit the application itself:
8
+ Prepare OpenSandbox, a supported Pi or Codex Worker and a model route. Export the
9
+ source outside the target project and install its pinned SDK.
17
10
 
18
11
  ```sh
19
- anys eject code --dir ./my-code
12
+ anyswarm eject code --dir ./my-code
20
13
  cd ./my-code
21
14
  npm install
22
- anys run ./project.ts --mode tui --lifetime interactive --cwd /path/to/project
15
+ npm run start -- --cwd /path/to/project --config ./trusted.ts --prompt "Add a test for empty input" --output-dir ./runs
16
+ anyswarm trace --root ./runs
23
17
  ```
24
18
 
25
- The exported package uses the SDK bytes from the installed AnySwarm package. Edit `prompts.ts` or `project.ts` and run the same command again to use your version. Keep the exported source outside the project directory if you do not want its files in the project scope.
19
+ The default configuration reads `ANYSWARM_MODEL_URL`, optional
20
+ `ANYSWARM_MODEL_TOKEN`, `ANYSWARM_MODEL_ID` and `ANYSWARM_MODEL_PROVIDER`.
21
+ Code-specific `ANYSWARM_CODE_*` values take precedence. The example command uses
22
+ an explicit trusted config. Set `check` to an argv array to authorize
23
+ verification, or set `check: false` to skip it. Checks run with the host user's
24
+ permissions in a temporary copy and can reuse a supported Node dependency
25
+ installation. A failed check or writeback conflict retains the original files.
26
+ The Run report includes verification, changed paths and the retained diff.
27
+
28
+ For follow-up turns and questions, import the Harness in an application and
29
+ drive it through `createHarnessSession`, or connect to
30
+ `npm run start -- --mode rpc --lifetime interactive --interaction questions`
31
+ with `HarnessRpcClient`. Send the target directory in the RPC `run` input.
32
+ See [HarnessSession clients](../harness-session/README.md) for the protocol and
33
+ [Code architecture](../../docs/architecture/26-code.md) for writeback rules.
@@ -1,11 +1,11 @@
1
1
  # Code 用户需求
2
2
 
3
- 适用范围见 [#336](https://github.com/AnySwarm/anyswarm/issues/336)。用户在自己的项目目录运行 `anys -u code [任务]`,也可以打开 `anys` 后输入 `/code`。共享界面显示项目、执行器和模型。用户可以回答内联问题、用 `/diff` 查看最近一轮的改动,或继续输入。退出时提供清理结果。
3
+ 适用范围见 [#336](https://github.com/AnySwarm/anyswarm/issues/336)。[#351](https://github.com/AnySwarm/anyswarm/issues/351) 将 Code 保留为进阶 SDK 示例。单次运行接收任务和显式配置,多轮输入、问答、差异和成员控制由 SDK 或 RPC 客户端处理。
4
4
 
5
5
  - 一个会话由一个 Runtime 管理。主 Agent 默认在一个可写的隔离工作区读项目、改代码并运行检查。用户可以在聊天中要求委派,主 Agent 可以和独立子 Agent 同时工作,收取结果并审查。用户可针对任意活跃成员发消息、中断或停止。
6
6
  - 每轮以用户当前目录的内容为起点,包含已跟踪文件的未提交修改和未忽略的新文件。宿主比较主 Agent、已收取的子 Agent 结果和实时工作树,合并后按任务授权写回。用户改动冲突时显示路径并保留原文件。
7
7
  - 用户可见改动文件和实际 diff。宿主监督配置或用户确认的检查,并展示命令、退出码和状态。Node 检查可复用受支持的现有依赖安装,缺失时显示校验环境问题。无命令时显示未验证。校验失败时保留原项目文件。
8
- - `Ctrl+C` 请求中断当前轮,之后可以继续输入。`/quit` 等待资源清理。空闲时在成功任务后退出,清理确认后返回 0。会话收尾保留报告、检查结果、已写入的路径和 Trace。
9
- - `anys eject code` 导出完整 TS 应用。作者能在仓库外直接运行、修改并重新执行其副本。
8
+ - 多轮客户端可以请求中断当前轮,之后继续输入,也可停止整个会话并等待清理。单次运行在任务完成、清理确认后返回 0。会话收尾保留报告、检查结果、已写入的路径和 Trace。
9
+ - `anyswarm eject code` 导出完整 TS 应用。作者能在仓库外直接运行、修改并重新执行其副本。
10
10
 
11
11
  验收使用同一个仓库外安装的候选包。用真实项目覆盖默认单 Agent 两轮编辑、用户明确要求并行委派、中断后继续、验证失败、并行成员控制、退出清理和导出源码。记录每轮文件上传下载字节数、实际容器数、峰值内存和最终检查结果。ProgramBench 使用同一 Code 应用,运行状态和官方评分单独记录。