@wrongstack/tools 0.9.19 → 0.10.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.
- package/dist/audit.js +2 -2
- package/dist/audit.js.map +1 -1
- package/dist/bash.js +86 -19
- package/dist/bash.js.map +1 -1
- package/dist/batch-tool-use.js +2 -2
- package/dist/batch-tool-use.js.map +1 -1
- package/dist/builtin.js +386 -171
- package/dist/builtin.js.map +1 -1
- package/dist/circuit-breaker.d.ts +0 -2
- package/dist/circuit-breaker.js +0 -3
- package/dist/circuit-breaker.js.map +1 -1
- package/dist/codebase-index/index.d.ts +26 -6
- package/dist/codebase-index/index.js +34 -25
- package/dist/codebase-index/index.js.map +1 -1
- package/dist/{codebase-stats-tool-BLhQmPNc.d.ts → codebase-stats-tool-C8ApERbn.d.ts} +0 -11
- package/dist/diff.js +28 -13
- package/dist/diff.js.map +1 -1
- package/dist/document.js +4 -4
- package/dist/document.js.map +1 -1
- package/dist/edit.js +3 -2
- package/dist/edit.js.map +1 -1
- package/dist/exec.js +96 -15
- package/dist/exec.js.map +1 -1
- package/dist/fetch.js +13 -6
- package/dist/fetch.js.map +1 -1
- package/dist/format.js +74 -4
- package/dist/format.js.map +1 -1
- package/dist/git.js +81 -8
- package/dist/git.js.map +1 -1
- package/dist/glob.js +15 -5
- package/dist/glob.js.map +1 -1
- package/dist/grep.js +32 -9
- package/dist/grep.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +404 -182
- package/dist/index.js.map +1 -1
- package/dist/install.js +85 -8
- package/dist/install.js.map +1 -1
- package/dist/json.js +2 -2
- package/dist/json.js.map +1 -1
- package/dist/lint.js +74 -4
- package/dist/lint.js.map +1 -1
- package/dist/logs.js +6 -2
- package/dist/logs.js.map +1 -1
- package/dist/memory.js +13 -6
- package/dist/memory.js.map +1 -1
- package/dist/mode.js +4 -4
- package/dist/mode.js.map +1 -1
- package/dist/outdated.js +2 -2
- package/dist/outdated.js.map +1 -1
- package/dist/pack.js +387 -172
- package/dist/pack.js.map +1 -1
- package/dist/patch.js +3 -2
- package/dist/patch.js.map +1 -1
- package/dist/process-registry.js +0 -3
- package/dist/process-registry.js.map +1 -1
- package/dist/read.js +16 -5
- package/dist/read.js.map +1 -1
- package/dist/replace.js +3 -3
- package/dist/replace.js.map +1 -1
- package/dist/scaffold.js +3 -2
- package/dist/scaffold.js.map +1 -1
- package/dist/search.js +3 -2
- package/dist/search.js.map +1 -1
- package/dist/test.js +74 -4
- package/dist/test.js.map +1 -1
- package/dist/todo.js +21 -7
- package/dist/todo.js.map +1 -1
- package/dist/tool-help.js +5 -5
- package/dist/tool-help.js.map +1 -1
- package/dist/tool-search.js +2 -2
- package/dist/tool-search.js.map +1 -1
- package/dist/tool-use.js +4 -4
- package/dist/tool-use.js.map +1 -1
- package/dist/tree.js +16 -8
- package/dist/tree.js.map +1 -1
- package/dist/typecheck.js +74 -4
- package/dist/typecheck.js.map +1 -1
- package/dist/write.js +11 -4
- package/dist/write.js.map +1 -1
- package/package.json +2 -2
package/dist/todo.js
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
var todoTool = {
|
|
3
3
|
name: "todo",
|
|
4
4
|
category: "Session",
|
|
5
|
-
description: "
|
|
6
|
-
usageHint: "
|
|
5
|
+
description: "Manage the session-level todo list. This is the primary mechanism for tracking multi-step work. The list is fully replaced on every call (not appended).",
|
|
6
|
+
usageHint: "BEST PRACTICE for complex tasks:\n- At the beginning of a non-trivial task, create a clear todo list with specific, actionable items.\n- Only **one** item should be `in_progress` at any time.\n- Update the list frequently as work progresses (mark items done, add new ones, change status).\n- The system and user can see this list, so keep it honest and up-to-date.\nThis tool is extremely valuable for maintaining focus and giving the user visibility into your plan.",
|
|
7
7
|
permission: "auto",
|
|
8
8
|
mutating: false,
|
|
9
9
|
timeoutMs: 1e3,
|
|
@@ -15,13 +15,27 @@ var todoTool = {
|
|
|
15
15
|
items: {
|
|
16
16
|
type: "object",
|
|
17
17
|
properties: {
|
|
18
|
-
id: {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
18
|
+
id: {
|
|
19
|
+
type: "string",
|
|
20
|
+
description: 'Unique identifier for the todo item (e.g. "1", "auth-flow").'
|
|
21
|
+
},
|
|
22
|
+
content: {
|
|
23
|
+
type: "string",
|
|
24
|
+
description: "Clear, actionable description of the task."
|
|
25
|
+
},
|
|
26
|
+
status: {
|
|
27
|
+
type: "string",
|
|
28
|
+
enum: ["pending", "in_progress", "completed"],
|
|
29
|
+
description: 'Current status. Only one item should be "in_progress" at a time.'
|
|
30
|
+
},
|
|
31
|
+
activeForm: {
|
|
32
|
+
type: "string",
|
|
33
|
+
description: 'Optional present-tense form shown while the task is active (e.g. "Fixing auth bug").'
|
|
34
|
+
}
|
|
22
35
|
},
|
|
23
36
|
required: ["id", "content", "status"]
|
|
24
|
-
}
|
|
37
|
+
},
|
|
38
|
+
description: "The complete new list of todos. This replaces the previous list entirely."
|
|
25
39
|
}
|
|
26
40
|
},
|
|
27
41
|
required: ["todos"]
|
package/dist/todo.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/todo.ts"],"names":[],"mappings":";AAWO,IAAM,QAAA,GAAwC;AAAA,EACnD,IAAA,EAAM,MAAA;AAAA,EACN,QAAA,EAAU,SAAA;AAAA,EACV,WAAA,
|
|
1
|
+
{"version":3,"sources":["../src/todo.ts"],"names":[],"mappings":";AAWO,IAAM,QAAA,GAAwC;AAAA,EACnD,IAAA,EAAM,MAAA;AAAA,EACN,QAAA,EAAU,SAAA;AAAA,EACV,WAAA,EACE,0JAAA;AAAA,EAEF,SAAA,EACE,odAAA;AAAA,EAMF,UAAA,EAAY,MAAA;AAAA,EACZ,QAAA,EAAU,KAAA;AAAA,EACV,SAAA,EAAW,GAAA;AAAA,EACX,WAAA,EAAa;AAAA,IACX,IAAA,EAAM,QAAA;AAAA,IACN,UAAA,EAAY;AAAA,MACV,KAAA,EAAO;AAAA,QACL,I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;AACxB,QAAA,IAAI,IAAA,CAAK,WAAW,aAAA,EAAe;AACjC,UAAA,IAAI,cAAA,OAAqB,MAAA,GAAS,SAAA;AAClC,UAAA,cAAA,GAAiB,IAAA;AAAA,QACnB;AAAA,MACF;AAAA,IACF;AACA,IAAA,GAAA,CAAI,KAAA,CAAM,aAAa,KAAK,CAAA;AAC5B,IAAA,OAAO;AAAA,MACL,OAAO,KAAA,CAAM,MAAA;AAAA,MACb,WAAA,EAAa,MAAM,MAAA,CAAO,CAAC,MAAM,CAAA,CAAE,MAAA,KAAW,aAAa,CAAA,CAAE;AAAA,KAC/D;AAAA,EACF;AACF","file":"todo.js","sourcesContent":["import type { TodoItem, Tool } from '@wrongstack/core';\n\ninterface TodoInput {\n todos: TodoItem[];\n}\n\ninterface TodoOutput {\n count: number;\n in_progress: number;\n}\n\nexport const todoTool: Tool<TodoInput, TodoOutput> = {\n name: 'todo',\n category: 'Session',\n description:\n 'Manage the session-level todo list. This is the primary mechanism for tracking multi-step work. ' +\n 'The list is fully replaced on every call (not appended).',\n usageHint:\n 'BEST PRACTICE for complex tasks:\\n' +\n '- At the beginning of a non-trivial task, create a clear todo list with specific, actionable items.\\n' +\n '- Only **one** item should be `in_progress` at any time.\\n' +\n '- Update the list frequently as work progresses (mark items done, add new ones, change status).\\n' +\n '- The system and user can see this list, so keep it honest and up-to-date.\\n' +\n 'This tool is extremely valuable for maintaining focus and giving the user visibility into your plan.',\n permission: 'auto',\n mutating: false,\n timeoutMs: 1_000,\n inputSchema: {\n type: 'object',\n properties: {\n todos: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: {\n type: 'string',\n description: 'Unique identifier for the todo item (e.g. \"1\", \"auth-flow\").',\n },\n content: {\n type: 'string',\n description: 'Clear, actionable description of the task.',\n },\n status: {\n type: 'string',\n enum: ['pending', 'in_progress', 'completed'],\n description: 'Current status. Only one item should be \"in_progress\" at a time.',\n },\n activeForm: {\n type: 'string',\n description: 'Optional present-tense form shown while the task is active (e.g. \"Fixing auth bug\").',\n },\n },\n required: ['id', 'content', 'status'],\n },\n description: 'The complete new list of todos. This replaces the previous list entirely.',\n },\n },\n required: ['todos'],\n },\n async execute(input, ctx) {\n if (!Array.isArray(input?.todos)) {\n throw new Error('todo: todos must be an array');\n }\n const items = input.todos.filter((t): t is TodoItem => Boolean(t?.id && t.content));\n const inProgress = items.filter((t) => t.status === 'in_progress');\n if (inProgress.length > 1) {\n // Keep only the first as in_progress, mark rest pending\n let seenInProgress = false;\n for (const item of items) {\n if (item.status === 'in_progress') {\n if (seenInProgress) item.status = 'pending';\n seenInProgress = true;\n }\n }\n }\n ctx.state.replaceTodos(items);\n return {\n count: items.length,\n in_progress: items.filter((t) => t.status === 'in_progress').length,\n };\n },\n};\n"]}
|
package/dist/tool-help.js
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
var toolHelpTool = {
|
|
3
3
|
name: "tool_help",
|
|
4
4
|
category: "Meta",
|
|
5
|
-
description: "Get help and usage
|
|
6
|
-
usageHint: "
|
|
5
|
+
description: "Get detailed help for one or more tools, including their full schema and usage guidance. This is the best way to understand exactly how to call a specific tool.",
|
|
6
|
+
usageHint: "USE WHEN YOU NEED PRECISE TOOL INFORMATION:\n\n- Call with a specific `tool` name when you want the full schema and current usageHint.\n- Omit `tool` (or use a broad query) to get an overview of available tools.\n- Different `format` options give you different levels of detail.\nThis tool is extremely valuable for self-correction when you are unsure about a tool's interface.",
|
|
7
7
|
permission: "auto",
|
|
8
8
|
mutating: false,
|
|
9
9
|
timeoutMs: 5e3,
|
|
@@ -12,16 +12,16 @@ var toolHelpTool = {
|
|
|
12
12
|
properties: {
|
|
13
13
|
tool: {
|
|
14
14
|
type: "string",
|
|
15
|
-
description: "
|
|
15
|
+
description: "Specific tool name to get detailed help for. Omit to get a list of all tools."
|
|
16
16
|
},
|
|
17
17
|
format: {
|
|
18
18
|
type: "string",
|
|
19
19
|
enum: ["short", "full", "markdown"],
|
|
20
|
-
description:
|
|
20
|
+
description: 'Level of detail: "short" (summary), "full" (with full schema), "markdown" (human readable).'
|
|
21
21
|
},
|
|
22
22
|
include_examples: {
|
|
23
23
|
type: "boolean",
|
|
24
|
-
description: "
|
|
24
|
+
description: "Whether to include example usage in the response."
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
},
|
package/dist/tool-help.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tool-help.ts"],"names":[],"mappings":";AAsBO,IAAM,YAAA,GAAoD;AAAA,EAC/D,IAAA,EAAM,WAAA;AAAA,EACN,QAAA,EAAU,MAAA;AAAA,EACV,WAAA,
|
|
1
|
+
{"version":3,"sources":["../src/tool-help.ts"],"names":[],"mappings":";AAsBO,IAAM,YAAA,GAAoD;AAAA,EAC/D,IAAA,EAAM,WAAA;AAAA,EACN,QAAA,EAAU,MAAA;AAAA,EACV,WAAA,EACE,kKAAA;AAAA,EAEF,SAAA,EACE,2XAAA;AAAA,EAKF,UAAA,EAAY,MAAA;AAAA,EACZ,QAAA,EAAU,KAAA;AAAA,EACV,SAAA,EAAW,GAAA;AAAA,EACX,WAAA,EAAa;AAAA,IACX,IAAA,EAAM,QAAA;AAAA,IACN,UAAA,EAAY;AAAA,MACV,IAAA,EAAM;AAAA,QACJ,IAAA,EAAM,QAAA;AAAA,QACN,WAAA,EAAa;AAAA,OACf;AAAA,MACA,MAAA,EAAQ;AAAA,QACN,IAAA,EAAM,QAAA;AAAA,QACN,IAAA,EAAM,CAAC,OAAA,EAAS,MAAA,EAAQ,UAAU,CAAA;AAAA,QAClC,WAAA,EAAa;AAAA,OACf;AAAA,MACA,gBAAA,EAAkB;AAAA,QAChB,IAAA,EAAM,SAAA;AAAA,QACN,WAAA,EAAa;AAAA;AACf;AACF,GACF;AAAA,EACA,MAAM,OAAA,CAAQ,KAAA,EAAO,GAAA,EAAK;AACxB,IAAA,MAAM,MAAA,GAAS,MAAM,MAAA,IAAU,OAAA;AAC/B,IAAA,MAAM,eAAA,GA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A,EAAK,EAAE,IAAA,CAAK,MAAA,CAAO,EAAE,CAAC,IAAI,CAAA,CAAE,WAAW,CAAA,CAAE,CAAA,CAAE,KAAK,IAAI,CAAA;AAC9E;AAEA,SAAS,uBACP,KAAA,EACQ;AACR,EAAA,MAAM,KAAA,GAAkB,CAAC,oBAAA,EAAsB,EAAE,CAAA;AACjD,EAAA,KAAA,CAAM,KAAK,wBAAwB,CAAA;AACnC,EAAA,KAAA,CAAM,KAAK,wBAAwB,CAAA;AACnC,EAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,IAAA,KAAA,CAAM,KAAK,CAAA,IAAA,EAAO,CAAA,CAAE,IAAI,CAAA,KAAA,EAAQ,CAAA,CAAE,WAAW,CAAA,EAAA,CAAI,CAAA;AAAA,EACnD;AACA,EAAA,OAAO,KAAA,CAAM,KAAK,IAAI,CAAA;AACxB","file":"tool-help.js","sourcesContent":["import type { Tool } from '@wrongstack/core';\n\ninterface ToolHelpInput {\n tool?: string;\n format?: 'short' | 'full' | 'markdown';\n include_examples?: boolean;\n}\n\ninterface ToolHelpOutput {\n tool?: string;\n help: string;\n tools: {\n name: string;\n description: string;\n usageHint: string;\n inputSchema: unknown;\n permission: string;\n mutating: boolean;\n }[];\n total: number;\n}\n\nexport const toolHelpTool: Tool<ToolHelpInput, ToolHelpOutput> = {\n name: 'tool_help',\n category: 'Meta',\n description:\n 'Get detailed help for one or more tools, including their full schema and usage guidance. ' +\n 'This is the best way to understand exactly how to call a specific tool.',\n usageHint:\n 'USE WHEN YOU NEED PRECISE TOOL INFORMATION:\\n\\n' +\n '- Call with a specific `tool` name when you want the full schema and current usageHint.\\n' +\n '- Omit `tool` (or use a broad query) to get an overview of available tools.\\n' +\n '- Different `format` options give you different levels of detail.\\n' +\n 'This tool is extremely valuable for self-correction when you are unsure about a tool\\'s interface.',\n permission: 'auto',\n mutating: false,\n timeoutMs: 5_000,\n inputSchema: {\n type: 'object',\n properties: {\n tool: {\n type: 'string',\n description: 'Specific tool name to get detailed help for. Omit to get a list of all tools.',\n },\n format: {\n type: 'string',\n enum: ['short', 'full', 'markdown'],\n description: 'Level of detail: \"short\" (summary), \"full\" (with full schema), \"markdown\" (human readable).',\n },\n include_examples: {\n type: 'boolean',\n description: 'Whether to include example usage in the response.',\n },\n },\n },\n async execute(input, ctx) {\n const format = input.format ?? 'short';\n const includeExamples = input.include_examples ?? false;\n\n if (input.tool) {\n const tool = ctx.tools.find((t: Tool) => t.name === input.tool);\n if (!tool) {\n return {\n tool: input.tool,\n help: `No tool found with name \"${input.tool}\"`,\n tools: [],\n total: 0,\n };\n }\n\n return {\n tool: tool.name,\n help: formatToolHelp(tool, format, includeExamples),\n tools: [\n {\n name: tool.name,\n description: tool.description,\n usageHint: tool.usageHint ?? '',\n inputSchema: tool.inputSchema,\n permission: tool.permission,\n mutating: tool.mutating,\n },\n ],\n total: 1,\n };\n }\n\n const allTools = ctx.tools.map((t: Tool) => ({\n name: t.name,\n description: t.description,\n usageHint: t.usageHint ?? '',\n inputSchema: format === 'full' ? t.inputSchema : undefined,\n permission: t.permission,\n mutating: t.mutating,\n }));\n\n return {\n help:\n format === 'markdown' ? formatAllToolsMarkdown(allTools) : formatAllToolsShort(allTools),\n tools: allTools,\n total: allTools.length,\n };\n },\n};\n\nfunction formatToolHelp(tool: Tool, format: string, includeExamples: boolean): string {\n const lines: string[] = [];\n\n if (format === 'short') {\n lines.push(`${tool.name}: ${tool.description}`);\n if (tool.usageHint) lines.push(`Hint: ${tool.usageHint}`);\n return lines.join('\\n');\n }\n\n if (format === 'markdown') {\n lines.push(`## ${tool.name}`);\n lines.push('');\n lines.push(tool.description);\n lines.push('');\n lines.push('**Permission:** ' + tool.permission);\n lines.push('**Mutating:** ' + (tool.mutating ? 'yes' : 'no'));\n if (tool.usageHint) {\n lines.push('');\n lines.push('### Usage Hint');\n lines.push(tool.usageHint);\n }\n if (includeExamples && tool.inputSchema) {\n lines.push('');\n lines.push('### Input Schema');\n lines.push('```json');\n lines.push(JSON.stringify(tool.inputSchema, null, 2));\n lines.push('```');\n }\n return lines.join('\\n');\n }\n\n lines.push(`Tool: ${tool.name}`);\n lines.push(`Description: ${tool.description}`);\n lines.push(`Permission: ${tool.permission}`);\n lines.push(`Mutating: ${tool.mutating}`);\n if (tool.usageHint) lines.push(`Usage: ${tool.usageHint}`);\n if (format === 'full' && tool.inputSchema) {\n lines.push('Schema: ' + JSON.stringify(tool.inputSchema, null, 2));\n }\n return lines.join('\\n');\n}\n\nfunction formatAllToolsShort(tools: { name: string; description: string }[]): string {\n return tools.map((t) => ` ${t.name.padEnd(16)} ${t.description}`).join('\\n');\n}\n\nfunction formatAllToolsMarkdown(\n tools: { name: string; description: string; usageHint: string }[],\n): string {\n const lines: string[] = ['## Available Tools', ''];\n lines.push('| Tool | Description |');\n lines.push('|------|-------------|');\n for (const t of tools) {\n lines.push(`| \\`${t.name}\\` | ${t.description} |`);\n }\n return lines.join('\\n');\n}\n"]}
|
package/dist/tool-search.js
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
var toolSearchTool = {
|
|
3
3
|
name: "tool_search",
|
|
4
4
|
category: "Meta",
|
|
5
|
-
description: "Search available tools
|
|
6
|
-
usageHint: "
|
|
5
|
+
description: "Search the catalog of available tools. Very useful when you are unsure which tool to use for a task.",
|
|
6
|
+
usageHint: "SELF-DISCOVERY TOOL:\n\n- Use when you need to find the right tool for a job.\n- `query` searches names and descriptions.\n- You can filter by `tags` (category), `permission`, or `mutating`.\nCall this before guessing tool names. It helps you discover the best tool for the current situation.",
|
|
7
7
|
permission: "auto",
|
|
8
8
|
mutating: false,
|
|
9
9
|
timeoutMs: 1e3,
|
package/dist/tool-search.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tool-search.ts"],"names":[],"mappings":";AAqBO,IAAM,cAAA,GAA0D;AAAA,EACrE,IAAA,EAAM,aAAA;AAAA,EACN,QAAA,EAAU,MAAA;AAAA,EACV,WAAA,EACE,
|
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,MACL,KAAA,EAAO,OAAA;AAAA,MACP,OAAO,QAAA,CAAS,MAAA;AAAA,MAChB,SAAA,EAAW,SAAS,MAAA,GAAS;AAAA,KAC/B;AAAA,EACF;AACF","file":"tool-search.js","sourcesContent":["import type { Tool } from '@wrongstack/core';\n\ninterface ToolSearchInput {\n query?: string;\n tags?: string[];\n permission?: 'auto' | 'confirm' | 'deny';\n mutating?: boolean;\n limit?: number;\n}\n\ninterface ToolSearchOutput {\n tools: {\n name: string;\n description: string;\n permission: string;\n mutating: boolean;\n }[];\n total: number;\n truncated: boolean;\n}\n\nexport const toolSearchTool: Tool<ToolSearchInput, ToolSearchOutput> = {\n name: 'tool_search',\n category: 'Meta',\n description:\n 'Search the catalog of available tools. Very useful when you are unsure which tool to use for a task.',\n usageHint:\n 'SELF-DISCOVERY TOOL:\\n\\n' +\n '- Use when you need to find the right tool for a job.\\n' +\n '- `query` searches names and descriptions.\\n' +\n '- You can filter by `tags` (category), `permission`, or `mutating`.\\n' +\n 'Call this before guessing tool names. It helps you discover the best tool for the current situation.',\n permission: 'auto',\n mutating: false,\n timeoutMs: 1_000,\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Search query for tool name or description',\n },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Filter by tags (e.g. \"filesystem\", \"network\", \"dev\")',\n },\n permission: {\n type: 'string',\n enum: ['auto', 'confirm', 'deny'],\n description: 'Filter by required permission level',\n },\n mutating: {\n type: 'boolean',\n description: 'Filter by mutating flag (true=filters that modify, false=read-only)',\n },\n limit: {\n type: 'integer',\n description: 'Maximum results to return (default: 20)',\n minimum: 1,\n maximum: 100,\n },\n },\n },\n async execute(input, ctx) {\n const limit = Math.min(input.limit ?? 20, 100);\n const tools = ctx.tools;\n const query = input.query?.toLowerCase() ?? '';\n\n const filtered = tools.filter((t: Tool) => {\n if (\n query &&\n !t.name.toLowerCase().includes(query) &&\n !t.description.toLowerCase().includes(query)\n ) {\n return false;\n }\n if (input.tags && input.tags.length > 0) {\n const toolCat = (t.category ?? '').toLowerCase();\n if (!input.tags.some((tag: string) => toolCat.includes(tag.toLowerCase()))) {\n return false;\n }\n }\n if (input.permission && t.permission !== input.permission) {\n return false;\n }\n if (typeof input.mutating === 'boolean' && t.mutating !== input.mutating) {\n return false;\n }\n return true;\n });\n\n const results = filtered.slice(0, limit).map((t: Tool) => ({\n name: t.name,\n description: t.description,\n permission: t.permission,\n mutating: t.mutating,\n }));\n\n return {\n tools: results,\n total: filtered.length,\n truncated: filtered.length > limit,\n };\n },\n};"]}
|
package/dist/tool-use.js
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
var toolUseTool = {
|
|
3
3
|
name: "tool_use",
|
|
4
4
|
category: "Meta",
|
|
5
|
-
description: "
|
|
6
|
-
usageHint: "
|
|
5
|
+
description: "Directly execute any registered tool by its exact name, bypassing normal discovery. This is a powerful meta-tool intended for cases where the agent has a clear plan and knows precisely which tool to invoke.",
|
|
6
|
+
usageHint: "ADVANCED META TOOL \u2014 USE WITH CARE:\n\n- Only use when you are certain of the exact tool name and its expected input shape.\n- Prefer using the normal tool calling mechanism when possible.\n- Very useful in batch-tool-use or when orchestrating complex workflows programmatically.\n- The call still goes through full permission checks and capability validation.",
|
|
7
7
|
permission: "confirm",
|
|
8
8
|
mutating: true,
|
|
9
9
|
timeoutMs: 6e4,
|
|
@@ -12,11 +12,11 @@ var toolUseTool = {
|
|
|
12
12
|
properties: {
|
|
13
13
|
tool: {
|
|
14
14
|
type: "string",
|
|
15
|
-
description:
|
|
15
|
+
description: 'The exact registered name of the tool to invoke (e.g. "bash", "read", "codebase-search").'
|
|
16
16
|
},
|
|
17
17
|
input: {
|
|
18
18
|
type: "object",
|
|
19
|
-
description: "
|
|
19
|
+
description: "The input object matching the target tool's inputSchema."
|
|
20
20
|
}
|
|
21
21
|
},
|
|
22
22
|
required: ["tool"]
|
package/dist/tool-use.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{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L,MAAM,KAAA,CAAM,IAAA;AAAA,QACZ,OAAA,EAAS,KAAA;AAAA,QACT,KAAA,EAAO,CAAA,gBAAA,EAAmB,KAAA,CAAM,IAAI,CAAA,WAAA,CAAA;AAAA,QACpC,WAAA,EAAa,IAAA,CAAK,GAAA,EAAI,GAAI;AAAA,OAC5B;AAAA,IACF;AAKA,IAAA,IAAI,IAAA,CAAK,eAAe,MAAA,EAAQ;AAC9B,MAAA,OAAO;AAAA,QACL,MAAM,KAAA,CAAM,IAAA;AAAA,QACZ,OAAA,EAAS,KAAA;AAAA,QACT,KAAA,EAAO,CAAA,gBAAA,EAAmB,KAAA,CAAM,IAAI,CAAA,qBAAA,CAAA;AAAA,QACpC,WAAA,EAAa,IAAA,CAAK,GAAA,EAAI,GAAI;AAAA,OAC5B;AAAA,IACF;AAWA,IAAA,IAAI;AACF,MAAA,MAAM,SAAS,MAAM,IAAA,CAAK,QAAQ,KAAA,CAAM,KAAA,EAAO,KAAK,IAAI,CAAA;AACxD,MAAA,OAAO;AAAA,QACL,MAAM,KAAA,CAAM,IAAA;AAAA,QACZ,OAAA,EAAS,IAAA;AAAA,QACT,MAAA;AAAA,QACA,WAAA,EAAa,IAAA,CAAK,GAAA,EAAI,GAAI;AAAA,OAC5B;AAAA,IACF,SAAS,CAAA,EAAG;AACV,MAAA,OAAO;AAAA,QACL,MAAM,KAAA,CAAM,IAAA;AAAA,QACZ,OAAA,EAAS,KAAA;AAAA,QACT,OAAO,CAAA,YAAa,KAAA,GAAQ,CAAA,CAAE,OAAA,GAAU,OAAO,CAAC,CAAA;AAAA,QAChD,WAAA,EAAa,IAAA,CAAK,GAAA,EAAI,GAAI;AAAA,OAC5B;AAAA,IACF;AAAA,EACF;AACF","file":"tool-use.js","sourcesContent":["import type { Tool } from '@wrongstack/core';\n\ninterface ToolUseInput {\n tool: string;\n input: Record<string, unknown>;\n}\n\ninterface ToolUseOutput {\n tool: string;\n success: boolean;\n result?: unknown;\n error?: string;\n executionMs: number;\n}\n\nexport const toolUseTool: Tool<ToolUseInput, ToolUseOutput> = {\n name: 'tool_use',\n category: 'Meta',\n description:\n 'Directly execute any registered tool by its exact name, bypassing normal discovery. ' +\n 'This is a powerful meta-tool intended for cases where the agent has a clear plan and knows precisely which tool to invoke.',\n usageHint:\n 'ADVANCED META TOOL — USE WITH CARE:\\n\\n' +\n '- Only use when you are certain of the exact tool name and its expected input shape.\\n' +\n '- Prefer using the normal tool calling mechanism when possible.\\n' +\n '- Very useful in batch-tool-use or when orchestrating complex workflows programmatically.\\n' +\n '- The call still goes through full permission checks and capability validation.',\n permission: 'confirm',\n mutating: true,\n timeoutMs: 60_000,\n inputSchema: {\n type: 'object',\n properties: {\n tool: {\n type: 'string',\n description: 'The exact registered name of the tool to invoke (e.g. \"bash\", \"read\", \"codebase-search\").',\n },\n input: {\n type: 'object',\n description: 'The input object matching the target tool\\'s inputSchema.',\n },\n },\n required: ['tool'],\n },\n async execute(input, ctx, opts) {\n const start = Date.now();\n\n if (!input?.tool) {\n return {\n tool: 'unknown',\n success: false,\n error: 'tool_use: tool name is required',\n executionMs: 0,\n };\n }\n\n const tool = ctx.tools.find((t: Tool) => t.name === input.tool);\n if (!tool) {\n return {\n tool: input.tool,\n success: false,\n error: `tool_use: tool \"${input.tool}\" not found`,\n executionMs: Date.now() - start,\n };\n }\n\n // `deny` is a hard policy gate — bypassing it through a meta-tool\n // would defeat the whole point of the permission system. Keep this\n // check even though the outer `tool_use` already requires `confirm`.\n if (tool.permission === 'deny') {\n return {\n tool: input.tool,\n success: false,\n error: `tool_use: tool \"${input.tool}\" is denied by policy`,\n executionMs: Date.now() - start,\n };\n }\n\n // Note: inner `permission === 'confirm'` is intentionally NOT short-\n // circuited here. The outer `tool_use` itself has `permission: 'confirm'`,\n // so the user already saw the full args (including which inner tool will\n // run, and with what input) before approving the meta-call. Duplicating\n // the check inside execute() turned every confirm-tool dispatch through\n // `tool_use` into a hard failure — the model would see \"requires\n // confirmation\" with no way to proceed, even after the user said yes.\n // `batch_tool_use` already follows this same model.\n\n try {\n const result = await tool.execute(input.input, ctx, opts);\n return {\n tool: input.tool,\n success: true,\n result,\n executionMs: Date.now() - start,\n };\n } catch (e) {\n return {\n tool: input.tool,\n success: false,\n error: e instanceof Error ? e.message : String(e),\n executionMs: Date.now() - start,\n };\n }\n },\n};\n"]}
|
package/dist/tree.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as fs from 'node:fs/promises';
|
|
2
2
|
import * as path from 'node:path';
|
|
3
|
+
import '@wrongstack/core';
|
|
3
4
|
|
|
4
5
|
// src/tree.ts
|
|
5
6
|
function resolvePath(input, ctx) {
|
|
@@ -35,34 +36,41 @@ var DEFAULT_IGNORE = [
|
|
|
35
36
|
var treeTool = {
|
|
36
37
|
name: "tree",
|
|
37
38
|
category: "Filesystem",
|
|
38
|
-
description: "Display directory
|
|
39
|
-
usageHint: "
|
|
39
|
+
description: "Display a directory tree of the project (or a subpath). This is the recommended way to explore the high-level structure of a codebase before reading specific files.",
|
|
40
|
+
usageHint: "BEST PRACTICE FOR INITIAL EXPLORATION:\n\n- Call early when working with an unfamiliar project or module.\n- Tune `depth` (default 3) and use `glob`/`exclude` to focus the view.\n- Prefer this over raw `bash find` or `glob` + manual reading when you need a quick structural overview.\nOutput is truncated for very large trees.",
|
|
40
41
|
permission: "auto",
|
|
41
42
|
mutating: false,
|
|
43
|
+
capabilities: ["fs.read"],
|
|
42
44
|
timeoutMs: 15e3,
|
|
43
45
|
inputSchema: {
|
|
44
46
|
type: "object",
|
|
45
47
|
properties: {
|
|
46
|
-
path: {
|
|
48
|
+
path: {
|
|
49
|
+
type: "string",
|
|
50
|
+
description: "Root directory to display the tree from (defaults to project root)."
|
|
51
|
+
},
|
|
47
52
|
depth: {
|
|
48
53
|
type: "integer",
|
|
49
|
-
description: "
|
|
54
|
+
description: "Maximum directory depth to traverse (default 3, use 0 for unlimited).",
|
|
50
55
|
minimum: 0,
|
|
51
56
|
maximum: 20
|
|
52
57
|
},
|
|
53
|
-
glob: {
|
|
58
|
+
glob: {
|
|
59
|
+
type: "string",
|
|
60
|
+
description: "Only include files matching this glob pattern."
|
|
61
|
+
},
|
|
54
62
|
exclude: {
|
|
55
63
|
type: "array",
|
|
56
64
|
items: { type: "string" },
|
|
57
|
-
description: "
|
|
65
|
+
description: "List of directory names to completely ignore."
|
|
58
66
|
},
|
|
59
67
|
show_files: {
|
|
60
68
|
type: "boolean",
|
|
61
|
-
description: "
|
|
69
|
+
description: "Whether to show individual files (default true)."
|
|
62
70
|
},
|
|
63
71
|
show_dirs: {
|
|
64
72
|
type: "boolean",
|
|
65
|
-
description: "
|
|
73
|
+
description: "Whether to show directories (default true)."
|
|
66
74
|
},
|
|
67
75
|
show_hidden: {
|
|
68
76
|
type: "boolean",
|
package/dist/tree.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/_util.ts","../src/tree.ts"],"names":["path2"],"mappings":";;;;AAIO,SAAS,WAAA,CAAY,OAAe,GAAA,EAAsB;AAC/D,EAAA,OAAY,IAAA,CAAA,UAAA,CAAW,KAAK,CAAA,GAAS,IAAA,CAAA,SAAA,CAAU,KAAK,CAAA,GAAS,IAAA,CAAA,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AACrF;AAEO,SAAS,gBAAA,CAAiB,SAAiB,GAAA,EAAsB;AACtE,EAAA,MAAM,IAAA,GAAY,IAAA,CAAA,OAAA,CAAQ,GAAA,CAAI,WAAW,CAAA;AACzC,EAAA,MAAM,MAAA,GAAc,aAAQ,OAAO,CAAA;AACnC,EAAA,MAAM,GAAA,GAAW,IAAA,CAAA,QAAA,CAAS,IAAA,EAAM,MAAM,CAAA;AACtC,EAAA,IAAI,IAAI,UAAA,CAAW,IAAI,CAAA,IAAU,IAAA,CAAA,UAAA,CAAW,GAAG,CAAA,EAAG;AAChD,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,MAAA,EAAS,OAAO,CAAA,2BAA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,qBAAA,GAAS,qBAAA;AACjC,IAAA,MAAM,cAAc,KAAA,CAAM,IAAA,IAAQ,KAAA,CAAM,WAAA,KAAgB,GAAA,GAAM,EAAA,CAAA;AAE9D,IAAA,IAAI,CAAC,IAAA,CAAK,QAAA,IAAY,KAAA,CAAM,aAAY,EAAG;AAC3C,IAAA,IAAI,CAAC,IAAA,CAAK,SAAA,IAAa,KAAA,CAAM,QAAO,EAAG;AAEvC,IAAA,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,MAAA,GAAS,SAAS,WAAW,CAAA;AAElD,IAAA,IAAI,KAAA,CAAM,aAAY,KAAM,IAAA,CAAK,aAAa,CAAA,IAAK,KAAA,GAAQ,KAAK,QAAA,CAAA,EAAW;AACzE,MAAA,MAAM,WAAA,GAAc,KAAK,MAAA,GAAS,SAAA;AAClC,MAAA,MAAM,QAAaA,IAAA,CAAA,IAAA,CAAK,GAAA,EAAK,MAAM,IAAI,CAAA,EAAG,QAAQ,CAAA,EAAG;AAAA,QACnD,GAAG,IAAA;AAAA,QACH,MAAA,EAAQ,WAAA;AAAA,QACR;AAAA,OACD,CAAA;AAAA,IACH;AAAA,EACF;AACF","file":"tree.js","sourcesContent":["import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { Context } from '@wrongstack/core';\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.cwd, input);\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const root = path.resolve(ctx.projectRoot);\n const target = path.resolve(absPath);\n const rel = path.relative(root, target);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path \"${absPath}\" is outside project root \"${root}\"`);\n }\n return target;\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n const realRoot = await fsp.realpath(ctx.projectRoot).catch(() => path.resolve(ctx.projectRoot));\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n const rel = path.relative(realRoot, real);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoot}\"`,\n );\n }\n return;\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { Tool, ToolProgressEvent, ToolStreamEvent } from '@wrongstack/core';\nimport { safeResolve } from './_util.js';\n\nconst DEFAULT_IGNORE = [\n 'node_modules',\n '.git',\n 'dist',\n 'build',\n '.next',\n 'coverage',\n '__pycache__',\n '.wrongstack',\n '.ssh',\n '.gnupg',\n '.aws',\n];\n\ninterface TreeInput {\n path?: string;\n depth?: number;\n glob?: string;\n exclude?: string[];\n show_files?: boolean;\n show_dirs?: boolean;\n show_hidden?: boolean;\n}\n\ninterface TreeOutput {\n tree: string;\n total_files: number;\n total_dirs: number;\n truncated: boolean;\n path: string;\n}\n\nexport const treeTool: Tool<TreeInput, TreeOutput> = {\n name: 'tree',\n category: 'Filesystem',\n description:\n 'Display directory structure as an ASCII tree. Shows files and folders with indentation.',\n usageHint:\n 'Set `path` (default: cwd). `depth` limits nesting (default: 3). `glob` filters files. `exclude` ignores dirs. `show_files` toggles file listing (default: true).',\n permission: 'auto',\n mutating: false,\n timeoutMs: 15_000,\n inputSchema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Root directory (default: cwd)' },\n depth: {\n type: 'integer',\n description: 'Max nesting depth (default: 3, 0 for unlimited)',\n minimum: 0,\n maximum: 20,\n },\n glob: { type: 'string', description: 'Filter files matching glob (e.g. \"*.ts\")' },\n exclude: {\n type: 'array',\n items: { type: 'string' },\n description: 'Directory names to exclude',\n },\n show_files: {\n type: 'boolean',\n description: 'Show files (default: true, false shows dirs only)',\n },\n show_dirs: {\n type: 'boolean',\n description: 'Show directories (default: true)',\n },\n show_hidden: {\n type: 'boolean',\n description: 'Show hidden files starting with . (default: false)',\n },\n },\n },\n async execute(input, ctx, opts) {\n let final: TreeOutput | undefined;\n for await (const ev of treeTool.executeStream!(input, ctx, opts)) {\n if (ev.type === 'final') final = ev.output;\n }\n if (!final) throw new Error('tree: stream ended without final event');\n return final;\n },\n async *executeStream(input, ctx): AsyncGenerator<ToolStreamEvent<TreeOutput>> {\n const basePath = input.path ? safeResolve(input.path, ctx) : ctx.cwd;\n const maxDepth = input.depth ?? 3;\n const showFiles = input.show_files ?? true;\n const showDirs = input.show_dirs ?? true;\n const showHidden = input.show_hidden ?? false;\n const exclude = new Set([...DEFAULT_IGNORE, ...(input.exclude ?? [])]);\n const filterGlob = input.glob;\n\n const lines: string[] = [basePath];\n const totals = { totalFiles: { value: 0 }, totalDirs: { value: 0 } };\n\n // Walker pushes progress into an async queue; the generator drains it.\n const queue: ToolProgressEvent[] = [];\n const FLUSH_EVERY = 200; // emit metric every 200 entries seen\n let lastEmittedTotal = 0;\n\n const tickProgress = () => {\n const seen = totals.totalFiles.value + totals.totalDirs.value;\n if (seen - lastEmittedTotal >= FLUSH_EVERY) {\n queue.push({\n type: 'metric',\n text: `${seen} entries`,\n data: { files: totals.totalFiles.value, dirs: totals.totalDirs.value },\n });\n lastEmittedTotal = seen;\n }\n };\n\n const walkPromise = walkDir(basePath, 0, {\n maxDepth,\n exclude,\n showFiles,\n showDirs,\n showHidden,\n filterGlob,\n lines,\n prefix: '',\n isLast: true,\n totalFiles: totals.totalFiles,\n totalDirs: totals.totalDirs,\n onProgress: tickProgress,\n });\n\n // Race the walk against periodic flushes — yield metrics while it runs.\n let walkDone = false;\n walkPromise.finally(() => {\n walkDone = true;\n });\n\n while (!walkDone || queue.length > 0) {\n if (queue.length > 0) {\n yield queue.shift()!;\n } else {\n // Race the walk completion against a short tick so we don't busy-\n // spin while the producer fills the queue. Previously the\n // setTimeout was never cleared when walkPromise won — one stray\n // timer per drain iteration accumulated on the event loop.\n let pollTimer: ReturnType<typeof setTimeout> | undefined;\n const poll = new Promise<void>((r) => {\n pollTimer = setTimeout(r, 50);\n });\n try {\n await Promise.race([walkPromise, poll]).catch(() => undefined);\n } finally {\n if (pollTimer) clearTimeout(pollTimer);\n }\n }\n }\n await walkPromise; // surface any error\n\n yield {\n type: 'final',\n output: {\n tree: lines.join('\\n'),\n total_files: totals.totalFiles.value,\n total_dirs: totals.totalDirs.value,\n truncated: false,\n path: basePath,\n },\n };\n },\n};\n\ninterface WalkOptions {\n maxDepth: number;\n exclude: Set<string>;\n showFiles: boolean;\n showDirs: boolean;\n showHidden: boolean;\n filterGlob?: string;\n lines: string[];\n prefix: string;\n isLast: boolean;\n totalFiles: { value: number };\n totalDirs: { value: number };\n onProgress?: () => void;\n}\n\nasync function walkDir(dir: string, depth: number, opts: WalkOptions): Promise<void> {\n const entries = await fs\n .readdir(dir, { withFileTypes: true })\n .catch(() => [] as import('node:fs').Dirent[]);\n\n const filtered = entries.filter((e) => {\n if (!opts.showHidden && e.name.startsWith('.')) return false;\n if (opts.exclude.has(e.name)) return false;\n return true;\n });\n\n if (depth > 0) {\n const dirCount = filtered.filter((e) => e.isDirectory()).length;\n const fileCount = filtered.filter((e) => e.isFile()).length;\n opts.totalDirs.value += dirCount;\n opts.totalFiles.value += fileCount;\n opts.onProgress?.();\n }\n\n const items = filtered.sort((a, b) => {\n if (a.isDirectory() && !b.isDirectory()) return -1;\n if (!a.isDirectory() && b.isDirectory()) return 1;\n return a.name.localeCompare(b.name);\n });\n\n for (let i = 0; i < items.length; i++) {\n const entry = items[i];\n if (!entry) continue;\n const isLast = i === items.length - 1;\n const connector = opts.isLast ? ' ' : '│ ';\n const branch = isLast ? '└── ' : '├── ';\n const displayName = entry.name + (entry.isDirectory() ? '/' : '');\n\n if (!opts.showDirs && entry.isDirectory()) continue;\n if (!opts.showFiles && entry.isFile()) continue;\n\n opts.lines.push(opts.prefix + branch + displayName);\n\n if (entry.isDirectory() && (opts.maxDepth === 0 || depth < opts.maxDepth)) {\n const childPrefix = opts.prefix + connector;\n await walkDir(path.join(dir, entry.name), depth + 1, {\n ...opts,\n prefix: childPrefix,\n isLast,\n });\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/_util.ts","../src/tree.ts"],"names":["path2"],"mappings":";;;;;AAIO,SAAS,WAAA,CAAY,OAAe,GAAA,EAAsB;AAC/D,EAAA,OAAY,IAAA,CAAA,UAAA,CAAW,KAAK,CAAA,GAAS,IAAA,CAAA,SAAA,CAAU,KAAK,CAAA,GAAS,IAAA,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AAA,QACR;AAAA,OACD,CAAA;AAAA,IACH;AAAA,EACF;AACF","file":"tree.js","sourcesContent":["import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { type Context, stripAnsi } from '@wrongstack/core';\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.cwd, input);\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const root = path.resolve(ctx.projectRoot);\n const target = path.resolve(absPath);\n const rel = path.relative(root, target);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path \"${absPath}\" is outside project root \"${root}\"`);\n }\n return target;\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n const realRoot = await fsp.realpath(ctx.projectRoot).catch(() => path.resolve(ctx.projectRoot));\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n const rel = path.relative(realRoot, real);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoot}\"`,\n );\n }\n return;\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number } = {},\n): string {\n if (!raw) return raw;\n let text = stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { Tool, ToolProgressEvent, ToolStreamEvent } from '@wrongstack/core';\nimport { safeResolve } from './_util.js';\n\nconst DEFAULT_IGNORE = [\n 'node_modules',\n '.git',\n 'dist',\n 'build',\n '.next',\n 'coverage',\n '__pycache__',\n '.wrongstack',\n '.ssh',\n '.gnupg',\n '.aws',\n];\n\ninterface TreeInput {\n path?: string;\n depth?: number;\n glob?: string;\n exclude?: string[];\n show_files?: boolean;\n show_dirs?: boolean;\n show_hidden?: boolean;\n}\n\ninterface TreeOutput {\n tree: string;\n total_files: number;\n total_dirs: number;\n truncated: boolean;\n path: string;\n}\n\nexport const treeTool: Tool<TreeInput, TreeOutput> = {\n name: 'tree',\n category: 'Filesystem',\n description:\n 'Display a directory tree of the project (or a subpath). This is the recommended way to explore the high-level structure of a codebase before reading specific files.',\n usageHint:\n 'BEST PRACTICE FOR INITIAL EXPLORATION:\\n\\n' +\n '- Call early when working with an unfamiliar project or module.\\n' +\n '- Tune `depth` (default 3) and use `glob`/`exclude` to focus the view.\\n' +\n '- Prefer this over raw `bash find` or `glob` + manual reading when you need a quick structural overview.\\n' +\n 'Output is truncated for very large trees.',\n permission: 'auto',\n mutating: false,\n capabilities: ['fs.read'],\n timeoutMs: 15_000,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Root directory to display the tree from (defaults to project root).',\n },\n depth: {\n type: 'integer',\n description: 'Maximum directory depth to traverse (default 3, use 0 for unlimited).',\n minimum: 0,\n maximum: 20,\n },\n glob: {\n type: 'string',\n description: 'Only include files matching this glob pattern.',\n },\n exclude: {\n type: 'array',\n items: { type: 'string' },\n description: 'List of directory names to completely ignore.',\n },\n show_files: {\n type: 'boolean',\n description: 'Whether to show individual files (default true).',\n },\n show_dirs: {\n type: 'boolean',\n description: 'Whether to show directories (default true).',\n },\n show_hidden: {\n type: 'boolean',\n description: 'Show hidden files starting with . (default: false)',\n },\n },\n },\n async execute(input, ctx, opts) {\n let final: TreeOutput | undefined;\n for await (const ev of treeTool.executeStream!(input, ctx, opts)) {\n if (ev.type === 'final') final = ev.output;\n }\n if (!final) throw new Error('tree: stream ended without final event');\n return final;\n },\n async *executeStream(input, ctx): AsyncGenerator<ToolStreamEvent<TreeOutput>> {\n const basePath = input.path ? safeResolve(input.path, ctx) : ctx.cwd;\n const maxDepth = input.depth ?? 3;\n const showFiles = input.show_files ?? true;\n const showDirs = input.show_dirs ?? true;\n const showHidden = input.show_hidden ?? false;\n const exclude = new Set([...DEFAULT_IGNORE, ...(input.exclude ?? [])]);\n const filterGlob = input.glob;\n\n const lines: string[] = [basePath];\n const totals = { totalFiles: { value: 0 }, totalDirs: { value: 0 } };\n\n // Walker pushes progress into an async queue; the generator drains it.\n const queue: ToolProgressEvent[] = [];\n const FLUSH_EVERY = 200; // emit metric every 200 entries seen\n let lastEmittedTotal = 0;\n\n const tickProgress = () => {\n const seen = totals.totalFiles.value + totals.totalDirs.value;\n if (seen - lastEmittedTotal >= FLUSH_EVERY) {\n queue.push({\n type: 'metric',\n text: `${seen} entries`,\n data: { files: totals.totalFiles.value, dirs: totals.totalDirs.value },\n });\n lastEmittedTotal = seen;\n }\n };\n\n const walkPromise = walkDir(basePath, 0, {\n maxDepth,\n exclude,\n showFiles,\n showDirs,\n showHidden,\n filterGlob,\n lines,\n prefix: '',\n isLast: true,\n totalFiles: totals.totalFiles,\n totalDirs: totals.totalDirs,\n onProgress: tickProgress,\n });\n\n // Race the walk against periodic flushes — yield metrics while it runs.\n let walkDone = false;\n walkPromise.finally(() => {\n walkDone = true;\n });\n\n while (!walkDone || queue.length > 0) {\n if (queue.length > 0) {\n yield queue.shift()!;\n } else {\n // Race the walk completion against a short tick so we don't busy-\n // spin while the producer fills the queue. Previously the\n // setTimeout was never cleared when walkPromise won — one stray\n // timer per drain iteration accumulated on the event loop.\n let pollTimer: ReturnType<typeof setTimeout> | undefined;\n const poll = new Promise<void>((r) => {\n pollTimer = setTimeout(r, 50);\n });\n try {\n await Promise.race([walkPromise, poll]).catch(() => undefined);\n } finally {\n if (pollTimer) clearTimeout(pollTimer);\n }\n }\n }\n await walkPromise; // surface any error\n\n yield {\n type: 'final',\n output: {\n tree: lines.join('\\n'),\n total_files: totals.totalFiles.value,\n total_dirs: totals.totalDirs.value,\n truncated: false,\n path: basePath,\n },\n };\n },\n};\n\ninterface WalkOptions {\n maxDepth: number;\n exclude: Set<string>;\n showFiles: boolean;\n showDirs: boolean;\n showHidden: boolean;\n filterGlob?: string;\n lines: string[];\n prefix: string;\n isLast: boolean;\n totalFiles: { value: number };\n totalDirs: { value: number };\n onProgress?: () => void;\n}\n\nasync function walkDir(dir: string, depth: number, opts: WalkOptions): Promise<void> {\n const entries = await fs\n .readdir(dir, { withFileTypes: true })\n .catch(() => [] as import('node:fs').Dirent[]);\n\n const filtered = entries.filter((e) => {\n if (!opts.showHidden && e.name.startsWith('.')) return false;\n if (opts.exclude.has(e.name)) return false;\n return true;\n });\n\n if (depth > 0) {\n const dirCount = filtered.filter((e) => e.isDirectory()).length;\n const fileCount = filtered.filter((e) => e.isFile()).length;\n opts.totalDirs.value += dirCount;\n opts.totalFiles.value += fileCount;\n opts.onProgress?.();\n }\n\n const items = filtered.sort((a, b) => {\n if (a.isDirectory() && !b.isDirectory()) return -1;\n if (!a.isDirectory() && b.isDirectory()) return 1;\n return a.name.localeCompare(b.name);\n });\n\n for (let i = 0; i < items.length; i++) {\n const entry = items[i];\n if (!entry) continue;\n const isLast = i === items.length - 1;\n const connector = opts.isLast ? ' ' : '│ ';\n const branch = isLast ? '└── ' : '├── ';\n const displayName = entry.name + (entry.isDirectory() ? '/' : '');\n\n if (!opts.showDirs && entry.isDirectory()) continue;\n if (!opts.showFiles && entry.isFile()) continue;\n\n opts.lines.push(opts.prefix + branch + displayName);\n\n if (entry.isDirectory() && (opts.maxDepth === 0 || depth < opts.maxDepth)) {\n const childPrefix = opts.prefix + connector;\n await walkDir(path.join(dir, entry.name), depth + 1, {\n ...opts,\n prefix: childPrefix,\n isLast,\n });\n }\n }\n}\n"]}
|
package/dist/typecheck.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as path from 'node:path';
|
|
2
2
|
import { spawn } from 'node:child_process';
|
|
3
|
-
import { buildChildEnv } from '@wrongstack/core';
|
|
3
|
+
import { buildChildEnv, stripAnsi } from '@wrongstack/core';
|
|
4
4
|
|
|
5
5
|
// src/typecheck.ts
|
|
6
6
|
async function* spawnStream(opts) {
|
|
@@ -96,13 +96,83 @@ function ensureInsideRoot(absPath, ctx) {
|
|
|
96
96
|
function safeResolve(input, ctx) {
|
|
97
97
|
return ensureInsideRoot(resolvePath(input, ctx), ctx);
|
|
98
98
|
}
|
|
99
|
+
var COMMAND_OUTPUT_MAX_BYTES = 32768;
|
|
100
|
+
var REPEAT_RUN_THRESHOLD = 3;
|
|
101
|
+
function collapseCarriageReturns(text) {
|
|
102
|
+
const lf = text.replace(/\r\n/g, "\n");
|
|
103
|
+
if (!lf.includes("\r")) return lf;
|
|
104
|
+
return lf.split("\n").map((line) => line.includes("\r") ? line.slice(line.lastIndexOf("\r") + 1) : line).join("\n");
|
|
105
|
+
}
|
|
106
|
+
function collapseConsecutiveDuplicates(text, minRun = REPEAT_RUN_THRESHOLD) {
|
|
107
|
+
const lines = text.split("\n");
|
|
108
|
+
const out = [];
|
|
109
|
+
let i = 0;
|
|
110
|
+
while (i < lines.length) {
|
|
111
|
+
let j = i + 1;
|
|
112
|
+
while (j < lines.length && lines[j] === lines[i]) j++;
|
|
113
|
+
const run = j - i;
|
|
114
|
+
if (run >= minRun) {
|
|
115
|
+
out.push(lines[i], `\u2026 \u27E8repeated ${run}\xD7\u27E9`);
|
|
116
|
+
} else {
|
|
117
|
+
for (let k = i; k < j; k++) out.push(lines[k]);
|
|
118
|
+
}
|
|
119
|
+
i = j;
|
|
120
|
+
}
|
|
121
|
+
return out.join("\n");
|
|
122
|
+
}
|
|
123
|
+
function takeHeadBytes(s, maxBytes) {
|
|
124
|
+
if (maxBytes <= 0) return "";
|
|
125
|
+
if (Buffer.byteLength(s, "utf8") <= maxBytes) return s;
|
|
126
|
+
let lo = 0;
|
|
127
|
+
let hi = s.length;
|
|
128
|
+
while (lo < hi) {
|
|
129
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
130
|
+
if (Buffer.byteLength(s.slice(0, mid), "utf8") <= maxBytes) lo = mid;
|
|
131
|
+
else hi = mid - 1;
|
|
132
|
+
}
|
|
133
|
+
return s.slice(0, lo);
|
|
134
|
+
}
|
|
135
|
+
function takeTailBytes(s, maxBytes) {
|
|
136
|
+
if (maxBytes <= 0) return "";
|
|
137
|
+
if (Buffer.byteLength(s, "utf8") <= maxBytes) return s;
|
|
138
|
+
let lo = 0;
|
|
139
|
+
let hi = s.length;
|
|
140
|
+
while (lo < hi) {
|
|
141
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
142
|
+
if (Buffer.byteLength(s.slice(s.length - mid), "utf8") <= maxBytes) lo = mid;
|
|
143
|
+
else hi = mid - 1;
|
|
144
|
+
}
|
|
145
|
+
return s.slice(s.length - lo);
|
|
146
|
+
}
|
|
147
|
+
function truncateHeadTail(s, maxBytes) {
|
|
148
|
+
const total = Buffer.byteLength(s, "utf8");
|
|
149
|
+
if (total <= maxBytes) return s;
|
|
150
|
+
const MARKER_RESERVE = 64;
|
|
151
|
+
const avail = Math.max(0, maxBytes - MARKER_RESERVE);
|
|
152
|
+
const headBudget = Math.floor(avail * 0.45);
|
|
153
|
+
const head = takeHeadBytes(s, headBudget);
|
|
154
|
+
const tail = takeTailBytes(s, avail - Buffer.byteLength(head, "utf8"));
|
|
155
|
+
const kept = Buffer.byteLength(head, "utf8") + Buffer.byteLength(tail, "utf8");
|
|
156
|
+
return `${head}
|
|
157
|
+
\u2026[truncated ${total - kept} bytes]\u2026
|
|
158
|
+
${tail}`;
|
|
159
|
+
}
|
|
160
|
+
function normalizeCommandOutput(raw, opts = {}) {
|
|
161
|
+
if (!raw) return raw;
|
|
162
|
+
let text = stripAnsi(raw);
|
|
163
|
+
text = collapseCarriageReturns(text);
|
|
164
|
+
text = text.replace(/[ \t]+$/gm, "");
|
|
165
|
+
text = collapseConsecutiveDuplicates(text);
|
|
166
|
+
text = text.replace(/\n{3,}/g, "\n\n");
|
|
167
|
+
return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);
|
|
168
|
+
}
|
|
99
169
|
|
|
100
170
|
// src/typecheck.ts
|
|
101
171
|
var typecheckTool = {
|
|
102
172
|
name: "typecheck",
|
|
103
173
|
category: "Code Quality",
|
|
104
|
-
description: "Run TypeScript type
|
|
105
|
-
usageHint: "
|
|
174
|
+
description: "Run the project's TypeScript type checker (`tsc --noEmit` or equivalent). Essential for verifying type safety before making changes or committing.",
|
|
175
|
+
usageHint: "ALWAYS RUN BEFORE CONSIDERING WORK COMPLETE:\n\n- Use this to catch type errors early.\n- In monorepos, `all: true` will check every package.\n- This is one of the most important quality gates in this project.\nNever claim a task is done without a clean typecheck (unless the user explicitly says otherwise).",
|
|
106
176
|
permission: "confirm",
|
|
107
177
|
mutating: false,
|
|
108
178
|
timeoutMs: 12e4,
|
|
@@ -160,7 +230,7 @@ var typecheckTool = {
|
|
|
160
230
|
exit_code: result.exitCode,
|
|
161
231
|
errors,
|
|
162
232
|
warnings,
|
|
163
|
-
output: result.stdout || result.stderr || result.error || "",
|
|
233
|
+
output: normalizeCommandOutput(result.stdout || result.stderr || result.error || ""),
|
|
164
234
|
truncated: result.truncated
|
|
165
235
|
}
|
|
166
236
|
};
|