@datename/fastcode-termux 0.1.6-beta → 0.1.8-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +50 -17
  3. package/dist/agent/approval-json.d.ts +43 -0
  4. package/dist/agent/approval-json.js +69 -0
  5. package/dist/agent/approval-native.d.ts +3 -0
  6. package/dist/agent/approval-native.js +165 -0
  7. package/dist/agent/approval-store.d.ts +16 -0
  8. package/dist/agent/approval-store.js +21 -0
  9. package/dist/agent/approval.d.ts +33 -0
  10. package/dist/agent/approval.js +40 -5
  11. package/dist/agent/compaction.d.ts +2 -0
  12. package/dist/agent/compaction.js +60 -17
  13. package/dist/agent/guards.d.ts +16 -16
  14. package/dist/agent/guards.js +978 -24
  15. package/dist/agent/policy/defaults.d.ts +16 -0
  16. package/dist/agent/policy/defaults.js +17 -0
  17. package/dist/agent/policy/egress.d.ts +32 -0
  18. package/dist/agent/policy/egress.js +280 -0
  19. package/dist/agent/process-tree.d.ts +20 -0
  20. package/dist/agent/process-tree.js +81 -10
  21. package/dist/agent/protocol.d.ts +20 -1
  22. package/dist/agent/protocol.js +165 -38
  23. package/dist/agent/registry.d.ts +3 -1
  24. package/dist/agent/registry.js +168 -11
  25. package/dist/agent/runner.d.ts +21 -0
  26. package/dist/agent/runner.js +44 -5
  27. package/dist/agent/shell-ast.d.ts +11 -0
  28. package/dist/agent/shell-ast.js +204 -0
  29. package/dist/agent/shell-session.d.ts +14 -0
  30. package/dist/agent/shell-session.js +251 -40
  31. package/dist/agent/tool-schemas.js +26 -7
  32. package/dist/agent/tools/append_file.js +3 -1
  33. package/dist/agent/tools/apply_patch.js +44 -4
  34. package/dist/agent/tools/copy_file.js +26 -3
  35. package/dist/agent/tools/delete_file.js +22 -3
  36. package/dist/agent/tools/grep.js +35 -4
  37. package/dist/agent/tools/make_dir.js +3 -1
  38. package/dist/agent/tools/move_path.d.ts +7 -0
  39. package/dist/agent/tools/move_path.js +31 -5
  40. package/dist/agent/tools/read_file.js +63 -3
  41. package/dist/agent/tools/read_many.js +21 -3
  42. package/dist/agent/tools/readers.d.ts +53 -1
  43. package/dist/agent/tools/readers.js +236 -26
  44. package/dist/agent/tools/replace_in_file.js +38 -5
  45. package/dist/agent/tools/shell.js +2 -2
  46. package/dist/agent/tools/types.d.ts +26 -0
  47. package/dist/agent/tools/validate.d.ts +15 -2
  48. package/dist/agent/tools/validate.js +66 -3
  49. package/dist/agent/tools/write_file.js +3 -1
  50. package/dist/app.d.ts +2 -1
  51. package/dist/app.js +526 -85
  52. package/dist/cli-main.js +363 -0
  53. package/dist/cli.js +397 -337
  54. package/dist/commands/about.js +1 -1
  55. package/dist/commands/clear.d.ts +1 -0
  56. package/dist/commands/clear.js +1 -1
  57. package/dist/commands/compact.d.ts +12 -0
  58. package/dist/commands/compact.js +14 -2
  59. package/dist/commands/context.js +5 -4
  60. package/dist/commands/index.js +2 -0
  61. package/dist/commands/jobs.js +3 -2
  62. package/dist/commands/kill.js +3 -1
  63. package/dist/commands/login.d.ts +2 -2
  64. package/dist/commands/login.js +15 -15
  65. package/dist/commands/model.d.ts +1 -13
  66. package/dist/commands/model.js +6 -38
  67. package/dist/commands/provider.d.ts +1 -15
  68. package/dist/commands/provider.js +4 -22
  69. package/dist/commands/skills.js +34 -4
  70. package/dist/commands/threads.d.ts +9 -0
  71. package/dist/commands/threads.js +26 -0
  72. package/dist/config/store.d.ts +21 -0
  73. package/dist/config/store.js +47 -9
  74. package/dist/config/trust.d.ts +9 -0
  75. package/dist/config/trust.js +41 -2
  76. package/dist/headless.d.ts +7 -0
  77. package/dist/headless.js +213 -0
  78. package/dist/index.js +19 -3
  79. package/dist/lib/debug.d.ts +2 -0
  80. package/dist/lib/debug.js +22 -0
  81. package/dist/lib/diagnostics.d.ts +19 -0
  82. package/dist/lib/diagnostics.js +32 -6
  83. package/dist/lib/highlight-subset.d.ts +21 -0
  84. package/dist/lib/highlight-subset.js +88 -0
  85. package/dist/lib/lifecycle.d.ts +5 -0
  86. package/dist/lib/lifecycle.js +62 -0
  87. package/dist/lib/markdown.js +22 -4
  88. package/dist/providers/deepseek.js +1 -1
  89. package/dist/providers/openaiCompatible.d.ts +24 -2
  90. package/dist/providers/openaiCompatible.js +20 -6
  91. package/dist/providers/spec.d.ts +12 -0
  92. package/dist/providers/spec.js +29 -0
  93. package/dist/session/log.d.ts +14 -2
  94. package/dist/session/log.js +56 -27
  95. package/dist/session/projection.d.ts +34 -1
  96. package/dist/session/projection.js +315 -46
  97. package/dist/skills/manager.d.ts +15 -0
  98. package/dist/skills/manager.js +135 -18
  99. package/dist/types.d.ts +15 -0
  100. package/dist/ui/StatusBar.js +1 -1
  101. package/package.json +3 -2
  102. package/src/agent/approval-json.ts +103 -0
  103. package/src/agent/approval-native.ts +168 -0
  104. package/src/agent/approval-store.ts +38 -0
  105. package/src/agent/approval.ts +58 -11
  106. package/src/agent/compaction.ts +62 -17
  107. package/src/agent/guards.ts +1049 -25
  108. package/src/agent/policy/defaults.ts +34 -0
  109. package/src/agent/policy/egress.ts +335 -0
  110. package/src/agent/process-tree.ts +105 -23
  111. package/src/agent/protocol.ts +187 -39
  112. package/src/agent/registry.ts +186 -14
  113. package/src/agent/runner.ts +50 -7
  114. package/src/agent/shell-ast.ts +227 -0
  115. package/src/agent/shell-session.ts +265 -41
  116. package/src/agent/tool-schemas.ts +26 -7
  117. package/src/agent/tools/append_file.ts +3 -1
  118. package/src/agent/tools/apply_patch.ts +45 -4
  119. package/src/agent/tools/copy_file.ts +27 -3
  120. package/src/agent/tools/delete_file.ts +22 -3
  121. package/src/agent/tools/grep.ts +36 -4
  122. package/src/agent/tools/make_dir.ts +3 -1
  123. package/src/agent/tools/move_path.ts +38 -5
  124. package/src/agent/tools/read_file.ts +64 -3
  125. package/src/agent/tools/read_many.ts +21 -3
  126. package/src/agent/tools/readers.ts +289 -26
  127. package/src/agent/tools/replace_in_file.ts +39 -5
  128. package/src/agent/tools/shell.ts +2 -2
  129. package/src/agent/tools/types.ts +43 -1
  130. package/src/agent/tools/validate.ts +73 -4
  131. package/src/agent/tools/write_file.ts +3 -1
  132. package/src/app.ts +533 -82
  133. package/src/{cli.ts → cli-main.ts} +34 -6
  134. package/src/commands/about.ts +1 -1
  135. package/src/commands/clear.ts +1 -1
  136. package/src/commands/compact.ts +14 -2
  137. package/src/commands/context.ts +5 -4
  138. package/src/commands/index.ts +2 -0
  139. package/src/commands/jobs.ts +3 -2
  140. package/src/commands/kill.ts +3 -1
  141. package/src/commands/login.ts +15 -15
  142. package/src/commands/model.ts +6 -38
  143. package/src/commands/provider.ts +4 -22
  144. package/src/commands/skills.ts +34 -4
  145. package/src/commands/threads.ts +28 -0
  146. package/src/config/store.ts +47 -9
  147. package/src/config/trust.ts +45 -2
  148. package/src/headless.ts +225 -0
  149. package/src/index.ts +19 -3
  150. package/src/lib/debug.ts +24 -0
  151. package/src/lib/diagnostics.ts +32 -6
  152. package/src/lib/highlight-subset.ts +93 -0
  153. package/src/lib/lifecycle.ts +69 -0
  154. package/src/lib/markdown.ts +22 -4
  155. package/src/providers/deepseek.ts +1 -1
  156. package/src/providers/openaiCompatible.ts +47 -10
  157. package/src/providers/spec.ts +42 -0
  158. package/src/session/log.ts +70 -27
  159. package/src/session/projection.ts +360 -47
  160. package/src/skills/manager.ts +140 -18
  161. package/src/types/highlight-shims.d.ts +14 -0
  162. package/src/types.ts +16 -1
  163. package/src/ui/StatusBar.ts +1 -1
  164. package/tsconfig.json +1 -0
  165. /package/dist/{cli.d.ts → cli-main.d.ts} +0 -0
@@ -1,18 +1,82 @@
1
- const TOOL_RE = /<fastcode_tool>([\s\S]*?)<\/fastcode_tool>/g;
2
1
  // Some models (notably DeepSeek) emit their native "DSML" tool-call markup
3
2
  // instead of <fastcode_tool>. The markers look like `<|DSML|invoke ...>`
4
3
  // (U+FF5C fullwidth bar, sometimes doubled or spaced). We canonicalize those
5
4
  // markers back to plain angle-bracket tags and then parse the
6
5
  // calls -> invoke -> parameter structure as a second dialect.
6
+ const FASTCODE_TOOL_OPEN = "<fastcode_tool>";
7
+ const FASTCODE_TOOL_CLOSE_RE = /<\/\s*fastcode_tool\s*>/gi;
8
+ const RESIDUAL_CLOSE_RE = /<\/\s*(?:fastcode_tool|parameter|invoke|calls)\s*>/i;
7
9
  const DSML_OPEN_RE = /<\s*(?:[||]\s*)+DSML\s*(?:[||]\s*)+/gi;
8
10
  const DSML_CLOSE_RE = /<\/\s*(?:[||]\s*)+DSML\s*(?:[||]\s*)+/gi;
9
- const DSML_BLOCK_RE = /<([a-z_]*calls?)>([\s\S]*?)<\/\1>/gi;
10
- const DSML_INVOKE_RE = /<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/gi;
11
- const DSML_PARAM_RE = /<parameter\s+name="([^"]+)"([^>]*)>([\s\S]*?)<\/parameter>/gi;
11
+ const DSML_BLOCK_RE = /<([a-z_]*calls?)>([\s\S]*?)<\/\s*\1\s*>/gi;
12
+ const DSML_INVOKE_RE = /<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/\s*invoke\s*>/gi;
13
+ const DSML_PARAM_RE = /<parameter\s+name="([^"]+)"([^>]*)>([\s\S]*?)<\/\s*parameter\s*>/gi;
14
+ const INVOKE_OPEN_RE = /<invoke\s+name="([^"]+)"\s*>/gi;
15
+
16
+ export interface ToolCallRecord {
17
+ tool: string;
18
+ [key: string]: any;
19
+ }
20
+
21
+ export interface ToolCallParseResult {
22
+ calls: ToolCallRecord[];
23
+ /** End offset of the last complete construct that was consumed. */
24
+ consumedEnd: number;
25
+ /** True parse failures. Salvaged calls do not add an error. */
26
+ errors: string[];
27
+ }
28
+
12
29
  /** Turn the DSML glyph markers into ordinary `<tag>` / `</tag>` tags. */
13
30
  function canonicalizeDsml(text) {
14
31
  return text.replace(DSML_CLOSE_RE, "</").replace(DSML_OPEN_RE, "<");
15
32
  }
33
+ function invokeToCall(invoke): ToolCallRecord {
34
+ const call: ToolCallRecord = { tool: invoke[1] };
35
+ for (const param of (invoke[2] ?? "").matchAll(DSML_PARAM_RE))
36
+ call[param[1]] = coerceDsmlValue(param[2] ?? "", param[3] ?? "");
37
+ return call;
38
+ }
39
+ function insideSpan(start: number, spans: Array<{ start: number; end: number }>): boolean {
40
+ return spans.some((span) => start >= span.start && start < span.end);
41
+ }
42
+ function matchFrom(text: string, from: number, re: RegExp): { start: number; end: number } | undefined {
43
+ re.lastIndex = from;
44
+ const match = re.exec(text);
45
+ if (!match || match.index === undefined)
46
+ return undefined;
47
+ return { start: match.index, end: match.index + match[0].length };
48
+ }
49
+ function parseJsonCall(body: string): ToolCallRecord | undefined {
50
+ try {
51
+ const parsed = JSON.parse(body.trim());
52
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && typeof parsed.tool === "string")
53
+ return parsed as ToolCallRecord;
54
+ }
55
+ catch {
56
+ // Malformed JSON is reported by the caller.
57
+ }
58
+ return undefined;
59
+ }
60
+ /**
61
+ * Recover a JSON object that starts at the beginning of `text` but may be
62
+ * followed by more markup (for example a drifted close tag). Returns the
63
+ * consumed prefix length so the caller can continue after it.
64
+ */
65
+ function salvageJsonPrefix(text: string): { call: ToolCallRecord; consumed: number } | undefined {
66
+ let searchFrom = 0;
67
+ while (searchFrom < text.length) {
68
+ const end = text.indexOf("}", searchFrom);
69
+ if (end < 0)
70
+ return undefined;
71
+ const call = parseJsonCall(text.slice(0, end + 1));
72
+ if (call) {
73
+ const close = matchFrom(text, end + 1, FASTCODE_TOOL_CLOSE_RE);
74
+ return { call, consumed: close ? close.end : end + 1 };
75
+ }
76
+ searchFrom = end + 1;
77
+ }
78
+ return undefined;
79
+ }
16
80
  function coerceDsmlValue(attrs, raw) {
17
81
  const value = raw.replace(/^\n/, "").replace(/\n$/, "");
18
82
  if (/\bstring\s*=\s*"true"/i.test(attrs))
@@ -32,44 +96,126 @@ function coerceDsmlValue(attrs, raw) {
32
96
  return Number.isNaN(n) ? value : n;
33
97
  }
34
98
  }
35
- function parseDsmlCalls(text) {
36
- const canonical = canonicalizeDsml(text);
37
- const bodies = [];
38
- for (const block of canonical.matchAll(DSML_BLOCK_RE))
39
- bodies.push(block[2] ?? "");
40
- if (bodies.length === 0)
41
- bodies.push(canonical);
42
- const calls = [];
43
- for (const body of bodies) {
44
- for (const invoke of body.matchAll(DSML_INVOKE_RE)) {
45
- const call = { tool: invoke[1] };
46
- for (const param of (invoke[2] ?? "").matchAll(DSML_PARAM_RE))
47
- call[param[1]] = coerceDsmlValue(param[2] ?? "", param[3] ?? "");
48
- calls.push(call);
99
+ /**
100
+ * Parse all complete tool calls, then salvage only the *remaining* text.
101
+ *
102
+ * Invariants (regression-tested):
103
+ * - a complete construct is consumed exactly once and never rescanned;
104
+ * - the salvage pass receives `raw.slice(consumedEnd)`, never the full text;
105
+ * - two adjacent normal calls plus a stray close tag stays at two calls.
106
+ */
107
+ export function parseToolCalls(text): ToolCallParseResult {
108
+ const raw = canonicalizeDsml(String(text ?? ""));
109
+ const calls: ToolCallRecord[] = [];
110
+ const errors: string[] = [];
111
+ const spans: Array<{ start: number; end: number }> = [];
112
+ let cursor = 0;
113
+ while (cursor < raw.length) {
114
+ const open = raw.indexOf(FASTCODE_TOOL_OPEN, cursor);
115
+ if (open < 0)
116
+ break;
117
+ const innerStart = open + FASTCODE_TOOL_OPEN.length;
118
+ const close = matchFrom(raw, innerStart, FASTCODE_TOOL_CLOSE_RE);
119
+ if (!close) {
120
+ const salvaged = salvageJsonPrefix(raw.slice(innerStart));
121
+ if (salvaged) {
122
+ calls.push(salvaged.call);
123
+ cursor = innerStart + salvaged.consumed;
124
+ spans.push({ start: open, end: cursor });
125
+ continue;
126
+ }
127
+ errors.push("unclosed <fastcode_tool> block; re-emit a complete tool call");
128
+ break;
129
+ }
130
+ const body = raw.slice(innerStart, close.start);
131
+ const full = parseJsonCall(body);
132
+ if (full) {
133
+ calls.push(full);
134
+ spans.push({ start: open, end: close.end });
135
+ cursor = close.end;
136
+ continue;
49
137
  }
138
+ // Closing drift: the JSON may be valid even when extra markup (or a
139
+ // second opener) sits before the matched close tag.
140
+ const prefix = salvageJsonPrefix(body);
141
+ if (prefix) {
142
+ calls.push(prefix.call);
143
+ cursor = innerStart + prefix.consumed;
144
+ spans.push({ start: open, end: cursor });
145
+ continue;
146
+ }
147
+ errors.push("invalid JSON inside <fastcode_tool>; re-emit a complete tool call");
148
+ spans.push({ start: open, end: close.end });
149
+ cursor = close.end;
50
150
  }
51
- return calls;
52
- }
53
- export function parseToolCalls(text) {
54
- const calls = [];
55
- for (const match of text.matchAll(TOOL_RE)) {
56
- const raw = match[1]?.trim();
57
- if (!raw)
151
+
152
+ // DSML dialect: parse each complete block once, then complete invokes that
153
+ // did not belong to a block. Spans prevent a second parse of the same text.
154
+ for (const block of raw.matchAll(DSML_BLOCK_RE)) {
155
+ const start = block.index ?? 0;
156
+ const end = start + block[0].length;
157
+ if (insideSpan(start, spans))
58
158
  continue;
59
- try {
60
- const parsed = JSON.parse(raw);
61
- if (typeof parsed.tool === "string")
62
- calls.push(parsed);
159
+ for (const invoke of (block[2] ?? "").matchAll(DSML_INVOKE_RE))
160
+ calls.push(invokeToCall(invoke));
161
+ spans.push({ start, end });
162
+ }
163
+ for (const invoke of raw.matchAll(DSML_INVOKE_RE)) {
164
+ const start = invoke.index ?? 0;
165
+ if (insideSpan(start, spans))
166
+ continue;
167
+ calls.push(invokeToCall(invoke));
168
+ spans.push({ start, end: start + invoke[0].length });
169
+ }
170
+
171
+ const consumedEnd = spans.reduce((max, span) => Math.max(max, span.end), 0);
172
+ salvageResidual(raw.slice(consumedEnd), calls, errors);
173
+ return { calls, consumedEnd, errors };
174
+ }
175
+
176
+ function salvageResidual(tail: string, calls: ToolCallRecord[], errors: string[]): void {
177
+ if (!tail.trim())
178
+ return;
179
+ let salvaged = false;
180
+
181
+ const toolOpen = tail.indexOf(FASTCODE_TOOL_OPEN);
182
+ if (toolOpen >= 0) {
183
+ const recovered = salvageJsonPrefix(tail.slice(toolOpen + FASTCODE_TOOL_OPEN.length));
184
+ if (recovered) {
185
+ calls.push(recovered.call);
186
+ salvaged = true;
63
187
  }
64
- catch {
65
- // Ignore malformed tool blocks; the model can correct itself next turn.
188
+ else {
189
+ errors.push("unclosed <fastcode_tool> block; re-emit a complete tool call");
66
190
  }
67
191
  }
68
- calls.push(...parseDsmlCalls(text));
69
- return calls;
192
+
193
+ const openers = Array.from(tail.matchAll(INVOKE_OPEN_RE));
194
+ openers.forEach((opener, index) => {
195
+ const start = opener.index ?? 0;
196
+ const bodyStart = start + opener[0].length;
197
+ const nextStart = openers[index + 1]?.index ?? tail.length;
198
+ const call = invokeToCall({ 1: opener[1], 2: tail.slice(bodyStart, nextStart) });
199
+ if (Object.keys(call).length > 1) {
200
+ calls.push(call);
201
+ salvaged = true;
202
+ }
203
+ else {
204
+ errors.push(`incomplete invoke for "${opener[1]}"; re-emit a complete tool call`);
205
+ }
206
+ });
207
+
208
+ if (!salvaged && openers.length === 0 && toolOpen < 0 && RESIDUAL_CLOSE_RE.test(tail))
209
+ errors.push("stray closing tag without an opening tool call; re-emit a complete tool call");
70
210
  }
211
+
71
212
  export function stripToolCalls(text) {
72
- return canonicalizeDsml(text).replace(TOOL_RE, "").replace(DSML_BLOCK_RE, "").trim();
213
+ return canonicalizeDsml(String(text ?? ""))
214
+ .replace(/<fastcode_tool>[\s\S]*?<\/\s*fastcode_tool\s*>/gi, "")
215
+ .replace(DSML_BLOCK_RE, "")
216
+ .replace(/<fastcode_tool>[\s\S]*$/i, "")
217
+ .replace(/<\/\s*(?:fastcode_tool|parameter|invoke|calls)\s*>/gi, "")
218
+ .trim();
73
219
  }
74
220
  export function formatToolResults(results) {
75
221
  const blocks = results.map((r, index) => {
@@ -101,19 +247,21 @@ Available tools:
101
247
  Polling returns only new output; use waitMs to wait briefly for more.
102
248
  - pwd: {"tool":"pwd"}
103
249
  - read_file: {"tool":"read_file","path":"path/to/file"}
104
- - read_many: {"tool":"read_many","paths":["file1","file2"]}
250
+ - read_file range: {"tool":"read_file","path":"large.ts","offset":800,"limit":50}
251
+ offset is 1-based; use it instead of reading a large file from the start.
252
+ - read_many: {"tool":"read_many","paths":["file1","file2"],"maxBytes":300000}
105
253
  - write_file: {"tool":"write_file","path":"path/to/file","content":"full file contents"}
106
254
  - append_file: {"tool":"append_file","path":"path/to/file","content":"text to append"}
107
255
  - apply_patch: {"tool":"apply_patch","patch":"*** Begin Patch\\n*** Update File: path\\n@@\\n-old\\n+new\\n*** End Patch\\n"}
108
256
  - list_files: {"tool":"list_files","path":"optional/path","maxDepth":2,"detail":false}
109
257
  - read_file is capped (default 200KB); grep skips files over 1MB. .fastcodeignore is honored.
110
- - grep: {"tool":"grep","pattern":"text or regex","path":"optional/path"}
111
- - replace_in_file: {"tool":"replace_in_file","path":"path/to/file","find":"exact text","replace":"replacement"}
258
+ - grep: {"tool":"grep","pattern":"text or regex","path":"optional/path","caseSensitive":false,"glob":"*.ts","context":2,"maxResults":200}
259
+ - replace_in_file: {"tool":"replace_in_file","path":"path/to/file","find":"exact text","replace":"replacement","expectedMatches":1}
112
260
  - stat_path: {"tool":"stat_path","path":"path/to/file"}
113
261
  - make_dir: {"tool":"make_dir","path":"path/to/dir"}
114
- - copy_file: {"tool":"copy_file","from":"src","to":"dest"}
262
+ - copy_file: {"tool":"copy_file","from":"src","to":"dest","overwrite":false}
115
263
  - move_path: {"tool":"move_path","from":"src","to":"dest"}
116
- - delete_file: {"tool":"delete_file","path":"path/to/file"}
264
+ - delete_file: {"tool":"delete_file","path":"path/to/file","recursive":false}
117
265
 
118
266
  Rules:
119
267
  - Prefer inspecting files before editing.
@@ -1,12 +1,64 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { isTrusted } from "../config/trust.js";
3
- import type { ApprovalDecision } from "./approval.js";
3
+ import {
4
+ DEFAULT_ALLOW_OPTIONS,
5
+ approvalRequestId,
6
+ type ApprovalDecision,
7
+ type ApprovalOption,
8
+ type ApprovalRequest,
9
+ } from "./approval.js";
10
+ import { approvalKey, isPreApproved, rememberApproval } from "./approval-store.js";
4
11
  import { evaluateShellCommand } from "./guards.js";
5
12
  import { TOOLS } from "./tools/index.js";
6
- import type { RevalidateKey, StateScope, Tool, ToolCall, ToolCtx, ToolResult } from "./tools/types.js";
13
+ import type { RevalidateKey, SideEffects, StateScope, Tool, ToolCall, ToolCtx, ToolErrorCode, ToolResult } from "./tools/types.js";
14
+ import { loadConfig } from "../config/store.js";
15
+ import {
16
+ egressAudit,
17
+ evaluateEgressCall,
18
+ evaluateEgressOutput,
19
+ formatEgressDenial,
20
+ normalizeEgressConfig,
21
+ } from "./policy/egress.js";
7
22
 
8
23
  const STATE_SCOPES = new Set<StateScope>(["call", "turn", "session"]);
9
24
  const REVALIDATE_KEYS = new Set<RevalidateKey>(["trust", "sandboxRoots", "schema", "modelCaps"]);
25
+ const TOOL_ERROR_CODES = new Set<ToolErrorCode>([
26
+ "ENOENT", "EACCES", "EEXIST", "ENOTDIR", "EISDIR", "EXDEV", "INVALID_ARGS",
27
+ "SANDBOX_DENY", "APPROVAL_DENY", "EGRESS_DENY", "NOT_FOUND", "ABORTED", "UNKNOWN",
28
+ ]);
29
+
30
+ function errorCode(error: any): ToolErrorCode {
31
+ const code = String(error?.code ?? "");
32
+ if (TOOL_ERROR_CODES.has(code as ToolErrorCode))
33
+ return code as ToolErrorCode;
34
+ const message = String(error?.message ?? error ?? "");
35
+ if (/outside sandbox/i.test(message))
36
+ return "SANDBOX_DENY";
37
+ if (/not trusted/i.test(message))
38
+ return "APPROVAL_DENY";
39
+ if (/aborted/i.test(message))
40
+ return "ABORTED";
41
+ return "UNKNOWN";
42
+ }
43
+
44
+ function unique(values: string[] | undefined): string[] {
45
+ return Array.from(new Set((values ?? []).filter(Boolean)));
46
+ }
47
+
48
+ function normalizeSideEffects(sideEffects: SideEffects | undefined): SideEffects | undefined {
49
+ if (!sideEffects)
50
+ return undefined;
51
+ const touched = unique(sideEffects.touched);
52
+ const created = unique(sideEffects.created);
53
+ const removed = unique(sideEffects.removed);
54
+ if (touched.length === 0 && created.length === 0 && removed.length === 0)
55
+ return undefined;
56
+ return {
57
+ ...(touched.length > 0 ? { touched } : {}),
58
+ ...(created.length > 0 ? { created } : {}),
59
+ ...(removed.length > 0 ? { removed } : {}),
60
+ };
61
+ }
10
62
 
11
63
  export function assertToolContract(tools: Tool[] = TOOLS): void {
12
64
  const names = new Set<string>();
@@ -42,10 +94,12 @@ export function toolCatalogHash(tools: Tool[] = TOOLS): string {
42
94
 
43
95
  export class ToolRegistry {
44
96
  private readonly tools = new Map<string, Tool>();
97
+ private readonly catalogHash: string;
45
98
  constructor(tools: Tool[] = TOOLS) {
46
99
  assertToolContract(tools);
47
100
  for (const tool of tools)
48
101
  this.tools.set(tool.name, tool);
102
+ this.catalogHash = toolCatalogHash(tools);
49
103
  }
50
104
  get(name: string): Tool | undefined {
51
105
  return this.tools.get(name);
@@ -59,6 +113,14 @@ export class ToolRegistry {
59
113
  return { kind: "deny", reason: `unknown tool: ${String(call.tool)}` };
60
114
  if (tool.name === "shell") {
61
115
  const verdict = evaluateShellCommand(call.command);
116
+ if (verdict.action === "hard_block")
117
+ return { kind: "deny", reason: verdict.output, code: verdict.code, target: verdict.target };
118
+ if (verdict.action === "soft_gate") {
119
+ const key = approvalKey(tool.name, call, ctx.cwd);
120
+ if (isPreApproved(key, this.catalogHash))
121
+ return { kind: "allow", scope: "once" };
122
+ return { kind: "pending", request: shellApprovalRequest(call, verdict) };
123
+ }
62
124
  if (!verdict.allow)
63
125
  return { kind: "deny", reason: verdict.output };
64
126
  }
@@ -73,26 +135,136 @@ export class ToolRegistry {
73
135
  async execute(call: ToolCall, ctx: ToolCtx): Promise<ToolResult> {
74
136
  const tool = this.get(call.tool);
75
137
  if (!tool)
76
- return { ok: false, output: `unknown tool: ${String(call.tool)}` };
77
- const prepared = tool.prepare(call, ctx);
138
+ return { ok: false, output: `unknown tool: ${String(call.tool)}`, code: "INVALID_ARGS" };
139
+ const toolCtx: ToolCtx = { ...ctx, catalogHash: this.catalogHash };
140
+ const prepared = tool.prepare(call, toolCtx);
78
141
  if (prepared.ok === false)
79
- return { ok: false, output: prepared.output };
80
- const decision = this.approve(call, ctx);
81
- if (decision.kind === "deny")
82
- return { ok: false, output: decision.reason ?? "denied by approval policy" };
83
- if (decision.kind === "pending")
84
- return { ok: false, output: "approval required, but no approval resolver is registered (fail closed)" };
142
+ return { ok: false, output: prepared.output, code: prepared.code ?? "INVALID_ARGS", hint: prepared.hint };
143
+ const egressConfig = normalizeEgressConfig(loadConfig().egress);
144
+ const preEgress = evaluateEgressCall(call, ctx.cwd, egressConfig);
145
+ if (preEgress.action === "deny") {
146
+ const egressDecision = preEgress.decision!;
147
+ return {
148
+ ok: false,
149
+ output: formatEgressDenial(egressDecision),
150
+ code: "EGRESS_DENY",
151
+ hint: "Egress policy blocked this call before execution; no approval request was created.",
152
+ egress: egressAudit(egressDecision),
153
+ };
154
+ }
155
+ const preAudit = preEgress.decision ? egressAudit(preEgress.decision) : undefined;
156
+ const decision = this.approve(call, toolCtx);
157
+ if (decision.kind === "deny") {
158
+ const output = decision.reason ?? "denied by approval policy";
159
+ if (tool.name === "shell" && (decision.code === "sensitive_file_egress" || decision.code === "credential_read")) {
160
+ return {
161
+ ok: false,
162
+ output,
163
+ code: "EGRESS_DENY",
164
+ egress: {
165
+ outlet: "shell.command",
166
+ ...(decision.target ? { target: decision.target } : {}),
167
+ rule: decision.code,
168
+ mode: "block",
169
+ wouldBlock: true,
170
+ code: "EGRESS_DENY",
171
+ reason: decision.code,
172
+ },
173
+ };
174
+ }
175
+ return { ok: false, output, code: "APPROVAL_DENY" };
176
+ }
177
+ if (decision.kind === "pending") {
178
+ if (!ctx.requestApproval)
179
+ return { ok: false, output: "approval required, but no approval resolver is registered (fail closed)", code: "APPROVAL_DENY" };
180
+ let resolved: ApprovalDecision | undefined;
181
+ try {
182
+ resolved = await ctx.requestApproval(decision.request);
183
+ }
184
+ catch (err: any) {
185
+ return { ok: false, output: `approval failed (fail closed): ${err?.message ?? String(err)}`, code: "APPROVAL_DENY" };
186
+ }
187
+ if (!resolved || resolved.kind === "pending")
188
+ return { ok: false, output: "approval unresolved; nothing was executed (fail closed)", code: "APPROVAL_DENY" };
189
+ if (resolved.kind !== "allow") {
190
+ const reason = resolved.kind === "deny" ? resolved.reason : resolved.kind === "feedback" ? resolved.text : `decision ${resolved.kind} requires a later batch`;
191
+ return { ok: false, output: `approval denied: ${reason ?? "no reason"}`, code: "APPROVAL_DENY" };
192
+ }
193
+ rememberApproval(approvalKey(tool.name, call, ctx.cwd), this.catalogHash, resolved.scope);
194
+ }
85
195
  try {
86
- return await tool.execute(call, ctx);
196
+ let result: ToolResult = await tool.execute(call, toolCtx);
197
+ result = {
198
+ ...result,
199
+ sideEffects: normalizeSideEffects(result.sideEffects),
200
+ ...(preAudit && !result.egress ? { egress: preAudit } : {}),
201
+ };
202
+ const postEgress = evaluateEgressOutput(call.tool, result.output, egressConfig);
203
+ if (postEgress.action === "deny") {
204
+ const egressDecision = postEgress.decision!;
205
+ return {
206
+ ok: false,
207
+ output: formatEgressDenial(egressDecision),
208
+ code: "EGRESS_DENY",
209
+ hint: "Egress policy blocked this tool output before it reached the model.",
210
+ sideEffects: result.sideEffects,
211
+ egress: egressAudit(egressDecision),
212
+ };
213
+ }
214
+ if (postEgress.decision)
215
+ result = { ...result, egress: egressAudit(postEgress.decision) };
216
+ return result;
87
217
  }
88
218
  catch (err: any) {
89
- return { ok: false, output: err?.message ?? String(err) };
219
+ const output = err?.message ?? String(err);
220
+ const postEgress = evaluateEgressOutput(call.tool, output, egressConfig);
221
+ if (postEgress.action === "deny") {
222
+ const egressDecision = postEgress.decision!;
223
+ return {
224
+ ok: false,
225
+ output: formatEgressDenial(egressDecision),
226
+ code: "EGRESS_DENY",
227
+ hint: "Egress policy blocked this error output before it reached the model.",
228
+ egress: egressAudit(egressDecision),
229
+ };
230
+ }
231
+ return {
232
+ ok: false,
233
+ output,
234
+ code: errorCode(err),
235
+ ...(preAudit ? { egress: preAudit } : {}),
236
+ ...(postEgress.decision ? { egress: egressAudit(postEgress.decision) } : {}),
237
+ };
90
238
  }
91
239
  }
92
240
  }
93
241
 
242
+ function shellApprovalRequest(call: ToolCall, verdict: { code: string; target?: string; reason?: string; output?: string }): ApprovalRequest {
243
+ const options = DEFAULT_ALLOW_OPTIONS.map((option) => ({ ...option })) as ApprovalOption[];
244
+ const denyIndex = options.findIndex((option) => option.kind === "deny");
245
+ const target = verdict.target ?? "";
246
+ const prompt = `Shell command needs approval: ${verdict.code}${target ? ` (${target})` : ""}`;
247
+ return {
248
+ id: approvalRequestId(),
249
+ tool: "shell",
250
+ args: call,
251
+ reason: "destructive",
252
+ options,
253
+ tier: 2,
254
+ prompt,
255
+ source: "system",
256
+ defaultIndex: denyIndex >= 0 ? denyIndex : 0,
257
+ timeoutMs: 60_000,
258
+ };
259
+ }
260
+
94
261
  export const registry = new ToolRegistry();
95
262
 
96
- export async function runAgentTool(call: ToolCall, cwd = process.cwd(), options: { signal?: AbortSignal; turn?: number } = {}): Promise<ToolResult> {
97
- return registry.execute(call, { cwd, signal: options.signal, turn: options.turn });
263
+ export async function runAgentTool(call: ToolCall, cwd = process.cwd(), options: { signal?: AbortSignal; turn?: number; requestApproval?: import("./approval.js").ApprovalResolver } = {}): Promise<ToolResult> {
264
+ return registry.execute(call, {
265
+ cwd,
266
+ signal: options.signal,
267
+ turn: options.turn,
268
+ requestApproval: options.requestApproval,
269
+ });
98
270
  }
@@ -2,11 +2,12 @@ import { createHash } from "node:crypto";
2
2
  import { readFileSync, statSync } from "node:fs";
3
3
  import type { ChatChunk, ChatMessage, NativeToolCall, Provider, ReasoningEffort, ToolSchema } from "../types.js";
4
4
  import type { ActiveFile } from "../session/log.js";
5
- import type { SideEffects } from "./tools/types.js";
5
+ import type { SideEffects, ToolResult } from "./tools/types.js";
6
6
  import { estMessagesTokens, estTokens, getModelMeta } from "../lib/model-meta.js";
7
7
  import { compactMessages, DEFAULT_COMPACTION_CONFIG, type CompactionConfig } from "./compaction.js";
8
8
  import { isLoopExempt, isReadOnlyToolCall, toolCallFingerprint } from "./guards.js";
9
9
  import { isNativeUnsupportedError, type ToolProtocol } from "./protocol-mode.js";
10
+ import type { ApprovalResolver } from "./approval.js";
10
11
  import { formatToolResults, parseToolCalls, stripToolCalls } from "./protocol.js";
11
12
  import { runStream } from "./stream.js";
12
13
  import { runAgentTool } from "./tools.js";
@@ -49,6 +50,7 @@ export interface RunOptions {
49
50
  onNativeOk?: () => void;
50
51
  takeSteering?: () => string[];
51
52
  onDelta?: (delta: string, text: string) => void;
53
+ requestApproval?: ApprovalResolver;
52
54
  }
53
55
 
54
56
  export type AgentStopReason =
@@ -79,7 +81,8 @@ export type AgentEvent =
79
81
  | { type: "assistant_raw"; text: string; toolCalls?: NativeToolCall[] }
80
82
  | { type: "assistant_text"; text: string }
81
83
  | { type: "tool_call"; id: string; call: ToolCall; native?: boolean }
82
- | { type: "tool_result"; id: string; call: ToolCall; ok: boolean; output: string; sideEffects?: SideEffects }
84
+ | { type: "tool_result"; id: string; call: ToolCall; ok: boolean; output: string; sideEffects?: SideEffects; code?: string; hint?: string; truncated?: boolean; totalLines?: number; returnedLines?: number; totalBytes?: number; returnedBytes?: number; filesRead?: number; filesSkipped?: number; matches?: number }
85
+ | { type: "egress_denied"; outlet: string; target?: string; rule: string; mode: "audit" | "block"; wouldBlock: boolean; code: "EGRESS_DENY"; reason: string }
83
86
  | { type: "usage"; usage: NonNullable<ChatChunk["usage"]> }
84
87
  | { type: "loop_detected"; fingerprint: string; occurrences: number; warned: boolean }
85
88
  | { type: "notice"; text: string }
@@ -258,6 +261,8 @@ export async function* runAgent(options: RunOptions): AsyncGenerator<AgentEvent,
258
261
  }
259
262
  if (resetNotice)
260
263
  yield { type: "notice", text: resetNotice };
264
+ if (streamed.retried > 0)
265
+ yield { type: "notice", text: `Network stream was interrupted; retried ${streamed.retried} time(s).` };
261
266
  if (streamed.usage) {
262
267
  consumedInput += streamed.usage.inputTokens ?? promptTokens;
263
268
  spentCost += streamed.usage.costUsd ?? 0;
@@ -321,9 +326,11 @@ export async function* runAgent(options: RunOptions): AsyncGenerator<AgentEvent,
321
326
  yield { type: "tool_call", id, call, native: true };
322
327
  const result: any = parseError
323
328
  ? { ok: false, output: parseError }
324
- : await runAgentTool(call, cwd, { signal, turn: turn + 1 });
329
+ : await runAgentTool(call, cwd, { signal, turn: turn + 1, requestApproval: options.requestApproval });
325
330
  trackSideEffects(activeFiles, result.sideEffects);
326
- yield { type: "tool_result", id, call, ok: Boolean(result.ok), output: String(result.output ?? ""), sideEffects: result.sideEffects };
331
+ if (result.egress)
332
+ yield { type: "egress_denied", ...result.egress };
333
+ yield { type: "tool_result", id, call, ok: Boolean(result.ok), output: String(result.output ?? ""), ...toolResultMeta(result) };
327
334
  history = [...history, { role: "tool", toolCallId: id, content: String(result.output ?? "") }];
328
335
  }
329
336
  yield { type: "checkpoint", turn: turn + 1, cwd, providerId: provider.id, model, activeFiles: Array.from(activeFiles.values()) };
@@ -333,9 +340,27 @@ export async function* runAgent(options: RunOptions): AsyncGenerator<AgentEvent,
333
340
  break;
334
341
  continue;
335
342
  }
336
- const calls: ToolCall[] = options.allowTools === false ? [] : parseToolCalls(streamed.text);
343
+ const parsed = options.allowTools === false
344
+ ? { calls: [] as ToolCall[], consumedEnd: 0, errors: [] as string[] }
345
+ : parseToolCalls(streamed.text);
346
+ const calls: ToolCall[] = parsed.calls;
337
347
  yield { type: "assistant_raw", text: streamed.text };
338
348
  if (calls.length === 0) {
349
+ if (parsed.errors.length > 0) {
350
+ // Never let a broken tool-call block end the turn silently: the
351
+ // model would wait forever for a tool result. Inject a visible
352
+ // tool error and continue so it can re-emit valid markup.
353
+ const id = `tc_${++toolCallSeq}`;
354
+ const call: ToolCall = { tool: "protocol_error" };
355
+ const output = "Previous output contained invalid tool-call markup. " +
356
+ "Re-emit a complete <fastcode_tool>{\"tool\":...}</fastcode_tool> block.\n" +
357
+ parsed.errors.join("\n");
358
+ yield { type: "tool_call", id, call };
359
+ yield { type: "tool_result", id, call, ok: false, output, code: "INVALID_ARGS", hint: "Re-emit a complete tool call." };
360
+ history = [...history, { role: "user", content: formatToolResults([{ call, ok: false, output }]) }];
361
+ yield { type: "checkpoint", turn: turn + 1, cwd, providerId: provider.id, model, activeFiles: Array.from(activeFiles.values()) };
362
+ continue;
363
+ }
339
364
  lastVisible = visibleText || streamed.text;
340
365
  naturalFinish = true;
341
366
  stopReason = "complete";
@@ -367,10 +392,12 @@ export async function* runAgent(options: RunOptions): AsyncGenerator<AgentEvent,
367
392
  }
368
393
  const id = `tc_${++toolCallSeq}`;
369
394
  yield { type: "tool_call", id, call };
370
- const result: any = await runAgentTool(call, cwd, { signal, turn: turn + 1 });
395
+ const result: any = await runAgentTool(call, cwd, { signal, turn: turn + 1, requestApproval: options.requestApproval });
371
396
  results.push({ call, ok: Boolean(result.ok), output: String(result.output ?? ""), sideEffects: result.sideEffects });
372
397
  trackSideEffects(activeFiles, result.sideEffects);
373
- yield { type: "tool_result", id, call, ok: Boolean(result.ok), output: String(result.output ?? ""), sideEffects: result.sideEffects };
398
+ if (result.egress)
399
+ yield { type: "egress_denied", ...result.egress };
400
+ yield { type: "tool_result", id, call, ok: Boolean(result.ok), output: String(result.output ?? ""), ...toolResultMeta(result) };
374
401
  }
375
402
  if (results.length > 0)
376
403
  history = [...history, { role: "user", content: formatToolResults(results) }];
@@ -415,6 +442,22 @@ function optionalPositive(value: number | undefined): number | undefined {
415
442
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
416
443
  }
417
444
 
445
+ function toolResultMeta(result: ToolResult) {
446
+ return {
447
+ sideEffects: result.sideEffects,
448
+ ...(result.code ? { code: result.code } : {}),
449
+ ...(result.hint ? { hint: result.hint } : {}),
450
+ ...(result.truncated !== undefined ? { truncated: result.truncated } : {}),
451
+ ...(result.totalLines !== undefined ? { totalLines: result.totalLines } : {}),
452
+ ...(result.returnedLines !== undefined ? { returnedLines: result.returnedLines } : {}),
453
+ ...(result.totalBytes !== undefined ? { totalBytes: result.totalBytes } : {}),
454
+ ...(result.returnedBytes !== undefined ? { returnedBytes: result.returnedBytes } : {}),
455
+ ...(result.filesRead !== undefined ? { filesRead: result.filesRead } : {}),
456
+ ...(result.filesSkipped !== undefined ? { filesSkipped: result.filesSkipped } : {}),
457
+ ...(result.matches !== undefined ? { matches: result.matches } : {}),
458
+ };
459
+ }
460
+
418
461
  function trackSideEffects(activeFiles: Map<string, ActiveFile>, sideEffects: SideEffects | undefined): void {
419
462
  if (!sideEffects)
420
463
  return;