@anyswarm/core 0.5.2 → 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 (210) hide show
  1. package/AGENTS.md +19 -4
  2. package/README.md +68 -61
  3. package/dist/examples/README.md +134 -84
  4. package/dist/examples/autoresearch/README.md +106 -21
  5. package/dist/examples/autoresearch/REQUIREMENTS.zh.md +14 -6
  6. package/dist/examples/autoresearch/config.d.ts +48 -5
  7. package/dist/examples/autoresearch/config.js +57 -23
  8. package/dist/examples/autoresearch/demo.d.ts +12 -4
  9. package/dist/examples/autoresearch/demo.js +65 -22
  10. package/dist/examples/autoresearch/frontiercs2-config.d.ts +2 -2
  11. package/dist/examples/autoresearch/frontiercs2-config.js +13 -2
  12. package/dist/examples/autoresearch/frontiercs2.d.ts +18 -1
  13. package/dist/examples/autoresearch/frontiercs2.js +71 -14
  14. package/dist/examples/autoresearch/prepare-demo.js +34 -3
  15. package/dist/examples/autoresearch/prepare.d.ts +105 -53
  16. package/dist/examples/autoresearch/prepare.js +126 -57
  17. package/dist/examples/autoresearch/project.d.ts +6 -1
  18. package/dist/examples/autoresearch/project.js +130 -26
  19. package/dist/examples/autoresearch/research-service.d.ts +16 -1
  20. package/dist/examples/autoresearch/research-service.js +84 -44
  21. package/dist/examples/code/config.d.ts +1 -0
  22. package/dist/examples/first-harness/AGENTS.md +25 -0
  23. package/dist/examples/first-harness/README.md +136 -0
  24. package/dist/examples/first-harness/config.d.ts +9 -8
  25. package/dist/examples/first-harness/config.js +33 -26
  26. package/dist/examples/first-harness/eject.json +14 -0
  27. package/dist/examples/first-harness/handoff.js +3 -3
  28. package/dist/examples/first-harness/harness.d.ts +14 -18
  29. package/dist/examples/first-harness/harness.js +102 -77
  30. package/dist/examples/first-harness/input/README.md +7 -0
  31. package/dist/examples/first-harness/session.js +2 -1
  32. package/dist/examples/first-harness/tsconfig.json +2 -1
  33. package/dist/examples/harness-session/README.md +1 -1
  34. package/dist/examples/lead-worker/README.md +1 -1
  35. package/dist/examples/lead-worker/project-config.d.ts +1 -0
  36. package/dist/examples/messages/README.md +2 -2
  37. package/dist/examples/notes/README.md +2 -2
  38. package/dist/examples/notes/config.d.ts +1 -0
  39. package/dist/examples/parallel-swarm/AGENTS.md +32 -0
  40. package/dist/examples/parallel-swarm/README.md +136 -0
  41. package/dist/examples/parallel-swarm/board-service.js +25 -8
  42. package/dist/examples/parallel-swarm/board.d.ts +31 -1
  43. package/dist/examples/parallel-swarm/board.js +98 -13
  44. package/dist/examples/parallel-swarm/config.d.ts +11 -0
  45. package/dist/examples/parallel-swarm/config.js +39 -0
  46. package/dist/examples/parallel-swarm/eject.json +5 -0
  47. package/dist/examples/parallel-swarm/harness.d.ts +26 -20
  48. package/dist/examples/parallel-swarm/harness.js +77 -76
  49. package/dist/examples/parallel-swarm/report.d.ts +12 -0
  50. package/dist/examples/parallel-swarm/report.js +30 -0
  51. package/dist/examples/peermesh/README.md +1 -1
  52. package/dist/examples/peermesh/project-config.d.ts +1 -0
  53. package/dist/examples/services/agent-control/README.md +1 -1
  54. package/dist/examples/services/mathlib-search/README.md +1 -1
  55. package/dist/examples/services/mcp-managed/README.md +1 -1
  56. package/dist/examples/services/persistent-board/README.md +1 -1
  57. package/dist/examples/subagents/AGENTS.md +35 -0
  58. package/dist/examples/subagents/README.md +129 -93
  59. package/dist/examples/subagents/config.d.ts +2 -10
  60. package/dist/examples/subagents/config.js +8 -15
  61. package/dist/examples/subagents/eject.json +17 -0
  62. package/dist/examples/subagents/handoff-config.d.ts +41 -0
  63. package/dist/examples/subagents/handoff-config.js +13 -0
  64. package/dist/examples/subagents/model.d.ts +3 -0
  65. package/dist/examples/subagents/model.js +19 -0
  66. package/dist/examples/substrate/README.md +12 -6
  67. package/dist/examples/substrate/config.d.ts +1 -0
  68. package/dist/examples/substrate/project-config.d.ts +1 -0
  69. package/dist/examples/taskpool/README.md +1 -1
  70. package/dist/examples/taskpool/config.d.ts +1 -0
  71. package/dist/examples/taskpool/deploy/service-hosts/service-authority-snapshot.d.ts +4 -4
  72. package/dist/scripts/anyswarm-progress.js +36 -5
  73. package/dist/scripts/build-provenance.json +1 -1
  74. package/dist/scripts/generate-architecture-coverage.js +1 -1
  75. package/dist/scripts/generate-architecture-prompts.js +18 -10
  76. package/dist/scripts/local-environment.d.ts +3 -3
  77. package/dist/scripts/local-environment.js +6 -1
  78. package/dist/scripts/local-setup.js +25 -18
  79. package/dist/scripts/pack-release.js +27 -3
  80. package/dist/src/core/index.js +1 -1
  81. package/dist/src/core/sandbox/opensandbox-backend.js +10 -4
  82. package/dist/src/core/sandbox/sandbox-connection.d.ts +9 -2
  83. package/dist/src/core/sandbox/sandbox-connection.js +22 -7
  84. package/dist/src/harness/project-harness.js +3 -2
  85. package/dist/src/harness/project-rpc-client.js +19 -0
  86. package/dist/src/harness/typescript-loader.d.ts +2 -0
  87. package/dist/src/harness/typescript-loader.js +26 -8
  88. package/dist/src/trace-viewer/command.mjs +6 -3
  89. package/dist/src/trace-viewer/public/app.js +239 -59
  90. package/dist/src/trace-viewer/public/index.html +5 -0
  91. package/dist/src/trace-viewer/public/style.css +22 -0
  92. package/dist/src/trace-viewer/reader.mjs +242 -26
  93. package/dist/src/trace-viewer/run-root.d.mts +1 -0
  94. package/dist/src/trace-viewer/run-root.mjs +7 -0
  95. package/dist/src/trace-viewer/server.mjs +3 -1
  96. package/docs/INDEX.md +9 -8
  97. package/docs/architecture/06-observability-experiments.md +21 -7
  98. package/docs/architecture/07-run-configuration.md +97 -12
  99. package/docs/architecture/08-prompts.md +21 -2
  100. package/docs/architecture/10-service-api-reference.md +12 -5
  101. package/docs/architecture/12-code-coverage.md +129 -86
  102. package/docs/architecture/15-core-runtime.md +1 -1
  103. package/docs/architecture/16-pi-opensandbox-backend.md +2 -0
  104. package/docs/architecture/17-harness-reporting.md +78 -0
  105. package/docs/architecture/22-website.md +53 -18
  106. package/docs/architecture/23-project-harness.md +63 -16
  107. package/docs/architecture/28-autoresearch.md +16 -22
  108. package/docs/architecture/prompts/11-first-sdk-harness.md +9 -9
  109. package/docs/architecture/prompts/16-parallel-swarm.md +46 -13
  110. package/docs/architecture/prompts/22-autoresearch.md +9 -2
  111. package/docs/architecture/prompts/source-manifest.json +78 -54
  112. package/docs/architecture/source-map.json +396 -36
  113. package/docs/designs/core-harness/06-project-harness.md +1 -1
  114. package/docs/en/autoresearch.md +41 -0
  115. package/docs/en/blog/100b-tokens.md +157 -0
  116. package/docs/en/build-your-harness.md +47 -22
  117. package/docs/en/changelog.md +22 -1
  118. package/docs/en/first-harness.md +40 -32
  119. package/docs/en/harnesses/index.md +23 -23
  120. package/docs/en/harnesses/subagents.md +8 -29
  121. package/docs/en/latest.md +26 -5
  122. package/docs/en/overview.md +22 -22
  123. package/docs/en/quickstart.md +55 -21
  124. package/docs/en/reference/api.md +1 -1
  125. package/docs/en/trace-viewer.md +32 -12
  126. package/docs/operations/trace-viewer.md +25 -10
  127. package/docs/workflows/development.md +160 -120
  128. package/docs/workflows/release-and-docs-versioning.md +207 -55
  129. package/docs/workflows/release-cli-acceptance.md +124 -47
  130. package/docs/zh/autoresearch.md +41 -0
  131. package/docs/zh/blog/100b-tokens.md +102 -0
  132. package/docs/zh/build-your-harness.md +48 -23
  133. package/docs/zh/changelog.md +22 -1
  134. package/docs/zh/first-harness.md +43 -35
  135. package/docs/zh/harnesses/index.md +23 -23
  136. package/docs/zh/harnesses/subagents.md +8 -29
  137. package/docs/zh/latest.md +26 -5
  138. package/docs/zh/overview.md +23 -23
  139. package/docs/zh/quickstart.md +51 -21
  140. package/docs/zh/reference/api.md +1 -1
  141. package/docs/zh/trace-viewer.md +32 -12
  142. package/examples/README.md +134 -84
  143. package/examples/autoresearch/README.md +106 -21
  144. package/examples/autoresearch/REQUIREMENTS.zh.md +14 -6
  145. package/examples/autoresearch/config.ts +64 -25
  146. package/examples/autoresearch/demo.ts +75 -22
  147. package/examples/autoresearch/frontiercs2-config.ts +13 -2
  148. package/examples/autoresearch/frontiercs2.ts +64 -11
  149. package/examples/autoresearch/prepare-demo.ts +32 -3
  150. package/examples/autoresearch/prepare.ts +134 -60
  151. package/examples/autoresearch/project.ts +119 -26
  152. package/examples/autoresearch/research-service.ts +91 -41
  153. package/examples/first-harness/AGENTS.md +25 -0
  154. package/examples/first-harness/README.md +136 -0
  155. package/examples/first-harness/config.ts +41 -27
  156. package/examples/first-harness/eject.json +14 -0
  157. package/examples/first-harness/handoff.ts +3 -3
  158. package/examples/first-harness/harness.ts +104 -72
  159. package/examples/first-harness/input/README.md +7 -0
  160. package/examples/first-harness/session.ts +2 -1
  161. package/examples/first-harness/tsconfig.json +2 -1
  162. package/examples/harness-session/README.md +1 -1
  163. package/examples/lead-worker/README.md +1 -1
  164. package/examples/messages/README.md +2 -2
  165. package/examples/notes/README.md +2 -2
  166. package/examples/parallel-swarm/AGENTS.md +32 -0
  167. package/examples/parallel-swarm/README.md +136 -0
  168. package/examples/parallel-swarm/board-service.ts +28 -9
  169. package/examples/parallel-swarm/board.ts +107 -13
  170. package/examples/parallel-swarm/config.ts +47 -0
  171. package/examples/parallel-swarm/eject.json +5 -0
  172. package/examples/parallel-swarm/harness.ts +83 -71
  173. package/examples/parallel-swarm/report.ts +33 -0
  174. package/examples/peermesh/README.md +1 -1
  175. package/examples/services/agent-control/README.md +1 -1
  176. package/examples/services/mathlib-search/README.md +1 -1
  177. package/examples/services/mcp-managed/README.md +1 -1
  178. package/examples/services/persistent-board/README.md +1 -1
  179. package/examples/subagents/AGENTS.md +35 -0
  180. package/examples/subagents/README.md +129 -93
  181. package/examples/subagents/config.ts +8 -15
  182. package/examples/subagents/eject.json +17 -0
  183. package/examples/subagents/handoff-config.ts +14 -0
  184. package/examples/subagents/model.ts +20 -0
  185. package/examples/substrate/README.md +12 -6
  186. package/examples/taskpool/README.md +1 -1
  187. package/npm-shrinkwrap.development.json +9 -2
  188. package/npm-shrinkwrap.json +9 -2
  189. package/package.development.json +2 -1
  190. package/package.json +2 -1
  191. package/scripts/anyswarm-progress.ts +36 -6
  192. package/scripts/generate-architecture-coverage.ts +1 -1
  193. package/scripts/generate-architecture-prompts.ts +21 -10
  194. package/scripts/local-environment.ts +8 -1
  195. package/scripts/local-setup.ts +22 -17
  196. package/scripts/pack-release.ts +24 -3
  197. package/src/core/index.ts +1 -1
  198. package/src/core/sandbox/opensandbox-backend.ts +10 -4
  199. package/src/core/sandbox/sandbox-connection.ts +22 -7
  200. package/src/harness/project-harness.ts +3 -2
  201. package/src/harness/project-rpc-client.ts +23 -0
  202. package/src/harness/typescript-loader.ts +28 -8
  203. package/src/trace-viewer/command.mjs +6 -3
  204. package/src/trace-viewer/public/app.js +239 -59
  205. package/src/trace-viewer/public/index.html +5 -0
  206. package/src/trace-viewer/public/style.css +22 -0
  207. package/src/trace-viewer/reader.mjs +242 -26
  208. package/src/trace-viewer/run-root.d.mts +1 -0
  209. package/src/trace-viewer/run-root.mjs +7 -0
  210. package/src/trace-viewer/server.mjs +3 -1
@@ -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
  }
@@ -7,6 +7,7 @@ declare const _default: {
7
7
  useServerProxy: boolean | undefined;
8
8
  egressMode: "dns+nft" | undefined;
9
9
  endpointHost: undefined;
10
+ preparedImage?: string | undefined;
10
11
  resourceLimits: {
11
12
  cpu: string;
12
13
  memory: string;
@@ -0,0 +1,25 @@
1
+ # Editing this Harness
2
+
3
+ This is consumer-owned source exported from AnySwarm. Use the public
4
+ `@anyswarm/core` entry and the SDK recorded in `anyswarm-source.json`; run `npm
5
+ install` here and use `npm run start` or `npm exec -- anyswarm`. Keep imports local
6
+ to this project or to declared dependencies.
7
+
8
+ - `config.ts` owns the connection, selected executor/model, shared model-request
9
+ limit and foreground channel. Explicit `--config ./custom.ts` replaces this
10
+ configuration; start from its exported defaults when changing one setting.
11
+ - `harness.ts` owns the two Profiles, turn order and completion checks.
12
+ `context.runWithRuntime` owns close/report classification; `runInput` waits for
13
+ each exclusive Agent turn. Keep business verification outside `afterClose`.
14
+ - `handoff.ts` owns the Service contract and authenticated caller evidence.
15
+ The publisher may publish; the writer may take. Preserve request IDs and the
16
+ fresh publisher-only reference when changing the exercise.
17
+ - Default foreground execution must finish without a question. `session.ts`
18
+ deliberately enables questions for the SDK/RPC extension.
19
+ - Check both sandbox and exported `delivery.txt` bytes, including final newlines.
20
+ Keep business acceptance, artifact export and cleanup separate. Preserve the
21
+ original pending resources and receipts instead of inventing success after a
22
+ timeout or missing export.
23
+
24
+ Make the smallest change needed for the user's task, keep credentials in trusted
25
+ configuration, and update this project's README when its commands or checks change.
@@ -0,0 +1,136 @@
1
+ # First SDK Harness: a verified Service handoff
2
+
3
+ Two Agents exchange a fresh release reference through a host-owned Handoff
4
+ Service. The publisher reads the reference in its isolated Sandbox. The writer
5
+ retrieves it using its own Service permission and writes `delivery.txt`. The host
6
+ checks the authenticated author and reader, then checks the exact bytes in the
7
+ writer's Sandbox and again after export.
8
+
9
+ This is a small SDK exercise for Profiles, Services and artifact verification.
10
+ The foreground channel defaults to `preview`, so the ordinary run has no midway
11
+ questions. Explicit SDK and RPC question clients are available below.
12
+
13
+ ## Prepare and run the exported source
14
+
15
+ Use Node.js 22.19 or later, an AnySwarm installation, a working OpenSandbox and a
16
+ compatible Worker prepared with `anyswarm setup`. The example inherits setup's
17
+ executor, image and connection. Local setup needs Docker and the selected Pi or
18
+ Codex installation; an existing OpenSandbox needs its authenticated connection
19
+ and a callback address reachable by its Workers. No additional business service
20
+ is needed: Handoff runs in the host process.
21
+
22
+ Configure an existing streaming model endpoint with tool support. Set
23
+ `ANYSWARM_MODEL_URL`, and set `ANYSWARM_MODEL_ID` and `ANYSWARM_MODEL_PROVIDER` for
24
+ your model. Pi defaults to `gpt-5-mini`; Codex requires an explicit model ID. The
25
+ provider defaults to `openai`. Set `ANYSWARM_MODEL_TOKEN`
26
+ in the host environment only if the endpoint requires authentication. Pi supports
27
+ `ANYSWARM_MODEL_PROTOCOL=responses` or `chat-completions`; Codex requires
28
+ `responses`. The endpoint URL must match that protocol.
29
+
30
+ ```sh
31
+ anyswarm eject first-harness --dir ./first-harness
32
+ cd ./first-harness
33
+ npm install
34
+ npm run start -- --cwd ./input --prompt "Prepare a release handoff." --output-dir ./runs
35
+ npm exec -- anyswarm trace --root ./runs
36
+ ```
37
+
38
+ The export contains the Harness, Service, configuration, question client and input
39
+ directory, together with the exact SDK archive used by `npm install`. It does not
40
+ require a checkout of AnySwarm or any sibling example. When running from the
41
+ AnySwarm repository instead, build the repository and run
42
+ `node dist/scripts/anyswarm.js run examples/first-harness/harness.ts --cwd
43
+ examples/first-harness/input --prompt "Prepare a release handoff." --output-dir
44
+ ./runs`.
45
+
46
+ ## Change the channel or configuration
47
+
48
+ ```sh
49
+ ANYSWARM_FIRST_CHANNEL=beta-east npm run start -- --cwd ./input \
50
+ --prompt "Prepare a release handoff." --output-dir ./runs
51
+ ```
52
+
53
+ A channel starts with a lowercase letter and contains at most 24 lowercase
54
+ letters, digits or hyphens. For further changes, edit `config.ts`, or create a
55
+ complete configuration such as:
56
+
57
+ ```ts
58
+ import defaults from './config.js';
59
+
60
+ export default { ...defaults, channel: 'staging' };
61
+ ```
62
+
63
+ Pass it as `npm run start -- --config ./custom.ts --cwd ./input --prompt "Prepare
64
+ a release handoff."`. A supplied configuration is used directly; it is not
65
+ silently overwritten with environment values. The default configuration reads
66
+ common `ANYSWARM_*` connection settings before saved setup values, and
67
+ `ANYSWARM_EXECUTOR` before setup's executor. Set `ANYSWARM_WORKER_IMAGE` to an image
68
+ compatible with an executor override when necessary. With neither selection,
69
+ the executor falls back to Pi. `ANYSWARM_CONTEXT_WINDOW` can supply a context limit
70
+ of at least 2048 tokens for an unlisted model; edit `models.default.capabilities`
71
+ for its other capabilities.
72
+
73
+ The default shared gateway limit is 32 model requests. Each Agent turn has a
74
+ 120-second deadline; Runtime close has a 60-second wait. These are bounds, not a
75
+ promise about model response time or cost. The example uses two Agent slots in
76
+ one Runtime.
77
+
78
+ ## Inspect the result
79
+
80
+ The foreground command prints a final result record. Successful delivery has
81
+ `outcome: "completed"`, `acceptance.status: "verified"`, `export.status:
82
+ "complete"` and `cleanup.status: "complete"`. `acceptance.file` identifies the
83
+ exported file; `acceptance.bytes` and `acceptance.sha256` describe the bytes that
84
+ were checked. Its content is:
85
+
86
+ ```text
87
+ reference=<fresh 12-character hexadecimal reference>
88
+ channel=preview
89
+ ```
90
+
91
+ Both lines end with a newline. The reference is generated per Run, supplied only
92
+ to the publisher, and read by the writer through Handoff. The input directory is
93
+ captured as a snapshot; neither Agent writes back to it. `result.handoff` records
94
+ the real author, reader and request IDs. `reportPath` points to the saved host
95
+ report, while `cleanup.receipt` retains the original Runtime close receipt.
96
+
97
+ Check export and cleanup separately from business outcome. A pending required
98
+ export remains `export.status: "pending"` with the raw resource identity in
99
+ `cleanup.pending`; a completed turn does not make it verified. An exported file
100
+ with wrong bytes fails acceptance without being relabelled a cleanup failure.
101
+ A failed or cancelled run retains the available business and cleanup evidence.
102
+ No file is published to a real release channel by this exercise.
103
+
104
+ ## Explicit SDK and RPC questions
105
+
106
+ The advanced terminal client opts into question events. These commands ask for
107
+ the channel even if the foreground preset is set:
108
+
109
+ ```sh
110
+ npm exec -- anyswarm run ./session.ts ./input "Prepare a release handoff."
111
+ npm exec -- anyswarm run ./session.ts --rpc ./input "Prepare a release handoff."
112
+ ```
113
+
114
+ `session.ts` uses `createHarnessSession` directly or wraps the JSONL CLI with
115
+ `HarnessRpcClient`. It answers the pending `questionId` using `respond`, observes
116
+ completion, and stops on terminal EOF or interruption. A custom JSONL client can
117
+ use `anyswarm --harness ./harness.ts --mode rpc --interaction questions`, submit a
118
+ `run` operation, then answer the emitted question. An SDK client explicitly sets
119
+ `clientCapabilities: { questions: true }`. Plain foreground and clients without
120
+ question support use the preset channel.
121
+
122
+ ## Read and modify
123
+
124
+ | File | Responsibility |
125
+ | --- | --- |
126
+ | `harness.ts` | Profiles, publisher/writer turns, questions, exact byte checks and result projection. |
127
+ | `handoff.ts` | Service schemas, authenticated publish/take and caller evidence. |
128
+ | `config.ts` | Setup inheritance, model protocol, budgets and foreground channel. |
129
+ | `session.ts` | Explicit SDK/RPC question client. |
130
+ | `AGENTS.md` | Short instructions for the coding agent editing your exported source. |
131
+
132
+ Controlled tests exercise the real Runtime and authenticated Service Bridge with
133
+ a simulated Worker transport, including wrong bytes and pending export. Installed
134
+ Worker/model tests live in `test/first-harness-installed.test.ts` in the AnySwarm
135
+ repository and require a configured backend. Passing controlled tests alone does
136
+ not establish that a particular external model or Worker is ready.
@@ -1,13 +1,14 @@
1
- import type { ModelConfig, RuntimeConnectionOptions, SandboxConfig } from '@anyswarm/core';
2
- declare const _default: {
1
+ import { type ExecutorSelection, type ModelConfig, type RuntimeConnectionOptions, type SandboxConfig } from '@anyswarm/core';
2
+ export interface FirstHarnessConfiguration {
3
3
  sandbox: SandboxConfig;
4
4
  connection: RuntimeConnectionOptions;
5
- executor: 'pi';
5
+ executor: ExecutorSelection;
6
6
  image: string;
7
- channel: string | undefined;
8
7
  model: string;
9
- models: {
10
- default: ModelConfig;
11
- };
12
- };
8
+ models: Record<string, ModelConfig>;
9
+ /** Used by foreground clients. Explicit question clients ask for their own channel. */
10
+ channel?: string;
11
+ }
12
+ export declare function firstHarnessConfig(): FirstHarnessConfiguration;
13
+ declare const _default: FirstHarnessConfiguration;
13
14
  export default _default;
@@ -1,27 +1,34 @@
1
- import * as sdk from '@anyswarm/core';
2
- const env = process.env;
3
- const resolved = sdk.resolveSandboxConnection();
4
- const sandbox = {
5
- lifecycleBaseUrl: resolved.lifecycleBaseUrl, apiKey: resolved.apiKey, endpointHost: resolved.endpointHost,
6
- };
7
- const protocol = env.ANYSWARM_MODEL_PROTOCOL ?? 'responses';
8
- if (!['responses', 'chat-completions'].includes(protocol)) {
9
- throw new Error('Select responses, or use chat-completions with the SDK that supports it.');
1
+ import { ProjectPreflightError, resolveSandboxConnection, workerImageFor } from '@anyswarm/core';
2
+ export function firstHarnessConfig() {
3
+ const env = process.env;
4
+ const { image, advertiseHost, publicUrl, executor: setupExecutor, endpointSource: _source, ...sandbox } = resolveSandboxConnection();
5
+ const executor = env.ANYSWARM_EXECUTOR ?? setupExecutor ?? 'pi';
6
+ if (executor !== 'pi' && executor !== 'codex')
7
+ throw new ProjectPreflightError('INVALID_RUN_CONFIGURATION', 'Set ANYSWARM_EXECUTOR to pi or codex, or provide an executor in your TypeScript configuration.');
8
+ const protocol = env.ANYSWARM_MODEL_PROTOCOL ?? 'responses';
9
+ if (protocol !== 'responses' && protocol !== 'chat-completions') {
10
+ throw new ProjectPreflightError('INVALID_RUN_CONFIGURATION', 'Set ANYSWARM_MODEL_PROTOCOL to responses or chat-completions.');
11
+ }
12
+ if (executor === 'codex' && protocol !== 'responses')
13
+ throw new ProjectPreflightError('INVALID_RUN_CONFIGURATION', 'Codex requires ANYSWARM_MODEL_PROTOCOL=responses.');
14
+ if (executor === 'codex' && !env.ANYSWARM_MODEL_ID?.trim())
15
+ throw new ProjectPreflightError('INVALID_RUN_CONFIGURATION', 'Set ANYSWARM_MODEL_ID to a model supported by your Codex Responses endpoint.');
16
+ const contextWindow = env.ANYSWARM_CONTEXT_WINDOW === undefined ? undefined : Number(env.ANYSWARM_CONTEXT_WINDOW);
17
+ if (contextWindow !== undefined && (!Number.isSafeInteger(contextWindow) || contextWindow < 2048)) {
18
+ throw new ProjectPreflightError('INVALID_RUN_CONFIGURATION', 'ANYSWARM_CONTEXT_WINDOW must be the configured model context limit, at least 2048 tokens.');
19
+ }
20
+ const model = {
21
+ provider: env.ANYSWARM_MODEL_PROVIDER ?? 'openai',
22
+ model: env.ANYSWARM_MODEL_ID ?? 'gpt-5-mini',
23
+ upstream: { url: env.ANYSWARM_MODEL_URL ?? '', headers: env.ANYSWARM_MODEL_TOKEN ? { authorization: `Bearer ${env.ANYSWARM_MODEL_TOKEN}` } : {} },
24
+ ...(protocol === 'chat-completions' ? { protocol } : {}),
25
+ ...(contextWindow ? { capabilities: { contextWindow, maxOutputTokens: 1024, tools: true, reasoning: false } } : {}),
26
+ };
27
+ return {
28
+ sandbox, executor, image: image ?? workerImageFor(executor),
29
+ connection: { advertiseHost, publicUrl,
30
+ modelGateway: { requestTimeoutMs: 90_000, maxOutputTokens: executor === 'codex' ? null : 1024, maxRequests: 32 } },
31
+ channel: env.ANYSWARM_FIRST_CHANNEL ?? 'preview', model: 'default', models: { default: model },
32
+ };
10
33
  }
11
- const contextWindow = env.ANYSWARM_CONTEXT_WINDOW === undefined ? undefined : Number(env.ANYSWARM_CONTEXT_WINDOW);
12
- if (contextWindow !== undefined && (!Number.isSafeInteger(contextWindow) || contextWindow < 2048)) {
13
- throw new Error('ANYSWARM_CONTEXT_WINDOW must be the configured model context limit, at least 2048 tokens.');
14
- }
15
- const model = {
16
- provider: env.ANYSWARM_MODEL_PROVIDER ?? 'openai',
17
- model: env.ANYSWARM_MODEL_ID ?? 'gpt-5-mini',
18
- upstream: { url: env.ANYSWARM_MODEL_URL ?? '', headers: env.ANYSWARM_MODEL_TOKEN ? { authorization: `Bearer ${env.ANYSWARM_MODEL_TOKEN}` } : {} },
19
- ...(protocol === 'chat-completions' ? { protocol } : {}),
20
- ...(contextWindow ? { capabilities: { contextWindow, maxOutputTokens: 1024, tools: true, reasoning: false } } : {}),
21
- };
22
- const connection = {
23
- advertiseHost: resolved.advertiseHost,
24
- modelGateway: { requestTimeoutMs: 90_000, maxOutputTokens: 1024, maxRequests: 32 },
25
- };
26
- const image = resolved.image ?? sdk.workerImageFor('pi');
27
- export default { sandbox, connection, executor: 'pi', image, channel: env.ANYSWARM_FIRST_CHANNEL, model: 'default', models: { default: model } };
34
+ export default firstHarnessConfig();
@@ -0,0 +1,14 @@
1
+ {
2
+ "apiVersion": 1,
3
+ "entry": "harness.ts",
4
+ "files": [
5
+ "harness.ts",
6
+ "config.ts",
7
+ "handoff.ts",
8
+ "session.ts",
9
+ "tsconfig.json",
10
+ "input/README.md",
11
+ "README.md",
12
+ "AGENTS.md"
13
+ ]
14
+ }
@@ -7,12 +7,12 @@ const record = {
7
7
  required: ['reference', 'question'], additionalProperties: false,
8
8
  };
9
9
  export const handoffInterface = {
10
- description: 'Publish a release reference and user question for the next Agent.',
10
+ description: 'Publish a release reference and an optional client question for the next Agent.',
11
11
  operations: {
12
- publish: { description: 'Save the release reference and ask the user for a channel.',
12
+ publish: { description: 'Save the release reference and a question for clients that support channel questions.',
13
13
  usage: 'After reading release-data.txt.', inputSchema: record, outputSchema: record, idempotent: true },
14
14
  take: { description: 'Fetch the reference and question together.',
15
- usage: 'After the Harness gives you the user’s answer.', sideEffect: 'read', outputSchema: record },
15
+ usage: 'After the Harness supplies the preset or answered release channel.', sideEffect: 'read', outputSchema: record },
16
16
  },
17
17
  };
18
18
  export function createHandoff() {
@@ -1,13 +1,23 @@
1
+ import { type HarnessJson } from '@anyswarm/core';
1
2
  declare const firstHarness: {
2
3
  id: string;
3
4
  apiVersion: 1;
4
5
  questions: true;
5
6
  run(context: import("@anyswarm/core").HarnessContext): Promise<{
6
- outcome: "cancelled" | "completed" | "failed";
7
+ outcome: 'completed' | 'failed' | 'cancelled';
7
8
  reason: string;
9
+ export?: {
10
+ status: 'complete' | 'failed' | 'pending';
11
+ receipt?: HarnessJson;
12
+ };
13
+ cleanup: {
14
+ status: 'complete' | 'pending';
15
+ receipt?: HarnessJson;
16
+ pending?: HarnessJson;
17
+ retained?: HarnessJson;
18
+ };
8
19
  result: {
9
- runtimeId: string;
10
- failure: {
20
+ verificationFailure: {
11
21
  stage: string;
12
22
  code: string;
13
23
  } | null;
@@ -29,21 +39,7 @@ declare const firstHarness: {
29
39
  } | {
30
40
  status: string;
31
41
  };
32
- artifacts: {
33
- path: string;
34
- sha256: string;
35
- }[];
36
- export?: {
37
- status: "complete" | "failed" | "pending";
38
- } | undefined;
39
- cleanup: {
40
- status: "complete" | "pending";
41
- pending: {
42
- id: string;
43
- kind: "agent" | "backend" | "bridge" | "model" | "report" | "service";
44
- action: "archive-session" | "await-startup" | "close" | "collect-artifacts" | "delete-sandbox" | "retire-service" | "save" | "stop-execution";
45
- }[];
46
- };
42
+ artifacts: HarnessJson[];
47
43
  }>;
48
44
  };
49
45
  export default firstHarness;