@link-assistant/agent 0.0.8

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 (133) hide show
  1. package/EXAMPLES.md +383 -0
  2. package/LICENSE +24 -0
  3. package/MODELS.md +95 -0
  4. package/README.md +388 -0
  5. package/TOOLS.md +134 -0
  6. package/package.json +89 -0
  7. package/src/agent/agent.ts +150 -0
  8. package/src/agent/generate.txt +75 -0
  9. package/src/auth/index.ts +64 -0
  10. package/src/bun/index.ts +96 -0
  11. package/src/bus/global.ts +10 -0
  12. package/src/bus/index.ts +119 -0
  13. package/src/cli/bootstrap.js +41 -0
  14. package/src/cli/bootstrap.ts +17 -0
  15. package/src/cli/cmd/agent.ts +165 -0
  16. package/src/cli/cmd/cmd.ts +5 -0
  17. package/src/cli/cmd/export.ts +88 -0
  18. package/src/cli/cmd/mcp.ts +80 -0
  19. package/src/cli/cmd/models.ts +58 -0
  20. package/src/cli/cmd/run.ts +359 -0
  21. package/src/cli/cmd/stats.ts +276 -0
  22. package/src/cli/error.ts +27 -0
  23. package/src/command/index.ts +73 -0
  24. package/src/command/template/initialize.txt +10 -0
  25. package/src/config/config.ts +705 -0
  26. package/src/config/markdown.ts +41 -0
  27. package/src/file/ripgrep.ts +391 -0
  28. package/src/file/time.ts +38 -0
  29. package/src/file/watcher.ts +75 -0
  30. package/src/file.ts +6 -0
  31. package/src/flag/flag.ts +19 -0
  32. package/src/format/formatter.ts +248 -0
  33. package/src/format/index.ts +137 -0
  34. package/src/global/index.ts +52 -0
  35. package/src/id/id.ts +72 -0
  36. package/src/index.js +371 -0
  37. package/src/mcp/index.ts +289 -0
  38. package/src/patch/index.ts +622 -0
  39. package/src/project/bootstrap.ts +22 -0
  40. package/src/project/instance.ts +67 -0
  41. package/src/project/project.ts +105 -0
  42. package/src/project/state.ts +65 -0
  43. package/src/provider/models-macro.ts +11 -0
  44. package/src/provider/models.ts +98 -0
  45. package/src/provider/opencode.js +47 -0
  46. package/src/provider/provider.ts +636 -0
  47. package/src/provider/transform.ts +241 -0
  48. package/src/server/project.ts +48 -0
  49. package/src/server/server.ts +249 -0
  50. package/src/session/agent.js +204 -0
  51. package/src/session/compaction.ts +249 -0
  52. package/src/session/index.ts +380 -0
  53. package/src/session/message-v2.ts +758 -0
  54. package/src/session/message.ts +189 -0
  55. package/src/session/processor.ts +356 -0
  56. package/src/session/prompt/anthropic-20250930.txt +166 -0
  57. package/src/session/prompt/anthropic.txt +105 -0
  58. package/src/session/prompt/anthropic_spoof.txt +1 -0
  59. package/src/session/prompt/beast.txt +147 -0
  60. package/src/session/prompt/build-switch.txt +5 -0
  61. package/src/session/prompt/codex.txt +318 -0
  62. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  63. package/src/session/prompt/gemini.txt +155 -0
  64. package/src/session/prompt/grok-code.txt +1 -0
  65. package/src/session/prompt/plan.txt +8 -0
  66. package/src/session/prompt/polaris.txt +107 -0
  67. package/src/session/prompt/qwen.txt +109 -0
  68. package/src/session/prompt/summarize-turn.txt +5 -0
  69. package/src/session/prompt/summarize.txt +10 -0
  70. package/src/session/prompt/title.txt +25 -0
  71. package/src/session/prompt.ts +1390 -0
  72. package/src/session/retry.ts +53 -0
  73. package/src/session/revert.ts +108 -0
  74. package/src/session/status.ts +75 -0
  75. package/src/session/summary.ts +179 -0
  76. package/src/session/system.ts +138 -0
  77. package/src/session/todo.ts +36 -0
  78. package/src/snapshot/index.ts +197 -0
  79. package/src/storage/storage.ts +226 -0
  80. package/src/tool/bash.ts +193 -0
  81. package/src/tool/bash.txt +121 -0
  82. package/src/tool/batch.ts +173 -0
  83. package/src/tool/batch.txt +28 -0
  84. package/src/tool/codesearch.ts +123 -0
  85. package/src/tool/codesearch.txt +12 -0
  86. package/src/tool/edit.ts +604 -0
  87. package/src/tool/edit.txt +10 -0
  88. package/src/tool/glob.ts +65 -0
  89. package/src/tool/glob.txt +6 -0
  90. package/src/tool/grep.ts +116 -0
  91. package/src/tool/grep.txt +8 -0
  92. package/src/tool/invalid.ts +17 -0
  93. package/src/tool/ls.ts +110 -0
  94. package/src/tool/ls.txt +1 -0
  95. package/src/tool/multiedit.ts +46 -0
  96. package/src/tool/multiedit.txt +41 -0
  97. package/src/tool/patch.ts +188 -0
  98. package/src/tool/patch.txt +1 -0
  99. package/src/tool/read.ts +201 -0
  100. package/src/tool/read.txt +12 -0
  101. package/src/tool/registry.ts +87 -0
  102. package/src/tool/task.ts +126 -0
  103. package/src/tool/task.txt +60 -0
  104. package/src/tool/todo.ts +39 -0
  105. package/src/tool/todoread.txt +14 -0
  106. package/src/tool/todowrite.txt +167 -0
  107. package/src/tool/tool.ts +66 -0
  108. package/src/tool/webfetch.ts +171 -0
  109. package/src/tool/webfetch.txt +14 -0
  110. package/src/tool/websearch.ts +133 -0
  111. package/src/tool/websearch.txt +11 -0
  112. package/src/tool/write.ts +33 -0
  113. package/src/tool/write.txt +8 -0
  114. package/src/util/binary.ts +41 -0
  115. package/src/util/context.ts +25 -0
  116. package/src/util/defer.ts +12 -0
  117. package/src/util/error.ts +54 -0
  118. package/src/util/eventloop.ts +20 -0
  119. package/src/util/filesystem.ts +69 -0
  120. package/src/util/fn.ts +11 -0
  121. package/src/util/iife.ts +3 -0
  122. package/src/util/keybind.ts +79 -0
  123. package/src/util/lazy.ts +11 -0
  124. package/src/util/locale.ts +39 -0
  125. package/src/util/lock.ts +98 -0
  126. package/src/util/log.ts +177 -0
  127. package/src/util/queue.ts +19 -0
  128. package/src/util/rpc.ts +42 -0
  129. package/src/util/scrap.ts +10 -0
  130. package/src/util/signal.ts +12 -0
  131. package/src/util/timeout.ts +14 -0
  132. package/src/util/token.ts +7 -0
  133. package/src/util/wildcard.ts +54 -0
@@ -0,0 +1,167 @@
1
+ Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
2
+ It also helps the user understand the progress of the task and overall progress of their requests.
3
+
4
+ ## When to Use This Tool
5
+ Use this tool proactively in these scenarios:
6
+
7
+ 1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
8
+ 2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
9
+ 3. User explicitly requests todo list - When the user directly asks you to use the todo list
10
+ 4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
11
+ 5. After receiving new instructions - Immediately capture user requirements as todos. Feel free to edit the todo list based on new information.
12
+ 6. After completing a task - Mark it complete and add any new follow-up tasks
13
+ 7. When you start working on a new task, mark the todo as in_progress. Ideally you should only have one todo as in_progress at a time. Complete existing tasks before starting new ones.
14
+
15
+ ## When NOT to Use This Tool
16
+
17
+ Skip using this tool when:
18
+ 1. There is only a single, straightforward task
19
+ 2. The task is trivial and tracking it provides no organizational benefit
20
+ 3. The task can be completed in less than 3 trivial steps
21
+ 4. The task is purely conversational or informational
22
+
23
+ NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
24
+
25
+ ## Examples of When to Use the Todo List
26
+
27
+ <example>
28
+ User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
29
+ Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
30
+ *Creates todo list with the following items:*
31
+ 1. Create dark mode toggle component in Settings page
32
+ 2. Add dark mode state management (context/store)
33
+ 3. Implement CSS-in-JS styles for dark theme
34
+ 4. Update existing components to support theme switching
35
+ 5. Run tests and build process, addressing any failures or errors that occur
36
+ *Begins working on the first task*
37
+
38
+ <reasoning>
39
+ The assistant used the todo list because:
40
+ 1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes
41
+ 2. The user explicitly requested tests and build be run afterward
42
+ 3. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
43
+ </reasoning>
44
+ </example>
45
+
46
+ <example>
47
+ User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
48
+ Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
49
+ *Uses grep or search tools to locate all instances of getCwd in the codebase*
50
+ Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
51
+ *Creates todo list with specific items for each file that needs updating*
52
+
53
+ <reasoning>
54
+ The assistant used the todo list because:
55
+ 1. First, the assistant searched to understand the scope of the task
56
+ 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps
57
+ 3. The todo list helps ensure every instance is tracked and updated systematically
58
+ 4. This approach prevents missing any occurrences and maintains code consistency
59
+ </reasoning>
60
+ </example>
61
+
62
+
63
+ <example>
64
+ User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.
65
+ Assistant: I'll help implement these features. First, let's add all the features to the todo list.
66
+ *Creates a todo list breaking down each feature into specific tasks based on the project architecture*
67
+ Assistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.
68
+
69
+ <reasoning>
70
+ The assistant used the todo list because:
71
+ 1. The user provided multiple complex features to implement in a comma separated list
72
+ 2. The todo list helps organize these large features into manageable tasks
73
+ 3. This approach allows for tracking progress across the entire implementation
74
+ </reasoning>
75
+ </example>
76
+
77
+ <example>
78
+ User: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>
79
+ Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.
80
+ *Reviews component structure, render patterns, state management, and data fetching*
81
+ Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.
82
+ *Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting*
83
+ Let's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>
84
+
85
+ <reasoning>
86
+ The assistant used the todo list because:
87
+ 1. First, the assistant examined the codebase to identify specific performance issues
88
+ 2. Based on this analysis, it identified multiple optimization opportunities
89
+ 3. Performance optimization is a non-trivial task requiring multiple steps
90
+ 4. The todo list helps methodically track improvements across different components
91
+ 5. This systematic approach ensures all performance bottlenecks are addressed
92
+ </reasoning>
93
+ </example>
94
+
95
+ ## Examples of When NOT to Use the Todo List
96
+
97
+ <example>
98
+ User: How do I print 'Hello World' in Python?
99
+ Assistant: In Python, you can print "Hello World" with this simple code:
100
+
101
+ python
102
+ print("Hello World")
103
+
104
+ This will output the text "Hello World" to the console when executed.</assistant>
105
+
106
+ <reasoning>
107
+ The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
108
+ </reasoning>
109
+ </example>
110
+
111
+ <example>
112
+ User: What does the git status command do?
113
+ Assistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.
114
+
115
+ <reasoning>
116
+ The assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.
117
+ </reasoning>
118
+ </example>
119
+
120
+ <example>
121
+ User: Can you add a comment to the calculateTotal function to explain what it does?
122
+ Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
123
+ * Uses the Edit tool to add a comment to the calculateTotal function *
124
+
125
+ <reasoning>
126
+ The assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization.
127
+ </reasoning>
128
+ </example>
129
+
130
+ <example>
131
+ User: Run npm install for me and tell me what happens.
132
+ Assistant: I'll run the npm install command for you.
133
+
134
+ *Executes: npm install*
135
+
136
+ The command completed successfully. Here's the output:
137
+ [Output of npm install command]
138
+
139
+ All dependencies have been installed according to your package.json file.
140
+
141
+ <reasoning>
142
+ The assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task.
143
+ </reasoning>
144
+ </example>
145
+
146
+ ## Task States and Management
147
+
148
+ 1. **Task States**: Use these states to track progress:
149
+ - pending: Task not yet started
150
+ - in_progress: Currently working on (limit to ONE task at a time)
151
+ - completed: Task finished successfully
152
+ - cancelled: Task no longer needed
153
+
154
+ 2. **Task Management**:
155
+ - Update task status in real-time as you work
156
+ - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
157
+ - Only have ONE task in_progress at any time
158
+ - Complete current tasks before starting new ones
159
+ - Cancel tasks that become irrelevant
160
+
161
+ 3. **Task Breakdown**:
162
+ - Create specific, actionable items
163
+ - Break complex tasks into smaller, manageable steps
164
+ - Use clear, descriptive task names
165
+
166
+ When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.
167
+
@@ -0,0 +1,66 @@
1
+ import z from "zod"
2
+ import type { MessageV2 } from "../session/message-v2"
3
+
4
+ export namespace Tool {
5
+ interface Metadata {
6
+ [key: string]: any
7
+ }
8
+
9
+ export type Context<M extends Metadata = Metadata> = {
10
+ sessionID: string
11
+ messageID: string
12
+ agent: string
13
+ abort: AbortSignal
14
+ callID?: string
15
+ extra?: { [key: string]: any }
16
+ metadata(input: { title?: string; metadata?: M }): void
17
+ }
18
+ export interface Info<Parameters extends z.ZodType = z.ZodType, M extends Metadata = Metadata> {
19
+ id: string
20
+ init: () => Promise<{
21
+ description: string
22
+ parameters: Parameters
23
+ execute(
24
+ args: z.infer<Parameters>,
25
+ ctx: Context,
26
+ ): Promise<{
27
+ title: string
28
+ metadata: M
29
+ output: string
30
+ attachments?: MessageV2.FilePart[]
31
+ }>
32
+ formatValidationError?(error: z.ZodError): string
33
+ }>
34
+ }
35
+
36
+ export type InferParameters<T extends Info> = T extends Info<infer P> ? z.infer<P> : never
37
+ export type InferMetadata<T extends Info> = T extends Info<any, infer M> ? M : never
38
+
39
+ export function define<Parameters extends z.ZodType, Result extends Metadata>(
40
+ id: string,
41
+ init: Info<Parameters, Result>["init"] | Awaited<ReturnType<Info<Parameters, Result>["init"]>>,
42
+ ): Info<Parameters, Result> {
43
+ return {
44
+ id,
45
+ init: async () => {
46
+ const toolInfo = init instanceof Function ? await init() : init
47
+ const execute = toolInfo.execute
48
+ toolInfo.execute = (args, ctx) => {
49
+ try {
50
+ toolInfo.parameters.parse(args)
51
+ } catch (error) {
52
+ if (error instanceof z.ZodError && toolInfo.formatValidationError) {
53
+ throw new Error(toolInfo.formatValidationError(error), { cause: error })
54
+ }
55
+ throw new Error(
56
+ `The ${id} tool was called with invalid arguments: ${error}.\nPlease rewrite the input so it satisfies the expected schema.`,
57
+ { cause: error },
58
+ )
59
+ }
60
+ return execute(args, ctx)
61
+ }
62
+ return toolInfo
63
+ },
64
+ }
65
+ }
66
+ }
@@ -0,0 +1,171 @@
1
+ import z from "zod"
2
+ import { Tool } from "./tool"
3
+ import TurndownService from "turndown"
4
+ import DESCRIPTION from "./webfetch.txt"
5
+
6
+ const MAX_RESPONSE_SIZE = 5 * 1024 * 1024 // 5MB
7
+ const DEFAULT_TIMEOUT = 30 * 1000 // 30 seconds
8
+ const MAX_TIMEOUT = 120 * 1000 // 2 minutes
9
+
10
+ export const WebFetchTool = Tool.define("webfetch", {
11
+ description: DESCRIPTION,
12
+ parameters: z.object({
13
+ url: z.string().describe("The URL to fetch content from"),
14
+ format: z
15
+ .enum(["text", "markdown", "html"])
16
+ .describe("The format to return the content in (text, markdown, or html)"),
17
+ timeout: z.number().describe("Optional timeout in seconds (max 120)").optional(),
18
+ }),
19
+ async execute(params, ctx) {
20
+ // Validate URL
21
+ if (!params.url.startsWith("http://") && !params.url.startsWith("https://")) {
22
+ throw new Error("URL must start with http:// or https://")
23
+ }
24
+
25
+ // No restrictions - unrestricted web fetch
26
+ const timeout = Math.min((params.timeout ?? DEFAULT_TIMEOUT / 1000) * 1000, MAX_TIMEOUT)
27
+
28
+ const controller = new AbortController()
29
+ const timeoutId = setTimeout(() => controller.abort(), timeout)
30
+
31
+ // Build Accept header based on requested format with q parameters for fallbacks
32
+ let acceptHeader = "*/*"
33
+ switch (params.format) {
34
+ case "markdown":
35
+ acceptHeader = "text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1"
36
+ break
37
+ case "text":
38
+ acceptHeader = "text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1"
39
+ break
40
+ case "html":
41
+ acceptHeader = "text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1"
42
+ break
43
+ default:
44
+ acceptHeader =
45
+ "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8"
46
+ }
47
+
48
+ const response = await fetch(params.url, {
49
+ signal: AbortSignal.any([controller.signal, ctx.abort]),
50
+ headers: {
51
+ "User-Agent":
52
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
53
+ Accept: acceptHeader,
54
+ "Accept-Language": "en-US,en;q=0.9",
55
+ },
56
+ })
57
+
58
+ clearTimeout(timeoutId)
59
+
60
+ if (!response.ok) {
61
+ throw new Error(`Request failed with status code: ${response.status}`)
62
+ }
63
+
64
+ // Check content length
65
+ const contentLength = response.headers.get("content-length")
66
+ if (contentLength && parseInt(contentLength) > MAX_RESPONSE_SIZE) {
67
+ throw new Error("Response too large (exceeds 5MB limit)")
68
+ }
69
+
70
+ const arrayBuffer = await response.arrayBuffer()
71
+ if (arrayBuffer.byteLength > MAX_RESPONSE_SIZE) {
72
+ throw new Error("Response too large (exceeds 5MB limit)")
73
+ }
74
+
75
+ const content = new TextDecoder().decode(arrayBuffer)
76
+ const contentType = response.headers.get("content-type") || ""
77
+
78
+ const title = `${params.url} (${contentType})`
79
+
80
+ // Handle content based on requested format and actual content type
81
+ switch (params.format) {
82
+ case "markdown":
83
+ if (contentType.includes("text/html")) {
84
+ const markdown = convertHTMLToMarkdown(content)
85
+ return {
86
+ output: markdown,
87
+ title,
88
+ metadata: {},
89
+ }
90
+ }
91
+ return {
92
+ output: content,
93
+ title,
94
+ metadata: {},
95
+ }
96
+
97
+ case "text":
98
+ if (contentType.includes("text/html")) {
99
+ const text = await extractTextFromHTML(content)
100
+ return {
101
+ output: text,
102
+ title,
103
+ metadata: {},
104
+ }
105
+ }
106
+ return {
107
+ output: content,
108
+ title,
109
+ metadata: {},
110
+ }
111
+
112
+ case "html":
113
+ return {
114
+ output: content,
115
+ title,
116
+ metadata: {},
117
+ }
118
+
119
+ default:
120
+ return {
121
+ output: content,
122
+ title,
123
+ metadata: {},
124
+ }
125
+ }
126
+ },
127
+ })
128
+
129
+ async function extractTextFromHTML(html: string) {
130
+ let text = ""
131
+ let skipContent = false
132
+
133
+ const rewriter = new HTMLRewriter()
134
+ .on("script, style, noscript, iframe, object, embed", {
135
+ element() {
136
+ skipContent = true
137
+ },
138
+ text() {
139
+ // Skip text content inside these elements
140
+ },
141
+ })
142
+ .on("*", {
143
+ element(element) {
144
+ // Reset skip flag when entering other elements
145
+ if (!["script", "style", "noscript", "iframe", "object", "embed"].includes(element.tagName)) {
146
+ skipContent = false
147
+ }
148
+ },
149
+ text(input) {
150
+ if (!skipContent) {
151
+ text += input.text
152
+ }
153
+ },
154
+ })
155
+ .transform(new Response(html))
156
+
157
+ await rewriter.text()
158
+ return text.trim()
159
+ }
160
+
161
+ function convertHTMLToMarkdown(html: string): string {
162
+ const turndownService = new TurndownService({
163
+ headingStyle: "atx",
164
+ hr: "---",
165
+ bulletListMarker: "-",
166
+ codeBlockStyle: "fenced",
167
+ emDelimiter: "*",
168
+ })
169
+ turndownService.remove(["script", "style", "meta", "link"])
170
+ return turndownService.turndown(html)
171
+ }
@@ -0,0 +1,14 @@
1
+ - Fetches content from a specified URL
2
+ - Takes a URL and a prompt as input
3
+ - Fetches the URL content, converts HTML to markdown
4
+ - Returns the model's response about the content
5
+ - Use this tool when you need to retrieve and analyze web content
6
+
7
+ Usage notes:
8
+ - IMPORTANT: if another tool is present that offers better web fetching capabilities, is more targeted to the task, or has fewer restrictions, prefer using that tool instead of this one.
9
+ - The URL must be a fully-formed valid URL
10
+ - HTTP URLs will be automatically upgraded to HTTPS
11
+ - The prompt should describe what information you want to extract from the page
12
+ - This tool is read-only and does not modify any files
13
+ - Results may be summarized if the content is very large
14
+ - Includes a self-cleaning 15-minute cache for faster responses when repeatedly accessing the same URL
@@ -0,0 +1,133 @@
1
+ import z from "zod"
2
+ import { Tool } from "./tool"
3
+ import DESCRIPTION from "./websearch.txt"
4
+ import { Config } from "../config/config"
5
+
6
+ const API_CONFIG = {
7
+ BASE_URL: "https://mcp.exa.ai",
8
+ ENDPOINTS: {
9
+ SEARCH: "/mcp",
10
+ },
11
+ DEFAULT_NUM_RESULTS: 8,
12
+ } as const
13
+
14
+ interface McpSearchRequest {
15
+ jsonrpc: string
16
+ id: number
17
+ method: string
18
+ params: {
19
+ name: string
20
+ arguments: {
21
+ query: string
22
+ numResults?: number
23
+ livecrawl?: "fallback" | "preferred"
24
+ type?: "auto" | "fast" | "deep"
25
+ contextMaxCharacters?: number
26
+ }
27
+ }
28
+ }
29
+
30
+ interface McpSearchResponse {
31
+ jsonrpc: string
32
+ result: {
33
+ content: Array<{
34
+ type: string
35
+ text: string
36
+ }>
37
+ }
38
+ }
39
+
40
+ export const WebSearchTool = Tool.define("websearch", {
41
+ description: DESCRIPTION,
42
+ parameters: z.object({
43
+ query: z.string().describe("Websearch query"),
44
+ numResults: z.number().optional().describe("Number of search results to return (default: 8)"),
45
+ livecrawl: z
46
+ .enum(["fallback", "preferred"])
47
+ .optional()
48
+ .describe(
49
+ "Live crawl mode - 'fallback': use live crawling as backup if cached content unavailable, 'preferred': prioritize live crawling (default: 'fallback')",
50
+ ),
51
+ type: z
52
+ .enum(["auto", "fast", "deep"])
53
+ .optional()
54
+ .describe("Search type - 'auto': balanced search (default), 'fast': quick results, 'deep': comprehensive search"),
55
+ contextMaxCharacters: z
56
+ .number()
57
+ .optional()
58
+ .describe("Maximum characters for context string optimized for LLMs (default: 10000)"),
59
+ }),
60
+ async execute(params, ctx) {
61
+ // No restrictions - unrestricted web search
62
+ const searchRequest: McpSearchRequest = {
63
+ jsonrpc: "2.0",
64
+ id: 1,
65
+ method: "tools/call",
66
+ params: {
67
+ name: "web_search_exa",
68
+ arguments: {
69
+ query: params.query,
70
+ type: params.type || "auto",
71
+ numResults: params.numResults || API_CONFIG.DEFAULT_NUM_RESULTS,
72
+ livecrawl: params.livecrawl || "fallback",
73
+ contextMaxCharacters: params.contextMaxCharacters,
74
+ },
75
+ },
76
+ }
77
+
78
+ const controller = new AbortController()
79
+ const timeoutId = setTimeout(() => controller.abort(), 25000)
80
+
81
+ try {
82
+ const headers: Record<string, string> = {
83
+ accept: "application/json, text/event-stream",
84
+ "content-type": "application/json",
85
+ }
86
+
87
+ const response = await fetch(`${API_CONFIG.BASE_URL}${API_CONFIG.ENDPOINTS.SEARCH}`, {
88
+ method: "POST",
89
+ headers,
90
+ body: JSON.stringify(searchRequest),
91
+ signal: AbortSignal.any([controller.signal, ctx.abort]),
92
+ })
93
+
94
+ clearTimeout(timeoutId)
95
+
96
+ if (!response.ok) {
97
+ const errorText = await response.text()
98
+ throw new Error(`Search error (${response.status}): ${errorText}`)
99
+ }
100
+
101
+ const responseText = await response.text()
102
+
103
+ // Parse SSE response
104
+ const lines = responseText.split("\n")
105
+ for (const line of lines) {
106
+ if (line.startsWith("data: ")) {
107
+ const data: McpSearchResponse = JSON.parse(line.substring(6))
108
+ if (data.result && data.result.content && data.result.content.length > 0) {
109
+ return {
110
+ output: data.result.content[0].text,
111
+ title: `Web search: ${params.query}`,
112
+ metadata: {},
113
+ }
114
+ }
115
+ }
116
+ }
117
+
118
+ return {
119
+ output: "No search results found. Please try a different query.",
120
+ title: `Web search: ${params.query}`,
121
+ metadata: {},
122
+ }
123
+ } catch (error) {
124
+ clearTimeout(timeoutId)
125
+
126
+ if (error instanceof Error && error.name === "AbortError") {
127
+ throw new Error("Search request timed out")
128
+ }
129
+
130
+ throw error
131
+ }
132
+ },
133
+ })
@@ -0,0 +1,11 @@
1
+ - Search the web using Exa AI - performs real-time web searches and can scrape content from specific URLs
2
+ - Provides up-to-date information for current events and recent data
3
+ - Supports configurable result counts and returns the content from the most relevant websites
4
+ - Use this tool for accessing information beyond knowledge cutoff
5
+ - Searches are performed automatically within a single API call
6
+
7
+ Usage notes:
8
+ - Supports live crawling modes: 'fallback' (backup if cached unavailable) or 'preferred' (prioritize live crawling)
9
+ - Search types: 'auto' (balanced), 'fast' (quick results), 'deep' (comprehensive search)
10
+ - Configurable context length for optimal LLM integration
11
+ - Domain filtering and advanced search options available
@@ -0,0 +1,33 @@
1
+ import z from "zod"
2
+ import * as path from "path"
3
+ import { Tool } from "./tool"
4
+ import DESCRIPTION from "./write.txt"
5
+ import { Instance } from "../project/instance"
6
+
7
+ export const WriteTool = Tool.define("write", {
8
+ description: DESCRIPTION,
9
+ parameters: z.object({
10
+ content: z.string().describe("The content to write to the file"),
11
+ filePath: z.string().describe("The absolute path to the file to write (must be absolute, not relative)"),
12
+ }),
13
+ async execute(params, ctx) {
14
+ // No restrictions - unrestricted file system access
15
+ const filepath = path.isAbsolute(params.filePath) ? params.filePath : path.join(Instance.directory, params.filePath)
16
+
17
+ const file = Bun.file(filepath)
18
+ const exists = await file.exists()
19
+
20
+ // Write the file without permission checks
21
+ await Bun.write(filepath, params.content)
22
+
23
+ return {
24
+ title: path.relative(Instance.worktree, filepath),
25
+ metadata: {
26
+ diagnostics: {},
27
+ filepath,
28
+ exists: exists,
29
+ },
30
+ output: "",
31
+ }
32
+ },
33
+ })
@@ -0,0 +1,8 @@
1
+ Writes a file to the local filesystem.
2
+
3
+ Usage:
4
+ - This tool will overwrite the existing file if there is one at the provided path.
5
+ - If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.
6
+ - ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
7
+ - NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.
8
+ - Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.
@@ -0,0 +1,41 @@
1
+ export namespace Binary {
2
+ export function search<T>(array: T[], id: string, compare: (item: T) => string): { found: boolean; index: number } {
3
+ let left = 0
4
+ let right = array.length - 1
5
+
6
+ while (left <= right) {
7
+ const mid = Math.floor((left + right) / 2)
8
+ const midId = compare(array[mid])
9
+
10
+ if (midId === id) {
11
+ return { found: true, index: mid }
12
+ } else if (midId < id) {
13
+ left = mid + 1
14
+ } else {
15
+ right = mid - 1
16
+ }
17
+ }
18
+
19
+ return { found: false, index: left }
20
+ }
21
+
22
+ export function insert<T>(array: T[], item: T, compare: (item: T) => string): T[] {
23
+ const id = compare(item)
24
+ let left = 0
25
+ let right = array.length
26
+
27
+ while (left < right) {
28
+ const mid = Math.floor((left + right) / 2)
29
+ const midId = compare(array[mid])
30
+
31
+ if (midId < id) {
32
+ left = mid + 1
33
+ } else {
34
+ right = mid
35
+ }
36
+ }
37
+
38
+ array.splice(left, 0, item)
39
+ return array
40
+ }
41
+ }
@@ -0,0 +1,25 @@
1
+ import { AsyncLocalStorage } from "async_hooks"
2
+
3
+ export namespace Context {
4
+ export class NotFound extends Error {
5
+ constructor(public override readonly name: string) {
6
+ super(`No context found for ${name}`)
7
+ }
8
+ }
9
+
10
+ export function create<T>(name: string) {
11
+ const storage = new AsyncLocalStorage<T>()
12
+ return {
13
+ use() {
14
+ const result = storage.getStore()
15
+ if (!result) {
16
+ throw new NotFound(name)
17
+ }
18
+ return result
19
+ },
20
+ provide<R>(value: T, fn: () => R) {
21
+ return storage.run(value, fn)
22
+ },
23
+ }
24
+ }
25
+ }