Files
PaperClipAI/server/src/services/environment-config.ts
T
DottaandPaperclip d67e3507b2 feat(runner): qualify Codex platform packages and cache hosted builds (#16028)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Native execution needs a compatible installed daemon and provider
dependency.
> - The Codex-default work found missing platform packages and
clean-install startup failures.
> - Release builds also repeat dependency compilation and run
preparation serially.
> - This prerequisite packages four daemon targets and verifies
installed native startup.
> - It also caches hosted Cargo dependencies and overlaps JavaScript
preparation with compilation.
> - Agent creation defaults and experimental gates stay at the current
master behavior.

## Linked Issues or Issue Description

Refs #15683. Refs #15555. Refs #15422. Refs #15926. Refs #15932.

Extract runtime and installation support from #15683. This prerequisite
has 65 changed files. Creation, onboarding, imports, UI runner selection
and graduation remain in the dependent PR. Feature/access maps and the
Storybook source catalog stay synchronized. Existing agents keep their
execution choices.

## What Changed

- Correct the existing runner test fixtures. Reserve owned credential
quorum listeners through the existing bounded fixture helper. Keep
foreign listeners intact, run actual credential staging once, and
preserve its rejection and unchanged-auth assertions. Reuse the
durable-resume outer-limit correction. Wait for actual warm-completion
and held-authorization callback entry under the existing recovery
deadline and surface early request errors. Preserve every semantic
assertion.
- Retain bounded installation failure diagnostics through the existing
qualification receipt upload. Keep the original error, 10-minute
deadline and all success checks.
- Keep startup ownership until credential preparation and registration
drain. Reject duplicate and post-close startup/resume work. Observe
shutdown during normal and adopted authentication readiness. Preserve
the primary failure and retain private state when cleanup is
unconfirmed.
- Package Linux x64/ARM64 and macOS Apple Silicon/Intel daemons. Verify
target headers, source identities, manifests, and hashes before assembly
and installation.
- Reuse the existing release producer/consumer workflows. Cache Cargo
dependencies by target, OS, compiler, lockfile, and contract inputs.
Rebuild workspace binaries. Permit trusted cache writes only for
canonical exact-source master pushes.
- Overlap JavaScript preparation with native compilation. Join both
commands and failure/cancellation cleanup before artifact verification.
- Preserve shell positional arguments in the shared SSH runner and apply
environment assignments correctly. Reject environment option keys. Six
before/after controls and two real SSH subprocess paths pass with zero
provider calls; this fix lands before both Codex and Claude defaults.
- Admit verified suspended SSH backups during cold controller
continuation, using the same full-scope, integrity and lifecycle checks
as sandbox targets. Two positive SSH cases fail before; all 14
positive/negative matrix cases pass afterward. Active ownership and
corrupt/malformed/nonempty state remain rejected.
- Record measured sandbox platform facts through the existing explicit
environment probe. Bind facts to the company, effective provider
configuration, immutable OCI image and actual captured image binding.
Check the returned cleanup receipt. Reject client-authored proof and
stale or named boot identities. Creation and discovery allocate nothing.
Preserve connection-only behavior.
- Resolve the actual remote Codex target and preserve same-host
development overrides. Preserve runtime artifact verification. Use
actual protocol/model compatibility rather than a numerical CLI version
fence.
- Resolve the installed Codex login dependency on 64-bit Linux and Mac
independently of the daemon libc baseline. Preserve account homes and
safe errors.
- Fix actual clean-install TOML table comparison. Preserve strict
semantic checks, comments, private writes, and malformed-input
rejection. Preserve primary startup failures and bounded cleanup.
- Document GNU libc 2.39+ and stock Ubuntu sandbox prerequisites.
Qualify ARM startup with a scoped distribution profile and unchanged
global restrictions. Preserve Windows and Alpine deferral.
- Preserve selected and saved native Codex reasoning effort in the
existing UI builder, while excluding it from other providers. This small
shared correction prevents import edits higher in the stack from
dropping effort.
- Reuse existing installed-package checks and assertions. Paperclip
tarballs contain no Codex native payloads. Official npm dependencies
supply the consumer's Codex binaries. All Docker and native builds stay
remote.

## Verification

Candidate: `271d434c170e74bdedde65d0b13059a55419c943`. It includes
current master `e168512f7bdbb6af6ea01954c6d7ed80b91e903e` and preserves
prior candidates through ordinary commits.

Current [full
CI](https://github.com/paperclipai/paperclip/actions/runs/38346601686)
is successful on attempt 2. GitHub reports 54 successful checks and four
conditional skips, including required verify and browser aggregates,
workspace typecheck/tests/build, Linux DB controls, both runner shards
and [isolated native
compilation](https://github.com/paperclipai/paperclip/actions/runs/38346601609).
Fresh current-head Greptile is 5/5 with all four threads resolved. The
passing build's clean Grok/Codex report records CI merge source
`7a82a37438e6e448abc7cc5caa60dc2519a97be0`, 18 installed packages,
omitted Codex payloads, official host-only npm dependencies and zero
provider calls. Pi setup and its no-prompt lease verification also pass.
The first attempt's single 60-second Node archive download timeout
remains retained; its DNS/TLS/download cause remains unknown. One
unchanged-source retry was requested through the normal Build-job dialog
with debug logging disabled. GitHub's attempt 2 graph reports the other
CI jobs as well; no second retry or source/deadline relaxation was made.

The [final exact-source package
campaign](https://github.com/paperclipai/paperclip/actions/runs/38347027535)
is successful on literal `271d434c170e74bdedde65d0b13059a55419c943`. It
passes all four native producers, public Linux package assembly and
clean installed consumers on Apple Silicon, Intel Mac and Linux ARM64.
The nine qualification-mode skips are intentional; full CI above covers
their ordinary gates. Native builds and Docker assembly ran remotely.
The predecessor [`dae808` package
campaign](https://github.com/paperclipai/paperclip/actions/runs/38342104102)
remains literal historical evidence. Only tests and the dated record
differ from that source; runtime, package and workflow code is
unchanged. The reused credential fixture correction passes all 42
canonical Node 24 controls with synthetic data and independent
matching-source review, and the current hosted runner shard passes.
Production credential behavior is unchanged.

**Merge hold:** current-source CI, fresh 5/5 review and exact-source
package qualification pass. Actual code-owner approval and normal
protected merge remain pending. No slice has merged or deployed. GitHub
CLI authentication needs refresh; the normal signed-in embedded GitHub
UI provided this status without credential workarounds.

- The master merge preserves both Storybook source-review appendices and
the guarded test-home cleanup. All six existing cleanup controls pass
without skips. Master's isolated-home helper/test/setup are
byte-identical. The two existing whitespace lines in master's unrelated
privacy test remain outside this PR's diff.
- Canonical Node 24 passes all 24 existing public-install helper tests.
Three narrow added cases prove bounded/redacted failure metadata,
symlink exclusions, original exception identity, failed diagnostic
writes and no false failure on success. The Mac installer now uses
`--timing`; at most two 16 KiB tails and 32 structured entries per tail
enter the existing receipt upload. Raw argv, URLs, environment, error
text and stacks are omitted. A failed receipt explicitly remains
FAILED/unqualified/runtime-not-attempted. The 600,000 ms install
deadline and every real package/hash/payload/lock/lifecycle/runtime
oracle are unchanged.
- Canonical Node 24 reproduces the durable-resume outer timeout under
controlled fake latency. Only its outer test limit changes to 15
seconds; internal 500 ms/5 second deadlines and usage/effect assertions
remain. Controlled warm-recovery and before-bootstrap authorization
scheduling delays reproduce their callback polling failures, while the
explicit entry signals pass. Early recovery errors surface unchanged.
Independent review is clear. Historical mock binaries support the
fixture controls; fresh full hosted CI remains decisive. The original
hosted callback failure cause is inconclusive.
- The composed runner/surfaces/server/E2E TypeScript checks pass. Map
checks pass 35 areas/171 capability IDs. Token gates pass. The existing
Storybook catalog passes 223 files/2,210 stories; story IDs and
classifications remain intact. The current master had 25 inherited stale
fingerprints from three changed map recipes. Only those guarded
fingerprints and a source-only review note change; all 92 non-map
story/component/fixture inputs remain unchanged. Existing
classifications are retained. This proves source structure, not visual
or live acceptance.
- The 65-file contribution audit has no code file crossing from below
1,000 lines to above the limit. Earlier comment cleanup preserves
executable emissions, parsed workflows and action pins. Independent
cleanup/catalog and three-file reporting reviews are clear. No new
workflow, suite, grader or local native/Docker build was added.

**Prior `dae808` gate evidence:** fresh Greptile is 5/5 with four
resolved threads, isolated native compilation and the browser aggregate
pass. Its first runner shard passes the previous two corrections but
fails a different held-authorization cell at the implicit one-second
polling deadline. It records 1,672 passes/one failure/three skips. This
candidate applies the verified entry-signal correction without changing
production deadlines or any semantic assertions. Its original hosted
cause remains inconclusive until fresh CI.

**Previous-source evidence, kept literal:** the [exact `16a532` package
campaign](https://github.com/paperclipai/paperclip/actions/runs/38338806076)
passes all four native producers, public Linux package assembly, Apple
Silicon, Intel Mac and Linux ARM64 installed consumers. Its fresh review
is 5/5 with all four threads resolved. Full CI records 52 successful
checks, four conditional skips and the two fixture failures corrected
here. This is not a green full-CI candidate or proof for the new source.

`64c074fb8da1b31f8d6042c4fef48dc4164e759b` passed [full
CI](https://github.com/paperclipai/paperclip/actions/runs/38332726938),
54 checks/four conditional skips, [isolated native
compilation](https://github.com/paperclipai/paperclip/actions/runs/38332726787/job/115085895328),
and fresh Greptile 5/5/all four resolved threads. The hosted transport
suite passed 246 tests and startup trust passed 22, closing that
source's local fake-binary limitation. These are historical after
reconciliation.

The [previous exact-source package
campaign](https://github.com/paperclipai/paperclip/actions/runs/38332921463)
built all four platform daemons and passed public Linux package assembly
plus Apple Silicon and Linux ARM64 installed consumers. **Intel Mac
failed:** its initial scripts-disabled npm install timed out before
lifecycle/runtime assertions. The underlying download/resolution/host
cause is unknown because the old helper deleted the npm logs. This is
the concrete baseline for the diagnostic change. The failed campaign
remains failed; no all-platform signoff or automatic retry is claimed.

The earlier `a200495` [four-target
campaign](https://github.com/paperclipai/paperclip/actions/runs/38283695248)
and [scoped ARM
qualification](https://github.com/paperclipai/paperclip/actions/runs/38291535914)
remain component evidence. Cargo restores were cold misses; no
warm-cache speedup is claimed. Paperclip tarballs contain no Codex
payloads. Official npm dependencies supply Codex on the user's platform.

Current-source full workspace typecheck/tests/build, Linux DB controls,
static/Rust/native tests, all browser shards and exact-source package
consumers must pass. New-agent defaults and final managed onboarding
belong to #15683. Actual private Cloud composition, warm/cold signup,
task/follow-up and rollback compatibility remain later release gates.
Source audits found that ordinary managed onboarding does not run the
saved platform probe and Cloud distributes named snapshots without a
verified final boot-image binding. These dependent release blockers
remain open; prequalified E2E fixtures do not close them. Master adds
task-workspace migrations; the final image/migrator and previous-image
checks must include them. ARM paid task/follow-up and ordinary OS APT
installation are not proven.

## Risks

- Multi-target packages require source and header agreement. Missing or
mismatched artifacts fail explicitly. Existing execution choices remain
unchanged.
- Linux requires GNU libc 2.39+ and compatible sandbox prerequisites.
The scoped hosted ARM preparation does not qualify arbitrary containers
or kernels. Windows, 32-bit ARM, and Alpine remain deferred.
- Only dependency crates are cached. Preview jobs cannot write trusted
caches. Concurrent command cleanup must preserve the primary failure.
- Native-free Paperclip packaging retains official Codex npm
dependencies. No Codex payload bundling, schema migration, automatic
agent migration, or production deployment is included.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning, repository tools, code
execution, and parallel agents. The exact serving model snapshot and
context-window size are not exposed.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-13 06:24:07 -05:00

831 lines
29 KiB
TypeScript

import { z } from "zod";
import { randomUUID } from "node:crypto";
import type { Db } from "@paperclipai/db";
import type {
Environment,
EnvironmentDriver,
FakeSandboxEnvironmentConfig,
LocalEnvironmentConfig,
PluginEnvironmentConfig,
PluginSandboxEnvironmentConfig,
SandboxEnvironmentConfig,
SecretProvider,
SecretVersionSelector,
SshEnvironmentConfig,
} from "@paperclipai/shared";
import { unprocessable } from "../errors.js";
import { parseObject } from "../adapters/utils.js";
import { secretService } from "./secrets.js";
import {
resolvePluginSandboxProviderDriverByKey,
validatePluginEnvironmentDriverConfig,
validatePluginSandboxProviderConfig,
} from "./plugin-environment-driver.js";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import {
collectSecretRefPaths,
isUuidSecretRef,
parseSecretRefBindingObject,
readConfigValueAtPath,
writeConfigValueAtPath,
} from "./json-schema-secret-refs.js";
import { resolveActiveEnvironmentCustomImageTemplateForRuntime } from "./environment-custom-image-runtime.js";
const secretRefSchema = z.object({
type: z.literal("secret_ref"),
secretId: z.string().guid(),
version: z.union([z.literal("latest"), z.number().int().positive()]).optional().default("latest"),
}).strict();
const sshEnvironmentConfigSchema = z.object({
host: z.string({ error: "SSH environments require a host." }).trim().min(1, "SSH environments require a host."),
port: z.coerce.number().int().min(1).max(65535).default(22),
username: z.string({ error: "SSH environments require a username." }).trim().min(1, "SSH environments require a username."),
remoteWorkspacePath: z
.string({ error: "SSH environments require a remote workspace path." })
.trim()
.min(1, "SSH environments require a remote workspace path.")
.refine((value) => value.startsWith("/"), "SSH remote workspace path must be absolute."),
privateKey: z.null().optional().default(null),
privateKeySecretRef: secretRefSchema.optional().nullable().default(null),
knownHosts: z
.string()
.trim()
.optional()
.nullable()
.transform((value) => (value && value.length > 0 ? value : null)),
strictHostKeyChecking: z.boolean().optional().default(true),
}).strict();
const sshEnvironmentConfigProbeSchema = sshEnvironmentConfigSchema.extend({
privateKey: z
.string()
.trim()
.optional()
.nullable()
.transform((value) => (value && value.length > 0 ? value : null)),
}).strict();
const sshEnvironmentConfigPersistenceSchema = sshEnvironmentConfigProbeSchema;
const fakeSandboxEnvironmentConfigSchema = z.object({
provider: z.literal("fake").default("fake"),
image: z
.string()
.trim()
.min(1, "Fake sandbox environments require an image.")
.default("ubuntu:24.04"),
reuseLease: z.boolean().optional().default(false),
streamRunLogs: z.boolean().optional(),
runnerLifecycleMode: z.enum(["inherit", "per_turn", "warm"]).optional(),
runnerIdleTimeoutMs: z.coerce
.number()
.int()
.min(1_000)
.max(86_400_000)
.optional(),
archiveOnRelease: z.boolean().optional(),
}).strict();
const pluginSandboxProviderKeySchema = z.string()
.trim()
.min(1, "Sandbox provider is required.")
.regex(
/^[a-z0-9][a-z0-9._-]*$/,
"Sandbox provider key must start with a lowercase alphanumeric and contain only lowercase letters, digits, dots, hyphens, or underscores",
);
const pluginSandboxEnvironmentConfigSchema = z.object({
provider: pluginSandboxProviderKeySchema,
timeoutMs: z.coerce.number().int().min(1).max(86_400_000).optional(),
reuseLease: z.boolean().optional().default(false),
streamRunLogs: z.boolean().optional(),
runnerLifecycleMode: z.enum(["inherit", "per_turn", "warm"]).optional(),
runnerIdleTimeoutMs: z.coerce
.number()
.int()
.min(1_000)
.max(86_400_000)
.optional(),
archiveOnRelease: z.boolean().optional(),
}).catchall(z.unknown());
const pluginEnvironmentConfigSchema = z.object({
pluginKey: z.string().min(1),
driverKey: z.string().min(1).regex(
/^[a-z0-9][a-z0-9._-]*$/,
"Environment driver key must start with a lowercase alphanumeric and contain only lowercase letters, digits, dots, hyphens, or underscores",
),
driverConfig: z.record(z.string(), z.unknown()).optional().default({}),
}).strict();
export type ParsedEnvironmentConfig =
| { driver: "local"; config: LocalEnvironmentConfig }
| { driver: "ssh"; config: SshEnvironmentConfig }
| { driver: "sandbox"; config: SandboxEnvironmentConfig }
| { driver: "plugin"; config: PluginEnvironmentConfig };
function toErrorMessage(error: z.ZodError) {
const first = error.issues[0];
if (!first) return "Invalid environment config.";
return first.message;
}
function getSandboxProvider(raw: Record<string, unknown>) {
return typeof raw.provider === "string" && raw.provider.trim().length > 0 ? raw.provider.trim() : "fake";
}
// Operator flags removed when session-output streaming moved to the verified
// capability snapshot. A saved environment config can still carry a removed key.
// The server now decides session-output streaming from the effective capability
// snapshot alone, so no consumer reads these flags. Strip a removed key before
// validation so a strict schema (the fake sandbox) still loads an old config,
// and so the removed flag never reaches the parsed config.
const REMOVED_SANDBOX_CONFIG_KEYS = ["streamAgentSessionOutput"] as const;
function stripRemovedSandboxConfigKeys(raw: Record<string, unknown>): Record<string, unknown> {
if (!REMOVED_SANDBOX_CONFIG_KEYS.some((key) => key in raw)) {
return raw;
}
const next = { ...raw };
for (const key of REMOVED_SANDBOX_CONFIG_KEYS) {
delete next[key];
}
return next;
}
function parseSandboxEnvironmentConfig(
input: Record<string, unknown> | null | undefined,
) {
const raw = stripRemovedSandboxConfigKeys(parseObject(input));
const provider = getSandboxProvider(raw);
if (provider === "fake") {
const parsed = fakeSandboxEnvironmentConfigSchema.safeParse(raw);
return parsed.success
? ({ success: true as const, data: parsed.data satisfies FakeSandboxEnvironmentConfig })
: ({ success: false as const, error: parsed.error });
}
const parsed = pluginSandboxEnvironmentConfigSchema.safeParse(raw);
return parsed.success
? ({ success: true as const, data: parsed.data satisfies PluginSandboxEnvironmentConfig })
: ({ success: false as const, error: parsed.error });
}
async function getSandboxProviderConfigSchema(
db: Db,
provider: string,
): Promise<Record<string, unknown> | null> {
const resolved = await resolvePluginSandboxProviderDriverByKey({
db,
driverKey: provider,
});
const schema = resolved?.driver.configSchema;
return schema && typeof schema === "object" && !Array.isArray(schema)
? schema as Record<string, unknown>
: null;
}
export async function resolveSandboxProviderSecretRefPaths(
db: Db,
provider: string,
): Promise<Set<string>> {
return collectSecretRefPaths(await getSandboxProviderConfigSchema(db, provider));
}
function secretName(input: {
environmentName: string;
driver: EnvironmentDriver;
field: string;
}) {
const slug = input.environmentName
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 48) || "environment";
return `environment-${input.driver}-${slug}-${input.field}-${randomUUID().slice(0, 8)}`;
}
async function createEnvironmentSecret(input: {
db: Db;
companyId: string;
environmentName: string;
driver: EnvironmentDriver;
field: string;
provider: SecretProvider;
value: string;
actor?: { userId?: string | null; agentId?: string | null };
}) {
const created = await secretService(input.db).create(
input.companyId,
{
name: secretName(input),
provider: input.provider,
value: input.value,
description: `Secret for ${input.environmentName} ${input.field}.`,
},
input.actor,
);
return {
type: "secret_ref" as const,
secretId: created.id,
version: "latest" as const,
};
}
/**
* Secret pickers submit `{ type: "secret_ref", secretId, version }` binding
* objects for `format: "secret-ref"` fields, while persisted configs store the
* bare secret id. Collapse binding objects to the secret id so every consumer
* downstream deals with one shape. Sandbox provider references always resolve
* the latest version, so pinned bindings are rejected rather than silently
* resolved to a different version than the caller asked for.
*/
function canonicalizeSecretRefValue(value: unknown, path: string): unknown {
const binding = parseSecretRefBindingObject(value);
if (!binding) return value;
if (binding.version !== "latest") {
throw unprocessable(
`Secret binding at ${path} pins version ${binding.version}; sandbox provider secret references always resolve the latest version.`,
);
}
return binding.secretId;
}
async function persistConfigSecretRefs(input: {
db: Db;
companyId: string;
environmentName: string;
driver: EnvironmentDriver;
secretProvider: SecretProvider;
config: Record<string, unknown>;
schema: Record<string, unknown> | null;
actor?: { userId?: string | null; agentId?: string | null };
}): Promise<Record<string, unknown>> {
let nextConfig = { ...input.config };
for (const path of collectSecretRefPaths(input.schema)) {
const rawValue = canonicalizeSecretRefValue(readConfigValueAtPath(nextConfig, path), path);
if (typeof rawValue !== "string") continue;
const trimmed = rawValue.trim();
if (trimmed.length === 0) {
nextConfig = writeConfigValueAtPath(nextConfig, path, undefined);
continue;
}
if (isUuidSecretRef(trimmed)) {
nextConfig = writeConfigValueAtPath(nextConfig, path, trimmed);
continue;
}
const created = await createEnvironmentSecret({
db: input.db,
companyId: input.companyId,
environmentName: input.environmentName,
driver: input.driver,
field: path.replace(/[^a-z0-9]+/gi, "-").toLowerCase(),
provider: input.secretProvider,
value: trimmed,
actor: input.actor,
});
nextConfig = writeConfigValueAtPath(nextConfig, path, created.secretId);
}
return nextConfig;
}
async function resolveConfigSecretRefsForRuntime(input: {
db: Db;
companyId: string;
config: Record<string, unknown>;
schema: Record<string, unknown> | null;
context: {
consumerId: string;
issueId?: string | null;
heartbeatRunId?: string | null;
};
}): Promise<Record<string, unknown>> {
const secrets = secretService(input.db);
let nextConfig = { ...input.config };
for (const path of collectSecretRefPaths(input.schema)) {
const current = canonicalizeSecretRefValue(readConfigValueAtPath(nextConfig, path), path);
if (typeof current !== "string") continue;
const trimmed = current.trim();
if (!isUuidSecretRef(trimmed)) continue;
if (!input.context.consumerId) {
throw unprocessable("Runtime secret resolution requires an environment id");
}
nextConfig = writeConfigValueAtPath(
nextConfig,
path,
await secrets.resolveSecretValue(input.companyId, trimmed, "latest", {
consumerType: "environment",
consumerId: input.context.consumerId,
actorType: "system",
actorId: null,
issueId: input.context.issueId ?? null,
heartbeatRunId: input.context.heartbeatRunId ?? null,
configPath: path,
}),
);
}
return nextConfig;
}
async function resolveConfigSecretRefsForProbe(input: {
db: Db;
companyId: string;
config: Record<string, unknown>;
schema: Record<string, unknown> | null;
accessContext?: {
actorType: "agent" | "user";
actorId: string;
actorSource?: "local_implicit" | "session" | "board_key" | "agent_key" | "agent_jwt" | "mcp_oauth" | "cloud_tenant";
heartbeatRunId?: string | null;
};
}): Promise<Record<string, unknown>> {
const secrets = secretService(input.db);
let nextConfig = { ...input.config };
for (const path of collectSecretRefPaths(input.schema)) {
const current = canonicalizeSecretRefValue(readConfigValueAtPath(nextConfig, path), path);
if (typeof current !== "string") continue;
const trimmed = current.trim();
if (!isUuidSecretRef(trimmed)) continue;
// Unsaved draft probes do not have an environment record yet, so they
// cannot rely on environment-bound secret resolution. Resolve directly for
// this ephemeral board-only probe and never persist the plaintext value.
nextConfig = writeConfigValueAtPath(
nextConfig,
path,
await secrets.resolveSecretValueForEphemeralAccess(input.companyId, trimmed, "latest", {
consumerType: "system",
consumerId: "environment-probe-config",
configPath: path,
actorType: input.accessContext?.actorType ?? "system",
actorId: input.accessContext?.actorId ?? null,
actorSource: input.accessContext?.actorSource,
heartbeatRunId: input.accessContext?.heartbeatRunId ?? null,
}),
);
}
return nextConfig;
}
export async function collectEnvironmentSecretRefs(input: {
db: Db;
environment: Pick<Environment, "id" | "driver" | "config">;
}): Promise<Array<{ secretId: string; configPath: string; versionSelector?: SecretVersionSelector }>> {
const parsed = parseEnvironmentDriverConfig(input.environment);
if (parsed.driver === "ssh" && parsed.config.privateKeySecretRef) {
return [{
secretId: parsed.config.privateKeySecretRef.secretId,
configPath: "privateKeySecretRef",
versionSelector: parsed.config.privateKeySecretRef.version ?? "latest",
}];
}
if (parsed.driver === "sandbox" && parsed.config.provider !== "fake") {
const schema = await getSandboxProviderConfigSchema(input.db, parsed.config.provider);
const refs: Array<{ secretId: string; configPath: string; versionSelector?: SecretVersionSelector }> = [];
for (const path of collectSecretRefPaths(schema)) {
const current = readConfigValueAtPath(parsed.config as Record<string, unknown>, path);
const binding = parseSecretRefBindingObject(current);
if (binding) {
refs.push({ secretId: binding.secretId, configPath: path, versionSelector: binding.version });
continue;
}
if (typeof current === "string" && isUuidSecretRef(current.trim())) {
refs.push({ secretId: current.trim(), configPath: path, versionSelector: "latest" });
}
}
return refs;
}
return [];
}
export function stripSandboxProviderEnvelope(config: SandboxEnvironmentConfig): Record<string, unknown> {
const {
provider: _provider,
streamRunLogs: _streamRunLogs,
...driverConfig
} = config as Record<string, unknown>;
return driverConfig;
}
// The host owns these sandbox run-behavior flags, not the provider plugin. The
// host passes the whole config to the plugin, so a plugin that allowlists only
// its provider fields may drop them from its normalized config. Re-apply them
// from the parsed envelope after plugin normalization. Otherwise a saved
// environment can silently fall back to per-turn runner behavior even though
// the caller explicitly selected a warm lifecycle.
const HOST_OWNED_SANDBOX_FLAGS = [
"streamRunLogs",
"runnerLifecycleMode",
"runnerIdleTimeoutMs",
] as const;
function applyHostOwnedSandboxFlags(
normalizedConfig: Record<string, unknown>,
envelope: Record<string, unknown>,
): Record<string, unknown> {
const merged: Record<string, unknown> = { ...normalizedConfig };
for (const key of HOST_OWNED_SANDBOX_FLAGS) {
if (envelope[key] !== undefined) {
merged[key] = envelope[key];
}
}
return merged;
}
export function normalizeEnvironmentConfig(input: {
driver: EnvironmentDriver;
config: Record<string, unknown> | null | undefined;
}): Record<string, unknown> {
if (input.driver === "local") {
return { ...parseObject(input.config) };
}
if (input.driver === "ssh") {
const parsed = sshEnvironmentConfigSchema.safeParse(parseObject(input.config));
if (!parsed.success) {
throw unprocessable(toErrorMessage(parsed.error), {
issues: parsed.error.issues,
});
}
return parsed.data satisfies SshEnvironmentConfig;
}
if (input.driver === "sandbox") {
const parsed = parseSandboxEnvironmentConfig(input.config);
if (!parsed.success) {
throw unprocessable(toErrorMessage(parsed.error), {
issues: parsed.error.issues,
});
}
return parsed.data;
}
if (input.driver === "plugin") {
const parsed = pluginEnvironmentConfigSchema.safeParse(parseObject(input.config));
if (!parsed.success) {
throw unprocessable(toErrorMessage(parsed.error), {
issues: parsed.error.issues,
});
}
return parsed.data satisfies PluginEnvironmentConfig;
}
throw unprocessable(`Unsupported environment driver "${input.driver}".`);
}
export function normalizeEnvironmentConfigForProbe(input: {
db: Db;
companyId: string;
driver: EnvironmentDriver;
config: Record<string, unknown> | null | undefined;
accessContext?: {
actorType: "agent" | "user";
actorId: string;
actorSource?: "local_implicit" | "session" | "board_key" | "agent_key" | "agent_jwt" | "mcp_oauth" | "cloud_tenant";
heartbeatRunId?: string | null;
};
pluginWorkerManager?: PluginWorkerManager;
}): Promise<Record<string, unknown>> | Record<string, unknown> {
if (input.driver === "ssh") {
const parsed = sshEnvironmentConfigProbeSchema.safeParse(parseObject(input.config));
if (!parsed.success) {
throw unprocessable(toErrorMessage(parsed.error), {
issues: parsed.error.issues,
});
}
return parsed.data satisfies SshEnvironmentConfig;
}
if (input.driver === "sandbox") {
const parsed = parseSandboxEnvironmentConfig(input.config);
if (!parsed.success) {
throw unprocessable(toErrorMessage(parsed.error), {
issues: parsed.error.issues,
});
}
if (parsed.data.provider === "fake") {
return parsed.data;
}
if (!input.pluginWorkerManager) {
throw unprocessable("Sandbox provider config validation requires a running plugin worker manager.");
}
return validatePluginSandboxProviderConfig({
db: input.db,
workerManager: input.pluginWorkerManager,
provider: parsed.data.provider,
config: stripSandboxProviderEnvelope(parsed.data),
}).then(async (validated) => ({
provider: parsed.data.provider,
...(await resolveConfigSecretRefsForProbe({
db: input.db,
companyId: input.companyId,
config: applyHostOwnedSandboxFlags(
validated.normalizedConfig,
parsed.data,
),
accessContext: input.accessContext,
schema:
validated.driver.configSchema &&
typeof validated.driver.configSchema === "object" &&
!Array.isArray(validated.driver.configSchema)
? validated.driver.configSchema as Record<string, unknown>
: null,
})),
}));
}
return normalizeEnvironmentConfig({
driver: input.driver,
config: input.config,
});
}
export async function normalizeEnvironmentConfigForPersistence(input: {
db: Db;
companyId: string;
environmentName: string;
driver: EnvironmentDriver;
secretProvider: SecretProvider;
config: Record<string, unknown> | null | undefined;
actor?: { userId?: string | null; agentId?: string | null };
pluginWorkerManager?: PluginWorkerManager;
}): Promise<Record<string, unknown>> {
if (input.driver === "ssh") {
const parsed = sshEnvironmentConfigPersistenceSchema.safeParse(parseObject(input.config));
if (!parsed.success) {
throw unprocessable(toErrorMessage(parsed.error), {
issues: parsed.error.issues,
});
}
const secrets = secretService(input.db);
const { privateKey, ...stored } = parsed.data;
let nextPrivateKeySecretRef = stored.privateKeySecretRef;
if (privateKey) {
nextPrivateKeySecretRef = await createEnvironmentSecret({
db: input.db,
companyId: input.companyId,
environmentName: input.environmentName,
driver: input.driver,
field: "private-key",
provider: input.secretProvider,
value: privateKey,
actor: input.actor,
});
if (
stored.privateKeySecretRef &&
stored.privateKeySecretRef.secretId !== nextPrivateKeySecretRef.secretId
) {
await secrets.remove(stored.privateKeySecretRef.secretId);
}
}
return {
...stored,
privateKey: null,
privateKeySecretRef: nextPrivateKeySecretRef,
} satisfies SshEnvironmentConfig;
}
if (input.driver === "sandbox") {
const parsed = parseSandboxEnvironmentConfig(input.config);
if (!parsed.success) {
throw unprocessable(toErrorMessage(parsed.error), {
issues: parsed.error.issues,
});
}
if (parsed.data.provider === "fake") {
throw unprocessable(
"Built-in fake sandbox environments are reserved for internal probes and cannot be saved.",
);
}
if (!input.pluginWorkerManager) {
throw unprocessable("Sandbox provider config validation requires a running plugin worker manager.");
}
const validated = await validatePluginSandboxProviderConfig({
db: input.db,
workerManager: input.pluginWorkerManager,
provider: parsed.data.provider,
config: stripSandboxProviderEnvelope(parsed.data),
});
return await persistConfigSecretRefs({
db: input.db,
companyId: input.companyId,
environmentName: input.environmentName,
driver: input.driver,
secretProvider: input.secretProvider,
config: {
provider: parsed.data.provider,
...applyHostOwnedSandboxFlags(validated.normalizedConfig, parsed.data),
},
schema:
validated.driver.configSchema && typeof validated.driver.configSchema === "object" && !Array.isArray(validated.driver.configSchema)
? validated.driver.configSchema as Record<string, unknown>
: null,
actor: input.actor,
});
}
if (input.driver === "plugin") {
const parsed = pluginEnvironmentConfigSchema.safeParse(parseObject(input.config));
if (!parsed.success) {
throw unprocessable(toErrorMessage(parsed.error), {
issues: parsed.error.issues,
});
}
if (!input.pluginWorkerManager) {
throw unprocessable("Plugin environment config validation requires a running plugin worker manager.");
}
return { ...(await validatePluginEnvironmentDriverConfig({
db: input.db,
workerManager: input.pluginWorkerManager,
config: parsed.data,
})) };
}
return normalizeEnvironmentConfig({
driver: input.driver,
config: input.config,
});
}
export async function resolveEnvironmentDriverConfigForRuntime(
db: Db,
companyId: string | null,
environment: Pick<Environment, "driver" | "config"> & Partial<Pick<Environment, "id">>,
context?: {
issueId?: string | null;
heartbeatRunId?: string | null;
// Force applying the active custom-image template even without a run/issue
// context. Operator-initiated `Test` probes have no issueId/heartbeatRunId
// but must still resolve the active custom image as prepared runtime
// configuration and tooling so the test reflects what real agent runs use.
applyCustomImageTemplate?: boolean;
readOnlyCustomImageTemplate?: boolean;
onResolvedCustomImageTemplate?: (identity: { id: string; capturedAt: string | null; templateKind: string; bindingField: string }) => void;
},
): Promise<ParsedEnvironmentConfig> {
const parsed = parseEnvironmentDriverConfig(environment);
const secrets = secretService(db);
const environmentId = environment.id;
if (parsed.driver === "ssh" && parsed.config.privateKeySecretRef && !environmentId) {
throw unprocessable("Runtime secret resolution requires an environment id");
}
if (parsed.driver === "ssh" && parsed.config.privateKeySecretRef) {
if (!companyId) {
throw unprocessable("Runtime secret resolution requires a companyId context");
}
return {
driver: "ssh",
config: {
...parsed.config,
privateKey: await secrets.resolveSecretValue(
companyId,
parsed.config.privateKeySecretRef.secretId,
parsed.config.privateKeySecretRef.version ?? "latest",
{
consumerType: "environment",
consumerId: environmentId!,
actorType: "system",
actorId: null,
issueId: context?.issueId ?? null,
heartbeatRunId: context?.heartbeatRunId ?? null,
configPath: "privateKeySecretRef",
},
),
},
};
}
if (parsed.driver === "sandbox" && parsed.config.provider !== "fake") {
const schema = await getSandboxProviderConfigSchema(db, parsed.config.provider);
let runtimeConfig = parsed.config;
if (companyId) {
runtimeConfig = await resolveConfigSecretRefsForRuntime({
db,
companyId,
config: parsed.config as Record<string, unknown>,
schema,
context: {
consumerId: environmentId!,
issueId: context?.issueId ?? null,
heartbeatRunId: context?.heartbeatRunId ?? null,
},
}) as SandboxEnvironmentConfig;
} else {
for (const path of collectSecretRefPaths(schema)) {
const current = readConfigValueAtPath(parsed.config as Record<string, unknown>, path);
if (parseSecretRefBindingObject(current) || (typeof current === "string" && isUuidSecretRef(current.trim()))) {
throw unprocessable("Runtime secret resolution requires a companyId context");
}
}
}
return {
driver: "sandbox",
config: environmentId && (context?.issueId || context?.heartbeatRunId || context?.applyCustomImageTemplate)
? await resolveActiveEnvironmentCustomImageTemplateForRuntime(db, {
environmentId,
baseConfig: parsed.config,
runtimeConfig,
// Match the capture-time fingerprint exclusions: secret-ref paths
// are excluded when the template's source fingerprint is computed,
// so they must be excluded when re-checking it here.
secretRefExcludePaths: collectSecretRefPaths(schema),
readOnly: context?.readOnlyCustomImageTemplate,
onResolvedTemplate: context?.onResolvedCustomImageTemplate,
})
: runtimeConfig,
};
}
return parsed;
}
/**
* Resolve the connection secrets of a recorded sandbox config for a durable
* orphan-sandbox teardown. The retry reads the recorded config from the durable
* `pending_cleanup` lease row, not from the current environment. So this
* resolver must not require the environment binding: a delete removed the
* environment, or a provider change replaced the binding. It resolves each
* schema-declared secret ref by id at the latest version through
* `resolveSecretValueForSandboxCleanup`, which authorizes the read from the
* durable orphan record and skips the binding check. The resolved values are
* used once for the teardown RPC and never persisted.
*/
export async function resolveSandboxCleanupConfigSecrets(
db: Db,
companyId: string,
config: SandboxEnvironmentConfig,
context?: { issueId?: string | null; heartbeatRunId?: string | null },
): Promise<SandboxEnvironmentConfig> {
if (config.provider === "fake") return config;
const schema = await getSandboxProviderConfigSchema(db, config.provider);
const secrets = secretService(db);
let nextConfig = { ...config } as Record<string, unknown>;
for (const path of collectSecretRefPaths(schema)) {
const current = canonicalizeSecretRefValue(readConfigValueAtPath(nextConfig, path), path);
if (typeof current !== "string") continue;
const trimmed = current.trim();
if (!isUuidSecretRef(trimmed)) continue;
nextConfig = writeConfigValueAtPath(
nextConfig,
path,
await secrets.resolveSecretValueForSandboxCleanup(companyId, trimmed, "latest", {
configPath: path,
issueId: context?.issueId ?? null,
heartbeatRunId: context?.heartbeatRunId ?? null,
}),
);
}
return nextConfig as SandboxEnvironmentConfig;
}
export function readSshEnvironmentPrivateKeySecretId(
environment: Pick<Environment, "driver" | "config">,
): string | null {
if (environment.driver !== "ssh") return null;
const parsed = sshEnvironmentConfigSchema.safeParse(parseObject(environment.config));
if (!parsed.success) return null;
return parsed.data.privateKeySecretRef?.secretId ?? null;
}
export function parseEnvironmentDriverConfig(
environment: Pick<Environment, "driver" | "config">,
): ParsedEnvironmentConfig {
if (environment.driver === "local") {
return {
driver: "local",
config: { ...parseObject(environment.config) },
};
}
if (environment.driver === "ssh") {
const parsed = sshEnvironmentConfigSchema.parse(parseObject(environment.config));
return {
driver: "ssh",
config: parsed,
};
}
if (environment.driver === "sandbox") {
const parsed = parseSandboxEnvironmentConfig(environment.config);
if (!parsed.success) {
throw parsed.error;
}
return {
driver: "sandbox",
config: parsed.data,
};
}
if (environment.driver === "plugin") {
const parsed = pluginEnvironmentConfigSchema.parse(parseObject(environment.config));
return {
driver: "plugin",
config: parsed,
};
}
throw new Error(`Unsupported environment driver "${environment.driver}".`);
}