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/dist/main.js ADDED
@@ -0,0 +1,80 @@
1
+ import fs from "node:fs/promises";
2
+ import { formatError, LoggerError } from "./errors.js";
3
+ import { createGateway } from "./gateway.js";
4
+ import { locations, readPreference, writePreference } from "./preferences.js";
5
+ import { resolveTarget, upstreamUrl } from "./targets.js";
6
+ import { choose } from "./wizard.js";
7
+ export async function main() {
8
+ const port = Number(process.env.PORT || 8787);
9
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
10
+ throw new Error("Invalid port.");
11
+ const paths = locations(process.env);
12
+ const target = await selectTarget(paths.preferenceFile, port, process.argv.includes("--force"));
13
+ if (!target)
14
+ return;
15
+ const override = testUpstream();
16
+ const server = createGateway({
17
+ target,
18
+ directory: paths.logDir,
19
+ override,
20
+ onCapture: (file) => console.log(`Captured ${file}`),
21
+ onError: (error) => console.error(formatError(error, process.env.REQUEST_LOGGER_DEBUG === "1")),
22
+ });
23
+ await listen(server, port);
24
+ printInstructions(target, paths, port, override);
25
+ }
26
+ async function selectTarget(preferenceFile, port, force) {
27
+ if (force)
28
+ await fs.rm(preferenceFile, { force: true });
29
+ const saved = force ? undefined : await readPreference(preferenceFile);
30
+ if (saved) {
31
+ try {
32
+ return resolveTarget(saved, port);
33
+ }
34
+ catch (error) {
35
+ console.warn(formatError(new LoggerError("SETUP_FAILED", "Saved setup could not be loaded; choose a setup again.", error)));
36
+ }
37
+ }
38
+ const selected = await choose(force || !!saved);
39
+ if (!selected)
40
+ return;
41
+ const target = resolveTarget(selected.choice, port);
42
+ if (selected.remember) {
43
+ try {
44
+ await writePreference(preferenceFile, selected.choice);
45
+ }
46
+ catch (error) {
47
+ // Remembering is optional: an unwritable preference directory should not
48
+ // prevent logging with the setup the user just selected.
49
+ console.warn(formatError(new LoggerError("PREFERENCES_FAILED", "Could not remember the setup.", error)));
50
+ }
51
+ }
52
+ return target;
53
+ }
54
+ function testUpstream() {
55
+ const configured = process.env.REQUEST_LOGGER_TEST_UPSTREAM;
56
+ if (!configured)
57
+ return;
58
+ const url = upstreamUrl(configured);
59
+ if (url.pathname !== "/")
60
+ throw new Error("Test upstream must be an origin without a path.");
61
+ return url;
62
+ }
63
+ async function listen(server, port) {
64
+ await new Promise((resolve, reject) => {
65
+ server.once("error", (error) => reject(new LoggerError("LISTEN_FAILED", `Cannot listen on 127.0.0.1:${port}. Use --port to choose another port.`, error)));
66
+ server.listen(port, "127.0.0.1", resolve);
67
+ });
68
+ }
69
+ function printInstructions(target, paths, port, override) {
70
+ console.log(`\n${target.name}\nListening: http://localhost:${port}\nUpstream: ${target.upstream}\nCaptures: ${paths.logDir}`);
71
+ if (override)
72
+ console.log(`TEST UPSTREAM OVERRIDE: ${override}`);
73
+ for (const file of target.files)
74
+ console.log(`\nMerge into ${file.path}:\n${file.content}`);
75
+ console.log(`\nRun in another terminal:\n\n${target.command}\n`);
76
+ for (const hint of target.hints)
77
+ console.log(hint);
78
+ console.log("\nCtrl+C stops the logger. Use --force to choose another setup.");
79
+ }
80
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAElC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAkB,SAAS,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAC9F,OAAO,EAAE,aAAa,EAAe,WAAW,EAAE,MAAM,cAAc,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,MAAM,CAAC,KAAK,UAAU,IAAI;IACxB,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG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AM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAC1C,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,CAC7B,MAAM,CACJ,IAAI,WAAW,CACb,eAAe,EACf,8BAA8B,IAAI,sCAAsC,EACxE,KAAK,CACN,CACF,CACF,CAAC;QACF,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC;IAC5C,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,iBAAiB,CAAC,MAAc,EAAE,KAAgB,EAAE,IAAY,EAAE,QAAc;IACvF,OAAO,CAAC,GAAG,CACT,KAAK,MAAM,CAAC,IAAI,iCAAiC,IAAI,eAAe,MAAM,CAAC,QAAQ,eAAe,KAAK,CAAC,MAAM,EAAE,CACjH,CAAC;IACF,IAAI,QAAQ;QAAE,OAAO,CAAC,GAAG,CAAC,2BAA2B,QAAQ,EAAE,CAAC,CAAC;IACjE,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK;QAAE,OAAO,CAAC,GAAG,CAAC,gBAAgB,IAAI,CAAC,IAAI,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;IAC5F,OAAO,CAAC,GAAG,CAAC,iCAAiC,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC;IACjE,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK;QAAE,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACnD,OAAO,CAAC,GAAG,CAAC,iEAAiE,CAAC,CAAC;AACjF,CAAC"}
@@ -0,0 +1,19 @@
1
+ /** Discovery is optional: unavailable or authenticated listings fall back to manual entry. */
2
+ export async function discoverModels(base) {
3
+ try {
4
+ const url = new URL(base);
5
+ const prefix = url.pathname.replace(/\/+$/, "");
6
+ url.pathname = prefix + (prefix.endsWith("/v1") ? "/models" : "/v1/models");
7
+ const response = await fetch(url, { signal: AbortSignal.timeout(3000) });
8
+ if (!response.ok)
9
+ return [];
10
+ const result = (await response.json());
11
+ return [
12
+ ...new Set((result.data ?? []).flatMap((item) => typeof item?.id === "string" && item.id.trim() ? [item.id] : [])),
13
+ ];
14
+ }
15
+ catch {
16
+ return [];
17
+ }
18
+ }
19
+ //# sourceMappingURL=model-discovery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-discovery.js","sourceRoot":"","sources":["../src/model-discovery.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,IAAY;IAC/C,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC;QAC1B,MAAM,MAAM,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QAChD,GAAG,CAAC,QAAQ,GAAG,MAAM,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;QAC5E,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACzE,IAAI,CAAC,QAAQ,CAAC,EAAE;YAAE,OAAO,EAAE,CAAC;QAC5B,MAAM,MAAM,GAAG,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAuC,CAAC;QAC7E,OAAO;YACL,GAAG,IAAI,GAAG,CACR,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CACnC,OAAO,IAAI,EAAE,EAAE,KAAK,QAAQ,IAAI,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAChE,CACF;SACF,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC"}
@@ -0,0 +1,41 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { isAgent, isProtocol } from "./targets.js";
5
+ // Resolve relative options against the launch directory, never the installed
6
+ // package location. Preferences alone use the home directory by default.
7
+ export function locations(env, cwd = process.cwd(), home = os.homedir()) {
8
+ return {
9
+ logDir: path.resolve(cwd, env.REQUEST_LOGGER_LOG_DIR || "request-logger-logs"),
10
+ preferenceFile: path.join(path.resolve(cwd, env.REQUEST_LOGGER_CONFIG_DIR || path.join(home, ".agent-request-logger")), ".agent-choice.json"),
11
+ };
12
+ }
13
+ export async function readPreference(file) {
14
+ try {
15
+ // Pick known fields explicitly so obsolete catalogue data never becomes
16
+ // runtime configuration merely because it was present in the saved file.
17
+ const value = JSON.parse(await fs.readFile(file, "utf8"));
18
+ if (!isAgent(value?.agent) || typeof value.provider !== "string")
19
+ return;
20
+ const choice = { agent: value.agent, provider: value.provider };
21
+ if (choice.provider !== "custom")
22
+ return choice;
23
+ if (typeof value.customBaseUrl !== "string" || !isProtocol(value.customRenderer))
24
+ return;
25
+ return {
26
+ ...choice,
27
+ customBaseUrl: value.customBaseUrl,
28
+ customRenderer: value.customRenderer,
29
+ customModel: typeof value.customModel === "string" ? value.customModel : undefined,
30
+ };
31
+ }
32
+ catch {
33
+ // Missing, unreadable, or damaged preferences all fall back to the wizard.
34
+ return;
35
+ }
36
+ }
37
+ export async function writePreference(file, choice) {
38
+ await fs.mkdir(path.dirname(file), { recursive: true });
39
+ await fs.writeFile(file, `${JSON.stringify(choice, null, 2)}\n`, { mode: 0o600 });
40
+ }
41
+ //# sourceMappingURL=preferences.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preferences.js","sourceRoot":"","sources":["../src/preferences.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,kBAAkB,CAA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GAAG,MAAM;YACT,aAAa,EAAE,KAAK,CAAC,aAAa;YAClC,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,WAAW,EAAE,OAAO,KAAK,CAAC,WAAW,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS;SACnF,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,2EAA2E;QAC3E,OAAO;IACT,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,IAAY,EAAE,MAAc;IAChE,MAAM,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACxD,MAAM,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;AACpF,CAAC"}
@@ -0,0 +1,136 @@
1
+ // Provider payloads are untrusted and change independently of this package.
2
+ // Check containers as they are read; the full payload is not schema-validated.
3
+ // The complete stream is also kept in the Markdown capture.
4
+ function array(value) {
5
+ return Array.isArray(value) ? value : [];
6
+ }
7
+ export function parseJson(text) {
8
+ try {
9
+ return JSON.parse(text);
10
+ }
11
+ catch {
12
+ return undefined;
13
+ }
14
+ }
15
+ function streamEvents(text) {
16
+ return text.split(/\r?\n\r?\n/).flatMap((event) => {
17
+ const data = event
18
+ .split(/\r?\n/)
19
+ .filter((line) => line.startsWith("data:"))
20
+ .map((line) => line.slice(5).trimStart())
21
+ .join("\n");
22
+ if (!data || data === "[DONE]")
23
+ return [];
24
+ const payload = parseJson(data);
25
+ return payload ? [payload] : [];
26
+ });
27
+ }
28
+ /** Decode either SSE events or one completed JSON response into display data. */
29
+ export function decodeResponse(text, protocol) {
30
+ const events = streamEvents(text);
31
+ const payloads = events.length ? events : [parseJson(text)].filter(Boolean);
32
+ const conversation = {
33
+ text: "",
34
+ reasoning: "",
35
+ tools: new Map(),
36
+ usage: [],
37
+ };
38
+ if (protocol !== "raw") {
39
+ for (const event of payloads) {
40
+ appendUsage(conversation, event);
41
+ if (protocol === "anthropic")
42
+ appendAnthropic(conversation, event);
43
+ else
44
+ appendOpenAI(conversation, event, events.length > 0);
45
+ }
46
+ }
47
+ return {
48
+ text: conversation.text,
49
+ reasoning: conversation.reasoning,
50
+ tools: [...conversation.tools.values()],
51
+ usage: conversation.usage,
52
+ payloads,
53
+ };
54
+ }
55
+ function appendUsage(result, event) {
56
+ for (const usage of [event.usage, event.message?.usage, event.response?.usage]) {
57
+ if (usage)
58
+ result.usage.push(usage);
59
+ }
60
+ }
61
+ function appendAnthropic(result, event) {
62
+ if (event.type === "content_block_start" && event.content_block?.type === "tool_use") {
63
+ result.tools.set(String(event.index), { name: event.content_block.name, arguments: "" });
64
+ }
65
+ if (event.delta?.text)
66
+ result.text += event.delta.text;
67
+ if (event.delta?.thinking)
68
+ result.reasoning += event.delta.thinking;
69
+ if (event.delta?.partial_json) {
70
+ const tool = result.tools.get(String(event.index));
71
+ if (tool)
72
+ tool.arguments += event.delta.partial_json;
73
+ }
74
+ // A non-streaming Messages response carries complete blocks instead of deltas.
75
+ for (const block of array(event.content)) {
76
+ if (block?.type === "text")
77
+ result.text += block.text ?? "";
78
+ if (block?.type === "thinking")
79
+ result.reasoning += block.thinking ?? "";
80
+ if (block?.type === "tool_use") {
81
+ result.tools.set(block.id, { name: block.name, arguments: JSON.stringify(block.input) });
82
+ }
83
+ }
84
+ }
85
+ function appendOpenAI(result, event, streaming) {
86
+ if (event.type === "response.output_text.delta")
87
+ result.text += event.delta ?? "";
88
+ if (event.type === "response.reasoning_summary_text.delta")
89
+ result.reasoning += event.delta ?? "";
90
+ if (event.type === "response.output_item.added" && event.item?.type === "function_call") {
91
+ result.tools.set(event.item.id, {
92
+ name: event.item.name,
93
+ arguments: event.item.arguments ?? "",
94
+ });
95
+ }
96
+ if (event.type === "response.function_call_arguments.delta") {
97
+ const tool = result.tools.get(event.item_id);
98
+ if (tool)
99
+ tool.arguments += event.delta ?? "";
100
+ }
101
+ for (const choice of array(event.choices)) {
102
+ appendChatMessage(result, choice?.delta ?? choice?.message);
103
+ }
104
+ // A completed stream repeats output items in its final response event.
105
+ // Read those only for JSON responses, or the text would be counted twice.
106
+ if (!streaming)
107
+ appendCompletedOutput(result, event.output);
108
+ }
109
+ function appendChatMessage(result, message) {
110
+ if (typeof message?.content === "string")
111
+ result.text += message.content;
112
+ if (message?.reasoning_content)
113
+ result.reasoning += message.reasoning_content;
114
+ for (const call of array(message?.tool_calls)) {
115
+ if (!call || typeof call !== "object")
116
+ continue;
117
+ // Stream fragments identify a call by index; complete messages use an ID.
118
+ const key = String(call.index ?? call.id);
119
+ const tool = result.tools.get(key) ?? { name: "", arguments: "" };
120
+ tool.name += call.function?.name ?? "";
121
+ tool.arguments += call.function?.arguments ?? "";
122
+ result.tools.set(key, tool);
123
+ }
124
+ }
125
+ function appendCompletedOutput(result, output) {
126
+ for (const item of array(output)) {
127
+ for (const content of array(item?.content)) {
128
+ if (content?.type === "output_text")
129
+ result.text += content.text ?? "";
130
+ }
131
+ if (item?.type === "function_call") {
132
+ result.tools.set(item.id, { name: item.name, arguments: item.arguments });
133
+ }
134
+ }
135
+ }
136
+ //# sourceMappingURL=response-decoder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response-decoder.js","sourceRoot":"","sources":["../src/response-decoder.ts"],"names":[],"mappings":"AAqBA,4EAA4E;AAC5E,+EAA+E;AAC/E,4DAA4D;AAC5D,SAAS,KAAK,CAAC,KAAc;IAC3B,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AAC3C,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,IAAI,CAAC;QACH,OAAO,IAAI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,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ;YAAE,SAAS;QAChD,0EAA0E;QAC1E,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC;QAC1C,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC;QAClE,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC;QACvC,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,QAAQ,EAAE,SAAS,IAAI,EAAE,CAAC;QACjD,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC;AAED,SAAS,qBAAqB,CAAC,MAAoB,EAAE,MAAe;IAClE,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;QACjC,KAAK,MAAM,OAAO,IAAI,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,CAAC;YAC3C,IAAI,OAAO,EAAE,IAAI,KAAK,aAAa;gBAAE,MAAM,CAAC,IAAI,IAAI,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC;QACzE,CAAC;QACD,IAAI,IAAI,EAAE,IAAI,KAAK,eAAe,EAAE,CAAC;YACnC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC;QAC5E,CAAC;IACH,CAAC;AACH,CAAC"}
@@ -0,0 +1,106 @@
1
+ import { buildAgentSetup } from "./agent-setup.js";
2
+ const route = (label, url, protocol) => ({ label, url, protocol });
3
+ export const catalogue = {
4
+ "claude-code": {
5
+ label: "Claude Code",
6
+ routes: {
7
+ anthropic: route("Anthropic / Claude subscription", "https://api.anthropic.com", "anthropic"),
8
+ },
9
+ },
10
+ codex: {
11
+ label: "Codex",
12
+ routes: {
13
+ chatgpt: route("ChatGPT subscription", "https://chatgpt.com", "openai"),
14
+ openai: route("OpenAI API key", "https://api.openai.com", "openai"),
15
+ },
16
+ },
17
+ copilot: {
18
+ label: "GitHub Copilot CLI",
19
+ routes: {
20
+ github: route("GitHub subscription", "https://api.githubcopilot.com", "openai"),
21
+ },
22
+ },
23
+ opencode: {
24
+ label: "OpenCode",
25
+ routes: {
26
+ anthropic: route("Anthropic API key", "https://api.anthropic.com", "anthropic"),
27
+ openai: route("OpenAI API key", "https://api.openai.com", "openai"),
28
+ },
29
+ },
30
+ pi: {
31
+ label: "Pi",
32
+ routes: {
33
+ anthropic: route("Anthropic API key", "https://api.anthropic.com", "anthropic"),
34
+ openai: route("OpenAI API key", "https://api.openai.com", "openai"),
35
+ codex: route("ChatGPT subscription", "https://chatgpt.com", "openai"),
36
+ },
37
+ },
38
+ };
39
+ export function isAgent(value) {
40
+ return typeof value === "string" && Object.hasOwn(catalogue, value);
41
+ }
42
+ export function isProtocol(value) {
43
+ return value === "anthropic" || value === "openai" || value === "raw";
44
+ }
45
+ export function upstreamUrl(text) {
46
+ const url = new URL(text);
47
+ if (!["http:", "https:"].includes(url.protocol) ||
48
+ url.username ||
49
+ url.password ||
50
+ url.search ||
51
+ url.hash) {
52
+ throw new Error("Use an HTTP(S) base URL without credentials, query parameters, or a fragment.");
53
+ }
54
+ url.pathname = url.pathname.replace(/\/+$/, "") || "/";
55
+ return url;
56
+ }
57
+ export function needsModel(choice) {
58
+ return (choice.provider === "custom" &&
59
+ (choice.agent === "pi" || (choice.agent === "opencode" && choice.customRenderer === "openai")));
60
+ }
61
+ /** Keep this free of network and filesystem work so saved and new choices
62
+ * resolve the same way.
63
+ */
64
+ export function resolveTarget(choice, port) {
65
+ if (!isAgent(choice.agent)) {
66
+ throw new Error("This saved agent is unavailable. Choose again with --force.");
67
+ }
68
+ const agent = catalogue[choice.agent];
69
+ const selected = resolveProvider(choice);
70
+ const upstream = upstreamUrl(selected.url);
71
+ const model = choice.customModel?.trim();
72
+ if (needsModel(choice) && !model) {
73
+ throw new Error("This custom setup needs a model ID. Choose again with --force.");
74
+ }
75
+ const setup = buildAgentSetup({
76
+ choice,
77
+ protocol: selected.protocol,
78
+ localUrl: `http://localhost:${port}`,
79
+ model,
80
+ });
81
+ if (choice.provider === "custom") {
82
+ setup.hints.push("The wire format controls display only; the endpoint must accept the agent's own protocol.");
83
+ }
84
+ return {
85
+ name: `${agent.label} · ${selected.label}`,
86
+ upstream,
87
+ protocol: selected.protocol,
88
+ ...setup,
89
+ };
90
+ }
91
+ function resolveProvider(choice) {
92
+ if (choice.provider === "custom") {
93
+ if (!choice.customBaseUrl)
94
+ throw new Error("A custom upstream URL is required.");
95
+ if (!isProtocol(choice.customRenderer)) {
96
+ throw new Error("Choose a supported wire format with --force.");
97
+ }
98
+ return { label: "Custom upstream", url: choice.customBaseUrl, protocol: choice.customRenderer };
99
+ }
100
+ const routes = catalogue[choice.agent].routes;
101
+ if (!Object.hasOwn(routes, choice.provider)) {
102
+ throw new Error("This saved provider is unavailable. Choose again with --force.");
103
+ }
104
+ return routes[choice.provider];
105
+ }
106
+ //# sourceMappingURL=targets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"targets.js","sourceRoot":"","sources":["../src/targets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAgCnD,MAAM,KAAK,GAAG,CAAC,KAAa,EAAE,GAAW,EAAE,QAAkB,EAAS,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,QAAQ,EAAE,CAAC,CAAC;AACpG,MAAM,CAAC,MAAM,SAAS,GAA2B;IAC/C,aAAa,EAAE;QACb,KAAK,EAAE,aAAa;QACpB,MAAM,EAAE;YACN,SAAS,EAAE,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Q,CAAC,CAAC;AACjC,CAAC"}
package/dist/wizard.js ADDED
@@ -0,0 +1,96 @@
1
+ import * as prompts from "@clack/prompts";
2
+ import { discoverModels } from "./model-discovery.js";
3
+ import { catalogue, needsModel, upstreamUrl, } from "./targets.js";
4
+ class Cancelled extends Error {
5
+ }
6
+ // Cancellation unwinds all nested questions to the single exit point in choose.
7
+ function answer(result) {
8
+ if (prompts.isCancel(result))
9
+ throw new Cancelled();
10
+ return result;
11
+ }
12
+ export async function choose(rememberByDefault = false) {
13
+ try {
14
+ prompts.intro("Agent request logger");
15
+ const agent = answer(await prompts.select({
16
+ message: "Agent to inspect",
17
+ options: Object.entries(catalogue).map(([value, entry]) => ({
18
+ value: value,
19
+ label: entry.label,
20
+ })),
21
+ }));
22
+ const provider = answer(await prompts.select({
23
+ message: "Provider",
24
+ options: [
25
+ ...Object.entries(catalogue[agent].routes).map(([value, entry]) => ({
26
+ value,
27
+ label: entry.label,
28
+ })),
29
+ { value: "custom", label: "Custom base URL" },
30
+ ],
31
+ }));
32
+ const choice = { agent, provider };
33
+ if (provider === "custom")
34
+ Object.assign(choice, await askCustomSetup(choice));
35
+ // Replacing an already remembered setup should not ask permission to save it again.
36
+ const remember = rememberByDefault ||
37
+ answer(await prompts.confirm({
38
+ message: "Remember this setup?",
39
+ initialValue: true,
40
+ }));
41
+ return { choice, remember };
42
+ }
43
+ catch (error) {
44
+ if (!(error instanceof Cancelled))
45
+ throw error;
46
+ prompts.cancel("Setup cancelled.");
47
+ return;
48
+ }
49
+ }
50
+ async function askCustomSetup(choice) {
51
+ const customBaseUrl = answer(await prompts.text({
52
+ message: "Upstream base URL",
53
+ placeholder: "http://localhost:11434",
54
+ validate(value) {
55
+ try {
56
+ upstreamUrl(value ?? "");
57
+ }
58
+ catch {
59
+ return "Enter an HTTP(S) URL without credentials, query, or fragment.";
60
+ }
61
+ },
62
+ })).trim();
63
+ const customRenderer = answer(await prompts.select({
64
+ message: "Capture format",
65
+ options: [
66
+ { value: "openai", label: "OpenAI" },
67
+ { value: "anthropic", label: "Anthropic" },
68
+ { value: "raw", label: "Raw JSON" },
69
+ ],
70
+ }));
71
+ const setup = { customBaseUrl, customRenderer };
72
+ if (needsModel({ ...choice, customRenderer })) {
73
+ setup.customModel = await askModelId(customBaseUrl);
74
+ }
75
+ return setup;
76
+ }
77
+ async function askModelId(baseUrl) {
78
+ const models = await discoverModels(baseUrl);
79
+ if (models.length) {
80
+ // Tagged values avoid collisions with a real model named "manual".
81
+ const selection = answer(await prompts.select({
82
+ message: "Model",
83
+ options: [
84
+ ...models.map((id) => ({ value: { id }, label: id })),
85
+ { value: null, label: "Enter a model ID" },
86
+ ],
87
+ }));
88
+ if (selection)
89
+ return selection.id;
90
+ }
91
+ return answer(await prompts.text({
92
+ message: "Model ID",
93
+ validate: (value) => (value?.trim() ? undefined : "Enter a model ID."),
94
+ })).trim();
95
+ }
96
+ //# sourceMappingURL=wizard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wizard.js","sourceRoot":"","sources":["../src/wizard.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAGL,SAAS,EACT,UAAU,EAEV,WAAW,GACZ,MAAM,cAAc,CAAC;AAItB,MAAM,SAAU,SAAQ,KAAK;CAAG;AAEhC,gFAAgF;AAChF,SAAS,MAAM,CAAI,MAAS;IAC1B,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,MAAM,IAAI,SAAS,EAAE,CAAC;IACpD,OAAO,MAA4B,CAAC;AACtC,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,iBAAiB,GAAG,KAAK;IACpD,IAAI,CAAC;QACH,OAAO,CAAC,KAAK,CAAC,sBAAsB,CAAC,CAAC;QACtC,MAAM,KAAK,GAAG,MAAM,CAClB,MAAM,OAAO,CAAC,MAAM,CAAU;YAC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OAAO,EAAE,OAAO;YAChB,OAAO,EAAE;gBACP,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;gBACrD,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,kBAAkB,EAAE;aAC3C;SACF,CAAC,CACH,CAAC;QACF,IAAI,SAAS;YAAE,OAAO,SAAS,CAAC,EAAE,CAAC;IACrC,CAAC;IACD,OAAO,MAAM,CACX,MAAM,OAAO,CAAC,IAAI,CAAC;QACjB,OAAO,EAAE,UAAU;QACnB,QAAQ,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,mBAAmB,CAAC;KACvE,CAAC,CACH,CAAC,IAAI,EAAE,CAAC;AACX,CAAC"}
package/docs/agents.md ADDED
@@ -0,0 +1,72 @@
1
+ # Agent setup
2
+
3
+ Choose your agent and provider in the logger, then follow the command and
4
+ configuration instructions it prints. Install and authenticate the agent
5
+ separately. Use bash or zsh for the generated commands.
6
+
7
+ | Agent | Provider choices | Configuration |
8
+ | ------------------ | ------------------------------------------ | ---------------------------------------------------------------- |
9
+ | Claude Code | Anthropic API or Claude subscription | An environment override; tool search remains enabled |
10
+ | Codex | OpenAI API key or ChatGPT subscription | A configuration override for the current invocation |
11
+ | GitHub Copilot CLI | GitHub subscription | An API URL environment override |
12
+ | OpenCode | Anthropic or OpenAI API key | An environment override, with provider configuration when needed |
13
+ | Pi | Anthropic, OpenAI, or ChatGPT subscription | Provider overrides in `~/.pi/agent/models.json` |
14
+
15
+ Merge printed file settings into your existing configuration. Pi's ChatGPT
16
+ route also prints SSE transport settings for `~/.pi/agent/settings.json`.
17
+ OpenCode's OpenAI route expects an API key; its ChatGPT subscription route
18
+ is not covered.
19
+
20
+ ## Custom providers
21
+
22
+ Every agent offers **Custom base URL**. Enter an HTTP or HTTPS address,
23
+ including a port or path prefix if needed, and select OpenAI, Anthropic,
24
+ or raw capture rendering. Configure authentication in the agent; URLs with
25
+ credentials, query parameters, or fragments are rejected.
26
+
27
+ The rendering choice controls how the logger displays captures. It does not
28
+ translate requests between protocols. The endpoint must accept the format
29
+ the agent actually sends.
30
+
31
+ Pi custom setups and OpenCode's OpenAI-compatible custom setup require a model
32
+ ID. The wizard tries an unauthenticated `/v1/models` listing; you can choose a
33
+ listed model or enter one manually. Manual entry also works when discovery is
34
+ unavailable or requires authentication.
35
+
36
+ OpenCode uses temporary provider configuration for its custom OpenAI route.
37
+ Pi prints a provider model override containing your selected model; that
38
+ replaces the provider's built-in model list.
39
+
40
+ ## Troubleshooting
41
+
42
+ **No captures:** Start the agent after applying the printed command. Check the
43
+ selected provider and log directory. Connectivity checks and token-counting
44
+ requests pass through without capture. Some agents use WebSockets; those
45
+ requests receive HTTP 426 because this proxy captures HTTP only.
46
+
47
+ **Upstream connection fails:** Check the scheme, host, port, path prefix,
48
+ credentials, and model ID. Connection failures return HTTP 502 with a request
49
+ ID; console diagnostics identify the operation and underlying cause. Use
50
+ `--debug` to include stacks.
51
+
52
+ **Many identical requests:** An agent may be retrying an upstream failure.
53
+ The logger forwards the responses but limits identical model captures to
54
+ 20 per two-second window. It does not retry requests itself.
55
+
56
+ **Unexpected output:** The complete request and response stream remain in
57
+ the Markdown capture, and separate files preserve the original body bytes.
58
+ A provider-specific field may be visible there even if it has no dedicated
59
+ summary section.
60
+
61
+ ## Limits and verification
62
+
63
+ This is a local inspection tool. Request and response bodies are buffered
64
+ until a response finishes, so avoid using it as a production telemetry proxy
65
+ or for arbitrarily large streams.
66
+
67
+ Pinned real-agent checks exercise six API-key routes against a local provider
68
+ with dummy credentials. They verify routing and captures, not live provider
69
+ acceptance. Copilot and subscription logins require manual checks with real
70
+ accounts. See [testing](testing.md) for the distinction.
71
+
72
+ Return to [installation and usage](../README.md).