codeblog-app 2.1.2 → 2.1.4

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 (69) hide show
  1. package/drizzle/0000_init.sql +34 -0
  2. package/drizzle/meta/_journal.json +13 -0
  3. package/drizzle.config.ts +10 -0
  4. package/package.json +71 -8
  5. package/src/ai/__tests__/chat.test.ts +110 -0
  6. package/src/ai/__tests__/provider.test.ts +184 -0
  7. package/src/ai/__tests__/tools.test.ts +54 -0
  8. package/src/ai/chat.ts +170 -0
  9. package/src/ai/configure.ts +134 -0
  10. package/src/ai/provider.ts +238 -0
  11. package/src/ai/tools.ts +91 -0
  12. package/src/auth/index.ts +47 -0
  13. package/src/auth/oauth.ts +94 -0
  14. package/src/cli/__tests__/commands.test.ts +225 -0
  15. package/src/cli/cmd/agent.ts +97 -0
  16. package/src/cli/cmd/chat.ts +190 -0
  17. package/src/cli/cmd/comment.ts +67 -0
  18. package/src/cli/cmd/config.ts +153 -0
  19. package/src/cli/cmd/feed.ts +53 -0
  20. package/src/cli/cmd/forum.ts +106 -0
  21. package/src/cli/cmd/login.ts +45 -0
  22. package/src/cli/cmd/logout.ts +12 -0
  23. package/src/cli/cmd/me.ts +188 -0
  24. package/src/cli/cmd/post.ts +25 -0
  25. package/src/cli/cmd/publish.ts +64 -0
  26. package/src/cli/cmd/scan.ts +78 -0
  27. package/src/cli/cmd/search.ts +35 -0
  28. package/src/cli/cmd/setup.ts +273 -0
  29. package/src/cli/cmd/tui.ts +20 -0
  30. package/src/cli/cmd/uninstall.ts +156 -0
  31. package/src/cli/cmd/update.ts +123 -0
  32. package/src/cli/cmd/vote.ts +50 -0
  33. package/src/cli/cmd/whoami.ts +18 -0
  34. package/src/cli/mcp-print.ts +6 -0
  35. package/src/cli/ui.ts +195 -0
  36. package/src/config/index.ts +54 -0
  37. package/src/flag/index.ts +23 -0
  38. package/src/global/index.ts +38 -0
  39. package/src/id/index.ts +20 -0
  40. package/src/index.ts +200 -0
  41. package/src/mcp/__tests__/client.test.ts +149 -0
  42. package/src/mcp/__tests__/e2e.ts +327 -0
  43. package/src/mcp/__tests__/integration.ts +148 -0
  44. package/src/mcp/client.ts +148 -0
  45. package/src/server/index.ts +48 -0
  46. package/src/storage/chat.ts +71 -0
  47. package/src/storage/db.ts +85 -0
  48. package/src/storage/schema.sql.ts +39 -0
  49. package/src/storage/schema.ts +1 -0
  50. package/src/tui/app.tsx +179 -0
  51. package/src/tui/commands.ts +187 -0
  52. package/src/tui/context/exit.tsx +15 -0
  53. package/src/tui/context/helper.tsx +25 -0
  54. package/src/tui/context/route.tsx +24 -0
  55. package/src/tui/context/theme.tsx +470 -0
  56. package/src/tui/routes/home.tsx +508 -0
  57. package/src/tui/routes/model.tsx +207 -0
  58. package/src/tui/routes/notifications.tsx +87 -0
  59. package/src/tui/routes/post.tsx +102 -0
  60. package/src/tui/routes/search.tsx +105 -0
  61. package/src/tui/routes/setup.tsx +255 -0
  62. package/src/tui/routes/trending.tsx +107 -0
  63. package/src/util/__tests__/context.test.ts +31 -0
  64. package/src/util/__tests__/lazy.test.ts +37 -0
  65. package/src/util/context.ts +23 -0
  66. package/src/util/error.ts +46 -0
  67. package/src/util/lazy.ts +18 -0
  68. package/src/util/log.ts +142 -0
  69. package/tsconfig.json +11 -0
@@ -0,0 +1,50 @@
1
+ import type { CommandModule } from "yargs"
2
+ import { McpBridge } from "../../mcp/client"
3
+ import { UI } from "../ui"
4
+
5
+ export const VoteCommand: CommandModule = {
6
+ command: "vote <post_id>",
7
+ describe: "Vote on a post (up/down/remove)",
8
+ builder: (yargs) =>
9
+ yargs
10
+ .positional("post_id", {
11
+ describe: "Post ID to vote on",
12
+ type: "string",
13
+ demandOption: true,
14
+ })
15
+ .option("up", {
16
+ alias: "u",
17
+ describe: "Upvote",
18
+ type: "boolean",
19
+ })
20
+ .option("down", {
21
+ alias: "d",
22
+ describe: "Downvote",
23
+ type: "boolean",
24
+ })
25
+ .option("remove", {
26
+ describe: "Remove existing vote",
27
+ type: "boolean",
28
+ })
29
+ .conflicts("up", "down")
30
+ .conflicts("up", "remove")
31
+ .conflicts("down", "remove"),
32
+ handler: async (args) => {
33
+ let value = 1 // default upvote
34
+ if (args.down) value = -1
35
+ if (args.remove) value = 0
36
+
37
+ try {
38
+ const text = await McpBridge.callTool("vote_on_post", {
39
+ post_id: args.post_id,
40
+ value,
41
+ })
42
+ console.log("")
43
+ console.log(` ${text}`)
44
+ console.log("")
45
+ } catch (err) {
46
+ UI.error(`Vote failed: ${err instanceof Error ? err.message : String(err)}`)
47
+ process.exitCode = 1
48
+ }
49
+ },
50
+ }
@@ -0,0 +1,18 @@
1
+ import type { CommandModule } from "yargs"
2
+ import { mcpPrint } from "../mcp-print"
3
+ import { UI } from "../ui"
4
+
5
+ export const WhoamiCommand: CommandModule = {
6
+ command: "whoami",
7
+ describe: "Show current auth status",
8
+ handler: async () => {
9
+ try {
10
+ console.log("")
11
+ await mcpPrint("codeblog_status")
12
+ console.log("")
13
+ } catch (err) {
14
+ UI.error(`Status check failed: ${err instanceof Error ? err.message : String(err)}`)
15
+ process.exitCode = 1
16
+ }
17
+ },
18
+ }
@@ -0,0 +1,6 @@
1
+ import { McpBridge } from "../mcp/client"
2
+
3
+ export async function mcpPrint(tool: string, args: Record<string, unknown> = {}) {
4
+ const text = await McpBridge.callTool(tool, args)
5
+ for (const line of text.split("\n")) console.log(` ${line}`)
6
+ }
package/src/cli/ui.ts ADDED
@@ -0,0 +1,195 @@
1
+ import { EOL } from "os"
2
+
3
+ export namespace UI {
4
+ export const Style = {
5
+ TEXT_HIGHLIGHT: "\x1b[96m",
6
+ TEXT_HIGHLIGHT_BOLD: "\x1b[96m\x1b[1m",
7
+ TEXT_DIM: "\x1b[90m",
8
+ TEXT_DIM_BOLD: "\x1b[90m\x1b[1m",
9
+ TEXT_NORMAL: "\x1b[0m",
10
+ TEXT_NORMAL_BOLD: "\x1b[1m",
11
+ TEXT_WARNING: "\x1b[93m",
12
+ TEXT_WARNING_BOLD: "\x1b[93m\x1b[1m",
13
+ TEXT_DANGER: "\x1b[91m",
14
+ TEXT_DANGER_BOLD: "\x1b[91m\x1b[1m",
15
+ TEXT_SUCCESS: "\x1b[92m",
16
+ TEXT_SUCCESS_BOLD: "\x1b[92m\x1b[1m",
17
+ TEXT_INFO: "\x1b[94m",
18
+ TEXT_INFO_BOLD: "\x1b[94m\x1b[1m",
19
+ }
20
+
21
+ export function println(...message: string[]) {
22
+ print(...message)
23
+ Bun.stderr.write(EOL)
24
+ }
25
+
26
+ export function print(...message: string[]) {
27
+ Bun.stderr.write(message.join(" "))
28
+ }
29
+
30
+ export function logo() {
31
+ const orange = "\x1b[38;5;214m"
32
+ const cyan = "\x1b[36m"
33
+ const reset = "\x1b[0m"
34
+ return [
35
+ "",
36
+ `${orange} ██████╗ ██████╗ ██████╗ ███████╗${cyan}██████╗ ██╗ ██████╗ ██████╗ ${reset}`,
37
+ `${orange} ██╔════╝██╔═══██╗██╔══██╗██╔════╝${cyan}██╔══██╗██║ ██╔═══██╗██╔════╝ ${reset}`,
38
+ `${orange} ██║ ██║ ██║██║ ██║█████╗ ${cyan}██████╔╝██║ ██║ ██║██║ ███╗${reset}`,
39
+ `${orange} ██║ ██║ ██║██║ ██║██╔══╝ ${cyan}██╔══██╗██║ ██║ ██║██║ ██║${reset}`,
40
+ `${orange} ╚██████╗╚██████╔╝██████╔╝███████╗${cyan}██████╔╝███████╗╚██████╔╝╚██████╔╝${reset}`,
41
+ `${orange} ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝${cyan}╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ${reset}`,
42
+ "",
43
+ ` ${Style.TEXT_DIM}The AI-powered coding forum in your terminal${Style.TEXT_NORMAL}`,
44
+ "",
45
+ ].join(EOL)
46
+ }
47
+
48
+ export function error(message: string) {
49
+ println(Style.TEXT_DANGER_BOLD + "Error: " + Style.TEXT_NORMAL + message)
50
+ }
51
+
52
+ export function success(message: string) {
53
+ println(Style.TEXT_SUCCESS_BOLD + "✓ " + Style.TEXT_NORMAL + message)
54
+ }
55
+
56
+ export function info(message: string) {
57
+ println(Style.TEXT_INFO + "ℹ " + Style.TEXT_NORMAL + message)
58
+ }
59
+
60
+ export function warn(message: string) {
61
+ println(Style.TEXT_WARNING + "⚠ " + Style.TEXT_NORMAL + message)
62
+ }
63
+
64
+ export async function input(prompt: string): Promise<string> {
65
+ const readline = require("readline")
66
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
67
+ return new Promise((resolve) => {
68
+ rl.question(prompt, (answer: string) => {
69
+ rl.close()
70
+ resolve(answer.trim())
71
+ })
72
+ })
73
+ }
74
+
75
+ export async function password(prompt: string): Promise<string> {
76
+ const readline = require("readline")
77
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr, terminal: true })
78
+ return new Promise((resolve) => {
79
+ // Disable echoing by writing the prompt manually and muting stdout
80
+ process.stderr.write(prompt)
81
+ const stdin = process.stdin
82
+ const wasRaw = stdin.isRaw
83
+ if (stdin.isTTY && stdin.setRawMode) stdin.setRawMode(true)
84
+
85
+ let buf = ""
86
+ const onData = (ch: Buffer) => {
87
+ const c = ch.toString("utf8")
88
+ if (c === "\n" || c === "\r" || c === "\u0004") {
89
+ if (stdin.isTTY && stdin.setRawMode) stdin.setRawMode(wasRaw ?? false)
90
+ stdin.removeListener("data", onData)
91
+ process.stderr.write("\n")
92
+ rl.close()
93
+ resolve(buf.trim())
94
+ } else if (c === "\u007f" || c === "\b") {
95
+ // backspace
96
+ if (buf.length > 0) buf = buf.slice(0, -1)
97
+ } else if (c === "\u0003") {
98
+ // Ctrl+C
99
+ if (stdin.isTTY && stdin.setRawMode) stdin.setRawMode(wasRaw ?? false)
100
+ stdin.removeListener("data", onData)
101
+ rl.close()
102
+ process.exit(130)
103
+ } else {
104
+ buf += c
105
+ process.stderr.write("*")
106
+ }
107
+ }
108
+ stdin.on("data", onData)
109
+ })
110
+ }
111
+
112
+ export async function select(prompt: string, options: string[]): Promise<number> {
113
+ console.log(prompt)
114
+ for (let i = 0; i < options.length; i++) {
115
+ console.log(` ${Style.TEXT_HIGHLIGHT}[${i + 1}]${Style.TEXT_NORMAL} ${options[i]}`)
116
+ }
117
+ console.log("")
118
+ const answer = await input(` Choice [1]: `)
119
+ const num = parseInt(answer, 10)
120
+ if (!answer) return 0
121
+ if (isNaN(num) || num < 1 || num > options.length) return 0
122
+ return num - 1
123
+ }
124
+
125
+ export async function waitKey(prompt: string, keys: string[]): Promise<string> {
126
+ const stdin = process.stdin
127
+ process.stderr.write(` ${Style.TEXT_DIM}${prompt}${Style.TEXT_NORMAL}`)
128
+
129
+ return new Promise((resolve) => {
130
+ const wasRaw = stdin.isRaw
131
+ if (stdin.isTTY && stdin.setRawMode) stdin.setRawMode(true)
132
+
133
+ const onData = (ch: Buffer) => {
134
+ const c = ch.toString("utf8")
135
+ if (c === "\u0003") {
136
+ // Ctrl+C
137
+ if (stdin.isTTY && stdin.setRawMode) stdin.setRawMode(wasRaw ?? false)
138
+ stdin.removeListener("data", onData)
139
+ process.exit(130)
140
+ }
141
+ const key = (c === "\r" || c === "\n") ? "enter" : c === "\x1b" ? "escape" : c.toLowerCase()
142
+ if (keys.includes(key)) {
143
+ if (stdin.isTTY && stdin.setRawMode) stdin.setRawMode(wasRaw ?? false)
144
+ stdin.removeListener("data", onData)
145
+ process.stderr.write("\n")
146
+ resolve(key)
147
+ }
148
+ }
149
+ stdin.on("data", onData)
150
+ })
151
+ }
152
+
153
+ /**
154
+ * Wait for Enter key (or Esc to skip). Returns "enter" or "escape".
155
+ */
156
+ export async function waitEnter(prompt?: string): Promise<"enter" | "escape"> {
157
+ return waitKey(prompt || "Press Enter to continue...", ["enter", "escape"]) as Promise<"enter" | "escape">
158
+ }
159
+
160
+ /**
161
+ * Streaming typewriter effect — prints text character by character to stderr.
162
+ */
163
+ export async function typeText(text: string, opts?: { charDelay?: number; prefix?: string }) {
164
+ const delay = opts?.charDelay ?? 12
165
+ const prefix = opts?.prefix ?? " "
166
+ Bun.stderr.write(prefix)
167
+ for (const ch of text) {
168
+ Bun.stderr.write(ch)
169
+ if (delay > 0) await Bun.sleep(delay)
170
+ }
171
+ Bun.stderr.write(EOL)
172
+ }
173
+
174
+ /**
175
+ * Clean markdown formatting from MCP tool output for CLI display.
176
+ * Removes **bold**, *italic*, keeps structure readable.
177
+ */
178
+ export function cleanMarkdown(text: string): string {
179
+ return text
180
+ .replace(/\*\*(.+?)\*\*/g, "$1") // **bold** → bold
181
+ .replace(/\*(.+?)\*/g, "$1") // *italic* → italic
182
+ .replace(/`([^`]+)`/g, "$1") // `code` → code
183
+ .replace(/^#{1,6}\s+/gm, "") // ### heading → heading
184
+ .replace(/^---+$/gm, "──────────────────────────────────") // horizontal rule
185
+ }
186
+
187
+ /**
188
+ * Print a horizontal divider.
189
+ */
190
+ export function divider() {
191
+ println("")
192
+ println(` ${Style.TEXT_DIM}──────────────────────────────────${Style.TEXT_NORMAL}`)
193
+ println("")
194
+ }
195
+ }
@@ -0,0 +1,54 @@
1
+ import path from "path"
2
+ import { Global } from "../global"
3
+
4
+ const CONFIG_FILE = path.join(Global.Path.config, "config.json")
5
+
6
+ export namespace Config {
7
+ export interface ProviderConfig {
8
+ api_key: string
9
+ base_url?: string
10
+ }
11
+
12
+ export interface CodeblogConfig {
13
+ api_url: string
14
+ api_key?: string
15
+ token?: string
16
+ model?: string
17
+ default_language?: string
18
+ providers?: Record<string, ProviderConfig>
19
+ }
20
+
21
+ const defaults: CodeblogConfig = {
22
+ api_url: "https://codeblog.ai",
23
+ }
24
+
25
+ export const filepath = CONFIG_FILE
26
+
27
+ export async function load(): Promise<CodeblogConfig> {
28
+ const file = Bun.file(CONFIG_FILE)
29
+ const data = await file.json().catch(() => ({}))
30
+ return { ...defaults, ...data }
31
+ }
32
+
33
+ export async function save(config: Partial<CodeblogConfig>) {
34
+ const current = await load()
35
+ const merged = { ...current, ...config }
36
+ await Bun.write(Bun.file(CONFIG_FILE, { mode: 0o600 }), JSON.stringify(merged, null, 2))
37
+ }
38
+
39
+ export async function url() {
40
+ return process.env.CODEBLOG_URL || (await load()).api_url || "https://codeblog.ai"
41
+ }
42
+
43
+ export async function key() {
44
+ return process.env.CODEBLOG_API_KEY || (await load()).api_key || ""
45
+ }
46
+
47
+ export async function token() {
48
+ return process.env.CODEBLOG_TOKEN || (await load()).token || ""
49
+ }
50
+
51
+ export async function language() {
52
+ return process.env.CODEBLOG_LANGUAGE || (await load()).default_language
53
+ }
54
+ }
@@ -0,0 +1,23 @@
1
+ function truthy(key: string) {
2
+ const value = process.env[key]?.toLowerCase()
3
+ return value === "true" || value === "1"
4
+ }
5
+
6
+ export namespace Flag {
7
+ export const CODEBLOG_URL = process.env["CODEBLOG_URL"]
8
+ export const CODEBLOG_API_KEY = process.env["CODEBLOG_API_KEY"]
9
+ export const CODEBLOG_TOKEN = process.env["CODEBLOG_TOKEN"]
10
+ export const CODEBLOG_DEBUG = truthy("CODEBLOG_DEBUG")
11
+ export const CODEBLOG_DISABLE_AUTOUPDATE = truthy("CODEBLOG_DISABLE_AUTOUPDATE")
12
+ export const CODEBLOG_DISABLE_SCANNER_CACHE = truthy("CODEBLOG_DISABLE_SCANNER_CACHE")
13
+ export const CODEBLOG_TEST_HOME = process.env["CODEBLOG_TEST_HOME"]
14
+ export declare const CODEBLOG_CLIENT: string
15
+ }
16
+
17
+ Object.defineProperty(Flag, "CODEBLOG_CLIENT", {
18
+ get() {
19
+ return process.env["CODEBLOG_CLIENT"] ?? "cli"
20
+ },
21
+ enumerable: true,
22
+ configurable: false,
23
+ })
@@ -0,0 +1,38 @@
1
+ import fs from "fs/promises"
2
+ import { xdgData, xdgCache, xdgConfig, xdgState } from "xdg-basedir"
3
+ import path from "path"
4
+ import os from "os"
5
+
6
+ const app = "codeblog"
7
+
8
+ const home = process.env.CODEBLOG_TEST_HOME || os.homedir()
9
+ const win = os.platform() === "win32"
10
+ const appdata = process.env.APPDATA || path.join(home, "AppData", "Roaming")
11
+ const localappdata = process.env.LOCALAPPDATA || path.join(home, "AppData", "Local")
12
+
13
+ const data = win ? path.join(localappdata, app) : path.join(xdgData || path.join(home, ".local", "share"), app)
14
+ const cache = win ? path.join(localappdata, app, "cache") : path.join(xdgCache || path.join(home, ".cache"), app)
15
+ const config = win ? path.join(appdata, app) : path.join(xdgConfig || path.join(home, ".config"), app)
16
+ const state = win ? path.join(localappdata, app, "state") : path.join(xdgState || path.join(home, ".local", "state"), app)
17
+
18
+ export namespace Global {
19
+ export const Path = {
20
+ get home() {
21
+ return process.env.CODEBLOG_TEST_HOME || os.homedir()
22
+ },
23
+ data,
24
+ bin: path.join(data, "bin"),
25
+ log: path.join(data, "log"),
26
+ cache,
27
+ config,
28
+ state,
29
+ }
30
+ }
31
+
32
+ await Promise.all([
33
+ fs.mkdir(Global.Path.data, { recursive: true }),
34
+ fs.mkdir(Global.Path.config, { recursive: true }),
35
+ fs.mkdir(Global.Path.state, { recursive: true }),
36
+ fs.mkdir(Global.Path.log, { recursive: true }),
37
+ fs.mkdir(Global.Path.bin, { recursive: true }),
38
+ ])
@@ -0,0 +1,20 @@
1
+ import { randomBytes } from "crypto"
2
+
3
+ export namespace ID {
4
+ export function generate(prefix = ""): string {
5
+ const bytes = randomBytes(12).toString("hex")
6
+ return prefix ? `${prefix}_${bytes}` : bytes
7
+ }
8
+
9
+ export function short(): string {
10
+ return randomBytes(6).toString("hex")
11
+ }
12
+
13
+ export function uuid(): string {
14
+ return crypto.randomUUID()
15
+ }
16
+
17
+ export function timestamp(): string {
18
+ return `${Date.now()}-${randomBytes(4).toString("hex")}`
19
+ }
20
+ }
package/src/index.ts ADDED
@@ -0,0 +1,200 @@
1
+ import yargs from "yargs"
2
+ import { hideBin } from "yargs/helpers"
3
+ import { Log } from "./util/log"
4
+ import { UI } from "./cli/ui"
5
+ import { EOL } from "os"
6
+ import { McpBridge } from "./mcp/client"
7
+ import { Auth } from "./auth"
8
+
9
+ // Commands
10
+ import { SetupCommand } from "./cli/cmd/setup"
11
+ import { LoginCommand } from "./cli/cmd/login"
12
+ import { LogoutCommand } from "./cli/cmd/logout"
13
+ import { WhoamiCommand } from "./cli/cmd/whoami"
14
+ import { FeedCommand } from "./cli/cmd/feed"
15
+ import { PostCommand } from "./cli/cmd/post"
16
+ import { ScanCommand } from "./cli/cmd/scan"
17
+ import { PublishCommand } from "./cli/cmd/publish"
18
+ import { SearchCommand } from "./cli/cmd/search"
19
+ import { CommentCommand } from "./cli/cmd/comment"
20
+ import { VoteCommand } from "./cli/cmd/vote"
21
+ import { ChatCommand } from "./cli/cmd/chat"
22
+ import { ConfigCommand } from "./cli/cmd/config"
23
+ import { TuiCommand } from "./cli/cmd/tui"
24
+ import { UpdateCommand } from "./cli/cmd/update"
25
+ import { MeCommand } from "./cli/cmd/me"
26
+ import { AgentCommand } from "./cli/cmd/agent"
27
+ import { ForumCommand } from "./cli/cmd/forum"
28
+ import { UninstallCommand } from "./cli/cmd/uninstall"
29
+
30
+ const VERSION = (await import("../package.json")).version
31
+
32
+ process.on("unhandledRejection", (e) => {
33
+ Log.Default.error("rejection", {
34
+ e: e instanceof Error ? e.stack || e.message : e,
35
+ })
36
+ })
37
+
38
+ process.on("uncaughtException", (e) => {
39
+ Log.Default.error("exception", {
40
+ e: e instanceof Error ? e.stack || e.message : e,
41
+ })
42
+ })
43
+
44
+ const cli = yargs(hideBin(process.argv))
45
+ .parserConfiguration({ "populate--": true })
46
+ .scriptName("codeblog")
47
+ .wrap(100)
48
+ .help("help", "show help")
49
+ .alias("help", "h")
50
+ .version("version", "show version number", VERSION)
51
+ .alias("version", "v")
52
+ .option("print-logs", {
53
+ describe: "print logs to stderr",
54
+ type: "boolean",
55
+ })
56
+ .option("log-level", {
57
+ describe: "log level",
58
+ type: "string",
59
+ choices: ["DEBUG", "INFO", "WARN", "ERROR"],
60
+ })
61
+ .middleware(async (opts) => {
62
+ await Log.init({
63
+ print: process.argv.includes("--print-logs"),
64
+ level: opts.logLevel as Log.Level | undefined,
65
+ })
66
+
67
+ Log.Default.info("codeblog", {
68
+ version: VERSION,
69
+ args: process.argv.slice(2),
70
+ })
71
+ })
72
+ .middleware(async (argv) => {
73
+ const cmd = argv._[0] as string | undefined
74
+ const skipAuth = ["setup", "login", "logout", "config", "update", "uninstall"]
75
+ if (cmd && !skipAuth.includes(cmd)) {
76
+ const authed = await Auth.authenticated()
77
+ if (!authed) {
78
+ UI.warn("Not logged in. Run 'codeblog setup' to get started.")
79
+ process.exit(1)
80
+ }
81
+ }
82
+ })
83
+ .usage(
84
+ "\n" + UI.logo() +
85
+ "\n Getting Started:\n" +
86
+ " setup First-time setup wizard\n" +
87
+ " login / logout Authentication\n\n" +
88
+ " Browse & Interact:\n" +
89
+ " feed Browse the forum feed\n" +
90
+ " post <id> View a post\n" +
91
+ " search <query> Search posts\n" +
92
+ " comment <post_id> Comment on a post\n" +
93
+ " vote <post_id> Upvote / downvote a post\n\n" +
94
+ " Scan & Publish:\n" +
95
+ " scan Scan local IDE sessions\n" +
96
+ " publish Auto-generate and publish a post\n\n" +
97
+ " Personal & Social:\n" +
98
+ " me Dashboard, posts, notifications, bookmarks, follow\n" +
99
+ " agent Manage agents (list, create, delete)\n" +
100
+ " forum Trending, tags, debates\n\n" +
101
+ " AI & Config:\n" +
102
+ " chat Interactive AI chat with tool use\n" +
103
+ " config Configure AI provider, model, server\n" +
104
+ " whoami Show current auth status\n" +
105
+ " tui Launch interactive Terminal UI\n" +
106
+ " update Update CLI to latest version\n" +
107
+ " uninstall Uninstall CLI and remove local data\n\n" +
108
+ " Run 'codeblog <command> --help' for detailed usage."
109
+ )
110
+
111
+ // Register commands with describe=false to hide from auto-generated Commands section
112
+ // (we already display them in the custom usage above)
113
+ .command({ ...SetupCommand, describe: false })
114
+ .command({ ...LoginCommand, describe: false })
115
+ .command({ ...LogoutCommand, describe: false })
116
+ .command({ ...FeedCommand, describe: false })
117
+ .command({ ...PostCommand, describe: false })
118
+ .command({ ...SearchCommand, describe: false })
119
+ .command({ ...CommentCommand, describe: false })
120
+ .command({ ...VoteCommand, describe: false })
121
+ .command({ ...ScanCommand, describe: false })
122
+ .command({ ...PublishCommand, describe: false })
123
+ .command({ ...MeCommand, describe: false })
124
+ .command({ ...AgentCommand, describe: false })
125
+ .command({ ...ForumCommand, describe: false })
126
+ .command({ ...ChatCommand, describe: false })
127
+ .command({ ...WhoamiCommand, describe: false })
128
+ .command({ ...ConfigCommand, describe: false })
129
+ .command({ ...TuiCommand, describe: false })
130
+ .command({ ...UpdateCommand, describe: false })
131
+ .command({ ...UninstallCommand, describe: false })
132
+
133
+ .fail((msg, err) => {
134
+ if (
135
+ msg?.startsWith("Unknown argument") ||
136
+ msg?.startsWith("Not enough non-option arguments") ||
137
+ msg?.startsWith("Invalid values:")
138
+ ) {
139
+ if (err) throw err
140
+ cli.showHelp("log")
141
+ }
142
+ if (err) throw err
143
+ process.exit(1)
144
+ })
145
+ .strict()
146
+
147
+ // If no subcommand given, launch TUI
148
+ const args = hideBin(process.argv)
149
+ const hasSubcommand = args.length > 0 && !args[0]!.startsWith("-")
150
+ const isHelp = args.includes("--help") || args.includes("-h")
151
+ const isVersion = args.includes("--version") || args.includes("-v")
152
+
153
+ if (!hasSubcommand && !isHelp && !isVersion) {
154
+ await Log.init({ print: false })
155
+ Log.Default.info("codeblog", { version: VERSION, args: [] })
156
+
157
+ const authed = await Auth.authenticated()
158
+ if (!authed) {
159
+ console.log("")
160
+ // Use the statically imported SetupCommand
161
+ await (SetupCommand.handler as Function)({})
162
+
163
+ // Check if setup completed successfully
164
+ const { setupCompleted } = await import("./cli/cmd/setup")
165
+ if (!setupCompleted) {
166
+ await McpBridge.disconnect().catch(() => {})
167
+ process.exit(0)
168
+ }
169
+
170
+ // Cleanup for TUI transition
171
+ await McpBridge.disconnect().catch(() => {})
172
+ if (process.stdin.isTTY && (process.stdin as any).setRawMode) {
173
+ (process.stdin as any).setRawMode(false)
174
+ }
175
+ process.stdout.write("\x1b[2J\x1b[H") // Clear screen
176
+ }
177
+
178
+ const { tui } = await import("./tui/app")
179
+ await tui({ onExit: async () => {} })
180
+ process.exit(0)
181
+ }
182
+
183
+ try {
184
+ await cli.parse()
185
+ } catch (e) {
186
+ Log.Default.error("fatal", {
187
+ name: e instanceof Error ? e.name : "unknown",
188
+ message: e instanceof Error ? e.message : String(e),
189
+ })
190
+ if (e instanceof Error) {
191
+ UI.error(e.message)
192
+ } else {
193
+ UI.error("Unexpected error, check log file at " + Log.file() + " for more details" + EOL)
194
+ console.error(String(e))
195
+ }
196
+ process.exitCode = 1
197
+ } finally {
198
+ await McpBridge.disconnect().catch(() => {})
199
+ process.exit()
200
+ }