@abacus-ai/cli 1.106.25007 → 2.0.0-canary.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 (200) hide show
  1. package/.oxlintrc.json +8 -0
  2. package/dist/index.mjs +12603 -0
  3. package/package.json +7 -39
  4. package/resources/abacus.ico +0 -0
  5. package/resources/entitlements.plist +9 -0
  6. package/src/__e2e__/README.md +196 -0
  7. package/src/__e2e__/agent-interactions.e2e.test.tsx +61 -0
  8. package/src/__e2e__/cli-commands.e2e.test.tsx +77 -0
  9. package/src/__e2e__/conversation-throttle.e2e.test.ts +453 -0
  10. package/src/__e2e__/conversation.e2e.test.tsx +56 -0
  11. package/src/__e2e__/diff-preview.e2e.test.tsx +3399 -0
  12. package/src/__e2e__/file-creation.e2e.test.tsx +149 -0
  13. package/src/__e2e__/helpers/test-helpers.ts +450 -0
  14. package/src/__e2e__/keyboard-navigation.e2e.test.tsx +34 -0
  15. package/src/__e2e__/llm-models.e2e.test.ts +402 -0
  16. package/src/__e2e__/mcp/mcp-callback-flow.e2e.test.tsx +71 -0
  17. package/src/__e2e__/mcp/mcp-full-app-ui.e2e.test.tsx +167 -0
  18. package/src/__e2e__/mcp/mcp-ui-rendering.e2e.test.tsx +185 -0
  19. package/src/__e2e__/repl.e2e.test.tsx +78 -0
  20. package/src/__e2e__/shell-compatibility.e2e.test.tsx +76 -0
  21. package/src/__e2e__/theme-mcp.e2e.test.tsx +98 -0
  22. package/src/__e2e__/tool-permissions.e2e.test.tsx +66 -0
  23. package/src/args.ts +22 -0
  24. package/src/components/__tests__/react-compiler.test.tsx +78 -0
  25. package/src/components/__tests__/status-indicator.test.tsx +403 -0
  26. package/src/components/composer/__tests__/bash-runner.test.tsx +263 -0
  27. package/src/components/composer/agent-mode-indicator.tsx +63 -0
  28. package/src/components/composer/bash-runner.tsx +54 -0
  29. package/src/components/composer/commands/default-commands.tsx +615 -0
  30. package/src/components/composer/commands/handler.tsx +59 -0
  31. package/src/components/composer/commands/picker.tsx +273 -0
  32. package/src/components/composer/commands/registry.ts +233 -0
  33. package/src/components/composer/commands/types.ts +33 -0
  34. package/src/components/composer/context.tsx +88 -0
  35. package/src/components/composer/file-mention-picker.tsx +83 -0
  36. package/src/components/composer/help.tsx +44 -0
  37. package/src/components/composer/index.tsx +1006 -0
  38. package/src/components/composer/mentions.ts +57 -0
  39. package/src/components/composer/message-queue.tsx +70 -0
  40. package/src/components/composer/mode-panel.tsx +35 -0
  41. package/src/components/composer/modes/__tests__/bash-handler.test.tsx +755 -0
  42. package/src/components/composer/modes/__tests__/bash-renderer.test.tsx +1108 -0
  43. package/src/components/composer/modes/bash-handler.tsx +132 -0
  44. package/src/components/composer/modes/bash-renderer.tsx +175 -0
  45. package/src/components/composer/modes/default-handlers.tsx +33 -0
  46. package/src/components/composer/modes/index.ts +41 -0
  47. package/src/components/composer/modes/types.ts +21 -0
  48. package/src/components/composer/persistent-shell.ts +283 -0
  49. package/src/components/composer/process.ts +65 -0
  50. package/src/components/composer/types.ts +9 -0
  51. package/src/components/composer/use-mention-search.ts +68 -0
  52. package/src/components/error-boundry.tsx +60 -0
  53. package/src/components/exit-message.tsx +29 -0
  54. package/src/components/expanded-view.tsx +74 -0
  55. package/src/components/file-completion.tsx +127 -0
  56. package/src/components/header.tsx +47 -0
  57. package/src/components/logo.tsx +37 -0
  58. package/src/components/segments.tsx +356 -0
  59. package/src/components/status-indicator.tsx +306 -0
  60. package/src/components/tool-group-summary.tsx +263 -0
  61. package/src/components/tool-permissions/ask-user-question-permission-ui.tsx +312 -0
  62. package/src/components/tool-permissions/diff-preview.tsx +355 -0
  63. package/src/components/tool-permissions/index.ts +5 -0
  64. package/src/components/tool-permissions/permission-options.tsx +375 -0
  65. package/src/components/tool-permissions/permission-preview-header.tsx +57 -0
  66. package/src/components/tool-permissions/tool-permission-ui.tsx +398 -0
  67. package/src/components/tools/agent/ask-user-question.tsx +101 -0
  68. package/src/components/tools/agent/enter-plan-mode.tsx +49 -0
  69. package/src/components/tools/agent/exit-plan-mode.tsx +75 -0
  70. package/src/components/tools/agent/handoff-to-main.tsx +27 -0
  71. package/src/components/tools/agent/subagent.tsx +37 -0
  72. package/src/components/tools/agent/todo-write.tsx +104 -0
  73. package/src/components/tools/browser/close-tab.tsx +58 -0
  74. package/src/components/tools/browser/computer.tsx +70 -0
  75. package/src/components/tools/browser/get-interactive-elements.tsx +54 -0
  76. package/src/components/tools/browser/get-tab-content.tsx +51 -0
  77. package/src/components/tools/browser/navigate-to.tsx +59 -0
  78. package/src/components/tools/browser/new-tab.tsx +60 -0
  79. package/src/components/tools/browser/perform-action.tsx +63 -0
  80. package/src/components/tools/browser/refresh-tab.tsx +43 -0
  81. package/src/components/tools/browser/switch-tab.tsx +58 -0
  82. package/src/components/tools/filesystem/delete-file.tsx +104 -0
  83. package/src/components/tools/filesystem/edit.tsx +220 -0
  84. package/src/components/tools/filesystem/list-dir.tsx +78 -0
  85. package/src/components/tools/filesystem/read-file.tsx +180 -0
  86. package/src/components/tools/filesystem/upload-image.tsx +76 -0
  87. package/src/components/tools/ide/ide-diagnostics.tsx +62 -0
  88. package/src/components/tools/index.ts +91 -0
  89. package/src/components/tools/mcp/mcp-tool.tsx +158 -0
  90. package/src/components/tools/search/fetch-url.tsx +73 -0
  91. package/src/components/tools/search/file-search.tsx +78 -0
  92. package/src/components/tools/search/grep.tsx +90 -0
  93. package/src/components/tools/search/semantic-search.tsx +66 -0
  94. package/src/components/tools/search/web-search.tsx +71 -0
  95. package/src/components/tools/shared/index.tsx +48 -0
  96. package/src/components/tools/shared/zod-coercion.ts +35 -0
  97. package/src/components/tools/terminal/bash-tool-output.tsx +174 -0
  98. package/src/components/tools/terminal/get-terminal-output.tsx +85 -0
  99. package/src/components/tools/terminal/run-in-terminal.tsx +106 -0
  100. package/src/components/tools/types.ts +16 -0
  101. package/src/components/tools.tsx +66 -0
  102. package/src/components/ui/__tests__/divider.test.tsx +61 -0
  103. package/src/components/ui/__tests__/gradient.test.tsx +125 -0
  104. package/src/components/ui/__tests__/input.test.tsx +166 -0
  105. package/src/components/ui/__tests__/select.test.tsx +273 -0
  106. package/src/components/ui/__tests__/shimmer.test.tsx +99 -0
  107. package/src/components/ui/blinking-indicator.tsx +25 -0
  108. package/src/components/ui/divider.tsx +162 -0
  109. package/src/components/ui/gradient.tsx +56 -0
  110. package/src/components/ui/input.tsx +228 -0
  111. package/src/components/ui/select.tsx +151 -0
  112. package/src/components/ui/shimmer.tsx +84 -0
  113. package/src/context/agent-mode.tsx +95 -0
  114. package/src/context/extension-file.tsx +136 -0
  115. package/src/context/network-activity.tsx +45 -0
  116. package/src/context/notification.tsx +62 -0
  117. package/src/context/shell-size.tsx +49 -0
  118. package/src/context/shell-title.tsx +38 -0
  119. package/src/entrypoints/print-mode.ts +312 -0
  120. package/src/entrypoints/repl.tsx +401 -0
  121. package/src/hooks/use-agent.ts +15 -0
  122. package/src/hooks/use-api-client.ts +1 -0
  123. package/src/hooks/use-available-height.ts +8 -0
  124. package/src/hooks/use-cleanup.ts +29 -0
  125. package/src/hooks/use-interrupt-manager.ts +242 -0
  126. package/src/hooks/use-models.ts +22 -0
  127. package/src/index.ts +217 -0
  128. package/src/lib/__tests__/ansi.test.ts +255 -0
  129. package/src/lib/__tests__/cli.test.ts +122 -0
  130. package/src/lib/__tests__/commands.test.ts +325 -0
  131. package/src/lib/__tests__/constants.test.ts +15 -0
  132. package/src/lib/__tests__/focusables.test.ts +25 -0
  133. package/src/lib/__tests__/fs.test.ts +231 -0
  134. package/src/lib/__tests__/markdown.test.tsx +348 -0
  135. package/src/lib/__tests__/mcpCommandHandler.test.ts +173 -0
  136. package/src/lib/__tests__/mcpManagement.test.ts +38 -0
  137. package/src/lib/__tests__/path-paste.test.ts +144 -0
  138. package/src/lib/__tests__/path.test.ts +300 -0
  139. package/src/lib/__tests__/queries.test.ts +39 -0
  140. package/src/lib/__tests__/standaloneMcpService.test.ts +71 -0
  141. package/src/lib/__tests__/text-buffer.test.ts +328 -0
  142. package/src/lib/__tests__/text-utils.test.ts +32 -0
  143. package/src/lib/__tests__/timing.test.ts +78 -0
  144. package/src/lib/__tests__/utils.test.ts +238 -0
  145. package/src/lib/__tests__/vim-buffer-actions.test.ts +154 -0
  146. package/src/lib/ansi.ts +150 -0
  147. package/src/lib/cli-push-server.ts +112 -0
  148. package/src/lib/cli.ts +44 -0
  149. package/src/lib/clipboard.ts +226 -0
  150. package/src/lib/command-utils.ts +93 -0
  151. package/src/lib/commands.ts +270 -0
  152. package/src/lib/constants.ts +3 -0
  153. package/src/lib/extension-connection.ts +181 -0
  154. package/src/lib/focusables.ts +7 -0
  155. package/src/lib/fs.ts +533 -0
  156. package/src/lib/markdown/code-block.tsx +63 -0
  157. package/src/lib/markdown/index.ts +4 -0
  158. package/src/lib/markdown/link.tsx +19 -0
  159. package/src/lib/markdown/markdown.tsx +372 -0
  160. package/src/lib/markdown/types.ts +15 -0
  161. package/src/lib/mcpCommandHandler.ts +121 -0
  162. package/src/lib/mcpManagement.ts +44 -0
  163. package/src/lib/path-paste.ts +185 -0
  164. package/src/lib/path.ts +179 -0
  165. package/src/lib/queries.ts +15 -0
  166. package/src/lib/standaloneMcpService.ts +688 -0
  167. package/src/lib/status-utils.ts +237 -0
  168. package/src/lib/test-utils.tsx +72 -0
  169. package/src/lib/text-buffer.ts +2415 -0
  170. package/src/lib/text-utils.ts +272 -0
  171. package/src/lib/timing.ts +63 -0
  172. package/src/lib/types.ts +295 -0
  173. package/src/lib/utils.ts +182 -0
  174. package/src/lib/vim-buffer-actions.ts +732 -0
  175. package/src/providers/agent.tsx +1075 -0
  176. package/src/providers/api-client.tsx +43 -0
  177. package/src/services/logger.ts +85 -0
  178. package/src/terminal/detection.ts +187 -0
  179. package/src/terminal/exit.ts +279 -0
  180. package/src/terminal/notification.ts +83 -0
  181. package/src/terminal/progress.ts +201 -0
  182. package/src/terminal/setup.ts +797 -0
  183. package/src/terminal/suspend.ts +58 -0
  184. package/src/terminal/types.ts +51 -0
  185. package/src/theme/context.tsx +57 -0
  186. package/src/theme/index.ts +4 -0
  187. package/src/theme/themed.tsx +35 -0
  188. package/src/theme/themes.json +546 -0
  189. package/src/theme/types.ts +110 -0
  190. package/src/tools/types.ts +59 -0
  191. package/src/tools/utils/__tests__/zod-coercion.test.ts +33 -0
  192. package/src/tools/utils/tool-ui-components.tsx +631 -0
  193. package/src/tools/utils/zod-coercion.ts +35 -0
  194. package/tsconfig.json +11 -0
  195. package/tsconfig.node.json +29 -0
  196. package/tsconfig.test.json +27 -0
  197. package/tsdown.config.ts +17 -0
  198. package/vitest.config.ts +76 -0
  199. package/README.md +0 -28
  200. package/dist/index.js +0 -26
@@ -0,0 +1,43 @@
1
+ import { AbacusClient } from "@codellm/api";
2
+ import { AuthManager } from "@codellm/auth";
3
+ import { createContext, memo, use, useMemo, useState } from "react";
4
+
5
+ export interface ApiClientContextValue {
6
+ apiClient: AbacusClient;
7
+ authManager: AuthManager;
8
+ authExpired: boolean;
9
+ setAuthExpired: (expired: boolean) => void;
10
+ clearAuthExpired: () => void;
11
+ }
12
+
13
+ export const ApiClientContext = createContext<ApiClientContextValue | null>(null);
14
+
15
+ export const useApiClient = () => {
16
+ const ctx = use(ApiClientContext);
17
+ if (!ctx) throw new Error("useApiClient must be used within ApiClientProvider");
18
+ return ctx;
19
+ };
20
+
21
+ export const ApiClientProvider = memo(
22
+ ({
23
+ children,
24
+ client,
25
+ authManager,
26
+ }: React.PropsWithChildren<{
27
+ client: AbacusClient;
28
+ authManager: AuthManager;
29
+ }>) => {
30
+ const [authExpired, setAuthExpired] = useState(false);
31
+
32
+ const clearAuthExpired = () => setAuthExpired(false);
33
+
34
+ const value = useMemo(
35
+ () => ({ apiClient: client, authManager, authExpired, setAuthExpired, clearAuthExpired }),
36
+ // eslint-disable-next-line react-hooks/exhaustive-deps
37
+ [authExpired, client, authManager],
38
+ );
39
+
40
+ return <ApiClientContext.Provider value={value}>{children}</ApiClientContext.Provider>;
41
+ },
42
+ );
43
+ ApiClientProvider.displayName = "ApiClientProvider";
@@ -0,0 +1,85 @@
1
+ import { product } from "@codellm/product";
2
+ import { appendFileSync, mkdirSync, existsSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+
6
+ export interface Logger {
7
+ error(message: string | Error, ...args: unknown[]): void;
8
+ warn(message: string, ...args: unknown[]): void;
9
+ info(message: string, ...args: unknown[]): void;
10
+ debug(...message: unknown[]): void;
11
+ trace(message: string, ...args: unknown[]): void;
12
+ }
13
+
14
+ const LOG_DIR = path.join(homedir(), product.configDirName, product.logsDirName);
15
+ const LOG_FILE = path.join(LOG_DIR, "cli.log");
16
+
17
+ let dirEnsured = false;
18
+
19
+ function ensureLogDir(): void {
20
+ if (dirEnsured) {
21
+ return;
22
+ }
23
+ try {
24
+ if (!existsSync(LOG_DIR)) {
25
+ mkdirSync(LOG_DIR, { recursive: true });
26
+ }
27
+ dirEnsured = true;
28
+ } catch {
29
+ // Silently fail — logging should never crash the app
30
+ }
31
+ }
32
+
33
+ function formatArgs(args: unknown[]): string {
34
+ if (args.length === 0) {
35
+ return "";
36
+ }
37
+ return (
38
+ " " +
39
+ args
40
+ .map((a) => {
41
+ if (typeof a === "string") {
42
+ return a;
43
+ }
44
+ try {
45
+ return JSON.stringify(a);
46
+ } catch {
47
+ return String(a);
48
+ }
49
+ })
50
+ .join(" ")
51
+ );
52
+ }
53
+
54
+ function write(level: string, message: unknown, args: unknown[]): void {
55
+ ensureLogDir();
56
+ const timestamp = new Date().toISOString();
57
+ const msg =
58
+ message instanceof Error
59
+ ? `${message.message}${message.stack ? "\n" + message.stack : ""}`
60
+ : String(message);
61
+ const line = `[${timestamp}] [${level}] ${msg}${formatArgs(args)}\n`;
62
+ try {
63
+ appendFileSync(LOG_FILE, line);
64
+ } catch {
65
+ // Silently fail
66
+ }
67
+ }
68
+
69
+ export const logger: Logger = {
70
+ error(message: string | Error, ...args: unknown[]) {
71
+ write("ERROR", message, args);
72
+ },
73
+ warn(message: string, ...args: unknown[]) {
74
+ write("WARN", message, args);
75
+ },
76
+ info(message: string, ...args: unknown[]) {
77
+ write("INFO", message, args);
78
+ },
79
+ debug(...message: unknown[]) {
80
+ write("DEBUG", message[0] ?? "", message.slice(1));
81
+ },
82
+ trace(message: string, ...args: unknown[]) {
83
+ write("TRACE", message, args);
84
+ },
85
+ };
@@ -0,0 +1,187 @@
1
+ import process from "node:process";
2
+
3
+ import type { TerminalType } from "./types.js";
4
+
5
+ const JETBRAIN_IDES = [
6
+ "pycharm",
7
+ "intellij",
8
+ "webstorm",
9
+ "phpstorm",
10
+ "rubymine",
11
+ "clion",
12
+ "goland",
13
+ "rider",
14
+ "datagrip",
15
+ "appcode",
16
+ "dataspell",
17
+ "aqua",
18
+ "gateway",
19
+ "fleet",
20
+ "jetbrains",
21
+ "androidstudio",
22
+ ];
23
+
24
+ export function getTerminal(logger?: { debug?: (message: string) => void }): TerminalType {
25
+ if (process.env.CURSOR_TRACE_ID) {
26
+ logger?.debug?.("Detected Cursor terminal via CURSOR_TRACE_ID");
27
+ return "cursor";
28
+ }
29
+ if (process.env.VSCODE_GIT_ASKPASS_MAIN?.includes("/.cursor-server/")) {
30
+ logger?.debug?.("Detected Cursor terminal via VSCODE_GIT_ASKPASS_MAIN");
31
+ return "cursor";
32
+ }
33
+ if (process.env.VSCODE_GIT_ASKPASS_MAIN?.includes("/.windsurf-server/")) {
34
+ logger?.debug?.("Detected Windsurf terminal");
35
+ return "windsurf";
36
+ }
37
+
38
+ const BUNDLE_ID = process.env.__CFBundleIdentifier?.toLowerCase();
39
+ if (BUNDLE_ID?.includes("vscodium")) {
40
+ return "codium";
41
+ }
42
+ if (BUNDLE_ID?.includes("windsurf")) {
43
+ return "windsurf";
44
+ }
45
+ if (BUNDLE_ID?.includes("com.google.android.studio")) {
46
+ return "androidstudio";
47
+ }
48
+ if (BUNDLE_ID) {
49
+ for (const IDE of JETBRAIN_IDES) {
50
+ if (BUNDLE_ID.includes(IDE)) {
51
+ return IDE;
52
+ }
53
+ }
54
+ }
55
+
56
+ if (process.env.VisualStudioVersion) {
57
+ return "visualstudio";
58
+ }
59
+ if (process.env.TERMINAL_EMULATOR === "JetBrains-JediTerm") {
60
+ return "pycharm";
61
+ }
62
+ if (process.env.TERM === "xterm-ghostty") {
63
+ return "ghostty";
64
+ }
65
+ if (process.env.TERM?.includes("kitty")) {
66
+ return "kitty";
67
+ }
68
+ if (process.env.WEZTERM_PANE) {
69
+ return "WezTerm";
70
+ }
71
+ if (process.env.ITERM_SESSION_ID) {
72
+ return "iTerm.app";
73
+ }
74
+ if (process.env.TERM_PROGRAM === "Apple_Terminal") {
75
+ return "Apple_Terminal";
76
+ }
77
+ if (process.env.TERM_PROGRAM) {
78
+ return process.env.TERM_PROGRAM;
79
+ }
80
+ if (process.env.STY) {
81
+ return "screen";
82
+ }
83
+ if (process.env.KONSOLE_VERSION) {
84
+ return "konsole";
85
+ }
86
+ if (process.env.GNOME_TERMINAL_SERVICE) {
87
+ return "gnome-terminal";
88
+ }
89
+ if (process.env.XTERM_VERSION) {
90
+ return "xterm";
91
+ }
92
+ if (process.env.VTE_VERSION) {
93
+ return "vte-based";
94
+ }
95
+ if (process.env.TERMINATOR_UUID) {
96
+ return "terminator";
97
+ }
98
+ if (process.env.KITTY_WINDOW_ID) {
99
+ return "kitty";
100
+ }
101
+ if (process.env.ALACRITTY_LOG) {
102
+ return "alacritty";
103
+ }
104
+ if (process.env.TILIX_ID) {
105
+ return "tilix";
106
+ }
107
+ if (process.env.WT_SESSION) {
108
+ return "windows-terminal";
109
+ }
110
+ if (process.env.SESSIONNAME && process.env.TERM === "cygwin") {
111
+ return "cygwin";
112
+ }
113
+ if (process.env.MSYSTEM) {
114
+ return process.env.MSYSTEM.toLowerCase();
115
+ }
116
+ if (process.env.ConEmuANSI || process.env.ConEmuPID || process.env.ConEmuTask) {
117
+ return "conemu";
118
+ }
119
+ if (process.env.WSL_DISTRO_NAME) {
120
+ return `wsl-${process.env.WSL_DISTRO_NAME}`;
121
+ }
122
+ if (process.env.SSH_CONNECTION || process.env.SSH_CLIENT || process.env.SSH_TTY) {
123
+ return "ssh-session";
124
+ }
125
+ if (process.env.TERM) {
126
+ const ENV_TERM = process.env.TERM;
127
+ if (ENV_TERM.includes("alacritty")) {
128
+ return "alacritty";
129
+ }
130
+ if (ENV_TERM.includes("rxvt")) {
131
+ return "rxvt";
132
+ }
133
+ if (ENV_TERM.includes("termite")) {
134
+ return "termite";
135
+ }
136
+ return process.env.TERM;
137
+ }
138
+ if (!process.stdout.isTTY) {
139
+ logger?.debug?.("Non-interactive terminal detected");
140
+ return "non-interactive";
141
+ }
142
+ logger?.debug?.("Could not detect terminal type");
143
+ return null;
144
+ }
145
+
146
+ export function isTerminalSetupSupported(): boolean {
147
+ const terminal = getTerminal();
148
+ if (process.platform === "darwin") {
149
+ return [
150
+ "iTerm.app",
151
+ "Apple_Terminal",
152
+ "vscode",
153
+ "cursor",
154
+ "windsurf",
155
+ "ghostty",
156
+ "WezTerm",
157
+ ].includes(terminal ?? "");
158
+ }
159
+ return ["vscode", "cursor", "windsurf", "ghostty", "WezTerm", "kitty"].includes(terminal ?? "");
160
+ }
161
+
162
+ export function getPasteKeyInstruction(): string {
163
+ if (process.platform === "darwin") return "Cmd+V";
164
+ if (process.platform === "win32") return "Ctrl+V";
165
+ return "Ctrl+Shift+V"; // Linux xterm/VTE convention
166
+ }
167
+
168
+ export function getNewlineInstructions(): string {
169
+ const terminal = getTerminal();
170
+
171
+ switch (terminal) {
172
+ case "Apple_Terminal":
173
+ return "Option+Enter";
174
+ case "cursor":
175
+ case "windsurf":
176
+ case "vscode":
177
+ case "codium":
178
+ case "iTerm.app":
179
+ case "ghostty":
180
+ case "WezTerm":
181
+ case "kitty":
182
+ case "alacritty":
183
+ return "Shift+Enter";
184
+ default:
185
+ return "backslash (\\) + Enter";
186
+ }
187
+ }
@@ -0,0 +1,279 @@
1
+ import type { Writable } from "node:stream";
2
+
3
+ import process from "node:process";
4
+
5
+ interface ExitHookOptions {
6
+ wait?: number;
7
+ streams?: Writable[];
8
+ logger?: {
9
+ debug?: (message: string, meta?: any) => void;
10
+ };
11
+ }
12
+
13
+ type ExitCallback = (exitCode: number) => void | Promise<void>;
14
+
15
+ const asyncCallbacks = new Set<[ExitCallback, number]>();
16
+ const syncCallbacks = new Set<ExitCallback>();
17
+ const streamsToDrain = new Set<Writable>();
18
+
19
+ let isExiting = false;
20
+ let isRegistered = false;
21
+ let originalExit: ((code?: number) => never) | null = null;
22
+ let firstExitCode: number | undefined;
23
+
24
+ async function drainStreams(streams: Writable[]): Promise<void> {
25
+ const drainPromises = streams.map((stream) => {
26
+ return new Promise<void>((resolve) => {
27
+ const writableLength =
28
+ "writableLength" in stream ? (stream as { writableLength: number }).writableLength : 0;
29
+ const bufferSize =
30
+ "bufferSize" in stream ? (stream as { bufferSize: number }).bufferSize : writableLength;
31
+
32
+ if (bufferSize === 0) {
33
+ resolve();
34
+ return;
35
+ }
36
+
37
+ const originalWrite = stream.write.bind(stream);
38
+ let isDrained = false;
39
+
40
+ const checkDrain = () => {
41
+ const currentLength =
42
+ "writableLength" in stream ? (stream as { writableLength: number }).writableLength : 0;
43
+ const currentBufferSize =
44
+ "bufferSize" in stream ? (stream as { bufferSize: number }).bufferSize : currentLength;
45
+
46
+ if (currentBufferSize === 0 && !isDrained) {
47
+ isDrained = true;
48
+ stream.write = originalWrite;
49
+ resolve();
50
+ }
51
+ };
52
+
53
+ stream.once("drain", checkDrain);
54
+
55
+ stream.write("", "utf-8", () => {
56
+ checkDrain();
57
+ });
58
+
59
+ stream.write = function () {
60
+ return false;
61
+ };
62
+ });
63
+ });
64
+
65
+ await Promise.all(drainPromises);
66
+ }
67
+
68
+ async function executeExit(
69
+ shouldManuallyExit: boolean,
70
+ isSynchronous: boolean,
71
+ signal: number,
72
+ logger?: { debug?: (message: string, meta?: any) => void },
73
+ ): Promise<void> {
74
+ if (isExiting) {
75
+ return;
76
+ }
77
+
78
+ logger?.debug?.("Executing exit handlers", {
79
+ shouldManuallyExit,
80
+ isSynchronous,
81
+ signal,
82
+ asyncCallbacks: asyncCallbacks.size,
83
+ syncCallbacks: syncCallbacks.size,
84
+ });
85
+
86
+ isExiting = true;
87
+
88
+ if (asyncCallbacks.size > 0 && isSynchronous) {
89
+ console.error(
90
+ [
91
+ "SYNCHRONOUS TERMINATION NOTICE:",
92
+ "When explicitly exiting the process via process.exit or via a parent process,",
93
+ "asynchronous tasks in your exitHooks will not run. Either remove these tasks,",
94
+ "use gracefulExit() instead of process.exit(), or ensure your parent process",
95
+ "sends a SIGINT to the process running this code.",
96
+ ].join(" "),
97
+ );
98
+ }
99
+
100
+ let exitCode = 0;
101
+
102
+ if (signal > 0) {
103
+ exitCode = 128 + signal;
104
+ } else if (firstExitCode !== undefined) {
105
+ exitCode = firstExitCode;
106
+ } else if (typeof process.exitCode === "number" || typeof process.exitCode === "string") {
107
+ exitCode = Number(process.exitCode);
108
+ }
109
+
110
+ const done = (force = false) => {
111
+ if (force || shouldManuallyExit) {
112
+ if (originalExit) {
113
+ originalExit.call(process, exitCode);
114
+ } else {
115
+ process.exit(exitCode);
116
+ }
117
+ }
118
+ };
119
+
120
+ for (const callback of syncCallbacks) {
121
+ try {
122
+ void callback(exitCode);
123
+ } catch (error) {
124
+ console.error("Error in synchronous exit hook:", error);
125
+ }
126
+ }
127
+
128
+ if (isSynchronous) {
129
+ done();
130
+ return;
131
+ }
132
+
133
+ const promises: Promise<void>[] = [];
134
+ let maxWait = 0;
135
+
136
+ for (const [callback, wait] of asyncCallbacks) {
137
+ maxWait = Math.max(maxWait, wait);
138
+ promises.push(
139
+ Promise.resolve(callback(exitCode)).catch((error) => {
140
+ console.error("Error in asynchronous exit hook:", error);
141
+ }),
142
+ );
143
+ }
144
+
145
+ const streams = Array.from(streamsToDrain);
146
+ if (streams.length > 0) {
147
+ promises.push(drainStreams(streams));
148
+ }
149
+
150
+ const asyncTimer = setTimeout(() => {
151
+ done(true);
152
+ }, maxWait);
153
+
154
+ try {
155
+ await Promise.all(promises);
156
+ clearTimeout(asyncTimer);
157
+ done();
158
+ } catch (error) {
159
+ clearTimeout(asyncTimer);
160
+ console.error("Error during exit cleanup:", error);
161
+ done(true);
162
+ }
163
+ }
164
+
165
+ function registerExitHandlers(): void {
166
+ if (isRegistered) {
167
+ return;
168
+ }
169
+
170
+ isRegistered = true;
171
+
172
+ process.once("beforeExit", () => {
173
+ void executeExit(true, false, -128);
174
+ });
175
+
176
+ process.once("SIGINT", () => {
177
+ void executeExit(true, false, 2);
178
+ });
179
+
180
+ process.once("SIGTERM", () => {
181
+ void executeExit(true, false, 15);
182
+ });
183
+
184
+ process.once("exit", () => {
185
+ void executeExit(false, true, 0);
186
+ });
187
+
188
+ process.on("message", (message) => {
189
+ if (message === "shutdown") {
190
+ void executeExit(true, true, -128);
191
+ }
192
+ });
193
+
194
+ if (!originalExit) {
195
+ originalExit = process.exit.bind(process) as (code?: number) => never;
196
+
197
+ const exitHandler = function (code?: number) {
198
+ if (firstExitCode === undefined) {
199
+ firstExitCode = code ?? 0;
200
+ }
201
+
202
+ if (asyncCallbacks.size === 0 && streamsToDrain.size === 0) {
203
+ if (originalExit) {
204
+ originalExit(code ?? 0);
205
+ return;
206
+ }
207
+ process.exit(code ?? 0);
208
+ }
209
+
210
+ executeExit(true, false, -128).catch((error) => {
211
+ console.error("Error during exit:", error);
212
+ if (originalExit) {
213
+ originalExit(1);
214
+ } else {
215
+ process.exit(1);
216
+ }
217
+ });
218
+ };
219
+
220
+ process.exit = exitHandler as typeof process.exit;
221
+ }
222
+ }
223
+
224
+ export function onExit(callback: ExitCallback, options?: ExitHookOptions): () => void {
225
+ if (typeof callback !== "function") {
226
+ throw new TypeError("callback must be a function");
227
+ }
228
+
229
+ if (isExiting) {
230
+ throw new Error("Cannot install exit hook while exit handlers are running");
231
+ }
232
+
233
+ options?.logger?.debug?.("Registering exit hook", {
234
+ wait: options?.wait,
235
+ hasStreams: options?.streams !== undefined,
236
+ });
237
+
238
+ registerExitHandlers();
239
+
240
+ const wait = options?.wait ?? 0;
241
+ const streams = options?.streams ?? [process.stdout, process.stderr];
242
+
243
+ if (wait > 0) {
244
+ const callbackConfig: [ExitCallback, number] = [callback, wait];
245
+ asyncCallbacks.add(callbackConfig);
246
+
247
+ for (const stream of streams) {
248
+ streamsToDrain.add(stream);
249
+ }
250
+
251
+ return () => {
252
+ asyncCallbacks.delete(callbackConfig);
253
+ for (const stream of streams) {
254
+ streamsToDrain.delete(stream);
255
+ }
256
+ };
257
+ }
258
+
259
+ syncCallbacks.add(callback);
260
+
261
+ return () => {
262
+ syncCallbacks.delete(callback);
263
+ };
264
+ }
265
+
266
+ export function gracefulExit(signal?: number): void {
267
+ if (signal !== undefined) {
268
+ process.exitCode = signal;
269
+ }
270
+
271
+ void executeExit(true, false, -128);
272
+ }
273
+
274
+ export function releaseExit(): void {
275
+ if (originalExit) {
276
+ process.exit = originalExit;
277
+ originalExit = null;
278
+ }
279
+ }
@@ -0,0 +1,83 @@
1
+ import process from "node:process";
2
+
3
+ import { ANSI, osc9, osc777, osc99 } from "../lib/ansi.js";
4
+ import { getTerminal } from "./detection.js";
5
+
6
+ export interface NotificationOptions {
7
+ title?: string;
8
+ message: string;
9
+ sound?: boolean;
10
+ }
11
+
12
+ function writeToTerminal(data: string): void {
13
+ if (process.stdout.isTTY) {
14
+ process.stdout.write(data);
15
+ }
16
+ }
17
+
18
+ function notifyIterm2(title: string, message: string): void {
19
+ const fullMessage = title ? `${title}:\n${message}` : message;
20
+ writeToTerminal(osc9(fullMessage));
21
+ }
22
+
23
+ function notifyKitty(title: string, message: string): void {
24
+ writeToTerminal(osc99(title, message));
25
+ }
26
+
27
+ function notifyGhostty(title: string, message: string): void {
28
+ writeToTerminal(osc777(title, message));
29
+ }
30
+
31
+ function notifyWindows(_title: string, _message: string): void {
32
+ // Windows notifications via PowerShell - simplified version
33
+ // Full implementation would require executing PowerShell script
34
+ // For now, just ring the bell
35
+ writeToTerminal(ANSI.BEL);
36
+ }
37
+
38
+ export async function notify(options: NotificationOptions): Promise<void> {
39
+ const { title = "Abacus.AI", message } = options;
40
+ const terminal = getTerminal();
41
+
42
+ switch (terminal) {
43
+ case "iTerm.app":
44
+ notifyIterm2(title, message);
45
+ break;
46
+ case "kitty":
47
+ notifyKitty(title, message);
48
+ break;
49
+ case "ghostty":
50
+ notifyGhostty(title, message);
51
+ break;
52
+ case "WezTerm":
53
+ notifyIterm2(title, message);
54
+ break;
55
+ default:
56
+ if (process.platform === "win32") {
57
+ notifyWindows(title, message);
58
+ }
59
+ break;
60
+ }
61
+ }
62
+
63
+ export async function notifyAction(
64
+ message: string,
65
+ options?: Omit<NotificationOptions, "message">,
66
+ ): Promise<void> {
67
+ await notify({
68
+ ...options,
69
+ message,
70
+ title: options?.title ?? "Action Required",
71
+ });
72
+ }
73
+
74
+ export async function notifyComplete(
75
+ message: string,
76
+ options?: Omit<NotificationOptions, "message">,
77
+ ): Promise<void> {
78
+ await notify({
79
+ ...options,
80
+ message,
81
+ title: options?.title ?? "Task Complete",
82
+ });
83
+ }