diff --git a/docs/execution-boundaries.md b/docs/execution-boundaries.md index 0651b77a..bcc75594 100644 --- a/docs/execution-boundaries.md +++ b/docs/execution-boundaries.md @@ -20,11 +20,13 @@ Backends map their native lifecycle into `queued`, `starting`, `running`, `recovering`, and `cancelled` rows are presented as `succeeded`, `starting`, and `stopped` respectively, avoiding a risky rewrite of durable history. -The current `ExeHerdrBackend` is one implementation. exe.dev supplies command +`ExeHerdrBackend` and `AmpBackend` implement this boundary. exe.dev supplies command transport and VM wake-up, Herdr supplies workspace and agent supervision, and the configured harness supplies Codex, Claude, Pi, or another Herdr-supported -agent. A future Amp implementation should implement `ExecutionBackend` without -adding Amp-specific state or commands to the orchestrator. +agent. Amp cloud runs persist an opaque thread handle and expose the canonical +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. Launch and prompt delivery are deliberately separate operations. An existing harness proves only that launch reconciliation succeeded. It never proves that diff --git a/packages/app/src/amp-backend.ts b/packages/app/src/amp-backend.ts new file mode 100644 index 00000000..27f1c018 --- /dev/null +++ b/packages/app/src/amp-backend.ts @@ -0,0 +1,48 @@ +import type { BackendCommandResult, ExecutionBackend, ExecutionObservation, ExecutionState, LaunchReceipt, LaunchRequest, RunHandle } from "./execution"; + +export interface AmpConnection { accessToken: string; project: string; apiBaseUrl?: string; } + +export function mapAmpState(value: unknown): ExecutionState { + switch (String(value ?? "").toLowerCase()) { + case "queued": case "pending": return "queued"; + case "creating": case "provisioning": case "starting": return "starting"; + case "running": case "working": case "active": return "running"; + case "waiting": case "waiting_for_input": case "blocked": return "blocked"; + case "stopping": case "cancelling": case "canceling": return "stopping"; + case "stopped": case "cancelled": case "canceled": case "archived": return "stopped"; + case "complete": case "completed": case "done": case "succeeded": case "success": return "succeeded"; + case "failed": case "error": return "failed"; + default: return "running"; + } +} + +export class AmpBackend implements ExecutionBackend { + readonly kind = "amp"; + readonly capabilities = ["stop"] as const; + private base: string; + constructor(private connection: AmpConnection, private request: typeof fetch = fetch) { this.base = (connection.apiBaseUrl || "https://ampcode.com/api/cloud/v1").replace(/\/$/, ""); } + private async call(path: string, init: RequestInit = {}) { + const requestBody = typeof init.body === "string" ? init.body : ""; + const response = await this.request(`${this.base}${path}`, { ...init, headers: { Authorization: `Bearer ${this.connection.accessToken}`, "Content-Type": "application/json", ...init.headers } }); + const body = await response.text(); let data: any = {}; try { data = body ? JSON.parse(body) : {}; } catch { /* retain raw body */ } + const command: BackendCommandResult = { ok: response.ok, status: response.status, exitCode: null, body, requestBody }; + return { data, command }; + } + async test() { return (await this.call("/projects?limit=1")).command.ok; } + async launch(request: LaunchRequest): Promise { + const result = await this.call("/runs", { method: "POST", body: JSON.stringify({ prompt: request.prompt, executor: "orb", project: this.connection.project, title: `Factorize ${request.runId}`, externalId: request.runId }) }); + if (!result.command.ok) throw new Error(`Amp launch failed (${result.command.status}): ${result.command.body.slice(0, 500)}`); + const threadId = String(result.data.threadId ?? result.data.threadID ?? result.data.id ?? ""); + if (!threadId) throw new Error("Amp launch response did not include a thread ID."); + return { handle: { backendKind: this.kind, id: threadId }, destinationUrl: String(result.data.url ?? `https://ampcode.com/threads/${encodeURIComponent(threadId)}`), capabilities: this.capabilities, observation: { state: mapAmpState(result.data.status ?? "starting") }, command: result.command }; + } + async inspect(handle: RunHandle): Promise { + const result = await this.call(`/runs/${encodeURIComponent(handle.id)}`); + if (!result.command.ok) return { state: result.command.status === 404 ? "failed" : "running", detail: result.command.body, command: result.command }; + return { state: mapAmpState(result.data.status ?? result.data.state), detail: result.data.detail, command: result.command }; + } + async stop(handle: RunHandle): Promise { + const result = await this.call(`/runs/${encodeURIComponent(handle.id)}/stop`, { method: "POST", body: "{}" }); + return { state: result.command.ok ? mapAmpState(result.data.status ?? "stopped") : "running", detail: result.data.detail ?? result.command.body, command: result.command }; + } +} diff --git a/packages/app/src/execution.ts b/packages/app/src/execution.ts index 115af788..fbdcf024 100644 --- a/packages/app/src/execution.ts +++ b/packages/app/src/execution.ts @@ -1,5 +1,5 @@ export type ExecutionState = "queued" | "starting" | "running" | "blocked" | "stopping" | "stopped" | "succeeded" | "failed"; -export type ExecutionCapability = "output" | "prompt-delivery" | "recovery"; +export type ExecutionCapability = "output" | "prompt-delivery" | "recovery" | "stop"; export type PromptDeliveryState = "pending" | "submitting" | "accepted" | "ambiguous" | "failed"; export interface BackendCommandResult { diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 36459dec..de22402b 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -140,6 +140,7 @@ app.post("/api/jobs/:id/disable", (c) => jobApi(c, `/jobs/${encodeURIComponent(c app.post("/api/jobs/:id/invocations", async (c) => jobApi(c, `/jobs/${encodeURIComponent(c.req.param("id"))}/invocations`, { method: "POST", headers: { "Content-Type": "application/json" }, body: await c.req.text() })); app.get("/api/job-runs", (c) => jobApi(c, `/runs?${new URL(c.req.url).searchParams.toString()}`)); app.get("/api/job-runs/:id", (c) => jobApi(c, `/runs/${encodeURIComponent(c.req.param("id"))}`)); +app.post("/api/job-runs/:id/stop", (c) => jobApi(c, `/runs/${encodeURIComponent(c.req.param("id"))}/stop`, { method: "POST" })); app.get("/api/execution-targets", (c) => jobApi(c, "/execution-targets")); app.post("/api/schedules/preview", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); @@ -208,6 +209,14 @@ app.post("/api/connections/exe/test", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); return tenant(c, session.tenantId).fetch("https://tenant/connections/exe/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); }); +app.put("/api/connections/amp", async (c) => { + const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); + return tenant(c, session.tenantId).fetch("https://tenant/connections/amp", { method: "PUT", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); +}); +app.post("/api/connections/amp/test", async (c) => { + const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); + return tenant(c, session.tenantId).fetch("https://tenant/connections/amp/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); +}); app.post("/api/pipes", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); const input = await c.req.json() as PipeInput & { source?: any }; diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 75934faf..42289988 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -5,13 +5,14 @@ import { agentListCommand, agentOutputCommand, agentStartupBlocked, agentStatusC import { findOwnedAgent, ownsPane, parseAgent, parseAgentList, parsePaneProcess, type HerdrIdentity } from "./recovery"; import { LINEAR_ISSUE_PROJECT_QUERY, LINEAR_OPTION_QUERIES, LINEAR_PROJECTS_QUERY, isLinearAuthenticationError, refreshLinearToken } from "./linear"; import { matchingIssue } from "./matcher"; -import type { Env, ExeConnectionInput, FilterType, MatchRule, PipeInput, RunState } from "./types"; +import type { AmpConnectionInput, Env, ExeConnectionInput, FilterType, MatchRule, PipeInput, RunState } from "./types"; import { workingDirectoryFor, workspaceNameFor } from "./workspace"; import { githubClaimKey, githubHeaders, installationToken, normalizeRepository, renderGitHubPrompt } from "./github"; import type { FlowSource, WorkItem } from "./types"; import { invokeCustomHandler, validateCustomHandler } from "./custom-handler"; import { sanitizeTailEvent, suppressTailEvent, tailFingerprint, verifyTailDelivery } from "./cloudflare-tail"; import { ExeHerdrBackend } from "./exe-herdr-backend"; +import { AmpBackend, type AmpConnection } from "./amp-backend"; import { DEFAULT_CONTEXT_TEMPLATE, LinearSourceAdapter, linearTicketPrompt, renderContextTemplate } from "./linear-source"; import { renderSourcePrompt } from "./source-lifecycle"; import { JOB_SCHEMA, renderJobPrompt } from "./job-domain"; @@ -128,6 +129,8 @@ export class Tenant extends DurableObject { if (request.method === "PUT" && url.pathname === "/connections/linear") return await this.saveLinear(await request.json()); if (request.method === "PUT" && url.pathname === "/connections/exe") return await this.saveExe(await request.json()); if (request.method === "POST" && url.pathname === "/connections/exe/test") return await this.testExe(await request.json()); + if (request.method === "PUT" && url.pathname === "/connections/amp") return await this.saveAmp(await request.json()); + if (request.method === "POST" && url.pathname === "/connections/amp/test") return await this.testAmp(await request.json()); if (request.method === "POST" && url.pathname === "/pipes") return await this.createPipe(await request.json() as PipeInput); if (request.method === "PUT" && url.pathname.startsWith("/pipes/")) return await this.updatePipe(url.pathname.split("/")[2] ?? "", await request.json() as PipeInput); if (request.method === "DELETE" && url.pathname.startsWith("/pipes/")) return this.deletePipe(url.pathname.split("/")[2] ?? ""); @@ -161,7 +164,7 @@ export class Tenant extends DurableObject { await this.processDueSchedules(); // Release completed slots before looking at the queue, so capacity is used // immediately rather than waiting for the next polling alarm. - const running = this.rows("SELECT * FROM runs WHERE state IN ('running','blocked','recovering') ORDER BY updated_at LIMIT 40"); + const running = this.rows("SELECT * FROM runs WHERE state IN ('starting','running','blocked','recovering') ORDER BY updated_at LIMIT 40"); for (const run of running) await this.pollRun(run); const queued = this.rows("SELECT * FROM runs WHERE state = 'queued' ORDER BY created_at LIMIT 20"); for (const run of queued) { @@ -215,6 +218,23 @@ export class Tenant extends DurableObject { return json({ ok: result.ok && (result.exitCode === null || result.exitCode === 0), httpStatus: result.status, exitCode: result.exitCode, command: result.requestBody, output: result.body }); } + private async saveAmp(input: unknown): Promise { + const value = input as AmpConnectionInput; + if (!value.accessToken || !value.project) throw new Error("Amp access token and project are required"); + if (!await new AmpBackend(value).test()) throw new Error("Amp connection verification failed"); + const connectionId = value.connectionId || id(); + await this.putConnection(`amp:${connectionId}`, value); + return json({ ok: true, connectionId }); + } + + private async testAmp(input: unknown): Promise { + const supplied = input as Partial; + const saved = supplied.connectionId ? await this.connection(`amp:${supplied.connectionId}`) : null; + const connection = supplied.accessToken ? supplied as AmpConnection : saved; + if (!connection?.accessToken || !connection.project) throw new Error("Amp access token and project are required"); + return json({ ok: await new AmpBackend(connection).test() }); + } + private async createPipe(input: PipeInput): Promise { const source = await this.validateSource(input); const rules = source.kind === "linear" ? source.matchRules : [{ type: "status", targetId: source.kind } as MatchRule]; @@ -262,16 +282,19 @@ export class Tenant extends DurableObject { const linear = await this.connection<{ organizationName?: string }>("linear"); const connections = await this.exeConnections(); const exe = await this.connection("exe"); + const ampConnections = await this.ampConnections(); return json({ linear: linear ? { organizationName: linear.organizationName ?? null } : null, exe: exe ? { vmName: exe.vmName, agentKind: exe.agentKind, cwd: exe.cwd, herdrCommand: exe.herdrCommand ?? "herdr", agentCommand: exe.agentCommand ?? defaultAgentCommand(exe.agentKind) } : null, exeConnections: connections.map(({ apiToken, ...connection }) => connection), + ampConnections: ampConnections.map(({ accessToken, ...connection }) => connection), }); } private async executionTargets(): Promise { const connections = await this.exeConnections(); - return json(connections.map(connection => ({ + const ampConnections = await this.ampConnections(); + return json([...connections.map(connection => ({ id: connection.connectionId, kind: "exe-herdr", name: connection.vmName, @@ -279,7 +302,7 @@ export class Tenant extends DurableObject { cwd: connection.cwd, agentKind: connection.agentKind, capabilities: ["output", "prompt-delivery", "recovery", "stop"], - }))); + })), ...ampConnections.map(connection => ({ id: `amp:${connection.connectionId}`, kind: "amp", name: `Amp · ${connection.project}`, workspace: connection.project, cwd: "Cloud orb", agentKind: "Amp", capabilities: ["stop"] }))]); } private triggerFor(jobId: unknown): Row | undefined { return this.one("SELECT * FROM triggers WHERE job_id = ?", jobId) as Row | undefined; } @@ -291,7 +314,7 @@ export class Tenant extends DurableObject { if (!job) return undefined; let target: Record = {}; try { target = JSON.parse(String(job.execution_target)); } catch { return undefined; } - return { id: job.id, name: job.name, max_concurrency: job.concurrency_limit, workspace_name: target.workspace, agent_kind: target.agentKind, cwd: target.cwd, exe_connection_id: target.connectionId, enabled: job.enabled }; + return { id: job.id, name: job.name, max_concurrency: job.concurrency_limit, workspace_name: target.workspace, agent_kind: target.agentKind, cwd: target.cwd, execution_backend_kind: target.backendKind ?? "exe-herdr", execution_connection_id: target.connectionId, exe_connection_id: target.connectionId, enabled: job.enabled }; } private async publicJob(row: Row): Promise> { @@ -309,7 +332,7 @@ export class Tenant extends DurableObject { id: row.id, name: row.name, promptTemplate: await decrypt(String(row.encrypted_prompt_template), this.env.CREDENTIAL_ENCRYPTION_KEY), parameterDefaults, concurrencyLimit: Number(row.concurrency_limit), - executionTargetId: String(executionTarget.connectionId ?? ""), + executionTargetId: `${executionTarget.backendKind === "amp" ? "amp:" : ""}${String(executionTarget.connectionId ?? "")}`, trigger: { kind: String(trigger?.kind ?? "manual"), config: triggerConfig, activity: { count: Number(activity?.count ?? 0), lastReceivedAt: activity?.last_received_at ?? null }, ...(trigger?.kind === "schedule" ? (() => { const state = this.one("SELECT next_run_at,last_triggered_at FROM schedule_state WHERE job_id=?", row.id) as Row | undefined; return { nextRunAt: state?.next_run_at == null ? null : new Date(Number(state.next_run_at)).toISOString(), lastTriggeredAt: state?.last_triggered_at ?? null }; })() : {}) }, enabled: Boolean(row.enabled), createdAt: row.created_at, updatedAt: row.updated_at, @@ -318,9 +341,14 @@ export class Tenant extends DurableObject { private async jobTarget(targetId: unknown): Promise> { if (typeof targetId !== "string" || !targetId) throw new Error("Execution target is required"); + if (targetId.startsWith("amp:")) { + const connectionId = targetId.slice(4), target = (await this.ampConnections()).find(item => item.connectionId === connectionId); + if (!target) throw new Error("Execution target not found"); + return { connectionId, backendKind: "amp", workspace: target.project, cwd: "", agentKind: "Amp" }; + } const target = (await this.exeConnections()).find(item => item.connectionId === targetId); if (!target) throw new Error("Execution target not found"); - return { connectionId: target.connectionId, workspace: target.vmName, cwd: target.cwd, agentKind: target.agentKind }; + return { connectionId: target.connectionId, backendKind: "exe-herdr", workspace: target.vmName, cwd: target.cwd, agentKind: target.agentKind }; } private validateJobInput(input: any): void { @@ -410,7 +438,8 @@ export class Tenant extends DurableObject { let target: Record = {}; try { target = JSON.parse(String(row.execution_target)); } catch { /* validated when the job is saved */ } const provider = source === "webhook" ? String((occurrence as any)?.metadata?.provider ?? "webhook") : source; - this.ctx.storage.sql.exec("INSERT INTO runs (id,pipe_id,issue_id,issue_title,issue_url,claim_key,agent_name,workspace_name,agent_kind,state,prompt,prompt_delivery_state,provider,execution_backend_kind,execution_capabilities,destination_url,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", runId, jobId, invocationId, String(row.name), null, claimKey, `factorize-${runId}`, String(target.workspace ?? ""), String(target.agentKind ?? ""), "queued", encryptedPrompt, "pending", provider, "exe-herdr", JSON.stringify(["output", "prompt-delivery", "recovery", "stop"]), "https://exe.dev/", timestamp, timestamp); + const backendKind = String(target.backendKind ?? "exe-herdr"), capabilities = backendKind === "amp" ? ["stop"] : ["output", "prompt-delivery", "recovery", "stop"]; + this.ctx.storage.sql.exec("INSERT INTO runs (id,pipe_id,issue_id,issue_title,issue_url,claim_key,agent_name,workspace_name,agent_kind,state,prompt,prompt_delivery_state,provider,execution_backend_kind,execution_capabilities,destination_url,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", runId, jobId, invocationId, String(row.name), null, claimKey, `factorize-${runId}`, String(target.workspace ?? ""), String(target.agentKind ?? ""), "queued", encryptedPrompt, "pending", provider, backendKind, JSON.stringify(capabilities), backendKind === "amp" ? null : "https://exe.dev/", timestamp, timestamp); await this.ctx.storage.setAlarm(Date.now()); return { invocationId, runId, state: "queued", duplicate: false }; } @@ -579,6 +608,14 @@ export class Tenant extends DurableObject { if (["starting", "running", "blocked", "recovering"].includes(String(run.state))) { const pipe = this.executionConfig(run.pipe_id); if (pipe) { + if (String(pipe.execution_backend_kind) === "amp") { + const connection = await this.connection(`amp:${String(pipe.execution_connection_id)}`); + if (!connection) return Response.json({ error: "Amp connection is unavailable" }, { status: 502 }); + const backend = new AmpBackend(connection); + this.ctx.storage.sql.exec("UPDATE runs SET state='stopping',updated_at=? WHERE id=?", now(), runId); + const stopped = await backend.stop(this.executionHandle(run, backend.kind)); + if (stopped.state !== "stopped") return Response.json({ error: "Could not stop the Amp run" }, { status: 502 }); + } else { const connection = await this.exeConnection(String(pipe.exe_connection_id || "default")); if (connection && run.agent_name) { const backend = new ExeHerdrBackend(connection); @@ -586,6 +623,7 @@ export class Tenant extends DurableObject { const stopped = await backend.stop(this.executionHandle(run, backend.kind)); if (stopped.state !== "stopped") return Response.json({ error: "Could not stop the active agent" }, { status: 502 }); } + } } } this.ctx.storage.sql.exec("UPDATE runs SET state = 'stopped', result = ?, updated_at = ? WHERE id = ?", await encrypt("Stopped by user", this.env.CREDENTIAL_ENCRYPTION_KEY), now(), runId); @@ -869,6 +907,16 @@ export class Tenant extends DurableObject { } private async startRun(run: Row, pipe: Row): Promise { + if (String(pipe.execution_backend_kind) === "amp") { + const connection = await this.connection(`amp:${String(pipe.execution_connection_id)}`); + if (!connection) return this.finishRun(run, "failed", "Amp connection is unavailable."); + const backend = new AmpBackend(connection), prompt = await decrypt(String(run.prompt), this.env.CREDENTIAL_ENCRYPTION_KEY); + try { + const launched = await backend.launch({ runId: String(run.id), prompt }); + this.ctx.storage.sql.exec("UPDATE runs SET state=?,execution_backend_kind=?,execution_handle=?,execution_capabilities=?,destination_url=?,prompt_delivery_state='accepted',prompt_accepted=1,updated_at=? WHERE id=?", launched.observation.state, backend.kind, JSON.stringify(launched.handle), JSON.stringify(launched.capabilities), launched.destinationUrl, now(), run.id); + } catch (error) { return this.finishRun(run, "failed", error instanceof Error ? error.message : "Amp launch failed."); } + return; + } const connection = await this.connectionForPipe(pipe); if (!connection) return this.finishRun(run, "failed", "No exe.dev VM is connected."); const workspaceName = String(run.workspace_name || pipe.workspace_name || workspaceNameFor(String(pipe.name))); @@ -906,6 +954,21 @@ export class Tenant extends DurableObject { private async pollRun(run: Row): Promise { const pipe = this.executionConfig(run.pipe_id); if (!pipe) return this.finishRun(run, "failed", "Job configuration is unavailable."); + if (String(pipe.execution_backend_kind) === "amp") { + const connection = await this.connection(`amp:${String(pipe.execution_connection_id)}`); + if (!connection) return this.finishRun(run, "failed", "Amp connection is unavailable."); + const backend = new AmpBackend(connection), observation = await backend.inspect(this.executionHandle(run, backend.kind)); + if (observation.state === "succeeded") return this.finishRun(run, "done", "Completed in Amp. Open the Amp thread for output."); + if (observation.state === "failed") return this.finishRun(run, "failed", observation.detail ?? "Amp run failed."); + if (observation.state === "stopped") { + this.ctx.storage.sql.exec("UPDATE runs SET state='stopped',updated_at=? WHERE id=?", now(), run.id); + this.ctx.storage.sql.exec("UPDATE job_runs SET state='cancelled',updated_at=? WHERE id=?", now(), run.id); + this.ctx.storage.sql.exec("DELETE FROM active_claims WHERE run_id=?", run.id); + return; + } + this.ctx.storage.sql.exec("UPDATE runs SET state=?,updated_at=? WHERE id=?", observation.state, now(), run.id); + return; + } const connection = await this.connectionForPipe(pipe); if (!connection) return this.finishRun(run, "failed", "exe.dev connection is unavailable."); if (String(run.state) === "recovering") return this.recoverRun(run, pipe, connection); @@ -1131,6 +1194,11 @@ export class Tenant extends DurableObject { return legacy ? [{ ...legacy, connectionId: "default" }] : []; } + private async ampConnections(): Promise> { + const rows = this.rows("SELECT kind, value FROM connections WHERE kind LIKE 'amp:%' ORDER BY updated_at DESC"); + return Promise.all(rows.map(async row => ({ ...(JSON.parse(await decrypt(String(row.value), this.env.CREDENTIAL_ENCRYPTION_KEY)) as AmpConnection), connectionId: String(row.kind).slice(4) }))); + } + private async connectionForPipe(pipe: Row): Promise { const connection = await this.exeConnection(String(pipe.exe_connection_id || "default")); return connection && pipe.cwd ? { ...connection, cwd: workingDirectoryFor(String(pipe.cwd), String(pipe.workspace_name)) } : connection; diff --git a/packages/app/src/types.ts b/packages/app/src/types.ts index f23b3416..99220de0 100644 --- a/packages/app/src/types.ts +++ b/packages/app/src/types.ts @@ -86,3 +86,5 @@ export interface ExeConnectionInput { /** Arguments passed to Herdr's canonical executable for the selected kind. */ agentCommand?: string; } + +export interface AmpConnectionInput { connectionId?: string; accessToken: string; project: string; apiBaseUrl?: string; } diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index daed7e0b..6237a8f9 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -227,7 +227,7 @@ async function runNow(job){const context=prompt('Optional run context (Cancel fo async function load(){const [j,runs]=await Promise.all([request('/api/jobs/'+encodeURIComponent(id)),request('/api/job-runs?jobId='+encodeURIComponent(id))]);const cfg=j.trigger.config||{},triggerDetail=j.trigger.kind==='schedule'?esc(cfg.cron)+' · '+esc(cfg.timezone)+(j.trigger.nextRunAt?' · next '+new Date(j.trigger.nextRunAt).toLocaleString():''):j.trigger.kind==='webhook'?esc(cfg.provider)+' provider':'Dashboard or MCP';root.innerHTML='

'+esc(j.name)+'

'+triggerBadge(j.trigger.kind)+(j.enabled?'':'Disabled')+'

'+triggerDetail+' · '+j.concurrencyLimit+' concurrent

Edit

Prompt template

'+esc(j.promptTemplate)+'

Defaults: '+esc(pairs(j.parameterDefaults)||'None')+'

Runs

'+(runs.items.length?'':'

No runs yet.

')+'
';$('#run').onclick=()=>runNow(j).catch(alert);$('#toggle').onclick=async()=>{await request('/api/jobs/'+encodeURIComponent(id)+'/'+(j.enabled?'disable':'enable'),{method:'POST'});load()};$('#delete').onclick=async()=>{if(confirm('Delete this job and its queued history?')){await request('/api/jobs/'+encodeURIComponent(id),{method:'DELETE'});location.href='/jobs'}}}load().catch(e=>root.innerHTML='

'+esc(e.message)+'

');`); export const jobRunPage = (viewer: { email: string }, runId: string) => shell("Run — Factorize", viewer, `

Loading run…

`, `${uiHelpers} -const root=$('#run-detail'),id=root.dataset.id;request('/api/job-runs/'+encodeURIComponent(id)).then(r=>{const caps=r.capabilities||[],canOutput=caps.includes('output'),trusted=typeof r.destination_url==='string'&&r.destination_url.startsWith('https://');root.innerHTML='← Job

Run '+esc(r.id.slice(0,8))+'

'+esc(r.backend_kind)+' · '+new Date(r.created_at).toLocaleString()+'

'+stateBadge(r.state)+'

Observation

'+(trusted?'Open '+esc(r.backend_kind)+' destination ↗':'

This backend has no external observation link.

')+'
'+(canOutput?'

Output

'+esc(r.result||'Output is not available yet.')+'
':'
Output is available only in the backend observation experience.
')}).catch(e=>root.innerHTML='

'+esc(e.message)+'

');`); +const root=$('#run-detail'),id=root.dataset.id;request('/api/job-runs/'+encodeURIComponent(id)).then(r=>{const caps=r.capabilities||[],canOutput=caps.includes('output'),canStop=caps.includes('stop')&&['starting','running','blocked'].includes(r.state),trusted=typeof r.destination_url==='string'&&r.destination_url.startsWith('https://');root.innerHTML='← Job

Run '+esc(r.id.slice(0,8))+'

'+esc(r.backend_kind)+' · '+new Date(r.created_at).toLocaleString()+'

'+stateBadge(r.state)+(canStop?'':'')+'

Observation

'+(trusted?'Open '+esc(r.backend_kind)+' destination ↗':'

This backend has no external observation link.

')+'
'+(canOutput?'

Output

'+esc(r.result||'Output is not available yet.')+'
':'
Output is available only in the backend observation experience.
');if(canStop)$('#stop-run').onclick=async()=>{await request('/api/job-runs/'+encodeURIComponent(id)+'/stop',{method:'POST'});location.reload()}}).catch(e=>root.innerHTML='

'+esc(e.message)+'

');`); -export const settingsPage = (viewer: { email: string }) => shell("Settings — Factorize", viewer, `
${dashboardHead("Settings", "Create and rotate provider connections here. Credential values never appear in Jobs or MCP.")}

Exe.dev execution connections

Loading…

`, `${uiHelpers} -async function load(){const s=await request('/api/connections/status');$('#connections').innerHTML=s.exeConnections?.length?'
    '+s.exeConnections.map(c=>'
  • '+esc(c.vmName)+' · '+esc(c.agentKind)+' · '+esc(c.cwd)+'
  • ').join('')+'
':'No execution connections yet.'}$('#connection').onsubmit=async e=>{e.preventDefault();const d=new FormData(e.currentTarget),m=$('#settings-message');try{await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({vmName:d.get('vmName'),apiToken:d.get('apiToken'),cwd:d.get('cwd'),agentKind:d.get('agentKind'),herdrCommand:'herdr',agentCommand:''})});e.currentTarget.reset();m.textContent='Connection saved. The credential is stored securely and will not be displayed.';load()}catch(x){m.textContent=x.message}};load();`); +export const settingsPage = (viewer: { email: string }) => shell("Settings — Factorize", viewer, `
${dashboardHead("Settings", "Create and rotate provider connections here. Credential values never appear in Jobs or MCP.")}

Exe.dev execution connections

Loading…

Amp cloud execution

Loading…

`, `${uiHelpers} +async function load(){const s=await request('/api/connections/status');$('#connections').innerHTML=s.exeConnections?.length?'
    '+s.exeConnections.map(c=>'
  • '+esc(c.vmName)+' · '+esc(c.agentKind)+' · '+esc(c.cwd)+'
  • ').join('')+'
':'No execution connections yet.';$('#amp-connections').innerHTML=s.ampConnections?.length?s.ampConnections.map(c=>'
'+esc(c.project)+' · Amp cloud
').join(''):'No Amp connections yet.'}$('#connection').onsubmit=async e=>{e.preventDefault();const d=new FormData(e.currentTarget),m=$('#settings-message');try{await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({vmName:d.get('vmName'),apiToken:d.get('apiToken'),cwd:d.get('cwd'),agentKind:d.get('agentKind'),herdrCommand:'herdr',agentCommand:''})});e.currentTarget.reset();m.textContent='Connection saved. The credential is stored securely and will not be displayed.';load()}catch(x){m.textContent=x.message}};const ampPayload=()=>{const d=new FormData($('#amp-connection'));return {project:d.get('project'),accessToken:d.get('accessToken'),apiBaseUrl:d.get('apiBaseUrl')}};$('#test-amp').onclick=async()=>{const m=$('#amp-message');try{const x=await request('/api/connections/amp/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});m.textContent=x.ok?'Amp connection succeeded.':'Amp connection failed.'}catch(x){m.textContent=x.message}};$('#amp-connection').onsubmit=async e=>{e.preventDefault();const m=$('#amp-message');try{await request('/api/connections/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});e.currentTarget.reset();m.textContent='Amp connection saved. The token will not be displayed.';load()}catch(x){m.textContent=x.message}};load();`); diff --git a/packages/app/test/amp-backend.test.ts b/packages/app/test/amp-backend.test.ts new file mode 100644 index 00000000..cd6e5341 --- /dev/null +++ b/packages/app/test/amp-backend.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it, vi } from "vitest"; +import { AmpBackend, mapAmpState } from "../src/amp-backend"; + +describe("AmpBackend", () => { + it("maps lifecycle states", () => { + expect(["starting", "running", "blocked", "stopping", "succeeded", "stopped", "failed"]).toEqual(["provisioning", "working", "waiting_for_input", "cancelling", "completed", "cancelled", "error"].map(mapAmpState)); + }); + it("launches, inspects, and stops without output capability", async () => { + const responses = [new Response('{"threadId":"T-123","status":"provisioning"}', { status: 201 }), new Response('{"status":"working"}'), new Response('{"status":"cancelled"}')]; + const request: any = vi.fn(async (..._args: any[]) => responses.shift()!); + const backend = new AmpBackend({ accessToken: "sgamp_secret", project: "acme/repo" }, request as any); + const launched = await backend.launch({ runId: "run-1", prompt: "Fix it" }); + expect(launched).toMatchObject({ handle: { backendKind: "amp", id: "T-123" }, destinationUrl: "https://ampcode.com/threads/T-123", capabilities: ["stop"] }); + expect(await backend.inspect(launched.handle)).toMatchObject({ state: "running" }); + expect(await backend.stop(launched.handle)).toMatchObject({ state: "stopped" }); + expect(JSON.stringify(launched)).not.toContain("sgamp_secret"); + expect(String(request.mock.calls[0][1].body)).not.toContain("sgamp_secret"); + }); +});