@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
@@ -94,10 +94,11 @@ function header(title, description) {
94
94
  const outputs = new Map();
95
95
  function output(file, text) { outputs.set(`${outputDir}/${file}`, `${text.trimEnd()}\n`); }
96
96
  const researchSource = 'examples/autoresearch/project.ts';
97
- let researchDoc = header('AutoResearch peer instructions', 'All peers receive the same Profile instructions. Their first native input uses the peer label, trusted configuration goal and the Run input. Each later turn uses a fixed nudge. An immutable patch can trigger a review notice by active steer or in the next regular input. The demo objective is also the default Run input.');
97
+ let researchDoc = header('AutoResearch peer instructions', 'All peers receive the same Profile instructions. Their first native input uses the peer label, trusted configuration goal and the Run input. Later native inputs choose a fixed nudge based on the shared train allowance. An immutable patch can trigger a review notice by active steer or appended to the next regular input. The demo objective is also the default Run input.');
98
98
  researchDoc += block('Shared Profile instruction', evaluate('`' + between(researchSource, 'const instructions = `', '`;') + '`', { candidatePath: '.anyswarm-candidate.patch' }));
99
99
  researchDoc += block('Initial peer input', evaluate('`' + between(researchSource, '? `', '`\n', 'const prompt = turn === 0') + '`', { label: '<PEER_LABEL>', config: { goal: '<RESEARCH_GOAL>' }, context: { input: { prompt: '<RUN_INPUT>' } } }));
100
- researchDoc += block('Follow-up peer input', between(researchSource, ": '", "';", "? `You are "));
100
+ researchDoc += block('Follow-up peer input while train is available', between(researchSource, ": '", "';", 'const remainingWork = trainExhausted'));
101
+ researchDoc += block('Follow-up peer input after the train budget is used', between(researchSource, "? '", "'\n", 'const remainingWork = trainExhausted'));
101
102
  researchDoc += block('Candidate review notice', evaluate('`' + between(researchSource, 'return `', '`;', 'function reviewNotice') + '`', { candidate: '<CANDIDATE_ID>', sha256: '<CANDIDATE_SHA256>' }));
102
103
  researchDoc += block('FrontierCS-2 demo objective', between('examples/autoresearch/config.ts', "export const demoGoal = '", "';"));
103
104
  output('22-autoresearch.md', researchDoc);
@@ -343,16 +344,23 @@ output('11-first-sdk-harness.md', '# First SDK Harness prompts\n\n'
343
344
  ].join('\n'), 'Startup discovery includes the purpose and the description for the operation granted to that Agent.'));
344
345
  const parallelHost = 'examples/parallel-swarm/harness.ts';
345
346
  const parallelService = 'examples/parallel-swarm/board-service.ts';
347
+ const parallelLiteral = (name) => evaluate(between(parallelHost, `const ${name} = `, ';\n'));
348
+ const researchFocuses = parallelLiteral('researchFocuses');
349
+ const researchTemplate = between(parallelHost, 'runInput(runtime, peer.id,\n `', '`,');
350
+ const synthesisTemplate = between(parallelHost, 'runInput(runtime, synth.id, `', '`,');
351
+ const parallelInput = { input: { prompt: '<ORIGINAL_USER_PROMPT>' } };
346
352
  output('16-parallel-swarm.md', '# Parallel Swarm prompts\n\n'
347
- + block('Researcher Profile', between(parallelHost, "const researcherPrompt = '", "';"))
348
- + block('Synthesizer Profile', between(parallelHost, "const synthesizerPrompt = '", "';"))
349
- + block('First research round', '<ORIGINAL_USER_PROMPT>', 'Each researcher receives the prompt supplied in the Run input.')
350
- + block('Peer review round', between(parallelHost, "const reviewInput = '", "';"))
351
- + block('Synthesis round', between(parallelHost, "const synthesisInput = '", "';"))
353
+ + block('Researcher Profile', parallelLiteral('researcherPrompt'))
354
+ + block('Synthesizer Profile', parallelLiteral('synthesizerPrompt'))
355
+ + researchFocuses.map((_, index) => block(`First research round: researcher ${index + 1}`, evaluate('`' + researchTemplate + '`', { context: parallelInput, researchFocuses, index }), 'The user question comes from context.input.prompt; the focus is selected by this researcher’s host-assigned index.')).join('\n')
356
+ + block('Peer review round', parallelLiteral('reviewInput'), 'The host sends this to all three original researchers only after every first-round contribution passes.')
357
+ + block('Synthesis round', evaluate('`' + synthesisTemplate + '`', {
358
+ synthesisInput: parallelLiteral('synthesisInput'), context: parallelInput,
359
+ }))
352
360
  + block('Board discovery', [
353
- between(parallelService, "purpose: '", "',"),
354
- between(parallelService, "description: '", "',", "operation: 'publish',"),
355
- between(parallelService, "description: '", "',", "operation: 'search',"),
361
+ evaluate(between(parallelService, 'purpose: ', ',\n')),
362
+ evaluate(between(parallelService, 'description: ', ',\n', "operation: 'publish',")),
363
+ evaluate(between(parallelService, 'description: ', ',\n', "operation: 'search',")),
356
364
  ].join('\n'), 'Each Profile receives guidance for the admitted operations. The shared board stores the actual authenticated caller.'));
357
365
  const durableBoardPath = 'examples/services/persistent-board/run.ts';
358
366
  output('17-persistent-board.md', header('Persistent Board Service example prompts', 'The standalone Board example uses the regular startup prompt with distinct grants. It sends publication, independent reading, and reading after publisher replacement through runInput and Runtime.send. Direct and code select an empty local tool set. CLI selects Bash.')
@@ -91,6 +91,9 @@ export declare function resolveLocalDocker(): Promise<{
91
91
  engineVersion: string | undefined;
92
92
  }>;
93
93
  export declare function checkLocalDocker(): Promise<{
94
+ diagnostic: DiagnosticCheck;
95
+ docker?: undefined;
96
+ } | {
94
97
  docker: {
95
98
  socket: string;
96
99
  advertiseHost: string | undefined;
@@ -100,9 +103,6 @@ export declare function checkLocalDocker(): Promise<{
100
103
  engineVersion: string | undefined;
101
104
  };
102
105
  diagnostic: DiagnosticCheck;
103
- } | {
104
- docker?: undefined;
105
- diagnostic: DiagnosticCheck;
106
106
  }>;
107
107
  export declare function discoverMacCallback(image: string, signal?: AbortSignal): Promise<string>;
108
108
  export declare function checkLocalProvider(config: LocalEnvironmentConfig, { requireAuth, managed }?: {
@@ -95,6 +95,11 @@ export async function resolveLocalDocker() {
95
95
  export async function checkLocalDocker() {
96
96
  try {
97
97
  const docker = await resolveLocalDocker();
98
+ const version = /^(\d+)\.(\d+)\./.exec(docker.engineVersion ?? '');
99
+ if (!darwin && docker.rootless && version &&
100
+ (Number(version[1]) < 29 || (Number(version[1]) === 29 && Number(version[2]) < 5))) {
101
+ return { diagnostic: check('host.docker-engine', false, `Rootless Docker Engine ${docker.engineVersion} cannot expose the local OpenSandbox host-network port to this host.`, 'Use Docker Engine 29.5 or newer, a rootful local Docker context, or an existing OpenSandbox endpoint.') };
102
+ }
98
103
  const engine = [`Linux Docker Engine`, docker.engineVersion, `(${docker.rootless ? 'rootless' : 'rootful'})`].filter(Boolean).join(' ');
99
104
  const client = docker.clientVersion ? `Docker CLI ${docker.clientVersion}` : '';
100
105
  const context = docker.context ? `context ${docker.context}` : '';
@@ -344,7 +349,7 @@ async function ensureLocalProviderLocked(config, { signal } = {}) {
344
349
  if (error.code !== 'EEXIST')
345
350
  throw error;
346
351
  }
347
- config = { ...config, apiKey: resolveSandboxConnection({ lifecycleBaseUrl: config.lifecycleBaseUrl }).apiKey };
352
+ config = { ...config, apiKey: resolveSandboxConnection({ lifecycleBaseUrl: config.lifecycleBaseUrl }, undefined, { discoverHost: false }).apiKey };
348
353
  }
349
354
  if (!config.apiKey)
350
355
  throw new Error('Could not load the owner-only OpenSandbox lifecycle key.');
@@ -11,6 +11,7 @@ import { checkLocalExecutor, findExecutorEntry } from '../src/core/sandbox/local
11
11
  import { resolveFilePolicy } from '../src/core/file-policy.js';
12
12
  import { claimOpenSandboxBackend, createSandbox } from '../src/core/sandbox/opensandbox-backend.js';
13
13
  import { snapshotModel } from '../src/core/model/model-access.js';
14
+ import { readSubagentsModel } from '../examples/subagents/model.js';
14
15
  import { modelClientProtocol } from '../src/core/model/model-transport.js';
15
16
  import { loadAnySwarmConfig, loopbackLifecycle, saveSandboxConnection } from '../src/core/sandbox/sandbox-connection.js';
16
17
  function modelState(config, executor) {
@@ -216,13 +217,16 @@ export async function runLocalCommand(command, signal, progress) {
216
217
  checks.push({ id: 'config.executor', ok: false, detail: 'Select a configured executor.' });
217
218
  return report;
218
219
  }
220
+ stage = 'connection';
221
+ const configuredPublicUrl = config?.connection?.publicUrl ?? config?.connection?.bridge?.publicUrl ?? config?.connection?.modelGateway?.publicUrl;
219
222
  const environment = await resolveLocalEnvironment({
220
223
  ...config?.sandbox,
221
224
  ...(command.command === 'setup' && command.endpoint ? { endpoint: command.endpoint, lifecycleBaseUrl: undefined } : {}),
222
- publicUrl: command.command === 'setup' ? command.publicUrl ?? config?.connection?.publicUrl : config?.connection?.publicUrl,
225
+ publicUrl: command.command === 'setup' ? command.publicUrl ?? configuredPublicUrl : configuredPublicUrl,
223
226
  image: config?.image,
224
227
  advertiseHost: config?.connection?.advertiseHost ?? config?.connection?.modelGateway?.advertiseHost,
225
228
  });
229
+ stage = 'config';
226
230
  const hostname = new URL(environment.lifecycleBaseUrl).hostname;
227
231
  const loopback = hostname === 'localhost' || hostname === '[::1]' || hostname.startsWith('127.') && isIP(hostname) === 4;
228
232
  const reuseExisting = loopback && (environment.management === 'existing' ||
@@ -284,25 +288,20 @@ export async function runLocalCommand(command, signal, progress) {
284
288
  }
285
289
  }
286
290
  }
287
- const modelUrl = process.env.ANYSWARM_MODEL_URL || process.env.ANYSWARM_SUBAGENTS_MODEL_URL;
288
- const modelId = process.env.ANYSWARM_MODEL_ID || process.env.ANYSWARM_SUBAGENTS_MODEL_ID;
289
- if (!config && modelUrl && (modelId || driver.kind !== 'codex')) {
290
- const route = {
291
- provider: process.env.ANYSWARM_MODEL_PROVIDER ?? process.env.ANYSWARM_SUBAGENTS_MODEL_PROVIDER ?? 'openai',
292
- model: modelId || 'gpt-5.4', protocol: process.env.ANYSWARM_MODEL_PROTOCOL,
293
- upstream: { url: modelUrl, headers: {} },
294
- };
291
+ if (config) {
292
+ report.model = modelState(config, driver.kind);
293
+ }
294
+ else {
295
295
  try {
296
- snapshotModel(route, driver.kind);
297
- report.model = { configuration: 'complete', verification: 'not-verified' };
296
+ const route = readSubagentsModel(driver.kind);
297
+ if (route)
298
+ snapshotModel(route, driver.kind);
299
+ report.model = { configuration: route ? 'complete' : 'missing', verification: 'not-verified' };
298
300
  }
299
301
  catch {
300
302
  report.model = { configuration: 'invalid', verification: 'not-verified' };
301
303
  }
302
304
  }
303
- else {
304
- report.model = config ? modelState(config, driver.kind) : { configuration: 'missing', verification: 'not-verified' };
305
- }
306
305
  if (report.model.configuration === 'missing') {
307
306
  report.model.remedy = config ? 'Set an upstream endpoint for each active model route in the trusted configuration.'
308
307
  : 'Before running the Quickstart Harness, set ANYSWARM_MODEL_URL and ANYSWARM_MODEL_ID. Set ANYSWARM_MODEL_TOKEN if the endpoint requires authentication.';
@@ -315,7 +314,8 @@ export async function runLocalCommand(command, signal, progress) {
315
314
  if (config && report.model.configuration !== 'invalid') {
316
315
  const { lifecycleBaseUrl, apiKey, endpointHost } = environment;
317
316
  checks.push(checkProjectRuntime({
318
- ...config, executor, connection: { ...config.connection, publicUrl: environment.publicUrl },
317
+ ...config, executor, connection: { ...config.connection, publicUrl: environment.publicUrl,
318
+ advertiseHost: environment.advertiseHost },
319
319
  }, { ...config.sandbox, endpoint: undefined, lifecycleBaseUrl, apiKey, endpointHost }));
320
320
  }
321
321
  report.configuration = {
@@ -324,7 +324,7 @@ export async function runLocalCommand(command, signal, progress) {
324
324
  image: environment.image ?? workerImageFor(executor),
325
325
  filePolicy: resolveFilePolicy(config?.filePolicy),
326
326
  };
327
- const publicUrl = environment.publicUrl ?? config?.connection?.bridge?.publicUrl ?? config?.connection?.modelGateway?.publicUrl;
327
+ const publicUrl = environment.publicUrl;
328
328
  report.connection = {
329
329
  lifecycleBaseUrl: reportedEndpoint(environment.lifecycleBaseUrl),
330
330
  advertiseHost: reportedHost(environment.advertiseHost),
@@ -426,14 +426,21 @@ export async function runLocalCommand(command, signal, progress) {
426
426
  // Configuration imports and provider/npm errors can contain credentials.
427
427
  const failure = {
428
428
  config: ['Could not load the project configuration.', 'Check the trusted config.js and adjacent .env file.'],
429
+ connection: ['Could not resolve the OpenSandbox connection.', 'Check the Lifecycle endpoint and Runtime callback settings.'],
429
430
  host: ['Could not complete the host capability checks.', 'Check the installation diagnostics for the selected setup mode.'],
430
431
  worker: ['Could not prepare the compatible Worker image.', 'Check local Docker and the configured Worker image.'],
431
432
  provider: ['Could not prepare or verify a compatible OpenSandbox provider.', 'Run anyswarm doctor to check lifecycle authentication. Ensure the requested endpoint or local port is available.'],
432
433
  smoke: ['Could not complete the infrastructure probe.', 'Check the local OpenSandbox service, Worker image and host network.'],
433
434
  };
434
435
  let [detail, remedy] = failure[stage];
436
+ let checkId = stage;
435
437
  const code = error?.code;
436
- if (code === 'DOCKER_CALLBACK_UNAVAILABLE') {
438
+ if (code === 'HOST_NETWORK_DISCOVERY_FAILED' && stage === 'connection') {
439
+ checkId = 'host.network-discovery';
440
+ detail = 'Could not inspect host network interfaces for the Sandbox callback address.';
441
+ remedy = 'Set ANYSWARM_ADVERTISE_HOST or ANYSWARM_RUNTIME_PUBLIC_URL to an address reachable from the Sandbox, then rerun the command.';
442
+ }
443
+ else if (code === 'DOCKER_CALLBACK_UNAVAILABLE') {
437
444
  detail = 'The Docker container could not resolve a unique Mac callback IPv4 address.';
438
445
  remedy = 'Check host.docker.internal from the selected local engine, or configure a Runtime publicUrl reachable from the Sandbox.';
439
446
  }
@@ -464,7 +471,7 @@ export async function runLocalCommand(command, signal, progress) {
464
471
  remedy = 'Verify that the selected rootless Docker context can start containers and expose the Lifecycle address. Check delegated CPU and memory controllers before retrying.';
465
472
  }
466
473
  if (!signal.aborted)
467
- checks.push({ id: stage, ok: false, detail, remedy });
474
+ checks.push({ id: checkId, ok: false, detail, remedy });
468
475
  // A provider deployment can fail before returning its ownership handle.
469
476
  if (stage === 'provider' && error && typeof error === 'object' && 'cleanup' in error && error.cleanup && typeof error.cleanup === 'object' &&
470
477
  'id' in error.cleanup && typeof error.cleanup.id === 'string' && 'status' in error.cleanup &&
@@ -4,15 +4,29 @@ import { tmpdir } from 'node:os';
4
4
  import { join, resolve } from 'node:path';
5
5
  import { promisify } from 'node:util';
6
6
  const [destination, ...options] = process.argv.slice(2);
7
- if (!destination || (options.length && options.join(' ') !== '--skip-build')) {
8
- throw new Error('Usage: npm run pack:release -- <output-directory> [--skip-build]');
7
+ let skipBuild = false;
8
+ let releaseVersion;
9
+ for (let index = 0; index < options.length; index++) {
10
+ const option = options[index];
11
+ if (option === '--skip-build' && !skipBuild)
12
+ skipBuild = true;
13
+ else if (option === '--version' && releaseVersion === undefined)
14
+ releaseVersion = options[++index];
15
+ else
16
+ throw new Error(`Unsupported or repeated pack option: ${option}`);
17
+ }
18
+ if (!destination || options.includes('--version') && !releaseVersion) {
19
+ throw new Error('Usage: npm run pack:release -- <output-directory> [--skip-build] [--version <next-version>]');
20
+ }
21
+ if (releaseVersion !== undefined && !/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)-next\.[1-9][0-9]*\.g[a-f0-9]{12}$/.test(releaseVersion)) {
22
+ throw new Error('A staged version override must be an immutable next release version');
9
23
  }
10
24
  // Keep the build and staging umask independent of the caller.
11
25
  process.umask(0o022);
12
26
  const run = promisify(execFile);
13
27
  const repository = resolve(import.meta.dirname, '..');
14
28
  const output = resolve(destination);
15
- if (!options.length) {
29
+ if (!skipBuild) {
16
30
  const build = spawnSync('npm', ['run', 'build'], { cwd: repository, stdio: ['ignore', 2, 2] });
17
31
  if (build.error)
18
32
  throw build.error;
@@ -34,6 +48,16 @@ try {
34
48
  const manifestPath = join(staged, 'package.json');
35
49
  const lockPath = join(staged, 'npm-shrinkwrap.json');
36
50
  const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
51
+ if (releaseVersion) {
52
+ manifest.version = releaseVersion;
53
+ const sourceLock = JSON.parse(await readFile(lockPath, 'utf8'));
54
+ if (sourceLock.lockfileVersion !== 3 || !sourceLock.packages?.['']) {
55
+ throw new Error('Release packaging requires a v3 npm shrinkwrap with root package metadata');
56
+ }
57
+ sourceLock.version = releaseVersion;
58
+ sourceLock.packages[''].version = releaseVersion;
59
+ await writeFile(lockPath, JSON.stringify(sourceLock, null, 2) + '\n');
60
+ }
37
61
  // Service images compile TypeScript. The Pi installation belongs to the executor.
38
62
  delete manifest.devDependencies?.['@earendil-works/pi-coding-agent'];
39
63
  await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
@@ -129,7 +129,7 @@ function planRuntimeWorker(options, config, profiles, recoveryDirectory) {
129
129
  }
130
130
  return { kind: worker.executor, prepare: async () => worker };
131
131
  }
132
- const { localExecutor } = resolveSandboxConnectionWithSources({ lifecycleBaseUrl: endpoint });
132
+ const { localExecutor } = resolveSandboxConnectionWithSources({ lifecycleBaseUrl: endpoint }, undefined, { discoverHost: false });
133
133
  const kind = options.executor ? config.driver.kind : selectors.find(selector => selector.kind)?.kind ?? localExecutor?.kind ?? config.driver.kind;
134
134
  if (kind !== 'pi' && kind !== 'codex')
135
135
  throw executorFailure('Select Pi or Codex for the built-in local Worker.');
@@ -11,7 +11,7 @@ import { isDeepStrictEqual } from 'node:util';
11
11
  import { isIP } from 'node:net';
12
12
  import { lookup } from 'node:dns/promises';
13
13
  import { createWorkerEventPoll } from '../worker-event-poll.js';
14
- import { loopbackLifecycle, normalizeRuntimePublicUrl, resolveSandboxConnection } from './sandbox-connection.js';
14
+ import { discoverDockerCallbackHost, loopbackLifecycle, normalizeRuntimePublicUrl, resolveSandboxConnection } from './sandbox-connection.js';
15
15
  import { validId } from '../config.js';
16
16
  import { adaptSandboxProvider, createApiOpenSandboxProvider } from './opensandbox-provider.js';
17
17
  const sandboxes = new WeakMap();
@@ -111,7 +111,9 @@ export function createSandbox(config = {}) {
111
111
  }
112
112
  }
113
113
  const { lifecycleBaseUrl: _alias, endpoint: _endpoint, endpointHost: _endpointHost, ...settings } = sandbox;
114
- const { lifecycleBaseUrl, apiKey, publicUrl, advertiseHost, useServerProxy, egressMode } = resolveSandboxConnection(sandbox);
114
+ // Runtime callback options are supplied at claim time, after this handle is
115
+ // created. Snapshot configured settings here without enumerating interfaces.
116
+ const { lifecycleBaseUrl, apiKey, publicUrl, advertiseHost, useServerProxy, egressMode } = resolveSandboxConnection(sandbox, undefined, { discoverHost: false });
115
117
  sandboxes.set(handle, freeze(structuredClone({
116
118
  sandbox: { ...settings, lifecycleBaseUrl, apiKey, publicUrl, advertiseHost, useServerProxy, egressMode, timeoutSeconds },
117
119
  isolation: { network: 'api' },
@@ -136,10 +138,14 @@ export function claimOpenSandboxBackend(handle, options) {
136
138
  const port = connection?.bindPort ?? 0;
137
139
  if (!Number.isSafeInteger(port) || port < 0 || port > 65_535)
138
140
  throw invalid('connection.bindPort must be from 0 through 65535');
139
- const advertiseHost = connection?.advertiseHost ?? gateway?.advertiseHost ?? settings.sandbox.advertiseHost ??
140
- ((settings.sandbox.lifecycleBaseUrl && loopbackLifecycle(settings.sandbox.lifecycleBaseUrl)) || settings.provider ? '172.17.0.1' : undefined);
141
141
  const savedPublicUrl = settings.sandbox.publicUrl;
142
142
  const advertised = [...candidates][0] ?? savedPublicUrl;
143
+ let advertiseHost = connection?.advertiseHost ?? gateway?.advertiseHost ?? settings.sandbox.advertiseHost;
144
+ if (advertiseHost === undefined && settings.provider)
145
+ advertiseHost = '172.17.0.1';
146
+ if (advertiseHost === undefined && !advertised && settings.sandbox.lifecycleBaseUrl && loopbackLifecycle(settings.sandbox.lifecycleBaseUrl)) {
147
+ advertiseHost = discoverDockerCallbackHost() ?? '172.17.0.1';
148
+ }
143
149
  if (!advertised && !advertiseHost)
144
150
  throw invalid('For an existing remote OpenSandbox, set connection.publicUrl to the Runtime address reachable from the Sandbox');
145
151
  const workerHost = advertiseHost ?? new URL(advertised).hostname.replace(/^\[|\]$/g, '');
@@ -19,7 +19,9 @@ interface ConnectionInput {
19
19
  preparedImage?: string;
20
20
  }
21
21
  export declare function normalizeRuntimePublicUrl(value: string): string;
22
- export declare function resolveSandboxConnectionWithSources(input?: ConnectionInput, scope?: string, { useSaved }?: {
22
+ export declare function discoverDockerCallbackHost(): string | undefined;
23
+ export declare function resolveSandboxConnectionWithSources(input?: ConnectionInput, scope?: string, { useSaved, discoverHost }?: {
24
+ discoverHost?: boolean | undefined;
23
25
  useSaved?: boolean | undefined;
24
26
  }): {
25
27
  lifecycleBaseUrl: string;
@@ -42,7 +44,11 @@ export declare function resolveSandboxConnectionWithSources(input?: ConnectionIn
42
44
  image: string | undefined;
43
45
  };
44
46
  };
45
- export declare function resolveSandboxConnection(...settings: Parameters<typeof resolveSandboxConnectionWithSources>): {
47
+ export declare function resolveSandboxConnection(input?: ConnectionInput, scope?: string, { useSaved, discoverHost, includePreparedImage }?: {
48
+ discoverHost?: boolean | undefined;
49
+ includePreparedImage?: boolean | undefined;
50
+ useSaved?: boolean | undefined;
51
+ }): {
46
52
  lifecycleBaseUrl: string;
47
53
  apiKey: string | undefined;
48
54
  advertiseHost: string | undefined;
@@ -53,6 +59,7 @@ export declare function resolveSandboxConnection(...settings: Parameters<typeof
53
59
  endpointHost: undefined;
54
60
  endpointSource: string;
55
61
  executor: import("../backend-config.js").ExecutorKind | undefined;
62
+ preparedImage?: string | undefined;
56
63
  };
57
64
  export declare function saveSandboxConnection(input: ConnectionInput & {
58
65
  lifecycleBaseUrl: string;
@@ -126,7 +126,16 @@ function loadSavedConnection() {
126
126
  }
127
127
  return saved;
128
128
  }
129
- export function resolveSandboxConnectionWithSources(input = {}, scope, { useSaved = true } = {}) {
129
+ export function discoverDockerCallbackHost() {
130
+ try {
131
+ return networkInterfaces().docker0?.find(item => item.family === 'IPv4')?.address;
132
+ }
133
+ catch {
134
+ throw Object.assign(new Error('Could not inspect host network interfaces for the Sandbox callback address. ' +
135
+ 'Set ANYSWARM_ADVERTISE_HOST or ANYSWARM_RUNTIME_PUBLIC_URL to an address reachable from the Sandbox.'), { code: 'HOST_NETWORK_DISCOVERY_FAILED' });
136
+ }
137
+ }
138
+ export function resolveSandboxConnectionWithSources(input = {}, scope, { useSaved = true, discoverHost = true } = {}) {
130
139
  const environment = process.env;
131
140
  const example = (name) => scope ? environment[`ANYSWARM_${scope}_${name}`] || undefined : undefined;
132
141
  const explicit = input.endpoint === undefined ? undefined : lifecycleUrl(input.endpoint, 'endpoint');
@@ -163,12 +172,17 @@ export function resolveSandboxConnectionWithSources(input = {}, scope, { useSave
163
172
  if (endpointHost !== undefined)
164
173
  throw connectionError('endpointHost was removed. Configure OpenSandbox to publish a reachable endpoint.');
165
174
  const publicUrl = input.publicUrl ?? (environment.ANYSWARM_RUNTIME_PUBLIC_URL || undefined) ?? stored.publicUrl;
175
+ const normalizedPublicUrl = publicUrl === undefined ? undefined : normalizeRuntimePublicUrl(publicUrl);
166
176
  const from = (settings) => settings.find(([, value]) => value !== undefined && value !== '');
167
- const callback = from([
177
+ let callback = from([
168
178
  ['config', input.advertiseHost], ['ANYSWARM_ADVERTISE_HOST', environment.ANYSWARM_ADVERTISE_HOST],
169
179
  [`ANYSWARM_${scope}_ADVERTISE_HOST`, example('ADVERTISE_HOST')], ['saved', stored.advertiseHost],
170
- ['docker0', local ? networkInterfaces().docker0?.find(address => address.family === 'IPv4')?.address : undefined],
171
180
  ]);
181
+ if (discoverHost && !callback && !normalizedPublicUrl && local) {
182
+ const address = discoverDockerCallbackHost();
183
+ if (address)
184
+ callback = ['docker0', address];
185
+ }
172
186
  const worker = from([
173
187
  ['config', input.image], ['ANYSWARM_WORKER_IMAGE', environment.ANYSWARM_WORKER_IMAGE],
174
188
  [`ANYSWARM_${scope}_IMAGE`, example('IMAGE')], ['saved', stored.image],
@@ -179,7 +193,7 @@ export function resolveSandboxConnectionWithSources(input = {}, scope, { useSave
179
193
  environment.OPENSANDBOX_API_KEY || undefined) ?? stored.apiKey ?? (local && readPrivateFile(localApiKeyPath(local), 256)),
180
194
  advertiseHost: callback?.[1],
181
195
  advertiseHostDiscovery: callback?.[0] === 'saved' ? stored.advertiseHostDiscovery : undefined,
182
- publicUrl: publicUrl === undefined ? undefined : normalizeRuntimePublicUrl(publicUrl),
196
+ publicUrl: normalizedPublicUrl,
183
197
  image: worker?.[1],
184
198
  useServerProxy: input.useServerProxy ?? stored.useServerProxy,
185
199
  egressMode: input.egressMode ?? stored.egressMode,
@@ -192,9 +206,10 @@ export function resolveSandboxConnectionWithSources(input = {}, scope, { useSave
192
206
  sources: { lifecycleBaseUrl: endpointSource, advertiseHost: callback?.[0], image: worker?.[0] },
193
207
  };
194
208
  }
195
- export function resolveSandboxConnection(...settings) {
196
- const { sources: _sources, advertiseHostDiscovery: _discovery, management: _management, providerId: _providerId, localExecutor, preparedImage: _preparedImage, ...connection } = resolveSandboxConnectionWithSources(...settings);
197
- return { ...connection, executor: localExecutor?.kind };
209
+ export function resolveSandboxConnection(input, scope, { useSaved = true, discoverHost = true, includePreparedImage = false } = {}) {
210
+ const { sources: _sources, advertiseHostDiscovery: _discovery, management: _management, providerId: _providerId, localExecutor, preparedImage, ...connection } = resolveSandboxConnectionWithSources(input, scope, { useSaved, discoverHost });
211
+ return { ...connection, executor: localExecutor?.kind,
212
+ ...(includePreparedImage && preparedImage ? { preparedImage } : {}) };
198
213
  }
199
214
  export async function saveSandboxConnection(input) {
200
215
  const path = connectionPath();
@@ -4,7 +4,8 @@ import { loadAnySwarmConfig } from '../core/sandbox/sandbox-connection.js';
4
4
  import { createHash, randomUUID } from 'node:crypto';
5
5
  import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises';
6
6
  import { registerHooks } from 'node:module';
7
- import { homedir, tmpdir } from 'node:os';
7
+ import { tmpdir } from 'node:os';
8
+ import { defaultRunRoot } from '../trace-viewer/run-root.mjs';
8
9
  import { extname, isAbsolute, join, resolve } from 'node:path';
9
10
  import { pathToFileURL } from 'node:url';
10
11
  import { captureProject, isInside, projectError, ProjectPreflightError, resolveProjectDirectory } from './project-input.js';
@@ -111,7 +112,7 @@ async function prepareOutput(runId, options, cwd) {
111
112
  await mkdir(path, { recursive: true, mode: 0o700 });
112
113
  return await realpath(path);
113
114
  }
114
- const stateDirectory = resolve(process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'anyswarm', 'runs');
115
+ const stateDirectory = defaultRunRoot();
115
116
  if (!isInside(cwd, stateDirectory)) {
116
117
  const stateRoot = await mkdir(stateDirectory, { recursive: true, mode: 0o700 })
117
118
  .then(() => realpath(stateDirectory)).catch(() => null);
@@ -4,6 +4,19 @@ import { projectError } from './project-input.js';
4
4
  import { readRpcLines } from './project-rpc-lines.js';
5
5
  import { MAX_COMMAND_BYTES } from './foreground-commands.js';
6
6
  import { HarnessEventStream } from './harness-event-stream.js';
7
+ // These launch errors contain public Host explanations, not author exceptions.
8
+ const startupMessageCodes = new Set(['HARNESS_MODULE_LOAD_FAILED', 'INVALID_HARNESS_MODULE',
9
+ 'INVALID_HARNESS_SESSION', 'INVALID_RUN_CONFIGURATION', 'INVALID_REQUEST']);
10
+ function startupError(record) {
11
+ if (typeof record.code !== 'string' || !/^[A-Za-z0-9_.:-]{1,128}$/.test(record.code)) {
12
+ throw new Error('Invalid RPC startup error');
13
+ }
14
+ const message = startupMessageCodes.has(record.code) && typeof record.message === 'string'
15
+ ? record.message.slice(0, 4096).replace(/[\p{Cc}\p{Cf}]/gu, (character) => '\\u' + character.charCodeAt(0).toString(16).padStart(4, '0'))
16
+ : 'Harness RPC startup failed';
17
+ const diagnostic = parseErrorDiagnostic(record.diagnostic);
18
+ return Object.assign(projectError(record.code, message), diagnostic ? frameworkErrorFields({ ...record, diagnostic }) : {});
19
+ }
7
20
  export class HarnessRpcClient {
8
21
  ready;
9
22
  agents;
@@ -16,6 +29,7 @@ export class HarnessRpcClient {
16
29
  #timeout;
17
30
  #prefix = randomUUID();
18
31
  #next = 0;
32
+ #readyConfirmed = false;
19
33
  #started = false;
20
34
  #failure;
21
35
  #resultConfirmed = false;
@@ -141,11 +155,16 @@ export class HarnessRpcClient {
141
155
  case 'ready':
142
156
  if (record.version !== 'v1' || !record.harness || !record.status || !record.descriptor)
143
157
  throw new Error('Invalid RPC handshake');
158
+ this.#readyConfirmed = true;
144
159
  this.#started ||= typeof record.status.runId === 'string';
145
160
  this.#ready.resolve(record);
146
161
  break;
147
162
  case 'reply':
148
163
  case 'error': {
164
+ if (record.type === 'error' && record.id === undefined && !this.#readyConfirmed) {
165
+ this.#disconnect(startupError(record));
166
+ break;
167
+ }
149
168
  const pending = this.#pending.get(record.id);
150
169
  if (!pending)
151
170
  break;
@@ -1,2 +1,4 @@
1
1
  /** Enable trusted author TypeScript without changing the author's package scope. */
2
2
  export declare function installSourceLoader(): void;
3
+ /** Compile author source without lowering the JavaScript syntax supported by the running Node. */
4
+ export declare function transformAuthorSource(source: string, filename: string): string;
@@ -1,14 +1,13 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
- import { registerHooks, stripTypeScriptTypes } from 'node:module';
2
+ import { createRequire, registerHooks } from 'node:module';
3
3
  import { fileURLToPath } from 'node:url';
4
+ const require = createRequire(import.meta.url);
4
5
  let installed = false;
5
6
  /** Enable trusted author TypeScript without changing the author's package scope. */
6
7
  export function installSourceLoader() {
7
8
  if (installed)
8
9
  return;
9
10
  installed = true;
10
- // Node 22.19+ supports transformation and inline maps, including enums.
11
- const transform = stripTypeScriptTypes;
12
11
  const sdk = new URL('../core/index.js', import.meta.url).href;
13
12
  registerHooks({
14
13
  resolve(specifier, context, nextResolve) {
@@ -21,8 +20,11 @@ export function installSourceLoader() {
21
20
  throw error;
22
21
  if (specifier === '@anyswarm/core')
23
22
  return { url: sdk, shortCircuit: true };
24
- if (context.parentURL?.startsWith('file:') && /^(?:\.{1,2}\/|\/)/.test(specifier) && /\.m?js$/.test(specifier)) {
25
- const source = new URL(specifier.replace(/\.m?js$/, match => match === '.mjs' ? '.mts' : '.ts'), context.parentURL);
23
+ const source = specifier.startsWith('file:') ? new URL(specifier)
24
+ : context.parentURL?.startsWith('file:') && /^(?:\.{1,2}\/|\/)/.test(specifier)
25
+ ? new URL(specifier, context.parentURL) : undefined;
26
+ if (source && /\.m?js$/.test(source.pathname)) {
27
+ source.pathname = source.pathname.replace(/\.m?js$/, match => match === '.mjs' ? '.mts' : '.ts');
26
28
  if (existsSync(source))
27
29
  return { url: source.href, shortCircuit: true };
28
30
  }
@@ -32,10 +34,26 @@ export function installSourceLoader() {
32
34
  load(url, context, nextLoad) {
33
35
  if (!url.startsWith('file:') || !/\.(?:ts|mts)$/.test(new URL(url).pathname))
34
36
  return nextLoad(url, context);
35
- const source = transform(readFileSync(fileURLToPath(url), 'utf8'), {
36
- mode: 'transform', sourceMap: true, sourceUrl: url,
37
- });
37
+ const filename = fileURLToPath(url);
38
+ const source = transformAuthorSource(readFileSync(filename, 'utf8'), filename);
38
39
  return { format: 'module', source, shortCircuit: true };
39
40
  },
40
41
  });
41
42
  }
43
+ /** Compile author source without lowering the JavaScript syntax supported by the running Node. */
44
+ export function transformAuthorSource(source, filename) {
45
+ const { transformSync } = require('@swc/wasm');
46
+ // The WASM transformer accepts these options even though its declarations lag the runtime.
47
+ const options = {
48
+ filename,
49
+ isModule: true,
50
+ sourceMaps: 'inline',
51
+ jsc: {
52
+ target: 'esnext',
53
+ parser: { syntax: 'typescript' },
54
+ transform: { verbatimModuleSyntax: true },
55
+ },
56
+ module: { type: 'es6' },
57
+ };
58
+ return transformSync(source, options).code;
59
+ }
@@ -1,9 +1,11 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { parseArgs } from 'node:util';
3
+ import { defaultRunRoot } from './run-root.mjs';
3
4
 
4
5
  export const traceUsage = [
5
- 'Usage: anyswarm trace --root <runs-dir> [--port 8787] [--open]',
6
+ 'Usage: anyswarm trace [--root <runs-dir>] [--port 8787] [--open]',
6
7
  ' anyswarm trace <runs-dir> [--port 8787] [--open]',
8
+ 'Default root: ${XDG_STATE_HOME:-$HOME/.local/state}/anyswarm/runs',
7
9
  ].join('\n');
8
10
 
9
11
  function openBrowser(url) {
@@ -46,8 +48,8 @@ export async function runTraceCommand(args) {
46
48
  console.log(traceUsage);
47
49
  return null;
48
50
  }
49
- const root = values.root ?? positionals[0];
50
- if (!root) throw new Error('--root is required');
51
+ const root = values.root ?? positionals[0] ?? defaultRunRoot();
52
+ if (!root) throw new Error('--root must not be empty');
51
53
  if (positionals.length > 1) {
52
54
  throw new Error('Unexpected positional argument: ' + positionals[1]);
53
55
  }
@@ -67,6 +69,7 @@ export async function runTraceCommand(args) {
67
69
  throw error;
68
70
  }
69
71
  console.log('AnySwarm Trace Viewer listening at ' + viewer.url);
72
+ console.log('Run root: ' + viewer.root);
70
73
  const actualPort = new URL(viewer.url).port;
71
74
  const sshHint = formatSshHint(actualPort);
72
75
  if (sshHint) console.log(sshHint);