dsh-codex-subscription 3.2.27 → 3.2.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -2973,6 +2973,22 @@ function safeStreamHealth(value) {
2973
2973
  }
2974
2974
  //#endregion
2975
2975
  //#region src/pi-ai-runtime.js
2976
+ function withUserPreferences(payload, preferences) {
2977
+ if (!preferences) return payload;
2978
+ const note = "User response preferences (apply as defaults when compatible with the current request, workspace instructions, and host policies):\n" + preferences;
2979
+ const first = payload.input?.[0];
2980
+ if (payload.instructions === void 0 && ["developer", "system"].includes(first?.role) && typeof first.content === "string") return {
2981
+ ...payload,
2982
+ input: [{
2983
+ ...first,
2984
+ content: first.content + "\n\n" + note
2985
+ }, ...payload.input.slice(1)]
2986
+ };
2987
+ return {
2988
+ ...payload,
2989
+ instructions: [payload.instructions, note].filter(Boolean).join("\n\n")
2990
+ };
2991
+ }
2976
2992
  const FAST_SERVICE_TIER = "priority";
2977
2993
  const ULTRAFAST_SERVICE_TIER = "ultrafast";
2978
2994
  /** Apply the chosen detail to user and tool-result images after the provider assembles the request. */
@@ -3074,8 +3090,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3074
3090
  ...serviceTier === void 0 ? {} : { serviceTier },
3075
3091
  async onPayload(payload, requestModel) {
3076
3092
  const preferred = {
3077
- ...payload,
3078
- ...instructions ? { instructions: [payload.instructions, "User response preferences (apply as defaults when compatible with the current request, workspace instructions, and host policies):\n" + instructions].filter(Boolean).join("\n\n") } : {},
3093
+ ...withUserPreferences(payload, instructions),
3079
3094
  ...textVerbosity === void 0 ? {} : { text: {
3080
3095
  ...payload.text ?? {},
3081
3096
  verbosity: textVerbosity
@@ -3420,7 +3435,15 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3420
3435
  context,
3421
3436
  options
3422
3437
  };
3423
- const create = () => route === void 0 ? networkIterable((prepared) => provider[method](model, context, prepared), withPreferences(model, options, instructions), reviewRequest, source) : networkIterable((prepared) => provider[method](model, context, prepared), withReview(route, options), true, source);
3438
+ const subscriptionModel = {
3439
+ ...model,
3440
+ compat: {
3441
+ ...model.compat,
3442
+ supportsMaxOutputTokens: false,
3443
+ supportsMidConvoEffort: false
3444
+ }
3445
+ };
3446
+ const create = () => route === void 0 ? networkIterable((prepared) => provider[method](subscriptionModel, context, prepared), withPreferences(model, options, instructions), reviewRequest, source) : networkIterable((prepared) => provider[method](subscriptionModel, context, prepared), withReview(route, options), true, source);
3424
3447
  return reviewRequest ? reviewIterable(create) : create();
3425
3448
  };
3426
3449
  return Object.freeze({
@@ -3453,7 +3476,8 @@ Object.freeze([
3453
3476
  "1.4.0",
3454
3477
  "1.5.0",
3455
3478
  "1.5.1",
3456
- "1.5.2"
3479
+ "1.5.2",
3480
+ "1.6.0"
3457
3481
  ]);
3458
3482
  //#endregion
3459
3483
  //#region src/reasoning-json.js
@@ -5095,7 +5119,7 @@ function inheritedOriginalImageRef(session, assetId) {
5095
5119
  }
5096
5120
  //#endregion
5097
5121
  //#region src/version.js
5098
- const PACKAGE_VERSION = "3.2.27";
5122
+ const PACKAGE_VERSION = "3.2.29";
5099
5123
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
5100
5124
  //#endregion
5101
5125
  //#region node_modules/@deepseek-ai/dsh-home-paths/lib/index.js
@@ -5525,7 +5549,7 @@ async function readSessionImage(attachmentId, attachments, signal, messages) {
5525
5549
  const id = normalizeAttachmentId(attachmentId);
5526
5550
  if (id === void 0) invalidAttachmentId({ attachmentId });
5527
5551
  const selected = sessionImageReferences(messages).get(id);
5528
- if (selected === void 0) throw new Error("The selected image attachment cannot be found in the current session. Copy attachmentId from the image block of the user message; never pass a path or filename.");
5552
+ if (selected === void 0) throw new Error("The selected image attachment cannot be found in the current session. Copy attachmentId from an image block or image tool result in this session; never pass a path or filename.");
5529
5553
  const stored = await attachments.readImage(referenceOf(selected, attachments), signal);
5530
5554
  return {
5531
5555
  data: stored.data,
@@ -5533,10 +5557,55 @@ async function readSessionImage(attachmentId, attachments, signal, messages) {
5533
5557
  name: stored.ref.name
5534
5558
  };
5535
5559
  }
5560
+ function readPathKey(path) {
5561
+ if (typeof path !== "string") return void 0;
5562
+ return /^[A-Za-z]:[\\/]/.test(path) ? path[0].toLowerCase() + path.slice(1).replaceAll("\\", "/") : path;
5563
+ }
5564
+ function localReadReferences(messages) {
5565
+ const calls = /* @__PURE__ */ new Map();
5566
+ const paths = /* @__PURE__ */ new Map();
5567
+ const aliases = /* @__PURE__ */ new Map();
5568
+ for (const message of messages ?? []) {
5569
+ if (!Array.isArray(message.content)) continue;
5570
+ if (message.role === "assistant") for (const block of message.content) {
5571
+ if (block.type !== "tool-call" || block.name !== "read_image" || typeof block.id !== "string") continue;
5572
+ let args = block.arguments;
5573
+ if (typeof args === "string") try {
5574
+ args = JSON.parse(args);
5575
+ } catch {
5576
+ continue;
5577
+ }
5578
+ if (typeof args?.file_path !== "string") continue;
5579
+ const key = readPathKey(args.file_path);
5580
+ const read = { key: aliases.get(key) ?? key };
5581
+ paths.set(read.key, read);
5582
+ calls.set(block.id, read);
5583
+ }
5584
+ else if (message.role === "tool" && !message.isError) {
5585
+ const read = calls.get(message.toolCallId);
5586
+ const image = message.content.find((block) => block.type === "image" && block.attachment);
5587
+ if (read && image && paths.get(read.key) === read) {
5588
+ read.image = image.attachment;
5589
+ const header = message.content.find((block) => block.type === "text" && block.text?.startsWith("<path>"));
5590
+ const displayPath = /^<path>([^\r\n]+)<\/path>\r?\n<type>image<\/type>/.exec(header?.text)?.[1];
5591
+ if (displayPath) aliases.set(readPathKey(displayPath), read.key);
5592
+ }
5593
+ }
5594
+ }
5595
+ for (const [alias, key] of aliases) paths.set(alias, paths.get(key));
5596
+ return paths;
5597
+ }
5536
5598
  async function editImages(values, attachments, signal, messages) {
5537
5599
  if (!Array.isArray(values) || values.length === 0 || values.length > MAX_REFERENCE_IMAGES) throw new Error(`referenceImages must contain between 1 and ${MAX_REFERENCE_IMAGES} images; omit it to generate a new image`);
5538
5600
  const available = messages === void 0 ? void 0 : sessionImageReferences(messages);
5601
+ const localReads = values.some((value) => value?.filePath !== void 0) ? localReadReferences(messages) : void 0;
5539
5602
  const references = values.map((value) => {
5603
+ if (value?.filePath !== void 0) {
5604
+ if (value.attachmentId !== void 0) throw new Error("Choose either filePath or attachmentId for each reference image");
5605
+ const image = localReads.get(readPathKey(value.filePath))?.image;
5606
+ if (!image) throw new Error("Call read_image on the selected local file first, then pass the exact file_path from that call as filePath");
5607
+ return referenceOf(image, attachments);
5608
+ }
5540
5609
  const id = normalizeAttachmentId(value?.attachmentId);
5541
5610
  if (id === void 0) invalidAttachmentId(value);
5542
5611
  if (available === void 0) return referenceOf(value, attachments);
@@ -5736,7 +5805,7 @@ function createCodexImageTool(options) {
5736
5805
  const attachments = options.attachments;
5737
5806
  return defineTool({
5738
5807
  name: CODEX_IMAGE_TOOL_NAME,
5739
- description: "Generate or edit images only when the user asks for image output, not when merely discussing images. Uses the signed-in Codex subscription. For a new image, omit referenceImages. For edits, copy attachmentId only from the selected session image block; the host supplies its metadata. Never call read_image for an attachmentId or attachment filename. Use read_image only for an actual local file whose reference is not already in the conversation. Never substitute paths, unrelated images, or text-only generation for an edit. For numbered annotations, include the clean source and location-reference image, preserve the requested changes and coordinates in the prompt, and remove guidance markers from the result. If the intended references cannot be identified, ask rather than guessing.",
5808
+ description: "Generate or edit images when the user asks for image output. Select relevant references from the requested project files, session attachments or earlier tool results. Inspect local candidates with read_image and pass only the chosen images in referenceImages. Use existing attachmentIds directly. Omit references for independent text-to-image generation. For numbered annotations include the clean source and location guide, describe the changes and coordinates, and remove markers from the output. If a required reference is unavailable, ask instead of substituting an unrelated image or a text-only generation.",
5740
5809
  parameters: {
5741
5810
  model: {
5742
5811
  type: "string",
@@ -5746,11 +5815,11 @@ function createCodexImageTool(options) {
5746
5815
  prompt: {
5747
5816
  type: "string",
5748
5817
  required: true,
5749
- description: "A complete, production-ready description of the image to generate."
5818
+ description: "Write a self-contained prompt with the intended use, subject, and relevant composition or style. Preserve exact requested text. Label each selected image by position and role (e.g. subject from image 1, palette from image 2). For edits state the change and what must stay, also on follow-ups. Add only details that support the request."
5750
5819
  },
5751
5820
  size: {
5752
5821
  type: "string",
5753
- description: "Optional GPT Image 2 output size. Use auto unless the user requests an exact valid widthxheight resolution."
5822
+ description: "Omit for automatic sizing. For an explicit aspect ratio, use valid pixel dimensions, e.g. 1536x1024 for landscape or 1024x1536 for portrait. Put framing instructions in the prompt."
5754
5823
  },
5755
5824
  quality: {
5756
5825
  type: "string",
@@ -5762,7 +5831,7 @@ function createCodexImageTool(options) {
5762
5831
  "xhigh",
5763
5832
  "max"
5764
5833
  ],
5765
- description: "Optional rendering quality. Use auto unless the user requests draft speed or final quality."
5834
+ description: "Omit to use the configured image quality. Set only when the user requests a different quality for this image."
5766
5835
  },
5767
5836
  background: {
5768
5837
  type: "string",
@@ -5790,16 +5859,20 @@ function createCodexImageTool(options) {
5790
5859
  },
5791
5860
  referenceImages: {
5792
5861
  type: "array",
5793
- description: "Optional references to 1-5 selected images. For session images provide only attachmentId; the host resolves trusted metadata. Omit only for a new image; never drop an invalid reference to bypass editing.",
5862
+ description: "Select 1-5 images for reference-guided creation or edits. Use attachmentId for a session image. For a local reference, inspect the chosen file with read_image first and use its attachmentId or the exact path from that call. Mix sources in prompt order; never drop an invalid reference.",
5794
5863
  items: {
5795
5864
  type: "object",
5796
5865
  additionalProperties: false,
5797
5866
  properties: {
5798
5867
  attachmentId: {
5799
5868
  type: "string",
5800
- required: true,
5869
+ ...typeof options.getSessionMessages !== "function" ? { required: true } : {},
5801
5870
  description: "Copy the complete attachmentId from the image block or read_image result: sha256:<64 lowercase hex>. Never pass a workspace path, absolute path, or filename. A bare 64-character hex digest is accepted and normalized to sha256:<64 lowercase hex>."
5802
5871
  },
5872
+ ...typeof options.getSessionMessages === "function" ? { filePath: {
5873
+ type: "string",
5874
+ description: "Alternative to attachmentId for a local file. Use file_path from your completed read_image call or the path shown in its image result."
5875
+ } } : {},
5803
5876
  mediaType: {
5804
5877
  type: "string",
5805
5878
  ...typeof options.getSessionMessages !== "function" ? { required: true } : {}
@@ -5969,7 +6042,7 @@ const MAX_REFERENCE_BYTES = 14e5;
5969
6042
  function createSketchAgentTool(bridge, attachments, getSessionMessages = () => []) {
5970
6043
  return defineTool({
5971
6044
  name: "codex_sketch",
5972
- description: "Edit the sketch board in this session using native editable strokes and layers. Use for @sketch requests and explicit follow-up edits to that drawing. The toolbar pen button is for manual drawing; do not require the user to open it. Start with inspect for the runId, documentId, revision and command reference. Draw with the svg op whenever possible: one SVG document per stage (paths, shapes, groups, transforms; see the reference from inspect) is far faster and richer than hand-placed strokes, and still becomes native editable strokes. Draw with depth, not flat colour: skies, skin, metal and glass take real linear/radial gradients (fill=\"url(#id)\"), glows, shadows, haze and distant things take a feGaussianBlur filter (soft edge), and light comes from a consistent direction with a darker shade, a lighter highlight and a reflected-light edge on each form. Draw the shapes, hair, clothing and lettering outlines of every layer with svg; use stroke commands only for small corrections and native text. Apply atomic batches and preview between stages. When the user attached a reference image, call reference with its attachmentId once after inspect to put it on the board as a hidden picture layer. To reproduce a reference faithfully, draw it yourself in stages, from big to small: 1) write a short plan (parts, drawing order, rough position and size of each), using preview with grid and measure with palette and regions to read proportions, key positions and the main colours, and measure scan along a few rows and columns to find exact edges; 2) block in the silhouette and the big colour areas (hair, clothes, skin, background) as filled shapes; 3) after every apply read progress (error, previous error, worst cells) and use preview mode side or diff, with box to zoom into a part, to see what is off; 4) fix the worst area first (position and size before colour, colour before detail), 5) then shading, then outlines and small details (eyes, headphones, patterns). Read exact colours from the reference with measure points instead of guessing. If a stage raised the error or looks wrong, undo it instead of painting over it. When the whole picture is roughly right, do refinement passes region by region instead of stopping: split the picture into its parts (for a figure: head and face, each mass of hair, torso, each arm, each leg, shoes and small accessories). For every part, call preview mode side with box set to that part and grid on (zoomed up to 3x) and look at reference and drawing next to each other, then measure with box on the same part and use scan along an edge to read exact positions; list the three biggest differences (edge position, size, colour, missing detail), fix them with targeted object updates or a replacement shape, and check progress. A part is done when its error stops falling or the zoomed pair looks the same; then go to the next part. Make at least one pass over every part before you finish, and never end with the first full draft. Stop when every part has had its pass and the error stops improving. When a reference picture is on the board, keep its layer hidden while drawing (compare shows it anyway), measure its key positions with preview grid, draw big shapes first, and after each stage check preview compare and fix the largest offset before adding detail. For repeated details such as hair strands or lace, generate the SVG with a script instead of placing each one by hand. and call finish to save the finished draft and release the editing lock. save is only a checkpoint. Closing the board does not stop drawing. If the user stops drawing, do not retry. Never generates AI images or sends messages. Finish returns the saved drawing as a native image attachment displayed by DSH. Refer to that attachment; never invent a Markdown image URL or use a shell-output/log path as an image. Inspect starts the board for this session. If this session is in view, its board opens automatically. Drawing continues in the background when the user switches sessions, and other sessions can draw independently. On timeout inspect before retrying; reuse the exact requestId only for the same request.",
6045
+ description: "Edit the sketch board in this session using native editable strokes and layers. Use for @sketch requests and explicit follow-up edits to that drawing. The toolbar pen button is for manual drawing; do not require the user to open it. Start with inspect for the runId, documentId, revision and command reference. Draw with the svg op whenever possible: one SVG document per stage (paths, shapes, groups, transforms; see the reference from inspect) is far faster and richer than hand-placed strokes, and still becomes native editable strokes. Draw with depth, not flat colour: skies, skin, metal and glass take real linear/radial gradients (fill=\"url(#id)\"), glows, shadows, haze and distant things take a feGaussianBlur filter (soft edge), and light comes from a consistent direction with a darker shade, a lighter highlight and a reflected-light edge on each form. Draw the shapes, hair, clothing and lettering outlines of every layer with svg; use stroke commands only for small corrections and native text. Apply atomic batches and preview between stages. When drawing from a reference, choose the relevant image from this session (including an earlier generated image) and call reference with its attachmentId once after inspect to put it on the board as a hidden picture layer. To reproduce a reference faithfully, draw it yourself in stages, from big to small: 1) write a short plan (parts, drawing order, rough position and size of each), using preview with grid and measure with palette and regions to read proportions, key positions and the main colours, and measure scan along a few rows and columns to find exact edges; 2) block in the silhouette and the big colour areas (hair, clothes, skin, background) as filled shapes; 3) after every apply read progress (error, previous error, worst cells) and use preview mode side or diff, with box to zoom into a part, to see what is off; 4) fix the worst area first (position and size before colour, colour before detail), 5) then shading, then outlines and small details (eyes, headphones, patterns). Read exact colours from the reference with measure points instead of guessing. If a stage raised the error or looks wrong, undo it instead of painting over it. When the whole picture is roughly right, do refinement passes region by region instead of stopping: split the picture into its parts (for a figure: head and face, each mass of hair, torso, each arm, each leg, shoes and small accessories). For every part, call preview mode side with box set to that part and grid on (zoomed up to 3x) and look at reference and drawing next to each other, then measure with box on the same part and use scan along an edge to read exact positions; list the three biggest differences (edge position, size, colour, missing detail), fix them with targeted object updates or a replacement shape, and check progress. A part is done when its error stops falling or the zoomed pair looks the same; then go to the next part. Make at least one pass over every part before you finish, and never end with the first full draft. Stop when every part has had its pass and the error stops improving. When a reference picture is on the board, keep its layer hidden while drawing (compare shows it anyway), measure its key positions with preview grid, draw big shapes first, and after each stage check preview compare and fix the largest offset before adding detail. For repeated details such as hair strands or lace, generate the SVG with a script instead of placing each one by hand. and call finish to save the finished draft and release the editing lock. save is only a checkpoint. Closing the board does not stop drawing. If the user stops drawing, do not retry. Never generates AI images or sends messages. Finish returns the saved drawing as a native image attachment displayed by DSH. Refer to that attachment; never invent a Markdown image URL or use a shell-output/log path as an image. Inspect starts the board for this session. If this session is in view, its board opens automatically. Drawing continues in the background when the user switches sessions, and other sessions can draw independently. On timeout inspect before retrying; reuse the exact requestId only for the same request.",
5973
6046
  parameters: {
5974
6047
  action: {
5975
6048
  type: "string",
@@ -6011,11 +6084,11 @@ function createSketchAgentTool(bridge, attachments, getSessionMessages = () => [
6011
6084
  },
6012
6085
  attachmentId: {
6013
6086
  type: "string",
6014
- description: "reference only: the attachmentId of an image the user attached to this session (copy it from the image block, never a path or filename). It is added to the board as a hidden picture layer, ready for preview compare."
6087
+ description: "reference only: the attachmentId of the chosen session image or image tool result (copy it from the image block, never a path or filename). It is added to the board as a hidden picture layer, ready for preview compare."
6015
6088
  },
6016
6089
  compare: {
6017
6090
  type: "boolean",
6018
- description: "preview only: blend the drawing 50/50 with the reference picture layer on the board, so offsets show as ghosting. Needs a picture layer; if there is none, ask the user to add the reference with the pictures button."
6091
+ description: "preview only: blend the drawing 50/50 with the reference picture layer on the board, so offsets show as ghosting. Needs a picture layer; if missing, load the intended session image with reference first."
6019
6092
  },
6020
6093
  grid: {
6021
6094
  type: "boolean",
@@ -14315,7 +14388,7 @@ function createDshSearchProvider({ resolveDshProvider, report }) {
14315
14388
  const CODEX_SEARCH_PROVIDER_ID = "codex-subscription";
14316
14389
  const CODEX_AUTO_SEARCH_PROVIDER_ID = "codex-subscription-auto";
14317
14390
  const CODEX_SEARCH_URL = "https://chatgpt.com/backend-api/codex/alpha/search";
14318
- const DEFAULT_MODEL = "gpt-5.6-luna";
14391
+ const DEFAULT_MODEL$1 = "gpt-5.6-luna";
14319
14392
  const MAX_OUTPUT_TOKENS = 4096;
14320
14393
  const MAX_SOURCE_DATE = 64;
14321
14394
  const RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
@@ -14385,7 +14458,7 @@ function createCodexSearchProvider(options) {
14385
14458
  if (preferences.searchMode === "disabled") throw new WebError("Codex search is disabled in subscription settings", "WEB_PROVIDER_UNAVAILABLE");
14386
14459
  const { access, accountId } = await readSubscriptionCredentials(options.getAuth, options.readCredential, signal);
14387
14460
  if (typeof access !== "string" || access.length === 0 || typeof accountId !== "string" || accountId.length === 0) throw new WebError("ChatGPT subscription is not signed in", "WEB_PROVIDER_CREDENTIAL_MISSING");
14388
- const model = nonEmpty(options.resolveModel?.()) ?? DEFAULT_MODEL;
14461
+ const model = nonEmpty(options.resolveModel?.()) ?? DEFAULT_MODEL$1;
14389
14462
  const id = nonEmpty(options.resolveSessionId?.()) ?? randomUUID();
14390
14463
  let response, authFailure;
14391
14464
  try {
@@ -16716,6 +16789,559 @@ function refineQuotaRate(samples, conservative) {
16716
16789
  };
16717
16790
  }
16718
16791
  //#endregion
16792
+ //#region src/quota-exhaustion.js
16793
+ const HOUR_MS$1 = 3600 * 1e3;
16794
+ function normalCdf(z) {
16795
+ const t = 1 / (1 + .2316419 * Math.abs(z));
16796
+ const p = .3989422804014327 * Math.exp(-z * z / 2) * t * (.31938153 + t * (-.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))));
16797
+ return z >= 0 ? 1 - p : p;
16798
+ }
16799
+ function normalInv(p) {
16800
+ const a = [
16801
+ -39.69683028665376,
16802
+ 220.9460984245205,
16803
+ -275.9285104469687,
16804
+ 138.357751867269,
16805
+ -30.66479806614716,
16806
+ 2.506628277459239
16807
+ ];
16808
+ const b = [
16809
+ -54.47609879822406,
16810
+ 161.5858368580409,
16811
+ -155.6989798598866,
16812
+ 66.80131188771972,
16813
+ -13.28068155288572
16814
+ ];
16815
+ const c = [
16816
+ -.007784894002430293,
16817
+ -.3223964580411365,
16818
+ -2.400758277161838,
16819
+ -2.549732539343734,
16820
+ 4.374664141464968,
16821
+ 2.938163982698783
16822
+ ];
16823
+ const d = [
16824
+ .007784695709041462,
16825
+ .3224671290700398,
16826
+ 2.445134137142996,
16827
+ 3.754408661907416
16828
+ ];
16829
+ if (p <= 0) return -Infinity;
16830
+ if (p >= 1) return Infinity;
16831
+ if (p < .02425) {
16832
+ const q = Math.sqrt(-2 * Math.log(p));
16833
+ return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
16834
+ }
16835
+ if (p > .97575) return -normalInv(1 - p);
16836
+ const q = p - .5, r = q * q;
16837
+ return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q / (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1);
16838
+ }
16839
+ function rng(seed) {
16840
+ let s = seed >>> 0;
16841
+ const uniform = () => {
16842
+ s = s + 1831565813 >>> 0;
16843
+ let t = s;
16844
+ t = Math.imul(t ^ t >>> 15, t | 1);
16845
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
16846
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
16847
+ };
16848
+ let spare = null;
16849
+ const normal = () => {
16850
+ if (spare !== null) {
16851
+ const v = spare;
16852
+ spare = null;
16853
+ return v;
16854
+ }
16855
+ let u, v, r;
16856
+ do {
16857
+ u = uniform() * 2 - 1;
16858
+ v = uniform() * 2 - 1;
16859
+ r = u * u + v * v;
16860
+ } while (r >= 1 || r === 0);
16861
+ const f = Math.sqrt(-2 * Math.log(r) / r);
16862
+ spare = v * f;
16863
+ return u * f;
16864
+ };
16865
+ return {
16866
+ uniform,
16867
+ normal
16868
+ };
16869
+ }
16870
+ function weightedQuantile(pairs, q) {
16871
+ let total = 0;
16872
+ for (const pair of pairs) total += pair[1];
16873
+ let acc = 0;
16874
+ for (const pair of pairs) {
16875
+ acc += pair[1];
16876
+ if (acc >= q * total) return pair[0];
16877
+ }
16878
+ return pairs.at(-1)?.[0];
16879
+ }
16880
+ function compressRuns(samples) {
16881
+ const out = [];
16882
+ for (let i = 0; i < samples.length; i++) {
16883
+ const same = (a, b) => a !== void 0 && b !== void 0 && a.remainingPercent === b.remainingPercent;
16884
+ if (!same(samples[i - 1], samples[i]) || !same(samples[i], samples[i + 1])) out.push(samples[i]);
16885
+ }
16886
+ return out;
16887
+ }
16888
+ function baselineExhaustion({ consumed, elapsedHours, remaining, horizonHours, daySd = .65 }) {
16889
+ if (!(consumed > 0) || !(elapsedHours > 0) || !(horizonHours > 0) || !(remaining > 0)) return { status: "insufficient" };
16890
+ const pace = consumed / elapsedHours;
16891
+ const needPace = remaining / horizonHours;
16892
+ const sd = daySd * Math.sqrt(24 / elapsedHours + 24 / horizonHours);
16893
+ const probability = normalCdf(Math.log(pace / needPace) / sd);
16894
+ const hoursAt = (q) => remaining / (pace * Math.exp(sd * normalInv(1 - probability * q)));
16895
+ return {
16896
+ status: "ready",
16897
+ method: "lognormal-pace",
16898
+ probability,
16899
+ pace,
16900
+ needPace,
16901
+ sd,
16902
+ hoursQ10: hoursAt(.1),
16903
+ hoursQ50: hoursAt(.5),
16904
+ hoursQ90: hoursAt(.9)
16905
+ };
16906
+ }
16907
+ function cyclePacePrior(pastLogPaces = [], { genericLogMean = Math.log(100 / 168), userSd = .8, betweenSd = .6 } = {}) {
16908
+ const precision = 1 / userSd ** 2 + pastLogPaces.length / betweenSd ** 2;
16909
+ return {
16910
+ paceLogMean: (genericLogMean / userSd ** 2 + pastLogPaces.reduce((sum, value) => sum + value, 0) / betweenSd ** 2) / precision,
16911
+ paceLogSd: Math.sqrt(1 / precision + betweenSd ** 2),
16912
+ cycles: pastLogPaces.length
16913
+ };
16914
+ }
16915
+ function finishedCycleLogPace(samples, cycleStartMs, windowHours = 168) {
16916
+ if (samples.length < 2) return void 0;
16917
+ const zero = samples.findIndex((sample) => sample.remainingPercent <= 0);
16918
+ if (zero < 0) {
16919
+ const hours = (samples.at(-1).at - cycleStartMs) / HOUR_MS$1;
16920
+ const used = 100 - samples.at(-1).remainingPercent;
16921
+ return hours >= .75 * windowHours && used >= 3 ? Math.log(used / hours) : void 0;
16922
+ }
16923
+ if (zero === 0) return void 0;
16924
+ const early = (samples[zero - 1].at - cycleStartMs) / HOUR_MS$1, late = (samples[zero].at - cycleStartMs) / HOUR_MS$1;
16925
+ return early > 0 ? Math.log(100 / Math.sqrt(early * late)) : void 0;
16926
+ }
16927
+ function splitPastCycles(samples, nominalStartMs, windowMs) {
16928
+ const groups = /* @__PURE__ */ new Map();
16929
+ for (const sample of samples) {
16930
+ if (sample.at >= nominalStartMs) break;
16931
+ const back = Math.ceil((nominalStartMs - sample.at) / windowMs);
16932
+ if (!groups.has(back)) groups.set(back, []);
16933
+ groups.get(back).push(sample);
16934
+ }
16935
+ return [...groups].map(([back, list]) => ({
16936
+ samples: list,
16937
+ cycleStartMs: nominalStartMs - back * windowMs
16938
+ })).filter((cycle) => cycle.samples.length >= 4 && cycle.samples[0].remainingPercent >= 90 && cycle.samples[0].at - cycle.cycleStartMs <= 12 * HOUR_MS$1 && cycle.samples.every((sample, i) => i === 0 || sample.remainingPercent <= cycle.samples[i - 1].remainingPercent + 1));
16939
+ }
16940
+ const DEFAULT_MODEL = {
16941
+ paceLogMean: Math.log(100 / 168),
16942
+ paceLogSd: 1,
16943
+ activeLogitMean: Math.log(.35 / .65),
16944
+ activeLogitSd: 1,
16945
+ minActiveFraction: .02,
16946
+ maxActiveFraction: .95,
16947
+ spellHoursLogMean: Math.log(1.5),
16948
+ spellHoursLogSd: .5,
16949
+ spellRateSd: .5,
16950
+ daySd: .65,
16951
+ slack: 1,
16952
+ hourProfile: null
16953
+ };
16954
+ function particleExhaustion(rawSamples, { cycleStartMs, resetMs, model = {}, particles = 4e3, seed = 1, anchorAtReset = true } = {}) {
16955
+ const m = {
16956
+ ...DEFAULT_MODEL,
16957
+ ...model
16958
+ };
16959
+ const samples = compressRuns(rawSamples);
16960
+ if (samples.length === 0) return { status: "insufficient" };
16961
+ const N = particles, random = rng(seed);
16962
+ const V = new Float64Array(N), spell = new Float64Array(N), day = new Float64Array(N);
16963
+ const active = new Uint8Array(N), logW = new Float64Array(N);
16964
+ const lo = new Float64Array(N), hi = new Float64Array(N).fill(Infinity), mass = new Float64Array(N).fill(1);
16965
+ const share = new Float64Array(N), alpha = new Float64Array(N), beta = new Float64Array(N), delta = new Float64Array(N);
16966
+ const logit = (x) => Math.log(x / (1 - x)), clampShare = (x) => Math.min(m.maxActiveFraction, Math.max(m.minActiveFraction, x));
16967
+ const drawSpell = () => Math.exp(m.spellRateSd * random.normal() - m.spellRateSd ** 2 / 2);
16968
+ const drawDay = () => Math.exp(m.daySd * random.normal() - m.daySd ** 2 / 2);
16969
+ const z = (x) => x <= 0 ? -Infinity : x === Infinity ? Infinity : (Math.log(x) - m.paceLogMean) / m.paceLogSd;
16970
+ const priorMass = (a, b) => {
16971
+ const za = z(a), zb = z(b);
16972
+ const mid = (za + zb) / 2;
16973
+ if (zb - za < .05) return Math.exp(-mid * mid / 2) * .3989422804014327 * (zb - za);
16974
+ return normalCdf(zb) - normalCdf(za);
16975
+ };
16976
+ for (let i = 0; i < N; i++) {
16977
+ share[i] = clampShare(1 / (1 + Math.exp(-(m.activeLogitMean + m.activeLogitSd * random.normal()))));
16978
+ beta[i] = 1 / Math.exp(m.spellHoursLogMean + m.spellHoursLogSd * random.normal());
16979
+ alpha[i] = beta[i] * share[i] / (1 - share[i]);
16980
+ delta[i] = random.uniform();
16981
+ active[i] = random.uniform() < share[i] ? 1 : 0;
16982
+ spell[i] = drawSpell();
16983
+ day[i] = drawDay();
16984
+ }
16985
+ const advance = (i, hours, hourMultiplier, limit) => {
16986
+ let left = hours;
16987
+ while (left > 1e-12) if (active[i]) {
16988
+ const hold = -Math.log(1 - random.uniform()) / beta[i];
16989
+ const run = Math.min(hold, left);
16990
+ const rate = spell[i] * day[i] / share[i];
16991
+ const next = V[i] + rate * run;
16992
+ if (limit !== void 0 && next >= limit) {
16993
+ const hit = hours - left + (limit - V[i]) / rate;
16994
+ V[i] = limit;
16995
+ return hit;
16996
+ }
16997
+ V[i] = next;
16998
+ left -= run;
16999
+ if (hold <= run) active[i] = 0;
17000
+ } else {
17001
+ const hold = -Math.log(1 - random.uniform()) / (alpha[i] * hourMultiplier);
17002
+ if (hold >= left) break;
17003
+ left -= hold;
17004
+ active[i] = 1;
17005
+ spell[i] = drawSpell();
17006
+ }
17007
+ return -1;
17008
+ };
17009
+ const segments = (fromMs, toMs) => {
17010
+ const list = [];
17011
+ let at = fromMs;
17012
+ while (at < toMs - 1) {
17013
+ const nextDay = cycleStartMs + (Math.floor((at - cycleStartMs) / (24 * HOUR_MS$1)) + 1) * 24 * HOUR_MS$1;
17014
+ const nextHour = m.hourProfile ? (Math.floor(at / HOUR_MS$1) + 1) * HOUR_MS$1 : Infinity;
17015
+ const end = Math.min(toMs, nextDay, nextHour);
17016
+ const hourOfWeek = (Math.floor(at / HOUR_MS$1) + 72) % 168;
17017
+ list.push({
17018
+ hours: (end - at) / HOUR_MS$1,
17019
+ multiplier: m.hourProfile ? m.hourProfile[hourOfWeek] : 1,
17020
+ newDay: end === nextDay
17021
+ });
17022
+ at = end;
17023
+ }
17024
+ return list;
17025
+ };
17026
+ const effectiveSize = () => {
17027
+ let max = -Infinity, sum = 0, sumSq = 0;
17028
+ for (let i = 0; i < N; i++) max = Math.max(max, logW[i]);
17029
+ if (max === -Infinity) return {
17030
+ ess: 0,
17031
+ max,
17032
+ sum: 0
17033
+ };
17034
+ for (let i = 0; i < N; i++) {
17035
+ const w = Math.exp(logW[i] - max);
17036
+ sum += w;
17037
+ sumSq += w * w;
17038
+ }
17039
+ return {
17040
+ ess: sum * sum / sumSq,
17041
+ max,
17042
+ sum
17043
+ };
17044
+ };
17045
+ const resample = ({ max, sum }) => {
17046
+ const index = new Int32Array(N);
17047
+ let cumulative = Math.exp(logW[0] - max), j = 0;
17048
+ const start = random.uniform() / N;
17049
+ for (let i = 0; i < N; i++) {
17050
+ const target = (start + i / N) * sum;
17051
+ while (cumulative < target && j < N - 1) cumulative += Math.exp(logW[++j] - max);
17052
+ index[i] = j;
17053
+ }
17054
+ for (const array of [
17055
+ V,
17056
+ spell,
17057
+ day,
17058
+ active,
17059
+ lo,
17060
+ hi,
17061
+ mass,
17062
+ share,
17063
+ beta,
17064
+ delta
17065
+ ]) {
17066
+ const copy = array.slice();
17067
+ for (let i = 0; i < N; i++) array[i] = copy[index[i]];
17068
+ }
17069
+ logW.fill(0);
17070
+ const a = .985, h = Math.sqrt(1 - a * a);
17071
+ const move = (get, set) => {
17072
+ let mean = 0, sq = 0;
17073
+ for (let i = 0; i < N; i++) {
17074
+ const v = get(i);
17075
+ mean += v;
17076
+ sq += v * v;
17077
+ }
17078
+ mean /= N;
17079
+ const sd = Math.sqrt(Math.max(0, sq / N - mean * mean));
17080
+ for (let i = 0; i < N; i++) set(i, a * get(i) + (1 - a) * mean + h * sd * random.normal());
17081
+ };
17082
+ move((i) => logit(share[i]), (i, v) => {
17083
+ share[i] = clampShare(1 / (1 + Math.exp(-v)));
17084
+ });
17085
+ move((i) => -Math.log(beta[i]), (i, v) => {
17086
+ beta[i] = Math.exp(-v);
17087
+ });
17088
+ for (let i = 0; i < N; i++) alpha[i] = beta[i] * share[i] / (1 - share[i]);
17089
+ };
17090
+ if (!anchorAtReset) for (let i = 0; i < N; i++) V[i] = (100 - samples[0].remainingPercent + .5) * Math.exp(m.paceLogSd * random.normal());
17091
+ let clock = anchorAtReset ? cycleStartMs : samples[0].at;
17092
+ let minEss = N, logEvidence = 0;
17093
+ for (const sample of samples) {
17094
+ for (const segment of segments(clock, sample.at)) for (let i = 0; i < N; i++) {
17095
+ advance(i, segment.hours, segment.multiplier);
17096
+ if (segment.newDay) day[i] = drawDay();
17097
+ }
17098
+ clock = Math.max(clock, sample.at);
17099
+ const before = effectiveSize();
17100
+ const y = sample.remainingPercent;
17101
+ for (let i = 0; i < N; i++) {
17102
+ if (logW[i] === -Infinity) continue;
17103
+ const usedLow = y >= 100 ? 0 : Math.max(0, 100 + delta[i] - y - 1 - m.slack);
17104
+ const usedHigh = y <= 0 ? Infinity : 100 + delta[i] - y + m.slack;
17105
+ let nextLo = lo[i], nextHi = hi[i];
17106
+ if (V[i] > 0) {
17107
+ nextLo = Math.max(nextLo, usedLow / V[i]);
17108
+ nextHi = Math.min(nextHi, usedHigh / V[i]);
17109
+ } else if (usedLow > 0) nextHi = -1;
17110
+ const nextMass = nextHi > nextLo ? priorMass(nextLo, nextHi) : 0;
17111
+ if (!(nextMass > 0)) {
17112
+ logW[i] = -Infinity;
17113
+ continue;
17114
+ }
17115
+ logW[i] += Math.log(nextMass / mass[i]);
17116
+ lo[i] = nextLo;
17117
+ hi[i] = nextHi;
17118
+ mass[i] = nextMass;
17119
+ }
17120
+ const after = effectiveSize();
17121
+ if (!(after.ess > 0)) return {
17122
+ status: "misfit",
17123
+ reason: "no-particle-explains-readings",
17124
+ readings: samples.length
17125
+ };
17126
+ logEvidence += Math.log(after.sum / before.sum) + after.max - before.max;
17127
+ minEss = Math.min(minEss, after.ess);
17128
+ if (after.ess < N / 2) resample(after);
17129
+ }
17130
+ const final = effectiveSize();
17131
+ if (final.ess < N) resample(final);
17132
+ const rho = new Float64Array(N);
17133
+ let activeNow = 0;
17134
+ for (let i = 0; i < N; i++) {
17135
+ const za = z(lo[i]), zb = z(hi[i]);
17136
+ const u = normalCdf(za) + random.uniform() * (normalCdf(zb) - normalCdf(za));
17137
+ const drawn = zb - za < .05 ? za + random.uniform() * (zb - za) : normalInv(Math.min(.999999999999, Math.max(1e-12, u)));
17138
+ rho[i] = Math.exp(m.paceLogMean + m.paceLogSd * Math.min(zb, Math.max(za, drawn)));
17139
+ activeNow += active[i];
17140
+ }
17141
+ const paceNow = Array.from(rho, (value) => [value, 1]).sort((a, b) => a[0] - b[0]);
17142
+ const hitMs = new Float64Array(N), done = new Uint8Array(N);
17143
+ let t = clock;
17144
+ for (const segment of segments(clock, resetMs)) {
17145
+ for (let i = 0; i < N; i++) {
17146
+ if (done[i]) continue;
17147
+ const hit = advance(i, segment.hours, segment.multiplier, (99 + delta[i]) / rho[i]);
17148
+ if (hit >= 0) {
17149
+ done[i] = 1;
17150
+ hitMs[i] = t + hit * HOUR_MS$1;
17151
+ } else if (segment.newDay) day[i] = drawDay();
17152
+ }
17153
+ t += segment.hours * HOUR_MS$1;
17154
+ }
17155
+ const hits = [], leftover = [];
17156
+ for (let i = 0; i < N; i++) if (done[i]) hits.push(hitMs[i]);
17157
+ else leftover.push(Math.max(0, Math.floor(100 - rho[i] * V[i] + delta[i])));
17158
+ hits.sort((a, b) => a - b);
17159
+ leftover.sort((a, b) => a - b);
17160
+ const at = (sorted, q) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))];
17161
+ return {
17162
+ status: "ready",
17163
+ method: "switching-particle",
17164
+ probability: hits.length / N,
17165
+ runOutAt: hits.length >= 50 ? {
17166
+ q10: at(hits, .1),
17167
+ q50: at(hits, .5),
17168
+ q90: at(hits, .9)
17169
+ } : null,
17170
+ cumulative: (atMs) => {
17171
+ let count = 0;
17172
+ while (count < hits.length && hits[count] <= atMs) count++;
17173
+ return count / N;
17174
+ },
17175
+ remainingAtReset: leftover.length >= 50 ? {
17176
+ q10: at(leftover, .1),
17177
+ q50: at(leftover, .5),
17178
+ q90: at(leftover, .9)
17179
+ } : null,
17180
+ activeNow: activeNow / N,
17181
+ cyclePace: {
17182
+ q10: weightedQuantile(paceNow, .1),
17183
+ q50: weightedQuantile(paceNow, .5),
17184
+ q90: weightedQuantile(paceNow, .9)
17185
+ },
17186
+ minEss,
17187
+ logEvidence,
17188
+ readings: samples.length,
17189
+ particles: N
17190
+ };
17191
+ }
17192
+ const memo = /* @__PURE__ */ new Map();
17193
+ function exhaustionOutlook(history, { remainingPercent, resetsAt, windowSeconds, pastCycles = [], model = {}, particles = 3e3, batches = 4, memoScope } = {}) {
17194
+ if (!(windowSeconds >= 86400) || !Number.isFinite(resetsAt) || history.length === 0) return void 0;
17195
+ const newest = history.at(-1), resetMs = resetsAt * 1e3;
17196
+ const horizonHours = (resetMs - newest.at) / HOUR_MS$1;
17197
+ if (!(horizonHours > 0) || horizonHours > 720) return void 0;
17198
+ if (remainingPercent <= 0) return { status: "exhausted" };
17199
+ const readings = (samples) => samples.map(({ at, remainingPercent }) => [at, remainingPercent]);
17200
+ const memoKey = createHash("sha256").update(JSON.stringify([
17201
+ memoScope,
17202
+ resetsAt,
17203
+ windowSeconds,
17204
+ remainingPercent,
17205
+ model,
17206
+ particles,
17207
+ batches,
17208
+ readings(history),
17209
+ pastCycles.map(({ cycleStartMs, samples }) => [cycleStartMs, readings(samples)])
17210
+ ])).digest("hex");
17211
+ if (memo.has(memoKey)) return memo.get(memoKey);
17212
+ const nominalStart = resetMs - windowSeconds * 1e3;
17213
+ const anchorAtReset = nominalStart <= history[0].at && history[0].remainingPercent >= 90;
17214
+ const cycleStartMs = anchorAtReset ? nominalStart : history[0].at;
17215
+ const used = anchorAtReset ? 100 - newest.remainingPercent : history[0].remainingPercent - newest.remainingPercent;
17216
+ const elapsedHours = (newest.at - cycleStartMs) / HOUR_MS$1;
17217
+ const logPaces = pastCycles.map((cycle) => finishedCycleLogPace(cycle.samples, cycle.cycleStartMs, windowSeconds / 3600)).filter(Number.isFinite);
17218
+ const prior = cyclePacePrior(logPaces, { genericLogMean: Math.log(100 / (windowSeconds / 3600)) });
17219
+ const enough = elapsedHours >= 6 && used >= 3;
17220
+ const evidence = {
17221
+ elapsedHours,
17222
+ usedPercent: used,
17223
+ pastCycles: logPaces.length,
17224
+ horizonHours,
17225
+ needPacePerHour: remainingPercent / horizonHours,
17226
+ priorOnly: !enough
17227
+ };
17228
+ const finish = (value) => {
17229
+ if (memo.size >= 12) memo.delete(memo.keys().next().value);
17230
+ memo.set(memoKey, value);
17231
+ return value;
17232
+ };
17233
+ if (!enough && logPaces.length < 3) return finish({
17234
+ status: "calibrating",
17235
+ reason: "early-cycle",
17236
+ ...evidence
17237
+ });
17238
+ const baseline = enough ? baselineExhaustion({
17239
+ consumed: used,
17240
+ elapsedHours,
17241
+ remaining: remainingPercent,
17242
+ horizonHours
17243
+ }) : { status: "insufficient" };
17244
+ const runs = [];
17245
+ for (let batch = 0; batch < batches; batch++) {
17246
+ const seed = (Math.floor(newest.at / 1e3) ^ Math.imul(history.length + 31 * batch, 2654435761)) >>> 0;
17247
+ const run = particleExhaustion(history, {
17248
+ cycleStartMs,
17249
+ resetMs,
17250
+ model: {
17251
+ ...model,
17252
+ ...prior
17253
+ },
17254
+ particles,
17255
+ seed,
17256
+ anchorAtReset
17257
+ });
17258
+ if (run.status === "ready") runs.push(run);
17259
+ }
17260
+ const mean = (values) => values.reduce((sum, value) => sum + value, 0) / values.length;
17261
+ if (runs.length < Math.max(1, batches - 1)) {
17262
+ if (baseline.status !== "ready") return finish({
17263
+ status: "calibrating",
17264
+ reason: "model-misfit",
17265
+ ...evidence
17266
+ });
17267
+ return finish({
17268
+ status: "ready",
17269
+ method: baseline.method,
17270
+ misfit: true,
17271
+ ...evidence,
17272
+ probability: baseline.probability,
17273
+ probabilityLow: Math.max(0, baseline.probability - .15),
17274
+ probabilityHigh: Math.min(1, baseline.probability + .15),
17275
+ runOutAt: {
17276
+ q10: newest.at + baseline.hoursQ10 * HOUR_MS$1,
17277
+ q50: newest.at + baseline.hoursQ50 * HOUR_MS$1,
17278
+ q90: newest.at + baseline.hoursQ90 * HOUR_MS$1
17279
+ },
17280
+ remainingAtReset: null
17281
+ });
17282
+ }
17283
+ const probability = mean(runs.map((run) => run.probability));
17284
+ const error = runs.length > 1 ? Math.sqrt(runs.reduce((sum, run) => sum + (run.probability - probability) ** 2, 0) / (runs.length - 1) / runs.length) : .03;
17285
+ const timed = runs.filter((run) => run.runOutAt), kept = runs.filter((run) => run.remainingAtReset);
17286
+ const average = (list, pick) => list.length ? Object.fromEntries([
17287
+ "q10",
17288
+ "q50",
17289
+ "q90"
17290
+ ].map((q) => [q, mean(list.map((run) => pick(run)[q]))])) : null;
17291
+ const other = baseline.status === "ready" ? baseline.probability : probability;
17292
+ return finish({
17293
+ status: "ready",
17294
+ method: "switching-particle",
17295
+ ...evidence,
17296
+ probability,
17297
+ probabilityLow: Math.max(0, Math.min(probability, other) - 2 * error),
17298
+ probabilityHigh: Math.min(1, Math.max(probability, other) + 2 * error),
17299
+ monteCarloError: error,
17300
+ baselineProbability: baseline.status === "ready" ? baseline.probability : void 0,
17301
+ runOutAt: average(timed, (run) => run.runOutAt),
17302
+ runOutCurve: Array.from({ length: Math.ceil(horizonHours / 6) }, (_, k) => Math.min(resetMs, newest.at + (k + 1) * 6 * HOUR_MS$1)).map((atMs) => [atMs, mean(runs.map((run) => run.cumulative(atMs)))]),
17303
+ remainingAtReset: average(kept, (run) => run.remainingAtReset)
17304
+ });
17305
+ }
17306
+ const BANDS = [
17307
+ "low",
17308
+ "possible",
17309
+ "likely",
17310
+ "very-likely"
17311
+ ];
17312
+ const EDGES = [
17313
+ .15,
17314
+ .5,
17315
+ .8
17316
+ ];
17317
+ function riskBand(outlook, previous = {}, nowMs = Date.now(), { margin = .07, dwellMs = 20 * 6e4, jump = .15 } = {}) {
17318
+ if (outlook?.status !== "ready" || outlook.priorOnly && outlook.pastCycles < 3) return {
17319
+ ...previous,
17320
+ shown: "hold"
17321
+ };
17322
+ const raw = (p) => EDGES.filter((edge) => p >= edge).length;
17323
+ let level = previous.band === void 0 ? raw(outlook.probability) : BANDS.indexOf(previous.band);
17324
+ const up = level < 3 && outlook.probability >= EDGES[level] + margin;
17325
+ const down = level > 0 && outlook.probabilityHigh < EDGES[level - 1] - margin;
17326
+ if (!up && !down) return {
17327
+ band: BANDS[level],
17328
+ shown: BANDS[level]
17329
+ };
17330
+ const target = BANDS[raw(up ? outlook.probability : outlook.probabilityHigh)];
17331
+ const far = up ? outlook.probability >= EDGES[level] + jump : outlook.probabilityHigh < EDGES[level - 1] - jump;
17332
+ const waited = previous.pendingBand === target && nowMs - previous.pendingSince >= dwellMs;
17333
+ if (far || waited) return {
17334
+ band: target,
17335
+ shown: target
17336
+ };
17337
+ return {
17338
+ band: BANDS[level],
17339
+ shown: BANDS[level],
17340
+ pendingBand: target,
17341
+ pendingSince: previous.pendingBand === target ? previous.pendingSince : nowMs
17342
+ };
17343
+ }
17344
+ //#endregion
16719
17345
  //#region src/quota-forecast.js
16720
17346
  const HOUR_MS = 3600 * 1e3;
16721
17347
  const HISTORY_MS = 720 * HOUR_MS;
@@ -16811,7 +17437,8 @@ function observeQuotaForecast(state, windows, now = Date.now(), context = {}) {
16811
17437
  const record = {
16812
17438
  resetsAt,
16813
17439
  epochStart,
16814
- samples: retainSamples([...previous?.samples ?? [], sample], now)
17440
+ samples: retainSamples([...previous?.samples ?? [], sample], now),
17441
+ ...previous?.risk && !resetChanged && !quotaIncreased ? { risk: previous.risk } : {}
16815
17442
  };
16816
17443
  next.windows[key] = record;
16817
17444
  changed = true;
@@ -16822,6 +17449,26 @@ function observeQuotaForecast(state, windows, now = Date.now(), context = {}) {
16822
17449
  };
16823
17450
  }
16824
17451
  function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
17452
+ const forecast = estimateShortHorizon(state, window, now, context);
17453
+ const key = keyFor(window, context);
17454
+ const record = state?.windows?.[key];
17455
+ if (forecast.reason === "stale" || record === void 0 || !finite(window?.remainingPercent) || !finite(window.resetsAt) || !finite(record.resetsAt) || Math.abs(record.resetsAt - Number(window.resetsAt)) > 300 || !(window.windowSeconds >= 86400)) return forecast;
17456
+ const history = record.samples.filter((sample) => sample.at >= (record.epochStart ?? 0) && sample.at <= now);
17457
+ const windowMs = window.windowSeconds * 1e3;
17458
+ const exhaustion = exhaustionOutlook(history, {
17459
+ remainingPercent: clampPercent(window.remainingPercent),
17460
+ resetsAt: record.resetsAt,
17461
+ windowSeconds: window.windowSeconds,
17462
+ memoScope: key,
17463
+ pastCycles: splitPastCycles(record.samples, record.resetsAt * 1e3 - windowMs, windowMs)
17464
+ });
17465
+ return exhaustion === void 0 ? forecast : {
17466
+ ...forecast,
17467
+ exhaustion,
17468
+ risk: riskBand(exhaustion, record.risk, history.at(-1).at)
17469
+ };
17470
+ }
17471
+ function estimateShortHorizon(state, window, now = Date.now(), context = {}) {
16825
17472
  if (!finite(window?.remainingPercent)) return { status: "calibrating" };
16826
17473
  const record = state?.windows?.[keyFor(window, context)];
16827
17474
  if (record === void 0) return { status: "calibrating" };
@@ -16961,10 +17608,25 @@ function forecastUsage(usage, state = { windows: {} }, now = Date.now(), options
16961
17608
  changed ||= observed.changed;
16962
17609
  return {
16963
17610
  ...limit,
16964
- windows: limit.windows.map((window) => ({
16965
- ...window,
16966
- forecast: estimateQuotaForecast(nextState, window, now, context)
16967
- }))
17611
+ windows: limit.windows.map((window) => {
17612
+ const forecast = estimateQuotaForecast(nextState, window, now, context);
17613
+ const key = keyFor(window, context), record = nextState.windows[key];
17614
+ const { shown, ...risk } = forecast.risk ?? {};
17615
+ if (forecast.risk && record && JSON.stringify(record.risk ?? {}) !== JSON.stringify(risk)) {
17616
+ nextState = { windows: {
17617
+ ...nextState.windows,
17618
+ [key]: {
17619
+ ...record,
17620
+ risk
17621
+ }
17622
+ } };
17623
+ changed = true;
17624
+ }
17625
+ return {
17626
+ ...window,
17627
+ forecast
17628
+ };
17629
+ })
16968
17630
  };
16969
17631
  });
16970
17632
  return {
@@ -17049,6 +17711,21 @@ function createQuotaForecastReader({ reader, enabled, now = Date.now, scope = ()
17049
17711
  const DEFAULT_MAX_BYTES = 256 * 1024;
17050
17712
  const MAX_WINDOWS = 128;
17051
17713
  const MAX_SAMPLES = 280;
17714
+ const RISK_BANDS = /* @__PURE__ */ new Set([
17715
+ "low",
17716
+ "possible",
17717
+ "likely",
17718
+ "very-likely"
17719
+ ]);
17720
+ function sanitizeRisk(value) {
17721
+ if (!RISK_BANDS.has(value?.band)) return void 0;
17722
+ const { band, pendingBand, pendingSince } = value;
17723
+ return RISK_BANDS.has(pendingBand) && pendingBand !== band && Number.isSafeInteger(pendingSince) && pendingSince >= 0 ? {
17724
+ band,
17725
+ pendingBand,
17726
+ pendingSince
17727
+ } : { band };
17728
+ }
17052
17729
  function sanitize(value) {
17053
17730
  if (value === null || typeof value !== "object" || Array.isArray(value) || value.windows === null || typeof value.windows !== "object" || Array.isArray(value.windows)) return void 0;
17054
17731
  const entries = Object.entries(value.windows);
@@ -17071,10 +17748,12 @@ function sanitize(value) {
17071
17748
  }
17072
17749
  const epochStart = record.epochStart;
17073
17750
  if (epochStart !== void 0 && !Number.isFinite(epochStart)) return void 0;
17751
+ const risk = sanitizeRisk(record.risk);
17074
17752
  windows[key] = {
17075
17753
  resetsAt,
17076
17754
  ...epochStart === void 0 ? {} : { epochStart },
17077
- samples
17755
+ samples,
17756
+ ...risk ? { risk } : {}
17078
17757
  };
17079
17758
  }
17080
17759
  return { windows };
@@ -19254,6 +19933,8 @@ function apply(ctx, config = {}) {
19254
19933
  maxRequestImageBytes: MAX_REQUEST_IMAGE_BYTES,
19255
19934
  requestImagePixelBudget: REQUEST_IMAGE_PIXEL_BUDGET,
19256
19935
  requestImageMaxBytes: REQUEST_IMAGE_MAX_BYTES,
19936
+ maxImageBytes: REQUEST_IMAGE_MAX_BYTES,
19937
+ requestImageBudgetCount: 20,
19257
19938
  cacheRetention: "short",
19258
19939
  transport: "sse"
19259
19940
  });