@uinaf/agent-plugin-stuff 0.0.0-stage → 2.1.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.
@@ -0,0 +1,189 @@
1
+ import { spawn } from "node:child_process";
2
+ import path from "node:path";
3
+ // src/grok-provider.ts
4
+ function record(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ function nonnegativeNumber(value) {
8
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
9
+ }
10
+ function isGrokEvent(value) {
11
+ if (!record(value) || typeof value.type !== "string") return false;
12
+ if (value.type === "text") return typeof value.data === "string";
13
+ if (value.type === "tool_call" && value.toolName === "read_file") {
14
+ if (typeof value.toolCallId !== "string") return false;
15
+ const input = value.rawInput;
16
+ if (input === void 0 || input === null) return true;
17
+ return record(input) && (input.target_file === void 0 || typeof input.target_file === "string") && (input.path === void 0 || typeof input.path === "string");
18
+ }
19
+ if (value.type === "tool_call_update") return typeof value.toolCallId === "string" && (value.status === void 0 || value.status === null || typeof value.status === "string");
20
+ if (value.type !== "end") return true;
21
+ if (typeof value.stopReason !== "string") return false;
22
+ if (value.usage !== void 0) {
23
+ if (!record(value.usage)) return false;
24
+ for (const key of [
25
+ "input_tokens",
26
+ "output_tokens",
27
+ "total_tokens",
28
+ "cache_read_input_tokens"
29
+ ]) if (value.usage[key] !== void 0 && !nonnegativeNumber(value.usage[key])) return false;
30
+ }
31
+ return value.total_cost_usd === void 0 || nonnegativeNumber(value.total_cost_usd);
32
+ }
33
+ const OUTPUT_CAP = 1e6;
34
+ function within(root, file) {
35
+ const rel = path.relative(root, file);
36
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
37
+ }
38
+ function attempt(action) {
39
+ try {
40
+ action();
41
+ return true;
42
+ } catch {
43
+ return false;
44
+ }
45
+ }
46
+ var GrokProvider = class {
47
+ config;
48
+ constructor(options) {
49
+ if (!options.config?.working_dir || !options.config.skill) throw new Error("grok provider requires working_dir and skill");
50
+ this.config = options.config;
51
+ }
52
+ id() {
53
+ return "grok:cli";
54
+ }
55
+ async callApi(prompt, _context, callOptions) {
56
+ const { working_dir: workdir, skill, model, command = "grok", timeout_ms = 6e5 } = this.config;
57
+ const skillFile = path.join(workdir, ".grok", "skills", skill, "SKILL.md");
58
+ const args = [
59
+ "--trust",
60
+ "--no-auto-update",
61
+ "--cwd",
62
+ workdir,
63
+ "--output-format",
64
+ "streaming-json",
65
+ "--permission-mode",
66
+ "acceptEdits",
67
+ "--no-subagents",
68
+ ...model ? ["--model", model] : [],
69
+ "-p",
70
+ prompt
71
+ ];
72
+ return new Promise((resolve) => {
73
+ const child = spawn(command, args, {
74
+ cwd: workdir,
75
+ detached: process.platform !== "win32",
76
+ stdio: [
77
+ "ignore",
78
+ "pipe",
79
+ "pipe"
80
+ ]
81
+ });
82
+ let stdout = "";
83
+ let stderr = "";
84
+ let output = "";
85
+ let stopReason;
86
+ let usage;
87
+ let cost;
88
+ let error;
89
+ const reads = /* @__PURE__ */ new Map();
90
+ const skillCalls = [];
91
+ const stop = (reason) => {
92
+ error ??= reason;
93
+ if (child.pid !== void 0) {
94
+ const pid = child.pid;
95
+ attempt(() => {
96
+ if (process.platform === "win32") child.kill();
97
+ else process.kill(-pid, "SIGKILL");
98
+ });
99
+ }
100
+ };
101
+ const consume = (line) => {
102
+ if (!line.trim()) return;
103
+ let event;
104
+ try {
105
+ event = JSON.parse(line);
106
+ } catch {
107
+ stop("grok emitted invalid streaming JSON");
108
+ return;
109
+ }
110
+ if (!isGrokEvent(event)) {
111
+ stop("grok emitted an invalid streaming event");
112
+ return;
113
+ }
114
+ if (event.type === "text" && typeof event.data === "string") {
115
+ output += event.data;
116
+ if (output.length > OUTPUT_CAP) stop("grok output exceeded limit");
117
+ } else if (event.type === "tool_call" && event.toolName === "read_file") {
118
+ const target = event.rawInput?.target_file ?? event.rawInput?.path;
119
+ if (event.toolCallId && typeof target === "string") {
120
+ const resolved = path.resolve(workdir, target);
121
+ if (within(workdir, resolved)) reads.set(event.toolCallId, resolved);
122
+ }
123
+ } else if (event.type === "tool_call_update" && event.status === "completed") {
124
+ const target = event.toolCallId && reads.get(event.toolCallId);
125
+ if (target === skillFile && !skillCalls.some((call) => call.path === target)) skillCalls.push({
126
+ name: skill,
127
+ source: "project",
128
+ path: target
129
+ });
130
+ } else if (event.type === "end") {
131
+ stopReason = event.stopReason;
132
+ usage = event.usage;
133
+ cost = event.total_cost_usd;
134
+ }
135
+ };
136
+ child.stdout?.setEncoding("utf8");
137
+ child.stderr?.setEncoding("utf8");
138
+ child.stdout?.on("data", (chunk) => {
139
+ stdout += chunk;
140
+ if (stdout.length > OUTPUT_CAP) {
141
+ stop("grok event stream exceeded limit");
142
+ return;
143
+ }
144
+ let newline = stdout.indexOf("\n");
145
+ while (newline !== -1) {
146
+ consume(stdout.slice(0, newline));
147
+ stdout = stdout.slice(newline + 1);
148
+ newline = stdout.indexOf("\n");
149
+ }
150
+ });
151
+ child.stderr?.on("data", (chunk) => {
152
+ stderr = (stderr + chunk).slice(-4e3);
153
+ });
154
+ child.on("error", (cause) => {
155
+ error ??= `grok could not start: ${cause.message}`;
156
+ });
157
+ const timer = setTimeout(() => stop(`grok timed out after ${timeout_ms}ms`), timeout_ms);
158
+ const abort = () => stop("grok run aborted");
159
+ callOptions?.abortSignal?.addEventListener("abort", abort, { once: true });
160
+ if (callOptions?.abortSignal?.aborted) abort();
161
+ child.on("exit", () => {
162
+ if (process.platform !== "win32" && child.pid !== void 0) {
163
+ const pid = child.pid;
164
+ attempt(() => process.kill(-pid, "SIGKILL"));
165
+ }
166
+ });
167
+ child.on("close", (code, signal) => {
168
+ clearTimeout(timer);
169
+ callOptions?.abortSignal?.removeEventListener("abort", abort);
170
+ if (stdout) consume(stdout);
171
+ if (error) resolve({ error });
172
+ else if (code !== 0) resolve({ error: `grok exited ${signal ?? code}: ${stderr.trim() || "no diagnostics"}` });
173
+ else if (stopReason !== "end_turn") resolve({ error: `grok stopped with ${stopReason ?? "no terminal event"}` });
174
+ else resolve({
175
+ output,
176
+ metadata: { skillCalls },
177
+ ...usage ? { tokenUsage: {
178
+ prompt: usage.input_tokens ?? 0,
179
+ completion: usage.output_tokens ?? 0,
180
+ total: usage.total_tokens ?? 0,
181
+ cached: usage.cache_read_input_tokens ?? 0
182
+ } } : {},
183
+ ...typeof cost === "number" ? { cost } : {}
184
+ });
185
+ });
186
+ });
187
+ }
188
+ };
189
+ export { GrokProvider as default };
package/dist/lint.js ADDED
@@ -0,0 +1,107 @@
1
+ import { FILE_BLOCK, isHiddenSkill, parseCriteria } from "./scenario.js";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ // src/lint.ts
5
+ const ALLOWED_KEYS = /* @__PURE__ */ new Set([
6
+ "name",
7
+ "description",
8
+ "disable-model-invocation"
9
+ ]);
10
+ function lintSkill(dir, root, errors) {
11
+ const skillMd = path.join(dir, "SKILL.md");
12
+ const label = path.relative(root, skillMd);
13
+ if (!fs.existsSync(skillMd)) {
14
+ errors.push(`${path.relative(root, dir)}: missing SKILL.md`);
15
+ return;
16
+ }
17
+ const lines = fs.readFileSync(skillMd, "utf8").split("\n");
18
+ if (lines[0] !== "---") {
19
+ errors.push(`${label}: frontmatter must open with --- on line 1`);
20
+ return;
21
+ }
22
+ const close = lines.indexOf("---", 1);
23
+ if (close === -1) {
24
+ errors.push(`${label}: frontmatter never closes`);
25
+ return;
26
+ }
27
+ const fields = /* @__PURE__ */ new Map();
28
+ for (const line of lines.slice(1, close)) {
29
+ const m = line.match(/^([a-z-]+):\s*(.*)$/);
30
+ if (!m) {
31
+ errors.push(`${label}: unparseable frontmatter line: ${line}`);
32
+ continue;
33
+ }
34
+ const [, key, raw] = m;
35
+ if (!ALLOWED_KEYS.has(key)) {
36
+ errors.push(`${label}: unknown frontmatter key: ${key}`);
37
+ continue;
38
+ }
39
+ if (fields.has(key)) {
40
+ errors.push(`${label}: duplicate frontmatter key: ${key}`);
41
+ continue;
42
+ }
43
+ const value = raw.replace(/^"(.*)"$/s, "$1").replace(/^'(.*)'$/s, "$1").trim();
44
+ fields.set(key, {
45
+ raw: raw.trim(),
46
+ value
47
+ });
48
+ }
49
+ const name = fields.get("name")?.value ?? "";
50
+ if (name !== path.basename(dir)) errors.push(`${label}: frontmatter name ${JSON.stringify(name)} != directory ${path.basename(dir)}`);
51
+ if (!fields.get("description")?.value) errors.push(`${label}: description is required and must be non-empty`);
52
+ const dmi = fields.get("disable-model-invocation");
53
+ if (dmi !== void 0 && dmi.raw !== "true") errors.push(`${label}: disable-model-invocation must be the literal boolean true, got ${JSON.stringify(dmi.raw)}`);
54
+ const body = lines.slice(close + 1).join("\n").replaceAll(/^```[\s\S]*?^```/gm, "").replaceAll(/`[^`\n]*`/g, "");
55
+ for (const link of body.matchAll(/\]\(\s*(<[^>\n]*>|[^)\s]+)(?:\s+"[^"\n]*")?\s*\)/g)) {
56
+ const target = link[1].replace(/^<(.*)>$/, "$1");
57
+ if (/^[a-z][a-z+.-]*:/.test(target) || target.startsWith("#") || target === "") continue;
58
+ const resolved = path.join(dir, target.split("#")[0]);
59
+ if (!fs.existsSync(resolved)) errors.push(`${label}: link target does not exist: ${target}`);
60
+ }
61
+ }
62
+ function lintSkills(root) {
63
+ const roots = ["skills", ...fs.globSync("cli/*/skills", { cwd: root })].map((r) => path.join(root, r));
64
+ const errors = [];
65
+ const skills = [];
66
+ for (const dir of roots) {
67
+ if (!fs.existsSync(dir)) continue;
68
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
69
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
70
+ lintSkill(path.join(dir, entry.name), root, errors);
71
+ skills.push(path.join(dir, entry.name));
72
+ }
73
+ }
74
+ lintEvals(skills, root, errors);
75
+ return {
76
+ errors,
77
+ count: skills.length
78
+ };
79
+ }
80
+ function lintEvals(skills, root, errors) {
81
+ const names = skills.map((dir) => path.basename(dir));
82
+ for (const dir of skills) {
83
+ const evals = path.join(dir, "evals");
84
+ if (!fs.existsSync(evals)) continue;
85
+ const skillMd = path.join(dir, "SKILL.md");
86
+ const hidden = fs.existsSync(skillMd) && isHiddenSkill(fs.readFileSync(skillMd, "utf8"));
87
+ for (const scenario of fs.readdirSync(evals, { withFileTypes: true })) {
88
+ if (!scenario.isDirectory()) continue;
89
+ const scenarioDir = path.join(evals, scenario.name);
90
+ const criteria = path.join(scenarioDir, "criteria.json");
91
+ if (fs.existsSync(criteria)) try {
92
+ parseCriteria(scenarioDir, hidden);
93
+ } catch (error) {
94
+ const message = error instanceof Error ? error.message : String(error);
95
+ errors.push(`${path.relative(root, criteria)}: ${message}`);
96
+ }
97
+ const file = path.join(scenarioDir, "task.md");
98
+ if (!fs.existsSync(file)) continue;
99
+ const text = fs.readFileSync(file, "utf8").replace(FILE_BLOCK, "");
100
+ for (const name of names) {
101
+ const escaped = name.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
102
+ if (new RegExp(`(?<![\\w-])${escaped}(?![\\w-])`, "i").test(text)) errors.push(`${path.relative(root, file)}: task names skill ${name}`);
103
+ }
104
+ }
105
+ }
106
+ }
107
+ export { lintSkills };
package/dist/plugin.js ADDED
@@ -0,0 +1,158 @@
1
+ import { lintSkills } from "./lint.js";
2
+ import { lintRules } from "./rules.js";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ // src/plugin.ts
6
+ const MANIFEST_PATHS = [
7
+ "plugin.json",
8
+ ".cursor-plugin/plugin.json",
9
+ ".claude-plugin/plugin.json"
10
+ ];
11
+ const MCP_PATHS = [
12
+ "mcp.json",
13
+ ".mcp.json",
14
+ "mcp_config.json"
15
+ ];
16
+ function readJsonObject(file, label, errors) {
17
+ let parsed;
18
+ try {
19
+ parsed = JSON.parse(fs.readFileSync(file, "utf8"));
20
+ } catch (error) {
21
+ const message = error instanceof Error ? error.message : String(error);
22
+ errors.push(`${label}: invalid JSON: ${message}`);
23
+ return;
24
+ }
25
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
26
+ errors.push(`${label}: expected a JSON object`);
27
+ return;
28
+ }
29
+ return parsed;
30
+ }
31
+ function checkDeclaredPaths(manifest, key, root, label, errors) {
32
+ const value = manifest[key];
33
+ if (value === void 0) return;
34
+ const items = typeof value === "string" ? [value] : Array.isArray(value) ? value : void 0;
35
+ if (items === void 0) {
36
+ errors.push(`${label}: ${key} must be a string or an array of strings`);
37
+ return;
38
+ }
39
+ for (const item of items) {
40
+ if (typeof item !== "string" || item.trim() === "") {
41
+ errors.push(`${label}: ${key} entries must be non-empty strings`);
42
+ continue;
43
+ }
44
+ const full = path.resolve(root, item);
45
+ if (!fs.existsSync(full)) errors.push(`${label}: ${key} target does not exist: ${item}`);
46
+ }
47
+ }
48
+ function lintManifests(root, errors) {
49
+ const names = [];
50
+ const descriptions = [];
51
+ let count = 0;
52
+ for (const rel of MANIFEST_PATHS) {
53
+ const file = path.join(root, rel);
54
+ if (!fs.existsSync(file)) continue;
55
+ count++;
56
+ const manifest = readJsonObject(file, rel, errors);
57
+ if (manifest === void 0) continue;
58
+ if (typeof manifest.name !== "string" || manifest.name.trim() === "") errors.push(`${rel}: name is required and must be a non-empty string`);
59
+ else names.push({
60
+ label: rel,
61
+ name: manifest.name.trim()
62
+ });
63
+ if (typeof manifest.description !== "string" || manifest.description.trim() === "") errors.push(`${rel}: description is required and must be a non-empty string`);
64
+ else descriptions.push({
65
+ label: rel,
66
+ description: manifest.description.trim()
67
+ });
68
+ for (const key of [
69
+ "skills",
70
+ "agents",
71
+ "commands"
72
+ ]) checkDeclaredPaths(manifest, key, root, rel, errors);
73
+ }
74
+ if (names.length > 1) {
75
+ const primary = names[0];
76
+ for (const other of names.slice(1)) if (other.name !== primary.name) errors.push(`${other.label}: name ${JSON.stringify(other.name)} differs from ${primary.label} (${JSON.stringify(primary.name)})`);
77
+ }
78
+ if (descriptions.length > 1) {
79
+ const primary = descriptions[0];
80
+ for (const other of descriptions.slice(1)) if (other.description !== primary.description) errors.push(`${other.label}: description differs from ${primary.label}`);
81
+ }
82
+ return count;
83
+ }
84
+ function normalizeMcpServer(raw) {
85
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return;
86
+ const server = raw;
87
+ const normalized = {};
88
+ for (const key of [
89
+ "type",
90
+ "url",
91
+ "command",
92
+ "args"
93
+ ]) if (server[key] !== void 0) normalized[key] = server[key];
94
+ return normalized;
95
+ }
96
+ function lintMcpConfigs(root, errors) {
97
+ const parsedConfigs = [];
98
+ let count = 0;
99
+ for (const rel of MCP_PATHS) {
100
+ const file = path.join(root, rel);
101
+ if (!fs.existsSync(file)) continue;
102
+ count++;
103
+ const config = readJsonObject(file, rel, errors);
104
+ if (config === void 0) continue;
105
+ const rawServers = config.mcpServers;
106
+ if (rawServers === null || typeof rawServers !== "object" || Array.isArray(rawServers)) {
107
+ errors.push(`${rel}: mcpServers must be an object`);
108
+ continue;
109
+ }
110
+ const servers = {};
111
+ for (const [name, entry] of Object.entries(rawServers).sort(([a], [b]) => a.localeCompare(b))) {
112
+ const normalized = normalizeMcpServer(entry);
113
+ if (normalized === void 0) {
114
+ errors.push(`${rel}: mcpServers.${name} must be an object`);
115
+ continue;
116
+ }
117
+ if (normalized.url === void 0 && normalized.command === void 0) errors.push(`${rel}: mcpServers.${name} must set url or command`);
118
+ servers[name] = normalized;
119
+ }
120
+ parsedConfigs.push({
121
+ label: rel,
122
+ servers
123
+ });
124
+ }
125
+ if (parsedConfigs.length > 1) {
126
+ const primary = parsedConfigs[0];
127
+ for (const other of parsedConfigs.slice(1)) {
128
+ const aKeys = Object.keys(primary.servers);
129
+ const bKeys = Object.keys(other.servers);
130
+ if (JSON.stringify(aKeys) !== JSON.stringify(bKeys)) {
131
+ errors.push(`${other.label}: mcpServers keys (${bKeys.join(", ")}) differ from ${primary.label} (${aKeys.join(", ")})`);
132
+ continue;
133
+ }
134
+ for (const name of aKeys) {
135
+ const a = primary.servers[name];
136
+ const b = other.servers[name];
137
+ if (a.url !== b.url || a.command !== b.command || JSON.stringify(a.args) !== JSON.stringify(b.args)) errors.push(`${other.label}: mcpServers.${name} differs from ${primary.label}`);
138
+ }
139
+ }
140
+ }
141
+ return count;
142
+ }
143
+ function lintPlugin(root) {
144
+ const errors = [];
145
+ const manifestsCount = lintManifests(root, errors);
146
+ const mcpCount = lintMcpConfigs(root, errors);
147
+ const skills = lintSkills(root);
148
+ const rules = lintRules(root);
149
+ errors.push(...skills.errors, ...rules.errors);
150
+ return {
151
+ errors: [...new Set(errors)],
152
+ skillsCount: skills.count,
153
+ rulesCount: rules.count,
154
+ manifestsCount,
155
+ mcpCount
156
+ };
157
+ }
158
+ export { lintPlugin };
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs, resolveRoot } from "./cli.js";
3
+ import { lintPlugin } from "./plugin.js";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ // src/plugincheck.ts
7
+ function fail(msg) {
8
+ console.error(msg);
9
+ process.exit(1);
10
+ }
11
+ function runPlugincheck(argv) {
12
+ const rest = argv[0] === "lint" ? argv.slice(1) : argv;
13
+ const { positional, flags } = parseArgs(rest);
14
+ if (positional.length > 1) fail("usage: plugincheck [lint] [<root>] [--root DIR]");
15
+ const root = positional.length === 1 ? path.resolve(positional[0]) : resolveRoot(flags);
16
+ const report = lintPlugin(root);
17
+ if (report.errors.length > 0) {
18
+ for (const e of report.errors) console.error(e);
19
+ console.error(`plugin lint: ${report.errors.length} error(s)`);
20
+ process.exit(1);
21
+ }
22
+ console.log(`plugin lint: ${report.skillsCount} skill(s), ${report.rulesCount} rule(s), ${report.manifestsCount} manifest(s), ${report.mcpCount} mcp config(s) clean`);
23
+ }
24
+ function isMainModule() {
25
+ const entry = process.argv[1];
26
+ if (entry === void 0) return false;
27
+ try {
28
+ return fs.realpathSync(entry) === fs.realpathSync(import.meta.filename);
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+ if (isMainModule()) try {
34
+ runPlugincheck(process.argv.slice(2));
35
+ } catch (error) {
36
+ fail(error instanceof Error ? error.message : String(error));
37
+ }
38
+ export { runPlugincheck };
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs, resolveRoot } from "./cli.js";
3
+ import { lintRules } from "./rules.js";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ // src/rulecheck.ts
7
+ function fail(msg) {
8
+ console.error(msg);
9
+ process.exit(1);
10
+ }
11
+ function runRulecheck(argv) {
12
+ const rest = argv[0] === "lint" ? argv.slice(1) : argv;
13
+ const { positional, flags } = parseArgs(rest);
14
+ if (positional.length > 1) fail("usage: rulecheck [lint] [<root>] [--root DIR]");
15
+ const root = positional.length === 1 ? path.resolve(positional[0]) : resolveRoot(flags);
16
+ const { errors, count } = lintRules(root);
17
+ if (errors.length > 0) {
18
+ for (const e of errors) console.error(e);
19
+ console.error(`rule lint: ${errors.length} error(s) across ${count} rule(s)`);
20
+ process.exit(1);
21
+ }
22
+ console.log(`rule lint: ${count} rule(s) clean`);
23
+ }
24
+ function isMainModule() {
25
+ const entry = process.argv[1];
26
+ if (entry === void 0) return false;
27
+ try {
28
+ return fs.realpathSync(entry) === fs.realpathSync(import.meta.filename);
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+ if (isMainModule()) try {
34
+ runRulecheck(process.argv.slice(2));
35
+ } catch (error) {
36
+ fail(error instanceof Error ? error.message : String(error));
37
+ }
38
+ export { runRulecheck };