@geminixiang/mikan 1.0.0-beta.8 → 1.0.0-beta.9
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 +25 -0
- package/dist/adapter.d.ts +1 -1
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js.map +1 -1
- package/dist/adapters/github/bot.d.ts +23 -1
- package/dist/adapters/github/bot.d.ts.map +1 -1
- package/dist/adapters/github/bot.js +142 -5
- package/dist/adapters/github/bot.js.map +1 -1
- package/dist/adapters/github/client.d.ts +24 -1
- package/dist/adapters/github/client.d.ts.map +1 -1
- package/dist/adapters/github/client.js +45 -0
- package/dist/adapters/github/client.js.map +1 -1
- package/dist/adapters/github/context.d.ts.map +1 -1
- package/dist/adapters/github/context.js +9 -1
- package/dist/adapters/github/context.js.map +1 -1
- package/dist/adapters/github/repo.d.ts +19 -0
- package/dist/adapters/github/repo.d.ts.map +1 -0
- package/dist/adapters/github/repo.js +58 -0
- package/dist/adapters/github/repo.js.map +1 -0
- package/dist/adapters/github/types.d.ts +32 -0
- package/dist/adapters/github/types.d.ts.map +1 -1
- package/dist/adapters/github/types.js.map +1 -1
- package/dist/agent.d.ts +2 -2
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +10 -2
- package/dist/agent.js.map +1 -1
- package/dist/main.js +9 -0
- package/dist/main.js.map +1 -1
- package/dist/runtime/conversation-runtime.js +1 -1
- package/dist/runtime/conversation-runtime.js.map +1 -1
- package/dist/runtime/types.d.ts +3 -1
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/tools/github-pr.d.ts +22 -0
- package/dist/tools/github-pr.d.ts.map +1 -0
- package/dist/tools/github-pr.js +53 -0
- package/dist/tools/github-pr.js.map +1 -0
- package/dist/tools/index.d.ts +2 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +4 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/types.d.ts +19 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/adapters/github/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AASpC,MAAM,OAAO,cAAe,SAAQ,KAAK;IACvC,YACkB,MAAc,EAC9B,MAAc,EACd,IAAY,EACZ,MAAc;QAEd,KAAK,CAAC,UAAU,MAAM,IAAI,IAAI,gBAAgB,MAAM,KAAK,MAAM,EAAE,CAAC,CAAC;sBALnD,MAAM;QAMtB,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,GAAU;IAC5C,IAAI,CAAC,CAAC,GAAG,YAAY,cAAc,CAAC;QAAE,OAAO,KAAK,CAAC;IACnD,OAAO,GAAG,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,KAAK,GAAG,IAAI,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC;AACvF,CAAC;AAED,SAAS,SAAS,CAAC,IAAqB;IACtC,OAAO,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AACrF,CAAC;AAED,yEAAyE;AACzE,MAAM,uBAAuB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAE9C;;;;GAIG;AACH,MAAM,OAAO,YAAY;IASvB,YAAY,OAA4B;QAHhC,sBAAiB,GAAgD,IAAI,CAAC;QACtE,UAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;QAGxC,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CA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AAO,CAAC,OAAO,EAAE,UAAU,KAAK,IAAI,IAAI,oBAAoB,SAAS,EAAE,EAAE;YAClF,IAAI,EAAE,EAAE,IAAI,EAAE;SACf,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,KAAa,EAAE,IAAY,EAAE,SAAiB;QACrE,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,UAAU,KAAK,IAAI,IAAI,oBAAoB,SAAS,EAAE,CAAC,CAAC;IACvF,CAAC;IAED,KAAK,CAAC,qBAAqB,CACzB,KAAa,EACb,IAAY,EACZ,SAAiB,EACjB,OAA8B;QAE9B,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,UAAU,KAAK,IAAI,IAAI,oBAAoB,SAAS,YAAY,EAAE;YAC3F,IAAI,EAAE,EAAE,OAAO,EAAE;SAClB,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,mBAAmB,CACvB,KAAa,EACb,IAAY,EACZ,MAAc,EACd,OAA8B;QAE9B,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,UAAU,KAAK,IAAI,IAAI,WAAW,MAAM,YAAY,EAAE;YAC/E,IAAI,EAAE,EAAE,OAAO,EAAE;SAClB,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { createSign } from \"crypto\";\nimport type {\n GithubClientOptions,\n GithubIssue,\n GithubIssueComment,\n GithubReactionContent,\n GithubRepository,\n} from \"./types.js\";\n\nexport class GithubApiError extends Error {\n constructor(\n public readonly status: number,\n method: string,\n path: string,\n detail: string,\n ) {\n super(`GitHub ${method} ${path} failed with ${status}: ${detail}`);\n this.name = \"GithubApiError\";\n }\n}\n\n/**\n * GitHub rate-limit responses are 429, or 403 with a rate-limit message\n * (secondary limits). Used as the `withRetry` predicate.\n */\nexport function githubIsRateLimited(err: Error): boolean {\n if (!(err instanceof GithubApiError)) return false;\n return err.status === 429 || (err.status === 403 && /rate limit/i.test(err.message));\n}\n\nfunction base64Url(data: string | Buffer): string {\n return (typeof data === \"string\" ? Buffer.from(data) : data).toString(\"base64url\");\n}\n\n/** Refresh the cached installation token this long before it expires. */\nconst TOKEN_REFRESH_MARGIN_MS = 5 * 60 * 1000;\n\n/**\n * Minimal GitHub REST client authenticated as a GitHub App installation.\n * Mints short-lived installation tokens from an RS256 app JWT and supports\n * ETag conditional polling (304 responses don't count against the rate limit).\n */\nexport class GithubClient {\n private readonly appId: string;\n private readonly privateKey: string;\n private readonly installationId: string;\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n private installationToken: { value: string; expiresAt: number } | null = null;\n private etags = new Map<string, string>();\n\n constructor(options: GithubClientOptions) {\n this.appId = options.appId;\n this.privateKey = options.privateKey;\n this.installationId = options.installationId;\n this.baseUrl = (options.baseUrl ?? \"https://api.github.com\").replace(/\\/+$/, \"\");\n this.fetchImpl = options.fetchImpl ?? fetch;\n }\n\n /** Short-lived JWT identifying the App itself (not an installation). */\n private appJwt(): string {\n const now = Math.floor(Date.now() / 1000);\n const header = base64Url(JSON.stringify({ alg: \"RS256\", typ: \"JWT\" }));\n // 60s clock-drift backdate; GitHub caps exp at 10 minutes.\n const payload = base64Url(JSON.stringify({ iat: now - 60, exp: now + 540, iss: this.appId }));\n const signature = base64Url(\n createSign(\"RSA-SHA256\").update(`${header}.${payload}`).sign(this.privateKey),\n );\n return `${header}.${payload}.${signature}`;\n }\n\n private async getInstallationToken(): Promise<string> {\n const cached = this.installationToken;\n if (cached && Date.now() < cached.expiresAt - TOKEN_REFRESH_MARGIN_MS) {\n return cached.value;\n }\n const data = await this.rawRequest<{ token: string; expires_at: string }>(\n \"POST\",\n `/app/installations/${this.installationId}/access_tokens`,\n { auth: `Bearer ${this.appJwt()}` },\n );\n this.installationToken = { value: data!.token, expiresAt: Date.parse(data!.expires_at) };\n return this.installationToken.value;\n }\n\n private async rawRequest<T>(\n method: string,\n path: string,\n options: { auth: string; body?: unknown; conditional?: boolean },\n ): Promise<T | null> {\n const headers: Record<string, string> = {\n Accept: \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n \"User-Agent\": \"mikan\",\n Authorization: options.auth,\n };\n if (options.conditional) {\n const etag = this.etags.get(path);\n if (etag) headers[\"If-None-Match\"] = etag;\n }\n const response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n });\n if (response.status === 304) {\n return null;\n }\n if (!response.ok) {\n const detail = (await response.text().catch(() => \"\")).slice(0, 300);\n throw new GithubApiError(response.status, method, path, detail || response.statusText);\n }\n if (options.conditional) {\n const etag = response.headers.get(\"etag\");\n if (etag) this.etags.set(path, etag);\n }\n if (response.status === 204) {\n return null;\n }\n return (await response.json()) as T;\n }\n\n /**\n * Installation-authenticated request. `conditional` GETs return null on 304\n * (nothing changed since the last call to the same path).\n */\n private async request<T>(\n method: string,\n path: string,\n options: { body?: unknown; conditional?: boolean } = {},\n ): Promise<T | null> {\n const token = await this.getInstallationToken();\n return this.rawRequest<T>(method, path, { ...options, auth: `Bearer ${token}` });\n }\n\n /** The App's mention slug; its comments author as `<slug>[bot]`. */\n async getAppSlug(): Promise<string> {\n const app = await this.rawRequest<{ slug: string }>(\"GET\", \"/app\", {\n auth: `Bearer ${this.appJwt()}`,\n });\n return app!.slug;\n }\n\n async listInstallationRepositories(): Promise<GithubRepository[]> {\n const data = await this.request<{ repositories: GithubRepository[] }>(\n \"GET\",\n \"/installation/repositories?per_page=100\",\n );\n return data!.repositories;\n }\n\n /**\n * All issue/PR conversation comments in a repo updated at or after `since`,\n * oldest first. Returns null when nothing changed (ETag 304). Capped at one\n * page; the poll cursor advances to the newest item seen, so a burst larger\n * than 100 comments drains across consecutive polls.\n */\n async listIssueCommentsSince(\n owner: string,\n repo: string,\n since: string,\n ): Promise<GithubIssueComment[] | null> {\n return this.request<GithubIssueComment[]>(\n \"GET\",\n `/repos/${owner}/${repo}/issues/comments?sort=updated&direction=asc&since=${encodeURIComponent(since)}&per_page=100`,\n { conditional: true },\n );\n }\n\n /** Issues and PRs updated at or after `since` (GitHub lists PRs as issues). */\n async listIssuesSince(owner: string, repo: string, since: string): Promise<GithubIssue[] | null> {\n return this.request<GithubIssue[]>(\n \"GET\",\n `/repos/${owner}/${repo}/issues?state=all&sort=updated&direction=asc&since=${encodeURIComponent(since)}&per_page=100`,\n { conditional: true },\n );\n }\n\n async getIssue(owner: string, repo: string, number: number): Promise<GithubIssue> {\n const issue = await this.request<GithubIssue>(\n \"GET\",\n `/repos/${owner}/${repo}/issues/${number}`,\n );\n return issue!;\n }\n\n async createIssueComment(\n owner: string,\n repo: string,\n number: number,\n body: string,\n ): Promise<GithubIssueComment> {\n const comment = await this.request<GithubIssueComment>(\n \"POST\",\n `/repos/${owner}/${repo}/issues/${number}/comments`,\n { body: { body } },\n );\n return comment!;\n }\n\n async updateIssueComment(\n owner: string,\n repo: string,\n commentId: number,\n body: string,\n ): Promise<void> {\n await this.request(\"PATCH\", `/repos/${owner}/${repo}/issues/comments/${commentId}`, {\n body: { body },\n });\n }\n\n async deleteIssueComment(owner: string, repo: string, commentId: number): Promise<void> {\n await this.request(\"DELETE\", `/repos/${owner}/${repo}/issues/comments/${commentId}`);\n }\n\n async createCommentReaction(\n owner: string,\n repo: string,\n commentId: number,\n content: GithubReactionContent,\n ): Promise<void> {\n await this.request(\"POST\", `/repos/${owner}/${repo}/issues/comments/${commentId}/reactions`, {\n body: { content },\n });\n }\n\n async createIssueReaction(\n owner: string,\n repo: string,\n number: number,\n content: GithubReactionContent,\n ): Promise<void> {\n await this.request(\"POST\", `/repos/${owner}/${repo}/issues/${number}/reactions`, {\n body: { content },\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/adapters/github/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAapC,MAAM,OAAO,cAAe,SAAQ,KAAK;IACvC,YACkB,MAAc,EA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AAO,CAAC,OAAO,EAAE,UAAU,KAAK,IAAI,IAAI,oBAAoB,SAAS,EAAE,EAAE;YAClF,IAAI,EAAE,EAAE,IAAI,EAAE;SACf,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,KAAa,EAAE,IAAY,EAAE,SAAiB;QACrE,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,UAAU,KAAK,IAAI,IAAI,oBAAoB,SAAS,EAAE,CAAC,CAAC;IACvF,CAAC;IAED,KAAK,CAAC,qBAAqB,CACzB,KAAa,EACb,IAAY,EACZ,SAAiB,EACjB,OAA8B;QAE9B,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,UAAU,KAAK,IAAI,IAAI,oBAAoB,SAAS,YAAY,EAAE;YAC3F,IAAI,EAAE,EAAE,OAAO,EAAE;SAClB,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,mBAAmB,CACvB,KAAa,EACb,IAAY,EACZ,MAAc,EACd,OAA8B;QAE9B,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,UAAU,KAAK,IAAI,IAAI,WAAW,MAAM,YAAY,EAAE;YAC/E,IAAI,EAAE,EAAE,OAAO,EAAE;SAClB,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { createSign } from \"crypto\";\nimport type {\n GithubClientOptions,\n GithubCollaboratorPermission,\n GithubIssue,\n GithubIssueComment,\n GithubPullRequest,\n GithubReactionContent,\n GithubRepository,\n GithubRepositoryDetails,\n GithubTokenPermissions,\n} from \"./types.js\";\n\nexport class GithubApiError extends Error {\n constructor(\n public readonly status: number,\n method: string,\n path: string,\n detail: string,\n ) {\n super(`GitHub ${method} ${path} failed with ${status}: ${detail}`);\n this.name = \"GithubApiError\";\n }\n}\n\n/**\n * GitHub rate-limit responses are 429, or 403 with a rate-limit message\n * (secondary limits). Used as the `withRetry` predicate.\n */\nexport function githubIsRateLimited(err: Error): boolean {\n if (!(err instanceof GithubApiError)) return false;\n return err.status === 429 || (err.status === 403 && /rate limit/i.test(err.message));\n}\n\nfunction base64Url(data: string | Buffer): string {\n return (typeof data === \"string\" ? Buffer.from(data) : data).toString(\"base64url\");\n}\n\n/** Refresh the cached installation token this long before it expires. */\nconst TOKEN_REFRESH_MARGIN_MS = 5 * 60 * 1000;\n\n/**\n * Minimal GitHub REST client authenticated as a GitHub App installation.\n * Mints short-lived installation tokens from an RS256 app JWT and supports\n * ETag conditional polling (304 responses don't count against the rate limit).\n */\nexport class GithubClient {\n private readonly appId: string;\n private readonly privateKey: string;\n private readonly installationId: string;\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n private installationToken: { value: string; expiresAt: number } | null = null;\n private etags = new Map<string, string>();\n\n constructor(options: GithubClientOptions) {\n this.appId = options.appId;\n this.privateKey = options.privateKey;\n this.installationId = options.installationId;\n this.baseUrl = (options.baseUrl ?? \"https://api.github.com\").replace(/\\/+$/, \"\");\n this.fetchImpl = options.fetchImpl ?? fetch;\n }\n\n /** Short-lived JWT identifying the App itself (not an installation). */\n private appJwt(): string {\n const now = Math.floor(Date.now() / 1000);\n const header = base64Url(JSON.stringify({ alg: \"RS256\", typ: \"JWT\" }));\n // 60s clock-drift backdate; GitHub caps exp at 10 minutes.\n const payload = base64Url(JSON.stringify({ iat: now - 60, exp: now + 540, iss: this.appId }));\n const signature = base64Url(\n createSign(\"RSA-SHA256\").update(`${header}.${payload}`).sign(this.privateKey),\n );\n return `${header}.${payload}.${signature}`;\n }\n\n private async getInstallationToken(): Promise<string> {\n const cached = this.installationToken;\n if (cached && Date.now() < cached.expiresAt - TOKEN_REFRESH_MARGIN_MS) {\n return cached.value;\n }\n const data = await this.rawRequest<{ token: string; expires_at: string }>(\n \"POST\",\n `/app/installations/${this.installationId}/access_tokens`,\n { auth: `Bearer ${this.appJwt()}` },\n );\n this.installationToken = { value: data!.token, expiresAt: Date.parse(data!.expires_at) };\n return this.installationToken.value;\n }\n\n private async rawRequest<T>(\n method: string,\n path: string,\n options: { auth: string; body?: unknown; conditional?: boolean },\n ): Promise<T | null> {\n const headers: Record<string, string> = {\n Accept: \"application/vnd.github+json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n \"User-Agent\": \"mikan\",\n Authorization: options.auth,\n };\n if (options.conditional) {\n const etag = this.etags.get(path);\n if (etag) headers[\"If-None-Match\"] = etag;\n }\n const response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n });\n if (response.status === 304) {\n return null;\n }\n if (!response.ok) {\n const detail = (await response.text().catch(() => \"\")).slice(0, 300);\n throw new GithubApiError(response.status, method, path, detail || response.statusText);\n }\n if (options.conditional) {\n const etag = response.headers.get(\"etag\");\n if (etag) this.etags.set(path, etag);\n }\n if (response.status === 204) {\n return null;\n }\n return (await response.json()) as T;\n }\n\n /**\n * Installation-authenticated request. `conditional` GETs return null on 304\n * (nothing changed since the last call to the same path).\n */\n private async request<T>(\n method: string,\n path: string,\n options: { body?: unknown; conditional?: boolean } = {},\n ): Promise<T | null> {\n const token = await this.getInstallationToken();\n return this.rawRequest<T>(method, path, { ...options, auth: `Bearer ${token}` });\n }\n\n /** The App's mention slug; its comments author as `<slug>[bot]`. */\n async getAppSlug(): Promise<string> {\n const app = await this.rawRequest<{ slug: string }>(\"GET\", \"/app\", {\n auth: `Bearer ${this.appJwt()}`,\n });\n return app!.slug;\n }\n\n /** Database id of a user/bot login (for noreply commit-author emails). */\n async getUserId(login: string): Promise<number> {\n const user = await this.request<{ id: number }>(\"GET\", `/users/${encodeURIComponent(login)}`);\n return user!.id;\n }\n\n /**\n * Mint a one-off installation token narrowed to a single repo and an\n * explicit permission subset. Used for host-side git operations so the\n * broad installation identity never leaves this process.\n */\n async createScopedInstallationToken(\n repoName: string,\n permissions: GithubTokenPermissions,\n ): Promise<string> {\n const data = await this.rawRequest<{ token: string }>(\n \"POST\",\n `/app/installations/${this.installationId}/access_tokens`,\n {\n auth: `Bearer ${this.appJwt()}`,\n body: { repositories: [repoName], permissions },\n },\n );\n return data!.token;\n }\n\n async getRepository(owner: string, repo: string): Promise<GithubRepositoryDetails> {\n const details = await this.request<GithubRepositoryDetails>(\"GET\", `/repos/${owner}/${repo}`);\n return details!;\n }\n\n /**\n * A user's effective role on a repo: granular `role_name` plus the legacy\n * `permission` field (callers rank whichever is stronger, so custom roles\n * still resolve via their legacy mapping). Needs only Metadata: Read — the\n * mandatory App permission. Unknown users resolve to none.\n */\n async getCollaboratorPermission(\n owner: string,\n repo: string,\n username: string,\n ): Promise<GithubCollaboratorPermission> {\n try {\n const data = await this.request<GithubCollaboratorPermission>(\n \"GET\",\n `/repos/${owner}/${repo}/collaborators/${encodeURIComponent(username)}/permission`,\n );\n return data!;\n } catch (err) {\n if (err instanceof GithubApiError && err.status === 404) {\n return { permission: \"none\" };\n }\n throw err;\n }\n }\n\n async createPullRequest(\n owner: string,\n repo: string,\n params: { title: string; head: string; base: string; body?: string; draft?: boolean },\n ): Promise<GithubPullRequest> {\n const pr = await this.request<GithubPullRequest>(\"POST\", `/repos/${owner}/${repo}/pulls`, {\n body: params,\n });\n return pr!;\n }\n\n async listInstallationRepositories(): Promise<GithubRepository[]> {\n const data = await this.request<{ repositories: GithubRepository[] }>(\n \"GET\",\n \"/installation/repositories?per_page=100\",\n );\n return data!.repositories;\n }\n\n /**\n * All issue/PR conversation comments in a repo updated at or after `since`,\n * oldest first. Returns null when nothing changed (ETag 304). Capped at one\n * page; the poll cursor advances to the newest item seen, so a burst larger\n * than 100 comments drains across consecutive polls.\n */\n async listIssueCommentsSince(\n owner: string,\n repo: string,\n since: string,\n ): Promise<GithubIssueComment[] | null> {\n return this.request<GithubIssueComment[]>(\n \"GET\",\n `/repos/${owner}/${repo}/issues/comments?sort=updated&direction=asc&since=${encodeURIComponent(since)}&per_page=100`,\n { conditional: true },\n );\n }\n\n /** Issues and PRs updated at or after `since` (GitHub lists PRs as issues). */\n async listIssuesSince(owner: string, repo: string, since: string): Promise<GithubIssue[] | null> {\n return this.request<GithubIssue[]>(\n \"GET\",\n `/repos/${owner}/${repo}/issues?state=all&sort=updated&direction=asc&since=${encodeURIComponent(since)}&per_page=100`,\n { conditional: true },\n );\n }\n\n async getIssue(owner: string, repo: string, number: number): Promise<GithubIssue> {\n const issue = await this.request<GithubIssue>(\n \"GET\",\n `/repos/${owner}/${repo}/issues/${number}`,\n );\n return issue!;\n }\n\n async createIssueComment(\n owner: string,\n repo: string,\n number: number,\n body: string,\n ): Promise<GithubIssueComment> {\n const comment = await this.request<GithubIssueComment>(\n \"POST\",\n `/repos/${owner}/${repo}/issues/${number}/comments`,\n { body: { body } },\n );\n return comment!;\n }\n\n async updateIssueComment(\n owner: string,\n repo: string,\n commentId: number,\n body: string,\n ): Promise<void> {\n await this.request(\"PATCH\", `/repos/${owner}/${repo}/issues/comments/${commentId}`, {\n body: { body },\n });\n }\n\n async deleteIssueComment(owner: string, repo: string, commentId: number): Promise<void> {\n await this.request(\"DELETE\", `/repos/${owner}/${repo}/issues/comments/${commentId}`);\n }\n\n async createCommentReaction(\n owner: string,\n repo: string,\n commentId: number,\n content: GithubReactionContent,\n ): Promise<void> {\n await this.request(\"POST\", `/repos/${owner}/${repo}/issues/comments/${commentId}/reactions`, {\n body: { content },\n });\n }\n\n async createIssueReaction(\n owner: string,\n repo: string,\n number: number,\n content: GithubReactionContent,\n ): Promise<void> {\n await this.request(\"POST\", `/repos/${owner}/${repo}/issues/${number}/reactions`, {\n body: { content },\n });\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,mBAAmB,EACnB,qBAAqB,EACrB,aAAa,EACd,MAAM,kBAAkB,CAAC;AAS1B,OAAO,EAGL,KAAK,kBAAkB,EACxB,MAAM,UAAU,CAAC;AAElB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAiB9C,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,WAAW,EAClB,GAAG,EAAE,kBAAkB,GACtB;IACD,OAAO,EAAE,mBAAmB,CAAC;IAC7B,SAAS,EAAE,qBAAqB,CAAC;IACjC,QAAQ,EAAE,aAAa,CAAC;CACzB,
|
|
1
|
+
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,mBAAmB,EACnB,qBAAqB,EACrB,aAAa,EACd,MAAM,kBAAkB,CAAC;AAS1B,OAAO,EAGL,KAAK,kBAAkB,EACxB,MAAM,UAAU,CAAC;AAElB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAiB9C,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,WAAW,EAClB,GAAG,EAAE,kBAAkB,GACtB;IACD,OAAO,EAAE,mBAAmB,CAAC;IAC7B,SAAS,EAAE,qBAAqB,CAAC;IACjC,QAAQ,EAAE,aAAa,CAAC;CACzB,CAsMA"}
|
|
@@ -47,7 +47,15 @@ export function createGithubAdapters(event, bot) {
|
|
|
47
47
|
`## Conversation context\n` +
|
|
48
48
|
`This conversation IS GitHub issue/PR ${ref.owner}/${ref.repo}#${ref.number}: the ` +
|
|
49
49
|
`first message in the history is its title and body, and the following messages are ` +
|
|
50
|
-
`its comments. When the user says "this issue", they mean #${ref.number}
|
|
50
|
+
`its comments. When the user says "this issue", they mean #${ref.number}.\n\n` +
|
|
51
|
+
`## Repository & pull requests\n` +
|
|
52
|
+
`The repository is cloned at ./repo — a snapshot from this conversation's first ` +
|
|
53
|
+
`trigger. If this conversation is a pull request, its head is checked out as branch ` +
|
|
54
|
+
`pr-${ref.number}. You have no git credentials, so git fetch/push fail by design.\n` +
|
|
55
|
+
`To ship code changes: branch as pi/<name> inside ./repo, commit (the git author is ` +
|
|
56
|
+
`preconfigured), then call the github_pr tool to push the branch and open a pull ` +
|
|
57
|
+
`request (draft: true for a draft). You cannot push the default branch or merge — ` +
|
|
58
|
+
`humans review and merge every PR.`,
|
|
51
59
|
channels: [],
|
|
52
60
|
users: [],
|
|
53
61
|
diagnostics: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/adapters/github/context.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EACL,+BAA+B,EAC/B,cAAc,EACd,SAAS,GAEV,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,wBAAwB,EACxB,yBAAyB,GAE1B,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,yBAAyB,EAAE,MAAM,UAAU,CAAC;AAGrD,MAAM,uBAAuB,GAAG;;2FAE2D,CAAC;AAE5F,SAAS,gBAAgB,CAAC,MAAsB;IAC9C,MAAM,aAAa,GAAG,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAClD,MAAM,QAAQ,GAAG,CAAC,MAAM,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IACvD,IAAI,IAAI,GAAG,KAAK,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,QAAQ,IAAI,CAAC;IACzE,IAAI,MAAM,CAAC,KAAK;QAAE,IAAI,IAAI,KAAK,MAAM,CAAC,KAAK,EAAE,CAAC;IAC9C,IAAI,IAAI,KAAK,QAAQ,MAAM,CAAC;IAC5B,IAAI,aAAa;QAAE,IAAI,IAAI,WAAW,aAAa,YAAY,CAAC;IAChE,IAAI,IAAI,wBAAwB,MAAM,CAAC,MAAM,UAAU,CAAC;IACxD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,UAAU,oBAAoB,CAClC,KAAkB,EAClB,GAAuB;IAMvB,I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AC,cAAc,EAAE,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;QACzD,CAAC;QAED,cAAc,EAAE,KAAK,IAAI,EAAE;YACzB,aAAa,GAAG,aAAa,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE;gBAC5C,IAAI,SAAS,KAAK,IAAI,EAAE,CAAC;oBACvB,IAAI,CAAC;wBACH,MAAM,GAAG,CAAC,aAAa,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;oBAC1C,CAAC;oBAAC,MAAM,CAAC;wBACP,gBAAgB;oBAClB,CAAC;oBACD,SAAS,GAAG,IAAI,CAAC;gBACnB,CAAC;YACH,CAAC,CAAC,CAAC;YACH,MAAM,aAAa,CAAC;QACtB,CAAC;KACF,CAAC;IAEF,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC;AAC1C,CAAC","sourcesContent":["import type {\n ChatToolResult,\n ConversationMessage,\n ConversationResponder,\n MessagingInfo,\n} from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport { resolveChatSessionKey } from \"../../sessions/policy.js\";\nimport {\n createChatResponseErrorReporter,\n formatToolArgs,\n splitText,\n type ChatResponseErrorOperation,\n} from \"../shared.js\";\nimport {\n formatGithubContinuation,\n GITHUB_MAX_COMMENT_LENGTH,\n type GithubMessagingBot,\n} from \"./bot.js\";\nimport { parseGithubConversationId } from \"./ids.js\";\nimport type { GithubEvent } from \"./types.js\";\n\nconst GITHUB_FORMATTING_GUIDE = `## GitHub Formatting (GitHub Flavored Markdown)\nStandard Markdown plus tables, task lists, and fenced code blocks.\nReference issues/PRs as #123 and users as @login (mentions notify people — use sparingly).`;\n\nfunction formatToolResult(result: ChatToolResult): string {\n const argsFormatted = formatToolArgs(result.args);\n const duration = (result.durationMs / 1000).toFixed(1);\n let text = `**${result.isError ? \"Error\" : \"Done\"} ${result.toolName}**`;\n if (result.label) text += `: ${result.label}`;\n text += ` (${duration}s)\\n`;\n if (argsFormatted) text += `\\`\\`\\`\\n${argsFormatted}\\n\\`\\`\\`\\n`;\n text += `**Result:**\\n\\`\\`\\`\\n${result.result}\\n\\`\\`\\``;\n return text;\n}\n\nexport function createGithubAdapters(\n event: GithubEvent,\n bot: GithubMessagingBot,\n): {\n message: ConversationMessage;\n responder: ConversationResponder;\n platform: MessagingInfo;\n} {\n let commentId: number | null = null;\n let accumulatedText = \"\";\n let updatePromise = Promise.resolve();\n\n const conversationId = event.conversationId;\n const ref = parseGithubConversationId(conversationId);\n\n const message: ConversationMessage = {\n id: event.ts,\n sessionKey:\n event.sessionKey ??\n resolveChatSessionKey({\n conversationId,\n conversationKind: event.conversationKind,\n messageId: event.ts,\n persistentTopLevel: true,\n threadTs: event.thread_ts,\n }),\n conversationKind: event.conversationKind,\n userId: event.user,\n userName: event.userName,\n text: event.text,\n attachments: event.attachments,\n threadTs: event.thread_ts,\n };\n\n const platform: MessagingInfo = {\n name: \"github\",\n formattingGuide:\n `${GITHUB_FORMATTING_GUIDE}\\n\\n` +\n `## Conversation context\\n` +\n `This conversation IS GitHub issue/PR ${ref.owner}/${ref.repo}#${ref.number}: the ` +\n `first message in the history is its title and body, and the following messages are ` +\n `its comments. When the user says \"this issue\", they mean #${ref.number}.`,\n channels: [],\n users: [],\n diagnostics: {\n showUsageSummary: false,\n },\n };\n\n const reportResponseError = createChatResponseErrorReporter(() => ({\n platform: \"github\",\n conversationId,\n messageId: message.id,\n sessionKey: message.sessionKey,\n responseMessageId: commentId,\n conversationKind: message.conversationKind,\n }));\n\n async function postOrUpdateResponse(displayText: string): Promise<void> {\n if (commentId !== null) {\n await bot.updateMessage(conversationId, String(commentId), displayText);\n } else {\n commentId = await bot.postComment(ref, displayText);\n }\n }\n\n async function postSplitResponse(text: string): Promise<void> {\n const [displayText, ...extraParts] = splitText(\n text,\n GITHUB_MAX_COMMENT_LENGTH,\n formatGithubContinuation,\n );\n await postOrUpdateResponse(displayText);\n for (const part of extraParts) {\n await bot.postComment(ref, part);\n }\n }\n\n async function queueGithubResponse(\n label: string,\n operation: ChatResponseErrorOperation,\n work: () => Promise<void>,\n extra: () => Record<string, unknown>,\n ): Promise<void> {\n updatePromise = updatePromise.then(async () => {\n try {\n await work();\n } catch (err) {\n log.logWarning(`GitHub ${label} error`, err instanceof Error ? err.message : String(err));\n reportResponseError(err, operation, extra());\n }\n });\n await updatePromise;\n }\n\n // No appendResponseDelta/finishResponse: GitHub gets the finished response\n // in one comment. Streaming would edit the comment on every flush — API\n // churn and \"edited\" noise for readers who refresh rather than watch typing.\n const responder: ConversationResponder = {\n respond: async (text: string) => {\n await queueGithubResponse(\n \"respond\",\n \"respond\",\n async () => {\n accumulatedText = accumulatedText ? `${accumulatedText}\\n${text}` : text;\n await postSplitResponse(accumulatedText);\n if (commentId !== null) {\n bot.logBotResponse(conversationId, text, String(commentId));\n }\n },\n () => ({\n phase: commentId ? \"update\" : \"initial_post\",\n textLength: text.length,\n accumulatedLength: accumulatedText.length,\n }),\n );\n },\n\n replaceResponse: async (text: string) => {\n await queueGithubResponse(\n \"replaceResponse\",\n \"replace_response\",\n async () => {\n accumulatedText = text;\n await postSplitResponse(accumulatedText);\n },\n () => ({\n textLength: text.length,\n hadExistingResponse: Boolean(commentId),\n }),\n );\n },\n\n respondDiagnostic: async (text: string, options?: { style?: \"muted\" | \"error\" }) => {\n await queueGithubResponse(\n \"respondDiagnostic\",\n \"respond_diagnostic\",\n async () => {\n const prefix = options?.style === \"error\" ? \"**Error:** \" : \"\";\n for (const part of splitText(\n `${prefix}${text}`,\n GITHUB_MAX_COMMENT_LENGTH,\n formatGithubContinuation,\n )) {\n await bot.postComment(ref, part);\n }\n },\n () => ({ textLength: text.length, style: options?.style }),\n );\n },\n\n respondToolResult: async (result: ChatToolResult) => {\n await responder.respondDiagnostic(formatToolResult(result));\n },\n\n // GitHub has no typing indicator; progress shows through comment edits.\n setTyping: async () => {},\n\n setWorking: async () => {},\n\n uploadFile: async (filePath: string, title?: string) => {\n // The REST API cannot attach files to comments (uploads are a browser\n // feature); leave a pointer instead of failing the run.\n const name = title ?? filePath;\n await queueGithubResponse(\n \"uploadFile\",\n \"respond_diagnostic\",\n async () => {\n await bot.postComment(\n ref,\n `*(file \\`${name}\\` was produced, but the GitHub adapter cannot attach files to comments)*`,\n );\n },\n () => ({ filePath }),\n );\n },\n\n react: async (emoji: string) => {\n await bot.addReaction(conversationId, event.ts, emoji);\n },\n\n deleteResponse: async () => {\n updatePromise = updatePromise.then(async () => {\n if (commentId !== null) {\n try {\n await bot.deleteComment(ref, commentId);\n } catch {\n // Ignore errors\n }\n commentId = null;\n }\n });\n await updatePromise;\n },\n };\n\n return { message, responder, platform };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/adapters/github/context.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EACL,+BAA+B,EAC/B,cAAc,EACd,SAAS,GAEV,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,wBAAwB,EACxB,yBAAyB,GAE1B,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,yBAAyB,EAAE,MAAM,UAAU,CAAC;AAGrD,MAAM,uBAAuB,GAAG;;2FAE2D,CAAC;AAE5F,SAAS,gBAAgB,CAAC,MAAsB;IAC9C,MAAM,aAAa,GAAG,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAClD,MAAM,QAAQ,GAAG,CAAC,MAAM,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IACvD,IAAI,IAAI,GAAG,KAAK,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,QAAQ,IAAI,CAAC;IACzE,IAAI,MAAM,CAAC,KAAK;QAAE,IAAI,IAAI,KAAK,MAAM,CAAC,KAAK,EAAE,CAA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rD,sEAAsE;YACtE,wDAAwD;YACxD,MAAM,IAAI,GAAG,KAAK,IAAI,QAAQ,CAAC;YAC/B,MAAM,mBAAmB,CACvB,YAAY,EACZ,oBAAoB,EACpB,KAAK,IAAI,EAAE;gBACT,MAAM,GAAG,CAAC,WAAW,CACnB,GAAG,EACH,YAAY,IAAI,2EAA2E,CAC5F,CAAC;YACJ,CAAC,EACD,GAAG,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CACrB,CAAC;QACJ,CAAC;QAED,KAAK,EAAE,KAAK,EAAE,KAAa,EAAE,EAAE;YAC7B,MAAM,GAAG,CAAC,WAAW,CAAC,cAAc,EAAE,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;QACzD,CAAC;QAED,cAAc,EAAE,KAAK,IAAI,EAAE;YACzB,aAAa,GAAG,aAAa,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE;gBAC5C,IAAI,SAAS,KAAK,IAAI,EAAE,CAAC;oBACvB,IAAI,CAAC;wBACH,MAAM,GAAG,CAAC,aAAa,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;oBAC1C,CAAC;oBAAC,MAAM,CAAC;wBACP,gBAAgB;oBAClB,CAAC;oBACD,SAAS,GAAG,IAAI,CAAC;gBACnB,CAAC;YACH,CAAC,CAAC,CAAC;YACH,MAAM,aAAa,CAAC;QACtB,CAAC;KACF,CAAC;IAEF,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC;AAC1C,CAAC","sourcesContent":["import type {\n ChatToolResult,\n ConversationMessage,\n ConversationResponder,\n MessagingInfo,\n} from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport { resolveChatSessionKey } from \"../../sessions/policy.js\";\nimport {\n createChatResponseErrorReporter,\n formatToolArgs,\n splitText,\n type ChatResponseErrorOperation,\n} from \"../shared.js\";\nimport {\n formatGithubContinuation,\n GITHUB_MAX_COMMENT_LENGTH,\n type GithubMessagingBot,\n} from \"./bot.js\";\nimport { parseGithubConversationId } from \"./ids.js\";\nimport type { GithubEvent } from \"./types.js\";\n\nconst GITHUB_FORMATTING_GUIDE = `## GitHub Formatting (GitHub Flavored Markdown)\nStandard Markdown plus tables, task lists, and fenced code blocks.\nReference issues/PRs as #123 and users as @login (mentions notify people — use sparingly).`;\n\nfunction formatToolResult(result: ChatToolResult): string {\n const argsFormatted = formatToolArgs(result.args);\n const duration = (result.durationMs / 1000).toFixed(1);\n let text = `**${result.isError ? \"Error\" : \"Done\"} ${result.toolName}**`;\n if (result.label) text += `: ${result.label}`;\n text += ` (${duration}s)\\n`;\n if (argsFormatted) text += `\\`\\`\\`\\n${argsFormatted}\\n\\`\\`\\`\\n`;\n text += `**Result:**\\n\\`\\`\\`\\n${result.result}\\n\\`\\`\\``;\n return text;\n}\n\nexport function createGithubAdapters(\n event: GithubEvent,\n bot: GithubMessagingBot,\n): {\n message: ConversationMessage;\n responder: ConversationResponder;\n platform: MessagingInfo;\n} {\n let commentId: number | null = null;\n let accumulatedText = \"\";\n let updatePromise = Promise.resolve();\n\n const conversationId = event.conversationId;\n const ref = parseGithubConversationId(conversationId);\n\n const message: ConversationMessage = {\n id: event.ts,\n sessionKey:\n event.sessionKey ??\n resolveChatSessionKey({\n conversationId,\n conversationKind: event.conversationKind,\n messageId: event.ts,\n persistentTopLevel: true,\n threadTs: event.thread_ts,\n }),\n conversationKind: event.conversationKind,\n userId: event.user,\n userName: event.userName,\n text: event.text,\n attachments: event.attachments,\n threadTs: event.thread_ts,\n };\n\n const platform: MessagingInfo = {\n name: \"github\",\n formattingGuide:\n `${GITHUB_FORMATTING_GUIDE}\\n\\n` +\n `## Conversation context\\n` +\n `This conversation IS GitHub issue/PR ${ref.owner}/${ref.repo}#${ref.number}: the ` +\n `first message in the history is its title and body, and the following messages are ` +\n `its comments. When the user says \"this issue\", they mean #${ref.number}.\\n\\n` +\n `## Repository & pull requests\\n` +\n `The repository is cloned at ./repo — a snapshot from this conversation's first ` +\n `trigger. If this conversation is a pull request, its head is checked out as branch ` +\n `pr-${ref.number}. You have no git credentials, so git fetch/push fail by design.\\n` +\n `To ship code changes: branch as pi/<name> inside ./repo, commit (the git author is ` +\n `preconfigured), then call the github_pr tool to push the branch and open a pull ` +\n `request (draft: true for a draft). You cannot push the default branch or merge — ` +\n `humans review and merge every PR.`,\n channels: [],\n users: [],\n diagnostics: {\n showUsageSummary: false,\n },\n };\n\n const reportResponseError = createChatResponseErrorReporter(() => ({\n platform: \"github\",\n conversationId,\n messageId: message.id,\n sessionKey: message.sessionKey,\n responseMessageId: commentId,\n conversationKind: message.conversationKind,\n }));\n\n async function postOrUpdateResponse(displayText: string): Promise<void> {\n if (commentId !== null) {\n await bot.updateMessage(conversationId, String(commentId), displayText);\n } else {\n commentId = await bot.postComment(ref, displayText);\n }\n }\n\n async function postSplitResponse(text: string): Promise<void> {\n const [displayText, ...extraParts] = splitText(\n text,\n GITHUB_MAX_COMMENT_LENGTH,\n formatGithubContinuation,\n );\n await postOrUpdateResponse(displayText);\n for (const part of extraParts) {\n await bot.postComment(ref, part);\n }\n }\n\n async function queueGithubResponse(\n label: string,\n operation: ChatResponseErrorOperation,\n work: () => Promise<void>,\n extra: () => Record<string, unknown>,\n ): Promise<void> {\n updatePromise = updatePromise.then(async () => {\n try {\n await work();\n } catch (err) {\n log.logWarning(`GitHub ${label} error`, err instanceof Error ? err.message : String(err));\n reportResponseError(err, operation, extra());\n }\n });\n await updatePromise;\n }\n\n // No appendResponseDelta/finishResponse: GitHub gets the finished response\n // in one comment. Streaming would edit the comment on every flush — API\n // churn and \"edited\" noise for readers who refresh rather than watch typing.\n const responder: ConversationResponder = {\n respond: async (text: string) => {\n await queueGithubResponse(\n \"respond\",\n \"respond\",\n async () => {\n accumulatedText = accumulatedText ? `${accumulatedText}\\n${text}` : text;\n await postSplitResponse(accumulatedText);\n if (commentId !== null) {\n bot.logBotResponse(conversationId, text, String(commentId));\n }\n },\n () => ({\n phase: commentId ? \"update\" : \"initial_post\",\n textLength: text.length,\n accumulatedLength: accumulatedText.length,\n }),\n );\n },\n\n replaceResponse: async (text: string) => {\n await queueGithubResponse(\n \"replaceResponse\",\n \"replace_response\",\n async () => {\n accumulatedText = text;\n await postSplitResponse(accumulatedText);\n },\n () => ({\n textLength: text.length,\n hadExistingResponse: Boolean(commentId),\n }),\n );\n },\n\n respondDiagnostic: async (text: string, options?: { style?: \"muted\" | \"error\" }) => {\n await queueGithubResponse(\n \"respondDiagnostic\",\n \"respond_diagnostic\",\n async () => {\n const prefix = options?.style === \"error\" ? \"**Error:** \" : \"\";\n for (const part of splitText(\n `${prefix}${text}`,\n GITHUB_MAX_COMMENT_LENGTH,\n formatGithubContinuation,\n )) {\n await bot.postComment(ref, part);\n }\n },\n () => ({ textLength: text.length, style: options?.style }),\n );\n },\n\n respondToolResult: async (result: ChatToolResult) => {\n await responder.respondDiagnostic(formatToolResult(result));\n },\n\n // GitHub has no typing indicator; progress shows through comment edits.\n setTyping: async () => {},\n\n setWorking: async () => {},\n\n uploadFile: async (filePath: string, title?: string) => {\n // The REST API cannot attach files to comments (uploads are a browser\n // feature); leave a pointer instead of failing the run.\n const name = title ?? filePath;\n await queueGithubResponse(\n \"uploadFile\",\n \"respond_diagnostic\",\n async () => {\n await bot.postComment(\n ref,\n `*(file \\`${name}\\` was produced, but the GitHub adapter cannot attach files to comments)*`,\n );\n },\n () => ({ filePath }),\n );\n },\n\n react: async (emoji: string) => {\n await bot.addReaction(conversationId, event.ts, emoji);\n },\n\n deleteResponse: async () => {\n updatePromise = updatePromise.then(async () => {\n if (commentId !== null) {\n try {\n await bot.deleteComment(ref, commentId);\n } catch {\n // Ignore errors\n }\n commentId = null;\n }\n });\n await updatePromise;\n },\n };\n\n return { message, responder, platform };\n}\n"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { CloneRepoOptions, PushBranchOptions } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Branches the bot may push: `pi/<name>`. Everything else — including the
|
|
4
|
+
* repo's default branch by construction — is refused, so a driven agent can
|
|
5
|
+
* only ever produce reviewable branches, never touch mainline directly.
|
|
6
|
+
*/
|
|
7
|
+
export declare const GITHUB_PUSH_BRANCH_PATTERN: RegExp;
|
|
8
|
+
/**
|
|
9
|
+
* Shallow-clone a repo into a conversation dir and preconfigure the bot's
|
|
10
|
+
* commit identity. For PR conversations, additionally fetch the PR head and
|
|
11
|
+
* check it out as `pr-<number>` so the agent starts on the code under review.
|
|
12
|
+
*/
|
|
13
|
+
export declare function cloneRepo(options: CloneRepoOptions): Promise<void>;
|
|
14
|
+
/**
|
|
15
|
+
* Push one local branch to origin. Non-force by construction (plain refspec),
|
|
16
|
+
* and only `pi/*` branches are accepted.
|
|
17
|
+
*/
|
|
18
|
+
export declare function pushBranch(options: PushBranchOptions): Promise<void>;
|
|
19
|
+
//# sourceMappingURL=repo.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"repo.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/repo.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAMtE;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,QAAwC,CAAC;AAoBhF;;;;GAIG;AACH,wBAAsB,SAAS,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAWxE;AAED;;;GAGG;AACH,wBAAsB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAa1E"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { execFile } from "child_process";
|
|
2
|
+
import { promisify } from "util";
|
|
3
|
+
const execFileAsync = promisify(execFile);
|
|
4
|
+
const GIT_TIMEOUT_MS = 120_000;
|
|
5
|
+
/**
|
|
6
|
+
* Branches the bot may push: `pi/<name>`. Everything else — including the
|
|
7
|
+
* repo's default branch by construction — is refused, so a driven agent can
|
|
8
|
+
* only ever produce reviewable branches, never touch mainline directly.
|
|
9
|
+
*/
|
|
10
|
+
export const GITHUB_PUSH_BRANCH_PATTERN = /^pi\/[A-Za-z0-9._][A-Za-z0-9._/-]*$/;
|
|
11
|
+
/**
|
|
12
|
+
* Pass the ephemeral token as a per-invocation header, never in the remote
|
|
13
|
+
* URL: nothing credential-shaped may end up in `.git/config`, which lives in
|
|
14
|
+
* the conversation dir and is bind-mounted into the sandbox.
|
|
15
|
+
*/
|
|
16
|
+
function gitAuthArgs(token) {
|
|
17
|
+
const basic = Buffer.from(`x-access-token:${token}`).toString("base64");
|
|
18
|
+
return ["-c", `http.extraheader=Authorization: basic ${basic}`];
|
|
19
|
+
}
|
|
20
|
+
async function git(args, token) {
|
|
21
|
+
const { stdout } = await execFileAsync("git", [...(token ? gitAuthArgs(token) : []), ...args], {
|
|
22
|
+
timeout: GIT_TIMEOUT_MS,
|
|
23
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
|
|
24
|
+
});
|
|
25
|
+
return stdout;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Shallow-clone a repo into a conversation dir and preconfigure the bot's
|
|
29
|
+
* commit identity. For PR conversations, additionally fetch the PR head and
|
|
30
|
+
* check it out as `pr-<number>` so the agent starts on the code under review.
|
|
31
|
+
*/
|
|
32
|
+
export async function cloneRepo(options) {
|
|
33
|
+
await git(["clone", "--depth", "50", options.url, options.dir], options.token);
|
|
34
|
+
await git(["-C", options.dir, "config", "user.name", options.botLogin]);
|
|
35
|
+
await git(["-C", options.dir, "config", "user.email", options.botEmail]);
|
|
36
|
+
if (options.prNumber !== undefined) {
|
|
37
|
+
await git(["-C", options.dir, "fetch", "--depth", "50", "origin", `pull/${options.prNumber}/head`], options.token);
|
|
38
|
+
await git(["-C", options.dir, "checkout", "-B", `pr-${options.prNumber}`, "FETCH_HEAD"]);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Push one local branch to origin. Non-force by construction (plain refspec),
|
|
43
|
+
* and only `pi/*` branches are accepted.
|
|
44
|
+
*/
|
|
45
|
+
export async function pushBranch(options) {
|
|
46
|
+
const { dir, branch, token } = options;
|
|
47
|
+
if (!GITHUB_PUSH_BRANCH_PATTERN.test(branch)) {
|
|
48
|
+
throw new Error(`Refusing to push branch '${branch}': only branches matching pi/<name> may be pushed.`);
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
await git(["-C", dir, "rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
throw new Error(`Branch '${branch}' does not exist in the conversation's ./repo clone.`);
|
|
55
|
+
}
|
|
56
|
+
await git(["-C", dir, "push", "origin", `refs/heads/${branch}:refs/heads/${branch}`], token);
|
|
57
|
+
}
|
|
58
|
+
//# sourceMappingURL=repo.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"repo.js","sourceRoot":"","sources":["../../../src/adapters/github/repo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAGjC,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;AAE1C,MAAM,cAAc,GAAG,OAAO,CAAC;AAE/B;;;;GAIG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,qCAAqC,CAAC;AAEhF;;;;GAIG;AACH,SAAS,WAAW,CAAC,KAAa;IAChC,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,kBAAkB,KAAK,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IACxE,OAAO,CAAC,IAAI,EAAE,yCAAyC,KAAK,EAAE,CAAC,CAAC;AAClE,CAAC;AAED,KAAK,UAAU,GAAG,CAAC,IAAc,EAAE,KAAc;IAC/C,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM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AK,UAAU,UAAU,CAAC,OAA0B;IACzD,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;IACvC,IAAI,CAAC,0BAA0B,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7C,MAAM,IAAI,KAAK,CACb,4BAA4B,MAAM,oDAAoD,CACvF,CAAC;IACJ,CAAC;IACD,IAAI,CAAC;QACH,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,cAAc,MAAM,EAAE,CAAC,CAAC,CAAC;IACrF,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,KAAK,CAAC,WAAW,MAAM,sDAAsD,CAAC,CAAC;IAC3F,CAAC;IACD,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,MAAM,eAAe,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;AAC/F,CAAC","sourcesContent":["import { execFile } from \"child_process\";\nimport { promisify } from \"util\";\nimport type { CloneRepoOptions, PushBranchOptions } from \"./types.js\";\n\nconst execFileAsync = promisify(execFile);\n\nconst GIT_TIMEOUT_MS = 120_000;\n\n/**\n * Branches the bot may push: `pi/<name>`. Everything else — including the\n * repo's default branch by construction — is refused, so a driven agent can\n * only ever produce reviewable branches, never touch mainline directly.\n */\nexport const GITHUB_PUSH_BRANCH_PATTERN = /^pi\\/[A-Za-z0-9._][A-Za-z0-9._/-]*$/;\n\n/**\n * Pass the ephemeral token as a per-invocation header, never in the remote\n * URL: nothing credential-shaped may end up in `.git/config`, which lives in\n * the conversation dir and is bind-mounted into the sandbox.\n */\nfunction gitAuthArgs(token: string): string[] {\n const basic = Buffer.from(`x-access-token:${token}`).toString(\"base64\");\n return [\"-c\", `http.extraheader=Authorization: basic ${basic}`];\n}\n\nasync function git(args: string[], token?: string): Promise<string> {\n const { stdout } = await execFileAsync(\"git\", [...(token ? gitAuthArgs(token) : []), ...args], {\n timeout: GIT_TIMEOUT_MS,\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n });\n return stdout;\n}\n\n/**\n * Shallow-clone a repo into a conversation dir and preconfigure the bot's\n * commit identity. For PR conversations, additionally fetch the PR head and\n * check it out as `pr-<number>` so the agent starts on the code under review.\n */\nexport async function cloneRepo(options: CloneRepoOptions): Promise<void> {\n await git([\"clone\", \"--depth\", \"50\", options.url, options.dir], options.token);\n await git([\"-C\", options.dir, \"config\", \"user.name\", options.botLogin]);\n await git([\"-C\", options.dir, \"config\", \"user.email\", options.botEmail]);\n if (options.prNumber !== undefined) {\n await git(\n [\"-C\", options.dir, \"fetch\", \"--depth\", \"50\", \"origin\", `pull/${options.prNumber}/head`],\n options.token,\n );\n await git([\"-C\", options.dir, \"checkout\", \"-B\", `pr-${options.prNumber}`, \"FETCH_HEAD\"]);\n }\n}\n\n/**\n * Push one local branch to origin. Non-force by construction (plain refspec),\n * and only `pi/*` branches are accepted.\n */\nexport async function pushBranch(options: PushBranchOptions): Promise<void> {\n const { dir, branch, token } = options;\n if (!GITHUB_PUSH_BRANCH_PATTERN.test(branch)) {\n throw new Error(\n `Refusing to push branch '${branch}': only branches matching pi/<name> may be pushed.`,\n );\n }\n try {\n await git([\"-C\", dir, \"rev-parse\", \"--verify\", \"--quiet\", `refs/heads/${branch}`]);\n } catch {\n throw new Error(`Branch '${branch}' does not exist in the conversation's ./repo clone.`);\n }\n await git([\"-C\", dir, \"push\", \"origin\", `refs/heads/${branch}:refs/heads/${branch}`], token);\n}\n"]}
|
|
@@ -66,7 +66,39 @@ export interface GithubRepository {
|
|
|
66
66
|
name: string;
|
|
67
67
|
owner: GithubUser;
|
|
68
68
|
}
|
|
69
|
+
export interface GithubRepositoryDetails {
|
|
70
|
+
default_branch: string;
|
|
71
|
+
}
|
|
72
|
+
export interface GithubCollaboratorPermission {
|
|
73
|
+
/** Legacy field: admin | write | read | none (maintain→write, triage→read). */
|
|
74
|
+
permission: string;
|
|
75
|
+
/** Granular assigned role (admin/maintain/write/triage/read or a custom role). */
|
|
76
|
+
role_name?: string;
|
|
77
|
+
}
|
|
78
|
+
export interface GithubPullRequest {
|
|
79
|
+
number: number;
|
|
80
|
+
html_url: string;
|
|
81
|
+
}
|
|
82
|
+
/** Permission subset requestable on a scoped installation token. */
|
|
83
|
+
export type GithubTokenPermissions = Partial<Record<"contents" | "pull_requests" | "issues", "read" | "write">>;
|
|
69
84
|
export type GithubReactionContent = "+1" | "-1" | "laugh" | "confused" | "heart" | "hooray" | "rocket" | "eyes";
|
|
85
|
+
export interface CloneRepoOptions {
|
|
86
|
+
/** HTTPS remote, e.g. https://github.com/owner/repo.git (no credentials). */
|
|
87
|
+
url: string;
|
|
88
|
+
/** Destination directory (the conversation dir's `repo/`). */
|
|
89
|
+
dir: string;
|
|
90
|
+
/** Ephemeral scoped installation token; used per-invocation, never stored. */
|
|
91
|
+
token: string;
|
|
92
|
+
botLogin: string;
|
|
93
|
+
botEmail: string;
|
|
94
|
+
/** When the conversation is a PR: fetch and checkout its head as pr-<n>. */
|
|
95
|
+
prNumber?: number;
|
|
96
|
+
}
|
|
97
|
+
export interface PushBranchOptions {
|
|
98
|
+
dir: string;
|
|
99
|
+
branch: string;
|
|
100
|
+
token: string;
|
|
101
|
+
}
|
|
70
102
|
export interface GithubClientOptions {
|
|
71
103
|
appId: string;
|
|
72
104
|
privateKey: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAE1D,MAAM,WAAW,WAAY,SAAQ,iBAAiB;IACpD,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,eAAe;IAC9B,KAAK,EAAE,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EAAE,MAAM,CAAC;CAClB;AAED,oEAAoE;AACpE,MAAM,MAAM,sBAAsB,GAAG,OAAO,CAC1C,MAAM,CAAC,UAAU,GAAG,eAAe,GAAG,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,CAClE,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAC7B,IAAI,GACJ,IAAI,GACJ,OAAO,GACP,UAAU,GACV,OAAO,GACP,QAAQ,GACR,QAAQ,GACR,MAAM,CAAC;AAEX,MAAM,WAAW,gBAAgB;IAC/B,6EAA6E;IAC7E,GAAG,EAAE,MAAM,CAAC;IACZ,8DAA8D;IAC9D,GAAG,EAAE,MAAM,CAAC;IACZ,8EAA8E;IAC9E,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,4EAA4E;IAC5E,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,iBAAiB;IAChC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,EAAE,MAAM,CAAC;IACvB,0EAA0E;IAC1E,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;CAC1B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/adapters/github/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ConversationEvent } from \"../../adapter.js\";\n\nexport interface GithubEvent extends ConversationEvent {\n type: \"message\" | \"issue\";\n userName?: string;\n}\n\nexport interface GithubBotConfig {\n appId: string;\n /** PEM-encoded GitHub App private key. */\n privateKey: string;\n installationId: string;\n /** `owner/repo` entries to watch; empty = all installation repositories. */\n repos: string[];\n pollIntervalMs: number;\n workingDir: string;\n /**\n * Where the poll watermark state (baseline + seen ids) is persisted. Lives\n * under the host-only state dir: the workspace dir can be mounted into\n * sandboxes, and sandboxed code must not be able to clear dedup state and\n * re-trigger runs.\n */\n syncStatePath: string;\n}\n\n/** Persisted per-repo poll watermark (DESIGN.md § Event source). */\ninterface GithubRepoSyncState {\n /** Comments/issues created before this ISO instant never trigger. */\n baseline: string;\n /** Newest updated_at seen; polls fetch from (cursor - overlap). */\n cursor: string;\n seenComments: number[];\n seenIssues: number[];\n}\n\nexport interface GithubSyncState {\n repos: Record<string, GithubRepoSyncState>;\n}\n\nexport interface GithubRepoRef {\n owner: string;\n repo: string;\n}\n\nexport interface GithubConversationRef extends GithubRepoRef {\n number: number;\n}\n\n// ── GitHub REST payload shapes (only the fields mikan reads) ─────────────────\n\ninterface GithubUser {\n login: string;\n type: string;\n}\n\nexport interface GithubIssue {\n id: number;\n number: number;\n title: string;\n body: string | null;\n user: GithubUser;\n created_at: string;\n updated_at: string;\n pull_request?: object;\n}\n\nexport interface GithubIssueComment {\n id: number;\n body: string;\n user: GithubUser;\n created_at: string;\n updated_at: string;\n /** API URL of the parent issue, e.g. …/repos/o/r/issues/42 */\n issue_url: string;\n}\n\nexport interface GithubRepository {\n name: string;\n owner: GithubUser;\n}\n\nexport type GithubReactionContent =\n | \"+1\"\n | \"-1\"\n | \"laugh\"\n | \"confused\"\n | \"heart\"\n | \"hooray\"\n | \"rocket\"\n | \"eyes\";\n\nexport interface GithubClientOptions {\n appId: string;\n privateKey: string;\n installationId: string;\n /** Override the API root for tests; defaults to https://api.github.com */\n baseUrl?: string;\n fetchImpl?: typeof fetch;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/adapters/github/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ConversationEvent } from \"../../adapter.js\";\n\nexport interface GithubEvent extends ConversationEvent {\n type: \"message\" | \"issue\";\n userName?: string;\n}\n\nexport interface GithubBotConfig {\n appId: string;\n /** PEM-encoded GitHub App private key. */\n privateKey: string;\n installationId: string;\n /** `owner/repo` entries to watch; empty = all installation repositories. */\n repos: string[];\n pollIntervalMs: number;\n workingDir: string;\n /**\n * Where the poll watermark state (baseline + seen ids) is persisted. Lives\n * under the host-only state dir: the workspace dir can be mounted into\n * sandboxes, and sandboxed code must not be able to clear dedup state and\n * re-trigger runs.\n */\n syncStatePath: string;\n}\n\n/** Persisted per-repo poll watermark (DESIGN.md § Event source). */\ninterface GithubRepoSyncState {\n /** Comments/issues created before this ISO instant never trigger. */\n baseline: string;\n /** Newest updated_at seen; polls fetch from (cursor - overlap). */\n cursor: string;\n seenComments: number[];\n seenIssues: number[];\n}\n\nexport interface GithubSyncState {\n repos: Record<string, GithubRepoSyncState>;\n}\n\nexport interface GithubRepoRef {\n owner: string;\n repo: string;\n}\n\nexport interface GithubConversationRef extends GithubRepoRef {\n number: number;\n}\n\n// ── GitHub REST payload shapes (only the fields mikan reads) ─────────────────\n\ninterface GithubUser {\n login: string;\n type: string;\n}\n\nexport interface GithubIssue {\n id: number;\n number: number;\n title: string;\n body: string | null;\n user: GithubUser;\n created_at: string;\n updated_at: string;\n pull_request?: object;\n}\n\nexport interface GithubIssueComment {\n id: number;\n body: string;\n user: GithubUser;\n created_at: string;\n updated_at: string;\n /** API URL of the parent issue, e.g. …/repos/o/r/issues/42 */\n issue_url: string;\n}\n\nexport interface GithubRepository {\n name: string;\n owner: GithubUser;\n}\n\nexport interface GithubRepositoryDetails {\n default_branch: string;\n}\n\nexport interface GithubCollaboratorPermission {\n /** Legacy field: admin | write | read | none (maintain→write, triage→read). */\n permission: string;\n /** Granular assigned role (admin/maintain/write/triage/read or a custom role). */\n role_name?: string;\n}\n\nexport interface GithubPullRequest {\n number: number;\n html_url: string;\n}\n\n/** Permission subset requestable on a scoped installation token. */\nexport type GithubTokenPermissions = Partial<\n Record<\"contents\" | \"pull_requests\" | \"issues\", \"read\" | \"write\">\n>;\n\nexport type GithubReactionContent =\n | \"+1\"\n | \"-1\"\n | \"laugh\"\n | \"confused\"\n | \"heart\"\n | \"hooray\"\n | \"rocket\"\n | \"eyes\";\n\nexport interface CloneRepoOptions {\n /** HTTPS remote, e.g. https://github.com/owner/repo.git (no credentials). */\n url: string;\n /** Destination directory (the conversation dir's `repo/`). */\n dir: string;\n /** Ephemeral scoped installation token; used per-invocation, never stored. */\n token: string;\n botLogin: string;\n botEmail: string;\n /** When the conversation is a PR: fetch and checkout its head as pr-<n>. */\n prNumber?: number;\n}\n\nexport interface PushBranchOptions {\n dir: string;\n branch: string;\n token: string;\n}\n\nexport interface GithubClientOptions {\n appId: string;\n privateKey: string;\n installationId: string;\n /** Override the API root for tests; defaults to https://api.github.com */\n baseUrl?: string;\n fetchImpl?: typeof fetch;\n}\n"]}
|
package/dist/agent.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type ImageContent } from "@earendil-works/pi-ai";
|
|
2
2
|
import type { ConversationMessage } from "./adapter.js";
|
|
3
|
-
import type { PlatformNotifier, PlatformReactor } from "./types.js";
|
|
3
|
+
import type { PlatformNotifier, PlatformPrCreator, PlatformReactor } from "./types.js";
|
|
4
4
|
import type { SessionViewTokenStoreLike } from "./commands/types.js";
|
|
5
5
|
import type { DockerContainerManager } from "./provisioner.js";
|
|
6
6
|
import { type RuntimePathContext, type SandboxConfig } from "./sandbox/index.js";
|
|
@@ -33,7 +33,7 @@ export declare function appendTriggerAttribution(text: string, triggerAttributio
|
|
|
33
33
|
export declare function createRunner(sandboxConfig: SandboxConfig, sessionKey: string, conversationId: string, conversationDir: string, workspaceDir: string, sessionScope: ResolvedSessionScope, vaultManager?: VaultManager, provisioner?: DockerContainerManager, sessionView?: {
|
|
34
34
|
tokenStore: SessionViewTokenStoreLike;
|
|
35
35
|
portalBaseUrl?: string;
|
|
36
|
-
}, platformNotifier?: PlatformNotifier, platformReactor?: PlatformReactor): Promise<PiAgentWrapper>;
|
|
36
|
+
}, platformNotifier?: PlatformNotifier, platformReactor?: PlatformReactor, platformPrCreator?: PlatformPrCreator): Promise<PiAgentWrapper>;
|
|
37
37
|
export declare function translateRuntimePathToHost(runtimePath: string, pathContext: RuntimePathContext): string;
|
|
38
38
|
export declare function translateAttachPathToHost(filePath: string, pathContext: RuntimePathContext): string;
|
|
39
39
|
//# sourceMappingURL=agent.d.ts.map
|
package/dist/agent.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AACA,OAAO,EAAY,KAAK,YAAY,EAAc,MAAM,uBAAuB,CAAC;AAkBhF,OAAO,KAAK,EACV,mBAAmB,EAKpB,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AACA,OAAO,EAAY,KAAK,YAAY,EAAc,MAAM,uBAAuB,CAAC;AAkBhF,OAAO,KAAK,EACV,mBAAmB,EAKpB,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAKV,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,EAChB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAMrE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAGL,KAAK,kBAAkB,EACvB,KAAK,aAAa,EACnB,MAAM,oBAAoB,CAAC;AAO5B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAGL,KAAK,oBAAoB,EAE1B,MAAM,qBAAqB,CAAC;AAQ7B,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAyIjD,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,IAAI,CAAC,mB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ED,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,MAAM,EAChB,WAAW,EAAE,kBAAkB,GAC9B,MAAM,CAKR"}
|
package/dist/agent.js
CHANGED
|
@@ -794,6 +794,12 @@ async function prepareRunContext(params) {
|
|
|
794
794
|
// (interactive turns on platforms with reaction support); otherwise unset
|
|
795
795
|
// so the tool reports it is unavailable rather than silently no-op'ing.
|
|
796
796
|
setReactFunction(responder.react ? async (emoji) => responder.react(emoji) : null);
|
|
797
|
+
// github_pr is available only in GitHub conversations with a wired creator;
|
|
798
|
+
// everywhere else the tool reports itself unavailable.
|
|
799
|
+
const { platformPrCreator, setGithubPrFunction } = params;
|
|
800
|
+
setGithubPrFunction(platform.name === "github" && platformPrCreator
|
|
801
|
+
? (request) => platformPrCreator(conversationId, request)
|
|
802
|
+
: null);
|
|
797
803
|
resetRunState(runState, responder, sessionConversation, message.userName, sessionUuid, triggerAttribution);
|
|
798
804
|
const runQueue = createRunQueue(responder, runState);
|
|
799
805
|
runState.queue = runQueue.queue;
|
|
@@ -1109,13 +1115,13 @@ function extractToolResultText(result) {
|
|
|
1109
1115
|
* Runner caching is handled by the caller (channelStates in main.ts).
|
|
1110
1116
|
* This is a stateless factory function.
|
|
1111
1117
|
*/
|
|
1112
|
-
export async function createRunner(sandboxConfig, sessionKey, conversationId, conversationDir, workspaceDir, sessionScope, vaultManager, provisioner, sessionView, platformNotifier, platformReactor) {
|
|
1118
|
+
export async function createRunner(sandboxConfig, sessionKey, conversationId, conversationDir, workspaceDir, sessionScope, vaultManager, provisioner, sessionView, platformNotifier, platformReactor, platformPrCreator) {
|
|
1113
1119
|
const agentConfig = resolveConversationSettings(conversationDir);
|
|
1114
1120
|
const workspaceBase = join(conversationDir, "..");
|
|
1115
1121
|
const { executionResolver, executor, getPathContext, resolveExecutorForRun } = createRunnerExecutionContext(sandboxConfig, vaultManager, provisioner, workspaceDir, workspaceBase);
|
|
1116
1122
|
let pathContext = getUnresolvedSandboxPathContext(sandboxConfig, workspaceBase);
|
|
1117
1123
|
// Create tools (per-runner, with per-runner upload function setter)
|
|
1118
|
-
const { tools, setUploadFunction, setReactFunction, setEventContext, setSandboxContext } = createMikanTools(executor, workspaceDir, { sandbox: sandboxConfig, provisioner });
|
|
1124
|
+
const { tools, setUploadFunction, setReactFunction, setGithubPrFunction, setEventContext, setSandboxContext, } = createMikanTools(executor, workspaceDir, { sandbox: sandboxConfig, provisioner });
|
|
1119
1125
|
const modelRegistry = MikanModels.create();
|
|
1120
1126
|
if (modelRegistry.getError()) {
|
|
1121
1127
|
log.logWarning("models.json load error", modelRegistry.getError());
|
|
@@ -1187,6 +1193,8 @@ export async function createRunner(sandboxConfig, sessionKey, conversationId, co
|
|
|
1187
1193
|
setSandboxContext,
|
|
1188
1194
|
setUploadFunction,
|
|
1189
1195
|
setReactFunction,
|
|
1196
|
+
setGithubPrFunction,
|
|
1197
|
+
platformPrCreator,
|
|
1190
1198
|
pathContext,
|
|
1191
1199
|
});
|
|
1192
1200
|
pathContext = prepared.pathContext;
|