s-app-scoder-agent 0.9.2 → 0.9.6

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 (112) hide show
  1. package/README.md +615 -638
  2. package/dist/{guardrails.js → agent/guardrails.js} +1 -1
  3. package/dist/agent/interaction.js +70 -0
  4. package/dist/agent/mcp-bridge.js +136 -0
  5. package/dist/agent/prompt-context.js +83 -0
  6. package/dist/agent/run-loop.js +318 -0
  7. package/dist/agent/session-persistence.js +61 -0
  8. package/dist/agent/tool-executor.js +158 -0
  9. package/dist/agent/types.js +88 -0
  10. package/dist/agent/verification.js +99 -0
  11. package/dist/agent.js +239 -1002
  12. package/dist/cli/args.js +230 -0
  13. package/dist/cli/init.js +79 -0
  14. package/dist/cli/main.js +211 -0
  15. package/dist/cli/mcp-command.js +185 -0
  16. package/dist/cli/repl.js +77 -0
  17. package/dist/cli/run-once.js +26 -0
  18. package/dist/{tui/commands.js → commands/definitions.js} +6 -16
  19. package/dist/commands/registry.js +260 -0
  20. package/dist/{config.js → config/config.js} +1 -1
  21. package/dist/{prompt-builder.js → context/prompt-builder.js} +12 -1
  22. package/dist/{prompt.js → context/prompt.js} +111 -9
  23. package/dist/{skills.js → context/skills.js} +41 -2
  24. package/dist/index.js +5 -798
  25. package/dist/io/console-reporter.js +24 -0
  26. package/dist/io/reporter.js +1 -0
  27. package/dist/mcp/connection.js +227 -0
  28. package/dist/mcp/env.js +8 -0
  29. package/dist/{mcp.js → mcp/manager.js} +3 -515
  30. package/dist/mcp/sse.js +28 -0
  31. package/dist/mcp/transport-http.js +140 -0
  32. package/dist/mcp/transport-stdio.js +98 -0
  33. package/dist/mcp/types.js +11 -0
  34. package/dist/media/image.js +149 -0
  35. package/dist/{server.js → server/server.js} +1 -1
  36. package/dist/{cost.js → session/cost.js} +1 -1
  37. package/dist/{session.js → session/session.js} +1 -1
  38. package/dist/{version.js → shared/version.js} +1 -1
  39. package/dist/tools/apply-patch.js +62 -0
  40. package/dist/tools/edit-file.js +29 -0
  41. package/dist/tools/file-edit-common.js +124 -0
  42. package/dist/tools/list-files.js +64 -0
  43. package/dist/tools/path-safety.js +75 -0
  44. package/dist/tools/read-file.js +64 -0
  45. package/dist/tools/registry.js +297 -0
  46. package/dist/tools/run-command.js +192 -0
  47. package/dist/tools/schemas.js +8 -0
  48. package/dist/tools/search.js +237 -0
  49. package/dist/tools/task-tool.js +48 -0
  50. package/dist/tools/types.js +1 -0
  51. package/dist/tools/write-file.js +34 -0
  52. package/dist/tui/app.js +59 -532
  53. package/dist/tui/ask-user-modal.js +2 -1
  54. package/dist/tui/at-complete.js +2 -93
  55. package/dist/tui/charset.js +41 -0
  56. package/dist/tui/chat-views.js +72 -16
  57. package/dist/tui/chrome.js +11 -4
  58. package/dist/tui/hooks/use-command-host.js +26 -0
  59. package/dist/tui/hooks/use-event-queue.js +69 -0
  60. package/dist/tui/hooks/use-keybinds.js +87 -0
  61. package/dist/tui/hooks/use-scroll.js +38 -0
  62. package/dist/tui/hooks/use-session-resume.js +47 -0
  63. package/dist/tui/hooks/use-submit.js +106 -0
  64. package/dist/tui/image.js +2 -149
  65. package/dist/tui/input.js +1 -1
  66. package/dist/tui/markdown/ast.js +5 -0
  67. package/dist/tui/markdown/diagram.js +239 -0
  68. package/dist/tui/markdown/inline-render.js +24 -0
  69. package/dist/tui/markdown/inline.js +93 -0
  70. package/dist/tui/markdown/parse.js +139 -0
  71. package/dist/tui/markdown/render.js +146 -0
  72. package/dist/tui/markdown/table.js +106 -0
  73. package/dist/tui/markdown.js +32 -379
  74. package/dist/tui/permission-modal.js +2 -1
  75. package/dist/tui/selectors.js +157 -0
  76. package/dist/tui/session-picker.js +4 -3
  77. package/dist/tui/sidebar.js +130 -15
  78. package/dist/tui/state.js +47 -118
  79. package/dist/tui/text-width.js +139 -0
  80. package/dist/tui/theme.js +7 -2
  81. package/dist/{build.js → workspace/build.js} +1 -1
  82. package/dist/workspace/file-index.js +93 -0
  83. package/package.json +5 -1
  84. package/dist/tools.js +0 -1223
  85. package/dist/tui/command-registry.js +0 -477
  86. package/dist/tui/review.js +0 -64
  87. package/dist/tui/transcript.js +0 -145
  88. /package/dist/{agents-guide.js → context/agents-guide.js} +0 -0
  89. /package/dist/{agents.js → context/agents.js} +0 -0
  90. /package/dist/{compaction.js → context/compaction.js} +0 -0
  91. /package/dist/{context.js → context/context.js} +0 -0
  92. /package/dist/{memory.js → context/memory.js} +0 -0
  93. /package/dist/{repo-map.js → context/repo-map.js} +0 -0
  94. /package/dist/{ui.js → io/terminal.js} +0 -0
  95. /package/dist/{llm.js → llm/llm.js} +0 -0
  96. /package/dist/{model-catalog.js → llm/model-catalog.js} +0 -0
  97. /package/dist/{provider-anthropic.js → llm/provider-anthropic.js} +0 -0
  98. /package/dist/{provider-registry.js → llm/provider-registry.js} +0 -0
  99. /package/dist/{retry.js → llm/retry.js} +0 -0
  100. /package/dist/{mcp-import.js → mcp/mcp-import.js} +0 -0
  101. /package/dist/{permissions.js → security/permissions.js} +0 -0
  102. /package/dist/{sandbox.js → security/sandbox.js} +0 -0
  103. /package/dist/{shell-scanner.js → security/shell-scanner.js} +0 -0
  104. /package/dist/{logger.js → session/logger.js} +0 -0
  105. /package/dist/{steering.js → session/steering.js} +0 -0
  106. /package/dist/{constants.js → shared/constants.js} +0 -0
  107. /package/dist/{json-schema.js → shared/json-schema.js} +0 -0
  108. /package/dist/{webfetch.js → tools/webfetch.js} +0 -0
  109. /package/dist/{diagnostics.js → workspace/diagnostics.js} +0 -0
  110. /package/dist/{diff.js → workspace/diff.js} +0 -0
  111. /package/dist/{snapshot.js → workspace/snapshot.js} +0 -0
  112. /package/dist/{watch.js → workspace/watch.js} +0 -0
@@ -0,0 +1,64 @@
1
+ import { readFileSync, statSync, realpathSync } from "node:fs";
2
+ import { relative } from "node:path";
3
+ import { detectImageBytes } from "../media/image.js";
4
+ import { clamp, MAX_FILE_SIZE_BYTES, safePath, toPosInt, toResult } from "./path-safety.js";
5
+ import { isProtectedEnvFile } from "./path-safety.js";
6
+ export function toolReadFile(workdir, args) {
7
+ return toResult(() => {
8
+ const abs = safePath(workdir, args.path);
9
+ // H-04: .env read policy — ask trước khi trả nội dung (secrets hygiene).
10
+ const rel = relative(workdir, abs);
11
+ let policyPath = rel;
12
+ try {
13
+ policyPath = relative(workdir, realpathSync(abs));
14
+ }
15
+ catch { /* handled by safePath */ }
16
+ const envPolicy = isProtectedEnvFile(policyPath.toLowerCase());
17
+ if (envPolicy === "ask") {
18
+ return {
19
+ ok: false,
20
+ output: `ASK_PERMISSION: ${rel} may contain secrets (env file). ` +
21
+ `Ask the user to confirm before reading; suggest reading .env.example instead ` +
22
+ `or running with a permission rule ({"action":"shell","resource":"read .env","effect":"allow"}).`,
23
+ };
24
+ }
25
+ const st = statSync(abs);
26
+ if (st.isDirectory()) {
27
+ return { ok: false, output: `ERROR: ${args.path} is a directory — use list_files instead.` };
28
+ }
29
+ if (st.size > MAX_FILE_SIZE_BYTES) {
30
+ return {
31
+ ok: false,
32
+ output: `ERROR: ${args.path} is ${(st.size / 1024 / 1024).toFixed(1)}MB (limit ${MAX_FILE_SIZE_BYTES / 1024 / 1024}MB). Use run_command with grep/head/tail to inspect specific parts.`,
33
+ };
34
+ }
35
+ // T7: image file → base64 notice cho TUI render (LLM vẫn nhận mô tả text).
36
+ let image;
37
+ try {
38
+ const probe = readFileSync(abs);
39
+ const ext = detectImageBytes(probe);
40
+ if (ext)
41
+ image = `data:image/${ext};base64,${probe.toString("base64")}`;
42
+ }
43
+ catch {
44
+ // not an image / unreadable — fall through to text read
45
+ }
46
+ if (image) {
47
+ return { ok: true, output: `[image: ${args.path}]`, image };
48
+ }
49
+ if (statSync(abs).size > MAX_FILE_SIZE_BYTES) {
50
+ return { ok: false, output: `ERROR: ${args.path} exceeds the ${MAX_FILE_SIZE_BYTES / 1024 / 1024}MB edit limit.` };
51
+ }
52
+ const content = readFileSync(abs, "utf8");
53
+ const lines = content.split("\n");
54
+ const total = lines.length;
55
+ // v2: line-range reads — offset (1-based, default 1) + limit (default all).
56
+ const offset = Math.min(toPosInt(args.offset, 1), total);
57
+ const limit = Math.min(toPosInt(args.limit, total - offset + 1), 2000);
58
+ const slice = lines.slice(offset - 1, offset - 1 + limit);
59
+ const numbered = slice.map((l, i) => `${offset + i}: ${l}`).join("\n");
60
+ const end = offset + slice.length - 1;
61
+ const header = offset > 1 || end < total ? `[lines ${offset}-${end} of ${total} — ${args.path}]\n` : "";
62
+ return { ok: true, output: clamp(header + numbered) };
63
+ });
64
+ }
@@ -0,0 +1,297 @@
1
+ import { findSkill, discoverSkills, loadSkillSection } from "../context/skills.js";
2
+ import { buildRepoMap, renderRepoMap } from "../context/repo-map.js";
3
+ import { toolWebFetch } from "./webfetch.js";
4
+ import { toolReadFile } from "./read-file.js";
5
+ import { toolWriteFile } from "./write-file.js";
6
+ import { toolEditFile } from "./edit-file.js";
7
+ import { toolApplyPatch } from "./apply-patch.js";
8
+ import { toolListFiles } from "./list-files.js";
9
+ import { toolGrep, toolGlob } from "./search.js";
10
+ import { toolRunCommand } from "./run-command.js";
11
+ import { taskTool } from "./task-tool.js";
12
+ import { obj, str, num } from "./schemas.js";
13
+ export const AGENT_TOOLS = [
14
+ {
15
+ spec: {
16
+ type: "function",
17
+ function: {
18
+ name: "load_skill",
19
+ description: "Load the full instructions of a named skill from the AVAILABLE SKILLS index (project + global). Call this at the start of a task when it matches a skill, then follow the returned instructions exactly.",
20
+ parameters: obj({
21
+ name: str("Skill name ONLY, exactly as listed in the AVAILABLE SKILLS index, e.g. 'prompt-gate-workflow' — do NOT append task text."),
22
+ section: str("Optional section heading to load (progressive disclosure). Omit for full body."),
23
+ }, ["name"]),
24
+ },
25
+ },
26
+ run: (ctx, args) => {
27
+ const name = String(args.name ?? "").trim();
28
+ if (!name)
29
+ return { ok: false, output: "ERROR: name is required — pick one from the AVAILABLE SKILLS index." };
30
+ const skill = findSkill(ctx.workdir, name);
31
+ if (!skill) {
32
+ const names = discoverSkills(ctx.workdir).map((s) => s.name).join(", ");
33
+ return { ok: false, output: `ERROR: skill "${name}" not found${names ? ` — available: ${names}` : " — no skills discovered"}.` };
34
+ }
35
+ const section = args.section;
36
+ const body = section ? loadSkillSection(skill, String(section)) : skill.body;
37
+ const refs = skill.references?.length ? `\n\nReferences: ${skill.references.join(", ")}` : "";
38
+ return { ok: true, output: `# skill: ${skill.name} (${skill.scope})${skill.version ? ` v${skill.version}` : ""}\n\n${body}${refs}` };
39
+ },
40
+ },
41
+ {
42
+ spec: {
43
+ type: "function",
44
+ function: {
45
+ name: "write_todos",
46
+ description: "Write the full task plan (replaces the previous list). Use at the start of a multi-step task and update as you go: mark items completed IMMEDIATELY after finishing them, set exactly one item in_progress, and add newly discovered steps. " +
47
+ "v2: each item may carry verify (how you will know it's done), depends_on (earlier step ids), files (expected paths) and acceptance (criteria). The user sees this list live.",
48
+ parameters: obj({
49
+ todos: {
50
+ type: "array",
51
+ description: "The complete todo list (full replacement).",
52
+ items: {
53
+ type: "object",
54
+ properties: {
55
+ id: { type: "string", description: "Stable step id (e.g. 't1'). Auto-assigned when omitted." },
56
+ content: { type: "string", description: "Imperative step, e.g. 'Fix null check in UserService'" },
57
+ status: { type: "string", enum: ["pending", "in_progress", "completed"] },
58
+ verify: { type: "string", description: "How to verify the step — command or observable behavior" },
59
+ depends_on: { type: "array", items: { type: "string" }, description: "Ids of steps that must complete first" },
60
+ files: { type: "array", items: { type: "string" }, description: "Files this step is expected to touch" },
61
+ acceptance: { type: "string", description: "Criteria for the step to count as done" },
62
+ },
63
+ required: ["content", "status"],
64
+ additionalProperties: false,
65
+ },
66
+ },
67
+ }, ["todos"]),
68
+ },
69
+ },
70
+ run: (ctx, args) => {
71
+ const todos = args.todos;
72
+ if (!Array.isArray(todos))
73
+ return { ok: false, output: "ERROR: todos must be an array of {content, status}." };
74
+ const clean = [];
75
+ for (const [i, t] of todos.entries()) {
76
+ if (typeof t?.content !== "string" || !t.content.trim()) {
77
+ return { ok: false, output: "ERROR: every todo needs a non-empty content string." };
78
+ }
79
+ if (!["pending", "in_progress", "completed"].includes(t.status)) {
80
+ return { ok: false, output: `ERROR: invalid status "${String(t.status)}" (pending|in_progress|completed).` };
81
+ }
82
+ const item = {
83
+ id: typeof t.id === "string" && t.id.trim() ? t.id.trim().slice(0, 32) : `t${i + 1}`,
84
+ content: t.content.trim().slice(0, 200),
85
+ status: t.status,
86
+ };
87
+ if (typeof t.verify === "string" && t.verify.trim())
88
+ item.verify = t.verify.trim().slice(0, 300);
89
+ if (typeof t.acceptance === "string" && t.acceptance.trim())
90
+ item.acceptance = t.acceptance.trim().slice(0, 300);
91
+ if (Array.isArray(t.depends_on))
92
+ item.depends_on = t.depends_on.filter((x) => typeof x === "string").slice(0, 10);
93
+ if (Array.isArray(t.files))
94
+ item.files = t.files.filter((x) => typeof x === "string").slice(0, 20);
95
+ clean.push(item);
96
+ }
97
+ // v2 rule: exactly one in_progress at a time.
98
+ const inProgress = clean.filter((t) => t.status === "in_progress");
99
+ if (inProgress.length > 1) {
100
+ return { ok: false, output: `ERROR: exactly one in_progress step allowed (got ${inProgress.length}: ${inProgress.map((t) => t.content).join(" | ")}). Mark the others pending or completed.` };
101
+ }
102
+ // v2 rule: depends_on must reference earlier ids in the SAME plan.
103
+ const ids = new Set(clean.map((t) => t.id));
104
+ for (const t of clean) {
105
+ for (const dep of t.depends_on ?? []) {
106
+ if (!ids.has(dep))
107
+ return { ok: false, output: `ERROR: step "${t.content}" depends_on unknown id "${dep}" — ids in this plan: ${[...ids].join(", ")}` };
108
+ }
109
+ }
110
+ ctx.plan?.set(clean);
111
+ const done = clean.filter((t) => t.status === "completed").length;
112
+ const next = clean.find((t) => t.status === "in_progress");
113
+ return { ok: true, output: `Plan updated: ${done}/${clean.length} completed.${next ? ` In progress: ${next.content}` : " (none in progress)"}` };
114
+ },
115
+ },
116
+ {
117
+ spec: {
118
+ type: "function",
119
+ function: {
120
+ name: "list_files",
121
+ description: "List files and directories recursively under a path in the working directory. Hidden dotfiles are excluded unless include_hidden=true; pass depth / exclude to shape the output.",
122
+ parameters: obj({
123
+ path: str("Relative path, defaults to '.'"),
124
+ depth: num("Max directory depth to recurse (default 4, cap 8)"),
125
+ exclude: str("Comma/space-separated globs to exclude, e.g. '*.log,coverage'"),
126
+ include_hidden: str("'true' to include dotfiles (default: excluded)"),
127
+ }, []),
128
+ },
129
+ },
130
+ run: (ctx, args) => toolListFiles(ctx.workdir, args),
131
+ },
132
+ {
133
+ spec: {
134
+ type: "function",
135
+ function: {
136
+ name: "read_file",
137
+ description: "Read a text file. Returns content with 1-based line numbers. Pass offset (1-based start line) and limit to read a slice instead of the whole file. Image files (PNG/JPG/GIF) return an `[image: path]` placeholder rendered inline by the TUI.",
138
+ parameters: obj({
139
+ path: str("Relative file path"),
140
+ offset: num("1-based line to start from (default: 1)"),
141
+ limit: num("Max lines to read (default: whole file, capped at 2000)"),
142
+ }, ["path"]),
143
+ },
144
+ },
145
+ run: (ctx, args) => toolReadFile(ctx.workdir, args),
146
+ },
147
+ {
148
+ spec: {
149
+ type: "function",
150
+ function: {
151
+ name: "write_file",
152
+ description: "Create or overwrite a file with the given full content. Parent dirs are created automatically.",
153
+ parameters: obj({ path: str("Relative file path"), content: str("Full file content") }, ["path", "content"]),
154
+ },
155
+ },
156
+ run: (ctx, args) => toolWriteFile(ctx, args),
157
+ },
158
+ {
159
+ spec: {
160
+ type: "function",
161
+ function: {
162
+ name: "edit_file",
163
+ description: "Replace an exact unique substring in a file. old_string must appear exactly once; include enough surrounding context. " +
164
+ "For multiple replacements in the same file, use apply_patch (atomic, one write).",
165
+ parameters: obj({
166
+ path: str("Relative file path"),
167
+ old_string: str("Exact text to replace"),
168
+ new_string: str("Replacement text"),
169
+ }, ["path", "old_string", "new_string"]),
170
+ },
171
+ },
172
+ run: (ctx, args) => toolEditFile(ctx, args),
173
+ },
174
+ {
175
+ spec: {
176
+ type: "function",
177
+ function: {
178
+ name: "apply_patch",
179
+ description: "Apply multiple exact replacements to ONE file atomically. Edits run in order; each old_string must match exactly once " +
180
+ "in the content produced by the previous edits. If any edit fails, nothing is written. " +
181
+ "Use this instead of repeated edit_file calls for multi-hunk changes.",
182
+ parameters: obj({
183
+ path: str("Relative file path"),
184
+ edits: {
185
+ type: "array",
186
+ description: "Ordered list of replacements applied atomically (1–50).",
187
+ items: obj({
188
+ old_string: str("Exact text to replace (must be unique at its turn)"),
189
+ new_string: str("Replacement text"),
190
+ }, ["old_string", "new_string"]),
191
+ },
192
+ }, ["path", "edits"]),
193
+ },
194
+ },
195
+ run: (ctx, args) => toolApplyPatch(ctx, args),
196
+ },
197
+ {
198
+ spec: {
199
+ type: "function",
200
+ function: {
201
+ name: "run_command",
202
+ description: "Run a shell command in the working directory (sh/bash -c; Windows: Git Bash when installed, else cmd /c). Use for builds, tests, git, installing deps, etc.",
203
+ parameters: obj({
204
+ command: str("Shell command to run"),
205
+ timeout_secs: num("Timeout in seconds (default 120, max 600)"),
206
+ }, ["command"]),
207
+ },
208
+ },
209
+ run: (ctx, args) => toolRunCommand(ctx.workdir, args, ctx.signal, ctx.onToolOutput ? (stream, delta) => ctx.onToolOutput?.("run_command", stream, delta) : undefined, ctx.sandbox, ctx.reporter),
210
+ },
211
+ {
212
+ spec: {
213
+ type: "function",
214
+ function: {
215
+ name: "web_fetch",
216
+ description: "Fetch a public HTTP(S) URL and return its content as readable plain text " +
217
+ "(HTML converted to text, JSON pretty-printed). WHEN TO USE: the task depends on external, " +
218
+ "possibly outdated knowledge — library/API documentation, an error message or comment " +
219
+ "containing a URL, current package versions or changelogs, standards/specs. " +
220
+ "WHEN NOT TO: the answer is already in the working directory or in the user's request; " +
221
+ "you need a search engine (this tool fetches exact URLs only, it cannot search); " +
222
+ "the content is a binary file (images, archives, PDFs are refused). " +
223
+ "Private/internal addresses (localhost, 10.x, 192.168.x, 127.x) are blocked.",
224
+ parameters: obj({
225
+ url: str("Absolute http(s) URL to fetch"),
226
+ max_chars: str("Max characters of extracted content to return (default 20000, max 100000)"),
227
+ }, ["url"]),
228
+ },
229
+ },
230
+ run: (ctx, args) => toolWebFetch(ctx, args),
231
+ },
232
+ {
233
+ spec: {
234
+ type: "function",
235
+ function: {
236
+ name: "grep",
237
+ description: "Search file contents with a regex (ripgrep-backed, gitignore-aware). Returns path:line:text hits (max 50 by default), with optional context lines and a hit cap. " +
238
+ "Use for finding code by symbol, error string, or pattern. Combine with read_file for full context.",
239
+ parameters: obj({
240
+ pattern: str("Regular expression to search for"),
241
+ path: str("Directory or file to search (default: workdir root)"),
242
+ include: str("Glob filter for filenames, e.g. '*.ts'"),
243
+ context_before: num("Context lines to print before each match (default 0)"),
244
+ context_after: num("Context lines to print after each match (default 0)"),
245
+ max_results: num("Max matching lines to return (default 50, cap 100)"),
246
+ type: str("ripgrep file type filter, e.g. 'ts', 'py' (rg only; ignored by fallbacks)"),
247
+ }, ["pattern"]),
248
+ },
249
+ },
250
+ run: (ctx, args) => toolGrep(ctx.workdir, args),
251
+ },
252
+ {
253
+ spec: {
254
+ type: "function",
255
+ function: {
256
+ name: "glob",
257
+ description: "Find files by glob pattern (supports **, *, ?, {a,b}). Returns matching paths sorted, max 200. " +
258
+ "Use when you know the filename shape but not the location.",
259
+ parameters: obj({
260
+ pattern: str("Glob pattern relative to workdir, e.g. 'src/**/*.ts'"),
261
+ path: str("Directory to search (default: workdir root)"),
262
+ }, ["pattern"]),
263
+ },
264
+ },
265
+ run: (ctx, args) => toolGlob(ctx.workdir, args),
266
+ },
267
+ {
268
+ spec: {
269
+ type: "function",
270
+ function: {
271
+ name: "repo_map",
272
+ description: "Return the repository map — file tree with sizes + exported symbols (regex-extracted, budget-bounded, cached). " +
273
+ "Use to orient before reading files; cheaper than listing/reading everything.",
274
+ parameters: obj({ path: str("Sub-directory to map (default: repo root)") }, []),
275
+ },
276
+ },
277
+ run: (ctx, args) => {
278
+ try {
279
+ const sub = typeof args.path === "string" ? args.path.trim() : "";
280
+ const out = sub
281
+ ? renderRepoMap(ctx.workdir, 4000, sub)
282
+ : buildRepoMap(ctx.workdir);
283
+ return { ok: true, output: out };
284
+ }
285
+ catch (err) {
286
+ return { ok: false, output: `ERROR: repo map failed: ${err.message}` };
287
+ }
288
+ },
289
+ },
290
+ ];
291
+ export function getTool(name) {
292
+ return AGENT_TOOLS.find((t) => t.spec.function.name === name) ?? (name === "task" ? taskTool : undefined);
293
+ }
294
+ /** All tool specs incl. task (agent adds MCP specs on top). */
295
+ export function allToolSpecs() {
296
+ return [...AGENT_TOOLS.map((t) => t.spec), taskTool.spec];
297
+ }
@@ -0,0 +1,192 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { loadRcFile } from "../config/config.js";
5
+ import { resolveSandbox } from "../security/sandbox.js";
6
+ import { consoleReporter } from "../io/console-reporter.js";
7
+ import { clamp, MAX_OUTPUT_CHARS } from "./path-safety.js";
8
+ import { redactSecrets } from "../llm/llm.js";
9
+ // ── G3: child env allowlist ─────────────────────────────────────────────────
10
+ // spawn /bin/sh -c with the FULL process.env leaks every secret in the shell's
11
+ // environment (API keys, tokens) to any command the model runs — and thus to
12
+ // the conversation/log via `env` or a misbehaving tool. Allowlist instead.
13
+ /** Always passed through — minimum for node/python/git builds to work. */
14
+ const BASE_ENV_KEYS = [
15
+ "PATH", "HOME", "LANG", "LC_ALL", "TMPDIR", "TERM", "SHELL", "USER", "LOGNAME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME",
16
+ // Windows essentiels — cmd.exe/npm.cmd cần SystemRoot/ComSpec/PATHEXT để chạy;
17
+ // Node trên Windows tra env key không phân biệt hoa thường nên viết hoa cũng khớp.
18
+ "SYSTEMROOT", "SYSTEMDRIVE", "COMSPEC", "PATHEXT", "WINDIR", "TEMP", "TMP",
19
+ "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "APPDATA", "LOCALAPPDATA", "PROGRAMDATA",
20
+ "PROGRAMFILES", "PROGRAMFILES(X86)", "PUBLIC", "NUMBER_OF_PROCESSORS", "PROCESSOR_ARCHITECTURE",
21
+ ];
22
+ /**
23
+ * G3: build the child env. Base keys + SCODER_* config + explicit extras from
24
+ * the rc (`shellEnvAllow`), resolved from process.env. Missing keys are absent
25
+ * (not empty) so tools detect them correctly.
26
+ */
27
+ export function buildChildEnv(workdir, extraKeys) {
28
+ const rc = loadRcFile(workdir);
29
+ const allow = [...BASE_ENV_KEYS, ...(rc.shellEnvAllow ?? []), ...(extraKeys ?? [])];
30
+ const out = {};
31
+ for (const k of allow) {
32
+ const v = process.env[k];
33
+ if (v !== undefined)
34
+ out[k] = v;
35
+ }
36
+ // Windows + Git Bash: không có HOME — git/bash đọc config từ ~ (.gitconfig,
37
+ // ssh keys). Map HOME → USERPROFILE để git hoạt động đúng user hiện tại.
38
+ if (process.platform === "win32" && out.HOME === undefined && out.USERPROFILE) {
39
+ out.HOME = out.USERPROFILE;
40
+ }
41
+ return out;
42
+ }
43
+ /**
44
+ * Shell mặc định theo platform:
45
+ * - Unix → /bin/sh -c.
46
+ * - Windows → Git Bash nếu tìm thấy (model hay emit cú pháp POSIX: pipes, grep,
47
+ * rm -rf — cmd.exe không chạy được), fallback cmd.exe /d /c.
48
+ * KHÔNG dùng `where bash` — System32\bash.exe là WSL (sai filesystem).
49
+ */
50
+ export function defaultShellArgv(command) {
51
+ if (process.platform === "win32") {
52
+ const bash = findGitBash();
53
+ if (bash)
54
+ return [bash, "-c", command];
55
+ return [process.env.ComSpec || process.env.COMSPEC || "cmd.exe", "/d", "/c", command];
56
+ }
57
+ return ["/bin/sh", "-c", command];
58
+ }
59
+ /** Locate Git for Windows' bash.exe (cached); null when not installed. */
60
+ let gitBashCache;
61
+ function findGitBash() {
62
+ if (gitBashCache !== undefined)
63
+ return gitBashCache;
64
+ const pf = process.env.ProgramFiles ?? "C:\\Program Files";
65
+ const pf86 = process.env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)";
66
+ const local = process.env.LOCALAPPDATA;
67
+ const candidates = [
68
+ join(pf, "Git", "bin", "bash.exe"),
69
+ join(pf86, "Git", "bin", "bash.exe"),
70
+ ...(local ? [join(local, "Programs", "Git", "bin", "bash.exe")] : []),
71
+ ];
72
+ for (const c of candidates) {
73
+ if (existsSync(c)) {
74
+ gitBashCache = c;
75
+ return c;
76
+ }
77
+ }
78
+ gitBashCache = null;
79
+ return null;
80
+ }
81
+ /**
82
+ * Run a shell command asynchronously (async spawn keeps the event loop free,
83
+ * so streaming output renders and SIGINT is handled promptly).
84
+ * Kills the child on timeout or external abort (SIGINT via ctx.signal).
85
+ * When `onOutput` is provided, stdout/stderr chunks are forwarded live as they
86
+ * arrive (in addition to being collected into the final ToolResult).
87
+ * G3: output is redacted (secret shapes) before it enters the conversation,
88
+ * the live stream, or the JSONL log.
89
+ */
90
+ export async function toolRunCommand(workdir, args, signal, onOutput, sandbox, reporter = consoleReporter) {
91
+ const timeoutMs = Math.min(Math.max(args.timeout_secs ?? 120, 1), 600) * 1000;
92
+ // G3: the echoed command line itself may contain a secret (e.g. `curl -H
93
+ // "Authorization: Bearer sk-..."`) — redact the echo, never run redacted
94
+ // (the child gets the raw command).
95
+ const echoLine = `$ ${redactSecrets(args.command)}`;
96
+ // G4: sandbox wrap khi config bật. Wrapper thiếu → warn + chạy trực tiếp.
97
+ const sandboxed = await resolveSandbox(sandbox ?? {}, workdir, args.command);
98
+ if (sandboxed.argv) {
99
+ reporter.info(`sandbox: ${sandboxed.wrapper} (${(sandbox ?? {}).mode})`);
100
+ }
101
+ else if ((sandbox ?? {}).mode && (sandbox ?? {}).mode !== "off") {
102
+ reporter.warn(`sandbox: ${sandboxed.reason}`);
103
+ }
104
+ const spawnArgv = sandboxed.argv ?? defaultShellArgv(args.command);
105
+ return new Promise((resolve) => {
106
+ let settled = false;
107
+ const finish = (result) => {
108
+ if (settled)
109
+ return;
110
+ settled = true;
111
+ clearTimeout(timer);
112
+ signal?.removeEventListener("abort", onAbort);
113
+ resolve(result);
114
+ };
115
+ const child = spawn(spawnArgv[0], spawnArgv.slice(1), {
116
+ cwd: workdir,
117
+ stdio: ["ignore", "pipe", "pipe"],
118
+ env: buildChildEnv(workdir), // G3: allowlist — không kế thừa full process.env
119
+ });
120
+ let stdout = "";
121
+ let stderr = "";
122
+ let killedReason = null;
123
+ const killChild = (reason) => {
124
+ killedReason = reason;
125
+ try {
126
+ child.kill("SIGTERM");
127
+ }
128
+ catch { /* already dead */ }
129
+ // SIGKILL fallback if the process ignores SIGTERM
130
+ setTimeout(() => {
131
+ try {
132
+ if (child.exitCode === null)
133
+ child.kill("SIGKILL");
134
+ }
135
+ catch { /* already dead */ }
136
+ }, 5_000).unref();
137
+ };
138
+ const timer = setTimeout(() => killChild("timeout"), timeoutMs);
139
+ const onAbort = () => killChild("aborted");
140
+ if (signal?.aborted)
141
+ onAbort();
142
+ else
143
+ signal?.addEventListener("abort", onAbort, { once: true });
144
+ child.stdout?.on("data", (c) => {
145
+ const s = c.toString("utf8");
146
+ if (stdout.length < MAX_OUTPUT_CHARS)
147
+ stdout += s.slice(0, MAX_OUTPUT_CHARS - stdout.length);
148
+ onOutput?.("stdout", redactSecrets(s)); // G3
149
+ });
150
+ child.stderr?.on("data", (c) => {
151
+ const s = c.toString("utf8");
152
+ if (stderr.length < MAX_OUTPUT_CHARS)
153
+ stderr += s.slice(0, MAX_OUTPUT_CHARS - stderr.length);
154
+ onOutput?.("stderr", redactSecrets(s)); // G3
155
+ });
156
+ child.on("error", (err) => {
157
+ finish({ ok: false, output: clamp(`${echoLine}\n(spawn error) ${err.message}`) });
158
+ });
159
+ child.on("close", (code) => {
160
+ if (killedReason === "timeout") {
161
+ finish({
162
+ ok: false,
163
+ output: clamp(`${echoLine}\n(command timed out after ${Math.round(timeoutMs / 1000)}s and was killed)\n--- stdout ---\n${redactSecrets(stdout)}\n--- stderr ---\n${redactSecrets(stderr)}`),
164
+ });
165
+ return;
166
+ }
167
+ if (killedReason === "aborted") {
168
+ finish({
169
+ ok: false,
170
+ output: clamp(`${echoLine}\n(interrupted by user)\n--- stdout ---\n${redactSecrets(stdout)}\n--- stderr ---\n${redactSecrets(stderr)}`),
171
+ });
172
+ return;
173
+ }
174
+ const status = code ?? -1;
175
+ // G3: redact trước khi output vào conversation/log/TUI.
176
+ const redacted = redactSecrets(stdout);
177
+ const redactedErr = redactSecrets(stderr);
178
+ if (status === 0) {
179
+ finish({ ok: true, output: clamp(`${echoLine}\n(exit 0)\n${redacted}`) });
180
+ }
181
+ else {
182
+ finish({
183
+ ok: false,
184
+ output: clamp(`${echoLine}\n(exit ${status})\n--- stdout ---\n${redacted}\n--- stderr ---\n${redactedErr}`),
185
+ });
186
+ }
187
+ });
188
+ });
189
+ }
190
+ // ---------------------------------------------------------------------------
191
+ // Tool registry
192
+ // ---------------------------------------------------------------------------
@@ -0,0 +1,8 @@
1
+ export const obj = (properties, required) => ({
2
+ type: "object",
3
+ properties,
4
+ required,
5
+ additionalProperties: false,
6
+ });
7
+ export const str = (description) => ({ type: "string", description });
8
+ export const num = (description) => ({ type: "number", description });