@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.
- package/AGENTS.md +19 -4
- package/README.md +68 -61
- package/dist/examples/README.md +134 -84
- package/dist/examples/autoresearch/README.md +106 -21
- package/dist/examples/autoresearch/REQUIREMENTS.zh.md +14 -6
- package/dist/examples/autoresearch/config.d.ts +48 -5
- package/dist/examples/autoresearch/config.js +57 -23
- package/dist/examples/autoresearch/demo.d.ts +12 -4
- package/dist/examples/autoresearch/demo.js +65 -22
- package/dist/examples/autoresearch/frontiercs2-config.d.ts +2 -2
- package/dist/examples/autoresearch/frontiercs2-config.js +13 -2
- package/dist/examples/autoresearch/frontiercs2.d.ts +18 -1
- package/dist/examples/autoresearch/frontiercs2.js +71 -14
- package/dist/examples/autoresearch/prepare-demo.js +34 -3
- package/dist/examples/autoresearch/prepare.d.ts +105 -53
- package/dist/examples/autoresearch/prepare.js +126 -57
- package/dist/examples/autoresearch/project.d.ts +6 -1
- package/dist/examples/autoresearch/project.js +130 -26
- package/dist/examples/autoresearch/research-service.d.ts +16 -1
- package/dist/examples/autoresearch/research-service.js +84 -44
- package/dist/examples/code/config.d.ts +1 -0
- package/dist/examples/first-harness/AGENTS.md +25 -0
- package/dist/examples/first-harness/README.md +136 -0
- package/dist/examples/first-harness/config.d.ts +9 -8
- package/dist/examples/first-harness/config.js +33 -26
- package/dist/examples/first-harness/eject.json +14 -0
- package/dist/examples/first-harness/handoff.js +3 -3
- package/dist/examples/first-harness/harness.d.ts +14 -18
- package/dist/examples/first-harness/harness.js +102 -77
- package/dist/examples/first-harness/input/README.md +7 -0
- package/dist/examples/first-harness/session.js +2 -1
- package/dist/examples/first-harness/tsconfig.json +2 -1
- package/dist/examples/harness-session/README.md +1 -1
- package/dist/examples/lead-worker/README.md +1 -1
- package/dist/examples/lead-worker/project-config.d.ts +1 -0
- package/dist/examples/messages/README.md +2 -2
- package/dist/examples/notes/README.md +2 -2
- package/dist/examples/notes/config.d.ts +1 -0
- package/dist/examples/parallel-swarm/AGENTS.md +32 -0
- package/dist/examples/parallel-swarm/README.md +136 -0
- package/dist/examples/parallel-swarm/board-service.js +25 -8
- package/dist/examples/parallel-swarm/board.d.ts +31 -1
- package/dist/examples/parallel-swarm/board.js +98 -13
- package/dist/examples/parallel-swarm/config.d.ts +11 -0
- package/dist/examples/parallel-swarm/config.js +39 -0
- package/dist/examples/parallel-swarm/eject.json +5 -0
- package/dist/examples/parallel-swarm/harness.d.ts +26 -20
- package/dist/examples/parallel-swarm/harness.js +77 -76
- package/dist/examples/parallel-swarm/report.d.ts +12 -0
- package/dist/examples/parallel-swarm/report.js +30 -0
- package/dist/examples/peermesh/README.md +1 -1
- package/dist/examples/peermesh/project-config.d.ts +1 -0
- package/dist/examples/services/agent-control/README.md +1 -1
- package/dist/examples/services/mathlib-search/README.md +1 -1
- package/dist/examples/services/mcp-managed/README.md +1 -1
- package/dist/examples/services/persistent-board/README.md +1 -1
- package/dist/examples/subagents/AGENTS.md +35 -0
- package/dist/examples/subagents/README.md +129 -93
- package/dist/examples/subagents/config.d.ts +2 -10
- package/dist/examples/subagents/config.js +8 -15
- package/dist/examples/subagents/eject.json +17 -0
- package/dist/examples/subagents/handoff-config.d.ts +41 -0
- package/dist/examples/subagents/handoff-config.js +13 -0
- package/dist/examples/subagents/model.d.ts +3 -0
- package/dist/examples/subagents/model.js +19 -0
- package/dist/examples/substrate/README.md +12 -6
- package/dist/examples/substrate/config.d.ts +1 -0
- package/dist/examples/substrate/project-config.d.ts +1 -0
- package/dist/examples/taskpool/README.md +1 -1
- package/dist/examples/taskpool/config.d.ts +1 -0
- package/dist/examples/taskpool/deploy/service-hosts/service-authority-snapshot.d.ts +4 -4
- package/dist/scripts/anyswarm-progress.js +36 -5
- package/dist/scripts/build-provenance.json +1 -1
- package/dist/scripts/generate-architecture-coverage.js +1 -1
- package/dist/scripts/generate-architecture-prompts.js +18 -10
- package/dist/scripts/local-environment.d.ts +3 -3
- package/dist/scripts/local-environment.js +6 -1
- package/dist/scripts/local-setup.js +25 -18
- package/dist/scripts/pack-release.js +27 -3
- package/dist/src/core/index.js +1 -1
- package/dist/src/core/sandbox/opensandbox-backend.js +10 -4
- package/dist/src/core/sandbox/sandbox-connection.d.ts +9 -2
- package/dist/src/core/sandbox/sandbox-connection.js +22 -7
- package/dist/src/harness/project-harness.js +3 -2
- package/dist/src/harness/project-rpc-client.js +19 -0
- package/dist/src/harness/typescript-loader.d.ts +2 -0
- package/dist/src/harness/typescript-loader.js +26 -8
- package/dist/src/trace-viewer/command.mjs +6 -3
- package/dist/src/trace-viewer/public/app.js +239 -59
- package/dist/src/trace-viewer/public/index.html +5 -0
- package/dist/src/trace-viewer/public/style.css +22 -0
- package/dist/src/trace-viewer/reader.mjs +242 -26
- package/dist/src/trace-viewer/run-root.d.mts +1 -0
- package/dist/src/trace-viewer/run-root.mjs +7 -0
- package/dist/src/trace-viewer/server.mjs +3 -1
- package/docs/INDEX.md +9 -8
- package/docs/architecture/06-observability-experiments.md +21 -7
- package/docs/architecture/07-run-configuration.md +97 -12
- package/docs/architecture/08-prompts.md +21 -2
- package/docs/architecture/10-service-api-reference.md +12 -5
- package/docs/architecture/12-code-coverage.md +129 -86
- package/docs/architecture/15-core-runtime.md +1 -1
- package/docs/architecture/16-pi-opensandbox-backend.md +2 -0
- package/docs/architecture/17-harness-reporting.md +78 -0
- package/docs/architecture/22-website.md +53 -18
- package/docs/architecture/23-project-harness.md +63 -16
- package/docs/architecture/28-autoresearch.md +16 -22
- package/docs/architecture/prompts/11-first-sdk-harness.md +9 -9
- package/docs/architecture/prompts/16-parallel-swarm.md +46 -13
- package/docs/architecture/prompts/22-autoresearch.md +9 -2
- package/docs/architecture/prompts/source-manifest.json +78 -54
- package/docs/architecture/source-map.json +396 -36
- package/docs/designs/core-harness/06-project-harness.md +1 -1
- package/docs/en/autoresearch.md +41 -0
- package/docs/en/blog/100b-tokens.md +157 -0
- package/docs/en/build-your-harness.md +47 -22
- package/docs/en/changelog.md +22 -1
- package/docs/en/first-harness.md +40 -32
- package/docs/en/harnesses/index.md +23 -23
- package/docs/en/harnesses/subagents.md +8 -29
- package/docs/en/latest.md +26 -5
- package/docs/en/overview.md +22 -22
- package/docs/en/quickstart.md +55 -21
- package/docs/en/reference/api.md +1 -1
- package/docs/en/trace-viewer.md +32 -12
- package/docs/operations/trace-viewer.md +25 -10
- package/docs/workflows/development.md +160 -120
- package/docs/workflows/release-and-docs-versioning.md +207 -55
- package/docs/workflows/release-cli-acceptance.md +124 -47
- package/docs/zh/autoresearch.md +41 -0
- package/docs/zh/blog/100b-tokens.md +102 -0
- package/docs/zh/build-your-harness.md +48 -23
- package/docs/zh/changelog.md +22 -1
- package/docs/zh/first-harness.md +43 -35
- package/docs/zh/harnesses/index.md +23 -23
- package/docs/zh/harnesses/subagents.md +8 -29
- package/docs/zh/latest.md +26 -5
- package/docs/zh/overview.md +23 -23
- package/docs/zh/quickstart.md +51 -21
- package/docs/zh/reference/api.md +1 -1
- package/docs/zh/trace-viewer.md +32 -12
- package/examples/README.md +134 -84
- package/examples/autoresearch/README.md +106 -21
- package/examples/autoresearch/REQUIREMENTS.zh.md +14 -6
- package/examples/autoresearch/config.ts +64 -25
- package/examples/autoresearch/demo.ts +75 -22
- package/examples/autoresearch/frontiercs2-config.ts +13 -2
- package/examples/autoresearch/frontiercs2.ts +64 -11
- package/examples/autoresearch/prepare-demo.ts +32 -3
- package/examples/autoresearch/prepare.ts +134 -60
- package/examples/autoresearch/project.ts +119 -26
- package/examples/autoresearch/research-service.ts +91 -41
- package/examples/first-harness/AGENTS.md +25 -0
- package/examples/first-harness/README.md +136 -0
- package/examples/first-harness/config.ts +41 -27
- package/examples/first-harness/eject.json +14 -0
- package/examples/first-harness/handoff.ts +3 -3
- package/examples/first-harness/harness.ts +104 -72
- package/examples/first-harness/input/README.md +7 -0
- package/examples/first-harness/session.ts +2 -1
- package/examples/first-harness/tsconfig.json +2 -1
- package/examples/harness-session/README.md +1 -1
- package/examples/lead-worker/README.md +1 -1
- package/examples/messages/README.md +2 -2
- package/examples/notes/README.md +2 -2
- package/examples/parallel-swarm/AGENTS.md +32 -0
- package/examples/parallel-swarm/README.md +136 -0
- package/examples/parallel-swarm/board-service.ts +28 -9
- package/examples/parallel-swarm/board.ts +107 -13
- package/examples/parallel-swarm/config.ts +47 -0
- package/examples/parallel-swarm/eject.json +5 -0
- package/examples/parallel-swarm/harness.ts +83 -71
- package/examples/parallel-swarm/report.ts +33 -0
- package/examples/peermesh/README.md +1 -1
- package/examples/services/agent-control/README.md +1 -1
- package/examples/services/mathlib-search/README.md +1 -1
- package/examples/services/mcp-managed/README.md +1 -1
- package/examples/services/persistent-board/README.md +1 -1
- package/examples/subagents/AGENTS.md +35 -0
- package/examples/subagents/README.md +129 -93
- package/examples/subagents/config.ts +8 -15
- package/examples/subagents/eject.json +17 -0
- package/examples/subagents/handoff-config.ts +14 -0
- package/examples/subagents/model.ts +20 -0
- package/examples/substrate/README.md +12 -6
- package/examples/taskpool/README.md +1 -1
- package/npm-shrinkwrap.development.json +9 -2
- package/npm-shrinkwrap.json +9 -2
- package/package.development.json +2 -1
- package/package.json +2 -1
- package/scripts/anyswarm-progress.ts +36 -6
- package/scripts/generate-architecture-coverage.ts +1 -1
- package/scripts/generate-architecture-prompts.ts +21 -10
- package/scripts/local-environment.ts +8 -1
- package/scripts/local-setup.ts +22 -17
- package/scripts/pack-release.ts +24 -3
- package/src/core/index.ts +1 -1
- package/src/core/sandbox/opensandbox-backend.ts +10 -4
- package/src/core/sandbox/sandbox-connection.ts +22 -7
- package/src/harness/project-harness.ts +3 -2
- package/src/harness/project-rpc-client.ts +23 -0
- package/src/harness/typescript-loader.ts +28 -8
- package/src/trace-viewer/command.mjs +6 -3
- package/src/trace-viewer/public/app.js +239 -59
- package/src/trace-viewer/public/index.html +5 -0
- package/src/trace-viewer/public/style.css +22 -0
- package/src/trace-viewer/reader.mjs +242 -26
- package/src/trace-viewer/run-root.d.mts +1 -0
- package/src/trace-viewer/run-root.mjs +7 -0
- package/src/trace-viewer/server.mjs +3 -1
|
@@ -15,7 +15,7 @@ const safe = (path: any) => typeof path === 'string' && path !== '' && !path.sta
|
|
|
15
15
|
// runtime inputs. They can contain dependency symlinks and must never affect
|
|
16
16
|
// the tracked source inventory.
|
|
17
17
|
const skipRoots = new Set(['.git', '.worktree', '.worktrees', '.claude', 'node_modules', 'dist', '.codex', 'docs', 'test', 'test-support', 'experiments', 'reports']);
|
|
18
|
-
const skipPaths = new Set(['third_party/agensh', 'website/.astro', 'website/dist', 'website/node_modules']);
|
|
18
|
+
const skipPaths = new Set(['third_party/agensh', 'website/.astro', 'website/.generated', 'website/dist', 'website/node_modules']);
|
|
19
19
|
async function walk(directory: any, prefix: any = ''): Promise<any> {
|
|
20
20
|
const files: any[] = [];
|
|
21
21
|
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
@@ -97,11 +97,12 @@ const outputs = new Map<string, string>();
|
|
|
97
97
|
function output(file: string, text: string) { outputs.set(`${outputDir}/${file}`, `${text.trimEnd()}\n`); }
|
|
98
98
|
|
|
99
99
|
const researchSource = 'examples/autoresearch/project.ts';
|
|
100
|
-
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.
|
|
100
|
+
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.');
|
|
101
101
|
researchDoc += block('Shared Profile instruction', evaluate('`' + between(researchSource, 'const instructions = `', '`;') + '`', { candidatePath: '.anyswarm-candidate.patch' }));
|
|
102
102
|
researchDoc += block('Initial peer input', evaluate('`' + between(researchSource, '? `', '`\n', 'const prompt = turn === 0') + '`',
|
|
103
103
|
{ label: '<PEER_LABEL>', config: { goal: '<RESEARCH_GOAL>' }, context: { input: { prompt: '<RUN_INPUT>' } } }));
|
|
104
|
-
researchDoc += block('Follow-up peer input', between(researchSource, ": '", "';",
|
|
104
|
+
researchDoc += block('Follow-up peer input while train is available', between(researchSource, ": '", "';", 'const remainingWork = trainExhausted'));
|
|
105
|
+
researchDoc += block('Follow-up peer input after the train budget is used', between(researchSource, "? '", "'\n", 'const remainingWork = trainExhausted'));
|
|
105
106
|
researchDoc += block('Candidate review notice', evaluate('`' + between(researchSource, 'return `', '`;', 'function reviewNotice') + '`',
|
|
106
107
|
{ candidate: '<CANDIDATE_ID>', sha256: '<CANDIDATE_SHA256>' }));
|
|
107
108
|
researchDoc += block('FrontierCS-2 demo objective', between('examples/autoresearch/config.ts', "export const demoGoal = '", "';"));
|
|
@@ -381,16 +382,26 @@ output('11-first-sdk-harness.md', '# First SDK Harness prompts\n\n'
|
|
|
381
382
|
].join('\n'), 'Startup discovery includes the purpose and the description for the operation granted to that Agent.'));
|
|
382
383
|
const parallelHost = 'examples/parallel-swarm/harness.ts';
|
|
383
384
|
const parallelService = 'examples/parallel-swarm/board-service.ts';
|
|
385
|
+
const parallelLiteral = (name: string) => evaluate(between(parallelHost, `const ${name} = `, ';\n'));
|
|
386
|
+
const researchFocuses = parallelLiteral('researchFocuses') as string[];
|
|
387
|
+
const researchTemplate = between(parallelHost, 'runInput(runtime, peer.id,\n `', '`,');
|
|
388
|
+
const synthesisTemplate = between(parallelHost, 'runInput(runtime, synth.id, `', '`,');
|
|
389
|
+
const parallelInput = { input: { prompt: '<ORIGINAL_USER_PROMPT>' } };
|
|
384
390
|
output('16-parallel-swarm.md', '# Parallel Swarm prompts\n\n'
|
|
385
|
-
+ block('Researcher Profile',
|
|
386
|
-
+ block('Synthesizer Profile',
|
|
387
|
-
+ block(
|
|
388
|
-
|
|
389
|
-
|
|
391
|
+
+ block('Researcher Profile', parallelLiteral('researcherPrompt'))
|
|
392
|
+
+ block('Synthesizer Profile', parallelLiteral('synthesizerPrompt'))
|
|
393
|
+
+ researchFocuses.map((_, index) => block(`First research round: researcher ${index + 1}`,
|
|
394
|
+
evaluate('`' + researchTemplate + '`', { context: parallelInput, researchFocuses, index }),
|
|
395
|
+
'The user question comes from context.input.prompt; the focus is selected by this researcher’s host-assigned index.')).join('\n')
|
|
396
|
+
+ block('Peer review round', parallelLiteral('reviewInput'),
|
|
397
|
+
'The host sends this to all three original researchers only after every first-round contribution passes.')
|
|
398
|
+
+ block('Synthesis round', evaluate('`' + synthesisTemplate + '`', {
|
|
399
|
+
synthesisInput: parallelLiteral('synthesisInput'), context: parallelInput,
|
|
400
|
+
}))
|
|
390
401
|
+ block('Board discovery', [
|
|
391
|
-
between(parallelService,
|
|
392
|
-
between(parallelService,
|
|
393
|
-
between(parallelService,
|
|
402
|
+
evaluate(between(parallelService, 'purpose: ', ',\n')),
|
|
403
|
+
evaluate(between(parallelService, 'description: ', ',\n', "operation: 'publish',")),
|
|
404
|
+
evaluate(between(parallelService, 'description: ', ',\n', "operation: 'search',")),
|
|
394
405
|
].join('\n'), 'Each Profile receives guidance for the admitted operations. The shared board stores the actual authenticated caller.'));
|
|
395
406
|
const durableBoardPath = 'examples/services/persistent-board/run.ts';
|
|
396
407
|
output('17-persistent-board.md', header('Persistent Board Service example prompts',
|
|
@@ -140,6 +140,13 @@ export async function resolveLocalDocker() {
|
|
|
140
140
|
export async function checkLocalDocker() {
|
|
141
141
|
try {
|
|
142
142
|
const docker = await resolveLocalDocker();
|
|
143
|
+
const version = /^(\d+)\.(\d+)\./.exec(docker.engineVersion ?? '');
|
|
144
|
+
if (!darwin && docker.rootless && version &&
|
|
145
|
+
(Number(version[1]) < 29 || (Number(version[1]) === 29 && Number(version[2]) < 5))) {
|
|
146
|
+
return { diagnostic: check('host.docker-engine', false,
|
|
147
|
+
`Rootless Docker Engine ${docker.engineVersion} cannot expose the local OpenSandbox host-network port to this host.`,
|
|
148
|
+
'Use Docker Engine 29.5 or newer, a rootful local Docker context, or an existing OpenSandbox endpoint.') };
|
|
149
|
+
}
|
|
143
150
|
const engine = [`Linux Docker Engine`, docker.engineVersion, `(${docker.rootless ? 'rootless' : 'rootful'})`].filter(Boolean).join(' ');
|
|
144
151
|
const client = docker.clientVersion ? `Docker CLI ${docker.clientVersion}` : '';
|
|
145
152
|
const context = docker.context ? `context ${docker.context}` : '';
|
|
@@ -390,7 +397,7 @@ async function ensureLocalProviderLocked(config: LocalEnvironmentConfig, { signa
|
|
|
390
397
|
if (existing) throw Object.assign(new Error('The key for the managed provider is missing'), { code: 'PROVIDER_AUTHENTICATION' });
|
|
391
398
|
try { await writeFile(filename, randomBytes(32).toString('hex'), { mode: 0o600, flag: 'wx' }); }
|
|
392
399
|
catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; }
|
|
393
|
-
config = { ...config, apiKey: resolveSandboxConnection({ lifecycleBaseUrl: config.lifecycleBaseUrl }).apiKey };
|
|
400
|
+
config = { ...config, apiKey: resolveSandboxConnection({ lifecycleBaseUrl: config.lifecycleBaseUrl }, undefined, { discoverHost: false }).apiKey };
|
|
394
401
|
}
|
|
395
402
|
if (!config.apiKey) throw new Error('Could not load the owner-only OpenSandbox lifecycle key.');
|
|
396
403
|
if (existing) {
|
package/scripts/local-setup.ts
CHANGED
|
@@ -16,6 +16,7 @@ import { checkLocalExecutor, findExecutorEntry, type LocalExecutorSelection } fr
|
|
|
16
16
|
import { resolveFilePolicy, type ResolvedFilePolicy } from '../src/core/file-policy.js';
|
|
17
17
|
import { claimOpenSandboxBackend, createSandbox } from '../src/core/sandbox/opensandbox-backend.js';
|
|
18
18
|
import { snapshotModel } from '../src/core/model/model-access.js';
|
|
19
|
+
import { readSubagentsModel } from '../examples/subagents/model.js';
|
|
19
20
|
import { modelClientProtocol } from '../src/core/model/model-transport.js';
|
|
20
21
|
import type { SandboxConfig } from '../src/core/backend-config.js';
|
|
21
22
|
import { loadAnySwarmConfig, loopbackLifecycle, saveSandboxConnection } from '../src/core/sandbox/sandbox-connection.js';
|
|
@@ -256,13 +257,16 @@ export async function runLocalCommand(command: LocalCommand, signal: AbortSignal
|
|
|
256
257
|
checks.push({ id: 'config.executor', ok: false, detail: 'Select a configured executor.' });
|
|
257
258
|
return report;
|
|
258
259
|
}
|
|
260
|
+
stage = 'connection';
|
|
261
|
+
const configuredPublicUrl = config?.connection?.publicUrl ?? config?.connection?.bridge?.publicUrl ?? config?.connection?.modelGateway?.publicUrl;
|
|
259
262
|
const environment = await resolveLocalEnvironment({
|
|
260
263
|
...config?.sandbox,
|
|
261
264
|
...(command.command === 'setup' && command.endpoint ? { endpoint: command.endpoint, lifecycleBaseUrl: undefined } : {}),
|
|
262
|
-
publicUrl: command.command === 'setup' ? command.publicUrl ??
|
|
265
|
+
publicUrl: command.command === 'setup' ? command.publicUrl ?? configuredPublicUrl : configuredPublicUrl,
|
|
263
266
|
image: config?.image,
|
|
264
267
|
advertiseHost: config?.connection?.advertiseHost ?? config?.connection?.modelGateway?.advertiseHost,
|
|
265
268
|
});
|
|
269
|
+
stage = 'config';
|
|
266
270
|
const hostname = new URL(environment.lifecycleBaseUrl).hostname;
|
|
267
271
|
const loopback = hostname === 'localhost' || hostname === '[::1]' || hostname.startsWith('127.') && isIP(hostname) === 4;
|
|
268
272
|
const reuseExisting = loopback && (environment.management === 'existing' ||
|
|
@@ -322,22 +326,16 @@ export async function runLocalCommand(command: LocalCommand, signal: AbortSignal
|
|
|
322
326
|
}
|
|
323
327
|
}
|
|
324
328
|
}
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
const route = {
|
|
329
|
-
provider: process.env.ANYSWARM_MODEL_PROVIDER ?? process.env.ANYSWARM_SUBAGENTS_MODEL_PROVIDER ?? 'openai',
|
|
330
|
-
model: modelId || 'gpt-5.4', protocol: process.env.ANYSWARM_MODEL_PROTOCOL,
|
|
331
|
-
upstream: { url: modelUrl, headers: {} },
|
|
332
|
-
};
|
|
329
|
+
if (config) {
|
|
330
|
+
report.model = modelState(config, driver.kind);
|
|
331
|
+
} else {
|
|
333
332
|
try {
|
|
334
|
-
|
|
335
|
-
|
|
333
|
+
const route = readSubagentsModel(driver.kind);
|
|
334
|
+
if (route) snapshotModel(route, driver.kind);
|
|
335
|
+
report.model = { configuration: route ? 'complete' : 'missing', verification: 'not-verified' };
|
|
336
336
|
} catch {
|
|
337
337
|
report.model = { configuration: 'invalid', verification: 'not-verified' };
|
|
338
338
|
}
|
|
339
|
-
} else {
|
|
340
|
-
report.model = config ? modelState(config, driver.kind) : { configuration: 'missing', verification: 'not-verified' };
|
|
341
339
|
}
|
|
342
340
|
if (report.model.configuration === 'missing') {
|
|
343
341
|
report.model.remedy = config ? 'Set an upstream endpoint for each active model route in the trusted configuration.'
|
|
@@ -350,7 +348,8 @@ export async function runLocalCommand(command: LocalCommand, signal: AbortSignal
|
|
|
350
348
|
if (config && report.model.configuration !== 'invalid') {
|
|
351
349
|
const { lifecycleBaseUrl, apiKey, endpointHost } = environment;
|
|
352
350
|
checks.push(checkProjectRuntime({
|
|
353
|
-
...config, executor, connection: { ...config.connection, publicUrl: environment.publicUrl
|
|
351
|
+
...config, executor, connection: { ...config.connection, publicUrl: environment.publicUrl,
|
|
352
|
+
advertiseHost: environment.advertiseHost },
|
|
354
353
|
}, { ...config.sandbox, endpoint: undefined, lifecycleBaseUrl, apiKey, endpointHost }));
|
|
355
354
|
}
|
|
356
355
|
report.configuration = {
|
|
@@ -359,7 +358,7 @@ export async function runLocalCommand(command: LocalCommand, signal: AbortSignal
|
|
|
359
358
|
image: environment.image ?? workerImageFor(executor),
|
|
360
359
|
filePolicy: resolveFilePolicy(config?.filePolicy),
|
|
361
360
|
};
|
|
362
|
-
const publicUrl = environment.publicUrl
|
|
361
|
+
const publicUrl = environment.publicUrl;
|
|
363
362
|
report.connection = {
|
|
364
363
|
lifecycleBaseUrl: reportedEndpoint(environment.lifecycleBaseUrl),
|
|
365
364
|
advertiseHost: reportedHost(environment.advertiseHost),
|
|
@@ -458,14 +457,20 @@ export async function runLocalCommand(command: LocalCommand, signal: AbortSignal
|
|
|
458
457
|
// Configuration imports and provider/npm errors can contain credentials.
|
|
459
458
|
const failure: Record<string, [string, string]> = {
|
|
460
459
|
config: ['Could not load the project configuration.', 'Check the trusted config.js and adjacent .env file.'],
|
|
460
|
+
connection: ['Could not resolve the OpenSandbox connection.', 'Check the Lifecycle endpoint and Runtime callback settings.'],
|
|
461
461
|
host: ['Could not complete the host capability checks.', 'Check the installation diagnostics for the selected setup mode.'],
|
|
462
462
|
worker: ['Could not prepare the compatible Worker image.', 'Check local Docker and the configured Worker image.'],
|
|
463
463
|
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.'],
|
|
464
464
|
smoke: ['Could not complete the infrastructure probe.', 'Check the local OpenSandbox service, Worker image and host network.'],
|
|
465
465
|
};
|
|
466
466
|
let [detail, remedy] = failure[stage];
|
|
467
|
+
let checkId = stage;
|
|
467
468
|
const code = (error as { code?: string })?.code;
|
|
468
|
-
if (code === '
|
|
469
|
+
if (code === 'HOST_NETWORK_DISCOVERY_FAILED' && stage === 'connection') {
|
|
470
|
+
checkId = 'host.network-discovery';
|
|
471
|
+
detail = 'Could not inspect host network interfaces for the Sandbox callback address.';
|
|
472
|
+
remedy = 'Set ANYSWARM_ADVERTISE_HOST or ANYSWARM_RUNTIME_PUBLIC_URL to an address reachable from the Sandbox, then rerun the command.';
|
|
473
|
+
} else if (code === 'DOCKER_CALLBACK_UNAVAILABLE') {
|
|
469
474
|
detail = 'The Docker container could not resolve a unique Mac callback IPv4 address.';
|
|
470
475
|
remedy = 'Check host.docker.internal from the selected local engine, or configure a Runtime publicUrl reachable from the Sandbox.';
|
|
471
476
|
} else if (stage === 'provider' && ['PROVIDER_EXECD_PULL_FAILED', 'PROVIDER_SERVER_PULL_FAILED', 'PROVIDER_EGRESS_PULL_FAILED'].includes(code ?? '')) {
|
|
@@ -489,7 +494,7 @@ export async function runLocalCommand(command: LocalCommand, signal: AbortSignal
|
|
|
489
494
|
} else if (stage === 'provider' && rootlessDocker) {
|
|
490
495
|
remedy = 'Verify that the selected rootless Docker context can start containers and expose the Lifecycle address. Check delegated CPU and memory controllers before retrying.';
|
|
491
496
|
}
|
|
492
|
-
if (!signal.aborted) checks.push({ id:
|
|
497
|
+
if (!signal.aborted) checks.push({ id: checkId, ok: false, detail, remedy });
|
|
493
498
|
// A provider deployment can fail before returning its ownership handle.
|
|
494
499
|
if (stage === 'provider' && error && typeof error === 'object' && 'cleanup' in error && error.cleanup && typeof error.cleanup === 'object' &&
|
|
495
500
|
'id' in error.cleanup && typeof error.cleanup.id === 'string' && 'status' in error.cleanup &&
|
package/scripts/pack-release.ts
CHANGED
|
@@ -5,8 +5,19 @@ import { join, resolve } from 'node:path';
|
|
|
5
5
|
import { promisify } from 'node:util';
|
|
6
6
|
|
|
7
7
|
const [destination, ...options] = process.argv.slice(2);
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
let skipBuild = false;
|
|
9
|
+
let releaseVersion: string | undefined;
|
|
10
|
+
for (let index = 0; index < options.length; index++) {
|
|
11
|
+
const option = options[index];
|
|
12
|
+
if (option === '--skip-build' && !skipBuild) skipBuild = true;
|
|
13
|
+
else if (option === '--version' && releaseVersion === undefined) releaseVersion = options[++index];
|
|
14
|
+
else throw new Error(`Unsupported or repeated pack option: ${option}`);
|
|
15
|
+
}
|
|
16
|
+
if (!destination || options.includes('--version') && !releaseVersion) {
|
|
17
|
+
throw new Error('Usage: npm run pack:release -- <output-directory> [--skip-build] [--version <next-version>]');
|
|
18
|
+
}
|
|
19
|
+
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)) {
|
|
20
|
+
throw new Error('A staged version override must be an immutable next release version');
|
|
10
21
|
}
|
|
11
22
|
|
|
12
23
|
// Keep the build and staging umask independent of the caller.
|
|
@@ -15,7 +26,7 @@ process.umask(0o022);
|
|
|
15
26
|
const run = promisify(execFile);
|
|
16
27
|
const repository = resolve(import.meta.dirname, '..');
|
|
17
28
|
const output = resolve(destination);
|
|
18
|
-
if (!
|
|
29
|
+
if (!skipBuild) {
|
|
19
30
|
const build = spawnSync('npm', ['run', 'build'], { cwd: repository, stdio: ['ignore', 2, 2] });
|
|
20
31
|
if (build.error) throw build.error;
|
|
21
32
|
if (build.status !== 0) process.exit(build.status ?? 1);
|
|
@@ -37,6 +48,16 @@ try {
|
|
|
37
48
|
const manifestPath = join(staged, 'package.json');
|
|
38
49
|
const lockPath = join(staged, 'npm-shrinkwrap.json');
|
|
39
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
|
+
}
|
|
40
61
|
// Service images compile TypeScript. The Pi installation belongs to the executor.
|
|
41
62
|
delete manifest.devDependencies?.['@earendil-works/pi-coding-agent'];
|
|
42
63
|
await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
|
package/src/core/index.ts
CHANGED
|
@@ -220,7 +220,7 @@ function planRuntimeWorker(
|
|
|
220
220
|
}
|
|
221
221
|
return { kind: worker.executor, prepare: async () => worker };
|
|
222
222
|
}
|
|
223
|
-
const { localExecutor } = resolveSandboxConnectionWithSources({ lifecycleBaseUrl: endpoint });
|
|
223
|
+
const { localExecutor } = resolveSandboxConnectionWithSources({ lifecycleBaseUrl: endpoint }, undefined, { discoverHost: false });
|
|
224
224
|
const kind = options.executor ? config.driver.kind : selectors.find(selector => selector.kind)?.kind ?? localExecutor?.kind ?? config.driver.kind;
|
|
225
225
|
if (kind !== 'pi' && kind !== 'codex') throw executorFailure('Select Pi or Codex for the built-in local Worker.');
|
|
226
226
|
if (selectors.some(selector => selector.kind && selector.kind !== kind)) {
|
|
@@ -191,7 +191,7 @@ import { isDeepStrictEqual } from 'node:util';
|
|
|
191
191
|
import { isIP } from 'node:net';
|
|
192
192
|
import { lookup } from 'node:dns/promises';
|
|
193
193
|
import { createWorkerEventPoll } from '../worker-event-poll.js';
|
|
194
|
-
import { loopbackLifecycle, normalizeRuntimePublicUrl, resolveSandboxConnection } from './sandbox-connection.js';
|
|
194
|
+
import { discoverDockerCallbackHost, loopbackLifecycle, normalizeRuntimePublicUrl, resolveSandboxConnection } from './sandbox-connection.js';
|
|
195
195
|
import { validId } from '../config.js';
|
|
196
196
|
import { adaptSandboxProvider, createApiOpenSandboxProvider, type OpenSandboxProvider } from './opensandbox-provider.js';
|
|
197
197
|
|
|
@@ -294,7 +294,10 @@ export function createSandbox(config: SandboxConfig | SandboxProviderConfig = {}
|
|
|
294
294
|
}
|
|
295
295
|
}
|
|
296
296
|
const { lifecycleBaseUrl: _alias, endpoint: _endpoint, endpointHost: _endpointHost, ...settings } = sandbox;
|
|
297
|
-
|
|
297
|
+
// Runtime callback options are supplied at claim time, after this handle is
|
|
298
|
+
// created. Snapshot configured settings here without enumerating interfaces.
|
|
299
|
+
const { lifecycleBaseUrl, apiKey, publicUrl, advertiseHost, useServerProxy, egressMode } =
|
|
300
|
+
resolveSandboxConnection(sandbox, undefined, { discoverHost: false });
|
|
298
301
|
sandboxes.set(handle, freeze(structuredClone({
|
|
299
302
|
sandbox: { ...settings, lifecycleBaseUrl, apiKey, publicUrl, advertiseHost, useServerProxy, egressMode, timeoutSeconds },
|
|
300
303
|
isolation: { network: 'api' } as const,
|
|
@@ -316,10 +319,13 @@ export function claimOpenSandboxBackend(handle: Sandbox, options: Pick<CreateRun
|
|
|
316
319
|
if (hosts.size > 1) throw invalid('Bridge and Model Gateway must use the same connection.bindHost');
|
|
317
320
|
const port = connection?.bindPort ?? 0;
|
|
318
321
|
if (!Number.isSafeInteger(port) || port < 0 || port > 65_535) throw invalid('connection.bindPort must be from 0 through 65535');
|
|
319
|
-
const advertiseHost = connection?.advertiseHost ?? gateway?.advertiseHost ?? settings.sandbox.advertiseHost ??
|
|
320
|
-
((settings.sandbox.lifecycleBaseUrl && loopbackLifecycle(settings.sandbox.lifecycleBaseUrl)) || settings.provider ? '172.17.0.1' : undefined);
|
|
321
322
|
const savedPublicUrl = settings.sandbox.publicUrl;
|
|
322
323
|
const advertised = [...candidates][0] ?? savedPublicUrl;
|
|
324
|
+
let advertiseHost = connection?.advertiseHost ?? gateway?.advertiseHost ?? settings.sandbox.advertiseHost;
|
|
325
|
+
if (advertiseHost === undefined && settings.provider) advertiseHost = '172.17.0.1';
|
|
326
|
+
if (advertiseHost === undefined && !advertised && settings.sandbox.lifecycleBaseUrl && loopbackLifecycle(settings.sandbox.lifecycleBaseUrl)) {
|
|
327
|
+
advertiseHost = discoverDockerCallbackHost() ?? '172.17.0.1';
|
|
328
|
+
}
|
|
323
329
|
if (!advertised && !advertiseHost) throw invalid('For an existing remote OpenSandbox, set connection.publicUrl to the Runtime address reachable from the Sandbox');
|
|
324
330
|
const workerHost = advertiseHost ?? new URL(advertised!).hostname.replace(/^\[|\]$/g, '');
|
|
325
331
|
if (!/^[a-zA-Z0-9.:-]+$/.test(workerHost) || ['localhost', '0.0.0.0', '::'].includes(workerHost) && !advertised) {
|
|
@@ -124,7 +124,16 @@ function loadSavedConnection(): ConnectionInput {
|
|
|
124
124
|
return saved;
|
|
125
125
|
}
|
|
126
126
|
|
|
127
|
-
export function
|
|
127
|
+
export function discoverDockerCallbackHost(): string | undefined {
|
|
128
|
+
try { return networkInterfaces().docker0?.find(item => item.family === 'IPv4')?.address; }
|
|
129
|
+
catch {
|
|
130
|
+
throw Object.assign(new Error('Could not inspect host network interfaces for the Sandbox callback address. ' +
|
|
131
|
+
'Set ANYSWARM_ADVERTISE_HOST or ANYSWARM_RUNTIME_PUBLIC_URL to an address reachable from the Sandbox.'),
|
|
132
|
+
{ code: 'HOST_NETWORK_DISCOVERY_FAILED' });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function resolveSandboxConnectionWithSources(input: ConnectionInput = {}, scope?: string, { useSaved = true, discoverHost = true } = {}) {
|
|
128
137
|
const environment = process.env;
|
|
129
138
|
const example = (name: string) => scope ? environment[`ANYSWARM_${scope}_${name}`] || undefined : undefined;
|
|
130
139
|
const explicit = input.endpoint === undefined ? undefined : lifecycleUrl(input.endpoint, 'endpoint');
|
|
@@ -157,13 +166,17 @@ export function resolveSandboxConnectionWithSources(input: ConnectionInput = {},
|
|
|
157
166
|
const endpointHost = input.endpointHost ?? (environment.ANYSWARM_ENDPOINT_HOST || undefined) ?? example('ENDPOINT_HOST');
|
|
158
167
|
if (endpointHost !== undefined) throw connectionError('endpointHost was removed. Configure OpenSandbox to publish a reachable endpoint.');
|
|
159
168
|
const publicUrl = input.publicUrl ?? (environment.ANYSWARM_RUNTIME_PUBLIC_URL || undefined) ?? stored.publicUrl;
|
|
169
|
+
const normalizedPublicUrl = publicUrl === undefined ? undefined : normalizeRuntimePublicUrl(publicUrl);
|
|
160
170
|
const from = (settings: readonly (readonly [string, string | undefined])[]) =>
|
|
161
171
|
settings.find(([, value]) => value !== undefined && value !== '');
|
|
162
|
-
|
|
172
|
+
let callback = from([
|
|
163
173
|
['config', input.advertiseHost], ['ANYSWARM_ADVERTISE_HOST', environment.ANYSWARM_ADVERTISE_HOST],
|
|
164
174
|
[`ANYSWARM_${scope}_ADVERTISE_HOST`, example('ADVERTISE_HOST')], ['saved', stored.advertiseHost],
|
|
165
|
-
['docker0', local ? networkInterfaces().docker0?.find(address => address.family === 'IPv4')?.address : undefined],
|
|
166
175
|
]);
|
|
176
|
+
if (discoverHost && !callback && !normalizedPublicUrl && local) {
|
|
177
|
+
const address = discoverDockerCallbackHost();
|
|
178
|
+
if (address) callback = ['docker0', address];
|
|
179
|
+
}
|
|
167
180
|
const worker = from([
|
|
168
181
|
['config', input.image], ['ANYSWARM_WORKER_IMAGE', environment.ANYSWARM_WORKER_IMAGE],
|
|
169
182
|
[`ANYSWARM_${scope}_IMAGE`, example('IMAGE')], ['saved', stored.image],
|
|
@@ -174,7 +187,7 @@ export function resolveSandboxConnectionWithSources(input: ConnectionInput = {},
|
|
|
174
187
|
environment.OPENSANDBOX_API_KEY || undefined) ?? stored.apiKey ?? (local && readPrivateFile(localApiKeyPath(local), 256)),
|
|
175
188
|
advertiseHost: callback?.[1],
|
|
176
189
|
advertiseHostDiscovery: callback?.[0] === 'saved' ? stored.advertiseHostDiscovery : undefined,
|
|
177
|
-
publicUrl:
|
|
190
|
+
publicUrl: normalizedPublicUrl,
|
|
178
191
|
image: worker?.[1],
|
|
179
192
|
useServerProxy: input.useServerProxy ?? stored.useServerProxy,
|
|
180
193
|
egressMode: input.egressMode ?? stored.egressMode,
|
|
@@ -188,10 +201,12 @@ export function resolveSandboxConnectionWithSources(input: ConnectionInput = {},
|
|
|
188
201
|
};
|
|
189
202
|
}
|
|
190
203
|
|
|
191
|
-
export function resolveSandboxConnection(
|
|
204
|
+
export function resolveSandboxConnection(input?: ConnectionInput, scope?: string,
|
|
205
|
+
{ useSaved = true, discoverHost = true, includePreparedImage = false } = {}) {
|
|
192
206
|
const { sources: _sources, advertiseHostDiscovery: _discovery, management: _management, providerId: _providerId,
|
|
193
|
-
localExecutor, preparedImage
|
|
194
|
-
return { ...connection, executor: localExecutor?.kind
|
|
207
|
+
localExecutor, preparedImage, ...connection } = resolveSandboxConnectionWithSources(input, scope, { useSaved, discoverHost });
|
|
208
|
+
return { ...connection, executor: localExecutor?.kind,
|
|
209
|
+
...(includePreparedImage && preparedImage ? { preparedImage } : {}) };
|
|
195
210
|
}
|
|
196
211
|
|
|
197
212
|
export async function saveSandboxConnection(input: ConnectionInput & { lifecycleBaseUrl: string }) {
|
|
@@ -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 {
|
|
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';
|
|
@@ -196,7 +197,7 @@ async function prepareOutput(runId: string, options: StartupOptions, cwd: string
|
|
|
196
197
|
await mkdir(path, { recursive: true, mode: 0o700 });
|
|
197
198
|
return await realpath(path);
|
|
198
199
|
}
|
|
199
|
-
const stateDirectory =
|
|
200
|
+
const stateDirectory = defaultRunRoot();
|
|
200
201
|
if (!isInside(cwd, stateDirectory)) {
|
|
201
202
|
const stateRoot = await mkdir(stateDirectory, { recursive: true, mode: 0o700 })
|
|
202
203
|
.then(() => realpath(stateDirectory)).catch(() => null);
|
|
@@ -45,6 +45,23 @@ type Pending = {
|
|
|
45
45
|
release(): void;
|
|
46
46
|
};
|
|
47
47
|
|
|
48
|
+
// These launch errors contain public Host explanations, not author exceptions.
|
|
49
|
+
const startupMessageCodes = new Set(['HARNESS_MODULE_LOAD_FAILED', 'INVALID_HARNESS_MODULE',
|
|
50
|
+
'INVALID_HARNESS_SESSION', 'INVALID_RUN_CONFIGURATION', 'INVALID_REQUEST']);
|
|
51
|
+
|
|
52
|
+
function startupError(record: any) {
|
|
53
|
+
if (typeof record.code !== 'string' || !/^[A-Za-z0-9_.:-]{1,128}$/.test(record.code)) {
|
|
54
|
+
throw new Error('Invalid RPC startup error');
|
|
55
|
+
}
|
|
56
|
+
const message = startupMessageCodes.has(record.code) && typeof record.message === 'string'
|
|
57
|
+
? record.message.slice(0, 4096).replace(/[\p{Cc}\p{Cf}]/gu, (character: string) =>
|
|
58
|
+
'\\u' + character.charCodeAt(0).toString(16).padStart(4, '0'))
|
|
59
|
+
: 'Harness RPC startup failed';
|
|
60
|
+
const diagnostic = parseErrorDiagnostic(record.diagnostic);
|
|
61
|
+
return Object.assign(projectError(record.code, message),
|
|
62
|
+
diagnostic ? frameworkErrorFields({ ...record, diagnostic }) : {});
|
|
63
|
+
}
|
|
64
|
+
|
|
48
65
|
export class HarnessRpcClient implements HarnessSession {
|
|
49
66
|
readonly ready: Promise<HarnessRpcReady>;
|
|
50
67
|
readonly agents: HarnessSession['agents'];
|
|
@@ -57,6 +74,7 @@ export class HarnessRpcClient implements HarnessSession {
|
|
|
57
74
|
readonly #timeout: number;
|
|
58
75
|
readonly #prefix = randomUUID();
|
|
59
76
|
#next = 0;
|
|
77
|
+
#readyConfirmed = false;
|
|
60
78
|
#started = false;
|
|
61
79
|
#failure?: Error;
|
|
62
80
|
#resultConfirmed = false;
|
|
@@ -187,11 +205,16 @@ export class HarnessRpcClient implements HarnessSession {
|
|
|
187
205
|
switch (record.type) {
|
|
188
206
|
case 'ready':
|
|
189
207
|
if (record.version !== 'v1' || !record.harness || !record.status || !record.descriptor) throw new Error('Invalid RPC handshake');
|
|
208
|
+
this.#readyConfirmed = true;
|
|
190
209
|
this.#started ||= typeof record.status.runId === 'string';
|
|
191
210
|
this.#ready.resolve(record);
|
|
192
211
|
break;
|
|
193
212
|
case 'reply':
|
|
194
213
|
case 'error': {
|
|
214
|
+
if (record.type === 'error' && record.id === undefined && !this.#readyConfirmed) {
|
|
215
|
+
this.#disconnect(startupError(record));
|
|
216
|
+
break;
|
|
217
|
+
}
|
|
195
218
|
const pending = this.#pending.get(record.id);
|
|
196
219
|
if (!pending) break;
|
|
197
220
|
this.#pending.delete(record.id);
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
-
import {
|
|
2
|
+
import { createRequire, registerHooks } from 'node:module';
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
4
|
|
|
5
|
+
const require = createRequire(import.meta.url);
|
|
6
|
+
|
|
5
7
|
let installed = false;
|
|
6
8
|
|
|
7
9
|
/** Enable trusted author TypeScript without changing the author's package scope. */
|
|
8
10
|
export function installSourceLoader() {
|
|
9
11
|
if (installed) return;
|
|
10
12
|
installed = true;
|
|
11
|
-
// Node 22.19+ supports transformation and inline maps, including enums.
|
|
12
|
-
const transform = stripTypeScriptTypes as unknown as (source: string, options: { mode: 'transform'; sourceMap: true; sourceUrl: string }) => string;
|
|
13
13
|
const sdk = new URL('../core/index.js', import.meta.url).href;
|
|
14
14
|
registerHooks({
|
|
15
15
|
resolve(specifier, context, nextResolve) {
|
|
@@ -19,8 +19,11 @@ export function installSourceLoader() {
|
|
|
19
19
|
if ((error as NodeJS.ErrnoException).code !== 'ERR_MODULE_NOT_FOUND' &&
|
|
20
20
|
(error as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') throw error;
|
|
21
21
|
if (specifier === '@anyswarm/core') return { url: sdk, shortCircuit: true };
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
const source = specifier.startsWith('file:') ? new URL(specifier)
|
|
23
|
+
: context.parentURL?.startsWith('file:') && /^(?:\.{1,2}\/|\/)/.test(specifier)
|
|
24
|
+
? new URL(specifier, context.parentURL) : undefined;
|
|
25
|
+
if (source && /\.m?js$/.test(source.pathname)) {
|
|
26
|
+
source.pathname = source.pathname.replace(/\.m?js$/, match => match === '.mjs' ? '.mts' : '.ts');
|
|
24
27
|
if (existsSync(source)) return { url: source.href, shortCircuit: true };
|
|
25
28
|
}
|
|
26
29
|
throw error;
|
|
@@ -28,10 +31,27 @@ export function installSourceLoader() {
|
|
|
28
31
|
},
|
|
29
32
|
load(url, context, nextLoad) {
|
|
30
33
|
if (!url.startsWith('file:') || !/\.(?:ts|mts)$/.test(new URL(url).pathname)) return nextLoad(url, context);
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
});
|
|
34
|
+
const filename = fileURLToPath(url);
|
|
35
|
+
const source = transformAuthorSource(readFileSync(filename, 'utf8'), filename);
|
|
34
36
|
return { format: 'module', source, shortCircuit: true };
|
|
35
37
|
},
|
|
36
38
|
});
|
|
37
39
|
}
|
|
40
|
+
|
|
41
|
+
/** Compile author source without lowering the JavaScript syntax supported by the running Node. */
|
|
42
|
+
export function transformAuthorSource(source: string, filename: string): string {
|
|
43
|
+
const { transformSync }: typeof import('@swc/wasm') = require('@swc/wasm');
|
|
44
|
+
// The WASM transformer accepts these options even though its declarations lag the runtime.
|
|
45
|
+
const options = {
|
|
46
|
+
filename,
|
|
47
|
+
isModule: true,
|
|
48
|
+
sourceMaps: 'inline',
|
|
49
|
+
jsc: {
|
|
50
|
+
target: 'esnext',
|
|
51
|
+
parser: { syntax: 'typescript' },
|
|
52
|
+
transform: { verbatimModuleSyntax: true },
|
|
53
|
+
},
|
|
54
|
+
module: { type: 'es6' },
|
|
55
|
+
} as unknown as import('@swc/wasm').Options;
|
|
56
|
+
return transformSync(source, options).code;
|
|
57
|
+
}
|
|
@@ -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
|
|
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);
|