Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions docs/execution-boundaries.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,26 @@ Amp thread URL. Amp does not declare output retrieval, so Factorize does not
ingest thread contents. Amp credentials are dashboard-only; REST and MCP expose
only non-secret target metadata and capabilities.

The prompt is delivered as part of direct process launch. The launch receipt is
persisted before polling begins so restarts can resume observation and cleanup.
For exe.dev runs, the scheduler encrypts and stores the exact launch payload
(rendered prompt, appended runtime instructions, harness and trace configuration,
or code script and input context) before VM provisioning. The first snapshot is
retained across launch retries. Provisioning transfers only the guest launcher
and identity helper, keeping prompts and scripts out of exe.dev's 64 KB command
request limit. Apply migration `0053_run_launch_payload` before deploying this
startup path.

The launcher fetches `GET /api/v1/runtime-launch` through its local identity
helper before starting the harness. The endpoint requires the same vendor-signed
VM/run binding as other runtime operations, returns only the calling active
run's snapshot, requires no application scopes, rejects non-run identities and
stopping or terminal runs, and disables response caching. Downloads are limited
to 32 MiB, refuse redirects and mismatched run IDs, and retry transient failures
up to three times with a ten-second socket timeout. Exhausted or invalid fetches
record a launcher failure without starting the job. The harness receives the
prompt through stdin as before.

The launch receipt is persisted before polling begins so restarts can resume
observation and cleanup.

## Job invocation boundary

Expand Down
80 changes: 80 additions & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1632,6 +1632,28 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/runtime-launch": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* Fetch this VM's immutable launch payload
* @description Requires the vendor-verified identity of an active run. Returns only that run's encrypted-at-rest scheduler snapshot, including the rendered prompt and harness or code context. No application scope is required. Sessions, API keys, OAuth clients, other runs and terminal runs cannot retrieve it. Responses are never cached.
*
* Requires vendor-verified run identity; sessions and other bearer tokens cannot call this operation.
*/
get: operations["get_api_v1_runtime_launch"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/runtime-context": {
parameters: {
query?: never;
Expand Down Expand Up @@ -6994,6 +7016,64 @@ export interface operations {
503: components["responses"]["Error503"];
};
};
get_api_v1_runtime_launch: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Launch payload for the calling run */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** @constant */
version: 1;
/** Format: uuid */
runId: string;
traceSources?: {
[key: string]: unknown;
};
prompt: string;
harness: {
executable: string;
args: string[];
env: {
[key: string]: string;
};
};
} | {
/** @constant */
version: 1;
/** Format: uuid */
runId: string;
traceSources?: {
[key: string]: unknown;
};
code: {
script: string;
context: {
[key: string]: unknown;
};
};
};
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
get_api_v1_runtime_context: {
parameters: {
query?: never;
Expand Down
3 changes: 3 additions & 0 deletions packages/api/migrations/0053_run_launch_payload.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- Exact scheduler launch snapshots; plaintext prompts and scripts remain encrypted.
ALTER TABLE app.runs ADD COLUMN encrypted_launch_payload text;
INSERT INTO app.schema_migrations(version) VALUES ('0053_run_launch_payload') ON CONFLICT DO NOTHING;
15 changes: 11 additions & 4 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { queryOf } from "./query-params";
import { launchPayloadResponse } from "./launch-payload";
import { searchResponse } from "./search-contracts";
import { consentPreviewInput, consentPreviewResponse, consentDecisionInput, consentDecisionResponse } from "./consent-api";
import { exeConnection, integrationStatus, authorizedClient, accessToken, createdAccessToken, savedExe, testedExe, savedAmp, savedTail, okResult } from "./settings-contracts";
Expand Down Expand Up @@ -37,6 +38,7 @@ export interface RouteContract {
path: string;
scope: string | string[];
ownerSession: boolean;
vendorIdentityOnly?: boolean;
authOperation?: AuthAction;
body?: z.ZodType;
maxBodyBytes?: number;
Expand Down Expand Up @@ -150,7 +152,7 @@ function route(
documentation: RouteContract["documentation"],
execute: RouteContract["execute"],
options: Partial<
Pick<RouteContract, "body" | "maxBodyBytes" | "query" | "ownerSession" | "parameters" | "authOperation">
Pick<RouteContract, "body" | "maxBodyBytes" | "query" | "ownerSession" | "vendorIdentityOnly" | "parameters" | "authOperation">
> = {},
): RouteContract {
const keys = [...path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
Expand Down Expand Up @@ -185,7 +187,7 @@ function route(
// Legacy route labels are translated by resource and effect; they are never
// accepted as newly issued scopes.
function scopeForRoute(path: string, legacy: string): string | string[] {
if (path === "/api/v1/runtime-context" || path === "/api/v1/runtime-integrations") return [];
if (path === "/api/v1/runtime-context" || path === "/api/v1/runtime-integrations" || path === "/api/v1/runtime-launch") return [];
if (legacy === "runs:write" && path.endsWith("/report-error")) return "runs:write";
if (legacy === "runs:write" && path === "/api/v1/runs/{runId}" ) return "runs:write";
if (legacy === "runs:read" && path === "/api/v1/search") return "jobs:read+runs:read";
Expand Down Expand Up @@ -846,6 +848,11 @@ export const API_ROUTES: RouteContract[] = [
(service, { params, body }) => service.invokeJob(params.jobId, body),
{ body: manualInvocationSchema },
),
route("GET", "/api/v1/runtime-launch", "runs:read", {
summary: "Fetch this VM's immutable launch payload",
description: "Requires the vendor-verified identity of an active run. Returns only that run's encrypted-at-rest scheduler snapshot, including the rendered prompt and harness or code context. No application scope is required. Sessions, API keys, OAuth clients, other runs and terminal runs cannot retrieve it. Responses are never cached.",
responses: { "200": { description: "Launch payload for the calling run", content: { "application/json": { schema: jsonSchema(launchPayloadResponse, "output") } } } } },
service => service.getRuntimeLaunchPayload(), { vendorIdentityOnly: true }),
route("GET", "/api/v1/runtime-context", "runs:read", {
summary: "Inspect the current runtime identity and scopes",
description: "Returns the verified calling identity and effective scopes without credentials. Requires a verified active identity but no application-resource scope; callers with zero scopes can inspect only their own identity. Execution provisioning uses this operation to verify the dedicated run proxy. Execution VMs must not have additional shared Factorize proxy attachments.",
Expand Down Expand Up @@ -1279,15 +1286,15 @@ export function generateOpenApi() {
description: [
route.documentation.description,
route.authOperation || (Array.isArray(route.scope) && route.scope.length === 0) ? undefined : `Requires the ${Array.isArray(route.scope) ? route.scope.join(" and ") : route.scope.replaceAll("+", " and ")} scope${Array.isArray(route.scope) || route.scope.includes("+") ? "s" : ""}.`,
route.authOperation ? undefined : route.ownerSession
route.vendorIdentityOnly ? "Requires vendor-verified run identity; sessions and other bearer tokens cannot call this operation." : route.authOperation ? undefined : route.ownerSession
? "An interactive owner session is required; bearer tokens cannot call this operation."
: "Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session.",
]
.filter(Boolean)
.join("\n\n"),
operationId: `${route.method.toLowerCase()}_${route.path.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_|_$/g, "")}`,
tags: [route.path.split("/")[3]],
security: route.authOperation ? (route.ownerSession ? [{ cookieAuth: [] }] : []) : route.ownerSession ? [{ cookieAuth: [] }] : [{ bearerAuth: [] }, { vendorRunIdentity: [], runIdentityHeader: [] }, { cookieAuth: [] }],
security: route.vendorIdentityOnly ? [{ vendorRunIdentity: [], runIdentityHeader: [] }] : route.authOperation ? (route.ownerSession ? [{ cookieAuth: [] }] : []) : route.ownerSession ? [{ cookieAuth: [] }] : [{ bearerAuth: [] }, { vendorRunIdentity: [], runIdentityHeader: [] }, { cookieAuth: [] }],
...(route.authOperation ? { "x-browser-auth-operation": route.authOperation } : { "x-required-scope": route.scope }),
"x-owner-session-required": route.ownerSession,
...(parameters.length ? { parameters } : {}),
Expand Down
8 changes: 5 additions & 3 deletions packages/api/src/exe-vm-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { runArtifactTarget } from "./run-artifact-target";
import { assertExeVmIsolation } from "./exe-vm-isolation";
import { RUN_IDENTITY_GUEST_HELPER } from "./run-identity-guest-helper";
import { FACTORIZE_JOB_LAUNCHER } from "./factorize-job-launcher";
import { serializeLaunchPayload } from "./launch-payload";

const API = "https://exe.dev/exec";
const capabilities = ["output", "recovery", "stop"] as const;
Expand Down Expand Up @@ -210,6 +211,7 @@ export class ExeVmBackend implements ExecutionBackend {

async launch(request: LaunchRequest): Promise<LaunchReceipt> {
const connection = this.connection as ExeRunConnection;
if (request.fetchLaunchPayload && !request.runIdentity) throw new Error("Run identity is required to fetch the launch payload");
if (!request.code && (!connection.agentKind || !request.harness)) throw new Error("The job is missing its agent harness launch plan");
if (request.traceSources) validateTraceSources(request.traceSources);
const handle: RunHandle = request.reservation ?? { backendKind: this.kind, id: vmNameFor(request.runId) };
Expand Down Expand Up @@ -244,7 +246,7 @@ export class ExeVmBackend implements ExecutionBackend {
}

const code = request.code, output = request.traceSources?.primary.formatVersion === "codex-exec-jsonl" ? request.traceSources.primary.path : "/tmp/factorize.log", unit = vm;
const launchPayload = JSON.stringify({ version: 1, runId: request.runId, ...(code ? { code } : { prompt: request.prompt, harness: request.harness }), ...(request.traceSources ? { traceSources: request.traceSources } : {}) });
const launchPayload = request.fetchLaunchPayload ? null : serializeLaunchPayload(request);
const launchPayloadPath = "/home/exedev/.factorize-job/launch.json";
const identitySetup = request.runIdentity ? [
"command -v node >/dev/null && command -v curl >/dev/null",
Expand All @@ -262,8 +264,8 @@ export class ExeVmBackend implements ExecutionBackend {
...(request.traceSources?.primary.kind === "execution_stream" ? [`mkdir -p -- ${shellAtom(request.traceSources.primary.path.slice(0, request.traceSources.primary.path.lastIndexOf("/")) || "/")}`, `touch -- ${shellAtom(request.traceSources.primary.path)}`] : []),
"sudo install -d -o exedev -g exedev -m 0700 /home/exedev/.factorize-job",
`printf '%s' ${shellAtom(base64(FACTORIZE_JOB_LAUNCHER))} | sudo sh -c ${shellAtom("base64 -d > /usr/local/bin/factorize-job && chmod 0755 /usr/local/bin/factorize-job")}`,
`printf '%s' ${shellAtom(base64(launchPayload))} | base64 -d > ${shellAtom(launchPayloadPath)} && sudo chown exedev:exedev ${shellAtom(launchPayloadPath)}`,
`if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=null --property=StandardOutput=${output === "/tmp/factorize.log" ? `append:${output}` : shellAtom(`append:${output}`)} --property=StandardError=append:/tmp/factorize.stderr /bin/sh -c ${shellAtom(`exec ${request.runIdentity ? "/usr/bin/env FACTORIZE_PROXY_URL=http://127.0.0.1:18180 " : ""}/usr/local/bin/factorize-job launch --foreground < ${launchPayloadPath}`)}; fi`,
...(launchPayload === null ? [] : [`printf '%s' ${shellAtom(base64(launchPayload))} | base64 -d > ${shellAtom(launchPayloadPath)} && sudo chown exedev:exedev ${shellAtom(launchPayloadPath)}`]),
`if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=null --property=StandardOutput=${output === "/tmp/factorize.log" ? `append:${output}` : shellAtom(`append:${output}`)} --property=StandardError=append:/tmp/factorize.stderr /bin/sh -c ${shellAtom(`exec ${request.runIdentity ? "/usr/bin/env FACTORIZE_PROXY_URL=http://127.0.0.1:18180 " : ""}/usr/local/bin/factorize-job launch --foreground ${request.fetchLaunchPayload ? `--fetch-payload ${shellAtom(request.runId)}` : `< ${launchPayloadPath}`}`)}; fi`,
"echo started",
].join("; ");
if (request.traceSources?.primary.formatVersion === "codex-exec-jsonl") {
Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ export interface LaunchRequest {
prompt: string;
/** Public backend configuration only; requests must use fresh vendor identity. */
runIdentity?: { backendOrigin: string };
/** The exact payload has been persisted for the VM to fetch with its vendor identity. */
fetchLaunchPayload?: boolean;
traceSources?: TraceSources;
harness?: { executable: string; args: string[]; env: Record<string, string> };
code?: { script: string; context: Record<string, unknown> };
Expand Down
42 changes: 37 additions & 5 deletions packages/api/src/factorize-job-launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import re
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request

ROOT = pathlib.Path('/home/exedev/.factorize-job')
PAYLOAD = ROOT / 'launch.json'
Expand All @@ -27,15 +30,40 @@ def save(path, value):
try: os.unlink(temp)
except FileNotFoundError: pass

def load_payload():
raw = sys.stdin.buffer.read(32 * 1024 * 1024 + 1)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None

def fetch_payload(run_id):
proxy = os.environ.get('FACTORIZE_PROXY_URL', '')
if not re.fullmatch(r'http://127\.0\.0\.1:[0-9]+', proxy):
raise ValueError('launch payload requires the local identity helper')
# Never route the local helper through the image's native HTTP proxy.
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
for attempt in range(3):
try:
with opener.open(proxy + '/api/v1/runtime-launch', timeout=10) as response:
return response.read(32 * 1024 * 1024 + 1)
except urllib.error.HTTPError as error:
if error.code not in (408, 429, 500, 502, 503, 504):
raise RuntimeError('launch payload fetch rejected (HTTP %s)' % error.code) from None
except (urllib.error.URLError, TimeoutError, OSError):
pass
if attempt < 2:
time.sleep(attempt + 1)
raise RuntimeError('launch payload fetch failed after 3 attempts')

def load_payload(run_id=None):
raw = fetch_payload(run_id) if run_id else sys.stdin.buffer.read(32 * 1024 * 1024 + 1)
if len(raw) > 32 * 1024 * 1024:
raise ValueError('launch payload exceeds 32 MiB')
value = json.loads(raw)
if not isinstance(value, dict) or value.get('version') != 1:
raise ValueError('unsupported launch payload')
if ('code' in value) == ('harness' in value):
raise ValueError('launch payload must contain code or harness')
if run_id and value.get('runId') != run_id:
raise ValueError('launch payload run binding mismatch')
return value

def child_command(payload):
Expand Down Expand Up @@ -69,7 +97,7 @@ def child_command(payload):
env['FACTORIZE_RESULT_PATH'] = str(RESULT)
return [harness['executable'], *harness['args']], str(payload.get('prompt', '')).encode(), env

def launch(foreground=False):
def launch(foreground=False, run_id=None):
ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
if STATE.exists():
current = json.loads(STATE.read_text())
Expand All @@ -78,7 +106,8 @@ def launch(foreground=False):
try: os.kill(pid, 0)
except ProcessLookupError: pass
else: raise RuntimeError('a Factorize job is already active')
payload = load_payload()
save(STATE, {'state': 'starting'})
payload = load_payload(run_id)
source = payload.get('traceSources', {}).get('primary', {})
trace_path = source.get('path') if source.get('kind') == 'execution_stream' else None
if trace_path:
Expand Down Expand Up @@ -141,10 +170,13 @@ if __name__ == '__main__':
try:
if sys.argv[1:] == ['launch']: launch()
elif sys.argv[1:] == ['launch', '--foreground']: launch(foreground=True)
elif len(sys.argv) == 5 and sys.argv[1:4] == ['launch', '--foreground', '--fetch-payload']: launch(foreground=True, run_id=sys.argv[4])
elif len(sys.argv) == 4 and sys.argv[1] == '_run': run(json.loads(sys.argv[2]), sys.argv[3])
elif sys.argv[1:] == ['status']: raise SystemExit(status())
else: raise ValueError('usage: factorize-job launch [--foreground]|status')
else: raise ValueError('usage: factorize-job launch [--foreground [--fetch-payload RUN_ID]]|status')
except Exception as error:
if sys.argv[1:2] == ['launch'] and STATE.exists() and json.loads(STATE.read_text()).get('state') == 'starting':
save(STATE, {'state': 'exited', 'exitCode': 1, 'error': str(error)[:500]})
print('factorize-job: ' + str(error)[:500], file=sys.stderr)
raise SystemExit(1)
`;
Loading
Loading