@schlenkr/ragents 0.1.15 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/apps/server/src/plugin-support/actor-programs/app-project.ts +1 -1
  2. package/apps/server/src/plugin-support/actor-programs/client-contracts.ts +47 -8
  3. package/apps/web/dist/host-web.json +1 -1
  4. package/bundles/ragents.activity/ragents-bundle.json +1 -1
  5. package/bundles/ragents.actor-programs/ragents-bundle.json +1 -1
  6. package/bundles/ragents.ask/ragents-bundle.json +1 -1
  7. package/bundles/ragents.browser/ragents-bundle.json +1 -1
  8. package/bundles/ragents.documents/ragents-bundle.json +1 -1
  9. package/bundles/ragents.lsp-fsharp/ragents-bundle.json +1 -1
  10. package/bundles/ragents.lsp-roslyn/ragents-bundle.json +1 -1
  11. package/bundles/ragents.lsp-typescript/ragents-bundle.json +1 -1
  12. package/bundles/ragents.model-relay/ragents-bundle.json +1 -1
  13. package/bundles/ragents.orchestration/ragents-bundle.json +1 -1
  14. package/bundles/ragents.overseer/ragents-bundle.json +1 -1
  15. package/bundles/ragents.processes/ragents-bundle.json +1 -1
  16. package/bundles/ragents.product/ragents-bundle.json +1 -1
  17. package/bundles/ragents.profile-distribution/ragents-bundle.json +1 -1
  18. package/bundles/ragents.reference/ragents-bundle.json +1 -1
  19. package/bundles/ragents.todo/ragents-bundle.json +1 -1
  20. package/bundles/ragents.transcript/ragents-bundle.json +1 -1
  21. package/bundles/ragents.watch/ragents-bundle.json +1 -1
  22. package/bundles/ragents.workspace/ragents-bundle.json +1 -1
  23. package/package.json +3 -2
  24. package/packages/ai/dist/api/openai-compatible-response.d.ts +2 -0
  25. package/packages/ai/package.json +1 -0
  26. package/packages/ai/src/api/ai-sdk-transport.ts +4 -2
  27. package/packages/ai/src/api/openai-compatible-response.ts +60 -0
@@ -13,7 +13,7 @@ import { runtimeLibraries, webRuntimeLibraries } from "./runtime-libraries.js";
13
13
  const webRequire = createRequire(new URL("../../../../web/package.json", import.meta.url));
14
14
  const rootRequire = createRequire(new URL("../../../../../package.json", import.meta.url));
15
15
  const serverRequire = createRequire(new URL("../../../package.json", import.meta.url));
16
- const serverTypeRoot = fileURLToPath(new URL("../../../node_modules/@types", import.meta.url));
16
+ const serverTypeRoot = path.dirname(path.dirname(serverRequire.resolve("@types/node/package.json")));
17
17
  const libraryDirectory = (name: string): string => {
18
18
  const resolver = (webRuntimeLibraries as readonly string[]).includes(name) ? webRequire
19
19
  : name === "@types/node" || name === "tsx" ? serverRequire : rootRequire;
@@ -1,16 +1,55 @@
1
+ import { realpathSync } from "node:fs";
1
2
  import path from "node:path";
2
3
  import { fileURLToPath } from "node:url";
3
4
  import ts from "typescript";
4
5
 
5
- function readContracts(repoRoot: string): { names: string[]; files: Record<string, string> } {
6
- const filename = path.join(repoRoot, "apps/web/src/actor-programs/client-ui/contracts.d.ts");
6
+ export function clientUiContractPaths(directory: string, paths: typeof path.posix = path) {
7
+ const canonical = (name: string) => paths.resolve(name).replaceAll(paths.sep, "/").replace(/^[a-z]:/, (drive) => drive.toUpperCase());
8
+ const repoRoot = canonical(directory);
9
+ const root = canonical(paths.join(paths.parse(repoRoot).root, "__ragents_ui_contract__"));
10
+ const contains = (base: string, name: string) => name === base || name.startsWith(`${base}/`);
11
+ const physical = (name: string) => {
12
+ const file = canonical(name);
13
+ return paths.normalize(contains(root, file) ? repoRoot + file.slice(root.length) : file);
14
+ };
15
+ const virtual = (name: string) => {
16
+ const file = canonical(name);
17
+ return contains(repoRoot, file) ? root + file.slice(repoRoot.length) : file;
18
+ };
19
+ return { root, physical, virtual, isVirtual: (name: string) => contains(root, canonical(name)) };
20
+ }
21
+
22
+ function readContracts(directory: string): { names: string[]; files: Record<string, string> } {
23
+ const { root, physical, virtual, isVirtual } = clientUiContractPaths(realpathSync(directory));
24
+ const filename = `${root}/apps/web/src/actor-programs/client-ui/contracts.d.ts`;
7
25
  const options: ts.CompilerOptions = {
8
26
  target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext,
9
27
  moduleResolution: ts.ModuleResolutionKind.Bundler, jsx: ts.JsxEmit.ReactJSX,
10
28
  strict: true, skipLibCheck: true, esModuleInterop: true,
11
29
  declaration: true, emitDeclarationOnly: true,
12
30
  };
13
- const program = ts.createProgram([filename], options);
31
+ // TypeScript must see public sources outside node_modules, including during declaration naming.
32
+ const host = ts.createCompilerHost(options);
33
+ host.readFile = (name) => ts.sys.readFile(physical(name));
34
+ host.fileExists = (name) => ts.sys.fileExists(physical(name));
35
+ host.directoryExists = (name) => ts.sys.directoryExists(physical(name));
36
+ host.getDirectories = (name) => ts.sys.getDirectories(physical(name));
37
+ host.realpath = (name) => virtual(ts.sys.realpath!(physical(name)));
38
+ host.getSourceFile = (name, languageVersion) => {
39
+ const text = host.readFile(name);
40
+ return text === undefined ? undefined : ts.createSourceFile(virtual(name), text, languageVersion, true);
41
+ };
42
+ const resolveModule = (name: string, containingFile: string) => {
43
+ const mapped = ts.resolveModuleName(name, containingFile, options, host).resolvedModule;
44
+ if (mapped) return mapped;
45
+ const resolved = ts.resolveModuleName(name, physical(containingFile), options, ts.sys).resolvedModule;
46
+ if (!resolved) return undefined;
47
+ const resolvedFileName = virtual(resolved.resolvedFileName);
48
+ return { ...resolved, resolvedFileName, isExternalLibraryImport: isVirtual(resolvedFileName)
49
+ ? path.posix.relative(root, resolvedFileName).split("/").includes("node_modules") : resolved.isExternalLibraryImport };
50
+ };
51
+ host.resolveModuleNames = (names, containingFile) => names.map((name) => resolveModule(name, containingFile));
52
+ const program = ts.createProgram([filename], options, host);
14
53
  const source = program.getSourceFile(filename);
15
54
  if (!source) throw new Error("The public UI contract is missing.");
16
55
  const checker = program.getTypeChecker();
@@ -27,8 +66,8 @@ function readContracts(repoRoot: string): { names: string[]; files: Record<strin
27
66
  const collect = (file: ts.SourceFile) => {
28
67
  if (visited.has(file.fileName)) return;
29
68
  visited.add(file.fileName);
30
- const relative = path.relative(repoRoot, file.fileName).replaceAll(path.sep, "/");
31
- if (relative.startsWith("../") || relative.includes("node_modules/")) throw new Error("A local UI type reference leaves the public repository sources.");
69
+ const relative = path.posix.relative(root, file.fileName);
70
+ if (!isVirtual(file.fileName) || relative.includes("node_modules/")) throw new Error("A local UI type reference leaves the public repository sources.");
32
71
  diagnostics.push(...program.getSyntacticDiagnostics(file), ...program.getSemanticDiagnostics(file));
33
72
  let text = file.isDeclarationFile ? file.text : "";
34
73
  if (!file.isDeclarationFile) {
@@ -41,13 +80,13 @@ function readContracts(repoRoot: string): { names: string[]; files: Record<strin
41
80
  const references = ts.preProcessFile(text, true, true);
42
81
  for (const reference of references.importedFiles) {
43
82
  if (!reference.fileName.startsWith(".")) continue;
44
- const resolved = ts.resolveModuleName(reference.fileName, file.fileName, options, ts.sys).resolvedModule;
83
+ const resolved = resolveModule(reference.fileName, file.fileName);
45
84
  const dependency = resolved && program.getSourceFile(resolved.resolvedFileName);
46
85
  if (!dependency) throw new Error(`Unresolvable local UI type reference: ${relative}: ${reference.fileName}`);
47
86
  collect(dependency);
48
87
  }
49
88
  for (const reference of declaration.referencedFiles) {
50
- const dependency = program.getSourceFile(path.resolve(path.dirname(file.fileName), reference.fileName));
89
+ const dependency = program.getSourceFile(path.posix.resolve(path.posix.dirname(file.fileName), reference.fileName));
51
90
  if (!dependency) throw new Error(`Unresolvable UI type file reference: ${relative}: ${reference.fileName}`);
52
91
  collect(dependency);
53
92
  }
@@ -76,7 +115,7 @@ export function readClientUiComponentContracts(component: string, repoRoot?: str
76
115
  }
77
116
 
78
117
  export function readClientUiExportContracts(component: string, repoRoot?: string): Record<string, string> {
79
- const root = repoRoot ?? fileURLToPath(new URL("../../../../../", import.meta.url));
118
+ const root = realpathSync(repoRoot ?? fileURLToPath(new URL("../../../../../", import.meta.url)));
80
119
  const catalog = contracts(repoRoot);
81
120
  const files = new Map(Object.entries(catalog.files).map(([name, text]) => [path.resolve(root, name), text]));
82
121
  const options: ts.CompilerOptions = { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler, strict: true, skipLibCheck: true };
@@ -138,6 +138,6 @@
138
138
  "packages/ragents/src/rpc/peer.ts": "9050dff218bdc6603478a77bdca241629f55c03b65f6efe7df598b53446b4c09",
139
139
  "packages/ragents/src/rpc/protocol.ts": "82bbcb8181a2f90708dc607922fef4a9d472cd82d6dede09324df778773699a6",
140
140
  "packages/ragents/src/runtime/domain-error.ts": "d6bf8fa09769c4137e616c83a84cb9c05a58bfa6c2e32c9404a1c202815837a4",
141
- "pnpm-lock.yaml": "7a0ed220c7b68d8da22c5b6df864934dafa53aecad8e61d438ee86ddf79ee108"
141
+ "pnpm-lock.yaml": "2428bb94f1bb44305e258747adef0db465a9dcceacc8eb901d082e3acfd06b2f"
142
142
  }
143
143
  }
@@ -23,7 +23,7 @@
23
23
  }
24
24
  },
25
25
  "revision": "b7b04d050f5f4bcb0980880167b8e2cdd3ad533ba07f589dd0de471b9e55c0fd",
26
- "sourceRevision": "047290b262944aedbbbb4c4a819509c4bc3a7e0df4fa76b38d9e21ebe5626828",
26
+ "sourceRevision": "51444903dfadf6f23f55ad0369575949aec7fd1696b5f34450834d06a3fd23ed",
27
27
  "server": "server/index.js",
28
28
  "web": {
29
29
  "entry": "web/index.js",
@@ -195,7 +195,7 @@
195
195
  }
196
196
  },
197
197
  "revision": "15fc5afb9aac414335069c28989cae4fa95fec8a2937584f8497a42ce01ffaba",
198
- "sourceRevision": "6abd7c9e82683655c2bf5010641391a3960ccf495729a87ef00ef58cfb07f7af",
198
+ "sourceRevision": "1e6b4725db96bd433b77a1f09f751a41152f77d2d394736bc51886b32ccdd691",
199
199
  "server": "server/index.js",
200
200
  "web": {
201
201
  "entry": "web/index.js",
@@ -72,7 +72,7 @@
72
72
  }
73
73
  },
74
74
  "revision": "0c115b8cade07b18dee1b1d11200bbc0427d98d13d0315d9bd47c8619ded8fbc",
75
- "sourceRevision": "79645163f0f2b1d740c94f0d0fd881b5a55bee6bcf7af7b21b827b7254e7b4c5",
75
+ "sourceRevision": "ce0c0ff38394586fe032f02838bd9fcf644642c31f4a08f1575ca2aaade7bfbf",
76
76
  "server": "server/index.js",
77
77
  "web": {
78
78
  "entry": "web/index.js",
@@ -32,7 +32,7 @@
32
32
  "web": {}
33
33
  },
34
34
  "revision": "333c6a9b57576a4ab95556e201da67ed864acdf02787ce5edbd653e7beba6020",
35
- "sourceRevision": "6c3246a05b9b6ddc46373f88bca9113a2b1705487b4de41711be7f5ccb5617f3",
35
+ "sourceRevision": "43dc6b7d6064ff67e5bbd6ab2a32ee77bca8e562a2c1566fb223ec2f7d5c6792",
36
36
  "server": "server/index.js",
37
37
  "executor": "executor/index.mjs",
38
38
  "exports": {
@@ -101,7 +101,7 @@
101
101
  }
102
102
  },
103
103
  "revision": "3fdba8c39f30027176229901cf731b778170f0e1597c287ad94f7e48a430b5e8",
104
- "sourceRevision": "8875b59b406fa0e663b9f69dff1f6525bff867dca5947d3e114084650393ebf2",
104
+ "sourceRevision": "4ec5929328998f6fff1cb2d4dd5a97d8d2352b1b858e4a88706728eafe2fead1",
105
105
  "server": "server/index.js",
106
106
  "web": {
107
107
  "entry": "web/index.js",
@@ -29,7 +29,7 @@
29
29
  }
30
30
  },
31
31
  "revision": "a39dafc264c6703d9481f358b21e5bf3997dc5d2dc7fe0d969d4905d49c7a1f8",
32
- "sourceRevision": "4ff8724bbc7065832b907cfc53ea561fa4df3e8802f2937e0df6963840baba31",
32
+ "sourceRevision": "0c1724bed58160a4bfb446c45ef22ea4fa063a43b358d7c78ef64b220b36f653",
33
33
  "server": "server/index.js",
34
34
  "web": {
35
35
  "entry": "web/index.js",
@@ -41,7 +41,7 @@
41
41
  }
42
42
  },
43
43
  "revision": "cbe81aa88a4ea56476537fabbbb0995d09ccbfa269dd6a003df50a57c8286b02",
44
- "sourceRevision": "0bb27e39ad643657c464d5c3c28d045ed71c2164dea8e76c4c0ffe491a84442a",
44
+ "sourceRevision": "f351e54c82571eb6cde2b5e75379e9d6f13e8f57b38bd36d661e68b53d2e355d",
45
45
  "server": "server/index.js",
46
46
  "web": {
47
47
  "entry": "web/index.js",
@@ -18,7 +18,7 @@
18
18
  }
19
19
  },
20
20
  "revision": "8387de707a4fe8fdb8c67315346522b331728f8adf51a7fadda8db662681f0c4",
21
- "sourceRevision": "9b9bdd5a6858ef808ae2541fefb7cb0262e4bc963cfb0674166ff9a29da22c5c",
21
+ "sourceRevision": "b188ca64f6ebf562df726715a505837a537cf9a432d549dc3dbec205ed8ff5ab",
22
22
  "server": "server/index.js",
23
23
  "web": {
24
24
  "entry": "web/index.js",
@@ -26,7 +26,7 @@
26
26
  "web": {}
27
27
  },
28
28
  "revision": "9090692eca49235944f149b25dccdc986a3c638007d8da2fb35f74d942454379",
29
- "sourceRevision": "9548157817cee5c693da03f3a7e0f37e1099915826ef682cb0339a32736b70ef",
29
+ "sourceRevision": "f57ee897c518cd93bc1a089c0e37ed0154b04da83549ecedcc3c340ab1e36c62",
30
30
  "server": "server/index.js",
31
31
  "exports": {
32
32
  "server": {},
@@ -173,7 +173,7 @@
173
173
  }
174
174
  },
175
175
  "revision": "cbd72b88af0c8ac76486b4c0617545fc53b23315cf93dd924631ceb8e389b34b",
176
- "sourceRevision": "306e4ba17b1cae6ee69a03bf8dd492a61b51eccc426b68bb55ab9b6721f08e0c",
176
+ "sourceRevision": "2a6a34d768f487b027fbffac38beed2afb04c8bbec3311d8f05ce7cd5d90ef4c",
177
177
  "server": "server/index.js",
178
178
  "web": {
179
179
  "entry": "web/index.js",
@@ -130,7 +130,7 @@
130
130
  }
131
131
  },
132
132
  "revision": "58b8b02a346c4323afdef69cfd96b8f3717806919f2c46f146bcc803ef12bac4",
133
- "sourceRevision": "9310057d7fc569e6a0d103d727131e6644899a9ccf17c9ba79680cc3539c9a16",
133
+ "sourceRevision": "23351003ee6534e2535ca08493c457c7366047bd1b4de4ef267fcac618bdef37",
134
134
  "server": "server/index.js",
135
135
  "web": {
136
136
  "entry": "web/index.js",
@@ -78,7 +78,7 @@
78
78
  }
79
79
  },
80
80
  "revision": "e602a8711818533fc7372c5cb2ca51ae55362079d9944da008db9084621b5ccc",
81
- "sourceRevision": "0d7379e3a1c3fe42300ff72891203b4c4c043ce8720e58152358571b7af8adf1",
81
+ "sourceRevision": "7913d1ad21363aa3742d7c2b5b32ab7b3be49aeef8d9fc3c9a5caf5df28cab2c",
82
82
  "server": "server/index.js",
83
83
  "web": {
84
84
  "entry": "web/index.js",
@@ -76,7 +76,7 @@
76
76
  }
77
77
  },
78
78
  "revision": "7a3eb7a847ce6a4c8324b9c073c3c7a13c760088a194d419fe21342575c4208f",
79
- "sourceRevision": "7c8b3522ee90f89a7d3941ea396c458980ac53c83fa5096eab5a19b5f1a7aa81",
79
+ "sourceRevision": "9164cdb7e60d692e88452d5f24dbd6bbbcb8e9eafff911e84726d3cad345cb10",
80
80
  "server": "server/index.js",
81
81
  "web": {
82
82
  "entry": "web/index.js",
@@ -53,7 +53,7 @@
53
53
  "web": {}
54
54
  },
55
55
  "revision": "3e99cf5cb8921685ad83aa6aaf9657da4c648f9d68cb744988a73f227c342e1d",
56
- "sourceRevision": "cbf9d98fe42583b619b84425e648666df7cafd04930cf0692b43a5943fb4bd39",
56
+ "sourceRevision": "37a64513c41b585ecfef5171e26eac917e7cb69f069e057f0f62bbc3bfbba29e",
57
57
  "server": "server/index.js",
58
58
  "exports": {
59
59
  "server": {},
@@ -21,7 +21,7 @@
21
21
  }
22
22
  },
23
23
  "revision": "2c684e9daab9b2ffe4c002c03d4fa8549b2d4dd0b20513fb5eec0e4f10a396ee",
24
- "sourceRevision": "0f2f0bb43908bed73e743ed21d07d35abed4bcc84563c893c5c32117ad559ade",
24
+ "sourceRevision": "3e5f750bd9f707910743092b94df19a6b9bf9956ad7ab33818b5cd820bb85075",
25
25
  "server": "server/index.js",
26
26
  "web": {
27
27
  "entry": "web/index.js",
@@ -33,7 +33,7 @@
33
33
  }
34
34
  },
35
35
  "revision": "5e18b249f3c8b53b61820ef05da59823d58163c6962e6d836dcb37c05034aad0",
36
- "sourceRevision": "e69f899d1733ba54341bfc2fd8c6adbf6025126a4b21a74bdd8206378e86b87e",
36
+ "sourceRevision": "1c5eafe2e0da0c98f0c03b6cdd33b3d3cddc799da393df6a94c6d290fb285cbd",
37
37
  "server": "server/index.js",
38
38
  "web": {
39
39
  "entry": "web/index.js",
@@ -23,7 +23,7 @@
23
23
  "web": {}
24
24
  },
25
25
  "revision": "e3bb513053f6385f9d78d314d28302324095a5163c4e1563df6fc8b3251305f7",
26
- "sourceRevision": "7df3be99d8024c7878a0afe2bcd698909b6389f4484d98f84a0e3bdead954ab4",
26
+ "sourceRevision": "840c4195ce48a06cc8c49513c96a94381e7d8e10802f8835e3aab1c6ece01118",
27
27
  "server": "server/index.js",
28
28
  "exports": {
29
29
  "server": {},
@@ -25,7 +25,7 @@
25
25
  "web": {}
26
26
  },
27
27
  "revision": "007ee50ab186e3070930f23e9795210fa36c723365657325d5440cc2f0b81d60",
28
- "sourceRevision": "1ce434ee7a1752f72e3d7160d895130948b8bcd5bba466f5555fff6ff278cd19",
28
+ "sourceRevision": "8cec5a0d238ff52a630bd3f822cf95ea9a640626c8c7345def28c4f1feabff10",
29
29
  "server": "server/index.js",
30
30
  "exports": {
31
31
  "server": {
@@ -137,7 +137,7 @@
137
137
  }
138
138
  },
139
139
  "revision": "db9370b7b3449c44be49986b074806351b857c430963aa878e209d2d5c9ba4f8",
140
- "sourceRevision": "f91d81de973c9c7b46f1882a8cb4f067fbdf72c2e7617f24f8865f92d9ed05bc",
140
+ "sourceRevision": "012d6527173d20efeeaa5102b884d7cd9bbf781cf4fa6446164529ec252fcc2e",
141
141
  "server": "server/index.js",
142
142
  "web": {
143
143
  "entry": "web/index.js",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@schlenkr/ragents",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
4
4
  "description": "RAgents host: server, engine, plugins and tools without a source checkout",
5
5
  "keywords": [
6
6
  "agents",
@@ -50,6 +50,7 @@
50
50
  "dompurify": "3.4.13",
51
51
  "elkjs": "0.12.0",
52
52
  "esbuild": "0.28.2",
53
+ "eventsource-parser": "3.1.1",
53
54
  "handlebars": "4.7.9",
54
55
  "highlight.js": "11.12.0",
55
56
  "lucide-react": "1.46.0",
@@ -70,6 +71,6 @@
70
71
  "yaml": "2.9.0"
71
72
  },
72
73
  "ragents": {
73
- "hostVersion": "9d43afb1f899a9b2bf01b46d9173d1ea901c9088"
74
+ "hostVersion": "29cbfb6c019aa6a9ceb540363ca37ef2f9d03cb1"
74
75
  }
75
76
  }
@@ -0,0 +1,2 @@
1
+ export declare function normalizeOpenAiResponse(response: Response): Promise<Response>;
2
+ //# sourceMappingURL=openai-compatible-response.d.ts.map
@@ -29,6 +29,7 @@
29
29
  "dependencies": {
30
30
  "@openrouter/ai-sdk-provider": "^3.0.0",
31
31
  "ai": "^7.0.99",
32
+ "eventsource-parser": "3.1.1",
32
33
  "partial-json": "0.1.7",
33
34
  "typebox": "1.1.38"
34
35
  },
@@ -1,6 +1,7 @@
1
1
  import { createOpenRouter } from "@openrouter/ai-sdk-provider";
2
2
  import type { Model, ProviderHeaders } from "../types.ts";
3
3
  import { headersToRecord } from "../utils/headers.ts";
4
+ import { normalizeOpenAiResponse } from "./openai-compatible-response.ts";
4
5
 
5
6
  interface SdkOptions<TModel> {
6
7
  apiKey?: string;
@@ -43,9 +44,10 @@ export function createSdkProvider<TModel extends Model<string>>(model: TModel, o
43
44
  });
44
45
  try {
45
46
  await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
46
- return response;
47
+ return model.baseUrl && new URL(model.baseUrl).hostname !== "openrouter.ai"
48
+ ? await normalizeOpenAiResponse(response) : response;
47
49
  } catch (error) {
48
- await response.body?.cancel();
50
+ if (!response.body?.locked) await response.body?.cancel();
49
51
  throw error;
50
52
  }
51
53
  },
@@ -0,0 +1,60 @@
1
+ import { EventSourceParserStream, type EventSourceMessage } from "eventsource-parser/stream";
2
+
3
+ function isObject(value: unknown): value is Record<string, unknown> {
4
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5
+ }
6
+
7
+ function omitNulls(value: Record<string, unknown>, fields: readonly string[]) {
8
+ for (const field of fields) if (value[field] === null) delete value[field];
9
+ }
10
+
11
+ function normalizeCompletion(value: unknown): unknown {
12
+ if (!isObject(value) || !Array.isArray(value.choices)) return value;
13
+ for (const choice of value.choices) {
14
+ if (!isObject(choice)) continue;
15
+ for (const kind of ["delta", "message"] as const) {
16
+ const message = choice[kind];
17
+ if (!isObject(message)) continue;
18
+ omitNulls(message, [
19
+ "content", "reasoning", "reasoning_content", "reasoning_text", "reasoning_details",
20
+ "tool_calls", "refusal", "audio", "function_call", "images", "annotations",
21
+ ]);
22
+ if (kind === "delta") omitNulls(message, ["role"]);
23
+ if (kind === "message" && message.reasoning === undefined && typeof message.reasoning_content === "string") {
24
+ message.reasoning = message.reasoning_content;
25
+ }
26
+ if (!Array.isArray(message.tool_calls)) continue;
27
+ for (const tool of message.tool_calls) {
28
+ if (!isObject(tool)) continue;
29
+ if (tool.type == null && isObject(tool.function)) tool.type = "function";
30
+ if (isObject(tool.function)) omitNulls(tool.function, ["arguments"]);
31
+ }
32
+ }
33
+ }
34
+ return value;
35
+ }
36
+
37
+ export async function normalizeOpenAiResponse(response: Response): Promise<Response> {
38
+ if (!response.ok || !response.body) return response;
39
+ const contentType = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
40
+ const headers = new Headers(response.headers);
41
+ headers.delete("content-length");
42
+ headers.delete("content-encoding");
43
+ const init = { status: response.status, statusText: response.statusText, headers };
44
+ if (contentType === "application/json") {
45
+ return new Response(JSON.stringify(normalizeCompletion(await response.json())), init);
46
+ }
47
+ if (contentType !== "text/event-stream") return response;
48
+ const body = response.body
49
+ .pipeThrough(new TextDecoderStream())
50
+ .pipeThrough(new EventSourceParserStream())
51
+ .pipeThrough(new TransformStream<EventSourceMessage, string>({
52
+ transform(event, controller) {
53
+ const data = event.data.trim() === "[DONE]" ? "[DONE]" : JSON.stringify(normalizeCompletion(JSON.parse(event.data)));
54
+ const metadata = `${event.id === undefined ? "" : `id: ${event.id}\n`}${event.event === undefined ? "" : `event: ${event.event}\n`}`;
55
+ controller.enqueue(`${metadata}data: ${data}\n\n`);
56
+ },
57
+ }))
58
+ .pipeThrough(new TextEncoderStream());
59
+ return new Response(body, init);
60
+ }