@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.
- package/CHANGELOG.md +134 -0
- package/LICENSE +22 -0
- package/NOTICE +13 -0
- package/PRIVACY.md +41 -0
- package/README.md +288 -2
- package/SECURITY.md +53 -0
- package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
- package/assets/SPLEEN_LICENSE.txt +24 -0
- package/assets/UNIFONT_LICENSE.txt +476 -0
- package/assets/fiche-logo-dark.svg +61 -0
- package/assets/fiche-logo-light.svg +61 -0
- package/assets/fiche-logo.svg +71 -0
- package/assets/fiche-mark.svg +48 -0
- package/bin/cli.js +7 -0
- package/bin/mcp.js +8 -0
- package/dist/calibrate.d.ts +30 -0
- package/dist/calibrate.js +588 -0
- package/dist/core/anthropic-vision.d.ts +28 -0
- package/dist/core/anthropic-vision.js +34 -0
- package/dist/core/applicability.d.ts +63 -0
- package/dist/core/applicability.js +151 -0
- package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono10.js +64 -0
- package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono12.js +64 -0
- package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono14.js +64 -0
- package/dist/core/atlas-gray.d.ts +26 -0
- package/dist/core/atlas-gray.js +64 -0
- package/dist/core/atlas-jbmono10.d.ts +34 -0
- package/dist/core/atlas-jbmono10.js +71 -0
- package/dist/core/atlas-jbmono12.d.ts +34 -0
- package/dist/core/atlas-jbmono12.js +71 -0
- package/dist/core/atlas-jbmono14.d.ts +34 -0
- package/dist/core/atlas-jbmono14.js +71 -0
- package/dist/core/atlas.d.ts +34 -0
- package/dist/core/atlas.js +71 -0
- package/dist/core/baseline.d.ts +121 -0
- package/dist/core/baseline.js +200 -0
- package/dist/core/calibration.d.ts +86 -0
- package/dist/core/calibration.js +547 -0
- package/dist/core/casi-delta.d.ts +63 -0
- package/dist/core/casi-delta.js +1271 -0
- package/dist/core/claude-model-profiles.d.ts +53 -0
- package/dist/core/claude-model-profiles.js +160 -0
- package/dist/core/client-tool-round.d.ts +31 -0
- package/dist/core/client-tool-round.js +58 -0
- package/dist/core/codex-cache.d.ts +20 -0
- package/dist/core/codex-cache.js +59 -0
- package/dist/core/context-mmu.d.ts +350 -0
- package/dist/core/context-mmu.js +3028 -0
- package/dist/core/cpt-fit.d.ts +70 -0
- package/dist/core/cpt-fit.js +197 -0
- package/dist/core/env.d.ts +8 -0
- package/dist/core/env.js +15 -0
- package/dist/core/export.d.ts +127 -0
- package/dist/core/export.js +385 -0
- package/dist/core/factsheet.d.ts +77 -0
- package/dist/core/factsheet.js +494 -0
- package/dist/core/gemini-model-profiles.d.ts +20 -0
- package/dist/core/gemini-model-profiles.js +134 -0
- package/dist/core/google.d.ts +76 -0
- package/dist/core/google.js +1380 -0
- package/dist/core/gpt-model-profiles.d.ts +218 -0
- package/dist/core/gpt-model-profiles.js +570 -0
- package/dist/core/gpt-tokens.d.ts +14 -0
- package/dist/core/gpt-tokens.js +165 -0
- package/dist/core/history.d.ts +197 -0
- package/dist/core/history.js +1003 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.js +16 -0
- package/dist/core/library.d.ts +80 -0
- package/dist/core/library.js +131 -0
- package/dist/core/measurement.d.ts +34 -0
- package/dist/core/measurement.js +280 -0
- package/dist/core/messages-chat-bridge.d.ts +23 -0
- package/dist/core/messages-chat-bridge.js +747 -0
- package/dist/core/messages-responses-bridge.d.ts +11 -0
- package/dist/core/messages-responses-bridge.js +893 -0
- package/dist/core/openai-history.d.ts +184 -0
- package/dist/core/openai-history.js +1279 -0
- package/dist/core/openai-savings.d.ts +57 -0
- package/dist/core/openai-savings.js +116 -0
- package/dist/core/openai.d.ts +68 -0
- package/dist/core/openai.js +2523 -0
- package/dist/core/pin.d.ts +199 -0
- package/dist/core/pin.js +1353 -0
- package/dist/core/png.d.ts +14 -0
- package/dist/core/png.js +188 -0
- package/dist/core/prefix-tape.d.ts +102 -0
- package/dist/core/prefix-tape.js +315 -0
- package/dist/core/price-id.d.ts +10 -0
- package/dist/core/price-id.js +26 -0
- package/dist/core/prices.generated.d.ts +36 -0
- package/dist/core/prices.generated.js +369 -0
- package/dist/core/pricing.d.ts +134 -0
- package/dist/core/pricing.js +335 -0
- package/dist/core/profile-base.d.ts +30 -0
- package/dist/core/profile-base.js +67 -0
- package/dist/core/provider-router.d.ts +51 -0
- package/dist/core/provider-router.js +121 -0
- package/dist/core/proxy.d.ts +252 -0
- package/dist/core/proxy.js +2929 -0
- package/dist/core/reader-tier.d.ts +24 -0
- package/dist/core/reader-tier.js +118 -0
- package/dist/core/render.d.ts +280 -0
- package/dist/core/render.js +1302 -0
- package/dist/core/request-guard.d.ts +31 -0
- package/dist/core/request-guard.js +126 -0
- package/dist/core/request-transform.d.ts +43 -0
- package/dist/core/request-transform.js +173 -0
- package/dist/core/schema-compiler.d.ts +64 -0
- package/dist/core/schema-compiler.js +1696 -0
- package/dist/core/schema-strip.d.ts +29 -0
- package/dist/core/schema-strip.js +173 -0
- package/dist/core/session-state.d.ts +219 -0
- package/dist/core/session-state.js +929 -0
- package/dist/core/stage-plugins.d.ts +45 -0
- package/dist/core/stage-plugins.js +205 -0
- package/dist/core/text-history.d.ts +74 -0
- package/dist/core/text-history.js +612 -0
- package/dist/core/text-hygiene.d.ts +160 -0
- package/dist/core/text-hygiene.js +2259 -0
- package/dist/core/toon.d.ts +29 -0
- package/dist/core/toon.js +425 -0
- package/dist/core/tracker.d.ts +223 -0
- package/dist/core/tracker.js +290 -0
- package/dist/core/transform.d.ts +589 -0
- package/dist/core/transform.js +3153 -0
- package/dist/core/types.d.ts +87 -0
- package/dist/core/types.js +8 -0
- package/dist/core/upstream-hosts.d.ts +127 -0
- package/dist/core/upstream-hosts.js +398 -0
- package/dist/core/vision-cost.d.ts +63 -0
- package/dist/core/vision-cost.js +137 -0
- package/dist/dashboard/fragments.d.ts +87 -0
- package/dist/dashboard/fragments.js +1515 -0
- package/dist/dashboard/types.d.ts +217 -0
- package/dist/dashboard/types.js +3 -0
- package/dist/dashboard/vendor.d.ts +3 -0
- package/dist/dashboard/vendor.js +6 -0
- package/dist/dashboard.d.ts +372 -0
- package/dist/dashboard.js +2731 -0
- package/dist/export-collect.d.ts +36 -0
- package/dist/export-collect.js +59 -0
- package/dist/file-tracker.d.ts +42 -0
- package/dist/file-tracker.js +234 -0
- package/dist/kosha-sync.d.ts +74 -0
- package/dist/kosha-sync.js +272 -0
- package/dist/launchd-socket.d.ts +22 -0
- package/dist/launchd-socket.js +210 -0
- package/dist/mcp/cli.d.ts +2 -0
- package/dist/mcp/cli.js +55 -0
- package/dist/mcp/server.d.ts +48 -0
- package/dist/mcp/server.js +987 -0
- package/dist/mmu-store.d.ts +31 -0
- package/dist/mmu-store.js +179 -0
- package/dist/node-fetch.d.ts +22 -0
- package/dist/node-fetch.js +489 -0
- package/dist/node.d.ts +9 -0
- package/dist/node.js +244396 -0
- package/dist/request-decoding.d.ts +30 -0
- package/dist/request-decoding.js +85 -0
- package/dist/sessions.d.ts +179 -0
- package/dist/sessions.js +837 -0
- package/dist/stats.d.ts +114 -0
- package/dist/stats.js +439 -0
- package/dist/turn-report.d.ts +65 -0
- package/dist/turn-report.js +724 -0
- package/dist/warp/app-launch.d.ts +26 -0
- package/dist/warp/app-launch.js +155 -0
- package/dist/warp/ca.d.ts +74 -0
- package/dist/warp/ca.js +416 -0
- package/dist/warp/connect.d.ts +42 -0
- package/dist/warp/connect.js +686 -0
- package/dist/warp/der.d.ts +57 -0
- package/dist/warp/der.js +151 -0
- package/dist/warp/index.d.ts +79 -0
- package/dist/warp/index.js +650 -0
- package/dist/warp/resolve.d.ts +12 -0
- package/dist/warp/resolve.js +49 -0
- package/dist/warp/route.d.ts +71 -0
- package/dist/warp/route.js +134 -0
- package/dist/worker.d.ts +71 -0
- package/dist/worker.js +174 -0
- package/docs/SECURITY_MODEL.md +84 -0
- package/package.json +122 -4
- package/plugins/fiche-companion/README.md +42 -0
- package/plugins/fiche-companion/assets/logo.svg +48 -0
- package/plugins/fiche-companion/hooks.json +11 -0
- package/plugins/fiche-companion/mcp_config.json +8 -0
- package/plugins/fiche-companion/plugin.json +18 -0
- package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
- package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
- package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
- package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export interface RequestGuardOptions {
|
|
2
|
+
/** Extra Host/Origin names to accept (INKLING_ALLOWED_HOSTS). `*` disables the Host and Origin checks. */
|
|
3
|
+
allowedHosts?: readonly string[];
|
|
4
|
+
/** Provider hosts to trust as Host names; defaults to the built-in registry.
|
|
5
|
+
* The Node entry passes the registry extended by INKLING_UPSTREAM_HOSTS. */
|
|
6
|
+
providerHosts?: ReadonlySet<string>;
|
|
7
|
+
/** True when the caller presented a verified per-user loopback `x-fiche-warp-auth`
|
|
8
|
+
* secret from `fiche warp`, allowing warped desktop app Origins / Sec-Fetch-Site. */
|
|
9
|
+
warpAuthenticated?: boolean;
|
|
10
|
+
}
|
|
11
|
+
export interface RequestGuardDenial {
|
|
12
|
+
status: 403 | 421;
|
|
13
|
+
reason: 'cross_origin' | 'untrusted_host';
|
|
14
|
+
message: string;
|
|
15
|
+
}
|
|
16
|
+
/** Hostname from a Host header or URL authority, lowercased, without port or brackets. */
|
|
17
|
+
export declare function hostnameOf(authority: string): string;
|
|
18
|
+
export declare function isLoopbackHostname(host: string): boolean;
|
|
19
|
+
/** True when no public DNS name can resolve to this hostname on an attacker's say-so. */
|
|
20
|
+
export declare function isTrustedHostname(host: string, allowed?: readonly string[], providerHosts?: ReadonlySet<string>): boolean;
|
|
21
|
+
export declare function parseAllowedHosts(spec: string | undefined): string[];
|
|
22
|
+
/**
|
|
23
|
+
* `null` lets the request through. Applies to the proxy API only; the dashboard
|
|
24
|
+
* keeps its stricter loopback-and-same-origin rule.
|
|
25
|
+
*/
|
|
26
|
+
export declare function guardProxyRequest(headers: {
|
|
27
|
+
host?: string | null;
|
|
28
|
+
origin?: string | null;
|
|
29
|
+
secFetchSite?: string | null;
|
|
30
|
+
}, options?: RequestGuardOptions): RequestGuardDenial | null;
|
|
31
|
+
//# sourceMappingURL=request-guard.d.ts.map
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { DEFAULT_UPSTREAM_REGISTRY } from './upstream-hosts.js';
|
|
2
|
+
/**
|
|
3
|
+
* Who may talk to the local proxy API.
|
|
4
|
+
*
|
|
5
|
+
* The proxy forwards with the host's configured keys, so a web page that can
|
|
6
|
+
* reach 127.0.0.1 must not be able to spend them. Two browser-only attacks:
|
|
7
|
+
*
|
|
8
|
+
* - Cross-site request: a page on evil.example POSTs to 127.0.0.1:47821. The
|
|
9
|
+
* browser sends `Origin: https://evil.example`.
|
|
10
|
+
* - DNS rebinding: evil.example re-resolves to 127.0.0.1, so the page is
|
|
11
|
+
* "same-origin" and can read responses. The request carries
|
|
12
|
+
* `Host: evil.example:47821`.
|
|
13
|
+
*
|
|
14
|
+
* Agents (Claude Code, Codex, curl) send no Origin, and a Host that is loopback,
|
|
15
|
+
* an IP literal, a container name, or the real provider host when `inkling warp`
|
|
16
|
+
* diverts traffic (warp keeps the agent's original Host on purpose).
|
|
17
|
+
*
|
|
18
|
+
* So the rule rejects only what an attacker can actually produce: a dotted
|
|
19
|
+
* public DNS name that is not a known provider host. Single-label names
|
|
20
|
+
* (`inkling`, a compose service) and `*.internal` / `*.localhost` cannot be
|
|
21
|
+
* registered publicly, so they cannot be rebound.
|
|
22
|
+
*/
|
|
23
|
+
/** Provider hosts an agent under `inkling warp` may name as Host. Derived from
|
|
24
|
+
* the upstream registry so the guard and the router cannot drift apart. */
|
|
25
|
+
const PROVIDER_HOSTS = new Set(DEFAULT_UPSTREAM_REGISTRY.keys());
|
|
26
|
+
/** Hostname from a Host header or URL authority, lowercased, without port or brackets. */
|
|
27
|
+
export function hostnameOf(authority) {
|
|
28
|
+
const value = authority.trim().toLowerCase();
|
|
29
|
+
if (value.startsWith('[')) {
|
|
30
|
+
const end = value.indexOf(']');
|
|
31
|
+
return end > 0 ? value.slice(1, end) : value;
|
|
32
|
+
}
|
|
33
|
+
// A bare IPv6 literal has several colons and no port.
|
|
34
|
+
if ((value.match(/:/g) ?? []).length > 1)
|
|
35
|
+
return value;
|
|
36
|
+
const colon = value.indexOf(':');
|
|
37
|
+
return (colon >= 0 ? value.slice(0, colon) : value).replace(/\.$/, '');
|
|
38
|
+
}
|
|
39
|
+
function isIpLiteral(host) {
|
|
40
|
+
if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host))
|
|
41
|
+
return true;
|
|
42
|
+
return host.includes(':') && /^[0-9a-f:.]+$/.test(host);
|
|
43
|
+
}
|
|
44
|
+
export function isLoopbackHostname(host) {
|
|
45
|
+
return host === 'localhost' || host.endsWith('.localhost') || host === '::1'
|
|
46
|
+
|| /^127(?:\.\d{1,3}){3}$/.test(host);
|
|
47
|
+
}
|
|
48
|
+
/** True when no public DNS name can resolve to this hostname on an attacker's say-so. */
|
|
49
|
+
export function isTrustedHostname(host, allowed = [], providerHosts = PROVIDER_HOSTS) {
|
|
50
|
+
if (host === '')
|
|
51
|
+
return true; // HTTP/1.0 without Host: nothing to rebind
|
|
52
|
+
if (allowed.includes(host))
|
|
53
|
+
return true;
|
|
54
|
+
if (host === 'localhost' || host.endsWith('.localhost'))
|
|
55
|
+
return true;
|
|
56
|
+
if (isIpLiteral(host))
|
|
57
|
+
return true;
|
|
58
|
+
if (!host.includes('.'))
|
|
59
|
+
return true; // single label: container, compose service
|
|
60
|
+
if (host.endsWith('.internal'))
|
|
61
|
+
return true; // host.docker.internal and friends
|
|
62
|
+
return providerHosts.has(host);
|
|
63
|
+
}
|
|
64
|
+
export function parseAllowedHosts(spec) {
|
|
65
|
+
if (!spec)
|
|
66
|
+
return [];
|
|
67
|
+
return spec
|
|
68
|
+
.split(',')
|
|
69
|
+
.map((s) => hostnameOf(s.trim().replace(/^[a-z][a-z0-9+.-]*:\/\//i, '').split(/[/?#]/, 1)[0] ?? ''))
|
|
70
|
+
.filter((s) => s !== '');
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* `null` lets the request through. Applies to the proxy API only; the dashboard
|
|
74
|
+
* keeps its stricter loopback-and-same-origin rule.
|
|
75
|
+
*/
|
|
76
|
+
export function guardProxyRequest(headers, options = {}) {
|
|
77
|
+
const allowed = options.allowedHosts ?? [];
|
|
78
|
+
if (allowed.includes('*'))
|
|
79
|
+
return null;
|
|
80
|
+
if (!options.warpAuthenticated) {
|
|
81
|
+
const fetchSite = typeof headers.secFetchSite === 'string'
|
|
82
|
+
? headers.secFetchSite.trim().toLowerCase()
|
|
83
|
+
: '';
|
|
84
|
+
if (fetchSite === 'cross-site') {
|
|
85
|
+
return {
|
|
86
|
+
status: 403,
|
|
87
|
+
reason: 'cross_origin',
|
|
88
|
+
message: 'fiche: cross-site browser request refused; set FICHE_ALLOWED_HOSTS=* to allow it',
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
const origin = headers.origin;
|
|
92
|
+
if (origin !== undefined && origin !== null) {
|
|
93
|
+
let originHost;
|
|
94
|
+
try {
|
|
95
|
+
const parsedOrigin = new URL(origin);
|
|
96
|
+
if (parsedOrigin.protocol === 'http:' || parsedOrigin.protocol === 'https:') {
|
|
97
|
+
originHost = parsedOrigin.hostname.replace(/^\[|\]$/g, '').toLowerCase();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
originHost = undefined; // `Origin: null` (sandboxed iframe, file://) lands here
|
|
102
|
+
}
|
|
103
|
+
// A page origin must be loopback: an attacker can serve a page from a raw
|
|
104
|
+
// public IP or any name, and a provider is never a page. Non-http(s) desktop
|
|
105
|
+
// origins (e.g. vscode-file://) require warpAuthenticated.
|
|
106
|
+
const ok = originHost !== undefined && (isLoopbackHostname(originHost) || allowed.includes(originHost));
|
|
107
|
+
if (!ok) {
|
|
108
|
+
return {
|
|
109
|
+
status: 403,
|
|
110
|
+
reason: 'cross_origin',
|
|
111
|
+
message: `fiche: browser request from ${origin} refused; set FICHE_ALLOWED_HOSTS to allow it`,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const host = hostnameOf(headers.host ?? '');
|
|
117
|
+
if (!isTrustedHostname(host, allowed, options.providerHosts)) {
|
|
118
|
+
return {
|
|
119
|
+
status: 421,
|
|
120
|
+
reason: 'untrusted_host',
|
|
121
|
+
message: `fiche: Host ${host} refused (possible DNS rebinding); set FICHE_ALLOWED_HOSTS to allow it`,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
//# sourceMappingURL=request-guard.js.map
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { type PromptCacheRoute } from './codex-cache.js';
|
|
2
|
+
import { type ReaderTier } from './reader-tier.js';
|
|
3
|
+
import { type TransformInfo, type TransformOptions } from './transform.js';
|
|
4
|
+
export type RequestWire = 'anthropic' | 'responses' | 'chat' | 'google' | 'auto';
|
|
5
|
+
export interface RequestReport {
|
|
6
|
+
readerTier: ReaderTier;
|
|
7
|
+
imaged: boolean;
|
|
8
|
+
textCompressed?: boolean;
|
|
9
|
+
textStages?: string[];
|
|
10
|
+
/** Estimated (o200k) text tokens of the incoming body. */
|
|
11
|
+
originalTokens: number;
|
|
12
|
+
imageTokens: number;
|
|
13
|
+
/** Text tokens of the outgoing body with image payloads stripped, plus image tokens. */
|
|
14
|
+
billableTokens: number;
|
|
15
|
+
savedVsOriginal: number;
|
|
16
|
+
savedPercent: number;
|
|
17
|
+
promptCacheBreakpoint: boolean;
|
|
18
|
+
reason?: string;
|
|
19
|
+
}
|
|
20
|
+
export interface RequestTransformOptions extends TransformOptions {
|
|
21
|
+
wire?: RequestWire;
|
|
22
|
+
/** ChatGPT Codex / chatgpt.com must pass false. */
|
|
23
|
+
explicitPromptCacheBreakpoints?: boolean;
|
|
24
|
+
/** When set, used only to decide the breakpoint ban. */
|
|
25
|
+
route?: PromptCacheRoute;
|
|
26
|
+
/** Per-call override. Does not read or write INKLING_FORCE_IMAGES. */
|
|
27
|
+
forceImages?: boolean;
|
|
28
|
+
}
|
|
29
|
+
/** Estimate only: o200k on the body with base64 image payloads stripped. */
|
|
30
|
+
export declare function countBillable(body: Uint8Array | string, imageTokens?: number): number;
|
|
31
|
+
/**
|
|
32
|
+
* Transforms an LLM request across any supported wire format:
|
|
33
|
+
* - `image` reader tier: renders bulky stale context optically + text hygiene.
|
|
34
|
+
* - `text` reader tier: runs 4-layer deterministic text compilation (TSCG+TOON+CASI+ACDC)
|
|
35
|
+
* with zero image rendering (`imageCompress: false`).
|
|
36
|
+
* Leaves clean payloads byte-identical (except explicit Codex breakpoint scrubbing).
|
|
37
|
+
*/
|
|
38
|
+
export declare function transformAnyRequest(body: Uint8Array, options?: RequestTransformOptions): Promise<{
|
|
39
|
+
body: Uint8Array;
|
|
40
|
+
info: TransformInfo;
|
|
41
|
+
report: RequestReport;
|
|
42
|
+
}>;
|
|
43
|
+
//# sourceMappingURL=request-transform.d.ts.map
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One entry point for any wire format (Anthropic Messages, OpenAI Responses,
|
|
3
|
+
* Chat Completions, Gemini generateContent). It detects the wire, images bulky
|
|
4
|
+
* context only for readers that can read it, keeps prompt_cache_breakpoint off
|
|
5
|
+
* Codex routes, and reports estimated billable tokens before and after.
|
|
6
|
+
*
|
|
7
|
+
* The proxy has its own per-route wiring; the MCP server and scripts use this.
|
|
8
|
+
*/
|
|
9
|
+
import { gptTokenCount as o200kCountTokens } from './gpt-tokens.js';
|
|
10
|
+
import { getAllowedModelBases, isFicheSupportedModel, isInConfiguredModelBases } from './applicability.js';
|
|
11
|
+
import { scrubPromptCacheBreakpoint, supportsExplicitPromptCacheBreakpoint } from './codex-cache.js';
|
|
12
|
+
import { transformOpenAIChatCompletions, transformOpenAIResponses } from './openai.js';
|
|
13
|
+
import { transformGoogleGenerateContent } from './google.js';
|
|
14
|
+
import { shouldImageModel } from './reader-tier.js';
|
|
15
|
+
import { isTextHygieneActive, resolveTextHygieneMode } from './text-hygiene.js';
|
|
16
|
+
import { transformRequest } from './transform.js';
|
|
17
|
+
import { resolveGptProfile } from './gpt-model-profiles.js';
|
|
18
|
+
import { visionTokens } from './vision-cost.js';
|
|
19
|
+
const dec = new TextDecoder();
|
|
20
|
+
function isRecord(value) {
|
|
21
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
22
|
+
}
|
|
23
|
+
/** Estimate only: o200k on the body with base64 image payloads stripped. */
|
|
24
|
+
export function countBillable(body, imageTokens = 0) {
|
|
25
|
+
const text = typeof body === 'string' ? body : dec.decode(body);
|
|
26
|
+
const stripped = text
|
|
27
|
+
.replace(/data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=\s]+/gi, '"IMG"')
|
|
28
|
+
.replace(/"data"\s*:\s*"[A-Za-z0-9+/=]{80,}"/g, '"data":"IMG"');
|
|
29
|
+
return o200kCountTokens(stripped) + imageTokens;
|
|
30
|
+
}
|
|
31
|
+
function parseJsonObject(body) {
|
|
32
|
+
try {
|
|
33
|
+
const parsed = JSON.parse(dec.decode(body));
|
|
34
|
+
return isRecord(parsed) ? parsed : null;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function detectWireFromParsed(parsed, hinted) {
|
|
41
|
+
if (hinted && hinted !== 'auto')
|
|
42
|
+
return hinted;
|
|
43
|
+
if (!parsed)
|
|
44
|
+
return 'anthropic';
|
|
45
|
+
if (typeof parsed.instructions === 'string' || Array.isArray(parsed.input))
|
|
46
|
+
return 'responses';
|
|
47
|
+
if (parsed.systemInstruction || parsed.contents)
|
|
48
|
+
return 'google';
|
|
49
|
+
if (Array.isArray(parsed.messages)) {
|
|
50
|
+
if (parsed.system !== undefined)
|
|
51
|
+
return 'anthropic';
|
|
52
|
+
const blob = JSON.stringify(parsed.messages);
|
|
53
|
+
if (blob.includes('"tool_result"') || blob.includes('"tool_use"'))
|
|
54
|
+
return 'anthropic';
|
|
55
|
+
return 'chat';
|
|
56
|
+
}
|
|
57
|
+
return 'anthropic';
|
|
58
|
+
}
|
|
59
|
+
function modelFromGooglePathname(pathname) {
|
|
60
|
+
if (!pathname)
|
|
61
|
+
return undefined;
|
|
62
|
+
const m = /\/models\/([^/:]+):/.exec(pathname);
|
|
63
|
+
return m?.[1] ? decodeURIComponent(m[1]) : undefined;
|
|
64
|
+
}
|
|
65
|
+
function chargedImageTokens(info, model) {
|
|
66
|
+
if ((info.imageTokens ?? 0) > 0)
|
|
67
|
+
return info.imageTokens ?? 0;
|
|
68
|
+
const dims = info.imageDims ?? [];
|
|
69
|
+
if (dims.length === 0)
|
|
70
|
+
return 0;
|
|
71
|
+
const pricing = resolveGptProfile(model);
|
|
72
|
+
return dims.reduce((sum, dim) => sum + visionTokens(pricing, dim.width, dim.height), 0);
|
|
73
|
+
}
|
|
74
|
+
function allowBreakpoints(options) {
|
|
75
|
+
if (options.explicitPromptCacheBreakpoints === false)
|
|
76
|
+
return false;
|
|
77
|
+
if (options.route && !supportsExplicitPromptCacheBreakpoint(options.route))
|
|
78
|
+
return false;
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Transforms an LLM request across any supported wire format:
|
|
83
|
+
* - `image` reader tier: renders bulky stale context optically + text hygiene.
|
|
84
|
+
* - `text` reader tier: runs 4-layer deterministic text compilation (TSCG+TOON+CASI+ACDC)
|
|
85
|
+
* with zero image rendering (`imageCompress: false`).
|
|
86
|
+
* Leaves clean payloads byte-identical (except explicit Codex breakpoint scrubbing).
|
|
87
|
+
*/
|
|
88
|
+
export async function transformAnyRequest(body, options = {}) {
|
|
89
|
+
const parsed = parseJsonObject(body);
|
|
90
|
+
const wire = detectWireFromParsed(parsed, options.wire);
|
|
91
|
+
const bodyModel = typeof parsed?.model === 'string' && parsed.model.trim()
|
|
92
|
+
? parsed.model.trim()
|
|
93
|
+
: wire === 'google'
|
|
94
|
+
? modelFromGooglePathname(options.route?.pathname)
|
|
95
|
+
: undefined;
|
|
96
|
+
const model = options.model ?? bodyModel;
|
|
97
|
+
const inScope = model ? isFicheSupportedModel(model) : false;
|
|
98
|
+
const familyInScope = inScope || (model ? isInConfiguredModelBases(model) : false);
|
|
99
|
+
const hygieneMode = resolveTextHygieneMode(options.textHygiene);
|
|
100
|
+
const hygieneActive = isTextHygieneActive(options.textHygiene);
|
|
101
|
+
const imageThisRequest = options.compress !== false &&
|
|
102
|
+
options.stageToggles?.optical !== false &&
|
|
103
|
+
shouldImageModel(model, inScope, options.forceImages);
|
|
104
|
+
const tier = imageThisRequest ? 'image' : 'text';
|
|
105
|
+
const allow = allowBreakpoints(options);
|
|
106
|
+
const imageTier = imageThisRequest;
|
|
107
|
+
const canRunTextHygiene = hygieneActive &&
|
|
108
|
+
(hygieneMode === 'on' || familyInScope || getAllowedModelBases().length > 0);
|
|
109
|
+
const shouldRun = options.compress !== false && (imageTier || canRunTextHygiene);
|
|
110
|
+
let outBody = body;
|
|
111
|
+
let info = {
|
|
112
|
+
compressed: false,
|
|
113
|
+
reason: options.compress === false
|
|
114
|
+
? 'compress=false'
|
|
115
|
+
: !familyInScope && hygieneMode !== 'on' && !canRunTextHygiene
|
|
116
|
+
? 'unsupported_model'
|
|
117
|
+
: hygieneMode === 'off'
|
|
118
|
+
? 'text_hygiene_off'
|
|
119
|
+
: imageTier
|
|
120
|
+
? 'noop'
|
|
121
|
+
: 'weak_reader',
|
|
122
|
+
origChars: 0,
|
|
123
|
+
compressedChars: 0,
|
|
124
|
+
imageCount: 0,
|
|
125
|
+
imageBytes: 0,
|
|
126
|
+
staticChars: 0,
|
|
127
|
+
dynamicChars: 0,
|
|
128
|
+
dynamicBlockCount: 0,
|
|
129
|
+
droppedChars: 0,
|
|
130
|
+
};
|
|
131
|
+
if (shouldRun) {
|
|
132
|
+
const wireOpts = {
|
|
133
|
+
...options,
|
|
134
|
+
model,
|
|
135
|
+
imageCompress: imageTier,
|
|
136
|
+
explicitPromptCacheBreakpoints: allow,
|
|
137
|
+
};
|
|
138
|
+
const result = wire === 'responses'
|
|
139
|
+
? await transformOpenAIResponses(body, wireOpts)
|
|
140
|
+
: wire === 'chat'
|
|
141
|
+
? await transformOpenAIChatCompletions(body, wireOpts)
|
|
142
|
+
: wire === 'google'
|
|
143
|
+
? await transformGoogleGenerateContent(body, model ?? 'gemini', wireOpts)
|
|
144
|
+
: await transformRequest(body, wireOpts);
|
|
145
|
+
outBody = result.body;
|
|
146
|
+
info = result.info;
|
|
147
|
+
if (!imageTier && !info.compressed && (info.reason === 'image_disabled' || info.reason === 'unsupported_model')) {
|
|
148
|
+
info = { ...info, reason: 'weak_reader' };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (!allow)
|
|
152
|
+
outBody = scrubPromptCacheBreakpoint(outBody);
|
|
153
|
+
const imageTokens = chargedImageTokens(info, model);
|
|
154
|
+
const originalTokens = countBillable(body);
|
|
155
|
+
const billableTokens = countBillable(outBody, imageTokens);
|
|
156
|
+
const savedVsOriginal = originalTokens - billableTokens;
|
|
157
|
+
const textStages = info.textHygieneStages ? [...info.textHygieneStages] : undefined;
|
|
158
|
+
const textCompressed = (info.textHygieneSavedTokens ?? 0) > 0 || Boolean(textStages && textStages.length > 0);
|
|
159
|
+
const report = {
|
|
160
|
+
readerTier: tier,
|
|
161
|
+
imaged: imageTier && info.imageCount > 0,
|
|
162
|
+
...(textCompressed ? { textCompressed: true, textStages } : {}),
|
|
163
|
+
originalTokens,
|
|
164
|
+
imageTokens,
|
|
165
|
+
billableTokens,
|
|
166
|
+
savedVsOriginal,
|
|
167
|
+
savedPercent: originalTokens > 0 ? Math.round((savedVsOriginal / originalTokens) * 1000) / 10 : 0,
|
|
168
|
+
promptCacheBreakpoint: dec.decode(outBody).includes('"prompt_cache_breakpoint"'),
|
|
169
|
+
reason: info.reason,
|
|
170
|
+
};
|
|
171
|
+
return { body: outBody, info, report };
|
|
172
|
+
}
|
|
173
|
+
//# sourceMappingURL=request-transform.js.map
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TSCG: Deterministic Tool-Schema & Static-Prompt Compiler.
|
|
3
|
+
*
|
|
4
|
+
* Grounded in:
|
|
5
|
+
* - TSCG (2026): lossless schema metadata compilation removes bloat ($schema,
|
|
6
|
+
* $comment, redundant titles, decorative whitespace, cross-tool repeated
|
|
7
|
+
* boilerplate) without altering tool names, parameter types, required fields,
|
|
8
|
+
* enums, constraints, or strictness.
|
|
9
|
+
* - CAPC (2026): strictly query-agnostic so compiled static prefixes produce
|
|
10
|
+
* identical bytes across every turn of a session (zero prefix-cache busts).
|
|
11
|
+
*
|
|
12
|
+
* Workers-safe: zero `node:` imports.
|
|
13
|
+
*/
|
|
14
|
+
export type ToolSchemaWire = 'anthropic' | 'openai_chat' | 'openai_responses' | 'google';
|
|
15
|
+
export interface CompileResult {
|
|
16
|
+
readonly changed: boolean;
|
|
17
|
+
readonly savedChars: number;
|
|
18
|
+
readonly savedTokens: number;
|
|
19
|
+
readonly schemaDagFactored?: boolean;
|
|
20
|
+
}
|
|
21
|
+
export interface CompileTextResult extends CompileResult {
|
|
22
|
+
readonly text: string;
|
|
23
|
+
}
|
|
24
|
+
export declare function clearSchemaCompilerCachesForTests(): void;
|
|
25
|
+
export interface VolatileXmlIsland {
|
|
26
|
+
readonly volatile: boolean;
|
|
27
|
+
readonly text: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Linear O(N) scanner splitting dynamic/volatile XML prompt islands
|
|
31
|
+
* (`<env>`, `<context>`, `<system-reminder>`, `<fast_mode_info>`, `<git_status>`,
|
|
32
|
+
* `<ADDITIONAL_METADATA>`) from surrounding static prose.
|
|
33
|
+
* Skips fenced code blocks and inline backtick spans, tracks same-tag nesting
|
|
34
|
+
* depth, and fails open as volatile on unclosed tags.
|
|
35
|
+
*/
|
|
36
|
+
export declare function splitVolatileXmlIslands(text: string): VolatileXmlIsland[];
|
|
37
|
+
/**
|
|
38
|
+
* Bottom-up Merkle subtree factoring across non-Google tool schemas.
|
|
39
|
+
* Hoists identical JSON Schema subtrees (`JSON.stringify(node).length >= 220`,
|
|
40
|
+
* occurring `>= 2` times inside one tool's schema) into `schema.$defs._f1.._fN`
|
|
41
|
+
* without colliding with existing `$defs` keys, replacing repeated occurrences
|
|
42
|
+
* with `{ $ref: '#/$defs/_fN' }`. Keeps a tool's rewrite only when serialized
|
|
43
|
+
* tool JSON shrinks by `>= 120` chars.
|
|
44
|
+
*/
|
|
45
|
+
export declare function factorSharedSchemaSubtrees(candidate: unknown): boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Compile tool definitions & JSON schemas deterministically in place.
|
|
48
|
+
* Only writes back to `tools` when net savings are >=200 chars & >=40 tokens.
|
|
49
|
+
*/
|
|
50
|
+
export declare function compileToolSchemas(tools: unknown[] | undefined, wire: ToolSchemaWire): CompileResult;
|
|
51
|
+
/**
|
|
52
|
+
* Compile multi-line static system/instruction prose deterministically.
|
|
53
|
+
* Leaves single-line text, OAuth identity lines, billing headers, inline code
|
|
54
|
+
* spans, and fenced code blocks verbatim untouched.
|
|
55
|
+
*/
|
|
56
|
+
export declare function compileStaticText(text: string): CompileTextResult;
|
|
57
|
+
/**
|
|
58
|
+
* Compile multi-line static prompt prose while preserving volatile XML islands
|
|
59
|
+
* (`<env>`, `<context>`, `<system-reminder>`, `<fast_mode_info>`, `<git_status>`,
|
|
60
|
+
* `<ADDITIONAL_METADATA>`) and fenced code blocks byte-identical.
|
|
61
|
+
* Deduplicates repeated paragraphs across non-volatile static islands (`#S1`, `#S2`, ...).
|
|
62
|
+
*/
|
|
63
|
+
export declare function compileSegmentedStaticText(text: string): CompileTextResult;
|
|
64
|
+
//# sourceMappingURL=schema-compiler.d.ts.map
|