@octen.ai/cli 0.7.0 → 0.9.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 (52) hide show
  1. package/README.md +325 -4
  2. package/dist/api/chat.d.ts +4 -1
  3. package/dist/api/client.d.ts +25 -1
  4. package/dist/api/client.js +144 -17
  5. package/dist/api/errors.d.ts +27 -0
  6. package/dist/api/errors.js +52 -0
  7. package/dist/api/search.js +5 -2
  8. package/dist/api/sse.d.ts +15 -3
  9. package/dist/api/sse.js +131 -36
  10. package/dist/auth/constants.d.ts +47 -0
  11. package/dist/auth/constants.js +89 -0
  12. package/dist/auth/exchange.d.ts +74 -0
  13. package/dist/auth/exchange.js +124 -0
  14. package/dist/auth/login.d.ts +64 -0
  15. package/dist/auth/login.js +163 -0
  16. package/dist/auth/loopback.d.ts +32 -0
  17. package/dist/auth/loopback.js +95 -0
  18. package/dist/auth/oauthClient.d.ts +70 -0
  19. package/dist/auth/oauthClient.js +136 -0
  20. package/dist/auth/pkce.d.ts +6 -0
  21. package/dist/auth/pkce.js +13 -0
  22. package/dist/auth/revoke.d.ts +58 -0
  23. package/dist/auth/revoke.js +91 -0
  24. package/dist/auth/store.d.ts +34 -0
  25. package/dist/auth/store.js +149 -0
  26. package/dist/cli.js +6 -0
  27. package/dist/commands/broadSearch.js +6 -6
  28. package/dist/commands/chat.js +12 -8
  29. package/dist/commands/configureMcp.js +38 -20
  30. package/dist/commands/configureSkills.js +25 -10
  31. package/dist/commands/imageSearch.js +3 -3
  32. package/dist/commands/login.d.ts +49 -0
  33. package/dist/commands/login.js +161 -0
  34. package/dist/commands/logout.d.ts +46 -0
  35. package/dist/commands/logout.js +142 -0
  36. package/dist/commands/reset.js +43 -5
  37. package/dist/commands/search.js +6 -6
  38. package/dist/commands/utils.d.ts +21 -2
  39. package/dist/commands/utils.js +43 -6
  40. package/dist/commands/whoami.d.ts +27 -0
  41. package/dist/commands/whoami.js +109 -0
  42. package/dist/config/resolve.d.ts +44 -1
  43. package/dist/config/resolve.js +80 -5
  44. package/dist/mcp/clients.js +7 -3
  45. package/dist/mcp/install.js +15 -2
  46. package/dist/mcp/write.js +24 -3
  47. package/dist/output/pretty/whoami.d.ts +59 -0
  48. package/dist/output/pretty/whoami.js +103 -0
  49. package/dist/skills/setkey.js +5 -4
  50. package/dist/util/secretFile.d.ts +24 -0
  51. package/dist/util/secretFile.js +35 -0
  52. package/package.json +1 -1
package/README.md CHANGED
@@ -43,16 +43,246 @@ octen completion zsh --install # writes to ~/.zshrc — then: source ~/.zshr
43
43
 
44
44
  ## Auth
45
45
 
46
- Set your API key (get one at https://octen.ai):
46
+ Octen CLI resolves the API key to use in this order — each step stopping resolution before
47
+ the next, so an explicit value always wins over a stored one:
48
+
49
+ 1. `--api-key <key>` on the command itself
50
+ 2. `OCTEN_API_KEY` in the environment
51
+ 3. `~/.octen/credentials.json`, written by `octen login`
52
+
53
+ Get a key at https://octen.ai. Either export it directly:
47
54
 
48
55
  ```sh
49
56
  export OCTEN_API_KEY=your_key_here
50
57
  ```
51
58
 
52
- You can also pass `--api-key <key>` on any command. To point at a self-hosted or staging endpoint, set `OCTEN_API_URL` or pass `--base-url <url>`.
59
+ or log in once and let the CLI manage it:
60
+
61
+ ```sh
62
+ octen login
63
+ ```
64
+
65
+ `octen login` opens your browser, completes an OAuth consent flow, and stores the resulting
66
+ API key at `~/.octen/credentials.json` (written with `0600` permissions). That key does not
67
+ expire, so `octen configure-mcp` and `octen configure-skills --set-key` can write it into
68
+ AI-client configs once and forget about it.
69
+
70
+ You can also pass `--api-key <key>` or `--base-url <url>` on any command; to point at a
71
+ self-hosted or staging endpoint, set `OCTEN_API_URL` or pass `--base-url <url>`.
72
+
73
+ Run `octen whoami` to see which of the three sources is actually in effect — it names the
74
+ winner explicitly, so a stored credential that is being shadowed or ignored says so rather
75
+ than looking live.
76
+
77
+ ### Auth environment variables
78
+
79
+ | Variable | Default | What it does |
80
+ | --- | --- | --- |
81
+ | `OCTEN_API_KEY` | — | The API key to use. Takes precedence over `~/.octen/credentials.json`, so a stored login is ignored while it is set. |
82
+ | `OCTEN_API_URL` | `https://api.octen.ai` | The Octen API base URL. |
83
+ | `OCTEN_AUTH_ISSUER` | `https://auth.octen.ai` | The OAuth authorization server `octen login` talks to. Only for local development against a self-hosted AS. |
84
+ | `OCTEN_AUTH_RESOURCE` | `https://cli.octen.ai` | The audience `octen login` requests the access token for. Despite the shape it is an identifier, not a site — nothing ever connects to it. Only for local development. |
85
+
86
+ `OCTEN_AUTH_ISSUER` and `OCTEN_AUTH_RESOURCE` **must not have a trailing slash** — a
87
+ trailing one is rejected with a named error rather than silently trimmed, because trimming
88
+ is what once turned a JWKS URL into `//api/oauth/jwks` and made a byte-for-byte issuer
89
+ comparison fail.
90
+
91
+ Changing either of them makes an existing stored credential **inapplicable**: the credential
92
+ records the issuer and resource it was minted for, and one minted for a different pair
93
+ belongs to another environment. The CLI never uses it and never deletes it — it says so and
94
+ names the variable. Unset the variable to go back to the stored credential, or run `octen
95
+ login` again to get one for the new environment. `octen whoami` shows both the stored
96
+ `Issuer`/`Resource` and which credential is in effect.
97
+
98
+ ### What the resource is, and why there are two
99
+
100
+ One authorization server issues access tokens for two different audiences, and they are
101
+ deliberately not interchangeable:
102
+
103
+ | Audience | Scope | What a token for it can do |
104
+ | --- | --- | --- |
105
+ | `https://mcp.octen.ai/mcp` | `mcp:tools` | Call MCP tools |
106
+ | `https://cli.octen.ai` | `octen:api_key` | Exchange for your account's API key |
107
+
108
+ Only the second can be traded for the API key. If both shared one audience, a token minted
109
+ for the MCP server — the one an AI client holds — could be replayed against the CLI's
110
+ exchange endpoint and walk away with that key. The `resource` is what keeps them apart: the
111
+ server checks that a token's granted audience is exactly this value before handing anything
112
+ over, and answers `403` otherwise.
113
+
114
+ That check is a byte-for-byte comparison, with no normalization anywhere along the chain,
115
+ which is why the trailing-slash rule above is a rejection rather than a quiet trim.
116
+ Normalizing in one place and not another produces a 401 on every request while each side
117
+ looks correct in isolation.
118
+
119
+ You do not need to set `OCTEN_AUTH_RESOURCE` to use Octen. It exists so a locally running
120
+ authorization server can use a different audience string.
121
+
122
+ **Add `.octen/` to your global gitignore.** A credentials file living in a dotfile directory
123
+ is more likely to be committed by accident than an environment variable ever was:
124
+
125
+ ```sh
126
+ git config --global core.excludesfile ~/.gitignore_global
127
+ echo ".octen/" >> ~/.gitignore_global
128
+ ```
129
+
130
+ **No browser on this machine (CI, containers)?** Paste a key directly — this branch makes
131
+ zero network requests:
132
+
133
+ ```sh
134
+ octen login --api-key "$OCTEN_API_KEY"
135
+ ```
136
+
137
+ **Over SSH**, forward the loopback callback port and pin it on both ends:
138
+
139
+ ```sh
140
+ # on the remote machine
141
+ octen login --port 8765
142
+ # from your local machine, before approving the consent screen in your browser
143
+ ssh -L 8765:localhost:8765 remote-host
144
+ ```
145
+
146
+ ### `octen logout`'s exact semantics
147
+
148
+ `octen logout` deletes `~/.octen/credentials.json` and revokes *this device's authorization*
149
+ (the OAuth grant behind it). Revoking the authorization only prevents it from being used to
150
+ silently mint a new credential later — it does **not** deactivate the underlying API key.
151
+ That key is your own account-wide, long-lived key, and the same key is very likely also
152
+ sitting on other machines, in your production code, and in the AI-client configs `octen
153
+ configure-mcp` wrote. All of those keep working after `octen logout` — that's by design,
154
+ since they're your own legitimate uses of your own key. If you believe the key itself was
155
+ exposed, deactivate or rotate it from the key management page at https://octen.ai — that
156
+ action, unlike `logout`, affects every place holding the key.
157
+
158
+ `octen logout --local` skips the network call entirely and only removes the local file,
159
+ without attempting to revoke the authorization.
160
+
161
+ ### One key, used by both the CLI and MCP
162
+
163
+ The audience split above applies to OAuth *access tokens*. The API key you end up with is
164
+ not audience-bound at all — it is your own account-wide key, and using it in more than one
165
+ place is the normal case, not a workaround. `octen configure-mcp` does exactly that: it
166
+ resolves your key through the same `--api-key` > `OCTEN_API_KEY` > stored-login order as
167
+ every other command and writes it into the MCP client config.
168
+
169
+ Three consequences of sharing one key:
170
+
171
+ - **`octen logout` does not stop MCP.** It revokes this device's authorization, not the key.
172
+ The key is still sitting in the MCP config and keeps working. To stop it everywhere,
173
+ deactivate or rotate the key from the key management page at https://octen.ai.
174
+ - **Usage and billing are pooled.** One key, one account — CLI calls and MCP calls land in
175
+ the same bucket.
176
+ - **The blast radius is shared.** Rotating or losing the key affects both at once.
177
+
178
+ To keep the two independent, pick a separate key for the CLI in the consent screen's **API
179
+ Key** dropdown instead of accepting the default, and leave MCP on another one.
180
+
181
+ This applies to the local stdio MCP server (`npx octen-mcp`, what `octen configure-mcp`
182
+ configures). A **remote OAuth connector** holds no API key at all — it carries an
183
+ MCP-audience token that the server resolves internally — so it is already independent of
184
+ whatever the CLI stores.
185
+
186
+ ### Dashboard "revoke" and an already-logged-in CLI
187
+
188
+ The dashboard's per-authorization "revoke" button has **no effect on a device that already
189
+ holds a credential**: it only stops that device from obtaining a *new* one without going
190
+ through the consent screen again — the API key it already has keeps working exactly as
191
+ before. The authorization still shows up in the dashboard's list either way; run `octen
192
+ whoami` on the device in question to get its `grantId` so you can identify which entry in
193
+ that list corresponds to it. To actually stop a key from working anywhere, deactivate or
194
+ rotate it from the key management page, not the authorization list.
195
+
196
+ ### Switching from a browser login to a pasted key
197
+
198
+ `octen login --api-key <KEY>` overwrites any existing `source: login` credential on disk
199
+ without revoking its grant — that branch makes no network request at all, deliberately, so
200
+ that it still works on a machine with no browser and no reachable auth server (see above).
201
+ So if you switch a machine from a browser login to a pasted key, the old
202
+ authorization is left behind: it stays listed as active in the dashboard's authorization
203
+ list, and once its `grantId` is gone from this machine's disk, nothing here can revoke it —
204
+ only the dashboard can. The command prints that `grantId` on stderr before overwriting the
205
+ file, so you can still find the entry; revoke it there directly if you want to clean it up,
206
+ or run `octen logout` first to revoke it properly.
53
207
 
54
208
  ## Commands
55
209
 
210
+ ### `octen login`
211
+
212
+ Log in via your browser and store the resulting long-lived API key at
213
+ `~/.octen/credentials.json`.
214
+
215
+ ```sh
216
+ octen login
217
+
218
+ # print the authorize URL instead of opening a browser
219
+ octen login --no-browser
220
+
221
+ # pin the loopback callback port, e.g. for the ssh -L forwarding above
222
+ octen login --port 8765
223
+
224
+ # no browser available: store a key directly, with zero network requests
225
+ octen login --api-key "$OCTEN_API_KEY"
226
+ ```
227
+
228
+ The consent screen asks for two things, and shows one you should check:
229
+
230
+ - **Account** — whose key this is: your personal account, or an organization you belong to.
231
+ This decides whose usage and billing the key draws on.
232
+ - **API Key** — which of that account's keys to hand over. Pick a separate one here if you
233
+ want the CLI's key independent of the one MCP uses (see
234
+ [One key, used by both the CLI and MCP](#one-key-used-by-both-the-cli-and-mcp)).
235
+ - **"Authorization result will be sent to 127.0.0.1:PORT"** — the loopback listener this
236
+ `octen login` just opened. If you did not just run it, press **Deny**.
237
+
238
+ On success the terminal names the account you approved as — `Logged in as Octen family.` —
239
+ falling back to the raw account id when the server does not supply a name.
240
+
241
+ If a `source: login` credential already exists, `octen login` best-effort revokes its grant
242
+ before starting the new login, so repeated logins don't accumulate orphaned authorizations
243
+ in the dashboard. A failure to revoke never blocks the new login.
244
+
245
+ Options: `--port <n>`, `--no-browser`.
246
+
247
+ ---
248
+
249
+ ### `octen logout`
250
+
251
+ Revoke this device's authorization and remove the locally stored credential. See
252
+ [Auth](#auth) above for the exact semantics — this does **not** deactivate the API key
253
+ itself.
254
+
255
+ ```sh
256
+ octen logout
257
+
258
+ # skip the network call; only remove the local file
259
+ octen logout --local
260
+ ```
261
+
262
+ A credential created with `octen login --api-key` has no authorization to revoke, so this
263
+ just removes the file, with zero network requests, and the output never mentions revocation
264
+ for that case.
265
+
266
+ Options: `--local`.
267
+
268
+ ---
269
+
270
+ ### `octen whoami`
271
+
272
+ Show the locally stored credential: account, credential source, and the `grantId` you can
273
+ use to find and revoke this device in the dashboard's authorization list. This reads only
274
+ `~/.octen/credentials.json` — it makes **zero network requests** and does not verify that
275
+ the key still works (run `octen search` for that; there's deliberately no `--verify` flag).
276
+
277
+ ```sh
278
+ octen whoami
279
+ octen whoami --json
280
+ ```
281
+
282
+ Exits non-zero when not logged in.
283
+
284
+ ---
285
+
56
286
  ### `octen search`
57
287
 
58
288
  Search the live web.
@@ -217,6 +447,60 @@ Options: `--all`, `--claude-code`, `--cursor`, `--claude-desktop`, `--windsurf`,
217
447
 
218
448
  Run without flags to print current status for each client.
219
449
 
450
+ #### Config scopes
451
+
452
+ `--scope` selects which file is written, and an unknown scope is an error rather
453
+ than a silent fall back to `user`:
454
+
455
+ | Client | `--scope user` | `--scope project` |
456
+ |---|---|---|
457
+ | Codex | `$HOME/.codex/config.toml` | `<project>/.codex/config.toml` |
458
+ | Cursor | `$HOME/.cursor/mcp.json` | `<project>/.cursor/mcp.json` |
459
+ | VS Code | `<project>/.vscode/mcp.json` | `<project>/.vscode/mcp.json` |
460
+ | Claude Code, Claude Desktop, Windsurf | user config only | same as user |
461
+
462
+ Codex reads a project-level `.codex/config.toml` only in a repository it has
463
+ been told to trust, so a project-scoped entry stays inert until you trust the
464
+ directory in Codex. `--scope status` and `reset --scope project` read and remove
465
+ from the same project file.
466
+
467
+ #### Codex cold start
468
+
469
+ On a machine that has never run `octen-mcp`, `npx -y octen-mcp` has to fetch
470
+ the package and its dependency tree before the server can answer `initialize`.
471
+ Measured on macOS 15 / Node 24.18 / octen-mcp 0.5.1, from an empty npm cache
472
+ (`npm_config_cache` pointed at a fresh directory) over three trials: **9.45s,
473
+ 9.59s and 9.75s** to `initialize`, 53 MB and ~4,200 files downloaded, all six
474
+ tools listed. The same run against a warm cache: **0.24s**.
475
+
476
+ Codex's default MCP startup window is in the same ballpark as that cold
477
+ figure, so a fresh-cache first run is a race — which is how the Octen tools
478
+ can be missing from a session that reports no error. Two optional keys make
479
+ Codex wait for the server instead:
480
+
481
+ ```toml
482
+ [mcp_servers.octen]
483
+ command = "npx"
484
+ args = ["-y", "octen-mcp"]
485
+ required = true
486
+ startup_timeout_sec = 60
487
+
488
+ [mcp_servers.octen.env]
489
+ OCTEN_API_KEY = "${OCTEN_API_KEY}"
490
+ ```
491
+
492
+ `required` and `startup_timeout_sec` are fields of Codex's MCP server config
493
+ (verified against codex-cli 0.153.4); Codex silently ignores config keys it does
494
+ not know, so check your own version before relying on them. Warming the cache
495
+ once with `npm i -g octen-mcp` (or a single `npx -y octen-mcp` run) is the
496
+ other way to close the same gap. `required = true`
497
+ means a server that fails to start blocks the Codex session, which is why
498
+ `octen configure-mcp --codex` does not write these two keys by default — add
499
+ them yourself where Octen has to be available. The `env` table is the same shape
500
+ `configure-mcp` writes. `${OCTEN_API_KEY}` above is a documentation placeholder,
501
+ not a value Codex expands: inject the real key through `configure-mcp` or your
502
+ own secret handling, and never commit one.
503
+
220
504
  ---
221
505
 
222
506
  ### `octen configure-skills`
@@ -253,7 +537,8 @@ Run without flags to show installed skills per client.
253
537
 
254
538
  ### `octen reset`
255
539
 
256
- Remove the Octen MCP server and/or skills from AI clients.
540
+ Remove the Octen MCP server and/or skills from AI clients, or clear the stored login
541
+ credential.
257
542
 
258
543
  ```sh
259
544
  # Remove everything from all clients
@@ -264,9 +549,24 @@ octen reset --mcp
264
549
 
265
550
  # Remove only skills from a specific client
266
551
  octen reset --skills --claude-code
552
+
553
+ # Clear ~/.octen/credentials.json (like octen logout --local, but see the note below)
554
+ octen reset --credentials
267
555
  ```
268
556
 
269
- Options: `--all` (both surfaces, all clients), `--mcp`, `--skills`, plus per-client flags: `--claude-code`, `--cursor`, `--claude-desktop`, `--windsurf`, `--vscode`, `--codex`, `--openclaw`, `--hermes`, `--scope` (user|project).
557
+ Options: `--all` (both surfaces, all clients), `--mcp`, `--skills`, `--credentials`, plus per-client flags: `--claude-code`, `--cursor`, `--claude-desktop`, `--windsurf`, `--vscode`, `--codex`, `--openclaw`, `--hermes`, `--scope` (user|project).
558
+
559
+ `--credentials` is **not** included in `--all` — `--all`'s existing meaning is "both
560
+ surfaces (MCP + skills) across all clients", and folding in the login credential would mean
561
+ `--all` silently logs you out, which would be an unwelcome surprise. Reach for `octen
562
+ logout` instead of `reset --credentials` when there's a remote authorization to revoke too;
563
+ `reset --credentials` only ever touches the local file, with no network request.
564
+
565
+ It behaves like `octen logout --local` — same file, same zero network requests — but it is
566
+ not the same command: `reset --credentials` reports removal in `reset`'s own style, and
567
+ `logout` is the command whose whole job is the authorization. Both print the `grantId` of a
568
+ `source: login` credential before destroying it, so the authorization left listed in the
569
+ dashboard can still be identified and revoked there.
270
570
 
271
571
  ---
272
572
 
@@ -296,6 +596,27 @@ eval "$(octen completion zsh)" # add this line to ~/.zshrc to persist
296
596
 
297
597
  All commands print human-readable output when stdout is a TTY. When stdout is piped or `--json` is passed, commands emit raw JSON. Use `--pretty` to force human-readable output even when piped. `--no-color` disables ANSI colors.
298
598
 
599
+ ## Errors and exit codes
600
+
601
+ Scripts must check the exit status, not just the output.
602
+
603
+ | Status | When |
604
+ |---|---|
605
+ | `0` | The command completed and the response was complete. |
606
+ | `2` | Bad input, caught before any request: a malformed number (`--count 1.5`, `--count 2junk`), an empty comma list (`--include-domains ""`), a blank query, an unknown `--scope`, or a missing API key. |
607
+ | `1` | Everything else: HTTP errors, an API envelope with a non-zero `code`, a timeout, and stream failures. |
608
+
609
+ Two consequences worth knowing:
610
+
611
+ - **Malformed numbers and empty lists fail instead of being guessed.** `--count 1.5`
612
+ used to be sent as `1` and `--include-domains ""` as `[""]`. Both now name the
613
+ flag and exit 2, so no request is made.
614
+ - **A streaming answer can fail after printing part of itself.** If the stream
615
+ carries an error event, ends without its terminator, or stalls past the
616
+ timeout, `octen chat` exits non-zero with the partial answer already on stdout.
617
+ It is not rolled back — a caller that ignores the exit status will treat a
618
+ truncated answer as a complete one.
619
+
299
620
  ## Keeping things up to date
300
621
 
301
622
  - **MCP server**: `octen-mcp` is invoked via `npx` so it auto-pulls the latest version on each run. Pin a version with `--pin` if you need stability.
@@ -43,14 +43,17 @@ export interface ChatCompletion {
43
43
  * chunks (search_done / content / finish / usage) terminated by a `[DONE]` sentinel.
44
44
  */
45
45
  export interface StreamEvent {
46
- type?: "search_done" | "content" | "finish" | "usage" | string;
46
+ type?: "search_done" | "content" | "finish" | "usage" | "error" | string;
47
47
  choices?: Array<{
48
48
  delta?: {
49
49
  content?: string;
50
50
  reasoning?: string;
51
51
  };
52
+ finish_reason?: string | null;
52
53
  }>;
53
54
  usage?: Record<string, unknown>;
55
+ /** Present on an in-stream error event; shape is server-defined. */
56
+ error?: unknown;
54
57
  }
55
58
  export declare const VERBOSITY_OPTIONS: readonly ["low", "medium", "high"];
56
59
  export type Verbosity = (typeof VERBOSITY_OPTIONS)[number];
@@ -4,6 +4,8 @@ export interface OctenClientOptions {
4
4
  timeoutMs?: number;
5
5
  maxRetries?: number;
6
6
  retryBaseMs?: number;
7
+ /** Upper bound on a single retry wait, including one asked for by Retry-After. */
8
+ retryMaxDelayMs?: number;
7
9
  }
8
10
  export declare class OctenClient {
9
11
  private apiKey;
@@ -11,9 +13,31 @@ export declare class OctenClient {
11
13
  private timeoutMs;
12
14
  private maxRetries;
13
15
  private retryBaseMs;
16
+ private retryMaxDelayMs;
14
17
  constructor(opts: OctenClientOptions);
18
+ /**
19
+ * How long to wait before the next attempt. A valid `Retry-After` (either
20
+ * delta-seconds or an HTTP-date) wins over the exponential backoff, but is
21
+ * capped: a server asking for an hour must not turn one command into an
22
+ * hour-long hang.
23
+ */
24
+ private retryDelayMs;
25
+ /**
26
+ * A 2xx body must be a non-empty JSON object, and an Octen envelope carrying a
27
+ * non-zero numeric `code` is a failure however cheerful its HTTP status was.
28
+ * A string or null `code` is left to the endpoint's own response shape.
29
+ */
30
+ private validateSuccessPayload;
15
31
  private headers;
16
32
  request<T = unknown>(endpoint: string, body: unknown, timeoutMs?: number): Promise<T>;
17
- /** Returns the raw Response for SSE streaming (chat). */
33
+ /**
34
+ * Returns the Response for SSE streaming (chat).
35
+ *
36
+ * The timeout covers the whole request, not just the headers: it is armed
37
+ * while we wait for the next chunk and disarmed once that chunk lands, so a
38
+ * server that stops sending mid-answer aborts the request while a long answer
39
+ * that keeps streaming does not. That is the same per-read deadline httpx
40
+ * gives the Python SDK, so both clients promise the same thing.
41
+ */
18
42
  stream(endpoint: string, body: Record<string, unknown>, timeoutMs?: number): Promise<Response>;
19
43
  }
@@ -1,13 +1,52 @@
1
1
  import { DEFAULT_BASE_URL, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT_MS, ENDPOINTS } from "./constants.js";
2
- import { OctenAPIError, OctenAuthError, OctenNetworkError, OctenTimeoutError } from "./errors.js";
2
+ import { errorMessage, OctenAPIError, OctenAuthError, OctenNetworkError, OctenTimeoutError, } from "./errors.js";
3
3
  const RETRYABLE = new Set([429, 500, 502, 503, 504]);
4
4
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
5
+ const MALFORMED_SUCCESS = "API returned a 2xx response with an empty or invalid JSON body";
6
+ /** Cap on one retry wait. Mirrors the Python SDK's max_delay. */
7
+ const DEFAULT_RETRY_MAX_DELAY_MS = 30_000;
8
+ /** A bare integer Retry-After — anything else is a date or invalid. */
9
+ const DELTA_SECONDS = /^[+-]?\d+$/;
10
+ /**
11
+ * RFC 9110 Retry-After: either non-negative delta-seconds or an HTTP-date.
12
+ * Returns milliseconds to wait, or null when the header cannot be trusted (a
13
+ * negative delta, a malformed date, junk) so the caller keeps its own backoff.
14
+ */
15
+ function parseRetryAfter(header, nowMs) {
16
+ const value = header.trim();
17
+ if (!value)
18
+ return null;
19
+ if (DELTA_SECONDS.test(value)) {
20
+ const seconds = Number(value);
21
+ return seconds >= 0 ? seconds * 1000 : null;
22
+ }
23
+ const when = Date.parse(value);
24
+ if (Number.isNaN(when))
25
+ return null;
26
+ return Math.max(0, when - nowMs);
27
+ }
28
+ /**
29
+ * Read the message out of a non-2xx body. Structured JSON wins; an unparseable
30
+ * body keeps up to 500 characters of its own text, which is often the only
31
+ * diagnostic an upstream gateway gives us; otherwise the HTTP status.
32
+ */
33
+ function httpErrorMessage(payload, rawText, status) {
34
+ if (payload !== undefined) {
35
+ const fromJson = errorMessage(payload, "");
36
+ if (fromJson)
37
+ return fromJson;
38
+ return `HTTP ${status}`;
39
+ }
40
+ const text = rawText.trim();
41
+ return text ? text.slice(0, 500) : `HTTP ${status}`;
42
+ }
5
43
  export class OctenClient {
6
44
  apiKey;
7
45
  baseUrl;
8
46
  timeoutMs;
9
47
  maxRetries;
10
48
  retryBaseMs;
49
+ retryMaxDelayMs;
11
50
  constructor(opts) {
12
51
  if (!opts.apiKey)
13
52
  throw new OctenAuthError("API key is required");
@@ -16,6 +55,39 @@ export class OctenClient {
16
55
  this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
17
56
  this.maxRetries = opts.maxRetries ?? DEFAULT_MAX_RETRIES;
18
57
  this.retryBaseMs = opts.retryBaseMs ?? 500;
58
+ this.retryMaxDelayMs = opts.retryMaxDelayMs ?? DEFAULT_RETRY_MAX_DELAY_MS;
59
+ }
60
+ /**
61
+ * How long to wait before the next attempt. A valid `Retry-After` (either
62
+ * delta-seconds or an HTTP-date) wins over the exponential backoff, but is
63
+ * capped: a server asking for an hour must not turn one command into an
64
+ * hour-long hang.
65
+ */
66
+ retryDelayMs(response, attempt, nowMs = Date.now()) {
67
+ const backoff = this.retryBaseMs * 2 ** attempt;
68
+ const header = response.headers.get("retry-after");
69
+ const asked = header == null ? null : parseRetryAfter(header, nowMs);
70
+ const delay = asked ?? backoff;
71
+ return Math.min(delay, this.retryMaxDelayMs);
72
+ }
73
+ /**
74
+ * A 2xx body must be a non-empty JSON object, and an Octen envelope carrying a
75
+ * non-zero numeric `code` is a failure however cheerful its HTTP status was.
76
+ * A string or null `code` is left to the endpoint's own response shape.
77
+ */
78
+ validateSuccessPayload(payload, status) {
79
+ if (payload === null || Array.isArray(payload) || typeof payload !== "object") {
80
+ throw new OctenAPIError(MALFORMED_SUCCESS, status, payload);
81
+ }
82
+ const obj = payload;
83
+ if (Object.keys(obj).length === 0) {
84
+ throw new OctenAPIError(MALFORMED_SUCCESS, status, payload);
85
+ }
86
+ const code = obj.code;
87
+ if (typeof code === "number" && code !== 0) {
88
+ throw new OctenAPIError(errorMessage(obj, `API returned code ${code}`), status, payload);
89
+ }
90
+ return obj;
19
91
  }
20
92
  headers(endpoint) {
21
93
  // Chat uses the OpenAI-compatible /v1/chat/completions surface (Authorization: Bearer); native Octen endpoints use x-api-key.
@@ -40,22 +112,24 @@ export class OctenClient {
40
112
  signal: ac.signal,
41
113
  });
42
114
  if (res.ok) {
115
+ let payload;
43
116
  try {
44
- return (await res.json());
117
+ payload = await res.json();
45
118
  }
46
119
  catch {
47
- throw new OctenAPIError("API returned a 2xx response with an invalid JSON body", res.status);
120
+ throw new OctenAPIError(MALFORMED_SUCCESS, res.status);
48
121
  }
122
+ return this.validateSuccessPayload(payload, res.status);
49
123
  }
50
124
  const rawText = await res.text().catch(() => "");
51
- let errBody = {};
125
+ let errBody = undefined;
52
126
  try {
53
- errBody = rawText ? JSON.parse(rawText) : {};
127
+ errBody = rawText ? JSON.parse(rawText) : undefined;
54
128
  }
55
129
  catch { /* keep raw text */ }
56
- const msg = errBody?.msg ?? errBody?.error ?? (rawText ? rawText.slice(0, 500) : `HTTP ${res.status}`);
130
+ const msg = httpErrorMessage(errBody, rawText, res.status);
57
131
  if (RETRYABLE.has(res.status) && attempt < this.maxRetries) {
58
- await sleep(this.retryBaseMs * 2 ** attempt);
132
+ await sleep(this.retryDelayMs(res, attempt));
59
133
  continue;
60
134
  }
61
135
  if (res.status === 401)
@@ -82,11 +156,30 @@ export class OctenClient {
82
156
  }
83
157
  throw lastErr;
84
158
  }
85
- /** Returns the raw Response for SSE streaming (chat). */
159
+ /**
160
+ * Returns the Response for SSE streaming (chat).
161
+ *
162
+ * The timeout covers the whole request, not just the headers: it is armed
163
+ * while we wait for the next chunk and disarmed once that chunk lands, so a
164
+ * server that stops sending mid-answer aborts the request while a long answer
165
+ * that keeps streaming does not. That is the same per-read deadline httpx
166
+ * gives the Python SDK, so both clients promise the same thing.
167
+ */
86
168
  async stream(endpoint, body, timeoutMs) {
87
169
  const ac = new AbortController();
88
170
  const ms = timeoutMs ?? this.timeoutMs;
89
- const t = ms ? setTimeout(() => ac.abort(), ms) : undefined;
171
+ let timer;
172
+ const arm = () => {
173
+ if (!ms)
174
+ return;
175
+ clearTimeout(timer);
176
+ timer = setTimeout(() => ac.abort(), ms);
177
+ };
178
+ const disarm = () => {
179
+ clearTimeout(timer);
180
+ timer = undefined;
181
+ };
182
+ arm();
90
183
  try {
91
184
  const res = await fetch(`${this.baseUrl}${endpoint}`, {
92
185
  method: "POST",
@@ -94,19 +187,56 @@ export class OctenClient {
94
187
  body: JSON.stringify({ ...body, stream: true }),
95
188
  signal: ac.signal,
96
189
  });
190
+ disarm();
97
191
  if (!res.ok) {
98
192
  const rawText = await res.text().catch(() => "");
99
- let errBody = {};
193
+ let errBody = undefined;
100
194
  try {
101
- errBody = rawText ? JSON.parse(rawText) : {};
195
+ errBody = rawText ? JSON.parse(rawText) : undefined;
102
196
  }
103
197
  catch { /* keep raw text */ }
104
- const msg = errBody?.msg ?? errBody?.error ?? (rawText ? rawText.slice(0, 500) : `HTTP ${res.status}`);
105
- throw new OctenAPIError(msg, res.status, errBody);
198
+ throw new OctenAPIError(httpErrorMessage(errBody, rawText, res.status), res.status, errBody);
106
199
  }
107
- return res;
200
+ if (!ms || !res.body)
201
+ return res;
202
+ // Wrap the body so the deadline keeps applying to each chunk. The source
203
+ // reader is released on end, error and consumer cancellation alike.
204
+ const source = res.body.getReader();
205
+ const wrapped = new ReadableStream({
206
+ async pull(controller) {
207
+ arm();
208
+ try {
209
+ const { done, value } = await source.read();
210
+ disarm();
211
+ if (done) {
212
+ controller.close();
213
+ return;
214
+ }
215
+ controller.enqueue(value);
216
+ }
217
+ catch (err) {
218
+ disarm();
219
+ controller.error(err);
220
+ }
221
+ },
222
+ async cancel(reason) {
223
+ disarm();
224
+ try {
225
+ await source.cancel(reason);
226
+ }
227
+ catch {
228
+ /* the stream is already gone */
229
+ }
230
+ },
231
+ });
232
+ return new Response(wrapped, {
233
+ status: res.status,
234
+ statusText: res.statusText,
235
+ headers: res.headers,
236
+ });
108
237
  }
109
238
  catch (e) {
239
+ disarm();
110
240
  if (e instanceof OctenAPIError || e instanceof OctenAuthError)
111
241
  throw e;
112
242
  if (e.name === "AbortError")
@@ -114,8 +244,5 @@ export class OctenClient {
114
244
  const cause = e?.cause?.code ?? e?.cause?.message ?? e.message;
115
245
  throw new OctenNetworkError(`network error reaching ${this.baseUrl}: ${cause}`);
116
246
  }
117
- finally {
118
- clearTimeout(t);
119
- }
120
247
  }
121
248
  }