sarvam-agents-client 0.3.0 → 0.3.2

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 (135) hide show
  1. package/README.md +98 -1
  2. package/dist/apis/FunctionToolsApi.d.ts +33 -0
  3. package/dist/apis/FunctionToolsApi.js +65 -0
  4. package/dist/apis/index.d.ts +1 -0
  5. package/dist/apis/index.js +1 -0
  6. package/dist/compose/agent.d.ts +20 -3
  7. package/dist/compose/agent.js +84 -7
  8. package/dist/compose/errors.d.ts +5 -1
  9. package/dist/compose/errors.js +4 -1
  10. package/dist/compose/events.d.ts +4 -0
  11. package/dist/compose/events.js +34 -0
  12. package/dist/compose/functionTool.d.ts +101 -0
  13. package/dist/compose/functionTool.js +420 -0
  14. package/dist/compose/index.d.ts +6 -2
  15. package/dist/compose/index.js +3 -1
  16. package/dist/compose/output.d.ts +11 -0
  17. package/dist/compose/output.js +32 -7
  18. package/dist/compose/run.d.ts +5 -1
  19. package/dist/compose/run.js +118 -25
  20. package/dist/compose/runState.d.ts +26 -1
  21. package/dist/compose/runState.js +30 -0
  22. package/dist/compose/settingsTransport.d.ts +28 -1
  23. package/dist/compose/settingsTransport.js +389 -7
  24. package/dist/compose/transport.d.ts +18 -1
  25. package/dist/compose/webhook.d.ts +19 -0
  26. package/dist/compose/webhook.js +184 -0
  27. package/dist/esm/apis/FunctionToolsApi.d.ts +33 -0
  28. package/dist/esm/apis/FunctionToolsApi.js +61 -0
  29. package/dist/esm/apis/index.d.ts +1 -0
  30. package/dist/esm/apis/index.js +1 -0
  31. package/dist/esm/compose/agent.d.ts +20 -3
  32. package/dist/esm/compose/agent.js +84 -7
  33. package/dist/esm/compose/errors.d.ts +5 -1
  34. package/dist/esm/compose/errors.js +4 -1
  35. package/dist/esm/compose/events.d.ts +4 -0
  36. package/dist/esm/compose/events.js +33 -0
  37. package/dist/esm/compose/functionTool.d.ts +101 -0
  38. package/dist/esm/compose/functionTool.js +406 -0
  39. package/dist/esm/compose/index.d.ts +6 -2
  40. package/dist/esm/compose/index.js +1 -0
  41. package/dist/esm/compose/output.d.ts +11 -0
  42. package/dist/esm/compose/output.js +30 -9
  43. package/dist/esm/compose/run.d.ts +5 -1
  44. package/dist/esm/compose/run.js +118 -25
  45. package/dist/esm/compose/runState.d.ts +26 -1
  46. package/dist/esm/compose/runState.js +31 -1
  47. package/dist/esm/compose/settingsTransport.d.ts +28 -1
  48. package/dist/esm/compose/settingsTransport.js +392 -11
  49. package/dist/esm/compose/transport.d.ts +18 -1
  50. package/dist/esm/compose/webhook.d.ts +19 -0
  51. package/dist/esm/compose/webhook.js +177 -0
  52. package/dist/esm/models/AgentConversationDetail.d.ts +7 -0
  53. package/dist/esm/models/AgentConversationDetail.js +3 -0
  54. package/dist/esm/models/ClarifyBody.d.ts +6 -0
  55. package/dist/esm/models/ClarifyBody.js +2 -0
  56. package/dist/esm/models/ConversationDetail.d.ts +7 -0
  57. package/dist/esm/models/ConversationDetail.js +3 -0
  58. package/dist/esm/models/ErrorDetail.d.ts +1 -0
  59. package/dist/esm/models/ErrorDetail.js +2 -1
  60. package/dist/esm/models/FunctionResultBody.d.ts +44 -0
  61. package/dist/esm/models/FunctionResultBody.js +49 -0
  62. package/dist/esm/models/QueueMessageInput.d.ts +23 -0
  63. package/dist/esm/models/QueueMessageInput.js +14 -0
  64. package/dist/esm/models/RequiredAction.d.ts +77 -0
  65. package/dist/esm/models/RequiredAction.js +69 -0
  66. package/dist/esm/models/ResponseDetail.d.ts +8 -0
  67. package/dist/esm/models/ResponseDetail.js +2 -0
  68. package/dist/esm/models/ResponseInput.d.ts +23 -0
  69. package/dist/esm/models/ResponseInput.js +14 -0
  70. package/dist/esm/models/ToolResults200Response.d.ts +38 -0
  71. package/dist/esm/models/ToolResults200Response.js +47 -0
  72. package/dist/esm/models/ToolResultsBody.d.ts +39 -0
  73. package/dist/esm/models/ToolResultsBody.js +48 -0
  74. package/dist/esm/models/index.d.ts +4 -0
  75. package/dist/esm/models/index.js +4 -0
  76. package/dist/esm/streaming.d.ts +14 -2
  77. package/dist/esm/streaming.js +26 -4
  78. package/dist/esm/webhooks.d.ts +203 -0
  79. package/dist/esm/webhooks.js +215 -0
  80. package/dist/models/AgentConversationDetail.d.ts +7 -0
  81. package/dist/models/AgentConversationDetail.js +3 -0
  82. package/dist/models/ClarifyBody.d.ts +6 -0
  83. package/dist/models/ClarifyBody.js +2 -0
  84. package/dist/models/ConversationDetail.d.ts +7 -0
  85. package/dist/models/ConversationDetail.js +3 -0
  86. package/dist/models/ErrorDetail.d.ts +1 -0
  87. package/dist/models/ErrorDetail.js +2 -1
  88. package/dist/models/FunctionResultBody.d.ts +44 -0
  89. package/dist/models/FunctionResultBody.js +56 -0
  90. package/dist/models/QueueMessageInput.d.ts +23 -0
  91. package/dist/models/QueueMessageInput.js +15 -1
  92. package/dist/models/RequiredAction.d.ts +77 -0
  93. package/dist/models/RequiredAction.js +77 -0
  94. package/dist/models/ResponseDetail.d.ts +8 -0
  95. package/dist/models/ResponseDetail.js +2 -0
  96. package/dist/models/ResponseInput.d.ts +23 -0
  97. package/dist/models/ResponseInput.js +15 -0
  98. package/dist/models/ToolResults200Response.d.ts +38 -0
  99. package/dist/models/ToolResults200Response.js +54 -0
  100. package/dist/models/ToolResultsBody.d.ts +39 -0
  101. package/dist/models/ToolResultsBody.js +55 -0
  102. package/dist/models/index.d.ts +4 -0
  103. package/dist/models/index.js +4 -0
  104. package/dist/streaming.d.ts +14 -2
  105. package/dist/streaming.js +27 -4
  106. package/dist/webhooks.d.ts +203 -0
  107. package/dist/webhooks.js +224 -0
  108. package/package.json +9 -1
  109. package/src/apis/FunctionToolsApi.ts +102 -0
  110. package/src/apis/index.ts +1 -0
  111. package/src/compose/agent.ts +96 -9
  112. package/src/compose/errors.ts +7 -1
  113. package/src/compose/events.ts +30 -0
  114. package/src/compose/functionTool.ts +441 -0
  115. package/src/compose/index.ts +6 -2
  116. package/src/compose/output.ts +30 -9
  117. package/src/compose/run.ts +115 -18
  118. package/src/compose/runState.ts +44 -5
  119. package/src/compose/settingsTransport.ts +379 -8
  120. package/src/compose/transport.ts +24 -1
  121. package/src/compose/webhook.ts +181 -0
  122. package/src/models/AgentConversationDetail.ts +15 -0
  123. package/src/models/ClarifyBody.ts +8 -0
  124. package/src/models/ConversationDetail.ts +15 -0
  125. package/src/models/ErrorDetail.ts +2 -1
  126. package/src/models/FunctionResultBody.ts +83 -0
  127. package/src/models/QueueMessageInput.ts +28 -0
  128. package/src/models/RequiredAction.ts +128 -0
  129. package/src/models/ResponseDetail.ts +8 -0
  130. package/src/models/ResponseInput.ts +30 -0
  131. package/src/models/ToolResults200Response.ts +75 -0
  132. package/src/models/ToolResultsBody.ts +83 -0
  133. package/src/models/index.ts +4 -0
  134. package/src/streaming.ts +39 -3
  135. package/src/webhooks.ts +390 -0
@@ -0,0 +1,75 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ /**
4
+ * Sarvam Agents API
5
+ * Chat with a Sarvam agent, exchange files with it, and set it up (instructions, skills, knowledge bases, connectors, deploy) from your own code. Authenticate with a service token sent as a Bearer token, and send the header X-Panja-Origin: managed_agents on every request.
6
+ *
7
+ * The version of the OpenAPI document: 0.1.0
8
+ * Contact: support@sarvam.ai
9
+ *
10
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
11
+ * https://openapi-generator.tech
12
+ * Do not edit the class manually.
13
+ */
14
+
15
+ import { mapValues } from '../runtime.js';
16
+ /**
17
+ *
18
+ * @export
19
+ * @interface ToolResults200Response
20
+ */
21
+ export interface ToolResults200Response {
22
+ /**
23
+ *
24
+ * @type {boolean}
25
+ * @memberof ToolResults200Response
26
+ */
27
+ accepted: boolean | null;
28
+ /**
29
+ *
30
+ * @type {boolean}
31
+ * @memberof ToolResults200Response
32
+ */
33
+ duplicate: boolean | null;
34
+ }
35
+
36
+ /**
37
+ * Check if a given object implements the ToolResults200Response interface.
38
+ */
39
+ export function instanceOfToolResults200Response(value: object): value is ToolResults200Response {
40
+ if (!('accepted' in value) || value['accepted'] === undefined) return false;
41
+ if (!('duplicate' in value) || value['duplicate'] === undefined) return false;
42
+ return true;
43
+ }
44
+
45
+ export function ToolResults200ResponseFromJSON(json: any): ToolResults200Response {
46
+ return ToolResults200ResponseFromJSONTyped(json, false);
47
+ }
48
+
49
+ export function ToolResults200ResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ToolResults200Response {
50
+ if (json == null) {
51
+ return json;
52
+ }
53
+ return {
54
+
55
+ 'accepted': json['accepted'],
56
+ 'duplicate': json['duplicate'],
57
+ };
58
+ }
59
+
60
+ export function ToolResults200ResponseToJSON(json: any): ToolResults200Response {
61
+ return ToolResults200ResponseToJSONTyped(json, false);
62
+ }
63
+
64
+ export function ToolResults200ResponseToJSONTyped(value?: ToolResults200Response | null, ignoreDiscriminator: boolean = false): any {
65
+ if (value == null) {
66
+ return value;
67
+ }
68
+
69
+ return {
70
+
71
+ 'accepted': value['accepted'],
72
+ 'duplicate': value['duplicate'],
73
+ };
74
+ }
75
+
@@ -0,0 +1,83 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ /**
4
+ * Sarvam Agents API
5
+ * Chat with a Sarvam agent, exchange files with it, and set it up (instructions, skills, knowledge bases, connectors, deploy) from your own code. Authenticate with a service token sent as a Bearer token, and send the header X-Panja-Origin: managed_agents on every request.
6
+ *
7
+ * The version of the OpenAPI document: 0.1.0
8
+ * Contact: support@sarvam.ai
9
+ *
10
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
11
+ * https://openapi-generator.tech
12
+ * Do not edit the class manually.
13
+ */
14
+
15
+ import { mapValues } from '../runtime.js';
16
+ import type { FunctionResultBody } from './FunctionResultBody.js';
17
+ import {
18
+ FunctionResultBodyFromJSON,
19
+ FunctionResultBodyFromJSONTyped,
20
+ FunctionResultBodyToJSON,
21
+ FunctionResultBodyToJSONTyped,
22
+ } from './FunctionResultBody.js';
23
+
24
+ /**
25
+ *
26
+ * @export
27
+ * @interface ToolResultsBody
28
+ */
29
+ export interface ToolResultsBody {
30
+ /**
31
+ *
32
+ * @type {string}
33
+ * @memberof ToolResultsBody
34
+ */
35
+ requestId: string;
36
+ /**
37
+ *
38
+ * @type {Array<FunctionResultBody>}
39
+ * @memberof ToolResultsBody
40
+ */
41
+ results: Array<FunctionResultBody>;
42
+ }
43
+
44
+ /**
45
+ * Check if a given object implements the ToolResultsBody interface.
46
+ */
47
+ export function instanceOfToolResultsBody(value: object): value is ToolResultsBody {
48
+ if (!('requestId' in value) || value['requestId'] === undefined) return false;
49
+ if (!('results' in value) || value['results'] === undefined) return false;
50
+ return true;
51
+ }
52
+
53
+ export function ToolResultsBodyFromJSON(json: any): ToolResultsBody {
54
+ return ToolResultsBodyFromJSONTyped(json, false);
55
+ }
56
+
57
+ export function ToolResultsBodyFromJSONTyped(json: any, ignoreDiscriminator: boolean): ToolResultsBody {
58
+ if (json == null) {
59
+ return json;
60
+ }
61
+ return {
62
+
63
+ 'requestId': json['requestId'],
64
+ 'results': ((json['results'] as Array<any>).map(FunctionResultBodyFromJSON)),
65
+ };
66
+ }
67
+
68
+ export function ToolResultsBodyToJSON(json: any): ToolResultsBody {
69
+ return ToolResultsBodyToJSONTyped(json, false);
70
+ }
71
+
72
+ export function ToolResultsBodyToJSONTyped(value?: ToolResultsBody | null, ignoreDiscriminator: boolean = false): any {
73
+ if (value == null) {
74
+ return value;
75
+ }
76
+
77
+ return {
78
+
79
+ 'requestId': value['requestId'],
80
+ 'results': ((value['results'] as Array<any>).map(FunctionResultBodyToJSON)),
81
+ };
82
+ }
83
+
@@ -101,6 +101,7 @@ export * from './FileQueuedResponse.js';
101
101
  export * from './FileRawResponse.js';
102
102
  export * from './FileRead.js';
103
103
  export * from './FileWriteBody.js';
104
+ export * from './FunctionResultBody.js';
104
105
  export * from './HTTPValidationError.js';
105
106
  export * from './HighlightRange.js';
106
107
  export * from './InlineCreateSkillBody.js';
@@ -131,6 +132,7 @@ export * from './QueueMessageInput.js';
131
132
  export * from './QueueMessageResult.js';
132
133
  export * from './QueuedTurnView.js';
133
134
  export * from './Reason.js';
135
+ export * from './RequiredAction.js';
134
136
  export * from './Requiredscope.js';
135
137
  export * from './Resourcetype.js';
136
138
  export * from './ResponseCompleteFileUpload.js';
@@ -154,6 +156,8 @@ export * from './StopResponse.js';
154
156
  export * from './TemplateConnectorTag.js';
155
157
  export * from './TemplateWorksWith.js';
156
158
  export * from './TextPart.js';
159
+ export * from './ToolResults200Response.js';
160
+ export * from './ToolResultsBody.js';
157
161
  export * from './TriggerCronBody.js';
158
162
  export * from './TriggerResponse.js';
159
163
  export * from './UIMessage.js';
package/src/streaming.ts CHANGED
@@ -14,13 +14,14 @@
14
14
  * const again = await reconnect(config, conversationId, stream.responseId!, stream.lastEventId);
15
15
  *
16
16
  * Each item is the event's JSON payload (`type` is `start`, `text-delta`, `data-file-shared`,
17
- * `data-clarify-request`, `data-stopped`, `error`, `finish`, ...). The stream keeps `lastEventId` and `responseId`
17
+ * `data-clarify-request`, `data-function-call-request`, `data-stopped`, `error`, `finish`, ...). The stream keeps `lastEventId` and `responseId`
18
18
  * up to date, the two values `reconnect` needs.
19
19
  */
20
20
 
21
21
  import { ClarifyApi } from "./apis/ClarifyApi.js";
22
+ import { FunctionToolsApi } from "./apis/FunctionToolsApi.js";
22
23
  import { ResponsesApi } from "./apis/ResponsesApi.js";
23
- import type { ClarifyBody, ResponseInput } from "./models/index.js";
24
+ import type { ClarifyBody, ResponseInput, ToolResultsBody } from "./models/index.js";
24
25
  import type { ApiResponse, Configuration } from "./runtime.js";
25
26
 
26
27
  /** One event's JSON payload. */
@@ -97,6 +98,9 @@ export async function* iterSse(
97
98
  export class ResponseStream implements AsyncIterable<StreamEvent> {
98
99
  responseId: string | null;
99
100
  lastEventId: string | null;
101
+ /** `postToolResults` only: the server already had these results (a repeat with the same idempotency key), so
102
+ * this stream is empty; follow the turn with `reconnect`. */
103
+ duplicate = false;
100
104
  private readonly body: ReadableStream<Uint8Array>;
101
105
  private readonly controller: AbortController;
102
106
  private readonly idleTimeoutMs: number;
@@ -165,15 +169,25 @@ export class ResponseStream implements AsyncIterable<StreamEvent> {
165
169
  }
166
170
 
167
171
  async function open(
168
- call: (init: RequestInit) => Promise<ApiResponse<string>>,
172
+ call: (init: RequestInit) => Promise<ApiResponse<unknown>>,
169
173
  options: StreamOptions,
170
174
  responseId: string | null = null,
171
175
  lastEventId: string | null = null,
176
+ jsonIsDuplicate = false,
172
177
  ): Promise<ResponseStream> {
173
178
  const controller = new AbortController();
174
179
  options.signal?.addEventListener("abort", () => controller.abort(options.signal!.reason), { once: true });
175
180
  // Non-2xx responses throw ResponseError here, like every other generated method.
176
181
  const response = await call({ signal: controller.signal });
182
+ const contentType = (response.raw.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
183
+ if (jsonIsDuplicate && contentType === "application/json") {
184
+ await response.raw.body?.cancel().catch(() => undefined);
185
+ const empty = new ReadableStream<Uint8Array>({ start: (c) => c.close() });
186
+ const stream = new ResponseStream(empty, controller, options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS);
187
+ stream.duplicate = true;
188
+ stream.close();
189
+ return stream;
190
+ }
177
191
  if (!response.raw.body) throw new Error("response has no body to stream");
178
192
  return new ResponseStream(
179
193
  response.raw.body,
@@ -231,3 +245,25 @@ export function answerClarify(
231
245
  ): Promise<ResponseStream> {
232
246
  return open((init) => new ClarifyApi(config).clarifyRaw({ conversationId, clarifyBody: body }, init), options);
233
247
  }
248
+
249
+ /**
250
+ * Answer the agent's function calls (a `data-function-call-request` event) and stream the rest of the reply.
251
+ * `body.requestId` comes from that event, with one result per call. Send the same `idempotencyKey` when you retry a
252
+ * post: a repeat the server already has resolves to an empty stream with `duplicate` set, and the turn can be followed
253
+ * with `reconnect`.
254
+ */
255
+ export function postToolResults(
256
+ config: Configuration,
257
+ conversationId: string,
258
+ body: ToolResultsBody,
259
+ options: StreamOptions & { idempotencyKey?: string } = {},
260
+ ): Promise<ResponseStream> {
261
+ return open(
262
+ (init) => new FunctionToolsApi(config).toolResultsRaw(
263
+ { conversationId, toolResultsBody: body, idempotencyKey: options.idempotencyKey }, init),
264
+ options,
265
+ null,
266
+ null,
267
+ true,
268
+ );
269
+ }
@@ -0,0 +1,390 @@
1
+ /**
2
+ * Receive the agent's outbound webhooks: verify the signature, then parse the event.
3
+ *
4
+ * Panja signs every delivery in the Standard Webhooks format. Verify against the raw body bytes before parsing:
5
+ *
6
+ * ```ts
7
+ * import { verify, parseEvent } from "sarvam-agents-client/webhooks";
8
+ * verify(rawBody, req.headers, "whsec_..."); // throws WebhookVerificationError
9
+ * const event = parseEvent(rawBody); // TurnCompletedEvent | TurnFailedEvent | ...
10
+ * ```
11
+ *
12
+ * `verify` behaves exactly like the server's reference verifier (`claw_common/webhooks/signing.py`) and the Python
13
+ * SDK's, and is tested against the server's vectors (`shared/webhooks/vectors.json`). Nothing here logs, and no error
14
+ * carries a secret or a signature: errors carry only a closed `reason` token. Uses `node:crypto` only.
15
+ */
16
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
17
+
18
+ /**
19
+ * Every event an `agent.json` webhook may subscribe to. `approval.requested` is reserved: the server accepts it
20
+ * (with the save warning `event_reserved`) but never sends it yet.
21
+ */
22
+ export const WEBHOOK_EVENTS = ["turn.completed", "turn.failed", "turn.requires_action", "approval.requested"] as const;
23
+ export type WebhookEventType = (typeof WEBHOOK_EVENTS)[number];
24
+
25
+ const SECRET_PREFIX = "whsec_";
26
+ const SECRET_MIN_BYTES = 24;
27
+ const SECRET_MAX_BYTES = 64;
28
+ const SIGNATURE_PREFIX = "v1,";
29
+ export const DEFAULT_TOLERANCE_S = 300;
30
+ /** `verify` examines at most this many space-separated signature entries; the rest are ignored. */
31
+ export const MAX_SIGNATURES_EXAMINED = 10;
32
+ /**
33
+ * A longer `webhook-timestamp` is refused as `bad_timestamp`, as on the server (where `int()` caps out at 4300
34
+ * digits); no real time needs more than 20.
35
+ */
36
+ export const MAX_TIMESTAMP_DIGITS = 20;
37
+
38
+ export type SecretFormatReason = "prefix" | "base64" | "length";
39
+ export type VerificationReason =
40
+ | "missing_header"
41
+ | "bad_timestamp"
42
+ | "timestamp_too_old"
43
+ | "timestamp_too_new"
44
+ | "no_matching_signature";
45
+
46
+ /** A secret is not `whsec_` + base64 of 24 to 64 bytes. The message is the reason alone, never the secret. */
47
+ export class SecretFormatError extends Error {
48
+ readonly reason: SecretFormatReason;
49
+ constructor(reason: SecretFormatReason) {
50
+ super(reason);
51
+ this.name = "SecretFormatError";
52
+ this.reason = reason;
53
+ Object.setPrototypeOf(this, new.target.prototype);
54
+ }
55
+ }
56
+
57
+ /** A delivery failed verification. The message is the reason alone. */
58
+ export class WebhookVerificationError extends Error {
59
+ readonly reason: VerificationReason;
60
+ constructor(reason: VerificationReason) {
61
+ super(reason);
62
+ this.name = "WebhookVerificationError";
63
+ this.reason = reason;
64
+ Object.setPrototypeOf(this, new.target.prototype);
65
+ }
66
+ }
67
+
68
+ /** What `verify` vouched for: the `webhook-id` (dedupe on it) and the `webhook-timestamp` in unix seconds. */
69
+ export interface VerifiedMessage {
70
+ msgId: string;
71
+ timestamp: number;
72
+ }
73
+
74
+ /** A fetch `Headers`, or a plain object such as Node's `req.headers`. Names are matched case-insensitively. */
75
+ export type HeadersLike =
76
+ | { forEach(callback: (value: string, key: string) => void): void; get(name: string): string | null }
77
+ | Record<string, string | string[] | undefined>;
78
+
79
+ export type Payload = string | Uint8Array;
80
+
81
+ export interface VerifyOptions {
82
+ /** Seconds the timestamp may differ from `now`; default 300. Must be finite and not negative. */
83
+ tolerance?: number;
84
+ /** The current time in unix seconds; default the clock. Must be finite. */
85
+ now?: number;
86
+ }
87
+
88
+ const B64 = /^[A-Za-z0-9+/]*={0,2}$/;
89
+
90
+ /**
91
+ * Python 3.12's `base64.b64decode(s, validate=True)`: the standard alphabet, padding only at the end and only where
92
+ * it completes the last group; leftover bits in the last character are ignored. Returns null when it would refuse.
93
+ */
94
+ function b64decodeStrict(text: string): Buffer | null {
95
+ if (!B64.test(text)) return null;
96
+ const data = text.replace(/=+$/, "");
97
+ const pads = text.length - data.length;
98
+ const rem = data.length % 4;
99
+ if (!((rem === 0 && pads === 0) || (rem === 2 && pads === 2) || (rem === 3 && pads === 1))) return null;
100
+ return Buffer.from(text, "base64");
101
+ }
102
+
103
+ function parseSecret(secret: string): Buffer {
104
+ if (typeof secret !== "string" || !secret.startsWith(SECRET_PREFIX)) throw new SecretFormatError("prefix");
105
+ const key = b64decodeStrict(secret.slice(SECRET_PREFIX.length));
106
+ if (key === null) throw new SecretFormatError("base64");
107
+ if (key.length < SECRET_MIN_BYTES || key.length > SECRET_MAX_BYTES) throw new SecretFormatError("length");
108
+ return key;
109
+ }
110
+
111
+ function bodyBytes(payload: Payload): Buffer {
112
+ if (typeof payload === "string") return Buffer.from(payload, "utf8");
113
+ return Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength);
114
+ }
115
+
116
+ function mac(key: Buffer, msgId: string, timestamp: string, body: Buffer): Buffer {
117
+ // The exact bytes received; the timestamp is the header string as received (never re-stringified).
118
+ return createHmac("sha256", key).update(Buffer.from(`${msgId}.${timestamp}.`, "utf8")).update(body).digest();
119
+ }
120
+
121
+ /** Lowercased name -> value; for a plain object the last spelling of a name wins, as in the Python verifier. */
122
+ function lowerHeaders(headers: HeadersLike): Map<string, unknown> {
123
+ const out = new Map<string, unknown>();
124
+ if (typeof (headers as { forEach?: unknown }).forEach === "function" &&
125
+ typeof (headers as { get?: unknown }).get === "function") {
126
+ (headers as { forEach(cb: (value: string, key: string) => void): void })
127
+ .forEach((value, key) => out.set(key.toLowerCase(), value));
128
+ return out;
129
+ }
130
+ for (const key of Object.keys(headers)) out.set(key.toLowerCase(), (headers as Record<string, unknown>)[key]);
131
+ return out;
132
+ }
133
+
134
+ function header(headers: Map<string, unknown>, name: string): string {
135
+ const value = headers.get(name);
136
+ return typeof value === "string" ? value : "";
137
+ }
138
+
139
+ // Python's str.split() with no argument: runs of str.isspace() characters (not JavaScript's \s, which adds U+FEFF
140
+ // and lacks U+001C..U+001F and U+0085).
141
+ const PY_WHITESPACE = /[\t\n\v\f\r\x1c-\x20\x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+/;
142
+
143
+ function splitWhitespace(text: string): string[] {
144
+ return text.split(PY_WHITESPACE).filter((part) => part.length > 0);
145
+ }
146
+
147
+ /** A fresh `whsec_` secret of `nbytes` (24 to 64) random bytes, to store as the webhook's vault credential. */
148
+ export function generateSecret(nbytes = 32): string {
149
+ if (!Number.isInteger(nbytes) || nbytes < SECRET_MIN_BYTES || nbytes > SECRET_MAX_BYTES) {
150
+ throw new SecretFormatError("length");
151
+ }
152
+ return SECRET_PREFIX + randomBytes(nbytes).toString("base64");
153
+ }
154
+
155
+ /** `"v1,<base64 HMAC-SHA256>"` over `{msgId}.{timestamp}.{body}`, as the server signs (for tests). */
156
+ export function sign(secret: string, msg: { msgId: string; timestamp: number; body: Payload }): string {
157
+ return SIGNATURE_PREFIX + mac(parseSecret(secret), msg.msgId, String(msg.timestamp), bodyBytes(msg.body))
158
+ .toString("base64");
159
+ }
160
+
161
+ /**
162
+ * Verify a delivery; throws `WebhookVerificationError` (or `SecretFormatError`) if it fails.
163
+ *
164
+ * `payload` is the raw request body (a `Buffer` from `express.raw()`, or the exact text), before any JSON parsing.
165
+ * `secret` is one `whsec_` secret, or several while you rotate. The `webhook-timestamp` must be 1 to 20 ASCII digits
166
+ * within `tolerance` seconds of `now`; it is checked before any HMAC work. Only the first 10 `webhook-signature`
167
+ * entries are examined and entries not starting `v1,` are skipped. Comparisons are constant time. A header given as
168
+ * an array counts as missing. Throws `TypeError` when `now` or `tolerance` is not a finite number, or `tolerance` is
169
+ * negative: `Number(process.env.UNSET)` is NaN, which would quietly turn off the timestamp check. An empty list of
170
+ * secrets throws `TypeError` too: a receiver missing its secret would otherwise refuse every delivery as forged.
171
+ */
172
+ export function verify(
173
+ payload: Payload,
174
+ headers: HeadersLike,
175
+ secret: string | readonly string[],
176
+ opts: VerifyOptions = {},
177
+ ): VerifiedMessage {
178
+ const now = opts.now ?? Math.floor(Date.now() / 1000);
179
+ const tolerance = opts.tolerance ?? DEFAULT_TOLERANCE_S;
180
+ if (!Number.isFinite(now) || !Number.isFinite(tolerance) || tolerance < 0) {
181
+ throw new TypeError("verify: now and tolerance must be finite numbers, and tolerance not negative");
182
+ }
183
+ const secrets = typeof secret === "string" ? [secret] : [...secret];
184
+ // A configuration error: as no_matching_signature it would refuse every genuine delivery.
185
+ if (secrets.length === 0) throw new TypeError("verify: no secrets; pass at least one whsec_ secret");
186
+ const body = bodyBytes(payload);
187
+ const lowered = lowerHeaders(headers);
188
+ const msgId = header(lowered, "webhook-id");
189
+ const rawTs = header(lowered, "webhook-timestamp");
190
+ const rawSigs = header(lowered, "webhook-signature");
191
+ if (!msgId || !rawTs || !rawSigs) throw new WebhookVerificationError("missing_header");
192
+ if (!/^[0-9]+$/.test(rawTs) || rawTs.length > MAX_TIMESTAMP_DIGITS) {
193
+ throw new WebhookVerificationError("bad_timestamp");
194
+ }
195
+ // Exact for every value near the clock; a larger one is far outside the tolerance either way.
196
+ const timestamp = Number(rawTs);
197
+ if (timestamp < now - tolerance) throw new WebhookVerificationError("timestamp_too_old");
198
+ if (timestamp > now + tolerance) throw new WebhookVerificationError("timestamp_too_new");
199
+
200
+ const received: Buffer[] = [];
201
+ for (const entry of splitWhitespace(rawSigs).slice(0, MAX_SIGNATURES_EXAMINED)) {
202
+ if (!entry.startsWith(SIGNATURE_PREFIX)) continue;
203
+ const decoded = b64decodeStrict(entry.slice(SIGNATURE_PREFIX.length));
204
+ if (decoded !== null) received.push(decoded);
205
+ }
206
+
207
+ let matched = false;
208
+ for (const s of secrets) {
209
+ const expected = mac(parseSecret(s), msgId, rawTs, body);
210
+ for (const candidate of received) {
211
+ // no early exit inside the loops: the work does not depend on which entry matches
212
+ if (candidate.length === expected.length && timingSafeEqual(candidate, expected)) matched = true;
213
+ }
214
+ }
215
+ if (!matched) throw new WebhookVerificationError("no_matching_signature");
216
+ return { msgId, timestamp };
217
+ }
218
+
219
+ // -- event payloads ------------------------------------------------------------------------------------------------
220
+ // The wire JSON as sent (camelCase); absent values are null, so the shape is stable. A newer server may add fields.
221
+
222
+ export interface TurnSource {
223
+ /** `message`, `cron` or `subagent_result`. */
224
+ kind: string;
225
+ /** `web`, `cli`, `slack`, `teams`, ... */
226
+ platform: string;
227
+ cronId: string | null;
228
+ scheduleRunId: string | null;
229
+ delegationIds: string[];
230
+ }
231
+
232
+ export interface TurnUsage {
233
+ inputTokens: number | null;
234
+ outputTokens: number | null;
235
+ reasoningTokens: number | null;
236
+ cacheReadTokens: number | null;
237
+ }
238
+
239
+ /** The `agent.json` limit that ended the turn. */
240
+ export interface TurnCap {
241
+ kind: string;
242
+ limit: string;
243
+ value: number | null;
244
+ }
245
+
246
+ export interface TurnData {
247
+ agent: { id: string };
248
+ /** `id` is the platform's conversation key; on web and API sessions, the id `GET /v1/conversations/{id}` takes. */
249
+ conversation: { id: string; sessionId: string };
250
+ /** `id` is the same on every event of a turn; `responseId` is currently always null. */
251
+ turn: { id: string; responseId: string | null };
252
+ source: TurnSource;
253
+ tenantId: string;
254
+ workspaceId: string;
255
+ userId: string;
256
+ /** Fields cut to fit the 64 KiB body cap (`text`, `rawText`, `output`, `actions.<i>.arguments`). */
257
+ truncated: string[];
258
+ }
259
+
260
+ export interface TurnCompletedData extends TurnData {
261
+ status: "completed";
262
+ text: string;
263
+ /** The validated structured output, or null. */
264
+ output: unknown;
265
+ /** `tool_in_loop`, `tool_oversize`, `forced_tool`, `native` or `prompted`; passed through as sent. */
266
+ outputMode: string | null;
267
+ /** `limit`, `budget`, `paused` or `suppressed`; passed through as sent. */
268
+ outputSkipped: string | null;
269
+ cap: TurnCap | null;
270
+ usage: TurnUsage;
271
+ }
272
+
273
+ export interface TurnFailedData extends TurnData {
274
+ status: "failed";
275
+ /** `code`: `user_stop`, `context_overflow`, `persist_failed`, `seat_budget_exhausted_error`, `schema_mismatch`,
276
+ * or `turn_failed`. */
277
+ error: { code: string; message: string };
278
+ /** Schema mismatch only: up to three `path: message` strings. */
279
+ errors: string[] | null;
280
+ /** Schema mismatch only: the model's raw text. */
281
+ rawText: string | null;
282
+ cap: TurnCap | null;
283
+ usage: TurnUsage;
284
+ }
285
+
286
+ export interface ClarifyQuestion {
287
+ id: string;
288
+ prompt: string;
289
+ inputType?: string;
290
+ choices?: string[] | null;
291
+ [key: string]: unknown;
292
+ }
293
+
294
+ export interface ClarifyAction {
295
+ type: "clarify";
296
+ requestId: string;
297
+ questions: ClarifyQuestion[];
298
+ createdAt: string | null;
299
+ expiresAt: string | null;
300
+ }
301
+
302
+ /**
303
+ * A function tool call waiting for its result: answer it with `postToolResults`
304
+ * (`POST /v1/conversations/{id}/tool-results` with `requestId` and this `toolCallId`), or continue the run with
305
+ * `run(agent, RunState.fromSession(...))`. A turn the SDK runner is driving answers its own function calls: don't
306
+ * answer those here too (the second answer gets 409 `already_answered`).
307
+ */
308
+ export interface FunctionCallAction {
309
+ type: "function_call";
310
+ requestId: string;
311
+ toolCallId: string;
312
+ name: string;
313
+ /** null when it was cut to fit the body cap (`truncated` lists `actions.<i>.arguments`). */
314
+ arguments: Record<string, unknown> | null;
315
+ createdAt: string | null;
316
+ expiresAt: string | null;
317
+ }
318
+
319
+ /**
320
+ * An action of a type this SDK release does not know, as sent. It is not part of `RequiredAction`, so narrowing on
321
+ * `type` keeps working; a newer server may still send one, so keep a default branch when you switch on `type`.
322
+ */
323
+ export interface UnknownAction {
324
+ type: string;
325
+ [key: string]: unknown;
326
+ }
327
+
328
+ /**
329
+ * Same shape as `requiredActions` on `GET /v1/conversations/{id}`. A newer server may send other action types
330
+ * (`UnknownAction`): `parseEvent` passes them through, so handle a `type` you don't know in a default branch.
331
+ */
332
+ export type RequiredAction = ClarifyAction | FunctionCallAction;
333
+
334
+ export interface TurnRequiresActionData extends TurnData {
335
+ status: "requires_action";
336
+ requestId: string;
337
+ /** `clarify` or `function_call`. */
338
+ kind: string;
339
+ expiresAt: string | null;
340
+ actions: RequiredAction[];
341
+ }
342
+
343
+ interface Envelope<T extends string, D> {
344
+ type: T;
345
+ id: string;
346
+ /** When the event was built: ISO 8601, UTC, milliseconds (`2026-11-11T10:15:42.123Z`). */
347
+ timestamp: string;
348
+ data: D;
349
+ }
350
+
351
+ export type TurnCompletedEvent = Envelope<"turn.completed", TurnCompletedData>;
352
+ export type TurnFailedEvent = Envelope<"turn.failed", TurnFailedData>;
353
+ export type TurnRequiresActionEvent = Envelope<"turn.requires_action", TurnRequiresActionData>;
354
+ export type WebhookEvent = TurnCompletedEvent | TurnFailedEvent | TurnRequiresActionEvent;
355
+
356
+ const STATUS = new Map<string, string>([
357
+ ["turn.completed", "completed"],
358
+ ["turn.failed", "failed"],
359
+ ["turn.requires_action", "requires_action"],
360
+ ]);
361
+
362
+ function isObject(value: unknown): value is Record<string, unknown> {
363
+ return typeof value === "object" && value !== null && !Array.isArray(value);
364
+ }
365
+
366
+ /**
367
+ * The typed event of a verified body (raw bytes, text or an already-parsed object).
368
+ *
369
+ * Returns `undefined` for an event type this SDK release doesn't know (reply 2xx and skip it). Throws `TypeError`
370
+ * when the body is not a webhook event or its `data.status` doesn't match its type. Only the envelope is checked;
371
+ * the fields are typed as the server documents them.
372
+ */
373
+ export function parseEvent(payload: Payload | Record<string, unknown>): WebhookEvent | undefined {
374
+ let raw: unknown = payload;
375
+ if (typeof payload === "string" || payload instanceof Uint8Array) {
376
+ try {
377
+ raw = JSON.parse(typeof payload === "string" ? payload : bodyBytes(payload).toString("utf8"));
378
+ } catch {
379
+ throw new TypeError("webhook body is not JSON");
380
+ }
381
+ }
382
+ if (!isObject(raw) || typeof raw.type !== "string") throw new TypeError("webhook body is not an event: no string 'type'");
383
+ const status = STATUS.get(raw.type);
384
+ if (status === undefined) return undefined;
385
+ if (typeof raw.id !== "string" || typeof raw.timestamp !== "string" || !isObject(raw.data) ||
386
+ raw.data.status !== status) {
387
+ throw new TypeError(`webhook body is not a ${raw.type} event`);
388
+ }
389
+ return raw as unknown as WebhookEvent;
390
+ }