@andorra-labs/code 0.1.15 → 0.1.17

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 (242) hide show
  1. package/dist/src/acp-agent.d.ts +6 -0
  2. package/dist/src/acp-agent.js +15 -4
  3. package/dist/src/agent-definitions.js +29 -6
  4. package/dist/src/agent-execution.js +15 -10
  5. package/dist/src/agent-mcp-catalog.js +1 -0
  6. package/dist/src/agent-mcp.d.ts +4 -1
  7. package/dist/src/agent-mcp.js +46 -10
  8. package/dist/src/andorra/entry.d.ts +10 -0
  9. package/dist/src/andorra/entry.js +18 -4
  10. package/dist/src/andorra/hosted.d.ts +2 -1
  11. package/dist/src/andorra/hosted.js +2 -1
  12. package/dist/src/andorra/notices.d.ts +5 -0
  13. package/dist/src/andorra/notices.js +7 -0
  14. package/dist/src/andorra/state.d.ts +3 -2
  15. package/dist/src/andorra/state.js +4 -4
  16. package/dist/src/andorra/terminal.js +7 -2
  17. package/dist/src/anthropic-credentials.js +2 -0
  18. package/dist/src/app-server/error.d.ts +5 -0
  19. package/dist/src/app-server/error.js +7 -0
  20. package/dist/src/app-server/protocol.d.ts +22 -44
  21. package/dist/src/app-server/protocol.js +5 -1
  22. package/dist/src/app-server/workspace.d.ts +89 -0
  23. package/dist/src/app-server/workspace.js +457 -11
  24. package/dist/src/app-server.d.ts +465 -32
  25. package/dist/src/app-server.js +3308 -517
  26. package/dist/src/auth/deployment.js +2 -2
  27. package/dist/src/bridge/cloud.d.ts +27 -0
  28. package/dist/src/bridge/cloud.js +187 -0
  29. package/dist/src/bridge/command.d.ts +30 -0
  30. package/dist/src/bridge/command.js +347 -0
  31. package/dist/src/bridge/control.d.ts +68 -0
  32. package/dist/src/bridge/control.js +233 -0
  33. package/dist/src/bridge/engines.d.ts +90 -0
  34. package/dist/src/bridge/engines.js +601 -0
  35. package/dist/src/bridge/host-ops.d.ts +9 -0
  36. package/dist/src/bridge/host-ops.js +129 -0
  37. package/dist/src/bridge/host.d.ts +47 -0
  38. package/dist/src/bridge/host.js +540 -0
  39. package/dist/src/bridge/link.d.ts +38 -0
  40. package/dist/src/bridge/link.js +508 -0
  41. package/dist/src/bridge/login-link.d.ts +29 -0
  42. package/dist/src/bridge/login-link.js +54 -0
  43. package/dist/src/bridge/protocol.d.ts +136 -0
  44. package/dist/src/bridge/protocol.js +11 -0
  45. package/dist/src/bridge/store.d.ts +12 -0
  46. package/dist/src/bridge/store.js +61 -0
  47. package/dist/src/bridge/wording.d.ts +6 -0
  48. package/dist/src/bridge/wording.js +10 -0
  49. package/dist/src/browser-runner.js +1 -0
  50. package/dist/src/browser-server.js +7 -1
  51. package/dist/src/browser-ui/style.css +3 -3
  52. package/dist/src/browser-ui/tokens.css +28 -17
  53. package/dist/src/change-authors.d.ts +41 -0
  54. package/dist/src/change-authors.js +146 -0
  55. package/dist/src/claude-provider.js +3 -1
  56. package/dist/src/cli.js +202 -38
  57. package/dist/src/codex-errors.js +4 -1
  58. package/dist/src/coding-tools.js +15 -15
  59. package/dist/src/command-screens.d.ts +6 -0
  60. package/dist/src/command-screens.js +19 -14
  61. package/dist/src/commands.d.ts +14 -1
  62. package/dist/src/compaction-phrases.d.ts +4 -0
  63. package/dist/src/compaction-phrases.js +20 -0
  64. package/dist/src/completion.js +82 -5
  65. package/dist/src/config.d.ts +71 -3
  66. package/dist/src/config.js +202 -77
  67. package/dist/src/context-compaction.js +2 -1
  68. package/dist/src/deadline.js +13 -1
  69. package/dist/src/decision/DecisionManager.js +3 -2
  70. package/dist/src/decision/checks.js +1 -1
  71. package/dist/src/decision/requestPhrases.d.ts +4 -0
  72. package/dist/src/decision/requestPhrases.js +22 -0
  73. package/dist/src/default-graph.js +1 -1
  74. package/dist/src/file-diff.d.ts +4 -0
  75. package/dist/src/file-diff.js +2 -1
  76. package/dist/src/github-app/agent-writes.d.ts +102 -0
  77. package/dist/src/github-app/agent-writes.js +320 -0
  78. package/dist/src/github-app/client.d.ts +349 -0
  79. package/dist/src/github-app/client.js +810 -0
  80. package/dist/src/github-app/event-source.d.ts +208 -0
  81. package/dist/src/github-app/event-source.js +684 -0
  82. package/dist/src/github-app/metrics.d.ts +32 -0
  83. package/dist/src/github-app/metrics.js +49 -0
  84. package/dist/src/github-app/review-loop.d.ts +274 -0
  85. package/dist/src/github-app/review-loop.js +1177 -0
  86. package/dist/src/github-app/review-node.d.ts +81 -0
  87. package/dist/src/github-app/review-node.js +205 -0
  88. package/dist/src/github-app/review-post.d.ts +73 -0
  89. package/dist/src/github-app/review-post.js +139 -0
  90. package/dist/src/github-app/review-text.d.ts +107 -0
  91. package/dist/src/github-app/review-text.js +1133 -0
  92. package/dist/src/github-app/review-threads.d.ts +47 -0
  93. package/dist/src/github-app/review-threads.js +107 -0
  94. package/dist/src/github-app/reviewer.d.ts +121 -0
  95. package/dist/src/github-app/reviewer.js +598 -0
  96. package/dist/src/github-app/store.d.ts +59 -0
  97. package/dist/src/github-app/store.js +148 -0
  98. package/dist/src/github-app/triggers.d.ts +141 -0
  99. package/dist/src/github-app/triggers.js +441 -0
  100. package/dist/src/github-inbox.d.ts +55 -0
  101. package/dist/src/github-inbox.js +153 -0
  102. package/dist/src/github-names.d.ts +8 -0
  103. package/dist/src/github-names.js +8 -0
  104. package/dist/src/glob-search.d.ts +61 -0
  105. package/dist/src/glob-search.js +180 -0
  106. package/dist/src/graph-health.js +13 -4
  107. package/dist/src/graph-manager-chat.js +1 -1
  108. package/dist/src/graph-preview.d.ts +46 -0
  109. package/dist/src/graph-preview.js +55 -0
  110. package/dist/src/graph-provider-portability.js +34 -11
  111. package/dist/src/graph-quota.d.ts +29 -2
  112. package/dist/src/graph-quota.js +68 -10
  113. package/dist/src/graph-runner.js +88 -10
  114. package/dist/src/graph-server.d.ts +1 -1
  115. package/dist/src/graph-server.js +11 -9
  116. package/dist/src/graph-sync.js +3 -3
  117. package/dist/src/graph-ui/app.js +201 -40
  118. package/dist/src/graph-ui/controls.css +1 -0
  119. package/dist/src/graph-ui/embed.js +2 -2
  120. package/dist/src/graph-ui/icons.js +3 -1
  121. package/dist/src/graph-ui/index.html +1 -1
  122. package/dist/src/graph-ui/manager.css +1 -1
  123. package/dist/src/graph-ui/manager.js +2 -2
  124. package/dist/src/graph-ui/sidebar.js +30 -0
  125. package/dist/src/graph-ui/studio-canvas.js +26 -13
  126. package/dist/src/graph-ui/studio.css +15 -7
  127. package/dist/src/graph-ui/studio.js +26 -5
  128. package/dist/src/graph-ui/style.css +77 -45
  129. package/dist/src/graph-ui/theme.js +3 -36
  130. package/dist/src/graph-ui/tokens.css +28 -20
  131. package/dist/src/graphs.d.ts +34 -1
  132. package/dist/src/graphs.js +162 -17
  133. package/dist/src/image-input.d.ts +16 -0
  134. package/dist/src/image-input.js +41 -0
  135. package/dist/src/membership.d.ts +30 -1
  136. package/dist/src/membership.js +48 -8
  137. package/dist/src/model-health-cache.js +1 -1
  138. package/dist/src/model-metadata.d.ts +7 -1
  139. package/dist/src/model-metadata.js +39 -17
  140. package/dist/src/model-relay/local.d.ts +116 -0
  141. package/dist/src/model-relay/local.js +468 -0
  142. package/dist/src/model-relay/remote.d.ts +129 -0
  143. package/dist/src/model-relay/remote.js +252 -0
  144. package/dist/src/model-relay/runs.d.ts +34 -0
  145. package/dist/src/model-relay/runs.js +146 -0
  146. package/dist/src/model-relay/wire.d.ts +5 -0
  147. package/dist/src/model-relay/wire.js +5 -0
  148. package/dist/src/plan-pass.d.ts +59 -0
  149. package/dist/src/plan-pass.js +165 -0
  150. package/dist/src/project-registry.d.ts +21 -0
  151. package/dist/src/project-registry.js +74 -0
  152. package/dist/src/provider-engine.js +3 -0
  153. package/dist/src/provider-import.d.ts +0 -12
  154. package/dist/src/provider-import.js +7 -195
  155. package/dist/src/providers.d.ts +40 -2
  156. package/dist/src/providers.js +93 -23
  157. package/dist/src/pull-request-checks.d.ts +26 -0
  158. package/dist/src/pull-request-checks.js +56 -0
  159. package/dist/src/pull-request-conversation.d.ts +134 -0
  160. package/dist/src/pull-request-conversation.js +221 -0
  161. package/dist/src/pull-request-create.d.ts +175 -0
  162. package/dist/src/pull-request-create.js +392 -0
  163. package/dist/src/pull-request-details.d.ts +242 -0
  164. package/dist/src/pull-request-details.js +614 -0
  165. package/dist/src/pull-request-edit.d.ts +23 -0
  166. package/dist/src/pull-request-edit.js +91 -0
  167. package/dist/src/pull-request-logs.d.ts +87 -0
  168. package/dist/src/pull-request-logs.js +183 -0
  169. package/dist/src/pull-request-merge.d.ts +112 -0
  170. package/dist/src/pull-request-merge.js +258 -0
  171. package/dist/src/pull-request-review.d.ts +137 -0
  172. package/dist/src/pull-request-review.js +401 -0
  173. package/dist/src/pull-requests.d.ts +369 -8
  174. package/dist/src/pull-requests.js +524 -55
  175. package/dist/src/react-runtime.js +38 -5
  176. package/dist/src/remote/engine-pool.d.ts +88 -4
  177. package/dist/src/remote/engine-pool.js +379 -90
  178. package/dist/src/remote/roots.d.ts +19 -0
  179. package/dist/src/remote/roots.js +45 -7
  180. package/dist/src/remote/types.d.ts +0 -44
  181. package/dist/src/run-control.d.ts +17 -0
  182. package/dist/src/run-control.js +47 -0
  183. package/dist/src/run-progress.d.ts +10 -0
  184. package/dist/src/run-progress.js +122 -0
  185. package/dist/src/run-records.d.ts +7 -2
  186. package/dist/src/run-records.js +71 -6
  187. package/dist/src/runtime.d.ts +9 -1
  188. package/dist/src/runtime.js +24 -4
  189. package/dist/src/session-changes.d.ts +35 -0
  190. package/dist/src/session-changes.js +194 -6
  191. package/dist/src/session-monitor.js +2 -1
  192. package/dist/src/session-reaper.d.ts +1 -1
  193. package/dist/src/session-reaper.js +6 -1
  194. package/dist/src/session-summary.d.ts +2 -1
  195. package/dist/src/session-summary.js +2 -1
  196. package/dist/src/sessions.d.ts +11 -1
  197. package/dist/src/sessions.js +17 -4
  198. package/dist/src/skills/bundled/diagram/SKILL.md +5 -3
  199. package/dist/src/skills/bundled/graph-manager/SKILL.md +7 -4
  200. package/dist/src/skills/bundled/provenance.json +2 -2
  201. package/dist/src/skills/runtime-skills.js +1 -1
  202. package/dist/src/subagent-run.js +1 -0
  203. package/dist/src/telemetry/capture-core.d.ts +17 -0
  204. package/dist/src/telemetry/capture-core.js +59 -1
  205. package/dist/src/telemetry/classify.d.ts +3 -1
  206. package/dist/src/telemetry/classify.js +37 -0
  207. package/dist/src/telemetry/emitter.d.ts +17 -0
  208. package/dist/src/telemetry/emitter.js +76 -5
  209. package/dist/src/telemetry/schema.d.ts +47 -2
  210. package/dist/src/telemetry/schema.js +120 -5
  211. package/dist/src/telemetry/surface.d.ts +3 -1
  212. package/dist/src/telemetry/surface.js +4 -1
  213. package/dist/src/telemetry/uploader.d.ts +6 -1
  214. package/dist/src/telemetry/uploader.js +22 -3
  215. package/dist/src/terminal-ui.d.ts +1 -0
  216. package/dist/src/terminal-ui.js +10 -3
  217. package/dist/src/test-edit-guard.d.ts +7 -0
  218. package/dist/src/test-edit-guard.js +49 -1
  219. package/dist/src/timers.d.ts +2 -0
  220. package/dist/src/tools.js +59 -9
  221. package/dist/src/transcript.js +8 -2
  222. package/dist/src/types.d.ts +7 -0
  223. package/dist/src/usage-analytics.js +18 -10
  224. package/package.json +6 -1
  225. package/dist/src/remote/cert.d.ts +0 -11
  226. package/dist/src/remote/cert.js +0 -87
  227. package/dist/src/remote/client.d.ts +0 -119
  228. package/dist/src/remote/client.js +0 -544
  229. package/dist/src/remote/command.d.ts +0 -4
  230. package/dist/src/remote/command.js +0 -194
  231. package/dist/src/remote/errors.d.ts +0 -11
  232. package/dist/src/remote/errors.js +0 -14
  233. package/dist/src/remote/network.d.ts +0 -22
  234. package/dist/src/remote/network.js +0 -102
  235. package/dist/src/remote/pairing.d.ts +0 -63
  236. package/dist/src/remote/pairing.js +0 -299
  237. package/dist/src/remote/pem.d.ts +0 -2
  238. package/dist/src/remote/pem.js +0 -7
  239. package/dist/src/remote/serve.d.ts +0 -68
  240. package/dist/src/remote/serve.js +0 -244
  241. package/dist/src/remote/server.d.ts +0 -21
  242. package/dist/src/remote/server.js +0 -406
@@ -1,13 +1,18 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
2
3
  import { createReadStream } from 'node:fs';
3
4
  import { opendir, open, readFile, readdir, realpath, stat } from 'node:fs/promises';
4
5
  import { StringDecoder } from 'node:string_decoder';
5
- import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
+ import { dirname, isAbsolute, join, matchesGlob as pathMatchesGlob, posix, relative, resolve, sep } from 'node:path';
6
7
  import { runRecordPath, runRecordsDirectory, sessionHasOpenRun } from '../run-records.js';
7
8
  import { validSavedSession } from '../sessions.js';
8
9
  import { listBundles } from '../extensions.js';
9
10
  import { builtinSkillEntries } from '../skills/invocable-skills.js';
10
- const SKIP_NAMES = new Set(['.git', 'node_modules', '.andorracode']);
11
+ const SKIP_NAMES = new Set(['.git', '.andorracode']);
12
+ // Listed (Git normally ignores it, so it arrives dimmed) but never walked into by a deep listing: its contents load
13
+ // only when it is the folder asked for.
14
+ const LIST_ONLY_NAMES = new Set(['node_modules']);
15
+ const MAX_IGNORED_BYTES = 4 * 1024 * 1024;
11
16
  const MAX_TREE_ENTRIES = 5_000;
12
17
  const MAX_TREE_DEPTH = 12;
13
18
  const MAX_FILE_BYTES = 512 * 1024;
@@ -53,8 +58,41 @@ export async function workspaceRoot(value) {
53
58
  throw new Error('The project path is not a folder');
54
59
  return root;
55
60
  }
61
+ /**
62
+ * The paths under `folder` (relative to `root`, `/`-separated) that Git ignores: files, and folders with a trailing
63
+ * slash that stand for everything inside them. Undefined outside a repository, or when Git fails or runs out of time,
64
+ * so the tree lists without marks rather than not at all.
65
+ */
66
+ async function ignoredUnder(root, folder) {
67
+ if (!(await gitInScope(root)))
68
+ return undefined;
69
+ try {
70
+ const collected = await collectCapped('git', ['--literal-pathspecs', '-C', root, 'ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory', '--', folder || '.'], MAX_IGNORED_BYTES, GIT_TIMEOUT_MS);
71
+ if (!collected.truncated && collected.code !== 0)
72
+ return undefined;
73
+ const records = collected.text.split('\0');
74
+ if (collected.truncated)
75
+ records.pop();
76
+ return records.filter(Boolean).map(record => record.split(sep).join('/'));
77
+ }
78
+ catch {
79
+ return undefined;
80
+ }
81
+ }
82
+ /** Whether Git ignores `path`: it is listed itself, or it is inside a listed folder (`dir/`). */
83
+ function isIgnored(path, ignored) {
84
+ if (ignored.has(path) || ignored.has(`${path}/`))
85
+ return true;
86
+ for (let slash = path.indexOf('/'); slash !== -1; slash = path.indexOf('/', slash + 1)) {
87
+ if (ignored.has(path.slice(0, slash + 1)))
88
+ return true;
89
+ }
90
+ return false;
91
+ }
56
92
  export async function readTree(root, options = {}) {
57
93
  const start = await resolveInside(root, options.path);
94
+ const folder = relative(root, start).split(sep).join('/');
95
+ const ignoring = ignoredUnder(root, folder);
58
96
  const deep = options.depth !== undefined;
59
97
  const maxDepth = deep ? Math.max(1, Math.min(MAX_TREE_DEPTH, Number.isSafeInteger(options.depth) ? options.depth : MAX_TREE_DEPTH)) : 1;
60
98
  const entries = [];
@@ -82,13 +120,25 @@ export async function readTree(root, options = {}) {
82
120
  return;
83
121
  }
84
122
  entries.push(child);
85
- if (child.type === 'directory' && depth < maxDepth)
123
+ if (child.type === 'directory' && depth < maxDepth && !LIST_ONLY_NAMES.has(child.name))
86
124
  await walk(join(directory, child.name), depth + 1);
87
125
  }
88
126
  };
89
127
  await walk(start, 1);
90
- return { path: relative(root, start).split(sep).join('/'), entries, truncated };
128
+ const ignored = await ignoring;
129
+ if (ignored?.length) {
130
+ const set = new Set(ignored);
131
+ for (const entry of entries)
132
+ if (isIgnored(entry.path, set))
133
+ entry.ignored = true;
134
+ }
135
+ return { path: folder, entries, truncated };
91
136
  }
137
+ /**
138
+ * A project file's text, capped at 512 KB. A whole text file also carries `hash`, the SHA-256 of its bytes, which
139
+ * `workspace.write` checks before it saves; `notUtf8` marks one whose bytes are not UTF-8, so saving the decoded text
140
+ * would change them.
141
+ */
92
142
  export async function readWorkspaceFile(root, name) {
93
143
  const path = await resolveInside(root, name);
94
144
  const info = await stat(path);
@@ -101,25 +151,58 @@ export async function readWorkspaceFile(root, name) {
101
151
  const head = buffer.subarray(0, bytesRead);
102
152
  const binary = head.subarray(0, Math.min(head.length, 8000)).includes(0);
103
153
  const content = new StringDecoder('utf8').write(head.subarray(0, MAX_FILE_BYTES));
104
- return { content: binary ? '' : content, truncated: info.size > MAX_FILE_BYTES, binary, size: info.size };
154
+ // The size from stat can be stale by the time of the read; what was read decides whether it is the whole file.
155
+ const truncated = info.size > MAX_FILE_BYTES || bytesRead > MAX_FILE_BYTES;
156
+ const whole = !binary && !truncated
157
+ ? { hash: createHash('sha256').update(head).digest('hex'), ...(Buffer.from(content, 'utf8').equals(head) ? {} : { notUtf8: true }) }
158
+ : {};
159
+ return { content: binary ? '' : content, truncated, binary, size: info.size, ...whole };
105
160
  }
106
161
  finally {
107
162
  await handle.close();
108
163
  }
109
164
  }
110
- async function gitInScope(root) {
165
+ /** The most a save from the Files tab may write. */
166
+ export const MAX_WRITE_BYTES = 16 * 1024 * 1024;
167
+ /** `workspace.write`'s checked parameters: the file, as a project-relative path with `/`, and the bytes to save. */
168
+ export async function writeTarget(root, params) {
169
+ if (typeof params.content !== 'string')
170
+ throw new Error('content must be the text to save');
171
+ if (typeof params.expectedHash !== 'string' || !/^[0-9a-f]{64}$/.test(params.expectedHash))
172
+ throw new Error('expectedHash must be the SHA-256 workspace.read gave');
173
+ const bytes = Buffer.from(params.content, 'utf8');
174
+ if (bytes.length > MAX_WRITE_BYTES)
175
+ throw new Error('The file is too large to save from the Files tab');
176
+ const path = await resolveInside(root, params.path);
177
+ if (path === root)
178
+ throw new Error('Only files can be saved');
179
+ const info = await stat(path).catch(() => undefined);
180
+ if (info && !info.isFile())
181
+ throw new Error('Only files can be saved');
182
+ return { relative: relative(root, path).split(sep).join('/'), bytes, expectedHash: params.expectedHash };
183
+ }
184
+ /** The repository's top folder when Git answers for the project (it holds `.git`, or its immediate parent does). */
185
+ async function gitTop(root) {
111
186
  const parent = dirname(root);
112
187
  const holds = async (folder) => stat(join(folder, '.git')).then(() => true, () => false);
113
188
  if (!(await holds(root)) && !(await holds(parent)))
114
- return false;
189
+ return undefined;
115
190
  const top = await collectCapped('git', ['-C', root, 'rev-parse', '--show-toplevel'], 4 * 1024, GIT_TIMEOUT_MS).catch(() => undefined);
116
191
  if (!top || top.code !== 0)
117
- return false;
118
- return inside(root, top.text.trim()) || inside(parent, top.text.trim());
192
+ return undefined;
193
+ const folder = top.text.trim();
194
+ return inside(root, folder) || inside(parent, folder) ? folder : undefined;
195
+ }
196
+ async function gitInScope(root) {
197
+ return (await gitTop(root)) !== undefined;
119
198
  }
120
199
  export async function gitStatus(root, options = {}) {
121
- if (!(await gitInScope(root)))
200
+ const top = await gitTop(root);
201
+ if (top === undefined)
122
202
  return { repository: false, files: [] };
203
+ // Porcelain paths are named from the repository's top; say where the project sits so a reader can match its own paths.
204
+ const below = relative(await realpath(top).catch(() => resolve(top)), root).split(sep).join('/');
205
+ const prefix = below && !below.startsWith('..') && !isAbsolute(below) ? `${below}/` : undefined;
123
206
  let collected;
124
207
  try {
125
208
  collected = await collectCapped('git', ['-C', root, 'status', '--porcelain=v1', '-z', '--branch', '--untracked-files=all'], options.maxBytes ?? MAX_STATUS_BYTES, GIT_TIMEOUT_MS);
@@ -152,7 +235,7 @@ export async function gitStatus(root, options = {}) {
152
235
  if (renamed)
153
236
  index++;
154
237
  }
155
- return { repository: true, branch, files, truncated: collected.truncated };
238
+ return { repository: true, branch, files, truncated: collected.truncated, ...(prefix ? { prefix } : {}) };
156
239
  }
157
240
  }
158
241
  const NOTHING_TO_COMPARE = /not a git repository|bad revision 'HEAD'|ambiguous argument 'HEAD'|does not have any commits/i;
@@ -872,3 +955,366 @@ export async function listExtensions(config, signal, directory) {
872
955
  notices,
873
956
  };
874
957
  }
958
+ // --- Quick open and search across files (design/specs/files-tab-v3.md, items 1 and 2) -------------------------------
959
+ const MAX_LISTED_FILES = 50_000;
960
+ /**
961
+ * Every file in the project for quick open, `/`-separated and relative to `root`, capped at 50,000. `.git` and
962
+ * `.andorracode` are skipped, `node_modules` is not walked into (as the tree), symbolic links are not followed, and
963
+ * files Git ignores are marked.
964
+ */
965
+ export async function listWorkspaceFiles(root) {
966
+ // Git's ignore list first, so ignored folders (a virtualenv, a build) are walked only after everything else and
967
+ // cannot fill the cap ahead of the project's own files.
968
+ const ignoredList = await ignoredUnder(root, '');
969
+ const ignoredSet = new Set(ignoredList ?? []);
970
+ const files = [];
971
+ let truncated = false;
972
+ const folders = [root];
973
+ const ignoredFolders = [];
974
+ while ((folders.length || ignoredFolders.length) && !truncated) {
975
+ const directory = folders.length ? folders.shift() : ignoredFolders.shift();
976
+ const found = [];
977
+ try {
978
+ for await (const entry of await opendir(directory)) {
979
+ if (entry.isSymbolicLink() || SKIP_NAMES.has(entry.name))
980
+ continue;
981
+ const path = join(directory, entry.name);
982
+ if (entry.isDirectory()) {
983
+ if (LIST_ONLY_NAMES.has(entry.name))
984
+ continue;
985
+ if (isIgnored(relative(root, path).split(sep).join('/'), ignoredSet))
986
+ ignoredFolders.push(path);
987
+ else
988
+ folders.push(path);
989
+ }
990
+ else if (entry.isFile())
991
+ found.push(relative(root, path).split(sep).join('/'));
992
+ }
993
+ }
994
+ catch { /* a folder that cannot be read is left out; the rest are listed */ }
995
+ found.sort((left, right) => left.localeCompare(right));
996
+ for (const path of found) {
997
+ if (files.length >= MAX_LISTED_FILES) {
998
+ truncated = true;
999
+ break;
1000
+ }
1001
+ files.push({ path });
1002
+ }
1003
+ }
1004
+ if (ignoredSet.size)
1005
+ for (const file of files)
1006
+ if (isIgnored(file.path, ignoredSet))
1007
+ file.ignored = true;
1008
+ return { files, truncated };
1009
+ }
1010
+ export const SEARCH_MAX_FILES = 200;
1011
+ export const SEARCH_MAX_MATCHES = 2_000;
1012
+ const SEARCH_TIME_MS = 10_000;
1013
+ const SEARCH_LINE_CHARS = 400;
1014
+ const SEARCH_FALLBACK_FILE_BYTES = 1024 * 1024;
1015
+ const SEARCH_FALLBACK_FILES = 20_000;
1016
+ /** Comma-separated globs; a comma inside `{…}` or `[…]` belongs to its glob (`*.{ts,tsx}`). */
1017
+ export function globList(value) {
1018
+ if (value === undefined || value === '')
1019
+ return [];
1020
+ if (typeof value !== 'string' || value.length > 2000)
1021
+ throw new Error('include and exclude must be comma-separated globs');
1022
+ const parts = [];
1023
+ let depth = 0;
1024
+ let current = '';
1025
+ for (const char of value) {
1026
+ if (char === '{' || char === '[')
1027
+ depth += 1;
1028
+ else if ((char === '}' || char === ']') && depth > 0)
1029
+ depth -= 1;
1030
+ if (char === ',' && depth === 0) {
1031
+ parts.push(current);
1032
+ current = '';
1033
+ continue;
1034
+ }
1035
+ current += char;
1036
+ }
1037
+ parts.push(current);
1038
+ return parts.map(part => part.trim()).filter(Boolean);
1039
+ }
1040
+ export function searchOptions(params) {
1041
+ const query = params.query;
1042
+ if (typeof query !== 'string' || !query || query.length > 1000 || query.includes('\0'))
1043
+ throw new Error('A search needs a query of up to 1000 characters');
1044
+ const flag = (name) => params[name] === true;
1045
+ const options = { query, regex: flag('regex'), caseSensitive: flag('caseSensitive'), wholeWord: flag('wholeWord') };
1046
+ if (globList(params.include).length)
1047
+ options.include = params.include;
1048
+ if (globList(params.exclude).length)
1049
+ options.exclude = params.exclude;
1050
+ return options;
1051
+ }
1052
+ /** A line clipped to what the results show, with its match ranges clipped to match. */
1053
+ function clipLine(text, ranges) {
1054
+ const line = text.replace(/\r?\n$/, '');
1055
+ if (line.length <= SEARCH_LINE_CHARS)
1056
+ return { text: line, ranges };
1057
+ // Keep the first match in view: start a little before it.
1058
+ const from = Math.max(0, Math.min((ranges[0]?.start ?? 0) - 40, line.length - SEARCH_LINE_CHARS));
1059
+ const to = from + SEARCH_LINE_CHARS;
1060
+ return {
1061
+ text: line.slice(from, to),
1062
+ ranges: ranges.filter(range => range.start < to && range.end > from).map(range => ({ start: Math.max(0, range.start - from), end: Math.min(SEARCH_LINE_CHARS, range.end - from) })),
1063
+ };
1064
+ }
1065
+ /** Submatches kept per line: the line shown is clipped to 400 characters, so more cannot be shown anyway. */
1066
+ const SEARCH_RANGES_PER_LINE = 50;
1067
+ /**
1068
+ * Ripgrep's byte offsets (ordered) as string offsets, walking the line once; a plain ASCII line needs no walk. A
1069
+ * minified line of a megabyte with thousands of matches stays linear.
1070
+ */
1071
+ export function charRanges(text, submatches) {
1072
+ const kept = submatches.slice(0, SEARCH_RANGES_PER_LINE);
1073
+ if (Buffer.byteLength(text, 'utf8') === text.length)
1074
+ return kept.map(sub => ({ start: sub.start, end: sub.end }));
1075
+ const out = [];
1076
+ let byte = 0;
1077
+ let index = 0;
1078
+ const advance = (target) => {
1079
+ while (byte < target && index < text.length) {
1080
+ const code = text.codePointAt(index);
1081
+ byte += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4;
1082
+ index += code > 0xffff ? 2 : 1;
1083
+ }
1084
+ return index;
1085
+ };
1086
+ for (const sub of kept) {
1087
+ const start = advance(sub.start);
1088
+ out.push({ start, end: advance(sub.end) });
1089
+ }
1090
+ return out;
1091
+ }
1092
+ class SearchCollector {
1093
+ files = [];
1094
+ matchCount = 0;
1095
+ full = false;
1096
+ add(path, match) {
1097
+ if (this.matchCount >= SEARCH_MAX_MATCHES) {
1098
+ this.full = true;
1099
+ return false;
1100
+ }
1101
+ let file = this.files[this.files.length - 1];
1102
+ if (!file || file.path !== path) {
1103
+ if (this.files.length >= SEARCH_MAX_FILES) {
1104
+ this.full = true;
1105
+ return false;
1106
+ }
1107
+ file = { path, matches: [] };
1108
+ this.files.push(file);
1109
+ }
1110
+ if (this.matchCount >= SEARCH_MAX_MATCHES) {
1111
+ this.full = true;
1112
+ return false;
1113
+ }
1114
+ file.matches.push(match);
1115
+ this.matchCount += 1;
1116
+ return true;
1117
+ }
1118
+ limitNote() { return `Showing the first ${SEARCH_MAX_MATCHES.toLocaleString('en-US')} results in ${SEARCH_MAX_FILES} files at most`; }
1119
+ }
1120
+ /**
1121
+ * Searches the project's files for `options.query`, with ripgrep when it is installed (it skips what Git ignores) and
1122
+ * a built-in scan otherwise. Results stop at 200 files, 2,000 matches or 10 seconds, and say so (`incomplete`).
1123
+ */
1124
+ export async function searchWorkspace(root, options, signal, rg = null) {
1125
+ return rg ? searchWithRipgrep(root, options, rg, signal) : searchBuiltIn(root, options, signal);
1126
+ }
1127
+ function searchWithRipgrep(root, options, rg, signal) {
1128
+ // node_modules is skipped even where Git does not ignore it, as quick open and the tree skip it.
1129
+ const args = ['--json', '--hidden', '--glob', '!.git', '--glob', '!.andorracode', '--glob', '!**/node_modules/**', '--max-filesize', '2M',
1130
+ options.caseSensitive ? '--case-sensitive' : '--ignore-case'];
1131
+ if (options.wholeWord)
1132
+ args.push('--word-regexp');
1133
+ if (!options.regex)
1134
+ args.push('--fixed-strings');
1135
+ for (const glob of globList(options.include))
1136
+ args.push('--glob', glob);
1137
+ for (const glob of globList(options.exclude))
1138
+ args.push('--glob', `!${glob}`);
1139
+ args.push('--', options.query, '.');
1140
+ if (signal?.aborted)
1141
+ return Promise.resolve({ files: [], matchCount: 0, incomplete: 'Search cancelled', engine: 'ripgrep' });
1142
+ return new Promise((done, fail) => {
1143
+ const collected = new SearchCollector();
1144
+ let incomplete;
1145
+ let settled = false;
1146
+ const child = spawn(rg, args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
1147
+ const timer = setTimeout(() => { incomplete = `Search stopped after ${SEARCH_TIME_MS / 1000} seconds`; child.kill(); }, SEARCH_TIME_MS);
1148
+ const onAbort = () => { incomplete = 'Search cancelled'; child.kill(); };
1149
+ signal?.addEventListener('abort', onAbort, { once: true });
1150
+ let buffered = '';
1151
+ let errors = '';
1152
+ const decoder = new StringDecoder('utf8');
1153
+ const finish = (error) => {
1154
+ if (settled)
1155
+ return;
1156
+ settled = true;
1157
+ clearTimeout(timer);
1158
+ signal?.removeEventListener('abort', onAbort);
1159
+ if (error) {
1160
+ fail(error);
1161
+ return;
1162
+ }
1163
+ if (collected.full)
1164
+ incomplete ??= collected.limitNote();
1165
+ done({ files: collected.files, matchCount: collected.matchCount, ...(incomplete ? { incomplete } : {}), engine: 'ripgrep' });
1166
+ };
1167
+ child.stdout.on('data', (chunk) => {
1168
+ buffered += decoder.write(chunk);
1169
+ let newline = buffered.indexOf('\n');
1170
+ while (newline !== -1) {
1171
+ const record = buffered.slice(0, newline);
1172
+ buffered = buffered.slice(newline + 1);
1173
+ newline = buffered.indexOf('\n');
1174
+ if (collected.full)
1175
+ continue;
1176
+ let event;
1177
+ try {
1178
+ event = JSON.parse(record);
1179
+ }
1180
+ catch {
1181
+ continue;
1182
+ }
1183
+ if (event.type !== 'match' || !event.data?.path?.text || typeof event.data.lines?.text !== 'string' || !event.data.line_number)
1184
+ continue;
1185
+ const text = event.data.lines.text;
1186
+ const ranges = charRanges(text, event.data.submatches ?? []);
1187
+ const path = event.data.path.text.replace(/^\.[\\/]/, '').split(sep).join('/');
1188
+ if (!collected.add(path, { line: event.data.line_number, ...clipLine(text, ranges) }))
1189
+ child.kill();
1190
+ }
1191
+ });
1192
+ child.stderr.on('data', (chunk) => { if (errors.length < 4000)
1193
+ errors += chunk.toString('utf8'); });
1194
+ child.on('error', error => finish(error));
1195
+ child.on('close', code => {
1196
+ // 1 is "no matches"; a killed search keeps what it found.
1197
+ if (code === 2 && !collected.matchCount && !incomplete) {
1198
+ // ripgrep's first line is often only "regex parse error:"; the lines after it say what and where.
1199
+ const said = errors.trim().split('\n').map(line => line.trim()).filter(Boolean).slice(0, 4).join(' ').replace(/^rg:\s*/, '');
1200
+ finish(new Error(said ? `The search failed: ${said}` : 'The search failed'));
1201
+ return;
1202
+ }
1203
+ if (code === 2 && errors.trim())
1204
+ incomplete ??= 'Some files could not be searched';
1205
+ finish();
1206
+ });
1207
+ });
1208
+ }
1209
+ async function searchBuiltIn(root, options, signal) {
1210
+ const source = options.regex ? options.query : options.query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1211
+ let pattern;
1212
+ // A whole word is one not touched by word characters, so `retry()` and `.foo` match as ripgrep's --word-regexp does.
1213
+ try {
1214
+ pattern = new RegExp(options.wholeWord ? `(?<![\\p{L}\\p{N}_])(?:${source})(?![\\p{L}\\p{N}_])` : source, `gu${options.caseSensitive ? '' : 'i'}`);
1215
+ }
1216
+ catch (error) {
1217
+ throw new Error(`The regular expression is not valid: ${message(error)}`);
1218
+ }
1219
+ const include = globList(options.include);
1220
+ const exclude = globList(options.exclude);
1221
+ // A glob without a folder matches the file's name anywhere, as ripgrep's --glob does.
1222
+ const matchesGlob = (path, glob) => pathMatchesGlob(path, glob) || (!glob.includes('/') && pathMatchesGlob(posix.basename(path), glob));
1223
+ const collected = new SearchCollector();
1224
+ const deadline = Date.now() + SEARCH_TIME_MS;
1225
+ let incomplete;
1226
+ const { files } = await listWorkspaceFiles(root);
1227
+ let scanned = 0;
1228
+ for (const file of files) {
1229
+ if (signal?.aborted) {
1230
+ incomplete = 'Search cancelled';
1231
+ break;
1232
+ }
1233
+ if (file.ignored)
1234
+ continue;
1235
+ if (include.length && !include.some(glob => matchesGlob(file.path, glob)))
1236
+ continue;
1237
+ if (exclude.some(glob => matchesGlob(file.path, glob)))
1238
+ continue;
1239
+ if (scanned >= SEARCH_FALLBACK_FILES) {
1240
+ incomplete = `Search stopped at ${SEARCH_FALLBACK_FILES.toLocaleString('en-US')} files`;
1241
+ break;
1242
+ }
1243
+ if (Date.now() > deadline) {
1244
+ incomplete = `Search stopped after ${SEARCH_TIME_MS / 1000} seconds`;
1245
+ break;
1246
+ }
1247
+ const full = join(root, file.path);
1248
+ let content;
1249
+ try {
1250
+ const info = await stat(full);
1251
+ if (info.size > SEARCH_FALLBACK_FILE_BYTES)
1252
+ continue;
1253
+ const bytes = await readFile(full);
1254
+ if (bytes.subarray(0, 8000).includes(0))
1255
+ continue;
1256
+ content = bytes.toString('utf8');
1257
+ }
1258
+ catch {
1259
+ continue;
1260
+ }
1261
+ scanned += 1;
1262
+ const lines = content.split('\n');
1263
+ for (let index = 0; index < lines.length; index += 1) {
1264
+ const text = lines[index].replace(/\r$/, '');
1265
+ pattern.lastIndex = 0;
1266
+ const ranges = [];
1267
+ for (let hit = pattern.exec(text); hit; hit = pattern.exec(text)) {
1268
+ ranges.push({ start: hit.index, end: hit.index + hit[0].length });
1269
+ if (hit[0].length === 0)
1270
+ pattern.lastIndex += 1;
1271
+ }
1272
+ if (!ranges.length)
1273
+ continue;
1274
+ if (!collected.add(file.path, { line: index + 1, ...clipLine(text, ranges) }))
1275
+ break;
1276
+ }
1277
+ if (collected.full)
1278
+ break;
1279
+ }
1280
+ if (collected.full)
1281
+ incomplete ??= collected.limitNote();
1282
+ return { files: collected.files, matchCount: collected.matchCount, ...(incomplete ? { incomplete } : {}), engine: 'built-in' };
1283
+ }
1284
+ // --- Copy a link to lines (design/specs/files-tab-v3.md, item 5) ----------------------------------------------------
1285
+ /** A GitHub remote URL (https, ssh or git@) as its web address, or undefined for any other host. */
1286
+ export function githubWebUrl(remote) {
1287
+ const match = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(remote.trim());
1288
+ return match ? `https://github.com/${match[1]}/${match[2]}` : undefined;
1289
+ }
1290
+ /**
1291
+ * What a GitHub link to lines needs: the repository's web address, the commit checked out, whether that commit is on
1292
+ * a remote branch (so the link resolves), and where the project sits in the repository. Fields are left out where Git
1293
+ * cannot say.
1294
+ */
1295
+ export async function gitLinkBase(root) {
1296
+ const top = await gitTop(root);
1297
+ if (top === undefined)
1298
+ return { repository: false };
1299
+ const git = async (args) => {
1300
+ try {
1301
+ const collected = await collectCapped('git', ['-C', root, ...args], 64 * 1024, GIT_TIMEOUT_MS);
1302
+ return collected.code === 0 ? collected.text.trim() : undefined;
1303
+ }
1304
+ catch {
1305
+ return undefined;
1306
+ }
1307
+ };
1308
+ const [remote, head] = await Promise.all([git(['config', '--get', 'remote.origin.url']), git(['rev-parse', 'HEAD'])]);
1309
+ // The link names origin's repository, so the commit must be on one of origin's branches.
1310
+ const contains = head ? await git(['branch', '-r', '--contains', head, '--list', 'origin/*']) : undefined;
1311
+ const below = relative(await realpath(top).catch(() => resolve(top)), root).split(sep).join('/');
1312
+ const webUrl = remote ? githubWebUrl(remote) : undefined;
1313
+ return {
1314
+ repository: true,
1315
+ ...(webUrl ? { webUrl } : {}),
1316
+ ...(head && /^[0-9a-f]{40}$/.test(head) ? { head } : {}),
1317
+ ...(contains !== undefined ? { pushed: contains.length > 0 } : {}),
1318
+ ...(below && !below.startsWith('..') && !isAbsolute(below) ? { prefix: `${below}/` } : {}),
1319
+ };
1320
+ }