@agimon-ai/po-deploy 0.0.0-stage → 0.0.2-alpha.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/LICENSE ADDED
@@ -0,0 +1,198 @@
1
+ License text copyright © 2017 MariaDB Corporation Ab, All Rights Reserved.
2
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
3
+
4
+ Parameters
5
+
6
+ Licensor: Agimon Pty Ltd
7
+ Licensed Work: Po, the software in the Po source repository and the
8
+ packages released from it, in each version released by
9
+ the Licensor.
10
+ The Licensed Work is (c) 2026 Agimon Pty Ltd.
11
+ Material identified as third-party in the "Third-party
12
+ components" section at the end of this file or in a
13
+ NOTICE file, and any package or directory whose own
14
+ license file grants a different license, is not part of
15
+ the Licensed Work and remains under its own license.
16
+ Additional Use Grant: You may make production use of the Licensed Work if
17
+ your use is Eligible Use. "Eligible Use" is production use that falls
18
+ within at least one of the following:
19
+
20
+ (a) Personal Use. Use by an individual for their own personal purposes,
21
+ and not on behalf of, or for the benefit of, an employer, client, or
22
+ other Organization. Use by an individual in the course of employment
23
+ or engagement by an Organization is use by that Organization.
24
+
25
+ (b) Small Organization Use. Use by or on behalf of an Organization whose
26
+ Annual Revenue is less than USD 1,000,000.
27
+
28
+ (c) Non-profit, Education and Research Use. Use, regardless of Annual
29
+ Revenue, by (i) an Organization registered or recognized as a
30
+ non-profit or charitable organization under the laws of its
31
+ jurisdiction, for its non-profit purposes; (ii) an accredited school,
32
+ college, or university, for teaching, learning, or academic research;
33
+ or (iii) a publicly funded research institution, for its research.
34
+
35
+ (d) Service Provider Use. Use by a consultant, contractor, agency, or other
36
+ service provider, regardless of its own Annual Revenue, solely to
37
+ build, deploy, host, operate, or support the Licensed Work for a client
38
+ whose own use would be Eligible Use under (a), (b), or (c). A service
39
+ provider's use for its own purposes is Eligible Use only if the service
40
+ provider itself qualifies under (b) or (c).
41
+
42
+
43
+ Hosted services. Offering the Licensed Work to third parties as a hosted
44
+ or managed service whose primary value is the Licensed Work is Eligible
45
+ Use only if each such third party's own use would be Eligible Use.
46
+
47
+ Definitions. "Organization" means any company, partnership, sole
48
+ proprietorship, trust, association, government body, or other entity, and
49
+ includes an individual acting in a business or professional capacity.
50
+ "Affiliate" means any entity that directly or indirectly controls, is
51
+ controlled by, or is under common control with an Organization, where
52
+ "control" means ownership of more than 50% of the voting interests of an
53
+ entity or the power to direct its management and policies by contract or
54
+ otherwise. "Annual Revenue" means the total gross revenue of an
55
+ Organization and all of its Affiliates combined, from all sources and
56
+ whether or not related to the Licensed Work, for its most recently
57
+ completed fiscal year, or, if it has not completed a fiscal year, for the
58
+ twelve months before the use (or since its formation, if shorter),
59
+ converted into US dollars at the average exchange rate for that period.
60
+ Proceeds of equity or debt financing are not revenue.
61
+
62
+ Threshold. If an Organization stops qualifying under (b), its existing
63
+ production use remains Eligible Use for 90 days after it stops
64
+ qualifying, after which it must obtain a commercial license or stop
65
+ production use. Use that was Eligible Use when it occurred never requires
66
+ a commercial license after the fact.
67
+ Change Date: Four years from the date a version of the Licensed Work
68
+ is first publicly released by the Licensor.
69
+ Change License: Apache License, Version 2.0
70
+
71
+ For information about alternative licensing arrangements for the Licensed
72
+ Work, please visit: https://agimon.ai/licensing
73
+
74
+ Notice
75
+
76
+ The Business Source License (this document, or the "License") is not an Open
77
+ Source license. However, the Licensed Work will eventually be made available
78
+ under an Open Source License, as stated in this License.
79
+
80
+ -----------------------------------------------------------------------------
81
+
82
+ Business Source License 1.1
83
+
84
+ Terms
85
+
86
+ The Licensor hereby grants you the right to copy, modify, create derivative
87
+ works, redistribute, and make non-production use of the Licensed Work. The
88
+ Licensor may make an Additional Use Grant, above, permitting limited
89
+ production use.
90
+
91
+ Effective on the Change Date, or the fourth anniversary of the first publicly
92
+ available distribution of a specific version of the Licensed Work under this
93
+ License, whichever comes first, the Licensor hereby grants you rights under
94
+ the terms of the Change License, and the rights granted in the paragraph
95
+ above terminate.
96
+
97
+ If your use of the Licensed Work does not comply with the requirements
98
+ currently in effect as described in this License, you must purchase a
99
+ commercial license from the Licensor, its affiliated entities, or authorized
100
+ resellers, or you must refrain from using the Licensed Work.
101
+
102
+ All copies of the original and modified Licensed Work, and derivative works
103
+ of the Licensed Work, are subject to this License. This License applies
104
+ separately for each version of the Licensed Work and the Change Date may vary
105
+ for each version of the Licensed Work released by Licensor.
106
+
107
+ You must conspicuously display this License on each original or modified copy
108
+ of the Licensed Work. If you receive the Licensed Work in original or
109
+ modified form from a third party, the terms and conditions set forth in this
110
+ License apply to your use of that work.
111
+
112
+ Any use of the Licensed Work in violation of this License will automatically
113
+ terminate your rights under this License for the current and all other
114
+ versions of the Licensed Work.
115
+
116
+ This License does not grant you any right in any trademark or logo of
117
+ Licensor or its affiliates (provided that you may use a trademark or logo of
118
+ Licensor as expressly required by this License).
119
+
120
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
121
+ AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
122
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
123
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
124
+ TITLE.
125
+
126
+ MariaDB hereby grants you permission to use this License’s text to license
127
+ your works, and to refer to it using the trademark “Business Source License”,
128
+ as long as you comply with the Covenants of Licensor below.
129
+
130
+ Covenants of Licensor
131
+
132
+ In consideration of the right to use this License’s text and the “Business
133
+ Source License” name and trademark, Licensor covenants to MariaDB, and to all
134
+ other recipients of the licensed work to be provided by Licensor:
135
+
136
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
137
+ or a license that is compatible with GPL Version 2.0 or a later version,
138
+ where “compatible” means that software provided under the Change License can
139
+ be included in a program with software provided under GPL Version 2.0 or a
140
+ later version. Licensor may specify additional Change Licenses without
141
+ limitation.
142
+
143
+ 2. To either: (a) specify an additional grant of rights to use that does not
144
+ impose any additional restriction on the right granted in this License, as
145
+ the Additional Use Grant; or (b) insert the text “None”.
146
+
147
+ 3. To specify a Change Date.
148
+
149
+ 4. Not to modify this License in any other way.
150
+
151
+ -----------------------------------------------------------------------------
152
+
153
+ Third-party components
154
+
155
+ The following material in this package was written by third parties. It is
156
+ not part of the Licensed Work, is not licensed under the Business Source
157
+ License above, and remains under its own license, reproduced below. Where a
158
+ file combines third-party material with changes by Agimon Pty Ltd, the
159
+ third-party portions remain under their original license and the changes
160
+ are part of the Licensed Work.
161
+
162
+ 1. Playwriter (https://github.com/remorses/playwriter)
163
+ Used in: .agents/skills/playwriter
164
+ License: MIT
165
+
166
+ MIT License
167
+
168
+ Copyright (c) 2026 Tommy D. Rossi
169
+
170
+ Permission is hereby granted, free of charge, to any person obtaining a copy
171
+ of this software and associated documentation files (the "Software"), to deal
172
+ in the Software without restriction, including without limitation the rights
173
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
174
+ copies of the Software, and to permit persons to whom the Software is
175
+ furnished to do so, subject to the following conditions:
176
+
177
+ The above copyright notice and this permission notice shall be included in all
178
+ copies or substantial portions of the Software.
179
+
180
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
181
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
182
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
183
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
184
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
185
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
186
+ SOFTWARE.
187
+
188
+ 2. Ponytail (https://github.com/DietrichGebert/ponytail)
189
+ Used in: agents/ponytail
190
+ License: MIT, see agents/ponytail/NOTICE.md for the copyright and license text.
191
+
192
+ 3. Caveman (https://github.com/JuliusBrussee/caveman), pre-3.0.0
193
+ Used in: agents/caveman
194
+ License: MIT, see agents/caveman/NOTICE.md for the copyright and license text.
195
+
196
+ 4. Contributor Covenant 2.1 (https://www.contributor-covenant.org/version/2/1/code_of_conduct.html)
197
+ Used in: CODE_OF_CONDUCT.md
198
+ License: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/).
package/README.md CHANGED
@@ -1,3 +1,35 @@
1
- # Temporary Holding Version
1
+ # Po Deploy
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Deploy Po with one command. The `@agimon-ai/po-deploy` CLI installs Alchemy and the deployment stacks for you. No checkout, starter copy, or separate Alchemy install is needed. Requires Node.js 24.11.1 or newer on Linux or macOS.
4
+
5
+ ## Deploy
6
+
7
+ From a dedicated directory for this installation, run the command for your target:
8
+
9
+ ```sh
10
+ npx @agimon-ai/po-deploy vps admin@your-vps.example
11
+ npx @agimon-ai/po-deploy cloudflare
12
+ ```
13
+
14
+ Alchemy shows the plan and asks before applying it. Add `--plan` for a local preview without connecting to a provider. Use `--yes` only to apply automatically after reviewing the plan. The CLI keeps Alchemy state and the generated VPS installation ID in the current directory's private `.po-deploy/` folder. Keep it, and don't share it between installations or run concurrent deploys.
15
+
16
+ ### VPS prerequisites
17
+
18
+ Use a dedicated Linux VPS with systemd, Node.js 24.11.1 or newer, npm, `ss`, and `lsof`. Configure a trusted SSH host key and root or non-interactive sudo access. The CLI prints the SSH tunnel command after a successful install. Keep Po's listeners private.
19
+
20
+ ### Cloudflare prerequisites
21
+
22
+ Set these before running the command:
23
+
24
+ | Setting | Value |
25
+ | ---------------------------------- | ----------------------------------------------------------------------------------------------- |
26
+ | `CLOUDFLARE_ACCOUNT_ID` | Account ID. Configure `workers.dev` in the account first. |
27
+ | `CLOUDFLARE_API_TOKEN` | Account-scoped Workers Scripts Edit token. Not needed for `--plan`. |
28
+ | `PO_CF_INSTALL_ID` | Generate once with `openssl rand -hex 16` and keep it. The Worker is named `po-<id>`. |
29
+ | `PO_CF_ACTION` | `create` for a fresh Worker, `update` for the same installation. |
30
+ | `PO_CF_PROVIDER` and `PO_CF_MODEL` | `openai` with `gpt-4.1-mini`, for example, or `openrouter` with the selected `vendor/model` ID. |
31
+ | `PO_CF_SECRETS_FILE` | Creation only: absolute path to a private JSON file (mode `0600`). |
32
+
33
+ The JSON file contains only `PO_ATTACH_TOKEN`, `PO_PROVIDER_API_KEY`, and `PO_ORG_KEY_WRAP`. Generate the attach token and wrapping key separately with `openssl rand -hex 32`. Use the attach token to sign into the HTTPS URL Wrangler prints. Keep secrets out of Git and retain the wrapping key to preserve access to stored credentials. Unset the secrets file for an update. Do not adopt an existing Worker or switch deployers.
34
+
35
+ The Worker uses the published Po bundle and its existing migration history. Optional agent browsing and containers remain off. The CLI does not publish packages or delete deployments. These commands are verified locally from the packed CLI; live deployment through this CLI is not yet verified.
@@ -0,0 +1,34 @@
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ import * as Alchemy from 'alchemy';
4
+ import * as Command from 'alchemy/Command';
5
+ import * as Config from 'effect/Config';
6
+ import * as Effect from 'effect/Effect';
7
+
8
+ import { resolveTarget } from './deploy.mjs';
9
+
10
+ export const PoSelfHostCloudflare = Alchemy.Stack(
11
+ 'PoSelfHostCloudflare',
12
+ { providers: Command.providers(), state: Alchemy.localState() },
13
+ Effect.gen(function* () {
14
+ const env = {
15
+ CLOUDFLARE_ACCOUNT_ID: yield* Config.String('CLOUDFLARE_ACCOUNT_ID'),
16
+ PO_CF_INSTALL_ID: yield* Config.String('PO_CF_INSTALL_ID'),
17
+ PO_CF_ACTION: yield* Config.String('PO_CF_ACTION'),
18
+ PO_CF_PROVIDER: yield* Config.String('PO_CF_PROVIDER').pipe(Config.withDefault('openrouter')),
19
+ PO_CF_MODEL: yield* Config.String('PO_CF_MODEL'),
20
+ };
21
+ const { worker } = yield* Effect.try(() => resolveTarget(env));
22
+ yield* Command.Exec('PoWorker', {
23
+ command: 'node deploy.mjs --apply',
24
+ cwd: fileURLToPath(new URL('.', import.meta.url)),
25
+ env,
26
+ // Create credentials are read at execution and never put in Alchemy state.
27
+ memo: { include: ['deploy.mjs', 'package-lock.json'] },
28
+ timeout: '15 minutes',
29
+ });
30
+ return { worker };
31
+ }),
32
+ );
33
+
34
+ export default PoSelfHostCloudflare;
@@ -0,0 +1,143 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { lstatSync, readFileSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+
7
+ const require = createRequire(import.meta.url);
8
+ const marker = 'PO_SELFHOST_INSTALL_ID';
9
+ const notFound = 10007;
10
+ const hexId = /^[a-f0-9]{32}$/;
11
+
12
+ export function resolveTarget(env) {
13
+ const { CLOUDFLARE_ACCOUNT_ID: account, PO_CF_INSTALL_ID: installId, PO_CF_ACTION: action, PO_CF_MODEL: model } = env;
14
+ if (!hexId.test(account ?? '')) throw new Error('Set CLOUDFLARE_ACCOUNT_ID to the 32-character account ID.');
15
+ if (!hexId.test(installId ?? '')) throw new Error('Set PO_CF_INSTALL_ID to 32 lowercase hex characters.');
16
+ if (action !== 'create' && action !== 'update') throw new Error('Set PO_CF_ACTION to create or update.');
17
+ const provider = env.PO_CF_PROVIDER ?? 'openrouter';
18
+ if (provider !== 'openrouter' && provider !== 'openai')
19
+ throw new Error('Set PO_CF_PROVIDER to openrouter or openai.');
20
+ const modelId = provider === 'openai' ? /^[\w.-]+$/ : /^[\w.-]+\/[\w.:-]+$/;
21
+ if (!modelId.test(model ?? '')) throw new Error(`Set PO_CF_MODEL to a valid ${provider} model ID.`);
22
+ return { account, installId, action, provider, model, worker: `po-${installId}` };
23
+ }
24
+
25
+ // ponytail: This check is not a deploy lock. Operators must serialize writes; a multi-writer workflow would need provider-side fencing.
26
+ export async function verifyTarget(target, token, request = fetch) {
27
+ const { account, worker, installId, action } = target;
28
+ const url = `https://api.cloudflare.com/client/v4/accounts/${account}/workers/scripts/${worker}/settings`;
29
+ let response;
30
+ let payload;
31
+ try {
32
+ response = await request(url, {
33
+ headers: { Authorization: `Bearer ${token}` },
34
+ redirect: 'error',
35
+ signal: AbortSignal.timeout(15_000),
36
+ });
37
+ payload = await response.json();
38
+ } catch {
39
+ throw new Error('Could not verify Worker ownership with the Cloudflare API. No deploy was attempted.');
40
+ }
41
+ if (
42
+ response.status === 404 &&
43
+ payload?.success === false &&
44
+ payload.errors?.length === 1 &&
45
+ payload.errors[0]?.code === notFound
46
+ ) {
47
+ if (action === 'create') return;
48
+ throw new Error('The Worker is missing. Refusing to create replacement storage during an update.');
49
+ }
50
+ if (!response.ok || payload?.success !== true || !Array.isArray(payload.result?.bindings)) {
51
+ throw new Error(`Cloudflare did not confirm Worker ownership (HTTP ${response.status}).`);
52
+ }
53
+ if (action === 'create') throw new Error('This Worker already exists. Create mode never overwrites a Worker.');
54
+ if (!payload.result.bindings.some((b) => b?.name === marker && b.type === 'plain_text' && b.text === installId)) {
55
+ throw new Error('This Worker does not belong to this starter installation.');
56
+ }
57
+ }
58
+
59
+ export function validateSecrets(path) {
60
+ const explanation =
61
+ 'PO_CF_SECRETS_FILE must be an absolute path to a private JSON file owned by you with only PO_ATTACH_TOKEN, PO_PROVIDER_API_KEY and PO_ORG_KEY_WRAP.';
62
+ let secrets;
63
+ try {
64
+ const stat = path && isAbsolute(path) && lstatSync(path);
65
+ if (stat && stat.isFile() && (stat.mode & 0o077) === 0 && stat.uid === process.getuid?.() && stat.size <= 16_384) {
66
+ secrets = JSON.parse(readFileSync(path, 'utf8'));
67
+ }
68
+ } catch {
69
+ // The original error can contain secret values or paths.
70
+ throw new Error(explanation);
71
+ }
72
+ const token = secrets?.PO_ATTACH_TOKEN;
73
+ const apiKey = secrets?.PO_PROVIDER_API_KEY;
74
+ const wrap = secrets?.PO_ORG_KEY_WRAP;
75
+ const valid =
76
+ secrets &&
77
+ Object.keys(secrets).length === 3 &&
78
+ typeof token === 'string' &&
79
+ /^[\x21-\x7e]{32,512}$/.test(token) &&
80
+ typeof apiKey === 'string' &&
81
+ /^[\x21-\x7e]{1,4096}$/.test(apiKey) &&
82
+ typeof wrap === 'string' &&
83
+ /^[\x21-\x7e]{32,512}$/.test(wrap) &&
84
+ wrap !== token;
85
+ if (!valid) throw new Error(explanation);
86
+ }
87
+
88
+ async function main(args, env) {
89
+ const childEnv = {
90
+ PATH: env.PATH,
91
+ HOME: env.HOME,
92
+ TMPDIR: env.TMPDIR,
93
+ CI: '1',
94
+ WRANGLER_SEND_METRICS: 'false',
95
+ WRANGLER_LOG_SANITIZE: 'true',
96
+ };
97
+ const published = dirname(require.resolve('@agimon-ai/po-cloudflare/package.json'));
98
+ const wrangler = join(dirname(require.resolve('wrangler/package.json')), 'bin/wrangler.js');
99
+ const flags = ['deploy', '--config', join(published, 'wrangler.jsonc')];
100
+ if (args.length === 1 && args[0] === '--dry-run') {
101
+ flags.push('--name', 'po-local-validation', '--dry-run');
102
+ } else if (args.length === 1 && args[0] === '--apply') {
103
+ const target = resolveTarget(env);
104
+ const token = env.CLOUDFLARE_API_TOKEN;
105
+ if (!token || /\s/.test(token)) throw new Error('Set CLOUDFLARE_API_TOKEN for the selected account.');
106
+ const secretsFile = env.PO_CF_SECRETS_FILE;
107
+ if (target.action === 'create') {
108
+ validateSecrets(secretsFile);
109
+ flags.push('--secrets-file', secretsFile);
110
+ } else if (secretsFile) {
111
+ throw new Error(
112
+ 'Unset PO_CF_SECRETS_FILE for updates. The pinned Wrangler retains existing secrets; replacing the wrapping key would strand stored credentials.',
113
+ );
114
+ }
115
+ await verifyTarget(target, token);
116
+ childEnv.CLOUDFLARE_API_TOKEN = token;
117
+ childEnv.CLOUDFLARE_ACCOUNT_ID = target.account;
118
+ flags.push(
119
+ '--name',
120
+ target.worker,
121
+ '--var',
122
+ `${marker}:${target.installId}`,
123
+ '--var',
124
+ `PO_DEFAULT_PROVIDER:${target.provider}`,
125
+ '--var',
126
+ `PO_DEFAULT_MODEL:${target.model}`,
127
+ );
128
+ } else {
129
+ throw new Error('Use npm run plan, npm run deploy, or npm run dry-run.');
130
+ }
131
+ const result = spawnSync(process.execPath, [wrangler, ...flags], { cwd: published, env: childEnv, stdio: 'inherit' });
132
+ if (result.error) throw result.error;
133
+ return result.status ?? 1;
134
+ }
135
+
136
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
137
+ try {
138
+ process.exitCode = await main(process.argv.slice(2), process.env);
139
+ } catch (error) {
140
+ process.stderr.write(`${error instanceof Error ? error.message : 'Cloudflare starter failed.'}\n`);
141
+ process.exitCode = 1;
142
+ }
143
+ }
@@ -0,0 +1,46 @@
1
+ import { dirname } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ import * as Alchemy from 'alchemy';
5
+ import * as Command from 'alchemy/Command';
6
+ import * as Config from 'effect/Config';
7
+ import * as Effect from 'effect/Effect';
8
+ import * as Option from 'effect/Option';
9
+
10
+ const projectDir = dirname(fileURLToPath(import.meta.url));
11
+
12
+ // Optional settings. An unset one is dropped, and scripts/config.mjs supplies the default.
13
+ const optional = (name ) => Config.option(Config.String(name)).pipe(Effect.map(Option.getOrUndefined));
14
+
15
+ /**
16
+ * One Command.Exec that converges an existing Linux VPS over SSH. Alchemy reruns it when
17
+ * scripts/** or any setting below changes. `alchemy destroy` forgets it but does not
18
+ * undo anything on the VPS: use `npm run uninstall` for that (see README.md).
19
+ */
20
+ export default Alchemy.Stack(
21
+ 'PoSelfHostVps',
22
+ { providers: Command.providers(), state: Alchemy.localState() },
23
+ Effect.gen(function* () {
24
+ const sshTarget = yield* Config.String('PO_VPS_SSH_TARGET');
25
+
26
+ yield* Command.Exec('PoHost', {
27
+ command: 'node scripts/deploy.mjs install',
28
+ cwd: projectDir,
29
+ env: {
30
+ PO_VPS_SSH_TARGET: sshTarget,
31
+ PO_VPS_SSH_PORT: yield* optional('PO_VPS_SSH_PORT'),
32
+ PO_VPS_SSH_CONFIG: yield* optional('PO_VPS_SSH_CONFIG'),
33
+ PO_VPS_PO_VERSION: yield* optional('PO_VPS_PO_VERSION'),
34
+ PO_VPS_PO_WEB_VERSION: yield* optional('PO_VPS_PO_WEB_VERSION'),
35
+ PO_VPS_SERVICE_USER: yield* optional('PO_VPS_SERVICE_USER'),
36
+ PO_VPS_WEB_PORT: yield* optional('PO_VPS_WEB_PORT'),
37
+ PO_VPS_HEADLESS_PORT: yield* optional('PO_VPS_HEADLESS_PORT'),
38
+ PO_VPS_INSTALL_ID: yield* optional('PO_VPS_INSTALL_ID'),
39
+ },
40
+ memo: { include: ['scripts/**'] },
41
+ timeout: '30 minutes',
42
+ });
43
+
44
+ return { sshTarget };
45
+ }),
46
+ );
@@ -0,0 +1,84 @@
1
+ // Single source of truth for the starter's inputs, shared by alchemy.run.ts and deploy.mjs.
2
+ // Everything is validated here because these values end up in a remote shell command.
3
+
4
+ export const DEFAULTS = {
5
+ // Exact pins. Bump both together after checking the registry; never "latest".
6
+ poVersion: '0.0.0-alpha.170',
7
+ poWebVersion: '0.0.0-alpha.169',
8
+ serviceUser: 'po-agent',
9
+ webPort: 7533,
10
+ headlessPort: 7534,
11
+ };
12
+
13
+ export class ConfigError extends Error {}
14
+
15
+ const SSH_TARGET = /^([A-Za-z0-9][A-Za-z0-9._-]*@)?[A-Za-z0-9][A-Za-z0-9._-]*$/;
16
+ const EXACT_VERSION = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
17
+ const USER_NAME = /^[a-z_][a-z0-9_-]{0,30}$/;
18
+ const INSTALL_ID = /^[A-Za-z0-9-]{8,64}$/;
19
+
20
+ const port = (name, value) => {
21
+ const n = typeof value === 'number' ? value : Number(value);
22
+ if (!Number.isInteger(n) || n < 1024 || n > 65535) {
23
+ throw new ConfigError(`${name} must be an integer from 1024 to 65535, got "${value}"`);
24
+ }
25
+ return n;
26
+ };
27
+
28
+ const match = (name, value, pattern, hint) => {
29
+ if (typeof value !== 'string' || !pattern.test(value)) {
30
+ throw new ConfigError(`${name} ${hint}, got "${value ?? ''}"`);
31
+ }
32
+ return value;
33
+ };
34
+
35
+ /**
36
+ * Turns raw environment values into a validated configuration.
37
+ * `installId` is required: deploy.mjs supplies it from the local `.po-selfhost/install-id` file.
38
+ */
39
+ export const resolveConfig = (env) => {
40
+ const sshTarget = match(
41
+ 'PO_VPS_SSH_TARGET',
42
+ env.PO_VPS_SSH_TARGET,
43
+ SSH_TARGET,
44
+ 'must be "host" or "user@host" (use an ~/.ssh/config alias for anything else)',
45
+ );
46
+ const sshPort = env.PO_VPS_SSH_PORT ? port('PO_VPS_SSH_PORT', env.PO_VPS_SSH_PORT) : undefined;
47
+ // Optional ssh_config file (passed as -F) for keys and known_hosts kept outside ~/.ssh.
48
+ const sshConfig = env.PO_VPS_SSH_CONFIG
49
+ ? match('PO_VPS_SSH_CONFIG', env.PO_VPS_SSH_CONFIG, /^[^\n\0]+$/, 'must be a single-line file path')
50
+ : undefined;
51
+ const poVersion = match(
52
+ 'PO_VPS_PO_VERSION',
53
+ env.PO_VPS_PO_VERSION || DEFAULTS.poVersion,
54
+ EXACT_VERSION,
55
+ 'must be an exact version such as 0.0.0-alpha.170',
56
+ );
57
+ const poWebVersion = match(
58
+ 'PO_VPS_PO_WEB_VERSION',
59
+ env.PO_VPS_PO_WEB_VERSION || DEFAULTS.poWebVersion,
60
+ EXACT_VERSION,
61
+ 'must be an exact version such as 0.0.0-alpha.169',
62
+ );
63
+ const serviceUser = match(
64
+ 'PO_VPS_SERVICE_USER',
65
+ env.PO_VPS_SERVICE_USER || DEFAULTS.serviceUser,
66
+ USER_NAME,
67
+ 'must be a lowercase unix user name',
68
+ );
69
+ if (serviceUser === 'root') {
70
+ throw new ConfigError('PO_VPS_SERVICE_USER must not be root');
71
+ }
72
+ const webPort = port('PO_VPS_WEB_PORT', env.PO_VPS_WEB_PORT || DEFAULTS.webPort);
73
+ const headlessPort = port('PO_VPS_HEADLESS_PORT', env.PO_VPS_HEADLESS_PORT || DEFAULTS.headlessPort);
74
+ if (webPort === headlessPort) {
75
+ throw new ConfigError('PO_VPS_WEB_PORT and PO_VPS_HEADLESS_PORT must differ');
76
+ }
77
+ const installId = match(
78
+ 'PO_VPS_INSTALL_ID',
79
+ env.PO_VPS_INSTALL_ID,
80
+ INSTALL_ID,
81
+ 'must be 8 to 64 letters, digits or dashes',
82
+ );
83
+ return { sshTarget, sshPort, sshConfig, poVersion, poWebVersion, serviceUser, webPort, headlessPort, installId };
84
+ };
@@ -0,0 +1,149 @@
1
+ // Runs from your machine. Sends scripts/remote.sh to the VPS over OpenSSH and runs it there as root.
2
+ // Alchemy calls `install` through Command.Exec; the other modes are for you (see README.md).
3
+ //
4
+ // node scripts/deploy.mjs install converge the VPS to the configured release
5
+ // node scripts/deploy.mjs preflight check the VPS and installation ownership, change nothing
6
+ // node scripts/deploy.mjs uninstall [--purge-data --confirm <install-id>]
7
+
8
+ import { spawn } from 'node:child_process';
9
+ import { randomUUID } from 'node:crypto';
10
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
11
+ import { dirname, join, resolve } from 'node:path';
12
+ import { fileURLToPath, pathToFileURL } from 'node:url';
13
+
14
+ import { ConfigError, resolveConfig } from './config.mjs';
15
+
16
+ const here = dirname(fileURLToPath(import.meta.url));
17
+ const projectDir = resolve(here, '..');
18
+ const remoteScript = join(here, 'remote.sh');
19
+
20
+ export const shellQuote = (value) => `'${String(value).replace(/'/g, `'\\''`)}'`;
21
+
22
+ // Strict host key checking means the host must already be in known_hosts: verify its
23
+ // fingerprint once with a normal `ssh` login. No agent, X11 or port forwarding is ever requested.
24
+ export const sshArgs = (config) => [
25
+ ...(config.sshConfig ? ['-F', config.sshConfig] : []),
26
+ '-T',
27
+ '-o',
28
+ 'BatchMode=yes',
29
+ '-o',
30
+ 'StrictHostKeyChecking=yes',
31
+ '-o',
32
+ 'ForwardAgent=no',
33
+ '-o',
34
+ 'ForwardX11=no',
35
+ '-o',
36
+ 'ClearAllForwardings=yes',
37
+ '-o',
38
+ 'ConnectTimeout=15',
39
+ '-o',
40
+ 'ServerAliveInterval=15',
41
+ ...(config.sshPort ? ['-p', String(config.sshPort)] : []),
42
+ '--',
43
+ config.sshTarget,
44
+ ];
45
+
46
+ export const remoteEnv = (config, extra = {}) => ({
47
+ PO_SELFHOST_INSTALL_ID: config.installId,
48
+ PO_SELFHOST_USER: config.serviceUser,
49
+ PO_SELFHOST_PO_VERSION: config.poVersion,
50
+ PO_SELFHOST_WEB_VERSION: config.poWebVersion,
51
+ PO_SELFHOST_WEB_PORT: String(config.webPort),
52
+ PO_SELFHOST_HEADLESS_PORT: String(config.headlessPort),
53
+ ...extra,
54
+ });
55
+
56
+ // The script arrives on stdin, so nothing from this machine is interpolated into the script itself.
57
+ export const remoteCommand = (config, mode, extraEnv = {}) => {
58
+ const assignments = Object.entries(remoteEnv(config, extraEnv))
59
+ .map(([key, value]) => shellQuote(`${key}=${value}`))
60
+ .join(' ');
61
+ return [
62
+ `if [ "$(id -u)" = 0 ]; then SUDO=''; else SUDO='sudo -n'; fi;`,
63
+ `exec $SUDO env ${assignments} sh -s -- ${shellQuote(mode)}`,
64
+ ].join(' ');
65
+ };
66
+
67
+ export const buildInvocation = (config, mode, extraEnv = {}) => ({
68
+ command: 'ssh',
69
+ args: [...sshArgs(config), remoteCommand(config, mode, extraEnv)],
70
+ });
71
+
72
+ export const loadInstallId = (env, directory, { create }) => {
73
+ if (env.PO_VPS_INSTALL_ID) return env.PO_VPS_INSTALL_ID;
74
+ const file = join(directory, '.po-selfhost', 'install-id');
75
+ if (existsSync(file)) return readFileSync(file, 'utf8').trim();
76
+ if (!create) {
77
+ throw new ConfigError(
78
+ `No installation id at ${file}. Set PO_VPS_INSTALL_ID to the id shown by: ssh <host> cat /var/lib/po-selfhost/installation`,
79
+ );
80
+ }
81
+ mkdirSync(dirname(file), { recursive: true });
82
+ const id = randomUUID();
83
+ writeFileSync(file, `${id}\n`, { mode: 0o600 });
84
+ return id;
85
+ };
86
+
87
+ const run = (invocation, script) =>
88
+ new Promise((resolveRun, rejectRun) => {
89
+ const child = spawn(invocation.command, invocation.args, { stdio: ['pipe', 'inherit', 'inherit'] });
90
+ child.on('error', rejectRun);
91
+ child.on('close', (code, signal) => resolveRun(signal ? 1 : (code ?? 1)));
92
+ child.stdin.on('error', (error) => {
93
+ // SSH can close stdin on early exit. The close event reports the remote failure.
94
+ if (error.code !== 'EPIPE') rejectRun(error);
95
+ });
96
+ child.stdin.end(script);
97
+ });
98
+
99
+ const connectHelp = (config) => {
100
+ const configFile = config.sshConfig ? ` -F ${shellQuote(config.sshConfig)}` : '';
101
+ const port = config.sshPort ? ` -p ${config.sshPort}` : '';
102
+ return [
103
+ '',
104
+ `Po is running on ${config.sshTarget} and listens on 127.0.0.1 only.`,
105
+ 'Open a loopback tunnel with the same web port at both ends, then browse the local address:',
106
+ ` ssh${configFile}${port} -N -o StrictHostKeyChecking=yes -o ExitOnForwardFailure=yes -L 127.0.0.1:${config.webPort}:127.0.0.1:${config.webPort} -- ${shellQuote(config.sshTarget)}`,
107
+ ` http://127.0.0.1:${config.webPort}`,
108
+ '',
109
+ ].join('\n');
110
+ };
111
+
112
+ export const main = async (argv, env = process.env) => {
113
+ const [mode, ...flags] = argv;
114
+ if (!['install', 'preflight', 'uninstall'].includes(mode)) {
115
+ console.error(
116
+ 'usage: node scripts/deploy.mjs install | preflight | uninstall [--purge-data --confirm <install-id>]',
117
+ );
118
+ return 2;
119
+ }
120
+ try {
121
+ const installId = loadInstallId(env, env.PO_VPS_STATE_DIR || projectDir, { create: mode !== 'uninstall' });
122
+ const config = resolveConfig({ ...env, PO_VPS_INSTALL_ID: installId });
123
+ const extraEnv = {};
124
+ if (mode === 'uninstall' && flags.includes('--purge-data')) {
125
+ const confirmed = flags[flags.indexOf('--confirm') + 1];
126
+ if (flags.indexOf('--confirm') < 0 || confirmed !== config.installId) {
127
+ throw new ConfigError(
128
+ `--purge-data deletes all Po data on the host. Repeat with: --confirm ${config.installId}`,
129
+ );
130
+ }
131
+ extraEnv.PO_SELFHOST_PURGE = '1';
132
+ }
133
+ const code = await run(buildInvocation(config, mode, extraEnv), readFileSync(remoteScript));
134
+ if (code === 0 && mode === 'install') console.log(connectHelp(config));
135
+ if (code === 20)
136
+ console.error('The host was left unchanged: it already holds something this starter does not own.');
137
+ return code;
138
+ } catch (error) {
139
+ if (error instanceof ConfigError) {
140
+ console.error(`po-selfhost: ${error.message}`);
141
+ return 2;
142
+ }
143
+ throw error;
144
+ }
145
+ };
146
+
147
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
148
+ process.exitCode = await main(process.argv.slice(2));
149
+ }
@@ -0,0 +1,271 @@
1
+ #!/bin/sh
2
+ # Runs on the VPS as root. scripts/deploy.mjs sends it over SSH stdin: `sh -s -- <mode>`.
3
+ #
4
+ # Modes: install | uninstall | preflight | ownership
5
+ # ownership only the "is this host ours" check; needs neither root nor Linux (used by the tests)
6
+ # preflight host requirements plus ownership; changes nothing
7
+ #
8
+ # Layout (root-owned unless noted):
9
+ # $APP_ROOT/releases/<versions>/ one npm install per release, read-only to the service user
10
+ # $APP_ROOT/current symlink to the active release
11
+ # $STATE_ROOT/installation marker: which installation owns this host
12
+ # $STATE_ROOT/home, workspace owned by the service user; these hold all Po data
13
+ # Exit codes: 1 failure, 20 refused (host holds something this starter does not own), 30 not ready.
14
+
15
+ set -eu
16
+ umask 022
17
+
18
+ MODE=${1:-install}
19
+
20
+ INSTALL_ID=${PO_SELFHOST_INSTALL_ID:?PO_SELFHOST_INSTALL_ID is required}
21
+ SVC_USER=${PO_SELFHOST_USER:-po-agent}
22
+ PO_VERSION=${PO_SELFHOST_PO_VERSION:-}
23
+ WEB_VERSION=${PO_SELFHOST_WEB_VERSION:-}
24
+ WEB_PORT=${PO_SELFHOST_WEB_PORT:-7533}
25
+ HEADLESS_PORT=${PO_SELFHOST_HEADLESS_PORT:-7534}
26
+ PURGE=${PO_SELFHOST_PURGE:-0}
27
+
28
+ # Test seams. deploy.mjs never sends these, so a real run always uses the defaults.
29
+ APP_ROOT=${PO_SELFHOST_APP_ROOT:-/opt/po-selfhost}
30
+ STATE_ROOT=${PO_SELFHOST_STATE_ROOT:-/var/lib/po-selfhost}
31
+ UNIT_NAME=po-selfhost.service
32
+ UNIT_PATH=${PO_SELFHOST_UNIT_PATH:-/etc/systemd/system/$UNIT_NAME}
33
+
34
+ MARKER=$STATE_ROOT/installation
35
+ ACTIVATED=$STATE_ROOT/activated
36
+ READY_SECONDS=${PO_SELFHOST_READY_SECONDS:-240}
37
+
38
+ log() { printf 'po-selfhost: %s\n' "$*"; }
39
+ die() { printf 'po-selfhost: %s\n' "$1" >&2; exit "${2:-1}"; }
40
+ refuse() { printf 'po-selfhost: refusing to continue: %s\n' "$1" >&2; exit 20; }
41
+
42
+ valid() { printf '%s' "$2" | grep -Eq "$1" || die "invalid value for $3: '$2'"; }
43
+ valid '^[A-Za-z0-9-]{8,64}$' "$INSTALL_ID" PO_SELFHOST_INSTALL_ID
44
+ valid '^[a-z_][a-z0-9_-]{0,30}$' "$SVC_USER" PO_SELFHOST_USER
45
+ valid '^[0-9]{4,5}$' "$WEB_PORT" PO_SELFHOST_WEB_PORT
46
+ valid '^[0-9]{4,5}$' "$HEADLESS_PORT" PO_SELFHOST_HEADLESS_PORT
47
+ [ "$SVC_USER" != root ] || die "the service user must not be root"
48
+
49
+ # rm -rf is only ever pointed at these, so keep them absolute and at least two levels deep.
50
+ for p in "$APP_ROOT" "$STATE_ROOT" "$UNIT_PATH"; do
51
+ case $p in /?*/?*) ;; *) die "unsafe path '$p'" ;; esac
52
+ done
53
+
54
+ non_empty_dir() { [ -d "$1" ] && [ -n "$(ls -A "$1" 2>/dev/null)" ]; }
55
+
56
+ # Proves this host is empty of Po, or already belongs to this installation id and service user.
57
+ ownership_check() {
58
+ if [ -f "$MARKER" ]; then
59
+ have_id=$(sed -n 's/^id=//p' "$MARKER" | sed -n 1p)
60
+ have_user=$(sed -n 's/^user=//p' "$MARKER" | sed -n 1p)
61
+ [ "$have_id" = "$INSTALL_ID" ] || refuse "this host belongs to installation '$have_id', not '$INSTALL_ID'"
62
+ [ "$have_user" = "$SVC_USER" ] || refuse "this installation runs as '$have_user', not '$SVC_USER'"
63
+ return 0
64
+ fi
65
+ if [ "${1:-}" = require ]; then
66
+ refuse "no installation marker at $MARKER, so nothing here belongs to this starter"
67
+ fi
68
+ if [ -e "$UNIT_PATH" ]; then refuse "$UNIT_PATH exists and was not created by this starter"; fi
69
+ if non_empty_dir "$APP_ROOT"; then refuse "$APP_ROOT exists and was not created by this starter"; fi
70
+ if non_empty_dir "$STATE_ROOT"; then refuse "$STATE_ROOT exists and was not created by this starter"; fi
71
+ if id -u "$SVC_USER" >/dev/null 2>&1; then refuse "user '$SVC_USER' already exists"; fi
72
+ }
73
+
74
+ node_ok() {
75
+ "$NODE_BIN" -e '
76
+ const [major, minor, patch] = process.versions.node.split(".").map(Number);
77
+ process.exit(major > 24 || (major === 24 && (minor > 11 || (minor === 11 && patch >= 1))) ? 0 : 1);
78
+ '
79
+ }
80
+
81
+ host_checks() {
82
+ [ "$(uname -s)" = Linux ] || die "this starter supports Linux hosts only"
83
+ [ "$(id -u)" = 0 ] || die "must run as root: log in as root, or as a user with passwordless sudo"
84
+ [ -d /run/systemd/system ] || die "systemd is not running on this host"
85
+ for tool in systemctl useradd userdel runuser node npm install ln mv cmp; do
86
+ command -v "$tool" >/dev/null 2>&1 || die "missing required command: $tool"
87
+ done
88
+ NODE_BIN=$(command -v node)
89
+ NODE_DIR=$(dirname "$NODE_BIN")
90
+ node_ok || die "Node.js 24.11.1 or newer is required, found $("$NODE_BIN" --version) at $NODE_BIN"
91
+ }
92
+
93
+ as_user() {
94
+ runuser -u "$SVC_USER" -- env HOME="$STATE_ROOT/home" PATH="$RUN_PATH" "$@"
95
+ }
96
+
97
+ in_workspace() {
98
+ as_user sh -c 'cd "$1" && shift && exec "$@"' sh "$STATE_ROOT/workspace" "$@"
99
+ }
100
+
101
+ ensure_marker() {
102
+ mkdir -p "$STATE_ROOT"
103
+ [ -f "$MARKER" ] && return 0
104
+ printf 'id=%s\nuser=%s\nlayout=1\n' "$INSTALL_ID" "$SVC_USER" >"$MARKER.new"
105
+ mv -f "$MARKER.new" "$MARKER"
106
+ }
107
+
108
+ ensure_user_and_dirs() {
109
+ if ! id -u "$SVC_USER" >/dev/null 2>&1; then
110
+ nologin=$(command -v nologin || echo /usr/sbin/nologin)
111
+ useradd --system --user-group --home-dir "$STATE_ROOT/home" --no-create-home --shell "$nologin" "$SVC_USER"
112
+ log "created user $SVC_USER (no sudo, no login shell)"
113
+ fi
114
+ install -d -m 0755 "$APP_ROOT" "$APP_ROOT/releases"
115
+ install -d -o "$SVC_USER" -g "$SVC_USER" -m 0750 "$STATE_ROOT/home" "$STATE_ROOT/workspace"
116
+ }
117
+
118
+ install_release() {
119
+ if [ -f "$REL/.complete" ]; then
120
+ log "release already installed: $REL"
121
+ return 0
122
+ fi
123
+ rm -rf "$REL.tmp" "$REL"
124
+ install -d -o "$SVC_USER" -g "$SVC_USER" -m 0755 "$REL.tmp"
125
+ log "installing @agimon-ai/po@$PO_VERSION and @agimon-ai/po-web@$WEB_VERSION"
126
+ as_user npm install --prefix "$REL.tmp" --no-audit --no-fund --no-update-notifier \
127
+ "@agimon-ai/po@$PO_VERSION" "@agimon-ai/po-web@$WEB_VERSION"
128
+ as_user "$REL.tmp/node_modules/.bin/po-web" --version >/dev/null ||
129
+ die "the installed po-web does not run as $SVC_USER (is Node at $NODE_BIN readable by that user?)"
130
+ touch "$REL.tmp/.complete"
131
+ # Installed by the unprivileged user, then frozen: the service cannot rewrite its own code.
132
+ chown -R root:root "$REL.tmp"
133
+ chmod -R go-w "$REL.tmp"
134
+ mv "$REL.tmp" "$REL"
135
+ }
136
+
137
+ write_unit() {
138
+ cat >"$UNIT_PATH.new" <<UNIT
139
+ [Unit]
140
+ Description=Po web console and headless host
141
+ After=network-online.target
142
+ Wants=network-online.target
143
+
144
+ [Service]
145
+ Type=simple
146
+ User=$SVC_USER
147
+ Group=$SVC_USER
148
+ WorkingDirectory=$STATE_ROOT/workspace
149
+ Environment=HOME=$STATE_ROOT/home
150
+ Environment=PATH=$RUN_PATH
151
+ Environment=PO_IMMUTABLE_INSTALL=1
152
+ ExecStart=$APP_ROOT/current/node_modules/.bin/po-web --host 127.0.0.1 --port $WEB_PORT --headless-port $HEADLESS_PORT
153
+ Restart=on-failure
154
+ RestartSec=5
155
+ NoNewPrivileges=true
156
+ PrivateTmp=true
157
+ ProtectHome=true
158
+
159
+ [Install]
160
+ WantedBy=multi-user.target
161
+ UNIT
162
+ if [ -f "$UNIT_PATH" ] && cmp -s "$UNIT_PATH" "$UNIT_PATH.new"; then
163
+ rm -f "$UNIT_PATH.new"
164
+ return 1
165
+ fi
166
+ mv -f "$UNIT_PATH.new" "$UNIT_PATH"
167
+ return 0
168
+ }
169
+
170
+ web_ready() {
171
+ systemctl is-active --quiet "$UNIT_NAME" &&
172
+ "$NODE_BIN" -e '
173
+ fetch(process.argv[1], { signal: AbortSignal.timeout(5000) })
174
+ .then((r) => process.exit(r.ok ? 0 : 1), () => process.exit(1));
175
+ ' "http://127.0.0.1:$WEB_PORT/api/health"
176
+ }
177
+
178
+ wait_ready() {
179
+ waited=0
180
+ while [ "$waited" -lt "$READY_SECONDS" ]; do
181
+ if web_ready; then return 0; fi
182
+ sleep 3
183
+ waited=$((waited + 3))
184
+ done
185
+ return 1
186
+ }
187
+
188
+ # Both ports must be loopback-only; anything else would expose the raw listener.
189
+ assert_loopback() {
190
+ command -v ss >/dev/null 2>&1 || { log "ss not found, skipped the loopback listener check"; return 0; }
191
+ exposed=$(ss -H -ltn | awk -v w=":$WEB_PORT" -v h=":$HEADLESS_PORT" '
192
+ { n = length($4); s = substr($4, n - length(w) + 1) }
193
+ (s == w || substr($4, n - length(h) + 1) == h) && $4 !~ /^127\.0\.0\.1:/ && $4 !~ /^\[::1\]:/ { print $4 }')
194
+ [ -z "$exposed" ] || die "Po is listening beyond loopback: $exposed" 31
195
+ }
196
+
197
+ do_install() {
198
+ : "${PO_VERSION:?PO_SELFHOST_PO_VERSION is required}" "${WEB_VERSION:?PO_SELFHOST_WEB_VERSION is required}"
199
+ host_checks
200
+ ownership_check
201
+ ensure_marker
202
+ RUN_PATH=$NODE_DIR:/usr/local/bin:/usr/bin:/bin
203
+ ensure_user_and_dirs
204
+
205
+ REL=$APP_ROOT/releases/po-$PO_VERSION-web-$WEB_VERSION
206
+ install_release
207
+ RUN_PATH=$REL/node_modules/.bin:$RUN_PATH
208
+
209
+ # Existing files are preserved by `po init`; `po sync` prepares this release's packages and builds.
210
+ in_workspace "$REL/node_modules/.bin/po" init
211
+ in_workspace "$REL/node_modules/.bin/po" sync
212
+
213
+ previous=$(cat "$ACTIVATED" 2>/dev/null || true)
214
+ ln -sfn "$REL" "$APP_ROOT/current.new"
215
+ mv -fT "$APP_ROOT/current.new" "$APP_ROOT/current"
216
+
217
+ RUN_PATH=$APP_ROOT/current/node_modules/.bin:$NODE_DIR:/usr/local/bin:/usr/bin:/bin
218
+ changed=0
219
+ if write_unit; then changed=1; systemctl daemon-reload; fi
220
+ systemctl enable "$UNIT_NAME"
221
+ # `activated` is written only after a healthy start, so an interrupted run is retried next time.
222
+ if [ "$previous" != "$REL" ]; then changed=1; fi
223
+ if [ "$changed" = 1 ] || ! systemctl is-active --quiet "$UNIT_NAME"; then
224
+ log "starting $UNIT_NAME"
225
+ systemctl restart "$UNIT_NAME"
226
+ fi
227
+
228
+ if ! wait_ready; then
229
+ journalctl -u "$UNIT_NAME" -n 40 --no-pager >&2 || true
230
+ if [ -n "$previous" ] && [ -d "$previous" ] && [ "$previous" != "$REL" ]; then
231
+ log "rolling back to $previous"
232
+ ln -sfn "$previous" "$APP_ROOT/current.new"
233
+ mv -fT "$APP_ROOT/current.new" "$APP_ROOT/current"
234
+ systemctl restart "$UNIT_NAME" || true
235
+ fi
236
+ die "Po did not become ready within ${READY_SECONDS}s; see the journal above" 30
237
+ fi
238
+ assert_loopback
239
+
240
+ printf '%s\n' "$REL" >"$ACTIVATED"
241
+ for old in "$APP_ROOT"/releases/*; do
242
+ [ -d "$old" ] || continue
243
+ [ "$old" = "$REL" ] || [ "$old" = "$previous" ] || rm -rf "$old"
244
+ done
245
+ log "ready: $REL"
246
+ }
247
+
248
+ do_uninstall() {
249
+ [ "$(id -u)" = 0 ] || die "must run as root: log in as root, or as a user with passwordless sudo"
250
+ ownership_check require
251
+ systemctl disable --now "$UNIT_NAME" 2>/dev/null || true
252
+ rm -f "$UNIT_PATH" "$UNIT_PATH.new"
253
+ systemctl daemon-reload
254
+ rm -rf "$APP_ROOT"
255
+ if [ "$PURGE" = 1 ]; then
256
+ rm -rf "$STATE_ROOT"
257
+ userdel "$SVC_USER" 2>/dev/null || true
258
+ log "removed the service, the application files, all Po data and user $SVC_USER"
259
+ else
260
+ rm -f "$ACTIVATED"
261
+ log "removed the service and application files; kept $STATE_ROOT and user $SVC_USER"
262
+ fi
263
+ }
264
+
265
+ case $MODE in
266
+ ownership) ownership_check; log "ownership ok" ;;
267
+ preflight) host_checks; ownership_check; log "preflight ok (node $("$NODE_BIN" --version) at $NODE_BIN)" ;;
268
+ install) do_install ;;
269
+ uninstall) do_uninstall ;;
270
+ *) die "unknown mode '$MODE'" ;;
271
+ esac
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-deploy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.2-alpha.0",
4
+ "description": "Deploy a fresh Po host with Alchemy.",
5
+ "license": "BUSL-1.1",
6
+ "bin": {
7
+ "po-deploy": "./src/bin/cli.mjs"
8
+ },
9
+ "files": [
10
+ "src/bin",
11
+ "dist/stacks/**/*.mjs",
12
+ "dist/stacks/**/*.sh",
13
+ "README.md"
14
+ ],
15
+ "type": "module",
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "dependencies": {
20
+ "@agimon-ai/po-cloudflare": "0.0.2-alpha.71",
21
+ "@effect/platform-node": "4.1.4",
22
+ "alchemy": "2.0.0-beta.87",
23
+ "effect": "4.1.4",
24
+ "wrangler": "4.150.0"
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "26.6.5",
28
+ "typescript": "7.0.2"
29
+ },
30
+ "engines": {
31
+ "node": ">=24.11.1"
32
+ },
33
+ "scripts": {
34
+ "build": "node scripts/build.mjs",
35
+ "typecheck": "tsc --noEmit --strict --allowJs --checkJs --skipLibCheck --types node --target es2022 --module nodenext src/bin/cli.mjs scripts/build.mjs",
36
+ "lint": "oxlint . && oxfmt . --check",
37
+ "test": "node --test tests/cli.test.mjs"
38
+ }
6
39
  }
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { spawnSync } from 'node:child_process';
4
+ import { lstatSync, mkdirSync, writeFileSync } from 'node:fs';
5
+ import { createRequire } from 'node:module';
6
+ import { dirname, join, resolve } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ const usage = `Usage:
10
+ po-deploy cloudflare [--plan | --yes]
11
+ po-deploy vps [user@host] [--plan | --yes]
12
+
13
+ Alchemy is included. Deploy shows the plan and asks before applying it.
14
+ Run from a dedicated directory for the installation. See the package README for provider credentials and settings.
15
+ `;
16
+ const require = createRequire(import.meta.url);
17
+
18
+ /** @param {string[]} argv @param {NodeJS.ProcessEnv} environment @param {string} cwd */
19
+ function run(argv, environment, cwd) {
20
+ if (argv.length === 0 || (argv.length === 1 && argv[0] === '--help')) {
21
+ process.stdout.write(usage);
22
+ return 0;
23
+ }
24
+ const [provider, ...args] = argv;
25
+ if (provider !== 'cloudflare' && provider !== 'vps') throw new Error(usage.trim());
26
+ if (args.length === 1 && args[0] === '--help') {
27
+ process.stdout.write(usage);
28
+ return 0;
29
+ }
30
+ const target = provider === 'vps' && args[0] && !args[0].startsWith('-') ? args.shift() : undefined;
31
+ const [flag] = args;
32
+ if (args.length > 1 || (flag && flag !== '--plan' && flag !== '--yes')) throw new Error(usage.trim());
33
+
34
+ const state = join(cwd, '.po-deploy', provider);
35
+ for (const directory of [dirname(state), state]) {
36
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
37
+ const stat = lstatSync(directory);
38
+ if (!stat.isDirectory() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0) {
39
+ throw new Error('Use a private, user-owned .po-deploy directory. Do not use symlinks.');
40
+ }
41
+ }
42
+ try {
43
+ writeFileSync(join(dirname(state), '.gitignore'), '*\n', { flag: 'wx', mode: 0o600 });
44
+ } catch (error) {
45
+ if (!(error instanceof Error && 'code' in error && error.code === 'EEXIST')) throw error;
46
+ }
47
+
48
+ const prefix = provider === 'vps' ? 'PO_VPS_' : 'PO_CF_';
49
+ /** @type {NodeJS.ProcessEnv} */
50
+ const env = {
51
+ ...Object.fromEntries(Object.entries(environment).filter(([key]) => key.startsWith(prefix))),
52
+ PATH: environment.PATH,
53
+ HOME: environment.HOME,
54
+ TMPDIR: environment.TMPDIR,
55
+ SSH_AUTH_SOCK: provider === 'vps' ? environment.SSH_AUTH_SOCK : undefined,
56
+ CLOUDFLARE_ACCOUNT_ID: environment.CLOUDFLARE_ACCOUNT_ID,
57
+ CLOUDFLARE_API_TOKEN: provider === 'cloudflare' && flag !== '--plan' ? environment.CLOUDFLARE_API_TOKEN : undefined,
58
+ PO_VPS_STATE_DIR: state,
59
+ };
60
+ if (target) env.PO_VPS_SSH_TARGET = target;
61
+ if (env.PO_VPS_SSH_CONFIG) env.PO_VPS_SSH_CONFIG = resolve(cwd, env.PO_VPS_SSH_CONFIG);
62
+ if (flag === '--plan') delete env.PO_CF_SECRETS_FILE;
63
+ const stack = fileURLToPath(new URL(`../../dist/stacks/${provider}/alchemy.run.mjs`, import.meta.url));
64
+ const destination = provider === 'vps' ? env.PO_VPS_SSH_TARGET : env.PO_CF_INSTALL_ID && `po-${env.PO_CF_INSTALL_ID}`;
65
+ if (destination) process.stdout.write(`Target: ${provider} ${JSON.stringify(destination)}\n`);
66
+ const alchemy = join(dirname(require.resolve('alchemy')), '../bin/cli.js');
67
+ const command = flag === '--plan' ? 'plan' : 'deploy';
68
+ const options = flag === '--yes' ? ['--yes', '--no-input'] : flag === '--plan' ? ['--no-input'] : [];
69
+ const child = spawnSync(process.execPath, [alchemy, command, '--config', stack, '--stage', 'po', ...options], {
70
+ cwd: state,
71
+ env,
72
+ stdio: 'inherit',
73
+ });
74
+ if (child.error) throw child.error;
75
+ return child.status ?? 1;
76
+ }
77
+
78
+ try {
79
+ process.exitCode = run(process.argv.slice(2), process.env, process.cwd());
80
+ } catch (error) {
81
+ process.stderr.write(`${error instanceof Error ? error.message : 'Deployment failed.'}\n`);
82
+ process.exitCode = 1;
83
+ }