codex-sift 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +236 -2
- package/dist/catalog.d.ts +19 -0
- package/dist/catalog.js +68 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +106 -0
- package/dist/demo.d.ts +2 -0
- package/dist/demo.js +33 -0
- package/dist/doctor.d.ts +1 -0
- package/dist/doctor.js +49 -0
- package/dist/e2e.d.ts +24 -0
- package/dist/e2e.js +225 -0
- package/dist/env.d.ts +3 -0
- package/dist/env.js +42 -0
- package/dist/explain.d.ts +1 -0
- package/dist/explain.js +29 -0
- package/dist/expr.d.ts +2 -0
- package/dist/expr.js +210 -0
- package/dist/jev.d.ts +23 -0
- package/dist/jev.js +156 -0
- package/dist/launch.d.ts +4 -0
- package/dist/launch.js +155 -0
- package/dist/log.d.ts +10 -0
- package/dist/log.js +33 -0
- package/dist/menu.d.ts +15 -0
- package/dist/menu.js +42 -0
- package/dist/policy.d.ts +20 -0
- package/dist/policy.js +179 -0
- package/dist/proxy.d.ts +7 -0
- package/dist/proxy.js +132 -0
- package/dist/redact.d.ts +1 -0
- package/dist/redact.js +21 -0
- package/dist/report.d.ts +1 -0
- package/dist/report.js +38 -0
- package/dist/setup.d.ts +10 -0
- package/dist/setup.js +125 -0
- package/dist/turns.d.ts +15 -0
- package/dist/turns.js +137 -0
- package/dist/types.d.ts +56 -0
- package/dist/types.js +2 -0
- package/dist/upstream.d.ts +16 -0
- package/dist/upstream.js +120 -0
- package/dist/usage.d.ts +21 -0
- package/dist/usage.js +62 -0
- package/package.json +53 -4
- package/policy.yaml +76 -0
- package/scripts/statusline.js +13 -0
- package/skills/sift-explain/SKILL.md +16 -0
package/dist/proxy.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import { URL } from "node:url";
|
|
3
|
+
import { injectIntoUnknown } from "./catalog.js";
|
|
4
|
+
import { decideTurn } from "./jev.js";
|
|
5
|
+
import { writeDecision } from "./log.js";
|
|
6
|
+
import { conversationKey, hasImage, isNewUserTurn, lastUserText, requestModel, rewriteModel, } from "./turns.js";
|
|
7
|
+
import { classifyPath, detectAuthMode, forwardHeaders, pipeUpstream, readIncoming, requestUpstream, upstreamFor, } from "./upstream.js";
|
|
8
|
+
function readBody(req) {
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
const chunks = [];
|
|
11
|
+
req.on("data", (c) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
|
|
12
|
+
req.on("end", () => resolve(Buffer.concat(chunks)));
|
|
13
|
+
req.on("error", reject);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
function json(res, status, payload) {
|
|
17
|
+
const body = Buffer.from(JSON.stringify(payload));
|
|
18
|
+
res.writeHead(status, {
|
|
19
|
+
"content-type": "application/json",
|
|
20
|
+
"content-length": body.length,
|
|
21
|
+
});
|
|
22
|
+
res.end(body);
|
|
23
|
+
}
|
|
24
|
+
export function startProxy(policy) {
|
|
25
|
+
const sessions = new Map();
|
|
26
|
+
const server = http.createServer(async (req, res) => {
|
|
27
|
+
try {
|
|
28
|
+
await handle(req, res, policy, sessions);
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
32
|
+
if (!res.headersSent) {
|
|
33
|
+
res.writeHead(500, { "content-type": "text/plain" });
|
|
34
|
+
res.end(`sift proxy error: ${message}`);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
res.end();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
return new Promise((resolve, reject) => {
|
|
42
|
+
server.listen(0, "127.0.0.1", () => {
|
|
43
|
+
const addr = server.address();
|
|
44
|
+
if (!addr || typeof addr === "string") {
|
|
45
|
+
reject(new Error("Failed to bind loopback proxy"));
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
resolve({
|
|
49
|
+
server,
|
|
50
|
+
port: addr.port,
|
|
51
|
+
url: `http://127.0.0.1:${addr.port}`,
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
server.on("error", reject);
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
async function handle(req, res, policy, sessions) {
|
|
58
|
+
const incoming = new URL(req.url || "/", "http://127.0.0.1");
|
|
59
|
+
const kind = classifyPath(incoming.pathname);
|
|
60
|
+
const mode = detectAuthMode(req.headers);
|
|
61
|
+
const target = upstreamFor(mode, incoming.pathname, incoming.search);
|
|
62
|
+
const targetUrl = new URL(target.path, target.origin);
|
|
63
|
+
const method = req.method || "GET";
|
|
64
|
+
if (kind !== "responses") {
|
|
65
|
+
const body = method === "GET" || method === "HEAD" ? undefined : await readBody(req);
|
|
66
|
+
if (kind === "models" && method === "GET") {
|
|
67
|
+
await proxyModels(req, res, targetUrl, policy);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
pipeUpstream(targetUrl, method, forwardHeaders(req.headers, targetUrl.host), body, req, res);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const raw = await readBody(req);
|
|
74
|
+
let parsed = {};
|
|
75
|
+
try {
|
|
76
|
+
parsed = JSON.parse(raw.toString("utf8") || "{}");
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
pipeUpstream(targetUrl, method, forwardHeaders(req.headers, targetUrl.host), raw, req, res);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const virtual = policy.virtual_model.slug;
|
|
83
|
+
const model = requestModel(parsed);
|
|
84
|
+
const key = conversationKey(parsed);
|
|
85
|
+
const pin = sessions.get(key);
|
|
86
|
+
let outbound = parsed;
|
|
87
|
+
let decision = null;
|
|
88
|
+
if (model && model !== virtual) {
|
|
89
|
+
// User pinned a real model in /model. Do not route.
|
|
90
|
+
}
|
|
91
|
+
else if (!isNewUserTurn(parsed) && pin) {
|
|
92
|
+
outbound = rewriteModel(parsed, pin.decision.model, pin.decision.effort);
|
|
93
|
+
decision = pin.decision;
|
|
94
|
+
}
|
|
95
|
+
else if (model === virtual || !model) {
|
|
96
|
+
const prompt = lastUserText(parsed);
|
|
97
|
+
const retry = Boolean(pin && pin.decision.lane === "flash");
|
|
98
|
+
decision = await decideTurn(policy, prompt, {
|
|
99
|
+
hasImage: hasImage(parsed),
|
|
100
|
+
retry,
|
|
101
|
+
previousLane: pin?.decision.lane,
|
|
102
|
+
});
|
|
103
|
+
outbound = rewriteModel(parsed, decision.model, decision.effort);
|
|
104
|
+
sessions.set(key, { conversationKey: key, lastUserText: prompt, decision });
|
|
105
|
+
writeDecision(decision, prompt);
|
|
106
|
+
}
|
|
107
|
+
const payload = Buffer.from(JSON.stringify(outbound));
|
|
108
|
+
const headers = forwardHeaders(req.headers, targetUrl.host);
|
|
109
|
+
headers["content-length"] = payload.length;
|
|
110
|
+
headers["content-type"] = "application/json";
|
|
111
|
+
pipeUpstream(targetUrl, method, headers, payload, req, res);
|
|
112
|
+
void decision;
|
|
113
|
+
}
|
|
114
|
+
async function proxyModels(req, res, targetUrl, policy) {
|
|
115
|
+
try {
|
|
116
|
+
const up = await requestUpstream(targetUrl, "GET", forwardHeaders(req.headers, targetUrl.host));
|
|
117
|
+
const raw = await readIncoming(up);
|
|
118
|
+
try {
|
|
119
|
+
const parsed = JSON.parse(raw.toString("utf8") || "{}");
|
|
120
|
+
json(res, up.statusCode || 200, injectIntoUnknown(parsed, policy));
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
res.writeHead(up.statusCode || 200, up.headers);
|
|
124
|
+
res.end(raw);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
catch (err) {
|
|
128
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
129
|
+
res.writeHead(502, { "content-type": "text/plain" });
|
|
130
|
+
res.end(`sift models error: ${message}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
package/dist/redact.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function redact(text: string, max?: number): string;
|
package/dist/redact.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const PATTERNS = [
|
|
2
|
+
[/\bsk-[A-Za-z0-9_-]{12,}\b/g, "[redacted-openai-key]"],
|
|
3
|
+
[/\bts_[A-Za-z0-9_-]{8,}\b/g, "[redacted-typesafe-key]"],
|
|
4
|
+
[/\bghp_[A-Za-z0-9]{20,}\b/g, "[redacted-github-token]"],
|
|
5
|
+
[/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g, "[redacted-github-token]"],
|
|
6
|
+
[/\bAKIA[0-9A-Z]{12,}\b/g, "[redacted-aws-key]"],
|
|
7
|
+
[/\bBearer\s+[A-Za-z0-9._\-+/=]{12,}\b/gi, "Bearer [redacted]"],
|
|
8
|
+
[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "[redacted-private-key]"],
|
|
9
|
+
[/\b(postgres|mysql|mongodb|redis):\/\/[^\s'"]+/gi, "[redacted-db-url]"],
|
|
10
|
+
[/\b(api[_-]?key|secret|token|password|passwd)\s*[:=]\s*['"]?[^'"\s]+/gi, "$1=[redacted]"],
|
|
11
|
+
];
|
|
12
|
+
const MAX_CHARS = 4000;
|
|
13
|
+
export function redact(text, max = MAX_CHARS) {
|
|
14
|
+
let out = text || "";
|
|
15
|
+
for (const [re, replacement] of PATTERNS) {
|
|
16
|
+
out = out.replace(re, replacement);
|
|
17
|
+
}
|
|
18
|
+
if (out.length > max)
|
|
19
|
+
out = `${out.slice(0, max)}\n[truncated]`;
|
|
20
|
+
return out;
|
|
21
|
+
}
|
package/dist/report.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function runReport(argv?: string[]): number;
|
package/dist/report.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { loadPolicy } from "./policy.js";
|
|
2
|
+
import { readLog } from "./log.js";
|
|
3
|
+
import { formatUsage, summarizeUsage } from "./usage.js";
|
|
4
|
+
function parseSince(argv) {
|
|
5
|
+
const flag = argv.find((a) => a.startsWith("--since="));
|
|
6
|
+
if (!flag)
|
|
7
|
+
return null;
|
|
8
|
+
const raw = flag.slice("--since=".length);
|
|
9
|
+
if (raw === "today") {
|
|
10
|
+
const d = new Date();
|
|
11
|
+
d.setHours(0, 0, 0, 0);
|
|
12
|
+
return d;
|
|
13
|
+
}
|
|
14
|
+
const parsed = new Date(raw);
|
|
15
|
+
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
16
|
+
}
|
|
17
|
+
export function runReport(argv = []) {
|
|
18
|
+
const jsonMode = argv.includes("--json");
|
|
19
|
+
const liveOnly = argv.includes("--live");
|
|
20
|
+
const since = parseSince(argv);
|
|
21
|
+
const policy = loadPolicy();
|
|
22
|
+
let rows = readLog();
|
|
23
|
+
if (since)
|
|
24
|
+
rows = rows.filter((row) => new Date(row.at) >= since);
|
|
25
|
+
if (liveOnly)
|
|
26
|
+
rows = rows.filter((row) => !row.degraded);
|
|
27
|
+
if (!rows.length) {
|
|
28
|
+
process.stdout.write("No decisions logged yet. Use Codex through `codex-sift`, then rerun report.\n");
|
|
29
|
+
return 1;
|
|
30
|
+
}
|
|
31
|
+
const summary = summarizeUsage(policy, rows);
|
|
32
|
+
if (jsonMode) {
|
|
33
|
+
process.stdout.write(`${JSON.stringify({ summary, turns: rows.length }, null, 2)}\n`);
|
|
34
|
+
return 0;
|
|
35
|
+
}
|
|
36
|
+
process.stdout.write(`${formatUsage(summary)}\n`);
|
|
37
|
+
return 0;
|
|
38
|
+
}
|
package/dist/setup.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
type SetupArgs = {
|
|
2
|
+
flash?: string;
|
|
3
|
+
craft?: string;
|
|
4
|
+
forge?: string;
|
|
5
|
+
yes?: boolean;
|
|
6
|
+
};
|
|
7
|
+
export declare function parseSetupArgs(argv: string[]): SetupArgs;
|
|
8
|
+
export declare function runSetup(argv: string[]): Promise<number>;
|
|
9
|
+
export declare function runModels(): Promise<number>;
|
|
10
|
+
export {};
|
package/dist/setup.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { createInterface } from "node:readline/promises";
|
|
2
|
+
import { stdin as input, stdout as output } from "node:process";
|
|
3
|
+
import { loadBundledCatalog } from "./catalog.js";
|
|
4
|
+
import { writeLocalEnvKey } from "./env.js";
|
|
5
|
+
import { resolveCodexBin } from "./launch.js";
|
|
6
|
+
import { defaultLaneIndexes, formatModelMenu, listVisibleModels, parsePick } from "./menu.js";
|
|
7
|
+
import { applyLanePicks, loadPolicy, saveUserPolicy } from "./policy.js";
|
|
8
|
+
export function parseSetupArgs(argv) {
|
|
9
|
+
const out = {};
|
|
10
|
+
for (const arg of argv) {
|
|
11
|
+
if (arg === "--yes" || arg === "-y")
|
|
12
|
+
out.yes = true;
|
|
13
|
+
else if (arg.startsWith("--flash="))
|
|
14
|
+
out.flash = arg.slice("--flash=".length);
|
|
15
|
+
else if (arg.startsWith("--craft="))
|
|
16
|
+
out.craft = arg.slice("--craft=".length);
|
|
17
|
+
else if (arg.startsWith("--forge="))
|
|
18
|
+
out.forge = arg.slice("--forge=".length);
|
|
19
|
+
}
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
async function ask(rl, question, fallback) {
|
|
23
|
+
if (!rl)
|
|
24
|
+
return fallback;
|
|
25
|
+
const answer = await rl.question(question);
|
|
26
|
+
return answer.trim() || fallback;
|
|
27
|
+
}
|
|
28
|
+
async function askHidden(question) {
|
|
29
|
+
return new Promise((resolve) => {
|
|
30
|
+
const stdin = process.stdin;
|
|
31
|
+
process.stdout.write(question);
|
|
32
|
+
const wasRaw = stdin.isRaw;
|
|
33
|
+
if (stdin.isTTY)
|
|
34
|
+
stdin.setRawMode(true);
|
|
35
|
+
let value = "";
|
|
36
|
+
const onData = (chunk) => {
|
|
37
|
+
const text = chunk.toString("utf8");
|
|
38
|
+
if (text === "\n" || text === "\r") {
|
|
39
|
+
cleanup();
|
|
40
|
+
process.stdout.write("\n");
|
|
41
|
+
resolve(value);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (text === "\u0003") {
|
|
45
|
+
cleanup();
|
|
46
|
+
process.stdout.write("\n");
|
|
47
|
+
process.exit(1);
|
|
48
|
+
}
|
|
49
|
+
if (text === "\u007f" || text === "\b") {
|
|
50
|
+
value = value.slice(0, -1);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
value += text;
|
|
54
|
+
};
|
|
55
|
+
const cleanup = () => {
|
|
56
|
+
stdin.off("data", onData);
|
|
57
|
+
if (stdin.isTTY)
|
|
58
|
+
stdin.setRawMode(wasRaw ?? false);
|
|
59
|
+
stdin.pause();
|
|
60
|
+
};
|
|
61
|
+
stdin.resume();
|
|
62
|
+
stdin.on("data", onData);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
export async function runSetup(argv) {
|
|
66
|
+
const flags = parseSetupArgs(argv);
|
|
67
|
+
const bin = resolveCodexBin();
|
|
68
|
+
let models = [];
|
|
69
|
+
try {
|
|
70
|
+
models = listVisibleModels(loadBundledCatalog(bin));
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
74
|
+
process.stderr.write(`Could not read Codex models: ${message}\n`);
|
|
75
|
+
return 1;
|
|
76
|
+
}
|
|
77
|
+
if (!models.length) {
|
|
78
|
+
process.stderr.write("Codex did not return any selectable models.\n");
|
|
79
|
+
return 1;
|
|
80
|
+
}
|
|
81
|
+
const defaults = defaultLaneIndexes(models);
|
|
82
|
+
process.stdout.write(`Codex Sift setup\n\nYour Codex models:\n${formatModelMenu(models)}\n\n`);
|
|
83
|
+
process.stdout.write(`Lanes:\n flash = cheapest / fastest\n craft = everyday default\n forge = hardest work\n\n`);
|
|
84
|
+
const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY) && !flags.yes && !flags.flash && !flags.craft && !flags.forge;
|
|
85
|
+
const rl = interactive ? createInterface({ input, output }) : null;
|
|
86
|
+
try {
|
|
87
|
+
if (!process.env.TYPESAFE_API_KEY && interactive) {
|
|
88
|
+
const key = (await askHidden("TypeSafe API key (hidden, Enter to skip): ")).trim();
|
|
89
|
+
if (key) {
|
|
90
|
+
const path = writeLocalEnvKey(key);
|
|
91
|
+
process.stdout.write(`Saved key to ${path} (mode 600).\n`);
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
process.stdout.write("Skipped key. Export TYPESAFE_API_KEY or rerun setup.\n");
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
else if (process.env.TYPESAFE_API_KEY) {
|
|
98
|
+
process.stdout.write("TypeSafe API key: set\n");
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
process.stdout.write("TypeSafe API key: missing (export TYPESAFE_API_KEY)\n");
|
|
102
|
+
}
|
|
103
|
+
const flashRaw = flags.flash ?? (await ask(rl, `flash [${defaults.flash}]: `, String(defaults.flash)));
|
|
104
|
+
const craftRaw = flags.craft ?? (await ask(rl, `craft [${defaults.craft}]: `, String(defaults.craft)));
|
|
105
|
+
const forgeRaw = flags.forge ?? (await ask(rl, `forge [${defaults.forge}]: `, String(defaults.forge)));
|
|
106
|
+
const picks = {
|
|
107
|
+
flash: parsePick(flashRaw, models.length, defaults.flash),
|
|
108
|
+
craft: parsePick(craftRaw, models.length, defaults.craft),
|
|
109
|
+
forge: parsePick(forgeRaw, models.length, defaults.forge),
|
|
110
|
+
};
|
|
111
|
+
const policy = applyLanePicks(loadPolicy(), models, picks);
|
|
112
|
+
const dest = saveUserPolicy(policy);
|
|
113
|
+
process.stdout.write(`\nSaved ${dest}\n flash -> ${policy.lanes.flash.model}\n craft -> ${policy.lanes.craft.model}\n forge -> ${policy.lanes.forge.model}\n\nNext: cd into a project and run \`codex-sift\`.\nAfter a turn, \`codex-sift explain\` shows the model that answered.\n`);
|
|
114
|
+
return 0;
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
rl?.close();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
export async function runModels() {
|
|
121
|
+
const bin = resolveCodexBin();
|
|
122
|
+
const models = listVisibleModels(loadBundledCatalog(bin));
|
|
123
|
+
process.stdout.write(`${formatModelMenu(models)}\n`);
|
|
124
|
+
return 0;
|
|
125
|
+
}
|
package/dist/turns.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
type Json = null | boolean | number | string | Json[] | {
|
|
2
|
+
[k: string]: Json;
|
|
3
|
+
};
|
|
4
|
+
export declare function requestModel(body: Record<string, unknown>): string;
|
|
5
|
+
export declare function lastInputItem(body: Record<string, unknown>): unknown;
|
|
6
|
+
export declare function isToolish(item: unknown): boolean;
|
|
7
|
+
export declare function hasImage(body: Record<string, unknown>): boolean;
|
|
8
|
+
export declare function extractUserTexts(body: Record<string, unknown>): string[];
|
|
9
|
+
export declare function lastUserText(body: Record<string, unknown>): string;
|
|
10
|
+
export declare function isAuxiliaryModel(model: string): boolean;
|
|
11
|
+
export declare function isAuxiliaryPrompt(text: string): boolean;
|
|
12
|
+
export declare function isNewUserTurn(body: Record<string, unknown>): boolean;
|
|
13
|
+
export declare function conversationKey(body: Record<string, unknown>): string;
|
|
14
|
+
export declare function rewriteModel(body: Record<string, unknown>, model: string, effort?: string): Record<string, unknown>;
|
|
15
|
+
export type { Json };
|
package/dist/turns.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
const AUX_MODELS = new Set(["codex-auto-review"]);
|
|
2
|
+
const AUX_PROMPT = [
|
|
3
|
+
/compact the conversation/i,
|
|
4
|
+
/summarize (this|the) conversation/i,
|
|
5
|
+
/you are (performing|running) a (code )?review/i,
|
|
6
|
+
/produce a (concise )?review of/i,
|
|
7
|
+
/automatic review/i,
|
|
8
|
+
/session recap/i,
|
|
9
|
+
];
|
|
10
|
+
function isRecord(value) {
|
|
11
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
12
|
+
}
|
|
13
|
+
function collectText(node, into) {
|
|
14
|
+
if (typeof node === "string") {
|
|
15
|
+
into.push(node);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (Array.isArray(node)) {
|
|
19
|
+
for (const item of node)
|
|
20
|
+
collectText(item, into);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (!isRecord(node))
|
|
24
|
+
return;
|
|
25
|
+
if (typeof node.text === "string")
|
|
26
|
+
into.push(node.text);
|
|
27
|
+
if (typeof node.input_text === "string")
|
|
28
|
+
into.push(node.input_text);
|
|
29
|
+
if (typeof node.content === "string")
|
|
30
|
+
into.push(node.content);
|
|
31
|
+
if (node.content)
|
|
32
|
+
collectText(node.content, into);
|
|
33
|
+
if (node.parts)
|
|
34
|
+
collectText(node.parts, into);
|
|
35
|
+
}
|
|
36
|
+
function inputItems(body) {
|
|
37
|
+
const input = body.input;
|
|
38
|
+
if (Array.isArray(input))
|
|
39
|
+
return input;
|
|
40
|
+
if (typeof input === "string")
|
|
41
|
+
return [{ role: "user", content: input }];
|
|
42
|
+
return [];
|
|
43
|
+
}
|
|
44
|
+
export function requestModel(body) {
|
|
45
|
+
return typeof body.model === "string" ? body.model : "";
|
|
46
|
+
}
|
|
47
|
+
export function lastInputItem(body) {
|
|
48
|
+
const items = inputItems(body);
|
|
49
|
+
return items.length ? items[items.length - 1] : null;
|
|
50
|
+
}
|
|
51
|
+
export function isToolish(item) {
|
|
52
|
+
if (!isRecord(item))
|
|
53
|
+
return false;
|
|
54
|
+
const type = String(item.type || "");
|
|
55
|
+
if (/function_call|tool|item_reference/i.test(type))
|
|
56
|
+
return true;
|
|
57
|
+
if (type.includes("output"))
|
|
58
|
+
return true;
|
|
59
|
+
if (item.role === "tool")
|
|
60
|
+
return true;
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
export function hasImage(body) {
|
|
64
|
+
const blob = JSON.stringify(body);
|
|
65
|
+
return /input_image|image_url|"image"/i.test(blob);
|
|
66
|
+
}
|
|
67
|
+
export function extractUserTexts(body) {
|
|
68
|
+
const texts = [];
|
|
69
|
+
for (const item of inputItems(body)) {
|
|
70
|
+
if (!isRecord(item))
|
|
71
|
+
continue;
|
|
72
|
+
const role = String(item.role || "");
|
|
73
|
+
if (role && role !== "user")
|
|
74
|
+
continue;
|
|
75
|
+
if (isToolish(item))
|
|
76
|
+
continue;
|
|
77
|
+
const chunk = [];
|
|
78
|
+
collectText(item, chunk);
|
|
79
|
+
const text = chunk.join("\n").trim();
|
|
80
|
+
if (text)
|
|
81
|
+
texts.push(text);
|
|
82
|
+
}
|
|
83
|
+
if (!texts.length && typeof body.input === "string")
|
|
84
|
+
texts.push(body.input);
|
|
85
|
+
return texts;
|
|
86
|
+
}
|
|
87
|
+
export function lastUserText(body) {
|
|
88
|
+
const texts = extractUserTexts(body);
|
|
89
|
+
return texts.length ? texts[texts.length - 1] : "";
|
|
90
|
+
}
|
|
91
|
+
export function isAuxiliaryModel(model) {
|
|
92
|
+
return AUX_MODELS.has(model) || model.includes("auto-review");
|
|
93
|
+
}
|
|
94
|
+
export function isAuxiliaryPrompt(text) {
|
|
95
|
+
if (!text.trim())
|
|
96
|
+
return true;
|
|
97
|
+
return AUX_PROMPT.some((re) => re.test(text));
|
|
98
|
+
}
|
|
99
|
+
export function isNewUserTurn(body) {
|
|
100
|
+
const model = requestModel(body);
|
|
101
|
+
if (isAuxiliaryModel(model))
|
|
102
|
+
return false;
|
|
103
|
+
if (isToolish(lastInputItem(body)))
|
|
104
|
+
return false;
|
|
105
|
+
const text = lastUserText(body);
|
|
106
|
+
if (!text)
|
|
107
|
+
return false;
|
|
108
|
+
if (isAuxiliaryPrompt(text))
|
|
109
|
+
return false;
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
export function conversationKey(body) {
|
|
113
|
+
for (const key of ["conversation_id", "conversationId", "previous_response_id"]) {
|
|
114
|
+
const value = body[key];
|
|
115
|
+
if (typeof value === "string" && value)
|
|
116
|
+
return value;
|
|
117
|
+
}
|
|
118
|
+
const first = extractUserTexts(body)[0] || lastUserText(body);
|
|
119
|
+
return `anon:${hash(first).slice(0, 16)}`;
|
|
120
|
+
}
|
|
121
|
+
export function rewriteModel(body, model, effort) {
|
|
122
|
+
const next = { ...body, model };
|
|
123
|
+
if (effort) {
|
|
124
|
+
const reasoning = isRecord(body.reasoning) ? { ...body.reasoning } : {};
|
|
125
|
+
reasoning.effort = effort;
|
|
126
|
+
next.reasoning = reasoning;
|
|
127
|
+
}
|
|
128
|
+
return next;
|
|
129
|
+
}
|
|
130
|
+
function hash(text) {
|
|
131
|
+
let h = 2166136261;
|
|
132
|
+
for (let i = 0; i < text.length; i++) {
|
|
133
|
+
h ^= text.charCodeAt(i);
|
|
134
|
+
h = Math.imul(h, 16777619);
|
|
135
|
+
}
|
|
136
|
+
return (h >>> 0).toString(16);
|
|
137
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
export declare const VIRTUAL_SLUG_DEFAULT = "sift";
|
|
2
|
+
export declare const PROVIDER_ID = "sift";
|
|
3
|
+
export type LaneName = string;
|
|
4
|
+
export type Lane = {
|
|
5
|
+
model: string;
|
|
6
|
+
effort?: string;
|
|
7
|
+
};
|
|
8
|
+
export type PolicyRule = {
|
|
9
|
+
when: string;
|
|
10
|
+
lane: LaneName;
|
|
11
|
+
reason: string;
|
|
12
|
+
};
|
|
13
|
+
export type Policy = {
|
|
14
|
+
jev_model: string;
|
|
15
|
+
jev_timeout_ms: number;
|
|
16
|
+
min_confidence: number;
|
|
17
|
+
on_jev_down: LaneName;
|
|
18
|
+
virtual_model: {
|
|
19
|
+
slug: string;
|
|
20
|
+
display_name: string;
|
|
21
|
+
description: string;
|
|
22
|
+
};
|
|
23
|
+
lanes: Record<LaneName, Lane>;
|
|
24
|
+
prices_usd_per_1m: Record<string, number>;
|
|
25
|
+
usage_weight: Record<string, number>;
|
|
26
|
+
effort_weight: Record<string, number>;
|
|
27
|
+
rules: PolicyRule[];
|
|
28
|
+
};
|
|
29
|
+
export type Signals = {
|
|
30
|
+
task_kind: string;
|
|
31
|
+
task_kind_confidence: number;
|
|
32
|
+
difficulty: number;
|
|
33
|
+
difficulty_confidence: number;
|
|
34
|
+
needs_reasoning: number;
|
|
35
|
+
needs_planning: number;
|
|
36
|
+
high_stakes: number;
|
|
37
|
+
cross_cutting: number;
|
|
38
|
+
is_chitchat: number;
|
|
39
|
+
confidence: number;
|
|
40
|
+
has_image: boolean;
|
|
41
|
+
};
|
|
42
|
+
export type Decision = {
|
|
43
|
+
lane: LaneName;
|
|
44
|
+
model: string;
|
|
45
|
+
effort?: string;
|
|
46
|
+
reason: string[];
|
|
47
|
+
signals: Signals;
|
|
48
|
+
degraded: boolean;
|
|
49
|
+
jev_ms: number;
|
|
50
|
+
prompt_chars: number;
|
|
51
|
+
};
|
|
52
|
+
export type SessionPin = {
|
|
53
|
+
conversationKey: string;
|
|
54
|
+
lastUserText: string;
|
|
55
|
+
decision: Decision;
|
|
56
|
+
};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import type { IncomingMessage } from "node:http";
|
|
3
|
+
import { URL } from "node:url";
|
|
4
|
+
export type AuthMode = "chatgpt" | "api";
|
|
5
|
+
export declare const CHATGPT_ORIGIN = "https://chatgpt.com";
|
|
6
|
+
export declare const OPENAI_ORIGIN = "https://api.openai.com";
|
|
7
|
+
export declare function detectAuthMode(headers: http.IncomingHttpHeaders): AuthMode;
|
|
8
|
+
export declare function classifyPath(pathname: string): "responses" | "models" | "other";
|
|
9
|
+
export declare function upstreamFor(mode: AuthMode, pathname: string, search: string): {
|
|
10
|
+
origin: string;
|
|
11
|
+
path: string;
|
|
12
|
+
};
|
|
13
|
+
export declare function forwardHeaders(src: http.IncomingHttpHeaders, host: string): http.OutgoingHttpHeaders;
|
|
14
|
+
export declare function requestUpstream(url: URL, method: string, headers: http.OutgoingHttpHeaders, body?: Buffer): Promise<IncomingMessage>;
|
|
15
|
+
export declare function readIncoming(up: IncomingMessage): Promise<Buffer>;
|
|
16
|
+
export declare function pipeUpstream(url: URL, method: string, headers: http.OutgoingHttpHeaders, body: Buffer | undefined, incoming: IncomingMessage, outgoing: http.ServerResponse): void;
|
package/dist/upstream.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import https from "node:https";
|
|
3
|
+
export const CHATGPT_ORIGIN = "https://chatgpt.com";
|
|
4
|
+
export const OPENAI_ORIGIN = "https://api.openai.com";
|
|
5
|
+
const HOP = new Set([
|
|
6
|
+
"connection",
|
|
7
|
+
"keep-alive",
|
|
8
|
+
"proxy-authenticate",
|
|
9
|
+
"proxy-authorization",
|
|
10
|
+
"te",
|
|
11
|
+
"trailers",
|
|
12
|
+
"transfer-encoding",
|
|
13
|
+
"upgrade",
|
|
14
|
+
"content-length",
|
|
15
|
+
"host",
|
|
16
|
+
]);
|
|
17
|
+
export function detectAuthMode(headers) {
|
|
18
|
+
const account = headers["chatgpt-account-id"] || headers["ChatGPT-Account-Id"];
|
|
19
|
+
if (account)
|
|
20
|
+
return "chatgpt";
|
|
21
|
+
return "api";
|
|
22
|
+
}
|
|
23
|
+
export function classifyPath(pathname) {
|
|
24
|
+
if (/\/responses\/?$/.test(pathname) || pathname.endsWith("/codex/responses"))
|
|
25
|
+
return "responses";
|
|
26
|
+
if (/\/models\/?$/.test(pathname) || pathname.includes("/models?"))
|
|
27
|
+
return "models";
|
|
28
|
+
return "other";
|
|
29
|
+
}
|
|
30
|
+
export function upstreamFor(mode, pathname, search) {
|
|
31
|
+
const kind = classifyPath(pathname);
|
|
32
|
+
if (mode === "chatgpt") {
|
|
33
|
+
const origin = process.env.SIFT_CHATGPT_ORIGIN || CHATGPT_ORIGIN;
|
|
34
|
+
if (kind === "responses")
|
|
35
|
+
return { origin, path: "/backend-api/codex/responses" };
|
|
36
|
+
if (kind === "models")
|
|
37
|
+
return { origin, path: `/backend-api/codex/models${search}` };
|
|
38
|
+
const path = pathname.startsWith("/backend-api") ? `${pathname}${search}` : `/backend-api/codex${pathname}${search}`;
|
|
39
|
+
return { origin, path };
|
|
40
|
+
}
|
|
41
|
+
const origin = process.env.SIFT_OPENAI_ORIGIN || OPENAI_ORIGIN;
|
|
42
|
+
if (kind === "responses")
|
|
43
|
+
return { origin, path: "/v1/responses" };
|
|
44
|
+
if (kind === "models")
|
|
45
|
+
return { origin, path: `/v1/models${search}` };
|
|
46
|
+
const path = pathname.startsWith("/v1") ? `${pathname}${search}` : `/v1${pathname}${search}`;
|
|
47
|
+
return { origin, path };
|
|
48
|
+
}
|
|
49
|
+
export function forwardHeaders(src, host) {
|
|
50
|
+
const out = {};
|
|
51
|
+
for (const [key, value] of Object.entries(src)) {
|
|
52
|
+
if (!value)
|
|
53
|
+
continue;
|
|
54
|
+
if (HOP.has(key.toLowerCase()))
|
|
55
|
+
continue;
|
|
56
|
+
out[key] = value;
|
|
57
|
+
}
|
|
58
|
+
out.host = host;
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
export function requestUpstream(url, method, headers, body) {
|
|
62
|
+
const opts = {
|
|
63
|
+
protocol: url.protocol,
|
|
64
|
+
hostname: url.hostname,
|
|
65
|
+
port: url.port || (url.protocol === "https:" ? 443 : 80),
|
|
66
|
+
path: `${url.pathname}${url.search}`,
|
|
67
|
+
method,
|
|
68
|
+
headers,
|
|
69
|
+
};
|
|
70
|
+
const transport = url.protocol === "http:" ? http : https;
|
|
71
|
+
return new Promise((resolve, reject) => {
|
|
72
|
+
const req = transport.request(opts, resolve);
|
|
73
|
+
req.on("error", reject);
|
|
74
|
+
if (body)
|
|
75
|
+
req.write(body);
|
|
76
|
+
req.end();
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
export async function readIncoming(up) {
|
|
80
|
+
const chunks = [];
|
|
81
|
+
for await (const chunk of up) {
|
|
82
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
83
|
+
}
|
|
84
|
+
return Buffer.concat(chunks);
|
|
85
|
+
}
|
|
86
|
+
export function pipeUpstream(url, method, headers, body, incoming, outgoing) {
|
|
87
|
+
const opts = {
|
|
88
|
+
protocol: url.protocol,
|
|
89
|
+
hostname: url.hostname,
|
|
90
|
+
port: url.port || (url.protocol === "https:" ? 443 : 80),
|
|
91
|
+
path: `${url.pathname}${url.search}`,
|
|
92
|
+
method,
|
|
93
|
+
headers,
|
|
94
|
+
};
|
|
95
|
+
const transport = url.protocol === "http:" ? http : https;
|
|
96
|
+
const req = transport.request(opts, (up) => {
|
|
97
|
+
const outHeaders = {};
|
|
98
|
+
for (const [key, value] of Object.entries(up.headers)) {
|
|
99
|
+
if (!value)
|
|
100
|
+
continue;
|
|
101
|
+
if (["connection", "keep-alive", "transfer-encoding"].includes(key.toLowerCase()))
|
|
102
|
+
continue;
|
|
103
|
+
outHeaders[key] = value;
|
|
104
|
+
}
|
|
105
|
+
outgoing.writeHead(up.statusCode || 502, outHeaders);
|
|
106
|
+
up.pipe(outgoing);
|
|
107
|
+
});
|
|
108
|
+
req.on("error", (err) => {
|
|
109
|
+
if (outgoing.headersSent) {
|
|
110
|
+
outgoing.end();
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
outgoing.writeHead(502, { "content-type": "text/plain" });
|
|
114
|
+
outgoing.end(`sift upstream error: ${err.message}`);
|
|
115
|
+
});
|
|
116
|
+
incoming.on("aborted", () => req.destroy());
|
|
117
|
+
if (body)
|
|
118
|
+
req.write(body);
|
|
119
|
+
req.end();
|
|
120
|
+
}
|