@inkeep/agents-work-apps 0.0.0-dev-20260203033642

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/LICENSE.md ADDED
@@ -0,0 +1,49 @@
1
+ # Inkeep SDK – Elastic License 2.0 with Supplemental Terms
2
+
3
+ NOTE: The Inkeep SDK is licensed under the Elastic License 2.0 (ELv2), subject to Supplemental Terms included in [SUPPLEMENTAL_TERMS.md](SUPPLEMENTAL_TERMS.md). In the event of conflict, the Supplemental Terms control.
4
+
5
+ # Elastic License 2.0
6
+
7
+ ## Acceptance
8
+ By using the software, you agree to all of the terms and conditions below.
9
+
10
+ ## Copyright License
11
+ The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below.
12
+
13
+ ## Limitations
14
+ You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
15
+
16
+ You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key.
17
+
18
+ You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor’s trademarks is subject to applicable law.
19
+
20
+ ## Patents
21
+ The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
22
+
23
+ ## Notices
24
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
25
+
26
+ If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
27
+
28
+ ## No Other Rights
29
+ These terms do not imply any licenses other than those expressly granted in these terms.
30
+
31
+ ## Termination
32
+ If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
33
+
34
+ ## No Liability
35
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
36
+
37
+ ## Definitions
38
+ The **licensor** is the entity offering these terms, and the **software** is the software the licensor makes available under these terms, including any portion of it.
39
+
40
+ **you** refers to the individual or entity agreeing to these terms.
41
+
42
+ **your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
43
+
44
+ **your licenses** are all the licenses granted to you for the software under these terms.
45
+
46
+ **use** means anything you do with the software requiring one of your licenses.
47
+
48
+ **trademark** means trademarks, service marks, and similar rights.
49
+
@@ -0,0 +1,2 @@
1
+ import runDbClient from "./runDbClient.js";
2
+ export { runDbClient };
@@ -0,0 +1,3 @@
1
+ import runDbClient_default from "./runDbClient.js";
2
+
3
+ export { runDbClient_default as runDbClient };
@@ -0,0 +1,6 @@
1
+ import * as _inkeep_agents_core0 from "@inkeep/agents-core";
2
+
3
+ //#region src/db/runDbClient.d.ts
4
+ declare const runDbClient: _inkeep_agents_core0.AgentsRunDatabaseClient;
5
+ //#endregion
6
+ export { runDbClient as default };
@@ -0,0 +1,9 @@
1
+ import { env } from "../env.js";
2
+ import { createAgentsRunDatabaseClient } from "@inkeep/agents-core";
3
+
4
+ //#region src/db/runDbClient.ts
5
+ const runDbClient = createAgentsRunDatabaseClient({ connectionString: env.INKEEP_AGENTS_RUN_DATABASE_URL });
6
+ var runDbClient_default = runDbClient;
7
+
8
+ //#endregion
9
+ export { runDbClient_default as default };
package/dist/env.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import { z } from "@hono/zod-openapi";
2
+
3
+ //#region src/env.d.ts
4
+ declare const envSchema: z.ZodObject<{
5
+ NODE_ENV: z.ZodDefault<z.ZodEnum<{
6
+ development: "development";
7
+ production: "production";
8
+ test: "test";
9
+ }>>;
10
+ ENVIRONMENT: z.ZodDefault<z.ZodEnum<{
11
+ development: "development";
12
+ production: "production";
13
+ test: "test";
14
+ pentest: "pentest";
15
+ }>>;
16
+ LOG_LEVEL: z.ZodDefault<z.ZodEnum<{
17
+ error: "error";
18
+ trace: "trace";
19
+ debug: "debug";
20
+ info: "info";
21
+ warn: "warn";
22
+ }>>;
23
+ INKEEP_AGENTS_RUN_DATABASE_URL: z.ZodString;
24
+ INKEEP_AGENTS_MANAGE_UI_URL: z.ZodOptional<z.ZodString>;
25
+ GITHUB_APP_ID: z.ZodOptional<z.ZodString>;
26
+ GITHUB_APP_PRIVATE_KEY: z.ZodOptional<z.ZodString>;
27
+ GITHUB_WEBHOOK_SECRET: z.ZodOptional<z.ZodString>;
28
+ GITHUB_STATE_SIGNING_SECRET: z.ZodOptional<z.ZodString>;
29
+ GITHUB_APP_NAME: z.ZodOptional<z.ZodString>;
30
+ GITHUB_MCP_API_KEY: z.ZodOptional<z.ZodString>;
31
+ }, z.core.$strip>;
32
+ declare const env: {
33
+ NODE_ENV: "development" | "production" | "test";
34
+ ENVIRONMENT: "development" | "production" | "test" | "pentest";
35
+ LOG_LEVEL: "error" | "trace" | "debug" | "info" | "warn";
36
+ INKEEP_AGENTS_RUN_DATABASE_URL: string;
37
+ INKEEP_AGENTS_MANAGE_UI_URL?: string | undefined;
38
+ GITHUB_APP_ID?: string | undefined;
39
+ GITHUB_APP_PRIVATE_KEY?: string | undefined;
40
+ GITHUB_WEBHOOK_SECRET?: string | undefined;
41
+ GITHUB_STATE_SIGNING_SECRET?: string | undefined;
42
+ GITHUB_APP_NAME?: string | undefined;
43
+ GITHUB_MCP_API_KEY?: string | undefined;
44
+ };
45
+ type Env = z.infer<typeof envSchema>;
46
+ //#endregion
47
+ export { Env, env };
package/dist/env.js ADDED
@@ -0,0 +1,48 @@
1
+ import { z } from "@hono/zod-openapi";
2
+ import { loadEnvironmentFiles } from "@inkeep/agents-core";
3
+
4
+ //#region src/env.ts
5
+ loadEnvironmentFiles();
6
+ const envSchema = z.object({
7
+ NODE_ENV: z.enum([
8
+ "development",
9
+ "production",
10
+ "test"
11
+ ]).default("development").describe("Node.js environment mode"),
12
+ ENVIRONMENT: z.enum([
13
+ "development",
14
+ "production",
15
+ "pentest",
16
+ "test"
17
+ ]).default("development").describe("Application environment mode"),
18
+ LOG_LEVEL: z.enum([
19
+ "trace",
20
+ "debug",
21
+ "info",
22
+ "warn",
23
+ "error"
24
+ ]).default("info").describe("Logging verbosity level"),
25
+ INKEEP_AGENTS_RUN_DATABASE_URL: z.string().describe("PostgreSQL connection URL for the runtime database (Doltgres with Git version control)"),
26
+ INKEEP_AGENTS_MANAGE_UI_URL: z.string().optional().describe("URL where the management UI is hosted"),
27
+ GITHUB_APP_ID: z.string().optional().describe("GitHub App ID for GitHub integration"),
28
+ GITHUB_APP_PRIVATE_KEY: z.string().optional().describe("GitHub App private key for authentication"),
29
+ GITHUB_WEBHOOK_SECRET: z.string().optional().describe("Secret for validating GitHub webhook payloads"),
30
+ GITHUB_STATE_SIGNING_SECRET: z.string().min(32, "GITHUB_STATE_SIGNING_SECRET must be at least 32 characters").optional().describe("Secret for signing GitHub OAuth state (minimum 32 characters)"),
31
+ GITHUB_APP_NAME: z.string().optional().describe("Name of the GitHub App"),
32
+ GITHUB_MCP_API_KEY: z.string().optional().describe("API key for the GitHub MCP")
33
+ });
34
+ const parseEnv = () => {
35
+ try {
36
+ return envSchema.parse(process.env);
37
+ } catch (error) {
38
+ if (error instanceof z.ZodError) {
39
+ const missingVars = error.issues.map((issue) => issue.path.join("."));
40
+ throw new Error(`❌ Invalid environment variables: ${missingVars.join(", ")}\n${error.message}`);
41
+ }
42
+ throw error;
43
+ }
44
+ };
45
+ const env = parseEnv();
46
+
47
+ //#endregion
48
+ export { env };
@@ -0,0 +1,22 @@
1
+ import { z } from "@hono/zod-openapi";
2
+
3
+ //#region src/github/config.d.ts
4
+ declare const GitHubAppConfigSchema: z.ZodObject<{
5
+ appId: z.ZodString;
6
+ privateKey: z.ZodString;
7
+ }, z.core.$strip>;
8
+ type GitHubAppConfig = z.infer<typeof GitHubAppConfigSchema>;
9
+ declare function getGitHubAppConfig(): GitHubAppConfig;
10
+ declare function isGitHubAppConfigured(): boolean;
11
+ declare function validateGitHubAppConfigOnStartup(): void;
12
+ declare function clearConfigCache(): void;
13
+ declare function isWebhookConfigured(): boolean;
14
+ declare function getWebhookSecret(): string;
15
+ declare function validateGitHubWebhookConfigOnStartup(): void;
16
+ declare function isStateSigningConfigured(): boolean;
17
+ declare function getStateSigningSecret(): string;
18
+ declare function isGitHubAppNameConfigured(): boolean;
19
+ declare function getGitHubAppName(): string;
20
+ declare function validateGitHubInstallFlowConfigOnStartup(): void;
21
+ //#endregion
22
+ export { GitHubAppConfig, clearConfigCache, getGitHubAppConfig, getGitHubAppName, getStateSigningSecret, getWebhookSecret, isGitHubAppConfigured, isGitHubAppNameConfigured, isStateSigningConfigured, isWebhookConfigured, validateGitHubAppConfigOnStartup, validateGitHubInstallFlowConfigOnStartup, validateGitHubWebhookConfigOnStartup };
@@ -0,0 +1,79 @@
1
+ import { env } from "../env.js";
2
+ import { getLogger } from "../logger.js";
3
+ import { z } from "@hono/zod-openapi";
4
+
5
+ //#region src/github/config.ts
6
+ const logger = getLogger("github-config");
7
+ const GitHubAppConfigSchema = z.object({
8
+ appId: z.string().min(1, "GITHUB_APP_ID is required"),
9
+ privateKey: z.string().min(1, "GITHUB_APP_PRIVATE_KEY is required")
10
+ });
11
+ let cachedConfig = null;
12
+ function getGitHubAppConfig() {
13
+ if (cachedConfig) return cachedConfig;
14
+ const appId = env.GITHUB_APP_ID;
15
+ const privateKey = env.GITHUB_APP_PRIVATE_KEY?.replace(/\\n/g, "\n");
16
+ const result = GitHubAppConfigSchema.safeParse({
17
+ appId,
18
+ privateKey
19
+ });
20
+ if (!result.success) {
21
+ const errorMessage = `GitHub App credentials are not configured. ${result.error.issues.map((issue) => issue.message).join(". ")}. Please set GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY environment variables.`;
22
+ logger.error({}, errorMessage);
23
+ throw new Error(errorMessage);
24
+ }
25
+ cachedConfig = result.data;
26
+ logger.info({ appId: cachedConfig.appId }, "GitHub App credentials loaded successfully");
27
+ return cachedConfig;
28
+ }
29
+ function isGitHubAppConfigured() {
30
+ return Boolean(env.GITHUB_APP_ID && env.GITHUB_APP_PRIVATE_KEY);
31
+ }
32
+ function validateGitHubAppConfigOnStartup() {
33
+ if (!isGitHubAppConfigured()) {
34
+ logger.warn({}, "GitHub App credentials not configured. Token exchange endpoint will return 500 errors. Set GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY to enable the feature.");
35
+ return;
36
+ }
37
+ try {
38
+ getGitHubAppConfig();
39
+ } catch (error) {
40
+ logger.error({ error }, "GitHub App credentials are invalid. Token exchange endpoint will return 500 errors.");
41
+ }
42
+ }
43
+ function clearConfigCache() {
44
+ cachedConfig = null;
45
+ }
46
+ function isWebhookConfigured() {
47
+ return Boolean(env.GITHUB_WEBHOOK_SECRET);
48
+ }
49
+ function getWebhookSecret() {
50
+ const secret = env.GITHUB_WEBHOOK_SECRET;
51
+ if (!secret) throw new Error("GITHUB_WEBHOOK_SECRET is not configured");
52
+ return secret;
53
+ }
54
+ function validateGitHubWebhookConfigOnStartup() {
55
+ if (!isWebhookConfigured()) logger.warn({}, "GitHub webhook secret not configured. Webhook endpoints will reject all requests. Set GITHUB_WEBHOOK_SECRET to enable webhook processing.");
56
+ }
57
+ function isStateSigningConfigured() {
58
+ return Boolean(env.GITHUB_STATE_SIGNING_SECRET);
59
+ }
60
+ function getStateSigningSecret() {
61
+ const secret = env.GITHUB_STATE_SIGNING_SECRET;
62
+ if (!secret) throw new Error("GITHUB_STATE_SIGNING_SECRET is not configured");
63
+ return secret;
64
+ }
65
+ function isGitHubAppNameConfigured() {
66
+ return Boolean(env.GITHUB_APP_NAME);
67
+ }
68
+ function getGitHubAppName() {
69
+ const appName = env.GITHUB_APP_NAME;
70
+ if (!appName) throw new Error("GITHUB_APP_NAME is not configured");
71
+ return appName;
72
+ }
73
+ function validateGitHubInstallFlowConfigOnStartup() {
74
+ if (!isStateSigningConfigured()) logger.warn({}, "GitHub state signing secret not configured. Install URL endpoint will return 500 errors. Set GITHUB_STATE_SIGNING_SECRET to enable the installation flow.");
75
+ if (!isGitHubAppNameConfigured()) logger.warn({}, "GitHub App name not configured. Install URL endpoint will return 500 errors. Set GITHUB_APP_NAME to enable the installation flow.");
76
+ }
77
+
78
+ //#endregion
79
+ export { clearConfigCache, getGitHubAppConfig, getGitHubAppName, getStateSigningSecret, getWebhookSecret, isGitHubAppConfigured, isGitHubAppNameConfigured, isStateSigningConfigured, isWebhookConfigured, validateGitHubAppConfigOnStartup, validateGitHubInstallFlowConfigOnStartup, validateGitHubWebhookConfigOnStartup };
@@ -0,0 +1,13 @@
1
+ import { GitHubAppConfig, clearConfigCache, getGitHubAppConfig, getGitHubAppName, getStateSigningSecret, getWebhookSecret, isGitHubAppConfigured, isGitHubAppNameConfigured, isStateSigningConfigured, isWebhookConfigured, validateGitHubAppConfigOnStartup, validateGitHubInstallFlowConfigOnStartup, validateGitHubWebhookConfigOnStartup } from "./config.js";
2
+ import { GenerateInstallationAccessTokenResult, GenerateTokenError, GenerateTokenResult, InstallationAccessToken, InstallationInfo, LookupInstallationError, LookupInstallationForRepoResult, LookupInstallationResult, createAppJwt, determineStatus, fetchInstallationDetails, fetchInstallationRepositories, generateInstallationAccessToken, lookupInstallationForRepo } from "./installation.js";
3
+ import "./routes/setup.js";
4
+ import "./routes/tokenExchange.js";
5
+ import { WebhookVerificationResult, verifyWebhookSignature } from "./routes/webhooks.js";
6
+ import { Hono } from "hono";
7
+ import * as hono_types6 from "hono/types";
8
+
9
+ //#region src/github/index.d.ts
10
+ declare function createGithubRoutes(): Hono<hono_types6.BlankEnv, hono_types6.BlankSchema, "/">;
11
+ declare const githubRoutes: Hono<hono_types6.BlankEnv, hono_types6.BlankSchema, "/">;
12
+ //#endregion
13
+ export { GenerateInstallationAccessTokenResult, GenerateTokenError, GenerateTokenResult, GitHubAppConfig, InstallationAccessToken, InstallationInfo, LookupInstallationError, LookupInstallationForRepoResult, LookupInstallationResult, WebhookVerificationResult, clearConfigCache, createAppJwt, createGithubRoutes, determineStatus, fetchInstallationDetails, fetchInstallationRepositories, generateInstallationAccessToken, getGitHubAppConfig, getGitHubAppName, getStateSigningSecret, getWebhookSecret, githubRoutes, isGitHubAppConfigured, isGitHubAppNameConfigured, isStateSigningConfigured, isWebhookConfigured, lookupInstallationForRepo, validateGitHubAppConfigOnStartup, validateGitHubInstallFlowConfigOnStartup, validateGitHubWebhookConfigOnStartup, verifyWebhookSignature };
@@ -0,0 +1,23 @@
1
+ import { clearConfigCache, getGitHubAppConfig, getGitHubAppName, getStateSigningSecret, getWebhookSecret, isGitHubAppConfigured, isGitHubAppNameConfigured, isStateSigningConfigured, isWebhookConfigured, validateGitHubAppConfigOnStartup, validateGitHubInstallFlowConfigOnStartup, validateGitHubWebhookConfigOnStartup } from "./config.js";
2
+ import mcp_default from "./mcp/index.js";
3
+ import { createAppJwt, determineStatus, fetchInstallationDetails, fetchInstallationRepositories, generateInstallationAccessToken, lookupInstallationForRepo } from "./installation.js";
4
+ import setup_default from "./routes/setup.js";
5
+ import tokenExchange_default from "./routes/tokenExchange.js";
6
+ import webhooks_default, { verifyWebhookSignature } from "./routes/webhooks.js";
7
+ import { Hono } from "hono";
8
+
9
+ //#region src/github/index.ts
10
+ function createGithubRoutes() {
11
+ validateGitHubAppConfigOnStartup();
12
+ validateGitHubWebhookConfigOnStartup();
13
+ const app = new Hono();
14
+ app.route("/token-exchange", tokenExchange_default);
15
+ app.route("/setup", setup_default);
16
+ app.route("/webhooks", webhooks_default);
17
+ app.route("/mcp", mcp_default);
18
+ return app;
19
+ }
20
+ const githubRoutes = createGithubRoutes();
21
+
22
+ //#endregion
23
+ export { clearConfigCache, createAppJwt, createGithubRoutes, determineStatus, fetchInstallationDetails, fetchInstallationRepositories, generateInstallationAccessToken, getGitHubAppConfig, getGitHubAppName, getStateSigningSecret, getWebhookSecret, githubRoutes, isGitHubAppConfigured, isGitHubAppNameConfigured, isStateSigningConfigured, isWebhookConfigured, lookupInstallationForRepo, validateGitHubAppConfigOnStartup, validateGitHubInstallFlowConfigOnStartup, validateGitHubWebhookConfigOnStartup, verifyWebhookSignature };
@@ -0,0 +1,66 @@
1
+ //#region src/github/installation.d.ts
2
+ interface InstallationInfo {
3
+ installationId: number;
4
+ accountLogin: string;
5
+ accountType: 'User' | 'Organization';
6
+ }
7
+ interface LookupInstallationResult {
8
+ success: true;
9
+ installation: InstallationInfo;
10
+ }
11
+ interface LookupInstallationError {
12
+ success: false;
13
+ errorType: 'not_installed' | 'api_error' | 'jwt_error';
14
+ message: string;
15
+ }
16
+ type LookupInstallationForRepoResult = LookupInstallationResult | LookupInstallationError;
17
+ interface InstallationAccessToken {
18
+ token: string;
19
+ expiresAt: string;
20
+ }
21
+ interface GenerateTokenResult {
22
+ success: true;
23
+ accessToken: InstallationAccessToken;
24
+ }
25
+ interface GenerateTokenError {
26
+ success: false;
27
+ errorType: 'api_error' | 'jwt_error';
28
+ message: string;
29
+ }
30
+ type SetupAction = 'install' | 'update' | 'request';
31
+ interface GitHubInstallationResponse {
32
+ id: number;
33
+ account: {
34
+ login: string;
35
+ id: number;
36
+ type: 'Organization' | 'User';
37
+ };
38
+ }
39
+ interface GitHubRepository {
40
+ id: number;
41
+ name: string;
42
+ full_name: string;
43
+ private: boolean;
44
+ }
45
+ type GenerateInstallationAccessTokenResult = GenerateTokenResult | GenerateTokenError;
46
+ declare function createAppJwt(): Promise<string>;
47
+ declare function lookupInstallationForRepo(repositoryOwner: string, repositoryName: string): Promise<LookupInstallationForRepoResult>;
48
+ declare function generateInstallationAccessToken(installationId: number): Promise<GenerateInstallationAccessTokenResult>;
49
+ declare function fetchInstallationDetails(installationId: string, appJwt: string): Promise<{
50
+ success: true;
51
+ installation: GitHubInstallationResponse;
52
+ } | {
53
+ success: false;
54
+ error: string;
55
+ status: number;
56
+ }>;
57
+ declare function fetchInstallationRepositories(installationId: string, appJwt: string): Promise<{
58
+ success: true;
59
+ repositories: GitHubRepository[];
60
+ } | {
61
+ success: false;
62
+ error: string;
63
+ }>;
64
+ declare function determineStatus(setupAction: SetupAction): 'active' | 'pending';
65
+ //#endregion
66
+ export { GenerateInstallationAccessTokenResult, GenerateTokenError, GenerateTokenResult, InstallationAccessToken, InstallationInfo, LookupInstallationError, LookupInstallationForRepoResult, LookupInstallationResult, createAppJwt, determineStatus, fetchInstallationDetails, fetchInstallationRepositories, generateInstallationAccessToken, lookupInstallationForRepo };
@@ -0,0 +1,293 @@
1
+ import { getLogger } from "../logger.js";
2
+ import { getGitHubAppConfig } from "./config.js";
3
+ import { SignJWT } from "jose";
4
+ import { createPrivateKey } from "node:crypto";
5
+
6
+ //#region src/github/installation.ts
7
+ const logger = getLogger("github-installation");
8
+ const GITHUB_API_BASE = "https://api.github.com";
9
+ async function createAppJwt() {
10
+ const config = getGitHubAppConfig();
11
+ logger.debug({ appId: config.appId }, "Creating GitHub App JWT");
12
+ const privateKey = createPrivateKey({
13
+ key: config.privateKey,
14
+ format: "pem"
15
+ });
16
+ const now = Math.floor(Date.now() / 1e3);
17
+ return await new SignJWT({}).setProtectedHeader({ alg: "RS256" }).setIssuedAt(now - 60).setExpirationTime(now + 600).setIssuer(config.appId).sign(privateKey);
18
+ }
19
+ async function lookupInstallationForRepo(repositoryOwner, repositoryName) {
20
+ let appJwt;
21
+ try {
22
+ appJwt = await createAppJwt();
23
+ } catch (error) {
24
+ const message = error instanceof Error ? error.message : "Unknown error";
25
+ logger.error({ error: message }, "Failed to create GitHub App JWT");
26
+ return {
27
+ success: false,
28
+ errorType: "jwt_error",
29
+ message: `Failed to create GitHub App authentication: ${message}`
30
+ };
31
+ }
32
+ const url = `${GITHUB_API_BASE}/repos/${repositoryOwner}/${repositoryName}/installation`;
33
+ try {
34
+ const response = await fetch(url, {
35
+ method: "GET",
36
+ headers: {
37
+ Authorization: `Bearer ${appJwt}`,
38
+ Accept: "application/vnd.github+json",
39
+ "X-GitHub-Api-Version": "2022-11-28",
40
+ "User-Agent": "inkeep-agents-api"
41
+ }
42
+ });
43
+ if (response.status === 404) return {
44
+ success: false,
45
+ errorType: "not_installed",
46
+ message: `GitHub App is not installed on repository ${repositoryOwner}/${repositoryName}. Please install the Inkeep Agents GitHub App on the repository to enable token exchange.`
47
+ };
48
+ if (!response.ok) {
49
+ const errorText = await response.text();
50
+ logger.error({
51
+ status: response.status,
52
+ error: errorText,
53
+ repositoryOwner,
54
+ repositoryName
55
+ }, "GitHub API error looking up installation");
56
+ return {
57
+ success: false,
58
+ errorType: "api_error",
59
+ message: `GitHub API error (${response.status}): Failed to look up installation for repository`
60
+ };
61
+ }
62
+ const data = await response.json();
63
+ const installationId = data.id;
64
+ const accountLogin = data.account?.login;
65
+ const accountType = data.account?.type;
66
+ if (typeof installationId !== "number" || typeof accountLogin !== "string") {
67
+ logger.error({ data }, "Unexpected response format from GitHub API");
68
+ return {
69
+ success: false,
70
+ errorType: "api_error",
71
+ message: "Unexpected response format from GitHub API"
72
+ };
73
+ }
74
+ logger.info({
75
+ installationId,
76
+ accountLogin,
77
+ accountType,
78
+ repositoryOwner,
79
+ repositoryName
80
+ }, "Found GitHub App installation for repository");
81
+ return {
82
+ success: true,
83
+ installation: {
84
+ installationId,
85
+ accountLogin,
86
+ accountType: accountType === "Organization" ? "Organization" : "User"
87
+ }
88
+ };
89
+ } catch (error) {
90
+ const message = error instanceof Error ? error.message : "Unknown error";
91
+ logger.error({
92
+ error: message,
93
+ repositoryOwner,
94
+ repositoryName
95
+ }, "Error calling GitHub API to look up installation");
96
+ return {
97
+ success: false,
98
+ errorType: "api_error",
99
+ message: `Failed to connect to GitHub API: ${message}`
100
+ };
101
+ }
102
+ }
103
+ async function generateInstallationAccessToken(installationId) {
104
+ let appJwt;
105
+ try {
106
+ appJwt = await createAppJwt();
107
+ } catch (error) {
108
+ const message = error instanceof Error ? error.message : "Unknown error";
109
+ logger.error({ error: message }, "Failed to create GitHub App JWT for token generation");
110
+ return {
111
+ success: false,
112
+ errorType: "jwt_error",
113
+ message: `Failed to create GitHub App authentication: ${message}`
114
+ };
115
+ }
116
+ const url = `${GITHUB_API_BASE}/app/installations/${installationId}/access_tokens`;
117
+ try {
118
+ const response = await fetch(url, {
119
+ method: "POST",
120
+ headers: {
121
+ Authorization: `Bearer ${appJwt}`,
122
+ Accept: "application/vnd.github+json",
123
+ "X-GitHub-Api-Version": "2022-11-28",
124
+ "User-Agent": "inkeep-agents-api"
125
+ }
126
+ });
127
+ if (!response.ok) {
128
+ const errorText = await response.text();
129
+ logger.error({
130
+ status: response.status,
131
+ error: errorText,
132
+ installationId
133
+ }, "GitHub API error generating installation access token");
134
+ return {
135
+ success: false,
136
+ errorType: "api_error",
137
+ message: `GitHub API error (${response.status}): Failed to generate installation access token`
138
+ };
139
+ }
140
+ const data = await response.json();
141
+ const token = data.token;
142
+ const expiresAt = data.expires_at;
143
+ if (typeof token !== "string" || typeof expiresAt !== "string") {
144
+ logger.error({ data }, "Unexpected response format from GitHub API for token generation");
145
+ return {
146
+ success: false,
147
+ errorType: "api_error",
148
+ message: "Unexpected response format from GitHub API"
149
+ };
150
+ }
151
+ return {
152
+ success: true,
153
+ accessToken: {
154
+ token,
155
+ expiresAt
156
+ }
157
+ };
158
+ } catch (error) {
159
+ const message = error instanceof Error ? error.message : "Unknown error";
160
+ logger.error({
161
+ error: message,
162
+ installationId
163
+ }, "Error calling GitHub API to generate installation access token");
164
+ return {
165
+ success: false,
166
+ errorType: "api_error",
167
+ message: `Failed to connect to GitHub API: ${message}`
168
+ };
169
+ }
170
+ }
171
+ async function fetchInstallationDetails(installationId, appJwt) {
172
+ const url = `${GITHUB_API_BASE}/app/installations/${installationId}`;
173
+ try {
174
+ const response = await fetch(url, {
175
+ method: "GET",
176
+ headers: {
177
+ Authorization: `Bearer ${appJwt}`,
178
+ Accept: "application/vnd.github+json",
179
+ "X-GitHub-Api-Version": "2022-11-28",
180
+ "User-Agent": "inkeep-agents-api"
181
+ }
182
+ });
183
+ if (!response.ok) {
184
+ const errorText = await response.text();
185
+ logger.error({
186
+ status: response.status,
187
+ error: errorText,
188
+ installationId
189
+ }, "Failed to fetch installation details");
190
+ return {
191
+ success: false,
192
+ error: `GitHub API error: ${response.status}`,
193
+ status: response.status
194
+ };
195
+ }
196
+ return {
197
+ success: true,
198
+ installation: await response.json()
199
+ };
200
+ } catch (error) {
201
+ logger.error({
202
+ error,
203
+ installationId
204
+ }, "Error fetching installation details");
205
+ return {
206
+ success: false,
207
+ error: "Failed to connect to GitHub API",
208
+ status: 500
209
+ };
210
+ }
211
+ }
212
+ async function fetchInstallationRepositories(installationId, appJwt) {
213
+ const tokenUrl = `${GITHUB_API_BASE}/app/installations/${installationId}/access_tokens`;
214
+ try {
215
+ const tokenResponse = await fetch(tokenUrl, {
216
+ method: "POST",
217
+ headers: {
218
+ Authorization: `Bearer ${appJwt}`,
219
+ Accept: "application/vnd.github+json",
220
+ "X-GitHub-Api-Version": "2022-11-28",
221
+ "User-Agent": "inkeep-agents-api"
222
+ }
223
+ });
224
+ if (!tokenResponse.ok) {
225
+ const errorText = await tokenResponse.text();
226
+ logger.error({
227
+ status: tokenResponse.status,
228
+ error: errorText,
229
+ installationId
230
+ }, "Failed to get installation access token");
231
+ return {
232
+ success: false,
233
+ error: "Failed to get installation access token"
234
+ };
235
+ }
236
+ const installationToken = (await tokenResponse.json()).token;
237
+ const allRepositories = [];
238
+ let page = 1;
239
+ const perPage = 100;
240
+ while (true) {
241
+ const reposUrl = `${GITHUB_API_BASE}/installation/repositories?per_page=${perPage}&page=${page}`;
242
+ const reposResponse = await fetch(reposUrl, {
243
+ method: "GET",
244
+ headers: {
245
+ Authorization: `Bearer ${installationToken}`,
246
+ Accept: "application/vnd.github+json",
247
+ "X-GitHub-Api-Version": "2022-11-28",
248
+ "User-Agent": "inkeep-agents-api"
249
+ }
250
+ });
251
+ if (!reposResponse.ok) {
252
+ const errorText = await reposResponse.text();
253
+ logger.error({
254
+ status: reposResponse.status,
255
+ error: errorText,
256
+ installationId
257
+ }, "Failed to fetch repositories");
258
+ return {
259
+ success: false,
260
+ error: "Failed to fetch repositories"
261
+ };
262
+ }
263
+ const reposData = await reposResponse.json();
264
+ allRepositories.push(...reposData.repositories);
265
+ if (reposData.repositories.length < perPage) break;
266
+ page++;
267
+ }
268
+ return {
269
+ success: true,
270
+ repositories: allRepositories
271
+ };
272
+ } catch (error) {
273
+ logger.error({
274
+ error,
275
+ installationId
276
+ }, "Error fetching installation repositories");
277
+ return {
278
+ success: false,
279
+ error: "Failed to connect to GitHub API"
280
+ };
281
+ }
282
+ }
283
+ function determineStatus(setupAction) {
284
+ switch (setupAction) {
285
+ case "install":
286
+ case "update": return "active";
287
+ case "request": return "pending";
288
+ default: return "active";
289
+ }
290
+ }
291
+
292
+ //#endregion
293
+ export { createAppJwt, determineStatus, fetchInstallationDetails, fetchInstallationRepositories, generateInstallationAccessToken, lookupInstallationForRepo };