@eloxiv/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (294) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/AgentSkills.d.ts +51 -0
  4. package/dist/AgentSkills.d.ts.map +1 -0
  5. package/dist/AgentSkills.js +264 -0
  6. package/dist/AgentSkills.js.map +1 -0
  7. package/dist/AgentWeb.d.ts +83 -0
  8. package/dist/AgentWeb.d.ts.map +1 -0
  9. package/dist/AgentWeb.js +436 -0
  10. package/dist/AgentWeb.js.map +1 -0
  11. package/dist/App.d.ts +213 -0
  12. package/dist/App.d.ts.map +1 -0
  13. package/dist/App.js +357 -0
  14. package/dist/App.js.map +1 -0
  15. package/dist/Blueprint.d.ts +47 -0
  16. package/dist/Blueprint.d.ts.map +1 -0
  17. package/dist/Blueprint.js +241 -0
  18. package/dist/Blueprint.js.map +1 -0
  19. package/dist/Brand.d.ts +42 -0
  20. package/dist/Brand.d.ts.map +1 -0
  21. package/dist/Brand.js +370 -0
  22. package/dist/Brand.js.map +1 -0
  23. package/dist/Changelog.d.ts +22 -0
  24. package/dist/Changelog.d.ts.map +1 -0
  25. package/dist/Changelog.js +117 -0
  26. package/dist/Changelog.js.map +1 -0
  27. package/dist/Cli.d.ts +17 -0
  28. package/dist/Cli.d.ts.map +1 -0
  29. package/dist/Cli.js +810 -0
  30. package/dist/Cli.js.map +1 -0
  31. package/dist/DbAdmin.d.ts +18 -0
  32. package/dist/DbAdmin.d.ts.map +1 -0
  33. package/dist/DbAdmin.js +91 -0
  34. package/dist/DbAdmin.js.map +1 -0
  35. package/dist/Dependencies.d.ts +53 -0
  36. package/dist/Dependencies.d.ts.map +1 -0
  37. package/dist/Dependencies.js +132 -0
  38. package/dist/Dependencies.js.map +1 -0
  39. package/dist/Deploy.d.ts +39 -0
  40. package/dist/Deploy.d.ts.map +1 -0
  41. package/dist/Deploy.js +458 -0
  42. package/dist/Deploy.js.map +1 -0
  43. package/dist/Docs.d.ts +71 -0
  44. package/dist/Docs.d.ts.map +1 -0
  45. package/dist/Docs.js +240 -0
  46. package/dist/Docs.js.map +1 -0
  47. package/dist/Doctor.d.ts +56 -0
  48. package/dist/Doctor.d.ts.map +1 -0
  49. package/dist/Doctor.js +368 -0
  50. package/dist/Doctor.js.map +1 -0
  51. package/dist/Dossier.d.ts +23 -0
  52. package/dist/Dossier.d.ts.map +1 -0
  53. package/dist/Dossier.js +92 -0
  54. package/dist/Dossier.js.map +1 -0
  55. package/dist/Emit.d.ts +26 -0
  56. package/dist/Emit.d.ts.map +1 -0
  57. package/dist/Emit.js +51 -0
  58. package/dist/Emit.js.map +1 -0
  59. package/dist/Errors.d.ts +26 -0
  60. package/dist/Errors.d.ts.map +1 -0
  61. package/dist/Errors.js +17 -0
  62. package/dist/Errors.js.map +1 -0
  63. package/dist/Evals.d.ts +52 -0
  64. package/dist/Evals.d.ts.map +1 -0
  65. package/dist/Evals.js +126 -0
  66. package/dist/Evals.js.map +1 -0
  67. package/dist/Files.d.ts +47 -0
  68. package/dist/Files.d.ts.map +1 -0
  69. package/dist/Files.js +145 -0
  70. package/dist/Files.js.map +1 -0
  71. package/dist/Generate.d.ts +80 -0
  72. package/dist/Generate.d.ts.map +1 -0
  73. package/dist/Generate.js +310 -0
  74. package/dist/Generate.js.map +1 -0
  75. package/dist/Guards.d.ts +45 -0
  76. package/dist/Guards.d.ts.map +1 -0
  77. package/dist/Guards.js +530 -0
  78. package/dist/Guards.js.map +1 -0
  79. package/dist/Inspect.d.ts +125 -0
  80. package/dist/Inspect.d.ts.map +1 -0
  81. package/dist/Inspect.js +270 -0
  82. package/dist/Inspect.js.map +1 -0
  83. package/dist/Keychain.d.ts +57 -0
  84. package/dist/Keychain.d.ts.map +1 -0
  85. package/dist/Keychain.js +73 -0
  86. package/dist/Keychain.js.map +1 -0
  87. package/dist/Lock.d.ts +13 -0
  88. package/dist/Lock.d.ts.map +1 -0
  89. package/dist/Lock.js +145 -0
  90. package/dist/Lock.js.map +1 -0
  91. package/dist/Mcp.d.ts +91 -0
  92. package/dist/Mcp.d.ts.map +1 -0
  93. package/dist/Mcp.js +128 -0
  94. package/dist/Mcp.js.map +1 -0
  95. package/dist/Merge.d.ts +18 -0
  96. package/dist/Merge.d.ts.map +1 -0
  97. package/dist/Merge.js +43 -0
  98. package/dist/Merge.js.map +1 -0
  99. package/dist/Migrate.d.ts +78 -0
  100. package/dist/Migrate.d.ts.map +1 -0
  101. package/dist/Migrate.js +288 -0
  102. package/dist/Migrate.js.map +1 -0
  103. package/dist/Plugins.d.ts +36 -0
  104. package/dist/Plugins.d.ts.map +1 -0
  105. package/dist/Plugins.js +304 -0
  106. package/dist/Plugins.js.map +1 -0
  107. package/dist/Postgres.d.ts +73 -0
  108. package/dist/Postgres.d.ts.map +1 -0
  109. package/dist/Postgres.js +294 -0
  110. package/dist/Postgres.js.map +1 -0
  111. package/dist/Publish.d.ts +23 -0
  112. package/dist/Publish.d.ts.map +1 -0
  113. package/dist/Publish.js +59 -0
  114. package/dist/Publish.js.map +1 -0
  115. package/dist/Registry.d.ts +539 -0
  116. package/dist/Registry.d.ts.map +1 -0
  117. package/dist/Registry.js +340 -0
  118. package/dist/Registry.js.map +1 -0
  119. package/dist/Remote.d.ts +90 -0
  120. package/dist/Remote.d.ts.map +1 -0
  121. package/dist/Remote.js +1006 -0
  122. package/dist/Remote.js.map +1 -0
  123. package/dist/Run.d.ts +120 -0
  124. package/dist/Run.d.ts.map +1 -0
  125. package/dist/Run.js +477 -0
  126. package/dist/Run.js.map +1 -0
  127. package/dist/SyncGen.d.ts +118 -0
  128. package/dist/SyncGen.d.ts.map +1 -0
  129. package/dist/SyncGen.js +392 -0
  130. package/dist/SyncGen.js.map +1 -0
  131. package/dist/Update.d.ts +301 -0
  132. package/dist/Update.d.ts.map +1 -0
  133. package/dist/Update.js +627 -0
  134. package/dist/Update.js.map +1 -0
  135. package/dist/bin.d.ts +3 -0
  136. package/dist/bin.d.ts.map +1 -0
  137. package/dist/bin.js +42 -0
  138. package/dist/bin.js.map +1 -0
  139. package/dist/docs/backlog.md +56 -0
  140. package/dist/docs/ci.md +277 -0
  141. package/dist/docs/cli.md +696 -0
  142. package/dist/docs/connectors/google.md +115 -0
  143. package/dist/docs/connectors/http-openapi.md +7 -0
  144. package/dist/docs/connectors/mcp.md +8 -0
  145. package/dist/docs/connectors/microsoft-graph.md +75 -0
  146. package/dist/docs/connectors/openai.md +25 -0
  147. package/dist/docs/connectors/slack.md +162 -0
  148. package/dist/docs/connectors/workos.md +39 -0
  149. package/dist/docs/contracts/README.md +173 -0
  150. package/dist/docs/contracts/action-consent.md +92 -0
  151. package/dist/docs/contracts/action-registry.md +85 -0
  152. package/dist/docs/contracts/actor.md +100 -0
  153. package/dist/docs/contracts/agent-resources.md +90 -0
  154. package/dist/docs/contracts/agent-runtime.md +257 -0
  155. package/dist/docs/contracts/approvals.md +126 -0
  156. package/dist/docs/contracts/audit.md +75 -0
  157. package/dist/docs/contracts/auth-provider.md +74 -0
  158. package/dist/docs/contracts/calendar-provider.md +46 -0
  159. package/dist/docs/contracts/client-sdk.md +245 -0
  160. package/dist/docs/contracts/collab-document.md +151 -0
  161. package/dist/docs/contracts/command.md +44 -0
  162. package/dist/docs/contracts/connections.md +235 -0
  163. package/dist/docs/contracts/context-accounting.md +50 -0
  164. package/dist/docs/contracts/daemon.md +243 -0
  165. package/dist/docs/contracts/db-tx.md +53 -0
  166. package/dist/docs/contracts/delegation.md +68 -0
  167. package/dist/docs/contracts/device-control.md +103 -0
  168. package/dist/docs/contracts/directory-provider.md +36 -0
  169. package/dist/docs/contracts/directory.md +161 -0
  170. package/dist/docs/contracts/document-source.md +33 -0
  171. package/dist/docs/contracts/files.md +115 -0
  172. package/dist/docs/contracts/flags.md +83 -0
  173. package/dist/docs/contracts/host.md +68 -0
  174. package/dist/docs/contracts/http-api.md +43 -0
  175. package/dist/docs/contracts/ingestion.md +130 -0
  176. package/dist/docs/contracts/ingress.md +141 -0
  177. package/dist/docs/contracts/invocation.md +260 -0
  178. package/dist/docs/contracts/local-client.md +108 -0
  179. package/dist/docs/contracts/locale.md +56 -0
  180. package/dist/docs/contracts/machine-identity.md +117 -0
  181. package/dist/docs/contracts/mail-provider.md +49 -0
  182. package/dist/docs/contracts/memory.md +53 -0
  183. package/dist/docs/contracts/messaging.md +40 -0
  184. package/dist/docs/contracts/metering.md +139 -0
  185. package/dist/docs/contracts/model-provider.md +84 -0
  186. package/dist/docs/contracts/module-manifest.md +213 -0
  187. package/dist/docs/contracts/notification-channel.md +90 -0
  188. package/dist/docs/contracts/notifications.md +123 -0
  189. package/dist/docs/contracts/outbox.md +80 -0
  190. package/dist/docs/contracts/privacy.md +110 -0
  191. package/dist/docs/contracts/progress.md +52 -0
  192. package/dist/docs/contracts/query-surface.md +108 -0
  193. package/dist/docs/contracts/readiness.md +63 -0
  194. package/dist/docs/contracts/release.md +142 -0
  195. package/dist/docs/contracts/result-rendering.md +61 -0
  196. package/dist/docs/contracts/sandbox.md +186 -0
  197. package/dist/docs/contracts/scheduler.md +148 -0
  198. package/dist/docs/contracts/screen-context.md +81 -0
  199. package/dist/docs/contracts/search.md +120 -0
  200. package/dist/docs/contracts/secrets.md +74 -0
  201. package/dist/docs/contracts/settings.md +109 -0
  202. package/dist/docs/contracts/sharing.md +77 -0
  203. package/dist/docs/contracts/slot.md +48 -0
  204. package/dist/docs/contracts/space.md +67 -0
  205. package/dist/docs/contracts/storage-adapter.md +45 -0
  206. package/dist/docs/contracts/storage-backend.md +56 -0
  207. package/dist/docs/contracts/sync.md +213 -0
  208. package/dist/docs/contracts/telemetry.md +80 -0
  209. package/dist/docs/contracts/theme-tokens.md +50 -0
  210. package/dist/docs/contracts/tool-source.md +58 -0
  211. package/dist/docs/contracts/versioning.md +99 -0
  212. package/dist/docs/contracts/view.md +65 -0
  213. package/dist/docs/contracts/work-items.md +99 -0
  214. package/dist/docs/contracts/workflow.md +82 -0
  215. package/dist/docs/decisions.md +163 -0
  216. package/dist/docs/example-app.md +192 -0
  217. package/dist/docs/getting-started.md +927 -0
  218. package/dist/docs/goal.md +54 -0
  219. package/dist/docs/parity.md +29 -0
  220. package/dist/docs/performance.md +129 -0
  221. package/dist/docs/registry/README.md +74 -0
  222. package/dist/docs/registry/app.md +38 -0
  223. package/dist/docs/registry/approvals-ui-foldkit.md +28 -0
  224. package/dist/docs/registry/calendar-ui-foldkit.md +27 -0
  225. package/dist/docs/registry/calendar.md +35 -0
  226. package/dist/docs/registry/chat-ui-foldkit.md +30 -0
  227. package/dist/docs/registry/desktop-rune.md +49 -0
  228. package/dist/docs/registry/desktop.md +32 -0
  229. package/dist/docs/registry/eloxiv-action.md +25 -0
  230. package/dist/docs/registry/eloxiv-connector.md +25 -0
  231. package/dist/docs/registry/eloxiv-module.md +25 -0
  232. package/dist/docs/registry/eloxiv-policy.md +25 -0
  233. package/dist/docs/registry/eloxiv-view.md +25 -0
  234. package/dist/docs/registry/hello-ui-foldkit.md +29 -0
  235. package/dist/docs/registry/hello.md +39 -0
  236. package/dist/docs/registry/home-ui-foldkit.md +27 -0
  237. package/dist/docs/registry/home.md +29 -0
  238. package/dist/docs/registry/inbox-ui-foldkit.md +27 -0
  239. package/dist/docs/registry/mail-ui-foldkit.md +27 -0
  240. package/dist/docs/registry/mail.md +34 -0
  241. package/dist/docs/registry/meeting-prep.md +26 -0
  242. package/dist/docs/registry/members-ui-foldkit.md +28 -0
  243. package/dist/docs/registry/mobile.md +37 -0
  244. package/dist/docs/registry/notes-ui-foldkit.md +27 -0
  245. package/dist/docs/registry/notes.md +26 -0
  246. package/dist/docs/registry/people-ui-foldkit.md +28 -0
  247. package/dist/docs/registry/people.md +38 -0
  248. package/dist/docs/registry/shell-foldkit.md +34 -0
  249. package/dist/docs/registry/theme.md +25 -0
  250. package/dist/docs/registry/ui-conformance.md +30 -0
  251. package/dist/docs/release.md +100 -0
  252. package/dist/docs/scaffold.md +826 -0
  253. package/dist/docs/security/threat-model.md +299 -0
  254. package/dist/docs/upstream/zero-cache-socket-handoff.md +105 -0
  255. package/dist/index.d.ts +8 -0
  256. package/dist/index.d.ts.map +1 -0
  257. package/dist/index.js +8 -0
  258. package/dist/index.js.map +1 -0
  259. package/package.json +48 -3
  260. package/src/AgentSkills.ts +329 -0
  261. package/src/AgentWeb.ts +507 -0
  262. package/src/App.ts +435 -0
  263. package/src/Blueprint.ts +276 -0
  264. package/src/Brand.ts +415 -0
  265. package/src/Changelog.ts +136 -0
  266. package/src/Cli.ts +1458 -0
  267. package/src/DbAdmin.ts +115 -0
  268. package/src/Dependencies.ts +170 -0
  269. package/src/Deploy.ts +563 -0
  270. package/src/Docs.ts +309 -0
  271. package/src/Doctor.ts +424 -0
  272. package/src/Dossier.ts +148 -0
  273. package/src/Emit.ts +68 -0
  274. package/src/Errors.ts +18 -0
  275. package/src/Evals.ts +153 -0
  276. package/src/Files.ts +152 -0
  277. package/src/Generate.ts +402 -0
  278. package/src/Guards.ts +541 -0
  279. package/src/Inspect.ts +358 -0
  280. package/src/Keychain.ts +107 -0
  281. package/src/Lock.ts +174 -0
  282. package/src/Mcp.ts +159 -0
  283. package/src/Merge.ts +70 -0
  284. package/src/Migrate.ts +331 -0
  285. package/src/Plugins.ts +347 -0
  286. package/src/Postgres.ts +353 -0
  287. package/src/Publish.ts +64 -0
  288. package/src/Registry.ts +405 -0
  289. package/src/Remote.ts +1158 -0
  290. package/src/Run.ts +541 -0
  291. package/src/SyncGen.ts +570 -0
  292. package/src/Update.ts +873 -0
  293. package/src/bin.ts +46 -0
  294. package/src/index.ts +7 -0
package/src/Remote.ts ADDED
@@ -0,0 +1,1158 @@
1
+ /**
2
+ * The CLI as a surface of a running kernel (docs/cli.md, "Calling a kernel"):
3
+ *
4
+ * eloxiv login [--url] the OAuth device flow (RFC 8628) against the kernel's authorisation server
5
+ * eloxiv logout [--url] revoke the stored grant and forget it
6
+ * eloxiv actions [--url] the kernel's actions
7
+ * eloxiv call <action> ... invoke an action over HTTP and print the result envelope
8
+ *
9
+ * A sign-in's tokens live in the OS keychain (`Keychain.ts`), or where none answers in `<config dir>/credentials.json`
10
+ * (mode 0600, directory 0700), which also holds the rest of each sign-in: the config dir is `ELOXIV_CONFIG_DIR`, else
11
+ * `$XDG_CONFIG_HOME/eloxiv`, else `~/.config/eloxiv` (`%APPDATA%\eloxiv` on Windows). Tokens an older CLI left in
12
+ * the file move to the keychain on the next command that reads them. `ELOXIV_TOKEN` (an API token) is used instead of
13
+ * a stored login when set. Calls carry `x-eloxiv-surface: cli`, so the audit log records them as the CLI's; the label
14
+ * grants nothing.
15
+ */
16
+ import { MAKE_ACTIONS_PATH, MAKE_MODULE_PREFIX, SURFACE_HEADER } from "@eloxiv/contracts"
17
+ import { Console, Effect, FileSystem, Option, Path, Schema } from "effect"
18
+ import { randomBytes } from "node:crypto"
19
+ import { CliError, ExitStatus } from "./Errors.ts"
20
+ import { SERVICE, TokenStores, type TokenStore } from "./Keychain.ts"
21
+ import { withFileLock } from "./Lock.ts"
22
+
23
+ const CLIENT_NAME = "eloxiv CLI"
24
+ const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"
25
+
26
+ /** A sign-in as `credentials.json` keeps it: its tokens too when they are kept there, else they are in the keychain. */
27
+ const StoredLogin = Schema.Struct({
28
+ clientId: Schema.String,
29
+ accessToken: Schema.optionalKey(Schema.String),
30
+ refreshToken: Schema.optionalKey(Schema.String),
31
+ /** Epoch milliseconds. */
32
+ expiresAt: Schema.Number,
33
+ scope: Schema.String,
34
+ })
35
+ type StoredLogin = typeof StoredLogin.Type
36
+
37
+ /** A sign-in with its tokens, wherever they are kept. */
38
+ interface Login extends StoredLogin {
39
+ readonly accessToken: string
40
+ readonly refreshToken: string
41
+ }
42
+
43
+ /**
44
+ * A grant's tokens, as the keychain holds them, with the client they were issued to (absent from an earlier CLI's
45
+ * entries), so `logout` can revoke an entry the file no longer records.
46
+ */
47
+ const Tokens = Schema.Struct({
48
+ accessToken: Schema.String,
49
+ refreshToken: Schema.String,
50
+ clientId: Schema.optionalKey(Schema.String),
51
+ })
52
+ const decodeTokens = Schema.decodeUnknownEffect(Schema.fromJsonString(Tokens))
53
+
54
+ const Credentials = Schema.Struct({
55
+ /** 1: every sign-in's tokens in the file (an older CLI); 2: in the keychain, or in the file where there is none. */
56
+ version: Schema.Literals([1, 2]),
57
+ /** The kernel `login` last signed in to: the default `--url`. */
58
+ current: Schema.optionalKey(Schema.String),
59
+ kernels: Schema.Record(Schema.String, StoredLogin),
60
+ })
61
+ type Credentials = typeof Credentials.Type
62
+
63
+ const empty: Credentials = { version: 2, kernels: {} }
64
+
65
+ /**
66
+ * Where the CLI keeps its credentials, always an absolute path: it also names the lock and every keychain account, so
67
+ * two working directories must never resolve one relative setting to the same name. A relative `XDG_CONFIG_HOME` is
68
+ * ignored, as the XDG Base Directory specification asks.
69
+ */
70
+ export const configDir = Effect.gen(function* () {
71
+ const path = yield* Path.Path
72
+ const env = process.env
73
+ if (env["ELOXIV_CONFIG_DIR"]) return path.resolve(env["ELOXIV_CONFIG_DIR"])
74
+ if (process.platform === "win32" && env["APPDATA"]) return path.resolve(env["APPDATA"], "eloxiv")
75
+ const xdg = env["XDG_CONFIG_HOME"]
76
+ if (xdg && path.isAbsolute(xdg)) return path.resolve(xdg, "eloxiv")
77
+ const home = env["HOME"] ?? env["USERPROFILE"]
78
+ if (!home) return yield* new CliError({ message: "Cannot find a config directory: set ELOXIV_CONFIG_DIR" })
79
+ return path.resolve(home, ".config", "eloxiv")
80
+ })
81
+
82
+ const credentialsFile = Effect.gen(function* () {
83
+ const path = yield* Path.Path
84
+ return path.join(yield* configDir, "credentials.json")
85
+ })
86
+
87
+ /**
88
+ * The config directory, made private before the credentials are read or written there: created 0700; one this user
89
+ * owns tightened to 0700 when its group or others may use it; one another user owns refused, since they could
90
+ * replace or read what the CLI keeps there. Windows has no POSIX owner or mode (Node cannot set an owner-only ACL):
91
+ * the directory keeps the ACL it inherits (docs/cli.md).
92
+ */
93
+ const privateConfigDir = Effect.gen(function* () {
94
+ const fs = yield* FileSystem.FileSystem
95
+ const dir = yield* configDir
96
+ const fail = (e: { message: string }) => new CliError({ message: `Cannot use ${dir}: ${e.message}` })
97
+ yield* fs.makeDirectory(dir, { recursive: true, mode: 0o700 }).pipe(Effect.mapError(fail))
98
+ const uid = process.getuid?.()
99
+ if (process.platform === "win32" || uid === undefined) return dir
100
+ const info = yield* fs.stat(dir).pipe(Effect.mapError(fail))
101
+ const owner = Option.getOrUndefined(info.uid)
102
+ if (owner !== undefined && owner !== uid) {
103
+ return yield* new CliError({
104
+ message: `${dir} belongs to another user, so the CLI will not keep sign-ins there: set ELOXIV_CONFIG_DIR to a directory of your own`,
105
+ })
106
+ }
107
+ if ((info.mode & 0o077) !== 0) yield* fs.chmod(dir, 0o700).pipe(Effect.mapError(fail))
108
+ return dir
109
+ })
110
+
111
+ /** `credentials.json` as it is now (no tokens moved). */
112
+ const readCredentialsFile = Effect.gen(function* () {
113
+ const fs = yield* FileSystem.FileSystem
114
+ const file = yield* credentialsFile
115
+ if (!(yield* fs.exists(file).pipe(Effect.orElseSucceed(() => false)))) return empty
116
+ yield* privateConfigDir
117
+ const text = yield* fs
118
+ .readFileString(file)
119
+ .pipe(Effect.mapError((e) => new CliError({ message: `Cannot read ${file}: ${e.message}` })))
120
+ return yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Credentials))(text).pipe(
121
+ Effect.mapError(() => new CliError({ message: `${file} is not a credentials file; delete it and log in again` })),
122
+ )
123
+ })
124
+
125
+ /** The store this command keeps tokens in (`ELOXIV_CREDENTIAL_STORE`, the machine's keychain; `Keychain.ts`). */
126
+ const tokenStore = Effect.gen(function* () {
127
+ const stores = yield* TokenStores
128
+ return yield* Effect.tryPromise({
129
+ try: () => stores.resolve(),
130
+ catch: (e) => new CliError({ message: e instanceof Error ? e.message : String(e) }),
131
+ })
132
+ })
133
+
134
+ /** Where the tokens are, as messages say it. */
135
+ const storeName = (store: TokenStore, file: string) =>
136
+ store.kind === "keychain" ? store.keychain.name : `${file} (mode 0600)`
137
+
138
+ /** The keychain account of a grant: the grant's key and the config directory, so two never share one. */
139
+ const accountOf = (key: string) => Effect.map(configDir, (dir) => `${key} (${dir})`)
140
+
141
+ const keychainFailure = (store: Extract<TokenStore, { kind: "keychain" }>, doing: string, e: unknown) =>
142
+ new CliError({
143
+ message: `Cannot ${doing} ${store.keychain.name}: ${e instanceof Error ? e.message : String(e)}`,
144
+ })
145
+
146
+ /** Save a grant's tokens, and the client they were issued to, under its keychain account. */
147
+ const saveTokens = (
148
+ store: Extract<TokenStore, { kind: "keychain" }>,
149
+ account: string,
150
+ tokens: { readonly accessToken: string; readonly refreshToken: string; readonly clientId: string },
151
+ ) =>
152
+ Effect.tryPromise({
153
+ try: () => store.keychain.set(account, JSON.stringify(tokens)),
154
+ catch: (e) => keychainFailure(store, "save sign-in tokens to", e),
155
+ })
156
+
157
+ /** The file's sign-ins with every token in `kernels` moved to the keychain: written there first, then the file. */
158
+ const moveTokens = (credentials: Credentials, store: Extract<TokenStore, { kind: "keychain" }>) =>
159
+ Effect.gen(function* () {
160
+ const kernels: Record<string, StoredLogin> = {}
161
+ for (const [key, stored] of Object.entries(credentials.kernels)) {
162
+ const { accessToken, refreshToken, ...rest } = stored
163
+ if (accessToken !== undefined && refreshToken !== undefined) {
164
+ yield* saveTokens(store, yield* accountOf(key), { accessToken, refreshToken, clientId: rest.clientId })
165
+ }
166
+ kernels[key] = rest
167
+ }
168
+ return { ...credentials, version: 2 as const, kernels }
169
+ })
170
+
171
+ /**
172
+ * The credentials, with tokens an older CLI (or a machine that had no keychain then) left in the file moved to the
173
+ * keychain now that one answers: under the credentials lock, after reading the file again; the file is rewritten
174
+ * without them only once the keychain holds them.
175
+ */
176
+ const readCredentials = Effect.gen(function* () {
177
+ const credentials = yield* readCredentialsFile
178
+ if (!tokensInFile(credentials) || (yield* tokenStore).kind !== "keychain") return credentials
179
+ return yield* withCredentialsLock(readCredentialsLocked)
180
+ })
181
+
182
+ const tokensInFile = (credentials: Credentials) =>
183
+ Object.values(credentials.kernels).some((login) => login.refreshToken !== undefined)
184
+
185
+ /** `readCredentials` for a command that holds the credentials lock already (the lock is not reentrant). */
186
+ const readCredentialsLocked = Effect.gen(function* () {
187
+ const credentials = yield* readCredentialsFile
188
+ if (!tokensInFile(credentials)) return credentials
189
+ const store = yield* tokenStore
190
+ if (store.kind !== "keychain") return credentials
191
+ const moved = yield* moveTokens(credentials, store)
192
+ yield* writeCredentialsFile(moved)
193
+ yield* Console.error(`Moved sign-in tokens from ${yield* credentialsFile} to ${store.keychain.name}`)
194
+ return moved
195
+ })
196
+
197
+ /** Why a sign-in kept in the keychain cannot be used by a command that keeps tokens in the file. */
198
+ const keychainUnreachable = (store: Extract<TokenStore, { kind: "file" }>) =>
199
+ `Sign-in tokens are stored in the OS keychain, which is unavailable here${store.reason === undefined ? " (ELOXIV_CREDENTIAL_STORE=file)" : `: ${store.reason}`}`
200
+
201
+ /** A stored sign-in with its tokens: from the file, or the keychain. Undefined when the keychain has none for it. */
202
+ const withTokens = (key: string, stored: StoredLogin) =>
203
+ Effect.gen(function* () {
204
+ if (stored.accessToken !== undefined && stored.refreshToken !== undefined)
205
+ return { ...stored, accessToken: stored.accessToken, refreshToken: stored.refreshToken } satisfies Login
206
+ const store = yield* tokenStore
207
+ if (store.kind !== "keychain")
208
+ return yield* new CliError({ message: `${keychainUnreachable(store)}. Unlock the keychain and try again` })
209
+ const account = yield* accountOf(key)
210
+ const secret = yield* Effect.tryPromise({
211
+ try: () => store.keychain.get(account),
212
+ catch: (e) => keychainFailure(store, "read sign-in tokens from", e),
213
+ })
214
+ if (secret === undefined) return undefined
215
+ const tokens = yield* decodeTokens(secret).pipe(Effect.orElseSucceed(() => undefined))
216
+ return tokens === undefined
217
+ ? undefined
218
+ : ({ ...stored, accessToken: tokens.accessToken, refreshToken: tokens.refreshToken } satisfies Login)
219
+ })
220
+
221
+ /**
222
+ * Refuse to replace a sign-in whose tokens are in the keychain while this command cannot reach it: written to the file
223
+ * instead, the keychain's grant would stay valid with nothing left that names it for `logout` to revoke.
224
+ */
225
+ const refuseStrandingKeychainGrant = (credentials: Credentials, key: string, store: TokenStore, url: string) => {
226
+ const previous = credentials.kernels[key]
227
+ if (previous === undefined || previous.refreshToken !== undefined || store.kind !== "file") return Effect.void
228
+ return Effect.fail(
229
+ new CliError({
230
+ message: `${keychainUnreachable(store)}. Signing in to ${url} again here would leave that sign-in valid: unlock the keychain, or run eloxiv logout where it is available, then sign in again`,
231
+ }),
232
+ )
233
+ }
234
+
235
+ /**
236
+ * The credentials with `key`'s sign-in set to `login` (or removed, when undefined): its tokens in the keychain when
237
+ * one is used, else in the file. Under the credentials lock.
238
+ */
239
+ const storeLogin = (credentials: Credentials, key: string, login: Login | undefined, current?: string | null) =>
240
+ Effect.gen(function* () {
241
+ const store = yield* tokenStore
242
+ const account = yield* accountOf(key)
243
+ const { [key]: _previous, ...others } = credentials.kernels
244
+ let kept: StoredLogin | undefined = login
245
+ if (store.kind === "keychain") {
246
+ if (login === undefined) {
247
+ yield* Effect.tryPromise({
248
+ try: () => store.keychain.delete(account),
249
+ catch: (e) => keychainFailure(store, "remove sign-in tokens from", e),
250
+ })
251
+ } else {
252
+ const { accessToken, refreshToken, ...rest } = login
253
+ yield* saveTokens(store, account, { accessToken, refreshToken, clientId: rest.clientId })
254
+ kept = rest
255
+ }
256
+ }
257
+ const next = current === undefined ? credentials.current : (current ?? undefined)
258
+ yield* writeCredentialsFile({
259
+ version: 2,
260
+ ...(next === undefined ? {} : { current: next }),
261
+ kernels: kept === undefined ? others : { ...others, [key]: kept },
262
+ })
263
+ return store
264
+ })
265
+
266
+ /** A temporary file `writeCredentialsFile` names (`credentials.json.<pid>.<16 hex>.tmp`). */
267
+ const TEMPORARY = /^credentials\.json\.\d+\.[0-9a-f]{16}\.tmp$/u
268
+
269
+ /**
270
+ * Remove temporary credentials files a command left when it exited hard (a kill, a crash) between writing one and
271
+ * renaming it: they may hold tokens. Every write holds the credentials lock, so under it no other command is writing
272
+ * one. Only this user's files are removed (POSIX; Windows has no owner to compare).
273
+ */
274
+ const removeAbandonedTemporaries = (dir: string) =>
275
+ Effect.gen(function* () {
276
+ const fs = yield* FileSystem.FileSystem
277
+ const path = yield* Path.Path
278
+ const uid = process.getuid?.()
279
+ for (const name of yield* fs.readDirectory(dir).pipe(Effect.orElseSucceed((): Array<string> => []))) {
280
+ if (!TEMPORARY.test(name)) continue
281
+ const file = path.join(dir, name)
282
+ const info = yield* fs.stat(file).pipe(Effect.option)
283
+ if (Option.isNone(info) || info.value.type !== "File") continue
284
+ const owner = Option.getOrUndefined(info.value.uid)
285
+ if (uid !== undefined && owner !== undefined && owner !== uid) continue
286
+ yield* fs.remove(file).pipe(Effect.ignore)
287
+ }
288
+ })
289
+
290
+ /**
291
+ * Write the credentials readable by the user alone, in the private config directory: a new temporary file there,
292
+ * created exclusively with mode 0600 (never one that already exists), renamed over the file (so it is 0600 also when
293
+ * it existed), and removed when anything fails.
294
+ */
295
+ const writeCredentialsFile = (credentials: Credentials) =>
296
+ Effect.gen(function* () {
297
+ const fs = yield* FileSystem.FileSystem
298
+ const file = yield* credentialsFile
299
+ const fail = (e: { message: string }) => new CliError({ message: `Cannot write ${file}: ${e.message}` })
300
+ const dir = yield* privateConfigDir
301
+ yield* removeAbandonedTemporaries(dir)
302
+ const temporary = `${file}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`
303
+ yield* Effect.gen(function* () {
304
+ yield* fs.writeFileString(temporary, `${JSON.stringify(credentials, null, 2)}\n`, { flag: "wx", mode: 0o600 })
305
+ yield* fs.rename(temporary, file)
306
+ }).pipe(
307
+ Effect.onError(() => fs.remove(temporary).pipe(Effect.ignore)),
308
+ Effect.mapError(fail),
309
+ )
310
+ })
311
+
312
+ /** Every request to a kernel gives up after this, so a lock holder cannot hang on the network. */
313
+ const REQUEST_TIMEOUT_MS = 20_000
314
+
315
+ /**
316
+ * Run `body` holding the credentials lock (`credentials.json.lock`, see `Lock.ts`). Every change to the
317
+ * credentials happens under it, after reading the file again: a refresh above all, since a refresh token works
318
+ * once and presenting it twice ends the whole grant.
319
+ */
320
+ const withCredentialsLock = <A, E, R>(body: Effect.Effect<A, E, R>) =>
321
+ Effect.gen(function* () {
322
+ const file = yield* credentialsFile
323
+ yield* privateConfigDir
324
+ return yield* withFileLock(file, body)
325
+ })
326
+
327
+ /** A JSON field as text, or `fallback` when it is not a string. */
328
+ const text = (value: unknown, fallback: string | number = "") => (typeof value === "string" ? value : String(fallback))
329
+
330
+ const normalise = (url: string) => url.replace(/\/+$/u, "")
331
+
332
+ /** The kernel `--url` names, else `ELOXIV_URL`, else the one `login` last signed in to. */
333
+ export const resolveKernelUrl = (flag: string | undefined) =>
334
+ Effect.flatMap(readCredentials, (credentials) => kernelUrl(flag, credentials))
335
+
336
+ /** The kernel to talk to: `--url`, else `ELOXIV_URL`, else the one `login` last signed in to. */
337
+ const kernelUrl = (flag: string | undefined, credentials: Credentials) => {
338
+ const fromEnv = process.env["ELOXIV_URL"]
339
+ const url = flag ?? (fromEnv === undefined || fromEnv.length === 0 ? undefined : fromEnv) ?? credentials.current
340
+ if (url === undefined) {
341
+ return Effect.fail(
342
+ new CliError({ message: "No kernel: pass --url, set ELOXIV_URL, or run eloxiv login --url <kernel>" }),
343
+ )
344
+ }
345
+ return Effect.succeed(normalise(url))
346
+ }
347
+
348
+ const request = (url: string, init: RequestInit = {}) =>
349
+ Effect.tryPromise({
350
+ try: () => fetch(url, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), ...init }),
351
+ catch: (e) => new CliError({ message: `Cannot reach ${url}: ${e instanceof Error ? e.message : String(e)}` }),
352
+ })
353
+
354
+ const readJson = (response: Response) =>
355
+ Effect.tryPromise({
356
+ try: async () => (await response.json()) as Record<string, unknown>,
357
+ catch: () => new CliError({ message: `The kernel answered ${response.status} with a body that is not JSON` }),
358
+ })
359
+
360
+ const form = (url: string, params: Record<string, string>) =>
361
+ request(url, {
362
+ method: "POST",
363
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
364
+ body: new URLSearchParams(params).toString(),
365
+ }).pipe(
366
+ Effect.flatMap((response) => readJson(response).pipe(Effect.map((body) => ({ status: response.status, body })))),
367
+ )
368
+
369
+ const metadataOf = (url: string) =>
370
+ Effect.gen(function* () {
371
+ const response = yield* request(`${url}/.well-known/oauth-authorization-server`)
372
+ if (!response.ok) {
373
+ return yield* new CliError({ message: `${url} has no OAuth authorisation server (${response.status})` })
374
+ }
375
+ const body = yield* readJson(response)
376
+ const endpoint = (name: string) => {
377
+ const value = body[name]
378
+ return typeof value === "string" ? value : undefined
379
+ }
380
+ const device = endpoint("device_authorization_endpoint")
381
+ const token = endpoint("token_endpoint")
382
+ const registration = endpoint("registration_endpoint")
383
+ if (device === undefined || token === undefined || registration === undefined) {
384
+ return yield* new CliError({ message: `${url} does not offer the device flow with client registration` })
385
+ }
386
+ return { device, token, registration, revocation: endpoint("revocation_endpoint") }
387
+ })
388
+
389
+ const tokensFrom = (clientId: string, body: Record<string, unknown>): Login => ({
390
+ clientId,
391
+ accessToken: text(body["access_token"]),
392
+ refreshToken: text(body["refresh_token"]),
393
+ expiresAt: Date.now() + Number(body["expires_in"] ?? 0) * 1000,
394
+ scope: text(body["scope"], ""),
395
+ })
396
+
397
+ /**
398
+ * The protected resources the CLI holds grants for: the kernel's API (`eloxiv login`) and its MCP endpoint (`eloxiv
399
+ * mcp login`, for `mcp serve`). The kernel binds each token to one resource (its audience), so each is a grant of its
400
+ * own, stored under its own key: the kernel's URL for the API, `<url>#mcp` for MCP.
401
+ */
402
+ export type Resource = "api" | "mcp"
403
+ const grantKey = (url: string, resource: Resource) => (resource === "api" ? url : `${url}#mcp`)
404
+ const loginCommand = (url: string, resource: Resource) =>
405
+ resource === "api" ? `eloxiv login --url ${url}` : `eloxiv mcp login --url ${url}`
406
+
407
+ /**
408
+ * Revoke a grant the kernel has just issued that this command could not keep (a check under the lock refused it, or
409
+ * storing it failed), so it is not left valid with nothing naming it for `logout`. What happened, as a sentence.
410
+ */
411
+ const revokeUnkept = (revocation: string | undefined, login: Login) =>
412
+ Effect.gen(function* () {
413
+ if (revocation === undefined)
414
+ return "The kernel has no revocation endpoint, so the sign-in it just issued may still be valid"
415
+ const status = yield* request(revocation, {
416
+ method: "POST",
417
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
418
+ body: new URLSearchParams({ token: login.refreshToken, client_id: login.clientId }).toString(),
419
+ }).pipe(
420
+ Effect.map((response) => response.status),
421
+ Effect.orElseSucceed(() => undefined),
422
+ )
423
+ return status === 200
424
+ ? "The sign-in the kernel just issued was revoked"
425
+ : `The sign-in the kernel just issued could not be revoked (${status === undefined ? "no answer" : `it answered ${status}`}) and may still be valid`
426
+ })
427
+
428
+ /** `eloxiv login` (and `mcp login`): register this CLI with the kernel (once per kernel), then the device flow. */
429
+ export const login = (options: {
430
+ readonly url: string | undefined
431
+ readonly scope: string | undefined
432
+ readonly resource?: Resource
433
+ }) =>
434
+ Effect.gen(function* () {
435
+ const resource = options.resource ?? "api"
436
+ const credentials = yield* readCredentials
437
+ const url = yield* kernelUrl(options.url, credentials)
438
+ const key = grantKey(url, resource)
439
+ yield* refuseStrandingKeychainGrant(credentials, key, yield* tokenStore, url)
440
+ const endpoints = yield* metadataOf(url)
441
+ let clientId = credentials.kernels[url]?.clientId ?? credentials.kernels[key]?.clientId
442
+ if (clientId === undefined) {
443
+ const registered = yield* request(endpoints.registration, {
444
+ method: "POST",
445
+ headers: { "content-type": "application/json" },
446
+ body: JSON.stringify({
447
+ client_name: CLIENT_NAME,
448
+ grant_types: [DEVICE_GRANT, "refresh_token"],
449
+ token_endpoint_auth_method: "none",
450
+ }),
451
+ })
452
+ const body = yield* readJson(registered)
453
+ if (registered.status !== 201 || typeof body["client_id"] !== "string") {
454
+ return yield* new CliError({
455
+ message: `Client registration failed: ${text(body["error_description"], registered.status)}`,
456
+ })
457
+ }
458
+ clientId = body["client_id"]
459
+ }
460
+ const started = yield* form(endpoints.device, {
461
+ client_id: clientId,
462
+ resource: `${url}/${resource}`,
463
+ ...(options.scope === undefined ? {} : { scope: options.scope }),
464
+ })
465
+ if (started.status !== 200) {
466
+ return yield* new CliError({
467
+ message: `The kernel refused the device flow: ${text(started.body["error_description"], text(started.body["error"], started.status))}`,
468
+ })
469
+ }
470
+ const device = started.body as {
471
+ device_code: string
472
+ user_code: string
473
+ verification_uri: string
474
+ verification_uri_complete?: string
475
+ expires_in: number
476
+ interval?: number
477
+ }
478
+ yield* Console.log(`To sign in, open ${device.verification_uri} and enter the code ${device.user_code}`)
479
+ if (device.verification_uri_complete !== undefined)
480
+ yield* Console.log(`or open ${device.verification_uri_complete}`)
481
+ let interval = (device.interval ?? 5) * 1000
482
+ const deadline = Date.now() + device.expires_in * 1000
483
+ for (;;) {
484
+ if (Date.now() > deadline) return yield* new CliError({ message: "The code expired; run eloxiv login again" })
485
+ yield* Effect.sleep(interval)
486
+ const polled = yield* form(endpoints.token, {
487
+ grant_type: DEVICE_GRANT,
488
+ device_code: device.device_code,
489
+ client_id: clientId,
490
+ })
491
+ if (polled.status === 200) {
492
+ const login = tokensFrom(clientId, polled.body)
493
+ // Other kernels' logins may have changed while this one waited for the person: write over the latest. A grant
494
+ // that cannot be kept is revoked before the command fails.
495
+ const store = yield* withCredentialsLock(
496
+ Effect.gen(function* () {
497
+ const latest = yield* readCredentialsLocked
498
+ yield* refuseStrandingKeychainGrant(latest, key, yield* tokenStore, url)
499
+ return yield* storeLogin(latest, key, login, url)
500
+ }),
501
+ ).pipe(
502
+ Effect.catch((error) =>
503
+ Effect.flatMap(revokeUnkept(endpoints.revocation, login), (note) =>
504
+ Effect.fail(error instanceof CliError ? new CliError({ message: `${error.message}. ${note}` }) : error),
505
+ ),
506
+ ),
507
+ )
508
+ const file = yield* credentialsFile
509
+ yield* Console.log(
510
+ `Signed in to ${url}${resource === "mcp" ? " (MCP)" : ""} (${login.scope}). Tokens stored in ${storeName(store, file)}`,
511
+ )
512
+ if (store.kind === "file" && store.reason !== undefined)
513
+ yield* Console.error(`No OS keychain is available, so tokens were saved to ${file} (${store.reason})`)
514
+ return
515
+ }
516
+ const error = text(polled.body["error"], "")
517
+ if (error === "authorization_pending") continue
518
+ if (error === "slow_down") {
519
+ interval += 5_000
520
+ continue
521
+ }
522
+ return yield* new CliError({
523
+ message:
524
+ error === "access_denied"
525
+ ? "Sign-in was denied"
526
+ : `Sign-in failed: ${text(polled.body["error_description"], error)}`,
527
+ })
528
+ }
529
+ })
530
+
531
+ /**
532
+ * `eloxiv logout`: revoke the stored grant, then forget it. When the grant cannot be revoked (the kernel is
533
+ * unreachable, has no revocation endpoint, or does not answer 200) the credentials are kept, so `logout` can
534
+ * be run again, and the command fails: the grant may still be valid (RFC 7009 section 2.2.1).
535
+ */
536
+ export const logout = (options: { readonly url: string | undefined; readonly resource?: Resource }) =>
537
+ Effect.gen(function* () {
538
+ const resource = options.resource ?? "api"
539
+ const url = yield* kernelUrl(options.url, yield* readCredentials)
540
+ const key = grantKey(url, resource)
541
+ const file = yield* credentialsFile
542
+ const signedOut = yield* withCredentialsLock(
543
+ Effect.gen(function* () {
544
+ const credentials = yield* readCredentialsLocked
545
+ const listed = credentials.kernels[key]
546
+ const store = yield* tokenStore
547
+ const unrevoked = (reason: string) =>
548
+ new CliError({
549
+ message: `Could not revoke the sign-in to ${url}: ${reason}. It may still be valid, so the credentials are kept; run eloxiv logout again (or remove ${url} from ${file} to forget it unrevoked)`,
550
+ })
551
+ // Every grant either store holds for this key: the file's tokens, and the keychain's entry, read even when the
552
+ // file has no record of it. Nothing is forgotten until each is revoked; revoking one twice is harmless
553
+ // (RFC 7009 answers 200 for a token already revoked), so a failed logout can simply be run again.
554
+ const grants: Array<{ readonly refreshToken: string; readonly clientId: string }> = []
555
+ if (listed?.refreshToken !== undefined)
556
+ grants.push({ refreshToken: listed.refreshToken, clientId: listed.clientId })
557
+ if (store.kind === "keychain") {
558
+ const account = yield* accountOf(key)
559
+ const secret = yield* Effect.tryPromise({
560
+ try: () => store.keychain.get(account),
561
+ catch: (e) => unrevoked(keychainFailure(store, "read sign-in tokens from", e).message),
562
+ })
563
+ if (secret !== undefined) {
564
+ const tokens = yield* decodeTokens(secret).pipe(Effect.orElseSucceed(() => undefined))
565
+ if (tokens === undefined) {
566
+ return yield* unrevoked(
567
+ `${store.keychain.name} holds an entry for it ("${account}", service ${SERVICE}) that is not a pair of sign-in tokens; delete that entry by hand`,
568
+ )
569
+ }
570
+ // The client the tokens were issued to: the entry's own, or the file's record of this same grant. Never
571
+ // another resource's: a kernel answers 200 to a revocation naming the wrong client, revoking nothing.
572
+ const clientId = tokens.clientId ?? listed?.clientId
573
+ if (clientId === undefined) {
574
+ return yield* new CliError({
575
+ message: `Could not revoke the sign-in to ${url}: ${store.keychain.name} holds tokens for it ("${account}", service ${SERVICE}) with no client recorded, so they cannot be revoked and were left in place. Revoke the sign-in on the kernel, then delete that entry by hand`,
576
+ })
577
+ }
578
+ if (!grants.some((grant) => grant.refreshToken === tokens.refreshToken))
579
+ grants.push({ refreshToken: tokens.refreshToken, clientId })
580
+ }
581
+ } else if (listed !== undefined && listed.refreshToken === undefined) {
582
+ // Its tokens are in the keychain, which this command cannot reach.
583
+ return yield* unrevoked(keychainUnreachable(store))
584
+ }
585
+ if (listed === undefined && grants.length === 0) return false
586
+ // With no grant left (its keychain entry removed by hand) there is nothing to revoke with: it is forgotten.
587
+ if (grants.length > 0) {
588
+ const endpoints = yield* metadataOf(url).pipe(Effect.mapError((e) => unrevoked(e.message)))
589
+ const revocation = endpoints.revocation
590
+ if (revocation === undefined) return yield* unrevoked("it has no revocation endpoint")
591
+ for (const grant of grants) {
592
+ const response = yield* request(revocation, {
593
+ method: "POST",
594
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
595
+ body: new URLSearchParams({ token: grant.refreshToken, client_id: grant.clientId }).toString(),
596
+ }).pipe(Effect.mapError((e) => unrevoked(e.message)))
597
+ if (response.status !== 200) return yield* unrevoked(`its revocation endpoint answered ${response.status}`)
598
+ }
599
+ }
600
+ // Removed from both: the keychain (when one is used) first, then the file, so a failure keeps the file's record.
601
+ yield* storeLogin(
602
+ credentials,
603
+ key,
604
+ undefined,
605
+ credentials.current === url && resource === "api" ? null : undefined,
606
+ )
607
+ return true
608
+ }),
609
+ )
610
+ yield* Console.log(signedOut ? `Signed out of ${url}` : `Not signed in to ${url}`)
611
+ })
612
+
613
+ /**
614
+ * A usable access token for `url`: `ELOXIV_TOKEN`, or the stored login, refreshed when it has expired (or the
615
+ * kernel refused it: `rejected`). A refresh happens under the credentials lock, with the file read again
616
+ * there: a command that waited for another's refresh uses the tokens that one stored instead of spending the
617
+ * same refresh token a second time (which would end the grant).
618
+ */
619
+ const accessToken = (url: string, rejected?: string, resource: Resource = "api") =>
620
+ Effect.gen(function* () {
621
+ const env = process.env["ELOXIV_TOKEN"]
622
+ if (env !== undefined && env.length > 0) return { token: env, refreshable: false }
623
+ const key = grantKey(url, resource)
624
+ const notSignedIn = new CliError({
625
+ message: `Not signed in to ${url}${resource === "mcp" ? "'s MCP endpoint" : ""}: run ${loginCommand(url, resource)}`,
626
+ })
627
+ const usable = (login: Login) => login.accessToken !== rejected && login.expiresAt > Date.now() + 30_000
628
+ const listed = (yield* readCredentials).kernels[key]
629
+ if (listed === undefined) return yield* notSignedIn
630
+ const stored = yield* withTokens(key, listed)
631
+ if (stored === undefined) return yield* notSignedIn
632
+ if (usable(stored)) return { token: stored.accessToken, refreshable: true }
633
+ return yield* withCredentialsLock(
634
+ Effect.gen(function* () {
635
+ const credentials = yield* readCredentialsLocked
636
+ const found = credentials.kernels[key]
637
+ const latest = found === undefined ? undefined : yield* withTokens(key, found)
638
+ if (latest === undefined) return yield* notSignedIn
639
+ if (usable(latest)) return { token: latest.accessToken, refreshable: false }
640
+ const endpoints = yield* metadataOf(url)
641
+ const refreshed = yield* form(endpoints.token, {
642
+ grant_type: "refresh_token",
643
+ refresh_token: latest.refreshToken,
644
+ client_id: latest.clientId,
645
+ })
646
+ if (refreshed.status !== 200) {
647
+ return yield* new CliError({
648
+ message: `Your sign-in to ${url} has ended; run ${loginCommand(url, resource)}`,
649
+ })
650
+ }
651
+ const login = tokensFrom(latest.clientId, refreshed.body)
652
+ yield* storeLogin(credentials, key, login)
653
+ return { token: login.accessToken, refreshable: false }
654
+ }),
655
+ )
656
+ })
657
+
658
+ /** `--input`: inline JSON, or `@<file>` for a file's contents (`@-` for standard input). */
659
+ const readInput = (input: string) =>
660
+ Effect.gen(function* () {
661
+ const fs = yield* FileSystem.FileSystem
662
+ let text = input
663
+ if (input === "@-") {
664
+ text = yield* Effect.tryPromise({
665
+ try: async () => {
666
+ const chunks: Array<Buffer> = []
667
+ for await (const chunk of process.stdin) chunks.push(chunk as Buffer)
668
+ return Buffer.concat(chunks).toString("utf8")
669
+ },
670
+ catch: () => new CliError({ message: "Cannot read standard input" }),
671
+ })
672
+ } else if (input.startsWith("@")) {
673
+ text = yield* fs
674
+ .readFileString(input.slice(1))
675
+ .pipe(Effect.mapError((e) => new CliError({ message: `Cannot read ${input.slice(1)}: ${e.message}` })))
676
+ }
677
+ try {
678
+ return JSON.parse(text) as unknown
679
+ } catch {
680
+ return yield* new CliError({ message: "--input is not valid JSON" })
681
+ }
682
+ })
683
+
684
+ /**
685
+ * `eloxiv call`: invoke an action through the kernel's HTTP surface and print the JSON result envelope.
686
+ * An action's error is printed as JSON too, with exit status 1.
687
+ */
688
+ export const call = (options: {
689
+ readonly action: string
690
+ readonly input: string
691
+ readonly url: string | undefined
692
+ readonly org: string | undefined
693
+ readonly idempotencyKey: string | undefined
694
+ }) =>
695
+ Effect.gen(function* () {
696
+ const credentials = yield* readCredentials
697
+ const url = yield* kernelUrl(options.url, credentials)
698
+ const input = yield* readInput(options.input)
699
+ const send = (token: string) =>
700
+ // A MAKE action (named mk_*, a prefix no app module may take) is served at its own route.
701
+ request(
702
+ `${url}${options.action.startsWith(MAKE_MODULE_PREFIX) ? MAKE_ACTIONS_PATH : "/api/actions"}/${encodeURIComponent(options.action)}`,
703
+ {
704
+ method: "POST",
705
+ headers: {
706
+ authorization: `Bearer ${token}`,
707
+ "content-type": "application/json",
708
+ [SURFACE_HEADER]: "cli",
709
+ ...(options.org === undefined ? {} : { "x-eloxiv-org": options.org }),
710
+ ...(options.idempotencyKey === undefined ? {} : { "idempotency-key": options.idempotencyKey }),
711
+ },
712
+ body: JSON.stringify(input),
713
+ },
714
+ )
715
+ const first = yield* accessToken(url)
716
+ let response = yield* send(first.token)
717
+ // An access token revoked or expired early: refresh once and retry.
718
+ if (response.status === 401 && first.refreshable) {
719
+ response = yield* send((yield* accessToken(url, first.token)).token)
720
+ }
721
+ const body = yield* readJson(response)
722
+ yield* Console.log(JSON.stringify(body, null, 2))
723
+ if (!response.ok) return yield* new ExitStatus({ code: 1, reason: text(body["_tag"], response.status) })
724
+ })
725
+
726
+ /**
727
+ * `eloxiv actions`: the actions the kernel serves, from its OpenAPI document. Signed in (or with `ELOXIV_TOKEN`),
728
+ * the kernel lists only the actions you can reach: what the policy or the token's scope hides is left out.
729
+ */
730
+ export const actions = (options: { readonly url: string | undefined; readonly json: boolean }) =>
731
+ Effect.gen(function* () {
732
+ const credentials = yield* readCredentials
733
+ const url = yield* kernelUrl(options.url, credentials)
734
+ // Not signed in: the whole catalogue, as the kernel publishes it. Signed in, what this sign-in reaches: a sign-in
735
+ // that has ended (its refresh refused) fails the command, as `call` does, never falling back to the catalogue.
736
+ const env = process.env["ELOXIV_TOKEN"]
737
+ const signedIn = (env !== undefined && env.length > 0) || credentials.kernels[url] !== undefined
738
+ const token = signedIn ? (yield* accessToken(url)).token : undefined
739
+ const response = yield* request(`${url}/api/openapi.json`, {
740
+ headers: token === undefined ? {} : { authorization: `Bearer ${token}`, [SURFACE_HEADER]: "cli" },
741
+ })
742
+ if (response.status === 401 || response.status === 403) {
743
+ const body = yield* readJson(response)
744
+ return yield* new CliError({ message: `${url} refused your sign-in: ${text(body["message"], response.status)}` })
745
+ }
746
+ if (!response.ok) return yield* new CliError({ message: `${url} has no action catalogue (${response.status})` })
747
+ const document = (yield* readJson(response)) as {
748
+ paths?: Record<
749
+ string,
750
+ { post?: { description?: string; requestBody?: { content?: Record<string, { schema?: unknown }> } } }
751
+ >
752
+ }
753
+ const listed = Object.entries(document.paths ?? {})
754
+ .filter(([path]) => path.startsWith("/api/actions/"))
755
+ .map(([path, item]) => ({
756
+ name: path.slice("/api/actions/".length),
757
+ description: item.post?.description ?? "",
758
+ input: item.post?.requestBody?.content?.["application/json"]?.schema ?? null,
759
+ }))
760
+ .sort((a, b) => a.name.localeCompare(b.name))
761
+ if (options.json) return yield* Console.log(JSON.stringify(listed, null, 2))
762
+ const width = Math.max(0, ...listed.map((a) => a.name.length))
763
+ for (const action of listed) yield* Console.log(`${action.name.padEnd(width)} ${action.description}`)
764
+ })
765
+
766
+ /**
767
+ * A request to the kernel with the stored sign-in (or `ELOXIV_TOKEN`), labelled as the CLI's: refreshed once and
768
+ * retried when the kernel refuses the access token. `stream` drops the request timeout (a run's event stream lasts
769
+ * as long as the run).
770
+ */
771
+ const authorized = (url: string, path: string, init: RequestInit = {}, stream = false, resource: Resource = "api") =>
772
+ Effect.gen(function* () {
773
+ const send = (token: string) =>
774
+ Effect.tryPromise({
775
+ try: () =>
776
+ fetch(`${url}${path}`, {
777
+ ...init,
778
+ ...(stream ? {} : { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }),
779
+ headers: {
780
+ ...(init.headers as Record<string, string> | undefined),
781
+ authorization: `Bearer ${token}`,
782
+ [SURFACE_HEADER]: "cli",
783
+ },
784
+ }),
785
+ catch: (e) => new CliError({ message: `Cannot reach ${url}: ${e instanceof Error ? e.message : String(e)}` }),
786
+ })
787
+ const first = yield* accessToken(url, undefined, resource)
788
+ const response = yield* send(first.token)
789
+ if (response.status !== 401 || !first.refreshable) return response
790
+ return yield* send((yield* accessToken(url, first.token, resource)).token)
791
+ })
792
+
793
+ /** `eloxiv whoami`: which kernel, which credential, and the organisations (with roles) it acts for. */
794
+ export const whoami = (options: { readonly url: string | undefined; readonly json: boolean }) =>
795
+ Effect.gen(function* () {
796
+ const credentials = yield* readCredentials
797
+ const url = yield* kernelUrl(options.url, credentials)
798
+ const env = process.env["ELOXIV_TOKEN"]
799
+ const stored = credentials.kernels[url]
800
+ const credential =
801
+ env !== undefined && env.length > 0
802
+ ? { kind: "ELOXIV_TOKEN" as const }
803
+ : stored === undefined
804
+ ? undefined
805
+ : {
806
+ kind: "login" as const,
807
+ scope: stored.scope,
808
+ expiresAt: new Date(stored.expiresAt).toISOString(),
809
+ // Where its tokens are: the OS keychain's name, or the credentials file.
810
+ tokens:
811
+ stored.refreshToken !== undefined
812
+ ? yield* credentialsFile
813
+ : storeName(yield* tokenStore, yield* credentialsFile),
814
+ }
815
+ if (credential === undefined) {
816
+ return yield* new CliError({ message: `Not signed in to ${url}: run eloxiv login --url ${url}` })
817
+ }
818
+ // Whether the kernel accepts the credential at all: what it lets the credential reach (as `actions` reads it).
819
+ // Only an answer that accepts the credential counts: a refusal fails, and so does a kernel that could not answer
820
+ // (a 5xx or anything else but 2xx; an unreachable kernel fails in `authorized`).
821
+ const reach = yield* authorized(url, "/api/openapi.json")
822
+ if (reach.status === 401 || reach.status === 403) {
823
+ const body: Record<string, unknown> = yield* readJson(reach).pipe(Effect.orElseSucceed(() => ({})))
824
+ return yield* new CliError({ message: `${url} refused your credential: ${text(body["message"], reach.status)}` })
825
+ }
826
+ if (!reach.ok) {
827
+ return yield* new CliError({
828
+ message: `Could not check your credential with ${url}: it answered ${reach.status}; try again later`,
829
+ })
830
+ }
831
+ // The organisations and roles: the kernel tells them to a person's session; an OAuth grant or an API token acts
832
+ // in the one organisation it was issued for, which the kernel does not list (it answers 401: expected). Any
833
+ // other failure means they could not be read.
834
+ const response = yield* authorized(url, "/api/me/organizations")
835
+ let organizations: ReadonlyArray<{ id: string; name: string; roles: ReadonlyArray<string> }> | null = null
836
+ if (response.ok) {
837
+ const body: unknown = yield* Effect.tryPromise(() => response.json()).pipe(Effect.orElseSucceed(() => undefined))
838
+ if (!Array.isArray(body)) {
839
+ return yield* new CliError({ message: `Could not read your organisations from ${url}: not a list` })
840
+ }
841
+ organizations = (body as ReadonlyArray<Record<string, unknown>>).map((org) => ({
842
+ id: text(org["orgId"] ?? org["id"]),
843
+ name: text(org["name"]),
844
+ roles: Array.isArray(org["roles"]) ? (org["roles"] as ReadonlyArray<unknown>).map((role) => text(role)) : [],
845
+ }))
846
+ } else if (response.status !== 401) {
847
+ return yield* new CliError({
848
+ message: `Could not read your organisations from ${url}: it answered ${response.status}; try again later`,
849
+ })
850
+ }
851
+ const report = { kernel: url, credential, organizations }
852
+ if (options.json) return yield* Console.log(JSON.stringify(report, null, 2))
853
+ yield* Console.log(
854
+ `${url}: ${credential.kind === "login" ? `signed in (scope ${credential.scope}, access token until ${credential.expiresAt}; tokens in ${credential.tokens})` : "ELOXIV_TOKEN"}`,
855
+ )
856
+ if (organizations === null) {
857
+ yield* Console.log(
858
+ " acts in the organisation picked when it was granted (the kernel lists organisations to sessions)",
859
+ )
860
+ } else {
861
+ for (const org of organizations)
862
+ yield* Console.log(` ${org.name} (${org.id})${org.roles.length === 0 ? "" : `: ${org.roles.join(", ")}`}`)
863
+ }
864
+ })
865
+
866
+ /** The complete server-sent events in `text`, and the incomplete rest. */
867
+ const sseEvents = (text: string) => {
868
+ const blocks = text.split(/\r?\n\r?\n/u)
869
+ const rest = blocks.pop() ?? ""
870
+ const events: Array<{ readonly type: string; readonly data: Record<string, unknown> }> = []
871
+ for (const block of blocks) {
872
+ const data = block
873
+ .split(/\r?\n/u)
874
+ .filter((line) => line.startsWith("data:"))
875
+ .map((line) => line.slice(5).trimStart())
876
+ .join("\n")
877
+ if (data === "") continue
878
+ try {
879
+ const event = JSON.parse(data) as { type?: unknown; data?: unknown }
880
+ if (typeof event.type === "string") {
881
+ events.push({ type: event.type, data: (event.data ?? {}) as Record<string, unknown> })
882
+ }
883
+ } catch {
884
+ // Not an event of the run's stream: skipped.
885
+ }
886
+ }
887
+ return { events, rest }
888
+ }
889
+
890
+ /**
891
+ * `eloxiv agent <prompt>`: one turn of the signed-in person's agent (`POST /agent/messages`, the action `agent.send`,
892
+ * so policy, consent and budgets apply as on every surface), followed to its end over the run's event stream. The
893
+ * answer is printed as it streams (or whole at the end), each tool call on standard error. Exits 1 when the run does
894
+ * not succeed.
895
+ */
896
+ export const agent = (options: {
897
+ readonly prompt: string
898
+ readonly url: string | undefined
899
+ readonly conversation: string | undefined
900
+ readonly json: boolean
901
+ }) =>
902
+ Effect.gen(function* () {
903
+ const url = yield* kernelUrl(options.url, yield* readCredentials)
904
+ const sent = yield* authorized(url, "/agent/messages", {
905
+ method: "POST",
906
+ headers: { "content-type": "application/json" },
907
+ body: JSON.stringify({
908
+ text: options.prompt,
909
+ ...(options.conversation === undefined ? {} : { conversationId: options.conversation }),
910
+ }),
911
+ })
912
+ const message = yield* readJson(sent)
913
+ if (!sent.ok) {
914
+ yield* Console.log(JSON.stringify(message, null, 2))
915
+ return yield* new ExitStatus({ code: 1, reason: text(message["_tag"], sent.status) })
916
+ }
917
+ const runId = text(message["runId"])
918
+ const conversationId = text(message["conversationId"])
919
+ const events = yield* authorized(
920
+ url,
921
+ `/agent/runs/${encodeURIComponent(runId)}/events?after=-1`,
922
+ { headers: { accept: "text/event-stream" } },
923
+ true,
924
+ )
925
+ if (!events.ok || events.body === null) {
926
+ return yield* new CliError({ message: `Cannot follow run ${runId}: the kernel answered ${events.status}` })
927
+ }
928
+ const body = events.body
929
+ const finished = yield* Effect.tryPromise({
930
+ try: async () => {
931
+ const reader = body.getReader()
932
+ const decoder = new TextDecoder()
933
+ let buffer = ""
934
+ let streamed = false
935
+ try {
936
+ for (;;) {
937
+ const { done, value } = await reader.read()
938
+ if (done) return { outcome: undefined, streamed }
939
+ const parsed = sseEvents(buffer + decoder.decode(value, { stream: true }))
940
+ buffer = parsed.rest
941
+ for (const event of parsed.events) {
942
+ if (event.type === "text-delta" && typeof event.data["delta"] === "string") {
943
+ streamed = true
944
+ if (!options.json) process.stdout.write(event.data["delta"])
945
+ } else if (event.type === "model-step" && Array.isArray(event.data["toolCalls"])) {
946
+ for (const call of event.data["toolCalls"] as ReadonlyArray<Record<string, unknown>>)
947
+ process.stderr.write(`tool: ${text(call["toolName"], "?")}\n`)
948
+ } else if (event.type === "tool-call") {
949
+ // A turn handed to one of the person's devices.
950
+ process.stderr.write(`tool: ${text(event.data["toolName"], "?")}\n`)
951
+ } else if (event.type === "consent-required") {
952
+ process.stderr.write("waiting for your consent to an action (answer it in the app)\n")
953
+ } else if (event.type === "run-finished") {
954
+ return { outcome: event.data, streamed }
955
+ }
956
+ }
957
+ }
958
+ } finally {
959
+ await reader.cancel().catch(() => undefined)
960
+ }
961
+ },
962
+ catch: (e) =>
963
+ new CliError({ message: `Lost run ${runId}'s events: ${e instanceof Error ? e.message : String(e)}` }),
964
+ })
965
+ const outcome = finished.outcome
966
+ if (outcome === undefined) return yield* new CliError({ message: `Run ${runId}'s events ended before it finished` })
967
+ const status = text(outcome["status"], "unknown")
968
+ if (options.json) yield* Console.log(JSON.stringify({ conversationId, runId, ...outcome }, null, 2))
969
+ else {
970
+ if (finished.streamed) process.stdout.write("\n")
971
+ else if (typeof outcome["result"] === "string") yield* Console.log(outcome["result"])
972
+ process.stderr.write(
973
+ `run ${runId} ${status}${typeof outcome["error"] === "string" ? `: ${outcome["error"]}` : ""} (continue with --conversation ${conversationId})\n`,
974
+ )
975
+ }
976
+ if (status !== "succeeded") return yield* new ExitStatus({ code: 1, reason: `run ${status}` })
977
+ })
978
+
979
+ /**
980
+ * Every event of a finished run (`eloxiv eval promote`), as the signed-in person reads it: the run's stream from the
981
+ * start until `run-finished`. A run still going, or one the kernel will not show this person, fails.
982
+ */
983
+ export const fetchRunEvents = (options: { readonly url: string | undefined; readonly runId: string }) =>
984
+ Effect.gen(function* () {
985
+ const url = yield* kernelUrl(options.url, yield* readCredentials)
986
+ const response = yield* authorized(
987
+ url,
988
+ `/agent/runs/${encodeURIComponent(options.runId)}/events?after=-1`,
989
+ { headers: { accept: "text/event-stream" }, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) },
990
+ true,
991
+ )
992
+ if (!response.ok || response.body === null) {
993
+ return yield* new CliError({
994
+ message: `Cannot read run ${options.runId}: the kernel answered ${response.status}`,
995
+ })
996
+ }
997
+ const body = response.body
998
+ return yield* Effect.tryPromise({
999
+ try: async () => {
1000
+ const reader = body.getReader()
1001
+ const decoder = new TextDecoder()
1002
+ const events: Array<{ readonly type: string; readonly data: Record<string, unknown> }> = []
1003
+ let buffer = ""
1004
+ try {
1005
+ for (;;) {
1006
+ const { done, value } = await reader.read()
1007
+ if (done) return { events, finished: false }
1008
+ const parsed = sseEvents(buffer + decoder.decode(value, { stream: true }))
1009
+ buffer = parsed.rest
1010
+ for (const event of parsed.events) {
1011
+ events.push(event)
1012
+ if (event.type === "run-finished") return { events, finished: true }
1013
+ }
1014
+ }
1015
+ } finally {
1016
+ await reader.cancel().catch(() => undefined)
1017
+ }
1018
+ },
1019
+ catch: (e) =>
1020
+ new CliError({ message: `Lost run ${options.runId}'s events: ${e instanceof Error ? e.message : String(e)}` }),
1021
+ }).pipe(
1022
+ Effect.flatMap(({ events, finished }) =>
1023
+ finished
1024
+ ? Effect.succeed(events)
1025
+ : Effect.fail(
1026
+ new CliError({ message: `Run ${options.runId} has not finished: only a finished run can be promoted` }),
1027
+ ),
1028
+ ),
1029
+ )
1030
+ })
1031
+
1032
+ /**
1033
+ * `eloxiv mcp serve`: the kernel's MCP server over stdio, for hosts that start local servers as processes. Each line
1034
+ * on standard input is a JSON-RPC message, posted to `<kernel>/mcp` (streamable HTTP) with the stored MCP grant
1035
+ * (`eloxiv mcp login`: the kernel takes for MCP only a token bound to its MCP resource, so the API sign-in of
1036
+ * `eloxiv login` is never sent; or `ELOXIV_TOKEN`), refreshed once when refused; each message the kernel answers (JSON or a server-sent event
1037
+ * stream) goes to standard output as one line. The session the kernel opens (`mcp-session-id`) is carried on every
1038
+ * later request and ended (`DELETE`) when standard input closes. Diagnostics go to standard error only.
1039
+ */
1040
+ export const mcpServe = (options: { readonly url: string | undefined }) =>
1041
+ Effect.gen(function* () {
1042
+ const url = yield* kernelUrl(options.url, yield* readCredentials)
1043
+ // Without an MCP grant nothing is read: the device flow cannot run here (standard output is the host's channel).
1044
+ yield* accessToken(url, undefined, "mcp")
1045
+ let session: string | undefined
1046
+ const post = (line: string) =>
1047
+ Effect.gen(function* () {
1048
+ const response = yield* authorized(
1049
+ url,
1050
+ "/mcp",
1051
+ {
1052
+ method: "POST",
1053
+ headers: {
1054
+ "content-type": "application/json",
1055
+ accept: "application/json, text/event-stream",
1056
+ ...(session === undefined ? {} : { "mcp-session-id": session }),
1057
+ },
1058
+ body: line,
1059
+ },
1060
+ true,
1061
+ "mcp",
1062
+ )
1063
+ session = response.headers.get("mcp-session-id") ?? session
1064
+ const type = response.headers.get("content-type") ?? ""
1065
+ if (response.status === 202 || response.body === null) return
1066
+ if (type.includes("text/event-stream")) {
1067
+ yield* Effect.tryPromise({
1068
+ try: async () => {
1069
+ const reader = response.body!.getReader()
1070
+ const decoder = new TextDecoder()
1071
+ let buffer = ""
1072
+ for (;;) {
1073
+ const { done, value } = await reader.read()
1074
+ if (done) break
1075
+ const blocks = (buffer + decoder.decode(value, { stream: true })).split(/\r?\n\r?\n/u)
1076
+ buffer = blocks.pop() ?? ""
1077
+ for (const block of blocks) {
1078
+ const data = block
1079
+ .split(/\r?\n/u)
1080
+ .filter((l) => l.startsWith("data:"))
1081
+ .map((l) => l.slice(5).trimStart())
1082
+ .join("\n")
1083
+ if (data !== "") process.stdout.write(`${data.replace(/\n/g, "")}\n`)
1084
+ }
1085
+ }
1086
+ },
1087
+ catch: (e) =>
1088
+ new CliError({ message: `Lost the kernel's answer: ${e instanceof Error ? e.message : String(e)}` }),
1089
+ })
1090
+ return
1091
+ }
1092
+ const text = yield* Effect.tryPromise({
1093
+ try: () => response.text(),
1094
+ catch: () => new CliError({ message: "Lost the kernel's answer" }),
1095
+ })
1096
+ if (response.ok && text.trim() !== "") process.stdout.write(`${text.trim().replace(/\n/g, "")}\n`)
1097
+ else if (!response.ok) {
1098
+ // The kernel refused the request itself (not a JSON-RPC error): answer the request's id so the host is not left waiting.
1099
+ const id = (() => {
1100
+ try {
1101
+ return (JSON.parse(line) as { id?: unknown }).id
1102
+ } catch {
1103
+ return undefined
1104
+ }
1105
+ })()
1106
+ process.stderr.write(
1107
+ `eloxiv mcp serve: the kernel answered ${response.status}${text === "" ? "" : `: ${text.slice(0, 300)}`}\n`,
1108
+ )
1109
+ if (id !== undefined) {
1110
+ process.stdout.write(
1111
+ `${JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32001, message: `The kernel answered ${response.status}` } })}\n`,
1112
+ )
1113
+ }
1114
+ }
1115
+ })
1116
+ // Lines queue as they arrive (readline emits a chunk's lines even while paused): none is lost while one is posted.
1117
+ const queue: Array<string | undefined> = []
1118
+ let waiting: ((line: string | undefined) => void) | undefined
1119
+ const push = (line: string | undefined) => {
1120
+ if (waiting === undefined) queue.push(line)
1121
+ else {
1122
+ const resolve = waiting
1123
+ waiting = undefined
1124
+ resolve(line)
1125
+ }
1126
+ }
1127
+ yield* Effect.tryPromise({
1128
+ try: async () => {
1129
+ const { createInterface } = await import("node:readline")
1130
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity })
1131
+ lines.on("line", (l) => push(l))
1132
+ lines.once("close", () => push(undefined))
1133
+ },
1134
+ catch: () => new CliError({ message: "Cannot read standard input" }),
1135
+ })
1136
+ for (;;) {
1137
+ const line = yield* Effect.promise(
1138
+ () =>
1139
+ new Promise<string | undefined>((resolve) =>
1140
+ queue.length > 0 ? resolve(queue.shift()) : (waiting = resolve),
1141
+ ),
1142
+ )
1143
+ if (line === undefined) break
1144
+ if (line.trim() === "") continue
1145
+ yield* post(line).pipe(
1146
+ Effect.catch((e) =>
1147
+ Effect.sync(() =>
1148
+ process.stderr.write(`eloxiv mcp serve: ${e instanceof CliError ? e.message : String(e)}\n`),
1149
+ ),
1150
+ ),
1151
+ )
1152
+ }
1153
+ if (session !== undefined) {
1154
+ yield* authorized(url, "/mcp", { method: "DELETE", headers: { "mcp-session-id": session } }, false, "mcp").pipe(
1155
+ Effect.ignore,
1156
+ )
1157
+ }
1158
+ })