@andorra-labs/code 0.1.16 → 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 (236) 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-execution.js +108 -19
  4. package/dist/src/agent-mcp-catalog.js +1 -0
  5. package/dist/src/agent-mcp.d.ts +3 -0
  6. package/dist/src/agent-mcp.js +33 -1
  7. package/dist/src/andorra/entry.d.ts +10 -0
  8. package/dist/src/andorra/entry.js +18 -4
  9. package/dist/src/andorra/errors.js +3 -0
  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 +30 -44
  21. package/dist/src/app-server/protocol.js +5 -1
  22. package/dist/src/app-server/workspace.d.ts +108 -0
  23. package/dist/src/app-server/workspace.js +608 -11
  24. package/dist/src/app-server.d.ts +390 -33
  25. package/dist/src/app-server.js +3033 -565
  26. package/dist/src/attachments.d.ts +10 -0
  27. package/dist/src/attachments.js +102 -7
  28. package/dist/src/automation-tool.js +2 -1
  29. package/dist/src/bridge/cloud.d.ts +27 -0
  30. package/dist/src/bridge/cloud.js +187 -0
  31. package/dist/src/bridge/command.d.ts +30 -0
  32. package/dist/src/bridge/command.js +359 -0
  33. package/dist/src/bridge/control.d.ts +70 -0
  34. package/dist/src/bridge/control.js +238 -0
  35. package/dist/src/bridge/engines.d.ts +90 -0
  36. package/dist/src/bridge/engines.js +601 -0
  37. package/dist/src/bridge/github.d.ts +108 -0
  38. package/dist/src/bridge/github.js +378 -0
  39. package/dist/src/bridge/host-ops.d.ts +9 -0
  40. package/dist/src/bridge/host-ops.js +139 -0
  41. package/dist/src/bridge/host.d.ts +47 -0
  42. package/dist/src/bridge/host.js +543 -0
  43. package/dist/src/bridge/link.d.ts +38 -0
  44. package/dist/src/bridge/link.js +508 -0
  45. package/dist/src/bridge/login-link.d.ts +29 -0
  46. package/dist/src/bridge/login-link.js +54 -0
  47. package/dist/src/bridge/protocol.d.ts +136 -0
  48. package/dist/src/bridge/protocol.js +11 -0
  49. package/dist/src/bridge/store.d.ts +12 -0
  50. package/dist/src/bridge/store.js +61 -0
  51. package/dist/src/bridge/wording.d.ts +6 -0
  52. package/dist/src/bridge/wording.js +10 -0
  53. package/dist/src/browser-server.js +7 -1
  54. package/dist/src/browser-ui/tokens.css +1 -1
  55. package/dist/src/bug-report-attachments.d.ts +48 -0
  56. package/dist/src/bug-report-attachments.js +327 -0
  57. package/dist/src/bug-report.d.ts +23 -3
  58. package/dist/src/bug-report.js +72 -9
  59. package/dist/src/change-authors.d.ts +41 -0
  60. package/dist/src/change-authors.js +146 -0
  61. package/dist/src/cli.d.ts +1 -3
  62. package/dist/src/cli.js +191 -35
  63. package/dist/src/codex-provider.js +1 -1
  64. package/dist/src/coding-tools.js +24 -17
  65. package/dist/src/command-screens.d.ts +6 -0
  66. package/dist/src/command-screens.js +14 -11
  67. package/dist/src/commands.d.ts +15 -3
  68. package/dist/src/commands.js +2 -1
  69. package/dist/src/compaction-phrases.js +1 -1
  70. package/dist/src/completion.js +89 -8
  71. package/dist/src/config.d.ts +71 -3
  72. package/dist/src/config.js +205 -78
  73. package/dist/src/context-budget.js +15 -2
  74. package/dist/src/deadline.js +13 -1
  75. package/dist/src/decision/DecisionEngine.d.ts +2 -0
  76. package/dist/src/decision/DecisionManager.d.ts +11 -0
  77. package/dist/src/decision/DecisionManager.js +36 -0
  78. package/dist/src/decision/applyTaskKind.d.ts +8 -0
  79. package/dist/src/decision/applyTaskKind.js +53 -0
  80. package/dist/src/decision/checks.js +1 -1
  81. package/dist/src/decision/hostedPolicy.js +2 -1
  82. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +2 -0
  83. package/dist/src/decision/providers/AndorraDecisionProvider.js +12 -0
  84. package/dist/src/decision/requestPhrases.js +0 -1
  85. package/dist/src/decision/taskKind.d.ts +52 -0
  86. package/dist/src/decision/taskKind.js +76 -0
  87. package/dist/src/decision/types.d.ts +1 -1
  88. package/dist/src/default-graph.js +1 -1
  89. package/dist/src/efficiency.d.ts +5 -0
  90. package/dist/src/efficiency.js +5 -1
  91. package/dist/src/effort-routing.d.ts +27 -0
  92. package/dist/src/effort-routing.js +34 -0
  93. package/dist/src/evidence.d.ts +110 -0
  94. package/dist/src/evidence.js +195 -0
  95. package/dist/src/file-diff.d.ts +4 -0
  96. package/dist/src/file-diff.js +2 -1
  97. package/dist/src/github-app/agent-writes.d.ts +102 -0
  98. package/dist/src/github-app/agent-writes.js +320 -0
  99. package/dist/src/github-app/client.d.ts +368 -0
  100. package/dist/src/github-app/client.js +830 -0
  101. package/dist/src/github-app/event-source.d.ts +208 -0
  102. package/dist/src/github-app/event-source.js +684 -0
  103. package/dist/src/github-app/metrics.d.ts +32 -0
  104. package/dist/src/github-app/metrics.js +49 -0
  105. package/dist/src/github-app/review-loop.d.ts +274 -0
  106. package/dist/src/github-app/review-loop.js +1177 -0
  107. package/dist/src/github-app/review-node.d.ts +81 -0
  108. package/dist/src/github-app/review-node.js +205 -0
  109. package/dist/src/github-app/review-post.d.ts +73 -0
  110. package/dist/src/github-app/review-post.js +139 -0
  111. package/dist/src/github-app/review-text.d.ts +107 -0
  112. package/dist/src/github-app/review-text.js +1133 -0
  113. package/dist/src/github-app/review-threads.d.ts +47 -0
  114. package/dist/src/github-app/review-threads.js +107 -0
  115. package/dist/src/github-app/reviewer.d.ts +121 -0
  116. package/dist/src/github-app/reviewer.js +598 -0
  117. package/dist/src/github-app/store.d.ts +59 -0
  118. package/dist/src/github-app/store.js +148 -0
  119. package/dist/src/github-app/triggers.d.ts +141 -0
  120. package/dist/src/github-app/triggers.js +441 -0
  121. package/dist/src/github-names.d.ts +15 -0
  122. package/dist/src/github-names.js +15 -0
  123. package/dist/src/glob-search.d.ts +61 -0
  124. package/dist/src/glob-search.js +180 -0
  125. package/dist/src/graph-health.js +6 -1
  126. package/dist/src/graph-manager-chat.js +1 -1
  127. package/dist/src/graph-preview.d.ts +48 -0
  128. package/dist/src/graph-preview.js +56 -0
  129. package/dist/src/graph-provider-portability.js +2 -1
  130. package/dist/src/graph-runner.js +65 -4
  131. package/dist/src/graph-server.js +7 -5
  132. package/dist/src/graph-sync.js +3 -3
  133. package/dist/src/graph-ui/app.js +121 -7
  134. package/dist/src/graph-ui/icons.js +2 -1
  135. package/dist/src/graph-ui/studio.js +15 -1
  136. package/dist/src/graph-ui/tokens.css +1 -1
  137. package/dist/src/graphs.d.ts +40 -1
  138. package/dist/src/graphs.js +164 -15
  139. package/dist/src/hardened-runtime.js +32 -21
  140. package/dist/src/image-input.d.ts +16 -0
  141. package/dist/src/image-input.js +41 -0
  142. package/dist/src/membership.d.ts +10 -0
  143. package/dist/src/membership.js +19 -4
  144. package/dist/src/model-health-cache.js +1 -1
  145. package/dist/src/model-metadata.d.ts +6 -0
  146. package/dist/src/model-metadata.js +35 -15
  147. package/dist/src/model-override.d.ts +2 -1
  148. package/dist/src/model-override.js +9 -0
  149. package/dist/src/model-relay/local.d.ts +116 -0
  150. package/dist/src/model-relay/local.js +468 -0
  151. package/dist/src/model-relay/remote.d.ts +129 -0
  152. package/dist/src/model-relay/remote.js +252 -0
  153. package/dist/src/model-relay/runs.d.ts +34 -0
  154. package/dist/src/model-relay/runs.js +146 -0
  155. package/dist/src/model-relay/wire.d.ts +5 -0
  156. package/dist/src/model-relay/wire.js +5 -0
  157. package/dist/src/model-tiers.d.ts +3 -0
  158. package/dist/src/model-tiers.js +3 -3
  159. package/dist/src/project-registry.d.ts +21 -0
  160. package/dist/src/project-registry.js +74 -0
  161. package/dist/src/provider-engine.d.ts +13 -1
  162. package/dist/src/provider-engine.js +74 -0
  163. package/dist/src/provider-import.d.ts +0 -12
  164. package/dist/src/provider-import.js +7 -195
  165. package/dist/src/providers.d.ts +28 -2
  166. package/dist/src/providers.js +59 -12
  167. package/dist/src/pull-request-logs.d.ts +12 -1
  168. package/dist/src/pull-request-logs.js +14 -3
  169. package/dist/src/pull-requests.d.ts +338 -8
  170. package/dist/src/pull-requests.js +482 -53
  171. package/dist/src/react-runtime.js +99 -16
  172. package/dist/src/remote/engine-pool.d.ts +88 -4
  173. package/dist/src/remote/engine-pool.js +367 -90
  174. package/dist/src/remote/roots.d.ts +19 -0
  175. package/dist/src/remote/roots.js +45 -7
  176. package/dist/src/remote/types.d.ts +0 -44
  177. package/dist/src/run-control.d.ts +7 -0
  178. package/dist/src/run-control.js +23 -0
  179. package/dist/src/run-records.d.ts +7 -2
  180. package/dist/src/run-records.js +71 -6
  181. package/dist/src/runtime.d.ts +34 -2
  182. package/dist/src/runtime.js +18 -2
  183. package/dist/src/session-changes.d.ts +35 -0
  184. package/dist/src/session-changes.js +194 -6
  185. package/dist/src/session-monitor.js +2 -1
  186. package/dist/src/session-reaper.d.ts +1 -1
  187. package/dist/src/session-reaper.js +6 -1
  188. package/dist/src/session-summary.d.ts +2 -1
  189. package/dist/src/session-summary.js +2 -1
  190. package/dist/src/sessions.d.ts +35 -1
  191. package/dist/src/sessions.js +70 -4
  192. package/dist/src/skills/bundled/bug-report/SKILL.md +51 -7
  193. package/dist/src/skills/bundled/diagram/SKILL.md +5 -3
  194. package/dist/src/skills/bundled/graph-manager/SKILL.md +7 -4
  195. package/dist/src/skills/bundled/provenance.json +3 -3
  196. package/dist/src/skills/runtime-skills.js +1 -1
  197. package/dist/src/task-checkout.d.ts +141 -0
  198. package/dist/src/task-checkout.js +558 -0
  199. package/dist/src/telemetry/emitter.d.ts +15 -0
  200. package/dist/src/telemetry/emitter.js +35 -1
  201. package/dist/src/telemetry/schema.d.ts +25 -2
  202. package/dist/src/telemetry/schema.js +52 -4
  203. package/dist/src/telemetry/surface.d.ts +2 -1
  204. package/dist/src/telemetry/surface.js +4 -1
  205. package/dist/src/terminal-ui.d.ts +1 -0
  206. package/dist/src/terminal-ui.js +10 -3
  207. package/dist/src/test-edit-guard.d.ts +37 -0
  208. package/dist/src/test-edit-guard.js +216 -3
  209. package/dist/src/thinking-level-detect.d.ts +11 -0
  210. package/dist/src/thinking-level-detect.js +47 -0
  211. package/dist/src/thinking-levels.d.ts +30 -0
  212. package/dist/src/thinking-levels.js +124 -0
  213. package/dist/src/timers.d.ts +3 -0
  214. package/dist/src/tool-catalog.js +1 -1
  215. package/dist/src/tools.js +59 -9
  216. package/dist/src/transcript.js +1 -1
  217. package/dist/src/types.d.ts +34 -0
  218. package/package.json +6 -1
  219. package/dist/src/remote/cert.d.ts +0 -11
  220. package/dist/src/remote/cert.js +0 -87
  221. package/dist/src/remote/client.d.ts +0 -119
  222. package/dist/src/remote/client.js +0 -544
  223. package/dist/src/remote/command.d.ts +0 -4
  224. package/dist/src/remote/command.js +0 -194
  225. package/dist/src/remote/errors.d.ts +0 -11
  226. package/dist/src/remote/errors.js +0 -14
  227. package/dist/src/remote/network.d.ts +0 -22
  228. package/dist/src/remote/network.js +0 -102
  229. package/dist/src/remote/pairing.d.ts +0 -63
  230. package/dist/src/remote/pairing.js +0 -299
  231. package/dist/src/remote/pem.d.ts +0 -2
  232. package/dist/src/remote/pem.js +0 -7
  233. package/dist/src/remote/serve.d.ts +0 -68
  234. package/dist/src/remote/serve.js +0 -244
  235. package/dist/src/remote/server.d.ts +0 -21
  236. package/dist/src/remote/server.js +0 -406
@@ -0,0 +1,108 @@
1
+ /** A clone still running after this long is stopped and reported as failed. */
2
+ export declare const CLONE_TIMEOUT_MS: number;
3
+ /** How long a clone request waits for the clone before answering `cloning`; a host operation has 30 seconds in all. */
4
+ export declare const CLONE_ANSWER_MS = 2000;
5
+ export type RepositoryTokenErrorCode = 'off' | 'not-connected' | 'not-covered' | 'not-cloud' | 'suspended' | 'permissions-pending' | 'not-allowed' | 'account-unavailable' | 'unlinked' | 'rate-limited' | 'network' | 'server';
6
+ export declare class RepositoryTokenError extends Error {
7
+ readonly code: RepositoryTokenErrorCode;
8
+ constructor(code: RepositoryTokenErrorCode, message: string);
9
+ }
10
+ export interface RepositoryToken {
11
+ token: string;
12
+ expiresAt: string;
13
+ login: string;
14
+ githubUserId: number;
15
+ push: boolean;
16
+ }
17
+ /** Asks the service for a token for one repository, as the machine `environmentToken` names. */
18
+ export declare function repositoryToken(apiBase: string, environmentTokenValue: string, owner: string, repo: string, fetcher?: typeof globalThis.fetch): Promise<RepositoryToken>;
19
+ /** The machine's own token for `owner/repo`: its secret is traded for an environment token, and that for the repository's. */
20
+ export declare function machineRepositoryToken(directory: string, apiBase: string, owner: string, repo: string): Promise<RepositoryToken>;
21
+ /** `owner/repo` from the path Git names in a credential request (`owner/repo.git`, with or without what follows it). */
22
+ export declare function repositoryOfPath(path: string | undefined): {
23
+ owner: string;
24
+ repo: string;
25
+ } | undefined;
26
+ /** A credential request as Git writes it: `key=value` lines up to a blank line. */
27
+ export declare function parseCredentialRequest(stdin: string): Record<string, string>;
28
+ export interface GitCredentialInput {
29
+ /** What Git asks: `get`, `store` or `erase`. */
30
+ action: string | undefined;
31
+ stdin: string;
32
+ apiBase: string;
33
+ directory: string;
34
+ /** Writes to Git: the credential, and nothing else. */
35
+ print(line: string): void;
36
+ /** Writes what a person reads in Git's own output. */
37
+ warn(line: string): void;
38
+ token?: typeof machineRepositoryToken;
39
+ }
40
+ /**
41
+ * Git's credential helper (`andorra bridge git-credential <action>`). It answers only a `get` for
42
+ * `https://github.com/<owner>/<repo>`; anything else gets no credential, and Git goes on to whatever else it has.
43
+ * `store` and `erase` do nothing: there is nothing kept to change.
44
+ */
45
+ export declare function runGitCredential(input: GitCredentialInput): Promise<number>;
46
+ export type CloneAnswer = {
47
+ state: 'cloning';
48
+ } | {
49
+ state: 'ready';
50
+ rootId: string;
51
+ name: string;
52
+ } | {
53
+ state: 'failed';
54
+ message: string;
55
+ };
56
+ export interface CloneDependencies {
57
+ directory: string;
58
+ apiBase: string;
59
+ /** Whether this machine is a Cloud instance: a linked workstation keeps its own Git credentials and clones nothing here. */
60
+ cloud: boolean;
61
+ /** The credential helper as Git's configuration names it (`!command`). */
62
+ helper: string;
63
+ git?: string;
64
+ token?: typeof machineRepositoryToken;
65
+ /** Where the repository is fetched from; tests point it at a local repository. */
66
+ remoteUrl?: (owner: string, repo: string) => string;
67
+ answerMs?: number;
68
+ }
69
+ /**
70
+ * The helper this process's own CLI provides, named by the paths it is running from. `settings` are set for the
71
+ * helper itself, so it reaches the same service and home as this machine's bridge even when the Git that runs it was
72
+ * started with a narrower environment (a task's command, say).
73
+ */
74
+ export declare function credentialHelperCommand(execPath?: string, script?: string | undefined, settings?: Record<string, string>): string;
75
+ /** The helper's file in the machine's Andorra home: the one path every clone's configuration names. */
76
+ export declare const CREDENTIAL_HELPER_FILE = "git-credential-andorra";
77
+ /**
78
+ * Writes the helper every clone names and answers it as Git's configuration takes it. A clone's configuration
79
+ * outlives the engine that made it, and an engine's own path changes with its version (old versions are pruned), so
80
+ * clones name this one file instead, and it is rewritten to run the current engine whenever the bridge starts and
81
+ * before every clone. It holds paths and the service's address: no secret.
82
+ */
83
+ export declare function installCredentialHelper(directory: string, options?: {
84
+ execPath?: string;
85
+ script?: string;
86
+ settings?: Record<string, string>;
87
+ }): Promise<string>;
88
+ /** The helper for this machine as its environment describes it, written afresh. */
89
+ export declare function installCredentialHelperFromEnvironment(directory: string, environment?: NodeJS.ProcessEnv): Promise<string>;
90
+ export declare function cloneDependenciesFromEnvironment(directory: string, environment?: NodeJS.ProcessEnv): Promise<CloneDependencies>;
91
+ /**
92
+ * The entry of `parent` that is `name` in any capitalisation, or `name` when there is none. GitHub's names ignore
93
+ * case and Cloud's disk does not, so a repository picked again under another spelling must find the folder it has.
94
+ */
95
+ export declare function spelledAs(parent: string, name: string): Promise<string>;
96
+ /**
97
+ * How many clones are running now. The bridge counts them as work, so it does not restart itself for a newer engine
98
+ * under a clone whose request was already answered `cloning`.
99
+ */
100
+ export declare function clonesRunning(): number;
101
+ /** Forgets every clone this process knows of (tests). */
102
+ export declare function resetCloneJobs(): void;
103
+ /**
104
+ * Clones `owner/repo` into the machine's first shared folder and registers it as a project. It never waits long:
105
+ * while the clone runs every call answers `cloning`, so a desktop asks again until it is `ready` or `failed`. A
106
+ * repository already cloned there is reused. A failure is reported once; asking after that starts again.
107
+ */
108
+ export declare function cloneRepository(dependencies: CloneDependencies, params: Record<string, unknown>): Promise<CloneAnswer>;
@@ -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
+ }
@@ -0,0 +1,9 @@
1
+ import type { Host } from './protocol.js';
2
+ export declare const BROWSE_ENTRY_CAP = 1000;
3
+ export type HostOperationName = 'whoami' | 'projects' | 'roots' | 'browse' | 'owner.roots' | 'owner.browse' | 'owner.projects.add' | 'owner.github.clone';
4
+ export type HostOperationErrorCode = 'not-found' | 'invalid-params' | 'forbidden';
5
+ export declare class HostOperationError extends Error {
6
+ readonly code: HostOperationErrorCode;
7
+ constructor(code: HostOperationErrorCode, message: string);
8
+ }
9
+ export declare function hostOperation(directory: string, op: HostOperationName, params: Record<string, unknown>, host: Host): Promise<unknown>;
@@ -0,0 +1,139 @@
1
+ import { opendir, stat } from 'node:fs/promises';
2
+ import { basename, dirname, isAbsolute, join } from 'node:path';
3
+ import { loadConfig } from '../config.js';
4
+ import { addProjectEntry } from '../project-registry.js';
5
+ import { authorizedRoots, directoryInsideFolders, projectRootId, sharedFolders } from '../remote/roots.js';
6
+ import { RELAY_CAPABILITY_REQUIREMENT } from '../remote/engine-pool.js';
7
+ import { cloneDependenciesFromEnvironment, cloneRepository } from './github.js';
8
+ import { bridgeCommand } from './wording.js';
9
+ export const BROWSE_ENTRY_CAP = 1000;
10
+ const SKIP_NAMES = new Set(['.git', 'node_modules', '.andorracode']);
11
+ const outsideFolders = () => `That folder is outside the folders this machine shares. Run ${bridgeCommand('folders add <path>')} on it.`;
12
+ export class HostOperationError extends Error {
13
+ code;
14
+ constructor(code, message) {
15
+ super(message);
16
+ this.code = code;
17
+ this.name = 'HostOperationError';
18
+ }
19
+ }
20
+ async function listDirectory(directory) {
21
+ const entries = [];
22
+ let hasMore = false;
23
+ for await (const entry of await opendir(directory)) {
24
+ if (entry.isSymbolicLink() || SKIP_NAMES.has(entry.name))
25
+ continue;
26
+ if (!(entry.isDirectory() || entry.isFile()))
27
+ continue;
28
+ if (entries.length >= BROWSE_ENTRY_CAP) {
29
+ hasMore = true;
30
+ break;
31
+ }
32
+ entries.push({ name: entry.name, type: entry.isDirectory() ? 'directory' : 'file' });
33
+ }
34
+ entries.sort((left, right) => left.type === right.type ? left.name.localeCompare(right.name) : left.type === 'directory' ? -1 : 1);
35
+ return { entries, hasMore };
36
+ }
37
+ function optionalString(params, key) {
38
+ const value = params[key];
39
+ return typeof value === 'string' ? value : undefined;
40
+ }
41
+ /** The real directory at `path`, which must lie inside a shared folder (`forbidden` otherwise). */
42
+ async function sharedDirectory(directory, path, missing) {
43
+ const found = await directoryInsideFolders(await sharedFolders(await loadConfig(directory)), path);
44
+ if (found === undefined)
45
+ throw new HostOperationError('not-found', missing);
46
+ if (!found.inside)
47
+ throw new HostOperationError('forbidden', outsideFolders());
48
+ return found.path;
49
+ }
50
+ export async function hostOperation(directory, op, params, host) {
51
+ switch (op) {
52
+ case 'whoami': {
53
+ const { APP_SERVER_CAPABILITIES } = await import('../app-server/protocol.js');
54
+ return {
55
+ hostname: host.hostname, platform: host.platform, version: host.version, grant: 'full', relay: true,
56
+ capabilities: [...new Set([...APP_SERVER_CAPABILITIES, 'remote.engine.relay', RELAY_CAPABILITY_REQUIREMENT, 'remote.github.clone'])],
57
+ };
58
+ }
59
+ case 'projects': {
60
+ const roots = await authorizedRoots(await loadConfig(directory));
61
+ return { projects: roots.filter(root => root.kind === 'project').map(root => ({ rootId: root.id, name: root.label })) };
62
+ }
63
+ case 'roots': {
64
+ const roots = await authorizedRoots(await loadConfig(directory));
65
+ return { roots: roots.map(root => ({ id: root.id, label: root.label, kind: root.kind })) };
66
+ }
67
+ case 'browse': {
68
+ const rootId = optionalString(params, 'root');
69
+ const roots = await authorizedRoots(await loadConfig(directory));
70
+ const root = roots.find(entry => entry.id === rootId);
71
+ if (!root)
72
+ throw new HostOperationError('not-found', 'Unknown root');
73
+ const rel = optionalString(params, 'rel') ?? '';
74
+ if (rel.includes('\0') || rel.length > 4096
75
+ || rel.startsWith('/') || rel.startsWith('\\') || /^[A-Za-z]:/.test(rel)
76
+ || rel.split(/[\\/]/).includes('..'))
77
+ throw new HostOperationError('invalid-params', 'Invalid path');
78
+ const { resolveInside } = await import('../app-server/workspace.js');
79
+ const target = await resolveInside(root.path, rel).catch(() => undefined);
80
+ if (target === undefined)
81
+ throw new HostOperationError('forbidden', 'That path is outside the shared folder');
82
+ const info = await stat(target).catch(() => undefined);
83
+ if (!info)
84
+ throw new HostOperationError('not-found', 'That folder no longer exists');
85
+ if (!info.isDirectory())
86
+ throw new HostOperationError('invalid-params', 'Only folders can be listed');
87
+ const listing = await listDirectory(target);
88
+ return {
89
+ rootId: root.id,
90
+ rel,
91
+ parent: rel === '' || rel === '.' ? null : dirname(rel.split('\\').join('/')) === '.' ? '' : dirname(rel.split('\\').join('/')),
92
+ ...listing,
93
+ };
94
+ }
95
+ case 'owner.roots': {
96
+ // The desktop browses for projects only inside the folders this machine shares.
97
+ return { roots: (await sharedFolders(await loadConfig(directory))).map(folder => ({ path: folder.path, name: folder.label })) };
98
+ }
99
+ case 'owner.browse': {
100
+ const requested = optionalString(params, 'path') ?? '';
101
+ if (!requested || requested.length > 4096 || requested.includes('\0') || !isAbsolute(requested)) {
102
+ throw new HostOperationError('invalid-params', 'An absolute host directory is required');
103
+ }
104
+ const actual = await sharedDirectory(directory, requested, 'Directory does not exist');
105
+ const listing = await listDirectory(actual);
106
+ const parent = dirname(actual);
107
+ // Never offer a way above a shared folder.
108
+ const upward = parent !== actual && (await directoryInsideFolders(await sharedFolders(await loadConfig(directory)), parent))?.inside === true;
109
+ return {
110
+ path: actual, parent: upward ? parent : null,
111
+ ...listing, entries: listing.entries.map(entry => ({ ...entry, path: join(actual, entry.name) })),
112
+ };
113
+ }
114
+ case 'owner.projects.add': {
115
+ const path = params.path;
116
+ const name = params.name;
117
+ if (typeof path !== 'string' || path.length > 4096 || path.includes('\0') || !isAbsolute(path)
118
+ || (name !== undefined && (typeof name !== 'string' || !name.trim() || name.length > 100 || /[\0\r\n]/.test(name)))) {
119
+ throw new HostOperationError('invalid-params', 'Invalid host project path/name');
120
+ }
121
+ const actual = await sharedDirectory(directory, path, 'Project directory does not exist');
122
+ const projectName = typeof name === 'string' ? name.trim() : basename(actual) || actual;
123
+ await addProjectEntry(actual, { directory, name: projectName });
124
+ const recorded = (await loadConfig(directory)).projects?.find(project => project.path === actual);
125
+ return { rootId: projectRootId(actual), name: recorded?.name?.trim() || basename(actual) || actual };
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
+ }
136
+ default:
137
+ throw new HostOperationError('invalid-params', 'Unknown host operation');
138
+ }
139
+ }