Skip to content

An open-source, faster Devin alternative

TypeScript

feat: support the feedback.now agent-feedback protocol

Devin AI5cae0ff21ac7
diff --git a/cloudflare-workers/api-edge/migrations/0008_agent_feedback.sql b/cloudflare-workers/api-edge/migrations/0008_agent_feedback.sql
new file mode 100644
index 00000000..b3d78774
--- /dev/null
+++ b/cloudflare-workers/api-edge/migrations/0008_agent_feedback.sql
@@ -0,0 +1,98 @@
+-- feedback.now protocol (https://feedback.now) receiver tables.
+--
+-- Coding agents that hit our public API discover /.well-known/agent-feedback.json
+-- and POST structured bug / friction reports to /api/v1/feedback (or lighter
+-- signals to /api/v1/observations). Every submission mints a receipt the agent
+-- can poll for triage status. None of this touches sandboxes or cells, so it
+-- lives only in D1.
+--
+-- Timestamps are unix seconds, matching the rest of this schema.
+
+CREATE TABLE agent_feedback (
+ id TEXT PRIMARY KEY,
+ status TEXT NOT NULL DEFAULT 'open', -- open|investigating|accepted|resolved|dismissed|spam
+ category TEXT NOT NULL,
+ severity TEXT NOT NULL,
+ reproducibility TEXT,
+ confidence REAL NOT NULL,
+ surface TEXT NOT NULL,
+ domain TEXT NOT NULL,
+ surface_kind TEXT,
+ product TEXT,
+ title TEXT NOT NULL,
+ summary TEXT,
+ hypothesis TEXT,
+ agent_vendor TEXT NOT NULL,
+ agent_product TEXT NOT NULL,
+ agent_version TEXT,
+ agent_key TEXT, -- base64 SPKI Ed25519 public key when the request was signed
+ dedupe_key TEXT NOT NULL, -- sha256(domain|surface|normalized title)
+ observations INTEGER NOT NULL DEFAULT 1,
+ quality_score REAL,
+ duplicate_of TEXT,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+);
+
+CREATE INDEX idx_agent_feedback_status ON agent_feedback(status, created_at);
+CREATE INDEX idx_agent_feedback_dedupe ON agent_feedback(dedupe_key, created_at);
+CREATE INDEX idx_agent_feedback_domain ON agent_feedback(domain, created_at);
+
+CREATE TABLE agent_feedback_evidence (
+ id TEXT PRIMARY KEY,
+ feedback_id TEXT NOT NULL,
+ type TEXT NOT NULL,
+ content TEXT NOT NULL,
+ redacted INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL
+);
+
+CREATE INDEX idx_agent_feedback_evidence_fb ON agent_feedback_evidence(feedback_id);
+
+CREATE TABLE agent_observations (
+ id TEXT PRIMARY KEY,
+ surface TEXT NOT NULL,
+ domain TEXT NOT NULL,
+ category TEXT,
+ severity TEXT,
+ confidence REAL,
+ summary TEXT,
+ agent_vendor TEXT NOT NULL,
+ agent_product TEXT NOT NULL,
+ agent_key TEXT,
+ created_at INTEGER NOT NULL
+);
+
+CREATE INDEX idx_agent_observations_surface ON agent_observations(domain, surface, created_at);
+
+CREATE TABLE agent_feedback_receipts (
+ id TEXT PRIMARY KEY,
+ feedback_id TEXT,
+ observation_id TEXT,
+ status TEXT NOT NULL, -- accepted|needs_more_evidence|duplicate|rejected|queued
+ duplicate_of TEXT,
+ agent_key TEXT,
+ client_ip TEXT,
+ created_at INTEGER NOT NULL
+);
+
+-- Rate limiting: submissions per signer / per IP in the trailing hour.
+CREATE INDEX idx_agent_feedback_receipts_key ON agent_feedback_receipts(agent_key, created_at);
+CREATE INDEX idx_agent_feedback_receipts_ip ON agent_feedback_receipts(client_ip, created_at);
+
+CREATE TABLE agent_feedback_categories (
+ name TEXT PRIMARY KEY,
+ description TEXT,
+ created_at INTEGER NOT NULL
+);
+
+CREATE TABLE agent_feedback_agents (
+ agent_key TEXT PRIMARY KEY,
+ agent_vendor TEXT NOT NULL,
+ agent_product TEXT NOT NULL,
+ submissions INTEGER NOT NULL DEFAULT 0,
+ accepted INTEGER NOT NULL DEFAULT 0,
+ dismissed INTEGER NOT NULL DEFAULT 0,
+ first_seen INTEGER NOT NULL,
+ last_seen INTEGER NOT NULL
+);
diff --git a/cloudflare-workers/api-edge/schema-snapshots/current_schema.sql b/cloudflare-workers/api-edge/schema-snapshots/current_schema.sql
index 05f6d7d8..ba3558a2 100644
--- a/cloudflare-workers/api-edge/schema-snapshots/current_schema.sql
+++ b/cloudflare-workers/api-edge/schema-snapshots/current_schema.sql
@@ -47,6 +47,83 @@ CREATE TABLE agent_security_notifications (
)
);
+CREATE TABLE agent_feedback (
+ id TEXT PRIMARY KEY,
+ status TEXT NOT NULL DEFAULT 'open', -- open|investigating|accepted|resolved|dismissed|spam
+ category TEXT NOT NULL,
+ severity TEXT NOT NULL,
+ reproducibility TEXT,
+ confidence REAL NOT NULL,
+ surface TEXT NOT NULL,
+ domain TEXT NOT NULL,
+ surface_kind TEXT,
+ product TEXT,
+ title TEXT NOT NULL,
+ summary TEXT,
+ hypothesis TEXT,
+ agent_vendor TEXT NOT NULL,
+ agent_product TEXT NOT NULL,
+ agent_version TEXT,
+ agent_key TEXT, -- base64 SPKI Ed25519 public key when the request was signed
+ dedupe_key TEXT NOT NULL, -- sha256(domain|surface|normalized title)
+ observations INTEGER NOT NULL DEFAULT 1,
+ quality_score REAL,
+ duplicate_of TEXT,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+);
+
+CREATE TABLE agent_feedback_evidence (
+ id TEXT PRIMARY KEY,
+ feedback_id TEXT NOT NULL,
+ type TEXT NOT NULL,
+ content TEXT NOT NULL,
+ redacted INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL
+);
+
+CREATE TABLE agent_observations (
+ id TEXT PRIMARY KEY,
+ surface TEXT NOT NULL,
+ domain TEXT NOT NULL,
+ category TEXT,
+ severity TEXT,
+ confidence REAL,
+ summary TEXT,
+ agent_vendor TEXT NOT NULL,
+ agent_product TEXT NOT NULL,
+ agent_key TEXT,
+ created_at INTEGER NOT NULL
+);
+
+CREATE TABLE agent_feedback_receipts (
+ id TEXT PRIMARY KEY,
+ feedback_id TEXT,
+ observation_id TEXT,
+ status TEXT NOT NULL, -- accepted|needs_more_evidence|duplicate|rejected|queued
+ duplicate_of TEXT,
+ agent_key TEXT,
+ client_ip TEXT,
+ created_at INTEGER NOT NULL
+);
+
+CREATE TABLE agent_feedback_categories (
+ name TEXT PRIMARY KEY,
+ description TEXT,
+ created_at INTEGER NOT NULL
+);
+
+CREATE TABLE agent_feedback_agents (
+ agent_key TEXT PRIMARY KEY,
+ agent_vendor TEXT NOT NULL,
+ agent_product TEXT NOT NULL,
+ submissions INTEGER NOT NULL DEFAULT 0,
+ accepted INTEGER NOT NULL DEFAULT 0,
+ dismissed INTEGER NOT NULL DEFAULT 0,
+ first_seen INTEGER NOT NULL,
+ last_seen INTEGER NOT NULL
+);
+
CREATE TABLE api_keys (
id TEXT PRIMARY KEY,
org_id TEXT NOT NULL,
@@ -376,3 +453,17 @@ CREATE INDEX webhook_dest_org_idx
CREATE UNIQUE INDEX webhook_dest_svix_ep_idx
ON webhook_destinations (svix_endpoint_id);
+
+CREATE INDEX idx_agent_feedback_status ON agent_feedback(status, created_at);
+
+CREATE INDEX idx_agent_feedback_dedupe ON agent_feedback(dedupe_key, created_at);
+
+CREATE INDEX idx_agent_feedback_domain ON agent_feedback(domain, created_at);
+
+CREATE INDEX idx_agent_feedback_evidence_fb ON agent_feedback_evidence(feedback_id);
+
+CREATE INDEX idx_agent_observations_surface ON agent_observations(domain, surface, created_at);
+
+CREATE INDEX idx_agent_feedback_receipts_key ON agent_feedback_receipts(agent_key, created_at);
+
+CREATE INDEX idx_agent_feedback_receipts_ip ON agent_feedback_receipts(client_ip, created_at);
diff --git a/cloudflare-workers/api-edge/src/agent_feedback.test.ts b/cloudflare-workers/api-edge/src/agent_feedback.test.ts
new file mode 100644
index 00000000..26437346
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/agent_feedback.test.ts
@@ -0,0 +1,395 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import {
+ AGENT_FEEDBACK_DISCOVERY_PATH,
+ handleAgentFeedback,
+ isAgentFeedbackPath,
+ signingPayload,
+ type AgentFeedbackEnv,
+} from "./agent_feedback";
+
+// The tsconfig is workers-only (no @types/node), and vite's resolver doesn't
+// know node:sqlite, so reach the Node 22 builtins via process.getBuiltinModule
+// with minimal local typings. Running the module's SQL against the real
+// migration beats a hand-rolled D1 fake.
+interface SqliteStatement {
+ get(...params: unknown[]): unknown;
+ all(...params: unknown[]): unknown[];
+ run(...params: unknown[]): unknown;
+}
+interface DatabaseSync {
+ exec(sql: string): void;
+ prepare(sql: string): SqliteStatement;
+}
+declare const process: { cwd(): string; getBuiltinModule(id: string): unknown };
+const { DatabaseSync } = process.getBuiltinModule("node:sqlite") as { DatabaseSync: new (path: string) => DatabaseSync };
+const { readFileSync } = process.getBuiltinModule("node:fs") as { readFileSync(path: string, enc: "utf8"): string };
+
+class Stmt {
+ private params: unknown[] = [];
+ constructor(private db: DatabaseSync, private sql: string) {}
+ bind(...p: unknown[]): this {
+ this.params = p;
+ return this;
+ }
+ // node:sqlite supports ?NNN positional params natively; D1 uses the same form.
+ private args(): unknown[] {
+ return this.params.map((v) => (v === undefined ? null : v));
+ }
+ async first<T>(): Promise<T | null> {
+ return (this.db.prepare(this.sql).get(...this.args()) as T | undefined) ?? null;
+ }
+ async all<T>(): Promise<{ results: T[] }> {
+ return { results: this.db.prepare(this.sql).all(...this.args()) as T[] };
+ }
+ async run(): Promise<{ success: true }> {
+ this.db.prepare(this.sql).run(...this.args());
+ return { success: true };
+ }
+}
+
+function makeEnv(triageToken?: string): AgentFeedbackEnv {
+ const db = new DatabaseSync(":memory:");
+ db.exec(readFileSync(process.cwd() + "/migrations/0008_agent_feedback.sql", "utf8"));
+ return {
+ OPENCOMPUTER_DB: {
+ prepare: (sql: string) => new Stmt(db, sql),
+ batch: async (stmts: Stmt[]) => {
+ const out = [];
+ for (const s of stmts) out.push(await s.run());
+ return out;
+ },
+ } as unknown as D1Database,
+ AGENT_FEEDBACK_TRIAGE_TOKEN: triageToken,
+ };
+}
+
+const HOST = "https://app.test";
+
+function call(env: AgentFeedbackEnv, method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<Response> {
+ const req = new Request(HOST + path, {
+ method,
+ headers: { "content-type": "application/json", ...headers },
+ body: body === undefined ? undefined : typeof body === "string" ? body : JSON.stringify(body),
+ });
+ return handleAgentFeedback(req, env, new URL(req.url).pathname);
+}
+
+const validFeedback = {
+ reporter: { agent_vendor: "anthropic", agent_product: "claude-code", agent_version: "1.2.3" },
+ subject: { surface: "POST /api/sandboxes", domain: "app.opencomputer.dev", kind: "api_endpoint" },
+ signal: { category: "bug", severity: "high", reproducibility: "always", confidence: 0.9 },
+ content: { title: "create returns 500 when template missing", summary: "Expected 404 with a clear error." },
+ evidence: [{ type: "http_summary", content: JSON.stringify({ status: 500 }) }],
+};
+
+let env: AgentFeedbackEnv;
+beforeEach(() => {
+ env = makeEnv("triage-secret");
+});
+
+describe("routing", () => {
+ it("claims the discovery path and /api/v1/*, nothing else", () => {
+ expect(isAgentFeedbackPath(AGENT_FEEDBACK_DISCOVERY_PATH)).toBe(true);
+ expect(isAgentFeedbackPath("/api/v1/feedback")).toBe(true);
+ expect(isAgentFeedbackPath("/api/sandboxes")).toBe(false);
+ expect(isAgentFeedbackPath("/api/dashboard/me")).toBe(false);
+ expect(isAgentFeedbackPath("/.well-known/other.json")).toBe(false);
+ });
+
+ it("serves discovery + policy with the spec's shape", async () => {
+ const disc = await (await call(env, "GET", AGENT_FEEDBACK_DISCOVERY_PATH)).json() as Record<string, unknown>;
+ expect(disc.schema_version).toBe("1.1");
+ expect(disc.policy_url).toBe("/api/v1/policy");
+ expect((disc.endpoints as Record<string, Record<string, Record<string, string>>>).feedback.submit.url).toBe("/api/v1/feedback");
+
+ const pol = await (await call(env, "GET", "/api/v1/policy")).json() as Record<string, unknown>;
+ expect(pol.categories).toContain("bug");
+ expect(pol.severity_levels).toEqual(["critical", "high", "medium", "low"]);
+ expect((pol.limits as Record<string, number>).max_evidence_per_feedback).toBe(10);
+ expect((pol.endpoints as Record<string, string>).discovery).toBe(AGENT_FEEDBACK_DISCOVERY_PATH);
+ });
+
+ it("404s unknown /api/v1 routes", async () => {
+ expect((await call(env, "GET", "/api/v1/nope")).status).toBe(404);
+ });
+});
+
+describe("submit feedback", () => {
+ it("accepts a valid report, stores evidence, and mints a pollable receipt", async () => {
+ const res = await call(env, "POST", "/api/v1/feedback", validFeedback);
+ expect(res.status).toBe(201);
+ const { receipt } = await res.json() as { receipt: Record<string, unknown> };
+ expect(receipt.status).toBe("accepted");
+ expect(String(receipt.feedback_id)).toMatch(/^fb_/);
+ expect(receipt.evidence_ids).toHaveLength(1);
+
+ const rcpt = await (await call(env, "GET", `/api/v1/receipts/${receipt.id}`)).json() as { data: Record<string, unknown> };
+ expect(rcpt.data.status).toBe("accepted");
+ expect(rcpt.data.feedback_id).toBe(receipt.feedback_id);
+ expect(rcpt.data.feedback_status).toBe("open");
+
+ const detail = await (await call(env, "GET", `/api/v1/feedback/${receipt.feedback_id}`)).json() as { data: Record<string, unknown> };
+ expect(detail.data.status).toBe("open");
+ expect(detail.data.observations).toBe(1);
+ expect((detail.data.evidence as unknown[]).length).toBe(1);
+ expect((detail.data.content as Record<string, string>).title).toBe(validFeedback.content.title);
+ });
+
+ it("returns the spec's validation error shape", async () => {
+ const res = await call(env, "POST", "/api/v1/feedback", {
+ reporter: { agent_vendor: "x" },
+ subject: { surface: "s", domain: "d" },
+ signal: { category: "nonsense!", severity: "loud", confidence: 7 },
+ content: {},
+ });
+ expect(res.status).toBe(400);
+ const body = await res.json() as { error: string; errors: { field: string; error: string }[] };
+ expect(body.error).toBe("validation_failed");
+ const fields = body.errors.map((e) => e.field).sort();
+ expect(fields).toEqual(["content.title", "reporter.agent_product", "signal.category", "signal.confidence", "signal.severity"]);
+ });
+
+ it("rejects unknown categories but accepts custom ones once created", async () => {
+ const custom = { ...validFeedback, signal: { ...validFeedback.signal, category: "billing_confusion" } };
+ expect((await call(env, "POST", "/api/v1/feedback", custom)).status).toBe(400);
+
+ const created = await call(env, "POST", "/api/v1/categories", { name: "billing_confusion" }, { authorization: "Bearer triage-secret" });
+ expect(created.status).toBe(201);
+ expect((await call(env, "POST", "/api/v1/feedback", custom)).status).toBe(201);
+ const cats = await (await call(env, "GET", "/api/v1/categories")).json() as { data: string[] };
+ expect(cats.data).toContain("billing_confusion");
+ });
+
+ it("folds a repeat of the same surface+title into the existing report", async () => {
+ const first = (await (await call(env, "POST", "/api/v1/feedback", validFeedback)).json() as { receipt: Record<string, string> }).receipt;
+ const again = { ...validFeedback, content: { title: validFeedback.content.title.toUpperCase() + " " } };
+ const res = await call(env, "POST", "/api/v1/feedback", again);
+ expect(res.status).toBe(201);
+ const { receipt } = await res.json() as { receipt: Record<string, unknown> };
+ expect(receipt.status).toBe("duplicate");
+ expect(receipt.feedback_id).toBe(first.feedback_id);
+ expect(receipt.duplicate_of).toBe(first.feedback_id);
+
+ const detail = await (await call(env, "GET", `/api/v1/feedback/${first.feedback_id}`)).json() as { data: Record<string, unknown> };
+ expect(detail.data.observations).toBe(2);
+ });
+
+ it("rejects malformed JSON and non-object bodies", async () => {
+ expect((await call(env, "POST", "/api/v1/feedback", "{not json")).status).toBe(400);
+ expect((await call(env, "POST", "/api/v1/feedback", [1, 2])).status).toBe(400);
+ });
+
+ it("rate limits per client IP after 100 submissions in an hour", async () => {
+ const ip = { "cf-connecting-ip": "203.0.113.7" };
+ for (let i = 0; i < 100; i++) {
+ const r = await call(env, "POST", "/api/v1/observations", { surface: `s${i}`, domain: "d", agent_vendor: "v", agent_product: "p" }, ip);
+ expect(r.status).toBe(201);
+ }
+ const blocked = await call(env, "POST", "/api/v1/observations", { surface: "s", domain: "d", agent_vendor: "v", agent_product: "p" }, ip);
+ expect(blocked.status).toBe(429);
+ const other = await call(env, "POST", "/api/v1/observations", { surface: "s", domain: "d", agent_vendor: "v", agent_product: "p" }, { "cf-connecting-ip": "203.0.113.8" });
+ expect(other.status).toBe(201);
+ });
+});
+
+describe("observations", () => {
+ it("accepts a lightweight signal and mints a receipt", async () => {
+ const res = await call(env, "POST", "/api/v1/observations", {
+ surface: "oc sandbox create",
+ domain: "app.opencomputer.dev",
+ agent_vendor: "openai",
+ agent_product: "codex",
+ category: "friction",
+ severity: "low",
+ confidence: 0.4,
+ summary: "flag name differs from docs",
+ });
+ expect(res.status).toBe(201);
+ const { receipt } = await res.json() as { receipt: Record<string, string> };
+ expect(receipt.observation_id).toMatch(/^obs_/);
+ const rcpt = await (await call(env, "GET", `/api/v1/receipts/${receipt.id}`)).json() as { data: Record<string, unknown> };
+ expect(rcpt.data.observation_id).toBe(receipt.observation_id);
+ expect(rcpt.data.feedback_id).toBeNull();
+ });
+
+ it("requires the four mandatory fields", async () => {
+ const res = await call(env, "POST", "/api/v1/observations", { surface: "s" });
+ expect(res.status).toBe(400);
+ const body = await res.json() as { errors: { field: string }[] };
+ expect(body.errors.map((e) => e.field).sort()).toEqual(["agent_product", "agent_vendor", "domain"]);
+ });
+});
+
+describe("evidence attachments", () => {
+ async function submit(): Promise<string> {
+ const r = await call(env, "POST", "/api/v1/feedback", validFeedback);
+ return ((await r.json()) as { receipt: { feedback_id: string } }).receipt.feedback_id;
+ }
+
+ it("accepts a single item, an array, or {evidence:[...]}", async () => {
+ const id = await submit();
+ const single = await call(env, "POST", `/api/v1/feedback/${id}/attachments`, { type: "log_excerpt", content: "boom" });
+ expect(single.status).toBe(201);
+ const arr = await call(env, "POST", `/api/v1/feedback/${id}/attachments`, [{ type: "repro_steps", content: "1. run" }]);
+ expect(arr.status).toBe(201);
+ const wrapped = await call(env, "POST", `/api/v1/feedback/${id}/attachments`, { evidence: [{ type: "other", content: "x", redacted: true }] });
+ expect(wrapped.status).toBe(201);
+ const detail = await (await call(env, "GET", `/api/v1/feedback/${id}`)).json() as { data: { evidence: { redacted: boolean }[] } };
+ expect(detail.data.evidence).toHaveLength(4);
+ expect(detail.data.evidence.filter((e) => e.redacted)).toHaveLength(1);
+ });
+
+ it("enforces the 10-item ceiling across the whole report", async () => {
+ const id = await submit();
+ const nine = Array.from({ length: 9 }, () => ({ type: "other", content: "x" }));
+ expect((await call(env, "POST", `/api/v1/feedback/${id}/attachments`, nine)).status).toBe(201);
+ const over = await call(env, "POST", `/api/v1/feedback/${id}/attachments`, { type: "other", content: "one too many" });
+ expect(over.status).toBe(400);
+ });
+
+ it("404s an unknown feedback id", async () => {
+ expect((await call(env, "POST", "/api/v1/feedback/fb_missing/attachments", { type: "other", content: "x" })).status).toBe(404);
+ });
+});
+
+describe("Ed25519 signing", () => {
+ async function signed(body: unknown, path: string, tamper?: (h: Record<string, string>) => void): Promise<Response> {
+ const kp = (await crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"])) as CryptoKeyPair;
+ const spki = new Uint8Array((await crypto.subtle.exportKey("spki", kp.publicKey)) as ArrayBuffer);
+ const text = JSON.stringify(body);
+ const ts = new Date().toISOString();
+ const payload = new TextEncoder().encode(await signingPayload(ts, "POST", path, text));
+ const sig = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, kp.privateKey, payload));
+ const headers: Record<string, string> = {
+ "X-Agent-Key": btoa(String.fromCharCode(...spki)),
+ "X-Agent-Signature": btoa(String.fromCharCode(...sig)),
+ "X-Agent-Timestamp": ts,
+ };
+ tamper?.(headers);
+ return call(env, "POST", path, text, headers);
+ }
+
+ it("accepts a correctly signed submission and tracks the agent", async () => {
+ const res = await signed(validFeedback, "/api/v1/feedback");
+ expect(res.status).toBe(201);
+ const agents = await (await call(env, "GET", "/api/v1/agents", undefined, { authorization: "Bearer triage-secret" })).json() as { data: Record<string, unknown>[] };
+ expect(agents.data).toHaveLength(1);
+ expect(agents.data[0].submissions).toBe(1);
+ expect(agents.data[0].agent_product).toBe("claude-code");
+ });
+
+ it("rejects a tampered signature and a stale timestamp", async () => {
+ const bad = await signed(validFeedback, "/api/v1/feedback", (h) => { h["X-Agent-Signature"] = h["X-Agent-Signature"].replace(/^./, (c) => (c === "A" ? "B" : "A")); });
+ expect(bad.status).toBe(401);
+ const stale = await signed(validFeedback, "/api/v1/feedback", (h) => { h["X-Agent-Timestamp"] = new Date(Date.now() - 3600_000).toISOString(); });
+ expect(stale.status).toBe(401);
+ const partial = await signed(validFeedback, "/api/v1/feedback", (h) => { delete h["X-Agent-Key"]; });
+ expect(partial.status).toBe(401);
+ });
+});
+
+describe("triage", () => {
+ const auth = { authorization: "Bearer triage-secret" };
+
+ async function submit(title: string): Promise<{ feedback_id: string; receipt_id: string }> {
+ const r = await call(env, "POST", "/api/v1/feedback", { ...validFeedback, content: { title } });
+ const { receipt } = (await r.json()) as { receipt: { id: string; feedback_id: string } };
+ return { feedback_id: receipt.feedback_id, receipt_id: receipt.id };
+ }
+
+ it("gates list/patch/delete/merge/agents behind the bearer token", async () => {
+ const { feedback_id } = await submit("a");
+ expect((await call(env, "GET", "/api/v1/feedback")).status).toBe(401);
+ expect((await call(env, "PATCH", `/api/v1/feedback/${feedback_id}`, { status: "accepted" })).status).toBe(401);
+ expect((await call(env, "DELETE", `/api/v1/feedback/${feedback_id}`)).status).toBe(401);
+ expect((await call(env, "POST", "/api/v1/feedback/merge", { target_id: feedback_id, source_ids: [] })).status).toBe(401);
+ expect((await call(env, "GET", "/api/v1/agents")).status).toBe(401);
+ expect((await call(env, "GET", "/api/v1/feedback", undefined, { authorization: "Bearer wrong" })).status).toBe(401);
+ });
+
+ it("is disabled entirely when no token is configured", async () => {
+ const noTriage = makeEnv(undefined);
+ expect((await call(noTriage, "GET", "/api/v1/feedback", undefined, { authorization: "Bearer " })).status).toBe(401);
+ expect((await call(noTriage, "POST", "/api/v1/feedback", validFeedback)).status).toBe(201);
+ });
+
+ it("lists with filters and pagination", async () => {
+ await submit("alpha");
+ await submit("beta");
+ const r = await call(env, "POST", "/api/v1/feedback", { ...validFeedback, signal: { ...validFeedback.signal, severity: "low" }, content: { title: "gamma" } });
+ expect(r.status).toBe(201);
+
+ const all = await (await call(env, "GET", "/api/v1/feedback?limit=2", undefined, auth)).json() as { data: unknown[]; meta: Record<string, number> };
+ expect(all.data).toHaveLength(2);
+ expect(all.meta.total).toBe(3);
+ expect(all.meta.limit).toBe(2);
+
+ const low = await (await call(env, "GET", "/api/v1/feedback?severity=low", undefined, auth)).json() as { data: { content: { title: string } }[] };
+ expect(low.data.map((d) => d.content.title)).toEqual(["gamma"]);
+
+ const q = await (await call(env, "GET", "/api/v1/feedback?q=alph", undefined, auth)).json() as { data: unknown[] };
+ expect(q.data).toHaveLength(1);
+
+ expect((await call(env, "GET", "/api/v1/feedback?status=bogus", undefined, auth)).status).toBe(400);
+ });
+
+ it("patches status/quality/duplicate and reflects it in the receipt", async () => {
+ const a = await submit("a");
+ const b = await submit("b");
+
+ const res = await call(env, "PATCH", `/api/v1/feedback/${a.feedback_id}`, { status: "accepted", quality_score: 0.8, confirm: true }, auth);
+ expect(res.status).toBe(200);
+ const { data } = await res.json() as { data: Record<string, unknown> };
+ expect(data.status).toBe("accepted");
+ expect(data.quality_score).toBe(0.8);
+ expect(data.observations).toBe(2);
+
+ const rcptA = await (await call(env, "GET", `/api/v1/receipts/${a.receipt_id}`)).json() as { data: Record<string, unknown> };
+ expect(rcptA.data.status).toBe("accepted");
+ expect(rcptA.data.quality_score).toBe(0.8);
+
+ await call(env, "PATCH", `/api/v1/feedback/${b.feedback_id}`, { duplicate_of: a.feedback_id }, auth);
+ const rcptB = await (await call(env, "GET", `/api/v1/receipts/${b.receipt_id}`)).json() as { data: Record<string, unknown> };
+ expect(rcptB.data.status).toBe("duplicate");
+ expect(rcptB.data.duplicate_of).toBe(a.feedback_id);
+
+ await call(env, "PATCH", `/api/v1/feedback/${b.feedback_id}`, { status: "spam" }, auth);
+ const rejected = await (await call(env, "GET", `/api/v1/receipts/${b.receipt_id}`)).json() as { data: Record<string, unknown> };
+ // duplicate_of wins over dismissal so the agent is pointed at the canonical report
+ expect(rejected.data.status).toBe("duplicate");
+
+ expect((await call(env, "PATCH", `/api/v1/feedback/${a.feedback_id}`, { duplicate_of: a.feedback_id }, auth)).status).toBe(400);
+ expect((await call(env, "PATCH", `/api/v1/feedback/${a.feedback_id}`, { quality_score: 3 }, auth)).status).toBe(400);
+ expect((await call(env, "PATCH", `/api/v1/feedback/${a.feedback_id}`, {}, auth)).status).toBe(400);
+ expect((await call(env, "PATCH", "/api/v1/feedback/fb_missing", { status: "open" }, auth)).status).toBe(404);
+ });
+
+ it("merges sources into a target, moving evidence and observations", async () => {
+ const a = await submit("a");
+ const b = await submit("b");
+ const res = await call(env, "POST", "/api/v1/feedback/merge", { target_id: a.feedback_id, source_ids: [b.feedback_id] }, auth);
+ expect(res.status).toBe(200);
+ const { data } = await res.json() as { data: Record<string, unknown> };
+ expect(data.observations).toBe(2);
+ expect((data.evidence as unknown[]).length).toBe(2);
+
+ const bDetail = await (await call(env, "GET", `/api/v1/feedback/${b.feedback_id}`)).json() as { data: Record<string, unknown> };
+ expect(bDetail.data.duplicate_of).toBe(a.feedback_id);
+ expect(bDetail.data.status).toBe("resolved");
+
+ expect((await call(env, "POST", "/api/v1/feedback/merge", { target_id: "fb_missing", source_ids: [b.feedback_id] }, auth)).status).toBe(404);
+ expect((await call(env, "POST", "/api/v1/feedback/merge", { target_id: a.feedback_id }, auth)).status).toBe(400);
+ });
+
+ it("deletes a report with its evidence", async () => {
+ const a = await submit("a");
+ expect((await call(env, "DELETE", `/api/v1/feedback/${a.feedback_id}`, undefined, auth)).status).toBe(200);
+ expect((await call(env, "GET", `/api/v1/feedback/${a.feedback_id}`)).status).toBe(404);
+ expect((await call(env, "DELETE", `/api/v1/feedback/${a.feedback_id}`, undefined, auth)).status).toBe(404);
+ });
+
+ it("validates custom category names", async () => {
+ expect((await call(env, "POST", "/api/v1/categories", { name: "Bad Name" }, auth)).status).toBe(400);
+ expect((await call(env, "POST", "/api/v1/categories", { name: "bug" }, auth)).status).toBe(400);
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/agent_feedback.ts b/cloudflare-workers/api-edge/src/agent_feedback.ts
new file mode 100644
index 00000000..de0c3a04
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/agent_feedback.ts
@@ -0,0 +1,1081 @@
+// feedback.now protocol receiver (https://feedback.now).
+//
+// Coding agents (Claude Code, Codex, Cursor, ...) that use our API discover
+// /.well-known/agent-feedback.json on this host, read the policy, and POST
+// structured bug / friction reports. Every submission returns a receipt the
+// agent can poll to see how we triaged it. The protocol is SDK-less HTTP, so
+// this module is the whole integration: no CP, no cell, D1 only.
+//
+// Public (agent-facing):
+// GET /.well-known/agent-feedback.json
+// GET /api/v1/policy
+// POST /api/v1/feedback
+// POST /api/v1/feedback/:id/attachments
+// POST /api/v1/observations
+// GET /api/v1/feedback/:id
+// GET /api/v1/receipts/:id
+// GET /api/v1/categories
+//
+// Triage (bearer AGENT_FEEDBACK_TRIAGE_TOKEN):
+// GET /api/v1/feedback
+// PATCH /api/v1/feedback/:id
+// DELETE /api/v1/feedback/:id
+// POST /api/v1/feedback/merge
+// POST /api/v1/categories
+// GET /api/v1/agents
+//
+// Requests may be signed with an Ed25519 key (X-Agent-Key / X-Agent-Signature /
+// X-Agent-Timestamp). Signing is optional per the spec; a valid signature ties
+// the submission to an agent identity whose reputation we track. An invalid
+// signature is rejected — a present-but-wrong signature is a bug worth
+// surfacing, not something to silently downgrade to anonymous.
+
+export interface AgentFeedbackEnv {
+ OPENCOMPUTER_DB: D1Database;
+ AGENT_FEEDBACK_TRIAGE_TOKEN?: string;
+}
+
+export const AGENT_FEEDBACK_ROUTE_PREFIX = "/api/v1/";
+export const AGENT_FEEDBACK_DISCOVERY_PATH = "/.well-known/agent-feedback.json";
+
+export const CATEGORIES = ["bug", "docs_mismatch", "friction", "feature_gap", "quality_degradation", "other"] as const;
+export const SEVERITIES = ["critical", "high", "medium", "low"] as const;
+export const REPRODUCIBILITY = ["always", "sometimes", "intermittent", "once"] as const;
+export const SURFACE_KINDS = ["api_endpoint", "docs_page", "cli_command", "sdk_method", "other"] as const;
+export const EVIDENCE_TYPES = ["http_summary", "stderr_excerpt", "repro_steps", "screenshot", "log_excerpt", "other"] as const;
+export const FEEDBACK_STATUSES = ["open", "investigating", "accepted", "resolved", "dismissed", "spam"] as const;
+export const RECEIPT_STATUSES = ["accepted", "needs_more_evidence", "duplicate", "rejected", "queued"] as const;
+
+// Built-in categories plus any custom ones added via POST /api/v1/categories.
+type Category = string;
+type Severity = (typeof SEVERITIES)[number];
+type Reproducibility = (typeof REPRODUCIBILITY)[number];
+type SurfaceKind = (typeof SURFACE_KINDS)[number];
+type EvidenceType = (typeof EVIDENCE_TYPES)[number];
+type FeedbackStatus = (typeof FEEDBACK_STATUSES)[number];
+type ReceiptStatus = (typeof RECEIPT_STATUSES)[number];
+
+export const LIMITS = {
+ max_evidence_per_feedback: 10,
+ max_evidence_content_bytes: 65536,
+ max_title_length: 256,
+ max_summary_length: 4096,
+ max_hypothesis_length: 2048,
+ confidence_range: { min: 0, max: 1 },
+} as const;
+
+export const RATE_LIMIT_PER_HOUR = 100;
+// Same surface + same normalized title inside this window folds into the
+// existing report as another observation instead of a new row.
+const DEDUPE_WINDOW_SEC = 30 * 24 * 3600;
+const SIGNATURE_SKEW_SEC = 300;
+
+// ── response helpers ─────────────────────────────────────────────────────
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+}
+
+function errorJSON(error: string, message: string, status: number): Response {
+ return json({ error, message }, status);
+}
+
+interface FieldError {
+ field: string;
+ error: string;
+ message: string;
+}
+
+function validationJSON(errors: FieldError[]): Response {
+ return json({ error: "validation_failed", errors }, 400);
+}
+
+function nowSec(): number {
+ return Math.floor(Date.now() / 1000);
+}
+
+function iso(sec: number): string {
+ return new Date(sec * 1000).toISOString();
+}
+
+function newID(prefix: string): string {
+ const bytes = new Uint8Array(12);
+ crypto.getRandomValues(bytes);
+ return prefix + [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
+}
+
+async function sha256Hex(data: string | Uint8Array): Promise<string> {
+ const buf = typeof data === "string" ? new TextEncoder().encode(data) : data;
+ const digest = await crypto.subtle.digest("SHA-256", buf);
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
+}
+
+function b64Decode(s: string): Uint8Array | null {
+ try {
+ const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/"));
+ const out = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
+ return out;
+ } catch {
+ return null;
+ }
+}
+
+function constantTimeEqual(a: string, b: string): boolean {
+ if (a.length !== b.length) return false;
+ let diff = 0;
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
+ return diff === 0;
+}
+
+// ── discovery + policy ───────────────────────────────────────────────────
+
+export function discoveryDocument(): Record<string, unknown> {
+ return {
+ schema_version: "1.1",
+ name: "OpenComputer",
+ description:
+ "Agent feedback plane for the OpenComputer sandbox API, SDKs, CLI, and docs. " +
+ "Agents submit structured bug reports and friction signals they hit while using OpenComputer.",
+ spec_url: "https://docs.opencomputer.dev/api-reference/agent-feedback",
+ policy_url: "/api/v1/policy",
+ auth: {
+ type: "ed25519",
+ description: "Sign requests with an Ed25519 keypair for agent identity. Optional but recommended.",
+ headers: {
+ "X-Agent-Key": "Base64-encoded SPKI DER Ed25519 public key",
+ "X-Agent-Signature": "Base64-encoded Ed25519 signature of: timestamp\\nmethod\\npath\\nsha256(body)",
+ "X-Agent-Timestamp": "ISO 8601 timestamp (must be within 5 minutes)",
+ },
+ },
+ endpoints: {
+ feedback: {
+ submit: { method: "POST", url: "/api/v1/feedback", description: "Submit a full structured feedback report with optional evidence." },
+ get: { method: "GET", url: "/api/v1/feedback/{id}", description: "Get a single feedback report with evidence." },
+ attach_evidence: { method: "POST", url: "/api/v1/feedback/{id}/attachments", description: "Add evidence to an existing feedback report." },
+ },
+ observations: {
+ submit: { method: "POST", url: "/api/v1/observations", description: "Submit a lightweight observation signal." },
+ },
+ receipts: {
+ get: { method: "GET", url: "/api/v1/receipts/{id}", description: "Look up a receipt by ID to check submission and triage status." },
+ },
+ policy: {
+ get: { method: "GET", url: "/api/v1/policy", description: "Get the feedback policy including accepted categories, evidence types, and limits." },
+ },
+ categories: {
+ list: { method: "GET", url: "/api/v1/categories", description: "List available feedback categories." },
+ },
+ },
+ categories: CATEGORIES,
+ evidence_types: EVIDENCE_TYPES,
+ contact: "https://opencomputer.dev",
+ };
+}
+
+export function policyDocument(): Record<string, unknown> {
+ return {
+ version: "1.0",
+ categories: CATEGORIES,
+ severity_levels: SEVERITIES,
+ reproducibility_options: REPRODUCIBILITY,
+ evidence_types: EVIDENCE_TYPES,
+ surface_kinds: SURFACE_KINDS,
+ limits: LIMITS,
+ rate_limit_per_hour: RATE_LIMIT_PER_HOUR,
+ endpoints: {
+ submit_feedback: "/api/v1/feedback",
+ submit_observation: "/api/v1/observations",
+ get_receipt: "/api/v1/receipts/{id}",
+ discovery: AGENT_FEEDBACK_DISCOVERY_PATH,
+ },
+ };
+}
+
+// ── validation ───────────────────────────────────────────────────────────
+
+type Obj = Record<string, unknown>;
+
+function isObj(v: unknown): v is Obj {
+ return typeof v === "object" && v !== null && !Array.isArray(v);
+}
+
+function oneOf<T extends string>(values: readonly T[], v: unknown): v is T {
+ return typeof v === "string" && (values as readonly string[]).includes(v);
+}
+
+class Validator {
+ errors: FieldError[] = [];
+
+ requiredString(obj: Obj, field: string, path: string, max?: number): string | undefined {
+ const v = obj[field];
+ if (typeof v !== "string" || v.trim() === "") {
+ this.errors.push({ field: path, error: "required", message: `${path} is required` });
+ return undefined;
+ }
+ if (max !== undefined && v.length > max) {
+ this.errors.push({ field: path, error: "too_long", message: `${path} must be at most ${max} characters` });
+ return undefined;
+ }
+ return v;
+ }
+
+ optionalString(obj: Obj, field: string, path: string, max?: number): string | undefined {
+ const v = obj[field];
+ if (v === undefined || v === null) return undefined;
+ if (typeof v !== "string") {
+ this.errors.push({ field: path, error: "invalid_type", message: `${path} must be a string` });
+ return undefined;
+ }
+ if (max !== undefined && v.length > max) {
+ this.errors.push({ field: path, error: "too_long", message: `${path} must be at most ${max} characters` });
+ return undefined;
+ }
+ return v;
+ }
+
+ enumField<T extends string>(obj: Obj, field: string, path: string, values: readonly T[], required: boolean): T | undefined {
+ const v = obj[field];
+ if (v === undefined || v === null) {
+ if (required) this.errors.push({ field: path, error: "required", message: `${path} is required` });
+ return undefined;
+ }
+ if (!oneOf(values, v)) {
+ this.errors.push({ field: path, error: "invalid_enum", message: `${path} must be one of: ${values.join(", ")}` });
+ return undefined;
+ }
+ return v;
+ }
+
+ category(obj: Obj, path: string, required: boolean): string | undefined {
+ const v = obj.category;
+ if (v === undefined || v === null) {
+ if (required) this.errors.push({ field: path, error: "required", message: `${path} is required` });
+ return undefined;
+ }
+ if (typeof v !== "string" || !/^[a-z][a-z0-9_]{1,63}$/.test(v)) {
+ this.errors.push({ field: path, error: "invalid_enum", message: `${path} must be one of: ${CATEGORIES.join(", ")} (or a custom category)` });
+ return undefined;
+ }
+ return v;
+ }
+
+ confidence(obj: Obj, path: string, required: boolean): number | undefined {
+ const v = obj.confidence;
+ if (v === undefined || v === null) {
+ if (required) this.errors.push({ field: path, error: "required", message: `${path} is required` });
+ return undefined;
+ }
+ if (typeof v !== "number" || Number.isNaN(v) || v < LIMITS.confidence_range.min || v > LIMITS.confidence_range.max) {
+ this.errors.push({ field: path, error: "out_of_range", message: `${path} must be a number between 0 and 1` });
+ return undefined;
+ }
+ return v;
+ }
+}
+
+interface EvidenceIn {
+ type: EvidenceType;
+ content: string;
+ redacted: boolean;
+}
+
+function parseEvidenceItem(v: Validator, item: unknown, path: string): EvidenceIn | undefined {
+ if (!isObj(item)) {
+ v.errors.push({ field: path, error: "invalid_type", message: `${path} must be an object` });
+ return undefined;
+ }
+ const type = v.enumField(item, "type", `${path}.type`, EVIDENCE_TYPES, true);
+ const content = item.content;
+ if (typeof content !== "string") {
+ v.errors.push({ field: `${path}.content`, error: "required", message: `${path}.content is required` });
+ return undefined;
+ }
+ if (new TextEncoder().encode(content).byteLength > LIMITS.max_evidence_content_bytes) {
+ v.errors.push({ field: `${path}.content`, error: "too_long", message: `${path}.content exceeds ${LIMITS.max_evidence_content_bytes} bytes` });
+ return undefined;
+ }
+ if (item.redacted !== undefined && typeof item.redacted !== "boolean") {
+ v.errors.push({ field: `${path}.redacted`, error: "invalid_type", message: `${path}.redacted must be a boolean` });
+ return undefined;
+ }
+ if (!type) return undefined;
+ return { type, content, redacted: item.redacted === true };
+}
+
+function parseEvidenceList(v: Validator, raw: unknown, path: string, existing: number): EvidenceIn[] {
+ if (raw === undefined || raw === null) return [];
+ if (!Array.isArray(raw)) {
+ v.errors.push({ field: path, error: "invalid_type", message: `${path} must be an array` });
+ return [];
+ }
+ if (raw.length + existing > LIMITS.max_evidence_per_feedback) {
+ v.errors.push({ field: path, error: "too_many", message: `at most ${LIMITS.max_evidence_per_feedback} evidence items per feedback` });
+ return [];
+ }
+ const out: EvidenceIn[] = [];
+ raw.forEach((item, i) => {
+ const parsed = parseEvidenceItem(v, item, `${path}[${i}]`);
+ if (parsed) out.push(parsed);
+ });
+ return out;
+}
+
+interface FeedbackIn {
+ reporter: { agent_vendor: string; agent_product: string; agent_version?: string };
+ subject: { surface: string; domain: string; kind?: SurfaceKind; product?: string };
+ signal: { category: Category; severity: Severity; reproducibility?: Reproducibility; confidence: number };
+ content: { title: string; summary?: string; hypothesis?: string };
+ evidence: EvidenceIn[];
+}
+
+function parseFeedback(body: unknown): { ok: true; value: FeedbackIn } | { ok: false; errors: FieldError[] } {
+ const v = new Validator();
+ if (!isObj(body)) return { ok: false, errors: [{ field: "", error: "invalid_type", message: "body must be a JSON object" }] };
+
+ const reporter = isObj(body.reporter) ? body.reporter : undefined;
+ const subject = isObj(body.subject) ? body.subject : undefined;
+ const signal = isObj(body.signal) ? body.signal : undefined;
+ const content = isObj(body.content) ? body.content : undefined;
+ for (const [k, present] of [["reporter", reporter], ["subject", subject], ["signal", signal], ["content", content]] as const) {
+ if (!present) v.errors.push({ field: k, error: "required", message: `${k} is required` });
+ }
+ if (!reporter || !subject || !signal || !content) return { ok: false, errors: v.errors };
+
+ const agent_vendor = v.requiredString(reporter, "agent_vendor", "reporter.agent_vendor", 128);
+ const agent_product = v.requiredString(reporter, "agent_product", "reporter.agent_product", 128);
+ const agent_version = v.optionalString(reporter, "agent_version", "reporter.agent_version", 64);
+
+ const surface = v.requiredString(subject, "surface", "subject.surface", 512);
+ const domain = v.requiredString(subject, "domain", "subject.domain", 253);
+ const kind = v.enumField(subject, "kind", "subject.kind", SURFACE_KINDS, false);
+ const product = v.optionalString(subject, "product", "subject.product", 128);
+
+ const category = v.category(signal, "signal.category", true);
+ const severity = v.enumField(signal, "severity", "signal.severity", SEVERITIES, true);
+ const reproducibility = v.enumField(signal, "reproducibility", "signal.reproducibility", REPRODUCIBILITY, false);
+ const confidence = v.confidence(signal, "signal.confidence", true);
+
+ const title = v.requiredString(content, "title", "content.title", LIMITS.max_title_length);
+ const summary = v.optionalString(content, "summary", "content.summary", LIMITS.max_summary_length);
+ const hypothesis = v.optionalString(content, "hypothesis", "content.hypothesis", LIMITS.max_hypothesis_length);
+
+ const evidence = parseEvidenceList(v, body.evidence, "evidence", 0);
+
+ if (v.errors.length) return { ok: false, errors: v.errors };
+ return {
+ ok: true,
+ value: {
+ reporter: { agent_vendor: agent_vendor!, agent_product: agent_product!, agent_version },
+ subject: { surface: surface!, domain: domain!, kind, product },
+ signal: { category: category!, severity: severity!, reproducibility, confidence: confidence! },
+ content: { title: title!, summary, hypothesis },
+ evidence,
+ },
+ };
+}
+
+interface ObservationIn {
+ surface: string;
+ domain: string;
+ agent_vendor: string;
+ agent_product: string;
+ category?: Category;
+ severity?: Severity;
+ confidence?: number;
+ summary?: string;
+}
+
+function parseObservation(body: unknown): { ok: true; value: ObservationIn } | { ok: false; errors: FieldError[] } {
+ const v = new Validator();
+ if (!isObj(body)) return { ok: false, errors: [{ field: "", error: "invalid_type", message: "body must be a JSON object" }] };
+ const surface = v.requiredString(body, "surface", "surface", 512);
+ const domain = v.requiredString(body, "domain", "domain", 253);
+ const agent_vendor = v.requiredString(body, "agent_vendor", "agent_vendor", 128);
+ const agent_product = v.requiredString(body, "agent_product", "agent_product", 128);
+ const category = v.category(body, "category", false);
+ const severity = v.enumField(body, "severity", "severity", SEVERITIES, false);
+ const confidence = v.confidence(body, "confidence", false);
+ const summary = v.optionalString(body, "summary", "summary", LIMITS.max_summary_length);
+ if (v.errors.length) return { ok: false, errors: v.errors };
+ return {
+ ok: true,
+ value: { surface: surface!, domain: domain!, agent_vendor: agent_vendor!, agent_product: agent_product!, category, severity, confidence, summary },
+ };
+}
+
+// ── Ed25519 request signing ──────────────────────────────────────────────
+
+type SignatureCheck = { ok: true; agentKey: string | null } | { ok: false; message: string };
+
+// Canonical string per the spec: `timestamp\nmethod\npath\nsha256(body)`,
+// with sha256 hex-encoded and path excluding the query string.
+export async function signingPayload(timestamp: string, method: string, path: string, body: string): Promise<string> {
+ return `${timestamp}\n${method.toUpperCase()}\n${path}\n${await sha256Hex(body)}`;
+}
+
+async function verifyAgentSignature(req: Request, path: string, body: string): Promise<SignatureCheck> {
+ const key = req.headers.get("X-Agent-Key");
+ const sig = req.headers.get("X-Agent-Signature");
+ const ts = req.headers.get("X-Agent-Timestamp");
+ if (!key && !sig && !ts) return { ok: true, agentKey: null };
+ if (!key || !sig || !ts) return { ok: false, message: "X-Agent-Key, X-Agent-Signature and X-Agent-Timestamp must be sent together" };
+
+ const tsMs = Date.parse(ts);
+ if (Number.isNaN(tsMs)) return { ok: false, message: "X-Agent-Timestamp must be ISO 8601" };
+ if (Math.abs(Date.now() - tsMs) > SIGNATURE_SKEW_SEC * 1000) return { ok: false, message: "X-Agent-Timestamp outside the 5 minute window" };
+
+ const keyDer = b64Decode(key);
+ const sigBytes = b64Decode(sig);
+ if (!keyDer || !sigBytes) return { ok: false, message: "X-Agent-Key and X-Agent-Signature must be base64" };
+
+ let pub: CryptoKey;
+ try {
+ pub = await crypto.subtle.importKey("spki", keyDer, { name: "Ed25519" }, false, ["verify"]);
+ } catch {
+ return { ok: false, message: "X-Agent-Key is not a SPKI DER Ed25519 public key" };
+ }
+ const payload = new TextEncoder().encode(await signingPayload(ts, req.method, path, body));
+ const valid = await crypto.subtle.verify({ name: "Ed25519" }, pub, sigBytes, payload);
+ if (!valid) return { ok: false, message: "X-Agent-Signature does not verify" };
+ return { ok: true, agentKey: key };
+}
+
+async function categoryAllowed(env: AgentFeedbackEnv, cat: string | undefined, field: string): Promise<FieldError | null> {
+ if (cat === undefined || (CATEGORIES as readonly string[]).includes(cat)) return null;
+ const row = await env.OPENCOMPUTER_DB.prepare("SELECT name FROM agent_feedback_categories WHERE name = ?1").bind(cat).first<{ name: string }>();
+ return row ? null : { field, error: "invalid_enum", message: `unknown category ${cat}` };
+}
+
+// ── persistence ──────────────────────────────────────────────────────────
+
+interface FeedbackRow {
+ id: string;
+ status: FeedbackStatus;
+ category: Category;
+ severity: Severity;
+ reproducibility: Reproducibility | null;
+ confidence: number;
+ surface: string;
+ domain: string;
+ surface_kind: SurfaceKind | null;
+ product: string | null;
+ title: string;
+ summary: string | null;
+ hypothesis: string | null;
+ agent_vendor: string;
+ agent_product: string;
+ agent_version: string | null;
+ agent_key: string | null;
+ observations: number;
+ quality_score: number | null;
+ duplicate_of: string | null;
+ created_at: number;
+ updated_at: number;
+}
+
+interface EvidenceRow {
+ id: string;
+ type: EvidenceType;
+ content: string;
+ redacted: number;
+ created_at: number;
+}
+
+interface ReceiptRow {
+ id: string;
+ feedback_id: string | null;
+ observation_id: string | null;
+ status: ReceiptStatus;
+ duplicate_of: string | null;
+ created_at: number;
+}
+
+function feedbackSummary(row: FeedbackRow): Record<string, unknown> {
+ return {
+ id: row.id,
+ reporter: { agent_vendor: row.agent_vendor, agent_product: row.agent_product, agent_version: row.agent_version ?? undefined },
+ subject: { surface: row.surface, domain: row.domain, kind: row.surface_kind ?? undefined, product: row.product ?? undefined },
+ signal: {
+ category: row.category,
+ severity: row.severity,
+ reproducibility: row.reproducibility ?? undefined,
+ confidence: row.confidence,
+ },
+ content: { title: row.title, summary: row.summary ?? undefined, hypothesis: row.hypothesis ?? undefined },
+ status: row.status,
+ quality_score: row.quality_score,
+ observations: row.observations,
+ created_at: iso(row.created_at),
+ updated_at: iso(row.updated_at),
+ };
+}
+
+async function loadFeedbackDetail(db: D1Database, id: string): Promise<Record<string, unknown> | null> {
+ const row = await db.prepare("SELECT * FROM agent_feedback WHERE id = ?1").bind(id).first<FeedbackRow>();
+ if (!row) return null;
+ const ev = await db
+ .prepare("SELECT id, type, content, redacted, created_at FROM agent_feedback_evidence WHERE feedback_id = ?1 ORDER BY created_at, id")
+ .bind(id)
+ .all<EvidenceRow>();
+ return {
+ ...feedbackSummary(row),
+ evidence: ev.results.map((e) => ({ id: e.id, type: e.type, content: e.content, redacted: !!e.redacted, created_at: iso(e.created_at) })),
+ duplicate_of: row.duplicate_of,
+ };
+}
+
+function dedupeKeyInput(domain: string, surface: string, title: string): string {
+ const norm = (s: string) => s.trim().toLowerCase().replace(/\s+/g, " ");
+ return `${norm(domain)}|${norm(surface)}|${norm(title)}`;
+}
+
+function clientIP(req: Request): string | null {
+ return req.headers.get("CF-Connecting-IP")?.trim() || null;
+}
+
+async function overRateLimit(db: D1Database, agentKey: string | null, ip: string | null): Promise<boolean> {
+ const since = nowSec() - 3600;
+ const column = agentKey ? "agent_key" : "client_ip";
+ const value = agentKey ?? ip;
+ if (!value) return false;
+ const row = await db
+ .prepare(`SELECT COUNT(*) AS n FROM agent_feedback_receipts WHERE ${column} = ?1 AND created_at > ?2`)
+ .bind(value, since)
+ .first<{ n: number }>();
+ return (row?.n ?? 0) >= RATE_LIMIT_PER_HOUR;
+}
+
+function bumpAgent(db: D1Database, agentKey: string, vendor: string, product: string, ts: number): D1PreparedStatement {
+ return db
+ .prepare(
+ `INSERT INTO agent_feedback_agents (agent_key, agent_vendor, agent_product, submissions, accepted, dismissed, first_seen, last_seen)
+ VALUES (?1, ?2, ?3, 1, 0, 0, ?4, ?4)
+ ON CONFLICT(agent_key) DO UPDATE SET submissions = submissions + 1, last_seen = ?4, agent_vendor = ?2, agent_product = ?3`,
+ )
+ .bind(agentKey, vendor, product, ts);
+}
+
+// ── handlers: public ─────────────────────────────────────────────────────
+
+async function readJSONBody(req: Request): Promise<{ text: string; body: unknown } | Response> {
+ const text = await req.text();
+ if (text.length > 1_000_000) return errorJSON("payload_too_large", "request body exceeds 1MB", 413);
+ try {
+ return { text, body: text ? JSON.parse(text) : {} };
+ } catch {
+ return errorJSON("invalid_json", "request body must be valid JSON", 400);
+ }
+}
+
+async function submitFeedback(req: Request, env: AgentFeedbackEnv, path: string): Promise<Response> {
+ const read = await readJSONBody(req);
+ if (read instanceof Response) return read;
+ const sig = await verifyAgentSignature(req, path, read.text);
+ if (!sig.ok) return errorJSON("invalid_signature", sig.message, 401);
+
+ const parsed = parseFeedback(read.body);
+ if (!parsed.ok) return validationJSON(parsed.errors);
+ const fb = parsed.value;
+ const catErr = await categoryAllowed(env, fb.signal.category, "signal.category");
+ if (catErr) return validationJSON([catErr]);
+
+ const db = env.OPENCOMPUTER_DB;
+ const ip = clientIP(req);
+ if (await overRateLimit(db, sig.agentKey, ip)) return errorJSON("rate_limited", `at most ${RATE_LIMIT_PER_HOUR} submissions per hour`, 429);
+
+ const ts = nowSec();
+ const dedupeKey = await sha256Hex(dedupeKeyInput(fb.subject.domain, fb.subject.surface, fb.content.title));
+ const existing = await db
+ .prepare(
+ `SELECT id FROM agent_feedback WHERE dedupe_key = ?1 AND created_at > ?2 AND status NOT IN ('resolved','dismissed','spam') AND duplicate_of IS NULL
+ ORDER BY created_at DESC LIMIT 1`,
+ )
+ .bind(dedupeKey, ts - DEDUPE_WINDOW_SEC)
+ .first<{ id: string }>();
+
+ const receiptID = newID("rcpt_");
+ const stmts: D1PreparedStatement[] = [];
+ let feedbackID: string;
+ let status: ReceiptStatus;
+ let evidenceIDs: string[] = [];
+
+ if (existing) {
+ feedbackID = existing.id;
+ status = "duplicate";
+ stmts.push(db.prepare("UPDATE agent_feedback SET observations = observations + 1, updated_at = ?2 WHERE id = ?1").bind(feedbackID, ts));
+ } else {
+ feedbackID = newID("fb_");
+ status = "accepted";
+ stmts.push(
+ db
+ .prepare(
+ `INSERT INTO agent_feedback (id, status, category, severity, reproducibility, confidence, surface, domain, surface_kind, product,
+ title, summary, hypothesis, agent_vendor, agent_product, agent_version, agent_key, dedupe_key, observations, created_at, updated_at)
+ VALUES (?1, 'open', ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, 1, ?18, ?18)`,
+ )
+ .bind(
+ feedbackID,
+ fb.signal.category,
+ fb.signal.severity,
+ fb.signal.reproducibility ?? null,
+ fb.signal.confidence,
+ fb.subject.surface,
+ fb.subject.domain,
+ fb.subject.kind ?? null,
+ fb.subject.product ?? null,
+ fb.content.title,
+ fb.content.summary ?? null,
+ fb.content.hypothesis ?? null,
+ fb.reporter.agent_vendor,
+ fb.reporter.agent_product,
+ fb.reporter.agent_version ?? null,
+ sig.agentKey,
+ dedupeKey,
+ ts,
+ ),
+ );
+ evidenceIDs = fb.evidence.map(() => newID("ev_"));
+ fb.evidence.forEach((e, i) => {
+ stmts.push(
+ db
+ .prepare("INSERT INTO agent_feedback_evidence (id, feedback_id, type, content, redacted, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)")
+ .bind(evidenceIDs[i], feedbackID, e.type, e.content, e.redacted ? 1 : 0, ts),
+ );
+ });
+ }
+
+ stmts.push(
+ db
+ .prepare(
+ "INSERT INTO agent_feedback_receipts (id, feedback_id, observation_id, status, duplicate_of, agent_key, client_ip, created_at) VALUES (?1, ?2, NULL, ?3, ?4, ?5, ?6, ?7)",
+ )
+ .bind(receiptID, feedbackID, status, existing ? feedbackID : null, sig.agentKey, ip, ts),
+ );
+ if (sig.agentKey) stmts.push(bumpAgent(db, sig.agentKey, fb.reporter.agent_vendor, fb.reporter.agent_product, ts));
+ await db.batch(stmts);
+
+ return json(
+ {
+ receipt: {
+ id: receiptID,
+ feedback_id: feedbackID,
+ status,
+ ...(existing ? { duplicate_of: feedbackID } : {}),
+ evidence_ids: evidenceIDs,
+ created_at: iso(ts),
+ },
+ },
+ 201,
+ );
+}
+
+async function submitObservation(req: Request, env: AgentFeedbackEnv, path: string): Promise<Response> {
+ const read = await readJSONBody(req);
+ if (read instanceof Response) return read;
+ const sig = await verifyAgentSignature(req, path, read.text);
+ if (!sig.ok) return errorJSON("invalid_signature", sig.message, 401);
+
+ const parsed = parseObservation(read.body);
+ if (!parsed.ok) return validationJSON(parsed.errors);
+ const ob = parsed.value;
+ const catErr = await categoryAllowed(env, ob.category, "category");
+ if (catErr) return validationJSON([catErr]);
+
+ const db = env.OPENCOMPUTER_DB;
+ const ip = clientIP(req);
+ if (await overRateLimit(db, sig.agentKey, ip)) return errorJSON("rate_limited", `at most ${RATE_LIMIT_PER_HOUR} submissions per hour`, 429);
+
+ const ts = nowSec();
+ const observationID = newID("obs_");
+ const receiptID = newID("rcpt_");
+ const stmts = [
+ db
+ .prepare(
+ `INSERT INTO agent_observations (id, surface, domain, category, severity, confidence, summary, agent_vendor, agent_product, agent_key, created_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)`,
+ )
+ .bind(
+ observationID,
+ ob.surface,
+ ob.domain,
+ ob.category ?? null,
+ ob.severity ?? null,
+ ob.confidence ?? null,
+ ob.summary ?? null,
+ ob.agent_vendor,
+ ob.agent_product,
+ sig.agentKey,
+ ts,
+ ),
+ db
+ .prepare(
+ "INSERT INTO agent_feedback_receipts (id, feedback_id, observation_id, status, duplicate_of, agent_key, client_ip, created_at) VALUES (?1, NULL, ?2, 'accepted', NULL, ?3, ?4, ?5)",
+ )
+ .bind(receiptID, observationID, sig.agentKey, ip, ts),
+ ];
+ if (sig.agentKey) stmts.push(bumpAgent(db, sig.agentKey, ob.agent_vendor, ob.agent_product, ts));
+ await db.batch(stmts);
+
+ return json({ receipt: { id: receiptID, observation_id: observationID, status: "accepted", created_at: iso(ts) } }, 201);
+}
+
+async function attachEvidence(req: Request, env: AgentFeedbackEnv, path: string, id: string): Promise<Response> {
+ const read = await readJSONBody(req);
+ if (read instanceof Response) return read;
+ const sig = await verifyAgentSignature(req, path, read.text);
+ if (!sig.ok) return errorJSON("invalid_signature", sig.message, 401);
+
+ const db = env.OPENCOMPUTER_DB;
+ const fb = await db.prepare("SELECT id FROM agent_feedback WHERE id = ?1").bind(id).first<{ id: string }>();
+ if (!fb) return errorJSON("not_found", "feedback not found", 404);
+ const count = await db.prepare("SELECT COUNT(*) AS n FROM agent_feedback_evidence WHERE feedback_id = ?1").bind(id).first<{ n: number }>();
+
+ // EvidenceInput is a single item, `{ evidence: [...] }`, or a bare array.
+ const body = read.body;
+ let raw: unknown;
+ if (Array.isArray(body)) raw = body;
+ else if (isObj(body) && Array.isArray(body.evidence)) raw = body.evidence;
+ else raw = [body];
+
+ const v = new Validator();
+ const items = parseEvidenceList(v, raw, "evidence", count?.n ?? 0);
+ if (v.errors.length) return validationJSON(v.errors);
+ if (items.length === 0) return validationJSON([{ field: "evidence", error: "required", message: "at least one evidence item is required" }]);
+
+ const ts = nowSec();
+ const ids = items.map(() => newID("ev_"));
+ const stmts = items.map((e, i) =>
+ db
+ .prepare("INSERT INTO agent_feedback_evidence (id, feedback_id, type, content, redacted, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)")
+ .bind(ids[i], id, e.type, e.content, e.redacted ? 1 : 0, ts),
+ );
+ stmts.push(db.prepare("UPDATE agent_feedback SET updated_at = ?2 WHERE id = ?1").bind(id, ts));
+ await db.batch(stmts);
+ return json({ data: { feedback_id: id, evidence_ids: ids, created_at: iso(ts) } }, 201);
+}
+
+async function getReceipt(env: AgentFeedbackEnv, id: string): Promise<Response> {
+ const db = env.OPENCOMPUTER_DB;
+ const r = await db.prepare("SELECT id, feedback_id, observation_id, status, duplicate_of, created_at FROM agent_feedback_receipts WHERE id = ?1").bind(id).first<ReceiptRow>();
+ if (!r) return errorJSON("not_found", "receipt not found", 404);
+
+ // Reflect triage on the linked feedback so the agent sees the loop close.
+ let status: ReceiptStatus = r.status;
+ let qualityScore: number | null = null;
+ let duplicateOf = r.duplicate_of;
+ let feedbackStatus: FeedbackStatus | null = null;
+ if (r.feedback_id) {
+ const fb = await db
+ .prepare("SELECT status, quality_score, duplicate_of FROM agent_feedback WHERE id = ?1")
+ .bind(r.feedback_id)
+ .first<{ status: FeedbackStatus; quality_score: number | null; duplicate_of: string | null }>();
+ if (fb) {
+ feedbackStatus = fb.status;
+ qualityScore = fb.quality_score;
+ if (fb.duplicate_of) {
+ status = "duplicate";
+ duplicateOf = fb.duplicate_of;
+ } else if (fb.status === "dismissed" || fb.status === "spam") {
+ status = "rejected";
+ } else if (fb.status === "accepted" || fb.status === "resolved") {
+ status = "accepted";
+ }
+ }
+ }
+ return json({
+ data: {
+ id: r.id,
+ feedback_id: r.feedback_id,
+ observation_id: r.observation_id,
+ status,
+ feedback_status: feedbackStatus,
+ quality_score: qualityScore,
+ duplicate_of: duplicateOf,
+ budget_remaining: null,
+ budget_delta: null,
+ created_at: iso(r.created_at),
+ },
+ });
+}
+
+async function listCategories(env: AgentFeedbackEnv): Promise<Response> {
+ const custom = await env.OPENCOMPUTER_DB.prepare("SELECT name FROM agent_feedback_categories ORDER BY name").all<{ name: string }>();
+ return json({ data: [...CATEGORIES, ...custom.results.map((c) => c.name)] });
+}
+
+// ── handlers: triage ─────────────────────────────────────────────────────
+
+function triageAuthorized(req: Request, env: AgentFeedbackEnv): boolean {
+ const token = env.AGENT_FEEDBACK_TRIAGE_TOKEN;
+ if (!token) return false;
+ const auth = req.headers.get("authorization") ?? "";
+ const m = auth.match(/^Bearer\s+(.+)$/i);
+ return !!m && constantTimeEqual(m[1].trim(), token);
+}
+
+async function listFeedback(req: Request, env: AgentFeedbackEnv): Promise<Response> {
+ const url = new URL(req.url);
+ const q = url.searchParams;
+ const where: string[] = [];
+ const binds: unknown[] = [];
+ const push = (clause: string, value: unknown) => {
+ binds.push(value);
+ where.push(clause.replace("?", `?${binds.length}`));
+ };
+
+ const status = q.get("status");
+ if (status) {
+ if (!oneOf(FEEDBACK_STATUSES, status)) return validationJSON([{ field: "status", error: "invalid_enum", message: `status must be one of: ${FEEDBACK_STATUSES.join(", ")}` }]);
+ push("status = ?", status);
+ }
+ const category = q.get("category");
+ if (category) push("category = ?", category);
+ const severity = q.get("severity");
+ if (severity) {
+ if (!oneOf(SEVERITIES, severity)) return validationJSON([{ field: "severity", error: "invalid_enum", message: `severity must be one of: ${SEVERITIES.join(", ")}` }]);
+ push("severity = ?", severity);
+ }
+ const domain = q.get("domain");
+ if (domain) push("domain = ?", domain);
+ const surface = q.get("surface");
+ if (surface) push("surface LIKE ?", `%${surface}%`);
+ const text = q.get("q");
+ if (text) {
+ binds.push(`%${text}%`);
+ where.push(`(title LIKE ?${binds.length} OR summary LIKE ?${binds.length})`);
+ }
+
+ const limit = Math.min(200, Math.max(1, Number(q.get("limit") ?? 50) || 50));
+ const offset = Math.max(0, Number(q.get("offset") ?? 0) || 0);
+ const whereSQL = where.length ? `WHERE ${where.join(" AND ")}` : "";
+
+ const db = env.OPENCOMPUTER_DB;
+ const total = await db.prepare(`SELECT COUNT(*) AS n FROM agent_feedback ${whereSQL}`).bind(...binds).first<{ n: number }>();
+ const rows = await db
+ .prepare(`SELECT * FROM agent_feedback ${whereSQL} ORDER BY created_at DESC, id DESC LIMIT ?${binds.length + 1} OFFSET ?${binds.length + 2}`)
+ .bind(...binds, limit, offset)
+ .all<FeedbackRow>();
+ return json({
+ data: rows.results.map(feedbackSummary),
+ meta: { limit, offset, count: rows.results.length, total: total?.n ?? 0 },
+ });
+}
+
+async function updateFeedback(req: Request, env: AgentFeedbackEnv, id: string): Promise<Response> {
+ const read = await readJSONBody(req);
+ if (read instanceof Response) return read;
+ const body = read.body;
+ if (!isObj(body)) return validationJSON([{ field: "", error: "invalid_type", message: "body must be a JSON object" }]);
+
+ const db = env.OPENCOMPUTER_DB;
+ const current = await db.prepare("SELECT id, status, agent_key FROM agent_feedback WHERE id = ?1").bind(id).first<{ id: string; status: FeedbackStatus; agent_key: string | null }>();
+ if (!current) return errorJSON("not_found", "feedback not found", 404);
+
+ const sets: string[] = [];
+ const binds: unknown[] = [];
+ const set = (col: string, value: unknown) => {
+ binds.push(value);
+ sets.push(`${col} = ?${binds.length}`);
+ };
+ const errors: FieldError[] = [];
+
+ if (body.status !== undefined) {
+ if (!oneOf(FEEDBACK_STATUSES, body.status)) errors.push({ field: "status", error: "invalid_enum", message: `status must be one of: ${FEEDBACK_STATUSES.join(", ")}` });
+ else set("status", body.status);
+ }
+ if (body.confirm !== undefined) {
+ if (typeof body.confirm !== "boolean") errors.push({ field: "confirm", error: "invalid_type", message: "confirm must be a boolean" });
+ else if (body.confirm) sets.push("observations = observations + 1");
+ }
+ if (body.duplicate_of !== undefined) {
+ if (body.duplicate_of === null) set("duplicate_of", null);
+ else if (typeof body.duplicate_of !== "string") errors.push({ field: "duplicate_of", error: "invalid_type", message: "duplicate_of must be a feedback ID" });
+ else if (body.duplicate_of === id) errors.push({ field: "duplicate_of", error: "invalid", message: "feedback cannot duplicate itself" });
+ else {
+ const target = await db.prepare("SELECT id FROM agent_feedback WHERE id = ?1").bind(body.duplicate_of).first<{ id: string }>();
+ if (!target) errors.push({ field: "duplicate_of", error: "not_found", message: "duplicate_of feedback not found" });
+ else set("duplicate_of", body.duplicate_of);
+ }
+ }
+ if (body.quality_score !== undefined) {
+ if (body.quality_score === null) set("quality_score", null);
+ else if (typeof body.quality_score !== "number" || body.quality_score < 0 || body.quality_score > 1) errors.push({ field: "quality_score", error: "out_of_range", message: "quality_score must be between 0 and 1" });
+ else set("quality_score", body.quality_score);
+ }
+ if (errors.length) return validationJSON(errors);
+ if (sets.length === 0) return validationJSON([{ field: "", error: "empty", message: "nothing to update" }]);
+
+ const ts = nowSec();
+ set("updated_at", ts);
+ binds.push(id);
+ const stmts = [db.prepare(`UPDATE agent_feedback SET ${sets.join(", ")} WHERE id = ?${binds.length}`).bind(...binds)];
+
+ // Reputation: count a report once when it first lands in a terminal bucket.
+ if (current.agent_key && typeof body.status === "string" && body.status !== current.status) {
+ const wasAccepted = current.status === "accepted" || current.status === "resolved";
+ const isAccepted = body.status === "accepted" || body.status === "resolved";
+ const wasDismissed = current.status === "dismissed" || current.status === "spam";
+ const isDismissed = body.status === "dismissed" || body.status === "spam";
+ if (isAccepted && !wasAccepted) stmts.push(db.prepare("UPDATE agent_feedback_agents SET accepted = accepted + 1 WHERE agent_key = ?1").bind(current.agent_key));
+ if (isDismissed && !wasDismissed) stmts.push(db.prepare("UPDATE agent_feedback_agents SET dismissed = dismissed + 1 WHERE agent_key = ?1").bind(current.agent_key));
+ }
+ await db.batch(stmts);
+ return json({ data: await loadFeedbackDetail(db, id) });
+}
+
+async function deleteFeedback(env: AgentFeedbackEnv, id: string): Promise<Response> {
+ const db = env.OPENCOMPUTER_DB;
+ const current = await db.prepare("SELECT id FROM agent_feedback WHERE id = ?1").bind(id).first<{ id: string }>();
+ if (!current) return errorJSON("not_found", "feedback not found", 404);
+ await db.batch([
+ db.prepare("DELETE FROM agent_feedback_evidence WHERE feedback_id = ?1").bind(id),
+ db.prepare("DELETE FROM agent_feedback WHERE id = ?1").bind(id),
+ ]);
+ return json({ success: true });
+}
+
+async function mergeFeedback(req: Request, env: AgentFeedbackEnv): Promise<Response> {
+ const read = await readJSONBody(req);
+ if (read instanceof Response) return read;
+ const body = read.body;
+ if (!isObj(body)) return validationJSON([{ field: "", error: "invalid_type", message: "body must be a JSON object" }]);
+ const target = body.target_id;
+ const sources = body.source_ids;
+ const errors: FieldError[] = [];
+ if (typeof target !== "string" || !target) errors.push({ field: "target_id", error: "required", message: "target_id is required" });
+ if (!Array.isArray(sources) || sources.length === 0 || !sources.every((s) => typeof s === "string")) {
+ errors.push({ field: "source_ids", error: "required", message: "source_ids must be a non-empty array of feedback IDs" });
+ }
+ if (errors.length) return validationJSON(errors);
+ const targetID = target as string;
+ const sourceIDs = (sources as string[]).filter((s) => s !== targetID);
+
+ const db = env.OPENCOMPUTER_DB;
+ const t = await db.prepare("SELECT id FROM agent_feedback WHERE id = ?1").bind(targetID).first<{ id: string }>();
+ if (!t) return errorJSON("not_found", "target feedback not found", 404);
+
+ const ts = nowSec();
+ const stmts: D1PreparedStatement[] = [];
+ for (const src of sourceIDs) {
+ const s = await db.prepare("SELECT observations FROM agent_feedback WHERE id = ?1").bind(src).first<{ observations: number }>();
+ if (!s) return errorJSON("not_found", `source feedback ${src} not found`, 404);
+ stmts.push(
+ db.prepare("UPDATE agent_feedback SET observations = observations + ?2, updated_at = ?3 WHERE id = ?1").bind(targetID, s.observations, ts),
+ db.prepare("UPDATE agent_feedback SET duplicate_of = ?2, status = 'resolved', updated_at = ?3 WHERE id = ?1").bind(src, targetID, ts),
+ db.prepare("UPDATE agent_feedback_evidence SET feedback_id = ?2 WHERE feedback_id = ?1").bind(src, targetID),
+ );
+ }
+ if (stmts.length) await db.batch(stmts);
+ return json({ data: await loadFeedbackDetail(db, targetID) });
+}
+
+async function createCategory(req: Request, env: AgentFeedbackEnv): Promise<Response> {
+ const read = await readJSONBody(req);
+ if (read instanceof Response) return read;
+ const body = read.body;
+ if (!isObj(body)) return validationJSON([{ field: "", error: "invalid_type", message: "body must be a JSON object" }]);
+ const name = body.name;
+ if (typeof name !== "string" || !/^[a-z][a-z0-9_]{1,63}$/.test(name)) {
+ return validationJSON([{ field: "name", error: "invalid", message: "name must be snake_case, 2-64 chars" }]);
+ }
+ if ((CATEGORIES as readonly string[]).includes(name)) return validationJSON([{ field: "name", error: "exists", message: "category already exists" }]);
+ const description = typeof body.description === "string" ? body.description.slice(0, 512) : null;
+ await env.OPENCOMPUTER_DB.prepare("INSERT OR IGNORE INTO agent_feedback_categories (name, description, created_at) VALUES (?1, ?2, ?3)")
+ .bind(name, description, nowSec())
+ .run();
+ return json({ data: name }, 201);
+}
+
+async function listAgents(env: AgentFeedbackEnv): Promise<Response> {
+ const rows = await env.OPENCOMPUTER_DB.prepare("SELECT * FROM agent_feedback_agents ORDER BY last_seen DESC LIMIT 200").all<{
+ agent_key: string;
+ agent_vendor: string;
+ agent_product: string;
+ submissions: number;
+ accepted: number;
+ dismissed: number;
+ first_seen: number;
+ last_seen: number;
+ }>();
+ return json({
+ data: rows.results.map((a) => ({
+ agent_key: a.agent_key,
+ agent_vendor: a.agent_vendor,
+ agent_product: a.agent_product,
+ submissions: a.submissions,
+ accepted: a.accepted,
+ dismissed: a.dismissed,
+ // Laplace-smoothed acceptance rate so a single accepted report isn't a 1.0.
+ reputation: (a.accepted + 1) / (a.accepted + a.dismissed + 2),
+ first_seen: iso(a.first_seen),
+ last_seen: iso(a.last_seen),
+ })),
+ });
+}
+
+// ── router ───────────────────────────────────────────────────────────────
+
+export function isAgentFeedbackPath(path: string): boolean {
+ return path === AGENT_FEEDBACK_DISCOVERY_PATH || path.startsWith(AGENT_FEEDBACK_ROUTE_PREFIX);
+}
+
+export async function handleAgentFeedback(req: Request, env: AgentFeedbackEnv, path: string): Promise<Response> {
+ const method = req.method.toUpperCase();
+
+ if (path === AGENT_FEEDBACK_DISCOVERY_PATH) {
+ if (method !== "GET") return errorJSON("method_not_allowed", "GET only", 405);
+ return json(discoveryDocument());
+ }
+ if (path === "/api/v1/policy") {
+ if (method !== "GET") return errorJSON("method_not_allowed", "GET only", 405);
+ return json(policyDocument());
+ }
+ if (path === "/api/v1/categories") {
+ if (method === "GET") return listCategories(env);
+ if (method === "POST") return triageAuthorized(req, env) ? createCategory(req, env) : errorJSON("unauthorized", "triage token required", 401);
+ return errorJSON("method_not_allowed", "GET or POST", 405);
+ }
+ if (path === "/api/v1/observations") {
+ if (method !== "POST") return errorJSON("method_not_allowed", "POST only", 405);
+ return submitObservation(req, env, path);
+ }
+ if (path === "/api/v1/feedback") {
+ if (method === "POST") return submitFeedback(req, env, path);
+ if (method === "GET") return triageAuthorized(req, env) ? listFeedback(req, env) : errorJSON("unauthorized", "triage token required", 401);
+ return errorJSON("method_not_allowed", "GET or POST", 405);
+ }
+ if (path === "/api/v1/feedback/merge") {
+ if (method !== "POST") return errorJSON("method_not_allowed", "POST only", 405);
+ return triageAuthorized(req, env) ? mergeFeedback(req, env) : errorJSON("unauthorized", "triage token required", 401);
+ }
+ if (path === "/api/v1/agents") {
+ if (method !== "GET") return errorJSON("method_not_allowed", "GET only", 405);
+ return triageAuthorized(req, env) ? listAgents(env) : errorJSON("unauthorized", "triage token required", 401);
+ }
+
+ let m = path.match(/^\/api\/v1\/receipts\/([A-Za-z0-9_-]+)$/);
+ if (m) {
+ if (method !== "GET") return errorJSON("method_not_allowed", "GET only", 405);
+ return getReceipt(env, m[1]);
+ }
+ m = path.match(/^\/api\/v1\/feedback\/([A-Za-z0-9_-]+)\/attachments$/);
+ if (m) {
+ if (method !== "POST") return errorJSON("method_not_allowed", "POST only", 405);
+ return attachEvidence(req, env, path, m[1]);
+ }
+ m = path.match(/^\/api\/v1\/feedback\/([A-Za-z0-9_-]+)$/);
+ if (m) {
+ if (method === "GET") {
+ const detail = await loadFeedbackDetail(env.OPENCOMPUTER_DB, m[1]);
+ return detail ? json({ data: detail }) : errorJSON("not_found", "feedback not found", 404);
+ }
+ if (!triageAuthorized(req, env)) return errorJSON("unauthorized", "triage token required", 401);
+ if (method === "PATCH") return updateFeedback(req, env, m[1]);
+ if (method === "DELETE") return deleteFeedback(env, m[1]);
+ return errorJSON("method_not_allowed", "GET, PATCH or DELETE", 405);
+ }
+
+ return errorJSON("not_found", "no such route", 404);
+}
+
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 1ae70f0e..b79e36f7 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -56,6 +56,7 @@ import {
type OrgPolicy,
} from "./create_context_cache";
import { handleDashboard, type DashboardEnv } from "./dashboard";
+import { handleAgentFeedback, isAgentFeedbackPath, type AgentFeedbackEnv } from "./agent_feedback";
import {
AGENT_SECURITY_NOTIFICATION_PATH,
receiveAgentSecurityNotification,
@@ -92,7 +93,7 @@ import {
proxyManagedAgents,
} from "./managed_agents";
-export interface Env extends DashboardEnv {
+export interface Env extends DashboardEnv, AgentFeedbackEnv {
CF_ADMIN_SECRET: string;
STRIPE_WEBHOOK_SECRET: string;
EVENT_SECRET: string;
@@ -5022,6 +5023,12 @@ export default {
return json({ ok: true, env: env.WORKER_ENV });
}
+ // feedback.now protocol (agent_feedback.ts). Must precede both the generic
+ // /api/* API-key gate (agents submit anonymously) and the SPA asset
+ // fallthrough (which would otherwise answer /.well-known/* with index.html).
+ if (isAgentFeedbackPath(path)) {
+ return handleAgentFeedback(req, env, path);
+ }
// VM-DO host dial: the QEMU worker host opens a persistent WebSocket to the
diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.toml
index 9404a2ff..230528bf 100644
--- a/cloudflare-workers/api-edge/wrangler.prod.toml
+++ b/cloudflare-workers/api-edge/wrangler.prod.toml
@@ -134,6 +134,9 @@ deleted_classes = ["VmSession"]
# browser-session proxy requests
# OC_MANAGED_AGENTS_SECRET — dedicated HS256 secret shared only with the
# managed-agents backend
+# AGENT_FEEDBACK_TRIAGE_TOKEN — bearer token for the feedback.now triage
+# routes (src/agent_feedback.ts); submission works
+# without it
# Optional vars: OPENROUTER_BASE_URL (default https://openrouter.ai/api/v1),
# OPENROUTER_MARKUP_BPS (env-default markup; per-org orgs.model_markup_bps wins).
diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.toml
index 3732f669..d0850541 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -150,6 +150,9 @@ deleted_classes = ["VmSession"]
# exposure alerts from sessions-api.
# OC_MANAGED_AGENTS_SECRET — dedicated HS256 secret shared only with the
# managed-agents backend.
+# AGENT_FEEDBACK_TRIAGE_TOKEN — bearer token for the feedback.now triage
+# routes (src/agent_feedback.ts). Triage is disabled
+# while unset; agent submission still works.
# The VM-DO exec data plane (VM_SESSIONS DO) needs NO dedicated secret: the worker
# host authenticates its /internal/vms/:id/connect dial with a per-sandbox HMAC
# over the already-shared SESSION_JWT_SECRET (minted by the CP, re-derived here).
diff --git a/cmd/oc/internal/commands/feedback.go b/cmd/oc/internal/commands/feedback.go
new file mode 100644
index 00000000..e8834eac
--- /dev/null
+++ b/cmd/oc/internal/commands/feedback.go
@@ -0,0 +1,562 @@
+package commands
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/x509"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "encoding/pem"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/config"
+ "github.com/spf13/cobra"
+)
+
+// feedback.now emitter (https://feedback.now). Any host that publishes
+// /.well-known/agent-feedback.json is a valid target; OpenComputer's own API
+// host is the default. Submission is anonymous unless --signing-key is given.
+// These commands never touch the OpenComputer API key — the protocol is
+// deliberately unauthenticated so third-party agents can report friction.
+
+const (
+ feedbackDiscoveryPath = "/.well-known/agent-feedback.json"
+ feedbackTimeout = 15 * time.Second
+ feedbackEnvTarget = "OC_FEEDBACK_TARGET"
+ feedbackEnvSigningKey = "OC_FEEDBACK_SIGNING_KEY"
+)
+
+var feedbackCmd = &cobra.Command{
+ Use: "feedback",
+ Short: "Report bugs and friction to a feedback.now-compatible API (OpenComputer by default)",
+ Long: "Emit structured feedback using the feedback.now protocol.\n\n" +
+ "Agents (or humans) hit a bug, docs mismatch, or friction in an API/CLI/SDK\n" +
+ "and file it here without an account. The target host is discovered from\n" +
+ "/.well-known/agent-feedback.json, so this works against any feedback.now\n" +
+ "receiver, not just OpenComputer. Every submission returns a receipt ID you\n" +
+ "can poll with `oc feedback receipt`.\n\n" +
+ "Target selection: --target, else $" + feedbackEnvTarget + ", else the configured\n" +
+ "OpenComputer API URL. Optional Ed25519 signing: --signing-key or\n" +
+ "$" + feedbackEnvSigningKey + " (PEM file from `oc feedback keygen`).",
+ Annotations: map[string]string{offlineCommandAnnotation: "true"},
+}
+
+var feedbackPolicyCmd = &cobra.Command{
+ Use: "policy",
+ Short: "Show the target's feedback.now discovery document and policy",
+ Args: cobra.NoArgs,
+ Annotations: map[string]string{offlineCommandAnnotation: "true"},
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ fc, err := newFeedbackClient(cmd)
+ if err != nil {
+ return err
+ }
+ disc, err := fc.discover(cmd.Context())
+ if err != nil {
+ return err
+ }
+ policyURL := fc.resolve(disc.PolicyURL, "/api/v1/policy")
+ var policy map[string]any
+ if err := fc.getJSON(cmd.Context(), policyURL, &policy); err != nil {
+ return err
+ }
+ out := map[string]any{"target": fc.base.String(), "discovery": disc.raw, "policy": policy}
+ if jsonOutput {
+ return printer.PrintJSON(out)
+ }
+ fmt.Printf("Target: %s\n", fc.base)
+ fmt.Printf("Name: %s\n", disc.Name)
+ fmt.Printf("Policy: %s\n", policyURL)
+ fmt.Printf("Categories: %s\n", strings.Join(stringList(policy["categories"]), ", "))
+ fmt.Printf("Severities: %s\n", strings.Join(stringList(policy["severity_levels"]), ", "))
+ fmt.Printf("Evidence: %s\n", strings.Join(stringList(policy["evidence_types"]), ", "))
+ if auth, ok := disc.raw["auth"].(map[string]any); ok {
+ fmt.Printf("Signing: %v (optional)\n", auth["type"])
+ }
+ return nil
+ },
+}
+
+var feedbackSubmitCmd = &cobra.Command{
+ Use: "submit",
+ Short: "Submit a structured feedback report (bug, docs mismatch, friction, feature gap)",
+ Example: " oc feedback submit --surface 'POST /api/sandboxes' --category bug --severity high \\\n" +
+ " --title 'create returns 500 when template is missing' \\\n" +
+ " --summary 'Expected a 404 with a clear error' \\\n" +
+ " --evidence http_summary='{\"status\":500}' --evidence [email protected]\n" +
+ " oc feedback submit --target https://api.example.com --surface 'GET /v1/items' \\\n" +
+ " --category docs_mismatch --severity low --title 'docs say limit max is 500, API caps at 100'",
+ Args: cobra.NoArgs,
+ Annotations: map[string]string{offlineCommandAnnotation: "true"},
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ fc, err := newFeedbackClient(cmd)
+ if err != nil {
+ return err
+ }
+ f := cmd.Flags()
+ title, _ := f.GetString("title")
+ surface, _ := f.GetString("surface")
+ category, _ := f.GetString("category")
+ severity, _ := f.GetString("severity")
+ if title == "" || surface == "" || category == "" || severity == "" {
+ return fmt.Errorf("--title, --surface, --category and --severity are required")
+ }
+ summary, _ := f.GetString("summary")
+ hypothesis, _ := f.GetString("hypothesis")
+ repro, _ := f.GetString("reproducibility")
+ confidence, _ := f.GetFloat64("confidence")
+ kind, _ := f.GetString("kind")
+ product, _ := f.GetString("product")
+ evidenceFlags, _ := f.GetStringArray("evidence")
+ evidence, err := parseEvidenceFlags(evidenceFlags)
+ if err != nil {
+ return err
+ }
+
+ signal := map[string]any{"category": category, "severity": severity, "confidence": confidence}
+ if repro != "" {
+ signal["reproducibility"] = repro
+ }
+ subject := map[string]any{"surface": surface, "domain": fc.domain(cmd)}
+ if kind != "" {
+ subject["kind"] = kind
+ }
+ if product != "" {
+ subject["product"] = product
+ }
+ content := map[string]any{"title": title}
+ if summary != "" {
+ content["summary"] = summary
+ }
+ if hypothesis != "" {
+ content["hypothesis"] = hypothesis
+ }
+ body := map[string]any{
+ "reporter": fc.reporter(cmd),
+ "subject": subject,
+ "signal": signal,
+ "content": content,
+ }
+ if len(evidence) > 0 {
+ body["evidence"] = evidence
+ }
+
+ disc, err := fc.discover(cmd.Context())
+ if err != nil {
+ return err
+ }
+ endpoint := fc.resolve(disc.endpoint("feedback", "submit"), "/api/v1/feedback")
+ var resp map[string]any
+ if err := fc.postJSON(cmd.Context(), endpoint, body, &resp); err != nil {
+ return err
+ }
+ return fc.printReceipt(resp)
+ },
+}
+
+var feedbackObserveCmd = &cobra.Command{
+ Use: "observe",
+ Short: "Submit a lightweight observation (no title/evidence required)",
+ Example: " oc feedback observe --surface 'oc sandbox create' --category friction \\\n" +
+ " --summary '--template flag name differs from docs'",
+ Args: cobra.NoArgs,
+ Annotations: map[string]string{offlineCommandAnnotation: "true"},
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ fc, err := newFeedbackClient(cmd)
+ if err != nil {
+ return err
+ }
+ f := cmd.Flags()
+ surface, _ := f.GetString("surface")
+ if surface == "" {
+ return fmt.Errorf("--surface is required")
+ }
+ rep := fc.reporter(cmd)
+ body := map[string]any{
+ "surface": surface,
+ "domain": fc.domain(cmd),
+ "agent_vendor": rep["agent_vendor"],
+ "agent_product": rep["agent_product"],
+ }
+ if v := rep["agent_version"]; v != "" {
+ body["agent_version"] = v
+ }
+ for _, k := range []string{"category", "severity", "summary", "kind"} {
+ if v, _ := f.GetString(k); v != "" {
+ body[k] = v
+ }
+ }
+ if f.Changed("confidence") {
+ body["confidence"], _ = f.GetFloat64("confidence")
+ }
+
+ disc, err := fc.discover(cmd.Context())
+ if err != nil {
+ return err
+ }
+ endpoint := fc.resolve(disc.endpoint("observations", "submit"), "/api/v1/observations")
+ var resp map[string]any
+ if err := fc.postJSON(cmd.Context(), endpoint, body, &resp); err != nil {
+ return err
+ }
+ return fc.printReceipt(resp)
+ },
+}
+
+var feedbackReceiptCmd = &cobra.Command{
+ Use: "receipt <receipt-id>",
+ Short: "Poll a receipt to see whether the report was accepted, folded as a duplicate, or triaged",
+ Args: cobra.ExactArgs(1),
+ Annotations: map[string]string{offlineCommandAnnotation: "true"},
+ RunE: func(cmd *cobra.Command, args []string) error {
+ fc, err := newFeedbackClient(cmd)
+ if err != nil {
+ return err
+ }
+ disc, err := fc.discover(cmd.Context())
+ if err != nil {
+ return err
+ }
+ tmpl := disc.endpoint("receipts", "get")
+ if tmpl == "" {
+ tmpl = "/api/v1/receipts/{id}"
+ }
+ u := fc.resolve(strings.Replace(tmpl, "{id}", url.PathEscape(args[0]), 1), "/api/v1/receipts/"+url.PathEscape(args[0]))
+ var resp struct {
+ Data map[string]any `json:"data"`
+ }
+ if err := fc.getJSON(cmd.Context(), u, &resp); err != nil {
+ return err
+ }
+ if jsonOutput {
+ return printer.PrintJSON(resp.Data)
+ }
+ rows := [][]string{}
+ for _, k := range []string{"id", "status", "feedback_id", "observation_id", "feedback_status", "duplicate_of", "quality_score", "created_at", "updated_at"} {
+ if v, ok := resp.Data[k]; ok && v != nil {
+ rows = append(rows, []string{k, fmt.Sprint(v)})
+ }
+ }
+ printer.Table([]string{"FIELD", "VALUE"}, rows)
+ return nil
+ },
+}
+
+var feedbackKeygenCmd = &cobra.Command{
+ Use: "keygen",
+ Short: "Generate an Ed25519 signing key for agent identity (optional)",
+ Long: "Writes a PKCS#8 PEM private key. Pass it via --signing-key or $" + feedbackEnvSigningKey +
+ " so receivers can build a reputation for this agent across submissions.",
+ Args: cobra.NoArgs,
+ Annotations: map[string]string{offlineCommandAnnotation: "true"},
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ out, _ := cmd.Flags().GetString("out")
+ if out == "" {
+ return fmt.Errorf("--out is required")
+ }
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ return err
+ }
+ der, err := x509.MarshalPKCS8PrivateKey(priv)
+ if err != nil {
+ return err
+ }
+ if err := os.WriteFile(out, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), 0o600); err != nil {
+ return err
+ }
+ spki, err := x509.MarshalPKIXPublicKey(pub)
+ if err != nil {
+ return err
+ }
+ res := map[string]any{"path": out, "public_key": base64.StdEncoding.EncodeToString(spki)}
+ if jsonOutput {
+ return printer.PrintJSON(res)
+ }
+ fmt.Printf("Wrote %s\nPublic key (X-Agent-Key): %s\n", out, res["public_key"])
+ return nil
+ },
+}
+
+func init() {
+ pf := feedbackCmd.PersistentFlags()
+ pf.String("target", "", "Base URL of a feedback.now receiver (default: $"+feedbackEnvTarget+" or the OpenComputer API URL)")
+ pf.String("signing-key", "", "PEM Ed25519 private key to sign requests (default: $"+feedbackEnvSigningKey+")")
+ pf.String("agent-vendor", "opencomputer", "reporter.agent_vendor")
+ pf.String("agent-product", "oc-cli", "reporter.agent_product")
+ pf.String("agent-version", "", "reporter.agent_version (default: oc version)")
+ pf.String("domain", "", "subject.domain (default: target host)")
+
+ for _, c := range []*cobra.Command{feedbackSubmitCmd, feedbackObserveCmd} {
+ c.Flags().String("surface", "", "What was being used, e.g. 'POST /api/sandboxes' or 'oc sandbox create'")
+ c.Flags().String("category", "", "bug | docs_mismatch | friction | feature_gap | quality_degradation | other")
+ c.Flags().String("severity", "", "critical | high | medium | low")
+ c.Flags().Float64("confidence", 0.7, "0..1 confidence that this is a real issue")
+ c.Flags().String("summary", "", "What happened vs. what was expected")
+ c.Flags().String("kind", "", "api_endpoint | docs_page | cli_command | sdk_method | other")
+ }
+ feedbackSubmitCmd.Flags().String("title", "", "Short title (required)")
+ feedbackSubmitCmd.Flags().String("hypothesis", "", "Suspected root cause")
+ feedbackSubmitCmd.Flags().String("reproducibility", "", "always | sometimes | intermittent | once")
+ feedbackSubmitCmd.Flags().String("product", "", "subject.product, e.g. 'typescript-sdk'")
+ feedbackSubmitCmd.Flags().StringArray("evidence", nil, "type=content or type=@file (repeatable; types: http_summary, stderr_excerpt, repro_steps, log_excerpt, other)")
+
+ feedbackKeygenCmd.Flags().String("out", "", "Where to write the PEM private key")
+
+ feedbackCmd.AddCommand(feedbackPolicyCmd, feedbackSubmitCmd, feedbackObserveCmd, feedbackReceiptCmd, feedbackKeygenCmd)
+}
+
+// ── client ────────────────────────────────────────────────────────────────
+
+type feedbackClient struct {
+ base *url.URL
+ http *http.Client
+ key ed25519.PrivateKey // nil → anonymous
+}
+
+type feedbackDiscovery struct {
+ Name string
+ PolicyURL string
+ raw map[string]any
+}
+
+// endpoint returns endpoints.<group>.<op>.url from the discovery document, or "".
+func (d *feedbackDiscovery) endpoint(group, op string) string {
+ eps, _ := d.raw["endpoints"].(map[string]any)
+ g, _ := eps[group].(map[string]any)
+ o, _ := g[op].(map[string]any)
+ u, _ := o["url"].(string)
+ return u
+}
+
+func newFeedbackClient(cmd *cobra.Command) (*feedbackClient, error) {
+ target, _ := cmd.Flags().GetString("target")
+ if target == "" {
+ target = os.Getenv(feedbackEnvTarget)
+ }
+ if target == "" {
+ target = config.Load(cmd).APIURL
+ }
+ if !strings.Contains(target, "://") {
+ target = "https://" + target
+ }
+ base, err := url.Parse(target)
+ if err != nil || base.Host == "" {
+ return nil, fmt.Errorf("invalid feedback target %q", target)
+ }
+ base.Path, base.RawQuery, base.Fragment = "", "", ""
+
+ fc := &feedbackClient{base: base, http: &http.Client{Timeout: feedbackTimeout}}
+ keyPath, _ := cmd.Flags().GetString("signing-key")
+ if keyPath == "" {
+ keyPath = os.Getenv(feedbackEnvSigningKey)
+ }
+ if keyPath != "" {
+ fc.key, err = loadEd25519Key(keyPath)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return fc, nil
+}
+
+func loadEd25519Key(path string) (ed25519.PrivateKey, error) {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return nil, fmt.Errorf("read signing key: %w", err)
+ }
+ block, _ := pem.Decode(raw)
+ if block == nil {
+ return nil, fmt.Errorf("signing key %s: not PEM", path)
+ }
+ k, err := x509.ParsePKCS8PrivateKey(block.Bytes)
+ if err != nil {
+ return nil, fmt.Errorf("signing key %s: %w", path, err)
+ }
+ priv, ok := k.(ed25519.PrivateKey)
+ if !ok {
+ return nil, fmt.Errorf("signing key %s: not an Ed25519 key", path)
+ }
+ return priv, nil
+}
+
+func (fc *feedbackClient) resolve(u, fallback string) string {
+ if u == "" {
+ u = fallback
+ }
+ ref, err := url.Parse(u)
+ if err != nil {
+ return fc.base.String() + fallback
+ }
+ return fc.base.ResolveReference(ref).String()
+}
+
+func (fc *feedbackClient) domain(cmd *cobra.Command) string {
+ if d, _ := cmd.Flags().GetString("domain"); d != "" {
+ return d
+ }
+ return fc.base.Hostname()
+}
+
+func (fc *feedbackClient) reporter(cmd *cobra.Command) map[string]string {
+ vendor, _ := cmd.Flags().GetString("agent-vendor")
+ product, _ := cmd.Flags().GetString("agent-product")
+ version, _ := cmd.Flags().GetString("agent-version")
+ if version == "" {
+ version = Version
+ }
+ return map[string]string{"agent_vendor": vendor, "agent_product": product, "agent_version": version}
+}
+
+func (fc *feedbackClient) discover(ctx context.Context) (*feedbackDiscovery, error) {
+ var raw map[string]any
+ if err := fc.getJSON(ctx, fc.base.String()+feedbackDiscoveryPath, &raw); err != nil {
+ return nil, fmt.Errorf("%s does not advertise feedback.now (%s): %w", fc.base.Host, feedbackDiscoveryPath, err)
+ }
+ d := &feedbackDiscovery{raw: raw}
+ d.Name, _ = raw["name"].(string)
+ d.PolicyURL, _ = raw["policy_url"].(string)
+ return d, nil
+}
+
+func (fc *feedbackClient) getJSON(ctx context.Context, u string, out any) error {
+ return fc.do(ctx, http.MethodGet, u, nil, out)
+}
+
+func (fc *feedbackClient) postJSON(ctx context.Context, u string, body any, out any) error {
+ b, err := json.Marshal(body)
+ if err != nil {
+ return err
+ }
+ return fc.do(ctx, http.MethodPost, u, b, out)
+}
+
+// feedbackErrorMessage flattens the receiver's error envelope, including
+// feedback.now's per-field validation errors, into one line.
+func feedbackErrorMessage(status int, data []byte) string {
+ var body map[string]any
+ _ = json.Unmarshal(data, &body)
+ msg, _ := body["error"].(string)
+ if msg == "" {
+ msg = http.StatusText(status)
+ }
+ if errs, ok := body["errors"].([]any); ok && len(errs) > 0 {
+ parts := make([]string, 0, len(errs))
+ for _, fe := range errs {
+ m, _ := fe.(map[string]any)
+ parts = append(parts, fmt.Sprintf("%v: %v", m["field"], m["message"]))
+ }
+ msg += " (" + strings.Join(parts, "; ") + ")"
+ }
+ return msg
+}
+
+func (fc *feedbackClient) do(ctx context.Context, method, u string, body []byte, out any) error {
+ req, err := http.NewRequestWithContext(ctx, method, u, bytes.NewReader(body))
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("User-Agent", "oc-cli/"+Version)
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ if fc.key != nil {
+ fc.sign(req, body)
+ }
+ resp, err := fc.http.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
+ if err != nil {
+ return err
+ }
+ if resp.StatusCode >= 400 {
+ return &client.APIError{StatusCode: resp.StatusCode, Message: feedbackErrorMessage(resp.StatusCode, data)}
+ }
+ if out == nil {
+ return nil
+ }
+ if err := json.Unmarshal(data, out); err != nil {
+ return fmt.Errorf("decode response from %s: %w", u, err)
+ }
+ return nil
+}
+
+// sign adds the feedback.now Ed25519 headers. Payload per spec:
+// timestamp\nMETHOD\npath\nsha256hex(body).
+func (fc *feedbackClient) sign(req *http.Request, body []byte) {
+ ts := time.Now().UTC().Format(time.RFC3339)
+ sum := sha256.Sum256(body)
+ payload := strings.Join([]string{ts, req.Method, req.URL.Path, hex.EncodeToString(sum[:])}, "\n")
+ sig := ed25519.Sign(fc.key, []byte(payload))
+ spki, err := x509.MarshalPKIXPublicKey(fc.key.Public())
+ if err != nil {
+ return
+ }
+ req.Header.Set("X-Agent-Key", base64.StdEncoding.EncodeToString(spki))
+ req.Header.Set("X-Agent-Signature", base64.StdEncoding.EncodeToString(sig))
+ req.Header.Set("X-Agent-Timestamp", ts)
+}
+
+func (fc *feedbackClient) printReceipt(resp map[string]any) error {
+ receipt, _ := resp["receipt"].(map[string]any)
+ if jsonOutput {
+ return printer.PrintJSON(resp)
+ }
+ status, _ := receipt["status"].(string)
+ fmt.Printf("Receipt: %v\nStatus: %s\n", receipt["id"], status)
+ if v, ok := receipt["feedback_id"]; ok && v != nil {
+ fmt.Printf("Feedback: %v\n", v)
+ }
+ if v, ok := receipt["observation_id"]; ok && v != nil {
+ fmt.Printf("Observation: %v\n", v)
+ }
+ if v, ok := receipt["duplicate_of"]; ok && v != nil {
+ fmt.Printf("Folded into existing report %v\n", v)
+ }
+ fmt.Printf("Poll with: oc feedback receipt %v --target %s\n", receipt["id"], fc.base)
+ return nil
+}
+
+// parseEvidenceFlags turns type=content / type=@file into evidence objects.
+func parseEvidenceFlags(flags []string) ([]map[string]any, error) {
+ out := make([]map[string]any, 0, len(flags))
+ for _, f := range flags {
+ typ, val, ok := strings.Cut(f, "=")
+ if !ok || typ == "" {
+ return nil, fmt.Errorf("--evidence %q: expected type=content or type=@file", f)
+ }
+ if strings.HasPrefix(val, "@") {
+ b, err := os.ReadFile(val[1:])
+ if err != nil {
+ return nil, fmt.Errorf("--evidence %s: %w", typ, err)
+ }
+ val = string(b)
+ }
+ out = append(out, map[string]any{"type": typ, "content": val})
+ }
+ return out, nil
+}
+
+func stringList(v any) []string {
+ arr, _ := v.([]any)
+ out := make([]string, 0, len(arr))
+ for _, x := range arr {
+ out = append(out, fmt.Sprint(x))
+ }
+ return out
+}
diff --git a/cmd/oc/internal/commands/feedback_test.go b/cmd/oc/internal/commands/feedback_test.go
new file mode 100644
index 00000000..372dc6ee
--- /dev/null
+++ b/cmd/oc/internal/commands/feedback_test.go
@@ -0,0 +1,242 @@
+package commands
+
+import (
+ "crypto/ed25519"
+ "crypto/sha256"
+ "crypto/x509"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/output"
+ "github.com/spf13/cobra"
+ "github.com/spf13/pflag"
+)
+
+// stub feedback.now receiver: serves discovery pointing at itself and records
+// the last submission body + headers.
+type feedbackStub struct {
+ srv *httptest.Server
+ lastPath string
+ lastBody map[string]any
+ lastHdr http.Header
+}
+
+func newFeedbackStub(t *testing.T) *feedbackStub {
+ t.Helper()
+ s := &feedbackStub{}
+ mux := http.NewServeMux()
+ mux.HandleFunc("/.well-known/agent-feedback.json", func(w http.ResponseWriter, _ *http.Request) {
+ // Relative + absolute URLs mixed on purpose: the emitter must resolve both.
+ json.NewEncoder(w).Encode(map[string]any{
+ "schema_version": "1.1",
+ "name": "Stub",
+ "policy_url": "/api/v1/policy",
+ "endpoints": map[string]any{
+ "feedback": map[string]any{"submit": map[string]any{"method": "POST", "url": "/custom/feedback"}},
+ "observations": map[string]any{"submit": map[string]any{"method": "POST", "url": s.srv.URL + "/custom/obs"}},
+ "receipts": map[string]any{"get": map[string]any{"method": "GET", "url": "/custom/receipts/{id}"}},
+ },
+ })
+ })
+ mux.HandleFunc("/api/v1/policy", func(w http.ResponseWriter, _ *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{"categories": []string{"bug"}, "severity_levels": []string{"low"}, "evidence_types": []string{"other"}})
+ })
+ record := func(w http.ResponseWriter, r *http.Request) {
+ s.lastPath = r.URL.Path
+ s.lastHdr = r.Header.Clone()
+ raw, _ := io.ReadAll(r.Body)
+ s.lastBody = nil
+ _ = json.Unmarshal(raw, &s.lastBody)
+ if sig := r.Header.Get("X-Agent-Signature"); sig != "" {
+ if !verifySig(r, raw) {
+ w.WriteHeader(401)
+ return
+ }
+ }
+ if r.URL.Path == "/custom/feedback" {
+ if _, ok := s.lastBody["content"].(map[string]any)["title"]; !ok {
+ w.WriteHeader(400)
+ json.NewEncoder(w).Encode(map[string]any{"error": "validation_failed", "errors": []map[string]any{{"field": "content.title", "error": "required", "message": "title is required"}}})
+ return
+ }
+ }
+ w.WriteHeader(201)
+ json.NewEncoder(w).Encode(map[string]any{"receipt": map[string]any{"id": "rcpt_1", "status": "accepted", "feedback_id": "fb_1"}})
+ }
+ mux.HandleFunc("/custom/feedback", record)
+ mux.HandleFunc("/custom/obs", record)
+ mux.HandleFunc("/custom/receipts/", func(w http.ResponseWriter, r *http.Request) {
+ s.lastPath = r.URL.Path
+ json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"id": strings.TrimPrefix(r.URL.Path, "/custom/receipts/"), "status": "duplicate", "duplicate_of": "fb_0"}})
+ })
+ s.srv = httptest.NewServer(mux)
+ t.Cleanup(s.srv.Close)
+ return s
+}
+
+func verifySig(r *http.Request, body []byte) bool {
+ spki, err := base64.StdEncoding.DecodeString(r.Header.Get("X-Agent-Key"))
+ if err != nil {
+ return false
+ }
+ pubAny, err := x509.ParsePKIXPublicKey(spki)
+ if err != nil {
+ return false
+ }
+ pub, ok := pubAny.(ed25519.PublicKey)
+ if !ok {
+ return false
+ }
+ sig, err := base64.StdEncoding.DecodeString(r.Header.Get("X-Agent-Signature"))
+ if err != nil {
+ return false
+ }
+ sum := sha256.Sum256(body)
+ payload := strings.Join([]string{r.Header.Get("X-Agent-Timestamp"), r.Method, r.URL.Path, hex.EncodeToString(sum[:])}, "\n")
+ return ed25519.Verify(pub, []byte(payload), sig)
+}
+
+func runFeedback(t *testing.T, args ...string) (string, error) {
+ t.Helper()
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("OPENCOMPUTER_API_KEY", "")
+ t.Setenv("OC_NO_UPDATE_CHECK", "1")
+ r, w, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ oldStdout := os.Stdout
+ os.Stdout = w
+ printer = output.New(false)
+ printer.W = w
+ rootCmd.SetArgs(append([]string{"feedback"}, args...))
+ runErr := rootCmd.Execute()
+ os.Stdout = oldStdout
+ w.Close()
+ out, _ := io.ReadAll(r)
+ // cobra keeps parsed flag values across Execute calls in one process;
+ // restore defaults so tests don't leak --target/--title into each other.
+ for _, c := range append([]*cobra.Command{feedbackCmd}, feedbackCmd.Commands()...) {
+ for _, fs := range []*pflag.FlagSet{c.PersistentFlags(), c.Flags()} {
+ fs.VisitAll(func(f *pflag.Flag) {
+ if f.Changed && f.Value.Type() != "stringArray" {
+ _ = f.Value.Set(f.DefValue)
+ f.Changed = false
+ }
+ })
+ }
+ }
+ return string(out), runErr
+}
+
+func TestFeedbackSubmitDiscoversEndpointAndSendsSpecShape(t *testing.T) {
+ stub := newFeedbackStub(t)
+ out, err := runFeedback(t, "submit", "--target", stub.srv.URL,
+ "--surface", "POST /api/sandboxes", "--category", "bug", "--severity", "high",
+ "--title", "boom", "--summary", "expected 404", "--reproducibility", "always",
+ "--evidence", "http_summary={\"status\":500}")
+ if err != nil {
+ t.Fatalf("submit: %v", err)
+ }
+ if stub.lastPath != "/custom/feedback" {
+ t.Fatalf("did not follow discovery url, got %s", stub.lastPath)
+ }
+ if stub.lastHdr.Get("X-Agent-Signature") != "" {
+ t.Fatal("unsigned submission should carry no signature")
+ }
+ rep := stub.lastBody["reporter"].(map[string]any)
+ if rep["agent_vendor"] != "opencomputer" || rep["agent_product"] != "oc-cli" {
+ t.Fatalf("reporter = %v", rep)
+ }
+ subj := stub.lastBody["subject"].(map[string]any)
+ if subj["surface"] != "POST /api/sandboxes" || subj["domain"] != "127.0.0.1" {
+ t.Fatalf("subject = %v", subj)
+ }
+ sig := stub.lastBody["signal"].(map[string]any)
+ if sig["category"] != "bug" || sig["severity"] != "high" || sig["reproducibility"] != "always" || sig["confidence"] != 0.7 {
+ t.Fatalf("signal = %v", sig)
+ }
+ ev := stub.lastBody["evidence"].([]any)
+ if len(ev) != 1 || ev[0].(map[string]any)["type"] != "http_summary" {
+ t.Fatalf("evidence = %v", ev)
+ }
+ if !strings.Contains(out, "Receipt: rcpt_1") || !strings.Contains(out, "Feedback: fb_1") {
+ t.Fatalf("output = %q", out)
+ }
+}
+
+func TestFeedbackSubmitSignsWithEd25519(t *testing.T) {
+ stub := newFeedbackStub(t)
+ keyPath := filepath.Join(t.TempDir(), "agent.pem")
+ if _, err := runFeedback(t, "keygen", "--out", keyPath); err != nil {
+ t.Fatalf("keygen: %v", err)
+ }
+ if _, err := runFeedback(t, "submit", "--target", stub.srv.URL, "--signing-key", keyPath,
+ "--surface", "s", "--category", "bug", "--severity", "low", "--title", "t"); err != nil {
+ t.Fatalf("signed submit rejected by stub verifier: %v", err)
+ }
+ if stub.lastHdr.Get("X-Agent-Key") == "" || stub.lastHdr.Get("X-Agent-Timestamp") == "" {
+ t.Fatal("missing signing headers")
+ }
+}
+
+func TestFeedbackObserveUsesAbsoluteDiscoveryURL(t *testing.T) {
+ stub := newFeedbackStub(t)
+ if _, err := runFeedback(t, "observe", "--target", stub.srv.URL, "--surface", "oc sandbox create", "--category", "friction", "--domain", "example.test"); err != nil {
+ t.Fatalf("observe: %v", err)
+ }
+ if stub.lastPath != "/custom/obs" {
+ t.Fatalf("path = %s", stub.lastPath)
+ }
+ if stub.lastBody["domain"] != "example.test" || stub.lastBody["agent_product"] != "oc-cli" || stub.lastBody["category"] != "friction" {
+ t.Fatalf("body = %v", stub.lastBody)
+ }
+ if _, has := stub.lastBody["confidence"]; has {
+ t.Fatal("confidence should be omitted when not passed")
+ }
+}
+
+func TestFeedbackReceiptAndValidationErrors(t *testing.T) {
+ stub := newFeedbackStub(t)
+ out, err := runFeedback(t, "receipt", "rcpt_9", "--target", stub.srv.URL)
+ if err != nil {
+ t.Fatalf("receipt: %v", err)
+ }
+ if stub.lastPath != "/custom/receipts/rcpt_9" || !strings.Contains(out, "duplicate") || !strings.Contains(out, "fb_0") {
+ t.Fatalf("path=%s out=%q", stub.lastPath, out)
+ }
+
+ _, err = runFeedback(t, "submit", "--target", stub.srv.URL, "--surface", "s", "--category", "bug", "--severity", "low")
+ if err == nil || !strings.Contains(err.Error(), "--title") {
+ t.Fatalf("expected local required-flag error, got %v", err)
+ }
+
+ _, err = runFeedback(t, "submit", "--target", "http://127.0.0.1:9", "--surface", "s", "--category", "bug", "--severity", "low", "--title", "t")
+ if err == nil || !strings.Contains(err.Error(), "does not advertise feedback.now") {
+ t.Fatalf("expected discovery failure, got %v", err)
+ }
+}
+
+func TestParseEvidenceFlags(t *testing.T) {
+ dir := t.TempDir()
+ p := filepath.Join(dir, "err.log")
+ os.WriteFile(p, []byte("stack trace"), 0o600)
+ ev, err := parseEvidenceFlags([]string{"stderr_excerpt=@" + p, "other=a=b"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if ev[0]["content"] != "stack trace" || ev[1]["type"] != "other" || ev[1]["content"] != "a=b" {
+ t.Fatalf("ev = %v", ev)
+ }
+ if _, err := parseEvidenceFlags([]string{"nope"}); err == nil {
+ t.Fatal("expected error for missing =")
+ }
+}
diff --git a/cmd/oc/internal/commands/root.go b/cmd/oc/internal/commands/root.go
index 1a8db987..3b1cfd07 100644
--- a/cmd/oc/internal/commands/root.go
+++ b/cmd/oc/internal/commands/root.go
@@ -83,6 +83,7 @@ func init() {
rootCmd.AddCommand(configCmd)
rootCmd.AddCommand(agentCmd)
rootCmd.AddCommand(logsCmd)
+ rootCmd.AddCommand(feedbackCmd)
rootCmd.AddCommand(loginCmd)
rootCmd.AddCommand(whoamiCmd)
rootCmd.AddCommand(logoutCmd)
diff --git a/docs/api-reference/agent-feedback.mdx b/docs/api-reference/agent-feedback.mdx
new file mode 100644
index 00000000..e890f3c2
--- /dev/null
+++ b/docs/api-reference/agent-feedback.mdx
@@ -0,0 +1,115 @@
+---
+title: "Agent Feedback (feedback.now)"
+description: "Let coding agents report bugs, docs mismatches, and friction directly to OpenComputer using the open feedback.now protocol"
+---
+
+OpenComputer implements the [feedback.now](https://feedback.now) protocol: a vendor-neutral, SDK-less
+HTTP interface that lets AI agents file structured feedback about an API, its docs, SDKs, or CLI
+while they are using it. Any agent that speaks feedback.now can report an issue to OpenComputer
+with no account, no API key, and no SDK — and get back a receipt it can poll for triage status.
+
+<Note>
+These endpoints are intentionally **unauthenticated** so third-party agents can report problems.
+They live under `/api/v1/` on the API host and are separate from the API-key-protected sandbox API
+under `/api/`.
+</Note>
+
+## Discovery
+
+Agents find the feedback surface at the well-known path:
+
+```bash
+curl https://app.opencomputer.dev/.well-known/agent-feedback.json
+```
+
+The document lists the endpoints below, the accepted categories and evidence types, and the
+optional request-signing scheme. `GET /api/v1/policy` returns the full policy including limits
+(max 10 evidence items, 64 KiB per item, titles up to 256 characters, summaries up to 4,096) and
+the rate limit (100 submissions per hour per client).
+
+## Submit feedback
+
+`POST /api/v1/feedback`
+
+```bash
+curl -X POST https://app.opencomputer.dev/api/v1/feedback \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "reporter": { "agent_vendor": "anthropic", "agent_product": "claude-code", "agent_version": "1.2.3" },
+ "subject": { "surface": "POST /api/sandboxes", "domain": "app.opencomputer.dev", "kind": "api_endpoint" },
+ "signal": { "category": "bug", "severity": "high", "reproducibility": "always", "confidence": 0.9 },
+ "content": { "title": "create returns 500 when template is missing",
+ "summary": "Expected a 404 with a clear error message." },
+ "evidence": [ { "type": "http_summary", "content": "{\"status\":500,\"body\":\"internal error\"}" } ]
+ }'
+```
+
+| Field | Values |
+| --- | --- |
+| `signal.category` | `bug`, `docs_mismatch`, `friction`, `feature_gap`, `quality_degradation`, `other` (plus any listed by `GET /api/v1/categories`) |
+| `signal.severity` | `critical`, `high`, `medium`, `low` |
+| `signal.reproducibility` | `always`, `sometimes`, `intermittent`, `once` |
+| `signal.confidence` | number from 0 to 1 |
+| `subject.kind` | `api_endpoint`, `docs_page`, `cli_command`, `sdk_method`, `other` |
+| `evidence[].type` | `http_summary`, `stderr_excerpt`, `repro_steps`, `screenshot`, `log_excerpt`, `other` |
+
+Responses:
+
+```json 201
+{
+ "receipt": {
+ "id": "rcpt_…",
+ "status": "accepted",
+ "feedback_id": "fb_…",
+ "evidence_ids": ["ev_…"],
+ "created_at": "2026-01-01T00:00:00.000Z"
+ }
+}
+```
+
+If the same surface and title were already reported in the last 30 days, the report is folded into
+the existing one: the receipt has `"status": "duplicate"` and `duplicate_of` pointing at the
+canonical `feedback_id`. Validation problems return `400` with
+`{ "error": "validation_failed", "errors": [{ "field", "error", "message" }] }`.
+
+More evidence can be attached later with `POST /api/v1/feedback/{id}/attachments`, and any report
+can be read back with `GET /api/v1/feedback/{id}`.
+
+## Submit an observation
+
+`POST /api/v1/observations` is the lightweight form for low-confidence or repetitive signals —
+only `surface`, `domain`, `agent_vendor`, and `agent_product` are required:
+
+```bash
+curl -X POST https://app.opencomputer.dev/api/v1/observations \
+ -H 'Content-Type: application/json' \
+ -d '{ "surface": "oc sandbox create", "domain": "app.opencomputer.dev",
+ "agent_vendor": "openai", "agent_product": "codex",
+ "category": "friction", "summary": "--template flag name differs from the docs" }'
+```
+
+## Receipts
+
+`GET /api/v1/receipts/{id}` returns the current state of a submission. `status` is one of
+`accepted`, `duplicate`, `rejected`, `queued`, or `needs_more_evidence`; once a report is triaged,
+`feedback_status` (`open`, `accepted`, `resolved`, `wontfix`, `spam`), `quality_score`, and
+`duplicate_of` are filled in so an agent can learn whether its report was useful.
+
+## Signing (optional)
+
+Anonymous submissions are accepted. Agents that want a persistent identity — and the reputation
+that comes with reports being accepted — can sign requests with an Ed25519 key:
+
+| Header | Value |
+| --- | --- |
+| `X-Agent-Key` | base64 SPKI DER Ed25519 public key |
+| `X-Agent-Timestamp` | ISO 8601 timestamp, within 5 minutes of server time |
+| `X-Agent-Signature` | base64 Ed25519 signature over `timestamp\nMETHOD\npath\nsha256hex(body)` |
+
+Requests carrying a bad or stale signature are rejected with `401`.
+
+## From the CLI
+
+The `oc` CLI ships an emitter so agents running inside OpenComputer (or anywhere `oc` is
+installed) can report issues without hand-writing JSON — see [`oc feedback`](/cli/feedback). It
+works against any feedback.now receiver, not only OpenComputer.
diff --git a/docs/cli/feedback.mdx b/docs/cli/feedback.mdx
new file mode 100644
index 00000000..718a0692
--- /dev/null
+++ b/docs/cli/feedback.mdx
@@ -0,0 +1,68 @@
+---
+title: "Feedback"
+description: "Report bugs, docs mismatches, and friction with the feedback.now protocol from the CLI"
+---
+
+`oc feedback` is a [feedback.now](https://feedback.now) emitter. When you — or an agent driving
+`oc` — hit a bug, a docs mismatch, or friction in an API, CLI, or SDK, file it straight from the
+terminal. No account or API key is needed; every submission returns a receipt you can poll.
+
+By default it reports to OpenComputer. Pass `--target` (or set `OC_FEEDBACK_TARGET`) to report to
+any other host that publishes `/.well-known/agent-feedback.json`. See the
+[protocol reference](/api-reference/agent-feedback) for the receiving side.
+
+```bash
+# What does the target accept?
+oc feedback policy
+
+# File a structured report
+oc feedback submit \
+ --surface 'POST /api/sandboxes' --category bug --severity high \
+ --title 'create returns 500 when template is missing' \
+ --summary 'Expected a 404 with a clear error' \
+ --reproducibility always \
+ --evidence 'http_summary={"status":500}' \
+ --evidence [email protected]
+
+# Lightweight signal — no title or evidence needed
+oc feedback observe --surface 'oc sandbox create' --category friction \
+ --summary '--template flag name differs from the docs'
+
+# Check what happened to a report
+oc feedback receipt rcpt_…
+
+# Report to a different feedback.now receiver
+oc feedback submit --target https://api.example.com --surface 'GET /v1/items' \
+ --category docs_mismatch --severity low --title 'docs say limit max is 500, API caps at 100'
+```
+
+## Flags
+
+| Flag | Applies to | Notes |
+| --- | --- | --- |
+| `--surface` | submit, observe | Required. What was being used: `POST /api/sandboxes`, `oc exec`, `Sandbox.create()`, a docs URL |
+| `--category` | submit, observe | `bug`, `docs_mismatch`, `friction`, `feature_gap`, `quality_degradation`, `other` |
+| `--severity` | submit, observe | `critical`, `high`, `medium`, `low` |
+| `--title` | submit | Required. Short, specific |
+| `--summary` | submit, observe | What happened vs. what you expected |
+| `--hypothesis` | submit | Suspected root cause |
+| `--reproducibility` | submit | `always`, `sometimes`, `intermittent`, `once` |
+| `--confidence` | submit, observe | 0–1, default 0.7 |
+| `--kind` | submit, observe | `api_endpoint`, `docs_page`, `cli_command`, `sdk_method`, `other` |
+| `--evidence` | submit | `type=content` or `type=@file`; repeatable, up to 10 |
+| `--target`, `--domain` | all | Receiver base URL; `subject.domain` defaults to its host |
+| `--agent-vendor`, `--agent-product`, `--agent-version` | all | Reporter identity; default `opencomputer` / `oc-cli` / the `oc` version |
+| `--signing-key` | all | PEM Ed25519 key from `oc feedback keygen`; also `OC_FEEDBACK_SIGNING_KEY` |
+
+`--json` prints the raw receipt. Exit code `3` means the receiver rejected the request (the
+validation errors are printed), matching the rest of `oc`.
+
+## Signing
+
+Signing is optional. A signed agent builds a reputation across submissions, which receivers use
+to prioritize triage:
+
+```bash
+oc feedback keygen --out ~/.config/oc/agent-feedback.pem
+export OC_FEEDBACK_SIGNING_KEY=~/.config/oc/agent-feedback.pem
+```
diff --git a/docs/docs.json b/docs/docs.json
index 1c3bcd9a..e0701ac3 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -166,7 +166,8 @@
"cli/checkpoint",
"cli/patch",
"cli/preview",
- "cli/secrets"
+ "cli/secrets",
+ "cli/feedback"
]
},
{
@@ -290,6 +291,7 @@
"api-reference/capacity/list-reservations"
]
},
+ "api-reference/agent-feedback",
{
"group": "Commands",
"pages": [
diff --git a/skills/opencomputer/SKILL.md b/skills/opencomputer/SKILL.md
index faad10b7..7cde66b4 100644
--- a/skills/opencomputer/SKILL.md
+++ b/skills/opencomputer/SKILL.md
@@ -183,6 +183,37 @@ oc shell <sandbox-id>
oc shell <sandbox-id> --shell /bin/zsh
```
+### Report a bug or friction (feedback.now)
+
+If OpenComputer itself misbehaves while you work — an API call returns an unexpected error, a
+flag doesn't match the docs, an SDK method is confusing — report it. Reports go through the
+open [feedback.now](https://feedback.now) protocol; no API key needed and it does not interrupt
+your task. Prefer one precise report over many vague ones.
+
+```bash
+# Full report: --surface, --category, --severity, --title are required
+oc feedback submit \
+ --surface 'POST /api/sandboxes' --kind api_endpoint \
+ --category bug --severity high --reproducibility always \
+ --title 'create returns 500 when template is missing' \
+ --summary 'Expected 404 with a clear error' \
+ --evidence 'http_summary={"status":500}' --evidence stderr_excerpt=@/tmp/err.log \
+ --agent-vendor <your-vendor> --agent-product <your-product> --json
+
+# Low-confidence or minor: an observation (only --surface required)
+oc feedback observe --surface 'oc sandbox create' --category friction \
+ --summary '--template flag name differs from the docs'
+
+# Later: was it accepted, folded into a known issue, or fixed?
+oc feedback receipt <receipt-id> --json
+```
+
+- Categories: `bug`, `docs_mismatch`, `friction`, `feature_gap`, `quality_degradation`, `other`.
+ Severities: `critical`, `high`, `medium`, `low`.
+- Set `--agent-vendor` / `--agent-product` to identify yourself (e.g. `anthropic` / `claude-code`).
+- Never put secrets, API keys, or customer data in `--summary` or `--evidence`.
+- Works against any feedback.now host: `oc feedback submit --target https://api.example.com ...`.
+
### Global Flags
All commands support: