@octen.ai/cli 0.1.6 → 0.1.7

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
@@ -142,11 +142,16 @@ octen configure-skills --all --offline
142
142
 
143
143
  # Fetch from a specific git ref
144
144
  octen configure-skills --claude-code --ref v0.3.0
145
+
146
+ # Also write OCTEN_API_KEY into the client's env config
147
+ octen configure-skills --claude-code --set-key --api-key <key>
145
148
  ```
146
149
 
147
150
  Supported clients: Claude Code, Cursor, Codex, OpenClaw, Hermes.
148
151
 
149
- Options: `--all`, `--claude-code`, `--cursor`, `--codex`, `--openclaw`, `--hermes`, `--scope` (user|project), `--ref <ref>` (default: main), `--bundled`/`--offline` (use vendored skills), `--only <names>` (comma-separated skill names), `--skills-dir <path>` (custom source directory).
152
+ `--set-key` also writes OCTEN_API_KEY into the client's env config (Claude Code `~/.claude/settings.json`, Codex `config.toml`, OpenClaw `.env`); Cursor/Hermes print a shell-profile hint. The key comes from `--api-key` or the `OCTEN_API_KEY` environment variable.
153
+
154
+ Options: `--all`, `--claude-code`, `--cursor`, `--codex`, `--openclaw`, `--hermes`, `--scope` (user|project), `--ref <ref>` (default: main), `--bundled`/`--offline` (use vendored skills), `--only <names>` (comma-separated skill names), `--skills-dir <path>` (custom source directory), `--set-key` (write OCTEN_API_KEY into the client's env config).
150
155
 
151
156
  Run without flags to show installed skills per client.
152
157
 
@@ -1,5 +1,5 @@
1
1
  import { DEFAULT_BASE_URL, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT_MS, ENDPOINTS } from "./constants.js";
2
- import { OctenAPIError, OctenAuthError, OctenTimeoutError } from "./errors.js";
2
+ import { 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
5
  export class OctenClient {
@@ -72,7 +72,9 @@ export class OctenClient {
72
72
  await sleep(this.retryBaseMs * 2 ** attempt);
73
73
  continue;
74
74
  }
75
- throw lastErr;
75
+ // Out of retries on a non-Octen, non-abort error: surface the underlying network cause.
76
+ const cause = e?.cause?.code ?? e?.cause?.message ?? e.message;
77
+ throw new OctenNetworkError(`network error reaching ${this.baseUrl}: ${cause}`);
76
78
  }
77
79
  finally {
78
80
  clearTimeout(t);
@@ -104,6 +106,14 @@ export class OctenClient {
104
106
  }
105
107
  return res;
106
108
  }
109
+ catch (e) {
110
+ if (e instanceof OctenAPIError || e instanceof OctenAuthError)
111
+ throw e;
112
+ if (e.name === "AbortError")
113
+ throw new OctenTimeoutError("request timed out");
114
+ const cause = e?.cause?.code ?? e?.cause?.message ?? e.message;
115
+ throw new OctenNetworkError(`network error reaching ${this.baseUrl}: ${cause}`);
116
+ }
107
117
  finally {
108
118
  clearTimeout(t);
109
119
  }
@@ -6,6 +6,8 @@ export declare class OctenValidationError extends OctenError {
6
6
  }
7
7
  export declare class OctenTimeoutError extends OctenError {
8
8
  }
9
+ export declare class OctenNetworkError extends OctenError {
10
+ }
9
11
  export declare class OctenAPIError extends OctenError {
10
12
  status: number;
11
13
  body?: unknown | undefined;
@@ -6,6 +6,8 @@ export class OctenValidationError extends OctenError {
6
6
  }
7
7
  export class OctenTimeoutError extends OctenError {
8
8
  }
9
+ export class OctenNetworkError extends OctenError {
10
+ }
9
11
  export class OctenAPIError extends OctenError {
10
12
  status;
11
13
  body;
@@ -5,6 +5,8 @@ import pc from "picocolors";
5
5
  import { SKILL_CLIENTS } from "../skills/clients.js";
6
6
  import { resolveSkillsDir } from "../skills/source.js";
7
7
  import { installSkills, skillStatus } from "../skills/install.js";
8
+ import { setClientEnvKey } from "../skills/setkey.js";
9
+ import { OctenValidationError } from "../api/errors.js";
8
10
  // Exported so tests can call with injected dirs
9
11
  export function registerConfigureSkills(program, internal = {}) {
10
12
  program
@@ -22,6 +24,7 @@ export function registerConfigureSkills(program, internal = {}) {
22
24
  .option("--ref <ref>", "upstream git ref to fetch skills from", "main")
23
25
  .option("--bundled", "force use of bundled (vendored) skills — no network")
24
26
  .option("--offline", "alias for --bundled")
27
+ .option("--set-key", "also write OCTEN_API_KEY into each selected client's env config")
25
28
  .action(async (_opts, command) => {
26
29
  const opts = command.opts();
27
30
  const scope = (opts.scope === "project" ? "project" : "user");
@@ -112,7 +115,25 @@ export function registerConfigureSkills(program, internal = {}) {
112
115
  if (anyFailed) {
113
116
  process.exitCode = 1;
114
117
  }
115
- // Print API key setup reminder
116
- process.stdout.write("\nSet OCTEN_API_KEY in each client's environment — see https://octen.ai\n");
118
+ if (opts.setKey) {
119
+ const g = command.optsWithGlobals();
120
+ const key = g.apiKey || process.env.OCTEN_API_KEY;
121
+ if (!key) {
122
+ throw new OctenValidationError("--set-key needs a key: pass --api-key or set OCTEN_API_KEY");
123
+ }
124
+ for (const client of selected) {
125
+ const result = setClientEnvKey(client.id, key, scope, home, cwd);
126
+ if (result.written) {
127
+ process.stdout.write(`set OCTEN_API_KEY in ${client.label} (${result.path})\n`);
128
+ }
129
+ else {
130
+ process.stdout.write(`${client.label}: ${result.hint}\n`);
131
+ }
132
+ }
133
+ }
134
+ else {
135
+ // Print API key setup reminder
136
+ process.stdout.write("\nSet OCTEN_API_KEY in each client's environment — see https://octen.ai\n");
137
+ }
117
138
  });
118
139
  }
@@ -0,0 +1,13 @@
1
+ export type SetKeyResult = {
2
+ clientId: string;
3
+ written: boolean;
4
+ path?: string;
5
+ hint?: string;
6
+ };
7
+ /**
8
+ * Write OCTEN_API_KEY into a client's env configuration, merging with any
9
+ * existing content (never clobbering unrelated keys). Returns whether a file
10
+ * was written; for clients without an env config file, returns a shell-profile
11
+ * hint instead of editing rc files.
12
+ */
13
+ export declare function setClientEnvKey(clientId: string, key: string, scope: "user" | "project", home: string, cwd: string): SetKeyResult;
@@ -0,0 +1,86 @@
1
+ import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { parse, stringify } from "smol-toml";
4
+ import { OctenValidationError } from "../api/errors.js";
5
+ const SHELL_PROFILE_HINT = "Set OCTEN_API_KEY in your shell profile (e.g. ~/.zshrc: export OCTEN_API_KEY=...) or use direnv";
6
+ function readJsonFile(filePath) {
7
+ if (!existsSync(filePath))
8
+ return {};
9
+ const raw = readFileSync(filePath, "utf8").trim();
10
+ if (!raw)
11
+ return {};
12
+ try {
13
+ return JSON.parse(raw);
14
+ }
15
+ catch (e) {
16
+ throw new OctenValidationError(`Config file ${filePath} contains invalid JSON and cannot be edited safely. Fix or remove it, then retry. (${e.message})`);
17
+ }
18
+ }
19
+ function readTomlFile(filePath) {
20
+ if (!existsSync(filePath))
21
+ return {};
22
+ const raw = readFileSync(filePath, "utf8").trim();
23
+ if (!raw)
24
+ return {};
25
+ try {
26
+ return parse(raw);
27
+ }
28
+ catch (e) {
29
+ throw new OctenValidationError(`Config file ${filePath} contains invalid TOML and cannot be edited safely. Fix or remove it, then retry. (${e.message})`);
30
+ }
31
+ }
32
+ /**
33
+ * Write OCTEN_API_KEY into a client's env configuration, merging with any
34
+ * existing content (never clobbering unrelated keys). Returns whether a file
35
+ * was written; for clients without an env config file, returns a shell-profile
36
+ * hint instead of editing rc files.
37
+ */
38
+ export function setClientEnvKey(clientId, key, scope, home, cwd) {
39
+ switch (clientId) {
40
+ case "claude-code": {
41
+ const path = scope === "project"
42
+ ? join(cwd, ".claude/settings.json")
43
+ : join(home, ".claude/settings.json");
44
+ const obj = readJsonFile(path);
45
+ obj.env = {
46
+ ...(obj.env ?? {}),
47
+ OCTEN_API_KEY: key,
48
+ };
49
+ mkdirSync(dirname(path), { recursive: true });
50
+ writeFileSync(path, JSON.stringify(obj, null, 2) + "\n", "utf8");
51
+ return { clientId, written: true, path };
52
+ }
53
+ case "codex": {
54
+ const path = join(home, ".codex/config.toml");
55
+ const obj = readTomlFile(path);
56
+ const policy = (obj.shell_environment_policy ??= {});
57
+ policy.set = {
58
+ ...(policy.set ?? {}),
59
+ OCTEN_API_KEY: key,
60
+ };
61
+ mkdirSync(dirname(path), { recursive: true });
62
+ writeFileSync(path, stringify(obj), "utf8");
63
+ return { clientId, written: true, path };
64
+ }
65
+ case "openclaw": {
66
+ const path = join(home, ".openclaw/.env");
67
+ const raw = existsSync(path) ? readFileSync(path, "utf8") : "";
68
+ const lines = raw === "" ? [] : raw.replace(/\n+$/, "").split("\n");
69
+ let replaced = false;
70
+ for (let i = 0; i < lines.length; i++) {
71
+ if (/^OCTEN_API_KEY=/.test(lines[i])) {
72
+ lines[i] = `OCTEN_API_KEY=${key}`;
73
+ replaced = true;
74
+ break;
75
+ }
76
+ }
77
+ if (!replaced)
78
+ lines.push(`OCTEN_API_KEY=${key}`);
79
+ mkdirSync(dirname(path), { recursive: true });
80
+ writeFileSync(path, lines.join("\n") + "\n", "utf8");
81
+ return { clientId, written: true, path };
82
+ }
83
+ default:
84
+ return { clientId, written: false, hint: SHELL_PROFILE_HINT };
85
+ }
86
+ }
@@ -11,46 +11,64 @@ export async function resolveSkillsDir(o) {
11
11
  }
12
12
  // Validate ref before use in paths/URLs to prevent traversal or malformed URLs.
13
13
  // Must match /^[\w.\/-]+$/ AND must not contain the ".." sequence.
14
+ // (Validated once up-front; a bad ref is a hard error, never retried/fallback.)
14
15
  if (!/^[\w.\/-]+$/.test(o.ref) || o.ref.includes("..")) {
15
16
  throw new OctenValidationError(`invalid ref: ${o.ref}`);
16
17
  }
17
- try {
18
- const fetcher = o.fetchImpl ?? fetch;
19
- const url = SKILLS_REPO_TARBALL(o.ref);
20
- const response = await fetcher(url);
21
- if (!response.ok) {
22
- throw new Error(`HTTP ${response.status} fetching ${url}`);
23
- }
24
- const buffer = Buffer.from(await response.arrayBuffer());
25
- // Write tarball to a collision-resistant temp file for tar.extract (which needs a file path)
26
- const tmpTar = join(tmpdir(), `octen-skills-${randomUUID()}.tar.gz`);
27
- writeFileSync(tmpTar, buffer);
28
- // Extract into a clean cacheDir/<ref>/ (clean so a prior run, possibly from a
29
- // differently-named archive root, can't leave a stale dir behind).
30
- const extractDir = join(o.cacheDir, o.ref);
31
- rmSync(extractDir, { recursive: true, force: true });
32
- mkdirSync(extractDir, { recursive: true });
18
+ // Retry transient fetch/extract failures (e.g. a single "fetch failed" blip)
19
+ // a few times before falling back to bundled skills.
20
+ const MAX_ATTEMPTS = 3;
21
+ let lastErr;
22
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
33
23
  try {
34
- await tar.extract({ file: tmpTar, cwd: extractDir });
35
- }
36
- finally {
37
- rmSync(tmpTar, { force: true });
24
+ return await fetchRemoteSkills(o);
38
25
  }
39
- // GitHub archive tarballs nest everything under a single top-level dir named
40
- // <repo>-<ref>. The repo can be renamed (the download follows GitHub's
41
- // redirect), so DISCOVER that root dir rather than hardcoding the repo name.
42
- const roots = readdirSync(extractDir, { withFileTypes: true }).filter((e) => e.isDirectory());
43
- if (roots.length !== 1) {
44
- throw new Error(`unexpected archive layout: ${roots.length} top-level dirs`);
26
+ catch (err) {
27
+ lastErr = err;
28
+ if (attempt < MAX_ATTEMPTS) {
29
+ await sleep(500 * attempt);
30
+ }
45
31
  }
46
- const skillsDir = join(extractDir, roots[0].name, "skills");
47
- // Verify the skills/ subdir exists
48
- readdirSync(skillsDir);
49
- return { dir: skillsDir, source: "remote" };
50
32
  }
51
- catch (err) {
52
- const msg = err instanceof Error ? err.message : String(err);
53
- process.stderr.write(`warning: failed to fetch skills from GitHub (${msg}) — using bundled fallback\n`);
54
- return { dir: o.bundledDir, source: "bundled" };
33
+ const cause = lastErr?.cause?.code ??
34
+ lastErr?.cause?.message ??
35
+ (lastErr instanceof Error ? lastErr.message : String(lastErr));
36
+ process.stderr.write(`warning: failed to fetch skills from GitHub (${cause}) — using bundled fallback\n`);
37
+ return { dir: o.bundledDir, source: "bundled" };
38
+ }
39
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
40
+ /** One attempt: fetch the tarball, extract it, and locate the skills/ dir. */
41
+ async function fetchRemoteSkills(o) {
42
+ const fetcher = o.fetchImpl ?? fetch;
43
+ const url = SKILLS_REPO_TARBALL(o.ref);
44
+ const response = await fetcher(url);
45
+ if (!response.ok) {
46
+ throw new Error(`HTTP ${response.status} fetching ${url}`);
47
+ }
48
+ const buffer = Buffer.from(await response.arrayBuffer());
49
+ // Write tarball to a collision-resistant temp file for tar.extract (which needs a file path)
50
+ const tmpTar = join(tmpdir(), `octen-skills-${randomUUID()}.tar.gz`);
51
+ writeFileSync(tmpTar, buffer);
52
+ // Extract into a clean cacheDir/<ref>/ (clean so a prior run, possibly from a
53
+ // differently-named archive root, can't leave a stale dir behind).
54
+ const extractDir = join(o.cacheDir, o.ref);
55
+ rmSync(extractDir, { recursive: true, force: true });
56
+ mkdirSync(extractDir, { recursive: true });
57
+ try {
58
+ await tar.extract({ file: tmpTar, cwd: extractDir });
59
+ }
60
+ finally {
61
+ rmSync(tmpTar, { force: true });
62
+ }
63
+ // GitHub archive tarballs nest everything under a single top-level dir named
64
+ // <repo>-<ref>. The repo can be renamed (the download follows GitHub's
65
+ // redirect), so DISCOVER that root dir rather than hardcoding the repo name.
66
+ const roots = readdirSync(extractDir, { withFileTypes: true }).filter((e) => e.isDirectory());
67
+ if (roots.length !== 1) {
68
+ throw new Error(`unexpected archive layout: ${roots.length} top-level dirs`);
55
69
  }
70
+ const skillsDir = join(extractDir, roots[0].name, "skills");
71
+ // Verify the skills/ subdir exists
72
+ readdirSync(skillsDir);
73
+ return { dir: skillsDir, source: "remote" };
56
74
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octen.ai/cli",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
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",