ceulen 0.9.0 → 0.10.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.
- package/CHANGELOG.md +37 -0
- package/extensions/lib/registry.ts +8 -2
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/index.ts +1 -0
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/gh/configPanel.ts +82 -0
- package/extensions/modules/gh/index.ts +86 -0
- package/extensions/modules/gh/lib/gh-cli.ts +337 -0
- package/extensions/modules/gh/lib/ops.ts +771 -0
- package/extensions/modules/gh/test/gh.test.ts +280 -0
- package/extensions/modules/plan/lib/plan-tools.ts +8 -0
- package/extensions/modules/repair/index.ts +138 -0
- package/extensions/modules/repair/lib/guards.ts +1 -1
- package/extensions/modules/repair/lib/read-selector.ts +242 -0
- package/extensions/modules/repair/test/read-selector.test.ts +198 -0
- package/extensions/modules/steering/configPanel.ts +8 -0
- package/extensions/modules/steering/index.ts +6 -0
- package/extensions/modules/steering/lib/settings.ts +6 -2
- package/extensions/modules/steering/lib/think.ts +66 -0
- package/extensions/modules/steering/test/harness.ts +5 -0
- package/extensions/modules/steering/test/settings.test.ts +2 -0
- package/extensions/modules/steering/test/think.test.ts +77 -0
- package/extensions/modules/web/index.ts +37 -1
- package/extensions/modules/web/lib/a11y.ts +252 -0
- package/extensions/modules/web/test/a11y.test.ts +218 -0
- package/extensions/modules/web/test/extension.test.ts +2 -2
- package/extensions/modules/web/test/hook.test.ts +2 -2
- package/extensions/modules/web/vendor/axe/LICENSE +362 -0
- package/extensions/modules/web/vendor/axe/LICENSE-3RD-PARTY.txt +66 -0
- package/extensions/modules/web/vendor/axe/README.md +19 -0
- package/extensions/modules/web/vendor/axe/axe.min.js +12 -0
- package/package.json +2 -2
- package/skills/web/SKILL.md +1 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,42 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.0 — 2026-10-05
|
|
4
|
+
|
|
5
|
+
- **gh module**: new module — ONE read-only `github` tool over the `gh` CLI
|
|
6
|
+
(port of oh-my-pi's github tool surface): `repo_view`, `file_read`,
|
|
7
|
+
`pr_view`, `pr_diff`, the five `search_*` flavors (issues/prs/code/commits/
|
|
8
|
+
repos, with repo:/org:/user: scope detection + since/until qualifiers), and
|
|
9
|
+
`run_watch` (lean JSON poller with failed-job log tails; budget
|
|
10
|
+
`gh.runWatchTimeoutSecs`, default 600s, on /config → Tools → GitHub).
|
|
11
|
+
Zero npm deps (`node:child_process` spawn, non-interactive env, 5-min
|
|
12
|
+
deadline, 8-MB output cap, one runner seam); fails open on a missing `gh`
|
|
13
|
+
binary. Mutating flows (pr_create/checkout/push) deliberately deferred to
|
|
14
|
+
bash `gh` — plan-mode auto-allow stays valid via READ_ONLY_TOOLS.
|
|
15
|
+
|
|
16
|
+
- **Read path selectors** (repair module): the wrapped `read` accepts OMP-style
|
|
17
|
+
suffixes — `:50`, `:50-200`, `:50+150`, `:50-`, `:-60`, comma-joined
|
|
18
|
+
multi-ranges (`:5-16,960-973`, `:19,59`), `:raw` compounds, and `:conflicts`
|
|
19
|
+
(one block per unresolved merge conflict). Literal-path-wins resolution (OMP
|
|
20
|
+
#4618); multi-range/conflicts slice in-memory with `[lines … of N]` headers.
|
|
21
|
+
|
|
22
|
+
- **think scratchpad tool** (steering module): OMP-parity private scratchpad,
|
|
23
|
+
opt-in via `steering.thinkTool` (default off; binds at load — autoBg
|
|
24
|
+
precedent). The call renders as one dim `· think (N chars)` marker so
|
|
25
|
+
planning notes stay out of the visible transcript while remaining in context
|
|
26
|
+
for later rounds. OMP's externalThinking reasoning-suppression is NOT ported
|
|
27
|
+
(providers flag the request shape as abuse; pi's thinking levels are the
|
|
28
|
+
honest off-switch).
|
|
29
|
+
|
|
30
|
+
- **web_a11y** (web module, 12th tool): real rendered-page accessibility audit
|
|
31
|
+
— axe-core 4.13 vendored unmodified (`vendor/axe/`, MPL-2.0, lazy-loaded,
|
|
32
|
+
zero new deps) injected into local headless Chrome over the existing
|
|
33
|
+
web_interact CDP lifecycle. Returns OMP-format violation reports (impact,
|
|
34
|
+
rule, helpUrl, node targets, `… and N more`); `tags`/`rules`/`selector`/
|
|
35
|
+
`include_incomplete` params; same-origin iframes only (axe walks them
|
|
36
|
+
in-page). The runtime complement to `ux_audit`'s static CSS checks. In-page
|
|
37
|
+
failures ride back through the evaluate value (the CDP connection layer
|
|
38
|
+
drops top-level exceptionDetails).
|
|
39
|
+
|
|
3
40
|
## 0.9.0 — 2026-10-04
|
|
4
41
|
|
|
5
42
|
- **todo HUD**: OMP-parity live UI for the todo module — an above-editor
|
|
@@ -42,6 +42,8 @@ import muninModule from "../modules/munin/index.ts";
|
|
|
42
42
|
import { muninConfig } from "../modules/munin/configPanel.ts";
|
|
43
43
|
import webModule from "../modules/web/index.ts";
|
|
44
44
|
import { webConfig } from "../modules/web/configPanel.ts";
|
|
45
|
+
import ghModule from "../modules/gh/index.ts";
|
|
46
|
+
import { ghConfig } from "../modules/gh/configPanel.js";
|
|
45
47
|
import rulesModule from "../modules/rules/index.ts";
|
|
46
48
|
import configModule from "../modules/config/index.ts";
|
|
47
49
|
|
|
@@ -150,9 +152,13 @@ export const MODULES: ModuleEntry[] = [
|
|
|
150
152
|
// (conditional on web_* tools being active) — no prompt-rewrite contract
|
|
151
153
|
// beyond fff's shipped precedent.
|
|
152
154
|
{ name: "web", category: "Tools", describe: "Unified web tools: search (SearXNG/Brave/Firecrawl), extract & crawl (JSDOM/Firecrawl/Crawl4AI/agy), screenshot/PDF, CDP browser interaction, Gemini research, image generation, one-off chat.", load: webModule, config: webConfig, tools: [
|
|
153
|
-
"web_search", "web_extract", "web_map", "web_crawl", "web_screenshot", "web_pdf", "web_interact", "web_research", "web_image", "web_chat", "web_status",
|
|
155
|
+
"web_search", "web_extract", "web_map", "web_crawl", "web_screenshot", "web_pdf", "web_interact", "web_research", "web_image", "web_chat", "web_status", "web_a11y",
|
|
154
156
|
] },
|
|
155
157
|
{ name: "rules", category: "Context", describe: "Sticky RULES.md constraints carried in every request + a rulebook of on-demand rules served by rule_get. Nearest-first project walk over user-level.", load: rulesModule, tools: ["rule_get"] },
|
|
158
|
+
// gh after web: same class of external-fetch tooling; fail-open on a missing
|
|
159
|
+
// gh binary (registers nothing until installed). Read-only ops only, so
|
|
160
|
+
// plan mode auto-allows it (plan-tools.ts READ_ONLY_TOOLS).
|
|
161
|
+
{ name: "gh", category: "Tools", describe: "GitHub tool over the gh CLI: repo/file/PR views, PR diff, five search flavors, Actions run_watch. Read-only; mutating flows stay on bash gh.", load: ghModule, config: ghConfig, tools: ["github"] },
|
|
156
162
|
// Steering LAST of the prompt rewriters, i.e. after EVERY before_agent_start
|
|
157
163
|
// composer (ponytail/plan/subagent/munin/advisor/ux/fff/serena/web/rules) and
|
|
158
164
|
// before the config module (load order is load-bearing even though its
|
|
@@ -162,7 +168,7 @@ export const MODULES: ModuleEntry[] = [
|
|
|
162
168
|
// (byte-identical minimal prompt) instead of appending to a prompt that
|
|
163
169
|
// serena/web then append to. Nothing after this entry (rtk, config) touches
|
|
164
170
|
// the prompt — do not move it earlier or add a prompt rewriter after it.
|
|
165
|
-
{ name: "steering", category: "Model", describe: "Per-model-family steering (DeepSeek/GLM): first-tool hints, reasoning strip, leak cleaning, error recovery hints, DeepSeek guidance + v4-pro minimal-mode anchor.", load: steeringModule, config: steeringConfig },
|
|
171
|
+
{ name: "steering", category: "Model", describe: "Per-model-family steering (DeepSeek/GLM): first-tool hints, reasoning strip, leak cleaning, error recovery hints, DeepSeek guidance + v4-pro minimal-mode anchor.", load: steeringModule, config: steeringConfig, tools: ["think"] },
|
|
166
172
|
// ── Shell ──────────────────────────────────────────────────────────────
|
|
167
173
|
{ name: "rtk", category: "Shell", describe: "Route shell commands through RTK for token savings.", load: rtkModule },
|
|
168
174
|
// ── Plugins ────────────────────────────────────────────────────────────
|
|
@@ -305,8 +305,8 @@ describe("core module contract", () => {
|
|
|
305
305
|
it("nextDisabled excludes core modules; withEnableRow adds no row for them", async () => {
|
|
306
306
|
const { nextDisabled, withEnableRow } = await import("../../config/index.js");
|
|
307
307
|
// working = enabled set; nextDisabled lists the NOT-enabled non-core modules.
|
|
308
|
-
assert.deepEqual(nextDisabled(new Set(["munin"])), ["zai", "ponytail", "subagent", "plan", "a2a", "todo", "repair", "serena", "fff", "web", "rules", "steering", "rtk"]);
|
|
309
|
-
assert.deepEqual(nextDisabled(new Set(["router", "classifier", "ux", "munin", "usage", "ponytail", "subagent", "plan", "a2a", "todo", "repair", "serena", "fff", "web", "rules", "steering", "zai", "rtk", "config"])), [], "all-on → nothing disabled");
|
|
308
|
+
assert.deepEqual(nextDisabled(new Set(["munin"])), ["zai", "ponytail", "subagent", "plan", "a2a", "todo", "repair", "serena", "fff", "web", "rules", "gh", "steering", "rtk"]);
|
|
309
|
+
assert.deepEqual(nextDisabled(new Set(["router", "classifier", "ux", "munin", "usage", "ponytail", "subagent", "plan", "a2a", "todo", "repair", "serena", "fff", "web", "gh", "rules", "steering", "zai", "rtk", "config"])), [], "all-on → nothing disabled");
|
|
310
310
|
for (const core of ["composer", "advisor", "router", "classifier", "usage", "ux", "config"]) {
|
|
311
311
|
assert.ok(!nextDisabled(new Set()).includes(core), `core (${core}) is never disableable`);
|
|
312
312
|
}
|
|
@@ -258,6 +258,7 @@ export default function configModule(pi: ExtensionAPI, deps?: ModuleLoadDeps): v
|
|
|
258
258
|
repair: { section: "Repair", icon: "🔧" },
|
|
259
259
|
fff: { section: "FFF search" },
|
|
260
260
|
web: { section: "Web", icon: "🌍" },
|
|
261
|
+
gh: { section: "GitHub", icon: "🐙" },
|
|
261
262
|
a2a: { section: "A2A", icon: "📡" },
|
|
262
263
|
rtk: { section: "RTK" },
|
|
263
264
|
config: { section: "Ceulen config", icon: "🧩" },
|
|
@@ -34,7 +34,7 @@ function toolGroups(): PanelGroup[] {
|
|
|
34
34
|
describe("render smoke — ported modules' /config sections", () => {
|
|
35
35
|
it("renders Enable + per-tool rows inside the boxed frame with zero overflow", () => {
|
|
36
36
|
const groups = toolGroups();
|
|
37
|
-
assert.equal(groups.length,
|
|
37
|
+
assert.equal(groups.length, 15, "serena + fff + ux + munin + classifier + advisor + subagent + repair + plan + todo + web + rules + a2a + gh + steering·think (rtk has no tools)");
|
|
38
38
|
const m = new ConfigPanelModel(groups, theme, "Settings");
|
|
39
39
|
m.getHeight = () => 40;
|
|
40
40
|
for (const w of [110, 100, 80, 60]) {
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// gh module's /config contribution — Tools tab, GitHub section.
|
|
2
|
+
//
|
|
3
|
+
// One row: the run_watch budget. The module itself needs no settings (the gh
|
|
4
|
+
// binary + the user's gh auth own everything else). Saving writes the GLOBAL
|
|
5
|
+
// settings.json `gh` section; ops read it per call, so a save applies live.
|
|
6
|
+
|
|
7
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { row, type PanelGroup } from "../../lib/panel.js";
|
|
12
|
+
import type { ModuleConfig } from "../../lib/registry.js";
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_RUN_WATCH_TIMEOUT_SECS = 600;
|
|
15
|
+
|
|
16
|
+
function agentDir(): string {
|
|
17
|
+
return process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function readRunWatchTimeoutSecs(): number {
|
|
21
|
+
for (const file of [path.join(agentDir(), "settings.json")]) {
|
|
22
|
+
try {
|
|
23
|
+
if (!existsSync(file)) continue;
|
|
24
|
+
const section = JSON.parse(readFileSync(file, "utf8"))?.gh;
|
|
25
|
+
const v = section?.runWatchTimeoutSecs;
|
|
26
|
+
if (typeof v === "number" && Number.isFinite(v) && v > 0) return Math.floor(v);
|
|
27
|
+
} catch {
|
|
28
|
+
// corrupt layer → default
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return DEFAULT_RUN_WATCH_TIMEOUT_SECS;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function writeRunWatchTimeoutSecs(secs: number): string {
|
|
35
|
+
const file = path.join(agentDir(), "settings.json");
|
|
36
|
+
let settings: Record<string, unknown> = {};
|
|
37
|
+
if (existsSync(file)) {
|
|
38
|
+
try {
|
|
39
|
+
settings = JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
|
|
40
|
+
} catch {
|
|
41
|
+
throw new Error(`${file} is not valid JSON — fix or remove it before saving.`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
settings.gh = { ...(settings.gh as object | undefined ?? {}), runWatchTimeoutSecs: secs };
|
|
45
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
46
|
+
const tmp = file + ".tmp";
|
|
47
|
+
writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 });
|
|
48
|
+
renameSync(tmp, file);
|
|
49
|
+
return file;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function buildGhGroups(runWatchTimeoutSecs: number): PanelGroup[] {
|
|
53
|
+
return [
|
|
54
|
+
{
|
|
55
|
+
key: "gh",
|
|
56
|
+
label: "GitHub",
|
|
57
|
+
tab: "Tools",
|
|
58
|
+
icon: "🐙",
|
|
59
|
+
rows: [
|
|
60
|
+
row("gh.runWatchTimeoutSecs", "run_watch budget", "number", runWatchTimeoutSecs, (v) => {
|
|
61
|
+
runWatchTimeoutSecs = Math.max(10, Math.floor(Number(v)));
|
|
62
|
+
}, {
|
|
63
|
+
defaultValue: DEFAULT_RUN_WATCH_TIMEOUT_SECS,
|
|
64
|
+
description: "Seconds run_watch keeps polling a workflow run before reporting in-progress (capped at gh's 5-min command deadline).",
|
|
65
|
+
}),
|
|
66
|
+
],
|
|
67
|
+
},
|
|
68
|
+
];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** gh's ModuleConfig for the central /config panel. */
|
|
72
|
+
export function ghConfig(_pi: ExtensionAPI): ModuleConfig {
|
|
73
|
+
let working = readRunWatchTimeoutSecs();
|
|
74
|
+
return {
|
|
75
|
+
groups: () => buildGhGroups(working),
|
|
76
|
+
save: async (edited, ctx: ExtensionContext) => {
|
|
77
|
+
if (![...edited].some((k) => k.startsWith("gh."))) return;
|
|
78
|
+
const file = writeRunWatchTimeoutSecs(working);
|
|
79
|
+
ctx.ui.notify(`Saved gh.runWatchTimeoutSecs=${working} to ${file} (applies to the next run_watch call).`, "info");
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// gh module — one `github` tool over the `gh` CLI (zero npm deps).
|
|
2
|
+
//
|
|
3
|
+
// Ported from oh-my-pi's github tool (tools/gh*.ts + utils/github.ts), scoped
|
|
4
|
+
// to READ-ONLY ops: repo_view, file_read, pr_view, pr_diff, the five search
|
|
5
|
+
// flavors, run_watch. Mutating flows (pr_create/checkout/push) are deferred —
|
|
6
|
+
// bash `gh` covers them, and a read-only tool lets plan mode auto-allow it
|
|
7
|
+
// (plan-tools.ts READ_ONLY_TOOLS).
|
|
8
|
+
//
|
|
9
|
+
// Registration is fail-open on a missing `gh` binary: the module loads, the
|
|
10
|
+
// Enable row stays reachable, but no tool registers (OMP's createIf pattern)
|
|
11
|
+
// until gh is installed.
|
|
12
|
+
|
|
13
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
14
|
+
import { Type } from "typebox";
|
|
15
|
+
import { readDisabledTools } from "../../lib/tools.js";
|
|
16
|
+
import { ghAvailable, realGh } from "./lib/gh-cli.js";
|
|
17
|
+
import { executeOp } from "./lib/ops.js";
|
|
18
|
+
|
|
19
|
+
const OP_ENUM = [
|
|
20
|
+
"repo_view", "file_read", "pr_view", "pr_diff",
|
|
21
|
+
"search_issues", "search_prs", "search_code", "search_commits", "search_repos",
|
|
22
|
+
"run_watch",
|
|
23
|
+
] as const;
|
|
24
|
+
|
|
25
|
+
const DESCRIPTION = [
|
|
26
|
+
"Interact with GitHub via the `gh` CLI — repositories, files, pull requests, issues, and Actions.",
|
|
27
|
+
"Read-only operations:",
|
|
28
|
+
"- repo_view: repository metadata (default branch, stars, language, topics).",
|
|
29
|
+
"- file_read: a repository file's contents (text; binary → notice with URL) at an optional branch/ref.",
|
|
30
|
+
"- pr_view: PR metadata, body, files, reviews.",
|
|
31
|
+
"- pr_diff: a PR's unified diff.",
|
|
32
|
+
"- search_issues / search_prs / search_code / search_commits / search_repos: GitHub search with repo/org/user scoping and since/until date filters.",
|
|
33
|
+
"- run_watch: poll a workflow run until it completes; on failure, tails each failed job's logs (`tail` lines per job). Blocks up to ~5 min.",
|
|
34
|
+
"",
|
|
35
|
+
"Prefer these over bash `gh` invocations: repo/ref normalization handles `[host/]owner/repo` and URLs, prompts can never hang, output is capped and structured.",
|
|
36
|
+
].join("\n");
|
|
37
|
+
|
|
38
|
+
export default function ghModule(pi: ExtensionAPI): void {
|
|
39
|
+
// No `gh` binary → no tool; /config's Enable row still renders (the module
|
|
40
|
+
// stays registered in the loader) so installing gh + /reload activates it.
|
|
41
|
+
if (!ghAvailable()) return;
|
|
42
|
+
|
|
43
|
+
const disabled = readDisabledTools();
|
|
44
|
+
pi.registerTool({
|
|
45
|
+
name: "github",
|
|
46
|
+
label: "GitHub",
|
|
47
|
+
description: DESCRIPTION,
|
|
48
|
+
promptSnippet: "Interact with GitHub repos, files, PRs, issues, Actions via gh",
|
|
49
|
+
promptGuidelines: [
|
|
50
|
+
"Prefer search_code over web search for code in known GitHub repos; scope with repo:/org:/user: or the repo param.",
|
|
51
|
+
"run_watch blocks until the run finishes — pass `run` plus `tail` to bound log lines.",
|
|
52
|
+
"Read-only surface: create/push/checkout flows go through bash `gh` explicitly.",
|
|
53
|
+
],
|
|
54
|
+
parameters: Type.Object({
|
|
55
|
+
op: Type.Union(OP_ENUM.map((o) => Type.Literal(o)), { description: "github operation" }),
|
|
56
|
+
repo: Type.Optional(Type.String({ description: "[host/]owner/repo (or full URL where noted); defaults to the cwd checkout." })),
|
|
57
|
+
branch: Type.Optional(Type.String({ description: "branch / ref (file_read, repo_view)." })),
|
|
58
|
+
path: Type.Optional(Type.String({ description: "repository-relative file path (file_read)." })),
|
|
59
|
+
pr: Type.Optional(Type.String({ description: "pr number, url, or branch (pr_view, pr_diff)." })),
|
|
60
|
+
query: Type.Optional(Type.String({ description: "search query (search_* ops)." })),
|
|
61
|
+
since: Type.Optional(Type.String({ description: "lower-bound date filter: relative (3d, 2w) or ISO (search_*, not search_code)." })),
|
|
62
|
+
until: Type.Optional(Type.String({ description: "upper-bound date filter (search_*, not search_code)." })),
|
|
63
|
+
dateField: Type.Optional(Type.Union([Type.Literal("created"), Type.Literal("updated")], { description: "date field for since/until (default created)." })),
|
|
64
|
+
limit: Type.Optional(Type.Number({ description: "max results (search_*; default 10, max 50)." })),
|
|
65
|
+
run: Type.Optional(Type.String({ description: "actions run id or url (run_watch)." })),
|
|
66
|
+
tail: Type.Optional(Type.Number({ description: "failed-job log tail lines (run_watch; default 15, max 200)." })),
|
|
67
|
+
}),
|
|
68
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
69
|
+
const cwd = ctx?.cwd || process.cwd();
|
|
70
|
+
const p = params as Record<string, unknown>;
|
|
71
|
+
try {
|
|
72
|
+
const result = await executeOp(p.op as string, realGh, cwd, p as never, signal);
|
|
73
|
+
const content: Array<{ type: "text"; text: string } | { type: "image"; data: string; mimeType: string }> = [
|
|
74
|
+
{ type: "text", text: result.text },
|
|
75
|
+
];
|
|
76
|
+
if (result.image) {
|
|
77
|
+
content.push({ type: "image", data: result.image.data, mimeType: result.image.mimeType });
|
|
78
|
+
}
|
|
79
|
+
return { content, details: { op: p.op, repo: p.repo } };
|
|
80
|
+
} catch (err) {
|
|
81
|
+
return { content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }], isError: true, details: undefined };
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
defaultActive: !disabled.has("github"),
|
|
85
|
+
});
|
|
86
|
+
}
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
// ponytail: ported from oh-my-pi packages/coding-agent src/utils/github.ts +
|
|
2
|
+
// src/tools/gh-common.ts (lean) — the sanctioned `gh` CLI runner, repo-ref
|
|
3
|
+
// normalization, and shared formatters. Zero deps: everything spawns `gh`.
|
|
4
|
+
|
|
5
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
6
|
+
|
|
7
|
+
/** Deadline for `gh` subprocesses (OMP GH_COMMAND_TIMEOUT_MS). */
|
|
8
|
+
export const GH_TIMEOUT_MS = 5 * 60_000;
|
|
9
|
+
/** Captured-output cap — gh can emit enormous diffs/logs. */
|
|
10
|
+
export const GH_OUTPUT_LIMIT_BYTES = 8 * 1024 * 1024;
|
|
11
|
+
const GH_TRUNCATED_MARKER = "\n[gh subprocess output truncated after 8 MiB]\n";
|
|
12
|
+
|
|
13
|
+
/** OMP's non-interactive env: gh must never hang on a prompt or colorize piped
|
|
14
|
+
* output (a CLICOLOR_FORCE=1 in the user's shell breaks JSON parsing). */
|
|
15
|
+
export function ghEnv(): NodeJS.ProcessEnv {
|
|
16
|
+
return {
|
|
17
|
+
...process.env,
|
|
18
|
+
GIT_ASKPASS: "true",
|
|
19
|
+
GIT_EDITOR: "true",
|
|
20
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
21
|
+
LC_MESSAGES: "C",
|
|
22
|
+
GH_PROMPT_DISABLED: "1",
|
|
23
|
+
GH_PAGER: "cat",
|
|
24
|
+
PAGER: "cat",
|
|
25
|
+
// Force color OFF — CLICOLOR_FORCE wins over gh's own TTY detection.
|
|
26
|
+
NO_COLOR: "1",
|
|
27
|
+
CLICOLOR: "0",
|
|
28
|
+
CLICOLOR_FORCE: "0",
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface GhCommandOptions {
|
|
33
|
+
/** Caller passed an explicit repo; suppresses "run inside a checkout" hints. */
|
|
34
|
+
repoProvided?: boolean;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface GhCommandResult {
|
|
38
|
+
exitCode: number;
|
|
39
|
+
stdout: string;
|
|
40
|
+
stderr: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The seam every op goes through — swapped for a fake in tests. */
|
|
44
|
+
export interface GhRunner {
|
|
45
|
+
/** Run `gh`; does NOT throw on non-zero exit. */
|
|
46
|
+
run(cwd: string, args: string[], signal?: AbortSignal, options?: GhCommandOptions): Promise<GhCommandResult>;
|
|
47
|
+
/** Run `gh` expecting JSON on stdout; throws on non-zero exit / bad JSON. */
|
|
48
|
+
json<T = unknown>(cwd: string, args: string[], signal?: AbortSignal, options?: GhCommandOptions): Promise<T>;
|
|
49
|
+
/** Run `gh` expecting text on stdout; throws on non-zero exit. */
|
|
50
|
+
text(cwd: string, args: string[], signal?: AbortSignal, options?: GhCommandOptions): Promise<string>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let availableCache: boolean | undefined;
|
|
54
|
+
|
|
55
|
+
/** True when the `gh` CLI is installed (cached after the first probe). */
|
|
56
|
+
export function ghAvailable(): boolean {
|
|
57
|
+
if (availableCache === undefined) {
|
|
58
|
+
try {
|
|
59
|
+
const probe = spawnSync("gh", ["--version"], { stdio: "ignore", timeout: 10_000 });
|
|
60
|
+
availableCache = !probe.error && probe.status === 0;
|
|
61
|
+
} catch {
|
|
62
|
+
availableCache = false;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return availableCache;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The real runner over `node:child_process`. */
|
|
69
|
+
export const realGh: GhRunner = {
|
|
70
|
+
async run(cwd, args, signal, options) {
|
|
71
|
+
if (!ghAvailable()) {
|
|
72
|
+
throw new Error("GitHub CLI (gh) is not installed. Install it from https://cli.github.com/.");
|
|
73
|
+
}
|
|
74
|
+
const timeout = AbortSignal.timeout(GH_TIMEOUT_MS);
|
|
75
|
+
const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
76
|
+
return await new Promise<GhCommandResult>((resolveP, rejectP) => {
|
|
77
|
+
const child = spawn("gh", args, { cwd, env: ghEnv(), stdio: ["ignore", "pipe", "pipe"], signal: combined });
|
|
78
|
+
const out: Buffer[] = [];
|
|
79
|
+
const err: Buffer[] = [];
|
|
80
|
+
let outTotal = 0;
|
|
81
|
+
let errTotal = 0;
|
|
82
|
+
child.stdout!.on("data", (chunk: Buffer) => {
|
|
83
|
+
outTotal += chunk.length;
|
|
84
|
+
if (outTotal <= GH_OUTPUT_LIMIT_BYTES) out.push(chunk);
|
|
85
|
+
});
|
|
86
|
+
child.stderr!.on("data", (chunk: Buffer) => {
|
|
87
|
+
errTotal += chunk.length;
|
|
88
|
+
if (errTotal <= GH_OUTPUT_LIMIT_BYTES) err.push(chunk);
|
|
89
|
+
});
|
|
90
|
+
child.on("error", rejectP);
|
|
91
|
+
child.on("close", (code) => {
|
|
92
|
+
let stdout = Buffer.concat(out).toString("utf8");
|
|
93
|
+
if (outTotal > GH_OUTPUT_LIMIT_BYTES) stdout += GH_TRUNCATED_MARKER;
|
|
94
|
+
let stderr = Buffer.concat(err).toString("utf8");
|
|
95
|
+
if (errTotal > GH_OUTPUT_LIMIT_BYTES) stderr += GH_TRUNCATED_MARKER;
|
|
96
|
+
resolveP({ exitCode: code ?? -1, stdout, stderr });
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
},
|
|
100
|
+
|
|
101
|
+
async json(cwd, args, signal, options) {
|
|
102
|
+
const r = await this.run(cwd, args, signal, options);
|
|
103
|
+
if (r.exitCode !== 0) throw new Error(formatGhJsonFailure(args, r.stdout, r.stderr, options));
|
|
104
|
+
try {
|
|
105
|
+
return JSON.parse(r.stdout) as never;
|
|
106
|
+
} catch {
|
|
107
|
+
throw new Error(`gh ${args.join(" ")} returned invalid JSON: ${r.stdout.slice(0, 300)}`);
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
|
|
111
|
+
async text(cwd, args, signal, options) {
|
|
112
|
+
const r = await this.run(cwd, args, signal, options);
|
|
113
|
+
if (r.exitCode !== 0) throw new Error(formatGhFailure(args, r.stdout, r.stderr, options));
|
|
114
|
+
return r.stdout;
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
// ── Failure formatting (OMP utils/github.ts) ──
|
|
119
|
+
|
|
120
|
+
export function formatGhFailure(args: readonly string[], stdout: string, stderr: string, options?: GhCommandOptions): string {
|
|
121
|
+
const message = (stderr || stdout).trim();
|
|
122
|
+
if (message.includes("gh auth login") || message.includes("not logged into any GitHub hosts")) {
|
|
123
|
+
return "GitHub CLI is not authenticated. Run `gh auth login`.";
|
|
124
|
+
}
|
|
125
|
+
if (
|
|
126
|
+
!options?.repoProvided &&
|
|
127
|
+
(message.includes("not a git repository") ||
|
|
128
|
+
message.includes("no git remotes found") ||
|
|
129
|
+
message.includes("unable to determine current repository"))
|
|
130
|
+
) {
|
|
131
|
+
return "GitHub repository context is unavailable. Pass `repo` explicitly or run the tool inside a GitHub checkout.";
|
|
132
|
+
}
|
|
133
|
+
if (message) return message;
|
|
134
|
+
return `GitHub CLI command failed: gh ${args.join(" ")}`;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function describeGitHubApiError(value: unknown): string | undefined {
|
|
138
|
+
if (typeof value === "string") return value.trim() || undefined;
|
|
139
|
+
if (!value || typeof value !== "object") return undefined;
|
|
140
|
+
const rec = value as Record<string, unknown>;
|
|
141
|
+
if (typeof rec.message === "string") return rec.message.trim() || undefined;
|
|
142
|
+
const resource = typeof rec.resource === "string" ? rec.resource.trim() : "";
|
|
143
|
+
const field = typeof rec.field === "string" ? rec.field.trim() : "";
|
|
144
|
+
const target = [resource, field].filter(Boolean).join(".");
|
|
145
|
+
const code = typeof rec.code === "string" ? rec.code.trim() : "";
|
|
146
|
+
return `${target}: ${code}` || target || code || undefined;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function parseGitHubApiErrorMessages(stdout: string): string[] {
|
|
150
|
+
let payload: unknown;
|
|
151
|
+
try {
|
|
152
|
+
payload = JSON.parse(stdout);
|
|
153
|
+
} catch {
|
|
154
|
+
return [];
|
|
155
|
+
}
|
|
156
|
+
if (!payload || typeof payload !== "object") return [];
|
|
157
|
+
const rec = payload as Record<string, unknown>;
|
|
158
|
+
const messages = new Set<string>();
|
|
159
|
+
const summary = describeGitHubApiError(rec.message);
|
|
160
|
+
if (summary) messages.add(summary);
|
|
161
|
+
if (Array.isArray(rec.errors)) {
|
|
162
|
+
for (const error of rec.errors) {
|
|
163
|
+
const message = describeGitHubApiError(error);
|
|
164
|
+
if (message) messages.add(message);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return [...messages];
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function formatGhJsonFailure(args: readonly string[], stdout: string, stderr: string, options?: GhCommandOptions): string {
|
|
171
|
+
const rawMessage = (stderr || stdout).trim();
|
|
172
|
+
const fallback = formatGhFailure(args, stdout, stderr, options);
|
|
173
|
+
if (fallback !== rawMessage) return fallback;
|
|
174
|
+
const details = parseGitHubApiErrorMessages(stdout).filter((message) => !fallback.includes(message));
|
|
175
|
+
if (details.length === 0) return fallback;
|
|
176
|
+
return `${fallback}\nGitHub details:\n${details.map((m) => `- ${m}`).join("\n")}`;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ── Repo refs (OMP gh-common.ts) ──
|
|
180
|
+
|
|
181
|
+
const GITHUB_HOST = "github.com";
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* A repository in `gh`'s `[HOST/]OWNER/REPO` form. A ref naming no host is
|
|
185
|
+
* left for `gh` to resolve against GH_HOST (github.com by default).
|
|
186
|
+
*/
|
|
187
|
+
export interface GhRepoRef {
|
|
188
|
+
host?: string;
|
|
189
|
+
/** `OWNER/REPO`, never host-qualified. */
|
|
190
|
+
slug: string;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Split `[HOST/]OWNER/REPO`; anything with another shape is taken as a slug. */
|
|
194
|
+
export function parseRepoRef(repo: string): GhRepoRef {
|
|
195
|
+
const firstSlash = repo.indexOf("/");
|
|
196
|
+
if (firstSlash < 0) return { slug: repo };
|
|
197
|
+
const secondSlash = repo.indexOf("/", firstSlash + 1);
|
|
198
|
+
if (secondSlash < 0 || repo.includes("/", secondSlash + 1)) return { slug: repo };
|
|
199
|
+
return { host: repo.slice(0, firstSlash), slug: repo.slice(firstSlash + 1) };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Join a known host and `OWNER/REPO` into the form `--repo` accepts. */
|
|
203
|
+
export function formatRepoRef(host: string | undefined, slug: string): string {
|
|
204
|
+
return host ? `${host}/${slug}` : slug;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** `gh api` endpoint paths carry no host, so a ref names its host with a flag. */
|
|
208
|
+
export function ghApiHostArgs(ref: GhRepoRef): string[] {
|
|
209
|
+
return ref.host ? ["--hostname", ref.host] : [];
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export function defaultGhHost(): string {
|
|
213
|
+
return (process.env.GH_HOST || GITHUB_HOST).toLowerCase();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const REPO_URL_PATTERN = /^https?:\/\/([^/]+)\/([^/]+)\/([^/?#]+)/;
|
|
217
|
+
|
|
218
|
+
/** `https://HOST/OWNER/REPO` → repository identity, keeping non-default hosts. */
|
|
219
|
+
export function repoFromUrl(value: string | undefined): string | undefined {
|
|
220
|
+
const match = REPO_URL_PATTERN.exec(value?.trim() ?? "");
|
|
221
|
+
if (!match) return undefined;
|
|
222
|
+
const host = match[1].toLowerCase();
|
|
223
|
+
const slug = `${match[2]}/${match[3]}`;
|
|
224
|
+
return host === defaultGhHost() ? slug : formatRepoRef(host, slug);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** A full URL identifier already names host/repo/number; `--repo` would clash. */
|
|
228
|
+
export function appendRepoFlag(args: string[], repo: string | undefined, identifier?: string): void {
|
|
229
|
+
if (!repo || identifier?.startsWith("https://")) return;
|
|
230
|
+
args.push("--repo", repo);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function effectiveHost(ref: GhRepoRef): string {
|
|
234
|
+
return ref.host?.toLowerCase() ?? defaultGhHost();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Case-insensitive repo comparison over the instance each ref resolves to. */
|
|
238
|
+
export function githubRepoSlugEquals(left: string | undefined, right: string): boolean {
|
|
239
|
+
if (left === undefined) return false;
|
|
240
|
+
const leftRef = parseRepoRef(left);
|
|
241
|
+
const rightRef = parseRepoRef(right);
|
|
242
|
+
if (effectiveHost(leftRef) !== effectiveHost(rightRef)) return false;
|
|
243
|
+
return leftRef.slug.toLowerCase() === rightRef.slug.toLowerCase();
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// ── Default-repo resolution (memoized per cwd, OMP gh-common.ts) ──
|
|
247
|
+
|
|
248
|
+
const DEFAULT_REPO_RESOLVED = new Map<string, string>();
|
|
249
|
+
|
|
250
|
+
async function resolveRepoFromCwd(cwd: string, signal?: AbortSignal): Promise<string> {
|
|
251
|
+
const url = await realGh.text(cwd, ["repo", "view", "--json", "url", "-q", ".url"], signal);
|
|
252
|
+
const repo = repoFromUrl(url);
|
|
253
|
+
if (!repo) throw new Error(`GitHub CLI returned an unrecognized repository URL: ${url}`);
|
|
254
|
+
return repo;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Current checkout → `[HOST/]OWNER/REPO`, memoized per absolute cwd. */
|
|
258
|
+
export async function resolveDefaultRepoMemoized(cwd: string, signal?: AbortSignal): Promise<string> {
|
|
259
|
+
const key = cwd;
|
|
260
|
+
const ready = DEFAULT_REPO_RESOLVED.get(key);
|
|
261
|
+
if (ready) return ready;
|
|
262
|
+
const value = await resolveRepoFromCwd(key, signal);
|
|
263
|
+
DEFAULT_REPO_RESOLVED.set(key, value);
|
|
264
|
+
return value;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Best-effort memoized cwd → repo; failures swallow to undefined. */
|
|
268
|
+
export async function tryResolveCurrentRepo(cwd: string, signal?: AbortSignal): Promise<string | undefined> {
|
|
269
|
+
try {
|
|
270
|
+
return await resolveDefaultRepoMemoized(cwd, signal);
|
|
271
|
+
} catch {
|
|
272
|
+
return undefined;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Resolve the effective repo for an op: explicit `repo` param wins, then a
|
|
278
|
+
* run/PR URL's embedded repo, then the cwd checkout. A mismatch between an
|
|
279
|
+
* explicit repo and the URL's repo is an error (OMP resolveGitHubRepo).
|
|
280
|
+
*/
|
|
281
|
+
export async function resolveGitHubRepo(cwd: string, repo: string | undefined, urlRepo: string | undefined, signal?: AbortSignal): Promise<string> {
|
|
282
|
+
if (repo && urlRepo && !githubRepoSlugEquals(repo, urlRepo)) {
|
|
283
|
+
throw new Error("URL repository does not match the provided repo");
|
|
284
|
+
}
|
|
285
|
+
if (repo) return repo;
|
|
286
|
+
if (urlRepo) return urlRepo;
|
|
287
|
+
try {
|
|
288
|
+
return await resolveDefaultRepoMemoized(cwd, signal);
|
|
289
|
+
} catch (err) {
|
|
290
|
+
throw new Error(
|
|
291
|
+
`${err instanceof Error ? err.message : String(err)}\nGitHub repository context is unavailable. Pass \`repo\` explicitly or run the tool inside a GitHub checkout.`,
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// ── Shared text formatters (OMP gh-common.ts) ──
|
|
297
|
+
|
|
298
|
+
export function normalizeText(value: string | null | undefined): string {
|
|
299
|
+
return (value ?? "").replaceAll("\r\n", "\n").replaceAll("\r", "\n").replaceAll("\t", " ").trim();
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export function normalizeBlock(value: string | null | undefined): string {
|
|
303
|
+
return (value ?? "").replaceAll("\r\n", "\n").replaceAll("\r", "\n").replaceAll("\t", " ").trimEnd();
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export function normalizeOptionalString(value: unknown): string | undefined {
|
|
307
|
+
const normalized = typeof value === "string" ? value.trim() : "";
|
|
308
|
+
return normalized || undefined;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
export function requireNonEmpty(value: unknown, label: string): string {
|
|
312
|
+
const normalized = normalizeOptionalString(value);
|
|
313
|
+
if (!normalized) throw new Error(`${label} must not be empty`);
|
|
314
|
+
return normalized;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Push `Label: value` only when value is non-empty (OMP pushLine). */
|
|
318
|
+
export function pushLine(lines: string[], label: string, value: string | number | boolean | undefined | null): void {
|
|
319
|
+
if (value === undefined || value === null || value === "") return;
|
|
320
|
+
lines.push(`${label}: ${value}`);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export function formatShortSha(sha: string | undefined | null): string | undefined {
|
|
324
|
+
return sha ? sha.slice(0, 8) : undefined;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export function formatAuthor(author: { login?: string; name?: string } | null | undefined): string | undefined {
|
|
328
|
+
if (!author) return undefined;
|
|
329
|
+
if (author.login) return `@${author.login}`;
|
|
330
|
+
if (author.name) return author.name;
|
|
331
|
+
return undefined;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export function formatLabels(labels: { name?: string }[] | undefined): string | undefined {
|
|
335
|
+
const names = labels?.map((l) => l.name).filter((n): n is string => Boolean(n)) ?? [];
|
|
336
|
+
return names.length > 0 ? names.join(", ") : undefined;
|
|
337
|
+
}
|