@garuda-agent/garuda 0.0.1 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +4 -0
  4. package/README.md +1040 -0
  5. package/SECURITY.md +32 -0
  6. package/dist/anthropic-NQDBCHJU.js +327 -0
  7. package/dist/chunk-35GMLLJW.js +157 -0
  8. package/dist/chunk-36GQIVGT.js +526 -0
  9. package/dist/chunk-3CEPHS4C.js +231 -0
  10. package/dist/chunk-3NJNVZTK.js +123 -0
  11. package/dist/chunk-42DSA4EA.js +116 -0
  12. package/dist/chunk-4P26OKTP.js +100 -0
  13. package/dist/chunk-5DEWP3YX.js +139 -0
  14. package/dist/chunk-6TWBYMY7.js +9 -0
  15. package/dist/chunk-A2QAIRQL.js +45 -0
  16. package/dist/chunk-ATW7BNIG.js +31 -0
  17. package/dist/chunk-D5O5CIWK.js +1339 -0
  18. package/dist/chunk-EU7PA45O.js +324 -0
  19. package/dist/chunk-FARS4R67.js +206 -0
  20. package/dist/chunk-G2AX7MGS.js +36 -0
  21. package/dist/chunk-HUIK3WXO.js +234 -0
  22. package/dist/chunk-ITITLNAR.js +9341 -0
  23. package/dist/chunk-KKB5W47S.js +231 -0
  24. package/dist/chunk-KWRJREUH.js +283 -0
  25. package/dist/chunk-N4I6YS3E.js +73 -0
  26. package/dist/chunk-OUCV3FCT.js +205 -0
  27. package/dist/chunk-PZS3V6P3.js +46 -0
  28. package/dist/chunk-QOW5TK4L.js +320 -0
  29. package/dist/chunk-U4OQVT2T.js +73 -0
  30. package/dist/chunk-V7WPGQLB.js +207 -0
  31. package/dist/chunk-W7BPYQMW.js +173 -0
  32. package/dist/chunk-WMOLXTBU.js +61 -0
  33. package/dist/chunk-YIZWYUBG.js +138 -0
  34. package/dist/chunk-YM6T4J5V.js +1350 -0
  35. package/dist/chunk-YQTGMCU6.js +111 -0
  36. package/dist/chunk-ZAE25JM2.js +158 -0
  37. package/dist/chunk-ZGZ2ZADL.js +49 -0
  38. package/dist/cli/index.js +1191 -0
  39. package/dist/create-Y5SXJUXO.js +223 -0
  40. package/dist/deadline-F5RJJ2QW.js +86 -0
  41. package/dist/detect-LARDSLLZ.js +10 -0
  42. package/dist/evalCommand-5TG2CKZY.js +2795 -0
  43. package/dist/export-HN3CT7AV.js +158 -0
  44. package/dist/inkChat-3J26R24L.js +1190 -0
  45. package/dist/install-XWLU22OH.js +17 -0
  46. package/dist/job-3NYDMP2M.js +31 -0
  47. package/dist/jobCommand-IYWZWTSI.js +30 -0
  48. package/dist/launchd-2FL5UN2U.js +40 -0
  49. package/dist/lspCommand-TJEZBV2E.js +99 -0
  50. package/dist/manager-4PMSXT47.js +14 -0
  51. package/dist/manager-EBTYO2GR.js +847 -0
  52. package/dist/nightCommand-DUNWJASI.js +247 -0
  53. package/dist/oauth-W6OK6XXO.js +23 -0
  54. package/dist/openaiCompatible-CJWVJP5M.js +501 -0
  55. package/dist/policy-EJPLEEXP.js +31 -0
  56. package/dist/proxy-XJAHCZB2.js +192 -0
  57. package/dist/remove-AENULZZE.js +59 -0
  58. package/dist/run-66Y6R2KU.js +886 -0
  59. package/dist/servers-6YDGWOZ6.js +24 -0
  60. package/dist/text-J2GD647J.js +11 -0
  61. package/package.json +83 -3
@@ -0,0 +1,231 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ parseRule
4
+ } from "./chunk-3NJNVZTK.js";
5
+
6
+ // src/jobs/job.ts
7
+ import { randomBytes } from "crypto";
8
+ import { mkdirSync, renameSync, writeFileSync } from "fs";
9
+ import { mkdir, readdir, readFile, rename, writeFile } from "fs/promises";
10
+ import { join } from "path";
11
+ import { z } from "zod";
12
+ var JOBS_DIR = join(".garuda", "jobs");
13
+ var DEFAULT_JOB_MAX_STEPS = 100;
14
+ var JOB_STATUSES = ["scheduled", "running", "done", "stopped", "failed"];
15
+ var fileChange = z.object({
16
+ status: z.enum(["added", "modified", "deleted"]),
17
+ path: z.string(),
18
+ added: z.number().optional(),
19
+ removed: z.number().optional()
20
+ });
21
+ var testRun = z.object({
22
+ exitCode: z.number().nullable(),
23
+ timedOut: z.boolean(),
24
+ durationMs: z.number(),
25
+ tail: z.string()
26
+ });
27
+ var resultSchema = z.object({
28
+ stopReason: z.string(),
29
+ steps: z.number(),
30
+ tokens: z.number(),
31
+ costUsd: z.number().optional(),
32
+ durationMs: z.number(),
33
+ sessionId: z.string().optional(),
34
+ commit: z.string().optional(),
35
+ files: z.array(fileChange),
36
+ denied: z.array(z.object({ tool: z.string(), target: z.string() })),
37
+ answer: z.string(),
38
+ error: z.string().optional(),
39
+ /** With the Batch API: requests per API, and when the job switched to the normal API. */
40
+ modelCalls: z.object({
41
+ batch: z.number(),
42
+ normal: z.number(),
43
+ /** Steps that waited past the step limit and ran on the normal API. */
44
+ slow: z.number().optional(),
45
+ switchedAt: z.string().optional()
46
+ }).optional(),
47
+ /** Proof of work (0.11): tests before and after, risk flags, the review and the verdict. */
48
+ proof: z.object({
49
+ verdict: z.enum(["ready", "needs-look"]),
50
+ before: testRun.optional(),
51
+ after: testRun.optional(),
52
+ flags: z.array(z.object({ level: z.enum(["stop", "look"]), text: z.string() })),
53
+ review: z.object({
54
+ verdict: z.enum(["ready", "needs-look"]),
55
+ text: z.string(),
56
+ costUsd: z.number().optional()
57
+ }).optional(),
58
+ reviewError: z.string().optional()
59
+ }).optional()
60
+ });
61
+ var jobSchema = z.object({
62
+ version: z.literal(1),
63
+ id: z.string().regex(/^[A-Za-z0-9_-]{1,80}$/),
64
+ title: z.string(),
65
+ createdAt: z.string(),
66
+ /** The project folder the job belongs to (the user's checkout). */
67
+ root: z.string(),
68
+ /** The commit the job starts from: HEAD, or a snapshot of the uncommitted changes. */
69
+ base: z.string().regex(/^[0-9a-f]{40,64}$/),
70
+ branch: z.string().regex(/^garuda\/job-[A-Za-z0-9_-]+$/),
71
+ worktree: z.string(),
72
+ /** The task: the plan and how to carry it out. */
73
+ prompt: z.string().min(1),
74
+ /** The session the plan came from. */
75
+ planSession: z.string().optional(),
76
+ model: z.string().optional(),
77
+ /** Permission rules for this job only, in the settings format ("edit_file(src/**)"). */
78
+ allow: z.array(z.string()),
79
+ onUnapproved: z.literal("deny-and-continue"),
80
+ /** "01:00" (local time) for `garuda run --at`, when the user gave one. */
81
+ at: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/).optional(),
82
+ maxSteps: z.number().int().min(1).max(1e3),
83
+ /** The Batch API (0.7): half price, minutes per step; the normal API from 15 min before finishBy. */
84
+ batch: z.boolean().optional(),
85
+ finishBy: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/).optional(),
86
+ /** A batch step that waits longer goes to the normal API (only that step). Default 20. */
87
+ stepLimitMinutes: z.number().int().min(1).max(24 * 60).optional(),
88
+ /**
89
+ * Ignored folders of the checkout (node_modules, .venv) that the worktree links to. Each is one
90
+ * folder name in the root (0.14.1, review: ".." made the parent folder writable for the job).
91
+ */
92
+ links: z.array(
93
+ z.string().regex(/^[^/\\]+$/, "a link is one folder name in the project").refine((name) => name !== "." && name !== "..", "a link is one folder name in the project")
94
+ ),
95
+ /**
96
+ * Proof of work (0.11): the test command, run in the sandbox before and after the job (absent:
97
+ * no tests), and the review of the diff (default true).
98
+ */
99
+ test: z.string().min(1).optional(),
100
+ review: z.boolean().optional(),
101
+ /**
102
+ * The network allowlist (0.13): presets and hosts that the job's sandboxed commands may reach,
103
+ * approved with the job. Other hosts are denied and reported. Absent: no network.
104
+ */
105
+ network: z.array(z.string()).optional(),
106
+ /** In the project's night queue (0.11): `garuda night` runs it. */
107
+ queue: z.boolean().optional(),
108
+ /** The launchd agent that starts the job (macOS), while it is installed. */
109
+ launchd: z.object({ label: z.string(), plist: z.string(), when: z.string() }).optional(),
110
+ status: z.enum(JOB_STATUSES),
111
+ /** Why a job failed before its turn ended (0.14.1, review). */
112
+ error: z.string().max(2e3).optional(),
113
+ startedAt: z.string().optional(),
114
+ endedAt: z.string().optional(),
115
+ result: resultSchema.optional()
116
+ });
117
+ function newJobId(now = /* @__PURE__ */ new Date()) {
118
+ const pad = (n) => String(n).padStart(2, "0");
119
+ const date = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`;
120
+ return `${date}-${pad(now.getHours())}${pad(now.getMinutes())}-${randomBytes(2).toString("hex")}`;
121
+ }
122
+ function jobPath(root, id) {
123
+ return join(root, JOBS_DIR, `${id}.json`);
124
+ }
125
+ function failJobSync(job, error) {
126
+ job.status = "failed";
127
+ job.error = error.slice(0, 2e3);
128
+ job.endedAt = (/* @__PURE__ */ new Date()).toISOString();
129
+ const dir = join(job.root, JOBS_DIR);
130
+ mkdirSync(dir, { recursive: true, mode: 448 });
131
+ const file = jobPath(job.root, job.id);
132
+ const temp = `${file}.${process.pid}.tmp`;
133
+ writeFileSync(temp, `${JSON.stringify(job, null, 2)}
134
+ `, { mode: 384 });
135
+ renameSync(temp, file);
136
+ }
137
+ async function settleJob(root, id, exitCode) {
138
+ const job = await loadJob(root, id).catch(() => void 0);
139
+ if (job?.status !== "running") return;
140
+ failJobSync(
141
+ job,
142
+ `The job process ended (exit code ${exitCode ?? "none"}) before the job finished. See ${JOBS_DIR}/${id}.log.`
143
+ );
144
+ }
145
+ async function saveJob(job) {
146
+ const dir = join(job.root, JOBS_DIR);
147
+ await mkdir(dir, { recursive: true, mode: 448 });
148
+ const file = jobPath(job.root, job.id);
149
+ const temp = `${file}.${process.pid}.tmp`;
150
+ await writeFile(temp, `${JSON.stringify(job, null, 2)}
151
+ `, { mode: 384 });
152
+ await rename(temp, file);
153
+ }
154
+ async function loadJob(root, id) {
155
+ if (!/^[A-Za-z0-9_-]{1,80}$/.test(id)) throw new Error(`"${id}" is not a job id.`);
156
+ let text;
157
+ try {
158
+ text = await readFile(jobPath(root, id), "utf8");
159
+ } catch (error) {
160
+ if (error.code === "ENOENT") {
161
+ throw new Error(`There is no job ${id} in this project (${JOBS_DIR}).`);
162
+ }
163
+ throw error;
164
+ }
165
+ let parsed;
166
+ try {
167
+ const result = jobSchema.safeParse(JSON.parse(text));
168
+ if (!result.success) throw new Error(z.prettifyError(result.error));
169
+ parsed = result.data;
170
+ } catch (error) {
171
+ throw new Error(`${JOBS_DIR}/${id}.json: ${error.message}`);
172
+ }
173
+ if (parsed.root !== root) {
174
+ throw new Error(`Job ${id} belongs to ${parsed.root}, not to ${root}.`);
175
+ }
176
+ for (const rule of parsed.allow) parseRule(rule);
177
+ return parsed;
178
+ }
179
+ async function listJobs(root) {
180
+ let names;
181
+ try {
182
+ names = (await readdir(join(root, JOBS_DIR))).filter((n) => n.endsWith(".json"));
183
+ } catch {
184
+ return [];
185
+ }
186
+ const jobs = [];
187
+ for (const name of names.sort().reverse()) {
188
+ try {
189
+ jobs.push(await loadJob(root, name.slice(0, -".json".length)));
190
+ } catch {
191
+ }
192
+ }
193
+ return jobs;
194
+ }
195
+ function planPermissions(plan) {
196
+ const block = /```permissions[^\n]*\n([\s\S]*?)```/.exec(plan)?.[1];
197
+ const rules = [];
198
+ const problems = [];
199
+ for (const raw of (block ?? "").split("\n")) {
200
+ const line = raw.replace(/^\s*[-*]\s+/, "").trim();
201
+ if (line === "" || line.startsWith("#")) continue;
202
+ try {
203
+ parseRule(line);
204
+ if (!rules.includes(line)) rules.push(line);
205
+ } catch {
206
+ problems.push(line);
207
+ }
208
+ }
209
+ return { rules, problems };
210
+ }
211
+ function planTitle(prompt, plan) {
212
+ const line = prompt.split("\n").map((l) => l.trim()).find((l) => l !== "") ?? plan.split("\n").find((l) => l.trim() !== "") ?? "job";
213
+ const clean = line.replace(/^#+\s*/, "");
214
+ return clean.length <= 70 ? clean : `${clean.slice(0, 69)}\u2026`;
215
+ }
216
+
217
+ export {
218
+ JOBS_DIR,
219
+ DEFAULT_JOB_MAX_STEPS,
220
+ JOB_STATUSES,
221
+ newJobId,
222
+ jobPath,
223
+ failJobSync,
224
+ settleJob,
225
+ saveJob,
226
+ loadJob,
227
+ listJobs,
228
+ planPermissions,
229
+ planTitle
230
+ };
231
+ //# sourceMappingURL=chunk-KKB5W47S.js.map
@@ -0,0 +1,283 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ isLoopbackHost
4
+ } from "./chunk-ATW7BNIG.js";
5
+
6
+ // src/commands/builtins.ts
7
+ var BUILTIN_COMMANDS = [
8
+ "help",
9
+ "usage",
10
+ "session",
11
+ "sessions",
12
+ "models",
13
+ "export",
14
+ "compact",
15
+ "diff",
16
+ "schedule",
17
+ "jobs",
18
+ "where",
19
+ "defs",
20
+ "refs",
21
+ "callers",
22
+ "impact",
23
+ "map",
24
+ "mcp",
25
+ "hooks",
26
+ "lsp",
27
+ "languages",
28
+ "experts",
29
+ "audit",
30
+ "commands",
31
+ "agents",
32
+ "plan",
33
+ "build",
34
+ "new",
35
+ "init",
36
+ "editor",
37
+ "details",
38
+ "thinking",
39
+ "search",
40
+ "undo",
41
+ "redo",
42
+ "exit",
43
+ "quit"
44
+ ];
45
+
46
+ // src/web/search.ts
47
+ import { mkdir, readFile, writeFile } from "fs/promises";
48
+ import { homedir } from "os";
49
+ import { dirname, join } from "path";
50
+ import { z } from "zod";
51
+ var SEARCH_FILE = join(".garuda", "search.json");
52
+ var SEARCH_TIMEOUT_MS = 2e4;
53
+ var SEARCH_MAX_BYTES = 2 * 1024 * 1024;
54
+ var DEFAULT_RESULTS = 5;
55
+ var MAX_RESULTS = 10;
56
+ var SEARCH_USES = ["claude", "provider", "off"];
57
+ var DEFAULT_CLAUDE_MAX_USES = 5;
58
+ var domains = z.array(
59
+ z.string().min(1).regex(/^[^\s:/][^\s:]*$/, "a bare domain, with an optional path (no scheme)")
60
+ );
61
+ var claudeSchema = z.strictObject({
62
+ /** Searches per model request, 1–20. Default 5. */
63
+ maxUses: z.number().int().min(1).max(20).optional(),
64
+ allowedDomains: domains.optional(),
65
+ blockedDomains: domains.optional()
66
+ }).refine((c) => c.allowedDomains === void 0 || c.blockedDomains === void 0, {
67
+ message: "use allowedDomains or blockedDomains, not both"
68
+ });
69
+ var fileSchema = z.strictObject({
70
+ /** The user's choice (0.14); absent: the chat asks once and saves the answer. */
71
+ use: z.enum(SEARCH_USES).optional(),
72
+ provider: z.enum(["brave", "tavily", "searxng"]).optional(),
73
+ /** Claude's own web search (0.6). */
74
+ claude: claudeSchema.optional(),
75
+ /** SearXNG only: the server's base URL. */
76
+ url: z.string().optional(),
77
+ /** The environment variable with the key. Default: BRAVE_API_KEY or TAVILY_API_KEY. */
78
+ apiKeyEnv: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).optional(),
79
+ /** Results per search, 1–10. Default 5. */
80
+ maxResults: z.number().int().min(1).max(MAX_RESULTS).optional()
81
+ });
82
+ var LABELS = {
83
+ brave: "Brave Search",
84
+ tavily: "Tavily",
85
+ searxng: "SearXNG"
86
+ };
87
+ function providerLabel(config) {
88
+ return `${LABELS[config.provider]} (${config.endpoint.host})`;
89
+ }
90
+ async function loadSearchConfig(home = homedir(), env = process.env) {
91
+ const file = join(home, SEARCH_FILE);
92
+ let text;
93
+ try {
94
+ text = await readFile(file, "utf8");
95
+ } catch (error) {
96
+ if (error.code !== "ENOENT") {
97
+ return { problem: `${file}: ${error.message}` };
98
+ }
99
+ }
100
+ if (text === void 0) return fromEnv(env, DEFAULT_RESULTS);
101
+ let parsed;
102
+ try {
103
+ const result = fileSchema.safeParse(JSON.parse(text));
104
+ if (!result.success) return { problem: `${file}: ${z.prettifyError(result.error)}` };
105
+ parsed = result.data;
106
+ } catch (error) {
107
+ return { problem: `${file}: invalid JSON: ${error.message}` };
108
+ }
109
+ const max = parsed.maxResults ?? DEFAULT_RESULTS;
110
+ const use = parsed.use === void 0 ? {} : { use: parsed.use };
111
+ const claude = parsed.claude === void 0 ? {} : {
112
+ claude: {
113
+ maxUses: parsed.claude.maxUses ?? DEFAULT_CLAUDE_MAX_USES,
114
+ ...parsed.claude.allowedDomains === void 0 ? {} : { allowedDomains: parsed.claude.allowedDomains },
115
+ ...parsed.claude.blockedDomains === void 0 ? {} : { blockedDomains: parsed.claude.blockedDomains }
116
+ }
117
+ };
118
+ if (parsed.provider === void 0) {
119
+ if (parsed.claude === void 0 && parsed.use === void 0) {
120
+ return { problem: `${file}: name a "provider", or add a "claude" section.` };
121
+ }
122
+ return { ...fromEnv(env, max), ...claude, ...use };
123
+ }
124
+ const client = clientConfig(file, { ...parsed, provider: parsed.provider }, env, max);
125
+ return "problem" in client ? { ...client, ...claude, ...use } : { config: client.config, ...claude, ...use };
126
+ }
127
+ async function saveSearchUse(home, use) {
128
+ const file = join(home, SEARCH_FILE);
129
+ let data = {};
130
+ try {
131
+ data = JSON.parse(await readFile(file, "utf8"));
132
+ } catch (error) {
133
+ if (error.code !== "ENOENT") throw error;
134
+ }
135
+ await mkdir(dirname(file), { recursive: true });
136
+ await writeFile(file, `${JSON.stringify({ ...data, use }, null, 2)}
137
+ `, { mode: 384 });
138
+ return file;
139
+ }
140
+ function fromEnv(env, max) {
141
+ if (env.BRAVE_API_KEY) return { config: brave(env.BRAVE_API_KEY, max) };
142
+ if (env.TAVILY_API_KEY) return { config: tavily(env.TAVILY_API_KEY, max) };
143
+ return {};
144
+ }
145
+ function clientConfig(file, parsed, env, max) {
146
+ if (parsed.provider === "searxng") {
147
+ if (parsed.url === void 0) return { problem: `${file}: "searxng" needs a "url".` };
148
+ const endpoint = searxngEndpoint(parsed.url);
149
+ if (typeof endpoint === "string") return { problem: `${file}: ${endpoint}` };
150
+ return { config: { provider: "searxng", endpoint, maxResults: max } };
151
+ }
152
+ const variable = parsed.apiKeyEnv ?? (parsed.provider === "brave" ? "BRAVE_API_KEY" : "TAVILY_API_KEY");
153
+ const key = env[variable];
154
+ if (!key) return { problem: `${file}: web search needs the key in ${variable}; it is not set.` };
155
+ return { config: parsed.provider === "brave" ? brave(key, max) : tavily(key, max) };
156
+ }
157
+ function brave(apiKey, maxResults) {
158
+ return {
159
+ provider: "brave",
160
+ endpoint: new URL("https://api.search.brave.com/res/v1/web/search"),
161
+ apiKey,
162
+ maxResults
163
+ };
164
+ }
165
+ function tavily(apiKey, maxResults) {
166
+ return {
167
+ provider: "tavily",
168
+ endpoint: new URL("https://api.tavily.com/search"),
169
+ apiKey,
170
+ maxResults
171
+ };
172
+ }
173
+ function searxngEndpoint(raw) {
174
+ let url;
175
+ try {
176
+ url = new URL(raw);
177
+ } catch {
178
+ return `"${raw}" is not a valid URL.`;
179
+ }
180
+ if (url.username !== "" || url.password !== "")
181
+ return "a URL with a user name or password is not allowed.";
182
+ const local = isLoopbackHost(url.hostname.replace(/^\[|\]$/g, ""));
183
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) {
184
+ return "use https (http only for localhost).";
185
+ }
186
+ return new URL(`${url.pathname.replace(/\/+$/, "")}/search`, url);
187
+ }
188
+ async function search(config, query, maxResults, signal, fetchFn = fetch) {
189
+ const count = Math.min(Math.max(1, maxResults), MAX_RESULTS);
190
+ const timeout = AbortSignal.any([signal, AbortSignal.timeout(SEARCH_TIMEOUT_MS)]);
191
+ let request;
192
+ if (config.provider === "brave") {
193
+ const url = new URL(config.endpoint);
194
+ url.searchParams.set("q", query);
195
+ url.searchParams.set("count", String(count));
196
+ request = new Request(url, {
197
+ headers: { accept: "application/json", "x-subscription-token": config.apiKey ?? "" }
198
+ });
199
+ } else if (config.provider === "tavily") {
200
+ request = new Request(config.endpoint, {
201
+ method: "POST",
202
+ headers: {
203
+ "content-type": "application/json",
204
+ authorization: `Bearer ${config.apiKey ?? ""}`
205
+ },
206
+ body: JSON.stringify({ query, max_results: count, search_depth: "basic" })
207
+ });
208
+ } else {
209
+ const url = new URL(config.endpoint);
210
+ url.searchParams.set("q", query);
211
+ url.searchParams.set("format", "json");
212
+ request = new Request(url, { headers: { accept: "application/json" } });
213
+ }
214
+ let response;
215
+ try {
216
+ response = await fetchFn(request, { signal: timeout, redirect: "error" });
217
+ } catch (error) {
218
+ if (signal.aborted) throw error;
219
+ throw new Error(`${LABELS[config.provider]} did not answer: ${error.message}`);
220
+ }
221
+ if (!response.ok) {
222
+ const hint = response.status === 401 || response.status === 403 ? " Check the API key." : response.status === 429 ? " Too many searches; wait, or check your plan." : "";
223
+ throw new Error(`${LABELS[config.provider]} answered ${response.status}.${hint}`);
224
+ }
225
+ const text = await readCapped(response, SEARCH_MAX_BYTES);
226
+ let json;
227
+ try {
228
+ json = JSON.parse(text);
229
+ } catch {
230
+ throw new Error(
231
+ `${LABELS[config.provider]} did not answer with JSON.${config.provider === "searxng" ? ' Turn on the "json" format in its settings.yml (search.formats).' : ""}`
232
+ );
233
+ }
234
+ return parseResults(config.provider, json).slice(0, count);
235
+ }
236
+ function parseResults(provider, json) {
237
+ const obj = (v) => v !== null && typeof v === "object" ? v : {};
238
+ const str = (v) => typeof v === "string" ? v : "";
239
+ const list = provider === "brave" ? obj(obj(json).web).results : obj(json).results;
240
+ if (!Array.isArray(list)) return [];
241
+ const out = [];
242
+ for (const item of list) {
243
+ const r = obj(item);
244
+ const url = str(r.url);
245
+ if (!/^https?:\/\//.test(url)) continue;
246
+ const snippet = provider === "brave" ? str(r.description) : str(r.content);
247
+ const age = provider === "brave" ? str(r.age) : str(r.publishedDate);
248
+ out.push({
249
+ title: str(r.title),
250
+ url,
251
+ snippet,
252
+ ...age === "" ? {} : { age }
253
+ });
254
+ }
255
+ return out;
256
+ }
257
+ async function readCapped(response, max) {
258
+ const reader = response.body?.getReader();
259
+ if (reader === void 0) return "";
260
+ const chunks = [];
261
+ let size = 0;
262
+ for (; ; ) {
263
+ const { done, value } = await reader.read();
264
+ if (done) break;
265
+ size += value.byteLength;
266
+ if (size > max) {
267
+ await reader.cancel();
268
+ throw new Error(`The search answer is larger than ${max} bytes.`);
269
+ }
270
+ chunks.push(value);
271
+ }
272
+ return Buffer.concat(chunks).toString("utf8");
273
+ }
274
+
275
+ export {
276
+ BUILTIN_COMMANDS,
277
+ MAX_RESULTS,
278
+ providerLabel,
279
+ loadSearchConfig,
280
+ saveSearchUse,
281
+ search
282
+ };
283
+ //# sourceMappingURL=chunk-KWRJREUH.js.map
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/notify.ts
4
+ var DEFAULT_AFTER_SECONDS = 10;
5
+ var MAX_TEXT = 120;
6
+ var OSC9_TERMINALS = /* @__PURE__ */ new Set(["iTerm.app", "ghostty", "WezTerm"]);
7
+ function pickChannel(choice, env = process.env) {
8
+ const fromEnv = env.GARUDA_NOTIFY;
9
+ const wanted = fromEnv !== void 0 && fromEnv !== "" ? fromEnv : choice ?? "auto";
10
+ if (wanted === "off" || wanted === "bell" || wanted === "osc9") return wanted;
11
+ const multiplexer = env.TMUX !== void 0 || (env.TERM ?? "").startsWith("screen");
12
+ return !multiplexer && OSC9_TERMINALS.has(env.TERM_PROGRAM ?? "") ? "osc9" : "bell";
13
+ }
14
+ function notificationBytes(channel, text) {
15
+ if (channel === "off") return "";
16
+ if (channel === "bell") return "\x07";
17
+ const clean = Array.from(text, (ch) => {
18
+ const code = ch.codePointAt(0) ?? 0;
19
+ return code < 32 || code >= 127 && code <= 159 ? " " : ch;
20
+ }).join("").replace(/ {2,}/g, " ").trim();
21
+ const cut = clean.length <= MAX_TEXT ? clean : `${clean.slice(0, MAX_TEXT - 1)}\u2026`;
22
+ return `\x1B]9;${cut}\x07`;
23
+ }
24
+ var Notifier = class {
25
+ constructor(channel, write, afterSeconds = DEFAULT_AFTER_SECONDS, isFocused = () => void 0) {
26
+ this.channel = channel;
27
+ this.write = write;
28
+ this.afterSeconds = afterSeconds;
29
+ this.isFocused = isFocused;
30
+ }
31
+ channel;
32
+ write;
33
+ afterSeconds;
34
+ isFocused;
35
+ /** Questions notify only during a turn: after a command the user typed (/undo), the user is here. */
36
+ running = false;
37
+ /** An approval or a consent question waits for the user. */
38
+ approval(request) {
39
+ if (!this.running) return;
40
+ const target = request.target;
41
+ const what = request.title ?? (target.kind === "command" ? `${request.tool}: ${target.command.split("\n")[0] ?? ""}` : target.kind === "path" ? `${request.tool} ${target.path}` : request.tool);
42
+ this.send(`Garuda needs your approval: ${what}`);
43
+ }
44
+ turnStarted() {
45
+ this.running = true;
46
+ }
47
+ /** A turn ended. Short turns and turns the user stopped stay quiet. */
48
+ turnEnded(outcome, ms) {
49
+ this.running = false;
50
+ if (outcome === void 0 || outcome.kind === "interrupted") return;
51
+ if (ms < this.afterSeconds * 1e3) return;
52
+ const time = formatSeconds(ms);
53
+ if (outcome.kind === "error") this.send(`Garuda: the task failed after ${time}.`);
54
+ else if (outcome.result.stopReason === "done") this.send(`Garuda: the task is done (${time}).`);
55
+ else this.send(`Garuda: the task stopped (${outcome.result.stopReason}) after ${time}.`);
56
+ }
57
+ send(text) {
58
+ if (this.isFocused() === true) return;
59
+ const bytes = notificationBytes(this.channel, text);
60
+ if (bytes !== "") this.write(bytes);
61
+ }
62
+ };
63
+ function formatSeconds(ms) {
64
+ const s = Math.round(ms / 1e3);
65
+ return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${s % 60} s`;
66
+ }
67
+
68
+ export {
69
+ pickChannel,
70
+ notificationBytes,
71
+ Notifier
72
+ };
73
+ //# sourceMappingURL=chunk-N4I6YS3E.js.map