@robhowley/pi-structured-return 1.10.0 → 2.0.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 (110) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -83
  3. package/extensions/structured-return/config/registry.ts +4 -30
  4. package/extensions/structured-return/index.ts +105 -76
  5. package/extensions/structured-return/native.ts +223 -0
  6. package/extensions/structured-return/parsers/ava-text.ts +2 -168
  7. package/extensions/structured-return/parsers/bandit-json.ts +2 -79
  8. package/extensions/structured-return/parsers/black-text.ts +2 -73
  9. package/extensions/structured-return/parsers/cargo-build.ts +2 -78
  10. package/extensions/structured-return/parsers/cargo-test.ts +2 -135
  11. package/extensions/structured-return/parsers/checkstyle-xml.ts +2 -182
  12. package/extensions/structured-return/parsers/clang-text.ts +2 -60
  13. package/extensions/structured-return/parsers/dbt-json.ts +2 -135
  14. package/extensions/structured-return/parsers/dotnet-build-text.ts +2 -49
  15. package/extensions/structured-return/parsers/eslint-json.ts +2 -38
  16. package/extensions/structured-return/parsers/go-test-json.ts +2 -138
  17. package/extensions/structured-return/parsers/hadolint-json.ts +2 -60
  18. package/extensions/structured-return/parsers/htmlhint-json.ts +2 -73
  19. package/extensions/structured-return/parsers/isort-text.ts +2 -63
  20. package/extensions/structured-return/parsers/javac-text.ts +2 -82
  21. package/extensions/structured-return/parsers/jsonlint-text.ts +2 -65
  22. package/extensions/structured-return/parsers/junit-xml.ts +2 -325
  23. package/extensions/structured-return/parsers/markdownlint-json.ts +2 -74
  24. package/extensions/structured-return/parsers/minitest-text.ts +2 -107
  25. package/extensions/structured-return/parsers/mocha-json.ts +2 -83
  26. package/extensions/structured-return/parsers/mypy-json.ts +2 -79
  27. package/extensions/structured-return/parsers/node-test-text.ts +2 -92
  28. package/extensions/structured-return/parsers/npm-audit-json.ts +2 -90
  29. package/extensions/structured-return/parsers/prettier-text.ts +2 -66
  30. package/extensions/structured-return/parsers/pylint-json.ts +2 -63
  31. package/extensions/structured-return/parsers/pyright-json.ts +2 -82
  32. package/extensions/structured-return/parsers/rspec-json.ts +2 -75
  33. package/extensions/structured-return/parsers/rubocop-json.ts +2 -75
  34. package/extensions/structured-return/parsers/ruff-json.ts +2 -36
  35. package/extensions/structured-return/parsers/shellcheck-json.ts +2 -60
  36. package/extensions/structured-return/parsers/stylelint-json.ts +2 -75
  37. package/extensions/structured-return/parsers/swiftc-text.ts +2 -52
  38. package/extensions/structured-return/parsers/tail-fallback.ts +2 -19
  39. package/extensions/structured-return/parsers/tidy-text.ts +2 -66
  40. package/extensions/structured-return/parsers/tsc-text.ts +2 -46
  41. package/extensions/structured-return/parsers/unittest-text.ts +2 -125
  42. package/extensions/structured-return/parsers/utils.ts +28 -0
  43. package/extensions/structured-return/parsers/vale-json.ts +2 -79
  44. package/extensions/structured-return/parsers/vitest-json.ts +2 -59
  45. package/extensions/structured-return/storage/log-store.ts +0 -15
  46. package/extensions/structured-return/types.ts +1 -14
  47. package/native/Cargo.lock +193 -0
  48. package/native/Cargo.toml +21 -0
  49. package/native/THIRD-PARTY-LICENSES.txt +3660 -0
  50. package/native/bin/darwin-arm64/build.json +7 -0
  51. package/native/bin/darwin-arm64/structured-return-native +0 -0
  52. package/native/bin/darwin-x64/build.json +7 -0
  53. package/native/bin/darwin-x64/structured-return-native +0 -0
  54. package/native/bin/linux-arm64-musl/build.json +7 -0
  55. package/native/bin/linux-arm64-musl/structured-return-native +0 -0
  56. package/native/bin/linux-x64-musl/build.json +7 -0
  57. package/native/bin/linux-x64-musl/structured-return-native +0 -0
  58. package/native/src/common.rs +118 -0
  59. package/native/src/main.rs +55 -0
  60. package/native/src/parsers/ava_text.rs +125 -0
  61. package/native/src/parsers/bandit_json.rs +120 -0
  62. package/native/src/parsers/black_text.rs +45 -0
  63. package/native/src/parsers/cargo_build.rs +96 -0
  64. package/native/src/parsers/cargo_test.rs +140 -0
  65. package/native/src/parsers/checkstyle_xml.rs +137 -0
  66. package/native/src/parsers/clang_text.rs +39 -0
  67. package/native/src/parsers/compiler_helpers.rs +74 -0
  68. package/native/src/parsers/dbt_json.rs +243 -0
  69. package/native/src/parsers/dotnet_build_text.rs +50 -0
  70. package/native/src/parsers/eslint_json.rs +58 -0
  71. package/native/src/parsers/go_test_json.rs +346 -0
  72. package/native/src/parsers/hadolint_json.rs +37 -0
  73. package/native/src/parsers/htmlhint_json.rs +71 -0
  74. package/native/src/parsers/isort_text.rs +22 -0
  75. package/native/src/parsers/javac_text.rs +49 -0
  76. package/native/src/parsers/json_support.rs +287 -0
  77. package/native/src/parsers/jsonlint_text.rs +50 -0
  78. package/native/src/parsers/junit_xml.rs +430 -0
  79. package/native/src/parsers/markdownlint_json.rs +68 -0
  80. package/native/src/parsers/minitest_text.rs +91 -0
  81. package/native/src/parsers/mocha_json.rs +75 -0
  82. package/native/src/parsers/mod.rs +119 -0
  83. package/native/src/parsers/mypy_json.rs +93 -0
  84. package/native/src/parsers/node_test_text.rs +106 -0
  85. package/native/src/parsers/npm_audit_json.rs +119 -0
  86. package/native/src/parsers/prettier_text.rs +34 -0
  87. package/native/src/parsers/pylint_json.rs +44 -0
  88. package/native/src/parsers/pyright_json.rs +88 -0
  89. package/native/src/parsers/rspec_json.rs +84 -0
  90. package/native/src/parsers/rubocop_json.rs +46 -0
  91. package/native/src/parsers/ruff_json.rs +30 -0
  92. package/native/src/parsers/shellcheck_json.rs +40 -0
  93. package/native/src/parsers/stylelint_json.rs +46 -0
  94. package/native/src/parsers/swiftc_text.rs +38 -0
  95. package/native/src/parsers/tail_fallback.rs +51 -0
  96. package/native/src/parsers/test_helpers.rs +172 -0
  97. package/native/src/parsers/tidy_text.rs +77 -0
  98. package/native/src/parsers/tsc_text.rs +28 -0
  99. package/native/src/parsers/unittest_text.rs +125 -0
  100. package/native/src/parsers/vale_json.rs +66 -0
  101. package/native/src/parsers/vitest_json.rs +71 -0
  102. package/native/src/parsers/xml_support.rs +241 -0
  103. package/native/src/runner.rs +252 -0
  104. package/package.json +22 -7
  105. package/scripts/build-native.mjs +73 -0
  106. package/scripts/native-artifacts.mjs +69 -0
  107. package/skills/structured-return/SKILL.md +103 -249
  108. package/extensions/structured-return/config/project-config.ts +0 -10
  109. package/extensions/structured-return/examples/.pi/machine-readable.json +0 -18
  110. package/extensions/structured-return/examples/.pi/parsers/foo-cli.ts +0 -25
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rob Howley
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # pi-structured-return
2
2
 
3
- A [Pi](https://pi.dev/) extension that adds a `structured_return` tool alongside `bash`, returning compact parsed results with full logs — 60–95% fewer tokens without losing signal.
3
+ A Rust-powered [Pi](https://pi.dev/) extension that cuts token costs with compact command results and preserves full logs. Adds the `structured_return` tool.
4
4
 
5
5
  A failing test run, before and after:
6
6
 
@@ -54,9 +54,20 @@ pytest test_math.py --junitxml=.tmp/report.xml → cwd: project
54
54
  pi install npm:@robhowley/pi-structured-return
55
55
  ```
56
56
 
57
+ Supports macOS 11+ and Linux on x64/arm64. Windows is not supported.
58
+
57
59
  ## Design
58
60
 
59
- `structured_return` is a separate tool, not a wrapper around `bash`. Intercepting `bash` to silently rewrite commands would override a primitive the model and platform both rely on. Pi's philosophy is to extend rather than obfuscate: features are built on top of the platform, not hidden inside it. A dedicated tool honors that. It adds to the available surface, keeps `bash` honest, and leaves the choice explicit. The skill guides the model toward it; nothing is hijacked to get there.
61
+ `structured_return` is a separate tool, not a wrapper around `bash`. It doesn't intercept `bash` calls or silently rewrite commands. The agent chooses which tool to use, with the skill guiding it toward `structured_return` when compact output helps. This follows Pi's approach: build on, don't obfuscate, existing primitives to extend the harness.
62
+
63
+ ## How it works
64
+
65
+ 1. The agent runs commands through `structured_return` when it would reduce noise and token usage.
66
+ 2. Full output is captured.
67
+ 3. A parser converts noisy CLI output into a compact structured result. If no parser matches, a successful command returns only `command completed; no parser matched`, with the log path in tool details. An unsuccessful unmatched command returns the last 200 log lines and the log path in the text.
68
+ 4. The agent receives the structured result in context — signal only, no noise.
69
+
70
+ Full logs remain on disk for the agent and humans to inspect. Run `/sr-parsers` in a pi session to see built-in parsers and their auto-detection rules. Run `/sr-stats` to see token savings for the current session, cwd lifetime, and lifetime.
60
71
 
61
72
  ## Token reduction
62
73
 
@@ -160,86 +171,6 @@ Evaluated for structured parsing but raw output is already compact enough that a
160
171
  | `vulture` | 58 | `file:line: message (confidence%)` | single line per finding |
161
172
  | `pydocstyle` | 48 | `file:line context + CODE: message` | two lines per issue; structured format would repeat file paths |
162
173
 
163
- ## How it works
164
-
165
- 1. The agent runs commands through `structured_return` when it would reduce noise and token usage.
166
- 2. Full output is captured and stored as a log.
167
- 3. A parser converts noisy CLI output into a compact structured result. If no parser matches, the last 200 lines and the log path are returned as a fallback.
168
- 4. The agent receives the structured result in context — signal only, no noise.
169
- 5. The full log is always available on disk for both the agent and humans to inspect.
170
- 6. Run `/sr-stats` to see how many tokens structured-return has saved — for the current session, the current working directory, and lifetime across all sessions.
171
-
172
- Run `/sr-parsers` in a pi session to see all registered parsers with their match rules. Run `/sr-stats` to see token savings for the current session, cwd lifetime, and lifetime.
173
-
174
- ## Extending with project-local parsers
175
-
176
- Built-in parsers cover common tools. For everything else — internal CLIs, custom test runners, proprietary lint tools — add a `.pi/structured-return.json` to your project root.
177
-
178
- **Why:** keeps token costs low for tools the built-ins don't know about, without forking the package.
179
-
180
- **Two options:**
181
-
182
- ### 1. Re-use a built-in parser
183
-
184
- Route a project-specific command to an existing parser. Use this when your tool's output already matches a supported format (e.g. a test runner that emits JUnit XML).
185
-
186
- ```json
187
- // .pi/structured-return.json
188
- {
189
- "parsers": [
190
- {
191
- "id": "acme-tests",
192
- "match": { "argvIncludes": ["acme", "test"] },
193
- "parseAs": "junit-xml"
194
- }
195
- ]
196
- }
197
- ```
198
-
199
- ### 2. Write a custom parser
200
-
201
- Point to a local `.ts` file for tools with unique output formats.
202
-
203
- ```json
204
- // .pi/structured-return.json
205
- {
206
- "parsers": [
207
- {
208
- "id": "foo-json",
209
- "match": { "argvIncludes": ["foo-cli", "check"] },
210
- "module": "parsers/foo-cli.js"
211
- }
212
- ]
213
- }
214
- ```
215
-
216
- ```ts
217
- // .pi/parsers/foo-cli.ts
218
- import fs from "node:fs";
219
- import type { RunContext } from "@robhowley/pi-structured-return/types";
220
-
221
- export default {
222
- id: "foo-json",
223
- async parse(ctx: RunContext) {
224
- const data = JSON.parse(fs.readFileSync(ctx.stdoutPath, "utf8"));
225
- return {
226
- tool: "foo-cli",
227
- status: data.ok ? "pass" : "fail",
228
- summary: data.ok ? "passed" : `${data.errors.length} errors`,
229
- failures: data.errors.map((e, i) => ({
230
- id: e.id ?? `error-${i}`,
231
- file: e.file,
232
- line: e.line,
233
- message: e.message,
234
- })),
235
- logPath: ctx.logPath,
236
- };
237
- },
238
- };
239
- ```
240
-
241
- The parser receives a `RunContext` (command, argv, cwd, stdout/stderr paths, artifact paths, log path) and returns a `ParsedResult`. Match rules support `argvIncludes` (array of required tokens) or `regex` (tested against the full argv string).
242
-
243
174
  ## Structured result schema
244
175
 
245
176
  Every parser returns the same shape. The model always knows where to look.
@@ -253,4 +184,23 @@ Every parser returns the same shape. The model always knows where to look.
253
184
  | `cwd` | `string` | Working directory — anchor for resolving relative paths in failures |
254
185
  | `failures` | `{ id, file?, line?, message?, rule? }[]` | Per-failure details with relative file paths |
255
186
  | `logPath` | `string` | Path to full stdout+stderr log |
256
- | `rawTail` | `string?` | Last 200 lines of log, included on fallback when no parser matched |
187
+ | `rawTail` | `string?` | Last 200 log lines on unmatched errors, not successful unmatched commands |
188
+
189
+ ## Native engine
190
+
191
+ Command capture and built-in parsers run in Rust.
192
+
193
+ - Prebuilt binaries ship with npm. No Rust toolchain or install-time downloads required.
194
+ - Linux binaries support glibc and musl; Node/Pi requirements still apply.
195
+ - There is no TypeScript runtime fallback.
196
+
197
+ ### Building and publishing
198
+
199
+ Source checkouts require Rust 1.88.0 via rustup. Linux also needs `musl-gcc` and the host's Rust musl target.
200
+
201
+ ```bash
202
+ pnpm install --frozen-lockfile
203
+ pnpm --filter @robhowley/pi-structured-return build
204
+ ```
205
+
206
+ Build before testing or loading the extension. CI assembles all four platform binaries for publishing; `prepack` rejects incomplete or stale artifacts.
@@ -1,5 +1,4 @@
1
- import path from 'node:path';
2
- import type { ParserModule, ParserRegistration } from '../types';
1
+ import type { ParserModule } from '../types';
3
2
  import ruffJson from '../parsers/ruff-json';
4
3
  import eslintJson from '../parsers/eslint-json';
5
4
  import vitestJson from '../parsers/vitest-json';
@@ -99,7 +98,7 @@ function hasFlag(argv: string[], flag: string, value: string): boolean {
99
98
  return false;
100
99
  }
101
100
 
102
- /** Built-in detection patterns — fire when no explicit parseAs or project registration matched. */
101
+ /** Ordered detection patterns used when no explicit built-in parser is selected. */
103
102
  const AUTO_DETECT: Array<{ parserId: string; detect: (argv: string[]) => boolean }> = [
104
103
  {
105
104
  parserId: 'eslint-json',
@@ -271,36 +270,11 @@ export function listParsers(): { id: string; autoDetect: boolean }[] {
271
270
  return builtInIds.map((id) => ({ id, autoDetect: autoDetectIds.has(id) }));
272
271
  }
273
272
 
274
- export async function resolveParser(opts: {
275
- cwd: string;
276
- parseAs?: string;
277
- argv: string[];
278
- registrations: ParserRegistration[];
279
- }): Promise<ParserModule> {
280
- if (opts.parseAs && builtIns[opts.parseAs]) return builtIns[opts.parseAs];
281
-
282
- const matched = opts.registrations.find((reg) => matches(reg, opts.argv));
283
- if (matched?.parseAs && builtIns[matched.parseAs]) return builtIns[matched.parseAs];
284
- if (matched?.module) {
285
- const modulePath = path.resolve(opts.cwd, '.pi', matched.module);
286
- const loaded = await import(modulePath);
287
- return loaded.default ?? loaded;
288
- }
273
+ export function resolveParser(opts: { parseAs?: string; argv: string[] }): ParserModule {
274
+ if (opts.parseAs && Object.hasOwn(builtIns, opts.parseAs)) return builtIns[opts.parseAs];
289
275
 
290
276
  const autoMatched = AUTO_DETECT.find((d) => d.detect(opts.argv));
291
277
  if (autoMatched) return builtIns[autoMatched.parserId];
292
278
 
293
279
  return builtIns['tail-fallback'];
294
280
  }
295
-
296
- function matches(reg: ParserRegistration, argv: string[]): boolean {
297
- if (reg.match?.argvIncludes?.length) {
298
- const ok = reg.match.argvIncludes.every((token) => argv.includes(token));
299
- if (!ok) return false;
300
- }
301
- if (reg.match?.regex) {
302
- const text = argv.join(' ');
303
- if (!new RegExp(reg.match.regex).test(text)) return false;
304
- }
305
- return Boolean(reg.match?.argvIncludes?.length || reg.match?.regex);
306
- }
@@ -1,15 +1,16 @@
1
- import { spawn } from 'node:child_process';
2
1
  import path from 'node:path';
2
+ import fs from 'node:fs';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { globSync } from 'glob';
5
5
  import { Type } from '@sinclair/typebox';
6
6
  import type { ExtensionAPI, ExtensionContext } from '@mariozechner/pi-coding-agent';
7
7
  import { Text } from '@mariozechner/pi-tui';
8
8
  import type { ObservedRunArgs, ParsedResult, RunContext } from './types';
9
- import { ensureRunDir, writeRunArtifacts } from './storage/log-store';
10
- import { loadProjectConfig } from './config/project-config';
9
+ import { ensureRunDir } from './storage/log-store';
10
+ import { runNative } from './native';
11
11
  import { resolveParser, listParsers } from './config/registry';
12
- import { safeReadFile } from './parsers/utils';
12
+ import { readTail } from './parsers/utils';
13
+ import tailFallback from './parsers/tail-fallback';
13
14
  import {
14
15
  appendRun,
15
16
  readLifetimeStats,
@@ -19,7 +20,7 @@ import {
19
20
 
20
21
  export default function structuredReturn(pi: ExtensionAPI) {
21
22
  pi.registerCommand('sr-parsers', {
22
- description: 'List all structured-return parsers: built-ins and project-local registrations',
23
+ description: 'List built-in structured-return parsers',
23
24
  handler: async (_args, ctx) => {
24
25
  const lines: string[] = ['structured-return parsers', ''];
25
26
 
@@ -28,27 +29,6 @@ export default function structuredReturn(pi: ExtensionAPI) {
28
29
  lines.push(` ${id}${autoDetect ? ' (auto-detect)' : ''}`);
29
30
  }
30
31
 
31
- const projectRegistrations = loadProjectConfig(ctx.cwd);
32
- lines.push('');
33
- lines.push('project-local (.pi/structured-return.json):');
34
- if (projectRegistrations.length === 0) {
35
- lines.push(' (none)');
36
- } else {
37
- for (const reg of projectRegistrations) {
38
- const via = reg.parseAs
39
- ? `→ ${reg.parseAs}`
40
- : reg.module
41
- ? `→ module: ${reg.module}`
42
- : '';
43
- const match = reg.match?.argvIncludes
44
- ? `argv includes [${reg.match.argvIncludes.join(', ')}]`
45
- : reg.match?.regex
46
- ? `regex: ${reg.match.regex}`
47
- : '(no match rule)';
48
- lines.push(` ${reg.id} ${match} ${via}`);
49
- }
50
- }
51
-
52
32
  ctx.ui.notify(lines.join('\n'), 'info');
53
33
  },
54
34
  });
@@ -106,7 +86,7 @@ export default function structuredReturn(pi: ExtensionAPI) {
106
86
  name: 'structured_return',
107
87
  label: 'Structured Return',
108
88
  description:
109
- 'Run a command, store full logs, apply an explicit or registered parser when available, and fall back to tail + log path.',
89
+ 'Run a command, store full logs, apply a built-in parser when available, and fall back to tail + log path.',
110
90
  promptGuidelines: [
111
91
  'Prefer structured_return over bash for test suites, linters, type checkers, and build commands - it returns compact results. Check the structured-return skill for the right flags and parseAs value for each tool.',
112
92
  ],
@@ -119,37 +99,85 @@ export default function structuredReturn(pi: ExtensionAPI) {
119
99
  async execute(
120
100
  _toolCallId: string,
121
101
  args: ObservedRunArgs,
122
- _signal: AbortSignal | undefined,
102
+ signal: AbortSignal | undefined,
123
103
  _onUpdate: unknown,
124
104
  ctx: ExtensionContext,
125
105
  ) {
126
- const cwd = args.cwd ?? ctx.cwd ?? process.cwd();
106
+ // Resolve through the filesystem before normalizing symlink/.. components.
107
+ const cwd = fs.realpathSync.native(args.cwd ?? ctx.cwd ?? process.cwd());
127
108
  const runDir = ensureRunDir(cwd);
128
109
  const runId = randomUUID();
129
110
  const argv = shellSplit(args.command);
130
- const { stdout, stderr, exitCode } = await runCommand(args.command, cwd);
131
- const logs = writeRunArtifacts(runDir, runId, stdout, stderr);
132
- const artifactPaths = expandArtifactPaths(args.artifactPaths ?? [], cwd);
133
- const runCtx: RunContext = {
134
- command: args.command,
135
- argv,
111
+ const {
112
+ exitCode,
113
+ rawBytes,
114
+ cancelled: captureCancelled,
115
+ ...logs
116
+ } = await runNative(args.command, cwd, runDir, runId, signal);
117
+ let parserId = 'unknown';
118
+ let result: ParsedResult = {
119
+ tool: parserId,
120
+ status: 'error',
121
+ summary: 'command cancelled',
122
+ exitCode,
136
123
  cwd,
137
- artifactPaths,
138
- ...logs,
124
+ logPath: logs.logPath,
139
125
  };
140
- const registrations = loadProjectConfig(cwd);
141
- const parser = await resolveParser({ cwd, parseAs: args.parseAs, argv, registrations });
142
- const parsed = await parser.parse(runCtx);
143
- const result = finalizeResult(parsed, exitCode, logs.logPath, cwd);
126
+ if (!captureCancelled && !signal?.aborted) {
127
+ try {
128
+ const artifactPaths = expandArtifactPaths(args.artifactPaths ?? [], cwd);
129
+ const runCtx: RunContext = {
130
+ command: args.command,
131
+ argv,
132
+ cwd,
133
+ artifactPaths,
134
+ signal,
135
+ ...logs,
136
+ };
137
+ const parser = resolveParser({ parseAs: args.parseAs, argv });
138
+ parserId = parser.id;
139
+ if (!signal?.aborted) {
140
+ // Successful fallback output is summary-only. Do not read and transmit a
141
+ // potentially enormous tail just to discard it in formatResult.
142
+ const parsed =
143
+ parser === tailFallback && exitCode === 0
144
+ ? {
145
+ tool: 'unknown',
146
+ status: 'pass' as const,
147
+ summary: 'command completed; no parser matched',
148
+ }
149
+ : await parser.parse(runCtx);
150
+ result = finalizeResult(parsed, exitCode, logs.logPath, cwd);
151
+ }
152
+ } catch (error) {
153
+ // Capture succeeded. Parsing failures must not hide its
154
+ // exit status or logs, nor reread an oversized log into the response.
155
+ result = {
156
+ ...result,
157
+ tool: parserId,
158
+ summary: `could not parse command output: ${error instanceof Error ? error.message : String(error)}`,
159
+ };
160
+ }
161
+ }
162
+ const cancelled = captureCancelled || Boolean(signal?.aborted);
163
+ if (cancelled) {
164
+ result = {
165
+ tool: parserId,
166
+ status: 'error',
167
+ summary: 'command cancelled',
168
+ exitCode,
169
+ cwd,
170
+ logPath: logs.logPath,
171
+ };
172
+ }
144
173
  const resultText = formatResult(result);
145
174
 
146
- const rawBytes = stdout.length + stderr.length;
147
- const parsedBytes = resultText.length;
175
+ const parsedBytes = Buffer.byteLength(resultText, 'utf8');
148
176
  try {
149
177
  appendRun({
150
178
  ts: new Date().toISOString(),
151
179
  session: ctx.sessionManager?.getSessionFile?.() ?? undefined,
152
- parser: parser.id,
180
+ parser: parserId,
153
181
  rawBytes,
154
182
  parsedBytes,
155
183
  command: stripCdPrefix(args.command),
@@ -163,7 +191,14 @@ export default function structuredReturn(pi: ExtensionAPI) {
163
191
  content: [
164
192
  { type: 'text' as const, text: `${stripCdPrefix(args.command)} → ${resultText}` },
165
193
  ],
166
- details: { exitCode, logPath: logs.logPath, parser: parser.id, rawBytes, parsedBytes },
194
+ details: {
195
+ exitCode,
196
+ ...logs,
197
+ parser: parserId,
198
+ rawBytes,
199
+ parsedBytes,
200
+ cancelled,
201
+ },
167
202
  };
168
203
  },
169
204
  renderCall(args: ObservedRunArgs) {
@@ -196,17 +231,24 @@ export function formatResult(result: ParsedResult): string {
196
231
  ) {
197
232
  if (result.logPath) lines.push(`log: ${result.logPath}`);
198
233
  if (result.rawTail) lines.push(result.rawTail);
234
+ } else if (result.tool === 'dbt' && result.rawTail) {
235
+ // DBT returns compiled SQL (and test diffs) here even when diagnostics exist.
236
+ lines.push(result.rawTail);
199
237
  }
200
238
  return lines.join('\n');
201
239
  }
202
240
 
203
241
  /** Resolve and glob-expand artifact paths. Patterns that match nothing are kept as-is (parser handles missing files). */
204
242
  export function expandArtifactPaths(raw: string[], cwd: string): string[] {
205
- return raw.flatMap((p) => {
206
- const resolved = path.isAbsolute(p) ? p : path.join(cwd, p);
207
- const expanded = globSync(resolved);
208
- return expanded.length > 0 ? expanded.sort() : [resolved];
209
- });
243
+ return [
244
+ ...new Set(
245
+ raw.flatMap((p) => {
246
+ const resolved = path.isAbsolute(p) ? p : path.join(cwd, p);
247
+ const expanded = globSync(resolved);
248
+ return expanded.length > 0 ? expanded.sort() : [resolved];
249
+ }),
250
+ ),
251
+ ];
210
252
  }
211
253
 
212
254
  export function stripCdPrefix(command: string): string {
@@ -219,31 +261,18 @@ function shellSplit(command: string): string[] {
219
261
  );
220
262
  }
221
263
 
222
- function runCommand(
223
- command: string,
224
- cwd: string,
225
- ): Promise<{ stdout: string; stderr: string; exitCode: number }> {
226
- return new Promise((resolve) => {
227
- const proc = spawn(command, { cwd, shell: true, stdio: ['ignore', 'pipe', 'pipe'] });
228
- let stdout = '';
229
- let stderr = '';
230
- proc.stdout.on('data', (d) => {
231
- stdout += d.toString();
232
- });
233
- proc.stderr.on('data', (d) => {
234
- stderr += d.toString();
235
- });
236
- proc.on('close', (code) => resolve({ stdout, stderr, exitCode: code ?? 1 }));
237
- });
238
- }
239
-
240
264
  export function finalizeResult(
241
265
  result: Omit<ParsedResult, 'exitCode'>,
242
266
  exitCode: number,
243
267
  logPath: string,
244
268
  cwd: string,
245
269
  ): ParsedResult {
246
- if (result.status === 'error' && exitCode === 0) {
270
+ if (
271
+ result.tool === 'unknown' &&
272
+ result.status === 'error' &&
273
+ result.summary === 'no parser matched; returning tail + log path' &&
274
+ exitCode === 0
275
+ ) {
247
276
  return {
248
277
  ...result,
249
278
  exitCode,
@@ -257,12 +286,14 @@ export function finalizeResult(
257
286
  };
258
287
  }
259
288
  const finalized: ParsedResult = { ...result, exitCode, cwd, logPath };
289
+ if (exitCode !== 0 && finalized.status === 'pass') {
290
+ finalized.status = 'error';
291
+ finalized.summary = `command exited ${exitCode}; ${finalized.summary}`;
292
+ }
260
293
  // Surface catastrophic failures (command not found, permission denied, missing
261
294
  // interpreter, etc.) — the combined log contains the actual diagnostic.
262
- if (finalized.status === 'error' && exitCode !== 0 && !finalized.rawTail) {
263
- const log = safeReadFile(logPath);
264
- const lines = log.split(/\r?\n/);
265
- finalized.rawTail = lines.slice(-200).join('\n');
295
+ if (finalized.status === 'error' && !finalized.rawTail) {
296
+ finalized.rawTail = readTail(logPath);
266
297
  }
267
298
  // Safety net: if the parser reports failures but couldn't extract any details
268
299
  // (e.g., tool output format changed), append the log tail so the model isn't
@@ -272,9 +303,7 @@ export function finalizeResult(
272
303
  (finalized.failures ?? []).length === 0 &&
273
304
  !finalized.rawTail
274
305
  ) {
275
- const log = safeReadFile(logPath);
276
- const lines = log.split(/\r?\n/);
277
- finalized.rawTail = lines.slice(-200).join('\n');
306
+ finalized.rawTail = readTail(logPath);
278
307
  }
279
308
  return finalized;
280
309
  }