@cursor/july 0.1.2 → 0.1.3

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 (174) hide show
  1. package/AGENTS.md +16 -5
  2. package/README.md +8 -9
  3. package/dist/bin/agent-serve.d.ts +3 -1
  4. package/dist/bin/agent-serve.d.ts.map +1 -1
  5. package/dist/bin/agent-serve.js +389 -152
  6. package/dist/docs/404.html +2 -2
  7. package/dist/docs/ab.html +3 -3
  8. package/dist/docs/assets/{app.Oje4vhlk.js → app.BR0RbIdx.js} +1 -1
  9. package/dist/docs/assets/chunks/@localSearchIndexroot.DtIOQzGj.js +1 -0
  10. package/dist/docs/assets/chunks/{VPLocalSearchBox.H5XZ2zCB.js → VPLocalSearchBox.qjsVTneI.js} +1 -1
  11. package/dist/docs/assets/chunks/{theme.CTR_TuaE.js → theme.2Kg8jIp_.js} +2 -2
  12. package/dist/docs/assets/{quickstart.md.CfU8_uTC.js → quickstart.md.BU6Iwi_9.js} +18 -6
  13. package/dist/docs/assets/{reference_cli.md.DA730zCu.js → reference_cli.md.Bv6pOxcF.js} +11 -6
  14. package/dist/docs/assets/{reference_cli.md.DA730zCu.lean.js → reference_cli.md.Bv6pOxcF.lean.js} +1 -1
  15. package/dist/docs/building-with-agents.html +3 -3
  16. package/dist/docs/concepts.html +3 -3
  17. package/dist/docs/deployment.html +3 -3
  18. package/dist/docs/evals.html +3 -3
  19. package/dist/docs/guides/agent-to-agent.html +3 -3
  20. package/dist/docs/guides/cloud-runtime.html +3 -3
  21. package/dist/docs/guides/github.html +3 -3
  22. package/dist/docs/guides/human-in-the-loop.html +3 -3
  23. package/dist/docs/guides/slack.html +3 -3
  24. package/dist/docs/guides/webhooks.html +3 -3
  25. package/dist/docs/hashmap.json +1 -1
  26. package/dist/docs/hillclimbing.html +3 -3
  27. package/dist/docs/index.html +3 -3
  28. package/dist/docs/quickstart.html +22 -10
  29. package/dist/docs/reference/agent-config.html +3 -3
  30. package/dist/docs/reference/channels.html +3 -3
  31. package/dist/docs/reference/cli.html +14 -9
  32. package/dist/docs/reference/connections.html +3 -3
  33. package/dist/docs/reference/hooks.html +3 -3
  34. package/dist/docs/reference/http-api.html +3 -3
  35. package/dist/docs/reference/instructions.html +3 -3
  36. package/dist/docs/reference/playground.html +3 -3
  37. package/dist/docs/reference/project-layout.html +3 -3
  38. package/dist/docs/reference/schedules.html +3 -3
  39. package/dist/docs/reference/sessions.html +3 -3
  40. package/dist/docs/reference/skills.html +3 -3
  41. package/dist/docs/reference/subagents.html +3 -3
  42. package/dist/docs/reference/tools.html +3 -3
  43. package/dist/docs/scaffolding-agents.html +3 -3
  44. package/dist/docs/storage.html +3 -3
  45. package/dist/docs/troubleshooting.html +3 -3
  46. package/dist/internal/chat-client.d.ts +29 -3
  47. package/dist/internal/chat-client.d.ts.map +1 -1
  48. package/dist/internal/chat-client.js +180 -27
  49. package/dist/internal/cli-ax.d.ts +75 -2
  50. package/dist/internal/cli-ax.d.ts.map +1 -1
  51. package/dist/internal/cli-ax.js +600 -52
  52. package/dist/internal/cli-cursor.d.ts.map +1 -1
  53. package/dist/internal/cli-cursor.js +8 -36
  54. package/dist/internal/cli-deploy.d.ts +59 -3
  55. package/dist/internal/cli-deploy.d.ts.map +1 -1
  56. package/dist/internal/cli-deploy.js +316 -38
  57. package/dist/internal/cursor/credentials.d.ts +9 -0
  58. package/dist/internal/cursor/credentials.d.ts.map +1 -1
  59. package/dist/internal/cursor/credentials.js +12 -0
  60. package/dist/internal/deploy-client.d.ts +9 -1
  61. package/dist/internal/deploy-client.d.ts.map +1 -1
  62. package/dist/internal/deploy-client.js +23 -3
  63. package/dist/internal/deploy-source.d.ts +35 -0
  64. package/dist/internal/deploy-source.d.ts.map +1 -0
  65. package/dist/internal/deploy-source.js +118 -0
  66. package/dist/internal/discovery.d.ts +11 -0
  67. package/dist/internal/discovery.d.ts.map +1 -1
  68. package/dist/internal/discovery.js +43 -14
  69. package/dist/internal/eval-run-store.d.ts.map +1 -1
  70. package/dist/internal/eval-run-store.js +2 -1
  71. package/dist/internal/eval-runner.d.ts +2 -0
  72. package/dist/internal/eval-runner.d.ts.map +1 -1
  73. package/dist/internal/eval-runner.js +2 -0
  74. package/dist/internal/event-mapper.d.ts +54 -1
  75. package/dist/internal/event-mapper.d.ts.map +1 -1
  76. package/dist/internal/event-mapper.js +151 -41
  77. package/dist/internal/init-project.d.ts +88 -1
  78. package/dist/internal/init-project.d.ts.map +1 -1
  79. package/dist/internal/init-project.js +221 -31
  80. package/dist/internal/install-cursor-skills.d.ts +64 -0
  81. package/dist/internal/install-cursor-skills.d.ts.map +1 -0
  82. package/dist/internal/install-cursor-skills.js +274 -0
  83. package/dist/internal/logs-client.d.ts +60 -0
  84. package/dist/internal/logs-client.d.ts.map +1 -0
  85. package/dist/internal/logs-client.js +311 -0
  86. package/dist/internal/open-browser.d.ts +5 -0
  87. package/dist/internal/open-browser.d.ts.map +1 -0
  88. package/dist/internal/open-browser.js +34 -0
  89. package/dist/internal/playground/toolchain.d.ts.map +1 -1
  90. package/dist/internal/playground/toolchain.js +16 -11
  91. package/dist/internal/playground-proxy.d.ts +69 -0
  92. package/dist/internal/playground-proxy.d.ts.map +1 -0
  93. package/dist/internal/playground-proxy.js +468 -0
  94. package/dist/internal/prompt-context.d.ts +35 -0
  95. package/dist/internal/prompt-context.d.ts.map +1 -0
  96. package/dist/internal/prompt-context.js +71 -0
  97. package/dist/internal/request-headers.d.ts +11 -0
  98. package/dist/internal/request-headers.d.ts.map +1 -0
  99. package/dist/internal/request-headers.js +14 -0
  100. package/dist/internal/resolve-prod-target.d.ts +42 -0
  101. package/dist/internal/resolve-prod-target.d.ts.map +1 -0
  102. package/dist/internal/resolve-prod-target.js +111 -0
  103. package/dist/internal/run-client.d.ts +2 -2
  104. package/dist/internal/run-client.d.ts.map +1 -1
  105. package/dist/internal/run-client.js +38 -23
  106. package/dist/internal/server.d.ts.map +1 -1
  107. package/dist/internal/server.js +10 -4
  108. package/dist/internal/session-engine.d.ts +1 -1
  109. package/dist/internal/session-engine.d.ts.map +1 -1
  110. package/dist/internal/session-engine.js +21 -6
  111. package/dist/internal/sessions-client.d.ts +21 -0
  112. package/dist/internal/sessions-client.d.ts.map +1 -0
  113. package/dist/internal/sessions-client.js +168 -0
  114. package/dist/internal/stream-progress.d.ts.map +1 -1
  115. package/dist/internal/stream-progress.js +31 -3
  116. package/dist/internal/terminal-style.d.ts +22 -0
  117. package/dist/internal/terminal-style.d.ts.map +1 -0
  118. package/dist/internal/terminal-style.js +49 -0
  119. package/dist/internal/trajectory.d.ts +10 -5
  120. package/dist/internal/trajectory.d.ts.map +1 -1
  121. package/dist/internal/trajectory.js +82 -10
  122. package/dist/internal/workspace.d.ts +11 -0
  123. package/dist/internal/workspace.d.ts.map +1 -1
  124. package/dist/internal/workspace.js +38 -4
  125. package/dist/playground/assets/index-D-vo2lV_.css +1 -0
  126. package/dist/playground/assets/index-x60b9q2j.js +312 -0
  127. package/dist/playground/index.html +2 -2
  128. package/dist/types.d.ts +26 -1
  129. package/dist/types.d.ts.map +1 -1
  130. package/docs/quickstart.md +22 -7
  131. package/docs/reference/cli.md +51 -3
  132. package/package.json +3 -1
  133. package/skills/ab/SKILL.md +8 -8
  134. package/skills/create-agent/SKILL.md +28 -22
  135. package/skills/debug/SKILL.md +11 -11
  136. package/skills/evals/SKILL.md +16 -16
  137. package/skills/framework-map/SKILL.md +6 -6
  138. package/skills/github/SKILL.md +13 -13
  139. package/skills/hillclimb/SKILL.md +10 -10
  140. package/skills/setup-slack/SKILL.md +13 -13
  141. package/src/bin/agent-serve.ts +422 -188
  142. package/src/internal/chat-client.ts +252 -37
  143. package/src/internal/cli-ax.ts +722 -72
  144. package/src/internal/cli-cursor.ts +14 -42
  145. package/src/internal/cli-deploy.ts +428 -49
  146. package/src/internal/cursor/credentials.ts +14 -0
  147. package/src/internal/deploy-client.ts +45 -4
  148. package/src/internal/deploy-source.ts +133 -0
  149. package/src/internal/discovery.ts +53 -16
  150. package/src/internal/eval-run-store.ts +2 -1
  151. package/src/internal/eval-runner.ts +5 -0
  152. package/src/internal/event-mapper.ts +222 -42
  153. package/src/internal/init-project.ts +333 -51
  154. package/src/internal/install-cursor-skills.ts +327 -0
  155. package/src/internal/logs-client.ts +442 -0
  156. package/src/internal/open-browser.ts +41 -0
  157. package/src/internal/playground/toolchain.ts +15 -13
  158. package/src/internal/playground-proxy.ts +576 -0
  159. package/src/internal/prompt-context.ts +95 -0
  160. package/src/internal/request-headers.ts +23 -0
  161. package/src/internal/resolve-prod-target.ts +150 -0
  162. package/src/internal/run-client.ts +39 -36
  163. package/src/internal/server.ts +12 -3
  164. package/src/internal/session-engine.ts +22 -3
  165. package/src/internal/sessions-client.ts +182 -0
  166. package/src/internal/stream-progress.ts +36 -2
  167. package/src/internal/terminal-style.ts +74 -0
  168. package/src/internal/trajectory.ts +91 -13
  169. package/src/internal/workspace.ts +42 -4
  170. package/src/types.ts +42 -6
  171. package/dist/docs/assets/chunks/@localSearchIndexroot.zwQ9RCQ7.js +0 -1
  172. package/dist/playground/assets/index-B1Qc9h2u.css +0 -1
  173. package/dist/playground/assets/index-CpDYCj8W.js +0 -79
  174. /package/dist/docs/assets/{quickstart.md.CfU8_uTC.lean.js → quickstart.md.BU6Iwi_9.lean.js} +0 -0
@@ -0,0 +1,576 @@
1
+ /**
2
+ * Loopback reverse proxy that injects engine / bearer auth so a normal
3
+ * browser can use the hosted (or remote) playground SPA.
4
+ *
5
+ * Hosted engines sit behind short-lived `engineAccess` headers that a
6
+ * browser cannot set; alias tokens are header-only too. This proxy binds
7
+ * `127.0.0.1` only and forwards every request upstream with those headers.
8
+ *
9
+ * Access is gated by a per-proxy `accessToken` (query on first hit → HttpOnly
10
+ * cookie): other local processes cannot upgrade to injected credentials just
11
+ * by knowing the port. Mutating requests also require Origin/Referer to match
12
+ * this proxy's own origin so another `http://127.0.0.1:<port>` page cannot
13
+ * CSRF the cookie (cookies are host-scoped across ports). Absolute-form
14
+ * request-targets are rejected so injected headers never leave the configured
15
+ * upstream.
16
+ *
17
+ * When `refreshUpstream` is provided (hosted `--prod`), credentials are
18
+ * re-minted shortly before `expiresAt` and once on upstream 401 so a long
19
+ * playground session does not require restarting the CLI.
20
+ */
21
+
22
+ import { randomBytes } from "node:crypto";
23
+ import {
24
+ createServer,
25
+ request as httpRequest,
26
+ type IncomingMessage,
27
+ type RequestOptions,
28
+ type Server,
29
+ type ServerResponse,
30
+ } from "node:http";
31
+ import { request as httpsRequest } from "node:https";
32
+ import type { AddressInfo } from "node:net";
33
+ import { URL } from "node:url";
34
+ import { openBrowser } from "./open-browser.js";
35
+
36
+ export { openBrowser };
37
+
38
+ const HOP_BY_HOP = new Set([
39
+ "connection",
40
+ "keep-alive",
41
+ "proxy-authenticate",
42
+ "proxy-authorization",
43
+ "te",
44
+ "trailers",
45
+ "transfer-encoding",
46
+ "upgrade",
47
+ "host",
48
+ "content-length",
49
+ ]);
50
+
51
+ /** Re-mint when the port token is within this window of expiry. */
52
+ const ACCESS_EXPIRY_LEEWAY_MS = 5 * 60 * 1000;
53
+
54
+ const PROXY_COOKIE = "agentkit_playground_proxy";
55
+ const PROXY_TOKEN_QUERY = "proxyToken";
56
+
57
+ export interface PlaygroundProxyHandle {
58
+ /** e.g. `http://127.0.0.1:54321` (no trailing slash). */
59
+ localUrl: string;
60
+ port: number;
61
+ /** Random token required via query (first hit) or cookie thereafter. */
62
+ accessToken: string;
63
+ /**
64
+ * Build a browser entry URL for `/playground` that includes the access
65
+ * token (and optional sessionId).
66
+ */
67
+ playgroundUrl: (sessionId?: string) => string;
68
+ close: () => Promise<void>;
69
+ }
70
+
71
+ export interface PlaygroundUpstreamAccess {
72
+ upstreamUrl: string;
73
+ headers?: Record<string, string>;
74
+ expiresAt?: string;
75
+ }
76
+
77
+ export interface StartPlaygroundProxyArgs {
78
+ /** Upstream agent base URL (engineAccess or --url). */
79
+ upstreamUrl: string;
80
+ /** Headers injected on every upstream request (engine tokens, wake, …). */
81
+ headers?: Record<string, string>;
82
+ /** Optional bearer for local servers that require it. */
83
+ bearerToken?: string;
84
+ /** Initial engineAccess expiry (ISO); enables proactive refresh. */
85
+ expiresAt?: string;
86
+ /**
87
+ * Re-mint upstream URL + headers (hosted `--prod`). Single-flighted across
88
+ * concurrent browser requests; called near expiry and once on 401.
89
+ */
90
+ refreshUpstream?: () => Promise<PlaygroundUpstreamAccess>;
91
+ /** Bind port; `0` = ephemeral. */
92
+ port?: number;
93
+ /** Injected for tests. */
94
+ createServerImpl?: typeof createServer;
95
+ /** Injected clock for expiry tests. */
96
+ now?: () => number;
97
+ /** Injected token for tests (defaults to a random 32-byte value). */
98
+ accessToken?: string;
99
+ }
100
+
101
+ interface UpstreamState {
102
+ upstream: URL;
103
+ injectHeaders: Record<string, string>;
104
+ expiresAtMs: number | undefined;
105
+ }
106
+
107
+ /**
108
+ * Start a loopback proxy. Resolves once listening.
109
+ */
110
+ export async function startPlaygroundProxy(
111
+ args: StartPlaygroundProxyArgs
112
+ ): Promise<PlaygroundProxyHandle> {
113
+ const upstream = parseUpstreamUrl(args.upstreamUrl);
114
+ const state: UpstreamState = {
115
+ upstream,
116
+ injectHeaders: buildInjectHeaders(args.headers, args.bearerToken),
117
+ expiresAtMs: parseExpiresAtMs(args.expiresAt),
118
+ };
119
+ const accessToken = args.accessToken ?? randomBytes(32).toString("base64url");
120
+ const now = args.now ?? Date.now;
121
+ let refreshInFlight: Promise<void> | undefined;
122
+ /** Set after listen; used for Origin CSRF checks. */
123
+ let proxyOrigin = "";
124
+
125
+ const ensureFreshAccess = async (force: boolean): Promise<void> => {
126
+ if (args.refreshUpstream === undefined) {
127
+ return;
128
+ }
129
+ const expired =
130
+ state.expiresAtMs !== undefined &&
131
+ now() >= state.expiresAtMs - ACCESS_EXPIRY_LEEWAY_MS;
132
+ if (!force && !expired) {
133
+ return;
134
+ }
135
+ if (refreshInFlight !== undefined) {
136
+ await refreshInFlight;
137
+ return;
138
+ }
139
+ refreshInFlight = (async () => {
140
+ const next = await args.refreshUpstream!();
141
+ state.upstream = parseUpstreamUrl(next.upstreamUrl);
142
+ state.injectHeaders = buildInjectHeaders(next.headers, args.bearerToken);
143
+ state.expiresAtMs = parseExpiresAtMs(next.expiresAt);
144
+ })().finally(() => {
145
+ refreshInFlight = undefined;
146
+ });
147
+ await refreshInFlight;
148
+ };
149
+
150
+ const create = args.createServerImpl ?? createServer;
151
+ const server: Server = create((req, res) => {
152
+ void handleProxyRequest({
153
+ req,
154
+ res,
155
+ getState: () => state,
156
+ ensureFreshAccess,
157
+ canRefresh: args.refreshUpstream !== undefined,
158
+ accessToken,
159
+ proxyOrigin: () => proxyOrigin,
160
+ }).catch((error: unknown) => {
161
+ if (res.headersSent) {
162
+ if (!res.writableEnded) {
163
+ res.end();
164
+ }
165
+ return;
166
+ }
167
+ const message = error instanceof Error ? error.message : String(error);
168
+ res.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
169
+ res.end(`Playground proxy error: ${message}`);
170
+ });
171
+ });
172
+
173
+ await new Promise<void>((resolve, reject) => {
174
+ server.once("error", reject);
175
+ server.listen(args.port ?? 0, "127.0.0.1", () => {
176
+ server.off("error", reject);
177
+ resolve();
178
+ });
179
+ });
180
+
181
+ const address = server.address() as AddressInfo;
182
+ const localUrl = `http://127.0.0.1:${address.port}`;
183
+ proxyOrigin = localUrl;
184
+
185
+ return {
186
+ localUrl,
187
+ port: address.port,
188
+ accessToken,
189
+ playgroundUrl: (sessionId?: string) => {
190
+ const url = new URL(`${localUrl}/playground`);
191
+ url.searchParams.set(PROXY_TOKEN_QUERY, accessToken);
192
+ if (sessionId !== undefined && sessionId.trim() !== "") {
193
+ url.searchParams.set("sessionId", sessionId.trim());
194
+ }
195
+ return url.toString();
196
+ },
197
+ close: () =>
198
+ new Promise<void>((resolve, reject) => {
199
+ // Drop keep-alive / streamed playground connections so Ctrl-C
200
+ // does not hang waiting for active sockets.
201
+ server.closeAllConnections();
202
+ server.close((error) => {
203
+ if (error) {
204
+ reject(error);
205
+ return;
206
+ }
207
+ resolve();
208
+ });
209
+ }),
210
+ };
211
+ }
212
+
213
+ function parseUpstreamUrl(raw: string): URL {
214
+ const upstream = new URL(raw.replace(/\/$/, ""));
215
+ if (upstream.protocol !== "http:" && upstream.protocol !== "https:") {
216
+ throw new Error(`Unsupported upstream protocol: ${upstream.protocol}`);
217
+ }
218
+ return upstream;
219
+ }
220
+
221
+ function parseExpiresAtMs(expiresAt: string | undefined): number | undefined {
222
+ if (expiresAt === undefined || expiresAt.trim() === "") {
223
+ return undefined;
224
+ }
225
+ const ms = Date.parse(expiresAt);
226
+ return Number.isFinite(ms) ? ms : undefined;
227
+ }
228
+
229
+ function buildInjectHeaders(
230
+ headers: Record<string, string> | undefined,
231
+ bearerToken: string | undefined
232
+ ): Record<string, string> {
233
+ const out: Record<string, string> = { ...(headers ?? {}) };
234
+ if (bearerToken !== undefined && bearerToken.trim() !== "") {
235
+ out.authorization = `Bearer ${bearerToken.trim()}`;
236
+ }
237
+ return out;
238
+ }
239
+
240
+ async function readRequestBody(req: IncomingMessage): Promise<Buffer> {
241
+ const chunks: Buffer[] = [];
242
+ for await (const chunk of req) {
243
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
244
+ }
245
+ return Buffer.concat(chunks);
246
+ }
247
+
248
+ async function handleProxyRequest(args: {
249
+ req: IncomingMessage;
250
+ res: ServerResponse;
251
+ getState: () => UpstreamState;
252
+ ensureFreshAccess: (force: boolean) => Promise<void>;
253
+ canRefresh: boolean;
254
+ accessToken: string;
255
+ proxyOrigin: () => string;
256
+ }): Promise<void> {
257
+ const {
258
+ req,
259
+ res,
260
+ getState,
261
+ ensureFreshAccess,
262
+ canRefresh,
263
+ accessToken,
264
+ proxyOrigin,
265
+ } = args;
266
+ const pathWithQuery = req.url ?? "/";
267
+
268
+ const pathParse = parseProxyPath(pathWithQuery);
269
+ if (!pathParse.ok) {
270
+ res.writeHead(400, { "content-type": "text/plain; charset=utf-8" });
271
+ res.end("Absolute-form request targets are not allowed");
272
+ return;
273
+ }
274
+
275
+ const auth = authorizeLocalRequest({
276
+ pathWithQuery: pathParse.path,
277
+ cookieHeader: req.headers.cookie,
278
+ accessToken,
279
+ });
280
+ if (auth.kind === "deny") {
281
+ res.writeHead(401, { "content-type": "text/plain; charset=utf-8" });
282
+ res.end("Playground proxy requires the session access token");
283
+ return;
284
+ }
285
+ if (auth.kind === "bootstrap") {
286
+ res.writeHead(302, {
287
+ location: auth.redirectPath,
288
+ "set-cookie": auth.setCookie,
289
+ "cache-control": "no-store",
290
+ });
291
+ res.end();
292
+ return;
293
+ }
294
+
295
+ const method = req.method ?? "GET";
296
+ if (
297
+ !isTrustedBrowserOrigin({
298
+ method,
299
+ origin: headerString(req.headers.origin),
300
+ referer: headerString(req.headers.referer),
301
+ secFetchSite: headerString(req.headers["sec-fetch-site"]),
302
+ proxyOrigin: proxyOrigin(),
303
+ })
304
+ ) {
305
+ res.writeHead(403, { "content-type": "text/plain; charset=utf-8" });
306
+ res.end("Playground proxy rejected cross-origin request");
307
+ return;
308
+ }
309
+
310
+ let body: Buffer;
311
+ try {
312
+ body = await readRequestBody(req);
313
+ } catch {
314
+ if (!res.headersSent) {
315
+ res.writeHead(400, { "content-type": "text/plain; charset=utf-8" });
316
+ res.end("Playground proxy failed to read request body");
317
+ }
318
+ return;
319
+ }
320
+
321
+ const forward = (
322
+ state: UpstreamState,
323
+ deferWriteOnUnauthorized: boolean
324
+ ): Promise<number> =>
325
+ forwardOnce({
326
+ method,
327
+ pathWithQuery: pathParse.path,
328
+ inboundHeaders: req.headers,
329
+ body,
330
+ state,
331
+ res,
332
+ deferWriteOnUnauthorized,
333
+ });
334
+
335
+ try {
336
+ await ensureFreshAccess(false);
337
+ let status = await forward(getState(), canRefresh);
338
+ if (status === 401 && canRefresh) {
339
+ await ensureFreshAccess(true);
340
+ // Retry once; always write this response (even if still 401).
341
+ status = await forward(getState(), false);
342
+ }
343
+ void status;
344
+ } catch (error) {
345
+ if (!res.headersSent) {
346
+ const message = error instanceof Error ? error.message : String(error);
347
+ res.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
348
+ res.end(`Playground proxy upstream error: ${message}`);
349
+ } else if (!res.writableEnded) {
350
+ res.end();
351
+ }
352
+ }
353
+ }
354
+
355
+ /**
356
+ * Cookies are host-scoped across ports on 127.0.0.1, so SameSite=Strict alone
357
+ * does not stop CSRF from another loopback origin. Require the browser's
358
+ * Origin (or Referer / Sec-Fetch-Site: same-origin) to match this proxy for
359
+ * mutating methods. Safe methods stay cookie-gated only (no side effects).
360
+ */
361
+ function isTrustedBrowserOrigin(args: {
362
+ method: string;
363
+ origin: string | undefined;
364
+ referer: string | undefined;
365
+ secFetchSite: string | undefined;
366
+ proxyOrigin: string;
367
+ }): boolean {
368
+ const method = args.method.toUpperCase();
369
+ if (method === "GET" || method === "HEAD" || method === "OPTIONS") {
370
+ return true;
371
+ }
372
+ if (args.proxyOrigin === "") {
373
+ return false;
374
+ }
375
+ if (args.origin === args.proxyOrigin) {
376
+ return true;
377
+ }
378
+ if (
379
+ args.referer !== undefined &&
380
+ (args.referer === args.proxyOrigin ||
381
+ args.referer.startsWith(`${args.proxyOrigin}/`))
382
+ ) {
383
+ return true;
384
+ }
385
+ // Some same-origin fetches omit Origin; modern browsers still send this.
386
+ if (args.secFetchSite === "same-origin") {
387
+ return true;
388
+ }
389
+ return false;
390
+ }
391
+
392
+ function headerString(
393
+ value: string | string[] | undefined
394
+ ): string | undefined {
395
+ if (value === undefined) {
396
+ return undefined;
397
+ }
398
+ return Array.isArray(value) ? value[0] : value;
399
+ }
400
+
401
+ function authorizeLocalRequest(args: {
402
+ pathWithQuery: string;
403
+ cookieHeader: string | string[] | undefined;
404
+ accessToken: string;
405
+ }):
406
+ | { kind: "allow" }
407
+ | { kind: "deny" }
408
+ | { kind: "bootstrap"; redirectPath: string; setCookie: string } {
409
+ const cookieToken = readCookie(args.cookieHeader, PROXY_COOKIE);
410
+ if (cookieToken === args.accessToken) {
411
+ return { kind: "allow" };
412
+ }
413
+
414
+ const url = new URL(args.pathWithQuery, "http://127.0.0.1");
415
+ const queryToken = url.searchParams.get(PROXY_TOKEN_QUERY);
416
+ if (queryToken === args.accessToken) {
417
+ url.searchParams.delete(PROXY_TOKEN_QUERY);
418
+ const redirectPath = `${url.pathname}${url.search}`;
419
+ return {
420
+ kind: "bootstrap",
421
+ redirectPath,
422
+ setCookie: `${PROXY_COOKIE}=${args.accessToken}; Path=/; HttpOnly; SameSite=Strict`,
423
+ };
424
+ }
425
+ return { kind: "deny" };
426
+ }
427
+
428
+ function readCookie(
429
+ header: string | string[] | undefined,
430
+ name: string
431
+ ): string | undefined {
432
+ if (header === undefined) {
433
+ return undefined;
434
+ }
435
+ const raw = Array.isArray(header) ? header.join("; ") : header;
436
+ for (const part of raw.split(";")) {
437
+ const trimmed = part.trim();
438
+ const eq = trimmed.indexOf("=");
439
+ if (eq <= 0) continue;
440
+ if (trimmed.slice(0, eq) === name) {
441
+ return trimmed.slice(eq + 1);
442
+ }
443
+ }
444
+ return undefined;
445
+ }
446
+
447
+ async function forwardOnce(args: {
448
+ method: string;
449
+ pathWithQuery: string;
450
+ inboundHeaders: IncomingMessage["headers"];
451
+ body: Buffer;
452
+ state: UpstreamState;
453
+ res: ServerResponse;
454
+ deferWriteOnUnauthorized: boolean;
455
+ }): Promise<number> {
456
+ const { method, pathWithQuery, inboundHeaders, body, state, res } = args;
457
+ const target = buildTargetUrl(pathWithQuery, state.upstream);
458
+
459
+ const outboundHeaders: Record<string, string | string[] | undefined> = {};
460
+ for (const [name, value] of Object.entries(inboundHeaders)) {
461
+ if (value === undefined) continue;
462
+ const lower = name.toLowerCase();
463
+ if (HOP_BY_HOP.has(lower)) continue;
464
+ if (lower === "authorization") continue;
465
+ // Do not forward the loopback session cookie upstream.
466
+ if (lower === "cookie") continue;
467
+ outboundHeaders[name] = value;
468
+ }
469
+ for (const [name, value] of Object.entries(state.injectHeaders)) {
470
+ outboundHeaders[name] = value;
471
+ }
472
+ outboundHeaders.host = target.host;
473
+ outboundHeaders["content-length"] = String(body.byteLength);
474
+
475
+ const isHttps = target.protocol === "https:";
476
+ const requestFn = isHttps ? httpsRequest : httpRequest;
477
+ const options: RequestOptions = {
478
+ protocol: target.protocol,
479
+ hostname: target.hostname,
480
+ port: target.port === "" ? (isHttps ? 443 : 80) : Number(target.port),
481
+ method,
482
+ path: `${target.pathname}${target.search}`,
483
+ headers: outboundHeaders,
484
+ };
485
+
486
+ return await new Promise<number>((resolve, reject) => {
487
+ const upstreamReq = requestFn(options, (upstreamRes) => {
488
+ const status = upstreamRes.statusCode ?? 502;
489
+ if (status === 401 && args.deferWriteOnUnauthorized) {
490
+ // Drain so the socket can be reused; caller will refresh + retry.
491
+ upstreamRes.resume();
492
+ upstreamRes.on("end", () => resolve(status));
493
+ upstreamRes.on("error", () => resolve(status));
494
+ return;
495
+ }
496
+
497
+ const responseHeaders: Record<string, string | string[] | undefined> = {
498
+ ...upstreamRes.headers,
499
+ };
500
+ for (const hop of HOP_BY_HOP) {
501
+ delete responseHeaders[hop];
502
+ }
503
+ res.writeHead(status, responseHeaders);
504
+ upstreamRes.pipe(res);
505
+ upstreamRes.on("end", () => resolve(status));
506
+ upstreamRes.on("error", () => {
507
+ if (!res.writableEnded) {
508
+ res.end();
509
+ }
510
+ resolve(status);
511
+ });
512
+ });
513
+
514
+ upstreamReq.on("error", (error) => {
515
+ reject(error);
516
+ });
517
+
518
+ res.on("close", () => {
519
+ if (!res.writableEnded) {
520
+ upstreamReq.destroy();
521
+ }
522
+ });
523
+
524
+ upstreamReq.end(body);
525
+ });
526
+ }
527
+
528
+ /**
529
+ * Build an upstream URL that always keeps the configured host/port.
530
+ * Absolute-form or protocol-relative request-targets must not retarget
531
+ * outbound requests (injected engine/bearer credentials would follow).
532
+ */
533
+ function buildTargetUrl(pathWithQuery: string, upstream: URL): URL {
534
+ const pathParse = parseProxyPath(pathWithQuery);
535
+ const relative = pathParse.ok ? pathParse.path : "/";
536
+ const target = new URL(relative, upstream);
537
+ // Force authority back onto the configured upstream even if `new URL`
538
+ // accepted an absolute/protocol-relative request-target.
539
+ target.protocol = upstream.protocol;
540
+ target.hostname = upstream.hostname;
541
+ target.port = upstream.port;
542
+ target.username = "";
543
+ target.password = "";
544
+
545
+ // Preserve upstream pathname prefix when the base URL has one
546
+ // (unusual for engineAccess; kept for `--url` mounts).
547
+ if (upstream.pathname !== "/" && upstream.pathname !== "") {
548
+ const basePath = upstream.pathname.replace(/\/$/, "");
549
+ if (!pathnameHasPrefix(target.pathname, basePath)) {
550
+ target.pathname =
551
+ target.pathname === "/"
552
+ ? `${basePath}/`
553
+ : `${basePath}${target.pathname}`;
554
+ }
555
+ }
556
+ return target;
557
+ }
558
+
559
+ /** Reject absolute / scheme-relative request-targets; keep path + query only. */
560
+ function parseProxyPath(
561
+ pathWithQuery: string
562
+ ): { ok: true; path: string } | { ok: false } {
563
+ const raw = pathWithQuery.trim();
564
+ if (raw === "") {
565
+ return { ok: true, path: "/" };
566
+ }
567
+ // Absolute-form ("http://evil/…") or protocol-relative ("//evil/…").
568
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/u.test(raw) || raw.startsWith("//")) {
569
+ return { ok: false };
570
+ }
571
+ return { ok: true, path: raw.startsWith("/") ? raw : `/${raw}` };
572
+ }
573
+
574
+ function pathnameHasPrefix(pathname: string, basePath: string): boolean {
575
+ return pathname === basePath || pathname.startsWith(`${basePath}/`);
576
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Framework-authored prompt context. Two pieces:
3
+ *
4
+ * 1. Identity section — static, appended to the agent's instructions (local
5
+ * AGENTS.md and cloud first-turn preamble) so the model knows its own
6
+ * name and how messages and sessions reach it.
7
+ * 2. Session context block — dynamic, prepended to the first turn's user
8
+ * prompt only, telling the model which session/channel/environment it is
9
+ * in plus a channel-appropriate presence line.
10
+ */
11
+
12
+ import type { ResolvedAgent } from "../types.js";
13
+
14
+ export const SCHEDULE_CHANNEL_PREFIX = "schedule:";
15
+
16
+ export type PromptEnvironment = "hosted deployment" | "local dev server";
17
+
18
+ export function buildIdentitySection(
19
+ agent: Pick<ResolvedAgent, "name" | "description">
20
+ ): string {
21
+ const description = agent.description?.trim().replace(/\.$/, "");
22
+ const intro =
23
+ description === undefined || description === ""
24
+ ? `You are "${agent.name}".`
25
+ : `You are "${agent.name}" — ${description}.`;
26
+ return [
27
+ "## About you",
28
+ "",
29
+ `${intro} You run as a persistent service: messages reach you through channels (such as Slack, GitHub, webhooks, or a web playground), and each conversation is a session that can continue across multiple turns.`,
30
+ ].join("\n");
31
+ }
32
+
33
+ export interface SessionContextInput {
34
+ sessionId: string;
35
+ channelId: string;
36
+ /**
37
+ * The channel pack's `meta.kind` (e.g. `"slack"`, `"github"`). Channel ids
38
+ * are file stems, so kind — not id — identifies what the channel is.
39
+ */
40
+ channelKind?: string;
41
+ environment: PromptEnvironment;
42
+ /** Injectable clock for tests; defaults to now. */
43
+ now?: Date;
44
+ }
45
+
46
+ export function buildSessionContextBlock(input: SessionContextInput): string {
47
+ const lines = [
48
+ "<agentkit_context>",
49
+ `session: ${input.sessionId}`,
50
+ `channel: ${input.channelId}`,
51
+ `environment: ${input.environment}`,
52
+ `time: ${(input.now ?? new Date()).toISOString()}`,
53
+ "</agentkit_context>",
54
+ ];
55
+ const presence = channelPresenceLine(input);
56
+ if (presence !== undefined) {
57
+ lines.push(presence);
58
+ }
59
+ return lines.join("\n");
60
+ }
61
+
62
+ /**
63
+ * One line telling the model whether anyone is watching this session and
64
+ * where its output lands. Resolved from the channel pack's declared kind
65
+ * when present, falling back to the built-in channel ids. Unknown channels
66
+ * get no line rather than a guess.
67
+ */
68
+ export function channelPresenceLine(
69
+ channel: Pick<SessionContextInput, "channelId" | "channelKind">
70
+ ): string | undefined {
71
+ const kind = channel.channelKind ?? builtinChannelKind(channel.channelId);
72
+ switch (kind) {
73
+ case "http":
74
+ case "mcp":
75
+ return "A user is interacting with you live and sees your replies as they stream.";
76
+ case "slack":
77
+ return "You are replying in a Slack thread; participants will read your messages.";
78
+ case "github":
79
+ return "You were triggered by a GitHub event. Deliver results through the actions available to you (comments, reviews, PRs); nobody sees your raw output otherwise.";
80
+ case "schedule":
81
+ return "This run was triggered automatically. No user is watching; complete the task autonomously and deliver results through your available tools/channels.";
82
+ default:
83
+ return undefined;
84
+ }
85
+ }
86
+
87
+ function builtinChannelKind(channelId: string): string | undefined {
88
+ if (channelId === "http" || channelId === "mcp") {
89
+ return channelId;
90
+ }
91
+ if (channelId.startsWith(SCHEDULE_CHANNEL_PREFIX)) {
92
+ return "schedule";
93
+ }
94
+ return undefined;
95
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Merge Authorization bearer + arbitrary request headers for agent HTTP
3
+ * clients (local `--bearer-token`, hosted `engineAccess.headers`, etc.).
4
+ */
5
+
6
+ export interface RequestAuth {
7
+ bearerToken?: string;
8
+ /** Extra headers (e.g. X-Anyrun-Port-Token from engineAccess). */
9
+ headers?: Record<string, string>;
10
+ }
11
+
12
+ export function mergeRequestHeaders(
13
+ auth: RequestAuth | undefined
14
+ ): Record<string, string> {
15
+ const out: Record<string, string> = {};
16
+ if (auth?.headers !== undefined) {
17
+ Object.assign(out, auth.headers);
18
+ }
19
+ if (auth?.bearerToken !== undefined) {
20
+ out.authorization = `Bearer ${auth.bearerToken}`;
21
+ }
22
+ return out;
23
+ }