@datename/fastcode-termux 0.0.0-stage → 0.1.6-beta

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 (347) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +418 -2
  3. package/bin/fastcode.mjs +59 -0
  4. package/dist/agent/approval.d.ts +50 -0
  5. package/dist/agent/approval.js +7 -0
  6. package/dist/agent/compaction.d.ts +39 -0
  7. package/dist/agent/compaction.js +227 -0
  8. package/dist/agent/context.d.ts +29 -0
  9. package/dist/agent/context.js +62 -0
  10. package/dist/agent/guards.d.ts +43 -0
  11. package/dist/agent/guards.js +269 -0
  12. package/dist/agent/ignore.d.ts +11 -0
  13. package/dist/agent/ignore.js +129 -0
  14. package/dist/agent/limits.d.ts +24 -0
  15. package/dist/agent/limits.js +71 -0
  16. package/dist/agent/process-tree.d.ts +2 -0
  17. package/dist/agent/process-tree.js +31 -0
  18. package/dist/agent/protocol-mode.d.ts +6 -0
  19. package/dist/agent/protocol-mode.js +51 -0
  20. package/dist/agent/protocol.d.ts +4 -0
  21. package/dist/agent/protocol.js +129 -0
  22. package/dist/agent/registry.d.ts +17 -0
  23. package/dist/agent/registry.js +90 -0
  24. package/dist/agent/runner.d.ts +106 -0
  25. package/dist/agent/runner.js +352 -0
  26. package/dist/agent/shell-session.d.ts +37 -0
  27. package/dist/agent/shell-session.js +400 -0
  28. package/dist/agent/stream.d.ts +29 -0
  29. package/dist/agent/stream.js +103 -0
  30. package/dist/agent/tool-schemas.d.ts +2 -0
  31. package/dist/agent/tool-schemas.js +63 -0
  32. package/dist/agent/tools/append_file.d.ts +2 -0
  33. package/dist/agent/tools/append_file.js +26 -0
  34. package/dist/agent/tools/apply_patch.d.ts +10 -0
  35. package/dist/agent/tools/apply_patch.js +52 -0
  36. package/dist/agent/tools/copy_file.d.ts +2 -0
  37. package/dist/agent/tools/copy_file.js +30 -0
  38. package/dist/agent/tools/delete_file.d.ts +2 -0
  39. package/dist/agent/tools/delete_file.js +24 -0
  40. package/dist/agent/tools/grep.d.ts +2 -0
  41. package/dist/agent/tools/grep.js +23 -0
  42. package/dist/agent/tools/index.d.ts +2 -0
  43. package/dist/agent/tools/index.js +32 -0
  44. package/dist/agent/tools/list_files.d.ts +2 -0
  45. package/dist/agent/tools/list_files.js +17 -0
  46. package/dist/agent/tools/make_dir.d.ts +2 -0
  47. package/dist/agent/tools/make_dir.js +24 -0
  48. package/dist/agent/tools/move_path.d.ts +2 -0
  49. package/dist/agent/tools/move_path.js +47 -0
  50. package/dist/agent/tools/paths.d.ts +7 -0
  51. package/dist/agent/tools/paths.js +84 -0
  52. package/dist/agent/tools/pwd.d.ts +2 -0
  53. package/dist/agent/tools/pwd.js +10 -0
  54. package/dist/agent/tools/read_file.d.ts +2 -0
  55. package/dist/agent/tools/read_file.js +21 -0
  56. package/dist/agent/tools/read_many.d.ts +2 -0
  57. package/dist/agent/tools/read_many.js +25 -0
  58. package/dist/agent/tools/readers.d.ts +6 -0
  59. package/dist/agent/tools/readers.js +216 -0
  60. package/dist/agent/tools/replace_in_file.d.ts +2 -0
  61. package/dist/agent/tools/replace_in_file.js +30 -0
  62. package/dist/agent/tools/shell.d.ts +2 -0
  63. package/dist/agent/tools/shell.js +48 -0
  64. package/dist/agent/tools/stat_path.d.ts +2 -0
  65. package/dist/agent/tools/stat_path.js +31 -0
  66. package/dist/agent/tools/types.d.ts +39 -0
  67. package/dist/agent/tools/types.js +1 -0
  68. package/dist/agent/tools/validate.d.ts +6 -0
  69. package/dist/agent/tools/validate.js +29 -0
  70. package/dist/agent/tools/write_file.d.ts +2 -0
  71. package/dist/agent/tools/write_file.js +26 -0
  72. package/dist/agent/tools.d.ts +3 -0
  73. package/dist/agent/tools.js +2 -0
  74. package/dist/app.d.ts +4 -0
  75. package/dist/app.js +708 -0
  76. package/dist/cli.d.ts +1 -0
  77. package/dist/cli.js +569 -0
  78. package/dist/commands/about.d.ts +8 -0
  79. package/dist/commands/about.js +16 -0
  80. package/dist/commands/agent.d.ts +11 -0
  81. package/dist/commands/agent.js +18 -0
  82. package/dist/commands/attach.d.ts +9 -0
  83. package/dist/commands/attach.js +15 -0
  84. package/dist/commands/bg.d.ts +7 -0
  85. package/dist/commands/bg.js +9 -0
  86. package/dist/commands/cancel.d.ts +10 -0
  87. package/dist/commands/cancel.js +10 -0
  88. package/dist/commands/clear.d.ts +11 -0
  89. package/dist/commands/clear.js +9 -0
  90. package/dist/commands/compact.d.ts +10 -0
  91. package/dist/commands/compact.js +22 -0
  92. package/dist/commands/config.d.ts +7 -0
  93. package/dist/commands/config.js +24 -0
  94. package/dist/commands/context.d.ts +7 -0
  95. package/dist/commands/context.js +24 -0
  96. package/dist/commands/cost.d.ts +9 -0
  97. package/dist/commands/cost.js +13 -0
  98. package/dist/commands/cwd.d.ts +7 -0
  99. package/dist/commands/cwd.js +7 -0
  100. package/dist/commands/edit.d.ts +10 -0
  101. package/dist/commands/edit.js +36 -0
  102. package/dist/commands/effort.d.ts +25 -0
  103. package/dist/commands/effort.js +48 -0
  104. package/dist/commands/exit.d.ts +9 -0
  105. package/dist/commands/exit.js +8 -0
  106. package/dist/commands/expand.d.ts +10 -0
  107. package/dist/commands/expand.js +8 -0
  108. package/dist/commands/help.d.ts +6 -0
  109. package/dist/commands/help.js +18 -0
  110. package/dist/commands/index.d.ts +9 -0
  111. package/dist/commands/index.js +80 -0
  112. package/dist/commands/jobs.d.ts +7 -0
  113. package/dist/commands/jobs.js +16 -0
  114. package/dist/commands/kill.d.ts +7 -0
  115. package/dist/commands/kill.js +11 -0
  116. package/dist/commands/login.d.ts +18 -0
  117. package/dist/commands/login.js +63 -0
  118. package/dist/commands/logout.d.ts +9 -0
  119. package/dist/commands/logout.js +45 -0
  120. package/dist/commands/model.d.ts +24 -0
  121. package/dist/commands/model.js +50 -0
  122. package/dist/commands/plugin.d.ts +11 -0
  123. package/dist/commands/plugin.js +74 -0
  124. package/dist/commands/provider.d.ts +24 -0
  125. package/dist/commands/provider.js +39 -0
  126. package/dist/commands/reset.d.ts +9 -0
  127. package/dist/commands/reset.js +13 -0
  128. package/dist/commands/skills.d.ts +11 -0
  129. package/dist/commands/skills.js +106 -0
  130. package/dist/commands/steer.d.ts +11 -0
  131. package/dist/commands/steer.js +13 -0
  132. package/dist/commands/system.d.ts +11 -0
  133. package/dist/commands/system.js +20 -0
  134. package/dist/commands/theme.d.ts +11 -0
  135. package/dist/commands/theme.js +22 -0
  136. package/dist/commands/tools.d.ts +7 -0
  137. package/dist/commands/tools.js +29 -0
  138. package/dist/commands/whoami.d.ts +9 -0
  139. package/dist/commands/whoami.js +52 -0
  140. package/dist/config/paths.d.ts +4 -0
  141. package/dist/config/paths.js +59 -0
  142. package/dist/config/store.d.ts +89 -0
  143. package/dist/config/store.js +260 -0
  144. package/dist/config/themes.d.ts +73 -0
  145. package/dist/config/themes.js +77 -0
  146. package/dist/config/trust.d.ts +22 -0
  147. package/dist/config/trust.js +153 -0
  148. package/dist/index.d.ts +1 -0
  149. package/dist/index.js +31 -0
  150. package/dist/lib/diagnostics.d.ts +66 -0
  151. package/dist/lib/diagnostics.js +195 -0
  152. package/dist/lib/http.d.ts +23 -0
  153. package/dist/lib/http.js +128 -0
  154. package/dist/lib/markdown.d.ts +1 -0
  155. package/dist/lib/markdown.js +32 -0
  156. package/dist/lib/model-meta.d.ts +19 -0
  157. package/dist/lib/model-meta.js +113 -0
  158. package/dist/lib/native-tools.d.ts +12 -0
  159. package/dist/lib/native-tools.js +21 -0
  160. package/dist/lib/net.d.ts +33 -0
  161. package/dist/lib/net.js +168 -0
  162. package/dist/lib/pkg.d.ts +5 -0
  163. package/dist/lib/pkg.js +27 -0
  164. package/dist/lib/platform.d.ts +7 -0
  165. package/dist/lib/platform.js +57 -0
  166. package/dist/lib/startup.d.ts +6 -0
  167. package/dist/lib/startup.js +25 -0
  168. package/dist/lib/uiMode.d.ts +2 -0
  169. package/dist/lib/uiMode.js +7 -0
  170. package/dist/patch/apply.d.ts +15 -0
  171. package/dist/patch/apply.js +172 -0
  172. package/dist/patch/parse.d.ts +29 -0
  173. package/dist/patch/parse.js +112 -0
  174. package/dist/patch/plan.d.ts +49 -0
  175. package/dist/patch/plan.js +273 -0
  176. package/dist/plugins/manager.d.ts +23 -0
  177. package/dist/plugins/manager.js +101 -0
  178. package/dist/providers/anthropic.d.ts +22 -0
  179. package/dist/providers/anthropic.js +119 -0
  180. package/dist/providers/custom.d.ts +33 -0
  181. package/dist/providers/custom.js +25 -0
  182. package/dist/providers/deepseek.d.ts +34 -0
  183. package/dist/providers/deepseek.js +16 -0
  184. package/dist/providers/google.d.ts +33 -0
  185. package/dist/providers/google.js +19 -0
  186. package/dist/providers/groq.d.ts +34 -0
  187. package/dist/providers/groq.js +21 -0
  188. package/dist/providers/index.d.ts +10 -0
  189. package/dist/providers/index.js +67 -0
  190. package/dist/providers/mistral.d.ts +34 -0
  191. package/dist/providers/mistral.js +20 -0
  192. package/dist/providers/moonshot.d.ts +34 -0
  193. package/dist/providers/moonshot.js +23 -0
  194. package/dist/providers/ollama.d.ts +33 -0
  195. package/dist/providers/ollama.js +22 -0
  196. package/dist/providers/openai.d.ts +34 -0
  197. package/dist/providers/openai.js +26 -0
  198. package/dist/providers/openaiCompatible.d.ts +26 -0
  199. package/dist/providers/openaiCompatible.js +158 -0
  200. package/dist/providers/openrouter.d.ts +34 -0
  201. package/dist/providers/openrouter.js +27 -0
  202. package/dist/providers/qwen.d.ts +34 -0
  203. package/dist/providers/qwen.js +24 -0
  204. package/dist/providers/xai.d.ts +34 -0
  205. package/dist/providers/xai.js +19 -0
  206. package/dist/providers/zhipu.d.ts +34 -0
  207. package/dist/providers/zhipu.js +24 -0
  208. package/dist/session/log.d.ts +52 -0
  209. package/dist/session/log.js +331 -0
  210. package/dist/session/projection.d.ts +43 -0
  211. package/dist/session/projection.js +257 -0
  212. package/dist/skills/manager.d.ts +18 -0
  213. package/dist/skills/manager.js +201 -0
  214. package/dist/skills/parser.d.ts +18 -0
  215. package/dist/skills/parser.js +65 -0
  216. package/dist/types.d.ts +205 -0
  217. package/dist/types.js +1 -0
  218. package/dist/ui/Banner.d.ts +5 -0
  219. package/dist/ui/Banner.js +65 -0
  220. package/dist/ui/Message.d.ts +1 -0
  221. package/dist/ui/Message.js +24 -0
  222. package/dist/ui/Picker.d.ts +8 -0
  223. package/dist/ui/Picker.js +24 -0
  224. package/dist/ui/Prompt.d.ts +9 -0
  225. package/dist/ui/Prompt.js +38 -0
  226. package/dist/ui/Spinner.d.ts +5 -0
  227. package/dist/ui/Spinner.js +39 -0
  228. package/dist/ui/StatusBar.d.ts +11 -0
  229. package/dist/ui/StatusBar.js +20 -0
  230. package/dist/ui/TrustGate.d.ts +5 -0
  231. package/dist/ui/TrustGate.js +26 -0
  232. package/package.json +96 -4
  233. package/src/agent/approval.ts +47 -0
  234. package/src/agent/compaction.ts +276 -0
  235. package/src/agent/context.ts +97 -0
  236. package/src/agent/guards.ts +270 -0
  237. package/src/agent/ignore.ts +147 -0
  238. package/src/agent/limits.ts +71 -0
  239. package/src/agent/process-tree.ts +32 -0
  240. package/src/agent/protocol-mode.ts +59 -0
  241. package/src/agent/protocol.ts +129 -0
  242. package/src/agent/registry.ts +98 -0
  243. package/src/agent/runner.ts +443 -0
  244. package/src/agent/shell-session.ts +449 -0
  245. package/src/agent/stream.ts +143 -0
  246. package/src/agent/tool-schemas.ts +67 -0
  247. package/src/agent/tools/append_file.ts +28 -0
  248. package/src/agent/tools/apply_patch.ts +54 -0
  249. package/src/agent/tools/copy_file.ts +32 -0
  250. package/src/agent/tools/delete_file.ts +26 -0
  251. package/src/agent/tools/grep.ts +25 -0
  252. package/src/agent/tools/index.ts +34 -0
  253. package/src/agent/tools/list_files.ts +19 -0
  254. package/src/agent/tools/make_dir.ts +26 -0
  255. package/src/agent/tools/move_path.ts +50 -0
  256. package/src/agent/tools/paths.ts +92 -0
  257. package/src/agent/tools/pwd.ts +12 -0
  258. package/src/agent/tools/read_file.ts +23 -0
  259. package/src/agent/tools/read_many.ts +27 -0
  260. package/src/agent/tools/readers.ts +228 -0
  261. package/src/agent/tools/replace_in_file.ts +32 -0
  262. package/src/agent/tools/shell.ts +53 -0
  263. package/src/agent/tools/stat_path.ts +33 -0
  264. package/src/agent/tools/types.ts +42 -0
  265. package/src/agent/tools/validate.ts +35 -0
  266. package/src/agent/tools/write_file.ts +28 -0
  267. package/src/agent/tools.ts +3 -0
  268. package/src/app.ts +708 -0
  269. package/src/cli.ts +335 -0
  270. package/src/commands/about.ts +16 -0
  271. package/src/commands/agent.ts +18 -0
  272. package/src/commands/attach.ts +16 -0
  273. package/src/commands/bg.ts +9 -0
  274. package/src/commands/cancel.ts +10 -0
  275. package/src/commands/clear.ts +9 -0
  276. package/src/commands/compact.ts +23 -0
  277. package/src/commands/config.ts +24 -0
  278. package/src/commands/context.ts +25 -0
  279. package/src/commands/cost.ts +13 -0
  280. package/src/commands/cwd.ts +7 -0
  281. package/src/commands/edit.ts +37 -0
  282. package/src/commands/effort.ts +49 -0
  283. package/src/commands/exit.ts +8 -0
  284. package/src/commands/expand.ts +8 -0
  285. package/src/commands/help.ts +18 -0
  286. package/src/commands/index.ts +80 -0
  287. package/src/commands/jobs.ts +17 -0
  288. package/src/commands/kill.ts +12 -0
  289. package/src/commands/login.ts +63 -0
  290. package/src/commands/logout.ts +45 -0
  291. package/src/commands/model.ts +50 -0
  292. package/src/commands/plugin.ts +74 -0
  293. package/src/commands/provider.ts +39 -0
  294. package/src/commands/reset.ts +13 -0
  295. package/src/commands/skills.ts +106 -0
  296. package/src/commands/steer.ts +13 -0
  297. package/src/commands/system.ts +20 -0
  298. package/src/commands/theme.ts +22 -0
  299. package/src/commands/tools.ts +29 -0
  300. package/src/commands/whoami.ts +52 -0
  301. package/src/config/paths.ts +59 -0
  302. package/src/config/store.ts +293 -0
  303. package/src/config/themes.ts +77 -0
  304. package/src/config/trust.ts +183 -0
  305. package/src/index.ts +31 -0
  306. package/src/lib/diagnostics.ts +195 -0
  307. package/src/lib/http.ts +132 -0
  308. package/src/lib/markdown.ts +32 -0
  309. package/src/lib/model-meta.ts +138 -0
  310. package/src/lib/native-tools.ts +32 -0
  311. package/src/lib/net.ts +204 -0
  312. package/src/lib/pkg.ts +35 -0
  313. package/src/lib/platform.ts +57 -0
  314. package/src/lib/startup.ts +25 -0
  315. package/src/lib/uiMode.ts +7 -0
  316. package/src/patch/apply.ts +194 -0
  317. package/src/patch/parse.ts +131 -0
  318. package/src/patch/plan.ts +317 -0
  319. package/src/plugins/manager.ts +101 -0
  320. package/src/providers/anthropic.ts +119 -0
  321. package/src/providers/custom.ts +25 -0
  322. package/src/providers/deepseek.ts +16 -0
  323. package/src/providers/google.ts +19 -0
  324. package/src/providers/groq.ts +21 -0
  325. package/src/providers/index.ts +68 -0
  326. package/src/providers/mistral.ts +20 -0
  327. package/src/providers/moonshot.ts +23 -0
  328. package/src/providers/ollama.ts +22 -0
  329. package/src/providers/openai.ts +26 -0
  330. package/src/providers/openaiCompatible.ts +158 -0
  331. package/src/providers/openrouter.ts +27 -0
  332. package/src/providers/qwen.ts +24 -0
  333. package/src/providers/xai.ts +19 -0
  334. package/src/providers/zhipu.ts +24 -0
  335. package/src/session/log.ts +374 -0
  336. package/src/session/projection.ts +308 -0
  337. package/src/skills/manager.ts +201 -0
  338. package/src/skills/parser.ts +65 -0
  339. package/src/types.ts +205 -0
  340. package/src/ui/Banner.ts +68 -0
  341. package/src/ui/Message.ts +24 -0
  342. package/src/ui/Picker.ts +24 -0
  343. package/src/ui/Prompt.ts +38 -0
  344. package/src/ui/Spinner.ts +39 -0
  345. package/src/ui/StatusBar.ts +20 -0
  346. package/src/ui/TrustGate.ts +26 -0
  347. package/tsconfig.json +22 -0
package/src/lib/net.ts ADDED
@@ -0,0 +1,204 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { ChatChunk } from "../types.js";
3
+
4
+ export class QuotaError extends Error {
5
+ readonly code = "QUOTA";
6
+ constructor(message: string) {
7
+ super(message);
8
+ this.name = "QuotaError";
9
+ }
10
+ }
11
+
12
+ export class IncompleteStreamError extends Error {
13
+ readonly partialText: string;
14
+ constructor(message: string, partialText: string) {
15
+ super(message);
16
+ this.name = "IncompleteStreamError";
17
+ this.partialText = partialText;
18
+ }
19
+ }
20
+
21
+ export interface RetryRequestOptions {
22
+ retries?: number;
23
+ backoffMs?: number[];
24
+ retryOn?: (error: Error) => boolean;
25
+ signal?: AbortSignal;
26
+ }
27
+
28
+ export interface RetryStreamOptions {
29
+ clientRequestId?: string;
30
+ lastAcc?: string;
31
+ retries?: number;
32
+ backoffMs?: number[];
33
+ retryOn?: (error: Error) => boolean;
34
+ signal?: AbortSignal;
35
+ onRetry?: (error: Error, attempt: number) => void;
36
+ onReset?: () => void;
37
+ }
38
+
39
+ export interface StreamChunk extends ChatChunk {
40
+ reset?: boolean;
41
+ }
42
+
43
+ const DEFAULT_BACKOFF = [1000, 2000, 4000];
44
+ const STREAM_BACKOFF = [400, 800, 1600];
45
+
46
+ export function isRetryableError(error: Error): boolean {
47
+ const message = String(error?.message ?? error);
48
+ if (/\b(401|402|403|404)\b/.test(message))
49
+ return false;
50
+ if (/timeout|timed? ?out|ECONNRESET|ECONNREFUSED|ENOTFOUND|ETIMEDOUT|EPIPE|fetch failed|network|socket hang up|terminated|other side closed|stream ended before done/i.test(message))
51
+ return true;
52
+ return /\b(429|5\d\d)\b/.test(message);
53
+ }
54
+
55
+ function isQuotaError(error: Error): boolean {
56
+ return /\b429\b|quota|insufficient|rate limit|billing|balance/i.test(String(error?.message ?? error));
57
+ }
58
+
59
+ export async function retryRequest<T>(fn: (attempt: number) => Promise<T>, options: RetryRequestOptions = {}): Promise<T> {
60
+ const attempts = Math.max(1, Math.floor(options.retries ?? 3));
61
+ const backoff = options.backoffMs ?? DEFAULT_BACKOFF;
62
+ const retryOn = options.retryOn ?? isRetryableError;
63
+ let lastError: Error | undefined;
64
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
65
+ if (options.signal?.aborted)
66
+ throw abortError();
67
+ try {
68
+ return await fn(attempt);
69
+ }
70
+ catch (err) {
71
+ lastError = toError(err);
72
+ if (attempt >= attempts - 1 || !retryOn(lastError))
73
+ break;
74
+ await delay(backoff[Math.min(attempt, backoff.length - 1)], options.signal);
75
+ }
76
+ }
77
+ if (lastError && isQuotaError(lastError))
78
+ throw new QuotaError(lastError.message);
79
+ throw lastError ?? new Error("retryRequest failed");
80
+ }
81
+
82
+ export async function* retryStream(
83
+ send: (options: { clientRequestId: string }) => AsyncGenerator<ChatChunk>,
84
+ options: RetryStreamOptions = {},
85
+ ): AsyncGenerator<StreamChunk> {
86
+ const clientRequestId = options.clientRequestId ?? randomUUID();
87
+ const attempts = Math.max(1, Math.floor(options.retries ?? 1) + 1);
88
+ const backoff = options.backoffMs ?? STREAM_BACKOFF;
89
+ const retryOn = options.retryOn ?? isRetryableError;
90
+ let delivered = options.lastAcc ?? "";
91
+ let lastError: Error | undefined;
92
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
93
+ if (options.signal?.aborted)
94
+ throw abortError();
95
+ let buffering = delivered.length > 0;
96
+ let pending = "";
97
+ let doneSeen = false;
98
+ let usage: ChatChunk["usage"];
99
+ let toolCalls: ChatChunk["toolCalls"];
100
+ try {
101
+ for await (const chunk of send({ clientRequestId })) {
102
+ if (options.signal?.aborted)
103
+ throw abortError();
104
+ if (chunk.usage)
105
+ usage = chunk.usage;
106
+ if (chunk.toolCalls)
107
+ toolCalls = chunk.toolCalls;
108
+ const delta = chunk.delta ?? "";
109
+ if (!delta) {
110
+ if (!buffering && !chunk.done)
111
+ yield chunk;
112
+ if (chunk.done)
113
+ doneSeen = true;
114
+ continue;
115
+ }
116
+ if (buffering) {
117
+ pending += delta;
118
+ const matchedPrefix = delivered.startsWith(pending) || pending.startsWith(delivered);
119
+ if (delivered.startsWith(pending)) {
120
+ if (pending.length === delivered.length) {
121
+ buffering = false;
122
+ pending = "";
123
+ }
124
+ if (chunk.done)
125
+ doneSeen = true;
126
+ continue;
127
+ }
128
+ if (matchedPrefix) {
129
+ const extra = pending.slice(delivered.length);
130
+ buffering = false;
131
+ pending = "";
132
+ if (extra) {
133
+ delivered += extra;
134
+ yield { ...chunk, delta: extra, done: false };
135
+ }
136
+ }
137
+ else {
138
+ buffering = false;
139
+ delivered = pending;
140
+ pending = "";
141
+ options.onReset?.();
142
+ yield { ...chunk, delta: delivered, reset: true, done: false };
143
+ }
144
+ if (chunk.done)
145
+ doneSeen = true;
146
+ continue;
147
+ }
148
+ delivered += delta;
149
+ yield { ...chunk, done: false };
150
+ if (chunk.done)
151
+ doneSeen = true;
152
+ }
153
+ if (!doneSeen)
154
+ throw new IncompleteStreamError("stream ended before done", delivered);
155
+ yield {
156
+ delta: "",
157
+ done: true,
158
+ ...(usage ? { usage } : {}),
159
+ ...(toolCalls ? { toolCalls } : {}),
160
+ };
161
+ return;
162
+ }
163
+ catch (err) {
164
+ lastError = toError(err);
165
+ if (options.signal?.aborted)
166
+ throw abortError();
167
+ if (attempt >= attempts - 1 || !retryOn(lastError)) {
168
+ (lastError as Error & { partialText?: string }).partialText = delivered;
169
+ throw lastError;
170
+ }
171
+ options.onRetry?.(lastError, attempt + 1);
172
+ await delay(backoff[Math.min(attempt, backoff.length - 1)], options.signal);
173
+ }
174
+ }
175
+ throw lastError ?? new Error("retryStream failed");
176
+ }
177
+
178
+ function delay(ms: number, signal?: AbortSignal): Promise<void> {
179
+ return new Promise((resolve, reject) => {
180
+ if (signal?.aborted) {
181
+ reject(abortError());
182
+ return;
183
+ }
184
+ const timer = setTimeout(() => {
185
+ signal?.removeEventListener("abort", onAbort);
186
+ resolve();
187
+ }, ms);
188
+ const onAbort = () => {
189
+ clearTimeout(timer);
190
+ reject(abortError());
191
+ };
192
+ signal?.addEventListener("abort", onAbort, { once: true });
193
+ });
194
+ }
195
+
196
+ function abortError(): Error {
197
+ const error = new Error("Aborted");
198
+ error.name = "AbortError";
199
+ return error;
200
+ }
201
+
202
+ function toError(value: unknown): Error {
203
+ return value instanceof Error ? value : new Error(String(value));
204
+ }
package/src/lib/pkg.ts ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Read this package's package.json (name + version) from any layout.
3
+ *
4
+ * The same source runs three ways, so `import.meta.url` points at different
5
+ * depths; try every plausible relative path and fall back gracefully.
6
+ *
7
+ * - tsx / dev: src/lib/pkg.ts -> ../../package.json
8
+ * - tsc output: dist/lib/pkg.js -> ../../package.json
9
+ * - esbuild bundle: dist/cli.js -> ../package.json
10
+ */
11
+ import { readFileSync } from "node:fs";
12
+
13
+ export interface PackageMeta {
14
+ name: string;
15
+ version: string;
16
+ }
17
+
18
+ const FALLBACK: PackageMeta = { name: "@datename/fastcode-termux", version: "0.0.0" };
19
+
20
+ const CANDIDATES = ["../package.json", "../../package.json", "../../../package.json"];
21
+
22
+ export function readPackageMeta(): PackageMeta {
23
+ for (const rel of CANDIDATES) {
24
+ try {
25
+ const meta = JSON.parse(readFileSync(new URL(rel, import.meta.url), "utf8"));
26
+ if (meta && typeof meta.version === "string") {
27
+ return { name: meta.name ?? FALLBACK.name, version: meta.version };
28
+ }
29
+ }
30
+ catch {
31
+ /* try the next candidate */
32
+ }
33
+ }
34
+ return FALLBACK;
35
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Cross-platform detection and small helpers.
3
+ *
4
+ * FastCode targets Termux, Linux, macOS, and Windows. Most of our
5
+ * environment-aware behavior keys off these flags rather than scattering
6
+ * `process.platform === "..."` checks across the codebase.
7
+ */
8
+ import { platform, homedir } from "node:os";
9
+ export function detectPlatform() {
10
+ // Termux exposes PREFIX=/data/data/com.termux/files/usr. The extra check
11
+ // makes us robust to users who manually export PREFIX for other reasons.
12
+ const prefix = process.env["PREFIX"];
13
+ // Termux exports TERMUX_VERSION; PREFIX=/data/data/com.termux/files/usr is a
14
+ // strong secondary signal. Neither requires the directory to exist yet.
15
+ if (process.platform === "android" ||
16
+ Boolean(process.env["TERMUX_VERSION"]) ||
17
+ (prefix && prefix.includes("com.termux"))) {
18
+ return "termux";
19
+ }
20
+ switch (process.platform) {
21
+ case "linux":
22
+ case "darwin":
23
+ case "win32":
24
+ return process.platform;
25
+ default:
26
+ return "other";
27
+ }
28
+ }
29
+ export const isTermux = () => detectPlatform() === "termux";
30
+ export const isWindows = () => process.platform === "win32";
31
+ export const isMac = () => process.platform === "darwin";
32
+ /** Human-readable label for the status bar. */
33
+ export function platformLabel() {
34
+ const p = detectPlatform();
35
+ switch (p) {
36
+ case "termux":
37
+ return "Termux";
38
+ case "linux":
39
+ return "Linux";
40
+ case "darwin":
41
+ return "macOS";
42
+ case "win32":
43
+ return "Windows";
44
+ default:
45
+ return platform();
46
+ }
47
+ }
48
+ export function safeHome() {
49
+ // os.homedir() can return undefined on weird CI containers; fall back
50
+ // to $HOME / %USERPROFILE% / cwd in that order.
51
+ const fromOs = homedir();
52
+ if (fromOs)
53
+ return fromOs;
54
+ return (process.env["HOME"] ??
55
+ process.env["USERPROFILE"] ??
56
+ process.cwd());
57
+ }
@@ -0,0 +1,25 @@
1
+ import { resolveApiKey } from "../config/store.js";
2
+ import { getProviderOrThrow } from "../providers/index.js";
3
+ export function createStartupTranscript(config) {
4
+ const messages = [
5
+ `Welcome to FastCode. Provider: **${config.providerId}** · model: **${config.model}**.\n\nType **/help** to list slash commands, or just start chatting.`,
6
+ ];
7
+ const provider = getProviderOrThrow(config.providerId);
8
+ if (provider.authEnv.length > 0) {
9
+ const lookup = resolveApiKey(provider.id, config.model, provider.authEnv);
10
+ if (lookup.status === "unbound") {
11
+ messages.push(`Stored ${provider.label} key isn't bound to a model, so it won't be used. ` +
12
+ `Re-bind it with \`/login ${provider.id} ${config.model} <key>\` (or \`/logout ${provider.id}\` to discard it).`);
13
+ }
14
+ else if (lookup.status === "missing") {
15
+ messages.push(`No API key for ${provider.label} · ${config.model}. ` +
16
+ `Run \`/login ${provider.id} ${config.model} <key>\`, or set ${provider.authEnv[0]} (provider-wide, any model).`);
17
+ }
18
+ }
19
+ return messages.map((content, index) => ({
20
+ id: index + 1,
21
+ role: "system",
22
+ content,
23
+ markdown: true,
24
+ }));
25
+ }
@@ -0,0 +1,7 @@
1
+ import { detectPlatform } from "./platform.js";
2
+ export function shouldUseStableTerminalUi(platform = detectPlatform(), env = process.env) {
3
+ return platform === "termux" || env.FASTCODE_STABLE_UI === "1";
4
+ }
5
+ export function shouldUseLiveStreamingUi(platform = detectPlatform(), env = process.env) {
6
+ return !shouldUseStableTerminalUi(platform, env);
7
+ }
@@ -0,0 +1,194 @@
1
+ import { closeSync, constants as fsConstants, fchmodSync, lstatSync, mkdirSync, openSync, renameSync, rmSync, unlinkSync, writeSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import type { PatchPlan, PlannedFile } from "./plan.js";
4
+
5
+ export interface AppliedFile {
6
+ path: string;
7
+ kind: PlannedFile["kind"];
8
+ diff: string;
9
+ }
10
+
11
+ export interface ApplyResult {
12
+ ok: boolean;
13
+ output: string;
14
+ files: AppliedFile[];
15
+ touched: string[];
16
+ removed: string[];
17
+ warnings: string[];
18
+ }
19
+
20
+ export function applyPatchPlan(plan: PatchPlan): ApplyResult {
21
+ const warnings = [...plan.warnings];
22
+ const applied: PlannedFile[] = [];
23
+ const touched: string[] = [];
24
+ const removed: string[] = [];
25
+ const temps: string[] = [];
26
+ try {
27
+ for (const file of plan.files) {
28
+ commit(file, warnings, temps);
29
+ applied.push(file);
30
+ if (file.kind === "delete") {
31
+ removed.push(file.path);
32
+ }
33
+ else if (file.kind === "add") {
34
+ touched.push(file.path);
35
+ }
36
+ else if (file.moveTo) {
37
+ removed.push(file.path);
38
+ touched.push(file.moveTo);
39
+ }
40
+ else {
41
+ touched.push(file.path);
42
+ }
43
+ }
44
+ }
45
+ catch (err: any) {
46
+ for (const tmp of temps) {
47
+ try {
48
+ rmSync(tmp, { force: true });
49
+ }
50
+ catch {
51
+ // best effort
52
+ }
53
+ }
54
+ rollback(applied, warnings);
55
+ return {
56
+ ok: false,
57
+ output: `patch failed: ${err?.message ?? String(err)}; rolled back ${applied.length} file(s)`,
58
+ files: [],
59
+ touched: [],
60
+ removed: [],
61
+ warnings,
62
+ };
63
+ }
64
+ const files = plan.files.map((file) => ({
65
+ path: file.moveTo ?? file.path,
66
+ kind: file.kind,
67
+ diff: file.diff,
68
+ }));
69
+ return {
70
+ ok: true,
71
+ output: [`applied ${plan.files.length} file(s)`, ...files.map((file) => file.diff)].join("\n\n"),
72
+ files,
73
+ touched,
74
+ removed,
75
+ warnings,
76
+ };
77
+ }
78
+
79
+ function commit(file: PlannedFile, warnings: string[], temps: string[]): void {
80
+ if (file.kind === "delete") {
81
+ rejectSymlink(file.path);
82
+ unlinkSync(file.path);
83
+ return;
84
+ }
85
+ const target = file.moveTo ?? file.path;
86
+ if (file.kind === "add" || file.moveTo) {
87
+ if (lexists(target))
88
+ throw new Error(`target already exists: ${target}`);
89
+ }
90
+ rejectSymlink(target, true);
91
+ mkdirSync(dirname(target), { recursive: true });
92
+ const tmp = `${target}.fastcode-patch-${process.pid}-${Math.random().toString(36).slice(2, 8)}.tmp`;
93
+ temps.push(tmp);
94
+ const flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | (fsConstants.O_NOFOLLOW ?? 0);
95
+ const fd = openSync(tmp, flags, 0o600);
96
+ try {
97
+ writeSync(fd, file.newContent ?? "");
98
+ try {
99
+ fchmodSync(fd, file.origMode & 0o777);
100
+ }
101
+ catch {
102
+ warnings.push(`could not restore mode ${(file.origMode & 0o777).toString(8)} on ${target}; check permissions`);
103
+ }
104
+ }
105
+ finally {
106
+ closeSync(fd);
107
+ }
108
+ rejectSymlink(target, true);
109
+ renameSync(tmp, target);
110
+ const index = temps.indexOf(tmp);
111
+ if (index >= 0)
112
+ temps.splice(index, 1);
113
+ if (file.moveTo) {
114
+ try {
115
+ unlinkSync(file.path);
116
+ }
117
+ catch (err) {
118
+ try {
119
+ rmSync(target, { force: true });
120
+ }
121
+ catch {
122
+ // best effort
123
+ }
124
+ throw err;
125
+ }
126
+ }
127
+ }
128
+
129
+ function rejectSymlink(path: string, allowMissing = false): void {
130
+ try {
131
+ if (lstatSync(path).isSymbolicLink())
132
+ throw new Error(`refusing to write through a symbolic link: ${path}`);
133
+ }
134
+ catch (err: any) {
135
+ if (err?.code === "ENOENT" && allowMissing)
136
+ return;
137
+ throw err;
138
+ }
139
+ }
140
+
141
+ function lexists(path: string): boolean {
142
+ try {
143
+ lstatSync(path);
144
+ return true;
145
+ }
146
+ catch {
147
+ return false;
148
+ }
149
+ }
150
+
151
+ function rollback(applied: PlannedFile[], warnings: string[]): void {
152
+ for (let i = applied.length - 1; i >= 0; i -= 1) {
153
+ const file = applied[i];
154
+ try {
155
+ if (file.kind === "add") {
156
+ rmSync(file.path, { force: true });
157
+ continue;
158
+ }
159
+ if (file.kind === "delete") {
160
+ restore(file.path, file.oldContent ?? "", file.origMode);
161
+ continue;
162
+ }
163
+ if (file.moveTo) {
164
+ rmSync(file.moveTo, { force: true });
165
+ restore(file.path, file.oldContent ?? "", file.origMode);
166
+ continue;
167
+ }
168
+ restore(file.path, file.oldContent ?? "", file.origMode);
169
+ }
170
+ catch (err: any) {
171
+ warnings.push(`rollback failed for ${file.path}: ${err?.message ?? String(err)}`);
172
+ }
173
+ }
174
+ }
175
+
176
+ function restore(path: string, content: string, mode: number): void {
177
+ mkdirSync(dirname(path), { recursive: true });
178
+ const tmp = `${path}.fastcode-restore-${process.pid}-${Math.random().toString(36).slice(2, 8)}.tmp`;
179
+ const flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | (fsConstants.O_NOFOLLOW ?? 0);
180
+ const fd = openSync(tmp, flags, 0o600);
181
+ try {
182
+ writeSync(fd, content);
183
+ try {
184
+ fchmodSync(fd, mode & 0o777);
185
+ }
186
+ catch {
187
+ // best effort during rollback
188
+ }
189
+ }
190
+ finally {
191
+ closeSync(fd);
192
+ }
193
+ renameSync(tmp, path);
194
+ }
@@ -0,0 +1,131 @@
1
+ export type PatchLineType = " " | "-" | "+";
2
+
3
+ export interface PatchLine {
4
+ type: PatchLineType;
5
+ text: string;
6
+ }
7
+
8
+ export interface PatchHunk {
9
+ lines: PatchLine[];
10
+ }
11
+
12
+ export type PatchOp =
13
+ | { kind: "add"; path: string; lines: string[] }
14
+ | { kind: "delete"; path: string }
15
+ | { kind: "update"; path: string; hunks: PatchHunk[]; moveTo?: string };
16
+
17
+ export type ParseResult = { ok: true; ops: PatchOp[] } | { ok: false; output: string };
18
+
19
+ export function parsePatch(patch: string): ParseResult {
20
+ const lines = String(patch ?? "").split(/\r?\n/);
21
+ if (lines[0] !== "*** Begin Patch")
22
+ return fail("patch must start with *** Begin Patch");
23
+ const ops: PatchOp[] = [];
24
+ const seen = new Set<string>();
25
+ const claim = (path: string): string | undefined => {
26
+ if (!path)
27
+ return "empty file path in patch";
28
+ if (seen.has(path))
29
+ return `duplicate file in patch: ${path}`;
30
+ seen.add(path);
31
+ return undefined;
32
+ };
33
+ let i = 1;
34
+ let foundEnd = false;
35
+ while (i < lines.length) {
36
+ const line = lines[i];
37
+ if (line === "*** End Patch") {
38
+ foundEnd = true;
39
+ i += 1;
40
+ break;
41
+ }
42
+ if (line === "" || line === undefined) {
43
+ i += 1;
44
+ continue;
45
+ }
46
+ if (line.startsWith("*** Add File: ")) {
47
+ const path = line.slice("*** Add File: ".length).trim();
48
+ const duplicate = claim(path);
49
+ if (duplicate)
50
+ return fail(duplicate);
51
+ i += 1;
52
+ const content: string[] = [];
53
+ while (i < lines.length && !lines[i].startsWith("*** ")) {
54
+ const row = lines[i];
55
+ if (row === "") {
56
+ content.push("");
57
+ i += 1;
58
+ continue;
59
+ }
60
+ if (!row.startsWith("+"))
61
+ return fail(`Add File body must start with '+': ${row}`);
62
+ content.push(row.slice(1));
63
+ i += 1;
64
+ }
65
+ ops.push({ kind: "add", path, lines: content });
66
+ continue;
67
+ }
68
+ if (line.startsWith("*** Delete File: ")) {
69
+ const path = line.slice("*** Delete File: ".length).trim();
70
+ const duplicate = claim(path);
71
+ if (duplicate)
72
+ return fail(duplicate);
73
+ ops.push({ kind: "delete", path });
74
+ i += 1;
75
+ continue;
76
+ }
77
+ if (line.startsWith("*** Update File: ")) {
78
+ const path = line.slice("*** Update File: ".length).trim();
79
+ const duplicate = claim(path);
80
+ if (duplicate)
81
+ return fail(duplicate);
82
+ i += 1;
83
+ let moveTo: string | undefined;
84
+ if (i < lines.length && lines[i].startsWith("*** Move to: ")) {
85
+ moveTo = lines[i].slice("*** Move to: ".length).trim();
86
+ const movedDuplicate = claim(moveTo);
87
+ if (movedDuplicate)
88
+ return fail(movedDuplicate);
89
+ i += 1;
90
+ }
91
+ const hunks: PatchHunk[] = [];
92
+ let current: PatchHunk | undefined;
93
+ while (i < lines.length && !lines[i].startsWith("*** ")) {
94
+ const row = lines[i];
95
+ if (row === "") {
96
+ i += 1;
97
+ continue;
98
+ }
99
+ if (row.startsWith("@@")) {
100
+ current = { lines: [] };
101
+ hunks.push(current);
102
+ i += 1;
103
+ continue;
104
+ }
105
+ const type = row[0];
106
+ if (type !== " " && type !== "-" && type !== "+")
107
+ return fail(`invalid hunk line (must start with ' ', '-', or '+'): ${row}`);
108
+ if (!current) {
109
+ current = { lines: [] };
110
+ hunks.push(current);
111
+ }
112
+ current.lines.push({ type: type as PatchLineType, text: row.slice(1) });
113
+ i += 1;
114
+ }
115
+ if (hunks.length === 0 && !moveTo)
116
+ return fail(`Update File has no hunks: ${path}`);
117
+ ops.push({ kind: "update", path, hunks, moveTo });
118
+ continue;
119
+ }
120
+ return fail(`unsupported patch directive: ${line}`);
121
+ }
122
+ if (!foundEnd)
123
+ return fail("patch must end with *** End Patch");
124
+ if (ops.length === 0)
125
+ return fail("patch contains no file operations");
126
+ return { ok: true, ops };
127
+ }
128
+
129
+ function fail(output: string): ParseResult {
130
+ return { ok: false, output };
131
+ }