mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-18 15:39:47 +02:00
## 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>
601 lines
24 KiB
TypeScript
601 lines
24 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { and, desc, eq } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import { environmentCustomImageTemplates } from "@paperclipai/db";
|
|
import {
|
|
ENVIRONMENT_CUSTOM_IMAGE_TEMPLATE_KINDS,
|
|
type EnvironmentCustomImageTemplate,
|
|
type EnvironmentCustomImageTemplateKind,
|
|
type SandboxEnvironmentConfig,
|
|
} from "@paperclipai/shared";
|
|
import { readConfigValueAtPath, writeConfigValueAtPath } from "./json-schema-secret-refs.js";
|
|
|
|
type TemplateRow = typeof environmentCustomImageTemplates.$inferSelect;
|
|
|
|
export const ENVIRONMENT_CUSTOM_IMAGE_RUNTIME_CONFIG_BINDING_METADATA_KEY = "runtimeConfigBinding";
|
|
export const SANDBOX_PLATFORM_PROBE_METADATA_KEY = "paperclipSandboxPlatformProbes";
|
|
export const ENVIRONMENT_CUSTOM_IMAGE_CONFIG_FINGERPRINT_EXCLUDED_PATHS = [
|
|
"timeoutMs",
|
|
"reuseLease",
|
|
"streamRunLogs",
|
|
"archiveOnRelease",
|
|
"cpu",
|
|
"memory",
|
|
"disk",
|
|
"gpu",
|
|
"autoStopInterval",
|
|
"autoArchiveInterval",
|
|
"autoDeleteInterval",
|
|
];
|
|
|
|
export interface EnvironmentCustomImageRuntimeConfigBinding {
|
|
field: string;
|
|
unsetFields: string[];
|
|
}
|
|
|
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
}
|
|
|
|
function stableStringify(value: unknown): string {
|
|
if (Array.isArray(value)) {
|
|
return `[${value.map((entry) => stableStringify(entry)).join(",")}]`;
|
|
}
|
|
if (isRecord(value)) {
|
|
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
|
|
}
|
|
return JSON.stringify(value) ?? "null";
|
|
}
|
|
|
|
export function readEnvironmentCustomImageTemplateKind(
|
|
value: string | null,
|
|
): EnvironmentCustomImageTemplateKind {
|
|
return (ENVIRONMENT_CUSTOM_IMAGE_TEMPLATE_KINDS as readonly string[]).includes(value ?? "")
|
|
? value as EnvironmentCustomImageTemplateKind
|
|
: "unknown";
|
|
}
|
|
|
|
export function defaultEnvironmentCustomImageRuntimeConfigBinding(
|
|
templateKind: string | null | undefined,
|
|
): EnvironmentCustomImageRuntimeConfigBinding {
|
|
const kind = readEnvironmentCustomImageTemplateKind(templateKind ?? null);
|
|
if (kind === "snapshot") return { field: "snapshot", unsetFields: ["image"] };
|
|
if (kind === "image") return { field: "image", unsetFields: ["snapshot"] };
|
|
if (kind === "provider_template") return { field: "template", unsetFields: [] };
|
|
return { field: "templateRef", unsetFields: [] };
|
|
}
|
|
|
|
function isValidRuntimeConfigBindingField(value: unknown): value is string {
|
|
return typeof value === "string"
|
|
&& /^[A-Za-z_][A-Za-z0-9_-]*$/.test(value)
|
|
&& value !== "provider";
|
|
}
|
|
|
|
export function normalizeEnvironmentCustomImageRuntimeConfigBinding(
|
|
value: unknown,
|
|
): EnvironmentCustomImageRuntimeConfigBinding | null {
|
|
if (!isRecord(value) || !isValidRuntimeConfigBindingField(value.field)) return null;
|
|
const unsetFields = Array.isArray(value.unsetFields)
|
|
? value.unsetFields.filter((field): field is string =>
|
|
isValidRuntimeConfigBindingField(field) && field !== value.field,
|
|
)
|
|
: [];
|
|
return {
|
|
field: value.field,
|
|
unsetFields: Array.from(new Set(unsetFields)),
|
|
};
|
|
}
|
|
|
|
export function resolveEnvironmentCustomImageRuntimeConfigBinding(input: {
|
|
templateKind: string | null | undefined;
|
|
metadata?: Record<string, unknown> | null;
|
|
}): EnvironmentCustomImageRuntimeConfigBinding {
|
|
return normalizeEnvironmentCustomImageRuntimeConfigBinding(
|
|
input.metadata?.[ENVIRONMENT_CUSTOM_IMAGE_RUNTIME_CONFIG_BINDING_METADATA_KEY],
|
|
) ?? defaultEnvironmentCustomImageRuntimeConfigBinding(input.templateKind);
|
|
}
|
|
|
|
export function fingerprintEnvironmentSandboxProviderConfig(
|
|
config: SandboxEnvironmentConfig,
|
|
options?: { excludePaths?: Iterable<string> },
|
|
): string {
|
|
let normalized = config as Record<string, unknown>;
|
|
for (const path of options?.excludePaths ?? []) {
|
|
normalized = writeConfigValueAtPath(normalized, path, undefined);
|
|
}
|
|
return createHash("sha256")
|
|
.update(stableStringify(normalized))
|
|
.digest("hex");
|
|
}
|
|
|
|
export function applyCustomImageTemplateToSandboxConfig(
|
|
config: SandboxEnvironmentConfig,
|
|
template: Pick<EnvironmentCustomImageTemplate, "templateKind" | "templateRef" | "metadata">,
|
|
): SandboxEnvironmentConfig {
|
|
if (!template.templateRef) return config;
|
|
const next = { ...(config as Record<string, unknown>) };
|
|
const binding = resolveEnvironmentCustomImageRuntimeConfigBinding({
|
|
templateKind: template.templateKind,
|
|
metadata: template.metadata,
|
|
});
|
|
for (const field of binding.unsetFields) {
|
|
delete next[field];
|
|
}
|
|
next[binding.field] = template.templateRef;
|
|
return next as SandboxEnvironmentConfig;
|
|
}
|
|
|
|
export function environmentCustomImageTemplateMatchesBaseConfig(input: {
|
|
template: EnvironmentCustomImageTemplate;
|
|
baseConfig: SandboxEnvironmentConfig;
|
|
secretRefExcludePaths?: Iterable<string>;
|
|
}): boolean {
|
|
const expectedFingerprint = input.template.sourceEnvironmentConfigFingerprint;
|
|
if (!expectedFingerprint) return true;
|
|
// Capture-time fingerprints exclude both runtime-only fields and the
|
|
// provider's secret-ref paths (see finishSetupSession); the runtime match
|
|
// must exclude the same set or configs that carry a secret ref can never
|
|
// match and the active template gets silently dropped.
|
|
const secretRefExcludePaths = [...(input.secretRefExcludePaths ?? [])];
|
|
const normalizedFingerprint = fingerprintEnvironmentSandboxProviderConfig(input.baseConfig, {
|
|
excludePaths: [
|
|
...ENVIRONMENT_CUSTOM_IMAGE_CONFIG_FINGERPRINT_EXCLUDED_PATHS,
|
|
...secretRefExcludePaths,
|
|
],
|
|
});
|
|
if (normalizedFingerprint === expectedFingerprint) return true;
|
|
// Backward compatibility for templates captured before runtime-only fields
|
|
// were excluded from the source fingerprint (secret-ref paths have always
|
|
// been excluded at capture time).
|
|
return fingerprintEnvironmentSandboxProviderConfig(input.baseConfig, {
|
|
excludePaths: secretRefExcludePaths,
|
|
}) === expectedFingerprint;
|
|
}
|
|
|
|
// Standard boot-source fields shared across sandbox providers. A change to any
|
|
// of these means the user asked for a different base, so a captured template
|
|
// no longer reflects the saved config and cannot simply be re-linked.
|
|
export const ENVIRONMENT_CUSTOM_IMAGE_TEMPLATE_SOURCE_FIELDS = [
|
|
"snapshot",
|
|
"image",
|
|
"template",
|
|
] as const;
|
|
|
|
export type EnvironmentCustomImageConfigChangeKind = "none" | "relinkable" | "breaking";
|
|
|
|
/**
|
|
* Classifies a saved-config change relative to an active captured template.
|
|
*
|
|
* - `none`: the template either already matched the new config, or was already
|
|
* detached before this change; nothing to reconcile.
|
|
* - `relinkable`: only fields that cannot affect the captured template's
|
|
* contents or reachability changed (for example a region hint), so the
|
|
* template's source fingerprint can be re-stamped to the new config.
|
|
* - `breaking`: a boot-source field or a provider-declared template identity
|
|
* path changed; the captured template no longer corresponds to the config
|
|
* and a fresh capture is required.
|
|
*/
|
|
export function classifyEnvironmentCustomImageConfigChange(input: {
|
|
template: EnvironmentCustomImageTemplate;
|
|
previousConfig: SandboxEnvironmentConfig;
|
|
nextConfig: SandboxEnvironmentConfig;
|
|
secretRefExcludePaths?: Iterable<string>;
|
|
templateIdentityPaths?: Iterable<string>;
|
|
}): EnvironmentCustomImageConfigChangeKind {
|
|
const secretRefExcludePaths = [...(input.secretRefExcludePaths ?? [])];
|
|
if (!environmentCustomImageTemplateMatchesBaseConfig({
|
|
template: input.template,
|
|
baseConfig: input.previousConfig,
|
|
secretRefExcludePaths,
|
|
})) {
|
|
return "none";
|
|
}
|
|
if (environmentCustomImageTemplateMatchesBaseConfig({
|
|
template: input.template,
|
|
baseConfig: input.nextConfig,
|
|
secretRefExcludePaths,
|
|
})) {
|
|
return "none";
|
|
}
|
|
const binding = resolveEnvironmentCustomImageRuntimeConfigBinding({
|
|
templateKind: input.template.templateKind,
|
|
metadata: input.template.metadata,
|
|
});
|
|
const breakingPaths = new Set<string>([
|
|
"provider",
|
|
binding.field,
|
|
...binding.unsetFields,
|
|
...ENVIRONMENT_CUSTOM_IMAGE_TEMPLATE_SOURCE_FIELDS,
|
|
...(input.templateIdentityPaths ?? []),
|
|
]);
|
|
const previous = input.previousConfig as Record<string, unknown>;
|
|
const next = input.nextConfig as Record<string, unknown>;
|
|
for (const path of breakingPaths) {
|
|
const before = readConfigValueAtPath(previous, path);
|
|
const after = readConfigValueAtPath(next, path);
|
|
if (stableStringify(before ?? null) !== stableStringify(after ?? null)) {
|
|
return "breaking";
|
|
}
|
|
}
|
|
return "relinkable";
|
|
}
|
|
|
|
// --- Operator relink action (server-owned boot-source classification) --------
|
|
//
|
|
// A saved config change moves the fingerprint and detaches an otherwise-valid
|
|
// template. The relink action re-stamps the fingerprint, but only after the
|
|
// server decides the boot source did not change. To decide that without the
|
|
// capture-time config, the capture persists a small, server-owned snapshot of
|
|
// the boot-relevant fields. The relink then compares that snapshot to the
|
|
// current config. The comparison runs on the server; the client never
|
|
// classifies.
|
|
|
|
export const ENVIRONMENT_CUSTOM_IMAGE_BOOT_RELEVANT_CONFIG_METADATA_KEY = "bootRelevantConfig";
|
|
export const ENVIRONMENT_CUSTOM_IMAGE_BOOT_RELEVANT_CONFIG_VERSION = 1;
|
|
// A driver-declared identity path that fails canonicalization is never trusted
|
|
// and never persisted verbatim. It records this fixed marker instead, which
|
|
// forces the fail-closed `unclassified` result at relink time.
|
|
export const ENVIRONMENT_CUSTOM_IMAGE_BOOT_RELEVANT_UNRESOLVED_PATH = "[unresolved-identity-path]";
|
|
|
|
const BOOT_RELEVANT_CONFIG_MAX_PATH_DEPTH = 8;
|
|
const BOOT_RELEVANT_CONFIG_PATH_SEGMENT_RE = /^[A-Za-z_][A-Za-z0-9_-]*$/;
|
|
// Prototype keys have an identifier shape but never name an own config field.
|
|
// A driver that declares one is hostile or broken. Reject it so the path fails
|
|
// closed as an unresolved identity path.
|
|
const BOOT_RELEVANT_CONFIG_RESERVED_SEGMENTS = new Set(["__proto__", "prototype", "constructor"]);
|
|
|
|
export type EnvironmentCustomImageRelinkClassification =
|
|
| "knob_only"
|
|
| "boot_source_drift"
|
|
| "unclassified";
|
|
|
|
/**
|
|
* Server-owned snapshot of the boot-relevant config fields at capture time. It
|
|
* carries the field values that decide the boot source, with every secret-ref
|
|
* path and every unresolvable driver path excluded (path name only, no value).
|
|
*/
|
|
export interface EnvironmentCustomImageBootRelevantConfig {
|
|
version: typeof ENVIRONMENT_CUSTOM_IMAGE_BOOT_RELEVANT_CONFIG_VERSION;
|
|
provider: string;
|
|
bindingField: string;
|
|
values: Record<string, unknown>;
|
|
excludedPaths: string[];
|
|
}
|
|
|
|
export interface EnvironmentCustomImageDriftedPath {
|
|
path: string;
|
|
from?: unknown;
|
|
to?: unknown;
|
|
}
|
|
|
|
/**
|
|
* Canonicalizes a config path as a bounded dot-path. Each segment must be a
|
|
* plain identifier and the depth is bounded. An invalid, ambiguous, or
|
|
* unresolvable path returns `null`; the caller must never persist the raw
|
|
* driver-supplied string.
|
|
*/
|
|
export function canonicalizeEnvironmentCustomImageConfigPath(raw: unknown): string | null {
|
|
if (typeof raw !== "string") return null;
|
|
const trimmed = raw.trim();
|
|
if (!trimmed) return null;
|
|
const segments = trimmed.split(".");
|
|
if (segments.length === 0 || segments.length > BOOT_RELEVANT_CONFIG_MAX_PATH_DEPTH) return null;
|
|
for (const segment of segments) {
|
|
if (!BOOT_RELEVANT_CONFIG_PATH_SEGMENT_RE.test(segment)) return null;
|
|
if (BOOT_RELEVANT_CONFIG_RESERVED_SEGMENTS.has(segment)) return null;
|
|
}
|
|
return segments.join(".");
|
|
}
|
|
|
|
/**
|
|
* Reports whether a candidate path overlaps any secret-ref path by exact,
|
|
* ancestor, or descendant containment.
|
|
*/
|
|
function environmentCustomImageConfigPathOverlapsSecret(
|
|
candidate: string,
|
|
secretPaths: Iterable<string>,
|
|
): boolean {
|
|
for (const raw of secretPaths) {
|
|
const secret = canonicalizeEnvironmentCustomImageConfigPath(raw);
|
|
if (!secret) continue;
|
|
if (candidate === secret) return true;
|
|
if (candidate.startsWith(`${secret}.`)) return true;
|
|
if (secret.startsWith(`${candidate}.`)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* The current boot-relevant path contract a provider driver declares. It names
|
|
* the config binding and the driver identity paths that decide the boot source
|
|
* now. A relink compares a persisted snapshot against this contract to detect a
|
|
* provider change since capture.
|
|
*/
|
|
export interface EnvironmentCustomImageBootRelevantContract {
|
|
binding: EnvironmentCustomImageRuntimeConfigBinding;
|
|
templateIdentityPaths?: Iterable<string>;
|
|
}
|
|
|
|
/**
|
|
* Computes the canonical candidate boot-relevant paths for a binding and its
|
|
* driver identity paths. Both the capture snapshot and the relink staleness
|
|
* check use this function, so they share one path set. `hasUnresolved` is true
|
|
* when any raw path fails canonicalization.
|
|
*/
|
|
export function environmentCustomImageBootRelevantCandidatePaths(
|
|
contract: EnvironmentCustomImageBootRelevantContract,
|
|
): { canonicalPaths: string[]; hasUnresolved: boolean } {
|
|
const canonicalPaths: string[] = [];
|
|
const seen = new Set<string>();
|
|
let hasUnresolved = false;
|
|
const rawCandidatePaths = [
|
|
contract.binding.field,
|
|
...contract.binding.unsetFields,
|
|
...ENVIRONMENT_CUSTOM_IMAGE_TEMPLATE_SOURCE_FIELDS,
|
|
...(contract.templateIdentityPaths ?? []),
|
|
];
|
|
for (const rawPath of rawCandidatePaths) {
|
|
const canonical = canonicalizeEnvironmentCustomImageConfigPath(rawPath);
|
|
if (!canonical) {
|
|
hasUnresolved = true;
|
|
continue;
|
|
}
|
|
if (seen.has(canonical)) continue;
|
|
seen.add(canonical);
|
|
canonicalPaths.push(canonical);
|
|
}
|
|
return { canonicalPaths, hasUnresolved };
|
|
}
|
|
|
|
/**
|
|
* Builds the capture-time boot-relevant snapshot from the parsed config only.
|
|
* Candidate paths are the runtime binding field, the binding unset fields, the
|
|
* standard boot-source fields, and every driver identity path. A secret-ref
|
|
* overlap or an unresolvable path is recorded in `excludedPaths` with no value.
|
|
*/
|
|
export function buildEnvironmentCustomImageBootRelevantConfig(input: {
|
|
config: SandboxEnvironmentConfig;
|
|
binding: EnvironmentCustomImageRuntimeConfigBinding;
|
|
templateIdentityPaths?: Iterable<string>;
|
|
secretRefExcludePaths?: Iterable<string>;
|
|
}): EnvironmentCustomImageBootRelevantConfig {
|
|
const config = input.config as Record<string, unknown>;
|
|
const secretPaths = [...(input.secretRefExcludePaths ?? [])];
|
|
// A null-prototype map is a second guard: a reserved segment assignment can
|
|
// never mutate the prototype, so a hostile path cannot vanish from `values`.
|
|
const values: Record<string, unknown> = Object.create(null);
|
|
const excludedPaths = new Set<string>();
|
|
|
|
const { canonicalPaths, hasUnresolved } = environmentCustomImageBootRelevantCandidatePaths({
|
|
binding: input.binding,
|
|
templateIdentityPaths: input.templateIdentityPaths,
|
|
});
|
|
if (hasUnresolved) {
|
|
excludedPaths.add(ENVIRONMENT_CUSTOM_IMAGE_BOOT_RELEVANT_UNRESOLVED_PATH);
|
|
}
|
|
for (const canonical of canonicalPaths) {
|
|
if (environmentCustomImageConfigPathOverlapsSecret(canonical, secretPaths)) {
|
|
excludedPaths.add(canonical);
|
|
continue;
|
|
}
|
|
const value = readConfigValueAtPath(config, canonical);
|
|
// An absent field is stored as `null` so that "absent then, absent now"
|
|
// compares equal at relink time.
|
|
values[canonical] = value === undefined ? null : value;
|
|
}
|
|
return {
|
|
version: ENVIRONMENT_CUSTOM_IMAGE_BOOT_RELEVANT_CONFIG_VERSION,
|
|
provider: input.config.provider,
|
|
bindingField: input.binding.field,
|
|
values,
|
|
excludedPaths: [...excludedPaths],
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Reports whether a persisted snapshot no longer matches the current provider
|
|
* boot-relevant contract. A provider plugin can change its config binding or
|
|
* its identity paths after capture. When it does, a field that is boot-relevant
|
|
* now but absent from the snapshot would compare equal by absence and hide real
|
|
* drift. The check fails closed on:
|
|
*
|
|
* - a binding field that differs from the captured `bindingField`;
|
|
* - a current identity path the snapshot never covered (neither a value nor an
|
|
* excluded path);
|
|
* - a current contract that itself carries an unresolvable identity path.
|
|
*/
|
|
export function environmentCustomImageBootRelevantSnapshotIsStale(input: {
|
|
bootRelevantConfig: EnvironmentCustomImageBootRelevantConfig;
|
|
currentContract: EnvironmentCustomImageBootRelevantContract;
|
|
}): boolean {
|
|
const boot = input.bootRelevantConfig;
|
|
if (input.currentContract.binding.field !== boot.bindingField) return true;
|
|
const { canonicalPaths, hasUnresolved } = environmentCustomImageBootRelevantCandidatePaths(
|
|
input.currentContract,
|
|
);
|
|
if (hasUnresolved) return true;
|
|
const covered = new Set<string>([
|
|
...Object.keys(boot.values),
|
|
...boot.excludedPaths,
|
|
]);
|
|
return canonicalPaths.some((path) => !covered.has(path));
|
|
}
|
|
|
|
/**
|
|
* Reads and validates the persisted boot-relevant snapshot. Returns `null` for
|
|
* a legacy template with no snapshot or for a malformed shape; both classify as
|
|
* `unclassified` (fail closed).
|
|
*/
|
|
export function readEnvironmentCustomImageBootRelevantConfig(
|
|
metadata: Record<string, unknown> | null | undefined,
|
|
): EnvironmentCustomImageBootRelevantConfig | null {
|
|
const raw = metadata?.[ENVIRONMENT_CUSTOM_IMAGE_BOOT_RELEVANT_CONFIG_METADATA_KEY];
|
|
if (!isRecord(raw)) return null;
|
|
if (raw.version !== ENVIRONMENT_CUSTOM_IMAGE_BOOT_RELEVANT_CONFIG_VERSION) return null;
|
|
if (typeof raw.provider !== "string" || typeof raw.bindingField !== "string") return null;
|
|
if (!isRecord(raw.values)) return null;
|
|
if (!Array.isArray(raw.excludedPaths)) return null;
|
|
const excludedPaths = raw.excludedPaths.filter(
|
|
(entry): entry is string => typeof entry === "string",
|
|
);
|
|
return {
|
|
version: ENVIRONMENT_CUSTOM_IMAGE_BOOT_RELEVANT_CONFIG_VERSION,
|
|
provider: raw.provider,
|
|
bindingField: raw.bindingField,
|
|
values: raw.values,
|
|
excludedPaths,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Classifies the drift between the capture-time boot-relevant snapshot and the
|
|
* current parsed config.
|
|
*
|
|
* - `knob_only`: the snapshot is present, no path was excluded, and every value
|
|
* still matches. The fingerprint can be re-stamped without confirmation.
|
|
* - `boot_source_drift`: a value-bearing path differs. The operator must
|
|
* confirm before the re-stamp.
|
|
* - `unclassified`: no snapshot, an excluded path, a provider mismatch, or a
|
|
* snapshot that no longer matches the current provider contract. The server
|
|
* cannot verify the boot source; the operator must confirm (fail closed).
|
|
*
|
|
* `driftedPaths` carries raw `from`/`to` values only for value-bearing paths
|
|
* that passed containment at capture. Excluded paths carry the path name only.
|
|
*
|
|
* `currentContract` is the current provider boot-relevant contract. When the
|
|
* caller cannot resolve the driver, it passes `null`; the server then cannot
|
|
* verify the boot source and the result is `unclassified` (fail closed).
|
|
*/
|
|
export function classifyEnvironmentCustomImageBootRelevantDrift(input: {
|
|
bootRelevantConfig: EnvironmentCustomImageBootRelevantConfig | null;
|
|
currentConfig: SandboxEnvironmentConfig;
|
|
currentContract: EnvironmentCustomImageBootRelevantContract | null;
|
|
}): {
|
|
classification: EnvironmentCustomImageRelinkClassification;
|
|
driftedPaths: EnvironmentCustomImageDriftedPath[];
|
|
} {
|
|
const boot = input.bootRelevantConfig;
|
|
if (!boot) return { classification: "unclassified", driftedPaths: [] };
|
|
// Without the current provider contract the boot source cannot be verified
|
|
// against a possible identity-path change; fail closed.
|
|
if (!input.currentContract) return { classification: "unclassified", driftedPaths: [] };
|
|
// A provider change since capture (new binding or new identity path) makes
|
|
// the persisted snapshot untrustworthy; fail closed.
|
|
if (environmentCustomImageBootRelevantSnapshotIsStale({
|
|
bootRelevantConfig: boot,
|
|
currentContract: input.currentContract,
|
|
})) {
|
|
return { classification: "unclassified", driftedPaths: [] };
|
|
}
|
|
const current = input.currentConfig as Record<string, unknown>;
|
|
|
|
const driftedPaths: EnvironmentCustomImageDriftedPath[] = [];
|
|
let hasValueDrift = false;
|
|
for (const [path, capturedValue] of Object.entries(boot.values)) {
|
|
const currentValue = readConfigValueAtPath(current, path);
|
|
if (stableStringify(capturedValue ?? null) !== stableStringify(currentValue ?? null)) {
|
|
hasValueDrift = true;
|
|
driftedPaths.push({ path, from: capturedValue ?? null, to: currentValue ?? null });
|
|
}
|
|
}
|
|
for (const path of boot.excludedPaths) {
|
|
driftedPaths.push({ path });
|
|
}
|
|
const providerMismatch = boot.provider !== input.currentConfig.provider;
|
|
if (boot.excludedPaths.length > 0 || providerMismatch) {
|
|
return { classification: "unclassified", driftedPaths };
|
|
}
|
|
if (hasValueDrift) {
|
|
return { classification: "boot_source_drift", driftedPaths };
|
|
}
|
|
return { classification: "knob_only", driftedPaths: [] };
|
|
}
|
|
|
|
/**
|
|
* Removes the server-only boot-relevant snapshot from a template's metadata.
|
|
* The snapshot exists to classify a later relink and holds raw boot-source
|
|
* config values. It must never reach an API response. The runtime keeps it in
|
|
* the persisted row and reads it straight from the row at relink time.
|
|
*/
|
|
export function stripInternalEnvironmentCustomImageTemplateMetadata(
|
|
metadata: Record<string, unknown> | null | undefined,
|
|
): Record<string, unknown> | null {
|
|
if (!metadata) return null;
|
|
if (!(ENVIRONMENT_CUSTOM_IMAGE_BOOT_RELEVANT_CONFIG_METADATA_KEY in metadata)) return metadata;
|
|
const rest = { ...metadata };
|
|
delete rest[ENVIRONMENT_CUSTOM_IMAGE_BOOT_RELEVANT_CONFIG_METADATA_KEY];
|
|
return rest;
|
|
}
|
|
|
|
export function environmentCustomImageTemplateFromRow(row: TemplateRow): EnvironmentCustomImageTemplate {
|
|
return {
|
|
id: row.id,
|
|
environmentId: row.environmentId,
|
|
provider: row.provider,
|
|
templateKind: readEnvironmentCustomImageTemplateKind(row.templateKind),
|
|
templateRef: row.templateRef,
|
|
sourceTemplateRef: row.sourceTemplateRef ?? null,
|
|
sourceEnvironmentConfigFingerprint: row.sourceEnvironmentConfigFingerprint ?? null,
|
|
status: row.status,
|
|
createdByUserId: row.createdByUserId ?? null,
|
|
createdByAgentId: row.createdByAgentId ?? null,
|
|
capturedAt: row.capturedAt ?? null,
|
|
lastUsedAt: row.lastUsedAt ?? null,
|
|
supersededByTemplateId: row.supersededByTemplateId ?? null,
|
|
// The boot-relevant snapshot is server-internal; keep it out of every
|
|
// template response. The relink path reads it from the persisted row.
|
|
metadata: stripInternalEnvironmentCustomImageTemplateMetadata(row.metadata),
|
|
createdAt: row.createdAt,
|
|
updatedAt: row.updatedAt,
|
|
};
|
|
}
|
|
|
|
export async function resolveActiveEnvironmentCustomImageTemplateForRuntime(
|
|
db: Db,
|
|
input: {
|
|
environmentId: string;
|
|
baseConfig: SandboxEnvironmentConfig;
|
|
runtimeConfig: SandboxEnvironmentConfig;
|
|
secretRefExcludePaths?: Iterable<string>;
|
|
now?: Date;
|
|
readOnly?: boolean;
|
|
onResolvedTemplate?: (identity: { id: string; capturedAt: string | null; templateKind: string; bindingField: string }) => void;
|
|
},
|
|
): Promise<SandboxEnvironmentConfig> {
|
|
const row = await db
|
|
.select()
|
|
.from(environmentCustomImageTemplates)
|
|
.where(and(
|
|
eq(environmentCustomImageTemplates.environmentId, input.environmentId),
|
|
eq(environmentCustomImageTemplates.provider, input.baseConfig.provider),
|
|
eq(environmentCustomImageTemplates.status, "active"),
|
|
))
|
|
.orderBy(desc(environmentCustomImageTemplates.capturedAt), desc(environmentCustomImageTemplates.createdAt))
|
|
.then((rows) => rows[0] ?? null);
|
|
if (!row) return input.runtimeConfig;
|
|
|
|
const active = environmentCustomImageTemplateFromRow(row);
|
|
if (!active.templateRef) return input.runtimeConfig;
|
|
if (!environmentCustomImageTemplateMatchesBaseConfig({
|
|
template: active,
|
|
baseConfig: input.baseConfig,
|
|
secretRefExcludePaths: input.secretRefExcludePaths,
|
|
})) {
|
|
return input.runtimeConfig;
|
|
}
|
|
|
|
// An active template is an explicit, environment+provider-scoped artifact: the
|
|
// captured snapshot/image fully replaces the base image at create time, so it is
|
|
// applied whenever the image/template-defining parts of the base config still
|
|
// match. Runtime-only knobs such as lease reuse, timeouts, and resource hints
|
|
// are excluded from the fingerprint so those edits do not discard the capture.
|
|
const now = input.now ?? new Date();
|
|
input.onResolvedTemplate?.({ id: row.id, capturedAt: row.capturedAt?.toISOString() ?? null,
|
|
templateKind: row.templateKind ?? "unknown", bindingField: resolveEnvironmentCustomImageRuntimeConfigBinding(row).field });
|
|
if (!input.readOnly) await db
|
|
.update(environmentCustomImageTemplates)
|
|
.set({ lastUsedAt: now, updatedAt: now })
|
|
.where(eq(environmentCustomImageTemplates.id, active.id));
|
|
return applyCustomImageTemplateToSandboxConfig(input.runtimeConfig, active);
|
|
}
|