Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Delete committed copies of the microvm agent, Fly templates, and shared helpers (#2430)

Regan Bell8e3a1bd885da
diff --git a/aws/microvm-agent/Dockerfile b/aws/microvm-agent/Dockerfile
deleted file mode 100644
index c281424c4..000000000
--- a/aws/microvm-agent/Dockerfile
+++ /dev/null
@@ -1,50 +0,0 @@
-FROM public.ecr.aws/lambda/microvms:al2023-minimal@sha256:05cb9b38d841e7ff1b693dc9e894909612f340bf99ec97d426e8000a5bbe96c3
-
-RUN dnf install -y \
- curl-minimal findutils tar git wget jq unzip \
- python3 python3-pip nodejs24 nodejs24-npm \
- && dnf clean all \
- && rpm -q openssl-snapsafe-libs \
- && curl --version \
- && node --version \
- && npm --version \
- && npx --version \
- && setsid --version \
- && seq 1 1
-
-RUN GH_VERSION=2.97.0 \
- && GH_SHA256=73ea440ecad9c9e284429997ee6f93577bc6f7bc6fba357ef62c53ad8fb641a5 \
- && curl -fsSL "https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_arm64.tar.gz" -o /tmp/gh.tgz \
- && echo "${GH_SHA256} /tmp/gh.tgz" | sha256sum -c - \
- && tar -xzf /tmp/gh.tgz -C /usr/local/bin --strip-components=2 "gh_${GH_VERSION}_linux_arm64/bin/gh" \
- && rm /tmp/gh.tgz \
- && gh --version
-
-RUN curl -fsSL "https://awscli.amazonaws.com/awscli-exe-linux-aarch64-2.36.5.zip" -o /tmp/awscliv2.zip \
- && echo "2662774cf3e70e2203ca1e6b85b84ff8438f6638523ea9d474f9731472740d85 /tmp/awscliv2.zip" | sha256sum -c - \
- && unzip -q /tmp/awscliv2.zip -d /tmp \
- && /tmp/aws/install \
- && rm -rf /tmp/aws /tmp/awscliv2.zip \
- && aws --version
-
-RUN ARCH="$(uname -m)" && case "$ARCH" in \
- x86_64) LS_ARCH=amd64; LS_SHA=eb75a3de5cab03875cdae9f5f539e6aedadd66607003d9b1e7a9077948818ba0 ;; \
- aarch64) LS_ARCH=arm64; LS_SHA=9585f5a508516bd66af2b2376bab4de256a5ef8e2b73ec760559e679628f2d59 ;; \
- *) echo "unsupported arch $ARCH" && exit 1 ;; esac \
- && curl -fsSL "https://github.com/benbjohnson/litestream/releases/download/v0.3.13/litestream-v0.3.13-linux-${LS_ARCH}.tar.gz" -o /tmp/litestream.tgz \
- && echo "${LS_SHA} /tmp/litestream.tgz" | sha256sum -c - \
- && tar -xzf /tmp/litestream.tgz -C /usr/local/bin litestream \
- && rm /tmp/litestream.tgz \
- && litestream version
-
-RUN python3 -m venv /opt/agent-venv \
- && /opt/agent-venv/bin/pip install --no-cache-dir --upgrade pip
-ENV PATH="/opt/agent-venv/bin:${PATH}"
-ENV VIRTUAL_ENV=/opt/agent-venv
-
-COPY agent.mjs /opt/microvm-agent/agent.mjs
-
-ENV HOME=/root
-WORKDIR /root
-
-CMD ["node", "/opt/microvm-agent/agent.mjs"]
diff --git a/aws/microvm-agent/agent.mjs b/aws/microvm-agent/agent.mjs
deleted file mode 100644
index a084f365c..000000000
--- a/aws/microvm-agent/agent.mjs
+++ /dev/null
@@ -1,91 +0,0 @@
-import http from "node:http";
-import { execFile } from "node:child_process";
-import fs from "node:fs";
-import path from "node:path";
-
-const PORT = Number(process.env.AGENT_PORT || 8080);
-const MAX_BUFFER = 256 * 1024 * 1024;
-const START_MS = Date.now();
-
-function readBody(req, cap = MAX_BUFFER) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- let size = 0;
- req.on("data", (c) => {
- size += c.length;
- if (size > cap) {
- reject(new Error("request body too large"));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on("end", () => resolve(Buffer.concat(chunks)));
- req.on("error", reject);
- });
-}
-
-function send(res, code, obj) {
- const body = Buffer.from(JSON.stringify(obj));
- res.writeHead(code, { "Content-Type": "application/json", "Content-Length": body.length });
- res.end(body);
-}
-
-async function handleExec(req, res) {
- const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
- const cmd = body.cmd;
- if (typeof cmd !== "string") return send(res, 400, { error: "missing cmd" });
- const timeoutMs = Math.max(1, Number(body.timeoutSec || 60)) * 1000;
- execFile(
- "/bin/sh",
- ["-c", cmd],
- { timeout: timeoutMs, maxBuffer: MAX_BUFFER, killSignal: "SIGKILL" },
- (err, stdout, stderr) => {
- const timedOut = !!(err && err.killed && err.signal === "SIGKILL");
- let code = 0;
- if (timedOut) code = 124;
- else if (err) code = typeof err.code === "number" ? err.code : 1;
- send(res, 200, { stdout: String(stdout), stderr: String(stderr), code, timedOut });
- },
- );
-}
-
-async function handleWrite(req, res) {
- const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
- if (typeof body.path !== "string" || typeof body.b64 !== "string")
- return send(res, 400, { error: "need path + b64" });
- fs.mkdirSync(path.dirname(body.path), { recursive: true });
- fs.writeFileSync(body.path, Buffer.from(body.b64, "base64"));
- send(res, 200, { ok: true });
-}
-
-async function handleRead(req, res) {
- const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
- if (typeof body.path !== "string") return send(res, 400, { error: "need path" });
- let buf;
- try {
- buf = fs.readFileSync(body.path);
- } catch {
- return send(res, 404, { error: "not found" });
- }
- send(res, 200, { b64: buf.toString("base64") });
-}
-
-const server = http.createServer((req, res) => {
- const route = (req.url || "").split("?")[0];
- (async () => {
- if (route === "/health")
- return send(res, 200, {
- ok: true,
- pid: process.pid,
- startMs: START_MS,
- uptimeSec: Math.round((Date.now() - START_MS) / 1000),
- });
- if (req.method === "POST" && route === "/exec") return handleExec(req, res);
- if (req.method === "POST" && route === "/write") return handleWrite(req, res);
- if (req.method === "POST" && route === "/read") return handleRead(req, res);
- return send(res, 404, { error: "not found", route });
- })().catch((e) => send(res, 500, { error: String((e && e.message) || e) }));
-});
-
-server.listen(PORT, "0.0.0.0", () => console.log(`[microvm-agent] exec daemon listening on ${PORT}`));
diff --git a/cli/src/backends/aws.ts b/cli/src/backends/aws.ts
index 5c9d975ea..86334e10e 100644
--- a/cli/src/backends/aws.ts
+++ b/cli/src/backends/aws.ts
@@ -56,8 +56,8 @@ import {
type ServiceName,
} from "../services.ts";
import { discoverPlugins, type ResolvedPlugin } from "../plugins.ts";
+import { canonicalJson } from "../canonical-json.ts";
import {
- canonicalJson,
capture,
deploymentSecretValue,
envNum,
diff --git a/cli/src/backends/fly.ts b/cli/src/backends/fly.ts
index 8bddd5dbd..1222d212c 100644
--- a/cli/src/backends/fly.ts
+++ b/cli/src/backends/fly.ts
@@ -190,7 +190,6 @@ export interface FlyUpOpts {
interface FlyCtx {
config: QmConfig;
- templateRoot: string;
generatedRoot: string;
commandCwd: string;
sourceRoot?: string;
@@ -335,8 +334,7 @@ const flyOwnershipMarker = (flyOrg: string, orgId: string, appPrefix: string): s
function deriveToml(ctx: FlyCtx, service: ServiceName): string {
const spec = serviceDef(service).fly!;
- const nested = join(ctx.templateRoot, service, "fly.toml");
- const base = readFileSync(existsSync(nested) ? nested : join(ctx.templateRoot, `${service}.toml`), "utf8");
+ const base = readFileSync(join(flyTemplateRoot(), `${service}.toml`), "utf8");
const sandboxEnv = service === "core" ? sandboxCoreEnv(ctx.config).env : {};
const virtualEnv = service === "core" ? virtualServiceEnv(ctx.config.services, ctx.config.env) : {};
const modelEnv: Record<string, string> =
@@ -429,7 +427,6 @@ export function derivedTomlFor(config: QmConfig, service: ServiceName, repoRoot:
const deployAppPrefix = config.deployAppPrefix ?? `${appPrefix}-d`;
const ctx: FlyCtx = {
config,
- templateRoot: join(repoRoot, "deploy"),
generatedRoot: join(repoRoot, "deploy", "stacks", ".generated"),
commandCwd: repoRoot,
sourceRoot: repoRoot,
@@ -790,7 +787,6 @@ function sourceRootFor(configDir: string, explicit?: string): string | undefined
const root = resolve(explicit);
return existsSync(join(root, "package.json")) &&
existsSync(join(root, "src", "index.ts")) &&
- existsSync(join(root, "deploy", "core", "fly.toml")) &&
existsSync(join(root, "deploy", "core", "Dockerfile"))
? root
: undefined;
@@ -808,12 +804,11 @@ function sourceRootFor(configDir: string, explicit?: string): string | undefined
(root) =>
existsSync(join(root, "package.json")) &&
existsSync(join(root, "src", "index.ts")) &&
- existsSync(join(root, "deploy", "core", "fly.toml")) &&
existsSync(join(root, "deploy", "core", "Dockerfile")),
);
}
-function packagedFlyTemplateRoot(): string {
+function flyTemplateRoot(): string {
const source = fileURLToPath(new URL("../../templates/fly", import.meta.url));
if (existsSync(source)) return source;
return fileURLToPath(new URL("../../../templates/fly", import.meta.url));
@@ -831,7 +826,6 @@ function buildCtx(config: QmConfig, configDir: string, opts: Pick<FlyUpOpts, "bu
const deployAppPrefix = config.deployAppPrefix ?? `${appPrefix}-d`;
return {
config,
- templateRoot: sourceRoot ? join(sourceRoot, "deploy") : packagedFlyTemplateRoot(),
generatedRoot: join(configDir, ".generated", "fly"),
commandCwd: configDir,
...(sourceRoot ? { sourceRoot } : {}),
diff --git a/cli/src/canonical-json.ts b/cli/src/canonical-json.ts
new file mode 100644
index 000000000..9f6a5ac32
--- /dev/null
+++ b/cli/src/canonical-json.ts
@@ -0,0 +1,13 @@
+export function canonicalJson(value: unknown): string {
+ if (value === undefined) return "";
+ return JSON.stringify(value, (_k, v) => {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return v;
+ return Object.fromEntries(
+ Object.entries(v as Record<string, unknown>).sort(([a], [b]) => {
+ if (a < b) return -1;
+ if (a > b) return 1;
+ return 0;
+ }),
+ );
+ });
+}
diff --git a/cli/src/commands/conformance.ts b/cli/src/commands/conformance.ts
index aa53797d5..bed27bc59 100644
--- a/cli/src/commands/conformance.ts
+++ b/cli/src/commands/conformance.ts
@@ -3,7 +3,7 @@ import { type Target, type QmConfig } from "../config.ts";
import { deploymentLayerBundle, deploymentLayerRequest, type DeploymentLayerBundle } from "../deployment-layer.ts";
import { CliError, errMessage, header, ok, step } from "../log.ts";
import { parseToolDescriptor, type ToolDescriptor } from "../tool-descriptor.ts";
-import { canonicalJson } from "../util.ts";
+import { canonicalJson } from "../canonical-json.ts";
import { runChecks } from "./check.ts";
import { hostingProvider } from "../backends/registry.ts";
diff --git a/cli/src/contract.d.ts b/cli/src/contract.d.ts
deleted file mode 100644
index ea5be6ee0..000000000
--- a/cli/src/contract.d.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-export { loadConfigAt, sandboxCoreEnv, securityScreenEnv, CONTRACT_VERSION as contractVersion } from "./config.ts";
-export { orgEnv } from "./services.ts";
-export { compileApproval } from "./tool-descriptor.ts";
-export { parseSkillFrontmatter, validateSandboxLayer } from "./sandbox-layer.ts";
-export { renderTaskDefinition } from "./backends/aws.ts";
-export { HOSTING_PROVIDER_IDS, hostingProviderChoices, isTarget } from "./providers.ts";
-export type {
- AwsConfig,
- AwsServiceConfig,
- PluginEntry,
- SandboxConfig,
- SecurityScreenConfig,
- Target,
- QmConfig,
-} from "./config.ts";
-export type { SandboxValidation, SkillFrontmatter } from "./sandbox-layer.ts";
-export type {
- ApprovalDecision,
- ToolApproval,
- ToolAuthDescriptor,
- ToolCredentialPath,
- ToolDescriptor,
-} from "./tool-descriptor.ts";
diff --git a/cli/src/terraform.ts b/cli/src/terraform.ts
index 98525ed10..e4dc2b8e4 100644
--- a/cli/src/terraform.ts
+++ b/cli/src/terraform.ts
@@ -6,7 +6,7 @@ import { awsWorkloadArchitecture, type QmConfig } from "./config.ts";
import { CliError, ok } from "./log.ts";
import { computedSecrets } from "./secrets.ts";
import { isServiceName, serviceDef } from "./services.ts";
-import { canonicalJson } from "./util.ts";
+import { canonicalJson } from "./canonical-json.ts";
const DERIVED_VARS = new Set([
"org_id",
diff --git a/cli/src/util.ts b/cli/src/util.ts
index 5056d06b0..b42ad311d 100644
--- a/cli/src/util.ts
+++ b/cli/src/util.ts
@@ -235,18 +235,6 @@ export function waitForLog(file: string, pattern: RegExp, timeoutSec: number): P
export const tailString = (s: string, lines: number): string => s.split("\n").slice(-lines).join("\n");
-export function canonicalJson(value: unknown): string {
- if (Array.isArray(value))
- return `[${value.map((element) => (element === undefined ? "null" : canonicalJson(element))).join(",")}]`;
- if (typeof value !== "object" || value === null) return JSON.stringify(value);
- const object = value as Record<string, unknown>;
- return `{${Object.keys(object)
- .filter((key) => object[key] !== undefined)
- .sort()
- .map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`)
- .join(",")}}`;
-}
-
export function tail(file: string, lines = 20): string {
if (!existsSync(file)) return "";
return tailString(readFileSync(file, "utf8"), lines);
diff --git a/cli/templates/fly/core.toml b/cli/templates/fly/core.toml
index d4039d642..838282cbc 100644
--- a/cli/templates/fly/core.toml
+++ b/cli/templates/fly/core.toml
@@ -19,6 +19,8 @@ primary_region = "sjc"
REQUIRE_SIGNED_PORTAL_IDENTITY = "1"
FLY_ORG = "personal"
FLY_DEPLOY_APP_PREFIX = "qm-d"
+ SANDBOX_BACKEND = "sprites"
+ SECURITY_SCREEN = "off"
[deploy]
strategy = "bluegreen"
diff --git a/cli/test/auth-broker.test.ts b/cli/test/auth-broker.test.ts
index d4f9bb900..43f37acec 100644
--- a/cli/test/auth-broker.test.ts
+++ b/cli/test/auth-broker.test.ts
@@ -71,7 +71,7 @@ test("fly derives the portal's whole OIDC block from the broker, over the privat
assert.match(core, /AUTH_ALLOWED_EMAIL_DOMAIN = "example\.com"/, "core refuses in-domain external invites");
const auth = derivedTomlFor(brokerConfig(), "auth", repoRoot);
- assert.equal(auth, readFileSync(join(repoRoot, "deploy", "auth", "fly.toml"), "utf8"));
+ assert.equal(auth, readFileSync(join(repoRoot, "cli", "templates", "fly", "auth.toml"), "utf8"));
assert.match(auth, /AUTH_ISSUER = "https:\/\/agent\.example\.com\/idp"/);
assert.match(auth, /AUTH_REDIRECT_URI = "https:\/\/agent\.example\.com\/auth\/callback"/);
});
diff --git a/cli/test/contract.test.ts b/cli/test/contract.test.ts
deleted file mode 100644
index 01dfb0e50..000000000
--- a/cli/test/contract.test.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import * as contract from "../src/contract.ts";
-
-test("contract.d.ts declares exactly the value exports contract.ts provides at runtime", () => {
- const dts = readFileSync(new URL("../src/contract.d.ts", import.meta.url), "utf8");
- const declared = new Set<string>();
- for (const clause of dts.matchAll(/export\s+(type\s+)?\{([^}]*)\}/g)) {
- if (clause[1]) continue;
- for (const item of clause[2]!.split(",")) {
- const name = item.trim();
- if (!name || name.startsWith("type ")) continue;
- declared.add(name.includes(" as ") ? name.split(" as ").pop()!.trim() : name);
- }
- }
- const runtime = Object.keys(contract).sort();
- assert.deepEqual([...declared].sort(), runtime, "contract.d.ts value exports must match contract.ts runtime exports");
-});
diff --git a/cli/test/fly-derive.test.ts b/cli/test/fly-derive.test.ts
index 7ddee76e6..6236a39e0 100644
--- a/cli/test/fly-derive.test.ts
+++ b/cli/test/fly-derive.test.ts
@@ -9,12 +9,12 @@ import { orgEnv, runnableServices } from "../src/services.ts";
const repoRoot = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
-test("acme fly config derives the checked-in deploy/<svc>/fly.toml byte-for-byte", () => {
+test("acme fly config derives the packaged cli/templates/fly/<svc>.toml byte-for-byte", () => {
const { config } = loadConfigAt(join(repoRoot, "deploy", "stacks", "acme", "qm.config.jsonc"));
for (const svc of runnableServices(config.services)) {
const derived = derivedTomlFor(config, svc, repoRoot);
- const checkedIn = readFileSync(join(repoRoot, "deploy", svc, "fly.toml"), "utf8");
- assert.equal(derived, checkedIn, `derived ${svc} fly.toml diverged from deploy/${svc}/fly.toml`);
+ const template = readFileSync(join(repoRoot, "cli", "templates", "fly", `${svc}.toml`), "utf8");
+ assert.equal(derived, template, `derived ${svc} fly.toml diverged from cli/templates/fly/${svc}.toml`);
}
});
@@ -147,7 +147,7 @@ test("a vms override rewrites the core [[vm]] size/memory without touching other
assert.doesNotMatch(coreToml, /size = "shared-cpu-1x"/);
assert.doesNotMatch(coreToml, /memory = "2gb"/);
const adminToml = derivedTomlFor(config, "admin", repoRoot);
- const adminVm = readFileSync(join(repoRoot, "deploy", "admin", "fly.toml"), "utf8").match(
+ const adminVm = readFileSync(join(repoRoot, "cli", "templates", "fly", "admin.toml"), "utf8").match(
/\[\[vm\]\][\s\S]*?(?=\n\[|\n\n|$)/,
);
if (adminVm) assert.ok(adminToml.includes(adminVm[0]), "admin [[vm]] block changed despite no vms override");
diff --git a/cli/test/microvm-dockerfile.test.ts b/cli/test/microvm-dockerfile.test.ts
index a9119c278..fed648a66 100644
--- a/cli/test/microvm-dockerfile.test.ts
+++ b/cli/test/microvm-dockerfile.test.ts
@@ -2,14 +2,8 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
-test("the canonical and packaged MicroVM Dockerfiles stay snapshot-safe and executable", () => {
- const canonical = readFileSync(new URL("../../aws/microvm-agent/Dockerfile", import.meta.url), "utf8");
- const packaged = readFileSync(new URL("../templates/aws/microvm-agent/Dockerfile", import.meta.url), "utf8");
- assert.equal(packaged, canonical);
- assert.equal(
- readFileSync(new URL("../templates/aws/microvm-agent/agent.mjs", import.meta.url), "utf8"),
- readFileSync(new URL("../../aws/microvm-agent/agent.mjs", import.meta.url), "utf8"),
- );
+test("the MicroVM Dockerfile stays snapshot-safe and executable", () => {
+ const canonical = readFileSync(new URL("../templates/aws/microvm-agent/Dockerfile", import.meta.url), "utf8");
assert.match(canonical, /^FROM public\.ecr\.aws\/lambda\/microvms:al2023-minimal@sha256:[a-f0-9]{64}$/m);
assert.match(canonical, /dnf install -y[\s\\]+curl-minimal\b/);
assert.doesNotMatch(canonical, /cli\.github\.com\/packages\/rpm/);
diff --git a/cli/test/scope-storage-key.test.ts b/cli/test/scope-storage-key.test.ts
new file mode 100644
index 000000000..cdd009c0e
--- /dev/null
+++ b/cli/test/scope-storage-key.test.ts
@@ -0,0 +1,10 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { scopeStorageKey } from "../src/scope-storage-key.ts";
+
+test("scope storage keys keep their persisted format", () => {
+ assert.equal(scopeStorageKey("personal:U123"), "personal__U123");
+ assert.equal(scopeStorageKey("channel:team/engineering"), "channel__team__engineering--e0d6b9a2c732");
+ assert.equal(scopeStorageKey("personal:[email protected]"), "personal__josh__example.com--10a055c43ea3");
+ assert.equal(scopeStorageKey("personal:λ"), "personal____--4bff5926cebf");
+});
diff --git a/cli/test/secrets.test.ts b/cli/test/secrets.test.ts
index 0dddcffca..969eef39e 100644
--- a/cli/test/secrets.test.ts
+++ b/cli/test/secrets.test.ts
@@ -253,19 +253,17 @@ test("real harnesses require and route the sandbox-reachable PUBLIC_API_URL to c
);
});
-test("FLY_TEMPLATE_ENV_DEFAULTS stays in sync with deploy/core/fly.toml", () => {
+test("FLY_TEMPLATE_ENV_DEFAULTS stays in sync with the packaged core fly template", () => {
const root = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
- const toml = readFileSync(join(root, "deploy", "core", "fly.toml"), "utf8");
- const packaged = readFileSync(join(root, "cli", "templates", "fly", "core.toml"), "utf8");
+ const toml = readFileSync(join(root, "cli", "templates", "fly", "core.toml"), "utf8");
for (const [name, value] of Object.entries(FLY_TEMPLATE_ENV_DEFAULTS.core ?? {})) {
assert.match(
toml,
new RegExp(`^\\s*${name}\\s*=\\s*"${value}"`, "m"),
- `deploy/core/fly.toml sets ${name}="${value}"`,
+ `cli/templates/fly/core.toml sets ${name}="${value}"`,
);
}
assert.doesNotMatch(toml, /^\s*DEPLOY_PROVIDER\s*=/m);
- assert.doesNotMatch(packaged, /^\s*DEPLOY_PROVIDER\s*=/m);
});
test("config secretEnv extras enter the computed set as required operator secrets, virtual services folding onto core", () => {
diff --git a/cli/test/util.test.ts b/cli/test/util.test.ts
index e69b87337..2b8137e40 100644
--- a/cli/test/util.test.ts
+++ b/cli/test/util.test.ts
@@ -3,15 +3,8 @@ import assert from "node:assert/strict";
import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import {
- canonicalJson,
- capture,
- runInheritAsync,
- flyBin,
- isInvalidSecret,
- readEnvFile,
- writeEnvValue,
-} from "../src/util.ts";
+import { canonicalJson } from "../src/canonical-json.ts";
+import { capture, runInheritAsync, flyBin, isInvalidSecret, readEnvFile, writeEnvValue } from "../src/util.ts";
test("capture accepts CLI output larger than Node's one-megabyte default", () => {
const output = capture(process.execPath, ["-e", 'process.stdout.write("x".repeat(2 * 1024 * 1024))']);
@@ -52,6 +45,16 @@ test("canonicalJson sorts keys and matches JSON.stringify's undefined semantics"
for (const value of [null, 0, "s", true, [], {}]) {
assert.equal(canonicalJson(value), JSON.stringify(value));
}
+ assert.equal(canonicalJson(undefined), "");
+ assert.equal(canonicalJson({ b: new Date(0), a: 1 }), '{"a":1,"b":"1970-01-01T00:00:00.000Z"}');
+});
+
+test("readEnvFile keeps everything after the first '=' verbatim and skips bad keys", (t) => {
+ const dir = mkdtempSync(join(tmpdir(), "qm-env-"));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const file = join(dir, "x.env");
+ writeFileSync(file, "GOOD=a=b=c\n1BAD=x\n# comment\nEMPTY=\n");
+ assert.deepEqual(Object.fromEntries(readEnvFile(file)), { GOOD: "a=b=c", EMPTY: "" });
});
test("readEnvFile preserves hashes in unquoted values", (t) => {
diff --git a/deploy/README.md b/deploy/README.md
index 9430dfe78..ff8d53378 100644
--- a/deploy/README.md
+++ b/deploy/README.md
@@ -51,7 +51,7 @@ the authenticated admin connector URL returned by `qm outputs`. Secrets are
encrypted in durable storage and are never committed to a deployment directory.
The agent advertises only connectors whose admin configuration is enabled.
-`deploy/auth/fly.toml` declares an `[http_service]` like every other surface, but the
+`cli/templates/fly/auth.toml` declares an `[http_service]` like every other surface, but the
CLI always deploys it `--flycast --no-public-ips`; on AWS the ALB assertions refuse to
attach it to a load balancer. Never `fly launch` that file by hand — a broker with a
public IP exposes its token endpoint and lets a caller forge the rate-limit client
@@ -60,6 +60,6 @@ address.
## Fixtures
[`stacks/`](./stacks/) contains account-neutral contract fixtures. The checked-in
-`deploy/<service>/fly.toml` files are templates from which the CLI derives
+`cli/templates/fly/<service>.toml` files are templates from which the CLI derives
deployment-specific copies under the ignored `deploy/stacks/.generated/`
directory.
diff --git a/deploy/admin/fly.toml b/deploy/admin/fly.toml
deleted file mode 100644
index e549a680b..000000000
--- a/deploy/admin/fly.toml
+++ /dev/null
@@ -1,26 +0,0 @@
-app = "qm-admin"
-primary_region = "sjc"
-
-[env]
- QM_DEPLOYMENT_ID = "qm-v2:personal:acme:qm"
- PORT = "8080"
- CORE_API_URL = "http://qm-core.internal:8080"
- CORE_ORG_ID = "acme"
- ADMIN_BASE_PATH = "/admin"
-
-[[vm]]
- size = "shared-cpu-1x"
- memory = "2gb"
-
-kill_signal = "SIGTERM"
-kill_timeout = "10s"
-
-[checks]
- [checks.health]
- type = "http"
- port = 8080
- method = "get"
- path = "/healthz"
- interval = "15s"
- timeout = "2s"
- grace_period = "10s"
diff --git a/deploy/auth/fly.toml b/deploy/auth/fly.toml
deleted file mode 100644
index a7e167bb8..000000000
--- a/deploy/auth/fly.toml
+++ /dev/null
@@ -1,43 +0,0 @@
-app = "qm-auth"
-primary_region = "sjc"
-
-[env]
- QM_DEPLOYMENT_ID = "qm-v2:personal:acme:qm"
- PORT = "8080"
- CORE_API_URL = "http://qm-core.internal:8080"
- CORE_ORG_ID = "acme"
- AUTH_ISSUER = "https://agent.example.com/idp"
- AUTH_CLIENT_ID = "qm-portal"
- AUTH_REDIRECT_URI = "https://agent.example.com/auth/callback"
- AUTH_EMAIL_TRANSPORT = "resend"
- AUTH_ALLOWED_EMAIL_DOMAIN = "example.com"
- AUTH_BRAND_NAME = "Acme"
-
-[http_service]
- internal_port = 8080
- force_https = false
- auto_stop_machines = false
- auto_start_machines = true
- min_machines_running = 1
-
- [http_service.concurrency]
- type = "requests"
- soft_limit = 100
- hard_limit = 150
-
-[[vm]]
- size = "shared-cpu-1x"
- memory = "512mb"
-
-kill_signal = "SIGTERM"
-kill_timeout = "10s"
-
-[checks]
- [checks.health]
- type = "http"
- port = 8080
- method = "get"
- path = "/healthz"
- interval = "15s"
- timeout = "2s"
- grace_period = "10s"
diff --git a/deploy/core/Dockerfile b/deploy/core/Dockerfile
index 8c8098051..d35660561 100644
--- a/deploy/core/Dockerfile
+++ b/deploy/core/Dockerfile
@@ -24,7 +24,7 @@ RUN npm ci --omit=dev && npm run audit:prod \
COPY --from=connector-sdk-build /app/.generated/connector-sdk ./.generated/connector-sdk
COPY src ./src
-COPY cli/src/credential-paths.ts cli/src/tool-descriptor.ts ./cli/src/
+COPY cli/src/canonical-json.ts cli/src/credential-paths.ts cli/src/scope-storage-key.ts cli/src/tool-descriptor.ts ./cli/src/
COPY cli/templates/slack-manifest.json ./cli/templates/slack-manifest.json
COPY skills-seed ./skills-seed
COPY plugins/onboarding ./plugins/onboarding
diff --git a/deploy/core/fly.toml b/deploy/core/fly.toml
deleted file mode 100644
index 838282cbc..000000000
--- a/deploy/core/fly.toml
+++ /dev/null
@@ -1,45 +0,0 @@
-app = "qm-core"
-primary_region = "sjc"
-
-[env]
- QM_DEPLOYMENT_ID = "qm-v2:personal:acme:qm"
- PORT = "8080"
- ORG_ID = "acme"
- HARNESS = "pi"
- PI_SYSTEM_CACHE_SPLIT = "1"
- SESSION_STORE = "postgres"
- RUN_STORE = "postgres"
- SNAPSHOT_STORE = "s3"
- TRANSFER_STORE = "s3"
- S3_BUCKET = "acme-data"
- S3_REGION = "auto"
- DATA_DIR = "/data"
- PUBLIC_WEB_URL = "https://agent.example.com"
- WEB_UI_PUBLIC_URL = "https://agent.example.com"
- REQUIRE_SIGNED_PORTAL_IDENTITY = "1"
- FLY_ORG = "personal"
- FLY_DEPLOY_APP_PREFIX = "qm-d"
- SANDBOX_BACKEND = "sprites"
- SECURITY_SCREEN = "off"
-[deploy]
- strategy = "bluegreen"
-
-[[restart]]
- policy = "always"
-
-[[vm]]
- size = "performance-2x"
- memory = "4gb"
-
-kill_signal = "SIGTERM"
-kill_timeout = "300s"
-
-[checks]
- [checks.health]
- type = "http"
- port = 8080
- method = "get"
- path = "/healthz"
- interval = "15s"
- timeout = "2s"
- grace_period = "20s"
diff --git a/deploy/egress-proxy/Dockerfile b/deploy/egress-proxy/Dockerfile
index 47a55440f..86f9aa263 100644
--- a/deploy/egress-proxy/Dockerfile
+++ b/deploy/egress-proxy/Dockerfile
@@ -12,7 +12,7 @@ COPY .husky/install.mjs .husky/install.mjs
RUN npm ci --omit=dev
COPY src ./src
-COPY cli/src/credential-paths.ts cli/src/tool-descriptor.ts ./cli/src/
+COPY cli/src/canonical-json.ts cli/src/credential-paths.ts cli/src/scope-storage-key.ts cli/src/tool-descriptor.ts ./cli/src/
COPY plugins/chassis ./plugins/chassis
COPY tsconfig.json ./
RUN node --input-type=module -e "await import('./src/egress-authz-main.ts')"
diff --git a/deploy/portal/fly.toml b/deploy/portal/fly.toml
deleted file mode 100644
index 75a4be8a9..000000000
--- a/deploy/portal/fly.toml
+++ /dev/null
@@ -1,57 +0,0 @@
-app = "qm-portal"
-primary_region = "sjc"
-
-[env]
- QM_DEPLOYMENT_ID = "qm-v2:personal:acme:qm"
- PORT = "8080"
- CORE_API_URL = "http://qm-core.internal:8080"
- CORE_ORG_ID = "acme"
- PORTAL_PUBLIC_URL = "https://agent.example.com"
- WEB_UI_UPSTREAM = "http://qm-web-ui.flycast"
- ADMIN_UPSTREAM = "http://qm-web-ui.flycast/admin"
- OIDC_AUTH_ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth"
- OIDC_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
- OIDC_USERINFO_ENDPOINT = "https://openidconnect.googleapis.com/v1/userinfo"
- OIDC_ISSUER = "https://accounts.google.com"
- OIDC_JWKS_URI = "https://www.googleapis.com/oauth2/v3/certs"
- OIDC_SCOPES = "openid email profile"
- OIDC_PRINCIPAL_CLAIM = "email"
- OIDC_ALLOWED_EMAIL_DOMAIN = "example.com"
-
-[http_service]
- internal_port = 8080
- force_https = true
- auto_stop_machines = false
- auto_start_machines = true
- min_machines_running = 1
-
- [[http_service.ports]]
- port = 80
- handlers = ["http"]
- force_https = true
-
- [[http_service.ports]]
- port = 443
- handlers = ["tls", "http"]
-
- [http_service.concurrency]
- type = "requests"
- soft_limit = 200
- hard_limit = 250
-
-[[vm]]
- size = "shared-cpu-1x"
- memory = "1gb"
-
-kill_signal = "SIGTERM"
-kill_timeout = "10s"
-
-[checks]
- [checks.health]
- type = "http"
- port = 8080
- method = "get"
- path = "/healthz"
- interval = "15s"
- timeout = "2s"
- grace_period = "10s"
diff --git a/deploy/stacks/README.md b/deploy/stacks/README.md
index 6c8f8c877..720693c06 100644
--- a/deploy/stacks/README.md
+++ b/deploy/stacks/README.md
@@ -9,7 +9,7 @@ under [`../layers/`](../layers/), asks for the operator's Fly organization or AW
account before mutation, and generates the optional bot manifest. It generates a
separate Slack SSO manifest only when Slack is selected as the OIDC provider.
-The checked-in `deploy/<service>/fly.toml` files remain the service templates.
+The packaged `cli/templates/fly/<service>.toml` files are the service templates.
The CLI derives per-deployment copies under the ignored
`deploy/stacks/.generated/` directory. Secrets belong in the provider's encrypted
secret store and never in these fixtures.
diff --git a/deploy/stacks/acme/slack-app-manifest.yml b/deploy/stacks/acme/slack-app-manifest.yml
deleted file mode 100644
index 428d411b6..000000000
--- a/deploy/stacks/acme/slack-app-manifest.yml
+++ /dev/null
@@ -1,54 +0,0 @@
-display_information:
- name: qm
- description: QM workspace agent
- background_color: "#1f2937"
-features:
- app_home:
- home_tab_enabled: false
- messages_tab_enabled: true
- messages_tab_read_only_enabled: false
- bot_user:
- display_name: qm
- always_online: true
-oauth_config:
- scopes:
- bot:
- - app_mentions:read
- - chat:write
- - chat:write.customize
- - im:history
- - im:read
- - im:write
- - users:read
- - users:read.email
- - channels:read
- - channels:history
- - channels:manage
- - groups:read
- - groups:history
- - groups:write
- - mpim:read
- - mpim:write
- - mpim:history
- - files:read
- - files:write
- - reactions:write
- - reactions:read
- - pins:read
- - pins:write
-settings:
- event_subscriptions:
- bot_events:
- - app_mention
- - message.im
- - message.channels
- - message.groups
- - message.mpim
- - member_joined_channel
- - reaction_added
- - reaction_removed
- interactivity:
- is_enabled: true
- org_deploy_enabled: false
- socket_mode_enabled: true
- token_rotation_enabled: false
diff --git a/deploy/web-ui/fly.toml b/deploy/web-ui/fly.toml
deleted file mode 100644
index 73e101279..000000000
--- a/deploy/web-ui/fly.toml
+++ /dev/null
@@ -1,41 +0,0 @@
-app = "qm-web-ui"
-primary_region = "sjc"
-
-[env]
- ADMIN_BASE_PATH = "/admin"
- ADMIN_ENABLED = "1"
- QM_DEPLOYMENT_ID = "qm-v2:personal:acme:qm"
- PORT = "8080"
- CORE_API_URL = "http://qm-core.internal:8080"
- CORE_ORG_ID = "acme"
- WEB_UI_PUBLIC_URL = "https://agent.example.com"
- WEB_UI_PRINCIPALS = ""
-
-[http_service]
- internal_port = 8080
- force_https = false
- auto_stop_machines = "stop"
- auto_start_machines = true
- min_machines_running = 1
-
- [http_service.concurrency]
- type = "requests"
- soft_limit = 200
- hard_limit = 250
-
-[[vm]]
- size = "shared-cpu-1x"
- memory = "2gb"
-
-kill_signal = "SIGTERM"
-kill_timeout = "10s"
-
-[checks]
- [checks.health]
- type = "http"
- port = 8080
- method = "get"
- path = "/healthz"
- interval = "15s"
- timeout = "2s"
- grace_period = "10s"
diff --git a/knip.json b/knip.json
index 7b880f734..f6781a772 100644
--- a/knip.json
+++ b/knip.json
@@ -46,7 +46,7 @@
]
},
"cli": {
- "entry": ["bin/qm.ts"]
+ "entry": ["bin/qm.ts", "src/contract.ts"]
},
"plugins/*": {},
"plugins/web-ui": {
diff --git a/local/Dockerfile b/local/Dockerfile
index b271a52fc..c26c4b4d5 100644
--- a/local/Dockerfile
+++ b/local/Dockerfile
@@ -1,7 +1,7 @@
ARG BASE=qm-sandbox-base:dev
FROM ${BASE}
-COPY aws/microvm-agent/agent.mjs /opt/microvm-agent/agent.mjs
+COPY cli/templates/aws/microvm-agent/agent.mjs /opt/microvm-agent/agent.mjs
ENV HOME=/root
WORKDIR /root
diff --git a/plugins/portal/README.md b/plugins/portal/README.md
index 3bc9def9e..e3fcfd04b 100644
--- a/plugins/portal/README.md
+++ b/plugins/portal/README.md
@@ -293,7 +293,7 @@ npm test
```
See **`deploy/README.md` → Portal** for the public bring-up (IPs + cert, DNS, the Slack OIDC
-app, and secrets) and `deploy/portal/fly.toml`.
+app, and secrets) and `cli/templates/fly/portal.toml`.
With embedded auth, trusted OIDC, and `PORTAL_TRUSTED_OIDC_LABEL` explicitly set,
all email sign-in pages offer a link
diff --git a/scripts/aws-build-sandbox-image.ts b/scripts/aws-build-sandbox-image.ts
index af20f9741..3ae6e8b99 100644
--- a/scripts/aws-build-sandbox-image.ts
+++ b/scripts/aws-build-sandbox-image.ts
@@ -17,7 +17,7 @@ import { sleep } from "../src/util/async.ts";
const execFileAsync = promisify(execFile);
const HERE = dirname(fileURLToPath(import.meta.url));
-const AGENT_DIR = join(HERE, "..", "aws", "microvm-agent");
+const AGENT_DIR = join(HERE, "..", "cli", "templates", "aws", "microvm-agent");
function reqEnv(name: string): string {
const v = process.env[name];
diff --git a/scripts/aws-sandbox-smoke.ts b/scripts/aws-sandbox-smoke.ts
index d7fbe1ee4..c1d07b447 100644
--- a/scripts/aws-sandbox-smoke.ts
+++ b/scripts/aws-sandbox-smoke.ts
@@ -7,6 +7,7 @@ import { createAwsSandbox } from "../src/sandbox/aws-sandbox.ts";
import { createMicrovmApi } from "../src/sandbox/aws-microvm-api.ts";
import { createLocalWorkspaceStore } from "../src/workspace/workspace-store.ts";
import { scopeId } from "../src/types.ts";
+import { scopeStorageKey } from "../cli/src/scope-storage-key.ts";
const region = process.env.AWS_SANDBOX_REGION ?? "us-west-2";
const profile = process.env.AWS_SANDBOX_PROFILE ?? "dev";
@@ -81,7 +82,7 @@ async function main(): Promise<void> {
if (bodyId) await api.terminate(bodyId).catch(() => {});
const { S3Client, DeleteObjectCommand } = await import("@aws-sdk/client-s3");
const s3 = new S3Client({ region, profile });
- const key = `sandbox-smoke/${scope.replace(/[^a-zA-Z0-9_.-]/g, "__")}.tar`;
+ const key = `sandbox-smoke/${scopeStorageKey(scope)}.tar`;
await s3.send(new DeleteObjectCommand({ Bucket: s3Bucket, Key: key })).catch(() => {});
log("done");
}
diff --git a/scripts/dev/lib/envctx.ts b/scripts/dev/lib/envctx.ts
index ffec74cbb..e42230ead 100644
--- a/scripts/dev/lib/envctx.ts
+++ b/scripts/dev/lib/envctx.ts
@@ -2,7 +2,8 @@ import { spawnSync } from "node:child_process";
import { appendFileSync, chmodSync, existsSync } from "node:fs";
import { dirname, join } from "node:path";
import { liveEnvPath } from "./pool.ts";
-import { bestEffort, readEnvFile, sha256Hex } from "./util.ts";
+import { readEnvFile } from "../../../cli/src/util.ts";
+import { bestEffort, sha256Hex } from "./util.ts";
import { run } from "./proc.ts";
import { codexAuthFileForEnv, readCodexOAuthAuthFile } from "../../../src/model/chatgpt-auth-file.ts";
@@ -68,8 +69,8 @@ export function seedEnvFromMain(worktree: string, log: (msg: string) => void): v
const existing = readEnvFile(wtEnvPath);
const main = readEnvFile(mainEnv);
const added: string[] = [];
- for (const [k, v] of Object.entries(main)) {
- if (k in existing) continue;
+ for (const [k, v] of main) {
+ if (existing.has(k)) continue;
appendFileSync(wtEnvPath, `${k}=${v}\n`);
added.push(k);
}
@@ -99,10 +100,10 @@ export async function assembleEnv(opts: {
const warnings: string[] = [];
const liveEnvFile = liveEnvPath();
const env: Record<string, string> = { ...opts.callerEnv };
- for (const [k, v] of Object.entries(readEnvFile(liveEnvFile))) {
+ for (const [k, v] of readEnvFile(liveEnvFile)) {
if (!env[k]) env[k] = v;
}
- const wtEnv = readEnvFile(join(opts.worktree, ".env"));
+ const wtEnv = Object.fromEntries(readEnvFile(join(opts.worktree, ".env")));
let anthropicKeySource = "";
if (opts.callerEnv.ANTHROPIC_API_KEY) anthropicKeySource = "your shell export";
@@ -166,7 +167,7 @@ export async function assembleEnv(opts: {
}
export function envFileGet(path: string, key: string): string {
- return readEnvFile(path)[key] ?? "";
+ return readEnvFile(path).get(key) ?? "";
}
export function callerEnvSnapshot(): Record<string, string> {
diff --git a/scripts/dev/lib/orphans.ts b/scripts/dev/lib/orphans.ts
index 1dc02d3b1..97d2d4773 100644
--- a/scripts/dev/lib/orphans.ts
+++ b/scripts/dev/lib/orphans.ts
@@ -1,5 +1,6 @@
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
+import { readEnvFile } from "../../../cli/src/util.ts";
import { killTree } from "./proc.ts";
function nodePids(): Array<{ pid: number; command: string }> {
@@ -43,12 +44,7 @@ function processCwd(pid: number): string {
}
function envFileToken(cwd: string): string {
- try {
- const match = readFileSync(`${cwd}/.env`, "utf8").match(/^SLACK_APP_TOKEN=(.+)$/m);
- return match?.[1]?.trim() ?? "";
- } catch {
- return "";
- }
+ return readEnvFile(`${cwd}/.env`).get("SLACK_APP_TOKEN") ?? "";
}
export interface OrphanSweepResult {
diff --git a/scripts/dev/lib/pool.ts b/scripts/dev/lib/pool.ts
index 6b263e54a..cc4d9b418 100644
--- a/scripts/dev/lib/pool.ts
+++ b/scripts/dev/lib/pool.ts
@@ -1,7 +1,8 @@
import { mkdirSync, readdirSync, chmodSync, readFileSync, writeFileSync, rmSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
-import { bestEffort, readEnvFile } from "./util.ts";
+import { readEnvFile } from "../../../cli/src/util.ts";
+import { bestEffort } from "./util.ts";
import type { SlotPorts } from "./types.ts";
const CONFIG_HOME = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
@@ -51,7 +52,7 @@ export interface SlotTokens {
}
export function slotTokens(slot: string, store = poolStore()): SlotTokens {
- const env = readEnvFile(join(store, `${slot}.env`));
+ const env = Object.fromEntries(readEnvFile(join(store, `${slot}.env`)));
return {
botToken: env.SLACK_BOT_TOKEN ?? "",
appToken: env.SLACK_APP_TOKEN ?? "",
diff --git a/scripts/dev/lib/util.ts b/scripts/dev/lib/util.ts
index 70b9affd9..39184b96c 100644
--- a/scripts/dev/lib/util.ts
+++ b/scripts/dev/lib/util.ts
@@ -1,5 +1,5 @@
import { createHash } from "node:crypto";
-import { readFileSync, statSync } from "node:fs";
+import { statSync } from "node:fs";
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
@@ -29,41 +29,6 @@ export function fileMtimeEpoch(path: string): number {
}
}
-// Mirrors parseEnvLine in cli/src/util.ts — keep the two in agreement.
-function parseEnvLine(raw: string): [key: string, value: string] | undefined {
- let line = raw.trim();
- if (!line || line.startsWith("#")) return undefined;
- if (line.startsWith("export ")) line = line.slice("export ".length).trimStart();
- const eq = line.indexOf("=");
- if (eq <= 0) return undefined;
- const key = line.slice(0, eq).trim();
- let value = line.slice(eq + 1).trim();
- const quote = value[0];
- if (quote === '"' || quote === "'" || quote === "`") {
- const end = value.indexOf(quote, 1);
- if (end > 0) {
- value = value.slice(1, end);
- if (quote === '"') value = value.replaceAll("\\n", "\n");
- }
- }
- return [key, value];
-}
-
-export function readEnvFile(path: string): Record<string, string> {
- let raw: string;
- try {
- raw = readFileSync(path, "utf8");
- } catch {
- return {};
- }
- const out: Record<string, string> = {};
- for (const line of raw.split("\n")) {
- const entry = parseEnvLine(line);
- if (entry && /^[A-Za-z_][A-Za-z0-9_]*$/.test(entry[0])) out[entry[0]] = entry[1];
- }
- return out;
-}
-
export function sha256Hex(text: string): string {
return createHash("sha256").update(text).digest("hex");
}
diff --git a/scripts/dev/twin-instance.ts b/scripts/dev/twin-instance.ts
index c7fbce872..9b3bf7788 100644
--- a/scripts/dev/twin-instance.ts
+++ b/scripts/dev/twin-instance.ts
@@ -3,7 +3,7 @@ import { spawn, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { provisionTwinEnvironment, teardownTwinEnvironment } from "../../test/live-slack/arga-provision.ts";
-import { readEnvFile } from "./lib/util.ts";
+import { readEnvFile } from "../../cli/src/util.ts";
const root = fileURLToPath(new URL("../..", import.meta.url)).replace(/\/$/, "");
const dir = join(root, ".twin-instance");
@@ -11,7 +11,7 @@ const envFile = join(dir, "env");
const pumpPid = join(dir, "pump.pid");
function loadEnvFile(): Record<string, string> {
- return readEnvFile(envFile);
+ return Object.fromEntries(readEnvFile(envFile));
}
async function up(): Promise<void> {
diff --git a/src/api/routes/loop-items.ts b/src/api/routes/loop-items.ts
index 2df7f3b71..3a45f8bb7 100644
--- a/src/api/routes/loop-items.ts
+++ b/src/api/routes/loop-items.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
import type { Cron, Loop, LoopItem, LoopSourcePayload } from "../../types.ts";
-import { canonicalJson } from "../../util/objects.ts";
+import { canonicalJson } from "../../../cli/src/canonical-json.ts";
import { errMessage } from "../../util/errors.ts";
import { sendJson } from "../http.ts";
import { isObj } from "./shared.ts";
diff --git a/src/deploy/aws-deploy-provider.ts b/src/deploy/aws-deploy-provider.ts
index 3d47d72d8..b9d8b421f 100644
--- a/src/deploy/aws-deploy-provider.ts
+++ b/src/deploy/aws-deploy-provider.ts
@@ -508,7 +508,7 @@ export function createAwsDeployProvider(opts: AwsDeployProviderOptions): DeployP
if (r.code === 24) {
if (fresh) binariesMissingUntilMs = Date.now() + 10 * 60_000;
msg =
- "litestream/aws binaries missing from the MicroVM image — roll AWS_DEPLOY_IMAGE (aws/microvm-agent) before setting AWS_DEPLOY_DATA_ROLE_ARN";
+ "litestream/aws binaries missing from the MicroVM image — roll AWS_DEPLOY_IMAGE (cli/templates/aws/microvm-agent) before setting AWS_DEPLOY_DATA_ROLE_ARN";
}
if (fresh) {
await store.delete(d.id).catch((e) => swallow("aws-deploy: litestream-fail clear pointer", e));
diff --git a/src/loops/item-ledger.ts b/src/loops/item-ledger.ts
index 6cccdc0d6..ef857131b 100644
--- a/src/loops/item-ledger.ts
+++ b/src/loops/item-ledger.ts
@@ -1,5 +1,5 @@
import type { LedgerEvent, LedgerEventOp } from "./ledger-events.ts";
-import { canonicalJson } from "../util/objects.ts";
+import { canonicalJson } from "../../cli/src/canonical-json.ts";
import { wireMentionKeys } from "../slack/mrkdwn.ts";
import type {
LoopItem,
diff --git a/src/loops/loop-store.ts b/src/loops/loop-store.ts
index 79d4d8a90..cc70dac83 100644
--- a/src/loops/loop-store.ts
+++ b/src/loops/loop-store.ts
@@ -9,7 +9,7 @@ import type {
ShipActionPolicy,
} from "../types.ts";
import { createMemoryMap, type DurableMap } from "../persistence/durable-map.ts";
-import { canonicalJson } from "../util/objects.ts";
+import { canonicalJson } from "../../cli/src/canonical-json.ts";
import {
assertNoEscalation,
buildTriggerBase,
diff --git a/src/sandbox/aws-sandbox.ts b/src/sandbox/aws-sandbox.ts
index cb37da0ff..4c5866e19 100644
--- a/src/sandbox/aws-sandbox.ts
+++ b/src/sandbox/aws-sandbox.ts
@@ -6,7 +6,7 @@ import type { WorkspaceStore } from "../workspace/workspace-store.ts";
import { createNoopAdvisoryLock, type AdvisoryLock } from "../persistence/advisory-lock.ts";
import { createMemoryMap, type DurableMap } from "../persistence/durable-map.ts";
import { createKeyedQueue } from "../util/async.ts";
-import { scopeStorageKey } from "../util/scope-storage-key.ts";
+import { scopeStorageKey } from "../../cli/src/scope-storage-key.ts";
import { swallowAs, errMessage } from "../util/errors.ts";
import { shq } from "../util/shell.ts";
import { nonInteractiveShellPrefix } from "./sandbox-env.ts";
diff --git a/src/sandbox/local-sandbox.ts b/src/sandbox/local-sandbox.ts
index e1c215034..2cc044a1b 100644
--- a/src/sandbox/local-sandbox.ts
+++ b/src/sandbox/local-sandbox.ts
@@ -55,7 +55,7 @@ export interface LocalSandboxOptions {
onError?: (e: { category: string; code: string; message: string; scopeLabel?: string }) => void;
}
-const FINGERPRINT_FIXED_SOURCES = ["fly/Dockerfile", "local/Dockerfile", "aws/microvm-agent/agent.mjs"];
+const FINGERPRINT_FIXED_SOURCES = ["fly/Dockerfile", "local/Dockerfile", "cli/templates/aws/microvm-agent/agent.mjs"];
export async function computeSandboxImageFingerprint(repoRoot: string): Promise<string | null> {
try {
diff --git a/src/sessions/session-syscalls.ts b/src/sessions/session-syscalls.ts
index 274b458c9..085a8834b 100644
--- a/src/sessions/session-syscalls.ts
+++ b/src/sessions/session-syscalls.ts
@@ -13,7 +13,7 @@ import { errMessage, swallowAs } from "../util/errors.ts";
import { filterHistoryForAudience } from "../resolution/context-filter.ts";
import { randomUUID } from "node:crypto";
import { hashId } from "../util/crypto.ts";
-import { canonicalJson } from "../util/objects.ts";
+import { canonicalJson } from "../../cli/src/canonical-json.ts";
import type { CoreSearch } from "../search/core-search.ts";
import type { ScopeId, Session, SessionEntry, SpawnMeta } from "../types.ts";
import type { OrchestratorInput } from "../core/orchestrator/types.ts";
diff --git a/src/swarms/swarm-service.ts b/src/swarms/swarm-service.ts
index ff32685e3..a4ce9d07d 100644
--- a/src/swarms/swarm-service.ts
+++ b/src/swarms/swarm-service.ts
@@ -11,7 +11,7 @@ import type { SessionStore } from "../sessions/session-store.ts";
import { conversationScope } from "../resolution/resolution-service.ts";
import { sleep, withTimeout } from "../util/async.ts";
import { createSweeper } from "../util/sweeper.ts";
-import { canonicalJson } from "../util/objects.ts";
+import { canonicalJson } from "../../cli/src/canonical-json.ts";
import { resolveSwarmSettings, type SwarmSettings } from "./swarm-settings.ts";
import { inheritRuntime, spawnRuntime, type SpawnRuntimeFields, type SwarmTemplate } from "./swarm-runtime.ts";
import { errMessage, swallow } from "../util/errors.ts";
diff --git a/src/triggers/trigger-store.ts b/src/triggers/trigger-store.ts
index 4b4f9feda..ccdb26f6a 100644
--- a/src/triggers/trigger-store.ts
+++ b/src/triggers/trigger-store.ts
@@ -1,7 +1,7 @@
import type { Destination, ScopeId, TriggerBase } from "../types.ts";
import type { DurableMap } from "../persistence/durable-map.ts";
import { samePerson } from "../directory/person.ts";
-import { canonicalJson } from "../util/objects.ts";
+import { canonicalJson } from "../../cli/src/canonical-json.ts";
export interface CreateTriggerInput {
ownerScopeId: ScopeId;
diff --git a/src/util/objects.ts b/src/util/objects.ts
index f8468263d..3bcf519f5 100644
--- a/src/util/objects.ts
+++ b/src/util/objects.ts
@@ -1,15 +1 @@
export const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null;
-
-export function canonicalJson(value: unknown): string {
- if (value === undefined) return "";
- return JSON.stringify(value, (_k, v) => {
- if (!v || typeof v !== "object" || Array.isArray(v)) return v;
- return Object.fromEntries(
- Object.entries(v as Record<string, unknown>).sort(([a], [b]) => {
- if (a < b) return -1;
- if (a > b) return 1;
- return 0;
- }),
- );
- });
-}
diff --git a/src/util/scope-storage-key.ts b/src/util/scope-storage-key.ts
deleted file mode 100644
index 9308704b6..000000000
--- a/src/util/scope-storage-key.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { hashId } from "./crypto.ts";
-
-export function scopeStorageKey(scopeId: string): string {
- const legacy = scopeId.replace(/[^a-zA-Z0-9_.-]/g, "__");
- const ref = scopeId.slice(scopeId.indexOf(":") + 1);
- return /^[a-zA-Z0-9_.-]+$/.test(ref) ? legacy : `${legacy}--${hashId([scopeId], 12)}`;
-}
diff --git a/src/workspace/workspace-store.ts b/src/workspace/workspace-store.ts
index 61564eb69..6725baa7b 100644
--- a/src/workspace/workspace-store.ts
+++ b/src/workspace/workspace-store.ts
@@ -1,7 +1,7 @@
import { mkdir, readFile, writeFile, readdir, opendir, rm } from "node:fs/promises";
import { join, resolve, relative, isAbsolute, dirname } from "node:path";
import type { ScopeId } from "../types.ts";
-import { scopeStorageKey } from "../util/scope-storage-key.ts";
+import { scopeStorageKey } from "../../cli/src/scope-storage-key.ts";
export interface WorkspaceStore {
scopeDir(scopeId: ScopeId): string;
diff --git a/test/cli-scope-storage-key.test.ts b/test/cli-scope-storage-key.test.ts
deleted file mode 100644
index 45d08764c..000000000
--- a/test/cli-scope-storage-key.test.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import assert from "node:assert/strict";
-import { test } from "node:test";
-import { scopeStorageKey as cliScopeStorageKey } from "../cli/src/scope-storage-key.ts";
-import { scopeStorageKey as coreScopeStorageKey } from "../src/util/scope-storage-key.ts";
-
-test("the deployment proof command derives the same scope key as core", () => {
- for (const scopeId of [
- "personal:U123",
- "channel:C123",
- "personal:[email protected]",
- "channel:team/engineering",
- "personal:λ",
- ]) {
- assert.equal(cliScopeStorageKey(scopeId), coreScopeStorageKey(scopeId));
- }
-});
diff --git a/test/dev-cli-lib.test.ts b/test/dev-cli-lib.test.ts
index 9afab21c2..feb38034c 100644
--- a/test/dev-cli-lib.test.ts
+++ b/test/dev-cli-lib.test.ts
@@ -7,7 +7,7 @@ import { ensureDeps } from "../scripts/dev/lib/deps.ts";
import { spawnCommand } from "../scripts/dev/lib/proc.ts";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { envSha, errMessage, formatAge, readEnvFile } from "../scripts/dev/lib/util.ts";
+import { envSha, errMessage, formatAge } from "../scripts/dev/lib/util.ts";
import {
clearSlotFlag,
ensureStore,
@@ -485,14 +485,6 @@ test("envSha is order-independent and value-sensitive", () => {
assert.notEqual(envSha({ A: "1" }), envSha({ A: "2" }));
});
-test("readEnvFile keeps everything after the first '=' verbatim and skips bad keys", () => {
- const dir = mkdtempSync(join(tmpdir(), "qm-env-"));
- writeFileSync(join(dir, "x.env"), "GOOD=a=b=c\nHASH=abc#def\n1BAD=x\n# comment\nEMPTY=\n");
- const env = readEnvFile(join(dir, "x.env"));
- assert.deepEqual(env, { GOOD: "a=b=c", HASH: "abc#def", EMPTY: "" });
- rmSync(dir, { recursive: true, force: true });
-});
-
test("leaseOrgId reads the stale lease's booted org", () => {
const store = tmpStore();
addSlot(store, 1);
diff --git a/test/local-sandbox.test.ts b/test/local-sandbox.test.ts
index 47dc81c33..96a8db85e 100644
--- a/test/local-sandbox.test.ts
+++ b/test/local-sandbox.test.ts
@@ -34,7 +34,7 @@ async function freePort(): Promise<number> {
before(async () => {
daemonPort = await freePort();
- daemon = spawn(process.execPath, [join(process.cwd(), "aws/microvm-agent/agent.mjs")], {
+ daemon = spawn(process.execPath, [join(process.cwd(), "cli/templates/aws/microvm-agent/agent.mjs")], {
env: { ...process.env, AGENT_PORT: String(daemonPort), HOME: guestHome },
stdio: "ignore",
});