@elyracode/coding-agent 0.1.0 → 0.3.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 (177) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/cli/config-selector.d.ts +1 -1
  3. package/dist/cli/config-selector.d.ts.map +1 -1
  4. package/dist/cli/config-selector.js +1 -1
  5. package/dist/cli/config-selector.js.map +1 -1
  6. package/dist/config.d.ts +1 -1
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +2 -2
  9. package/dist/config.js.map +1 -1
  10. package/dist/core/agent-session-runtime.d.ts +1 -0
  11. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  12. package/dist/core/agent-session-runtime.js +35 -0
  13. package/dist/core/agent-session-runtime.js.map +1 -1
  14. package/dist/core/agent-session.d.ts +7 -1
  15. package/dist/core/agent-session.d.ts.map +1 -1
  16. package/dist/core/agent-session.js +55 -3
  17. package/dist/core/agent-session.js.map +1 -1
  18. package/dist/core/bash-executor.d.ts.map +1 -1
  19. package/dist/core/bash-executor.js +1 -1
  20. package/dist/core/bash-executor.js.map +1 -1
  21. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  22. package/dist/core/compaction/branch-summarization.js +1 -1
  23. package/dist/core/compaction/branch-summarization.js.map +1 -1
  24. package/dist/core/compaction/compaction.d.ts.map +1 -1
  25. package/dist/core/compaction/compaction.js +1 -1
  26. package/dist/core/compaction/compaction.js.map +1 -1
  27. package/dist/core/extensions/loader.d.ts.map +1 -1
  28. package/dist/core/extensions/loader.js +3 -3
  29. package/dist/core/extensions/loader.js.map +1 -1
  30. package/dist/core/extensions/runner.d.ts.map +1 -1
  31. package/dist/core/extensions/runner.js +1 -1
  32. package/dist/core/extensions/runner.js.map +1 -1
  33. package/dist/core/extensions/types.d.ts +9 -9
  34. package/dist/core/extensions/types.d.ts.map +1 -1
  35. package/dist/core/extensions/types.js.map +1 -1
  36. package/dist/core/memory.d.ts +23 -0
  37. package/dist/core/memory.d.ts.map +1 -0
  38. package/dist/core/memory.js +173 -0
  39. package/dist/core/memory.js.map +1 -0
  40. package/dist/core/package-manager.d.ts.map +1 -1
  41. package/dist/core/package-manager.js +12 -12
  42. package/dist/core/package-manager.js.map +1 -1
  43. package/dist/core/session-manager.d.ts +6 -6
  44. package/dist/core/session-manager.d.ts.map +1 -1
  45. package/dist/core/session-manager.js +4 -4
  46. package/dist/core/session-manager.js.map +1 -1
  47. package/dist/core/settings-manager.d.ts +6 -0
  48. package/dist/core/settings-manager.d.ts.map +1 -1
  49. package/dist/core/settings-manager.js +16 -0
  50. package/dist/core/settings-manager.js.map +1 -1
  51. package/dist/core/smart-router.d.ts +43 -0
  52. package/dist/core/smart-router.d.ts.map +1 -0
  53. package/dist/core/smart-router.js +206 -0
  54. package/dist/core/smart-router.js.map +1 -0
  55. package/dist/core/stack-detector.d.ts +21 -0
  56. package/dist/core/stack-detector.d.ts.map +1 -0
  57. package/dist/core/stack-detector.js +120 -0
  58. package/dist/core/stack-detector.js.map +1 -0
  59. package/dist/core/system-prompt.d.ts +4 -0
  60. package/dist/core/system-prompt.d.ts.map +1 -1
  61. package/dist/core/system-prompt.js +27 -1
  62. package/dist/core/system-prompt.js.map +1 -1
  63. package/dist/core/tools/bash.d.ts +2 -2
  64. package/dist/core/tools/bash.d.ts.map +1 -1
  65. package/dist/core/tools/bash.js +3 -3
  66. package/dist/core/tools/bash.js.map +1 -1
  67. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  68. package/dist/core/tools/output-accumulator.js +1 -1
  69. package/dist/core/tools/output-accumulator.js.map +1 -1
  70. package/dist/migrations.d.ts.map +1 -1
  71. package/dist/migrations.js +1 -1
  72. package/dist/migrations.js.map +1 -1
  73. package/dist/modes/interactive/components/settings-selector.d.ts +4 -0
  74. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  75. package/dist/modes/interactive/components/settings-selector.js +20 -0
  76. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  77. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  78. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  79. package/dist/modes/interactive/interactive-mode.js +26 -0
  80. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  81. package/dist/package-manager-cli.d.ts.map +1 -1
  82. package/dist/package-manager-cli.js +10 -10
  83. package/dist/package-manager-cli.js.map +1 -1
  84. package/dist/utils/clipboard-image.d.ts.map +1 -1
  85. package/dist/utils/clipboard-image.js +1 -1
  86. package/dist/utils/clipboard-image.js.map +1 -1
  87. package/docs/extensions.md +17 -17
  88. package/docs/index.md +1 -1
  89. package/docs/prompt-templates.md +1 -1
  90. package/docs/providers.md +1 -1
  91. package/docs/quickstart.md +5 -5
  92. package/docs/rpc.md +6 -6
  93. package/docs/sdk.md +2 -2
  94. package/docs/session-format.md +3 -3
  95. package/docs/settings.md +4 -4
  96. package/docs/skills.md +2 -2
  97. package/docs/termux.md +3 -3
  98. package/docs/themes.md +1 -1
  99. package/docs/tui.md +1 -1
  100. package/docs/usage.md +2 -2
  101. package/examples/extensions/auto-commit-on-exit.ts +5 -5
  102. package/examples/extensions/bash-spawn-hook.ts +2 -2
  103. package/examples/extensions/bookmark.ts +5 -5
  104. package/examples/extensions/border-status-editor.ts +7 -7
  105. package/examples/extensions/built-in-tool-renderer.ts +5 -5
  106. package/examples/extensions/claude-rules.ts +3 -3
  107. package/examples/extensions/commands.ts +4 -4
  108. package/examples/extensions/confirm-destructive.ts +3 -3
  109. package/examples/extensions/custom-compaction.ts +2 -2
  110. package/examples/extensions/custom-footer.ts +2 -2
  111. package/examples/extensions/custom-header.ts +3 -3
  112. package/examples/extensions/custom-provider-anthropic/index.ts +2 -2
  113. package/examples/extensions/custom-provider-anthropic/package.json +2 -2
  114. package/examples/extensions/custom-provider-gitlab-duo/index.ts +2 -2
  115. package/examples/extensions/custom-provider-gitlab-duo/package.json +2 -2
  116. package/examples/extensions/dirty-repo-guard.ts +7 -7
  117. package/examples/extensions/doom-overlay/index.ts +2 -2
  118. package/examples/extensions/dynamic-resources/index.ts +2 -2
  119. package/examples/extensions/dynamic-tools.ts +4 -4
  120. package/examples/extensions/event-bus.ts +8 -8
  121. package/examples/extensions/file-trigger.ts +3 -3
  122. package/examples/extensions/git-checkpoint.ts +7 -7
  123. package/examples/extensions/github-issue-autocomplete.ts +6 -6
  124. package/examples/extensions/handoff.ts +2 -2
  125. package/examples/extensions/hello.ts +2 -2
  126. package/examples/extensions/hidden-thinking-label.ts +3 -3
  127. package/examples/extensions/inline-bash.ts +3 -3
  128. package/examples/extensions/input-transform.ts +2 -2
  129. package/examples/extensions/interactive-shell.ts +2 -2
  130. package/examples/extensions/mac-system-theme.ts +3 -3
  131. package/examples/extensions/message-renderer.ts +4 -4
  132. package/examples/extensions/minimal-mode.ts +8 -8
  133. package/examples/extensions/modal-editor.ts +2 -2
  134. package/examples/extensions/model-status.ts +2 -2
  135. package/examples/extensions/notify.ts +2 -2
  136. package/examples/extensions/overlay-qa-tests.ts +14 -14
  137. package/examples/extensions/overlay-test.ts +2 -2
  138. package/examples/extensions/permission-gate.ts +2 -2
  139. package/examples/extensions/pirate.ts +3 -3
  140. package/examples/extensions/plan-mode/index.ts +22 -22
  141. package/examples/extensions/preset.ts +23 -23
  142. package/examples/extensions/prompt-customizer.ts +2 -2
  143. package/examples/extensions/protected-paths.ts +2 -2
  144. package/examples/extensions/provider-payload.ts +3 -3
  145. package/examples/extensions/qna.ts +2 -2
  146. package/examples/extensions/question.ts +2 -2
  147. package/examples/extensions/questionnaire.ts +2 -2
  148. package/examples/extensions/rainbow-editor.ts +2 -2
  149. package/examples/extensions/reload-runtime.ts +4 -4
  150. package/examples/extensions/rpc-demo.ts +10 -10
  151. package/examples/extensions/sandbox/index.ts +8 -8
  152. package/examples/extensions/sandbox/package.json +2 -2
  153. package/examples/extensions/send-user-message.ts +13 -13
  154. package/examples/extensions/session-name.ts +4 -4
  155. package/examples/extensions/shutdown-command.ts +10 -10
  156. package/examples/extensions/snake.ts +3 -3
  157. package/examples/extensions/space-invaders.ts +3 -3
  158. package/examples/extensions/ssh.ts +10 -10
  159. package/examples/extensions/status-line.ts +4 -4
  160. package/examples/extensions/structured-output.ts +2 -2
  161. package/examples/extensions/subagent/index.ts +3 -3
  162. package/examples/extensions/summarize.ts +2 -2
  163. package/examples/extensions/system-prompt-header.ts +3 -3
  164. package/examples/extensions/tic-tac-toe.ts +15 -15
  165. package/examples/extensions/timed-confirm.ts +4 -4
  166. package/examples/extensions/titlebar-spinner.ts +8 -8
  167. package/examples/extensions/todo.ts +5 -5
  168. package/examples/extensions/tool-override.ts +3 -3
  169. package/examples/extensions/tools.ts +9 -9
  170. package/examples/extensions/trigger-compact.ts +3 -3
  171. package/examples/extensions/truncated-tool.ts +3 -3
  172. package/examples/extensions/widget-placement.ts +2 -2
  173. package/examples/extensions/with-deps/index.ts +2 -2
  174. package/examples/extensions/with-deps/package.json +2 -2
  175. package/examples/extensions/working-indicator.ts +5 -5
  176. package/examples/extensions/working-message-test.ts +2 -2
  177. package/package.json +5 -5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"smart-router.d.ts","sourceRoot":"","sources":["../../src/core/smart-router.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACzE,OAAO,KAAK,EAAE,GAAG,EAAoB,KAAK,EAA4C,MAAM,eAAe,CAAC;AAO5G,MAAM,WAAW,iBAAiB;IACjC,OAAO,EAAE,OAAO,CAAC;IACjB,yEAAyE;IACzE,eAAe,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;IAC9B,qFAAqF;IACrF,cAAc,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;CAC3B;AAED,MAAM,WAAW,YAAY;IAC5B,+CAA+C;IAC/C,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,8BAA8B;IAC9B,aAAa,EAAE,aAAa,CAAC;CAC7B;AAED,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,UAAU,GAAG,UAAU,CAAC;AAE9D,MAAM,WAAW,iBAAiB;IACjC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAClB,IAAI,EAAE,cAAc,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;CACf;AA4GD,sDAAsD;AACtD,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,YAAY,GAAG;IAAE,IAAI,EAAE,cAAc,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CA0EnG;AAMD,+EAA+E;AAC/E,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,cAAc,EAAE,MAAM,EAAE,iBAAiB,GAAG,KAAK,CAAC,GAAG,CAAC,CAmB9F;AAMD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,YAAY,EAAE,MAAM,EAAE,iBAAiB,GAAG,iBAAiB,GAAG,SAAS,CAU9G","sourcesContent":["/**\n * Smart model routing for automatic tier-based model selection.\n *\n * Analyzes conversation signals after each turn and selects the optimal model\n * tier (fast/balanced/powerful) for the next turn based on task complexity.\n */\n\nimport type { AgentMessage, ThinkingLevel } from \"@elyracode/agent-core\";\nimport type { Api, AssistantMessage, Model, ToolCall, ToolResultMessage, UserMessage } from \"@elyracode/ai\";\nimport { modelsAreEqual } from \"@elyracode/ai\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface SmartRouterConfig {\n\tenabled: boolean;\n\t/** Available models the router can pick from. Must have at least one. */\n\tavailableModels: Model<Api>[];\n\t/** The user's preferred/current model -- used as the Tier 2 default and fallback. */\n\tpreferredModel: Model<Api>;\n}\n\nexport interface TurnAnalysis {\n\t/** The messages in the conversation so far. */\n\tmessages: AgentMessage[];\n\t/** Current thinking level. */\n\tthinkingLevel: ThinkingLevel;\n}\n\nexport type ComplexityTier = \"fast\" | \"balanced\" | \"powerful\";\n\nexport interface SmartRouterResult {\n\tmodel: Model<Api>;\n\ttier: ComplexityTier;\n\treason: string;\n}\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Output cost thresholds ($/million tokens) for tier classification. */\nconst TIER_1_MAX_COST = 3;\nconst TIER_3_MIN_COST = 20;\n\n/** Tool names considered read-only (no side effects). */\nconst READ_ONLY_TOOLS: ReadonlySet<string> = new Set([\"read\", \"grep\", \"find\", \"ls\"]);\n\n/** Keywords in user messages that signal complex work. */\nconst COMPLEX_KEYWORDS: readonly string[] = [\n\t\"refactor\",\n\t\"architect\",\n\t\"redesign\",\n\t\"migrate\",\n\t\"rewrite\",\n\t\"debug\",\n\t\"fix the bug\",\n\t\"security audit\",\n];\n\n/** Short user message threshold (characters). */\nconst SHORT_MESSAGE_THRESHOLD = 100;\n\n/** Message count threshold for complex multi-step tasks. */\nconst LONG_CONVERSATION_THRESHOLD = 20;\n\n/** File edit count threshold per turn for complexity escalation. */\nconst MANY_EDITS_THRESHOLD = 3;\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction isUserMessage(msg: AgentMessage): msg is UserMessage {\n\treturn \"role\" in msg && (msg as UserMessage).role === \"user\";\n}\n\nfunction isAssistantMessage(msg: AgentMessage): msg is AssistantMessage {\n\treturn \"role\" in msg && (msg as AssistantMessage).role === \"assistant\";\n}\n\nfunction isToolResultMessage(msg: AgentMessage): msg is ToolResultMessage {\n\treturn \"role\" in msg && (msg as ToolResultMessage).role === \"toolResult\";\n}\n\n/** Extract the plain-text content of a user message. */\nfunction getUserMessageText(msg: UserMessage): string {\n\tif (typeof msg.content === \"string\") return msg.content;\n\treturn msg.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\" \");\n}\n\n/** Extract tool calls from an assistant message's content. */\nfunction getToolCalls(msg: AssistantMessage): ToolCall[] {\n\treturn msg.content.filter((c): c is ToolCall => c.type === \"toolCall\");\n}\n\n/** True when all tool calls in a message are read-only. */\nfunction allToolCallsReadOnly(toolCalls: ToolCall[]): boolean {\n\treturn toolCalls.length > 0 && toolCalls.every((tc) => READ_ONLY_TOOLS.has(tc.name));\n}\n\n/** Count write/edit tool calls in an assistant message. */\nfunction countFileEditCalls(toolCalls: ToolCall[]): number {\n\treturn toolCalls.filter((tc) => tc.name === \"write\" || tc.name === \"edit\").length;\n}\n\n/**\n * Collect tool result messages that follow an assistant message.\n * Walks forward from the assistant message index, collecting consecutive\n * tool results (there may be other message types interleaved in custom\n * AgentMessage streams, so we stop at the next user or assistant message).\n */\nfunction getToolResultsAfter(messages: AgentMessage[], assistantIndex: number): ToolResultMessage[] {\n\tconst results: ToolResultMessage[] = [];\n\tfor (let i = assistantIndex + 1; i < messages.length; i++) {\n\t\tconst msg = messages[i];\n\t\tif (isUserMessage(msg) || isAssistantMessage(msg)) break;\n\t\tif (isToolResultMessage(msg)) results.push(msg);\n\t}\n\treturn results;\n}\n\n/** True when the text contains any of the complex keywords (case-insensitive). */\nfunction containsComplexKeyword(text: string): boolean {\n\tconst lower = text.toLowerCase();\n\treturn COMPLEX_KEYWORDS.some((kw) => lower.includes(kw));\n}\n\n// ============================================================================\n// Tier classification\n// ============================================================================\n\n/** Classify a model into its cost tier. */\nfunction modelTier(model: Model<Api>): ComplexityTier {\n\tconst cost = model.cost.output;\n\tif (cost < TIER_1_MAX_COST) return \"fast\";\n\tif (cost < TIER_3_MIN_COST) return \"balanced\";\n\treturn \"powerful\";\n}\n\n/** Classify the complexity tier for the next turn. */\nexport function classifyComplexity(analysis: TurnAnalysis): { tier: ComplexityTier; reason: string } {\n\tconst { messages, thinkingLevel } = analysis;\n\n\t// High thinking level -> complex\n\tif (thinkingLevel === \"high\" || thinkingLevel === \"xhigh\") {\n\t\treturn { tier: \"powerful\", reason: `thinking level is set to ${thinkingLevel}` };\n\t}\n\n\t// Long conversation -> complex\n\tif (messages.length > LONG_CONVERSATION_THRESHOLD) {\n\t\treturn { tier: \"powerful\", reason: `long conversation (${messages.length} messages)` };\n\t}\n\n\t// Find the last assistant message and its tool results\n\tlet lastAssistantIndex = -1;\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tif (isAssistantMessage(messages[i])) {\n\t\t\tlastAssistantIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Find the last user message\n\tlet lastUserMessage: UserMessage | undefined;\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tif (isUserMessage(messages[i])) {\n\t\t\tlastUserMessage = messages[i] as UserMessage;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Check for complex signals from the last assistant turn\n\tif (lastAssistantIndex >= 0) {\n\t\tconst lastAssistant = messages[lastAssistantIndex] as AssistantMessage;\n\t\tconst toolCalls = getToolCalls(lastAssistant);\n\t\tconst toolResults = getToolResultsAfter(messages, lastAssistantIndex);\n\n\t\t// Errors in last turn -> complex\n\t\tconst hasErrors = toolResults.some((tr) => tr.isError);\n\t\tif (hasErrors) {\n\t\t\treturn { tier: \"powerful\", reason: \"tool errors in last turn\" };\n\t\t}\n\n\t\t// Many file edits in last turn -> complex\n\t\tif (countFileEditCalls(toolCalls) > MANY_EDITS_THRESHOLD) {\n\t\t\treturn { tier: \"powerful\", reason: `many file edits in last turn (${countFileEditCalls(toolCalls)})` };\n\t\t}\n\n\t\t// All read-only tools and no errors -> check for simple\n\t\tif (allToolCallsReadOnly(toolCalls) && !hasErrors) {\n\t\t\t// If the last user message is also short and simple, use fast tier\n\t\t\tif (lastUserMessage) {\n\t\t\t\tconst text = getUserMessageText(lastUserMessage);\n\t\t\t\tif (text.length < SHORT_MESSAGE_THRESHOLD && !containsComplexKeyword(text)) {\n\t\t\t\t\treturn { tier: \"fast\", reason: \"read-only tools with short user message\" };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check user message for complex keywords\n\tif (lastUserMessage) {\n\t\tconst text = getUserMessageText(lastUserMessage);\n\t\tif (containsComplexKeyword(text)) {\n\t\t\treturn { tier: \"powerful\", reason: \"complex keywords in user message\" };\n\t\t}\n\n\t\t// Short question with no prior assistant context -> fast\n\t\tif (lastAssistantIndex < 0 && text.length < SHORT_MESSAGE_THRESHOLD) {\n\t\t\treturn { tier: \"fast\", reason: \"short initial message\" };\n\t\t}\n\t}\n\n\treturn { tier: \"balanced\", reason: \"default\" };\n}\n\n// ============================================================================\n// Model selection\n// ============================================================================\n\n/** Select the best model for a given complexity tier from available models. */\nexport function selectModelForTier(tier: ComplexityTier, config: SmartRouterConfig): Model<Api> {\n\tconst { availableModels, preferredModel } = config;\n\n\t// Partition models into tiers\n\tconst tierModels = availableModels.filter((m) => modelTier(m) === tier);\n\n\tif (tierModels.length === 0) {\n\t\t// Requested tier has no models, fall back to preferred\n\t\treturn preferredModel;\n\t}\n\n\t// Pick the model with the largest context window (best value within tier)\n\tlet best = tierModels[0];\n\tfor (let i = 1; i < tierModels.length; i++) {\n\t\tif (tierModels[i].contextWindow > best.contextWindow) {\n\t\t\tbest = tierModels[i];\n\t\t}\n\t}\n\treturn best;\n}\n\n// ============================================================================\n// Main entry\n// ============================================================================\n\n/**\n * Analyze the turn and return a model recommendation.\n *\n * Returns undefined when:\n * - Smart routing is disabled\n * - The selected model is the same as the preferred model (no change needed)\n */\nexport function routeNextTurn(analysis: TurnAnalysis, config: SmartRouterConfig): SmartRouterResult | undefined {\n\tif (!config.enabled) return undefined;\n\n\tconst { tier, reason } = classifyComplexity(analysis);\n\tconst model = selectModelForTier(tier, config);\n\n\t// No change needed if the router picks the same model the user already has\n\tif (modelsAreEqual(model, config.preferredModel)) return undefined;\n\n\treturn { model, tier, reason };\n}\n"]}
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Smart model routing for automatic tier-based model selection.
3
+ *
4
+ * Analyzes conversation signals after each turn and selects the optimal model
5
+ * tier (fast/balanced/powerful) for the next turn based on task complexity.
6
+ */
7
+ import { modelsAreEqual } from "@elyracode/ai";
8
+ // ============================================================================
9
+ // Constants
10
+ // ============================================================================
11
+ /** Output cost thresholds ($/million tokens) for tier classification. */
12
+ const TIER_1_MAX_COST = 3;
13
+ const TIER_3_MIN_COST = 20;
14
+ /** Tool names considered read-only (no side effects). */
15
+ const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]);
16
+ /** Keywords in user messages that signal complex work. */
17
+ const COMPLEX_KEYWORDS = [
18
+ "refactor",
19
+ "architect",
20
+ "redesign",
21
+ "migrate",
22
+ "rewrite",
23
+ "debug",
24
+ "fix the bug",
25
+ "security audit",
26
+ ];
27
+ /** Short user message threshold (characters). */
28
+ const SHORT_MESSAGE_THRESHOLD = 100;
29
+ /** Message count threshold for complex multi-step tasks. */
30
+ const LONG_CONVERSATION_THRESHOLD = 20;
31
+ /** File edit count threshold per turn for complexity escalation. */
32
+ const MANY_EDITS_THRESHOLD = 3;
33
+ // ============================================================================
34
+ // Helpers
35
+ // ============================================================================
36
+ function isUserMessage(msg) {
37
+ return "role" in msg && msg.role === "user";
38
+ }
39
+ function isAssistantMessage(msg) {
40
+ return "role" in msg && msg.role === "assistant";
41
+ }
42
+ function isToolResultMessage(msg) {
43
+ return "role" in msg && msg.role === "toolResult";
44
+ }
45
+ /** Extract the plain-text content of a user message. */
46
+ function getUserMessageText(msg) {
47
+ if (typeof msg.content === "string")
48
+ return msg.content;
49
+ return msg.content
50
+ .filter((c) => c.type === "text")
51
+ .map((c) => c.text)
52
+ .join(" ");
53
+ }
54
+ /** Extract tool calls from an assistant message's content. */
55
+ function getToolCalls(msg) {
56
+ return msg.content.filter((c) => c.type === "toolCall");
57
+ }
58
+ /** True when all tool calls in a message are read-only. */
59
+ function allToolCallsReadOnly(toolCalls) {
60
+ return toolCalls.length > 0 && toolCalls.every((tc) => READ_ONLY_TOOLS.has(tc.name));
61
+ }
62
+ /** Count write/edit tool calls in an assistant message. */
63
+ function countFileEditCalls(toolCalls) {
64
+ return toolCalls.filter((tc) => tc.name === "write" || tc.name === "edit").length;
65
+ }
66
+ /**
67
+ * Collect tool result messages that follow an assistant message.
68
+ * Walks forward from the assistant message index, collecting consecutive
69
+ * tool results (there may be other message types interleaved in custom
70
+ * AgentMessage streams, so we stop at the next user or assistant message).
71
+ */
72
+ function getToolResultsAfter(messages, assistantIndex) {
73
+ const results = [];
74
+ for (let i = assistantIndex + 1; i < messages.length; i++) {
75
+ const msg = messages[i];
76
+ if (isUserMessage(msg) || isAssistantMessage(msg))
77
+ break;
78
+ if (isToolResultMessage(msg))
79
+ results.push(msg);
80
+ }
81
+ return results;
82
+ }
83
+ /** True when the text contains any of the complex keywords (case-insensitive). */
84
+ function containsComplexKeyword(text) {
85
+ const lower = text.toLowerCase();
86
+ return COMPLEX_KEYWORDS.some((kw) => lower.includes(kw));
87
+ }
88
+ // ============================================================================
89
+ // Tier classification
90
+ // ============================================================================
91
+ /** Classify a model into its cost tier. */
92
+ function modelTier(model) {
93
+ const cost = model.cost.output;
94
+ if (cost < TIER_1_MAX_COST)
95
+ return "fast";
96
+ if (cost < TIER_3_MIN_COST)
97
+ return "balanced";
98
+ return "powerful";
99
+ }
100
+ /** Classify the complexity tier for the next turn. */
101
+ export function classifyComplexity(analysis) {
102
+ const { messages, thinkingLevel } = analysis;
103
+ // High thinking level -> complex
104
+ if (thinkingLevel === "high" || thinkingLevel === "xhigh") {
105
+ return { tier: "powerful", reason: `thinking level is set to ${thinkingLevel}` };
106
+ }
107
+ // Long conversation -> complex
108
+ if (messages.length > LONG_CONVERSATION_THRESHOLD) {
109
+ return { tier: "powerful", reason: `long conversation (${messages.length} messages)` };
110
+ }
111
+ // Find the last assistant message and its tool results
112
+ let lastAssistantIndex = -1;
113
+ for (let i = messages.length - 1; i >= 0; i--) {
114
+ if (isAssistantMessage(messages[i])) {
115
+ lastAssistantIndex = i;
116
+ break;
117
+ }
118
+ }
119
+ // Find the last user message
120
+ let lastUserMessage;
121
+ for (let i = messages.length - 1; i >= 0; i--) {
122
+ if (isUserMessage(messages[i])) {
123
+ lastUserMessage = messages[i];
124
+ break;
125
+ }
126
+ }
127
+ // Check for complex signals from the last assistant turn
128
+ if (lastAssistantIndex >= 0) {
129
+ const lastAssistant = messages[lastAssistantIndex];
130
+ const toolCalls = getToolCalls(lastAssistant);
131
+ const toolResults = getToolResultsAfter(messages, lastAssistantIndex);
132
+ // Errors in last turn -> complex
133
+ const hasErrors = toolResults.some((tr) => tr.isError);
134
+ if (hasErrors) {
135
+ return { tier: "powerful", reason: "tool errors in last turn" };
136
+ }
137
+ // Many file edits in last turn -> complex
138
+ if (countFileEditCalls(toolCalls) > MANY_EDITS_THRESHOLD) {
139
+ return { tier: "powerful", reason: `many file edits in last turn (${countFileEditCalls(toolCalls)})` };
140
+ }
141
+ // All read-only tools and no errors -> check for simple
142
+ if (allToolCallsReadOnly(toolCalls) && !hasErrors) {
143
+ // If the last user message is also short and simple, use fast tier
144
+ if (lastUserMessage) {
145
+ const text = getUserMessageText(lastUserMessage);
146
+ if (text.length < SHORT_MESSAGE_THRESHOLD && !containsComplexKeyword(text)) {
147
+ return { tier: "fast", reason: "read-only tools with short user message" };
148
+ }
149
+ }
150
+ }
151
+ }
152
+ // Check user message for complex keywords
153
+ if (lastUserMessage) {
154
+ const text = getUserMessageText(lastUserMessage);
155
+ if (containsComplexKeyword(text)) {
156
+ return { tier: "powerful", reason: "complex keywords in user message" };
157
+ }
158
+ // Short question with no prior assistant context -> fast
159
+ if (lastAssistantIndex < 0 && text.length < SHORT_MESSAGE_THRESHOLD) {
160
+ return { tier: "fast", reason: "short initial message" };
161
+ }
162
+ }
163
+ return { tier: "balanced", reason: "default" };
164
+ }
165
+ // ============================================================================
166
+ // Model selection
167
+ // ============================================================================
168
+ /** Select the best model for a given complexity tier from available models. */
169
+ export function selectModelForTier(tier, config) {
170
+ const { availableModels, preferredModel } = config;
171
+ // Partition models into tiers
172
+ const tierModels = availableModels.filter((m) => modelTier(m) === tier);
173
+ if (tierModels.length === 0) {
174
+ // Requested tier has no models, fall back to preferred
175
+ return preferredModel;
176
+ }
177
+ // Pick the model with the largest context window (best value within tier)
178
+ let best = tierModels[0];
179
+ for (let i = 1; i < tierModels.length; i++) {
180
+ if (tierModels[i].contextWindow > best.contextWindow) {
181
+ best = tierModels[i];
182
+ }
183
+ }
184
+ return best;
185
+ }
186
+ // ============================================================================
187
+ // Main entry
188
+ // ============================================================================
189
+ /**
190
+ * Analyze the turn and return a model recommendation.
191
+ *
192
+ * Returns undefined when:
193
+ * - Smart routing is disabled
194
+ * - The selected model is the same as the preferred model (no change needed)
195
+ */
196
+ export function routeNextTurn(analysis, config) {
197
+ if (!config.enabled)
198
+ return undefined;
199
+ const { tier, reason } = classifyComplexity(analysis);
200
+ const model = selectModelForTier(tier, config);
201
+ // No change needed if the router picks the same model the user already has
202
+ if (modelsAreEqual(model, config.preferredModel))
203
+ return undefined;
204
+ return { model, tier, reason };
205
+ }
206
+ //# sourceMappingURL=smart-router.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"smart-router.js","sourceRoot":"","sources":["../../src/core/smart-router.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AA6B/C,+EAA+E;AAC/E,YAAY;AACZ,+EAA+E;AAE/E,yEAAyE;AACzE,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B,yDAAyD;AACzD,MAAM,eAAe,GAAwB,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;AAErF,0DAA0D;AAC1D,MAAM,gBAAgB,GAAsB;IAC3C,UAAU;IACV,WAAW;IACX,UAAU;IACV,SAAS;IACT,SAAS;IACT,OAAO;IACP,aAAa;IACb,gBAAgB;CAChB,CAAC;AAEF,iDAAiD;AACjD,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC,4DAA4D;AAC5D,MAAM,2BAA2B,GAAG,EAAE,CAAC;AAEvC,oEAAoE;AACpE,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAE/B,+EAA+E;AAC/E,UAAU;AAC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AE,GAAG,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IACtD,MAAM,KAAK,GAAG,kBAAkB,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IAE/C,2EAA2E;IAC3E,IAAI,cAAc,CAAC,KAAK,EAAE,MAAM,CAAC,cAAc,CAAC;QAAE,OAAO,SAAS,CAAC;IAEnE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAAA,CAC/B","sourcesContent":["/**\n * Smart model routing for automatic tier-based model selection.\n *\n * Analyzes conversation signals after each turn and selects the optimal model\n * tier (fast/balanced/powerful) for the next turn based on task complexity.\n */\n\nimport type { AgentMessage, ThinkingLevel } from \"@elyracode/agent-core\";\nimport type { Api, AssistantMessage, Model, ToolCall, ToolResultMessage, UserMessage } from \"@elyracode/ai\";\nimport { modelsAreEqual } from \"@elyracode/ai\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface SmartRouterConfig {\n\tenabled: boolean;\n\t/** Available models the router can pick from. Must have at least one. */\n\tavailableModels: Model<Api>[];\n\t/** The user's preferred/current model -- used as the Tier 2 default and fallback. */\n\tpreferredModel: Model<Api>;\n}\n\nexport interface TurnAnalysis {\n\t/** The messages in the conversation so far. */\n\tmessages: AgentMessage[];\n\t/** Current thinking level. */\n\tthinkingLevel: ThinkingLevel;\n}\n\nexport type ComplexityTier = \"fast\" | \"balanced\" | \"powerful\";\n\nexport interface SmartRouterResult {\n\tmodel: Model<Api>;\n\ttier: ComplexityTier;\n\treason: string;\n}\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Output cost thresholds ($/million tokens) for tier classification. */\nconst TIER_1_MAX_COST = 3;\nconst TIER_3_MIN_COST = 20;\n\n/** Tool names considered read-only (no side effects). */\nconst READ_ONLY_TOOLS: ReadonlySet<string> = new Set([\"read\", \"grep\", \"find\", \"ls\"]);\n\n/** Keywords in user messages that signal complex work. */\nconst COMPLEX_KEYWORDS: readonly string[] = [\n\t\"refactor\",\n\t\"architect\",\n\t\"redesign\",\n\t\"migrate\",\n\t\"rewrite\",\n\t\"debug\",\n\t\"fix the bug\",\n\t\"security audit\",\n];\n\n/** Short user message threshold (characters). */\nconst SHORT_MESSAGE_THRESHOLD = 100;\n\n/** Message count threshold for complex multi-step tasks. */\nconst LONG_CONVERSATION_THRESHOLD = 20;\n\n/** File edit count threshold per turn for complexity escalation. */\nconst MANY_EDITS_THRESHOLD = 3;\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction isUserMessage(msg: AgentMessage): msg is UserMessage {\n\treturn \"role\" in msg && (msg as UserMessage).role === \"user\";\n}\n\nfunction isAssistantMessage(msg: AgentMessage): msg is AssistantMessage {\n\treturn \"role\" in msg && (msg as AssistantMessage).role === \"assistant\";\n}\n\nfunction isToolResultMessage(msg: AgentMessage): msg is ToolResultMessage {\n\treturn \"role\" in msg && (msg as ToolResultMessage).role === \"toolResult\";\n}\n\n/** Extract the plain-text content of a user message. */\nfunction getUserMessageText(msg: UserMessage): string {\n\tif (typeof msg.content === \"string\") return msg.content;\n\treturn msg.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\" \");\n}\n\n/** Extract tool calls from an assistant message's content. */\nfunction getToolCalls(msg: AssistantMessage): ToolCall[] {\n\treturn msg.content.filter((c): c is ToolCall => c.type === \"toolCall\");\n}\n\n/** True when all tool calls in a message are read-only. */\nfunction allToolCallsReadOnly(toolCalls: ToolCall[]): boolean {\n\treturn toolCalls.length > 0 && toolCalls.every((tc) => READ_ONLY_TOOLS.has(tc.name));\n}\n\n/** Count write/edit tool calls in an assistant message. */\nfunction countFileEditCalls(toolCalls: ToolCall[]): number {\n\treturn toolCalls.filter((tc) => tc.name === \"write\" || tc.name === \"edit\").length;\n}\n\n/**\n * Collect tool result messages that follow an assistant message.\n * Walks forward from the assistant message index, collecting consecutive\n * tool results (there may be other message types interleaved in custom\n * AgentMessage streams, so we stop at the next user or assistant message).\n */\nfunction getToolResultsAfter(messages: AgentMessage[], assistantIndex: number): ToolResultMessage[] {\n\tconst results: ToolResultMessage[] = [];\n\tfor (let i = assistantIndex + 1; i < messages.length; i++) {\n\t\tconst msg = messages[i];\n\t\tif (isUserMessage(msg) || isAssistantMessage(msg)) break;\n\t\tif (isToolResultMessage(msg)) results.push(msg);\n\t}\n\treturn results;\n}\n\n/** True when the text contains any of the complex keywords (case-insensitive). */\nfunction containsComplexKeyword(text: string): boolean {\n\tconst lower = text.toLowerCase();\n\treturn COMPLEX_KEYWORDS.some((kw) => lower.includes(kw));\n}\n\n// ============================================================================\n// Tier classification\n// ============================================================================\n\n/** Classify a model into its cost tier. */\nfunction modelTier(model: Model<Api>): ComplexityTier {\n\tconst cost = model.cost.output;\n\tif (cost < TIER_1_MAX_COST) return \"fast\";\n\tif (cost < TIER_3_MIN_COST) return \"balanced\";\n\treturn \"powerful\";\n}\n\n/** Classify the complexity tier for the next turn. */\nexport function classifyComplexity(analysis: TurnAnalysis): { tier: ComplexityTier; reason: string } {\n\tconst { messages, thinkingLevel } = analysis;\n\n\t// High thinking level -> complex\n\tif (thinkingLevel === \"high\" || thinkingLevel === \"xhigh\") {\n\t\treturn { tier: \"powerful\", reason: `thinking level is set to ${thinkingLevel}` };\n\t}\n\n\t// Long conversation -> complex\n\tif (messages.length > LONG_CONVERSATION_THRESHOLD) {\n\t\treturn { tier: \"powerful\", reason: `long conversation (${messages.length} messages)` };\n\t}\n\n\t// Find the last assistant message and its tool results\n\tlet lastAssistantIndex = -1;\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tif (isAssistantMessage(messages[i])) {\n\t\t\tlastAssistantIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Find the last user message\n\tlet lastUserMessage: UserMessage | undefined;\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tif (isUserMessage(messages[i])) {\n\t\t\tlastUserMessage = messages[i] as UserMessage;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Check for complex signals from the last assistant turn\n\tif (lastAssistantIndex >= 0) {\n\t\tconst lastAssistant = messages[lastAssistantIndex] as AssistantMessage;\n\t\tconst toolCalls = getToolCalls(lastAssistant);\n\t\tconst toolResults = getToolResultsAfter(messages, lastAssistantIndex);\n\n\t\t// Errors in last turn -> complex\n\t\tconst hasErrors = toolResults.some((tr) => tr.isError);\n\t\tif (hasErrors) {\n\t\t\treturn { tier: \"powerful\", reason: \"tool errors in last turn\" };\n\t\t}\n\n\t\t// Many file edits in last turn -> complex\n\t\tif (countFileEditCalls(toolCalls) > MANY_EDITS_THRESHOLD) {\n\t\t\treturn { tier: \"powerful\", reason: `many file edits in last turn (${countFileEditCalls(toolCalls)})` };\n\t\t}\n\n\t\t// All read-only tools and no errors -> check for simple\n\t\tif (allToolCallsReadOnly(toolCalls) && !hasErrors) {\n\t\t\t// If the last user message is also short and simple, use fast tier\n\t\t\tif (lastUserMessage) {\n\t\t\t\tconst text = getUserMessageText(lastUserMessage);\n\t\t\t\tif (text.length < SHORT_MESSAGE_THRESHOLD && !containsComplexKeyword(text)) {\n\t\t\t\t\treturn { tier: \"fast\", reason: \"read-only tools with short user message\" };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check user message for complex keywords\n\tif (lastUserMessage) {\n\t\tconst text = getUserMessageText(lastUserMessage);\n\t\tif (containsComplexKeyword(text)) {\n\t\t\treturn { tier: \"powerful\", reason: \"complex keywords in user message\" };\n\t\t}\n\n\t\t// Short question with no prior assistant context -> fast\n\t\tif (lastAssistantIndex < 0 && text.length < SHORT_MESSAGE_THRESHOLD) {\n\t\t\treturn { tier: \"fast\", reason: \"short initial message\" };\n\t\t}\n\t}\n\n\treturn { tier: \"balanced\", reason: \"default\" };\n}\n\n// ============================================================================\n// Model selection\n// ============================================================================\n\n/** Select the best model for a given complexity tier from available models. */\nexport function selectModelForTier(tier: ComplexityTier, config: SmartRouterConfig): Model<Api> {\n\tconst { availableModels, preferredModel } = config;\n\n\t// Partition models into tiers\n\tconst tierModels = availableModels.filter((m) => modelTier(m) === tier);\n\n\tif (tierModels.length === 0) {\n\t\t// Requested tier has no models, fall back to preferred\n\t\treturn preferredModel;\n\t}\n\n\t// Pick the model with the largest context window (best value within tier)\n\tlet best = tierModels[0];\n\tfor (let i = 1; i < tierModels.length; i++) {\n\t\tif (tierModels[i].contextWindow > best.contextWindow) {\n\t\t\tbest = tierModels[i];\n\t\t}\n\t}\n\treturn best;\n}\n\n// ============================================================================\n// Main entry\n// ============================================================================\n\n/**\n * Analyze the turn and return a model recommendation.\n *\n * Returns undefined when:\n * - Smart routing is disabled\n * - The selected model is the same as the preferred model (no change needed)\n */\nexport function routeNextTurn(analysis: TurnAnalysis, config: SmartRouterConfig): SmartRouterResult | undefined {\n\tif (!config.enabled) return undefined;\n\n\tconst { tier, reason } = classifyComplexity(analysis);\n\tconst model = selectModelForTier(tier, config);\n\n\t// No change needed if the router picks the same model the user already has\n\tif (modelsAreEqual(model, config.preferredModel)) return undefined;\n\n\treturn { model, tier, reason };\n}\n"]}
@@ -0,0 +1,21 @@
1
+ /** Individual framework detected in the project */
2
+ export interface DetectedFramework {
3
+ name: string;
4
+ version?: string;
5
+ }
6
+ /** Known stack profiles that can be suggested for installation */
7
+ export type KnownStack = "TALL" | "VILT";
8
+ /** Result of stack detection */
9
+ export interface StackDetectionResult {
10
+ /** All detected frameworks */
11
+ frameworks: DetectedFramework[];
12
+ /** Recognized stack profile (if frameworks match a known combination) */
13
+ stack?: KnownStack;
14
+ /** Human-readable summary for system prompt injection */
15
+ summary: string;
16
+ }
17
+ /** Detect the technology stack in a project directory */
18
+ export declare function detectStack(cwd: string): StackDetectionResult;
19
+ /** Get the suggested package name for a detected stack */
20
+ export declare function getSuggestedPackage(stack: KnownStack): string;
21
+ //# sourceMappingURL=stack-detector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stack-detector.d.ts","sourceRoot":"","sources":["../../src/core/stack-detector.ts"],"names":[],"mappings":"AAGA,mDAAmD;AACnD,MAAM,WAAW,iBAAiB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,kEAAkE;AAClE,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,MAAM,CAAC;AAEzC,gCAAgC;AAChC,MAAM,WAAW,oBAAoB;IACpC,8BAA8B;IAC9B,UAAU,EAAE,iBAAiB,EAAE,CAAC;IAChC,yEAAyE;IACzE,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB,yDAAyD;IACzD,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,yDAAyD;AACzD,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,oBAAoB,CA2G7D;AASD,0DAA0D;AAC1D,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAO7D","sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/** Individual framework detected in the project */\nexport interface DetectedFramework {\n\tname: string;\n\tversion?: string;\n}\n\n/** Known stack profiles that can be suggested for installation */\nexport type KnownStack = \"TALL\" | \"VILT\";\n\n/** Result of stack detection */\nexport interface StackDetectionResult {\n\t/** All detected frameworks */\n\tframeworks: DetectedFramework[];\n\t/** Recognized stack profile (if frameworks match a known combination) */\n\tstack?: KnownStack;\n\t/** Human-readable summary for system prompt injection */\n\tsummary: string;\n}\n\n/** Detect the technology stack in a project directory */\nexport function detectStack(cwd: string): StackDetectionResult {\n\tconst frameworks: DetectedFramework[] = [];\n\n\t// Parse composer.json for PHP/Laravel dependencies\n\tconst composerPath = join(cwd, \"composer.json\");\n\tif (existsSync(composerPath)) {\n\t\ttry {\n\t\t\tconst composer = JSON.parse(readFileSync(composerPath, \"utf-8\"));\n\t\t\tconst deps = { ...composer.require, ...composer[\"require-dev\"] };\n\n\t\t\tif (deps[\"laravel/framework\"]) {\n\t\t\t\tframeworks.push({ name: \"Laravel\", version: extractVersion(deps[\"laravel/framework\"]) });\n\t\t\t}\n\t\t\tif (deps[\"livewire/livewire\"]) {\n\t\t\t\tframeworks.push({ name: \"Livewire\", version: extractVersion(deps[\"livewire/livewire\"]) });\n\t\t\t}\n\t\t\tif (deps[\"livewire/flux\"]) {\n\t\t\t\tframeworks.push({ name: \"Flux UI\", version: extractVersion(deps[\"livewire/flux\"]) });\n\t\t\t}\n\t\t\tif (deps[\"inertiajs/inertia-laravel\"]) {\n\t\t\t\tframeworks.push({ name: \"Inertia\", version: extractVersion(deps[\"inertiajs/inertia-laravel\"]) });\n\t\t\t}\n\t\t\tif (deps[\"laravel/reverb\"]) {\n\t\t\t\tframeworks.push({ name: \"Reverb\", version: extractVersion(deps[\"laravel/reverb\"]) });\n\t\t\t}\n\t\t\tif (deps[\"laravel/sanctum\"]) {\n\t\t\t\tframeworks.push({ name: \"Sanctum\", version: extractVersion(deps[\"laravel/sanctum\"]) });\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore malformed composer.json\n\t\t}\n\t}\n\n\t// Parse package.json for JS/frontend dependencies\n\tconst packagePath = join(cwd, \"package.json\");\n\tif (existsSync(packagePath)) {\n\t\ttry {\n\t\t\tconst pkg = JSON.parse(readFileSync(packagePath, \"utf-8\"));\n\t\t\tconst deps = { ...pkg.dependencies, ...pkg.devDependencies };\n\n\t\t\tif (deps.vue) {\n\t\t\t\tframeworks.push({ name: \"Vue\", version: extractVersion(deps.vue) });\n\t\t\t}\n\t\t\tif (deps.alpinejs) {\n\t\t\t\tframeworks.push({ name: \"Alpine.js\", version: extractVersion(deps.alpinejs) });\n\t\t\t}\n\t\t\tif (deps.tailwindcss) {\n\t\t\t\tframeworks.push({ name: \"Tailwind CSS\", version: extractVersion(deps.tailwindcss) });\n\t\t\t}\n\t\t\tif (\n\t\t\t\tdeps[\"@inertiajs/vue3\"] ||\n\t\t\t\tdeps[\"@inertiajs/vue2\"] ||\n\t\t\t\tdeps[\"@inertiajs/react\"] ||\n\t\t\t\tdeps[\"@inertiajs/svelte\"]\n\t\t\t) {\n\t\t\t\t// Inertia frontend adapter -- version from whichever is present\n\t\t\t\tconst inertiaFe =\n\t\t\t\t\tdeps[\"@inertiajs/vue3\"] ||\n\t\t\t\t\tdeps[\"@inertiajs/vue2\"] ||\n\t\t\t\t\tdeps[\"@inertiajs/react\"] ||\n\t\t\t\t\tdeps[\"@inertiajs/svelte\"];\n\t\t\t\tif (!frameworks.some((f) => f.name === \"Inertia\")) {\n\t\t\t\t\tframeworks.push({ name: \"Inertia\", version: extractVersion(inertiaFe) });\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (deps.react || deps[\"react-dom\"]) {\n\t\t\t\tframeworks.push({ name: \"React\", version: extractVersion(deps.react || deps[\"react-dom\"]) });\n\t\t\t}\n\t\t\tif (deps.svelte) {\n\t\t\t\tframeworks.push({ name: \"Svelte\", version: extractVersion(deps.svelte) });\n\t\t\t}\n\t\t\tif (deps.typescript) {\n\t\t\t\tframeworks.push({ name: \"TypeScript\", version: extractVersion(deps.typescript) });\n\t\t\t}\n\t\t\tif (deps.vite) {\n\t\t\t\tframeworks.push({ name: \"Vite\", version: extractVersion(deps.vite) });\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore malformed package.json\n\t\t}\n\t}\n\n\tif (frameworks.length === 0) {\n\t\treturn { frameworks, summary: \"\" };\n\t}\n\n\t// Detect known stack profiles\n\tconst has = (name: string) => frameworks.some((f) => f.name === name);\n\tlet stack: KnownStack | undefined;\n\n\tif (has(\"Laravel\") && has(\"Tailwind CSS\") && has(\"Alpine.js\") && has(\"Livewire\")) {\n\t\tstack = \"TALL\";\n\t} else if (has(\"Laravel\") && has(\"Tailwind CSS\") && has(\"Inertia\") && has(\"Vue\")) {\n\t\tstack = \"VILT\";\n\t}\n\n\t// Build human-readable summary\n\tconst frameworkList = frameworks.map((f) => (f.version ? `${f.name} ${f.version}` : f.name)).join(\", \");\n\tlet summary = `Detected frameworks: ${frameworkList}`;\n\tif (stack === \"TALL\") {\n\t\tconst hasFlux = has(\"Flux UI\");\n\t\tsummary = `TALL stack project (Tailwind, Alpine.js, Laravel, Livewire${hasFlux ? \", Flux UI\" : \"\"}).\\n${frameworkList}`;\n\t} else if (stack === \"VILT\") {\n\t\tsummary = `VILT stack project (Vue, Inertia, Laravel, Tailwind).\\n${frameworkList}`;\n\t}\n\n\treturn { frameworks, stack, summary };\n}\n\n/** Strip semver constraint prefixes (^, ~, >=, etc.) to get a clean version */\nfunction extractVersion(constraint: string | undefined): string | undefined {\n\tif (!constraint) return undefined;\n\tconst match = constraint.match(/(\\d+\\.\\d+(?:\\.\\d+)?)/);\n\treturn match?.[1];\n}\n\n/** Get the suggested package name for a detected stack */\nexport function getSuggestedPackage(stack: KnownStack): string {\n\tswitch (stack) {\n\t\tcase \"TALL\":\n\t\t\treturn \"@elyracode/stack-tall\";\n\t\tcase \"VILT\":\n\t\t\treturn \"@elyracode/stack-vilt\";\n\t}\n}\n"]}
@@ -0,0 +1,120 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ /** Detect the technology stack in a project directory */
4
+ export function detectStack(cwd) {
5
+ const frameworks = [];
6
+ // Parse composer.json for PHP/Laravel dependencies
7
+ const composerPath = join(cwd, "composer.json");
8
+ if (existsSync(composerPath)) {
9
+ try {
10
+ const composer = JSON.parse(readFileSync(composerPath, "utf-8"));
11
+ const deps = { ...composer.require, ...composer["require-dev"] };
12
+ if (deps["laravel/framework"]) {
13
+ frameworks.push({ name: "Laravel", version: extractVersion(deps["laravel/framework"]) });
14
+ }
15
+ if (deps["livewire/livewire"]) {
16
+ frameworks.push({ name: "Livewire", version: extractVersion(deps["livewire/livewire"]) });
17
+ }
18
+ if (deps["livewire/flux"]) {
19
+ frameworks.push({ name: "Flux UI", version: extractVersion(deps["livewire/flux"]) });
20
+ }
21
+ if (deps["inertiajs/inertia-laravel"]) {
22
+ frameworks.push({ name: "Inertia", version: extractVersion(deps["inertiajs/inertia-laravel"]) });
23
+ }
24
+ if (deps["laravel/reverb"]) {
25
+ frameworks.push({ name: "Reverb", version: extractVersion(deps["laravel/reverb"]) });
26
+ }
27
+ if (deps["laravel/sanctum"]) {
28
+ frameworks.push({ name: "Sanctum", version: extractVersion(deps["laravel/sanctum"]) });
29
+ }
30
+ }
31
+ catch {
32
+ // Ignore malformed composer.json
33
+ }
34
+ }
35
+ // Parse package.json for JS/frontend dependencies
36
+ const packagePath = join(cwd, "package.json");
37
+ if (existsSync(packagePath)) {
38
+ try {
39
+ const pkg = JSON.parse(readFileSync(packagePath, "utf-8"));
40
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
41
+ if (deps.vue) {
42
+ frameworks.push({ name: "Vue", version: extractVersion(deps.vue) });
43
+ }
44
+ if (deps.alpinejs) {
45
+ frameworks.push({ name: "Alpine.js", version: extractVersion(deps.alpinejs) });
46
+ }
47
+ if (deps.tailwindcss) {
48
+ frameworks.push({ name: "Tailwind CSS", version: extractVersion(deps.tailwindcss) });
49
+ }
50
+ if (deps["@inertiajs/vue3"] ||
51
+ deps["@inertiajs/vue2"] ||
52
+ deps["@inertiajs/react"] ||
53
+ deps["@inertiajs/svelte"]) {
54
+ // Inertia frontend adapter -- version from whichever is present
55
+ const inertiaFe = deps["@inertiajs/vue3"] ||
56
+ deps["@inertiajs/vue2"] ||
57
+ deps["@inertiajs/react"] ||
58
+ deps["@inertiajs/svelte"];
59
+ if (!frameworks.some((f) => f.name === "Inertia")) {
60
+ frameworks.push({ name: "Inertia", version: extractVersion(inertiaFe) });
61
+ }
62
+ }
63
+ if (deps.react || deps["react-dom"]) {
64
+ frameworks.push({ name: "React", version: extractVersion(deps.react || deps["react-dom"]) });
65
+ }
66
+ if (deps.svelte) {
67
+ frameworks.push({ name: "Svelte", version: extractVersion(deps.svelte) });
68
+ }
69
+ if (deps.typescript) {
70
+ frameworks.push({ name: "TypeScript", version: extractVersion(deps.typescript) });
71
+ }
72
+ if (deps.vite) {
73
+ frameworks.push({ name: "Vite", version: extractVersion(deps.vite) });
74
+ }
75
+ }
76
+ catch {
77
+ // Ignore malformed package.json
78
+ }
79
+ }
80
+ if (frameworks.length === 0) {
81
+ return { frameworks, summary: "" };
82
+ }
83
+ // Detect known stack profiles
84
+ const has = (name) => frameworks.some((f) => f.name === name);
85
+ let stack;
86
+ if (has("Laravel") && has("Tailwind CSS") && has("Alpine.js") && has("Livewire")) {
87
+ stack = "TALL";
88
+ }
89
+ else if (has("Laravel") && has("Tailwind CSS") && has("Inertia") && has("Vue")) {
90
+ stack = "VILT";
91
+ }
92
+ // Build human-readable summary
93
+ const frameworkList = frameworks.map((f) => (f.version ? `${f.name} ${f.version}` : f.name)).join(", ");
94
+ let summary = `Detected frameworks: ${frameworkList}`;
95
+ if (stack === "TALL") {
96
+ const hasFlux = has("Flux UI");
97
+ summary = `TALL stack project (Tailwind, Alpine.js, Laravel, Livewire${hasFlux ? ", Flux UI" : ""}).\n${frameworkList}`;
98
+ }
99
+ else if (stack === "VILT") {
100
+ summary = `VILT stack project (Vue, Inertia, Laravel, Tailwind).\n${frameworkList}`;
101
+ }
102
+ return { frameworks, stack, summary };
103
+ }
104
+ /** Strip semver constraint prefixes (^, ~, >=, etc.) to get a clean version */
105
+ function extractVersion(constraint) {
106
+ if (!constraint)
107
+ return undefined;
108
+ const match = constraint.match(/(\d+\.\d+(?:\.\d+)?)/);
109
+ return match?.[1];
110
+ }
111
+ /** Get the suggested package name for a detected stack */
112
+ export function getSuggestedPackage(stack) {
113
+ switch (stack) {
114
+ case "TALL":
115
+ return "@elyracode/stack-tall";
116
+ case "VILT":
117
+ return "@elyracode/stack-vilt";
118
+ }
119
+ }
120
+ //# sourceMappingURL=stack-detector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stack-detector.js","sourceRoot":"","sources":["../../src/core/stack-detector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAqBjC,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AAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxG,IAAI,OAAO,GAAG,wBAAwB,aAAa,EAAE,CAAC;IACtD,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;QACtB,MAAM,OAAO,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC;QAC/B,OAAO,GAAG,6DAA6D,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,OAAO,aAAa,EAAE,CAAC;IACzH,CAAC;SAAM,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;QAC7B,OAAO,GAAG,0DAA0D,aAAa,EAAE,CAAC;IACrF,CAAC;IAED,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;AAAA,CACtC;AAED,+EAA+E;AAC/E,SAAS,cAAc,CAAC,UAA8B,EAAsB;IAC3E,IAAI,CAAC,UAAU;QAAE,OAAO,SAAS,CAAC;IAClC,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,sBAAsB,CAAC,CAAC;IACvD,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;AAAA,CAClB;AAED,0DAA0D;AAC1D,MAAM,UAAU,mBAAmB,CAAC,KAAiB,EAAU;IAC9D,QAAQ,KAAK,EAAE,CAAC;QACf,KAAK,MAAM;YACV,OAAO,uBAAuB,CAAC;QAChC,KAAK,MAAM;YACV,OAAO,uBAAuB,CAAC;IACjC,CAAC;AAAA,CACD","sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/** Individual framework detected in the project */\nexport interface DetectedFramework {\n\tname: string;\n\tversion?: string;\n}\n\n/** Known stack profiles that can be suggested for installation */\nexport type KnownStack = \"TALL\" | \"VILT\";\n\n/** Result of stack detection */\nexport interface StackDetectionResult {\n\t/** All detected frameworks */\n\tframeworks: DetectedFramework[];\n\t/** Recognized stack profile (if frameworks match a known combination) */\n\tstack?: KnownStack;\n\t/** Human-readable summary for system prompt injection */\n\tsummary: string;\n}\n\n/** Detect the technology stack in a project directory */\nexport function detectStack(cwd: string): StackDetectionResult {\n\tconst frameworks: DetectedFramework[] = [];\n\n\t// Parse composer.json for PHP/Laravel dependencies\n\tconst composerPath = join(cwd, \"composer.json\");\n\tif (existsSync(composerPath)) {\n\t\ttry {\n\t\t\tconst composer = JSON.parse(readFileSync(composerPath, \"utf-8\"));\n\t\t\tconst deps = { ...composer.require, ...composer[\"require-dev\"] };\n\n\t\t\tif (deps[\"laravel/framework\"]) {\n\t\t\t\tframeworks.push({ name: \"Laravel\", version: extractVersion(deps[\"laravel/framework\"]) });\n\t\t\t}\n\t\t\tif (deps[\"livewire/livewire\"]) {\n\t\t\t\tframeworks.push({ name: \"Livewire\", version: extractVersion(deps[\"livewire/livewire\"]) });\n\t\t\t}\n\t\t\tif (deps[\"livewire/flux\"]) {\n\t\t\t\tframeworks.push({ name: \"Flux UI\", version: extractVersion(deps[\"livewire/flux\"]) });\n\t\t\t}\n\t\t\tif (deps[\"inertiajs/inertia-laravel\"]) {\n\t\t\t\tframeworks.push({ name: \"Inertia\", version: extractVersion(deps[\"inertiajs/inertia-laravel\"]) });\n\t\t\t}\n\t\t\tif (deps[\"laravel/reverb\"]) {\n\t\t\t\tframeworks.push({ name: \"Reverb\", version: extractVersion(deps[\"laravel/reverb\"]) });\n\t\t\t}\n\t\t\tif (deps[\"laravel/sanctum\"]) {\n\t\t\t\tframeworks.push({ name: \"Sanctum\", version: extractVersion(deps[\"laravel/sanctum\"]) });\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore malformed composer.json\n\t\t}\n\t}\n\n\t// Parse package.json for JS/frontend dependencies\n\tconst packagePath = join(cwd, \"package.json\");\n\tif (existsSync(packagePath)) {\n\t\ttry {\n\t\t\tconst pkg = JSON.parse(readFileSync(packagePath, \"utf-8\"));\n\t\t\tconst deps = { ...pkg.dependencies, ...pkg.devDependencies };\n\n\t\t\tif (deps.vue) {\n\t\t\t\tframeworks.push({ name: \"Vue\", version: extractVersion(deps.vue) });\n\t\t\t}\n\t\t\tif (deps.alpinejs) {\n\t\t\t\tframeworks.push({ name: \"Alpine.js\", version: extractVersion(deps.alpinejs) });\n\t\t\t}\n\t\t\tif (deps.tailwindcss) {\n\t\t\t\tframeworks.push({ name: \"Tailwind CSS\", version: extractVersion(deps.tailwindcss) });\n\t\t\t}\n\t\t\tif (\n\t\t\t\tdeps[\"@inertiajs/vue3\"] ||\n\t\t\t\tdeps[\"@inertiajs/vue2\"] ||\n\t\t\t\tdeps[\"@inertiajs/react\"] ||\n\t\t\t\tdeps[\"@inertiajs/svelte\"]\n\t\t\t) {\n\t\t\t\t// Inertia frontend adapter -- version from whichever is present\n\t\t\t\tconst inertiaFe =\n\t\t\t\t\tdeps[\"@inertiajs/vue3\"] ||\n\t\t\t\t\tdeps[\"@inertiajs/vue2\"] ||\n\t\t\t\t\tdeps[\"@inertiajs/react\"] ||\n\t\t\t\t\tdeps[\"@inertiajs/svelte\"];\n\t\t\t\tif (!frameworks.some((f) => f.name === \"Inertia\")) {\n\t\t\t\t\tframeworks.push({ name: \"Inertia\", version: extractVersion(inertiaFe) });\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (deps.react || deps[\"react-dom\"]) {\n\t\t\t\tframeworks.push({ name: \"React\", version: extractVersion(deps.react || deps[\"react-dom\"]) });\n\t\t\t}\n\t\t\tif (deps.svelte) {\n\t\t\t\tframeworks.push({ name: \"Svelte\", version: extractVersion(deps.svelte) });\n\t\t\t}\n\t\t\tif (deps.typescript) {\n\t\t\t\tframeworks.push({ name: \"TypeScript\", version: extractVersion(deps.typescript) });\n\t\t\t}\n\t\t\tif (deps.vite) {\n\t\t\t\tframeworks.push({ name: \"Vite\", version: extractVersion(deps.vite) });\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore malformed package.json\n\t\t}\n\t}\n\n\tif (frameworks.length === 0) {\n\t\treturn { frameworks, summary: \"\" };\n\t}\n\n\t// Detect known stack profiles\n\tconst has = (name: string) => frameworks.some((f) => f.name === name);\n\tlet stack: KnownStack | undefined;\n\n\tif (has(\"Laravel\") && has(\"Tailwind CSS\") && has(\"Alpine.js\") && has(\"Livewire\")) {\n\t\tstack = \"TALL\";\n\t} else if (has(\"Laravel\") && has(\"Tailwind CSS\") && has(\"Inertia\") && has(\"Vue\")) {\n\t\tstack = \"VILT\";\n\t}\n\n\t// Build human-readable summary\n\tconst frameworkList = frameworks.map((f) => (f.version ? `${f.name} ${f.version}` : f.name)).join(\", \");\n\tlet summary = `Detected frameworks: ${frameworkList}`;\n\tif (stack === \"TALL\") {\n\t\tconst hasFlux = has(\"Flux UI\");\n\t\tsummary = `TALL stack project (Tailwind, Alpine.js, Laravel, Livewire${hasFlux ? \", Flux UI\" : \"\"}).\\n${frameworkList}`;\n\t} else if (stack === \"VILT\") {\n\t\tsummary = `VILT stack project (Vue, Inertia, Laravel, Tailwind).\\n${frameworkList}`;\n\t}\n\n\treturn { frameworks, stack, summary };\n}\n\n/** Strip semver constraint prefixes (^, ~, >=, etc.) to get a clean version */\nfunction extractVersion(constraint: string | undefined): string | undefined {\n\tif (!constraint) return undefined;\n\tconst match = constraint.match(/(\\d+\\.\\d+(?:\\.\\d+)?)/);\n\treturn match?.[1];\n}\n\n/** Get the suggested package name for a detected stack */\nexport function getSuggestedPackage(stack: KnownStack): string {\n\tswitch (stack) {\n\t\tcase \"TALL\":\n\t\t\treturn \"@elyracode/stack-tall\";\n\t\tcase \"VILT\":\n\t\t\treturn \"@elyracode/stack-vilt\";\n\t}\n}\n"]}
@@ -22,6 +22,10 @@ export interface BuildSystemPromptOptions {
22
22
  }>;
23
23
  /** Pre-loaded skills. */
24
24
  skills?: Skill[];
25
+ /** Persistent codebase memory from previous sessions. */
26
+ memoryContent?: string;
27
+ /** Detected technology stack summary (from stack-detector). */
28
+ stackInfo?: string;
25
29
  }
26
30
  /** Build the system prompt with tools, guidelines, and context */
27
31
  export declare function buildSystemPrompt(options: BuildSystemPromptOptions): string;
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAEhE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,qEAAqE;IACrE,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,gCAAgC;IAChC,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,yBAAyB;IACzB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;CACjB;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CAgJ3E","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst customPromptHasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (customPromptHasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Add date and working directory last\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst tools = selectedTools || [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t} else if (hasBash && (hasGrep || hasFind || hasLs)) {\n\t\taddGuideline(\"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\");\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside elyra, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}\n\nElyra documentation (read only when the user asks about elyra itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), elyra packages (docs/packages.md)\n- When working on elyra topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read elyra .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Add date and working directory last\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n"]}
1
+ {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAEhE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,qEAAqE;IACrE,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,gCAAgC;IAChC,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,yBAAyB;IACzB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;IACjB,yDAAyD;IACzD,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,+DAA+D;IAC/D,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CAgL3E","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n\t/** Persistent codebase memory from previous sessions. */\n\tmemoryContent?: string;\n\t/** Detected technology stack summary (from stack-detector). */\n\tstackInfo?: string;\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t\tmemoryContent,\n\t\tstackInfo,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append stack info\n\t\tif (stackInfo) {\n\t\t\tprompt += \"\\n\\n# Technology Stack\\n\\n\";\n\t\t\tprompt += stackInfo;\n\t\t\tprompt += \"\\n\";\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append codebase memory\n\t\tif (memoryContent) {\n\t\t\tprompt += \"\\n\\n# Codebase Memory\\n\\n\";\n\t\t\tprompt += \"Knowledge from previous sessions on this project:\\n\\n\";\n\t\t\tprompt += memoryContent;\n\t\t\tprompt += \"\\n\";\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst customPromptHasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (customPromptHasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Add date and working directory last\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst tools = selectedTools || [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t} else if (hasBash && (hasGrep || hasFind || hasLs)) {\n\t\taddGuideline(\"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\");\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside elyra, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}\n\nElyra documentation (read only when the user asks about elyra itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), elyra packages (docs/packages.md)\n- When working on elyra topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read elyra .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append stack info\n\tif (stackInfo) {\n\t\tprompt += \"\\n\\n# Technology Stack\\n\\n\";\n\t\tprompt += stackInfo;\n\t\tprompt += \"\\n\";\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n# Project Context\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\n\t}\n\n\t// Append codebase memory\n\tif (memoryContent) {\n\t\tprompt += \"\\n\\n# Codebase Memory\\n\\n\";\n\t\tprompt += \"Knowledge from previous sessions on this project:\\n\\n\";\n\t\tprompt += memoryContent;\n\t\tprompt += \"\\n\";\n\t}\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Add date and working directory last\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n"]}
@@ -5,7 +5,7 @@ import { getDocsPath, getExamplesPath, getReadmePath } from "../config.js";
5
5
  import { formatSkillsForPrompt } from "./skills.js";
6
6
  /** Build the system prompt with tools, guidelines, and context */
7
7
  export function buildSystemPrompt(options) {
8
- const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, contextFiles: providedContextFiles, skills: providedSkills, } = options;
8
+ const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, contextFiles: providedContextFiles, skills: providedSkills, memoryContent, stackInfo, } = options;
9
9
  const resolvedCwd = cwd;
10
10
  const promptCwd = resolvedCwd.replace(/\\/g, "/");
11
11
  const now = new Date();
@@ -21,6 +21,12 @@ export function buildSystemPrompt(options) {
21
21
  if (appendSection) {
22
22
  prompt += appendSection;
23
23
  }
24
+ // Append stack info
25
+ if (stackInfo) {
26
+ prompt += "\n\n# Technology Stack\n\n";
27
+ prompt += stackInfo;
28
+ prompt += "\n";
29
+ }
24
30
  // Append project context files
25
31
  if (contextFiles.length > 0) {
26
32
  prompt += "\n\n# Project Context\n\n";
@@ -29,6 +35,13 @@ export function buildSystemPrompt(options) {
29
35
  prompt += `## ${filePath}\n\n${content}\n\n`;
30
36
  }
31
37
  }
38
+ // Append codebase memory
39
+ if (memoryContent) {
40
+ prompt += "\n\n# Codebase Memory\n\n";
41
+ prompt += "Knowledge from previous sessions on this project:\n\n";
42
+ prompt += memoryContent;
43
+ prompt += "\n";
44
+ }
32
45
  // Append skills section (only if read tool is available)
33
46
  const customPromptHasRead = !selectedTools || selectedTools.includes("read");
34
47
  if (customPromptHasRead && skills.length > 0) {
@@ -100,6 +113,12 @@ Elyra documentation (read only when the user asks about elyra itself, its SDK, e
100
113
  if (appendSection) {
101
114
  prompt += appendSection;
102
115
  }
116
+ // Append stack info
117
+ if (stackInfo) {
118
+ prompt += "\n\n# Technology Stack\n\n";
119
+ prompt += stackInfo;
120
+ prompt += "\n";
121
+ }
103
122
  // Append project context files
104
123
  if (contextFiles.length > 0) {
105
124
  prompt += "\n\n# Project Context\n\n";
@@ -108,6 +127,13 @@ Elyra documentation (read only when the user asks about elyra itself, its SDK, e
108
127
  prompt += `## ${filePath}\n\n${content}\n\n`;
109
128
  }
110
129
  }
130
+ // Append codebase memory
131
+ if (memoryContent) {
132
+ prompt += "\n\n# Codebase Memory\n\n";
133
+ prompt += "Knowledge from previous sessions on this project:\n\n";
134
+ prompt += memoryContent;
135
+ prompt += "\n";
136
+ }
111
137
  // Append skills section (only if read tool is available)
112
138
  if (hasRead && skills.length > 0) {
113
139
  prompt += formatSkillsForPrompt(skills);