dsh-codex-subscription 3.2.26 → 3.2.28

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
@@ -16,8 +16,7 @@ import * as dshLlm from "@deepseek-ai/dsh-llm";
16
16
  import { LlmError, createUserMessage } from "@deepseek-ai/dsh-llm";
17
17
  import { fileURLToPath, pathToFileURL } from "node:url";
18
18
  import { openaiCodexProvider as createOpenAICodexProvider } from "@earendil-works/pi-ai/providers/openai-codex";
19
- import { isContextOverflow } from "@earendil-works/pi-ai/utils/overflow";
20
- import { createModels } from "@earendil-works/pi-ai";
19
+ import { createModels, isContextOverflow } from "@earendil-works/pi-ai";
21
20
  import { clientRequestSchema } from "@deepseek-ai/dsh-client-connection";
22
21
  import { lstat, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
23
22
  import { PassThrough } from "node:stream";
@@ -458,6 +457,8 @@ const SPEED_MODE_FAST = "fast";
458
457
  const SPEED_MODE_ULTRAFAST = "ultrafast";
459
458
  const DEFAULT_SPEED_MODE = SPEED_MODE_STANDARD;
460
459
  const OUTPUT_VERBOSITY_FIELD = "outputVerbosity";
460
+ const CUSTOM_INSTRUCTIONS_FIELD = "customInstructions";
461
+ const CUSTOM_INSTRUCTIONS_LIMIT = 1500;
461
462
  const OUTPUT_VERBOSITY_DEFAULT = "default";
462
463
  const OUTPUT_VERBOSITY_MEDIUM = "medium";
463
464
  const OUTPUT_VERBOSITY_HIGH = "high";
@@ -2800,10 +2801,14 @@ function createModelRetryBridge() {
2800
2801
  const scope = new AsyncLocalStorage();
2801
2802
  const wrapStream = (factory, options) => (async function* () {
2802
2803
  const hint = createModelRetryHint();
2803
- const iterator = scope.run(hint, () => factory(options)[Symbol.asyncIterator]());
2804
+ const request = {
2805
+ hint,
2806
+ purpose: options.purpose
2807
+ };
2808
+ const iterator = scope.run(request, () => factory(options)[Symbol.asyncIterator]());
2804
2809
  try {
2805
2810
  while (true) {
2806
- const result = await scope.run(hint, () => iterator.next());
2811
+ const result = await scope.run(request, () => iterator.next());
2807
2812
  if (result.done) return;
2808
2813
  const event = result.value;
2809
2814
  if (event.type === "finish" && event.reason?.kind === "error") yield {
@@ -2816,11 +2821,12 @@ function createModelRetryBridge() {
2816
2821
  else yield event;
2817
2822
  }
2818
2823
  } finally {
2819
- await scope.run(hint, () => iterator.return?.());
2824
+ await scope.run(request, () => iterator.return?.());
2820
2825
  }
2821
2826
  })();
2822
2827
  return {
2823
- current: () => scope.getStore(),
2828
+ current: () => scope.getStore()?.hint,
2829
+ currentPurpose: () => scope.getStore()?.purpose,
2824
2830
  wrapAdapter(adapter) {
2825
2831
  return new Proxy(adapter, { get(target, property) {
2826
2832
  if (property === "stream") return (options) => wrapStream((o) => target.stream(o), options);
@@ -2967,6 +2973,22 @@ function safeStreamHealth(value) {
2967
2973
  }
2968
2974
  //#endregion
2969
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
+ }
2970
2992
  const FAST_SERVICE_TIER = "priority";
2971
2993
  const ULTRAFAST_SERVICE_TIER = "ultrafast";
2972
2994
  /** Apply the chosen detail to user and tool-result images after the provider assembles the request. */
@@ -3035,7 +3057,7 @@ function isDshAutoReview(context) {
3035
3057
  * persistence, headers, transport, and model behavior remain owned by the
3036
3058
  * original provider.
3037
3059
  */
3038
- function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, resolveOutputVerbosity = () => OUTPUT_VERBOSITY_DEFAULT, resolveInputImageDetail = () => void 0, resolveReasoningSummary = () => void 0, resolveContextMode = () => void 0, resolveCustomContextWindow = () => void 0, resolveReviewModel = () => REVIEW_MODEL_SESSION, catalog, connection, compaction, reasoning, ultra, runNetwork = (_area, operation) => operation(), runOAuthRefresh = (operation) => operation(), beginModelAttempt = createModelAttempt, providerFactory = createOpenAICodexProvider } = {}) {
3060
+ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, resolveCustomInstructions = () => "", resolveOutputVerbosity = () => OUTPUT_VERBOSITY_DEFAULT, resolveInputImageDetail = () => void 0, resolveReasoningSummary = () => void 0, resolveContextMode = () => void 0, resolveCustomContextWindow = () => void 0, resolveReviewModel = () => REVIEW_MODEL_SESSION, catalog, connection, compaction, reasoning, ultra, runNetwork = (_area, operation) => operation(), runOAuthRefresh = (operation) => operation(), beginModelAttempt = createModelAttempt, providerFactory = createOpenAICodexProvider } = {}) {
3039
3061
  const provider = providerFactory();
3040
3062
  const streamHealth = createModelStreamHealth({ log: (level, message) => diagnosticLog.log(level, "model-stream", message) });
3041
3063
  const retryBridge = createModelRetryBridge();
@@ -3052,7 +3074,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3052
3074
  });
3053
3075
  const modelMetadata = (model) => catalog?.metadata?.(model?.id);
3054
3076
  const supportsVerbosity = (model) => modelMetadata(model)?.supportVerbosity ?? model?.id !== "gpt-5.3-codex-spark";
3055
- const withPreferences = (model, options = {}) => {
3077
+ const withPreferences = (model, options = {}, instructions = "") => {
3056
3078
  const metadata = modelMetadata(model);
3057
3079
  const requestedVerbosity = resolveOutputVerbosity();
3058
3080
  const textVerbosity = supportsVerbosity(model) ? requestedVerbosity === "default" ? metadata?.defaultVerbosity ?? "medium" : requestedVerbosity : void 0;
@@ -3068,7 +3090,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3068
3090
  ...serviceTier === void 0 ? {} : { serviceTier },
3069
3091
  async onPayload(payload, requestModel) {
3070
3092
  const preferred = {
3071
- ...payload,
3093
+ ...withUserPreferences(payload, instructions),
3072
3094
  ...textVerbosity === void 0 ? {} : { text: {
3073
3095
  ...payload.text ?? {},
3074
3096
  verbosity: textVerbosity
@@ -3403,15 +3425,26 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3403
3425
  };
3404
3426
  const routed = (method, model, transcript, options) => {
3405
3427
  const context = understandsSystemMessages(runtimeVersions().piAi) ? transcript : hoistLeadingSystem(transcript);
3428
+ const reviewRequest = isDshAutoReview(context);
3406
3429
  const route = reviewRoute(model, context);
3430
+ const purpose = options?.purpose ?? retryBridge.currentPurpose();
3431
+ const instructions = !reviewRequest && purpose === void 0 ? resolveCustomInstructions()?.trim() : "";
3407
3432
  const source = {
3408
3433
  method,
3409
3434
  model,
3410
3435
  context,
3411
3436
  options
3412
3437
  };
3413
- const create = () => route === void 0 ? networkIterable((prepared) => provider[method](model, context, prepared), withPreferences(model, options), isDshAutoReview(context), source) : networkIterable((prepared) => provider[method](model, context, prepared), withReview(route, options), true, source);
3414
- return isDshAutoReview(context) ? reviewIterable(create) : create();
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);
3447
+ return reviewRequest ? reviewIterable(create) : create();
3415
3448
  };
3416
3449
  return Object.freeze({
3417
3450
  ...provider,
@@ -3434,6 +3467,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3434
3467
  });
3435
3468
  }
3436
3469
  Object.freeze([
3470
+ "0.82.1",
3437
3471
  "0.85.1",
3438
3472
  "0.87.1",
3439
3473
  "1.1.0",
@@ -3442,7 +3476,8 @@ Object.freeze([
3442
3476
  "1.4.0",
3443
3477
  "1.5.0",
3444
3478
  "1.5.1",
3445
- "1.5.2"
3479
+ "1.5.2",
3480
+ "1.6.0"
3446
3481
  ]);
3447
3482
  //#endregion
3448
3483
  //#region src/reasoning-json.js
@@ -5084,7 +5119,7 @@ function inheritedOriginalImageRef(session, assetId) {
5084
5119
  }
5085
5120
  //#endregion
5086
5121
  //#region src/version.js
5087
- const PACKAGE_VERSION = "3.2.26";
5122
+ const PACKAGE_VERSION = "3.2.28";
5088
5123
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
5089
5124
  //#endregion
5090
5125
  //#region node_modules/@deepseek-ai/dsh-home-paths/lib/index.js
@@ -5514,7 +5549,7 @@ async function readSessionImage(attachmentId, attachments, signal, messages) {
5514
5549
  const id = normalizeAttachmentId(attachmentId);
5515
5550
  if (id === void 0) invalidAttachmentId({ attachmentId });
5516
5551
  const selected = sessionImageReferences(messages).get(id);
5517
- 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.");
5518
5553
  const stored = await attachments.readImage(referenceOf(selected, attachments), signal);
5519
5554
  return {
5520
5555
  data: stored.data,
@@ -5522,10 +5557,55 @@ async function readSessionImage(attachmentId, attachments, signal, messages) {
5522
5557
  name: stored.ref.name
5523
5558
  };
5524
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
+ }
5525
5598
  async function editImages(values, attachments, signal, messages) {
5526
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`);
5527
5600
  const available = messages === void 0 ? void 0 : sessionImageReferences(messages);
5601
+ const localReads = values.some((value) => value?.filePath !== void 0) ? localReadReferences(messages) : void 0;
5528
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
+ }
5529
5609
  const id = normalizeAttachmentId(value?.attachmentId);
5530
5610
  if (id === void 0) invalidAttachmentId(value);
5531
5611
  if (available === void 0) return referenceOf(value, attachments);
@@ -5725,7 +5805,7 @@ function createCodexImageTool(options) {
5725
5805
  const attachments = options.attachments;
5726
5806
  return defineTool({
5727
5807
  name: CODEX_IMAGE_TOOL_NAME,
5728
- 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.",
5729
5809
  parameters: {
5730
5810
  model: {
5731
5811
  type: "string",
@@ -5735,11 +5815,11 @@ function createCodexImageTool(options) {
5735
5815
  prompt: {
5736
5816
  type: "string",
5737
5817
  required: true,
5738
- 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."
5739
5819
  },
5740
5820
  size: {
5741
5821
  type: "string",
5742
- 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."
5743
5823
  },
5744
5824
  quality: {
5745
5825
  type: "string",
@@ -5751,7 +5831,7 @@ function createCodexImageTool(options) {
5751
5831
  "xhigh",
5752
5832
  "max"
5753
5833
  ],
5754
- 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."
5755
5835
  },
5756
5836
  background: {
5757
5837
  type: "string",
@@ -5779,16 +5859,20 @@ function createCodexImageTool(options) {
5779
5859
  },
5780
5860
  referenceImages: {
5781
5861
  type: "array",
5782
- 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.",
5783
5863
  items: {
5784
5864
  type: "object",
5785
5865
  additionalProperties: false,
5786
5866
  properties: {
5787
5867
  attachmentId: {
5788
5868
  type: "string",
5789
- required: true,
5869
+ ...typeof options.getSessionMessages !== "function" ? { required: true } : {},
5790
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>."
5791
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
+ } } : {},
5792
5876
  mediaType: {
5793
5877
  type: "string",
5794
5878
  ...typeof options.getSessionMessages !== "function" ? { required: true } : {}
@@ -5958,7 +6042,7 @@ const MAX_REFERENCE_BYTES = 14e5;
5958
6042
  function createSketchAgentTool(bridge, attachments, getSessionMessages = () => []) {
5959
6043
  return defineTool({
5960
6044
  name: "codex_sketch",
5961
- 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.",
5962
6046
  parameters: {
5963
6047
  action: {
5964
6048
  type: "string",
@@ -6000,11 +6084,11 @@ function createSketchAgentTool(bridge, attachments, getSessionMessages = () => [
6000
6084
  },
6001
6085
  attachmentId: {
6002
6086
  type: "string",
6003
- 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."
6004
6088
  },
6005
6089
  compare: {
6006
6090
  type: "boolean",
6007
- 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."
6008
6092
  },
6009
6093
  grid: {
6010
6094
  type: "boolean",
@@ -14304,7 +14388,7 @@ function createDshSearchProvider({ resolveDshProvider, report }) {
14304
14388
  const CODEX_SEARCH_PROVIDER_ID = "codex-subscription";
14305
14389
  const CODEX_AUTO_SEARCH_PROVIDER_ID = "codex-subscription-auto";
14306
14390
  const CODEX_SEARCH_URL = "https://chatgpt.com/backend-api/codex/alpha/search";
14307
- const DEFAULT_MODEL = "gpt-5.6-luna";
14391
+ const DEFAULT_MODEL$1 = "gpt-5.6-luna";
14308
14392
  const MAX_OUTPUT_TOKENS = 4096;
14309
14393
  const MAX_SOURCE_DATE = 64;
14310
14394
  const RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
@@ -14374,7 +14458,7 @@ function createCodexSearchProvider(options) {
14374
14458
  if (preferences.searchMode === "disabled") throw new WebError("Codex search is disabled in subscription settings", "WEB_PROVIDER_UNAVAILABLE");
14375
14459
  const { access, accountId } = await readSubscriptionCredentials(options.getAuth, options.readCredential, signal);
14376
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");
14377
- const model = nonEmpty(options.resolveModel?.()) ?? DEFAULT_MODEL;
14461
+ const model = nonEmpty(options.resolveModel?.()) ?? DEFAULT_MODEL$1;
14378
14462
  const id = nonEmpty(options.resolveSessionId?.()) ?? randomUUID();
14379
14463
  let response, authFailure;
14380
14464
  try {
@@ -16705,6 +16789,559 @@ function refineQuotaRate(samples, conservative) {
16705
16789
  };
16706
16790
  }
16707
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
16708
17345
  //#region src/quota-forecast.js
16709
17346
  const HOUR_MS = 3600 * 1e3;
16710
17347
  const HISTORY_MS = 720 * HOUR_MS;
@@ -16800,7 +17437,8 @@ function observeQuotaForecast(state, windows, now = Date.now(), context = {}) {
16800
17437
  const record = {
16801
17438
  resetsAt,
16802
17439
  epochStart,
16803
- samples: retainSamples([...previous?.samples ?? [], sample], now)
17440
+ samples: retainSamples([...previous?.samples ?? [], sample], now),
17441
+ ...previous?.risk && !resetChanged && !quotaIncreased ? { risk: previous.risk } : {}
16804
17442
  };
16805
17443
  next.windows[key] = record;
16806
17444
  changed = true;
@@ -16811,6 +17449,26 @@ function observeQuotaForecast(state, windows, now = Date.now(), context = {}) {
16811
17449
  };
16812
17450
  }
16813
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 = {}) {
16814
17472
  if (!finite(window?.remainingPercent)) return { status: "calibrating" };
16815
17473
  const record = state?.windows?.[keyFor(window, context)];
16816
17474
  if (record === void 0) return { status: "calibrating" };
@@ -16950,10 +17608,25 @@ function forecastUsage(usage, state = { windows: {} }, now = Date.now(), options
16950
17608
  changed ||= observed.changed;
16951
17609
  return {
16952
17610
  ...limit,
16953
- windows: limit.windows.map((window) => ({
16954
- ...window,
16955
- forecast: estimateQuotaForecast(nextState, window, now, context)
16956
- }))
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
+ })
16957
17630
  };
16958
17631
  });
16959
17632
  return {
@@ -17038,6 +17711,21 @@ function createQuotaForecastReader({ reader, enabled, now = Date.now, scope = ()
17038
17711
  const DEFAULT_MAX_BYTES = 256 * 1024;
17039
17712
  const MAX_WINDOWS = 128;
17040
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
+ }
17041
17729
  function sanitize(value) {
17042
17730
  if (value === null || typeof value !== "object" || Array.isArray(value) || value.windows === null || typeof value.windows !== "object" || Array.isArray(value.windows)) return void 0;
17043
17731
  const entries = Object.entries(value.windows);
@@ -17060,10 +17748,12 @@ function sanitize(value) {
17060
17748
  }
17061
17749
  const epochStart = record.epochStart;
17062
17750
  if (epochStart !== void 0 && !Number.isFinite(epochStart)) return void 0;
17751
+ const risk = sanitizeRisk(record.risk);
17063
17752
  windows[key] = {
17064
17753
  resetsAt,
17065
17754
  ...epochStart === void 0 ? {} : { epochStart },
17066
- samples
17755
+ samples,
17756
+ ...risk ? { risk } : {}
17067
17757
  };
17068
17758
  }
17069
17759
  return { windows };
@@ -17698,6 +18388,11 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
17698
18388
  let liveSynced = true;
17699
18389
  if (endpoint === "preferences/update") {
17700
18390
  patch = capabilityPatch(payload);
18391
+ if (Object.hasOwn(payload ?? {}, "customInstructions")) {
18392
+ const instructions = payload[CUSTOM_INSTRUCTIONS_FIELD];
18393
+ if (typeof instructions !== "string" || instructions.length > 1500) return publicError("internal", "Invalid custom instructions preference");
18394
+ patch[CUSTOM_INSTRUCTIONS_FIELD] = instructions;
18395
+ }
17701
18396
  if (Object.hasOwn(payload ?? {}, "disabledModels")) {
17702
18397
  const disabled = payload[DISABLED_MODELS_FIELD];
17703
18398
  if (!Array.isArray(disabled) || disabled.length > 100 || disabled.length !== normalizeDisabledModels(disabled).length) return publicError("internal", "Invalid disabled models preference");
@@ -18999,6 +19694,7 @@ const settingsFields = {
18999
19694
  webFetchFallbackProvider: z.string(),
19000
19695
  [DISABLED_MODELS_FIELD]: z.transform(z.array(z.string()).max(100), normalizeDisabledModels).default([]),
19001
19696
  [AUTO_QUOTA_RETRY_FIELD]: z.boolean().default(false),
19697
+ [CUSTOM_INSTRUCTIONS_FIELD]: z.string().max(CUSTOM_INSTRUCTIONS_LIMIT).default(""),
19002
19698
  subagentDefaultModel: z.transform(z.string().max(80), normalizeSubagentModel).default(""),
19003
19699
  ...Object.fromEntries(Object.entries(PREFERENCE_FIELDS).map(([field, rule]) => [field, rule.default === void 0 ? z.union(rule.choices) : z.union(rule.choices).default(rule.default)])),
19004
19700
  imageModel: z.union(Object.keys(IMAGE_MODELS)).default(DEFAULT_IMAGE_MODEL),
@@ -19134,6 +19830,7 @@ function apply(ctx, config = {}) {
19134
19830
  compaction,
19135
19831
  reasoning,
19136
19832
  resolveSpeedMode: () => settings.get()[SPEED_MODE_FIELD],
19833
+ resolveCustomInstructions: () => settings.get()[CUSTOM_INSTRUCTIONS_FIELD],
19137
19834
  resolveOutputVerbosity: () => normalizeOutputVerbosity(settings.get()[OUTPUT_VERBOSITY_FIELD]),
19138
19835
  resolveInputImageDetail: () => settings.get()[INPUT_IMAGE_DETAIL_FIELD],
19139
19836
  resolveReasoningSummary: () => settings.get()[REASONING_SUMMARY_FIELD],
@@ -19185,6 +19882,7 @@ function apply(ctx, config = {}) {
19185
19882
  fetchRoutingAvailable: fetchRouted,
19186
19883
  [SPEED_MODE_FIELD]: settings.get()[SPEED_MODE_FIELD],
19187
19884
  [SPEED_SHORTCUT_FIELD]: normalizeSpeedShortcut(settings.get()[SPEED_SHORTCUT_FIELD]),
19885
+ [CUSTOM_INSTRUCTIONS_FIELD]: settings.get()["customInstructions"] ?? "",
19188
19886
  [OUTPUT_VERBOSITY_FIELD]: normalizeOutputVerbosity(settings.get()[OUTPUT_VERBOSITY_FIELD]),
19189
19887
  [INPUT_IMAGE_DETAIL_FIELD]: normalizeInputImageDetail(settings.get()[INPUT_IMAGE_DETAIL_FIELD]),
19190
19888
  [REASONING_SUMMARY_FIELD]: normalizeReasoningSummary(settings.get()[REASONING_SUMMARY_FIELD]),