@cursor/july 0.1.61 → 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 (196) hide show
  1. package/dist/bin/agent-serve.js +8 -0
  2. package/dist/channels/github/github-channel.d.ts +1 -1
  3. package/dist/channels/github/github-channel.d.ts.map +1 -1
  4. package/dist/channels/github/github-channel.js +14 -1
  5. package/dist/channels/github/types.d.ts +2 -0
  6. package/dist/channels/github/types.d.ts.map +1 -1
  7. package/dist/channels/slack/channel-watch.d.ts +2 -1
  8. package/dist/channels/slack/channel-watch.d.ts.map +1 -1
  9. package/dist/channels/slack/channel-watch.js +7 -3
  10. package/dist/channels/slack/dispatch.d.ts +9 -0
  11. package/dist/channels/slack/dispatch.d.ts.map +1 -1
  12. package/dist/channels/slack/dispatch.js +41 -21
  13. package/dist/channels/slack/manifest.d.ts.map +1 -1
  14. package/dist/channels/slack/manifest.js +1 -0
  15. package/dist/channels/slack/nudge-store.d.ts +16 -0
  16. package/dist/channels/slack/nudge-store.d.ts.map +1 -1
  17. package/dist/channels/slack/nudge-store.js +53 -0
  18. package/dist/channels/slack/slack-channel.d.ts.map +1 -1
  19. package/dist/channels/slack/slack-channel.js +4 -1
  20. package/dist/channels/slack/types.d.ts +22 -5
  21. package/dist/channels/slack/types.d.ts.map +1 -1
  22. package/dist/docs/404.html +2 -2
  23. package/dist/docs/ab.html +3 -3
  24. package/dist/docs/assets/{app.CW3KJh72.js → app.C5XUTCw9.js} +1 -1
  25. package/dist/docs/assets/chunks/@localSearchIndexroot.DvUR3lv9.js +1 -0
  26. package/dist/docs/assets/chunks/{VPLocalSearchBox.Bk6EWpPj.js → VPLocalSearchBox.CGDTAYHY.js} +1 -1
  27. package/dist/docs/assets/chunks/{theme.Bz9AodBA.js → theme.lPixh250.js} +2 -2
  28. package/dist/docs/assets/{reference_connections.md.CSQiNzre.js → reference_connections.md.Bwswbm6H.js} +13 -3
  29. package/dist/docs/assets/{reference_connections.md.CSQiNzre.lean.js → reference_connections.md.Bwswbm6H.lean.js} +1 -1
  30. package/dist/docs/assets/{reference_tools.md.kJfJAP2m.js → reference_tools.md.Wmvb7Lob.js} +2 -2
  31. package/dist/docs/assets/{reference_tools.md.kJfJAP2m.lean.js → reference_tools.md.Wmvb7Lob.lean.js} +1 -1
  32. package/dist/docs/building-with-agents.html +3 -3
  33. package/dist/docs/concepts.html +3 -3
  34. package/dist/docs/deployment.html +3 -3
  35. package/dist/docs/evals.html +3 -3
  36. package/dist/docs/example-agents/approval-buddy.html +3 -3
  37. package/dist/docs/example-agents/benny.html +3 -3
  38. package/dist/docs/example-agents/bugbot.html +3 -3
  39. package/dist/docs/example-agents/codebase-wiki.html +3 -3
  40. package/dist/docs/example-agents/codeowners-review.html +3 -3
  41. package/dist/docs/example-agents/concierge.html +3 -3
  42. package/dist/docs/example-agents/fsd.html +3 -3
  43. package/dist/docs/example-agents/index.html +3 -3
  44. package/dist/docs/example-agents/knowledge-base.html +3 -3
  45. package/dist/docs/example-agents/oncall.html +3 -3
  46. package/dist/docs/example-agents/security-reviewer.html +3 -3
  47. package/dist/docs/example-agents/slack-agent.html +3 -3
  48. package/dist/docs/example-agents/weather-agent.html +3 -3
  49. package/dist/docs/guides/agent-to-agent.html +3 -3
  50. package/dist/docs/guides/cloud-runtime.html +3 -3
  51. package/dist/docs/guides/convert-automation.html +3 -3
  52. package/dist/docs/guides/github.html +3 -3
  53. package/dist/docs/guides/human-in-the-loop.html +3 -3
  54. package/dist/docs/guides/mcp-oauth.html +3 -3
  55. package/dist/docs/guides/opentelemetry.html +3 -3
  56. package/dist/docs/guides/slack.html +3 -3
  57. package/dist/docs/guides/webhooks.html +3 -3
  58. package/dist/docs/hashmap.json +1 -1
  59. package/dist/docs/hillclimbing.html +3 -3
  60. package/dist/docs/index.html +3 -3
  61. package/dist/docs/quickstart.html +3 -3
  62. package/dist/docs/reference/agent-config.html +3 -3
  63. package/dist/docs/reference/artifacts.html +3 -3
  64. package/dist/docs/reference/channels.html +3 -3
  65. package/dist/docs/reference/cli.html +3 -3
  66. package/dist/docs/reference/connections.html +15 -5
  67. package/dist/docs/reference/hooks.html +3 -3
  68. package/dist/docs/reference/http-api.html +3 -3
  69. package/dist/docs/reference/instructions.html +3 -3
  70. package/dist/docs/reference/playground.html +3 -3
  71. package/dist/docs/reference/project-layout.html +3 -3
  72. package/dist/docs/reference/prompt.html +3 -3
  73. package/dist/docs/reference/schedules.html +3 -3
  74. package/dist/docs/reference/sessions.html +3 -3
  75. package/dist/docs/reference/skills.html +3 -3
  76. package/dist/docs/reference/subagents.html +3 -3
  77. package/dist/docs/reference/tools.html +5 -5
  78. package/dist/docs/scaffolding-agents.html +3 -3
  79. package/dist/docs/storage.html +3 -3
  80. package/dist/docs/templates/agentic-owners.html +3 -3
  81. package/dist/docs/templates/demo.html +3 -3
  82. package/dist/docs/templates/pr-autofixer.html +3 -3
  83. package/dist/docs/templates/security-reviewer.html +3 -3
  84. package/dist/docs/templates/triage.html +3 -3
  85. package/dist/docs/troubleshooting.html +3 -3
  86. package/dist/files-backends/agent-store-presigned-url.js +1 -1
  87. package/dist/index.d.ts +2 -2
  88. package/dist/index.d.ts.map +1 -1
  89. package/dist/index.js +1 -1
  90. package/dist/internal/advertise-tools.d.ts +74 -0
  91. package/dist/internal/advertise-tools.d.ts.map +1 -0
  92. package/dist/internal/advertise-tools.js +152 -0
  93. package/dist/internal/cli-deploy.d.ts.map +1 -1
  94. package/dist/internal/cli-deploy.js +11 -3
  95. package/dist/internal/cli-manifest.d.ts +19 -0
  96. package/dist/internal/cli-manifest.d.ts.map +1 -0
  97. package/dist/internal/cli-manifest.js +49 -0
  98. package/dist/internal/cli-slack.d.ts.map +1 -1
  99. package/dist/internal/cli-slack.js +9 -1
  100. package/dist/internal/cursor-agent-template.d.ts +9 -0
  101. package/dist/internal/cursor-agent-template.d.ts.map +1 -0
  102. package/dist/internal/cursor-agent-template.js +37 -0
  103. package/dist/internal/cursor-event-relay.d.ts +5 -1
  104. package/dist/internal/cursor-event-relay.d.ts.map +1 -1
  105. package/dist/internal/cursor-event-relay.js +5 -0
  106. package/dist/internal/deploy-client.d.ts +8 -0
  107. package/dist/internal/deploy-client.d.ts.map +1 -1
  108. package/dist/internal/deploy-client.js +21 -3
  109. package/dist/internal/deploy-manifest.d.ts +85 -0
  110. package/dist/internal/deploy-manifest.d.ts.map +1 -0
  111. package/dist/internal/deploy-manifest.js +106 -0
  112. package/dist/internal/deployment-scm-event-stream.d.ts +113 -0
  113. package/dist/internal/deployment-scm-event-stream.d.ts.map +1 -0
  114. package/dist/internal/deployment-scm-event-stream.js +460 -0
  115. package/dist/internal/discovery.d.ts.map +1 -1
  116. package/dist/internal/discovery.js +69 -0
  117. package/dist/internal/init-project.d.ts.map +1 -1
  118. package/dist/internal/init-project.js +5 -17
  119. package/dist/internal/mcp-host.d.ts +18 -0
  120. package/dist/internal/mcp-host.d.ts.map +1 -1
  121. package/dist/internal/mcp-host.js +41 -5
  122. package/dist/internal/mcp-oauth.d.ts +0 -4
  123. package/dist/internal/mcp-oauth.d.ts.map +1 -1
  124. package/dist/internal/mcp-oauth.js +0 -4
  125. package/dist/internal/sdk-runner.d.ts +1 -1
  126. package/dist/internal/sdk-runner.d.ts.map +1 -1
  127. package/dist/internal/sdk-runner.js +36 -13
  128. package/dist/internal/server.d.ts.map +1 -1
  129. package/dist/internal/server.js +20 -2
  130. package/dist/internal/session-engine.d.ts +66 -0
  131. package/dist/internal/session-engine.d.ts.map +1 -1
  132. package/dist/internal/session-engine.js +430 -110
  133. package/dist/internal/shallow-clone.d.ts +115 -0
  134. package/dist/internal/shallow-clone.d.ts.map +1 -0
  135. package/dist/internal/shallow-clone.js +292 -0
  136. package/dist/internal/slack-provision-client.d.ts +2 -0
  137. package/dist/internal/slack-provision-client.d.ts.map +1 -1
  138. package/dist/internal/slack-provision-client.js +1 -0
  139. package/dist/internal/turn-lease-store.d.ts +44 -0
  140. package/dist/internal/turn-lease-store.d.ts.map +1 -0
  141. package/dist/internal/turn-lease-store.js +139 -0
  142. package/dist/internal/workspace.d.ts +12 -0
  143. package/dist/internal/workspace.d.ts.map +1 -1
  144. package/dist/internal/workspace.js +28 -0
  145. package/dist/playground/assets/index-CoL7xCJl.css +1 -0
  146. package/dist/playground/assets/index-yxs1heea.js +85 -0
  147. package/dist/playground/index.html +2 -2
  148. package/dist/storage-protocol.d.ts +122 -0
  149. package/dist/storage-protocol.d.ts.map +1 -0
  150. package/dist/storage-protocol.js +173 -0
  151. package/dist/storage.d.ts +2 -72
  152. package/dist/storage.d.ts.map +1 -1
  153. package/dist/storage.js +2 -82
  154. package/dist/types.d.ts +114 -4
  155. package/dist/types.d.ts.map +1 -1
  156. package/docs/reference/connections.md +80 -0
  157. package/docs/reference/tools.md +14 -0
  158. package/package.json +4 -2
  159. package/skills/github/SKILL.md +2 -1
  160. package/src/bin/agent-serve.ts +9 -0
  161. package/src/channels/github/github-channel.ts +18 -2
  162. package/src/channels/github/types.ts +2 -0
  163. package/src/channels/slack/channel-watch.ts +6 -3
  164. package/src/channels/slack/dispatch.ts +40 -3
  165. package/src/channels/slack/manifest.ts +1 -0
  166. package/src/channels/slack/nudge-store.ts +56 -0
  167. package/src/channels/slack/slack-channel.ts +3 -0
  168. package/src/channels/slack/types.ts +22 -5
  169. package/src/index.ts +5 -0
  170. package/src/internal/advertise-tools.ts +229 -0
  171. package/src/internal/cli-deploy.ts +22 -1
  172. package/src/internal/cli-manifest.ts +63 -0
  173. package/src/internal/cli-slack.ts +10 -1
  174. package/src/internal/cursor-agent-template.ts +46 -0
  175. package/src/internal/cursor-event-relay.ts +8 -1
  176. package/src/internal/deploy-client.ts +35 -6
  177. package/src/internal/deploy-manifest.ts +167 -0
  178. package/src/internal/deployment-scm-event-stream.ts +577 -0
  179. package/src/internal/discovery.ts +85 -0
  180. package/src/internal/init-project.ts +11 -20
  181. package/src/internal/mcp-host.ts +66 -9
  182. package/src/internal/mcp-oauth.ts +0 -4
  183. package/src/internal/sdk-runner.ts +50 -11
  184. package/src/internal/server.ts +21 -2
  185. package/src/internal/session-engine.ts +385 -19
  186. package/src/internal/shallow-clone.ts +407 -0
  187. package/src/internal/slack-provision-client.ts +3 -0
  188. package/src/internal/turn-lease-store.ts +147 -0
  189. package/src/internal/workspace.ts +27 -0
  190. package/src/storage-protocol.ts +247 -0
  191. package/src/storage.ts +16 -110
  192. package/src/types.ts +118 -4
  193. package/templates/pr-autofixer/agent/lib/drive-schemas.ts +4 -1
  194. package/dist/docs/assets/chunks/@localSearchIndexroot.BuymfBAo.js +0 -1
  195. package/dist/playground/assets/index-ClbuaLpm.css +0 -1
  196. package/dist/playground/assets/index-SqkR13k_.js +0 -85
@@ -0,0 +1,577 @@
1
+ /**
2
+ * Deployment-scoped SCM event intake for hosted multi-tenant agents.
3
+ *
4
+ * Instead of receiving HMAC-signed webhook forwards from the backend (which
5
+ * required a shared `GITHUB_WEBHOOK_SECRET` / forward-secret pair), the
6
+ * engine pulls its deliveries from the control plane's deployment-scoped
7
+ * event stream:
8
+ *
9
+ * GET /internal/agent-serve/automation-agent-sdk/events
10
+ *
11
+ * authenticated with the engine pod's `CURSOR_API_KEY` — the same
12
+ * credential (and server-side deployment allowlist) that authorizes the
13
+ * consuming agent's customer list read. The backend writes each envelope's
14
+ * `installationId` itself from the verified GitHub delivery, so agent-side
15
+ * tenant binding does not depend on an HMAC-covered payload.
16
+ *
17
+ * Each envelope is stubbed into a GitHub-shaped `pull_request` webhook body
18
+ * and POSTed to this process's own github channel route over loopback
19
+ * (admitted by the channel's no-secret `localDevStrict` policy), so the
20
+ * consuming agent's whole pipeline — Zod parse, cursorAccount credential
21
+ * lease, customer routing, tools — runs unchanged. Loopback (rather than
22
+ * the in-process `handleAgentServeTrigger` fan-out the `--cursor-events`
23
+ * relay uses) is deliberate: this stream is started from a channel's
24
+ * `onStart`, which cannot reach the serve-level mount/handler wiring.
25
+ *
26
+ * Offsets are client-owned (`<ms>-<seq>` Redis stream ids) and persisted
27
+ * under the state dir so a restart resumes where it left off instead of
28
+ * dropping deliveries (the old push path was fire-and-forget).
29
+ *
30
+ * INTERNAL: first-party host plumbing shared by agents in `factory/*`.
31
+ * Consumed via relative source imports, following
32
+ * `tenant-mcp/run-mcp-registry.ts`. Policy (which deliveries to act on,
33
+ * tenant routing) stays in the consuming agent; this module is transport
34
+ * only.
35
+ */
36
+
37
+ // Node builtins only: hosted engines install the consuming agent's directory
38
+ // alone and load this file as raw TypeScript source, so third-party imports
39
+ // (even zod) do not resolve from here. See the tenant-mcp internals for the
40
+ // same constraint.
41
+ import { createHmac } from "node:crypto";
42
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
43
+ import { join } from "node:path";
44
+
45
+ const DEFAULT_BASE_URL = "https://api.cursor.com";
46
+ const EVENTS_PATH = "/internal/agent-serve/automation-agent-sdk/events";
47
+ const POLL_WAIT_MS = 20_000;
48
+ const POLL_LIMIT = 100;
49
+ const MIN_BACKOFF_MS = 1_000;
50
+ const MAX_BACKOFF_MS = 30_000;
51
+ // Bounded self-dispatch retry before the offset advances past a delivery
52
+ // (mirrors CursorRelayCore): transient loopback failures (connection
53
+ // reset, channel briefly unavailable at startup) get a few tries; a
54
+ // poison delivery still costs only DISPATCH_ATTEMPTS and is then skipped.
55
+ const DISPATCH_ATTEMPTS = 3;
56
+ const DISPATCH_RETRY_DELAYS_MS = [250, 1_000];
57
+ /** Auth/gate failures (401/403/404) are config problems; poll slowly. */
58
+ const AUTH_FAILURE_BACKOFF_MS = 60_000;
59
+
60
+ const OFFSET_SNAPSHOT_VERSION = 1 as const;
61
+
62
+ export interface AgentSdkScmPullRequestMeta {
63
+ number: number;
64
+ url: string;
65
+ title: string;
66
+ body?: string | null | undefined;
67
+ draft?: boolean | undefined;
68
+ merged?: boolean | undefined;
69
+ authorLogin?: string | undefined;
70
+ headRef: string;
71
+ headSha: string;
72
+ baseRef: string;
73
+ baseSha?: string | undefined;
74
+ }
75
+
76
+ /** One entry from the deployment-scoped control-plane event stream. */
77
+ export interface AgentSdkScmEventEnvelope {
78
+ provider: "github";
79
+ eventName: string;
80
+ deliveryId: string;
81
+ repo: string;
82
+ receivedAtMs: number;
83
+ action: string;
84
+ /** Tenant-binding material, written by the control plane. */
85
+ installationId: number;
86
+ pullRequest: AgentSdkScmPullRequestMeta;
87
+ occurredAtMs?: number | undefined;
88
+ }
89
+
90
+ function isRecord(value: unknown): value is Record<string, unknown> {
91
+ return typeof value === "object" && value !== null && !Array.isArray(value);
92
+ }
93
+
94
+ function nonEmptyString(value: unknown): string | undefined {
95
+ return typeof value === "string" && value.length > 0 ? value : undefined;
96
+ }
97
+
98
+ function optionalString(value: unknown): value is string | undefined {
99
+ return value === undefined || typeof value === "string";
100
+ }
101
+
102
+ function optionalBoolean(value: unknown): value is boolean | undefined {
103
+ return value === undefined || typeof value === "boolean";
104
+ }
105
+
106
+ function parsePullRequestMeta(
107
+ value: unknown
108
+ ): AgentSdkScmPullRequestMeta | undefined {
109
+ if (!isRecord(value)) {
110
+ return undefined;
111
+ }
112
+ const number = value.number;
113
+ const url = nonEmptyString(value.url);
114
+ const headRef = nonEmptyString(value.headRef);
115
+ const headSha = nonEmptyString(value.headSha);
116
+ const baseRef = nonEmptyString(value.baseRef);
117
+ if (
118
+ typeof number !== "number" ||
119
+ !Number.isInteger(number) ||
120
+ number <= 0 ||
121
+ url === undefined ||
122
+ typeof value.title !== "string" ||
123
+ !(
124
+ value.body === undefined ||
125
+ value.body === null ||
126
+ typeof value.body === "string"
127
+ ) ||
128
+ !optionalBoolean(value.draft) ||
129
+ !optionalBoolean(value.merged) ||
130
+ !optionalString(value.authorLogin) ||
131
+ headRef === undefined ||
132
+ headSha === undefined ||
133
+ baseRef === undefined ||
134
+ !optionalString(value.baseSha)
135
+ ) {
136
+ return undefined;
137
+ }
138
+ return {
139
+ number,
140
+ url,
141
+ title: value.title,
142
+ body: value.body,
143
+ draft: value.draft,
144
+ merged: value.merged,
145
+ authorLogin: value.authorLogin,
146
+ headRef,
147
+ headSha,
148
+ baseRef,
149
+ baseSha: value.baseSha,
150
+ };
151
+ }
152
+
153
+ /** Unknown envelope shapes return undefined (skipped, forward compat). */
154
+ export function parseAgentSdkScmEventEnvelope(
155
+ value: unknown
156
+ ): AgentSdkScmEventEnvelope | undefined {
157
+ if (!isRecord(value) || value.provider !== "github") {
158
+ return undefined;
159
+ }
160
+ const eventName = nonEmptyString(value.eventName);
161
+ const deliveryId = nonEmptyString(value.deliveryId);
162
+ const repo = nonEmptyString(value.repo);
163
+ const action = nonEmptyString(value.action);
164
+ const installationId = value.installationId;
165
+ const pullRequest = parsePullRequestMeta(value.pullRequest);
166
+ if (
167
+ eventName === undefined ||
168
+ deliveryId === undefined ||
169
+ repo === undefined ||
170
+ typeof value.receivedAtMs !== "number" ||
171
+ action === undefined ||
172
+ typeof installationId !== "number" ||
173
+ !Number.isInteger(installationId) ||
174
+ installationId <= 0 ||
175
+ pullRequest === undefined ||
176
+ !(
177
+ value.occurredAtMs === undefined || typeof value.occurredAtMs === "number"
178
+ )
179
+ ) {
180
+ return undefined;
181
+ }
182
+ return {
183
+ provider: "github",
184
+ eventName,
185
+ deliveryId,
186
+ repo,
187
+ receivedAtMs: value.receivedAtMs,
188
+ action,
189
+ installationId,
190
+ pullRequest,
191
+ occurredAtMs: value.occurredAtMs,
192
+ };
193
+ }
194
+
195
+ type PollResponse = {
196
+ /** Unknown envelope shapes are skipped, not fatal (forward compat). */
197
+ events: Array<{ offset: string; envelope: unknown }>;
198
+ nextOffset: string;
199
+ gapDetected: boolean;
200
+ };
201
+
202
+ function parsePollResponse(value: unknown): PollResponse {
203
+ if (!isRecord(value) || !Array.isArray(value.events)) {
204
+ throw new Error("malformed poll response");
205
+ }
206
+ const events: PollResponse["events"] = [];
207
+ for (const entry of value.events) {
208
+ if (!isRecord(entry)) {
209
+ throw new Error("malformed poll response event");
210
+ }
211
+ const offset = nonEmptyString(entry.offset);
212
+ if (offset === undefined) {
213
+ throw new Error("malformed poll response event offset");
214
+ }
215
+ events.push({ offset, envelope: entry.envelope });
216
+ }
217
+ if (
218
+ typeof value.nextOffset !== "string" ||
219
+ typeof value.gapDetected !== "boolean"
220
+ ) {
221
+ throw new Error("malformed poll response fields");
222
+ }
223
+ return {
224
+ events,
225
+ nextOffset: value.nextOffset,
226
+ gapDetected: value.gapDetected,
227
+ };
228
+ }
229
+
230
+ /**
231
+ * Stub a GitHub-shaped `pull_request` webhook body from an envelope —
232
+ * enough for agent-serve's pull_request Zod schema, plus `installation.id`
233
+ * so the channel's `ctx.installationId` tenant binding keeps working.
234
+ * Pure — exported for tests.
235
+ */
236
+ export function envelopeToGitHubPayload(
237
+ envelope: AgentSdkScmEventEnvelope
238
+ ): Record<string, unknown> {
239
+ const slash = envelope.repo.indexOf("/");
240
+ const owner = slash === -1 ? "" : envelope.repo.slice(0, slash);
241
+ const name = slash === -1 ? envelope.repo : envelope.repo.slice(slash + 1);
242
+ const pr = envelope.pullRequest;
243
+ return {
244
+ action: envelope.action,
245
+ repository: {
246
+ full_name: envelope.repo,
247
+ name,
248
+ html_url: `https://github.com/${envelope.repo}`,
249
+ owner: { login: owner },
250
+ },
251
+ pull_request: {
252
+ number: pr.number,
253
+ html_url: pr.url,
254
+ title: pr.title,
255
+ body: pr.body,
256
+ draft: pr.draft,
257
+ merged: pr.merged,
258
+ user:
259
+ pr.authorLogin === undefined ? undefined : { login: pr.authorLogin },
260
+ head: { ref: pr.headRef, sha: pr.headSha },
261
+ base: { ref: pr.baseRef, sha: pr.baseSha },
262
+ },
263
+ installation: { id: envelope.installationId },
264
+ };
265
+ }
266
+
267
+ /** Durable offset snapshot under `<stateDir>/offset.json`. */
268
+ class OffsetStore {
269
+ constructor(private readonly stateDir: string) {}
270
+
271
+ private get filePath(): string {
272
+ return join(this.stateDir, "offset.json");
273
+ }
274
+
275
+ async load(): Promise<string | undefined> {
276
+ try {
277
+ const raw = await readFile(this.filePath, "utf8");
278
+ const parsed = JSON.parse(raw) as {
279
+ version?: number;
280
+ offset?: unknown;
281
+ };
282
+ if (
283
+ parsed.version === OFFSET_SNAPSHOT_VERSION &&
284
+ typeof parsed.offset === "string" &&
285
+ parsed.offset !== ""
286
+ ) {
287
+ return parsed.offset;
288
+ }
289
+ return undefined;
290
+ } catch {
291
+ return undefined;
292
+ }
293
+ }
294
+
295
+ async save(offset: string): Promise<void> {
296
+ await mkdir(this.stateDir, { recursive: true });
297
+ // Write-then-rename so a crash mid-write never corrupts the snapshot.
298
+ const tmpPath = `${this.filePath}.tmp`;
299
+ await writeFile(
300
+ tmpPath,
301
+ JSON.stringify(
302
+ {
303
+ version: OFFSET_SNAPSHOT_VERSION,
304
+ offset,
305
+ updatedAt: new Date().toISOString(),
306
+ },
307
+ null,
308
+ 2
309
+ ),
310
+ "utf8"
311
+ );
312
+ await rename(tmpPath, this.filePath);
313
+ }
314
+ }
315
+
316
+ export interface AgentSdkEventStreamOptions {
317
+ logger?: (line: string) => void;
318
+ env?: NodeJS.ProcessEnv;
319
+ /** Injected for tests. */
320
+ fetch?: typeof fetch;
321
+ /** Injected for tests (default `process.argv`). */
322
+ argv?: readonly string[];
323
+ /**
324
+ * Prefix for the consumer-scoped env overrides
325
+ * `<prefix>_SELF_WEBHOOK_URL` and `<prefix>_EVENTS_STATE_DIR`
326
+ * (default `AGENT_SERVE`; e.g. the security reviewer passes
327
+ * `SECURITY_REVIEWER` to keep its existing deployment env vars working).
328
+ */
329
+ envPrefix?: string;
330
+ /** Log-line prefix (default `agent-sdk/deployment-events`). */
331
+ logLabel?: string;
332
+ /**
333
+ * Offset state directory name under `<cwd>/.agent-serve`
334
+ * (default `deployment-events`). Consumers with persisted offsets must
335
+ * keep their historical name or a restart re-anchors at `$`.
336
+ */
337
+ stateDirName?: string;
338
+ }
339
+
340
+ /**
341
+ * Port the serve process is actually listening on, read from its own argv.
342
+ *
343
+ * The channel runs inside the serve process, so `--port <n>` / `--port=<n>`
344
+ * on the command line is authoritative. Hosted-platform engines start with
345
+ * `--port 26100` and export no `PORT` env, so guessing a fixed default posts
346
+ * self-dispatches at a port nothing listens on ("fetch failed" for every
347
+ * delivery).
348
+ */
349
+ export function servePortFromArgv(argv: readonly string[]): string | undefined {
350
+ const flagIndex = argv.lastIndexOf("--port");
351
+ if (flagIndex !== -1) {
352
+ const value = argv[flagIndex + 1]?.trim();
353
+ if (value !== undefined && /^\d+$/.test(value)) {
354
+ return value;
355
+ }
356
+ }
357
+ for (let i = argv.length - 1; i >= 0; i--) {
358
+ const arg = argv[i];
359
+ if (arg !== undefined && arg.startsWith("--port=")) {
360
+ const value = arg.slice("--port=".length).trim();
361
+ if (/^\d+$/.test(value)) {
362
+ return value;
363
+ }
364
+ }
365
+ }
366
+ return undefined;
367
+ }
368
+
369
+ export interface AgentSdkEventStream {
370
+ stop(): Promise<void>;
371
+ }
372
+
373
+ function delay(ms: number, signal: AbortSignal): Promise<void> {
374
+ return new Promise((resolve) => {
375
+ const timer = setTimeout(finish, ms);
376
+ timer.unref?.();
377
+ signal.addEventListener("abort", finish, { once: true });
378
+ function finish(): void {
379
+ clearTimeout(timer);
380
+ signal.removeEventListener("abort", finish);
381
+ resolve();
382
+ }
383
+ });
384
+ }
385
+
386
+ /**
387
+ * Start the pull loop. Returns undefined (with a log line) when required
388
+ * config is missing so `serve` still starts — mirroring how other relays
389
+ * degrade instead of failing the host.
390
+ */
391
+ export function startAgentSdkEventStream(
392
+ options: AgentSdkEventStreamOptions = {}
393
+ ): AgentSdkEventStream | undefined {
394
+ const env = options.env ?? process.env;
395
+ const logLabel = options.logLabel ?? "agent-sdk/deployment-events";
396
+ const rawLog = options.logger ?? (() => {});
397
+ const log = (message: string): void => {
398
+ rawLog(`[${logLabel}] ${message}`);
399
+ };
400
+ const doFetch = options.fetch ?? fetch;
401
+ const envPrefix = options.envPrefix ?? "AGENT_SERVE";
402
+
403
+ const apiKey = env.CURSOR_API_KEY?.trim();
404
+ if (apiKey === undefined || apiKey === "") {
405
+ log("CURSOR_API_KEY missing; deployment event stream disabled");
406
+ return undefined;
407
+ }
408
+ const baseRaw = (env.CURSOR_API_BASE_URL ?? DEFAULT_BASE_URL).trim();
409
+ const base = baseRaw.endsWith("/") ? baseRaw.slice(0, -1) : baseRaw;
410
+ // Loopback self-dispatch into this process's github channel route, single
411
+ // agent mounting assumed (multi-agent mounts need the slugged path via the
412
+ // env var override). Port resolution: explicit env override, then `PORT`,
413
+ // then the serve process's own `--port` argv (hosted-platform engines run
414
+ // `serve --port 26100` and export no PORT), then the :3000 default of the
415
+ // corp hosted image.
416
+ const selfUrl =
417
+ env[`${envPrefix}_SELF_WEBHOOK_URL`]?.trim() ||
418
+ `http://127.0.0.1:${
419
+ env.PORT?.trim() ||
420
+ servePortFromArgv(options.argv ?? process.argv) ||
421
+ "3000"
422
+ }/v1/channels/github`;
423
+ log(`self-dispatch url: ${selfUrl}`);
424
+ const stateDir =
425
+ env[`${envPrefix}_EVENTS_STATE_DIR`]?.trim() ||
426
+ join(
427
+ process.cwd(),
428
+ ".agent-serve",
429
+ options.stateDirName ?? "deployment-events"
430
+ );
431
+ const offsetStore = new OffsetStore(stateDir);
432
+ const abort = new AbortController();
433
+
434
+ // Transition aid: while the deployment still sets GITHUB_WEBHOOK_SECRET,
435
+ // the channel's auth is HMAC-only (allowAll + signature check), so sign
436
+ // the self-dispatch with it. Once the secret is removed from the env,
437
+ // the channel falls back to its loopback policy and the unsigned POST is
438
+ // admitted — either configuration works, so rollout order doesn't matter.
439
+ const webhookSecret = env.GITHUB_WEBHOOK_SECRET?.trim();
440
+
441
+ async function dispatch(envelope: AgentSdkScmEventEnvelope): Promise<void> {
442
+ const body = JSON.stringify(envelopeToGitHubPayload(envelope));
443
+ const headers: Record<string, string> = {
444
+ "content-type": "application/json",
445
+ "x-github-event": envelope.eventName,
446
+ "x-github-delivery": envelope.deliveryId,
447
+ };
448
+ if (webhookSecret !== undefined && webhookSecret !== "") {
449
+ const signature = createHmac("sha256", webhookSecret)
450
+ .update(body)
451
+ .digest("hex");
452
+ headers["x-hub-signature-256"] = `sha256=${signature}`;
453
+ }
454
+ const response = await doFetch(selfUrl, {
455
+ method: "POST",
456
+ headers,
457
+ body,
458
+ signal: AbortSignal.timeout(POLL_WAIT_MS),
459
+ });
460
+ void response.body?.cancel().catch(() => {});
461
+ if (!response.ok) {
462
+ throw new Error(`self dispatch returned ${response.status}`);
463
+ }
464
+ }
465
+
466
+ async function run(): Promise<void> {
467
+ let after = (await offsetStore.load()) ?? "$";
468
+ let backoffMs = MIN_BACKOFF_MS;
469
+ log(`pulling ${base}${EVENTS_PATH} (after=${after})`);
470
+ while (!abort.signal.aborted) {
471
+ let parsed: PollResponse;
472
+ try {
473
+ const query = new URLSearchParams({
474
+ after,
475
+ limit: String(POLL_LIMIT),
476
+ waitMs: String(POLL_WAIT_MS),
477
+ });
478
+ const response = await doFetch(`${base}${EVENTS_PATH}?${query}`, {
479
+ headers: { authorization: `Bearer ${apiKey}` },
480
+ signal: AbortSignal.any([
481
+ abort.signal,
482
+ AbortSignal.timeout(POLL_WAIT_MS + 10_000),
483
+ ]),
484
+ });
485
+ if (!response.ok) {
486
+ void response.body?.cancel().catch(() => {});
487
+ const authFailure = [401, 403, 404].includes(response.status);
488
+ log(`poll failed (${response.status}); backing off`);
489
+ await delay(
490
+ authFailure ? AUTH_FAILURE_BACKOFF_MS : backoffMs,
491
+ abort.signal
492
+ );
493
+ backoffMs = Math.min(backoffMs * 2, MAX_BACKOFF_MS);
494
+ continue;
495
+ }
496
+ parsed = parsePollResponse(await response.json());
497
+ } catch (error) {
498
+ if (abort.signal.aborted) return;
499
+ log(
500
+ `poll error (${
501
+ error instanceof Error ? error.message : String(error)
502
+ }); backing off`
503
+ );
504
+ await delay(backoffMs, abort.signal);
505
+ backoffMs = Math.min(backoffMs * 2, MAX_BACKOFF_MS);
506
+ continue;
507
+ }
508
+ backoffMs = MIN_BACKOFF_MS;
509
+ if (parsed.gapDetected) {
510
+ log(
511
+ "gap detected: some deliveries were trimmed before this consumer read them"
512
+ );
513
+ }
514
+ for (const entry of parsed.events) {
515
+ if (abort.signal.aborted) return;
516
+ const envelope = parseAgentSdkScmEventEnvelope(entry.envelope);
517
+ if (envelope !== undefined) {
518
+ for (let attempt = 1; attempt <= DISPATCH_ATTEMPTS; attempt++) {
519
+ if (abort.signal.aborted) return;
520
+ try {
521
+ await dispatch(envelope);
522
+ log(
523
+ `dispatched ${envelope.repo}#${envelope.pullRequest.number} (${envelope.action}, delivery=${envelope.deliveryId})`
524
+ );
525
+ break;
526
+ } catch (error) {
527
+ if (abort.signal.aborted) return;
528
+ const message =
529
+ error instanceof Error ? error.message : String(error);
530
+ if (attempt === DISPATCH_ATTEMPTS) {
531
+ // Skip, don't wedge: the offset advances so one poison
532
+ // delivery cannot stall the stream.
533
+ log(
534
+ `dispatch failed for ${envelope.deliveryId} after ${attempt} attempts: ${message}`
535
+ );
536
+ break;
537
+ }
538
+ log(
539
+ `dispatch attempt ${attempt} failed for ${envelope.deliveryId}: ${message}; retrying`
540
+ );
541
+ await delay(
542
+ DISPATCH_RETRY_DELAYS_MS[
543
+ Math.min(attempt - 1, DISPATCH_RETRY_DELAYS_MS.length - 1)
544
+ ],
545
+ abort.signal
546
+ );
547
+ }
548
+ }
549
+ }
550
+ after = entry.offset;
551
+ await offsetStore.save(after).catch(() => {});
552
+ }
553
+ if (parsed.events.length === 0 && parsed.nextOffset !== after) {
554
+ // "$" anchor resolution. An empty stream anchors at "" (read from
555
+ // the beginning), which is valid in-memory but not worth persisting
556
+ // (a restart re-anchors at "$" anyway).
557
+ after = parsed.nextOffset;
558
+ if (after !== "") {
559
+ await offsetStore.save(after).catch(() => {});
560
+ }
561
+ }
562
+ }
563
+ }
564
+
565
+ const done = run().catch((error: unknown) => {
566
+ log(
567
+ `loop crashed: ${error instanceof Error ? error.message : String(error)}`
568
+ );
569
+ });
570
+
571
+ return {
572
+ stop: async () => {
573
+ abort.abort();
574
+ await done;
575
+ },
576
+ };
577
+ }
@@ -448,6 +448,23 @@ async function loadAgent(
448
448
  'tools cannot be enforced on runtime: "cloud" yet (the Cursor SDK rejects tool restrictions on cloud agents). Remove `tools` or run the agent on the local runtime.',
449
449
  });
450
450
  }
451
+ // Per-session connection features (defineConnection auth/advertiseTools)
452
+ // only run on local turns: advertised tools are in-process server tools,
453
+ // and per-session headers cannot reach a cloud VM's MCP config. A
454
+ // cloud-runtime agent that declares them must fail at serve start —
455
+ // never run without the connection's tools or identity. (Hybrid
456
+ // per-send cloud sessions fail closed in the session engine.)
457
+ const perSessionConnection = connections.find(
458
+ (connection) =>
459
+ connection.advertiseTools === true || connection.auth !== undefined
460
+ );
461
+ if (perSessionConnection !== undefined && runtime === "cloud") {
462
+ ctx.diagnostics.push({
463
+ severity: "error",
464
+ path: displayPath(ctx, join(agentDir, "agent.ts")),
465
+ message: `MCP connection "${perSessionConnection.name}" uses advertiseTools/auth, which only run on runtime: "local". Remove them or run the agent on the local runtime.`,
466
+ });
467
+ }
451
468
  // `execution: "agent"` tool scripts run through the shell tool. Shell is
452
469
  // a real capability, so it is never injected — but an allowlist that
453
470
  // strands authored scripts deserves a loud diagnostic, not silence.
@@ -1176,6 +1193,72 @@ async function loadConnections(
1176
1193
  });
1177
1194
  continue;
1178
1195
  }
1196
+ if (
1197
+ connection.auth !== undefined &&
1198
+ typeof connection.auth !== "function"
1199
+ ) {
1200
+ ctx.diagnostics.push({
1201
+ severity: "error",
1202
+ path: displayPath(ctx, entryPath),
1203
+ message:
1204
+ "MCP connection `auth` must be a function: (session) => { headers }.",
1205
+ });
1206
+ continue;
1207
+ }
1208
+ if (connection.auth !== undefined && !("url" in connection)) {
1209
+ ctx.diagnostics.push({
1210
+ severity: "error",
1211
+ path: displayPath(ctx, entryPath),
1212
+ message:
1213
+ "MCP connection `auth` (per-session headers) is only supported on http/sse connections (`url`).",
1214
+ });
1215
+ continue;
1216
+ }
1217
+ if (
1218
+ connection.advertiseTools !== undefined &&
1219
+ typeof connection.advertiseTools !== "boolean"
1220
+ ) {
1221
+ ctx.diagnostics.push({
1222
+ severity: "error",
1223
+ path: displayPath(ctx, entryPath),
1224
+ message: "MCP connection `advertiseTools` must be a boolean.",
1225
+ });
1226
+ continue;
1227
+ }
1228
+ if (
1229
+ connection.advertiseTools === true &&
1230
+ isInlineStdioConnection(connection)
1231
+ ) {
1232
+ ctx.diagnostics.push({
1233
+ severity: "error",
1234
+ path: displayPath(ctx, entryPath),
1235
+ message:
1236
+ "MCP connection `advertiseTools` is not supported on inline `tools` connections — author those as agent/tools/ server tools instead.",
1237
+ });
1238
+ continue;
1239
+ }
1240
+ if (connection.advertiseTools === true && connection.hostOnly === true) {
1241
+ ctx.diagnostics.push({
1242
+ severity: "error",
1243
+ path: displayPath(ctx, entryPath),
1244
+ message:
1245
+ "MCP connection `advertiseTools` puts the connection's tools in the model's toolset, which contradicts `hostOnly` (off the model entirely). Drop one of them.",
1246
+ });
1247
+ continue;
1248
+ }
1249
+ if (
1250
+ connection.auth !== undefined &&
1251
+ "url" in connection &&
1252
+ connection.oauth === true
1253
+ ) {
1254
+ ctx.diagnostics.push({
1255
+ severity: "error",
1256
+ path: displayPath(ctx, entryPath),
1257
+ message:
1258
+ "MCP connection `oauth: true` cannot be combined with `auth` (per-session headers): the host OAuth provider owns the Authorization header. Drop one of them.",
1259
+ });
1260
+ continue;
1261
+ }
1179
1262
  if (isInlineStdioConnection(connection)) {
1180
1263
  const packed = await loadInlineStdioConnection(
1181
1264
  ctx,
@@ -1252,6 +1335,8 @@ async function loadConnections(
1252
1335
  transport,
1253
1336
  description: connection.description,
1254
1337
  hostOnly: connection.hostOnly,
1338
+ auth: connection.auth,
1339
+ advertiseTools: connection.advertiseTools,
1255
1340
  });
1256
1341
  }
1257
1342
  return connections;