@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
@@ -0,0 +1,109 @@
1
+ import os from "node:os";
2
+ import { readCredentials } from "../auth/store.js";
3
+ import { authIssuer, authResource } from "../auth/constants.js";
4
+ import { credentialIgnoredReason } from "../config/resolve.js";
5
+ import { chooseMode, emit } from "../output/render.js";
6
+ import { renderWhoami, } from "../output/pretty/whoami.js";
7
+ /**
8
+ * `octen whoami` — show the locally stored credential. This reads only the
9
+ * local file and makes zero network requests.
10
+ *
11
+ * There is deliberately no `--verify`. The stored credential is a long-lived
12
+ * API key with no short-lived state attached, so there is nothing local that
13
+ * could have gone stale and needs checking against the server; a request
14
+ * would only prove the key worked at that instant, which running any actual
15
+ * command already demonstrates. A `--verify` flag would also turn the one
16
+ * command a user reaches for while debugging broken connectivity into
17
+ * another command that needs working connectivity.
18
+ *
19
+ * It also reports which of the three sources is *actually* in effect. The
20
+ * two filters `resolveApiKey` applies — the flag/env short-circuit and the
21
+ * issuer/resource comparison — are applied here too (the second by calling
22
+ * `credentialIgnoredReason`, the very function `resolveApiKey` calls), so
23
+ * `whoami` can never describe a credential that `octen search` would refuse
24
+ * to use.
25
+ */
26
+ export function registerWhoami(program, internal = {}) {
27
+ program
28
+ .command("whoami")
29
+ .description("Show the locally stored credential (reads only the local file, no network request)")
30
+ .action(async (_opts, command) => {
31
+ const g = command.optsWithGlobals();
32
+ const home = internal.home ?? os.homedir();
33
+ const env = internal.env ?? process.env;
34
+ const mode = chooseMode(g, process.stdout.isTTY ?? false);
35
+ // Step 1/2 of resolveApiKey: an explicit flag or env var wins before
36
+ // the file is even read, so a stored credential behind either of them
37
+ // is not the one any command would use.
38
+ const shadow = g.apiKey
39
+ ? "flag-shadowed"
40
+ : env.OCTEN_API_KEY
41
+ ? "env-shadowed"
42
+ : undefined;
43
+ const shadowSource = g.apiKey
44
+ ? "--api-key"
45
+ : env.OCTEN_API_KEY
46
+ ? "OCTEN_API_KEY"
47
+ : undefined;
48
+ // The comment above is the whole point, so honour it: when a flag or env
49
+ // var already decided the outcome, the file is irrelevant and must not be
50
+ // able to fail this command. `resolveApiKey` returns on that path without
51
+ // touching disk, so `octen search` works with a corrupt credentials file
52
+ // while `octen whoami` used to be the one command that exited 2 — and in
53
+ // --json mode emitted nothing at all, which is worse than useless to the
54
+ // scripts that read it.
55
+ let creds;
56
+ try {
57
+ creds = readCredentials(home);
58
+ }
59
+ catch (err) {
60
+ if (!shadowSource)
61
+ throw err;
62
+ creds = undefined;
63
+ }
64
+ if (!creds) {
65
+ const data = { loggedIn: false, effectiveSource: shadowSource ?? "none" };
66
+ emit(data, mode, renderWhoami);
67
+ // Exit code tracks "is a key in effect", not "does a file exist".
68
+ // It used to track the latter and was wrong in both directions: it
69
+ // exited 0 while reporting effectiveSource "none" (every command would
70
+ // fail), and exited 2 when an env key was working fine. That made
71
+ // `octen whoami && octen search …` unreliable in both directions.
72
+ if (!shadowSource)
73
+ process.exitCode = 2;
74
+ return;
75
+ }
76
+ // Only reached when nothing shadows the file — mirroring resolveApiKey,
77
+ // which never parses OCTEN_AUTH_* on the flag/env path either.
78
+ const mismatch = shadow ? undefined : credentialIgnoredReason(creds, env);
79
+ const ignoredReason = shadow ?? mismatch;
80
+ const inEffect = ignoredReason === undefined;
81
+ const effectiveSource = shadowSource ?? (inEffect ? "credentials-file" : "none");
82
+ const effect = {
83
+ loggedIn: true,
84
+ effectiveSource,
85
+ inEffect,
86
+ ...(ignoredReason !== undefined ? { ignoredReason } : {}),
87
+ ...(mismatch === "issuer-mismatch" ? { expectedIssuer: authIssuer(env) } : {}),
88
+ ...(mismatch === "resource-mismatch" ? { expectedResource: authResource(env) } : {}),
89
+ };
90
+ const data = creds.source === "api-key"
91
+ ? { ...effect, source: "api-key" }
92
+ : {
93
+ ...effect,
94
+ source: "login",
95
+ issuer: creds.issuer,
96
+ resource: creds.resource,
97
+ grantId: creds.grantId,
98
+ ...(creds.accountId !== undefined ? { accountId: creds.accountId } : {}),
99
+ ...(creds.accountType !== undefined ? { accountType: creds.accountType } : {}),
100
+ apiKeyExpiresAt: creds.apiKeyExpiresAt,
101
+ };
102
+ emit(data, mode, renderWhoami);
103
+ // Same rule as the no-credential branch: "none" means every command would
104
+ // fail, so it must not exit 0. A credential that exists but is shadowed
105
+ // or belongs to another environment is exactly that case.
106
+ if (effectiveSource === "none")
107
+ process.exitCode = 2;
108
+ });
109
+ }
@@ -1,2 +1,45 @@
1
- export declare function resolveApiKey(flag: string | undefined, env: NodeJS.ProcessEnv): string;
1
+ import { type Credentials } from "../auth/store.js";
2
+ /**
3
+ * Why a stored credential is not the one commands will use. `undefined` means
4
+ * it is usable. Deliberately does NOT cover flag/env shadowing: those are
5
+ * decided before the file is even read (`resolveApiKey` steps 1-2), and
6
+ * `octen whoami` labels them separately.
7
+ */
8
+ export type CredentialIgnoredReason = "issuer-mismatch" | "resource-mismatch" | "expired";
9
+ /**
10
+ * The single place that decides whether a stored credential is usable.
11
+ * `resolveApiKey` calls it below, and so does `octen whoami`
12
+ * (`src/commands/whoami.ts` calls it via this export) — sharing the one
13
+ * function is what stops `whoami` from reporting a credential that no other
14
+ * command would touch.
15
+ *
16
+ * Synchronous and network-free, like everything on this path.
17
+ */
18
+ export declare function credentialIgnoredReason(creds: Credentials, env: NodeJS.ProcessEnv, nowSeconds?: number): CredentialIgnoredReason | undefined;
19
+ /**
20
+ * The message for a credential that exists on disk but was minted for another
21
+ * environment. It deliberately does NOT reuse NO_CREDENTIAL_MESSAGE: telling
22
+ * the user to run `octen login` when an OCTEN_AUTH_* override is the cause
23
+ * sends them through a browser consent flow that cannot fix anything.
24
+ */
25
+ export declare function mismatchMessage(reason: "issuer-mismatch" | "resource-mismatch", stored: string, expected: string): string;
26
+ export interface ResolveApiKeyOpts {
27
+ /** Injected home dir (for testing); defaults to os.homedir(). */
28
+ home?: string;
29
+ }
30
+ /**
31
+ * Resolve the API key to use: --api-key flag > OCTEN_API_KEY env >
32
+ * ~/.octen/credentials.json (written by `octen login`) > throw.
33
+ *
34
+ * Stays synchronous and does no network work: the stored key never expires
35
+ * on its own (the not-yet-reachable short-lived-key path below is the only
36
+ * exception), so a plain, lock-free file read is enough. This is the property
37
+ * everything else depends on: the credential is written once, by `octen
38
+ * login`, and afterwards only read — so there is no refresh to serialize, no
39
+ * lock to hold, and no reason for this function to become async. Making it
40
+ * async would ripple into every command's client construction. Steps 1 and 2 return before
41
+ * touching the disk at all, so an explicit flag or env var never pays for a
42
+ * file read and always wins over a stale or foreign login.
43
+ */
44
+ export declare function resolveApiKey(flag: string | undefined, env: NodeJS.ProcessEnv, opts?: ResolveApiKeyOpts): string;
2
45
  export declare function resolveBaseUrl(flag: string | undefined, env: NodeJS.ProcessEnv): string;
@@ -1,11 +1,86 @@
1
+ import os from "node:os";
1
2
  import { DEFAULT_BASE_URL } from "../api/constants.js";
2
- import { OctenAuthError } from "../api/errors.js";
3
- export function resolveApiKey(flag, env) {
3
+ import { OctenAuthError, OctenNoCredentialError } from "../api/errors.js";
4
+ import { readCredentials } from "../auth/store.js";
5
+ import { authIssuer, authResource } from "../auth/constants.js";
6
+ /** Names both ways out: interactive login and the environment variable. */
7
+ const NO_CREDENTIAL_MESSAGE = "No API key. Run `octen login`, pass --api-key, or set OCTEN_API_KEY.";
8
+ /**
9
+ * The single place that decides whether a stored credential is usable.
10
+ * `resolveApiKey` calls it below, and so does `octen whoami`
11
+ * (`src/commands/whoami.ts` calls it via this export) — sharing the one
12
+ * function is what stops `whoami` from reporting a credential that no other
13
+ * command would touch.
14
+ *
15
+ * Synchronous and network-free, like everything on this path.
16
+ */
17
+ export function credentialIgnoredReason(creds, env, nowSeconds = Math.floor(Date.now() / 1000)) {
18
+ // A pasted key carries no issuer/resource/expiry — nothing to disqualify it.
19
+ if (creds.source !== "login")
20
+ return undefined;
21
+ // A credential minted for a different issuer/resource belongs to another
22
+ // environment, not to this resolution. Treat it as no credential at all —
23
+ // never use it, and never delete the file, since it isn't ours to manage.
24
+ if (creds.issuer !== authIssuer(env))
25
+ return "issuer-mismatch";
26
+ if (creds.resource !== authResource(env))
27
+ return "resource-mismatch";
28
+ // Forward-compatibility only: the server returns apiKeyExpiresAt: null for
29
+ // every credential it mints today, so this branch never fires yet. It is
30
+ // here so that if short-lived keys ever ship, an expired credential names
31
+ // itself instead of surfacing as an opaque 401 from the first API call.
32
+ if (creds.apiKeyExpiresAt !== null && creds.apiKeyExpiresAt <= nowSeconds)
33
+ return "expired";
34
+ return undefined;
35
+ }
36
+ /**
37
+ * The message for a credential that exists on disk but was minted for another
38
+ * environment. It deliberately does NOT reuse NO_CREDENTIAL_MESSAGE: telling
39
+ * the user to run `octen login` when an OCTEN_AUTH_* override is the cause
40
+ * sends them through a browser consent flow that cannot fix anything.
41
+ */
42
+ export function mismatchMessage(reason, stored, expected) {
43
+ const varName = reason === "issuer-mismatch" ? "OCTEN_AUTH_ISSUER" : "OCTEN_AUTH_RESOURCE";
44
+ return (`A stored credential exists, but it was issued for ${stored} while ${varName} selects ` +
45
+ `${expected}, so it is being ignored. Unset ${varName} to use the stored credential, or ` +
46
+ `run \`octen login\` again to get one for ${expected}. \`octen whoami\` shows which ` +
47
+ `credential is in effect.`);
48
+ }
49
+ /**
50
+ * Resolve the API key to use: --api-key flag > OCTEN_API_KEY env >
51
+ * ~/.octen/credentials.json (written by `octen login`) > throw.
52
+ *
53
+ * Stays synchronous and does no network work: the stored key never expires
54
+ * on its own (the not-yet-reachable short-lived-key path below is the only
55
+ * exception), so a plain, lock-free file read is enough. This is the property
56
+ * everything else depends on: the credential is written once, by `octen
57
+ * login`, and afterwards only read — so there is no refresh to serialize, no
58
+ * lock to hold, and no reason for this function to become async. Making it
59
+ * async would ripple into every command's client construction. Steps 1 and 2 return before
60
+ * touching the disk at all, so an explicit flag or env var never pays for a
61
+ * file read and always wins over a stale or foreign login.
62
+ */
63
+ export function resolveApiKey(flag, env, opts = {}) {
4
64
  const key = flag || env.OCTEN_API_KEY;
5
- if (!key) {
6
- throw new OctenAuthError("No API key. Pass --api-key or set OCTEN_API_KEY. Get one at https://octen.ai");
65
+ if (key)
66
+ return key;
67
+ const home = opts.home ?? os.homedir();
68
+ const creds = readCredentials(home);
69
+ if (!creds) {
70
+ throw new OctenNoCredentialError(NO_CREDENTIAL_MESSAGE);
71
+ }
72
+ if (creds.source === "login") {
73
+ const reason = credentialIgnoredReason(creds, env);
74
+ if (reason === "expired") {
75
+ throw new OctenAuthError("Credential expired; run `octen login` again.");
76
+ }
77
+ if (reason !== undefined) {
78
+ const stored = reason === "issuer-mismatch" ? creds.issuer : creds.resource;
79
+ const expected = reason === "issuer-mismatch" ? authIssuer(env) : authResource(env);
80
+ throw new OctenAuthError(mismatchMessage(reason, stored, expected));
81
+ }
7
82
  }
8
- return key;
83
+ return creds.apiKey;
9
84
  }
10
85
  export function resolveBaseUrl(flag, env) {
11
86
  return flag || env.OCTEN_API_URL || DEFAULT_BASE_URL;
@@ -13,9 +13,22 @@ function claudeAvailable(override) {
13
13
  }
14
14
  export function installMcp(client, scope, entry, home, cwd, opts = {}) {
15
15
  if (client.id === "claude-code") {
16
- if (claudeAvailable(opts.hasClaudeCli)) {
16
+ const apiKey = entry.env["OCTEN_API_KEY"] ?? "";
17
+ // A real key must never reach another process's argv: `ps -ww` and
18
+ // /proc/<pid>/cmdline expose it to every local user for the child's
19
+ // lifetime. That used to be harmless here because the only values that
20
+ // could arrive were ones the user had already put in argv (`--api-key`) or
21
+ // the environment (`OCTEN_API_KEY`); since credential resolution learned to
22
+ // read ~/.octen/credentials.json, a key that exists nowhere but a 0600 file
23
+ // can land here, and shelling out would be the one thing that leaks it.
24
+ //
25
+ // So: when the value is a literal secret, take the file path — the same
26
+ // path this function already uses when the `claude` CLI is absent, writing
27
+ // the same `mcpServers` entry to the same file. The CLI is still used for
28
+ // the `${OCTEN_API_KEY}` placeholder, which is not a secret.
29
+ const carriesLiteralSecret = apiKey !== "" && !apiKey.startsWith("${");
30
+ if (claudeAvailable(opts.hasClaudeCli) && !carriesLiteralSecret) {
17
31
  // Use claude CLI: build args safely, no string concatenation
18
- const apiKey = entry.env["OCTEN_API_KEY"] ?? "";
19
32
  execFileSync("claude", [
20
33
  "mcp",
21
34
  "add",
package/dist/mcp/write.js CHANGED
@@ -2,6 +2,17 @@ import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { parse as tomlParse, stringify as tomlStringify } from "smol-toml";
4
4
  import { OctenValidationError } from "../api/errors.js";
5
+ import { writeSecretFile } from "../util/secretFile.js";
6
+ /**
7
+ * True when this entry embeds an actual key rather than the
8
+ * `${OCTEN_API_KEY}` placeholder, i.e. when the file we are about to write
9
+ * becomes a secret-bearing file.
10
+ */
11
+ function carriesLiteralSecret(entry) {
12
+ const env = entry.env;
13
+ const value = env?.["OCTEN_API_KEY"];
14
+ return typeof value === "string" && value !== "" && !value.startsWith("${");
15
+ }
5
16
  function assertNever(x) {
6
17
  throw new Error(`unhandled McpFormat: ${String(x)}`);
7
18
  }
@@ -33,6 +44,7 @@ function readTomlFile(filePath) {
33
44
  }
34
45
  export function upsertMcpServer(filePath, format, entry) {
35
46
  mkdirSync(dirname(filePath), { recursive: true });
47
+ const restrict = carriesLiteralSecret(entry);
36
48
  switch (format) {
37
49
  case "json-mcpServers":
38
50
  case "claude-code": {
@@ -41,7 +53,10 @@ export function upsertMcpServer(filePath, format, entry) {
41
53
  obj.mcpServers = {};
42
54
  }
43
55
  obj.mcpServers["octen"] = entry;
44
- writeFileSync(filePath, JSON.stringify(obj, null, 2), "utf8");
56
+ if (restrict)
57
+ writeSecretFile(filePath, JSON.stringify(obj, null, 2));
58
+ else
59
+ writeFileSync(filePath, JSON.stringify(obj, null, 2), "utf8");
45
60
  return;
46
61
  }
47
62
  case "json-servers": {
@@ -50,7 +65,10 @@ export function upsertMcpServer(filePath, format, entry) {
50
65
  obj.servers = {};
51
66
  }
52
67
  obj.servers["octen"] = entry;
53
- writeFileSync(filePath, JSON.stringify(obj, null, 2), "utf8");
68
+ if (restrict)
69
+ writeSecretFile(filePath, JSON.stringify(obj, null, 2));
70
+ else
71
+ writeFileSync(filePath, JSON.stringify(obj, null, 2), "utf8");
54
72
  return;
55
73
  }
56
74
  case "toml": {
@@ -59,7 +77,10 @@ export function upsertMcpServer(filePath, format, entry) {
59
77
  obj.mcp_servers = {};
60
78
  }
61
79
  obj.mcp_servers["octen"] = entry;
62
- writeFileSync(filePath, tomlStringify(obj), "utf8");
80
+ if (restrict)
81
+ writeSecretFile(filePath, tomlStringify(obj));
82
+ else
83
+ writeFileSync(filePath, tomlStringify(obj), "utf8");
63
84
  return;
64
85
  }
65
86
  default:
@@ -1 +1,5 @@
1
- export declare function renderExtract(data: any, full?: boolean): string;
1
+ /**
2
+ * @param requestedMode the `--mode` the caller asked for, if any. Used only to
3
+ * decide whether suggesting `--mode advanced` would be news to them.
4
+ */
5
+ export declare function renderExtract(data: any, full?: boolean, requestedMode?: string): string;
@@ -1,6 +1,46 @@
1
1
  import pc from "picocolors";
2
2
  const MAX_CONTENT = 500;
3
- export function renderExtract(data, full = false) {
3
+ /** Links and media lists are capped like content: first N entries unless --full. */
4
+ const MAX_LIST = 10;
5
+ /** A labelled, indented URL list, capped at MAX_LIST unless `full`. */
6
+ function formatList(label, entries, full) {
7
+ if (!entries.length)
8
+ return [];
9
+ const shown = full ? entries : entries.slice(0, MAX_LIST);
10
+ const lines = [pc.dim(` ${label} (${entries.length}):`), ...shown.map((e) => ` ${e}`)];
11
+ if (shown.length < entries.length)
12
+ lines.push(pc.dim(` … ${entries.length - shown.length} more (--full to show all)`));
13
+ return lines;
14
+ }
15
+ function formatLink(l) {
16
+ const anchor = l.anchor_text ? ` ${pc.dim(`— ${l.anchor_text}`)}` : "";
17
+ const ext = l.is_external ? ` ${pc.dim("[external]")}` : "";
18
+ return `${l.url ?? ""}${anchor}${ext}`;
19
+ }
20
+ const mediaUrls = (list) => (list ?? []).map((m) => m.url).filter((u) => !!u);
21
+ /** Footer from the top-level `meta`: counts, billing by mode, and any warning. */
22
+ function formatFooter(meta) {
23
+ if (!meta || typeof meta !== "object")
24
+ return undefined;
25
+ const lines = [];
26
+ const usage = meta.usage;
27
+ const parts = [];
28
+ if (usage?.total_urls != null)
29
+ parts.push(`${usage.successful_urls ?? 0}/${usage.total_urls} successful`);
30
+ const byMode = usage?.successful_by_mode;
31
+ if (byMode)
32
+ parts.push(`billed: ${byMode.standard_urls ?? 0} standard, ${byMode.advanced_urls ?? 0} advanced`);
33
+ if (parts.length)
34
+ lines.push(pc.dim(parts.join(" · ")));
35
+ if (meta.warning)
36
+ lines.push(pc.yellow(`warning: ${meta.warning}`));
37
+ return lines.length ? lines.join("\n") : undefined;
38
+ }
39
+ /**
40
+ * @param requestedMode the `--mode` the caller asked for, if any. Used only to
41
+ * decide whether suggesting `--mode advanced` would be news to them.
42
+ */
43
+ export function renderExtract(data, full = false, requestedMode) {
4
44
  // The Octen API wraps the payload in an envelope: { data: { results }, code, msg, ... }.
5
45
  // Unwrap to the inner body only when `data.data` is a non-array object (the real
6
46
  // API shape); fall back to the raw object otherwise so un-enveloped inputs still work.
@@ -20,13 +60,16 @@ export function renderExtract(data, full = false) {
20
60
  }
21
61
  return pc.dim("No results.");
22
62
  }
23
- return items
63
+ const blocks = items
24
64
  .map((item) => {
25
65
  const lines = [];
26
66
  // Bold URL header
27
67
  lines.push(pc.bold(item.url));
28
68
  if (item.status === "failed") {
29
69
  lines.push(pc.red(` failed: ${item.error_message ?? "(unknown error)"}`));
70
+ // resolved_mode is absent on failure, so only the requested mode can rule it out.
71
+ if (requestedMode !== "advanced")
72
+ lines.push(pc.dim(" hint: retry with --mode advanced"));
30
73
  }
31
74
  else {
32
75
  // Dim metadata line: category / page_structure
@@ -39,6 +82,9 @@ export function renderExtract(data, full = false) {
39
82
  // Title
40
83
  if (item.title)
41
84
  lines.push(` ${item.title}`);
85
+ // The mode actually used — may differ from the requested one.
86
+ if (item.resolved_mode)
87
+ lines.push(pc.dim(` mode: ${item.resolved_mode}`));
42
88
  // Media identity: favicon (default) + cover image (with --images)
43
89
  if (item.favicon)
44
90
  lines.push(pc.dim(` favicon: ${item.favicon}`));
@@ -53,8 +99,22 @@ export function renderExtract(data, full = false) {
53
99
  const snippet = !full && raw.length > MAX_CONTENT ? raw.slice(0, MAX_CONTENT) + "…" : raw;
54
100
  lines.push(` ${snippet}`);
55
101
  }
102
+ lines.push(...formatList("images", mediaUrls(item.images), full));
103
+ lines.push(...formatList("videos", mediaUrls(item.videos), full));
104
+ lines.push(...formatList("audio", mediaUrls(item.audio), full));
105
+ lines.push(...formatList("links", (item.links ?? []).map(formatLink), full));
106
+ // Standard can report "success" with only a page skeleton; advanced often recovers it.
107
+ if (structPrimary === "No Main Content" &&
108
+ item.resolved_mode !== "advanced" &&
109
+ requestedMode !== "advanced") {
110
+ lines.push(pc.dim(" hint: retry with --mode advanced"));
111
+ }
56
112
  }
57
113
  return lines.join("\n");
58
- })
59
- .join("\n\n");
114
+ });
115
+ // `meta` is top-level in the envelope (a sibling of `data`), not inside it.
116
+ const footer = formatFooter(data?.meta);
117
+ if (footer)
118
+ blocks.push(footer);
119
+ return blocks.join("\n\n");
60
120
  }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Which of the three credential sources (`--api-key` > `OCTEN_API_KEY` >
3
+ * the stored file) `resolveApiKey` would actually pick right now. `"none"`
4
+ * means every command would fail with "No API key" — including when a
5
+ * credentials file exists but is being ignored.
6
+ */
7
+ export type EffectiveKeySource = "--api-key" | "OCTEN_API_KEY" | "credentials-file" | "none";
8
+ /**
9
+ * The one wording for "there is no local credential file". Two paths render
10
+ * it: pretty mode throws it as an OctenAuthError from src/commands/whoami.ts
11
+ * (to get exit code 2), json mode emits the structured payload. Spelling it
12
+ * twice is how the two drift, so both go through `notLoggedInMessage`.
13
+ */
14
+ export declare const NOT_LOGGED_IN_MESSAGE = "Not logged in (no local credential file). Run `octen login`, or `octen login --api-key <key>`.";
15
+ /**
16
+ * The not-logged-in message, plus — when a flag or env var is supplying a key
17
+ * regardless — the note that commands still work. Saying only "not logged in"
18
+ * to someone whose `OCTEN_API_KEY` is set describes a state they are not in.
19
+ */
20
+ export declare function notLoggedInMessage(effectiveSource?: EffectiveKeySource): string;
21
+ /**
22
+ * Why the stored credential is not the one in effect. The first two are
23
+ * decided before the file is read at all; the last three mirror
24
+ * `credentialIgnoredReason` in src/config/resolve.ts.
25
+ */
26
+ export type WhoamiIgnoredReason = "flag-shadowed" | "env-shadowed" | "issuer-mismatch" | "resource-mismatch" | "expired";
27
+ /** Fields common to every "a credentials file exists" shape. */
28
+ interface WhoamiEffect {
29
+ loggedIn: true;
30
+ effectiveSource: EffectiveKeySource;
31
+ /** Would `resolveApiKey` return THIS credential's key? */
32
+ inEffect: boolean;
33
+ ignoredReason?: WhoamiIgnoredReason;
34
+ /** Only present for a mismatch, and only for the field that mismatched. */
35
+ expectedIssuer?: string;
36
+ expectedResource?: string;
37
+ }
38
+ export type WhoamiData = {
39
+ loggedIn: false;
40
+ effectiveSource: EffectiveKeySource;
41
+ } | (WhoamiEffect & {
42
+ source: "api-key";
43
+ }) | (WhoamiEffect & {
44
+ source: "login";
45
+ issuer: string;
46
+ resource: string;
47
+ grantId: string;
48
+ accountId?: string;
49
+ accountType?: string;
50
+ apiKeyExpiresAt: number | null;
51
+ });
52
+ /**
53
+ * Pretty-print `octen whoami` output. Reflects only the local credentials
54
+ * file — every line here is derived from disk, never from a request, and the
55
+ * trailing note says so explicitly so a reader never mistakes this for
56
+ * confirmation that the key still works server-side.
57
+ */
58
+ export declare function renderWhoami(data: WhoamiData): string;
59
+ export {};
@@ -0,0 +1,103 @@
1
+ /**
2
+ * The one wording for "there is no local credential file". Two paths render
3
+ * it: pretty mode throws it as an OctenAuthError from src/commands/whoami.ts
4
+ * (to get exit code 2), json mode emits the structured payload. Spelling it
5
+ * twice is how the two drift, so both go through `notLoggedInMessage`.
6
+ */
7
+ export const NOT_LOGGED_IN_MESSAGE = "Not logged in (no local credential file). Run `octen login`, or `octen login --api-key <key>`.";
8
+ /**
9
+ * The not-logged-in message, plus — when a flag or env var is supplying a key
10
+ * regardless — the note that commands still work. Saying only "not logged in"
11
+ * to someone whose `OCTEN_API_KEY` is set describes a state they are not in.
12
+ */
13
+ export function notLoggedInMessage(effectiveSource) {
14
+ return effectiveSource === "OCTEN_API_KEY" || effectiveSource === "--api-key"
15
+ ? `${NOT_LOGGED_IN_MESSAGE} (${effectiveSource} is set, so commands use that key.)`
16
+ : NOT_LOGGED_IN_MESSAGE;
17
+ }
18
+ function formatRemaining(seconds) {
19
+ if (seconds <= 0)
20
+ return "expired";
21
+ const days = Math.floor(seconds / 86400);
22
+ const hours = Math.floor((seconds % 86400) / 3600);
23
+ const minutes = Math.floor((seconds % 3600) / 60);
24
+ if (days > 0)
25
+ return `${days}d ${hours}h`;
26
+ if (hours > 0)
27
+ return `${hours}h ${minutes}m`;
28
+ return `${minutes}m`;
29
+ }
30
+ /**
31
+ * The "In effect:" line — the one `whoami` was missing. Before this, `whoami`
32
+ * described the file's credential as live while `octen search` refused to use
33
+ * it, in the same second on the same machine. Every branch names both the
34
+ * cause and the way out.
35
+ */
36
+ function effectLine(data, stored = {}) {
37
+ if (data.inEffect)
38
+ return "In effect: yes — commands use this stored credential.";
39
+ switch (data.ignoredReason) {
40
+ case "flag-shadowed":
41
+ return ("In effect: no — --api-key was passed on this command line and takes precedence, " +
42
+ "so that key is used instead of this stored credential.");
43
+ case "env-shadowed":
44
+ return ("In effect: no — OCTEN_API_KEY is set in the environment and takes precedence, " +
45
+ "so commands use that key, not this stored credential. Unset OCTEN_API_KEY to use it.");
46
+ case "issuer-mismatch":
47
+ return (`In effect: no — this credential was issued for issuer ${stored.issuer}, ` +
48
+ `but OCTEN_AUTH_ISSUER selects ${data.expectedIssuer}, so every command ignores it. ` +
49
+ "Unset OCTEN_AUTH_ISSUER, or run `octen login` again.");
50
+ case "resource-mismatch":
51
+ return (`In effect: no — this credential was issued for resource ${stored.resource}, ` +
52
+ `but OCTEN_AUTH_RESOURCE selects ${data.expectedResource}, so every command ignores it. ` +
53
+ "Unset OCTEN_AUTH_RESOURCE, or run `octen login` again.");
54
+ case "expired":
55
+ return "In effect: no — this credential has expired. Run `octen login` again.";
56
+ default:
57
+ return "In effect: no.";
58
+ }
59
+ }
60
+ /**
61
+ * Pretty-print `octen whoami` output. Reflects only the local credentials
62
+ * file — every line here is derived from disk, never from a request, and the
63
+ * trailing note says so explicitly so a reader never mistakes this for
64
+ * confirmation that the key still works server-side.
65
+ */
66
+ export function renderWhoami(data) {
67
+ const lines = [];
68
+ if (!data.loggedIn) {
69
+ // Reachable in both modes now. This used to be dead code because pretty
70
+ // mode threw instead of rendering; whoami stopped throwing because "not
71
+ // logged in" is a status this command reports, not a failure — the
72
+ // non-zero exit code carries that signal. The comment that used to sit
73
+ // here predicted exactly this: the wording is shared with the json path
74
+ // through `notLoggedInMessage` so the two cannot drift, and that is what
75
+ // made the change a one-liner rather than a second message nothing tests.
76
+ return notLoggedInMessage(data.effectiveSource);
77
+ }
78
+ if (data.source === "api-key") {
79
+ lines.push("Source: api-key (set via `octen login --api-key` or a manually-configured key)");
80
+ lines.push(effectLine(data));
81
+ lines.push("No account or grant information is available for this credential — it was not created via the browser login flow.");
82
+ }
83
+ else {
84
+ const who = data.accountId
85
+ ? `${data.accountId}${data.accountType ? ` (${data.accountType})` : ""}`
86
+ : "(account id unknown)";
87
+ lines.push(`Account: ${who}`);
88
+ lines.push("Source: login (browser OAuth)");
89
+ lines.push(effectLine(data, { issuer: data.issuer, resource: data.resource }));
90
+ lines.push(`Issuer: ${data.issuer}`);
91
+ lines.push(`Resource: ${data.resource}`);
92
+ lines.push(`Grant: ${data.grantId} — find and revoke this device in the dashboard's authorization list.`);
93
+ if (data.apiKeyExpiresAt !== null) {
94
+ const remaining = data.apiKeyExpiresAt - Math.floor(Date.now() / 1000);
95
+ lines.push(`API key expires in: ${formatRemaining(remaining)}`);
96
+ }
97
+ else {
98
+ lines.push("API key: does not expire");
99
+ }
100
+ }
101
+ lines.push("(Read from the local credentials file only — no network request was made.)");
102
+ return lines.join("\n");
103
+ }
@@ -1,4 +1,5 @@
1
- import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";
1
+ import { mkdirSync, readFileSync, existsSync } from "node:fs";
2
+ import { writeSecretFile } from "../util/secretFile.js";
2
3
  import { dirname, join } from "node:path";
3
4
  import { parse, stringify } from "smol-toml";
4
5
  import { OctenValidationError } from "../api/errors.js";
@@ -47,7 +48,7 @@ export function setClientEnvKey(clientId, key, scope, home, cwd) {
47
48
  OCTEN_API_KEY: key,
48
49
  };
49
50
  mkdirSync(dirname(path), { recursive: true });
50
- writeFileSync(path, JSON.stringify(obj, null, 2) + "\n", "utf8");
51
+ writeSecretFile(path, JSON.stringify(obj, null, 2) + "\n");
51
52
  return { clientId, written: true, path };
52
53
  }
53
54
  case "codex": {
@@ -59,7 +60,7 @@ export function setClientEnvKey(clientId, key, scope, home, cwd) {
59
60
  OCTEN_API_KEY: key,
60
61
  };
61
62
  mkdirSync(dirname(path), { recursive: true });
62
- writeFileSync(path, stringify(obj), "utf8");
63
+ writeSecretFile(path, stringify(obj));
63
64
  return { clientId, written: true, path };
64
65
  }
65
66
  case "openclaw": {
@@ -77,7 +78,7 @@ export function setClientEnvKey(clientId, key, scope, home, cwd) {
77
78
  if (!replaced)
78
79
  lines.push(`OCTEN_API_KEY=${key}`);
79
80
  mkdirSync(dirname(path), { recursive: true });
80
- writeFileSync(path, lines.join("\n") + "\n", "utf8");
81
+ writeSecretFile(path, lines.join("\n") + "\n");
81
82
  return { clientId, written: true, path };
82
83
  }
83
84
  default: