edhvault-mcp 0.2.15 → 0.2.17

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.
Files changed (3) hide show
  1. package/README.md +16 -1
  2. package/dist/cli.js +1690 -163
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -606,6 +606,26 @@ function additionalData(header, aad) {
606
606
  out.set(extra, header.length);
607
607
  return out;
608
608
  }
609
+ async function seal(plain2, key, opts = {}) {
610
+ const gzip = (opts.compress ?? true) && canGzip();
611
+ const body = gzip ? await pipeThrough(plain2, new CompressionStream("gzip")) : plain2;
612
+ const header = new Uint8Array([VERSION2, gzip ? FLAG_GZIP : 0]);
613
+ const iv = new Uint8Array(IV_BYTES);
614
+ crypto.getRandomValues(iv);
615
+ const ck = await importKey(key, "encrypt");
616
+ const ct = new Uint8Array(
617
+ await crypto.subtle.encrypt(
618
+ { name: "AES-GCM", iv, additionalData: additionalData(header, opts.aad) },
619
+ ck,
620
+ body
621
+ )
622
+ );
623
+ const out = new Uint8Array(HEADER_BYTES + IV_BYTES + ct.length);
624
+ out.set(header, 0);
625
+ out.set(iv, HEADER_BYTES);
626
+ out.set(ct, HEADER_BYTES + IV_BYTES);
627
+ return out;
628
+ }
609
629
  async function open(sealed, key, opts = {}) {
610
630
  if (sealed.length < HEADER_BYTES + IV_BYTES + TAG_BYTES) {
611
631
  throw new SealedBoxError("malformed", "This data is too short to be a sealed box.");
@@ -640,6 +660,9 @@ async function open(sealed, key, opts = {}) {
640
660
  throw new SealedBoxError("malformed", "The decrypted data couldn't be unpacked.");
641
661
  }
642
662
  }
663
+ async function sealText(text, key, opts = {}) {
664
+ return seal(new TextEncoder().encode(text), key, opts);
665
+ }
643
666
  async function openText(sealed, key, opts = {}) {
644
667
  return new TextDecoder().decode(await open(sealed, key, opts));
645
668
  }
@@ -815,6 +838,19 @@ async function errorOf(res) {
815
838
  return null;
816
839
  }
817
840
  }
841
+ function frame(header, parts) {
842
+ const head = new TextEncoder().encode(JSON.stringify(header));
843
+ const total = 4 + head.length + parts.reduce((n, p) => n + p.byteLength, 0);
844
+ const out = new Uint8Array(total);
845
+ new DataView(out.buffer).setUint32(0, head.length);
846
+ out.set(head, 4);
847
+ let at = 4 + head.length;
848
+ for (const p of parts) {
849
+ out.set(p, at);
850
+ at += p.byteLength;
851
+ }
852
+ return out;
853
+ }
818
854
  function unframe(buf) {
819
855
  if (buf.length < 4) return null;
820
856
  const len = new DataView(buf.buffer, buf.byteOffset).getUint32(0);
@@ -827,9 +863,12 @@ function unframe(buf) {
827
863
  }
828
864
  }
829
865
  async function agentFetchBundle(token, t = {}) {
866
+ return (await agentFetchBundleInfo(token, t)).bundle;
867
+ }
868
+ async function agentFetchBundleInfo(token, t = {}) {
830
869
  const res = await call(t, `${SYNC_AGENT_API}/bundle`, { method: "GET", headers: agentHeaders(token) });
831
870
  if (!res.ok) throw new SyncHttpError("server", `Unexpected answer (${res.status}).`);
832
- return new Uint8Array(await res.arrayBuffer());
871
+ return { bundle: new Uint8Array(await res.arrayBuffer()), writes: res.headers.get("x-agent-writes") ?? "" };
833
872
  }
834
873
  async function agentFetchView(token, scope, etag, t = {}) {
835
874
  const res = await call(t, `${SYNC_AGENT_API}/view?scope=${encodeURIComponent(scope)}`, {
@@ -859,6 +898,24 @@ async function agentFetchObjects(token, scope, names, t = {}) {
859
898
  }
860
899
  return out;
861
900
  }
901
+ async function agentPostRequest(token, kind, sealed, t = {}) {
902
+ const res = await call(t, `${SYNC_AGENT_API}/request`, {
903
+ method: "POST",
904
+ headers: { ...agentHeaders(token), "content-type": "application/octet-stream" },
905
+ body: frame({ k: kind }, [sealed])
906
+ });
907
+ if (res.status === 409 && await errorOf(res) === "too many pending") {
908
+ return { status: "full", maxPending: (await res.json()).maxPending };
909
+ }
910
+ if (!res.ok) throw new SyncHttpError("server", `Unexpected answer (${res.status}).`);
911
+ const body = await res.json();
912
+ return { status: "ok", id: body.id, expiresAt: body.expiresAt };
913
+ }
914
+ async function agentListRequests(token, t = {}) {
915
+ const res = await call(t, `${SYNC_AGENT_API}/requests`, { method: "GET", headers: agentHeaders(token) });
916
+ if (!res.ok) throw new SyncHttpError("server", `Unexpected answer (${res.status}).`);
917
+ return (await res.json()).requests;
918
+ }
862
919
  async function takePair(id, t = {}) {
863
920
  const res = await call(t, `${SYNC_PAIR_API}/${id}`, { method: "GET" });
864
921
  if (res.status === 404) return null;
@@ -7920,9 +7977,9 @@ var require_papaparse = __commonJS({
7920
7977
  };
7921
7978
  Papa.parse(f.file, f.instanceConfig);
7922
7979
  }
7923
- function error62(name, file3, elem, reason) {
7980
+ function error62(name, file4, elem, reason) {
7924
7981
  if (isFunction(options.error))
7925
- options.error({ name }, file3, elem, reason);
7982
+ options.error({ name }, file4, elem, reason);
7926
7983
  }
7927
7984
  function fileComplete() {
7928
7985
  queue.splice(0, 1);
@@ -8297,9 +8354,9 @@ var require_papaparse = __commonJS({
8297
8354
  ChunkStreamer.call(this, config2);
8298
8355
  var reader, slice;
8299
8356
  var usingAsyncReader = typeof FileReader !== "undefined";
8300
- this.stream = function(file3) {
8301
- this._input = file3;
8302
- slice = file3.slice || file3.webkitSlice || file3.mozSlice;
8357
+ this.stream = function(file4) {
8358
+ this._input = file4;
8359
+ slice = file4.slice || file4.webkitSlice || file4.mozSlice;
8303
8360
  if (usingAsyncReader) {
8304
8361
  reader = new FileReader();
8305
8362
  reader.onload = bindFunction(this._chunkLoaded, this);
@@ -9254,23 +9311,635 @@ var init_printings = __esm({
9254
9311
  });
9255
9312
 
9256
9313
  // ../src/lib/savedDecks/tags.ts
9314
+ function normalizeTags(input2) {
9315
+ const seenLower = /* @__PURE__ */ new Set();
9316
+ const out = [];
9317
+ for (const raw of input2) {
9318
+ if (typeof raw !== "string") continue;
9319
+ const stripped = raw.replace(/[,\n\r]/g, " ");
9320
+ const trimmed = stripped.trim();
9321
+ if (!trimmed) continue;
9322
+ const truncated = trimmed.length > MAX_TAG_LENGTH ? trimmed.slice(0, MAX_TAG_LENGTH) : trimmed;
9323
+ const lower = truncated.toLowerCase();
9324
+ if (seenLower.has(lower)) continue;
9325
+ seenLower.add(lower);
9326
+ out.push(truncated);
9327
+ if (out.length >= MAX_TAGS_PER_DECK) break;
9328
+ }
9329
+ return out;
9330
+ }
9331
+ var MAX_TAG_LENGTH, MAX_TAGS_PER_DECK;
9257
9332
  var init_tags = __esm({
9258
9333
  "../src/lib/savedDecks/tags.ts"() {
9259
9334
  "use strict";
9260
9335
  init_storage();
9336
+ MAX_TAG_LENGTH = 24;
9337
+ MAX_TAGS_PER_DECK = 12;
9261
9338
  }
9262
9339
  });
9263
9340
 
9264
9341
  // ../src/lib/deckPlan/reducer.ts
9342
+ function commanderDeckKeys(commanders) {
9343
+ const oracleIds = /* @__PURE__ */ new Set();
9344
+ const slugs = /* @__PURE__ */ new Set();
9345
+ for (const c of commanders) {
9346
+ if (c.oracleId) oracleIds.add(c.oracleId);
9347
+ if (c.name) {
9348
+ slugs.add(toEdhrecSlug(c.name));
9349
+ slugs.add(toEdhrecSlug(c.name, { joined: true }));
9350
+ }
9351
+ }
9352
+ return { oracleIds, slugs };
9353
+ }
9354
+ function reconcileCommandersOutOf99(state, commanders) {
9355
+ const { oracleIds, slugs } = commanderDeckKeys(commanders);
9356
+ let { assignments, purchases, basicQuantities, purchaseQuantities, considering, sideboard } = state;
9357
+ let changed = false;
9358
+ for (const oid of oracleIds) {
9359
+ if (assignments.has(oid)) {
9360
+ assignments = new Map(assignments);
9361
+ assignments.delete(oid);
9362
+ changed = true;
9363
+ }
9364
+ if (basicQuantities.has(oid)) {
9365
+ basicQuantities = new Map(basicQuantities);
9366
+ basicQuantities.delete(oid);
9367
+ changed = true;
9368
+ }
9369
+ if (considering.has(oid)) {
9370
+ considering = new Set(considering);
9371
+ considering.delete(oid);
9372
+ changed = true;
9373
+ }
9374
+ if (sideboard.has(oid)) {
9375
+ sideboard = new Set(sideboard);
9376
+ sideboard.delete(oid);
9377
+ changed = true;
9378
+ }
9379
+ }
9380
+ for (const slug of slugs) {
9381
+ if (purchases.has(slug)) {
9382
+ purchases = new Map(purchases);
9383
+ purchases.delete(slug);
9384
+ changed = true;
9385
+ }
9386
+ if (purchaseQuantities.has(slug)) {
9387
+ purchaseQuantities = new Map(purchaseQuantities);
9388
+ purchaseQuantities.delete(slug);
9389
+ changed = true;
9390
+ }
9391
+ }
9392
+ return {
9393
+ assignments,
9394
+ purchases,
9395
+ basicQuantities,
9396
+ purchaseQuantities,
9397
+ considering,
9398
+ sideboard,
9399
+ changed
9400
+ };
9401
+ }
9402
+ function stampNewKeys(stamps, keys, had, now = Date.now()) {
9403
+ let out = stamps;
9404
+ for (const k of keys) {
9405
+ if (had(k)) continue;
9406
+ if (out === stamps) out = new Map(stamps);
9407
+ out.set(k, now);
9408
+ }
9409
+ return out;
9410
+ }
9411
+ function liveAddedAt(s) {
9412
+ const out = /* @__PURE__ */ new Map();
9413
+ for (const [k, t] of s.cardAddedAt) {
9414
+ if (s.assignments.has(k) || s.purchases.has(k) || s.considering.has(k) || s.sideboard.has(k)) {
9415
+ out.set(k, t);
9416
+ }
9417
+ }
9418
+ return out;
9419
+ }
9420
+ function toStored(s) {
9421
+ const cardAddedAt = liveAddedAt(s);
9422
+ return {
9423
+ assignments: s.assignments,
9424
+ purchases: s.purchases,
9425
+ basicQuantities: s.basicQuantities,
9426
+ purchaseQuantities: s.purchaseQuantities,
9427
+ considering: s.considering,
9428
+ sideboard: s.sideboard,
9429
+ // Omitted when empty, so a deck with no stamps (every older save, a
9430
+ // seeded/imported deck nobody has touched) stores exactly as before.
9431
+ ...cardAddedAt.size > 0 ? { cardAddedAt } : {},
9432
+ slotTargetOverrides: s.slotTargetOverrides,
9433
+ soloHalf: s.soloHalf,
9434
+ // Persist the editable-commander override only when one is set. Omitted
9435
+ // when [], so fresh / route-derived decks — and every older save — restore
9436
+ // to "no override" and resolve the commander from the route slug exactly
9437
+ // as before. See DeckPlanState.commanders.
9438
+ ...s.commanders.length > 0 ? { commanders: s.commanders } : {},
9439
+ foundCardIds: s.foundCardIds,
9440
+ expandedSlots: s.expandedSlots,
9441
+ useCardsInOtherDecks: s.useCardsInOtherDecks,
9442
+ useQualityFloor: s.useQualityFloor,
9443
+ rankMode: s.rankMode,
9444
+ targetBracket: s.targetBracket,
9445
+ comboTarget: s.comboTarget,
9446
+ priceCap: s.priceCap,
9447
+ totalBudget: s.totalBudget,
9448
+ editedSinceFill: s.editedSinceFill,
9449
+ savedAt: Date.now(),
9450
+ // Persist the fill provenance only when a fill has actually run. Fresh
9451
+ // / hand-built / reset decks omit these fields entirely, so they (and
9452
+ // every older save) restore to "no fill" and the "Why this deck?"
9453
+ // explainer stays correctly hidden.
9454
+ ...s.lastFillAction ? {
9455
+ lastFillAction: s.lastFillAction,
9456
+ skippedLowSignalCount: s.skippedLowSignalCount,
9457
+ lowSignalSlots: s.lowSignalSlots,
9458
+ ...s.fillActionAt != null ? { fillActionAt: s.fillActionAt } : {}
9459
+ } : {}
9460
+ };
9461
+ }
9462
+ function fromStored(stored) {
9463
+ return {
9464
+ assignments: stored.assignments ?? /* @__PURE__ */ new Map(),
9465
+ purchases: stored.purchases ?? /* @__PURE__ */ new Map(),
9466
+ basicQuantities: stored.basicQuantities ?? /* @__PURE__ */ new Map(),
9467
+ // Default empty for older saves — every buy restores to a single copy,
9468
+ // exactly the pre-feature behavior.
9469
+ purchaseQuantities: stored.purchaseQuantities ?? /* @__PURE__ */ new Map(),
9470
+ // Default empty for older saves (and every v1 deck) — no Considering zone.
9471
+ // Coerce to a fresh Set: `new Set(set)` clones, `new Set(array)` tolerates a
9472
+ // malformed/legacy array shape, so a bad persisted value can't reach the
9473
+ // reducer as a non-Set and crash `.has()` downstream.
9474
+ considering: new Set(stored.considering ?? []),
9475
+ // Same coercion story as considering — the Sideboard swap-box, absent on
9476
+ // every pre-feature save, restores empty.
9477
+ sideboard: new Set(stored.sideboard ?? []),
9478
+ // Older saves have no stamps; their cards sort last under "Recent". A
9479
+ // non-Map (malformed / hand-edited) value restores empty rather than
9480
+ // reaching the reducer as something without `.get`.
9481
+ cardAddedAt: stored.cardAddedAt instanceof Map ? stored.cardAddedAt : /* @__PURE__ */ new Map(),
9482
+ slotTargetOverrides: stored.slotTargetOverrides ?? {},
9483
+ soloHalf: stored.soloHalf ?? null,
9484
+ // Default [] for older saves + every v1 deck — "no override, resolve from
9485
+ // the route slug", the exact pre-feature commander. Coerced through a fresh
9486
+ // array so a malformed persisted value can't reach the reducer as a
9487
+ // non-array. Capped at 2 defensively (the UI never writes more).
9488
+ commanders: Array.isArray(stored.commanders) ? stored.commanders.slice(0, 2) : [],
9489
+ // A persisted commander is by definition committed — never provisional. The
9490
+ // flag is in-memory only (a `?commander=` seed the user hasn't acted on), so
9491
+ // it isn't serialized and always restores false.
9492
+ commandersProvisional: false,
9493
+ foundCardIds: stored.foundCardIds ?? /* @__PURE__ */ new Set(),
9494
+ expandedSlots: stored.expandedSlots ?? /* @__PURE__ */ new Set(),
9495
+ // Default true preserves pre-toggle behavior for older saves.
9496
+ useCardsInOtherDecks: stored.useCardsInOtherDecks ?? true,
9497
+ // Default true preserves the post-R1 floor-active behavior for older
9498
+ // saves (the floor shipped before this opt-out existed).
9499
+ useQualityFloor: stored.useQualityFloor ?? true,
9500
+ // Default "synergy" — the new R3 default — for saves without the
9501
+ // field. Deliberately NOT "preserve old popularity behavior": the
9502
+ // mode only re-derives on the next explicit Best Build, and the whole
9503
+ // point of R3 is that the better default reaches users who never flip
9504
+ // the toggle. See StoredDeckPlan.rankMode.
9505
+ rankMode: stored.rankMode ?? "synergy",
9506
+ // Default null ("follow commander default") for saves without the
9507
+ // field — reproduces the pre-R4 GC-cap behavior (cap derived from
9508
+ // detail.bracket) exactly. An explicit number is a per-deck override.
9509
+ targetBracket: stored.targetBracket ?? null,
9510
+ // Default 0 ("Off") for saves without the field — reproduces the pre-v2
9511
+ // no-combo-acquisition behavior exactly. A non-zero value is a per-deck
9512
+ // combo target. See StoredDeckPlan.comboTarget.
9513
+ comboTarget: stored.comboTarget ?? 0,
9514
+ // Default null ("no cap") for saves without the field — reproduces the
9515
+ // pre-F2 behavior exactly. A number is a per-deck per-card price cap.
9516
+ priceCap: stored.priceCap ?? null,
9517
+ // Default null ("no budget") for saves without the field — reproduces the
9518
+ // pre-F1 behavior exactly (no trim pass). A number is a per-deck total
9519
+ // deck budget.
9520
+ totalBudget: stored.totalBudget ?? null,
9521
+ // Default false for saves without the field — the destructive-refill
9522
+ // confirm degrades to "not edited" until the user touches a card. See
9523
+ // StoredDeckPlan.editedSinceFill.
9524
+ editedSinceFill: stored.editedSinceFill ?? false,
9525
+ // Fill provenance — restored so the "Why this deck?" explainer survives
9526
+ // a reload. Missing (older saves, or never-filled decks) defaults to "no
9527
+ // fill", which keeps the explainer hidden — the correct fresh-deck state.
9528
+ lastFillAction: stored.lastFillAction ?? null,
9529
+ skippedLowSignalCount: stored.skippedLowSignalCount ?? 0,
9530
+ lowSignalSlots: stored.lowSignalSlots ?? [],
9531
+ fillActionAt: stored.fillActionAt ?? null,
9532
+ // Anything we restore from storage is, by definition, loaded. Caller
9533
+ // (the `load` reducer case) also sets this; making the function's
9534
+ // own return type satisfy DeckPlanState keeps the build strict.
9535
+ loaded: true,
9536
+ // Key ownership is the CALLER's knowledge — the `load` case stamps the
9537
+ // action's storageKey over this. Null here keeps direct fromStored()
9538
+ // consumers (cross-deck peeks) from claiming a key they don't own.
9539
+ loadedKey: null,
9540
+ // Placeholder — the `load` case bumps this from the PRIOR state's counter so
9541
+ // the increment is monotonic (a bare fromStored peek has no prior). See
9542
+ // DeckPlanState.hydrationSeq.
9543
+ hydrationSeq: 0
9544
+ };
9545
+ }
9546
+ function deckPlanReducer(state, action) {
9547
+ switch (action.type) {
9548
+ case "assign": {
9549
+ const assignments = new Map(state.assignments);
9550
+ assignments.set(action.oracleId, action.slot);
9551
+ let { purchases, purchaseQuantities } = state;
9552
+ let cardAddedAt = stampNewKeys(
9553
+ state.cardAddedAt,
9554
+ [action.oracleId],
9555
+ (k) => state.assignments.has(k)
9556
+ );
9557
+ const card = action.card;
9558
+ if (card && !allowsMultipleCopies(card.typeLine, card.name)) {
9559
+ const slugs = /* @__PURE__ */ new Set([
9560
+ toEdhrecSlug(card.name),
9561
+ toEdhrecSlug(card.name, { joined: true })
9562
+ ]);
9563
+ for (const slug of slugs) {
9564
+ if (purchases.has(slug)) {
9565
+ if (purchases === state.purchases) purchases = new Map(purchases);
9566
+ purchases.delete(slug);
9567
+ const boughtAt = state.cardAddedAt.get(slug);
9568
+ if (boughtAt !== void 0 && !state.assignments.has(action.oracleId)) {
9569
+ if (cardAddedAt === state.cardAddedAt) cardAddedAt = new Map(cardAddedAt);
9570
+ cardAddedAt.set(action.oracleId, boughtAt);
9571
+ }
9572
+ }
9573
+ if (purchaseQuantities.has(slug)) {
9574
+ if (purchaseQuantities === state.purchaseQuantities) {
9575
+ purchaseQuantities = new Map(purchaseQuantities);
9576
+ }
9577
+ purchaseQuantities.delete(slug);
9578
+ }
9579
+ }
9580
+ }
9581
+ return {
9582
+ ...state,
9583
+ assignments,
9584
+ purchases,
9585
+ purchaseQuantities,
9586
+ cardAddedAt,
9587
+ editedSinceFill: true
9588
+ };
9589
+ }
9590
+ case "unassign": {
9591
+ const assignments = new Map(state.assignments);
9592
+ assignments.delete(action.oracleId);
9593
+ let basicQuantities = state.basicQuantities;
9594
+ if (basicQuantities.has(action.oracleId)) {
9595
+ basicQuantities = new Map(basicQuantities);
9596
+ basicQuantities.delete(action.oracleId);
9597
+ }
9598
+ return { ...state, assignments, basicQuantities, editedSinceFill: true };
9599
+ }
9600
+ case "adjustBasicQty": {
9601
+ const basicQuantities = new Map(state.basicQuantities);
9602
+ const current = basicQuantities.get(action.oracleId) ?? 1;
9603
+ const proposed = Math.max(
9604
+ 1,
9605
+ Math.min(action.ownedQty, current + action.delta)
9606
+ );
9607
+ if (proposed <= 1) basicQuantities.delete(action.oracleId);
9608
+ else basicQuantities.set(action.oracleId, proposed);
9609
+ return { ...state, basicQuantities, editedSinceFill: true };
9610
+ }
9611
+ case "addPurchase": {
9612
+ const purchases = new Map(state.purchases);
9613
+ purchases.set(action.slug, action.slot);
9614
+ const cardAddedAt = stampNewKeys(
9615
+ state.cardAddedAt,
9616
+ [action.slug],
9617
+ (k) => state.purchases.has(k)
9618
+ );
9619
+ return { ...state, purchases, cardAddedAt, editedSinceFill: true };
9620
+ }
9621
+ case "removePurchase": {
9622
+ const purchases = new Map(state.purchases);
9623
+ purchases.delete(action.slug);
9624
+ let purchaseQuantities = state.purchaseQuantities;
9625
+ if (purchaseQuantities.has(action.slug)) {
9626
+ purchaseQuantities = new Map(purchaseQuantities);
9627
+ purchaseQuantities.delete(action.slug);
9628
+ }
9629
+ return { ...state, purchases, purchaseQuantities, editedSinceFill: true };
9630
+ }
9631
+ case "adjustPurchaseQty": {
9632
+ const purchaseQuantities = new Map(state.purchaseQuantities);
9633
+ const current = purchaseQuantities.get(action.slug) ?? 1;
9634
+ const proposed = Math.max(1, Math.min(action.max, current + action.delta));
9635
+ if (proposed <= 1) purchaseQuantities.delete(action.slug);
9636
+ else purchaseQuantities.set(action.slug, proposed);
9637
+ return { ...state, purchaseQuantities, editedSinceFill: true };
9638
+ }
9639
+ case "addToConsidering": {
9640
+ if (state.considering.has(action.oracleId)) return state;
9641
+ const considering = new Set(state.considering);
9642
+ considering.add(action.oracleId);
9643
+ const cardAddedAt = stampNewKeys(state.cardAddedAt, [action.oracleId], () => false);
9644
+ return { ...state, considering, cardAddedAt, editedSinceFill: true };
9645
+ }
9646
+ case "removeFromConsidering": {
9647
+ if (!state.considering.has(action.oracleId)) return state;
9648
+ const considering = new Set(state.considering);
9649
+ considering.delete(action.oracleId);
9650
+ return { ...state, considering, editedSinceFill: true };
9651
+ }
9652
+ case "addToSideboard": {
9653
+ if (state.sideboard.has(action.oracleId)) return state;
9654
+ const sideboard = new Set(state.sideboard);
9655
+ sideboard.add(action.oracleId);
9656
+ const cardAddedAt = stampNewKeys(state.cardAddedAt, [action.oracleId], () => false);
9657
+ return { ...state, sideboard, cardAddedAt, editedSinceFill: true };
9658
+ }
9659
+ case "removeFromSideboard": {
9660
+ if (!state.sideboard.has(action.oracleId)) return state;
9661
+ const sideboard = new Set(state.sideboard);
9662
+ sideboard.delete(action.oracleId);
9663
+ return { ...state, sideboard, editedSinceFill: true };
9664
+ }
9665
+ case "adjustSlotTarget": {
9666
+ const slotTargetOverrides = { ...state.slotTargetOverrides };
9667
+ const current = slotTargetOverrides[action.slot];
9668
+ const next = (current ?? 0) + action.delta;
9669
+ slotTargetOverrides[action.slot] = current === void 0 ? action.delta : next;
9670
+ return { ...state, slotTargetOverrides };
9671
+ }
9672
+ case "resetSlotTarget": {
9673
+ if (!(action.slot in state.slotTargetOverrides)) return state;
9674
+ const slotTargetOverrides = { ...state.slotTargetOverrides };
9675
+ delete slotTargetOverrides[action.slot];
9676
+ return { ...state, slotTargetOverrides };
9677
+ }
9678
+ case "setSoloHalf": {
9679
+ return { ...state, soloHalf: action.soloHalf };
9680
+ }
9681
+ case "setCommanders": {
9682
+ const commanders = action.commanders.slice(0, 2);
9683
+ const cleaned = reconcileCommandersOutOf99(state, commanders);
9684
+ return {
9685
+ ...state,
9686
+ assignments: cleaned.assignments,
9687
+ purchases: cleaned.purchases,
9688
+ basicQuantities: cleaned.basicQuantities,
9689
+ purchaseQuantities: cleaned.purchaseQuantities,
9690
+ considering: cleaned.considering,
9691
+ sideboard: cleaned.sideboard,
9692
+ commanders,
9693
+ commandersProvisional: false,
9694
+ soloHalf: null,
9695
+ ...cleaned.changed ? { editedSinceFill: true } : {}
9696
+ };
9697
+ }
9698
+ case "seedCommanders": {
9699
+ const commanders = action.commanders.slice(0, 2);
9700
+ const cleaned = reconcileCommandersOutOf99(state, commanders);
9701
+ return {
9702
+ ...state,
9703
+ assignments: cleaned.assignments,
9704
+ purchases: cleaned.purchases,
9705
+ basicQuantities: cleaned.basicQuantities,
9706
+ purchaseQuantities: cleaned.purchaseQuantities,
9707
+ considering: cleaned.considering,
9708
+ sideboard: cleaned.sideboard,
9709
+ commanders,
9710
+ commandersProvisional: true,
9711
+ soloHalf: null
9712
+ };
9713
+ }
9714
+ case "commitCommanders": {
9715
+ if (!state.commandersProvisional) return state;
9716
+ return { ...state, commandersProvisional: false };
9717
+ }
9718
+ case "setFoundCardIds": {
9719
+ return { ...state, foundCardIds: action.ids };
9720
+ }
9721
+ case "toggleSlotExpanded": {
9722
+ const expandedSlots = new Set(state.expandedSlots);
9723
+ if (expandedSlots.has(action.slot)) expandedSlots.delete(action.slot);
9724
+ else expandedSlots.add(action.slot);
9725
+ return { ...state, expandedSlots };
9726
+ }
9727
+ case "setUseCardsInOtherDecks": {
9728
+ if (state.useCardsInOtherDecks === action.value) return state;
9729
+ return { ...state, useCardsInOtherDecks: action.value };
9730
+ }
9731
+ case "setUseQualityFloor": {
9732
+ if (state.useQualityFloor === action.value) return state;
9733
+ return { ...state, useQualityFloor: action.value };
9734
+ }
9735
+ case "setRankMode": {
9736
+ if (state.rankMode === action.mode) return state;
9737
+ return { ...state, rankMode: action.mode };
9738
+ }
9739
+ case "setTargetBracket": {
9740
+ if (state.targetBracket === action.bracket) return state;
9741
+ return { ...state, targetBracket: action.bracket };
9742
+ }
9743
+ case "setComboTarget": {
9744
+ if (state.comboTarget === action.value) return state;
9745
+ return { ...state, comboTarget: action.value };
9746
+ }
9747
+ case "setPriceCap": {
9748
+ if (state.priceCap === action.cap) return state;
9749
+ return { ...state, priceCap: action.cap };
9750
+ }
9751
+ case "setTotalBudget": {
9752
+ if (state.totalBudget === action.budget) return state;
9753
+ return { ...state, totalBudget: action.budget };
9754
+ }
9755
+ case "dropPurchases": {
9756
+ let { purchases, purchaseQuantities } = state;
9757
+ for (const slug of action.slugs) {
9758
+ if (purchases.has(slug)) {
9759
+ if (purchases === state.purchases) purchases = new Map(purchases);
9760
+ purchases.delete(slug);
9761
+ }
9762
+ if (purchaseQuantities.has(slug)) {
9763
+ if (purchaseQuantities === state.purchaseQuantities) {
9764
+ purchaseQuantities = new Map(purchaseQuantities);
9765
+ }
9766
+ purchaseQuantities.delete(slug);
9767
+ }
9768
+ }
9769
+ if (purchases === state.purchases && purchaseQuantities === state.purchaseQuantities) {
9770
+ return state;
9771
+ }
9772
+ return { ...state, purchases, purchaseQuantities };
9773
+ }
9774
+ case "clearOtherOverride": {
9775
+ if (!("other" in state.slotTargetOverrides)) return state;
9776
+ const slotTargetOverrides = { ...state.slotTargetOverrides };
9777
+ delete slotTargetOverrides.other;
9778
+ return { ...state, slotTargetOverrides };
9779
+ }
9780
+ case "applyBulkFill": {
9781
+ const purchases = action.payload.purchases ?? /* @__PURE__ */ new Map();
9782
+ const now = Date.now();
9783
+ const cardAddedAt = stampNewKeys(
9784
+ stampNewKeys(
9785
+ state.cardAddedAt,
9786
+ action.payload.assignments.keys(),
9787
+ (k) => state.assignments.has(k),
9788
+ now
9789
+ ),
9790
+ purchases.keys(),
9791
+ (k) => state.purchases.has(k),
9792
+ now
9793
+ );
9794
+ return {
9795
+ ...state,
9796
+ assignments: action.payload.assignments,
9797
+ purchases,
9798
+ cardAddedAt,
9799
+ basicQuantities: action.payload.basicQuantities,
9800
+ // A bulk fill defines a fresh buy list (1 copy each) — drop any
9801
+ // hand-stacked buy quantities so they can't outlive the cards.
9802
+ purchaseQuantities: /* @__PURE__ */ new Map(),
9803
+ ...action.fill ? {
9804
+ lastFillAction: action.fill.action,
9805
+ skippedLowSignalCount: action.fill.skippedLowSignalCount,
9806
+ lowSignalSlots: action.fill.lowSignalSlots,
9807
+ fillActionAt: action.fill.at,
9808
+ // Best Build / Owned Only establishes a fresh clean baseline —
9809
+ // there are no manual edits to protect right after a fill. A
9810
+ // bulk apply WITHOUT fill (seed apply, combo-acquisition swap)
9811
+ // leaves this alone: combo-acquisition continues the same Best
9812
+ // Build, and seed apply runs on an empty deck.
9813
+ editedSinceFill: false
9814
+ } : {}
9815
+ };
9816
+ }
9817
+ case "resetAll": {
9818
+ return {
9819
+ ...state,
9820
+ assignments: /* @__PURE__ */ new Map(),
9821
+ purchases: /* @__PURE__ */ new Map(),
9822
+ basicQuantities: /* @__PURE__ */ new Map(),
9823
+ purchaseQuantities: /* @__PURE__ */ new Map(),
9824
+ slotTargetOverrides: {},
9825
+ // The deck is cleared, so any fill provenance is now stale — drop it
9826
+ // so the "Why this deck?" explainer hides again (matches the
9827
+ // pre-persistence behavior, where reset cleared the page-level state).
9828
+ lastFillAction: null,
9829
+ skippedLowSignalCount: 0,
9830
+ lowSignalSlots: [],
9831
+ fillActionAt: null,
9832
+ // Nothing committed means nothing to protect — a post-reset auto-fill
9833
+ // is friction-free.
9834
+ editedSinceFill: false
9835
+ };
9836
+ }
9837
+ case "resetSlot": {
9838
+ const assignments = new Map(state.assignments);
9839
+ const basicQuantities = new Map(state.basicQuantities);
9840
+ for (const oid of action.cardsToClear) {
9841
+ assignments.delete(oid);
9842
+ basicQuantities.delete(oid);
9843
+ }
9844
+ const purchases = new Map(state.purchases);
9845
+ const purchaseQuantities = new Map(state.purchaseQuantities);
9846
+ for (const [slug, s] of purchases) {
9847
+ if (s === action.slot) {
9848
+ purchases.delete(slug);
9849
+ purchaseQuantities.delete(slug);
9850
+ }
9851
+ }
9852
+ const slotTargetOverrides = { ...state.slotTargetOverrides };
9853
+ delete slotTargetOverrides[action.slot];
9854
+ return {
9855
+ ...state,
9856
+ assignments,
9857
+ purchases,
9858
+ basicQuantities,
9859
+ purchaseQuantities,
9860
+ slotTargetOverrides,
9861
+ // Clearing a slot's cards is a manual edit a fresh fill would discard.
9862
+ editedSinceFill: true
9863
+ };
9864
+ }
9865
+ case "restore": {
9866
+ return { ...state, ...action.content };
9867
+ }
9868
+ case "load": {
9869
+ const loaded = {
9870
+ ...EMPTY_DECK_PLAN,
9871
+ ...fromStored(action.stored),
9872
+ loaded: true,
9873
+ loadedKey: action.storageKey,
9874
+ // Bump off the PRIOR state so the counter is monotonic across a same-deck
9875
+ // reload (fromStored reset it to 0). A same-key load that only changes
9876
+ // this number is how useDeckHistory recognizes a passive cross-tab sync.
9877
+ hydrationSeq: state.hydrationSeq + 1
9878
+ };
9879
+ const cleaned = reconcileCommandersOutOf99(loaded, loaded.commanders);
9880
+ return {
9881
+ ...loaded,
9882
+ assignments: cleaned.assignments,
9883
+ purchases: cleaned.purchases,
9884
+ basicQuantities: cleaned.basicQuantities,
9885
+ purchaseQuantities: cleaned.purchaseQuantities,
9886
+ considering: cleaned.considering,
9887
+ sideboard: cleaned.sideboard
9888
+ };
9889
+ }
9890
+ case "loadEmpty": {
9891
+ return {
9892
+ ...EMPTY_DECK_PLAN,
9893
+ loaded: true,
9894
+ loadedKey: action.storageKey,
9895
+ hydrationSeq: state.hydrationSeq + 1
9896
+ };
9897
+ }
9898
+ }
9899
+ }
9900
+ var EMPTY_DECK_PLAN;
9265
9901
  var init_reducer = __esm({
9266
9902
  "../src/lib/deckPlan/reducer.ts"() {
9267
9903
  "use strict";
9268
9904
  init_slug();
9269
9905
  init_utils();
9906
+ EMPTY_DECK_PLAN = {
9907
+ assignments: /* @__PURE__ */ new Map(),
9908
+ purchases: /* @__PURE__ */ new Map(),
9909
+ basicQuantities: /* @__PURE__ */ new Map(),
9910
+ purchaseQuantities: /* @__PURE__ */ new Map(),
9911
+ considering: /* @__PURE__ */ new Set(),
9912
+ sideboard: /* @__PURE__ */ new Set(),
9913
+ cardAddedAt: /* @__PURE__ */ new Map(),
9914
+ slotTargetOverrides: {},
9915
+ soloHalf: null,
9916
+ commanders: [],
9917
+ commandersProvisional: false,
9918
+ foundCardIds: /* @__PURE__ */ new Set(),
9919
+ expandedSlots: /* @__PURE__ */ new Set(),
9920
+ useCardsInOtherDecks: true,
9921
+ useQualityFloor: true,
9922
+ rankMode: "synergy",
9923
+ targetBracket: null,
9924
+ comboTarget: 0,
9925
+ priceCap: null,
9926
+ totalBudget: null,
9927
+ lastFillAction: null,
9928
+ skippedLowSignalCount: 0,
9929
+ lowSignalSlots: [],
9930
+ fillActionAt: null,
9931
+ editedSinceFill: false,
9932
+ loaded: false,
9933
+ loadedKey: null,
9934
+ hydrationSeq: 0
9935
+ };
9270
9936
  }
9271
9937
  });
9272
9938
 
9273
9939
  // ../src/lib/savedDecks/emptyDeck.ts
9940
+ function emptyStoredDeck() {
9941
+ return toStored(EMPTY_DECK_PLAN);
9942
+ }
9274
9943
  var init_emptyDeck = __esm({
9275
9944
  "../src/lib/savedDecks/emptyDeck.ts"() {
9276
9945
  "use strict";
@@ -9282,13 +9951,15 @@ var init_emptyDeck = __esm({
9282
9951
  function clampDeckName(name) {
9283
9952
  return name.trim().slice(0, MAX_DECK_NAME_LENGTH);
9284
9953
  }
9285
- var MAX_DECK_NAME_LENGTH;
9954
+ var MAX_DESCRIPTION_LENGTH, MAX_NOTES_LENGTH, MAX_DECK_NAME_LENGTH;
9286
9955
  var init_deckText = __esm({
9287
9956
  "../src/lib/savedDecks/deckText.ts"() {
9288
9957
  "use strict";
9289
9958
  init_storage();
9290
9959
  init_tags();
9291
9960
  init_emptyDeck();
9961
+ MAX_DESCRIPTION_LENGTH = 150;
9962
+ MAX_NOTES_LENGTH = 2e3;
9292
9963
  MAX_DECK_NAME_LENGTH = 150;
9293
9964
  }
9294
9965
  });
@@ -11966,9 +12637,9 @@ var require_react_development = __commonJS({
11966
12637
  return "";
11967
12638
  }
11968
12639
  {
11969
- var frame = componentFrameCache.get(fn);
11970
- if (frame !== void 0) {
11971
- return frame;
12640
+ var frame2 = componentFrameCache.get(fn);
12641
+ if (frame2 !== void 0) {
12642
+ return frame2;
11972
12643
  }
11973
12644
  }
11974
12645
  var control;
@@ -15120,17 +15791,17 @@ function buildOtagBroadMatch(index, slugs) {
15120
15791
 
15121
15792
  // ../src/lib/cardCatalog/setIndex.ts
15122
15793
  init_fetchWithTimeout();
15123
- function hydrateSetIndex(file3) {
15794
+ function hydrateSetIndex(file4) {
15124
15795
  const membership = /* @__PURE__ */ new Map();
15125
- for (const [oid, codes] of Object.entries(file3.membership ?? {})) {
15796
+ for (const [oid, codes] of Object.entries(file4.membership ?? {})) {
15126
15797
  membership.set(oid, new Set(codes));
15127
15798
  }
15128
- const finishes = new Map(Object.entries(file3.finishes ?? {}));
15799
+ const finishes = new Map(Object.entries(file4.finishes ?? {}));
15129
15800
  const treatments = /* @__PURE__ */ new Map();
15130
- for (const [oid, codes] of Object.entries(file3.treatments ?? {})) {
15801
+ for (const [oid, codes] of Object.entries(file4.treatments ?? {})) {
15131
15802
  treatments.set(oid, new Set(codes));
15132
15803
  }
15133
- return { membership, finishes, treatments, sets: file3.sets ?? [] };
15804
+ return { membership, finishes, treatments, sets: file4.sets ?? [] };
15134
15805
  }
15135
15806
  function buildSetMatch(idx) {
15136
15807
  return (oracleId, codes) => {
@@ -15901,8 +16572,8 @@ import { join as join5 } from "node:path";
15901
16572
 
15902
16573
  // ../src/lib/deckStats/baseline.ts
15903
16574
  init_fetchWithTimeout();
15904
- function hydrateBaseline(file3) {
15905
- const { freeSpellOids, finisherOids, ...rest } = file3;
16575
+ function hydrateBaseline(file4) {
16576
+ const { freeSpellOids, finisherOids, ...rest } = file4;
15906
16577
  return {
15907
16578
  ...rest,
15908
16579
  freeSpellOids: new Set(freeSpellOids),
@@ -16019,28 +16690,28 @@ function extrasLoader(opts) {
16019
16690
  throw e;
16020
16691
  });
16021
16692
  };
16022
- const file3 = (name, read) => once(async () => {
16693
+ const file4 = (name, read) => once(async () => {
16023
16694
  const got = await ensureFile(opts, name);
16024
16695
  if (got.stale) stale.add(name);
16025
16696
  return read(JSON.parse(readFileSync5(got.path, "utf8")));
16026
16697
  });
16027
16698
  return {
16028
- prices: file3("card-prices.json", parse.prices),
16029
- printings: file3("printings.json", parse.printings),
16030
- printingTrend: file3("printing-prices-trend.json", parse.printingTrend),
16031
- landCycles: file3("land-cycles.json", parse.landCycles),
16032
- cardText: file3("card-text.json", parse.cardText),
16699
+ prices: file4("card-prices.json", parse.prices),
16700
+ printings: file4("printings.json", parse.printings),
16701
+ printingTrend: file4("printing-prices-trend.json", parse.printingTrend),
16702
+ landCycles: file4("land-cycles.json", parse.landCycles),
16703
+ cardText: file4("card-text.json", parse.cardText),
16033
16704
  comboDetail: once(async () => {
16034
16705
  const files = await ensureDataSet(opts, COMBO_DETAIL_SET);
16035
16706
  if (files.stale) stale.add("combos-detail.json");
16036
16707
  return parse.comboDetail(files.files.map((n) => JSON.parse(readFileSync5(join5(files.dir, n), "utf8"))));
16037
16708
  }),
16038
- deckStatsBaseline: file3("deck-stats-baseline.json", parse.deckStatsBaseline),
16039
- commandersIndex: file3("commanders/_index.json", parse.commandersIndex),
16709
+ deckStatsBaseline: file4("deck-stats-baseline.json", parse.deckStatsBaseline),
16710
+ commandersIndex: file4("commanders/_index.json", parse.commandersIndex),
16040
16711
  commanderDetail: (slug) => {
16041
16712
  if (!/^[a-z0-9-]+$/.test(slug)) return Promise.reject(new Error(`Not a commander slug: ${slug}`));
16042
16713
  let load = details.get(slug);
16043
- if (!load) details.set(slug, load = file3(`commanders/${slug}.json`, (raw) => parse.commanderDetail(raw, slug)));
16714
+ if (!load) details.set(slug, load = file4(`commanders/${slug}.json`, (raw) => parse.commanderDetail(raw, slug)));
16044
16715
  return load();
16045
16716
  },
16046
16717
  comboStepsOnDisk: () => existsSync3(join5(opts.dir, COMBO_DETAIL_SET.name, "manifest.json")),
@@ -16092,8 +16763,17 @@ async function openAgentBundle(sealed, keys) {
16092
16763
  const k = typeof text === "string" ? keyFromText(text) : null;
16093
16764
  if (k) out[s] = k;
16094
16765
  }
16766
+ const req = typeof b.req === "string" ? keyFromText(b.req) : null;
16767
+ if (req) out.requests = req;
16095
16768
  return out;
16096
16769
  }
16770
+ var requestAad = (ah) => `agent-request:${ah}`;
16771
+ function sealAgentRequest(text, requestKey, ah) {
16772
+ return sealText(text, requestKey, { aad: requestAad(ah) });
16773
+ }
16774
+ function openAgentRequest(sealed, requestKey, ah) {
16775
+ return openText(sealed, requestKey, { aad: requestAad(ah) });
16776
+ }
16097
16777
 
16098
16778
  // ../src/lib/sync/agentView.ts
16099
16779
  init_sealedBox();
@@ -16129,6 +16809,9 @@ var LibraryError = class extends Error {
16129
16809
  };
16130
16810
  var KeySwapped = class extends Error {
16131
16811
  };
16812
+ var CANT_REQUEST = `This access code can't ask to change decks. Turn on "Can ask to: Change decks" for it with Edit access in edhvault Settings, AI tools access.`;
16813
+ var CANT_CREATE = `This access code can't ask to make decks. Turn on "Can ask to: Make decks" for it with Edit access in edhvault Settings, AI tools access.`;
16814
+ var cantAsk = (letter) => letter === "c" ? CANT_CREATE : CANT_REQUEST;
16132
16815
  var NOT_CONNECTED = "Not connected yet. Run `npx edhvault-mcp login`, or make a code in edhvault Settings, AI tools access.";
16133
16816
  var REMOVED = "This access code was removed. Connect again in edhvault Settings, AI tools access.";
16134
16817
  var NO_COPY = "Your library isn't ready yet. Open edhvault on a synced device, then try again.";
@@ -16157,12 +16840,15 @@ var Library = class {
16157
16840
  opts;
16158
16841
  token = null;
16159
16842
  keys = null;
16843
+ /** What this code may ask to change, as the server's letters ("ec"). */
16844
+ writes = "";
16160
16845
  parts = /* @__PURE__ */ new Map();
16161
16846
  cache;
16162
16847
  now;
16163
16848
  freshMs;
16164
16849
  forget() {
16165
16850
  rmSync2(this.cache, { recursive: true, force: true });
16851
+ rmSync2(join6(this.opts.dir, "requests"), { recursive: true, force: true });
16166
16852
  this.parts.clear();
16167
16853
  this.token = null;
16168
16854
  this.keys = null;
@@ -16192,7 +16878,9 @@ var Library = class {
16192
16878
  const agent = await deriveAgentKeys(this.opts.secret);
16193
16879
  let keys;
16194
16880
  try {
16195
- keys = await openAgentBundle(await agentFetchBundle(agent.token, this.opts.transport), agent);
16881
+ const got = await agentFetchBundleInfo(agent.token, this.opts.transport);
16882
+ keys = await openAgentBundle(got.bundle, agent);
16883
+ this.writes = got.writes;
16196
16884
  } catch (e) {
16197
16885
  this.fail(e);
16198
16886
  }
@@ -16274,8 +16962,8 @@ var Library = class {
16274
16962
  const sealed = /* @__PURE__ */ new Map();
16275
16963
  const missing = [];
16276
16964
  for (const e of list) {
16277
- const file3 = join6(dir, e.obj);
16278
- if (existsSync4(file3)) sealed.set(e.obj, new Uint8Array(readFileSync6(file3)));
16965
+ const file4 = join6(dir, e.obj);
16966
+ if (existsSync4(file4)) sealed.set(e.obj, new Uint8Array(readFileSync6(file4)));
16279
16967
  else missing.push(e.obj);
16280
16968
  }
16281
16969
  for (let i = 0; i < missing.length; i += GET_BATCH) {
@@ -16346,6 +17034,67 @@ var Library = class {
16346
17034
  if (!decks && !lists) return null;
16347
17035
  return { ...decks ?? {}, ...lists ?? {} };
16348
17036
  }
17037
+ // ── Change requests (spec §12 step 5) ──────────────────────────────────
17038
+ /** Whether this code may ask for this kind of change ("e": change decks,
17039
+ * "c": make decks): its bundle carries a request key and the server lists
17040
+ * the letter. The server checks the letter again on every request. */
17041
+ async canRequest(letter = "e") {
17042
+ const { keys } = await this.connect();
17043
+ return !!keys.requests && this.writes.includes(letter);
17044
+ }
17045
+ requestDir() {
17046
+ return join6(this.opts.dir, "requests");
17047
+ }
17048
+ /** File a change request. The text is sealed here, under a key only this
17049
+ * code and the user's own devices hold; a copy stays on disk, sealed, so
17050
+ * `requests()` can say what each one was. */
17051
+ async fileRequest(kind, text) {
17052
+ const { token, keys } = await this.connect();
17053
+ if (!keys.requests || !this.writes.includes(kind)) throw new LibraryError("no-scope", cantAsk(kind));
17054
+ const agent = await deriveAgentKeys(this.opts.secret);
17055
+ const sealed = await sealAgentRequest(text, keys.requests, agent.ah);
17056
+ let r;
17057
+ try {
17058
+ r = await agentPostRequest(token, kind, sealed, this.opts.transport);
17059
+ } catch (e) {
17060
+ if (e instanceof SyncHttpError && e.kind === "no-scope") {
17061
+ this.token = null;
17062
+ this.keys = null;
17063
+ throw new LibraryError("no-scope", cantAsk(kind));
17064
+ }
17065
+ this.fail(e);
17066
+ }
17067
+ if (r.status === "ok") {
17068
+ mkdirSync3(this.requestDir(), { recursive: true });
17069
+ writeFileSync3(join6(this.requestDir(), r.id), sealed);
17070
+ }
17071
+ return r;
17072
+ }
17073
+ /** This code's requests: what became of each, and (from the sealed copy kept
17074
+ * when it was filed) what it asked for. */
17075
+ async requests() {
17076
+ const { token, keys } = await this.connect();
17077
+ let list;
17078
+ try {
17079
+ list = await agentListRequests(token, this.opts.transport);
17080
+ } catch (e) {
17081
+ this.fail(e);
17082
+ }
17083
+ const agent = await deriveAgentKeys(this.opts.secret);
17084
+ const dir = this.requestDir();
17085
+ const known = new Set(list.map((r) => r.id));
17086
+ if (existsSync4(dir)) {
17087
+ for (const f of readdirSync(dir)) if (!known.has(f)) rmSync2(join6(dir, f), { force: true });
17088
+ }
17089
+ return Promise.all(
17090
+ list.map(async (r) => {
17091
+ const file4 = join6(dir, r.id);
17092
+ if (!keys.requests || !existsSync4(file4)) return r;
17093
+ const text = await openAgentRequest(new Uint8Array(readFileSync6(file4)), keys.requests, agent.ah).catch(() => void 0);
17094
+ return text ? { ...r, text } : r;
17095
+ })
17096
+ );
17097
+ }
16349
17098
  };
16350
17099
 
16351
17100
  // src/log.ts
@@ -16444,34 +17193,34 @@ async function osKeychain() {
16444
17193
  return null;
16445
17194
  }
16446
17195
  }
16447
- function lockToOwner(file3) {
17196
+ function lockToOwner(file4) {
16448
17197
  if (process.platform !== "win32") {
16449
- chmodSync(file3, 384);
17198
+ chmodSync(file4, 384);
16450
17199
  return;
16451
17200
  }
16452
17201
  const windir = process.env.SystemRoot ?? "C:\\Windows";
16453
17202
  execFileSync(
16454
17203
  join7(windir, "System32", "icacls.exe"),
16455
- [file3, "/inheritance:r", "/grant:r", `${userInfo().username}:F`],
17204
+ [file4, "/inheritance:r", "/grant:r", `${userInfo().username}:F`],
16456
17205
  { stdio: "ignore", windowsHide: true }
16457
17206
  );
16458
17207
  }
16459
17208
  function fileKeychain(dir) {
16460
- const file3 = join7(dir, ACCOUNT);
17209
+ const file4 = join7(dir, ACCOUNT);
16461
17210
  return {
16462
- get: () => existsSync5(file3) ? readFileSync7(file3, "utf8").trim() : null,
17211
+ get: () => existsSync5(file4) ? readFileSync7(file4, "utf8").trim() : null,
16463
17212
  set: (value) => {
16464
- mkdirSync5(dirname3(file3), { recursive: true, mode: 448 });
16465
- writeFileSync4(file3, "", { mode: 384 });
17213
+ mkdirSync5(dirname3(file4), { recursive: true, mode: 448 });
17214
+ writeFileSync4(file4, "", { mode: 384 });
16466
17215
  try {
16467
- lockToOwner(file3);
17216
+ lockToOwner(file4);
16468
17217
  } catch (e) {
16469
- rmSync3(file3, { force: true });
16470
- throw new Error(`Couldn't make ${file3} private, so the code wasn't saved: ${e instanceof Error ? e.message : e}`);
17218
+ rmSync3(file4, { force: true });
17219
+ throw new Error(`Couldn't make ${file4} private, so the code wasn't saved: ${e instanceof Error ? e.message : e}`);
16471
17220
  }
16472
- writeFileSync4(file3, value);
17221
+ writeFileSync4(file4, value);
16473
17222
  },
16474
- remove: () => rmSync3(file3, { force: true })
17223
+ remove: () => rmSync3(file4, { force: true })
16475
17224
  };
16476
17225
  }
16477
17226
  function saveSecret(store2, secret) {
@@ -37199,7 +37948,7 @@ function visit(schema, fnOrHandlers) {
37199
37948
  return h ? h(node2, rewritten) : node2;
37200
37949
  };
37201
37950
  const cache2 = /* @__PURE__ */ new Map();
37202
- function run(s) {
37951
+ function run2(s) {
37203
37952
  const cached2 = cache2.get(s);
37204
37953
  if (cached2 === RESOLVING) {
37205
37954
  return new $ZodLazy({
@@ -37225,21 +37974,21 @@ function visit(schema, fnOrHandlers) {
37225
37974
  let changed = false;
37226
37975
  const newShape = {};
37227
37976
  for (const k of keys) {
37228
- const mapped = run(oldShape[k]);
37977
+ const mapped = run2(oldShape[k]);
37229
37978
  if (mapped !== oldShape[k])
37230
37979
  changed = true;
37231
37980
  newShape[k] = mapped;
37232
37981
  }
37233
37982
  let newCatchall = def.catchall;
37234
37983
  if (def.catchall) {
37235
- newCatchall = run(def.catchall);
37984
+ newCatchall = run2(def.catchall);
37236
37985
  if (newCatchall !== def.catchall)
37237
37986
  changed = true;
37238
37987
  }
37239
37988
  return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s;
37240
37989
  }
37241
37990
  case "array": {
37242
- const mapped = run(def.element);
37991
+ const mapped = run2(def.element);
37243
37992
  return mapped === def.element ? s : clone(s, { ...def, element: mapped });
37244
37993
  }
37245
37994
  case "tuple": {
@@ -37247,14 +37996,14 @@ function visit(schema, fnOrHandlers) {
37247
37996
  let changed = false;
37248
37997
  const newItems = [];
37249
37998
  for (const item of oldItems) {
37250
- const mapped = run(item);
37999
+ const mapped = run2(item);
37251
38000
  if (mapped !== item)
37252
38001
  changed = true;
37253
38002
  newItems.push(mapped);
37254
38003
  }
37255
38004
  let newRest = def.rest;
37256
38005
  if (def.rest) {
37257
- newRest = run(def.rest);
38006
+ newRest = run2(def.rest);
37258
38007
  if (newRest !== def.rest)
37259
38008
  changed = true;
37260
38009
  }
@@ -37262,12 +38011,12 @@ function visit(schema, fnOrHandlers) {
37262
38011
  }
37263
38012
  case "record":
37264
38013
  case "map": {
37265
- const newKey2 = run(def.keyType);
37266
- const newVal = run(def.valueType);
38014
+ const newKey2 = run2(def.keyType);
38015
+ const newVal = run2(def.valueType);
37267
38016
  return newKey2 === def.keyType && newVal === def.valueType ? s : clone(s, { ...def, keyType: newKey2, valueType: newVal });
37268
38017
  }
37269
38018
  case "set": {
37270
- const newVal = run(def.valueType);
38019
+ const newVal = run2(def.valueType);
37271
38020
  return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal });
37272
38021
  }
37273
38022
  case "union": {
@@ -37275,7 +38024,7 @@ function visit(schema, fnOrHandlers) {
37275
38024
  let changed = false;
37276
38025
  const newOptions = [];
37277
38026
  for (const opt of oldOptions) {
37278
- const mapped = run(opt);
38027
+ const mapped = run2(opt);
37279
38028
  if (mapped !== opt)
37280
38029
  changed = true;
37281
38030
  newOptions.push(mapped);
@@ -37283,8 +38032,8 @@ function visit(schema, fnOrHandlers) {
37283
38032
  return changed ? clone(s, { ...def, options: newOptions }) : s;
37284
38033
  }
37285
38034
  case "intersection": {
37286
- const newLeft = run(def.left);
37287
- const newRight = run(def.right);
38035
+ const newLeft = run2(def.left);
38036
+ const newRight = run2(def.right);
37288
38037
  return newLeft === def.left && newRight === def.right ? s : clone(s, { ...def, left: newLeft, right: newRight });
37289
38038
  }
37290
38039
  case "optional":
@@ -37296,23 +38045,23 @@ function visit(schema, fnOrHandlers) {
37296
38045
  case "nonoptional":
37297
38046
  case "promise":
37298
38047
  case "success": {
37299
- const newInner = run(def.innerType);
38048
+ const newInner = run2(def.innerType);
37300
38049
  return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner });
37301
38050
  }
37302
38051
  case "pipe": {
37303
- const newIn = run(def.in);
37304
- const newOut = run(def.out);
38052
+ const newIn = run2(def.in);
38053
+ const newOut = run2(def.out);
37305
38054
  return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut });
37306
38055
  }
37307
38056
  case "function": {
37308
- const newInput = run(def.input);
37309
- const newOutput = run(def.output);
38057
+ const newInput = run2(def.input);
38058
+ const newOutput = run2(def.output);
37310
38059
  return newInput === def.input && newOutput === def.output ? s : clone(s, { ...def, input: newInput, output: newOutput });
37311
38060
  }
37312
38061
  case "lazy": {
37313
38062
  const original = def.getter;
37314
38063
  const { _cachedInner, ...rest } = def;
37315
- return clone(s, { ...rest, getter: () => run(original()) });
38064
+ return clone(s, { ...rest, getter: () => run2(original()) });
37316
38065
  }
37317
38066
  // A leaf by choice: `parts` are regex fragments, not data positions.
37318
38067
  case "template_literal":
@@ -37343,7 +38092,7 @@ function visit(schema, fnOrHandlers) {
37343
38092
  }
37344
38093
  }
37345
38094
  }
37346
- return run(schema);
38095
+ return run2(schema);
37347
38096
  }
37348
38097
 
37349
38098
  // ../../commander/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
@@ -46862,18 +47611,15 @@ init_utils();
46862
47611
  // ../src/lib/deckPlan/storedDeckCount.ts
46863
47612
  function countStoredMainboard(plan) {
46864
47613
  let total = 0;
46865
- if (plan.assignments) {
46866
- for (const oid of plan.assignments.keys()) {
46867
- total += plan.basicQuantities?.get(oid) ?? 1;
46868
- }
46869
- }
46870
- if (plan.purchases) {
46871
- for (const slug of plan.purchases.keys()) {
46872
- total += plan.purchaseQuantities?.get(slug) ?? 1;
46873
- }
46874
- }
47614
+ forEachCommitted(plan, (_side, _key, copies) => {
47615
+ total += copies;
47616
+ });
46875
47617
  return total;
46876
47618
  }
47619
+ function forEachCommitted(plan, visit2) {
47620
+ for (const oid of plan.assignments?.keys() ?? []) visit2("main", oid, plan.basicQuantities?.get(oid) ?? 1);
47621
+ for (const slug of plan.purchases?.keys() ?? []) visit2("buy", slug, plan.purchaseQuantities?.get(slug) ?? 1);
47622
+ }
46877
47623
 
46878
47624
  // ../src/lib/deckPlan/importDeck.ts
46879
47625
  function looksLikeDeckUrl(input2) {
@@ -52788,12 +53534,12 @@ function formatLift(lift) {
52788
53534
 
52789
53535
  // ../src/lib/printingTrend.ts
52790
53536
  var SLOT2 = { "7d": 0, "30d": 2, "1d": 4 };
52791
- function printingTrendWindows(file3, set3, collectorNumber, foil, priceNow) {
53537
+ function printingTrendWindows(file4, set3, collectorNumber, foil, priceNow) {
52792
53538
  const out = {};
52793
- if (!file3 || !set3 || !collectorNumber) return out;
52794
- const slots = file3.s[set3.toLowerCase()]?.[collectorNumber];
53539
+ if (!file4 || !set3 || !collectorNumber) return out;
53540
+ const slots = file4.s[set3.toLowerCase()]?.[collectorNumber];
52795
53541
  for (const w of ["1d", "7d", "30d"]) {
52796
- const at = file3.trend[w];
53542
+ const at = file4.trend[w];
52797
53543
  if (!at) continue;
52798
53544
  const delta = slots?.[SLOT2[w] + (foil ? 1 : 0)] ?? 0;
52799
53545
  const then = priceNow != null ? priceNow - delta : void 0;
@@ -53094,6 +53840,490 @@ function isLand3(card) {
53094
53840
  return (card.typeLine.split(" // ")[0] ?? card.typeLine).includes("Land");
53095
53841
  }
53096
53842
 
53843
+ // ../src/lib/agentRequests/deckOps.ts
53844
+ init_slug();
53845
+
53846
+ // ../src/lib/deckPlan/addDecision.ts
53847
+ init_slug();
53848
+ init_utils();
53849
+ function addDecision(card, owned) {
53850
+ const slot = slotsForCard(card)[0] ?? "other";
53851
+ if (isBasicLandType(card.typeLine)) {
53852
+ return { action: "assign", oracleId: card.oracleId, slot: "lands" };
53853
+ }
53854
+ if (owned) {
53855
+ return { action: "assign", oracleId: card.oracleId, slot };
53856
+ }
53857
+ return { action: "purchase", slug: toEdhrecSlug(card.name), slot };
53858
+ }
53859
+
53860
+ // ../src/lib/agentRequests/deckOps.ts
53861
+ init_reducer();
53862
+
53863
+ // ../src/lib/deckPlan/storedSideFields.ts
53864
+ var REDUCER_FIELDS = [
53865
+ "assignments",
53866
+ "purchases",
53867
+ "basicQuantities",
53868
+ "purchaseQuantities",
53869
+ "considering",
53870
+ "sideboard",
53871
+ "cardAddedAt",
53872
+ "slotTargetOverrides",
53873
+ "soloHalf",
53874
+ "commanders",
53875
+ "foundCardIds",
53876
+ "expandedSlots",
53877
+ "savedAt",
53878
+ "useCardsInOtherDecks",
53879
+ "useQualityFloor",
53880
+ "rankMode",
53881
+ "targetBracket",
53882
+ "comboTarget",
53883
+ "priceCap",
53884
+ "totalBudget",
53885
+ "lastFillAction",
53886
+ "skippedLowSignalCount",
53887
+ "lowSignalSlots",
53888
+ "fillActionAt",
53889
+ "editedSinceFill"
53890
+ ];
53891
+ var REDUCER = new Set(REDUCER_FIELDS);
53892
+
53893
+ // ../src/lib/agentRequests/deckOps.ts
53894
+ init_utils();
53895
+ var DECK_BOARDS = ["deck", "considering", "sideboard"];
53896
+ var MAX_CARDS_PER_EDIT = 30;
53897
+ var MAX_COPIES = 99;
53898
+ function slugsOf(card) {
53899
+ return [.../* @__PURE__ */ new Set([toEdhrecSlug(card.name), toEdhrecSlug(card.name, { joined: true })])];
53900
+ }
53901
+ function placeOf(s, card) {
53902
+ if (s.assignments.has(card.oracleId)) {
53903
+ return { board: "deck", qty: s.basicQuantities.get(card.oracleId) ?? 1, owned: true };
53904
+ }
53905
+ for (const slug of slugsOf(card)) {
53906
+ if (s.purchases.has(slug)) return { board: "deck", qty: s.purchaseQuantities.get(slug) ?? 1, owned: false, slug };
53907
+ }
53908
+ if (s.considering.has(card.oracleId)) return { board: "considering" };
53909
+ if (s.sideboard.has(card.oracleId)) return { board: "sideboard" };
53910
+ return null;
53911
+ }
53912
+ var boardName = (b) => b === "deck" ? "the deck" : b;
53913
+ function entryProblem(card, qty, identity2) {
53914
+ if (isCardBanned(card)) return "banned in Commander";
53915
+ if (identity2.length && !withinColorIdentity(card.colors ?? [], new Set(identity2))) return "outside the commander's colors";
53916
+ if (qty > 1 && !allowsMultipleCopies(card.typeLine, card.name)) return "only one copy is allowed";
53917
+ return null;
53918
+ }
53919
+ function cardsChanged(ops) {
53920
+ return new Set(ops.map((o) => o.oracleId)).size;
53921
+ }
53922
+ function checkDeckOps(stored, ops, ctx, maxCards = MAX_CARDS_PER_EDIT) {
53923
+ const issues = [];
53924
+ if (cardsChanged(ops) > maxCards) {
53925
+ issues.push({ index: -1, card: "", reason: `changes ${cardsChanged(ops)} cards; at most ${maxCards} per request` });
53926
+ }
53927
+ let s = fromStored(stored);
53928
+ ops.forEach((op, index) => {
53929
+ const card = ctx.card(op.oracleId);
53930
+ if (!card) {
53931
+ issues.push({ index, card: op.oracleId, reason: "not a card EDHVault knows" });
53932
+ return;
53933
+ }
53934
+ const problem = opProblem(s, op, card, ctx);
53935
+ if (problem) issues.push({ index, card: card.name, reason: problem });
53936
+ else s = run(s, op, card, ctx).state;
53937
+ });
53938
+ return issues;
53939
+ }
53940
+ function opProblem(s, op, card, ctx) {
53941
+ const at = placeOf(s, card);
53942
+ switch (op.op) {
53943
+ case "add": {
53944
+ const to = op.to ?? "deck";
53945
+ const qty = op.qty ?? 1;
53946
+ if (!Number.isInteger(qty) || qty < 1 || qty > MAX_COPIES) return `asks for ${qty} copies`;
53947
+ if (at?.board === to) return `already in ${boardName(to)}`;
53948
+ if (at) return `already in ${boardName(at.board)}; move it instead`;
53949
+ return to === "deck" ? entryProblem(card, qty, ctx.identity) : null;
53950
+ }
53951
+ case "remove":
53952
+ return at ? null : "not in the deck (already cut?)";
53953
+ case "setQty": {
53954
+ if (!at || at.board !== "deck") return "not in the deck";
53955
+ if (!Number.isInteger(op.qty) || op.qty < 1 || op.qty > MAX_COPIES) return `asks for ${op.qty} copies`;
53956
+ if (op.qty === at.qty) return `already ${op.qty} ${op.qty === 1 ? "copy" : "copies"}`;
53957
+ return op.qty > 1 && !allowsMultipleCopies(card.typeLine, card.name) ? "only one copy is allowed" : null;
53958
+ }
53959
+ case "move": {
53960
+ if (!at) return "not in the deck";
53961
+ if (at.board === op.to) return `already in ${boardName(op.to)}`;
53962
+ return op.to === "deck" ? entryProblem(card, 1, ctx.identity) : null;
53963
+ }
53964
+ }
53965
+ }
53966
+ function run(s, op, card, ctx) {
53967
+ const at = placeOf(s, card);
53968
+ const dispatch = (a) => s = deckPlanReducer(s, a);
53969
+ const leave = (from) => {
53970
+ if (from.board === "deck") {
53971
+ if (from.owned) dispatch({ type: "unassign", oracleId: card.oracleId });
53972
+ else dispatch({ type: "removePurchase", slug: from.slug });
53973
+ } else if (from.board === "considering") dispatch({ type: "removeFromConsidering", oracleId: card.oracleId });
53974
+ else dispatch({ type: "removeFromSideboard", oracleId: card.oracleId });
53975
+ };
53976
+ const enter = (to, qty) => {
53977
+ if (to === "considering") return dispatch({ type: "addToConsidering", oracleId: card.oracleId });
53978
+ if (to === "sideboard") return dispatch({ type: "addToSideboard", oracleId: card.oracleId });
53979
+ const d = addDecision(card, ctx.owned(card.oracleId));
53980
+ if (d.action === "assign") {
53981
+ dispatch({ type: "assign", oracleId: d.oracleId, slot: d.slot, card: { name: card.name, typeLine: card.typeLine } });
53982
+ if (qty > 1) dispatch({ type: "adjustBasicQty", oracleId: d.oracleId, delta: qty - 1, ownedQty: MAX_COPIES });
53983
+ } else {
53984
+ dispatch({ type: "addPurchase", slug: d.slug, slot: d.slot });
53985
+ if (qty > 1) dispatch({ type: "adjustPurchaseQty", slug: d.slug, delta: qty - 1, max: MAX_COPIES });
53986
+ }
53987
+ };
53988
+ const id = card.oracleId;
53989
+ switch (op.op) {
53990
+ case "add":
53991
+ enter(op.to ?? "deck", op.qty ?? 1);
53992
+ return { state: s, inverse: { op: "remove", oracleId: id } };
53993
+ case "remove": {
53994
+ const from = at;
53995
+ leave(from);
53996
+ const back = { op: "add", oracleId: id, to: from.board, ...from.board === "deck" && from.qty > 1 ? { qty: from.qty } : {} };
53997
+ return { state: s, inverse: back };
53998
+ }
53999
+ case "setQty": {
54000
+ const from = at;
54001
+ const delta = op.qty - from.qty;
54002
+ if (from.owned) dispatch({ type: "adjustBasicQty", oracleId: id, delta, ownedQty: MAX_COPIES });
54003
+ else dispatch({ type: "adjustPurchaseQty", slug: from.slug, delta, max: MAX_COPIES });
54004
+ return { state: s, inverse: { op: "setQty", oracleId: id, qty: from.qty } };
54005
+ }
54006
+ case "move": {
54007
+ const from = at;
54008
+ leave(from);
54009
+ enter(op.to, from.board === "deck" ? from.qty : 1);
54010
+ return { state: s, inverse: { op: "move", oracleId: id, to: from.board } };
54011
+ }
54012
+ }
54013
+ }
54014
+ function summarizeDeckOps(ops) {
54015
+ const add = ops.filter((o) => o.op === "add").length;
54016
+ const cut = ops.filter((o) => o.op === "remove").length;
54017
+ const moved = ops.filter((o) => o.op === "move").length;
54018
+ const counts = ops.filter((o) => o.op === "setQty").length;
54019
+ return [
54020
+ add ? `+${add}` : "",
54021
+ cut ? `\u2212${cut}` : "",
54022
+ moved ? `${moved} moved` : "",
54023
+ counts ? `${counts} recounted` : ""
54024
+ ].filter(Boolean).join(" ") || "no change";
54025
+ }
54026
+
54027
+ // ../src/lib/agentRequests/request.ts
54028
+ init_deckText();
54029
+ init_tags();
54030
+ var REQUEST_KIND_LETTER = {
54031
+ edit_deck: "e",
54032
+ set_deck_notes: "e",
54033
+ move_to_folder: "e",
54034
+ create_deck: "c"
54035
+ };
54036
+ var MAX_NOTE_CHARS = 500;
54037
+ var MAX_CARDS_PER_NEW_DECK = 120;
54038
+ var MAX_DECKS_PER_MOVE = 50;
54039
+ var MAX_FOLDER_NAME = 60;
54040
+ var NOTE_FIELDS = ["name", "description", "notes", "primer", "tags"];
54041
+ var NOTES_PART_FIELDS = ["description", "notes", "primer"];
54042
+ var OID_RE = /^[0-9a-f-]{8,64}$/i;
54043
+ var SEEN_RE = /^[0-9a-f]{8}$/;
54044
+ var DECK_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
54045
+ function parseOp(x) {
54046
+ if (!x || typeof x !== "object") return null;
54047
+ const o = x;
54048
+ if (typeof o.oracleId !== "string" || !OID_RE.test(o.oracleId)) return null;
54049
+ const board = (b) => typeof b === "string" && DECK_BOARDS.includes(b);
54050
+ const count2 = (n) => Number.isInteger(n) && n >= 1 && n <= MAX_COPIES;
54051
+ switch (o.op) {
54052
+ case "add":
54053
+ if (o.qty !== void 0 && !count2(o.qty)) return null;
54054
+ if (o.to !== void 0 && !board(o.to)) return null;
54055
+ return { op: "add", oracleId: o.oracleId, ...o.qty !== void 0 ? { qty: o.qty } : {}, ...o.to !== void 0 ? { to: o.to } : {} };
54056
+ case "remove":
54057
+ return { op: "remove", oracleId: o.oracleId };
54058
+ case "setQty":
54059
+ return count2(o.qty) ? { op: "setQty", oracleId: o.oracleId, qty: o.qty } : null;
54060
+ case "move":
54061
+ return board(o.to) ? { op: "move", oracleId: o.oracleId, to: o.to } : null;
54062
+ default:
54063
+ return null;
54064
+ }
54065
+ }
54066
+ function parseOps(x, max) {
54067
+ if (!Array.isArray(x) || x.length === 0 || x.length > max * 2) return null;
54068
+ const ops = x.map(parseOp);
54069
+ return ops.some((o) => o === null) ? null : ops;
54070
+ }
54071
+ var utf8Bytes = (s) => new TextEncoder().encode(s).length;
54072
+ function parseNotesSet(x) {
54073
+ if (!x || typeof x !== "object" || Array.isArray(x)) return null;
54074
+ const r = x;
54075
+ if (Object.keys(r).some((k) => !NOTE_FIELDS.includes(k))) return null;
54076
+ const out = {};
54077
+ const text = (k, ok) => {
54078
+ if (r[k] === void 0) return true;
54079
+ if (typeof r[k] !== "string" || !ok(r[k])) return false;
54080
+ out[k] = r[k];
54081
+ return true;
54082
+ };
54083
+ if (!text("name", (s) => s.trim().length <= MAX_DECK_NAME_LENGTH)) return null;
54084
+ if (!text("description", (s) => s.trim().length <= MAX_DESCRIPTION_LENGTH)) return null;
54085
+ if (!text("notes", (s) => s.trim().length <= MAX_NOTES_LENGTH)) return null;
54086
+ if (!text("primer", (s) => utf8Bytes(s.trim()) <= MAX_PRIMER_BYTES)) return null;
54087
+ if (r.tags !== void 0) {
54088
+ if (!Array.isArray(r.tags) || r.tags.length > MAX_TAGS_PER_DECK) return null;
54089
+ if (r.tags.some((t) => typeof t !== "string" || !t.trim() || t.trim().length > MAX_TAG_LENGTH)) return null;
54090
+ out.tags = r.tags.map((t) => t.trim());
54091
+ }
54092
+ return Object.keys(out).length ? out : null;
54093
+ }
54094
+ function parseFolderName(x) {
54095
+ return typeof x === "string" && x.trim() && x.trim().length <= MAX_FOLDER_NAME ? x.trim() : null;
54096
+ }
54097
+ function parseRequest(text) {
54098
+ let x;
54099
+ try {
54100
+ x = JSON.parse(text);
54101
+ } catch {
54102
+ return null;
54103
+ }
54104
+ if (!x || typeof x !== "object") return null;
54105
+ const r = x;
54106
+ if (r.v !== 1 || !Number.isFinite(r.madeAt)) return null;
54107
+ if (r.note !== void 0 && (typeof r.note !== "string" || r.note.length > MAX_NOTE_CHARS)) return null;
54108
+ const base = {
54109
+ v: 1,
54110
+ ...typeof r.note === "string" && r.note.trim() ? { note: r.note.trim() } : {},
54111
+ madeAt: r.madeAt
54112
+ };
54113
+ const deck = () => typeof r.deckId === "string" && DECK_ID_RE.test(r.deckId) && Number.isFinite(r.basedOn) && (r.seen === void 0 || typeof r.seen === "string" && SEEN_RE.test(r.seen));
54114
+ const seen = typeof r.seen === "string" ? { seen: r.seen } : {};
54115
+ switch (r.kind) {
54116
+ case "edit_deck": {
54117
+ if (!deck()) return null;
54118
+ const ops = parseOps(r.ops, MAX_CARDS_PER_EDIT);
54119
+ return ops ? { ...base, kind: "edit_deck", deckId: r.deckId, basedOn: r.basedOn, ...seen, ops } : null;
54120
+ }
54121
+ case "set_deck_notes": {
54122
+ if (!deck()) return null;
54123
+ const set3 = parseNotesSet(r.set);
54124
+ return set3 ? { ...base, kind: "set_deck_notes", deckId: r.deckId, basedOn: r.basedOn, ...seen, set: set3 } : null;
54125
+ }
54126
+ case "move_to_folder": {
54127
+ if (!Array.isArray(r.deckIds) || r.deckIds.length === 0 || r.deckIds.length > MAX_DECKS_PER_MOVE) return null;
54128
+ if (r.deckIds.some((id) => typeof id !== "string" || !DECK_ID_RE.test(id))) return null;
54129
+ const folder = r.folder === null ? null : parseFolderName(r.folder);
54130
+ if (r.folder !== null && folder === null) return null;
54131
+ return { ...base, kind: "move_to_folder", deckIds: [...new Set(r.deckIds)], folder };
54132
+ }
54133
+ case "create_deck": {
54134
+ if (!Array.isArray(r.commanders) || r.commanders.length < 1 || r.commanders.length > 2) return null;
54135
+ if (r.commanders.some((c) => typeof c !== "string" || !OID_RE.test(c))) return null;
54136
+ const ops = parseOps(r.ops, MAX_CARDS_PER_NEW_DECK);
54137
+ if (!ops || ops.some((o) => o.op !== "add")) return null;
54138
+ if (r.name !== void 0 && (typeof r.name !== "string" || r.name.trim().length > MAX_DECK_NAME_LENGTH)) return null;
54139
+ const folder = r.folder === void 0 ? void 0 : parseFolderName(r.folder);
54140
+ if (folder === null) return null;
54141
+ return {
54142
+ ...base,
54143
+ kind: "create_deck",
54144
+ ...typeof r.name === "string" && r.name.trim() ? { name: r.name.trim() } : {},
54145
+ commanders: [...new Set(r.commanders)],
54146
+ ops,
54147
+ ...folder ? { folder } : {}
54148
+ };
54149
+ }
54150
+ default:
54151
+ return null;
54152
+ }
54153
+ }
54154
+
54155
+ // ../src/lib/agentRequests/aiHistory.ts
54156
+ init_deckText();
54157
+ init_tags();
54158
+ init_organization();
54159
+
54160
+ // ../src/lib/agentRequests/fingerprint.ts
54161
+ function fnv(s) {
54162
+ let h = 2166136261;
54163
+ for (let i = 0; i < s.length; i++) {
54164
+ h ^= s.charCodeAt(i);
54165
+ h = Math.imul(h, 16777619) >>> 0;
54166
+ }
54167
+ return h.toString(16).padStart(8, "0");
54168
+ }
54169
+ function entriesOf(x) {
54170
+ if (x instanceof Map) return [...x.entries()];
54171
+ if (x instanceof Set) return [...x.values()];
54172
+ if (Array.isArray(x)) return x;
54173
+ if (x && typeof x === "object" && "v" in x && Array.isArray(x.v)) return x.v;
54174
+ return [];
54175
+ }
54176
+ var sorted = (xs) => xs.map((x) => JSON.stringify(x)).sort();
54177
+ function contentPrint(stored) {
54178
+ const s = stored;
54179
+ return fnv(
54180
+ JSON.stringify([
54181
+ sorted(entriesOf(s.assignments)),
54182
+ sorted(entriesOf(s.purchases)),
54183
+ sorted(entriesOf(s.basicQuantities)),
54184
+ sorted(entriesOf(s.purchaseQuantities)),
54185
+ sorted(entriesOf(s.considering)),
54186
+ sorted(entriesOf(s.sideboard)),
54187
+ (Array.isArray(s.commanders) ? s.commanders : []).map((c) => c.oracleId ?? "")
54188
+ ])
54189
+ );
54190
+ }
54191
+ function fieldsPrint(stored, fields) {
54192
+ const s = stored;
54193
+ const norm = (v) => Array.isArray(v) ? v.length ? v : null : typeof v === "string" && v ? v : null;
54194
+ return fnv(JSON.stringify([...fields].sort().map((f) => [f, norm(s[f])])));
54195
+ }
54196
+
54197
+ // ../src/lib/agentRequests/aiHistory.ts
54198
+ var NOTE_FIELD_LABEL = {
54199
+ name: "name",
54200
+ description: "description",
54201
+ notes: "notes",
54202
+ primer: "primer",
54203
+ tags: "tags"
54204
+ };
54205
+ function cleanNoteField(field, value) {
54206
+ switch (field) {
54207
+ case "name":
54208
+ return clampDeckName(value) || null;
54209
+ case "description":
54210
+ return value.trim().slice(0, MAX_DESCRIPTION_LENGTH) || null;
54211
+ case "notes":
54212
+ return value.trim().slice(0, MAX_NOTES_LENGTH) || null;
54213
+ case "primer":
54214
+ return clampPrimer(value) || null;
54215
+ case "tags": {
54216
+ const t = normalizeTags(value);
54217
+ return t.length ? t : null;
54218
+ }
54219
+ }
54220
+ }
54221
+ var fieldOf = (stored, f) => {
54222
+ const v = stored[f];
54223
+ if (f === "tags") return Array.isArray(v) && v.length ? v : null;
54224
+ return typeof v === "string" && v ? v : null;
54225
+ };
54226
+ function textPrint(v) {
54227
+ return fnv(JSON.stringify(v ?? null));
54228
+ }
54229
+ function changedNoteFields(stored, set3) {
54230
+ const out = {};
54231
+ for (const f of NOTE_FIELDS) {
54232
+ const v = set3[f];
54233
+ if (v === void 0) continue;
54234
+ const clean = cleanNoteField(f, v);
54235
+ if (textPrint(clean) !== textPrint(fieldOf(stored, f))) out[f] = clean;
54236
+ }
54237
+ return out;
54238
+ }
54239
+ var summarizeNoteFields = (fields) => fields.map((f) => NOTE_FIELD_LABEL[f]).join(", ") || "no change";
54240
+
54241
+ // src/tools/registry.ts
54242
+ init_emptyDeck();
54243
+ init_deckText();
54244
+ init_tags();
54245
+
54246
+ // ../src/lib/deckPlan/deckLibrary.ts
54247
+ function deckLibrary(plan, index, commanderOracleIds) {
54248
+ const bySlug = buildBuySlugIndex(index);
54249
+ const cards = [];
54250
+ const gaps = /* @__PURE__ */ new Map();
54251
+ let committed = 0;
54252
+ forEachCommitted(plan, (side, key, copies) => {
54253
+ committed += copies;
54254
+ const card = side === "main" ? index.byOracleId.get(key) : bySlug.get(key);
54255
+ if (!card) {
54256
+ const k = `unknown:${key}`;
54257
+ const g = gaps.get(k);
54258
+ if (g) g.copies += copies;
54259
+ else gaps.set(k, { name: side === "buy" ? key : null, copies, why: "unknown" });
54260
+ return;
54261
+ }
54262
+ if (commanderOracleIds.has(card.oracleId)) {
54263
+ const k = `commander:${card.oracleId}`;
54264
+ const g = gaps.get(k);
54265
+ if (g) g.copies += copies;
54266
+ else gaps.set(k, { name: card.name, copies, why: "commander" });
54267
+ return;
54268
+ }
54269
+ for (let i = 0; i < copies; i++) cards.push(card);
54270
+ });
54271
+ return { cards, gaps: [...gaps.values()], committed };
54272
+ }
54273
+ function libraryGapNote(gaps) {
54274
+ if (!gaps.length) return null;
54275
+ const parts = [];
54276
+ const unknown2 = gaps.filter((g) => g.why === "unknown");
54277
+ const n = unknown2.reduce((s, g) => s + g.copies, 0);
54278
+ if (n) {
54279
+ const named = unknown2.flatMap((g) => g.name ? [g.name] : []);
54280
+ parts.push(`${n} card${n === 1 ? "" : "s"} we can't find in the card data${named.length ? ` (${named.join(", ")})` : ""}`);
54281
+ }
54282
+ for (const g of gaps.filter((g2) => g2.why === "commander")) parts.push(`${g.name}, which is also your commander`);
54283
+ return `Not in these games: ${parts.join("; ")}.`;
54284
+ }
54285
+
54286
+ // ../src/lib/deckPlan/speedConsistency.ts
54287
+ var DEFAULT_OPENING_HAND = 7;
54288
+ function cardsSeenByTurn(turn, openingHand = DEFAULT_OPENING_HAND, onDraw = false) {
54289
+ return openingHand + Math.max(0, turn - 1) + (onDraw ? 1 : 0);
54290
+ }
54291
+
54292
+ // ../src/lib/deckPlan/oddsQuestions.ts
54293
+ var OPENING_HAND = 7;
54294
+ function oddsPct(p) {
54295
+ if (!(p > 0)) return "0%";
54296
+ if (p >= 1) return "100%";
54297
+ const r = Math.round(p * 100);
54298
+ return r === 0 ? "<1%" : r === 100 ? ">99%" : `${r}%`;
54299
+ }
54300
+
54301
+ // ../src/lib/deckPlan/oddsFormat.ts
54302
+ function levelMeaning(games) {
54303
+ return `How often this came together in ${games.toLocaleString("en-US")} simulated games, played alone with simple turn-by-turn choices. Best for comparing builds; a skilled pilot at a real table can do better.`;
54304
+ }
54305
+ function headlinePct(p, games) {
54306
+ const { lead, value, tail } = headlineParts(p, games);
54307
+ return [lead, value, tail].filter(Boolean).join(" ");
54308
+ }
54309
+ function headlineParts(p, games) {
54310
+ const n = `in ${games.toLocaleString("en-US")} games`;
54311
+ if (!(p > 0)) return { lead: null, value: "Never", tail: n };
54312
+ if (p >= 1) return { lead: null, value: "Always", tail: n };
54313
+ if (p < 5e-3) return { lead: "Under", value: "1%", tail: null };
54314
+ if (p >= 0.995) return { lead: "Over", value: "99%", tail: null };
54315
+ return { lead: "About", value: `${Math.round(p * 100)}%`, tail: null };
54316
+ }
54317
+ var levelPct = oddsPct;
54318
+ function pointsChange(d) {
54319
+ const t = Math.round(d * 1e3) / 10;
54320
+ return `${t > 0 ? "+" : t < 0 ? "-" : "\xB1"}${Math.abs(t).toFixed(1)} points`;
54321
+ }
54322
+
54323
+ // src/plan.ts
54324
+ init_manaOverrides();
54325
+ init_oddsPlans();
54326
+
53097
54327
  // ../src/lib/deckPlan/handSim.ts
53098
54328
  function mulberry32(seed) {
53099
54329
  let a = seed >>> 0;
@@ -53114,46 +54344,6 @@ function frontFaceLower(typeLine) {
53114
54344
  function isCreatureType(card) {
53115
54345
  return frontFaceLower(card.typeLine).includes("creature");
53116
54346
  }
53117
- function materializeDeckFromPlan({
53118
- assignments,
53119
- purchases,
53120
- purchaseQuantities,
53121
- basicQuantities,
53122
- qtyForCard,
53123
- cardById,
53124
- cardBySlug,
53125
- excludeOracleIds
53126
- }) {
53127
- const out = [];
53128
- const fromAssign = /* @__PURE__ */ new Map();
53129
- for (const [oracleId] of assignments) {
53130
- if (excludeOracleIds?.has(oracleId)) continue;
53131
- const card = cardById(oracleId);
53132
- if (!card) continue;
53133
- const copies = qtyForCard(oracleId, card.typeLine, card.name);
53134
- for (let i = 0; i < copies; i++) out.push(card);
53135
- if (copies > 0) fromAssign.set(oracleId, copies);
53136
- }
53137
- for (const [slug] of purchases) {
53138
- const card = cardBySlug(slug);
53139
- if (!card || excludeOracleIds?.has(card.oracleId)) continue;
53140
- const copies = purchaseQuantities.get(slug) ?? 1;
53141
- for (let i = 0; i < copies; i++) out.push(card);
53142
- }
53143
- for (const [oracleId, qty] of basicQuantities) {
53144
- if (excludeOracleIds?.has(oracleId)) continue;
53145
- const already = fromAssign.get(oracleId) ?? 0;
53146
- if (already >= qty) continue;
53147
- const card = cardById(oracleId);
53148
- if (!card) continue;
53149
- for (let i = already; i < qty; i++) out.push(card);
53150
- }
53151
- return out;
53152
- }
53153
-
53154
- // src/plan.ts
53155
- init_manaOverrides();
53156
- init_oddsPlans();
53157
54347
 
53158
54348
  // ../src/lib/deckPlan/planFetch.ts
53159
54349
  function readFetch(fetches, text) {
@@ -55405,8 +56595,11 @@ function readExilesFirst(text) {
55405
56595
  return { count: count2, ...m[2].startsWith("reveal") ? { untilFound: true } : {} };
55406
56596
  }
55407
56597
  var SYMBOLS = /(?:\{[^}]+\})+/;
56598
+ var TOP_DEPTH = /\b(?:shuffle and )?put (?:that card|it|them) (?:into your library )?(second|third|fourth|fifth) from the top\b/;
56599
+ var DEPTH = { second: 2, third: 3, fourth: 4, fifth: 5 };
55408
56600
  function destination(text) {
55409
56601
  const line = text.split("\n").find((l) => /search your library/.test(l)) ?? "";
56602
+ if (TOP_DEPTH.test(line)) return "top";
55410
56603
  if (/\bon top\b/.test(line) && !/into your hand|onto the battlefield|into your graveyard/.test(line)) return "top";
55411
56604
  if (/into your hand/.test(text)) return "hand";
55412
56605
  if (/onto the battlefield/.test(text)) return "battlefield";
@@ -55436,8 +56629,19 @@ function readTutor(manaCost, oracleText) {
55436
56629
  const lines = text.split("\n");
55437
56630
  const searchLine = lines.find((l) => (/search your library/.test(l) || /^when enchanted creature dies, that creature's controller may search their library\b/.test(l)) && !/\bcycling\b|^\(/.test(l)) ?? "";
55438
56631
  const dieRoll = /\broll a d\d+\b/.test(text) && lines.some((l) => /^\d+(?:[—–-]\d+)? \|.*search your library/.test(l));
56632
+ const mvCap = /\bmana value x or less\b/.test(searchLine) && /\{x\}/i.test(own2) ? "x" : /\bmana value less than or equal to the number of lands you control\b/.test(searchLine) ? "lands" : void 0;
56633
+ const pt = searchLine.match(/\bcreature card with (power|toughness) (\d+) or (less|greater)\b/);
56634
+ const ifDo = searchLine.match(/\b(?:you may )?(?:sacrifice (?:an?|another) (creature|artifact|land)|discard an? (?:(creature|land|artifact) )?card)\. if you do, search your library\b/);
56635
+ const swap = /\bsacrifice any number of lands\. search your library for up to that many land cards\b/.test(searchLine);
56636
+ const depth = searchLine.match(TOP_DEPTH)?.[1];
55439
56637
  const out = {
55440
56638
  to,
56639
+ ...mvCap ? { mvCap } : {},
56640
+ ...pt ? { ptGate: { stat: pt[1], mode: pt[3] === "less" ? "lte" : "gte", value: Number(pt[2]) } } : {},
56641
+ ...depth ? { topDepth: DEPTH[depth] } : {},
56642
+ ...to === "battlefield" && /\bput (?:it|them|that card|those cards) onto the battlefield tapped\b/.test(searchLine) ? { tapped: true } : {},
56643
+ ...ifDo?.[1] ? { sacrificeCost: ifDo[1] } : ifDo ? { discardCost: ifDo[2] ?? "card" } : {},
56644
+ ...swap ? { sacrificeCost: "land" } : {},
55441
56645
  ...needsCreature ? { needs: "creature" } : {},
55442
56646
  // (Delirium: "if there are four or more card types among cards in your
55443
56647
  // graveyard, instead search your library for any card": Demonic Counsel.)
@@ -55494,6 +56698,7 @@ function readTutor(manaCost, oracleText) {
55494
56698
  .../\ban opponent gains control of (?:this|~|it)\b/.test(line) ? { gone: "opponent" } : {},
55495
56699
  ...((m) => m ? { discardCost: m[1] ?? "card" } : {})(head.match(/\bdiscard an? (?:(creature|land|artifact) )?card\b/)),
55496
56700
  ...((m) => m ? { treasureCost: n(m[1]) } : {})(head.match(/\bsacrifice (\w+) treasures?\b/)),
56701
+ ...((m) => m ? { clueCost: n(m[1]) } : {})(head.match(/\bsacrifice (\w+) clues?\b/)),
55497
56702
  ...((m) => m ? { sacrificeCost: m[1] } : {})(head.match(/\bsacrifice (?:an?|another) (creature|artifact|land)\b/)),
55498
56703
  ...limit ? { limit } : {},
55499
56704
  ...loyalty ? { loyalty: Number(loyalty[1]) } : {}
@@ -55510,6 +56715,8 @@ function readTutor(manaCost, oracleText) {
55510
56715
  const castM = trig?.match(/^whenever you cast an? (?:(white|blue|black|red|green) )?(creature|noncreature|artifact|enchantment|instant|sorcery|legendary|historic) spells?$/);
55511
56716
  const castOf = castM?.[2];
55512
56717
  const castColor = castM?.[1] ? { white: "W", blue: "U", black: "B", red: "R", green: "G" }[castM[1]] : void 0;
56718
+ if (trig && /^when [^,]* exploits a creature$/.test(trig) && /(?:^|\n)exploit\b/.test(text))
56719
+ return { ...withFinds, trigger: "enters", gone: "sacrifice" };
55513
56720
  if (trig)
55514
56721
  return {
55515
56722
  ...withFinds,
@@ -55608,6 +56815,10 @@ function tutorFields(read, ov, card) {
55608
56815
  ...read?.gone ? { tutorGone: read.gone } : {},
55609
56816
  ...read?.discardCost ? { tutorDiscard: read.discardCost } : {},
55610
56817
  ...read?.treasureCost ? { tutorTreasures: read.treasureCost } : {},
56818
+ ...read?.mvCap === "lands" ? { tutorMvCap: "lands" } : {},
56819
+ ...read?.clueCost ? { tutorClues: read.clueCost } : {},
56820
+ ...read?.topDepth && read.topDepth > 1 ? { tutorTopDepth: read.topDepth } : {},
56821
+ ...read?.tapped ? { tutorTapped: true } : {},
55611
56822
  ...read?.sacrificeCost ? { tutorSacrifice: read.sacrificeCost } : {},
55612
56823
  ...read?.trigger ? { tutorTrigger: read.trigger } : {},
55613
56824
  ...read?.castOf ? { tutorCastOf: read.castOf } : {},
@@ -55700,8 +56911,12 @@ function zoneEngineProfiles({
55700
56911
  return { ...p, ...read || ov ? tutorFields(read, ov, zone[z2]) : {}, ...cutBy.length ? { cutBy } : {}, ...triggeredBy.length ? { triggeredBy } : {}, ...byToughness && p.creature ? toughnessOf(zone[z2]) : {}, ...byPower && p.creature ? powerOf(zone[z2]) : {}, ...byType && p.creature ? typesOf(zone[z2]) : {}, ...byLegend || byShare ? legendOf(zone[z2]) : {}, ...byShare ? colorsOf(zone[z2]) : {}, ...byRestricted ? { ...typesOfCard(zone[z2]), ...typesOf(zone[z2]), ...colorsOf(zone[z2]) } : {} };
55701
56912
  });
55702
56913
  }
55703
- function classifiedTutors(otagIndex, cards, target) {
56914
+ function classifiedTutors(otagIndex, cards, target, reads) {
55704
56915
  const card = cards.find((c) => c.oracleId === target.oracleId)?.card;
56916
+ const ptFits = (g) => {
56917
+ const v = Number((card ?? target)[g.stat]);
56918
+ return Number.isFinite(v) && ((card ?? target)[g.stat] ?? "") !== "" && (g.mode === "lte" ? v <= g.value : v >= g.value);
56919
+ };
55705
56920
  const cls = classifyDeckTutors(
55706
56921
  otagIndex,
55707
56922
  tutorTargetOf(card ?? target),
@@ -55714,7 +56929,11 @@ function classifiedTutors(otagIndex, cards, target) {
55714
56929
  );
55715
56930
  return /* @__PURE__ */ new Set([
55716
56931
  ...cls.counted.map((t) => t.oracleId),
55717
- ...cls.review.filter((t) => t.mv && mvReaches(t.mv.seed, target.cmc)).map((t) => t.oracleId)
56932
+ ...cls.review.filter((t) => {
56933
+ const r = reads?.get(t.oracleId);
56934
+ if (t.mv) return !!r?.mvCap || mvReaches(t.mv.seed, target.cmc);
56935
+ return !!r?.ptGate && ptFits(r.ptGate);
56936
+ }).map((t) => t.oracleId)
55718
56937
  ]);
55719
56938
  }
55720
56939
  function canTutorFind({
@@ -56149,6 +57368,15 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
56149
57368
  const inHand = new Set(state.hand);
56150
57369
  const bottomed = state.order.slice(0, state.next).filter((i) => !inHand.has(i));
56151
57370
  const onTop = [];
57371
+ const shuffleLibrary = (why2) => {
57372
+ if (!onTop.length) return;
57373
+ lg?.("shuffledAway", { cards: [...onTop], why: why2, note: "known to be on top; the library is shuffled, so they're no longer known" });
57374
+ for (const c of onTop) {
57375
+ taken[c] = 0;
57376
+ bottomed.push(c);
57377
+ }
57378
+ onTop.length = 0;
57379
+ };
56152
57380
  const grave = /* @__PURE__ */ new Set();
56153
57381
  let owedNext = [];
56154
57382
  let lost = false;
@@ -56216,6 +57444,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
56216
57444
  }
56217
57445
  }
56218
57446
  if (pick2 < 0) return;
57447
+ shuffleLibrary("a land search");
56219
57448
  taken[pick2] = 1;
56220
57449
  hand.push(pick2);
56221
57450
  lg?.("searchLandToHand", { card: pick2 });
@@ -56607,6 +57836,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
56607
57836
  const u = Array.from({ length: q.rampLands.n }, () => q.rampLands.colors ?? "WUBRG");
56608
57837
  rampUnits.push(...u);
56609
57838
  lg?.("rampLands", { lands: q.rampLands.n, units: [...u], tapped: q.rampLands.tapped && !landsUntapped(), note: "basic lands from the library onto the battlefield; the engine models them as mana units, not as named cards" });
57839
+ shuffleLibrary("a land search");
56610
57840
  if (q.rampLands.tapped && !landsUntapped()) pending.push(...u);
56611
57841
  else {
56612
57842
  online.push(...u);
@@ -57420,6 +58650,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57420
58650
  return colors;
57421
58651
  };
57422
58652
  const boardLets = (t, i) => {
58653
+ if ((t < 0 ? opts.commanders[-1 - t].profile : profiles[t])?.tutorMvCap === "lands" && profiles[i].cost > landOut.size + rampLandsOut) return false;
57423
58654
  const kind = (t < 0 ? opts.commanders[-1 - t].profile : profiles[t])?.tutorShares;
57424
58655
  if (!kind) return true;
57425
58656
  const out = legendColorsOut(kind);
@@ -57965,7 +59196,30 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57965
59196
  if (!live(k) || !r.tutors?.[t] || r.members[t] || !usableFor(k, t, false)) continue;
57966
59197
  const target = pickTarget(k, t);
57967
59198
  if (target < 0) continue;
57968
- lg?.("search", { tutor: t, row: k, target, cost: "none: it searches as it enters, dies, or as a trigger" });
59199
+ const dc = profiles[t].tutorDiscard;
59200
+ const pitch = dc ? hand.find((h) => {
59201
+ const q = profiles[h];
59202
+ if (h === t || (dc === "creature" ? !q.creature || q.land : dc === "land" ? !q.land : dc === "artifact" ? !q.artifact : false)) return false;
59203
+ return !reqs.some((r2, kk) => wanted(kk) && r2.mode !== "graveyard" && (r2.members[h] || !!r2.tutors?.[h]));
59204
+ }) : void 0;
59205
+ if (dc && pitch === void 0) continue;
59206
+ const sk = profiles[t].tutorSacrifice;
59207
+ let victim = -1;
59208
+ if (sk)
59209
+ for (let j = 0; j < deckSize && victim < 0; j++) {
59210
+ const q = profiles[j];
59211
+ if (!cast[j] || j === t || (sk === "creature" ? !q.creature || q.land : sk === "artifact" ? !q.artifact : !q.land)) continue;
59212
+ if (reqs.some((r2, kk) => wanted(kk) && r2.mode !== "graveyard" && (r2.members[j] || !!r2.tutors?.[j]))) continue;
59213
+ victim = j;
59214
+ }
59215
+ if (sk && victim < 0) continue;
59216
+ lg?.("search", { tutor: t, row: k, target, cost: "none: it searches as it enters, dies, or as a trigger", discarded: pitch ?? null, sacrificed: victim >= 0 ? victim : null });
59217
+ if (pitch !== void 0) {
59218
+ removeFromHand(pitch);
59219
+ grave.add(pitch);
59220
+ }
59221
+ if (victim >= 0) sacrifice([victim]);
59222
+ if (profiles[t].tutorGone === "sacrifice" && cast[t]) sacrifice([t]);
57969
59223
  deliver(k, t, target);
57970
59224
  tutorTurn.set(t, turn);
57971
59225
  usedTutor = true;
@@ -58085,11 +59339,28 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
58085
59339
  }
58086
59340
  }
58087
59341
  const to = tq.tutorTo ?? "hand";
59342
+ shuffleLibrary("a tutor's search");
58088
59343
  const put = (i) => {
58089
59344
  taken[i] = 1;
58090
- lg?.("found", { tutor: t, row: k, card: i, to, wasBottomed: bottomed.includes(i) });
58091
- if (to === "battlefield") castCard(i, true);
58092
- else if (to === "top") onTop.push(i);
59345
+ lg?.("found", { tutor: t, row: k, card: i, to, wasBottomed: bottomed.includes(i), ...tq.tutorTopDepth ? { depth: tq.tutorTopDepth } : {}, ...tq.tutorTapped ? { tapped: true } : {} });
59346
+ if (to === "battlefield") {
59347
+ castCard(i, true);
59348
+ if (tq.tutorTapped) {
59349
+ const u = srcOut.get(i) ?? [];
59350
+ removeUnits(online, u);
59351
+ removeUnits(pool, u);
59352
+ pending.push(...u);
59353
+ }
59354
+ } else if (to === "top" && (tq.tutorTopDepth ?? 1) > 1) {
59355
+ const above = [];
59356
+ for (let j = next; above.length < tq.tutorTopDepth - 1 && j < state.order.length; j++) {
59357
+ const c = state.order[j];
59358
+ if (taken[c] || under[c]) continue;
59359
+ taken[c] = 1;
59360
+ above.push(c);
59361
+ }
59362
+ onTop.push(...above, i);
59363
+ } else if (to === "top") onTop.push(i);
58093
59364
  else if (to === "graveyard") grave.add(i);
58094
59365
  else hand.push(i);
58095
59366
  };
@@ -58231,6 +59502,8 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
58231
59502
  if (sk && victim < 0) continue;
58232
59503
  const tc5 = profiles[t].tutorTreasures ?? 0;
58233
59504
  if (tc5 && pool.filter((u) => u === TREASURE).length < tc5) continue;
59505
+ const clues = profiles[t].tutorClues ?? 0;
59506
+ if (clues && clueCount < clues) continue;
58234
59507
  const out = !!cast[t];
58235
59508
  if (!out) feed(t, rituals);
58236
59509
  if (!out && (tapSick(t) || profiles[t].tutorChapter)) {
@@ -58297,6 +59570,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
58297
59570
  grave.add(pitch);
58298
59571
  }
58299
59572
  if (victim >= 0) sacrifice([victim]);
59573
+ if (clues) clueCount -= clues;
58300
59574
  for (let k2 = 0; k2 < tc5; k2++) {
58301
59575
  const at = pool.indexOf(TREASURE);
58302
59576
  if (at >= 0) pool.splice(at, 1);
@@ -58646,6 +59920,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
58646
59920
  landsPlayed++;
58647
59921
  if (profiles[j].fetch) fetchedGrave++;
58648
59922
  const units = landUnitsNow(j);
59923
+ if (profiles[j].fetch && !profiles[j].tapsFirst) shuffleLibrary("a fetch land");
58649
59924
  const creatureLand = !!profiles[j].creature;
58650
59925
  if (creatureLand) entered[j] = turn;
58651
59926
  const tapped = tappedIfPlayed(j) || creatureLand;
@@ -58955,6 +60230,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
58955
60230
  for (const u of left) spent.splice(spent.indexOf(u), 1);
58956
60231
  cycledFor = spent;
58957
60232
  lg?.("landcycle", { card: c, found: land, cost: { generic: lc.generic, pips: { ...lc.pips } }, spentUnits: [...spent], why: "no land in hand to play" });
60233
+ shuffleLibrary("landcycling");
58958
60234
  break;
58959
60235
  }
58960
60236
  }
@@ -58984,6 +60260,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
58984
60260
  for (const u of left) spent.splice(spent.indexOf(u), 1);
58985
60261
  cycledFor = spent;
58986
60262
  lg?.("landcycle", { card: c, found: land, cost: { generic: lc.generic, pips: { ...lc.pips } }, spentUnits: [...spent], why: "a color a row needs that no land of yours makes" });
60263
+ shuffleLibrary("landcycling");
58987
60264
  break;
58988
60265
  }
58989
60266
  mark?.("main 1");
@@ -59005,6 +60282,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
59005
60282
  landsPlayed++;
59006
60283
  if (profiles[pick2].fetch) fetchedGrave++;
59007
60284
  const units = landUnitsNow(pick2);
60285
+ if (profiles[pick2].fetch && !profiles[pick2].tapsFirst) shuffleLibrary("a fetch land");
59008
60286
  const creatureLand = !!profiles[pick2].creature;
59009
60287
  if (creatureLand) entered[pick2] = turn;
59010
60288
  const tapped = tappedIfPlayed(pick2) || creatureLand;
@@ -59095,6 +60373,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
59095
60373
  const u = Array.from({ length: q.rampLands.n }, () => q.rampLands.colors ?? "WUBRG");
59096
60374
  rampUnits.push(...u);
59097
60375
  lg?.("rampLands", { card: j, lands: q.rampLands.n, units: [...u], tapped: q.rampLands.tapped && !landsUntapped(), note: "an activated land search, paid now" });
60376
+ shuffleLibrary("a land search");
59098
60377
  if (q.rampLands.tapped && !landsUntapped()) pending.push(...u);
59099
60378
  else {
59100
60379
  online.push(...u);
@@ -59740,6 +61019,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
59740
61019
  removeUnits(landUnits, units);
59741
61020
  cracked.add(j);
59742
61021
  fetchedGrave++;
61022
+ shuffleLibrary("a fetch land");
59743
61023
  landOut.set(j, found);
59744
61024
  landUnits.push(...found);
59745
61025
  pending.push(...found);
@@ -59888,7 +61168,7 @@ function planContext(a) {
59888
61168
  if (!otagIndex) return /* @__PURE__ */ new Set();
59889
61169
  let hit = tutorCache.get(target.oracleId);
59890
61170
  if (!hit) {
59891
- hit = classifiedTutors(otagIndex, cards, target);
61171
+ hit = classifiedTutors(otagIndex, cards, target, tutorReads);
59892
61172
  tutorCache.set(target.oracleId, hit);
59893
61173
  }
59894
61174
  return hit;
@@ -59898,7 +61178,7 @@ function planContext(a) {
59898
61178
  if (!otagIndex) return /* @__PURE__ */ new Set();
59899
61179
  let hit = zoneTutorCache.get(target.oracleId);
59900
61180
  if (!hit) {
59901
- hit = classifiedTutors(otagIndex, [...cards, ...commanders.map((c) => ({ oracleId: c.oracleId, card: c.card, copies: 1 }))], target);
61181
+ hit = classifiedTutors(otagIndex, [...cards, ...commanders.map((c) => ({ oracleId: c.oracleId, card: c.card, copies: 1 }))], target, new Map([...tutorReads, ...zoneTutorReads]));
59902
61182
  zoneTutorCache.set(target.oracleId, hit);
59903
61183
  }
59904
61184
  return hit;
@@ -60101,15 +61381,6 @@ function resolvePlanRow(row, rc) {
60101
61381
  // src/plan.ts
60102
61382
  init_countRows();
60103
61383
 
60104
- // ../src/lib/deckPlan/speedConsistency.ts
60105
- var DEFAULT_OPENING_HAND = 7;
60106
- function cardsSeenByTurn(turn, openingHand = DEFAULT_OPENING_HAND, onDraw = false) {
60107
- return openingHand + Math.max(0, turn - 1) + (onDraw ? 1 : 0);
60108
- }
60109
-
60110
- // ../src/lib/deckPlan/oddsQuestions.ts
60111
- var OPENING_HAND = 7;
60112
-
60113
61384
  // ../src/lib/deckPlan/planOdds.ts
60114
61385
  var DEEP_SIM = { turns: 5, trials: 5e3 };
60115
61386
  function planSeed(deckSize, reqs, opts = {}) {
@@ -60141,15 +61412,15 @@ function shuffleSeed(seed, game, look) {
60141
61412
  function deepLands(hand, order, reqs, profiles, base, prep, turns) {
60142
61413
  const forced = /* @__PURE__ */ new Map();
60143
61414
  const horizon = Math.min(8, Math.max(turns + 1, ...reqs.map((r) => r.byTurn)));
60144
- const run = (stopAfter, f, hooks) => playGame({ hand: [...hand], order, next: OPENING_HAND }, reqs, profiles, { ...base, deep: { forceLand: f, stopAfter, ...hooks } }, prep);
61415
+ const run2 = (stopAfter, f, hooks) => playGame({ hand: [...hand], order, next: OPENING_HAND }, reqs, profiles, { ...base, deep: { forceLand: f, stopAfter, ...hooks } }, prep);
60145
61416
  for (let t = 1; t <= turns; t++) {
60146
61417
  let cands = [];
60147
61418
  let def = -1;
60148
- run(t, forced, { onLand: (turn, c, p) => turn === t && (cands = c, def = p) });
61419
+ run2(t, forced, { onLand: (turn, c, p) => turn === t && (cands = c, def = p) });
60149
61420
  if (def < 0 || cands.length < 2) continue;
60150
61421
  const score = (c) => {
60151
61422
  let s = 0;
60152
- const g = run(horizon, new Map([...forced, [t, c]]), {
61423
+ const g = run2(horizon, new Map([...forced, [t, c]]), {
60153
61424
  peek: (turn, online, want) => {
60154
61425
  if (turn === horizon) s += 10 * pipsCovered(online, want) + online.length;
60155
61426
  }
@@ -60566,10 +61837,10 @@ function simulatePlan(deckSize, planReqs, opts = {}) {
60566
61837
  }
60567
61838
  function cumulative(counts, to, trials) {
60568
61839
  const out = [];
60569
- let run = 0;
61840
+ let run2 = 0;
60570
61841
  for (let t = 1; t <= to; t++) {
60571
- run += counts[t] ?? 0;
60572
- out.push(run / trials);
61842
+ run2 += counts[t] ?? 0;
61843
+ out.push(run2 / trials);
60573
61844
  }
60574
61845
  return out;
60575
61846
  }
@@ -61626,20 +62897,8 @@ function planModel(deckId, stored, catalog, lib, given) {
61626
62897
  return card ? [card] : [];
61627
62898
  });
61628
62899
  const zoneIds = new Set(zone.map((c) => c.oracleId));
61629
- const basics = stored.basicQuantities ?? /* @__PURE__ */ new Map();
61630
- const deck = canonicalDeck(
61631
- materializeDeckFromPlan({
61632
- assignments: stored.assignments ?? /* @__PURE__ */ new Map(),
61633
- purchases: stored.purchases ?? /* @__PURE__ */ new Map(),
61634
- purchaseQuantities: stored.purchaseQuantities ?? /* @__PURE__ */ new Map(),
61635
- basicQuantities: basics,
61636
- // (selectQtyForCard: an assigned card counts its stored copies, default 1.)
61637
- qtyForCard: (oid) => basics.get(oid) ?? 1,
61638
- cardById: (oid) => catalog.index.byOracleId.get(oid),
61639
- cardBySlug: (slug) => catalog.bySlug.get(slug),
61640
- excludeOracleIds: zoneIds
61641
- })
61642
- );
62900
+ const library = deckLibrary(stored, catalog.index, zoneIds);
62901
+ const deck = canonicalDeck(library.cards);
61643
62902
  if (deck.length === 0) throw new PlanProblem("This deck has no cards to draw yet.");
61644
62903
  const commanders = zone.map(planZoneCard);
61645
62904
  const pool = /* @__PURE__ */ new Map();
@@ -61672,6 +62931,7 @@ function planModel(deckId, stored, catalog, lib, given) {
61672
62931
  const built = buildPlanInput(ctx, resolved, settings);
61673
62932
  return {
61674
62933
  deck,
62934
+ notInGames: libraryGapNote(library.gaps),
61675
62935
  rows,
61676
62936
  settings,
61677
62937
  from: given?.rows?.length ? "given rows" : saved ? "saved plan" : "default rows",
@@ -61793,7 +63053,7 @@ function runPlan(m, opts = {}) {
61793
63053
  const o = opts.deep ? { ...m.input.opts, deep: { turns: DEEP_SIM.turns }, trials: DEEP_SIM.trials } : m.input.opts;
61794
63054
  return simulatePlan(m.input.deckSize, m.input.reqs, o);
61795
63055
  }
61796
- var pct = (p) => `${Math.round(p * 1e3) / 10}%`;
63056
+ var pct = levelPct;
61797
63057
  function assumptionList(list, cap2 = MAX_ASSUMED) {
61798
63058
  const byKind = /* @__PURE__ */ new Map();
61799
63059
  for (const a of list) byKind.set(a.kind, [...byKind.get(a.kind) ?? [], a.name]);
@@ -61819,13 +63079,14 @@ function planAnswer(m, r, withCurve) {
61819
63079
  return {
61820
63080
  plan: m.from,
61821
63081
  ...m.whatIf.length ? { whatIf: { label: "what-if, not saved", reads: m.whatIf } } : {},
61822
- together: { chance: pct(r.all), means: need && need < m.rows.length ? `at least ${need} of the rows` : "every row in the same game", ...withCurve ? { byTurn: r.curve.all.map(pct) } : {} },
63082
+ together: { chance: headlinePct(r.all, r.trials), about: levelMeaning(r.trials), means: need && need < m.rows.length ? `at least ${need} of the rows` : "every row in the same game", ...withCurve ? { byTurn: r.curve.all.map(pct) } : {} },
61823
63083
  rows,
61824
63084
  ...bottleneck ? { mostOftenTheOnlyMiss: m.labels.get(bottleneck.key) } : {},
61825
63085
  onlyThanksToTutors: pct(r.viaTutor),
61826
63086
  averageMulligans: Math.round(r.avgMulligans * 100) / 100,
61827
63087
  game: {
61828
63088
  deckSize: m.deck.length,
63089
+ ...m.notInGames ? { notInGames: m.notInGames } : {},
61829
63090
  onTheDraw: m.settings.onDraw,
61830
63091
  mulligans: m.settings.mulligans,
61831
63092
  keepLands: `${m.settings.keepLands[0]} to ${m.settings.keepLands[1]}`,
@@ -62087,9 +63348,14 @@ var getDeck = {
62087
63348
  }
62088
63349
  const stored = asDeck(notes ? { ...raw, ...notes } : raw);
62089
63350
  const noNotes = !src.pasted && !canNotes;
63351
+ const pending = !src.pasted && await ctx.library.canRequest() ? (await ctx.library.requests()).filter((r) => r.status === "pending").flatMap((r) => {
63352
+ const req = requestOf(r.text);
63353
+ return req && touchesDeck(req, id) ? [{ request: r.id, kind: req.kind, summary: requestSummary(req), status: "waiting for the user" }] : [];
63354
+ }) : [];
62090
63355
  return json2({
62091
63356
  ...deckAnswer(viewDeck(id, stored, catalog, combos?.index), stored, detail, typeof args.only === "string" ? args.only : void 0),
62092
63357
  ...noNotes ? { notesLeftOut: noScopeMessage("notes") } : {},
63358
+ ...pending.length ? { pendingChanges: pending } : {},
62093
63359
  ...pastedNote(src),
62094
63360
  ...catalog ? comboNotes(combos) : {},
62095
63361
  ...catalog ? staleNote(catalog) : { note: "Card data isn't available, so card names and legality are missing." }
@@ -62312,7 +63578,7 @@ var readInput = external_exports.object({
62312
63578
  });
62313
63579
  var planOdds = {
62314
63580
  name: "plan_odds",
62315
- description: "Odds a deck's plan comes together by turn N, from the same 20,000 seeded games as the Odds tab's Plan by turn: the deck's saved plan, or rows you give. Takes every Odds tab setting with the tab's meaning: per row AND / OR parts, have / play / graveyard, mulligan for it (one, one or a tutor, all, a 7 that casts it), tutors off, what it gives you; and the game's mulligans, play or draw, the land range to keep (keepLands), opponents, how many rows must come together (need), the table guesses, and the deep sim. Counts the user's own card reads and tutors, and lists what it had to assume (weAssume). `reads` tries card reads for this run only (what-if, not saved).",
63581
+ description: "Odds a deck's plan comes together by turn N, from the same 20,000 seeded games as the Odds tab's Plan by turn: the deck's saved plan, or rows you give. Takes every Odds tab setting with the tab's meaning: per row AND / OR parts, have / play / graveyard, mulligan for it (one, one or a tutor, all, a 7 that casts it), tutors off, what it gives you; and the game's mulligans, play or draw, the land range to keep (keepLands), opponents, how many rows must come together (need), the table guesses, and the deep sim. Counts the user's own card reads and tutors, and lists what it had to assume (weAssume). Chances are whole percents with About on the total, the way the tab says them: a yardstick for comparing builds under simple play, not the chance at a real table (together.about says so; pass it on). Only the what-if difference keeps a tenth of a point. `reads` tries card reads for this run only (what-if, not saved).",
62316
63582
  input: {
62317
63583
  ...deckOrList,
62318
63584
  rows: external_exports.array(rowInput).max(8).optional().describe("Rows to ask about instead of the deck's saved plan."),
@@ -62348,14 +63614,18 @@ var planOdds = {
62348
63614
  const reads = Array.isArray(args.reads) ? args.reads : [];
62349
63615
  const m = planModel(id, asDeck(raw), catalog, lib, { ...given, reads });
62350
63616
  const deep = args.deep === true;
62351
- const answer = planAnswer(m, runPlan(m, { deep }), args.curve === true);
63617
+ const result = runPlan(m, { deep });
63618
+ const answerAll = result.all;
63619
+ const answer = planAnswer(m, result, args.curve === true);
62352
63620
  const yours = reads.length ? runPlan(planModel(id, asDeck(raw), catalog, lib, given), { deep }) : null;
62353
63621
  return json2({
62354
63622
  deck: viewDeck(id, asDeck(raw), null).name,
62355
63623
  ...pastedNote(src),
62356
63624
  ...answer,
62357
63625
  ...deep ? { deepSim: "the deep sim: early land drops chosen by playing ahead, 5,000 games" } : {},
62358
- ...yours ? { withYourReads: { together: `${Math.round(yours.all * 1e3) / 10}%` } } : {},
63626
+ // (The same seed, so the two runs play the same shuffles: the difference is
63627
+ // sharper than either number, and keeps its tenth of a point.)
63628
+ ...yours ? { withYourReads: { together: headlinePct(yours.all, yours.trials), triedReadsChangeIt: pointsChange(answerAll - yours.all) } } : {},
62359
63629
  ...staleNote(catalog)
62360
63630
  });
62361
63631
  }
@@ -62370,10 +63640,10 @@ function changes(windows) {
62370
63640
  }
62371
63641
  return out;
62372
63642
  }
62373
- function printingChanges(file3, set3, number4, usd, foil) {
63643
+ function printingChanges(file4, set3, number4, usd, foil) {
62374
63644
  const out = {};
62375
63645
  for (const [isFoil, now] of [[false, usd], [true, foil]]) {
62376
- const w = printingTrendWindows(file3, set3, number4, isFoil, now ?? void 0);
63646
+ const w = printingTrendWindows(file4, set3, number4, isFoil, now ?? void 0);
62377
63647
  for (const k of TREND_WINDOWS) {
62378
63648
  const d = w[k]?.delta;
62379
63649
  if (d) out[`${k}${isFoil ? "Foil" : ""}`] = cents(d);
@@ -63438,7 +64708,264 @@ var manabaseTool = {
63438
64708
  });
63439
64709
  }
63440
64710
  };
63441
- var TOOLS = [listDecks, getDeck, collectionLookup, cardSearch, cardTool, tutorTool, swapsTool, commanderTool, deckCombos2, comboSearch, collectionCombos, statsTool, budgetTool, pullListTool, compareTool, overlapTool, manabaseTool, planOdds];
64711
+ var BOARD_INPUT = external_exports.enum(["deck", "considering", "sideboard"]);
64712
+ var requestOf = (text) => text ? parseRequest(text) : null;
64713
+ var touchesDeck = (r, id) => r.kind === "edit_deck" || r.kind === "set_deck_notes" ? r.deckId === id : r.kind === "move_to_folder" ? r.deckIds.includes(id) : false;
64714
+ function requestSummary(r) {
64715
+ switch (r.kind) {
64716
+ case "edit_deck":
64717
+ return summarizeDeckOps(r.ops);
64718
+ case "set_deck_notes":
64719
+ return `set its ${summarizeNoteFields(Object.keys(r.set))}`;
64720
+ case "move_to_folder":
64721
+ return r.folder === null ? `${r.deckIds.length} out of their folders` : `${r.deckIds.length} to ${r.folder}`;
64722
+ case "create_deck":
64723
+ return `a new deck, ${r.ops.length} cards`;
64724
+ }
64725
+ }
64726
+ async function file3(ctx, request) {
64727
+ const letter = REQUEST_KIND_LETTER[request.kind];
64728
+ const r = await ctx.library.fileRequest(letter, JSON.stringify(request));
64729
+ if (r.status === "full") {
64730
+ throw new ToolProblem(`This code already has ${r.maxPending} requests waiting for the user. Ask them to approve or decline some first (get_requests lists them).`);
64731
+ }
64732
+ return r;
64733
+ }
64734
+ var PENDING_ABOUT = "Nothing has changed yet. The user approves or declines it in EDHVault (Settings, AI tools, or on the deck); if things change first, they see that it did. get_requests shows what became of it.";
64735
+ var editDeckTool = {
64736
+ name: "edit_deck",
64737
+ write: true,
64738
+ description: "Ask to change one of the user's saved decks: add cards, cut cards, set a card's copies, or move cards between the deck, considering and the sideboard. This files a REQUEST: nothing changes until the user approves it in EDHVault (Settings, AI tools), and it expires after 7 days. Owned cards go in the deck, others on its buy list, as the deck builder does. At most 30 cards per request. It's checked first against the deck as you see it (already in, not in it, outside the commander's colors, banned, one copy only) and refused with the reasons if it wouldn't apply. Give `note` to say why, in a sentence: the user sees it. Needs an access code allowed to ask to change decks.",
64739
+ input: {
64740
+ deck: external_exports.string().describe("The deck: its name or id (list_decks)."),
64741
+ add: external_exports.array(external_exports.object({ name: external_exports.string(), qty: external_exports.number().int().min(1).max(99).optional(), to: BOARD_INPUT.optional() })).max(30).optional().describe("Cards to add: name, copies (basics and any-number cards only), and where (default: deck)."),
64742
+ remove: external_exports.array(external_exports.string()).max(30).optional().describe("Cards to cut, wherever they are in the deck."),
64743
+ setQuantity: external_exports.array(external_exports.object({ name: external_exports.string(), qty: external_exports.number().int().min(1).max(99) })).max(30).optional().describe("Copies of a card already in the deck."),
64744
+ move: external_exports.array(external_exports.object({ name: external_exports.string(), to: BOARD_INPUT })).max(30).optional().describe("Cards to move to the deck, considering or the sideboard."),
64745
+ note: external_exports.string().max(MAX_NOTE_CHARS).optional().describe("Why, in a sentence. Shown to the user beside the request.")
64746
+ },
64747
+ async run(args, ctx) {
64748
+ if (!await ctx.library.canRequest("e")) throw new ToolProblem(CANT_REQUEST);
64749
+ const catalog = await ctx.catalog();
64750
+ const [id, raw] = findDeck(String(args.deck ?? ""), await ctx.library.decks(true));
64751
+ const stored = asDeck(raw);
64752
+ const card = (name2) => {
64753
+ const c = resolveCardName(catalog.index, name2);
64754
+ if (!c) throw new ToolProblem(`No card named "${name2}".`);
64755
+ return c;
64756
+ };
64757
+ const ops = [
64758
+ ...(args.remove ?? []).map((n) => ({ op: "remove", oracleId: card(n).oracleId })),
64759
+ ...(args.move ?? []).map((m) => ({ op: "move", oracleId: card(m.name).oracleId, to: m.to })),
64760
+ ...(args.setQuantity ?? []).map((m) => ({ op: "setQty", oracleId: card(m.name).oracleId, qty: m.qty })),
64761
+ ...(args.add ?? []).map((a) => ({ op: "add", oracleId: card(a.name).oracleId, ...a.qty ? { qty: a.qty } : {}, ...a.to ? { to: a.to } : {} }))
64762
+ ];
64763
+ if (ops.length === 0) throw new ToolProblem("Nothing to change: give add, remove, setQuantity or move.");
64764
+ const owned = await ownedIdsOf(ctx, catalog, false);
64765
+ const commanders = viewDeck(id, stored, catalog, null).commanderCards;
64766
+ const opCtx = {
64767
+ card: (oid) => catalog.index.byOracleId.get(oid),
64768
+ identity: [...new Set(commanders.flatMap((c) => c.colors))],
64769
+ owned: (oid) => owned.ids.has(oid)
64770
+ };
64771
+ const issues = checkDeckOps(stored, ops, opCtx);
64772
+ if (issues.length) {
64773
+ throw new ToolProblem(`That wouldn't apply to the deck as it is: ${issues.map((i) => i.card ? `${i.card}: ${i.reason}` : i.reason).join("; ")}.`);
64774
+ }
64775
+ const note = noteOf(args);
64776
+ const request = { v: 1, kind: "edit_deck", deckId: id, basedOn: Number(stored.savedAt ?? 0), seen: contentPrint(stored), ops, ...note ? { note } : {}, madeAt: Date.now() };
64777
+ const r = await file3(ctx, request);
64778
+ const name = (oid) => catalog.index.byOracleId.get(oid)?.name ?? oid;
64779
+ return json2({
64780
+ request: r.id,
64781
+ status: "pending",
64782
+ deck: viewDeck(id, stored, null).name,
64783
+ summary: summarizeDeckOps(ops),
64784
+ changes: ops.map(
64785
+ (o) => o.op === "add" ? `+ ${name(o.oracleId)}${o.qty && o.qty > 1 ? ` x${o.qty}` : ""}${o.to && o.to !== "deck" ? ` (to ${o.to})` : ""}` : o.op === "remove" ? `- ${name(o.oracleId)}` : o.op === "setQty" ? `${name(o.oracleId)}: ${o.qty} copies` : `${name(o.oracleId)} to ${o.to}`
64786
+ ),
64787
+ expires: new Date(r.expiresAt).toISOString().slice(0, 10),
64788
+ about: PENDING_ABOUT
64789
+ });
64790
+ }
64791
+ };
64792
+ var noteOf = (args) => typeof args.note === "string" && args.note.trim() ? args.note.trim() : void 0;
64793
+ var noteInput = external_exports.string().max(MAX_NOTE_CHARS).optional().describe("Why, in a sentence. Shown to the user beside the request.");
64794
+ var utf8Bytes2 = (t) => new TextEncoder().encode(t).length;
64795
+ var setDeckNotesTool = {
64796
+ name: "set_deck_notes",
64797
+ write: true,
64798
+ description: "Ask to change a saved deck's name, description (one line), notes (a scratchpad), primer (markdown) or tags. Each field you give REPLACES what's there; an empty string (or empty tag list) clears it. This files a REQUEST: nothing changes until the user approves it, and it expires after 7 days. Changing the description, notes or primer needs a code that can read deck notes (so you see what you'd replace). Needs an access code allowed to ask to change decks.",
64799
+ input: {
64800
+ deck: external_exports.string().describe("The deck: its name or id (list_decks)."),
64801
+ name: external_exports.string().max(MAX_DECK_NAME_LENGTH).optional().describe(`The deck's name (at most ${MAX_DECK_NAME_LENGTH} characters).`),
64802
+ description: external_exports.string().max(MAX_DESCRIPTION_LENGTH).optional().describe(`One line under the name (at most ${MAX_DESCRIPTION_LENGTH} characters).`),
64803
+ notes: external_exports.string().max(MAX_NOTES_LENGTH).optional().describe(`The deck's notes, plain text (at most ${MAX_NOTES_LENGTH} characters).`),
64804
+ primer: external_exports.string().optional().describe(`The primer, markdown (at most ${MAX_PRIMER_BYTES / 1024} KB).`),
64805
+ tags: external_exports.array(external_exports.string().max(MAX_TAG_LENGTH)).max(MAX_TAGS_PER_DECK).optional().describe(`The deck's tags (at most ${MAX_TAGS_PER_DECK}, ${MAX_TAG_LENGTH} characters each).`),
64806
+ note: noteInput
64807
+ },
64808
+ async run(args, ctx) {
64809
+ if (!await ctx.library.canRequest("e")) throw new ToolProblem(CANT_REQUEST);
64810
+ const [id, raw] = findDeck(String(args.deck ?? ""), await ctx.library.decks(true));
64811
+ const set3 = {};
64812
+ for (const f of ["name", "description", "notes", "primer"]) if (typeof args[f] === "string") set3[f] = args[f];
64813
+ if (Array.isArray(args.tags)) set3.tags = args.tags.map((t) => t.trim()).filter(Boolean);
64814
+ const fields = Object.keys(set3);
64815
+ if (fields.length === 0) throw new ToolProblem("Nothing to change: give name, description, notes, primer or tags.");
64816
+ if (set3.primer !== void 0 && utf8Bytes2(set3.primer.trim()) > MAX_PRIMER_BYTES) throw new ToolProblem(`The primer is over ${MAX_PRIMER_BYTES / 1024} KB. Shorten it.`);
64817
+ if (set3.name !== void 0 && !set3.name.trim()) throw new ToolProblem("A deck needs a name: give one, or leave name out.");
64818
+ let current = raw;
64819
+ if (fields.some((f) => NOTES_PART_FIELDS.includes(f))) {
64820
+ if (!await ctx.library.has("notes")) {
64821
+ throw new ToolProblem(`${noScopeMessage("notes")} So it can't change the description, notes or primer (it would be writing over text it can't see).`);
64822
+ }
64823
+ current = { ...raw, ...await ctx.library.notesOf(id, true) ?? {} };
64824
+ }
64825
+ const changing = Object.keys(changedNoteFields(asDeck(current), set3));
64826
+ if (changing.length === 0) throw new ToolProblem("That changes nothing: the deck already says that.");
64827
+ const note = noteOf(args);
64828
+ const request = { v: 1, kind: "set_deck_notes", deckId: id, basedOn: Number(raw.savedAt ?? 0), seen: fieldsPrint(asDeck(current), fields), set: set3, ...note ? { note } : {}, madeAt: Date.now() };
64829
+ const r = await file3(ctx, request);
64830
+ return json2({
64831
+ request: r.id,
64832
+ status: "pending",
64833
+ deck: viewDeck(id, asDeck(raw), null).name,
64834
+ changes: summarizeNoteFields(changing),
64835
+ expires: new Date(r.expiresAt).toISOString().slice(0, 10),
64836
+ about: PENDING_ABOUT
64837
+ });
64838
+ }
64839
+ };
64840
+ var moveToFolderTool = {
64841
+ name: "move_to_folder",
64842
+ write: true,
64843
+ description: "Ask to move saved decks into a folder (made if there's no folder by that name), or out of every folder (folder: null). This files a REQUEST: nothing changes until the user approves it, and it expires after 7 days. Needs an access code allowed to ask to change decks.",
64844
+ input: {
64845
+ decks: external_exports.array(external_exports.string()).min(1).max(MAX_DECKS_PER_MOVE).describe("The decks: names or ids (list_decks)."),
64846
+ folder: external_exports.string().max(MAX_FOLDER_NAME).nullable().describe("The folder's name, or null to take the decks out of their folders."),
64847
+ note: noteInput
64848
+ },
64849
+ async run(args, ctx) {
64850
+ if (!await ctx.library.canRequest("e")) throw new ToolProblem(CANT_REQUEST);
64851
+ const decks = await ctx.library.decks(true);
64852
+ const ids = [...new Set(args.decks.map((d) => findDeck(d, decks)[0]))];
64853
+ const folder = typeof args.folder === "string" ? args.folder.trim() : null;
64854
+ if (typeof args.folder === "string" && !folder) throw new ToolProblem("Give the folder a name, or null to take the decks out of their folders.");
64855
+ const org = (await ctx.library.library())?.org;
64856
+ const inFolder = (id) => Object.entries(org?.membership ?? {}).find(([, m]) => m.includes(id))?.[0] ?? null;
64857
+ const target = folder === null ? null : org?.folders?.find((f) => f.name.trim().toLowerCase() === folder.toLowerCase()) ?? null;
64858
+ const moving = ids.filter((id) => folder === null ? inFolder(id) !== null : inFolder(id) !== target?.id);
64859
+ if (org && moving.length === 0) throw new ToolProblem(folder === null ? "Those decks aren't in a folder." : "Those decks are already there.");
64860
+ const note = noteOf(args);
64861
+ const request = { v: 1, kind: "move_to_folder", deckIds: ids, folder: target?.name ?? folder, ...note ? { note } : {}, madeAt: Date.now() };
64862
+ const r = await file3(ctx, request);
64863
+ return json2({
64864
+ request: r.id,
64865
+ status: "pending",
64866
+ decks: ids.map((id) => viewDeck(id, asDeck(decks.get(id)), null).name),
64867
+ folder: folder === null ? null : target?.name ?? `${folder} (a new folder)`,
64868
+ expires: new Date(r.expiresAt).toISOString().slice(0, 10),
64869
+ about: PENDING_ABOUT
64870
+ });
64871
+ }
64872
+ };
64873
+ var createDeckTool = {
64874
+ name: "create_deck",
64875
+ write: true,
64876
+ description: `Ask to make a new deck: its commander (or a legal pair), a name, the cards it starts with (at most ${MAX_CARDS_PER_NEW_DECK}), and a folder. This files a REQUEST: nothing is made until the user approves it, and it expires after 7 days. Owned cards go in the deck, others on its buy list, as the deck builder does. The deck is private (the user publishes it). It's checked first (a real commander, cards in its colors, not banned, one copy only) and refused with the reasons if it wouldn't work. Needs an access code allowed to ask to make decks.`,
64877
+ input: {
64878
+ commander: external_exports.string().describe("The commander's name."),
64879
+ partner: external_exports.string().optional().describe("A second commander (partner, background, and the like)."),
64880
+ name: external_exports.string().max(MAX_DECK_NAME_LENGTH).optional().describe("The deck's name. Default: the commander's."),
64881
+ cards: external_exports.array(external_exports.object({ name: external_exports.string(), qty: external_exports.number().int().min(1).max(99).optional(), to: BOARD_INPUT.optional() })).max(MAX_CARDS_PER_NEW_DECK).optional().describe("Cards it starts with: name, copies (basics and any-number cards only), and where (default: deck)."),
64882
+ folder: external_exports.string().max(MAX_FOLDER_NAME).optional().describe("A folder to put it in (made if there's none by that name)."),
64883
+ note: noteInput
64884
+ },
64885
+ async run(args, ctx) {
64886
+ if (!await ctx.library.canRequest("c")) throw new ToolProblem(CANT_CREATE);
64887
+ const catalog = await ctx.catalog();
64888
+ const card = (name2) => {
64889
+ const c = resolveCardName(catalog.index, name2);
64890
+ if (!c) throw new ToolProblem(`No card named "${name2}".`);
64891
+ return c;
64892
+ };
64893
+ const commanders = [card(String(args.commander ?? "")), ...typeof args.partner === "string" && args.partner.trim() ? [card(args.partner)] : []];
64894
+ for (const c of commanders) if (!c.canBeCommander) throw new ToolProblem(`${c.name} can't be a commander.`);
64895
+ if (commanders.length === 2) {
64896
+ const pair = isPairLegal(commanders[0], commanders[1]);
64897
+ if (!pair.legal) throw new ToolProblem(`${commanders[0].name} and ${commanders[1].name} can't be commanders together: ${pair.reason}`);
64898
+ }
64899
+ const ops = (args.cards ?? []).map((a) => ({
64900
+ op: "add",
64901
+ oracleId: card(a.name).oracleId,
64902
+ ...a.qty ? { qty: a.qty } : {},
64903
+ ...a.to ? { to: a.to } : {}
64904
+ }));
64905
+ if (ops.length === 0) throw new ToolProblem("Give the deck's cards: a new deck starts with at least one.");
64906
+ const base = { ...emptyStoredDeck(), commanders: commanders.map((c) => ({ oracleId: c.oracleId, name: c.name, colors: c.colors ?? [] })) };
64907
+ const opCtx = {
64908
+ card: (oid) => catalog.index.byOracleId.get(oid),
64909
+ identity: [...new Set(commanders.flatMap((c) => c.colors ?? []))],
64910
+ owned: () => false
64911
+ };
64912
+ const issues = checkDeckOps(base, ops, opCtx, MAX_CARDS_PER_NEW_DECK);
64913
+ if (issues.length) {
64914
+ throw new ToolProblem(`That deck wouldn't work: ${issues.map((i) => i.card ? `${i.card}: ${i.reason}` : i.reason).join("; ")}.`);
64915
+ }
64916
+ const note = noteOf(args);
64917
+ const name = typeof args.name === "string" && args.name.trim() ? args.name.trim() : void 0;
64918
+ const folder = typeof args.folder === "string" && args.folder.trim() ? args.folder.trim() : void 0;
64919
+ const request = {
64920
+ v: 1,
64921
+ kind: "create_deck",
64922
+ ...name ? { name } : {},
64923
+ commanders: commanders.map((c) => c.oracleId),
64924
+ ops,
64925
+ ...folder ? { folder } : {},
64926
+ ...note ? { note } : {},
64927
+ madeAt: Date.now()
64928
+ };
64929
+ const r = await file3(ctx, request);
64930
+ return json2({
64931
+ request: r.id,
64932
+ status: "pending",
64933
+ name: name ?? commanders.map((c) => c.name).join(" + "),
64934
+ commanders: commanders.map((c) => c.name),
64935
+ cards: ops.length,
64936
+ ...folder ? { folder } : {},
64937
+ expires: new Date(r.expiresAt).toISOString().slice(0, 10),
64938
+ about: PENDING_ABOUT
64939
+ });
64940
+ }
64941
+ };
64942
+ var getRequestsTool = {
64943
+ name: "get_requests",
64944
+ description: "The change requests this code has filed (edit_deck, set_deck_notes, move_to_folder, create_deck) and what became of each: pending (waiting for the user), applied, declined, or expired (not answered within 7 days). Each shows what it asked, when this package filed it.",
64945
+ input: {},
64946
+ async run(_args, ctx) {
64947
+ const catalog = await tryCatalog(ctx);
64948
+ const list = await ctx.library.requests();
64949
+ const name = (oid) => catalog?.index.byOracleId.get(oid)?.name ?? oid;
64950
+ return json2({
64951
+ requests: list.sort((a, b) => b.at - a.at).map((r) => {
64952
+ const req = requestOf(r.text);
64953
+ return {
64954
+ request: r.id,
64955
+ status: r.status,
64956
+ ...req ? { kind: req.kind, summary: requestSummary(req) } : {},
64957
+ ...req && (req.kind === "edit_deck" || req.kind === "set_deck_notes") ? { deck: req.deckId } : {},
64958
+ ...req && req.kind === "move_to_folder" ? { decks: req.deckIds } : {},
64959
+ ...req && (req.kind === "edit_deck" || req.kind === "create_deck") ? { cards: [...new Set(req.ops.map((o) => name(o.oracleId)))] } : {},
64960
+ [r.status === "pending" ? "filed" : r.status]: new Date(r.at).toISOString().slice(0, 10),
64961
+ ...r.status === "pending" && r.expiresAt ? { expires: new Date(r.expiresAt).toISOString().slice(0, 10) } : {}
64962
+ };
64963
+ }),
64964
+ about: "Applied changes are in the user's library now (and in each deck's History, where the user can undo them; a new deck is in their Decks). A declined or expired request changed nothing."
64965
+ });
64966
+ }
64967
+ };
64968
+ var TOOLS = [listDecks, getDeck, collectionLookup, cardSearch, cardTool, tutorTool, swapsTool, commanderTool, deckCombos2, comboSearch, collectionCombos, statsTool, budgetTool, pullListTool, compareTool, overlapTool, manabaseTool, planOdds, editDeckTool, setDeckNotesTool, moveToFolderTool, createDeckTool, getRequestsTool];
63442
64969
 
63443
64970
  // src/server.ts
63444
64971
  async function serve(version2, ctx) {
@@ -63449,7 +64976,7 @@ async function serve(version2, ctx) {
63449
64976
  {
63450
64977
  description: tool.description,
63451
64978
  inputSchema: tool.input,
63452
- annotations: { readOnlyHint: true, openWorldHint: false }
64979
+ annotations: tool.write ? { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false } : { readOnlyHint: true, openWorldHint: false }
63453
64980
  },
63454
64981
  async (args) => {
63455
64982
  const r = await runTool(tool, args, ctx);
@@ -63468,7 +64995,7 @@ var say = (m) => process.stderr.write(`${m}
63468
64995
  var transport = {
63469
64996
  fetchImpl: ((url2, init) => fetch(`${ORIGIN}${url2}`, {
63470
64997
  ...init,
63471
- headers: { ...Object.fromEntries(new Headers(init?.headers)), "user-agent": `edhvault-mcp/${"0.2.15"}` }
64998
+ headers: { ...Object.fromEntries(new Headers(init?.headers)), "user-agent": `edhvault-mcp/${"0.2.17"}` }
63472
64999
  }))
63473
65000
  };
63474
65001
  async function store(dir) {
@@ -63484,7 +65011,7 @@ async function secretFromEnv() {
63484
65011
  async function main() {
63485
65012
  const args = process.argv.slice(2);
63486
65013
  if (args.includes("--version")) {
63487
- say("0.2.15");
65014
+ say("0.2.17");
63488
65015
  return;
63489
65016
  }
63490
65017
  const dir = configDir();
@@ -63506,7 +65033,7 @@ async function main() {
63506
65033
  return;
63507
65034
  }
63508
65035
  const extras = extrasLoader({ dir, origin: ORIGIN });
63509
- await serve("0.2.15", {
65036
+ await serve("0.2.17", {
63510
65037
  library: new Library({ secret: await secretFromEnv() ?? loadSecret(secrets), dir, transport }),
63511
65038
  catalog: catalogLoader({ dir, origin: ORIGIN, prices: extras.prices }),
63512
65039
  combos: comboLoader({ dir, origin: ORIGIN }),