thatgfsj-code 1.0.3 → 3.0.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 (184) hide show
  1. package/CHANGELOG.md +192 -0
  2. package/DEVELOPMENT.md +286 -0
  3. package/dist/app/index.d.ts +40 -3
  4. package/dist/app/index.d.ts.map +1 -1
  5. package/dist/app/index.js +87 -12
  6. package/dist/app/index.js.map +1 -1
  7. package/dist/cache/fingerprint.d.ts +49 -0
  8. package/dist/cache/fingerprint.d.ts.map +1 -0
  9. package/dist/cache/fingerprint.js +100 -0
  10. package/dist/cache/fingerprint.js.map +1 -0
  11. package/dist/cache/index.d.ts +15 -0
  12. package/dist/cache/index.d.ts.map +1 -0
  13. package/dist/cache/index.js +15 -0
  14. package/dist/cache/index.js.map +1 -0
  15. package/dist/cache/smartModel.d.ts +40 -0
  16. package/dist/cache/smartModel.d.ts.map +1 -0
  17. package/dist/cache/smartModel.js +43 -0
  18. package/dist/cache/smartModel.js.map +1 -0
  19. package/dist/cache/stats.d.ts +93 -0
  20. package/dist/cache/stats.d.ts.map +1 -0
  21. package/dist/cache/stats.js +155 -0
  22. package/dist/cache/stats.js.map +1 -0
  23. package/dist/cache/volatile.d.ts +32 -0
  24. package/dist/cache/volatile.d.ts.map +1 -0
  25. package/dist/cache/volatile.js +44 -0
  26. package/dist/cache/volatile.js.map +1 -0
  27. package/dist/cmd/index.d.ts +21 -0
  28. package/dist/cmd/index.d.ts.map +1 -1
  29. package/dist/cmd/index.js +155 -31
  30. package/dist/cmd/index.js.map +1 -1
  31. package/dist/config/index.d.ts.map +1 -1
  32. package/dist/config/index.js +8 -0
  33. package/dist/config/index.js.map +1 -1
  34. package/dist/config/types.d.ts +14 -0
  35. package/dist/config/types.d.ts.map +1 -1
  36. package/dist/llm/anthropic.d.ts +55 -5
  37. package/dist/llm/anthropic.d.ts.map +1 -1
  38. package/dist/llm/anthropic.js +172 -26
  39. package/dist/llm/anthropic.js.map +1 -1
  40. package/dist/llm/index.d.ts +26 -8
  41. package/dist/llm/index.d.ts.map +1 -1
  42. package/dist/llm/index.js +83 -15
  43. package/dist/llm/index.js.map +1 -1
  44. package/dist/llm/openai.d.ts +28 -8
  45. package/dist/llm/openai.d.ts.map +1 -1
  46. package/dist/llm/openai.js +58 -8
  47. package/dist/llm/openai.js.map +1 -1
  48. package/dist/llm/provider.d.ts +40 -8
  49. package/dist/llm/provider.d.ts.map +1 -1
  50. package/dist/llm/provider.js +8 -1
  51. package/dist/llm/provider.js.map +1 -1
  52. package/dist/prompts/index.d.ts +32 -0
  53. package/dist/prompts/index.d.ts.map +1 -1
  54. package/dist/prompts/index.js +33 -11
  55. package/dist/prompts/index.js.map +1 -1
  56. package/dist/session/index.d.ts +43 -3
  57. package/dist/session/index.d.ts.map +1 -1
  58. package/dist/session/index.js +114 -17
  59. package/dist/session/index.js.map +1 -1
  60. package/dist/skills/brainstorming.js +33 -33
  61. package/dist/skills/code-review.js +35 -35
  62. package/dist/skills/executing-plans.js +18 -18
  63. package/dist/skills/frontend-design.js +25 -25
  64. package/dist/skills/git-workflow.js +26 -26
  65. package/dist/skills/improve-architecture.js +28 -28
  66. package/dist/skills/neuroweave.js +37 -37
  67. package/dist/skills/playwright.js +62 -62
  68. package/dist/skills/prototype.js +20 -20
  69. package/dist/skills/subagent.js +19 -19
  70. package/dist/skills/supabase.js +34 -34
  71. package/dist/skills/systematic-debugging.js +34 -34
  72. package/dist/skills/tdd.js +29 -29
  73. package/dist/skills/triage.js +25 -25
  74. package/dist/skills/verification.js +22 -22
  75. package/dist/skills/writing-plans.js +32 -32
  76. package/dist/tools/nwt.js +16 -16
  77. package/dist/tui/app.d.ts.map +1 -1
  78. package/dist/tui/app.js +9 -2
  79. package/dist/tui/app.js.map +1 -1
  80. package/dist/tui/components/ChatList.d.ts.map +1 -1
  81. package/dist/tui/components/ChatList.js +4 -3
  82. package/dist/tui/components/ChatList.js.map +1 -1
  83. package/dist/tui/components/Header.d.ts +8 -0
  84. package/dist/tui/components/Header.d.ts.map +1 -1
  85. package/dist/tui/components/Header.js +17 -3
  86. package/dist/tui/components/Header.js.map +1 -1
  87. package/dist/tui/components/InitWizard.d.ts +12 -1
  88. package/dist/tui/components/InitWizard.d.ts.map +1 -1
  89. package/dist/tui/components/InitWizard.js +58 -3
  90. package/dist/tui/components/InitWizard.js.map +1 -1
  91. package/dist/tui/components/ToolCall.d.ts +1 -1
  92. package/dist/tui/components/ToolCall.d.ts.map +1 -1
  93. package/dist/tui/components/ToolCall.js +4 -4
  94. package/dist/tui/components/ToolCall.js.map +1 -1
  95. package/dist/tui/hooks/useChat.d.ts +22 -0
  96. package/dist/tui/hooks/useChat.d.ts.map +1 -1
  97. package/dist/tui/hooks/useChat.js +127 -50
  98. package/dist/tui/hooks/useChat.js.map +1 -1
  99. package/dist/tui/hooks/useCommands.d.ts.map +1 -1
  100. package/dist/tui/hooks/useCommands.js +78 -0
  101. package/dist/tui/hooks/useCommands.js.map +1 -1
  102. package/dist/types.d.ts +79 -6
  103. package/dist/types.d.ts.map +1 -1
  104. package/dist/types.js +7 -0
  105. package/dist/types.js.map +1 -1
  106. package/dist/utils/stableStringify.d.ts +21 -0
  107. package/dist/utils/stableStringify.d.ts.map +1 -0
  108. package/dist/utils/stableStringify.js +53 -0
  109. package/dist/utils/stableStringify.js.map +1 -0
  110. package/dist/utils/thinking.d.ts +59 -0
  111. package/dist/utils/thinking.d.ts.map +1 -0
  112. package/dist/utils/thinking.js +104 -0
  113. package/dist/utils/thinking.js.map +1 -0
  114. package/install.bat +63 -0
  115. package/install.ps1 +238 -0
  116. package/install.sh +113 -0
  117. package/package.json +7 -4
  118. package/src/app/index.ts +180 -108
  119. package/src/cache/fingerprint.ts +101 -0
  120. package/src/cache/index.ts +15 -0
  121. package/src/cache/smartModel.ts +52 -0
  122. package/src/cache/stats.ts +199 -0
  123. package/src/cache/volatile.ts +47 -0
  124. package/src/cmd/index.tsx +288 -160
  125. package/src/config/index.ts +156 -148
  126. package/src/config/providers.ts +234 -234
  127. package/src/config/types.ts +67 -53
  128. package/src/hooks/index.ts +111 -111
  129. package/src/llm/anthropic.ts +388 -243
  130. package/src/llm/gemini.ts +169 -169
  131. package/src/llm/index.ts +265 -200
  132. package/src/llm/openai.ts +243 -196
  133. package/src/llm/provider.ts +66 -34
  134. package/src/prompts/index.ts +260 -220
  135. package/src/session/compactor.ts +103 -103
  136. package/src/session/index.ts +181 -87
  137. package/src/session/message.ts +42 -42
  138. package/src/skills/brainstorming.ts +43 -43
  139. package/src/skills/code-review.ts +45 -45
  140. package/src/skills/executing-plans.ts +27 -27
  141. package/src/skills/frontend-design.ts +35 -35
  142. package/src/skills/git-workflow.ts +36 -36
  143. package/src/skills/improve-architecture.ts +38 -38
  144. package/src/skills/index.ts +136 -136
  145. package/src/skills/neuroweave.ts +47 -47
  146. package/src/skills/playwright.ts +72 -72
  147. package/src/skills/prototype.ts +30 -30
  148. package/src/skills/subagent.ts +28 -28
  149. package/src/skills/supabase.ts +44 -44
  150. package/src/skills/systematic-debugging.ts +44 -44
  151. package/src/skills/tdd.ts +39 -39
  152. package/src/skills/triage.ts +35 -35
  153. package/src/skills/verification.ts +31 -31
  154. package/src/skills/writing-plans.ts +42 -42
  155. package/src/tools/nwt.ts +598 -598
  156. package/src/tools/types.ts +122 -122
  157. package/src/tui/app.tsx +199 -186
  158. package/src/tui/components/ChatList.tsx +41 -32
  159. package/src/tui/components/ChatMessage.tsx +54 -54
  160. package/src/tui/components/Header.tsx +56 -28
  161. package/src/tui/components/InitWizard.tsx +217 -132
  162. package/src/tui/components/Markdown.tsx +35 -35
  163. package/src/tui/components/ModelSelector.tsx +87 -87
  164. package/src/tui/components/StatusBar.tsx +30 -30
  165. package/src/tui/components/Thinking.tsx +17 -17
  166. package/src/tui/components/ToolCall.tsx +102 -71
  167. package/src/tui/components/UserInput.tsx +131 -131
  168. package/src/tui/hooks/useChat.ts +287 -194
  169. package/src/tui/hooks/useCommands.ts +234 -154
  170. package/src/tui/index.ts +6 -6
  171. package/src/tui/welcome.ts +177 -177
  172. package/src/types.ts +104 -42
  173. package/src/utils/diff.ts +71 -71
  174. package/src/utils/project.ts +99 -99
  175. package/src/utils/stableStringify.ts +47 -0
  176. package/src/utils/thinking.ts +119 -0
  177. package/tests/cache/fingerprint.test.ts +75 -0
  178. package/tests/cache/stableStringify.test.ts +43 -0
  179. package/tests/cache/stats.test.ts +146 -0
  180. package/tests/cache/volatile.test.ts +75 -0
  181. package/tests/smoke-pollution.mjs +78 -0
  182. package/tests/smoke-thinking.mjs +110 -0
  183. package/tests/smoke-tool-stream.mjs +69 -0
  184. package/tests/smoke-tool.mjs +117 -0
@@ -0,0 +1,47 @@
1
+ /**
2
+ * VolatileScratch — per-round reasoning / planning state that MUST NOT be
3
+ * uploaded to the API.
4
+ *
5
+ * Reasonix Principle #3 (Volatile Scratch):
6
+ * The model's thinking content, intermediate plans, and other
7
+ * intra-round state should never be appended to the conversation
8
+ * history. They are useful for the UI (so users can debug / audit
9
+ * reasoning) and for cross-iteration handoff within the same round
10
+ * (e.g. retry-after-tool-failure), but they are NOT part of the cache
11
+ * prefix and re-uploading them in the next round would:
12
+ * 1. waste tokens (potentially a lot — reasoning can dwarf the answer)
13
+ * 2. cause context-window pressure
14
+ * 3. risk leaking partial / contradictory reasoning back to the model
15
+ *
16
+ * Usage (in LLMService / useChat when receiving 'thinking' chunks):
17
+ * scratch.write(chunk.content);
18
+ * // ... later in the same round ...
19
+ * scratch.read(); // → joined reasoning so far
20
+ * scratch.reset(); // → call at end of round OR on /new
21
+ */
22
+ export class VolatileScratch {
23
+ private current: string[] = [];
24
+
25
+ reset(): void {
26
+ this.current = [];
27
+ }
28
+
29
+ write(data: string): void {
30
+ if (!data) return;
31
+ this.current.push(data);
32
+ }
33
+
34
+ read(): string {
35
+ return this.current.join('\n');
36
+ }
37
+
38
+ /** True when no scratch has been written since the last reset. */
39
+ isEmpty(): boolean {
40
+ return this.current.length === 0;
41
+ }
42
+
43
+ /** Number of segments written. Useful for UI display ("thought for N lines"). */
44
+ size(): number {
45
+ return this.current.length;
46
+ }
47
+ }
package/src/cmd/index.tsx CHANGED
@@ -1,160 +1,288 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Thatgfsj Code - CLI Entry Point
5
- */
6
-
7
- if (process.platform === 'win32') {
8
- try {
9
- require('child_process').execSync('chcp 65001', { stdio: 'ignore', windowsHide: true });
10
- } catch {}
11
- }
12
-
13
- import { program } from 'commander';
14
- import chalk from 'chalk';
15
- import { App } from '../app/index.js';
16
- import { WelcomeScreen } from '../tui/welcome.js';
17
-
18
- process.on('uncaughtException', (error) => {
19
- console.error(chalk.red('\n Error:'), error.message);
20
- process.exit(1);
21
- });
22
-
23
- process.on('unhandledRejection', (reason) => {
24
- console.error(chalk.red('\n Error:'), reason);
25
- process.exit(1);
26
- });
27
-
28
- program
29
- .name('gfcode')
30
- .description('Thatgfsj Code - AI Coding Assistant')
31
- .version('1.0.3')
32
- .argument('[prompt]', 'Task to execute (omit to start interactive mode)')
33
- .option('-m, --model <model>', 'Specify model')
34
- .option('-i, --interactive', 'Force interactive mode')
35
- .action(async (prompt: string | undefined, options: { model?: string; interactive?: boolean }) => {
36
- try {
37
- const app = await App.create();
38
-
39
- // Check if API key is configured
40
- if (!app.config.hasApiKey()) {
41
- console.log(chalk.yellow('\n ⚠ No API key configured\n'));
42
- console.log(chalk.gray(' Run ') + chalk.cyan('gfcode init') + chalk.gray(' to set up your provider.\n'));
43
- const readline = await import('readline');
44
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
45
- const answer = await new Promise<string>(resolve => {
46
- rl.question(chalk.cyan(' Run init now? (Y/n): '), resolve);
47
- });
48
- rl.close();
49
- if (answer.toLowerCase() !== 'n') {
50
- await WelcomeScreen.interactiveSetup();
51
- // Reload config after setup
52
- const newApp = await App.create();
53
- Object.assign(app, newApp);
54
- } else {
55
- process.exit(0);
56
- }
57
- }
58
-
59
- if (options.model) {
60
- await app.config.save({ model: options.model });
61
- }
62
-
63
- if (!prompt || options.interactive) {
64
- // Interactive mode - Ink TUI
65
- const { render } = await import('ink');
66
- const { TuiApp } = await import('../tui/app.js');
67
- const { unmount } = render(<TuiApp app={app} />);
68
- await new Promise<void>((resolve) => {
69
- process.on('exit', () => { unmount(); resolve(); });
70
- });
71
- } else {
72
- // Single prompt mode
73
- console.log(chalk.cyan.bold('\n ⚡ THATGFSJ CODE\n'));
74
- console.log(chalk.gray(' You'));
75
- console.log(chalk.gray(' ' + '─'.repeat(40)));
76
- console.log(' ' + prompt);
77
- console.log();
78
-
79
- app.session.addMessage('user', prompt);
80
- let fullResponse = '';
81
-
82
- try {
83
- process.stdout.write(chalk.gray(' Thinking...\r'));
84
- const stream = app.streamResponse();
85
-
86
- for await (const chunk of stream) {
87
- // Clear thinking line
88
- process.stdout.write('\r' + ' '.repeat(40) + '\r');
89
-
90
- // Parse tool messages
91
- if (chunk.includes('@@TOOL@@')) {
92
- const parts = chunk.split('\n');
93
- for (const part of parts) {
94
- if (part.startsWith('@@TOOL@@')) {
95
- try {
96
- const data = JSON.parse(part.slice(8));
97
- if (data.action === 'call') {
98
- console.log();
99
- console.log(chalk.cyan(` ⚙ ${data.name}: ${formatArgs(data.args)}`));
100
- } else if (data.action === 'result') {
101
- const output = data.output || data.error || '';
102
- const lines = output.split('\n').slice(0, 10);
103
- for (const line of lines) {
104
- console.log(chalk.gray(' │ ') + line);
105
- }
106
- }
107
- } catch {}
108
- } else if (part) {
109
- process.stdout.write(chalk.cyan(' │ ') + part);
110
- }
111
- }
112
- } else {
113
- process.stdout.write(chunk);
114
- }
115
- fullResponse += chunk;
116
- }
117
-
118
- console.log();
119
- app.session.addMessage('assistant', fullResponse);
120
- } catch (error: any) {
121
- const msg = error.message || String(error);
122
- if (msg.includes('401') || msg.includes('403') || msg.includes('Unauthorized')) {
123
- console.error(chalk.red('\n ❌ API key invalid or expired.'));
124
- console.log(chalk.gray(' Run ') + chalk.cyan('gfcode init') + chalk.gray(' to reconfigure.\n'));
125
- } else if (msg.includes('429') || msg.includes('rate limit') || msg.includes('quota')) {
126
- console.error(chalk.red('\n ❌ Rate limit or quota exceeded.'));
127
- console.log(chalk.gray(' Wait or run ') + chalk.cyan('gfcode init') + chalk.gray(' to switch provider.\n'));
128
- } else if (msg.includes('ECONNREFUSED') || msg.includes('ENOTFOUND')) {
129
- console.error(chalk.red('\n ❌ Cannot connect to API server.'));
130
- console.log(chalk.gray(' Check network or run ') + chalk.cyan('gfcode init') + chalk.gray('.\n'));
131
- } else {
132
- console.error(chalk.red(`\n Error: ${msg}`));
133
- }
134
- }
135
- }
136
- } catch (error: any) {
137
- console.error(chalk.red(`\n ${error.message}`));
138
- process.exit(1);
139
- }
140
- });
141
-
142
- program
143
- .command('init')
144
- .description('Configure API key and model')
145
- .action(async () => {
146
- await WelcomeScreen.interactiveSetup();
147
- });
148
-
149
- program.parse(process.argv);
150
-
151
- function formatArgs(args: string): string {
152
- try {
153
- const obj = JSON.parse(args);
154
- return Object.entries(obj)
155
- .map(([k, v]) => `${k}=${typeof v === 'string' && v.length > 40 ? v.slice(0, 40) + '...' : JSON.stringify(v)}`)
156
- .join(' ');
157
- } catch {
158
- return args.length > 60 ? args.slice(0, 60) + '...' : args;
159
- }
160
- }
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Thatgfsj Code - CLI Entry Point
5
+ *
6
+ * v2.2.4 (product 0.4.1): three concrete fixes for the bugs visible
7
+ * in the 2.2.3 (product 0.4.0) session log:
8
+ *
9
+ * 1. Encoding: chcp 65001 used to be wrapped in a silent try/catch,
10
+ * and stdout never had its default encoding set. On Windows this
11
+ * caused Chinese characters from tool output to render as
12
+ * mojibake (ļ ʹ ϵͳ Ƿ ...).
13
+ *
14
+ * 2. [已中断] hallucination loop: 1.0.4's SessionManager had no
15
+ * anti-pollution filter. When the user pressed Ctrl+C mid-
16
+ * stream, the truncated assistant message (containing the
17
+ * model's literal "[已中断]" marker) got persisted to history.
18
+ * On the next turn, the model saw that and kept echoing it.
19
+ * v2.1.0 had the right fix (_wasAborted flag + filter) — we
20
+ * port it back here.
21
+ *
22
+ * 3. Tool output visual: 1.0.4 printed `@@TOOL@@{...}` markers
23
+ * inline with text, no separator, no truncation. Long tool
24
+ * output (registry dumps, dir listings) bled into the next
25
+ * AI message. Add separator + truncation + color separation.
26
+ */
27
+
28
+ if (process.platform === 'win32') {
29
+ // Switch Windows console to UTF-8 BEFORE any other code runs.
30
+ // v2.2.3 wrapped this in `try { } catch {}` which silently swallowed
31
+ // failures (e.g. when running under a non-interactive shell where
32
+ // chcp is meaningless). Now we still try, but we also fall back to
33
+ // setting the codepage via the parent process's stdio handles.
34
+ try {
35
+ require('child_process').execSync('chcp 65001 >NUL', { stdio: 'ignore', windowsHide: true });
36
+ } catch {
37
+ // Non-Windows shell, or chcp unavailable (e.g. git-bash on CI)
38
+ // that's fine, Node defaults to UTF-8 in that environment.
39
+ }
40
+ }
41
+
42
+ // Force stdout/stderr to UTF-8 regardless of platform. Without this,
43
+ // Node will emit GBK-encoded bytes for non-ASCII characters on
44
+ // Windows even after `chcp 65001`, because the underlying file
45
+ // descriptors still report a non-UTF-8 code page.
46
+ if (process.stdout.setDefaultEncoding) {
47
+ process.stdout.setDefaultEncoding('utf8');
48
+ }
49
+ if (process.stderr.setDefaultEncoding) {
50
+ process.stderr.setDefaultEncoding('utf8');
51
+ }
52
+
53
+ import { program } from 'commander';
54
+ import chalk from 'chalk';
55
+ import { App } from '../app/index.js';
56
+ import { WelcomeScreen } from '../tui/welcome.js';
57
+ import { compressThinking, summarizeThinking, splitThinking } from '../utils/thinking.js';
58
+
59
+ process.on('uncaughtException', (error) => {
60
+ console.error(chalk.red('\n Error:'), error.message);
61
+ process.exit(1);
62
+ });
63
+
64
+ process.on('unhandledRejection', (reason) => {
65
+ console.error(chalk.red('\n Error:'), reason);
66
+ process.exit(1);
67
+ });
68
+
69
+ program
70
+ .name('gfcode')
71
+ .description('Thatgfsj Code - AI Coding Assistant')
72
+ .version('0.5.0')
73
+ .argument('[prompt]', 'Task to execute (omit to start interactive mode)')
74
+ .option('-m, --model <model>', 'Specify model')
75
+ .option('-i, --interactive', 'Force interactive mode')
76
+ .option('--show-thinking', 'Show full <think>...</think> reasoning blocks (default: compress to one-line summary)')
77
+ .action(async (prompt: string | undefined, options: { model?: string; interactive?: boolean; showThinking?: boolean }) => {
78
+ try {
79
+ const app = await App.create();
80
+
81
+ // Check if API key is configured
82
+ if (!app.config.hasApiKey()) {
83
+ console.log(chalk.yellow('\n ⚠ No API key configured\n'));
84
+ console.log(chalk.gray(' Run ') + chalk.cyan('gfcode init') + chalk.gray(' to set up your provider.\n'));
85
+ const readline = await import('readline');
86
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
87
+ const answer = await new Promise<string>(resolve => {
88
+ rl.question(chalk.cyan(' Run init now? (Y/n): '), resolve);
89
+ });
90
+ rl.close();
91
+ if (answer.toLowerCase() !== 'n') {
92
+ await WelcomeScreen.interactiveSetup();
93
+ // Reload config after setup
94
+ const newApp = await App.create();
95
+ Object.assign(app, newApp);
96
+ } else {
97
+ process.exit(0);
98
+ }
99
+ }
100
+
101
+ if (options.model) {
102
+ await app.config.save({ model: options.model });
103
+ }
104
+
105
+ if (!prompt || options.interactive) {
106
+ // Interactive mode - Ink TUI
107
+ const { render } = await import('ink');
108
+ const { TuiApp } = await import('../tui/app.js');
109
+ const { unmount } = render(<TuiApp app={app} />);
110
+ await new Promise<void>((resolve) => {
111
+ process.on('exit', () => { unmount(); resolve(); });
112
+ });
113
+ } else {
114
+ // Single prompt mode
115
+ console.log(chalk.cyan.bold('\n ⚡ THATGFSJ CODE\n'));
116
+ console.log(chalk.gray(' You'));
117
+ console.log(chalk.gray(' ' + '─'.repeat(40)));
118
+ console.log(' ' + prompt);
119
+ console.log();
120
+
121
+ app.session.addMessage('user', prompt);
122
+ let fullResponse = '';
123
+ // v2.2.4: track whether the stream was aborted so we don't
124
+ // persist a truncated assistant message (which is what caused
125
+ // the [已中断] hallucination loop in v2.2.3).
126
+ const abortCtrl = new AbortController();
127
+ const onSigInt = () => { abortCtrl.abort(); };
128
+ process.once('SIGINT', onSigInt);
129
+ // v2.2.5 (product 0.4.2): compress <think> blocks at render time
130
+ // AND before persisting to history. Without this, every assistant
131
+ // message balloons history with reasoning the user has already
132
+ // seen compressed, and context windows blow up fast.
133
+ const showThinking = !!options.showThinking;
134
+
135
+ try {
136
+ process.stdout.write(chalk.gray(' Thinking...'));
137
+ const stream = app.streamResponse();
138
+
139
+ // v3.0.0: stream is now AsyncGenerator<StreamChunk> instead of
140
+ // string. Tool calls come as { type: 'tool_calls', toolCalls }
141
+ // with structured args; usage comes as { type: 'usage', usage }
142
+ // at end. We render text live, render tool dispatches inline, and
143
+ // capture the final response text into fullResponse for the
144
+ // post-process step below.
145
+ for await (const chunk of stream) {
146
+ if (abortCtrl.signal.aborted) break;
147
+ // Clear the entire "Thinking..." line — must use enough
148
+ // spaces to overwrite any longer thinking indicator.
149
+ process.stdout.write('\r' + ' '.repeat(80) + '\r');
150
+
151
+ switch (chunk.type) {
152
+ case 'text': {
153
+ if (chunk.content) {
154
+ fullResponse += chunk.content;
155
+ // Show the chunk as it streams, but we'll re-render the
156
+ // final compressed version below. To avoid double-
157
+ // printing, only echo when we're NOT going to post-
158
+ // process (i.e., when showThinking is true and we want
159
+ // to see everything live).
160
+ if (showThinking) {
161
+ process.stdout.write(chalk.cyan(' │ ') + chunk.content);
162
+ }
163
+ }
164
+ break;
165
+ }
166
+ case 'thinking': {
167
+ // Reasoning content. Strip from persisted content via
168
+ // compressThinking; show live if user asked for it.
169
+ if (showThinking && chunk.content) {
170
+ fullResponse += chunk.content;
171
+ process.stdout.write(chalk.cyan(' │ ') + chunk.content);
172
+ }
173
+ break;
174
+ }
175
+ case 'tool_calls': {
176
+ if (chunk.toolCalls && chunk.toolCalls.length > 0) {
177
+ for (const tc of chunk.toolCalls) {
178
+ console.log();
179
+ console.log(chalk.cyan(` ⚙ ${tc.function.name}: ${formatArgs(tc.function.arguments)}`));
180
+ console.log(chalk.gray(' ' + '─'.repeat(40)));
181
+ }
182
+ }
183
+ break;
184
+ }
185
+ case 'usage': {
186
+ // v3.0.0: surface cache stats at the end of single-prompt
187
+ // mode so CLI users can see hit-rate without /cache command.
188
+ const u = chunk.usage;
189
+ const hit = u.prompt_cache_hit_tokens || u.cache_read_input_tokens || 0;
190
+ const miss = u.prompt_cache_miss_tokens || u.cache_creation_input_tokens || (u.prompt_tokens - hit);
191
+ if (hit > 0 || miss > 0) {
192
+ const total = hit + miss;
193
+ const rate = total > 0 ? ((hit / total) * 100).toFixed(1) : '0.0';
194
+ console.log(chalk.gray(` ⚡ cache: ${rate}% hit (${hit} / ${total} tokens)`));
195
+ }
196
+ break;
197
+ }
198
+ }
199
+ }
200
+
201
+ // v2.2.5: post-process. Strip <think> blocks, summarize,
202
+ // and print the cleaned conclusion if we suppressed it
203
+ // during streaming.
204
+ if (!showThinking && !abortCtrl.signal.aborted && fullResponse) {
205
+ const split = splitThinking(fullResponse);
206
+ if (split.thinking) {
207
+ // Clear what we already streamed (we suppressed text
208
+ // chunks during streaming, so there's nothing to clear
209
+ // unless showThinking was on; in that case the text
210
+ // already contains the <think> block live and there's
211
+ // no point double-printing).
212
+ const summary = summarizeThinking(split);
213
+ if (summary) {
214
+ console.log(chalk.gray(` ${summary}`));
215
+ }
216
+ if (split.conclusion) {
217
+ console.log(chalk.cyan(' │ ') + split.conclusion);
218
+ }
219
+ } else if (fullResponse.trim()) {
220
+ // No thinking block found — print the conclusion if we
221
+ // hadn't already (showThinking=false suppresses
222
+ // streaming text).
223
+ console.log(chalk.cyan(' │ ') + fullResponse);
224
+ }
225
+ }
226
+
227
+ console.log();
228
+ // v2.2.4: skip persistence on abort.
229
+ if (!abortCtrl.signal.aborted) {
230
+ // v2.2.5: persist only the conclusion (no <think> blocks)
231
+ // when compression is enabled. This keeps the conversation
232
+ // log readable AND keeps context-window usage low.
233
+ const toPersist = showThinking
234
+ ? fullResponse
235
+ : compressThinking(fullResponse, false);
236
+ const accepted = app.session.addMessageSafe('assistant', toPersist);
237
+ if (!accepted) {
238
+ console.error(chalk.yellow(
239
+ ' ⚠️ Dropped assistant message containing [已中断] marker.\n' +
240
+ ' (prevents hallucination loop — try your question again)'
241
+ ));
242
+ }
243
+ } else {
244
+ console.log(chalk.yellow(' ⏹ Cancelled (response not saved)'));
245
+ }
246
+ } catch (error: any) {
247
+ const msg = error.message || String(error);
248
+ if (msg.includes('401') || msg.includes('403') || msg.includes('Unauthorized')) {
249
+ console.error(chalk.red('\n ❌ API key invalid or expired.'));
250
+ console.log(chalk.gray(' Run ') + chalk.cyan('gfcode init') + chalk.gray(' to reconfigure.\n'));
251
+ } else if (msg.includes('429') || msg.includes('rate limit') || msg.includes('quota')) {
252
+ console.error(chalk.red('\n ❌ Rate limit or quota exceeded.'));
253
+ console.log(chalk.gray(' Wait or run ') + chalk.cyan('gfcode init') + chalk.gray(' to switch provider.\n'));
254
+ } else if (msg.includes('ECONNREFUSED') || msg.includes('ENOTFOUND')) {
255
+ console.error(chalk.red('\n ❌ Cannot connect to API server.'));
256
+ console.log(chalk.gray(' Check network or run ') + chalk.cyan('gfcode init') + chalk.gray('.\n'));
257
+ } else {
258
+ console.error(chalk.red(`\n Error: ${msg}`));
259
+ }
260
+ } finally {
261
+ process.removeListener('SIGINT', onSigInt);
262
+ }
263
+ }
264
+ } catch (error: any) {
265
+ console.error(chalk.red(`\n ${error.message}`));
266
+ process.exit(1);
267
+ }
268
+ });
269
+
270
+ program
271
+ .command('init')
272
+ .description('Configure API key and model')
273
+ .action(async () => {
274
+ await WelcomeScreen.interactiveSetup();
275
+ });
276
+
277
+ program.parse(process.argv);
278
+
279
+ function formatArgs(args: string): string {
280
+ try {
281
+ const obj = JSON.parse(args);
282
+ return Object.entries(obj)
283
+ .map(([k, v]) => `${k}=${typeof v === 'string' && v.length > 40 ? v.slice(0, 40) + '...' : JSON.stringify(v)}`)
284
+ .join(' ');
285
+ } catch {
286
+ return args.length > 60 ? args.slice(0, 60) + '...' : args;
287
+ }
288
+ }