@foliox/transparent-compact-pi 0.9.3 → 0.11.1

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.
@@ -2,7 +2,9 @@
2
2
  * model calls, or session mutation. Canonical span lines/records are never edited.
3
3
  */
4
4
  export const TOOL_PREFIX = "[Tools]: ";
5
- export const NORMAL_PREVIEW_CHARS = 160;
5
+ export const FILTER_MARKER = "[Turn manually filtered]";
6
+ import { NORMAL_PREVIEW_CHARS, headPrefix, commandPreview } from "./tool-stubs/display.mjs";
7
+ export { NORMAL_PREVIEW_CHARS, commandPreview };
6
8
  export const TIGHTENED_ATTR = ' tools-tightened="true"';
7
9
 
8
10
  // Encoded display fragments, NOT full commands or executable arguments.
@@ -12,34 +14,27 @@ export interface ToolStub {
12
14
  prefix: string;
13
15
  command?: CommandPreview;
14
16
  suffix: string;
17
+ /** Authoritative dictionary references, never inferred by scanning prose. */
18
+ locations?: string[];
15
19
  }
16
20
  export interface ToolLine {
17
21
  index: number;
18
22
  calls: ToolStub[];
19
23
  /** Both adjacent messages must be tool-only before prefixes may be folded. */
20
24
  mergeable: boolean;
25
+ prefix?: string;
21
26
  }
22
27
  export interface ToolLines { version: 2; lines: ToolLine[] }
23
- export interface SpanContent { lines: string[]; tools?: ToolLines }
24
- export interface CappedSpans { lines: string[][]; tightened: boolean[]; trimmed: boolean[] }
25
-
26
- function headPrefix(text: string, max: number): string {
27
- let end = Math.min(text.length, max);
28
- if (/[\uD800-\uDBFF]/.test(text[end - 1])) end--;
29
- return text.slice(0, end);
30
- }
31
- export function commandPreview(encoded: string): CommandPreview {
32
- return encoded.length <= NORMAL_PREVIEW_CHARS ? { head: encoded }
33
- : { head: headPrefix(encoded, NORMAL_PREVIEW_CHARS), truncated: true };
34
- }
28
+ export interface SpanContent { lines: string[]; tools?: ToolLines; protectedLines?: number[] }
29
+ export interface CappedSpans { lines: string[][]; tightened: boolean[]; trimmed: boolean[]; locationIds: string[] }
35
30
  export function renderCommand(preview: CommandPreview, max = NORMAL_PREVIEW_CHARS): string {
36
31
  return headPrefix(preview.head, max) + (preview.truncated || preview.head.length > max ? "…" : "");
37
32
  }
38
33
  export function renderToolStub(stub: ToolStub, max = NORMAL_PREVIEW_CHARS): string {
39
34
  return stub.prefix + (stub.command ? renderCommand(stub.command, max) : "") + stub.suffix;
40
35
  }
41
- export function renderToolLine(calls: ToolStub[], max = NORMAL_PREVIEW_CHARS): string {
42
- return TOOL_PREFIX + calls.map((call) => renderToolStub(call, max)).join("; ");
36
+ export function renderToolLine(calls: ToolStub[], max = NORMAL_PREVIEW_CHARS, prefix = TOOL_PREFIX): string {
37
+ return prefix + calls.map((call) => renderToolStub(call, max)).join("; ");
43
38
  }
44
39
 
45
40
  // Stored records are optional/versioned. Require exact canonical round-tripping
@@ -54,9 +49,11 @@ function toolRecords(span: SpanContent): Map<number, ToolLine> {
54
49
  if (!record || !Number.isSafeInteger(record.index) || record.index < 0 || record.index >= span.lines.length) continue;
55
50
  if (seen.has(record.index)) { records.delete(record.index); continue; }
56
51
  seen.add(record.index);
57
- if (typeof record.mergeable !== "boolean" || !Array.isArray(record.calls) || !record.calls.length) continue;
52
+ if (typeof record.mergeable !== "boolean" || !Array.isArray(record.calls) || !record.calls.length ||
53
+ (record.prefix !== undefined && record.prefix !== TOOL_PREFIX && record.prefix !== "[BashExecution]: ")) continue;
58
54
  const valid = record.calls.every((call) => {
59
55
  if (!call || typeof call.prefix !== "string" || typeof call.suffix !== "string") return false;
56
+ if (call.locations !== undefined && (!Array.isArray(call.locations) || !call.locations.every((id) => typeof id === "string" && /^@\d+$/.test(id)))) return false;
60
57
  const p = call.command;
61
58
  if (p === undefined) return true;
62
59
  if (!p || typeof p.head !== "string") return false;
@@ -64,7 +61,7 @@ function toolRecords(span: SpanContent): Map<number, ToolLine> {
64
61
  (p.truncated === undefined || typeof p.truncated === "boolean") &&
65
62
  (p.truncated !== true || p.head.length >= NORMAL_PREVIEW_CHARS - 1);
66
63
  });
67
- if (valid && renderToolLine(record.calls) === span.lines[record.index]) records.set(record.index, record);
64
+ if (valid && renderToolLine(record.calls, NORMAL_PREVIEW_CHARS, record.prefix) === span.lines[record.index]) records.set(record.index, record);
68
65
  }
69
66
  } catch { return new Map(); }
70
67
  return records;
@@ -72,10 +69,12 @@ function toolRecords(span: SpanContent): Map<number, ToolLine> {
72
69
 
73
70
  interface Row {
74
71
  index: number;
72
+ protected: boolean;
75
73
  text: string;
76
74
  calls?: ToolStub[];
77
75
  mergeable: boolean;
78
76
  preview: number;
77
+ prefix: string;
79
78
  foldPrefix: boolean;
80
79
  tightened: boolean;
81
80
  }
@@ -84,22 +83,26 @@ interface Row {
84
83
  * tool-only prefixes, and finally the historical destructive cap.
85
84
  * Every rung walks oldest first, across all spans (not just the new one).
86
85
  */
87
- export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
86
+ export function capSpans(spans: SpanContent[], budget = Infinity, extraChars: (ids: string[]) => number = () => 0): CappedSpans {
88
87
  const tightened = spans.map(() => false), trimmed = spans.map(() => false);
89
- let size = spans.reduce((n, span) => n + span.lines.reduce((s, line) => s + line.length + 1, 0), 0);
90
- if (size <= budget) return { lines: spans.map((s) => s.lines.slice()), tightened, trimmed };
91
- const states = spans.map((span) => {
92
- const records = toolRecords(span);
88
+ const records = spans.map(toolRecords);
89
+ const references = (calls: ToolStub[]) => [...new Set(calls.flatMap((call) => call.locations ?? []))];
90
+ const initialIds = references(records.flatMap((map) => [...map.values()].flatMap((record) => record.calls)));
91
+ let size = spans.reduce((n, span) => n + span.lines.reduce((s, line) => s + line.length + 1, 0), 0) + extraChars(initialIds);
92
+ if (size <= budget) return { lines: spans.map((s) => s.lines.slice()), tightened, trimmed, locationIds: initialIds };
93
+ const states = spans.map((span, spanIndex) => {
94
+ const ownRecords = records[spanIndex];
93
95
  return span.lines.map((text, index): Row => {
94
- const record = records.get(index);
95
- return { index, text, calls: record?.calls.slice(), mergeable: record?.mergeable ?? false,
96
- preview: NORMAL_PREVIEW_CHARS, foldPrefix: false, tightened: false };
96
+ const record = ownRecords.get(index);
97
+ return { index, protected: span.protectedLines?.includes(index) ?? false, text, calls: record?.calls.slice(), mergeable: record?.mergeable ?? false,
98
+ preview: NORMAL_PREVIEW_CHARS, prefix: record?.prefix ?? TOOL_PREFIX, foldPrefix: false, tightened: false };
97
99
  });
98
100
  });
99
101
  const joined = (rows: Row[], i: number) => i > 0 && rows[i].foldPrefix && rows[i].calls && rows[i - 1].calls &&
100
- rows[i].mergeable && rows[i - 1].mergeable && rows[i].index === rows[i - 1].index + 1;
102
+ rows[i].mergeable && rows[i - 1].mergeable && rows[i].prefix === TOOL_PREFIX && rows[i - 1].prefix === TOOL_PREFIX && rows[i].index === rows[i - 1].index + 1;
103
+ const currentIds = () => references(states.flatMap((rows) => rows.flatMap((row) => row.calls ?? [])));
101
104
  const measure = () => states.reduce((n, rows) => n + rows.reduce((s, row, i) =>
102
- s + row.text.length + 1 - (joined(rows, i) ? TOOL_PREFIX.length - 1 : 0), 0), 0);
105
+ s + row.text.length + 1 - (joined(rows, i) ? TOOL_PREFIX.length - 1 : 0), 0), 0) + extraChars(currentIds());
103
106
  const finish = (): CappedSpans => ({
104
107
  lines: states.map((rows, span) => {
105
108
  const lines: string[] = [];
@@ -110,9 +113,9 @@ export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
110
113
  if (row.tightened || joined(rows, i)) tightened[span] = true;
111
114
  }
112
115
  return lines;
113
- }), tightened, trimmed,
116
+ }), tightened, trimmed, locationIds: currentIds(),
114
117
  });
115
- const render = (row: Row) => renderToolLine(row.calls!, row.preview);
118
+ const render = (row: Row) => renderToolLine(row.calls!, row.preview, row.prefix);
116
119
  const update = (row: Row) => {
117
120
  const text = render(row);
118
121
  if (text.length < row.text.length) {
@@ -142,7 +145,7 @@ export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
142
145
  const rows = states[span];
143
146
  for (let i = 0; i < rows.length && size > budget;) {
144
147
  const row = rows[i];
145
- if (row.text.startsWith("[User]:")) { i++; continue; }
148
+ if (row.protected || row.text.startsWith("[User]:") || row.text === FILTER_MARKER) { i++; continue; }
146
149
  if (row.calls && row.calls.length > 1) {
147
150
  row.calls.shift();
148
151
  row.text = render(row);
@@ -157,7 +160,7 @@ export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
157
160
  for (const row of states[span]) {
158
161
  if (size <= budget) break;
159
162
  const line = row.text;
160
- if (!line.startsWith("[User]:") || line.length <= 120) continue;
163
+ if (row.protected || !line.startsWith("[User]:") || line.length <= 120) continue;
161
164
  let end = 120;
162
165
  if (/[\uD800-\uDBFF]/.test(line[end - 1])) end--;
163
166
  const stub = `${line.slice(0, end)}…[truncated +${line.length - end} chars — use context_lookup]`;
@@ -168,8 +171,10 @@ export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
168
171
  }
169
172
  }
170
173
  for (let span = 0; span < states.length && size > budget; span++) {
171
- while (states[span].length && size > budget) {
172
- states[span].shift();
174
+ while (size > budget) {
175
+ const index = states[span].findIndex((row) => !row.protected && row.text !== FILTER_MARKER);
176
+ if (index < 0) break;
177
+ states[span].splice(index, 1);
173
178
  trimmed[span] = true;
174
179
  size = measure();
175
180
  }
@@ -0,0 +1,21 @@
1
+ export const NORMAL_PREVIEW_CHARS = 160;
2
+ export function headPrefix(text, max) {
3
+ let end = Math.min(text.length, max);
4
+ if (/[\uD800-\uDBFF]/.test(text[end - 1])) end--;
5
+ return text.slice(0, end);
6
+ }
7
+ export function commandPreview(encoded) {
8
+ return encoded.length <= NORMAL_PREVIEW_CHARS ? { head: encoded }
9
+ : { head: headPrefix(encoded, NORMAL_PREVIEW_CHARS), truncated: true };
10
+ }
11
+ export function argumentSnippet(value) {
12
+ let text;
13
+ try { text = JSON.stringify(value) ?? String(value); } catch { text = String(value); }
14
+ return text.length > NORMAL_PREVIEW_CHARS ? text.slice(0, NORMAL_PREVIEW_CHARS) + '…' : text;
15
+ }
16
+ export const checkpointPath = (value, cwd) => value === cwd ? '.'
17
+ : value.startsWith(cwd.endsWith('/') ? cwd : cwd + '/') ? value.slice(cwd.endsWith('/') ? cwd.length : cwd.length + 1) : value;
18
+ export function checkpointCommand(command, cwd) {
19
+ const escaped = cwd.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
20
+ return command.replace(new RegExp(`(^|[\\s"'=<>|;&(])${escaped}(?=$|[/\\s"'<>|;&)])`, 'g'), '$1.');
21
+ }
@@ -0,0 +1,12 @@
1
+ // Known tools select payload, never infer which arbitrary extension fields are
2
+ // metadata. Unknown tools retain an agnostic bounded argument display.
3
+ const PAYLOAD_FIELDS = new Map([
4
+ ['bash', new Set(['command'])],
5
+ ['read', new Set(['path', 'offset', 'limit'])],
6
+ ['write', new Set(['path', 'content'])],
7
+ ['edit', new Set(['path', 'edits', 'oldText', 'newText'])],
8
+ ]);
9
+ export function selectToolInputs(name, args = {}) {
10
+ const fields = PAYLOAD_FIELDS.get(name);
11
+ return fields ? Object.fromEntries(Object.entries(args ?? {}).filter(([key]) => fields.has(key))) : undefined;
12
+ }
@@ -0,0 +1,42 @@
1
+ import path from 'node:path';
2
+
3
+ /** Append-only, checkpoint-scoped identities. No filesystem access or expansion. */
4
+ export class Locations {
5
+ constructor(cwd, entries = []) {
6
+ this.cwd = cwd;
7
+ this.entries = entries.map(entry => ({ ...entry }));
8
+ this.byKey = new Map(this.entries.map(entry => [entry.key, entry]));
9
+ }
10
+
11
+ describe(value, cwd = this.cwd, kind = 'path', literal = false) {
12
+ if (/^[a-z][a-z\d+.-]*:\/\//i.test(value)) kind = 'url';
13
+ const relative = cwd && value.startsWith(cwd + '/') ? value.slice(cwd.length + 1) : value === cwd ? '' : value;
14
+ const dynamic = !literal && /[$`*?{}\[\]~]/.test(relative);
15
+ // Unknown working directories remain explicitly scoped, never guessed.
16
+ const resolved = kind !== 'path' ? value : dynamic || (!cwd && !path.posix.isAbsolute(value))
17
+ ? `${cwd ?? '?'} :: ${value}` : path.posix.resolve(cwd ?? '/', value);
18
+ const scope = cwd === this.cwd ? '.' : cwd?.startsWith(this.cwd + '/') ? cwd.slice(this.cwd.length + 1) : cwd ?? '?';
19
+ const display = kind !== 'path' ? value : dynamic || (!cwd && !path.posix.isAbsolute(value)) ? `${scope} :: ${value}`
20
+ : resolved === this.cwd ? '.' : resolved.startsWith(this.cwd + '/') ? resolved.slice(this.cwd.length + 1) : resolved;
21
+ return { key: `${kind}:${resolved}`, kind, value: resolved, display };
22
+ }
23
+
24
+ ref(value, cwd = this.cwd, kind = 'path', literal = false) {
25
+ const description = this.describe(value, cwd, kind, literal);
26
+ let entry = this.byKey.get(description.key);
27
+ if (!entry) {
28
+ entry = { id: `@${this.entries.length + 1}`, ...description };
29
+ this.entries.push(entry);
30
+ this.byKey.set(entry.key, entry);
31
+ }
32
+ return entry;
33
+ }
34
+
35
+ render(ids) {
36
+ const entries = ids ? this.entries.filter(entry => ids.has(entry.id)) : this.entries;
37
+ if (!entries.length) return '';
38
+ return ['<locations note="lexical references, not verified accesses; ? means unknown cwd">',
39
+ ...entries.map(entry => `${entry.id} ${entry.kind !== 'path' ? entry.kind.toUpperCase() + ' ' : ''}${JSON.stringify(entry.display)}`),
40
+ '</locations>'].join('\n');
41
+ }
42
+ }
@@ -0,0 +1,39 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import vm from 'node:vm';
3
+ import { webcrypto } from 'node:crypto';
4
+
5
+ let runtime;
6
+ async function loadParser() {
7
+ const [wasm, support] = await Promise.all([
8
+ readFile(new URL('./parser/shell.wasm', import.meta.url)),
9
+ readFile(new URL('./parser/wasm_exec.js', import.meta.url), 'utf8'),
10
+ ]);
11
+ let register;
12
+ const ready = new Promise(resolve => { register = resolve; });
13
+ // Go's unmodified support script installs globals. Keep them local to this
14
+ // runtime so extension reloads do not change Pi's globals or other extensions.
15
+ const scope = vm.createContext({ TextEncoder, TextDecoder, WebAssembly,
16
+ crypto: webcrypto, performance, console, setTimeout, clearTimeout,
17
+ registerShellParser: register });
18
+ vm.runInContext(support, scope, { filename: 'wasm_exec.js' });
19
+ const go = new scope.Go();
20
+ const { instance } = await WebAssembly.instantiate(wasm, go.importObject);
21
+ // run remains pending while registered JS callbacks are available. Race it
22
+ // against registration so an initialization failure cannot leave us waiting.
23
+ const exited = go.run(instance).then(() => { throw new Error('shell parser runtime exited'); });
24
+ const parse = await Promise.race([ready, exited]);
25
+ return { parse, go }; // Keep the instance alive for later callbacks.
26
+ }
27
+
28
+ /** mvdan/sh's official typed JSON, without schema conversion or shell execution.
29
+ * Input bounds are checked before starting WASM. No binary on PATH, downloads,
30
+ * target-file access, or subprocesses are involved at runtime.
31
+ */
32
+ export async function parseShell(command, { maxBytes = 262144 } = {}) {
33
+ if (typeof command !== 'string') throw new TypeError('shell input must be a string');
34
+ if (Buffer.byteLength(command, 'utf8') > maxBytes) throw new Error('shell input byte budget exceeded');
35
+ const { parse } = await (runtime ??= loadParser());
36
+ const result = parse(command);
37
+ if (result.error) throw new SyntaxError(result.error);
38
+ return JSON.parse(result.json);
39
+ }
@@ -0,0 +1,27 @@
1
+ Copyright 2009 The Go Authors.
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ * Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+ * Redistributions in binary form must reproduce the above
10
+ copyright notice, this list of conditions and the following disclaimer
11
+ in the documentation and/or other materials provided with the
12
+ distribution.
13
+ * Neither the name of Google LLC nor the names of its
14
+ contributors may be used to endorse or promote products derived from
15
+ this software without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2016, Daniel Martí. All rights reserved.
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ * Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+ * Redistributions in binary form must reproduce the above
10
+ copyright notice, this list of conditions and the following disclaimer
11
+ in the documentation and/or other materials provided with the
12
+ distribution.
13
+ * Neither the name of the copyright holder nor the names of its
14
+ contributors may be used to endorse or promote products derived from
15
+ this software without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,13 @@
1
+ # Bundled shell parser
2
+
3
+ `shell.wasm` compiles our `main.go` bridge with the official `mvdan.cc/sh/v3`
4
+ parser and `syntax/typedjson` encoder. `go.mod` pins the upstream release;
5
+ `go.sum` records its checksums. No interpreter is imported.
6
+
7
+ - mvdan/sh: BSD 3-Clause; see `LICENSE.mvdan-sh`.
8
+ - Go runtime and standard library: see `LICENSE.Go` and `PATENTS.Go`.
9
+ - `wasm_exec.js` is copied unmodified from the matching official Go toolchain.
10
+ - `build.json` records the upstream/toolchain versions and generated asset hashes.
11
+
12
+ The bridge and JavaScript loader are part of transparent-compact, under its MIT
13
+ license. The bundled assets require no Go installation or runtime downloads.
@@ -0,0 +1,22 @@
1
+ Additional IP Rights Grant (Patents)
2
+
3
+ "This implementation" means the copyrightable works distributed by
4
+ Google as part of the Go project.
5
+
6
+ Google hereby grants to You a perpetual, worldwide, non-exclusive,
7
+ no-charge, royalty-free, irrevocable (except as stated in this section)
8
+ patent license to make, have made, use, offer to sell, sell, import,
9
+ transfer and otherwise run, modify and propagate the contents of this
10
+ implementation of Go, where such license applies only to those patent
11
+ claims, both currently owned or controlled by Google and acquired in
12
+ the future, licensable by Google that are necessarily infringed by this
13
+ implementation of Go. This grant does not include claims that would be
14
+ infringed only as a consequence of further modification of this
15
+ implementation. If you or your agent or exclusive licensee institute or
16
+ order or agree to the institution of patent litigation against any
17
+ entity (including a cross-claim or counterclaim in a lawsuit) alleging
18
+ that this implementation of Go or any code incorporated within this
19
+ implementation of Go constitutes direct or contributory patent
20
+ infringement, or inducement of patent infringement, then any patent
21
+ rights granted to you under this License for this implementation of Go
22
+ shall terminate as of the date such litigation is filed.
@@ -0,0 +1,12 @@
1
+ {
2
+ "module": "mvdan.cc/sh/v3",
3
+ "version": "v3.14.1",
4
+ "go": "go1.27.3",
5
+ "wasmSha256": "5a3863987dcd484b76f7e30ba2e1b0e7ec44733de2b9020ced47fce1a805759a",
6
+ "runtimeSha256": "0c949f4996f9a89698e4b5c586de32249c3b69b7baadb64d220073cc04acba14",
7
+ "sourceSha256": {
8
+ "main.go": "9e3e81b5b887ebeed4a9ce892f1aacb074f25f1d3bc9e566cb6f5c3934c2c84c",
9
+ "go.mod": "6abdd17a1fbbd701de015c52d58142fb7baefeb3afae0eb95369f0a7d3062bdd",
10
+ "go.sum": "816811ceede3e018d293b5097e3cfea283ce6205309d387c21fce95846e2215b"
11
+ }
12
+ }
@@ -0,0 +1,5 @@
1
+ module github.com/felixwoolford/transparent-compact-pi/shellparser
2
+
3
+ go 1.27.3
4
+
5
+ require mvdan.cc/sh/v3 v3.14.1
@@ -0,0 +1,2 @@
1
+ mvdan.cc/sh/v3 v3.14.1 h1:bXkhQWNHCs0KZEChF8hYS6FC+T2N9mUZLbQv9blditI=
2
+ mvdan.cc/sh/v3 v3.14.1/go.mod h1:syYCoFET8w9tvevxiXUtY8/ICrU+l26jHmhJDra3Vwo=
@@ -0,0 +1,36 @@
1
+ // The bridge deliberately uses upstream's AST encoder, not a custom AST schema.
2
+ // No interpreter, command execution, filesystem access, or shell expansion.
3
+ package main
4
+
5
+ import (
6
+ "bytes"
7
+ "fmt"
8
+ "strings"
9
+ "syscall/js"
10
+
11
+ "mvdan.cc/sh/v3/syntax"
12
+ "mvdan.cc/sh/v3/syntax/typedjson"
13
+ )
14
+
15
+ func parse(_ js.Value, args []js.Value) (result any) {
16
+ // Keep an unexpected upstream panic from terminating the cached WASM runtime.
17
+ defer func() {
18
+ if err := recover(); err != nil {
19
+ result = map[string]any{"error": fmt.Sprint(err)}
20
+ }
21
+ }()
22
+ file, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(args[0].String()), "")
23
+ if err != nil {
24
+ return map[string]any{"error": err.Error()}
25
+ }
26
+ var out bytes.Buffer
27
+ if err := typedjson.Encode(&out, file); err != nil {
28
+ return map[string]any{"error": err.Error()}
29
+ }
30
+ return map[string]any{"json": out.String()}
31
+ }
32
+
33
+ func main() {
34
+ js.Global().Call("registerShellParser", js.FuncOf(parse))
35
+ select {}
36
+ }