agent-request-logger 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 José Lugo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,123 @@
1
- # Temporary Holding Version
1
+ # agent-request-logger
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ See what your coding agent sends to its model provider: system instructions,
4
+ tool definitions, messages, responses, and token usage. This CLI runs a local
5
+ HTTP proxy, forwards traffic to the provider, and saves readable captures on
6
+ your machine while streaming responses back to the agent.
7
+
8
+ Supports **Claude Code, Codex, GitHub Copilot CLI, OpenCode, and Pi**.
9
+ See [agent setup](docs/agents.md) for available providers and limitations.
10
+
11
+ ## Install
12
+
13
+ Requires **Node.js 22.15 or newer**, npm, and an installed coding agent.
14
+ Launch commands printed by the logger use bash/zsh syntax.
15
+
16
+ Run without a global install:
17
+
18
+ ```sh
19
+ npx agent-request-logger
20
+ ```
21
+
22
+ Or install globally:
23
+
24
+ ```sh
25
+ npm i -g agent-request-logger
26
+ agent-request-logger
27
+ ```
28
+
29
+ Or install in a project:
30
+
31
+ ```sh
32
+ npm i -D agent-request-logger
33
+ ```
34
+
35
+ Add a script to that project's `package.json`:
36
+
37
+ ```json
38
+ {
39
+ "scripts": {
40
+ "log:agent": "agent-request-logger"
41
+ }
42
+ }
43
+ ```
44
+
45
+ Then run:
46
+
47
+ ```sh
48
+ npm run log:agent
49
+ ```
50
+
51
+ The published CLI runs built JavaScript; consumers do not need pnpm or
52
+ TypeScript. This repository uses pnpm for development.
53
+
54
+ ## Use
55
+
56
+ 1. Open a terminal in the project where you want to save captures and start
57
+ the logger using one of the commands above.
58
+ 2. Choose your agent and provider. You can remember the setup for future runs.
59
+ 3. Leave the logger running. It listens on `127.0.0.1:8787` by default.
60
+ 4. In a second terminal, launch your agent with the exact command printed by
61
+ the logger. Merge any printed configuration settings into your existing
62
+ agent configuration first.
63
+ 5. Send a message to the agent and open the newest Markdown file under
64
+ `./request-logger-logs/` in the logger's working directory.
65
+ 6. Press Ctrl+C in the logger terminal when finished.
66
+
67
+ Authenticate your agent normally before using the logger. Existing credentials
68
+ are forwarded to the configured upstream; the logger does not sign you in.
69
+
70
+ A single agent turn can make several model requests. Each captured request has
71
+ three files sharing a timestamp and request ID:
72
+
73
+ | File | What it contains |
74
+ | --------------- | ------------------------------------------------------------------------- |
75
+ | `.md` | Readable headers, instructions, tools, messages, response text, and usage |
76
+ | `.request.txt` | Original request body bytes, including compression |
77
+ | `.response.txt` | Original upstream response body bytes |
78
+
79
+ Captures default to `./request-logger-logs/` **where you launch the logger**,
80
+ including through npx, a global executable, or an npm script. Remembered setup
81
+ lives separately in `~/.agent-request-logger/.agent-choice.json`.
82
+
83
+ Sensitive HTTP headers are redacted in readable captures. Request and response
84
+ bodies can still contain private code or secrets. Add your capture directory
85
+ to the project's `.gitignore`.
86
+
87
+ ## Options
88
+
89
+ ```sh
90
+ npx agent-request-logger --force
91
+ npx agent-request-logger --port 9000
92
+ npx agent-request-logger --log-dir ./captures
93
+ npx agent-request-logger --config-dir ./preferences
94
+ npx agent-request-logger --debug
95
+ npx agent-request-logger --help
96
+ npx agent-request-logger --version
97
+ ```
98
+
99
+ | Option | Purpose |
100
+ | ----------------- | ------------------------------------------------ |
101
+ | `--force` | Forget the saved setup and choose again |
102
+ | `--port` | Change the listening port; default `8787` |
103
+ | `--log-dir` | Choose where captures are written |
104
+ | `--config-dir` | Choose where preferences are stored |
105
+ | `--debug` | Include stack traces in contextual error reports |
106
+ | `--help`, `-h` | Show command help |
107
+ | `--version`, `-v` | Print the installed version |
108
+
109
+ With an npm script, pass options after `--`, for example
110
+ `npm run log:agent -- --port 9000`.
111
+
112
+ Environment alternatives are `PORT`, `REQUEST_LOGGER_LOG_DIR`, and
113
+ `REQUEST_LOGGER_CONFIG_DIR`. CLI options take precedence. Relative paths are
114
+ resolved from the logger's working directory.
115
+
116
+ ## More
117
+
118
+ - [Agent setup and troubleshooting](docs/agents.md)
119
+ - [Contributing and local development](CONTRIBUTING.md)
120
+ - [Testing conventions](docs/testing.md)
121
+ - [Release process](docs/releases.md)
122
+
123
+ Licensed under [MIT](LICENSE).
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { parseArgs } from "node:util";
4
+
5
+ try {
6
+ const { values } = parseArgs({
7
+ options: {
8
+ help: { type: "boolean", short: "h" },
9
+ version: { type: "boolean", short: "v" },
10
+ debug: { type: "boolean" },
11
+ force: { type: "boolean" },
12
+ port: { type: "string" },
13
+ "log-dir": { type: "string" },
14
+ "config-dir": { type: "string" },
15
+ },
16
+ });
17
+ if (values.help) {
18
+ console.log(`Usage: agent-request-logger [options]
19
+
20
+ Inspect the HTTP requests your coding agent sends to its model provider.
21
+
22
+ --debug Include stack traces in error reports
23
+ --force Choose your agent and provider again
24
+ --port <number> Local port (default: PORT or 8787)
25
+ --log-dir <path> Capture directory (default: ./request-logger-logs)
26
+ --config-dir <path> Preferences directory (default: ~/.agent-request-logger)
27
+ -h, --help Show this help
28
+ -v, --version Show the version
29
+
30
+ Start this command, then launch your agent using the command it prints.
31
+ Press Ctrl+C to stop.`);
32
+ } else if (values.version) {
33
+ console.log(JSON.parse(readFileSync(new URL("../package.json", import.meta.url))).version);
34
+ } else {
35
+ const port = values.port ?? process.env.PORT ?? "8787";
36
+ if (!/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535) {
37
+ throw new Error("Port must be an integer between 1 and 65535.");
38
+ }
39
+ process.env.PORT = port;
40
+ if (values.debug) process.env.REQUEST_LOGGER_DEBUG = "1";
41
+ if (values["log-dir"]) process.env.REQUEST_LOGGER_LOG_DIR = values["log-dir"];
42
+ if (values["config-dir"]) process.env.REQUEST_LOGGER_CONFIG_DIR = values["config-dir"];
43
+ const { main } = await import("../dist/main.js");
44
+ await main();
45
+ }
46
+ } catch (error) {
47
+ const { formatError } = await import("../dist/errors.js").catch(() => ({
48
+ formatError: (error) => error.message,
49
+ }));
50
+ console.error(
51
+ formatError(
52
+ error,
53
+ process.env.REQUEST_LOGGER_DEBUG === "1" || process.argv.includes("--debug"),
54
+ ),
55
+ );
56
+ process.exitCode = 1;
57
+ }
@@ -0,0 +1,111 @@
1
+ /** Quote one POSIX shell argument, including embedded quotes and metacharacters. */
2
+ export function shellArgument(text) {
3
+ return `'${text.replaceAll("'", "'\"'\"'")}'`;
4
+ }
5
+ function jsonFile(path, value) {
6
+ return { path, content: JSON.stringify(value, null, 2) };
7
+ }
8
+ export function buildAgentSetup(context) {
9
+ const { choice, localUrl } = context;
10
+ switch (choice.agent) {
11
+ case "claude-code":
12
+ return {
13
+ command: `ANTHROPIC_BASE_URL=${shellArgument(localUrl)} ENABLE_TOOL_SEARCH=true claude`,
14
+ files: [],
15
+ // Changing the API host otherwise changes Claude's deferred-tool behavior.
16
+ hints: [
17
+ "Tool search stays enabled so the proxy does not cause Claude to send all deferred tools.",
18
+ ],
19
+ };
20
+ case "codex":
21
+ return codexSetup(choice, localUrl);
22
+ case "copilot":
23
+ return {
24
+ command: `COPILOT_API_URL=${shellArgument(localUrl)} copilot`,
25
+ files: [],
26
+ hints: ["HTTP requests are captured; WebSocket model traffic is unsupported."],
27
+ };
28
+ case "opencode":
29
+ return openCodeSetup(context);
30
+ case "pi":
31
+ return piSetup(context);
32
+ }
33
+ }
34
+ function codexSetup(choice, localUrl) {
35
+ // Subscription traffic uses a different path from the public OpenAI API.
36
+ const suffix = choice.provider === "chatgpt" ? "/backend-api/codex" : "/v1";
37
+ return {
38
+ command: `codex -c ${shellArgument(`openai_base_url="${localUrl}${suffix}"`)}`,
39
+ files: [],
40
+ hints: ["This flag overrides the API URL for this invocation only."],
41
+ };
42
+ }
43
+ function openCodeSetup({ choice, protocol, localUrl, model }) {
44
+ const baseURL = `${localUrl}/v1`;
45
+ if (choice.provider === "custom" && protocol === "openai") {
46
+ // A temporary provider lets OpenCode select a model absent from its catalogue
47
+ // without editing the user's normal provider or small-model configuration.
48
+ if (!model)
49
+ throw new Error("A custom OpenCode setup requires a model ID.");
50
+ const provider = "logger";
51
+ const config = {
52
+ model: `${provider}/${model}`,
53
+ small_model: `${provider}/${model}`,
54
+ provider: {
55
+ [provider]: {
56
+ npm: "@ai-sdk/openai-compatible",
57
+ options: { baseURL },
58
+ models: { [model]: { name: model } },
59
+ },
60
+ },
61
+ };
62
+ return {
63
+ command: `OPENCODE_CONFIG_CONTENT=${shellArgument(JSON.stringify(config))} opencode`,
64
+ files: [],
65
+ hints: [],
66
+ };
67
+ }
68
+ const anthropic = choice.provider === "custom" ? protocol === "anthropic" : choice.provider === "anthropic";
69
+ const environmentVariable = anthropic ? "ANTHROPIC_BASE_URL" : "OPENAI_BASE_URL";
70
+ const provider = anthropic ? "anthropic" : "openai";
71
+ return {
72
+ command: `${environmentVariable}=${shellArgument(baseURL)} opencode`,
73
+ files: [
74
+ jsonFile("~/.config/opencode/opencode.json", {
75
+ provider: { [provider]: { options: { baseURL } } },
76
+ }),
77
+ ],
78
+ hints: [
79
+ "Merge the printed provider options into your OpenCode config if it overrides the environment variable.",
80
+ ],
81
+ };
82
+ }
83
+ function piSetup({ choice, protocol, localUrl, model }) {
84
+ const custom = choice.provider === "custom";
85
+ const provider = custom
86
+ ? protocol === "anthropic"
87
+ ? "anthropic"
88
+ : "openai"
89
+ : choice.provider === "codex"
90
+ ? "openai-codex"
91
+ : choice.provider;
92
+ // Pi's SDK supplies the remaining endpoint path, including /codex/responses.
93
+ const suffix = provider === "openai-codex" ? "/backend-api" : provider === "openai" ? "/v1" : "";
94
+ const settings = {
95
+ baseUrl: localUrl + suffix,
96
+ // Supplying models replaces Pi's built-in list; omit it for known providers.
97
+ ...(custom ? { models: [{ id: model }] } : {}),
98
+ };
99
+ const files = [jsonFile("~/.pi/agent/models.json", { providers: { [provider]: settings } })];
100
+ if (provider === "openai-codex") {
101
+ files.push(jsonFile("~/.pi/agent/settings.json", { transport: "sse" }));
102
+ }
103
+ return {
104
+ command: "pi",
105
+ files,
106
+ hints: [
107
+ "Merge these settings with your existing files. A custom model list replaces that provider's catalogue.",
108
+ ],
109
+ };
110
+ }
111
+ //# sourceMappingURL=agent-setup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-setup.js","sourceRoot":"","sources":["../src/agent-setup.ts"],"names":[],"mappings":"AAUA,oFAAoF;AACpF,MAAM,UAAU,aAAa,CAAC,IAAY;IACxC,OAAO,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,SAAS,CAAC,GAAG,CAAC;AAChD,CAAC;AAED,SAAS,QAAQ,CAAC,IAAY,EAAE,KAAc;IAC5C,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,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,OAAO,EAAE,IAAI;QACb,KAAK;QACL,KAAK,EAAE;YACL,wGAAwG;SACzG;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,107 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import * as zlib from "node:zlib";
5
+ import { decodeResponse, parseJson } from "./response-decoder.js";
6
+ const hidden = new Set([
7
+ "authorization",
8
+ "proxy-authorization",
9
+ "x-api-key",
10
+ "api-key",
11
+ "x-goog-api-key",
12
+ "cookie",
13
+ "set-cookie",
14
+ ]);
15
+ export function safeHeaders(headers) {
16
+ return Object.fromEntries(Object.entries(headers).map(([name, value]) => [
17
+ name,
18
+ hidden.has(name.toLowerCase()) ? "[REDACTED]" : value,
19
+ ]));
20
+ }
21
+ export function requestText(bytes, encoding = "") {
22
+ try {
23
+ switch (encoding.toLowerCase()) {
24
+ case "gzip":
25
+ return zlib.gunzipSync(bytes).toString();
26
+ case "br":
27
+ return zlib.brotliDecompressSync(bytes).toString();
28
+ case "deflate":
29
+ return zlib.inflateSync(bytes).toString();
30
+ case "zstd": {
31
+ const decode = zlib
32
+ .zstdDecompressSync;
33
+ if (!decode)
34
+ throw new Error("zstd requires Node 22.15+ or 23.8+");
35
+ return decode(bytes).toString();
36
+ }
37
+ case "":
38
+ case "identity":
39
+ return bytes.toString();
40
+ default:
41
+ throw new Error(`unsupported content encoding: ${encoding}`);
42
+ }
43
+ }
44
+ catch (error) {
45
+ return `[Body could not be decoded: ${error.message}. Original bytes are in .request.txt]`;
46
+ }
47
+ }
48
+ function code(value) {
49
+ const text = typeof value === "string" ? value : (JSON.stringify(value, null, 2) ?? "null");
50
+ // Captured prompts may contain Markdown fences of their own. The enclosing
51
+ // fence must be longer or the rest of the capture would render incorrectly.
52
+ const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map((match) => match[0].length));
53
+ const delimiter = "`".repeat(longest + 1);
54
+ return `${delimiter}\n${text}\n${delimiter}`;
55
+ }
56
+ export function responseSummary(text, protocol) {
57
+ const decoded = decodeResponse(text, protocol);
58
+ const sections = [];
59
+ if (decoded.text)
60
+ sections.push(`### Assistant text\n\n${code(decoded.text)}`);
61
+ if (decoded.reasoning)
62
+ sections.push(`### Reasoning\n\n${code(decoded.reasoning)}`);
63
+ if (decoded.tools.length)
64
+ sections.push(`### Tool calls\n\n${code(decoded.tools)}`);
65
+ if (decoded.usage.length)
66
+ sections.push(`### Token usage\n\n${code(decoded.usage)}`);
67
+ return sections.join("\n\n") || code(decoded.payloads.length ? decoded.payloads : text);
68
+ }
69
+ export function markdown(exchange) {
70
+ const encoding = exchange.headers["content-encoding"];
71
+ const text = requestText(exchange.request, Array.isArray(encoding) ? encoding[0] : encoding);
72
+ const request = parseJson(text);
73
+ const responseText = requestText(exchange.response, exchange.responseEncoding);
74
+ const sections = [
75
+ "# Agent HTTP capture",
76
+ `${exchange.agent}\n\nRequest: ${exchange.requestId ?? "unassigned"}\n\n${exchange.method} ${exchange.url} → ${exchange.status} (${exchange.elapsedMs} ms)${exchange.responseIncomplete ? "\n\nResponse stream closed by the client before the upstream finished; capture may be incomplete." : ""}`,
77
+ `## Request headers\n\n${code(safeHeaders(exchange.headers))}`,
78
+ ];
79
+ if (request && exchange.protocol !== "raw") {
80
+ const system = request.system ?? request.instructions;
81
+ if (system != null)
82
+ sections.push(`## System instructions\n\n${code(system)}`);
83
+ if (request.tools)
84
+ sections.push(`## Tools\n\n${code(request.tools)}`);
85
+ const messages = request.messages ?? request.input;
86
+ if (messages)
87
+ sections.push(`## Messages\n\n${code(messages)}`);
88
+ }
89
+ sections.push(`## Complete request\n\n${code(request ?? text)}`);
90
+ sections.push(`## Response\n\n${responseSummary(responseText, exchange.protocol)}`);
91
+ // Keep unrecognized events and provider-specific fields visible as well.
92
+ sections.push(`## Complete response stream\n\n${code(responseText)}`);
93
+ return `${sections.join("\n\n")}\n`;
94
+ }
95
+ export async function saveExchange(directory, exchange) {
96
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
97
+ const prefix = `${new Date().toISOString().replaceAll(":", "-")}_${exchange.requestId ?? randomUUID()}`;
98
+ const base = path.join(directory, prefix);
99
+ await Promise.all([
100
+ fs.writeFile(`${base}.request.txt`, exchange.request, { mode: 0o600 }),
101
+ fs.writeFile(`${base}.response.txt`, exchange.response, { mode: 0o600 }),
102
+ ]);
103
+ // Write Markdown last so a visible .md file means both raw files are ready.
104
+ await fs.writeFile(`${base}.md`, markdown(exchange), { mode: 0o600 });
105
+ return `${base}.md`;
106
+ }
107
+ //# sourceMappingURL=capture.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capture.js","sourceRoot":"","sources":["../src/capture.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAElC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAiBlE,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC;IACrB,eAAe;IACf,qBAAqB;IACrB,WAAW;IACX,SAAS;IACT,gBAAgB;IAChB,QAAQ;IACR,YAAY;CACb,CAAC,CAAC;AACH,MAAM,UAAU,WAAW,CAAC,OAA4B;IACtD,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC;QAC7C,IAAI;QACJ,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK;KACtD,CAAC,CACH,CAAC;AACJ,CAAC;AACD,MAAM,UAAU,WAAW,CAAC,KAAa,EAAE,QAAQ,GAAG,EAAE;IACtD,IAAI,CAAC;QACH,QAA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AAK,EAAE,CAAC,CAAC;IACtE,OAAO,GAAG,IAAI,KAAK,CAAC;AACtB,CAAC"}
package/dist/errors.js ADDED
@@ -0,0 +1,34 @@
1
+ export class LoggerError extends Error {
2
+ code;
3
+ requestId;
4
+ constructor(code, message, cause, requestId) {
5
+ super(message, { cause });
6
+ this.code = code;
7
+ this.requestId = requestId;
8
+ this.name = "LoggerError";
9
+ }
10
+ }
11
+ export function formatError(value, debug = false) {
12
+ const lines = [];
13
+ const visited = new Set();
14
+ let current = value;
15
+ while (current != null && !visited.has(current)) {
16
+ visited.add(current);
17
+ const prefix = lines.length ? " caused by: " : "";
18
+ if (!(current instanceof Error)) {
19
+ lines.push(prefix + String(current));
20
+ break;
21
+ }
22
+ const code = "code" in current && typeof current.code === "string" ? `[${current.code}] ` : "";
23
+ const request = current instanceof LoggerError && current.requestId ? `request=${current.requestId} ` : "";
24
+ lines.push(prefix + request + code + current.message);
25
+ if (debug && current.stack)
26
+ lines.push(...current.stack
27
+ .split("\n")
28
+ .slice(1)
29
+ .map((line) => ` ${line.trim()}`));
30
+ current = current.cause;
31
+ }
32
+ return lines.join("\n");
33
+ }
34
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAOA,MAAM,OAAO,WAAY,SAAQ,KAAK;IAEzB;IAGA;IAJX,YACW,IAAe,EACxB,OAAe,EACf,KAAe,EACN,SAAkB;QAE3B,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QALjB,SAAI,GAAJ,IAAI,CAAW;QAGf,cAAS,GAAT,SAAS,CAAS;QAG3B,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF;AACD,MAAM,UAAU,WAAW,CAAC,KAAc,EAAE,KAAK,GAAG,KAAK;IACvD,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,OAAO,GAAG,IAAI,GAAG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@@ -0,0 +1,164 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import http from "node:http";
3
+ import https from "node:https";
4
+ import { performance } from "node:perf_hooks";
5
+ import { saveExchange } from "./capture.js";
6
+ import { formatError, LoggerError } from "./errors.js";
7
+ const HOP_HEADERS = [
8
+ "connection",
9
+ "keep-alive",
10
+ "proxy-authenticate",
11
+ "proxy-authorization",
12
+ "te",
13
+ "trailer",
14
+ "transfer-encoding",
15
+ "upgrade",
16
+ ];
17
+ function transportHeaders(input) {
18
+ const result = { ...input };
19
+ // Connection may name additional headers that are valid only on this hop.
20
+ const named = String(input.connection ?? "")
21
+ .split(",")
22
+ .map((name) => name.trim().toLowerCase());
23
+ for (const name of [...HOP_HEADERS, ...named])
24
+ delete result[name];
25
+ delete result.host;
26
+ return result;
27
+ }
28
+ export function requestPath(base, incoming) {
29
+ // URL resolution would interpret //host as a new origin. Joining only paths
30
+ // preserves the configured host, custom prefixes, and incoming query string.
31
+ return base.pathname.replace(/\/+$/, "") + (incoming.startsWith("/") ? incoming : `/${incoming}`);
32
+ }
33
+ function isModelRequest(exchange) {
34
+ if (exchange.method !== "POST")
35
+ return false;
36
+ const pathname = exchange.url.split("?")[0];
37
+ if (exchange.protocol === "raw")
38
+ return !/count[_-]?tokens/i.test(pathname);
39
+ return /\/(messages|responses|chat\/completions)$/.test(pathname);
40
+ }
41
+ function createRecorder(options, report) {
42
+ const recent = new Map();
43
+ const windowMs = 2000;
44
+ const captureLimit = 20;
45
+ return (exchange) => {
46
+ if (!isModelRequest(exchange))
47
+ return;
48
+ const now = Date.now();
49
+ const signature = `${exchange.method} ${exchange.url} ${exchange.status}`;
50
+ const times = (recent.get(signature) ?? []).filter((time) => now - time < windowMs);
51
+ times.push(now);
52
+ recent.set(signature, times.slice(-(captureLimit + 1)));
53
+ for (const [key, history] of recent) {
54
+ if (now - history[history.length - 1] > windowMs)
55
+ recent.delete(key);
56
+ }
57
+ // Only capture writes are limited. Every upstream response still reaches
58
+ // the agent, including a failing response the agent is retrying rapidly.
59
+ if (times.length > captureLimit)
60
+ return;
61
+ void saveExchange(options.directory, exchange)
62
+ .then((file) => options.onCapture?.(file))
63
+ .catch((error) => report(new LoggerError("CAPTURE_FAILED", "Could not write capture files.", error, exchange.requestId)));
64
+ };
65
+ }
66
+ /** The caller must start and close the server. */
67
+ export function createGateway(options) {
68
+ const report = options.onError ??
69
+ ((error) => {
70
+ console.error(formatError(error, process.env.REQUEST_LOGGER_DEBUG === "1"));
71
+ });
72
+ const context = {
73
+ target: options.target,
74
+ upstream: options.override ?? options.target.upstream,
75
+ record: createRecorder(options, report),
76
+ report,
77
+ };
78
+ const server = http.createServer((incoming, outgoing) => forwardRequest(incoming, outgoing, context));
79
+ server.on("upgrade", (_request, socket) => {
80
+ // A prompt rejection allows clients with an HTTP fallback to use it.
81
+ socket.end("HTTP/1.1 426 Upgrade Required\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
82
+ });
83
+ return server;
84
+ }
85
+ function forwardRequest(incoming, outgoing, context) {
86
+ const started = performance.now();
87
+ const requestId = randomUUID();
88
+ const method = incoming.method ?? "GET";
89
+ const url = requestPath(context.target.upstream, incoming.url ?? "/");
90
+ const headers = transportHeaders(incoming.headers);
91
+ // Ask for plain SSE, but never change the request body's content encoding.
92
+ headers["accept-encoding"] = "identity";
93
+ const requestChunks = [];
94
+ const send = context.upstream.protocol === "https:" ? https.request : http.request;
95
+ let failed = false;
96
+ let responseComplete = false;
97
+ let clientClosed = false;
98
+ let savePartialResponse;
99
+ const upstream = send({
100
+ protocol: context.upstream.protocol,
101
+ hostname: context.upstream.hostname.replace(/^\[|\]$/g, ""),
102
+ port: context.upstream.port || undefined,
103
+ method: incoming.method,
104
+ path: url,
105
+ headers,
106
+ }, handleResponse);
107
+ function handleResponse(response) {
108
+ const responseChunks = [];
109
+ outgoing.writeHead(response.statusCode ?? 502, transportHeaders(response.headers));
110
+ response.on("data", (chunk) => responseChunks.push(Buffer.from(chunk)));
111
+ response.on("error", fail);
112
+ const recordResponse = () => {
113
+ if (responseComplete)
114
+ return;
115
+ responseComplete = true;
116
+ context.record({
117
+ requestId,
118
+ agent: context.target.name,
119
+ protocol: context.target.protocol,
120
+ method,
121
+ url,
122
+ status: response.statusCode ?? 502,
123
+ headers: incoming.headers,
124
+ request: Buffer.concat(requestChunks),
125
+ response: Buffer.concat(responseChunks),
126
+ responseEncoding: String(response.headers["content-encoding"] ?? ""),
127
+ elapsedMs: Math.round(performance.now() - started),
128
+ responseIncomplete: clientClosed,
129
+ });
130
+ };
131
+ savePartialResponse = recordResponse;
132
+ response.on("end", recordResponse);
133
+ // Pipe streams immediately. Buffered copies are used only after completion
134
+ // to write captures, so capture formatting cannot delay individual tokens.
135
+ response.pipe(outgoing);
136
+ }
137
+ function fail(error) {
138
+ // Request and response streams can report the same failure during teardown.
139
+ if (failed || clientClosed)
140
+ return;
141
+ failed = true;
142
+ context.report(new LoggerError("UPSTREAM_FAILED", `${incoming.method} ${url.split("?")[0]} via ${context.upstream.origin}`, error, requestId));
143
+ if (!outgoing.headersSent) {
144
+ outgoing.writeHead(502, { "content-type": "application/json" });
145
+ outgoing.end(JSON.stringify({ error: "Unable to reach upstream", requestId }));
146
+ }
147
+ else {
148
+ outgoing.destroy(error);
149
+ }
150
+ upstream.destroy();
151
+ }
152
+ upstream.on("error", fail);
153
+ incoming.on("data", (chunk) => requestChunks.push(Buffer.from(chunk)));
154
+ incoming.on("error", (error) => upstream.destroy(error));
155
+ outgoing.on("close", () => {
156
+ if (!responseComplete) {
157
+ clientClosed = true;
158
+ savePartialResponse?.();
159
+ upstream.destroy();
160
+ }
161
+ });
162
+ incoming.pipe(upstream);
163
+ }
164
+ //# sourceMappingURL=gateway.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gateway.js","sourceRoot":"","sources":["../src/gateway.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,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