@andorra-labs/code 0.1.17 → 0.1.18

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 (94) hide show
  1. package/dist/src/agent-execution.js +97 -11
  2. package/dist/src/andorra/errors.js +3 -0
  3. package/dist/src/app-server/protocol.d.ts +13 -2
  4. package/dist/src/app-server/protocol.js +1 -1
  5. package/dist/src/app-server/workspace.d.ts +19 -0
  6. package/dist/src/app-server/workspace.js +155 -4
  7. package/dist/src/app-server.d.ts +32 -1
  8. package/dist/src/app-server.js +622 -74
  9. package/dist/src/attachments.d.ts +10 -0
  10. package/dist/src/attachments.js +102 -7
  11. package/dist/src/automation-tool.js +2 -1
  12. package/dist/src/bridge/command.js +12 -0
  13. package/dist/src/bridge/control.d.ts +3 -1
  14. package/dist/src/bridge/control.js +7 -2
  15. package/dist/src/bridge/github.d.ts +108 -0
  16. package/dist/src/bridge/github.js +378 -0
  17. package/dist/src/bridge/host-ops.d.ts +1 -1
  18. package/dist/src/bridge/host-ops.js +11 -1
  19. package/dist/src/bridge/host.js +7 -4
  20. package/dist/src/bug-report-attachments.d.ts +48 -0
  21. package/dist/src/bug-report-attachments.js +327 -0
  22. package/dist/src/bug-report.d.ts +23 -3
  23. package/dist/src/bug-report.js +72 -9
  24. package/dist/src/cli.d.ts +1 -3
  25. package/dist/src/cli.js +10 -4
  26. package/dist/src/codex-provider.js +1 -1
  27. package/dist/src/coding-tools.js +9 -2
  28. package/dist/src/commands.d.ts +1 -1
  29. package/dist/src/commands.js +2 -1
  30. package/dist/src/completion.js +8 -4
  31. package/dist/src/config.js +3 -1
  32. package/dist/src/context-budget.js +15 -2
  33. package/dist/src/decision/DecisionEngine.d.ts +2 -0
  34. package/dist/src/decision/DecisionManager.d.ts +11 -0
  35. package/dist/src/decision/DecisionManager.js +36 -0
  36. package/dist/src/decision/applyTaskKind.d.ts +8 -0
  37. package/dist/src/decision/applyTaskKind.js +53 -0
  38. package/dist/src/decision/hostedPolicy.js +2 -1
  39. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +2 -0
  40. package/dist/src/decision/providers/AndorraDecisionProvider.js +12 -0
  41. package/dist/src/decision/taskKind.d.ts +52 -0
  42. package/dist/src/decision/taskKind.js +76 -0
  43. package/dist/src/decision/types.d.ts +1 -1
  44. package/dist/src/default-graph.js +1 -1
  45. package/dist/src/efficiency.d.ts +5 -0
  46. package/dist/src/efficiency.js +5 -1
  47. package/dist/src/effort-routing.d.ts +27 -0
  48. package/dist/src/effort-routing.js +34 -0
  49. package/dist/src/evidence.d.ts +110 -0
  50. package/dist/src/evidence.js +195 -0
  51. package/dist/src/github-app/client.d.ts +19 -0
  52. package/dist/src/github-app/client.js +21 -1
  53. package/dist/src/github-names.d.ts +7 -0
  54. package/dist/src/github-names.js +7 -0
  55. package/dist/src/graph-preview.d.ts +2 -0
  56. package/dist/src/graph-preview.js +1 -0
  57. package/dist/src/graph-runner.js +1 -1
  58. package/dist/src/graph-server.js +4 -2
  59. package/dist/src/graph-ui/app.js +30 -0
  60. package/dist/src/graphs.d.ts +6 -0
  61. package/dist/src/graphs.js +7 -2
  62. package/dist/src/hardened-runtime.js +32 -21
  63. package/dist/src/model-health-cache.js +1 -1
  64. package/dist/src/model-override.d.ts +2 -1
  65. package/dist/src/model-override.js +9 -0
  66. package/dist/src/model-tiers.d.ts +3 -0
  67. package/dist/src/model-tiers.js +3 -3
  68. package/dist/src/provider-engine.d.ts +13 -1
  69. package/dist/src/provider-engine.js +74 -0
  70. package/dist/src/providers.d.ts +5 -0
  71. package/dist/src/providers.js +34 -8
  72. package/dist/src/pull-requests.d.ts +11 -1
  73. package/dist/src/pull-requests.js +53 -2
  74. package/dist/src/react-runtime.js +98 -15
  75. package/dist/src/remote/engine-pool.js +5 -5
  76. package/dist/src/runtime.d.ts +29 -1
  77. package/dist/src/runtime.js +8 -0
  78. package/dist/src/sessions.d.ts +24 -0
  79. package/dist/src/sessions.js +55 -2
  80. package/dist/src/skills/bundled/bug-report/SKILL.md +51 -7
  81. package/dist/src/skills/bundled/provenance.json +1 -1
  82. package/dist/src/task-checkout.d.ts +141 -0
  83. package/dist/src/task-checkout.js +558 -0
  84. package/dist/src/test-edit-guard.d.ts +30 -0
  85. package/dist/src/test-edit-guard.js +167 -2
  86. package/dist/src/thinking-level-detect.d.ts +11 -0
  87. package/dist/src/thinking-level-detect.js +47 -0
  88. package/dist/src/thinking-levels.d.ts +30 -0
  89. package/dist/src/thinking-levels.js +124 -0
  90. package/dist/src/timers.d.ts +1 -0
  91. package/dist/src/tool-catalog.js +1 -1
  92. package/dist/src/transcript.js +1 -1
  93. package/dist/src/types.d.ts +34 -0
  94. package/package.json +1 -1
@@ -0,0 +1,378 @@
1
+ /**
2
+ * GitHub repositories on a Cloud machine (docs/superpowers/specs/2026-11-25-cloud-repo-picker-design.md): the Git
3
+ * credential helper, and the clone a desktop asks for. The machine holds no GitHub credential. Each time Git wants
4
+ * one, the helper trades the machine's own secret for an environment token and asks the Andorra service for a
5
+ * one-hour token for that one repository. The token is printed to Git alone: never to a file, a log, a URL or an
6
+ * argument.
7
+ */
8
+ import { execFile } from 'node:child_process';
9
+ import { randomBytes } from 'node:crypto';
10
+ import { mkdir, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
11
+ import { join } from 'node:path';
12
+ import { AUTH_DEPLOYMENT } from '../auth/deployment.js';
13
+ import { loadConfig } from '../config.js';
14
+ import { GITHUB_ACCOUNT, GITHUB_REPO } from '../github-names.js';
15
+ import { addProjectEntry } from '../project-registry.js';
16
+ import { projectRootId, sharedFolders } from '../remote/roots.js';
17
+ import { ControlError, environmentToken } from './control.js';
18
+ import { readBridgeIdentity } from './store.js';
19
+ const TOKEN_TIMEOUT_MS = 20_000;
20
+ const MAX_ANSWER_CHARS = 16 * 1024;
21
+ const MAX_CREDENTIAL_INPUT_CHARS = 8 * 1024;
22
+ /** A clone still running after this long is stopped and reported as failed. */
23
+ export const CLONE_TIMEOUT_MS = 30 * 60_000;
24
+ /** How long a clone request waits for the clone before answering `cloning`; a host operation has 30 seconds in all. */
25
+ export const CLONE_ANSWER_MS = 2_000;
26
+ const GIT_COMMAND_TIMEOUT_MS = 20_000;
27
+ const LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,62})$/;
28
+ const TOKEN = /^[A-Za-z0-9_.-]{1,4096}$/;
29
+ export class RepositoryTokenError extends Error {
30
+ code;
31
+ constructor(code, message) {
32
+ super(message);
33
+ this.code = code;
34
+ this.name = 'RepositoryTokenError';
35
+ }
36
+ }
37
+ function refusal(error, status, name) {
38
+ switch (error) {
39
+ case 'not_connected': return new RepositoryTokenError('not-connected', 'GitHub is not connected to your Andorra account. Connect it in Andorra Code under Settings → GitHub.');
40
+ case 'not_covered': return new RepositoryTokenError('not-covered', `The Andorra Code GitHub App cannot reach ${name} for your GitHub account. Check that the App is installed on that repository and that your account can read it.`);
41
+ case 'not_cloud': return new RepositoryTokenError('not-cloud', 'Only Cloud gets GitHub access from Andorra. On this machine, use the Git credentials it already has.');
42
+ case 'suspended': return new RepositoryTokenError('suspended', `The Andorra Code GitHub App is suspended on the account that owns ${name}.`);
43
+ case 'permissions_pending': return new RepositoryTokenError('permissions-pending', `The Andorra Code GitHub App is waiting for an owner of ${name} to approve its access to repository contents.`);
44
+ case 'not_allowed': return new RepositoryTokenError('not-allowed', 'The GitHub App is not available to this Andorra account yet.');
45
+ case 'account_unavailable': return new RepositoryTokenError('account-unavailable', 'The Andorra account that owns this machine cannot be used right now.');
46
+ case 'rate_limited': return new RepositoryTokenError('rate-limited', 'Andorra was asked for GitHub access too many times. Try again in a few minutes.');
47
+ case 'unauthorized': return new RepositoryTokenError('unlinked', 'The Andorra service did not accept this machine\'s link.');
48
+ default: return new RepositoryTokenError('server', `The Andorra service could not give GitHub access (${error ?? `HTTP ${status}`}).`);
49
+ }
50
+ }
51
+ /** Asks the service for a token for one repository, as the machine `environmentToken` names. */
52
+ export async function repositoryToken(apiBase, environmentTokenValue, owner, repo, fetcher = globalThis.fetch) {
53
+ let status;
54
+ let text;
55
+ try {
56
+ const response = await fetcher(`${apiBase.replace(/\/+$/, '')}/github/environment-token`, {
57
+ method: 'POST',
58
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${environmentTokenValue}` },
59
+ body: JSON.stringify({ owner, repo }),
60
+ signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS),
61
+ redirect: 'error',
62
+ });
63
+ status = response.status;
64
+ text = (await response.text()).slice(0, MAX_ANSWER_CHARS);
65
+ }
66
+ catch (error) {
67
+ throw new RepositoryTokenError('network', `The Andorra service could not be reached: ${error instanceof Error ? error.message : String(error)}`);
68
+ }
69
+ let value = {};
70
+ try {
71
+ const parsed = JSON.parse(text);
72
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
73
+ value = parsed;
74
+ }
75
+ catch { }
76
+ const name = `${owner}/${repo}`;
77
+ if (status === 200 && value.enabled === false)
78
+ throw new RepositoryTokenError('off', 'GitHub access for Cloud is not turned on yet.');
79
+ if (status !== 200)
80
+ throw refusal(typeof value.error === 'string' ? value.error : undefined, status, name);
81
+ const { token, expiresAt, login, githubUserId, push } = value;
82
+ if (typeof token !== 'string' || !TOKEN.test(token) || typeof expiresAt !== 'string' || !Number.isFinite(Date.parse(expiresAt))
83
+ || typeof login !== 'string' || !LOGIN.test(login) || typeof githubUserId !== 'number' || !Number.isSafeInteger(githubUserId) || githubUserId <= 0) {
84
+ throw new RepositoryTokenError('server', 'The Andorra service answered something this version does not understand.');
85
+ }
86
+ return { token, expiresAt, login, githubUserId, push: push === true };
87
+ }
88
+ /** The machine's own token for `owner/repo`: its secret is traded for an environment token, and that for the repository's. */
89
+ export async function machineRepositoryToken(directory, apiBase, owner, repo) {
90
+ const identity = await readBridgeIdentity(directory);
91
+ if (!identity)
92
+ throw new RepositoryTokenError('unlinked', 'This machine is not linked to an Andorra account.');
93
+ let environment;
94
+ try {
95
+ environment = await environmentToken(apiBase, identity.environmentId, identity.secret);
96
+ }
97
+ catch (error) {
98
+ if (error instanceof ControlError)
99
+ throw new RepositoryTokenError(error.code === 'unlinked' ? 'unlinked' : error.code === 'network' ? 'network' : 'server', error.message);
100
+ throw error;
101
+ }
102
+ return repositoryToken(apiBase, environment.token, owner, repo);
103
+ }
104
+ /** `owner/repo` from the path Git names in a credential request (`owner/repo.git`, with or without what follows it). */
105
+ export function repositoryOfPath(path) {
106
+ if (path === undefined)
107
+ return undefined;
108
+ const [owner, rawRepo] = path.replace(/^\/+/, '').split('/');
109
+ if (owner === undefined || rawRepo === undefined)
110
+ return undefined;
111
+ const repo = rawRepo.endsWith('.git') ? rawRepo.slice(0, -4) : rawRepo;
112
+ return GITHUB_ACCOUNT.test(owner) && GITHUB_REPO.test(repo) ? { owner, repo } : undefined;
113
+ }
114
+ /** A credential request as Git writes it: `key=value` lines up to a blank line. */
115
+ export function parseCredentialRequest(stdin) {
116
+ const fields = {};
117
+ for (const line of stdin.slice(0, MAX_CREDENTIAL_INPUT_CHARS).split('\n')) {
118
+ const trimmed = line.endsWith('\r') ? line.slice(0, -1) : line;
119
+ if (trimmed === '')
120
+ break;
121
+ const at = trimmed.indexOf('=');
122
+ if (at > 0)
123
+ fields[trimmed.slice(0, at)] = trimmed.slice(at + 1);
124
+ }
125
+ return fields;
126
+ }
127
+ /**
128
+ * Git's credential helper (`andorra bridge git-credential <action>`). It answers only a `get` for
129
+ * `https://github.com/<owner>/<repo>`; anything else gets no credential, and Git goes on to whatever else it has.
130
+ * `store` and `erase` do nothing: there is nothing kept to change.
131
+ */
132
+ export async function runGitCredential(input) {
133
+ if (input.action !== 'get')
134
+ return 0;
135
+ const request = parseCredentialRequest(input.stdin);
136
+ if (request.protocol !== 'https' || request.host !== 'github.com')
137
+ return 0;
138
+ const repository = repositoryOfPath(request.path);
139
+ if (!repository) {
140
+ // Without credential.useHttpPath Git names no repository, and a token must name one.
141
+ input.warn('andorra: this clone does not tell Andorra which repository it is. Clone it again from the Project menu in Andorra Code.');
142
+ return 0;
143
+ }
144
+ try {
145
+ const answer = await (input.token ?? machineRepositoryToken)(input.directory, input.apiBase, repository.owner, repository.repo);
146
+ input.print('username=x-access-token');
147
+ input.print(`password=${answer.token}`);
148
+ return 0;
149
+ }
150
+ catch (error) {
151
+ input.warn(`andorra: ${error instanceof Error ? error.message : String(error)}`);
152
+ return 1;
153
+ }
154
+ }
155
+ /** A single-quoted word for the shell Git runs a helper with. */
156
+ const quoted = (value) => `'${value.replaceAll('\'', '\'\\\'\'')}'`;
157
+ /**
158
+ * The helper this process's own CLI provides, named by the paths it is running from. `settings` are set for the
159
+ * helper itself, so it reaches the same service and home as this machine's bridge even when the Git that runs it was
160
+ * started with a narrower environment (a task's command, say).
161
+ */
162
+ export function credentialHelperCommand(execPath = process.execPath, script = process.argv[1], settings = {}) {
163
+ const assignments = Object.entries(settings).filter(([name]) => /^[A-Z][A-Z0-9_]*$/.test(name)).map(([name, value]) => `${name}=${quoted(value)} `).join('');
164
+ return `!${assignments}${quoted(execPath)}${script === undefined ? '' : ` ${quoted(script)}`} bridge git-credential`;
165
+ }
166
+ /** The helper's file in the machine's Andorra home: the one path every clone's configuration names. */
167
+ export const CREDENTIAL_HELPER_FILE = 'git-credential-andorra';
168
+ /**
169
+ * Writes the helper every clone names and answers it as Git's configuration takes it. A clone's configuration
170
+ * outlives the engine that made it, and an engine's own path changes with its version (old versions are pruned), so
171
+ * clones name this one file instead, and it is rewritten to run the current engine whenever the bridge starts and
172
+ * before every clone. It holds paths and the service's address: no secret.
173
+ */
174
+ export async function installCredentialHelper(directory, options = {}) {
175
+ const command = credentialHelperCommand(options.execPath ?? process.execPath, options.script ?? process.argv[1], options.settings ?? {}).slice(1);
176
+ // Git's shell reads this path on every platform, so it is written with forward slashes.
177
+ const file = join(directory, CREDENTIAL_HELPER_FILE).replaceAll('\\', '/');
178
+ const temporary = `${file}.${randomBytes(4).toString('hex')}.tmp`;
179
+ await mkdir(directory, { recursive: true });
180
+ try {
181
+ await writeFile(temporary, `#!/bin/sh\n# Written by Andorra Code when its bridge starts and before each clone. Changes are overwritten.\nexec env ${command} "$@"\n`, { mode: 0o700 });
182
+ await moveIntoPlace(temporary, file);
183
+ }
184
+ finally {
185
+ await rm(temporary, { force: true }).catch(() => undefined);
186
+ }
187
+ return `!${quoted(file)}`;
188
+ }
189
+ /** The helper for this machine as its environment describes it, written afresh. */
190
+ export function installCredentialHelperFromEnvironment(directory, environment = process.env) {
191
+ const configured = environment.ANDORRA_API_BASE_URL?.trim();
192
+ const home = environment.ANDORRACODE_HOME?.trim();
193
+ return installCredentialHelper(directory, { settings: { ...(configured?.startsWith('https://') ? { ANDORRA_API_BASE_URL: configured } : {}), ...(home ? { ANDORRACODE_HOME: home } : {}) } });
194
+ }
195
+ export async function cloneDependenciesFromEnvironment(directory, environment = process.env) {
196
+ const configured = environment.ANDORRA_API_BASE_URL?.trim();
197
+ const cloud = environment.ANDORRA_CLOUD === '1';
198
+ return {
199
+ directory,
200
+ apiBase: configured?.startsWith('https://') ? configured : AUTH_DEPLOYMENT.apiBaseUrl,
201
+ cloud,
202
+ // A machine that clones nothing gets no helper file.
203
+ helper: cloud ? await installCredentialHelperFromEnvironment(directory, environment) : credentialHelperCommand(),
204
+ };
205
+ }
206
+ const githubUrl = (owner, repo) => `https://github.com/${owner}/${repo}.git`;
207
+ const sameRepository = (url, owner, repo) => url.trim().replace(/\/+$/, '').replace(/\.git$/i, '').toLowerCase() === `https://github.com/${owner}/${repo}`.toLowerCase();
208
+ function git(binary, args, timeoutMs) {
209
+ return new Promise(resolvePromise => {
210
+ execFile(binary, args, {
211
+ timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024, windowsHide: true,
212
+ // Git must fail instead of waiting for someone to type a name and password.
213
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never' },
214
+ }, (error, stdout, stderr) => resolvePromise({ ok: !error, stdout: String(stdout), stderr: String(stderr) }));
215
+ });
216
+ }
217
+ /** The last thing Git said, without control characters and without anything shaped like a credential. */
218
+ function gitFailure(stderr) {
219
+ const lines = stderr.split(/\r?\n/).map(line => line.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ').trim()).filter(Boolean);
220
+ const last = (lines.findLast(line => /^(fatal|error|andorra):/i.test(line)) ?? lines.at(-1) ?? 'Git gave no reason.')
221
+ .replace(/https:\/\/[^@\s/]+@/g, 'https://').replace(/\b(gh[pousr]_|github_pat_)[A-Za-z0-9_]+/g, '[token]');
222
+ return last.slice(0, 300);
223
+ }
224
+ /** Renames the finished clone to its name. A scanner that still holds a new file (Windows) gets a few moments to let go. */
225
+ async function moveIntoPlace(from, to) {
226
+ for (let attempt = 0;; attempt++) {
227
+ try {
228
+ await rename(from, to);
229
+ return;
230
+ }
231
+ catch (error) {
232
+ const code = error.code;
233
+ if (attempt >= 9 || (code !== 'EPERM' && code !== 'EBUSY' && code !== 'EACCES'))
234
+ throw error;
235
+ await new Promise(resolvePromise => setTimeout(resolvePromise, 100 * (attempt + 1)));
236
+ }
237
+ }
238
+ }
239
+ const exists = (path) => stat(path).then(() => true, () => false);
240
+ /**
241
+ * The helper, and for a new clone the author, in the clone's own configuration: every later pull, push and commit
242
+ * there uses them. A clone that is opened again gets the helper set again, so one made by an earlier engine keeps working.
243
+ */
244
+ async function configureClone(binary, target, helper, author) {
245
+ const settings = [
246
+ // An empty value first drops any helper configured for the whole machine, so only this one answers for GitHub.
247
+ [['--replace-all', 'credential.https://github.com.helper', ''], 'credential helper'],
248
+ [['--add', 'credential.https://github.com.helper', helper], 'credential helper'],
249
+ [['credential.https://github.com.useHttpPath', 'true'], 'credential path'],
250
+ ...(author === undefined ? [] : [
251
+ [['user.name', author.login], 'author name'],
252
+ [['user.email', `${author.githubUserId}+${author.login}@users.noreply.github.com`], 'author address'],
253
+ ]),
254
+ ];
255
+ for (const [args, what] of settings) {
256
+ const done = await git(binary, ['-C', target, 'config', ...args], GIT_COMMAND_TIMEOUT_MS);
257
+ if (!done.ok)
258
+ return `Could not set the clone's ${what}: ${gitFailure(done.stderr)}`;
259
+ }
260
+ return undefined;
261
+ }
262
+ async function register(directory, target, repo) {
263
+ const actual = await realpath(target);
264
+ await addProjectEntry(actual, { directory, name: repo });
265
+ const recorded = (await loadConfig(directory)).projects?.find(project => project.path === actual);
266
+ return { state: 'ready', rootId: projectRootId(actual), name: recorded?.name?.trim() || repo };
267
+ }
268
+ /**
269
+ * The entry of `parent` that is `name` in any capitalisation, or `name` when there is none. GitHub's names ignore
270
+ * case and Cloud's disk does not, so a repository picked again under another spelling must find the folder it has.
271
+ */
272
+ export async function spelledAs(parent, name) {
273
+ const entries = await readdir(parent).catch(() => []);
274
+ return entries.includes(name) ? name : entries.find(entry => entry.toLowerCase() === name.toLowerCase()) ?? name;
275
+ }
276
+ async function performClone(dependencies, owner, repo) {
277
+ const binary = dependencies.git ?? 'git';
278
+ const name = `${owner}/${repo}`;
279
+ const folders = await sharedFolders(await loadConfig(dependencies.directory));
280
+ const base = folders[0]?.path;
281
+ if (base === undefined)
282
+ return { state: 'failed', message: 'This machine shares no folder to clone into.' };
283
+ const ownerFolder = await spelledAs(base, owner);
284
+ const target = join(base, ownerFolder, await spelledAs(join(base, ownerFolder), repo));
285
+ const url = (dependencies.remoteUrl ?? githubUrl)(owner, repo);
286
+ if (await exists(target)) {
287
+ const origin = await git(binary, ['-C', target, 'config', '--get', 'remote.origin.url'], GIT_COMMAND_TIMEOUT_MS);
288
+ const matches = origin.ok && (dependencies.remoteUrl ? origin.stdout.trim() === url : sameRepository(origin.stdout, owner, repo));
289
+ if (!matches)
290
+ return { state: 'failed', message: `A folder named ${name} is already on this machine and is not a clone of that repository. Move it, or add it as a project from the sidebar.` };
291
+ const problem = await configureClone(binary, target, dependencies.helper);
292
+ if (problem !== undefined)
293
+ return { state: 'failed', message: problem };
294
+ return register(dependencies.directory, target, repo);
295
+ }
296
+ // Asked for before the clone, so a repository the App cannot reach is refused in Andorra's words, not Git's.
297
+ let access;
298
+ try {
299
+ access = await (dependencies.token ?? machineRepositoryToken)(dependencies.directory, dependencies.apiBase, owner, repo);
300
+ }
301
+ catch (error) {
302
+ return { state: 'failed', message: error instanceof Error ? error.message : String(error) };
303
+ }
304
+ await mkdir(join(base, ownerFolder), { recursive: true });
305
+ const temporary = `${target}.cloning-${randomBytes(4).toString('hex')}`;
306
+ try {
307
+ const cloned = await git(binary, [
308
+ '-c', 'credential.https://github.com.helper=', '-c', `credential.https://github.com.helper=${dependencies.helper}`,
309
+ '-c', 'credential.https://github.com.useHttpPath=true', 'clone', '--quiet', url, temporary,
310
+ ], CLONE_TIMEOUT_MS);
311
+ if (!cloned.ok)
312
+ return { state: 'failed', message: `Could not clone ${name}: ${gitFailure(cloned.stderr)}` };
313
+ const problem = await configureClone(binary, temporary, dependencies.helper, access);
314
+ if (problem !== undefined)
315
+ return { state: 'failed', message: problem };
316
+ try {
317
+ await moveIntoPlace(temporary, target);
318
+ }
319
+ catch (error) {
320
+ return { state: 'failed', message: `Could not put ${name} in place: ${error instanceof Error ? error.message : String(error)}` };
321
+ }
322
+ return await register(dependencies.directory, target, repo);
323
+ }
324
+ finally {
325
+ await rm(temporary, { recursive: true, force: true }).catch(() => undefined);
326
+ }
327
+ }
328
+ const jobs = new Map();
329
+ /**
330
+ * How many clones are running now. The bridge counts them as work, so it does not restart itself for a newer engine
331
+ * under a clone whose request was already answered `cloning`.
332
+ */
333
+ export function clonesRunning() {
334
+ let running = 0;
335
+ for (const job of jobs.values())
336
+ if (job.settled === undefined)
337
+ running += 1;
338
+ return running;
339
+ }
340
+ /** Forgets every clone this process knows of (tests). */
341
+ export function resetCloneJobs() { jobs.clear(); }
342
+ /**
343
+ * Clones `owner/repo` into the machine's first shared folder and registers it as a project. It never waits long:
344
+ * while the clone runs every call answers `cloning`, so a desktop asks again until it is `ready` or `failed`. A
345
+ * repository already cloned there is reused. A failure is reported once; asking after that starts again.
346
+ */
347
+ export async function cloneRepository(dependencies, params) {
348
+ const { owner, repo } = params;
349
+ if (typeof owner !== 'string' || !GITHUB_ACCOUNT.test(owner) || typeof repo !== 'string' || !GITHUB_REPO.test(repo)) {
350
+ throw new Error('A GitHub owner and repository name are required.');
351
+ }
352
+ if (!dependencies.cloud)
353
+ return { state: 'failed', message: 'Only Cloud clones repositories from GitHub. On this machine, clone it yourself and add the folder as a project.' };
354
+ // Names differ only by case on GitHub, and one folder serves them all.
355
+ const key = `${owner}/${repo}`.toLowerCase();
356
+ let job = jobs.get(key);
357
+ if (job?.settled) {
358
+ jobs.delete(key);
359
+ if (job.settled.state === 'failed')
360
+ return job.settled;
361
+ job = undefined; // ready before: the folder is checked again, and reused when it is still that clone
362
+ }
363
+ if (!job) {
364
+ const created = {
365
+ running: performClone(dependencies, owner, repo).catch((error) => ({ state: 'failed', message: error instanceof Error ? error.message : String(error) })),
366
+ };
367
+ void created.running.then(answer => { created.settled = answer; });
368
+ jobs.set(key, created);
369
+ job = created;
370
+ }
371
+ let timer;
372
+ const waited = new Promise(resolvePromise => { timer = setTimeout(() => resolvePromise({ state: 'cloning' }), dependencies.answerMs ?? CLONE_ANSWER_MS); });
373
+ const answer = await Promise.race([job.running, waited]);
374
+ clearTimeout(timer);
375
+ if (answer.state !== 'cloning' && jobs.get(key) === job)
376
+ jobs.delete(key);
377
+ return answer;
378
+ }
@@ -1,6 +1,6 @@
1
1
  import type { Host } from './protocol.js';
2
2
  export declare const BROWSE_ENTRY_CAP = 1000;
3
- export type HostOperationName = 'whoami' | 'projects' | 'roots' | 'browse' | 'owner.roots' | 'owner.browse' | 'owner.projects.add';
3
+ export type HostOperationName = 'whoami' | 'projects' | 'roots' | 'browse' | 'owner.roots' | 'owner.browse' | 'owner.projects.add' | 'owner.github.clone';
4
4
  export type HostOperationErrorCode = 'not-found' | 'invalid-params' | 'forbidden';
5
5
  export declare class HostOperationError extends Error {
6
6
  readonly code: HostOperationErrorCode;
@@ -4,6 +4,7 @@ import { loadConfig } from '../config.js';
4
4
  import { addProjectEntry } from '../project-registry.js';
5
5
  import { authorizedRoots, directoryInsideFolders, projectRootId, sharedFolders } from '../remote/roots.js';
6
6
  import { RELAY_CAPABILITY_REQUIREMENT } from '../remote/engine-pool.js';
7
+ import { cloneDependenciesFromEnvironment, cloneRepository } from './github.js';
7
8
  import { bridgeCommand } from './wording.js';
8
9
  export const BROWSE_ENTRY_CAP = 1000;
9
10
  const SKIP_NAMES = new Set(['.git', 'node_modules', '.andorracode']);
@@ -52,7 +53,7 @@ export async function hostOperation(directory, op, params, host) {
52
53
  const { APP_SERVER_CAPABILITIES } = await import('../app-server/protocol.js');
53
54
  return {
54
55
  hostname: host.hostname, platform: host.platform, version: host.version, grant: 'full', relay: true,
55
- capabilities: [...new Set([...APP_SERVER_CAPABILITIES, 'remote.engine.relay', RELAY_CAPABILITY_REQUIREMENT])],
56
+ capabilities: [...new Set([...APP_SERVER_CAPABILITIES, 'remote.engine.relay', RELAY_CAPABILITY_REQUIREMENT, 'remote.github.clone'])],
56
57
  };
57
58
  }
58
59
  case 'projects': {
@@ -123,6 +124,15 @@ export async function hostOperation(directory, op, params, host) {
123
124
  const recorded = (await loadConfig(directory)).projects?.find(project => project.path === actual);
124
125
  return { rootId: projectRootId(actual), name: recorded?.name?.trim() || basename(actual) || actual };
125
126
  }
127
+ case 'owner.github.clone': {
128
+ // Answers at once and is asked again while the clone runs: a host operation may not outlast its deadline.
129
+ try {
130
+ return await cloneRepository(await cloneDependenciesFromEnvironment(directory), params);
131
+ }
132
+ catch (error) {
133
+ throw new HostOperationError('invalid-params', error instanceof Error ? error.message : String(error));
134
+ }
135
+ }
126
136
  default:
127
137
  throw new HostOperationError('invalid-params', 'Unknown host operation');
128
138
  }
@@ -4,6 +4,7 @@ import { MODEL_RELAY_CONNECTION_PREFIX } from '../model-relay/wire.js';
4
4
  import { HEARTBEAT_MS } from './cloud.js';
5
5
  import { ControlError } from './control.js';
6
6
  import { compareVersions } from './engines.js';
7
+ import { clonesRunning } from './github.js';
7
8
  import { hostOperation, HostOperationError } from './host-ops.js';
8
9
  import { CLIENT_DEAD_MS, CLIENT_PING_MS, CLOSE, MAX_FRAME_BYTES, PROTOCOL_VERSION } from './protocol.js';
9
10
  export const DEFAULT_RELAY_URL = 'wss://relay.andorracode.com/v1/link';
@@ -22,7 +23,7 @@ export const HOST_REQUEST_HOLD_MS = 10 * 60_000;
22
23
  export const MAX_NEWER_VERSIONS = 4;
23
24
  export const RESTARTING_MESSAGE = 'This machine is restarting to update Andorra Code. Try again in a moment.';
24
25
  const TASK_START_METHODS = new Set(['run.start', 'run.resume']);
25
- const HOST_OPERATIONS = new Set(['whoami', 'projects', 'roots', 'browse', 'owner.roots', 'owner.browse', 'owner.projects.add']);
26
+ const HOST_OPERATIONS = new Set(['whoami', 'projects', 'roots', 'browse', 'owner.roots', 'owner.browse', 'owner.projects.add', 'owner.github.clone']);
26
27
  export const hostDependencies = {
27
28
  createRelay: (directory, engines) => new RemoteEngineRelay(directory, {}, engines ? { engines } : {}),
28
29
  };
@@ -165,6 +166,8 @@ export async function runBridgeHost(hostOptions) {
165
166
  let restarting = false;
166
167
  // Requests and host operations not yet answered: a restart would cut a compaction or a save short, or tear a config write.
167
168
  let answering = 0;
169
+ // A clone goes on after its request was answered `cloning`, so it is counted on its own: a restart would cut it off.
170
+ const busyHere = () => answering > 0 || clonesRunning() > 0;
168
171
  // Asking the engines what they hold can outlast the interval between checks.
169
172
  let checking = false;
170
173
  const restartIfIdle = async () => {
@@ -182,7 +185,7 @@ export async function runBridgeHost(hostOptions) {
182
185
  const engines = options.engines;
183
186
  if (!engines || restarting || signal.aborted || newer.size === 0)
184
187
  return;
185
- if (answering > 0 || relay.runningTasks() > 0 || engines.installing() > 0)
188
+ if (busyHere() || relay.runningTasks() > 0 || engines.installing() > 0)
186
189
  return;
187
190
  const installed = [];
188
191
  for (const version of newer)
@@ -196,7 +199,7 @@ export async function runBridgeHost(hostOptions) {
196
199
  // Work no run.start announced would be lost with the engines: a wake, a run an engine started itself, a background process, a terminal.
197
200
  if (await relay.holdsWork())
198
201
  return;
199
- if (restarting || signal.aborted || answering > 0 || relay.runningTasks() > 0)
202
+ if (restarting || signal.aborted || busyHere() || relay.runningTasks() > 0)
200
203
  return;
201
204
  // From here on task starts are refused, so none can begin while the restart is written.
202
205
  restarting = true;
@@ -208,7 +211,7 @@ export async function runBridgeHost(hostOptions) {
208
211
  log(`Could not hand this bridge over to Andorra Code ${next}: ${error instanceof Error ? error.message : String(error)}`);
209
212
  return;
210
213
  }
211
- if (answering > 0 || relay.runningTasks() > 0 || await relay.holdsWork()) {
214
+ if (busyHere() || relay.runningTasks() > 0 || await relay.holdsWork()) {
212
215
  await engines.withdrawHostVersion().catch(error => log(`Could not withdraw the restart: ${error instanceof Error ? error.message : String(error)}`));
213
216
  restarting = false;
214
217
  return;
@@ -0,0 +1,48 @@
1
+ /** Byte limits the service enforces on the two attachments (infra/andorra-auth/bug_report.py). */
2
+ export declare const GRAPH_LIMIT = 8000;
3
+ export declare const TRAJECTORY_LIMIT = 12000;
4
+ export interface ReportSession {
5
+ id: string;
6
+ name: string;
7
+ updatedAt: string;
8
+ current?: true;
9
+ }
10
+ export interface SessionAttachments {
11
+ graph?: string;
12
+ trajectory?: string;
13
+ }
14
+ /**
15
+ * The sessions a report can be about: the newest saved ones, with the one this run belongs to first. Only the
16
+ * newest files are opened, so a home with thousands of sessions costs a directory listing and a few reads.
17
+ */
18
+ export declare function listReportSessions(home: string, currentId?: string, limit?: number): Promise<ReportSession[]>;
19
+ /**
20
+ * A graph as one line per node and edge. Settings are listed; the text of an instruction, prompt or command is
21
+ * replaced by its length, because a bug in routing or tools is visible without the user's wording.
22
+ */
23
+ export declare function graphOutline(value: unknown): string | undefined;
24
+ /**
25
+ * Reads a session's trajectory into the two attachments: the graph of the last run it reports, and each run as a short
26
+ * list of steps (nodes, tools, retries, refusals, how it stopped). It never copies a prompt, a model reply, tool
27
+ * arguments or a successful tool's output; a failed step keeps the first 200 characters of its error.
28
+ */
29
+ export declare class TrajectoryDigest {
30
+ private readonly runs;
31
+ /** One line of the trajectory file. Model requests and replies are the bulk of the file and are skipped unparsed. */
32
+ add(line: string): void;
33
+ private run;
34
+ private at;
35
+ private flush;
36
+ private event;
37
+ /** `skipOpenRun` leaves out a last run that has not finished: in the reporting session, that run is the report itself. */
38
+ result(options?: {
39
+ skipOpenRun?: boolean;
40
+ }): SessionAttachments;
41
+ }
42
+ /** Whether this machine has a saved session or a trajectory under that id. */
43
+ export declare function sessionExists(home: string, sessionId: string): Promise<boolean>;
44
+ /** The graph and compressed trajectory of one saved session, or nothing when the session left no trajectory. */
45
+ export declare function sessionAttachments(home: string, sessionId: string, options?: {
46
+ current?: boolean;
47
+ signal?: AbortSignal;
48
+ }): Promise<SessionAttachments>;