Skip to content

Commit 0e3e03c

Browse files
committed
wip(cli): os deploy to a remembered self-hosted runtime
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017ihL2dLQEXWGsE2SZ3Qn5F
1 parent 5f00374 commit 0e3e03c

7 files changed

Lines changed: 617 additions & 44 deletions

File tree

‎packages/cli/src/commands/deploy.ts‎

Lines changed: 105 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,31 @@
4545
*
4646
* ⛔ Not the retired `os publish` id (see `package/publish.ts`'s header), on
4747
* purpose: that id is documented as removed and must stay unresolvable.
48+
*
49+
* ## A self-hosted runtime target
50+
*
51+
* When `os environments use-runtime` made a self-hosted runtime (the Docker
52+
* image, Community or Enterprise) the active deploy target, the same command
53+
* with no flags deploys THERE instead (`--env` still names a cloud environment
54+
* and deploys to it). There is no catalog and no version to mint: the build is
55+
* sent inline to the runtime's install-local door — `os package install` itself,
56+
* run in this process with the remembered url and key, so its refusals and
57+
* answers stay in ONE place:
58+
*
59+
* 1. build (`compileForDeploy`), as above;
60+
* 2. the dry run — the runtime's package upgrade plan of the installed
61+
* version against this build, printed; nothing is installed. A runtime
62+
* that refuses it, or does not serve install-local, stops the deploy here
63+
* with its sentence and exit 1;
64+
* 3. the install, with `--confirm-access-upgrade` passed through; the door's
65+
* refusals (an access upgrade to confirm, …) stop the deploy with exit 1;
66+
* 4. the answer — install-local registers the package in the live kernel
67+
* before it answers, so the answer IS "live": `hotLoaded` ⇒ 0; a package
68+
* the running kernel could not load ⇒ 1, naming the restart it waits for.
69+
*
70+
* Whether an upgrade is refused for a rename or a type change (epic
71+
* cloud#3652 Q3) is install-local's verdict, not this command's: a refusal it
72+
* answers is printed and stops the deploy like any other.
4873
*/
4974

5075
import { readFile } from 'node:fs/promises';
@@ -56,7 +81,10 @@ import { describeEnvironment, resolveInstallTarget } from '../utils/install-targ
5681
import { compileForDeploy } from '../utils/deploy-build.js';
5782
import { devVersion } from '../utils/dev-version.js';
5883
import { fetchEnvironmentOrigin, waitUntilServed, wakeEnvironment, type ServedVersionVerdict } from '../utils/served-version.js';
84+
import { activeRuntimeTarget } from '../utils/runtime-target.js';
85+
import type { RuntimeTarget } from '../utils/cloud-config.js';
5986
import PackagePublish from './package/publish.js';
87+
import PackageInstall from './package/install.js';
6088

6189
/** The artifact the build writes and the publish reads — `os build`'s default output. */
6290
export const DEPLOY_ARTIFACT = 'dist/objectstack.json';
@@ -66,12 +94,14 @@ export const DEPLOY_POLL_INTERVAL_MS = 3_000;
6694

6795
export default class Deploy extends Command {
6896
static override description =
69-
'Deploy this app to your ObjectOS Cloud environment: build it, publish a dev version, install it, and wait until it is live';
97+
'Deploy this app to your ObjectOS Cloud environment (build it, publish a dev version, install it, and wait until '
98+
+ 'it is live), or to the self-hosted runtime `os environments use-runtime` made the active target';
7099

71100
static override examples = [
72101
'$ os deploy',
73102
'$ os deploy --env env_abc123 # your account reaches several environments',
74103
'$ os deploy --no-wait # return once the install is recorded',
104+
'$ os deploy --confirm-access-upgrade <finding-set> # self-hosted: confirm the findings the runtime printed',
75105
];
76106

77107
static override flags = {
@@ -105,13 +135,34 @@ export default class Deploy extends Command {
105135
description: 'API key for ObjectOS Cloud (bearer token; defaults to OS_CLOUD_API_KEY / OS_TOKEN, then `os cloud login`)',
106136
env: 'OS_CLOUD_API_KEY',
107137
}),
138+
'confirm-access-upgrade': Flags.string({
139+
description:
140+
'Self-hosted runtime target: confirm the access findings of this upgrade with the finding-set token the '
141+
+ "runtime's refusal printed (as `os package install --confirm-access-upgrade`)",
142+
}),
108143
};
109144

110145
async run(): Promise<void> {
111146
const { flags } = await this.parse(Deploy);
112147
printHeader('Deploy');
113148

114149
try {
150+
// 0. Target: the self-hosted runtime when it is the active one and no
151+
// cloud environment was named.
152+
const runtime = flags.env ? undefined : await activeRuntimeTarget();
153+
if (runtime) {
154+
await this.deployToRuntime(runtime, flags['confirm-access-upgrade']);
155+
return;
156+
}
157+
if (flags['confirm-access-upgrade'] !== undefined) {
158+
printError(
159+
'`--confirm-access-upgrade` confirms a self-hosted runtime\'s refusal; the deploy target is ObjectOS Cloud. '
160+
+ 'Drop the flag, or record the runtime with `os environments use-runtime <url> --token <key>`.',
161+
);
162+
this.exit(1);
163+
return;
164+
}
165+
115166
// 1. Credential.
116167
const { token, baseUrl } = await resolveCloudCredential({ token: flags.token, server: flags.server });
117168
if (!token) {
@@ -229,6 +280,59 @@ export default class Deploy extends Command {
229280
this.exit(1);
230281
}
231282
}
283+
284+
/**
285+
* The self-hosted half (the header's "A self-hosted runtime target"):
286+
* build → dry run (plan printed) → install → the `hotLoaded` answer.
287+
*/
288+
private async deployToRuntime(runtime: RuntimeTarget, confirmAccessUpgrade: string | undefined): Promise<void> {
289+
printStep(`Deploying to the self-hosted runtime ${runtime.url} (os environments use-runtime)`);
290+
291+
printStep('Building...');
292+
const artifactPath = resolvePath(process.cwd(), DEPLOY_ARTIFACT);
293+
if (compileForDeploy(artifactPath) !== 0) {
294+
printError('The build failed — fix the errors above, then run `os deploy` again. Nothing was installed.');
295+
this.exit(1);
296+
return;
297+
}
298+
299+
const install = async (extra: string[]) => {
300+
const command = new PackageInstall(
301+
[artifactPath, '--url', runtime.url, '--token', runtime.token, ...extra],
302+
this.config,
303+
);
304+
command.retryCommand = 'os deploy';
305+
command.embedded = true;
306+
await command.run();
307+
return command.outcome;
308+
};
309+
310+
console.log('');
311+
printStep(`Asking ${runtime.url} for the upgrade plan (dry run — nothing is installed)...`);
312+
const plan = await install(['--dry-run']);
313+
if (plan?.kind !== 'dry-run') {
314+
printError(`${runtime.url} did not answer the dry run with a plan, so nothing more was sent. Upgrade the runtime, then run \`os deploy\` again.`);
315+
this.exit(1);
316+
return;
317+
}
318+
319+
printStep(`Installing ${plan.manifestId} ${plan.version} into ${runtime.url}...`);
320+
const outcome = await install(confirmAccessUpgrade !== undefined ? ['--confirm-access-upgrade', confirmAccessUpgrade] : []);
321+
if (outcome?.kind !== 'installed') {
322+
printError(`${runtime.url} did not answer the install as a managed package install, so this cannot say ${plan.manifestId} is live (see above).`);
323+
this.exit(1);
324+
return;
325+
}
326+
if (!outcome.hotLoaded) {
327+
printError(
328+
`${runtime.url} recorded ${outcome.manifestId} ${outcome.version}, but its running kernel could not load it, so `
329+
+ 'it is not live: it loads when the runtime restarts. Fix the cause above, then run `os deploy` again.',
330+
);
331+
this.exit(1);
332+
return;
333+
}
334+
printSuccess(`Live: ${runtime.url} now serves ${outcome.manifestId} ${outcome.version}.`);
335+
}
232336
}
233337

234338
/** Print the wait's verdict; return the exit code it means. */

‎packages/cli/src/commands/environments/switch.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { printError } from '../../utils/format.js';
55
import { createControlPlaneApiClient, requireControlPlaneAuth } from '../../utils/api-client.js';
66
import { readAuthConfig, writeAuthConfig } from '../../utils/auth-config.js';
77
import { recordCloudActiveEnvironmentId } from '../../utils/active-environment.js';
8+
import { activateCloudDeployTarget } from '../../utils/runtime-target.js';
89

910
/**
1011
* `os environments switch <id>` — set the active environment for this CLI session.
@@ -24,6 +25,11 @@ import { recordCloudActiveEnvironmentId } from '../../utils/active-environment.j
2425
* uuid. Two files, two servers, an active environment for each — the id is
2526
* never carried across, because it would not resolve on the other side. The
2627
* gate lives in `utils/active-environment.ts`.
28+
*
29+
* Recorded there, it also makes ObjectOS Cloud the deploy target again when
30+
* `os environments use-runtime` had made a self-hosted runtime the target: the
31+
* two commands are the two ways to pick where `os deploy` goes, and the one
32+
* that ran last wins. The runtime stays remembered.
2733
*/
2834
export default class EnvironmentsSwitch extends Command {
2935
static override description = 'Activate an environment for subsequent CLI calls';
@@ -70,6 +76,7 @@ export default class EnvironmentsSwitch extends Command {
7076
// runtime store below (a user who only ran `os cloud login` has no
7177
// `credentials.json` at all).
7278
const recordedForCloud = await recordCloudActiveEnvironmentId(environment.id, baseUrl);
79+
const leftRuntime = recordedForCloud ? await activateCloudDeployTarget() : undefined;
7380

7481
// Runtime store: the copy `createApiClient` reads, so the `data` / `meta`
7582
// families keep targeting the environment you just switched to. Skipped
@@ -88,6 +95,12 @@ export default class EnvironmentsSwitch extends Command {
8895
if (recordedForCloud) {
8996
console.log(' (also recorded in cloud.json — `os package publish --install` will use it)');
9097
}
98+
if (leftRuntime !== undefined) {
99+
console.log(
100+
` Deploy target: this environment again, not the self-hosted runtime${leftRuntime ? ` ${leftRuntime}` : ''} `
101+
+ '(still remembered; `os environments use-runtime <url>` to go back)',
102+
);
103+
}
91104
if (!recordedForCloud && !cfg) {
92105
console.log(' ⚠ no local credential store to record it in — run `os login` or `os cloud login`');
93106
}
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { Args, Command, Flags } from '@oclif/core';
4+
import { isExitSignal, printError, printStep, printSuccess } from '../../utils/format.js';
5+
import { forgetRuntimeTarget, recordRuntimeTarget } from '../../utils/runtime-target.js';
6+
import { getCloudCredentialsPath } from '../../utils/cloud-config.js';
7+
8+
/**
9+
* `os environments use-runtime <url> --token <key>` — remember a SELF-HOSTED
10+
* runtime (ObjectStack's Docker image, Community or Enterprise) as the deploy
11+
* target, beside `os environments switch`, which picks an ObjectOS Cloud
12+
* environment. Whichever of the two ran last is the target `os deploy` and
13+
* `os dev`'s `d` key use; `os package install` falls back to this runtime when
14+
* `-u` / `-t` are not given.
15+
*
16+
* The url and an API key the runtime issued are stored in
17+
* `~/.objectstack/cloud.json` (0600), the file the cloud token lives in, as
18+
* their own record (`utils/cloud-config.ts` states the split; storage and
19+
* resolution are `utils/runtime-target.ts`). The key is sent only to this url.
20+
*
21+
* Before anything is written the key is tried on the runtime's install-local
22+
* door (`GET /api/v1/marketplace/install-local`, which answers only an
23+
* authenticated caller): a key the runtime rejects, a runtime that does not
24+
* serve the door, or one that cannot be reached is refused, naming why —
25+
* `--no-verify` records it anyway (a container that is not up yet).
26+
*
27+
* `--forget` drops the record; the cloud is the deploy target again.
28+
*/
29+
export default class EnvironmentsUseRuntime extends Command {
30+
static override description =
31+
'Remember a self-hosted runtime (url + API key) as the deploy target for `os deploy`, the `d` key in `os dev`, '
32+
+ 'and `os package install`';
33+
34+
static override examples = [
35+
'$ os environments use-runtime http://localhost:8080 --token osk_…',
36+
'$ OS_RUNTIME_TOKEN=osk_… os environments use-runtime https://objectos.example.com',
37+
'$ os environments use-runtime --forget # deploy to ObjectOS Cloud again',
38+
];
39+
40+
static override args = {
41+
url: Args.string({ description: 'Base URL of the self-hosted runtime (e.g. http://localhost:8080)' }),
42+
};
43+
44+
static override flags = {
45+
token: Flags.string({
46+
char: 't',
47+
description: 'An API key the runtime issued (sent only to this runtime)',
48+
env: 'OS_RUNTIME_TOKEN',
49+
}),
50+
verify: Flags.boolean({
51+
description: 'Try the key on the runtime before recording it (default: on). Disable with --no-verify.',
52+
default: true,
53+
allowNo: true,
54+
}),
55+
forget: Flags.boolean({
56+
description: 'Forget the remembered runtime; ObjectOS Cloud is the deploy target again',
57+
default: false,
58+
}),
59+
};
60+
61+
async run(): Promise<void> {
62+
const { args, flags } = await this.parse(EnvironmentsUseRuntime);
63+
64+
try {
65+
if (flags.forget) {
66+
if (args.url) {
67+
printError('Pass either a runtime url or --forget, not both.');
68+
this.exit(1);
69+
return;
70+
}
71+
const forgotten = await forgetRuntimeTarget();
72+
console.log(forgotten
73+
? `\n✓ Forgot the self-hosted runtime ${forgotten.url}. \`os deploy\` deploys to ObjectOS Cloud again.\n`
74+
: '\n✓ No self-hosted runtime was remembered. `os deploy` deploys to ObjectOS Cloud.\n');
75+
return;
76+
}
77+
78+
const url = normalizeRuntimeUrl(args.url);
79+
if (!url.ok) {
80+
printError(url.message);
81+
this.exit(1);
82+
return;
83+
}
84+
if (!flags.token) {
85+
printError(
86+
'A self-hosted runtime needs an API key it issued: pass --token <key> (or set $OS_RUNTIME_TOKEN). '
87+
+ 'Create one in the runtime\'s Setup → API Keys.',
88+
);
89+
this.exit(1);
90+
return;
91+
}
92+
93+
if (flags.verify) {
94+
printStep(`Trying the key on ${url.value}...`);
95+
const probe = await probeRuntime(url.value, flags.token);
96+
if (!probe.ok) {
97+
printError(`${probe.message} Nothing was recorded. (Record it anyway with --no-verify.)`);
98+
this.exit(1);
99+
return;
100+
}
101+
}
102+
103+
await recordRuntimeTarget(url.value, flags.token);
104+
printSuccess(`Deploy target: the self-hosted runtime ${url.value}`);
105+
console.log(` Recorded in ${getCloudCredentialsPath()}. \`os deploy\` and the \`d\` key in \`os dev\` install there,`);
106+
console.log(' and `os package install` uses it when -u/-t are not given.');
107+
console.log(' Deploy to ObjectOS Cloud again: `os environments switch <id>` or `os environments use-runtime --forget`.');
108+
console.log('');
109+
} catch (error: any) {
110+
if (isExitSignal(error)) throw error;
111+
printError(error?.message || String(error));
112+
this.exit(1);
113+
}
114+
}
115+
}
116+
117+
/** An http(s) url with no query or fragment, trailing slashes dropped. */
118+
export function normalizeRuntimeUrl(raw: string | undefined): { ok: true; value: string } | { ok: false; message: string } {
119+
const trimmed = raw?.trim();
120+
if (!trimmed) {
121+
return { ok: false, message: 'Name the runtime: `os environments use-runtime <url> --token <key>` (or --forget).' };
122+
}
123+
let parsed: URL;
124+
try {
125+
parsed = new URL(trimmed);
126+
} catch {
127+
return { ok: false, message: `'${trimmed}' is not a url. Pass the runtime's base url, e.g. http://localhost:8080.` };
128+
}
129+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
130+
return { ok: false, message: `'${trimmed}' is not an http(s) url. Pass the runtime's base url, e.g. http://localhost:8080.` };
131+
}
132+
if (parsed.search || parsed.hash) {
133+
return { ok: false, message: `'${trimmed}' carries a query or fragment. Pass the runtime's base url only.` };
134+
}
135+
return { ok: true, value: `${parsed.protocol}//${parsed.host}${parsed.pathname.replace(/\/+$/, '')}` };
136+
}
137+
138+
/**
139+
* One authenticated read of the install-local door — the door `os deploy`
140+
* will POST to. Never throws.
141+
*/
142+
export async function probeRuntime(
143+
url: string,
144+
token: string,
145+
timeoutMs = 15_000,
146+
): Promise<{ ok: true } | { ok: false; message: string }> {
147+
const controller = new AbortController();
148+
const timer = setTimeout(() => controller.abort(), timeoutMs);
149+
try {
150+
const response = await fetch(`${url}/api/v1/marketplace/install-local`, {
151+
method: 'GET',
152+
headers: { Authorization: `Bearer ${token}` },
153+
signal: controller.signal,
154+
});
155+
if (response.ok) return { ok: true };
156+
if (response.status === 401 || response.status === 403) {
157+
return {
158+
ok: false,
159+
message: `${url} rejected the key (${response.status}). Pass an API key this runtime issued (Setup → API Keys).`,
160+
};
161+
}
162+
if (response.status === 404) {
163+
return {
164+
ok: false,
165+
message:
166+
`${url} does not serve install-local (GET /api/v1/marketplace/install-local answered 404), so it cannot `
167+
+ 'take a deploy. A runtime booted from a composed artifact takes no package installs; any other runtime '
168+
+ 'must mount MarketplaceInstallLocalPlugin (@objectstack/cloud-connection).',
169+
};
170+
}
171+
return { ok: false, message: `${url} answered ${response.status} ${response.statusText} to an authenticated read.` };
172+
} catch (err: any) {
173+
const why = err?.name === 'AbortError' ? `no answer within ${Math.round(timeoutMs / 1000)}s` : (err?.message ?? String(err));
174+
return { ok: false, message: `${url} cannot be reached (${why}). Is the runtime running, and is this its url?` };
175+
} finally {
176+
clearTimeout(timer);
177+
}
178+
}

0 commit comments

Comments
 (0)