even-keel 0.2.3 → 0.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/.claude-plugin/marketplace.json +12 -0
  2. package/CHANGELOG.md +12 -0
  3. package/README.md +5 -5
  4. package/dist/src/account/aws.js +76 -0
  5. package/dist/src/account/azure.js +36 -0
  6. package/dist/src/account/cloud-errors.js +72 -0
  7. package/dist/src/account/cloud.js +335 -0
  8. package/dist/src/account/credit.js +49 -7
  9. package/dist/src/account/gcloud.js +71 -0
  10. package/dist/src/account/homes.js +35 -1
  11. package/dist/src/account/keycheck.js +57 -4
  12. package/dist/src/account/management.js +41 -0
  13. package/dist/src/account/model.js +10 -2
  14. package/dist/src/account/network.js +8 -3
  15. package/dist/src/account/service-defaults.js +12 -3
  16. package/dist/src/account/share.js +12 -2
  17. package/dist/src/account/spend.js +155 -0
  18. package/dist/src/account/watcher.js +141 -18
  19. package/dist/src/agent/adapters.js +13 -2
  20. package/dist/src/agent/env.js +7 -0
  21. package/dist/src/agent/process.js +32 -6
  22. package/dist/src/agent/projectRules.js +3 -2
  23. package/dist/src/agent/scripted.js +305 -0
  24. package/dist/src/builtin/adapter.js +40 -0
  25. package/dist/src/builtin/control.js +165 -0
  26. package/dist/src/builtin/editor.js +69 -0
  27. package/dist/src/builtin/files.js +155 -0
  28. package/dist/src/builtin/links.js +25 -0
  29. package/dist/src/builtin/model.js +59 -0
  30. package/dist/src/builtin/routes.js +91 -0
  31. package/dist/src/builtin/source.js +239 -0
  32. package/dist/src/builtin/store.js +498 -0
  33. package/dist/src/chain/dispatcher.js +52 -8
  34. package/dist/src/chain/handover.js +21 -4
  35. package/dist/src/chain/launches.js +3 -3
  36. package/dist/src/chain/lists.js +10 -1
  37. package/dist/src/chain/log.js +3 -1
  38. package/dist/src/chain/maincheck.js +114 -10
  39. package/dist/src/chain/mainci.js +20 -4
  40. package/dist/src/chain/mainfix.js +12 -1
  41. package/dist/src/chain/milestone-sequence.js +40 -0
  42. package/dist/src/chain/milestones.js +3 -2
  43. package/dist/src/chain/order.js +20 -5
  44. package/dist/src/chain/prompts.js +14 -2
  45. package/dist/src/chain/relay.js +9 -3
  46. package/dist/src/chain/reviews.js +1 -1
  47. package/dist/src/chain/rules.js +2 -5
  48. package/dist/src/chain/snapshots.js +2 -0
  49. package/dist/src/chain/start.js +1 -1
  50. package/dist/src/chain/store.js +7 -0
  51. package/dist/src/ci/adapters.js +3 -1
  52. package/dist/src/ci/forgejo-profile.js +3 -24
  53. package/dist/src/ci/forgejo.js +2 -1
  54. package/dist/src/ci/github.js +10 -2
  55. package/dist/src/ci/gitlab.js +10 -3
  56. package/dist/src/ci/http.js +4 -0
  57. package/dist/src/ci/model.js +79 -6
  58. package/dist/src/ci/report.js +6 -3
  59. package/dist/src/ci/shared.js +9 -0
  60. package/dist/src/ci/verdict.js +18 -7
  61. package/dist/src/ci/watcher.js +95 -23
  62. package/dist/src/ci/wiring.js +15 -0
  63. package/dist/src/claude/adapter.js +26 -1
  64. package/dist/src/claude/cli.js +21 -3
  65. package/dist/src/claude/instructions.js +42 -7
  66. package/dist/src/claude/oauth.js +67 -0
  67. package/dist/src/claude/sdk/host.js +7 -4
  68. package/dist/src/codex/cli.js +24 -16
  69. package/dist/src/codex/turns.js +6 -3
  70. package/dist/src/codex/window.js +14 -0
  71. package/dist/src/config-form.js +29 -3
  72. package/dist/src/config-store.js +20 -6
  73. package/dist/src/config.js +18 -2
  74. package/dist/src/copilot/cli.js +5 -9
  75. package/dist/src/demo/agent.js +97 -0
  76. package/dist/src/demo/model.js +6 -0
  77. package/dist/src/demo/scenario.js +139 -0
  78. package/dist/src/demo/service.js +155 -0
  79. package/dist/src/event-log/log.js +96 -0
  80. package/dist/src/event-log/model.js +1 -0
  81. package/dist/src/event-log/page-events.js +66 -0
  82. package/dist/src/event-log/watch.js +236 -0
  83. package/dist/src/events.js +57 -1
  84. package/dist/src/forgejo/adapter.js +48 -0
  85. package/dist/src/forgejo/api.js +81 -0
  86. package/dist/src/forgejo/model.js +57 -0
  87. package/dist/src/forgejo/profile.js +24 -0
  88. package/dist/src/forgejo/source.js +242 -0
  89. package/dist/src/forgejo/trust.js +45 -0
  90. package/dist/src/git/branches.js +88 -0
  91. package/dist/src/jira/model.js +11 -4
  92. package/dist/src/jira/source.js +42 -7
  93. package/dist/src/limits/model.js +48 -3
  94. package/dist/src/limits/usage.js +60 -5
  95. package/dist/src/linear/model.js +11 -2
  96. package/dist/src/linear/source.js +5 -6
  97. package/dist/src/notice/en.js +156 -5
  98. package/dist/src/notice/kinds.js +26 -0
  99. package/dist/src/opencode/adapter.js +2 -2
  100. package/dist/src/opencode/cli.js +28 -21
  101. package/dist/src/opencode/home.js +7 -2
  102. package/dist/src/opencode/transcript.js +2 -1
  103. package/dist/src/opencode/window.js +54 -0
  104. package/dist/src/packages/gateway.js +40 -1
  105. package/dist/src/packages/launch.js +5 -2
  106. package/dist/src/packages/service.js +1 -1
  107. package/dist/src/profiles/control.js +1 -0
  108. package/dist/src/profiles/model.js +2 -2
  109. package/dist/src/profiles/service.js +46 -4
  110. package/dist/src/profiles/store.js +10 -5
  111. package/dist/src/projects/add.js +6 -1
  112. package/dist/src/projects/branch-control.js +86 -0
  113. package/dist/src/projects/branch-move.js +39 -0
  114. package/dist/src/projects/branch.js +13 -0
  115. package/dist/src/projects/check.js +16 -23
  116. package/dist/src/review/events.js +1 -1
  117. package/dist/src/review/wiring.js +19 -2
  118. package/dist/src/server-request.js +25 -4
  119. package/dist/src/server-response.js +140 -0
  120. package/dist/src/server.js +48 -110
  121. package/dist/src/service/accounts.js +105 -17
  122. package/dist/src/service/chain.js +66 -97
  123. package/dist/src/service/cleanup.js +105 -0
  124. package/dist/src/service/demo.js +45 -0
  125. package/dist/src/service/hosting.js +99 -10
  126. package/dist/src/service/stats.js +3 -3
  127. package/dist/src/service/trackers.js +3 -0
  128. package/dist/src/service.js +91 -9
  129. package/dist/src/sessions/ask.js +19 -3
  130. package/dist/src/sessions/boot.js +7 -0
  131. package/dist/src/sessions/chat.js +14 -3
  132. package/dist/src/sessions/keepwarm.js +1 -1
  133. package/dist/src/sessions/lingering.js +5 -5
  134. package/dist/src/sessions/monitor.js +16 -1
  135. package/dist/src/sessions/protection.js +10 -8
  136. package/dist/src/sessions/rare.js +130 -0
  137. package/dist/src/sessions/tail.js +4 -0
  138. package/dist/src/sessions/transcript.js +6 -2
  139. package/dist/src/settings/defaults.js +1 -0
  140. package/dist/src/settings/registry.js +39 -1
  141. package/dist/src/settings/store.js +14 -5
  142. package/dist/src/shown-work.js +22 -0
  143. package/dist/src/stats/base-sql.js +7 -1
  144. package/dist/src/stats/checkpoint.js +7 -4
  145. package/dist/src/stats/model.js +1 -1
  146. package/dist/src/stats/reader.js +41 -21
  147. package/dist/src/stats/rules-reader.js +4 -2
  148. package/dist/src/stats/tally-schema.js +1 -1
  149. package/dist/src/storage/copy.js +7 -3
  150. package/dist/src/storage/database.js +167 -1
  151. package/dist/src/storage/migrations.js +40 -1
  152. package/dist/src/storage/owner.js +2 -0
  153. package/dist/src/storage/schema.js +1 -1
  154. package/dist/src/taskmcp/args.js +95 -0
  155. package/dist/src/taskmcp/calls.js +346 -0
  156. package/dist/src/taskmcp/server.js +77 -0
  157. package/dist/src/taskmcp/tools.js +99 -0
  158. package/dist/src/tracker/adapters.js +3 -1
  159. package/dist/src/tracker/card.js +7 -5
  160. package/dist/src/tracker/closes.js +6 -0
  161. package/dist/src/tracker/control.js +21 -12
  162. package/dist/src/tracker/editor.js +55 -0
  163. package/dist/src/tracker/health.js +5 -0
  164. package/dist/src/tracker/link.js +40 -5
  165. package/dist/src/tracker/model.js +0 -2
  166. package/dist/src/tracker/questions.js +10 -3
  167. package/dist/src/tracker/readers.js +5 -3
  168. package/dist/src/tracker/source.js +4 -0
  169. package/dist/src/tracker/start.js +4 -1
  170. package/dist/src/tracker/trackers.js +20 -10
  171. package/dist/src/updates/updater.js +2 -2
  172. package/dist/tally/src/builtin-tasks.js +45 -0
  173. package/dist/tally/src/catalogue.js +70 -0
  174. package/dist/tally/src/classify.js +1 -0
  175. package/dist/tally/src/collect.js +27 -10
  176. package/dist/tally/src/copilot.js +1 -0
  177. package/dist/tally/src/db.js +53 -23
  178. package/dist/tally/src/migrations/10-rework-label.sql +73 -0
  179. package/dist/tally/src/migrations/11-catalogue-prices.sql +53 -0
  180. package/dist/tally/src/migrations/12-key-spends.sql +30 -0
  181. package/dist/tally/src/migrations.js +1 -1
  182. package/dist/tally/src/opencode.js +1 -0
  183. package/dist/tally/src/parse.js +3 -0
  184. package/dist/tally/src/rollout.js +2 -1
  185. package/dist/tally/src/rule-hook-size.js +2 -1
  186. package/dist/tally/src/rule-hook.js +3 -0
  187. package/dist/web/assets/ConfirmDialog-CT1w8fds.css +1 -0
  188. package/dist/web/assets/ConfirmDialog-DtrqXMLY.js +7 -0
  189. package/dist/web/assets/DescriptionEditor-D8PUeuQ6.js +216 -0
  190. package/dist/web/assets/Loader-D4ik19jr.css +1 -0
  191. package/dist/web/assets/Loader-mgoVDIvZ.js +12 -0
  192. package/dist/web/assets/ProjectPackages-DnCW8kXc.js +1 -0
  193. package/dist/web/assets/TaskCard-Bjnnsxah.js +3 -0
  194. package/dist/web/assets/TaskCard-f7aXQS6c.css +1 -0
  195. package/dist/web/assets/TranscriptWindow-BEAdgN2M.js +4 -0
  196. package/dist/web/assets/chatKeys-7ClMP73F.css +1 -0
  197. package/dist/web/assets/chatKeys-Doxn3auX.js +1 -0
  198. package/dist/web/assets/description-C-o9LBbp.css +1 -0
  199. package/dist/web/assets/feedLine-qIhoKONX.js +1 -0
  200. package/dist/web/assets/index-ernY0hZ5.css +1 -0
  201. package/dist/web/assets/index-srs3Jx9s.js +24 -0
  202. package/dist/web/assets/lib-DZ3lmyI6.js +18 -0
  203. package/dist/web/assets/overview-B_Cnubfu.css +1 -0
  204. package/dist/web/assets/overview-hxpvjWJS.js +1 -0
  205. package/dist/web/assets/packageGroups-DMT_PhT3.css +1 -0
  206. package/dist/web/assets/packageGroups-DWLFjsUs.js +8 -0
  207. package/dist/web/assets/state-DZUHccAT.css +1 -0
  208. package/dist/web/assets/state-ky_dNYYi.js +3 -0
  209. package/dist/web/assets/useFileDrop-4efYr2eq.js +1 -0
  210. package/dist/web/assets/useModels-1WRBMBb2.css +1 -0
  211. package/dist/web/assets/useModels-C_U0wgab.js +4 -0
  212. package/dist/web/assets/useRowFocus-BjMFkowJ.js +1 -0
  213. package/dist/web/assets/useRowFocus-BsvvWNh2.css +1 -0
  214. package/dist/web/index.html +18 -8
  215. package/even-keel.config.example.json +3 -1
  216. package/package.json +20 -4
  217. package/plugins/checkpoint/README.md +1 -1
  218. package/plugins/forgejo/.claude-plugin/plugin.json +7 -0
  219. package/plugins/forgejo/.mcp.json +13 -0
  220. package/plugins/forgejo/README.md +23 -0
  221. package/plugins/forgejo/skills/task/SKILL.md +55 -0
  222. package/plugins/huly/.claude-plugin/plugin.json +1 -1
  223. package/plugins/huly/skills/task/SKILL.md +1 -1
  224. package/plugins/jira/.claude-plugin/plugin.json +1 -1
  225. package/plugins/jira/skills/task/SKILL.md +1 -1
  226. package/plugins/linear/.claude-plugin/plugin.json +1 -1
  227. package/plugins/linear/skills/task/SKILL.md +1 -1
  228. package/plugins/tasks/.claude-plugin/plugin.json +9 -0
  229. package/plugins/tasks/.mcp.json +8 -0
  230. package/plugins/tasks/README.md +21 -0
  231. package/plugins/tasks/skills/split/SKILL.md +29 -0
  232. package/plugins/tasks/skills/task/SKILL.md +52 -0
  233. package/service/EvenKeelTray.cs +4 -20
  234. package/tally/tally.config.json +1 -0
  235. package/dist/web/assets/Loader-CRe-GCoI.js +0 -31
  236. package/dist/web/assets/Loader-DJJTBsaF.css +0 -1
  237. package/dist/web/assets/TaskCard-Br2QIllc.css +0 -1
  238. package/dist/web/assets/TaskCard-C2xeaHWD.js +0 -2
  239. package/dist/web/assets/TranscriptWindow-COL_WTrF.js +0 -4
  240. package/dist/web/assets/feedLine-D0lnFyBZ.js +0 -1
  241. package/dist/web/assets/index-DQje9Nfo.js +0 -25
  242. package/dist/web/assets/index-mDBlgk2Y.css +0 -1
  243. package/dist/web/assets/media-BlW-XXN0.js +0 -1
  244. package/dist/web/assets/media-DR8nAbPy.css +0 -1
  245. package/dist/web/assets/rolldown-runtime-XKyaHtl9.js +0 -1
  246. package/dist/web/assets/useModels-1oIk0mDX.css +0 -1
  247. package/dist/web/assets/useModels-DRW63oka.js +0 -15
@@ -36,6 +36,18 @@
36
36
  "source": "./plugins/jira",
37
37
  "category": "productivity"
38
38
  },
39
+ {
40
+ "name": "forgejo",
41
+ "description": "Forgejo Issues for Even Keel sessions, Gitea and Codeberg too: the official gitea-mcp server signed in with the profile's token and a skill to read the issue, record decisions, file blockers and questions, and close the issue by merging",
42
+ "source": "./plugins/forgejo",
43
+ "category": "productivity"
44
+ },
45
+ {
46
+ "name": "tasks",
47
+ "description": "Even Keel's built-in tracker for sessions: its own tasks server with five tools — list, read, create in batches, update with description patches, comment — and skills to work a task and split it into subtasks",
48
+ "source": "./plugins/tasks",
49
+ "category": "productivity"
50
+ },
39
51
  {
40
52
  "name": "checkpoint",
41
53
  "description": "Context checkpoints: once the context grows past a threshold, the session writes a handoff note and ends its turn with CHECKPOINT: <path>, and Even Keel continues the task in a fresh session; a chain session's merge waits for the project's check when no CI judges main",
package/CHANGELOG.md CHANGED
@@ -4,6 +4,18 @@ All notable changes to Even Keel are documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [Unreleased]
8
+
9
+ ### Changed
10
+
11
+ - **The main branch field offers the repository's branches, and saving another branch switches the main checkout to it**, in a project's settings and in the wizard that adds one: a branch the repository lacks is created from where the checkout stands, one only on a remote is taken from there, and the line under the field says which before you save. The wizard fills in the checkout's current branch and no longer refuses a branch the repository lacks. A checkout switched by hand is shown in the settings and on the chain's card, with buttons to make its branch the main one or to put the folder back, instead of only when a task fails to start.
12
+
13
+ ### Fixed
14
+
15
+ - **A project's lone `AGENTS.md` is no longer in a Claude session's context twice.** Claude Code reads the file by itself, so Even Keel stopped appending it to the system prompt; the same text reached every turn twice before.
16
+ - **A project's lone `AGENTS.md` reaches a Claude session again when a `CLAUDE.md` lies in a folder above the checkout**, such as `~/.claude/CLAUDE.md` for a checkout in your home folder. Claude Code skips the file then, so Even Keel appends it to the system prompt in that case only.
17
+ - The Forgejo plugin's `forgejo:task` skill loads again: its description is quoted, so the skill's frontmatter parses and chain sessions on Forgejo, Gitea and Codeberg projects get the skill (plugin 0.1.1). A test now parses the frontmatter of every bundled skill.
18
+
7
19
  ## [0.2.3] - 2026-11-07
8
20
 
9
21
  ### Fixed
package/README.md CHANGED
@@ -13,9 +13,9 @@
13
13
  - **A full context, your way.** A session past its context threshold writes a handoff note and a fresh one takes over in the same worktree — or leaves it to Claude Code's auto-compact, per project or per task by a [label](docs/guide/reference.md#configuration). The statistics count both, so you can compare what each cost on your own tasks.
14
14
  - **What each task cost.** Built-in statistics (optional): cost and time per task, where sessions got stuck, how full the context ran, and before/after every change to your rule files. A session audit skill reads them and proposes what to change in your rules.
15
15
  - **Every account on one page.** Claude, Codex, OpenCode and Copilot — subscriptions and API keys — each with its limits or spend and what runs on it right now. You pick the account a project runs on.
16
- - **`CLAUDE.md` or `AGENTS.md`.** One instruction file reaches every agent: Claude Code gets your `AGENTS.md`, Codex your `CLAUDE.md`.
16
+ - **`CLAUDE.md` or `AGENTS.md`.** One instruction file reaches every agent: Claude Code reads your `AGENTS.md` by itself, Codex your `CLAUDE.md`.
17
17
 
18
- It runs as a service on your own machine, next to your repositories, on your own subscription, through the unmodified `claude`, `codex`, `opencode` and `copilot` CLIs. Trackers out of the box: [Huly](https://huly.io), GitHub Issues, [Linear](https://linear.app), GitLab Issues (GitLab.com or your own server) and Jira Cloud.
18
+ It runs as a service on your own machine, next to your repositories, on your own subscription, through the unmodified `claude`, `codex`, `opencode` and `copilot` CLIs. Trackers out of the box: [Huly](https://huly.io), GitHub Issues, [Linear](https://linear.app), GitLab Issues (GitLab.com or your own server), Jira Cloud and Forgejo Issues (Forgejo, Gitea or Codeberg).
19
19
 
20
20
  ![A project's chain: one task done, one session working, the rest queued; the panel on the right shows the session's stage, context fill and current action](assets/screens/chain.png)
21
21
 
@@ -34,7 +34,7 @@ Even Keel wins in time, not in width: the agent keeps working while you are away
34
34
 
35
35
  ## What it does
36
36
 
37
- - **A chain per project**, ordered by blockers first, then the order you drag on the page, then milestone and priority. A task labelled `Manual` stays yours.
37
+ - **A chain per project**, ordered by blockers first, then the order you drag on the page, then milestone and priority. A task labelled `Manual` (or any label you exclude) stays yours.
38
38
  - **A session per task**, in its own git worktree. It does the task and merges; Even Keel closes the task and starts the next.
39
39
  - **Several trackers in one chain**, say the GitHub issues others file next to your private Huly project; or **several chains on one tracker project**, say fixes of a released version beside the next one.
40
40
  - **Unattended mode** for nights: a task that needs your answer is left on its branch with the question, and the chain moves on.
@@ -56,7 +56,7 @@ Every feature in full: [docs/guide/features.md](docs/guide/features.md).
56
56
  - **Node.js 24** or newer ([nodejs.org](https://nodejs.org/en/download); on Linux nvm needs no `sudo`).
57
57
  - **git** ([git-scm.com](https://git-scm.com/downloads)) with your name and e-mail set (`git config --global user.name` and `user.email`): sessions commit and merge under that name.
58
58
  - **An agent and an account of it:** [Claude Code](https://docs.claude.com/en/docs/claude-code/setup), [Codex](https://github.com/openai/codex), [OpenCode](https://opencode.ai) (preview) or [GitHub Copilot CLI](https://github.com/github/copilot-cli) (preview), on a subscription or an API key; OpenCode also runs its free models. The setup can download the CLI for you.
59
- - **A tracker:** a Huly workspace, GitHub or GitLab projects with Issues, a Linear workspace or a Jira Cloud site.
59
+ - **A tracker:** a Huly workspace, GitHub, GitLab or Forgejo projects with Issues, a Linear workspace or a Jira Cloud site.
60
60
  - **Windows, Linux or macOS.** Windows is where it runs every day; Linux and macOS (Apple silicon) were checked end to end. The MSI installer of Node can sit on "Preparing to install…" for over 10 minutes: wait it out.
61
61
 
62
62
  ## Before you run it
@@ -100,7 +100,7 @@ Its data — `.env`, the state and the logs — lives in `%LOCALAPPDATA%\even-ke
100
100
 
101
101
  Open `http://localhost:4747`. The first start walks a short setup — the languages, the agent and its account, a tracker profile, update checks, statistics — and then a wizard that adds a project: the agent, the repository folder, a tracker profile and the project in that tracker. What each tracker's token needs: [Token permissions](docs/guide/setup.md#token-permissions). For Claude Code the wizard also trusts the repository folder, unless you turn that off. Then press **Start** on the project: the chain takes its first task.
102
102
 
103
- To let sessions read the task themselves, file blockers and leave comments, add the tracker's plugin (`huly@even-keel` and the like) on `/tools` → **Add a package**. Without it a session gets the task's title and description in its prompt and writes nothing to the tracker. Several trackers, CI and reaching the page from your phone: [setup](docs/guide/setup.md).
103
+ To let sessions read the task themselves, file blockers and leave comments, add the tracker's plugin (`huly@even-keel` and the like) in **Settings → Packages** → **Add a package**. Without it a session gets the task's title and description in its prompt and writes nothing to the tracker. Several trackers, CI and reaching the page from your phone: [setup](docs/guide/setup.md).
104
104
 
105
105
  Running it from a clone, or a look at the page on fake data first: [From a clone](docs/guide/setup.md#from-a-clone).
106
106
 
@@ -0,0 +1,76 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { homedir, userInfo } from 'node:os';
3
+ import { join } from 'node:path';
4
+ /** The keys that make a profile's credentials expire within hours. */
5
+ const SHORT_LIVED_KEYS = ['sso_session', 'sso_start_url', 'login_session', 'aws_session_token'];
6
+ /** The AWS CLI's files where the SDK reads them: `AWS_CONFIG_FILE` and `AWS_SHARED_CREDENTIALS_FILE` move them. */
7
+ export function awsFiles(env) {
8
+ return {
9
+ config: env.AWS_CONFIG_FILE ?? join(homedir(), '.aws', 'config'),
10
+ credentials: env.AWS_SHARED_CREDENTIALS_FILE ?? join(homedir(), '.aws', 'credentials'),
11
+ };
12
+ }
13
+ export function readAwsProfiles(env) {
14
+ const files = awsFiles(env);
15
+ return { profiles: awsProfiles(readText(files.config), readText(files.credentials)), user: currentUser(), home: homedir() };
16
+ }
17
+ /**
18
+ * The named profiles of both files, `default` first, the rest by name. In `config` a profile is `[profile name]` (the
19
+ * default — `[default]`) and `[sso-session …]` is no profile; in `credentials` it is `[name]`.
20
+ */
21
+ export function awsProfiles(config, credentials) {
22
+ const merged = new Map();
23
+ const add = (name, keys) => merged.set(name, new Map([...(merged.get(name) ?? []), ...keys]));
24
+ for (const [section, keys] of parseIni(config)) {
25
+ const name = section === 'default' ? 'default' : /^profile\s+(.+)$/.exec(section)?.[1]?.trim();
26
+ if (name !== undefined && name !== '')
27
+ add(name, keys);
28
+ }
29
+ for (const [section, keys] of parseIni(credentials))
30
+ add(section, keys);
31
+ return [...merged]
32
+ .map(([name, keys]) => ({ name, region: keys.get('region') ?? null, shortLived: SHORT_LIVED_KEYS.some((key) => keys.has(key)) }))
33
+ .sort((a, b) => Number(b.name === 'default') - Number(a.name === 'default') || a.name.localeCompare(b.name));
34
+ }
35
+ /** Whether the named profile's credentials expire within hours; false for one not found. */
36
+ export function shortLivedProfile(env, name) {
37
+ const files = awsFiles(env);
38
+ return awsProfiles(readText(files.config), readText(files.credentials)).find((profile) => profile.name === name)?.shortLived ?? false;
39
+ }
40
+ function parseIni(text) {
41
+ const sections = new Map();
42
+ let current = null;
43
+ for (const raw of text.split(/\r?\n/)) {
44
+ const line = raw.trim();
45
+ if (line === '' || line.startsWith('#') || line.startsWith(';'))
46
+ continue;
47
+ const head = /^\[([^\]]+)\]$/.exec(line);
48
+ if (head !== null) {
49
+ const name = head[1].trim();
50
+ current = sections.get(name) ?? new Map();
51
+ sections.set(name, current);
52
+ continue;
53
+ }
54
+ const pair = /^([^=]+?)\s*=\s*(.*)$/.exec(line);
55
+ if (pair !== null && current !== null && !/^\s/.test(raw))
56
+ current.set(pair[1].toLowerCase(), pair[2]);
57
+ }
58
+ return sections;
59
+ }
60
+ function readText(file) {
61
+ try {
62
+ return readFileSync(file, 'utf8');
63
+ }
64
+ catch {
65
+ return '';
66
+ }
67
+ }
68
+ /** The account Even Keel runs as: the one whose home holds `~/.aws`. */
69
+ export function currentUser() {
70
+ try {
71
+ return userInfo().username;
72
+ }
73
+ catch {
74
+ return '';
75
+ }
76
+ }
@@ -0,0 +1,36 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { currentUser } from './aws.js';
5
+ /** The Azure CLI's folder, where `az login` leaves the profile: `AZURE_CONFIG_DIR` moves it. */
6
+ export function azureDir(env) {
7
+ if (env.AZURE_CONFIG_DIR !== undefined && env.AZURE_CONFIG_DIR !== '')
8
+ return env.AZURE_CONFIG_DIR;
9
+ return join(homedir(), '.azure');
10
+ }
11
+ /**
12
+ * The Azure sign-in of the user Even Keel runs as, for the Foundry form's Entra ID way (BTN-824). The Azure SDK's chain
13
+ * the CLI uses tries a service principal of the environment before `az login`, so both are told.
14
+ */
15
+ export function readAzure(env) {
16
+ const profileFile = join(azureDir(env), 'azureProfile.json');
17
+ const secret = env.AZURE_CLIENT_SECRET || env.AZURE_CLIENT_CERTIFICATE_PATH || env.AZURE_FEDERATED_TOKEN_FILE;
18
+ return {
19
+ user: currentUser(),
20
+ home: homedir(),
21
+ profileFile,
22
+ signedIn: subscriptions(profileFile) > 0,
23
+ environment: Boolean(env.AZURE_CLIENT_ID && env.AZURE_TENANT_ID && secret),
24
+ };
25
+ }
26
+ /** The subscriptions of the profile; the Azure CLI writes it with a byte order mark on Windows. */
27
+ function subscriptions(file) {
28
+ try {
29
+ const value = JSON.parse(readFileSync(file, 'utf8').replace(/^/, ''));
30
+ const list = typeof value === 'object' && value !== null ? value.subscriptions : undefined;
31
+ return Array.isArray(list) ? list.length : 0;
32
+ }
33
+ catch {
34
+ return 0;
35
+ }
36
+ }
@@ -0,0 +1,72 @@
1
+ import { notice } from '../notice/notice.js';
2
+ const NOBODY = { user: '', home: '' };
3
+ /**
4
+ * Bedrock's refusals as the CLI words them (its own table of `refused`, `denied` and `credential` in 2.1.319) and as AWS
5
+ * answers, first match wins: a payment refusal also says access is denied, and a credential timeout is a credential error.
6
+ */
7
+ const BEDROCK_ERRORS = [
8
+ [/INVALID_PAYMENT_INSTRUMENT|valid payment instrument/i, () => notice('cloud.bedrockPayment', {})],
9
+ [/default-chain credential resolve timed out/i, (whose) => notice('cloud.awsTimeout', whose)],
10
+ [
11
+ /Could not load credentials|No AWS credentials found|ExpiredToken|InvalidSignature|SignatureDoesNotMatch|UnrecognizedClient|InvalidClientTokenId|security token.*(invalid|expired)|SSO session.*expired|Token has expired|profile .* could not be found|CredentialsProviderError/i,
12
+ (whose) => notice('cloud.awsCredentials', whose),
13
+ ],
14
+ [/on-demand throughput|provided model identifier is invalid/i, () => notice('cloud.bedrockRegion', {})],
15
+ [
16
+ /you don't have access to the model|anthropic\.\S+ is not available for this account|marketplace subscription for this model cannot be completed|is not authorized to perform: bedrock:InvokeModel|AccessDeniedException/i,
17
+ () => notice('cloud.bedrockModelDenied', {}),
18
+ ],
19
+ [/ThrottlingException|TooManyRequestsException|Too many (requests|tokens), please wait/i, () => notice('cloud.throttled', {})],
20
+ ];
21
+ /**
22
+ * Vertex AI's refusals (BTN-823): Google's auth library as the CLI's own Vertex wizard reads it in 2.1.319, and Google
23
+ * Cloud's error bodies. Billing goes before the disabled API, which a project without billing may also report. Every
24
+ * pattern names Google's own words, so an `invalid_grant` or a 404 of Anthropic's API is left alone.
25
+ */
26
+ const VERTEX_ERRORS = [
27
+ [
28
+ /Could not load the default credentials|does not exist, or it is not a file|The incoming JSON object does not|Must pass in a JSON object containing|invalid_rapt|reauth related error|Token has been expired or revoked|Timed out waiting for GCP credentials|Unable to detect a Project Id/i,
29
+ (whose) => notice('cloud.gcpCredentials', whose),
30
+ ],
31
+ [/BILLING_DISABLED|requires billing to be enabled/i, () => notice('cloud.vertexBilling', {})],
32
+ [/SERVICE_DISABLED|has not been used in project \S+ before or it is disabled/i, () => notice('cloud.vertexApi', {})],
33
+ [/Publisher Model .*(not found|does not have access)/i, () => notice('cloud.vertexModel', {})],
34
+ [/Quota exceeded for aiplatform\.googleapis\.com|RESOURCE_EXHAUSTED/i, () => notice('cloud.vertexQuota', {})],
35
+ [/Permission '?aiplatform\.\S+'? denied/i, () => notice('cloud.vertexPermission', {})],
36
+ ];
37
+ /**
38
+ * Microsoft Foundry's refusals (BTN-824): the Azure SDK's chain and the CLI's own Foundry wording in 2.1.319, and Azure's
39
+ * error bodies. Every pattern names Azure's or the CLI's Foundry words, never a bare 401, 404 or 429.
40
+ */
41
+ const FOUNDRY_ERRORS = [
42
+ [
43
+ /Failed to get token from azureADTokenProvider|ChainedTokenCredential authentication failed|CredentialUnavailableError|Please run 'az login'/i,
44
+ (whose) => notice('cloud.azureCredentials', whose),
45
+ ],
46
+ [/DeploymentNotFound|The API deployment for this resource does not exist/i, () => notice('cloud.foundryDeployment', {})],
47
+ [
48
+ /MarketplacePurchaseEligibilityFailed|marketplace (offer|purchase|subscription).*(not eligible|failed|not available)|subscription is not (eligible|supported) for|not available (for|in) (this|your) (Azure )?subscription/i,
49
+ () => notice('cloud.foundrySubscription', {}),
50
+ ],
51
+ [
52
+ /refresh your Foundry credential|Access denied due to invalid subscription key|Access token is missing, invalid, audience is incorrect|lacks the required data action/i,
53
+ () => notice('cloud.foundryRefused', {}),
54
+ ],
55
+ [/RateLimitReached|have exceeded (the )?(token|call) rate limit/i, () => notice('cloud.foundryThrottled', {})],
56
+ ];
57
+ /**
58
+ * The first message of a Foundry account that cannot reach its resource: the CLI retries the connection and gives up.
59
+ * Only a Foundry account's check reads it so: the words are the same for any host.
60
+ */
61
+ const FOUNDRY_UNREACHABLE = /Connection error|ENOTFOUND|EAI_AGAIN|getaddrinfo|ECONNREFUSED|Unable to connect to API/i;
62
+ const CLOUD_ERRORS = [...FOUNDRY_ERRORS, ...VERTEX_ERRORS, ...BEDROCK_ERRORS];
63
+ /**
64
+ * What a cloud refusal means and what to do, by the error's text; undefined for any other error. `cloud` is the
65
+ * account's cloud where it is known, as at the check of a new account, for the errors only that cloud words so.
66
+ */
67
+ export function cloudErrorNotice(text, whose = NOBODY, cloud) {
68
+ const known = CLOUD_ERRORS.find(([pattern]) => pattern.test(text))?.[1](whose);
69
+ if (known === undefined && cloud === 'foundry' && FOUNDRY_UNREACHABLE.test(text))
70
+ return notice('cloud.foundryUnreachable', {});
71
+ return known;
72
+ }
@@ -0,0 +1,335 @@
1
+ import { fail } from '../notice/notice.js';
2
+ /**
3
+ * A Claude account on a cloud (BTN-822): the CLI reaches the models through the cloud's own API, paid by the cloud's
4
+ * bill. Every cloud is one of `CLOUDS`; only the ones of `CLOUDS_READY` can be added.
5
+ * Its whole connection is the `env` of the folder's `settings.json`, the way an API account holds its key.
6
+ */
7
+ export const CLOUDS = ['bedrock', 'vertex', 'foundry'];
8
+ export const CLOUDS_READY = ['bedrock', 'vertex', 'foundry'];
9
+ /** How a Bedrock account finds its AWS credentials. */
10
+ export const BEDROCK_WAYS = ['profile', 'apiKey', 'keys', 'environment'];
11
+ /**
12
+ * How a Vertex account finds its Google Cloud credentials (BTN-823): the ADC file `gcloud auth application-default
13
+ * login` leaves, a key file (a service account's, or a Workload Identity Federation config), or the service's own.
14
+ */
15
+ export const VERTEX_WAYS = ['adc', 'keyFile', 'environment'];
16
+ /**
17
+ * How a Foundry account signs in (BTN-824): an API key of the resource, Microsoft Entra ID through the Azure SDK's
18
+ * chain (`az login` of the service's user, its environment, the machine's identity), or a Bearer token of about an hour.
19
+ */
20
+ export const FOUNDRY_WAYS = ['apiKey', 'entra', 'token'];
21
+ export const CLOUD_WAYS = { bedrock: BEDROCK_WAYS, vertex: VERTEX_WAYS, foundry: FOUNDRY_WAYS };
22
+ /**
23
+ * The models the CLI gives a region variable of their own, by model id prefix, as in 2.1.319. Only the form's choices:
24
+ * the account takes any `VERTEX_REGION_CLAUDE_*`, so a newer model's variable works before this list knows it.
25
+ */
26
+ export const VERTEX_REGION_MODELS = [
27
+ ['claude-fable-5-1', 'VERTEX_REGION_CLAUDE_FABLE_5_1'],
28
+ ['claude-fable-5', 'VERTEX_REGION_CLAUDE_FABLE_5'],
29
+ ['claude-opus-5-5', 'VERTEX_REGION_CLAUDE_5_5_OPUS'],
30
+ ['claude-sonnet-5-5', 'VERTEX_REGION_CLAUDE_5_5_SONNET'],
31
+ ['claude-haiku-5-5', 'VERTEX_REGION_CLAUDE_HAIKU_5_5'],
32
+ ['claude-opus-5', 'VERTEX_REGION_CLAUDE_5_OPUS'],
33
+ ['claude-sonnet-5', 'VERTEX_REGION_CLAUDE_5_SONNET'],
34
+ ['claude-opus-4-8', 'VERTEX_REGION_CLAUDE_4_8_OPUS'],
35
+ ['claude-opus-4-7', 'VERTEX_REGION_CLAUDE_4_7_OPUS'],
36
+ ['claude-opus-4-6', 'VERTEX_REGION_CLAUDE_4_6_OPUS'],
37
+ ['claude-sonnet-4-6', 'VERTEX_REGION_CLAUDE_4_6_SONNET'],
38
+ ['claude-opus-4-5', 'VERTEX_REGION_CLAUDE_4_5_OPUS'],
39
+ ['claude-sonnet-4-5', 'VERTEX_REGION_CLAUDE_4_5_SONNET'],
40
+ ['claude-haiku-4-5', 'VERTEX_REGION_CLAUDE_HAIKU_4_5'],
41
+ ['claude-opus-4-1', 'VERTEX_REGION_CLAUDE_4_1_OPUS'],
42
+ ['claude-opus-4', 'VERTEX_REGION_CLAUDE_4_0_OPUS'],
43
+ ['claude-sonnet-4', 'VERTEX_REGION_CLAUDE_4_0_SONNET'],
44
+ ['claude-3-7-sonnet', 'VERTEX_REGION_CLAUDE_3_7_SONNET'],
45
+ ['claude-3-5-sonnet', 'VERTEX_REGION_CLAUDE_3_5_SONNET'],
46
+ ['claude-3-5-haiku', 'VERTEX_REGION_CLAUDE_3_5_HAIKU'],
47
+ ];
48
+ export const BEDROCK_SWITCH = 'CLAUDE_CODE_USE_BEDROCK';
49
+ export const VERTEX_SWITCH = 'CLAUDE_CODE_USE_VERTEX';
50
+ const MODEL_VARIABLES = { opus: 'ANTHROPIC_DEFAULT_OPUS_MODEL', sonnet: 'ANTHROPIC_DEFAULT_SONNET_MODEL', haiku: 'ANTHROPIC_DEFAULT_HAIKU_MODEL' };
51
+ const FAMILIES = ['opus', 'sonnet', 'haiku'];
52
+ const BEDROCK_VARIABLES = {
53
+ region: 'AWS_REGION',
54
+ profile: 'AWS_PROFILE',
55
+ apiKey: 'AWS_BEARER_TOKEN_BEDROCK',
56
+ accessKeyId: 'AWS_ACCESS_KEY_ID',
57
+ secretAccessKey: 'AWS_SECRET_ACCESS_KEY',
58
+ sessionToken: 'AWS_SESSION_TOKEN',
59
+ regionPrefix: 'ANTHROPIC_BEDROCK_REGION_PREFIX',
60
+ };
61
+ const VERTEX_VARIABLES = { projectId: 'ANTHROPIC_VERTEX_PROJECT_ID', region: 'CLOUD_ML_REGION', keyFile: 'GOOGLE_APPLICATION_CREDENTIALS' };
62
+ const MODEL_REGION = /^VERTEX_REGION_CLAUDE_[A-Z0-9_]+$/;
63
+ export const FOUNDRY_SWITCH = 'CLAUDE_CODE_USE_FOUNDRY';
64
+ const FOUNDRY_VARIABLES = {
65
+ resource: 'ANTHROPIC_FOUNDRY_RESOURCE',
66
+ baseUrl: 'ANTHROPIC_FOUNDRY_BASE_URL',
67
+ apiKey: 'ANTHROPIC_FOUNDRY_API_KEY',
68
+ token: 'ANTHROPIC_FOUNDRY_AUTH_TOKEN',
69
+ };
70
+ const CLOUD_VARIABLES = [
71
+ BEDROCK_SWITCH,
72
+ VERTEX_SWITCH,
73
+ FOUNDRY_SWITCH,
74
+ ...Object.values(BEDROCK_VARIABLES),
75
+ ...Object.values(VERTEX_VARIABLES),
76
+ ...Object.values(FOUNDRY_VARIABLES),
77
+ ...Object.values(MODEL_VARIABLES),
78
+ ];
79
+ /** A resource name as the CLI takes it in 2.1.319: 2–64 letters, digits and hyphens, no hyphen at either end. */
80
+ const FOUNDRY_RESOURCE = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])$/i;
81
+ /** The hosts the CLI counts as Foundry's own in 2.1.319; another one it treats as a gateway and may refuse. */
82
+ const FOUNDRY_HOST = /^[a-z0-9-]{2,64}\.(?:services\.ai|cognitiveservices|openai)\.azure\.(?:com|us|cn)$/;
83
+ /**
84
+ * The Foundry field's value as the CLI takes it: a bare resource name, or a full `https://…/anthropic` address of a
85
+ * Foundry host. One field takes both, since the portal shows the address and the CLI refuses it as a name.
86
+ */
87
+ export function foundryEndpointOf(value) {
88
+ const given = value.trim();
89
+ if (FOUNDRY_RESOURCE.test(given))
90
+ return { resource: given };
91
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(given))
92
+ return { problem: /[./:]/.test(given) ? 'host' : 'name' };
93
+ let url;
94
+ try {
95
+ url = new URL(given);
96
+ }
97
+ catch {
98
+ return { problem: 'name' };
99
+ }
100
+ if (url.protocol !== 'https:')
101
+ return { problem: 'http' };
102
+ if (!FOUNDRY_HOST.test(url.hostname))
103
+ return { problem: 'foreign' };
104
+ if (url.pathname.replace(/\/+$/, '') !== '/anthropic' || url.search !== '' || url.hash !== '')
105
+ return { problem: 'path' };
106
+ return { baseUrl: `${url.origin}/anthropic` };
107
+ }
108
+ /**
109
+ * A variable a cloud folder may hold. The transfer of the shared configuration takes them from the folder only, so
110
+ * a model pinned in `~/.claude` for Anthropic's API does not reach a cloud that names its models otherwise.
111
+ */
112
+ export function isCloudVariable(name) {
113
+ return CLOUD_VARIABLES.includes(name) || MODEL_REGION.test(name);
114
+ }
115
+ /** A short-term Bedrock API key is a presigned URL and lives up to 12 hours; a long-term one starts with `ABSK`. */
116
+ const SHORT_BEDROCK_KEY = /^bedrock-api-key-/;
117
+ export function shortBedrockKey(key) {
118
+ return SHORT_BEDROCK_KEY.test(key.trim());
119
+ }
120
+ /** The `env` the folder's `settings.json` gets: only what is set, so the CLI's own order fills the rest. */
121
+ export function cloudEnv(connection) {
122
+ const env = {};
123
+ const set = (name, value) => {
124
+ if (value !== undefined && value !== '')
125
+ env[name] = value;
126
+ };
127
+ if (connection.cloud === 'foundry') {
128
+ env[FOUNDRY_SWITCH] = '1';
129
+ const { endpoint, auth } = connection;
130
+ if ('resource' in endpoint)
131
+ set(FOUNDRY_VARIABLES.resource, endpoint.resource);
132
+ else
133
+ set(FOUNDRY_VARIABLES.baseUrl, endpoint.baseUrl);
134
+ if (auth.way === 'apiKey')
135
+ set(FOUNDRY_VARIABLES.apiKey, auth.key);
136
+ if (auth.way === 'token')
137
+ set(FOUNDRY_VARIABLES.token, auth.token);
138
+ for (const family of FAMILIES)
139
+ set(MODEL_VARIABLES[family], connection.models[family]);
140
+ return env;
141
+ }
142
+ if (connection.cloud === 'vertex') {
143
+ env[VERTEX_SWITCH] = '1';
144
+ set(VERTEX_VARIABLES.projectId, connection.projectId);
145
+ set(VERTEX_VARIABLES.region, connection.region);
146
+ if (connection.auth.way === 'keyFile')
147
+ set(VERTEX_VARIABLES.keyFile, connection.auth.keyFile);
148
+ for (const family of FAMILIES)
149
+ set(MODEL_VARIABLES[family], connection.models?.[family]);
150
+ for (const [variable, region] of Object.entries(connection.modelRegions ?? {}))
151
+ set(variable, region);
152
+ return env;
153
+ }
154
+ env[BEDROCK_SWITCH] = '1';
155
+ set(BEDROCK_VARIABLES.region, connection.region);
156
+ const { auth } = connection;
157
+ if (auth.way === 'profile')
158
+ set(BEDROCK_VARIABLES.profile, auth.profile);
159
+ if (auth.way === 'apiKey')
160
+ set(BEDROCK_VARIABLES.apiKey, auth.key);
161
+ if (auth.way === 'keys') {
162
+ set(BEDROCK_VARIABLES.accessKeyId, auth.accessKeyId);
163
+ set(BEDROCK_VARIABLES.secretAccessKey, auth.secretAccessKey);
164
+ set(BEDROCK_VARIABLES.sessionToken, auth.sessionToken);
165
+ }
166
+ for (const family of FAMILIES)
167
+ set(MODEL_VARIABLES[family], connection.models?.[family]);
168
+ set(BEDROCK_VARIABLES.regionPrefix, connection.regionPrefix);
169
+ return env;
170
+ }
171
+ /**
172
+ * The cloud a folder's `settings.json` `env` connects to; null for one on a subscription or a key. What is not in the
173
+ * env is asked: `shortLivedProfile` tells an AWS profile's expiry from `~/.aws`, `userCredentials` whether the Google
174
+ * credentials file in effect — the key file, or for null the service's own — holds a user's sign-in.
175
+ */
176
+ export function cloudOf(env, shortLivedProfile = () => false, userCredentials = () => false) {
177
+ const text = (name) => (typeof env[name] === 'string' && env[name] !== '' ? env[name] : undefined);
178
+ const models = {};
179
+ for (const family of FAMILIES) {
180
+ const model = text(MODEL_VARIABLES[family]);
181
+ if (model !== undefined)
182
+ models[family] = model;
183
+ }
184
+ if (truthy(env[BEDROCK_SWITCH])) {
185
+ const profile = text(BEDROCK_VARIABLES.profile);
186
+ const key = text(BEDROCK_VARIABLES.apiKey);
187
+ const way = key !== undefined ? 'apiKey' : text(BEDROCK_VARIABLES.accessKeyId) !== undefined ? 'keys' : profile !== undefined ? 'profile' : 'environment';
188
+ const shortLived = way === 'apiKey' ? SHORT_BEDROCK_KEY.test(key) : way === 'keys' ? text(BEDROCK_VARIABLES.sessionToken) !== undefined : way === 'profile' && shortLivedProfile(profile);
189
+ return { cloud: 'bedrock', region: text(BEDROCK_VARIABLES.region) ?? null, way, ...(way === 'profile' && { profile }), models, shortLived };
190
+ }
191
+ if (truthy(env[VERTEX_SWITCH])) {
192
+ // ADC and the service's environment write the same env, as the CLI's own wizard does: only a key file tells.
193
+ const keyFile = text(VERTEX_VARIABLES.keyFile);
194
+ const project = text(VERTEX_VARIABLES.projectId);
195
+ return {
196
+ cloud: 'vertex',
197
+ region: text(VERTEX_VARIABLES.region) ?? null,
198
+ way: keyFile !== undefined ? 'keyFile' : 'adc',
199
+ ...(project !== undefined && { project }),
200
+ models,
201
+ shortLived: userCredentials(keyFile ?? null),
202
+ };
203
+ }
204
+ if (truthy(env[FOUNDRY_SWITCH])) {
205
+ // The CLI's own order: a token, then a key, then the Azure SDK's chain.
206
+ const way = text(FOUNDRY_VARIABLES.token) !== undefined ? 'token' : text(FOUNDRY_VARIABLES.apiKey) !== undefined ? 'apiKey' : 'entra';
207
+ const baseUrl = text(FOUNDRY_VARIABLES.baseUrl);
208
+ let resource = text(FOUNDRY_VARIABLES.resource);
209
+ if (baseUrl !== undefined) {
210
+ try {
211
+ resource = new URL(baseUrl).hostname;
212
+ }
213
+ catch {
214
+ resource = baseUrl;
215
+ }
216
+ }
217
+ return { cloud: 'foundry', region: null, way, ...(resource !== undefined && { resource }), models, shortLived: way === 'token' };
218
+ }
219
+ return null;
220
+ }
221
+ /** The CLI reads a switch as on for `1` or `true`, in any case. */
222
+ function truthy(value) {
223
+ return typeof value === 'string' && ['1', 'true'].includes(value.trim().toLowerCase());
224
+ }
225
+ const text = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
226
+ /** A one-word field the request must hold; one with a space inside is a pasted value with a line break in it. */
227
+ function need(value, field) {
228
+ const given = text(value);
229
+ if (given === undefined)
230
+ throw fail('request.required', { field });
231
+ if (/\s/.test(given))
232
+ throw fail('account.cloudFieldInvalid', { field });
233
+ return given;
234
+ }
235
+ /** A one-word field the request may hold; undefined when blank. */
236
+ function may(value, field) {
237
+ return text(value) === undefined ? undefined : need(value, field);
238
+ }
239
+ function modelsOf(body) {
240
+ const models = {};
241
+ const given = typeof body.models === 'object' && body.models !== null ? body.models : {};
242
+ for (const family of FAMILIES) {
243
+ const model = may(given[family], family);
244
+ if (model !== undefined)
245
+ models[family] = model;
246
+ }
247
+ return Object.keys(models).length > 0 ? models : undefined;
248
+ }
249
+ /** A request's connection, trimmed; a missing field the way needs is refused naming it. */
250
+ export function cloudConnectionOf(body) {
251
+ const cloud = body.cloud;
252
+ if (!CLOUDS.includes(cloud))
253
+ throw fail('request.required', { field: 'cloud' });
254
+ if (!CLOUDS_READY.includes(cloud))
255
+ throw fail('account.cloudNotReady', { cloud: String(cloud) });
256
+ return cloud === 'vertex' ? vertexConnectionOf(body) : cloud === 'foundry' ? foundryConnectionOf(body) : bedrockConnectionOf(body);
257
+ }
258
+ function foundryConnectionOf(body) {
259
+ const way = body.way;
260
+ if (!FOUNDRY_WAYS.includes(way))
261
+ throw fail('request.required', { field: 'way' });
262
+ const given = text(body.resource);
263
+ if (given === undefined)
264
+ throw fail('request.required', { field: 'resource' });
265
+ const endpoint = foundryEndpointOf(given);
266
+ if ('problem' in endpoint)
267
+ throw fail('account.foundryEndpoint', {});
268
+ const auth = way === 'apiKey' ? { way, key: need(body.key, 'key') } : way === 'token' ? { way, token: need(body.token, 'token') } : { way: 'entra' };
269
+ const models = modelsOf(body);
270
+ if (models === undefined)
271
+ throw fail('account.foundryModels', {});
272
+ return { cloud: 'foundry', endpoint, auth, models };
273
+ }
274
+ function bedrockConnectionOf(body) {
275
+ const way = body.way;
276
+ if (!BEDROCK_WAYS.includes(way))
277
+ throw fail('request.required', { field: 'way' });
278
+ const auth = way === 'profile'
279
+ ? { way, profile: need(body.profile, 'profile') }
280
+ : way === 'apiKey'
281
+ ? { way, key: need(body.key, 'key') }
282
+ : way === 'keys'
283
+ ? {
284
+ way,
285
+ accessKeyId: need(body.accessKeyId, 'accessKeyId'),
286
+ secretAccessKey: need(body.secretAccessKey, 'secretAccessKey'),
287
+ ...(text(body.sessionToken) !== undefined && { sessionToken: need(body.sessionToken, 'sessionToken') }),
288
+ }
289
+ : { way: 'environment' };
290
+ const models = modelsOf(body);
291
+ const region = may(body.region, 'region');
292
+ const regionPrefix = may(body.regionPrefix, 'regionPrefix');
293
+ return {
294
+ cloud: 'bedrock',
295
+ ...(region !== undefined && { region }),
296
+ auth,
297
+ ...(models !== undefined && { models }),
298
+ ...(regionPrefix !== undefined && { regionPrefix }),
299
+ };
300
+ }
301
+ function vertexConnectionOf(body) {
302
+ const way = body.way;
303
+ if (!VERTEX_WAYS.includes(way))
304
+ throw fail('request.required', { field: 'way' });
305
+ const projectId = need(body.projectId, 'projectId');
306
+ let auth = { way: way === 'adc' ? 'adc' : 'environment' };
307
+ if (way === 'keyFile') {
308
+ // A path may hold spaces (`C:\Users\John Doe\…`), never a line break.
309
+ const keyFile = text(body.keyFile);
310
+ if (keyFile === undefined)
311
+ throw fail('request.required', { field: 'keyFile' });
312
+ if (/[\r\n]/.test(keyFile))
313
+ throw fail('account.cloudFieldInvalid', { field: 'keyFile' });
314
+ auth = { way, keyFile };
315
+ }
316
+ const regions = {};
317
+ const given = typeof body.modelRegions === 'object' && body.modelRegions !== null ? body.modelRegions : {};
318
+ for (const [variable, value] of Object.entries(given)) {
319
+ if (!MODEL_REGION.test(variable))
320
+ throw fail('account.cloudFieldInvalid', { field: variable });
321
+ const region = may(value, variable);
322
+ if (region !== undefined)
323
+ regions[variable] = region;
324
+ }
325
+ const models = modelsOf(body);
326
+ const region = may(body.region, 'region');
327
+ return {
328
+ cloud: 'vertex',
329
+ projectId,
330
+ ...(region !== undefined && { region }),
331
+ auth,
332
+ ...(models !== undefined && { models }),
333
+ ...(Object.keys(regions).length > 0 && { modelRegions: regions }),
334
+ };
335
+ }