@travisennis/acai 0.0.1
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.
- package/.acai/acai.json +9 -0
- package/.acai/prompts/add-openrouter-model.md +13 -0
- package/.acai/prompts/project-status.md +4 -0
- package/.acai/prompts/update-architecture-document.md +9 -0
- package/.acai/rules/learned-rules.md +9 -0
- package/.ai/docs/available-tools.txt +3 -0
- package/.ai/docs/cognitive_complexity_refactoring_progress.md +65 -0
- package/.ai/docs/deleted_tools.md +168 -0
- package/.ai/docs/deleted_tools_88ced9ef.md +56 -0
- package/.ai/docs/image-pasting.md +46 -0
- package/.ai/docs/initialize-app.md +117 -0
- package/.ai/docs/issue-4-plan.md +44 -0
- package/.ai/docs/marked-renderer-debug.md +15 -0
- package/.ai/docs/marked-renderer-refactor-plan.md +64 -0
- package/.ai/docs/memory-use-cases.md +55 -0
- package/.ai/docs/prompt-consistency.md +31 -0
- package/.ai/docs/refactoring-tools.md +98 -0
- package/.ai/docs/system-prompt-update.md +174 -0
- package/.ai/docs/system_prompt.txt +210 -0
- package/.ai/docs/tasks.md +49 -0
- package/.ai/plan.md +131 -0
- package/.ai/prompt.md +1 -0
- package/.ai/scripts/fetch_models.js +27 -0
- package/.ai/scripts/generateSystemPrompt.ts +15 -0
- package/.ai/scripts/list-tools.mjs +4 -0
- package/.ai/scripts/p5_geometric_shapes.js +149 -0
- package/.husky/commit-msg +1 -0
- package/.husky/pre-commit +3 -0
- package/.husky/pre-push +1 -0
- package/.ignore +4 -0
- package/AGENTS.md +25 -0
- package/ARCHITECTURE.md +304 -0
- package/LICENSE +21 -0
- package/README.md +392 -0
- package/TODO.md +2 -0
- package/biome.json +61 -0
- package/commitlint.config.js +3 -0
- package/dist/cli.d.ts +19 -0
- package/dist/cli.js +116 -0
- package/dist/commands/application-log-command.d.ts +2 -0
- package/dist/commands/application-log-command.js +43 -0
- package/dist/commands/clear-command.d.ts +2 -0
- package/dist/commands/clear-command.js +12 -0
- package/dist/commands/compact-command.d.ts +2 -0
- package/dist/commands/compact-command.js +51 -0
- package/dist/commands/copy-command.d.ts +2 -0
- package/dist/commands/copy-command.js +51 -0
- package/dist/commands/edit-command.d.ts +2 -0
- package/dist/commands/edit-command.js +53 -0
- package/dist/commands/edit-prompt-command.d.ts +2 -0
- package/dist/commands/edit-prompt-command.js +25 -0
- package/dist/commands/exit-command.d.ts +2 -0
- package/dist/commands/exit-command.js +14 -0
- package/dist/commands/files-command.d.ts +2 -0
- package/dist/commands/files-command.js +63 -0
- package/dist/commands/generate-rules-command.d.ts +2 -0
- package/dist/commands/generate-rules-command.js +61 -0
- package/dist/commands/help-command.d.ts +2 -0
- package/dist/commands/help-command.js +19 -0
- package/dist/commands/init-command.d.ts +2 -0
- package/dist/commands/init-command.js +40 -0
- package/dist/commands/last-log-command.d.ts +2 -0
- package/dist/commands/last-log-command.js +76 -0
- package/dist/commands/manager.d.ts +22 -0
- package/dist/commands/manager.js +123 -0
- package/dist/commands/model-command.d.ts +2 -0
- package/dist/commands/model-command.js +84 -0
- package/dist/commands/paste-command.d.ts +2 -0
- package/dist/commands/paste-command.js +40 -0
- package/dist/commands/prompt-command.d.ts +2 -0
- package/dist/commands/prompt-command.js +111 -0
- package/dist/commands/reset-command.d.ts +2 -0
- package/dist/commands/reset-command.js +16 -0
- package/dist/commands/rules-command.d.ts +2 -0
- package/dist/commands/rules-command.js +68 -0
- package/dist/commands/save-command.d.ts +2 -0
- package/dist/commands/save-command.js +14 -0
- package/dist/commands/types.d.ts +26 -0
- package/dist/commands/types.js +1 -0
- package/dist/commands/usage-command.d.ts +2 -0
- package/dist/commands/usage-command.js +21 -0
- package/dist/config.d.ts +60 -0
- package/dist/config.js +193 -0
- package/dist/conversation-analyzer.d.ts +10 -0
- package/dist/conversation-analyzer.js +88 -0
- package/dist/dedent.d.ts +3 -0
- package/dist/dedent.js +38 -0
- package/dist/formatting.d.ts +17 -0
- package/dist/formatting.js +103 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +213 -0
- package/dist/logger.d.ts +2 -0
- package/dist/logger.js +24 -0
- package/dist/mentions.d.ts +9 -0
- package/dist/mentions.js +182 -0
- package/dist/messages.d.ts +69 -0
- package/dist/messages.js +261 -0
- package/dist/middleware/audit-message.d.ts +5 -0
- package/dist/middleware/audit-message.js +95 -0
- package/dist/middleware/index.d.ts +2 -0
- package/dist/middleware/index.js +2 -0
- package/dist/middleware/rate-limit.d.ts +4 -0
- package/dist/middleware/rate-limit.js +17 -0
- package/dist/models/ai-config.d.ts +12 -0
- package/dist/models/ai-config.js +87 -0
- package/dist/models/anthropic-provider.d.ts +25 -0
- package/dist/models/anthropic-provider.js +184 -0
- package/dist/models/deepseek-provider.d.ts +20 -0
- package/dist/models/deepseek-provider.js +42 -0
- package/dist/models/google-provider.d.ts +19 -0
- package/dist/models/google-provider.js +56 -0
- package/dist/models/manager.d.ts +15 -0
- package/dist/models/manager.js +48 -0
- package/dist/models/openai-provider.d.ts +22 -0
- package/dist/models/openai-provider.js +70 -0
- package/dist/models/openrouter-provider.d.ts +36 -0
- package/dist/models/openrouter-provider.js +276 -0
- package/dist/models/providers.d.ts +33 -0
- package/dist/models/providers.js +116 -0
- package/dist/models/xai-provider.d.ts +20 -0
- package/dist/models/xai-provider.js +47 -0
- package/dist/parsing.d.ts +2 -0
- package/dist/parsing.js +18 -0
- package/dist/prompts/manager.d.ts +19 -0
- package/dist/prompts/manager.js +71 -0
- package/dist/prompts.d.ts +4 -0
- package/dist/prompts.js +158 -0
- package/dist/repl-prompt.d.ts +14 -0
- package/dist/repl-prompt.js +147 -0
- package/dist/repl.d.ts +27 -0
- package/dist/repl.js +431 -0
- package/dist/source/cli.d.ts +19 -0
- package/dist/source/cli.js +116 -0
- package/dist/source/commands/application-log-command.d.ts +2 -0
- package/dist/source/commands/application-log-command.js +43 -0
- package/dist/source/commands/clear-command.d.ts +2 -0
- package/dist/source/commands/clear-command.js +12 -0
- package/dist/source/commands/compact-command.d.ts +2 -0
- package/dist/source/commands/compact-command.js +51 -0
- package/dist/source/commands/copy-command.d.ts +2 -0
- package/dist/source/commands/copy-command.js +51 -0
- package/dist/source/commands/edit-command.d.ts +2 -0
- package/dist/source/commands/edit-command.js +53 -0
- package/dist/source/commands/edit-prompt-command.d.ts +2 -0
- package/dist/source/commands/edit-prompt-command.js +25 -0
- package/dist/source/commands/exit-command.d.ts +2 -0
- package/dist/source/commands/exit-command.js +14 -0
- package/dist/source/commands/files-command.d.ts +2 -0
- package/dist/source/commands/files-command.js +63 -0
- package/dist/source/commands/generate-rules-command.d.ts +2 -0
- package/dist/source/commands/generate-rules-command.js +61 -0
- package/dist/source/commands/help-command.d.ts +2 -0
- package/dist/source/commands/help-command.js +19 -0
- package/dist/source/commands/init-command.d.ts +2 -0
- package/dist/source/commands/init-command.js +40 -0
- package/dist/source/commands/last-log-command.d.ts +2 -0
- package/dist/source/commands/last-log-command.js +76 -0
- package/dist/source/commands/manager.d.ts +22 -0
- package/dist/source/commands/manager.js +123 -0
- package/dist/source/commands/model-command.d.ts +2 -0
- package/dist/source/commands/model-command.js +84 -0
- package/dist/source/commands/paste-command.d.ts +2 -0
- package/dist/source/commands/paste-command.js +40 -0
- package/dist/source/commands/prompt-command.d.ts +2 -0
- package/dist/source/commands/prompt-command.js +111 -0
- package/dist/source/commands/reset-command.d.ts +2 -0
- package/dist/source/commands/reset-command.js +16 -0
- package/dist/source/commands/rules-command.d.ts +2 -0
- package/dist/source/commands/rules-command.js +68 -0
- package/dist/source/commands/save-command.d.ts +2 -0
- package/dist/source/commands/save-command.js +14 -0
- package/dist/source/commands/types.d.ts +26 -0
- package/dist/source/commands/types.js +1 -0
- package/dist/source/commands/usage-command.d.ts +2 -0
- package/dist/source/commands/usage-command.js +21 -0
- package/dist/source/config.d.ts +60 -0
- package/dist/source/config.js +193 -0
- package/dist/source/conversation-analyzer.d.ts +10 -0
- package/dist/source/conversation-analyzer.js +88 -0
- package/dist/source/dedent.d.ts +3 -0
- package/dist/source/dedent.js +38 -0
- package/dist/source/formatting.d.ts +17 -0
- package/dist/source/formatting.js +103 -0
- package/dist/source/index.d.ts +18 -0
- package/dist/source/index.js +213 -0
- package/dist/source/logger.d.ts +2 -0
- package/dist/source/logger.js +24 -0
- package/dist/source/mentions.d.ts +9 -0
- package/dist/source/mentions.js +182 -0
- package/dist/source/messages.d.ts +69 -0
- package/dist/source/messages.js +261 -0
- package/dist/source/middleware/audit-message.d.ts +5 -0
- package/dist/source/middleware/audit-message.js +95 -0
- package/dist/source/middleware/index.d.ts +2 -0
- package/dist/source/middleware/index.js +2 -0
- package/dist/source/middleware/rate-limit.d.ts +4 -0
- package/dist/source/middleware/rate-limit.js +17 -0
- package/dist/source/models/ai-config.d.ts +12 -0
- package/dist/source/models/ai-config.js +87 -0
- package/dist/source/models/anthropic-provider.d.ts +25 -0
- package/dist/source/models/anthropic-provider.js +184 -0
- package/dist/source/models/deepseek-provider.d.ts +20 -0
- package/dist/source/models/deepseek-provider.js +42 -0
- package/dist/source/models/google-provider.d.ts +19 -0
- package/dist/source/models/google-provider.js +56 -0
- package/dist/source/models/manager.d.ts +15 -0
- package/dist/source/models/manager.js +48 -0
- package/dist/source/models/openai-provider.d.ts +22 -0
- package/dist/source/models/openai-provider.js +70 -0
- package/dist/source/models/openrouter-provider.d.ts +36 -0
- package/dist/source/models/openrouter-provider.js +276 -0
- package/dist/source/models/providers.d.ts +33 -0
- package/dist/source/models/providers.js +116 -0
- package/dist/source/models/xai-provider.d.ts +20 -0
- package/dist/source/models/xai-provider.js +47 -0
- package/dist/source/parsing.d.ts +2 -0
- package/dist/source/parsing.js +18 -0
- package/dist/source/prompts/manager.d.ts +19 -0
- package/dist/source/prompts/manager.js +71 -0
- package/dist/source/prompts.d.ts +4 -0
- package/dist/source/prompts.js +158 -0
- package/dist/source/repl-prompt.d.ts +14 -0
- package/dist/source/repl-prompt.js +147 -0
- package/dist/source/repl.d.ts +27 -0
- package/dist/source/repl.js +431 -0
- package/dist/source/terminal/formatting.d.ts +37 -0
- package/dist/source/terminal/formatting.js +106 -0
- package/dist/source/terminal/index.d.ts +94 -0
- package/dist/source/terminal/index.js +420 -0
- package/dist/source/terminal/markdown-utils.d.ts +2 -0
- package/dist/source/terminal/markdown-utils.js +81 -0
- package/dist/source/terminal/markdown.d.ts +1 -0
- package/dist/source/terminal/markdown.js +111 -0
- package/dist/source/terminal/types.d.ts +71 -0
- package/dist/source/terminal/types.js +1 -0
- package/dist/source/terminal-output.d.ts +8 -0
- package/dist/source/terminal-output.js +213 -0
- package/dist/source/terminal-output.test.d.ts +8 -0
- package/dist/source/terminal-output.test.js +213 -0
- package/dist/source/token-tracker.d.ts +14 -0
- package/dist/source/token-tracker.js +53 -0
- package/dist/source/token-utils.d.ts +7 -0
- package/dist/source/token-utils.js +13 -0
- package/dist/source/tools/agent.d.ts +17 -0
- package/dist/source/tools/agent.js +87 -0
- package/dist/source/tools/bash.d.ts +19 -0
- package/dist/source/tools/bash.js +294 -0
- package/dist/source/tools/code-interpreter.d.ts +12 -0
- package/dist/source/tools/code-interpreter.js +131 -0
- package/dist/source/tools/command-validation.d.ts +8 -0
- package/dist/source/tools/command-validation.js +69 -0
- package/dist/source/tools/delete-file.d.ts +12 -0
- package/dist/source/tools/delete-file.js +56 -0
- package/dist/source/tools/directory-tree.d.ts +12 -0
- package/dist/source/tools/directory-tree.js +38 -0
- package/dist/source/tools/edit-file.d.ts +19 -0
- package/dist/source/tools/edit-file.js +107 -0
- package/dist/source/tools/filesystem-utils.d.ts +22 -0
- package/dist/source/tools/filesystem-utils.js +191 -0
- package/dist/source/tools/git-utils.d.ts +14 -0
- package/dist/source/tools/git-utils.js +64 -0
- package/dist/source/tools/grep.d.ts +17 -0
- package/dist/source/tools/grep.js +138 -0
- package/dist/source/tools/index.d.ts +161 -0
- package/dist/source/tools/index.js +209 -0
- package/dist/source/tools/memory-read.d.ts +13 -0
- package/dist/source/tools/memory-read.js +135 -0
- package/dist/source/tools/memory-write.d.ts +12 -0
- package/dist/source/tools/memory-write.js +83 -0
- package/dist/source/tools/move-file.d.ts +13 -0
- package/dist/source/tools/move-file.js +44 -0
- package/dist/source/tools/read-file.d.ts +17 -0
- package/dist/source/tools/read-file.js +86 -0
- package/dist/source/tools/read-multiple-files.d.ts +14 -0
- package/dist/source/tools/read-multiple-files.js +55 -0
- package/dist/source/tools/save-file.d.ts +17 -0
- package/dist/source/tools/save-file.js +98 -0
- package/dist/source/tools/think.d.ts +11 -0
- package/dist/source/tools/think.js +45 -0
- package/dist/source/tools/types.d.ts +29 -0
- package/dist/source/tools/types.js +14 -0
- package/dist/source/tools/web-fetch.d.ts +47 -0
- package/dist/source/tools/web-fetch.js +246 -0
- package/dist/source/tools/web-search.d.ts +13 -0
- package/dist/source/tools/web-search.js +80 -0
- package/dist/source/utils/process.d.ts +36 -0
- package/dist/source/utils/process.js +75 -0
- package/dist/source/version.d.ts +1 -0
- package/dist/source/version.js +21 -0
- package/dist/terminal/formatting.d.ts +37 -0
- package/dist/terminal/formatting.js +106 -0
- package/dist/terminal/index.d.ts +94 -0
- package/dist/terminal/index.js +420 -0
- package/dist/terminal/markdown-utils.d.ts +2 -0
- package/dist/terminal/markdown-utils.js +81 -0
- package/dist/terminal/markdown.d.ts +1 -0
- package/dist/terminal/markdown.js +111 -0
- package/dist/terminal/types.d.ts +71 -0
- package/dist/terminal/types.js +1 -0
- package/dist/terminal-output.d.ts +8 -0
- package/dist/terminal-output.js +213 -0
- package/dist/token-tracker.d.ts +14 -0
- package/dist/token-tracker.js +53 -0
- package/dist/token-utils.d.ts +7 -0
- package/dist/token-utils.js +13 -0
- package/dist/tools/agent.d.ts +17 -0
- package/dist/tools/agent.js +87 -0
- package/dist/tools/bash.d.ts +19 -0
- package/dist/tools/bash.js +294 -0
- package/dist/tools/code-interpreter.d.ts +12 -0
- package/dist/tools/code-interpreter.js +131 -0
- package/dist/tools/command-validation.d.ts +8 -0
- package/dist/tools/command-validation.js +69 -0
- package/dist/tools/delete-file.d.ts +12 -0
- package/dist/tools/delete-file.js +56 -0
- package/dist/tools/directory-tree.d.ts +12 -0
- package/dist/tools/directory-tree.js +38 -0
- package/dist/tools/edit-file.d.ts +19 -0
- package/dist/tools/edit-file.js +107 -0
- package/dist/tools/filesystem-utils.d.ts +22 -0
- package/dist/tools/filesystem-utils.js +191 -0
- package/dist/tools/git-utils.d.ts +14 -0
- package/dist/tools/git-utils.js +64 -0
- package/dist/tools/grep.d.ts +17 -0
- package/dist/tools/grep.js +138 -0
- package/dist/tools/index.d.ts +161 -0
- package/dist/tools/index.js +209 -0
- package/dist/tools/memory-read.d.ts +13 -0
- package/dist/tools/memory-read.js +135 -0
- package/dist/tools/memory-write.d.ts +12 -0
- package/dist/tools/memory-write.js +83 -0
- package/dist/tools/move-file.d.ts +13 -0
- package/dist/tools/move-file.js +44 -0
- package/dist/tools/read-file.d.ts +17 -0
- package/dist/tools/read-file.js +86 -0
- package/dist/tools/read-multiple-files.d.ts +14 -0
- package/dist/tools/read-multiple-files.js +55 -0
- package/dist/tools/save-file.d.ts +17 -0
- package/dist/tools/save-file.js +98 -0
- package/dist/tools/think.d.ts +11 -0
- package/dist/tools/think.js +45 -0
- package/dist/tools/types.d.ts +29 -0
- package/dist/tools/types.js +14 -0
- package/dist/tools/web-fetch.d.ts +47 -0
- package/dist/tools/web-fetch.js +246 -0
- package/dist/tools/web-search.d.ts +13 -0
- package/dist/tools/web-search.js +80 -0
- package/dist/utils/process.d.ts +36 -0
- package/dist/utils/process.js +75 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +21 -0
- package/knip.json +5 -0
- package/package.json +83 -0
- package/source/cli.ts +172 -0
- package/source/commands/application-log-command.ts +53 -0
- package/source/commands/clear-command.ts +14 -0
- package/source/commands/compact-command.ts +64 -0
- package/source/commands/copy-command.ts +55 -0
- package/source/commands/edit-command.ts +63 -0
- package/source/commands/edit-prompt-command.ts +31 -0
- package/source/commands/exit-command.ts +18 -0
- package/source/commands/files-command.ts +85 -0
- package/source/commands/generate-rules-command.ts +82 -0
- package/source/commands/help-command.ts +27 -0
- package/source/commands/init-command.ts +48 -0
- package/source/commands/last-log-command.ts +88 -0
- package/source/commands/manager.ts +151 -0
- package/source/commands/model-command.ts +123 -0
- package/source/commands/paste-command.ts +62 -0
- package/source/commands/prompt-command.ts +150 -0
- package/source/commands/reset-command.ts +22 -0
- package/source/commands/rules-command.ts +76 -0
- package/source/commands/save-command.ts +20 -0
- package/source/commands/types.ts +28 -0
- package/source/commands/usage-command.ts +26 -0
- package/source/config.ts +223 -0
- package/source/conversation-analyzer.ts +115 -0
- package/source/dedent.ts +53 -0
- package/source/formatting.ts +132 -0
- package/source/index.ts +240 -0
- package/source/logger.ts +29 -0
- package/source/mentions.ts +227 -0
- package/source/messages.ts +360 -0
- package/source/middleware/audit-message.ts +133 -0
- package/source/middleware/index.ts +2 -0
- package/source/middleware/rate-limit.ts +24 -0
- package/source/models/ai-config.ts +109 -0
- package/source/models/anthropic-provider.ts +199 -0
- package/source/models/deepseek-provider.ts +53 -0
- package/source/models/google-provider.ts +68 -0
- package/source/models/manager.ts +84 -0
- package/source/models/openai-provider.ts +81 -0
- package/source/models/openrouter-provider.ts +288 -0
- package/source/models/providers.ts +197 -0
- package/source/models/xai-provider.ts +59 -0
- package/source/parsing.ts +20 -0
- package/source/prompts/manager.ts +90 -0
- package/source/prompts.ts +172 -0
- package/source/repl-prompt.ts +196 -0
- package/source/repl.ts +572 -0
- package/source/terminal/formatting.ts +121 -0
- package/source/terminal/index.ts +518 -0
- package/source/terminal/markdown-utils.ts +89 -0
- package/source/terminal/markdown.ts +155 -0
- package/source/terminal/types.ts +84 -0
- package/source/terminal-output.test.ts +266 -0
- package/source/token-tracker.ts +78 -0
- package/source/token-utils.ts +17 -0
- package/source/tools/agent.ts +107 -0
- package/source/tools/bash.ts +367 -0
- package/source/tools/code-interpreter.ts +172 -0
- package/source/tools/command-validation.ts +81 -0
- package/source/tools/delete-file.ts +71 -0
- package/source/tools/directory-tree.ts +54 -0
- package/source/tools/edit-file.ts +155 -0
- package/source/tools/filesystem-utils.ts +265 -0
- package/source/tools/git-utils.ts +70 -0
- package/source/tools/grep.ts +184 -0
- package/source/tools/index.ts +278 -0
- package/source/tools/memory-read.ts +174 -0
- package/source/tools/memory-write.ts +105 -0
- package/source/tools/move-file.ts +59 -0
- package/source/tools/read-file.ts +129 -0
- package/source/tools/read-multiple-files.ts +80 -0
- package/source/tools/save-file.ts +147 -0
- package/source/tools/think.ts +51 -0
- package/source/tools/types.ts +58 -0
- package/source/tools/web-fetch.ts +327 -0
- package/source/tools/web-search.ts +101 -0
- package/source/utils/process.ts +121 -0
- package/source/version.ts +21 -0
- package/test/commands/copy-command.test.ts +69 -0
- package/test/config.test.ts +200 -0
- package/test/terminal/markdown-utils.test.ts +124 -0
- package/test/tools/bash-tool.test.ts +58 -0
- package/test/tools/code-interpreter.test.ts +91 -0
- package/test/tools/command-validation.test.ts +48 -0
- package/tsconfig.build.json +9 -0
- package/tsconfig.json +30 -0
package/dist/mentions.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { isString } from "@travisennis/stdlib/typeguards";
|
|
4
|
+
import { formatFile, formatUrl } from "./formatting.js";
|
|
5
|
+
import { readUrl } from "./tools/web-fetch.js";
|
|
6
|
+
import { executeCommand } from "./utils/process.js";
|
|
7
|
+
// Helper function to recursively read all files in a directory
|
|
8
|
+
async function readDirectoryRecursive(dirPath, format) {
|
|
9
|
+
const allContents = [];
|
|
10
|
+
async function readDir(currentPath, relativePath = "") {
|
|
11
|
+
const entries = await fs.readdir(currentPath, { withFileTypes: true });
|
|
12
|
+
for (const entry of entries) {
|
|
13
|
+
const fullPath = path.join(currentPath, entry.name);
|
|
14
|
+
const relativeFilePath = path.join(relativePath, entry.name);
|
|
15
|
+
if (entry.isDirectory()) {
|
|
16
|
+
await readDir(fullPath, relativeFilePath);
|
|
17
|
+
}
|
|
18
|
+
else if (entry.isFile()) {
|
|
19
|
+
try {
|
|
20
|
+
const fileContents = await fs.readFile(fullPath, "utf8");
|
|
21
|
+
allContents.push(formatFile(relativeFilePath, fileContents, format));
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
allContents.push(`Error reading file ${relativeFilePath}: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
await readDir(dirPath);
|
|
30
|
+
if (allContents.length === 0) {
|
|
31
|
+
return `Directory ${path.basename(dirPath)} is empty or contains no readable files.`;
|
|
32
|
+
}
|
|
33
|
+
return allContents.join("\n\n");
|
|
34
|
+
}
|
|
35
|
+
// Returns the formatted string or an error message string
|
|
36
|
+
async function processFileCommand(context) {
|
|
37
|
+
const { baseDir, match } = context;
|
|
38
|
+
const filePath = match.trim();
|
|
39
|
+
const format = context.model.promptFormat;
|
|
40
|
+
try {
|
|
41
|
+
// Resolve paths to absolute to prevent traversal issues
|
|
42
|
+
const resolvedBaseDir = path.resolve(baseDir);
|
|
43
|
+
const resolvedFilePath = path.resolve(resolvedBaseDir, filePath);
|
|
44
|
+
// Security Check: Ensure the resolved path is still within the base directory
|
|
45
|
+
if (!resolvedFilePath.startsWith(resolvedBaseDir + path.sep)) {
|
|
46
|
+
return `Error: Access denied. Attempted to read file outside the allowed directory: ${filePath}`;
|
|
47
|
+
}
|
|
48
|
+
// Check if path exists
|
|
49
|
+
const stats = await fs.stat(resolvedFilePath);
|
|
50
|
+
// If it's a directory, read all files recursively
|
|
51
|
+
if (stats.isDirectory()) {
|
|
52
|
+
return await readDirectoryRecursive(resolvedFilePath, format);
|
|
53
|
+
}
|
|
54
|
+
// If it's a file, process as before
|
|
55
|
+
if (stats.isFile()) {
|
|
56
|
+
const fileContents = await fs.readFile(resolvedFilePath, "utf8");
|
|
57
|
+
return formatFile(filePath, fileContents, format);
|
|
58
|
+
}
|
|
59
|
+
return `Error: ${filePath} is neither a regular file nor directory.`;
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
// Handle both ENOENT (file not found) and permission errors
|
|
63
|
+
if (error && typeof error === "object" && "code" in error) {
|
|
64
|
+
if (error.code === "ENOENT") {
|
|
65
|
+
return `Error: File or directory not found: ${filePath}\nPlease check that the path is correct and exists.`;
|
|
66
|
+
}
|
|
67
|
+
if (error.code === "EACCES") {
|
|
68
|
+
return `Error: Permission denied accessing: ${filePath}`;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (error instanceof Error) {
|
|
72
|
+
return `Error accessing ${filePath}: ${error.message}`;
|
|
73
|
+
}
|
|
74
|
+
// Fallback for unknown error types
|
|
75
|
+
return `Error accessing ${filePath}: An unknown error occurred.`;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
async function processShellCommand(command) {
|
|
79
|
+
try {
|
|
80
|
+
const { stdout, stderr, code } = await executeCommand(command, {
|
|
81
|
+
shell: true,
|
|
82
|
+
});
|
|
83
|
+
if (code === 0) {
|
|
84
|
+
return stdout;
|
|
85
|
+
}
|
|
86
|
+
return `Error executing command: ${command}\n${stderr}`;
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
if (error instanceof Error) {
|
|
90
|
+
return `Error executing command ${command}: ${error.message}`;
|
|
91
|
+
}
|
|
92
|
+
return `Error executing command ${command}: An unknown error occurred.`;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
// Returns the formatted string or an error message string
|
|
96
|
+
async function processUrlCommand(context) {
|
|
97
|
+
const { match } = context;
|
|
98
|
+
const urlPath = match;
|
|
99
|
+
try {
|
|
100
|
+
return Object.assign(await readUrl(urlPath), { source: urlPath });
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
if (error instanceof Error) {
|
|
104
|
+
return {
|
|
105
|
+
contentType: "text/plain",
|
|
106
|
+
data: `Url: ${urlPath} Status: Error fetching URL: ${error.message}`,
|
|
107
|
+
source: urlPath,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
// Fallback for unknown error types
|
|
111
|
+
return {
|
|
112
|
+
contentType: "text/plain",
|
|
113
|
+
data: `Url: ${urlPath} Status: Error fetching URL: An unknown error occurred.`,
|
|
114
|
+
source: urlPath,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
export async function processPrompt(message, { baseDir, model }) {
|
|
119
|
+
const fileRegex = /@([^\s@]+(?:\.[\w\d]+))/g;
|
|
120
|
+
const urlRegex = /@(https?:\/\/[^\s]+)/g;
|
|
121
|
+
const shellRegex = /!`([^`]+)`/g;
|
|
122
|
+
// Collect all matches for files and urls
|
|
123
|
+
const fileMatches = Array.from(message.matchAll(fileRegex));
|
|
124
|
+
const urlMatches = Array.from(message.matchAll(urlRegex));
|
|
125
|
+
const shellMatches = Array.from(message.matchAll(shellRegex));
|
|
126
|
+
const mentionProcessingPromises = [];
|
|
127
|
+
// Process file references - collect promises
|
|
128
|
+
for (const match of fileMatches) {
|
|
129
|
+
const firstMatch = match[1];
|
|
130
|
+
if (firstMatch) {
|
|
131
|
+
const context = {
|
|
132
|
+
model,
|
|
133
|
+
baseDir,
|
|
134
|
+
match: firstMatch,
|
|
135
|
+
};
|
|
136
|
+
mentionProcessingPromises.push(processFileCommand(context));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// Process url references - collect promises
|
|
140
|
+
for (const match of urlMatches) {
|
|
141
|
+
const firstMatch = match[1];
|
|
142
|
+
if (firstMatch) {
|
|
143
|
+
const context = {
|
|
144
|
+
model,
|
|
145
|
+
baseDir, // baseDir is not used by processUrlCommand but kept for consistency
|
|
146
|
+
match: firstMatch,
|
|
147
|
+
};
|
|
148
|
+
mentionProcessingPromises.push(processUrlCommand(context));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
let processedMessage = message;
|
|
152
|
+
// Process shell commands
|
|
153
|
+
for (const match of shellMatches) {
|
|
154
|
+
const command = match[1];
|
|
155
|
+
if (command) {
|
|
156
|
+
const output = await processShellCommand(command);
|
|
157
|
+
processedMessage = processedMessage.replace(match[0], output);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// Wait for all mentions to be processed
|
|
161
|
+
const mentionResults = await Promise.all(mentionProcessingPromises);
|
|
162
|
+
const context = [];
|
|
163
|
+
for (const mention of mentionResults) {
|
|
164
|
+
if (isString(mention)) {
|
|
165
|
+
context.push(mention);
|
|
166
|
+
}
|
|
167
|
+
else if (mention.data.startsWith("data")) {
|
|
168
|
+
context.push({
|
|
169
|
+
type: "image",
|
|
170
|
+
mediaType: mention.contentType,
|
|
171
|
+
image: mention.data,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
context.push(formatUrl(mention.source, mention.data.trim(), model.promptFormat));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
message: processedMessage,
|
|
180
|
+
context,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import EventEmitter from "node:events";
|
|
2
|
+
import { type AssistantModelMessage, type ImagePart, // Added ImagePart
|
|
3
|
+
type ModelMessage, type ToolModelMessage, type UserModelMessage } from "ai";
|
|
4
|
+
import type { ModelManager } from "./models/manager.ts";
|
|
5
|
+
import type { TokenTracker } from "./token-tracker.ts";
|
|
6
|
+
export type UserMessageContentItem = string | ImagePart;
|
|
7
|
+
export declare function createUserMessage(contentItems: UserMessageContentItem[], prompt?: string): UserModelMessage;
|
|
8
|
+
export declare function createAssistantMessage(content: string): AssistantModelMessage;
|
|
9
|
+
/**
|
|
10
|
+
A message that was generated during the generation process.
|
|
11
|
+
It can be either an assistant message or a tool message.
|
|
12
|
+
*/
|
|
13
|
+
type ResponseMessage = AssistantModelMessage | ToolModelMessage;
|
|
14
|
+
export type SavedMessageHistory = {
|
|
15
|
+
title: string;
|
|
16
|
+
createdAt: Date;
|
|
17
|
+
updatedAt: Date;
|
|
18
|
+
messages: ModelMessage[];
|
|
19
|
+
};
|
|
20
|
+
interface MessageHistoryEvents {
|
|
21
|
+
"update-title": [string];
|
|
22
|
+
"clear-history": [];
|
|
23
|
+
}
|
|
24
|
+
export declare class MessageHistory extends EventEmitter<MessageHistoryEvents> {
|
|
25
|
+
private history;
|
|
26
|
+
private title;
|
|
27
|
+
private createdAt;
|
|
28
|
+
private updatedAt;
|
|
29
|
+
private stateDir;
|
|
30
|
+
private modelManager;
|
|
31
|
+
private tokenTracker;
|
|
32
|
+
constructor({ stateDir, modelManager, tokenTracker, }: {
|
|
33
|
+
stateDir: string;
|
|
34
|
+
modelManager: ModelManager;
|
|
35
|
+
tokenTracker: TokenTracker;
|
|
36
|
+
});
|
|
37
|
+
private validMessage;
|
|
38
|
+
get(): ModelMessage[];
|
|
39
|
+
clear(): void;
|
|
40
|
+
appendUserMessage(msg: string): void;
|
|
41
|
+
appendUserMessage(msg: UserModelMessage): void;
|
|
42
|
+
appendAssistantMessage(msg: string): void;
|
|
43
|
+
appendAssistantMessage(msg: AssistantModelMessage): void;
|
|
44
|
+
appendResponseMessages(responseMessages: ResponseMessage[]): void;
|
|
45
|
+
isEmpty(): boolean;
|
|
46
|
+
save(): Promise<void>;
|
|
47
|
+
private generateTitle;
|
|
48
|
+
getFirstUserMessage(): UserModelMessage | undefined;
|
|
49
|
+
static load(stateDir: string, count?: number): Promise<SavedMessageHistory[]>;
|
|
50
|
+
restore(savedHistory: SavedMessageHistory): void;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Normalizes an array of messages for API consumption by:
|
|
54
|
+
* 1. Filtering out progress-type messages
|
|
55
|
+
* 2. Processing user and assistant messages
|
|
56
|
+
* 3. Handling tool results by either:
|
|
57
|
+
* - Adding them as new messages if they're the first tool result
|
|
58
|
+
* - Adding them as new messages if the previous message wasn't a tool result
|
|
59
|
+
* - Merging them with the previous message if it was also a tool result
|
|
60
|
+
*
|
|
61
|
+
* This consolidation of sequential tool results into a single message
|
|
62
|
+
* ensures proper formatting for API consumption while maintaining the
|
|
63
|
+
* logical flow of the conversation.
|
|
64
|
+
*
|
|
65
|
+
* @param messages - Array of messages to normalize
|
|
66
|
+
* @returns Normalized array of user and assistant messages ready for API
|
|
67
|
+
*/
|
|
68
|
+
export declare function normalizeMessagesForApi(messages: ModelMessage[]): ModelMessage[];
|
|
69
|
+
export {};
|
package/dist/messages.js
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import EventEmitter from "node:events";
|
|
2
|
+
import { readdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { isString } from "@travisennis/stdlib/typeguards";
|
|
5
|
+
import { generateText, } from "ai";
|
|
6
|
+
export function createUserMessage(contentItems, prompt) {
|
|
7
|
+
const messageParts = [];
|
|
8
|
+
// Process content items (images and pre-defined texts)
|
|
9
|
+
for (const item of contentItems) {
|
|
10
|
+
if (typeof item === "string") {
|
|
11
|
+
if (item.trim().length > 0) {
|
|
12
|
+
messageParts.push({ type: "text", text: item });
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
else if (item.type === "image") {
|
|
16
|
+
messageParts.push(item);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
// Add the main prompt text if provided
|
|
20
|
+
if (prompt && prompt.trim().length > 0) {
|
|
21
|
+
messageParts.push({ type: "text", text: prompt });
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
role: "user",
|
|
25
|
+
content: messageParts,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export function createAssistantMessage(content) {
|
|
29
|
+
return {
|
|
30
|
+
role: "assistant",
|
|
31
|
+
content: [
|
|
32
|
+
{
|
|
33
|
+
type: "text",
|
|
34
|
+
text: content,
|
|
35
|
+
},
|
|
36
|
+
],
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export class MessageHistory extends EventEmitter {
|
|
40
|
+
history;
|
|
41
|
+
title;
|
|
42
|
+
createdAt;
|
|
43
|
+
updatedAt;
|
|
44
|
+
stateDir;
|
|
45
|
+
modelManager;
|
|
46
|
+
tokenTracker;
|
|
47
|
+
constructor({ stateDir, modelManager, tokenTracker, }) {
|
|
48
|
+
super();
|
|
49
|
+
this.history = [];
|
|
50
|
+
this.title = "";
|
|
51
|
+
this.createdAt = new Date();
|
|
52
|
+
this.updatedAt = new Date();
|
|
53
|
+
this.stateDir = stateDir;
|
|
54
|
+
this.modelManager = modelManager;
|
|
55
|
+
this.tokenTracker = tokenTracker;
|
|
56
|
+
}
|
|
57
|
+
validMessage(msg) {
|
|
58
|
+
// Filter out messages with empty content arrays
|
|
59
|
+
if (Array.isArray(msg.content) && msg.content.length === 0) {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
// Filter out assistant messages with empty text fields
|
|
63
|
+
if (msg.role === "assistant" &&
|
|
64
|
+
Array.isArray(msg.content) &&
|
|
65
|
+
msg.content.length === 1 &&
|
|
66
|
+
msg.content[0]?.type === "text" &&
|
|
67
|
+
msg.content[0]?.text === "") {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
get() {
|
|
73
|
+
return [...this.history].filter(this.validMessage);
|
|
74
|
+
}
|
|
75
|
+
clear() {
|
|
76
|
+
this.history.length = 0;
|
|
77
|
+
this.emit("clear-history");
|
|
78
|
+
}
|
|
79
|
+
appendUserMessage(msg) {
|
|
80
|
+
const now = new Date();
|
|
81
|
+
const msgObj = isString(msg) ? createUserMessage([], msg) : msg;
|
|
82
|
+
if (this.history.length === 0 &&
|
|
83
|
+
msgObj.content &&
|
|
84
|
+
msgObj.content.length > 0) {
|
|
85
|
+
const textPart = msgObj.content.at(-1);
|
|
86
|
+
if (textPart?.text && textPart.text.trim() !== "") {
|
|
87
|
+
this.generateTitle(textPart.text);
|
|
88
|
+
}
|
|
89
|
+
this.createdAt = now;
|
|
90
|
+
}
|
|
91
|
+
this.updatedAt = now;
|
|
92
|
+
this.history.push(msgObj);
|
|
93
|
+
}
|
|
94
|
+
appendAssistantMessage(msg) {
|
|
95
|
+
this.updatedAt = new Date();
|
|
96
|
+
const msgObj = isString(msg) ? createAssistantMessage(msg) : msg;
|
|
97
|
+
this.history.push(msgObj);
|
|
98
|
+
}
|
|
99
|
+
appendResponseMessages(responseMessages) {
|
|
100
|
+
this.updatedAt = new Date();
|
|
101
|
+
// Filter out messages with empty content arrays
|
|
102
|
+
const validMessages = responseMessages.filter(this.validMessage);
|
|
103
|
+
this.history.push(...validMessages);
|
|
104
|
+
}
|
|
105
|
+
isEmpty() {
|
|
106
|
+
return this.history.length === 0;
|
|
107
|
+
}
|
|
108
|
+
async save() {
|
|
109
|
+
const msgHistoryDir = this.stateDir;
|
|
110
|
+
const timestamp = new Date().toISOString().replace(/:/g, "-");
|
|
111
|
+
const fileName = `message-history-${timestamp}.json`;
|
|
112
|
+
const filePath = join(msgHistoryDir, fileName);
|
|
113
|
+
const output = {
|
|
114
|
+
title: this.title,
|
|
115
|
+
createdAt: this.createdAt,
|
|
116
|
+
updatedAt: this.updatedAt,
|
|
117
|
+
messages: this.history,
|
|
118
|
+
};
|
|
119
|
+
await writeFile(filePath, JSON.stringify(output, null, 2));
|
|
120
|
+
}
|
|
121
|
+
async generateTitle(message) {
|
|
122
|
+
// Skip title generation if message is empty
|
|
123
|
+
if (!message || message.trim() === "") {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const app = "title-conversation";
|
|
127
|
+
const systemPrompt = "You are an assistant who task is to analyze messages to generate a conversation topic that can be used as a conversation title. For each message, generate a 4-7 word title that captures the topic. Return only the title with no other text.\n\nExamples:\nMessage:\nHow do I implement authentication in my Express app?\nTitle: Express Authentication Implementation\n\nMessage:\nCan you help me debug this React component that isn't rendering correctly?\nTitle:React Component Rendering Debug";
|
|
128
|
+
try {
|
|
129
|
+
const { text, usage } = await generateText({
|
|
130
|
+
model: this.modelManager.getModel(app),
|
|
131
|
+
system: systemPrompt,
|
|
132
|
+
prompt: `Request:\n${message}\nTitle:`,
|
|
133
|
+
});
|
|
134
|
+
this.tokenTracker.trackUsage(app, usage);
|
|
135
|
+
if (text && text.split(" ").length < 10) {
|
|
136
|
+
this.title = text;
|
|
137
|
+
this.emit("update-title", this.title);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
console.error(error);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
getFirstUserMessage() {
|
|
145
|
+
const firstUser = this.get().find((msg) => msg.role === "user");
|
|
146
|
+
return firstUser;
|
|
147
|
+
}
|
|
148
|
+
static async load(stateDir, count = 10) {
|
|
149
|
+
try {
|
|
150
|
+
const files = await readdir(stateDir);
|
|
151
|
+
const messageHistoryFiles = files
|
|
152
|
+
.filter((file) => file.startsWith("message-history-") && file.endsWith(".json"))
|
|
153
|
+
.sort((a, b) => {
|
|
154
|
+
// Extract timestamps and compare in reverse order (newest first)
|
|
155
|
+
const timeA = a.replace("message-history-", "").replace(".json", "");
|
|
156
|
+
const timeB = b.replace("message-history-", "").replace(".json", "");
|
|
157
|
+
return timeB.localeCompare(timeA); // Newest first
|
|
158
|
+
})
|
|
159
|
+
.slice(0, count); // Use the count parameter here
|
|
160
|
+
const fileReadPromises = messageHistoryFiles.map(async (fileName) => {
|
|
161
|
+
const filePath = join(stateDir, fileName);
|
|
162
|
+
try {
|
|
163
|
+
const content = await readFile(filePath, "utf-8");
|
|
164
|
+
const parsed = JSON.parse(content);
|
|
165
|
+
const result = parsed;
|
|
166
|
+
// Basic validation - ensure messages array exists
|
|
167
|
+
if (parsed && Array.isArray(parsed.messages)) {
|
|
168
|
+
// Convert date strings back to Date objects
|
|
169
|
+
result.createdAt = new Date(parsed.createdAt ?? 0);
|
|
170
|
+
result.updatedAt = new Date(parsed.updatedAt ?? 0);
|
|
171
|
+
return result;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
console.error(`Error reading or parsing file ${filePath}:`, error);
|
|
176
|
+
}
|
|
177
|
+
return null; // Return null for failed reads/parses
|
|
178
|
+
});
|
|
179
|
+
const results = await Promise.all(fileReadPromises);
|
|
180
|
+
// Filter out null results (failed reads/parses)
|
|
181
|
+
//sort results by result.updatedAt which is a Date
|
|
182
|
+
return results
|
|
183
|
+
.filter((result) => result !== null)
|
|
184
|
+
.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
// Handle cases where the directory might not exist or other readdir errors
|
|
188
|
+
if (error.code !== "ENOENT") {
|
|
189
|
+
console.error(`Error loading message history from ${stateDir}:`, error);
|
|
190
|
+
}
|
|
191
|
+
// Return empty array if directory doesn't exist or other read errors occur
|
|
192
|
+
return [];
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
// Method to restore state from a SavedMessageHistory object
|
|
196
|
+
restore(savedHistory) {
|
|
197
|
+
this.title = savedHistory.title;
|
|
198
|
+
// Ensure dates are Date objects, though load should handle this
|
|
199
|
+
this.createdAt =
|
|
200
|
+
typeof savedHistory.createdAt === "string"
|
|
201
|
+
? new Date(savedHistory.createdAt)
|
|
202
|
+
: savedHistory.createdAt;
|
|
203
|
+
this.updatedAt =
|
|
204
|
+
typeof savedHistory.updatedAt === "string"
|
|
205
|
+
? new Date(savedHistory.updatedAt)
|
|
206
|
+
: savedHistory.updatedAt;
|
|
207
|
+
this.history = [...savedHistory.messages]; // Use the correct internal property name and create a copy
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Normalizes an array of messages for API consumption by:
|
|
212
|
+
* 1. Filtering out progress-type messages
|
|
213
|
+
* 2. Processing user and assistant messages
|
|
214
|
+
* 3. Handling tool results by either:
|
|
215
|
+
* - Adding them as new messages if they're the first tool result
|
|
216
|
+
* - Adding them as new messages if the previous message wasn't a tool result
|
|
217
|
+
* - Merging them with the previous message if it was also a tool result
|
|
218
|
+
*
|
|
219
|
+
* This consolidation of sequential tool results into a single message
|
|
220
|
+
* ensures proper formatting for API consumption while maintaining the
|
|
221
|
+
* logical flow of the conversation.
|
|
222
|
+
*
|
|
223
|
+
* @param messages - Array of messages to normalize
|
|
224
|
+
* @returns Normalized array of user and assistant messages ready for API
|
|
225
|
+
*/
|
|
226
|
+
export function normalizeMessagesForApi(messages) {
|
|
227
|
+
const result = [];
|
|
228
|
+
for (const message of messages) {
|
|
229
|
+
switch (message.role) {
|
|
230
|
+
case "user": {
|
|
231
|
+
result.push(message);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
case "tool": {
|
|
235
|
+
// If the last message is not a tool result, add it to the result
|
|
236
|
+
const lastMessage = result.at(-1);
|
|
237
|
+
if (!lastMessage ||
|
|
238
|
+
lastMessage.role === "assistant" ||
|
|
239
|
+
!Array.isArray(lastMessage.content) ||
|
|
240
|
+
lastMessage.content[0]?.type !== "tool-result") {
|
|
241
|
+
result.push(message);
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
// Otherwise, merge the current message with the last message
|
|
245
|
+
result[result.indexOf(lastMessage)] = {
|
|
246
|
+
...lastMessage,
|
|
247
|
+
// biome-ignore lint/suspicious/noExplicitAny: can't figure out type
|
|
248
|
+
content: [...lastMessage.content, ...message.content], // #FIXME figure out what type this should be
|
|
249
|
+
};
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
case "assistant": {
|
|
253
|
+
result.push(message);
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
default:
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return result;
|
|
261
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
/**
|
|
4
|
+
* Writes an audit record to the specified file, overwriting any existing content.
|
|
5
|
+
* Ensures the directory exists before writing.
|
|
6
|
+
*
|
|
7
|
+
* @param filePath - The path to the file where the audit record will be saved.
|
|
8
|
+
* @param content - The audit record object to write.
|
|
9
|
+
*/
|
|
10
|
+
const writeAuditRecord = async (app, filePath, content) => {
|
|
11
|
+
try {
|
|
12
|
+
const now = new Date();
|
|
13
|
+
const path = join(filePath, `${now.toISOString()}-${app}-message.json`);
|
|
14
|
+
// Ensure directory exists
|
|
15
|
+
await mkdir(dirname(path), { recursive: true });
|
|
16
|
+
await writeFile(path, `${JSON.stringify(content, null, 2)}`);
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
console.error("Error writing audit file:", error);
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
export const auditMessage = ({ filePath = "messages", app = "default", }) => {
|
|
24
|
+
const middleware = {
|
|
25
|
+
wrapGenerate: async ({ doGenerate, params, model }) => {
|
|
26
|
+
const result = await doGenerate();
|
|
27
|
+
const msg = {
|
|
28
|
+
model: model.modelId,
|
|
29
|
+
app,
|
|
30
|
+
messages: [...params.prompt].concat({
|
|
31
|
+
role: "assistant",
|
|
32
|
+
content: [
|
|
33
|
+
{
|
|
34
|
+
type: "text",
|
|
35
|
+
// biome-ignore lint/suspicious/noExplicitAny: work-around on type issue
|
|
36
|
+
text: result.text,
|
|
37
|
+
},
|
|
38
|
+
],
|
|
39
|
+
}),
|
|
40
|
+
usage: result.usage,
|
|
41
|
+
timestamp: Date.now(),
|
|
42
|
+
};
|
|
43
|
+
await writeAuditRecord(app, filePath, msg);
|
|
44
|
+
return result;
|
|
45
|
+
},
|
|
46
|
+
wrapStream: async ({ doStream, params, model }) => {
|
|
47
|
+
const { stream, ...rest } = await doStream();
|
|
48
|
+
let generatedText = "";
|
|
49
|
+
let usage = {
|
|
50
|
+
inputTokens: 0,
|
|
51
|
+
outputTokens: 0,
|
|
52
|
+
totalTokens: 0,
|
|
53
|
+
};
|
|
54
|
+
const transformStream = new TransformStream({
|
|
55
|
+
transform(chunk, controller) {
|
|
56
|
+
if (chunk.type === "text-delta") {
|
|
57
|
+
generatedText += chunk.delta;
|
|
58
|
+
}
|
|
59
|
+
if (chunk.type === "finish") {
|
|
60
|
+
usage = chunk.usage;
|
|
61
|
+
}
|
|
62
|
+
controller.enqueue(chunk);
|
|
63
|
+
},
|
|
64
|
+
async flush() {
|
|
65
|
+
const msg = {
|
|
66
|
+
model: model.modelId,
|
|
67
|
+
app,
|
|
68
|
+
messages: generatedText
|
|
69
|
+
? [
|
|
70
|
+
...params.prompt,
|
|
71
|
+
{
|
|
72
|
+
role: "assistant",
|
|
73
|
+
content: [
|
|
74
|
+
{
|
|
75
|
+
type: "text",
|
|
76
|
+
text: generatedText,
|
|
77
|
+
},
|
|
78
|
+
],
|
|
79
|
+
},
|
|
80
|
+
]
|
|
81
|
+
: [...params.prompt],
|
|
82
|
+
usage,
|
|
83
|
+
timestamp: Date.now(),
|
|
84
|
+
};
|
|
85
|
+
await writeAuditRecord(app, filePath, msg);
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
return {
|
|
89
|
+
stream: stream.pipeThrough(transformStream),
|
|
90
|
+
...rest,
|
|
91
|
+
};
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
return middleware;
|
|
95
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import pThrottle from "p-throttle";
|
|
2
|
+
export const createRateLimitMiddleware = ({ requestsPerMinute, }) => {
|
|
3
|
+
const throttle = pThrottle({
|
|
4
|
+
limit: requestsPerMinute,
|
|
5
|
+
interval: 60 * 1000, // 1 minute
|
|
6
|
+
});
|
|
7
|
+
return {
|
|
8
|
+
wrapGenerate: ({ doGenerate }) => {
|
|
9
|
+
const throttledGenerate = throttle(doGenerate);
|
|
10
|
+
return Promise.resolve(throttledGenerate());
|
|
11
|
+
},
|
|
12
|
+
wrapStream: ({ doStream }) => {
|
|
13
|
+
const throttledStream = throttle(doStream);
|
|
14
|
+
return throttledStream();
|
|
15
|
+
},
|
|
16
|
+
};
|
|
17
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { SharedV2ProviderMetadata } from "@ai-sdk/provider";
|
|
2
|
+
import type { ModelMetadata } from "./providers.ts";
|
|
3
|
+
export declare class AiConfig {
|
|
4
|
+
private modelMetadata;
|
|
5
|
+
private prompt;
|
|
6
|
+
constructor({ modelMetadata, prompt, }: {
|
|
7
|
+
modelMetadata: ModelMetadata;
|
|
8
|
+
prompt: string;
|
|
9
|
+
});
|
|
10
|
+
getMaxTokens(): number;
|
|
11
|
+
getProviderOptions(): SharedV2ProviderMetadata;
|
|
12
|
+
}
|