dsh-hiss-plugins 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js ADDED
@@ -0,0 +1,374 @@
1
+ /**
2
+ * The bundle's browser half: one management tab in the Plugins page, with a switch per feature.
3
+ *
4
+ * Hand-written lazy-CJS bundle, no build step: executing this file only registers a factory, and the
5
+ * module body below runs when the client module system materializes the bundle. Only `react` and
6
+ * `react/jsx-runtime` come from the client baseline, so every control is plain markup styled with
7
+ * host theme tokens — a token rename degrades the look, it never blanks the tab.
8
+ *
9
+ * The tab owns no state: it reads the running profile through `pluginManager/listPlugins` and
10
+ * re-reads after every switch, so what the page shows is always what the host holds.
11
+ *
12
+ * @module dsh-hiss-plugins/client
13
+ */
14
+ window.__ModuleLoader__.load({
15
+ id: "dsh-hiss-plugins",
16
+ factory: (require) => {
17
+ var module = { exports: {} };
18
+ var exports = module.exports;
19
+ const React = require("react");
20
+ const { jsx, jsxs } = require("react/jsx-runtime");
21
+
22
+ /** Dictionary namespace owned by this plugin. */
23
+ const NS = "hissPlugins";
24
+ /** The one package whose rows this tab manages. */
25
+ const PACKAGE_ID = "dsh-hiss-plugins";
26
+ /**
27
+ * The features this bundle carries, in the order the tab lists them.
28
+ * Each row is a top-level Loader row, which is what makes its switch addressable at all.
29
+ */
30
+ const FEATURES = [
31
+ { key: "colgrep", moduleName: `${PACKAGE_ID}/colgrep`, description: "featureColgrepDescription" },
32
+ { key: "codegraph", moduleName: `${PACKAGE_ID}/codegraph`, description: "featureCodegraphDescription" },
33
+ { key: "project-mcp", moduleName: `${PACKAGE_ID}/project-mcp`, description: "featureProjectMcpDescription" },
34
+ { key: "gitbash", moduleName: `${PACKAGE_ID}/gitbash`, description: "featureGitbashDescription" },
35
+ ];
36
+ /** The same features keyed by the name a card shows. */
37
+ const FEATURE_BY_KEY = new Map(FEATURES.map((feature) => [feature.key, feature]));
38
+
39
+ /** Host theme tokens keep the tab inside the page's look without a stylesheet. */
40
+ const SECTION_STYLE = { display: "flex", flexDirection: "column", gap: "12px", maxWidth: "760px", color: "var(--dsw-alias-label-primary)" };
41
+ const LIST_STYLE = { display: "flex", flexDirection: "column", gap: "10px", margin: 0, padding: 0, listStyle: "none" };
42
+ const CARD_STYLE = { display: "flex", alignItems: "center", gap: "14px", padding: "12px 14px", border: "0.5px solid var(--dsw-alias-settings-card-stroke, var(--dsw-alias-border-l3))", borderRadius: "12px", background: "var(--dsw-alias-settings-card-fill, transparent)" };
43
+ const TEXT_STYLE = { display: "flex", flexDirection: "column", gap: "2px", flex: "1 1 auto", minWidth: 0 };
44
+ const DESCRIPTION_STYLE = { color: "var(--dsw-alias-label-tertiary)", fontSize: "13px", lineHeight: "20px" };
45
+ const SWITCH_STYLE = { display: "inline-flex", alignItems: "center", gap: "6px", color: "var(--dsw-alias-label-tertiary)", fontSize: "13px", whiteSpace: "nowrap" };
46
+ const STATUS_STYLE = { margin: 0, color: "var(--dsw-alias-label-tertiary)", fontSize: "13px", lineHeight: "20px" };
47
+ const FAILURE_STYLE = { display: "flex", alignItems: "center", gap: "10px" };
48
+ const NOTICE_STYLE = { margin: 0, color: "var(--dsw-alias-label-secondary, var(--dsw-alias-label-tertiary))", fontSize: "13px", lineHeight: "20px" };
49
+ const REASON_STYLE = { color: "var(--dsw-alias-label-tertiary)", fontSize: "12px", lineHeight: "18px", maxWidth: "220px" };
50
+ const BUTTON_STYLE = { border: "0.5px solid var(--dsw-alias-border-l3)", borderRadius: "6px", color: "var(--dsw-alias-label-primary)", font: "inherit", cursor: "pointer", background: "none", padding: "4px 10px" };
51
+
52
+ /**
53
+ * Copy for the management tab; the `locale/*.json` files carry the same entries, where the
54
+ * `meta` object is the package display text the Plugins page reads.
55
+ */
56
+ /** Simplified Chinese dictionary, the key source of truth. */
57
+ const zh = {
58
+ loading: "正在读取插件…",
59
+ error: "暂时无法读取插件:{error}",
60
+ retry: "重试",
61
+ empty: "本包没有声明任何插件行。",
62
+ enabledTag: "已启用",
63
+ disabledTag: "已停用",
64
+ toggleAria: "切换 {name}",
65
+ toggleFailed: "切换 {name} 失败:{error}",
66
+ restartRequired: "{name} 的改动将在重启 DSH 后生效。",
67
+ reasonManagementRequired: "该插件由 DSH 自身管理,无法在这个页面切换。",
68
+ reasonUnaddressable: "无法在 profile 中定位该插件的行,请手动修改 cordis.patch.yml。",
69
+ reasonUnknown: "该插件无法在这个页面切换({code})。",
70
+ featureColgrepDescription: "语义代码检索工具",
71
+ featureCodegraphDescription: "代码图 MCP 工具",
72
+ featureProjectMcpDescription: "按会话挂载项目 .mcp.json",
73
+ featureGitbashDescription: "Windows 上的 Git Bash shell",
74
+ };
75
+ /** English dictionary checked against the Chinese key set. */
76
+ const en = {
77
+ loading: "Reading plugins…",
78
+ error: "Plugins are unavailable: {error}",
79
+ retry: "Retry",
80
+ empty: "This bundle declares no plugin rows.",
81
+ enabledTag: "Enabled",
82
+ disabledTag: "Disabled",
83
+ toggleAria: "Toggle {name}",
84
+ toggleFailed: "Switching {name} failed: {error}",
85
+ restartRequired: "The change to {name} takes effect after DSH restarts.",
86
+ reasonManagementRequired: "DSH manages this plugin itself, so it cannot be switched from this page.",
87
+ reasonUnaddressable: "This plugin's row cannot be addressed in the profile; edit cordis.patch.yml by hand.",
88
+ reasonUnknown: "This plugin cannot be switched from this page ({code}).",
89
+ featureColgrepDescription: "semantic code search tool",
90
+ featureCodegraphDescription: "CodeGraph MCP tools",
91
+ featureProjectMcpDescription: "mounts the project's .mcp.json per session",
92
+ featureGitbashDescription: "Git Bash shell on Windows",
93
+ };
94
+
95
+ /** Read one thrown value as text. */
96
+ function messageOf(error) {
97
+ return error instanceof Error ? error.message : String(error);
98
+ }
99
+
100
+ /**
101
+ * The dictionary key a manager refusal code reads as.
102
+ * @param code - the manager's failure code.
103
+ * @returns the key that explains it, or undefined for a code the page has no sentence for.
104
+ */
105
+ function refusalKey(code) {
106
+ if (code === "management-required") return "reasonManagementRequired";
107
+ if (code === "unaddressable") return "reasonUnaddressable";
108
+ return undefined;
109
+ }
110
+
111
+ /**
112
+ * Readable copy for one manager failure: the dictionary's sentence for a code the page
113
+ * explains, otherwise the code and the manager's own diagnostic.
114
+ * @param t - page dictionary lookup.
115
+ * @param code - the manager's failure code, when it named one.
116
+ * @param message - the manager's diagnostic, when it carried one.
117
+ * @returns the sentence the page shows.
118
+ */
119
+ function failureText(t, code, message) {
120
+ const key = refusalKey(code);
121
+ if (key !== undefined) return t(key);
122
+ const diagnostic = message ?? "";
123
+ if (code === undefined || code === "") return diagnostic;
124
+ return diagnostic === "" || diagnostic === code ? code : `${code}: ${diagnostic}`;
125
+ }
126
+
127
+ /**
128
+ * Turn a refused answer into the Error the page shows.
129
+ * The message is readable copy; the raw code stays on the Error for callers that branch on it.
130
+ * @param t - page dictionary lookup.
131
+ * @param code - the manager's failure code, when it named one.
132
+ * @param message - the manager's diagnostic, when it carried one.
133
+ * @returns the Error to reject with.
134
+ */
135
+ function refusalError(t, code, message) {
136
+ const error = new Error(failureText(t, code, message));
137
+ if (code !== undefined) error.code = code;
138
+ return error;
139
+ }
140
+
141
+ /**
142
+ * Why a read-only row cannot move here.
143
+ * @param t - page dictionary lookup.
144
+ * @param code - the row's `readOnlyReason`.
145
+ * @returns the sentence the card shows.
146
+ */
147
+ function reasonText(t, code) {
148
+ const key = refusalKey(code);
149
+ return key === undefined ? t("reasonUnknown", { code: String(code) }) : t(key);
150
+ }
151
+
152
+ /**
153
+ * Project the manager's roster onto this package's features.
154
+ * @param entries - rows `pluginManager/listPlugins` reported.
155
+ * @returns one row per feature this package contributes, in the tab's fixed order, with
156
+ * readonly rows kept but marked untoggleable.
157
+ */
158
+ function project(entries) {
159
+ const rows = [];
160
+ for (const feature of FEATURES) {
161
+ const entry = entries.find((item) => item.moduleName === feature.moduleName);
162
+ if (entry === undefined) continue;
163
+ rows.push({
164
+ entryId: entry.entryId,
165
+ key: feature.key,
166
+ enabled: entry.enabled === true,
167
+ toggleable: entry.readOnlyReason === undefined,
168
+ reason: entry.readOnlyReason,
169
+ });
170
+ }
171
+ return rows;
172
+ }
173
+
174
+ /**
175
+ * Render one feature card: its name and one-line copy, its switch, and — for a row the
176
+ * profile cannot address — the sentence that says why the switch stays out of reach.
177
+ * @param row - one projected row.
178
+ * @param view - the tab's lookups, its pending entry and its toggle.
179
+ * @returns the card element.
180
+ */
181
+ function featureCard(row, view) {
182
+ const { t, pending, onToggle } = view;
183
+ const reason = row.toggleable ? undefined : reasonText(t, row.reason);
184
+ return jsxs("li", {
185
+ style: CARD_STYLE,
186
+ "data-feature": row.key,
187
+ children: [
188
+ jsxs("span", { style: TEXT_STYLE, children: [
189
+ jsx("strong", { children: row.key }),
190
+ jsx("span", { style: DESCRIPTION_STYLE, children: t(FEATURE_BY_KEY.get(row.key).description) }),
191
+ ] }),
192
+ jsx("label", { style: SWITCH_STYLE, children: [
193
+ jsx("input", {
194
+ type: "checkbox",
195
+ checked: row.enabled,
196
+ disabled: !row.toggleable || pending,
197
+ "aria-label": t("toggleAria", { name: row.key }),
198
+ onChange: (event) => {
199
+ onToggle(row, event.currentTarget.checked);
200
+ },
201
+ }),
202
+ jsx("span", { children: row.enabled ? t("enabledTag") : t("disabledTag") }),
203
+ ] }),
204
+ reason === undefined ? null : jsx("span", { style: REASON_STYLE, children: reason }),
205
+ ],
206
+ }, row.entryId);
207
+ }
208
+
209
+ /** The Plugins-page tab: one card per feature row, each with its own switch. */
210
+ function HissPluginsTab(props) {
211
+ const list = props.list;
212
+ const setEnabled = props.setEnabled;
213
+ const t = typeof props.t === "function" ? props.t : (key) => key;
214
+ const [request, setRequest] = React.useState(0);
215
+ const [state, setState] = React.useState({ status: "loading" });
216
+ const [busy, setBusy] = React.useState(null);
217
+ const [notice, setNotice] = React.useState(null);
218
+ React.useEffect(() => {
219
+ let current = true;
220
+ Promise.resolve().then(() => list()).then((rows) => {
221
+ if (current) setState({
222
+ status: "ready",
223
+ rows
224
+ });
225
+ }, (error) => {
226
+ if (current) setState({
227
+ status: "error",
228
+ message: messageOf(error)
229
+ });
230
+ });
231
+ return () => {
232
+ current = false;
233
+ };
234
+ }, [
235
+ list,
236
+ request
237
+ ]);
238
+ /** Read the host again: the page keeps no enablement of its own. */
239
+ const refresh = () => {
240
+ setRequest((value) => value + 1);
241
+ };
242
+ /**
243
+ * Persist one switch through the manager, then re-read the host so the card shows what
244
+ * the profile now holds — a refused write included.
245
+ * @param row - the row the switch belongs to.
246
+ * @param enabled - the switch's new position.
247
+ * @returns the settled request, for callers that await it.
248
+ */
249
+ const toggle = (row, enabled) => Promise.resolve().then(() => setEnabled(row.entryId, enabled)).then((application) => {
250
+ if (application === "restart-required") setNotice({
251
+ kind: "restart",
252
+ key: row.key
253
+ });
254
+ }, (error) => {
255
+ setNotice({
256
+ kind: "failure",
257
+ key: row.key,
258
+ message: messageOf(error)
259
+ });
260
+ }).finally(() => {
261
+ setBusy(null);
262
+ refresh();
263
+ });
264
+ const view = {
265
+ t,
266
+ onToggle: toggle
267
+ };
268
+ const noticeText = notice === null ? undefined : notice.kind === "restart" ? t("restartRequired", { name: notice.key }) : t("toggleFailed", {
269
+ name: notice.key,
270
+ error: notice.message
271
+ });
272
+ return jsxs("section", {
273
+ className: "hissPlugins",
274
+ style: SECTION_STYLE,
275
+ "aria-busy": state.status === "loading",
276
+ children: [
277
+ state.status === "loading" ? jsx("p", {
278
+ role: "status",
279
+ style: STATUS_STYLE,
280
+ children: t("loading")
281
+ }) : null,
282
+ state.status === "error" ? jsxs("div", {
283
+ role: "alert",
284
+ style: FAILURE_STYLE,
285
+ children: [jsx("p", {
286
+ style: STATUS_STYLE,
287
+ children: t("error", { error: state.message })
288
+ }), jsx("button", {
289
+ type: "button",
290
+ style: BUTTON_STYLE,
291
+ onClick: refresh,
292
+ children: t("retry")
293
+ })]
294
+ }) : null,
295
+ state.status === "ready" && state.rows.length === 0 ? jsx("p", {
296
+ style: STATUS_STYLE,
297
+ children: t("empty")
298
+ }) : null,
299
+ state.status === "ready" && state.rows.length > 0 ? jsx("ul", {
300
+ style: LIST_STYLE,
301
+ children: state.rows.map((row) => featureCard(row, {
302
+ ...view,
303
+ pending: busy === row.entryId
304
+ }))
305
+ }) : null,
306
+ noticeText === undefined ? null : jsx("p", {
307
+ role: "status",
308
+ style: NOTICE_STYLE,
309
+ children: noticeText
310
+ }),
311
+ ],
312
+ });
313
+ }
314
+
315
+ /** Services required by the tab registration and its Remote answers. */
316
+ const inject = [
317
+ "slots",
318
+ "locale",
319
+ "remote",
320
+ "remote.pluginManager"
321
+ ];
322
+
323
+ /**
324
+ * Contribute the management tab to the Plugins page.
325
+ * @param ctx - the browser plugin context.
326
+ */
327
+ function apply(ctx) {
328
+ ctx.effect(() => ctx.locale.register(NS, {
329
+ zh,
330
+ en
331
+ }), "hiss-plugins: dictionaries");
332
+ const t = ctx.locale.bind(NS);
333
+ /**
334
+ * Read the running profile's rows.
335
+ * @returns one projected row per feature this package contributes.
336
+ */
337
+ const list = async () => {
338
+ const answer = await ctx.remote.pluginManager.listPlugins();
339
+ if (!answer.ok) throw new Error(`pluginManager.listPlugins failed: ${answer.error.code}: ${answer.error.message}`);
340
+ return project(answer.value);
341
+ };
342
+ /**
343
+ * Persist one row's enablement.
344
+ * @param entryId - the Loader entry identity `list()` reported.
345
+ * @param enabled - whether the row should run.
346
+ * @returns the manager's application outcome; `restart-required` means the next start lands it.
347
+ */
348
+ const setEnabled = async (entryId, enabled) => {
349
+ const answer = await ctx.remote.pluginManager.setPluginEnabled(entryId, enabled);
350
+ if (!answer.ok) throw refusalError(t, answer.error.code, answer.error.message);
351
+ const result = answer.value;
352
+ if (result.application === "failed") throw refusalError(t, result.error?.code, result.error?.diagnostic);
353
+ return result.application;
354
+ };
355
+ ctx.slots.inject("plugins.tab", () => ctx.slots.register({
356
+ name: "plugins.tab",
357
+ id: "dsh-hiss-plugins",
358
+ order: 20,
359
+ label: () => "dsh-hiss-plugins",
360
+ locale: NS,
361
+ inject: () => ({
362
+ list,
363
+ setEnabled,
364
+ t,
365
+ features: FEATURES.map((feature) => feature.key)
366
+ })
367
+ }, HissPluginsTab));
368
+ }
369
+
370
+ exports.apply = apply;
371
+ exports.inject = inject;
372
+ return module.exports;
373
+ },
374
+ });
@@ -0,0 +1,62 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { apply as mcpClientApply, inject as mcpClientInject } from "@deepseek-ai/dsh-mcp-client";
4
+
5
+ export const name = "codegraph";
6
+ export const inject = ["systemPrompt"];
7
+
8
+ const GUIDANCE = [
9
+ "CodeGraph (semantic code intelligence) is available through the `mcp__codegraph__codegraph_explore` tool. ",
10
+ "For structural questions about the codebase — how a component works, how X reaches Y, the blast radius of a change — ",
11
+ "call `mcp__codegraph__codegraph_explore` directly instead of grepping or reading files one by one; ",
12
+ "it returns the relevant symbols' source, call paths, and impact in one call. ",
13
+ "Always pass `projectPath` as the workspace directory you are working in (or a subdirectory that has a `.codegraph/` index). ",
14
+ "If the tool reports no index, tell the user to run `codegraph init` in that project first. ",
15
+ "If the `mcp__codegraph__*` tool is not listed, the codegraph CLI is not installed or failed to start — check the DSH host logs.",
16
+ ].join("");
17
+
18
+ // This workspace has no index. The MCP server exposes only `codegraph_explore`,
19
+ // so nothing can build the index but the agent itself.
20
+ const MISSING_INDEX = " This workspace has no index yet — run `codegraph init -y` here once before exploring, then retry.";
21
+
22
+ export function guidanceFor(cwd) {
23
+ const hint = cwd && !existsSync(join(cwd, ".codegraph")) ? MISSING_INDEX : "";
24
+ return `${GUIDANCE} Current workspace: ${cwd}; pass it as \`projectPath\`.${hint}`;
25
+ }
26
+
27
+ /**
28
+ * Stdio config for the CodeGraph MCP server. `command` resolves `codegraph`
29
+ * from the DSH host process's PATH (installed globally), and `cwd` is only the
30
+ * server's default project — the model always passes `projectPath` to target
31
+ * the actual workspace.
32
+ *
33
+ * @param {string} [cwd] default project directory for the spawned server.
34
+ * @returns {import("@deepseek-ai/dsh-mcp-client").StdioConfig}
35
+ */
36
+ export function codegraphConfig(cwd = process.cwd()) {
37
+ return {
38
+ transport: "stdio",
39
+ serverName: "codegraph",
40
+ command: "codegraph",
41
+ args: ["serve", "--mcp"],
42
+ env: {},
43
+ cwd,
44
+ toolCallTimeoutMs: 120000,
45
+ failOnStartupError: false,
46
+ };
47
+ }
48
+
49
+ /**
50
+ * DSH plugin entry point. Loads the DSH MCP client bridge for the CodeGraph
51
+ * server (registering `mcp__codegraph__*` tools globally) and injects usage
52
+ * guidance whose text carries the current session's workspace path, so agents
53
+ * prefer it and pass the right `projectPath`.
54
+ */
55
+ export function apply(ctx) {
56
+ ctx.plugin({ inject: mcpClientInject, apply: mcpClientApply }, codegraphConfig());
57
+ ctx.systemPrompt.section({
58
+ name: "codegraph:guidance",
59
+ order: 100,
60
+ text: (context) => guidanceFor(context.scope?.session?.header?.cwd ?? process.cwd()),
61
+ });
62
+ }
@@ -0,0 +1,196 @@
1
+ import { resolve } from "node:path";
2
+ import { defineTool } from "@deepseek-ai/dsh-tools";
3
+
4
+ export const name = "colgrep";
5
+ export const inject = ["tools", "shell", "sandboxPolicy", "systemPrompt"];
6
+
7
+ const LONG_PATH_PREFIX = String.fromCharCode(92, 92, 63, 92); // "\\?\"
8
+
9
+ const TOOL_DESCRIPTION = `Semantic code search over the workspace using the local colgrep CLI (ColBERT multi-vector search). Finds code by meaning, not exact text. Use a natural-language \`query\` such as "error handling for database connections". Defaults to \`search\`; search auto-indexes, so the first run in a project builds the index and is slower. Use \`command:"status"\` to inspect the index, \`command:"init"\` to (re)build it explicitly, and \`no_update:true\` for a fast search over an existing index. Pass \`root\` to search a project other than the workspace, and \`path\` to narrow the search within it. Use \`pattern\` to pre-filter by regex, \`include\` to limit file types (e.g. "*.rs"), and \`code_only\` to skip text/config files.`;
10
+
11
+ const GUIDANCE = [
12
+ "Semantic code search is available through the `colgrep` tool. ",
13
+ "Reach for it when you want code by meaning and cannot name the exact identifier — grep is for text you can already spell out. ",
14
+ "It auto-indexes on demand, so the first search in a project is slower; use `pattern` for a regex pre-filter that ranks semantically after. ",
15
+ "Pass `root` to search a project other than the workspace. ",
16
+ ].join("");
17
+
18
+ /**
19
+ * Usage guidance carrying the current workspace, so the agent passes the right
20
+ * default root.
21
+ *
22
+ * @param {string} cwd the session workspace path.
23
+ * @returns {string} prompt text for the colgrep guidance section.
24
+ */
25
+ export function guidanceFor(cwd) {
26
+ return `${GUIDANCE} Current workspace: ${cwd}; the default root.`;
27
+ }
28
+
29
+ export function stripPathPrefix(path) {
30
+ const value = String(path);
31
+ return value.startsWith(LONG_PATH_PREFIX) ? value.slice(4) : value;
32
+ }
33
+
34
+ export function quoteArg(value) {
35
+ return "'" + String(value).replace(/'/g, "''") + "'";
36
+ }
37
+
38
+ export function buildArgs(args) {
39
+ const command = args.command || "search";
40
+ const argv = ["colgrep"];
41
+ if (command === "search") {
42
+ if (typeof args.query !== "string" || args.query.trim() === "") {
43
+ throw new Error("query must be a non-empty string");
44
+ }
45
+ argv.push("--json", "--color", "never", "-y");
46
+ if (args.no_update) argv.push("--no-update");
47
+ argv.push("-k", String(args.top_k ? Number(args.top_k) : 15));
48
+ if (args.pattern) argv.push("-e", args.pattern);
49
+ if (args.include) argv.push("--include", args.include);
50
+ if (args.code_only) argv.push("--code-only");
51
+ argv.push(String(args.query || ""));
52
+ if (args.root) argv.push(String(args.root));
53
+ if (args.path) argv.push(args.path);
54
+ } else if (command === "init") {
55
+ argv.push("init", "-y");
56
+ if (args.root) argv.push(String(args.root));
57
+ if (args.path) argv.push(args.path);
58
+ } else if (command === "status") {
59
+ argv.push("status");
60
+ } else if (command === "clear") {
61
+ argv.push("clear");
62
+ } else {
63
+ throw new Error("command must be one of: search, init, status, clear");
64
+ }
65
+ return argv;
66
+ }
67
+
68
+ export function normalizeResults(parsed) {
69
+ return parsed.map((item) => {
70
+ const unit = item && item.unit ? item.unit : {};
71
+ return {
72
+ file: stripPathPrefix(unit.file),
73
+ name: unit.name || "",
74
+ qualified_name: unit.qualified_name || "",
75
+ line: unit.line,
76
+ end_line: unit.end_line,
77
+ language: unit.language || "",
78
+ unit_type: unit.unit_type || "",
79
+ signature: unit.signature || "",
80
+ score: item ? item.score : null,
81
+ };
82
+ });
83
+ }
84
+
85
+ export function renderOutput(value) {
86
+ if (!value || typeof value !== "object") return String(value);
87
+ const lines = [];
88
+ if (value.command === "search" && Array.isArray(value.results)) {
89
+ lines.push(`colgrep: ${value.results.length} result(s) for ${JSON.stringify(value.query)}`);
90
+ value.results.forEach((result, index) => {
91
+ const file = result.file || result.qualified_name || "?";
92
+ const location = typeof result.line === "number" && typeof result.end_line === "number"
93
+ ? `:${result.line}-${result.end_line}`
94
+ : "";
95
+ const meta = [result.language, result.unit_type, result.name].filter(Boolean).join(", ");
96
+ const score = typeof result.score === "number" ? `score ${result.score.toFixed(2)}` : "";
97
+ lines.push("");
98
+ lines.push(`${index + 1}. ${file}${location}${meta ? ` [${meta}]` : ""}${score ? ` (${score})` : ""}`);
99
+ if (result.signature) {
100
+ lines.push(` ${String(result.signature).split("\n")[0].slice(0, 200)}`);
101
+ }
102
+ });
103
+ } else if (value.command === "search") {
104
+ lines.push(value.ok ? "colgrep search returned unparseable output (ok=true)" : "colgrep search failed (ok=false)");
105
+ if (value.stderr) lines.push(`[stderr]\n${value.stderr}`);
106
+ else if (value.stdout) lines.push(`[stdout]\n${value.stdout}`);
107
+ } else {
108
+ lines.push(`colgrep ${value.command} (exit ${value.exitCode})`);
109
+ if (value.stdout) lines.push(value.stdout);
110
+ if (!value.ok && value.stderr) lines.push(`[stderr]\n${value.stderr}`);
111
+ }
112
+ if (value.timedOut) lines.push("[timed out]");
113
+ if (value.aborted) lines.push("[aborted]");
114
+ return lines.join("\n");
115
+ }
116
+
117
+ export function apply(ctx) {
118
+ ctx.systemPrompt.section({
119
+ name: "colgrep:guidance",
120
+ order: 100,
121
+ text: (context) => guidanceFor(context.scope?.session?.header?.cwd ?? process.cwd()),
122
+ });
123
+
124
+ ctx.tools.register(defineTool({
125
+ name: "colgrep",
126
+ description: TOOL_DESCRIPTION,
127
+ parameters: {
128
+ query: { type: "string", description: "Natural-language query (used by search).", required: true },
129
+ command: { type: "string", enum: ["search", "init", "status", "clear"], description: "Operation. search (default) finds code; init builds/updates the index; status reports index state; clear removes the index." },
130
+ root: { type: "string", description: "Project directory to search or index (default: the workspace root). Absolute or relative to the workspace." },
131
+ path: { type: "string", description: "File or directory of `root` to search (default: the whole root). colgrep searches this target and falls back to the project index, so it is a focus, not a hard filter — narrow with `include` or `pattern` instead." },
132
+ top_k: { type: "integer", description: "Number of results to return (-k). Default 15." },
133
+ pattern: { type: "string", description: "Regex pre-filter (-e): grep first, then rank semantically (hybrid)." },
134
+ include: { type: "string", description: "Only search files matching this glob (--include), e.g. \"*.rs\"." },
135
+ code_only: { type: "boolean", description: "Only search code files; skip text/config files such as md/txt/yaml/json (--code-only)." },
136
+ no_update: { type: "boolean", description: "Skip automatic index update and search the existing index as-is (--no-update)." },
137
+ },
138
+ output: {
139
+ schema: { type: "json" },
140
+ render(_args, value) {
141
+ return [{ type: "text", text: renderOutput(value) }];
142
+ },
143
+ },
144
+ async execute(args, exec) {
145
+ const policy = ctx.sandboxPolicy.resolve({ session: exec.agent && exec.agent.session });
146
+ const root = policy && typeof policy.workspaceRoot === "string" ? policy.workspaceRoot : "";
147
+ const base = root.replace(/[\\/]+$/, "");
148
+ const dataDir = base + "/.colgrep-data";
149
+ // `root` moves the run, never the index: index data stays inside the
150
+ // workspace so it remains under the sandbox policy and the same
151
+ // registry serves every root.
152
+ const workdir = args.root && base ? resolve(base, args.root) : base;
153
+ const command = buildArgs(args).map((part, index) => (index === 0 ? part : quoteArg(part))).join(" ");
154
+ const spec = ctx.shell.resolve({
155
+ command,
156
+ timeoutMs: 300000,
157
+ stdoutMaxBytes: 2 * 1024 * 1024,
158
+ signal: exec.signal,
159
+ sandboxPolicy: policy,
160
+ ...(workdir ? { workdir, env: { COLGREP_DATA_DIR: dataDir } } : {}),
161
+ });
162
+ // The shell seam is `execute()` → handle → `result()` since 0.1.7; the
163
+ // older `run()` that settled the outcome directly no longer exists.
164
+ const run = await (await ctx.shell.execute(spec)).result();
165
+ const stdout = run.stdout && run.stdout.text ? run.stdout.text : "";
166
+ const stderr = run.stderr && run.stderr.text ? run.stderr.text : "";
167
+ const commandName = args.command || "search";
168
+ const common = {
169
+ ok: run.exitCode === 0,
170
+ command: commandName,
171
+ exitCode: run.exitCode,
172
+ ...(run.timedOut ? { timedOut: true } : {}),
173
+ ...(run.aborted ? { aborted: true } : {}),
174
+ };
175
+ if (commandName !== "search") {
176
+ return { ...common, stdout, stderr };
177
+ }
178
+ let parsed = null;
179
+ try {
180
+ parsed = JSON.parse(stdout);
181
+ } catch {
182
+ parsed = null;
183
+ }
184
+ let results = null;
185
+ if (Array.isArray(parsed)) {
186
+ results = normalizeResults(parsed);
187
+ } else if (parsed && typeof parsed === "object" && Array.isArray(parsed.results)) {
188
+ results = normalizeResults(parsed.results);
189
+ }
190
+ if (results === null) {
191
+ return { ...common, query: args.query, results: null, stdout, stderr };
192
+ }
193
+ return { ...common, query: args.query, count: results.length, results };
194
+ },
195
+ }));
196
+ }