@octen.ai/cli 0.8.0 → 0.10.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 (63) hide show
  1. package/README.md +272 -6
  2. package/dist/api/constants.d.ts +6 -0
  3. package/dist/api/constants.js +3 -0
  4. package/dist/api/errors.d.ts +15 -0
  5. package/dist/api/errors.js +15 -0
  6. package/dist/api/extract.d.ts +57 -0
  7. package/dist/api/extract.js +36 -1
  8. package/dist/auth/constants.d.ts +47 -0
  9. package/dist/auth/constants.js +89 -0
  10. package/dist/auth/exchange.d.ts +74 -0
  11. package/dist/auth/exchange.js +124 -0
  12. package/dist/auth/login.d.ts +64 -0
  13. package/dist/auth/login.js +163 -0
  14. package/dist/auth/loopback.d.ts +32 -0
  15. package/dist/auth/loopback.js +95 -0
  16. package/dist/auth/oauthClient.d.ts +70 -0
  17. package/dist/auth/oauthClient.js +136 -0
  18. package/dist/auth/pkce.d.ts +6 -0
  19. package/dist/auth/pkce.js +13 -0
  20. package/dist/auth/revoke.d.ts +58 -0
  21. package/dist/auth/revoke.js +91 -0
  22. package/dist/auth/store.d.ts +34 -0
  23. package/dist/auth/store.js +149 -0
  24. package/dist/cli.js +6 -0
  25. package/dist/commands/configureMcp.js +34 -18
  26. package/dist/commands/configureSkills.js +18 -4
  27. package/dist/commands/extract.js +9 -5
  28. package/dist/commands/login.d.ts +49 -0
  29. package/dist/commands/login.js +161 -0
  30. package/dist/commands/logout.d.ts +46 -0
  31. package/dist/commands/logout.js +142 -0
  32. package/dist/commands/reset.js +39 -3
  33. package/dist/commands/utils.d.ts +9 -0
  34. package/dist/commands/utils.js +16 -0
  35. package/dist/commands/whoami.d.ts +27 -0
  36. package/dist/commands/whoami.js +109 -0
  37. package/dist/config/resolve.d.ts +44 -1
  38. package/dist/config/resolve.js +80 -5
  39. package/dist/mcp/install.js +15 -2
  40. package/dist/mcp/write.js +24 -3
  41. package/dist/output/pretty/extract.d.ts +5 -1
  42. package/dist/output/pretty/extract.js +64 -4
  43. package/dist/output/pretty/whoami.d.ts +59 -0
  44. package/dist/output/pretty/whoami.js +103 -0
  45. package/dist/skills/setkey.js +5 -4
  46. package/dist/util/secretFile.d.ts +24 -0
  47. package/dist/util/secretFile.js +35 -0
  48. package/package.json +1 -1
  49. package/skills/manifest.json +5 -1
  50. package/skills/octen-design/SKILL.md +32 -9
  51. package/skills/octen-design/agents/openai.yaml +4 -0
  52. package/skills/octen-design/scripts/search.py +326 -71
  53. package/skills/octen-design/scripts/tests/test_search.py +449 -0
  54. package/skills/octen-extract/SKILL.md +178 -0
  55. package/skills/octen-extract/agents/openai.yaml +4 -0
  56. package/skills/octen-image-search/SKILL.md +125 -0
  57. package/skills/octen-image-search/agents/openai.yaml +4 -0
  58. package/skills/octen-search/SKILL.md +82 -3
  59. package/skills/octen-search/agents/openai.yaml +4 -0
  60. package/skills/octen-video-search/SKILL.md +108 -0
  61. package/skills/octen-video-search/agents/openai.yaml +4 -0
  62. package/skills/octen-web-search/SKILL.md +113 -0
  63. package/skills/octen-web-search/agents/openai.yaml +4 -0
@@ -6,7 +6,8 @@ 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
8
  import { setClientEnvKey } from "../skills/setkey.js";
9
- import { OctenValidationError } from "../api/errors.js";
9
+ import { resolveApiKey } from "../config/resolve.js";
10
+ import { OctenValidationError, OctenNoCredentialError } from "../api/errors.js";
10
11
  import { isClientInstalled } from "../util/detectClient.js";
11
12
  import { quotePath } from "../util/quotePath.js";
12
13
  import { parseCsvOpt, parseScopeOpt } from "./utils.js";
@@ -152,9 +153,22 @@ export function registerConfigureSkills(program, internal = {}) {
152
153
  }
153
154
  if (opts.setKey) {
154
155
  const g = command.optsWithGlobals();
155
- const key = g.apiKey || process.env.OCTEN_API_KEY;
156
- if (!key) {
157
- throw new OctenValidationError("--set-key needs a key: pass --api-key or set OCTEN_API_KEY");
156
+ let key;
157
+ try {
158
+ key = resolveApiKey(g.apiKey, process.env, { home });
159
+ }
160
+ catch (err) {
161
+ // ONLY a total absence of credentials becomes the generic "needs a
162
+ // key" message. This used to test `instanceof OctenAuthError`, which
163
+ // also matches expiry and issuer/resource mismatch — so a user with a
164
+ // perfectly good credential and an OCTEN_AUTH_ISSUER override was told
165
+ // to run `octen login`, which cannot fix an OCTEN_AUTH_* override.
166
+ // Those errors already carry a message naming the real problem
167
+ // (resolve.ts's `mismatchMessage` exists for exactly this); rethrow
168
+ // and let it be seen.
169
+ if (!(err instanceof OctenNoCredentialError))
170
+ throw err;
171
+ throw new OctenValidationError("--set-key needs a key: pass --api-key, set OCTEN_API_KEY, or run `octen login`");
158
172
  }
159
173
  for (const client of selected) {
160
174
  const result = setClientEnvKey(client.id, key, scope, home, cwd);
@@ -1,8 +1,8 @@
1
1
  import { ENDPOINTS } from "../api/constants.js";
2
- import { buildExtractRequest } from "../api/extract.js";
2
+ import { buildExtractRequest, extractClientTimeoutMs, } from "../api/extract.js";
3
3
  import { chooseMode, emit } from "../output/render.js";
4
4
  import { renderExtract } from "../output/pretty/extract.js";
5
- import { makeClient, parseIntOpt } from "./utils.js";
5
+ import { makeClient, parseIntOpt, parseLinkScopeOpt } from "./utils.js";
6
6
  export function registerExtract(program) {
7
7
  program
8
8
  .command("extract")
@@ -15,12 +15,16 @@ export function registerExtract(program) {
15
15
  .option("--images", "include images (also returns cover_image when present)")
16
16
  .option("--videos", "include videos")
17
17
  .option("--audio", "include audio")
18
- .option("--full", "print full page content untruncated (pretty mode)")
18
+ .option("--mode <m>", "standard (default, fast/cheap) | advanced (hard sites, 2.5x) | auto (mixed batch)")
19
+ .option("--links [scope]", "include page links; scope prefer_internal (default) | prefer_external", parseLinkScopeOpt("--links"))
20
+ .option("--max-links <n>", "max links per page (1-1000, default 200); implies --links", parseIntOpt("--max-links"))
21
+ .option("--full", "print full page content, links and media untruncated (pretty mode)")
19
22
  .action(async (urls, opts, command) => {
20
23
  const g = command.optsWithGlobals();
21
24
  const client = makeClient(g);
22
25
  const req = buildExtractRequest(urls, opts);
23
- const res = await client.request(ENDPOINTS.extract, req);
24
- emit(res, chooseMode(g, process.stdout.isTTY ?? false), (d) => renderExtract(d, opts.full));
26
+ // Per-call ceiling derived from the per-URL budget; the client default is too tight.
27
+ const res = await client.request(ENDPOINTS.extract, req, extractClientTimeoutMs(opts.fetchTimeout));
28
+ emit(res, chooseMode(g, process.stdout.isTTY ?? false), (d) => renderExtract(d, opts.full, opts.mode));
25
29
  });
26
30
  }
@@ -0,0 +1,49 @@
1
+ import type { Command } from "commander";
2
+ export interface LoginInternalOpts {
3
+ /** Injected home dir (for testing); defaults to os.homedir(). */
4
+ home?: string;
5
+ /** Injected env (for testing); defaults to process.env. */
6
+ env?: NodeJS.ProcessEnv;
7
+ /** Injected fetch (for testing); defaults to global fetch. */
8
+ fetchImpl?: typeof fetch;
9
+ /** Injected browser opener (for testing); defaults to spawning the OS opener. */
10
+ openBrowser?: (url: string, onFailure: (err: unknown) => void) => void;
11
+ }
12
+ /**
13
+ * Build the argv for opening `url` in the platform's default browser. Pure
14
+ * so each platform can be asserted without spawning anything.
15
+ *
16
+ * win32 is `rundll32 url.dll,FileProtocolHandler`, deliberately NOT
17
+ * `cmd /c start`: `cmd` treats `&` as a command separator, and the
18
+ * authorize URL's query string is full of them — the URL would arrive
19
+ * truncated at the first `&`.
20
+ */
21
+ export declare function browserCommand(platform: NodeJS.Platform, url: string): [cmd: string, args: string[]];
22
+ /**
23
+ * Spawn `cmd args` detached and ignored (`stdio: "ignore"`, `unref()`), so
24
+ * the CLI never waits on the child. Reports a failure — sync OR async — via
25
+ * `onFailure` instead of letting it propagate.
26
+ *
27
+ * This is the piece the original implementation got wrong: `spawn()` only
28
+ * throws synchronously for a narrow set of argument-validation failures. A
29
+ * missing binary (ENOENT — the common case: a headless box or a slim
30
+ * container without `xdg-open`, exactly the environment this fallback
31
+ * exists for) is reported asynchronously via the child's `'error'` event.
32
+ * An EventEmitter with no `'error'` listener turns that into an uncaught
33
+ * exception that kills the process — so the listener below is not optional.
34
+ */
35
+ export declare function spawnDetached(cmd: string, args: string[], onFailure: (err: unknown) => void): void;
36
+ /**
37
+ * Open `url` in the platform's default browser. `onFailure` is called for
38
+ * either a synchronous spawn error or (the common real-world case) an
39
+ * asynchronous one, and the caller (`src/auth/login.ts`) routes both to the
40
+ * same "print the URL instead" fallback.
41
+ *
42
+ * `resolveCommand` defaults to `browserCommand` and exists only so a test
43
+ * can drive this real function — real `spawnDetached`, real `spawn`, real
44
+ * `'error'` handling — against a guaranteed-nonexistent command, instead of
45
+ * a real platform opener (`xdg-open`, `open`, `rundll32`) whose presence on
46
+ * the machine running the suite is not something a test controls.
47
+ */
48
+ export declare function openBrowser(url: string, onFailure: (err: unknown) => void, platform?: NodeJS.Platform, resolveCommand?: (platform: NodeJS.Platform, url: string) => [string, string[]]): void;
49
+ export declare function registerLogin(program: Command, internal?: LoginInternalOpts): void;
@@ -0,0 +1,161 @@
1
+ import os from "node:os";
2
+ import { spawn } from "node:child_process";
3
+ import { login } from "../auth/login.js";
4
+ import { CREDENTIALS_VERSION, credentialsPath, readCredentials, writeCredentials } from "../auth/store.js";
5
+ import { assertRange } from "../api/search.js";
6
+ import { parseIntOpt } from "./utils.js";
7
+ /**
8
+ * Build the argv for opening `url` in the platform's default browser. Pure
9
+ * so each platform can be asserted without spawning anything.
10
+ *
11
+ * win32 is `rundll32 url.dll,FileProtocolHandler`, deliberately NOT
12
+ * `cmd /c start`: `cmd` treats `&` as a command separator, and the
13
+ * authorize URL's query string is full of them — the URL would arrive
14
+ * truncated at the first `&`.
15
+ */
16
+ export function browserCommand(platform, url) {
17
+ if (platform === "win32")
18
+ return ["rundll32", ["url.dll,FileProtocolHandler", url]];
19
+ if (platform === "linux")
20
+ return ["xdg-open", [url]];
21
+ return ["open", [url]];
22
+ }
23
+ /**
24
+ * Spawn `cmd args` detached and ignored (`stdio: "ignore"`, `unref()`), so
25
+ * the CLI never waits on the child. Reports a failure — sync OR async — via
26
+ * `onFailure` instead of letting it propagate.
27
+ *
28
+ * This is the piece the original implementation got wrong: `spawn()` only
29
+ * throws synchronously for a narrow set of argument-validation failures. A
30
+ * missing binary (ENOENT — the common case: a headless box or a slim
31
+ * container without `xdg-open`, exactly the environment this fallback
32
+ * exists for) is reported asynchronously via the child's `'error'` event.
33
+ * An EventEmitter with no `'error'` listener turns that into an uncaught
34
+ * exception that kills the process — so the listener below is not optional.
35
+ */
36
+ export function spawnDetached(cmd, args, onFailure) {
37
+ let child;
38
+ try {
39
+ child = spawn(cmd, args, { detached: true, stdio: "ignore" });
40
+ }
41
+ catch (err) {
42
+ onFailure(err);
43
+ return;
44
+ }
45
+ child.on("error", onFailure);
46
+ child.unref();
47
+ }
48
+ /**
49
+ * Open `url` in the platform's default browser. `onFailure` is called for
50
+ * either a synchronous spawn error or (the common real-world case) an
51
+ * asynchronous one, and the caller (`src/auth/login.ts`) routes both to the
52
+ * same "print the URL instead" fallback.
53
+ *
54
+ * `resolveCommand` defaults to `browserCommand` and exists only so a test
55
+ * can drive this real function — real `spawnDetached`, real `spawn`, real
56
+ * `'error'` handling — against a guaranteed-nonexistent command, instead of
57
+ * a real platform opener (`xdg-open`, `open`, `rundll32`) whose presence on
58
+ * the machine running the suite is not something a test controls.
59
+ */
60
+ export function openBrowser(url, onFailure, platform = process.platform, resolveCommand = browserCommand) {
61
+ const [cmd, args] = resolveCommand(platform, url);
62
+ spawnDetached(cmd, args, onFailure);
63
+ }
64
+ /**
65
+ * A credential written while `OCTEN_API_KEY` is exported will never be read
66
+ * by any command: `resolveApiKey` returns the env var before it touches the
67
+ * file (src/config/resolve.ts:31-32). Reporting an unqualified "Logged in"
68
+ * for that would tell the user a browser consent flow accomplished something
69
+ * it did not. Warns on stderr only — stdout keeps carrying just the result,
70
+ * so a script parsing stdout is unaffected — and never echoes either key.
71
+ */
72
+ function warnIfEnvKeyShadows(env) {
73
+ if (!env.OCTEN_API_KEY)
74
+ return;
75
+ process.stderr.write("warning: OCTEN_API_KEY is set in the environment and takes precedence over the stored " +
76
+ "credential, so nothing will use the credential just saved. Unset OCTEN_API_KEY for this " +
77
+ "login to take effect (`octen whoami` shows which source is in effect).\n");
78
+ }
79
+ /**
80
+ * `login --api-key` overwrites whatever is on disk. When that is a
81
+ * `source: "login"` credential, the file being replaced is the only place
82
+ * this machine records its `grantId` — the authorization stays listed in the
83
+ * dashboard and, once the file is gone, nothing here can name it any more
84
+ * — the same stranding `octen logout --local` prints the id to avoid.
85
+ *
86
+ * Costs zero network requests, which is what keeps this branch's contract
87
+ * intact: `--api-key` exists so a machine with no browser and no outbound
88
+ * access to the auth server can still be configured, so it must stay a pure
89
+ * local file operation. Reading the old file before overwriting it is still
90
+ * just a file read; the grant is deliberately NOT revoked here, which the
91
+ * README's "Switching from a browser login to a pasted key" section
92
+ * documents. An unreadable file is tolerated the way `octen logout` tolerates
93
+ * it — there is no grantId to extract from it either way.
94
+ */
95
+ function warnIfOverwritingLoginGrant(home) {
96
+ let existing;
97
+ try {
98
+ existing = readCredentials(home);
99
+ }
100
+ catch {
101
+ return;
102
+ }
103
+ if (existing?.source !== "login")
104
+ return;
105
+ process.stderr.write(`warning: this replaces a browser login. Grant ${existing.grantId} was not revoked — ` +
106
+ "`octen login --api-key` makes no network request. It can still mint a new credential " +
107
+ "without a fresh consent screen; revoke it from the dashboard's authorization list if " +
108
+ "you want to close it out. (Run `octen logout` first to revoke it properly.)\n");
109
+ }
110
+ export function registerLogin(program, internal = {}) {
111
+ program
112
+ .command("login")
113
+ .description("Log in via your browser and store the resulting API key")
114
+ .option("--port <n>", "pin the loopback callback port (for ssh -L forwarding)", parseIntOpt("--port"))
115
+ .option("--no-browser", "print the authorize URL instead of opening it")
116
+ .addHelpText("after", [
117
+ "",
118
+ "Environment:",
119
+ " OCTEN_AUTH_ISSUER authorization server (default: https://auth.octen.ai)",
120
+ " OCTEN_AUTH_RESOURCE token audience (default: https://cli.octen.ai)",
121
+ "",
122
+ " Both are for local development only and must have no trailing slash. A stored",
123
+ " credential minted for a different issuer/resource pair is ignored (never used,",
124
+ " never deleted) — see the README's Auth section.",
125
+ "",
126
+ ].join("\n"))
127
+ .action(async (_opts, command) => {
128
+ const g = command.optsWithGlobals();
129
+ const home = internal.home ?? os.homedir();
130
+ const env = internal.env ?? process.env;
131
+ // --api-key is a separate branch: no loopback server, no network
132
+ // request, just write the file and return. This is the path for CI, a
133
+ // container, or any machine where a browser flow is not possible.
134
+ if (g.apiKey) {
135
+ warnIfOverwritingLoginGrant(home);
136
+ writeCredentials(home, { version: CREDENTIALS_VERSION, source: "api-key", apiKey: g.apiKey });
137
+ process.stdout.write("API key saved.\n");
138
+ warnIfEnvKeyShadows(env);
139
+ return;
140
+ }
141
+ // A bad --port names itself instead of surfacing as Node's own
142
+ // ERR_SOCKET_BAD_PORT, or (for 0) silently picking a random port and
143
+ // quietly defeating the `ssh -L` pinning the flag exists for.
144
+ assertRange("--port", g.port, { min: 1, max: 65535 });
145
+ const { credentials: creds, accountName } = await login({
146
+ home,
147
+ env,
148
+ fetchImpl: internal.fetchImpl,
149
+ openBrowser: internal.openBrowser ?? ((url, onFailure) => openBrowser(url, onFailure)),
150
+ noBrowser: g.browser === false,
151
+ port: g.port,
152
+ });
153
+ // Prefer the server's human-readable name ("Octen family", "Personal")
154
+ // over the raw id, but keep the id as the fallback: the name is optional
155
+ // on the wire, and it is absent both against a server that predates the
156
+ // field and whenever the name could not be loaded.
157
+ const account = creds.source === "login" ? (accountName ?? creds.accountId) : undefined;
158
+ process.stdout.write(`Logged in${account ? ` as ${account}` : ""}. Credentials saved to ${credentialsPath(home)}\n`);
159
+ warnIfEnvKeyShadows(env);
160
+ });
161
+ }
@@ -0,0 +1,46 @@
1
+ import type { Command } from "commander";
2
+ export interface LogoutInternalOpts {
3
+ /** Injected home dir (for testing); defaults to os.homedir(). */
4
+ home?: string;
5
+ /**
6
+ * Injected fetch (for testing); defaults to global fetch. Never invoked
7
+ * for a `source: "api-key"` credential (no grant exists to revoke), when
8
+ * `--local` is passed, or when the stored file is unreadable — all three
9
+ * branches make zero network requests, because in each of them there is
10
+ * either no grant to revoke or no way left to name it.
11
+ */
12
+ fetchImpl?: typeof fetch;
13
+ }
14
+ /**
15
+ * `octen logout` — revoke this device's authorization, then remove the
16
+ * local credential.
17
+ *
18
+ * The copy here is a hard requirement, not polish: this command clears a
19
+ * local file and revokes a *grant* (which only blocks the CLI from silently
20
+ * minting a new credential without a fresh consent screen). It never
21
+ * deactivates the underlying API key — that key is the user's own
22
+ * account-wide, long-lived key, and is very likely also sitting in other
23
+ * machines, production code, and the AI-client configs `octen
24
+ * configure-mcp` wrote. So the output must never claim to have revoked
25
+ * *access*, only "this authorization". Telling a user their access was
26
+ * revoked when the key is still live everywhere else would be the most
27
+ * damaging kind of wrong: they would stop looking for the exposure.
28
+ *
29
+ * Whether a failed revocation should keep or delete the file depends on
30
+ * whether the failure is retriable: `OctenNetworkError` is a transport
31
+ * fault, and a transport fault must never be read as "the credential is
32
+ * invalid" — deleting a working credential because the network was down
33
+ * would leave the user with nothing and no way back without re-consenting.
34
+ * So the file is kept and `--local` is suggested. Every
35
+ * other failure `revokeCliGrant` can throw is `OctenAuthError` from one of
36
+ * three deterministic causes (401/403/400 in revoke.ts) — the stored
37
+ * key is no longer valid, the grant isn't bound to it, or the grant id
38
+ * isn't recognized. All three fail identically on every retry of plain
39
+ * `octen logout`, so keeping the file there would strand the user with
40
+ * `--local` as the only escape hatch (and a lie for the 400 case, where the
41
+ * authorization was already gone). Those branches delete the file and say
42
+ * precisely why revocation didn't happen, printing the `grantId` so the
43
+ * user can still find and clean up the authorization in the dashboard if
44
+ * it's still listed as active there.
45
+ */
46
+ export declare function registerLogout(program: Command, internal?: LogoutInternalOpts): void;
@@ -0,0 +1,142 @@
1
+ import os from "node:os";
2
+ import { readCredentials, deleteCredentials } from "../auth/store.js";
3
+ // The 400 case ("the grant is already gone server-side", so logout's goal
4
+ // is already met) is identified by importing revoke.ts's own constant rather
5
+ // than re-typing its sentence: editing that copy now breaks the build here
6
+ // instead of silently downgrading this branch to the generic 401/403 message
7
+ // with no test failure.
8
+ import { revokeCliGrant, GRANT_NOT_RECOGNIZED_MESSAGE } from "../auth/revoke.js";
9
+ import { OctenNetworkError } from "../api/errors.js";
10
+ /**
11
+ * `octen logout` — revoke this device's authorization, then remove the
12
+ * local credential.
13
+ *
14
+ * The copy here is a hard requirement, not polish: this command clears a
15
+ * local file and revokes a *grant* (which only blocks the CLI from silently
16
+ * minting a new credential without a fresh consent screen). It never
17
+ * deactivates the underlying API key — that key is the user's own
18
+ * account-wide, long-lived key, and is very likely also sitting in other
19
+ * machines, production code, and the AI-client configs `octen
20
+ * configure-mcp` wrote. So the output must never claim to have revoked
21
+ * *access*, only "this authorization". Telling a user their access was
22
+ * revoked when the key is still live everywhere else would be the most
23
+ * damaging kind of wrong: they would stop looking for the exposure.
24
+ *
25
+ * Whether a failed revocation should keep or delete the file depends on
26
+ * whether the failure is retriable: `OctenNetworkError` is a transport
27
+ * fault, and a transport fault must never be read as "the credential is
28
+ * invalid" — deleting a working credential because the network was down
29
+ * would leave the user with nothing and no way back without re-consenting.
30
+ * So the file is kept and `--local` is suggested. Every
31
+ * other failure `revokeCliGrant` can throw is `OctenAuthError` from one of
32
+ * three deterministic causes (401/403/400 in revoke.ts) — the stored
33
+ * key is no longer valid, the grant isn't bound to it, or the grant id
34
+ * isn't recognized. All three fail identically on every retry of plain
35
+ * `octen logout`, so keeping the file there would strand the user with
36
+ * `--local` as the only escape hatch (and a lie for the 400 case, where the
37
+ * authorization was already gone). Those branches delete the file and say
38
+ * precisely why revocation didn't happen, printing the `grantId` so the
39
+ * user can still find and clean up the authorization in the dashboard if
40
+ * it's still listed as active there.
41
+ */
42
+ export function registerLogout(program, internal = {}) {
43
+ program
44
+ .command("logout")
45
+ .description("Revoke this device's authorization and remove the locally stored credential")
46
+ .option("--local", "remove only the local credential file; skip revoking the authorization")
47
+ .action(async (opts) => {
48
+ const home = internal.home ?? os.homedir();
49
+ let creds;
50
+ try {
51
+ creds = readCredentials(home);
52
+ }
53
+ catch (err) {
54
+ // Corrupt JSON or an unrecognized CREDENTIALS_VERSION: logout's job
55
+ // is to remove the file, not diagnose it — symmetric with
56
+ // src/auth/login.ts's tolerance of the same failure. There is no
57
+ // apiKey/grantId to extract from an unreadable file, so no
58
+ // revocation is attempted (or even possible) either way, regardless
59
+ // of --local.
60
+ const msg = err instanceof Error ? err.message : String(err);
61
+ process.stderr.write(`warning: ignoring an unreadable credentials file (removing it): ${msg}\n`);
62
+ deleteCredentials(home);
63
+ process.stdout.write("Cleared local credentials.\n");
64
+ return;
65
+ }
66
+ if (!creds) {
67
+ process.stdout.write("Not logged in; nothing to do.\n");
68
+ return;
69
+ }
70
+ if (creds.source === "api-key") {
71
+ // A pasted key has no grant behind it — nothing to revoke, and the
72
+ // copy must never claim otherwise, or the user is told an
73
+ // authorization was closed that never existed. Zero network requests
74
+ // on this branch.
75
+ deleteCredentials(home);
76
+ process.stdout.write("Cleared local credentials.\n");
77
+ return;
78
+ }
79
+ // source === "login"
80
+ if (opts.local) {
81
+ const grantId = creds.grantId;
82
+ deleteCredentials(home);
83
+ process.stdout.write(`Cleared local credentials (--local: the authorization was not revoked). ` +
84
+ `Grant ${grantId} can still mint a new credential without a fresh consent screen — ` +
85
+ `revoke it from the dashboard if you want to close it out.\n`);
86
+ return;
87
+ }
88
+ try {
89
+ await revokeCliGrant({
90
+ issuer: creds.issuer,
91
+ apiKey: creds.apiKey,
92
+ grantId: creds.grantId,
93
+ fetchImpl: internal.fetchImpl,
94
+ });
95
+ }
96
+ catch (err) {
97
+ const msg = err instanceof Error ? err.message : String(err);
98
+ if (err instanceof OctenNetworkError) {
99
+ // A failed revocation does not mean the credential is invalid —
100
+ // deleting it here would strand the user with no working key and
101
+ // no way to get a new one without re-consenting. Keep the file.
102
+ process.stderr.write(`Could not revoke this authorization: ${msg}\n` +
103
+ "Local credentials were kept. Retry, or run `octen logout --local` to remove them without revoking.\n");
104
+ process.exitCode = 1;
105
+ return;
106
+ }
107
+ // Every other failure is deterministic (OctenAuthError from
108
+ // revoke.ts: 401/403/400) — retrying plain `octen logout` fails
109
+ // identically every time, so keeping the file only strands the
110
+ // user. Delete it, and say exactly why revocation didn't happen.
111
+ deleteCredentials(home);
112
+ if (msg === GRANT_NOT_RECOGNIZED_MESSAGE) {
113
+ // Do NOT say "already gone". The server's 400 is ambiguous by
114
+ // construction (see GRANT_NOT_RECOGNIZED_MESSAGE in auth/revoke.ts):
115
+ // it covers both "that id is unknown" and "the id is real and still
116
+ // active, but this key may no longer act on it" — the latter happens
117
+ // when the user has been removed from the organization that owns the
118
+ // key. Telling those users there is nothing left to revoke leaves a
119
+ // live grant behind that can still mint credentials, which is exactly
120
+ // what this command's doc comment above promises never to do.
121
+ process.stdout.write(`Cleared local credentials, but the server did not accept the revocation of ` +
122
+ `grant ${creds.grantId}.\n` +
123
+ ` Most often the authorization no longer exists. It can also mean the ` +
124
+ `authorization is still active\n while this key may no longer act on it — for ` +
125
+ `example after you were removed from the\n organization that owns it. ` +
126
+ `Check that grant id in the dashboard if you need to be sure.\n`);
127
+ }
128
+ else {
129
+ process.stdout.write(`Cleared local credentials. This credential could not revoke its authorization ` +
130
+ `(${msg}) — if grant ${creds.grantId} still shows as active in the dashboard, ` +
131
+ `revoke it there.\n`);
132
+ }
133
+ return;
134
+ }
135
+ deleteCredentials(home);
136
+ process.stdout.write("Cleared local credentials and revoked this authorization. " +
137
+ "This does not deactivate the API key itself: the same key still works on " +
138
+ "other machines, in production code, and in AI-client configs written by " +
139
+ "`octen configure-mcp`. If you suspect it was exposed, deactivate or rotate the " +
140
+ "key from the dashboard.\n");
141
+ });
142
+ }
@@ -6,6 +6,7 @@ import { removeMcp } from "../mcp/install.js";
6
6
  import { removeSkills } from "../skills/install.js";
7
7
  import { quotePath } from "../util/quotePath.js";
8
8
  import { parseScopeOpt } from "./utils.js";
9
+ import { deleteCredentials, readCredentials, credentialsPath } from "../auth/store.js";
9
10
  // Maps CLI flag name → client id (shared across both registries)
10
11
  const CLIENT_FLAG_MAP = {
11
12
  claudeCode: "claude-code",
@@ -23,6 +24,7 @@ export function registerReset(program, internal = {}) {
23
24
  .description("Remove Octen MCP server and/or skills from AI clients")
24
25
  .option("--mcp", "remove MCP entries")
25
26
  .option("--skills", "remove skills")
27
+ .option("--credentials", "remove the locally stored login credential (~/.octen/credentials.json); not included in --all")
26
28
  .option("--all", "remove from both surfaces across all clients")
27
29
  .option("--claude-code", "target Claude Code")
28
30
  .option("--cursor", "target Cursor")
@@ -40,13 +42,47 @@ export function registerReset(program, internal = {}) {
40
42
  // Parsed and validated by parseScopeOpt at option-parse time.
41
43
  const scope = opts.scope;
42
44
  const installOpts = { hasClaudeCli: internal.hasClaudeCli };
43
- // Surface selection
45
+ // Surface selection. `--credentials` is deliberately NOT folded into
46
+ // `--all` — `--all`'s existing meaning is "both surfaces x all
47
+ // clients" (MCP + skills), and silently logging the user out as a
48
+ // side effect of that would be an unwelcome surprise.
44
49
  const doMcp = opts.all ? true : !!opts.mcp;
45
50
  const doSkills = opts.all ? true : !!opts.skills;
46
- if (!doMcp && !doSkills) {
47
- process.stdout.write("specify --mcp, --skills, or --all to select what to remove\n");
51
+ const doCredentials = !!opts.credentials;
52
+ if (!doMcp && !doSkills && !doCredentials) {
53
+ process.stdout.write("specify --mcp, --skills, --credentials, or --all to select what to remove\n" +
54
+ "(--all covers --mcp and --skills across all clients; --credentials is separate)\n");
48
55
  return;
49
56
  }
57
+ // --- Credentials surface (independent of MCP/skills and of --all) ---
58
+ if (doCredentials) {
59
+ // Read before deleting: a `source: "login"` credential is the only
60
+ // place this machine records its grantId, and destroying it without
61
+ // printing that id strands the user — the grant stays listed in the
62
+ // dashboard and nothing here can name it any more — the same
63
+ // stranding `octen logout --local` prints the id to avoid. A
64
+ // corrupt/unreadable file is tolerated, exactly as `octen logout`
65
+ // tolerates it: reset's job is to remove the file, not diagnose it.
66
+ let grantId;
67
+ try {
68
+ const existing = readCredentials(home);
69
+ if (existing?.source === "login")
70
+ grantId = existing.grantId;
71
+ }
72
+ catch (err) {
73
+ const msg = err instanceof Error ? err.message : String(err);
74
+ process.stderr.write(`warning: ignoring an unreadable credentials file (removing it): ${msg}\n`);
75
+ }
76
+ const removed = deleteCredentials(home);
77
+ process.stdout.write(removed
78
+ ? `removed local credentials (${quotePath(credentialsPath(home))})\n`
79
+ : "no local credentials found\n");
80
+ if (removed && grantId) {
81
+ process.stdout.write(`Grant ${grantId} was not revoked — \`reset --credentials\` makes no network ` +
82
+ `request. It can still mint a new credential without a fresh consent screen; ` +
83
+ `revoke it from the dashboard's authorization list if you want to close it out.\n`);
84
+ }
85
+ }
50
86
  // Determine which client ids were explicitly requested via per-client flags
51
87
  const requestedIds = new Set();
52
88
  const anyPerClientFlag = Object.entries(CLIENT_FLAG_MAP).some(([flagName]) => !!opts[flagName]);
@@ -1,4 +1,5 @@
1
1
  import { OctenClient } from "../api/client.js";
2
+ import type { LinkScope } from "../api/extract.js";
2
3
  /** Build an OctenClient from resolved global options (flag > env). */
3
4
  export declare function makeClient(g: {
4
5
  apiKey?: string;
@@ -27,3 +28,11 @@ export type ConfigScope = (typeof SCOPE_OPTIONS)[number];
27
28
  * for, and `reset` would then delete from the wrong one.
28
29
  */
29
30
  export declare const parseScopeOpt: (name: string) => (v: string) => ConfigScope;
31
+ /**
32
+ * Commander option parser for extract's `--links [scope]`. The scope is optional,
33
+ * so commander hands the next bare word to this parser — which, in
34
+ * `octen extract --links https://a.com`, is a URL. Name that mistake instead of
35
+ * letting it surface as an unknown scope (or as "missing required argument").
36
+ * A bare `--links` never reaches here: commander sets `true` without parsing.
37
+ */
38
+ export declare const parseLinkScopeOpt: (name: string) => (v: string) => LinkScope;
@@ -1,4 +1,5 @@
1
1
  import { OctenClient } from "../api/client.js";
2
+ import { LINK_SCOPE_OPTIONS } from "../api/constants.js";
2
3
  import { OctenValidationError } from "../api/errors.js";
3
4
  import { resolveApiKey, resolveBaseUrl } from "../config/resolve.js";
4
5
  /** Build an OctenClient from resolved global options (flag > env). */
@@ -59,3 +60,18 @@ export const parseScopeOpt = (name) => (v) => {
59
60
  }
60
61
  return v;
61
62
  };
63
+ /**
64
+ * Commander option parser for extract's `--links [scope]`. The scope is optional,
65
+ * so commander hands the next bare word to this parser — which, in
66
+ * `octen extract --links https://a.com`, is a URL. Name that mistake instead of
67
+ * letting it surface as an unknown scope (or as "missing required argument").
68
+ * A bare `--links` never reaches here: commander sets `true` without parsing.
69
+ */
70
+ export const parseLinkScopeOpt = (name) => (v) => {
71
+ if (LINK_SCOPE_OPTIONS.includes(v))
72
+ return v;
73
+ if (v.includes("://") || v.includes(".")) {
74
+ throw new OctenValidationError(`${name} got "${v}" as its scope; put ${name} after the URLs or use ${name}=<scope>`);
75
+ }
76
+ throw new OctenValidationError(`${name} must be one of: ${LINK_SCOPE_OPTIONS.join(", ")}`);
77
+ };
@@ -0,0 +1,27 @@
1
+ import type { Command } from "commander";
2
+ export interface WhoamiInternalOpts {
3
+ /** Injected home dir (for testing); defaults to os.homedir(). */
4
+ home?: string;
5
+ /** Injected env (for testing); defaults to process.env. */
6
+ env?: NodeJS.ProcessEnv;
7
+ }
8
+ /**
9
+ * `octen whoami` — show the locally stored credential. This reads only the
10
+ * local file and makes zero network requests.
11
+ *
12
+ * There is deliberately no `--verify`. The stored credential is a long-lived
13
+ * API key with no short-lived state attached, so there is nothing local that
14
+ * could have gone stale and needs checking against the server; a request
15
+ * would only prove the key worked at that instant, which running any actual
16
+ * command already demonstrates. A `--verify` flag would also turn the one
17
+ * command a user reaches for while debugging broken connectivity into
18
+ * another command that needs working connectivity.
19
+ *
20
+ * It also reports which of the three sources is *actually* in effect. The
21
+ * two filters `resolveApiKey` applies — the flag/env short-circuit and the
22
+ * issuer/resource comparison — are applied here too (the second by calling
23
+ * `credentialIgnoredReason`, the very function `resolveApiKey` calls), so
24
+ * `whoami` can never describe a credential that `octen search` would refuse
25
+ * to use.
26
+ */
27
+ export declare function registerWhoami(program: Command, internal?: WhoamiInternalOpts): void;