@orchestraai/agent-tools 0.10.17 → 0.10.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,12 @@
1
+ /**
2
+ * `understudy trust` — the one-time autonomy posture (~/.understudy/trust.json).
3
+ *
4
+ * Smart defaults instead of per-action approval dialogs: set the posture
5
+ * once, and every spend/upload/traffic gate consults it instead of
6
+ * prompting. Visible (`trust show`) and reversible (`trust set`).
7
+ */
8
+ import { createInterface } from "node:readline/promises";
9
+ import { SPEND_APPROVAL_TTL_MS, issueSpendApproval, listPendingSpendRequests, spendApprovalsPath, } from "../config/spend-approval.js";
1
10
  import { TRUST_LEVELS, readTrustPosture, resolveTrustBoundaries, trustPosturePath, writeTrustPosture, } from "../config/trust.js";
2
11
  export function registerTrustCommand(program) {
3
12
  const trust = program
@@ -51,5 +60,58 @@ export function registerTrustCommand(program) {
51
60
  console.error(`trust: posture set to ${posture.level} (${trustPosturePath()})`);
52
61
  console.log(JSON.stringify({ posture, resolved: resolveTrustBoundaries(posture) }, null, 2));
53
62
  });
63
+ trust
64
+ .command("approve-spend")
65
+ .description("Approve ONE blocked spend-adjacent benchmark request without raising the posture. Interactive: run it " +
66
+ `yourself in a terminal and answer the prompt. Issues a single-use approval for that exact request, valid ${SPEND_APPROVAL_TTL_MS / 60_000} minutes; the same request then goes through once.`)
67
+ .option("--request <id>", "Pending request id (or a unique prefix) to review; defaults to the most recent")
68
+ .option("--list", "List pending requests without prompting")
69
+ .action(async (options) => {
70
+ const pending = listPendingSpendRequests();
71
+ if (options.list) {
72
+ console.log(JSON.stringify({ file: spendApprovalsPath(), pending: pending.map((p) => ({ id: p.digest.slice(0, 12), ...p })) }, null, 2));
73
+ return;
74
+ }
75
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
76
+ console.error("trust approve-spend: needs an interactive terminal. Run it yourself and answer the prompt " +
77
+ "(or raise the posture with `orchestra trust set bounded_experiments`).");
78
+ process.exitCode = 1;
79
+ return;
80
+ }
81
+ if (pending.length === 0) {
82
+ console.error("trust approve-spend: no blocked spend requests are waiting.");
83
+ return;
84
+ }
85
+ const matches = options.request
86
+ ? pending.filter((p) => p.digest.startsWith(options.request.toLowerCase()))
87
+ : pending.slice(0, 1);
88
+ if (matches.length !== 1) {
89
+ console.error(`trust approve-spend: ${matches.length === 0 ? "no" : "more than one"} pending request matches ` +
90
+ `"${options.request}". See \`orchestra trust approve-spend --list\`.`);
91
+ process.exitCode = 1;
92
+ return;
93
+ }
94
+ const request = matches[0];
95
+ console.log(`Pending request ${request.digest.slice(0, 12)} (blocked at ${request.requested_at}):`);
96
+ console.log(` ${request.summary}`);
97
+ if (pending.length > 1 && !options.request) {
98
+ console.log(`(${pending.length - 1} older request(s) waiting; see --list and --request.)`);
99
+ }
100
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
101
+ let answer = "";
102
+ try {
103
+ answer = (await rl.question("Approve this one request? Type \"yes\" to approve: ")).trim().toLowerCase();
104
+ }
105
+ finally {
106
+ rl.close();
107
+ }
108
+ if (answer !== "yes") {
109
+ console.log("Not approved.");
110
+ return;
111
+ }
112
+ const approval = issueSpendApproval(request.digest);
113
+ console.log(`Approved once, until ${approval.expires_at}. Ask the agent to make the same request again; ` +
114
+ "the approval is used up by that one call.");
115
+ });
54
116
  }
55
117
  //# sourceMappingURL=trust.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"trust.js","sourceRoot":"","sources":["../../src/commands/trust.ts"],"names":[],"mappings":"AASA,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,sBAAsB,EACtB,gBAAgB,EAChB,iBAAiB,GAElB,MAAM,oBAAoB,CAAC;AAE5B,MAAM,UAAU,oBAAoB,CAAC,OAAgB;IACnD,MAAM,KAAK,GAAG,OAAO;SAClB,OAAO,CAAC,OAAO,CAAC;SAChB,WAAW,CACV,iGAAiG;QAC/F,WAAW,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,6DAA6D,CACnG,C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AE,CAAC,KAAK,EAAE,CAAC;QACb,CAAC;QACD,IAAI,MAAM,KAAK,KAAK,EAAE,CAAC;YACrB,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;YAC7B,OAAO;QACT,CAAC;QACD,MAAM,QAAQ,GAAG,kBAAkB,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACpD,OAAO,CAAC,GAAG,CACT,wBAAwB,QAAQ,CAAC,UAAU,kDAAkD;YAC3F,2CAA2C,CAC9C,CAAC;IACJ,CAAC,CAAC,CAAC;AACP,CAAC"}
@@ -0,0 +1,45 @@
1
+ export declare const SPEND_APPROVALS_SCHEMA = "understudy.spend_approvals.v1";
2
+ /** How long an issued approval stays usable. */
3
+ export declare const SPEND_APPROVAL_TTL_MS: number;
4
+ export type PendingSpendRequest = {
5
+ digest: string;
6
+ tool: string;
7
+ summary: string;
8
+ requested_at: string;
9
+ };
10
+ export type SpendApproval = {
11
+ token: string;
12
+ digest: string;
13
+ tool: string;
14
+ issued_at: string;
15
+ expires_at: string;
16
+ };
17
+ type Obj = Record<string, unknown>;
18
+ /** `UNDERSTUDY_SPEND_APPROVALS_FILE` overrides for tests/sandboxes; default is the global config dir. */
19
+ export declare function spendApprovalsPath(env?: NodeJS.ProcessEnv): string;
20
+ /** Stable digest of one request: tool name plus arguments with sorted keys. */
21
+ export declare function spendRequestDigest(tool: string, args: Obj): string;
22
+ /**
23
+ * Record a blocked request so the operator can review it with
24
+ * `orchestra trust approve-spend`. Newest first; a repeat of the same
25
+ * request moves to the front instead of duplicating.
26
+ */
27
+ export declare function recordPendingSpendRequest(tool: string, args: Obj, env?: NodeJS.ProcessEnv, now?: () => Date): PendingSpendRequest;
28
+ /** Pending requests, newest first. */
29
+ export declare function listPendingSpendRequests(env?: NodeJS.ProcessEnv, now?: () => Date): PendingSpendRequest[];
30
+ /**
31
+ * Issue a single-use approval for one pending request. Called only from the
32
+ * interactive operator prompt; removes the request from the pending list.
33
+ */
34
+ export declare function issueSpendApproval(digest: string, env?: NodeJS.ProcessEnv, now?: () => Date): SpendApproval;
35
+ /** The unexpired approval for this exact request, if any (does not consume it). */
36
+ export declare function findSpendApproval(tool: string, args: Obj, env?: NodeJS.ProcessEnv, now?: () => Date): SpendApproval | null;
37
+ /** Use up the approval for this exact request. Returns it, or null when none is left. */
38
+ export declare function consumeSpendApproval(tool: string, args: Obj, env?: NodeJS.ProcessEnv, now?: () => Date): SpendApproval | null;
39
+ /**
40
+ * Put back an approval whose call failed before it changed anything (for
41
+ * example a request the queue rejected), so the operator's approval is not
42
+ * lost. It keeps its original expiry.
43
+ */
44
+ export declare function restoreSpendApproval(approval: SpendApproval, env?: NodeJS.ProcessEnv, now?: () => Date): void;
45
+ export {};
@@ -0,0 +1,203 @@
1
+ /**
2
+ * One-time operator approvals for spend-adjacent benchmark requests
3
+ * (`~/.understudy/spend-approvals.json`).
4
+ *
5
+ * The trust posture (src/config/trust.ts) is the standing consent: at
6
+ * `bounded_experiments`+ spend-adjacent requests proceed. Below it, the
7
+ * operator can still approve ONE specific request without raising the
8
+ * posture: the guard records the blocked request as pending, the operator
9
+ * answers an interactive prompt (`orchestra trust approve-spend`, terminal
10
+ * only), and that issues a single-use, short-lived approval bound to the
11
+ * digest of that exact request. The guard consumes the approval when the
12
+ * identical request is made again. Tool arguments never carry consent.
13
+ */
14
+ import { createHash, randomBytes } from "node:crypto";
15
+ import { closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
16
+ import { dirname, join } from "node:path";
17
+ import { globalConfigDir } from "./paths.js";
18
+ export const SPEND_APPROVALS_SCHEMA = "understudy.spend_approvals.v1";
19
+ /** How long an issued approval stays usable. */
20
+ export const SPEND_APPROVAL_TTL_MS = 15 * 60 * 1000;
21
+ /** Pending requests older than this are dropped. */
22
+ const PENDING_TTL_MS = 24 * 60 * 60 * 1000;
23
+ const MAX_PENDING = 20;
24
+ /** How long to wait for the file lock, and when a left-over lock counts as stale. */
25
+ const LOCK_WAIT_MS = 5_000;
26
+ const LOCK_STALE_MS = 30_000;
27
+ const asObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
28
+ /** `UNDERSTUDY_SPEND_APPROVALS_FILE` overrides for tests/sandboxes; default is the global config dir. */
29
+ export function spendApprovalsPath(env = process.env) {
30
+ const override = env.UNDERSTUDY_SPEND_APPROVALS_FILE?.trim();
31
+ return override ? override : join(globalConfigDir(), "spend-approvals.json");
32
+ }
33
+ function canonical(value) {
34
+ if (Array.isArray(value))
35
+ return value.map(canonical);
36
+ if (value !== null && typeof value === "object") {
37
+ return Object.fromEntries(Object.keys(value)
38
+ .sort()
39
+ .map((key) => [key, canonical(value[key])]));
40
+ }
41
+ return value;
42
+ }
43
+ /** Stable digest of one request: tool name plus arguments with sorted keys. */
44
+ export function spendRequestDigest(tool, args) {
45
+ return createHash("sha256").update(JSON.stringify(canonical({ tool, args }))).digest("hex");
46
+ }
47
+ function readFile(env, now) {
48
+ let parsed = {};
49
+ try {
50
+ parsed = asObject(JSON.parse(readFileSync(spendApprovalsPath(env), "utf8")));
51
+ }
52
+ catch {
53
+ /* missing or unreadable: no pending requests, no approvals */
54
+ }
55
+ if (parsed.schema_version !== SPEND_APPROVALS_SCHEMA)
56
+ parsed = {};
57
+ const t = now.getTime();
58
+ const pending = (Array.isArray(parsed.pending) ? parsed.pending : [])
59
+ .map(asObject)
60
+ .filter((p) => typeof p.digest === "string" &&
61
+ typeof p.tool === "string" &&
62
+ typeof p.summary === "string" &&
63
+ typeof p.requested_at === "string" &&
64
+ t - Date.parse(p.requested_at) < PENDING_TTL_MS);
65
+ const approvals = (Array.isArray(parsed.approvals) ? parsed.approvals : [])
66
+ .map(asObject)
67
+ .filter((a) => typeof a.token === "string" &&
68
+ typeof a.digest === "string" &&
69
+ typeof a.tool === "string" &&
70
+ typeof a.issued_at === "string" &&
71
+ typeof a.expires_at === "string" &&
72
+ Date.parse(a.expires_at) > t);
73
+ return { schema_version: SPEND_APPROVALS_SCHEMA, pending, approvals };
74
+ }
75
+ function sleepSync(ms) {
76
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
77
+ }
78
+ /**
79
+ * Run one read-modify-write of the approvals file under an exclusive lock
80
+ * file, so concurrent processes cannot both use one approval or undo each
81
+ * other's writes.
82
+ */
83
+ function withLock(env, fn) {
84
+ const lock = `${spendApprovalsPath(env)}.lock`;
85
+ mkdirSync(dirname(lock), { recursive: true });
86
+ const deadline = Date.now() + LOCK_WAIT_MS;
87
+ for (;;) {
88
+ try {
89
+ closeSync(openSync(lock, "wx", 0o600));
90
+ break;
91
+ }
92
+ catch (error) {
93
+ if (error.code !== "EEXIST")
94
+ throw error;
95
+ try {
96
+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS)
97
+ rmSync(lock, { force: true });
98
+ }
99
+ catch {
100
+ /* lock released meanwhile */
101
+ }
102
+ if (Date.now() > deadline)
103
+ throw new Error(`spend approvals file is locked (${lock})`);
104
+ sleepSync(25);
105
+ }
106
+ }
107
+ try {
108
+ return fn();
109
+ }
110
+ finally {
111
+ rmSync(lock, { force: true });
112
+ }
113
+ }
114
+ function writeFile(file, env) {
115
+ const path = spendApprovalsPath(env);
116
+ mkdirSync(dirname(path), { recursive: true });
117
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
118
+ writeFileSync(tmp, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o600 });
119
+ renameSync(tmp, path);
120
+ }
121
+ /**
122
+ * Record a blocked request so the operator can review it with
123
+ * `orchestra trust approve-spend`. Newest first; a repeat of the same
124
+ * request moves to the front instead of duplicating.
125
+ */
126
+ export function recordPendingSpendRequest(tool, args, env = process.env, now = () => new Date()) {
127
+ const at = now();
128
+ const digest = spendRequestDigest(tool, args);
129
+ // The full request, never truncated: the operator approves what they see.
130
+ const entry = {
131
+ digest,
132
+ tool,
133
+ summary: `${tool} ${JSON.stringify(canonical(args))}`,
134
+ requested_at: at.toISOString(),
135
+ };
136
+ return withLock(env, () => {
137
+ const file = readFile(env, at);
138
+ file.pending = [entry, ...file.pending.filter((p) => p.digest !== digest)].slice(0, MAX_PENDING);
139
+ writeFile(file, env);
140
+ return entry;
141
+ });
142
+ }
143
+ /** Pending requests, newest first. */
144
+ export function listPendingSpendRequests(env = process.env, now = () => new Date()) {
145
+ return readFile(env, now()).pending;
146
+ }
147
+ /**
148
+ * Issue a single-use approval for one pending request. Called only from the
149
+ * interactive operator prompt; removes the request from the pending list.
150
+ */
151
+ export function issueSpendApproval(digest, env = process.env, now = () => new Date()) {
152
+ const at = now();
153
+ return withLock(env, () => {
154
+ const file = readFile(env, at);
155
+ const pending = file.pending.find((p) => p.digest === digest);
156
+ if (!pending)
157
+ throw new Error("no pending spend request with that id");
158
+ const approval = {
159
+ token: randomBytes(16).toString("hex"),
160
+ digest,
161
+ tool: pending.tool,
162
+ issued_at: at.toISOString(),
163
+ expires_at: new Date(at.getTime() + SPEND_APPROVAL_TTL_MS).toISOString(),
164
+ };
165
+ file.pending = file.pending.filter((p) => p.digest !== digest);
166
+ file.approvals = [...file.approvals.filter((a) => a.digest !== digest), approval];
167
+ writeFile(file, env);
168
+ return approval;
169
+ });
170
+ }
171
+ /** The unexpired approval for this exact request, if any (does not consume it). */
172
+ export function findSpendApproval(tool, args, env = process.env, now = () => new Date()) {
173
+ const digest = spendRequestDigest(tool, args);
174
+ return readFile(env, now()).approvals.find((a) => a.digest === digest && a.tool === tool) ?? null;
175
+ }
176
+ /** Use up the approval for this exact request. Returns it, or null when none is left. */
177
+ export function consumeSpendApproval(tool, args, env = process.env, now = () => new Date()) {
178
+ const digest = spendRequestDigest(tool, args);
179
+ return withLock(env, () => {
180
+ const file = readFile(env, now());
181
+ const approval = file.approvals.find((a) => a.digest === digest && a.tool === tool) ?? null;
182
+ if (!approval)
183
+ return null;
184
+ file.approvals = file.approvals.filter((a) => a.token !== approval.token);
185
+ writeFile(file, env);
186
+ return approval;
187
+ });
188
+ }
189
+ /**
190
+ * Put back an approval whose call failed before it changed anything (for
191
+ * example a request the queue rejected), so the operator's approval is not
192
+ * lost. It keeps its original expiry.
193
+ */
194
+ export function restoreSpendApproval(approval, env = process.env, now = () => new Date()) {
195
+ withLock(env, () => {
196
+ const file = readFile(env, now());
197
+ if (Date.parse(approval.expires_at) <= now().getTime())
198
+ return;
199
+ file.approvals = [...file.approvals.filter((a) => a.token !== approval.token), approval];
200
+ writeFile(file, env);
201
+ });
202
+ }
203
+ //# sourceMappingURL=spend-approval.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spend-approval.js","sourceRoot":"","sources":["../../src/config/spend-approval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EACL,SAAS,EACT,SAAS,EACT,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,MAAM,EACN,QAAQ,EACR,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,MAAM,CAAC,MAAM,sBAAsB,GAAG,+BAA+B,CAAC;AAEtE,gDAAgD;AAChD,MAAM,CAAC,MAAM,qBAAqB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACpD,oDAAoD;AACpD,MAAM,cAAc,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC3C,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,qFAAqF;AACrF,MAAM,YAAY,GAAG,KAAK,CAAC;AAC3B,MAAM,aAAa,GAAG,MAAM,CAAC;AAwB7B,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAO,EAAE,CACvC,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAA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ZodObject<{
196
196
  schema_version: z.ZodLiteral<"understudy.eval-draft-metric.v1">;
197
197
  name: z.ZodString;
198
198
  description: z.ZodString;
199
+ approved: z.ZodLiteral<false>;
199
200
  validator: z.ZodObject<{
200
201
  kind: z.ZodLiteral<"local_verifier">;
201
202
  entrypoint: z.ZodString;
202
203
  }, z.core.$strict>;
203
204
  pass_threshold: z.ZodNumber;
204
205
  failure_taxonomy: z.ZodArray<z.ZodString>;
205
- approved: z.ZodLiteral<false>;
206
206
  }, z.core.$strict>;
207
207
  export declare const EvalHarnessSchema: z.ZodObject<{
208
208
  schema_version: z.ZodLiteral<"understudy.eval-harness.v1">;
@@ -1,6 +1,7 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "@earendil-works/pi-ai";
3
3
  import { type TrustPosture } from "../../config/trust.js";
4
+ import { type SpendApproval } from "../../config/spend-approval.js";
4
5
  /**
5
6
  * Explicit allowlist of MCP-shared operator tools exposed in the embedded
6
7
  * chat. Deliberately smaller than the full MCP surface: rollout-forensics
@@ -14,10 +15,15 @@ export declare const PI_BENCHMARK_RIGOR_TOOL: "read_rigor_report";
14
15
  export declare const PI_BENCHMARK_TOOL_NAMES: readonly string[];
15
16
  export declare function benchmarkHubRoots(): string;
16
17
  export type BenchmarkGuardDecision =
17
- /** `notice`, when present, is the visible one-line posture notice that MUST surface with the result. */
18
+ /**
19
+ * `notice`, when present, is the visible one-line notice that MUST surface
20
+ * with the result. `approved` means a one-time operator approval matched
21
+ * this request; the execute path consumes it.
22
+ */
18
23
  {
19
24
  decision: "allow";
20
25
  notice?: string;
26
+ approved?: boolean;
21
27
  } | {
22
28
  decision: "block";
23
29
  rule_id: string;
@@ -28,7 +34,7 @@ type Obj = Record<string, unknown>;
28
34
  /**
29
35
  * A trivial queue_run — exactly one candidate arm, one rollout per task, an
30
36
  * explicit task list, and no incumbent arm — is a cheap targeted probe and is
31
- * allowed without confirmation. Anything wider is spend-adjacent once an
37
+ * allowed without approval. Anything wider is spend-adjacent once an
32
38
  * executor picks it up.
33
39
  */
34
40
  export declare function queueRunIsTrivial(args: Obj): boolean;
@@ -43,8 +49,14 @@ export declare function classifyBenchmarkToolCall(toolName: string, input: unkno
43
49
  export declare function benchmarkGuardBlockMessage(decision: Exclude<BenchmarkGuardDecision, {
44
50
  decision: "allow";
45
51
  }>): string;
52
+ /**
53
+ * Enforce the guard for one call (the execute path). A blocked request is
54
+ * recorded as pending; a call allowed by a one-time operator approval uses
55
+ * that approval up and returns it, so a failed call can put it back.
56
+ */
46
57
  export declare function enforceBenchmarkToolCall(toolName: string, input: unknown, posture?: TrustPosture): {
47
58
  notice?: string;
59
+ approval?: SpendApproval;
48
60
  };
49
61
  export declare function benchmarkToolDefinitions(): (import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TUnsafe<unknown>, unknown, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>)[];
50
62
  /**
@@ -18,9 +18,11 @@
18
18
  // ONE-TIME trust posture (~/.understudy/trust.json, src/config/trust.ts)
19
19
  // instead of demanding a per-call dialog: at `bounded_experiments`+ they
20
20
  // proceed with a visible one-line notice (arm count, rough cost estimate);
21
- // below that they return the single-action guidance to raise the posture.
22
- // `confirm: true` (set only after explicit user consent in chat) remains a
23
- // per-call escape hatch that works at any posture.
21
+ // below that they are blocked with the posture change that would allow them.
22
+ // Below the posture, the only other way through is a one-time operator
23
+ // approval for that exact request (src/config/spend-approval.ts), issued by
24
+ // an interactive terminal prompt the operator answers. Tool arguments never
25
+ // carry consent.
24
26
  //
25
27
  // These tools are Pi-only by design: the Vercel runtime twin builds its tool
26
28
  // set purely from the request's tool definitions and has no extension
@@ -35,11 +37,12 @@
35
37
  import { join } from "node:path";
36
38
  import { defineTool } from "@earendil-works/pi-coding-agent";
37
39
  import { Type } from "@earendil-works/pi-ai";
38
- import { BENCHMARKS_TOOLS, callBenchmarksTool } from "../../benchmarks-mcp.js";
40
+ import { BENCHMARKS_TOOLS, OPERATOR_APPROVAL_NOTICE, callBenchmarksTool, dispatchWithApproval, spendGuardArgs, spendRequestIdentity, } from "../../benchmarks-mcp.js";
39
41
  import { getEntry } from "../../benchmark-hub-core.js";
40
42
  import { deriveRigorReport } from "../../rigor-report.js";
41
43
  import { COST_PER_MTOKEN } from "../../trace-author.js";
42
44
  import { raiseTrustHint, readTrustPosture, trustAtLeast } from "../../config/trust.js";
45
+ import { consumeSpendApproval, findSpendApproval, recordPendingSpendRequest, } from "../../config/spend-approval.js";
43
46
  import { globalConfigDir } from "../../config/paths.js";
44
47
  /**
45
48
  * Explicit allowlist of MCP-shared operator tools exposed in the embedded
@@ -83,7 +86,7 @@ function asObject(value) {
83
86
  /**
84
87
  * A trivial queue_run — exactly one candidate arm, one rollout per task, an
85
88
  * explicit task list, and no incumbent arm — is a cheap targeted probe and is
86
- * allowed without confirmation. Anything wider is spend-adjacent once an
89
+ * allowed without approval. Anything wider is spend-adjacent once an
87
90
  * executor picks it up.
88
91
  */
89
92
  export function queueRunIsTrivial(args) {
@@ -148,77 +151,94 @@ export function queueRunSpendNotice(args, posture) {
148
151
  `${totalRollouts === null ? "" : ` = ${totalRollouts} rollout(s)`}; ${est}. ` +
149
152
  `Recorded, reversible: cancel via run_status/cancel; lower autonomy any time with \`orchestra trust set local_sandbox\`.`);
150
153
  }
154
+ const SPEND_BLOCKS = {
155
+ queue_run: {
156
+ decision: "block",
157
+ rule_id: "benchmark.queue-run-below-posture",
158
+ reason: "This run request is spend-adjacent (multiple model arms, an incumbent arm, repeated rollouts, or an implicit all-task run) and an executor will spend money or compute the moment it picks the queued file up.",
159
+ severity: "high",
160
+ },
161
+ update_experiment: {
162
+ decision: "block",
163
+ rule_id: "benchmark.experiment-approval-below-posture",
164
+ reason: "This experiment patch changes approval, status, or verdict state that downstream tooling treats as cleared spend gates.",
165
+ severity: "high",
166
+ },
167
+ };
168
+ function spendGateFor(toolName, args) {
169
+ if (toolName === "queue_run" && !queueRunIsTrivial(args))
170
+ return "queue_run";
171
+ if (toolName === "update_experiment" && experimentPatchTouchesApprovals(asObject(args.patch))) {
172
+ return "update_experiment";
173
+ }
174
+ return null;
175
+ }
151
176
  export function classifyBenchmarkToolCall(toolName, input, posture = readTrustPosture()) {
152
177
  if (!PI_BENCHMARK_TOOL_NAMES.includes(toolName))
153
178
  return { decision: "allow" };
154
- const args = asObject(input);
155
- if (args.confirm === true)
179
+ const args = spendGuardArgs(toolName, input);
180
+ const gate = spendGateFor(toolName, args);
181
+ if (gate === null)
156
182
  return { decision: "allow" };
157
- const postureAllows = trustAtLeast(posture, "bounded_experiments");
158
- if (toolName === "queue_run" && !queueRunIsTrivial(args)) {
159
- if (postureAllows)
160
- return { decision: "allow", notice: queueRunSpendNotice(args, posture) };
183
+ if (trustAtLeast(posture, "bounded_experiments")) {
161
184
  return {
162
- decision: "block",
163
- rule_id: "benchmark.queue-run-below-posture",
164
- reason: "This run request is spend-adjacent (multiple model arms, an incumbent arm, repeated rollouts, or an implicit all-task run) and an executor will spend money or compute the moment it picks the queued file up.",
165
- severity: "high",
185
+ decision: "allow",
186
+ notice: gate === "queue_run"
187
+ ? queueRunSpendNotice(args, posture)
188
+ : `Trust posture ${posture.level}: updating experiment approval/status/verdict state (spend-gate-adjacent). Recorded in experiments.jsonl (append-only, reversible with a later line).`,
166
189
  };
167
190
  }
168
- if (toolName === "update_experiment" && experimentPatchTouchesApprovals(asObject(args.patch))) {
169
- if (postureAllows) {
170
- return {
171
- decision: "allow",
172
- notice: `Trust posture ${posture.level}: updating experiment approval/status/verdict state (spend-gate-adjacent). Recorded in experiments.jsonl (append-only, reversible with a later line).`,
173
- };
174
- }
175
- return {
176
- decision: "block",
177
- rule_id: "benchmark.experiment-approval-below-posture",
178
- reason: "This experiment patch changes approval, status, or verdict state that downstream tooling treats as cleared spend gates.",
179
- severity: "high",
180
- };
191
+ if (findSpendApproval(toolName, spendRequestIdentity(toolName, input))) {
192
+ return { decision: "allow", notice: OPERATOR_APPROVAL_NOTICE, approved: true };
181
193
  }
182
- return { decision: "allow" };
194
+ return SPEND_BLOCKS[gate];
183
195
  }
184
196
  export function benchmarkGuardBlockMessage(decision) {
185
197
  return (`Blocked by Orchestra benchmark guard [${decision.rule_id}]: ${decision.reason} ` +
186
- `The current trust posture is below "bounded_experiments". ONE action fixes this for every future call ` +
187
- `(no per-call dialogs): have the user run \`${raiseTrustHint("bounded_experiments")}\` once — visible and ` +
188
- `reversible. Alternatively, for this single call only, retry with confirm: true after the user explicitly consented in chat.`);
198
+ `This needs the trust posture at "bounded_experiments" or higher; the operator can raise it with ` +
199
+ `\`${raiseTrustHint("bounded_experiments")}\` (visible and reversible).`);
200
+ }
201
+ /** Record a blocked request as pending so the operator can review it. */
202
+ function recordBlocked(toolName, input) {
203
+ recordPendingSpendRequest(toolName, spendRequestIdentity(toolName, input));
189
204
  }
205
+ /**
206
+ * Enforce the guard for one call (the execute path). A blocked request is
207
+ * recorded as pending; a call allowed by a one-time operator approval uses
208
+ * that approval up and returns it, so a failed call can put it back.
209
+ */
190
210
  export function enforceBenchmarkToolCall(toolName, input, posture) {
191
211
  const decision = classifyBenchmarkToolCall(toolName, input, posture);
192
212
  if (decision.decision === "block") {
213
+ recordBlocked(toolName, input);
193
214
  throw new Error(benchmarkGuardBlockMessage(decision));
194
215
  }
216
+ if (decision.approved) {
217
+ const approval = consumeSpendApproval(toolName, spendRequestIdentity(toolName, input));
218
+ if (!approval) {
219
+ recordBlocked(toolName, input);
220
+ const gate = spendGateFor(toolName, spendGuardArgs(toolName, input));
221
+ throw new Error(benchmarkGuardBlockMessage(SPEND_BLOCKS[gate ?? "queue_run"]));
222
+ }
223
+ return { notice: decision.notice, approval };
224
+ }
195
225
  return decision.notice ? { notice: decision.notice } : {};
196
226
  }
197
227
  /* ---------------- tool definitions ---------------- */
198
- const CONFIRM_PROPERTY = {
199
- confirm: {
200
- type: "boolean",
201
- description: "Per-call escape hatch for spend-adjacent shapes when the trust posture is below bounded_experiments. Set only after the user explicitly consented in this conversation.",
202
- },
203
- };
204
- /** Tools whose schema gains the guard's `confirm` escape hatch. */
205
- const CONFIRMABLE_TOOLS = new Set(["queue_run", "update_experiment"]);
228
+ /** Tools whose description carries the posture caveat. */
229
+ const SPEND_GATED_TOOLS = new Set(["queue_run", "update_experiment"]);
206
230
  function sharedToolSchema(name) {
207
231
  const source = BENCHMARKS_TOOLS.find((tool) => tool.name === name);
208
232
  if (!source)
209
233
  throw new Error(`benchmarks MCP no longer exposes tool ${name}`);
210
- const schema = JSON.parse(JSON.stringify(source.inputSchema));
211
- if (CONFIRMABLE_TOOLS.has(name)) {
212
- schema.properties = { ...(schema.properties ?? {}), ...CONFIRM_PROPERTY };
213
- }
214
- return schema;
234
+ return JSON.parse(JSON.stringify(source.inputSchema));
215
235
  }
216
236
  function sharedToolDescription(name) {
217
237
  const source = BENCHMARKS_TOOLS.find((tool) => tool.name === name);
218
238
  if (!source)
219
239
  throw new Error(`benchmarks MCP no longer exposes tool ${name}`);
220
- return CONFIRMABLE_TOOLS.has(name)
221
- ? `${source.description} Spend-adjacent shapes consult the one-time trust posture (~/.understudy/trust.json): at bounded_experiments+ they proceed with a visible spend notice; below that they are blocked with guidance to raise the posture once (or pass confirm: true after explicit user consent).`
240
+ return SPEND_GATED_TOOLS.has(name)
241
+ ? `${source.description} Spend-adjacent shapes consult the one-time trust posture (~/.understudy/trust.json): at bounded_experiments+ they proceed with a visible spend notice; below that they are blocked unless the operator approves the request.`
222
242
  : source.description;
223
243
  }
224
244
  function toolResult(value) {
@@ -249,11 +269,8 @@ export function benchmarkToolDefinitions() {
249
269
  description: sharedToolDescription(name),
250
270
  parameters: Type.Unsafe(sharedToolSchema(name)),
251
271
  async execute(_toolCallId, parameters) {
252
- const { notice } = enforceBenchmarkToolCall(name, parameters);
253
- // Strip the pi-layer confirm flag before delegating: the shared MCP
254
- // dispatcher's argument surface stays byte-identical to the hub API.
255
- const { confirm: _confirm, ...args } = asObject(parameters);
256
- const result = toolResult(callBenchmarksTool(name, args));
272
+ const { notice, approval } = enforceBenchmarkToolCall(name, parameters);
273
+ const result = toolResult(dispatchWithApproval(approval, () => callBenchmarksTool(name, asObject(parameters))));
257
274
  // Posture notices are VISIBLE by contract: the one-line notice rides
258
275
  // ahead of the payload so the model must surface it to the user.
259
276
  return notice ? { ...result, content: [{ type: "text", text: notice }, ...result.content] } : result;
@@ -284,8 +301,10 @@ export function piBenchmarkLabExtension(pi) {
284
301
  pi.registerTool(tool);
285
302
  }
286
303
  pi.on("tool_call", (event) => {
304
+ // Peek only: a matching operator approval is consumed by the execute path.
287
305
  const decision = classifyBenchmarkToolCall(event.toolName, event.input);
288
306
  if (decision.decision === "block") {
307
+ recordBlocked(event.toolName, event.input);
289
308
  return { block: true, reason: benchmarkGuardBlockMessage(decision) };
290
309
  }
291
310
  });