@sriinnu/fiche 0.0.0-stage → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +13 -0
  4. package/PRIVACY.md +41 -0
  5. package/README.md +288 -2
  6. package/SECURITY.md +53 -0
  7. package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
  8. package/assets/SPLEEN_LICENSE.txt +24 -0
  9. package/assets/UNIFONT_LICENSE.txt +476 -0
  10. package/assets/fiche-logo-dark.svg +61 -0
  11. package/assets/fiche-logo-light.svg +61 -0
  12. package/assets/fiche-logo.svg +71 -0
  13. package/assets/fiche-mark.svg +48 -0
  14. package/bin/cli.js +7 -0
  15. package/bin/mcp.js +8 -0
  16. package/dist/calibrate.d.ts +30 -0
  17. package/dist/calibrate.js +588 -0
  18. package/dist/core/anthropic-vision.d.ts +28 -0
  19. package/dist/core/anthropic-vision.js +34 -0
  20. package/dist/core/applicability.d.ts +63 -0
  21. package/dist/core/applicability.js +151 -0
  22. package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
  23. package/dist/core/atlas-gray-jbmono10.js +64 -0
  24. package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
  25. package/dist/core/atlas-gray-jbmono12.js +64 -0
  26. package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
  27. package/dist/core/atlas-gray-jbmono14.js +64 -0
  28. package/dist/core/atlas-gray.d.ts +26 -0
  29. package/dist/core/atlas-gray.js +64 -0
  30. package/dist/core/atlas-jbmono10.d.ts +34 -0
  31. package/dist/core/atlas-jbmono10.js +71 -0
  32. package/dist/core/atlas-jbmono12.d.ts +34 -0
  33. package/dist/core/atlas-jbmono12.js +71 -0
  34. package/dist/core/atlas-jbmono14.d.ts +34 -0
  35. package/dist/core/atlas-jbmono14.js +71 -0
  36. package/dist/core/atlas.d.ts +34 -0
  37. package/dist/core/atlas.js +71 -0
  38. package/dist/core/baseline.d.ts +121 -0
  39. package/dist/core/baseline.js +200 -0
  40. package/dist/core/calibration.d.ts +86 -0
  41. package/dist/core/calibration.js +547 -0
  42. package/dist/core/casi-delta.d.ts +63 -0
  43. package/dist/core/casi-delta.js +1271 -0
  44. package/dist/core/claude-model-profiles.d.ts +53 -0
  45. package/dist/core/claude-model-profiles.js +160 -0
  46. package/dist/core/client-tool-round.d.ts +31 -0
  47. package/dist/core/client-tool-round.js +58 -0
  48. package/dist/core/codex-cache.d.ts +20 -0
  49. package/dist/core/codex-cache.js +59 -0
  50. package/dist/core/context-mmu.d.ts +350 -0
  51. package/dist/core/context-mmu.js +3028 -0
  52. package/dist/core/cpt-fit.d.ts +70 -0
  53. package/dist/core/cpt-fit.js +197 -0
  54. package/dist/core/env.d.ts +8 -0
  55. package/dist/core/env.js +15 -0
  56. package/dist/core/export.d.ts +127 -0
  57. package/dist/core/export.js +385 -0
  58. package/dist/core/factsheet.d.ts +77 -0
  59. package/dist/core/factsheet.js +494 -0
  60. package/dist/core/gemini-model-profiles.d.ts +20 -0
  61. package/dist/core/gemini-model-profiles.js +134 -0
  62. package/dist/core/google.d.ts +76 -0
  63. package/dist/core/google.js +1380 -0
  64. package/dist/core/gpt-model-profiles.d.ts +218 -0
  65. package/dist/core/gpt-model-profiles.js +570 -0
  66. package/dist/core/gpt-tokens.d.ts +14 -0
  67. package/dist/core/gpt-tokens.js +165 -0
  68. package/dist/core/history.d.ts +197 -0
  69. package/dist/core/history.js +1003 -0
  70. package/dist/core/index.d.ts +16 -0
  71. package/dist/core/index.js +16 -0
  72. package/dist/core/library.d.ts +80 -0
  73. package/dist/core/library.js +131 -0
  74. package/dist/core/measurement.d.ts +34 -0
  75. package/dist/core/measurement.js +280 -0
  76. package/dist/core/messages-chat-bridge.d.ts +23 -0
  77. package/dist/core/messages-chat-bridge.js +747 -0
  78. package/dist/core/messages-responses-bridge.d.ts +11 -0
  79. package/dist/core/messages-responses-bridge.js +893 -0
  80. package/dist/core/openai-history.d.ts +184 -0
  81. package/dist/core/openai-history.js +1279 -0
  82. package/dist/core/openai-savings.d.ts +57 -0
  83. package/dist/core/openai-savings.js +116 -0
  84. package/dist/core/openai.d.ts +68 -0
  85. package/dist/core/openai.js +2523 -0
  86. package/dist/core/pin.d.ts +199 -0
  87. package/dist/core/pin.js +1353 -0
  88. package/dist/core/png.d.ts +14 -0
  89. package/dist/core/png.js +188 -0
  90. package/dist/core/prefix-tape.d.ts +102 -0
  91. package/dist/core/prefix-tape.js +315 -0
  92. package/dist/core/price-id.d.ts +10 -0
  93. package/dist/core/price-id.js +26 -0
  94. package/dist/core/prices.generated.d.ts +36 -0
  95. package/dist/core/prices.generated.js +369 -0
  96. package/dist/core/pricing.d.ts +134 -0
  97. package/dist/core/pricing.js +335 -0
  98. package/dist/core/profile-base.d.ts +30 -0
  99. package/dist/core/profile-base.js +67 -0
  100. package/dist/core/provider-router.d.ts +51 -0
  101. package/dist/core/provider-router.js +121 -0
  102. package/dist/core/proxy.d.ts +252 -0
  103. package/dist/core/proxy.js +2929 -0
  104. package/dist/core/reader-tier.d.ts +24 -0
  105. package/dist/core/reader-tier.js +118 -0
  106. package/dist/core/render.d.ts +280 -0
  107. package/dist/core/render.js +1302 -0
  108. package/dist/core/request-guard.d.ts +31 -0
  109. package/dist/core/request-guard.js +126 -0
  110. package/dist/core/request-transform.d.ts +43 -0
  111. package/dist/core/request-transform.js +173 -0
  112. package/dist/core/schema-compiler.d.ts +64 -0
  113. package/dist/core/schema-compiler.js +1696 -0
  114. package/dist/core/schema-strip.d.ts +29 -0
  115. package/dist/core/schema-strip.js +173 -0
  116. package/dist/core/session-state.d.ts +219 -0
  117. package/dist/core/session-state.js +929 -0
  118. package/dist/core/stage-plugins.d.ts +45 -0
  119. package/dist/core/stage-plugins.js +205 -0
  120. package/dist/core/text-history.d.ts +74 -0
  121. package/dist/core/text-history.js +612 -0
  122. package/dist/core/text-hygiene.d.ts +160 -0
  123. package/dist/core/text-hygiene.js +2259 -0
  124. package/dist/core/toon.d.ts +29 -0
  125. package/dist/core/toon.js +425 -0
  126. package/dist/core/tracker.d.ts +223 -0
  127. package/dist/core/tracker.js +290 -0
  128. package/dist/core/transform.d.ts +589 -0
  129. package/dist/core/transform.js +3153 -0
  130. package/dist/core/types.d.ts +87 -0
  131. package/dist/core/types.js +8 -0
  132. package/dist/core/upstream-hosts.d.ts +127 -0
  133. package/dist/core/upstream-hosts.js +398 -0
  134. package/dist/core/vision-cost.d.ts +63 -0
  135. package/dist/core/vision-cost.js +137 -0
  136. package/dist/dashboard/fragments.d.ts +87 -0
  137. package/dist/dashboard/fragments.js +1515 -0
  138. package/dist/dashboard/types.d.ts +217 -0
  139. package/dist/dashboard/types.js +3 -0
  140. package/dist/dashboard/vendor.d.ts +3 -0
  141. package/dist/dashboard/vendor.js +6 -0
  142. package/dist/dashboard.d.ts +372 -0
  143. package/dist/dashboard.js +2731 -0
  144. package/dist/export-collect.d.ts +36 -0
  145. package/dist/export-collect.js +59 -0
  146. package/dist/file-tracker.d.ts +42 -0
  147. package/dist/file-tracker.js +234 -0
  148. package/dist/kosha-sync.d.ts +74 -0
  149. package/dist/kosha-sync.js +272 -0
  150. package/dist/launchd-socket.d.ts +22 -0
  151. package/dist/launchd-socket.js +210 -0
  152. package/dist/mcp/cli.d.ts +2 -0
  153. package/dist/mcp/cli.js +55 -0
  154. package/dist/mcp/server.d.ts +48 -0
  155. package/dist/mcp/server.js +987 -0
  156. package/dist/mmu-store.d.ts +31 -0
  157. package/dist/mmu-store.js +179 -0
  158. package/dist/node-fetch.d.ts +22 -0
  159. package/dist/node-fetch.js +489 -0
  160. package/dist/node.d.ts +9 -0
  161. package/dist/node.js +244396 -0
  162. package/dist/request-decoding.d.ts +30 -0
  163. package/dist/request-decoding.js +85 -0
  164. package/dist/sessions.d.ts +179 -0
  165. package/dist/sessions.js +837 -0
  166. package/dist/stats.d.ts +114 -0
  167. package/dist/stats.js +439 -0
  168. package/dist/turn-report.d.ts +65 -0
  169. package/dist/turn-report.js +724 -0
  170. package/dist/warp/app-launch.d.ts +26 -0
  171. package/dist/warp/app-launch.js +155 -0
  172. package/dist/warp/ca.d.ts +74 -0
  173. package/dist/warp/ca.js +416 -0
  174. package/dist/warp/connect.d.ts +42 -0
  175. package/dist/warp/connect.js +686 -0
  176. package/dist/warp/der.d.ts +57 -0
  177. package/dist/warp/der.js +151 -0
  178. package/dist/warp/index.d.ts +79 -0
  179. package/dist/warp/index.js +650 -0
  180. package/dist/warp/resolve.d.ts +12 -0
  181. package/dist/warp/resolve.js +49 -0
  182. package/dist/warp/route.d.ts +71 -0
  183. package/dist/warp/route.js +134 -0
  184. package/dist/worker.d.ts +71 -0
  185. package/dist/worker.js +174 -0
  186. package/docs/SECURITY_MODEL.md +84 -0
  187. package/package.json +122 -4
  188. package/plugins/fiche-companion/README.md +42 -0
  189. package/plugins/fiche-companion/assets/logo.svg +48 -0
  190. package/plugins/fiche-companion/hooks.json +11 -0
  191. package/plugins/fiche-companion/mcp_config.json +8 -0
  192. package/plugins/fiche-companion/plugin.json +18 -0
  193. package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
  194. package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
  195. package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
  196. package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
@@ -0,0 +1,16 @@
1
+ export { getAllowedModelBases, getConfiguredModelBases, isFicheSupportedGptModel, isFicheSupportedModel, isInklingSupportedGptModel, isInklingSupportedModel, setAllowedModelBases, shouldTransformAnthropicMessages, type FicheApplicabilityInput, type FicheApplicabilityReason, type InklingApplicabilityInput, type InklingApplicabilityReason, } from './applicability.js';
2
+ export { buildCountTokensBodies, buildBaselineCountTokensBody, buildCacheablePrefixCountTokensBody, countCacheControlMarkers, isThreadContinuation, type CountTokensBodies, } from './measurement.js';
3
+ export { transformAnthropicMessages, renderTextToImages, type FicheOptions, type FicheReason, type FicheTransformInput, type FicheTransformResult, type InklingOptions, type InklingReason, type InklingTransformInput, type InklingTransformResult, type RenderTextToImagesOptions, type RenderedTextImage, type RenderTextToImagesResult, } from './library.js';
4
+ export { transformRequest, type TransformInfo as FicheTransformInfo, type TransformInfo as InklingTransformInfo, type TransformOptions, type KeepSharpBlock, type RecoverableBlock, } from './transform.js';
5
+ export { transformOpenAIChatCompletions, transformOpenAIResponses, resolveVisionCost, openAIVisionTokens } from './openai.js';
6
+ export { transformAnyRequest, countBillable } from './request-transform.js';
7
+ export { readerTier } from './reader-tier.js';
8
+ export { supportsExplicitPromptCacheBreakpoint, scrubPromptCacheBreakpoint } from './codex-cache.js';
9
+ export { createProxy, type ProxyConfig, type ProxyEvent } from './proxy.js';
10
+ export { createProviderRouter, parseProviderRoute, assertProviderId, type ProviderProtocol, type ProviderRouteDefinition, type ProviderRouterConfig, type ProviderRouterInspection, type ParsedProviderRoute, } from './provider-router.js';
11
+ export { computeActualInputEff, computeBaselineInputEff, CACHE_CREATE_RATE, CACHE_READ_RATE, } from './baseline.js';
12
+ export { buildCalibrationProbe, scoreCalibrationResponse, getCalibratedProfile, setCalibratedProfile, removeCalibratedProfile, listCalibratedProfiles, clearCalibratedProfiles, serializeCalibratedProfiles, restoreCalibratedProfiles, type CalibrationBand, type CalibratedModelProfile, type CalibrationProbe, type CalibrationScores, } from './calibration.js';
13
+ export { ContextPageStore, getGlobalMmuStore, configureMmuPersistence, flushMmuPersistence, resetGlobalMmuStore, computeTailHydration, extractFaultSignalSnippet, computeHorizonPaybackLimit, foldMarkovianEpisodes, linkSessionSkills, pruneLowDensityBlob, extractSymbolSpans, type MmuPage, type MmuPageSummary, type MmuStats, type MmuSymbolSpan, type MmuPersistenceAdapter, type TailHydrationResult, type FoldMarkovianEpisodesResult, type LinkSessionSkillsResult, type PruneLowDensityResult, } from './context-mmu.js';
14
+ export { PrefixMemoTape, getGlobalPrefixTape, resetGlobalPrefixTape, tapeHash64Hex, INITIAL_PREFIX_HASH, type Stage2MemoEntry, type CommittedSlotSeal, type CasiMemoEntry, type PrefixTapeStats, type PrefixMemoTapeOptions, } from './prefix-tape.js';
15
+ export { resolveOpticalHistoryPolicy, type OpticalMode, } from './transform.js';
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,16 @@
1
+ export { getAllowedModelBases, getConfiguredModelBases, isFicheSupportedGptModel, isFicheSupportedModel, isInklingSupportedGptModel, isInklingSupportedModel, setAllowedModelBases, shouldTransformAnthropicMessages, } from './applicability.js';
2
+ export { buildCountTokensBodies, buildBaselineCountTokensBody, buildCacheablePrefixCountTokensBody, countCacheControlMarkers, isThreadContinuation, } from './measurement.js';
3
+ export { transformAnthropicMessages, renderTextToImages, } from './library.js';
4
+ export { transformRequest, } from './transform.js';
5
+ export { transformOpenAIChatCompletions, transformOpenAIResponses, resolveVisionCost, openAIVisionTokens } from './openai.js';
6
+ export { transformAnyRequest, countBillable } from './request-transform.js';
7
+ export { readerTier } from './reader-tier.js';
8
+ export { supportsExplicitPromptCacheBreakpoint, scrubPromptCacheBreakpoint } from './codex-cache.js';
9
+ export { createProxy } from './proxy.js';
10
+ export { createProviderRouter, parseProviderRoute, assertProviderId, } from './provider-router.js';
11
+ export { computeActualInputEff, computeBaselineInputEff, CACHE_CREATE_RATE, CACHE_READ_RATE, } from './baseline.js';
12
+ export { buildCalibrationProbe, scoreCalibrationResponse, getCalibratedProfile, setCalibratedProfile, removeCalibratedProfile, listCalibratedProfiles, clearCalibratedProfiles, serializeCalibratedProfiles, restoreCalibratedProfiles, } from './calibration.js';
13
+ export { ContextPageStore, getGlobalMmuStore, configureMmuPersistence, flushMmuPersistence, resetGlobalMmuStore, computeTailHydration, extractFaultSignalSnippet, computeHorizonPaybackLimit, foldMarkovianEpisodes, linkSessionSkills, pruneLowDensityBlob, extractSymbolSpans, } from './context-mmu.js';
14
+ export { PrefixMemoTape, getGlobalPrefixTape, resetGlobalPrefixTape, tapeHash64Hex, INITIAL_PREFIX_HASH, } from './prefix-tape.js';
15
+ export { resolveOpticalHistoryPolicy, } from './transform.js';
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,80 @@
1
+ import { type RenderStyle } from './render.js';
2
+ import { type TransformInfo, type TransformOptions, type KeepSharpBlock, type RecoverableBlock } from './transform.js';
3
+ export type { KeepSharpBlock, RecoverableBlock };
4
+ export type BytesLike = Uint8Array | ArrayBuffer | ArrayBufferView;
5
+ export interface FicheOptions extends Pick<TransformOptions, 'charsPerToken' | 'historyAmortizationHorizon' | 'keepSharp' | 'emitRecoverable'> {
6
+ /** Test/debug-only bypass. Product hosts should prefer their dashboard setting. */
7
+ readonly compress?: boolean;
8
+ }
9
+ export interface FicheTransformInput {
10
+ readonly body: BytesLike;
11
+ /** Resolved upstream model when available; aliases are accepted for applicability checks. */
12
+ readonly model?: string | null;
13
+ readonly requestId?: string;
14
+ readonly options?: FicheOptions;
15
+ }
16
+ export type FicheReason = 'applied' | 'unsupported_model' | 'parse_error' | 'below_min_chars' | 'below_min_tokens' | 'not_profitable' | 'compress_disabled' | 'image_limit' | 'transform_error' | 'passthrough';
17
+ export interface FicheTransformResult {
18
+ readonly body: Uint8Array;
19
+ readonly applied: boolean;
20
+ readonly reason: FicheReason;
21
+ readonly detail?: string;
22
+ readonly info: TransformInfo;
23
+ readonly cache: {
24
+ readonly ownsCacheControl: boolean;
25
+ readonly markerCount: number;
26
+ };
27
+ }
28
+ /** @deprecated Use {@link FicheOptions}. */
29
+ export type InklingOptions = FicheOptions;
30
+ /** @deprecated Use {@link FicheReason}. */
31
+ export type InklingReason = FicheReason;
32
+ /** @deprecated Use {@link FicheTransformInput}. */
33
+ export type InklingTransformInput = FicheTransformInput;
34
+ /** @deprecated Use {@link FicheTransformResult}. */
35
+ export type InklingTransformResult = FicheTransformResult;
36
+ /**
37
+ * Library wrapper for the Anthropic Messages transformer: model gate, machine-readable
38
+ * reasons, and cache_control ownership flag (prevents hosts stacking a second injector).
39
+ */
40
+ export declare function transformAnthropicMessages(input: FicheTransformInput): Promise<FicheTransformResult>;
41
+ export interface RenderTextToImagesOptions {
42
+ /** Model whose complete built-in render profile supplies defaults. */
43
+ readonly model?: string;
44
+ /** Wrap-width cap. Defaults to the model profile when `model` is set. */
45
+ readonly cols?: number;
46
+ /** Shrink the canvas to the widest actual line (default true). `false` keeps the
47
+ * full `cols` width — the proxy's eval-backed full-canvas behavior. */
48
+ readonly shrink?: boolean;
49
+ /** Reflow the text before rendering (minify + join hard newlines with the ↵ sentinel so
50
+ * short lines pack into full-width rows). This is the proxy's dense history format and is
51
+ * what `inkling export` uses. Default false (raw one-line-per-row). */
52
+ readonly reflow?: boolean;
53
+ /** Max source chars per page. Default DENSE_CONTENT_CHARS_PER_IMAGE. */
54
+ readonly maxCharsPerImage?: number;
55
+ /** Render style. Defaults to the model profile when `model` is set. */
56
+ readonly style?: RenderStyle;
57
+ /** Max page height. Defaults to the model profile when `model` is set. */
58
+ readonly maxHeightPx?: number;
59
+ }
60
+ export interface RenderedTextImage {
61
+ readonly png: Uint8Array;
62
+ readonly width: number;
63
+ readonly height: number;
64
+ }
65
+ export interface RenderTextToImagesResult {
66
+ readonly pages: RenderedTextImage[];
67
+ /** Codepoints absent from the glyph atlas (rendered as blank cells). */
68
+ readonly droppedChars: number;
69
+ /** Σ width×height across all pages. */
70
+ readonly pixels: number;
71
+ }
72
+ /**
73
+ * Render arbitrary text to dense PNG pages — the public, documented entry for the
74
+ * renderer the proxy uses internally. Sizes a narrow canvas to the content (`shrink`).
75
+ * Returns raw PNG bytes + pixel dimensions, ready to write to disk or wrap in
76
+ * image blocks. This is the surface SDK consumers should use instead of reaching into
77
+ * the internal leaf renderers in `render.ts`.
78
+ */
79
+ export declare function renderTextToImages(text: string, opts?: RenderTextToImagesOptions): Promise<RenderTextToImagesResult>;
80
+ //# sourceMappingURL=library.d.ts.map
@@ -0,0 +1,131 @@
1
+ import { isFicheSupportedModel } from './applicability.js';
2
+ import { prefersText } from './reader-tier.js';
3
+ import { countCacheControlMarkers } from './measurement.js';
4
+ import { renderTextToPngsWithCharLimit, measureContentCols, reflow, DENSE_CONTENT_COLS, DENSE_CONTENT_CHARS_PER_IMAGE, DENSE_RENDER_STYLE, MAX_HEIGHT_PX, } from './render.js';
5
+ import { transformRequest, } from './transform.js';
6
+ import { resolveGptProfile } from './gpt-model-profiles.js';
7
+ function toUint8Array(bytes) {
8
+ if (bytes instanceof Uint8Array)
9
+ return bytes;
10
+ if (bytes instanceof ArrayBuffer)
11
+ return new Uint8Array(bytes);
12
+ return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
13
+ }
14
+ function emptyInfo(reason) {
15
+ return {
16
+ compressed: false,
17
+ reason,
18
+ origChars: 0,
19
+ compressedChars: 0,
20
+ imageCount: 0,
21
+ imageBytes: 0,
22
+ staticChars: 0,
23
+ dynamicChars: 0,
24
+ dynamicBlockCount: 0,
25
+ droppedChars: 0,
26
+ };
27
+ }
28
+ function classifyReason(info) {
29
+ if (info.compressed)
30
+ return 'applied';
31
+ const r = info.reason ?? '';
32
+ if (r.startsWith('parse_error'))
33
+ return 'parse_error';
34
+ if (r.startsWith('compress=false'))
35
+ return 'compress_disabled';
36
+ if (r.startsWith('below_min_chars'))
37
+ return 'below_min_chars';
38
+ if (r.startsWith('below_min_tokens'))
39
+ return 'below_min_tokens';
40
+ if (r.startsWith('not_profitable'))
41
+ return 'not_profitable';
42
+ if (r.includes('image') && r.includes('limit'))
43
+ return 'image_limit';
44
+ return 'passthrough';
45
+ }
46
+ /**
47
+ * Library wrapper for the Anthropic Messages transformer: model gate, machine-readable
48
+ * reasons, and cache_control ownership flag (prevents hosts stacking a second injector).
49
+ */
50
+ export async function transformAnthropicMessages(input) {
51
+ const original = toUint8Array(input.body);
52
+ if (!isFicheSupportedModel(input.model)) {
53
+ return {
54
+ body: original,
55
+ applied: false,
56
+ reason: 'unsupported_model',
57
+ detail: input.model ?? undefined,
58
+ info: emptyInfo('unsupported_model'),
59
+ cache: { ownsCacheControl: false, markerCount: countCacheControlMarkers(original) },
60
+ };
61
+ }
62
+ try {
63
+ const { body, info } = await transformRequest(original, {
64
+ ...input.options,
65
+ model: input.model ?? undefined,
66
+ imageCompress: !prefersText(input.model),
67
+ });
68
+ const reason = classifyReason(info);
69
+ const markerCount = countCacheControlMarkers(body);
70
+ return {
71
+ body,
72
+ applied: info.compressed,
73
+ reason,
74
+ detail: info.reason,
75
+ info,
76
+ cache: {
77
+ ownsCacheControl: info.compressed && markerCount > 0,
78
+ markerCount,
79
+ },
80
+ };
81
+ }
82
+ catch (e) {
83
+ return {
84
+ body: original,
85
+ applied: false,
86
+ reason: 'transform_error',
87
+ detail: e instanceof Error ? e.message : String(e),
88
+ info: emptyInfo(`transform_error: ${e instanceof Error ? e.message : String(e)}`),
89
+ cache: { ownsCacheControl: false, markerCount: countCacheControlMarkers(original) },
90
+ };
91
+ }
92
+ }
93
+ /**
94
+ * Render arbitrary text to dense PNG pages — the public, documented entry for the
95
+ * renderer the proxy uses internally. Sizes a narrow canvas to the content (`shrink`).
96
+ * Returns raw PNG bytes + pixel dimensions, ready to write to disk or wrap in
97
+ * image blocks. This is the surface SDK consumers should use instead of reaching into
98
+ * the internal leaf renderers in `render.ts`.
99
+ */
100
+ export async function renderTextToImages(text, opts = {}) {
101
+ const profile = opts.model ? resolveGptProfile(opts.model) : undefined;
102
+ const maxCols = Math.max(1, (opts.cols ?? profile?.stripCols ?? DENSE_CONTENT_COLS) | 0);
103
+ const style = opts.style ?? profile?.style ?? DENSE_RENDER_STYLE;
104
+ const maxHeightPx = opts.maxHeightPx ?? profile?.maxHeightPx ?? MAX_HEIGHT_PX;
105
+ const maxChars = opts.maxCharsPerImage ?? DENSE_CONTENT_CHARS_PER_IMAGE;
106
+ // Reflow (the proxy's dense default; opt-in here): minify trailing whitespace + collapse
107
+ // blank-line runs, then join hard newlines with the ↵ sentinel so short lines PACK into
108
+ // full-width rows instead of one-line-per-row with a ragged right margin. Indentation is
109
+ // preserved (minifyForRender only touches trailing ws), so code stays readable and the ↵
110
+ // marks every real newline so the text is fully reconstructable. This is exactly what the
111
+ // proxy's history path does before rendering — without it, a 384-col canvas holding ~25-col
112
+ // code lines wastes ~75% of every row, which is why raw exports looked sparse. reflow()
113
+ // bails (→ raw text) only if the source already contains ↵, which is vanishingly rare.
114
+ const source = opts.reflow ? reflow(text) ?? text : text;
115
+ // Measure the content width. Reflowed source is one joined full-width line, so this is
116
+ // byte-identical to the proxy's history render.
117
+ const cols = opts.shrink === false ? maxCols : measureContentCols(source, maxCols, style.markerScale, style.font);
118
+ const imgs = await renderTextToPngsWithCharLimit(source, cols, maxChars, style, maxHeightPx);
119
+ let droppedChars = 0;
120
+ let pixels = 0;
121
+ for (const im of imgs) {
122
+ droppedChars += im.droppedChars;
123
+ pixels += im.width * im.height;
124
+ }
125
+ return {
126
+ pages: imgs.map((im) => ({ png: im.png, width: im.width, height: im.height })),
127
+ droppedChars,
128
+ pixels,
129
+ };
130
+ }
131
+ //# sourceMappingURL=library.js.map
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Pure body-shaping utilities for the uncompressed count_tokens counterfactual.
3
+ * No fetch, auth, or Node APIs — hosts supply their own transport.
4
+ */
5
+ export interface CountTokensBodies {
6
+ /** Full original body, filtered to count_tokens-accepted fields. */
7
+ readonly fullBody: Uint8Array | null;
8
+ /** Original body truncated at the latest cache_control marker; null when none exists. */
9
+ readonly cacheablePrefixBody: Uint8Array | null;
10
+ }
11
+ type BytesLike = Uint8Array | ArrayBuffer | ArrayBufferView;
12
+ /**
13
+ * True when the body is a server-side thread continuation
14
+ * (`thread: {type: "continue", ...}`). Such a body carries only the delta; the
15
+ * upstream bills the server-held thread on top (as cache_read/cache_create), so a
16
+ * count_tokens probe on it is not a full-request counterfactual and must not be
17
+ * paired against provider usage.
18
+ */
19
+ export declare function isThreadContinuation(bytes: BytesLike): boolean;
20
+ export declare function buildCountTokensBodies(bytes: BytesLike): CountTokensBodies;
21
+ export declare function buildBaselineCountTokensBody(bytes: BytesLike): Uint8Array | null;
22
+ /** Prepend a minimal user turn + assistant tool_use turn pairing every orphan
23
+ * tool_result, so a thread-delta body is countable. Measurement-only: this body
24
+ * goes to count_tokens, never to /v1/messages. Adds a few dozen tokens of overhead. */
25
+ export declare function prependSyntheticToolUses(body: Record<string, unknown>): Record<string, unknown>;
26
+ /** Build a body containing only the longest cacheable prefix (everything up to and including the last
27
+ * cache_control marker). count_tokens on this body gives cacheable_prefix_tokens.
28
+ * Walk order (latest-first in cache order): messages → system → tools.
29
+ * Returns null when no markers exist (cacheable_prefix_tokens = 0). */
30
+ export declare function buildCacheablePrefixCountTokensBody(bytes: BytesLike): Uint8Array | null;
31
+ /** Count cache_control markers anywhere in an Anthropic Messages body. */
32
+ export declare function countCacheControlMarkers(bytes: BytesLike): number;
33
+ export {};
34
+ //# sourceMappingURL=measurement.d.ts.map
@@ -0,0 +1,280 @@
1
+ /**
2
+ * Pure body-shaping utilities for the uncompressed count_tokens counterfactual.
3
+ * No fetch, auth, or Node APIs — hosts supply their own transport.
4
+ */
5
+ /** Fields accepted by /v1/messages/count_tokens. Any other field returns 400 "Unknown parameter". */
6
+ const COUNT_TOKENS_FIELDS = new Set([
7
+ 'model',
8
+ 'messages',
9
+ 'system',
10
+ 'tools',
11
+ 'tool_choice',
12
+ 'thinking',
13
+ 'mcp_servers',
14
+ ]);
15
+ function toUint8Array(bytes) {
16
+ if (bytes instanceof Uint8Array)
17
+ return bytes;
18
+ if (bytes instanceof ArrayBuffer)
19
+ return new Uint8Array(bytes);
20
+ return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
21
+ }
22
+ /**
23
+ * True when the body is a server-side thread continuation
24
+ * (`thread: {type: "continue", ...}`). Such a body carries only the delta; the
25
+ * upstream bills the server-held thread on top (as cache_read/cache_create), so a
26
+ * count_tokens probe on it is not a full-request counterfactual and must not be
27
+ * paired against provider usage.
28
+ */
29
+ export function isThreadContinuation(bytes) {
30
+ try {
31
+ const obj = JSON.parse(new TextDecoder().decode(toUint8Array(bytes)));
32
+ const thread = obj?.thread;
33
+ return !!thread && typeof thread === 'object' && thread.type === 'continue';
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ }
39
+ export function buildCountTokensBodies(bytes) {
40
+ const b = toUint8Array(bytes);
41
+ return {
42
+ fullBody: buildBaselineCountTokensBody(b),
43
+ cacheablePrefixBody: buildCacheablePrefixCountTokensBody(b),
44
+ };
45
+ }
46
+ export function buildBaselineCountTokensBody(bytes) {
47
+ const b = toUint8Array(bytes);
48
+ try {
49
+ const obj = JSON.parse(new TextDecoder().decode(b));
50
+ const out = {};
51
+ for (const k of Object.keys(obj)) {
52
+ if (COUNT_TOKENS_FIELDS.has(k))
53
+ out[k] = obj[k];
54
+ }
55
+ if (typeof out.model !== 'string' || !Array.isArray(out.messages))
56
+ return null;
57
+ return new TextEncoder().encode(JSON.stringify(prependSyntheticToolUses(out)));
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ }
63
+ /** True when an object carries a cache_control key (presence only; value ignored). */
64
+ function hasCacheControl(x) {
65
+ return (typeof x === 'object'
66
+ && x !== null
67
+ && x.cache_control != null);
68
+ }
69
+ /** Return tool_use ids with no matching tool_result. count_tokens rejects orphans;
70
+ * truncating at a cache_control marker commonly creates them (result is in the dropped tail). */
71
+ function findOrphanToolUseIds(messages) {
72
+ const uses = [];
73
+ const results = new Set();
74
+ for (const msg of messages) {
75
+ if (!msg || typeof msg !== 'object')
76
+ continue;
77
+ const content = msg.content;
78
+ if (!Array.isArray(content))
79
+ continue;
80
+ for (const blk of content) {
81
+ if (!blk || typeof blk !== 'object')
82
+ continue;
83
+ const t = blk.type;
84
+ if (t === 'tool_use') {
85
+ const id = blk.id;
86
+ if (typeof id === 'string')
87
+ uses.push(id);
88
+ }
89
+ else if (t === 'tool_result') {
90
+ const id = blk.tool_use_id;
91
+ if (typeof id === 'string')
92
+ results.add(id);
93
+ }
94
+ }
95
+ }
96
+ return uses.filter((id) => !results.has(id));
97
+ }
98
+ /** Append minimal synthetic tool_results for orphan tool_use ids so count_tokens won't reject the body.
99
+ * Adds only a handful of tokens; keeps estimate within ~1% of truth. */
100
+ function appendSyntheticToolResults(truncated) {
101
+ const messages = truncated.messages;
102
+ if (!Array.isArray(messages))
103
+ return truncated;
104
+ const orphanIds = findOrphanToolUseIds(messages);
105
+ if (orphanIds.length === 0)
106
+ return truncated;
107
+ const syntheticUserMsg = {
108
+ role: 'user',
109
+ content: orphanIds.map((id) => ({
110
+ type: 'tool_result',
111
+ tool_use_id: id,
112
+ content: 'ok',
113
+ })),
114
+ };
115
+ return { ...truncated, messages: [...messages, syntheticUserMsg] };
116
+ }
117
+ /** Return tool_result ids with no EARLIER matching tool_use. A server-side thread
118
+ * continue (`thread:{type:"continue"}`) sends only the delta, which usually opens
119
+ * with the tool_result whose tool_use lives in the server-held thread; count_tokens
120
+ * rejects that body with 400, so the baseline probe used to fail on every such turn. */
121
+ function findOrphanToolResultIds(messages) {
122
+ const seen = new Set();
123
+ const orphans = [];
124
+ for (const msg of messages) {
125
+ if (!msg || typeof msg !== 'object')
126
+ continue;
127
+ const content = msg.content;
128
+ if (!Array.isArray(content))
129
+ continue;
130
+ for (const blk of content) {
131
+ if (!blk || typeof blk !== 'object')
132
+ continue;
133
+ const t = blk.type;
134
+ if (t === 'tool_use') {
135
+ const id = blk.id;
136
+ if (typeof id === 'string')
137
+ seen.add(id);
138
+ }
139
+ else if (t === 'tool_result') {
140
+ const id = blk.tool_use_id;
141
+ if (typeof id === 'string' && !seen.has(id) && !orphans.includes(id))
142
+ orphans.push(id);
143
+ }
144
+ }
145
+ }
146
+ return orphans;
147
+ }
148
+ /** Prepend a minimal user turn + assistant tool_use turn pairing every orphan
149
+ * tool_result, so a thread-delta body is countable. Measurement-only: this body
150
+ * goes to count_tokens, never to /v1/messages. Adds a few dozen tokens of overhead. */
151
+ export function prependSyntheticToolUses(body) {
152
+ const messages = body.messages;
153
+ if (!Array.isArray(messages))
154
+ return body;
155
+ const orphanIds = findOrphanToolResultIds(messages);
156
+ if (orphanIds.length === 0)
157
+ return body;
158
+ const prefix = [
159
+ { role: 'user', content: 'x' },
160
+ {
161
+ role: 'assistant',
162
+ content: orphanIds.map((id) => ({ type: 'tool_use', id, name: 'x', input: {} })),
163
+ },
164
+ ];
165
+ return { ...body, messages: [...prefix, ...messages] };
166
+ }
167
+ /** Build a body containing only the longest cacheable prefix (everything up to and including the last
168
+ * cache_control marker). count_tokens on this body gives cacheable_prefix_tokens.
169
+ * Walk order (latest-first in cache order): messages → system → tools.
170
+ * Returns null when no markers exist (cacheable_prefix_tokens = 0). */
171
+ export function buildCacheablePrefixCountTokensBody(bytes) {
172
+ const b = toUint8Array(bytes);
173
+ let obj;
174
+ try {
175
+ obj = JSON.parse(new TextDecoder().decode(b));
176
+ }
177
+ catch {
178
+ return null;
179
+ }
180
+ if (typeof obj.model !== 'string')
181
+ return null;
182
+ const system = obj.system;
183
+ const messages = obj.messages;
184
+ const tools = obj.tools;
185
+ let truncated = null;
186
+ if (Array.isArray(messages)) {
187
+ for (let mi = messages.length - 1; mi >= 0 && truncated == null; mi--) {
188
+ const msg = messages[mi];
189
+ const content = msg?.content;
190
+ if (Array.isArray(content)) {
191
+ for (let bi = content.length - 1; bi >= 0; bi--) {
192
+ if (hasCacheControl(content[bi])) {
193
+ const truncatedMsg = { ...msg, content: content.slice(0, bi + 1) };
194
+ const truncatedMessages = messages.slice(0, mi).concat([truncatedMsg]);
195
+ truncated = {
196
+ model: obj.model,
197
+ messages: truncatedMessages,
198
+ };
199
+ if (system !== undefined)
200
+ truncated.system = system;
201
+ if (tools !== undefined)
202
+ truncated.tools = tools;
203
+ break;
204
+ }
205
+ }
206
+ }
207
+ else if (hasCacheControl(msg)) {
208
+ truncated = {
209
+ model: obj.model,
210
+ messages: messages.slice(0, mi + 1),
211
+ };
212
+ if (system !== undefined)
213
+ truncated.system = system;
214
+ if (tools !== undefined)
215
+ truncated.tools = tools;
216
+ }
217
+ }
218
+ }
219
+ if (truncated == null && Array.isArray(system)) {
220
+ for (let si = system.length - 1; si >= 0; si--) {
221
+ if (hasCacheControl(system[si])) {
222
+ truncated = {
223
+ model: obj.model,
224
+ system: system.slice(0, si + 1),
225
+ messages: [{ role: 'user', content: 'x' }],
226
+ };
227
+ if (tools !== undefined)
228
+ truncated.tools = tools;
229
+ break;
230
+ }
231
+ }
232
+ }
233
+ if (truncated == null && Array.isArray(tools)) {
234
+ for (let ti = tools.length - 1; ti >= 0; ti--) {
235
+ if (hasCacheControl(tools[ti])) {
236
+ truncated = {
237
+ model: obj.model,
238
+ tools: tools.slice(0, ti + 1),
239
+ messages: [{ role: 'user', content: 'x' }],
240
+ };
241
+ break;
242
+ }
243
+ }
244
+ }
245
+ if (truncated == null)
246
+ return null;
247
+ truncated = prependSyntheticToolUses(appendSyntheticToolResults(truncated));
248
+ const out = {};
249
+ for (const k of Object.keys(truncated)) {
250
+ if (COUNT_TOKENS_FIELDS.has(k))
251
+ out[k] = truncated[k];
252
+ }
253
+ return new TextEncoder().encode(JSON.stringify(out));
254
+ }
255
+ /** Count cache_control markers anywhere in an Anthropic Messages body. */
256
+ export function countCacheControlMarkers(bytes) {
257
+ const b = toUint8Array(bytes);
258
+ try {
259
+ return countCacheControlValue(JSON.parse(new TextDecoder().decode(b)));
260
+ }
261
+ catch {
262
+ return 0;
263
+ }
264
+ }
265
+ function countCacheControlValue(value) {
266
+ if (!value || typeof value !== 'object')
267
+ return 0;
268
+ let n = hasCacheControl(value) ? 1 : 0;
269
+ if (Array.isArray(value)) {
270
+ for (const item of value)
271
+ n += countCacheControlValue(item);
272
+ }
273
+ else {
274
+ for (const item of Object.values(value)) {
275
+ n += countCacheControlValue(item);
276
+ }
277
+ }
278
+ return n;
279
+ }
280
+ //# sourceMappingURL=measurement.js.map
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Anthropic Messages wire compatibility for OpenAI Chat Completions upstreams.
3
+ *
4
+ * Lets Claude Code (which only speaks the Anthropic /v1/messages schema) drive
5
+ * Kimi through Cloudflare's OpenAI-compatible Chat Completions endpoint. This
6
+ * module is pure wire translation and contains no credentials.
7
+ *
8
+ * Mirrors messages-responses-bridge.ts, but targets /v1/chat/completions rather
9
+ * than the Responses API.
10
+ */
11
+ type JsonObject = Record<string, unknown>;
12
+ /** Convert a Claude Code Messages request into an OpenAI Chat Completions request. */
13
+ export declare function anthropicMessagesToOpenAIChat(body: Uint8Array, modelOverride?: string): Uint8Array;
14
+ /** Convert one completed Chat Completions JSON object into Anthropic Messages JSON. */
15
+ export declare function openAIChatToAnthropicMessage(response: unknown, fallbackModel: string): JsonObject;
16
+ export declare function openAIChatStreamToAnthropic(body: ReadableStream<Uint8Array>, fallbackModel: string): ReadableStream<Uint8Array>;
17
+ /** Translate a Chat Completions HTTP response to the Messages wire format. */
18
+ export declare function openAIChatToAnthropicResponse(response: Response, fallbackModel: string): Promise<Response>;
19
+ /** Build the chat-completions endpoint URL from a user-supplied base. Accepts a
20
+ * bare host, a `/v1` base, or the full `/chat/completions` URL. */
21
+ export declare function chatCompletionsUrl(base: string): string;
22
+ export {};
23
+ //# sourceMappingURL=messages-chat-bridge.d.ts.map