@cursor/july 0.1.62 → 0.1.73

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.
Files changed (286) hide show
  1. package/AGENTS.md +4 -5
  2. package/README.md +23 -11
  3. package/dist/bin/agent-serve.js +11 -2
  4. package/dist/channels/github/api.d.ts +2 -0
  5. package/dist/channels/github/api.d.ts.map +1 -1
  6. package/dist/channels/github/api.js +2 -1
  7. package/dist/channels/github/binding.d.ts +7 -0
  8. package/dist/channels/github/binding.d.ts.map +1 -1
  9. package/dist/channels/github/binding.js +4 -0
  10. package/dist/channels/github/checks.d.ts +99 -0
  11. package/dist/channels/github/checks.d.ts.map +1 -0
  12. package/dist/channels/github/checks.js +108 -0
  13. package/dist/channels/github/cursor-account.d.ts +4 -4
  14. package/dist/channels/github/cursor-account.d.ts.map +1 -1
  15. package/dist/channels/github/cursor-account.js +7 -5
  16. package/dist/channels/github/index.d.ts +1 -0
  17. package/dist/channels/github/index.d.ts.map +1 -1
  18. package/dist/channels/github/index.js +1 -0
  19. package/dist/channels/github/types.d.ts +8 -0
  20. package/dist/channels/github/types.d.ts.map +1 -1
  21. package/dist/channels/slack/channel-watch.d.ts +2 -1
  22. package/dist/channels/slack/channel-watch.d.ts.map +1 -1
  23. package/dist/channels/slack/channel-watch.js +7 -3
  24. package/dist/channels/slack/dispatch.d.ts +9 -0
  25. package/dist/channels/slack/dispatch.d.ts.map +1 -1
  26. package/dist/channels/slack/dispatch.js +41 -21
  27. package/dist/channels/slack/manifest.d.ts +2 -2
  28. package/dist/channels/slack/manifest.d.ts.map +1 -1
  29. package/dist/channels/slack/manifest.js +14 -11
  30. package/dist/channels/slack/nudge-store.d.ts +16 -0
  31. package/dist/channels/slack/nudge-store.d.ts.map +1 -1
  32. package/dist/channels/slack/nudge-store.js +53 -0
  33. package/dist/channels/slack/slack-channel.d.ts.map +1 -1
  34. package/dist/channels/slack/slack-channel.js +4 -1
  35. package/dist/channels/slack/types.d.ts +24 -7
  36. package/dist/channels/slack/types.d.ts.map +1 -1
  37. package/dist/connections.d.ts +17 -5
  38. package/dist/connections.d.ts.map +1 -1
  39. package/dist/connections.js +17 -5
  40. package/dist/docs/404.html +2 -2
  41. package/dist/docs/ab.html +3 -3
  42. package/dist/docs/assets/{app.B-biogkN.js → app.CdbcFD8T.js} +1 -1
  43. package/dist/docs/assets/chunks/@localSearchIndexroot.DQad--_z.js +1 -0
  44. package/dist/docs/assets/chunks/{VPLocalSearchBox.DZqKtFZS.js → VPLocalSearchBox.D_NKImM7.js} +1 -1
  45. package/dist/docs/assets/chunks/{theme.BwC5zP2r.js → theme.CMvz7cu9.js} +2 -2
  46. package/dist/docs/assets/{concepts.md.CqOsxbMU.js → concepts.md.BXAm6G-C.js} +1 -1
  47. package/dist/docs/assets/{guides_mcp-oauth.md.C7G7IykG.js → guides_mcp-oauth.md.CzEB6RaG.js} +1 -1
  48. package/dist/docs/assets/{reference_agent-config.md.DHkkvcEZ.js → reference_agent-config.md.BZnEKfEc.js} +3 -4
  49. package/dist/docs/assets/{reference_agent-config.md.DHkkvcEZ.lean.js → reference_agent-config.md.BZnEKfEc.lean.js} +1 -1
  50. package/dist/docs/assets/{reference_connections.md.CSQiNzre.js → reference_connections.md.Cu3N-S3Q.js} +26 -9
  51. package/dist/docs/assets/reference_connections.md.Cu3N-S3Q.lean.js +1 -0
  52. package/dist/docs/assets/{reference_sessions.md.DBVFi2Sx.js → reference_sessions.md.B0DdlM-K.js} +1 -1
  53. package/dist/docs/assets/{reference_tools.md.kJfJAP2m.js → reference_tools.md.DTg_kEsx.js} +2 -2
  54. package/dist/docs/assets/{reference_tools.md.kJfJAP2m.lean.js → reference_tools.md.DTg_kEsx.lean.js} +1 -1
  55. package/dist/docs/assets/troubleshooting.md.DQ-hYuZT.js +1 -0
  56. package/dist/docs/building-with-agents.html +3 -3
  57. package/dist/docs/concepts.html +5 -5
  58. package/dist/docs/deployment.html +3 -3
  59. package/dist/docs/evals.html +3 -3
  60. package/dist/docs/example-agents/approval-buddy.html +3 -3
  61. package/dist/docs/example-agents/benny.html +3 -3
  62. package/dist/docs/example-agents/bugbot.html +3 -3
  63. package/dist/docs/example-agents/codebase-wiki.html +3 -3
  64. package/dist/docs/example-agents/codeowners-review.html +3 -3
  65. package/dist/docs/example-agents/concierge.html +3 -3
  66. package/dist/docs/example-agents/fsd.html +3 -3
  67. package/dist/docs/example-agents/index.html +3 -3
  68. package/dist/docs/example-agents/knowledge-base.html +3 -3
  69. package/dist/docs/example-agents/oncall.html +3 -3
  70. package/dist/docs/example-agents/security-reviewer.html +3 -3
  71. package/dist/docs/example-agents/slack-agent.html +3 -3
  72. package/dist/docs/example-agents/weather-agent.html +3 -3
  73. package/dist/docs/guides/agent-to-agent.html +3 -3
  74. package/dist/docs/guides/cloud-runtime.html +3 -3
  75. package/dist/docs/guides/convert-automation.html +3 -3
  76. package/dist/docs/guides/github.html +3 -3
  77. package/dist/docs/guides/human-in-the-loop.html +3 -3
  78. package/dist/docs/guides/mcp-oauth.html +5 -5
  79. package/dist/docs/guides/opentelemetry.html +3 -3
  80. package/dist/docs/guides/slack.html +3 -3
  81. package/dist/docs/guides/webhooks.html +3 -3
  82. package/dist/docs/hashmap.json +1 -1
  83. package/dist/docs/hillclimbing.html +3 -3
  84. package/dist/docs/index.html +3 -3
  85. package/dist/docs/quickstart.html +3 -3
  86. package/dist/docs/reference/agent-config.html +5 -6
  87. package/dist/docs/reference/artifacts.html +3 -3
  88. package/dist/docs/reference/channels.html +3 -3
  89. package/dist/docs/reference/cli.html +3 -3
  90. package/dist/docs/reference/connections.html +28 -11
  91. package/dist/docs/reference/hooks.html +3 -3
  92. package/dist/docs/reference/http-api.html +3 -3
  93. package/dist/docs/reference/instructions.html +3 -3
  94. package/dist/docs/reference/playground.html +3 -3
  95. package/dist/docs/reference/project-layout.html +3 -3
  96. package/dist/docs/reference/prompt.html +3 -3
  97. package/dist/docs/reference/schedules.html +3 -3
  98. package/dist/docs/reference/sessions.html +5 -5
  99. package/dist/docs/reference/skills.html +3 -3
  100. package/dist/docs/reference/subagents.html +3 -3
  101. package/dist/docs/reference/tools.html +5 -5
  102. package/dist/docs/scaffolding-agents.html +3 -3
  103. package/dist/docs/storage.html +3 -3
  104. package/dist/docs/templates/agentic-owners.html +3 -3
  105. package/dist/docs/templates/demo.html +3 -3
  106. package/dist/docs/templates/pr-autofixer.html +3 -3
  107. package/dist/docs/templates/security-reviewer.html +3 -3
  108. package/dist/docs/templates/triage.html +3 -3
  109. package/dist/docs/troubleshooting.html +5 -5
  110. package/dist/files-backends/agent-store-presigned-url.js +1 -1
  111. package/dist/index.d.ts +2 -2
  112. package/dist/index.d.ts.map +1 -1
  113. package/dist/index.js +1 -1
  114. package/dist/internal/advertise-tools.d.ts +79 -0
  115. package/dist/internal/advertise-tools.d.ts.map +1 -0
  116. package/dist/internal/advertise-tools.js +185 -0
  117. package/dist/internal/cli-deploy.d.ts.map +1 -1
  118. package/dist/internal/cli-deploy.js +7 -1
  119. package/dist/internal/cli-manifest.d.ts +19 -0
  120. package/dist/internal/cli-manifest.d.ts.map +1 -0
  121. package/dist/internal/cli-manifest.js +49 -0
  122. package/dist/internal/cli-slack.d.ts.map +1 -1
  123. package/dist/internal/cli-slack.js +9 -1
  124. package/dist/internal/convert-automation/convert-workflow.d.ts.map +1 -1
  125. package/dist/internal/convert-automation/convert-workflow.js +2 -10
  126. package/dist/internal/cursor/account-mcp.d.ts +29 -3
  127. package/dist/internal/cursor/account-mcp.d.ts.map +1 -1
  128. package/dist/internal/cursor/account-mcp.js +147 -67
  129. package/dist/internal/cursor/backend-client.d.ts +11 -6
  130. package/dist/internal/cursor/backend-client.d.ts.map +1 -1
  131. package/dist/internal/cursor/backend-client.js +32 -10
  132. package/dist/internal/cursor-account-mcp-auth.d.ts +11 -0
  133. package/dist/internal/cursor-account-mcp-auth.d.ts.map +1 -1
  134. package/dist/internal/cursor-account-mcp-auth.js +69 -0
  135. package/dist/internal/cursor-agent-template.d.ts +9 -0
  136. package/dist/internal/cursor-agent-template.d.ts.map +1 -0
  137. package/dist/internal/cursor-agent-template.js +37 -0
  138. package/dist/internal/deploy-client.d.ts +1 -0
  139. package/dist/internal/deploy-client.d.ts.map +1 -1
  140. package/dist/internal/deploy-client.js +18 -2
  141. package/dist/internal/deploy-manifest.d.ts +76 -0
  142. package/dist/internal/deploy-manifest.d.ts.map +1 -0
  143. package/dist/internal/deploy-manifest.js +117 -0
  144. package/dist/internal/deployment-scm-event-stream.d.ts +116 -0
  145. package/dist/internal/deployment-scm-event-stream.d.ts.map +1 -0
  146. package/dist/internal/deployment-scm-event-stream.js +474 -0
  147. package/dist/internal/discovery.d.ts.map +1 -1
  148. package/dist/internal/discovery.js +111 -10
  149. package/dist/internal/init-project.d.ts.map +1 -1
  150. package/dist/internal/init-project.js +12 -123
  151. package/dist/internal/init-scaffold.d.ts +8 -0
  152. package/dist/internal/init-scaffold.d.ts.map +1 -0
  153. package/dist/internal/init-scaffold.js +168 -0
  154. package/dist/internal/inline-stdio-mcp.d.ts +2 -0
  155. package/dist/internal/inline-stdio-mcp.d.ts.map +1 -1
  156. package/dist/internal/inline-stdio-mcp.js +10 -8
  157. package/dist/internal/json-schema.d.ts +7 -0
  158. package/dist/internal/json-schema.d.ts.map +1 -1
  159. package/dist/internal/json-schema.js +18 -3
  160. package/dist/internal/mcp-endpoint.js +7 -7
  161. package/dist/internal/mcp-host.d.ts +18 -0
  162. package/dist/internal/mcp-host.d.ts.map +1 -1
  163. package/dist/internal/mcp-host.js +43 -5
  164. package/dist/internal/mcp-oauth.d.ts +22 -0
  165. package/dist/internal/mcp-oauth.d.ts.map +1 -1
  166. package/dist/internal/mcp-oauth.js +40 -1
  167. package/dist/internal/package-inline-stdio.d.ts.map +1 -1
  168. package/dist/internal/package-inline-stdio.js +5 -5
  169. package/dist/internal/review-comments.d.ts +97 -0
  170. package/dist/internal/review-comments.d.ts.map +1 -1
  171. package/dist/internal/review-comments.js +151 -0
  172. package/dist/internal/sanitize-mcp-tool-name.d.ts +20 -0
  173. package/dist/internal/sanitize-mcp-tool-name.d.ts.map +1 -0
  174. package/dist/internal/sanitize-mcp-tool-name.js +30 -0
  175. package/dist/internal/sdk-runner.d.ts +1 -1
  176. package/dist/internal/sdk-runner.d.ts.map +1 -1
  177. package/dist/internal/sdk-runner.js +36 -13
  178. package/dist/internal/server.d.ts.map +1 -1
  179. package/dist/internal/server.js +18 -0
  180. package/dist/internal/session-engine.d.ts +66 -0
  181. package/dist/internal/session-engine.d.ts.map +1 -1
  182. package/dist/internal/session-engine.js +428 -110
  183. package/dist/internal/shallow-clone.d.ts +170 -0
  184. package/dist/internal/shallow-clone.d.ts.map +1 -0
  185. package/dist/internal/shallow-clone.js +412 -0
  186. package/dist/internal/slack-provision-client.d.ts +2 -0
  187. package/dist/internal/slack-provision-client.d.ts.map +1 -1
  188. package/dist/internal/slack-provision-client.js +1 -0
  189. package/dist/internal/terminal-style.d.ts +18 -0
  190. package/dist/internal/terminal-style.d.ts.map +1 -1
  191. package/dist/internal/terminal-style.js +46 -1
  192. package/dist/internal/turn-lease-store.d.ts +44 -0
  193. package/dist/internal/turn-lease-store.d.ts.map +1 -0
  194. package/dist/internal/turn-lease-store.js +139 -0
  195. package/dist/internal/workspace.d.ts +14 -0
  196. package/dist/internal/workspace.d.ts.map +1 -1
  197. package/dist/internal/workspace.js +33 -0
  198. package/dist/playground/assets/index-77uhu5Kr.css +1 -0
  199. package/dist/playground/assets/index-D4buox4m.js +85 -0
  200. package/dist/playground/index.html +2 -2
  201. package/dist/storage-protocol.d.ts +122 -0
  202. package/dist/storage-protocol.d.ts.map +1 -0
  203. package/dist/storage-protocol.js +173 -0
  204. package/dist/storage.d.ts +2 -72
  205. package/dist/storage.d.ts.map +1 -1
  206. package/dist/storage.js +2 -82
  207. package/dist/tools.d.ts +7 -0
  208. package/dist/tools.d.ts.map +1 -1
  209. package/dist/types.d.ts +141 -6
  210. package/dist/types.d.ts.map +1 -1
  211. package/docs/concepts.md +4 -4
  212. package/docs/guides/mcp-oauth.md +3 -1
  213. package/docs/reference/agent-config.md +11 -12
  214. package/docs/reference/connections.md +108 -10
  215. package/docs/reference/sessions.md +2 -2
  216. package/docs/reference/tools.md +14 -0
  217. package/docs/troubleshooting.md +3 -2
  218. package/package.json +7 -2
  219. package/skills/create-agent/SKILL.md +12 -9
  220. package/skills/debug/SKILL.md +2 -1
  221. package/skills/framework-map/SKILL.md +6 -6
  222. package/skills/mcp-auth/SKILL.md +8 -6
  223. package/src/bin/agent-serve.ts +12 -2
  224. package/src/channels/github/api.ts +6 -1
  225. package/src/channels/github/binding.ts +21 -0
  226. package/src/channels/github/checks.ts +179 -0
  227. package/src/channels/github/cursor-account.ts +9 -6
  228. package/src/channels/github/index.ts +1 -0
  229. package/src/channels/github/types.ts +8 -0
  230. package/src/channels/slack/channel-watch.ts +6 -3
  231. package/src/channels/slack/dispatch.ts +40 -3
  232. package/src/channels/slack/manifest.ts +9 -10
  233. package/src/channels/slack/nudge-store.ts +56 -0
  234. package/src/channels/slack/slack-channel.ts +3 -0
  235. package/src/channels/slack/types.ts +24 -7
  236. package/src/connections.ts +17 -5
  237. package/src/index.ts +5 -0
  238. package/src/internal/advertise-tools.ts +278 -0
  239. package/src/internal/cli-deploy.ts +11 -1
  240. package/src/internal/cli-manifest.ts +63 -0
  241. package/src/internal/cli-slack.ts +10 -1
  242. package/src/internal/convert-automation/convert-workflow.ts +2 -11
  243. package/src/internal/cursor/account-mcp.ts +208 -73
  244. package/src/internal/cursor/backend-client.ts +45 -11
  245. package/src/internal/cursor-account-mcp-auth.ts +83 -0
  246. package/src/internal/cursor-agent-template.ts +46 -0
  247. package/src/internal/deploy-client.ts +25 -6
  248. package/src/internal/deploy-manifest.ts +161 -0
  249. package/src/internal/deployment-scm-event-stream.ts +593 -0
  250. package/src/internal/discovery.ts +132 -3
  251. package/src/internal/init-project.ts +18 -153
  252. package/src/internal/init-scaffold.ts +176 -0
  253. package/src/internal/inline-stdio-mcp.ts +13 -0
  254. package/src/internal/json-schema.ts +24 -3
  255. package/src/internal/mcp-endpoint.ts +6 -0
  256. package/src/internal/mcp-host.ts +70 -9
  257. package/src/internal/mcp-oauth.ts +55 -1
  258. package/src/internal/package-inline-stdio.ts +5 -1
  259. package/src/internal/review-comments.ts +245 -0
  260. package/src/internal/sanitize-mcp-tool-name.ts +33 -0
  261. package/src/internal/sdk-runner.ts +50 -11
  262. package/src/internal/server.ts +19 -0
  263. package/src/internal/session-engine.ts +392 -19
  264. package/src/internal/shallow-clone.ts +595 -0
  265. package/src/internal/slack-provision-client.ts +3 -0
  266. package/src/internal/terminal-style.ts +67 -1
  267. package/src/internal/turn-lease-store.ts +147 -0
  268. package/src/internal/workspace.ts +33 -0
  269. package/src/storage-protocol.ts +247 -0
  270. package/src/storage.ts +16 -110
  271. package/src/tools.ts +7 -0
  272. package/src/types.ts +149 -7
  273. package/templates/agentic-owners/agent/agent.ts +3 -0
  274. package/templates/demo/agent/agent.ts +3 -0
  275. package/templates/pr-autofixer/agent/lib/drive-schemas.ts +4 -1
  276. package/templates/security-reviewer/agent/agent.ts +3 -0
  277. package/templates/triage/agent/agent.ts +3 -0
  278. package/dist/docs/assets/chunks/@localSearchIndexroot.5ozYNf74.js +0 -1
  279. package/dist/docs/assets/reference_connections.md.CSQiNzre.lean.js +0 -1
  280. package/dist/docs/assets/troubleshooting.md.CuVztCKs.js +0 -1
  281. package/dist/playground/assets/index-B4rcOgeP.css +0 -1
  282. package/dist/playground/assets/index-DXcY42Jv.js +0 -85
  283. /package/dist/docs/assets/{concepts.md.CqOsxbMU.lean.js → concepts.md.BXAm6G-C.lean.js} +0 -0
  284. /package/dist/docs/assets/{guides_mcp-oauth.md.C7G7IykG.lean.js → guides_mcp-oauth.md.CzEB6RaG.lean.js} +0 -0
  285. /package/dist/docs/assets/{reference_sessions.md.DBVFi2Sx.lean.js → reference_sessions.md.B0DdlM-K.lean.js} +0 -0
  286. /package/dist/docs/assets/{troubleshooting.md.CuVztCKs.lean.js → troubleshooting.md.DQ-hYuZT.lean.js} +0 -0
@@ -0,0 +1,595 @@
1
+ import { execFile } from "node:child_process";
2
+ import { mkdirSync, rmSync } from "node:fs";
3
+ import { promisify } from "node:util";
4
+
5
+ const execFileAsync = promisify(execFile);
6
+
7
+ /**
8
+ * Shallow SCM PR checkout for SDK agents that review a PR's code.
9
+ *
10
+ * Mirrors Bugbot's `shallow_fetch` prefetch strategy
11
+ * (`backend/crates/napi_bugbot/src/temp_clone.rs`): instead of cloning the
12
+ * whole repository, run a single `git fetch --depth=1 --no-tags origin <head>
13
+ * <merge_base>` into a fresh checkout so the agents get the PR head working
14
+ * tree (plus the merge-base commit for `git diff baseSha headSha`) with one
15
+ * bounded network round-trip. Bugbot keeps a bare `--filter=tree:0` partial
16
+ * clone because its tools stream objects on demand; SDK agents read a real
17
+ * working tree, so we materialize the head checkout instead.
18
+ *
19
+ * SCM support follows Bugbot's provider seam (`IGitProvider.getCloneTarget`
20
+ * / the Rust `clone_url` dispatch): everything provider-specific — remote
21
+ * URL shape, git credential username convention, PR head ref layout — lives
22
+ * in one {@link ScmCloneTarget} produced by {@link resolveScmCloneTarget}.
23
+ * Supporting another SCM (GitLab, Bitbucket, …) means adding a resolver
24
+ * case and a default credential source; the fetch/verify/checkout machinery
25
+ * is provider-agnostic.
26
+ *
27
+ * Auth also mirrors Bugbot (`IGitProvider.getAccessToken` → token handed
28
+ * straight to git): the clone takes one explicit repo-scoped bearer token.
29
+ * For GitHub the default source is the serve host's Cursor-account lease —
30
+ * the same backend `GithubAccessService` mint Bugbot uses — which
31
+ * `CursorGithubCredentialProvider` installs as `GH_TOKEN` for child
32
+ * processes. Where Bugbot embeds the token in the clone URL, this module
33
+ * serves it through an inline credential helper that reads a child-process
34
+ * env var, so the token never lands in argv or in `.git/config` inside a
35
+ * working tree that untrusted PR code later executes in.
36
+ *
37
+ * INTERNAL: first-party host plumbing shared by agents in `factory/*` (e.g.
38
+ * the security reviewer's `prepare_review` stage). Consumed via relative
39
+ * source imports, following `tenant-mcp/run-mcp-registry.ts`.
40
+ */
41
+
42
+ /** SCMs with shallow-clone support. */
43
+ export type ScmProvider = "github";
44
+
45
+ /**
46
+ * Everything git needs to clone one SCM's PR head. Provider-specific
47
+ * conventions live here and nowhere else.
48
+ */
49
+ export type ScmCloneTarget = {
50
+ provider: ScmProvider;
51
+ /** `owner/name` — used for logs and error messages. */
52
+ repo: string;
53
+ prNumber: number;
54
+ /** HTTPS remote to fetch from. */
55
+ remoteUrl: string;
56
+ /** Username paired with the bearer token for git-over-HTTPS basic auth. */
57
+ credentialUsername: string;
58
+ /**
59
+ * Server-advertised PR head ref (e.g. GitHub `refs/pull/<n>/head`,
60
+ * GitLab `refs/merge-requests/<n>/head`) — the fallback when the pinned
61
+ * SHA cannot be fetched directly.
62
+ */
63
+ prHeadRef: string;
64
+ };
65
+
66
+ /**
67
+ * Resolve a PR URL to its clone target, or `undefined` when the SCM has no
68
+ * shallow-clone support (callers then review on their fallback checkout —
69
+ * e.g. Origin PRs, where the host checkout already is the reviewed repo).
70
+ */
71
+ export function resolveScmCloneTarget(
72
+ prUrl: string
73
+ ): ScmCloneTarget | undefined {
74
+ let url: URL;
75
+ try {
76
+ url = new URL(prUrl);
77
+ } catch {
78
+ return undefined;
79
+ }
80
+ const parts = url.pathname.split("/").filter(Boolean);
81
+ if (
82
+ url.hostname === "github.com" &&
83
+ parts.length >= 4 &&
84
+ parts[2] === "pull" &&
85
+ Number.isInteger(Number(parts[3]))
86
+ ) {
87
+ const repo = `${parts[0]}/${parts[1]}`;
88
+ const prNumber = Number(parts[3]);
89
+ return {
90
+ provider: "github",
91
+ repo,
92
+ prNumber,
93
+ remoteUrl: `https://github.com/${repo}.git`,
94
+ credentialUsername: "x-access-token",
95
+ prHeadRef: `refs/pull/${prNumber}/head`,
96
+ };
97
+ }
98
+ return undefined;
99
+ }
100
+
101
+ /** Repo-scoped bearer for git-over-HTTPS. */
102
+ export type ShallowCloneAuth = {
103
+ token: string;
104
+ };
105
+
106
+ /**
107
+ * Default GitHub clone credential: the serve host's Cursor-account lease.
108
+ * `CursorGithubCredentialProvider` mints it repo-scoped from the backend and
109
+ * keeps `GH_TOKEN` refreshed for child processes; `GITHUB_TOKEN` covers
110
+ * local/CI runs that export the conventional variable instead.
111
+ */
112
+ export function serveHostGithubAuth(
113
+ env: NodeJS.ProcessEnv = process.env
114
+ ): ShallowCloneAuth | undefined {
115
+ const token = (env.GH_TOKEN ?? env.GITHUB_TOKEN ?? "").trim();
116
+ return token === "" ? undefined : { token };
117
+ }
118
+
119
+ /** Pair the provider's git-over-HTTPS username with the bearer token. */
120
+ function cloneCredential(
121
+ target: ScmCloneTarget,
122
+ auth: ShallowCloneAuth | undefined
123
+ ): GitCredential | undefined {
124
+ return auth === undefined
125
+ ? undefined
126
+ : { username: target.credentialUsername, token: auth.token };
127
+ }
128
+
129
+ /** Default clone credential source per provider. */
130
+ function defaultCloneAuth(
131
+ target: ScmCloneTarget
132
+ ): ShallowCloneAuth | undefined {
133
+ switch (target.provider) {
134
+ case "github":
135
+ return serveHostGithubAuth();
136
+ }
137
+ }
138
+
139
+ /** Cap on diff text handed to a model; beyond this it is truncated. */
140
+ const DIFF_MAX_CHARS = 80_000;
141
+
142
+ export type CommitRangeDiff =
143
+ | { status: "ok"; diff: string }
144
+ | { status: "unavailable"; reason: string };
145
+
146
+ /**
147
+ * Diff two commits inside an existing shallow PR checkout, fetching either
148
+ * end on demand when the shallow history does not already contain it.
149
+ *
150
+ * Lives here because it needs the same authenticated git the clone uses —
151
+ * a `--depth=1` checkout usually lacks the older commit, so reading a range
152
+ * means another credentialed fetch. Never throws: every failure becomes an
153
+ * `unavailable` reason the caller can act on or surface.
154
+ */
155
+ export async function tryDiffCommitRange(args: {
156
+ /** Existing checkout to run git in (see {@link createShallowPrCheckout}). */
157
+ checkoutDir: string;
158
+ /** The checkout's clone target; supplies the remote's ref + auth conventions. */
159
+ target: ScmCloneTarget;
160
+ from: string;
161
+ to: string;
162
+ /** Restrict the diff to one path when set. */
163
+ file?: string | undefined;
164
+ /** Fetch credential; defaults to the target provider's credential source. */
165
+ auth?: ShallowCloneAuth | undefined;
166
+ }): Promise<CommitRangeDiff> {
167
+ if (!isFullCommitSha(args.from) || !isFullCommitSha(args.to)) {
168
+ return {
169
+ status: "unavailable",
170
+ reason:
171
+ "Could not compute a reliable diff because a commit SHA was not a full 40-character SHA.",
172
+ };
173
+ }
174
+ const credential = cloneCredential(
175
+ args.target,
176
+ args.auth ?? defaultCloneAuth(args.target)
177
+ );
178
+ for (const sha of [args.from, args.to]) {
179
+ if (
180
+ !(await ensureCommitFetched(
181
+ args.checkoutDir,
182
+ sha,
183
+ args.target,
184
+ credential
185
+ ))
186
+ ) {
187
+ return {
188
+ status: "unavailable",
189
+ reason:
190
+ "Could not compute a reliable diff because a commit was unavailable in the checkout.",
191
+ };
192
+ }
193
+ }
194
+ try {
195
+ const diff = await git(args.checkoutDir, [
196
+ "diff",
197
+ "--no-ext-diff",
198
+ "--unified=80",
199
+ `${args.from}..${args.to}`,
200
+ ...(args.file === undefined ? [] : ["--", args.file]),
201
+ ]);
202
+ return {
203
+ status: "ok",
204
+ diff:
205
+ diff.length <= DIFF_MAX_CHARS
206
+ ? diff
207
+ : `${diff.slice(0, DIFF_MAX_CHARS)}\n\n[diff truncated at ${DIFF_MAX_CHARS} characters]`,
208
+ };
209
+ } catch {
210
+ return {
211
+ status: "unavailable",
212
+ reason: "Could not compute a reliable diff because git diff failed.",
213
+ };
214
+ }
215
+ }
216
+
217
+ function isFullCommitSha(value: string): boolean {
218
+ return /^[0-9a-f]{40}$/i.test(value);
219
+ }
220
+
221
+ /** Present already, or fetchable by SHA, or reachable from the PR head ref. */
222
+ async function ensureCommitFetched(
223
+ checkoutDir: string,
224
+ sha: string,
225
+ target: ScmCloneTarget,
226
+ credential: GitCredential | undefined
227
+ ): Promise<boolean> {
228
+ if ((await revParse(checkoutDir, sha)) !== undefined) {
229
+ return true;
230
+ }
231
+ const attempts = [
232
+ [...FETCH_ARGS, sha],
233
+ // Deeper history on the PR head ref: the older end of an inter-run range
234
+ // is usually an ancestor of the tip rather than the tip itself.
235
+ [
236
+ "fetch",
237
+ "--depth=200",
238
+ "--no-tags",
239
+ "--quiet",
240
+ "origin",
241
+ target.prHeadRef,
242
+ ],
243
+ ];
244
+ for (const attempt of attempts) {
245
+ try {
246
+ await git(checkoutDir, attempt, credential);
247
+ if ((await revParse(checkoutDir, sha)) !== undefined) {
248
+ return true;
249
+ }
250
+ } catch {
251
+ // Try the next strategy; the caller fails closed if none work.
252
+ }
253
+ }
254
+ return false;
255
+ }
256
+
257
+ export type ShallowPrCheckout = {
258
+ /** Directory containing the PR head working tree (detached at headSha). */
259
+ checkoutDir: string;
260
+ headSha: string;
261
+ /** True when the merge-base commit was also fetched (enables local diffs). */
262
+ baseFetched: boolean;
263
+ /** How the head commit was obtained. */
264
+ headSource: "sha_fetch" | "pr_ref_fetch";
265
+ };
266
+
267
+ function logShallowClone(
268
+ message: string,
269
+ fields: Record<string, string | number | boolean | undefined> = {}
270
+ ): void {
271
+ const suffix = Object.entries(fields)
272
+ .filter(([, value]) => value !== undefined)
273
+ .map(([key, value]) => `${key}=${String(value)}`)
274
+ .join(" ");
275
+ process.stderr.write(
276
+ `[shallow-clone] ${message}${suffix ? ` ${suffix}` : ""}\n`
277
+ );
278
+ }
279
+
280
+ function errorSummary(error: unknown): string {
281
+ return error instanceof Error
282
+ ? (error.message.split("\n")[0] ?? String(error))
283
+ : String(error);
284
+ }
285
+
286
+ /**
287
+ * Single-line git failure: the invoked git args (without the credential
288
+ * config noise) plus the first meaningful stderr line — the actual git
289
+ * diagnostic (auth, ref, network) — so fallback reasons surfaced to tool
290
+ * results say why, not just what ran.
291
+ */
292
+ function gitError(args: string[], error: unknown): Error {
293
+ const stderr = (error as { stderr?: unknown }).stderr;
294
+ const detail =
295
+ typeof stderr === "string"
296
+ ? stderr
297
+ .split("\n")
298
+ .map((line) => line.trim())
299
+ .find((line) => line.length > 0)
300
+ : error instanceof Error
301
+ ? (error.message.split("\n")[0] ?? String(error))
302
+ : String(error);
303
+ return new Error(`git ${args.join(" ")} failed — ${detail}`);
304
+ }
305
+
306
+ /**
307
+ * The one credential helper git may use: serve the caller-provided
308
+ * credential from the child process env at request time. The shell reads
309
+ * the values when git asks, keeping the token out of argv.
310
+ */
311
+ const CREDENTIAL_HELPER =
312
+ '!f() { test "$1" = get && printf "username=$SHALLOW_CLONE_GIT_USERNAME\\npassword=$SHALLOW_CLONE_GIT_TOKEN\\n"; }; f';
313
+
314
+ type GitCredential = {
315
+ username: string;
316
+ token: string;
317
+ };
318
+
319
+ async function git(
320
+ cwd: string,
321
+ args: string[],
322
+ credential?: GitCredential
323
+ ): Promise<string> {
324
+ // Async on purpose: fetches/checkouts of large repos take minutes, and the
325
+ // serve host runs the clone in-process. A synchronous git call blocks the
326
+ // event loop for the whole clone, freezing /v1/health and session streams
327
+ // long enough for the platform's probe budget to replace the engine.
328
+ try {
329
+ const { stdout } = await execFileAsync(
330
+ "git",
331
+ [
332
+ ...(credential === undefined
333
+ ? []
334
+ : ["-c", `credential.helper=${CREDENTIAL_HELPER}`]),
335
+ ...args,
336
+ ],
337
+ {
338
+ cwd,
339
+ encoding: "utf8",
340
+ maxBuffer: 32 * 1024 * 1024,
341
+ env: {
342
+ ...process.env,
343
+ // Hermetic git: ignore global/system config so host-provisioned
344
+ // credential rewrites (`url.https://x-access-token:<token>@github
345
+ // .com/.insteadOf` entries scoped to a *different* repo, as cloud
346
+ // VMs bake in) cannot hijack auth away from the explicit token,
347
+ // and no ambient credential helpers run against PR-author input.
348
+ GIT_CONFIG_GLOBAL: "/dev/null",
349
+ GIT_CONFIG_SYSTEM: "/dev/null",
350
+ GIT_TERMINAL_PROMPT: "0",
351
+ ...(credential === undefined
352
+ ? {}
353
+ : {
354
+ SHALLOW_CLONE_GIT_USERNAME: credential.username,
355
+ SHALLOW_CLONE_GIT_TOKEN: credential.token,
356
+ }),
357
+ },
358
+ }
359
+ );
360
+ return stdout;
361
+ } catch (error) {
362
+ throw gitError(args, error);
363
+ }
364
+ }
365
+
366
+ async function revParse(cwd: string, rev: string): Promise<string | undefined> {
367
+ try {
368
+ const sha = (
369
+ await git(cwd, ["rev-parse", "--verify", `${rev}^{commit}`])
370
+ ).trim();
371
+ return sha === "" ? undefined : sha;
372
+ } catch {
373
+ return undefined;
374
+ }
375
+ }
376
+
377
+ const FETCH_ARGS = ["fetch", "--depth=1", "--no-tags", "--quiet", "origin"];
378
+
379
+ /** Local tracking ref the PR head ref is fetched into. */
380
+ const LOCAL_PR_HEAD_REF = "refs/remotes/origin/shallow-clone-pr-head";
381
+
382
+ /**
383
+ * Create a fresh shallow checkout of a PR head at `checkoutDir`.
384
+ *
385
+ * Fetch order (both single depth-1 round-trips):
386
+ * 1. Fetch `headSha` (and `baseSha` when known) directly — GitHub advertises
387
+ * `allow-reachable-sha1-in-want`, and this pins the exact reviewed commit
388
+ * the way Bugbot's `shallow_fetch` does.
389
+ * 2. Fall back to the target's PR head ref, verifying it still resolves to
390
+ * `headSha` so the working tree cannot silently drift from the pinned
391
+ * patch in the review bundle.
392
+ *
393
+ * A missing merge-base commit is non-fatal (agents still have the pinned
394
+ * patch text in their prompt); a missing head checkout throws.
395
+ */
396
+ export async function createShallowPrCheckout(args: {
397
+ target: ScmCloneTarget;
398
+ headSha: string;
399
+ /** Merge-base SHA; fetched too so `git diff baseSha headSha` works locally. */
400
+ baseSha?: string | undefined;
401
+ checkoutDir: string;
402
+ /** Clone credential; required for HTTPS remotes, unused for file fixtures. */
403
+ auth?: ShallowCloneAuth | undefined;
404
+ }): Promise<ShallowPrCheckout> {
405
+ const { target, headSha, baseSha, checkoutDir, auth } = args;
406
+ const { repo, prNumber } = target;
407
+ const credential = cloneCredential(target, auth);
408
+ const startedAt = Date.now();
409
+ logShallowClone("cloning PR head", { repo, prNumber, headSha, baseSha });
410
+ rmSync(checkoutDir, { recursive: true, force: true });
411
+ mkdirSync(checkoutDir, { recursive: true });
412
+ await git(checkoutDir, ["init", "--quiet"]);
413
+ await git(checkoutDir, ["remote", "add", "origin", target.remoteUrl]);
414
+
415
+ const shaFetch = async (): Promise<void> => {
416
+ const extraBase =
417
+ baseSha === undefined || baseSha === headSha ? [] : [baseSha];
418
+ try {
419
+ await git(
420
+ checkoutDir,
421
+ [...FETCH_ARGS, headSha, ...extraBase],
422
+ credential
423
+ );
424
+ } catch (error) {
425
+ if (extraBase.length === 0) {
426
+ throw error;
427
+ }
428
+ // The merge-base SHA may have aged out of reachability; the head commit
429
+ // is the part the review cannot proceed without, so retry it alone.
430
+ logShallowClone("combined sha fetch failed; retrying head sha alone", {
431
+ repo,
432
+ headSha,
433
+ baseSha,
434
+ error: errorSummary(error),
435
+ });
436
+ await git(checkoutDir, [...FETCH_ARGS, headSha], credential);
437
+ }
438
+ };
439
+
440
+ let headSource: ShallowPrCheckout["headSource"];
441
+ try {
442
+ await shaFetch();
443
+ headSource = "sha_fetch";
444
+ } catch (error) {
445
+ const shaFetchError = errorSummary(error);
446
+ logShallowClone("sha fetch failed; falling back to PR head ref", {
447
+ repo,
448
+ prNumber,
449
+ headSha,
450
+ error: shaFetchError,
451
+ });
452
+ await git(
453
+ checkoutDir,
454
+ [...FETCH_ARGS, `+${target.prHeadRef}:${LOCAL_PR_HEAD_REF}`],
455
+ credential
456
+ );
457
+ const fetchedSha = await revParse(checkoutDir, LOCAL_PR_HEAD_REF);
458
+ if (fetchedSha !== headSha) {
459
+ throw new Error(
460
+ `Shallow PR ref fetch for ${repo}#${prNumber} resolved to ${fetchedSha ?? "nothing"}, expected pinned head ${headSha} (sha fetch error: ${shaFetchError})`
461
+ );
462
+ }
463
+ headSource = "pr_ref_fetch";
464
+ }
465
+
466
+ if ((await revParse(checkoutDir, headSha)) === undefined) {
467
+ throw new Error(
468
+ `Shallow fetch completed but head commit ${headSha} is missing from ${checkoutDir}`
469
+ );
470
+ }
471
+ logShallowClone("fetch complete; materializing working tree", {
472
+ repo,
473
+ headSha,
474
+ fetchMs: Date.now() - startedAt,
475
+ });
476
+ await git(checkoutDir, ["checkout", "--quiet", "--detach", headSha]);
477
+
478
+ let baseFetched =
479
+ baseSha !== undefined &&
480
+ (await revParse(checkoutDir, baseSha)) !== undefined;
481
+ if (baseSha !== undefined && baseSha !== headSha && !baseFetched) {
482
+ // Best-effort: local diffs are nice-to-have, the pinned patch in the
483
+ // prompt is the authoritative delta either way.
484
+ try {
485
+ await git(checkoutDir, [...FETCH_ARGS, baseSha], credential);
486
+ baseFetched = (await revParse(checkoutDir, baseSha)) !== undefined;
487
+ } catch (error) {
488
+ logShallowClone("merge-base fetch failed; continuing without it", {
489
+ repo,
490
+ baseSha,
491
+ error: errorSummary(error),
492
+ });
493
+ }
494
+ }
495
+
496
+ logShallowClone("checkout ready", {
497
+ repo,
498
+ prNumber,
499
+ headSha,
500
+ baseSha,
501
+ headSource,
502
+ baseFetched,
503
+ durationMs: Date.now() - startedAt,
504
+ checkoutDir,
505
+ });
506
+ return { checkoutDir, headSha, baseFetched, headSource };
507
+ }
508
+
509
+ export type TryShallowPrCheckoutOptions = {
510
+ /** PR URL; resolved to a clone target (unsupported SCMs skip). */
511
+ prUrl: string;
512
+ /** Pinned head SHA; skipped (undefined result) when unknown. */
513
+ headSha?: string | undefined;
514
+ /** Merge-base SHA; fetched too so `git diff baseSha headSha` works locally. */
515
+ baseSha?: string | undefined;
516
+ checkoutDir: string;
517
+ /** Clone credential; defaults to the target provider's credential source. */
518
+ auth?: ShallowCloneAuth | undefined;
519
+ /** Test seam: clone this target instead of resolving `prUrl`. */
520
+ target?: ScmCloneTarget | undefined;
521
+ };
522
+
523
+ export type TryShallowPrCheckoutResult = {
524
+ /** Set when the shallow checkout succeeded. */
525
+ checkout?: ShallowPrCheckout;
526
+ /**
527
+ * Why there is no checkout: a skip gate or the clone failure's first error
528
+ * line. Callers surface this in their own results/logs so the reason is
529
+ * visible on hosts that do not capture this module's stderr.
530
+ */
531
+ fallbackReason?: string;
532
+ };
533
+
534
+ /**
535
+ * Best-effort shallow PR checkout for hosts whose SDK agents should read the
536
+ * reviewed repo instead of the host's own checkout.
537
+ *
538
+ * Returns no checkout — leaving the caller on its fallback working
539
+ * directory — when the PR's SCM has no clone support (e.g. Origin PRs,
540
+ * where the host checkout is the reviewed repo), when no head SHA is
541
+ * pinned, when no clone credential is available, or when the clone fails;
542
+ * `fallbackReason` says which. Failures are logged, never thrown: agents
543
+ * still have the pinned patch in their prompts, so a missing checkout
544
+ * degrades quality rather than the run.
545
+ */
546
+ export async function tryCreateShallowPrCheckout(
547
+ options: TryShallowPrCheckoutOptions
548
+ ): Promise<TryShallowPrCheckoutResult> {
549
+ const { prUrl, headSha, baseSha, checkoutDir } = options;
550
+ const target = options.target ?? resolveScmCloneTarget(prUrl);
551
+ if (target === undefined) {
552
+ logShallowClone("skipped: unsupported SCM for shallow clone", { prUrl });
553
+ return { fallbackReason: "skipped: unsupported SCM for shallow clone" };
554
+ }
555
+ if (headSha === undefined) {
556
+ logShallowClone("skipped: no pinned head SHA", {
557
+ repo: target.repo,
558
+ prUrl,
559
+ });
560
+ return { fallbackReason: "skipped: no pinned head SHA" };
561
+ }
562
+ const auth = options.auth ?? defaultCloneAuth(target);
563
+ if (auth === undefined && target.remoteUrl.startsWith("https://")) {
564
+ // Fail fast instead of letting an unauthenticated fetch 404/hang: HTTPS
565
+ // clones need the provider's credential (or an explicit token).
566
+ logShallowClone("skipped: no clone credential", {
567
+ repo: target.repo,
568
+ provider: target.provider,
569
+ prUrl,
570
+ });
571
+ return {
572
+ fallbackReason: `skipped: no ${target.provider} clone credential (serve host token lease not installed)`,
573
+ };
574
+ }
575
+ try {
576
+ return {
577
+ checkout: await createShallowPrCheckout({
578
+ target,
579
+ headSha,
580
+ baseSha,
581
+ checkoutDir,
582
+ auth,
583
+ }),
584
+ };
585
+ } catch (error) {
586
+ const reason = errorSummary(error);
587
+ logShallowClone("failed; caller falls back to host checkout", {
588
+ repo: target.repo,
589
+ prNumber: target.prNumber,
590
+ headSha,
591
+ error: reason,
592
+ });
593
+ return { fallbackReason: `clone failed: ${reason}` };
594
+ }
595
+ }
@@ -192,6 +192,7 @@ const wizardPollResponseSchema = z
192
192
  status: z.string(),
193
193
  appId: z.string().optional(),
194
194
  oauthAuthorizeUrl: z.string().optional(),
195
+ approvalRequest: z.string().optional(),
195
196
  error: z.string().optional(),
196
197
  localEnv: z
197
198
  .object({
@@ -216,6 +217,8 @@ export interface SlackWizardPollResult {
216
217
  status: string;
217
218
  appId?: string;
218
219
  oauthAuthorizeUrl?: string;
220
+ /** "pending" means the admin-approval request is already in Slack's queue. */
221
+ approvalRequest?: string;
219
222
  error?: string;
220
223
  localEnv?: { botToken: string; appToken?: string };
221
224
  localEnvClaimed?: boolean;
@@ -16,6 +16,14 @@ export interface TerminalPalette {
16
16
  }
17
17
 
18
18
  const IDENTITY = (s: string): string => s;
19
+ const ESC = "\u001b";
20
+ const BEL = "\u0007";
21
+ const ANSI_CSI = new RegExp(`${ESC}\\[[0-9;]*m`, "g");
22
+ /** OSC 8 hyperlinks: `ESC ] 8 ; params ; uri BEL` (or ST). */
23
+ const OSC_8 = new RegExp(
24
+ `${ESC}\\]8;[^${BEL}${ESC}]*(?:${BEL}|${ESC}\\\\)`,
25
+ "g"
26
+ );
19
27
 
20
28
  const PLAIN: TerminalPalette = {
21
29
  dim: IDENTITY,
@@ -42,7 +50,7 @@ export function makePalette(enabled: boolean): TerminalPalette {
42
50
  (s: string): string =>
43
51
  `\u001b[${code}m${s}\u001b[0m`;
44
52
  return {
45
- dim: wrap("2"),
53
+ dim: (s: string) => (hasAnsiStyling(s) ? s : wrap("2")(s)),
46
54
  bold: wrap("1"),
47
55
  cyan: wrap("36"),
48
56
  green: wrap("32"),
@@ -62,6 +70,64 @@ export function stderrPalette(): TerminalPalette {
62
70
  return makePalette(colorEnabledFor(process.stderr));
63
71
  }
64
72
 
73
+ /** Visible column count, ignoring CSI color/style and OSC 8 hyperlinks. */
74
+ export function visibleWidth(text: string): number {
75
+ return text.replace(OSC_8, "").replace(ANSI_CSI, "").length;
76
+ }
77
+
78
+ /** True when `text` already carries CSI styling or OSC 8 (do not wrap again). */
79
+ export function hasAnsiStyling(text: string): boolean {
80
+ return text.includes("\u001b[") || text.includes("\u001b]");
81
+ }
82
+
83
+ /**
84
+ * Clickable terminal hyperlink (OSC 8). The URI is the click target; `label`
85
+ * is what the user sees. `visibleWidth` ignores the OSC wrapper.
86
+ */
87
+ export function terminalHyperlink(
88
+ url: string,
89
+ label: string,
90
+ enabled: boolean = colorEnabledFor()
91
+ ): string {
92
+ if (!enabled) {
93
+ return label;
94
+ }
95
+ return `\u001b]8;;${url}\u0007\u001b[4m${label}\u001b[24m\u001b]8;;\u0007`;
96
+ }
97
+
98
+ /**
99
+ * Unicode box around `lines`. `color` wraps the whole box (borders + body)
100
+ * so a warning panel can be yellow without per-line prefixes.
101
+ */
102
+ export function formatTerminalBox(
103
+ lines: readonly string[],
104
+ options?: {
105
+ color?: (s: string) => string;
106
+ minWidth?: number;
107
+ padding?: number;
108
+ }
109
+ ): string {
110
+ const color = options?.color ?? IDENTITY;
111
+ const padding = options?.padding ?? 1;
112
+ const contentWidth = Math.max(
113
+ options?.minWidth ?? 0,
114
+ ...lines.map((line) => visibleWidth(line)),
115
+ 1
116
+ );
117
+ const inner = contentWidth + padding * 2;
118
+ const padLine = (line: string): string => {
119
+ const extra = contentWidth - visibleWidth(line);
120
+ return `│${" ".repeat(padding)}${line}${" ".repeat(padding + extra)}│`;
121
+ };
122
+ const paint = (line: string): string => color(line);
123
+ const box = [
124
+ paint(`╭${"─".repeat(inner)}╮`),
125
+ ...lines.map((line) => paint(padLine(line))),
126
+ paint(`╰${"─".repeat(inner)}╯`),
127
+ ].join("\n");
128
+ return box;
129
+ }
130
+
65
131
  /** Wipe the terminal before a `dev` Enter-to-restart cycle. */
66
132
  export function clearTerminal(
67
133
  stream: NodeJS.WriteStream = process.stdout