@arhan-w/ibex 0.0.0-stage → 3.6.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 (167) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +295 -2
  3. package/npm-package/LICENSE +21 -0
  4. package/npm-package/README.md +176 -0
  5. package/npm-package/bin/goat.js +3 -0
  6. package/npm-package/bin/ibex.js +77 -0
  7. package/npm-package/package.json +58 -0
  8. package/npm-package/scripts/install-binary.js +168 -0
  9. package/package.json +69 -6
  10. package/src/agent.ts +695 -0
  11. package/src/agents/loader.ts +110 -0
  12. package/src/ambient.d.ts +2 -0
  13. package/src/code/extract.ts +292 -0
  14. package/src/code/find.ts +244 -0
  15. package/src/code/grammars.ts +88 -0
  16. package/src/code/indexer.ts +242 -0
  17. package/src/code/semantic.ts +253 -0
  18. package/src/code/slash.ts +88 -0
  19. package/src/code/tool.ts +40 -0
  20. package/src/collab/client.ts +141 -0
  21. package/src/collab/handlers.ts +141 -0
  22. package/src/collab/invite.ts +39 -0
  23. package/src/collab/relay.ts +106 -0
  24. package/src/collab/sync.ts +131 -0
  25. package/src/commands.tsx +943 -0
  26. package/src/computer.ts +629 -0
  27. package/src/config.ts +318 -0
  28. package/src/constants.ts +18 -0
  29. package/src/context.ts +73 -0
  30. package/src/data/providers.json +2342 -0
  31. package/src/diff.ts +50 -0
  32. package/src/doctor.ts +443 -0
  33. package/src/errors.ts +139 -0
  34. package/src/gflash.ts +170 -0
  35. package/src/hooks.ts +133 -0
  36. package/src/ide/assets.gen.ts +3 -0
  37. package/src/ide/index.html +844 -0
  38. package/src/ide/server.ts +506 -0
  39. package/src/ide/vendor/marked.umd.js +80 -0
  40. package/src/ide/vendor/vs/base/browser/ui/codicons/codicon/codicon.ttf +0 -0
  41. package/src/ide/vendor/vs/base/worker/workerMain.js +31 -0
  42. package/src/ide/vendor/vs/basic-languages/abap/abap.js +10 -0
  43. package/src/ide/vendor/vs/basic-languages/apex/apex.js +10 -0
  44. package/src/ide/vendor/vs/basic-languages/azcli/azcli.js +10 -0
  45. package/src/ide/vendor/vs/basic-languages/bat/bat.js +10 -0
  46. package/src/ide/vendor/vs/basic-languages/bicep/bicep.js +11 -0
  47. package/src/ide/vendor/vs/basic-languages/cameligo/cameligo.js +10 -0
  48. package/src/ide/vendor/vs/basic-languages/clojure/clojure.js +10 -0
  49. package/src/ide/vendor/vs/basic-languages/coffee/coffee.js +10 -0
  50. package/src/ide/vendor/vs/basic-languages/cpp/cpp.js +10 -0
  51. package/src/ide/vendor/vs/basic-languages/csharp/csharp.js +10 -0
  52. package/src/ide/vendor/vs/basic-languages/csp/csp.js +10 -0
  53. package/src/ide/vendor/vs/basic-languages/css/css.js +12 -0
  54. package/src/ide/vendor/vs/basic-languages/cypher/cypher.js +10 -0
  55. package/src/ide/vendor/vs/basic-languages/dart/dart.js +10 -0
  56. package/src/ide/vendor/vs/basic-languages/dockerfile/dockerfile.js +10 -0
  57. package/src/ide/vendor/vs/basic-languages/ecl/ecl.js +10 -0
  58. package/src/ide/vendor/vs/basic-languages/elixir/elixir.js +10 -0
  59. package/src/ide/vendor/vs/basic-languages/flow9/flow9.js +10 -0
  60. package/src/ide/vendor/vs/basic-languages/freemarker2/freemarker2.js +12 -0
  61. package/src/ide/vendor/vs/basic-languages/fsharp/fsharp.js +10 -0
  62. package/src/ide/vendor/vs/basic-languages/go/go.js +10 -0
  63. package/src/ide/vendor/vs/basic-languages/graphql/graphql.js +10 -0
  64. package/src/ide/vendor/vs/basic-languages/handlebars/handlebars.js +10 -0
  65. package/src/ide/vendor/vs/basic-languages/hcl/hcl.js +10 -0
  66. package/src/ide/vendor/vs/basic-languages/html/html.js +10 -0
  67. package/src/ide/vendor/vs/basic-languages/ini/ini.js +10 -0
  68. package/src/ide/vendor/vs/basic-languages/java/java.js +10 -0
  69. package/src/ide/vendor/vs/basic-languages/javascript/javascript.js +10 -0
  70. package/src/ide/vendor/vs/basic-languages/julia/julia.js +10 -0
  71. package/src/ide/vendor/vs/basic-languages/kotlin/kotlin.js +10 -0
  72. package/src/ide/vendor/vs/basic-languages/less/less.js +11 -0
  73. package/src/ide/vendor/vs/basic-languages/lexon/lexon.js +10 -0
  74. package/src/ide/vendor/vs/basic-languages/liquid/liquid.js +10 -0
  75. package/src/ide/vendor/vs/basic-languages/lua/lua.js +10 -0
  76. package/src/ide/vendor/vs/basic-languages/m3/m3.js +10 -0
  77. package/src/ide/vendor/vs/basic-languages/markdown/markdown.js +10 -0
  78. package/src/ide/vendor/vs/basic-languages/mdx/mdx.js +10 -0
  79. package/src/ide/vendor/vs/basic-languages/mips/mips.js +10 -0
  80. package/src/ide/vendor/vs/basic-languages/msdax/msdax.js +10 -0
  81. package/src/ide/vendor/vs/basic-languages/mysql/mysql.js +10 -0
  82. package/src/ide/vendor/vs/basic-languages/objective-c/objective-c.js +10 -0
  83. package/src/ide/vendor/vs/basic-languages/pascal/pascal.js +10 -0
  84. package/src/ide/vendor/vs/basic-languages/pascaligo/pascaligo.js +10 -0
  85. package/src/ide/vendor/vs/basic-languages/perl/perl.js +10 -0
  86. package/src/ide/vendor/vs/basic-languages/pgsql/pgsql.js +10 -0
  87. package/src/ide/vendor/vs/basic-languages/php/php.js +10 -0
  88. package/src/ide/vendor/vs/basic-languages/pla/pla.js +10 -0
  89. package/src/ide/vendor/vs/basic-languages/postiats/postiats.js +10 -0
  90. package/src/ide/vendor/vs/basic-languages/powerquery/powerquery.js +10 -0
  91. package/src/ide/vendor/vs/basic-languages/powershell/powershell.js +10 -0
  92. package/src/ide/vendor/vs/basic-languages/protobuf/protobuf.js +11 -0
  93. package/src/ide/vendor/vs/basic-languages/pug/pug.js +10 -0
  94. package/src/ide/vendor/vs/basic-languages/python/python.js +10 -0
  95. package/src/ide/vendor/vs/basic-languages/qsharp/qsharp.js +10 -0
  96. package/src/ide/vendor/vs/basic-languages/r/r.js +10 -0
  97. package/src/ide/vendor/vs/basic-languages/razor/razor.js +10 -0
  98. package/src/ide/vendor/vs/basic-languages/redis/redis.js +10 -0
  99. package/src/ide/vendor/vs/basic-languages/redshift/redshift.js +10 -0
  100. package/src/ide/vendor/vs/basic-languages/restructuredtext/restructuredtext.js +10 -0
  101. package/src/ide/vendor/vs/basic-languages/ruby/ruby.js +10 -0
  102. package/src/ide/vendor/vs/basic-languages/rust/rust.js +10 -0
  103. package/src/ide/vendor/vs/basic-languages/sb/sb.js +10 -0
  104. package/src/ide/vendor/vs/basic-languages/scala/scala.js +10 -0
  105. package/src/ide/vendor/vs/basic-languages/scheme/scheme.js +10 -0
  106. package/src/ide/vendor/vs/basic-languages/scss/scss.js +12 -0
  107. package/src/ide/vendor/vs/basic-languages/shell/shell.js +10 -0
  108. package/src/ide/vendor/vs/basic-languages/solidity/solidity.js +10 -0
  109. package/src/ide/vendor/vs/basic-languages/sophia/sophia.js +10 -0
  110. package/src/ide/vendor/vs/basic-languages/sparql/sparql.js +10 -0
  111. package/src/ide/vendor/vs/basic-languages/sql/sql.js +10 -0
  112. package/src/ide/vendor/vs/basic-languages/st/st.js +10 -0
  113. package/src/ide/vendor/vs/basic-languages/swift/swift.js +13 -0
  114. package/src/ide/vendor/vs/basic-languages/systemverilog/systemverilog.js +10 -0
  115. package/src/ide/vendor/vs/basic-languages/tcl/tcl.js +10 -0
  116. package/src/ide/vendor/vs/basic-languages/twig/twig.js +10 -0
  117. package/src/ide/vendor/vs/basic-languages/typescript/typescript.js +10 -0
  118. package/src/ide/vendor/vs/basic-languages/typespec/typespec.js +10 -0
  119. package/src/ide/vendor/vs/basic-languages/vb/vb.js +10 -0
  120. package/src/ide/vendor/vs/basic-languages/wgsl/wgsl.js +307 -0
  121. package/src/ide/vendor/vs/basic-languages/xml/xml.js +10 -0
  122. package/src/ide/vendor/vs/basic-languages/yaml/yaml.js +10 -0
  123. package/src/ide/vendor/vs/editor/editor.main.css +8 -0
  124. package/src/ide/vendor/vs/editor/editor.main.js +798 -0
  125. package/src/ide/vendor/vs/language/css/cssMode.js +13 -0
  126. package/src/ide/vendor/vs/language/css/cssWorker.js +77 -0
  127. package/src/ide/vendor/vs/language/html/htmlMode.js +13 -0
  128. package/src/ide/vendor/vs/language/html/htmlWorker.js +454 -0
  129. package/src/ide/vendor/vs/language/json/jsonMode.js +19 -0
  130. package/src/ide/vendor/vs/language/json/jsonWorker.js +42 -0
  131. package/src/ide/vendor/vs/language/typescript/tsMode.js +20 -0
  132. package/src/ide/vendor/vs/language/typescript/tsWorker.js +51328 -0
  133. package/src/ide/vendor/vs/loader.js +11 -0
  134. package/src/index-shared.ts +117 -0
  135. package/src/index.ts +586 -0
  136. package/src/llm.ts +721 -0
  137. package/src/logger.ts +39 -0
  138. package/src/mcp/client.ts +121 -0
  139. package/src/mcp/types.ts +27 -0
  140. package/src/oauth.ts +205 -0
  141. package/src/onboarding.ts +140 -0
  142. package/src/palette.tsx +199 -0
  143. package/src/permissions.ts +123 -0
  144. package/src/plugins/loader.ts +120 -0
  145. package/src/plugins/marketplace.ts +252 -0
  146. package/src/plugins/sandbox.ts +303 -0
  147. package/src/plugins/tar.ts +241 -0
  148. package/src/pricing.ts +78 -0
  149. package/src/protocol/client.ts +102 -0
  150. package/src/protocol/rpc.ts +43 -0
  151. package/src/protocol/serve.ts +136 -0
  152. package/src/providers.ts +402 -0
  153. package/src/rate-limiter.ts +101 -0
  154. package/src/refs.ts +97 -0
  155. package/src/runtime.ts +144 -0
  156. package/src/session.ts +401 -0
  157. package/src/skills/loader.ts +136 -0
  158. package/src/statusline.ts +70 -0
  159. package/src/system-prompt.ts +28 -0
  160. package/src/tools.ts +1280 -0
  161. package/src/tui.tsx +1355 -0
  162. package/src/update.ts +236 -0
  163. package/src/vendor/flashServer.ts +2 -0
  164. package/src/vendor/gemini-web2api/gemini_web2api.py +1136 -0
  165. package/src/virtual-list.tsx +125 -0
  166. package/src/window.ts +31 -0
  167. package/tsconfig.json +16 -0
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Command Palette — Ctrl+P overlay for GoatCode v3.2.
3
+ *
4
+ * Filters commands by name/description/category, supports arrow-key
5
+ * navigation, Enter to select, Esc to cancel.
6
+ */
7
+ import { Box, Text, useInput } from "ink";
8
+ import { useState, useCallback, useMemo } from "react";
9
+
10
+ export type CommandCategory = "slash" | "skill" | "plugin" | "file" | "session";
11
+
12
+ export interface Command {
13
+ name: string;
14
+ description: string;
15
+ category: CommandCategory;
16
+ }
17
+
18
+ const CATEGORY_LABEL: Record<CommandCategory, string> = {
19
+ slash: "Slash",
20
+ skill: "Skill",
21
+ plugin: "Plugin",
22
+ file: "File",
23
+ session: "Session",
24
+ };
25
+
26
+ const CATEGORY_COLOR: Record<CommandCategory, string> = {
27
+ slash: "#a855f7",
28
+ skill: "#4ade80",
29
+ plugin: "#facc15",
30
+ file: "#38bdf8",
31
+ session: "#fb923c",
32
+ };
33
+
34
+ export function CommandPalette({
35
+ commands,
36
+ onSelect,
37
+ onClose,
38
+ }: {
39
+ commands: Command[];
40
+ onSelect: (cmd: Command) => void;
41
+ onClose: () => void;
42
+ }) {
43
+ const [filter, setFilter] = useState("");
44
+ const [selected, setSelected] = useState(0);
45
+
46
+ const filtered = useMemo(() => {
47
+ const q = filter.toLowerCase();
48
+ if (!q) return commands;
49
+ return commands.filter(
50
+ (c) =>
51
+ c.name.toLowerCase().includes(q) ||
52
+ c.description.toLowerCase().includes(q) ||
53
+ c.category.toLowerCase().includes(q),
54
+ );
55
+ }, [commands, filter]);
56
+
57
+ // Reset selection when filter changes
58
+ useMemo(() => {
59
+ setSelected(0);
60
+ }, [filtered.length]);
61
+
62
+ useInput((_, key: any) => {
63
+ if (key.upArrow) {
64
+ setSelected((s) => Math.max(0, s - 1));
65
+ } else if (key.downArrow) {
66
+ setSelected((s) => Math.min(filtered.length - 1, s + 1));
67
+ } else if (key.return) {
68
+ if (filtered[selected]) {
69
+ onSelect(filtered[selected]);
70
+ }
71
+ onClose();
72
+ } else if (key.escape) {
73
+ onClose();
74
+ } else if (key.char) {
75
+ // Handle backspace
76
+ if (key.ctrl && key.char === "?") {
77
+ // Help toggle
78
+ return;
79
+ }
80
+ setFilter((prev) => prev + key.char);
81
+ }
82
+ });
83
+
84
+ // Group filtered commands by category for display
85
+ const grouped = useMemo(() => {
86
+ const map = new Map<CommandCategory, Command[]>();
87
+ for (const cmd of filtered) {
88
+ const list = map.get(cmd.category) ?? [];
89
+ list.push(cmd);
90
+ map.set(cmd.category, list);
91
+ }
92
+ return map;
93
+ }, [filtered]);
94
+
95
+ const selectedCmd = filtered[selected];
96
+
97
+ return (
98
+ <Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1} paddingY={1} backgroundColor="#1a1a2e">
99
+ <Box marginBottom={1}>
100
+ <Text color="cyan" bold>❯ Command Palette</Text>
101
+ <Text dimColor color="#7c8390"> (Ctrl+P to open)</Text>
102
+ </Box>
103
+ <Box marginBottom={1} borderStyle="single" borderColor="#25262D" paddingX={1}>
104
+ <Text color="#facc15">Search: </Text>
105
+ <Text color="white" bold>{filter || "(type to filter)"}</Text>
106
+ </Box>
107
+ {filtered.length === 0 ? (
108
+ <Box paddingY={1}>
109
+ <Text dimColor color="#7c8390"> No commands match "{filter}"</Text>
110
+ </Box>
111
+ ) : (
112
+ <>
113
+ {Array.from(grouped.entries()).map(([cat, cmds]) => (
114
+ <Box key={cat} flexDirection="column" marginBottom={1}>
115
+ <Text dimColor color="#7c8390"> {CATEGORY_LABEL[cat]}</Text>
116
+ {cmds.map((cmd, i) => {
117
+ const globalIdx = filtered.indexOf(cmd);
118
+ const isSelected = globalIdx === selected;
119
+ return (
120
+ <Box key={cmd.name} paddingLeft={1}>
121
+ <Text
122
+ color={isSelected ? "cyan" : "#7c8390"}
123
+ bold={isSelected}
124
+ >
125
+ {isSelected ? "❯ " : " "}
126
+ <Text color={CATEGORY_COLOR[cmd.category]}>
127
+ [{CATEGORY_LABEL[cmd.category].slice(0, 3).toUpperCase()}]
128
+ </Text>{" "}
129
+ <Text bold={isSelected} color={isSelected ? "white" : undefined}>
130
+ {cmd.name}
131
+ </Text>
132
+ <Text dimColor color="#7c8390"> — {cmd.description}</Text>
133
+ </Text>
134
+ </Box>
135
+ );
136
+ })}
137
+ </Box>
138
+ ))}
139
+ </>
140
+ )}
141
+ <Box marginTop={1} borderStyle="single" borderColor="#25262D" paddingTop={1}>
142
+ <Text dimColor color="#7c8390">
143
+ ↑↓ navigate · Enter select · Esc cancel · type to filter
144
+ </Text>
145
+ </Box>
146
+ </Box>
147
+ );
148
+ }
149
+
150
+ /**
151
+ * Build the full command list from all available sources.
152
+ */
153
+ export function buildCommandList(opts: {
154
+ slashCommands: string[];
155
+ commandDescs: Record<string, string>;
156
+ skills: Array<{ name: string; description: string }>;
157
+ plugins: Array<{ name: string; description: string }>;
158
+ sessions: string[];
159
+ }): Command[] {
160
+ const commands: Command[] = [];
161
+
162
+ // Slash commands
163
+ for (const cmd of opts.slashCommands) {
164
+ commands.push({
165
+ name: cmd,
166
+ description: opts.commandDescs[cmd] ?? "",
167
+ category: "slash",
168
+ });
169
+ }
170
+
171
+ // Skills
172
+ for (const sk of opts.skills) {
173
+ commands.push({
174
+ name: `/${sk.name}`,
175
+ description: sk.description,
176
+ category: "skill",
177
+ });
178
+ }
179
+
180
+ // Plugins
181
+ for (const pl of opts.plugins) {
182
+ commands.push({
183
+ name: `/plugin:${pl.name}`,
184
+ description: pl.description,
185
+ category: "plugin",
186
+ });
187
+ }
188
+
189
+ // Sessions
190
+ for (const s of opts.sessions) {
191
+ commands.push({
192
+ name: `/resume ${s}`,
193
+ description: "Resume session",
194
+ category: "session",
195
+ });
196
+ }
197
+
198
+ return commands;
199
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Permission rules — Claude Code settings.json compatible.
3
+ *
4
+ * Bash(git add:*) — command starts with "git add"
5
+ * Bash(npm run test) — exact command
6
+ * Edit(src/**) — file path glob (** spans dirs, * doesn't)
7
+ * Read(~/.ssh/**) — home path glob (absolute outside sandbox)
8
+ * WebFetch(domain:docs.example.com)
9
+ * Task — bare tool name matches every call of that tool
10
+ *
11
+ * deny beats allow beats asking the user. Tool names are matched
12
+ * case-insensitively; goat's write/edit both answer to Edit/Write.
13
+ */
14
+ import { homedir } from "node:os";
15
+
16
+ export interface RuleSet { allow: string[]; deny: string[] }
17
+
18
+ interface Rule { tool: string; arg?: string; raw: string }
19
+
20
+ function parseRule(raw: string): Rule | null {
21
+ const m = raw.trim().match(/^([A-Za-z_][\w]*)(?:\((.+)\))?$/s);
22
+ if (!m) return null;
23
+ return { tool: m[1].toLowerCase(), arg: m[2], raw: raw.trim() };
24
+ }
25
+
26
+ /** Glob with * (single segment) and ** (across separators). */
27
+ export function globMatch(rel: string, pattern: string): boolean {
28
+ let rx = "";
29
+ const p = pattern.replaceAll("\\", "/");
30
+ for (let i = 0; i < p.length; i++) {
31
+ const c = p[i];
32
+ if (c === "*") {
33
+ if (p[i + 1] === "*") {
34
+ rx += ".*"; i++;
35
+ if (p[i + 1] === "/") i++;
36
+ } else rx += "[^/]*";
37
+ } else if ("\\^$.|+()[]{}?".includes(c)) rx += "\\" + c;
38
+ else rx += c;
39
+ }
40
+ return new RegExp("^" + rx + "$").test(rel.replaceAll("\\", "/"));
41
+ }
42
+
43
+ /** One rule against one tool call. */
44
+ export function ruleMatches(rule: Rule, tool: string, args: Record<string, unknown>): boolean {
45
+ const t = tool.toLowerCase();
46
+ // goat write/edit both satisfy Edit/Write rules; mcp__x__y matches a Mcp(x) style loosely
47
+ const toolOk =
48
+ rule.tool === t ||
49
+ (rule.tool === "edit" && (t === "edit" || t === "write")) ||
50
+ (rule.tool === "write" && t === "write");
51
+ if (!toolOk) return false;
52
+ if (rule.arg === undefined) return true;
53
+ const pat = rule.arg;
54
+ switch (t) {
55
+ case "bash": {
56
+ const cmd = String(args.command ?? "").trim();
57
+ // Anti-bypass (matches Claude): prefix/glob allow rules never match
58
+ // compound commands — exact rules only. deny checks both anyway.
59
+ const compound = /[;&|]|\$\(|`/.test(cmd);
60
+ if (pat.endsWith(":*")) {
61
+ const prefix = pat.slice(0, -2).trim();
62
+ return !compound && (cmd === prefix || cmd.startsWith(prefix + " "));
63
+ }
64
+ if (pat.includes("*")) return !compound && globMatch(cmd, pat);
65
+ return cmd === pat;
66
+ }
67
+ case "edit":
68
+ case "write":
69
+ case "read": {
70
+ // _rulePaths = every path form this call can touch (tool layer adds the
71
+ // resolved repo/display path). A rule matches if ANY form matches, so a
72
+ // repo-prefixed workspace path can't dodge Edit(src/**)-style rules.
73
+ const forms: string[] = [String(args.path ?? "")];
74
+ if (Array.isArray(args._rulePaths)) forms.push(...args._rulePaths.map(String));
75
+ const expanded = pat.startsWith("~/") ? joinHome(pat) : pat;
76
+ for (const raw of forms) {
77
+ const path = raw.replaceAll("\\", "/");
78
+ if (expanded === pat) { if (globMatch(path, pat)) return true; }
79
+ else if (path === expanded || path.startsWith(expanded.replace(/\/\*\*.*$/, "/"))) return true;
80
+ }
81
+ return false;
82
+ }
83
+ case "webfetch": {
84
+ const url = String(args.url ?? "");
85
+ if (pat.startsWith("domain:")) {
86
+ const dom = pat.slice(7).replace(/^\./, "");
87
+ try {
88
+ const host = new URL(url).hostname;
89
+ return host === dom || host.endsWith("." + dom);
90
+ } catch { return false; }
91
+ }
92
+ return url.startsWith(pat);
93
+ }
94
+ case "computer": {
95
+ // Computer(type) matches the type action; Computer(click) covers the
96
+ // click variants; bare Computer matches everything.
97
+ const action = String(args.action ?? "");
98
+ if (pat === "click") return ["click", "double_click", "right_click"].includes(action);
99
+ return action === pat;
100
+ }
101
+ default:
102
+ return false; // arg-bearing rules only defined for known tools
103
+ }
104
+ }
105
+
106
+ function joinHome(p: string): string {
107
+ return (homedir() + p.slice(1)).replaceAll("\\", "/");
108
+ }
109
+
110
+ export type Decision = "allow" | "deny" | "ask";
111
+
112
+ export function decide(rules: RuleSet | undefined, tool: string, args: Record<string, unknown>): Decision {
113
+ if (!rules) return "ask";
114
+ for (const raw of rules.deny) {
115
+ const r = parseRule(raw);
116
+ if (r && ruleMatches(r, tool, args)) return "deny";
117
+ }
118
+ for (const raw of rules.allow) {
119
+ const r = parseRule(raw);
120
+ if (r && ruleMatches(r, tool, args)) return "allow";
121
+ }
122
+ return "ask";
123
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Plugin loader — bundles of commands + skills, loaded from plugin
3
+ * directories listed under "plugins" in config. Claude Code compatible
4
+ * directory layout:
5
+ *
6
+ * <plugin>/manifest.json (optional — name/version/description)
7
+ * <plugin>/commands/<name>.md frontmatter + $ARGUMENTS body → /name prompt
8
+ * <plugin>/skills/<name>/SKILL.md progressive-disclosure skills
9
+ * <plugin>/sandbox/ optional sandboxed entry point for untrusted plugins
10
+ *
11
+ * Everything a plugin contributes becomes a SkillDef, so plugin commands
12
+ * and skills flow through the same invocation path (/name, body on demand,
13
+ * listed by /skills) as native ones.
14
+ */
15
+ import { existsSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { loadSkills, type SkillDef } from "../skills/loader.ts";
18
+ import { createSandbox, type SandboxConfig, type SandboxResult, executeSandbox } from "./sandbox.ts";
19
+
20
+ export interface PluginManifest {
21
+ name?: string;
22
+ version?: string;
23
+ description?: string;
24
+ /** If true, plugin commands run in a sandbox (untrusted plugins) */
25
+ sandboxed?: boolean;
26
+ /** Sandbox entry point (default: commands/main.ts) */
27
+ sandboxEntry?: string;
28
+ }
29
+
30
+ export interface Plugin {
31
+ manifest: PluginManifest;
32
+ dir: string;
33
+ sandboxed: boolean;
34
+ }
35
+
36
+ function readManifest(dir: string): Plugin {
37
+ let manifest: PluginManifest = { name: dir.split(/[\\/]/).pop() };
38
+ const p = join(dir, "manifest.json");
39
+ if (existsSync(p)) {
40
+ try { manifest = { name: manifest.name, ...JSON.parse(readFileSync(p, "utf8")) }; } catch { /* keep dir name */ }
41
+ }
42
+ return { manifest, dir, sandboxed: manifest.sandboxed ?? false };
43
+ }
44
+
45
+ export function loadPlugins(dirs: string[]): Plugin[] {
46
+ return dirs.filter((d) => existsSync(d)).map(readManifest);
47
+ }
48
+
49
+ /** Commands a plugin dir contributes: <dir>/commands/<name>.md → SkillDefs. */
50
+ export function pluginCommandSkills(dir: string): SkillDef[] {
51
+ const cmdDir = join(dir, "commands");
52
+ if (!existsSync(cmdDir)) return [];
53
+ const out: SkillDef[] = [];
54
+ for (const f of readdirSync(cmdDir)) {
55
+ if (!f.endsWith(".md")) continue;
56
+ const name = f.replace(/\.md$/, "");
57
+ const text = readFileSync(join(cmdDir, f), "utf8");
58
+ const m = text.match(/^---\s*\n([\s\S]*?)\n---\s*\n?/);
59
+ let description = `/${name} from plugin ${dir.split(/[\\/]/).pop()}`;
60
+ let body = text;
61
+ if (m) {
62
+ body = text.slice(m[0].length);
63
+ for (const line of m[1].split("\n")) {
64
+ const i = line.indexOf(":");
65
+ if (i > 0 && line.slice(0, i).trim() === "description") {
66
+ description = line.slice(i + 1).trim().replace(/^"|"$/g, "");
67
+ }
68
+ }
69
+ }
70
+ // $ARGUMENTS / $1..$9 placeholders stay in the body; substituted at invocation
71
+ out.push({ name, description, _body: body, _path: join(cmdDir, f) });
72
+ }
73
+ return out;
74
+ }
75
+
76
+ /** All SkillDefs a set of plugin dirs contributes (commands + skills). */
77
+ export function pluginSkills(plugins: Plugin[]): SkillDef[] {
78
+ const out: SkillDef[] = [];
79
+ for (const p of plugins) {
80
+ out.push(...pluginCommandSkills(p.dir));
81
+ const skillRoot = join(p.dir, "skills");
82
+ if (existsSync(skillRoot)) out.push(...loadSkills(skillRoot));
83
+ }
84
+ return out;
85
+ }
86
+
87
+ /**
88
+ * Execute a sandboxed plugin command via the sandbox runner.
89
+ * Returns the result as a string (stdout).
90
+ */
91
+ export async function executeSandboxedPlugin(
92
+ plugin: Plugin,
93
+ args: Record<string, unknown>,
94
+ ): Promise<SandboxResult> {
95
+ const entryPoint = plugin.manifest.sandboxEntry ?? join(plugin.dir, "sandbox", "main.ts");
96
+ if (!existsSync(entryPoint)) {
97
+ return { ok: false, output: `sandbox entry not found: ${entryPoint}`, exitCode: null, signal: null, durationMs: 0, timedOut: false };
98
+ }
99
+
100
+ // Write args to temp file for the sandbox to read
101
+ const argsFile = join(plugin.dir, ".sandbox-args.json");
102
+ try {
103
+ writeFileSync(argsFile, JSON.stringify(args), "utf8");
104
+ } catch { /* best effort */ }
105
+
106
+ const result = await executeSandbox({
107
+ entryPoint,
108
+ workDir: plugin.dir,
109
+ env: { GOAT_PLUGIN_ARGS_FILE: argsFile },
110
+ timeoutMs: 30_000,
111
+ onStdout: (data) => process.stdout.write(data),
112
+ onStderr: (data) => process.stderr.write(data),
113
+ });
114
+
115
+ // Clean up args file
116
+ try { unlinkSync(argsFile); } catch { /* ignore */ }
117
+
118
+ return result;
119
+ }
120
+
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Plugin Marketplace — registry index, tgz install with pinned ed25519
3
+ * sigs, and plugin lifecycle. Plugin dirs live under <appDir()>/plugins.
4
+ *
5
+ * NO wasmtime — the v2 plugin directory bundle IS the plugin system;
6
+ * tgz installation is the extension mechanism only.
7
+ */
8
+ import { existsSync, mkdirSync, rmSync, readFileSync, writeFileSync, readdirSync, statSync, renameSync } from "node:fs";
9
+ import { join, dirname, resolve, basename } from "node:path";
10
+ import { appDir } from "../config.ts";
11
+ import { loadPlugins, type PluginManifest as _PM } from "./loader.ts";
12
+ export type { PluginManifest } from "./loader.ts";
13
+ import type { PluginManifest } from "./loader.ts";
14
+ import { extractTar, writeTarFixtures, TarError, MAX_DECOMPRESSED } from "./tar.ts";
15
+ import { randomUUID, generateKeyPairSync, sign, createPublicKey } from "node:crypto";
16
+
17
+ export const DEFAULT_REGISTRY_URL = "https://raw.githubusercontent.com/Arhan-w/GoatCode/v3-plugins/index.json";
18
+ const FETCH_CAP = 50_000_000;
19
+
20
+ function registryBase(url?: string): string {
21
+ const u = url ?? DEFAULT_REGISTRY_URL;
22
+ return u.replace(/\/index\.json$/, "");
23
+ }
24
+
25
+ function pluginsDir(): string {
26
+ return join(appDir(), "plugins");
27
+ }
28
+
29
+ /** Stable canonical JSON stringify (sorted keys at every level, arrays keep order). */
30
+ export function canonicalManifest(obj: unknown): string {
31
+ return JSON.stringify(obj, (_key, val) => {
32
+ if (val && typeof val === "object" && !Array.isArray(val)) {
33
+ return Object.keys(val as Record<string, unknown>).sort().reduce((acc, k) => {
34
+ acc[k] = (val as Record<string, unknown>)[k];
35
+ return acc;
36
+ }, {} as Record<string, unknown>);
37
+ }
38
+ return val;
39
+ });
40
+ }
41
+
42
+ function compareVersions(a: string, b: string): number {
43
+ const pa = a.split(".").map(Number);
44
+ const pb = b.split(".").map(Number);
45
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
46
+ const x = pa[i] ?? 0;
47
+ const y = pb[i] ?? 0;
48
+ if (x !== y) return x < y ? -1 : 1;
49
+ }
50
+ return 0;
51
+ }
52
+
53
+ /** Verify ed25519 signature using node:crypto. */
54
+ function verifySig(pubKeyPem: string, data: Buffer, sigHex: string): boolean {
55
+ try {
56
+ const { verify } = require("node:crypto");
57
+ const pubKey = createPublicKey(pubKeyPem);
58
+ return verify(null, data, pubKey, Buffer.from(sigHex, "hex"));
59
+ } catch { return false; }
60
+ }
61
+
62
+ export async function installPlugin(
63
+ source: string,
64
+ cfg: any,
65
+ io: { confirm?: (msg: string) => Promise<boolean>; log?: (s: string) => void } = {}
66
+ ): Promise<string> {
67
+ const destDir = pluginsDir();
68
+ const tmpDir = join(destDir, `.tmp-${process.pid}-${randomUUID().slice(0, 8)}`);
69
+ const confirm = io.confirm ?? (async () => true);
70
+ const log = io.log ?? (() => {});
71
+
72
+ try {
73
+ let tgzBuf: Buffer;
74
+ let sigHex: string | undefined;
75
+ let keyId: string | undefined;
76
+
77
+ if (source.startsWith("file://")) {
78
+ const path = decodeURI(new URL(source).pathname);
79
+ tgzBuf = readFileSync(path);
80
+ // Check for sibling .sig
81
+ const sigPath = path.replace(/\.tgz$/, "") + ".sig";
82
+ if (existsSync(sigPath)) {
83
+ const parsed = JSON.parse(readFileSync(sigPath, "utf8"));
84
+ sigHex = parsed.sig; keyId = parsed.key;
85
+ }
86
+ } else {
87
+ // URL (https or registry)
88
+ const url = source;
89
+ const fetchUrl = url.endsWith(".tgz") ? url : `${registryBase(url.includes("index.json") ? undefined : url)}/${url.split("/").pop()?.replace(/\.tgz$/, "") ?? url}.tgz`;
90
+
91
+ const res = await fetch(fetchUrl, { signal: AbortSignal.timeout(30_000) });
92
+ if (!res.ok) throw new Error(`registry fetch failed: ${res.status}`);
93
+ const bytes = Buffer.from(await res.arrayBuffer());
94
+ if (bytes.length > FETCH_CAP) throw new TarError("plugin payload exceeds 50MB");
95
+ tgzBuf = bytes;
96
+
97
+ // Fetch signature if available
98
+ const sigUrl = fetchUrl.replace(/\.tgz$/, ".sig");
99
+ try {
100
+ const sres = await fetch(sigUrl, { signal: AbortSignal.timeout(10_000) });
101
+ if (sres.ok) {
102
+ const body = await sres.json();
103
+ sigHex = body.sig; keyId = body.key;
104
+ }
105
+ } catch { /* sig optional */ }
106
+ }
107
+
108
+ // Extract to tmp
109
+ mkdirSync(tmpDir, { recursive: true });
110
+ extractTar(tgzBuf, tmpDir);
111
+
112
+ // Find manifest.json
113
+ const manifestPath = join(tmpDir, "manifest.json");
114
+ if (!existsSync(manifestPath)) throw new Error("manifest.json required");
115
+ const manifest: PluginManifest & { name: string; version: string; description?: string } = JSON.parse(readFileSync(manifestPath, "utf8"));
116
+ const slug = basename(source.endsWith(".tgz") ? source.slice(0, -4) : source).split("/").pop() ?? manifest.name;
117
+
118
+ if (!manifest.name || !/^[a-z0-9][a-z0-9_-]*$/.test(manifest.name)) {
119
+ throw new Error(`manifest name does not match slug pattern`);
120
+ }
121
+
122
+ // Signature verification if sigHex present
123
+ if (sigHex) {
124
+ const keysPath = join(destDir, "keys.json");
125
+ if (!existsSync(keysPath)) {
126
+ const allowed = await confirm("unsigned plugin — keys.json missing, install anyway?");
127
+ if (!allowed) { rmSync(tmpDir, { recursive: true, force: true }); return "refused"; }
128
+ } else {
129
+ const keys: Record<string, string> = JSON.parse(readFileSync(keysPath, "utf8"));
130
+ if (!keyId || !keys[keyId]) {
131
+ rmSync(tmpDir, { recursive: true, force: true });
132
+ throw new Error("unknown key id — signature refused");
133
+ }
134
+ const canonical = canonicalManifest(manifest);
135
+ if (!verifySig(keys[keyId], Buffer.from(canonical), sigHex)) {
136
+ rmSync(tmpDir, { recursive: true, force: true });
137
+ throw new Error("signature verification failed");
138
+ }
139
+ }
140
+ } else if (source.startsWith("file://") || sigHex !== undefined) {
141
+ // unsigned from file:// or registry with sig available but not present
142
+ const allowed = await confirm(`unsigned plugin ${slug} — install anyway?`);
143
+ if (!allowed) { rmSync(tmpDir, { recursive: true, force: true }); return "refused"; }
144
+ }
145
+
146
+ // Determine target: <pluginsDir>/<name>@<version>
147
+ const targetName = manifest.name ?? slug;
148
+ const targetVersion = manifest.version ?? "0.0.0";
149
+ const targetDir = join(destDir, `${targetName}@${targetVersion}`);
150
+
151
+ // Windows: rm existing dest then rename (renameSync fails if dest exists)
152
+ if (existsSync(targetDir)) {
153
+ rmSync(targetDir, { recursive: true, force: true });
154
+ }
155
+
156
+ // Move extracted content to target
157
+ const entries = readdirSync(tmpDir);
158
+ const srcDir = entries.length === 1 && statSync(join(tmpDir, entries[0])).isDirectory()
159
+ ? join(tmpDir, entries[0]) : tmpDir;
160
+
161
+ mkdirSync(targetDir, { recursive: true });
162
+ for (const e of readdirSync(srcDir)) {
163
+ const src = join(srcDir, e);
164
+ const dst = join(targetDir, e);
165
+ if (existsSync(dst)) rmSync(dst, { recursive: true, force: true });
166
+ renameSync(src, dst);
167
+ }
168
+
169
+ // Update plugin list — store absolute path (pluginDirs is canonical)
170
+ const key = Array.isArray(cfg.pluginDirs) ? "pluginDirs" : "plugins";
171
+ if (!cfg[key]?.includes(targetDir)) {
172
+ cfg[key] = cfg[key] ?? [];
173
+ cfg[key].push(targetDir);
174
+ }
175
+
176
+ rmSync(tmpDir, { recursive: true, force: true });
177
+ return targetName;
178
+ } catch (e) {
179
+ rmSync(tmpDir, { recursive: true, force: true });
180
+ throw e;
181
+ }
182
+ }
183
+
184
+ export async function listInstalled(cfg: any): Promise<{ name: string; version: string; dir: string }[]> {
185
+ const dirs: string[] = cfg.pluginDirs ?? cfg.plugins ?? [];
186
+ const plugins = loadPlugins(dirs.map((d: string) => join(process.cwd(), d)));
187
+ return plugins.map((p) => ({
188
+ name: p.manifest.name ?? basename(p.dir),
189
+ version: p.manifest.version ?? "0.0.0",
190
+ dir: p.dir,
191
+ }));
192
+ }
193
+
194
+ export function removePlugin(name: string, cfg: any): void {
195
+ const dir = join(pluginsDir(), name);
196
+ if (existsSync(dir)) rmSync(dir, { recursive: true, force: true });
197
+ // Strip from the plugin list
198
+ for (const key of ["pluginDirs", "plugins"] as const) {
199
+ if (Array.isArray(cfg[key]))
200
+ cfg[key] = cfg[key].filter((p: string) => {
201
+ const b = basename(p);
202
+ return !b.startsWith(name + "@") && b !== name;
203
+ });
204
+ }
205
+ }
206
+
207
+ export async function updatePlugin(name: string, cfg: any): Promise<boolean> {
208
+ const installed = loadPlugins([join(pluginsDir(), name)]);
209
+ if (!installed.length) return false;
210
+ const instVer = installed[0].manifest.version ?? "0.0.0";
211
+ const base = registryBase();
212
+ try {
213
+ const res = await fetch(`${base}/${name}/index.json`, { signal: AbortSignal.timeout(10_000) });
214
+ if (!res.ok) return false;
215
+ const idx = await res.json();
216
+ const regVer = idx.version ?? "0.0.0";
217
+ if (compareVersions(regVer, instVer) > 0) {
218
+ await installPlugin(`${base}/${name}/${regVer}.tgz`, cfg, {});
219
+ return true;
220
+ }
221
+ } catch { /* registry unavailable */ }
222
+ return false;
223
+ }
224
+
225
+ export async function searchPlugins(query: string, cfg: any): Promise<{ plugins: { name: string; version: string; description: string }[] } | string> {
226
+ try {
227
+ const url = (cfg.pluginRegistry?.url ?? DEFAULT_REGISTRY_URL).replace(/\/index\.json$/, "") + "/index.json";
228
+ const res = await fetch(url, { signal: AbortSignal.timeout(10_000) });
229
+ if (!res.ok) return "registry index unavailable";
230
+ const idx = await res.json();
231
+ if (!idx.plugins) return "registry index unavailable";
232
+ if (!query) return idx;
233
+ const q = query.toLowerCase();
234
+ return { plugins: idx.plugins.filter((p: any) => p.name.toLowerCase().includes(q) || (p.description ?? "").toLowerCase().includes(q)) };
235
+ } catch { return "registry index unavailable"; }
236
+ }
237
+
238
+ /** Parse a goat:// URI. Returns the plugin name or null. */
239
+ export function parseGoatUri(s: string): string | null {
240
+ try {
241
+ const u = new URL(s);
242
+ if (u.protocol === "goat:" && u.hostname === "plugins") return u.pathname.slice(1) || null;
243
+ return null;
244
+ } catch { return null; }
245
+ }
246
+
247
+ /** Read keys.json for a plugin. */
248
+ export function loadKeys(): Record<string, string> {
249
+ const kp = join(pluginsDir(), "keys.json");
250
+ if (!existsSync(kp)) return {};
251
+ return JSON.parse(readFileSync(kp, "utf8"));
252
+ }