@mastra/factory 0.0.0 → 0.1.0-alpha.2
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 +10 -0
- package/LICENSE.md +30 -0
- package/dist/auth.d.ts +181 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +370 -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/connection.js.map +1 -0
- package/dist/capabilities/intake.d.ts +93 -0
- package/dist/capabilities/intake.d.ts.map +1 -0
- package/dist/capabilities/intake.js +1 -0
- package/dist/capabilities/intake.js.map +1 -0
- package/dist/capabilities/version-control.d.ts +239 -0
- package/dist/capabilities/version-control.d.ts.map +1 -0
- package/dist/capabilities/version-control.js +1 -0
- package/dist/capabilities/version-control.js.map +1 -0
- package/dist/factory.d.ts +145 -0
- package/dist/factory.d.ts.map +1 -0
- package/dist/factory.js +38208 -0
- package/dist/factory.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +38208 -0
- package/dist/index.js.map +1 -0
- package/dist/integrations/base.d.ts +197 -0
- package/dist/integrations/base.d.ts.map +1 -0
- package/dist/integrations/base.js +1 -0
- package/dist/integrations/base.js.map +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 +28 -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 +41 -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 +2999 -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/project-lock.d.ts +78 -0
- package/dist/integrations/github/project-lock.d.ts.map +1 -0
- package/dist/integrations/github/project-lock.js +70 -0
- package/dist/integrations/github/project-lock.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 +104 -0
- package/dist/integrations/github/provenance.js.map +1 -0
- package/dist/integrations/github/routes.d.ts +72 -0
- package/dist/integrations/github/routes.d.ts.map +1 -0
- package/dist/integrations/github/routes.js +1832 -0
- package/dist/integrations/github/routes.js.map +1 -0
- package/dist/integrations/github/sandbox.d.ts +268 -0
- package/dist/integrations/github/sandbox.d.ts.map +1 -0
- package/dist/integrations/github/sandbox.js +381 -0
- package/dist/integrations/github/sandbox.js.map +1 -0
- package/dist/integrations/github/session-subscriptions.d.ts +23 -0
- package/dist/integrations/github/session-subscriptions.d.ts.map +1 -0
- package/dist/integrations/github/session-subscriptions.js +190 -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 +70 -0
- package/dist/integrations/github/subscriptions.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 +381 -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 +108 -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 +962 -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 +242 -0
- package/dist/integrations/linear/routes.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/linear/storage.js.map +1 -0
- package/dist/integrations/platform/api-client.d.ts +24 -0
- package/dist/integrations/platform/api-client.d.ts.map +1 -0
- package/dist/integrations/platform/api-client.js +153 -0
- package/dist/integrations/platform/api-client.js.map +1 -0
- package/dist/integrations/platform/github/event-worker.d.ts +42 -0
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -0
- package/dist/integrations/platform/github/event-worker.js +577 -0
- package/dist/integrations/platform/github/event-worker.js.map +1 -0
- package/dist/integrations/platform/github/integration.d.ts +36 -0
- package/dist/integrations/platform/github/integration.d.ts.map +1 -0
- package/dist/integrations/platform/github/integration.js +3242 -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 +891 -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 +96 -0
- package/dist/integrations/workos/integration.js.map +1 -0
- package/dist/routes/config.d.ts +220 -0
- package/dist/routes/config.d.ts.map +1 -0
- package/dist/routes/config.js +770 -0
- package/dist/routes/config.js.map +1 -0
- package/dist/routes/fs.d.ts +105 -0
- package/dist/routes/fs.d.ts.map +1 -0
- package/dist/routes/fs.js +294 -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 +25058 -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 +395 -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 +68 -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 +11 -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 +181 -0
- package/dist/routes/skills.js.map +1 -0
- package/dist/routes/surface.d.ts +83 -0
- package/dist/routes/surface.d.ts.map +1 -0
- package/dist/routes/surface.js +28504 -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 +181 -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 +902 -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 +40 -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 +328 -0
- package/dist/rules/defaults.js.map +1 -0
- package/dist/rules/dispatcher.d.ts +40 -0
- package/dist/rules/dispatcher.d.ts.map +1 -0
- package/dist/rules/dispatcher.js +695 -0
- package/dist/rules/dispatcher.js.map +1 -0
- package/dist/rules/github-service.d.ts +27 -0
- package/dist/rules/github-service.d.ts.map +1 -0
- package/dist/rules/github-service.js +460 -0
- package/dist/rules/github-service.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 +577 -0
- package/dist/rules/index.js.map +1 -0
- package/dist/rules/linear-service.d.ts +27 -0
- package/dist/rules/linear-service.d.ts.map +1 -0
- package/dist/rules/linear-service.js +343 -0
- package/dist/rules/linear-service.js.map +1 -0
- package/dist/rules/processor.d.ts +54 -0
- package/dist/rules/processor.d.ts.map +1 -0
- package/dist/rules/processor.js +629 -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 +27 -0
- package/dist/rules/resolve.js.map +1 -0
- package/dist/rules/start-coordinator.d.ts +58 -0
- package/dist/rules/start-coordinator.d.ts.map +1 -0
- package/dist/rules/start-coordinator.js +136 -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 +93 -0
- package/dist/rules/tools.js.map +1 -0
- package/dist/rules/transition-service.d.ts +32 -0
- package/dist/rules/transition-service.d.ts.map +1 -0
- package/dist/rules/transition-service.js +474 -0
- package/dist/rules/transition-service.js.map +1 -0
- package/dist/rules/types.d.ts +220 -0
- package/dist/rules/types.d.ts.map +1 -0
- package/dist/rules/types.js +33 -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 +310 -0
- package/dist/rules/validation.js.map +1 -0
- package/dist/sandbox/fleet.d.ts +208 -0
- package/dist/sandbox/fleet.d.ts.map +1 -0
- package/dist/sandbox/fleet.js +259 -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 +9 -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 +20 -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 +45 -0
- package/dist/skills/service.js.map +1 -0
- package/dist/spa-static.d.ts +34 -0
- package/dist/spa-static.d.ts.map +1 -0
- package/dist/spa-static.js +73 -0
- package/dist/spa-static.js.map +1 -0
- package/dist/state-signing.d.ts +48 -0
- package/dist/state-signing.d.ts.map +1 -0
- package/dist/state-signing.js +48 -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 +65 -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 +127 -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 +165 -0
- package/dist/storage/domains/audit/domain.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 +257 -0
- package/dist/storage/domains/credentials/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 +62 -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 +252 -0
- package/dist/storage/domains/integrations/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 +95 -0
- package/dist/storage/domains/model-packs/base.js.map +1 -0
- package/dist/storage/domains/projects/base.d.ts +55 -0
- package/dist/storage/domains/projects/base.d.ts.map +1 -0
- package/dist/storage/domains/projects/base.js +99 -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 +87 -0
- package/dist/storage/domains/queue-health/base.js.map +1 -0
- package/dist/storage/domains/source-control/base.d.ts +288 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -0
- package/dist/storage/domains/source-control/base.js +722 -0
- package/dist/storage/domains/source-control/base.js.map +1 -0
- package/dist/storage/domains/source-control/inmemory.d.ts +158 -0
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -0
- package/dist/storage/domains/source-control/inmemory.js +348 -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 +1174 -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 +203 -0
- package/dist/storage/domains/work-items/metrics.js.map +1 -0
- package/dist/workspace.d.ts +20 -0
- package/dist/workspace.d.ts.map +1 -0
- package/dist/workspace.js +364 -0
- package/dist/workspace.js.map +1 -0
- package/package.json +19 -19
|
@@ -0,0 +1,1832 @@
|
|
|
1
|
+
// src/integrations/github/routes.ts
|
|
2
|
+
import { randomUUID } from "crypto";
|
|
3
|
+
import { registerApiRoute } from "@mastra/core/server";
|
|
4
|
+
import { streamSSE } from "hono/streaming";
|
|
5
|
+
|
|
6
|
+
// src/sandbox/fleet.ts
|
|
7
|
+
import path from "path";
|
|
8
|
+
function reportProgress(onProgress, event) {
|
|
9
|
+
if (!onProgress) return;
|
|
10
|
+
try {
|
|
11
|
+
onProgress(event);
|
|
12
|
+
} catch {
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
var SandboxBudgetError = class extends Error {
|
|
16
|
+
constructor(max) {
|
|
17
|
+
super(
|
|
18
|
+
`Sandbox budget exceeded: this server already has ${max} active sandbox(es), the configured per-replica maximum. Close an existing repository's sandbox and try again.`
|
|
19
|
+
);
|
|
20
|
+
this.max = max;
|
|
21
|
+
this.name = "SandboxBudgetError";
|
|
22
|
+
}
|
|
23
|
+
max;
|
|
24
|
+
code = "sandbox-budget-exceeded";
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// src/integrations/github/config.ts
|
|
28
|
+
var GITHUB_APP_ENV_VARS = [
|
|
29
|
+
"GITHUB_APP_ID",
|
|
30
|
+
"GITHUB_APP_PRIVATE_KEY",
|
|
31
|
+
"GITHUB_APP_CLIENT_ID",
|
|
32
|
+
"GITHUB_APP_CLIENT_SECRET",
|
|
33
|
+
"GITHUB_APP_SLUG"
|
|
34
|
+
];
|
|
35
|
+
function isGithubFeatureEnabled(options) {
|
|
36
|
+
return options.github !== void 0 && options.auth.enabled();
|
|
37
|
+
}
|
|
38
|
+
function getGithubFeatureDiagnostics(options) {
|
|
39
|
+
const { github, auth, appDbConfigured, stateSigner, fleet } = options;
|
|
40
|
+
return {
|
|
41
|
+
githubAppConfigured: github !== void 0,
|
|
42
|
+
factoryAuthEnabled: auth.enabled(),
|
|
43
|
+
appDbConfigured,
|
|
44
|
+
stateSecretConfigured: stateSigner?.stable ?? false,
|
|
45
|
+
sandboxEnabled: fleet?.enabled ?? false,
|
|
46
|
+
sandboxProvider: fleet?.provider ?? "none",
|
|
47
|
+
missingGithubAppEnvVars: github ? [] : [...GITHUB_APP_ENV_VARS]
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// src/integrations/github/project-lock.ts
|
|
52
|
+
import { createHash } from "crypto";
|
|
53
|
+
var inProcessLocks = /* @__PURE__ */ new Map();
|
|
54
|
+
function hashKey(key) {
|
|
55
|
+
const digest = createHash("sha256").update(key).digest();
|
|
56
|
+
const a = digest.readInt32BE(0);
|
|
57
|
+
const b = digest.readInt32BE(4);
|
|
58
|
+
return [a, b];
|
|
59
|
+
}
|
|
60
|
+
function withProjectLock(options) {
|
|
61
|
+
const { key, storage, fn, pool } = options;
|
|
62
|
+
const prev = inProcessLocks.get(key) ?? Promise.resolve();
|
|
63
|
+
const run = () => withDbAdvisoryLock({ key, storage, fn, pool });
|
|
64
|
+
const next = prev.then(run, run);
|
|
65
|
+
const tail = next.then(
|
|
66
|
+
() => void 0,
|
|
67
|
+
() => void 0
|
|
68
|
+
);
|
|
69
|
+
inProcessLocks.set(key, tail);
|
|
70
|
+
void tail.then(() => {
|
|
71
|
+
if (inProcessLocks.get(key) === tail) {
|
|
72
|
+
inProcessLocks.delete(key);
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
return next;
|
|
76
|
+
}
|
|
77
|
+
async function withDbAdvisoryLock(options) {
|
|
78
|
+
const { key, storage, fn, pool } = options;
|
|
79
|
+
if (process.env.MASTRACODE_DISTRIBUTED_LOCK === "0") {
|
|
80
|
+
return fn();
|
|
81
|
+
}
|
|
82
|
+
if (pool) return advisoryLockOver(pool, key, fn);
|
|
83
|
+
if (typeof storage?.withDistributedLock !== "function") {
|
|
84
|
+
return fn();
|
|
85
|
+
}
|
|
86
|
+
return storage.withDistributedLock(key, fn);
|
|
87
|
+
}
|
|
88
|
+
async function advisoryLockOver(pool, key, fn) {
|
|
89
|
+
const [k1, k2] = hashKey(key);
|
|
90
|
+
const client = await pool.connect();
|
|
91
|
+
try {
|
|
92
|
+
await client.query("BEGIN");
|
|
93
|
+
await client.query("SELECT pg_advisory_xact_lock($1, $2)", [k1, k2]);
|
|
94
|
+
try {
|
|
95
|
+
const result = await fn();
|
|
96
|
+
await client.query("COMMIT");
|
|
97
|
+
return result;
|
|
98
|
+
} catch (err) {
|
|
99
|
+
await client.query("ROLLBACK");
|
|
100
|
+
throw err;
|
|
101
|
+
}
|
|
102
|
+
} finally {
|
|
103
|
+
client.release();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// src/integrations/github/sandbox.ts
|
|
108
|
+
import { createHash as createHash2 } from "crypto";
|
|
109
|
+
function bindingStore(row, storage) {
|
|
110
|
+
return {
|
|
111
|
+
sandboxId: row.sandboxId,
|
|
112
|
+
setSandboxId: (id) => id === null ? storage.clearBinding({ id: row.id }) : storage.setSandboxId({ id: row.id, sandboxId: id }),
|
|
113
|
+
clear: () => storage.clearBinding({ id: row.id })
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
async function ensureProjectSandbox(options) {
|
|
117
|
+
const { fleet, row, storage, onProgress } = options;
|
|
118
|
+
return fleet.ensureSandbox(bindingStore(row, storage), onProgress);
|
|
119
|
+
}
|
|
120
|
+
async function teardownProjectSandbox(options) {
|
|
121
|
+
const { fleet, row, storage, sandbox } = options;
|
|
122
|
+
return fleet.teardownSandbox(bindingStore(row, storage), sandbox);
|
|
123
|
+
}
|
|
124
|
+
function shellQuote(value) {
|
|
125
|
+
return `'` + value.split(`'`).join(`'\\''`) + `'`;
|
|
126
|
+
}
|
|
127
|
+
async function sh(sandbox, script) {
|
|
128
|
+
return sandbox.executeCommand("sh", ["-c", script]);
|
|
129
|
+
}
|
|
130
|
+
var MaterializeError = class extends Error {
|
|
131
|
+
constructor(message, code) {
|
|
132
|
+
super(message);
|
|
133
|
+
this.code = code;
|
|
134
|
+
this.name = "MaterializeError";
|
|
135
|
+
}
|
|
136
|
+
code;
|
|
137
|
+
};
|
|
138
|
+
function tokenUrl(repoFullName, token) {
|
|
139
|
+
return `https://x-access-token:${token}@github.com/${repoFullName}.git`;
|
|
140
|
+
}
|
|
141
|
+
function cleanUrl(repoFullName) {
|
|
142
|
+
return `https://github.com/${repoFullName}.git`;
|
|
143
|
+
}
|
|
144
|
+
async function materializeRepo(options) {
|
|
145
|
+
const { row: sandboxRow, repoInfo, sandbox, token, storage, onProgress } = options;
|
|
146
|
+
const workdir = sandboxRow.sandboxWorkdir;
|
|
147
|
+
const repo = repoInfo.repoFullName;
|
|
148
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) {
|
|
149
|
+
throw new MaterializeError(`Refusing to materialize: invalid repo full name '${repo}'.`, "clone-failed");
|
|
150
|
+
}
|
|
151
|
+
if (!/^[A-Za-z0-9_./-]+$/.test(repoInfo.defaultBranch)) {
|
|
152
|
+
throw new MaterializeError(
|
|
153
|
+
`Refusing to materialize: invalid default branch '${repoInfo.defaultBranch}'.`,
|
|
154
|
+
"clone-failed"
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
const gitVersion = await sh(sandbox, "git --version");
|
|
158
|
+
if (gitVersion.exitCode !== 0) {
|
|
159
|
+
throw new MaterializeError(
|
|
160
|
+
"git is not installed in the sandbox. The sandbox template must include git.",
|
|
161
|
+
"git-missing"
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
const authUrl = tokenUrl(repo, token);
|
|
165
|
+
const alreadyMaterialized = Boolean(sandboxRow.materializedAt) || await hasExistingCheckout(sandbox, workdir, repo);
|
|
166
|
+
try {
|
|
167
|
+
if (!alreadyMaterialized) {
|
|
168
|
+
reportProgress(onProgress, {
|
|
169
|
+
phase: "cloning",
|
|
170
|
+
message: `Cloning ${repo} (first open can take a minute)\u2026`
|
|
171
|
+
});
|
|
172
|
+
const clone = await sh(
|
|
173
|
+
sandbox,
|
|
174
|
+
`git clone --depth=1 --single-branch --branch ${shellQuote(repoInfo.defaultBranch)} ${shellQuote(authUrl)} ${shellQuote(workdir)}`
|
|
175
|
+
);
|
|
176
|
+
if (clone.exitCode !== 0) {
|
|
177
|
+
throw classifyGitFailure(clone, "clone-failed");
|
|
178
|
+
}
|
|
179
|
+
} else {
|
|
180
|
+
reportProgress(onProgress, { phase: "pulling", message: `Updating ${repo} to the latest changes\u2026` });
|
|
181
|
+
const setUrl = await sh(sandbox, `git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(authUrl)}`);
|
|
182
|
+
if (setUrl.exitCode !== 0) {
|
|
183
|
+
throw new MaterializeError(`Failed to set git remote: ${setUrl.stderr}`, "pull-failed");
|
|
184
|
+
}
|
|
185
|
+
const pull = await sh(sandbox, `git -C ${shellQuote(workdir)} pull --ff-only`);
|
|
186
|
+
if (pull.exitCode !== 0) {
|
|
187
|
+
throw classifyGitFailure(pull, "pull-failed");
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
} finally {
|
|
191
|
+
await scrubRemote(sandbox, workdir, repo, alreadyMaterialized);
|
|
192
|
+
}
|
|
193
|
+
reportProgress(onProgress, { phase: "finalizing", message: "Finalizing workspace\u2026" });
|
|
194
|
+
await storage.markMaterialized({ id: sandboxRow.id });
|
|
195
|
+
}
|
|
196
|
+
async function hasExistingCheckout(sandbox, workdir, repoFullName) {
|
|
197
|
+
const result = await sh(sandbox, `git -C ${shellQuote(workdir)} remote get-url origin`);
|
|
198
|
+
if (result.exitCode !== 0) return false;
|
|
199
|
+
const url = result.stdout.trim().toLowerCase();
|
|
200
|
+
const suffix = `github.com/${repoFullName.toLowerCase()}`;
|
|
201
|
+
return url.endsWith(`${suffix}.git`) || url.endsWith(suffix);
|
|
202
|
+
}
|
|
203
|
+
async function scrubRemote(sandbox, workdir, repoFullName, expectGitDir) {
|
|
204
|
+
const result = await sh(
|
|
205
|
+
sandbox,
|
|
206
|
+
`git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(cleanUrl(repoFullName))}`
|
|
207
|
+
);
|
|
208
|
+
if (result.exitCode !== 0 && expectGitDir) {
|
|
209
|
+
throw new MaterializeError(
|
|
210
|
+
`Failed to scrub installation token from git remote: ${result.stderr.trim() || result.stdout.trim()}`,
|
|
211
|
+
"pull-failed"
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
function classifyGitFailure(result, fallback) {
|
|
216
|
+
const stderr = result.stderr || "";
|
|
217
|
+
if (/could not resolve host|failed to connect|network is unreachable|Connection timed out/i.test(stderr)) {
|
|
218
|
+
return new MaterializeError(
|
|
219
|
+
"The sandbox could not reach github.com. The sandbox network must allow outbound egress to github.com.",
|
|
220
|
+
"egress-blocked"
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
const verb = fallback === "clone-failed" ? "clone" : fallback === "pull-failed" ? "pull" : "push";
|
|
224
|
+
return new MaterializeError(`git ${verb} failed: ${stderr}`, fallback);
|
|
225
|
+
}
|
|
226
|
+
function isValidGitRef(value) {
|
|
227
|
+
return typeof value === "string" && value.length > 0 && value.length <= 255 && // Reject leading-dash refs (e.g. `--mirror`) so the value can never be
|
|
228
|
+
// parsed as a git option when interpolated into a command.
|
|
229
|
+
!value.startsWith("-") && /^[A-Za-z0-9_./-]+$/.test(value);
|
|
230
|
+
}
|
|
231
|
+
function resolveGitIdentity(identity) {
|
|
232
|
+
const login = (identity.login || "").trim();
|
|
233
|
+
const name = (identity.name || "").trim() || login || "Mastra Code";
|
|
234
|
+
const email = (identity.email || "").trim() || (login ? `${login}@users.noreply.github.com` : "mastra-code@users.noreply.github.com");
|
|
235
|
+
return { name, email };
|
|
236
|
+
}
|
|
237
|
+
async function configureGitIdentity(sandbox, workdir, identity) {
|
|
238
|
+
const { name, email } = resolveGitIdentity(identity);
|
|
239
|
+
const setName = await sh(sandbox, `git -C ${shellQuote(workdir)} config user.name ${shellQuote(name)}`);
|
|
240
|
+
if (setName.exitCode !== 0) {
|
|
241
|
+
throw new MaterializeError(`Failed to set git user.name: ${setName.stderr.trim()}`, "commit-failed");
|
|
242
|
+
}
|
|
243
|
+
const setEmail = await sh(sandbox, `git -C ${shellQuote(workdir)} config user.email ${shellQuote(email)}`);
|
|
244
|
+
if (setEmail.exitCode !== 0) {
|
|
245
|
+
throw new MaterializeError(`Failed to set git user.email: ${setEmail.stderr.trim()}`, "commit-failed");
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
async function withInstallToken(sandbox, workdir, repoFullName, token, fn) {
|
|
249
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(repoFullName)) {
|
|
250
|
+
throw new MaterializeError(`Refusing to push: invalid repo full name '${repoFullName}'.`, "push-failed");
|
|
251
|
+
}
|
|
252
|
+
const setUrl = await sh(
|
|
253
|
+
sandbox,
|
|
254
|
+
`git -C ${shellQuote(workdir)} remote set-url origin ${shellQuote(tokenUrl(repoFullName, token))}`
|
|
255
|
+
);
|
|
256
|
+
if (setUrl.exitCode !== 0) {
|
|
257
|
+
await scrubRemote(sandbox, workdir, repoFullName, false);
|
|
258
|
+
throw new MaterializeError(`Failed to set git remote: ${setUrl.stderr.trim()}`, "push-failed");
|
|
259
|
+
}
|
|
260
|
+
try {
|
|
261
|
+
return await fn();
|
|
262
|
+
} finally {
|
|
263
|
+
await scrubRemote(sandbox, workdir, repoFullName, true);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
async function pushBranch(sandbox, workdir, branch, token, repoFullName) {
|
|
267
|
+
if (!isValidGitRef(branch)) {
|
|
268
|
+
throw new MaterializeError(`Refusing to push: invalid branch name '${branch}'.`, "push-failed");
|
|
269
|
+
}
|
|
270
|
+
await withInstallToken(sandbox, workdir, repoFullName, token, async () => {
|
|
271
|
+
const push = await sh(sandbox, `git -C ${shellQuote(workdir)} push -u origin ${shellQuote(branch)}`);
|
|
272
|
+
if (push.exitCode !== 0) {
|
|
273
|
+
throw classifyGitFailure(push, "push-failed");
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
async function commitAll(sandbox, workdir, message, identity) {
|
|
278
|
+
await configureGitIdentity(sandbox, workdir, identity);
|
|
279
|
+
const add = await sh(sandbox, `git -C ${shellQuote(workdir)} add -A`);
|
|
280
|
+
if (add.exitCode !== 0) {
|
|
281
|
+
throw new MaterializeError(`git add failed: ${add.stderr.trim() || add.stdout.trim()}`, "commit-failed");
|
|
282
|
+
}
|
|
283
|
+
const staged = await sh(sandbox, `git -C ${shellQuote(workdir)} diff --cached --quiet`);
|
|
284
|
+
if (staged.exitCode === 0) {
|
|
285
|
+
return { committed: false };
|
|
286
|
+
}
|
|
287
|
+
const commit = await sh(sandbox, `git -C ${shellQuote(workdir)} commit -m ${shellQuote(message)}`);
|
|
288
|
+
if (commit.exitCode !== 0) {
|
|
289
|
+
throw new MaterializeError(`git commit failed: ${commit.stderr.trim() || commit.stdout.trim()}`, "commit-failed");
|
|
290
|
+
}
|
|
291
|
+
return { committed: true };
|
|
292
|
+
}
|
|
293
|
+
var WorktreeError = class extends Error {
|
|
294
|
+
constructor(message, code) {
|
|
295
|
+
super(message);
|
|
296
|
+
this.code = code;
|
|
297
|
+
this.name = "WorktreeError";
|
|
298
|
+
}
|
|
299
|
+
code;
|
|
300
|
+
};
|
|
301
|
+
function safeBranchDir(branch) {
|
|
302
|
+
const sanitized = branch.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/\/+/g, "-").replace(/^[-.]+|[-.]+$/g, "").slice(0, 100) || "work";
|
|
303
|
+
if (sanitized === branch) return sanitized;
|
|
304
|
+
const hash = createHash2("sha256").update(branch).digest("hex").slice(0, 8);
|
|
305
|
+
return `${sanitized}-${hash}`;
|
|
306
|
+
}
|
|
307
|
+
function computeWorktreePath(repoWorkdir, branch) {
|
|
308
|
+
const parent = repoWorkdir.replace(/\/+$/, "").split("/").slice(0, -1).join("/") || "";
|
|
309
|
+
return `${parent}/worktrees/${safeBranchDir(branch)}`;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// src/integrations/github/subscriptions.ts
|
|
313
|
+
function changeRequestTargetKey(input) {
|
|
314
|
+
return `change-request:${input.installationExternalId}:${input.repositoryExternalId}:${input.changeRequestId}`;
|
|
315
|
+
}
|
|
316
|
+
function sameSession(row, input) {
|
|
317
|
+
return row.orgId === input.orgId && row.sessionId === input.sessionId && row.resourceId === input.resourceId && row.threadId === input.threadId && (row.sessionScope ?? "") === (input.sessionScope ?? "");
|
|
318
|
+
}
|
|
319
|
+
async function subscribeToPullRequest(input, storage) {
|
|
320
|
+
const targetKey = changeRequestTargetKey(input);
|
|
321
|
+
const existing = (await storage.subscriptions.listByTarget(targetKey)).find((row) => sameSession(row, input));
|
|
322
|
+
if (existing) {
|
|
323
|
+
if (existing.status !== "open") await storage.subscriptions.updateStatus(existing.id, "open");
|
|
324
|
+
return { ...existing, status: "open" };
|
|
325
|
+
}
|
|
326
|
+
return storage.subscriptions.create({
|
|
327
|
+
orgId: input.orgId,
|
|
328
|
+
targetKey,
|
|
329
|
+
sessionId: input.sessionId,
|
|
330
|
+
resourceId: input.resourceId,
|
|
331
|
+
threadId: input.threadId,
|
|
332
|
+
sessionScope: input.sessionScope ?? "",
|
|
333
|
+
status: "open",
|
|
334
|
+
data: {
|
|
335
|
+
installationExternalId: input.installationExternalId,
|
|
336
|
+
projectRepositoryId: input.projectRepositoryId,
|
|
337
|
+
repositoryExternalId: input.repositoryExternalId,
|
|
338
|
+
repositorySlug: input.repositorySlug,
|
|
339
|
+
changeRequestId: input.changeRequestId,
|
|
340
|
+
ownerId: input.ownerId,
|
|
341
|
+
source: input.source,
|
|
342
|
+
subscribedByUserId: input.subscribedByUserId ?? null
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
async function listPullRequestSubscriptionsForThread(input, storage) {
|
|
347
|
+
const rows = await storage.subscriptions.listByThread(input.resourceId, input.threadId);
|
|
348
|
+
return rows.filter(
|
|
349
|
+
(row) => row.orgId === input.orgId && row.resourceId === input.resourceId && row.threadId === input.threadId && (row.sessionScope ?? "") === (input.sessionScope ?? "")
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
async function listPullRequestSubscriptionsForWebhook(input, options, storage) {
|
|
353
|
+
const rows = await storage.subscriptions.listByTarget(changeRequestTargetKey(input));
|
|
354
|
+
return options?.includeTerminal ? rows : rows.filter((row) => row.status === "open");
|
|
355
|
+
}
|
|
356
|
+
function retirePullRequestSubscription(id, status, storage) {
|
|
357
|
+
return storage.subscriptions.updateStatus(id, status);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// src/integrations/github/webhook.ts
|
|
361
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
362
|
+
var SUPPORTED_GITHUB_WEBHOOK_EVENTS = /* @__PURE__ */ new Set([
|
|
363
|
+
"issues",
|
|
364
|
+
"issue_comment",
|
|
365
|
+
"pull_request",
|
|
366
|
+
"pull_request_review",
|
|
367
|
+
"pull_request_review_comment"
|
|
368
|
+
]);
|
|
369
|
+
function normalizeHeader(value) {
|
|
370
|
+
if (!value) return null;
|
|
371
|
+
const trimmed = value.trim();
|
|
372
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
373
|
+
}
|
|
374
|
+
function verifySignature(rawBody, signature, secret) {
|
|
375
|
+
if (!signature.startsWith("sha256=")) return false;
|
|
376
|
+
const signatureHex = signature.slice("sha256=".length);
|
|
377
|
+
if (!/^[a-fA-F0-9]{64}$/.test(signatureHex)) return false;
|
|
378
|
+
const expectedHex = createHmac("sha256", secret).update(rawBody).digest("hex");
|
|
379
|
+
const received = Buffer.from(signatureHex, "hex");
|
|
380
|
+
const expected = Buffer.from(expectedHex, "hex");
|
|
381
|
+
return received.length === expected.length && timingSafeEqual(received, expected);
|
|
382
|
+
}
|
|
383
|
+
async function parseGithubWebhook(c, secret) {
|
|
384
|
+
if (!secret) {
|
|
385
|
+
return { status: 401, body: { error: "unauthorized", message: "GitHub webhook secret is not configured" } };
|
|
386
|
+
}
|
|
387
|
+
const event = normalizeHeader(c.req.header("x-github-event"));
|
|
388
|
+
const deliveryId = normalizeHeader(c.req.header("x-github-delivery"));
|
|
389
|
+
const signature = normalizeHeader(c.req.header("x-hub-signature-256"));
|
|
390
|
+
if (!event) return { status: 400, body: { error: "bad_request", message: "Missing x-github-event header" } };
|
|
391
|
+
if (!deliveryId) return { status: 400, body: { error: "bad_request", message: "Missing x-github-delivery header" } };
|
|
392
|
+
if (!signature)
|
|
393
|
+
return { status: 401, body: { error: "unauthorized", message: "Missing x-hub-signature-256 header" } };
|
|
394
|
+
const rawBody = await c.req.text();
|
|
395
|
+
if (!verifySignature(rawBody, signature, secret)) {
|
|
396
|
+
return { status: 401, body: { error: "unauthorized", message: "Invalid GitHub webhook signature" } };
|
|
397
|
+
}
|
|
398
|
+
let payload;
|
|
399
|
+
try {
|
|
400
|
+
payload = JSON.parse(rawBody);
|
|
401
|
+
} catch {
|
|
402
|
+
return { status: 400, body: { error: "bad_request", message: "Malformed JSON payload" } };
|
|
403
|
+
}
|
|
404
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
405
|
+
return { status: 400, body: { error: "bad_request", message: "Payload must be a JSON object" } };
|
|
406
|
+
}
|
|
407
|
+
return { event, deliveryId, payload };
|
|
408
|
+
}
|
|
409
|
+
function getObject(value) {
|
|
410
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
411
|
+
}
|
|
412
|
+
function getString(value) {
|
|
413
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
414
|
+
}
|
|
415
|
+
function getNumber(value) {
|
|
416
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
417
|
+
}
|
|
418
|
+
function getBoolean(value) {
|
|
419
|
+
return typeof value === "boolean" ? value : void 0;
|
|
420
|
+
}
|
|
421
|
+
function getLabels(value) {
|
|
422
|
+
if (!Array.isArray(value)) return [];
|
|
423
|
+
return value.map((label) => typeof label === "string" ? label : getString(getObject(label)?.name)).filter((label) => Boolean(label));
|
|
424
|
+
}
|
|
425
|
+
function getIssueTriageRunInput(parsed) {
|
|
426
|
+
if (parsed.event !== "issues" || getString(parsed.payload.action) !== "opened") return null;
|
|
427
|
+
const repository = getString(getObject(parsed.payload.repository)?.full_name);
|
|
428
|
+
const issue = getObject(parsed.payload.issue);
|
|
429
|
+
const sender = getString(getObject(parsed.payload.sender)?.login);
|
|
430
|
+
const installationId = getNumber(getObject(parsed.payload.installation)?.id);
|
|
431
|
+
const issueNumber = getNumber(issue?.number);
|
|
432
|
+
const issueTitle = getString(issue?.title);
|
|
433
|
+
const issueUrl = getString(issue?.html_url);
|
|
434
|
+
if (!repository || !installationId || !issueNumber || !issueTitle || !issueUrl) return null;
|
|
435
|
+
return {
|
|
436
|
+
repository,
|
|
437
|
+
issueNumber,
|
|
438
|
+
issueTitle,
|
|
439
|
+
issueUrl,
|
|
440
|
+
labels: getLabels(issue?.labels),
|
|
441
|
+
sender,
|
|
442
|
+
installationId
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
function normalizeGithubWebhookMetadata(parsed) {
|
|
446
|
+
const { event, deliveryId, payload } = parsed;
|
|
447
|
+
const repository = getObject(payload.repository);
|
|
448
|
+
const issue = getObject(payload.issue);
|
|
449
|
+
const pullRequest = getObject(payload.pull_request);
|
|
450
|
+
const sender = getObject(payload.sender);
|
|
451
|
+
const installation = getObject(payload.installation);
|
|
452
|
+
const issuePullRequest = getObject(issue?.pull_request);
|
|
453
|
+
return {
|
|
454
|
+
event,
|
|
455
|
+
action: getString(payload.action),
|
|
456
|
+
deliveryId,
|
|
457
|
+
repository: getString(repository?.full_name),
|
|
458
|
+
repositoryId: getNumber(repository?.id),
|
|
459
|
+
issueNumber: getNumber(issue?.number),
|
|
460
|
+
pullRequestNumber: getNumber(pullRequest?.number) ?? (event === "issue_comment" && issuePullRequest ? getNumber(issue?.number) : void 0),
|
|
461
|
+
sender: getString(sender?.login),
|
|
462
|
+
senderType: getString(sender?.type),
|
|
463
|
+
installationId: getNumber(installation?.id)
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
function notificationSummary(metadata, label) {
|
|
467
|
+
const actor = metadata.sender ? `${metadata.sender} ` : "";
|
|
468
|
+
return `${actor}${label} on ${metadata.repository}#${metadata.pullRequestNumber}`;
|
|
469
|
+
}
|
|
470
|
+
function notificationTargetUrl(event, payload) {
|
|
471
|
+
if (event === "issue_comment" || event === "pull_request_review_comment") {
|
|
472
|
+
return getString(getObject(payload.comment)?.html_url);
|
|
473
|
+
}
|
|
474
|
+
if (event === "pull_request_review") {
|
|
475
|
+
return getString(getObject(payload.review)?.html_url);
|
|
476
|
+
}
|
|
477
|
+
return getString(getObject(payload.pull_request)?.html_url);
|
|
478
|
+
}
|
|
479
|
+
function classifyGithubWebhook(parsed) {
|
|
480
|
+
const metadata = normalizeGithubWebhookMetadata(parsed);
|
|
481
|
+
const { event, payload } = parsed;
|
|
482
|
+
const action = metadata.action;
|
|
483
|
+
if (!action || !metadata.repositoryId || !metadata.installationId || !metadata.pullRequestNumber || !metadata.repository) {
|
|
484
|
+
return void 0;
|
|
485
|
+
}
|
|
486
|
+
let priority;
|
|
487
|
+
let kind;
|
|
488
|
+
let label;
|
|
489
|
+
let terminal = false;
|
|
490
|
+
if (event === "pull_request_review" && action === "submitted") {
|
|
491
|
+
const state = getString(getObject(payload.review)?.state)?.toLowerCase().replaceAll("_", "-");
|
|
492
|
+
priority = state === "approved" || state === "changes-requested" ? "urgent" : "high";
|
|
493
|
+
kind = state === "approved" ? "review-approved" : state === "changes-requested" ? "review-changes-requested" : "review-submitted";
|
|
494
|
+
label = state === "approved" ? "approved the pull request" : state === "changes-requested" ? "requested changes" : "submitted a review";
|
|
495
|
+
} else if (event === "pull_request" && action === "closed") {
|
|
496
|
+
const merged = getBoolean(getObject(payload.pull_request)?.merged) === true;
|
|
497
|
+
priority = "urgent";
|
|
498
|
+
kind = merged ? "pull-request-merged" : "pull-request-closed";
|
|
499
|
+
label = merged ? "merged the pull request" : "closed the pull request";
|
|
500
|
+
terminal = true;
|
|
501
|
+
} else if (event === "issue_comment" && action === "created") {
|
|
502
|
+
priority = "high";
|
|
503
|
+
kind = "issue-comment-created";
|
|
504
|
+
label = "commented";
|
|
505
|
+
} else if (event === "pull_request_review_comment" && action === "created") {
|
|
506
|
+
priority = "high";
|
|
507
|
+
kind = "review-comment-created";
|
|
508
|
+
label = "left a review comment";
|
|
509
|
+
} else if (event === "pull_request" && action === "reopened") {
|
|
510
|
+
priority = "high";
|
|
511
|
+
kind = "pull-request-reopened";
|
|
512
|
+
label = "reopened the pull request";
|
|
513
|
+
} else if (event === "pull_request_review" && action === "dismissed") {
|
|
514
|
+
priority = "high";
|
|
515
|
+
kind = "review-dismissed";
|
|
516
|
+
label = "dismissed a review";
|
|
517
|
+
} else if (event === "pull_request" && [
|
|
518
|
+
"synchronize",
|
|
519
|
+
"ready_for_review",
|
|
520
|
+
"converted_to_draft",
|
|
521
|
+
"assigned",
|
|
522
|
+
"unassigned",
|
|
523
|
+
"review_requested",
|
|
524
|
+
"review_request_removed"
|
|
525
|
+
].includes(action)) {
|
|
526
|
+
priority = "medium";
|
|
527
|
+
kind = `pull-request-${action.replaceAll("_", "-")}`;
|
|
528
|
+
label = action.replaceAll("_", " ");
|
|
529
|
+
} else if (event === "pull_request" && ["edited", "labeled", "unlabeled", "milestoned", "demilestoned"].includes(action)) {
|
|
530
|
+
priority = "low";
|
|
531
|
+
kind = `pull-request-${action.replaceAll("_", "-")}`;
|
|
532
|
+
label = action.replaceAll("_", " ");
|
|
533
|
+
} else {
|
|
534
|
+
return void 0;
|
|
535
|
+
}
|
|
536
|
+
return {
|
|
537
|
+
action,
|
|
538
|
+
kind,
|
|
539
|
+
priority,
|
|
540
|
+
summary: notificationSummary(metadata, label),
|
|
541
|
+
terminal,
|
|
542
|
+
metadata: {
|
|
543
|
+
...metadata,
|
|
544
|
+
pullRequestNumber: metadata.pullRequestNumber,
|
|
545
|
+
repositoryId: metadata.repositoryId,
|
|
546
|
+
installationId: metadata.installationId
|
|
547
|
+
},
|
|
548
|
+
payload
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
async function resolveSubscriptionSession(controller, subscription) {
|
|
552
|
+
const { sessionId, resourceId, threadId } = subscription;
|
|
553
|
+
if (!sessionId || !resourceId || !threadId) {
|
|
554
|
+
throw new Error(`GitHub subscription ${subscription.id} is missing its session binding.`);
|
|
555
|
+
}
|
|
556
|
+
const scope = subscription.sessionScope || void 0;
|
|
557
|
+
let session = await controller.getSessionByResource(resourceId, scope);
|
|
558
|
+
if (!session) {
|
|
559
|
+
const tags = {
|
|
560
|
+
factoryProjectId: resourceId,
|
|
561
|
+
projectRepositoryId: subscription.data.projectRepositoryId,
|
|
562
|
+
...scope ? { worktreePath: scope } : {}
|
|
563
|
+
};
|
|
564
|
+
session = await controller.createSession({
|
|
565
|
+
id: sessionId,
|
|
566
|
+
ownerId: subscription.data.ownerId,
|
|
567
|
+
resourceId,
|
|
568
|
+
scope,
|
|
569
|
+
tags
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
if (session.thread.getId() !== threadId) {
|
|
573
|
+
await session.thread.switch({ threadId, emitEvent: false });
|
|
574
|
+
}
|
|
575
|
+
if (session.thread.getId() !== threadId) {
|
|
576
|
+
throw new Error(`Session ${sessionId} did not bind thread ${threadId}.`);
|
|
577
|
+
}
|
|
578
|
+
return session;
|
|
579
|
+
}
|
|
580
|
+
var AUTHORIZED_BOTS = /* @__PURE__ */ new Set(["coderabbitai[bot]", "devin-ai-integration[bot]"]);
|
|
581
|
+
var AUTHORIZED_PERMISSIONS = /* @__PURE__ */ new Set(["admin", "maintain", "write"]);
|
|
582
|
+
var PERMISSION_CHECK_TIMEOUT_MS = 5e3;
|
|
583
|
+
var AUTHOR_GATED_KINDS = /* @__PURE__ */ new Set([
|
|
584
|
+
"issue-comment-created",
|
|
585
|
+
"review-comment-created",
|
|
586
|
+
"review-submitted",
|
|
587
|
+
"review-approved",
|
|
588
|
+
"review-changes-requested",
|
|
589
|
+
"review-dismissed"
|
|
590
|
+
]);
|
|
591
|
+
async function isAuthorizedGithubSender(notification, github) {
|
|
592
|
+
if (!AUTHOR_GATED_KINDS.has(notification.kind)) return true;
|
|
593
|
+
const sender = notification.metadata.sender;
|
|
594
|
+
const repository = notification.metadata.repository;
|
|
595
|
+
if (!sender || !repository) return false;
|
|
596
|
+
const normalizedSender = sender.toLowerCase();
|
|
597
|
+
if (notification.metadata.senderType?.toLowerCase() === "bot" || normalizedSender.endsWith("[bot]")) {
|
|
598
|
+
return AUTHORIZED_BOTS.has(normalizedSender);
|
|
599
|
+
}
|
|
600
|
+
if (!github) return false;
|
|
601
|
+
const abortController = new AbortController();
|
|
602
|
+
let timeout;
|
|
603
|
+
try {
|
|
604
|
+
const permission = await Promise.race([
|
|
605
|
+
github.getRepositoryCollaboratorPermission(
|
|
606
|
+
notification.metadata.installationId,
|
|
607
|
+
repository,
|
|
608
|
+
sender,
|
|
609
|
+
abortController.signal
|
|
610
|
+
),
|
|
611
|
+
new Promise((resolve) => {
|
|
612
|
+
timeout = setTimeout(() => {
|
|
613
|
+
abortController.abort();
|
|
614
|
+
resolve(void 0);
|
|
615
|
+
}, PERMISSION_CHECK_TIMEOUT_MS);
|
|
616
|
+
})
|
|
617
|
+
]);
|
|
618
|
+
return permission !== void 0 && AUTHORIZED_PERMISSIONS.has(permission);
|
|
619
|
+
} catch {
|
|
620
|
+
return false;
|
|
621
|
+
} finally {
|
|
622
|
+
if (timeout) clearTimeout(timeout);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
async function dispatchGithubWebhook(parsed, dependencies) {
|
|
626
|
+
const notification = classifyGithubWebhook(parsed);
|
|
627
|
+
if (!notification) return { delivered: 0, failed: 0, ignored: true };
|
|
628
|
+
const isAuthorizedSender = dependencies.isAuthorizedSender ?? ((n) => isAuthorizedGithubSender(n, dependencies.github));
|
|
629
|
+
if (!await isAuthorizedSender(notification)) {
|
|
630
|
+
return { delivered: 0, failed: 0, ignored: true };
|
|
631
|
+
}
|
|
632
|
+
const target = {
|
|
633
|
+
installationExternalId: notification.metadata.installationId.toString(),
|
|
634
|
+
repositoryExternalId: notification.metadata.repositoryId.toString(),
|
|
635
|
+
changeRequestId: notification.metadata.pullRequestNumber.toString()
|
|
636
|
+
};
|
|
637
|
+
const listSubscriptions = dependencies.listSubscriptions ?? ((subscriptionTarget, options) => {
|
|
638
|
+
if (!dependencies.github) throw new Error("GitHub integration is required to load webhook subscriptions.");
|
|
639
|
+
return listPullRequestSubscriptionsForWebhook(
|
|
640
|
+
subscriptionTarget,
|
|
641
|
+
options,
|
|
642
|
+
dependencies.github.integrationStorage
|
|
643
|
+
);
|
|
644
|
+
});
|
|
645
|
+
const retireSubscription = dependencies.retireSubscription ?? ((id, status) => {
|
|
646
|
+
if (!dependencies.github) throw new Error("GitHub integration is required to retire webhook subscriptions.");
|
|
647
|
+
return retirePullRequestSubscription(id, status, dependencies.github.integrationStorage);
|
|
648
|
+
});
|
|
649
|
+
const subscriptions = await listSubscriptions(target, { includeTerminal: notification.action === "reopened" });
|
|
650
|
+
let delivered = 0;
|
|
651
|
+
let failed = 0;
|
|
652
|
+
for (const subscription of subscriptions) {
|
|
653
|
+
try {
|
|
654
|
+
const session = await resolveSubscriptionSession(dependencies.controller, subscription);
|
|
655
|
+
const result = await session.sendNotificationSignal({
|
|
656
|
+
source: "github",
|
|
657
|
+
kind: notification.kind,
|
|
658
|
+
summary: notification.summary,
|
|
659
|
+
priority: notification.priority,
|
|
660
|
+
payload: notification.payload,
|
|
661
|
+
sourceId: parsed.deliveryId,
|
|
662
|
+
dedupeKey: `${parsed.deliveryId}:${subscription.sessionId}:${subscription.threadId}`,
|
|
663
|
+
coalesceKey: `github:${subscription.data.repositoryExternalId}:pull-request:${subscription.data.changeRequestId}`,
|
|
664
|
+
metadata: {
|
|
665
|
+
event: notification.metadata.event,
|
|
666
|
+
action: notification.action,
|
|
667
|
+
repository: notification.metadata.repository,
|
|
668
|
+
issueNumber: notification.metadata.issueNumber,
|
|
669
|
+
pullRequestNumber: notification.metadata.pullRequestNumber,
|
|
670
|
+
targetUrl: notificationTargetUrl(parsed.event, parsed.payload),
|
|
671
|
+
deliveryId: parsed.deliveryId
|
|
672
|
+
}
|
|
673
|
+
});
|
|
674
|
+
await Promise.all([result.persisted, result.accepted].filter(Boolean));
|
|
675
|
+
if (notification.terminal) {
|
|
676
|
+
await retireSubscription(subscription.id, notification.kind === "pull-request-merged" ? "merged" : "closed");
|
|
677
|
+
} else if (notification.action === "reopened") {
|
|
678
|
+
await retireSubscription(subscription.id, "open");
|
|
679
|
+
}
|
|
680
|
+
delivered += 1;
|
|
681
|
+
} catch (error) {
|
|
682
|
+
failed += 1;
|
|
683
|
+
dependencies.onTargetError?.(subscription, error);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
return { delivered, failed, ignored: false };
|
|
687
|
+
}
|
|
688
|
+
async function handleGithubWebhook(c, options) {
|
|
689
|
+
const parsed = await parseGithubWebhook(c, options.github.webhookSecret);
|
|
690
|
+
if ("status" in parsed) return parsed;
|
|
691
|
+
if (!SUPPORTED_GITHUB_WEBHOOK_EVENTS.has(parsed.event)) {
|
|
692
|
+
return { status: 202, body: { ok: true, ignored: true } };
|
|
693
|
+
}
|
|
694
|
+
const metadata = normalizeGithubWebhookMetadata(parsed);
|
|
695
|
+
console.info("[GitHub Webhook]", metadata);
|
|
696
|
+
if (options.ingestFactoryEvent) {
|
|
697
|
+
await options.ingestFactoryEvent(parsed);
|
|
698
|
+
} else {
|
|
699
|
+
const issueTriageRun = getIssueTriageRunInput(parsed);
|
|
700
|
+
if (issueTriageRun && options.runIssueTriage) {
|
|
701
|
+
void options.runIssueTriage(issueTriageRun).catch((error) => {
|
|
702
|
+
console.error("[GitHub Webhook] Failed to run issue triage", {
|
|
703
|
+
deliveryId: metadata.deliveryId,
|
|
704
|
+
repository: metadata.repository,
|
|
705
|
+
issueNumber: metadata.issueNumber,
|
|
706
|
+
error: error instanceof Error ? error.message : String(error)
|
|
707
|
+
});
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
if (!options.controller) {
|
|
712
|
+
return { status: 202, body: { ok: true } };
|
|
713
|
+
}
|
|
714
|
+
const result = await dispatchGithubWebhook(parsed, options);
|
|
715
|
+
if (result.failed > 0) {
|
|
716
|
+
console.warn(`[GitHub Webhook] ${result.failed} subscribed target(s) failed for delivery ${parsed.deliveryId}.`);
|
|
717
|
+
}
|
|
718
|
+
return { status: 202, body: { ok: true, ...result.ignored ? { ignored: true } : {} } };
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
// src/integrations/github/routes.ts
|
|
722
|
+
function loose(c) {
|
|
723
|
+
return c;
|
|
724
|
+
}
|
|
725
|
+
async function resolveFactoryDefaultModelId(projects, factoryProjectId) {
|
|
726
|
+
if (!projects || !factoryProjectId) return void 0;
|
|
727
|
+
try {
|
|
728
|
+
const project = await projects.getById({ id: factoryProjectId });
|
|
729
|
+
return project?.defaultModelId ?? void 0;
|
|
730
|
+
} catch {
|
|
731
|
+
return void 0;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
function pullRequestNumberFromUrl(value, expectedRepo) {
|
|
735
|
+
try {
|
|
736
|
+
const url = new URL(value);
|
|
737
|
+
const match = url.pathname.match(/^\/([^/]+\/[^/]+)\/pull\/(\d+)\/?$/);
|
|
738
|
+
if (url.protocol !== "https:" || url.hostname !== "github.com" || match?.[1]?.toLowerCase() !== expectedRepo.toLowerCase()) {
|
|
739
|
+
return void 0;
|
|
740
|
+
}
|
|
741
|
+
const number = Number(match[2]);
|
|
742
|
+
return Number.isInteger(number) && number > 0 ? number : void 0;
|
|
743
|
+
} catch {
|
|
744
|
+
return void 0;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
function isCanonicalGithubIssueUrl(value, repoFullName, issueNumber) {
|
|
748
|
+
try {
|
|
749
|
+
const url = new URL(value);
|
|
750
|
+
const [owner, repo] = repoFullName.split("/");
|
|
751
|
+
return url.protocol === "https:" && url.hostname === "github.com" && url.pathname === `/${owner}/${repo}/issues/${issueNumber}` && url.search === "" && url.hash === "";
|
|
752
|
+
} catch {
|
|
753
|
+
return false;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
function isValidGitRef2(value) {
|
|
757
|
+
return typeof value === "string" && value.length > 0 && value.length <= 255 && /^[A-Za-z0-9_./-]+$/.test(value);
|
|
758
|
+
}
|
|
759
|
+
async function resolveOrgTenant(c, auth) {
|
|
760
|
+
await auth.ensureUser(c);
|
|
761
|
+
const tenant = auth.tenant(c);
|
|
762
|
+
if (!tenant) return { response: c.json({ error: "unauthorized" }, 401) };
|
|
763
|
+
if (!tenant.orgId) {
|
|
764
|
+
return {
|
|
765
|
+
response: c.json(
|
|
766
|
+
{
|
|
767
|
+
error: "organization_required",
|
|
768
|
+
message: "GitHub projects require a WorkOS organization. Personal accounts cannot connect repositories."
|
|
769
|
+
},
|
|
770
|
+
403
|
|
771
|
+
)
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };
|
|
775
|
+
}
|
|
776
|
+
function parseListPage(raw) {
|
|
777
|
+
if (raw === void 0) return 1;
|
|
778
|
+
if (!/^\d{1,5}$/.test(raw)) return null;
|
|
779
|
+
const page = Number(raw);
|
|
780
|
+
return page >= 1 ? page : null;
|
|
781
|
+
}
|
|
782
|
+
var VALID_ISSUE_LABEL_FILTERS = /* @__PURE__ */ new Set(["auto-triaged", "needs-approval"]);
|
|
783
|
+
function parseIssueLabelFilter(raw) {
|
|
784
|
+
if (raw === void 0 || raw === "") return void 0;
|
|
785
|
+
if (VALID_ISSUE_LABEL_FILTERS.has(raw)) return raw;
|
|
786
|
+
return null;
|
|
787
|
+
}
|
|
788
|
+
function parseIssueNumberParam(raw) {
|
|
789
|
+
if (!raw || !/^\d{1,10}$/.test(raw)) return null;
|
|
790
|
+
const issueNumber = Number(raw);
|
|
791
|
+
return Number.isSafeInteger(issueNumber) && issueNumber > 0 ? issueNumber : null;
|
|
792
|
+
}
|
|
793
|
+
function parseStringList(value) {
|
|
794
|
+
if (!Array.isArray(value)) return [];
|
|
795
|
+
return value.filter((item) => typeof item === "string" && item.length > 0);
|
|
796
|
+
}
|
|
797
|
+
async function resolveProjectRepository(args) {
|
|
798
|
+
const projectRepository = await args.github.sourceControlStorage.projectRepositories.get({
|
|
799
|
+
orgId: args.orgId,
|
|
800
|
+
id: args.projectRepositoryId
|
|
801
|
+
});
|
|
802
|
+
if (!projectRepository) return null;
|
|
803
|
+
const connection = await args.github.sourceControlStorage.connections.get({
|
|
804
|
+
orgId: args.orgId,
|
|
805
|
+
id: projectRepository.connectionId
|
|
806
|
+
});
|
|
807
|
+
if (!connection) return null;
|
|
808
|
+
const repository = await args.github.sourceControlStorage.repositories.get({
|
|
809
|
+
orgId: args.orgId,
|
|
810
|
+
id: projectRepository.repositoryId
|
|
811
|
+
});
|
|
812
|
+
if (!repository) return null;
|
|
813
|
+
const installation = await args.github.sourceControlStorage.installations.get({
|
|
814
|
+
orgId: args.orgId,
|
|
815
|
+
id: connection.installationId
|
|
816
|
+
});
|
|
817
|
+
if (!installation) return null;
|
|
818
|
+
return {
|
|
819
|
+
...projectRepository,
|
|
820
|
+
connection,
|
|
821
|
+
installation,
|
|
822
|
+
repository,
|
|
823
|
+
factoryProjectId: connection.factoryProjectId,
|
|
824
|
+
defaultBranch: projectRepository.branch ?? repository.defaultBranch
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
function polledIssueEvent(project, issue) {
|
|
828
|
+
const repositoryId = Number(project.repository.externalId);
|
|
829
|
+
return {
|
|
830
|
+
event: "issues",
|
|
831
|
+
deliveryId: `poll:${repositoryId}:issue:${issue.number}:${issue.createdAt}`,
|
|
832
|
+
payload: {
|
|
833
|
+
action: "opened",
|
|
834
|
+
installation: { id: Number(project.installation.externalId) },
|
|
835
|
+
repository: { id: repositoryId, full_name: project.repository.slug },
|
|
836
|
+
sender: { login: issue.author ?? "__unknown__" },
|
|
837
|
+
issue: {
|
|
838
|
+
number: issue.number,
|
|
839
|
+
title: issue.title,
|
|
840
|
+
html_url: issue.url,
|
|
841
|
+
labels: issue.labels.map((name) => ({ name }))
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
function polledPullRequestEvent(project, pullRequest) {
|
|
847
|
+
const repositoryId = Number(project.repository.externalId);
|
|
848
|
+
return {
|
|
849
|
+
event: "pull_request",
|
|
850
|
+
deliveryId: `poll:${repositoryId}:pull-request:${pullRequest.number}:${pullRequest.createdAt}`,
|
|
851
|
+
payload: {
|
|
852
|
+
action: "opened",
|
|
853
|
+
installation: { id: Number(project.installation.externalId) },
|
|
854
|
+
repository: { id: repositoryId, full_name: project.repository.slug },
|
|
855
|
+
sender: { login: pullRequest.author ?? "__unknown__" },
|
|
856
|
+
pull_request: {
|
|
857
|
+
number: pullRequest.number,
|
|
858
|
+
title: pullRequest.title,
|
|
859
|
+
html_url: pullRequest.url,
|
|
860
|
+
state: "open",
|
|
861
|
+
merged: false,
|
|
862
|
+
head: { ref: pullRequest.headBranch },
|
|
863
|
+
base: { ref: pullRequest.baseBranch }
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
async function ingestPolledEvents(events, ingestFactoryEvent) {
|
|
869
|
+
if (!ingestFactoryEvent) return;
|
|
870
|
+
const results = await Promise.allSettled(events.map((event) => ingestFactoryEvent(event)));
|
|
871
|
+
const rejected = results.find((result) => result.status === "rejected");
|
|
872
|
+
if (rejected) throw rejected.reason;
|
|
873
|
+
}
|
|
874
|
+
function buildGithubRoutes(options) {
|
|
875
|
+
const routes = [];
|
|
876
|
+
const { auth, fleet, storage, github, stateSigner, emitAudit } = options;
|
|
877
|
+
const diagnostics = () => getGithubFeatureDiagnostics({ github, auth, appDbConfigured: storage !== void 0, stateSigner, fleet });
|
|
878
|
+
routes.push(
|
|
879
|
+
registerApiRoute("/web/github/status", {
|
|
880
|
+
method: "GET",
|
|
881
|
+
requiresAuth: false,
|
|
882
|
+
handler: async (c) => {
|
|
883
|
+
if (!isGithubFeatureEnabled({ github, auth }) || !github || !stateSigner) {
|
|
884
|
+
return c.json({
|
|
885
|
+
enabled: false,
|
|
886
|
+
connected: false,
|
|
887
|
+
installations: [],
|
|
888
|
+
reason: "missing_config",
|
|
889
|
+
diagnostics: diagnostics()
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
await auth.ensureUser(loose(c));
|
|
893
|
+
const tenant = auth.tenant(loose(c));
|
|
894
|
+
if (!tenant) return c.json({ error: "unauthorized", reason: "auth_required" }, 401);
|
|
895
|
+
if (!tenant.orgId) {
|
|
896
|
+
return c.json({
|
|
897
|
+
enabled: true,
|
|
898
|
+
sandboxEnabled: fleet.enabled,
|
|
899
|
+
organizationRequired: true,
|
|
900
|
+
connected: false,
|
|
901
|
+
installations: [],
|
|
902
|
+
reason: "organization_required",
|
|
903
|
+
diagnostics: diagnostics()
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
const rows = options.github ? await options.github.sourceControlStorage.installations.list({ orgId: tenant.orgId }) : [];
|
|
907
|
+
const connected = rows.length > 0;
|
|
908
|
+
return c.json({
|
|
909
|
+
enabled: true,
|
|
910
|
+
sandboxEnabled: fleet.enabled,
|
|
911
|
+
connected,
|
|
912
|
+
installations: rows.map((r) => ({
|
|
913
|
+
installationId: Number(r.externalId),
|
|
914
|
+
accountLogin: r.accountName,
|
|
915
|
+
accountType: r.accountType
|
|
916
|
+
})),
|
|
917
|
+
reason: connected ? "ready" : "not_connected",
|
|
918
|
+
diagnostics: diagnostics()
|
|
919
|
+
});
|
|
920
|
+
}
|
|
921
|
+
})
|
|
922
|
+
);
|
|
923
|
+
if (!isGithubFeatureEnabled({ github, auth }) || !github || !stateSigner) {
|
|
924
|
+
return routes;
|
|
925
|
+
}
|
|
926
|
+
const signState = (orgId, userId) => stateSigner.sign(orgId, userId);
|
|
927
|
+
const verifyState = (state) => stateSigner.verify(state);
|
|
928
|
+
const { runIssueTriage } = options;
|
|
929
|
+
const runBoardIssueTriage = runIssueTriage ? async (input) => {
|
|
930
|
+
if (!input.resourceId || !input.projectPath) {
|
|
931
|
+
throw new Error("GitHub issue triage requires an explicit Factory project repository");
|
|
932
|
+
}
|
|
933
|
+
await github.addIssueLabels(input.installationId, input.repository, input.issueNumber, ["auto-triaged"]);
|
|
934
|
+
return runIssueTriage({
|
|
935
|
+
...input,
|
|
936
|
+
defaultModelId: input.defaultModelId ?? await resolveFactoryDefaultModelId(options.projects, input.resourceId),
|
|
937
|
+
labels: input.labels.includes("auto-triaged") ? input.labels : [...input.labels, "auto-triaged"]
|
|
938
|
+
});
|
|
939
|
+
} : void 0;
|
|
940
|
+
routes.push(
|
|
941
|
+
registerApiRoute("/web/github/subscriptions", {
|
|
942
|
+
method: "GET",
|
|
943
|
+
handler: async (c) => {
|
|
944
|
+
await auth.ensureUser(loose(c));
|
|
945
|
+
const tenant = auth.tenant(loose(c));
|
|
946
|
+
if (!tenant?.orgId) return c.json({ error: "unauthorized" }, 401);
|
|
947
|
+
const resourceId = c.req.query("resourceId");
|
|
948
|
+
const threadId = c.req.query("threadId");
|
|
949
|
+
const sessionScope = c.req.query("scope");
|
|
950
|
+
if (!resourceId || !threadId) return c.json({ error: "resourceId and threadId are required" }, 400);
|
|
951
|
+
const subscriptions = await listPullRequestSubscriptionsForThread(
|
|
952
|
+
{
|
|
953
|
+
orgId: tenant.orgId,
|
|
954
|
+
resourceId,
|
|
955
|
+
threadId,
|
|
956
|
+
sessionScope
|
|
957
|
+
},
|
|
958
|
+
github.integrationStorage
|
|
959
|
+
);
|
|
960
|
+
return c.json({
|
|
961
|
+
subscriptions: subscriptions.map((subscription) => ({
|
|
962
|
+
id: subscription.id,
|
|
963
|
+
repoFullName: subscription.data.repositorySlug,
|
|
964
|
+
pullRequestNumber: Number(subscription.data.changeRequestId),
|
|
965
|
+
status: subscription.status,
|
|
966
|
+
url: `https://github.com/${subscription.data.repositorySlug}/pull/${subscription.data.changeRequestId}`
|
|
967
|
+
}))
|
|
968
|
+
});
|
|
969
|
+
}
|
|
970
|
+
}),
|
|
971
|
+
registerApiRoute("/web/github/webhook", {
|
|
972
|
+
method: "POST",
|
|
973
|
+
requiresAuth: false,
|
|
974
|
+
handler: async (c) => {
|
|
975
|
+
const result = await handleGithubWebhook(loose(c), {
|
|
976
|
+
github,
|
|
977
|
+
runIssueTriage: runBoardIssueTriage,
|
|
978
|
+
ingestFactoryEvent: options.ingestFactoryEvent,
|
|
979
|
+
...options.controller ? {
|
|
980
|
+
controller: options.controller,
|
|
981
|
+
onTargetError: (subscription, error) => {
|
|
982
|
+
console.warn(
|
|
983
|
+
`[GitHub Webhook] Delivery failed for subscription ${subscription.id} (${subscription.resourceId}/${subscription.threadId}).`,
|
|
984
|
+
error
|
|
985
|
+
);
|
|
986
|
+
}
|
|
987
|
+
} : {}
|
|
988
|
+
});
|
|
989
|
+
return c.json(result.body, result.status);
|
|
990
|
+
}
|
|
991
|
+
})
|
|
992
|
+
);
|
|
993
|
+
const redirectUri = options.redirectUri ?? `${(options.baseUrl ?? "").replace(/\/$/, "")}/auth/github/callback`;
|
|
994
|
+
routes.push(
|
|
995
|
+
registerApiRoute("/auth/github/connect", {
|
|
996
|
+
method: "GET",
|
|
997
|
+
requiresAuth: false,
|
|
998
|
+
handler: async (c) => {
|
|
999
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
1000
|
+
if ("response" in resolved) return resolved.response;
|
|
1001
|
+
const state = signState(resolved.tenant.orgId, resolved.tenant.userId);
|
|
1002
|
+
if (c.req.query("manage")) return c.redirect(github.buildInstallUrl(state));
|
|
1003
|
+
return c.redirect(github.buildOAuthIdentifyUrl(state, redirectUri));
|
|
1004
|
+
}
|
|
1005
|
+
})
|
|
1006
|
+
);
|
|
1007
|
+
routes.push(
|
|
1008
|
+
registerApiRoute("/auth/github/callback", {
|
|
1009
|
+
method: "GET",
|
|
1010
|
+
requiresAuth: false,
|
|
1011
|
+
handler: async (c) => {
|
|
1012
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
1013
|
+
if ("response" in resolved) return resolved.response;
|
|
1014
|
+
const { orgId, userId } = resolved.tenant;
|
|
1015
|
+
const state = c.req.query("state");
|
|
1016
|
+
if (!state) {
|
|
1017
|
+
return c.redirect(github.buildOAuthIdentifyUrl(signState(orgId, userId), redirectUri));
|
|
1018
|
+
}
|
|
1019
|
+
const stateTenant = verifyState(state);
|
|
1020
|
+
if (!stateTenant || stateTenant.userId !== userId || stateTenant.orgId !== orgId) {
|
|
1021
|
+
console.warn(
|
|
1022
|
+
"[GitHub] Install callback rejected: state/tenant mismatch.",
|
|
1023
|
+
JSON.stringify({
|
|
1024
|
+
stateValid: Boolean(stateTenant),
|
|
1025
|
+
stateOrgId: stateTenant?.orgId,
|
|
1026
|
+
stateUserId: stateTenant?.userId,
|
|
1027
|
+
sessionOrgId: orgId,
|
|
1028
|
+
sessionUserId: userId
|
|
1029
|
+
})
|
|
1030
|
+
);
|
|
1031
|
+
return c.redirect("/?github=error");
|
|
1032
|
+
}
|
|
1033
|
+
const code = c.req.query("code");
|
|
1034
|
+
if (!code) {
|
|
1035
|
+
return c.redirect(github.buildOAuthIdentifyUrl(signState(orgId, userId), redirectUri));
|
|
1036
|
+
}
|
|
1037
|
+
try {
|
|
1038
|
+
const userToken = await github.exchangeOAuthCode(code, redirectUri);
|
|
1039
|
+
const installations = await github.listUserInstallations(userToken);
|
|
1040
|
+
if (installations.length === 0) {
|
|
1041
|
+
return c.redirect(github.buildInstallUrl(signState(orgId, userId)));
|
|
1042
|
+
}
|
|
1043
|
+
for (const inst of installations) {
|
|
1044
|
+
await github.sourceControlStorage.installations.upsert({
|
|
1045
|
+
orgId,
|
|
1046
|
+
connectedByUserId: userId,
|
|
1047
|
+
externalId: inst.installationId.toString(),
|
|
1048
|
+
accountName: inst.accountLogin,
|
|
1049
|
+
accountType: inst.accountType
|
|
1050
|
+
});
|
|
1051
|
+
}
|
|
1052
|
+
} catch (error) {
|
|
1053
|
+
console.warn(
|
|
1054
|
+
`[GitHub] Install callback failed to persist installations for org ${orgId} / user ${userId}.`,
|
|
1055
|
+
error
|
|
1056
|
+
);
|
|
1057
|
+
return c.redirect("/?github=error");
|
|
1058
|
+
}
|
|
1059
|
+
return c.redirect("/?github=connected");
|
|
1060
|
+
}
|
|
1061
|
+
})
|
|
1062
|
+
);
|
|
1063
|
+
routes.push(
|
|
1064
|
+
registerApiRoute("/web/github/repos", {
|
|
1065
|
+
method: "GET",
|
|
1066
|
+
requiresAuth: false,
|
|
1067
|
+
handler: async (c) => {
|
|
1068
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
1069
|
+
if ("response" in resolved) return resolved.response;
|
|
1070
|
+
const installs = await github.sourceControlStorage.installations.list({ orgId: resolved.tenant.orgId });
|
|
1071
|
+
const query = (c.req.query("q") ?? "").toLowerCase();
|
|
1072
|
+
const repos = [];
|
|
1073
|
+
const seenRepositoryIds = /* @__PURE__ */ new Set();
|
|
1074
|
+
for (const inst of installs) {
|
|
1075
|
+
let list;
|
|
1076
|
+
try {
|
|
1077
|
+
list = await github.listInstallationRepos(Number(inst.externalId));
|
|
1078
|
+
} catch (err) {
|
|
1079
|
+
if (err.status !== 404) throw err;
|
|
1080
|
+
console.error(`[MastraCode Web] pruning stale GitHub installation ${inst.externalId} (404 from GitHub)`);
|
|
1081
|
+
await github.sourceControlStorage.installations.delete({ orgId: resolved.tenant.orgId, id: inst.id });
|
|
1082
|
+
continue;
|
|
1083
|
+
}
|
|
1084
|
+
for (const repo of list) {
|
|
1085
|
+
if (query && !repo.fullName.toLowerCase().includes(query)) continue;
|
|
1086
|
+
if (seenRepositoryIds.has(repo.id)) continue;
|
|
1087
|
+
seenRepositoryIds.add(repo.id);
|
|
1088
|
+
const repository = await github.sourceControlStorage.repositories.upsert({
|
|
1089
|
+
orgId: resolved.tenant.orgId,
|
|
1090
|
+
input: {
|
|
1091
|
+
installationId: inst.id,
|
|
1092
|
+
externalId: repo.id.toString(),
|
|
1093
|
+
slug: repo.fullName,
|
|
1094
|
+
defaultBranch: isValidGitRef2(repo.defaultBranch) ? repo.defaultBranch : "main",
|
|
1095
|
+
providerMetadata: { private: repo.private, owner: repo.owner }
|
|
1096
|
+
}
|
|
1097
|
+
});
|
|
1098
|
+
repos.push({
|
|
1099
|
+
...repo,
|
|
1100
|
+
installationStorageId: inst.id,
|
|
1101
|
+
repositoryStorageId: repository.id,
|
|
1102
|
+
sandboxProvider: fleet.provider,
|
|
1103
|
+
sandboxWorkdir: fleet.computeWorkdir(repo.fullName)
|
|
1104
|
+
});
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
return c.json({ repos });
|
|
1108
|
+
}
|
|
1109
|
+
})
|
|
1110
|
+
);
|
|
1111
|
+
routes.push(
|
|
1112
|
+
registerApiRoute("/web/github/projects/:id/ensure", {
|
|
1113
|
+
method: "POST",
|
|
1114
|
+
requiresAuth: false,
|
|
1115
|
+
handler: async (c) => {
|
|
1116
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
1117
|
+
if ("response" in resolved) return resolved.response;
|
|
1118
|
+
const { orgId, userId } = resolved.tenant;
|
|
1119
|
+
if (!fleet.enabled) {
|
|
1120
|
+
return c.json({ error: "sandbox_not_configured", message: "No sandbox provider is configured." }, 503);
|
|
1121
|
+
}
|
|
1122
|
+
const projectRepositoryId = c.req.param("id");
|
|
1123
|
+
if (!projectRepositoryId) return c.json({ error: "Project repository not found" }, 404);
|
|
1124
|
+
const project = await resolveProjectRepository({ github, orgId, projectRepositoryId });
|
|
1125
|
+
if (!project) {
|
|
1126
|
+
return c.json({ error: "Project repository not found" }, 404);
|
|
1127
|
+
}
|
|
1128
|
+
const wantsStream = (c.req.header("accept") ?? "").includes("text/event-stream");
|
|
1129
|
+
if (wantsStream) {
|
|
1130
|
+
return streamSSE(loose(c), async (stream) => {
|
|
1131
|
+
try {
|
|
1132
|
+
const result = await prepareProject({
|
|
1133
|
+
github,
|
|
1134
|
+
fleet,
|
|
1135
|
+
project,
|
|
1136
|
+
userId,
|
|
1137
|
+
onProgress: (ev) => void stream.writeSSE({ event: "progress", data: JSON.stringify(ev) })
|
|
1138
|
+
});
|
|
1139
|
+
await stream.writeSSE({ event: "done", data: JSON.stringify(result) });
|
|
1140
|
+
} catch (err) {
|
|
1141
|
+
await stream.writeSSE({ event: "error", data: JSON.stringify(ensureErrorPayload(err).body) });
|
|
1142
|
+
}
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
try {
|
|
1146
|
+
const result = await prepareProject({ github, fleet, project, userId });
|
|
1147
|
+
return c.json(result);
|
|
1148
|
+
} catch (err) {
|
|
1149
|
+
const { status, body } = ensureErrorPayload(err);
|
|
1150
|
+
return c.json(body, status);
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
})
|
|
1154
|
+
);
|
|
1155
|
+
routes.push(
|
|
1156
|
+
registerApiRoute("/web/github/projects/:id/issues", {
|
|
1157
|
+
method: "GET",
|
|
1158
|
+
requiresAuth: false,
|
|
1159
|
+
handler: async (c) => {
|
|
1160
|
+
const loaded = await loadOrgProject({ github, auth, c: loose(c) });
|
|
1161
|
+
if ("response" in loaded) return loaded.response;
|
|
1162
|
+
const page = parseListPage(c.req.query("page"));
|
|
1163
|
+
if (page === null) return c.json({ error: "invalid_page" }, 400);
|
|
1164
|
+
const label = parseIssueLabelFilter(c.req.query("label"));
|
|
1165
|
+
if (label === null) return c.json({ error: "invalid_label" }, 400);
|
|
1166
|
+
try {
|
|
1167
|
+
const { issues, nextCursor } = await github.intake.listIssues({
|
|
1168
|
+
connection: {
|
|
1169
|
+
type: "app-installation",
|
|
1170
|
+
installationId: Number(loaded.project.installation.externalId)
|
|
1171
|
+
},
|
|
1172
|
+
sourceIds: [loaded.project.repository.slug],
|
|
1173
|
+
labels: label ? [label] : void 0,
|
|
1174
|
+
cursor: String(page)
|
|
1175
|
+
});
|
|
1176
|
+
const responseIssues = issues.map((issue) => ({
|
|
1177
|
+
number: Number(issue.id),
|
|
1178
|
+
title: issue.title,
|
|
1179
|
+
url: issue.url,
|
|
1180
|
+
author: issue.author,
|
|
1181
|
+
labels: issue.labels,
|
|
1182
|
+
comments: issue.commentCount ?? 0,
|
|
1183
|
+
createdAt: issue.createdAt,
|
|
1184
|
+
updatedAt: issue.updatedAt
|
|
1185
|
+
}));
|
|
1186
|
+
await ingestPolledEvents(
|
|
1187
|
+
responseIssues.map((issue) => polledIssueEvent(loaded.project, issue)),
|
|
1188
|
+
options.ingestFactoryEvent
|
|
1189
|
+
);
|
|
1190
|
+
return c.json({
|
|
1191
|
+
issues: responseIssues,
|
|
1192
|
+
nextPage: nextCursor === null ? null : Number(nextCursor)
|
|
1193
|
+
});
|
|
1194
|
+
} catch (err) {
|
|
1195
|
+
return c.json(
|
|
1196
|
+
{ error: "github_fetch_failed", message: err instanceof Error ? err.message : String(err) },
|
|
1197
|
+
502
|
|
1198
|
+
);
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
})
|
|
1202
|
+
);
|
|
1203
|
+
routes.push(
|
|
1204
|
+
registerApiRoute("/web/github/projects/:id/issues/:number/triage", {
|
|
1205
|
+
method: "POST",
|
|
1206
|
+
requiresAuth: false,
|
|
1207
|
+
handler: async (c) => {
|
|
1208
|
+
const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
|
|
1209
|
+
if ("response" in owned) return owned.response;
|
|
1210
|
+
const { project, sandboxRow } = owned;
|
|
1211
|
+
const issueNumber = parseIssueNumberParam(c.req.param("number"));
|
|
1212
|
+
if (issueNumber === null) return c.json({ error: "invalid_issue_number" }, 400);
|
|
1213
|
+
let body;
|
|
1214
|
+
try {
|
|
1215
|
+
body = await c.req.json();
|
|
1216
|
+
} catch {
|
|
1217
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
1218
|
+
}
|
|
1219
|
+
if (typeof body.title !== "string" || body.title.trim().length === 0 || body.title.length > 5e3) {
|
|
1220
|
+
return c.json({ error: "invalid_title" }, 400);
|
|
1221
|
+
}
|
|
1222
|
+
if (typeof body.url !== "string" || body.url.trim().length === 0 || body.url.length > 2048 || !isCanonicalGithubIssueUrl(body.url, project.repository.slug, issueNumber)) {
|
|
1223
|
+
return c.json({ error: "invalid_url" }, 400);
|
|
1224
|
+
}
|
|
1225
|
+
if (!runIssueTriage) return c.json({ error: "triage_unavailable" }, 503);
|
|
1226
|
+
const branch = `factory/issue-${issueNumber}`;
|
|
1227
|
+
const projectPath = computeWorktreePath(sandboxRow.sandboxWorkdir, branch);
|
|
1228
|
+
await github.addIssueLabels(Number(project.installation.externalId), project.repository.slug, issueNumber, [
|
|
1229
|
+
"auto-triaged"
|
|
1230
|
+
]);
|
|
1231
|
+
const result = await runIssueTriage({
|
|
1232
|
+
repository: project.repository.slug,
|
|
1233
|
+
issueNumber,
|
|
1234
|
+
issueTitle: body.title,
|
|
1235
|
+
issueUrl: body.url,
|
|
1236
|
+
labels: parseStringList(body.labels),
|
|
1237
|
+
installationId: Number(project.installation.externalId),
|
|
1238
|
+
resourceId: project.factoryProjectId,
|
|
1239
|
+
projectPath,
|
|
1240
|
+
branch,
|
|
1241
|
+
defaultModelId: await resolveFactoryDefaultModelId(options.projects, project.factoryProjectId)
|
|
1242
|
+
});
|
|
1243
|
+
await emitAudit?.({
|
|
1244
|
+
context: loose(c),
|
|
1245
|
+
input: {
|
|
1246
|
+
action: "factory.triage.started",
|
|
1247
|
+
factoryProjectId: project.factoryProjectId,
|
|
1248
|
+
projectRepositoryId: project.id,
|
|
1249
|
+
targets: [{ type: "issue", id: String(issueNumber), name: body.title }],
|
|
1250
|
+
metadata: { issueNumber, branch, threadId: result.threadId }
|
|
1251
|
+
}
|
|
1252
|
+
});
|
|
1253
|
+
return c.json(
|
|
1254
|
+
{
|
|
1255
|
+
ok: true,
|
|
1256
|
+
threadId: result.threadId,
|
|
1257
|
+
projectPath: result.projectPath ?? projectPath,
|
|
1258
|
+
branch: result.branch ?? branch
|
|
1259
|
+
},
|
|
1260
|
+
202
|
|
1261
|
+
);
|
|
1262
|
+
}
|
|
1263
|
+
})
|
|
1264
|
+
);
|
|
1265
|
+
routes.push(
|
|
1266
|
+
registerApiRoute("/web/github/projects/:id/prs", {
|
|
1267
|
+
method: "GET",
|
|
1268
|
+
requiresAuth: false,
|
|
1269
|
+
handler: async (c) => {
|
|
1270
|
+
const loaded = await loadOrgProject({ github, auth, c: loose(c) });
|
|
1271
|
+
if ("response" in loaded) return loaded.response;
|
|
1272
|
+
const page = parseListPage(c.req.query("page"));
|
|
1273
|
+
if (page === null) return c.json({ error: "invalid_page" }, 400);
|
|
1274
|
+
try {
|
|
1275
|
+
const { pullRequests, nextCursor } = await github.versionControl.listPullRequests({
|
|
1276
|
+
connection: {
|
|
1277
|
+
type: "app-installation",
|
|
1278
|
+
installationId: Number(loaded.project.installation.externalId)
|
|
1279
|
+
},
|
|
1280
|
+
sourceId: loaded.project.repository.slug,
|
|
1281
|
+
includeDrafts: false,
|
|
1282
|
+
cursor: String(page)
|
|
1283
|
+
});
|
|
1284
|
+
const responsePullRequests = pullRequests.map((pr) => ({
|
|
1285
|
+
number: Number(pr.id),
|
|
1286
|
+
title: pr.title,
|
|
1287
|
+
url: pr.url,
|
|
1288
|
+
author: pr.author,
|
|
1289
|
+
baseBranch: pr.baseBranch,
|
|
1290
|
+
headBranch: pr.headBranch,
|
|
1291
|
+
createdAt: pr.createdAt,
|
|
1292
|
+
updatedAt: pr.updatedAt
|
|
1293
|
+
}));
|
|
1294
|
+
await ingestPolledEvents(
|
|
1295
|
+
responsePullRequests.map((pullRequest) => polledPullRequestEvent(loaded.project, pullRequest)),
|
|
1296
|
+
options.ingestFactoryEvent
|
|
1297
|
+
);
|
|
1298
|
+
return c.json({
|
|
1299
|
+
pullRequests: responsePullRequests,
|
|
1300
|
+
nextPage: nextCursor === null ? null : Number(nextCursor)
|
|
1301
|
+
});
|
|
1302
|
+
} catch (err) {
|
|
1303
|
+
return c.json(
|
|
1304
|
+
{ error: "github_fetch_failed", message: err instanceof Error ? err.message : String(err) },
|
|
1305
|
+
502
|
|
1306
|
+
);
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
})
|
|
1310
|
+
);
|
|
1311
|
+
routes.push(
|
|
1312
|
+
registerApiRoute("/web/github/projects/:id/settings", {
|
|
1313
|
+
method: "GET",
|
|
1314
|
+
requiresAuth: false,
|
|
1315
|
+
handler: async (c) => {
|
|
1316
|
+
const loaded = await loadOrgProject({ github, auth, c: loose(c) });
|
|
1317
|
+
if ("response" in loaded) return loaded.response;
|
|
1318
|
+
return c.json({ setupCommand: loaded.project.setupCommand });
|
|
1319
|
+
}
|
|
1320
|
+
})
|
|
1321
|
+
);
|
|
1322
|
+
routes.push(
|
|
1323
|
+
registerApiRoute("/web/github/projects/:id/settings", {
|
|
1324
|
+
method: "POST",
|
|
1325
|
+
requiresAuth: false,
|
|
1326
|
+
handler: async (c) => {
|
|
1327
|
+
const loaded = await loadOrgProject({ github, auth, c: loose(c) });
|
|
1328
|
+
if ("response" in loaded) return loaded.response;
|
|
1329
|
+
let body;
|
|
1330
|
+
try {
|
|
1331
|
+
body = await c.req.json();
|
|
1332
|
+
} catch {
|
|
1333
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
1334
|
+
}
|
|
1335
|
+
if (body.setupCommand !== null && typeof body.setupCommand !== "string") {
|
|
1336
|
+
return c.json({ error: "Invalid setupCommand" }, 400);
|
|
1337
|
+
}
|
|
1338
|
+
if (typeof body.setupCommand === "string" && body.setupCommand.length > 2e3) {
|
|
1339
|
+
return c.json({ error: "setupCommand too long (max 2000 characters)" }, 400);
|
|
1340
|
+
}
|
|
1341
|
+
if (typeof body.setupCommand === "string" && /[\0-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(body.setupCommand)) {
|
|
1342
|
+
return c.json({ error: "setupCommand contains control characters" }, 400);
|
|
1343
|
+
}
|
|
1344
|
+
const setupCommand = typeof body.setupCommand === "string" && body.setupCommand.trim().length > 0 ? body.setupCommand.trim() : null;
|
|
1345
|
+
await github.sourceControlStorage.projectRepositories.update({
|
|
1346
|
+
orgId: loaded.project.installation.orgId,
|
|
1347
|
+
id: loaded.project.id,
|
|
1348
|
+
input: { setupCommand }
|
|
1349
|
+
});
|
|
1350
|
+
return c.json({ setupCommand });
|
|
1351
|
+
}
|
|
1352
|
+
})
|
|
1353
|
+
);
|
|
1354
|
+
routes.push(...buildProjectGitRoutes({ github, auth, fleet, storage, emitAudit }));
|
|
1355
|
+
return routes;
|
|
1356
|
+
}
|
|
1357
|
+
async function loadOrgProject(options) {
|
|
1358
|
+
const { github, auth, c } = options;
|
|
1359
|
+
const resolved = await resolveOrgTenant(c, auth);
|
|
1360
|
+
if ("response" in resolved) return { response: resolved.response };
|
|
1361
|
+
const { orgId, userId } = resolved.tenant;
|
|
1362
|
+
const projectRepositoryId = c.req.param("id");
|
|
1363
|
+
if (!projectRepositoryId) {
|
|
1364
|
+
return { response: c.json({ error: "Project repository not found" }, 404) };
|
|
1365
|
+
}
|
|
1366
|
+
const project = await resolveProjectRepository({ github, orgId, projectRepositoryId });
|
|
1367
|
+
if (!project) {
|
|
1368
|
+
return { response: c.json({ error: "Project repository not found" }, 404) };
|
|
1369
|
+
}
|
|
1370
|
+
return { project, userId };
|
|
1371
|
+
}
|
|
1372
|
+
function identityFromUser(user) {
|
|
1373
|
+
const u = user;
|
|
1374
|
+
return { name: u?.name ?? null, email: u?.email ?? null };
|
|
1375
|
+
}
|
|
1376
|
+
async function resolveProjectSandbox(options) {
|
|
1377
|
+
const { fleet, sandboxRow } = options;
|
|
1378
|
+
if (!sandboxRow.sandboxId) {
|
|
1379
|
+
throw new MaterializeError("Project sandbox is not provisioned. Open the project first.", "clone-failed");
|
|
1380
|
+
}
|
|
1381
|
+
return fleet.reattachSandbox(sandboxRow.sandboxId);
|
|
1382
|
+
}
|
|
1383
|
+
async function loadOrCreateSandboxRow(github, project, userId) {
|
|
1384
|
+
return github.sourceControlStorage.sandboxes.getOrCreate({ projectRepository: project, userId });
|
|
1385
|
+
}
|
|
1386
|
+
async function prepareProject(options) {
|
|
1387
|
+
const { github, fleet, project, userId, onProgress } = options;
|
|
1388
|
+
const sandboxRow = await loadOrCreateSandboxRow(github, project, userId);
|
|
1389
|
+
const sandbox = await ensureProjectSandbox({
|
|
1390
|
+
fleet,
|
|
1391
|
+
row: sandboxRow,
|
|
1392
|
+
storage: github.sourceControlStorage.sandboxes,
|
|
1393
|
+
onProgress
|
|
1394
|
+
});
|
|
1395
|
+
const fresh = await github.sourceControlStorage.sandboxes.getById({ id: sandboxRow.id });
|
|
1396
|
+
const access = await github.versionControl.getRepositoryAccess({
|
|
1397
|
+
orgId: project.installation.orgId,
|
|
1398
|
+
repositoryId: project.repository.id
|
|
1399
|
+
});
|
|
1400
|
+
if (!access.authorization) {
|
|
1401
|
+
throw new MaterializeError("Repository access did not include a bearer token.", "clone-failed");
|
|
1402
|
+
}
|
|
1403
|
+
const finalRow = fresh ?? sandboxRow;
|
|
1404
|
+
await materializeRepo({
|
|
1405
|
+
row: finalRow,
|
|
1406
|
+
repoInfo: { repoFullName: project.repository.slug, defaultBranch: project.defaultBranch },
|
|
1407
|
+
sandbox,
|
|
1408
|
+
token: access.authorization.token,
|
|
1409
|
+
storage: github.sourceControlStorage.sandboxes,
|
|
1410
|
+
onProgress
|
|
1411
|
+
});
|
|
1412
|
+
const result = {
|
|
1413
|
+
resourceId: project.factoryProjectId,
|
|
1414
|
+
factoryProjectId: project.factoryProjectId,
|
|
1415
|
+
projectRepositoryId: project.id,
|
|
1416
|
+
sandboxId: finalRow.sandboxId,
|
|
1417
|
+
sandboxWorkdir: finalRow.sandboxWorkdir
|
|
1418
|
+
};
|
|
1419
|
+
const done = { phase: "done", message: "Workspace ready." };
|
|
1420
|
+
onProgress?.(done);
|
|
1421
|
+
return result;
|
|
1422
|
+
}
|
|
1423
|
+
function ensureErrorPayload(err) {
|
|
1424
|
+
if (err instanceof SandboxBudgetError) {
|
|
1425
|
+
return { status: 429, body: { error: err.code, message: err.message } };
|
|
1426
|
+
}
|
|
1427
|
+
if (err instanceof MaterializeError) {
|
|
1428
|
+
return { status: 502, body: { error: err.code, message: err.message } };
|
|
1429
|
+
}
|
|
1430
|
+
return {
|
|
1431
|
+
status: 500,
|
|
1432
|
+
body: { error: "materialize_failed", message: err instanceof Error ? err.message : String(err) }
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
1435
|
+
function gitErrorResponse(c, err) {
|
|
1436
|
+
if (err instanceof WorktreeError) {
|
|
1437
|
+
return c.json({ error: err.code, message: err.message }, err.code === "invalid-branch" ? 400 : 502);
|
|
1438
|
+
}
|
|
1439
|
+
if (err instanceof MaterializeError) {
|
|
1440
|
+
return c.json({ error: err.code, message: err.message }, 502);
|
|
1441
|
+
}
|
|
1442
|
+
return c.json({ error: "git_failed", message: err instanceof Error ? err.message : String(err) }, 500);
|
|
1443
|
+
}
|
|
1444
|
+
async function loadOwnedProject(options) {
|
|
1445
|
+
const { github, auth, fleet, c } = options;
|
|
1446
|
+
const resolved = await resolveOrgTenant(c, auth);
|
|
1447
|
+
if ("response" in resolved) return { response: resolved.response };
|
|
1448
|
+
const { orgId, userId } = resolved.tenant;
|
|
1449
|
+
if (!fleet.enabled) {
|
|
1450
|
+
return {
|
|
1451
|
+
response: c.json({ error: "sandbox_not_configured", message: "No sandbox provider is configured." }, 503)
|
|
1452
|
+
};
|
|
1453
|
+
}
|
|
1454
|
+
const projectRepositoryId = c.req.param("id");
|
|
1455
|
+
if (!projectRepositoryId) {
|
|
1456
|
+
return { response: c.json({ error: "Project repository not found" }, 404) };
|
|
1457
|
+
}
|
|
1458
|
+
const project = await resolveProjectRepository({ github, orgId, projectRepositoryId });
|
|
1459
|
+
if (!project) {
|
|
1460
|
+
return { response: c.json({ error: "Project repository not found" }, 404) };
|
|
1461
|
+
}
|
|
1462
|
+
const sandboxRow = await loadOrCreateSandboxRow(github, project, userId);
|
|
1463
|
+
return { orgId, userId, project, sandboxRow };
|
|
1464
|
+
}
|
|
1465
|
+
function buildProjectGitRoutes({
|
|
1466
|
+
github,
|
|
1467
|
+
auth,
|
|
1468
|
+
fleet,
|
|
1469
|
+
storage,
|
|
1470
|
+
emitAudit
|
|
1471
|
+
}) {
|
|
1472
|
+
return [
|
|
1473
|
+
// ── Create / list Factory sessions ──────────────────────────────────────
|
|
1474
|
+
registerApiRoute("/web/github/projects/:id/sessions", {
|
|
1475
|
+
method: "GET",
|
|
1476
|
+
requiresAuth: false,
|
|
1477
|
+
handler: async (c) => {
|
|
1478
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
1479
|
+
if ("response" in resolved) return resolved.response;
|
|
1480
|
+
const { orgId, userId } = resolved.tenant;
|
|
1481
|
+
const projectRepositoryId = c.req.param("id");
|
|
1482
|
+
const project = projectRepositoryId ? await resolveProjectRepository({ github, orgId, projectRepositoryId }) : null;
|
|
1483
|
+
if (!project) return c.json({ error: "Project repository not found" }, 404);
|
|
1484
|
+
const sessions = await github.sourceControlStorage.sessions.list({ projectRepositoryId: project.id, userId });
|
|
1485
|
+
return c.json({ sessions });
|
|
1486
|
+
}
|
|
1487
|
+
}),
|
|
1488
|
+
registerApiRoute("/web/github/projects/:id/sessions", {
|
|
1489
|
+
method: "POST",
|
|
1490
|
+
requiresAuth: false,
|
|
1491
|
+
handler: async (c) => {
|
|
1492
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
1493
|
+
if ("response" in resolved) return resolved.response;
|
|
1494
|
+
const { orgId, userId } = resolved.tenant;
|
|
1495
|
+
const projectRepositoryId = c.req.param("id");
|
|
1496
|
+
const project = projectRepositoryId ? await resolveProjectRepository({ github, orgId, projectRepositoryId }) : null;
|
|
1497
|
+
if (!project) return c.json({ error: "Project repository not found" }, 404);
|
|
1498
|
+
let body;
|
|
1499
|
+
try {
|
|
1500
|
+
body = await c.req.json();
|
|
1501
|
+
} catch {
|
|
1502
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
1503
|
+
}
|
|
1504
|
+
if (!isValidGitRef(body.branch)) return c.json({ error: "Invalid branch" }, 400);
|
|
1505
|
+
const baseBranch = body.baseBranch === void 0 ? project.defaultBranch : body.baseBranch;
|
|
1506
|
+
if (!isValidGitRef(baseBranch)) return c.json({ error: "Invalid baseBranch" }, 400);
|
|
1507
|
+
const session = await github.sourceControlStorage.sessions.create({
|
|
1508
|
+
sessionId: randomUUID(),
|
|
1509
|
+
projectRepositoryId: project.id,
|
|
1510
|
+
orgId,
|
|
1511
|
+
userId,
|
|
1512
|
+
branch: body.branch,
|
|
1513
|
+
baseBranch
|
|
1514
|
+
});
|
|
1515
|
+
return c.json({ session });
|
|
1516
|
+
}
|
|
1517
|
+
}),
|
|
1518
|
+
registerApiRoute("/web/user-sessions/:sessionId", {
|
|
1519
|
+
method: "GET",
|
|
1520
|
+
requiresAuth: false,
|
|
1521
|
+
handler: async (c) => {
|
|
1522
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
1523
|
+
if ("response" in resolved) return resolved.response;
|
|
1524
|
+
const session = await github.sourceControlStorage.sessions.getBySessionId(c.req.param("sessionId"));
|
|
1525
|
+
if (!session || session.orgId !== resolved.tenant.orgId || session.userId !== resolved.tenant.userId) {
|
|
1526
|
+
return c.json({ error: "Session not found" }, 404);
|
|
1527
|
+
}
|
|
1528
|
+
return c.json({ session });
|
|
1529
|
+
}
|
|
1530
|
+
}),
|
|
1531
|
+
registerApiRoute("/web/user-sessions/:sessionId", {
|
|
1532
|
+
method: "DELETE",
|
|
1533
|
+
requiresAuth: false,
|
|
1534
|
+
handler: async (c) => {
|
|
1535
|
+
const resolved = await resolveOrgTenant(loose(c), auth);
|
|
1536
|
+
if ("response" in resolved) return resolved.response;
|
|
1537
|
+
const session = await github.sourceControlStorage.sessions.getBySessionId(c.req.param("sessionId"));
|
|
1538
|
+
if (!session || session.orgId !== resolved.tenant.orgId || session.userId !== resolved.tenant.userId) {
|
|
1539
|
+
return c.json({ error: "Session not found" }, 404);
|
|
1540
|
+
}
|
|
1541
|
+
let sandbox;
|
|
1542
|
+
if (session.sandboxId) {
|
|
1543
|
+
try {
|
|
1544
|
+
sandbox = await fleet.reattachSandbox(session.sandboxId);
|
|
1545
|
+
} catch {
|
|
1546
|
+
}
|
|
1547
|
+
await fleet.teardownSandbox(
|
|
1548
|
+
{
|
|
1549
|
+
sandboxId: session.sandboxId,
|
|
1550
|
+
setSandboxId: async () => {
|
|
1551
|
+
},
|
|
1552
|
+
clear: async () => {
|
|
1553
|
+
await github.sourceControlStorage.sessions.setSandbox({
|
|
1554
|
+
id: session.id,
|
|
1555
|
+
sandboxId: null,
|
|
1556
|
+
sandboxWorkdir: session.sandboxWorkdir ?? ""
|
|
1557
|
+
});
|
|
1558
|
+
}
|
|
1559
|
+
},
|
|
1560
|
+
sandbox
|
|
1561
|
+
);
|
|
1562
|
+
}
|
|
1563
|
+
await github.sourceControlStorage.sessions.delete(session.id);
|
|
1564
|
+
return c.json({ removed: true });
|
|
1565
|
+
}
|
|
1566
|
+
}),
|
|
1567
|
+
// ── Stage all + commit inside a Factory session workspace ──────────────
|
|
1568
|
+
registerApiRoute("/web/github/projects/:id/commit", {
|
|
1569
|
+
method: "POST",
|
|
1570
|
+
requiresAuth: false,
|
|
1571
|
+
handler: async (c) => {
|
|
1572
|
+
const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
|
|
1573
|
+
if ("response" in owned) return owned.response;
|
|
1574
|
+
const { userId, project } = owned;
|
|
1575
|
+
let body;
|
|
1576
|
+
try {
|
|
1577
|
+
body = await c.req.json();
|
|
1578
|
+
} catch {
|
|
1579
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
1580
|
+
}
|
|
1581
|
+
if (typeof body.message !== "string" || body.message.trim().length === 0 || body.message.length > 5e3) {
|
|
1582
|
+
return c.json({ error: "Invalid message" }, 400);
|
|
1583
|
+
}
|
|
1584
|
+
const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
|
|
1585
|
+
if (!sessionWorkspace) {
|
|
1586
|
+
return c.json({ error: "Invalid sessionId" }, 400);
|
|
1587
|
+
}
|
|
1588
|
+
const { workdir, sandboxBinding } = sessionWorkspace;
|
|
1589
|
+
try {
|
|
1590
|
+
return await withProjectLock({
|
|
1591
|
+
key: `${project.id}:${userId}`,
|
|
1592
|
+
storage,
|
|
1593
|
+
fn: async () => {
|
|
1594
|
+
const sandbox = await resolveProjectSandbox({ fleet, sandboxRow: sandboxBinding });
|
|
1595
|
+
const result = await commitAll(
|
|
1596
|
+
sandbox,
|
|
1597
|
+
workdir,
|
|
1598
|
+
body.message,
|
|
1599
|
+
identityFromUser(await auth.ensureUser(loose(c)))
|
|
1600
|
+
);
|
|
1601
|
+
if (result.committed) {
|
|
1602
|
+
await emitAudit?.({
|
|
1603
|
+
context: loose(c),
|
|
1604
|
+
input: {
|
|
1605
|
+
action: "factory.git.commit",
|
|
1606
|
+
factoryProjectId: project.factoryProjectId,
|
|
1607
|
+
projectRepositoryId: project.id,
|
|
1608
|
+
targets: [{ type: "session", id: sessionWorkspace.session.sessionId }],
|
|
1609
|
+
metadata: { sessionId: sessionWorkspace.session.sessionId }
|
|
1610
|
+
}
|
|
1611
|
+
});
|
|
1612
|
+
}
|
|
1613
|
+
return c.json({ committed: result.committed });
|
|
1614
|
+
}
|
|
1615
|
+
});
|
|
1616
|
+
} catch (err) {
|
|
1617
|
+
return gitErrorResponse(loose(c), err);
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
}),
|
|
1621
|
+
// ── Push a branch back to GitHub ────────────────────────────────────────
|
|
1622
|
+
registerApiRoute("/web/github/projects/:id/push", {
|
|
1623
|
+
method: "POST",
|
|
1624
|
+
requiresAuth: false,
|
|
1625
|
+
handler: async (c) => {
|
|
1626
|
+
const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
|
|
1627
|
+
if ("response" in owned) return owned.response;
|
|
1628
|
+
const { orgId, userId, project } = owned;
|
|
1629
|
+
let body;
|
|
1630
|
+
try {
|
|
1631
|
+
body = await c.req.json();
|
|
1632
|
+
} catch {
|
|
1633
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
1634
|
+
}
|
|
1635
|
+
if (!isValidGitRef(body.branch)) {
|
|
1636
|
+
return c.json({ error: "Invalid branch" }, 400);
|
|
1637
|
+
}
|
|
1638
|
+
const branch = body.branch;
|
|
1639
|
+
const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
|
|
1640
|
+
if (!sessionWorkspace) {
|
|
1641
|
+
return c.json({ error: "Invalid sessionId" }, 400);
|
|
1642
|
+
}
|
|
1643
|
+
const { workdir, sandboxBinding } = sessionWorkspace;
|
|
1644
|
+
try {
|
|
1645
|
+
return await withProjectLock({
|
|
1646
|
+
key: `${project.id}:${userId}`,
|
|
1647
|
+
storage,
|
|
1648
|
+
fn: async () => {
|
|
1649
|
+
const sandbox = await resolveProjectSandbox({ fleet, sandboxRow: sandboxBinding });
|
|
1650
|
+
const access = await github.versionControl.getRepositoryAccess({
|
|
1651
|
+
orgId,
|
|
1652
|
+
repositoryId: project.repository.id
|
|
1653
|
+
});
|
|
1654
|
+
if (!access.authorization) throw new Error("Repository access did not include a bearer token.");
|
|
1655
|
+
await pushBranch(sandbox, workdir, branch, access.authorization.token, project.repository.slug);
|
|
1656
|
+
await emitAudit?.({
|
|
1657
|
+
context: loose(c),
|
|
1658
|
+
input: {
|
|
1659
|
+
action: "factory.git.push",
|
|
1660
|
+
factoryProjectId: project.factoryProjectId,
|
|
1661
|
+
projectRepositoryId: project.id,
|
|
1662
|
+
targets: [{ type: "branch", id: branch }],
|
|
1663
|
+
metadata: { branch, sessionId: sessionWorkspace.session.sessionId }
|
|
1664
|
+
}
|
|
1665
|
+
});
|
|
1666
|
+
return c.json({ pushed: true, branch });
|
|
1667
|
+
}
|
|
1668
|
+
});
|
|
1669
|
+
} catch (err) {
|
|
1670
|
+
return gitErrorResponse(loose(c), err);
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
}),
|
|
1674
|
+
// ── Open a pull request through the version-control capability ─────────
|
|
1675
|
+
registerApiRoute("/web/github/projects/:id/pr", {
|
|
1676
|
+
method: "POST",
|
|
1677
|
+
requiresAuth: false,
|
|
1678
|
+
handler: async (c) => {
|
|
1679
|
+
const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
|
|
1680
|
+
if ("response" in owned) return owned.response;
|
|
1681
|
+
const { orgId, userId, project } = owned;
|
|
1682
|
+
let body;
|
|
1683
|
+
try {
|
|
1684
|
+
body = await c.req.json();
|
|
1685
|
+
} catch {
|
|
1686
|
+
return c.json({ error: "Invalid JSON body" }, 400);
|
|
1687
|
+
}
|
|
1688
|
+
if (!isValidGitRef(body.branch)) {
|
|
1689
|
+
return c.json({ error: "Invalid branch" }, 400);
|
|
1690
|
+
}
|
|
1691
|
+
const base = body.base === void 0 ? project.defaultBranch : body.base;
|
|
1692
|
+
if (!isValidGitRef(base)) {
|
|
1693
|
+
return c.json({ error: "Invalid base" }, 400);
|
|
1694
|
+
}
|
|
1695
|
+
if (typeof body.title !== "string" || body.title.trim().length === 0 || body.title.length > 256) {
|
|
1696
|
+
return c.json({ error: "Invalid title" }, 400);
|
|
1697
|
+
}
|
|
1698
|
+
if (body.body !== void 0 && (typeof body.body !== "string" || body.body.length > 65536)) {
|
|
1699
|
+
return c.json({ error: "Invalid body" }, 400);
|
|
1700
|
+
}
|
|
1701
|
+
const head = body.branch;
|
|
1702
|
+
const title = body.title;
|
|
1703
|
+
const prBody = body.body;
|
|
1704
|
+
const sessionWorkspace = await resolveSessionWorkspace(github, project.id, userId, body.sessionId);
|
|
1705
|
+
if (!sessionWorkspace) {
|
|
1706
|
+
return c.json({ error: "Invalid sessionId" }, 400);
|
|
1707
|
+
}
|
|
1708
|
+
try {
|
|
1709
|
+
return await withProjectLock({
|
|
1710
|
+
key: `${project.id}:${userId}`,
|
|
1711
|
+
storage,
|
|
1712
|
+
fn: async () => {
|
|
1713
|
+
const result = await github.versionControl.createPullRequest({
|
|
1714
|
+
connection: {
|
|
1715
|
+
type: "app-installation",
|
|
1716
|
+
installationId: Number(project.installation.externalId)
|
|
1717
|
+
},
|
|
1718
|
+
sourceId: project.repository.slug,
|
|
1719
|
+
baseBranch: base,
|
|
1720
|
+
headBranch: head,
|
|
1721
|
+
title,
|
|
1722
|
+
body: prBody
|
|
1723
|
+
});
|
|
1724
|
+
await emitAudit?.({
|
|
1725
|
+
context: loose(c),
|
|
1726
|
+
input: {
|
|
1727
|
+
action: "factory.git.pr_opened",
|
|
1728
|
+
factoryProjectId: project.factoryProjectId,
|
|
1729
|
+
projectRepositoryId: project.id,
|
|
1730
|
+
targets: [{ type: "pull_request", id: result.url, name: title }],
|
|
1731
|
+
metadata: { branch: head, base, url: result.url }
|
|
1732
|
+
}
|
|
1733
|
+
});
|
|
1734
|
+
const pullRequestNumber = pullRequestNumberFromUrl(result.url, project.repository.slug);
|
|
1735
|
+
if (pullRequestNumber) {
|
|
1736
|
+
const sessionId = sessionWorkspace.session.sessionId;
|
|
1737
|
+
await subscribeToPullRequest(
|
|
1738
|
+
{
|
|
1739
|
+
orgId,
|
|
1740
|
+
installationExternalId: project.installation.externalId,
|
|
1741
|
+
projectRepositoryId: project.id,
|
|
1742
|
+
repositoryExternalId: project.repository.externalId,
|
|
1743
|
+
repositorySlug: project.repository.slug,
|
|
1744
|
+
changeRequestId: pullRequestNumber.toString(),
|
|
1745
|
+
sessionId,
|
|
1746
|
+
ownerId: userId,
|
|
1747
|
+
resourceId: sessionId,
|
|
1748
|
+
threadId: sessionId,
|
|
1749
|
+
source: "factory-pr-create",
|
|
1750
|
+
subscribedByUserId: userId
|
|
1751
|
+
},
|
|
1752
|
+
github.integrationStorage
|
|
1753
|
+
).catch((error) => {
|
|
1754
|
+
console.warn(
|
|
1755
|
+
`[GitHub] Pull request ${result.url} was created but automatic subscription failed.`,
|
|
1756
|
+
error
|
|
1757
|
+
);
|
|
1758
|
+
});
|
|
1759
|
+
}
|
|
1760
|
+
return c.json({ url: result.url });
|
|
1761
|
+
}
|
|
1762
|
+
});
|
|
1763
|
+
} catch (err) {
|
|
1764
|
+
return c.json(
|
|
1765
|
+
{ error: "github_pr_create_failed", message: err instanceof Error ? err.message : String(err) },
|
|
1766
|
+
502
|
|
1767
|
+
);
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
}),
|
|
1771
|
+
// ── Tear down the caller's sandbox for a project ────────────────────────
|
|
1772
|
+
// Per-user teardown only: drops the caller's `(project, user)` sandbox
|
|
1773
|
+
// binding and stops the VM, freeing a slot in the per-replica budget. Project
|
|
1774
|
+
// deletion at the org level is out of scope (org admin model is later).
|
|
1775
|
+
registerApiRoute("/web/github/projects/:id/sandbox", {
|
|
1776
|
+
method: "DELETE",
|
|
1777
|
+
requiresAuth: false,
|
|
1778
|
+
handler: async (c) => {
|
|
1779
|
+
const owned = await loadOwnedProject({ github, auth, fleet, c: loose(c) });
|
|
1780
|
+
if ("response" in owned) return owned.response;
|
|
1781
|
+
const { userId, project, sandboxRow } = owned;
|
|
1782
|
+
if (!sandboxRow.sandboxId) {
|
|
1783
|
+
return c.json({ tornDown: false });
|
|
1784
|
+
}
|
|
1785
|
+
try {
|
|
1786
|
+
return await withProjectLock({
|
|
1787
|
+
key: `${project.id}:${userId}`,
|
|
1788
|
+
storage,
|
|
1789
|
+
fn: async () => {
|
|
1790
|
+
const sandbox = await fleet.reattachSandbox(sandboxRow.sandboxId);
|
|
1791
|
+
await teardownProjectSandbox({
|
|
1792
|
+
fleet,
|
|
1793
|
+
row: sandboxRow,
|
|
1794
|
+
storage: github.sourceControlStorage.sandboxes,
|
|
1795
|
+
sandbox
|
|
1796
|
+
});
|
|
1797
|
+
return c.json({ tornDown: true });
|
|
1798
|
+
}
|
|
1799
|
+
});
|
|
1800
|
+
} catch (err) {
|
|
1801
|
+
return gitErrorResponse(loose(c), err);
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
})
|
|
1805
|
+
];
|
|
1806
|
+
}
|
|
1807
|
+
async function resolveSessionWorkspace(github, projectId, userId, sessionId) {
|
|
1808
|
+
if (typeof sessionId !== "string") {
|
|
1809
|
+
return void 0;
|
|
1810
|
+
}
|
|
1811
|
+
const session = await github.sourceControlStorage.sessions.getBySessionId(sessionId);
|
|
1812
|
+
if (session?.projectRepositoryId !== projectId || session.userId !== userId || !session.sandboxId || !session.sandboxWorkdir) {
|
|
1813
|
+
return void 0;
|
|
1814
|
+
}
|
|
1815
|
+
return {
|
|
1816
|
+
session,
|
|
1817
|
+
workdir: session.sandboxWorkdir,
|
|
1818
|
+
sandboxBinding: {
|
|
1819
|
+
id: session.id,
|
|
1820
|
+
projectRepositoryId: session.projectRepositoryId,
|
|
1821
|
+
userId: session.userId,
|
|
1822
|
+
sandboxId: session.sandboxId,
|
|
1823
|
+
sandboxWorkdir: session.sandboxWorkdir,
|
|
1824
|
+
materializedAt: session.materializedAt,
|
|
1825
|
+
createdAt: session.createdAt
|
|
1826
|
+
}
|
|
1827
|
+
};
|
|
1828
|
+
}
|
|
1829
|
+
export {
|
|
1830
|
+
buildGithubRoutes
|
|
1831
|
+
};
|
|
1832
|
+
//# sourceMappingURL=routes.js.map
|