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
7 changes: 7 additions & 0 deletions .changeset/manager-guest-exec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@mieweb/cli": minor
"@mieweb/deploy-contract": minor
"mieweb": minor
---

Add `mieweb exec --site <id> --container <id> -- <program> [arg ...]` for running a one-shot command in an existing guest through a provider with the optional `exec` capability. Preserve argument boundaries, output bytes, and the guest process exit status.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,12 @@ mieweb whoami
mieweb deploy
```

Commands that use a target print its name to standard error. For commands
Run a one-off command in a running guest with
`mieweb exec --site <id> --container <id> -- node --version`. This requires a
Manager and OS provider with exec support. It preserves guest stdout, stderr,
and exit status for scripts. [Guest exec details](packages/cli/README.md#run-a-command-in-a-manager-guest)

Other commands that use a target print its name to standard error. For commands
that contact an opensource-server Manager, the same line includes its URL.
Deploy, tail and destroy also show the site ID when one is configured.
Wrangler commands show the named environment selected with `--env` or
Expand Down
32 changes: 32 additions & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,38 @@ Select `--target cloudflare` to use Wrangler. The CLI uses
in that order. Any target can override its deploy provider with
`targets.<target>.provider` in `mieweb.jsonc`.

## Run a command in a Manager guest

Sign in with `mieweb login`, or set `MIEWEB_OS_TOKEN` in CI. Use the numeric site
ID and Manager container ID of a running guest you have permission to execute in.
The guest can have just an HTTP route.

```sh
mieweb exec --site 2 --container 41 -- node --version
mieweb exec --site 2 --container 41 -- node -e 'process.exit(17)'
```

The first argument after `--` is the program. Each remaining argument goes to it
literally, including empty strings and flags such as `--target`. Shell expansion
by your local shell still applies. The command runs once, with no terminal or
stdin. The CLI sends guest output to the matching local streams and exits with
the guest status. If the Manager caps a stream, the CLI reports which one on
stderr.

CLI, Manager, and transport failures exit with status 125 and a
`[mieweb exec] Request failed:` diagnostic. A guest that exits 125 gets a final
`[mieweb exec] Guest exited with status 125.` line on stderr. If the connection
breaks after submission, the command may already have run. Check its effect
before issuing another request.

Exec requires an updated Manager and an exec-capable
`@mieweb/os-cloud-provider`. The CLI prefers the provider installed in the
current project. For a pull request preview, install the provider tarball from
the OS provider preview workflow's job summary in that project. For a local
build, point `targets.mieweb.provider` at the provider's
built entry point and configure `targets.mieweb.instanceUrl` for the test
Manager. The built-in Cloudflare provider does not implement this command.

## Images (Cloudflare Containers)

Build container images once, distribute them with **skopeo**
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"@mieweb/cloud-adapters": "workspace:*",
"@mieweb/deploy-contract": "workspace:*",
"@mieweb/deploy-wrangler": "workspace:*",
"@mieweb/os-cloud-provider": "~2026.10.4",
"@mieweb/os-cloud-provider": "~2026.12.1",
"import-meta-resolve": "^4.2.0",
"jsonc-parser": "^3.3.1"
},
Expand Down
100 changes: 100 additions & 0 deletions packages/cli/src/exec.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// @ts-check
import { parseArgs } from 'node:util';
import { loadConfig } from './config.mjs';
import { buildContext, resolveProvider, usesOpensourceServer } from './provider.mjs';

const usage = 'Usage: mieweb exec --site <site-id> --container <manager-container-id> -- <program> [arg ...]';
const cliFailure = 125;

/** @param {string[] | undefined} values @param {string} option */
function requiredId(values, option) {
const value = values?.[0];
const id = Number(value);
if (values?.length !== 1 || !value || !/^\d+$/.test(value) || !Number.isSafeInteger(id) || id < 1) {
throw new Error(`Supply exactly one positive integer for --${option}.\n${usage}`);
}
return id;
}

/** @param {string[]} args @returns {import('@mieweb/deploy-contract').ContainerExecRequest} */
function parseRequest(args) {
const end = args.indexOf('--');
if (end < 0 || !args[end + 1]) throw new Error(usage);
const { values } = parseArgs({
args: args.slice(0, end),
options: {
site: { type: 'string', multiple: true },
container: { type: 'string', multiple: true },
},
});
return {
siteId: requiredId(values.site, 'site'),
containerId: requiredId(values.container, 'container'),
argv: args.slice(end + 1),
};
}

/** @param {NodeJS.WriteStream} stream @param {Uint8Array} bytes */
async function writeBytes(stream, bytes) {
if (!bytes.length) return;
// The CLI exits explicitly. Wait for redirected streams to drain before returning.
await new Promise((resolve, reject) => {
stream.once('error', reject);
stream.write(bytes, error => {
if (error) return reject(error);
stream.removeListener('error', reject);
resolve(undefined);
});
});
}

/** @param {string[]} args @param {string | null} overrideTarget */
export async function runExec(args, overrideTarget) {
if (args.length === 1 && (args[0] === '--help' || args[0] === '-h')) {
console.log(usage);
return 0;
}

try {
const request = parseRequest(args);
const config = loadConfig({ overrideTarget });
const provider = await resolveProvider(config);
if (!provider?.exec) {
const hint = usesOpensourceServer(config)
? ' Install an exec-capable version of @mieweb/os-cloud-provider in your project.'
: '';
throw new Error(`The provider for target "${config.target}" does not implement exec.${hint}`);
}
// The executable and guest args belong exclusively to request.argv.
const { context, dispose } = buildContext(config, []);
try {
const result = await provider.exec(context, request);
if (!(result?.stdout instanceof Uint8Array) || !(result.stderr instanceof Uint8Array) ||
!Number.isInteger(result.exitCode) || result.exitCode < 0 || result.exitCode > 255 ||
typeof result.stdoutTruncated !== 'boolean' || typeof result.stderrTruncated !== 'boolean') {
throw new Error('Invalid provider result. The command may have run. Check the guest before retrying.');
}
const notices = [];
if (result.stdoutTruncated) notices.push('[mieweb exec] Guest stdout was truncated.');
if (result.stderrTruncated) notices.push('[mieweb exec] Guest stderr was truncated.');
// A shell has just 256 statuses. Label the collision with a CLI failure.
if (result.exitCode === cliFailure) notices.push('[mieweb exec] Guest exited with status 125.');
try {
await writeBytes(process.stdout, result.stdout);
await writeBytes(process.stderr, result.stderr);
if (notices.length) {
const newline = result.stderr.length && result.stderr.at(-1) !== 10 ? '\n' : '';
await writeBytes(process.stderr, Buffer.from(newline + notices.join('\n') + '\n'));
}
} catch {
throw new Error(`Guest exited with status ${result.exitCode}, but the CLI could not write its output.`);
}
return result.exitCode;
} finally {
dispose();
}
} catch (error) {
console.error(`[mieweb exec] Request failed: ${error instanceof Error ? error.message : String(error)}`);
return cliFailure;
}
}
11 changes: 10 additions & 1 deletion packages/cli/src/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { loadConfig } from './config.mjs';
import { runExec } from './exec.mjs';
import { delegateToWrangler } from './cloudflare.mjs';
import { runHostTarget } from './local.mjs';
import { runInit } from './init.mjs';
Expand All @@ -45,9 +46,13 @@ async function main(argv) {
// it reaches wrangler (which wouldn't understand it).
let overrideTarget = null;
/** @type {string[]} */
const args = [];
let args = [];
for (let i = 0; i < argv.length; i += 1) {
const a = argv[i];
if (a === '--') {
args = args.concat(argv.slice(i));
break;
}
if (a === '--target' || a === '-t') {
overrideTarget = argv[i + 1] ?? null;
i += 1;
Expand Down Expand Up @@ -77,6 +82,8 @@ async function main(argv) {
return runInit(args.slice(1));
}

if (args[0] === 'exec') return runExec(args.slice(1), overrideTarget);

const config = loadConfig({ overrideTarget });
process.stderr.write(`[mieweb] Target: ${formatEnvironment(config, args)}\n`);

Expand Down Expand Up @@ -158,6 +165,8 @@ function printHelp() {
" mieweb login Authenticate the active target's provider.",
" mieweb logout Clear the provider's stored session.",
" mieweb whoami Show the provider's auth status.",
' mieweb exec --site <id> --container <id> -- <program> [arg ...]',
' Run a one-shot command in a running guest.',
' mieweb dev Start a dev server for the active target.',
" mieweb deploy Deploy via the active target's provider.",
' mieweb tail Stream logs from the deployed worker.',
Expand Down
112 changes: 112 additions & 0 deletions packages/cli/test/exec.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import assert from 'node:assert/strict';
import { execFile } from 'node:child_process';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { test } from 'node:test';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';

const execFileAsync = promisify(execFile);
const cli = fileURLToPath(new URL('../src/index.mjs', import.meta.url));
const select = ['--site', '2', '--container', '41', '--'];

function project(t, result = "throw new Error('Unexpected provider call.');") {
const cwd = mkdtempSync(join(tmpdir(), 'mieweb-exec-'));
t.after(() => rmSync(cwd, { recursive: true, force: true }));
writeFileSync(join(cwd, 'mieweb.jsonc'), JSON.stringify({
target: 'mieweb', targets: { mieweb: { provider: './fixture.mjs' } },
}));
writeFileSync(join(cwd, 'fixture.mjs'), `
import { appendFileSync } from 'node:fs';
export default {
name: 'fixture', supports: target => target === 'mieweb', deploy() {},
async exec(context, request) {
appendFileSync('requests', JSON.stringify(request) + '\\n');
${result}
}
};
`);
const env = { ...process.env, MIEWEB_TARGET: '' };
const run = (...args) => execFileAsync(process.execPath, [cli, 'exec', ...args], { cwd, env, encoding: 'buffer' });
return { run, cwd };
}

test('passes the executable and literal guest arguments, and drains raw streams', async t => {
const { run, cwd } = project(t, `
return { stdout: Buffer.alloc(131072, 0xff), stderr: Buffer.from([0, 13, 255]),
exitCode: 0, stdoutTruncated: false, stderrTruncated: false };
`);
const guest = ['tool', 'space here', '', '--target', 'local', '-t', '$HOME', '--', '--help'];
const { stdout, stderr } = await run('--target', 'mieweb', ...select, ...guest);
assert.deepEqual(stdout, Buffer.alloc(131072, 0xff));
assert.deepEqual(stderr, Buffer.from([0, 13, 255]));
assert.deepEqual(JSON.parse(readFileSync(join(cwd, 'requests'), 'utf8')), { siteId: 2, containerId: 41, argv: guest });
});

test('returns a guest failure including its unmodified stderr', async t => {
const { run } = project(t, `
return { stdout: Buffer.from('out'), stderr: Buffer.from('guest error'),
exitCode: 17, stdoutTruncated: false, stderrTruncated: false };
`);
await assert.rejects(run(...select, 'guest'), err => {
assert.equal(err.code, 17);
assert.equal(err.stdout.toString(), 'out');
assert.equal(err.stderr.toString(), 'guest error');
return true;
});
});

test('identifies truncation and distinguishes guest exit 125 from a request failure', async t => {
const { run } = project(t, `
return { stdout: Buffer.from('out'), stderr: Buffer.from('err'),
exitCode: 125, stdoutTruncated: false, stderrTruncated: true };
`);
await assert.rejects(run(...select, 'guest'), err => {
assert.equal(err.code, 125);
assert.equal(err.stdout.toString(), 'out');
assert.equal(err.stderr.toString(), 'err\n[mieweb exec] Guest stderr was truncated.\n[mieweb exec] Guest exited with status 125.\n');
return true;
});
});

test('rejects bad results and reports provider failures without retrying the exec', async t => {
for (const [body, detail] of [
["throw new Error('Manager denied this guest.');", /Manager denied this guest/],
["throw new Error('Connection lost. Check the guest before retrying.');", /Check the guest/],
['return { stdout: new Uint8Array(), stderr: new Uint8Array(), exitCode: -1 };', /command may have run/],
]) {
const { run, cwd } = project(t, body);
await assert.rejects(run(...select, 'guest'), err => {
assert.equal(err.code, 125);
assert.equal(err.stdout.length, 0);
assert.match(err.stderr.toString(), /^\[mieweb exec\] Request failed:/);
assert.match(err.stderr.toString(), detail);
assert.equal(readFileSync(join(cwd, 'requests'), 'utf8').trim().split('\n').length, 1);
return true;
});
}
});

test('validates ambiguous selectors, requires the delimiter and executable, and offers local help', async t => {
const { run } = project(t);
for (const args of [
['--site', '2', '--', 'guest'], ['--site', '2', '--container', '0', '--', 'guest'],
['--site', '2', '--site', '3', '--container', '41', '--', 'guest'], select,
['--site', '2', '--container', '41', 'guest'],
]) {
await assert.rejects(run(...args), err => {
assert.equal(err.code, 125);
assert.match(err.stderr.toString(), /Usage: mieweb exec/);
return true;
});
}
const help = await run('--help');
assert.match(help.stdout.toString(), /Usage: mieweb exec/);
assert.equal(help.stderr.length, 0);
await assert.rejects(run('--target', 'local', ...select, 'guest'), err => {
assert.equal(err.code, 125);
assert.match(err.stderr.toString(), /target "local" does not implement exec/);
return true;
});
});
24 changes: 24 additions & 0 deletions packages/deploy-contract/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,22 @@ export interface DeployHandle {
stop(): void | Promise<void>;
}

/** Identifies one running guest and the executable and literal arguments to run in it. */
export interface ContainerExecRequest {
readonly siteId: number;
readonly containerId: number;
readonly argv: readonly string[];
}

/** A completed command, including a nonzero guest exit. Both streams contain raw bytes. */
export interface ContainerExecResult {
readonly stdout: Uint8Array;
readonly stderr: Uint8Array;
readonly exitCode: number;
readonly stdoutTruncated: boolean;
readonly stderrTruncated: boolean;
}

/**
* The result of an authentication-status check ({@link DeployProvider.whoami}).
*
Expand Down Expand Up @@ -274,6 +290,14 @@ export interface DeployProvider {
/** Stream logs from the deployed worker. Absent ⇒ CLI reports unsupported. */
tail?(context: DeployContext): Promise<void>;

/**
* Run a non-interactive command once in an existing guest. Preserve argv boundaries,
* bound execution time and output, and return the guest's exit status (0–255).
* Reject failures to obtain a guest result. A lost response can follow execution,
* so providers must not retry automatically.
*/
exec?(context: DeployContext, request: ContainerExecRequest): Promise<ContainerExecResult>;

/** Tear down what {@link deploy} created. Absent ⇒ CLI reports unsupported. */
destroy?(context: DeployContext): Promise<void>;

Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading