@gugacoder/agentic-sdk 0.2.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 (129) hide show
  1. package/dist/agent.d.ts +2 -0
  2. package/dist/agent.js +463 -0
  3. package/dist/context/compaction.d.ts +27 -0
  4. package/dist/context/compaction.js +219 -0
  5. package/dist/context/models.d.ts +6 -0
  6. package/dist/context/models.js +41 -0
  7. package/dist/context/tokenizer.d.ts +5 -0
  8. package/dist/context/tokenizer.js +11 -0
  9. package/dist/context/usage.d.ts +11 -0
  10. package/dist/context/usage.js +49 -0
  11. package/dist/display-schemas.d.ts +1865 -0
  12. package/dist/display-schemas.js +219 -0
  13. package/dist/index.d.ts +38 -0
  14. package/dist/index.js +28 -0
  15. package/dist/middleware/logging.d.ts +2 -0
  16. package/dist/middleware/logging.js +32 -0
  17. package/dist/prompts/assembly.d.ts +13 -0
  18. package/dist/prompts/assembly.js +229 -0
  19. package/dist/providers.d.ts +19 -0
  20. package/dist/providers.js +44 -0
  21. package/dist/proxy.d.ts +2 -0
  22. package/dist/proxy.js +103 -0
  23. package/dist/schemas.d.ts +228 -0
  24. package/dist/schemas.js +51 -0
  25. package/dist/session.d.ts +7 -0
  26. package/dist/session.js +102 -0
  27. package/dist/structured.d.ts +18 -0
  28. package/dist/structured.js +38 -0
  29. package/dist/tool-repair.d.ts +21 -0
  30. package/dist/tool-repair.js +72 -0
  31. package/dist/tools/api-spec.d.ts +4 -0
  32. package/dist/tools/api-spec.js +123 -0
  33. package/dist/tools/apply-patch.d.ts +484 -0
  34. package/dist/tools/apply-patch.js +157 -0
  35. package/dist/tools/ask-user.d.ts +14 -0
  36. package/dist/tools/ask-user.js +27 -0
  37. package/dist/tools/bash.d.ts +550 -0
  38. package/dist/tools/bash.js +43 -0
  39. package/dist/tools/batch.d.ts +13 -0
  40. package/dist/tools/batch.js +84 -0
  41. package/dist/tools/brave-search.d.ts +6 -0
  42. package/dist/tools/brave-search.js +19 -0
  43. package/dist/tools/code-search.d.ts +20 -0
  44. package/dist/tools/code-search.js +42 -0
  45. package/dist/tools/diagnostics.d.ts +4 -0
  46. package/dist/tools/diagnostics.js +69 -0
  47. package/dist/tools/display.d.ts +483 -0
  48. package/dist/tools/display.js +77 -0
  49. package/dist/tools/edit.d.ts +682 -0
  50. package/dist/tools/edit.js +47 -0
  51. package/dist/tools/glob.d.ts +4 -0
  52. package/dist/tools/glob.js +42 -0
  53. package/dist/tools/grep.d.ts +6 -0
  54. package/dist/tools/grep.js +69 -0
  55. package/dist/tools/http-request.d.ts +7 -0
  56. package/dist/tools/http-request.js +98 -0
  57. package/dist/tools/index.d.ts +1611 -0
  58. package/dist/tools/index.js +46 -0
  59. package/dist/tools/job-tools.d.ts +24 -0
  60. package/dist/tools/job-tools.js +67 -0
  61. package/dist/tools/list-dir.d.ts +5 -0
  62. package/dist/tools/list-dir.js +79 -0
  63. package/dist/tools/multi-edit.d.ts +814 -0
  64. package/dist/tools/multi-edit.js +57 -0
  65. package/dist/tools/read.d.ts +5 -0
  66. package/dist/tools/read.js +33 -0
  67. package/dist/tools/task.d.ts +21 -0
  68. package/dist/tools/task.js +51 -0
  69. package/dist/tools/todo.d.ts +14 -0
  70. package/dist/tools/todo.js +60 -0
  71. package/dist/tools/web-fetch.d.ts +4 -0
  72. package/dist/tools/web-fetch.js +126 -0
  73. package/dist/tools/web-search.d.ts +22 -0
  74. package/dist/tools/web-search.js +48 -0
  75. package/dist/tools/write.d.ts +550 -0
  76. package/dist/tools/write.js +30 -0
  77. package/dist/types.d.ts +201 -0
  78. package/dist/types.js +1 -0
  79. package/package.json +43 -0
  80. package/src/agent.ts +520 -0
  81. package/src/context/compaction.ts +265 -0
  82. package/src/context/models.ts +42 -0
  83. package/src/context/tokenizer.ts +12 -0
  84. package/src/context/usage.ts +65 -0
  85. package/src/display-schemas.ts +276 -0
  86. package/src/index.ts +43 -0
  87. package/src/middleware/logging.ts +37 -0
  88. package/src/prompts/assembly.ts +263 -0
  89. package/src/prompts/identity.md +10 -0
  90. package/src/prompts/patterns.md +7 -0
  91. package/src/prompts/safety.md +7 -0
  92. package/src/prompts/tool-guide.md +9 -0
  93. package/src/prompts/tools/bash.md +7 -0
  94. package/src/prompts/tools/edit.md +7 -0
  95. package/src/prompts/tools/glob.md +7 -0
  96. package/src/prompts/tools/grep.md +7 -0
  97. package/src/prompts/tools/read.md +7 -0
  98. package/src/prompts/tools/write.md +7 -0
  99. package/src/providers.ts +58 -0
  100. package/src/proxy.ts +101 -0
  101. package/src/schemas.ts +58 -0
  102. package/src/session.ts +110 -0
  103. package/src/structured.ts +65 -0
  104. package/src/tool-repair.ts +92 -0
  105. package/src/tools/api-spec.ts +158 -0
  106. package/src/tools/apply-patch.ts +188 -0
  107. package/src/tools/ask-user.ts +40 -0
  108. package/src/tools/bash.ts +51 -0
  109. package/src/tools/batch.ts +103 -0
  110. package/src/tools/brave-search.ts +24 -0
  111. package/src/tools/code-search.ts +69 -0
  112. package/src/tools/diagnostics.ts +93 -0
  113. package/src/tools/display.ts +105 -0
  114. package/src/tools/edit.ts +55 -0
  115. package/src/tools/glob.ts +46 -0
  116. package/src/tools/grep.ts +68 -0
  117. package/src/tools/http-request.ts +103 -0
  118. package/src/tools/index.ts +48 -0
  119. package/src/tools/job-tools.ts +84 -0
  120. package/src/tools/list-dir.ts +102 -0
  121. package/src/tools/multi-edit.ts +65 -0
  122. package/src/tools/read.ts +40 -0
  123. package/src/tools/task.ts +71 -0
  124. package/src/tools/todo.ts +82 -0
  125. package/src/tools/web-fetch.ts +155 -0
  126. package/src/tools/web-search.ts +75 -0
  127. package/src/tools/write.ts +34 -0
  128. package/src/types.ts +145 -0
  129. package/tsconfig.json +17 -0
@@ -0,0 +1,219 @@
1
+ import { z } from "zod";
2
+ // --- Primitivos reutilizaveis ---
3
+ const MoneySchema = z.object({
4
+ value: z.number(),
5
+ currency: z.string().default("BRL"),
6
+ });
7
+ const SourceRefSchema = z.object({
8
+ name: z.string(),
9
+ url: z.string().url(),
10
+ favicon: z.string().url().optional(),
11
+ });
12
+ const ImageItemSchema = z.object({
13
+ url: z.string().url(),
14
+ alt: z.string().optional(),
15
+ caption: z.string().optional(),
16
+ });
17
+ const BadgeSchema = z.object({
18
+ label: z.string(),
19
+ variant: z.enum(["default", "success", "warning", "error", "info"]).default("default"),
20
+ });
21
+ // --- Display Tools ---
22
+ // 1. METRICAS E DADOS
23
+ export const DisplayMetricSchema = z.object({
24
+ label: z.string(),
25
+ value: z.union([z.string(), z.number()]),
26
+ unit: z.string().optional(),
27
+ trend: z.object({
28
+ direction: z.enum(["up", "down", "neutral"]),
29
+ value: z.string(),
30
+ }).optional(),
31
+ icon: z.string().optional(),
32
+ });
33
+ export const DisplayChartSchema = z.object({
34
+ type: z.enum(["bar", "line", "pie", "area", "donut"]),
35
+ title: z.string(),
36
+ data: z.array(z.object({
37
+ label: z.string(),
38
+ value: z.number(),
39
+ color: z.string().optional(),
40
+ })),
41
+ format: z.object({
42
+ prefix: z.string().optional(),
43
+ suffix: z.string().optional(),
44
+ locale: z.string().default("pt-BR"),
45
+ }).optional(),
46
+ });
47
+ export const DisplayTableSchema = z.object({
48
+ title: z.string().optional(),
49
+ columns: z.array(z.object({
50
+ key: z.string(),
51
+ label: z.string(),
52
+ type: z.enum(["text", "number", "money", "image", "link", "badge"]).default("text"),
53
+ align: z.enum(["left", "center", "right"]).default("left"),
54
+ })),
55
+ rows: z.array(z.record(z.unknown())),
56
+ sortable: z.boolean().default(false),
57
+ });
58
+ export const DisplayProgressSchema = z.object({
59
+ title: z.string().optional(),
60
+ steps: z.array(z.object({
61
+ label: z.string(),
62
+ status: z.enum(["completed", "current", "pending"]),
63
+ description: z.string().optional(),
64
+ })),
65
+ });
66
+ // 2. PRODUTOS E COMERCIO
67
+ export const DisplayProductSchema = z.object({
68
+ title: z.string(),
69
+ image: z.string().url().optional(),
70
+ price: MoneySchema.optional(),
71
+ originalPrice: MoneySchema.optional(),
72
+ rating: z.object({
73
+ score: z.number().min(0).max(5),
74
+ count: z.number(),
75
+ }).optional(),
76
+ source: SourceRefSchema.optional(),
77
+ badges: z.array(BadgeSchema).optional(),
78
+ url: z.string().url().optional(),
79
+ description: z.string().optional(),
80
+ });
81
+ export const DisplayComparisonSchema = z.object({
82
+ title: z.string().optional(),
83
+ items: z.array(DisplayProductSchema),
84
+ attributes: z.array(z.object({
85
+ key: z.string(),
86
+ label: z.string(),
87
+ })).optional(),
88
+ });
89
+ export const DisplayPriceSchema = z.object({
90
+ value: MoneySchema,
91
+ label: z.string(),
92
+ context: z.string().optional(),
93
+ source: SourceRefSchema.optional(),
94
+ badge: BadgeSchema.optional(),
95
+ });
96
+ // 3. MIDIA
97
+ export const DisplayImageSchema = z.object({
98
+ url: z.string().url(),
99
+ alt: z.string().optional(),
100
+ caption: z.string().optional(),
101
+ width: z.number().optional(),
102
+ height: z.number().optional(),
103
+ });
104
+ export const DisplayGallerySchema = z.object({
105
+ title: z.string().optional(),
106
+ images: z.array(ImageItemSchema),
107
+ layout: z.enum(["grid", "masonry"]).default("grid"),
108
+ columns: z.number().min(2).max(5).default(3),
109
+ });
110
+ export const DisplayCarouselSchema = z.object({
111
+ title: z.string().optional(),
112
+ items: z.array(z.object({
113
+ image: z.string().url().optional(),
114
+ title: z.string(),
115
+ subtitle: z.string().optional(),
116
+ price: MoneySchema.optional(),
117
+ url: z.string().url().optional(),
118
+ badges: z.array(BadgeSchema).optional(),
119
+ })),
120
+ });
121
+ // 4. REFERENCIAS E NAVEGACAO
122
+ export const DisplaySourcesSchema = z.object({
123
+ label: z.string().default("Fontes consultadas"),
124
+ sources: z.array(z.object({
125
+ title: z.string(),
126
+ url: z.string().url(),
127
+ favicon: z.string().url().optional(),
128
+ snippet: z.string().optional(),
129
+ })),
130
+ });
131
+ export const DisplayLinkSchema = z.object({
132
+ url: z.string().url(),
133
+ title: z.string(),
134
+ description: z.string().optional(),
135
+ image: z.string().url().optional(),
136
+ favicon: z.string().url().optional(),
137
+ domain: z.string().optional(),
138
+ });
139
+ export const DisplayMapSchema = z.object({
140
+ title: z.string().optional(),
141
+ pins: z.array(z.object({
142
+ lat: z.number(),
143
+ lng: z.number(),
144
+ label: z.string().optional(),
145
+ address: z.string().optional(),
146
+ })),
147
+ zoom: z.number().min(1).max(20).default(14),
148
+ });
149
+ // 5. DOCUMENTOS E ARQUIVOS
150
+ export const DisplayFileSchema = z.object({
151
+ name: z.string(),
152
+ type: z.string(),
153
+ size: z.number().optional(),
154
+ url: z.string().url().optional(),
155
+ preview: z.string().optional(),
156
+ });
157
+ export const DisplayCodeSchema = z.object({
158
+ language: z.string(),
159
+ code: z.string(),
160
+ title: z.string().optional(),
161
+ lineNumbers: z.boolean().default(true),
162
+ });
163
+ export const DisplaySpreadsheetSchema = z.object({
164
+ title: z.string().optional(),
165
+ headers: z.array(z.string()),
166
+ rows: z.array(z.array(z.union([z.string(), z.number(), z.null()]))),
167
+ format: z.object({
168
+ moneyColumns: z.array(z.number()).optional(),
169
+ percentColumns: z.array(z.number()).optional(),
170
+ }).optional(),
171
+ });
172
+ // 6. INTERATIVO
173
+ export const DisplayStepsSchema = z.object({
174
+ title: z.string().optional(),
175
+ steps: z.array(z.object({
176
+ title: z.string(),
177
+ description: z.string().optional(),
178
+ status: z.enum(["completed", "current", "pending"]).default("pending"),
179
+ })),
180
+ orientation: z.enum(["vertical", "horizontal"]).default("vertical"),
181
+ });
182
+ export const DisplayAlertSchema = z.object({
183
+ variant: z.enum(["info", "warning", "error", "success"]),
184
+ title: z.string().optional(),
185
+ message: z.string(),
186
+ icon: z.string().optional(),
187
+ });
188
+ export const DisplayChoicesSchema = z.object({
189
+ question: z.string().optional(),
190
+ choices: z.array(z.object({
191
+ id: z.string(),
192
+ label: z.string(),
193
+ description: z.string().optional(),
194
+ icon: z.string().optional(),
195
+ })),
196
+ layout: z.enum(["buttons", "cards", "list"]).default("buttons"),
197
+ });
198
+ // --- Registry (mapa nome → schema) ---
199
+ export const DisplayToolRegistry = {
200
+ display_metric: DisplayMetricSchema,
201
+ display_chart: DisplayChartSchema,
202
+ display_table: DisplayTableSchema,
203
+ display_progress: DisplayProgressSchema,
204
+ display_product: DisplayProductSchema,
205
+ display_comparison: DisplayComparisonSchema,
206
+ display_price: DisplayPriceSchema,
207
+ display_image: DisplayImageSchema,
208
+ display_gallery: DisplayGallerySchema,
209
+ display_carousel: DisplayCarouselSchema,
210
+ display_sources: DisplaySourcesSchema,
211
+ display_link: DisplayLinkSchema,
212
+ display_map: DisplayMapSchema,
213
+ display_file: DisplayFileSchema,
214
+ display_code: DisplayCodeSchema,
215
+ display_spreadsheet: DisplaySpreadsheetSchema,
216
+ display_steps: DisplayStepsSchema,
217
+ display_alert: DisplayAlertSchema,
218
+ display_choices: DisplayChoicesSchema,
219
+ };
@@ -0,0 +1,38 @@
1
+ export { runAgent } from "./proxy.js";
2
+ export { AgentRunOptionsSchema, AgentEventSchema, UsageDataSchema } from "./schemas.js";
3
+ export type { AgentEvent, UsageData, AgentRunOptions } from "./schemas.js";
4
+ export { runAiAgent } from "./agent.js";
5
+ export type { AiAgentEvent, AiUsageData, AiAgentOptions, AiTodoItem, McpServerConfig, ContextUsage, PrepareStepContext, PrepareStepResult, AiTelemetryOptions } from "./types.js";
6
+ export { getContextUsage } from "./context/usage.js";
7
+ export type { GetContextUsageOptions } from "./context/usage.js";
8
+ export { compactMessages } from "./context/compaction.js";
9
+ export type { CompactOptions, CompactResult } from "./context/compaction.js";
10
+ export { getSystemPrompt, discoverProjectContext } from "./prompts/assembly.js";
11
+ export { createAskUserTool } from "./tools/ask-user.js";
12
+ export type { AskUserCallback } from "./tools/ask-user.js";
13
+ export { webFetchTool } from "./tools/web-fetch.js";
14
+ export { createWebSearchTool } from "./tools/web-search.js";
15
+ export type { WebSearchProvider, WebSearchResult } from "./tools/web-search.js";
16
+ export { createTaskTool } from "./tools/task.js";
17
+ export type { TaskConfig } from "./tools/task.js";
18
+ export { createBatchTool } from "./tools/batch.js";
19
+ export { applyPatchTool, createApplyPatchTool } from "./tools/apply-patch.js";
20
+ export { createBashTool } from "./tools/bash.js";
21
+ export { createWriteTool } from "./tools/write.js";
22
+ export { createEditTool } from "./tools/edit.js";
23
+ export { createMultiEditTool } from "./tools/multi-edit.js";
24
+ export { createCodeSearchTool } from "./tools/code-search.js";
25
+ export type { CodeSearchProvider, CodeSearchResult } from "./tools/code-search.js";
26
+ export { httpRequestTool } from "./tools/http-request.js";
27
+ export { apiSpecTool } from "./tools/api-spec.js";
28
+ export { aiGenerateObject, aiStreamObject } from "./structured.js";
29
+ export type { AiObjectOptions } from "./structured.js";
30
+ export { createAiProviderRegistry } from "./providers.js";
31
+ export type { AiProviderConfig } from "./providers.js";
32
+ export { createLoggingMiddleware } from "./middleware/logging.js";
33
+ export type { LanguageModelMiddleware } from "ai";
34
+ export { createToolCallRepairHandler } from "./tool-repair.js";
35
+ export type { RepairContext } from "./tool-repair.js";
36
+ export { DisplayToolRegistry, DisplayMetricSchema, DisplayChartSchema, DisplayTableSchema, DisplayProgressSchema, DisplayProductSchema, DisplayComparisonSchema, DisplayPriceSchema, DisplayImageSchema, DisplayGallerySchema, DisplayCarouselSchema, DisplaySourcesSchema, DisplayLinkSchema, DisplayMapSchema, DisplayFileSchema, DisplayCodeSchema, DisplaySpreadsheetSchema, DisplayStepsSchema, DisplayAlertSchema, DisplayChoicesSchema } from "./display-schemas.js";
37
+ export type { DisplayToolName, DisplayMetric, DisplayChart, DisplayTable, DisplayProgress, DisplayProduct, DisplayComparison, DisplayPrice, DisplayImage, DisplayGallery, DisplayCarousel, DisplaySources, DisplayLink, DisplayMap, DisplayFile, DisplayCode, DisplaySpreadsheet, DisplaySteps, DisplayAlert, DisplayChoices } from "./display-schemas.js";
38
+ export { createDisplayTools } from "./tools/display.js";
package/dist/index.js ADDED
@@ -0,0 +1,28 @@
1
+ // Proxy (primary API)
2
+ export { runAgent } from "./proxy.js";
3
+ export { AgentRunOptionsSchema, AgentEventSchema, UsageDataSchema } from "./schemas.js";
4
+ // AI agent (internal, kept for backward compat)
5
+ export { runAiAgent } from "./agent.js";
6
+ export { getContextUsage } from "./context/usage.js";
7
+ export { compactMessages } from "./context/compaction.js";
8
+ export { getSystemPrompt, discoverProjectContext } from "./prompts/assembly.js";
9
+ export { createAskUserTool } from "./tools/ask-user.js";
10
+ export { webFetchTool } from "./tools/web-fetch.js";
11
+ export { createWebSearchTool } from "./tools/web-search.js";
12
+ export { createTaskTool } from "./tools/task.js";
13
+ export { createBatchTool } from "./tools/batch.js";
14
+ export { applyPatchTool, createApplyPatchTool } from "./tools/apply-patch.js";
15
+ export { createBashTool } from "./tools/bash.js";
16
+ export { createWriteTool } from "./tools/write.js";
17
+ export { createEditTool } from "./tools/edit.js";
18
+ export { createMultiEditTool } from "./tools/multi-edit.js";
19
+ export { createCodeSearchTool } from "./tools/code-search.js";
20
+ export { httpRequestTool } from "./tools/http-request.js";
21
+ export { apiSpecTool } from "./tools/api-spec.js";
22
+ export { aiGenerateObject, aiStreamObject } from "./structured.js";
23
+ export { createAiProviderRegistry } from "./providers.js";
24
+ export { createLoggingMiddleware } from "./middleware/logging.js";
25
+ export { createToolCallRepairHandler } from "./tool-repair.js";
26
+ // Display tools
27
+ export { DisplayToolRegistry, DisplayMetricSchema, DisplayChartSchema, DisplayTableSchema, DisplayProgressSchema, DisplayProductSchema, DisplayComparisonSchema, DisplayPriceSchema, DisplayImageSchema, DisplayGallerySchema, DisplayCarouselSchema, DisplaySourcesSchema, DisplayLinkSchema, DisplayMapSchema, DisplayFileSchema, DisplayCodeSchema, DisplaySpreadsheetSchema, DisplayStepsSchema, DisplayAlertSchema, DisplayChoicesSchema } from "./display-schemas.js";
28
+ export { createDisplayTools } from "./tools/display.js";
@@ -0,0 +1,2 @@
1
+ import type { LanguageModelMiddleware } from "ai";
2
+ export declare function createLoggingMiddleware(logger?: (msg: string, data?: Record<string, unknown>) => void): LanguageModelMiddleware;
@@ -0,0 +1,32 @@
1
+ export function createLoggingMiddleware(logger = console.log) {
2
+ return {
3
+ specificationVersion: "v3",
4
+ transformParams: async (options) => {
5
+ const { params } = options;
6
+ const tools = params.mode?.type === "regular" ? params.mode.tools?.length ?? 0 : 0;
7
+ logger("[ai:llm] request", {
8
+ tools,
9
+ messages: params.prompt?.length ?? 0,
10
+ });
11
+ return params;
12
+ },
13
+ wrapGenerate: async (options) => {
14
+ const { doGenerate } = options;
15
+ const startMs = Date.now();
16
+ const result = await doGenerate();
17
+ logger("[ai:llm] generate", {
18
+ durationMs: Date.now() - startMs,
19
+ finishReason: result.finishReason,
20
+ usage: result.usage,
21
+ });
22
+ return result;
23
+ },
24
+ wrapStream: async (options) => {
25
+ const { doStream } = options;
26
+ const startMs = Date.now();
27
+ const result = await doStream();
28
+ logger("[ai:llm] stream started", { durationMs: Date.now() - startMs });
29
+ return result;
30
+ },
31
+ };
32
+ }
@@ -0,0 +1,13 @@
1
+ export declare function getSystemPrompt(activeTools: string[]): string;
2
+ /**
3
+ * Discovers project context files (AGENTS.md, CLAUDE.md) by walking up the
4
+ * directory tree from `cwd` to the project root (.git) or filesystem root.
5
+ *
6
+ * Files are concatenated in root → cwd order (lowest → highest precedence).
7
+ * Empty files are skipped. Total context is truncated to 4000 tokens by
8
+ * removing the most distant files (lowest precedence) first.
9
+ *
10
+ * @param cwd - Starting directory for the walk-up search.
11
+ * @returns Concatenated context string, or empty string if nothing found.
12
+ */
13
+ export declare function discoverProjectContext(cwd: string): Promise<string>;
@@ -0,0 +1,229 @@
1
+ // System prompt assembler — all .md content embedded as strings (build-time, no fs reads)
2
+ import { readFile, access } from "node:fs/promises";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { countTokens } from "../context/tokenizer.js";
5
+ // --- Base modules ---
6
+ const IDENTITY = `# Identity
7
+
8
+ You are AI, an autonomous agent. You operate exclusively through tools.
9
+
10
+ ## Principles
11
+
12
+ - Be concise and technical. Skip filler and pleasantries.
13
+ - Respond in the user's language.
14
+ - Show your work through tool calls, not lengthy explanations.
15
+ - When uncertain, investigate before assuming.`;
16
+ const TOOL_GUIDE = `# Tool Usage
17
+
18
+ ## Core Rules
19
+
20
+ - **Always read before editing.** Use the Read tool to see current content before any Edit or Write.
21
+ - **Prefer dedicated tools over Bash.** Use Read instead of \`cat\`, Grep instead of \`grep\`, Glob instead of \`find\`. Reserve Bash for git, npm, build, and system commands.
22
+ - **Verify after modifying.** After editing a file, read it back or run a build/test to confirm correctness.
23
+ - **Never repeat a failed action identically.** If a tool call fails, change your approach — different parameters, different tool, or investigate the error first.
24
+ - **Parallelize when possible.** If multiple tool calls are independent, make them together instead of sequentially.`;
25
+ const PATTERNS = `# Working Patterns
26
+
27
+ 1. **Explore before acting** — Use Glob and Grep to understand the codebase structure before making changes.
28
+ 2. **Read before editing** — Always Read a file before using Edit. This ensures your \`old_string\` matches exactly.
29
+ 3. **Validate after modifying** — Run the build or tests after changes to catch errors early.
30
+ 4. **Failed? Change approach** — Do not retry the same action that failed. Diagnose the error, then try a different strategy.
31
+ 5. **Incremental progress** — Make one change at a time, verify it works, then proceed to the next.`;
32
+ const SAFETY = `# Safety
33
+
34
+ - Do not run destructive commands (\`rm -rf\`, \`drop table\`, \`git push --force\`) without explicit user confirmation.
35
+ - Do not modify files outside the scope of the current task.
36
+ - Do not fabricate file contents — always read first.
37
+ - Do not hardcode secrets, passwords, or API keys in source files.
38
+ - When uncertain about the right action, stop and ask the user (if AskUser is available).`;
39
+ // --- Tool-specific modules ---
40
+ const TOOL_PROMPTS = {
41
+ Read: `## Read
42
+
43
+ **Use para:** Reading file contents, verifying edits, inspecting configuration.
44
+
45
+ **NAO use para:** Listing directory contents — use Bash \`ls\` or Glob instead.
46
+
47
+ **Dica:** Always Read a file before editing it so your \`old_string\` matches exactly.`,
48
+ Write: `## Write
49
+
50
+ **Use para:** Creating new files, rewriting an entire file when most content changes.
51
+
52
+ **NAO use para:** Editing specific sections of an existing file — use Edit instead.
53
+
54
+ **Dica:** Prefer Edit for targeted changes. Write replaces the whole file and can lose surrounding code.`,
55
+ Edit: `## Edit
56
+
57
+ **Use para:** Replacing specific sections of an existing file with exact string matching.
58
+
59
+ **NAO use para:** Rewriting an entire file (use Write), or editing a file you haven't read yet.
60
+
61
+ **Dica:** Copy the exact \`old_string\` from Read output — do not type it from memory.`,
62
+ Bash: `## Bash
63
+
64
+ **Use para:** Git operations, npm/build commands, running tests, system commands.
65
+
66
+ **NAO use para:** Reading files (use Read), searching file contents (use Grep), finding files (use Glob).
67
+
68
+ **Dica:** Always quote file paths with spaces. Check command exit codes before proceeding.`,
69
+ Glob: `## Glob
70
+
71
+ **Use para:** Finding files by name pattern (e.g., \`**/*.ts\`, \`src/**/index.*\`).
72
+
73
+ **NAO use para:** Searching content inside files — use Grep instead.
74
+
75
+ **Dica:** Use Glob to explore project structure before modifying code. Know what files exist first.`,
76
+ Grep: `## Grep
77
+
78
+ **Use para:** Searching content inside files by regex (function names, imports, error messages).
79
+
80
+ **NAO use para:** Finding files by name or pattern — use Glob instead.
81
+
82
+ **Dica:** Use Grep to locate all references before renaming or refactoring.`,
83
+ HttpRequest: `## HttpRequest
84
+
85
+ **Use para:** Making HTTP requests to REST APIs (GET, POST, PUT, PATCH, DELETE). Interacting with external services, APIs, and webhooks.
86
+
87
+ **NAO use para:** Fetching web pages for reading — use WebFetch instead. Downloading large files.
88
+
89
+ **Dica:** Use ApiSpec first to understand an API's endpoints and auth requirements, then use HttpRequest to interact with it. Always include Authorization headers when required.`,
90
+ ApiSpec: `## ApiSpec
91
+
92
+ **Use para:** Fetching and parsing OpenAPI/Swagger specs to understand available API endpoints, parameters, and authentication.
93
+
94
+ **NAO use para:** Making actual API calls — use HttpRequest for that.
95
+
96
+ **Dica:** Fetch the spec first, study the endpoints, then use HttpRequest to interact with the API.`,
97
+ };
98
+ /**
99
+ * Assembles the AI system prompt from embedded markdown modules.
100
+ *
101
+ * @param activeTools - Tool names to include (e.g. ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]).
102
+ * Unknown names are silently ignored.
103
+ * @returns The assembled system prompt string.
104
+ */
105
+ function currentTimestamp() {
106
+ const tz = process.env.TIMEZONE || "UTC";
107
+ const now = new Date();
108
+ const date = now.toLocaleDateString("en-US", {
109
+ timeZone: tz,
110
+ weekday: "long",
111
+ year: "numeric",
112
+ month: "long",
113
+ day: "numeric",
114
+ });
115
+ const time = now.toLocaleTimeString("en-US", {
116
+ timeZone: tz,
117
+ hour: "2-digit",
118
+ minute: "2-digit",
119
+ hour12: false,
120
+ });
121
+ return `It is now ${date} (${tz}) at ${time}`;
122
+ }
123
+ export function getSystemPrompt(activeTools) {
124
+ const sections = [currentTimestamp(), IDENTITY, TOOL_GUIDE];
125
+ for (const name of activeTools) {
126
+ const prompt = TOOL_PROMPTS[name];
127
+ if (prompt) {
128
+ sections.push(prompt);
129
+ }
130
+ }
131
+ sections.push(PATTERNS, SAFETY);
132
+ return sections.join("\n\n");
133
+ }
134
+ // --- Project context discovery ---
135
+ const CONTEXT_FILENAMES = ["AGENTS.md", "CLAUDE.md"];
136
+ const MAX_CONTEXT_TOKENS = 4000;
137
+ async function fileExists(path) {
138
+ try {
139
+ await access(path);
140
+ return true;
141
+ }
142
+ catch {
143
+ return false;
144
+ }
145
+ }
146
+ async function isGitRoot(dir) {
147
+ return fileExists(join(dir, ".git"));
148
+ }
149
+ /**
150
+ * Discovers project context files (AGENTS.md, CLAUDE.md) by walking up the
151
+ * directory tree from `cwd` to the project root (.git) or filesystem root.
152
+ *
153
+ * Files are concatenated in root → cwd order (lowest → highest precedence).
154
+ * Empty files are skipped. Total context is truncated to 4000 tokens by
155
+ * removing the most distant files (lowest precedence) first.
156
+ *
157
+ * @param cwd - Starting directory for the walk-up search.
158
+ * @returns Concatenated context string, or empty string if nothing found.
159
+ */
160
+ export async function discoverProjectContext(cwd) {
161
+ // Collect per-directory groups (cwd → root order)
162
+ const dirGroups = [];
163
+ let current = resolve(cwd);
164
+ // Walk up the directory tree collecting context files
165
+ while (true) {
166
+ const group = [];
167
+ for (const filename of CONTEXT_FILENAMES) {
168
+ const filePath = join(current, filename);
169
+ if (await fileExists(filePath)) {
170
+ try {
171
+ const content = await readFile(filePath, "utf-8");
172
+ if (content.trim().length > 0) {
173
+ group.push({ path: filePath, content: content.trim() });
174
+ }
175
+ }
176
+ catch {
177
+ // Skip unreadable files
178
+ }
179
+ }
180
+ }
181
+ if (group.length > 0) {
182
+ dirGroups.push(group);
183
+ }
184
+ // Stop if we've reached a .git root
185
+ if (await isGitRoot(current))
186
+ break;
187
+ // Move to parent directory
188
+ const parent = dirname(current);
189
+ // Stop at filesystem root (dirname returns same path)
190
+ if (parent === current)
191
+ break;
192
+ current = parent;
193
+ }
194
+ if (dirGroups.length === 0)
195
+ return "";
196
+ // Reverse groups to get root → cwd order, then flatten
197
+ // Within each group, AGENTS.md comes before CLAUDE.md (as collected)
198
+ dirGroups.reverse();
199
+ const collected = dirGroups.flat();
200
+ // Apply token budget — remove most distant (first items = lowest precedence) if over budget
201
+ let totalTokens = 0;
202
+ const formatted = [];
203
+ // Calculate total tokens for all files
204
+ const entries = collected.map((file) => {
205
+ const block = `--- project context: ${file.path} ---\n${file.content}`;
206
+ return { block, tokens: countTokens(block) };
207
+ });
208
+ // Sum total tokens
209
+ totalTokens = entries.reduce((sum, e) => sum + e.tokens, 0);
210
+ if (totalTokens <= MAX_CONTEXT_TOKENS) {
211
+ // Everything fits
212
+ for (const entry of entries) {
213
+ formatted.push(entry.block);
214
+ }
215
+ }
216
+ else {
217
+ // Truncate: remove from the beginning (most distant = lowest precedence)
218
+ let remaining = totalTokens;
219
+ let startIndex = 0;
220
+ while (remaining > MAX_CONTEXT_TOKENS && startIndex < entries.length) {
221
+ remaining -= entries[startIndex].tokens;
222
+ startIndex++;
223
+ }
224
+ for (let i = startIndex; i < entries.length; i++) {
225
+ formatted.push(entries[i].block);
226
+ }
227
+ }
228
+ return formatted.join("\n\n");
229
+ }
@@ -0,0 +1,19 @@
1
+ export interface AiProviderConfig {
2
+ /** Default API key (used for openrouter) */
3
+ apiKey: string;
4
+ /** Aliases de modelo: nome amigavel → model ID completo */
5
+ aliases?: Record<string, string>;
6
+ /** Additional providers by name (e.g. groq) */
7
+ providers?: Record<string, {
8
+ baseURL: string;
9
+ apiKey: string;
10
+ }>;
11
+ }
12
+ export declare function createAiProviderRegistry(config: AiProviderConfig): {
13
+ /** Resolve modelo por ID ou alias, opcionalmente de um provider especifico */
14
+ model(nameOrAlias: string, provider?: string): import("@ai-sdk/provider").LanguageModelV3;
15
+ /** Aliases registrados */
16
+ aliases: {
17
+ [x: string]: string;
18
+ };
19
+ };
@@ -0,0 +1,44 @@
1
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
2
+ import { createGroq } from "@ai-sdk/groq";
3
+ const DEFAULT_ALIASES = {
4
+ "fast": "anthropic/claude-haiku-4.5",
5
+ "balanced": "anthropic/claude-sonnet-4",
6
+ "strong": "anthropic/claude-opus-4.6",
7
+ };
8
+ export function createAiProviderRegistry(config) {
9
+ const aliases = { ...DEFAULT_ALIASES, ...config.aliases };
10
+ const instances = new Map();
11
+ function getProvider(name) {
12
+ const cached = instances.get(name);
13
+ if (cached)
14
+ return cached;
15
+ const extra = config.providers?.[name];
16
+ if (extra) {
17
+ if (name === "groq") {
18
+ const p = createGroq({ apiKey: extra.apiKey });
19
+ instances.set(name, p);
20
+ return p;
21
+ }
22
+ const p = createOpenAICompatible({ name, baseURL: extra.baseURL, apiKey: extra.apiKey });
23
+ instances.set(name, p);
24
+ return p;
25
+ }
26
+ // Default: openrouter
27
+ const p = createOpenAICompatible({
28
+ name: "openrouter",
29
+ baseURL: "https://openrouter.ai/api/v1",
30
+ apiKey: config.apiKey,
31
+ });
32
+ instances.set(name, p);
33
+ return p;
34
+ }
35
+ return {
36
+ /** Resolve modelo por ID ou alias, opcionalmente de um provider especifico */
37
+ model(nameOrAlias, provider) {
38
+ const resolved = aliases[nameOrAlias] ?? nameOrAlias;
39
+ return getProvider(provider ?? "openrouter")(resolved);
40
+ },
41
+ /** Aliases registrados */
42
+ aliases,
43
+ };
44
+ }
@@ -0,0 +1,2 @@
1
+ import { type AgentEvent } from "./schemas.js";
2
+ export declare function runAgent(raw: unknown): AsyncGenerator<AgentEvent>;