@anyswarm/core 0.5.1 → 0.5.2

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 (171) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +13 -6
  3. package/dist/examples/README.md +16 -5
  4. package/dist/examples/authoring/README.md +4 -4
  5. package/dist/examples/autoresearch/README.md +15 -8
  6. package/dist/examples/autoresearch/REQUIREMENTS.zh.md +3 -10
  7. package/dist/examples/autoresearch/demo.js +1 -1
  8. package/dist/examples/autoresearch/eject.json +2 -0
  9. package/dist/examples/autoresearch/frontiercs2-config.d.ts +2 -0
  10. package/dist/examples/autoresearch/frontiercs2-config.js +3 -0
  11. package/dist/examples/autoresearch/prepare-demo.d.ts +1 -0
  12. package/dist/examples/autoresearch/prepare-demo.js +15 -0
  13. package/dist/examples/autoresearch/prepare.js +3 -3
  14. package/dist/examples/autoresearch/project.d.ts +0 -94
  15. package/dist/examples/autoresearch/project.js +2 -20
  16. package/dist/examples/code/README.md +25 -17
  17. package/dist/examples/code/REQUIREMENTS.zh.md +3 -3
  18. package/dist/examples/harness-session/README.md +3 -3
  19. package/dist/examples/messages/README.md +1 -1
  20. package/dist/examples/notes/README.md +3 -3
  21. package/dist/examples/services/mathlib-search/README.md +1 -1
  22. package/dist/examples/services/persistent-board/README.md +5 -2
  23. package/dist/examples/subagents/README.md +2 -2
  24. package/dist/examples/subagents/config.js +3 -3
  25. package/dist/examples/substrate/README.md +2 -2
  26. package/dist/examples/super/README.md +34 -22
  27. package/dist/examples/super/actions.d.ts +1 -1
  28. package/dist/examples/super/actions.js +11 -11
  29. package/dist/examples/super/config.js +3 -3
  30. package/dist/examples/super/eject.json +1 -1
  31. package/dist/examples/super/location.js +1 -1
  32. package/dist/examples/super/operator.d.ts +1 -0
  33. package/dist/examples/super/operator.js +31 -0
  34. package/dist/examples/super/project.d.ts +0 -107
  35. package/dist/examples/super/project.js +1 -3
  36. package/dist/scripts/anyswarm-arguments.d.ts +7 -25
  37. package/dist/scripts/anyswarm-arguments.js +69 -97
  38. package/dist/scripts/anyswarm-eject.js +1 -1
  39. package/dist/scripts/anyswarm-harnesses.d.ts +0 -1
  40. package/dist/scripts/anyswarm-harnesses.js +1 -22
  41. package/dist/scripts/anyswarm-installation.d.ts +7 -40
  42. package/dist/scripts/anyswarm-installation.js +17 -291
  43. package/dist/scripts/anyswarm-launch.d.ts +6 -36
  44. package/dist/scripts/anyswarm-launch.js +32 -81
  45. package/dist/scripts/anyswarm-progress.d.ts +6 -0
  46. package/dist/scripts/anyswarm-progress.js +102 -0
  47. package/dist/scripts/anyswarm-project.d.ts +1 -9
  48. package/dist/scripts/anyswarm-project.js +40 -127
  49. package/dist/scripts/anyswarm-source-runner.js +9 -41
  50. package/dist/scripts/anyswarm.js +6 -26
  51. package/dist/scripts/build-provenance.json +1 -1
  52. package/dist/scripts/local-environment.d.ts +10 -4
  53. package/dist/scripts/local-environment.js +67 -20
  54. package/dist/scripts/local-setup.d.ts +3 -0
  55. package/dist/scripts/local-setup.js +135 -107
  56. package/dist/scripts/pack-release.js +4 -1
  57. package/dist/src/core/worker-image.js +1 -1
  58. package/dist/src/harness/project-harness.d.ts +1 -0
  59. package/dist/src/harness/project-harness.js +2 -2
  60. package/dist/src/harness/project-runtime.js +3 -1
  61. package/docs/INDEX.md +2 -1
  62. package/docs/architecture/04-services.md +1 -1
  63. package/docs/architecture/07-run-configuration.md +28 -14
  64. package/docs/architecture/12-code-coverage.md +56 -57
  65. package/docs/architecture/17-harness-reporting.md +1 -1
  66. package/docs/architecture/22-website.md +4 -7
  67. package/docs/architecture/23-project-harness.md +48 -23
  68. package/docs/architecture/26-code.md +20 -5
  69. package/docs/architecture/27-personal.md +23 -8
  70. package/docs/architecture/28-autoresearch.md +18 -6
  71. package/docs/architecture/INDEX.md +1 -2
  72. package/docs/architecture/prompts/source-manifest.json +5 -5
  73. package/docs/architecture/source-map.json +51 -71
  74. package/docs/designs/core-harness/01-core.md +2 -2
  75. package/docs/designs/core-harness/06-project-harness.md +3 -3
  76. package/docs/designs/core-harness/README.md +2 -2
  77. package/docs/en/agents.md +1 -1
  78. package/docs/en/build-your-harness.md +1 -1
  79. package/docs/en/changelog.md +7 -0
  80. package/docs/en/first-harness.md +6 -6
  81. package/docs/en/harnesses/lead-worker.md +1 -1
  82. package/docs/en/harnesses/peermesh.md +2 -2
  83. package/docs/en/harnesses/subagents.md +2 -2
  84. package/docs/en/harnesses/substrate.md +4 -4
  85. package/docs/en/harnesses/taskpool.md +2 -2
  86. package/docs/en/latest.md +9 -5
  87. package/docs/en/quickstart.md +20 -41
  88. package/docs/en/reference/api.md +1 -1
  89. package/docs/en/reference/cli.md +47 -85
  90. package/docs/en/sandbox.md +3 -3
  91. package/docs/operations/trace-viewer.md +1 -1
  92. package/docs/third-party-notices.md +0 -1
  93. package/docs/workflows/development.md +14 -12
  94. package/docs/workflows/release-and-docs-versioning.md +13 -12
  95. package/docs/workflows/release-cli-acceptance.md +85 -0
  96. package/docs/zh/agents.md +1 -1
  97. package/docs/zh/build-your-harness.md +1 -1
  98. package/docs/zh/changelog.md +8 -1
  99. package/docs/zh/first-harness.md +7 -7
  100. package/docs/zh/harnesses/lead-worker.md +1 -1
  101. package/docs/zh/harnesses/peermesh.md +2 -2
  102. package/docs/zh/harnesses/subagents.md +2 -2
  103. package/docs/zh/harnesses/substrate.md +4 -4
  104. package/docs/zh/harnesses/taskpool.md +2 -2
  105. package/docs/zh/latest.md +9 -5
  106. package/docs/zh/quickstart.md +20 -41
  107. package/docs/zh/reference/api.md +1 -1
  108. package/docs/zh/reference/cli.md +19 -79
  109. package/docs/zh/sandbox.md +3 -3
  110. package/examples/README.md +16 -5
  111. package/examples/authoring/README.md +4 -4
  112. package/examples/autoresearch/README.md +15 -8
  113. package/examples/autoresearch/REQUIREMENTS.zh.md +3 -10
  114. package/examples/autoresearch/demo.ts +1 -1
  115. package/examples/autoresearch/eject.json +2 -0
  116. package/examples/autoresearch/frontiercs2-config.ts +4 -0
  117. package/examples/autoresearch/prepare-demo.ts +15 -0
  118. package/examples/autoresearch/prepare.ts +3 -3
  119. package/examples/autoresearch/project.ts +2 -19
  120. package/examples/code/README.md +25 -17
  121. package/examples/code/REQUIREMENTS.zh.md +3 -3
  122. package/examples/harness-session/README.md +3 -3
  123. package/examples/messages/README.md +1 -1
  124. package/examples/notes/README.md +3 -3
  125. package/examples/services/mathlib-search/README.md +1 -1
  126. package/examples/services/persistent-board/README.md +5 -2
  127. package/examples/subagents/README.md +2 -2
  128. package/examples/subagents/config.ts +4 -3
  129. package/examples/substrate/README.md +2 -2
  130. package/examples/super/README.md +34 -22
  131. package/examples/super/actions.ts +11 -11
  132. package/examples/super/config.ts +3 -3
  133. package/examples/super/eject.json +1 -1
  134. package/examples/super/location.ts +1 -1
  135. package/examples/super/operator.ts +28 -0
  136. package/examples/super/project.ts +1 -3
  137. package/npm-shrinkwrap.development.json +42 -1541
  138. package/npm-shrinkwrap.json +3 -43
  139. package/package.development.json +2 -6
  140. package/package.json +2 -5
  141. package/scripts/anyswarm-arguments.ts +67 -96
  142. package/scripts/anyswarm-eject.ts +1 -1
  143. package/scripts/anyswarm-harnesses.ts +1 -18
  144. package/scripts/anyswarm-installation.ts +18 -294
  145. package/scripts/anyswarm-launch.ts +30 -102
  146. package/scripts/anyswarm-progress.ts +95 -0
  147. package/scripts/anyswarm-project.ts +31 -123
  148. package/scripts/anyswarm-source-runner.ts +9 -36
  149. package/scripts/anyswarm.ts +4 -24
  150. package/scripts/local-environment.ts +71 -20
  151. package/scripts/local-setup.ts +134 -94
  152. package/scripts/pack-release.ts +4 -1
  153. package/src/core/worker-image.ts +1 -1
  154. package/src/harness/project-harness.ts +2 -2
  155. package/src/harness/project-runtime.ts +2 -1
  156. package/dist/scripts/anyswarm-applications.d.ts +0 -19
  157. package/dist/scripts/anyswarm-applications.js +0 -19
  158. package/dist/scripts/anyswarm-tui-config.d.ts +0 -36
  159. package/dist/scripts/anyswarm-tui-config.js +0 -189
  160. package/dist/scripts/anyswarm-tui-session.d.ts +0 -66
  161. package/dist/scripts/anyswarm-tui-session.js +0 -304
  162. package/dist/scripts/anyswarm-tui-terminal.d.ts +0 -41
  163. package/dist/scripts/anyswarm-tui-terminal.js +0 -154
  164. package/dist/scripts/anyswarm-tui.d.ts +0 -2
  165. package/dist/scripts/anyswarm-tui.js +0 -1012
  166. package/docs/architecture/25-foreground-tui.md +0 -51
  167. package/scripts/anyswarm-applications.ts +0 -39
  168. package/scripts/anyswarm-tui-config.ts +0 -174
  169. package/scripts/anyswarm-tui-session.ts +0 -295
  170. package/scripts/anyswarm-tui-terminal.ts +0 -147
  171. package/scripts/anyswarm-tui.ts +0 -912
@@ -1,14 +1,11 @@
1
- import { resolve } from 'node:path';
2
1
  import { frameworkErrorFields } from '../src/core/error-diagnostics.js';
3
- import { captureHarnessSnapshot, createHarnessSession, failureCode, getHarnessExitCode, loadProjectHarness, stopHarnessTransport } from '../src/harness/project-harness.js';
2
+ import { captureHarnessSnapshot, createHarnessSession, failureCode, getHarnessExitCode, stopHarnessTransport } from '../src/harness/project-harness.js';
4
3
  import { resolveHarnessInput } from '../src/harness/project-input.js';
5
4
  import { runProjectRpc } from '../src/harness/project-rpc.js';
6
- import type { HarnessCommand, ProjectCommand } from './anyswarm-arguments.js';
5
+ import type { ProjectCommand } from './anyswarm-arguments.js';
7
6
 
8
- import { findApplication } from './anyswarm-applications.js';
9
- import { builtins } from './anyswarm-harnesses.js';
10
- import { actionReport, actionRun, configuredStopTimeout, harnessLifetime, loadHarness, requestedTraceRoot, splitInput, type ActionRun } from './anyswarm-launch.js';
11
- import { LauncherConfiguration } from './anyswarm-tui-config.js';
7
+ import { prepareProjectLaunch } from './anyswarm-launch.js';
8
+ import { foregroundProgress } from './anyswarm-progress.js';
12
9
 
13
10
  const MAX_QUEUED_OUTPUT_BYTES = 1_048_576;
14
11
  const MAX_OUTPUT_RECORD_BYTES = 8 * 1024 * 1024;
@@ -22,18 +19,15 @@ interface OutputFrame {
22
19
  }
23
20
 
24
21
  export async function runProjectCommand(command: ProjectCommand, launchDirectory: string,
25
- options: { onSourceError?: (error: unknown) => void; action?: {
26
- run: ActionRun; loaded: Awaited<ReturnType<typeof loadHarness>>;
27
- } } = {}) {
22
+ options: { onSourceError?: (error: unknown) => void } = {}) {
23
+ const human = command.mode === 'foreground' && process.stdout.isTTY;
28
24
  const stdout = process.stdout.write;
29
25
  const transport = stdout.bind(process.stdout);
30
26
  const startup = new AbortController();
31
27
  let session: ReturnType<typeof createHarnessSession> | undefined;
32
28
  let signalCode: number | undefined;
33
29
  let outputFailed = false;
34
- let workspace = 'cwd' in command ? command.cwd : undefined;
35
- let trace: Promise<{ root: string; close(): Promise<void> } | undefined> | undefined;
36
- let unsubscribeTrace: (() => void) | undefined;
30
+ let progress: ReturnType<typeof foregroundProgress> | undefined;
37
31
  let lastWrite: Promise<void> | undefined;
38
32
  const outputQueue: OutputFrame[] = [];
39
33
  let queuedBytes = 0;
@@ -78,16 +72,8 @@ export async function runProjectCommand(command: ProjectCommand, launchDirectory
78
72
  }
79
73
  }
80
74
 
81
- const write = (record: unknown, replaceableState = false): Promise<void> => {
75
+ const enqueue = (data: string, replaceableState = false): Promise<void> => {
82
76
  if (outputFailed) return Promise.resolve();
83
- let encoded: string;
84
- try {
85
- encoded = JSON.stringify(record);
86
- } catch {
87
- pipeFailed();
88
- return Promise.resolve();
89
- }
90
- const data = encoded + '\n';
91
77
  const bytes = Buffer.byteLength(data);
92
78
  const last = outputQueue.at(-1);
93
79
  const replace = replaceableState && last?.replaceableState ? last : undefined;
@@ -107,6 +93,10 @@ export async function runProjectCommand(command: ProjectCommand, launchDirectory
107
93
  void flushOutput();
108
94
  return lastWrite;
109
95
  };
96
+ const write = (record: unknown, replaceableState = false): Promise<void> => {
97
+ try { return enqueue(JSON.stringify(record) + '\n', replaceableState); }
98
+ catch { pipeFailed(); return Promise.resolve(); }
99
+ };
110
100
  const ignoreDiagnosticError = () => {};
111
101
  process.on('SIGINT', signal);
112
102
  process.on('SIGTERM', signal);
@@ -118,79 +108,44 @@ export async function runProjectCommand(command: ProjectCommand, launchDirectory
118
108
  const stopped = Promise.withResolvers<never>();
119
109
  const abortStartup = () => stopped.reject(startup.signal.reason);
120
110
  startup.signal.addEventListener('abort', abortStartup, { once: true });
121
- const prepare = async () => {
122
- const loaded = options.action?.loaded ?? (command.defaults
123
- ? await loadHarness(launchDirectory, command.harness, options) : undefined);
124
- const definition = loaded?.definition ?? await loadProjectHarness(launchDirectory, command.harness, builtins, options);
125
- const config = { launchDirectory, configPath: command.configPath, outputRoot: command.outputRoot,
126
- lifetime: command.lifetime, clientCapabilities: { questions: command.mode !== 'headless' && command.interaction === 'questions' } };
127
- if (!command.defaults) return createHarnessSession(definition, config);
128
- const launcher = new LauncherConfiguration(command.harness, command.harness, launchDirectory,
129
- 'cwd' in command ? command.cwd : undefined, command.configPath);
130
- let configuration = options.action?.run.configuration;
131
- if (!options.action) {
132
- await launcher.refresh();
133
- if (launcher.error) throw new Error(launcher.error);
134
- configuration = launcher.configuration;
135
- if (!workspace && loaded?.workspace && command.mode !== 'rpc') {
136
- workspace = loaded.workspace({ cwd: launcher.workspace, configuration });
137
- }
138
- }
139
- const lifetime = harnessLifetime(definition, command.lifetime, findApplication(command.harness)?.lifetime);
140
- return createHarnessSession(definition, { ...config, configPath: undefined, configuration, lifetime,
141
- stopTimeoutMs: configuredStopTimeout(configuration) });
142
- };
111
+ let launch;
143
112
  try {
144
- session = await Promise.race([prepare(), stopped.promise]);
113
+ launch = await Promise.race([prepareProjectLaunch(command, launchDirectory, options, startup.signal), stopped.promise]);
114
+ session = launch.session;
145
115
  startup.signal.throwIfAborted();
146
116
  } finally {
147
117
  startup.signal.removeEventListener('abort', abortStartup);
148
118
  }
149
- unsubscribeTrace = session.onEvent(event => {
150
- if (trace || event.type !== 'event') return;
151
- const root = requestedTraceRoot(event.event, event.runId);
152
- if (!root) return;
153
- const modulePath = '../src/trace-viewer/server.mjs';
154
- trace = import(modulePath).then(async ({ startTraceServer }) => {
155
- const viewer = await startTraceServer({ root, port: 0 });
156
- console.error('Live Trace URL ' + viewer.url);
157
- return { root, close: () => viewer.close() };
158
- }).catch(() => {
159
- console.error('Could not open the live Trace Viewer. Replay this Run from its records.');
160
- return undefined;
161
- });
162
- }, { initialSnapshot: false });
163
- const input = command.mode !== 'rpc'
164
- ? resolveHarnessInput({ cwd: workspace, prompt: command.prompt }, launchDirectory)
165
- : undefined;
166
- if (command.mode === 'rpc' || (command.mode === 'foreground' && (command.lifetime === 'interactive' || command.interaction === 'questions'))) {
167
- const code = await runProjectRpc(session, process.stdin, write, launchDirectory, input);
119
+ if (command.mode === 'rpc') {
120
+ const code = await runProjectRpc(session, process.stdin, write, launchDirectory);
168
121
  await lastWrite;
169
122
  return signalCode ?? (outputFailed ? 1 : code);
170
123
  }
171
- const unsubscribe = command.mode === 'headless' ? session.onEvent(event => {
172
- if (event.type !== 'result') void write(event, event.type === 'state');
173
- }, { onError: pipeFailed }) : undefined;
124
+ if (human) progress = foregroundProgress(session, launch.harnessId, launchDirectory, command.outputRoot, message => enqueue(message + '\n'));
125
+ const input = resolveHarnessInput({ cwd: launch.cwd, prompt: command.prompt }, launchDirectory);
126
+ const unsubscribe = progress && session.onEvent(progress.observe, {
127
+ initialSnapshot: false,
128
+ onError: () => { void enqueue('Live progress unavailable. Follow the Run in Trace.\n'); },
129
+ });
174
130
  let result;
175
131
  try {
176
- await session.start(input!, { requestId: 'foreground-start' });
132
+ await session.start(input, { requestId: 'foreground-start' });
177
133
  result = await session.completion!;
178
134
  } finally { unsubscribe?.(); }
179
- await write({ type: 'result', runId: result.runId, result });
135
+ if (progress) await progress.finish(result);
136
+ else await write({ type: 'result', runId: result.runId, result });
180
137
  return signalCode ?? (outputFailed ? 1 : getHarnessExitCode(session));
181
138
  } catch (error) {
182
139
  if (!startup.signal.aborted) {
183
140
  const code = failureCode(error, 'HARNESS_COMMAND_FAILED');
184
- await write({ type: 'error', code, ...(error instanceof Error ? { message: error.message } : {}), ...frameworkErrorFields(error) });
141
+ const message = error instanceof Error ? error.message : undefined;
142
+ if (human) {
143
+ if (progress) await progress.fail(code, message);
144
+ else console.error(code + (message ? ' ' + message : ''));
145
+ } else await write({ type: 'error', code, ...(message ? { message } : {}), ...frameworkErrorFields(error) });
185
146
  }
186
147
  return signalCode ?? (outputFailed ? 1 : 2);
187
148
  } finally {
188
- unsubscribeTrace?.();
189
- const viewer = await trace;
190
- if (viewer) {
191
- await viewer.close().catch(() => {});
192
- console.error('Replay with anys trace --root ' + JSON.stringify(viewer.root));
193
- }
194
149
  process.stdout.write = stdout;
195
150
  process.off('SIGINT', signal);
196
151
  process.off('SIGTERM', signal);
@@ -198,50 +153,3 @@ export async function runProjectCommand(command: ProjectCommand, launchDirectory
198
153
  process.stderr.off('error', ignoreDiagnosticError);
199
154
  }
200
155
  }
201
-
202
-
203
- export async function runHarnessAction(command: Extract<HarnessCommand, { mode: 'action' }>, launchDirectory: string,
204
- options?: Parameters<typeof loadHarness>[2]) {
205
- const controller = new AbortController();
206
- let exitCode = 0;
207
- let start: { run: ActionRun; loaded: Awaited<ReturnType<typeof loadHarness>> } | undefined;
208
- const cancel = (signal: 'SIGINT' | 'SIGTERM') => {
209
- exitCode ||= signal === 'SIGINT' ? 130 : 143;
210
- controller.abort();
211
- };
212
- const stdout = process.stdout.write;
213
- process.stdout.write = process.stderr.write.bind(process.stderr);
214
- process.on('SIGINT', cancel).on('SIGTERM', cancel);
215
- try {
216
- const loaded = await loadHarness(launchDirectory, command.harness, options);
217
- const [name, args] = splitInput(command.slash.slice(1));
218
- const handler = loaded.actions.get(name);
219
- if (!handler) throw new Error('Harness has no standalone /' + name + ' action.');
220
- const launcher = new LauncherConfiguration(command.harness, command.harness, launchDirectory, command.cwd, command.configPath);
221
- await launcher.refresh();
222
- if (launcher.error && launcher.path) throw new Error(launcher.error);
223
- controller.signal.throwIfAborted();
224
- const result = await handler({ cwd: launcher.workspace, configuration: launcher.configuration,
225
- signal: controller.signal, outputRoot: command.outputRoot && resolve(launchDirectory, command.outputRoot), args });
226
- controller.signal.throwIfAborted();
227
- const run = actionRun(result);
228
- if (run) start = { run: { ...run, configuration: run.configuration ?? launcher.configuration }, loaded };
229
- else if (result !== undefined) {
230
- const report = actionReport(result);
231
- const output = report ? report.result : result;
232
- await new Promise<void>((done, reject) => {
233
- stdout.call(process.stdout, JSON.stringify(output) + '\n', undefined, error => error ? reject(error) : done());
234
- });
235
- exitCode ||= report?.exitCode ?? 0;
236
- }
237
- if (!start) return exitCode;
238
- } catch (error) {
239
- if (!exitCode) console.error(error instanceof Error ? error.message : 'Harness action failed.');
240
- return exitCode || 1;
241
- } finally {
242
- process.stdout.write = stdout;
243
- process.off('SIGINT', cancel).off('SIGTERM', cancel);
244
- }
245
- return runProjectCommand({ ...command, defaults: true, command: 'harness', mode: 'headless',
246
- cwd: start.run.cwd, prompt: start.run.prompt }, launchDirectory, { ...options, action: start });
247
- }
@@ -6,7 +6,7 @@ import { tmpdir } from 'node:os';
6
6
  import { verifyExportedSdk } from './anyswarm-eject.js';
7
7
  import type { Harness } from '../src/harness/project-harness.js';
8
8
  import { installSourceLoader } from '../src/harness/typescript-loader.js';
9
- import { parseAnySwarmCommand, parseHarnessSelection } from './anyswarm-arguments.js';
9
+ import { parseSourceHarnessCommand } from './anyswarm-arguments.js';
10
10
 
11
11
  const [, , entry, ...args] = process.argv;
12
12
  if (!entry) throw new TypeError('A TypeScript or JavaScript entry file is required');
@@ -15,17 +15,12 @@ const entryUrl = pathToFileURL(filename).href;
15
15
  process.argv = [process.execPath, filename, ...args];
16
16
  installSourceLoader();
17
17
 
18
- const hasOption = (name: string, value: string) => args.includes(`${name}=${value}`) ||
19
- args.some((arg, index) => arg === name && args[index + 1] === value);
20
- const modernFlags = args.some(arg => /^--(?:headless|rpc|cmd)(?:=|$)/.test(arg));
21
- const hasPrompt = args.some(arg => arg === '--prompt' || arg.startsWith('--prompt='));
22
- const outputsRecords = !hasOption('--mode', 'tui') &&
23
- (hasPrompt || hasOption('--mode', 'foreground') || hasOption('--mode', 'rpc'));
18
+ const hasPrompt = args.some(arg => /^--prompt(?:=|$)/.test(arg));
19
+ const hasMode = args.some(arg => /^--mode(?:=|$)/.test(arg));
24
20
 
25
21
  type SourceModule = { default?: Harness };
26
22
  const isHarness = (source: SourceModule): source is { default: Harness } =>
27
23
  source.default?.apiVersion === 1 && typeof source.default.run === 'function';
28
- const isInteractiveOnly = (harness: Harness) => harness.lifetimes?.includes('interactive') && !harness.lifetimes.includes('task');
29
24
 
30
25
  async function importWithDiagnostics<T>(load: () => Promise<T>, useStderr = true): Promise<T> {
31
26
  if (!useStderr) return load();
@@ -132,7 +127,7 @@ async function importImplicitSource(load: () => Promise<SourceModule>) {
132
127
  let destination: NodeJS.WriteStream = process.stderr;
133
128
  try {
134
129
  const source = await load();
135
- if (!isHarness(source) || (args.length === 0 && isInteractiveOnly(source.default))) destination = process.stdout;
130
+ if (!isHarness(source)) destination = process.stdout;
136
131
  else if (interactiveOutput) {
137
132
  throw new Error('Use an explicit --prompt for a task Harness that writes to stdout while reading stdin during import.');
138
133
  }
@@ -167,35 +162,13 @@ try {
167
162
  try { import.meta.resolve(sdk); } finally { checkingEntry = false; }
168
163
  }
169
164
  const load = (): Promise<SourceModule> => import(entryUrl);
170
- const interactive = process.stdin.isTTY && process.stdout.isTTY && process.env.TERM !== 'dumb';
171
- const probeSourceOutput = modernFlags || (args.length === 0 && /\.(?:ts|mts)$/.test(filename)) ||
172
- (!interactive && !outputsRecords && args.length > 0);
173
- const source = await (probeSourceOutput ? importImplicitSource(load) : importWithDiagnostics(load, outputsRecords));
165
+ const source = await (hasPrompt || hasMode ? importWithDiagnostics(load) : importImplicitSource(load));
174
166
  if (isHarness(source)) {
167
+ const command = parseSourceHarnessCommand(args, filename);
175
168
  const diagnostics = { onSourceError(error: unknown) { console.error(error instanceof Error ? error.stack : String(error)); } };
176
- if (modernFlags || (!hasPrompt && !args.includes('--help') &&
177
- !args.some(arg => /^--mode(?:=|$)/.test(arg)) && (args.length > 0 || interactive))) {
178
- const { runHarnessSelection } = await import('./anyswarm-launch.js');
179
- const code = await runHarnessSelection(parseHarnessSelection(args, filename), process.cwd(), diagnostics);
180
- process.stdout.write('', () => process.exit(code));
181
- } else {
182
- const command = parseAnySwarmCommand(['--harness', filename,
183
- ...(args.length || isInteractiveOnly(source.default) ? args : ['--prompt', 'Run this Harness.'])]);
184
- if ('help' in command) {
185
- console.log(command.help);
186
- } else if (command.command === 'tui') {
187
- const { runAnySwarmTui } = await import('./anyswarm-tui.js');
188
- process.exit(await runAnySwarmTui(command, process.cwd()));
189
- } else if (command.command === 'harness') {
190
- if (command.configPath) {
191
- const configPath = resolve(command.configPath);
192
- const { loadAnySwarmConfig } = await import('../src/core/sandbox/sandbox-connection.js');
193
- await importWithDiagnostics(() => loadAnySwarmConfig(configPath));
194
- }
195
- const { runProjectCommand } = await import('./anyswarm-project.js');
196
- process.exitCode = await runProjectCommand(command, process.cwd(), diagnostics);
197
- } else throw new TypeError('Harness arguments must use TUI, foreground or RPC options');
198
- }
169
+ const { runProjectCommand } = await import('./anyswarm-project.js');
170
+ const code = await runProjectCommand(command, process.cwd(), diagnostics);
171
+ process.stdout.write('', () => process.exit(code));
199
172
  }
200
173
  } catch (error) {
201
174
  console.error(error instanceof Error ? error.stack : String(error));
@@ -4,7 +4,6 @@ import { readFile, realpath } from 'node:fs/promises';
4
4
  import { resolve } from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
6
6
  import { parseAnySwarmCommand } from './anyswarm-arguments.js';
7
- import { builtins } from './anyswarm-harnesses.js';
8
7
 
9
8
  const args = process.argv.slice(2);
10
9
  if (args.length === 1 && args[0] === '--version') {
@@ -29,32 +28,12 @@ if (args.length === 1 && args[0] === '--version') {
29
28
  } else {
30
29
  let command;
31
30
  try {
32
- command = parseAnySwarmCommand(args, builtins);
31
+ command = parseAnySwarmCommand(args);
33
32
  } catch (error) {
34
33
  console.error((error as Error).message);
35
34
  process.exitCode = 2;
36
35
  }
37
36
  if (command && 'help' in command) console.log(command.help);
38
- if (command && 'command' in command && command.command === 'tui') {
39
- let code = 2;
40
- try {
41
- const { runAnySwarmTui } = await import('./anyswarm-tui.js');
42
- code = await runAnySwarmTui(command, process.cwd());
43
- } catch {
44
- console.error('Could not load the TUI. Reinstall @anyswarm/core or use explicit foreground or RPC mode.');
45
- }
46
- process.exit(code);
47
- }
48
- if (command && 'command' in command && command.command === 'use') {
49
- try {
50
- const { runHarnessSelection } = await import('./anyswarm-launch.js');
51
- const code = await runHarnessSelection(command, process.cwd());
52
- process.stdout.write('', () => process.exit(code));
53
- } catch (error) {
54
- console.error(error instanceof Error ? error.message : 'Could not launch the requested Harness.');
55
- process.exitCode = 1;
56
- }
57
- }
58
37
  if (command && 'command' in command && command.command === 'run') {
59
38
  try {
60
39
  const { runSourceCommand } = await import('./anyswarm-author.js');
@@ -110,10 +89,11 @@ if (args.length === 1 && args[0] === '--version') {
110
89
  process.on('SIGTERM', interrupt);
111
90
  try {
112
91
  const report = command.command === 'update'
113
- ? await (await import('./anyswarm-installation.js')).updateAnySwarm(command, controller.signal, console.error)
92
+ ? await (await import('./anyswarm-installation.js')).updateAnySwarm(controller.signal)
114
93
  : await (await import('./local-setup.js')).runLocalCommand(command, controller.signal,
115
94
  command.command === 'setup' || process.stderr.isTTY ? message => console.error(message) : undefined);
116
- console.log(JSON.stringify(report, null, 2));
95
+ if (command.command === 'update' && process.stdout.isTTY) console.log((report as { detail: string }).detail);
96
+ else console.log(JSON.stringify(report, null, 2));
117
97
  process.exitCode = signalCode ?? (report.ok ? 0 : 1);
118
98
  } catch {
119
99
  console.error(JSON.stringify({ ok: false, error: 'The requested AnySwarm command could not start. Rebuild or reinstall @anyswarm/core.' }));
@@ -2,7 +2,7 @@ import { execFile, spawn } from 'node:child_process';
2
2
  import { randomBytes, randomUUID } from 'node:crypto';
3
3
  import { access, lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
4
4
  import { createConnection, isIP } from 'node:net';
5
- import { homedir, platform } from 'node:os';
5
+ import { homedir, platform, release } from 'node:os';
6
6
  import { join } from 'node:path';
7
7
  import { setTimeout as delay } from 'node:timers/promises';
8
8
  import { fileURLToPath } from 'node:url';
@@ -75,18 +75,35 @@ export function resolveSubagentsEnvironment(config: Partial<LocalEnvironmentConf
75
75
  return resolveLocalEnvironment(config, 'SUBAGENTS');
76
76
  }
77
77
 
78
- export function checkSetupHost({ requiresLinux = true }: { requiresLinux?: boolean } = {}): DiagnosticCheck[] {
78
+ export function checkSetupHost(): DiagnosticCheck[] {
79
79
  const [major, minor] = process.versions.node.split('.').map(Number);
80
80
  const os = platform();
81
81
  return [
82
- requiresLinux
83
- ? check('host.linux', os === 'linux', `Host operating system ${os}`,
84
- os === 'darwin' ? 'macOS managed Worker preparation and smoke are not yet available in this build.' : 'Run this command on Linux.')
85
- : check('host.platform', os === 'linux' || os === 'darwin', `Host operating system ${os}`, 'Run this command on Linux or macOS.'),
86
- check('host.node', major > 22 || major === 22 && minor >= 19, `Node.js ${process.versions.node}`, 'Install Node.js 22.19 or newer.'),
82
+ check('host.platform', os === 'linux' || os === 'darwin',
83
+ `Host operating system ${os} ${release()} (${process.arch})`, 'Run this command on Linux or macOS.'),
84
+ check('host.node', major > 22 || major === 22 && minor >= 19, `Node.js ${process.versions.node} (${process.execPath})`, 'Install Node.js 22.19 or newer.'),
87
85
  ];
88
86
  }
89
87
 
88
+ export async function checkHostTools(signal: AbortSignal) {
89
+ return Promise.all((['npm', 'git'] as const).map(async tool => {
90
+ const id = `host.${tool}`;
91
+ const remedy = tool === 'npm' ? 'Install Node.js with npm and use that installation on PATH.'
92
+ : 'Install Git before running a project Harness that captures local files.';
93
+ const options = { signal, timeout: 5_000 };
94
+ let path: string | undefined;
95
+ try {
96
+ path = (await execute('/bin/sh', ['-c', 'command -v "$1"', 'anyswarm', tool], options)).stdout.trim();
97
+ const version = (await execute(tool, ['--version'], options)).stdout.trim();
98
+ return check(id, true, `${tool === 'git' ? version : 'npm ' + version} (${path})`);
99
+ } catch {
100
+ signal.throwIfAborted();
101
+ const detail = path ? `Could not verify ${tool} at ${path}.` : `${tool} was not found on PATH.`;
102
+ return check(id, false, detail, remedy);
103
+ }
104
+ }));
105
+ }
106
+
90
107
  async function dockerInstallRemedy(): Promise<string> {
91
108
  const release = await readFile('/etc/os-release', 'utf8').catch(() => '');
92
109
  const id = /^ID="?([a-z0-9_-]+)/m.exec(release)?.[1];
@@ -107,31 +124,63 @@ async function dockerInstallRemedy(): Promise<string> {
107
124
  export async function resolveLocalDocker() {
108
125
  const socket = await localDockerSocket();
109
126
  const info = JSON.parse(await run('docker', ['info', '--format', '{{json .}}']));
110
- if (info.OSType !== 'linux') throw new Error('Local setup needs a Linux Docker Engine.');
127
+ if (info.OSType !== 'linux') {
128
+ throw Object.assign(new Error('Local setup needs a Linux Docker Engine.'), { code: 'DOCKER_OS' });
129
+ }
111
130
  if (darwin && ![nativeArchitecture, ...(nativeArchitecture === 'arm64' ? ['aarch64'] : ['x86_64'])].includes(info.Architecture)) {
112
131
  throw Object.assign(new Error('The Docker daemon does not match the native Mac architecture.'), { code: 'DOCKER_ARCHITECTURE' });
113
132
  }
114
133
  const bridge = darwin ? undefined : JSON.parse(await run('docker', ['network', 'inspect', 'bridge']).catch(() => '[]'))[0];
115
134
  const advertiseHost: string | undefined = bridge?.IPAM?.Config?.find((entry: { Gateway?: string }) => isIP(entry.Gateway ?? '') === 4)?.Gateway;
116
- return { socket, advertiseHost, rootless: info.SecurityOptions?.some((value: string) => value.includes('rootless')) === true };
135
+ return { socket, advertiseHost, rootless: info.SecurityOptions?.some((value: string) => value.includes('rootless')) === true,
136
+ clientVersion: info.ClientInfo?.Version as string | undefined, context: info.ClientInfo?.Context as string | undefined,
137
+ engineVersion: info.ServerVersion as string | undefined };
117
138
  }
118
139
 
119
140
  export async function checkLocalDocker() {
120
141
  try {
121
142
  const docker = await resolveLocalDocker();
122
- return { docker, diagnostic: check('host.docker-engine', true, `Linux Docker Engine (${docker.rootless ? 'rootless' : 'rootful'})`) };
143
+ const engine = [`Linux Docker Engine`, docker.engineVersion, `(${docker.rootless ? 'rootless' : 'rootful'})`].filter(Boolean).join(' ');
144
+ const client = docker.clientVersion ? `Docker CLI ${docker.clientVersion}` : '';
145
+ const context = docker.context ? `context ${docker.context}` : '';
146
+ return { docker, diagnostic: check('host.docker-engine', true, [engine, client, context].filter(Boolean).join(', ')) };
123
147
  } catch (error) {
124
148
  if ((error as NodeJS.ErrnoException).code === 'DOCKER_ARCHITECTURE') {
125
149
  return { diagnostic: check('host.docker-engine', false, 'The Docker daemon does not match the native Mac architecture.',
126
150
  'Select a native local Docker engine for this Mac and run docker info. AnySwarm does not fall back to emulation.') };
127
151
  }
128
- const missing = (error as NodeJS.ErrnoException).code === 'ENOENT' &&
129
- (error as NodeJS.ErrnoException).syscall === 'spawn docker';
130
- const remedy = platform() === 'darwin'
131
- ? 'Install Docker Desktop for Mac (https://docs.docker.com/desktop/setup/install/mac-install/), open it, and wait for the engine to start. If you already use another local Linux engine such as OrbStack, start that instead. The Docker CLI alone is not enough. Run docker context show and docker info. If needed, run docker context ls and docker context use <local-context>. Also check any DOCKER_CONTEXT or DOCKER_HOST override.'
132
- : missing ? await dockerInstallRemedy() :
133
- 'Run docker context show and docker info. Start the selected engine or use an authorized local Docker context. For a socket permission error, ask the host administrator to grant access and sign in again after any group change. Then rerun the same anyswarm setup command.';
134
- return { diagnostic: check('host.docker-engine', false, 'Could not access a Linux Docker Engine through the selected local Unix Docker context.', remedy) };
152
+ const { code, syscall, stderr = '' } = error as NodeJS.ErrnoException & { stderr?: string };
153
+ const missing = code === 'ENOENT' && syscall === 'spawn docker';
154
+ const contextRemedy = 'Run docker context show and docker info. If needed, run docker context ls and docker context use <local-context>. Check DOCKER_CONTEXT and DOCKER_HOST overrides.';
155
+ if (code === 'LOCAL_WORKER_UNAVAILABLE') {
156
+ return { diagnostic: check('host.docker-engine', false, 'The selected Docker context does not use a local Unix socket.', contextRemedy) };
157
+ }
158
+ if (code === 'DOCKER_OS') {
159
+ return { diagnostic: check('host.docker-engine', false, 'The selected Docker daemon is not a Linux engine.', contextRemedy) };
160
+ }
161
+ if (code === 'EACCES' || code === 'EPERM' || /permission denied.*(?:socket|docker daemon)|(?:socket|docker daemon).*permission denied/i.test(stderr)) {
162
+ return { diagnostic: check('host.docker-engine', false, 'Permission denied while accessing the local Docker engine.',
163
+ 'Ask the host administrator to grant socket access. Sign in again after any group change and run docker info as your login user.') };
164
+ }
165
+ let desktopRemedy = 'Install Docker Desktop for Mac (https://docs.docker.com/desktop/setup/install/mac-install/), open it, and wait for the engine to start.';
166
+ if (darwin) {
167
+ const app = 'Docker.app/Contents/Info.plist';
168
+ const installed = await Promise.all(['/Applications', join(homedir(), 'Applications')]
169
+ .map(directory => access(join(directory, app)).then(() => true, () => false)));
170
+ if (installed.some(Boolean)) {
171
+ desktopRemedy = 'Docker Desktop is installed. Open Docker Desktop or wait for its engine to finish starting, then check that its CLI is on PATH.';
172
+ }
173
+ desktopRemedy += ' If you already use another local Linux engine such as OrbStack, start that instead.';
174
+ }
175
+ if (missing) {
176
+ return { diagnostic: check('host.docker-engine', false, 'The Docker CLI was not found on PATH.',
177
+ darwin ? desktopRemedy + ' ' + contextRemedy : await dockerInstallRemedy()) };
178
+ }
179
+ const unavailable = code === 'ENOENT' || /cannot connect|connection refused|daemon running/i.test(stderr);
180
+ const detail = unavailable ? 'The Docker CLI is installed, but the local daemon or its Unix socket is unavailable.'
181
+ : 'Could not verify the selected local Docker engine.';
182
+ return { diagnostic: check('host.docker-engine', false, detail,
183
+ (darwin ? desktopRemedy : 'Start the local Docker engine, then verify access as your login user.') + ' ' + contextRemedy) };
135
184
  }
136
185
  }
137
186
 
@@ -244,14 +293,16 @@ async function authenticatedHealth(config: LocalEnvironmentConfig, budget?: Abor
244
293
  }
245
294
  }
246
295
 
247
- export async function checkLocalProvider(config: LocalEnvironmentConfig, { requireAuth = true } = {}): Promise<DiagnosticCheck[]> {
296
+ export async function checkLocalProvider(config: LocalEnvironmentConfig, { requireAuth = true, managed = false } = {}): Promise<DiagnosticCheck[]> {
248
297
  const [healthy, denied] = await Promise.all([providerHealthy(config, true), requireAuth ? providerHealthy(config, false) : true]);
249
298
  return [
250
299
  check('provider.health', healthy, healthy ? 'OpenSandbox lifecycle listing is reachable with the configured credentials.' : 'OpenSandbox lifecycle listing failed.',
251
- 'Check ANYSWARM_LIFECYCLE_URL (or sandbox.lifecycleBaseUrl in --config), TLS trust, and the lifecycle API key. Rerun the same command.'),
300
+ managed ? 'Run anyswarm setup to start or restore the managed OpenSandbox service.'
301
+ : 'Check ANYSWARM_LIFECYCLE_URL (or sandbox.lifecycleBaseUrl in --config), TLS trust, and the lifecycle API key. Rerun the same command.'),
252
302
  ...(requireAuth ? [check('provider.authentication', denied && !!config.apiKey,
253
303
  denied && config.apiKey ? 'Lifecycle rejects requests without the configured API key.' : 'Lifecycle authentication could not be confirmed.',
254
- 'Configure a lifecycle API key on OpenSandbox and pass it through trusted anyswarm configuration.')] : []),
304
+ managed ? 'Run anyswarm setup to check the managed service and its local credentials.'
305
+ : 'Configure a lifecycle API key on OpenSandbox and pass it through trusted anyswarm configuration.')] : []),
255
306
  ];
256
307
  }
257
308