@andorra-labs/code 0.1.17 → 0.1.19
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.
- package/dist/src/account-jev-savings.d.ts +4 -0
- package/dist/src/account-jev-savings.js +92 -0
- package/dist/src/acp-agent.js +2 -2
- package/dist/src/agent-execution.js +441 -53
- package/dist/src/agent-mcp.js +7 -1
- package/dist/src/agent-modifiers.js +5 -7
- package/dist/src/analytics.d.ts +19 -1
- package/dist/src/analytics.js +9 -1
- package/dist/src/andorra/entry.js +15 -6
- package/dist/src/andorra/errors.js +3 -0
- package/dist/src/andorra/hosted.d.ts +8 -0
- package/dist/src/andorra/hosted.js +22 -3
- package/dist/src/andorra/streams.d.ts +49 -0
- package/dist/src/andorra/streams.js +98 -0
- package/dist/src/antigravity-acp.d.ts +28 -0
- package/dist/src/antigravity-acp.js +150 -0
- package/dist/src/antigravity-terminal.d.ts +2 -0
- package/dist/src/antigravity-terminal.js +214 -0
- package/dist/src/app-server/adaptive-routing-settings.d.ts +37 -0
- package/dist/src/app-server/adaptive-routing-settings.js +69 -0
- package/dist/src/app-server/artifact.d.ts +14 -0
- package/dist/src/app-server/artifact.js +46 -0
- package/dist/src/app-server/legal-protocol.d.ts +33 -0
- package/dist/src/app-server/legal-protocol.js +16 -0
- package/dist/src/app-server/protocol.d.ts +34 -3
- package/dist/src/app-server/protocol.js +3 -1
- package/dist/src/app-server/telemetry-protocol.d.ts +53 -0
- package/dist/src/app-server/telemetry-protocol.js +2 -0
- package/dist/src/app-server/telemetry.d.ts +38 -0
- package/dist/src/app-server/telemetry.js +163 -0
- package/dist/src/app-server/workspace.d.ts +21 -0
- package/dist/src/app-server/workspace.js +192 -10
- package/dist/src/app-server.d.ts +82 -26
- package/dist/src/app-server.js +1573 -417
- package/dist/src/attachments.d.ts +10 -0
- package/dist/src/attachments.js +102 -7
- package/dist/src/auth/AuthManager.d.ts +11 -2
- package/dist/src/auth/AuthManager.js +56 -13
- package/dist/src/auth/index.d.ts +5 -1
- package/dist/src/auth/index.js +8 -1
- package/dist/src/auth/lifecycle.d.ts +13 -0
- package/dist/src/auth/lifecycle.js +109 -0
- package/dist/src/auth/store.d.ts +1 -0
- package/dist/src/auth/store.js +12 -0
- package/dist/src/auth/types.d.ts +12 -0
- package/dist/src/automation-runner.js +2 -0
- package/dist/src/automation-service.js +7 -2
- package/dist/src/automation-tool.js +2 -1
- package/dist/src/benchmark-scores.d.ts +88 -0
- package/dist/src/benchmark-scores.js +302 -0
- package/dist/src/bridge/command.js +16 -1
- package/dist/src/bridge/control.d.ts +3 -1
- package/dist/src/bridge/control.js +9 -3
- package/dist/src/bridge/engines.d.ts +2 -0
- package/dist/src/bridge/engines.js +9 -0
- package/dist/src/bridge/github.d.ts +108 -0
- package/dist/src/bridge/github.js +378 -0
- package/dist/src/bridge/host-ops.d.ts +3 -3
- package/dist/src/bridge/host-ops.js +14 -2
- package/dist/src/bridge/host.d.ts +2 -0
- package/dist/src/bridge/host.js +70 -16
- package/dist/src/bridge/protocol.d.ts +1 -0
- package/dist/src/bridge/protocol.js +1 -0
- package/dist/src/browser-panel-tool.d.ts +12 -0
- package/dist/src/browser-panel-tool.js +30 -3
- package/dist/src/browser-runner.js +53 -62
- package/dist/src/browser-server.js +10 -4
- package/dist/src/browser-session.d.ts +14 -0
- package/dist/src/browser-session.js +57 -12
- package/dist/src/browser-view.d.ts +40 -1
- package/dist/src/browser-view.js +163 -9
- package/dist/src/browser-window-style.d.ts +27 -0
- package/dist/src/browser-window-style.js +244 -0
- package/dist/src/bug-report-attachments.d.ts +48 -0
- package/dist/src/bug-report-attachments.js +327 -0
- package/dist/src/bug-report.d.ts +23 -3
- package/dist/src/bug-report.js +72 -9
- package/dist/src/claude-provider.d.ts +1 -0
- package/dist/src/claude-provider.js +77 -36
- package/dist/src/cli.d.ts +1 -3
- package/dist/src/cli.js +245 -62
- package/dist/src/codex-provider.d.ts +1 -0
- package/dist/src/codex-provider.js +44 -8
- package/dist/src/coding-tools.d.ts +1 -0
- package/dist/src/coding-tools.js +28 -7
- package/dist/src/command-screens.d.ts +1 -1
- package/dist/src/command-screens.js +2 -2
- package/dist/src/commands.d.ts +9 -2
- package/dist/src/commands.js +69 -64
- package/dist/src/completion.js +13 -7
- package/dist/src/config.d.ts +14 -3
- package/dist/src/config.js +57 -17
- package/dist/src/context-budget.d.ts +11 -2
- package/dist/src/context-budget.js +38 -4
- package/dist/src/context-compaction.d.ts +10 -8
- package/dist/src/context-compaction.js +23 -24
- package/dist/src/deadline.js +1 -1
- package/dist/src/decision/DecisionEngine.d.ts +2 -0
- package/dist/src/decision/DecisionManager.d.ts +16 -0
- package/dist/src/decision/DecisionManager.js +75 -2
- package/dist/src/decision/applyTaskKind.d.ts +8 -0
- package/dist/src/decision/applyTaskKind.js +53 -0
- package/dist/src/decision/applyToolMenu.js +6 -2
- package/dist/src/decision/hostedPolicy.js +6 -3
- package/dist/src/decision/optimizationPolicy.d.ts +10 -0
- package/dist/src/decision/optimizationPolicy.js +23 -3
- package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +4 -1
- package/dist/src/decision/providers/AndorraDecisionProvider.js +29 -7
- package/dist/src/decision/providers/index.js +1 -1
- package/dist/src/decision/taskKind.d.ts +52 -0
- package/dist/src/decision/taskKind.js +76 -0
- package/dist/src/decision/toolFamilies.js +1 -1
- package/dist/src/decision/types.d.ts +3 -1
- package/dist/src/default-graph.js +1 -1
- package/dist/src/efficiency.d.ts +80 -1
- package/dist/src/efficiency.js +119 -4
- package/dist/src/effort-routing.d.ts +27 -0
- package/dist/src/effort-routing.js +34 -0
- package/dist/src/evidence.d.ts +110 -0
- package/dist/src/evidence.js +195 -0
- package/dist/src/extensions.d.ts +2 -0
- package/dist/src/extensions.js +30 -20
- package/dist/src/github-app/agent-writes.d.ts +1 -1
- package/dist/src/github-app/agent-writes.js +1 -1
- package/dist/src/github-app/client.d.ts +19 -0
- package/dist/src/github-app/client.js +21 -1
- package/dist/src/github-app/event-source.d.ts +0 -5
- package/dist/src/github-app/event-source.js +1 -31
- package/dist/src/github-app/metrics.d.ts +2 -5
- package/dist/src/github-app/metrics.js +2 -14
- package/dist/src/github-app/review-loop.d.ts +5 -5
- package/dist/src/github-app/review-loop.js +1 -1
- package/dist/src/github-app/review-node.d.ts +2 -2
- package/dist/src/github-app/triggers.d.ts +3 -3
- package/dist/src/github-names.d.ts +7 -0
- package/dist/src/github-names.js +7 -0
- package/dist/src/glob-search.d.ts +1 -0
- package/dist/src/glob-search.js +3 -0
- package/dist/src/google-provider.d.ts +5 -28
- package/dist/src/google-provider.js +6 -141
- package/dist/src/graph-editor-session.d.ts +1 -0
- package/dist/src/graph-editor-session.js +2 -0
- package/dist/src/graph-health.js +3 -1
- package/dist/src/graph-preview.d.ts +2 -0
- package/dist/src/graph-preview.js +1 -0
- package/dist/src/graph-runner.js +20 -14
- package/dist/src/graph-selection.d.ts +3 -1
- package/dist/src/graph-selection.js +2 -2
- package/dist/src/graph-server.d.ts +8 -1
- package/dist/src/graph-server.js +49 -12
- package/dist/src/graph-sync.d.ts +2 -1
- package/dist/src/graph-sync.js +13 -0
- package/dist/src/graph-ui/app.js +49 -8
- package/dist/src/graph-ui/index.html +1 -1
- package/dist/src/graphs.d.ts +23 -1
- package/dist/src/graphs.js +58 -7
- package/dist/src/grok-provider.js +17 -14
- package/dist/src/hardened-runtime.js +39 -25
- package/dist/src/jev-savings.d.ts +4 -0
- package/dist/src/jev-savings.js +13 -0
- package/dist/src/legal/client.d.ts +25 -0
- package/dist/src/legal/client.js +47 -0
- package/dist/src/legal/command.d.ts +13 -0
- package/dist/src/legal/command.js +98 -0
- package/dist/src/legal/documents.d.ts +2 -0
- package/dist/src/legal/documents.js +14 -0
- package/dist/src/legal/gate.d.ts +13 -0
- package/dist/src/legal/gate.js +96 -0
- package/dist/src/legal/manifest.d.ts +21 -0
- package/dist/src/legal/manifest.js +23 -0
- package/dist/src/legal/receipt.d.ts +13 -0
- package/dist/src/legal/receipt.js +137 -0
- package/dist/src/legal/release.d.ts +27 -0
- package/dist/src/legal/release.js +28 -0
- package/dist/src/managed-sign-in.d.ts +0 -1
- package/dist/src/managed-sign-in.js +0 -13
- package/dist/src/membership.d.ts +27 -1
- package/dist/src/membership.js +139 -7
- package/dist/src/model-health-cache.js +1 -1
- package/dist/src/model-metadata.js +3 -7
- package/dist/src/model-override.d.ts +2 -1
- package/dist/src/model-override.js +9 -0
- package/dist/src/model-pool.d.ts +99 -0
- package/dist/src/model-pool.js +136 -0
- package/dist/src/model-relay/local.js +5 -0
- package/dist/src/model-relay/remote.d.ts +2 -0
- package/dist/src/model-relay/remote.js +4 -0
- package/dist/src/model-tiers.d.ts +16 -1
- package/dist/src/model-tiers.js +31 -7
- package/dist/src/opencode-cli-provider.js +59 -56
- package/dist/src/opencode-provider.js +16 -13
- package/dist/src/permissions.d.ts +5 -0
- package/dist/src/permissions.js +7 -0
- package/dist/src/plan-pass.js +2 -1
- package/dist/src/pool-scores.d.ts +45 -0
- package/dist/src/pool-scores.js +40 -0
- package/dist/src/provider-connection.js +3 -17
- package/dist/src/provider-engine.d.ts +13 -1
- package/dist/src/provider-engine.js +116 -12
- package/dist/src/provider-request-error.d.ts +8 -0
- package/dist/src/provider-request-error.js +12 -0
- package/dist/src/provider-settings.d.ts +1 -1
- package/dist/src/provider-settings.js +36 -18
- package/dist/src/provider-turn-deadline.d.ts +39 -0
- package/dist/src/provider-turn-deadline.js +139 -0
- package/dist/src/providers.d.ts +8 -9
- package/dist/src/providers.js +211 -150
- package/dist/src/pull-request-merge.d.ts +1 -8
- package/dist/src/pull-request-merge.js +0 -4
- package/dist/src/pull-requests.d.ts +83 -57
- package/dist/src/pull-requests.js +266 -225
- package/dist/src/qa/runtime/ProcessManager.d.ts +5 -1
- package/dist/src/qa/runtime/ProcessManager.js +9 -3
- package/dist/src/react-runtime.js +245 -71
- package/dist/src/reasoning-probe-cloud.d.ts +10 -0
- package/dist/src/reasoning-probe-cloud.js +209 -0
- package/dist/src/remote/engine-pool.d.ts +3 -0
- package/dist/src/remote/engine-pool.js +88 -21
- package/dist/src/remote/recovery.d.ts +6 -0
- package/dist/src/remote/recovery.js +37 -0
- package/dist/src/run-records.d.ts +13 -3
- package/dist/src/run-records.js +59 -34
- package/dist/src/runtime.d.ts +47 -2
- package/dist/src/runtime.js +33 -7
- package/dist/src/session-summary.d.ts +8 -0
- package/dist/src/session-summary.js +34 -0
- package/dist/src/sessions.d.ts +32 -0
- package/dist/src/sessions.js +65 -3
- package/dist/src/shell.js +6 -0
- package/dist/src/side-panel.js +36 -2
- package/dist/src/sign-in-detection.d.ts +1 -1
- package/dist/src/sign-in-detection.js +4 -10
- package/dist/src/sign-in-offer.js +1 -1
- package/dist/src/skill-commands.js +1 -1
- package/dist/src/skills/bundled/bug-report/SKILL.md +51 -7
- package/dist/src/skills/bundled/graph-manager/SKILL.md +2 -2
- package/dist/src/skills/bundled/graph-manager/patterns.md +13 -19
- package/dist/src/skills/bundled/provenance.json +3 -3
- package/dist/src/subagent-run.js +50 -50
- package/dist/src/subscription-usage.d.ts +50 -0
- package/dist/src/subscription-usage.js +92 -0
- package/dist/src/task-checkout.d.ts +157 -0
- package/dist/src/task-checkout.js +628 -0
- package/dist/src/telemetry/access.d.ts +18 -0
- package/dist/src/telemetry/access.js +43 -0
- package/dist/src/telemetry/aggregate.d.ts +18 -2
- package/dist/src/telemetry/aggregate.js +22 -9
- package/dist/src/telemetry/capture-core.d.ts +33 -14
- package/dist/src/telemetry/capture-core.js +124 -25
- package/dist/src/telemetry/capture.d.ts +3 -2
- package/dist/src/telemetry/capture.js +21 -1
- package/dist/src/telemetry/decision-capture.js +4 -0
- package/dist/src/telemetry/emitter.d.ts +6 -7
- package/dist/src/telemetry/emitter.js +124 -29
- package/dist/src/telemetry/gate.d.ts +41 -2
- package/dist/src/telemetry/gate.js +89 -4
- package/dist/src/telemetry/home.d.ts +1 -0
- package/dist/src/telemetry/home.js +20 -0
- package/dist/src/telemetry/identity.d.ts +6 -3
- package/dist/src/telemetry/identity.js +19 -6
- package/dist/src/telemetry/lifecycle.d.ts +8 -0
- package/dist/src/telemetry/lifecycle.js +76 -0
- package/dist/src/telemetry/outbox.d.ts +13 -8
- package/dist/src/telemetry/outbox.js +68 -12
- package/dist/src/telemetry/permission-command.d.ts +38 -0
- package/dist/src/telemetry/permission-command.js +208 -0
- package/dist/src/telemetry/permission.d.ts +168 -0
- package/dist/src/telemetry/permission.js +662 -0
- package/dist/src/telemetry/record-installation.d.ts +1 -0
- package/dist/src/telemetry/record-installation.js +9 -0
- package/dist/src/telemetry/region-data.d.ts +12 -0
- package/dist/src/telemetry/region-data.js +1314 -0
- package/dist/src/telemetry/region.d.ts +34 -0
- package/dist/src/telemetry/region.js +87 -0
- package/dist/src/telemetry/run-privacy.d.ts +11 -0
- package/dist/src/telemetry/run-privacy.js +165 -0
- package/dist/src/telemetry/schema.d.ts +27 -6
- package/dist/src/telemetry/schema.js +109 -14
- package/dist/src/telemetry/state.d.ts +11 -7
- package/dist/src/telemetry/state.js +39 -6
- package/dist/src/telemetry/surface.d.ts +20 -3
- package/dist/src/telemetry/surface.js +71 -15
- package/dist/src/telemetry/uploader.d.ts +6 -11
- package/dist/src/telemetry/uploader.js +72 -46
- package/dist/src/telemetry/uploads.d.ts +5 -1
- package/dist/src/telemetry/uploads.js +25 -6
- package/dist/src/telemetry/version.d.ts +5 -0
- package/dist/src/telemetry/version.js +34 -0
- package/dist/src/telemetry/workspace.d.ts +4 -1
- package/dist/src/telemetry/workspace.js +18 -3
- package/dist/src/terminal-ui.d.ts +3 -0
- package/dist/src/terminal-ui.js +48 -6
- package/dist/src/test-edit-guard.d.ts +30 -0
- package/dist/src/test-edit-guard.js +167 -2
- package/dist/src/thinking-level-detect.d.ts +13 -0
- package/dist/src/thinking-level-detect.js +52 -0
- package/dist/src/thinking-levels.d.ts +30 -0
- package/dist/src/thinking-levels.js +131 -0
- package/dist/src/timers.d.ts +3 -0
- package/dist/src/todos.d.ts +2 -1
- package/dist/src/todos.js +24 -4
- package/dist/src/tool-argument-coercion.d.ts +7 -0
- package/dist/src/tool-argument-coercion.js +49 -0
- package/dist/src/tool-catalog.d.ts +2 -2
- package/dist/src/tool-catalog.js +1 -1
- package/dist/src/tools.js +67 -22
- package/dist/src/transcript.js +3 -2
- package/dist/src/types.d.ts +48 -1
- package/dist/src/update.js +4 -0
- package/dist/src/usage-analytics.d.ts +7 -0
- package/dist/src/usage-analytics.js +85 -13
- package/dist/telemetry-consent-v1 +1 -0
- package/package.json +97 -96
|
@@ -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,9 +1,9 @@
|
|
|
1
|
-
import type
|
|
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;
|
|
7
7
|
constructor(code: HostOperationErrorCode, message: string);
|
|
8
8
|
}
|
|
9
|
-
export declare function hostOperation(directory: string, op: HostOperationName, params: Record<string, unknown>, host: Host): Promise<unknown>;
|
|
9
|
+
export declare function hostOperation(directory: string, op: HostOperationName, params: Record<string, unknown>, host: Host, cloudUpdates?: boolean): Promise<unknown>;
|
|
@@ -4,6 +4,8 @@ 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 { CLOUD_BRIDGE_AUTO_UPDATE } from './protocol.js';
|
|
8
|
+
import { cloneDependenciesFromEnvironment, cloneRepository } from './github.js';
|
|
7
9
|
import { bridgeCommand } from './wording.js';
|
|
8
10
|
export const BROWSE_ENTRY_CAP = 1000;
|
|
9
11
|
const SKIP_NAMES = new Set(['.git', 'node_modules', '.andorracode']);
|
|
@@ -46,13 +48,14 @@ async function sharedDirectory(directory, path, missing) {
|
|
|
46
48
|
throw new HostOperationError('forbidden', outsideFolders());
|
|
47
49
|
return found.path;
|
|
48
50
|
}
|
|
49
|
-
export async function hostOperation(directory, op, params, host) {
|
|
51
|
+
export async function hostOperation(directory, op, params, host, cloudUpdates = false) {
|
|
50
52
|
switch (op) {
|
|
51
53
|
case 'whoami': {
|
|
52
54
|
const { APP_SERVER_CAPABILITIES } = await import('../app-server/protocol.js');
|
|
53
55
|
return {
|
|
54
56
|
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
|
|
57
|
+
capabilities: [...new Set([...APP_SERVER_CAPABILITIES, 'remote.engine.relay', RELAY_CAPABILITY_REQUIREMENT, 'remote.github.clone',
|
|
58
|
+
...(cloudUpdates ? [CLOUD_BRIDGE_AUTO_UPDATE] : [])])],
|
|
56
59
|
};
|
|
57
60
|
}
|
|
58
61
|
case 'projects': {
|
|
@@ -123,6 +126,15 @@ export async function hostOperation(directory, op, params, host) {
|
|
|
123
126
|
const recorded = (await loadConfig(directory)).projects?.find(project => project.path === actual);
|
|
124
127
|
return { rootId: projectRootId(actual), name: recorded?.name?.trim() || basename(actual) || actual };
|
|
125
128
|
}
|
|
129
|
+
case 'owner.github.clone': {
|
|
130
|
+
// Answers at once and is asked again while the clone runs: a host operation may not outlast its deadline.
|
|
131
|
+
try {
|
|
132
|
+
return await cloneRepository(await cloneDependenciesFromEnvironment(directory), params);
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
throw new HostOperationError('invalid-params', error instanceof Error ? error.message : String(error));
|
|
136
|
+
}
|
|
137
|
+
}
|
|
126
138
|
default:
|
|
127
139
|
throw new HostOperationError('invalid-params', 'Unknown host operation');
|
|
128
140
|
}
|
|
@@ -33,6 +33,8 @@ export interface BridgeHostOptions {
|
|
|
33
33
|
heartbeat?: (activity: BridgeActivity) => Promise<void>;
|
|
34
34
|
/** The launcher's engine store: present only when the bridge launcher started this host. */
|
|
35
35
|
engines?: EngineStore;
|
|
36
|
+
/** Managed Cloud hosts follow the published release before accepting new work. */
|
|
37
|
+
cloudUpdates?: boolean;
|
|
36
38
|
/** Whether the launcher that started this host is still running; the host stops once it is not. */
|
|
37
39
|
launcherAlive?: () => boolean;
|
|
38
40
|
launcherCheckMs?: number;
|
package/dist/src/bridge/host.js
CHANGED
|
@@ -3,7 +3,8 @@ import { RemoteEngineRelay } from '../remote/engine-pool.js';
|
|
|
3
3
|
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
|
-
import { compareVersions } from './engines.js';
|
|
6
|
+
import { compareVersions, validVersion } 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,9 @@ 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
|
|
26
|
+
const CLOUD_RELEASE_CHECK_MS = 60_000;
|
|
27
|
+
const CLOUD_RELEASE_RETRY_MS = 15_000;
|
|
28
|
+
const HOST_OPERATIONS = new Set(['whoami', 'projects', 'roots', 'browse', 'owner.roots', 'owner.browse', 'owner.projects.add', 'owner.github.clone']);
|
|
26
29
|
export const hostDependencies = {
|
|
27
30
|
createRelay: (directory, engines) => new RemoteEngineRelay(directory, {}, engines ? { engines } : {}),
|
|
28
31
|
};
|
|
@@ -153,6 +156,9 @@ export async function runBridgeHost(hostOptions) {
|
|
|
153
156
|
// Only the highest MAX_NEWER_VERSIONS are kept, so a desktop naming made-up versions cannot grow the set.
|
|
154
157
|
const newer = new Set();
|
|
155
158
|
const now = options.now ?? Date.now;
|
|
159
|
+
let releaseVersion;
|
|
160
|
+
let releaseCheck;
|
|
161
|
+
let releaseCheckAfter = 0;
|
|
156
162
|
// A host started for a restart it asked for, but running another version (the launcher could not start that one),
|
|
157
163
|
// does not ask for the same version again at once: the launcher would fall back again and again.
|
|
158
164
|
let held;
|
|
@@ -165,6 +171,8 @@ export async function runBridgeHost(hostOptions) {
|
|
|
165
171
|
let restarting = false;
|
|
166
172
|
// Requests and host operations not yet answered: a restart would cut a compaction or a save short, or tear a config write.
|
|
167
173
|
let answering = 0;
|
|
174
|
+
// A clone goes on after its request was answered `cloning`, so it is counted on its own: a restart would cut it off.
|
|
175
|
+
const busyHere = () => answering > 0 || clonesRunning() > 0;
|
|
168
176
|
// Asking the engines what they hold can outlast the interval between checks.
|
|
169
177
|
let checking = false;
|
|
170
178
|
const restartIfIdle = async () => {
|
|
@@ -180,14 +188,16 @@ export async function runBridgeHost(hostOptions) {
|
|
|
180
188
|
};
|
|
181
189
|
const checkRestart = async () => {
|
|
182
190
|
const engines = options.engines;
|
|
183
|
-
|
|
191
|
+
const candidates = options.cloudUpdates ? (releaseVersion ? [releaseVersion] : []) : newer;
|
|
192
|
+
if (!engines || restarting || signal.aborted)
|
|
184
193
|
return;
|
|
185
|
-
if (
|
|
194
|
+
if (busyHere() || relay.runningTasks() > 0 || engines.installing() > 0)
|
|
186
195
|
return;
|
|
187
196
|
const installed = [];
|
|
188
|
-
for (const version of
|
|
189
|
-
if (await engines.installed(version))
|
|
197
|
+
for (const version of candidates) {
|
|
198
|
+
if (compareVersions(version, options.version) > 0 && await engines.installed(version))
|
|
190
199
|
installed.push(version);
|
|
200
|
+
}
|
|
191
201
|
if (installed.length === 0)
|
|
192
202
|
return;
|
|
193
203
|
const next = installed.sort(compareVersions).at(-1);
|
|
@@ -196,7 +206,7 @@ export async function runBridgeHost(hostOptions) {
|
|
|
196
206
|
// 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
207
|
if (await relay.holdsWork())
|
|
198
208
|
return;
|
|
199
|
-
if (restarting || signal.aborted ||
|
|
209
|
+
if (restarting || signal.aborted || busyHere() || relay.runningTasks() > 0)
|
|
200
210
|
return;
|
|
201
211
|
// From here on task starts are refused, so none can begin while the restart is written.
|
|
202
212
|
restarting = true;
|
|
@@ -205,10 +215,12 @@ export async function runBridgeHost(hostOptions) {
|
|
|
205
215
|
}
|
|
206
216
|
catch (error) {
|
|
207
217
|
restarting = false;
|
|
218
|
+
if (options.cloudUpdates)
|
|
219
|
+
held = { version: next, until: now() + HOST_REQUEST_HOLD_MS };
|
|
208
220
|
log(`Could not hand this bridge over to Andorra Code ${next}: ${error instanceof Error ? error.message : String(error)}`);
|
|
209
221
|
return;
|
|
210
222
|
}
|
|
211
|
-
if (
|
|
223
|
+
if (busyHere() || relay.runningTasks() > 0 || await relay.holdsWork()) {
|
|
212
224
|
await engines.withdrawHostVersion().catch(error => log(`Could not withdraw the restart: ${error instanceof Error ? error.message : String(error)}`));
|
|
213
225
|
restarting = false;
|
|
214
226
|
return;
|
|
@@ -217,7 +229,7 @@ export async function runBridgeHost(hostOptions) {
|
|
|
217
229
|
stopped.abort();
|
|
218
230
|
};
|
|
219
231
|
const noteVersion = (version) => {
|
|
220
|
-
if (!options.engines || compareVersions(version, options.version) <= 0 || !ENGINE_VERSION.test(options.version))
|
|
232
|
+
if (options.cloudUpdates || !options.engines || compareVersions(version, options.version) <= 0 || !ENGINE_VERSION.test(options.version))
|
|
221
233
|
return;
|
|
222
234
|
newer.add(version);
|
|
223
235
|
if (newer.size > MAX_NEWER_VERSIONS)
|
|
@@ -239,7 +251,46 @@ export async function runBridgeHost(hostOptions) {
|
|
|
239
251
|
answering -= 1;
|
|
240
252
|
}
|
|
241
253
|
};
|
|
242
|
-
const
|
|
254
|
+
const updatingBeforeTask = async () => {
|
|
255
|
+
const engines = options.engines;
|
|
256
|
+
if (restarting || !options.cloudUpdates || !engines)
|
|
257
|
+
return restarting;
|
|
258
|
+
if (now() >= releaseCheckAfter) {
|
|
259
|
+
releaseCheck ??= (async () => {
|
|
260
|
+
let version;
|
|
261
|
+
try {
|
|
262
|
+
version = await engines.latestRelease();
|
|
263
|
+
}
|
|
264
|
+
catch { /* Keep serving the current release. */ }
|
|
265
|
+
releaseVersion = validVersion(version) ? version : undefined;
|
|
266
|
+
releaseCheckAfter = now() + (releaseVersion ? CLOUD_RELEASE_CHECK_MS : CLOUD_RELEASE_RETRY_MS);
|
|
267
|
+
if (!releaseVersion && !signal.aborted)
|
|
268
|
+
log('Could not check for a Cloud bridge update. Continuing with the current version.');
|
|
269
|
+
})().finally(() => { releaseCheck = undefined; });
|
|
270
|
+
await releaseCheck;
|
|
271
|
+
}
|
|
272
|
+
if (signal.aborted || restarting)
|
|
273
|
+
return true;
|
|
274
|
+
const target = releaseVersion;
|
|
275
|
+
if (!target || !validVersion(options.version) || compareVersions(target, options.version) <= 0)
|
|
276
|
+
return false;
|
|
277
|
+
if (held?.version === target && now() < held.until)
|
|
278
|
+
return false;
|
|
279
|
+
try {
|
|
280
|
+
const stage = await engines.prepare(target);
|
|
281
|
+
if (stage === 'failed' || (stage === 'none' && !await engines.installed(target)))
|
|
282
|
+
return restarting;
|
|
283
|
+
// A terminal, clone, or running task may keep the host on its current release for a while.
|
|
284
|
+
if (relay.runningTasks() > 0 || clonesRunning() > 0 || await relay.holdsWork())
|
|
285
|
+
return restarting;
|
|
286
|
+
return true;
|
|
287
|
+
}
|
|
288
|
+
catch (error) {
|
|
289
|
+
log(`Could not prepare Cloud bridge update ${target}: ${error instanceof Error ? error.message : String(error)}`);
|
|
290
|
+
return restarting;
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
const watch = { noteVersion, settled: () => { void restartIfIdle(); }, updatingBeforeTask, answer };
|
|
243
294
|
try {
|
|
244
295
|
while (!signal.aborted) {
|
|
245
296
|
let credential;
|
|
@@ -471,12 +522,15 @@ function runSession(options, relay, host, credential, connections, onToken, vers
|
|
|
471
522
|
answerWith(viewer, id, { error: { code: 'invalid-params', message: 'A request body is required.' } });
|
|
472
523
|
return;
|
|
473
524
|
}
|
|
474
|
-
if (versions.restarting() && TASK_START_METHODS.has(frame.body.method)) {
|
|
475
|
-
answerWith(viewer, id, { error: { code: 'busy', message: RESTARTING_MESSAGE } });
|
|
476
|
-
return;
|
|
477
|
-
}
|
|
478
525
|
const body = frame.body;
|
|
479
|
-
await versions.answer(async () => {
|
|
526
|
+
await versions.answer(async () => {
|
|
527
|
+
if (TASK_START_METHODS.has(body.method) && await versions.updatingBeforeTask()) {
|
|
528
|
+
answerWith(viewer, id, { error: { code: 'busy', message: RESTARTING_MESSAGE } });
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
if (!finished && !signal.aborted)
|
|
532
|
+
answerWith(viewer, id, await relay.request(viewer, body));
|
|
533
|
+
});
|
|
480
534
|
versions.settled();
|
|
481
535
|
return;
|
|
482
536
|
}
|
|
@@ -491,7 +545,7 @@ function runSession(options, relay, host, credential, connections, onToken, vers
|
|
|
491
545
|
const params = isRecord(frame.params) ? frame.params : {};
|
|
492
546
|
await versions.answer(async () => {
|
|
493
547
|
try {
|
|
494
|
-
answerWith(viewer, id, { result: await hostOperation(options.directory, op, params, host) });
|
|
548
|
+
answerWith(viewer, id, { result: await hostOperation(options.directory, op, params, host, options.cloudUpdates === true && options.engines !== undefined) });
|
|
495
549
|
}
|
|
496
550
|
catch (error) {
|
|
497
551
|
const code = error instanceof HostOperationError ? error.code : 'remote';
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export declare const PROTOCOL_VERSION = 1;
|
|
2
|
+
export declare const CLOUD_BRIDGE_AUTO_UPDATE = "cloud.bridgeAutoUpdate";
|
|
2
3
|
export declare const MAX_FRAME_BYTES: number;
|
|
3
4
|
/** The hello, the only frame the relay reads before `ready`, may be at most this large. */
|
|
4
5
|
export declare const PRE_HELLO_MAX_BYTES: number;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// The wire protocol between a bridge host, the relay and a desktop engine. Every frame is one JSON text
|
|
2
2
|
// message of at most MAX_FRAME_BYTES. The bridge host and the engine client keep a byte-for-byte copy of this file.
|
|
3
3
|
export const PROTOCOL_VERSION = 1;
|
|
4
|
+
export const CLOUD_BRIDGE_AUTO_UPDATE = 'cloud.bridgeAutoUpdate';
|
|
4
5
|
export const MAX_FRAME_BYTES = 16 * 1024 * 1024;
|
|
5
6
|
/** The hello, the only frame the relay reads before `ready`, may be at most this large. */
|
|
6
7
|
export const PRE_HELLO_MAX_BYTES = 16 * 1024;
|
|
@@ -2,6 +2,16 @@ import type { Tool, ToolImage } from './types.js';
|
|
|
2
2
|
import type { BrowserViewManager } from './browser-view.js';
|
|
3
3
|
export declare const PANEL_HOLD_LEASE_MS: number;
|
|
4
4
|
export declare const PANEL_HOLD_RENEW_MS: number;
|
|
5
|
+
export declare const PANEL_RESIZE_LIMITS: {
|
|
6
|
+
readonly width: {
|
|
7
|
+
readonly min: 320;
|
|
8
|
+
readonly max: 1600;
|
|
9
|
+
};
|
|
10
|
+
readonly height: {
|
|
11
|
+
readonly min: 240;
|
|
12
|
+
readonly max: 1200;
|
|
13
|
+
};
|
|
14
|
+
};
|
|
5
15
|
export interface PanelArguments {
|
|
6
16
|
operation: string;
|
|
7
17
|
url?: string;
|
|
@@ -11,6 +21,8 @@ export interface PanelArguments {
|
|
|
11
21
|
key?: string;
|
|
12
22
|
button?: 'left' | 'right' | 'middle';
|
|
13
23
|
deltaY?: number;
|
|
24
|
+
width?: number;
|
|
25
|
+
height?: number;
|
|
14
26
|
}
|
|
15
27
|
export declare function validatePanelArguments(args: Record<string, unknown>): PanelArguments;
|
|
16
28
|
/**
|