@mastra/factory 0.0.0-fix-thread-subscription-multi-instance-redis-streams-20260730204150
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/CHANGELOG.md +695 -0
- package/LICENSE.md +30 -0
- package/README.md +27 -0
- package/dist/auth.d.ts +181 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +505 -0
- package/dist/auth.js.map +1 -0
- package/dist/capabilities/connection.d.ts +9 -0
- package/dist/capabilities/connection.d.ts.map +1 -0
- package/dist/capabilities/connection.js +1 -0
- package/dist/capabilities/intake.d.ts +140 -0
- package/dist/capabilities/intake.d.ts.map +1 -0
- package/dist/capabilities/intake.js +1 -0
- package/dist/capabilities/version-control.d.ts +245 -0
- package/dist/capabilities/version-control.d.ts.map +1 -0
- package/dist/capabilities/version-control.js +1 -0
- package/dist/factory.d.ts +156 -0
- package/dist/factory.d.ts.map +1 -0
- package/dist/factory.js +483 -0
- package/dist/factory.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/integrations/base.d.ts +210 -0
- package/dist/integrations/base.d.ts.map +1 -0
- package/dist/integrations/base.js +1 -0
- package/dist/integrations/github/config.d.ts +60 -0
- package/dist/integrations/github/config.d.ts.map +1 -0
- package/dist/integrations/github/config.js +42 -0
- package/dist/integrations/github/config.js.map +1 -0
- package/dist/integrations/github/factory-session.d.ts +12 -0
- package/dist/integrations/github/factory-session.d.ts.map +1 -0
- package/dist/integrations/github/factory-session.js +37 -0
- package/dist/integrations/github/factory-session.js.map +1 -0
- package/dist/integrations/github/integration.d.ts +191 -0
- package/dist/integrations/github/integration.d.ts.map +1 -0
- package/dist/integrations/github/integration.js +1077 -0
- package/dist/integrations/github/integration.js.map +1 -0
- package/dist/integrations/github/issue-triage.d.ts +27 -0
- package/dist/integrations/github/issue-triage.d.ts.map +1 -0
- package/dist/integrations/github/issue-triage.js +82 -0
- package/dist/integrations/github/issue-triage.js.map +1 -0
- package/dist/integrations/github/pat.d.ts +38 -0
- package/dist/integrations/github/pat.d.ts.map +1 -0
- package/dist/integrations/github/pat.js +59 -0
- package/dist/integrations/github/pat.js.map +1 -0
- package/dist/integrations/github/provenance.d.ts +27 -0
- package/dist/integrations/github/provenance.d.ts.map +1 -0
- package/dist/integrations/github/provenance.js +75 -0
- package/dist/integrations/github/provenance.js.map +1 -0
- package/dist/integrations/github/routes.d.ts +69 -0
- package/dist/integrations/github/routes.d.ts.map +1 -0
- package/dist/integrations/github/routes.js +1324 -0
- package/dist/integrations/github/routes.js.map +1 -0
- package/dist/integrations/github/rules.d.ts +78 -0
- package/dist/integrations/github/rules.d.ts.map +1 -0
- package/dist/integrations/github/rules.js +362 -0
- package/dist/integrations/github/rules.js.map +1 -0
- package/dist/integrations/github/sandbox-release.d.ts +38 -0
- package/dist/integrations/github/sandbox-release.d.ts.map +1 -0
- package/dist/integrations/github/sandbox-release.js +74 -0
- package/dist/integrations/github/sandbox-release.js.map +1 -0
- package/dist/integrations/github/sandbox.d.ts +281 -0
- package/dist/integrations/github/sandbox.d.ts.map +1 -0
- package/dist/integrations/github/sandbox.js +547 -0
- package/dist/integrations/github/sandbox.js.map +1 -0
- package/dist/integrations/github/session-subscriptions.d.ts +26 -0
- package/dist/integrations/github/session-subscriptions.d.ts.map +1 -0
- package/dist/integrations/github/session-subscriptions.js +192 -0
- package/dist/integrations/github/session-subscriptions.js.map +1 -0
- package/dist/integrations/github/subscriptions.d.ts +54 -0
- package/dist/integrations/github/subscriptions.d.ts.map +1 -0
- package/dist/integrations/github/subscriptions.js +62 -0
- package/dist/integrations/github/subscriptions.js.map +1 -0
- package/dist/integrations/github/token-refresh.d.ts +12 -0
- package/dist/integrations/github/token-refresh.d.ts.map +1 -0
- package/dist/integrations/github/token-refresh.js +24 -0
- package/dist/integrations/github/token-refresh.js.map +1 -0
- package/dist/integrations/github/webhook.d.ts +87 -0
- package/dist/integrations/github/webhook.d.ts.map +1 -0
- package/dist/integrations/github/webhook.js +397 -0
- package/dist/integrations/github/webhook.js.map +1 -0
- package/dist/integrations/linear/agent-tools.d.ts +34 -0
- package/dist/integrations/linear/agent-tools.d.ts.map +1 -0
- package/dist/integrations/linear/agent-tools.js +85 -0
- package/dist/integrations/linear/agent-tools.js.map +1 -0
- package/dist/integrations/linear/integration.d.ts +233 -0
- package/dist/integrations/linear/integration.d.ts.map +1 -0
- package/dist/integrations/linear/integration.js +672 -0
- package/dist/integrations/linear/integration.js.map +1 -0
- package/dist/integrations/linear/routes.d.ts +61 -0
- package/dist/integrations/linear/routes.d.ts.map +1 -0
- package/dist/integrations/linear/routes.js +239 -0
- package/dist/integrations/linear/routes.js.map +1 -0
- package/dist/integrations/linear/rules.d.ts +42 -0
- package/dist/integrations/linear/rules.d.ts.map +1 -0
- package/dist/integrations/linear/rules.js +133 -0
- package/dist/integrations/linear/rules.js.map +1 -0
- package/dist/integrations/linear/storage.d.ts +65 -0
- package/dist/integrations/linear/storage.d.ts.map +1 -0
- package/dist/integrations/linear/storage.js +1 -0
- package/dist/integrations/platform/api-client.d.ts +26 -0
- package/dist/integrations/platform/api-client.d.ts.map +1 -0
- package/dist/integrations/platform/api-client.js +156 -0
- package/dist/integrations/platform/api-client.js.map +1 -0
- package/dist/integrations/platform/github/event-worker.d.ts +49 -0
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -0
- package/dist/integrations/platform/github/event-worker.js +348 -0
- package/dist/integrations/platform/github/event-worker.js.map +1 -0
- package/dist/integrations/platform/github/integration.d.ts +50 -0
- package/dist/integrations/platform/github/integration.d.ts.map +1 -0
- package/dist/integrations/platform/github/integration.js +961 -0
- package/dist/integrations/platform/github/integration.js.map +1 -0
- package/dist/integrations/platform/linear/integration.d.ts +46 -0
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -0
- package/dist/integrations/platform/linear/integration.js +483 -0
- package/dist/integrations/platform/linear/integration.js.map +1 -0
- package/dist/integrations/workos/integration.d.ts +39 -0
- package/dist/integrations/workos/integration.d.ts.map +1 -0
- package/dist/integrations/workos/integration.js +91 -0
- package/dist/integrations/workos/integration.js.map +1 -0
- package/dist/routes/config.d.ts +235 -0
- package/dist/routes/config.d.ts.map +1 -0
- package/dist/routes/config.js +972 -0
- package/dist/routes/config.js.map +1 -0
- package/dist/routes/custom-provider-source.d.ts +52 -0
- package/dist/routes/custom-provider-source.d.ts.map +1 -0
- package/dist/routes/custom-provider-source.js +124 -0
- package/dist/routes/custom-provider-source.js.map +1 -0
- package/dist/routes/fs.d.ts +151 -0
- package/dist/routes/fs.d.ts.map +1 -0
- package/dist/routes/fs.js +708 -0
- package/dist/routes/fs.js.map +1 -0
- package/dist/routes/intake.d.ts +23 -0
- package/dist/routes/intake.d.ts.map +1 -0
- package/dist/routes/intake.js +179 -0
- package/dist/routes/intake.js.map +1 -0
- package/dist/routes/oauth.d.ts +43 -0
- package/dist/routes/oauth.d.ts.map +1 -0
- package/dist/routes/oauth.js +463 -0
- package/dist/routes/oauth.js.map +1 -0
- package/dist/routes/projects.d.ts +19 -0
- package/dist/routes/projects.d.ts.map +1 -0
- package/dist/routes/projects.js +461 -0
- package/dist/routes/projects.js.map +1 -0
- package/dist/routes/provider-credentials.d.ts +81 -0
- package/dist/routes/provider-credentials.d.ts.map +1 -0
- package/dist/routes/provider-credentials.js +86 -0
- package/dist/routes/provider-credentials.js.map +1 -0
- package/dist/routes/route.d.ts +48 -0
- package/dist/routes/route.d.ts.map +1 -0
- package/dist/routes/route.js +15 -0
- package/dist/routes/route.js.map +1 -0
- package/dist/routes/skills.d.ts +30 -0
- package/dist/routes/skills.d.ts.map +1 -0
- package/dist/routes/skills.js +168 -0
- package/dist/routes/skills.js.map +1 -0
- package/dist/routes/surface.d.ts +91 -0
- package/dist/routes/surface.d.ts.map +1 -0
- package/dist/routes/surface.js +260 -0
- package/dist/routes/surface.js.map +1 -0
- package/dist/routes/tenant-credentials.d.ts +74 -0
- package/dist/routes/tenant-credentials.d.ts.map +1 -0
- package/dist/routes/tenant-credentials.js +156 -0
- package/dist/routes/tenant-credentials.js.map +1 -0
- package/dist/routes/work-items.d.ts +40 -0
- package/dist/routes/work-items.d.ts.map +1 -0
- package/dist/routes/work-items.js +695 -0
- package/dist/routes/work-items.js.map +1 -0
- package/dist/rules/binding-context.d.ts +5 -0
- package/dist/rules/binding-context.d.ts.map +1 -0
- package/dist/rules/binding-context.js +28 -0
- package/dist/rules/binding-context.js.map +1 -0
- package/dist/rules/defaults.d.ts +9 -0
- package/dist/rules/defaults.d.ts.map +1 -0
- package/dist/rules/defaults.js +260 -0
- package/dist/rules/defaults.js.map +1 -0
- package/dist/rules/dispatcher.d.ts +42 -0
- package/dist/rules/dispatcher.d.ts.map +1 -0
- package/dist/rules/dispatcher.js +518 -0
- package/dist/rules/dispatcher.js.map +1 -0
- package/dist/rules/index.d.ts +7 -0
- package/dist/rules/index.d.ts.map +1 -0
- package/dist/rules/index.js +5 -0
- package/dist/rules/processor.d.ts +54 -0
- package/dist/rules/processor.d.ts.map +1 -0
- package/dist/rules/processor.js +378 -0
- package/dist/rules/processor.js.map +1 -0
- package/dist/rules/resolve.d.ts +17 -0
- package/dist/rules/resolve.d.ts.map +1 -0
- package/dist/rules/resolve.js +30 -0
- package/dist/rules/resolve.js.map +1 -0
- package/dist/rules/start-coordinator.d.ts +60 -0
- package/dist/rules/start-coordinator.d.ts.map +1 -0
- package/dist/rules/start-coordinator.js +194 -0
- package/dist/rules/start-coordinator.js.map +1 -0
- package/dist/rules/tools.d.ts +10 -0
- package/dist/rules/tools.d.ts.map +1 -0
- package/dist/rules/tools.js +58 -0
- package/dist/rules/tools.js.map +1 -0
- package/dist/rules/transition-service.d.ts +49 -0
- package/dist/rules/transition-service.d.ts.map +1 -0
- package/dist/rules/transition-service.js +232 -0
- package/dist/rules/transition-service.js.map +1 -0
- package/dist/rules/types.d.ts +234 -0
- package/dist/rules/types.d.ts.map +1 -0
- package/dist/rules/types.js +38 -0
- package/dist/rules/types.js.map +1 -0
- package/dist/rules/validation.d.ts +11 -0
- package/dist/rules/validation.d.ts.map +1 -0
- package/dist/rules/validation.js +308 -0
- package/dist/rules/validation.js.map +1 -0
- package/dist/sandbox/fleet.d.ts +222 -0
- package/dist/sandbox/fleet.d.ts.map +1 -0
- package/dist/sandbox/fleet.js +322 -0
- package/dist/sandbox/fleet.js.map +1 -0
- package/dist/sandbox/reattach.d.ts +3 -0
- package/dist/sandbox/reattach.d.ts.map +1 -0
- package/dist/sandbox/reattach.js +16 -0
- package/dist/sandbox/reattach.js.map +1 -0
- package/dist/server-error.d.ts +12 -0
- package/dist/server-error.d.ts.map +1 -0
- package/dist/server-error.js +16 -0
- package/dist/server-error.js.map +1 -0
- package/dist/skills/service.d.ts +48 -0
- package/dist/skills/service.d.ts.map +1 -0
- package/dist/skills/service.js +40 -0
- package/dist/skills/service.js.map +1 -0
- package/dist/spa-static.d.ts +33 -0
- package/dist/spa-static.d.ts.map +1 -0
- package/dist/spa-static.js +104 -0
- package/dist/spa-static.js.map +1 -0
- package/dist/state-signing.d.ts +59 -0
- package/dist/state-signing.d.ts.map +1 -0
- package/dist/state-signing.js +83 -0
- package/dist/state-signing.js.map +1 -0
- package/dist/storage/domains/audit/agent-audit.d.ts +27 -0
- package/dist/storage/domains/audit/agent-audit.d.ts.map +1 -0
- package/dist/storage/domains/audit/agent-audit.js +66 -0
- package/dist/storage/domains/audit/agent-audit.js.map +1 -0
- package/dist/storage/domains/audit/base.d.ts +140 -0
- package/dist/storage/domains/audit/base.d.ts.map +1 -0
- package/dist/storage/domains/audit/base.js +184 -0
- package/dist/storage/domains/audit/base.js.map +1 -0
- package/dist/storage/domains/audit/domain.d.ts +69 -0
- package/dist/storage/domains/audit/domain.d.ts.map +1 -0
- package/dist/storage/domains/audit/domain.js +167 -0
- package/dist/storage/domains/audit/domain.js.map +1 -0
- package/dist/storage/domains/channel-identity/base.d.ts +96 -0
- package/dist/storage/domains/channel-identity/base.d.ts.map +1 -0
- package/dist/storage/domains/channel-identity/base.js +149 -0
- package/dist/storage/domains/channel-identity/base.js.map +1 -0
- package/dist/storage/domains/credentials/base.d.ts +134 -0
- package/dist/storage/domains/credentials/base.d.ts.map +1 -0
- package/dist/storage/domains/credentials/base.js +273 -0
- package/dist/storage/domains/credentials/base.js.map +1 -0
- package/dist/storage/domains/custom-providers/base.d.ts +57 -0
- package/dist/storage/domains/custom-providers/base.d.ts.map +1 -0
- package/dist/storage/domains/custom-providers/base.js +145 -0
- package/dist/storage/domains/custom-providers/base.js.map +1 -0
- package/dist/storage/domains/intake/base.d.ts +38 -0
- package/dist/storage/domains/intake/base.d.ts.map +1 -0
- package/dist/storage/domains/intake/base.js +80 -0
- package/dist/storage/domains/intake/base.js.map +1 -0
- package/dist/storage/domains/integrations/base.d.ts +126 -0
- package/dist/storage/domains/integrations/base.d.ts.map +1 -0
- package/dist/storage/domains/integrations/base.js +317 -0
- package/dist/storage/domains/integrations/base.js.map +1 -0
- package/dist/storage/domains/memory-settings/base.d.ts +62 -0
- package/dist/storage/domains/memory-settings/base.d.ts.map +1 -0
- package/dist/storage/domains/memory-settings/base.js +126 -0
- package/dist/storage/domains/memory-settings/base.js.map +1 -0
- package/dist/storage/domains/model-packs/base.d.ts +49 -0
- package/dist/storage/domains/model-packs/base.d.ts.map +1 -0
- package/dist/storage/domains/model-packs/base.js +96 -0
- package/dist/storage/domains/model-packs/base.js.map +1 -0
- package/dist/storage/domains/projects/base.d.ts +58 -0
- package/dist/storage/domains/projects/base.d.ts.map +1 -0
- package/dist/storage/domains/projects/base.js +111 -0
- package/dist/storage/domains/projects/base.js.map +1 -0
- package/dist/storage/domains/queue-health/base.d.ts +52 -0
- package/dist/storage/domains/queue-health/base.d.ts.map +1 -0
- package/dist/storage/domains/queue-health/base.js +122 -0
- package/dist/storage/domains/queue-health/base.js.map +1 -0
- package/dist/storage/domains/source-control/base.d.ts +358 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -0
- package/dist/storage/domains/source-control/base.js +908 -0
- package/dist/storage/domains/source-control/base.js.map +1 -0
- package/dist/storage/domains/source-control/inmemory.d.ts +175 -0
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -0
- package/dist/storage/domains/source-control/inmemory.js +377 -0
- package/dist/storage/domains/source-control/inmemory.js.map +1 -0
- package/dist/storage/domains/work-items/base.d.ts +412 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -0
- package/dist/storage/domains/work-items/base.js +1309 -0
- package/dist/storage/domains/work-items/base.js.map +1 -0
- package/dist/storage/domains/work-items/metrics.d.ts +101 -0
- package/dist/storage/domains/work-items/metrics.d.ts.map +1 -0
- package/dist/storage/domains/work-items/metrics.js +221 -0
- package/dist/storage/domains/work-items/metrics.js.map +1 -0
- package/dist/timing.d.ts +15 -0
- package/dist/timing.d.ts.map +1 -0
- package/dist/timing.js +34 -0
- package/dist/timing.js.map +1 -0
- package/dist/workspace.d.ts +24 -0
- package/dist/workspace.d.ts.map +1 -0
- package/dist/workspace.js +286 -0
- package/dist/workspace.js.map +1 -0
- package/factory-skills/configure-factory-rules/SKILL.md +67 -0
- package/factory-skills/factory-plan/SKILL.md +61 -0
- package/factory-skills/factory-review/SKILL.md +155 -0
- package/factory-skills/factory-triage/SKILL.md +77 -0
- package/package.json +81 -0
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
import { reportProgress } from "../../sandbox/fleet.js";
|
|
2
|
+
import { createHash } from "crypto";
|
|
3
|
+
//#region src/integrations/github/sandbox.ts
|
|
4
|
+
/**
|
|
5
|
+
* Repo materialization for GitHub-backed repositories.
|
|
6
|
+
*
|
|
7
|
+
* A GitHub repo is never cloned onto the server host. Instead each project gets
|
|
8
|
+
* its own isolated sandbox (provisioned by the fleet in `../sandbox/fleet`) and
|
|
9
|
+
* the repo is cloned *inside* that sandbox. The agent's file tools and command
|
|
10
|
+
* tools then operate entirely against the remote checkout.
|
|
11
|
+
*
|
|
12
|
+
* - `ensureProjectSandbox(row)` / `teardownProjectSandbox(row)` bind the fleet's
|
|
13
|
+
* provision/reattach/teardown lifecycle to the per-(project,user) sandbox row.
|
|
14
|
+
* - `materializeRepo(row, token)` runs `git clone` (first open) or `git pull`
|
|
15
|
+
* (re-open) inside the sandbox, using a short-lived installation token that is
|
|
16
|
+
* scrubbed from the git remote afterwards so it never persists in the VM.
|
|
17
|
+
*
|
|
18
|
+
* This module owns everything git/GitHub: clone/pull, commit/push, worktrees,
|
|
19
|
+
* and `gh pr create`. Sandbox provisioning, budgets, and workdir layout live in
|
|
20
|
+
* the fleet module.
|
|
21
|
+
*/
|
|
22
|
+
/** Adapt a per-(project,user) sandbox binding row to the fleet's persistence seam. */
|
|
23
|
+
function bindingStore(row, storage) {
|
|
24
|
+
return {
|
|
25
|
+
sandboxId: row.sandboxId,
|
|
26
|
+
setSandboxId: (id) => id === null ? storage.clearBinding({ id: row.id }) : storage.setSandboxId({
|
|
27
|
+
id: row.id,
|
|
28
|
+
sandboxId: id
|
|
29
|
+
}),
|
|
30
|
+
clear: () => storage.clearBinding({ id: row.id })
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Provision a new sandbox (persisting its provider id on first open) or
|
|
35
|
+
* reattach to the stored one. Returns a started, live sandbox.
|
|
36
|
+
*/
|
|
37
|
+
async function ensureProjectSandbox(options) {
|
|
38
|
+
const { fleet, row, storage, token, onProgress } = options;
|
|
39
|
+
return fleet.ensureSandbox(bindingStore(row, storage), { GH_TOKEN: token }, onProgress);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Tear down a user's sandbox for a project: stop the live VM (best-effort) and
|
|
43
|
+
* clear the persisted `sandboxId`/`materializedAt` on the per-(project,user)
|
|
44
|
+
* binding row so the next open re-provisions cleanly.
|
|
45
|
+
*
|
|
46
|
+
* @param row the per-(project,user) sandbox binding to tear down
|
|
47
|
+
* @param sandbox an already-reattached live sandbox to stop, when available
|
|
48
|
+
*/
|
|
49
|
+
async function teardownProjectSandbox(options) {
|
|
50
|
+
const { fleet, row, storage, sandbox } = options;
|
|
51
|
+
return fleet.teardownSandbox(bindingStore(row, storage), sandbox);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Single-quote a string for safe POSIX shell interpolation. Wraps the value in
|
|
55
|
+
* single quotes and escapes any embedded single quote using the canonical
|
|
56
|
+
* close-quote / escaped-quote / reopen-quote sequence (`'\''`). This is the
|
|
57
|
+
* standard POSIX-safe construction and prevents the quoted string from being
|
|
58
|
+
* terminated early.
|
|
59
|
+
*/
|
|
60
|
+
function shellQuote(value) {
|
|
61
|
+
return `'` + value.split(`'`).join(`'\\''`) + `'`;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Default hang guard for sandbox shell commands. Generous by design — large
|
|
65
|
+
* clones and dependency installs legitimately take minutes; the guard exists
|
|
66
|
+
* so a wedged sandbox surfaces a failure instead of hanging the request that
|
|
67
|
+
* triggered materialization forever.
|
|
68
|
+
*/
|
|
69
|
+
const DEFAULT_COMMAND_TIMEOUT_MS = 15 * 6e4;
|
|
70
|
+
/** Branch checkout only fetches one ref — a much tighter budget applies. */
|
|
71
|
+
const CHECKOUT_COMMAND_TIMEOUT_MS = 5 * 6e4;
|
|
72
|
+
/**
|
|
73
|
+
* A thrown transport-level failure that is worth retrying: remote sandbox
|
|
74
|
+
* providers (e.g. the platform workspace proxy) surface transient 5xx errors
|
|
75
|
+
* as exceptions carrying an HTTP `status` — typically while a freshly
|
|
76
|
+
* provisioned VM is still coming up. Command failures are NOT exceptions
|
|
77
|
+
* (they resolve with a non-zero exit code), so retrying here never re-runs a
|
|
78
|
+
* command that the sandbox already executed and rejected.
|
|
79
|
+
*/
|
|
80
|
+
function isTransientTransportError(error) {
|
|
81
|
+
const status = error?.status;
|
|
82
|
+
return typeof status === "number" && status >= 500;
|
|
83
|
+
}
|
|
84
|
+
const SH_RETRIES = 2;
|
|
85
|
+
const SH_RETRY_DELAY_MS = 2e3;
|
|
86
|
+
/**
|
|
87
|
+
* Run a shell script in the sandbox via `sh -c`, bounded by a hang guard.
|
|
88
|
+
* Transient transport-level 5xx failures (proxy hiccups while the VM boots)
|
|
89
|
+
* are retried with a short backoff; every script routed through here is safe
|
|
90
|
+
* to re-run. Hang-guard timeouts are NOT retried — the budget applies to the
|
|
91
|
+
* command as a whole.
|
|
92
|
+
*/
|
|
93
|
+
async function sh(sandbox, script, options = {}) {
|
|
94
|
+
const deadlineMs = Date.now() + (options.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS);
|
|
95
|
+
for (let attempt = 0;; attempt++) try {
|
|
96
|
+
return await shOnce(sandbox, script, {
|
|
97
|
+
...options,
|
|
98
|
+
timeoutMs: Math.max(deadlineMs - Date.now(), 1)
|
|
99
|
+
});
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (attempt >= SH_RETRIES || !isTransientTransportError(error)) throw error;
|
|
102
|
+
const delayMs = SH_RETRY_DELAY_MS * (attempt + 1);
|
|
103
|
+
if (deadlineMs - Date.now() <= delayMs) throw error;
|
|
104
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Single `sh -c` execution attempt, bounded by the hang guard. */
|
|
108
|
+
async function shOnce(sandbox, script, options) {
|
|
109
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
|
|
110
|
+
let timer;
|
|
111
|
+
const hangGuard = new Promise((_, reject) => {
|
|
112
|
+
timer = setTimeout(() => {
|
|
113
|
+
const phase = options.phase ? ` during ${options.phase}` : "";
|
|
114
|
+
reject(/* @__PURE__ */ new Error(`Sandbox command timed out after ${Math.round(timeoutMs / 1e3)}s${phase}.`));
|
|
115
|
+
}, timeoutMs);
|
|
116
|
+
timer.unref?.();
|
|
117
|
+
});
|
|
118
|
+
try {
|
|
119
|
+
return await Promise.race([sandbox.executeCommand("sh", ["-c", script], { timeout: timeoutMs }), hangGuard]);
|
|
120
|
+
} finally {
|
|
121
|
+
clearTimeout(timer);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** Error raised when the sandbox cannot materialize the repo (actionable). */
|
|
125
|
+
var MaterializeError = class extends Error {
|
|
126
|
+
code;
|
|
127
|
+
constructor(message, code) {
|
|
128
|
+
super(message);
|
|
129
|
+
this.code = code;
|
|
130
|
+
this.name = "MaterializeError";
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* Build the token-auth clone/pull URL for a repo. The token lives only inside
|
|
135
|
+
* this URL and is scrubbed from the remote after the operation.
|
|
136
|
+
*/
|
|
137
|
+
function tokenUrl(repoFullName, token) {
|
|
138
|
+
return `https://x-access-token:${token}@github.com/${repoFullName}.git`;
|
|
139
|
+
}
|
|
140
|
+
function cleanUrl(repoFullName) {
|
|
141
|
+
return `https://github.com/${repoFullName}.git`;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Materialize the repo inside the user's sandbox. Clones on first open, pulls on
|
|
145
|
+
* re-open. Always scrubs the install token from the remote afterwards and sets
|
|
146
|
+
* `materialized_at` on the per-user sandbox binding row.
|
|
147
|
+
*
|
|
148
|
+
*/
|
|
149
|
+
async function materializeRepo(options) {
|
|
150
|
+
const { row: sandboxRow, repoInfo, sandbox, token, storage, onProgress } = options;
|
|
151
|
+
const workdir = sandboxRow.sandboxWorkdir;
|
|
152
|
+
const repo = repoInfo.repoFullName;
|
|
153
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw new MaterializeError(`Refusing to materialize: invalid repo full name '${repo}'.`, "clone-failed");
|
|
154
|
+
if (!/^[A-Za-z0-9_./-]+$/.test(repoInfo.defaultBranch)) throw new MaterializeError(`Refusing to materialize: invalid default branch '${repoInfo.defaultBranch}'.`, "clone-failed");
|
|
155
|
+
if ((await sh(sandbox, "git --version")).exitCode !== 0) throw new MaterializeError("git is not installed in the sandbox. The sandbox template must include git.", "git-missing");
|
|
156
|
+
const authUrl = tokenUrl(repo, token);
|
|
157
|
+
const alreadyMaterialized = await hasExistingCheckout(sandbox, workdir, repo);
|
|
158
|
+
let succeeded = false;
|
|
159
|
+
try {
|
|
160
|
+
if (!alreadyMaterialized) {
|
|
161
|
+
reportProgress(onProgress, {
|
|
162
|
+
phase: "cloning",
|
|
163
|
+
message: `Cloning ${repo} (first open can take a minute)…`
|
|
164
|
+
});
|
|
165
|
+
const clone = await sh(sandbox, `git clone --depth=1 --single-branch --branch ${shellQuote(repoInfo.defaultBranch)} ${shellQuote(authUrl)} ${shellQuote(workdir)}`, { phase: "repository clone" });
|
|
166
|
+
if (clone.exitCode !== 0) throw classifyGitFailure(clone, "clone-failed");
|
|
167
|
+
} else {
|
|
168
|
+
reportProgress(onProgress, {
|
|
169
|
+
phase: "pulling",
|
|
170
|
+
message: `Updating ${repo} to the latest changes…`
|
|
171
|
+
});
|
|
172
|
+
const setUrl = await sh(sandbox, `git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(authUrl)}`);
|
|
173
|
+
if (setUrl.exitCode !== 0) throw new MaterializeError(`Failed to set git remote: ${setUrl.stderr}`, "pull-failed");
|
|
174
|
+
const pull = await sh(sandbox, `git -C ${shellQuote(workdir)} pull --ff-only`, { phase: "repository pull" });
|
|
175
|
+
if (pull.exitCode !== 0) {
|
|
176
|
+
if (!isBenignNonFastForward(pull)) throw classifyGitFailure(pull, "pull-failed");
|
|
177
|
+
reportProgress(onProgress, {
|
|
178
|
+
phase: "pulling",
|
|
179
|
+
message: "Workspace has local changes that diverge from the remote — keeping them as-is."
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
succeeded = true;
|
|
184
|
+
} finally {
|
|
185
|
+
await scrubRemote(sandbox, workdir, repo, succeeded);
|
|
186
|
+
}
|
|
187
|
+
reportProgress(onProgress, {
|
|
188
|
+
phase: "finalizing",
|
|
189
|
+
message: "Finalizing workspace…"
|
|
190
|
+
});
|
|
191
|
+
await storage.markMaterialized({ id: sandboxRow.id });
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Reset a pooled workdir that a new session just claimed: the previous
|
|
195
|
+
* session's branch and dirty state must not leak into the new session, so
|
|
196
|
+
* force-checkout the default branch and drop all local modifications. When
|
|
197
|
+
* the claimed VM was reaped and re-provisioned there is no checkout yet and
|
|
198
|
+
* this is a no-op (the clone path handles it). A wedged checkout falls back
|
|
199
|
+
* to wiping the workdir so `materializeRepo` re-clones inside the same VM
|
|
200
|
+
* instead of permanently failing the session.
|
|
201
|
+
*/
|
|
202
|
+
async function recycleClaimedWorkdir(sandbox, workdir, defaultBranch) {
|
|
203
|
+
if (!/^[A-Za-z0-9_./-]+$/.test(defaultBranch)) throw new MaterializeError(`Refusing to recycle: invalid default branch '${defaultBranch}'.`, "clone-failed");
|
|
204
|
+
const w = shellQuote(workdir);
|
|
205
|
+
if ((await sh(sandbox, `git -C ${w} rev-parse --is-inside-work-tree`)).exitCode !== 0) return;
|
|
206
|
+
const recycle = await sh(sandbox, `git -C ${w} checkout -f ${shellQuote(defaultBranch)} && git -C ${w} reset --hard && git -C ${w} clean -fdx`, { phase: "claimed workdir recycle" });
|
|
207
|
+
if (recycle.exitCode === 0) return;
|
|
208
|
+
if ((await sh(sandbox, `rm -rf ${w}`)).exitCode !== 0) throw new MaterializeError(`Failed to recycle claimed sandbox workdir: ${recycle.stderr}`, "clone-failed");
|
|
209
|
+
}
|
|
210
|
+
/** Check out a session's branch inside its isolated repository clone. */
|
|
211
|
+
async function checkoutSessionBranch(sandbox, workdir, { branch, baseBranch, token, repoFullName }) {
|
|
212
|
+
if (!isValidGitRef(branch) || !isValidGitRef(baseBranch)) throw new MaterializeError("Refusing to create a session from an invalid branch name.", "clone-failed");
|
|
213
|
+
const current = await sh(sandbox, `git -C ${shellQuote(workdir)} branch --show-current`);
|
|
214
|
+
if (current.exitCode === 0 && current.stdout.trim() === branch) return;
|
|
215
|
+
if ((await sh(sandbox, `git -C ${shellQuote(workdir)} show-ref --verify --quiet refs/heads/${shellQuote(branch)}`)).exitCode === 0) {
|
|
216
|
+
const checkout = await sh(sandbox, `git -C ${shellQuote(workdir)} checkout ${shellQuote(branch)}`);
|
|
217
|
+
if (checkout.exitCode !== 0) {
|
|
218
|
+
if (isBlockedByLocalWork(checkout)) return;
|
|
219
|
+
throw classifyGitFailure(checkout, "clone-failed");
|
|
220
|
+
}
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
const authUrl = tokenUrl(repoFullName, token);
|
|
224
|
+
try {
|
|
225
|
+
const setUrl = await sh(sandbox, `git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(authUrl)}`);
|
|
226
|
+
if (setUrl.exitCode !== 0) throw classifyGitFailure(setUrl, "pull-failed");
|
|
227
|
+
const fetch = await sh(sandbox, `git -C ${shellQuote(workdir)} fetch origin ${shellQuote(baseBranch)} && git -C ${shellQuote(workdir)} checkout -b ${shellQuote(branch)} FETCH_HEAD`, {
|
|
228
|
+
timeoutMs: CHECKOUT_COMMAND_TIMEOUT_MS,
|
|
229
|
+
phase: "branch checkout"
|
|
230
|
+
});
|
|
231
|
+
if (fetch.exitCode !== 0) {
|
|
232
|
+
if (isBlockedByLocalWork(fetch)) return;
|
|
233
|
+
throw classifyGitFailure(fetch, "clone-failed");
|
|
234
|
+
}
|
|
235
|
+
} finally {
|
|
236
|
+
await sh(sandbox, `git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(cleanUrl(repoFullName))}`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* True when a failed `git checkout` just means uncommitted or untracked files
|
|
241
|
+
* in the working tree would be clobbered by the branch switch. Those files are
|
|
242
|
+
* a session's work in progress — the switch must yield to them, never the
|
|
243
|
+
* other way around.
|
|
244
|
+
*/
|
|
245
|
+
function isBlockedByLocalWork(result) {
|
|
246
|
+
const output = `${result.stderr || ""}\n${result.stdout || ""}`;
|
|
247
|
+
return /Your local changes to the following files would be overwritten by checkout|untracked working tree files would be overwritten by checkout/i.test(output);
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* True when the workdir already holds a git checkout whose `origin` points at
|
|
251
|
+
* this exact repo. Matches both the clean and token-auth URL forms; any other
|
|
252
|
+
* remote (or no git dir at all) falls back to the clone path.
|
|
253
|
+
*/
|
|
254
|
+
async function hasExistingCheckout(sandbox, workdir, repoFullName) {
|
|
255
|
+
const result = await sh(sandbox, `git -C ${shellQuote(workdir)} remote get-url origin`);
|
|
256
|
+
if (result.exitCode !== 0) return false;
|
|
257
|
+
const url = result.stdout.trim().toLowerCase();
|
|
258
|
+
const suffix = `github.com/${repoFullName.toLowerCase()}`;
|
|
259
|
+
return url.endsWith(`${suffix}.git`) || url.endsWith(suffix);
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Reset the git remote back to the tokenless URL. On a successful clone/pull the
|
|
263
|
+
* workdir always has a `.git`, so a non-zero exit code here means the token may
|
|
264
|
+
* still be persisted — surface it. On the failure path the workdir may not exist
|
|
265
|
+
* (e.g. a failed clone), so a non-zero exit is tolerated — and never masks the
|
|
266
|
+
* primary failure being thrown through the `finally`.
|
|
267
|
+
*/
|
|
268
|
+
async function scrubRemote(sandbox, workdir, repoFullName, expectGitDir) {
|
|
269
|
+
const result = await sh(sandbox, `git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(cleanUrl(repoFullName))}`);
|
|
270
|
+
if (result.exitCode !== 0 && expectGitDir) throw new MaterializeError(`Failed to scrub installation token from git remote: ${result.stderr.trim() || result.stdout.trim()}`, "pull-failed");
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* True when a failed `git pull --ff-only` on re-open just means the current
|
|
274
|
+
* branch can't be fast-forwarded — not that anything is broken. The shared
|
|
275
|
+
* workdir is routinely left on a session's working branch, which may have
|
|
276
|
+
* local commits diverging from upstream, no upstream at all (session branches
|
|
277
|
+
* are created from `FETCH_HEAD`), or a detached HEAD. A checkout can also
|
|
278
|
+
* hold uncommitted or untracked files (a build or script run left residue,
|
|
279
|
+
* or an older session worked directly in the shared checkout), which makes
|
|
280
|
+
* git refuse the merge outright. In all of these cases the checkout is
|
|
281
|
+
* intact and may hold real work; materialization must keep it as-is rather
|
|
282
|
+
* than fail the workspace open — and must never discard the local state to
|
|
283
|
+
* force the pull through.
|
|
284
|
+
*/
|
|
285
|
+
function isBenignNonFastForward(result) {
|
|
286
|
+
const output = `${result.stderr || ""}\n${result.stdout || ""}`;
|
|
287
|
+
return /Not possible to fast-forward|Diverging branches can't be fast-forwarded|no tracking information for the current branch|You are not currently on a branch|Your local changes to the following files would be overwritten by merge|untracked working tree files would be overwritten by merge/i.test(output);
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Turn a failed git command into an actionable error, detecting the common
|
|
291
|
+
* "cannot reach github.com" egress failure.
|
|
292
|
+
*/
|
|
293
|
+
function classifyGitFailure(result, fallback) {
|
|
294
|
+
const stderr = result.stderr || "";
|
|
295
|
+
if (/could not resolve host|failed to connect|network is unreachable|Connection timed out/i.test(stderr)) return new MaterializeError("The sandbox could not reach github.com. The sandbox network must allow outbound egress to github.com.", "egress-blocked");
|
|
296
|
+
return new MaterializeError(`git ${fallback === "clone-failed" ? "clone" : fallback === "pull-failed" ? "pull" : "push"} failed: ${stderr}`, fallback);
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Validate a git ref (branch) name. Server-side defense-in-depth: only allow a
|
|
300
|
+
* conservative character set so a branch can never be built into a shell
|
|
301
|
+
* command in a way that escapes quoting. Mirrors the route-layer check.
|
|
302
|
+
*/
|
|
303
|
+
function isValidGitRef(value) {
|
|
304
|
+
return typeof value === "string" && value.length > 0 && value.length <= 255 && !value.startsWith("-") && /^[A-Za-z0-9_./-]+$/.test(value);
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Resolve a concrete `{ name, email }` for git authorship from a possibly-sparse
|
|
308
|
+
* identity. Falls back to a GitHub-style noreply identity so commits are never
|
|
309
|
+
* authored with an empty or host-derived identity.
|
|
310
|
+
*/
|
|
311
|
+
function resolveGitIdentity(identity) {
|
|
312
|
+
const login = (identity.login || "").trim();
|
|
313
|
+
return {
|
|
314
|
+
name: (identity.name || "").trim() || login || "Mastra Code",
|
|
315
|
+
email: (identity.email || "").trim() || (login ? `${login}@users.noreply.github.com` : "mastra-code@users.noreply.github.com")
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Configure `user.name` / `user.email` for the given repo working tree inside
|
|
320
|
+
* the sandbox so commits are authored correctly. Values are shell-quoted.
|
|
321
|
+
*/
|
|
322
|
+
async function configureGitIdentity(sandbox, workdir, identity) {
|
|
323
|
+
const { name, email } = resolveGitIdentity(identity);
|
|
324
|
+
const setName = await sh(sandbox, `git -C ${shellQuote(workdir)} config user.name ${shellQuote(name)}`);
|
|
325
|
+
if (setName.exitCode !== 0) throw new MaterializeError(`Failed to set git user.name: ${setName.stderr.trim()}`, "commit-failed");
|
|
326
|
+
const setEmail = await sh(sandbox, `git -C ${shellQuote(workdir)} config user.email ${shellQuote(email)}`);
|
|
327
|
+
if (setEmail.exitCode !== 0) throw new MaterializeError(`Failed to set git user.email: ${setEmail.stderr.trim()}`, "commit-failed");
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Temporarily rewrite `origin` to a tokenized URL, run `fn` (e.g. a push), and
|
|
331
|
+
* **always** scrub the remote back to the tokenless URL in a `finally`. The
|
|
332
|
+
* token therefore only ever lives in the remote URL for the duration of the
|
|
333
|
+
* operation and is never left in the VM's git config.
|
|
334
|
+
*
|
|
335
|
+
* On the success path the scrub must succeed (a leaked token is a hard error);
|
|
336
|
+
* if it fails we surface it. On the failure path the scrub is best-effort but
|
|
337
|
+
* still attempted, and the original operation error is rethrown.
|
|
338
|
+
*/
|
|
339
|
+
async function withInstallToken(sandbox, workdir, repoFullName, token, fn) {
|
|
340
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(repoFullName)) throw new MaterializeError(`Refusing to push: invalid repo full name '${repoFullName}'.`, "push-failed");
|
|
341
|
+
const setUrl = await sh(sandbox, `git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(tokenUrl(repoFullName, token))}`);
|
|
342
|
+
if (setUrl.exitCode !== 0) {
|
|
343
|
+
await scrubRemote(sandbox, workdir, repoFullName, false);
|
|
344
|
+
throw new MaterializeError(`Failed to set git remote: ${setUrl.stderr.trim()}`, "push-failed");
|
|
345
|
+
}
|
|
346
|
+
try {
|
|
347
|
+
return await fn();
|
|
348
|
+
} finally {
|
|
349
|
+
await scrubRemote(sandbox, workdir, repoFullName, true);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Push a branch back to GitHub from inside the sandbox using a short-lived
|
|
354
|
+
* installation token. The branch is ref-validated, the token is injected only
|
|
355
|
+
* into the remote URL via `withInstallToken`, and egress failures are
|
|
356
|
+
* classified into actionable errors.
|
|
357
|
+
*/
|
|
358
|
+
async function pushBranch(sandbox, workdir, branch, token, repoFullName) {
|
|
359
|
+
if (!isValidGitRef(branch)) throw new MaterializeError(`Refusing to push: invalid branch name '${branch}'.`, "push-failed");
|
|
360
|
+
await withInstallToken(sandbox, workdir, repoFullName, token, async () => {
|
|
361
|
+
const push = await sh(sandbox, `git -C ${shellQuote(workdir)} push -u origin ${shellQuote(branch)}`);
|
|
362
|
+
if (push.exitCode !== 0) throw classifyGitFailure(push, "push-failed");
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Stage every change in the working tree and create a commit inside the
|
|
367
|
+
* sandbox. The git identity is configured first so authorship is correct. When
|
|
368
|
+
* there is nothing to commit this is a no-op (`committed: false`) rather than an
|
|
369
|
+
* error, so callers can safely commit-then-push without first diffing.
|
|
370
|
+
*
|
|
371
|
+
* @param sandbox the live sandbox containing the checkout
|
|
372
|
+
* @param workdir the worktree (or repo) path to commit in
|
|
373
|
+
* @param message the commit message (quoted; arbitrary text is safe)
|
|
374
|
+
* @param identity authorship identity for the commit
|
|
375
|
+
*/
|
|
376
|
+
async function commitAll(sandbox, workdir, message, identity) {
|
|
377
|
+
await configureGitIdentity(sandbox, workdir, identity);
|
|
378
|
+
const add = await sh(sandbox, `git -C ${shellQuote(workdir)} add -A`);
|
|
379
|
+
if (add.exitCode !== 0) throw new MaterializeError(`git add failed: ${add.stderr.trim() || add.stdout.trim()}`, "commit-failed");
|
|
380
|
+
if ((await sh(sandbox, `git -C ${shellQuote(workdir)} diff --cached --quiet`)).exitCode === 0) return { committed: false };
|
|
381
|
+
const commit = await sh(sandbox, `git -C ${shellQuote(workdir)} commit -m ${shellQuote(message)}`);
|
|
382
|
+
if (commit.exitCode !== 0) throw new MaterializeError(`git commit failed: ${commit.stderr.trim() || commit.stdout.trim()}`, "commit-failed");
|
|
383
|
+
return { committed: true };
|
|
384
|
+
}
|
|
385
|
+
/** Error raised when a worktree cannot be created/reused inside the sandbox. */
|
|
386
|
+
var WorktreeError = class extends Error {
|
|
387
|
+
code;
|
|
388
|
+
constructor(message, code) {
|
|
389
|
+
super(message);
|
|
390
|
+
this.code = code;
|
|
391
|
+
this.name = "WorktreeError";
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
/**
|
|
395
|
+
* Reduce a (already ref-validated) branch name to a filesystem-safe directory
|
|
396
|
+
* segment for the worktree path: slashes/dots/unsafe chars collapsed to `-`.
|
|
397
|
+
* This only affects the *directory name*, never the git branch itself.
|
|
398
|
+
*
|
|
399
|
+
* Sanitization is lossy (e.g. `feat/a` and `feat-a` both reduce to `feat-a`),
|
|
400
|
+
* so an 8-char hash of the original branch is appended whenever the sanitized
|
|
401
|
+
* form differs from the input. That keeps clean names (`main`) readable while
|
|
402
|
+
* guaranteeing distinct branches never share a worktree directory.
|
|
403
|
+
*/
|
|
404
|
+
function safeBranchDir(branch) {
|
|
405
|
+
const sanitized = branch.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/\/+/g, "-").replace(/^[-.]+|[-.]+$/g, "").slice(0, 100) || "work";
|
|
406
|
+
if (sanitized === branch) return sanitized;
|
|
407
|
+
return `${sanitized}-${createHash("sha256").update(branch).digest("hex").slice(0, 8)}`;
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Compute the absolute worktree path for a branch, server-side only. Worktrees
|
|
411
|
+
* live alongside the repo checkout under a sibling `worktrees/` directory so the
|
|
412
|
+
* repo's `.git` is shared. Never derived from client-supplied paths.
|
|
413
|
+
*/
|
|
414
|
+
function computeWorktreePath(repoWorkdir, branch) {
|
|
415
|
+
return `${repoWorkdir.replace(/\/+$/, "").split("/").slice(0, -1).join("/") || ""}/worktrees/${safeBranchDir(branch)}`;
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Create (or reuse) a git worktree + branch inside the sandbox for a unit of
|
|
419
|
+
* work. Idempotent: if a worktree already exists at the computed path it is
|
|
420
|
+
* reused. The branch is created from the freshly fetched `origin/<baseBranch>`
|
|
421
|
+
* — never the sandbox's possibly stale local ref — so new worktrees always
|
|
422
|
+
* start from the latest remote state.
|
|
423
|
+
*
|
|
424
|
+
* @param sandbox live sandbox containing the base checkout
|
|
425
|
+
* @param repoWorkdir the base repo checkout path inside the sandbox
|
|
426
|
+
* @param branch the feature branch (ref-validated server-side)
|
|
427
|
+
* @param baseBranch the branch to fork from (ref-validated; defaults to the repo's default branch)
|
|
428
|
+
* @param token short-lived installation token used only for the base-branch fetch
|
|
429
|
+
* @param repoFullName `owner/repo` used to build the tokenized remote URL
|
|
430
|
+
*/
|
|
431
|
+
async function ensureWorktree(sandbox, repoWorkdir, { branch, baseBranch, token, repoFullName }) {
|
|
432
|
+
if (!isValidGitRef(branch)) throw new WorktreeError(`Invalid branch name '${branch}'.`, "invalid-branch");
|
|
433
|
+
if (!isValidGitRef(baseBranch)) throw new WorktreeError(`Invalid base branch name '${baseBranch}'.`, "invalid-branch");
|
|
434
|
+
const worktreePath = computeWorktreePath(repoWorkdir, branch);
|
|
435
|
+
if ((await sh(sandbox, `test -e ${shellQuote(`${worktreePath}/.git`)}`)).exitCode === 0) return {
|
|
436
|
+
worktreePath,
|
|
437
|
+
branch,
|
|
438
|
+
baseBranch,
|
|
439
|
+
reused: true
|
|
440
|
+
};
|
|
441
|
+
const baseRef = `origin/${baseBranch}`;
|
|
442
|
+
await withInstallToken(sandbox, repoWorkdir, repoFullName, token, async () => {
|
|
443
|
+
const fetch = await sh(sandbox, `git -C ${shellQuote(repoWorkdir)} fetch origin ${shellQuote(`+refs/heads/${baseBranch}:refs/remotes/${baseRef}`)}`);
|
|
444
|
+
if (fetch.exitCode !== 0) throw classifyGitFailure(fetch, "pull-failed");
|
|
445
|
+
});
|
|
446
|
+
const add = await sh(sandbox, `git -C ${shellQuote(repoWorkdir)} worktree add --no-track -B ${shellQuote(branch)} ${shellQuote(worktreePath)} ${shellQuote(baseRef)}`);
|
|
447
|
+
if (add.exitCode !== 0) throw new WorktreeError(`git worktree add failed: ${add.stderr.trim() || add.stdout.trim()}`, "worktree-failed");
|
|
448
|
+
return {
|
|
449
|
+
worktreePath,
|
|
450
|
+
branch,
|
|
451
|
+
baseBranch,
|
|
452
|
+
reused: false
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Run the project's setup command (e.g. `pnpm i && pnpm build`) inside a
|
|
457
|
+
* freshly created worktree. Called before the worktree is handed to any agent
|
|
458
|
+
* run so the checkout is ready to build/test. A non-zero exit is a hard error —
|
|
459
|
+
* starting agent work in a half-set-up tree is worse than failing the request.
|
|
460
|
+
*
|
|
461
|
+
* Security model: the command is intentionally arbitrary shell — that is the
|
|
462
|
+
* feature (install deps, build, seed fixtures). It is only configurable by
|
|
463
|
+
* authenticated org members (the settings route is gated by
|
|
464
|
+
* `resolveOrgTenant` + org-scoped project lookup, with length and
|
|
465
|
+
* control-character validation), and it executes exclusively inside the
|
|
466
|
+
* project's isolated sandbox — the same environment where org members already
|
|
467
|
+
* run arbitrary shell via the agent's command tool. It never runs on the web
|
|
468
|
+
* server host, so it grants no privilege beyond what sandbox access already
|
|
469
|
+
* provides.
|
|
470
|
+
*
|
|
471
|
+
* @param sandbox live sandbox containing the worktree
|
|
472
|
+
* @param worktreePath the server-computed worktree path the command runs in
|
|
473
|
+
* @param command the org-configured setup shell command
|
|
474
|
+
*/
|
|
475
|
+
async function runWorktreeSetup(sandbox, worktreePath, command) {
|
|
476
|
+
const result = await sh(sandbox, `cd ${shellQuote(worktreePath)} && { ${command}\n}`, { phase: "worktree setup" });
|
|
477
|
+
if (result.exitCode !== 0) {
|
|
478
|
+
const detail = (result.stderr.trim() || result.stdout.trim()).slice(-2e3);
|
|
479
|
+
throw new WorktreeError(`Setup command failed (exit ${result.exitCode}): ${detail}`, "setup-failed");
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Remove a worktree (and its local feature branch) from the sandbox. The
|
|
484
|
+
* checkout is removed with `--force` — the caller owns confirming that any
|
|
485
|
+
* uncommitted work in it can be discarded. Idempotent: a worktree whose
|
|
486
|
+
* directory is already gone only has its metadata pruned.
|
|
487
|
+
*
|
|
488
|
+
* @param sandbox live sandbox containing the base checkout
|
|
489
|
+
* @param repoWorkdir the base repo checkout path inside the sandbox
|
|
490
|
+
* @param branch the worktree's feature branch (ref-validated)
|
|
491
|
+
* @param worktreePath the persisted, server-computed worktree path
|
|
492
|
+
*/
|
|
493
|
+
async function removeWorktree(sandbox, repoWorkdir, { branch, worktreePath }) {
|
|
494
|
+
if (!isValidGitRef(branch)) throw new WorktreeError(`Invalid branch name '${branch}'.`, "invalid-branch");
|
|
495
|
+
const remove = await sh(sandbox, `git -C ${shellQuote(repoWorkdir)} worktree remove --force ${shellQuote(worktreePath)}`);
|
|
496
|
+
if (remove.exitCode !== 0) {
|
|
497
|
+
await sh(sandbox, `git -C ${shellQuote(repoWorkdir)} worktree prune`);
|
|
498
|
+
if ((await sh(sandbox, `test -e ${shellQuote(worktreePath)}`)).exitCode === 0) throw new WorktreeError(`git worktree remove failed: ${remove.stderr.trim() || remove.stdout.trim()}`, "worktree-failed");
|
|
499
|
+
}
|
|
500
|
+
await sh(sandbox, `git -C ${shellQuote(repoWorkdir)} branch -D ${shellQuote(branch)}`);
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Preflight that `gh` is installed in the sandbox. Only called on the PR path so
|
|
504
|
+
* a missing `gh` never blocks clone/open. Surfaces an actionable error naming
|
|
505
|
+
* the sandbox template requirement.
|
|
506
|
+
*/
|
|
507
|
+
async function assertGhAvailable(sandbox) {
|
|
508
|
+
if ((await sh(sandbox, "gh --version")).exitCode !== 0) throw new MaterializeError("The GitHub CLI (gh) is not installed in the sandbox. The sandbox template must include gh to open pull requests.", "gh-missing");
|
|
509
|
+
}
|
|
510
|
+
/** Match the first GitHub PR URL in `gh pr create` output. */
|
|
511
|
+
function parsePullRequestUrl(stdout) {
|
|
512
|
+
return stdout.match(/https:\/\/github\.com\/[^\s]+\/pull\/\d+/)?.[0];
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Open a pull request from inside the sandbox via `gh pr create`. The token is
|
|
516
|
+
* passed only through a per-invocation `GH_TOKEN` env scoped to the single `gh`
|
|
517
|
+
* process (never persisted), all arguments are shell-quoted, and the resulting
|
|
518
|
+
* PR URL is parsed from stdout.
|
|
519
|
+
*
|
|
520
|
+
* @param sandbox live sandbox containing the checkout
|
|
521
|
+
* @param workdir the worktree (or repo) path the PR head branch is checked out in
|
|
522
|
+
*/
|
|
523
|
+
async function createPullRequest(sandbox, workdir, { token, base, head, title, body }) {
|
|
524
|
+
if (!isValidGitRef(base)) throw new MaterializeError(`Refusing to open PR: invalid base branch '${base}'.`, "pr-failed");
|
|
525
|
+
if (!isValidGitRef(head)) throw new MaterializeError(`Refusing to open PR: invalid head branch '${head}'.`, "pr-failed");
|
|
526
|
+
await assertGhAvailable(sandbox);
|
|
527
|
+
const ghCommand = [
|
|
528
|
+
`GH_TOKEN=${shellQuote(token)} gh pr create`,
|
|
529
|
+
`--base ${shellQuote(base)}`,
|
|
530
|
+
`--head ${shellQuote(head)}`,
|
|
531
|
+
`--title ${shellQuote(title)}`,
|
|
532
|
+
`--body ${shellQuote(body ?? "")}`
|
|
533
|
+
].join(" ");
|
|
534
|
+
const result = await sh(sandbox, `cd ${shellQuote(workdir)} && ${ghCommand}`);
|
|
535
|
+
if (result.exitCode !== 0) {
|
|
536
|
+
const classified = classifyGitFailure(result, "push-failed");
|
|
537
|
+
if (classified.code === "egress-blocked") throw classified;
|
|
538
|
+
throw new MaterializeError(`gh pr create failed: ${result.stderr.trim() || result.stdout.trim()}`, "pr-failed");
|
|
539
|
+
}
|
|
540
|
+
const url = parsePullRequestUrl(result.stdout);
|
|
541
|
+
if (!url) throw new MaterializeError(`gh pr create succeeded but no PR URL was found in its output: ${result.stdout.trim()}`, "pr-failed");
|
|
542
|
+
return { url };
|
|
543
|
+
}
|
|
544
|
+
//#endregion
|
|
545
|
+
export { CHECKOUT_COMMAND_TIMEOUT_MS, MaterializeError, WorktreeError, checkoutSessionBranch, commitAll, computeWorktreePath, configureGitIdentity, createPullRequest, ensureProjectSandbox, ensureWorktree, isValidGitRef, materializeRepo, pushBranch, recycleClaimedWorkdir, removeWorktree, resolveGitIdentity, runWorktreeSetup, safeBranchDir, shellQuote, teardownProjectSandbox, withInstallToken };
|
|
546
|
+
|
|
547
|
+
//# sourceMappingURL=sandbox.js.map
|