@odysx/codemind 0.1.0 → 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.
Files changed (226) hide show
  1. package/dist/core/provider/index.d.ts +52 -10
  2. package/dist/core/provider/index.js +99 -12
  3. package/package.json +6 -1
  4. package/dist/commands/agents.d.ts.map +0 -1
  5. package/dist/commands/agents.js.map +0 -1
  6. package/dist/commands/auth.d.ts.map +0 -1
  7. package/dist/commands/auth.js.map +0 -1
  8. package/dist/commands/chat.d.ts.map +0 -1
  9. package/dist/commands/chat.js.map +0 -1
  10. package/dist/commands/keys.d.ts.map +0 -1
  11. package/dist/commands/keys.js.map +0 -1
  12. package/dist/commands/local.d.ts.map +0 -1
  13. package/dist/commands/local.js.map +0 -1
  14. package/dist/commands/mcp.d.ts.map +0 -1
  15. package/dist/commands/mcp.js.map +0 -1
  16. package/dist/commands/prompts.d.ts.map +0 -1
  17. package/dist/commands/prompts.js.map +0 -1
  18. package/dist/commands/skills.d.ts.map +0 -1
  19. package/dist/commands/skills.js.map +0 -1
  20. package/dist/core/auth/index.d.ts.map +0 -1
  21. package/dist/core/auth/index.js.map +0 -1
  22. package/dist/core/config/index.d.ts.map +0 -1
  23. package/dist/core/config/index.js.map +0 -1
  24. package/dist/core/history.d.ts.map +0 -1
  25. package/dist/core/history.js.map +0 -1
  26. package/dist/core/markdown-renderer.d.ts.map +0 -1
  27. package/dist/core/markdown-renderer.js.map +0 -1
  28. package/dist/core/permissions/index.d.ts.map +0 -1
  29. package/dist/core/permissions/index.js.map +0 -1
  30. package/dist/core/provider/external.d.ts.map +0 -1
  31. package/dist/core/provider/external.js.map +0 -1
  32. package/dist/core/provider/index.d.ts.map +0 -1
  33. package/dist/core/provider/index.js.map +0 -1
  34. package/dist/core/registry/index.d.ts.map +0 -1
  35. package/dist/core/registry/index.js.map +0 -1
  36. package/dist/core/schema/types.d.ts.map +0 -1
  37. package/dist/core/schema/types.js.map +0 -1
  38. package/dist/core/terminal.d.ts.map +0 -1
  39. package/dist/core/terminal.js.map +0 -1
  40. package/dist/core/workspace/index.d.ts.map +0 -1
  41. package/dist/core/workspace/index.js.map +0 -1
  42. package/dist/index.d.ts.map +0 -1
  43. package/dist/index.js.map +0 -1
  44. package/dist/ui/app.d.ts.map +0 -1
  45. package/dist/ui/app.js.map +0 -1
  46. package/dist/ui/commands/cases/catalog.d.ts.map +0 -1
  47. package/dist/ui/commands/cases/catalog.js.map +0 -1
  48. package/dist/ui/commands/cases/misc.d.ts.map +0 -1
  49. package/dist/ui/commands/cases/misc.js.map +0 -1
  50. package/dist/ui/commands/cases/tasks.d.ts.map +0 -1
  51. package/dist/ui/commands/cases/tasks.js.map +0 -1
  52. package/dist/ui/commands/runCommand.d.ts.map +0 -1
  53. package/dist/ui/commands/runCommand.js.map +0 -1
  54. package/dist/ui/components/AgentPicker.d.ts.map +0 -1
  55. package/dist/ui/components/AgentPicker.js.map +0 -1
  56. package/dist/ui/components/AuthPicker.d.ts.map +0 -1
  57. package/dist/ui/components/AuthPicker.js.map +0 -1
  58. package/dist/ui/components/Banner.d.ts.map +0 -1
  59. package/dist/ui/components/Banner.js.map +0 -1
  60. package/dist/ui/components/CommandMenu.d.ts.map +0 -1
  61. package/dist/ui/components/CommandMenu.js.map +0 -1
  62. package/dist/ui/components/ErrorBoundary.d.ts.map +0 -1
  63. package/dist/ui/components/ErrorBoundary.js.map +0 -1
  64. package/dist/ui/components/InputBar.d.ts.map +0 -1
  65. package/dist/ui/components/InputBar.js.map +0 -1
  66. package/dist/ui/components/KeysPanel.d.ts.map +0 -1
  67. package/dist/ui/components/KeysPanel.js.map +0 -1
  68. package/dist/ui/components/MessageView.d.ts.map +0 -1
  69. package/dist/ui/components/MessageView.js.map +0 -1
  70. package/dist/ui/components/PermissionPrompt.d.ts.map +0 -1
  71. package/dist/ui/components/PermissionPrompt.js.map +0 -1
  72. package/dist/ui/components/Pickers.d.ts.map +0 -1
  73. package/dist/ui/components/Pickers.js.map +0 -1
  74. package/dist/ui/components/SearchOverlay.d.ts.map +0 -1
  75. package/dist/ui/components/SearchOverlay.js.map +0 -1
  76. package/dist/ui/components/SessionPicker.d.ts.map +0 -1
  77. package/dist/ui/components/SessionPicker.js.map +0 -1
  78. package/dist/ui/components/WorkingIndicator.d.ts.map +0 -1
  79. package/dist/ui/components/WorkingIndicator.js.map +0 -1
  80. package/dist/ui/controls/ApiKeyEntry.d.ts.map +0 -1
  81. package/dist/ui/controls/ApiKeyEntry.js.map +0 -1
  82. package/dist/ui/controls/MultiSelect.d.ts.map +0 -1
  83. package/dist/ui/controls/MultiSelect.js.map +0 -1
  84. package/dist/ui/hooks/useAgentPicker.d.ts.map +0 -1
  85. package/dist/ui/hooks/useAgentPicker.js.map +0 -1
  86. package/dist/ui/hooks/useAuthFlow.d.ts.map +0 -1
  87. package/dist/ui/hooks/useAuthFlow.js.map +0 -1
  88. package/dist/ui/hooks/useKeysFlow.d.ts.map +0 -1
  89. package/dist/ui/hooks/useKeysFlow.js.map +0 -1
  90. package/dist/ui/hooks/useSessionPicker.d.ts.map +0 -1
  91. package/dist/ui/hooks/useSessionPicker.js.map +0 -1
  92. package/dist/ui/hooks/useTerminalSize.d.ts.map +0 -1
  93. package/dist/ui/hooks/useTerminalSize.js.map +0 -1
  94. package/dist/ui/input/keyRouter.d.ts.map +0 -1
  95. package/dist/ui/input/keyRouter.js.map +0 -1
  96. package/dist/ui/layouts/ScreenLayout.d.ts.map +0 -1
  97. package/dist/ui/layouts/ScreenLayout.js.map +0 -1
  98. package/dist/ui/shared/types.d.ts.map +0 -1
  99. package/dist/ui/shared/types.js.map +0 -1
  100. package/dist/ui/theme.d.ts.map +0 -1
  101. package/dist/ui/theme.js.map +0 -1
  102. package/dist/ui/utils/markdown.d.ts.map +0 -1
  103. package/dist/ui/utils/markdown.js.map +0 -1
  104. package/dist/ui/utils/mentions.d.ts.map +0 -1
  105. package/dist/ui/utils/mentions.js.map +0 -1
  106. package/dist/ui/utils/terminal-text.d.ts.map +0 -1
  107. package/dist/ui/utils/terminal-text.js.map +0 -1
  108. package/dist/ui/utils/text.d.ts.map +0 -1
  109. package/dist/ui/utils/text.js.map +0 -1
  110. package/eslint.config.js +0 -40
  111. package/graphify-out/GRAPH_REPORT.md +0 -140
  112. package/graphify-out/cache/1236b1806943f8eb5c64fece9fb448149370f4a1b52b32f0977ad528d7911291.json +0 -1
  113. package/graphify-out/cache/15cbf641dcc0fd641c18da872214918203a1f64baa7ac8430e4702ef32d18b02.json +0 -1
  114. package/graphify-out/cache/1abc52745bb46f6cc5a528530e2bc1f368c26e348dff85cdde5cad6f275d7177.json +0 -1
  115. package/graphify-out/cache/1c7815c37c13177e98895e272285f6151a8d0807478fc843ec452634b3e9912d.json +0 -1
  116. package/graphify-out/cache/1ec38c39f044f329c78642b61d6394fb8e15d0014335f32947d1f5c7b88c02bc.json +0 -1
  117. package/graphify-out/cache/20c9b57ff76dbb9d57cbd00659b0a42d2b28dd2abacf1ef4143cc67a5b6fe7f4.json +0 -1
  118. package/graphify-out/cache/285e11876884eb619e779d540cd957b33e70f14c67ecc26c9b9755aa9cedd717.json +0 -1
  119. package/graphify-out/cache/2c0a9c49ab51f4e0f07543b4e941bf802b7db31fa607c4cee8e595575be68fe7.json +0 -1
  120. package/graphify-out/cache/3025e6c2756c79ccaadd51d611f25a8b6630a6a11ce1b4e6e261b3e033dc194f.json +0 -1
  121. package/graphify-out/cache/4801a686ddfa0a52824a4fc3d65443cbb0ab9f0b030af67d02fccb520c584a08.json +0 -1
  122. package/graphify-out/cache/4f8fd96f38aa7d0293b4fab60c4581c4f3e68f4533c664c9cd78d1c53bea1cba.json +0 -1
  123. package/graphify-out/cache/5928e562b0f5700184b810e2403f4aa685e2b93c3c584c10460562b514c40fdd.json +0 -1
  124. package/graphify-out/cache/66132486efb0a4cfaeea766448f1f15bb33635808714052e7e24e5b00fbc984f.json +0 -1
  125. package/graphify-out/cache/66ab27669e7ec685130063662af9f30018c267f7639b4af4b0504a98282c383a.json +0 -1
  126. package/graphify-out/cache/6ff6b3dd433b5ffe96e166263a203dd622397e419dc00bb676824988b7defeab.json +0 -1
  127. package/graphify-out/cache/7a00a49932177a6215e2590b1ddfd6f1d8494792f693068e9d427d16b165d370.json +0 -1
  128. package/graphify-out/cache/7b681bc5182f40f707f1c0b16b78af38efffa62a1df315d10878f4de888408ef.json +0 -1
  129. package/graphify-out/cache/81196d44e50ac0b276d826a531ed10c425a528b298e3fe18e8d5a3eec996e9d5.json +0 -1
  130. package/graphify-out/cache/8934e9b32dea6e66fdc34fa1681b287ff1335c389917e0fc6ee2fc573e23e87b.json +0 -1
  131. package/graphify-out/cache/975f6c99807f86b79c80ca40c783618e2080a927eaebe6ea3db37b869f048851.json +0 -1
  132. package/graphify-out/cache/9ab98f08626fd8190462595e38de828293ad184db8df5e1177b05a8fe290faa1.json +0 -1
  133. package/graphify-out/cache/9c434a6796d7932b6e87a908c155c09cb2b8d097fc55f141f0302b6600f94749.json +0 -1
  134. package/graphify-out/cache/ac5cf4c489dc417c1f6ea728d0b6ba12ac7087bc6c2e736697ff3024b4d4e534.json +0 -1
  135. package/graphify-out/cache/ae5083b5c1dca3e5c6af485e7f6eb8a08ff8b382cdecf92ab5e0902053442afe.json +0 -1
  136. package/graphify-out/cache/b274057fc2e0118cf2746d1d8060841122bb2a2b0305566fc3f32d3a51e08bcc.json +0 -1
  137. package/graphify-out/cache/b39beef31da682387f030c0d149f6cd5b3e66effbf936cc8430db15360759dda.json +0 -1
  138. package/graphify-out/cache/bf3c6a36bb72820bc11cbf4a5c49067d1f62013d4686c019a4dbd9951b1e980e.json +0 -1
  139. package/graphify-out/cache/c034e156028d1a58b89bce659726e9a4065ddc4d2b560d6bce7a206fdff8dad3.json +0 -1
  140. package/graphify-out/cache/c619b5bbe8d1f427fbd7816d1e9fcfaf90d7201b020ae6b578166aeb9cb20683.json +0 -1
  141. package/graphify-out/cache/c8db77a9da0b0f601acfa50a620f31155cdda0d0cc0f2285adcea19e77194ee6.json +0 -1
  142. package/graphify-out/cache/ca664791ec7741a2077d9e7c10384142d30e7a3b77b388df719c315da608d57d.json +0 -1
  143. package/graphify-out/cache/cba43a116186bd55c8a63368dea4eee4a8123b2bec0a42df6efb3254f89f9a7a.json +0 -1
  144. package/graphify-out/cache/cd51cbb3dad1cf34417b9761fe2eb184a9f57d23dc86e45630e63bfa2ecafddc.json +0 -1
  145. package/graphify-out/cache/d06738cde193b34a136b94104220c17e0212b814b3e4d7ff399105635cae1a03.json +0 -1
  146. package/graphify-out/cache/d093c19f0169c0398eeb1360895b1c16ecc50abc59f4be8eec3f6fd27c89a6e5.json +0 -1
  147. package/graphify-out/cache/da8f75c438531d232fe114d5cbf2374576ce842a5fb87c7e5a88b78fdb334e5e.json +0 -1
  148. package/graphify-out/cache/e35798fa04ddede548a6953bdea506bd7d0788dfed4e8a8ea6ae77b1b60ef5e0.json +0 -1
  149. package/graphify-out/cache/e5a38c254719000487098782125e15e2e982c07d66b99d359ed1781f30f9fc8c.json +0 -1
  150. package/graphify-out/cache/e6e4c4a5a7200ee0154585b5d6538f699b0a746dbded3164f8391f06ce7cb212.json +0 -1
  151. package/graphify-out/cache/ea8d0838df6309b673b031f616b253af957898ee7289d25a541fa6183b732e4e.json +0 -1
  152. package/graphify-out/cache/ebaee92b0e881efd7a08f3143e2c1803310396b4651d4f77532003c699cc6836.json +0 -1
  153. package/graphify-out/cache/edf8543318a9e60d56d04704078da6c37202ddd6fdfc83144fe2b94fe19b80ef.json +0 -1
  154. package/graphify-out/cache/efca19d3668035f11126fc9eccbeab290abfa94babf3f9a8706de81d17aba263.json +0 -1
  155. package/graphify-out/cache/f1480bb642025ebd6d99986cdd8a7d5726897ec038300e4b095c9c938435dfad.json +0 -1
  156. package/graphify-out/cache/f459f21277f03865f732affb175b1b092954dae5967f27b3cd1864466e3e24f4.json +0 -1
  157. package/graphify-out/cache/f899e37e864010b30f4c196e86082d7bd022a0df032005e0407883ebcec36514.json +0 -1
  158. package/graphify-out/cache/fb3cbe07fbcd97c536cff9c6bc343c35f22d49613f05c53ad30ef67a75c5d93e.json +0 -1
  159. package/graphify-out/cache/fd3dc682b1ca2f5ae03b50d6b0e045ae50f5701c0a21c5a388d77ef482939d3a.json +0 -1
  160. package/graphify-out/graph.html +0 -257
  161. package/graphify-out/graph.json +0 -4396
  162. package/scripts/e2e-external.mjs +0 -65
  163. package/scripts/live-agents.mjs +0 -6
  164. package/scripts/live-stream.mjs +0 -51
  165. package/src/commands/agents.ts +0 -91
  166. package/src/commands/auth.ts +0 -39
  167. package/src/commands/chat.ts +0 -198
  168. package/src/commands/keys.ts +0 -83
  169. package/src/commands/local.ts +0 -302
  170. package/src/commands/mcp.ts +0 -74
  171. package/src/commands/prompts.ts +0 -58
  172. package/src/commands/skills.ts +0 -43
  173. package/src/core/auth/index.ts +0 -101
  174. package/src/core/config/index.ts +0 -152
  175. package/src/core/history.ts +0 -79
  176. package/src/core/markdown-renderer.ts +0 -420
  177. package/src/core/permissions/index.ts +0 -99
  178. package/src/core/provider/external.ts +0 -312
  179. package/src/core/provider/index.ts +0 -517
  180. package/src/core/registry/index.ts +0 -250
  181. package/src/core/schema/types.ts +0 -106
  182. package/src/core/terminal.ts +0 -124
  183. package/src/core/workspace/index.ts +0 -216
  184. package/src/index.ts +0 -401
  185. package/src/ui/app.tsx +0 -644
  186. package/src/ui/commands/cases/catalog.ts +0 -76
  187. package/src/ui/commands/cases/misc.ts +0 -293
  188. package/src/ui/commands/cases/tasks.ts +0 -115
  189. package/src/ui/commands/runCommand.ts +0 -178
  190. package/src/ui/components/Banner.tsx +0 -63
  191. package/src/ui/components/CommandMenu.tsx +0 -63
  192. package/src/ui/components/ErrorBoundary.tsx +0 -75
  193. package/src/ui/components/InputBar.tsx +0 -227
  194. package/src/ui/components/KeysPanel.tsx +0 -115
  195. package/src/ui/components/MessageView.tsx +0 -226
  196. package/src/ui/components/Pickers.tsx +0 -234
  197. package/src/ui/components/SearchOverlay.tsx +0 -65
  198. package/src/ui/components/WorkingIndicator.tsx +0 -35
  199. package/src/ui/controls/ApiKeyEntry.tsx +0 -29
  200. package/src/ui/controls/MultiSelect.tsx +0 -55
  201. package/src/ui/hooks/useAgentPicker.ts +0 -64
  202. package/src/ui/hooks/useAuthFlow.ts +0 -47
  203. package/src/ui/hooks/useKeysFlow.ts +0 -157
  204. package/src/ui/hooks/useSessionPicker.ts +0 -84
  205. package/src/ui/hooks/useTerminalSize.ts +0 -36
  206. package/src/ui/input/keyRouter.ts +0 -627
  207. package/src/ui/layouts/ScreenLayout.tsx +0 -202
  208. package/src/ui/shared/types.ts +0 -160
  209. package/src/ui/theme.ts +0 -53
  210. package/src/ui/utils/markdown.ts +0 -255
  211. package/src/ui/utils/mentions.ts +0 -40
  212. package/src/ui/utils/terminal-text.ts +0 -130
  213. package/src/ui/utils/text.ts +0 -174
  214. package/test/commands.test.mjs +0 -127
  215. package/test/config.test.mjs +0 -123
  216. package/test/history.test.mjs +0 -42
  217. package/test/keyrouter.test.mjs +0 -324
  218. package/test/layout.test.mjs +0 -271
  219. package/test/markdown.test.mjs +0 -92
  220. package/test/mentions.test.mjs +0 -51
  221. package/test/permissions.test.mjs +0 -130
  222. package/test/provider.test.mjs +0 -287
  223. package/test/terminal-text.test.mjs +0 -116
  224. package/test/text.test.mjs +0 -134
  225. package/test/workspace.test.mjs +0 -101
  226. package/tsconfig.json +0 -32
@@ -1,99 +0,0 @@
1
- /**
2
- * Permission modes — who decides whether a workspace operation may run.
3
- *
4
- * The CLI can read, edit, and execute files in your workspace. This module is
5
- * the single place that answers "is this operation allowed, and does anyone
6
- * need to be asked?" so the interactive REPL, the one-shot CLI, and the
7
- * command handlers can never disagree about it.
8
- *
9
- * Four modes, each a strictly different posture toward the workspace:
10
- *
11
- * plan read-only — mutations are refused outright
12
- * guide nothing runs; the operation is printed for you to run yourself
13
- * manual every mutation asks (the default)
14
- * auto scoped writes run unprompted; irreversible ops still ask
15
- *
16
- * The policy is a table rather than a chain of conditionals: adding a mode or
17
- * an operation class is a data change, and the tests exercise the whole
18
- * matrix instead of the paths someone remembered to write.
19
- */
20
- import { getConfig, updateConfig } from "../config/index.js";
21
-
22
- export type PermissionMode = "plan" | "guide" | "manual" | "auto";
23
-
24
- /** What an operation does to the workspace. */
25
- export type OpClass = "read" | "write" | "irreversible";
26
-
27
- /** The outcome the caller must honour. */
28
- export type Decision =
29
- /** Run it. */
30
- | "allow"
31
- /** Ask the user first (interactive) or require --yes (non-interactive). */
32
- | "ask"
33
- /** Refuse, and say why. */
34
- | "refuse"
35
- /** Don't run it; show the user the exact command instead. */
36
- | "guide";
37
-
38
- export interface ModeInfo {
39
- id: PermissionMode;
40
- label: string;
41
- /** One line for the picker and /help. */
42
- summary: string;
43
- }
44
-
45
- export const PERMISSION_MODES: readonly ModeInfo[] = [
46
- { id: "plan", label: "plan", summary: "Read-only — never writes, deletes, or executes" },
47
- { id: "guide", label: "guide", summary: "Prints the command it would run instead of running it" },
48
- { id: "manual", label: "manual", summary: "Asks before every write, delete, move, or exec" },
49
- { id: "auto", label: "auto", summary: "Runs workspace writes; still asks for irreversible ops" },
50
- ];
51
-
52
- /**
53
- * mode × operation class → decision.
54
- *
55
- * The ladder is deliberate: each row is a superset of the one above it, so
56
- * `auto` is the only mode that can act without being asked, and even it stops
57
- * at anything it cannot undo.
58
- */
59
- const POLICY: Record<PermissionMode, Record<OpClass, Decision>> = {
60
- plan: { read: "allow", write: "refuse", irreversible: "refuse" },
61
- guide: { read: "allow", write: "guide", irreversible: "guide" },
62
- manual: { read: "allow", write: "ask", irreversible: "ask" },
63
- auto: { read: "allow", write: "allow", irreversible: "ask" },
64
- };
65
-
66
- const MODE_IDS = PERMISSION_MODES.map((m) => m.id);
67
-
68
- export const isPermissionMode = (value: unknown): value is PermissionMode =>
69
- typeof value === "string" && (MODE_IDS as string[]).includes(value);
70
-
71
- /** The active mode. Anything unrecognised in the config file falls back. */
72
- export const getPermissionMode = (): PermissionMode => {
73
- const configured = getConfig().permissionMode;
74
- return isPermissionMode(configured) ? configured : "manual";
75
- };
76
-
77
- export const setPermissionMode = (mode: PermissionMode): void => {
78
- updateConfig({ permissionMode: mode });
79
- };
80
-
81
- /** Classify a `local` subcommand. The only place these names are mapped. */
82
- export const classifyLocalOp = (sub: string): OpClass => {
83
- const op = sub.toLowerCase();
84
- if (op === "read" || op === "ls" || op === "pwd" || op === "which") return "read";
85
- if (op === "write") return "write";
86
- // delete and move cannot be undone; exec runs arbitrary code.
87
- return "irreversible";
88
- };
89
-
90
- export const decide = (mode: PermissionMode, op: OpClass): Decision => POLICY[mode][op];
91
-
92
- /** Convenience: decide for a `local` subcommand under the active mode. */
93
- export const decideLocal = (
94
- sub: string,
95
- mode: PermissionMode = getPermissionMode(),
96
- ): Decision => decide(mode, classifyLocalOp(sub));
97
-
98
- export const modeInfo = (mode: PermissionMode): ModeInfo =>
99
- PERMISSION_MODES.find((m) => m.id === mode) ?? PERMISSION_MODES[2]!;
@@ -1,312 +0,0 @@
1
- /**
2
- * External providers — bring-your-own LLM (like Claude Code / Copilot's
3
- * settings-file model). Codemind stays platform-first; an external provider
4
- * is an opt-in override configured in ~/.odysx/config.json:
5
- *
6
- * "providers": {
7
- * "openai": { "type": "openai", "baseUrl": "https://api.openai.com/v1", "apiKey": "sk-…", "model": "gpt-4o" },
8
- * "groq": { "type": "openai", "baseUrl": "https://api.groq.com/openai/v1", "apiKey": "gsk_…", "model": "llama-3.3-70b" },
9
- * "ollama": { "type": "openai", "baseUrl": "http://localhost:11434/v1", "model": "llama3.2" },
10
- * "claude": { "type": "anthropic", "apiKey": "sk-ant-…", "model": "claude-sonnet-5" },
11
- * "gemini": { "type": "gemini", "apiKey": "AIza…", "model": "gemini-2.0-flash" }
12
- * },
13
- * "provider": "openai" // active selection; absent/null = OdysX platform
14
- *
15
- * Any `type: "openai"` entry with a custom baseUrl covers OpenAI-compatible
16
- * servers (Groq, Ollama, LM Studio, vLLM, Together, …).
17
- */
18
- import { getConfig } from "../config/index.js";
19
- import { readSSE, idleTimeout, STREAM_IDLE_TIMEOUT_MS } from "./index.js";
20
-
21
- export type ProviderType = "openai" | "anthropic" | "gemini";
22
-
23
- export interface ExternalProviderConfig {
24
- /** Wire protocol to speak. */
25
- type: ProviderType;
26
- /** API base (OpenAI-compatible servers override this). */
27
- baseUrl?: string;
28
- apiKey?: string;
29
- model: string;
30
- }
31
-
32
- /** Chat message as sent over the wire (system prompt folded in by caller). */
33
- export interface WireMessage {
34
- role: "user" | "assistant";
35
- content: string;
36
- }
37
-
38
- const DEFAULT_BASE_URLS: Record<ProviderType, string> = {
39
- openai: "https://api.openai.com/v1",
40
- anthropic: "https://api.anthropic.com/v1",
41
- gemini: "https://generativelanguage.googleapis.com/v1beta",
42
- };
43
-
44
- const PROVIDER_TYPES: readonly string[] = ["openai", "anthropic", "gemini"];
45
- const isProviderType = (t: unknown): t is ProviderType =>
46
- typeof t === "string" && PROVIDER_TYPES.includes(t);
47
-
48
- export const getActiveProvider = (): {
49
- name: string;
50
- config: ExternalProviderConfig;
51
- } | null => {
52
- const config = getConfig();
53
- const name = config.provider;
54
- if (!name || name === "odysx") return null;
55
- const cfg = config.providers?.[name];
56
- if (!cfg) return null;
57
- // config.json is user-edited and unvalidated. A typo'd `type` used to fall
58
- // through to `fetch("undefined/chat/completions")`, which surfaced as a
59
- // baffling URL parse error; refuse cleanly instead.
60
- if (!isProviderType(cfg.type)) {
61
- throw new Error(
62
- `Provider '${name}' has unknown type '${String(cfg.type)}' — expected openai, anthropic, or gemini.`,
63
- );
64
- }
65
- return {
66
- name,
67
- config: { ...cfg, type: cfg.type, baseUrl: cfg.baseUrl ?? DEFAULT_BASE_URLS[cfg.type] },
68
- };
69
- };
70
-
71
- interface StreamOpts {
72
- system?: string;
73
- onToken: (token: string) => void;
74
- signal?: AbortSignal;
75
- }
76
-
77
- /** Stream a chat turn through the active external provider. Throws on HTTP
78
- * errors with the provider's own message so the REPL can show it directly. */
79
- export async function streamExternalChat(
80
- messages: WireMessage[],
81
- opts: StreamOpts,
82
- ): Promise<void> {
83
- const active = getActiveProvider();
84
- if (!active) throw new Error("No external provider configured");
85
- const { type, baseUrl, apiKey, model } = active.config;
86
-
87
- switch (type) {
88
- case "openai":
89
- return streamOpenAI(baseUrl!, apiKey, model, messages, opts);
90
- case "anthropic":
91
- return streamAnthropic(baseUrl!, apiKey, model, messages, opts);
92
- case "gemini":
93
- return streamGemini(baseUrl!, apiKey ?? "", model, messages, opts);
94
- default:
95
- throw new Error(
96
- `Provider '${active.name}' has unknown type '${String(type)}' — expected openai, anthropic, or gemini.`,
97
- );
98
- }
99
- }
100
-
101
- /* ── OpenAI-compatible (/chat/completions, SSE) ─────────────────────────── */
102
- async function streamOpenAI(
103
- baseUrl: string,
104
- apiKey: string | undefined,
105
- model: string,
106
- messages: WireMessage[],
107
- opts: StreamOpts,
108
- ): Promise<void> {
109
- const res = await postJson(`${baseUrl}/chat/completions`, {
110
- "Content-Type": "application/json",
111
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
112
- }, {
113
- model,
114
- stream: true,
115
- messages: [
116
- ...(opts.system ? [{ role: "system", content: opts.system }] : []),
117
- ...messages,
118
- ],
119
- }, opts);
120
- await consume(res, opts, (json) => {
121
- const token =
122
- json?.choices?.[0]?.delta?.content ??
123
- json?.choices?.[0]?.text ??
124
- "";
125
- if (token) opts.onToken(token);
126
- }, (json) => {
127
- // OpenAI-compatible servers report mid-stream failures as a frame body.
128
- const err = json?.error;
129
- if (err) return typeof err === "string" ? err : (err.message ?? JSON.stringify(err));
130
- return null;
131
- });
132
- }
133
-
134
- /* ── Anthropic (/messages, SSE) ─────────────────────────────────────────── */
135
- async function streamAnthropic(
136
- baseUrl: string,
137
- apiKey: string | undefined,
138
- model: string,
139
- messages: WireMessage[],
140
- opts: StreamOpts,
141
- ): Promise<void> {
142
- if (!apiKey) throw new Error(`Anthropic provider needs an apiKey`);
143
- const res = await postJson(`${baseUrl}/messages`, {
144
- "Content-Type": "application/json",
145
- "x-api-key": apiKey,
146
- "anthropic-version": "2023-06-01",
147
- }, {
148
- model,
149
- max_tokens: 4096,
150
- stream: true,
151
- ...(opts.system ? { system: opts.system } : {}),
152
- messages,
153
- }, opts);
154
- await consume(res, opts, (json) => {
155
- if (json?.type === "content_block_delta" && json?.delta?.text) {
156
- opts.onToken(json.delta.text);
157
- }
158
- }, (json) => {
159
- // Anthropic sends `event: error` with an error body mid-stream.
160
- if (json?.type === "error") return json?.error?.message ?? "Provider stream error";
161
- return null;
162
- });
163
- }
164
-
165
- /* ── Google Gemini (streamGenerateContent?alt=sse) ──────────────────────── */
166
- async function streamGemini(
167
- baseUrl: string,
168
- apiKey: string,
169
- model: string,
170
- messages: WireMessage[],
171
- opts: StreamOpts,
172
- ): Promise<void> {
173
- const contents = messages.map((m) => ({
174
- role: m.role === "assistant" ? "model" : "user",
175
- parts: [{ text: m.content }],
176
- }));
177
- // The key goes in a header, not the query string: query strings land in
178
- // provider/proxy access logs and in any error that echoes the URL.
179
- const url = `${baseUrl}/models/${encodeURIComponent(model)}:streamGenerateContent?alt=sse`;
180
- const res = await postJson(
181
- url,
182
- { "Content-Type": "application/json", "x-goog-api-key": apiKey },
183
- {
184
- contents,
185
- ...(opts.system
186
- ? { systemInstruction: { parts: [{ text: opts.system }] } }
187
- : {}),
188
- },
189
- opts,
190
- );
191
- await consume(res, opts, (json) => {
192
- const parts = json?.candidates?.[0]?.content?.parts ?? [];
193
- for (const part of parts) if (part.text) opts.onToken(part.text);
194
- }, (json) => {
195
- const err = json?.error;
196
- if (err) return err.message ?? JSON.stringify(err);
197
- // A blocked prompt comes back as a finishReason with no text at all.
198
- const reason = json?.candidates?.[0]?.finishReason;
199
- if (reason && reason !== "STOP" && reason !== "MAX_TOKENS") {
200
- return `Gemini stopped the response: ${reason}`;
201
- }
202
- const blocked = json?.promptFeedback?.blockReason;
203
- if (blocked) return `Gemini blocked the prompt: ${blocked}`;
204
- return null;
205
- });
206
- }
207
-
208
- /* ── Shared helpers ─────────────────────────────────────────────────────── */
209
-
210
- /** How long a provider may take to accept the connection and send headers. */
211
- const HEADER_TIMEOUT_MS = 30_000;
212
-
213
- const idleMessage = (): string =>
214
- `Provider sent nothing for ${Math.round(STREAM_IDLE_TIMEOUT_MS / 1000)}s — gave up`;
215
-
216
- /**
217
- * POST JSON and return the response, with a deadline covering connect + the
218
- * first byte of headers.
219
- *
220
- * The idle watchdog only starts *after* `fetch` resolves, so without this a
221
- * provider that completes the TCP handshake and then never sends headers (a
222
- * black-holed endpoint, a firewall that accepts) hung the REPL forever with
223
- * no way out but Ctrl+C.
224
- */
225
- async function postJson(
226
- url: string,
227
- headers: Record<string, string>,
228
- body: unknown,
229
- opts: StreamOpts,
230
- ): Promise<Response> {
231
- const connect = idleTimeout(HEADER_TIMEOUT_MS, opts.signal);
232
- let res: Response;
233
- try {
234
- res = await fetch(url, {
235
- method: "POST",
236
- headers,
237
- body: JSON.stringify(body),
238
- signal: connect.signal,
239
- });
240
- } catch (err) {
241
- if (connect.timedOut()) {
242
- throw new Error(`Provider did not respond within ${HEADER_TIMEOUT_MS / 1000}s`);
243
- }
244
- throw err;
245
- } finally {
246
- connect.clear();
247
- }
248
- if (!res.ok) throw new Error(await readError(res));
249
- return res;
250
- }
251
-
252
- /**
253
- * Drain a provider SSE stream, surfacing two things the old code lost:
254
- *
255
- * - A mid-stream error frame (OpenAI `{"error":…}`, Anthropic
256
- * `{"type":"error"}`, a Gemini safety stop). These used to be swallowed,
257
- * so a rate-limited turn ended as an empty reply with exit code 0.
258
- * - The idle timeout itself. The watchdog aborts the reader, so the failure
259
- * arrives as an AbortError *before* a `timedOut()` check placed after the
260
- * read could run — the user saw "interrupted" as if they had pressed Esc.
261
- */
262
- async function consume(
263
- res: Response,
264
- opts: StreamOpts,
265
- onJson: (json: any) => void,
266
- findError: (json: any) => string | null,
267
- ): Promise<void> {
268
- const idle = idleTimeout(STREAM_IDLE_TIMEOUT_MS, opts.signal);
269
- try {
270
- await readProviderSSE(res, (json) => {
271
- const message = findError(json);
272
- if (message) throw new Error(message);
273
- onJson(json);
274
- }, idle.signal, idle.touch);
275
- } catch (err) {
276
- if (idle.timedOut()) throw new Error(idleMessage());
277
- throw err;
278
- } finally {
279
- idle.clear();
280
- }
281
- }
282
-
283
- async function readError(res: Response): Promise<string> {
284
- let detail = "";
285
- try {
286
- const text = await res.text();
287
- try {
288
- const body = JSON.parse(text);
289
- detail =
290
- body?.error?.message ??
291
- body?.message ??
292
- (typeof body?.error === "string" ? body.error : JSON.stringify(body).slice(0, 200));
293
- } catch {
294
- detail = text.slice(0, 200);
295
- }
296
- } catch { /* ignore unreadable bodies */ }
297
- return `Provider error HTTP ${res.status}: ${detail || res.statusText}`;
298
- }
299
-
300
- /** Parse provider SSE frames through the shared, framing-tolerant reader.
301
- * Malformed JSON frames are skipped rather than killing the turn. */
302
- async function readProviderSSE(
303
- res: Response,
304
- onJson: (json: any) => void,
305
- signal?: AbortSignal,
306
- onActivity?: () => void,
307
- ): Promise<void> {
308
- await readSSE(res, (data) => {
309
- if (!data || data === "[DONE]") return;
310
- try { onJson(JSON.parse(data)); } catch { /* skip malformed frames */ }
311
- }, signal, onActivity);
312
- }