@octen.ai/cli 0.7.0 → 0.8.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.
package/README.md CHANGED
@@ -217,6 +217,60 @@ Options: `--all`, `--claude-code`, `--cursor`, `--claude-desktop`, `--windsurf`,
217
217
 
218
218
  Run without flags to print current status for each client.
219
219
 
220
+ #### Config scopes
221
+
222
+ `--scope` selects which file is written, and an unknown scope is an error rather
223
+ than a silent fall back to `user`:
224
+
225
+ | Client | `--scope user` | `--scope project` |
226
+ |---|---|---|
227
+ | Codex | `$HOME/.codex/config.toml` | `<project>/.codex/config.toml` |
228
+ | Cursor | `$HOME/.cursor/mcp.json` | `<project>/.cursor/mcp.json` |
229
+ | VS Code | `<project>/.vscode/mcp.json` | `<project>/.vscode/mcp.json` |
230
+ | Claude Code, Claude Desktop, Windsurf | user config only | same as user |
231
+
232
+ Codex reads a project-level `.codex/config.toml` only in a repository it has
233
+ been told to trust, so a project-scoped entry stays inert until you trust the
234
+ directory in Codex. `--scope status` and `reset --scope project` read and remove
235
+ from the same project file.
236
+
237
+ #### Codex cold start
238
+
239
+ On a machine that has never run `octen-mcp`, `npx -y octen-mcp` has to fetch
240
+ the package and its dependency tree before the server can answer `initialize`.
241
+ Measured on macOS 15 / Node 24.18 / octen-mcp 0.5.1, from an empty npm cache
242
+ (`npm_config_cache` pointed at a fresh directory) over three trials: **9.45s,
243
+ 9.59s and 9.75s** to `initialize`, 53 MB and ~4,200 files downloaded, all six
244
+ tools listed. The same run against a warm cache: **0.24s**.
245
+
246
+ Codex's default MCP startup window is in the same ballpark as that cold
247
+ figure, so a fresh-cache first run is a race — which is how the Octen tools
248
+ can be missing from a session that reports no error. Two optional keys make
249
+ Codex wait for the server instead:
250
+
251
+ ```toml
252
+ [mcp_servers.octen]
253
+ command = "npx"
254
+ args = ["-y", "octen-mcp"]
255
+ required = true
256
+ startup_timeout_sec = 60
257
+
258
+ [mcp_servers.octen.env]
259
+ OCTEN_API_KEY = "${OCTEN_API_KEY}"
260
+ ```
261
+
262
+ `required` and `startup_timeout_sec` are fields of Codex's MCP server config
263
+ (verified against codex-cli 0.153.4); Codex silently ignores config keys it does
264
+ not know, so check your own version before relying on them. Warming the cache
265
+ once with `npm i -g octen-mcp` (or a single `npx -y octen-mcp` run) is the
266
+ other way to close the same gap. `required = true`
267
+ means a server that fails to start blocks the Codex session, which is why
268
+ `octen configure-mcp --codex` does not write these two keys by default — add
269
+ them yourself where Octen has to be available. The `env` table is the same shape
270
+ `configure-mcp` writes. `${OCTEN_API_KEY}` above is a documentation placeholder,
271
+ not a value Codex expands: inject the real key through `configure-mcp` or your
272
+ own secret handling, and never commit one.
273
+
220
274
  ---
221
275
 
222
276
  ### `octen configure-skills`
@@ -296,6 +350,27 @@ eval "$(octen completion zsh)" # add this line to ~/.zshrc to persist
296
350
 
297
351
  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
352
 
353
+ ## Errors and exit codes
354
+
355
+ Scripts must check the exit status, not just the output.
356
+
357
+ | Status | When |
358
+ |---|---|
359
+ | `0` | The command completed and the response was complete. |
360
+ | `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. |
361
+ | `1` | Everything else: HTTP errors, an API envelope with a non-zero `code`, a timeout, and stream failures. |
362
+
363
+ Two consequences worth knowing:
364
+
365
+ - **Malformed numbers and empty lists fail instead of being guessed.** `--count 1.5`
366
+ used to be sent as `1` and `--include-domains ""` as `[""]`. Both now name the
367
+ flag and exit 2, so no request is made.
368
+ - **A streaming answer can fail after printing part of itself.** If the stream
369
+ carries an error event, ends without its terminator, or stalls past the
370
+ timeout, `octen chat` exits non-zero with the partial answer already on stdout.
371
+ It is not rolled back — a caller that ignores the exit status will treat a
372
+ truncated answer as a complete one.
373
+
299
374
  ## Keeping things up to date
300
375
 
301
376
  - **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
  }
@@ -8,9 +8,21 @@ export declare class OctenTimeoutError extends OctenError {
8
8
  }
9
9
  export declare class OctenNetworkError extends OctenError {
10
10
  }
11
+ /** A stream that was malformed, truncated, or carried a typed error event. */
12
+ export declare class OctenStreamError extends OctenError {
13
+ }
11
14
  export declare class OctenAPIError extends OctenError {
12
15
  status: number;
13
16
  body?: unknown | undefined;
14
17
  constructor(message: string, status: number, body?: unknown | undefined);
15
18
  }
19
+ /**
20
+ * Pull a human-readable message out of an error payload.
21
+ *
22
+ * Fixed order: `msg` -> `message` -> `detail`, then recurse into `error`, then
23
+ * the caller's fallback. Only a non-empty string is ever returned, so a nested
24
+ * object can no longer reach the terminal as "[object Object]". Visited nodes
25
+ * are tracked so a self-referential payload cannot loop.
26
+ */
27
+ export declare function errorMessage(payload: unknown, fallback: string): string;
16
28
  export declare function exitCodeFor(err: unknown): number;
@@ -8,6 +8,9 @@ export class OctenTimeoutError extends OctenError {
8
8
  }
9
9
  export class OctenNetworkError extends OctenError {
10
10
  }
11
+ /** A stream that was malformed, truncated, or carried a typed error event. */
12
+ export class OctenStreamError extends OctenError {
13
+ }
11
14
  export class OctenAPIError extends OctenError {
12
15
  status;
13
16
  body;
@@ -17,6 +20,40 @@ export class OctenAPIError extends OctenError {
17
20
  this.body = body;
18
21
  }
19
22
  }
23
+ /** Keys that, when they hold a non-empty string, are the error message. */
24
+ const MESSAGE_KEYS = ["msg", "message", "detail"];
25
+ function nonEmptyString(value) {
26
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
27
+ }
28
+ /**
29
+ * Pull a human-readable message out of an error payload.
30
+ *
31
+ * Fixed order: `msg` -> `message` -> `detail`, then recurse into `error`, then
32
+ * the caller's fallback. Only a non-empty string is ever returned, so a nested
33
+ * object can no longer reach the terminal as "[object Object]". Visited nodes
34
+ * are tracked so a self-referential payload cannot loop.
35
+ */
36
+ export function errorMessage(payload, fallback) {
37
+ const seen = new Set();
38
+ const walk = (node) => {
39
+ const direct = nonEmptyString(node);
40
+ if (direct)
41
+ return direct;
42
+ if (node === null || typeof node !== "object")
43
+ return undefined;
44
+ if (seen.has(node))
45
+ return undefined;
46
+ seen.add(node);
47
+ const obj = node;
48
+ for (const key of MESSAGE_KEYS) {
49
+ const found = nonEmptyString(obj[key]);
50
+ if (found)
51
+ return found;
52
+ }
53
+ return walk(obj.error);
54
+ };
55
+ return walk(payload) ?? fallback;
56
+ }
20
57
  export function exitCodeFor(err) {
21
58
  if (err instanceof OctenAuthError || err instanceof OctenValidationError)
22
59
  return 2;
@@ -76,7 +76,10 @@ export function buildSearchOptions(o) {
76
76
  return opts;
77
77
  }
78
78
  export function buildSearchRequest(query, o) {
79
- if (!query)
79
+ // Validate on the trimmed value but send the caller's text verbatim: a query
80
+ // of only whitespace is a mistake, whitespace inside a real query is not ours
81
+ // to rewrite.
82
+ if (query.trim().length === 0)
80
83
  throw new OctenValidationError("query is required");
81
84
  return { query, ...buildSearchOptions(o) };
82
85
  }
@@ -86,7 +89,7 @@ export function buildSearchRequest(query, o) {
86
89
  * `max_queries` stay at the top level.
87
90
  */
88
91
  export function buildBroadSearchRequest(query, o) {
89
- if (!query)
92
+ if (query.trim().length === 0)
90
93
  throw new OctenValidationError("query is required");
91
94
  if (o.maxQueries != null && (o.maxQueries < LIMITS.maxQueries.min || o.maxQueries > LIMITS.maxQueries.max))
92
95
  throw new OctenValidationError(`max-queries must be ${LIMITS.maxQueries.min}-${LIMITS.maxQueries.max}`);
package/dist/api/sse.d.ts CHANGED
@@ -1,6 +1,18 @@
1
1
  /**
2
- * Parse a Server-Sent Events (SSE) stream from a fetch Response.
3
- * Yields parsed JSON objects from `data:` lines, stops at `data: [DONE]`.
4
- * Tolerates non-JSON keepalive/comment lines by skipping them.
2
+ * Parse a Server-Sent Events stream from a fetch Response into parsed JSON events.
3
+ *
4
+ * Framing follows the SSE rules the chat endpoint actually uses: events are
5
+ * separated by a blank line, LF and CRLF both terminate a line, `data:` may or
6
+ * may not be followed by a space, and every `data:` line in one event is joined
7
+ * with "\n" and parsed once — so a JSON object split across data lines survives.
8
+ *
9
+ * Completion is explicit. `[DONE]` is authoritative and nothing after it is
10
+ * read; a typed `finish` event or an OpenAI-style `finish_reason` followed by
11
+ * EOF also counts as complete. A stream that just stops is a truncation error
12
+ * rather than a silently short answer. Malformed JSON is an error too, for the
13
+ * same reason: a dropped event is indistinguishable from a shorter answer.
14
+ *
15
+ * The reader is always released, and the source is cancelled whenever iteration
16
+ * stops before the body is drained — including when the consumer breaks early.
5
17
  */
6
18
  export declare function parseSSE(res: Response): AsyncGenerator<unknown>;
package/dist/api/sse.js CHANGED
@@ -1,53 +1,148 @@
1
+ import { OctenStreamError, OctenTimeoutError } from "./errors.js";
2
+ /** Prefix of an SSE data field. The single space after the colon is optional. */
3
+ const DATA_PREFIX = "data:";
4
+ const DONE_SENTINEL = "[DONE]";
5
+ /** True when an event says generation is over: typed `finish` or an OpenAI finish_reason. */
6
+ function isTerminalEvent(event) {
7
+ if (event === null || typeof event !== "object")
8
+ return false;
9
+ const obj = event;
10
+ if (obj.type === "finish")
11
+ return true;
12
+ const choices = obj.choices;
13
+ if (Array.isArray(choices)) {
14
+ return choices.some((choice) => choice !== null &&
15
+ typeof choice === "object" &&
16
+ choice.finish_reason != null);
17
+ }
18
+ return false;
19
+ }
1
20
  /**
2
- * Parse a Server-Sent Events (SSE) stream from a fetch Response.
3
- * Yields parsed JSON objects from `data:` lines, stops at `data: [DONE]`.
4
- * Tolerates non-JSON keepalive/comment lines by skipping them.
21
+ * Parse a Server-Sent Events stream from a fetch Response into parsed JSON events.
22
+ *
23
+ * Framing follows the SSE rules the chat endpoint actually uses: events are
24
+ * separated by a blank line, LF and CRLF both terminate a line, `data:` may or
25
+ * may not be followed by a space, and every `data:` line in one event is joined
26
+ * with "\n" and parsed once — so a JSON object split across data lines survives.
27
+ *
28
+ * Completion is explicit. `[DONE]` is authoritative and nothing after it is
29
+ * read; a typed `finish` event or an OpenAI-style `finish_reason` followed by
30
+ * EOF also counts as complete. A stream that just stops is a truncation error
31
+ * rather than a silently short answer. Malformed JSON is an error too, for the
32
+ * same reason: a dropped event is indistinguishable from a shorter answer.
33
+ *
34
+ * The reader is always released, and the source is cancelled whenever iteration
35
+ * stops before the body is drained — including when the consumer breaks early.
5
36
  */
6
37
  export async function* parseSSE(res) {
7
38
  const reader = res.body.getReader();
8
39
  const decoder = new TextDecoder();
9
40
  let buffer = "";
10
- while (true) {
11
- const { done, value } = await reader.read();
12
- if (done)
13
- break;
14
- buffer += decoder.decode(value, { stream: true });
15
- // SSE events are separated by double newlines
16
- const events = buffer.split("\n\n");
17
- // Keep the last (possibly incomplete) segment in the buffer
18
- buffer = events.pop() ?? "";
19
- for (const event of events) {
20
- // Gather data lines from the event block
21
- for (const line of event.split("\n")) {
22
- if (!line.startsWith("data:"))
23
- continue;
24
- const payload = line.slice("data:".length).trim();
25
- if (payload === "[DONE]")
26
- return;
27
- try {
28
- yield JSON.parse(payload);
29
- }
30
- catch {
31
- // Skip non-JSON keepalive or malformed lines
41
+ let pendingCR = false;
42
+ let sawDone = false;
43
+ let sawFinish = false;
44
+ let sourceDrained = false;
45
+ /** Normalize line endings, holding back a CR that may be half of a split CRLF. */
46
+ const feed = (text) => {
47
+ let chunk = pendingCR ? `\r${text}` : text;
48
+ pendingCR = chunk.endsWith("\r");
49
+ if (pendingCR)
50
+ chunk = chunk.slice(0, -1);
51
+ return chunk.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
52
+ };
53
+ /** Parse one event block. Returns the event, or undefined for comment-only blocks. */
54
+ const parseEvent = (block) => {
55
+ const dataLines = [];
56
+ for (const line of block.split("\n")) {
57
+ if (line.startsWith(":"))
58
+ continue;
59
+ if (!line.startsWith(DATA_PREFIX))
60
+ continue;
61
+ let value = line.slice(DATA_PREFIX.length);
62
+ if (value.startsWith(" "))
63
+ value = value.slice(1);
64
+ dataLines.push(value);
65
+ }
66
+ if (dataLines.length === 0)
67
+ return {};
68
+ const payload = dataLines.join("\n");
69
+ if (payload.trim() === DONE_SENTINEL)
70
+ return { done: true };
71
+ if (payload.trim() === "")
72
+ return {};
73
+ try {
74
+ return { event: JSON.parse(payload) };
75
+ }
76
+ catch {
77
+ throw new OctenStreamError(`stream returned a malformed event: ${payload.slice(0, 200)}`);
78
+ }
79
+ };
80
+ /** A body read aborted by the client deadline is a timeout, not a stream defect. */
81
+ const read = async () => {
82
+ try {
83
+ return await reader.read();
84
+ }
85
+ catch (err) {
86
+ const name = err?.name;
87
+ if (name === "AbortError" || name === "TimeoutError") {
88
+ throw new OctenTimeoutError("request timed out");
89
+ }
90
+ throw err;
91
+ }
92
+ };
93
+ try {
94
+ while (!sawDone) {
95
+ const { done, value } = await read();
96
+ if (done) {
97
+ sourceDrained = true;
98
+ buffer += feed(decoder.decode());
99
+ }
100
+ else {
101
+ buffer += feed(decoder.decode(value, { stream: true }));
102
+ }
103
+ const blocks = buffer.split("\n\n");
104
+ // The trailing segment may be an incomplete event; at EOF there is no more
105
+ // data coming, so it is complete by definition and gets dispatched too.
106
+ buffer = sourceDrained ? "" : (blocks.pop() ?? "");
107
+ if (sourceDrained && blocks.length > 0 && blocks[blocks.length - 1].trim() === "") {
108
+ blocks.pop();
109
+ }
110
+ for (const block of blocks) {
111
+ const { event, done: isDone } = parseEvent(block);
112
+ if (isDone) {
113
+ sawDone = true;
114
+ break;
32
115
  }
116
+ if (event === undefined)
117
+ continue;
118
+ if (isTerminalEvent(event))
119
+ sawFinish = true;
120
+ yield event;
33
121
  }
122
+ if (sourceDrained)
123
+ break;
124
+ }
125
+ if (!sawDone && !sawFinish) {
126
+ throw new OctenStreamError("stream ended before the response was complete (no [DONE] or finish event)");
34
127
  }
35
128
  }
36
- // Flush any remaining buffer content
37
- if (buffer.trim()) {
38
- for (const line of buffer.split("\n")) {
39
- if (!line.startsWith("data:"))
40
- continue;
41
- const payload = line.slice("data:".length).trim();
42
- if (payload === "[DONE]")
43
- return;
129
+ finally {
130
+ // Cancel unless the body was read to its end, so an early stop (consumer
131
+ // break, [DONE], or an error) actually releases the connection. Cleanup
132
+ // failures must not replace the error that got us here.
133
+ if (!sourceDrained) {
44
134
  try {
45
- yield JSON.parse(payload);
135
+ await reader.cancel();
46
136
  }
47
137
  catch {
48
- // Skip non-JSON keepalive or malformed lines
138
+ /* the stream is already gone */
49
139
  }
50
140
  }
141
+ try {
142
+ reader.releaseLock();
143
+ }
144
+ catch {
145
+ /* already released */
146
+ }
51
147
  }
52
- // A stream ending without [DONE] is treated as a normal end; the chat command owns user-facing truncation messaging.
53
148
  }
@@ -2,7 +2,7 @@ import { ENDPOINTS } from "../api/constants.js";
2
2
  import { buildBroadSearchRequest, } from "../api/search.js";
3
3
  import { chooseMode, emit } from "../output/render.js";
4
4
  import { renderBroadSearch } from "../output/pretty/broadSearch.js";
5
- import { makeClient, parseIntOpt } from "./utils.js";
5
+ import { makeClient, parseCsvOpt, parseIntOpt } from "./utils.js";
6
6
  export function registerBroadSearch(program) {
7
7
  program.command("broad-search")
8
8
  .alias("broad")
@@ -11,15 +11,15 @@ export function registerBroadSearch(program) {
11
11
  .option("--max-queries <n>", "decompose into up to N sub-queries (1-30; default 5, raise toward 30 for surveys/research)", parseIntOpt("--max-queries"))
12
12
  .option("--topic <t>", "general|news")
13
13
  .option("-n, --count <n>", "results per sub-query 1-100", parseIntOpt("--count"))
14
- .option("--include-domains <list>", "comma list", (v) => v.split(","))
15
- .option("--exclude-domains <list>", "comma list", (v) => v.split(","))
16
- .option("--include-text <list>", "comma list", (v) => v.split(","))
17
- .option("--exclude-text <list>", "comma list", (v) => v.split(","))
14
+ .option("--include-domains <list>", "comma list", parseCsvOpt("--include-domains"))
15
+ .option("--exclude-domains <list>", "comma list", parseCsvOpt("--exclude-domains"))
16
+ .option("--include-text <list>", "comma list", parseCsvOpt("--include-text"))
17
+ .option("--exclude-text <list>", "comma list", parseCsvOpt("--exclude-text"))
18
18
  .option("--time-basis <b>", "auto|published|crawled").option("--time-range <r>", "day|week|month|year (or d|w|m|y)")
19
19
  .option("--start-time <when>", "YYYY-MM-DD or ISO datetime (e.g. 2024-01-01T00:00:00Z)")
20
20
  .option("--end-time <when>", "YYYY-MM-DD or ISO datetime (e.g. 2024-12-31T23:59:59Z)")
21
21
  .option("--format <f>", "text|markdown").option("--safesearch <s>", "off|strict")
22
- .option("--language <list>", "ISO 639-1 codes, comma-separated, e.g. en,ja", (v) => v.split(","))
22
+ .option("--language <list>", "ISO 639-1 codes, comma-separated, e.g. en,ja", parseCsvOpt("--language"))
23
23
  .option("--highlight").option("--highlight-max-tokens <n>", "max tokens per highlight", parseIntOpt("--highlight-max-tokens"))
24
24
  .option("--full-content").option("--full-content-max-tokens <n>", "max tokens per result", parseIntOpt("--full-content-max-tokens"))
25
25
  .option("--images")
@@ -3,11 +3,10 @@ import { ENDPOINTS } from "../api/constants.js";
3
3
  import { buildChatRequest, } from "../api/chat.js";
4
4
  import pc from "picocolors";
5
5
  import { parseSSE } from "../api/sse.js";
6
- import { OctenValidationError } from "../api/errors.js";
6
+ import { errorMessage, OctenStreamError, OctenValidationError } from "../api/errors.js";
7
7
  import { chooseMode, emit } from "../output/render.js";
8
8
  import { renderChat } from "../output/pretty/chat.js";
9
- import { makeClient, parseIntOpt, parseFloatOpt } from "./utils.js";
10
- const splitList = (v) => v.split(",").map((s) => s.trim()).filter(Boolean);
9
+ import { makeClient, parseCsvOpt, parseIntOpt, parseFloatOpt } from "./utils.js";
11
10
  /**
12
11
  * Drive an interactive chat REPL until the input closes (EOF, /exit, /quit).
13
12
  * `send` performs one round-trip given the running history and returns the reply.
@@ -85,17 +84,17 @@ export function registerChat(program) {
85
84
  .option("--search-max-queries <n>", "octen_broad_search: max sub-queries (1-30, default 5)", parseIntOpt("--search-max-queries"))
86
85
  .option("--search-topic <t>", "search tools: general|news")
87
86
  .option("--search-count <n>", "search tools: results per search (1-100)", parseIntOpt("--search-count"))
88
- .option("--search-include-domains <list>", "search tools: comma-separated domains to include", splitList)
89
- .option("--search-exclude-domains <list>", "search tools: comma-separated domains to exclude", splitList)
90
- .option("--search-include-text <list>", "search tools: comma-separated phrases to require (max 5)", splitList)
91
- .option("--search-exclude-text <list>", "search tools: comma-separated phrases to exclude (max 5)", splitList)
87
+ .option("--search-include-domains <list>", "search tools: comma-separated domains to include", parseCsvOpt("--search-include-domains"))
88
+ .option("--search-exclude-domains <list>", "search tools: comma-separated domains to exclude", parseCsvOpt("--search-exclude-domains"))
89
+ .option("--search-include-text <list>", "search tools: comma-separated phrases to require (max 5)", parseCsvOpt("--search-include-text"))
90
+ .option("--search-exclude-text <list>", "search tools: comma-separated phrases to exclude (max 5)", parseCsvOpt("--search-exclude-text"))
92
91
  .option("--search-time-basis <b>", "search tools: auto|published|crawled")
93
92
  .option("--search-time-range <r>", "search tools: day|week|month|year (or d|w|m|y)")
94
93
  .option("--search-start-time <when>", "search tools: start time filter")
95
94
  .option("--search-end-time <when>", "search tools: end time filter")
96
95
  .option("--search-format <f>", "search tools: markdown|text")
97
96
  .option("--search-safesearch <s>", "search tools: off|strict")
98
- .option("--search-language <list>", "search tools: ISO 639-1 codes, comma-separated, e.g. en,ja", splitList)
97
+ .option("--search-language <list>", "search tools: ISO 639-1 codes, comma-separated, e.g. en,ja", parseCsvOpt("--search-language"))
99
98
  .option("--search-include-images", "search tools: include image results")
100
99
  .option("--search-full-content", "search tools: include full page content")
101
100
  .option("--search-full-content-max-tokens <n>", "search tools: max tokens for full content", parseIntOpt("--search-full-content-max-tokens"))
@@ -205,6 +204,11 @@ export function registerChat(program) {
205
204
  const sources = [];
206
205
  for await (const ev of parseSSE(httpRes)) {
207
206
  const e = ev;
207
+ // A typed error event ends the turn as a failure. Content already
208
+ // written to stdout stays; the non-zero exit is what callers check.
209
+ if (e.type === "error" || e.error != null) {
210
+ throw new OctenStreamError(errorMessage(e.error ?? e, "stream returned an error"));
211
+ }
208
212
  if (e.type === "search_done") {
209
213
  if (!noted) {
210
214
  process.stderr.write("(web search complete)\n");
@@ -5,6 +5,7 @@ import { installMcp } from "../mcp/install.js";
5
5
  import { mcpStatus } from "../mcp/detect.js";
6
6
  import { resolveApiKey } from "../config/resolve.js";
7
7
  import { isClientInstalled } from "../util/detectClient.js";
8
+ import { parseScopeOpt } from "./utils.js";
8
9
  import { quotePath } from "../util/quotePath.js";
9
10
  // Exported so tests can call with injected dirs
10
11
  export function registerConfigureMcp(program, internal = {}) {
@@ -18,13 +19,14 @@ export function registerConfigureMcp(program, internal = {}) {
18
19
  .option("--windsurf", "configure Windsurf")
19
20
  .option("--vscode", "configure VS Code")
20
21
  .option("--codex", "configure Codex")
21
- .option("--scope <s>", "config scope: user | project (default: user)", "user")
22
+ .option("--scope <s>", "config scope: user | project (default: user)", parseScopeOpt("--scope"), "user")
22
23
  .option("--pin <ver>", "pin octen-mcp to a specific version, e.g. 0.2.1")
23
24
  .option("--force", "configure even if the client is not detected")
24
25
  .action(async (_opts, command) => {
25
26
  const g = command.optsWithGlobals();
26
27
  const opts = command.opts();
27
- const scope = (opts.scope === "project" ? "project" : "user");
28
+ // Parsed and validated by parseScopeOpt at option-parse time.
29
+ const scope = opts.scope;
28
30
  const pin = opts.pin;
29
31
  // Resolve API key — tolerate missing
30
32
  let key;
@@ -9,6 +9,7 @@ import { setClientEnvKey } from "../skills/setkey.js";
9
9
  import { OctenValidationError } from "../api/errors.js";
10
10
  import { isClientInstalled } from "../util/detectClient.js";
11
11
  import { quotePath } from "../util/quotePath.js";
12
+ import { parseCsvOpt, parseScopeOpt } from "./utils.js";
12
13
  // Exported so tests can call with injected dirs
13
14
  export function registerConfigureSkills(program, internal = {}) {
14
15
  program
@@ -22,8 +23,8 @@ export function registerConfigureSkills(program, internal = {}) {
22
23
  .option("--openclaw", "install into OpenClaw")
23
24
  .option("--hermes", "install into Hermes")
24
25
  .option("--skills-dir <path>", "use a custom skills source directory")
25
- .option("--scope <s>", "config scope: user | project (default: user)", "user")
26
- .option("--only <names>", "comma-separated list of skill names to install (e.g. octen-search,octen-design)")
26
+ .option("--scope <s>", "config scope: user | project (default: user)", parseScopeOpt("--scope"), "user")
27
+ .option("--only <names>", "comma-separated list of skill names to install (e.g. octen-search,octen-design)", parseCsvOpt("--only"))
27
28
  .option("--ref <ref>", "upstream git ref to fetch skills from", "main")
28
29
  .option("--bundled", "force use of bundled (vendored) skills — no network")
29
30
  .option("--offline", "alias for --bundled")
@@ -31,12 +32,12 @@ export function registerConfigureSkills(program, internal = {}) {
31
32
  .option("--force", "configure even if the client is not detected")
32
33
  .action(async (_opts, command) => {
33
34
  const opts = command.opts();
34
- const scope = (opts.scope === "project" ? "project" : "user");
35
+ // Parsed and validated by parseScopeOpt at option-parse time.
36
+ const scope = opts.scope;
35
37
  const ref = opts.ref;
36
38
  const offline = !!(opts.bundled || opts.offline);
37
- const only = opts.only
38
- ? opts.only.split(",").map((s) => s.trim()).filter(Boolean)
39
- : undefined;
39
+ // parseCsvOpt already trimmed the names and rejected an all-empty list.
40
+ const only = opts.only;
40
41
  const home = internal.home ?? os.homedir();
41
42
  const cwd = internal.cwd ?? process.cwd();
42
43
  const isInstalled = internal.isInstalled ?? ((id) => isClientInstalled(id, { home }));
@@ -2,7 +2,7 @@ import { ENDPOINTS } from "../api/constants.js";
2
2
  import { buildImageSearchRequest, } from "../api/mediaSearch.js";
3
3
  import { chooseMode, emit } from "../output/render.js";
4
4
  import { renderImageSearch } from "../output/pretty/imageSearch.js";
5
- import { makeClient, parseIntOpt } from "./utils.js";
5
+ import { makeClient, parseCsvOpt, parseIntOpt } from "./utils.js";
6
6
  export function registerImageSearch(program) {
7
7
  program
8
8
  .command("image-search")
@@ -11,8 +11,8 @@ export function registerImageSearch(program) {
11
11
  .option("--image <url|path>", "image input: public URL or local file path")
12
12
  .option("--topic <t>", "general|design")
13
13
  .option("-n, --count <n>", "results 1-10", parseIntOpt("--count"))
14
- .option("--include-domains <list>", "comma list", (v) => v.split(","))
15
- .option("--exclude-domains <list>", "comma list", (v) => v.split(","))
14
+ .option("--include-domains <list>", "comma list", parseCsvOpt("--include-domains"))
15
+ .option("--exclude-domains <list>", "comma list", parseCsvOpt("--exclude-domains"))
16
16
  .option("--safesearch <s>", "off|strict")
17
17
  .option("--html-snippet", "include HTML snippet for each result")
18
18
  .option("--html-snippet-max-tokens <n>", "max tokens per HTML snippet", parseIntOpt("--html-snippet-max-tokens"))
@@ -5,6 +5,7 @@ import { SKILL_CLIENTS } from "../skills/clients.js";
5
5
  import { removeMcp } from "../mcp/install.js";
6
6
  import { removeSkills } from "../skills/install.js";
7
7
  import { quotePath } from "../util/quotePath.js";
8
+ import { parseScopeOpt } from "./utils.js";
8
9
  // Maps CLI flag name → client id (shared across both registries)
9
10
  const CLIENT_FLAG_MAP = {
10
11
  claudeCode: "claude-code",
@@ -31,12 +32,13 @@ export function registerReset(program, internal = {}) {
31
32
  .option("--codex", "target Codex")
32
33
  .option("--openclaw", "target OpenClaw")
33
34
  .option("--hermes", "target Hermes")
34
- .option("--scope <s>", "config scope: user | project (default: user)", "user")
35
+ .option("--scope <s>", "config scope: user | project (default: user)", parseScopeOpt("--scope"), "user")
35
36
  .action((_opts, command) => {
36
37
  const opts = command.opts();
37
38
  const home = internal.home ?? os.homedir();
38
39
  const cwd = internal.cwd ?? process.cwd();
39
- const scope = (opts.scope === "project" ? "project" : "user");
40
+ // Parsed and validated by parseScopeOpt at option-parse time.
41
+ const scope = opts.scope;
40
42
  const installOpts = { hasClaudeCli: internal.hasClaudeCli };
41
43
  // Surface selection
42
44
  const doMcp = opts.all ? true : !!opts.mcp;
@@ -2,21 +2,21 @@ import { ENDPOINTS } from "../api/constants.js";
2
2
  import { buildSearchRequest } from "../api/search.js";
3
3
  import { chooseMode, emit } from "../output/render.js";
4
4
  import { renderSearch } from "../output/pretty/search.js";
5
- import { makeClient, parseIntOpt } from "./utils.js";
5
+ import { makeClient, parseCsvOpt, parseIntOpt } from "./utils.js";
6
6
  export function registerSearch(program, fixedTopic) {
7
7
  const cmd = program.command(fixedTopic ?? "search")
8
8
  .argument("<query...>", "search query")
9
9
  .description(fixedTopic ? "News-focused web search" : "Search the live web")
10
10
  .option("-n, --count <n>", "results 1-100", parseIntOpt("--count"))
11
- .option("--include-domains <list>", "comma list", (v) => v.split(","))
12
- .option("--exclude-domains <list>", "comma list", (v) => v.split(","))
13
- .option("--include-text <list>", "comma list", (v) => v.split(","))
14
- .option("--exclude-text <list>", "comma list", (v) => v.split(","))
11
+ .option("--include-domains <list>", "comma list", parseCsvOpt("--include-domains"))
12
+ .option("--exclude-domains <list>", "comma list", parseCsvOpt("--exclude-domains"))
13
+ .option("--include-text <list>", "comma list", parseCsvOpt("--include-text"))
14
+ .option("--exclude-text <list>", "comma list", parseCsvOpt("--exclude-text"))
15
15
  .option("--time-basis <b>", "auto|published|crawled").option("--time-range <r>", "day|week|month|year (or d|w|m|y)")
16
16
  .option("--start-time <when>", "YYYY-MM-DD or ISO datetime (e.g. 2024-01-01T00:00:00Z)")
17
17
  .option("--end-time <when>", "YYYY-MM-DD or ISO datetime (e.g. 2024-12-31T23:59:59Z)")
18
18
  .option("--format <f>", "text|markdown").option("--safesearch <s>", "off|strict")
19
- .option("--language <list>", "ISO 639-1 codes, comma-separated, e.g. en,ja", (v) => v.split(","))
19
+ .option("--language <list>", "ISO 639-1 codes, comma-separated, e.g. en,ja", parseCsvOpt("--language"))
20
20
  .option("--highlight").option("--highlight-max-tokens <n>", "max tokens per highlight", parseIntOpt("--highlight-max-tokens"))
21
21
  .option("--full-content").option("--full-content-max-tokens <n>", "max tokens per result", parseIntOpt("--full-content-max-tokens"))
22
22
  .option("--images");
@@ -4,7 +4,26 @@ export declare function makeClient(g: {
4
4
  apiKey?: string;
5
5
  baseUrl?: string;
6
6
  }): OctenClient;
7
- /** Commander option parser for integer flags that errors clearly on non-integers. */
7
+ /**
8
+ * Commander option parser for integer flags. Lexical only: a value that is not
9
+ * exactly an integer is rejected rather than truncated, so `1.5`, `2junk` and
10
+ * `1e2` name themselves instead of silently becoming `1`, `2` and `1`. Range
11
+ * checks stay in the request builders, which own the published limits.
12
+ */
8
13
  export declare const parseIntOpt: (name: string) => (v: string) => number;
9
- /** Commander option parser for float flags that errors clearly on non-numbers. */
14
+ /** Commander option parser for float flags. Whole-string match, finite result only. */
10
15
  export declare const parseFloatOpt: (name: string) => (v: string) => number;
16
+ /**
17
+ * Commander option parser for comma-separated list flags. Each item is trimmed
18
+ * and empty items are dropped; a list with nothing left is an error rather than
19
+ * a `[""]` or `[]` that would reach the API as a filter nobody asked for.
20
+ */
21
+ export declare const parseCsvOpt: (name: string) => (v: string) => string[];
22
+ export declare const SCOPE_OPTIONS: readonly ["user", "project"];
23
+ export type ConfigScope = (typeof SCOPE_OPTIONS)[number];
24
+ /**
25
+ * Commander option parser for `--scope`. An unknown scope is an error: coercing
26
+ * it to `user` would write a config file to a location the caller did not ask
27
+ * for, and `reset` would then delete from the wrong one.
28
+ */
29
+ export declare const parseScopeOpt: (name: string) => (v: string) => ConfigScope;
@@ -8,17 +8,54 @@ export function makeClient(g) {
8
8
  baseUrl: resolveBaseUrl(g.baseUrl, process.env),
9
9
  });
10
10
  }
11
- /** Commander option parser for integer flags that errors clearly on non-integers. */
11
+ /** Optional sign followed by decimal digits — nothing else. */
12
+ const INTEGER = /^-?\d+$/;
13
+ /** Decimal, fractional or exponent notation, whole-string. Rejects hex and trailing garbage. */
14
+ const DECIMAL = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
15
+ /**
16
+ * Commander option parser for integer flags. Lexical only: a value that is not
17
+ * exactly an integer is rejected rather than truncated, so `1.5`, `2junk` and
18
+ * `1e2` name themselves instead of silently becoming `1`, `2` and `1`. Range
19
+ * checks stay in the request builders, which own the published limits.
20
+ */
12
21
  export const parseIntOpt = (name) => (v) => {
13
- const n = parseInt(v, 10);
14
- if (Number.isNaN(n))
22
+ if (!INTEGER.test(v))
15
23
  throw new OctenValidationError(`${name} must be an integer`);
24
+ const n = Number(v);
25
+ if (!Number.isSafeInteger(n))
26
+ throw new OctenValidationError(`${name} must be a safe integer`);
16
27
  return n;
17
28
  };
18
- /** Commander option parser for float flags that errors clearly on non-numbers. */
29
+ /** Commander option parser for float flags. Whole-string match, finite result only. */
19
30
  export const parseFloatOpt = (name) => (v) => {
20
- const n = parseFloat(v);
21
- if (Number.isNaN(n))
31
+ if (!DECIMAL.test(v))
32
+ throw new OctenValidationError(`${name} must be a number`);
33
+ const n = Number(v);
34
+ if (!Number.isFinite(n))
22
35
  throw new OctenValidationError(`${name} must be a number`);
23
36
  return n;
24
37
  };
38
+ /**
39
+ * Commander option parser for comma-separated list flags. Each item is trimmed
40
+ * and empty items are dropped; a list with nothing left is an error rather than
41
+ * a `[""]` or `[]` that would reach the API as a filter nobody asked for.
42
+ */
43
+ export const parseCsvOpt = (name) => (v) => {
44
+ const values = v.split(",").map((item) => item.trim()).filter(Boolean);
45
+ if (values.length === 0) {
46
+ throw new OctenValidationError(`${name} must contain at least one non-empty value`);
47
+ }
48
+ return values;
49
+ };
50
+ export const SCOPE_OPTIONS = ["user", "project"];
51
+ /**
52
+ * Commander option parser for `--scope`. An unknown scope is an error: coercing
53
+ * it to `user` would write a config file to a location the caller did not ask
54
+ * for, and `reset` would then delete from the wrong one.
55
+ */
56
+ export const parseScopeOpt = (name) => (v) => {
57
+ if (!SCOPE_OPTIONS.includes(v)) {
58
+ throw new OctenValidationError(`${name} must be one of: ${SCOPE_OPTIONS.join(", ")}`);
59
+ }
60
+ return v;
61
+ };
@@ -50,9 +50,13 @@ export const MCP_CLIENTS = [
50
50
  id: "codex",
51
51
  label: "Codex",
52
52
  format: "toml",
53
- supportsProject: false,
54
- pathFor(_scope, home, _cwd) {
55
- return join(home, ".codex/config.toml");
53
+ // Codex reads a project-level .codex/config.toml (MCP servers included) in a
54
+ // repository it has been told to trust, so project scope has a real target.
55
+ supportsProject: true,
56
+ pathFor(scope, home, cwd) {
57
+ return scope === "project"
58
+ ? join(cwd, ".codex/config.toml")
59
+ : join(home, ".codex/config.toml");
56
60
  },
57
61
  },
58
62
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octen.ai/cli",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Command-line tool for Octen — web search, extract, chat, embeddings, and one-command MCP/Skills setup.",
5
5
  "type": "module",
6
6
  "license": "MIT",