Open History to see the last commit
1/**
2 * Renders a webhook task's prompt from the request that triggered it. The
3 * rendered prompt is the only thing the agent receives, so a user who wants
4 * the whole request writes `{{request}}` or `{{body}}` themselves.
5 *
6 * The syntax is deliberately just `{{path}}` lookups — no conditionals,
7 * defaults, filters or escaping — so it never grows into a template language:
8 *
9 * - `{{body.a.b.0}}` a field of a JSON or form-encoded body
10 * - `{{headers.name}}` a request header (case-insensitive)
11 * - `{{query.name}}` a URL query parameter
12 * - `{{body}}` the raw body text
13 * - `{{request}}` method, path, query, headers and body
14 *
15 * Strings and numbers render as text, objects and arrays as JSON. A path with
16 * no value renders empty and is reported in `missing`.
17 *
18 * Credential-looking headers and query parameters are redacted wherever the
19 * whole set renders (`{{request}}`, `{{headers}}`, `{{query}}`), as in the
20 * delivery log. Naming one (`{{headers.authorization}}`) gives its raw value.
21 */
22
23export interface WebhookRequest {
24 readonly method: string;
25 readonly path: string;
26 /** Raw query string without the leading `?`. */
27 readonly query: string;
28 /** Lowercased header names. */
29 readonly headers: Readonly<Record<string, string>>;
30 readonly bodyText: string;
31}
32
33export interface RenderedWebhookPrompt {
34 readonly prompt: string;
35 readonly missing: ReadonlyArray<string>;
36}
37
38/** Header and query parameter names that commonly carry credentials. */
39const CREDENTIAL_NAME =
40 /^(authorization|proxy-authorization|cookie|set-cookie)$|token|secret|signature|key|password|auth/i;
41const REDACTED = "[redacted]";
42
43export function redactHeaders(headers: Readonly<Record<string, string>>): Record<string, string> {
44 return Object.fromEntries(
45 Object.entries(headers).map(([name, value]) => [
46 name,
47 CREDENTIAL_NAME.test(name) ? REDACTED : value,
48 ]),
49 );
50}
51
52/** Redacts credential-named values in a raw query string, keeping the rest as sent. */
53export function redactQuery(query: string): string {
54 if (query === "") return query;
55 return query
56 .split("&")
57 .map((part) => {
58 const separator = part.indexOf("=");
59 if (separator === -1) return part;
60 const name = part.slice(0, separator);
61 let decoded = name;
62 try {
63 decoded = decodeURIComponent(name.replaceAll("+", " "));
64 } catch {
65 // A malformed escape is matched as sent.
66 }
67 return CREDENTIAL_NAME.test(decoded) ? `${name}=${REDACTED}` : part;
68 })
69 .join("&");
70}
71
72const PLACEHOLDER = /\{\{\s*([^{}]*?)\s*\}\}/g;
73
74function parseBody(request: WebhookRequest): unknown {
75 const contentType = (request.headers["content-type"] ?? "").toLowerCase();
76 if (contentType.includes("application/x-www-form-urlencoded")) {
77 return Object.fromEntries(new URLSearchParams(request.bodyText));
78 }
79 // Senders are inconsistent about content types, so any body that parses
80 // as JSON is addressable.
81 try {
82 return JSON.parse(request.bodyText) as unknown;
83 } catch {
84 return undefined;
85 }
86}
87
88function lookup(root: unknown, segments: ReadonlyArray<string>): unknown {
89 let current = root;
90 for (const segment of segments) {
91 if (current === null || typeof current !== "object") return undefined;
92 if (!Object.hasOwn(current, segment)) return undefined;
93 current = (current as Record<string, unknown>)[segment];
94 }
95 return current;
96}
97
98function stringify(value: unknown): string {
99 if (typeof value === "string") return value;
100 if (typeof value === "number" || typeof value === "boolean") return String(value);
101 return JSON.stringify(value, null, 2);
102}
103
104function formatWebhookRequest(request: WebhookRequest): string {
105 const headerLines = Object.entries(redactHeaders(request.headers)).map(
106 ([name, value]) => `${name}: ${value}`,
107 );
108 const query = redactQuery(request.query);
109 return [
110 `${request.method} ${request.path}${query ? `?${query}` : ""}`,
111 ...headerLines,
112 "",
113 request.bodyText,
114 ].join("\n");
115}
116
117export function renderWebhookPrompt(
118 template: string,
119 request: WebhookRequest,
120): RenderedWebhookPrompt {
121 const missing: string[] = [];
122 let body: { parsed: unknown } | undefined;
123 const parsedBody = () => (body ??= { parsed: parseBody(request) }).parsed;
124
125 const resolve = (expression: string): unknown => {
126 const [root, ...segments] = expression.split(".");
127 switch (root) {
128 case "request":
129 return segments.length === 0 ? formatWebhookRequest(request) : undefined;
130 case "body":
131 return segments.length === 0 ? request.bodyText : lookup(parsedBody(), segments);
132 case "headers":
133 return segments.length === 0
134 ? redactHeaders(request.headers)
135 : request.headers[segments.join(".").toLowerCase()];
136 case "query": {
137 if (segments.length === 0) {
138 return Object.fromEntries(new URLSearchParams(redactQuery(request.query)));
139 }
140 return new URLSearchParams(request.query).get(segments.join(".")) ?? undefined;
141 }
142 default:
143 return undefined;
144 }
145 };
146
147 const prompt = template.replace(PLACEHOLDER, (_match, expression: string) => {
148 const value = resolve(expression);
149 if (value === undefined || value === null) {
150 if (!missing.includes(expression)) missing.push(expression);
151 return "";
152 }
153 return stringify(value);
154 });
155 return { prompt, missing };
156}