@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,187 +1,11 @@
1
- import { execFile, spawn } from 'node:child_process';
2
- import { createHash, randomUUID } from 'node:crypto';
3
- import { constants, createReadStream } from 'node:fs';
4
- import { access, mkdir, mkdtemp, readFile, readlink, realpath, rename, rm, symlink, writeFile } from 'node:fs/promises';
5
- import { homedir } from 'node:os';
6
- import { basename, dirname, join, relative, resolve } from 'node:path';
1
+ import { execFile } from 'node:child_process';
2
+ import { readFile, realpath } from 'node:fs/promises';
3
+ import { dirname, join, resolve } from 'node:path';
7
4
  import { fileURLToPath } from 'node:url';
8
5
  import { promisify } from 'node:util';
9
6
  const execute = promisify(execFile);
10
7
  const packageName = '@anyswarm/core';
11
- const previousPackageNames = ['@anyswarm/anyswarm', '@luna-shi/anyswarm'];
12
8
  const packageRoot = resolve(fileURLToPath(new URL('../..', import.meta.url)));
13
- const releaseRoot = 'https://github.com/AnySwarm/anyswarm/releases/download';
14
- const stableVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
15
- const bins = ['anyswarm', 'anys', 'swarm'];
16
- const installDirectory = (prefix) => join(prefix, 'lib', 'anyswarm');
17
- const installedPackage = (stage) => join(stage, 'node_modules', packageName);
18
- const installBin = (prefix, name) => join(prefix, 'bin', name);
19
- async function manifest(root) {
20
- return JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
21
- }
22
- export async function archiveDigest(path) {
23
- const hash = createHash('sha256');
24
- for await (const chunk of createReadStream(path))
25
- hash.update(chunk);
26
- return hash.digest('hex');
27
- }
28
- async function replaceLink(path, target) {
29
- const temporary = join(dirname(path), `.anyswarm-link-${randomUUID()}`);
30
- try {
31
- await symlink(target, temporary);
32
- await rename(temporary, path);
33
- }
34
- finally {
35
- await rm(temporary, { force: true });
36
- }
37
- }
38
- async function inspectLink(path) {
39
- try {
40
- return await readlink(path);
41
- }
42
- catch (error) {
43
- if (error.code === 'ENOENT')
44
- return undefined;
45
- if (error.code === 'EINVAL')
46
- throw new Error(`The regular file at ${path} belongs to another installation.`);
47
- throw error;
48
- }
49
- }
50
- function currentPath(prefix) {
51
- return join(installDirectory(prefix), 'current');
52
- }
53
- function binTarget(prefix, name) {
54
- return relative(join(prefix, 'bin'), join(currentPath(prefix), 'node_modules', '.bin', name));
55
- }
56
- async function lockActivation(prefix, action, signal) {
57
- signal?.throwIfAborted();
58
- const lock = join(installDirectory(prefix), 'activation-flock');
59
- const darwin = process.platform === 'darwin';
60
- // Keep the inode stable so waiting and newly arriving processes lock the same file.
61
- const flags = darwin ? ['-k', '-t', '15'] : ['--exclusive', '--timeout', '15'];
62
- const child = spawn(darwin ? '/usr/bin/lockf' : 'flock', [...flags, lock, process.execPath, '-e',
63
- 'console.log("locked"); process.stdin.resume()'], { stdio: ['pipe', 'pipe', 'ignore'] });
64
- child.stdin.on('error', () => { });
65
- const cancelled = () => child.kill();
66
- signal?.addEventListener('abort', cancelled, { once: true });
67
- if (signal?.aborted)
68
- cancelled();
69
- try {
70
- await new Promise((ready, reject) => {
71
- child.once('error', reject);
72
- child.once('exit', () => reject(new Error('The installation is busy. Retry after the other activation finishes.')));
73
- child.stdout.once('data', () => ready());
74
- });
75
- signal?.removeEventListener('abort', cancelled);
76
- signal?.throwIfAborted();
77
- return await action();
78
- }
79
- finally {
80
- signal?.removeEventListener('abort', cancelled);
81
- child.stdin.end();
82
- }
83
- }
84
- async function activate(prefix, stage, source, sha256, signal, expected) {
85
- const root = installedPackage(stage);
86
- const { name, version } = await manifest(root);
87
- if (name !== packageName || !stableVersion.test(version))
88
- throw new Error('The archive does not contain a stable AnySwarm distribution.');
89
- for (const bin of ['anyswarm', 'swarm']) {
90
- const path = join(stage, 'node_modules', '.bin', bin);
91
- if (await realpath(path) !== join(root, 'dist', 'scripts', `${bin}.js`)) {
92
- throw new Error(`The staged ${bin} entry does not belong to the package.`);
93
- }
94
- await access(path, constants.X_OK);
95
- }
96
- const { stdout } = await execute(join(stage, 'node_modules', '.bin', 'anyswarm'), ['--version'], {
97
- signal, timeout: 10_000, env: { ...process.env, NODE_OPTIONS: '' },
98
- });
99
- if (stdout.trim() !== version)
100
- throw new Error('The staged CLI did not report the package version.');
101
- await writeFile(join(stage, 'install.json'), JSON.stringify({ schema: 1, prefix, version, source, sha256 }), { mode: 0o600 });
102
- await mkdir(join(prefix, 'bin'), { recursive: true });
103
- return lockActivation(prefix, async () => {
104
- const changed = [];
105
- try {
106
- const oldCurrent = await inspectLink(currentPath(prefix));
107
- if (expected !== undefined && (!oldCurrent || resolve(installDirectory(prefix), oldCurrent) !== expected)) {
108
- throw new Error('Another process already changed this installation. Run the current CLI to update.');
109
- }
110
- for (const bin of bins) {
111
- const path = installBin(prefix, bin);
112
- const host = bin === 'anys' ? 'anyswarm' : bin;
113
- const target = binTarget(prefix, host);
114
- const previous = await inspectLink(path);
115
- if (previous === target)
116
- continue;
117
- const npmTargets = [packageName, ...previousPackageNames].map(name => join(prefix, 'lib', 'node_modules', name, 'dist', 'scripts', `${host}.js`));
118
- const legacyAlias = bin === 'anys' && previous === binTarget(prefix, 'anys') && oldCurrent &&
119
- dirname(resolve(installDirectory(prefix), oldCurrent)) === join(installDirectory(prefix), 'versions');
120
- if (previous && !legacyAlias && !npmTargets.includes(resolve(dirname(path), previous))) {
121
- throw new Error(`The link at ${path} belongs to another installation.`);
122
- }
123
- await replaceLink(path, target);
124
- changed.push({ path, previous });
125
- }
126
- signal?.throwIfAborted();
127
- await replaceLink(currentPath(prefix), relative(installDirectory(prefix), stage));
128
- return { version, packageRoot: root, path: installBin(prefix, 'anyswarm') };
129
- }
130
- catch (error) {
131
- for (const { path, previous } of changed.reverse()) {
132
- if (previous)
133
- await replaceLink(path, previous);
134
- else
135
- await rm(path);
136
- }
137
- throw error;
138
- }
139
- }, signal);
140
- }
141
- async function managedInstallation(invocation, version) {
142
- const stage = resolve(packageRoot, '../../..');
143
- const installation = await readFile(join(stage, 'install.json'), 'utf8')
144
- .then(data => JSON.parse(data)).catch(() => undefined);
145
- if (!installation || installation.schema !== 1 || installation.version !== version ||
146
- typeof installation.prefix !== 'string' ||
147
- dirname(stage) !== join(installDirectory(installation.prefix), 'versions') ||
148
- await realpath(invocation).catch(() => '') !== join(packageRoot, 'dist', 'scripts', 'anyswarm.js'))
149
- return undefined;
150
- const entry = installBin(installation.prefix, 'anyswarm');
151
- if (await realpath(entry).catch(() => '') !== await realpath(invocation)) {
152
- throw new Error(`This CLI version is no longer active. Run ${entry} update.`);
153
- }
154
- return { ...installation, stage, entry };
155
- }
156
- async function fetchFile(url, signal) {
157
- const response = await fetch(url, { signal, headers: { 'User-Agent': 'AnySwarm-CLI' } });
158
- if (!response.ok)
159
- throw new Error(`GitHub returned HTTP ${response.status} for the release material.`);
160
- return response;
161
- }
162
- async function latestRelease(signal) {
163
- const response = await fetchFile('https://api.github.com/repos/AnySwarm/anyswarm/releases/latest', signal);
164
- const data = await response.json();
165
- const version = data.tag_name?.slice(1);
166
- if (!data.tag_name?.startsWith('v') || !version || !stableVersion.test(version) || data.draft || data.prerelease) {
167
- throw new Error('GitHub did not return a stable AnySwarm release.');
168
- }
169
- return version;
170
- }
171
- async function releaseArchive(version, temporary, signal) {
172
- const directory = `${releaseRoot}/v${version}`;
173
- const filename = `luna-shi-anyswarm-${version}.tgz`;
174
- const checksums = await (await fetchFile(`${directory}/SHA256SUMS`, signal)).text();
175
- const digest = checksums.split('\n').map(line => line.trim().split(/\s+/))
176
- .find(([hash, name]) => name === filename && /^[a-f0-9]{64}$/.test(hash))?.[0];
177
- if (!digest)
178
- throw new Error('The release does not contain a checksum for the package.');
179
- const source = `${directory}/${filename}`;
180
- const response = await fetchFile(source, signal);
181
- const path = join(temporary, filename);
182
- await writeFile(path, response.body, { signal });
183
- return { path, source, digest };
184
- }
185
9
  const quoted = (value) => "'" + value.replaceAll("'", "'\\''") + "'";
186
10
  async function npmGlobalPrefix(invocation, signal) {
187
11
  const prefix = await realpath(dirname(dirname(invocation))).catch(() => undefined);
@@ -195,126 +19,28 @@ async function npmGlobalPrefix(invocation, signal) {
195
19
  return stdout.trim() === join(prefix, 'lib', 'node_modules') ? prefix : undefined;
196
20
  }
197
21
  function packageManagerRemedy(path) {
198
- const archive = 'https://github.com/AnySwarm/anyswarm/releases/latest/download/luna-shi-anyswarm.tgz';
22
+ const latest = packageName + '@latest';
199
23
  if (path.includes('/.pnpm/') || path.includes('/pnpm/global/')) {
200
- return `Use pnpm in the original scope: pnpm add${path.includes('/pnpm/global/') ? ' --global' : ''} ${archive}. Package: ${path}.`;
24
+ return `Use pnpm in the original scope: pnpm add${path.includes('/pnpm/global/') ? ' --global' : ''} ${latest}. Package: ${path}.`;
201
25
  }
202
26
  if (path.includes('/.yarn/') || path.includes('/yarn/global/')) {
203
- return `Use Yarn in the original scope: yarn ${path.includes('/yarn/global/') ? 'global ' : ''}add ${archive}. Package: ${path}.`;
27
+ return `Use Yarn in the original scope: yarn ${path.includes('/yarn/global/') ? 'global ' : ''}add ${latest}. Package: ${path}.`;
204
28
  }
205
29
  if (path.includes('/node_modules/')) {
206
30
  const prefix = path.slice(0, path.lastIndexOf('/node_modules/'));
207
- return `To change this project's SDK explicitly, run npm install --prefix ${quoted(prefix)} ${archive}. Package: ${path}.`;
31
+ return `To change this project's SDK explicitly, run npm install --prefix ${quoted(prefix)} ${latest}. Package: ${path}.`;
208
32
  }
209
- return `Review the installer at ${path} or select a prefix with npm_config_prefix before running the official installer: https://anyswarm.github.io/anyswarm/install.sh`;
33
+ return `Update the package in its original installation scope. Package: ${path}.`;
210
34
  }
211
- export async function updateAnySwarm(options, signal, progress) {
212
- const { version: before } = await manifest(packageRoot);
213
- const invocation = resolve(process.argv[1]);
214
- const installation = await managedInstallation(invocation, before);
215
- if (!installation) {
216
- const npmPrefix = await npmGlobalPrefix(invocation, signal);
217
- if (npmPrefix)
218
- return {
219
- ok: false, before, after: before, path: invocation, packageRoot, source: 'npm global',
220
- result: 'preserved', environment: 'separate',
221
- detail: `This CLI was installed with npm. Update it with \`npm install -g --prefix ${quoted(npmPrefix)} ${packageName}@latest\`.`,
222
- };
35
+ export async function updateAnySwarm(signal) {
36
+ const { version } = JSON.parse(await readFile(join(packageRoot, 'package.json'), 'utf8'));
37
+ const path = resolve(process.argv[1]);
38
+ const prefix = await npmGlobalPrefix(path, signal);
39
+ const result = { ok: false, before: version, path, packageRoot, environment: 'separate' };
40
+ if (prefix)
223
41
  return {
224
- ok: false, before, path: invocation, packageRoot, source: 'other',
225
- detail: packageManagerRemedy(packageRoot), environment: 'separate',
42
+ ...result, ok: true, after: version, source: 'npm global', result: 'preserved',
43
+ detail: `This CLI was installed with npm. Update it with \`npm install -g --prefix ${quoted(prefix)} ${packageName}@latest\`.`,
226
44
  };
227
- }
228
- const status = { before, path: installation.entry, packageRoot, source: installation.source, environment: 'separate' };
229
- let temporary;
230
- let stage;
231
- let activated = false;
232
- try {
233
- const deadline = AbortSignal.any([signal, AbortSignal.timeout(180_000)]);
234
- const release = options.archive ? undefined : await latestRelease(deadline);
235
- if (release) {
236
- const current = before.split('.').map(Number);
237
- const candidate = release.split('.').map(Number);
238
- const firstChange = candidate.findIndex((part, index) => part !== current[index]);
239
- if (firstChange < 0 || candidate[firstChange] < current[firstChange]) {
240
- return { ok: true, ...status, after: before, result: 'up-to-date' };
241
- }
242
- }
243
- const parent = installDirectory(installation.prefix);
244
- temporary = await mkdtemp(join(parent, 'anyswarm-download-'));
245
- const archive = options.archive
246
- ? { path: resolve(options.archive), source: resolve(options.archive), digest: options.sha256 }
247
- : await releaseArchive(release, temporary, deadline);
248
- if (await archiveDigest(archive.path) !== archive.digest)
249
- throw new Error('The archive SHA-256 does not match the expected checksum.');
250
- const verifiedArchive = join(temporary, 'verified.tgz');
251
- if (options.archive) {
252
- await writeFile(verifiedArchive, createReadStream(archive.path), { signal: deadline });
253
- if (await archiveDigest(verifiedArchive) !== archive.digest)
254
- throw new Error('The archive changed while it was being staged.');
255
- }
256
- progress(`Preparing ${release ? `AnySwarm ${release}` : 'the specified AnySwarm archive'}`);
257
- const approvedArchive = options.archive ? verifiedArchive : archive.path;
258
- const npmFlags = ['--omit=dev', '--prefer-offline', '--ignore-scripts', '--no-audit', '--no-fund'];
259
- stage = await mkdtemp(join(parent, 'versions', 'release-'));
260
- await execute('npm', ['install', '--prefix', stage, ...npmFlags, approvedArchive], { timeout: 120_000, signal: deadline });
261
- const { version } = await manifest(installedPackage(stage));
262
- if (release && version !== release)
263
- throw new Error('The release archive version does not match its release tag.');
264
- const updated = await activate(installation.prefix, stage, archive.source, archive.digest, deadline, installation.stage);
265
- activated = true;
266
- return { ok: true, ...status, ...updated, after: updated.version, source: archive.source, sha256: archive.digest, result: 'updated' };
267
- }
268
- catch (error) {
269
- const detail = error instanceof Error && 'cmd' in error
270
- ? 'A command failed while installing or verifying the staged CLI. Check npm connectivity and installation permissions.'
271
- : error instanceof Error ? error.message : String(error);
272
- const activePath = await realpath(status.path).catch(() => undefined);
273
- const preserved = activePath === join(packageRoot, 'dist', 'scripts', 'anyswarm.js');
274
- return { ok: false, ...status, ...(preserved ? { after: before } : {}), result: preserved ? 'preserved' : 'failed', detail };
275
- }
276
- finally {
277
- if (temporary)
278
- await rm(temporary, { recursive: true, force: true }).catch(() => { });
279
- if (stage && !activated)
280
- await rm(stage, { recursive: true, force: true }).catch(() => { });
281
- }
282
- }
283
- export async function activateOfficialInstall(input) {
284
- const prefix = await realpath(resolve(input.prefix));
285
- const stage = await realpath(resolve(input.stage));
286
- if (dirname(stage) !== join(installDirectory(prefix), 'versions'))
287
- throw new Error('The staged installation is outside the selected prefix.');
288
- if (!/^[a-f0-9]{64}$/.test(input.sha256))
289
- throw new Error('A verified archive SHA-256 is required.');
290
- if (input.expectedVersion && (await manifest(installedPackage(stage))).version !== input.expectedVersion) {
291
- throw new Error('The archive version does not match the requested GitHub release.');
292
- }
293
- const result = await activate(prefix, stage, input.source, input.sha256);
294
- console.log(`Installed AnySwarm ${result.version} at ${result.path}`);
295
- console.log(`Package root: ${result.packageRoot}\nInstall source: ${input.source}\nArchive SHA-256: ${input.sha256}`);
296
- let resolvedOnPath;
297
- for (const entry of (process.env.PATH ?? '').split(':')) {
298
- const path = resolve(entry, 'anyswarm');
299
- if (await access(path, constants.X_OK).then(() => true, () => false)) {
300
- resolvedOnPath = path;
301
- break;
302
- }
303
- }
304
- if (resolvedOnPath !== result.path) {
305
- const directory = dirname(result.path);
306
- const display = directory === join(homedir(), '.local', 'bin') ? '"$HOME/.local/bin:$PATH"'
307
- : `'${directory.replaceAll("'", "'\\''")}':"$PATH"`;
308
- console.error(`Add the installation to PATH:\n export PATH=${display}`);
309
- }
310
- }
311
- if (basename(process.argv[1] ?? '') === 'anyswarm-installation.js') {
312
- const [prefix, stage, source, sha256, expectedVersion] = process.argv.slice(2);
313
- try {
314
- await activateOfficialInstall({ prefix, stage, source, sha256, expectedVersion });
315
- }
316
- catch (error) {
317
- console.error(error instanceof Error ? error.message : String(error));
318
- process.exitCode = 1;
319
- }
45
+ return { ...result, source: 'other', detail: packageManagerRemedy(packageRoot) };
320
46
  }
@@ -1,37 +1,7 @@
1
- import { loadProjectHarnessModule, type Harness, type HarnessLifetime } from '../src/harness/project-harness.js';
2
- import type { HarnessCommand } from './anyswarm-arguments.js';
3
- import { type ApplicationObservation } from './anyswarm-applications.js';
4
- export type LaunchContext = {
5
- cwd: string;
6
- configuration?: unknown;
7
- signal: AbortSignal;
8
- outputRoot?: string;
9
- progress?: (message: string) => void;
10
- };
11
- export type ActionRun = {
12
- kind: 'start-run';
13
- cwd: string;
14
- prompt: string;
15
- configuration?: Record<string, unknown>;
16
- };
17
- export declare function actionRun(value: unknown): ActionRun | undefined;
18
- export declare function actionReport(value: unknown): {
19
- exitCode: number;
20
- result: unknown;
21
- } | undefined;
22
- export declare function configuredStopTimeout(configuration: Record<string, unknown> | undefined): number | undefined;
23
- export declare function requestedTraceRoot(value: unknown, runId: string | null): string | undefined;
24
- type SlashAction = (options: LaunchContext & {
25
- args: string;
26
- }) => unknown | Promise<unknown>;
27
- export declare function loadHarness(launchDirectory: string, specifier: string, options?: Parameters<typeof loadProjectHarnessModule>[3]): Promise<{
28
- definition: Harness;
29
- observe: ((options: LaunchContext) => Promise<ApplicationObservation | undefined>) | undefined;
30
- actions: Map<string, SlashAction>;
31
- workspace: ((options: Pick<LaunchContext, 'cwd' | 'configuration'>) => string) | undefined;
1
+ import { loadProjectHarnessModule } from '../src/harness/project-harness.js';
2
+ import type { ProjectCommand } from './anyswarm-arguments.js';
3
+ export declare function prepareProjectLaunch(command: ProjectCommand, launchDirectory: string, options: Parameters<typeof loadProjectHarnessModule>[3], signal: AbortSignal): Promise<{
4
+ session: import("../src/harness/harness-session-types.js").HarnessSession;
5
+ cwd: string | undefined;
6
+ harnessId: string;
32
7
  }>;
33
- export declare function harnessLifetime(harness: Harness, requested?: HarnessLifetime, preferred?: HarnessLifetime): HarnessLifetime;
34
- export declare function splitInput(text: string): [string, string];
35
- export declare function interactiveTerminal(): boolean;
36
- export declare function runHarnessSelection(command: HarnessCommand, launchDirectory: string, options?: Parameters<typeof loadProjectHarnessModule>[3]): Promise<number | undefined>;
37
- export {};
@@ -1,86 +1,37 @@
1
- import { loadProjectHarnessModule } from '../src/harness/project-harness.js';
2
- import { basename, isAbsolute, resolve } from 'node:path';
3
- import { findApplication } from './anyswarm-applications.js';
1
+ import { createHarnessSession, loadProjectConfiguration, loadProjectHarnessModule } from '../src/harness/project-harness.js';
2
+ import { ProjectPreflightError } from '../src/harness/project-input.js';
4
3
  import { builtins } from './anyswarm-harnesses.js';
5
- export function actionRun(value) {
6
- if (!value || typeof value !== 'object' || !('kind' in value) || value.kind !== 'start-run')
7
- return;
8
- const run = value;
9
- if (typeof run.cwd !== 'string' || !run.cwd || typeof run.prompt !== 'string' || !run.prompt.trim()) {
10
- throw new Error('A standalone action must supply a workspace and prompt to start a Run.');
11
- }
12
- return run;
13
- }
14
- export function actionReport(value) {
15
- if (!value || typeof value !== 'object' || !('kind' in value) || value.kind !== 'action-report')
16
- return;
17
- if (!('result' in value) || !('exitCode' in value) || typeof value.exitCode !== 'number' ||
18
- !Number.isSafeInteger(value.exitCode) || value.exitCode < 0 || value.exitCode > 125) {
19
- throw new Error('An action report must supply a result and an exit code from 0 to 125.');
20
- }
21
- return { exitCode: value.exitCode, result: value.result };
22
- }
23
- export function configuredStopTimeout(configuration) {
24
- const ms = configuration?.closeTimeoutMs ?? configuration?.cleanupTimeoutMs;
25
- return typeof ms === 'number' && Number.isSafeInteger(ms) && ms > 0 ? Math.min(2_147_483_647, ms + 5000) : undefined;
26
- }
27
- export function requestedTraceRoot(value, runId) {
28
- if (!runId || !value || typeof value !== 'object' || !('kind' in value) || value.kind !== 'trace.request' ||
29
- !('runDirectory' in value) || typeof value.runDirectory !== 'string' || !isAbsolute(value.runDirectory) ||
30
- basename(value.runDirectory) !== runId)
31
- return;
32
- return value.runDirectory;
33
- }
34
- export async function loadHarness(launchDirectory, specifier, options) {
35
- const application = findApplication(specifier);
36
- if (application && !application.available)
37
- throw new Error(application.title + ' is not included in this SDK build.');
38
- const { module, definition } = await loadProjectHarnessModule(launchDirectory, specifier, builtins, options);
39
- const observe = typeof module.observe === 'function'
40
- ? module.observe
41
- : undefined;
42
- const actions = new Map();
43
- if (module.slashActions && typeof module.slashActions === 'object') {
44
- for (const [name, handler] of Object.entries(module.slashActions)) {
45
- if (!/^[a-z][\w-]*$/.test(name) || typeof handler !== 'function') {
46
- throw new Error('Harness slashActions must map command names to functions.');
4
+ export async function prepareProjectLaunch(command, launchDirectory, options, signal) {
5
+ const { module, definition } = await loadProjectHarnessModule(launchDirectory, command.harness, builtins, options);
6
+ signal.throwIfAborted();
7
+ let cwd = command.mode === 'foreground' ? command.cwd : undefined;
8
+ let configuration;
9
+ let stopTimeoutMs;
10
+ if (command.mode === 'foreground' && typeof module.resolveWorkspace === 'function') {
11
+ configuration = await loadProjectConfiguration(launchDirectory, command.configPath);
12
+ signal.throwIfAborted();
13
+ if (cwd === undefined) {
14
+ try {
15
+ cwd = module.resolveWorkspace({ cwd: launchDirectory, configuration });
16
+ }
17
+ catch {
18
+ throw new ProjectPreflightError('INVALID_RUN_CONFIGURATION', 'Could not resolve the Harness workspace');
19
+ }
20
+ if (typeof cwd !== 'string' || !cwd.trim()) {
21
+ throw new ProjectPreflightError('INVALID_RUN_CONFIGURATION', 'The Harness workspace resolver must return a directory');
47
22
  }
48
- actions.set(name, handler);
23
+ }
24
+ const config = configuration;
25
+ const timeout = config?.closeTimeoutMs ?? config?.cleanupTimeoutMs;
26
+ if (typeof timeout === 'number' && Number.isSafeInteger(timeout) && timeout > 0) {
27
+ stopTimeoutMs = Math.min(2_147_483_647, timeout + 5000);
49
28
  }
50
29
  }
51
- const workspace = typeof module.resolveWorkspace === 'function'
52
- ? module.resolveWorkspace
53
- : undefined;
54
- return { definition, observe, actions, workspace };
55
- }
56
- export function harnessLifetime(harness, requested, preferred) {
57
- const supported = harness.lifetimes ?? ['task'];
58
- const lifetime = requested ?? (preferred && supported.includes(preferred) ? preferred : supported[0]);
59
- if (!supported.includes(lifetime))
60
- throw new Error('This Harness does not support the requested lifetime.');
61
- return lifetime;
62
- }
63
- export function splitInput(text) {
64
- const end = text.search(/\s/);
65
- return end < 0 ? [text, ''] : [text.slice(0, end), text.slice(end).trimStart()];
66
- }
67
- export function interactiveTerminal() {
68
- return process.stdin.isTTY && process.stdout.isTTY && process.env.TERM !== 'dumb';
69
- }
70
- export async function runHarnessSelection(command, launchDirectory, options) {
71
- if (command.mode === 'action') {
72
- const { runHarnessAction } = await import('./anyswarm-project.js');
73
- return runHarnessAction(command, launchDirectory, options);
74
- }
75
- const mode = command.mode === 'auto' ? (interactiveTerminal() ? 'tui' : 'headless') : command.mode;
76
- if (mode === 'tui') {
77
- const { runAnySwarmTui } = await import('./anyswarm-tui.js');
78
- return runAnySwarmTui({ ...command, command: 'tui' }, launchDirectory);
79
- }
80
- const { runProjectCommand } = await import('./anyswarm-project.js');
81
- const project = { ...command, command: 'harness', defaults: true };
82
- if (mode === 'rpc')
83
- return runProjectCommand({ ...project, mode }, launchDirectory, options);
84
- return runProjectCommand({ ...project, mode, cwd: command.cwd && resolve(launchDirectory, command.cwd),
85
- prompt: command.prompt ?? 'Run this Harness.' }, launchDirectory, options);
30
+ const session = createHarnessSession(definition, {
31
+ launchDirectory, configuration, stopTimeoutMs,
32
+ configPath: configuration === undefined ? command.configPath : undefined, outputRoot: command.outputRoot,
33
+ lifetime: command.mode === 'foreground' ? 'task' : command.lifetime,
34
+ clientCapabilities: { questions: command.mode === 'rpc' && command.interaction === 'questions' },
35
+ });
36
+ return { session, cwd, harnessId: definition.id };
86
37
  }
@@ -0,0 +1,6 @@
1
+ import type { HarnessEvent, HarnessResult, HarnessSession } from '../src/harness/harness-session-types.js';
2
+ export declare function foregroundProgress(session: HarnessSession, harnessId: string, launchDirectory: string, outputRoot: string | undefined, write: (message: string) => Promise<void>): {
3
+ observe: (event: HarnessEvent) => void;
4
+ finish(result: HarnessResult): Promise<void>;
5
+ fail(code: string, message?: string): Promise<void>;
6
+ };
@@ -0,0 +1,102 @@
1
+ import { dirname, join, resolve } from 'node:path';
2
+ import { homedir } from 'node:os';
3
+ function object(value) {
4
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
5
+ }
6
+ function shellPath(path) {
7
+ return /^[\w./-]+$/.test(path) ? path : "'" + path.replaceAll("'", "'\\''") + "'";
8
+ }
9
+ const serviceActions = new Set(['service.register', 'service.start', 'service.restart', 'service.stop', 'service.retire']);
10
+ export function foregroundProgress(session, harnessId, launchDirectory, outputRoot, write) {
11
+ const root = outputRoot ? resolve(launchDirectory, outputRoot)
12
+ : resolve(process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'anyswarm', 'runs');
13
+ const report = (message) => write(message.replace(/[\p{Cc}\p{Cf}]/gu, character => '\\u' + character.charCodeAt(0).toString(16).padStart(4, '0')));
14
+ const trace = (directory) => report('Trace anyswarm trace --root ' + shellPath(directory));
15
+ void report('Starting ' + harnessId);
16
+ void trace(root);
17
+ const agents = new Map();
18
+ let phase;
19
+ let services;
20
+ let closed = false;
21
+ function observe(event) {
22
+ if (event.type === 'state' || event.type === 'snapshot') {
23
+ if (phase !== event.state.phase) {
24
+ phase = event.state.phase;
25
+ if (phase === 'running') {
26
+ void report('Harness running');
27
+ services = session.services.list().then(async (sources) => {
28
+ const names = [...new Set(sources.map(source => source.name))].sort();
29
+ if (!closed && names.length)
30
+ await report('Services available ' + names.join(', '));
31
+ }).catch(() => { });
32
+ }
33
+ if (phase === 'stopping')
34
+ void report('Stopping Run and waiting for cleanup');
35
+ }
36
+ if (!Array.isArray(event.state.agents))
37
+ return;
38
+ for (const item of event.state.agents) {
39
+ const { id, profile, status } = object(item);
40
+ if (typeof id !== 'string' || typeof profile !== 'string' || typeof status !== 'string')
41
+ continue;
42
+ const previous = agents.get(id);
43
+ if (status === previous)
44
+ continue;
45
+ agents.set(id, status);
46
+ const label = profile + ' [' + id.slice(0, 8) + ']';
47
+ if (status === 'starting')
48
+ void report('Agent starting ' + label);
49
+ if ((!previous || previous === 'starting') && (status === 'idle' || status === 'running')) {
50
+ void report('Sandbox ready ' + label);
51
+ }
52
+ if (status === 'closed')
53
+ void report('Agent closed ' + label);
54
+ }
55
+ }
56
+ if (event.type !== 'event')
57
+ return;
58
+ const { kind, event: raw } = object(event.event);
59
+ if (kind !== 'agent')
60
+ return;
61
+ const runtime = object(raw);
62
+ if (runtime.type === 'settled' && typeof runtime.agentId === 'string') {
63
+ void report('Agent settled [' + runtime.agentId.slice(0, 8) + '] ' + String(runtime.outcome));
64
+ }
65
+ if (runtime.type !== 'management')
66
+ return;
67
+ const { operation, definition } = object(runtime.change);
68
+ const { id, state } = object(definition);
69
+ if (typeof operation === 'string' && serviceActions.has(operation) && typeof id === 'string' && typeof state === 'string') {
70
+ void report('Service ' + operation.slice('service.'.length) + ' ' + id + ' (' + state + ')');
71
+ }
72
+ }
73
+ return {
74
+ observe,
75
+ async finish(result) {
76
+ await services;
77
+ closed = true;
78
+ const message = result.failure?.message ?? result.reportSaveFailure?.message;
79
+ void report('Run ' + result.outcome + ' ' + result.reason + (message ? ' (' + message + ')' : ''));
80
+ for (const artifact of result.artifacts.slice(0, 5)) {
81
+ const path = typeof artifact === 'string' ? artifact : object(artifact).path;
82
+ if (typeof path === 'string')
83
+ void report('Artifact ' + path);
84
+ }
85
+ if (result.artifacts.length > 5)
86
+ void report('Additional artifacts ' + (result.artifacts.length - 5));
87
+ if (result.export)
88
+ void report('Export ' + result.export.status);
89
+ void report('Cleanup ' + result.cleanup.status);
90
+ if (result.reportPath)
91
+ void report('Run report ' + result.reportPath);
92
+ const prompt = object(object(result).prompt).path;
93
+ const recordPath = result.reportPath ?? (typeof prompt === 'string' ? prompt : undefined);
94
+ await trace(recordPath ? dirname(dirname(recordPath)) : root);
95
+ },
96
+ async fail(code, message) {
97
+ closed = true;
98
+ void report(code + (message ? ' ' + message : ''));
99
+ await trace(root);
100
+ },
101
+ };
102
+ }
@@ -1,12 +1,4 @@
1
- import type { HarnessCommand, ProjectCommand } from './anyswarm-arguments.js';
2
- import { loadHarness, type ActionRun } from './anyswarm-launch.js';
1
+ import type { ProjectCommand } from './anyswarm-arguments.js';
3
2
  export declare function runProjectCommand(command: ProjectCommand, launchDirectory: string, options?: {
4
3
  onSourceError?: (error: unknown) => void;
5
- action?: {
6
- run: ActionRun;
7
- loaded: Awaited<ReturnType<typeof loadHarness>>;
8
- };
9
4
  }): Promise<number | undefined>;
10
- export declare function runHarnessAction(command: Extract<HarnessCommand, {
11
- mode: 'action';
12
- }>, launchDirectory: string, options?: Parameters<typeof loadHarness>[2]): Promise<number | undefined>;