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