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
2 changes: 2 additions & 0 deletions packages/app/migrations/0007_harness_diagnostics.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- Terminal execution evidence is independent of artifact and cleanup errors.
ALTER TABLE app.runs ADD COLUMN execution_diagnostics jsonb;
46 changes: 34 additions & 12 deletions packages/app/src/exe-vm-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import type { BackendCommandResult, ExecutionBackend, ExecutionObservation, Laun
import { base64 } from "./crypto";
import { shellAtom, type ExeConnection, type ExeRunConnection } from "./exe";

import { HARNESS_LOG_LIMIT, safeDiagnosticText } from "./harness-diagnostics";

const API = "https://exe.dev/exec";
const capabilities = ["output", "recovery", "stop"] as const;

Expand Down Expand Up @@ -101,31 +103,51 @@ export class ExeVmBackend implements ExecutionBackend {
"mkdir -p /home/exedev/workspace",
"cd /home/exedev/workspace",
`printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md`,
`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=file:/tmp/factorize-prompt.md --property=StandardOutput=append:${output} --property=StandardError=append:${output} ${harnessCommand(request.harness)}; fi`,
`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=file:/tmp/factorize-prompt.md --property=StandardOutput=append:${output} --property=StandardError=append:/tmp/factorize.stderr ${harnessCommand(request.harness)}; fi`,
"echo started",
].join("; ");
let started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`);
const accepted = (result: BackendCommandResult) => result.ok && result.body.trim() === "started";
for (let attempt = 1; !accepted(started) && attempt < 5; attempt++) started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`);
if (!accepted(started)) {
const cleanup = await this.deleteVm(vm);
const detail = `VM provisioning failed (${started.status}): ${started.body.slice(0, 500)}${cleanup.ok ? "" : `; cleanup also failed: ${cleanup.body.slice(0, 200)}`}`;
const detail = `VM provisioning failed (${started.status}): ${safeDiagnosticText(started.body, 500)}`;
return { handle: { backendKind: this.kind, id: vm }, destinationUrl: `https://${vm}.exe.xyz/`, capabilities, observation: { state: "failed", detail, command: started }, command: started };
}
return { handle: { backendKind: this.kind, id: vm }, destinationUrl: `https://${vm}.exe.xyz/`, capabilities, observation: { state: "running", command: started }, command: started };
}

async inspect(handle: RunHandle): Promise<ExecutionObservation> {
const vm = this.vm(handle);
const inspect = `unit=${shellAtom(vm)}; load=$(sudo systemctl show "$unit" --property=LoadState --value 2>/dev/null || true); active=$(sudo systemctl show "$unit" --property=ActiveState --value 2>/dev/null || true); sub=$(sudo systemctl show "$unit" --property=SubState --value 2>/dev/null || true); result=$(sudo systemctl show "$unit" --property=Result --value 2>/dev/null || true); code=$(sudo systemctl show "$unit" --property=ExecMainStatus --value 2>/dev/null || true); if [ "$load" != loaded ]; then printf missing; elif [ "$sub" = running ] || [ "$sub" = start ] || [ "$active" = activating ] || [ "$active" = deactivating ]; then printf running; elif [ "$result" = success ] && [ "$code" = 0 ]; then printf succeeded; else printf failed; fi`;
const result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(inspect)}`);
if (!result.ok) return result.status >= 500
? { state: "running", detail: `VM inspection is temporarily unavailable (${result.status})`, command: result }
: { state: "failed", detail: `The run-owned VM is unavailable (${result.status}): ${result.body.slice(0, 300)}`, command: result };
const state = result.body.trim();
if (state === "succeeded") return { state: "succeeded", command: result };
if (state === "running") return { state: "running", command: result };
return { state: "failed", detail: state === "missing" ? "The run supervisor disappeared before recording a result." : "The supervised agent process exited unsuccessfully.", command: result };
const inspect = `sudo systemctl show ${shellAtom(vm)} --property=LoadState,ActiveState,SubState,Result,ExecMainCode,ExecMainStatus`;
let response: BackendCommandResult;
try { response = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(inspect)}`); }
catch { return { state: "running", detail: "VM inspection is temporarily unavailable" }; }
// systemctl can return nonzero for a missing unit, but still emits LoadState.
if (!response.ok && !response.body.includes("LoadState=not-found")) return ![404, 410].includes(response.status)
? { state: "running", detail: `VM inspection is temporarily unavailable (${response.status})` }
: { state: "failed", detail: `The run-owned VM is unavailable (${response.status})` };
const properties = Object.fromEntries(response.body.split("\n").filter(line => /^[A-Za-z]+=/.test(line)).map(line => { const index = line.indexOf("="); return [line.slice(0, index), line.slice(index + 1).trim()]; }));
const label = (name: string) => /^[a-z-]{1,64}$/.test(properties[name] ?? "") ? properties[name] : "";
const number = (name: string) => /^\d{1,10}$/.test(properties[name] ?? "") ? Number(properties[name]) : null;
const systemd = { loadState: label("LoadState"), activeState: label("ActiveState"), subState: label("SubState"), result: label("Result"), execMainCode: number("ExecMainCode"), execMainStatus: number("ExecMainStatus") };
if (!systemd.loadState) return { state: "running", detail: "VM inspection returned incomplete supervisor metadata" };
if (systemd.loadState !== "loaded") return { state: "failed", systemd, detail: "The run supervisor disappeared before recording a result." };
if (["running", "start"].includes(systemd.subState) || ["activating", "deactivating"].includes(systemd.activeState)) return { state: "running", systemd };
if (!systemd.activeState || !systemd.subState || !systemd.result || systemd.execMainStatus === null || systemd.execMainCode === null) return { state: "running", detail: "VM inspection returned incomplete supervisor metadata" };
if (systemd.result === "success" && systemd.execMainStatus === 0) return { state: "succeeded", systemd };
return { state: "failed", systemd, detail: `The supervised agent process exited unsuccessfully (Result=${systemd.result}, ExecMainCode=${systemd.execMainCode}, ExecMainStatus=${systemd.execMainStatus}).` };
}

async readHarnessLog(handle: RunHandle): Promise<string> {
// Read the first bounded bytes: starting in the middle of a credential could evade redaction.
// Old VMs have only the combined log.
const remote = `if [ -f /tmp/factorize.stderr ]; then head -c ${HARNESS_LOG_LIMIT} /tmp/factorize.stderr; else head -c ${HARNESS_LOG_LIMIT} /tmp/factorize.log; fi`;
const response = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(remote)}`);
if (!response.ok) throw new Error(`Harness log collection failed (${response.status})`);
// Drop a possibly cut final line before redaction. Never retain a partial credential.
const text = new TextEncoder().encode(response.body).length >= HARNESS_LOG_LIMIT
? response.body.slice(0, response.body.lastIndexOf("\n") + 1) + "\n[Harness log truncated]\n" : response.body;
return safeDiagnosticText(text, HARNESS_LOG_LIMIT);
}

async readOutput(handle: RunHandle): Promise<string | null> {
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export interface LaunchRequest {
export interface RunHandle { backendKind: string; id: string; }

export interface ExecutionObservation {
systemd?: import("./harness-diagnostics").ExecutionDiagnostics["systemd"];
state: ExecutionState;
detail?: string;
command?: BackendCommandResult;
Expand Down
4 changes: 2 additions & 2 deletions packages/app/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,9 @@ export class ApiService {
async listTailIntegrations() { await this.authorize("flows:read"); return new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).tails(); }
async listRuns(query: URLSearchParams) { await this.authorize("runs:read"); return new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).list(query); }
async search(query: string) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).search(query); }
async getRun(runId: string) { await this.authorize("runs:read"); const repository = new RunQueryRepository(databaseFor(this.env), this.auth.tenantId), run = await repository.get(runId); if (!run) throw new ServiceError(404, "not_found", "Run not found"); const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, created_at: run.invocation_created_at }; run.activity = await repository.activity(runId); return run; }
async getRun(runId: string) { await this.authorize("runs:read"); const repository = new RunQueryRepository(databaseFor(this.env), this.auth.tenantId), run = await repository.get(runId); if (!run) throw new ServiceError(404, "not_found", "Run not found"); const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, created_at: run.invocation_created_at }; run.activity = await repository.activity(runId); run.execution_diagnostics ??= null; run.harness_log = (await new ArtifactRepository(databaseFor(this.env), this.auth.tenantId).list(runId)).find(item => item.kind === "terminal_log") ?? null; return run; }
async getRunTrace(runId: string, after: number, limit: number) { await this.authorize("runs:read"); return new TraceRepository(databaseFor(this.env), this.auth.tenantId).page(runId, after, limit); }
async getRunDiagnostics(runId: string) { const run: any = await this.getRun(runId); return { runId: run.id, jobId: run.job_id, state: run.state, provider: run.provider, backendKind: run.execution_backend_kind, artifact: { state: run.artifact_state, error: run.artifact_error }, activity: run.activity, createdAt: run.created_at, updatedAt: run.updated_at }; }
async getRunDiagnostics(runId: string) { const run: any = await this.getRun(runId); return { runId: run.id, jobId: run.job_id, state: run.state, provider: run.provider, backendKind: run.execution_backend_kind, execution: run.execution_diagnostics, harnessLog: run.harness_log, artifact: { state: run.artifact_state, error: run.artifact_error }, activity: run.activity, createdAt: run.created_at, updatedAt: run.updated_at }; }
async stopRun(runId: string) { await this.authorize("runs:write"); const stopped = await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).stop(runId); if (!stopped) throw new ServiceError(409, "operation_failed", "Run is not active"); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return stopped; }
killRun(runId: string) { return this.stopRun(runId); }
async listJobs() { await this.authorize("flows:read"); return Promise.all((await this.jobs().list()).map(job => this.presentJob(job))); }
Expand Down
27 changes: 27 additions & 0 deletions packages/app/src/harness-diagnostics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { ExecutionObservation } from "./execution";
import { scrubSession } from "./session-scrubber";

export const HARNESS_LOG_LIMIT = 64 * 1024;
export interface ExecutionDiagnostics {
state: "succeeded" | "failed" | "stopped";
detail: string | null;
systemd: { loadState: string; activeState: string; subState: string; result: string; execMainCode: number | null; execMainStatus: number | null } | null;
}

/** Redact before truncation so a cut cannot expose part of a recognized credential. */
export function safeDiagnosticText(value: string, limit = 2048): string {
const withoutAssignments = value.replace(/^.*["']?(?:[\w-]*(?:token|secret|password|passwd|api[_-]?key|authorization|cookie))["']?\s*[:=].*$/gim, "[REDACTED]");
const safe = scrubSession(withoutAssignments)
.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*/gi, "[REDACTED]")
.replace(/\b[A-Z][A-Z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD)\s*=\s*[^\r\n]+/g, "[REDACTED]")
.replace(/([?&](?:token|key|signature|credential|password|secret|x-amz-[\w-]+)=)[^&#\s]+/gi, "$1[REDACTED]");
return new TextDecoder().decode(new TextEncoder().encode(safe).slice(0, limit)).replace(/\uFFFD$/, "");
}

export function terminalDiagnostics(observation: ExecutionObservation): ExecutionDiagnostics {
return {
state: observation.state === "succeeded" ? "succeeded" : observation.state === "stopped" ? "stopped" : "failed",
detail: observation.detail ? safeDiagnosticText(observation.detail) : null,
systemd: observation.systemd ?? null,
};
}
2 changes: 1 addition & 1 deletion packages/app/src/postgres/artifact-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export class ArtifactRepository {
await client.query(`INSERT INTO app.run_artifacts(tenant_id,run_id,id,kind,object_key,provider,format,format_version,cli_version,native_session_id,byte_size,sha256,state)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
ON CONFLICT (tenant_id,object_key) DO UPDATE SET byte_size=excluded.byte_size,sha256=excluded.sha256,state=excluded.state`, [this.tenantId, input.runId, id, input.kind, input.objectKey, input.provider, input.format, input.formatVersion ?? null, input.cliVersion ?? null, input.nativeSessionId ?? null, input.byteSize, input.sha256, input.state ?? "stored"]);
await client.query("UPDATE app.runs SET artifact_state='stored',artifact_error=NULL,updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, input.runId]);
await client.query("UPDATE app.runs SET artifact_state='stored',updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, input.runId]);
});
}
async list(runId: string) { return (await this.database.pool.query("SELECT id,kind,object_key,provider,format,format_version,cli_version,native_session_id,byte_size,sha256,state,created_at FROM app.run_artifacts WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at,id", [this.tenantId, runId])).rows; }
Expand Down
Loading
Loading