@0perator/operator 0.1.284 → 0.1.313

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 (99) hide show
  1. package/README.md +24 -2
  2. package/dist/acp/agent.js +3 -2
  3. package/dist/acp/config-options.js +15 -1
  4. package/dist/acp/tool-map.js +2 -1
  5. package/dist/auth/commands.js +69 -13
  6. package/dist/autonomy/agent-cli.js +304 -0
  7. package/dist/autonomy/cloud-agent.js +439 -0
  8. package/dist/autonomy/cron-lifecycle.js +78 -0
  9. package/dist/autonomy/cron-lock.js +121 -0
  10. package/dist/autonomy/cron.js +216 -43
  11. package/dist/autonomy/delegate.js +5 -1
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/session-factory.js +25 -16
  14. package/dist/background/index.js +40 -0
  15. package/dist/bus/inbox.js +20 -0
  16. package/dist/classifier/config.js +47 -0
  17. package/dist/classifier/modes.js +41 -0
  18. package/dist/classifier/types.js +1 -0
  19. package/dist/cli.js +529 -53
  20. package/dist/config/features.js +69 -0
  21. package/dist/config/persona.js +118 -99
  22. package/dist/config/scaffold.js +15 -0
  23. package/dist/config/settings.js +96 -6
  24. package/dist/consolidation/sleep.js +73 -11
  25. package/dist/engine/agent.js +275 -18
  26. package/dist/engine/anthropic-chat.js +343 -0
  27. package/dist/engine/aurora.js +101 -13
  28. package/dist/engine/batch-scheduler.js +41 -9
  29. package/dist/engine/classifier.js +85 -0
  30. package/dist/engine/compaction.js +24 -5
  31. package/dist/engine/fast-start.js +25 -0
  32. package/dist/engine/loop-guard.js +448 -0
  33. package/dist/engine/moa.js +5 -1
  34. package/dist/engine/net-error.js +24 -0
  35. package/dist/engine/repetition-guard.js +180 -0
  36. package/dist/engine/selfheal.js +8 -0
  37. package/dist/engine/toolcalls.js +51 -1
  38. package/dist/engine/verify-gate.js +2 -0
  39. package/dist/flywheel/processor.js +78 -31
  40. package/dist/flywheel/srft.js +13 -0
  41. package/dist/hooks/index.js +196 -0
  42. package/dist/mcp/config.js +21 -1
  43. package/dist/memory/index.js +0 -0
  44. package/dist/memory/providers.js +210 -0
  45. package/dist/memory/session-catalog.js +422 -0
  46. package/dist/memory/session-providers.js +121 -0
  47. package/dist/memory/session-sources.js +335 -0
  48. package/dist/memory/skylark.js +131 -0
  49. package/dist/models/bench.js +103 -0
  50. package/dist/models/registry.js +144 -0
  51. package/dist/models/switch.js +69 -0
  52. package/dist/observability/blackbox.js +37 -0
  53. package/dist/permissions/policy.js +31 -6
  54. package/dist/router/discovery.js +127 -0
  55. package/dist/router/models.js +117 -24
  56. package/dist/router/portal.js +100 -0
  57. package/dist/router/router.js +1 -1
  58. package/dist/services/preflight.js +55 -7
  59. package/dist/session.js +316 -46
  60. package/dist/tools/chauffeur.js +12 -0
  61. package/dist/tools/executor.js +19 -9
  62. package/dist/tools/find-files.js +483 -0
  63. package/dist/tools/git-pr.js +94 -0
  64. package/dist/tools/incident-tools.js +82 -0
  65. package/dist/tools/memory.js +12 -2
  66. package/dist/tools/registry.js +281 -85
  67. package/dist/tools/semantic-compress.js +124 -0
  68. package/dist/tools/shell-context.js +1 -0
  69. package/dist/tools/shell-jobs.js +160 -0
  70. package/dist/tools/shell-session.js +170 -4
  71. package/dist/tools/wave-tools.js +609 -0
  72. package/dist/tools/wave2-tools.js +411 -0
  73. package/dist/ui/App.js +15 -4
  74. package/dist/ui/BgPanel.js +30 -6
  75. package/dist/ui/Composer.js +11 -1
  76. package/dist/ui/QuestionPrompt.js +31 -11
  77. package/dist/ui/SessionPicker.js +86 -0
  78. package/dist/ui/StatusRule.js +5 -5
  79. package/dist/ui/ToolStep.js +2 -1
  80. package/dist/ui/Transcript.js +17 -1
  81. package/dist/ui/index.js +1 -1
  82. package/dist/ui/liveTools.js +21 -3
  83. package/dist/ui/slashCommands.js +2 -0
  84. package/dist/util/screenshots.js +74 -8
  85. package/dist/util/slash.js +2 -2
  86. package/package.json +8 -2
  87. package/dist/engine/cli.js +0 -1171
  88. package/dist/router/models.js.bak +0 -78
  89. package/dist/router/models.js.bak-1791259923 +0 -78
  90. package/dist/router/models.js.bak-pre-gateway +0 -78
  91. package/dist/router/models.js.bak-pre-patch2 +0 -78
  92. package/dist/router/models.js.bak2 +0 -78
  93. package/dist/services/model-autodetect.js +0 -240
  94. package/dist/tools/native-redirect.js +0 -140
  95. package/dist/tools/power-tools.js +0 -627
  96. package/dist/tools/registry.js.bak-1791259948 +0 -1914
  97. package/dist/tools/registry.js.bak-pre-plugins +0 -1914
  98. package/dist/ui/BusTray.js +0 -70
  99. package/dist/ui/resize.js +0 -160
@@ -2,9 +2,8 @@
2
2
  // Interface consumed by the engine (Karpathy's lane):
3
3
  // execute(name, args) -> Promise<string> one call; never throws, always resolves
4
4
  // executeParallel(calls) -> Promise<string[]> one round's tool_calls, in input order;
5
- // executed in input order: a contiguous run of safe
6
- // (read-only) tools runs concurrently, every other
7
- // call runs alone, awaited in place
5
+ // BTX DAG: reads overlap, writes conflict-order,
6
+ // barriers alone, independent bash/shell_exec overlap
8
7
  // resetTurn() -> void clear loop-guard history; call once per
9
8
  // new user turn (not required by SPEC §3's
10
9
  // round loop itself, but needed so the guard
@@ -12,11 +11,12 @@
12
11
  import { isAbsolute, join, resolve } from "node:path";
13
12
  import { registry } from "./registry.js";
14
13
  import { expandPath } from "./paths.js";
15
- import { shellKeyStore } from "./shell-context.js";
14
+ import { shellKeyStore, shellExecMode } from "./shell-context.js";
16
15
  // Re-exported for back-compat (existing importers reach it via executor.js) — moved to its own
17
16
  // file since it's a pure helper with no node deps; see result-cap.ts for why that separation matters.
18
17
  import { capToolResult } from "./result-cap.js";
19
18
  import { spillToolOutput } from "./tool-output-spill.js"; // GW-10: lossless eviction — spill big outputs, hand back a re-readable pointer
19
+ import { semanticCompress } from "./semantic-compress.js";
20
20
  export { TOOL_RESULT_MAX_CHARS, capToolResult } from "./result-cap.js";
21
21
  import { runBatch, defaultClassify, defaultKeys } from "../engine/batch-scheduler.js";
22
22
  // Command tools whose working directory should default to the executor root (they take an optional `cwd`).
@@ -94,7 +94,10 @@ export class Executor {
94
94
  try {
95
95
  // Run the tool inside THIS session's shell-key context so a persistent-shell tool (bash) picks
96
96
  // this session's own ShellSession, not a process-wide singleton shared with other sub-agents.
97
- const out = capToolResult(await shellKeyStore.run(this.shellKey, () => tool.run(args)), spillToolOutput);
97
+ const raw = await shellKeyStore.run(this.shellKey, () => tool.run(args));
98
+ // Semantic compression first (per-tool-type, keeps errors/head/tail), then the hard cap+spill.
99
+ const compressed = semanticCompress(raw, { toolName: name, toolArgs: args });
100
+ const out = capToolResult(compressed, spillToolOutput);
98
101
  // A file edit that LANDED changed the workspace, so prior identical-call counts are stale — re-running the
99
102
  // same test/build after an edit is verify-after-fix iteration, not a loop. Clear so repeats start fresh.
100
103
  // A FAILING edit ("error: old_string not found") changed nothing, so it must not reset the count.
@@ -116,14 +119,21 @@ export class Executor {
116
119
  }
117
120
  async executeParallel(calls, onSettle, signal) {
118
121
  // BTX: one shared DAG scheduler (engine/batch-scheduler.ts) — per-resource write chains,
119
- // reads wait only for conflicting prior writes, device tools barrier-serialize. This replaces
120
- // the 0.1.225 contiguous walk: same guarantees, strictly more overlap.
121
- return runBatch(calls, {
122
+ // reads wait only for conflicting prior writes, device tools barrier-serialize, independent
123
+ // bash/shell_exec overlap (shell kind). This replaces the 0.1.225 contiguous walk.
124
+ //
125
+ // Cursor-parity for shells: when this round has ≥2 bash/shell_exec calls, run them as ephemeral
126
+ // one-shots so the persistent ShellSession FIFO cannot serialize wall-clock. A lone bash still
127
+ // uses the persistent session (cwd/env + ctrl+b detach stick). See shellExecMode.
128
+ const SHELL_TOOLS = new Set(["bash", "shell_exec"]);
129
+ const shellCount = calls.reduce((n, c) => n + (SHELL_TOOLS.has(c.name) ? 1 : 0), 0);
130
+ const mode = shellCount >= 2 ? "ephemeral" : "persistent";
131
+ return shellExecMode.run(mode, () => runBatch(calls, {
122
132
  classify: this.sched.classify,
123
133
  keys: (n, a) => this.sched.keys(n, a),
124
134
  runOne: (c) => this.execute(c.name, c.args),
125
135
  onSettle,
126
136
  signal,
127
- });
137
+ }));
128
138
  }
129
139
  }
@@ -0,0 +1,483 @@
1
+ // find_files — "where is the file" across the machine, answered from the OS search index instead of a
2
+ // tree walk. One interface, one backend per OS (Spotlight / Windows Search / locate), and a bounded
3
+ // fallback (rg --files, then a capped fs walk) so the tool ALWAYS answers — a missing binary, a disabled
4
+ // index, a non-zero exit or a timeout degrades to a scan of ONE directory, never to a hard failure and
5
+ // never to an unbounded sweep of the home tree (the `find ~/ | grep` trap the system prompt forbids).
6
+ // Node builtins load lazily (see registry.ts) so this module stays out of the mobile bundle's static graph.
7
+ import { pexecFile } from "./exec.js";
8
+ import { expandPath } from "./paths.js";
9
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
10
+ function str(v, fallback = "") {
11
+ return v === undefined || v === null ? fallback : String(v);
12
+ }
13
+ export const FIND_FILES_DEFAULT_LIMIT = 50;
14
+ export const FIND_FILES_MAX_LIMIT = 500;
15
+ // Index backends can return tens of thousands of hits for a broad term; stat-sorting all of them would
16
+ // cost more than the search. Candidates are capped here BEFORE the stat pass; the trailer says "N+ more".
17
+ const MAX_CANDIDATES = 5000;
18
+ const EXEC_OPTS = { maxBuffer: 10 * 1024 * 1024, timeout: 60_000, killSignal: "SIGKILL" };
19
+ // Fallback walk bounds: deep enough for any project tree, shallow enough that a stray `/` or `~` scope
20
+ // (the model passing the wrong path) can't run for minutes.
21
+ const WALK_MAX_DEPTH = 12;
22
+ const WALK_MAX_ENTRIES = 200_000;
23
+ const WALK_SKIP = new Set([".git", "node_modules"]);
24
+ export const KINDS = ["any", "document", "pdf", "image", "video", "audio", "code", "folder"];
25
+ // Extension → kind, the one classification every backend can agree on: the fallback filters by it,
26
+ // `details` labels by it, and Windows Search (no "code" kind) and locate (no kinds at all) lean on it.
27
+ const KIND_EXTS = {
28
+ image: ["png", "jpg", "jpeg", "gif", "webp", "heic", "heif", "bmp", "tif", "tiff", "svg"],
29
+ video: ["mp4", "mov", "mkv", "avi", "webm", "m4v"],
30
+ audio: ["mp3", "wav", "m4a", "aac", "flac", "ogg", "aiff"],
31
+ pdf: ["pdf"],
32
+ document: ["pdf", "doc", "docx", "txt", "md", "rtf", "pages", "odt", "xls", "xlsx", "csv", "ppt", "pptx", "key", "numbers"],
33
+ code: ["ts", "tsx", "js", "jsx", "mjs", "cjs", "mts", "py", "rs", "go", "java", "c", "cc", "cpp", "h", "hpp", "cs", "swift", "kt", "rb", "php", "sh", "zsh", "sql", "json", "yaml", "yml", "toml", "html", "css"],
34
+ };
35
+ export function kindOfExtension(ext) {
36
+ const e = ext.toLowerCase();
37
+ for (const k of ["image", "video", "audio", "pdf", "code", "document"]) {
38
+ if (KIND_EXTS[k].includes(e))
39
+ return k;
40
+ }
41
+ return "any";
42
+ }
43
+ const baseOf = (p) => p.slice(Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\")) + 1);
44
+ const extOf = (p) => {
45
+ const base = baseOf(p);
46
+ const dot = base.lastIndexOf(".");
47
+ return dot > 0 ? base.slice(dot + 1).toLowerCase() : "";
48
+ };
49
+ const isAbsolute = (p) => /^([a-zA-Z]:[\\/]|[\\/])/.test(p);
50
+ const matchesKind = (p, kind, isDir) => {
51
+ if (kind === "any")
52
+ return true;
53
+ if (kind === "folder")
54
+ return isDir;
55
+ return !isDir && KIND_EXTS[kind].includes(extOf(p));
56
+ };
57
+ /** `7d` / `24h` / `30m` / `90s` → seconds; null when unparseable. */
58
+ export function parseDuration(s) {
59
+ const m = /^\s*(\d+(?:\.\d+)?)\s*([smhdw])\s*$/i.exec(s);
60
+ if (!m)
61
+ return null;
62
+ const mult = { s: 1, m: 60, h: 3600, d: 86_400, w: 604_800 };
63
+ return Math.round(Number(m[1]) * mult[m[2].toLowerCase()]);
64
+ }
65
+ /** `10MB` / `500KB` / `1.5GB` / `4096` → bytes (binary units); null when unparseable. */
66
+ export function parseSize(s) {
67
+ const m = /^\s*(\d+(?:\.\d+)?)\s*([kmgt]?)b?\s*$/i.exec(s);
68
+ if (!m)
69
+ return null;
70
+ const mult = { "": 1, k: 1024, m: 1024 ** 2, g: 1024 ** 3, t: 1024 ** 4 };
71
+ return Math.round(Number(m[1]) * mult[m[2].toLowerCase()]);
72
+ }
73
+ /** Validate + normalize the tool args. Returns an error string (the tool's reply) on bad input. */
74
+ export function parseSpec(args) {
75
+ const query = str(args.query).trim();
76
+ const name = str(args.name).trim();
77
+ const extension = str(args.extension).trim().replace(/^\./, "").toLowerCase() || undefined;
78
+ const kind = (str(args.kind, "any").toLowerCase() || "any");
79
+ if (!KINDS.includes(kind))
80
+ return `error: unknown kind "${args.kind}" — one of ${KINDS.join("|")}`;
81
+ const where = str(args.where).trim() || undefined;
82
+ const author = str(args.author).trim() || undefined;
83
+ const tags = Array.isArray(args.tags) ? args.tags.map(String).map((t) => t.trim()).filter(Boolean) : [];
84
+ let modifiedWithin;
85
+ if (args.modified_within !== undefined && args.modified_within !== null && str(args.modified_within).trim()) {
86
+ const secs = parseDuration(str(args.modified_within));
87
+ if (secs === null)
88
+ return `error: modified_within "${args.modified_within}" — use a number + unit like 30m, 24h, 7d, 2w`;
89
+ modifiedWithin = secs;
90
+ }
91
+ const sizes = { minSize: undefined, maxSize: undefined };
92
+ for (const [key, arg] of [["minSize", "min_size"], ["maxSize", "max_size"]]) {
93
+ if (args[arg] === undefined || args[arg] === null || !str(args[arg]).trim())
94
+ continue;
95
+ const bytes = parseSize(str(args[arg]));
96
+ if (bytes === null)
97
+ return `error: ${arg} "${args[arg]}" — use a number + unit like 500KB, 10MB, 1.5GB`;
98
+ sizes[key] = bytes;
99
+ }
100
+ if (!query && !name && !extension && kind === "any" && !where && !author && !tags.length && modifiedWithin === undefined && sizes.minSize === undefined && sizes.maxSize === undefined) {
101
+ return "error: give a query (words or a filename fragment) or at least one filter (name, extension, kind, modified_within, min_size, author, tags, where)";
102
+ }
103
+ let limit = Number(args.limit ?? FIND_FILES_DEFAULT_LIMIT);
104
+ if (!Number.isFinite(limit) || limit < 1)
105
+ limit = FIND_FILES_DEFAULT_LIMIT;
106
+ limit = Math.min(Math.floor(limit), FIND_FILES_MAX_LIMIT);
107
+ const path = str(args.path).trim();
108
+ return {
109
+ query, name, path: path ? expandPath(path).replace(/\/+$/, "") || "/" : undefined, kind, modifiedWithin, limit,
110
+ content: !!args.content, minSize: sizes.minSize, maxSize: sizes.maxSize, author, tags, extension, where,
111
+ details: !!args.details,
112
+ };
113
+ }
114
+ // ---- Spotlight (darwin) ------------------------------------------------------------------------------
115
+ const mdq = (s) => `"${s.replace(/["\\]/g, "\\$&")}"`;
116
+ // Content-type trees alone misclassify: macOS 12 types .md as an unknown dynamic UTI (so it was never a
117
+ // "document"), json/yaml/toml are not under public.source-code, and public.text swept every source file
118
+ // into "document". document and code therefore OR their UTI with the same extension list the fallback uses.
119
+ const extClause = (exts) => exts.map((e) => `kMDItemFSName == ${mdq(`*.${e}`)}c`).join(" || ");
120
+ const SPOTLIGHT_KIND = {
121
+ image: 'kMDItemContentTypeTree == "public.image"',
122
+ video: 'kMDItemContentTypeTree == "public.movie"',
123
+ audio: 'kMDItemContentTypeTree == "public.audio"',
124
+ pdf: 'kMDItemContentTypeTree == "com.adobe.pdf"',
125
+ code: `(kMDItemContentTypeTree == "public.source-code" || ${extClause(KIND_EXTS.code)})`,
126
+ folder: 'kMDItemContentType == "public.folder"',
127
+ document: `(kMDItemContentTypeTree == "public.composite-content" || ${extClause(KIND_EXTS.document)})`,
128
+ };
129
+ /** The Spotlight predicate for a spec — pure, so the escaping and the kind map are unit-testable. */
130
+ export function spotlightQuery(spec) {
131
+ const terms = [];
132
+ if (spec.query) {
133
+ const nameTerm = `kMDItemFSName == ${mdq(`*${spec.query}*`)}c`;
134
+ terms.push(spec.content ? `(${nameTerm} || kMDItemTextContent == ${mdq(spec.query)}cd)` : nameTerm);
135
+ }
136
+ if (spec.name)
137
+ terms.push(`kMDItemFSName == ${mdq(`*${spec.name}*`)}c`);
138
+ if (spec.extension)
139
+ terms.push(`kMDItemFSName == ${mdq(`*.${spec.extension}`)}c`);
140
+ if (spec.kind !== "any")
141
+ terms.push(SPOTLIGHT_KIND[spec.kind]);
142
+ if (spec.modifiedWithin !== undefined)
143
+ terms.push(`kMDItemFSContentChangeDate >= $time.now(-${spec.modifiedWithin})`);
144
+ if (spec.minSize !== undefined)
145
+ terms.push(`kMDItemFSSize >= ${spec.minSize}`);
146
+ if (spec.maxSize !== undefined)
147
+ terms.push(`kMDItemFSSize <= ${spec.maxSize}`);
148
+ if (spec.author)
149
+ terms.push(`kMDItemAuthors == ${mdq(`*${spec.author}*`)}cd`);
150
+ for (const t of spec.tags)
151
+ terms.push(`kMDItemUserTags == ${mdq(t)}cd`);
152
+ if (spec.where)
153
+ terms.push(`(${spec.where})`);
154
+ // A filter-only spec (e.g. kind + modified_within) still needs a name term for mdfind to accept it.
155
+ if (!terms.length)
156
+ terms.push('kMDItemFSName == "*"');
157
+ return terms.join(" && ");
158
+ }
159
+ export function spotlightArgs(spec, home) {
160
+ return ["-onlyin", spec.path ?? home, spotlightQuery(spec)];
161
+ }
162
+ // ---- Windows Search (win32) --------------------------------------------------------------------------
163
+ const sq = (s) => s.replace(/'/g, "''");
164
+ const WINDOWS_KIND = {
165
+ image: "System.Kind = 'picture'", video: "System.Kind = 'video'", audio: "System.Kind = 'music'",
166
+ document: "System.Kind = 'document'", folder: "System.Kind = 'folder'", pdf: "System.FileExtension = '.pdf'",
167
+ };
168
+ /** The SYSTEMINDEX SQL for a spec (newest-first, TOP = limit); pure so the quoting is testable. */
169
+ export function windowsSearchSql(spec, home, now = new Date()) {
170
+ const where = [];
171
+ if (spec.query) {
172
+ const nameTerm = `System.FileName LIKE '%${sq(spec.query)}%'`;
173
+ where.push(spec.content ? `(${nameTerm} OR CONTAINS(System.Search.Contents, '"${sq(spec.query)}"'))` : nameTerm);
174
+ }
175
+ if (spec.name)
176
+ where.push(`System.FileName LIKE '%${sq(spec.name)}%'`);
177
+ where.push(`SCOPE='file:${sq(spec.path ?? home)}'`);
178
+ if (spec.extension)
179
+ where.push(`System.FileExtension = '.${sq(spec.extension)}'`);
180
+ if (spec.kind === "code")
181
+ where.push(`System.FileExtension IN (${KIND_EXTS.code.map((e) => `'.${e}'`).join(", ")})`);
182
+ else if (spec.kind !== "any")
183
+ where.push(WINDOWS_KIND[spec.kind]);
184
+ if (spec.modifiedWithin !== undefined)
185
+ where.push(`System.DateModified >= '${new Date(now.getTime() - spec.modifiedWithin * 1000).toISOString()}'`);
186
+ if (spec.minSize !== undefined)
187
+ where.push(`System.Size >= ${spec.minSize}`);
188
+ if (spec.maxSize !== undefined)
189
+ where.push(`System.Size <= ${spec.maxSize}`);
190
+ if (spec.author)
191
+ where.push(`System.Author LIKE '%${sq(spec.author)}%'`);
192
+ for (const t of spec.tags)
193
+ where.push(`System.Keywords = '${sq(t)}'`);
194
+ if (spec.where)
195
+ where.push(`(${spec.where})`);
196
+ return `SELECT TOP ${spec.limit} System.ItemPathDisplay FROM SYSTEMINDEX WHERE ${where.join(" AND ")} ORDER BY System.DateModified DESC`;
197
+ }
198
+ /** One `powershell -Command` string: OleDb over Search.CollatorDSO, one path per line. The SQL rides
199
+ * inside a PowerShell single-quoted literal (quotes doubled) so no `$`/backtick expansion can touch it. */
200
+ export function windowsSearchCommand(spec, home, now = new Date()) {
201
+ const sql = windowsSearchSql(spec, home, now);
202
+ return "$c = New-Object System.Data.OleDb.OleDbConnection 'Provider=Search.CollatorDSO;Extended Properties=\"Application=Windows\"'; " +
203
+ `$c.Open(); $q = New-Object System.Data.OleDb.OleDbCommand('${sq(sql)}', $c); $r = $q.ExecuteReader(); ` +
204
+ "while ($r.Read()) { $r.GetString(0) }; $c.Close()";
205
+ }
206
+ /** Everything (es.exe) argv for name-only searches — faster than the Windows index when installed. */
207
+ export function everythingArgs(spec) {
208
+ const args = ["-sort", "dm", "-n", String(Math.min(MAX_CANDIDATES, spec.limit * 20))];
209
+ if (spec.path)
210
+ args.push("-path", spec.path);
211
+ if (spec.extension)
212
+ args.push(`ext:${spec.extension}`);
213
+ if (spec.query)
214
+ args.push(spec.query);
215
+ if (spec.name)
216
+ args.push(spec.name);
217
+ return args;
218
+ }
219
+ const everythingEligible = (spec) => !spec.content && !spec.where && !spec.author && !spec.tags.length && (!!spec.query || !!spec.name);
220
+ // ---- locate (linux) ----------------------------------------------------------------------------------
221
+ /** plocate/locate argv: case-insensitive name match; everything else is post-filtered in JS. */
222
+ export function locateArgs(spec, bin) {
223
+ const term = spec.name || spec.query || (spec.extension ? `.${spec.extension}` : "");
224
+ return bin === "plocate" ? ["-i", "-l", String(MAX_CANDIDATES), term] : ["-i", term];
225
+ }
226
+ export function trackerArgs(spec) {
227
+ return ["search", "--files", "--limit", String(MAX_CANDIDATES), spec.query];
228
+ }
229
+ // `tracker3 search --files` prints indented `file://` URLs (and a "Results:" header); keep only paths.
230
+ export function trackerPaths(stdout) {
231
+ return stdout.split("\n").map((l) => l.trim()).filter((l) => l.startsWith("file://")).map((l) => {
232
+ try {
233
+ return decodeURIComponent(l.slice("file://".length));
234
+ }
235
+ catch {
236
+ return l.slice("file://".length);
237
+ }
238
+ });
239
+ }
240
+ const lines = (stdout) => stdout.split("\n").map((l) => l.trim()).filter(Boolean);
241
+ class IndexUnavailable extends Error {
242
+ }
243
+ const INDEX_FILTERS = ["path", "name", "extension", "kind", "modified", "size", "content"];
244
+ // `mdfind` on a volume whose Spotlight index is off prints NOTHING and exits 0 — indistinguishable from
245
+ // "no matches". Only an empty result pays for the `mdutil -s` disambiguation, so the hit path costs one exec.
246
+ async function spotlight(spec, deps) {
247
+ const { stdout } = await deps.exec("mdfind", spotlightArgs(spec, deps.home), EXEC_OPTS);
248
+ const paths = lines(stdout);
249
+ if (!paths.length) {
250
+ try {
251
+ // mdutil answers for a VOLUME ("/"); a sub-directory gets "unknown indexing state".
252
+ const st = await deps.exec("mdutil", ["-s", "/"], { ...EXEC_OPTS, timeout: 10_000 });
253
+ if (/disabled/i.test(st.stdout + st.stderr))
254
+ throw new IndexUnavailable("Spotlight indexing is disabled");
255
+ }
256
+ catch (e) {
257
+ if (e instanceof IndexUnavailable)
258
+ throw e;
259
+ if (/disabled/i.test(String(e?.stdout ?? "") + String(e?.stderr ?? "")))
260
+ throw new IndexUnavailable("Spotlight indexing is disabled");
261
+ }
262
+ }
263
+ return { paths, applied: new Set(INDEX_FILTERS) };
264
+ }
265
+ async function windowsSearch(spec, deps) {
266
+ if (everythingEligible(spec)) {
267
+ try {
268
+ const { stdout } = await deps.exec("es.exe", everythingArgs(spec), EXEC_OPTS);
269
+ return { paths: lines(stdout), applied: new Set(["path", "name", "extension"]) };
270
+ }
271
+ catch (e) {
272
+ if (e?.code !== "ENOENT")
273
+ throw e; // Everything present but failing → surface, don't double-search
274
+ }
275
+ }
276
+ const { stdout } = await deps.exec("powershell", ["-NoProfile", "-NonInteractive", "-Command", windowsSearchCommand(spec, deps.home)], EXEC_OPTS);
277
+ return { paths: lines(stdout), applied: new Set(INDEX_FILTERS) };
278
+ }
279
+ async function locate(spec, deps) {
280
+ if (spec.content && spec.query) {
281
+ try {
282
+ const { stdout } = await deps.exec("tracker3", trackerArgs(spec), EXEC_OPTS);
283
+ return { paths: trackerPaths(stdout), applied: new Set(["content"]) };
284
+ }
285
+ catch (e) {
286
+ if (e?.code !== "ENOENT")
287
+ throw e;
288
+ }
289
+ }
290
+ if (spec.where)
291
+ throw new IndexUnavailable("locate has no predicate syntax");
292
+ try {
293
+ const { stdout } = await deps.exec("plocate", locateArgs(spec, "plocate"), EXEC_OPTS);
294
+ return { paths: lines(stdout), applied: new Set(["name"]) };
295
+ }
296
+ catch (e) {
297
+ if (e?.code !== "ENOENT")
298
+ throw e;
299
+ }
300
+ const { stdout } = await deps.exec("locate", locateArgs(spec, "locate"), EXEC_OPTS);
301
+ return { paths: lines(stdout), applied: new Set(["name"]) };
302
+ }
303
+ const BACKENDS = {
304
+ darwin: { name: "Spotlight", run: spotlight },
305
+ win32: { name: "Windows Search", run: windowsSearch },
306
+ linux: { name: "locate", run: locate },
307
+ };
308
+ // Fallback: rg --files (gitignore-aware, skips hidden — same scoping as the `search` tool) over ONE
309
+ // directory, or a bounded fs walk when rg is absent. Name/extension/kind/mtime/size are all applied in JS
310
+ // afterwards, so rg's glob is only a pre-filter and a differing glob dialect can never drop a hit.
311
+ async function fallbackScan(spec, root, deps) {
312
+ const frag = spec.name || spec.query;
313
+ const rgArgs = spec.content && spec.query
314
+ ? ["-l", "--fixed-strings", "-i", "--color=never", "--no-messages", "-e", spec.query]
315
+ : ["--files", "--color=never", "--no-messages"];
316
+ if (!spec.content && (frag || spec.extension))
317
+ rgArgs.push("-g", `*${frag}*${spec.extension ? `.${spec.extension}` : ""}`);
318
+ rgArgs.push(root);
319
+ try {
320
+ const { stdout } = await deps.exec("rg", rgArgs, EXEC_OPTS);
321
+ return { paths: lines(stdout), via: "rg" };
322
+ }
323
+ catch (e) {
324
+ if (e?.stdout && String(e.stdout).trim())
325
+ return { paths: lines(String(e.stdout)), via: "rg" };
326
+ if (e?.code === 1)
327
+ return { paths: [], via: "rg" }; // rg: 1 = no match
328
+ // ENOENT (not installed), killed (timeout) or exit 2 (unreadable root) → the bounded walk
329
+ }
330
+ return { paths: await walk(root), via: "walk" };
331
+ }
332
+ async function walk(root) {
333
+ const { readdir } = await nodeImport("node:fs/promises");
334
+ const out = [];
335
+ const stack = [{ dir: root, depth: 0 }];
336
+ let seen = 0;
337
+ while (stack.length && seen < WALK_MAX_ENTRIES) {
338
+ const { dir, depth } = stack.pop();
339
+ let entries;
340
+ try {
341
+ entries = await readdir(dir, { withFileTypes: true });
342
+ }
343
+ catch {
344
+ continue;
345
+ }
346
+ for (const e of entries) {
347
+ if (++seen > WALK_MAX_ENTRIES)
348
+ break;
349
+ const full = `${dir === "/" ? "" : dir}/${e.name}`;
350
+ out.push(full);
351
+ if (e.isDirectory() && !WALK_SKIP.has(e.name) && depth < WALK_MAX_DEPTH)
352
+ stack.push({ dir: full, depth: depth + 1 });
353
+ }
354
+ }
355
+ return out;
356
+ }
357
+ // One stat pass does triple duty: newest-first ordering (no backend sorts for us except Windows), the
358
+ // JS-side filters the backend didn't apply, and the `details` columns. Stale index entries (file gone)
359
+ // drop out here instead of being reported.
360
+ async function statAll(paths) {
361
+ const { stat } = await nodeImport("node:fs/promises");
362
+ const hits = [];
363
+ const CHUNK = 64;
364
+ for (let i = 0; i < paths.length; i += CHUNK) {
365
+ const part = await Promise.all(paths.slice(i, i + CHUNK).map(async (p) => {
366
+ try {
367
+ const s = await stat(p);
368
+ return { path: p, mtimeMs: s.mtimeMs, size: s.size, isDir: s.isDirectory() };
369
+ }
370
+ catch {
371
+ return null;
372
+ }
373
+ }));
374
+ for (const h of part)
375
+ if (h)
376
+ hits.push(h);
377
+ }
378
+ return hits;
379
+ }
380
+ function applyFilters(hits, spec, applied, now) {
381
+ const lower = (s) => s.toLowerCase();
382
+ // `query` is a name term unless the backend already matched it against content.
383
+ const queryByName = spec.query && !(spec.content && applied.has("content"));
384
+ return hits.filter((h) => {
385
+ const base = lower(baseOf(h.path));
386
+ if (!applied.has("path") && spec.path && h.path !== spec.path && !h.path.startsWith(`${spec.path}/`))
387
+ return false;
388
+ if (!applied.has("name")) {
389
+ if (spec.name && !base.includes(lower(spec.name)))
390
+ return false;
391
+ if (queryByName && !base.includes(lower(spec.query)))
392
+ return false;
393
+ }
394
+ if (!applied.has("extension") && spec.extension && extOf(h.path) !== spec.extension)
395
+ return false;
396
+ if (!applied.has("kind") && !matchesKind(h.path, spec.kind, h.isDir))
397
+ return false;
398
+ if (!applied.has("modified") && spec.modifiedWithin !== undefined && h.mtimeMs < now - spec.modifiedWithin * 1000)
399
+ return false;
400
+ if (!applied.has("size")) {
401
+ if (spec.minSize !== undefined && h.size < spec.minSize)
402
+ return false;
403
+ if (spec.maxSize !== undefined && h.size > spec.maxSize)
404
+ return false;
405
+ }
406
+ return true;
407
+ });
408
+ }
409
+ export function formatHits(hits, spec, header, capped) {
410
+ const shown = hits.slice(0, spec.limit).map((h) => {
411
+ if (!spec.details)
412
+ return h.path;
413
+ const byExt = kindOfExtension(extOf(h.path));
414
+ const kind = h.isDir ? "folder" : byExt === "any" ? "file" : byExt;
415
+ return `${h.path}\t${h.size}\t${new Date(h.mtimeMs).toISOString()}\t${kind}`;
416
+ });
417
+ const out = [...header];
418
+ if (!shown.length)
419
+ out.push("(no matches)");
420
+ else
421
+ out.push(...shown);
422
+ if (hits.length > spec.limit)
423
+ out.push(`…[${hits.length - spec.limit}${capped ? "+" : ""} more]`);
424
+ return out.join("\n");
425
+ }
426
+ export const defaultDeps = () => ({
427
+ platform: process.platform, exec: pexecFile, env: process.env, cwd: process.cwd(),
428
+ home: process.env.HOME ?? process.env.USERPROFILE ?? process.cwd(),
429
+ });
430
+ export async function findFiles(args, deps = defaultDeps()) {
431
+ const spec = parseSpec(args);
432
+ if (typeof spec === "string")
433
+ return spec;
434
+ if (spec.path && !isAbsolute(spec.path)) {
435
+ const { resolve } = await nodeImport("node:path");
436
+ spec.path = resolve(deps.cwd, spec.path); // scope filtering is a prefix test, so it needs an absolute root
437
+ }
438
+ const now = Date.now();
439
+ const header = [];
440
+ let paths = [];
441
+ let applied = new Set();
442
+ // FIND_FILES_BACKEND=none skips the index on purpose — the knob that lets the fallback be driven and
443
+ // tested on a machine whose index works (and the escape hatch if an index is returning garbage).
444
+ const backend = deps.env.FIND_FILES_BACKEND === "none" ? undefined : BACKENDS[deps.platform];
445
+ let reason = backend ? "" : (deps.env.FIND_FILES_BACKEND === "none" ? "FIND_FILES_BACKEND=none" : `no index backend for ${deps.platform}`);
446
+ if (backend) {
447
+ try {
448
+ const r = await backend.run(spec, deps);
449
+ paths = r.paths;
450
+ applied = r.applied;
451
+ }
452
+ catch (e) {
453
+ if (e instanceof IndexUnavailable)
454
+ reason = e.message;
455
+ else if (e?.code === "ENOENT")
456
+ reason = `${backend.name} binary not found`;
457
+ else if (e?.killed)
458
+ reason = `${backend.name} timed out`;
459
+ else
460
+ reason = `${backend.name} failed: ${String(e?.stderr || e?.message || e).trim().split("\n")[0]}`;
461
+ }
462
+ }
463
+ if (reason) {
464
+ if (spec.where)
465
+ return `error: \`where\` needs the OS search index (${reason}) — drop \`where\`, or use the search tool for content`;
466
+ const root = spec.path ?? deps.cwd;
467
+ const notes = [];
468
+ if (spec.author)
469
+ notes.push("author ignored");
470
+ if (spec.tags.length)
471
+ notes.push("tags ignored");
472
+ const scan = await fallbackScan(spec, root, deps);
473
+ if (spec.content && scan.via === "walk")
474
+ notes.push("content matched by name only (no ripgrep)");
475
+ header.push(`(index unavailable — scanned ${root}${notes.length ? `; ${notes.join(", ")}` : ""})`);
476
+ paths = scan.paths;
477
+ applied = new Set(spec.content && scan.via === "rg" ? ["content"] : []);
478
+ }
479
+ const capped = paths.length > MAX_CANDIDATES;
480
+ const hits = applyFilters(await statAll(paths.slice(0, MAX_CANDIDATES)), spec, applied, now);
481
+ hits.sort((a, b) => b.mtimeMs - a.mtimeMs);
482
+ return formatHits(hits, spec, header, capped);
483
+ }
@@ -0,0 +1,94 @@
1
+ // git_pr tool — open|status|list PRs via gh CLI.
2
+ // Transfers PR lifecycle into a normal session (today requires spawn_cloud_agent).
3
+ // All external commands use execFile (lazy import) — NO shell strings, NO interpolation.
4
+ // Title/body ride as argv elements. Zero AI trailers in anything written.
5
+ // safe:false — open pushes to origin and creates a real PR; status/list are read-only gh calls but
6
+ // ride the same action under one approval-gated tool rather than splitting by mutation risk.
7
+ import { expandPath } from "./paths.js";
8
+ import { pexecFile } from "./exec.js"; // the shared lazy execFile (git-pr.ts briefly carried its own
9
+ function str(v, fallback = "") {
10
+ return typeof v === "string" && v ? v : (fallback ?? "");
11
+ }
12
+ const EXEC_OPTS = { encoding: "utf8", maxBuffer: 10 * 1024 * 1024 }; // shared pexecFile leaves maxBuffer at node's 1MB default — gh/git output can exceed that
13
+ async function gh(args, cwd) {
14
+ try {
15
+ const { stdout } = await pexecFile("gh", args, { ...EXEC_OPTS, cwd });
16
+ return stdout.trim() || "(no output)";
17
+ }
18
+ catch (e) {
19
+ return `error: ${e.message || e.stderr || "gh command failed"}`;
20
+ }
21
+ }
22
+ async function git(args, cwd) {
23
+ try {
24
+ const { stdout } = await pexecFile("git", args, { ...EXEC_OPTS, cwd });
25
+ return stdout.trim() || "(no output)";
26
+ }
27
+ catch (e) {
28
+ return `error: ${e.message || e.stderr || "git command failed"}`;
29
+ }
30
+ }
31
+ export async function gitPr(args) {
32
+ const action = str(args.action);
33
+ const cwd = args.cwd ? expandPath(str(args.cwd)) : undefined;
34
+ const repo = str(args.repo, "");
35
+ switch (action) {
36
+ case "open": {
37
+ if (!cwd)
38
+ return "error: cwd required for open";
39
+ const branch = await git(["rev-parse", "--abbrev-ref", "HEAD"], cwd);
40
+ if (branch.startsWith("error:") || branch === "HEAD") {
41
+ return "error: not on a branch (detached HEAD?)";
42
+ }
43
+ const remoteUrl = await git(["remote", "get-url", "origin"], cwd);
44
+ if (remoteUrl.startsWith("error:")) {
45
+ return "error: no origin remote configured";
46
+ }
47
+ const pushOut = await git(["push", "-u", "origin", branch], cwd);
48
+ if (pushOut.startsWith("error:")) {
49
+ return `error: push failed — ${pushOut}`;
50
+ }
51
+ const title = str(args.title, `feat: ${branch}`);
52
+ const body = str(args.body, "");
53
+ const prArgs = ["pr", "create", "--head", branch, "--title", title];
54
+ if (body)
55
+ prArgs.push("--body", body);
56
+ if (repo)
57
+ prArgs.push("--repo", repo);
58
+ const prOut = await gh(prArgs, cwd);
59
+ if (prOut.startsWith("error:"))
60
+ return prOut;
61
+ const urlMatch = prOut.match(/https:\/\/github\.com\/[^\/]+\/[^\/]+\/pull\/\d+/);
62
+ const url = urlMatch ? urlMatch[0] : prOut;
63
+ return `PR opened: ${url}\n${prOut}`;
64
+ }
65
+ case "status": {
66
+ if (!cwd)
67
+ return "error: cwd required for status";
68
+ return gh(["pr", "status", "--repo", repo].filter(Boolean), cwd);
69
+ }
70
+ case "list": {
71
+ if (!repo)
72
+ return "error: repo required for list (e.g. owner/repo)";
73
+ return gh(["pr", "list", "--repo", repo], cwd);
74
+ }
75
+ default:
76
+ return `error: unknown action '${action}'. Valid: open, status, list`;
77
+ }
78
+ }
79
+ // ─── export ─────────────────────────────────────────────────────────────────
80
+ export const GIT_PR_TOOLS = [
81
+ {
82
+ name: "git_pr", safe: false,
83
+ description: "Open, check status of, or list pull requests via the gh CLI — open pushes the current " +
84
+ "branch and creates a real PR, so it needs approval like any other write.",
85
+ parameters: { type: "object", properties: {
86
+ action: { type: "string", enum: ["open", "status", "list"] },
87
+ cwd: { type: "string", description: "repo working directory (required for open/status)" },
88
+ repo: { type: "string", description: "owner/repo — required for list, optional override for open/status" },
89
+ title: { type: "string", description: "open: PR title (default 'feat: <branch>')" },
90
+ body: { type: "string", description: "open: PR body" },
91
+ }, required: ["action"] },
92
+ run: gitPr,
93
+ },
94
+ ];