@bubblebrain-ai/bubble 0.0.12 → 0.0.14

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 (180) hide show
  1. package/dist/agent/execution-governor.js +1 -1
  2. package/dist/agent/input-controller.d.ts +11 -0
  3. package/dist/agent/input-controller.js +30 -0
  4. package/dist/agent/tool-intent.js +1 -0
  5. package/dist/agent.d.ts +8 -4
  6. package/dist/agent.js +623 -312
  7. package/dist/approval/controller.d.ts +1 -0
  8. package/dist/approval/controller.js +20 -3
  9. package/dist/approval/tool-helper.js +2 -0
  10. package/dist/approval/types.d.ts +14 -1
  11. package/dist/context/compact.js +9 -3
  12. package/dist/context/projector.js +27 -12
  13. package/dist/debug-trace.d.ts +27 -0
  14. package/dist/debug-trace.js +385 -0
  15. package/dist/feishu/agent-host/approval-card.js +9 -0
  16. package/dist/feishu/serve.js +7 -1
  17. package/dist/main.js +86 -9
  18. package/dist/model-catalog.js +1 -0
  19. package/dist/orchestrator/default-hooks.js +19 -8
  20. package/dist/orchestrator/hooks.d.ts +1 -0
  21. package/dist/prompt/environment.js +2 -0
  22. package/dist/prompt/reminders.d.ts +5 -6
  23. package/dist/prompt/reminders.js +8 -9
  24. package/dist/prompt/runtime.js +2 -2
  25. package/dist/provider-openai-codex.d.ts +7 -0
  26. package/dist/provider-openai-codex.js +265 -124
  27. package/dist/provider-registry.d.ts +2 -0
  28. package/dist/provider-registry.js +58 -9
  29. package/dist/provider.d.ts +3 -0
  30. package/dist/provider.js +5 -1
  31. package/dist/session-log.js +13 -1
  32. package/dist/slash-commands/commands.js +39 -0
  33. package/dist/slash-commands/types.d.ts +12 -0
  34. package/dist/stats/usage.d.ts +52 -0
  35. package/dist/stats/usage.js +414 -0
  36. package/dist/tools/apply-patch.d.ts +9 -0
  37. package/dist/tools/apply-patch.js +330 -0
  38. package/dist/tools/bash.js +205 -44
  39. package/dist/tools/edit-apply.d.ts +5 -2
  40. package/dist/tools/edit-apply.js +221 -31
  41. package/dist/tools/edit.js +12 -3
  42. package/dist/tools/file-mutation-queue.d.ts +1 -0
  43. package/dist/tools/file-mutation-queue.js +12 -1
  44. package/dist/tools/index.d.ts +2 -0
  45. package/dist/tools/index.js +7 -1
  46. package/dist/tools/patch-apply.d.ts +41 -0
  47. package/dist/tools/patch-apply.js +312 -0
  48. package/dist/tools/server-manager.d.ts +36 -0
  49. package/dist/tools/server-manager.js +234 -0
  50. package/dist/tools/server.d.ts +6 -0
  51. package/dist/tools/server.js +245 -0
  52. package/dist/tools/write.d.ts +3 -6
  53. package/dist/tools/write.js +26 -46
  54. package/dist/tui/clipboard.d.ts +1 -0
  55. package/dist/tui/clipboard.js +53 -0
  56. package/dist/tui/detect-theme.d.ts +2 -0
  57. package/dist/tui/detect-theme.js +87 -0
  58. package/dist/tui/display-history.d.ts +63 -0
  59. package/dist/tui/display-history.js +306 -0
  60. package/dist/tui/edit-diff.d.ts +11 -0
  61. package/dist/tui/edit-diff.js +57 -0
  62. package/dist/tui/escape-confirmation.d.ts +15 -0
  63. package/dist/tui/escape-confirmation.js +30 -0
  64. package/dist/tui/file-mentions.d.ts +29 -0
  65. package/dist/tui/file-mentions.js +174 -0
  66. package/dist/tui/global-key-router.d.ts +3 -0
  67. package/dist/tui/global-key-router.js +87 -0
  68. package/dist/tui/image-paste.d.ts +95 -0
  69. package/dist/tui/image-paste.js +505 -0
  70. package/dist/tui/input-history.d.ts +16 -0
  71. package/dist/tui/input-history.js +79 -0
  72. package/dist/tui/markdown-inline.d.ts +22 -0
  73. package/dist/tui/markdown-inline.js +68 -0
  74. package/dist/tui/markdown-theme-rules.d.ts +23 -0
  75. package/dist/tui/markdown-theme-rules.js +164 -0
  76. package/dist/tui/markdown-theme.d.ts +5 -0
  77. package/dist/tui/markdown-theme.js +27 -0
  78. package/dist/tui/model-picker-data.d.ts +10 -0
  79. package/dist/tui/model-picker-data.js +32 -0
  80. package/dist/tui/opencode-spinner.d.ts +22 -0
  81. package/dist/tui/opencode-spinner.js +216 -0
  82. package/dist/tui/prompt-keybindings.d.ts +42 -0
  83. package/dist/tui/prompt-keybindings.js +35 -0
  84. package/dist/tui/recent-activity.d.ts +8 -0
  85. package/dist/tui/recent-activity.js +71 -0
  86. package/dist/tui/render-signature.d.ts +1 -0
  87. package/dist/tui/render-signature.js +7 -0
  88. package/dist/tui/run.d.ts +45 -0
  89. package/dist/tui/run.js +9359 -0
  90. package/dist/tui/session-display.d.ts +6 -0
  91. package/dist/tui/session-display.js +12 -0
  92. package/dist/tui/sidebar-mcp.d.ts +31 -0
  93. package/dist/tui/sidebar-mcp.js +62 -0
  94. package/dist/tui/sidebar-state.d.ts +12 -0
  95. package/dist/tui/sidebar-state.js +69 -0
  96. package/dist/tui/streaming-tool-args.d.ts +15 -0
  97. package/dist/tui/streaming-tool-args.js +30 -0
  98. package/dist/tui/tool-renderers/fallback.d.ts +2 -0
  99. package/dist/tui/tool-renderers/fallback.js +75 -0
  100. package/dist/tui/tool-renderers/registry.d.ts +3 -0
  101. package/dist/tui/tool-renderers/registry.js +11 -0
  102. package/dist/tui/tool-renderers/subagent.d.ts +2 -0
  103. package/dist/tui/tool-renderers/subagent.js +135 -0
  104. package/dist/tui/tool-renderers/types.d.ts +36 -0
  105. package/dist/tui/tool-renderers/types.js +1 -0
  106. package/dist/tui/tool-renderers/write-preview.d.ts +12 -0
  107. package/dist/tui/tool-renderers/write-preview.js +32 -0
  108. package/dist/tui/tool-renderers/write.d.ts +6 -0
  109. package/dist/tui/tool-renderers/write.js +88 -0
  110. package/dist/tui/trace-groups.d.ts +27 -0
  111. package/dist/tui/trace-groups.js +419 -0
  112. package/dist/tui/wordmark.d.ts +15 -0
  113. package/dist/tui/wordmark.js +179 -0
  114. package/dist/tui-ink/app.js +45 -9
  115. package/dist/tui-ink/approval/approval-dialog.js +7 -1
  116. package/dist/tui-ink/display-history.d.ts +1 -0
  117. package/dist/tui-ink/display-history.js +5 -4
  118. package/dist/tui-ink/message-list.js +23 -9
  119. package/dist/tui-ink/theme.d.ts +3 -9
  120. package/dist/tui-ink/theme.js +39 -45
  121. package/dist/tui-ink/trace-groups.js +1 -1
  122. package/dist/tui-ink/welcome.js +22 -78
  123. package/dist/tui-opentui/app.d.ts +54 -0
  124. package/dist/tui-opentui/app.js +1365 -0
  125. package/dist/tui-opentui/approval/approval-dialog.d.ts +15 -0
  126. package/dist/tui-opentui/approval/approval-dialog.js +145 -0
  127. package/dist/tui-opentui/approval/diff-view.d.ts +9 -0
  128. package/dist/tui-opentui/approval/diff-view.js +43 -0
  129. package/dist/tui-opentui/approval/select.d.ts +37 -0
  130. package/dist/tui-opentui/approval/select.js +91 -0
  131. package/dist/tui-opentui/detect-theme.d.ts +2 -0
  132. package/dist/tui-opentui/detect-theme.js +87 -0
  133. package/dist/tui-opentui/display-history.d.ts +56 -0
  134. package/dist/tui-opentui/display-history.js +130 -0
  135. package/dist/tui-opentui/edit-diff.d.ts +11 -0
  136. package/dist/tui-opentui/edit-diff.js +57 -0
  137. package/dist/tui-opentui/feedback-dialog.d.ts +21 -0
  138. package/dist/tui-opentui/feedback-dialog.js +164 -0
  139. package/dist/tui-opentui/feishu-setup-picker.d.ts +7 -0
  140. package/dist/tui-opentui/feishu-setup-picker.js +272 -0
  141. package/dist/tui-opentui/file-mentions.d.ts +29 -0
  142. package/dist/tui-opentui/file-mentions.js +174 -0
  143. package/dist/tui-opentui/footer.d.ts +26 -0
  144. package/dist/tui-opentui/footer.js +40 -0
  145. package/dist/tui-opentui/image-paste.d.ts +54 -0
  146. package/dist/tui-opentui/image-paste.js +288 -0
  147. package/dist/tui-opentui/input-box.d.ts +34 -0
  148. package/dist/tui-opentui/input-box.js +471 -0
  149. package/dist/tui-opentui/input-history.d.ts +16 -0
  150. package/dist/tui-opentui/input-history.js +79 -0
  151. package/dist/tui-opentui/markdown.d.ts +66 -0
  152. package/dist/tui-opentui/markdown.js +127 -0
  153. package/dist/tui-opentui/message-list.d.ts +31 -0
  154. package/dist/tui-opentui/message-list.js +128 -0
  155. package/dist/tui-opentui/model-picker.d.ts +63 -0
  156. package/dist/tui-opentui/model-picker.js +450 -0
  157. package/dist/tui-opentui/plan-confirm.d.ts +9 -0
  158. package/dist/tui-opentui/plan-confirm.js +124 -0
  159. package/dist/tui-opentui/question-dialog.d.ts +10 -0
  160. package/dist/tui-opentui/question-dialog.js +110 -0
  161. package/dist/tui-opentui/recent-activity.d.ts +8 -0
  162. package/dist/tui-opentui/recent-activity.js +71 -0
  163. package/dist/tui-opentui/run-session-picker.d.ts +10 -0
  164. package/dist/tui-opentui/run-session-picker.js +28 -0
  165. package/dist/tui-opentui/run.d.ts +38 -0
  166. package/dist/tui-opentui/run.js +48 -0
  167. package/dist/tui-opentui/session-picker.d.ts +12 -0
  168. package/dist/tui-opentui/session-picker.js +120 -0
  169. package/dist/tui-opentui/theme.d.ts +89 -0
  170. package/dist/tui-opentui/theme.js +157 -0
  171. package/dist/tui-opentui/todos.d.ts +9 -0
  172. package/dist/tui-opentui/todos.js +45 -0
  173. package/dist/tui-opentui/trace-groups.d.ts +27 -0
  174. package/dist/tui-opentui/trace-groups.js +419 -0
  175. package/dist/tui-opentui/use-terminal-size.d.ts +4 -0
  176. package/dist/tui-opentui/use-terminal-size.js +5 -0
  177. package/dist/tui-opentui/welcome.d.ts +25 -0
  178. package/dist/tui-opentui/welcome.js +77 -0
  179. package/dist/types.d.ts +36 -2
  180. package/package.json +5 -1
@@ -0,0 +1,87 @@
1
+ import { isEscapeSequence } from "./prompt-keybindings.js";
2
+ export function normalizeKeyName(name) {
3
+ const rawName = String(name || "").toLowerCase();
4
+ if (["arrowleft", "left_arrow", "leftarrow", "cursorleft", "left"].includes(rawName))
5
+ return "left";
6
+ if (["arrowright", "right_arrow", "rightarrow", "cursorright", "right"].includes(rawName))
7
+ return "right";
8
+ if (["arrowup", "up_arrow", "uparrow", "cursorup", "up"].includes(rawName))
9
+ return "up";
10
+ if (["arrowdown", "down_arrow", "downarrow", "cursordown", "down"].includes(rawName))
11
+ return "down";
12
+ if (rawName === "return" || rawName === "enter")
13
+ return "enter";
14
+ if (rawName === "esc" || rawName === "escape")
15
+ return "escape";
16
+ if (rawName === "tab")
17
+ return "tab";
18
+ return rawName;
19
+ }
20
+ export function keyNameFromSequence(sequence) {
21
+ if (!sequence)
22
+ return "";
23
+ const kittyName = keyNameFromKittySequence(sequence);
24
+ if (kittyName)
25
+ return kittyName;
26
+ if (sequence === "\x1b[D" || /^\x1b\[[0-9;]*D$/.test(sequence))
27
+ return "left";
28
+ if (sequence === "\x1b[C" || /^\x1b\[[0-9;]*C$/.test(sequence))
29
+ return "right";
30
+ if (sequence === "\x1b[A" || /^\x1b\[[0-9;]*A$/.test(sequence))
31
+ return "up";
32
+ if (sequence === "\x1b[B" || /^\x1b\[[0-9;]*B$/.test(sequence))
33
+ return "down";
34
+ if (sequence === "\x1bOD")
35
+ return "left";
36
+ if (sequence === "\x1bOC")
37
+ return "right";
38
+ if (sequence === "\x1bOA")
39
+ return "up";
40
+ if (sequence === "\x1bOB")
41
+ return "down";
42
+ if (sequence === "\t")
43
+ return "tab";
44
+ if (sequence === "\r" || sequence === "\n")
45
+ return "enter";
46
+ if (isEscapeSequence(sequence))
47
+ return "escape";
48
+ return "";
49
+ }
50
+ function keyNameFromKittySequence(sequence) {
51
+ const kittyMatch = /^\x1b\[(\d+)(?:;[1-9]\d*(?::[1-3])?)?u$/.exec(sequence);
52
+ const kittyCode = kittyMatch?.[1] ? Number(kittyMatch[1]) : NaN;
53
+ if (!Number.isNaN(kittyCode))
54
+ return keyNameFromKittyCode(kittyCode);
55
+ const modifyOtherKeysMatch = /^\x1b\[27;[1-9]\d*(?::[1-3])?;(\d+)~$/.exec(sequence);
56
+ const modifyOtherKeysCode = modifyOtherKeysMatch?.[1] ? Number(modifyOtherKeysMatch[1]) : NaN;
57
+ if (!Number.isNaN(modifyOtherKeysCode))
58
+ return keyNameFromKittyCode(modifyOtherKeysCode);
59
+ return "";
60
+ }
61
+ function keyNameFromKittyCode(code) {
62
+ switch (code) {
63
+ case 27:
64
+ case 57344:
65
+ return "escape";
66
+ case 9:
67
+ case 57346:
68
+ return "tab";
69
+ case 13:
70
+ case 57345:
71
+ return "enter";
72
+ case 57350:
73
+ return "left";
74
+ case 57351:
75
+ return "right";
76
+ case 57352:
77
+ return "up";
78
+ case 57353:
79
+ return "down";
80
+ default:
81
+ return "";
82
+ }
83
+ }
84
+ export function keyNameFromEvent(event) {
85
+ const rawName = normalizeKeyName(event?.name || event?.key || event?.input);
86
+ return rawName || keyNameFromSequence(event?.raw || event?.sequence);
87
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Image paste utilities: path detection, file reading, clipboard access, and size-capping.
3
+ *
4
+ * Terminals don't forward image bytes to stdin. Paths arrive as text when users
5
+ * drag files in; Cmd+V of an image produces an empty paste (we probe the
6
+ * clipboard). macOS screenshot shortcut (Cmd+Shift+Ctrl+4) writes to both a
7
+ * TemporaryItems path and the clipboard — the path often gets cleaned up before
8
+ * we can read it, so we fall back to the clipboard.
9
+ */
10
+ import type { ContentPart } from "../types.js";
11
+ export interface ImageAttachment {
12
+ base64: string;
13
+ mediaType: string;
14
+ /** Raw byte size of the decoded image (not base64). */
15
+ bytes: number;
16
+ /** data:<mediaType>;base64,<...> — ready to send as image_url.url. */
17
+ dataUrl: string;
18
+ filename?: string;
19
+ sourcePath?: string;
20
+ }
21
+ export interface ImagePathToken {
22
+ rawPath: string;
23
+ start: number;
24
+ end: number;
25
+ }
26
+ export interface ImageInputResolution {
27
+ actualInput: string | ContentPart[];
28
+ displayInput: string;
29
+ errors: string[];
30
+ attachments: ImageAttachment[];
31
+ imagePathCount: number;
32
+ }
33
+ export interface LabeledImageAttachment extends ImageAttachment {
34
+ label: string;
35
+ }
36
+ export interface ComposerImageResolution {
37
+ text: string;
38
+ attachments: LabeledImageAttachment[];
39
+ errors: string[];
40
+ imagePathCount: number;
41
+ nextLabelIndex: number;
42
+ }
43
+ export declare function isImageFilePath(raw: string): boolean;
44
+ export declare function extractImagePathTokens(input: string): ImagePathToken[];
45
+ export declare function removeImagePathTokens(input: string, tokens: ImagePathToken[]): string;
46
+ export declare function imageAttachmentLabel(att: ImageAttachment, index: number): string;
47
+ export declare function imageAttachmentReference(att: ImageAttachment, index: number): string;
48
+ export declare function imageAttachmentLabelPattern(): RegExp;
49
+ export declare function buildImageContentParts(promptText: string, attachments: ImageAttachment[]): ContentPart[];
50
+ export declare function formatImageDisplayInput(promptText: string, attachments: ImageAttachment[], labelStart?: number): string;
51
+ export declare function buildImageContentPartsFromLabels(input: string, attachmentsByLabel: Map<string, ImageAttachment>): {
52
+ actualInput?: ContentPart[];
53
+ displayInput: string;
54
+ usedLabels: string[];
55
+ };
56
+ /**
57
+ * Split a pasted blob into candidate path tokens.
58
+ *
59
+ * Multi-drag from Finder delivers a mix of newline- and space-separated
60
+ * absolute paths. Spaces inside a single path are escaped (`\ `) — we split
61
+ * only on a space that is followed by the start of a new absolute path.
62
+ */
63
+ export declare function splitPastedPaths(pasted: string): string[];
64
+ export declare function readImageFromPath(rawPath: string): Promise<ImageAttachment | null>;
65
+ /** macOS screenshot shortcut writes to these paths and they may be auto-cleaned. */
66
+ export declare function isScreenshotTempPath(s: string): boolean;
67
+ export declare function getImageFromClipboard(): Promise<ImageAttachment | null>;
68
+ /**
69
+ * If the image is close to the API size cap, try to downscale it in place.
70
+ * Uses the OS-native tools that are typically available:
71
+ * - macOS: `sips` (always present)
72
+ * - linux: ImageMagick `convert` (if installed)
73
+ * Returns the original attachment if resize isn't needed or can't run.
74
+ */
75
+ export declare function maybeResizeImage(att: ImageAttachment): Promise<ImageAttachment>;
76
+ export interface ValidationResult {
77
+ ok: boolean;
78
+ reason?: string;
79
+ }
80
+ export declare function validateImageSize(att: ImageAttachment): ValidationResult;
81
+ /** End-to-end: given a file path, read -> resize-if-needed -> validate. */
82
+ export declare function ingestImagePath(p: string): Promise<{
83
+ attachment?: ImageAttachment;
84
+ error?: string;
85
+ }>;
86
+ export declare function ingestClipboardImage(): Promise<{
87
+ attachment?: ImageAttachment;
88
+ error?: string;
89
+ }>;
90
+ export declare function resolveImageInput(input: string, options?: {
91
+ labelStart?: number;
92
+ }): Promise<ImageInputResolution>;
93
+ export declare function resolveComposerImagePaths(input: string, options?: {
94
+ labelStart?: number;
95
+ }): Promise<ComposerImageResolution>;
@@ -0,0 +1,505 @@
1
+ /**
2
+ * Image paste utilities: path detection, file reading, clipboard access, and size-capping.
3
+ *
4
+ * Terminals don't forward image bytes to stdin. Paths arrive as text when users
5
+ * drag files in; Cmd+V of an image produces an empty paste (we probe the
6
+ * clipboard). macOS screenshot shortcut (Cmd+Shift+Ctrl+4) writes to both a
7
+ * TemporaryItems path and the clipboard — the path often gets cleaned up before
8
+ * we can read it, so we fall back to the clipboard.
9
+ */
10
+ import { execFile } from "node:child_process";
11
+ import fs from "node:fs/promises";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ import { promisify } from "node:util";
15
+ const execFileAsync = promisify(execFile);
16
+ const IMAGE_EXT = /\.(png|jpe?g|gif|webp|bmp)$/i;
17
+ const IMAGE_EXT_SOURCE = String.raw `(?:png|jpe?g|gif|webp|bmp)`;
18
+ // Anthropic/OpenAI image uploads cap at ~5MB base64. We target a bit below so
19
+ // the base64 inflation (4/3) doesn't push us over.
20
+ const MAX_BASE64_BYTES = 5 * 1024 * 1024;
21
+ const RESIZE_TRIGGER_BYTES = Math.floor(MAX_BASE64_BYTES * 0.95);
22
+ // Target max dimension for auto-resize.
23
+ const RESIZE_MAX_DIM = 2048;
24
+ export function isImageFilePath(raw) {
25
+ const s = raw.trim();
26
+ if (!s)
27
+ return false;
28
+ if (!IMAGE_EXT.test(s))
29
+ return false;
30
+ // Require an absolute or home-relative path. Pasted arbitrary text shouldn't
31
+ // be treated as a path.
32
+ return path.isAbsolute(s) || s.startsWith("~") || /^[A-Za-z]:\\/.test(s);
33
+ }
34
+ export function extractImagePathTokens(input) {
35
+ const pattern = new RegExp(String.raw `(^|\s)(?:"([^"]+\.${IMAGE_EXT_SOURCE})"|'([^']+\.${IMAGE_EXT_SOURCE})'|((?:~|\/|[A-Za-z]:\\)(?:\\ |[^\s"'<>])+\.${IMAGE_EXT_SOURCE}))(?=$|\s)`, "gi");
36
+ const tokens = [];
37
+ for (const match of input.matchAll(pattern)) {
38
+ const leading = match[1] ?? "";
39
+ const rawPath = match[2] ?? match[3] ?? match[4];
40
+ if (!rawPath || !isImageFilePath(rawPath))
41
+ continue;
42
+ const start = (match.index ?? 0) + leading.length;
43
+ const end = (match.index ?? 0) + match[0].length;
44
+ tokens.push({ rawPath, start, end });
45
+ }
46
+ return tokens;
47
+ }
48
+ export function removeImagePathTokens(input, tokens) {
49
+ if (tokens.length === 0)
50
+ return input.trim();
51
+ let out = "";
52
+ let cursor = 0;
53
+ for (const token of tokens) {
54
+ out += input.slice(cursor, token.start);
55
+ out += " ";
56
+ cursor = token.end;
57
+ }
58
+ out += input.slice(cursor);
59
+ return out
60
+ .replace(/[ \t]+/g, " ")
61
+ .replace(/ *\n */g, "\n")
62
+ .replace(/\n{3,}/g, "\n\n")
63
+ .trim();
64
+ }
65
+ export function imageAttachmentLabel(att, index) {
66
+ return `image#${index}${imageExtension(att)}`;
67
+ }
68
+ export function imageAttachmentReference(att, index) {
69
+ return `[${imageAttachmentLabel(att, index)}]`;
70
+ }
71
+ export function imageAttachmentLabelPattern() {
72
+ return /\[image#(\d+)\.[^\]\s]+\]/g;
73
+ }
74
+ function defaultImagePrompt(count) {
75
+ return count === 1
76
+ ? "Please analyze the attached image."
77
+ : "Please analyze the attached images.";
78
+ }
79
+ function imageExtension(att) {
80
+ const fromPath = path.extname(att.filename ?? att.sourcePath ?? "").toLowerCase();
81
+ if (fromPath)
82
+ return fromPath;
83
+ if (att.mediaType === "image/jpeg")
84
+ return ".jpg";
85
+ if (att.mediaType === "image/webp")
86
+ return ".webp";
87
+ if (att.mediaType === "image/gif")
88
+ return ".gif";
89
+ if (att.mediaType === "image/bmp")
90
+ return ".bmp";
91
+ return ".png";
92
+ }
93
+ export function buildImageContentParts(promptText, attachments) {
94
+ const text = promptText.trim() || defaultImagePrompt(attachments.length);
95
+ return [
96
+ { type: "text", text },
97
+ ...attachments.map((attachment) => ({
98
+ type: "image_url",
99
+ image_url: { url: attachment.dataUrl },
100
+ })),
101
+ ];
102
+ }
103
+ export function formatImageDisplayInput(promptText, attachments, labelStart = 1) {
104
+ const text = promptText.trim() || defaultImagePrompt(attachments.length);
105
+ const imageLines = attachments.map((attachment, index) => imageAttachmentReference(attachment, labelStart + index));
106
+ return `${text}\n${imageLines.join("\n")}`;
107
+ }
108
+ export function buildImageContentPartsFromLabels(input, attachmentsByLabel) {
109
+ const matches = Array.from(input.matchAll(imageAttachmentLabelPattern()));
110
+ const usedLabels = [];
111
+ const parts = [];
112
+ let cursor = 0;
113
+ for (const match of matches) {
114
+ const label = match[0].slice(1, -1);
115
+ const attachment = attachmentsByLabel.get(label);
116
+ if (!attachment)
117
+ continue;
118
+ const start = match.index ?? 0;
119
+ const before = input.slice(cursor, start).trim();
120
+ if (before)
121
+ parts.push({ type: "text", text: before });
122
+ parts.push({ type: "image_url", image_url: { url: attachment.dataUrl } });
123
+ usedLabels.push(label);
124
+ cursor = start + match[0].length;
125
+ }
126
+ if (usedLabels.length === 0)
127
+ return { displayInput: input, usedLabels: [] };
128
+ const rest = input.slice(cursor).trim();
129
+ if (rest)
130
+ parts.push({ type: "text", text: rest });
131
+ if (!parts.some((part) => part.type === "text")) {
132
+ parts.unshift({ type: "text", text: defaultImagePrompt(usedLabels.length) });
133
+ }
134
+ return {
135
+ actualInput: parts,
136
+ displayInput: input.trim() || usedLabels.map((label) => `[${label}]`).join("\n"),
137
+ usedLabels,
138
+ };
139
+ }
140
+ /**
141
+ * Split a pasted blob into candidate path tokens.
142
+ *
143
+ * Multi-drag from Finder delivers a mix of newline- and space-separated
144
+ * absolute paths. Spaces inside a single path are escaped (`\ `) — we split
145
+ * only on a space that is followed by the start of a new absolute path.
146
+ */
147
+ export function splitPastedPaths(pasted) {
148
+ const out = [];
149
+ for (const line of pasted.split(/\r?\n/)) {
150
+ for (const piece of line.split(/ (?=\/|[A-Za-z]:\\)/)) {
151
+ const t = piece.trim();
152
+ if (t)
153
+ out.push(t);
154
+ }
155
+ }
156
+ return out;
157
+ }
158
+ function mediaTypeFromExt(p) {
159
+ const ext = path.extname(p).toLowerCase();
160
+ if (ext === ".jpg" || ext === ".jpeg")
161
+ return "image/jpeg";
162
+ if (ext === ".gif")
163
+ return "image/gif";
164
+ if (ext === ".webp")
165
+ return "image/webp";
166
+ if (ext === ".bmp")
167
+ return "image/bmp";
168
+ return "image/png";
169
+ }
170
+ function resolveHome(p) {
171
+ if (p.startsWith("~/") || p === "~") {
172
+ return path.join(os.homedir(), p.slice(1));
173
+ }
174
+ return p;
175
+ }
176
+ function unescapeShell(p) {
177
+ return p.replace(/\\ /g, " ");
178
+ }
179
+ function attachmentFromBuffer(buffer, mediaType, meta = {}) {
180
+ const base64 = buffer.toString("base64");
181
+ return {
182
+ base64,
183
+ mediaType,
184
+ bytes: buffer.length,
185
+ dataUrl: `data:${mediaType};base64,${base64}`,
186
+ filename: meta.filename,
187
+ sourcePath: meta.sourcePath,
188
+ };
189
+ }
190
+ export async function readImageFromPath(rawPath) {
191
+ const resolved = resolveHome(unescapeShell(rawPath.trim()));
192
+ try {
193
+ const stat = await fs.stat(resolved);
194
+ if (!stat.isFile())
195
+ return null;
196
+ const buffer = await fs.readFile(resolved);
197
+ return attachmentFromBuffer(buffer, mediaTypeFromExt(resolved), {
198
+ filename: path.basename(resolved),
199
+ sourcePath: resolved,
200
+ });
201
+ }
202
+ catch {
203
+ return null;
204
+ }
205
+ }
206
+ /** macOS screenshot shortcut writes to these paths and they may be auto-cleaned. */
207
+ export function isScreenshotTempPath(s) {
208
+ return /\/TemporaryItems\/.*screencaptureui.*\/Screenshot/i.test(s);
209
+ }
210
+ export async function getImageFromClipboard() {
211
+ switch (process.platform) {
212
+ case "darwin":
213
+ return getClipboardImageDarwin();
214
+ case "linux":
215
+ return getClipboardImageLinux();
216
+ case "win32":
217
+ return getClipboardImageWindows();
218
+ default:
219
+ return null;
220
+ }
221
+ }
222
+ async function getClipboardImageDarwin() {
223
+ // Probe first — `as «class PNGf»` throws if clipboard has no image.
224
+ try {
225
+ await execFileAsync("osascript", ["-e", "the clipboard as «class PNGf»"], {
226
+ timeout: 5000,
227
+ });
228
+ }
229
+ catch {
230
+ return null;
231
+ }
232
+ const tmp = path.join(os.tmpdir(), `bubble_clip_${Date.now()}_${process.pid}.png`);
233
+ const script = `set png_data to (the clipboard as «class PNGf»)\n` +
234
+ `set fp to open for access POSIX file "${tmp}" with write permission\n` +
235
+ `write png_data to fp\n` +
236
+ `close access fp`;
237
+ try {
238
+ await execFileAsync("osascript", ["-e", script], { timeout: 5000 });
239
+ const buf = await fs.readFile(tmp);
240
+ return attachmentFromBuffer(buf, "image/png");
241
+ }
242
+ catch {
243
+ return null;
244
+ }
245
+ finally {
246
+ await fs.unlink(tmp).catch(() => undefined);
247
+ }
248
+ }
249
+ async function getClipboardImageLinux() {
250
+ const candidates = [
251
+ ["xclip", ["-selection", "clipboard", "-t", "image/png", "-o"]],
252
+ ["wl-paste", ["--type", "image/png"]],
253
+ ];
254
+ for (const [cmd, args] of candidates) {
255
+ try {
256
+ // encoding: "buffer" makes stdout a Buffer instead of a string so PNG
257
+ // bytes survive without UTF-8 mangling.
258
+ const result = await execFileAsync(cmd, args, {
259
+ timeout: 5000,
260
+ encoding: "buffer",
261
+ });
262
+ const buf = result.stdout;
263
+ if (buf && buf.length > 0) {
264
+ return attachmentFromBuffer(buf, "image/png");
265
+ }
266
+ }
267
+ catch {
268
+ continue;
269
+ }
270
+ }
271
+ return null;
272
+ }
273
+ async function getClipboardImageWindows() {
274
+ const tmp = path.join(os.tmpdir(), `bubble_clip_${Date.now()}_${process.pid}.png`);
275
+ const tmpPs = tmp.replace(/\\/g, "\\\\");
276
+ const script = `Add-Type -AssemblyName System.Drawing; ` +
277
+ `$img = Get-Clipboard -Format Image; ` +
278
+ `if ($img) { $img.Save('${tmpPs}', [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'OK' } ` +
279
+ `else { Write-Output 'NONE' }`;
280
+ try {
281
+ const result = await execFileAsync("powershell", ["-NoProfile", "-Command", script], { timeout: 5000 });
282
+ if (!String(result.stdout).includes("OK"))
283
+ return null;
284
+ const buf = await fs.readFile(tmp);
285
+ return attachmentFromBuffer(buf, "image/png");
286
+ }
287
+ catch {
288
+ return null;
289
+ }
290
+ finally {
291
+ await fs.unlink(tmp).catch(() => undefined);
292
+ }
293
+ }
294
+ async function which(cmd) {
295
+ try {
296
+ await execFileAsync(process.platform === "win32" ? "where" : "which", [cmd], {
297
+ timeout: 1500,
298
+ });
299
+ return true;
300
+ }
301
+ catch {
302
+ return false;
303
+ }
304
+ }
305
+ /**
306
+ * If the image is close to the API size cap, try to downscale it in place.
307
+ * Uses the OS-native tools that are typically available:
308
+ * - macOS: `sips` (always present)
309
+ * - linux: ImageMagick `convert` (if installed)
310
+ * Returns the original attachment if resize isn't needed or can't run.
311
+ */
312
+ export async function maybeResizeImage(att) {
313
+ if (att.base64.length < RESIZE_TRIGGER_BYTES)
314
+ return att;
315
+ const tmpDir = os.tmpdir();
316
+ const stamp = `${Date.now()}_${process.pid}`;
317
+ const inExt = path.extname(att.filename ?? att.sourcePath ?? `.png`).toLowerCase() || ".png";
318
+ const tmpIn = path.join(tmpDir, `bubble_img_in_${stamp}${inExt}`);
319
+ const tmpOut = path.join(tmpDir, `bubble_img_out_${stamp}.jpg`);
320
+ try {
321
+ await fs.writeFile(tmpIn, Buffer.from(att.base64, "base64"));
322
+ let ok = false;
323
+ if (process.platform === "darwin") {
324
+ try {
325
+ await execFileAsync("sips", ["-Z", String(RESIZE_MAX_DIM), "-s", "format", "jpeg", "-s", "formatOptions", "80", tmpIn, "--out", tmpOut], { timeout: 10000 });
326
+ ok = true;
327
+ }
328
+ catch {
329
+ ok = false;
330
+ }
331
+ }
332
+ else if (await which("convert")) {
333
+ try {
334
+ await execFileAsync("convert", [tmpIn, "-resize", `${RESIZE_MAX_DIM}x${RESIZE_MAX_DIM}>`, "-quality", "80", tmpOut], { timeout: 10000 });
335
+ ok = true;
336
+ }
337
+ catch {
338
+ ok = false;
339
+ }
340
+ }
341
+ if (!ok)
342
+ return att;
343
+ const resized = await fs.readFile(tmpOut);
344
+ if (resized.length >= att.bytes)
345
+ return att;
346
+ return attachmentFromBuffer(resized, "image/jpeg", {
347
+ filename: att.filename,
348
+ sourcePath: att.sourcePath,
349
+ });
350
+ }
351
+ catch {
352
+ return att;
353
+ }
354
+ finally {
355
+ await fs.unlink(tmpIn).catch(() => undefined);
356
+ await fs.unlink(tmpOut).catch(() => undefined);
357
+ }
358
+ }
359
+ export function validateImageSize(att) {
360
+ if (att.base64.length > MAX_BASE64_BYTES) {
361
+ const kb = Math.round(att.base64.length / 1024);
362
+ const max = Math.round(MAX_BASE64_BYTES / 1024);
363
+ const hint = process.platform === "darwin"
364
+ ? " (install/confirm `sips` on PATH to auto-resize)"
365
+ : process.platform === "linux"
366
+ ? " (install ImageMagick `convert` to auto-resize)"
367
+ : "";
368
+ return {
369
+ ok: false,
370
+ reason: `image base64 is ${kb}KB, exceeds ${max}KB API cap${hint}`,
371
+ };
372
+ }
373
+ return { ok: true };
374
+ }
375
+ /** End-to-end: given a file path, read -> resize-if-needed -> validate. */
376
+ export async function ingestImagePath(p) {
377
+ const raw = await readImageFromPath(p);
378
+ if (!raw)
379
+ return { error: `cannot read image at ${p}` };
380
+ const sized = await maybeResizeImage(raw);
381
+ const validation = validateImageSize(sized);
382
+ if (!validation.ok)
383
+ return { error: validation.reason };
384
+ return { attachment: sized };
385
+ }
386
+ export async function ingestClipboardImage() {
387
+ const raw = await getImageFromClipboard();
388
+ if (!raw)
389
+ return { error: "clipboard has no image" };
390
+ const sized = await maybeResizeImage(raw);
391
+ const validation = validateImageSize(sized);
392
+ if (!validation.ok)
393
+ return { error: validation.reason };
394
+ return { attachment: sized };
395
+ }
396
+ export async function resolveImageInput(input, options = {}) {
397
+ const tokens = extractImagePathTokens(input);
398
+ if (tokens.length === 0) {
399
+ return {
400
+ actualInput: input,
401
+ displayInput: input,
402
+ errors: [],
403
+ attachments: [],
404
+ imagePathCount: 0,
405
+ };
406
+ }
407
+ const attachments = [];
408
+ const errors = [];
409
+ const attachmentsByToken = new Map();
410
+ let nextLabelIndex = options.labelStart ?? 1;
411
+ for (const token of tokens) {
412
+ const result = await ingestImagePath(token.rawPath);
413
+ if (result.attachment) {
414
+ attachments.push(result.attachment);
415
+ attachmentsByToken.set(token, {
416
+ attachment: result.attachment,
417
+ label: imageAttachmentLabel(result.attachment, nextLabelIndex++),
418
+ });
419
+ }
420
+ else {
421
+ errors.push(`${token.rawPath}: ${result.error ?? "could not attach image"}`);
422
+ }
423
+ }
424
+ if (attachments.length === 0) {
425
+ return {
426
+ actualInput: input,
427
+ displayInput: input,
428
+ errors,
429
+ attachments: [],
430
+ imagePathCount: tokens.length,
431
+ };
432
+ }
433
+ const parts = [];
434
+ let displayInput = "";
435
+ let cursor = 0;
436
+ for (const token of tokens) {
437
+ const entry = attachmentsByToken.get(token);
438
+ if (!entry)
439
+ continue;
440
+ const before = input.slice(cursor, token.start);
441
+ displayInput += before;
442
+ const text = before.trim();
443
+ if (text)
444
+ parts.push({ type: "text", text });
445
+ parts.push({ type: "image_url", image_url: { url: entry.attachment.dataUrl } });
446
+ displayInput += `[${entry.label}]`;
447
+ cursor = token.end;
448
+ }
449
+ const rest = input.slice(cursor);
450
+ displayInput += rest;
451
+ const restText = rest.trim();
452
+ if (restText)
453
+ parts.push({ type: "text", text: restText });
454
+ if (!parts.some((part) => part.type === "text")) {
455
+ parts.unshift({ type: "text", text: defaultImagePrompt(attachments.length) });
456
+ }
457
+ return {
458
+ actualInput: parts,
459
+ displayInput: displayInput.trim(),
460
+ errors,
461
+ attachments,
462
+ imagePathCount: tokens.length,
463
+ };
464
+ }
465
+ export async function resolveComposerImagePaths(input, options = {}) {
466
+ const tokens = extractImagePathTokens(input);
467
+ let nextLabelIndex = options.labelStart ?? 1;
468
+ if (tokens.length === 0) {
469
+ return {
470
+ text: input,
471
+ attachments: [],
472
+ errors: [],
473
+ imagePathCount: 0,
474
+ nextLabelIndex,
475
+ };
476
+ }
477
+ const errors = [];
478
+ const attachments = [];
479
+ const replacements = new Map();
480
+ for (const token of tokens) {
481
+ const result = await ingestImagePath(token.rawPath);
482
+ if (!result.attachment) {
483
+ errors.push(`${token.rawPath}: ${result.error ?? "could not attach image"}`);
484
+ continue;
485
+ }
486
+ const label = imageAttachmentLabel(result.attachment, nextLabelIndex++);
487
+ attachments.push({ ...result.attachment, label });
488
+ replacements.set(token, `[${label}]`);
489
+ }
490
+ let text = "";
491
+ let cursor = 0;
492
+ for (const token of tokens) {
493
+ text += input.slice(cursor, token.start);
494
+ text += replacements.get(token) ?? input.slice(token.start, token.end);
495
+ cursor = token.end;
496
+ }
497
+ text += input.slice(cursor);
498
+ return {
499
+ text,
500
+ attachments,
501
+ errors,
502
+ imagePathCount: tokens.length,
503
+ nextLabelIndex,
504
+ };
505
+ }