@keystrokehq/keystroke 0.1.76 → 0.1.79

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.
@@ -272,7 +272,65 @@ function resolveThinkingLevel(level) {
272
272
  return level ?? "medium";
273
273
  }
274
274
  //#endregion
275
- //#region ../agent/dist/context-compaction-B2veGznA.mjs
275
+ //#region ../agent/dist/context-compaction-Bxp4WK2B.mjs
276
+ /** Map every `FileUIPart` in each message, leaving other parts and non-array messages untouched. */
277
+ async function mapMessageFileParts(messages, mapFilePart) {
278
+ return Promise.all(messages.map(async (message) => {
279
+ if (!Array.isArray(message.parts)) return message;
280
+ const parts = await Promise.all(message.parts.map((part) => require_dist$1.isFileUIPart(part) ? mapFilePart(part) : part));
281
+ return {
282
+ ...message,
283
+ parts
284
+ };
285
+ }));
286
+ }
287
+ /**
288
+ * Approximate model-token cost of one image attachment. Vision pricing is
289
+ * tile-based (provider-dependent, roughly 750–1,600 tokens for a typical
290
+ * photo), not proportional to serialized bytes — a flat per-image charge is
291
+ * closer to reality than counting base64 chars.
292
+ */
293
+ const APPROX_ATTACHMENT_IMAGE_TOKENS = 1100;
294
+ /**
295
+ * Approximate model-token cost of one non-image attachment (PDFs). Page count
296
+ * is unknown without downloading, so this assumes a short document; a giant
297
+ * PDF under-counts, but the estimate only steers the compaction heuristic.
298
+ */
299
+ const APPROX_ATTACHMENT_FILE_TOKENS = 3e3;
300
+ function isUnhydratedAttachment(part) {
301
+ return require_dist.parseChatAttachmentServePath(part.url) !== null;
302
+ }
303
+ /**
304
+ * Replace unhydrated chat-attachment file parts (relative serve paths) with
305
+ * text placeholders so the messages survive `convertToModelMessages` — the AI
306
+ * SDK's `new URL(part.url)` throws `TypeError: Invalid URL` on relative paths.
307
+ *
308
+ * For estimation and compaction only: the placeholder tells the compaction
309
+ * model an attachment existed, and the real model call hydrates the actual
310
+ * bytes via `hydrateChatAttachmentMessages` instead.
311
+ */
312
+ function placeholderChatAttachmentMessages(messages) {
313
+ return mapMessageFileParts(messages, (part) => isUnhydratedAttachment(part) ? {
314
+ type: "text",
315
+ text: `[attachment: ${part.filename?.trim() || "file"} (${part.mediaType})]`
316
+ } : part);
317
+ }
318
+ /**
319
+ * Estimated token cost of the unhydrated attachments in `messages`, to add on
320
+ * top of a char-based serialized estimate (which only sees the placeholder
321
+ * text, not what the attachment will cost once hydrated for the model).
322
+ */
323
+ function estimateChatAttachmentTokens(messages) {
324
+ let total = 0;
325
+ for (const message of messages) {
326
+ if (!Array.isArray(message.parts)) continue;
327
+ for (const part of message.parts) {
328
+ if (!require_dist$1.isFileUIPart(part) || !isUnhydratedAttachment(part)) continue;
329
+ total += part.mediaType.startsWith("image/") ? APPROX_ATTACHMENT_IMAGE_TOKENS : APPROX_ATTACHMENT_FILE_TOKENS;
330
+ }
331
+ }
332
+ return total;
333
+ }
276
334
  /** Soft compaction trigger as a fraction of the usable input budget. */
277
335
  const CONTEXT_COMPACTION_SOFT_RATIO = .9;
278
336
  /**
@@ -287,7 +345,11 @@ const MIN_OUTPUT_RESERVE = 4096;
287
345
  const MAX_OUTPUT_RESERVE = 32768;
288
346
  /** Extra framing/tool-schema overhead beyond the output reservation. */
289
347
  const SAFETY_RESERVE = 2048;
290
- /** Conservative chars-per-token floor when no calibration sample exists. */
348
+ /**
349
+ * Conservative fixed chars-per-token ratio. Anchored estimates only apply it
350
+ * to the delta since the last real `input_tokens`, so a systematic error here
351
+ * is bounded by one step's new content, not the whole transcript.
352
+ */
291
353
  const DEFAULT_CHARS_PER_TOKEN = 3.5;
292
354
  /**
293
355
  * Derive the usable input budget from gateway context metadata.
@@ -318,15 +380,65 @@ function estimateSerializedChars(input) {
318
380
  if (input.tools !== void 0) total += JSON.stringify(input.tools).length;
319
381
  return total;
320
382
  }
383
+ const DATA_URL_MEDIA_MIN_CHARS = 4096;
384
+ function approxMediaTokens(mediaType) {
385
+ return typeof mediaType === "string" && mediaType.startsWith("image/") ? APPROX_ATTACHMENT_IMAGE_TOKENS : APPROX_ATTACHMENT_FILE_TOKENS;
386
+ }
321
387
  /**
322
- * Per-prompt tracker: calibrates a chars→tokens ratio from actual step usage,
323
- * then estimates the next request before it is sent.
388
+ * Serialized message size with media content measured as flat token estimates
389
+ * instead of chars. Vision/file pricing is tile- or page-based — counting a
390
+ * 4 MB image's ~5.3M base64 chars would estimate ~1.5M tokens for what the
391
+ * provider bills as ~1,100, wrongly triggering compaction on any large image.
392
+ */
393
+ function measureMessagesForBudget(messages) {
394
+ let mediaTokens = 0;
395
+ return {
396
+ chars: JSON.stringify(messages, (_key, value) => {
397
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
398
+ mediaTokens += 3e3;
399
+ return "[media]";
400
+ }
401
+ if (typeof value === "object" && value !== null) {
402
+ const part = value;
403
+ if (part.type === "image" && part.image !== void 0) {
404
+ mediaTokens += 1100;
405
+ return {
406
+ type: "image",
407
+ omitted: true
408
+ };
409
+ }
410
+ if ((part.type === "file" || part.type === "media") && part.data !== void 0) {
411
+ mediaTokens += approxMediaTokens(part.mediaType);
412
+ return {
413
+ type: part.type,
414
+ omitted: true
415
+ };
416
+ }
417
+ if (part.type === "Buffer" && Array.isArray(part.data)) {
418
+ mediaTokens += 3e3;
419
+ return "[media]";
420
+ }
421
+ }
422
+ if (typeof value === "string" && value.length >= DATA_URL_MEDIA_MIN_CHARS && value.startsWith("data:")) {
423
+ mediaTokens += value.startsWith("data:image/") ? 1100 : 3e3;
424
+ return "[media]";
425
+ }
426
+ return value;
427
+ })?.length ?? 0,
428
+ mediaTokens
429
+ };
430
+ }
431
+ /**
432
+ * Per-prompt tracker: anchors on the last real `input_tokens` and estimates
433
+ * only the delta (new content since that request), so estimation error is
434
+ * bounded by one step's new content instead of the whole transcript. Before
435
+ * the first completed step it falls back to a full char scan with media
436
+ * priced at flat token constants.
324
437
  */
325
438
  var ContextBudgetTracker = class {
326
439
  budget;
327
- charsPerToken = DEFAULT_CHARS_PER_TOKEN;
328
- lastActualInputTokens;
329
- lastEstimatedChars;
440
+ anchor;
441
+ lastMeasure;
330
442
  constructor(budget) {
331
443
  this.budget = budget;
332
444
  }
@@ -334,43 +446,52 @@ var ContextBudgetTracker = class {
334
446
  return this.budget;
335
447
  }
336
448
  get lastInputTokens() {
337
- return this.lastActualInputTokens;
449
+ return this.anchor?.inputTokens;
338
450
  }
339
451
  /**
340
- * Update calibration from a completed primary-model step's input token
341
- * count. Pairs it with the serialized size measured by the estimate that
342
- * preceded the request (or an explicit `serializedChars`), so the ratio
343
- * describes the same payload the provider tokenized.
452
+ * Anchor on a completed primary-model step's input token count, paired with
453
+ * the measure taken by the estimate that preceded that request future
454
+ * estimates price only content added after this point.
344
455
  */
345
- recordStepUsage(inputTokens, serializedChars) {
346
- const chars = serializedChars ?? this.lastEstimatedChars;
347
- if (inputTokens > 0 && chars !== void 0 && chars > 0) {
348
- const sample = chars / inputTokens;
349
- this.charsPerToken = this.charsPerToken * .35 + sample * .65;
350
- }
351
- this.lastActualInputTokens = inputTokens > 0 ? inputTokens : this.lastActualInputTokens;
456
+ recordStepUsage(inputTokens) {
457
+ if (inputTokens > 0 && this.lastMeasure) this.anchor = {
458
+ inputTokens,
459
+ ...this.lastMeasure
460
+ };
352
461
  }
353
- /** Reset after a successful compaction so the next estimate starts fresh. */
462
+ /** Reset after a successful compaction: the transcript the anchor priced no longer exists. */
354
463
  resetAfterCompaction() {
355
- this.lastActualInputTokens = void 0;
356
- this.lastEstimatedChars = void 0;
357
- this.charsPerToken = DEFAULT_CHARS_PER_TOKEN;
464
+ this.anchor = void 0;
465
+ this.lastMeasure = void 0;
358
466
  }
359
467
  estimate(input) {
360
468
  if (!this.budget) return null;
361
- const messageChars = estimateSerializedChars({ messages: input.messages });
469
+ const measure = measureMessagesForBudget(input.messages);
362
470
  const overheadChars = input.overheadChars ?? estimateSerializedChars({
363
471
  systemPrompt: input.systemPrompt,
364
472
  tools: input.tools
365
473
  });
366
- this.lastEstimatedChars = overheadChars + messageChars;
367
- const toTokens = (chars) => Math.max(Math.ceil(chars / this.charsPerToken), Math.ceil(chars / 4));
368
- const estimatedInputTokens = toTokens(overheadChars + messageChars);
369
- const estimatedMessageTokens = toTokens(messageChars);
474
+ const mediaTokens = measure.mediaTokens + (input.extraMessageTokens ?? 0);
475
+ this.lastMeasure = {
476
+ chars: measure.chars,
477
+ mediaTokens
478
+ };
479
+ const toTokens = (chars) => Math.ceil(chars / DEFAULT_CHARS_PER_TOKEN);
480
+ let estimatedInputTokens;
481
+ let estimatedMessageTokens;
482
+ if (this.anchor) {
483
+ const deltaTokens = toTokens(Math.max(0, measure.chars - this.anchor.chars)) + Math.max(0, mediaTokens - this.anchor.mediaTokens);
484
+ estimatedInputTokens = this.anchor.inputTokens + deltaTokens;
485
+ estimatedMessageTokens = Math.max(deltaTokens, estimatedInputTokens - toTokens(overheadChars));
486
+ } else {
487
+ estimatedInputTokens = toTokens(overheadChars + measure.chars) + mediaTokens;
488
+ estimatedMessageTokens = toTokens(measure.chars) + mediaTokens;
489
+ }
490
+ const decision = estimatedInputTokens >= this.budget.softLimit && estimatedMessageTokens > Math.floor(this.budget.softLimit * .5) ? "compact" : "allow";
370
491
  return {
371
492
  estimatedInputTokens,
372
493
  estimatedMessageTokens,
373
- decision: estimatedInputTokens >= this.budget.softLimit && estimatedMessageTokens > Math.floor(this.budget.softLimit * .5) ? "compact" : "allow",
494
+ decision,
374
495
  budget: this.budget
375
496
  };
376
497
  }
@@ -745,6 +866,12 @@ Object.defineProperty(exports, "currentLlmRunContext", {
745
866
  return currentLlmRunContext;
746
867
  }
747
868
  });
869
+ Object.defineProperty(exports, "estimateChatAttachmentTokens", {
870
+ enumerable: true,
871
+ get: function() {
872
+ return estimateChatAttachmentTokens;
873
+ }
874
+ });
748
875
  Object.defineProperty(exports, "estimateSerializedChars", {
749
876
  enumerable: true,
750
877
  get: function() {
@@ -757,6 +884,12 @@ Object.defineProperty(exports, "llmUsageFromLanguageModelUsage", {
757
884
  return llmUsageFromLanguageModelUsage;
758
885
  }
759
886
  });
887
+ Object.defineProperty(exports, "mapMessageFileParts", {
888
+ enumerable: true,
889
+ get: function() {
890
+ return mapMessageFileParts;
891
+ }
892
+ });
760
893
  Object.defineProperty(exports, "parseAgentCreateInput", {
761
894
  enumerable: true,
762
895
  get: function() {
@@ -769,6 +902,12 @@ Object.defineProperty(exports, "parseContextCompactionCheckpoint", {
769
902
  return parseContextCompactionCheckpoint;
770
903
  }
771
904
  });
905
+ Object.defineProperty(exports, "placeholderChatAttachmentMessages", {
906
+ enumerable: true,
907
+ get: function() {
908
+ return placeholderChatAttachmentMessages;
909
+ }
910
+ });
772
911
  Object.defineProperty(exports, "rebuildMessagesFromCheckpoint", {
773
912
  enumerable: true,
774
913
  get: function() {
@@ -824,4 +963,4 @@ Object.defineProperty(exports, "withLlmRunContext", {
824
963
  }
825
964
  });
826
965
 
827
- //# sourceMappingURL=context-compaction-B2veGznA-BNxANwjo.cjs.map
966
+ //# sourceMappingURL=context-compaction-Bxp4WK2B-CWLdNWoS.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-compaction-Bxp4WK2B-CWLdNWoS.cjs","names":["AsyncLocalStorage","LLM_RUN_ID_HEADER","LLM_RUN_KIND_HEADER","LLM_SKIP_USAGE_HEADER","getProjectScopeId","createGateway","z","isFileUIPart","parseChatAttachmentServePath","LLM_KEY_SOURCE_HEADER","generateText","generateId"],"sources":["../../agent/dist/schemas-DDyTkszQ.mjs","../../agent/dist/context-compaction-Bxp4WK2B.mjs"],"sourcesContent":["import { LLM_RUN_ID_HEADER, LLM_RUN_KIND_HEADER, LLM_SKIP_USAGE_HEADER, modelSupportsMediaType } from \"@keystrokehq/shared\";\nimport { z } from \"zod\";\nimport { getProjectScopeId } from \"@keystrokehq/database\";\nimport { createGateway } from \"@ai-sdk/gateway\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n//#region src/define/model-capabilities.ts\nfunction capabilitiesFromGatewayTags(tags) {\n\tconst set = new Set(tags ?? []);\n\treturn {\n\t\timages: set.has(\"vision\"),\n\t\tfiles: set.has(\"file-input\")\n\t};\n}\nfunction attachmentPlaceholderText(filename, mediaType) {\n\treturn `[attachment omitted: ${filename?.trim() || mediaType} — model has no ${mediaType.startsWith(\"image/\") ? \"image\" : \"file\"} support]`;\n}\n//#endregion\n//#region src/ai/run-context.ts\nconst storage = new AsyncLocalStorage();\n/**\n* Best-effort run attribution for LLM proxy traffic. The gateway client reads\n* this to stamp run headers on each request so the platform can tag the usage\n* it records to a run. Billing never depends on it — losing the context only\n* drops the history-UI attribution.\n*/\nfunction withLlmRunContext(context, fn) {\n\treturn storage.run(context, fn);\n}\nfunction currentLlmRunContext() {\n\treturn storage.getStore();\n}\n//#endregion\n//#region src/ai/gateway-client.ts\nconst DEFAULT_GATEWAY_ORIGIN = \"https://ai-gateway.vercel.sh\";\n/**\n* Wrap `fetch` so every gateway request carries the current run's attribution\n* headers. Read at call time (not client-construction time) so the cached\n* singleton client still tags each request with its own run.\n*/\nconst runContextFetch = (input, init) => {\n\tconst run = currentLlmRunContext();\n\tif (!run) return fetch(input, init);\n\tconst headers = new Headers(init?.headers);\n\theaders.set(LLM_RUN_ID_HEADER, run.runId);\n\theaders.set(LLM_RUN_KIND_HEADER, run.runKind);\n\tif (run.skipUsage) headers.set(LLM_SKIP_USAGE_HEADER, \"1\");\n\treturn fetch(input, {\n\t\t...init,\n\t\theaders\n\t});\n};\n/** Resolve the model catalog URL for pricing metadata (via platform proxy when configured). */\nfunction resolveGatewayCatalogUrl(modelId) {\n\tconst baseUrl = resolveGatewayBaseUrl();\n\tconst apiKey = process.env.AI_GATEWAY_API_KEY?.trim();\n\tif (baseUrl && apiKey) return {\n\t\turl: `${baseUrl.replace(/\\/$/, \"\")}/models/${modelId}`,\n\t\theaders: {\n\t\t\taccept: \"application/json\",\n\t\t\tauthorization: `Bearer ${apiKey}`\n\t\t},\n\t\tcacheKey: baseUrl\n\t};\n\treturn {\n\t\turl: `${DEFAULT_GATEWAY_ORIGIN}/v1/models/${modelId}`,\n\t\theaders: { accept: \"application/json\" },\n\t\tcacheKey: DEFAULT_GATEWAY_ORIGIN\n\t};\n}\nlet cachedGateway;\nfunction resolveGatewayBaseUrl() {\n\tconst configured = process.env.AI_GATEWAY_BASE_URL?.trim();\n\tif (configured) return configured.replace(/\\/$/, \"\");\n\tconst platformUrl = process.env.PLATFORM_URL?.trim();\n\tif (!platformUrl || !process.env.AI_GATEWAY_API_KEY?.trim()) return;\n\tconst projectId = getProjectScopeId();\n\treturn `${platformUrl.replace(/\\/$/, \"\")}/internal/projects/${encodeURIComponent(projectId)}/llm`;\n}\n/** Shared AI Gateway client honoring keystroke env conventions. */\nfunction getGatewayClient(baseUrl) {\n\tconst resolvedBaseUrl = baseUrl ?? resolveGatewayBaseUrl();\n\tconst cacheKey = resolvedBaseUrl ?? DEFAULT_GATEWAY_ORIGIN;\n\tif (cachedGateway && cachedGateway.__baseUrl === cacheKey) return cachedGateway;\n\tconst apiKey = process.env.AI_GATEWAY_API_KEY?.trim();\n\tconst gateway = createGateway({\n\t\t...resolvedBaseUrl ? { baseURL: resolvedBaseUrl } : {},\n\t\t...apiKey ? { apiKey } : {},\n\t\tfetch: runContextFetch\n\t});\n\tgateway.__baseUrl = cacheKey;\n\tcachedGateway = gateway;\n\treturn gateway;\n}\n//#endregion\n//#region src/define/resolve-agent-model.ts\nconst AGENT_MODEL_ID_PATTERN = /^[a-z0-9-]+\\/.+/;\nconst AgentModelIdSchema = z.custom((value) => typeof value === \"string\" && AGENT_MODEL_ID_PATTERN.test(value), \"model must be vendor/model-id\");\nconst GatewayModelPricingSchema = z.object({\n\tinput: z.string().optional(),\n\toutput: z.string().optional(),\n\tinput_cache_read: z.string().optional(),\n\tinput_cache_write: z.string().optional()\n});\nconst GatewayModelResponseSchema = z.object({\n\tid: z.string().min(1),\n\tname: z.string().optional(),\n\ttype: z.string().optional(),\n\tcontext_window: z.number().int().positive().optional(),\n\tmax_tokens: z.number().int().positive().optional(),\n\ttags: z.array(z.string()).optional(),\n\tpricing: GatewayModelPricingSchema.optional()\n});\nfunction splitAgentModelId(modelId) {\n\tconst slash = modelId.indexOf(\"/\");\n\treturn {\n\t\tvendor: modelId.slice(0, slash),\n\t\tdirectId: modelId.slice(slash + 1)\n\t};\n}\nfunction parseGatewayModelResponse(body) {\n\tconst parsed = GatewayModelResponseSchema.safeParse(body);\n\treturn parsed.success ? parsed.data : void 0;\n}\nfunction pricePerMillion(value) {\n\tif (!value) return 0;\n\tconst perToken = Number(value);\n\tif (!Number.isFinite(perToken) || perToken <= 0) return 0;\n\treturn perToken * 1e6;\n}\nconst gatewayModelCache = /* @__PURE__ */ new Map();\nconst gatewayModelPending = /* @__PURE__ */ new Map();\nfunction gatewayModelCacheKey(modelId, catalog) {\n\treturn `${catalog.cacheKey}::${modelId}`;\n}\nfunction catalogLogContext(modelId, catalog) {\n\treturn {\n\t\tmodelId,\n\t\turl: catalog.url,\n\t\tprojectScopeId: getProjectScopeId(),\n\t\tcacheKey: gatewayModelCacheKey(modelId, catalog)\n\t};\n}\nfunction snippet(value, max = 400) {\n\tconst trimmed = value.trim();\n\treturn trimmed.length <= max ? trimmed : `${trimmed.slice(0, max)}…`;\n}\nasync function fetchGatewayModelMetadata(modelId) {\n\tconst catalog = resolveGatewayCatalogUrl(modelId);\n\tconst cacheKey = gatewayModelCacheKey(modelId, catalog);\n\tconst cached = gatewayModelCache.get(cacheKey);\n\tif (cached) {\n\t\tif (cached.status === \"found\") {\n\t\t\tconst { status: _status, ...metadata } = cached;\n\t\t\treturn metadata;\n\t\t}\n\t\tconsole.warn(\"[gateway-model] catalog lookup cache miss (missing)\", catalogLogContext(modelId, catalog));\n\t\treturn;\n\t}\n\tconst pending = gatewayModelPending.get(cacheKey);\n\tif (pending) return pending;\n\tconst request = (async () => {\n\t\ttry {\n\t\t\tconst response = await fetch(catalog.url, { headers: catalog.headers });\n\t\t\tif (!response.ok) {\n\t\t\t\tconst body = await response.text().catch(() => \"\");\n\t\t\t\tconsole.warn(\"[gateway-model] catalog HTTP error\", {\n\t\t\t\t\t...catalogLogContext(modelId, catalog),\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\tstatusText: response.statusText,\n\t\t\t\t\tbody: snippet(body)\n\t\t\t\t});\n\t\t\t\tgatewayModelCache.set(cacheKey, { status: \"missing\" });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst body = await response.json();\n\t\t\tconst raw = parseGatewayModelResponse(body);\n\t\t\tif (!raw || raw.type && raw.type !== \"language\") {\n\t\t\t\tconsole.warn(\"[gateway-model] catalog payload rejected\", {\n\t\t\t\t\t...catalogLogContext(modelId, catalog),\n\t\t\t\t\ttype: raw?.type,\n\t\t\t\t\tbody: snippet(JSON.stringify(body))\n\t\t\t\t});\n\t\t\t\tgatewayModelCache.set(cacheKey, { status: \"missing\" });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst capabilities = capabilitiesFromGatewayTags(raw.tags);\n\t\t\tconst metadata = {\n\t\t\t\tpricing: {\n\t\t\t\t\tinputPerMillion: pricePerMillion(raw.pricing?.input),\n\t\t\t\t\toutputPerMillion: pricePerMillion(raw.pricing?.output),\n\t\t\t\t\tcacheReadPerMillion: pricePerMillion(raw.pricing?.input_cache_read),\n\t\t\t\t\tcacheWritePerMillion: pricePerMillion(raw.pricing?.input_cache_write)\n\t\t\t\t},\n\t\t\t\tcapabilities,\n\t\t\t\t...raw.context_window !== void 0 ? { contextWindow: raw.context_window } : {},\n\t\t\t\t...raw.max_tokens !== void 0 ? { maxOutputTokens: raw.max_tokens } : {}\n\t\t\t};\n\t\t\tgatewayModelCache.set(cacheKey, {\n\t\t\t\tstatus: \"found\",\n\t\t\t\t...metadata\n\t\t\t});\n\t\t\treturn metadata;\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"[gateway-model] catalog fetch failed\", {\n\t\t\t\t...catalogLogContext(modelId, catalog),\n\t\t\t\terror: error instanceof Error ? error.message : String(error)\n\t\t\t});\n\t\t\tgatewayModelCache.set(cacheKey, { status: \"missing\" });\n\t\t\treturn;\n\t\t} finally {\n\t\t\tgatewayModelPending.delete(cacheKey);\n\t\t}\n\t})();\n\tgatewayModelPending.set(cacheKey, request);\n\treturn request;\n}\n/** Cached gateway catalog lookup for model multimodal capabilities. */\nasync function resolveModelCapabilities(modelId) {\n\treturn (await fetchGatewayModelMetadata(modelId))?.capabilities ?? {\n\t\timages: false,\n\t\tfiles: false\n\t};\n}\n/** Resolve a user-authored model id to an AI Gateway language model + optional pricing metadata. */\nasync function resolveAgentModel(modelId) {\n\tconst baseUrl = resolveGatewayBaseUrl();\n\tconst gateway = getGatewayClient(baseUrl);\n\tconst metadata = await fetchGatewayModelMetadata(modelId);\n\tconst pricing = metadata?.pricing;\n\tconst capabilities = metadata?.capabilities ?? {\n\t\timages: false,\n\t\tfiles: false\n\t};\n\tif (pricing === void 0) {\n\t\tconst catalog = resolveGatewayCatalogUrl(modelId);\n\t\tif (gatewayModelCache.get(gatewayModelCacheKey(modelId, catalog))?.status === \"missing\" && process.env.AI_GATEWAY_API_KEY?.trim()) {\n\t\t\tconsole.warn(\"[gateway-model] rejecting model after catalog miss\", catalogLogContext(modelId, catalog));\n\t\t\tthrow new Error(`Unknown gateway model: ${modelId}`);\n\t\t}\n\t}\n\treturn {\n\t\tlanguageModel: gateway(modelId),\n\t\tmodelId,\n\t\tprovider: \"vercel-ai-gateway\",\n\t\tcapabilities,\n\t\t...baseUrl ? { baseUrl } : {},\n\t\t...pricing ? { pricing } : {},\n\t\t...metadata?.contextWindow !== void 0 ? { contextWindow: metadata.contextWindow } : {},\n\t\t...metadata?.maxOutputTokens !== void 0 ? { maxOutputTokens: metadata.maxOutputTokens } : {}\n\t};\n}\n//#endregion\n//#region src/schemas.ts\nconst ThinkingLevelSchema = z.enum([\n\t\"provider-default\",\n\t\"none\",\n\t\"minimal\",\n\t\"low\",\n\t\"medium\",\n\t\"high\",\n\t\"xhigh\"\n]);\nconst DEFAULT_THINKING_LEVEL = \"medium\";\n/** Default model for automatic context compaction when `compactionModel` is omitted. */\nconst DEFAULT_COMPACTION_MODEL_ID = \"deepseek/deepseek-v4-flash\";\n/** Serializable subset of {@link AgentConfig} for JSON/env/CLI boundaries. */\nconst AgentCreateInputSchema = z.object({\n\tsystemPrompt: z.string(),\n\tmodel: AgentModelIdSchema,\n\t/**\n\t* Optional model used only for context compaction. Same `vendor/model-id` form as\n\t* `model`. When omitted, Keystroke uses {@link DEFAULT_COMPACTION_MODEL_ID}.\n\t*/\n\tcompactionModel: AgentModelIdSchema.optional(),\n\tthinkingLevel: ThinkingLevelSchema.optional()\n});\nfunction parseAgentCreateInput(input) {\n\treturn AgentCreateInputSchema.parse(input);\n}\nfunction resolveThinkingLevel(level) {\n\treturn level ?? \"medium\";\n}\n//#endregion\nexport { parseAgentCreateInput as a, resolveAgentModel as c, currentLlmRunContext as d, withLlmRunContext as f, ThinkingLevelSchema as i, resolveModelCapabilities as l, modelSupportsMediaType as m, DEFAULT_COMPACTION_MODEL_ID as n, resolveThinkingLevel as o, attachmentPlaceholderText as p, DEFAULT_THINKING_LEVEL as r, AgentModelIdSchema as s, AgentCreateInputSchema as t, splitAgentModelId as u };\n\n//# sourceMappingURL=schemas-DDyTkszQ.mjs.map","import { c as resolveAgentModel, u as splitAgentModelId } from \"./schemas-DDyTkszQ.mjs\";\nimport { generateId, generateText, isFileUIPart } from \"ai\";\nimport { LLM_KEY_SOURCE_HEADER, parseChatAttachmentServePath } from \"@keystrokehq/shared\";\n//#region src/ai/map-message-file-parts.ts\n/** Map every `FileUIPart` in each message, leaving other parts and non-array messages untouched. */\nasync function mapMessageFileParts(messages, mapFilePart) {\n\treturn Promise.all(messages.map(async (message) => {\n\t\tif (!Array.isArray(message.parts)) return message;\n\t\tconst parts = await Promise.all(message.parts.map((part) => isFileUIPart(part) ? mapFilePart(part) : part));\n\t\treturn {\n\t\t\t...message,\n\t\t\tparts\n\t\t};\n\t}));\n}\n//#endregion\n//#region src/ai/placeholder-chat-attachment-messages.ts\n/**\n* Approximate model-token cost of one image attachment. Vision pricing is\n* tile-based (provider-dependent, roughly 750–1,600 tokens for a typical\n* photo), not proportional to serialized bytes — a flat per-image charge is\n* closer to reality than counting base64 chars.\n*/\nconst APPROX_ATTACHMENT_IMAGE_TOKENS = 1100;\n/**\n* Approximate model-token cost of one non-image attachment (PDFs). Page count\n* is unknown without downloading, so this assumes a short document; a giant\n* PDF under-counts, but the estimate only steers the compaction heuristic.\n*/\nconst APPROX_ATTACHMENT_FILE_TOKENS = 3e3;\nfunction isUnhydratedAttachment(part) {\n\treturn parseChatAttachmentServePath(part.url) !== null;\n}\n/**\n* Replace unhydrated chat-attachment file parts (relative serve paths) with\n* text placeholders so the messages survive `convertToModelMessages` — the AI\n* SDK's `new URL(part.url)` throws `TypeError: Invalid URL` on relative paths.\n*\n* For estimation and compaction only: the placeholder tells the compaction\n* model an attachment existed, and the real model call hydrates the actual\n* bytes via `hydrateChatAttachmentMessages` instead.\n*/\nfunction placeholderChatAttachmentMessages(messages) {\n\treturn mapMessageFileParts(messages, (part) => isUnhydratedAttachment(part) ? {\n\t\ttype: \"text\",\n\t\ttext: `[attachment: ${part.filename?.trim() || \"file\"} (${part.mediaType})]`\n\t} : part);\n}\n/**\n* Estimated token cost of the unhydrated attachments in `messages`, to add on\n* top of a char-based serialized estimate (which only sees the placeholder\n* text, not what the attachment will cost once hydrated for the model).\n*/\nfunction estimateChatAttachmentTokens(messages) {\n\tlet total = 0;\n\tfor (const message of messages) {\n\t\tif (!Array.isArray(message.parts)) continue;\n\t\tfor (const part of message.parts) {\n\t\t\tif (!isFileUIPart(part) || !isUnhydratedAttachment(part)) continue;\n\t\t\ttotal += part.mediaType.startsWith(\"image/\") ? APPROX_ATTACHMENT_IMAGE_TOKENS : APPROX_ATTACHMENT_FILE_TOKENS;\n\t\t}\n\t}\n\treturn total;\n}\n//#endregion\n//#region src/ai/context-budget.ts\n/** Soft compaction trigger as a fraction of the usable input budget. */\nconst CONTEXT_COMPACTION_SOFT_RATIO = .9;\n/**\n* Fraction of the soft limit the retained raw tail may occupy after a\n* compaction. The remainder is headroom for the summary, system prompt, and\n* tool schemas.\n*/\nconst COMPACTION_TAIL_BUDGET_RATIO = .4;\n/** Floor for reserved output + framing tokens. */\nconst MIN_OUTPUT_RESERVE = 4096;\n/** Cap so million-token models are not compacted prematurely. */\nconst MAX_OUTPUT_RESERVE = 32768;\n/** Extra framing/tool-schema overhead beyond the output reservation. */\nconst SAFETY_RESERVE = 2048;\n/**\n* Conservative fixed chars-per-token ratio. Anchored estimates only apply it\n* to the delta since the last real `input_tokens`, so a systematic error here\n* is bounded by one step's new content, not the whole transcript.\n*/\nconst DEFAULT_CHARS_PER_TOKEN = 3.5;\n/**\n* Derive the usable input budget from gateway context metadata.\n* Returns null when the model has no known context window — auto-compaction is disabled.\n*/\nfunction resolveContextBudget(resolved) {\n\tconst contextWindow = resolved.contextWindow;\n\tif (contextWindow == null || contextWindow <= 0) return null;\n\tconst catalogMax = resolved.maxOutputTokens;\n\tconst proportional = Math.floor(contextWindow * .05);\n\tconst outputReserve = Math.min(MAX_OUTPUT_RESERVE, Math.max(MIN_OUTPUT_RESERVE, catalogMax ?? proportional, proportional));\n\tconst safetyReserve = Math.min(SAFETY_RESERVE, Math.floor(contextWindow * .01));\n\tconst inputBudget = Math.max(1, contextWindow - outputReserve - safetyReserve);\n\treturn {\n\t\tcontextWindow,\n\t\toutputReserve,\n\t\tsafetyReserve,\n\t\tinputBudget,\n\t\tsoftLimit: Math.floor(inputBudget * CONTEXT_COMPACTION_SOFT_RATIO),\n\t\thardLimit: inputBudget\n\t};\n}\n/** Rough serialized size used for preflight estimation (chars ≈ JSON length). */\nfunction estimateSerializedChars(input) {\n\tlet total = 0;\n\tif (input.systemPrompt) total += input.systemPrompt.length;\n\tif (input.messages !== void 0) total += JSON.stringify(input.messages).length;\n\tif (input.tools !== void 0) total += JSON.stringify(input.tools).length;\n\treturn total;\n}\nconst DATA_URL_MEDIA_MIN_CHARS = 4096;\nfunction approxMediaTokens(mediaType) {\n\treturn typeof mediaType === \"string\" && mediaType.startsWith(\"image/\") ? APPROX_ATTACHMENT_IMAGE_TOKENS : APPROX_ATTACHMENT_FILE_TOKENS;\n}\n/**\n* Serialized message size with media content measured as flat token estimates\n* instead of chars. Vision/file pricing is tile- or page-based — counting a\n* 4 MB image's ~5.3M base64 chars would estimate ~1.5M tokens for what the\n* provider bills as ~1,100, wrongly triggering compaction on any large image.\n*/\nfunction measureMessagesForBudget(messages) {\n\tlet mediaTokens = 0;\n\treturn {\n\t\tchars: JSON.stringify(messages, (_key, value) => {\n\t\t\tif (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n\t\t\t\tmediaTokens += 3e3;\n\t\t\t\treturn \"[media]\";\n\t\t\t}\n\t\t\tif (typeof value === \"object\" && value !== null) {\n\t\t\t\tconst part = value;\n\t\t\t\tif (part.type === \"image\" && part.image !== void 0) {\n\t\t\t\t\tmediaTokens += 1100;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"image\",\n\t\t\t\t\t\tomitted: true\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif ((part.type === \"file\" || part.type === \"media\") && part.data !== void 0) {\n\t\t\t\t\tmediaTokens += approxMediaTokens(part.mediaType);\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: part.type,\n\t\t\t\t\t\tomitted: true\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (part.type === \"Buffer\" && Array.isArray(part.data)) {\n\t\t\t\t\tmediaTokens += 3e3;\n\t\t\t\t\treturn \"[media]\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (typeof value === \"string\" && value.length >= DATA_URL_MEDIA_MIN_CHARS && value.startsWith(\"data:\")) {\n\t\t\t\tmediaTokens += value.startsWith(\"data:image/\") ? 1100 : 3e3;\n\t\t\t\treturn \"[media]\";\n\t\t\t}\n\t\t\treturn value;\n\t\t})?.length ?? 0,\n\t\tmediaTokens\n\t};\n}\n/**\n* Per-prompt tracker: anchors on the last real `input_tokens` and estimates\n* only the delta (new content since that request), so estimation error is\n* bounded by one step's new content instead of the whole transcript. Before\n* the first completed step it falls back to a full char scan with media\n* priced at flat token constants.\n*/\nvar ContextBudgetTracker = class {\n\tbudget;\n\tanchor;\n\tlastMeasure;\n\tconstructor(budget) {\n\t\tthis.budget = budget;\n\t}\n\tget contextBudget() {\n\t\treturn this.budget;\n\t}\n\tget lastInputTokens() {\n\t\treturn this.anchor?.inputTokens;\n\t}\n\t/**\n\t* Anchor on a completed primary-model step's input token count, paired with\n\t* the measure taken by the estimate that preceded that request — future\n\t* estimates price only content added after this point.\n\t*/\n\trecordStepUsage(inputTokens) {\n\t\tif (inputTokens > 0 && this.lastMeasure) this.anchor = {\n\t\t\tinputTokens,\n\t\t\t...this.lastMeasure\n\t\t};\n\t}\n\t/** Reset after a successful compaction: the transcript the anchor priced no longer exists. */\n\tresetAfterCompaction() {\n\t\tthis.anchor = void 0;\n\t\tthis.lastMeasure = void 0;\n\t}\n\testimate(input) {\n\t\tif (!this.budget) return null;\n\t\tconst measure = measureMessagesForBudget(input.messages);\n\t\tconst overheadChars = input.overheadChars ?? estimateSerializedChars({\n\t\t\tsystemPrompt: input.systemPrompt,\n\t\t\ttools: input.tools\n\t\t});\n\t\tconst mediaTokens = measure.mediaTokens + (input.extraMessageTokens ?? 0);\n\t\tthis.lastMeasure = {\n\t\t\tchars: measure.chars,\n\t\t\tmediaTokens\n\t\t};\n\t\tconst toTokens = (chars) => Math.ceil(chars / DEFAULT_CHARS_PER_TOKEN);\n\t\tlet estimatedInputTokens;\n\t\tlet estimatedMessageTokens;\n\t\tif (this.anchor) {\n\t\t\tconst deltaTokens = toTokens(Math.max(0, measure.chars - this.anchor.chars)) + Math.max(0, mediaTokens - this.anchor.mediaTokens);\n\t\t\testimatedInputTokens = this.anchor.inputTokens + deltaTokens;\n\t\t\testimatedMessageTokens = Math.max(deltaTokens, estimatedInputTokens - toTokens(overheadChars));\n\t\t} else {\n\t\t\testimatedInputTokens = toTokens(overheadChars + measure.chars) + mediaTokens;\n\t\t\testimatedMessageTokens = toTokens(measure.chars) + mediaTokens;\n\t\t}\n\t\tconst decision = estimatedInputTokens >= this.budget.softLimit && estimatedMessageTokens > Math.floor(this.budget.softLimit * .5) ? \"compact\" : \"allow\";\n\t\treturn {\n\t\t\testimatedInputTokens,\n\t\t\testimatedMessageTokens,\n\t\t\tdecision,\n\t\t\tbudget: this.budget\n\t\t};\n\t}\n};\n//#endregion\n//#region src/ai/usage.ts\n/**\n* Key source from the platform LLM proxy's response header. Undefined when the\n* request didn't go through the proxy (standalone / direct provider).\n*/\nfunction byokFromResponseHeaders(headers) {\n\tconst value = headers?.[LLM_KEY_SOURCE_HEADER];\n\tif (value === \"byok\") return true;\n\tif (value === \"platform\") return false;\n}\nfunction llmUsageFromLanguageModelUsage(usage, resolved, options) {\n\tconst input = usage.inputTokens ?? 0;\n\tconst output = usage.outputTokens ?? 0;\n\tconst reasoning = usage.outputTokenDetails.reasoningTokens ?? 0;\n\tconst cacheRead = usage.inputTokenDetails.cacheReadTokens ?? 0;\n\tconst cacheWrite = usage.inputTokenDetails.cacheWriteTokens ?? 0;\n\tconst noCache = usage.inputTokenDetails.noCacheTokens ?? Math.max(0, input - cacheRead - cacheWrite);\n\tconst totalTokens = usage.totalTokens ?? input + output;\n\tconst pricing = resolved.pricing;\n\tconst inputCost = pricing ? noCache / 1e6 * pricing.inputPerMillion : 0;\n\tconst outputCost = pricing ? output / 1e6 * pricing.outputPerMillion : 0;\n\tconst cacheReadCost = pricing ? cacheRead / 1e6 * pricing.cacheReadPerMillion : 0;\n\tconst cacheWriteCost = pricing ? cacheWrite / 1e6 * pricing.cacheWritePerMillion : 0;\n\tconst total = inputCost + outputCost + cacheReadCost + cacheWriteCost;\n\tconst { directId } = splitAgentModelId(resolved.modelId);\n\treturn {\n\t\tlabel: resolved.modelId,\n\t\tquantity: totalTokens,\n\t\tamount: total,\n\t\t...options?.byok !== void 0 ? { byok: options.byok } : {},\n\t\t...options?.stepRef ? { stepRef: options.stepRef } : {},\n\t\tmetadata: {\n\t\t\tprovider: resolved.provider,\n\t\t\tmodel: directId,\n\t\t\t...options?.byok !== void 0 ? { keySource: options.byok ? \"byok\" : \"platform\" } : {},\n\t\t\tresponseModel: resolved.modelId,\n\t\t\tinput,\n\t\t\tnoCache,\n\t\t\toutput,\n\t\t\treasoning,\n\t\t\tcacheRead,\n\t\t\tcacheWrite,\n\t\t\tcost: {\n\t\t\t\tnoCache: inputCost,\n\t\t\t\toutput: outputCost,\n\t\t\t\tcacheRead: cacheReadCost,\n\t\t\t\tcacheWrite: cacheWriteCost,\n\t\t\t\ttotal\n\t\t\t}\n\t\t}\n\t};\n}\n/** Soft char budget for one compaction-model request (chunk recursively above this). */\nconst COMPACTION_CHUNK_CHARS = 12e4;\nconst CONTEXT_COMPACTED_EVENT_TYPE = \"context_compacted\";\nfunction resolveCompactionModelId(explicit) {\n\treturn explicit ?? \"deepseek/deepseek-v4-flash\";\n}\nconst COMPACTION_SYSTEM_PROMPT = [\n\t\"You compress long agent conversation history into a compact context summary.\",\n\t\"Preserve durable facts, decisions, IDs, file paths, unresolved tasks, and recent tool outcomes.\",\n\t\"Omit chit-chat, repeated tool dumps, and superseded drafts.\",\n\t\"Write plain prose the primary agent can continue from. Do not call tools.\",\n\t\"Respond with ONLY the summary text.\"\n].join(\"\\n\");\nfunction messageTextPreview(message) {\n\tif (typeof message.content === \"string\") return message.content;\n\tif (!Array.isArray(message.content)) return JSON.stringify(message.content);\n\treturn message.content.map((part) => {\n\t\tif (typeof part === \"object\" && part !== null && \"type\" in part) {\n\t\t\tif (part.type === \"text\" && \"text\" in part) return String(part.text);\n\t\t\tif (part.type === \"tool-call\") return `[tool-call ${part.toolName ?? \"unknown\"}]`;\n\t\t\tif (part.type === \"tool-result\") return `[tool-result ${part.toolName ?? \"unknown\"}]`;\n\t\t}\n\t\treturn JSON.stringify(part);\n\t}).join(\"\\n\");\n}\nfunction formatMessagesForCompaction(messages) {\n\treturn messages.map((message, index) => {\n\t\tconst role = message.role;\n\t\treturn `### ${index + 1}. ${role}\\n${messageTextPreview(message)}`;\n\t}).join(\"\\n\\n\");\n}\n/**\n* Split off a recent raw tail. Prefer a user-turn boundary and never start the\n* tail on an orphaned tool result (keeps tool-call / tool-result pairs intact).\n*/\nfunction splitTail(messages, retain, options) {\n\tif (messages.length <= retain) return {\n\t\tprefix: [],\n\t\ttail: messages\n\t};\n\tlet start = messages.length - retain;\n\twhile (start > 0 && messages[start]?.role === \"tool\") start -= 1;\n\tif (options?.preferUserBoundary !== false) while (start > 0 && messages[start]?.role !== \"user\") start -= 1;\n\treturn {\n\t\tprefix: messages.slice(0, start),\n\t\ttail: messages.slice(start)\n\t};\n}\n/**\n* Fraction of the soft limit the retained raw tail may occupy. Kept below the\n* compaction trigger's messages-only floor so a just-compacted context can't\n* immediately re-trigger (see COMPACTION_MIN_MESSAGE_RATIO).\n*/\nconst TAIL_BUDGET_RATIO = COMPACTION_TAIL_BUDGET_RATIO;\n/**\n* Token allowance for the summary itself: capped at the summarizer's\n* maxOutputTokens, scaled down for small budgets (summaries track content\n* size, not the cap).\n*/\nfunction summaryReserveTokens(softLimit) {\n\treturn Math.min(4096, Math.ceil(softLimit * .1));\n}\n/**\n* Choose which messages to summarize vs keep raw. Starts from the requested\n* retained tail, then shrinks it while it exceeds the tail budget — down to\n* zero, so even a single oversized latest message gets summarized instead of\n* staying protected and blowing the context window.\n*/\nfunction resolveCompactionSplit(options) {\n\tconst { messages, budget } = options;\n\tlet retain = options.retainTail;\n\tlet split = splitTail(messages, retain);\n\tif (budget) {\n\t\tconst tailBudget = Math.max(1, Math.min(Math.floor(budget.softLimit * TAIL_BUDGET_RATIO), budget.softLimit - (options.overheadTokens ?? 0) - summaryReserveTokens(budget.softLimit)));\n\t\twhile (split.tail.length > 0 && estimateSerializedCharsApprox(split.tail) > tailBudget) {\n\t\t\tretain = Math.min(retain - 1, split.tail.length - 1);\n\t\t\tif (retain <= 0) {\n\t\t\t\tsplit = {\n\t\t\t\t\tprefix: messages,\n\t\t\t\t\ttail: []\n\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsplit = splitTail(messages, retain, { preferUserBoundary: false });\n\t\t}\n\t\treturn split;\n\t}\n\tif (split.prefix.length === 0 && !options.hasPriorSummary && split.tail.length > 0) return {\n\t\tprefix: messages,\n\t\ttail: []\n\t};\n\treturn split;\n}\nasync function summarizeChunk(resolved, text, priorSummary) {\n\tconst prompt = [\n\t\tpriorSummary ? `Prior summary:\\n${priorSummary}\\n` : \"\",\n\t\t\"Conversation to compress:\\n\",\n\t\ttext\n\t].filter(Boolean).join(\"\\n\");\n\tconst result = await generateText({\n\t\tmodel: resolved.languageModel,\n\t\tsystem: COMPACTION_SYSTEM_PROMPT,\n\t\tprompt,\n\t\tmaxOutputTokens: 4096,\n\t\treasoning: \"minimal\"\n\t});\n\tconst usage = llmUsageFromLanguageModelUsage(result.usage, resolved, {\n\t\tbyok: byokFromResponseHeaders(result.response?.headers),\n\t\tstepRef: `compaction:${generateId()}`\n\t});\n\tusage.label = `LLM compaction · ${resolved.modelId}`;\n\tusage.metadata = {\n\t\t...usage.metadata,\n\t\toperation: \"context_compaction\"\n\t};\n\treturn {\n\t\tsummary: result.text.trim() || priorSummary || \"(empty summary)\",\n\t\tusage\n\t};\n}\nasync function summarizeMessages(resolved, messages, priorSummary) {\n\tconst formatted = formatMessagesForCompaction(messages);\n\tif (formatted.length <= COMPACTION_CHUNK_CHARS) {\n\t\tconst chunk = await summarizeChunk(resolved, priorSummary ? `${priorSummary}\\n\\n${formatted}` : formatted, void 0);\n\t\treturn {\n\t\t\tsummary: chunk.summary,\n\t\t\tusages: [chunk.usage]\n\t\t};\n\t}\n\tconst usages = [];\n\tlet rolling = priorSummary;\n\tlet offset = 0;\n\twhile (offset < formatted.length) {\n\t\tconst chunk = await summarizeChunk(resolved, formatted.slice(offset, offset + COMPACTION_CHUNK_CHARS), rolling);\n\t\tusages.push(chunk.usage);\n\t\trolling = chunk.summary;\n\t\toffset += COMPACTION_CHUNK_CHARS;\n\t}\n\treturn {\n\t\tsummary: rolling ?? \"(empty summary)\",\n\t\tusages\n\t};\n}\nfunction summaryToModelMessage(summary) {\n\treturn {\n\t\trole: \"user\",\n\t\tcontent: [\n\t\t\t\"Context summary from earlier in this session (older messages were compacted):\",\n\t\t\t\"\",\n\t\t\tsummary\n\t\t].join(\"\\n\")\n\t};\n}\nfunction summaryToUiMessage(summary) {\n\treturn {\n\t\tid: generateId(),\n\t\trole: \"user\",\n\t\tparts: [{\n\t\t\ttype: \"text\",\n\t\t\ttext: [\n\t\t\t\t\"Context summary from earlier in this session (older messages were compacted):\",\n\t\t\t\t\"\",\n\t\t\t\tsummary\n\t\t\t].join(\"\\n\")\n\t\t}]\n\t};\n}\n/**\n* Compact model messages with the compaction model. Retains a recent raw tail.\n* Caller supplies `compactedThroughSeq` for durable checkpoints (message event seq).\n*/\nasync function compactModelMessages(options) {\n\tconst retain = options.retainTail ?? 4;\n\tconst { prefix, tail } = resolveCompactionSplit({\n\t\tmessages: options.messages,\n\t\tretainTail: retain,\n\t\tbudget: options.budget ?? null,\n\t\thasPriorSummary: Boolean(options.priorSummary),\n\t\t...options.overheadTokens !== void 0 ? { overheadTokens: options.overheadTokens } : {}\n\t});\n\tif (prefix.length === 0 && !options.priorSummary) throw new Error(\"Nothing to compact\");\n\tconst compactedThroughSeq = typeof options.compactedThroughSeq === \"function\" ? options.compactedThroughSeq(prefix.length) : options.compactedThroughSeq;\n\tconst resolved = await resolveAgentModel(options.compactionModelId);\n\tconst { summary, usages } = await summarizeMessages(resolved, prefix.length > 0 ? prefix : [], options.priorSummary);\n\tconst primary = usages[0];\n\tlet quantity = 0;\n\tlet amount = 0;\n\tlet summaryInputTokens = 0;\n\tlet summaryOutputTokens = 0;\n\tfor (const usage of usages) {\n\t\tquantity += usage.quantity;\n\t\tamount += usage.amount;\n\t\tif (typeof usage.metadata.input === \"number\") summaryInputTokens += usage.metadata.input;\n\t\tif (typeof usage.metadata.output === \"number\") summaryOutputTokens += usage.metadata.output;\n\t}\n\tconst usage = {\n\t\t...primary,\n\t\tquantity,\n\t\tamount,\n\t\tlabel: `LLM compaction · ${resolved.modelId}`,\n\t\tmetadata: {\n\t\t\t...primary.metadata,\n\t\t\toperation: \"context_compaction\",\n\t\t\tsourceModel: options.sourceModel,\n\t\t\tcompactedThroughSeq,\n\t\t\tdurable: options.durable,\n\t\t\tcompactionChunks: usages.length,\n\t\t\tinput: summaryInputTokens || primary.metadata.input,\n\t\t\toutput: summaryOutputTokens || primary.metadata.output,\n\t\t\tcost: {\n\t\t\t\t...primary.metadata.cost ?? {},\n\t\t\t\ttotal: amount\n\t\t\t}\n\t\t}\n\t};\n\tconst checkpoint = {\n\t\tcompactedThroughSeq,\n\t\tsummary,\n\t\tcompactionModel: resolved.modelId,\n\t\tsourceModel: options.sourceModel,\n\t\tdurable: options.durable,\n\t\t...options.estimatedBeforeTokens !== void 0 ? { estimatedBeforeTokens: options.estimatedBeforeTokens } : {},\n\t\t...options.actualBeforeTokens !== void 0 ? { actualBeforeTokens: options.actualBeforeTokens } : {},\n\t\tretainedTailEstimate: estimateSerializedCharsApprox(tail),\n\t\tsummaryInputTokens: summaryInputTokens > 0 ? summaryInputTokens : void 0,\n\t\tsummaryOutputTokens: summaryOutputTokens > 0 ? summaryOutputTokens : void 0,\n\t\t...options.budget ? {\n\t\t\tcontextWindow: options.budget.contextWindow,\n\t\t\tsoftLimit: options.budget.softLimit\n\t\t} : {},\n\t\t...options.promptId !== void 0 ? { promptId: options.promptId } : {}\n\t};\n\treturn {\n\t\tmessages: [summaryToModelMessage(summary), ...tail],\n\t\tcheckpoint,\n\t\tusage\n\t};\n}\nfunction estimateSerializedCharsApprox(messages) {\n\treturn Math.ceil(JSON.stringify(messages).length / 4);\n}\n/**\n* Rebuild model-facing UI messages from a durable checkpoint + newer transcript.\n* The full transcript is unchanged; this only shapes what the model sees.\n*/\nfunction rebuildMessagesFromCheckpoint(options) {\n\tconst { checkpoint, messageEvents } = options;\n\tif (!checkpoint || !checkpoint.durable) return messageEvents.map((event) => event.message);\n\tconst suffix = messageEvents.filter((event) => event.seq > checkpoint.compactedThroughSeq).map((event) => event.message);\n\treturn [summaryToUiMessage(checkpoint.summary), ...suffix];\n}\n/** Parse a durable checkpoint from a persisted agent event payload. */\nfunction parseContextCompactionCheckpoint(payload) {\n\tif (typeof payload !== \"object\" || payload === null) return null;\n\tconst record = payload;\n\tconst checkpoint = record.type === \"context_compacted\" && typeof record.checkpoint === \"object\" && record.checkpoint !== null ? record.checkpoint : record;\n\tif (typeof checkpoint.compactedThroughSeq !== \"number\" || typeof checkpoint.summary !== \"string\" || typeof checkpoint.compactionModel !== \"string\" || typeof checkpoint.sourceModel !== \"string\" || typeof checkpoint.durable !== \"boolean\") return null;\n\treturn checkpoint;\n}\n//#endregion\nexport { resolveCompactionModelId as a, llmUsageFromLanguageModelUsage as c, resolveContextBudget as d, estimateChatAttachmentTokens as f, rebuildMessagesFromCheckpoint as i, ContextBudgetTracker as l, mapMessageFileParts as m, compactModelMessages as n, summaryToUiMessage as o, placeholderChatAttachmentMessages as p, parseContextCompactionCheckpoint as r, byokFromResponseHeaders as s, CONTEXT_COMPACTED_EVENT_TYPE as t, estimateSerializedChars as u };\n\n//# sourceMappingURL=context-compaction-Bxp4WK2B.mjs.map"],"mappings":";;;;;AAMA,SAAS,4BAA4B,MAAM;CAC1C,MAAM,MAAM,IAAI,IAAI,QAAQ,CAAC,CAAC;CAC9B,OAAO;EACN,QAAQ,IAAI,IAAI,QAAQ;EACxB,OAAO,IAAI,IAAI,YAAY;CAC5B;AACD;AACA,SAAS,0BAA0B,UAAU,WAAW;CACvD,OAAO,wBAAwB,UAAU,KAAK,KAAK,UAAU,kBAAkB,UAAU,WAAW,QAAQ,IAAI,UAAU,OAAO;AAClI;AAGA,MAAM,UAAU,IAAIA,iBAAAA,kBAAkB;;;;;;;AAOtC,SAAS,kBAAkB,SAAS,IAAI;C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C,mBAAmB,WAAW,OAAO,GAAG,GAAG,MAAM;AAC1D;;AAEA,SAAS,iCAAiC,SAAS;CAClD,IAAI,OAAO,YAAY,YAAY,YAAY,MAAM,OAAO;CAC5D,MAAM,SAAS;CACf,MAAM,aAAa,OAAO,SAAS,uBAAuB,OAAO,OAAO,eAAe,YAAY,OAAO,eAAe,OAAO,OAAO,aAAa;CACpJ,IAAI,OAAO,WAAW,wBAAwB,YAAY,OAAO,WAAW,YAAY,YAAY,OAAO,WAAW,oBAAoB,YAAY,OAAO,WAAW,gBAAgB,YAAY,OAAO,WAAW,YAAY,WAAW,OAAO;CACpP,OAAO;AACR"}
@@ -1,5 +1,5 @@
1
- import { c as LLM_RUN_KIND_HEADER, l as LLM_SKIP_USAGE_HEADER, o as LLM_KEY_SOURCE_HEADER, s as LLM_RUN_ID_HEADER } from "./dist-D0P3wUQe.mjs";
2
- import { L as getProjectScopeId, _ as generateId, a as generateText, f as createGateway } from "./dist-C_APGtUJ.mjs";
1
+ import { D as parseChatAttachmentServePath, c as LLM_RUN_KIND_HEADER, l as LLM_SKIP_USAGE_HEADER, o as LLM_KEY_SOURCE_HEADER, s as LLM_RUN_ID_HEADER } from "./dist-D0P3wUQe.mjs";
2
+ import { L as getProjectScopeId, _ as generateId, a as generateText, f as createGateway, s as isFileUIPart } from "./dist-C_APGtUJ.mjs";
3
3
  import { z } from "zod";
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
5
  //#region ../agent/dist/schemas-DDyTkszQ.mjs
@@ -272,7 +272,65 @@ function resolveThinkingLevel(level) {
272
272
  return level ?? "medium";
273
273
  }
274
274
  //#endregion
275
- //#region ../agent/dist/context-compaction-B2veGznA.mjs
275
+ //#region ../agent/dist/context-compaction-Bxp4WK2B.mjs
276
+ /** Map every `FileUIPart` in each message, leaving other parts and non-array messages untouched. */
277
+ async function mapMessageFileParts(messages, mapFilePart) {
278
+ return Promise.all(messages.map(async (message) => {
279
+ if (!Array.isArray(message.parts)) return message;
280
+ const parts = await Promise.all(message.parts.map((part) => isFileUIPart(part) ? mapFilePart(part) : part));
281
+ return {
282
+ ...message,
283
+ parts
284
+ };
285
+ }));
286
+ }
287
+ /**
288
+ * Approximate model-token cost of one image attachment. Vision pricing is
289
+ * tile-based (provider-dependent, roughly 750–1,600 tokens for a typical
290
+ * photo), not proportional to serialized bytes — a flat per-image charge is
291
+ * closer to reality than counting base64 chars.
292
+ */
293
+ const APPROX_ATTACHMENT_IMAGE_TOKENS = 1100;
294
+ /**
295
+ * Approximate model-token cost of one non-image attachment (PDFs). Page count
296
+ * is unknown without downloading, so this assumes a short document; a giant
297
+ * PDF under-counts, but the estimate only steers the compaction heuristic.
298
+ */
299
+ const APPROX_ATTACHMENT_FILE_TOKENS = 3e3;
300
+ function isUnhydratedAttachment(part) {
301
+ return parseChatAttachmentServePath(part.url) !== null;
302
+ }
303
+ /**
304
+ * Replace unhydrated chat-attachment file parts (relative serve paths) with
305
+ * text placeholders so the messages survive `convertToModelMessages` — the AI
306
+ * SDK's `new URL(part.url)` throws `TypeError: Invalid URL` on relative paths.
307
+ *
308
+ * For estimation and compaction only: the placeholder tells the compaction
309
+ * model an attachment existed, and the real model call hydrates the actual
310
+ * bytes via `hydrateChatAttachmentMessages` instead.
311
+ */
312
+ function placeholderChatAttachmentMessages(messages) {
313
+ return mapMessageFileParts(messages, (part) => isUnhydratedAttachment(part) ? {
314
+ type: "text",
315
+ text: `[attachment: ${part.filename?.trim() || "file"} (${part.mediaType})]`
316
+ } : part);
317
+ }
318
+ /**
319
+ * Estimated token cost of the unhydrated attachments in `messages`, to add on
320
+ * top of a char-based serialized estimate (which only sees the placeholder
321
+ * text, not what the attachment will cost once hydrated for the model).
322
+ */
323
+ function estimateChatAttachmentTokens(messages) {
324
+ let total = 0;
325
+ for (const message of messages) {
326
+ if (!Array.isArray(message.parts)) continue;
327
+ for (const part of message.parts) {
328
+ if (!isFileUIPart(part) || !isUnhydratedAttachment(part)) continue;
329
+ total += part.mediaType.startsWith("image/") ? APPROX_ATTACHMENT_IMAGE_TOKENS : APPROX_ATTACHMENT_FILE_TOKENS;
330
+ }
331
+ }
332
+ return total;
333
+ }
276
334
  /** Soft compaction trigger as a fraction of the usable input budget. */
277
335
  const CONTEXT_COMPACTION_SOFT_RATIO = .9;
278
336
  /**
@@ -287,7 +345,11 @@ const MIN_OUTPUT_RESERVE = 4096;
287
345
  const MAX_OUTPUT_RESERVE = 32768;
288
346
  /** Extra framing/tool-schema overhead beyond the output reservation. */
289
347
  const SAFETY_RESERVE = 2048;
290
- /** Conservative chars-per-token floor when no calibration sample exists. */
348
+ /**
349
+ * Conservative fixed chars-per-token ratio. Anchored estimates only apply it
350
+ * to the delta since the last real `input_tokens`, so a systematic error here
351
+ * is bounded by one step's new content, not the whole transcript.
352
+ */
291
353
  const DEFAULT_CHARS_PER_TOKEN = 3.5;
292
354
  /**
293
355
  * Derive the usable input budget from gateway context metadata.
@@ -318,15 +380,65 @@ function estimateSerializedChars(input) {
318
380
  if (input.tools !== void 0) total += JSON.stringify(input.tools).length;
319
381
  return total;
320
382
  }
383
+ const DATA_URL_MEDIA_MIN_CHARS = 4096;
384
+ function approxMediaTokens(mediaType) {
385
+ return typeof mediaType === "string" && mediaType.startsWith("image/") ? APPROX_ATTACHMENT_IMAGE_TOKENS : APPROX_ATTACHMENT_FILE_TOKENS;
386
+ }
387
+ /**
388
+ * Serialized message size with media content measured as flat token estimates
389
+ * instead of chars. Vision/file pricing is tile- or page-based — counting a
390
+ * 4 MB image's ~5.3M base64 chars would estimate ~1.5M tokens for what the
391
+ * provider bills as ~1,100, wrongly triggering compaction on any large image.
392
+ */
393
+ function measureMessagesForBudget(messages) {
394
+ let mediaTokens = 0;
395
+ return {
396
+ chars: JSON.stringify(messages, (_key, value) => {
397
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
398
+ mediaTokens += 3e3;
399
+ return "[media]";
400
+ }
401
+ if (typeof value === "object" && value !== null) {
402
+ const part = value;
403
+ if (part.type === "image" && part.image !== void 0) {
404
+ mediaTokens += 1100;
405
+ return {
406
+ type: "image",
407
+ omitted: true
408
+ };
409
+ }
410
+ if ((part.type === "file" || part.type === "media") && part.data !== void 0) {
411
+ mediaTokens += approxMediaTokens(part.mediaType);
412
+ return {
413
+ type: part.type,
414
+ omitted: true
415
+ };
416
+ }
417
+ if (part.type === "Buffer" && Array.isArray(part.data)) {
418
+ mediaTokens += 3e3;
419
+ return "[media]";
420
+ }
421
+ }
422
+ if (typeof value === "string" && value.length >= DATA_URL_MEDIA_MIN_CHARS && value.startsWith("data:")) {
423
+ mediaTokens += value.startsWith("data:image/") ? 1100 : 3e3;
424
+ return "[media]";
425
+ }
426
+ return value;
427
+ })?.length ?? 0,
428
+ mediaTokens
429
+ };
430
+ }
321
431
  /**
322
- * Per-prompt tracker: calibrates a chars→tokens ratio from actual step usage,
323
- * then estimates the next request before it is sent.
432
+ * Per-prompt tracker: anchors on the last real `input_tokens` and estimates
433
+ * only the delta (new content since that request), so estimation error is
434
+ * bounded by one step's new content instead of the whole transcript. Before
435
+ * the first completed step it falls back to a full char scan with media
436
+ * priced at flat token constants.
324
437
  */
325
438
  var ContextBudgetTracker = class {
326
439
  budget;
327
- charsPerToken = DEFAULT_CHARS_PER_TOKEN;
328
- lastActualInputTokens;
329
- lastEstimatedChars;
440
+ anchor;
441
+ lastMeasure;
330
442
  constructor(budget) {
331
443
  this.budget = budget;
332
444
  }
@@ -334,43 +446,52 @@ var ContextBudgetTracker = class {
334
446
  return this.budget;
335
447
  }
336
448
  get lastInputTokens() {
337
- return this.lastActualInputTokens;
449
+ return this.anchor?.inputTokens;
338
450
  }
339
451
  /**
340
- * Update calibration from a completed primary-model step's input token
341
- * count. Pairs it with the serialized size measured by the estimate that
342
- * preceded the request (or an explicit `serializedChars`), so the ratio
343
- * describes the same payload the provider tokenized.
452
+ * Anchor on a completed primary-model step's input token count, paired with
453
+ * the measure taken by the estimate that preceded that request future
454
+ * estimates price only content added after this point.
344
455
  */
345
- recordStepUsage(inputTokens, serializedChars) {
346
- const chars = serializedChars ?? this.lastEstimatedChars;
347
- if (inputTokens > 0 && chars !== void 0 && chars > 0) {
348
- const sample = chars / inputTokens;
349
- this.charsPerToken = this.charsPerToken * .35 + sample * .65;
350
- }
351
- this.lastActualInputTokens = inputTokens > 0 ? inputTokens : this.lastActualInputTokens;
456
+ recordStepUsage(inputTokens) {
457
+ if (inputTokens > 0 && this.lastMeasure) this.anchor = {
458
+ inputTokens,
459
+ ...this.lastMeasure
460
+ };
352
461
  }
353
- /** Reset after a successful compaction so the next estimate starts fresh. */
462
+ /** Reset after a successful compaction: the transcript the anchor priced no longer exists. */
354
463
  resetAfterCompaction() {
355
- this.lastActualInputTokens = void 0;
356
- this.lastEstimatedChars = void 0;
357
- this.charsPerToken = DEFAULT_CHARS_PER_TOKEN;
464
+ this.anchor = void 0;
465
+ this.lastMeasure = void 0;
358
466
  }
359
467
  estimate(input) {
360
468
  if (!this.budget) return null;
361
- const messageChars = estimateSerializedChars({ messages: input.messages });
469
+ const measure = measureMessagesForBudget(input.messages);
362
470
  const overheadChars = input.overheadChars ?? estimateSerializedChars({
363
471
  systemPrompt: input.systemPrompt,
364
472
  tools: input.tools
365
473
  });
366
- this.lastEstimatedChars = overheadChars + messageChars;
367
- const toTokens = (chars) => Math.max(Math.ceil(chars / this.charsPerToken), Math.ceil(chars / 4));
368
- const estimatedInputTokens = toTokens(overheadChars + messageChars);
369
- const estimatedMessageTokens = toTokens(messageChars);
474
+ const mediaTokens = measure.mediaTokens + (input.extraMessageTokens ?? 0);
475
+ this.lastMeasure = {
476
+ chars: measure.chars,
477
+ mediaTokens
478
+ };
479
+ const toTokens = (chars) => Math.ceil(chars / DEFAULT_CHARS_PER_TOKEN);
480
+ let estimatedInputTokens;
481
+ let estimatedMessageTokens;
482
+ if (this.anchor) {
483
+ const deltaTokens = toTokens(Math.max(0, measure.chars - this.anchor.chars)) + Math.max(0, mediaTokens - this.anchor.mediaTokens);
484
+ estimatedInputTokens = this.anchor.inputTokens + deltaTokens;
485
+ estimatedMessageTokens = Math.max(deltaTokens, estimatedInputTokens - toTokens(overheadChars));
486
+ } else {
487
+ estimatedInputTokens = toTokens(overheadChars + measure.chars) + mediaTokens;
488
+ estimatedMessageTokens = toTokens(measure.chars) + mediaTokens;
489
+ }
490
+ const decision = estimatedInputTokens >= this.budget.softLimit && estimatedMessageTokens > Math.floor(this.budget.softLimit * .5) ? "compact" : "allow";
370
491
  return {
371
492
  estimatedInputTokens,
372
493
  estimatedMessageTokens,
373
- decision: estimatedInputTokens >= this.budget.softLimit && estimatedMessageTokens > Math.floor(this.budget.softLimit * .5) ? "compact" : "allow",
494
+ decision,
374
495
  budget: this.budget
375
496
  };
376
497
  }
@@ -685,6 +806,6 @@ function parseContextCompactionCheckpoint(payload) {
685
806
  return checkpoint;
686
807
  }
687
808
  //#endregion
688
- export { withLlmRunContext as C, splitAgentModelId as S, currentLlmRunContext as _, llmUsageFromLanguageModelUsage as a, resolveModelCapabilities as b, resolveCompactionModelId as c, AgentCreateInputSchema as d, AgentModelIdSchema as f, attachmentPlaceholderText as g, ThinkingLevelSchema as h, estimateSerializedChars as i, resolveContextBudget as l, DEFAULT_THINKING_LEVEL as m, byokFromResponseHeaders as n, parseContextCompactionCheckpoint as o, DEFAULT_COMPACTION_MODEL_ID as p, compactModelMessages as r, rebuildMessagesFromCheckpoint as s, ContextBudgetTracker as t, summaryToUiMessage as u, parseAgentCreateInput as v, resolveThinkingLevel as x, resolveAgentModel as y };
809
+ export { resolveModelCapabilities as C, withLlmRunContext as E, resolveAgentModel as S, splitAgentModelId as T, DEFAULT_THINKING_LEVEL as _, estimateSerializedChars as a, currentLlmRunContext as b, parseContextCompactionCheckpoint as c, resolveCompactionModelId as d, resolveContextBudget as f, DEFAULT_COMPACTION_MODEL_ID as g, AgentModelIdSchema as h, estimateChatAttachmentTokens as i, placeholderChatAttachmentMessages as l, AgentCreateInputSchema as m, byokFromResponseHeaders as n, llmUsageFromLanguageModelUsage as o, summaryToUiMessage as p, compactModelMessages as r, mapMessageFileParts as s, ContextBudgetTracker as t, rebuildMessagesFromCheckpoint as u, ThinkingLevelSchema as v, resolveThinkingLevel as w, parseAgentCreateInput as x, attachmentPlaceholderText as y };
689
810
 
690
- //# sourceMappingURL=context-compaction-B2veGznA-Br9-3A43.mjs.map
811
+ //# sourceMappingURL=context-compaction-Bxp4WK2B-Ct4RSjlg.mjs.map