sarvam-agents-client 0.5.2 → 0.5.4

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/README.md +52 -29
  2. package/dist/apis/AgentsApi.d.ts +96 -11
  3. package/dist/apis/AgentsApi.js +229 -9
  4. package/dist/apis/ConversationsApi.d.ts +5 -2
  5. package/dist/apis/ConversationsApi.js +7 -2
  6. package/dist/client.d.ts +3 -2
  7. package/dist/client.js +2 -1
  8. package/dist/compat/core/agents.d.ts +6 -1
  9. package/dist/compat/core/agents.js +237 -27
  10. package/dist/compat/core/customApis.d.ts +76 -0
  11. package/dist/compat/core/customApis.js +424 -0
  12. package/dist/compat/core/data.js +1 -1
  13. package/dist/compat/openai/client.d.ts +3 -0
  14. package/dist/compat/openai/client.js +5 -1
  15. package/dist/compat/openai/index.d.ts +1 -0
  16. package/dist/compat/openai/index.js +0 -1
  17. package/dist/compat/openai/resources/agents.js +8 -1
  18. package/dist/compat/openai/resources/sarvam.d.ts +26 -0
  19. package/dist/compat/openai/resources/sarvam.js +56 -0
  20. package/dist/compose/deploy.d.ts +14 -3
  21. package/dist/compose/deploy.js +60 -7
  22. package/dist/compose/errors.d.ts +4 -0
  23. package/dist/compose/errors.js +6 -1
  24. package/dist/compose/settingsTransport.d.ts +18 -13
  25. package/dist/compose/settingsTransport.js +78 -130
  26. package/dist/compose/transport.d.ts +12 -2
  27. package/dist/compose/webhook.d.ts +10 -13
  28. package/dist/compose/webhook.js +48 -45
  29. package/dist/compose/webhookSecrets.d.ts +79 -49
  30. package/dist/compose/webhookSecrets.js +244 -195
  31. package/dist/esm/apis/AgentsApi.d.ts +96 -11
  32. package/dist/esm/apis/AgentsApi.js +230 -10
  33. package/dist/esm/apis/ConversationsApi.d.ts +5 -2
  34. package/dist/esm/apis/ConversationsApi.js +7 -2
  35. package/dist/esm/client.d.ts +3 -2
  36. package/dist/esm/client.js +2 -1
  37. package/dist/esm/compat/core/agents.d.ts +6 -1
  38. package/dist/esm/compat/core/agents.js +237 -27
  39. package/dist/esm/compat/core/customApis.d.ts +76 -0
  40. package/dist/esm/compat/core/customApis.js +419 -0
  41. package/dist/esm/compat/core/data.js +1 -1
  42. package/dist/esm/compat/openai/client.d.ts +3 -0
  43. package/dist/esm/compat/openai/client.js +5 -1
  44. package/dist/esm/compat/openai/index.d.ts +1 -0
  45. package/dist/esm/compat/openai/index.js +0 -1
  46. package/dist/esm/compat/openai/resources/agents.js +8 -1
  47. package/dist/esm/compat/openai/resources/sarvam.d.ts +26 -0
  48. package/dist/esm/compat/openai/resources/sarvam.js +51 -0
  49. package/dist/esm/compose/deploy.d.ts +14 -3
  50. package/dist/esm/compose/deploy.js +60 -7
  51. package/dist/esm/compose/errors.d.ts +4 -0
  52. package/dist/esm/compose/errors.js +4 -0
  53. package/dist/esm/compose/settingsTransport.d.ts +18 -13
  54. package/dist/esm/compose/settingsTransport.js +80 -132
  55. package/dist/esm/compose/transport.d.ts +12 -2
  56. package/dist/esm/compose/webhook.d.ts +10 -13
  57. package/dist/esm/compose/webhook.js +45 -42
  58. package/dist/esm/compose/webhookSecrets.d.ts +79 -49
  59. package/dist/esm/compose/webhookSecrets.js +241 -193
  60. package/dist/esm/index.d.ts +2 -1
  61. package/dist/esm/index.js +2 -1
  62. package/dist/esm/models/AgentConversationDetail.d.ts +12 -0
  63. package/dist/esm/models/AgentConversationDetail.js +4 -0
  64. package/dist/esm/models/AgentConversationView.d.ts +12 -0
  65. package/dist/esm/models/AgentConversationView.js +4 -0
  66. package/dist/esm/models/AgentResource.d.ts +7 -0
  67. package/dist/esm/models/AgentResource.js +3 -0
  68. package/dist/esm/models/AgentVersionSavedResource.d.ts +65 -0
  69. package/dist/esm/models/AgentVersionSavedResource.js +60 -0
  70. package/dist/esm/models/AgentWebhookList.d.ts +33 -0
  71. package/dist/esm/models/AgentWebhookList.js +44 -0
  72. package/dist/esm/models/AgentWebhookView.d.ts +76 -0
  73. package/dist/esm/models/AgentWebhookView.js +70 -0
  74. package/dist/esm/models/ConversationDetail.d.ts +6 -0
  75. package/dist/esm/models/ConversationDetail.js +2 -0
  76. package/dist/esm/models/ConversationView.d.ts +6 -0
  77. package/dist/esm/models/ConversationView.js +2 -0
  78. package/dist/esm/models/ErrorDetailItem.d.ts +3 -0
  79. package/dist/esm/models/FileNodeView.d.ts +7 -0
  80. package/dist/esm/models/FileNodeView.js +3 -0
  81. package/dist/esm/models/QueueMessageInput.d.ts +6 -0
  82. package/dist/esm/models/QueueMessageInput.js +2 -0
  83. package/dist/esm/models/RotatedWebhookSecretView.d.ts +58 -0
  84. package/dist/esm/models/RotatedWebhookSecretView.js +61 -0
  85. package/dist/esm/models/SaveWarningView.d.ts +44 -0
  86. package/dist/esm/models/SaveWarningView.js +51 -0
  87. package/dist/esm/models/ShareSkippedResource.d.ts +41 -0
  88. package/dist/esm/models/ShareSkippedResource.js +47 -0
  89. package/dist/esm/models/WebhookSecretPutBody.d.ts +32 -0
  90. package/dist/esm/models/WebhookSecretPutBody.js +43 -0
  91. package/dist/esm/models/WebhookSecretStateView.d.ts +52 -0
  92. package/dist/esm/models/WebhookSecretStateView.js +56 -0
  93. package/dist/esm/models/WebhookSecretValueView.d.ts +32 -0
  94. package/dist/esm/models/WebhookSecretValueView.js +44 -0
  95. package/dist/esm/models/WebhookWarning.d.ts +44 -0
  96. package/dist/esm/models/WebhookWarning.js +51 -0
  97. package/dist/esm/models/index.d.ts +10 -0
  98. package/dist/esm/models/index.js +10 -0
  99. package/dist/index.d.ts +2 -1
  100. package/dist/index.js +4 -1
  101. package/dist/models/AgentConversationDetail.d.ts +12 -0
  102. package/dist/models/AgentConversationDetail.js +4 -0
  103. package/dist/models/AgentConversationView.d.ts +12 -0
  104. package/dist/models/AgentConversationView.js +4 -0
  105. package/dist/models/AgentResource.d.ts +7 -0
  106. package/dist/models/AgentResource.js +3 -0
  107. package/dist/models/AgentVersionSavedResource.d.ts +65 -0
  108. package/dist/models/AgentVersionSavedResource.js +67 -0
  109. package/dist/models/AgentWebhookList.d.ts +33 -0
  110. package/dist/models/AgentWebhookList.js +51 -0
  111. package/dist/models/AgentWebhookView.d.ts +76 -0
  112. package/dist/models/AgentWebhookView.js +78 -0
  113. package/dist/models/ConversationDetail.d.ts +6 -0
  114. package/dist/models/ConversationDetail.js +2 -0
  115. package/dist/models/ConversationView.d.ts +6 -0
  116. package/dist/models/ConversationView.js +2 -0
  117. package/dist/models/ErrorDetailItem.d.ts +3 -0
  118. package/dist/models/FileNodeView.d.ts +7 -0
  119. package/dist/models/FileNodeView.js +3 -0
  120. package/dist/models/QueueMessageInput.d.ts +6 -0
  121. package/dist/models/QueueMessageInput.js +2 -0
  122. package/dist/models/RotatedWebhookSecretView.d.ts +58 -0
  123. package/dist/models/RotatedWebhookSecretView.js +69 -0
  124. package/dist/models/SaveWarningView.d.ts +44 -0
  125. package/dist/models/SaveWarningView.js +58 -0
  126. package/dist/models/ShareSkippedResource.d.ts +41 -0
  127. package/dist/models/ShareSkippedResource.js +54 -0
  128. package/dist/models/WebhookSecretPutBody.d.ts +32 -0
  129. package/dist/models/WebhookSecretPutBody.js +50 -0
  130. package/dist/models/WebhookSecretStateView.d.ts +52 -0
  131. package/dist/models/WebhookSecretStateView.js +64 -0
  132. package/dist/models/WebhookSecretValueView.d.ts +32 -0
  133. package/dist/models/WebhookSecretValueView.js +51 -0
  134. package/dist/models/WebhookWarning.d.ts +44 -0
  135. package/dist/models/WebhookWarning.js +58 -0
  136. package/dist/models/index.d.ts +10 -0
  137. package/dist/models/index.js +10 -0
  138. package/package.json +1 -1
  139. package/src/apis/AgentsApi.ts +366 -11
  140. package/src/apis/ConversationsApi.ts +9 -2
  141. package/src/client.ts +3 -2
  142. package/src/compat/core/agents.ts +265 -36
  143. package/src/compat/core/customApis.ts +506 -0
  144. package/src/compat/core/data.ts +1 -1
  145. package/src/compat/openai/client.ts +7 -1
  146. package/src/compat/openai/index.ts +9 -0
  147. package/src/compat/openai/resources/agents.ts +9 -1
  148. package/src/compat/openai/resources/sarvam.ts +94 -0
  149. package/src/compose/deploy.ts +71 -10
  150. package/src/compose/errors.ts +4 -0
  151. package/src/compose/settingsTransport.ts +78 -131
  152. package/src/compose/transport.ts +10 -2
  153. package/src/compose/webhook.ts +49 -45
  154. package/src/compose/webhookSecrets.ts +227 -179
  155. package/src/index.ts +2 -1
  156. package/src/models/AgentConversationDetail.ts +16 -0
  157. package/src/models/AgentConversationView.ts +16 -0
  158. package/src/models/AgentResource.ts +15 -0
  159. package/src/models/AgentVersionSavedResource.ts +119 -0
  160. package/src/models/AgentWebhookList.ts +74 -0
  161. package/src/models/AgentWebhookView.ts +129 -0
  162. package/src/models/ConversationDetail.ts +8 -0
  163. package/src/models/ConversationView.ts +8 -0
  164. package/src/models/ErrorDetailItem.ts +3 -0
  165. package/src/models/FileNodeView.ts +16 -0
  166. package/src/models/QueueMessageInput.ts +8 -0
  167. package/src/models/RotatedWebhookSecretView.ts +103 -0
  168. package/src/models/SaveWarningView.ts +84 -0
  169. package/src/models/ShareSkippedResource.ts +78 -0
  170. package/src/models/WebhookSecretPutBody.ts +66 -0
  171. package/src/models/WebhookSecretStateView.ts +94 -0
  172. package/src/models/WebhookSecretValueView.ts +66 -0
  173. package/src/models/WebhookWarning.ts +84 -0
  174. package/src/models/index.ts +10 -0
@@ -0,0 +1,94 @@
1
+ /** Sarvam-specific helper namespace (client.sarvam.customApis). */
2
+ import {
3
+ CustomApis,
4
+ type CustomApiAgentEntry,
5
+ type CustomApiCreateParams,
6
+ type CustomApiInfo,
7
+ type CustomApiUpdateParams,
8
+ } from "../../core/customApis.js";
9
+ import { Http, type PerCallRequestOptions } from "../../core/http.js";
10
+ import { wrapCoreErrors } from "../errors.js";
11
+ import type { RequestOptions } from "../types.js";
12
+
13
+ function toPerCallOpts(options?: RequestOptions): PerCallRequestOptions {
14
+ if (!options) return {};
15
+ return {
16
+ timeout: options.timeout,
17
+ maxRetries: options.maxRetries,
18
+ headers: options.headers,
19
+ query: options.query,
20
+ signal: options.signal,
21
+ idempotencyKey: options.idempotencyKey,
22
+ };
23
+ }
24
+
25
+ export class CustomApisResource {
26
+ constructor(
27
+ private readonly http: Http,
28
+ private readonly core: CustomApis,
29
+ ) {}
30
+
31
+ async list(opts: { q?: string } = {}, options?: RequestOptions): Promise<CustomApiInfo[]> {
32
+ return wrapCoreErrors(() =>
33
+ this.http.withRequestOptions(toPerCallOpts(options), () => this.core.list(opts)),
34
+ );
35
+ }
36
+
37
+ async get(customApiId: string, options?: RequestOptions): Promise<CustomApiInfo> {
38
+ return wrapCoreErrors(() =>
39
+ this.http.withRequestOptions(toPerCallOpts(options), () => this.core.get(customApiId)),
40
+ );
41
+ }
42
+
43
+ async retrieve(customApiId: string, options?: RequestOptions): Promise<CustomApiInfo> {
44
+ return this.get(customApiId, options);
45
+ }
46
+
47
+ async create(params: CustomApiCreateParams, options?: RequestOptions): Promise<CustomApiInfo> {
48
+ return wrapCoreErrors(() =>
49
+ this.http.withRequestOptions(toPerCallOpts(options), () => this.core.create(params)),
50
+ );
51
+ }
52
+
53
+ async update(
54
+ customApiId: string,
55
+ params: CustomApiUpdateParams,
56
+ options?: RequestOptions,
57
+ ): Promise<CustomApiInfo> {
58
+ return wrapCoreErrors(() =>
59
+ this.http.withRequestOptions(toPerCallOpts(options), () => this.core.update(customApiId, params)),
60
+ );
61
+ }
62
+
63
+ async delete(customApiId: string, opts: { force?: boolean } = {}, options?: RequestOptions): Promise<void> {
64
+ await wrapCoreErrors(() =>
65
+ this.http.withRequestOptions(toPerCallOpts(options), () => this.core.delete(customApiId, opts)),
66
+ );
67
+ }
68
+
69
+ async listForAgent(agentId: string, options?: RequestOptions): Promise<CustomApiAgentEntry[]> {
70
+ return wrapCoreErrors(() =>
71
+ this.http.withRequestOptions(toPerCallOpts(options), () => this.core.listForAgent(agentId)),
72
+ );
73
+ }
74
+
75
+ async bind(agentId: string, customApiId: string, options?: RequestOptions): Promise<void> {
76
+ await wrapCoreErrors(() =>
77
+ this.http.withRequestOptions(toPerCallOpts(options), () => this.core.bind(agentId, customApiId)),
78
+ );
79
+ }
80
+
81
+ async unbind(agentId: string, customApiId: string, options?: RequestOptions): Promise<void> {
82
+ await wrapCoreErrors(() =>
83
+ this.http.withRequestOptions(toPerCallOpts(options), () => this.core.unbind(agentId, customApiId)),
84
+ );
85
+ }
86
+ }
87
+
88
+ export class SarvamResource {
89
+ readonly customApis: CustomApisResource;
90
+
91
+ constructor(http: Http, customApis: CustomApis) {
92
+ this.customApis = new CustomApisResource(http, customApis);
93
+ }
94
+ }
@@ -15,13 +15,19 @@ export interface Deployment {
15
15
  /** The live version, or while the agent is paused, the paused version (what `resumeAgent` brings back); undefined
16
16
  * from a server without versions, or when no version was ever live. */
17
17
  version?: number;
18
- /** URLs of the webhooks that still have no signing secret: this deploy stored a placeholder secret nobody holds so
19
- * the server accepts them. Call `client.webhooks.setSecret(agentId, url)` for each before pointing a provider at
20
- * the agent; until then deliveries fail verification. Left out when there are none. */
18
+ /** URLs of the agent's webhooks that have no signing secret after this deploy: one it added whose secret it could
19
+ * not create (it warned why), or one deployed before whose secret is missing (deleted, perhaps on purpose; deploy
20
+ * never recreates it). Nothing is delivered to them: `client.webhooks.createSecret(agentId, url)` gives one. Left
21
+ * out when there are none. */
21
22
  webhooksMissingSecret?: string[];
22
23
  /** The token (and fire URL) of each bearer trigger this deploy created. The server shows a token only once: keep
23
24
  * it now. Left out when nothing was minted; `client.triggers.list(agentId)` lists every trigger's URL. */
24
25
  triggerTokens?: MintedTriggerToken[];
26
+ /** The signing secret this deploy created for each webhook it added (every webhook on a first deploy), by URL. Give each to its receiver
27
+ * now (`client.webhooks.getSecret` shows it again). A webhook that already had a secret keeps it and is not listed.
28
+ * The property is non-enumerable, so logging or serialising the deployment leaves it out. Left out when deploy
29
+ * created none. */
30
+ readonly webhookSecrets?: Readonly<Record<string, string>>;
25
31
  }
26
32
 
27
33
  let defaultClient: Configuration | null = null;
@@ -66,7 +72,11 @@ function changedFields(remote: RemoteAgent, agent: Agent<OutputType | undefined>
66
72
  return keys;
67
73
  }
68
74
 
69
- async function update(transport: Transport, remote: RemoteAgent, agent: Agent<OutputType | undefined>, strict: boolean): Promise<Deployment> {
75
+ /** What this deploy added: the URLs of the webhooks it adds, set before the write. */
76
+ interface Added { urls: Set<string> }
77
+
78
+ async function update(transport: Transport, remote: RemoteAgent, agent: Agent<OutputType | undefined>, strict: boolean,
79
+ added: Added): Promise<Deployment> {
70
80
  const stored = storedHash(remote);
71
81
  if (stored !== undefined && settingsFingerprint(remote.instructions, remote.settings) !== stored) {
72
82
  const changed = changedFields(remote, agent);
@@ -75,8 +85,9 @@ async function update(transport: Transport, remote: RemoteAgent, agent: Agent<Ou
75
85
  `agent "${agent.name}" (${remote.agentId}) was edited outside the SDK; overwriting fields: ${changed.join(", ")}`,
76
86
  );
77
87
  } else if (stored === agent.specHash()) {
78
- return settle(transport, remote, agent);
88
+ return settle(transport, remote, agent, added);
79
89
  }
90
+ added.urls = await addedUrls(transport, remote, agent);
80
91
  const updated = await transport.updateAgent(remote.agentId, agent);
81
92
  return deployment(remote.agentId, "updated", liveVersion(updated), missingSecrets(updated), updated?.triggerTokens);
82
93
  }
@@ -89,6 +100,38 @@ function deployment(agentId: string, action: Deployment["action"], version: numb
89
100
  return out;
90
101
  }
91
102
 
103
+ /**
104
+ * The URLs of `agent`'s webhooks that this deploy adds: not in the agent.json last deployed (read before the write,
105
+ * with the transport's optional `deployedWebhookUrls`). Nothing deployed yet: every webhook. A read that fails
106
+ * (`null`), or a transport that cannot tell: none, so a secret is never created for a webhook deployed before.
107
+ */
108
+ async function addedUrls(transport: Transport, remote: RemoteAgent, agent: Agent<OutputType | undefined>):
109
+ Promise<Set<string>> {
110
+ const urls = (agent.webhooks ?? []).map((h) => h.url);
111
+ if (urls.length === 0 || transport.deployedWebhookUrls === undefined) return new Set();
112
+ const previous = await transport.deployedWebhookUrls(remote.agentId, remote.liveVersion, remote.versionState);
113
+ if (previous === null) return new Set();
114
+ return new Set(urls.filter((u) => !previous.has(u)));
115
+ }
116
+
117
+ /**
118
+ * Create the signing secret of each webhook this deploy added (a URL not in the agent.json last deployed; on a first
119
+ * deploy, every webhook) when it has none. A webhook deployed before is never given a secret here, even when it has
120
+ * none (its owner may have deleted it on purpose): it is listed in `webhooksMissingSecret`, like a webhook whose create
121
+ * failed. Never rotates or overwrites a secret, and a failure never fails the deploy.
122
+ */
123
+ async function withWebhookSecrets(transport: Transport, agent: Agent<OutputType | undefined>,
124
+ out: Deployment, added: Set<string>): Promise<Deployment> {
125
+ if (!agent.webhooks || agent.webhooks.length === 0 || transport.createWebhookSecrets === undefined) return out;
126
+ const { created, missing } = await transport.createWebhookSecrets(out.agentId, agent, added);
127
+ const allMissing = [...new Set([...(out.webhooksMissingSecret ?? []), ...missing])];
128
+ if (allMissing.length > 0) out.webhooksMissingSecret = allMissing;
129
+ if (Object.keys(created).length > 0) {
130
+ Object.defineProperty(out, "webhookSecrets", { value: Object.freeze({ ...created }), enumerable: false });
131
+ }
132
+ return out;
133
+ }
134
+
92
135
  function missingSecrets(remote: RemoteAgent | undefined | null): string[] {
93
136
  const missing = remote?.webhooksMissingSecret;
94
137
  return Array.isArray(missing) ? [...missing] : [];
@@ -121,16 +164,19 @@ function liveVersion(remote: RemoteAgent | undefined | null): number | undefined
121
164
  * goes live again with the next deploy of a changed definition. Only an agent with no live version that was never
122
165
  * paused (created, but its first deploy did not finish) is published here.
123
166
  */
124
- async function settle(transport: Transport, remote: RemoteAgent, agent: Agent<OutputType | undefined>): Promise<Deployment> {
167
+ async function settle(transport: Transport, remote: RemoteAgent, agent: Agent<OutputType | undefined>,
168
+ added: Added): Promise<Deployment> {
125
169
  const state = remote.versionState;
126
170
  if (state === undefined || state === "live" || state === "paused" || !transport.publish) {
127
171
  if (state === "live") await checkTriggers(transport, remote, agent);
128
172
  return deployment(remote.agentId, "unchanged", remote.liveVersion);
129
173
  }
174
+ added.urls = await addedUrls(transport, remote, agent);
130
175
  return published(remote.agentId, await transport.publish(remote.agentId, VERSION_NOTE));
131
176
  }
132
177
 
133
- async function deployWith(agent: Agent<OutputType | undefined>, transport: Transport, strict: boolean, adopt?: string): Promise<Deployment> {
178
+ async function deployWith(agent: Agent<OutputType | undefined>, transport: Transport, strict: boolean, added: Added,
179
+ adopt?: string): Promise<Deployment> {
134
180
  const found = await transport.findAgents(agent.name);
135
181
  if (adopt !== undefined) {
136
182
  const target = await transport.readAgent(adopt);
@@ -143,15 +189,17 @@ async function deployWith(agent: Agent<OutputType | undefined>, transport: Trans
143
189
  if (others.length) {
144
190
  throw new UserError(`cannot adopt ${adopt}: agent "${agent.name}" is already deployed as ${others.join(", ")}`);
145
191
  }
192
+ added.urls = await addedUrls(transport, target, agent);
146
193
  const adopted = await transport.updateAgent(adopt, agent);
147
194
  return deployment(adopt, "updated", liveVersion(adopted), missingSecrets(adopted), adopted?.triggerTokens);
148
195
  }
149
196
  if (found.length > 1) throw new DuplicateAgentsError(found.map((r) => r.agentId));
150
197
  if (found.length === 0) {
198
+ added.urls = new Set((agent.webhooks ?? []).map((h) => h.url)); // a new agent: every webhook is new
151
199
  const created = await transport.createAgent(agent);
152
200
  return deployment(created.agentId, "created", liveVersion(created), missingSecrets(created), created.triggerTokens);
153
201
  }
154
- return update(transport, found[0], agent, strict);
202
+ return update(transport, found[0], agent, strict, added);
155
203
  }
156
204
 
157
205
  /**
@@ -183,6 +231,11 @@ async function findDeployed(agent: Agent<OutputType | undefined>, transport: Tra
183
231
  * saves any edits the owner left in the draft, so check the draft first. `strict: true` throws `DriftError` instead of
184
232
  * overwriting fields edited outside the SDK. `adopt: agentId` takes over an agent made elsewhere. `version` is the live
185
233
  * version (the paused one while paused).
234
+ *
235
+ * The deploy then creates the signing secret of each webhook it added (a URL not in the agent.json last deployed;
236
+ * every webhook on a first deploy) and returns it once in `webhookSecrets` (by URL). An existing secret is never
237
+ * rotated or overwritten, and a missing one on a webhook deployed before is never recreated: it is listed in
238
+ * `webhooksMissingSecret`.
186
239
  */
187
240
  export async function deploy(
188
241
  agent: Agent<OutputType | undefined>,
@@ -190,7 +243,11 @@ export async function deploy(
190
243
  ): Promise<Deployment> {
191
244
  const transport = resolveTransport(opts.client, opts.transport);
192
245
  forget(agent.name); // this deploy may replace what cached runs of the name point at
193
- return serialized(agent.name, () => deployWith(agent, transport, opts.strict ?? false, opts.adopt));
246
+ return serialized(agent.name, async () => {
247
+ const added: Added = { urls: new Set() };
248
+ const out = await deployWith(agent, transport, opts.strict ?? false, added, opts.adopt);
249
+ return withWebhookSecrets(transport, agent, out, added.urls);
250
+ });
194
251
  }
195
252
 
196
253
  /**
@@ -285,7 +342,11 @@ export function agentIdFor(
285
342
  const prev = owners.get(owner);
286
343
  if (prev && prev.hash === hash) return prev.id;
287
344
  const id = deploy
288
- ? serialized(agent.name, () => deployWith(agent, transport, false)).then((d) => d.agentId)
345
+ ? serialized(agent.name, async () => {
346
+ // As deploy(): the webhooks a run's deploy adds get their secrets (client.webhooks.getSecret shows them).
347
+ const added: Added = { urls: new Set() };
348
+ return withWebhookSecrets(transport, agent, await deployWith(agent, transport, false, added), added.urls);
349
+ }).then((d) => d.agentId)
289
350
  : serialized(agent.name, () => findDeployed(agent, transport));
290
351
  const entry: Entry = { hash, id };
291
352
  owners.set(owner, entry);
@@ -19,6 +19,10 @@ export class UserError extends AgentsError {
19
19
  }
20
20
  }
21
21
 
22
+ /** `client.webhooks.createSecret`: the webhook already has a signing secret. Rotate it (`rotateSecret`), view it
23
+ * (`getSecret`), or delete it first. */
24
+ export class SecretExistsError extends UserError {}
25
+
22
26
  /** Where a `ModelBehaviorError` came from: the server's check, or the `outputType`'s own `parse`. */
23
27
  export type ModelBehaviorErrorSource = "server" | "local_parse";
24
28
 
@@ -2,7 +2,6 @@
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { AgentsApi } from "../apis/AgentsApi.js";
4
4
  import { ConversationsApi } from "../apis/ConversationsApi.js";
5
- import { CustomAPIsApi } from "../apis/CustomAPIsApi.js";
6
5
  import { ResponsesApi } from "../apis/ResponsesApi.js";
7
6
  import { TriggersApi } from "../apis/TriggersApi.js";
8
7
  import { FetchError, ResponseError } from "../runtime.js";
@@ -16,9 +15,8 @@ import { chunksFromUiMessage, fromUiChunk } from "./events.js";
16
15
  import type { Event } from "./events.js";
17
16
  import type { FunctionResult } from "./functionTool.js";
18
17
  import { VERSION_NOTE } from "./transport.js";
19
- import { secretCredentialName, urlProblem } from "./webhook.js";
20
- import { secretBackend } from "./webhookSecrets.js";
21
- import type { SecretBackend } from "./webhookSecrets.js";
18
+ import { withoutLegacyCredentials } from "./webhook.js";
19
+ import { createMissingSecrets } from "./webhookSecrets.js";
22
20
  import type {
23
21
  PendingFunctionCalls, Published, RemoteAgent, SettingsWarning, Transport, TurnStream,
24
22
  } from "./transport.js";
@@ -213,42 +211,15 @@ interface Envelope {
213
211
  warnings?: SettingsWarning[] | null;
214
212
  }
215
213
 
216
- /** `settings` for a new agent's first write: no `webhooks` (the server checks them against the agent's bound
217
- * credentials, and a new agent has none yet) and no `sdk_hash` (it covers the webhooks, so an agent left in this
218
- * state would otherwise read as deployed and never get them). */
214
+ /** `settings` for a new agent's first write: no `webhooks` (written by the second write, whose envelope carries the
215
+ * save's webhook warnings) and no `sdk_hash` (it covers the webhooks, so an agent left in this state would otherwise
216
+ * read as deployed and never get them). */
219
217
  function withoutWebhooks(settings: Record<string, any>): Record<string, any> {
220
218
  const { webhooks: _webhooks, ...out } = settings;
221
219
  const { sdk_hash: _hash, ...metadata } = settings["metadata"];
222
220
  return { ...out, metadata };
223
221
  }
224
222
 
225
- type Hook = Record<string, unknown>;
226
-
227
- function hooksOf(settings: Record<string, any>): Hook[] {
228
- const hooks = settings["webhooks"];
229
- return Array.isArray(hooks) ? hooks.filter((h) => typeof h === "object" && h !== null && !Array.isArray(h)) : [];
230
- }
231
-
232
- function sdkNamed(agentId: string, hook: Hook): boolean {
233
- const url = hook["url"];
234
- return typeof url === "string" && urlProblem(url) === null &&
235
- hook["secret_credential"] === secretCredentialName(agentId, url);
236
- }
237
-
238
- /** `settings` as a definition writes them: a webhook whose `secret_credential` is the one `deploy` filled in loses it
239
- * again, so the stored `sdk_hash` (computed without it) still matches. */
240
- function asDefined(agentId: string, settings: Record<string, any>): Record<string, any> {
241
- if (!hooksOf(settings).some((h) => sdkNamed(agentId, h))) return settings;
242
- return {
243
- ...settings,
244
- webhooks: (settings["webhooks"] as unknown[]).map((h) => {
245
- if (typeof h !== "object" || h === null || !sdkNamed(agentId, h as Hook)) return h;
246
- const { secret_credential: _name, ...rest } = h as Hook;
247
- return rest;
248
- }),
249
- };
250
- }
251
-
252
223
  /** The deploy response's `triggerTokens` (the server shows each token once); never logged. An entry missing a field
253
224
  * is skipped with a warning that names the trigger, never the token. */
254
225
  function triggerTokens(resource: { triggerTokens?: { name: string; triggerId: string; url: string; token: string }[] | null }):
@@ -267,6 +238,13 @@ function triggerTokens(resource: { triggerTokens?: { name: string; triggerId: st
267
238
  return out;
268
239
  }
269
240
 
241
+ /** A v2 agent write's `webhookWarnings` (`host_unresolvable`). */
242
+ function logWebhookWarnings(agentId: string, resource: unknown): void {
243
+ const items = (resource as { webhookWarnings?: { code?: string; path?: string; message?: string }[] | null } | null)
244
+ ?.webhookWarnings ?? [];
245
+ for (const w of items) console.warn(`agent ${agentId}: webhook warning ${w?.code} at ${w?.path}: ${w?.message}`);
246
+ }
247
+
270
248
  function isNotFound(err: unknown): boolean {
271
249
  return err instanceof ResponseError && err.response.status === 404;
272
250
  }
@@ -305,17 +283,13 @@ export class SettingsTransport implements Transport {
305
283
  private readonly agents: AgentsApi;
306
284
  private readonly conversations: ConversationsApi;
307
285
  private readonly responses: ResponsesApi;
308
- private readonly customApis: CustomAPIsApi;
309
286
  private readonly triggers: TriggersApi;
310
- private readonly secrets: SecretBackend;
311
287
 
312
288
  constructor(private readonly config: Configuration) {
313
289
  this.agents = new AgentsApi(config);
314
290
  this.conversations = new ConversationsApi(config);
315
291
  this.responses = new ResponsesApi(config);
316
- this.customApis = new CustomAPIsApi(config);
317
292
  this.triggers = new TriggersApi(config);
318
- this.secrets = secretBackend({ customApis: this.customApis });
319
293
  }
320
294
 
321
295
  // -- agents ---------------------------------------------------------------------------------------------
@@ -345,12 +319,11 @@ export class SettingsTransport implements Transport {
345
319
  }
346
320
 
347
321
  async createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent> {
348
- let settings = agent.toSettings();
349
- let missing: string[] = [];
350
- const webhooks = (settings["webhooks"] ?? []) as { secret_credential?: string }[];
351
- // The server checks webhooks against the credentials bound to the agent, and a new agent has none: create it
352
- // without them, bind the Custom APIs they name, then write the settings in full.
353
- const { bind, unbound } = await this.webhookCredentials(webhooks);
322
+ const settings = agent.toSettings();
323
+ const webhooks = (settings["webhooks"] ?? []) as unknown[];
324
+ // Webhooks are written in a second step, whose settings envelope carries the save's webhook warnings
325
+ // (webhooks_disabled, host_unresolvable). No save creates a webhook's signing secret: deploy() does that after the
326
+ // agent is live (createWebhookSecrets).
354
327
  let resource;
355
328
  try {
356
329
  resource = await this.agents.createAgent({
@@ -376,19 +349,13 @@ export class SettingsTransport implements Transport {
376
349
  throw err;
377
350
  }
378
351
  if (webhooks.length > 0) {
379
- for (const { path, name, customApiId } of bind) await this.bind(resource.id, path, name, customApiId);
380
- ({ settings, missing } = await this.withSecretCredentials(resource.id, settings));
381
352
  try {
382
353
  envelope = await this.agents.putAgentSettings({ agentId: resource.id, body: settings });
383
354
  } catch (err) {
384
- const invalid = await invalidSettings(err);
385
- if (invalid === null) throw err;
386
- throw new UserError([invalid.message, ...unbound].join("; "), invalid.issues);
355
+ throw (await invalidSettings(err)) ?? err;
387
356
  }
388
357
  }
389
358
  warnings = checkWarnings(envelope, settings);
390
- // Accepted unchecked (webhooks switched off): refused once they are on.
391
- for (const sentence of unbound) console.warn(`agent ${resource.id}: ${sentence}`);
392
359
  checkMetadata(envelope, agent);
393
360
  live = await this.goLive(resource.id, versionStateOf(resource), agent);
394
361
  } catch (err) {
@@ -404,87 +371,71 @@ export class SettingsTransport implements Transport {
404
371
  agentId: resource.id,
405
372
  name: agent.name,
406
373
  instructions: agent.instructions,
407
- settings: asDefined(resource.id, { ...(envelope.settings ?? {}) }),
374
+ settings: withoutLegacyCredentials({ ...(envelope.settings ?? {}) }),
408
375
  warnings,
409
- ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
410
376
  triggerTokens: live.triggerTokens ?? [],
411
377
  }, live.liveVersion, versionStateOf(resource));
412
378
  }
413
379
 
414
- /** `settings` with each webhook that names no `secret_credential` given the one `client.webhooks` keeps for the
415
- * agent and host (stored, with a random secret nobody holds, when there is none yet), and the URLs of those
416
- * webhooks still without a secret set by `client.webhooks`. */
417
- private async withSecretCredentials(agentId: string, settings: Record<string, any>):
418
- Promise<{ settings: Record<string, any>; missing: string[] }> {
419
- const hooks = hooksOf(settings);
420
- if (hooks.every((h) => "secret_credential" in h)) return { settings, missing: [] };
421
- const filled: unknown[] = [];
422
- const missing: string[] = [];
423
- for (const h of settings["webhooks"] as Hook[]) {
424
- if (typeof h !== "object" || h === null || "secret_credential" in h) {
425
- filled.push(h);
426
- continue;
427
- }
428
- const url = h["url"] as string;
429
- const { name, status } = await this.secrets.ensure(agentId, url);
430
- filled.push({ ...h, secret_credential: name });
431
- if (status === "missing") missing.push(url);
432
- }
433
- return { settings: { ...settings, webhooks: filled }, missing };
434
- }
435
-
436
- /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
437
- * one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
438
- * checks credentials). */
439
- private async webhookCredentials(webhooks: { secret_credential?: string }[]): Promise<{
440
- bind: { path: string; name: string; customApiId: string }[];
441
- unbound: string[];
442
- }> {
443
- const bind: { path: string; name: string; customApiId: string }[] = [];
444
- const unbound: string[] = [];
445
- const seen = new Set<string>();
446
- for (const [i, hook] of webhooks.entries()) {
447
- const name = hook.secret_credential;
448
- if (name === undefined || seen.has(name)) continue; // left out: deploy fills in the one client.webhooks keeps
449
- seen.add(name);
450
- const path = `webhooks.${i}.secret_credential`;
451
- const ids = await this.customApiIds(name);
452
- if (ids.length === 1) {
453
- bind.push({ path, name, customApiId: ids[0] });
454
- } else if (ids.length === 0) {
455
- unbound.push(`${path}: you have no Custom API named '${name}' to bind to the new agent; create it, then ` +
456
- "deploy again");
380
+ /**
381
+ * The webhook URLs of the agent.json last deployed, read before a deploy writes: the live (or paused) version's,
382
+ * `GET /v2/agents/{agentId}/versions/{version}` (its `agent.json` file). Without versions on the server, the
383
+ * agent's settings (`GET /v1/agents/{agentId}/settings`), which are what is deployed there. An empty set when
384
+ * nothing was ever deployed; null, with a warning, when it cannot be read.
385
+ */
386
+ async deployedWebhookUrls(agentId: string, liveVersion?: number, versionState?: string): Promise<Set<string> | null> {
387
+ let settings: unknown;
388
+ try {
389
+ if (versionState === undefined) {
390
+ settings = (await this.agents.getAgentSettings({ agentId })).settings ?? {};
391
+ } else if (liveVersion === undefined) {
392
+ return new Set();
457
393
  } else {
458
- unbound.push(`${path}: ${ids.length} of your Custom APIs are named '${name}', so none was bound to the new ` +
459
- "agent; rename or delete all but one, then deploy again");
394
+ const files = (await this.agents.getVersion({ agentId, version: liveVersion })).files ?? [];
395
+ const data = files.find((f) => String(f.path).replace(/^\/+/, "") === "agent.json")?.data;
396
+ settings = data ? JSON.parse(data) : {};
460
397
  }
398
+ } catch (err) {
399
+ const why = err instanceof ResponseError ? `HTTP ${err.response.status}` : err instanceof SyntaxError ? "not JSON" : String(err);
400
+ console.warn(`agent ${agentId}: could not read the deployed agent.json (${why}), so this deploy creates no ` +
401
+ "webhook secret; create any you need with client.webhooks.createSecret");
402
+ return null;
461
403
  }
462
- return { bind, unbound };
463
- }
464
-
465
- /** The ids of the caller's own Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
466
- private async customApiIds(name: string): Promise<string[]> {
467
- const ids: string[] = [];
468
- let offset = 0;
469
- for (;;) {
470
- const result = await this.customApis.listCustomApis({ q: name, limit: PAGE, offset });
471
- const items = result.data;
472
- for (const item of items) if (item.name === name) ids.push(item.id);
473
- offset += items.length;
474
- if (items.length === 0 || !result.hasMore) return ids;
404
+ const hooks = (settings as { webhooks?: unknown } | null)?.webhooks;
405
+ const out = new Set<string>();
406
+ if (Array.isArray(hooks)) {
407
+ for (const h of hooks) {
408
+ const url = (h as { url?: unknown } | null)?.url;
409
+ if (typeof url === "string") out.add(url);
410
+ }
475
411
  }
412
+ return out;
476
413
  }
477
414
 
478
- private async bind(agentId: string, path: string, name: string, customApiId: string): Promise<void> {
415
+ /**
416
+ * Create the signing secret of each webhook in `added` (the URLs this deploy added) whose `secretStatus` is
417
+ * `missing` (`POST .../webhooks/{webhookKey}/secret`); resolves to the new secrets by URL and the URLs of `agent`'s
418
+ * webhooks still without one. A webhook deployed before whose secret is missing is reported, never given one. An
419
+ * existing secret is never rotated or overwritten. Nothing here fails the deploy: a failure is logged (never with a
420
+ * secret) and the webhook reported missing.
421
+ */
422
+ async createWebhookSecrets(agentId: string, agent: Agent<OutputType | undefined>,
423
+ added: ReadonlySet<string> = new Set()): Promise<{ created: Record<string, string>; missing: string[] }> {
424
+ const urls = (agent.webhooks ?? []).map((h) => h.url);
425
+ let result;
479
426
  try {
480
- await this.customApis.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } });
427
+ result = await createMissingSecrets(this.agents, agentId, urls, added);
481
428
  } catch (err) {
482
- const status = err instanceof ResponseError ? err.response.status : 0;
483
- if (!(err instanceof ResponseError) || status < 400 || status >= 500) throw err;
484
- const message = (await chatError(err))?.["message"];
485
- throw new UserError(`${path}: could not bind the Custom API '${name}' to the new agent: ` +
486
- (typeof message === "string" && message ? message : `HTTP ${status}`));
429
+ const code = err instanceof ResponseError ? err.response.status : "error";
430
+ console.warn(`agent ${agentId}: could not read its webhooks to create their signing secrets (HTTP ${code}); ` +
431
+ "check client.webhooks.list(agentId) and createSecret for each");
432
+ return { created: {}, missing: [...urls] };
433
+ }
434
+ for (const url of result.missing) {
435
+ console.warn(`agent ${agentId}: webhook ${url} has no signing secret, so nothing is sent to it; create one ` +
436
+ "with client.webhooks.createSecret(agentId, url)");
487
437
  }
438
+ return result;
488
439
  }
489
440
 
490
441
  async updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent> {
@@ -509,13 +460,6 @@ export class SettingsTransport implements Transport {
509
460
  if (instructionsChanged) {
510
461
  await this.agents.putInstructions({ agentId, instructionsBody: { data: agent.instructions } });
511
462
  }
512
- let missing: string[];
513
- try {
514
- ({ settings, missing } = await this.withSecretCredentials(agentId, settings));
515
- } catch (err) {
516
- if (instructionsChanged) await this.restore(agentId, null, previousInstructions);
517
- throw err;
518
- }
519
463
  let envelope: Envelope;
520
464
  try {
521
465
  envelope = await this.agents.putAgentSettings({ agentId, body: settings });
@@ -542,9 +486,8 @@ export class SettingsTransport implements Transport {
542
486
  agentId,
543
487
  name: agent.name,
544
488
  instructions: agent.instructions,
545
- settings: asDefined(agentId, { ...(envelope.settings ?? {}) }),
489
+ settings: withoutLegacyCredentials({ ...(envelope.settings ?? {}) }),
546
490
  warnings,
547
- ...(missing.length > 0 ? { webhooksMissingSecret: missing } : {}),
548
491
  triggerTokens: live.triggerTokens ?? [],
549
492
  }, live.liveVersion, versionStateOf(current));
550
493
  }
@@ -554,6 +497,7 @@ export class SettingsTransport implements Transport {
554
497
  private async goLive(agentId: string, versionState: string | undefined, agent: Agent<OutputType | undefined>): Promise<Published> {
555
498
  if (versionState === undefined) {
556
499
  const resource = await this.agents.deployAgent({ agentId }); // idempotent; moves an adopted draft to deployed
500
+ logWebhookWarnings(agentId, resource);
557
501
  return { triggerTokens: triggerTokens(resource) };
558
502
  }
559
503
  return this.publish(agentId, VERSION_NOTE);
@@ -583,8 +527,9 @@ export class SettingsTransport implements Transport {
583
527
  }
584
528
  const live = resource.liveVersion ?? undefined;
585
529
  if (live !== undefined) deployed.add(`${agentId} v${live}`);
586
- return live === undefined ? { triggerTokens: triggerTokens(resource) }
587
- : { liveVersion: live, triggerTokens: triggerTokens(resource) };
530
+ logWebhookWarnings(agentId, resource);
531
+ const minted = { triggerTokens: triggerTokens(resource) };
532
+ return live === undefined ? minted : { liveVersion: live, ...minted };
588
533
  }
589
534
 
590
535
  /** Read the trigger rows of an unchanged live agent and warn, once per process, when they do not match
@@ -830,7 +775,9 @@ export class SettingsTransport implements Transport {
830
775
  if (instructions !== null) {
831
776
  await this.agents.putInstructions({ agentId, instructionsBody: { data: instructions } });
832
777
  }
833
- if (settings !== null) await this.agents.putAgentSettings({ agentId, body: settings });
778
+ if (settings !== null) {
779
+ await this.agents.putAgentSettings({ agentId, body: settings });
780
+ }
834
781
  } catch (err) {
835
782
  console.warn(`could not restore agent ${agentId} after rejected settings: ${err}`);
836
783
  }
@@ -846,7 +793,7 @@ export class SettingsTransport implements Transport {
846
793
  ): RemoteAgent {
847
794
  const remote: RemoteAgent = {
848
795
  agentId: resource.id, name: resource.name, instructions, warnings: [],
849
- settings: asDefined(resource.id, { ...(resource.settings ?? {}) }),
796
+ settings: withoutLegacyCredentials({ ...(resource.settings ?? {}) }),
850
797
  };
851
798
  // Left out, not set to undefined, when the server has no versions: the shape a 0.3 transport returned.
852
799
  if (resource.liveVersion !== undefined && resource.liveVersion !== null) remote.liveVersion = resource.liveVersion;
@@ -23,8 +23,8 @@ export interface RemoteAgent {
23
23
  /** `"live"`, `"paused"` or `"not_live"` (`AgentResource.versionState`); undefined when the server has no versions,
24
24
  * in which case deploy() never calls `publish`. */
25
25
  versionState?: string;
26
- /** URLs of the webhooks this write left without a secret set by `client.webhooks` (a placeholder secret nobody
27
- * holds stands in until `client.webhooks.setSecret`); left out when there are none. */
26
+ /** URLs of webhooks the write left without a signing secret; `deploy` adds them to
27
+ * `Deployment.webhooksMissingSecret`. The SDK's own transport leaves it out (see `createWebhookSecrets`). */
28
28
  webhooksMissingSecret?: string[];
29
29
  /** The bearer tokens the write's deploy minted (the server shows each once). */
30
30
  triggerTokens?: MintedTriggerToken[];
@@ -71,6 +71,14 @@ export interface Transport {
71
71
  * `agent.triggers` (a deploy whose trigger reconcile failed went live without them, or the owner changed them) it
72
72
  * warns, naming the fix. It never deploys: an unchanged definition writes nothing. */
73
73
  checkTriggers?(agentId: string, agent: Agent<OutputType | undefined>, liveVersion?: number): Promise<void>;
74
+ /** Optional: deploy() calls it before it writes, for the webhook URLs of the agent.json last deployed (an empty set
75
+ * when nothing was deployed; null when unknown, so nothing counts as added). */
76
+ deployedWebhookUrls?(agentId: string, liveVersion?: number, versionState?: string): Promise<Set<string> | null>;
77
+ /** Optional: deploy() calls it after a deploy of an agent with webhooks. It creates the signing secret of each
78
+ * webhook in `added` (the URLs the deploy added) that has none (never rotating or overwriting one) and resolves to
79
+ * the new secrets by URL and the URLs of the agent's webhooks still without one. */
80
+ createWebhookSecrets?(agentId: string, agent: Agent<OutputType | undefined>, added: ReadonlySet<string>):
81
+ Promise<{ created: Record<string, string>; missing: string[] }>;
74
82
  startTurn(agentId: string, conversationId: string | null, text: string, signal?: AbortSignal): Promise<TurnStream>;
75
83
  answerClarify(
76
84
  conversationId: string,