Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions src/action-help.js
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand All @@ -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] };
Expand Down
13 changes: 11 additions & 2 deletions src/args.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,15 +86,15 @@ 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"]),
};
// Which experiments options each action takes, beyond READ_BASE and READ_KEY.
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
Expand Down Expand Up @@ -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;
}

Expand Down
40 changes: 40 additions & 0 deletions src/experiments-contract.js
Original file line number Diff line number Diff line change
Expand Up @@ -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/<id>: 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.
Expand Down
13 changes: 11 additions & 2 deletions src/experiments-output.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down Expand Up @@ -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],
Expand Down Expand Up @@ -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)]];
Expand Down
24 changes: 23 additions & 1 deletion src/experiments.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
experimentEstimate,
experimentRefusal,
experimentStarted,
managedExperiment,
experimentSummary,
experimentsList,
} from "./experiments-contract.js";
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 3 additions & 1 deletion src/output.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand All @@ -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"),
Expand Down
13 changes: 13 additions & 0 deletions test/args.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading