edhvault-mcp 0.2.11 → 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 +27 -3
  2. package/dist/cli.js +3161 -265
  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
  }
@@ -791,6 +814,12 @@ async function call(t, url2, init, timeoutMs = FETCH_TIMEOUTS.sync.timeoutMs) {
791
814
  if (why === "too many devices") {
792
815
  throw new SyncHttpError("forbidden", "This sync space already has the most devices it can hold (20). Remove one first.");
793
816
  }
817
+ if (why === "outdated") {
818
+ throw new SyncHttpError("outdated", "This access code is from an older version of EDHVault. Make a new one in edhvault Settings, AI tools access.");
819
+ }
820
+ if (why === "scope") {
821
+ throw new SyncHttpError("no-scope", "This access code can't read that part of your library.");
822
+ }
794
823
  if (why === "too many codes") {
795
824
  throw new SyncHttpError("forbidden", "You already have the most access codes you can (10). Remove one first.");
796
825
  }
@@ -809,6 +838,19 @@ async function errorOf(res) {
809
838
  return null;
810
839
  }
811
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
+ }
812
854
  function unframe(buf) {
813
855
  if (buf.length < 4) return null;
814
856
  const len = new DataView(buf.buffer, buf.byteOffset).getUint32(0);
@@ -821,12 +863,15 @@ function unframe(buf) {
821
863
  }
822
864
  }
823
865
  async function agentFetchBundle(token, t = {}) {
866
+ return (await agentFetchBundleInfo(token, t)).bundle;
867
+ }
868
+ async function agentFetchBundleInfo(token, t = {}) {
824
869
  const res = await call(t, `${SYNC_AGENT_API}/bundle`, { method: "GET", headers: agentHeaders(token) });
825
870
  if (!res.ok) throw new SyncHttpError("server", `Unexpected answer (${res.status}).`);
826
- return new Uint8Array(await res.arrayBuffer());
871
+ return { bundle: new Uint8Array(await res.arrayBuffer()), writes: res.headers.get("x-agent-writes") ?? "" };
827
872
  }
828
- async function agentFetchView(token, etag, t = {}) {
829
- const res = await call(t, `${SYNC_AGENT_API}/view`, {
873
+ async function agentFetchView(token, scope, etag, t = {}) {
874
+ const res = await call(t, `${SYNC_AGENT_API}/view?scope=${encodeURIComponent(scope)}`, {
830
875
  method: "GET",
831
876
  headers: { ...agentHeaders(token), ...etag ? { "x-sync-if-none-match": etag } : {} }
832
877
  });
@@ -836,11 +881,11 @@ async function agentFetchView(token, etag, t = {}) {
836
881
  if (!res.ok) throw new SyncHttpError("server", `Unexpected answer (${res.status}).`);
837
882
  return { status: "ok", etag: tag, sealed: new Uint8Array(await res.arrayBuffer()) };
838
883
  }
839
- async function agentFetchObjects(token, names, t = {}) {
884
+ async function agentFetchObjects(token, scope, names, t = {}) {
840
885
  const res = await call(t, `${SYNC_AGENT_API}/get`, {
841
886
  method: "POST",
842
887
  headers: { ...agentHeaders(token), "content-type": "application/json" },
843
- body: JSON.stringify({ items: names })
888
+ body: JSON.stringify({ scope, items: names })
844
889
  });
845
890
  if (!res.ok) throw new SyncHttpError("server", `Unexpected answer (${res.status}).`);
846
891
  const parsed = unframe(new Uint8Array(await res.arrayBuffer()));
@@ -853,6 +898,24 @@ async function agentFetchObjects(token, names, t = {}) {
853
898
  }
854
899
  return out;
855
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
+ }
856
919
  async function takePair(id, t = {}) {
857
920
  const res = await call(t, `${SYNC_PAIR_API}/${id}`, { method: "GET" });
858
921
  if (res.status === 404) return null;
@@ -7914,9 +7977,9 @@ var require_papaparse = __commonJS({
7914
7977
  };
7915
7978
  Papa.parse(f.file, f.instanceConfig);
7916
7979
  }
7917
- function error62(name, file3, elem, reason) {
7980
+ function error62(name, file4, elem, reason) {
7918
7981
  if (isFunction(options.error))
7919
- options.error({ name }, file3, elem, reason);
7982
+ options.error({ name }, file4, elem, reason);
7920
7983
  }
7921
7984
  function fileComplete() {
7922
7985
  queue.splice(0, 1);
@@ -8291,9 +8354,9 @@ var require_papaparse = __commonJS({
8291
8354
  ChunkStreamer.call(this, config2);
8292
8355
  var reader, slice;
8293
8356
  var usingAsyncReader = typeof FileReader !== "undefined";
8294
- this.stream = function(file3) {
8295
- this._input = file3;
8296
- slice = file3.slice || file3.webkitSlice || file3.mozSlice;
8357
+ this.stream = function(file4) {
8358
+ this._input = file4;
8359
+ slice = file4.slice || file4.webkitSlice || file4.mozSlice;
8297
8360
  if (usingAsyncReader) {
8298
8361
  reader = new FileReader();
8299
8362
  reader.onload = bindFunction(this._chunkLoaded, this);
@@ -9248,23 +9311,635 @@ var init_printings = __esm({
9248
9311
  });
9249
9312
 
9250
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;
9251
9332
  var init_tags = __esm({
9252
9333
  "../src/lib/savedDecks/tags.ts"() {
9253
9334
  "use strict";
9254
9335
  init_storage();
9336
+ MAX_TAG_LENGTH = 24;
9337
+ MAX_TAGS_PER_DECK = 12;
9255
9338
  }
9256
9339
  });
9257
9340
 
9258
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;
9259
9901
  var init_reducer = __esm({
9260
9902
  "../src/lib/deckPlan/reducer.ts"() {
9261
9903
  "use strict";
9262
9904
  init_slug();
9263
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
+ };
9264
9936
  }
9265
9937
  });
9266
9938
 
9267
9939
  // ../src/lib/savedDecks/emptyDeck.ts
9940
+ function emptyStoredDeck() {
9941
+ return toStored(EMPTY_DECK_PLAN);
9942
+ }
9268
9943
  var init_emptyDeck = __esm({
9269
9944
  "../src/lib/savedDecks/emptyDeck.ts"() {
9270
9945
  "use strict";
@@ -9276,13 +9951,15 @@ var init_emptyDeck = __esm({
9276
9951
  function clampDeckName(name) {
9277
9952
  return name.trim().slice(0, MAX_DECK_NAME_LENGTH);
9278
9953
  }
9279
- var MAX_DECK_NAME_LENGTH;
9954
+ var MAX_DESCRIPTION_LENGTH, MAX_NOTES_LENGTH, MAX_DECK_NAME_LENGTH;
9280
9955
  var init_deckText = __esm({
9281
9956
  "../src/lib/savedDecks/deckText.ts"() {
9282
9957
  "use strict";
9283
9958
  init_storage();
9284
9959
  init_tags();
9285
9960
  init_emptyDeck();
9961
+ MAX_DESCRIPTION_LENGTH = 150;
9962
+ MAX_NOTES_LENGTH = 2e3;
9286
9963
  MAX_DECK_NAME_LENGTH = 150;
9287
9964
  }
9288
9965
  });
@@ -11960,9 +12637,9 @@ var require_react_development = __commonJS({
11960
12637
  return "";
11961
12638
  }
11962
12639
  {
11963
- var frame = componentFrameCache.get(fn);
11964
- if (frame !== void 0) {
11965
- return frame;
12640
+ var frame2 = componentFrameCache.get(fn);
12641
+ if (frame2 !== void 0) {
12642
+ return frame2;
11966
12643
  }
11967
12644
  }
11968
12645
  var control;
@@ -14578,12 +15255,12 @@ function cardMatchesProduces(produced, clause) {
14578
15255
  }
14579
15256
  function cardMatchesDerivedFlag(card, flag) {
14580
15257
  const t = card.typeLine.toLowerCase();
14581
- const isLand4 = t.includes("land");
15258
+ const isLand5 = t.includes("land");
14582
15259
  const layout = card.layout ?? "normal";
14583
15260
  switch (flag) {
14584
15261
  // Cast from hand as a spell — everything that isn't a land.
14585
15262
  case "spell":
14586
- return !isLand4;
15263
+ return !isLand5;
14587
15264
  // Stays on the battlefield.
14588
15265
  case "permanent":
14589
15266
  return /\b(creature|artifact|enchantment|land|planeswalker|battle)\b/.test(t) && !/\b(instant|sorcery)\b/.test(t);
@@ -15114,17 +15791,17 @@ function buildOtagBroadMatch(index, slugs) {
15114
15791
 
15115
15792
  // ../src/lib/cardCatalog/setIndex.ts
15116
15793
  init_fetchWithTimeout();
15117
- function hydrateSetIndex(file3) {
15794
+ function hydrateSetIndex(file4) {
15118
15795
  const membership = /* @__PURE__ */ new Map();
15119
- for (const [oid, codes] of Object.entries(file3.membership ?? {})) {
15796
+ for (const [oid, codes] of Object.entries(file4.membership ?? {})) {
15120
15797
  membership.set(oid, new Set(codes));
15121
15798
  }
15122
- const finishes = new Map(Object.entries(file3.finishes ?? {}));
15799
+ const finishes = new Map(Object.entries(file4.finishes ?? {}));
15123
15800
  const treatments = /* @__PURE__ */ new Map();
15124
- for (const [oid, codes] of Object.entries(file3.treatments ?? {})) {
15801
+ for (const [oid, codes] of Object.entries(file4.treatments ?? {})) {
15125
15802
  treatments.set(oid, new Set(codes));
15126
15803
  }
15127
- return { membership, finishes, treatments, sets: file3.sets ?? [] };
15804
+ return { membership, finishes, treatments, sets: file4.sets ?? [] };
15128
15805
  }
15129
15806
  function buildSetMatch(idx) {
15130
15807
  return (oracleId, codes) => {
@@ -15895,8 +16572,8 @@ import { join as join5 } from "node:path";
15895
16572
 
15896
16573
  // ../src/lib/deckStats/baseline.ts
15897
16574
  init_fetchWithTimeout();
15898
- function hydrateBaseline(file3) {
15899
- const { freeSpellOids, finisherOids, ...rest } = file3;
16575
+ function hydrateBaseline(file4) {
16576
+ const { freeSpellOids, finisherOids, ...rest } = file4;
15900
16577
  return {
15901
16578
  ...rest,
15902
16579
  freeSpellOids: new Set(freeSpellOids),
@@ -16013,28 +16690,28 @@ function extrasLoader(opts) {
16013
16690
  throw e;
16014
16691
  });
16015
16692
  };
16016
- const file3 = (name, read) => once(async () => {
16693
+ const file4 = (name, read) => once(async () => {
16017
16694
  const got = await ensureFile(opts, name);
16018
16695
  if (got.stale) stale.add(name);
16019
16696
  return read(JSON.parse(readFileSync5(got.path, "utf8")));
16020
16697
  });
16021
16698
  return {
16022
- prices: file3("card-prices.json", parse.prices),
16023
- printings: file3("printings.json", parse.printings),
16024
- printingTrend: file3("printing-prices-trend.json", parse.printingTrend),
16025
- landCycles: file3("land-cycles.json", parse.landCycles),
16026
- 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),
16027
16704
  comboDetail: once(async () => {
16028
16705
  const files = await ensureDataSet(opts, COMBO_DETAIL_SET);
16029
16706
  if (files.stale) stale.add("combos-detail.json");
16030
16707
  return parse.comboDetail(files.files.map((n) => JSON.parse(readFileSync5(join5(files.dir, n), "utf8"))));
16031
16708
  }),
16032
- deckStatsBaseline: file3("deck-stats-baseline.json", parse.deckStatsBaseline),
16033
- commandersIndex: file3("commanders/_index.json", parse.commandersIndex),
16709
+ deckStatsBaseline: file4("deck-stats-baseline.json", parse.deckStatsBaseline),
16710
+ commandersIndex: file4("commanders/_index.json", parse.commandersIndex),
16034
16711
  commanderDetail: (slug) => {
16035
16712
  if (!/^[a-z0-9-]+$/.test(slug)) return Promise.reject(new Error(`Not a commander slug: ${slug}`));
16036
16713
  let load = details.get(slug);
16037
- 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)));
16038
16715
  return load();
16039
16716
  },
16040
16717
  comboStepsOnDisk: () => existsSync3(join5(opts.dir, COMBO_DETAIL_SET.name, "manifest.json")),
@@ -16050,7 +16727,14 @@ import { join as join6 } from "node:path";
16050
16727
  init_sealedBox();
16051
16728
  init_syncKeys();
16052
16729
  var AGENT_CODE_PREFIX = "EV-AI-";
16053
- var AGENT_SCOPE = "read";
16730
+ var AGENT_SCOPES = ["decks", "notes", "collection", "lists"];
16731
+ var OUTDATED_CODE_MESSAGE = "This access code is from an older version of EDHVault. Make a new one in edhvault Settings, AI tools access.";
16732
+ var AgentCodeOutdated = class extends Error {
16733
+ constructor() {
16734
+ super(OUTDATED_CODE_MESSAGE);
16735
+ this.name = "AgentCodeOutdated";
16736
+ }
16737
+ };
16054
16738
  async function deriveAgentKeys(secret) {
16055
16739
  const [access, wrapKey] = await Promise.all([
16056
16740
  deriveLabelled(secret, "agent-access", 256),
@@ -16071,23 +16755,38 @@ async function parseAgentCode(text) {
16071
16755
  var bundleAad = (ah) => `agent-bundle:${ah}`;
16072
16756
  async function openAgentBundle(sealed, keys) {
16073
16757
  const b = JSON.parse(await openText(sealed, keys.wrapKey, { aad: bundleAad(keys.ah) }));
16074
- const viewKey = b.v === 1 && b.scope === AGENT_SCOPE ? keyFromText(b.viewKey) : null;
16075
- if (!viewKey) throw new Error("This access code's data is from a newer version.");
16076
- return viewKey;
16758
+ if (b.v === 1) throw new AgentCodeOutdated();
16759
+ if (b.v !== 2 || !b.keys || typeof b.keys !== "object") throw new Error("This access code's data is from a newer version.");
16760
+ const out = {};
16761
+ for (const s of AGENT_SCOPES) {
16762
+ const text = b.keys[s];
16763
+ const k = typeof text === "string" ? keyFromText(text) : null;
16764
+ if (k) out[s] = k;
16765
+ }
16766
+ const req = typeof b.req === "string" ? keyFromText(b.req) : null;
16767
+ if (req) out.requests = req;
16768
+ return out;
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) });
16077
16776
  }
16078
16777
 
16079
16778
  // ../src/lib/sync/agentView.ts
16080
16779
  init_sealedBox();
16081
16780
  init_syncKeys();
16082
16781
  init_syncApi();
16083
- var viewAad = (name) => `v:${name}`;
16084
- var INDEX_AAD = "v:index";
16085
- function openViewObject(sealed, viewKey, name) {
16086
- return openText(sealed, viewKey, { aad: viewAad(name) });
16087
- }
16088
- async function openViewIndex(sealed, viewKey) {
16089
- const index = JSON.parse(await openText(sealed, viewKey, { aad: INDEX_AAD }));
16090
- if (!index || index.v !== 1 || typeof index.decks !== "object") {
16782
+ var viewAad = (scope, name) => `v2:${scope}:${name}`;
16783
+ var indexAad = (scope) => `v2:${scope}:index`;
16784
+ function openViewObject(sealed, viewKey, scope, name) {
16785
+ return openText(sealed, viewKey, { aad: viewAad(scope, name) });
16786
+ }
16787
+ async function openViewIndex(sealed, viewKey, scope) {
16788
+ const index = JSON.parse(await openText(sealed, viewKey, { aad: indexAad(scope) }));
16789
+ if (!index || index.v !== 2 || index.scope !== scope || typeof index.decks !== "object") {
16091
16790
  throw new Error("The read copy was written by a newer version of EDHVault.");
16092
16791
  }
16093
16792
  return index;
@@ -16108,9 +16807,21 @@ var LibraryError = class extends Error {
16108
16807
  }
16109
16808
  kind;
16110
16809
  };
16810
+ var KeySwapped = class extends Error {
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;
16111
16815
  var NOT_CONNECTED = "Not connected yet. Run `npx edhvault-mcp login`, or make a code in edhvault Settings, AI tools access.";
16112
16816
  var REMOVED = "This access code was removed. Connect again in edhvault Settings, AI tools access.";
16113
16817
  var NO_COPY = "Your library isn't ready yet. Open edhvault on a synced device, then try again.";
16818
+ var SCOPE_WHAT = {
16819
+ decks: "your decks",
16820
+ notes: "your deck notes, primers and descriptions",
16821
+ collection: "your collection",
16822
+ lists: "your wishlist, binders and seeds"
16823
+ };
16824
+ var noScopeMessage = (scope) => `This access code can't read ${SCOPE_WHAT[scope]}. What a code can read is chosen in edhvault Settings, AI tools access.`;
16114
16825
  function entries(index) {
16115
16826
  return [
16116
16827
  ...Object.values(index.decks),
@@ -16121,104 +16832,160 @@ function entries(index) {
16121
16832
  var Library = class {
16122
16833
  constructor(opts) {
16123
16834
  this.opts = opts;
16124
- this.cache = join6(opts.dir, "view");
16835
+ this.cache = join6(opts.dir, "view2");
16836
+ rmSync2(join6(opts.dir, "view"), { recursive: true, force: true });
16125
16837
  this.now = opts.now ?? Date.now;
16126
16838
  this.freshMs = opts.freshMs ?? FRESH_MS;
16127
16839
  }
16128
16840
  opts;
16129
16841
  token = null;
16130
- viewKey = null;
16131
- index = null;
16132
- etag = null;
16133
- checkedAt = 0;
16842
+ keys = null;
16843
+ /** What this code may ask to change, as the server's letters ("ec"). */
16844
+ writes = "";
16845
+ parts = /* @__PURE__ */ new Map();
16134
16846
  cache;
16135
16847
  now;
16136
16848
  freshMs;
16849
+ forget() {
16850
+ rmSync2(this.cache, { recursive: true, force: true });
16851
+ rmSync2(join6(this.opts.dir, "requests"), { recursive: true, force: true });
16852
+ this.parts.clear();
16853
+ this.token = null;
16854
+ this.keys = null;
16855
+ }
16137
16856
  fail(e) {
16857
+ if (e instanceof AgentCodeOutdated || e instanceof SyncHttpError && e.kind === "outdated") {
16858
+ this.forget();
16859
+ throw new LibraryError("outdated", OUTDATED_CODE_MESSAGE);
16860
+ }
16138
16861
  if (e instanceof SyncHttpError) {
16139
16862
  if (e.kind === "forbidden") {
16140
- rmSync2(this.cache, { recursive: true, force: true });
16141
- this.index = null;
16142
- this.etag = null;
16143
- this.token = null;
16144
- this.viewKey = null;
16863
+ this.forget();
16145
16864
  throw new LibraryError("removed", REMOVED);
16146
16865
  }
16866
+ if (e.kind === "no-scope") {
16867
+ this.token = null;
16868
+ this.keys = null;
16869
+ throw new LibraryError("no-scope", e.message);
16870
+ }
16147
16871
  if (e.kind === "network") throw new LibraryError("offline", "Couldn't reach edhvault.com.");
16148
16872
  }
16149
16873
  throw e;
16150
16874
  }
16151
16875
  async connect() {
16152
- if (this.token && this.viewKey) return { token: this.token, viewKey: this.viewKey };
16876
+ if (this.token && this.keys) return { token: this.token, keys: this.keys };
16153
16877
  if (!this.opts.secret) throw new LibraryError("not-connected", NOT_CONNECTED);
16154
- const keys = await deriveAgentKeys(this.opts.secret);
16155
- let viewKey;
16878
+ const agent = await deriveAgentKeys(this.opts.secret);
16879
+ let keys;
16156
16880
  try {
16157
- viewKey = await openAgentBundle(await agentFetchBundle(keys.token, this.opts.transport), keys);
16881
+ const got = await agentFetchBundleInfo(agent.token, this.opts.transport);
16882
+ keys = await openAgentBundle(got.bundle, agent);
16883
+ this.writes = got.writes;
16158
16884
  } catch (e) {
16159
16885
  this.fail(e);
16160
16886
  }
16161
- this.token = keys.token;
16162
- this.viewKey = viewKey;
16163
- return { token: keys.token, viewKey };
16887
+ this.token = agent.token;
16888
+ this.keys = keys;
16889
+ return { token: agent.token, keys };
16164
16890
  }
16165
- /** The read copy's index, at most FRESH_MS old unless `refresh`. */
16166
- async view(refresh = false) {
16167
- const { token, viewKey } = await this.connect();
16168
- if (this.index && !refresh && this.now() - this.checkedAt < this.freshMs) return this.index;
16891
+ /** The parts this code may read. */
16892
+ async scopes() {
16893
+ const { keys } = await this.connect();
16894
+ return AGENT_SCOPES.filter((s) => keys[s]);
16895
+ }
16896
+ /** Whether this code may read a part. */
16897
+ async has(scope) {
16898
+ return (await this.scopes()).includes(scope);
16899
+ }
16900
+ async key(scope) {
16901
+ const { token, keys } = await this.connect();
16902
+ const key = keys[scope];
16903
+ if (!key) throw new LibraryError("no-scope", noScopeMessage(scope));
16904
+ return { token, key };
16905
+ }
16906
+ /** One part's index, at most FRESH_MS old unless `refresh`. */
16907
+ async view(scope, refresh = false) {
16908
+ try {
16909
+ return await this.viewOnce(scope, refresh);
16910
+ } catch (e) {
16911
+ if (!(e instanceof KeySwapped)) throw e;
16912
+ }
16913
+ this.token = null;
16914
+ this.keys = null;
16915
+ this.parts.delete(scope);
16916
+ try {
16917
+ return await this.viewOnce(scope, true);
16918
+ } catch (e) {
16919
+ if (e instanceof KeySwapped) throw new LibraryError("no-copy", NO_COPY);
16920
+ throw e;
16921
+ }
16922
+ }
16923
+ async viewOnce(scope, refresh) {
16924
+ const { token, key } = await this.key(scope);
16925
+ const part2 = this.parts.get(scope) ?? { index: null, etag: null, checkedAt: 0 };
16926
+ this.parts.set(scope, part2);
16927
+ if (part2.index && !refresh && this.now() - part2.checkedAt < this.freshMs) return part2.index;
16169
16928
  let got;
16170
16929
  try {
16171
- got = await agentFetchView(token, this.etag, this.opts.transport);
16930
+ got = await agentFetchView(token, scope, part2.etag, this.opts.transport);
16172
16931
  } catch (e) {
16173
- if (this.index && e instanceof SyncHttpError && e.kind === "network") return this.index;
16932
+ if (part2.index && e instanceof SyncHttpError && e.kind === "network") return part2.index;
16174
16933
  this.fail(e);
16175
16934
  }
16176
16935
  if (got.status === "missing") throw new LibraryError("no-copy", NO_COPY);
16177
- this.checkedAt = this.now();
16936
+ part2.checkedAt = this.now();
16178
16937
  if (got.status === "ok") {
16179
- this.index = await openViewIndex(got.sealed, viewKey);
16180
- this.etag = got.etag;
16181
- this.prune(this.index);
16938
+ try {
16939
+ part2.index = await openViewIndex(got.sealed, key, scope);
16940
+ } catch {
16941
+ throw new KeySwapped();
16942
+ }
16943
+ part2.etag = got.etag;
16944
+ this.prune(scope, part2.index);
16182
16945
  }
16183
- return this.index;
16946
+ return part2.index;
16947
+ }
16948
+ dirOf(scope) {
16949
+ return join6(this.cache, scope);
16184
16950
  }
16185
- prune(index) {
16186
- if (!existsSync4(this.cache)) return;
16951
+ prune(scope, index) {
16952
+ const dir = this.dirOf(scope);
16953
+ if (!existsSync4(dir)) return;
16187
16954
  const live = new Set(entries(index).map((e) => e.obj));
16188
- for (const f of readdirSync(this.cache)) if (!live.has(f)) rmSync2(join6(this.cache, f), { force: true });
16955
+ for (const f of readdirSync(dir)) if (!live.has(f)) rmSync2(join6(dir, f), { force: true });
16189
16956
  }
16190
- /** Object texts by name, from the disk cache or batched reads. */
16191
- async read(list) {
16192
- const { token, viewKey } = await this.connect();
16193
- mkdirSync3(this.cache, { recursive: true });
16957
+ /** Object texts of one part by name, from the disk cache or batched reads. */
16958
+ async read(scope, list) {
16959
+ const { token, key } = await this.key(scope);
16960
+ const dir = this.dirOf(scope);
16961
+ mkdirSync3(dir, { recursive: true });
16194
16962
  const sealed = /* @__PURE__ */ new Map();
16195
16963
  const missing = [];
16196
16964
  for (const e of list) {
16197
- const file3 = join6(this.cache, e.obj);
16198
- 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)));
16199
16967
  else missing.push(e.obj);
16200
16968
  }
16201
16969
  for (let i = 0; i < missing.length; i += GET_BATCH) {
16202
16970
  let got;
16203
16971
  try {
16204
- got = await agentFetchObjects(token, missing.slice(i, i + GET_BATCH), this.opts.transport);
16972
+ got = await agentFetchObjects(token, scope, missing.slice(i, i + GET_BATCH), this.opts.transport);
16205
16973
  } catch (e) {
16206
16974
  this.fail(e);
16207
16975
  }
16208
16976
  for (const [name, bytes] of got) {
16209
16977
  if (!bytes) continue;
16210
16978
  sealed.set(name, bytes);
16211
- writeFileSync3(join6(this.cache, name), bytes);
16979
+ writeFileSync3(join6(dir, name), bytes);
16212
16980
  }
16213
16981
  }
16214
16982
  const out = /* @__PURE__ */ new Map();
16215
- for (const [name, bytes] of sealed) out.set(name, await openViewObject(bytes, viewKey, name));
16983
+ for (const [name, bytes] of sealed) out.set(name, await openViewObject(bytes, key, scope, name));
16216
16984
  return out;
16217
16985
  }
16218
- /** Every deck, parsed, by deck id. */
16219
- async decks(refresh = false) {
16220
- const index = await this.view(refresh);
16221
- const texts = await this.read(Object.values(index.decks));
16986
+ async partDecks(scope, refresh) {
16987
+ const index = await this.view(scope, refresh);
16988
+ const texts = await this.read(scope, Object.values(index.decks));
16222
16989
  const out = /* @__PURE__ */ new Map();
16223
16990
  for (const [id, e] of Object.entries(index.decks)) {
16224
16991
  const text = texts.get(e.obj);
@@ -16226,24 +16993,108 @@ var Library = class {
16226
16993
  }
16227
16994
  return out;
16228
16995
  }
16996
+ /** Every deck, parsed, by deck id: the decks part, so without primers,
16997
+ * descriptions and notes (those are `notesOf`). */
16998
+ async decks(refresh = false) {
16999
+ return this.partDecks("decks", refresh);
17000
+ }
17001
+ /** One deck's primer, description and notes, from the notes part. null when
17002
+ * the code can't read notes (`has("notes")`) or the deck has none. */
17003
+ async notesOf(id, refresh = false) {
17004
+ if (!await this.has("notes")) return null;
17005
+ const index = await this.view("notes", refresh);
17006
+ const e = index.decks[id];
17007
+ if (!e) return null;
17008
+ const text = (await this.read("notes", [e])).get(e.obj);
17009
+ return text ? JSON.parse(text, reviver) : null;
17010
+ }
16229
17011
  /** Every collection stack. */
16230
17012
  async collection(refresh = false) {
16231
- const index = await this.view(refresh);
17013
+ const index = await this.view("collection", refresh);
16232
17014
  const chunks = Object.values(index.coll?.chunks ?? {});
16233
- const texts = await this.read(chunks);
17015
+ const texts = await this.read("collection", chunks);
16234
17016
  return chunks.flatMap((e) => {
16235
17017
  const text = texts.get(e.obj);
16236
17018
  if (!text) return [];
16237
17019
  return JSON.parse(text).stacks.map(([, stack]) => stack);
16238
17020
  });
16239
17021
  }
16240
- /** The library document, or null when the space has none yet. */
16241
- async library(refresh = false) {
16242
- const index = await this.view(refresh);
17022
+ async partLib(scope, refresh) {
17023
+ if (!await this.has(scope)) return null;
17024
+ const index = await this.view(scope, refresh);
16243
17025
  if (!index.lib) return null;
16244
- const text = (await this.read([index.lib])).get(index.lib.obj);
17026
+ const text = (await this.read(scope, [index.lib])).get(index.lib.obj);
16245
17027
  return text ? JSON.parse(text) : null;
16246
17028
  }
17029
+ /** The library document, from the parts this code holds: the decks part's
17030
+ * folders, card reads and odds plans, the lists part's wishlist, binders and
17031
+ * seeds. null when it holds neither, or the space has none yet. */
17032
+ async library(refresh = false) {
17033
+ const [decks, lists] = await Promise.all([this.partLib("decks", refresh), this.partLib("lists", refresh)]);
17034
+ if (!decks && !lists) return null;
17035
+ return { ...decks ?? {}, ...lists ?? {} };
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
+ }
16247
17098
  };
16248
17099
 
16249
17100
  // src/log.ts
@@ -16342,34 +17193,34 @@ async function osKeychain() {
16342
17193
  return null;
16343
17194
  }
16344
17195
  }
16345
- function lockToOwner(file3) {
17196
+ function lockToOwner(file4) {
16346
17197
  if (process.platform !== "win32") {
16347
- chmodSync(file3, 384);
17198
+ chmodSync(file4, 384);
16348
17199
  return;
16349
17200
  }
16350
17201
  const windir = process.env.SystemRoot ?? "C:\\Windows";
16351
17202
  execFileSync(
16352
17203
  join7(windir, "System32", "icacls.exe"),
16353
- [file3, "/inheritance:r", "/grant:r", `${userInfo().username}:F`],
17204
+ [file4, "/inheritance:r", "/grant:r", `${userInfo().username}:F`],
16354
17205
  { stdio: "ignore", windowsHide: true }
16355
17206
  );
16356
17207
  }
16357
17208
  function fileKeychain(dir) {
16358
- const file3 = join7(dir, ACCOUNT);
17209
+ const file4 = join7(dir, ACCOUNT);
16359
17210
  return {
16360
- get: () => existsSync5(file3) ? readFileSync7(file3, "utf8").trim() : null,
17211
+ get: () => existsSync5(file4) ? readFileSync7(file4, "utf8").trim() : null,
16361
17212
  set: (value) => {
16362
- mkdirSync5(dirname3(file3), { recursive: true, mode: 448 });
16363
- writeFileSync4(file3, "", { mode: 384 });
17213
+ mkdirSync5(dirname3(file4), { recursive: true, mode: 448 });
17214
+ writeFileSync4(file4, "", { mode: 384 });
16364
17215
  try {
16365
- lockToOwner(file3);
17216
+ lockToOwner(file4);
16366
17217
  } catch (e) {
16367
- rmSync3(file3, { force: true });
16368
- 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}`);
16369
17220
  }
16370
- writeFileSync4(file3, value);
17221
+ writeFileSync4(file4, value);
16371
17222
  },
16372
- remove: () => rmSync3(file3, { force: true })
17223
+ remove: () => rmSync3(file4, { force: true })
16373
17224
  };
16374
17225
  }
16375
17226
  function saveSecret(store2, secret) {
@@ -37097,7 +37948,7 @@ function visit(schema, fnOrHandlers) {
37097
37948
  return h ? h(node2, rewritten) : node2;
37098
37949
  };
37099
37950
  const cache2 = /* @__PURE__ */ new Map();
37100
- function run(s) {
37951
+ function run2(s) {
37101
37952
  const cached2 = cache2.get(s);
37102
37953
  if (cached2 === RESOLVING) {
37103
37954
  return new $ZodLazy({
@@ -37123,21 +37974,21 @@ function visit(schema, fnOrHandlers) {
37123
37974
  let changed = false;
37124
37975
  const newShape = {};
37125
37976
  for (const k of keys) {
37126
- const mapped = run(oldShape[k]);
37977
+ const mapped = run2(oldShape[k]);
37127
37978
  if (mapped !== oldShape[k])
37128
37979
  changed = true;
37129
37980
  newShape[k] = mapped;
37130
37981
  }
37131
37982
  let newCatchall = def.catchall;
37132
37983
  if (def.catchall) {
37133
- newCatchall = run(def.catchall);
37984
+ newCatchall = run2(def.catchall);
37134
37985
  if (newCatchall !== def.catchall)
37135
37986
  changed = true;
37136
37987
  }
37137
37988
  return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s;
37138
37989
  }
37139
37990
  case "array": {
37140
- const mapped = run(def.element);
37991
+ const mapped = run2(def.element);
37141
37992
  return mapped === def.element ? s : clone(s, { ...def, element: mapped });
37142
37993
  }
37143
37994
  case "tuple": {
@@ -37145,14 +37996,14 @@ function visit(schema, fnOrHandlers) {
37145
37996
  let changed = false;
37146
37997
  const newItems = [];
37147
37998
  for (const item of oldItems) {
37148
- const mapped = run(item);
37999
+ const mapped = run2(item);
37149
38000
  if (mapped !== item)
37150
38001
  changed = true;
37151
38002
  newItems.push(mapped);
37152
38003
  }
37153
38004
  let newRest = def.rest;
37154
38005
  if (def.rest) {
37155
- newRest = run(def.rest);
38006
+ newRest = run2(def.rest);
37156
38007
  if (newRest !== def.rest)
37157
38008
  changed = true;
37158
38009
  }
@@ -37160,12 +38011,12 @@ function visit(schema, fnOrHandlers) {
37160
38011
  }
37161
38012
  case "record":
37162
38013
  case "map": {
37163
- const newKey2 = run(def.keyType);
37164
- const newVal = run(def.valueType);
38014
+ const newKey2 = run2(def.keyType);
38015
+ const newVal = run2(def.valueType);
37165
38016
  return newKey2 === def.keyType && newVal === def.valueType ? s : clone(s, { ...def, keyType: newKey2, valueType: newVal });
37166
38017
  }
37167
38018
  case "set": {
37168
- const newVal = run(def.valueType);
38019
+ const newVal = run2(def.valueType);
37169
38020
  return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal });
37170
38021
  }
37171
38022
  case "union": {
@@ -37173,7 +38024,7 @@ function visit(schema, fnOrHandlers) {
37173
38024
  let changed = false;
37174
38025
  const newOptions = [];
37175
38026
  for (const opt of oldOptions) {
37176
- const mapped = run(opt);
38027
+ const mapped = run2(opt);
37177
38028
  if (mapped !== opt)
37178
38029
  changed = true;
37179
38030
  newOptions.push(mapped);
@@ -37181,8 +38032,8 @@ function visit(schema, fnOrHandlers) {
37181
38032
  return changed ? clone(s, { ...def, options: newOptions }) : s;
37182
38033
  }
37183
38034
  case "intersection": {
37184
- const newLeft = run(def.left);
37185
- const newRight = run(def.right);
38035
+ const newLeft = run2(def.left);
38036
+ const newRight = run2(def.right);
37186
38037
  return newLeft === def.left && newRight === def.right ? s : clone(s, { ...def, left: newLeft, right: newRight });
37187
38038
  }
37188
38039
  case "optional":
@@ -37194,23 +38045,23 @@ function visit(schema, fnOrHandlers) {
37194
38045
  case "nonoptional":
37195
38046
  case "promise":
37196
38047
  case "success": {
37197
- const newInner = run(def.innerType);
38048
+ const newInner = run2(def.innerType);
37198
38049
  return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner });
37199
38050
  }
37200
38051
  case "pipe": {
37201
- const newIn = run(def.in);
37202
- const newOut = run(def.out);
38052
+ const newIn = run2(def.in);
38053
+ const newOut = run2(def.out);
37203
38054
  return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut });
37204
38055
  }
37205
38056
  case "function": {
37206
- const newInput = run(def.input);
37207
- const newOutput = run(def.output);
38057
+ const newInput = run2(def.input);
38058
+ const newOutput = run2(def.output);
37208
38059
  return newInput === def.input && newOutput === def.output ? s : clone(s, { ...def, input: newInput, output: newOutput });
37209
38060
  }
37210
38061
  case "lazy": {
37211
38062
  const original = def.getter;
37212
38063
  const { _cachedInner, ...rest } = def;
37213
- return clone(s, { ...rest, getter: () => run(original()) });
38064
+ return clone(s, { ...rest, getter: () => run2(original()) });
37214
38065
  }
37215
38066
  // A leaf by choice: `parts` are regex fragments, not data positions.
37216
38067
  case "template_literal":
@@ -37241,7 +38092,7 @@ function visit(schema, fnOrHandlers) {
37241
38092
  }
37242
38093
  }
37243
38094
  }
37244
- return run(schema);
38095
+ return run2(schema);
37245
38096
  }
37246
38097
 
37247
38098
  // ../../commander/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
@@ -46760,18 +47611,15 @@ init_utils();
46760
47611
  // ../src/lib/deckPlan/storedDeckCount.ts
46761
47612
  function countStoredMainboard(plan) {
46762
47613
  let total = 0;
46763
- if (plan.assignments) {
46764
- for (const oid of plan.assignments.keys()) {
46765
- total += plan.basicQuantities?.get(oid) ?? 1;
46766
- }
46767
- }
46768
- if (plan.purchases) {
46769
- for (const slug of plan.purchases.keys()) {
46770
- total += plan.purchaseQuantities?.get(slug) ?? 1;
46771
- }
46772
- }
47614
+ forEachCommitted(plan, (_side, _key, copies) => {
47615
+ total += copies;
47616
+ });
46773
47617
  return total;
46774
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
+ }
46775
47623
 
46776
47624
  // ../src/lib/deckPlan/importDeck.ts
46777
47625
  function looksLikeDeckUrl(input2) {
@@ -48690,6 +49538,187 @@ function groupByDeckCard(variants) {
48690
49538
  );
48691
49539
  }
48692
49540
 
49541
+ // ../src/lib/deckPlan/compareSources.ts
49542
+ init_slug();
49543
+
49544
+ // ../src/lib/deckPlan/compareDecks.ts
49545
+ function buildDeckCardMap(entries2) {
49546
+ const map2 = /* @__PURE__ */ new Map();
49547
+ for (const entry of entries2) {
49548
+ const card = entry?.card;
49549
+ const qty = entry?.qty ?? 0;
49550
+ if (!card || !card.oracleId || qty <= 0) continue;
49551
+ const prev = map2.get(card.oracleId);
49552
+ if (prev) prev.qty += qty;
49553
+ else map2.set(card.oracleId, { card, qty });
49554
+ }
49555
+ return map2;
49556
+ }
49557
+ var byCardName = (a, b) => a.card.name.localeCompare(b.card.name);
49558
+ function compareDecks(mine, theirs) {
49559
+ const onlyMine = [];
49560
+ const onlyTheirs = [];
49561
+ const shared = [];
49562
+ for (const [oracleId, { card, qty }] of mine) {
49563
+ const t = theirs.get(oracleId);
49564
+ if (t) {
49565
+ shared.push({ oracleId, card, mineQty: qty, theirsQty: t.qty });
49566
+ } else {
49567
+ onlyMine.push({ oracleId, card, qty });
49568
+ }
49569
+ }
49570
+ for (const [oracleId, { card, qty }] of theirs) {
49571
+ if (!mine.has(oracleId)) onlyTheirs.push({ oracleId, card, qty });
49572
+ }
49573
+ onlyMine.sort(byCardName);
49574
+ onlyTheirs.sort(byCardName);
49575
+ shared.sort(byCardName);
49576
+ return { onlyMine, onlyTheirs, shared };
49577
+ }
49578
+ function isQtyDelta(s) {
49579
+ return s.mineQty !== s.theirsQty;
49580
+ }
49581
+ function buyDifference(bucket, owned) {
49582
+ let own2 = 0;
49583
+ let buyCount = 0;
49584
+ let buyUsd = 0;
49585
+ for (const e of bucket) {
49586
+ if (owned.has(e.oracleId)) {
49587
+ own2++;
49588
+ continue;
49589
+ }
49590
+ buyCount++;
49591
+ buyUsd += (e.card.priceUsd ?? 0) * e.qty;
49592
+ }
49593
+ return { differ: bucket.length, own: own2, buyCount, buyUsd };
49594
+ }
49595
+
49596
+ // ../src/lib/deckPlan/compareSources.ts
49597
+ function deckCardMapFromStored(blob, cards, slugIndex) {
49598
+ const counts = [];
49599
+ for (const [oid] of blob.assignments) {
49600
+ const card = cards.byOracleId.get(oid);
49601
+ if (card) counts.push({ card, qty: blob.basicQuantities.get(oid) ?? 1 });
49602
+ }
49603
+ for (const [slug] of blob.purchases) {
49604
+ const card = slugIndex.get(slug);
49605
+ if (card) counts.push({ card, qty: blob.purchaseQuantities?.get(slug) ?? 1 });
49606
+ }
49607
+ return buildDeckCardMap(counts);
49608
+ }
49609
+ function buildSlugCardIndex(cards) {
49610
+ const map2 = /* @__PURE__ */ new Map();
49611
+ for (const card of cards.byOracleId.values()) {
49612
+ const slug = toEdhrecSlug(card.name);
49613
+ if (!map2.has(slug)) map2.set(slug, card);
49614
+ if (card.name.includes(" // ")) {
49615
+ const joined = toEdhrecSlug(card.name, { joined: true });
49616
+ if (!map2.has(joined)) map2.set(joined, card);
49617
+ }
49618
+ }
49619
+ return map2;
49620
+ }
49621
+
49622
+ // ../src/lib/deckPlan/crossDeckOverlap.ts
49623
+ function crossDeckOverlap(decks) {
49624
+ const acc = /* @__PURE__ */ new Map();
49625
+ decks.forEach((deck, i) => {
49626
+ for (const [oid, { card, qty }] of deck) {
49627
+ let e = acc.get(oid);
49628
+ if (!e) {
49629
+ e = { card, deckIndices: [], qtyPerDeck: [] };
49630
+ acc.set(oid, e);
49631
+ }
49632
+ e.deckIndices.push(i);
49633
+ e.qtyPerDeck.push(qty);
49634
+ }
49635
+ });
49636
+ const out = [];
49637
+ for (const [oracleId, e] of acc) {
49638
+ out.push({
49639
+ oracleId,
49640
+ card: e.card,
49641
+ inCount: e.deckIndices.length,
49642
+ deckIndices: e.deckIndices,
49643
+ qtyPerDeck: e.qtyPerDeck,
49644
+ maxQty: Math.max(...e.qtyPerDeck)
49645
+ });
49646
+ }
49647
+ out.sort(
49648
+ (a, b) => b.inCount - a.inCount || a.card.name.localeCompare(b.card.name)
49649
+ );
49650
+ return out;
49651
+ }
49652
+
49653
+ // ../src/lib/deckPlan/stickerShare.ts
49654
+ init_utils();
49655
+ var MIN_SHARED_DECKS = 2;
49656
+ function filterOverlap(entries2, opts) {
49657
+ return entries2.filter(
49658
+ (e) => e.inCount >= opts.minDecks && (opts.includeBasics || !isBasicLandType(e.card.typeLine))
49659
+ );
49660
+ }
49661
+ function stickerReadout(entry, owned) {
49662
+ let copiesIfSeparate = 0;
49663
+ for (const q of entry.qtyPerDeck) copiesIfSeparate += q;
49664
+ const copiesToShare = entry.maxQty;
49665
+ return {
49666
+ inCount: entry.inCount,
49667
+ copiesToShare,
49668
+ copiesIfSeparate,
49669
+ saved: copiesIfSeparate - copiesToShare,
49670
+ ownership: owned ? owned.has(entry.oracleId) ? "own" : "buy" : null
49671
+ };
49672
+ }
49673
+ function summarizeStickerShare(rows, owned) {
49674
+ let savedCopies = 0;
49675
+ let savedUsd = 0;
49676
+ let ownedCount = 0;
49677
+ for (const e of rows) {
49678
+ let sum = 0;
49679
+ for (const q of e.qtyPerDeck) sum += q;
49680
+ const saved = sum - e.maxQty;
49681
+ savedCopies += saved;
49682
+ savedUsd += saved * (e.card.priceUsd ?? 0);
49683
+ if (owned && owned.has(e.oracleId)) ownedCount++;
49684
+ }
49685
+ return {
49686
+ sharedCards: rows.length,
49687
+ savedCopies,
49688
+ ownedCount: owned ? ownedCount : null,
49689
+ toBuyCount: owned ? rows.length - ownedCount : null,
49690
+ savedUsd
49691
+ };
49692
+ }
49693
+
49694
+ // ../src/lib/deckPlan/overlapSort.ts
49695
+ var DEFAULT_DIR = {
49696
+ name: "asc",
49697
+ in: "desc",
49698
+ sticker: "asc",
49699
+ price: "desc"
49700
+ };
49701
+ var byName = (a, b) => a.card.name.localeCompare(b.card.name);
49702
+ function sortOverlapRows(rows, key, dir, owned) {
49703
+ const sign = dir === "asc" ? 1 : -1;
49704
+ const cmp = (a, b) => {
49705
+ switch (key) {
49706
+ case "name":
49707
+ return sign * byName(a, b);
49708
+ case "in":
49709
+ return sign * (a.inCount - b.inCount) || byName(a, b);
49710
+ case "price":
49711
+ return sign * ((a.card.priceUsd ?? 0) - (b.card.priceUsd ?? 0)) || byName(a, b);
49712
+ case "sticker": {
49713
+ const oa = owned ? owned.has(a.oracleId) ? 1 : 0 : 0;
49714
+ const ob = owned ? owned.has(b.oracleId) ? 1 : 0 : 0;
49715
+ return sign * (oa - ob) || byName(a, b);
49716
+ }
49717
+ }
49718
+ };
49719
+ return [...rows].sort(cmp);
49720
+ }
49721
+
48693
49722
  // ../src/lib/deckPlan/tutorMvGates.generated.ts
48694
49723
  var PRINTED_MV_GATES = {
48695
49724
  "4c80112a-8ff5-4ca4-8737-b8d499d78982": ["lte", 3],
@@ -51766,6 +52795,734 @@ function budgetStatus(spent, budget) {
51766
52795
  return { over: spent > budget, delta: spent - budget };
51767
52796
  }
51768
52797
 
52798
+ // ../src/lib/deckPlan/karstenTable.generated.ts
52799
+ var KARSTEN_2022 = {
52800
+ landsFrom: 28,
52801
+ landsTo: 45,
52802
+ rows: {
52803
+ 28: [
52804
+ [16, 15, 14, 12, 11, 10, 9],
52805
+ [null, 24, 21, 19, 17, 15, 14],
52806
+ [null, null, 27, 24, 21, 19, 18],
52807
+ [null, null, null, 28, 25, 23, 21]
52808
+ ],
52809
+ 29: [
52810
+ [16, 16, 14, 13, 11, 10, 10],
52811
+ [null, 24, 22, 19, 17, 16, 15],
52812
+ [null, null, 27, 25, 22, 20, 19],
52813
+ [null, null, null, 28, 26, 24, 22]
52814
+ ],
52815
+ 30: [
52816
+ [16, 16, 14, 13, 12, 11, 10],
52817
+ [null, 25, 22, 20, 18, 16, 15],
52818
+ [null, null, 28, 25, 23, 21, 19],
52819
+ [null, null, null, 29, 27, 25, 23]
52820
+ ],
52821
+ 31: [
52822
+ [17, 16, 15, 13, 12, 11, 10],
52823
+ [null, 25, 23, 20, 18, 17, 16],
52824
+ [null, null, 29, 26, 23, 21, 20],
52825
+ [null, null, null, 30, 28, 25, 23]
52826
+ ],
52827
+ 32: [
52828
+ [17, 16, 15, 14, 12, 11, 11],
52829
+ [null, 26, 23, 21, 19, 17, 16],
52830
+ [null, null, 30, 27, 24, 22, 20],
52831
+ [null, null, null, 31, 29, 26, 24]
52832
+ ],
52833
+ 33: [
52834
+ [17, 17, 15, 14, 13, 12, 11],
52835
+ [null, 26, 24, 22, 19, 18, 17],
52836
+ [null, null, 31, 27, 25, 23, 21],
52837
+ [null, null, null, 32, 29, 27, 25]
52838
+ ],
52839
+ 34: [
52840
+ [18, 17, 16, 14, 13, 12, 11],
52841
+ [null, 27, 25, 22, 20, 18, 17],
52842
+ [null, null, 31, 28, 26, 23, 22],
52843
+ [null, null, null, 33, 30, 28, 26]
52844
+ ],
52845
+ 35: [
52846
+ [18, 17, 16, 15, 13, 12, 12],
52847
+ [null, 27, 25, 23, 21, 19, 17],
52848
+ [null, null, 32, 29, 26, 24, 22],
52849
+ [null, null, null, 34, 31, 28, 26]
52850
+ ],
52851
+ 36: [
52852
+ [18, 18, 16, 15, 14, 13, 12],
52853
+ [null, 28, 26, 23, 21, 19, 18],
52854
+ [null, null, 33, 30, 27, 25, 23],
52855
+ [null, null, null, 35, 32, 29, 27]
52856
+ ],
52857
+ 37: [
52858
+ [18, 18, 17, 15, 14, 13, 12],
52859
+ [null, 28, 26, 24, 22, 20, 18],
52860
+ [null, null, 33, 30, 28, 25, 24],
52861
+ [null, null, null, 36, 33, 30, 28]
52862
+ ],
52863
+ 38: [
52864
+ [19, 18, 17, 16, 14, 13, 13],
52865
+ [null, 28, 26, 24, 22, 20, 19],
52866
+ [null, null, 34, 31, 28, 26, 24],
52867
+ [null, null, null, 36, 33, 31, 29]
52868
+ ],
52869
+ 39: [
52870
+ [19, 18, 17, 16, 15, 14, 13],
52871
+ [null, 29, 27, 25, 23, 21, 19],
52872
+ [null, null, 35, 32, 29, 27, 25],
52873
+ [null, null, null, 37, 34, 32, 29]
52874
+ ],
52875
+ 40: [
52876
+ [19, 18, 17, 16, 15, 14, 13],
52877
+ [null, 29, 27, 25, 23, 21, 20],
52878
+ [null, null, 35, 32, 30, 27, 25],
52879
+ [null, null, null, 38, 35, 32, 30]
52880
+ ],
52881
+ 41: [
52882
+ [19, 19, 18, 16, 15, 14, 14],
52883
+ [null, 30, 28, 26, 23, 22, 20],
52884
+ [null, null, 36, 33, 30, 28, 26],
52885
+ [null, null, null, 39, 36, 33, 31]
52886
+ ],
52887
+ 42: [
52888
+ [20, 19, 18, 17, 16, 15, 14],
52889
+ [null, 30, 28, 26, 24, 22, 21],
52890
+ [null, null, 37, 34, 31, 28, 26],
52891
+ [null, null, null, 40, 36, 34, 31]
52892
+ ],
52893
+ 43: [
52894
+ [20, 19, 18, 17, 16, 15, 14],
52895
+ [null, 30, 29, 26, 24, 23, 21],
52896
+ [null, null, 37, 34, 31, 29, 27],
52897
+ [null, null, null, 40, 37, 34, 32]
52898
+ ],
52899
+ 44: [
52900
+ [20, 19, 18, 17, 16, 15, 14],
52901
+ [null, 31, 29, 27, 25, 23, 22],
52902
+ [null, null, 38, 35, 32, 30, 28],
52903
+ [null, null, null, 41, 38, 35, 33]
52904
+ ],
52905
+ 45: [
52906
+ [20, 20, 19, 18, 16, 15, 15],
52907
+ [null, 31, 29, 27, 25, 24, 22],
52908
+ [null, null, 38, 35, 33, 30, 28],
52909
+ [null, null, null, 42, 39, 36, 33]
52910
+ ]
52911
+ }
52912
+ };
52913
+
52914
+ // ../src/lib/deckPlan/manabase.ts
52915
+ function sumDeckPips(cards) {
52916
+ const out = { W: 0, U: 0, B: 0, R: 0, G: 0 };
52917
+ for (const c of cards) {
52918
+ if (!c.colorPips) continue;
52919
+ out.W += c.colorPips.W;
52920
+ out.U += c.colorPips.U;
52921
+ out.B += c.colorPips.B;
52922
+ out.R += c.colorPips.R;
52923
+ out.G += c.colorPips.G;
52924
+ }
52925
+ return out;
52926
+ }
52927
+ function distributeBasics(pips, identity2, slotCount) {
52928
+ const allowed = new Set(identity2);
52929
+ const out = { W: 0, U: 0, B: 0, R: 0, G: 0 };
52930
+ if (slotCount <= 0) return out;
52931
+ const inIdentity = { W: 0, U: 0, B: 0, R: 0, G: 0 };
52932
+ let totalInIdentity = 0;
52933
+ for (const c of WUBRG_ORDER) {
52934
+ if (!allowed.has(c)) continue;
52935
+ inIdentity[c] = pips[c];
52936
+ totalInIdentity += pips[c];
52937
+ }
52938
+ if (totalInIdentity === 0 || allowed.size === 0) {
52939
+ if (allowed.size === 0) return out;
52940
+ const per = Math.floor(slotCount / allowed.size);
52941
+ let remainder = slotCount - per * allowed.size;
52942
+ for (const c of WUBRG_ORDER) {
52943
+ if (!allowed.has(c)) continue;
52944
+ out[c] = per + (remainder > 0 ? 1 : 0);
52945
+ if (remainder > 0) remainder--;
52946
+ }
52947
+ return out;
52948
+ }
52949
+ const shares = [];
52950
+ let floorTotal = 0;
52951
+ for (const c of WUBRG_ORDER) {
52952
+ if (!allowed.has(c)) continue;
52953
+ const exact = inIdentity[c] / totalInIdentity * slotCount;
52954
+ const f = Math.floor(exact);
52955
+ shares.push({ color: c, floor: f, remainder: exact - f });
52956
+ floorTotal += f;
52957
+ out[c] = f;
52958
+ }
52959
+ let leftover = slotCount - floorTotal;
52960
+ shares.sort((a, b) => b.remainder - a.remainder);
52961
+ for (const s of shares) {
52962
+ if (leftover <= 0) break;
52963
+ out[s.color]++;
52964
+ leftover--;
52965
+ }
52966
+ return out;
52967
+ }
52968
+ var BASIC_NAME = {
52969
+ W: "Plains",
52970
+ U: "Island",
52971
+ B: "Swamp",
52972
+ R: "Mountain",
52973
+ G: "Forest"
52974
+ };
52975
+ var KARSTEN_LANDS_RANGE = { min: KARSTEN_2022.landsFrom, max: KARSTEN_2022.landsTo };
52976
+ function karstenTarget(pips, mv, lands) {
52977
+ if (pips <= 0) return 0;
52978
+ const p = Math.min(4, Math.max(1, Math.floor(pips)));
52979
+ const m = Math.max(p, Math.min(7, Math.max(1, Math.floor(mv || 1))));
52980
+ const n = Math.min(
52981
+ KARSTEN_LANDS_RANGE.max,
52982
+ Math.max(KARSTEN_LANDS_RANGE.min, Math.round(Number.isFinite(lands) ? lands : 0))
52983
+ );
52984
+ return KARSTEN_2022.rows[n][p - 1][m - 1];
52985
+ }
52986
+ var KARSTEN_LANDS = { base: 31.42, perAvgMv: 3.13, perCheap: 0.28 };
52987
+ var CHEAP_SPELL_MAX_MV = 2;
52988
+ var LAND_COUNT_RANGE = { min: 28, max: 42 };
52989
+ function recommendedLandCount(inputs) {
52990
+ const raw = KARSTEN_LANDS.base + KARSTEN_LANDS.perAvgMv * inputs.avgMv - KARSTEN_LANDS.perCheap * inputs.cheapRampDraw;
52991
+ return Math.min(LAND_COUNT_RANGE.max, Math.max(LAND_COUNT_RANGE.min, Math.round(raw)));
52992
+ }
52993
+ function isLandCard(card) {
52994
+ return card.typeLine?.toLowerCase().includes("land") ?? false;
52995
+ }
52996
+ function isCheapRampOrDraw(card, lens) {
52997
+ if ((card.cmc ?? 99) > CHEAP_SPELL_MAX_MV) return false;
52998
+ if (lens) return isRamp(card, lens) || isDraw(card, lens);
52999
+ return card.roles.includes("ramp") || card.roles.includes("draw");
53000
+ }
53001
+ function landCountInputs(cards, lens) {
53002
+ let mvSum = 0;
53003
+ let spellCount = 0;
53004
+ const cheap = /* @__PURE__ */ new Set();
53005
+ for (const dc of cards) {
53006
+ if (dc.source === "commander") continue;
53007
+ const c = dc.card;
53008
+ if (isLandCard(c)) continue;
53009
+ const copies = dc.copies ?? 1;
53010
+ mvSum += (c.cmc ?? 0) * copies;
53011
+ spellCount += copies;
53012
+ if (isCheapRampOrDraw(c, lens)) cheap.add(c.oracleId);
53013
+ }
53014
+ return {
53015
+ avgMv: spellCount > 0 ? mvSum / spellCount : 0,
53016
+ cheapRampDraw: cheap.size,
53017
+ spellCount
53018
+ };
53019
+ }
53020
+ function demandPips(card) {
53021
+ const cost = card.manaCost;
53022
+ if (!cost || !/\{(?:[WUBRG]\/[WUBRG]|2\/[WUBRG])\}/.test(cost)) return card.colorPips;
53023
+ const out = { W: 0, U: 0, B: 0, R: 0, G: 0 };
53024
+ for (const face of cost.split(" // ")) {
53025
+ const f = { W: 0, U: 0, B: 0, R: 0, G: 0 };
53026
+ for (const tok of face.match(/\{[^}]+\}/g) ?? []) {
53027
+ const m = /^\{([WUBRG])(?:\/?P)?\}$/.exec(tok);
53028
+ if (m) f[m[1]]++;
53029
+ }
53030
+ for (const c of WUBRG_ORDER) out[c] = Math.max(out[c], f[c]);
53031
+ }
53032
+ return out;
53033
+ }
53034
+ function cardTarget(card, color, lands) {
53035
+ const p = demandPips(card);
53036
+ const pips = p?.[color] ?? 0;
53037
+ if (pips < 1) return 0;
53038
+ const colours = WUBRG_ORDER.filter((c) => (p?.[c] ?? 0) > 0).length;
53039
+ return karstenTarget(pips, card.cmc, lands) + (colours >= 2 ? 1 : 0);
53040
+ }
53041
+ function fetchableColors(fetch2, lands) {
53042
+ const out = /* @__PURE__ */ new Set();
53043
+ const f = fetch2.fetches;
53044
+ if (!f) return out;
53045
+ const typeRes = f.types?.map((t) => new RegExp(`\\b${t.toLowerCase()}\\b`));
53046
+ for (const land of lands) {
53047
+ if (land.oracleId === fetch2.oracleId) continue;
53048
+ const tl = land.typeLine?.toLowerCase() ?? "";
53049
+ if (!/\bland\b/.test(tl)) continue;
53050
+ if (f.basicOnly && !/\bbasic\b/.test(tl)) continue;
53051
+ if (typeRes && !typeRes.some((re) => re.test(tl))) continue;
53052
+ for (const c of land.producedMana ?? []) out.add(c);
53053
+ }
53054
+ return out;
53055
+ }
53056
+
53057
+ // ../src/lib/deckPlan/deckHealth.ts
53058
+ function comb(n, k) {
53059
+ if (k < 0 || k > n) return 0;
53060
+ if (k === 0 || k === n) return 1;
53061
+ const kk = Math.min(k, n - k);
53062
+ let result = 1;
53063
+ for (let i = 0; i < kk; i++) {
53064
+ result = result * (n - i) / (i + 1);
53065
+ }
53066
+ return result;
53067
+ }
53068
+ function hypergeometricPmf(N, K, n, k) {
53069
+ if (k < 0 || k > n || k > K || n - k > N - K) return 0;
53070
+ const denom = comb(N, n);
53071
+ if (denom === 0) return 0;
53072
+ return comb(K, k) * comb(N - K, n - k) / denom;
53073
+ }
53074
+ var OPENING_HAND_SIZE = 7;
53075
+ var MANA_SCREW_MAX_LANDS = 1;
53076
+ var MANA_SWEET_MAX_LANDS = 4;
53077
+ function computeManaConsistency(deckSize, landCount, handSize = OPENING_HAND_SIZE) {
53078
+ if (deckSize <= 0 || handSize <= 0) return null;
53079
+ const K = Math.max(0, Math.min(landCount, deckSize));
53080
+ const n = Math.min(handSize, deckSize);
53081
+ let screw = 0;
53082
+ let sweet = 0;
53083
+ let flood = 0;
53084
+ for (let k = 0; k <= n; k++) {
53085
+ const p = hypergeometricPmf(deckSize, K, n, k);
53086
+ if (k <= MANA_SCREW_MAX_LANDS) screw += p;
53087
+ else if (k <= MANA_SWEET_MAX_LANDS) sweet += p;
53088
+ else flood += p;
53089
+ }
53090
+ return { deckSize, landCount: K, handSize: n, screw, sweet, flood };
53091
+ }
53092
+
53093
+ // ../src/lib/deckPlan/sourceWeights.ts
53094
+ var SOURCE_WEIGHT = {
53095
+ land: 1,
53096
+ splitLand3Color: 2 / 3,
53097
+ opponentLand: 3 / 4,
53098
+ dork: 1 / 2,
53099
+ rock: 3 / 4,
53100
+ opponentRock: 1 / 2,
53101
+ ramp2: 3 / 4,
53102
+ ramp3: 1 / 2,
53103
+ treasure: 1 / 4
53104
+ };
53105
+ var SOURCE_FROM_MV = { tappedLand: 2, dork: 2, rock: 3, ramp2: 3, ramp3: 5, treasure: 2 };
53106
+ var PERMANENT2 = /\b(creature|artifact|enchantment|planeswalker|battle)\b/i;
53107
+ var isLand2 = (c) => /\bland\b/i.test(c.typeLine ?? "");
53108
+ function isPathway(c) {
53109
+ return isLand2(c) && c.layout === "modal_dfc" && / Pathway \/\/ .* Pathway$/.test(c.name);
53110
+ }
53111
+ function sourceWeight(card, color, mv, ctx) {
53112
+ const makes = card.producedMana?.includes(color) ?? false;
53113
+ const fetched = ctx.fetchColors.get(card.oracleId)?.has(color) ?? false;
53114
+ if (isLand2(card)) {
53115
+ if (!makes && !fetched) return 0;
53116
+ if (card.enterTapped === "always" && mv < SOURCE_FROM_MV.tappedLand) return 0;
53117
+ if (card.opponentColors) return SOURCE_WEIGHT.opponentLand;
53118
+ const oneOfSeveral = isPathway(card) || card.fetches?.basicOnly === true && card.fetches.types === null;
53119
+ if (oneOfSeveral && ctx.colorCount >= 3) return SOURCE_WEIGHT.splitLand3Color;
53120
+ return SOURCE_WEIGHT.land;
53121
+ }
53122
+ const manaPermanent = ctx.lens ? ctx.lens.isManaSource(card.oracleId) : PERMANENT2.test(card.typeLine ?? "");
53123
+ if (makes && manaPermanent) {
53124
+ if (/\bcreature\b/i.test(card.typeLine ?? "")) return mv >= SOURCE_FROM_MV.dork ? SOURCE_WEIGHT.dork : 0;
53125
+ if (mv < SOURCE_FROM_MV.rock) return 0;
53126
+ return card.opponentColors ? SOURCE_WEIGHT.opponentRock : SOURCE_WEIGHT.rock;
53127
+ }
53128
+ if (fetched && /\b(instant|sorcery)\b/i.test(card.typeLine ?? "") && card.roles.includes("ramp")) {
53129
+ if (card.cmc <= 2) return mv >= SOURCE_FROM_MV.ramp2 ? SOURCE_WEIGHT.ramp2 : 0;
53130
+ if (card.cmc === 3) return mv >= SOURCE_FROM_MV.ramp3 ? SOURCE_WEIGHT.ramp3 : 0;
53131
+ return 0;
53132
+ }
53133
+ if (card.tokens?.includes("treasure") && ctx.lens?.isRepeatableTreasure(card.oracleId)) {
53134
+ return mv >= SOURCE_FROM_MV.treasure ? SOURCE_WEIGHT.treasure : 0;
53135
+ }
53136
+ return 0;
53137
+ }
53138
+ function formatSources(n) {
53139
+ const r = Math.round(n * 10) / 10;
53140
+ return Number.isInteger(r) ? String(r) : r.toFixed(1);
53141
+ }
53142
+ function formatShortfall(target, have) {
53143
+ return formatSources(target - Math.round(have * 10) / 10);
53144
+ }
53145
+ function wholeShort(n) {
53146
+ return Math.ceil(n - 1e-9);
53147
+ }
53148
+
53149
+ // ../src/components/deckBuilderV2/manaSources.ts
53150
+ init_utils();
53151
+ var MANA_COLOR_ORDER = ["W", "U", "B", "R", "G"];
53152
+ var MANA_COLOR_LABEL = {
53153
+ W: "White",
53154
+ U: "Blue",
53155
+ B: "Black",
53156
+ R: "Red",
53157
+ G: "Green"
53158
+ };
53159
+ function countSources(cards, color, mv, ctx) {
53160
+ let n = 0;
53161
+ for (const { card, copies } of cards) n += copies * sourceWeight(card, color, mv, ctx);
53162
+ return Math.round(n * 100) / 100;
53163
+ }
53164
+ function deckFetchColors(cards) {
53165
+ const out = /* @__PURE__ */ new Map();
53166
+ if (!cards.some(({ card }) => card.fetches)) return out;
53167
+ const lands = cards.filter(({ card }) => isLandCard(card)).map(({ card }) => card);
53168
+ for (const { card } of cards) {
53169
+ if (card.fetches) out.set(card.oracleId, fetchableColors(card, lands));
53170
+ }
53171
+ return out;
53172
+ }
53173
+ var mvTurn = (cmc) => Math.min(7, Math.max(1, Math.floor(cmc || 1)));
53174
+ function measureDemand(cards, color, lands, haveAt) {
53175
+ let need = 0;
53176
+ let doubleNeed = 0;
53177
+ let tripleNeed = 0;
53178
+ let target = 0;
53179
+ let driverPips = 0;
53180
+ let driverMv = 0;
53181
+ let worstGap = -Infinity;
53182
+ for (const { card } of cards) {
53183
+ const pips = demandPips(card)?.[color] ?? 0;
53184
+ if (pips < 1) continue;
53185
+ need++;
53186
+ if (pips >= 2) doubleNeed++;
53187
+ if (pips >= 3) tripleNeed++;
53188
+ const t = cardTarget(card, color, lands);
53189
+ const gap = t - haveAt(mvTurn(card.cmc));
53190
+ if (gap > worstGap || gap === worstGap && (t > target || t === target && pips > driverPips)) {
53191
+ worstGap = gap;
53192
+ target = t;
53193
+ driverPips = pips;
53194
+ driverMv = card.cmc;
53195
+ }
53196
+ }
53197
+ return { target, need, doubleNeed, tripleNeed, driverPips, driverMv };
53198
+ }
53199
+ function classify(have, target) {
53200
+ if (target <= 0) return { status: "none", shortBy: 0 };
53201
+ const diff = Math.round((have - target) * 100) / 100;
53202
+ if (diff >= 3) return { status: "over", shortBy: 0 };
53203
+ if (diff >= -1) return { status: "on", shortBy: Math.max(0, -diff) };
53204
+ return { status: "short", shortBy: -diff };
53205
+ }
53206
+ function manabaseReport(cards, identity2, lens = null) {
53207
+ const idSet = new Set(identity2);
53208
+ const inIdentity = MANA_COLOR_ORDER.filter((c) => idSet.has(c));
53209
+ const rows = [];
53210
+ const fetchColors2 = deckFetchColors(cards);
53211
+ const ctx = { colorCount: inIdentity.length, fetchColors: fetchColors2, lens };
53212
+ let lands = 0;
53213
+ for (const { card, copies } of cards) if (isLandCard(card)) lands += copies;
53214
+ for (const color of MANA_COLOR_ORDER) {
53215
+ const byMv = /* @__PURE__ */ new Map();
53216
+ const haveAt = (mv) => {
53217
+ let v = byMv.get(mv);
53218
+ if (v === void 0) byMv.set(mv, v = countSources(cards, color, mv, ctx));
53219
+ return v;
53220
+ };
53221
+ const demand = measureDemand(cards, color, lands, haveAt);
53222
+ const have = demand.need > 0 ? haveAt(mvTurn(demand.driverMv)) : haveAt(7);
53223
+ const active = inIdentity.length > 0 ? idSet.has(color) : have > 0 || demand.need > 0;
53224
+ if (!active) continue;
53225
+ const { status, shortBy } = classify(have, demand.target);
53226
+ rows.push({ color, have, status, shortBy, ...demand });
53227
+ }
53228
+ const colorless = rows.length === 0 || rows.every((r) => r.have === 0 && r.need === 0);
53229
+ return { colors: rows, colorless, lands };
53230
+ }
53231
+ function manabaseSummary(cards, identity2, lens) {
53232
+ let deckSize = 0;
53233
+ let landsHave = 0;
53234
+ for (const dc of cards) {
53235
+ if (dc.source === "commander") continue;
53236
+ deckSize += dc.copies;
53237
+ if (isLandCard(dc.card)) landsHave += dc.copies;
53238
+ }
53239
+ const landInputs = landCountInputs(cards, lens);
53240
+ const report = manabaseReport(cards, identity2, lens);
53241
+ const consistency = computeManaConsistency(deckSize, landsHave);
53242
+ return {
53243
+ landsHave,
53244
+ landsRecommended: landInputs.spellCount > 0 ? recommendedLandCount(landInputs) : null,
53245
+ landInputs,
53246
+ colorsShort: report.colors.filter((r) => r.target > 0 && r.target - r.have >= COLOR_SHORT_THRESHOLD).map((r) => ({ color: r.color, shortBy: Math.round((r.target - r.have) * 100) / 100 })).sort((a, b) => b.shortBy - a.shortBy),
53247
+ screwPct: consistency ? consistency.screw * 100 : null,
53248
+ report,
53249
+ consistency
53250
+ };
53251
+ }
53252
+ var LAND_COUNT_TOLERANCE = 2;
53253
+ var COLOR_SHORT_THRESHOLD = LAND_COUNT_TOLERANCE;
53254
+ function shortLabel(color, shortBy) {
53255
+ return `${MANA_COLOR_LABEL[color]} short ${wholeShort(shortBy)}`;
53256
+ }
53257
+ function landInputsLabel(i) {
53258
+ return `avg MV ${i.avgMv.toFixed(1)}, ${i.cheapRampDraw} cheap ramp/draw`;
53259
+ }
53260
+ var COLOR_STATUS_LABEL = {
53261
+ over: "comfortably over",
53262
+ on: "on target",
53263
+ short: "short",
53264
+ none: "no demand yet"
53265
+ };
53266
+ var PIP_WORD = ["", "single", "double", "triple", "quadruple"];
53267
+ function demandSentence(row, lands) {
53268
+ const cname = MANA_COLOR_LABEL[row.color].toLowerCase();
53269
+ if (row.need === 0) {
53270
+ return `Nothing in the deck needs ${cname} yet. No target to hit.`;
53271
+ }
53272
+ const parts = [
53273
+ `${row.need} card${row.need === 1 ? "" : "s"} need${row.need === 1 ? "s" : ""} ${cname}`
53274
+ ];
53275
+ if (row.doubleNeed > 0) parts.push(`${row.doubleNeed} double`);
53276
+ if (row.tripleNeed > 0) parts.push(`${row.tripleNeed} triple`);
53277
+ const demand = parts.join(" \xB7 ");
53278
+ const p = Math.min(4, Math.max(1, row.driverPips));
53279
+ const driver = p === 1 ? `a single ${cname} pip` : `a ${PIP_WORD[p]}-${cname} card`;
53280
+ const basis = lands >= KARSTEN_LANDS_RANGE.min ? `with your ${lands} lands` : `for a ${KARSTEN_LANDS_RANGE.min}-land deck`;
53281
+ return `${demand} \u2192 Karsten wants ~${row.target} ${basis}, enough to cast ${driver} on turn ${row.driverMv}.`;
53282
+ }
53283
+ function balancedBasics(deckCards, identity2) {
53284
+ const current = /* @__PURE__ */ new Map();
53285
+ let total = 0;
53286
+ for (const dc of deckCards) {
53287
+ if (dc.source === "commander") continue;
53288
+ if (!isBasicLandType(dc.card.typeLine)) continue;
53289
+ const pm = dc.card.producedMana;
53290
+ if (!pm || pm.length !== 1) continue;
53291
+ const color = pm[0];
53292
+ if (!WUBRG_ORDER.includes(color)) continue;
53293
+ const prev = current.get(color);
53294
+ current.set(color, { oracleId: dc.card.oracleId, copies: (prev?.copies ?? 0) + dc.copies });
53295
+ total += dc.copies;
53296
+ }
53297
+ const spells = deckCards.filter((dc) => dc.source !== "commander" && !isBasicLandType(dc.card.typeLine)).map((dc) => dc.card);
53298
+ const target = total > 0 ? distributeBasics(sumDeckPips(spells), identity2, total) : { W: 0, U: 0, B: 0, R: 0, G: 0 };
53299
+ return { current, total, target, basicName: BASIC_NAME };
53300
+ }
53301
+
53302
+ // ../src/components/deckBuilderV2/fixingLands.ts
53303
+ init_slug();
53304
+ init_utils();
53305
+ var WUBRG2 = /* @__PURE__ */ new Set(["W", "U", "B", "R", "G"]);
53306
+ var PREMIUM_CYCLES = /* @__PURE__ */ new Set([
53307
+ "dual",
53308
+ "shockland",
53309
+ "painland",
53310
+ "checkland",
53311
+ "fastland",
53312
+ "battleland",
53313
+ "canopyland",
53314
+ "snarl",
53315
+ "pathway"
53316
+ ]);
53317
+ var TAPLAND_CYCLES = /* @__PURE__ */ new Set([
53318
+ "triome",
53319
+ "scryland",
53320
+ "gainland",
53321
+ "bounceland",
53322
+ "bikeland",
53323
+ "slowland",
53324
+ "storageland",
53325
+ "filterland"
53326
+ ]);
53327
+ var BASIC_DEPENDENT_TAP = /* @__PURE__ */ new Set([
53328
+ "controls_basic_type",
53329
+ "reveals_basic",
53330
+ "two_or_more_basics"
53331
+ ]);
53332
+ function coloredProduced(card) {
53333
+ return (card.producedMana ?? []).filter((c) => WUBRG2.has(c));
53334
+ }
53335
+ function isLandType(typeLine) {
53336
+ return (typeLine ?? "").toLowerCase().includes("land");
53337
+ }
53338
+ function indexCyclesByOracleId(cycles) {
53339
+ const m = /* @__PURE__ */ new Map();
53340
+ for (const c of cycles) {
53341
+ for (const member of c.members) {
53342
+ const s = m.get(member.oracleId);
53343
+ if (s) s.add(c.slug);
53344
+ else m.set(member.oracleId, /* @__PURE__ */ new Set([c.slug]));
53345
+ }
53346
+ }
53347
+ return m;
53348
+ }
53349
+ function cycleLabels(cycles) {
53350
+ const m = /* @__PURE__ */ new Map();
53351
+ for (const c of cycles) m.set(c.slug, c.displayName);
53352
+ return m;
53353
+ }
53354
+ function classifyTier(card, cycleSlugs, labels) {
53355
+ let premium = null;
53356
+ let tapland = null;
53357
+ if (cycleSlugs) {
53358
+ for (const slug of cycleSlugs) {
53359
+ if (PREMIUM_CYCLES.has(slug) && !premium) premium = slug;
53360
+ else if (TAPLAND_CYCLES.has(slug) && !tapland) tapland = slug;
53361
+ }
53362
+ }
53363
+ if (premium) return { tier: 0, cycleLabel: labels.get(premium) ?? null, cycleSlug: premium };
53364
+ if (coloredProduced(card).length === 5) return { tier: 1, cycleLabel: null, cycleSlug: null };
53365
+ if (tapland) return { tier: 2, cycleLabel: labels.get(tapland) ?? null, cycleSlug: tapland };
53366
+ return { tier: 3, cycleLabel: null, cycleSlug: null };
53367
+ }
53368
+ function fixingLandCandidates(input2) {
53369
+ const {
53370
+ shortColor,
53371
+ cards,
53372
+ identity: identity2,
53373
+ ownedOracleIds,
53374
+ inDeckOracleIds,
53375
+ cycles,
53376
+ priceOf,
53377
+ limit = 5
53378
+ } = input2;
53379
+ const allowed = new Set(identity2);
53380
+ if (allowed.size < 2) return [];
53381
+ const cyclesByOid = indexCyclesByOracleId(cycles);
53382
+ const labels = cycleLabels(cycles);
53383
+ const out = [];
53384
+ for (const card of cards.byOracleId.values()) {
53385
+ if (!isLandType(card.typeLine)) continue;
53386
+ if (isBasicLandType(card.typeLine)) continue;
53387
+ if (inDeckOracleIds.has(card.oracleId)) continue;
53388
+ const produced = coloredProduced(card);
53389
+ if (!produced.includes(shortColor) || produced.length < 2) continue;
53390
+ if (!withinColorIdentity(card.colors, allowed)) continue;
53391
+ const { tier, cycleLabel, cycleSlug } = classifyTier(
53392
+ card,
53393
+ cyclesByOid.get(card.oracleId),
53394
+ labels
53395
+ );
53396
+ out.push({
53397
+ card,
53398
+ owned: ownedOracleIds?.has(card.oracleId) ?? false,
53399
+ slug: toEdhrecSlug(card.name),
53400
+ committed: false,
53401
+ untapped: card.enterTapped === void 0,
53402
+ cycleLabel,
53403
+ cycleSlug,
53404
+ price: priceOf(card),
53405
+ tier
53406
+ });
53407
+ }
53408
+ out.sort(compareFixingCandidates);
53409
+ return out.slice(0, limit);
53410
+ }
53411
+ function compareFixingCandidates(a, b) {
53412
+ if (a.owned !== b.owned) return a.owned ? -1 : 1;
53413
+ if (a.tier !== b.tier) return a.tier - b.tier;
53414
+ if (a.untapped !== b.untapped) return a.untapped ? -1 : 1;
53415
+ const pa = a.price ?? Infinity;
53416
+ const pb = b.price ?? Infinity;
53417
+ if (pa !== pb) return pa - pb;
53418
+ const ra = a.card.edhrecRank ?? Infinity;
53419
+ const rb = b.card.edhrecRank ?? Infinity;
53420
+ if (ra !== rb) return ra - rb;
53421
+ return a.card.name.localeCompare(b.card.name);
53422
+ }
53423
+ function surplusByColor(report) {
53424
+ const m = /* @__PURE__ */ new Map();
53425
+ for (const row of report.colors) m.set(row.color, row.have - row.target);
53426
+ return m;
53427
+ }
53428
+ function deckNeedsBasics(deckCards, cycles) {
53429
+ const basicFetchOids = /* @__PURE__ */ new Set();
53430
+ for (const c of cycles) {
53431
+ if (c.slug === "basicfetch") for (const m of c.members) basicFetchOids.add(m.oracleId);
53432
+ }
53433
+ for (const { card } of deckCards) {
53434
+ if (card.tapCondition && BASIC_DEPENDENT_TAP.has(card.tapCondition)) return true;
53435
+ if (basicFetchOids.has(card.oracleId)) return true;
53436
+ }
53437
+ return false;
53438
+ }
53439
+ function pickBasicToCut(input2) {
53440
+ const { report, deckCards, cycles, shortColor } = input2;
53441
+ const backfillColors = input2.backfillColors ?? /* @__PURE__ */ new Set();
53442
+ const surplus = surplusByColor(report);
53443
+ const floor = Math.max(1, deckNeedsBasics(deckCards, cycles) ? 2 : 0);
53444
+ const colors = [...surplus.entries()].filter(
53445
+ ([color, s]) => color !== shortColor && (s >= 1 || backfillColors.has(color))
53446
+ ).sort((a, b) => b[1] - a[1]).map(([color]) => color);
53447
+ for (const color of colors) {
53448
+ for (const { card, copies } of deckCards) {
53449
+ if (!isBasicLandType(card.typeLine)) continue;
53450
+ if (!coloredProduced(card).includes(color)) continue;
53451
+ if (copies - 1 < floor) continue;
53452
+ return { card, color, copies };
53453
+ }
53454
+ }
53455
+ return null;
53456
+ }
53457
+ function sharedBackfillColors(candidates, shortColor) {
53458
+ if (candidates.length === 0) return /* @__PURE__ */ new Set();
53459
+ let shared = coloredProduced(candidates[0].card);
53460
+ for (let i = 1; i < candidates.length; i++) {
53461
+ const produced = new Set(coloredProduced(candidates[i].card));
53462
+ shared = shared.filter((x) => produced.has(x));
53463
+ }
53464
+ const out = /* @__PURE__ */ new Set();
53465
+ for (const x of shared) {
53466
+ if (x !== shortColor) out.add(x);
53467
+ }
53468
+ return out;
53469
+ }
53470
+ function uncountedFetchCount(deckCards, cycles) {
53471
+ const fetchOids = /* @__PURE__ */ new Set();
53472
+ for (const c of cycles) {
53473
+ if (c.slug === "fetchland") for (const m of c.members) fetchOids.add(m.oracleId);
53474
+ }
53475
+ let n = 0;
53476
+ for (const { card, copies } of deckCards) {
53477
+ if (fetchOids.has(card.oracleId) && (card.producedMana?.length ?? 0) === 0 && !card.fetches) {
53478
+ n += copies;
53479
+ }
53480
+ }
53481
+ return n;
53482
+ }
53483
+ function buildManabaseFixes(input2) {
53484
+ const {
53485
+ report,
53486
+ deckCards,
53487
+ cards,
53488
+ identity: identity2,
53489
+ ownedOracleIds,
53490
+ cycles,
53491
+ priceOf,
53492
+ perColor = 3
53493
+ } = input2;
53494
+ if (new Set(identity2).size < 2) return [];
53495
+ const inDeckOracleIds = /* @__PURE__ */ new Set();
53496
+ for (const { card } of deckCards) inDeckOracleIds.add(card.oracleId);
53497
+ const fixes = [];
53498
+ for (const row of report.colors) {
53499
+ if (row.status !== "short" || row.shortBy <= 0) continue;
53500
+ const candidates = fixingLandCandidates({
53501
+ shortColor: row.color,
53502
+ cards,
53503
+ identity: identity2,
53504
+ ownedOracleIds,
53505
+ inDeckOracleIds,
53506
+ cycles,
53507
+ priceOf,
53508
+ limit: perColor
53509
+ });
53510
+ if (candidates.length === 0) continue;
53511
+ const cut = pickBasicToCut({
53512
+ report,
53513
+ deckCards,
53514
+ cycles,
53515
+ shortColor: row.color,
53516
+ // A basic of a colour the offered duals also make is safe to cut — the dual
53517
+ // backfills it. This is what lets a both-colours-short deck swap instead of
53518
+ // being told to add a land.
53519
+ backfillColors: sharedBackfillColors(candidates, row.color)
53520
+ });
53521
+ fixes.push({ color: row.color, shortBy: row.shortBy, candidates, cut });
53522
+ }
53523
+ return fixes;
53524
+ }
53525
+
51769
53526
  // ../src/lib/edhrec/cardStats.ts
51770
53527
  var TRENDING_MIN = 3;
51771
53528
  function isTrending(trend) {
@@ -51777,12 +53534,12 @@ function formatLift(lift) {
51777
53534
 
51778
53535
  // ../src/lib/printingTrend.ts
51779
53536
  var SLOT2 = { "7d": 0, "30d": 2, "1d": 4 };
51780
- function printingTrendWindows(file3, set3, collectorNumber, foil, priceNow) {
53537
+ function printingTrendWindows(file4, set3, collectorNumber, foil, priceNow) {
51781
53538
  const out = {};
51782
- if (!file3 || !set3 || !collectorNumber) return out;
51783
- const slots = file3.s[set3.toLowerCase()]?.[collectorNumber];
53539
+ if (!file4 || !set3 || !collectorNumber) return out;
53540
+ const slots = file4.s[set3.toLowerCase()]?.[collectorNumber];
51784
53541
  for (const w of ["1d", "7d", "30d"]) {
51785
- const at = file3.trend[w];
53542
+ const at = file4.trend[w];
51786
53543
  if (!at) continue;
51787
53544
  const delta = slots?.[SLOT2[w] + (foil ? 1 : 0)] ?? 0;
51788
53545
  const then = priceNow != null ? priceNow - delta : void 0;
@@ -52079,10 +53836,494 @@ function primaryType(card) {
52079
53836
  const front = card.typeLine.split(" // ")[0] ?? card.typeLine;
52080
53837
  return TYPE_ORDER.find((t) => front.includes(t)) ?? "Other";
52081
53838
  }
52082
- function isLand2(card) {
53839
+ function isLand3(card) {
52083
53840
  return (card.typeLine.split(" // ")[0] ?? card.typeLine).includes("Land");
52084
53841
  }
52085
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
+
52086
54327
  // ../src/lib/deckPlan/handSim.ts
52087
54328
  function mulberry32(seed) {
52088
54329
  let a = seed >>> 0;
@@ -52094,7 +54335,7 @@ function mulberry32(seed) {
52094
54335
  return ((t ^ t >>> 14) >>> 0) / 4294967296;
52095
54336
  };
52096
54337
  }
52097
- function isLand3(card) {
54338
+ function isLand4(card) {
52098
54339
  return card.typeLine.toLowerCase().includes("land");
52099
54340
  }
52100
54341
  function frontFaceLower(typeLine) {
@@ -52103,46 +54344,6 @@ function frontFaceLower(typeLine) {
52103
54344
  function isCreatureType(card) {
52104
54345
  return frontFaceLower(card.typeLine).includes("creature");
52105
54346
  }
52106
- function materializeDeckFromPlan({
52107
- assignments,
52108
- purchases,
52109
- purchaseQuantities,
52110
- basicQuantities,
52111
- qtyForCard,
52112
- cardById,
52113
- cardBySlug,
52114
- excludeOracleIds
52115
- }) {
52116
- const out = [];
52117
- const fromAssign = /* @__PURE__ */ new Map();
52118
- for (const [oracleId] of assignments) {
52119
- if (excludeOracleIds?.has(oracleId)) continue;
52120
- const card = cardById(oracleId);
52121
- if (!card) continue;
52122
- const copies = qtyForCard(oracleId, card.typeLine, card.name);
52123
- for (let i = 0; i < copies; i++) out.push(card);
52124
- if (copies > 0) fromAssign.set(oracleId, copies);
52125
- }
52126
- for (const [slug] of purchases) {
52127
- const card = cardBySlug(slug);
52128
- if (!card || excludeOracleIds?.has(card.oracleId)) continue;
52129
- const copies = purchaseQuantities.get(slug) ?? 1;
52130
- for (let i = 0; i < copies; i++) out.push(card);
52131
- }
52132
- for (const [oracleId, qty] of basicQuantities) {
52133
- if (excludeOracleIds?.has(oracleId)) continue;
52134
- const already = fromAssign.get(oracleId) ?? 0;
52135
- if (already >= qty) continue;
52136
- const card = cardById(oracleId);
52137
- if (!card) continue;
52138
- for (let i = already; i < qty; i++) out.push(card);
52139
- }
52140
- return out;
52141
- }
52142
-
52143
- // src/plan.ts
52144
- init_manaOverrides();
52145
- init_oddsPlans();
52146
54347
 
52147
54348
  // ../src/lib/deckPlan/planFetch.ts
52148
54349
  function readFetch(fetches, text) {
@@ -52327,13 +54528,23 @@ function readUntapsAndReduces(text) {
52327
54528
  t.match(/\beach spell you cast that's ((?:[a-z]+ or )?[a-z]+ )costs \{(\d+)\} less/)
52328
54529
  );
52329
54530
  const tax = red ? null : t.match(/(?:^|\n)((?:[a-z]+ (?:spells )?(?:and|or) )?(?:[a-z]+ )?)?spells cost \{(\d+)\} more to cast\.(?:\n|$)/);
52330
- if (red || tax) {
52331
- const m = red ?? tax;
54531
+ const counted = !!red && t.startsWith(" to cast for each ", red.index + red[0].length);
54532
+ const colored = !red && !tax ? t.match(/(?:^|\n)spells of the chosen type you cast cost ((?:\{[wubrg]\})+) less to cast\. this effect reduces only the amount of colored mana you pay\./) : null;
54533
+ if (colored) {
54534
+ const pips = {};
54535
+ for (const x of colored[1].match(/\{([wubrg])\}/g)) {
54536
+ const k = x[1].toUpperCase();
54537
+ pips[k] = (pips[k] ?? 0) + 1;
54538
+ }
54539
+ out.reduces = { amount: 0, finds: /\bchoose a creature type\b/.test(t) ? "@subtype" : "@type", pips };
54540
+ }
54541
+ if (red && !counted || tax) {
54542
+ const m = red && !counted ? red : tax;
52332
54543
  const sign = red ? 1 : -1;
52333
54544
  const words = (m[1] ?? "").trim();
52334
54545
  const COLOR = { white: "w", blue: "u", black: "b", red: "r", green: "g" };
52335
54546
  const NOT_A_TYPE = /* @__PURE__ */ new Set(["the", "other", "each", "your", "all", "that", "of", "and", "or", "spells"]);
52336
- const one = (w) => w === "noncreature" ? "-t:creature" : COLOR[w] ? `c:${COLOR[w]}` : w && !NOT_A_TYPE.has(w) ? `t:${w}` : "";
54547
+ const one = (w) => w === "noncreature" ? "-t:creature" : w === "historic" ? "is:historic" : w === "colorless" ? "c:c" : w === "multicolored" ? "c:m" : COLOR[w] ? `c:${COLOR[w]}` : w && !NOT_A_TYPE.has(w) ? `t:${w}` : "";
52337
54548
  const parts = words.split(/ (?:and|or) /).map((part2) => part2.split(/\s+/).map(one).filter(Boolean).join(" ")).filter(Boolean);
52338
54549
  const finds = parts.length > 1 ? parts.join(" or ") : parts[0] ?? "";
52339
54550
  const chosen = / of the chosen type /.test(m[0]) ? /\bchoose a creature type\b/.test(t) || /\bcreature\b/.test(words) ? "@subtype" : "@type" : "";
@@ -52814,9 +55025,13 @@ function readDiesDraws(text) {
52814
55025
  var SAC_DRAW = /^whenever you sacrifice (?:a|an|one or more|another) (permanent|creature|artifact|treasure)s?, (?:put [^.]*? and )?(?:you )?draw (a|one|two) cards?\.$/;
52815
55026
  var GRANTS_CREATURE_MANA = /\bcreatures you control (?:have|gain) (?:[a-z]+ and )?"\{t\}: add (one mana of any color|\{[wubrgc]\})\.( spend this mana only to cast (?:a )?creature spells?\.)?"/;
52816
55027
  function readGrantsTapMana(text) {
55028
+ const all = text.match(/(?:^|\n)all ([a-z]+)s have "\{t\}: add (one mana of any color|\{[wubrgc]\})\."/);
55029
+ if (all) return { grantsTapMana: [all[2] === "one mana of any color" ? "WUBRG" : all[2][1].toUpperCase()], grantType: all[1] };
52817
55030
  const m = text.match(GRANTS_CREATURE_MANA);
52818
55031
  if (!m || /\buntil end of turn\b/.test(text.slice(m.index + m[0].length, m.index + m[0].length + 20))) return {};
52819
- return { grantsTapMana: [m[1] === "one mana of any color" ? "WUBRG" : m[1][1].toUpperCase()], ...m[2] ? { manaVaries: true } : {} };
55032
+ const kind = text.slice(0, m.index).match(/(?:^|[\n ])([a-z]+) $/)?.[1];
55033
+ const grantType = kind && !/^(?:other|nontoken|untapped|tapped|and|the|your|of|legendary|artifact|enchantment)$/.test(kind) ? kind : void 0;
55034
+ return { grantsTapMana: [m[1] === "one mana of any color" ? "WUBRG" : m[1][1].toUpperCase()], ...m[2] ? { manaVaries: true } : {}, ...grantType ? { grantType } : {} };
52820
55035
  }
52821
55036
  var LANDFALL_DRAW = /^(?:landfall — )?whenever a land you control enters, (?:you gain \d+ life and )?(?:you )?draw a card\.$/;
52822
55037
  function readTokenEngines(text) {
@@ -52846,6 +55061,46 @@ function readStartsInPlay(text) {
52846
55061
  const luck = !!m[2] && /if [^.\n]* has a luck counter on it, instead add one mana of any color/.test(text);
52847
55062
  return { onDrawOnly: !!m[1], exiles, ...luck ? { makes: ["WUBRG"] } : {} };
52848
55063
  }
55064
+ function readLandSearch(text) {
55065
+ const N = { a: 1, an: 1, one: 1, two: 2, three: 3, four: 4, five: 5 };
55066
+ const BASIC = { plains: "W", island: "U", swamp: "B", mountain: "R", forest: "G" };
55067
+ const TYPE = "(?:basic |snow |nonbasic )*(?:land|forest|plains|island|swamp|mountain|gate|desert|town|cave|sphere)s?(?: cards?)?";
55068
+ const WHAT = `(${TYPE}(?:(?:,? and\\/or |,? or |, )${TYPE})*)(?: cards?)?(?: with different names)?`;
55069
+ const re = new RegExp(`search your library for (up to )?(a|an|one|two|three|four|five) ${WHAT}(?:,| and)(?: reveal (?:it|them|those cards),)? (?:and )?put (?:it|them|that card|those cards|one) onto the battlefield( tapped)?(?: and the (?:other|rest) into your hand)?`);
55070
+ for (const raw of text.replace(/\([^)]*\)/g, "").split("\n")) {
55071
+ let l = raw.trim().replace(/^i(?:, [ivx]+)* — /, "").replace(/^• /, "");
55072
+ if (/^[ivx]+(?:, [ivx]+)* — /.test(l)) continue;
55073
+ l = l.replace(/^[a-z][a-z' ]* — /, "");
55074
+ if (/^(?:when|whenever|at the beginning|as long as|as the game begins)\b/.test(l)) {
55075
+ const t = l.match(/^(?:when(?:ever)? (?:this [a-z]+|~|[^,]+?) enters(?: or attacks)?|when you cast this spell), (?:you may )?/);
55076
+ if (!t || /\bequipped|enchanted|another|a creature\b/.test(t[0])) continue;
55077
+ l = l.slice(t[0].length);
55078
+ }
55079
+ let cost;
55080
+ const act = l.match(/^((?:\{[^}]+\}(?:, )?)+)(?:, \{t\})?(?:, sacrifice (?:this [a-z]+|~))?: (.*)$/);
55081
+ if (act) {
55082
+ const c = parseCost(act[1].replace(/\{t\}/g, "").replace(/, /g, ""));
55083
+ cost = { generic: c.generic, pips: c.pips };
55084
+ l = act[2];
55085
+ } else if (/^[^:]*\b(?:tap|sacrifice|exile|discard|pay) [^:]*: /.test(l)) continue;
55086
+ for (const [k, s] of l.split(/(?<=\.)\s+/).entries()) {
55087
+ if (/^(?:if|then if)\b|\binstead\b/.test(s) || /\bif\b[^,]*,\s*search/.test(s)) continue;
55088
+ if (/\b(?:target|an?) opponent|each opponent|target player\b/.test(s.split("search your library")[0])) continue;
55089
+ const m = s.match(re);
55090
+ if (!m) continue;
55091
+ const words = m[3];
55092
+ const typed = words.match(/forest|plains|island|swamp|mountain/g) ?? [];
55093
+ const anyLand = /\bland\b|gate|desert|town|cave|sphere/.test(words);
55094
+ const colors = anyLand ? void 0 : "WUBRG".split("").filter((c) => typed.some((w) => BASIC[w] === c)).join("") || void 0;
55095
+ const n = N[m[2]] ?? 1;
55096
+ const split = /\bput one onto the battlefield/.test(s) && /into your hand/.test(s);
55097
+ const prev = l.split(/(?<=\.)\s+/)[k - 1] ?? "";
55098
+ const sac = prev.match(/^sacrifice (a|an|one|two|three) lands?\.$/);
55099
+ return { ramp: { n: split ? 1 : n, tapped: !!m[4] || split && /onto the battlefield tapped/.test(s), ...colors ? { colors } : {} }, ...cost && (cost.generic || Object.keys(cost.pips).length) ? { cost } : {}, ...sac ? { sacLands: N[sac[1]] ?? 1 } : {}, ...split ? { toHand: n - 1 } : {} };
55100
+ }
55101
+ }
55102
+ return null;
55103
+ }
52849
55104
  function readSacOutlet(text) {
52850
55105
  const m = text.match(/(?:^|\n)(\{t\}, )?(?:pay \d+ life, )?sacrifice (?:a|another) (?:nontoken )?(?:creature|artifact or creature)(?: or artifact)?:/);
52851
55106
  return m ? { sacOutlet: m[1] ? "tap" : "free" } : {};
@@ -53234,6 +55489,22 @@ function withNonPlain(p0, text) {
53234
55489
  }
53235
55490
  }
53236
55491
  const restricted = mana.filter((m) => /^spend this mana only to /.test(m[3]));
55492
+ if (restricted.length && mana.length === 1 && p.makes.length === 1) {
55493
+ const syms = mana[0][2].match(/^add ((?:\{[wubrgc]\}){2,})\.$/);
55494
+ if (syms && /^\{t\}$/.test(mana[0][1].trim())) {
55495
+ const makes2 = syms[1].match(/\{[wubrgc]\}/g).map((x) => x[1].toUpperCase());
55496
+ const { manaVaries: _v, ...rest } = p;
55497
+ void _v;
55498
+ p = { ...rest, makes: makes2, produces: makes2.length };
55499
+ }
55500
+ } else if (!p.land && restricted.length && mana.every((m) => /^\{t\}$/.test(m[1].trim()))) {
55501
+ const plain2 = mana.filter(plainLine);
55502
+ const own2 = plain2.length === 1 ? plain2[0][2].match(/^add ((?:\{[wubrgc]\})+)\.$/) : null;
55503
+ if (own2 && plain2.length + restricted.length === mana.length) {
55504
+ const makes2 = own2[1].match(/\{[wubrgc]\}/g).map((x) => x[1].toUpperCase());
55505
+ if (makes2.length < p.makes.length) return { ...p, makes: makes2, produces: makes2.length, manaVaries: true };
55506
+ }
55507
+ }
53237
55508
  const code = restricted.map((m) => restrictionCode(m[3].replace(/^spend this mana only to (?:cast )?/, "").replace(/\..*$/, "").replace(/^(?:activate|pay|turn|foretell|unlock).*/, "zz"))).find((c) => c !== null) ?? null;
53238
55509
  if (!restricted.length || code === null) return p;
53239
55510
  const tag = (us) => us.map((u) => {
@@ -53286,7 +55557,8 @@ function readExtraMana2(text) {
53286
55557
  }
53287
55558
  const mult = !out.boost ? text.match(/(?:^|\n)if you tap an? (permanent|basic land|land) for mana, it produces (twice|three times) as much of that mana instead\./) : null;
53288
55559
  if (mult) out.boost = { per: mult[1] === "permanent" ? "permanent" : "land", adds: null, mult: mult[2] === "twice" ? 1 : 2 };
53289
- else if (!out.boost && /(?:^|\n)(?:whenever a land's ability causes you to add one or more mana of the chosen color, add an additional one mana of that color|whenever a basic land is tapped for mana of the chosen color, its controller adds an additional one mana of that color)\./.test(text)) out.boost = { per: "land", adds: null };
55560
+ else if (!out.boost && /(?:^|\n)whenever a land's ability causes you to add one or more mana of the chosen color, add an additional one mana of that color\./.test(text)) out.boost = { per: "land", adds: null, chosenColor: true };
55561
+ else if (!out.boost && /(?:^|\n)whenever a basic land is tapped for mana of the chosen color, its controller adds an additional one mana of that color\./.test(text)) out.boost = { per: "land", adds: null, chosenColor: true, basicOnly: true };
53290
55562
  else if (!out.boost && /(?:^|\n)whenever you tap a land for mana while you're the monarch, add an additional one mana of any color\./.test(text)) out.boost = { per: "land", adds: ["WUBRG"] };
53291
55563
  const landfall = text.match(/(?:^|\n)(?:landfall — )?whenever a land (?:you control )?enters(?: the battlefield)?(?: under your control)?, add ([^.\n]*)/);
53292
55564
  if (landfall) {
@@ -53596,6 +55868,13 @@ function readProfile(card, oracleText) {
53596
55868
  p0 = { ...p0, rampLands: { n: m[1] === "three" ? 3 : m[1] === "two" ? 2 : 1, tapped: !!m[3], ...colors !== "WUBRG" ? { colors } : {} } };
53597
55869
  break;
53598
55870
  }
55871
+ if (!p0.land && !p0.rampLands) {
55872
+ const r = readLandSearch(text);
55873
+ if (r) {
55874
+ p0 = { ...p0, rampLands: r.ramp, ...r.cost ? { rampCost: r.cost } : {}, ...r.toHand && !p0.landsToHand ? { landsToHand: r.toHand } : {} };
55875
+ if (r.sacLands && !p0.sacrifice) p0 = { ...p0, sacrifice: { count: r.sacLands, kinds: ["land"] } };
55876
+ }
55877
+ }
53599
55878
  if (!p0.land && !p0.landsToHand)
53600
55879
  for (const l of self2.split("\n")) {
53601
55880
  const s = l.trim().replace(/^• /, "");
@@ -53622,6 +55901,7 @@ function readProfile(card, oracleText) {
53622
55901
  void _v;
53623
55902
  p0 = { ...rest, makes: [], grantsTapMana: [urza[1].toUpperCase()], grantTo: "artifact" };
53624
55903
  }
55904
+ if (p0.grantType && p0.grantsTapMana && new RegExp(`\\b${p0.grantType}s?\\b`).test(type) && p0.makes.length === 1 && p0.makes[0] === p0.grantsTapMana[0]) p0 = { ...p0, makes: [] };
53625
55905
  if (!p0.land && (p0.draws ?? 0) > 0 && /(?:^|\n)• each player may discard their hand and draw five cards\./.test(text)) p0 = { ...p0, wheel: true };
53626
55906
  const discDraw = !p0.land ? text.match(/(?:^|\n)you may (?:discard a card|sacrifice an? [a-z]+ or discard a card|discard a card or sacrifice an? [a-z]+)\. if you do, draw (two|three) cards\./) : null;
53627
55907
  if (discDraw && !p0.draws) p0 = { ...p0, draws: discDraw[1] === "three" ? 3 : 2, discards: 1, discardFirst: true };
@@ -53655,6 +55935,10 @@ function readProfile(card, oracleText) {
53655
55935
  const sb = text.match(/(?:^|\n)(\{t\}, )?sacrifice (?:this [a-z]+|~): add ((?:\{[wubrgc]\})+|one mana of any color)\.(?:\n|$)/);
53656
55936
  if (sb) p0 = { ...p0, sacBurst: { units: unitsOf(sb[2]), tap: !!sb[1] } };
53657
55937
  }
55938
+ if (!p0.makes.length && !p0.ritualMakes.length && !p0.sacBurst) {
55939
+ const own3 = text.match(/(?:^|\n)sacrifice an? ([a-z]+): add ((?:\{[wubrgc]\})+)\.(?:\n|$)/);
55940
+ if (own3 && own3[1] !== "land" && new RegExp(`\\b${own3[1]}\\b`).test(type)) p0 = { ...p0, sacBurst: { units: unitsOf(own3[2]), tap: false } };
55941
+ }
53658
55942
  const pt = text.match(/(?:^|\n)((?:\{[0-9wubrgc]\})+, \{t\}|\{t\}|(?:\{[0-9wubrgc]\})+): (?:roll a d(\d+) and create a number of treasure tokens equal to the result|create (a|an|one|two|three) treasure tokens?)\.( [^.\n]* gains control of this [a-z]+\.)?(?:\n|$)/);
53659
55943
  if (pt) {
53660
55944
  const c = parseCost(pt[1].replace(/(?:, )?\{t\}/, ""));
@@ -54311,8 +56595,11 @@ function readExilesFirst(text) {
54311
56595
  return { count: count2, ...m[2].startsWith("reveal") ? { untilFound: true } : {} };
54312
56596
  }
54313
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 };
54314
56600
  function destination(text) {
54315
56601
  const line = text.split("\n").find((l) => /search your library/.test(l)) ?? "";
56602
+ if (TOP_DEPTH.test(line)) return "top";
54316
56603
  if (/\bon top\b/.test(line) && !/into your hand|onto the battlefield|into your graveyard/.test(line)) return "top";
54317
56604
  if (/into your hand/.test(text)) return "hand";
54318
56605
  if (/onto the battlefield/.test(text)) return "battlefield";
@@ -54342,8 +56629,19 @@ function readTutor(manaCost, oracleText) {
54342
56629
  const lines = text.split("\n");
54343
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)) ?? "";
54344
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];
54345
56637
  const out = {
54346
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" } : {},
54347
56645
  ...needsCreature ? { needs: "creature" } : {},
54348
56646
  // (Delirium: "if there are four or more card types among cards in your
54349
56647
  // graveyard, instead search your library for any card": Demonic Counsel.)
@@ -54400,6 +56698,7 @@ function readTutor(manaCost, oracleText) {
54400
56698
  .../\ban opponent gains control of (?:this|~|it)\b/.test(line) ? { gone: "opponent" } : {},
54401
56699
  ...((m) => m ? { discardCost: m[1] ?? "card" } : {})(head.match(/\bdiscard an? (?:(creature|land|artifact) )?card\b/)),
54402
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/)),
54403
56702
  ...((m) => m ? { sacrificeCost: m[1] } : {})(head.match(/\bsacrifice (?:an?|another) (creature|artifact|land)\b/)),
54404
56703
  ...limit ? { limit } : {},
54405
56704
  ...loyalty ? { loyalty: Number(loyalty[1]) } : {}
@@ -54416,6 +56715,8 @@ function readTutor(manaCost, oracleText) {
54416
56715
  const castM = trig?.match(/^whenever you cast an? (?:(white|blue|black|red|green) )?(creature|noncreature|artifact|enchantment|instant|sorcery|legendary|historic) spells?$/);
54417
56716
  const castOf = castM?.[2];
54418
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" };
54419
56720
  if (trig)
54420
56721
  return {
54421
56722
  ...withFinds,
@@ -54446,12 +56747,12 @@ function planEngineProfiles({
54446
56747
  // A commander that cuts costs: -1 - zone.
54447
56748
  ...(commanderReads ?? []).map((p, z2) => ({ r: -1 - z2, red: p.reduces }))
54448
56749
  ].filter(
54449
- (x) => !!x.red && x.red.amount !== 0
56750
+ (x) => !!x.red && (x.red.amount !== 0 || !!x.red.pips)
54450
56751
  );
54451
56752
  const triggers = castTriggerSources(manaProfiles, commanderReads, finder);
54452
56753
  const byToughness = manaProfiles.some((p) => p.paidDraw?.sacCreature);
54453
56754
  const byPower = [...manaProfiles, ...commanderReads ?? []].some((p) => p.enterDraw?.minPower);
54454
- const byType = [...manaProfiles, ...commanderReads ?? []].some((p) => p.diesDraw?.some((d) => d.type) || !!p.paidDig?.notType || !!p.tapTreasure?.type);
56755
+ const byType = [...manaProfiles, ...commanderReads ?? []].some((p) => p.diesDraw?.some((d) => d.type) || !!p.paidDig?.notType || !!p.tapTreasure?.type || !!p.grantType);
54455
56756
  const byLegend = [...manaProfiles, ...commanderReads ?? []].some((p) => p.manaIf?.kind === "legendary");
54456
56757
  const byShare = deck.some((c) => !!tutorBoardShare(c.oracleId)) || (commanderReads ?? []).some((p) => !!p.tutorShares);
54457
56758
  const byImprint = [...manaProfiles, ...commanderReads ?? []].some((p) => p.manaIf?.kind === "imprint" || p.manaIf?.kind === "permanentColors");
@@ -54465,7 +56766,7 @@ function planEngineProfiles({
54465
56766
  const ov = tutorOv[oid];
54466
56767
  const cutBy = p.land ? [] : reducers.filter(
54467
56768
  ({ r, red }) => r !== i && (!red.finds.trim() || finder(chosenFinds(red.finds, deck))(deck[i]))
54468
- ).map(({ r, red }) => ({ by: r, amount: red.amount }));
56769
+ ).map(({ r, red }) => ({ by: r, amount: red.amount, ...red.pips ? { pips: red.pips } : {} }));
54469
56770
  return {
54470
56771
  ...p,
54471
56772
  ...tutorFields(read, ov, deck[i]),
@@ -54514,6 +56815,10 @@ function tutorFields(read, ov, card) {
54514
56815
  ...read?.gone ? { tutorGone: read.gone } : {},
54515
56816
  ...read?.discardCost ? { tutorDiscard: read.discardCost } : {},
54516
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 } : {},
54517
56822
  ...read?.sacrificeCost ? { tutorSacrifice: read.sacrificeCost } : {},
54518
56823
  ...read?.trigger ? { tutorTrigger: read.trigger } : {},
54519
56824
  ...read?.castOf ? { tutorCastOf: read.castOf } : {},
@@ -54590,24 +56895,28 @@ function zoneEngineProfiles({
54590
56895
  const reducers = [
54591
56896
  ...manaProfiles.map((p, r) => ({ r, red: p.reduces })),
54592
56897
  ...commanderReads.map((p, z2) => ({ r: -1 - z2, red: p.reduces }))
54593
- ].filter((x) => !!x.red && x.red.amount !== 0);
56898
+ ].filter((x) => !!x.red && (x.red.amount !== 0 || !!x.red.pips));
54594
56899
  const triggers = castTriggerSources(manaProfiles, commanderReads, finder);
54595
56900
  const byToughness = manaProfiles.some((p) => p.paidDraw?.sacCreature);
54596
56901
  const byPower = [...manaProfiles, ...commanderReads].some((p) => p.enterDraw?.minPower);
54597
- const byType = [...manaProfiles, ...commanderReads].some((p) => p.diesDraw?.some((d) => d.type) || !!p.paidDig?.notType || !!p.tapTreasure?.type);
56902
+ const byType = [...manaProfiles, ...commanderReads].some((p) => p.diesDraw?.some((d) => d.type) || !!p.paidDig?.notType || !!p.tapTreasure?.type || !!p.grantType);
54598
56903
  const byLegend = [...manaProfiles, ...commanderReads].some((p) => p.manaIf?.kind === "legendary");
54599
56904
  const byShare = [...deck ?? [], ...zone].some((c) => !!tutorBoardShare(c.oracleId));
54600
56905
  const byRestricted = restrictedMana([...manaProfiles, ...commanderReads]);
54601
56906
  return commanderReads.map((p, z2) => {
54602
- const cutBy = reducers.filter(({ r, red }) => r !== -1 - z2 && (!red.finds.trim() || (!/@/.test(red.finds) || !!deck) && finder(chosenFinds(red.finds, deck ?? []))(zone[z2]))).map(({ r, red }) => ({ by: r, amount: red.amount }));
56907
+ const cutBy = reducers.filter(({ r, red }) => r !== -1 - z2 && (!red.finds.trim() || (!/@/.test(red.finds) || !!deck) && finder(chosenFinds(red.finds, deck ?? []))(zone[z2]))).map(({ r, red }) => ({ by: r, amount: red.amount, ...red.pips ? { pips: red.pips } : {} }));
54603
56908
  const triggeredBy = triggersOn(zone[z2], -1 - z2, triggers);
54604
56909
  const read = tutorReads?.get(zone[z2].oracleId);
54605
56910
  const ov = tutorOv?.[zone[z2].oracleId];
54606
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]) } : {} };
54607
56912
  });
54608
56913
  }
54609
- function classifiedTutors(otagIndex, cards, target) {
56914
+ function classifiedTutors(otagIndex, cards, target, reads) {
54610
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
+ };
54611
56920
  const cls = classifyDeckTutors(
54612
56921
  otagIndex,
54613
56922
  tutorTargetOf(card ?? target),
@@ -54620,7 +56929,11 @@ function classifiedTutors(otagIndex, cards, target) {
54620
56929
  );
54621
56930
  return /* @__PURE__ */ new Set([
54622
56931
  ...cls.counted.map((t) => t.oracleId),
54623
- ...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)
54624
56937
  ]);
54625
56938
  }
54626
56939
  function canTutorFind({
@@ -55055,6 +57368,15 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55055
57368
  const inHand = new Set(state.hand);
55056
57369
  const bottomed = state.order.slice(0, state.next).filter((i) => !inHand.has(i));
55057
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
+ };
55058
57380
  const grave = /* @__PURE__ */ new Set();
55059
57381
  let owedNext = [];
55060
57382
  let lost = false;
@@ -55122,6 +57444,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55122
57444
  }
55123
57445
  }
55124
57446
  if (pick2 < 0) return;
57447
+ shuffleLibrary("a land search");
55125
57448
  taken[pick2] = 1;
55126
57449
  hand.push(pick2);
55127
57450
  lg?.("searchLandToHand", { card: pick2 });
@@ -55230,6 +57553,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55230
57553
  return unit.replace(/^[WUBRGC]+/, colors);
55231
57554
  };
55232
57555
  const chosenColor = /* @__PURE__ */ new Map();
57556
+ const boostColor = /* @__PURE__ */ new Map();
55233
57557
  const deckColors = new Set([...profiles.flatMap((q) => Object.keys(q.pips)), ...opts.commanders.flatMap((c) => Object.keys(c.pips))].join("").replace(/[^WUBRG]/g, ""));
55234
57558
  const chooseColor = (can) => {
55235
57559
  const opts_ = [...can.replace(/[^WUBRG]/g, "")].filter((c) => deckColors.has(c));
@@ -55293,6 +57617,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55293
57617
  const charged = /* @__PURE__ */ new Set();
55294
57618
  const suspended = [];
55295
57619
  const cracked = /* @__PURE__ */ new Set();
57620
+ const rampLater = [];
55296
57621
  const rampUnits = [];
55297
57622
  const fixLands = () => {
55298
57623
  const all = fixesAll();
@@ -55349,6 +57674,16 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55349
57674
  }
55350
57675
  };
55351
57676
  const isOut = (by) => by < 0 ? !!zoneCast[-1 - by] : !!cast[by];
57677
+ const lessPips = (pips, by) => {
57678
+ if (!by?.some((x) => x.pips && isOut(x.by))) return pips;
57679
+ const out = { ...pips };
57680
+ for (const x of by) {
57681
+ if (!x.pips || !isOut(x.by)) continue;
57682
+ for (const [k, v] of Object.entries(x.pips)) if (out[k]) out[k] = Math.max(0, out[k] - v);
57683
+ }
57684
+ for (const k of Object.keys(out)) if (!out[k]) delete out[k];
57685
+ return out;
57686
+ };
55352
57687
  const cutOf = (by) => {
55353
57688
  if (!by) return 0;
55354
57689
  let n2 = 0;
@@ -55359,7 +57694,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55359
57694
  const costNow = (i, extra = 0) => {
55360
57695
  const q = profiles[i];
55361
57696
  const c = costParts(q, extra + xFor(i) + (q.scaling ? (kicked.get(i) ?? 0) * q.scaling.generic : 0));
55362
- return { generic: Math.max(0, c.generic - cut(i)), pips: c.pips };
57697
+ return { generic: Math.max(0, c.generic - cut(i)), pips: lessPips(c.pips, q.cutBy) };
55363
57698
  };
55364
57699
  const xFor = (i) => profiles[i].xCounters && rowNeeds(i) ? profiles[i].xSymbols ?? 1 : 0;
55365
57700
  const xPaid = /* @__PURE__ */ new Map();
@@ -55460,7 +57795,6 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55460
57795
  }
55461
57796
  };
55462
57797
  const resolveEffects = (i, refund, q) => {
55463
- for (let e = q.extraLandsNow ?? 0; e > 0 && playExtraLand(); e--) ;
55464
57798
  if (q.freeCast && !q.freeCast.each) for (let n2 = 0; n2 < q.freeCast.count && castFree(q.freeCast, i); n2++) ;
55465
57799
  if (q.treasures) lg?.("treasure", { made: q.treasures, why: "when it resolves or enters" });
55466
57800
  makeTreasure(q.treasures ?? 0);
@@ -55494,11 +57828,15 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55494
57828
  toPool(...g.map((x) => x.unit));
55495
57829
  }
55496
57830
  }
55497
- if (q.rampLands) {
57831
+ if (q.rampLands && q.rampCost && !pay(q.rampCost.generic, q.rampCost.pips, false)) {
57832
+ rampLater.push(i);
57833
+ lg?.("rampLater", { card: i, cost: { ...q.rampCost }, note: "its land search costs mana it doesn't have now: on a later main phase" });
57834
+ } else if (q.rampLands) {
55498
57835
  rampLandsOut += q.rampLands.n;
55499
57836
  const u = Array.from({ length: q.rampLands.n }, () => q.rampLands.colors ?? "WUBRG");
55500
57837
  rampUnits.push(...u);
55501
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");
55502
57840
  if (q.rampLands.tapped && !landsUntapped()) pending.push(...u);
55503
57841
  else {
55504
57842
  online.push(...u);
@@ -55512,6 +57850,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
55512
57850
  else discard(q.discards, !!q.discardsLand, false, !!q.discardRandom);
55513
57851
  }
55514
57852
  if (!noDraw) drawWith(q);
57853
+ for (let e = q.extraLandsNow ?? 0; e > 0 && playExtraLand(); e--) ;
55515
57854
  if (q.selects) dig(q.selects.look, q.selects.keep, !!q.selects.top);
55516
57855
  if (q.discards && !q.discardFirst && searching !== i) discard(q.discards, !!q.discardsLand, false, !!q.discardRandom);
55517
57856
  if (refund && q.untaps && !q.ritualMakes.length) {
@@ -56311,6 +58650,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
56311
58650
  return colors;
56312
58651
  };
56313
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;
56314
58654
  const kind = (t < 0 ? opts.commanders[-1 - t].profile : profiles[t])?.tutorShares;
56315
58655
  if (!kind) return true;
56316
58656
  const out = legendColorsOut(kind);
@@ -56471,7 +58811,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
56471
58811
  const q = c.profile;
56472
58812
  const off = cutOf(q?.cutBy);
56473
58813
  const tax = 2 * (zoneCasts[z2] ?? 0);
56474
- const options = [{ generic: Math.max(0, c.generic + tax - off), pips: c.pips, alt: null }];
58814
+ const options = [{ generic: Math.max(0, c.generic + tax - off), pips: lessPips(c.pips, q?.cutBy), alt: null }];
56475
58815
  for (const a of q?.alts ?? []) {
56476
58816
  if (!holds(a)) continue;
56477
58817
  const k = parseCost(a.cost);
@@ -56523,7 +58863,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
56523
58863
  };
56524
58864
  const zoneMakesMana = (z2) => {
56525
58865
  const q = opts.commanders[z2].profile;
56526
- return !!q && (q.makes.length > 0 || !!q.boost || !!q.landfall?.length || (q.reduces?.amount ?? 0) > 0 || tableTreasure(q) || !!q.combatTreasures || !!q.tapTreasure);
58866
+ return !!q && (q.makes.length > 0 || !!q.boost || !!q.landfall?.length || (q.reduces?.amount ?? 0) > 0 || !!q.reduces?.pips || tableTreasure(q) || !!q.combatTreasures || !!q.tapTreasure);
56527
58867
  };
56528
58868
  const zoneSearches = (z2) => opts.useTutors && reqs.some((r, k) => !!r.zoneTutors?.[z2] && wanted(k));
56529
58869
  const zoneDraws = (z2) => {
@@ -56856,7 +59196,30 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
56856
59196
  if (!live(k) || !r.tutors?.[t] || r.members[t] || !usableFor(k, t, false)) continue;
56857
59197
  const target = pickTarget(k, t);
56858
59198
  if (target < 0) continue;
56859
- 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]);
56860
59223
  deliver(k, t, target);
56861
59224
  tutorTurn.set(t, turn);
56862
59225
  usedTutor = true;
@@ -56976,11 +59339,28 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
56976
59339
  }
56977
59340
  }
56978
59341
  const to = tq.tutorTo ?? "hand";
59342
+ shuffleLibrary("a tutor's search");
56979
59343
  const put = (i) => {
56980
59344
  taken[i] = 1;
56981
- lg?.("found", { tutor: t, row: k, card: i, to, wasBottomed: bottomed.includes(i) });
56982
- if (to === "battlefield") castCard(i, true);
56983
- 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);
56984
59364
  else if (to === "graveyard") grave.add(i);
56985
59365
  else hand.push(i);
56986
59366
  };
@@ -57122,6 +59502,8 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57122
59502
  if (sk && victim < 0) continue;
57123
59503
  const tc5 = profiles[t].tutorTreasures ?? 0;
57124
59504
  if (tc5 && pool.filter((u) => u === TREASURE).length < tc5) continue;
59505
+ const clues = profiles[t].tutorClues ?? 0;
59506
+ if (clues && clueCount < clues) continue;
57125
59507
  const out = !!cast[t];
57126
59508
  if (!out) feed(t, rituals);
57127
59509
  if (!out && (tapSick(t) || profiles[t].tutorChapter)) {
@@ -57188,6 +59570,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57188
59570
  grave.add(pitch);
57189
59571
  }
57190
59572
  if (victim >= 0) sacrifice([victim]);
59573
+ if (clues) clueCount -= clues;
57191
59574
  for (let k2 = 0; k2 < tc5; k2++) {
57192
59575
  const at = pool.indexOf(TREASURE);
57193
59576
  if (at >= 0) pool.splice(at, 1);
@@ -57445,26 +59828,29 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57445
59828
  }
57446
59829
  };
57447
59830
  const granted = () => {
57448
- let adds;
59831
+ const creatureGrants = [];
57449
59832
  let artAdds;
57450
59833
  const take = (q) => {
57451
59834
  if (!q?.grantsTapMana?.length) return;
57452
59835
  if (q.grantTo === "artifact") artAdds ??= q.grantsTapMana[0];
57453
- else adds ??= q.grantsTapMana[0];
59836
+ else creatureGrants.push({ unit: q.grantsTapMana[0], ...q.grantType ? { type: q.grantType } : {} });
57454
59837
  };
57455
59838
  for (let j = 0; j < deckSize; j++) if (cast[j]) take(profiles[j]);
57456
59839
  for (let z2 = 0; z2 < zoneCast.length; z2++) if (zoneCast[z2]) take(opts.commanders[z2].profile);
57457
- if (!adds && !artAdds) return [];
59840
+ if (!creatureGrants.length && !artAdds) return [];
59841
+ const grantFor = (types) => creatureGrants.find((g) => !g.type || !!types?.includes(g.type))?.unit;
57458
59842
  const out = [];
57459
59843
  for (let j = 0; j < deckSize; j++) {
57460
59844
  const q = profiles[j];
57461
59845
  if (!cast[j] || q.land || srcOut.get(j)?.length) continue;
57462
59846
  if (condOut.includes(j) && condUnit(j)) continue;
57463
- if (adds && q.creature && !(entered[j] === turn && !hasteOf(q, true))) out.push({ who: j, unit: adds });
59847
+ const adds = q.creature ? grantFor(q.types) : void 0;
59848
+ if (adds && !(entered[j] === turn && !hasteOf(q, true))) out.push({ who: j, unit: adds });
57464
59849
  else if (artAdds && q.artifact) out.push({ who: j, unit: artAdds });
57465
59850
  }
57466
59851
  for (let z2 = 0; z2 < zoneCast.length; z2++) {
57467
59852
  const c = opts.commanders[z2];
59853
+ const adds = grantFor(c.profile?.types);
57468
59854
  if (!adds || !zoneCast[z2] || c.creature === false || c.profile?.makes.length || zoneEntered[z2] === turn && !zoneHaste(z2)) continue;
57469
59855
  out.push({ who: -1 - z2, unit: adds });
57470
59856
  }
@@ -57478,11 +59864,17 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57478
59864
  };
57479
59865
  const boostUnits = () => {
57480
59866
  const by = [];
57481
- for (let j = 0; j < deckSize; j++) if (cast[j] && profiles[j].boost) by.push(profiles[j].boost);
57482
- for (let z2 = 0; z2 < zoneCast.length; z2++) if (zoneCast[z2] && opts.commanders[z2].profile?.boost) by.push(opts.commanders[z2].profile.boost);
59867
+ const who = [];
59868
+ for (let j = 0; j < deckSize; j++) if (cast[j] && profiles[j].boost) by.push(profiles[j].boost), who.push(j);
59869
+ for (let z2 = 0; z2 < zoneCast.length; z2++) if (zoneCast[z2] && opts.commanders[z2].profile?.boost) by.push(opts.commanders[z2].profile.boost), who.push(-1 - z2);
57483
59870
  if (!by.length) return [];
57484
59871
  const out = [];
57485
- for (const b of by) {
59872
+ for (const [n2, b] of by.entries()) {
59873
+ let chosen = "";
59874
+ if (b.chosenColor) {
59875
+ chosen = boostColor.get(who[n2]) ?? chooseColor("WUBRG");
59876
+ boostColor.set(who[n2], chosen);
59877
+ }
57486
59878
  const sources = b.per === "land" ? [...landOut] : b.per === "permanent" ? [...landOut, ...srcOut] : [...srcOut];
57487
59879
  for (const [j, units] of sources) {
57488
59880
  if (!units.length) continue;
@@ -57490,6 +59882,10 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57490
59882
  if (b.per === "creature" ? !q.creature : b.per === "artifact" ? !q.artifact : false) continue;
57491
59883
  if (b.landType && !(q.basicTypes ?? []).includes(b.landType)) continue;
57492
59884
  if (b.basicOnly && !q.basicLand) continue;
59885
+ if (chosen) {
59886
+ for (const u of units) if (u.includes(chosen) || u.includes("*")) out.push(chosen);
59887
+ continue;
59888
+ }
57493
59889
  if (b.per !== "land" && b.per !== "permanent" && q.enchantLand) continue;
57494
59890
  if (b.mult) for (let k = 0; k < b.mult; k++) out.push(...units);
57495
59891
  else out.push(...b.adds ?? [units[0]]);
@@ -57524,6 +59920,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57524
59920
  landsPlayed++;
57525
59921
  if (profiles[j].fetch) fetchedGrave++;
57526
59922
  const units = landUnitsNow(j);
59923
+ if (profiles[j].fetch && !profiles[j].tapsFirst) shuffleLibrary("a fetch land");
57527
59924
  const creatureLand = !!profiles[j].creature;
57528
59925
  if (creatureLand) entered[j] = turn;
57529
59926
  const tapped = tappedIfPlayed(j) || creatureLand;
@@ -57833,6 +60230,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57833
60230
  for (const u of left) spent.splice(spent.indexOf(u), 1);
57834
60231
  cycledFor = spent;
57835
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");
57836
60234
  break;
57837
60235
  }
57838
60236
  }
@@ -57862,6 +60260,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57862
60260
  for (const u of left) spent.splice(spent.indexOf(u), 1);
57863
60261
  cycledFor = spent;
57864
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");
57865
60264
  break;
57866
60265
  }
57867
60266
  mark?.("main 1");
@@ -57883,6 +60282,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57883
60282
  landsPlayed++;
57884
60283
  if (profiles[pick2].fetch) fetchedGrave++;
57885
60284
  const units = landUnitsNow(pick2);
60285
+ if (profiles[pick2].fetch && !profiles[pick2].tapsFirst) shuffleLibrary("a fetch land");
57886
60286
  const creatureLand = !!profiles[pick2].creature;
57887
60287
  if (creatureLand) entered[pick2] = turn;
57888
60288
  const tapped = tappedIfPlayed(pick2) || creatureLand;
@@ -57965,6 +60365,21 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
57965
60365
  }
57966
60366
  condPaid.clear();
57967
60367
  condCheck();
60368
+ for (const j of [...rampLater]) {
60369
+ const q = profiles[j];
60370
+ if (!cast[j] || !q.rampLands || !q.rampCost || !pay(q.rampCost.generic, q.rampCost.pips, false)) continue;
60371
+ rampLater.splice(rampLater.indexOf(j), 1);
60372
+ rampLandsOut += q.rampLands.n;
60373
+ const u = Array.from({ length: q.rampLands.n }, () => q.rampLands.colors ?? "WUBRG");
60374
+ rampUnits.push(...u);
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");
60377
+ if (q.rampLands.tapped && !landsUntapped()) pending.push(...u);
60378
+ else {
60379
+ online.push(...u);
60380
+ toPool(...u);
60381
+ }
60382
+ }
57968
60383
  for (const j of [...manaLocked]) {
57969
60384
  if (!cast[j]) {
57970
60385
  manaLocked.delete(j);
@@ -58048,7 +60463,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
58048
60463
  (i) => !profiles[i].land && !profiles[i].target && // (A sunburst source waits for the colors it could have: not
58049
60464
  // Pentad Prism off Sol Ring's {C}{C} when your lands make two.)
58050
60465
  !sunburstWaits(i) && manaIfSoon(i) && (profiles[i].makes.length > 0 || // A boost or landfall (Leyline of Abundance, Lotus Cobra) is mana while it's out.
58051
- !!profiles[i].boost || !!profiles[i].landfall?.length || (profiles[i].reduces?.amount ?? 0) > 0 || tableTreasure(profiles[i]) || (profiles[i].treasures ?? 0) > sizeOf(costNow(i)) || // Mana for every creature of yours (Cryptolith Rite), with one
60466
+ !!profiles[i].boost || !!profiles[i].landfall?.length || (profiles[i].reduces?.amount ?? 0) > 0 || !!profiles[i].reduces?.pips || tableTreasure(profiles[i]) || (profiles[i].treasures ?? 0) > sizeOf(costNow(i)) || // Mana for every creature of yours (Cryptolith Rite), with one
58052
60467
  // out or in hand; and with one out, a cheap creature is a dork
58053
60468
  // (2 mana or less: a 6-drop isn't ramp for one mana a turn).
58054
60469
  !!profiles[i].grantsTapMana?.length && (hasCreatureOut() || hand.some((h) => h !== i && !!profiles[h].creature && !profiles[h].land)) || !!profiles[i].creature && sizeOf(costNow(i)) <= 2 && grantOut() || // (With Urza out, a cheap artifact taps for {U}.)
@@ -58604,6 +61019,7 @@ function playGame(state, reqs, profiles, opts, prep = preparePlay(reqs, profiles
58604
61019
  removeUnits(landUnits, units);
58605
61020
  cracked.add(j);
58606
61021
  fetchedGrave++;
61022
+ shuffleLibrary("a fetch land");
58607
61023
  landOut.set(j, found);
58608
61024
  landUnits.push(...found);
58609
61025
  pending.push(...found);
@@ -58707,7 +61123,7 @@ function canonicalDeck(cards) {
58707
61123
  }
58708
61124
  function planContext(a) {
58709
61125
  const { deck, commanders, cards, oracle, otagIndex, overrides, tutorOv } = a;
58710
- const landFlags = deck.map((c) => isLand3(c));
61126
+ const landFlags = deck.map((c) => isLand4(c));
58711
61127
  const autoProfiles = oracle ? withLifeDraws(deck, withFetchColors(deck.map((c) => manaProfile(c, oracle(c.oracleId))))) : null;
58712
61128
  const tutorReads = new Map(oracle ? deck.map((c) => [c.oracleId, readTutor(c.manaCost, oracle(c.oracleId))]) : []);
58713
61129
  const zoneTutorReads = new Map(
@@ -58752,7 +61168,7 @@ function planContext(a) {
58752
61168
  if (!otagIndex) return /* @__PURE__ */ new Set();
58753
61169
  let hit = tutorCache.get(target.oracleId);
58754
61170
  if (!hit) {
58755
- hit = classifiedTutors(otagIndex, cards, target);
61171
+ hit = classifiedTutors(otagIndex, cards, target, tutorReads);
58756
61172
  tutorCache.set(target.oracleId, hit);
58757
61173
  }
58758
61174
  return hit;
@@ -58762,7 +61178,7 @@ function planContext(a) {
58762
61178
  if (!otagIndex) return /* @__PURE__ */ new Set();
58763
61179
  let hit = zoneTutorCache.get(target.oracleId);
58764
61180
  if (!hit) {
58765
- 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]));
58766
61182
  zoneTutorCache.set(target.oracleId, hit);
58767
61183
  }
58768
61184
  return hit;
@@ -58965,15 +61381,6 @@ function resolvePlanRow(row, rc) {
58965
61381
  // src/plan.ts
58966
61382
  init_countRows();
58967
61383
 
58968
- // ../src/lib/deckPlan/speedConsistency.ts
58969
- var DEFAULT_OPENING_HAND = 7;
58970
- function cardsSeenByTurn(turn, openingHand = DEFAULT_OPENING_HAND, onDraw = false) {
58971
- return openingHand + Math.max(0, turn - 1) + (onDraw ? 1 : 0);
58972
- }
58973
-
58974
- // ../src/lib/deckPlan/oddsQuestions.ts
58975
- var OPENING_HAND = 7;
58976
-
58977
61384
  // ../src/lib/deckPlan/planOdds.ts
58978
61385
  var DEEP_SIM = { turns: 5, trials: 5e3 };
58979
61386
  function planSeed(deckSize, reqs, opts = {}) {
@@ -59005,15 +61412,15 @@ function shuffleSeed(seed, game, look) {
59005
61412
  function deepLands(hand, order, reqs, profiles, base, prep, turns) {
59006
61413
  const forced = /* @__PURE__ */ new Map();
59007
61414
  const horizon = Math.min(8, Math.max(turns + 1, ...reqs.map((r) => r.byTurn)));
59008
- 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);
59009
61416
  for (let t = 1; t <= turns; t++) {
59010
61417
  let cands = [];
59011
61418
  let def = -1;
59012
- 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) });
59013
61420
  if (def < 0 || cands.length < 2) continue;
59014
61421
  const score = (c) => {
59015
61422
  let s = 0;
59016
- const g = run(horizon, new Map([...forced, [t, c]]), {
61423
+ const g = run2(horizon, new Map([...forced, [t, c]]), {
59017
61424
  peek: (turn, online, want) => {
59018
61425
  if (turn === horizon) s += 10 * pipsCovered(online, want) + online.length;
59019
61426
  }
@@ -59430,10 +61837,10 @@ function simulatePlan(deckSize, planReqs, opts = {}) {
59430
61837
  }
59431
61838
  function cumulative(counts, to, trials) {
59432
61839
  const out = [];
59433
- let run = 0;
61840
+ let run2 = 0;
59434
61841
  for (let t = 1; t <= to; t++) {
59435
- run += counts[t] ?? 0;
59436
- out.push(run / trials);
61842
+ run2 += counts[t] ?? 0;
61843
+ out.push(run2 / trials);
59437
61844
  }
59438
61845
  return out;
59439
61846
  }
@@ -60355,7 +62762,7 @@ function planZoneCard(c) {
60355
62762
  return { name: c.name.split(" // ")[0], cost: c.cmc, manaCost: c.manaCost, oracleId: c.oracleId, card: c };
60356
62763
  }
60357
62764
  var PLAN_GROUPS = [
60358
- { id: "land", label: "Lands", match: (c) => isLand3(c) },
62765
+ { id: "land", label: "Lands", match: (c) => isLand4(c) },
60359
62766
  { id: "creature", label: "Creatures", match: (c) => isCreatureType(c) },
60360
62767
  { id: "dork", label: "Mana creatures", match: (c) => isCreatureType(c) && c.roles.includes("ramp") },
60361
62768
  { id: "ramp", label: "Ramp", match: (c) => c.roles.includes("ramp") },
@@ -60490,20 +62897,8 @@ function planModel(deckId, stored, catalog, lib, given) {
60490
62897
  return card ? [card] : [];
60491
62898
  });
60492
62899
  const zoneIds = new Set(zone.map((c) => c.oracleId));
60493
- const basics = stored.basicQuantities ?? /* @__PURE__ */ new Map();
60494
- const deck = canonicalDeck(
60495
- materializeDeckFromPlan({
60496
- assignments: stored.assignments ?? /* @__PURE__ */ new Map(),
60497
- purchases: stored.purchases ?? /* @__PURE__ */ new Map(),
60498
- purchaseQuantities: stored.purchaseQuantities ?? /* @__PURE__ */ new Map(),
60499
- basicQuantities: basics,
60500
- // (selectQtyForCard: an assigned card counts its stored copies, default 1.)
60501
- qtyForCard: (oid) => basics.get(oid) ?? 1,
60502
- cardById: (oid) => catalog.index.byOracleId.get(oid),
60503
- cardBySlug: (slug) => catalog.bySlug.get(slug),
60504
- excludeOracleIds: zoneIds
60505
- })
60506
- );
62900
+ const library = deckLibrary(stored, catalog.index, zoneIds);
62901
+ const deck = canonicalDeck(library.cards);
60507
62902
  if (deck.length === 0) throw new PlanProblem("This deck has no cards to draw yet.");
60508
62903
  const commanders = zone.map(planZoneCard);
60509
62904
  const pool = /* @__PURE__ */ new Map();
@@ -60536,6 +62931,7 @@ function planModel(deckId, stored, catalog, lib, given) {
60536
62931
  const built = buildPlanInput(ctx, resolved, settings);
60537
62932
  return {
60538
62933
  deck,
62934
+ notInGames: libraryGapNote(library.gaps),
60539
62935
  rows,
60540
62936
  settings,
60541
62937
  from: given?.rows?.length ? "given rows" : saved ? "saved plan" : "default rows",
@@ -60657,7 +63053,7 @@ function runPlan(m, opts = {}) {
60657
63053
  const o = opts.deep ? { ...m.input.opts, deep: { turns: DEEP_SIM.turns }, trials: DEEP_SIM.trials } : m.input.opts;
60658
63054
  return simulatePlan(m.input.deckSize, m.input.reqs, o);
60659
63055
  }
60660
- var pct = (p) => `${Math.round(p * 1e3) / 10}%`;
63056
+ var pct = levelPct;
60661
63057
  function assumptionList(list, cap2 = MAX_ASSUMED) {
60662
63058
  const byKind = /* @__PURE__ */ new Map();
60663
63059
  for (const a of list) byKind.set(a.kind, [...byKind.get(a.kind) ?? [], a.name]);
@@ -60683,13 +63079,14 @@ function planAnswer(m, r, withCurve) {
60683
63079
  return {
60684
63080
  plan: m.from,
60685
63081
  ...m.whatIf.length ? { whatIf: { label: "what-if, not saved", reads: m.whatIf } } : {},
60686
- 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) } : {} },
60687
63083
  rows,
60688
63084
  ...bottleneck ? { mostOftenTheOnlyMiss: m.labels.get(bottleneck.key) } : {},
60689
63085
  onlyThanksToTutors: pct(r.viaTutor),
60690
63086
  averageMulligans: Math.round(r.avgMulligans * 100) / 100,
60691
63087
  game: {
60692
63088
  deckSize: m.deck.length,
63089
+ ...m.notInGames ? { notInGames: m.notInGames } : {},
60693
63090
  onTheDraw: m.settings.onDraw,
60694
63091
  mulligans: m.settings.mulligans,
60695
63092
  keepLands: `${m.settings.keepLands[0]} to ${m.settings.keepLands[1]}`,
@@ -60728,11 +63125,12 @@ async function tryCatalog(ctx) {
60728
63125
  return null;
60729
63126
  }
60730
63127
  }
63128
+ var isUnread = (e) => e instanceof LibraryError && (e.kind === "not-connected" || e.kind === "no-scope");
60731
63129
  async function tryLibrary(ctx) {
60732
63130
  try {
60733
63131
  return await ctx.library.library();
60734
63132
  } catch (e) {
60735
- if (e instanceof LibraryError && e.kind === "not-connected") return null;
63133
+ if (isUnread(e)) return null;
60736
63134
  throw e;
60737
63135
  }
60738
63136
  }
@@ -60812,7 +63210,7 @@ async function collectionMatch(ctx, catalog, refresh) {
60812
63210
  try {
60813
63211
  stacks = await ctx.library.collection(refresh);
60814
63212
  } catch (e) {
60815
- if (e instanceof LibraryError && e.kind === "not-connected") return emptyMatchResult();
63213
+ if (isUnread(e)) return emptyMatchResult();
60816
63214
  throw e;
60817
63215
  }
60818
63216
  const out = emptyMatchResult();
@@ -60865,7 +63263,7 @@ var pastedNote = (src) => src.pasted ? {
60865
63263
  function curveOf(lines) {
60866
63264
  const curve = {};
60867
63265
  for (const l of lines) {
60868
- if (isLand2(l.card)) continue;
63266
+ if (isLand3(l.card)) continue;
60869
63267
  const key = l.card.cmc >= 7 ? "7+" : String(l.card.cmc);
60870
63268
  curve[key] = (curve[key] ?? 0) + l.qty;
60871
63269
  }
@@ -60880,7 +63278,7 @@ function matchesOnly(l, only, stored) {
60880
63278
  const o = only.toLowerCase();
60881
63279
  if (o === "buy" || o === "considering" || o === "sideboard") return l.board === o;
60882
63280
  if (l.board !== "main" && l.board !== "buy") return false;
60883
- if (o === "lands") return isLand2(l.card);
63281
+ if (o === "lands") return isLand3(l.card);
60884
63282
  if (l.card.typeLine.toLowerCase().includes(o)) return true;
60885
63283
  const cats = stored.v2Categories;
60886
63284
  const id = cats?.categories.find((c) => c.name.toLowerCase() === o)?.id;
@@ -60937,9 +63335,27 @@ var getDeck = {
60937
63335
  const src = await deckFrom(args, ctx, catalog);
60938
63336
  const { id, raw } = src;
60939
63337
  const combos = catalog ? await tryCombos(ctx) : null;
60940
- const stored = asDeck(raw);
63338
+ const detail = detailOf(args);
63339
+ let canNotes = !src.pasted && await ctx.library.has("notes");
63340
+ let notes = null;
63341
+ if (canNotes) {
63342
+ try {
63343
+ notes = await ctx.library.notesOf(id, args.refresh === true);
63344
+ } catch (e) {
63345
+ if (!(e instanceof LibraryError && e.kind === "no-scope")) throw e;
63346
+ canNotes = false;
63347
+ }
63348
+ }
63349
+ const stored = asDeck(notes ? { ...raw, ...notes } : raw);
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
+ }) : [];
60941
63355
  return json2({
60942
- ...deckAnswer(viewDeck(id, stored, catalog, combos?.index), stored, detailOf(args), typeof args.only === "string" ? args.only : void 0),
63356
+ ...deckAnswer(viewDeck(id, stored, catalog, combos?.index), stored, detail, typeof args.only === "string" ? args.only : void 0),
63357
+ ...noNotes ? { notesLeftOut: noScopeMessage("notes") } : {},
63358
+ ...pending.length ? { pendingChanges: pending } : {},
60943
63359
  ...pastedNote(src),
60944
63360
  ...catalog ? comboNotes(combos) : {},
60945
63361
  ...catalog ? staleNote(catalog) : { note: "Card data isn't available, so card names and legality are missing." }
@@ -61162,7 +63578,7 @@ var readInput = external_exports.object({
61162
63578
  });
61163
63579
  var planOdds = {
61164
63580
  name: "plan_odds",
61165
- 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).",
61166
63582
  input: {
61167
63583
  ...deckOrList,
61168
63584
  rows: external_exports.array(rowInput).max(8).optional().describe("Rows to ask about instead of the deck's saved plan."),
@@ -61198,14 +63614,18 @@ var planOdds = {
61198
63614
  const reads = Array.isArray(args.reads) ? args.reads : [];
61199
63615
  const m = planModel(id, asDeck(raw), catalog, lib, { ...given, reads });
61200
63616
  const deep = args.deep === true;
61201
- 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);
61202
63620
  const yours = reads.length ? runPlan(planModel(id, asDeck(raw), catalog, lib, given), { deep }) : null;
61203
63621
  return json2({
61204
63622
  deck: viewDeck(id, asDeck(raw), null).name,
61205
63623
  ...pastedNote(src),
61206
63624
  ...answer,
61207
63625
  ...deep ? { deepSim: "the deep sim: early land drops chosen by playing ahead, 5,000 games" } : {},
61208
- ...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) } } : {},
61209
63629
  ...staleNote(catalog)
61210
63630
  });
61211
63631
  }
@@ -61220,10 +63640,10 @@ function changes(windows) {
61220
63640
  }
61221
63641
  return out;
61222
63642
  }
61223
- function printingChanges(file3, set3, number4, usd, foil) {
63643
+ function printingChanges(file4, set3, number4, usd, foil) {
61224
63644
  const out = {};
61225
63645
  for (const [isFoil, now] of [[false, usd], [true, foil]]) {
61226
- const w = printingTrendWindows(file3, set3, number4, isFoil, now ?? void 0);
63646
+ const w = printingTrendWindows(file4, set3, number4, isFoil, now ?? void 0);
61227
63647
  for (const k of TREND_WINDOWS) {
61228
63648
  const d = w[k]?.delta;
61229
63649
  if (d) out[`${k}${isFoil ? "Foil" : ""}`] = cents(d);
@@ -61326,7 +63746,7 @@ var cardTool = {
61326
63746
  yours = (await ownership(ctx, catalog, args.refresh === true)).row(c.oracleId, detail === "summary" ? "standard" : detail);
61327
63747
  } catch (e) {
61328
63748
  if (!(e instanceof LibraryError)) throw e;
61329
- if (e.kind !== "not-connected") missing.push(`what you own (${e.message})`);
63749
+ if (!isUnread(e)) missing.push(`what you own (${e.message})`);
61330
63750
  }
61331
63751
  const stale = [...catalog.stale ? ["the card catalog"] : [], ...x?.stale() ?? []];
61332
63752
  return json2({
@@ -61488,7 +63908,7 @@ var commanderTool = {
61488
63908
  owned = new Map([...own2.owned].map(([oid, r]) => [oid, r.stacks.reduce((n, s) => n + s.quantity, 0)]));
61489
63909
  } catch (e) {
61490
63910
  if (!(e instanceof LibraryError)) throw e;
61491
- if (e.kind !== "not-connected") missing.push(`what you own (${e.message})`);
63911
+ if (!isUnread(e)) missing.push(`what you own (${e.message})`);
61492
63912
  }
61493
63913
  }
61494
63914
  const ownedOf = (name) => {
@@ -61838,7 +64258,7 @@ var ownedIdsOf = async (ctx, catalog, refresh) => {
61838
64258
  const own2 = await ownership(ctx, catalog, refresh);
61839
64259
  return { ids: new Set(own2.owned.keys()), connected: true };
61840
64260
  } catch (e) {
61841
- if (e instanceof LibraryError && e.kind === "not-connected") return { ids: /* @__PURE__ */ new Set(), connected: false };
64261
+ if (isUnread(e)) return { ids: /* @__PURE__ */ new Set(), connected: false };
61842
64262
  throw e;
61843
64263
  }
61844
64264
  };
@@ -62069,7 +64489,483 @@ var comboSearch = {
62069
64489
  });
62070
64490
  }
62071
64491
  };
62072
- var TOOLS = [listDecks, getDeck, collectionLookup, cardSearch, cardTool, tutorTool, swapsTool, commanderTool, deckCombos2, comboSearch, collectionCombos, statsTool, budgetTool, pullListTool, planOdds];
64492
+ var slugIndexes = /* @__PURE__ */ new WeakMap();
64493
+ var slugIndexOf = (catalog) => {
64494
+ let s = slugIndexes.get(catalog.index);
64495
+ if (!s) slugIndexes.set(catalog.index, s = buildSlugCardIndex(catalog.index));
64496
+ return s;
64497
+ };
64498
+ var deckMapOf = (stored, catalog) => deckCardMapFromStored(
64499
+ {
64500
+ ...stored,
64501
+ assignments: stored.assignments ?? /* @__PURE__ */ new Map(),
64502
+ purchases: stored.purchases ?? /* @__PURE__ */ new Map(),
64503
+ basicQuantities: stored.basicQuantities ?? /* @__PURE__ */ new Map()
64504
+ },
64505
+ catalog.index,
64506
+ slugIndexOf(catalog)
64507
+ );
64508
+ var ownedOrNull = async (ctx, catalog, refresh) => {
64509
+ const o = await ownedIdsOf(ctx, catalog, refresh);
64510
+ return o.connected ? o.ids : null;
64511
+ };
64512
+ var compareTool = {
64513
+ name: "deck_compare",
64514
+ description: "Two decks side by side, as the deck builder's Compare shows them: the cards only in the first, only in the second, and in both (with each side's copies), over the 99 (commanders apart). And what the second deck's extra cards would cost to buy, minus the ones the user owns. Either deck can be saved, a pasted list, or a public Moxfield / Archidekt link.",
64515
+ input: {
64516
+ ...deckOrList,
64517
+ with: external_exports.string().optional().describe("The other deck: a saved deck's name or id."),
64518
+ withList: external_exports.string().optional().describe("Or the other deck as a pasted list or a public Moxfield / Archidekt link."),
64519
+ withCommander: external_exports.string().optional().describe("With withList: its commander, when the list doesn't mark one."),
64520
+ detail: detailInput,
64521
+ refresh: refreshInput
64522
+ },
64523
+ async run(args, ctx) {
64524
+ const catalog = await ctx.catalog();
64525
+ const mine = await deckFrom(args, ctx, catalog);
64526
+ if (!(typeof args.with === "string" && args.with.trim()) && !(typeof args.withList === "string" && args.withList.trim())) {
64527
+ throw new ToolProblem("Compare with which deck? Give with (a saved deck) or withList (a pasted list or link).");
64528
+ }
64529
+ const theirs = await deckFrom({ deck: args.with, list: args.withList, commander: args.withCommander, refresh: args.refresh }, ctx, catalog);
64530
+ const a = asDeck(mine.raw);
64531
+ const b = asDeck(theirs.raw);
64532
+ const diff = compareDecks(deckMapOf(a, catalog), deckMapOf(b, catalog));
64533
+ const owned = await ownedOrNull(ctx, catalog, args.refresh === true);
64534
+ const buy = buyDifference(diff.onlyTheirs, owned ?? /* @__PURE__ */ new Set());
64535
+ const detail = detailOf(args);
64536
+ const cap2 = { summary: 40, standard: 120, full: Infinity }[detail];
64537
+ const only = (xs) => xs.slice(0, cap2).map((x) => x.qty > 1 ? `${x.qty} ${x.card.name}` : x.card.name);
64538
+ const changed = diff.shared.filter(isQtyDelta);
64539
+ const nameOf = (s) => viewDeck(s.id, asDeck(s.raw), null).name;
64540
+ const cmdr = (s) => viewDeck(s.id, asDeck(s.raw), catalog, null).commanders;
64541
+ return json2({
64542
+ first: { deck: nameOf(mine), commanders: cmdr(mine), ...pastedNote(mine) },
64543
+ second: { deck: nameOf(theirs), commanders: cmdr(theirs), ...pastedNote(theirs) },
64544
+ counts: { onlyFirst: diff.onlyMine.length, onlySecond: diff.onlyTheirs.length, inBoth: diff.shared.length, inBothDifferentCopies: changed.length },
64545
+ onlyFirst: only(diff.onlyMine),
64546
+ onlySecond: only(diff.onlyTheirs),
64547
+ ...changed.length ? { differentCopies: changed.slice(0, cap2).map((s) => `${s.card.name}: ${s.mineQty} \u2192 ${s.theirsQty}`) } : {},
64548
+ ...detail !== "summary" ? { inBoth: diff.shared.slice(0, cap2).map((s) => s.card.name) } : {},
64549
+ ...diff.onlyMine.length > cap2 || diff.onlyTheirs.length > cap2 ? { more: "Ask with detail: full for every card." } : {},
64550
+ toAddTheSecondsCards: {
64551
+ cards: buy.differ,
64552
+ ...owned ? { youOwn: buy.own } : {},
64553
+ toBuy: owned ? buy.buyCount : buy.differ,
64554
+ usd: Math.round(buy.buyUsd * 100) / 100,
64555
+ ...owned ? {} : { note: "Without the collection (no access code, or one that can't read it), it counts every card as a buy." }
64556
+ },
64557
+ credit: SCRYFALL_CREDIT
64558
+ });
64559
+ }
64560
+ };
64561
+ var OVERLAP_SORTS = ["in", "name", "sticker", "price"];
64562
+ var overlapTool = {
64563
+ name: "deck_overlap",
64564
+ description: "Cards shared across the user's decks, as /overlap shows them: each card, how many of the chosen decks run it, which, and the copies each needs. With the sticker-share readout: decks you don't play at the same time can share one physical copy, so it says how many copies sharing saves and their value, and with the collection which shared cards the user owns. Basics are left out unless asked. Needs an access code.",
64565
+ input: {
64566
+ decks: external_exports.array(external_exports.string()).max(60).optional().describe("Which decks, by name or id (at least 2). Default: every deck."),
64567
+ minDecks: external_exports.number().int().min(2).max(60).optional().describe("Only cards in at least this many of them (default 2)."),
64568
+ includeBasics: external_exports.boolean().optional().describe("Also list basic lands (never counted in the savings)."),
64569
+ inDeck: external_exports.string().optional().describe("Only the shared cards in this one deck."),
64570
+ sort: external_exports.enum(OVERLAP_SORTS).optional().describe("in (default: most-shared first), name, sticker (owned first), or price."),
64571
+ detail: detailInput,
64572
+ refresh: refreshInput
64573
+ },
64574
+ async run(args, ctx) {
64575
+ const catalog = await ctx.catalog();
64576
+ const all = await ctx.library.decks(args.refresh === true);
64577
+ const chosen = Array.isArray(args.decks) && args.decks.length ? args.decks.map((d) => findDeck(d, all)) : [...all];
64578
+ const unique = [...new Map(chosen).entries()];
64579
+ if (unique.length < 2) throw new ToolProblem("Overlap needs at least 2 decks.");
64580
+ const names = unique.map(([id, raw]) => viewDeck(id, asDeck(raw), null).name);
64581
+ const tally = crossDeckOverlap(unique.map(([, raw]) => deckMapOf(asDeck(raw), catalog)));
64582
+ const owned = await ownedOrNull(ctx, catalog, args.refresh === true);
64583
+ const minDecks = typeof args.minDecks === "number" ? args.minDecks : MIN_SHARED_DECKS;
64584
+ let rows = filterOverlap(tally, { minDecks, includeBasics: args.includeBasics === true });
64585
+ if (typeof args.inDeck === "string" && args.inDeck.trim()) {
64586
+ const [id] = findDeck(args.inDeck, new Map(unique));
64587
+ const at = unique.findIndex(([x]) => x === id);
64588
+ rows = rows.filter((e) => e.deckIndices.includes(at));
64589
+ }
64590
+ const key = OVERLAP_SORTS.includes(args.sort) ? args.sort : "in";
64591
+ if (args.sort) rows = sortOverlapRows(rows, key, DEFAULT_DIR[key], owned);
64592
+ const summary = summarizeStickerShare(filterOverlap(tally, { minDecks, includeBasics: false }), owned);
64593
+ const cap2 = { summary: 40, standard: 150, full: 1e3 }[detailOf(args)];
64594
+ return json2({
64595
+ decks: names.length,
64596
+ ...names.length <= 12 ? { deckNames: names } : {},
64597
+ shared: {
64598
+ cards: summary.sharedCards,
64599
+ copiesSaved: summary.savedCopies,
64600
+ usdSaved: Math.round(summary.savedUsd * 100) / 100,
64601
+ ...summary.ownedCount !== null ? { youOwn: summary.ownedCount, toBuy: summary.toBuyCount } : {}
64602
+ },
64603
+ rows: rows.slice(0, cap2).map((e) => {
64604
+ const s = stickerReadout(e, owned);
64605
+ return {
64606
+ name: e.card.name,
64607
+ inDecks: e.inCount,
64608
+ decks: e.deckIndices.map((i) => names[i]),
64609
+ ...s.copiesIfSeparate !== e.inCount ? { copiesPerDeck: e.qtyPerDeck } : {},
64610
+ ...s.saved > 0 ? { sharingSaves: s.saved } : {},
64611
+ ...s.ownership ? { youHaveIt: s.ownership === "own" } : {},
64612
+ ...e.card.priceUsd != null ? { priceUsd: e.card.priceUsd } : {}
64613
+ };
64614
+ }),
64615
+ ...rows.length > cap2 ? { more: rows.length - cap2 } : {},
64616
+ about: "Sharing: decks you don't play at the same time can share one physical copy, moved between them. copiesSaved is the copies a one-per-deck approach needs minus the copies sharing needs; usdSaved prices them today (unpriced cards count 0).",
64617
+ credit: SCRYFALL_CREDIT
64618
+ });
64619
+ }
64620
+ };
64621
+ var manabaseTool = {
64622
+ name: "deck_manabase",
64623
+ description: "A deck's mana base, as the deck builder's Manabase shows it: lands run vs Karsten's recommended count (and what it's based on), the opening-hand odds (screw, keepable, flood), and per color the sources the deck runs vs Frank Karsten's target for what its spells demand, with the card that sets each target. For a short color, the fixing lands that would help (owned first, then by cycle, untapped, price) and the basic to cut to keep the land count. And what balancing the basics to the colored pips would change. A shortfall is a finding, not an error. Either a saved deck, a pasted list, or a public Moxfield / Archidekt link.",
64624
+ input: {
64625
+ ...deckOrList,
64626
+ refresh: refreshInput
64627
+ },
64628
+ async run(args, ctx) {
64629
+ const catalog = await ctx.catalog();
64630
+ const src = await deckFrom(args, ctx, catalog);
64631
+ const v = viewDeck(src.id, asDeck(src.raw), catalog, null);
64632
+ const missing = [];
64633
+ const tags = catalog.otags();
64634
+ if (!tags) missing.push("Scryfall tags (rocks and dorks fall back to any mana-making permanent)");
64635
+ const lens = tags ? makeCardTagLens(tags) : null;
64636
+ const deckCards = [
64637
+ ...v.commanderCards.map((card) => ({ card, copies: 1, source: "commander" })),
64638
+ ...v.lines.filter((l) => l.board === "main" || l.board === "buy").map((l) => ({ card: l.card, copies: l.qty }))
64639
+ ];
64640
+ const identity2 = MANA_COLOR_ORDER.filter((c) => v.commanderCards.some((x) => x.colors.includes(c)));
64641
+ const s = manabaseSummary(deckCards, identity2, lens);
64642
+ const cycles = await part(missing, "land cycles (no fixing-land suggestions)", ctx.extras?.landCycles);
64643
+ const owned = await ownedIdsOf(ctx, catalog, args.refresh === true);
64644
+ const fixes = new Map(
64645
+ (cycles ? buildManabaseFixes({
64646
+ report: s.report,
64647
+ deckCards,
64648
+ cards: catalog.index,
64649
+ identity: identity2,
64650
+ ownedOracleIds: owned.connected ? owned.ids : null,
64651
+ cycles,
64652
+ priceOf: (c) => c.priceUsd ?? void 0
64653
+ }) : []).map((f) => [f.color, f])
64654
+ );
64655
+ const fetches = cycles ? uncountedFetchCount(deckCards, cycles) : 0;
64656
+ const bal = balancedBasics(deckCards, identity2);
64657
+ const balance = MANA_COLOR_ORDER.flatMap((c) => {
64658
+ const have = bal.current.get(c)?.copies ?? 0;
64659
+ const want = bal.target[c] ?? 0;
64660
+ return have === want ? [] : [`${bal.basicName[c]}: ${have} \u2192 ${want}`];
64661
+ });
64662
+ const pct3 = (x) => Math.round(x * 100);
64663
+ return json2({
64664
+ deck: v.name,
64665
+ ...pastedNote(src),
64666
+ commander: v.commanders,
64667
+ lands: {
64668
+ have: s.landsHave,
64669
+ ...s.landsRecommended !== null ? { recommended: s.landsRecommended, basedOn: landInputsLabel(s.landInputs), ...Math.abs(s.landsHave - s.landsRecommended) >= LAND_COUNT_TOLERANCE ? { off: true } : {} } : {}
64670
+ },
64671
+ ...s.consistency ? {
64672
+ openingHand: {
64673
+ screwPct: pct3(s.consistency.screw),
64674
+ keepablePct: pct3(s.consistency.sweet),
64675
+ floodPct: pct3(s.consistency.flood),
64676
+ about: `Chance the opening 7 has 0-1 / 2-4 / 5+ lands (${s.consistency.landCount} of ${s.consistency.deckSize}). Exact math, no mulligan: the London mulligan only improves these.`
64677
+ }
64678
+ } : {},
64679
+ ...s.report.colorless ? { colorless: "Nothing in the deck needs or makes colored mana." } : {},
64680
+ colors: s.report.colors.map((r) => {
64681
+ const f = fixes.get(r.color);
64682
+ return {
64683
+ color: MANA_COLOR_LABEL[r.color],
64684
+ sources: r.have,
64685
+ ...r.target > 0 ? { target: r.target } : {},
64686
+ status: r.status === "short" ? `short ${formatShortfall(r.target, r.have)}` : COLOR_STATUS_LABEL[r.status],
64687
+ why: demandSentence(r, s.report.lands),
64688
+ ...f ? {
64689
+ fix: {
64690
+ move: f.cut ? `Swap a ${f.cut.card.name} for one of these (keeps the land count).` : "Add one of these (no basic to spare, so this raises the land count).",
64691
+ lands: f.candidates.map((c) => ({
64692
+ name: c.card.name,
64693
+ ...c.owned ? { youOwn: true } : {},
64694
+ ...c.cycleLabel ? { cycle: c.cycleLabel } : {},
64695
+ untapped: c.untapped,
64696
+ ...c.price != null ? { priceUsd: c.price } : {}
64697
+ })),
64698
+ ...fetches > 0 ? { note: `The deck runs ${fetches} fetch land${fetches === 1 ? "" : "s"} not counted above, so the real access is higher: treat this shortfall as a ceiling.` } : {}
64699
+ }
64700
+ } : {}
64701
+ };
64702
+ }),
64703
+ ...s.colorsShort.length ? { short: s.colorsShort.map((c) => shortLabel(c.color, c.shortBy)) } : {},
64704
+ ...bal.total > 0 ? { balanceBasics: balance.length ? balance : "The basics already match the color demand." } : {},
64705
+ about: "Sources: lands count 1; rocks and dorks count part of a source by the turn the spell needs them, as Karsten counts them. Targets are Frank Karsten's for the deck's land count. Short means 2 or more under target.",
64706
+ ...missing.length ? { missing } : {},
64707
+ credit: SCRYFALL_CREDIT
64708
+ });
64709
+ }
64710
+ };
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];
62073
64969
 
62074
64970
  // src/server.ts
62075
64971
  async function serve(version2, ctx) {
@@ -62080,7 +64976,7 @@ async function serve(version2, ctx) {
62080
64976
  {
62081
64977
  description: tool.description,
62082
64978
  inputSchema: tool.input,
62083
- annotations: { readOnlyHint: true, openWorldHint: false }
64979
+ annotations: tool.write ? { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false } : { readOnlyHint: true, openWorldHint: false }
62084
64980
  },
62085
64981
  async (args) => {
62086
64982
  const r = await runTool(tool, args, ctx);
@@ -62099,7 +64995,7 @@ var say = (m) => process.stderr.write(`${m}
62099
64995
  var transport = {
62100
64996
  fetchImpl: ((url2, init) => fetch(`${ORIGIN}${url2}`, {
62101
64997
  ...init,
62102
- headers: { ...Object.fromEntries(new Headers(init?.headers)), "user-agent": `edhvault-mcp/${"0.2.11"}` }
64998
+ headers: { ...Object.fromEntries(new Headers(init?.headers)), "user-agent": `edhvault-mcp/${"0.2.17"}` }
62103
64999
  }))
62104
65000
  };
62105
65001
  async function store(dir) {
@@ -62115,7 +65011,7 @@ async function secretFromEnv() {
62115
65011
  async function main() {
62116
65012
  const args = process.argv.slice(2);
62117
65013
  if (args.includes("--version")) {
62118
- say("0.2.11");
65014
+ say("0.2.17");
62119
65015
  return;
62120
65016
  }
62121
65017
  const dir = configDir();
@@ -62137,7 +65033,7 @@ async function main() {
62137
65033
  return;
62138
65034
  }
62139
65035
  const extras = extrasLoader({ dir, origin: ORIGIN });
62140
- await serve("0.2.11", {
65036
+ await serve("0.2.17", {
62141
65037
  library: new Library({ secret: await secretFromEnv() ?? loadSecret(secrets), dir, transport }),
62142
65038
  catalog: catalogLoader({ dir, origin: ORIGIN, prices: extras.prices }),
62143
65039
  combos: comboLoader({ dir, origin: ORIGIN }),