@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,11 +1,11 @@
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 } from '@anyswarm/core';
5
- import { checkBudget, demoGoal } from './config.js';
6
- import { frontierDemo } from './demo.js';
7
- import { prepareFrontier } from './prepare.js';
8
- import { appendResearchEvent, candidatePath, createResearch, researchOperations, withDeadline } from './research-service.js';
7
+ import { checkBudget, modelConfigurationError } from './config.js';
8
+ import { appendResearchEvent, candidatePath, createResearch, readFinalEvaluation, researchOperations, withDeadline } from './research-service.js';
9
9
  const instructions = `You are one of several equal research peers exploring the same goal. Choose your own concrete direction and coordinate directly with peers.
10
10
  Use the following CLI directly in your private project. The host already provides this Service.
11
11
  swarm service invoke research board
@@ -35,34 +35,22 @@ function configuration(value) {
35
35
  !config.evaluator || typeof config.evaluator.train !== 'function' || typeof config.evaluator.final !== 'function' ||
36
36
  !config.executor || !config.image || !config.model || !config.sandbox || !config.connection ||
37
37
  (config.targetScore !== undefined && !Number.isFinite(config.targetScore))) {
38
- 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.');
38
+ throw new ProjectPreflightError('AUTORESEARCH_CONFIG_REQUIRED', 'Run anyswarm --harness autoresearch --config ./research.ts --prompt <goal> with a trusted evaluator and runtime settings.');
39
39
  }
40
40
  for (const ms of [config.evaluationTimeoutMs, config.closeTimeoutMs]) {
41
41
  if (ms !== undefined && (!Number.isSafeInteger(ms) || ms < 1 || ms > 2_147_483_647)) {
42
42
  throw new ProjectPreflightError('AUTORESEARCH_CONFIG_INVALID', 'Evaluator timeouts must be positive millisecond values.');
43
43
  }
44
44
  }
45
+ const problem = modelConfigurationError(config.model, config.executor);
46
+ if (problem)
47
+ throw new ProjectPreflightError('AUTORESEARCH_MODEL_REQUIRED', problem);
45
48
  return { ...config, budget: checkBudget(config.budget) };
46
49
  }
47
50
  export function resolveWorkspace({ cwd, configuration }) {
48
51
  const target = configuration?.targetPath;
49
52
  return typeof target === 'string' && target.trim() ? resolve(cwd, target) : cwd;
50
53
  }
51
- export const slashActions = {
52
- async prepare({ args, signal, progress = console.error }) {
53
- if (args && args !== 'frontiercs2')
54
- throw new Error('Usage: /prepare [frontiercs2]');
55
- const result = await prepareFrontier({ signal, progress });
56
- return result.ok ? result : { kind: 'action-report', exitCode: 2, result };
57
- },
58
- async demo({ args, signal }) {
59
- if (args !== 'frontiercs2')
60
- throw new Error('Usage: /demo frontiercs2');
61
- const { configuration, starter } = await frontierDemo();
62
- signal.throwIfAborted();
63
- return { kind: 'start-run', cwd: starter, prompt: demoGoal, configuration };
64
- },
65
- };
66
54
  const streamedEvents = new Set([
67
55
  'peer.ready', 'peer.claim', 'peer.steer', 'peer.interrupt', 'peer.stop', 'peer.turn-ended', 'team.ready',
68
56
  'peer.review-notice', 'peer.read-patch', 'peer.review', 'candidate.queued', 'candidate.built-on', 'candidate.best', 'train.returned', 'train.unknown', 'final.selected', 'final.returned',
@@ -74,6 +62,8 @@ async function modelUsage(directory, peers) {
74
62
  let outputTokens = 0;
75
63
  let attemptsWithUsage = 0;
76
64
  const intervals = [];
65
+ const upstreamModels = new Map();
66
+ const requestIntervals = [];
77
67
  const summarized = new Map(peers.map(peer => [peer.agentId, { ...peer, dispatched: 0, succeeded: 0 }]));
78
68
  for (const id of attempts) {
79
69
  const attempt = (file) => readFile(join(trace, id, file), 'utf8').then(text => JSON.parse(text)).catch(() => null);
@@ -90,6 +80,29 @@ async function modelUsage(directory, peers) {
90
80
  if (result?.state !== 'completed' || result?.upstreamStatus !== 200)
91
81
  continue;
92
82
  peer.succeeded++;
83
+ const models = new Set();
84
+ const stream = createReadStream(join(trace, id, 'response.txt'));
85
+ try {
86
+ for await (const line of createInterface({ input: stream, crlfDelay: Infinity })) {
87
+ if (!line.startsWith('data:'))
88
+ continue;
89
+ try {
90
+ const event = JSON.parse(line.slice(5));
91
+ const model = event.type === 'response.completed' ? event.response?.model : event.model;
92
+ if (typeof model === 'string')
93
+ models.add(model.slice(0, 160));
94
+ }
95
+ catch { /* Incomplete or non-JSON SSE fields carry no model identity. */ }
96
+ }
97
+ }
98
+ catch { /* The gateway can record the attempt even if the upstream bytes are unavailable. */ }
99
+ finally {
100
+ stream.destroy();
101
+ }
102
+ if (models.size === 1) {
103
+ const model = [...models][0];
104
+ upstreamModels.set(model, (upstreamModels.get(model) ?? 0) + 1);
105
+ }
93
106
  const start = Date.parse(request.startedAt);
94
107
  const end = Date.parse(result.endedAt);
95
108
  if (start < end)
@@ -97,7 +110,12 @@ async function modelUsage(directory, peers) {
97
110
  }
98
111
  const current = new Map();
99
112
  let peakConcurrentPeers = 0;
113
+ let lastAt;
100
114
  for (const point of intervals.flatMap(({ agentId, start, end }) => [{ agentId, at: start, delta: 1 }, { agentId, at: end, delta: -1 }]).sort((a, b) => a.at - b.at || a.delta - b.delta)) {
115
+ if (lastAt !== undefined && lastAt < point.at && current.size > 1) {
116
+ requestIntervals.push({ from: lastAt, to: point.at, peers: current.size });
117
+ }
118
+ lastAt = point.at;
101
119
  const next = (current.get(point.agentId) ?? 0) + point.delta;
102
120
  if (next)
103
121
  current.set(point.agentId, next);
@@ -109,6 +127,13 @@ async function modelUsage(directory, peers) {
109
127
  dispatched: attempts.length, attemptsWithUsage, attemptsWithoutUsage: attempts.length - attemptsWithUsage,
110
128
  inputTokens: attemptsWithUsage ? inputTokens : null, outputTokens: attemptsWithUsage ? outputTokens : null,
111
129
  peers: [...summarized.values()], peakConcurrentPeers,
130
+ upstreamModels: Object.fromEntries(upstreamModels),
131
+ requestsWithoutUpstreamModel: [...summarized.values()].reduce((sum, peer) => sum + peer.succeeded, 0) -
132
+ [...upstreamModels.values()].reduce((sum, count) => sum + count, 0),
133
+ peerOverlapMs: requestIntervals.reduce((summary, { from, to, peers }) => {
134
+ summary[peers] = (summary[peers] ?? 0) + to - from;
135
+ return summary;
136
+ }, {}),
112
137
  };
113
138
  }
114
139
  const encode = (value) => JSON.parse(JSON.stringify(value));
@@ -118,6 +143,7 @@ export default {
118
143
  async run(context) {
119
144
  const config = configuration(context.configuration);
120
145
  const { budget } = config;
146
+ await config.validateStarter?.(context.initial);
121
147
  if (config.requiredFiles?.some(path => !Object.hasOwn(context.initial.files, path))) {
122
148
  throw new ProjectPreflightError('AUTORESEARCH_STARTER_INCOMPLETE', 'Project capture missed required starter files. Verify the prepared Git checkout and retry.');
123
149
  }
@@ -128,6 +154,11 @@ export default {
128
154
  : Promise.resolve('complete');
129
155
  const registry = new ServiceRegistry();
130
156
  let deadlineAt = 0;
157
+ let workStartedAt = null;
158
+ let workEndedAt = null;
159
+ const startingAt = Date.now();
160
+ let runtimeAttempted = false;
161
+ let initFailure;
131
162
  let runtime;
132
163
  const peerLabels = Array.from({ length: budget.workers }, (_, index) => `peer-${index + 1}`);
133
164
  const profile = { model: 'research', image: config.image, writable: true, services: { research: researchOperations }, addedSystemPrompt: instructions, ...(config.restrictNetwork ? { network: { allow: [] } } : {}) };
@@ -156,7 +187,7 @@ export default {
156
187
  }
157
188
  }
158
189
  const research = createResearch({
159
- outputDir: context.outputDir, direction: config.direction, maxEvaluations: budget.maxEvaluations, targetScore: config.targetScore,
190
+ get outputDir() { return join(context.outputDir, runtime.id); }, direction: config.direction, maxEvaluations: budget.maxEvaluations, targetScore: config.targetScore,
160
191
  get deadlineAt() { return deadlineAt; }, signal, trainSignal: context.signal, evaluator: config.evaluator, evaluationTimeoutMs: config.evaluationTimeoutMs ?? 190_000,
161
192
  stopWork: reason => controller.abort(reason),
162
193
  statusChanged: () => {
@@ -205,6 +236,9 @@ export default {
205
236
  let final = null;
206
237
  let judgeCleanup = 'complete';
207
238
  let error = null;
239
+ let finalStartedAt = null;
240
+ let finalEndedAt = null;
241
+ let cleanupStartedAt = null;
208
242
  let searchEnd = 'workers-settled';
209
243
  let selected;
210
244
  try {
@@ -212,8 +246,7 @@ export default {
212
246
  const startSignal = AbortSignal.any([context.signal, AbortSignal.timeout(360_000)]);
213
247
  await withDeadline(startSignal, () => config.evaluator.start(context.outputDir, startSignal));
214
248
  }
215
- deadlineAt = Date.now() + budget.workMs;
216
- deadline = setTimeout(() => controller.abort('work-deadline'), budget.workMs);
249
+ runtimeAttempted = true;
217
250
  runtime = await createRuntime({
218
251
  sandbox: createSandbox(config.sandbox), connection: { ...config.connection, modelGateway: {
219
252
  ...config.connection.modelGateway,
@@ -281,7 +314,6 @@ export default {
281
314
  : { status: 'unknown', requestId: request.requestId };
282
315
  },
283
316
  });
284
- context.emit({ kind: 'trace.request', runDirectory: context.outputDir });
285
317
  status = 'spawning peers';
286
318
  research.event('run.start');
287
319
  const setup = await Promise.allSettled(peerLabels.map(async (label) => {
@@ -299,6 +331,9 @@ export default {
299
331
  }
300
332
  signal.throwIfAborted();
301
333
  status = 'researching';
334
+ workStartedAt = Date.now();
335
+ deadlineAt = workStartedAt + budget.workMs;
336
+ deadline = setTimeout(() => controller.abort('work-deadline'), budget.workMs);
302
337
  context.markRunning();
303
338
  research.event('team.ready');
304
339
  await Promise.all(peers.map(async ({ peer, label, member }) => {
@@ -316,11 +351,15 @@ export default {
316
351
  if (remaining <= 0)
317
352
  break;
318
353
  const review = member.reviewOfferedInTurn ? undefined : member.review;
319
- if (turn > 0 && !review && research.state().budget.evaluations >= budget.maxEvaluations)
354
+ const trainExhausted = research.state().budget.evaluations >= budget.maxEvaluations;
355
+ if (turn > 0 && !review && trainExhausted && !config.continueAfterTrainBudget)
320
356
  break;
357
+ const remainingWork = trainExhausted
358
+ ? 'Train capacity is exhausted. Review another peer’s candidate, run local checks and publish concrete findings.'
359
+ : 'Check updates, review or build on promising peers’ work, and propose the next evidence-backed improvement.';
321
360
  const prompt = turn === 0
322
361
  ? `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.`
323
- : 'Check updates, review or build on promising peers’ work, and propose the next evidence-backed improvement.';
362
+ : remainingWork;
324
363
  const interrupting = new Error('Peer interrupt pending before dispatch.');
325
364
  try {
326
365
  await runInput(runtime, peer.id, review ? `${prompt}\n\n${reviewNotice(review)}` : prompt, {
@@ -346,8 +385,17 @@ export default {
346
385
  research.event('peer.turn-ended', { agentId: peer.id, detail: error.message.slice(0, 250) });
347
386
  }
348
387
  }));
388
+ workEndedAt = Date.now();
349
389
  searchEnd = research.stopReason() ?? (context.signal.aborted ? 'stopped' : controller.signal.aborted ? 'deadline' :
350
- research.state().budget.evaluations >= budget.maxEvaluations ? 'evaluation-budget' : 'workers-settled');
390
+ !config.continueAfterTrainBudget && research.state().budget.evaluations >= budget.maxEvaluations ? 'evaluation-budget' : 'workers-settled');
391
+ if (searchEnd === 'workers-settled' && budget.maxModelRequests !== undefined) {
392
+ const attempts = await readdir(join(context.outputDir, runtime.id, 'model-trace')).catch(() => []);
393
+ if (attempts.length >= budget.maxModelRequests)
394
+ searchEnd = 'model-request-budget';
395
+ }
396
+ if (!controller.signal.aborted)
397
+ controller.abort(searchEnd);
398
+ research.event('research.stopped', { detail: searchEnd });
351
399
  // The host owns the judge independently of the Runtime. Stop native work
352
400
  // while the last admitted train call settles under its own deadline.
353
401
  [close] = await Promise.all([
@@ -362,16 +410,32 @@ export default {
362
410
  selected = research.selection();
363
411
  if (selected && !context.signal.aborted) {
364
412
  status = 'final evaluation';
413
+ finalStartedAt = Date.now();
365
414
  research.event('final.selected', { agentId: selected.agentId, candidate: selected.id });
366
415
  const finalSignal = AbortSignal.any([context.signal, AbortSignal.timeout(config.closeTimeoutMs ?? 240_000)]);
367
416
  final = await withDeadline(finalSignal, () => config.evaluator.final(research.patch(selected), finalSignal));
368
- research.event('final.returned', { agentId: selected.agentId, candidate: selected.id });
417
+ finalEndedAt = Date.now();
418
+ const verdict = readFinalEvaluation(final);
419
+ const evidence = verdict?.evidence;
420
+ research.event('final.returned', { agentId: selected.agentId, candidate: selected.id,
421
+ score: verdict?.score, payloadDigest: evidence?.payload?.digest,
422
+ detail: evidence?.summary ?? verdict?.status ?? 'unverified evaluator result' });
369
423
  }
370
424
  }
371
425
  catch (failure) {
372
- error = failure.message?.slice(0, 500) ?? 'Research failed';
426
+ error = failure instanceof Error ? failure.message.slice(0, 500) : 'Research failed';
427
+ if (!runtime && runtimeAttempted && failure instanceof Error && failure.name === 'ResourceError') {
428
+ initFailure = failure;
429
+ }
430
+ if (runtime)
431
+ research.event(finalStartedAt === null ? 'run.failed' : 'final.failed', {
432
+ ...(selected ? { agentId: selected.agentId, candidate: selected.id } : {}), detail: error,
433
+ });
373
434
  }
374
435
  finally {
436
+ cleanupStartedAt = Date.now();
437
+ workEndedAt ??= workStartedAt === null ? null : cleanupStartedAt;
438
+ finalEndedAt ??= finalStartedAt === null ? null : cleanupStartedAt;
375
439
  clearTimeout(deadline);
376
440
  controller.abort('closing');
377
441
  research.close();
@@ -382,29 +446,51 @@ export default {
382
446
  }
383
447
  observation?.close();
384
448
  judgeCleanup = await cleanupJudge();
449
+ if (runtime)
450
+ research.event('run.cleanup', {
451
+ detail: `Runtime ${close?.cleanup ?? 'pending'}; evaluator ${judgeCleanup}`,
452
+ });
385
453
  }
386
454
  const best = research.best();
387
455
  const peers = research.state().peers;
388
456
  const traceDirectory = runtime ? join(context.outputDir, runtime.id) : null;
389
- const runtimeReport = close?.reportPath ? await readFile(close.reportPath, 'utf8').then(text => JSON.parse(text)).catch(() => null) : null;
457
+ const runtimeReceipt = close?.reportPath ?? initFailure?.reportPath ?? null;
458
+ const runtimeReport = runtimeReceipt ? await readFile(runtimeReceipt, 'utf8').then(text => JSON.parse(text)).catch(() => null) : null;
459
+ const usage = traceDirectory ? await modelUsage(traceDirectory, peers) : null;
460
+ const finalEvaluation = readFinalEvaluation(final);
461
+ const accepted = finalEvaluation?.status === 'valid' && finalEvaluation.meetsObjective !== false;
462
+ const reason = context.signal.aborted ? 'stopped'
463
+ : error ? searchEnd === 'train-outcome-unknown' ? searchEnd : finalStartedAt === null ? 'research-error' : 'final-error'
464
+ : !best ? 'no-valid-candidate'
465
+ : journalError ? 'trace-write-failed'
466
+ : !finalEvaluation || finalEvaluation.status === 'unknown' ? 'final-unconfirmed'
467
+ : finalEvaluation.status === 'rejected' ? 'final-rejected'
468
+ : !accepted ? 'objective-unmet'
469
+ : searchEnd;
470
+ const runtimeCleanup = close?.cleanup ?? initFailure?.cleanup ?? (runtimeAttempted ? 'pending' : 'complete');
471
+ const record = join(context.outputDir, 'research-result.json');
390
472
  const result = {
391
- runtimeId: runtime?.id ?? null, budget, searchEnd,
392
- model: { provider: config.model.provider, id: config.model.model, usage: traceDirectory ? await modelUsage(traceDirectory, peers) : null, trace: runtimeReport?.modelTrace ?? null, cost: 'unknown' },
393
- peers,
394
- candidates: research.candidates(), best: best ?? null, selected: selected ?? null, final, journalError, error,
395
- record: join(context.outputDir, 'research-result.json'), judge: config.evaluator.evidence?.() ?? null,
396
- traceDirectory,
397
- cleanup: { runtime: close?.cleanup ?? 'pending', judge: judgeCleanup },
473
+ schemaVersion: 1, runId: context.runId, runtimeId: runtime?.id ?? initFailure?.runtimeId ?? null, goal: config.goal, budget, searchEnd,
474
+ timing: { startingAt, workStartedAt, workEndedAt, finalStartedAt, finalEndedAt, cleanupStartedAt, completedAt: Date.now() },
475
+ executor: typeof config.executor === 'string' ? config.executor : config.executor.kind,
476
+ initial: { digest: context.initial.digest, files: context.initial.fileCount },
477
+ model: { provider: config.model.provider, id: config.model.model, usage, trace: runtimeReport?.modelTrace ?? null, cost: 'unknown' },
478
+ peers, candidates: research.candidates(), best: best ?? null, selected: selected ?? null, final, finalEvaluation: finalEvaluation ?? null, journalError, error,
479
+ record, judge: config.evaluator.evidence?.() ?? null, traceDirectory,
480
+ cleanup: { runtime: runtimeCleanup, judge: judgeCleanup, runtimePending: close?.pending ?? runtimeReport?.pending ?? [],
481
+ runtimeReceipt, runtimeInitializationDetails: initFailure?.details ?? null },
398
482
  };
399
483
  await mkdir(context.outputDir, { recursive: true, mode: 0o700 });
400
- await writeFile(result.record, JSON.stringify(result, null, 2) + '\n', { mode: 0o600 });
484
+ await writeFile(record + '.next', JSON.stringify(result, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
485
+ await rename(record + '.next', record);
486
+ const outcome = context.signal.aborted ? 'cancelled' : error || !best || !accepted || journalError ? 'failed' : 'completed';
401
487
  return {
402
- outcome: context.signal.aborted ? 'cancelled' : error || !best || final === null || journalError ? 'failed' : 'completed',
403
- reason: error ? 'research-error' : !best ? 'no-valid-candidate' : journalError ? 'trace-write-failed' : searchEnd,
404
- result: encode(result),
405
- acceptance: encode({ status: best && final !== null && !error ? 'verified' : 'unverified', final }),
406
- artifacts: [...(selected ? [{ path: selected.path, sha256: selected.sha256 }] : []), { path: result.record }],
407
- cleanup: { status: close?.cleanup === 'complete' && judgeCleanup === 'complete' ? 'complete' : 'pending', ...(close?.pending.length ? { pending: encode(close.pending) } : {}) },
488
+ outcome, reason, result: encode(result),
489
+ acceptance: encode({ status: outcome === 'completed' ? 'verified' : finalEvaluation?.status === 'rejected' || finalEvaluation?.meetsObjective === false
490
+ ? 'rejected' : 'unverified', final: finalEvaluation ?? null }),
491
+ artifacts: [...research.candidates().map(candidate => ({ path: candidate.path, sha256: candidate.sha256 })), { path: record }],
492
+ cleanup: { status: runtimeCleanup === 'complete' && judgeCleanup === 'complete' ? 'complete' : 'pending',
493
+ ...(close?.pending.length ? { pending: encode(close.pending) } : {}) },
408
494
  };
409
495
  },
410
496
  };
@@ -4,13 +4,24 @@ export interface Evaluation {
4
4
  valid: boolean;
5
5
  score: number | null;
6
6
  feedback: JsonValue;
7
+ payload?: {
8
+ digest: string;
9
+ size: number;
10
+ };
7
11
  }
12
+ export type FinalEvaluation = {
13
+ status: 'valid' | 'rejected' | 'unknown';
14
+ score: number | null;
15
+ meetsObjective: boolean | null;
16
+ evidence: JsonValue;
17
+ };
18
+ export declare function readFinalEvaluation(value: JsonValue): FinalEvaluation | undefined;
8
19
  export interface Evaluator {
9
20
  start?(directory: string, signal: AbortSignal): Promise<void>;
10
21
  close?(): Promise<'complete' | 'pending'>;
11
22
  evidence?(): JsonValue;
12
23
  train(candidate: Buffer, signal: AbortSignal, admitted: (reference: string | number) => void): Promise<Evaluation>;
13
- final(candidate: Buffer, signal: AbortSignal): Promise<JsonValue>;
24
+ final(candidate: Buffer, signal: AbortSignal): Promise<FinalEvaluation | JsonValue>;
14
25
  }
15
26
  export interface Candidate {
16
27
  id: string;
@@ -38,6 +49,8 @@ interface ResearchEvent {
38
49
  basedOnSha256?: string;
39
50
  score?: number | null;
40
51
  officialJob?: string | number;
52
+ payloadDigest?: string;
53
+ bytes?: number;
41
54
  label?: string;
42
55
  }
43
56
  export declare const researchOperations: string[];
@@ -86,6 +99,8 @@ export declare function createResearch(options: {
86
99
  basedOnSha256?: string;
87
100
  score?: number | null;
88
101
  officialJob?: string | number;
102
+ payloadDigest?: string;
103
+ bytes?: number;
89
104
  label?: string;
90
105
  peer: string | undefined;
91
106
  }[];
@@ -1,12 +1,21 @@
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 } from '@anyswarm/core';
6
6
  export const candidatePath = '.anyswarm-candidate.patch';
7
7
  const maxPatch = 1024 * 1024 - 1536;
8
8
  const patchChunk = 24 * 1024;
9
- const maxNotes = 512;
9
+ const maxMutations = 16_384;
10
+ export function readFinalEvaluation(value) {
11
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
12
+ !['valid', 'rejected', 'unknown'].includes(value.status) ||
13
+ (value.score !== null && (typeof value.score !== 'number' || !Number.isFinite(value.score))) ||
14
+ (value.meetsObjective !== null && typeof value.meetsObjective !== 'boolean') ||
15
+ value.evidence === undefined)
16
+ return undefined;
17
+ return value;
18
+ }
10
19
  const text = (maxLength) => ({ type: 'string', minLength: 1, maxLength });
11
20
  const object = (properties, required) => ({ type: 'object', properties, required, additionalProperties: false });
12
21
  const identifier = text(200);
@@ -41,21 +50,44 @@ export function createResearch(options) {
41
50
  const claims = new Map();
42
51
  let best;
43
52
  let reserved = 0;
53
+ let nextCandidate = 0;
54
+ let storing = Promise.resolve();
55
+ const mutations = new Map();
44
56
  let closed = false;
45
57
  let stopReason;
46
58
  let queue = Promise.resolve();
47
59
  const project = (record) => record;
48
60
  const reached = (score, target) => options.direction === 'max' ? score >= target : score <= target;
49
61
  function event(operation, data = {}) {
50
- const entry = { ...data, seq: events.length + 1, at: new Date().toISOString(), type: 'research', operation };
62
+ const candidate = data.candidate && candidates.get(data.candidate);
63
+ const entry = { ...(candidate ? { sha256: candidate.sha256 } : {}), ...data, seq: events.length + 1, at: new Date().toISOString(), type: 'research', operation };
51
64
  events.push(entry);
52
65
  options.traceEvent(entry);
53
66
  options.statusChanged();
54
67
  }
55
68
  function admit() {
56
- if (closed || stopReason || options.signal.aborted || events.length >= maxNotes)
69
+ if (closed || stopReason || options.signal.aborted)
57
70
  throw new Error('Research admissions are closed');
58
71
  }
72
+ function mutation(operation, handler) {
73
+ return (input, context) => {
74
+ context.assertAuthorized();
75
+ const key = JSON.stringify([context.caller.agentId, context.envelope.operation_id]);
76
+ const payload = input;
77
+ const fingerprint = JSON.stringify([operation, Object.entries(payload).sort(([left], [right]) => left.localeCompare(right))]);
78
+ const entry = mutations.get(key);
79
+ if (entry) {
80
+ if (entry.fingerprint !== fingerprint)
81
+ throw new Error('Operation ID already identifies a different research action');
82
+ return entry.receipt;
83
+ }
84
+ if (mutations.size >= maxMutations)
85
+ throw new Error('Research mutation receipt limit reached');
86
+ const receipt = Promise.resolve().then(() => handler(input, context));
87
+ mutations.set(key, { fingerprint, receipt });
88
+ return receipt;
89
+ };
90
+ }
59
91
  function state() {
60
92
  return {
61
93
  peers: [...peers].map(([agentId, label]) => ({ agentId, label })),
@@ -86,7 +118,8 @@ export function createResearch(options) {
86
118
  }));
87
119
  candidate.evaluation = evaluation;
88
120
  candidate.state = validScore(evaluation) ? 'scored' : 'invalid';
89
- event('train.returned', { agentId: candidate.agentId, candidate: candidate.id, score: evaluation.score });
121
+ event('train.returned', { agentId: candidate.agentId, candidate: candidate.id, score: evaluation.score,
122
+ officialJob: candidate.officialJob, payloadDigest: evaluation.payload?.digest });
90
123
  if (validScore(evaluation) && (!best || (evaluation.score !== best.evaluation.score && reached(evaluation.score, best.evaluation.score)))) {
91
124
  best = candidate;
92
125
  event('candidate.best', { agentId: candidate.agentId, candidate: candidate.id, score: evaluation.score });
@@ -112,7 +145,7 @@ export function createResearch(options) {
112
145
  candidates: [...candidates.values()].slice(-8).map(({ path: _, ...candidate }) => candidate),
113
146
  });
114
147
  },
115
- claim: (input, { caller, assertAuthorized }) => {
148
+ claim: mutation('claim', (input, { caller, assertAuthorized }) => {
116
149
  assertAuthorized();
117
150
  admit();
118
151
  const direction = input.direction.trim();
@@ -125,8 +158,8 @@ export function createResearch(options) {
125
158
  claims.set(key, caller.agentId);
126
159
  event('peer.claim', { agentId: caller.agentId, detail: direction });
127
160
  return { claimed: true, agentId: caller.agentId };
128
- },
129
- publish: (input, { caller, assertAuthorized }) => {
161
+ }),
162
+ publish: mutation('publish', (input, { caller, assertAuthorized }) => {
130
163
  assertAuthorized();
131
164
  admit();
132
165
  const { kind, summary, candidate } = input;
@@ -139,8 +172,8 @@ export function createResearch(options) {
139
172
  event(`peer.${kind}`, { agentId: caller.agentId, detail: summary,
140
173
  ...(reviewed ? { candidate: reviewed.id, sha256: reviewed.sha256 } : {}) });
141
174
  return { published: true };
142
- },
143
- message: (input, { caller, assertAuthorized }) => {
175
+ }),
176
+ message: mutation('message', (input, { caller, assertAuthorized }) => {
144
177
  assertAuthorized();
145
178
  admit();
146
179
  const { peer, summary } = input;
@@ -148,7 +181,7 @@ export function createResearch(options) {
148
181
  throw new Error('Peer does not belong to this Run');
149
182
  event('peer.message', { agentId: caller.agentId, to: peer, detail: summary });
150
183
  return { sent: true };
151
- },
184
+ }),
152
185
  read_patch: (input, { caller, assertAuthorized }) => {
153
186
  assertAuthorized();
154
187
  admit();
@@ -172,47 +205,54 @@ export function createResearch(options) {
172
205
  }
173
206
  return { candidate, sha256, data: bytes.subarray(start, end).toString('base64'), nextOffset: end < bytes.length ? end : null };
174
207
  },
175
- submit: async (input, { caller, envelope, assertAuthorized }) => {
208
+ submit: mutation('submit', async (input, { caller, envelope, assertAuthorized }) => {
176
209
  assertAuthorized();
177
210
  admit();
178
211
  const { summary, basedOn } = input;
179
- if (basedOn && !readEntirePatch(caller.agentId, basedOn))
180
- throw new Error('Read the referenced candidate before building on it');
212
+ const parent = basedOn ? candidates.get(basedOn) : undefined;
213
+ if (basedOn && (!parent || parent.agentId === caller.agentId || !readEntirePatch(caller.agentId, basedOn))) {
214
+ throw new Error('Read the referenced peer candidate before building on it');
215
+ }
181
216
  const bytes = await options.readPatch(caller.agentId, envelope.operation_id);
182
- assertAuthorized();
183
- admit();
184
217
  if (!bytes.length || bytes.length > maxPatch)
185
218
  throw new Error('Candidate patch is empty or exceeds the size limit');
186
219
  const sha256 = createHash('sha256').update(bytes).digest('hex');
187
- const previous = known.get(sha256);
188
- if (previous)
189
- return { candidate: previous.id, status: previous.state, duplicate: true, sha256 };
190
- if (reserved >= options.maxEvaluations)
191
- throw new Error('Shared evaluation budget is exhausted');
192
- reserved++;
193
- const id = `candidate-${reserved}`;
194
- const path = join(options.outputDir, 'candidates', `${id}.patch`);
195
- const candidate = { id, agentId: caller.agentId, summary, basedOn: basedOn ?? null, path,
196
- sha256, bytes: bytes.length, state: 'queued' };
197
- known.set(sha256, candidate);
198
- try {
199
- await mkdir(join(options.outputDir, 'candidates'), { recursive: true, mode: 0o700 });
200
- await writeFile(path, bytes, { mode: 0o600, flag: 'wx' });
220
+ // Serialize the host file commit and quota admission, once the private
221
+ // workspace snapshot is available. No duplicate can observe a half write.
222
+ const result = storing.then(async () => {
201
223
  assertAuthorized();
202
224
  admit();
203
- }
204
- catch (error) {
205
- candidate.state = 'cancelled';
225
+ const previous = known.get(sha256);
226
+ if (previous)
227
+ return { candidate: previous.id, status: previous.state, duplicate: true, sha256 };
228
+ if (reserved >= options.maxEvaluations)
229
+ throw new Error('Shared evaluation budget is exhausted');
230
+ const id = `candidate-${++nextCandidate}`;
231
+ const path = join(options.outputDir, 'candidates', `${id}.patch`);
232
+ const candidate = { id, agentId: caller.agentId, summary, basedOn: basedOn ?? null, path,
233
+ sha256, bytes: bytes.length, state: 'queued' };
234
+ await mkdir(join(options.outputDir, 'candidates'), { recursive: true, mode: 0o700 });
235
+ await writeFile(path, bytes, { mode: 0o600, flag: 'wx' });
236
+ try {
237
+ assertAuthorized();
238
+ admit();
239
+ }
240
+ catch (error) {
241
+ await unlink(path);
242
+ throw error;
243
+ }
244
+ reserved++;
245
+ known.set(sha256, candidate);
246
+ patches.set(id, bytes);
206
247
  candidates.set(id, candidate);
207
- throw error;
208
- }
209
- patches.set(id, bytes);
210
- candidates.set(id, candidate);
211
- event(basedOn ? 'candidate.built-on' : 'candidate.queued', { agentId: caller.agentId, candidate: id, sha256, detail: summary,
212
- ...(basedOn ? { basedOn, basedOnSha256: candidates.get(basedOn).sha256 } : {}) });
213
- queue = queue.then(() => evaluate(candidate, bytes));
214
- return { candidate: id, status: candidate.state, duplicate: false, sha256 };
215
- },
248
+ event(parent ? 'candidate.built-on' : 'candidate.queued', { agentId: caller.agentId, candidate: id, sha256, bytes: bytes.length, detail: summary,
249
+ ...(parent ? { basedOn, basedOnSha256: parent.sha256 } : {}) });
250
+ queue = queue.then(() => evaluate(candidate, bytes));
251
+ return { candidate: id, status: 'queued', duplicate: false, sha256 };
252
+ });
253
+ storing = result.then(() => { }, () => { });
254
+ return result;
255
+ }),
216
256
  }, {
217
257
  readState: () => ({
218
258
  state: project(state()), capturedAt: new Date().toISOString(), revision: String(events.length),
@@ -229,10 +269,10 @@ export function createResearch(options) {
229
269
  addPeer: (id, label) => { peers.set(id, label); event('peer.ready', { agentId: id, label }); },
230
270
  close: () => { closed = true; },
231
271
  stopReason: () => stopReason,
232
- drained: () => queue,
272
+ drained: async () => { await storing; await queue; },
233
273
  best: () => best,
234
274
  peerLabel: (agentId) => peers.get(agentId),
235
- selection: () => best ?? [...candidates.values()].find(candidate => candidate.state === 'invalid'),
275
+ selection: () => best,
236
276
  patch: (candidate) => Buffer.from(patches.get(candidate.id)),
237
277
  candidates: () => [...candidates.values()], };
238
278
  }
@@ -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.