From 0a9b897f48e545a63ee761a3d6ad38bddb1b1f51 Mon Sep 17 00:00:00 2001 From: Sam Bretz Date: Fri, 23 Oct 2026 02:03:48 -0700 Subject: [PATCH] Support staged provider approval for experiment operations --- README.md | 8 ++++ src/action-help.js | 6 +-- src/args.js | 13 +++++- src/experiments-contract.js | 40 +++++++++++++++++++ src/experiments-output.js | 13 +++++- src/experiments.js | 24 ++++++++++- src/output.js | 4 +- test/args.test.js | 13 ++++++ test/experiments.test.js | 80 +++++++++++++++++++++++++++++++++++++ 9 files changed, 192 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 80bcdf4..3154dcf 100644 --- a/README.md +++ b/README.md @@ -274,6 +274,14 @@ Exit codes are stable. Changing one is a breaking change. Codes 10 to 18 are not the read commands still send only their Metadata requests with it. `experiments start` needs Debug access and Allow analysis starts; the service then replays the sampled calls on the chosen providers within its own budget. A key with Replay access is refused. + For services offering staged provider consent, add `--request-key UUID` to prepare an + operation. Keep that UUID and the complete request unchanged when checking progress. + The workspace owner reviews the exact input, provider, model and spending limits on + the service's receipt page. After approval, repeat the request with `--consent-id UUID`. + Later requests derived from provider output can require another approval. The CLI + never approves a receipt. It refuses this workflow before posting to an older service + that does not advertise it. Preparation is reported as an operation, not a started + experiment; an uncertain call must not be resent under a new request key. - **Credentials.** The sign in grant is stored per user in `~/.config/metergraph` (`AppData\Roaming\Metergraph` on Windows), as owner-only files on Linux and macOS and encrypted with DPAPI on Windows. The ingest key goes only into the project's private diff --git a/src/action-help.js b/src/action-help.js index 38db4ef..eab4863 100644 --- a/src/action-help.js +++ b/src/action-help.js @@ -59,9 +59,9 @@ export function actionHelpData(topic, action, commands) { const entry = commands.find(c => c.name === topic); const names = { list: ["--workload", "--limit"], get: ["--id"], estimate: ["--workload", "--treatment", "--last-n", "--sample-model", "--track"], - start: ["--workload", "--treatment", "--last-n", "--sample-model", "--track"] }[action]; + start: ["--workload", "--treatment", "--last-n", "--sample-model", "--track", "--request-key", "--consent-id"] }[action]; if (!names) return null; - const specific = ["--workload", "--limit", "--id", "--treatment", "--last-n", "--sample-model", "--track"]; + const specific = ["--workload", "--limit", "--id", "--treatment", "--last-n", "--sample-model", "--track", "--request-key", "--consent-id"]; const options = entry.options.filter(o => !specific.includes(o.name) || names.includes(o.name)).map(o => { if (o.name === "--agent-token-file") return { ...o, summary: action === "start" ? "Private (0600) Debug key file with Allow analysis starts. Or set METERGRAPH_AGENT_TOKEN." @@ -82,7 +82,7 @@ export function actionHelpData(topic, action, commands) { usage: `metergraph experiments ${action} ${invocation} [options]`, options, examples: [`metergraph experiments ${action} ${{ list: "--limit 10", get: "--id UUID", estimate: "--workload ROUTE --treatment PROVIDER/MODEL", start: "--workload ROUTE --treatment PROVIDER/MODEL --agent-token-file /path/to/private-key" }[action]}`], note: action === "start" - ? "Replays captured production prompts on the selected providers and incurs provider costs. Requires a Debug key with Allow analysis starts. Estimate first. Each start creates a new experiment; never retry a successful start." + ? "Provider execution sends captured prompts and incurs costs. Estimate first. With --request-key, preparation and later calls pause for owner approval of exact data, provider, model and spending limits. Reuse the same key and request to check or resume. Older services cannot accept this consent workflow. Without a request key, never retry a successful legacy start." : { list: "Uses Metadata access. Returns experiment summaries.", get: "Uses Metadata access. Returns results without prompts or responses.", estimate: "Uses Metadata access. Estimates provider cost without starting a replay." }[action] }; diff --git a/src/args.js b/src/args.js index af7f6e3..b03066a 100644 --- a/src/args.js +++ b/src/args.js @@ -86,7 +86,7 @@ const OPTIONS = { ]), verify: new Set([...READ_BASE, "--trace-id", "--request-id", "--since", "--until", "--source", "--days", "--poll-ms", "--max-attempts"]), experiments: new Set([ - ...READ_BASE, ...READ_KEY, "--workload", "--limit", "--treatment", "--last-n", "--sample-model", "--track", "--id", + ...READ_BASE, ...READ_KEY, "--workload", "--limit", "--treatment", "--last-n", "--sample-model", "--track", "--id", "--request-key", "--consent-id", ]), tools: new Set([...READ_BASE, ...READ_KEY, "--name", "--args", "--args-file"]), }; @@ -94,7 +94,7 @@ const OPTIONS = { const EXPERIMENT_OPTIONS = { list: new Set(["--workload", "--limit"]), estimate: new Set(["--workload", "--treatment", "--last-n", "--sample-model", "--track"]), - start: new Set(["--workload", "--treatment", "--last-n", "--sample-model", "--track"]), + start: new Set(["--workload", "--treatment", "--last-n", "--sample-model", "--track", "--request-key", "--consent-id"]), get: new Set(["--id"]), }; // Requests the read commands recognize and refuse, so a script gets an @@ -542,6 +542,15 @@ function parseExperiments(action, values, json, fail) { return fail("invalid_tracked_fields", `Give at most ${EXPERIMENT_MAX_TRACKED_FIELDS} --track JSON paths, each starting with $.`); } parsed.experiment.request = { workload_id: workload, sample, treatments, tracked_fields: [...new Set(tracked)] }; + for (const [option, field] of [["--request-key", "request_key"], ["--consent-id", "consent_id"]]) { + if (values[option] !== undefined) { + if (!UUID.test(values[option])) return fail("invalid_consent_identifier", `${option} must be a UUID.`); + parsed.experiment.request[field] = values[option].toLowerCase(); + } + } + if (parsed.experiment.request.consent_id && !parsed.experiment.request.request_key) { + return fail("missing_request_key", "--consent-id requires the original --request-key."); + } return parsed; } diff --git a/src/experiments-contract.js b/src/experiments-contract.js index e4352eb..41177f6 100644 --- a/src/experiments-contract.js +++ b/src/experiments-contract.js @@ -379,6 +379,46 @@ export function experimentStarted(body, ctx, request, notices) { }); } +// A managed start prepares or resumes one operation. It is not a claim that +// an experiment exists, and returned commands are never executed or copied. +export function managedExperiment(body, ctx, request, notices) { + return run(() => { + const reason = "experiment_start_invalid"; + const origin = provenance(body, ctx, reason); + contentExcluded(body); + const echoed = echoedRequest(body.request, request, notices, reason); + if (normalizeUuid(request.request_key) === null || body.request.request_key !== request.request_key) fail(reason); + const operation = rowObject(body.managed_operation, reason); + const id = normalizeUuid(operation.id); + const states = ["preparing", "awaiting_approval", "queued", "running", "completed", "uncertain", "failed"]; + const terminal = ["completed", "uncertain", "failed"].includes(operation.status); + const money = value => { + if (typeof value !== "string" || !/^(?:0|[1-9][0-9]{0,11})(?:\.[0-9]{1,12})?$/.test(value)) return null; + const [whole, fraction = ""] = value.split("."); + return BigInt(whole) * 1000000000000n + BigInt(fraction.padEnd(12, "0")); + }; + const ceiling = money(operation.operation_ceiling_usd), allocated = money(operation.allocated_usd); + if (id === null || operation.kind !== "experiment" || !states.includes(operation.status) || + operation.terminal !== terminal || ceiling === null || allocated === null || + ceiling <= 0n || allocated > ceiling) fail(reason); + let approval = null; + if (body.approval !== null) { + const entry = rowObject(body.approval, reason); + const consentId = normalizeUuid(entry.consent_id); + if (operation.status !== "awaiting_approval" || consentId === null || + !Number.isSafeInteger(entry.stage) || entry.stage < 0 || + typeof entry.plan_digest !== "string" || !/^[0-9a-f]{64}$/.test(entry.plan_digest) || + entry.consent_url !== `/v1/agent/provider-consent/${consentId}`) fail(reason); + // Only the fixed receipt path on the already verified origin survives. + approval = { consent_id: consentId, stage: entry.stage, plan_digest: entry.plan_digest, + consent_url: new URL(entry.consent_url, ctx.origin).href }; + } else if (operation.status === "awaiting_approval") fail(reason); + return { provenance: origin, request: { ...echoed, request_key: request.request_key }, + managed_operation: { id, kind: "experiment", status: operation.status, terminal, + operation_ceiling_usd: operation.operation_ceiling_usd, allocated_usd: operation.allocated_usd }, approval }; + }); +} + // GET /v1/agent/experiments/: status while it runs, then the built-in // statistics per arm next to the production control over the same cases. // They show differences; nothing here judges a treatment. diff --git a/src/experiments-output.js b/src/experiments-output.js index d1259e5..f17c709 100644 --- a/src/experiments-output.js +++ b/src/experiments-output.js @@ -7,6 +7,7 @@ import { PLAIN, fields, headline, paragraph, render, steps, toneFor, workspaceSh // message is never printed. const MESSAGES = { + managed_consent_unavailable: "This service does not advertise the required provider-consent contract. Nothing was sent to start an experiment.", experiments_unavailable: "This deployment does not offer experiments to this credential, for example because the feature is off. " + "Nothing was read or started.", @@ -132,6 +133,14 @@ function resultLines(action, report) { return [rows, body]; } if (action === "start") { + if (report.managed_operation) { + const operation = report.managed_operation; + return [[ + ["Operation", operation.id], ["Status", operation.status], ["Request key", report.request.request_key], + ["Spending limit", `$${operation.operation_ceiling_usd}`], ["Reserved", `$${operation.allocated_usd}`], + ["Consent ID", report.approval?.consent_id ?? null], ["Owner review", report.approval?.consent_url ?? null], + ], ["Preparation and later provider calls can each pause for a new exact-plan approval."]]; + } const { experiment } = report; const rows = [ ["Experiment", experiment.id], @@ -160,10 +169,10 @@ function resultLines(action, report) { export function experimentsText(result, message, style = PLAIN, action) { const data = result.data; - const title = `${TITLES[action]}${result.ok ? "" : action === "start" ? " was not started" : " could not be read"}`; + const title = `${data.result?.managed_operation ? "Experiment operation" : TITLES[action]}${result.ok ? "" : action === "start" ? " was not started" : " could not be read"}`; const lines = [ `${headline(style, result.ok ? "info" : toneFor(result.outcome), title, result.outcome)} ${ - style.dim(action === "start" ? "Replays captured prompts within the server's budget" : "Metadata only")}`, + style.dim(data.result?.managed_operation ? "Exact provider-plan approval" : action === "start" ? "Replays captured prompts within the server's budget" : "Metadata only")}`, "", ]; const rows = [["Origin", data.origin], ["Workspace", workspaceShown(data.workspace)]]; diff --git a/src/experiments.js b/src/experiments.js index 6671baf..d0c0c91 100644 --- a/src/experiments.js +++ b/src/experiments.js @@ -7,6 +7,7 @@ import { experimentEstimate, experimentRefusal, experimentStarted, + managedExperiment, experimentSummary, experimentsList, } from "./experiments-contract.js"; @@ -295,6 +296,11 @@ export async function runExperimentStart(options) { ctx.authenticated = true; ctx.scopes = session.session.scopes; const request = options.experiment.request; + ctx.requestKey = request.request_key ?? null; + if (request.request_key && session.documents.capabilities?.agent?.experiment_start?.provider_consent_contract !== + "metergraph.pipeline-managed/v1") { + return end("capability_unavailable", "managed_consent_unavailable"); + } // The start has its own deadline: the service samples, prices and // launches within the request, and an answer cut short is ambiguous. const post = deadline(options.timeoutMs, trap.signal); @@ -310,7 +316,12 @@ export async function runExperimentStart(options) { if (trap.signal.aborted) return end("cancelled", "cancelled"); return end(started.outcome, started.reason, started.refusal ? { refusal: started.refusal } : null); } - // Accepted: whatever its answer says from here, an experiment exists. + if (request.request_key) { + const value = managedExperiment(started.body, ctx, request, notices); + if (!value.ok) return end("unconfirmed", "experiment_start_unconfirmed"); + return end("ok", null, value.value); + } + // Legacy accepted start: an experiment exists. const value = experimentStarted(started.body, ctx, request, notices); if (!value.ok) return end("unconfirmed", "experiment_start_unconfirmed"); if (value.value.experiment.status === "failed") return end("unhealthy", "experiment_launch_failed", value.value); @@ -353,13 +364,24 @@ function startData(ctx, notices, outcome, report) { refusal: outcome === "refused" ? report?.refusal ?? null : null, notices: [...notices].sort(), next_action: startNextAction(outcome, ctx, report), + ...(ctx.requestKey ? { request_key: ctx.requestKey } : {}), }; } function startNextAction(outcome, ctx, report) { const keys = handoffPages(ctx.origin ?? ctx.keysOrigin).keys_url; + if (outcome === "ok" && report.managed_operation) { + const operation = report.managed_operation; + if (report.approval) return { kind: "review_provider_plan", url: report.approval.consent_url, + message: "The workspace owner must review the exact data, provider, model and spending limits. After approval, repeat the same request key with this consent ID. Never approve on the owner's behalf." }; + return { kind: operation.terminal ? "inspect_operation" : "poll_operation", url: null, + message: operation.terminal ? "This operation is terminal. Do not resend an uncertain provider call." + : "Preparation or execution is pending. Repeat the same request and request key to check progress; do not create another key." }; + } if (outcome === "ok") return pollOrOpen({ ...report.experiment, app_url: report.app_url }, { started: true }); if (outcome === "unconfirmed") { + if (ctx.requestKey) return { kind: "check_same_operation", url: null, + message: "The operation may exist. Repeat the identical request with the same request key to check its state. Do not create another key or resend an uncertain provider call." }; return { kind: "check_before_retry", message: diff --git a/src/output.js b/src/output.js index 38cf84b..03a1e39 100644 --- a/src/output.js +++ b/src/output.js @@ -279,7 +279,7 @@ const EXPERIMENTS_USAGE = [ "metergraph experiments list [--workload ID] [--limit N] [read options] [--json]", "metergraph experiments estimate --workload ID --treatment SPEC [--treatment SPEC]... [--last-n N] " + "[--sample-model MODEL] [--track PATH]... [read options] [--json]", - "metergraph experiments start (same as estimate) [--agent-token-file PATH] [--json]", + "metergraph experiments start (same as estimate) [--request-key UUID] [--consent-id UUID] [--agent-token-file PATH] [--json]", "metergraph experiments get --id UUID [read options] [--json]", ]; const EXPERIMENTS_OPTIONS = [ @@ -294,6 +294,8 @@ const EXPERIMENTS_OPTIONS = [ { name: "--last-n", value: "N", summary: "Replay the last N replayable calls, 10 to 40. Default 20." }, { name: "--sample-model", value: "MODEL", summary: "Only production calls made with this exact model, for a single-model control." }, { name: "--track", value: "PATH", summary: "Up to 10 times. A JSON path such as $.priority whose values the dashboard compares." }, + { name: "--request-key", value: "UUID", summary: "Prepare or resume the same provider-consent operation. Keep this key and the request unchanged across approvals." }, + { name: "--consent-id", value: "UUID", summary: "Resume with the receipt the workspace owner approved. Requires the original --request-key." }, { name: "--id", value: "UUID", summary: "The experiment to read (get)." }, { name: "--limit", value: "N", summary: "Experiments to list, 1 to 50. Default 20." }, ...READ_BASE_OPTIONS.filter((option) => option.name !== "--agent-token-file"), diff --git a/test/args.test.js b/test/args.test.js index 7c0e008..97b7df0 100644 --- a/test/args.test.js +++ b/test/args.test.js @@ -3,6 +3,19 @@ import { test } from "node:test"; import { parseArgs } from "../src/args.js"; +test("provider consent identifiers apply only to starts and preserve the request key", () => { + const args = ["experiments", "start", "--workload", "sample", "--treatment", "openai/example-model"]; + const key = "10000000-0000-4000-8000-000000000001"; + const consent = "10000000-0000-4000-8000-000000000002"; + const result = parseArgs([...args, "--request-key", key, "--consent-id", consent]); + assert.equal(result.ok, true); + assert.equal(result.experiment.request.request_key, key); + assert.equal(result.experiment.request.consent_id, consent); + assert.equal(parseArgs([...args, "--consent-id", consent]).ok, false); + assert.equal(parseArgs([...args, "--request-key", "not-a-key"]).ok, false); + assert.equal(parseArgs(["experiments", "list", "--request-key", key]).ok, false); +}); + test("defaults doctor to the hosted origin and the default timeout", () => { const parsed = parseArgs(["doctor"]); assert.equal(parsed.ok, true); diff --git a/test/experiments.test.js b/test/experiments.test.js index ed893a4..a10b2a7 100644 --- a/test/experiments.test.js +++ b/test/experiments.test.js @@ -36,6 +36,86 @@ const SENT = { tracked_fields: ["$.priority"], }; +const REQUEST_KEY = "10000000-0000-4000-8000-000000000001"; +const CONSENT_ID = "10000000-0000-4000-8000-000000000002"; +const MANAGED_START = ["experiments", "start", ...ESTIMATE.slice(2), "--request-key", REQUEST_KEY]; +const managedCapability = doc => { + doc.agent.experiment_start.provider_consent_contract = "metergraph.pipeline-managed/v1"; + return doc; +}; +function managedDocument(doc) { + delete doc.experiment; + delete doc.app_url; + doc.request.request_key = REQUEST_KEY; + doc.managed_operation = { id: EXPERIMENT_ID, kind: "experiment", status: "awaiting_approval", terminal: false, + operation_ceiling_usd: "5.00", allocated_usd: "0.00" }; + doc.approval = { consent_id: CONSENT_ID, consent_url: `/v1/agent/provider-consent/${CONSENT_ID}`, + stage: 0, plan_digest: "a".repeat(64) }; + doc.follow = { command: "SYNTHETIC_BODY_MARKER", url: "https://evil.example.com" }; + return doc; +} + +test("managed preparation requires advertised consent before any start POST", () => + withServer({}, async server => { + const { result } = await run(server, MANAGED_START, { key: START_KEY }); + assert.equal(result.error.reason, "managed_consent_unavailable"); + assert.equal(server.requestsTo("/v1/agent/experiments").length, 0); + })); + +test("managed start shows a validated owner receipt without claiming an experiment started", () => + withServer({ capabilities: managedCapability, experiments: (doc, kind) => kind === "start" ? managedDocument(doc) : doc }, async server => { + const { result } = await run(server, MANAGED_START, { key: START_KEY }); + assert.equal(result.ok, true); + assert.equal(result.data.result.managed_operation.status, "awaiting_approval"); + assert.equal(result.data.result.experiment, undefined); + assert.equal(result.data.result.request.request_key, REQUEST_KEY); + assert.equal(result.data.next_action.kind, "review_provider_plan"); + assert.equal(result.data.next_action.url, `${server.origin}/v1/agent/provider-consent/${CONSENT_ID}`); + const { run: output } = await run(server, MANAGED_START, { key: START_KEY, json: false }); + assert.match(output.stdout, /Experiment operation/); + assert.doesNotMatch(output.stdout, /Experiment started/); + })); + +test("managed response rejects substituted requests, foreign links, caps and terminal mismatches", async () => { + for (const mutate of [ + doc => { doc.request.request_key = CONSENT_ID; }, + doc => { doc.approval.consent_url = "https://evil.example.com"; }, + doc => { doc.approval.consent_url += "?token=secret"; }, + doc => { doc.managed_operation.allocated_usd = "6.00"; }, + doc => { doc.managed_operation.operation_ceiling_usd = "999999999999.000000000001"; doc.managed_operation.allocated_usd = "999999999999.000000000002"; }, + doc => { doc.managed_operation.terminal = true; }, + doc => { doc.content_included = true; }, + doc => { doc.approval.plan_digest = "\u001b[31m"; }, + ]) { + await withServer({ capabilities: managedCapability, experiments: (doc, kind) => { + if (kind === "start") { managedDocument(doc); mutate(doc); } + return doc; + } }, async server => { + const { result } = await run(server, MANAGED_START, { key: START_KEY }); + assert.equal(result.outcome, "unconfirmed"); + assert.equal(result.data.result, null); + }); + } +}); + +test("managed resume sends the same request key and approved receipt and preserves preparation state", () => + withServer({ capabilities: managedCapability, experiments: (doc, kind) => { + if (kind === "start") { + managedDocument(doc); + doc.managed_operation.status = "queued"; + doc.approval = null; + } + return doc; + } }, async server => { + const { result } = await run(server, [...MANAGED_START, "--consent-id", CONSENT_ID], { key: START_KEY }); + assert.equal(result.ok, true); + assert.equal(result.data.result.managed_operation.status, "queued"); + assert.equal(result.data.next_action.kind, "poll_operation"); + const posted = server.requestsTo("/v1/agent/experiments").find(entry => entry.method === "POST"); + assert.equal(JSON.parse(posted.body).request_key, REQUEST_KEY); + assert.equal(JSON.parse(posted.body).consent_id, CONSENT_ID); + })); + async function withServer(behavior, work) { const server = await startOAuthServer({ agentTokens: [METADATA_KEY], startTokens: [START_KEY], ...behavior }); try {