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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \
https://app.factorize.sh/api/v1/github-installations
```

Job CRUD is available at `/jobs` and `/jobs/:id`; job metadata includes `currentRuns` and `maxConcurrency`. Run collections return `{ "items": [...], "nextCursor": "..." }`; pass `nextCursor` back as the `cursor` query parameter. Runs can be filtered by `jobId`, `state`, and `contextQuery`; context queries use case-insensitive literal substring matching and matching items contain a bounded `context_excerpt`, never the full context. `GET /runs/:runId` returns the complete structured trigger `context` and invocation metadata, including the firing `trigger_id`. The canonical Job prompt contract is documented in [docs/job-trigger-context.md](docs/job-trigger-context.md). Errors consistently use `{ "error": { "code": "...", "message": "..." } }`.
Job CRUD is available at `/jobs` and `/jobs/:id`; job metadata includes `currentRuns` and `maxConcurrency`. Run collections return `{ "items": [...], "nextCursor": "..." }`; pass `nextCursor` back as the `cursor` query parameter. Runs can be filtered by `jobId`, `state`, and `contextQuery`; context queries use case-insensitive literal substring matching and matching items contain a bounded `context_excerpt`, never the full context. `GET /runs/:runId` returns the rendered `prompt`, complete structured trigger `context`, and invocation metadata, including the firing `trigger_id`. The canonical Job prompt contract is documented in [docs/job-trigger-context.md](docs/job-trigger-context.md). Errors consistently use `{ "error": { "code": "...", "message": "..." } }`.

## MCP clients

Expand All @@ -184,7 +184,7 @@ Factorize also supports the OAuth 2.0 Device Authorization Grant (RFC 8628) for
- Linear webhooks require a valid HMAC-SHA256 signature and fresh timestamp before workspace routing.
- Session cookies are signed, expire after seven days, and are checked against workspace membership.
- OAuth access is tenant-bound, scope-checked, revocable, and revalidates current owner membership at the shared service boundary.
- Public REST and MCP responses omit connection tokens, credential records, prompts, and internal execution requests/responses.
- Public REST and MCP responses omit connection tokens, credential records, and internal execution requests/responses. Authorized run inspection includes the rendered prompt sent to the agent.
- Agent output is not copied into Linear; completion comments point back to the Herdr session on your VM.
- The dashboard uses a restrictive content-security policy and locally built Tailwind CSS.

Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ async function mcp(request: Request, service: ApiService, env: Env, ctx: Executi
tool("list_exe_connections", "List safe metadata for saved exe.dev connections. API tokens are never returned.", z.object({}), () => service.listExeConnections());
tool("list_github_installations", "List connected GitHub App installations, including the installation IDs needed by GitHub Job triggers. Credentials are never returned.", z.object({}), () => service.listGitHubInstallations());
tool("list_runs", "List authoritative job runs by job ID, state, and an optional case-insensitive literal substring of triggered context. Automatic webhook, schedule, and lifecycle signals coalesce, so query runs and the provider API for authoritative work. Context matches include only a bounded excerpt.", listRunsSchema, (input: any) => service.listRuns(queryOf(input)));
tool("get_run", "Get a run with its full triggered context, invocation metadata, execution metadata, output, and activity. For manual invocations, invocation.idempotency_key is the client-reusable value; invocation.claim_key is internal.", runIdSchema, ({ runId }: any) => service.getRun(runId));
tool("get_run", "Get a run with its rendered prompt, full triggered context, invocation metadata, execution metadata, output, and activity. For manual invocations, invocation.idempotency_key is the client-reusable value; invocation.claim_key is internal.", runIdSchema, ({ runId }: any) => service.getRun(runId));
tool("stop_run", "Stop an active run", runIdSchema, ({ runId }: any) => service.stopRun(runId));
tool("list_jobs", "List jobs with their current run count and maximum concurrency", z.object({}), () => service.listJobs());
tool("get_job", "Get a job with its current run count and maximum concurrency", jobIdSchema, ({ jobId }: any) => service.getJob(jobId));
Expand Down
4 changes: 3 additions & 1 deletion packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -896,7 +896,7 @@ export class TenantV2 extends DurableObject<Env> {
}

private async getRun(runId: string): Promise<Response> {
const run = this.one(`SELECT r.id, r.pipe_id AS job_id, r.issue_id, r.issue_url, r.agent_name, r.workspace_name, r.agent_kind, r.state, r.provider, r.execution_backend_kind AS backend_kind, r.execution_handle, r.execution_capabilities AS capabilities, r.destination_url, r.result, r.exec_status, r.exec_exit_code, r.recovery_last_action, r.created_at, r.updated_at,
const run = this.one(`SELECT r.id, r.pipe_id AS job_id, r.issue_id, r.issue_url, r.agent_name, r.workspace_name, r.agent_kind, r.state, r.provider, r.execution_backend_kind AS backend_kind, r.execution_handle, r.execution_capabilities AS capabilities, r.destination_url, r.prompt AS encrypted_prompt, r.result, r.exec_status, r.exec_exit_code, r.recovery_last_action, r.created_at, r.updated_at,
i.id AS invocation_id, i.job_id AS invocation_job_id, i.source AS invocation_source, i.claim_key AS invocation_claim_key, i.trigger_id AS invocation_trigger_id, i.context, i.occurrence AS invocation_occurrence, i.created_at AS invocation_created_at
FROM runs r LEFT JOIN job_runs jr ON jr.id = r.id LEFT JOIN invocations i ON i.id = jr.invocation_id WHERE r.id = ?`, runId);
if (!run) return new Response("Not found", { status: 404 });
Expand All @@ -914,6 +914,8 @@ export class TenantV2 extends DurableObject<Env> {
run.invocation = null;
}
for (const key of ["invocation_id", "invocation_job_id", "invocation_source", "invocation_trigger_id", "invocation_claim_key", "invocation_occurrence", "invocation_created_at"]) delete run[key];
if (typeof run.encrypted_prompt === "string" && run.encrypted_prompt) run.prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY);
delete run.encrypted_prompt;
if (run.state !== "ignored" && typeof run.result === "string" && run.result) run.result = await decrypt(run.result, this.env.CREDENTIAL_ENCRYPTION_KEY);
run.activity = this.rows("SELECT action, detail, created_at FROM run_activity WHERE run_id = ? ORDER BY created_at, id", runId);
this.presentExecution(run);
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ function elapsed(r){const start=new Date(r.created_at).getTime(),end=activeState
function updateElapsed(r){const label=$('[data-run-elapsed]');if(label)label.textContent=elapsed(r);clearInterval(elapsedTimer);if(activeStates.includes(r.state))elapsedTimer=setInterval(()=>{const current=$('[data-run-elapsed]');if(current)current.textContent=elapsed(r)},1000)}
function scheduleRefresh(r){clearTimeout(refreshTimer);if(activeStates.includes(r.state)&&(r.capabilities||[]).includes('output'))refreshTimer=setTimeout(refreshOutput,3000)}
async function refreshOutput(){try{const r=await request('/api/v1/runs/'+encodeURIComponent(id)),output=$('[data-run-output]'),state=$('[data-run-state]');if(output){const follow=output.scrollHeight-output.scrollTop-output.clientHeight<24;output.innerHTML=ansiToHtml(outputText(r));if(follow)output.scrollTop=output.scrollHeight}if(state)state.innerHTML=stateBadge(r.state);updateElapsed(r);scheduleRefresh(r)}catch{refreshTimer=setTimeout(refreshOutput,5000)}}
request('/api/v1/runs/'+encodeURIComponent(id)).then(async r=>({r,j:await request('/api/v1/jobs/'+encodeURIComponent(r.job_id))})).then(({r,j})=>{const caps=r.capabilities||[],canOutput=caps.includes('output'),canStop=caps.includes('stop')&&['starting','running','blocked'].includes(r.state),context=r.context===null?'<p class="mt-3 text-sm text-slate-500">Context is not available for this legacy run.</p>':'<pre data-run-context class="mt-4 overflow-x-auto whitespace-pre-wrap rounded-xl bg-slate-950 p-4 font-mono text-xs leading-5 text-slate-100">'+esc(JSON.stringify(r.context,null,2))+'</pre>',runLabel='Run '+r.id.slice(0,8);root.innerHTML='<nav aria-label="Breadcrumb"><ol class="flex flex-wrap items-center gap-2 text-sm text-slate-500"><li><a href="/jobs" class="font-medium hover:text-slate-950 dark:hover:text-white">Jobs</a></li><li aria-hidden="true">/</li><li><a href="/jobs/'+encodeURIComponent(r.job_id)+'" class="font-medium hover:text-slate-950 dark:hover:text-white">'+esc(j.name)+'</a></li><li aria-hidden="true">/</li><li aria-current="page" class="font-medium text-slate-950 dark:text-white">'+esc(runLabel)+'</li></ol></nav><div class="mt-6 flex flex-wrap items-start justify-between gap-4"><div><h1 class="text-3xl font-bold">'+esc(runLabel)+'</h1><p data-run-elapsed class="mt-2 text-slate-500">'+elapsed(r)+'</p></div><div class="flex items-center gap-3"><span data-run-state>'+stateBadge(r.state)+'</span>'+(canStop?'<button id="stop-run" class="rounded-xl border border-red-200 px-4 py-2 text-sm font-semibold text-red-700">Stop run</button>':'')+'</div></div><details class="${card} mt-8 p-6"><summary class="cursor-pointer font-semibold">Context sent to agent</summary>'+context+'</details>'+(canOutput?'<section class="${card} mt-6 p-6"><div class="flex items-center justify-between gap-4"><h2 class="font-semibold">Output</h2>'+(activeStates.includes(r.state)?'<span class="text-xs text-slate-500" aria-live="polite">Live · refreshes automatically</span>':'')+'</div><pre data-run-output class="mt-4 max-h-[calc(100vh-12rem)] overflow-auto whitespace-pre-wrap rounded-xl bg-slate-950 p-4 font-mono text-xs leading-5 text-slate-100" aria-live="polite">'+ansiToHtml(outputText(r))+'</pre></section>':'<section class="${card} mt-6 p-6 text-sm text-slate-500">Output is not available for this run.</section>');const output=$('[data-run-output]');if(output)output.scrollTop=output.scrollHeight;if(canStop)$('#stop-run').onclick=async()=>{await request('/api/v1/runs/'+encodeURIComponent(id)+'/stop',{method:'POST'});location.reload()};updateElapsed(r);scheduleRefresh(r)}).catch(e=>root.innerHTML='<p class="text-red-700">'+esc(e.message)+'</p>');`);
request('/api/v1/runs/'+encodeURIComponent(id)).then(async r=>({r,j:await request('/api/v1/jobs/'+encodeURIComponent(r.job_id))})).then(({r,j})=>{const caps=r.capabilities||[],canOutput=caps.includes('output'),canStop=caps.includes('stop')&&['starting','running','blocked'].includes(r.state),runLabel='Run '+r.id.slice(0,8);root.innerHTML='<nav aria-label="Breadcrumb"><ol class="flex flex-wrap items-center gap-2 text-sm text-slate-500"><li><a href="/jobs" class="font-medium hover:text-slate-950 dark:hover:text-white">Jobs</a></li><li aria-hidden="true">/</li><li><a href="/jobs/'+encodeURIComponent(r.job_id)+'" class="font-medium hover:text-slate-950 dark:hover:text-white">'+esc(j.name)+'</a></li><li aria-hidden="true">/</li><li aria-current="page" class="font-medium text-slate-950 dark:text-white">'+esc(runLabel)+'</li></ol></nav><div class="mt-6 flex flex-wrap items-start justify-between gap-4"><div><h1 class="text-3xl font-bold">'+esc(runLabel)+'</h1><p data-run-elapsed class="mt-2 text-slate-500">'+elapsed(r)+'</p></div><div class="flex items-center gap-3"><span data-run-state>'+stateBadge(r.state)+'</span>'+(canStop?'<button id="stop-run" class="rounded-xl border border-red-200 px-4 py-2 text-sm font-semibold text-red-700">Stop run</button>':'')+'</div></div><section class="${card} mt-8 p-6"><h2 class="font-semibold">Prompt</h2><pre data-run-prompt class="mt-4 overflow-x-auto whitespace-pre-wrap rounded-xl bg-slate-950 p-4 font-mono text-xs leading-5 text-slate-100">'+esc(r.prompt||'Prompt is not available for this run.')+'</pre></section>'+(canOutput?'<section class="${card} mt-6 p-6"><div class="flex items-center justify-between gap-4"><h2 class="font-semibold">Output</h2>'+(activeStates.includes(r.state)?'<span class="text-xs text-slate-500" aria-live="polite">Live · refreshes automatically</span>':'')+'</div><pre data-run-output class="mt-4 max-h-[calc(100vh-12rem)] overflow-auto whitespace-pre-wrap rounded-xl bg-slate-950 p-4 font-mono text-xs leading-5 text-slate-100" aria-live="polite">'+ansiToHtml(outputText(r))+'</pre></section>':'<section class="${card} mt-6 p-6 text-sm text-slate-500">Output is not available for this run.</section>');const output=$('[data-run-output]');if(output)output.scrollTop=output.scrollHeight;if(canStop)$('#stop-run').onclick=async()=>{await request('/api/v1/runs/'+encodeURIComponent(id)+'/stop',{method:'POST'});location.reload()};updateElapsed(r);scheduleRefresh(r)}).catch(e=>root.innerHTML='<p class="text-red-700">'+esc(e.message)+'</p>');`);

const settingsLayout = (active: "integrations" | "api-keys", content: string) => `<main class="mx-auto max-w-6xl px-5 py-12 lg:px-8"><div class="grid gap-8 md:grid-cols-[13rem_minmax(0,1fr)] md:gap-10"><nav aria-label="Settings" class="flex gap-2 overflow-x-auto border-b border-stone-200 pb-3 md:block md:border-b-0 md:pb-0 dark:border-slate-800">
${[["integrations", "Integrations"], ["api-keys", "API Keys"]].map(([id, label]) => `<a href="/settings/${id}"${active === id ? ` aria-current="page"` : ""} class="flex min-h-11 shrink-0 items-center rounded-lg px-3 py-2 text-sm text-slate-600 hover:bg-stone-100 hover:text-slate-950 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-factorize-600 aria-[current=page]:bg-stone-100 aria-[current=page]:font-semibold aria-[current=page]:text-slate-950 md:mb-1 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-white dark:aria-[current=page]:bg-slate-800 dark:aria-[current=page]:text-white">${label}</a>`).join("")}
Expand Down
19 changes: 19 additions & 0 deletions packages/app/test/run-inspection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ vi.mock("cloudflare:workers", () => ({ DurableObject: class {} }));

import { TenantV2 } from "../src/tenant";
import { ExeHerdrBackend } from "../src/exe-herdr-backend";
import { encrypt } from "../src/crypto";

function tenantWithRows(rows: (query: string, ...params: unknown[]) => Record<string, unknown>[]): TenantV2 {
const tenant = Object.create(TenantV2.prototype) as TenantV2;
Expand Down Expand Up @@ -84,6 +85,24 @@ describe("run invocation inspection", () => {
});
});

it("returns the decrypted prompt alongside canonical context", async () => {
const encryptionKey = btoa("0123456789abcdef0123456789abcdef");
const encryptedPrompt = await encrypt("Rendered prompt sent to the agent", encryptionKey);
const tenant = tenantWithRows((query) => query.includes("FROM runs r") ? [{
id: "run-1", job_id: "job-1", state: "queued", backend_kind: "amp", capabilities: "[]", result: null,
encrypted_prompt: encryptedPrompt, context: '{"trigger-1":{"prompt":"go"}}', invocation_id: "inv-1", invocation_job_id: "job-1",
invocation_source: "manual", invocation_trigger_id: "manual-1", invocation_claim_key: "manual:one", invocation_occurrence: null,
invocation_created_at: "2026-09-16T12:00:01Z",
}] : []);
(tenant as any).env = { CREDENTIAL_ENCRYPTION_KEY: encryptionKey };

const body = await ((tenant as any).getRun("run-1") as Promise<Response>).then((response: Response) => response.json()) as any;

expect(body.prompt).toBe("Rendered prompt sent to the agent");
expect(body.context).toEqual({ "trigger-1": { prompt: "go" } });
expect(body).not.toHaveProperty("encrypted_prompt");
});

it("reads current backend output while an output-capable run is active", async () => {
const tenant = tenantWithRows((query) => query.includes("FROM runs r") ? [{
id: "run-1", job_id: "job-1", state: "running", backend_kind: "exe-herdr",
Expand Down
10 changes: 5 additions & 5 deletions packages/app/test/ui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,11 +290,11 @@ describe("pages", () => {
expect(run).not.toContain("Observation");
expect(run).toContain("caps.includes('output')");
expect(run).toContain('data-run-output');
expect(run).toContain("Context sent to agent");
expect(run).toContain('<details class=');
expect(run).toContain('data-run-context');
expect(run).toContain("JSON.stringify(r.context,null,2)");
expect(run).toContain("Context is not available for this legacy run.");
expect(run).toContain('>Prompt</h2>');
expect(run).toContain('data-run-prompt');
expect(run).toContain("esc(r.prompt||'Prompt is not available for this run.')");
expect(run).not.toContain("Context sent to agent");
expect(run).not.toContain('data-run-context');
expect(run).toContain('font-mono text-xs leading-5');
expect(run).toContain("ansiToHtml(outputText(r))");
expect(run).toContain("r.live_output??r.result");
Expand Down