rebut-mcp 0.3.2 → 0.4.0

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.
package/lib/cli.mjs CHANGED
@@ -1,21 +1,65 @@
1
1
  // src/cli.ts
2
2
  import { join as join6, resolve as resolve5 } from "node:path";
3
3
  import { parseArgs } from "node:util";
4
- import { readFile as readFile4 } from "node:fs/promises";
4
+ import { readFile as readFile3 } from "node:fs/promises";
5
+
6
+ // src/budget-cycle.ts
7
+ function boundary(now, day, monthOffset = 0) {
8
+ return new Date(
9
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + monthOffset, day)
10
+ ).toISOString();
11
+ }
12
+ function monthlyBudgetPeriod(now, cycle) {
13
+ const at = now.toISOString();
14
+ const day = cycle?.start_day ?? 1;
15
+ if (cycle?.bridge_month && at < cycle.effective_at) {
16
+ if (at.slice(0, 7) < cycle.bridge_month)
17
+ return monthlyBudgetPeriod(now, null);
18
+ return {
19
+ key: cycle.bridge_month,
20
+ start: cycle.bridge_month + "-01T00:00:00.000Z",
21
+ end: cycle.effective_at
22
+ };
23
+ }
24
+ const offset = at < boundary(now, day) ? -1 : 0;
25
+ const start = boundary(now, day, offset);
26
+ return {
27
+ key: start.slice(0, day === 1 ? 7 : 10),
28
+ start,
29
+ end: boundary(now, day, offset + 1)
30
+ };
31
+ }
32
+ function validMonthlyStartDay(day) {
33
+ return typeof day === "number" && Number.isInteger(day) && day >= 1 && day <= 28;
34
+ }
35
+ function monthlyTransition(now, day) {
36
+ return {
37
+ currentMonth: now.toISOString().slice(0, 7),
38
+ nextCalendarBoundary: boundary(now, 1, 1),
39
+ effectiveForExistingLedger: boundary(now, day, 1),
40
+ effectiveForEmptyLedger: monthlyBudgetPeriod(now, {
41
+ start_day: day,
42
+ effective_at: "",
43
+ bridge_month: null
44
+ }).start
45
+ };
46
+ }
47
+
48
+ // src/cli.ts
5
49
  import { realpathSync } from "node:fs";
6
50
  import { fileURLToPath } from "node:url";
7
51
 
8
52
  // src/client/settings.ts
53
+ import { constants } from "node:fs";
9
54
  import { homedir } from "node:os";
10
55
  import { join, dirname, resolve } from "node:path";
11
56
  import {
12
57
  mkdir,
13
- readFile,
14
- writeFile,
15
58
  rename,
16
59
  unlink,
17
60
  lstat,
18
- chmod
61
+ open,
62
+ realpath
19
63
  } from "node:fs/promises";
20
64
  import { randomUUID } from "node:crypto";
21
65
  import { z as z2 } from "zod";
@@ -134,7 +178,7 @@ async function connectRemote(options2) {
134
178
  reconnectionDelayGrowFactor: 1
135
179
  }
136
180
  });
137
- const client = new Client({ name: "rebut-mcp", version: "0.3.2" });
181
+ const client = new Client({ name: "rebut-mcp", version: "0.4.0" });
138
182
  const close = client.close.bind(client);
139
183
  let closing;
140
184
  client.close = () => closing ??= (async () => {
@@ -159,6 +203,7 @@ async function connectRemote(options2) {
159
203
  }
160
204
 
161
205
  // src/client/settings.ts
206
+ var ProfileId = z2.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/);
162
207
  var SettingsSchema = z2.object({
163
208
  schemaVersion: z2.literal(1),
164
209
  mode: z2.enum(["local", "worker"]).optional(),
@@ -169,7 +214,11 @@ var SettingsSchema = z2.object({
169
214
  vaultwardenApiKeyItem: z2.string().min(1).max(200).refine((s) => !/[\x00-\x1f\x7f]/.test(s)).optional(),
170
215
  defaultModel: z2.string().regex(/^[a-zA-Z0-9._:-]{1,100}$/).optional(),
171
216
  defaultReasoning: z2.string().regex(/^[a-z][a-z0-9_-]{0,31}$/).optional(),
172
- defaultProfile: z2.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/).optional(),
217
+ defaultProfile: ProfileId.optional(),
218
+ clientProfiles: z2.strictObject({
219
+ codex: ProfileId.optional(),
220
+ claude: ProfileId.optional()
221
+ }).optional(),
173
222
  vaultwardenAdminItem: z2.string().min(1).max(200).refine((s) => !/[\x00-\x1f\x7f]/.test(s)).default("Rebut \u2014 MCP Admin Token"),
174
223
  endpoint: z2.string().max(2048).optional(),
175
224
  secretStore: z2.enum(["keychain", "vaultwarden", "env"]),
@@ -181,16 +230,170 @@ function settingsPath() {
181
230
  "config.json"
182
231
  );
183
232
  }
233
+ function unsafeSettings() {
234
+ throw new Error("SETTINGS_UNSAFE");
235
+ }
236
+ function currentUid() {
237
+ const getuid = process.getuid;
238
+ if (process.platform === "win32" || !getuid) unsafeSettings();
239
+ return getuid();
240
+ }
241
+ function sameIdentity(left, right) {
242
+ return left.dev === right.dev && left.ino === right.ino;
243
+ }
244
+ function pathChain(path2) {
245
+ const chain = [];
246
+ for (let current = resolve(path2); ; current = dirname(current)) {
247
+ chain.push(current);
248
+ const parent = dirname(current);
249
+ if (parent === current) break;
250
+ }
251
+ return chain.reverse();
252
+ }
253
+ function checkDirectoryEntry(stat, options2) {
254
+ const uid = currentUid();
255
+ if (stat.isSymbolicLink()) {
256
+ if (!options2.allowTrustedLink || stat.uid !== 0) unsafeSettings();
257
+ return;
258
+ }
259
+ if (!stat.isDirectory()) unsafeSettings();
260
+ if (options2.requireCurrentOwner && stat.uid !== uid || !options2.requireCurrentOwner && stat.uid !== uid && stat.uid !== 0)
261
+ unsafeSettings();
262
+ if ((stat.mode & 18) !== 0 && !(!options2.requireCurrentOwner && stat.uid === 0 && (stat.mode & 512) !== 0))
263
+ unsafeSettings();
264
+ }
265
+ async function snapshotDirectoryChain(path2, allowTrustedLinks, requireDirectoryOwner = true) {
266
+ const paths = pathChain(path2);
267
+ return Promise.all(
268
+ paths.map(async (entry, index) => {
269
+ const requireCurrentOwner = requireDirectoryOwner && index === paths.length - 1;
270
+ const options2 = {
271
+ allowTrustedLink: allowTrustedLinks && !requireCurrentOwner,
272
+ requireCurrentOwner
273
+ };
274
+ const stat = await lstat(entry);
275
+ checkDirectoryEntry(stat, options2);
276
+ return { path: entry, stat, ...options2 };
277
+ })
278
+ );
279
+ }
280
+ async function verifyDirectory(state) {
281
+ for (const entry of state.entries) {
282
+ const current2 = await lstat(entry.path);
283
+ checkDirectoryEntry(current2, entry);
284
+ if (!sameIdentity(current2, entry.stat)) unsafeSettings();
285
+ }
286
+ const current = await state.handle.stat();
287
+ const directory = state.entries[state.entries.length - 1];
288
+ checkDirectoryEntry(current, {
289
+ allowTrustedLink: false,
290
+ requireCurrentOwner: true
291
+ });
292
+ if (!sameIdentity(current, directory.stat)) unsafeSettings();
293
+ }
294
+ async function createSettingsDirectory(path2) {
295
+ let ancestor = path2;
296
+ for (; ; ) {
297
+ try {
298
+ await lstat(ancestor);
299
+ break;
300
+ } catch (error) {
301
+ if (error.code !== "ENOENT") unsafeSettings();
302
+ ancestor = dirname(ancestor);
303
+ }
304
+ }
305
+ if (ancestor === path2) return;
306
+ await snapshotDirectoryChain(ancestor, true, false);
307
+ await snapshotDirectoryChain(await realpath(ancestor), false, false);
308
+ await mkdir(path2, { recursive: true, mode: 448 });
309
+ }
310
+ async function inspectDirectory(path2) {
311
+ let handle;
312
+ try {
313
+ const lexical = await snapshotDirectoryChain(path2, true);
314
+ const canonicalPath = await realpath(path2);
315
+ const canonical = await snapshotDirectoryChain(canonicalPath, false);
316
+ const lexicalDirectory = lexical[lexical.length - 1].stat;
317
+ const canonicalDirectory = canonical[canonical.length - 1].stat;
318
+ if (!sameIdentity(lexicalDirectory, canonicalDirectory)) unsafeSettings();
319
+ handle = await open(
320
+ path2,
321
+ constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW
322
+ );
323
+ const state = { handle, entries: [...lexical, ...canonical] };
324
+ await verifyDirectory(state);
325
+ return state;
326
+ } catch (error) {
327
+ await handle?.close().catch(() => {
328
+ });
329
+ if (error instanceof Error && error.message === "SETTINGS_UNSAFE")
330
+ throw error;
331
+ return unsafeSettings();
332
+ }
333
+ }
334
+ function checkSettingsFile(stat) {
335
+ const uid = currentUid();
336
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.uid !== uid || (stat.mode & 63) !== 0)
337
+ unsafeSettings();
338
+ }
339
+ async function openSettingsFile(path2, directory, allowMissing = false) {
340
+ let handle;
341
+ try {
342
+ let observed;
343
+ try {
344
+ observed = await lstat(path2);
345
+ } catch (error) {
346
+ if (allowMissing && error.code === "ENOENT")
347
+ return void 0;
348
+ throw error;
349
+ }
350
+ checkSettingsFile(observed);
351
+ handle = await open(path2, constants.O_RDONLY | constants.O_NOFOLLOW);
352
+ const current = await handle.stat();
353
+ checkSettingsFile(current);
354
+ if (!sameIdentity(observed, current)) unsafeSettings();
355
+ await verifyDirectory(directory);
356
+ return { handle, stat: current };
357
+ } catch (error) {
358
+ await handle?.close().catch(() => {
359
+ });
360
+ if (error instanceof Error && error.message === "SETTINGS_UNSAFE")
361
+ throw error;
362
+ return unsafeSettings();
363
+ }
364
+ }
365
+ async function readSettingsSource(path2) {
366
+ try {
367
+ await lstat(path2);
368
+ } catch (error) {
369
+ if (error.code === "ENOENT") return void 0;
370
+ unsafeSettings();
371
+ }
372
+ let directory;
373
+ let file;
374
+ try {
375
+ directory = await inspectDirectory(dirname(path2));
376
+ const opened = await openSettingsFile(path2, directory);
377
+ if (!opened) unsafeSettings();
378
+ file = opened.handle;
379
+ const source = await file.readFile("utf8");
380
+ const current = await file.stat();
381
+ checkSettingsFile(current);
382
+ if (!sameIdentity(opened.stat, current)) unsafeSettings();
383
+ await verifyDirectory(directory);
384
+ return source;
385
+ } finally {
386
+ await file?.close().catch(() => {
387
+ });
388
+ await directory?.handle.close().catch(() => {
389
+ });
390
+ }
391
+ }
184
392
  async function readSettings() {
185
393
  try {
186
394
  const path2 = settingsPath();
187
- const stat = await lstat(path2);
188
- if (!stat.isFile() || stat.isSymbolicLink()) throw Error();
189
- const data = SettingsSchema.parse(JSON.parse(await readFile(path2, "utf8")));
190
- if (data.endpoint) validateEndpoint(data.endpoint);
191
- return data;
192
- } catch (error) {
193
- if (error.code === "ENOENT")
395
+ const source = await readSettingsSource(path2);
396
+ if (source === void 0)
194
397
  return {
195
398
  schemaVersion: 1,
196
399
  mode: "local",
@@ -198,6 +401,12 @@ async function readSettings() {
198
401
  vaultwardenItem: "Rebut \u2014 MCP Access Token",
199
402
  vaultwardenAdminItem: "Rebut \u2014 MCP Admin Token"
200
403
  };
404
+ const data = SettingsSchema.parse(JSON.parse(source));
405
+ if (data.endpoint) validateEndpoint(data.endpoint);
406
+ return data;
407
+ } catch (error) {
408
+ if (error instanceof Error && error.message === "SETTINGS_UNSAFE")
409
+ throw error;
201
410
  throw new Error("SETTINGS_INVALID");
202
411
  }
203
412
  }
@@ -205,24 +414,49 @@ async function writeSettings(value) {
205
414
  const checked = SettingsSchema.parse(value);
206
415
  if (checked.endpoint) validateEndpoint(checked.endpoint);
207
416
  const path2 = settingsPath(), dir = dirname(path2);
208
- await mkdir(dir, { recursive: true, mode: 448 });
209
- try {
210
- const stat = await lstat(path2);
211
- if (!stat.isFile() || stat.isSymbolicLink())
212
- throw new Error("SETTINGS_UNSAFE");
213
- } catch (error) {
214
- if (error.code !== "ENOENT") throw error;
215
- }
417
+ currentUid();
418
+ await createSettingsDirectory(dir);
216
419
  const temporary = join(dir, ".config-" + randomUUID() + ".tmp");
420
+ let directory;
421
+ let staged;
422
+ let temporaryCreated = false;
423
+ let destination;
217
424
  try {
218
- await writeFile(temporary, JSON.stringify(checked, null, 2) + "\n", {
219
- flag: "wx",
220
- mode: 384
221
- });
425
+ directory = await inspectDirectory(dir);
426
+ const existing = await openSettingsFile(path2, directory, true);
427
+ if (existing) {
428
+ destination = existing.stat;
429
+ await existing.handle.close();
430
+ }
431
+ staged = await open(
432
+ temporary,
433
+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,
434
+ 384
435
+ );
436
+ temporaryCreated = true;
437
+ await staged.chmod(384);
438
+ const stagedStat = await staged.stat();
439
+ checkSettingsFile(stagedStat);
440
+ await staged.writeFile(JSON.stringify(checked, null, 2) + "\n", "utf8");
441
+ await staged.sync();
442
+ await staged.close();
443
+ staged = void 0;
444
+ await verifyDirectory(directory);
445
+ try {
446
+ const current = await lstat(path2);
447
+ checkSettingsFile(current);
448
+ if (!destination || !sameIdentity(destination, current)) unsafeSettings();
449
+ } catch (error) {
450
+ if (error.code !== "ENOENT" || destination)
451
+ unsafeSettings();
452
+ }
222
453
  await rename(temporary, path2);
223
- await chmod(path2, 384);
224
454
  } finally {
225
- await unlink(temporary).catch(() => {
455
+ await staged?.close().catch(() => {
456
+ });
457
+ await directory?.handle.close().catch(() => {
458
+ });
459
+ if (temporaryCreated) await unlink(temporary).catch(() => {
226
460
  });
227
461
  }
228
462
  }
@@ -327,10 +561,215 @@ import {
327
561
  fromJsonSchema
328
562
  } from "@modelcontextprotocol/server";
329
563
  import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
564
+
565
+ // src/client/review-pair.ts
566
+ import { z as z4 } from "zod";
567
+
568
+ // src/contracts.ts
569
+ import { z as z3 } from "zod";
570
+ var MAX_INPUT_BYTES = 128e3;
571
+ var safePath = (path2) => path2.length > 0 && path2.length <= 512 && !/^[\/\\]|^[A-Za-z]:|[\\\x00-\x1f\x7f]/.test(path2) && path2.split("/").every((part) => part !== "" && part !== "." && part !== "..");
572
+ var PathSchema = z3.string().refine(safePath, "Expected a safe relative path");
573
+ var SafeId = z3.string().min(1).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/);
574
+ var ReviewInputSchema = z3.strictObject({
575
+ schema_version: z3.union([z3.literal(1), z3.literal(2)]).describe(
576
+ "Use 2 for new supplier-pinned bundles. Legacy 1 new requests are OpenAI only."
577
+ ),
578
+ provider: z3.enum(["openai", "anthropic"]).optional().describe(
579
+ "Required and hash-pinned for schema_version 2. Legacy schema 1 new requests are OpenAI only."
580
+ ),
581
+ request_id: SafeId.max(80),
582
+ profile: SafeId.max(64),
583
+ input_sha256: z3.string().regex(/^[a-f0-9]{64}$/),
584
+ task_kind: z3.enum(["code", "design", "text"]),
585
+ requirements: z3.string().max(16e3),
586
+ files: z3.array(
587
+ z3.strictObject({
588
+ path: PathSchema,
589
+ start_line: z3.number().int().positive().max(Number.MAX_SAFE_INTEGER),
590
+ content: z3.string()
591
+ })
592
+ ).max(40),
593
+ diff: z3.string().max(1e5)
594
+ }).superRefine((value, ctx) => {
595
+ if (value.schema_version === 2 && value.provider === void 0 || value.schema_version === 1 && value.provider !== void 0)
596
+ ctx.addIssue({
597
+ code: "custom",
598
+ message: "Schema 2 requires provider; legacy schema 1 must omit it"
599
+ });
600
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > MAX_INPUT_BYTES)
601
+ ctx.addIssue({ code: "custom", message: "Input exceeds byte limit" });
602
+ if (new Set(value.files.map((file) => file.path)).size !== value.files.length)
603
+ ctx.addIssue({ code: "custom", message: "File paths must be unique" });
604
+ if (!value.diff.trim() && !value.files.some((file) => file.content.trim()))
605
+ ctx.addIssue({ code: "custom", message: "Source content is required" });
606
+ for (const file of value.files) {
607
+ if (!Number.isSafeInteger(
608
+ file.start_line + file.content.split("\n").length - 1
609
+ ))
610
+ ctx.addIssue({
611
+ code: "custom",
612
+ message: "Source line range exceeds safe integers"
613
+ });
614
+ }
615
+ });
616
+ function inputProvider(input) {
617
+ if (input.schema_version === 1) return "openai";
618
+ if (input.provider !== "openai" && input.provider !== "anthropic")
619
+ throw new Error("Provider pin required");
620
+ return input.provider;
621
+ }
622
+ async function inputHash(input) {
623
+ const bytes = new TextEncoder().encode(
624
+ JSON.stringify({
625
+ schema_version: input.schema_version,
626
+ ...input.schema_version === 2 ? { provider: inputProvider(input) } : {},
627
+ task_kind: input.task_kind,
628
+ requirements: input.requirements,
629
+ files: input.files.map(({ path: path2, start_line, content }) => ({
630
+ path: path2,
631
+ start_line,
632
+ content
633
+ })),
634
+ diff: input.diff
635
+ })
636
+ );
637
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
638
+ return Array.from(
639
+ new Uint8Array(digest),
640
+ (byte) => byte.toString(16).padStart(2, "0")
641
+ ).join("");
642
+ }
643
+ function profileProvider(profile) {
644
+ const provider = profile.provider ?? "openai";
645
+ if (provider !== "openai" && provider !== "anthropic")
646
+ throw new Error("Invalid provider");
647
+ return provider;
648
+ }
649
+ var ReviewSchema = z3.strictObject({
650
+ summary: z3.string().min(1).max(16e3),
651
+ additional_evidence: z3.array(z3.string().max(8e3)).max(40),
652
+ findings: z3.array(
653
+ z3.strictObject({
654
+ severity: z3.enum(["critical", "high", "medium", "low"]),
655
+ title: z3.string().min(1).max(1e3),
656
+ explanation: z3.string().min(1).max(16e3),
657
+ path: PathSchema,
658
+ line: z3.number().int().positive().max(Number.MAX_SAFE_INTEGER),
659
+ end_line: z3.number().int().positive().max(Number.MAX_SAFE_INTEGER),
660
+ counterexample: z3.string().min(1).max(16e3),
661
+ remediation: z3.string().min(1).max(16e3)
662
+ })
663
+ ).max(100)
664
+ });
665
+
666
+ // src/client/review-pair.ts
667
+ var ReviewPairSchema = z4.strictObject({
668
+ first: ReviewInputSchema.describe(
669
+ "An unchanged schema version 2 bundle from rebut collect."
670
+ ),
671
+ second: z4.strictObject({
672
+ request_id: ReviewInputSchema.shape.request_id,
673
+ profile: ReviewInputSchema.shape.profile,
674
+ provider: ReviewInputSchema.shape.provider.unwrap()
675
+ }).describe(
676
+ "Explicit second reviewer. Rebut copies the first bundle's evidence and computes a supplier-pinned hash."
677
+ )
678
+ });
679
+ function toolResult(value, isError = false) {
680
+ return {
681
+ ...isError ? { isError: true } : {},
682
+ content: [{ type: "text", text: JSON.stringify(value) }]
683
+ };
684
+ }
685
+ function registerReviewPair(server, callReview, localMaxConcurrent) {
686
+ server.registerTool(
687
+ "review_pair",
688
+ {
689
+ description: "Use only when the user explicitly opts in to two paid reviews with distinct profiles. Dispatches through the active backend in parallel and shares its budget and concurrency limits. Keep both request IDs. After a lost response, call review_status for each original ID on this backend. Never start replacement paid requests automatically.",
690
+ inputSchema: ReviewPairSchema
691
+ },
692
+ async ({ first, second }, extra) => {
693
+ if (first.schema_version !== 2 || first.request_id === second.request_id || first.profile === second.profile) {
694
+ return toolResult(
695
+ {
696
+ status: "invalid_review_pair",
697
+ message: "Use a schema version 2 first bundle, distinct request IDs, and distinct profiles."
698
+ },
699
+ true
700
+ );
701
+ }
702
+ if (await inputHash(first) !== first.input_sha256)
703
+ return toolResult({ status: "input_hash_mismatch" }, true);
704
+ const candidate = { ...first, ...second };
705
+ const parsed = ReviewInputSchema.safeParse(candidate);
706
+ if (!parsed.success)
707
+ return toolResult({ status: "invalid_second_bundle" }, true);
708
+ const secondary = {
709
+ ...parsed.data,
710
+ input_sha256: await inputHash(parsed.data)
711
+ };
712
+ if (localMaxConcurrent !== void 0 && localMaxConcurrent < 2)
713
+ return toolResult(
714
+ {
715
+ status: "pair_concurrency_unavailable",
716
+ message: "Local parallel review requires a concurrency limit of at least 2. Use rebut set max-concurrent 2 to opt in."
717
+ },
718
+ true
719
+ );
720
+ const signal = extra.mcpReq.signal;
721
+ if (signal.aborted)
722
+ return toolResult(
723
+ { status: "review_pair_cancelled_before_dispatch" },
724
+ true
725
+ );
726
+ const reviews = await Promise.all(
727
+ [first, secondary].map(async (input) => {
728
+ const identity = {
729
+ request_id: input.request_id,
730
+ profile: input.profile,
731
+ provider: input.provider,
732
+ input_sha256: input.input_sha256
733
+ };
734
+ try {
735
+ const response = await callReview(input, signal);
736
+ const [content] = response.content;
737
+ const result = content?.type === "text" && content.text ? JSON.parse(content.text) : void 0;
738
+ if (response.content.length === 1 && typeof result?.status === "string")
739
+ return {
740
+ ...identity,
741
+ has_review: !response.isError && result.status === "completed" && typeof result.review?.summary === "string",
742
+ result
743
+ };
744
+ } catch {
745
+ }
746
+ return {
747
+ ...identity,
748
+ has_review: false,
749
+ result: {
750
+ status: "unknown",
751
+ result_replay_available: false,
752
+ message: "Query review_status with this original request ID on the same backend."
753
+ }
754
+ };
755
+ })
756
+ );
757
+ const returned = reviews.filter(({ has_review }) => has_review).length;
758
+ let status = "incomplete";
759
+ if (returned === 2) status = "completed";
760
+ else if (returned === 1) status = "partial";
761
+ else if (reviews.every(({ result }) => result.status === "completed"))
762
+ status = "completed_without_review";
763
+ return toolResult({ status, reviews });
764
+ }
765
+ );
766
+ }
767
+
768
+ // src/client/stdio.ts
330
769
  var REVIEW_GUIDANCE = "Use only when the user explicitly opts in to a review using the frozen profile provider. Keep the original request_id and backend after uncertainty and query review_status before another paid invocation. Do not automatically change reviewers, providers, or keys. Project default real API tests: luna-test (gpt-6-luna).";
331
770
  async function serveStdio(options2) {
332
771
  const remote = await connectRemote(options2);
333
- const server = new McpServer({ name: "rebut-mcp", version: "0.3.2" });
772
+ const server = new McpServer({ name: "rebut-mcp", version: "0.4.0" });
334
773
  let finish;
335
774
  const finished = new Promise((resolve6) => {
336
775
  finish = resolve6;
@@ -360,7 +799,7 @@ async function serveStdio(options2) {
360
799
  title: tool.title,
361
800
  description: tool.name === "review" ? `${tool.description ?? ""}
362
801
 
363
- ${REVIEW_GUIDANCE}${options2.preferredProfile ? "\nPreferred profile for new reviews: " + options2.preferredProfile.id + " (model " + options2.preferredProfile.model + ", reasoning " + (options2.preferredProfile.reasoning ?? "provider default") + "). Explicit request profile remains authoritative." : ""}`.trim() : tool.description,
802
+ ${REVIEW_GUIDANCE}${options2.preferredProfile ? "\nPreferred profile for new reviews: " + options2.preferredProfile.id + " (model " + options2.preferredProfile.model + ", reasoning " + (options2.preferredProfile.reasoning ?? "provider default") + "). Explicit request profile remains authoritative." : options2.clientProfileUnavailable ? "\nCould not resolve the configured client default. Select an enabled profile explicitly." : options2.reviewUnavailable ? "\nThe shared review preference is unavailable." : ""}${options2.client ? "\nFor new bundles, use rebut collect --client " + options2.client + " to apply this client default." : ""}`.trim() : tool.description,
364
803
  inputSchema: fromJsonSchema(
365
804
  tool.inputSchema
366
805
  ),
@@ -400,6 +839,10 @@ ${REVIEW_GUIDANCE}${options2.preferredProfile ? "\nPreferred profile for new rev
400
839
  )) {
401
840
  throw new Error(REMOTE_FAILURE_MESSAGE);
402
841
  }
842
+ registerReviewPair(
843
+ server,
844
+ (input, signal) => remote.callTool({ name: "review", arguments: input }, { signal })
845
+ );
403
846
  await server.connect(new StdioServerTransport());
404
847
  await finished;
405
848
  } catch {
@@ -410,11 +853,11 @@ ${REVIEW_GUIDANCE}${options2.preferredProfile ? "\nPreferred profile for new rev
410
853
  }
411
854
 
412
855
  // src/client/claude.ts
413
- import { constants } from "node:fs";
856
+ import { constants as constants2 } from "node:fs";
414
857
  import { randomUUID as randomUUID2 } from "node:crypto";
415
858
  import { homedir as homedir3 } from "node:os";
416
859
  import { dirname as dirname3, isAbsolute, join as join3, resolve as resolve2 } from "node:path";
417
- import { lstat as lstat2, mkdir as mkdir2, open, rename as rename2, unlink as unlink2 } from "node:fs/promises";
860
+ import { lstat as lstat2, mkdir as mkdir2, open as open2, rename as rename2, unlink as unlink2 } from "node:fs/promises";
418
861
  import {
419
862
  parseTree,
420
863
  findNodeAtLocation,
@@ -483,7 +926,7 @@ async function readConfig(path2) {
483
926
  "UNSAFE_CONFIG",
484
927
  "Claude config must be a private regular file owned by the current user."
485
928
  );
486
- file = await open(path2, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
929
+ file = await open2(path2, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
487
930
  const current = await file.stat();
488
931
  if (current.size > MAX_BYTES)
489
932
  fail(
@@ -519,7 +962,7 @@ async function readConfig(path2) {
519
962
  await file?.close();
520
963
  }
521
964
  }
522
- function safePath(path2) {
965
+ function safePath2(path2) {
523
966
  if (/[\x00-\x1f\x7f]|\$\{/.test(path2))
524
967
  fail(
525
968
  "INVALID_PATH",
@@ -530,7 +973,7 @@ function safePath(path2) {
530
973
  function desired(options2) {
531
974
  const env = {};
532
975
  if (options2.configDir !== void 0)
533
- env.REBUT_CONFIG_DIR = safePath(options2.configDir);
976
+ env.REBUT_CONFIG_DIR = safePath2(options2.configDir);
534
977
  if (options2.forwardApiKeyEnv) {
535
978
  const name = options2.apiKeyEnv ?? "REBUT_OPENAI_API_KEY";
536
979
  if (![
@@ -543,8 +986,8 @@ function desired(options2) {
543
986
  } else if (options2.forwardTokenEnv) env.REBUT_TOKEN = "${REBUT_TOKEN:-}";
544
987
  return {
545
988
  type: "stdio",
546
- command: safePath(options2.nodePath ?? process.execPath),
547
- args: [safePath(options2.entrypoint), "mcp"],
989
+ command: safePath2(options2.nodePath ?? process.execPath),
990
+ args: [safePath2(options2.entrypoint), "mcp", "--client", "claude"],
548
991
  timeout: CODEX_TOOL_TIMEOUT_SECONDS * 1e3,
549
992
  ...Object.keys(env).length ? { env } : {}
550
993
  };
@@ -567,7 +1010,7 @@ function equivalent(a, b) {
567
1010
  function recognized(value) {
568
1011
  if (typeof value !== "object" || !value || Array.isArray(value)) return false;
569
1012
  const v = value;
570
- return (v.type === void 0 || v.type === "stdio") && typeof v.command === "string" && isAbsolute(v.command) && Array.isArray(v.args) && v.args.length === 2 && typeof v.args[0] === "string" && /(?:^|[\\/])bin[\\/]rebut\.mjs$/.test(v.args[0]) && v.args[1] === "mcp";
1013
+ return (v.type === void 0 || v.type === "stdio") && typeof v.command === "string" && isAbsolute(v.command) && Array.isArray(v.args) && (v.args.length === 2 || v.args.length === 4 && v.args[2] === "--client" && v.args[3] === "claude") && typeof v.args[0] === "string" && /(?:^|[\\/])bin[\\/]rebut\.mjs$/.test(v.args[0]) && v.args[1] === "mcp";
571
1014
  }
572
1015
  async function update(options2, remove) {
573
1016
  if (!options2.claudeConfig && process.env.CLAUDE_CONFIG_DIR)
@@ -575,7 +1018,7 @@ async function update(options2, remove) {
575
1018
  "CONFIG_PATH_REQUIRED",
576
1019
  "Set --claude-config PATH explicitly when CLAUDE_CONFIG_DIR is in use."
577
1020
  );
578
- const configPath = safePath(
1021
+ const configPath = safePath2(
579
1022
  options2.claudeConfig ?? join3(homedir3(), ".claude.json")
580
1023
  );
581
1024
  let temporary;
@@ -612,7 +1055,7 @@ async function update(options2, remove) {
612
1055
  "Claude config parent must be owned and writable only by the current user."
613
1056
  );
614
1057
  temporary = join3(dirname3(configPath), `.rebut-claude-${randomUUID2()}.tmp`);
615
- const file = await open(temporary, "wx", 384);
1058
+ const file = await open2(temporary, "wx", 384);
616
1059
  try {
617
1060
  await file.writeFile(output2, "utf8");
618
1061
  await file.sync();
@@ -642,110 +1085,10 @@ var setupClaude = (options2) => update(options2, false);
642
1085
  var removeClaude = (options2) => update(options2, true);
643
1086
 
644
1087
  // src/review.ts
645
- import { z as z5 } from "zod";
646
-
647
- // src/anthropic.ts
648
- import { z as z4 } from "zod";
649
-
650
- // src/contracts.ts
651
- import { z as z3 } from "zod";
652
- var MAX_INPUT_BYTES = 128e3;
653
- var safePath2 = (path2) => path2.length > 0 && path2.length <= 512 && !/^[\/\\]|^[A-Za-z]:|[\\\x00-\x1f\x7f]/.test(path2) && path2.split("/").every((part) => part !== "" && part !== "." && part !== "..");
654
- var PathSchema = z3.string().refine(safePath2, "Expected a safe relative path");
655
- var SafeId = z3.string().min(1).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/);
656
- var ReviewInputSchema = z3.strictObject({
657
- schema_version: z3.union([z3.literal(1), z3.literal(2)]).describe(
658
- "Use 2 for new supplier-pinned bundles. Legacy 1 new requests are OpenAI only."
659
- ),
660
- provider: z3.enum(["openai", "anthropic"]).optional().describe(
661
- "Required and hash-pinned for schema_version 2. Legacy schema 1 new requests are OpenAI only."
662
- ),
663
- request_id: SafeId.max(80),
664
- profile: SafeId.max(64),
665
- input_sha256: z3.string().regex(/^[a-f0-9]{64}$/),
666
- task_kind: z3.enum(["code", "design", "text"]),
667
- requirements: z3.string().max(16e3),
668
- files: z3.array(
669
- z3.strictObject({
670
- path: PathSchema,
671
- start_line: z3.number().int().positive().max(Number.MAX_SAFE_INTEGER),
672
- content: z3.string()
673
- })
674
- ).max(40),
675
- diff: z3.string().max(1e5)
676
- }).superRefine((value, ctx) => {
677
- if (value.schema_version === 2 && value.provider === void 0 || value.schema_version === 1 && value.provider !== void 0)
678
- ctx.addIssue({
679
- code: "custom",
680
- message: "Schema 2 requires provider; legacy schema 1 must omit it"
681
- });
682
- if (new TextEncoder().encode(JSON.stringify(value)).byteLength > MAX_INPUT_BYTES)
683
- ctx.addIssue({ code: "custom", message: "Input exceeds byte limit" });
684
- if (new Set(value.files.map((file) => file.path)).size !== value.files.length)
685
- ctx.addIssue({ code: "custom", message: "File paths must be unique" });
686
- if (!value.diff.trim() && !value.files.some((file) => file.content.trim()))
687
- ctx.addIssue({ code: "custom", message: "Source content is required" });
688
- for (const file of value.files) {
689
- if (!Number.isSafeInteger(
690
- file.start_line + file.content.split("\n").length - 1
691
- ))
692
- ctx.addIssue({
693
- code: "custom",
694
- message: "Source line range exceeds safe integers"
695
- });
696
- }
697
- });
698
- function inputProvider(input) {
699
- if (input.schema_version === 1) return "openai";
700
- if (input.provider !== "openai" && input.provider !== "anthropic")
701
- throw new Error("Provider pin required");
702
- return input.provider;
703
- }
704
- async function inputHash(input) {
705
- const bytes = new TextEncoder().encode(
706
- JSON.stringify({
707
- schema_version: input.schema_version,
708
- ...input.schema_version === 2 ? { provider: inputProvider(input) } : {},
709
- task_kind: input.task_kind,
710
- requirements: input.requirements,
711
- files: input.files.map(({ path: path2, start_line, content }) => ({
712
- path: path2,
713
- start_line,
714
- content
715
- })),
716
- diff: input.diff
717
- })
718
- );
719
- const digest = await crypto.subtle.digest("SHA-256", bytes);
720
- return Array.from(
721
- new Uint8Array(digest),
722
- (byte) => byte.toString(16).padStart(2, "0")
723
- ).join("");
724
- }
725
- function profileProvider(profile) {
726
- const provider = profile.provider ?? "openai";
727
- if (provider !== "openai" && provider !== "anthropic")
728
- throw new Error("Invalid provider");
729
- return provider;
730
- }
731
- var ReviewSchema = z3.strictObject({
732
- summary: z3.string().min(1).max(16e3),
733
- additional_evidence: z3.array(z3.string().max(8e3)).max(40),
734
- findings: z3.array(
735
- z3.strictObject({
736
- severity: z3.enum(["critical", "high", "medium", "low"]),
737
- title: z3.string().min(1).max(1e3),
738
- explanation: z3.string().min(1).max(16e3),
739
- path: PathSchema,
740
- line: z3.number().int().positive().max(Number.MAX_SAFE_INTEGER),
741
- end_line: z3.number().int().positive().max(Number.MAX_SAFE_INTEGER),
742
- counterexample: z3.string().min(1).max(16e3),
743
- remediation: z3.string().min(1).max(16e3)
744
- })
745
- ).max(100)
746
- });
1088
+ import { z as z6 } from "zod";
747
1089
 
748
1090
  // src/anthropic.ts
1091
+ import { z as z5 } from "zod";
749
1092
  var ANTHROPIC_VERSION = "2026-10-21";
750
1093
  var record = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
751
1094
  var counter = (v) => Number.isSafeInteger(v) && v >= 0;
@@ -816,7 +1159,7 @@ function buildAnthropicBody(input, profile, instructions) {
816
1159
  format: {
817
1160
  type: "json_schema",
818
1161
  schema: anthropicSchema(
819
- z4.toJSONSchema(ReviewSchema, { target: "draft-7" })
1162
+ z5.toJSONSchema(ReviewSchema, { target: "draft-7" })
820
1163
  )
821
1164
  }
822
1165
  }
@@ -916,7 +1259,7 @@ function buildReviewBody(input, profile) {
916
1259
  type: "json_schema",
917
1260
  name: "rebut_review",
918
1261
  strict: true,
919
- schema: z5.toJSONSchema(ReviewSchema, { target: "draft-7" })
1262
+ schema: z6.toJSONSchema(ReviewSchema, { target: "draft-7" })
920
1263
  }
921
1264
  }
922
1265
  };
@@ -937,12 +1280,12 @@ function estimateReservation(input, profile, serializedBody) {
937
1280
  profile
938
1281
  );
939
1282
  }
940
- var count = z5.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
941
- var UsageSchema = z5.object({
1283
+ var count = z6.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
1284
+ var UsageSchema = z6.object({
942
1285
  input_tokens: count,
943
1286
  output_tokens: count,
944
- input_tokens_details: z5.object({ cached_tokens: count }),
945
- output_tokens_details: z5.object({ reasoning_tokens: count }),
1287
+ input_tokens_details: z6.object({ cached_tokens: count }),
1288
+ output_tokens_details: z6.object({ reasoning_tokens: count }),
946
1289
  total_tokens: count
947
1290
  }).refine(
948
1291
  (v) => v.input_tokens_details.cached_tokens <= v.input_tokens && v.output_tokens_details.reasoning_tokens <= v.output_tokens && Number.isSafeInteger(v.input_tokens + v.output_tokens) && v.total_tokens === v.input_tokens + v.output_tokens
@@ -969,7 +1312,7 @@ function evidenceRanges(input) {
969
1312
  }
970
1313
  if (line.startsWith("+++ ") && oldRemaining === 0 && newRemaining === 0) {
971
1314
  const candidate = line.slice(4).split(" ")[0].replace(/^b\//, "");
972
- path2 = safePath2(candidate) && candidate !== "/dev/null" ? candidate : void 0;
1315
+ path2 = safePath(candidate) && candidate !== "/dev/null" ? candidate : void 0;
973
1316
  } else if (line.startsWith("@@ ")) {
974
1317
  const match = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
975
1318
  oldRemaining = match ? Number(match[2] ?? 1) : 0;
@@ -1309,13 +1652,13 @@ import { randomUUID as randomUUID3 } from "node:crypto";
1309
1652
  import { homedir as homedir4 } from "node:os";
1310
1653
  import { dirname as dirname4, join as join4, resolve as resolve3 } from "node:path";
1311
1654
  import {
1312
- chmod as chmod2,
1655
+ chmod,
1313
1656
  lstat as lstat3,
1314
1657
  mkdir as mkdir3,
1315
- readFile as readFile2,
1658
+ readFile,
1316
1659
  rename as rename3,
1317
1660
  unlink as unlink3,
1318
- writeFile as writeFile2
1661
+ writeFile
1319
1662
  } from "node:fs/promises";
1320
1663
  import { parse as parse2, stringify } from "smol-toml";
1321
1664
  var CodexSetupError = class extends Error {
@@ -1344,14 +1687,25 @@ function equivalent2(a, b) {
1344
1687
  function desired2(options2) {
1345
1688
  return {
1346
1689
  command: options2.nodePath ?? process.execPath,
1347
- args: [resolve3(options2.entrypoint), "mcp"],
1690
+ args: [resolve3(options2.entrypoint), "mcp", "--client", "codex"],
1348
1691
  startup_timeout_sec: 60,
1349
1692
  tool_timeout_sec: CODEX_TOOL_TIMEOUT_SECONDS,
1350
- enabled_tools: ["review", "review_status"],
1693
+ enabled_tools: ["review", "review_status", "review_pair"],
1351
1694
  ...options2.forwardApiKeyEnv ? { env_vars: [options2.apiKeyEnv ?? "REBUT_OPENAI_API_KEY"] } : options2.forwardTokenEnv ? { env_vars: ["REBUT_TOKEN"] } : {},
1352
1695
  ...options2.configDir !== void 0 ? { env: { REBUT_CONFIG_DIR: resolve3(options2.configDir) } } : {}
1353
1696
  };
1354
1697
  }
1698
+ function providerKeyVars(value) {
1699
+ return value === void 0 || Array.isArray(value) && value.length === 1 && (value[0] === "REBUT_OPENAI_API_KEY" || value[0] === "OPENAI_API_KEY" || value[0] === "REBUT_ANTHROPIC_API_KEY");
1700
+ }
1701
+ function matchesRemoval(existing, desired3, entrypoint) {
1702
+ if (!table(existing)) return false;
1703
+ const { env_vars: existingVars, ...registered } = existing;
1704
+ const { env_vars: desiredVars, ...expected } = desired3;
1705
+ if (!equivalent2(existingVars, desiredVars) && !(providerKeyVars(existingVars) && providerKeyVars(desiredVars)))
1706
+ return false;
1707
+ return equivalent2(registered, expected) || equivalent2(registered, { ...expected, args: [resolve3(entrypoint), "mcp"] });
1708
+ }
1355
1709
  function headers(source) {
1356
1710
  const result = [];
1357
1711
  let quote = "", triple = false, lineStart = true;
@@ -1432,7 +1786,7 @@ async function readConfig2(path2) {
1432
1786
  "UNSAFE_CONFIG",
1433
1787
  "Codex config must be a regular file."
1434
1788
  );
1435
- return await readFile2(path2, "utf8");
1789
+ return await readFile(path2, "utf8");
1436
1790
  } catch (error) {
1437
1791
  if (error.code === "ENOENT") return void 0;
1438
1792
  throw error;
@@ -1469,7 +1823,7 @@ async function update2(options2, remove) {
1469
1823
  if (!remove && equivalent2(existing, replacement) || remove && existing === void 0) {
1470
1824
  return { configPath, changed: false };
1471
1825
  }
1472
- if (existing !== void 0 && !equivalent2(existing, replacement) && !options2.replace) {
1826
+ if (existing !== void 0 && !equivalent2(existing, replacement) && !(remove && matchesRemoval(existing, replacement, options2.entrypoint)) && !options2.replace) {
1473
1827
  throw new CodexSetupError(
1474
1828
  "SERVER_CONFLICT",
1475
1829
  "Codex already has a different rebut server. Use --replace to replace it."
@@ -1484,9 +1838,9 @@ async function update2(options2, remove) {
1484
1838
  remove ? void 0 : replacement
1485
1839
  );
1486
1840
  await mkdir3(dirname4(configPath), { recursive: true, mode: 448 });
1487
- await chmod2(dirname4(configPath), 448);
1841
+ await chmod(dirname4(configPath), 448);
1488
1842
  temporary = join4(dirname4(configPath), `.rebut-config-${randomUUID3()}.tmp`);
1489
- await writeFile2(temporary, output2, { mode: 384, flag: "wx" });
1843
+ await writeFile(temporary, output2, { mode: 384, flag: "wx" });
1490
1844
  if (await readConfig2(configPath) !== original) {
1491
1845
  throw new CodexSetupError(
1492
1846
  "CONFIG_CHANGED",
@@ -1515,8 +1869,8 @@ function removeCodex(options2) {
1515
1869
  }
1516
1870
 
1517
1871
  // src/client/collector.ts
1518
- import { constants as constants2 } from "node:fs";
1519
- import { lstat as lstat4, realpath, open as open2 } from "node:fs/promises";
1872
+ import { constants as constants3 } from "node:fs";
1873
+ import { lstat as lstat4, realpath as realpath2, open as open3 } from "node:fs/promises";
1520
1874
  import path from "node:path";
1521
1875
  var forbidden = /(^|\/)(\.git|node_modules|\.env(?:\..*)?|\.dev\.vars.*|\.ssh|\.aws|\.config|.*\.(pem|key|p12|pfx|sqlite|db)|(?:credentials|secrets|id_rsa|id_ed25519)(?:\..*)?)$/i;
1522
1876
  function redact(text) {
@@ -1532,7 +1886,7 @@ function redact(text) {
1532
1886
  );
1533
1887
  }
1534
1888
  async function readSafe(root, relative) {
1535
- if (!safePath2(relative) || relative.split("/").some((_, i, a) => forbidden.test(a.slice(0, i + 1).join("/"))))
1889
+ if (!safePath(relative) || relative.split("/").some((_, i, a) => forbidden.test(a.slice(0, i + 1).join("/"))))
1536
1890
  throw new Error("Disallowed source path");
1537
1891
  const parts = relative.split("/");
1538
1892
  let current = root;
@@ -1544,12 +1898,12 @@ async function readSafe(root, relative) {
1544
1898
  const expected = await lstat4(current);
1545
1899
  if (!expected.isFile() || expected.size > 1e5)
1546
1900
  throw new Error("Unsupported source type or size");
1547
- const resolved = await realpath(current);
1901
+ const resolved = await realpath2(current);
1548
1902
  if (!resolved.startsWith(root + path.sep))
1549
1903
  throw new Error("Source escapes root");
1550
- const handle = await open2(
1904
+ const handle = await open3(
1551
1905
  current,
1552
- constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK
1906
+ constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK
1553
1907
  );
1554
1908
  try {
1555
1909
  const stat = await handle.stat();
@@ -1585,7 +1939,7 @@ async function collect(root, files, requirements, request_id, profile = "astra-m
1585
1939
  throw new Error("Collection exceeds input limits");
1586
1940
  if (new Set(files).size !== files.length)
1587
1941
  throw new Error("Duplicate source paths");
1588
- const canonicalRoot = await realpath(root);
1942
+ const canonicalRoot = await realpath2(root);
1589
1943
  const material = {
1590
1944
  schema_version: 2,
1591
1945
  provider,
@@ -1609,20 +1963,24 @@ async function collect(root, files, requirements, request_id, profile = "astra-m
1609
1963
  }
1610
1964
 
1611
1965
  // src/client/profiles.ts
1612
- import { z as z6 } from "zod";
1613
- var Id = z6.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/);
1614
- var RecordSchema = z6.strictObject({
1966
+ import { z as z7 } from "zod";
1967
+ var Id = z7.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/);
1968
+ var RecordSchema = z7.strictObject({
1615
1969
  id: Id,
1616
- revision: z6.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
1617
- enabled: z6.boolean(),
1970
+ revision: z7.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
1971
+ enabled: z7.boolean(),
1618
1972
  profile: ProfileSchema.optional()
1619
1973
  }).refine((record3) => !record3.enabled || record3.profile !== void 0);
1620
- var ListSchema = z6.strictObject({ profiles: z6.array(RecordSchema) }).refine(
1974
+ var ListSchema = z7.strictObject({ profiles: z7.array(RecordSchema) }).refine(
1621
1975
  ({ profiles }) => new Set(profiles.map((record3) => record3.id)).size === profiles.length
1622
1976
  );
1623
1977
  var FAILURE = "Profile request failed; no automatic retry was made.";
1624
1978
  var SAFE_ERRORS = /* @__PURE__ */ new Set([
1625
1979
  FAILURE,
1980
+ "Budget request failed; no automatic retry was made.",
1981
+ "Budget schedule already set or the calendar boundary changed; run rebut budget.",
1982
+ "Budget administration authentication failed.",
1983
+ "Budget service unavailable; check the Worker and ledger migration.",
1626
1984
  "Profile revision conflict; read current profiles before making another change.",
1627
1985
  "Profile authentication or authorization failed.",
1628
1986
  "Profile service unavailable; check migration and service status.",
@@ -1645,7 +2003,11 @@ function safeProfileError(error) {
1645
2003
  return error instanceof Error && SAFE_ERRORS.has(error.message) ? error.message : void 0;
1646
2004
  }
1647
2005
  var LIMIT = 65536;
1648
- async function request(options2, path2, method = "GET", body) {
2006
+ async function request(options2, path2, method = "GET", body, isBudget = false) {
2007
+ const failure = isBudget ? "Budget request failed; no automatic retry was made." : FAILURE;
2008
+ const conflict = isBudget ? "Budget schedule already set or the calendar boundary changed; run rebut budget." : "Profile revision conflict; read current profiles before making another change.";
2009
+ const unauthorized = isBudget ? "Budget administration authentication failed." : "Profile authentication or authorization failed.";
2010
+ const unavailable = isBudget ? "Budget service unavailable; check the Worker and ledger migration." : "Profile service unavailable; check migration and service status.";
1649
2011
  const endpoint = validateEndpoint(options2.endpoint);
1650
2012
  const url = new URL(path2, endpoint.origin);
1651
2013
  const controller = new AbortController();
@@ -1655,7 +2017,7 @@ async function request(options2, path2, method = "GET", body) {
1655
2017
  return await Promise.race([
1656
2018
  (async () => {
1657
2019
  const token = await options2.loadToken();
1658
- if (controller.signal.aborted) throw new Error(FAILURE);
2020
+ if (controller.signal.aborted) throw new Error(failure);
1659
2021
  const response = await fetch(url, {
1660
2022
  method,
1661
2023
  headers: {
@@ -1667,22 +2029,16 @@ async function request(options2, path2, method = "GET", body) {
1667
2029
  signal: controller.signal
1668
2030
  });
1669
2031
  if (!response.ok) {
1670
- if (response.status === 409)
1671
- throw new Error(
1672
- "Profile revision conflict; read current profiles before making another change."
1673
- );
2032
+ if (response.status === 409) throw new Error(conflict);
1674
2033
  if (response.status === 401 || response.status === 403)
1675
- throw new Error("Profile authentication or authorization failed.");
1676
- if (response.status === 503)
1677
- throw new Error(
1678
- "Profile service unavailable; check migration and service status."
1679
- );
1680
- throw new Error(FAILURE);
2034
+ throw new Error(unauthorized);
2035
+ if (response.status === 503) throw new Error(unavailable);
2036
+ throw new Error(failure);
1681
2037
  }
1682
2038
  const declared = response.headers.get("content-length");
1683
2039
  if (declared && (!/^\d+$/.test(declared) || Number(declared) > LIMIT))
1684
- throw new Error(FAILURE);
1685
- if (!response.body) throw new Error(FAILURE);
2040
+ throw new Error(failure);
2041
+ if (!response.body) throw new Error(failure);
1686
2042
  reader = response.body.getReader();
1687
2043
  const chunks = [];
1688
2044
  let size = 0;
@@ -1690,7 +2046,7 @@ async function request(options2, path2, method = "GET", body) {
1690
2046
  const chunk = await reader.read();
1691
2047
  if (chunk.done) break;
1692
2048
  size += chunk.value.byteLength;
1693
- if (size > LIMIT) throw new Error(FAILURE);
2049
+ if (size > LIMIT) throw new Error(failure);
1694
2050
  chunks.push(chunk.value);
1695
2051
  }
1696
2052
  const bytes = new Uint8Array(size);
@@ -1704,26 +2060,21 @@ async function request(options2, path2, method = "GET", body) {
1704
2060
  new TextDecoder("utf-8", { fatal: true }).decode(bytes)
1705
2061
  );
1706
2062
  } catch {
1707
- throw new Error(FAILURE);
2063
+ throw new Error(failure);
1708
2064
  }
1709
2065
  })(),
1710
2066
  new Promise((_, reject) => {
1711
2067
  timeout = setTimeout(() => {
1712
2068
  controller.abort();
1713
- reject(new Error(FAILURE));
2069
+ reject(new Error(failure));
1714
2070
  }, 15e3);
1715
2071
  })
1716
2072
  ]);
1717
2073
  } catch (error) {
1718
2074
  const message = error instanceof Error ? error.message : "";
1719
- if ([
1720
- FAILURE,
1721
- "Profile revision conflict; read current profiles before making another change.",
1722
- "Profile authentication or authorization failed.",
1723
- "Profile service unavailable; check migration and service status."
1724
- ].includes(message))
2075
+ if ([failure, conflict, unauthorized, unavailable].includes(message))
1725
2076
  throw new Error(message);
1726
- throw new Error(FAILURE);
2077
+ throw new Error(failure);
1727
2078
  } finally {
1728
2079
  if (timeout !== void 0) clearTimeout(timeout);
1729
2080
  controller.abort();
@@ -1731,6 +2082,15 @@ async function request(options2, path2, method = "GET", body) {
1731
2082
  });
1732
2083
  }
1733
2084
  }
2085
+ function workerBudget(options2, day) {
2086
+ return day === void 0 ? request(options2, "/admin/budget", "GET", void 0, true) : request(
2087
+ options2,
2088
+ `/admin/budget/start-day/${day}`,
2089
+ "PUT",
2090
+ void 0,
2091
+ true
2092
+ );
2093
+ }
1734
2094
  async function listProfiles(options2) {
1735
2095
  const parsed = ListSchema.safeParse(await request(options2, "/profiles"));
1736
2096
  if (!parsed.success) throw new Error("Invalid profile service response.");
@@ -1872,8 +2232,8 @@ async function profileCommand(args, deps) {
1872
2232
  command === "set" ? "PUT" : "DELETE",
1873
2233
  { expected_revision: revision, ...profile ? { profile } : {} }
1874
2234
  );
1875
- const parsed = z6.strictObject({
1876
- status: z6.literal("updated"),
2235
+ const parsed = z7.strictObject({
2236
+ status: z7.literal("updated"),
1877
2237
  record: RecordSchema.refine((record3) => record3.revision > 0)
1878
2238
  }).safeParse(payload);
1879
2239
  if (!parsed.success || parsed.data.record.id !== id)
@@ -1884,15 +2244,31 @@ async function profileCommand(args, deps) {
1884
2244
  }
1885
2245
 
1886
2246
  // src/local.ts
1887
- import { constants as constants3 } from "node:fs";
1888
- import { lstat as lstat5, mkdir as mkdir4, open as open3, readFile as readFile3 } from "node:fs/promises";
2247
+ import { constants as constants4 } from "node:fs";
2248
+ import { lstat as lstat5, mkdir as mkdir4, open as open4, readFile as readFile2 } from "node:fs/promises";
1889
2249
  import { homedir as homedir5 } from "node:os";
1890
2250
  import { dirname as dirname5, join as join5, resolve as resolve4 } from "node:path";
1891
2251
  import { McpServer as McpServer2 } from "@modelcontextprotocol/server";
1892
2252
  import { StdioServerTransport as StdioServerTransport2 } from "@modelcontextprotocol/server/stdio";
1893
- import { z as z7 } from "zod";
2253
+ import { z as z8 } from "zod";
1894
2254
 
1895
2255
  // src/ledger.ts
2256
+ function monthlyCycleInsert(day, now) {
2257
+ const t = monthlyTransition(now, day);
2258
+ const sql = `INSERT INTO monthly_budget_cycle(id, start_day, effective_at, bridge_month)
2259
+ SELECT 1, ?, CASE WHEN EXISTS (SELECT 1 FROM requests) THEN ? ELSE ? END,
2260
+ CASE WHEN EXISTS (SELECT 1 FROM requests) THEN ? ELSE NULL END
2261
+ WHERE NOT EXISTS (SELECT 1 FROM requests WHERE day >= ?)
2262
+ ON CONFLICT(id) DO NOTHING`;
2263
+ const args = [
2264
+ day,
2265
+ t.effectiveForExistingLedger,
2266
+ t.effectiveForEmptyLedger,
2267
+ t.currentMonth,
2268
+ t.nextCalendarBoundary.slice(0, 10)
2269
+ ];
2270
+ return { sql, args };
2271
+ }
1896
2272
  var Ledger = class {
1897
2273
  constructor(db) {
1898
2274
  this.db = db;
@@ -1901,45 +2277,104 @@ var Ledger = class {
1901
2277
  async get(principal, id) {
1902
2278
  return this.db.prepare("SELECT * FROM requests WHERE principal=? AND request_id=?").bind(principal, id).first();
1903
2279
  }
2280
+ async monthlyCycle() {
2281
+ const table2 = await this.db.prepare(
2282
+ "SELECT 1 FROM sqlite_schema WHERE type='table' AND name='monthly_budget_cycle'"
2283
+ ).first();
2284
+ if (!table2) return null;
2285
+ return this.db.prepare(
2286
+ "SELECT start_day, effective_at, bridge_month FROM monthly_budget_cycle WHERE id=1"
2287
+ ).first();
2288
+ }
2289
+ async scheduleMonthlyCycle(day, now = /* @__PURE__ */ new Date()) {
2290
+ if (!validMonthlyStartDay(day)) throw Error("INVALID_MONTHLY_START_DAY");
2291
+ if (day !== 1) {
2292
+ const { sql, args } = monthlyCycleInsert(day, now);
2293
+ await this.db.prepare(sql).bind(...args).run();
2294
+ }
2295
+ return this.monthlyCycleSetting(day);
2296
+ }
2297
+ async monthlyCycleSetting(day) {
2298
+ const cycle = await this.monthlyCycle();
2299
+ return {
2300
+ status: (cycle?.start_day ?? 1) === day ? "configured" : "conflict",
2301
+ monthly_start_day: cycle?.start_day ?? 1,
2302
+ effective_at: cycle?.effective_at ?? null
2303
+ };
2304
+ }
2305
+ async budget(limits, now = /* @__PURE__ */ new Date()) {
2306
+ const cycle = await this.monthlyCycle();
2307
+ const period = monthlyBudgetPeriod(now, cycle);
2308
+ const totals = await this.db.prepare(
2309
+ `SELECT
2310
+ COALESCE((SELECT SUM(charged_microusd) FROM requests WHERE month=?),0) AS accounted,
2311
+ (SELECT COUNT(*) FROM requests WHERE state IN ('reserved','unknown')) AS unresolved`
2312
+ ).bind(period.key).first();
2313
+ if (!totals) throw Error("BUDGET_STATUS_UNAVAILABLE");
2314
+ return {
2315
+ monthly_start_day: cycle?.start_day ?? 1,
2316
+ effective_at: cycle?.effective_at ?? null,
2317
+ period_start: period.start,
2318
+ next_reset_at: period.end,
2319
+ monthly_accounted_microusd: totals.accounted,
2320
+ monthly_limit_microusd: limits.monthlyMicrousd,
2321
+ unresolved_slots: totals.unresolved,
2322
+ max_concurrent: limits.maxConcurrent
2323
+ };
2324
+ }
1904
2325
  async reserve(principal, id, fingerprint, hash, profile, amount, limits, now = /* @__PURE__ */ new Date(), initialMetadata) {
1905
- const claim = crypto.randomUUID(), date = now.toISOString(), day = date.slice(0, 10), month = date.slice(0, 7);
1906
- await this.db.prepare(
1907
- `INSERT INTO requests
1908
- (principal,request_id,fingerprint,input_sha256,profile,claim,created_at,day,month,state,reserved_microusd,charged_microusd,metadata)
1909
- SELECT ?,?,?,?,?,?,?,?,?,'reserved',?,?,?
2326
+ const cycle = await this.monthlyCycle();
2327
+ const claim = crypto.randomUUID(), date = now.toISOString(), day = date.slice(0, 10), month = monthlyBudgetPeriod(now, cycle).key;
2328
+ const cycleColumn = cycle ? ",monthly_cycle_day" : "";
2329
+ const cycleValue = cycle ? ",?" : "";
2330
+ let scheduleChanged = false;
2331
+ try {
2332
+ await this.db.prepare(
2333
+ `INSERT INTO requests
2334
+ (principal,request_id,fingerprint,input_sha256,profile,claim,created_at,day,month,state,reserved_microusd,charged_microusd,metadata${cycleColumn})
2335
+ SELECT ?,?,?,?,?,?,?,?,?,'reserved',?,?,?${cycleValue}
1910
2336
  WHERE ? <= ?
1911
2337
  AND COALESCE((SELECT SUM(charged_microusd) FROM requests WHERE day=?),0)+? <= ?
1912
2338
  AND COALESCE((SELECT SUM(charged_microusd) FROM requests WHERE month=?),0)+? <= ?
1913
2339
  AND (SELECT COUNT(*) FROM requests WHERE state IN ('reserved','unknown')) < ?
1914
2340
  AND (SELECT COUNT(*) FROM requests WHERE day=?) < ?
1915
2341
  ON CONFLICT(principal,request_id) DO NOTHING`
1916
- ).bind(
1917
- principal,
1918
- id,
1919
- fingerprint,
1920
- hash,
1921
- profile,
1922
- claim,
1923
- date,
1924
- day,
1925
- month,
1926
- amount,
1927
- amount,
1928
- initialMetadata ? JSON.stringify(initialMetadata) : null,
1929
- amount,
1930
- limits.requestMicrousd,
1931
- day,
1932
- amount,
1933
- limits.dailyMicrousd,
1934
- month,
1935
- amount,
1936
- limits.monthlyMicrousd,
1937
- limits.maxConcurrent,
1938
- day,
1939
- limits.dailyRequests
1940
- ).run();
2342
+ ).bind(
2343
+ principal,
2344
+ id,
2345
+ fingerprint,
2346
+ hash,
2347
+ profile,
2348
+ claim,
2349
+ date,
2350
+ day,
2351
+ month,
2352
+ amount,
2353
+ amount,
2354
+ initialMetadata ? JSON.stringify(initialMetadata) : null,
2355
+ ...cycle ? [cycle.start_day] : [],
2356
+ amount,
2357
+ limits.requestMicrousd,
2358
+ day,
2359
+ amount,
2360
+ limits.dailyMicrousd,
2361
+ month,
2362
+ amount,
2363
+ limits.monthlyMicrousd,
2364
+ limits.maxConcurrent,
2365
+ day,
2366
+ limits.dailyRequests
2367
+ ).run();
2368
+ } catch (error) {
2369
+ if (!(error instanceof Error) || !error.message.includes("budget_schedule_changed"))
2370
+ throw error;
2371
+ scheduleChanged = true;
2372
+ }
1941
2373
  const row = await this.get(principal, id);
1942
- if (!row) return { status: "limit_exceeded" };
2374
+ if (!row)
2375
+ return {
2376
+ status: scheduleChanged ? "budget_schedule_changed" : "limit_exceeded"
2377
+ };
1943
2378
  if (row.fingerprint !== fingerprint) return { status: "conflict" };
1944
2379
  if (row.claim !== claim) return { status: "existing", row };
1945
2380
  return { status: "acquired", row };
@@ -2237,7 +2672,7 @@ function localDirectory() {
2237
2672
  }
2238
2673
  async function localConfig(settings) {
2239
2674
  const defaults = JSON.parse(
2240
- await readFile3(new URL("../config.example.json", import.meta.url), "utf8")
2675
+ await readFile2(new URL("../config.example.json", import.meta.url), "utf8")
2241
2676
  );
2242
2677
  return parseConfig(
2243
2678
  JSON.stringify({
@@ -2283,8 +2718,8 @@ function adapter(database) {
2283
2718
  async function openLocalRuntime(settings, options2 = {}) {
2284
2719
  const config = await localConfig(settings);
2285
2720
  const migrations = await Promise.all(
2286
- ["0001_ledger.sql", "0002_profiles.sql"].map(
2287
- (name) => readFile3(new URL("../migrations/" + name, import.meta.url), "utf8")
2721
+ ["0001_ledger.sql", "0002_profiles.sql", "0003_budget_cycle.sql"].map(
2722
+ (name) => readFile2(new URL("../migrations/" + name, import.meta.url), "utf8")
2288
2723
  )
2289
2724
  );
2290
2725
  const directory = resolve4(options2.directory ?? localDirectory());
@@ -2292,9 +2727,9 @@ async function openLocalRuntime(settings, options2 = {}) {
2292
2727
  await privatePath(directory, true);
2293
2728
  const path2 = join5(directory, "ledger.sqlite");
2294
2729
  try {
2295
- const file = await open3(
2730
+ const file = await open4(
2296
2731
  path2,
2297
- constants3.O_CREAT | constants3.O_EXCL | constants3.O_RDWR | (constants3.O_NOFOLLOW ?? 0),
2732
+ constants4.O_CREAT | constants4.O_EXCL | constants4.O_RDWR | (constants4.O_NOFOLLOW ?? 0),
2298
2733
  384
2299
2734
  );
2300
2735
  await file.close();
@@ -2310,7 +2745,7 @@ async function openLocalRuntime(settings, options2 = {}) {
2310
2745
  const version = Number(
2311
2746
  database.prepare("PRAGMA user_version").get()?.user_version
2312
2747
  );
2313
- if (!Number.isInteger(version) || version < 0 || version > 2)
2748
+ if (!Number.isInteger(version) || version < 0 || version > 3)
2314
2749
  throw Error("LOCAL_SCHEMA_UNSUPPORTED");
2315
2750
  if (version < 1) database.exec(migrations[0]);
2316
2751
  if (version < 2) database.exec(migrations[1]);
@@ -2329,6 +2764,34 @@ async function openLocalRuntime(settings, options2 = {}) {
2329
2764
  const db = adapter(database);
2330
2765
  const env = { DB: db, REBUT_CONFIG: JSON.stringify(config) };
2331
2766
  const profiles = new ProfileRegistry(db, config.profiles);
2767
+ const ledger = new Ledger(db);
2768
+ function setFirstCustomBudgetCycle(day, now) {
2769
+ database.exec("BEGIN IMMEDIATE;");
2770
+ try {
2771
+ const version = Number(
2772
+ database.prepare("PRAGMA user_version").get()?.user_version
2773
+ );
2774
+ if (version === 3) {
2775
+ database.exec("COMMIT;");
2776
+ return false;
2777
+ }
2778
+ if (version !== 2) throw Error("LOCAL_SCHEMA_UNSUPPORTED");
2779
+ database.exec(migrations[2]);
2780
+ const { sql, args } = monthlyCycleInsert(day, now);
2781
+ if (!database.prepare(sql).run(...args).changes) {
2782
+ database.exec("ROLLBACK;");
2783
+ return true;
2784
+ }
2785
+ database.exec("PRAGMA user_version=3; COMMIT;");
2786
+ return true;
2787
+ } catch (error) {
2788
+ try {
2789
+ database.exec("ROLLBACK;");
2790
+ } catch {
2791
+ }
2792
+ throw error;
2793
+ }
2794
+ }
2332
2795
  const shutdown = new AbortController();
2333
2796
  const http = createNodeHttpTransport();
2334
2797
  const providerFetch = options2.fetcher ?? http.fetch;
@@ -2338,6 +2801,13 @@ async function openLocalRuntime(settings, options2 = {}) {
2338
2801
  path: path2,
2339
2802
  config,
2340
2803
  profiles,
2804
+ budget: () => ledger.budget(config.limits),
2805
+ async scheduleMonthlyCycle(day, now = /* @__PURE__ */ new Date()) {
2806
+ if (!validMonthlyStartDay(day)) throw Error("INVALID_MONTHLY_START_DAY");
2807
+ if (day !== 1 && setFirstCustomBudgetCycle(day, now))
2808
+ return ledger.monthlyCycleSetting(day);
2809
+ return ledger.scheduleMonthlyCycle(day, now);
2810
+ },
2341
2811
  async review(raw, signal) {
2342
2812
  if (shutdown.signal.aborted) throw Error("LOCAL_RUNTIME_CLOSED");
2343
2813
  const work = handleReview(raw, PRINCIPAL, env, {
@@ -2390,7 +2860,7 @@ async function openLocalRuntime(settings, options2 = {}) {
2390
2860
  }
2391
2861
  };
2392
2862
  }
2393
- var toolResult = (value) => ({
2863
+ var toolResult2 = (value) => ({
2394
2864
  content: [
2395
2865
  {
2396
2866
  type: "text",
@@ -2398,13 +2868,14 @@ var toolResult = (value) => ({
2398
2868
  }
2399
2869
  ]
2400
2870
  });
2401
- async function localMcpServer(runtime, settings) {
2871
+ async function localMcpServer(runtime, settings, client) {
2872
+ const clientProfile = client && settings.clientProfiles?.[client];
2402
2873
  const records = await runtime.profiles.list();
2403
- const hasPreference = !!(settings.defaultModel || settings.defaultReasoning || settings.defaultProfile);
2874
+ const hasPreference = !!(settings.defaultModel || settings.defaultReasoning || settings.defaultProfile || clientProfile);
2404
2875
  let preferred, unavailable = false;
2405
2876
  try {
2406
2877
  preferred = resolveProfile(records, {
2407
- profile: settings.defaultProfile,
2878
+ profile: clientProfile ?? settings.defaultProfile,
2408
2879
  provider: settings.provider,
2409
2880
  model: settings.defaultModel || settings.defaultReasoning ? settings.defaultModel ?? records.find(
2410
2881
  (r) => r.id === (settings.provider === "anthropic" ? "claude-medium" : "astra-medium") && r.enabled
@@ -2414,61 +2885,63 @@ async function localMcpServer(runtime, settings) {
2414
2885
  } catch {
2415
2886
  unavailable = hasPreference;
2416
2887
  }
2417
- const server = new McpServer2({ name: "rebut-mcp", version: "0.3.2" });
2418
- server.registerTool(
2419
- "review",
2420
- {
2421
- description: `Explicit opt-in provider review. Local per-device ledger; budgets are not shared with another machine or Worker. Keep the original request_id and backend after uncertainty; never replay another backend's uncertain request here. ${preferred ? "Preferred profile: " + preferred : unavailable ? "Configured profile is unavailable." : "Select an enabled profile explicitly."}`,
2422
- inputSchema: ReviewInputSchema
2423
- },
2424
- async (input, extra) => {
2425
- try {
2426
- return toolResult(await runtime.review(input, extra.mcpReq.signal));
2427
- } catch (error) {
2428
- if (error instanceof ProviderKeyUnavailable)
2429
- return {
2430
- isError: true,
2431
- ...toolResult({
2432
- status: "provider_key_unavailable",
2433
- message: "Check local credentials with rebut doctor and query the original ID before any further paid invocation."
2434
- })
2435
- };
2888
+ const server = new McpServer2({ name: "rebut-mcp", version: "0.4.0" });
2889
+ const review = async (input, signal) => {
2890
+ try {
2891
+ return toolResult2(await runtime.review(input, signal));
2892
+ } catch (error) {
2893
+ if (error instanceof ProviderKeyUnavailable)
2436
2894
  return {
2437
2895
  isError: true,
2438
- ...toolResult({
2439
- status: "request_failed",
2440
- message: "Query review_status with the same request_id before any further paid invocation."
2896
+ ...toolResult2({
2897
+ status: "provider_key_unavailable",
2898
+ message: "Check local credentials with rebut doctor and query the original ID before any further paid invocation."
2441
2899
  })
2442
2900
  };
2443
- }
2901
+ return {
2902
+ isError: true,
2903
+ ...toolResult2({
2904
+ status: "request_failed",
2905
+ message: "Query review_status with the same request_id before any further paid invocation."
2906
+ })
2907
+ };
2444
2908
  }
2909
+ };
2910
+ server.registerTool(
2911
+ "review",
2912
+ {
2913
+ description: `Explicit opt-in provider review. Local per-device ledger; budgets are not shared with another machine or Worker. Keep the original request_id and backend after uncertainty; never replay another backend's uncertain request here. ${preferred ? "Preferred profile: " + preferred : unavailable ? "Configured profile is unavailable." : "Select an enabled profile explicitly."}${client ? " For new bundles, use rebut collect --client " + client + " to apply this client default." : ""}`,
2914
+ inputSchema: ReviewInputSchema
2915
+ },
2916
+ (input, extra) => review(input, extra.mcpReq.signal)
2445
2917
  );
2446
2918
  server.registerTool(
2447
2919
  "review_status",
2448
2920
  {
2449
2921
  description: "Read local metadata only; no paid execution and no review-body replay.",
2450
- inputSchema: z7.object({
2451
- request_id: z7.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/)
2922
+ inputSchema: z8.object({
2923
+ request_id: z8.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/)
2452
2924
  }).strict()
2453
2925
  },
2454
2926
  async ({ request_id }) => {
2455
2927
  try {
2456
- return toolResult(await runtime.status(request_id));
2928
+ return toolResult2(await runtime.status(request_id));
2457
2929
  } catch {
2458
2930
  return {
2459
2931
  isError: true,
2460
- ...toolResult({ status: "status_unavailable" })
2932
+ ...toolResult2({ status: "status_unavailable" })
2461
2933
  };
2462
2934
  }
2463
2935
  }
2464
2936
  );
2937
+ registerReviewPair(server, review, runtime.config.limits.maxConcurrent);
2465
2938
  return server;
2466
2939
  }
2467
- async function serveLocalStdio(settings) {
2940
+ async function serveLocalStdio(settings, client) {
2468
2941
  const runtime = await openLocalRuntime(settings);
2469
2942
  let server;
2470
2943
  try {
2471
- server = await localMcpServer(runtime, settings);
2944
+ server = await localMcpServer(runtime, settings, client);
2472
2945
  } catch (error) {
2473
2946
  await runtime.close();
2474
2947
  throw error;
@@ -2516,11 +2989,14 @@ rebut set vaultwarden-item NAME
2516
2989
  rebut set vaultwarden-api-key-item NAME
2517
2990
  rebut set daily-budget USD
2518
2991
  rebut set monthly-budget USD
2992
+ rebut budget Show budget and unresolved concurrency (Worker admin)
2993
+ rebut budget set-start-day DAY Set a monthly UTC start day once per ledger (1\u201328)
2519
2994
  rebut set request-budget USD
2520
2995
  rebut set vaultwarden-admin-item NAME
2521
2996
  rebut set model MODEL
2522
2997
  rebut set reasoning EFFORT
2523
- rebut set profile PROFILE_ID
2998
+ rebut set profile PROFILE_ID [--client codex|claude]
2999
+ rebut set profile --client codex|claude --clear
2524
3000
  rebut set admin-token [--stdin]
2525
3001
  rebut profile list
2526
3002
  rebut profile set ID [--provider openai|anthropic] --model MODEL --reasoning EFFORT --max-output-tokens N --input-usd-per-million USD --output-usd-per-million USD --price-version VERSION [--if-revision N]
@@ -2528,12 +3004,12 @@ rebut profile remove ID [--if-revision N]
2528
3004
  rebut set token [--stdin] Hidden input; never pass a token as an argument
2529
3005
  rebut setup --client codex|claude [--codex-home PATH | --claude-config PATH] [--replace]
2530
3006
  rebut remove --client codex|claude [--codex-home PATH | --claude-config PATH] [--replace]
2531
- rebut mcp Start the local server or Worker bridge
2532
- rebut doctor [--connect] [--provider] Check selected backend; --connect lists tools, never calls a model
3007
+ rebut mcp [--client codex|claude] Start the local server or Worker bridge
3008
+ rebut doctor [--connect] [--provider] [--client codex|claude] Check selected backend; --connect lists tools, never calls a model
2533
3009
  rebut status --pending Local reserved/unknown metadata only
2534
3010
  rebut status REQUEST_ID Free metadata query
2535
3011
  rebut review Explicit paid review; JSON bundle on stdin
2536
- rebut collect --root PATH --request-id ID --requirements TEXT [--profile ID] -- FILE...
3012
+ rebut collect --root PATH --request-id ID --requirements TEXT [--profile ID] [--client codex|claude] -- FILE...
2537
3013
  rebut --version
2538
3014
 
2539
3015
  New installs run locally with your selected provider API key. Host registration does not select the provider. No Cloudflare account is required.
@@ -2557,6 +3033,11 @@ function options(args, opts, positionals = false) {
2557
3033
  throw new CliError("Invalid arguments. Run rebut --help.");
2558
3034
  }
2559
3035
  }
3036
+ function selectedClient(value) {
3037
+ if (value === void 0 || value === "codex" || value === "claude")
3038
+ return value;
3039
+ throw new CliError("Specify --client codex or claude.");
3040
+ }
2560
3041
  async function stdin(max = 16e4) {
2561
3042
  const chunks = [];
2562
3043
  let size = 0;
@@ -2609,7 +3090,7 @@ async function hidden(label = "Bearer token") {
2609
3090
  }
2610
3091
  async function packageVersion() {
2611
3092
  return JSON.parse(
2612
- await readFile4(new URL("../package.json", import.meta.url), "utf8")
3093
+ await readFile3(new URL("../package.json", import.meta.url), "utf8")
2613
3094
  ).version;
2614
3095
  }
2615
3096
  async function runCli(args) {
@@ -2665,6 +3146,47 @@ async function runCli(args) {
2665
3146
  );
2666
3147
  return;
2667
3148
  }
3149
+ if (key === "profile") {
3150
+ const parsed = options(
3151
+ values,
3152
+ {
3153
+ client: { type: "string" },
3154
+ clear: { type: "boolean" }
3155
+ },
3156
+ true
3157
+ );
3158
+ const client = selectedClient(parsed.values.client);
3159
+ const [value2] = parsed.positionals;
3160
+ if (parsed.values.clear) {
3161
+ if (!client || parsed.positionals.length)
3162
+ throw new CliError(
3163
+ "Use rebut set profile --client codex|claude --clear."
3164
+ );
3165
+ if (settings.clientProfiles) {
3166
+ delete settings.clientProfiles[client];
3167
+ if (!settings.clientProfiles.codex && !settings.clientProfiles.claude)
3168
+ delete settings.clientProfiles;
3169
+ }
3170
+ } else {
3171
+ if (parsed.positionals.length !== 1 || !value2 || !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(value2))
3172
+ throw new CliError("Expected one valid profile ID.");
3173
+ if (client)
3174
+ settings.clientProfiles = {
3175
+ ...settings.clientProfiles,
3176
+ [client]: value2
3177
+ };
3178
+ else {
3179
+ settings.defaultProfile = value2;
3180
+ delete settings.defaultModel;
3181
+ delete settings.defaultReasoning;
3182
+ }
3183
+ }
3184
+ await writeSettings(settings);
3185
+ process.stdout.write(
3186
+ "Profile preference saved. Restart the MCP host. Re-register existing hosts to enable client selection or refresh forwarded API key environment variables.\n"
3187
+ );
3188
+ return;
3189
+ }
2668
3190
  if (values.length !== 1)
2669
3191
  throw new CliError(
2670
3192
  "Expected one configuration value. Tokens must use hidden input."
@@ -2746,12 +3268,6 @@ async function runCli(args) {
2746
3268
  throw new CliError("Invalid reasoning effort.");
2747
3269
  settings.defaultReasoning = value;
2748
3270
  delete settings.defaultProfile;
2749
- } else if (key === "profile") {
2750
- if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(value))
2751
- throw new CliError("Invalid profile ID.");
2752
- settings.defaultProfile = value;
2753
- delete settings.defaultModel;
2754
- delete settings.defaultReasoning;
2755
3271
  } else throw new CliError("Unknown configuration key.");
2756
3272
  await writeSettings(settings);
2757
3273
  process.stdout.write(
@@ -2766,9 +3282,8 @@ async function runCli(args) {
2766
3282
  "claude-config": { type: "string" },
2767
3283
  replace: { type: "boolean" }
2768
3284
  });
2769
- const client = parsed.values.client;
2770
- if (client !== "codex" && client !== "claude")
2771
- throw new CliError("Specify --client codex or claude.");
3285
+ const client = selectedClient(parsed.values.client);
3286
+ if (!client) throw new CliError("Specify --client codex or claude.");
2772
3287
  if (client === "claude" && parsed.values["codex-home"] || client === "codex" && parsed.values["claude-config"])
2773
3288
  throw new CliError("Use only the selected host configuration option.");
2774
3289
  if (command === "setup" && mode === "worker" && !settings.endpoint)
@@ -2777,10 +3292,17 @@ async function runCli(args) {
2777
3292
  process.argv[1] || fileURLToPath(new URL("../bin/rebut.mjs", import.meta.url))
2778
3293
  );
2779
3294
  let keyProvider = settings.provider ?? "openai";
2780
- if (command === "setup" && mode === "local" && settings.secretStore === "env") {
3295
+ let forwardApiKeyEnv = mode === "local" && settings.secretStore === "env";
3296
+ if (command === "setup" && forwardApiKeyEnv) {
2781
3297
  try {
2782
- keyProvider = (await preferred()).provider;
3298
+ keyProvider = (await preferred(void 0, client)).provider;
2783
3299
  } catch {
3300
+ if (settings.clientProfiles?.[client]) {
3301
+ forwardApiKeyEnv = false;
3302
+ process.stderr.write(
3303
+ "Client default could not be resolved. No provider key variable was added to the registration.\n"
3304
+ );
3305
+ }
2784
3306
  }
2785
3307
  }
2786
3308
  const value = {
@@ -2789,7 +3311,7 @@ async function runCli(args) {
2789
3311
  entrypoint,
2790
3312
  replace: parsed.values.replace,
2791
3313
  forwardTokenEnv: mode === "worker" && settings.secretStore === "env",
2792
- forwardApiKeyEnv: mode === "local" && settings.secretStore === "env",
3314
+ forwardApiKeyEnv,
2793
3315
  apiKeyEnv: providerEnvName(settings, keyProvider),
2794
3316
  configDir: process.env.REBUT_CONFIG_DIR
2795
3317
  };
@@ -2805,7 +3327,8 @@ async function runCli(args) {
2805
3327
  root: { type: "string" },
2806
3328
  "request-id": { type: "string" },
2807
3329
  requirements: { type: "string" },
2808
- profile: { type: "string" }
3330
+ profile: { type: "string" },
3331
+ client: { type: "string" }
2809
3332
  },
2810
3333
  true
2811
3334
  );
@@ -2813,7 +3336,16 @@ async function runCli(args) {
2813
3336
  throw new CliError(
2814
3337
  "Collect requires root, request-id, requirements and explicit source files."
2815
3338
  );
2816
- const chosen = await preferred(p.values.profile);
3339
+ const client = selectedClient(p.values.client);
3340
+ if (!client && p.values.profile === void 0 && (settings.clientProfiles?.codex || settings.clientProfiles?.claude)) {
3341
+ process.stderr.write(
3342
+ "No client selected. This bundle uses the shared review preference. Pass --client codex or --client claude to use a client default.\n"
3343
+ );
3344
+ }
3345
+ const chosen = await preferred(
3346
+ p.values.profile,
3347
+ client
3348
+ );
2817
3349
  output(
2818
3350
  await collect(
2819
3351
  p.values.root,
@@ -2826,7 +3358,8 @@ async function runCli(args) {
2826
3358
  );
2827
3359
  return;
2828
3360
  }
2829
- async function preferred(explicitProfile) {
3361
+ async function preferred(explicitProfile, client) {
3362
+ const selectedProfile = explicitProfile ?? (client && settings.clientProfiles?.[client]);
2830
3363
  if (mode === "worker" && !settings.endpoint)
2831
3364
  throw new CliError(
2832
3365
  "Set the Worker endpoint before selecting server models."
@@ -2840,7 +3373,7 @@ async function runCli(args) {
2840
3373
  )?.profile?.model;
2841
3374
  const id = resolveProfile(
2842
3375
  records,
2843
- explicitProfile !== void 0 ? { profile: explicitProfile } : {
3376
+ selectedProfile !== void 0 ? { profile: selectedProfile } : {
2844
3377
  provider: settings.provider,
2845
3378
  profile: settings.defaultProfile,
2846
3379
  model: settings.defaultModel || settings.defaultReasoning ? model : void 0,
@@ -2856,6 +3389,45 @@ async function runCli(args) {
2856
3389
  revision: selected.revision
2857
3390
  };
2858
3391
  }
3392
+ if (command === "budget") {
3393
+ let day;
3394
+ if (rest.length > 0) {
3395
+ if (rest.length !== 2 || rest[0] !== "set-start-day" || !/^[0-9]{1,2}$/.test(rest[1]))
3396
+ throw new CliError(
3397
+ "Use rebut budget or rebut budget set-start-day DAY."
3398
+ );
3399
+ day = Number(rest[1]);
3400
+ if (!validMonthlyStartDay(day))
3401
+ throw new CliError("Expected a monthly start day from 1 to 28.");
3402
+ }
3403
+ if (mode === "local") {
3404
+ if (day === void 0)
3405
+ output(await withLocal((runtime) => runtime.budget()));
3406
+ else {
3407
+ const result = await withLocal(
3408
+ (runtime) => runtime.scheduleMonthlyCycle(day)
3409
+ );
3410
+ if (result.status === "conflict")
3411
+ throw new CliError(
3412
+ "Budget schedule already set or the calendar boundary changed; run rebut budget."
3413
+ );
3414
+ output(result);
3415
+ }
3416
+ } else {
3417
+ if (!settings.endpoint)
3418
+ throw new CliError("Set the Worker endpoint first.");
3419
+ output(
3420
+ await workerBudget(
3421
+ {
3422
+ endpoint: settings.endpoint,
3423
+ loadToken: () => loadToken(settings, "admin")
3424
+ },
3425
+ day
3426
+ )
3427
+ );
3428
+ }
3429
+ return;
3430
+ }
2859
3431
  if (command === "profile") {
2860
3432
  if (mode === "local") {
2861
3433
  output(
@@ -2879,40 +3451,46 @@ async function runCli(args) {
2879
3451
  if (command === "doctor") {
2880
3452
  const p = options(rest, {
2881
3453
  connect: { type: "boolean" },
2882
- provider: { type: "boolean" }
3454
+ provider: { type: "boolean" },
3455
+ client: { type: "string" }
2883
3456
  });
3457
+ const client = selectedClient(p.values.client);
3458
+ const clientProfile = client && settings.clientProfiles?.[client];
2884
3459
  if (p.values.provider && mode !== "local")
2885
3460
  throw new CliError(
2886
3461
  "Provider metadata diagnostics are local mode only; Worker credentials stay on the Worker."
2887
3462
  );
2888
3463
  let chosen;
2889
- if (mode === "local" && (p.values.connect || p.values.provider)) {
3464
+ if ((mode === "local" || client !== void 0) && (p.values.connect || p.values.provider)) {
2890
3465
  try {
2891
- chosen = await preferred();
3466
+ chosen = await preferred(void 0, client);
2892
3467
  } catch {
2893
3468
  }
2894
3469
  }
2895
- const activeProvider = chosen?.provider ?? settings.provider ?? "openai";
2896
- let credentialAvailable = false;
3470
+ const activeProvider = chosen?.provider ?? (clientProfile ? void 0 : settings.provider ?? "openai");
3471
+ let credentialAvailable;
2897
3472
  let providerKey;
2898
- try {
2899
- providerKey = await loadToken(
2900
- settings,
2901
- mode === "local" ? "provider" : "review",
2902
- activeProvider
2903
- );
2904
- credentialAvailable = true;
2905
- } catch {
3473
+ if (mode === "worker" || activeProvider) {
3474
+ credentialAvailable = false;
3475
+ try {
3476
+ providerKey = await loadToken(
3477
+ settings,
3478
+ mode === "local" ? "provider" : "review",
3479
+ activeProvider
3480
+ );
3481
+ credentialAvailable = true;
3482
+ } catch {
3483
+ }
2906
3484
  }
2907
3485
  const report = {
2908
3486
  configPath: settingsPath(),
2909
3487
  mode,
2910
3488
  provider: activeProvider,
2911
- ...mode === "local" ? {
3489
+ ...mode === "local" || client !== void 0 ? {
2912
3490
  profileResolution: !(p.values.connect || p.values.provider) ? "not_checked" : chosen ? "resolved" : "unavailable"
2913
3491
  } : {},
2914
3492
  keyConfigurationProvider: settings.provider ?? "openai",
2915
- ...mode === "local" && settings.secretStore === "env" ? { apiKeyEnv: providerEnvName(settings, activeProvider) } : {},
3493
+ ...mode === "local" && settings.secretStore === "env" && activeProvider ? { apiKeyEnv: providerEnvName(settings, activeProvider) } : {},
2916
3494
  ...mode === "local" ? {
2917
3495
  ledgerPath: join6(resolve5(localDirectory()), "ledger.sqlite"),
2918
3496
  budgetScope: "this local data directory only"
@@ -2920,12 +3498,14 @@ async function runCli(args) {
2920
3498
  endpointConfigured: !!settings.endpoint,
2921
3499
  secretStore: settings.secretStore,
2922
3500
  credentialAvailable,
2923
- defaultModel: settings.defaultModel,
2924
- defaultReasoning: settings.defaultReasoning,
2925
- defaultProfile: settings.defaultProfile
3501
+ ...client ? { client } : {},
3502
+ defaultModel: clientProfile ? void 0 : settings.defaultModel,
3503
+ defaultReasoning: clientProfile ? void 0 : settings.defaultReasoning,
3504
+ defaultProfile: clientProfile ?? settings.defaultProfile,
3505
+ clientProfiles: settings.clientProfiles
2926
3506
  };
2927
3507
  if (p.values.provider) {
2928
- chosen ??= await preferred();
3508
+ chosen ??= await preferred(void 0, client);
2929
3509
  report.providerDiagnostic = providerKey ? await providerDiagnostic(chosen, providerKey) : {
2930
3510
  provider: chosen.provider,
2931
3511
  model: chosen.model,
@@ -2934,6 +3514,8 @@ async function runCli(args) {
2934
3514
  report.providerDiagnosticScope = "Metadata reachability only; not generation permission, credits, rate limits, geo, structured-output support, or quality.";
2935
3515
  }
2936
3516
  if (p.values.connect) {
3517
+ if (mode === "local" && clientProfile && !chosen)
3518
+ throw new CliError("The configured client profile is unavailable.");
2937
3519
  if (mode === "worker" && !settings.endpoint || !credentialAvailable)
2938
3520
  throw new CliError(
2939
3521
  "Endpoint or credentials unavailable. Check your selected secret store."
@@ -2941,35 +3523,35 @@ async function runCli(args) {
2941
3523
  if (mode === "local") {
2942
3524
  const version = await packageVersion();
2943
3525
  report.localTools = await withLocal(async (runtime) => {
2944
- const server = await localMcpServer(runtime, settings);
3526
+ const server = await localMcpServer(runtime, settings, client);
2945
3527
  const { Client: Client2 } = await import("@modelcontextprotocol/client");
2946
3528
  const { InMemoryTransport } = await import("@modelcontextprotocol/server");
2947
3529
  const [host, local] = InMemoryTransport.createLinkedPair();
2948
- const client2 = new Client2({
3530
+ const mcpClient2 = new Client2({
2949
3531
  name: "rebut-local-doctor",
2950
3532
  version
2951
3533
  });
2952
3534
  try {
2953
- await Promise.all([client2.connect(host), server.connect(local)]);
2954
- return (await client2.listTools()).tools.map((t) => t.name);
3535
+ await Promise.all([mcpClient2.connect(host), server.connect(local)]);
3536
+ return (await mcpClient2.listTools()).tools.map((t) => t.name);
2955
3537
  } finally {
2956
- await client2.close();
3538
+ await mcpClient2.close();
2957
3539
  await server.close();
2958
3540
  }
2959
3541
  });
2960
3542
  output(report);
2961
3543
  return;
2962
3544
  }
2963
- const client = await connectRemote({
3545
+ const mcpClient = await connectRemote({
2964
3546
  endpoint: settings.endpoint,
2965
3547
  loadToken: () => loadToken(settings)
2966
3548
  });
2967
3549
  try {
2968
- report.remoteTools = (await client.listTools()).tools.map(
3550
+ report.remoteTools = (await mcpClient.listTools()).tools.map(
2969
3551
  (t) => t.name
2970
3552
  );
2971
3553
  } finally {
2972
- await client.close();
3554
+ await mcpClient.close();
2973
3555
  }
2974
3556
  }
2975
3557
  output(report);
@@ -2982,21 +3564,31 @@ async function runCli(args) {
2982
3564
  loadToken: () => loadToken(settings)
2983
3565
  };
2984
3566
  if (command === "mcp") {
2985
- if (rest.length) throw new CliError("Unexpected mcp arguments.");
3567
+ const parsed = options(rest, { client: { type: "string" } });
3568
+ const client = selectedClient(parsed.values.client);
3569
+ const clientProfile = client && settings.clientProfiles?.[client];
2986
3570
  if (mode === "local") {
2987
- await serveLocalStdio(settings);
3571
+ await serveLocalStdio(settings, client);
2988
3572
  return;
2989
3573
  }
2990
3574
  let preferredProfile;
2991
3575
  let reviewUnavailable = false;
2992
- if (settings.defaultModel || settings.defaultReasoning || settings.defaultProfile) {
3576
+ let clientProfileUnavailable = false;
3577
+ if (settings.defaultModel || settings.defaultReasoning || settings.defaultProfile || clientProfile) {
2993
3578
  try {
2994
- preferredProfile = await preferred();
3579
+ preferredProfile = await preferred(void 0, client);
2995
3580
  } catch {
2996
- reviewUnavailable = true;
3581
+ clientProfileUnavailable = clientProfile !== void 0;
3582
+ reviewUnavailable = !clientProfileUnavailable;
2997
3583
  }
2998
3584
  }
2999
- await serveStdio({ ...remote, preferredProfile, reviewUnavailable });
3585
+ await serveStdio({
3586
+ ...remote,
3587
+ client,
3588
+ preferredProfile,
3589
+ reviewUnavailable,
3590
+ clientProfileUnavailable
3591
+ });
3000
3592
  return;
3001
3593
  }
3002
3594
  if (command === "status" && rest.length === 1 && rest[0] === "--pending") {
@@ -3066,7 +3658,7 @@ function safeError(error) {
3066
3658
  LOCAL_REVIEW_ABORTED: "Local review cancelled before execution; query the original request ID.",
3067
3659
  PROVIDER_KEY_UNAVAILABLE: "Configure the selected profile provider key for local mode.",
3068
3660
  SETTINGS_INVALID: "Invalid local settings file.",
3069
- SETTINGS_UNSAFE: "Local settings path is unsafe.",
3661
+ SETTINGS_UNSAFE: "Local settings path is unsafe. Use a user-owned config.json with mode 0600 in a directory you own, and check the parent directory permissions.",
3070
3662
  TOKEN_INVALID: "Credential must contain 32\u2013512 non-space ASCII characters.",
3071
3663
  KEYCHAIN_UNSUPPORTED: "Keychain backend requires macOS. Select an explicit supported secret store.",
3072
3664
  KEYCHAIN_UNAVAILABLE: "Login Keychain unavailable. Authorize it locally or explicitly select the existing Vaultwarden backend.",