@cursor/july 0.1.62 → 0.1.68

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 (180) hide show
  1. package/dist/bin/agent-serve.js +8 -0
  2. package/dist/channels/slack/channel-watch.d.ts +2 -1
  3. package/dist/channels/slack/channel-watch.d.ts.map +1 -1
  4. package/dist/channels/slack/channel-watch.js +7 -3
  5. package/dist/channels/slack/dispatch.d.ts +9 -0
  6. package/dist/channels/slack/dispatch.d.ts.map +1 -1
  7. package/dist/channels/slack/dispatch.js +41 -21
  8. package/dist/channels/slack/manifest.d.ts.map +1 -1
  9. package/dist/channels/slack/manifest.js +1 -0
  10. package/dist/channels/slack/nudge-store.d.ts +16 -0
  11. package/dist/channels/slack/nudge-store.d.ts.map +1 -1
  12. package/dist/channels/slack/nudge-store.js +53 -0
  13. package/dist/channels/slack/slack-channel.d.ts.map +1 -1
  14. package/dist/channels/slack/slack-channel.js +4 -1
  15. package/dist/channels/slack/types.d.ts +22 -5
  16. package/dist/channels/slack/types.d.ts.map +1 -1
  17. package/dist/docs/404.html +2 -2
  18. package/dist/docs/ab.html +3 -3
  19. package/dist/docs/assets/{app.B-biogkN.js → app.C5XUTCw9.js} +1 -1
  20. package/dist/docs/assets/chunks/@localSearchIndexroot.DvUR3lv9.js +1 -0
  21. package/dist/docs/assets/chunks/{VPLocalSearchBox.DZqKtFZS.js → VPLocalSearchBox.CGDTAYHY.js} +1 -1
  22. package/dist/docs/assets/chunks/{theme.BwC5zP2r.js → theme.lPixh250.js} +2 -2
  23. package/dist/docs/assets/{reference_connections.md.CSQiNzre.js → reference_connections.md.Bwswbm6H.js} +13 -3
  24. package/dist/docs/assets/{reference_connections.md.CSQiNzre.lean.js → reference_connections.md.Bwswbm6H.lean.js} +1 -1
  25. package/dist/docs/assets/{reference_tools.md.kJfJAP2m.js → reference_tools.md.Wmvb7Lob.js} +2 -2
  26. package/dist/docs/assets/{reference_tools.md.kJfJAP2m.lean.js → reference_tools.md.Wmvb7Lob.lean.js} +1 -1
  27. package/dist/docs/building-with-agents.html +3 -3
  28. package/dist/docs/concepts.html +3 -3
  29. package/dist/docs/deployment.html +3 -3
  30. package/dist/docs/evals.html +3 -3
  31. package/dist/docs/example-agents/approval-buddy.html +3 -3
  32. package/dist/docs/example-agents/benny.html +3 -3
  33. package/dist/docs/example-agents/bugbot.html +3 -3
  34. package/dist/docs/example-agents/codebase-wiki.html +3 -3
  35. package/dist/docs/example-agents/codeowners-review.html +3 -3
  36. package/dist/docs/example-agents/concierge.html +3 -3
  37. package/dist/docs/example-agents/fsd.html +3 -3
  38. package/dist/docs/example-agents/index.html +3 -3
  39. package/dist/docs/example-agents/knowledge-base.html +3 -3
  40. package/dist/docs/example-agents/oncall.html +3 -3
  41. package/dist/docs/example-agents/security-reviewer.html +3 -3
  42. package/dist/docs/example-agents/slack-agent.html +3 -3
  43. package/dist/docs/example-agents/weather-agent.html +3 -3
  44. package/dist/docs/guides/agent-to-agent.html +3 -3
  45. package/dist/docs/guides/cloud-runtime.html +3 -3
  46. package/dist/docs/guides/convert-automation.html +3 -3
  47. package/dist/docs/guides/github.html +3 -3
  48. package/dist/docs/guides/human-in-the-loop.html +3 -3
  49. package/dist/docs/guides/mcp-oauth.html +3 -3
  50. package/dist/docs/guides/opentelemetry.html +3 -3
  51. package/dist/docs/guides/slack.html +3 -3
  52. package/dist/docs/guides/webhooks.html +3 -3
  53. package/dist/docs/hashmap.json +1 -1
  54. package/dist/docs/hillclimbing.html +3 -3
  55. package/dist/docs/index.html +3 -3
  56. package/dist/docs/quickstart.html +3 -3
  57. package/dist/docs/reference/agent-config.html +3 -3
  58. package/dist/docs/reference/artifacts.html +3 -3
  59. package/dist/docs/reference/channels.html +3 -3
  60. package/dist/docs/reference/cli.html +3 -3
  61. package/dist/docs/reference/connections.html +15 -5
  62. package/dist/docs/reference/hooks.html +3 -3
  63. package/dist/docs/reference/http-api.html +3 -3
  64. package/dist/docs/reference/instructions.html +3 -3
  65. package/dist/docs/reference/playground.html +3 -3
  66. package/dist/docs/reference/project-layout.html +3 -3
  67. package/dist/docs/reference/prompt.html +3 -3
  68. package/dist/docs/reference/schedules.html +3 -3
  69. package/dist/docs/reference/sessions.html +3 -3
  70. package/dist/docs/reference/skills.html +3 -3
  71. package/dist/docs/reference/subagents.html +3 -3
  72. package/dist/docs/reference/tools.html +5 -5
  73. package/dist/docs/scaffolding-agents.html +3 -3
  74. package/dist/docs/storage.html +3 -3
  75. package/dist/docs/templates/agentic-owners.html +3 -3
  76. package/dist/docs/templates/demo.html +3 -3
  77. package/dist/docs/templates/pr-autofixer.html +3 -3
  78. package/dist/docs/templates/security-reviewer.html +3 -3
  79. package/dist/docs/templates/triage.html +3 -3
  80. package/dist/docs/troubleshooting.html +3 -3
  81. package/dist/files-backends/agent-store-presigned-url.js +1 -1
  82. package/dist/index.d.ts +2 -2
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +1 -1
  85. package/dist/internal/advertise-tools.d.ts +74 -0
  86. package/dist/internal/advertise-tools.d.ts.map +1 -0
  87. package/dist/internal/advertise-tools.js +152 -0
  88. package/dist/internal/cli-deploy.d.ts.map +1 -1
  89. package/dist/internal/cli-deploy.js +11 -3
  90. package/dist/internal/cli-manifest.d.ts +19 -0
  91. package/dist/internal/cli-manifest.d.ts.map +1 -0
  92. package/dist/internal/cli-manifest.js +49 -0
  93. package/dist/internal/cli-slack.d.ts.map +1 -1
  94. package/dist/internal/cli-slack.js +9 -1
  95. package/dist/internal/cursor-agent-template.d.ts +9 -0
  96. package/dist/internal/cursor-agent-template.d.ts.map +1 -0
  97. package/dist/internal/cursor-agent-template.js +37 -0
  98. package/dist/internal/deploy-client.d.ts +8 -0
  99. package/dist/internal/deploy-client.d.ts.map +1 -1
  100. package/dist/internal/deploy-client.js +21 -3
  101. package/dist/internal/deploy-manifest.d.ts +85 -0
  102. package/dist/internal/deploy-manifest.d.ts.map +1 -0
  103. package/dist/internal/deploy-manifest.js +106 -0
  104. package/dist/internal/deployment-scm-event-stream.d.ts +113 -0
  105. package/dist/internal/deployment-scm-event-stream.d.ts.map +1 -0
  106. package/dist/internal/deployment-scm-event-stream.js +460 -0
  107. package/dist/internal/discovery.d.ts.map +1 -1
  108. package/dist/internal/discovery.js +69 -0
  109. package/dist/internal/init-project.d.ts.map +1 -1
  110. package/dist/internal/init-project.js +5 -17
  111. package/dist/internal/mcp-host.d.ts +18 -0
  112. package/dist/internal/mcp-host.d.ts.map +1 -1
  113. package/dist/internal/mcp-host.js +41 -5
  114. package/dist/internal/sdk-runner.d.ts +1 -1
  115. package/dist/internal/sdk-runner.d.ts.map +1 -1
  116. package/dist/internal/sdk-runner.js +36 -13
  117. package/dist/internal/server.d.ts.map +1 -1
  118. package/dist/internal/server.js +18 -0
  119. package/dist/internal/session-engine.d.ts +66 -0
  120. package/dist/internal/session-engine.d.ts.map +1 -1
  121. package/dist/internal/session-engine.js +430 -110
  122. package/dist/internal/shallow-clone.d.ts +115 -0
  123. package/dist/internal/shallow-clone.d.ts.map +1 -0
  124. package/dist/internal/shallow-clone.js +292 -0
  125. package/dist/internal/slack-provision-client.d.ts +2 -0
  126. package/dist/internal/slack-provision-client.d.ts.map +1 -1
  127. package/dist/internal/slack-provision-client.js +1 -0
  128. package/dist/internal/turn-lease-store.d.ts +44 -0
  129. package/dist/internal/turn-lease-store.d.ts.map +1 -0
  130. package/dist/internal/turn-lease-store.js +139 -0
  131. package/dist/internal/workspace.d.ts +12 -0
  132. package/dist/internal/workspace.d.ts.map +1 -1
  133. package/dist/internal/workspace.js +28 -0
  134. package/dist/playground/assets/index-CoL7xCJl.css +1 -0
  135. package/dist/playground/assets/index-yxs1heea.js +85 -0
  136. package/dist/playground/index.html +2 -2
  137. package/dist/storage-protocol.d.ts +122 -0
  138. package/dist/storage-protocol.d.ts.map +1 -0
  139. package/dist/storage-protocol.js +173 -0
  140. package/dist/storage.d.ts +2 -72
  141. package/dist/storage.d.ts.map +1 -1
  142. package/dist/storage.js +2 -82
  143. package/dist/types.d.ts +113 -3
  144. package/dist/types.d.ts.map +1 -1
  145. package/docs/reference/connections.md +80 -0
  146. package/docs/reference/tools.md +14 -0
  147. package/package.json +4 -2
  148. package/src/bin/agent-serve.ts +9 -0
  149. package/src/channels/slack/channel-watch.ts +6 -3
  150. package/src/channels/slack/dispatch.ts +40 -3
  151. package/src/channels/slack/manifest.ts +1 -0
  152. package/src/channels/slack/nudge-store.ts +56 -0
  153. package/src/channels/slack/slack-channel.ts +3 -0
  154. package/src/channels/slack/types.ts +22 -5
  155. package/src/index.ts +5 -0
  156. package/src/internal/advertise-tools.ts +229 -0
  157. package/src/internal/cli-deploy.ts +22 -1
  158. package/src/internal/cli-manifest.ts +63 -0
  159. package/src/internal/cli-slack.ts +10 -1
  160. package/src/internal/cursor-agent-template.ts +46 -0
  161. package/src/internal/deploy-client.ts +35 -6
  162. package/src/internal/deploy-manifest.ts +167 -0
  163. package/src/internal/deployment-scm-event-stream.ts +577 -0
  164. package/src/internal/discovery.ts +85 -0
  165. package/src/internal/init-project.ts +11 -20
  166. package/src/internal/mcp-host.ts +66 -9
  167. package/src/internal/sdk-runner.ts +50 -11
  168. package/src/internal/server.ts +19 -0
  169. package/src/internal/session-engine.ts +385 -19
  170. package/src/internal/shallow-clone.ts +407 -0
  171. package/src/internal/slack-provision-client.ts +3 -0
  172. package/src/internal/turn-lease-store.ts +147 -0
  173. package/src/internal/workspace.ts +27 -0
  174. package/src/storage-protocol.ts +247 -0
  175. package/src/storage.ts +16 -110
  176. package/src/types.ts +117 -3
  177. package/templates/pr-autofixer/agent/lib/drive-schemas.ts +4 -1
  178. package/dist/docs/assets/chunks/@localSearchIndexroot.5ozYNf74.js +0 -1
  179. package/dist/playground/assets/index-B4rcOgeP.css +0 -1
  180. package/dist/playground/assets/index-DXcY42Jv.js +0 -85
@@ -0,0 +1,407 @@
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 GitHub 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
+ * Auth also mirrors Bugbot's provider model (`IGitProvider.getAccessToken`
20
+ * → token handed straight to git): the clone takes one explicit repo-scoped
21
+ * bearer token. The default source is the serve host's Cursor-account
22
+ * GitHub lease — the same backend `GithubAccessService` mint Bugbot uses —
23
+ * which `CursorGithubCredentialProvider` installs as `GH_TOKEN` for child
24
+ * processes. Where Bugbot embeds the token in the clone URL, this module
25
+ * serves it through an inline credential helper that reads a child-process
26
+ * env var, so the token never lands in argv or in `.git/config` inside a
27
+ * working tree that untrusted PR code later executes in.
28
+ *
29
+ * INTERNAL: first-party host plumbing shared by agents in `factory/*` (e.g.
30
+ * the security reviewer's `prepare_review` stage). Consumed via relative
31
+ * source imports, following `tenant-mcp/run-mcp-registry.ts`.
32
+ */
33
+
34
+ export type ShallowPrCheckout = {
35
+ /** Directory containing the PR head working tree (detached at headSha). */
36
+ checkoutDir: string;
37
+ headSha: string;
38
+ /** True when the merge-base commit was also fetched (enables local diffs). */
39
+ baseFetched: boolean;
40
+ /** How the head commit was obtained. */
41
+ headSource: "sha_fetch" | "pr_ref_fetch";
42
+ };
43
+
44
+ /** Repo-scoped bearer for git-over-HTTPS (installation token or PAT). */
45
+ export type ShallowCloneAuth = {
46
+ token: string;
47
+ };
48
+
49
+ /**
50
+ * Default clone credential: the serve host's Cursor-account GitHub lease.
51
+ * `CursorGithubCredentialProvider` mints it repo-scoped from the backend and
52
+ * keeps `GH_TOKEN` refreshed for child processes; `GITHUB_TOKEN` covers
53
+ * local/CI runs that export the conventional variable instead.
54
+ */
55
+ export function serveHostGithubAuth(
56
+ env: NodeJS.ProcessEnv = process.env
57
+ ): ShallowCloneAuth | undefined {
58
+ const token = (env.GH_TOKEN ?? env.GITHUB_TOKEN ?? "").trim();
59
+ return token === "" ? undefined : { token };
60
+ }
61
+
62
+ function logShallowClone(
63
+ message: string,
64
+ fields: Record<string, string | number | boolean | undefined> = {}
65
+ ): void {
66
+ const suffix = Object.entries(fields)
67
+ .filter(([, value]) => value !== undefined)
68
+ .map(([key, value]) => `${key}=${String(value)}`)
69
+ .join(" ");
70
+ process.stderr.write(
71
+ `[shallow-clone] ${message}${suffix ? ` ${suffix}` : ""}\n`
72
+ );
73
+ }
74
+
75
+ function errorSummary(error: unknown): string {
76
+ return error instanceof Error
77
+ ? (error.message.split("\n")[0] ?? String(error))
78
+ : String(error);
79
+ }
80
+
81
+ /**
82
+ * Single-line git failure: the invoked git args (without the credential
83
+ * config noise) plus the first meaningful stderr line — the actual git
84
+ * diagnostic (auth, ref, network) — so fallback reasons surfaced to tool
85
+ * results say why, not just what ran.
86
+ */
87
+ function gitError(args: string[], error: unknown): Error {
88
+ const stderr = (error as { stderr?: unknown }).stderr;
89
+ const detail =
90
+ typeof stderr === "string"
91
+ ? stderr
92
+ .split("\n")
93
+ .map((line) => line.trim())
94
+ .find((line) => line.length > 0)
95
+ : error instanceof Error
96
+ ? (error.message.split("\n")[0] ?? String(error))
97
+ : String(error);
98
+ return new Error(`git ${args.join(" ")} failed — ${detail}`);
99
+ }
100
+
101
+ /**
102
+ * The one credential helper git may use: serve the caller-provided token
103
+ * from the child process env at request time. The shell reads
104
+ * `$SHALLOW_CLONE_GIT_TOKEN` when git asks, keeping the token out of argv.
105
+ */
106
+ const TOKEN_CREDENTIAL_HELPER =
107
+ '!f() { test "$1" = get && printf "username=x-access-token\\npassword=$SHALLOW_CLONE_GIT_TOKEN\\n"; }; f';
108
+
109
+ async function git(
110
+ cwd: string,
111
+ args: string[],
112
+ auth?: ShallowCloneAuth
113
+ ): Promise<string> {
114
+ // Async on purpose: fetches/checkouts of large repos take minutes, and the
115
+ // serve host runs the clone in-process. A synchronous git call blocks the
116
+ // event loop for the whole clone, freezing /v1/health and session streams
117
+ // long enough for the platform's probe budget to replace the engine.
118
+ try {
119
+ const { stdout } = await execFileAsync(
120
+ "git",
121
+ [
122
+ ...(auth === undefined
123
+ ? []
124
+ : ["-c", `credential.helper=${TOKEN_CREDENTIAL_HELPER}`]),
125
+ ...args,
126
+ ],
127
+ {
128
+ cwd,
129
+ encoding: "utf8",
130
+ maxBuffer: 32 * 1024 * 1024,
131
+ env: {
132
+ ...process.env,
133
+ // Hermetic git: ignore global/system config so host-provisioned
134
+ // credential rewrites (`url.https://x-access-token:<token>@github
135
+ // .com/.insteadOf` entries scoped to a *different* repo, as cloud
136
+ // VMs bake in) cannot hijack auth away from the explicit token,
137
+ // and no ambient credential helpers run against PR-author input.
138
+ GIT_CONFIG_GLOBAL: "/dev/null",
139
+ GIT_CONFIG_SYSTEM: "/dev/null",
140
+ GIT_TERMINAL_PROMPT: "0",
141
+ ...(auth === undefined
142
+ ? {}
143
+ : { SHALLOW_CLONE_GIT_TOKEN: auth.token }),
144
+ },
145
+ }
146
+ );
147
+ return stdout;
148
+ } catch (error) {
149
+ throw gitError(args, error);
150
+ }
151
+ }
152
+
153
+ async function revParse(cwd: string, rev: string): Promise<string | undefined> {
154
+ try {
155
+ const sha = (
156
+ await git(cwd, ["rev-parse", "--verify", `${rev}^{commit}`])
157
+ ).trim();
158
+ return sha === "" ? undefined : sha;
159
+ } catch {
160
+ return undefined;
161
+ }
162
+ }
163
+
164
+ const FETCH_ARGS = ["fetch", "--depth=1", "--no-tags", "--quiet", "origin"];
165
+
166
+ /**
167
+ * Create a fresh shallow checkout of a GitHub PR head at `checkoutDir`.
168
+ *
169
+ * Fetch order (both single depth-1 round-trips):
170
+ * 1. Fetch `headSha` (and `baseSha` when known) directly — GitHub advertises
171
+ * `allow-reachable-sha1-in-want`, and this pins the exact reviewed commit
172
+ * the way Bugbot's `shallow_fetch` does.
173
+ * 2. Fall back to `refs/pull/<n>/head`, verifying it still resolves to
174
+ * `headSha` so the working tree cannot silently drift from the pinned
175
+ * patch in the review bundle.
176
+ *
177
+ * A missing merge-base commit is non-fatal (agents still have the pinned
178
+ * patch text in their prompt); a missing head checkout throws.
179
+ */
180
+ export async function createShallowPrCheckout(args: {
181
+ /** `owner/name`. */
182
+ repo: string;
183
+ prNumber?: number | undefined;
184
+ headSha: string;
185
+ /** Merge-base SHA; fetched too so `git diff baseSha headSha` works locally. */
186
+ baseSha?: string | undefined;
187
+ checkoutDir: string;
188
+ /** Clone credential; required for GitHub remotes, unused for file fixtures. */
189
+ auth?: ShallowCloneAuth | undefined;
190
+ /** Test seam: clone from this URL instead of `https://github.com/<repo>.git`. */
191
+ remoteUrl?: string | undefined;
192
+ }): Promise<ShallowPrCheckout> {
193
+ const { repo, prNumber, headSha, baseSha, checkoutDir, auth } = args;
194
+ const startedAt = Date.now();
195
+ logShallowClone("cloning PR head", { repo, prNumber, headSha, baseSha });
196
+ rmSync(checkoutDir, { recursive: true, force: true });
197
+ mkdirSync(checkoutDir, { recursive: true });
198
+ await git(checkoutDir, ["init", "--quiet"]);
199
+ await git(checkoutDir, [
200
+ "remote",
201
+ "add",
202
+ "origin",
203
+ args.remoteUrl ?? `https://github.com/${repo}.git`,
204
+ ]);
205
+
206
+ const shaFetch = async (): Promise<void> => {
207
+ const extraBase =
208
+ baseSha === undefined || baseSha === headSha ? [] : [baseSha];
209
+ try {
210
+ await git(checkoutDir, [...FETCH_ARGS, headSha, ...extraBase], auth);
211
+ } catch (error) {
212
+ if (extraBase.length === 0) {
213
+ throw error;
214
+ }
215
+ // The merge-base SHA may have aged out of reachability; the head commit
216
+ // is the part the review cannot proceed without, so retry it alone.
217
+ logShallowClone("combined sha fetch failed; retrying head sha alone", {
218
+ repo,
219
+ headSha,
220
+ baseSha,
221
+ error: errorSummary(error),
222
+ });
223
+ await git(checkoutDir, [...FETCH_ARGS, headSha], auth);
224
+ }
225
+ };
226
+
227
+ let headSource: ShallowPrCheckout["headSource"];
228
+ let shaFetchError: string | undefined;
229
+ try {
230
+ await shaFetch();
231
+ headSource = "sha_fetch";
232
+ } catch (error) {
233
+ shaFetchError = errorSummary(error);
234
+ if (prNumber === undefined) {
235
+ throw new Error(
236
+ `Shallow SHA fetch failed for ${repo}@${headSha} and no PR number is available for a ref fallback: ${shaFetchError}`
237
+ );
238
+ }
239
+ logShallowClone("sha fetch failed; falling back to PR head ref", {
240
+ repo,
241
+ prNumber,
242
+ headSha,
243
+ error: shaFetchError,
244
+ });
245
+ const prRef = `refs/pull/${prNumber}/head`;
246
+ await git(
247
+ checkoutDir,
248
+ [...FETCH_ARGS, `+${prRef}:refs/remotes/origin/pr/${prNumber}/head`],
249
+ auth
250
+ );
251
+ const fetchedSha = await revParse(
252
+ checkoutDir,
253
+ `refs/remotes/origin/pr/${prNumber}/head`
254
+ );
255
+ if (fetchedSha !== headSha) {
256
+ throw new Error(
257
+ `Shallow PR ref fetch for ${repo}#${prNumber} resolved to ${fetchedSha ?? "nothing"}, expected pinned head ${headSha} (sha fetch error: ${shaFetchError})`
258
+ );
259
+ }
260
+ headSource = "pr_ref_fetch";
261
+ }
262
+
263
+ if ((await revParse(checkoutDir, headSha)) === undefined) {
264
+ throw new Error(
265
+ `Shallow fetch completed but head commit ${headSha} is missing from ${checkoutDir}`
266
+ );
267
+ }
268
+ logShallowClone("fetch complete; materializing working tree", {
269
+ repo,
270
+ headSha,
271
+ fetchMs: Date.now() - startedAt,
272
+ });
273
+ await git(checkoutDir, ["checkout", "--quiet", "--detach", headSha]);
274
+
275
+ let baseFetched =
276
+ baseSha !== undefined &&
277
+ (await revParse(checkoutDir, baseSha)) !== undefined;
278
+ if (baseSha !== undefined && baseSha !== headSha && !baseFetched) {
279
+ // Best-effort: local diffs are nice-to-have, the pinned patch in the
280
+ // prompt is the authoritative delta either way.
281
+ try {
282
+ await git(checkoutDir, [...FETCH_ARGS, baseSha], auth);
283
+ baseFetched = (await revParse(checkoutDir, baseSha)) !== undefined;
284
+ } catch (error) {
285
+ logShallowClone("merge-base fetch failed; continuing without it", {
286
+ repo,
287
+ baseSha,
288
+ error: errorSummary(error),
289
+ });
290
+ }
291
+ }
292
+
293
+ logShallowClone("checkout ready", {
294
+ repo,
295
+ prNumber,
296
+ headSha,
297
+ baseSha,
298
+ headSource,
299
+ baseFetched,
300
+ durationMs: Date.now() - startedAt,
301
+ checkoutDir,
302
+ });
303
+ return { checkoutDir, headSha, baseFetched, headSource };
304
+ }
305
+
306
+ /** True for `https://github.com/<owner>/<repo>/pull/<n>` URLs. */
307
+ export function isGithubPrUrl(prUrl: string): boolean {
308
+ try {
309
+ const url = new URL(prUrl);
310
+ const parts = url.pathname.split("/").filter(Boolean);
311
+ return (
312
+ url.hostname === "github.com" &&
313
+ parts.length >= 4 &&
314
+ parts[2] === "pull" &&
315
+ Number.isInteger(Number(parts[3]))
316
+ );
317
+ } catch {
318
+ return false;
319
+ }
320
+ }
321
+
322
+ export type TryShallowPrCheckoutOptions = {
323
+ /** PR URL; only GitHub PR URLs are cloned (others skip). */
324
+ prUrl: string;
325
+ /** `owner/name`. */
326
+ repo: string;
327
+ prNumber?: number | undefined;
328
+ /** Pinned head SHA; skipped (undefined result) when unknown. */
329
+ headSha?: string | undefined;
330
+ /** Merge-base SHA; fetched too so `git diff baseSha headSha` works locally. */
331
+ baseSha?: string | undefined;
332
+ checkoutDir: string;
333
+ /** Clone credential; defaults to {@link serveHostGithubAuth}. */
334
+ auth?: ShallowCloneAuth | undefined;
335
+ /** Test seam: clone from this URL instead of `https://github.com/<repo>.git`. */
336
+ remoteUrl?: string | undefined;
337
+ };
338
+
339
+ export type TryShallowPrCheckoutResult = {
340
+ /** Set when the shallow checkout succeeded. */
341
+ checkout?: ShallowPrCheckout;
342
+ /**
343
+ * Why there is no checkout: a skip gate or the clone failure's first error
344
+ * line. Callers surface this in their own results/logs so the reason is
345
+ * visible on hosts that do not capture this module's stderr.
346
+ */
347
+ fallbackReason?: string;
348
+ };
349
+
350
+ /**
351
+ * Best-effort shallow PR checkout for hosts whose SDK agents should read the
352
+ * reviewed repo instead of the host's own checkout.
353
+ *
354
+ * Returns no checkout — leaving the caller on its fallback working
355
+ * directory — when the PR is not on GitHub (e.g. Origin PRs, where the host
356
+ * checkout is the reviewed repo), when no head SHA is pinned, when no clone
357
+ * credential is available, or when the clone fails; `fallbackReason` says
358
+ * which. Failures are logged, never thrown: agents still have the pinned
359
+ * patch in their prompts, so a missing checkout degrades quality rather
360
+ * than the run.
361
+ */
362
+ export async function tryCreateShallowPrCheckout(
363
+ options: TryShallowPrCheckoutOptions
364
+ ): Promise<TryShallowPrCheckoutResult> {
365
+ const { prUrl, repo, prNumber, headSha, baseSha, checkoutDir, remoteUrl } =
366
+ options;
367
+ if (remoteUrl === undefined && !isGithubPrUrl(prUrl)) {
368
+ logShallowClone("skipped: not a GitHub PR URL", { prUrl });
369
+ return { fallbackReason: "skipped: not a GitHub PR URL" };
370
+ }
371
+ if (headSha === undefined) {
372
+ logShallowClone("skipped: no pinned head SHA", { repo, prUrl });
373
+ return { fallbackReason: "skipped: no pinned head SHA" };
374
+ }
375
+ const auth = options.auth ?? serveHostGithubAuth();
376
+ if (remoteUrl === undefined && auth === undefined) {
377
+ // Fail fast instead of letting an unauthenticated fetch 404/hang: real
378
+ // GitHub clones need the serve host's lease (or an explicit token).
379
+ logShallowClone("skipped: no GitHub clone credential", { repo, prUrl });
380
+ return {
381
+ fallbackReason:
382
+ "skipped: no GitHub clone credential (serve host GH_TOKEN lease not installed)",
383
+ };
384
+ }
385
+ try {
386
+ return {
387
+ checkout: await createShallowPrCheckout({
388
+ repo,
389
+ prNumber,
390
+ headSha,
391
+ baseSha,
392
+ checkoutDir,
393
+ auth,
394
+ remoteUrl,
395
+ }),
396
+ };
397
+ } catch (error) {
398
+ const reason = errorSummary(error);
399
+ logShallowClone("failed; caller falls back to host checkout", {
400
+ repo,
401
+ prNumber,
402
+ headSha,
403
+ error: reason,
404
+ });
405
+ return { fallbackReason: `clone failed: ${reason}` };
406
+ }
407
+ }
@@ -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;
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Durable per-session turn ownership: `activeTurns` is in-memory, so servers
3
+ * sharing a state root would otherwise both run the same session.
4
+ *
5
+ * Exclusion, staleness and liveness refresh come from `proper-lockfile`, which
6
+ * the monorepo already uses for the git cache. Hand-rolling them means
7
+ * inferring that a process died — timeouts, heartbeats, and a takeover path
8
+ * that has to stay atomic while removing another owner's claim. That is where
9
+ * the subtle races live, and none of it is specific to turns.
10
+ *
11
+ * Liveness is lock age, not pid: containers have separate PID namespaces.
12
+ */
13
+
14
+ import { mkdir } from "node:fs/promises";
15
+ import { join } from "node:path";
16
+ import * as lockfile from "proper-lockfile";
17
+
18
+ /** A held turn lease. Releasing is idempotent. */
19
+ export interface TurnLease {
20
+ release(): Promise<void>;
21
+ }
22
+
23
+ /** Reject path traversal; session ids are opaque strings from the caller. */
24
+ function safeKey(sessionId: string): string {
25
+ const sanitized = sessionId
26
+ .trim()
27
+ .replace(/[^a-zA-Z0-9._-]+/g, "_")
28
+ .replace(/^\.+/, "")
29
+ .replace(/\.+/g, "_")
30
+ .slice(0, 180);
31
+ return sanitized === "" ? "_empty" : sanitized;
32
+ }
33
+
34
+ interface HeldLock {
35
+ release: () => Promise<void>;
36
+ /** The coalesce drain nests turns, so the same session is acquired twice. */
37
+ refs: number;
38
+ }
39
+
40
+ export class TurnLeaseStore {
41
+ private readonly dir: string;
42
+ private readonly staleMs: number;
43
+ /** Locks this process holds. Their release closures cannot live on disk. */
44
+ private readonly held = new Map<string, HeldLock>();
45
+
46
+ constructor(dir: string, options: { ttlMs?: number } = {}) {
47
+ this.dir = dir;
48
+ // Several refreshes, so a slow owner is not mistaken for a dead one.
49
+ this.staleMs = options.ttlMs ?? 30_000;
50
+ }
51
+
52
+ private path(sessionId: string): string {
53
+ return join(this.dir, `${safeKey(sessionId)}.lease`);
54
+ }
55
+
56
+ /**
57
+ * Undefined when another process holds this session and is still refreshing.
58
+ *
59
+ * `onCompromised` fires when the lock is lost mid-turn — the owner stalled
60
+ * past the stale window and a successor took over. No lease scheme can stop
61
+ * that; the callback is how the displaced turn learns to stand down instead
62
+ * of answering alongside its successor.
63
+ */
64
+ async acquire(
65
+ sessionId: string,
66
+ onCompromised?: () => void
67
+ ): Promise<TurnLease | undefined> {
68
+ const existing = this.held.get(sessionId);
69
+ if (existing !== undefined) {
70
+ existing.refs += 1;
71
+ return this.handle(sessionId);
72
+ }
73
+
74
+ await mkdir(this.dir, { recursive: true });
75
+ let release: () => Promise<void>;
76
+ try {
77
+ release = await lockfile.lock(this.path(sessionId), {
78
+ realpath: false,
79
+ retries: 0,
80
+ stale: this.staleMs,
81
+ // How often the library refreshes the lock's mtime while we hold it.
82
+ update: 5_000,
83
+ onCompromised: () => {
84
+ this.held.delete(sessionId);
85
+ onCompromised?.();
86
+ },
87
+ });
88
+ } catch {
89
+ // Held elsewhere, or the store is unusable. Either way this process must
90
+ // not run the turn: coalescing costs latency, two servers on one session
91
+ // costs the conversation.
92
+ return undefined;
93
+ }
94
+ this.held.set(sessionId, { release, refs: 1 });
95
+ return this.handle(sessionId);
96
+ }
97
+
98
+ private handle(sessionId: string): TurnLease {
99
+ let released = false;
100
+ return {
101
+ release: async () => {
102
+ if (released) {
103
+ return;
104
+ }
105
+ released = true;
106
+ const lock = this.held.get(sessionId);
107
+ if (lock === undefined) {
108
+ return;
109
+ }
110
+ lock.refs -= 1;
111
+ if (lock.refs > 0) {
112
+ return;
113
+ }
114
+ this.held.delete(sessionId);
115
+ // Throws if the lock was already compromised, which is not our problem
116
+ // to solve here: the successor owns it.
117
+ await lock.release().catch(() => {});
118
+ },
119
+ };
120
+ }
121
+
122
+ /** Graceful shutdown: drop every claim so a successor need not wait it out. */
123
+ async releaseAll(): Promise<void> {
124
+ for (const [sessionId, lock] of [...this.held]) {
125
+ this.held.delete(sessionId);
126
+ await lock.release().catch(() => {});
127
+ }
128
+ }
129
+
130
+ /**
131
+ * The session is running in another server process. Mirrors the engine's
132
+ * in-memory `isTurnRunning`, which only ever sees this process.
133
+ */
134
+ async runningElsewhere(sessionId: string): Promise<boolean> {
135
+ if (this.held.has(sessionId)) {
136
+ return false;
137
+ }
138
+ try {
139
+ return await lockfile.check(this.path(sessionId), {
140
+ realpath: false,
141
+ stale: this.staleMs,
142
+ });
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+ }
@@ -7,6 +7,7 @@
7
7
  * all of this up natively through its project setting source.
8
8
  */
9
9
 
10
+ import { execFile } from "node:child_process";
10
11
  import {
11
12
  chmod,
12
13
  copyFile,
@@ -19,6 +20,7 @@ import {
19
20
  writeFile,
20
21
  } from "node:fs/promises";
21
22
  import { dirname, join, parse, relative, resolve, sep } from "node:path";
23
+ import { promisify } from "node:util";
22
24
  import { agentStoreKeys, DEPLOYMENT_STORE_MOUNT_PATH } from "../files.js";
23
25
  import { MEMORY_DIR_NAME } from "../memory.js";
24
26
  import type {
@@ -29,6 +31,8 @@ import type {
29
31
  import { parseFrontmatter, serializeFrontmatter } from "./frontmatter.js";
30
32
  import { buildIdentitySection } from "./prompt-context.js";
31
33
 
34
+ const execFileAsync = promisify(execFile);
35
+
32
36
  export interface MaterializeWorkspaceOptions {
33
37
  agent: ResolvedAgent;
34
38
  workspaceDir: string;
@@ -268,6 +272,29 @@ export async function isNestedInGitRepo(dir: string): Promise<boolean> {
268
272
  return false;
269
273
  }
270
274
 
275
+ /**
276
+ * Give a session workspace its own git root so the harness roots *there*
277
+ * rather than at the enclosing repo (see {@link isNestedInGitRepo}). Without
278
+ * it the harness reads the outer repo's `.cursor/hooks.json`, rules, skills
279
+ * and `mcp.json`, and never sees the ones written into this workspace —
280
+ * instructions have an inline fallback, hooks have none.
281
+ *
282
+ * Best effort: a workspace that already has `.git` (a borrowed checkout or
283
+ * worktree) is left alone, and a failed `git init` leaves the harness where
284
+ * it already was.
285
+ */
286
+ export async function ensureOwnGitRoot(dir: string): Promise<boolean> {
287
+ if (!(await isNestedInGitRepo(dir))) {
288
+ return false;
289
+ }
290
+ try {
291
+ await execFileAsync("git", ["init", "--quiet"], { cwd: dir });
292
+ return true;
293
+ } catch {
294
+ return false;
295
+ }
296
+ }
297
+
271
298
  export async function materializeWorkspace(
272
299
  options: MaterializeWorkspaceOptions
273
300
  ): Promise<void> {