Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions packages/deploy/src/bundle.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import path from 'node:path';
import os from 'node:os';
import { pathToFileURL } from 'node:url';
import { bundleStager } from './bundle.js';
import { runtimeContextEnv } from './runtime-context.js';
import type { PersonaSpec } from '@agentworkforce/persona-kit';

const require = createRequire(import.meta.url);

function persona(overrides: Partial<PersonaSpec> = {}): PersonaSpec {
return {
id: 'bundle-fixture',
Expand Down Expand Up @@ -79,6 +82,18 @@ test('bundleStager produces an executable, importable bundle from a real onEvent
const bundleSource = await readFile(result.bundlePath, 'utf8');
assert.match(bundleSource, /^import /m);
assert.match(bundleSource, /from\s+['"]@agentworkforce\/runtime['"]/);

// package.json pins the exact installed runtime version — never a
// wildcard a sandbox's npm install could silently satisfy with a
// stale pre-baked/cached copy.
const generatedPackageJson = JSON.parse(await readFile(result.packageJsonPath, 'utf8'));
const runtimeDep = generatedPackageJson.dependencies['@agentworkforce/runtime'];
const installedRuntimePackageJsonPath = require.resolve('@agentworkforce/runtime/package.json');
const installedRuntimeVersion = JSON.parse(
await readFile(installedRuntimePackageJsonPath, 'utf8')
).version;
assert.equal(runtimeDep, installedRuntimeVersion);
assert.notEqual(runtimeDep, '*');
} finally {
await rm(dir, { recursive: true, force: true });
}
Expand Down
40 changes: 35 additions & 5 deletions packages/deploy/src/bundle.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { mkdir, writeFile, stat } from 'node:fs/promises';
import { builtinModules } from 'node:module';
import { builtinModules, createRequire } from 'node:module';
import path from 'node:path';
import { build } from 'esbuild';
import type { BundleStageInput, BundleResult, BundleStager } from './types.js';

const require = createRequire(import.meta.url);

/**
* Versioned identifier embedded in the generated runner so a future
* bundle reader can detect format drift. Bumped whenever the runner
Expand Down Expand Up @@ -82,7 +84,7 @@ export const bundleStager: BundleStager = {

await writeFile(personaCopyPath, JSON.stringify(input.persona, null, 2) + '\n', 'utf8');

await writeFile(packageJsonPath, buildPackageJson(input.persona.id), 'utf8');
await writeFile(packageJsonPath, buildPackageJson(input.persona.id, resolveRuntimeVersion()), 'utf8');

await writeFile(runnerPath, renderRunner(), 'utf8');

Expand All @@ -100,7 +102,35 @@ export const bundleStager: BundleStager = {
}
};

function buildPackageJson(personaId: string): string {
/**
* Resolve the exact `@agentworkforce/runtime` version this copy of
* `@agentworkforce/deploy` was built against, by reading the installed
* package's own `package.json`. In a published install this is the exact
* version `workspace:*` was pinned to at publish time (see
* `packages/deploy/package.json`'s own dependency); in the monorepo it's
* whatever's checked out locally. Either way it's the version the CLI
* actually knows how to talk to — never a wildcard the sandbox's npm
* install could silently satisfy with a stale cached/pre-baked copy.
*/
function resolveRuntimeVersion(): string {
let packageJsonPath: string;
try {
packageJsonPath = require.resolve('@agentworkforce/runtime/package.json');
} catch (err) {
throw new Error(
`bundle: could not resolve @agentworkforce/runtime/package.json to pin an exact version (${
err instanceof Error ? err.message : String(err)
})`
);
}
const pkg = require(packageJsonPath) as { version?: unknown };
if (typeof pkg.version !== 'string' || pkg.version.length === 0) {
throw new Error(`bundle: ${packageJsonPath} has no valid "version" field`);
}
return pkg.version;
}
Comment on lines +115 to +131

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since resolveRuntimeVersion performs synchronous resolution and file system read/parse operations, calling it on every stage invocation can be inefficient if multiple bundles are staged in a single process (e.g., during batch deployments). Caching the resolved version in a module-level variable avoids redundant disk I/O and resolution overhead.

let cachedRuntimeVersion: string | undefined;

function resolveRuntimeVersion(): string {
  if (cachedRuntimeVersion !== undefined) {
    return cachedRuntimeVersion;
  }
  let packageJsonPath: string;
  try {
    packageJsonPath = require.resolve('@agentworkforce/runtime/package.json');
  } catch (err) {
    throw new Error(
      `bundle: could not resolve @agentworkforce/runtime/package.json to pin an exact version (${
        err instanceof Error ? err.message : String(err)
      })`
    );
  }
  const pkg = require(packageJsonPath) as { version?: unknown };
  if (typeof pkg.version !== 'string' || pkg.version.length === 0) {
    throw new Error(`bundle: ${packageJsonPath} has no valid "version" field`);
  }
  cachedRuntimeVersion = pkg.version;
  return cachedRuntimeVersion;
}


function buildPackageJson(personaId: string, runtimeVersion: string): string {
return (
JSON.stringify(
{
Expand All @@ -110,10 +140,10 @@ function buildPackageJson(personaId: string): string {
type: 'module',
main: './runner.mjs',
dependencies: {
'@agentworkforce/runtime': '*'
'@agentworkforce/runtime': runtimeVersion
},
comment:
'Generated by workforce deploy. The runtime dep is pinned to "*" because deploys resolve the runtime version from the active workspace.'
'Generated by workforce deploy. The runtime dep is pinned to the exact version this deploy CLI was built against so the sandbox installs the same runtime the bundle was compiled for, instead of trusting whatever is pre-baked or cached.'
},
null,
2
Expand Down
Loading