sarvam-agents-client 0.3.2 → 0.4.0

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 (136) hide show
  1. package/dist/apis/AgentConversationsApi.d.ts +2 -2
  2. package/dist/apis/AgentConversationsApi.js +2 -2
  3. package/dist/apis/AgentsApi.d.ts +195 -5
  4. package/dist/apis/AgentsApi.js +478 -5
  5. package/dist/apis/ArtifactsApi.d.ts +8 -4
  6. package/dist/apis/ArtifactsApi.js +8 -4
  7. package/dist/apis/ConversationsApi.d.ts +2 -0
  8. package/dist/apis/ConversationsApi.js +6 -0
  9. package/dist/compose/deploy.d.ts +33 -7
  10. package/dist/compose/deploy.js +97 -19
  11. package/dist/compose/errors.d.ts +1 -1
  12. package/dist/compose/errors.js +1 -1
  13. package/dist/compose/index.d.ts +1 -1
  14. package/dist/compose/index.js +2 -1
  15. package/dist/compose/run.d.ts +5 -1
  16. package/dist/compose/run.js +9 -9
  17. package/dist/compose/settingsTransport.d.ts +9 -0
  18. package/dist/compose/settingsTransport.js +82 -8
  19. package/dist/compose/transport.d.ts +11 -0
  20. package/dist/compose/transport.js +3 -0
  21. package/dist/esm/apis/AgentConversationsApi.d.ts +2 -2
  22. package/dist/esm/apis/AgentConversationsApi.js +2 -2
  23. package/dist/esm/apis/AgentsApi.d.ts +195 -5
  24. package/dist/esm/apis/AgentsApi.js +478 -5
  25. package/dist/esm/apis/ArtifactsApi.d.ts +8 -4
  26. package/dist/esm/apis/ArtifactsApi.js +8 -4
  27. package/dist/esm/apis/ConversationsApi.d.ts +2 -0
  28. package/dist/esm/apis/ConversationsApi.js +6 -0
  29. package/dist/esm/compose/deploy.d.ts +33 -7
  30. package/dist/esm/compose/deploy.js +97 -20
  31. package/dist/esm/compose/errors.d.ts +1 -1
  32. package/dist/esm/compose/errors.js +1 -1
  33. package/dist/esm/compose/index.d.ts +1 -1
  34. package/dist/esm/compose/index.js +1 -1
  35. package/dist/esm/compose/run.d.ts +5 -1
  36. package/dist/esm/compose/run.js +9 -9
  37. package/dist/esm/compose/settingsTransport.d.ts +9 -0
  38. package/dist/esm/compose/settingsTransport.js +82 -8
  39. package/dist/esm/compose/transport.d.ts +11 -0
  40. package/dist/esm/compose/transport.js +2 -1
  41. package/dist/esm/models/AgentAttachmentDiff.d.ts +50 -0
  42. package/dist/esm/models/AgentAttachmentDiff.js +55 -0
  43. package/dist/esm/models/AgentContentsResource.d.ts +71 -0
  44. package/dist/esm/models/AgentContentsResource.js +70 -0
  45. package/dist/esm/models/AgentDeploy.d.ts +33 -0
  46. package/dist/esm/models/AgentDeploy.js +41 -0
  47. package/dist/esm/models/AgentDraftResource.d.ts +51 -0
  48. package/dist/esm/models/AgentDraftResource.js +52 -0
  49. package/dist/esm/models/AgentFileContent.d.ts +38 -0
  50. package/dist/esm/models/AgentFileContent.js +47 -0
  51. package/dist/esm/models/AgentHistoryResource.d.ts +71 -0
  52. package/dist/esm/models/AgentHistoryResource.js +66 -0
  53. package/dist/esm/models/AgentResource.d.ts +21 -0
  54. package/dist/esm/models/AgentResource.js +12 -0
  55. package/dist/esm/models/AgentSkillFilePin.d.ts +44 -0
  56. package/dist/esm/models/AgentSkillFilePin.js +51 -0
  57. package/dist/esm/models/AgentSubagentEntry.d.ts +38 -0
  58. package/dist/esm/models/AgentSubagentEntry.js +47 -0
  59. package/dist/esm/models/AgentVersionCreate.d.ts +32 -0
  60. package/dist/esm/models/AgentVersionCreate.js +41 -0
  61. package/dist/esm/models/AgentVersionDiffResource.d.ts +87 -0
  62. package/dist/esm/models/AgentVersionDiffResource.js +78 -0
  63. package/dist/esm/models/AgentVersionPick.d.ts +32 -0
  64. package/dist/esm/models/AgentVersionPick.js +43 -0
  65. package/dist/esm/models/AgentVersionResource.d.ts +56 -0
  66. package/dist/esm/models/AgentVersionResource.js +57 -0
  67. package/dist/esm/models/AppResource.d.ts +12 -0
  68. package/dist/esm/models/AppResource.js +4 -0
  69. package/dist/esm/models/ResponseInput.d.ts +6 -0
  70. package/dist/esm/models/ResponseInput.js +2 -0
  71. package/dist/esm/models/SkillUpdateResource.d.ts +38 -0
  72. package/dist/esm/models/SkillUpdateResource.js +47 -0
  73. package/dist/esm/models/index.d.ts +13 -0
  74. package/dist/esm/models/index.js +13 -0
  75. package/dist/models/AgentAttachmentDiff.d.ts +50 -0
  76. package/dist/models/AgentAttachmentDiff.js +62 -0
  77. package/dist/models/AgentContentsResource.d.ts +71 -0
  78. package/dist/models/AgentContentsResource.js +77 -0
  79. package/dist/models/AgentDeploy.d.ts +33 -0
  80. package/dist/models/AgentDeploy.js +48 -0
  81. package/dist/models/AgentDraftResource.d.ts +51 -0
  82. package/dist/models/AgentDraftResource.js +59 -0
  83. package/dist/models/AgentFileContent.d.ts +38 -0
  84. package/dist/models/AgentFileContent.js +54 -0
  85. package/dist/models/AgentHistoryResource.d.ts +71 -0
  86. package/dist/models/AgentHistoryResource.js +74 -0
  87. package/dist/models/AgentResource.d.ts +21 -0
  88. package/dist/models/AgentResource.js +13 -1
  89. package/dist/models/AgentSkillFilePin.d.ts +44 -0
  90. package/dist/models/AgentSkillFilePin.js +58 -0
  91. package/dist/models/AgentSubagentEntry.d.ts +38 -0
  92. package/dist/models/AgentSubagentEntry.js +54 -0
  93. package/dist/models/AgentVersionCreate.d.ts +32 -0
  94. package/dist/models/AgentVersionCreate.js +48 -0
  95. package/dist/models/AgentVersionDiffResource.d.ts +87 -0
  96. package/dist/models/AgentVersionDiffResource.js +85 -0
  97. package/dist/models/AgentVersionPick.d.ts +32 -0
  98. package/dist/models/AgentVersionPick.js +50 -0
  99. package/dist/models/AgentVersionResource.d.ts +56 -0
  100. package/dist/models/AgentVersionResource.js +64 -0
  101. package/dist/models/AppResource.d.ts +12 -0
  102. package/dist/models/AppResource.js +4 -0
  103. package/dist/models/ResponseInput.d.ts +6 -0
  104. package/dist/models/ResponseInput.js +2 -0
  105. package/dist/models/SkillUpdateResource.d.ts +38 -0
  106. package/dist/models/SkillUpdateResource.js +54 -0
  107. package/dist/models/index.d.ts +13 -0
  108. package/dist/models/index.js +13 -0
  109. package/package.json +1 -1
  110. package/src/apis/AgentConversationsApi.ts +2 -2
  111. package/src/apis/AgentsApi.ts +737 -6
  112. package/src/apis/ArtifactsApi.ts +8 -4
  113. package/src/apis/ConversationsApi.ts +10 -0
  114. package/src/compose/deploy.ts +113 -20
  115. package/src/compose/errors.ts +1 -1
  116. package/src/compose/index.ts +1 -1
  117. package/src/compose/run.ts +6 -2
  118. package/src/compose/settingsTransport.ts +81 -9
  119. package/src/compose/transport.ts +12 -0
  120. package/src/models/AgentAttachmentDiff.ts +93 -0
  121. package/src/models/AgentContentsResource.ts +142 -0
  122. package/src/models/AgentDeploy.ts +66 -0
  123. package/src/models/AgentDraftResource.ts +99 -0
  124. package/src/models/AgentFileContent.ts +75 -0
  125. package/src/models/AgentHistoryResource.ts +121 -0
  126. package/src/models/AgentResource.ts +26 -0
  127. package/src/models/AgentSkillFilePin.ts +84 -0
  128. package/src/models/AgentSubagentEntry.ts +75 -0
  129. package/src/models/AgentVersionCreate.ts +65 -0
  130. package/src/models/AgentVersionDiffResource.ts +154 -0
  131. package/src/models/AgentVersionPick.ts +66 -0
  132. package/src/models/AgentVersionResource.ts +101 -0
  133. package/src/models/AppResource.ts +16 -0
  134. package/src/models/ResponseInput.ts +8 -0
  135. package/src/models/SkillUpdateResource.ts +75 -0
  136. package/src/models/index.ts +13 -0
@@ -265,6 +265,7 @@ export class ArtifactsApi extends runtime.BaseAPI {
265
265
  }
266
266
 
267
267
  /**
268
+ * A GET URL for one file: a presigned S3 URL while the file is plaintext. Clients that can follow file-gateway URLs use the v2 route.
268
269
  * Download Url Route
269
270
  */
270
271
  async downloadUrlRaw(requestParameters: DownloadUrlRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<DownloadUrlResponse>> {
@@ -313,6 +314,7 @@ export class ArtifactsApi extends runtime.BaseAPI {
313
314
  }
314
315
 
315
316
  /**
317
+ * A GET URL for one file: a presigned S3 URL while the file is plaintext. Clients that can follow file-gateway URLs use the v2 route.
316
318
  * Download Url Route
317
319
  */
318
320
  async downloadUrl(requestParameters: DownloadUrlRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<DownloadUrlResponse> {
@@ -321,7 +323,7 @@ export class ArtifactsApi extends runtime.BaseAPI {
321
323
  }
322
324
 
323
325
  /**
324
- * Render an HTML deck to PPTX or PDF and return a download link (sync).
326
+ * Render an HTML deck to PPTX or PDF and return a download link (sync). The link is a presigned S3 URL while the exported file is plaintext; clients that can follow file-gateway URLs use the v2 route.
325
327
  * Export Artifact Route
326
328
  */
327
329
  async exportArtifactRaw(requestParameters: ExportArtifactRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<ExportResponse>> {
@@ -372,7 +374,7 @@ export class ArtifactsApi extends runtime.BaseAPI {
372
374
  }
373
375
 
374
376
  /**
375
- * Render an HTML deck to PPTX or PDF and return a download link (sync).
377
+ * Render an HTML deck to PPTX or PDF and return a download link (sync). The link is a presigned S3 URL while the exported file is plaintext; clients that can follow file-gateway URLs use the v2 route.
376
378
  * Export Artifact Route
377
379
  */
378
380
  async exportArtifact(requestParameters: ExportArtifactRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<ExportResponse> {
@@ -424,6 +426,7 @@ export class ArtifactsApi extends runtime.BaseAPI {
424
426
  }
425
427
 
426
428
  /**
429
+ * Mint the PUT URL for an upload: a presigned S3 URL while the file is stored plaintext. Clients that can follow file-gateway URLs use ``POST /v2/artifacts/upload-url``.
427
430
  * Mint Upload Url Route
428
431
  */
429
432
  async mintUploadUrlRaw(requestParameters: MintUploadUrlRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<UploadUrlResponse>> {
@@ -460,6 +463,7 @@ export class ArtifactsApi extends runtime.BaseAPI {
460
463
  }
461
464
 
462
465
  /**
466
+ * Mint the PUT URL for an upload: a presigned S3 URL while the file is stored plaintext. Clients that can follow file-gateway URLs use ``POST /v2/artifacts/upload-url``.
463
467
  * Mint Upload Url Route
464
468
  */
465
469
  async mintUploadUrl(requestParameters: MintUploadUrlRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<UploadUrlResponse> {
@@ -468,7 +472,7 @@ export class ArtifactsApi extends runtime.BaseAPI {
468
472
  }
469
473
 
470
474
  /**
471
- * Presign the PUT for a user\'s edit of ``artifact_id``, saved as its next version. ``artifact_id`` is the version the client edited. 409 ``CHAT_CONFLICT`` (``details[0].latest_artifact_id`` / ``latest_version``) when a newer one has landed; 422 when the artifact has no version chain (uploads, exports).
475
+ * Presign the PUT for a user\'s edit of ``artifact_id``, saved as its next version. ``artifact_id`` is the version the client edited. 409 ``CHAT_CONFLICT`` (``details[0].latest_artifact_id`` / ``latest_version``) when a newer one has landed; 422 when the artifact has no version chain (uploads, exports). The URL is a presigned S3 URL while the edit is stored plaintext; clients that can follow file-gateway URLs use the v2 route.
472
476
  * Mint Version Upload Url Route
473
477
  */
474
478
  async mintVersionUploadUrlRaw(requestParameters: MintVersionUploadUrlRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<UploadUrlResponse>> {
@@ -519,7 +523,7 @@ export class ArtifactsApi extends runtime.BaseAPI {
519
523
  }
520
524
 
521
525
  /**
522
- * Presign the PUT for a user\'s edit of ``artifact_id``, saved as its next version. ``artifact_id`` is the version the client edited. 409 ``CHAT_CONFLICT`` (``details[0].latest_artifact_id`` / ``latest_version``) when a newer one has landed; 422 when the artifact has no version chain (uploads, exports).
526
+ * Presign the PUT for a user\'s edit of ``artifact_id``, saved as its next version. ``artifact_id`` is the version the client edited. 409 ``CHAT_CONFLICT`` (``details[0].latest_artifact_id`` / ``latest_version``) when a newer one has landed; 422 when the artifact has no version chain (uploads, exports). The URL is a presigned S3 URL while the edit is stored plaintext; clients that can follow file-gateway URLs use the v2 route.
523
527
  * Mint Version Upload Url Route
524
528
  */
525
529
  async mintVersionUploadUrl(requestParameters: MintVersionUploadUrlRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<UploadUrlResponse> {
@@ -64,6 +64,8 @@ export interface DeleteConversationRequest {
64
64
 
65
65
  export interface GetConversationRequest {
66
66
  conversationId: string;
67
+ xClientPlatform?: string | null;
68
+ xClientVersion?: string | null;
67
69
  }
68
70
 
69
71
  export interface GetResponseRequest {
@@ -211,6 +213,14 @@ export class ConversationsApi extends runtime.BaseAPI {
211
213
 
212
214
  const headerParameters: runtime.HTTPHeaders = {};
213
215
 
216
+ if (requestParameters['xClientPlatform'] != null) {
217
+ headerParameters['X-Client-Platform'] = String(requestParameters['xClientPlatform']);
218
+ }
219
+
220
+ if (requestParameters['xClientVersion'] != null) {
221
+ headerParameters['X-Client-Version'] = String(requestParameters['xClientVersion']);
222
+ }
223
+
214
224
  if (this.configuration && this.configuration.accessToken) {
215
225
  const token = this.configuration.accessToken;
216
226
  const tokenString = await token("bearerAuth", []);
@@ -1,20 +1,24 @@
1
- /** deploy()/undeploy(): upsert a hosted agent by name, with fingerprint-based drift detection, and the deploy cache. */
1
+ /** deploy()/remove(): upsert a hosted agent by name, with fingerprint-based drift detection, and the deploy cache. */
2
2
  import type { Configuration } from "../runtime.js";
3
3
  import type { Agent } from "./agent.js";
4
4
  import type { OutputType } from "./output.js";
5
- import { DriftError, DuplicateAgentsError, UserError } from "./errors.js";
5
+ import { DriftError, DuplicateAgentsError, NotDeployedError, UserError } from "./errors.js";
6
6
  import { canonicalJson, fingerprintBody, settingsFingerprint } from "./fingerprint.js";
7
7
  import { SettingsTransport } from "./settingsTransport.js";
8
+ import { VERSION_NOTE } from "./transport.js";
8
9
  import type { RemoteAgent, Transport } from "./transport.js";
9
10
 
10
11
  export interface Deployment {
11
12
  agentId: string;
12
13
  action: "created" | "updated" | "unchanged";
14
+ /** The live version, or while the agent is paused, the paused version (what `resumeAgent` brings back); undefined
15
+ * from a server without versions, or when no version was ever live. */
16
+ version?: number;
13
17
  }
14
18
 
15
19
  let defaultClient: Configuration | null = null;
16
20
 
17
- /** Set (or clear, with null) the client used when deploy/undeploy/run get no client. */
21
+ /** Set (or clear, with null) the client used when deploy/remove/run get no client. */
18
22
  export function setDefaultClient(config: Configuration | null): void {
19
23
  defaultClient = config;
20
24
  }
@@ -63,10 +67,33 @@ async function update(transport: Transport, remote: RemoteAgent, agent: Agent<Ou
63
67
  `agent "${agent.name}" (${remote.agentId}) was edited outside the SDK; overwriting fields: ${changed.join(", ")}`,
64
68
  );
65
69
  } else if (stored === agent.specHash()) {
66
- return { agentId: remote.agentId, action: "unchanged" };
70
+ return settle(transport, remote, agent);
67
71
  }
68
- await transport.updateAgent(remote.agentId, agent);
69
- return { agentId: remote.agentId, action: "updated" };
72
+ const updated = await transport.updateAgent(remote.agentId, agent);
73
+ return deployment(remote.agentId, "updated", liveVersion(updated));
74
+ }
75
+
76
+ function deployment(agentId: string, action: Deployment["action"], version: number | undefined): Deployment {
77
+ return version === undefined ? { agentId, action } : { agentId, action, version };
78
+ }
79
+
80
+ // Optional chaining: a custom transport written for 0.3 may resolve anything from updateAgent/createAgent.
81
+ function liveVersion(remote: RemoteAgent | undefined | null): number | undefined {
82
+ return remote?.liveVersion ?? undefined;
83
+ }
84
+
85
+ /**
86
+ * The stored definition already is this one, so nothing is written to a live or paused agent. What the owner does in
87
+ * the dashboard stays: unsaved draft edits, a version saved to try out, a rollback and a pause. The code's definition
88
+ * goes live again with the next deploy of a changed definition. Only an agent with no live version that was never
89
+ * paused (created, but its first deploy did not finish) is published here.
90
+ */
91
+ async function settle(transport: Transport, remote: RemoteAgent, agent: Agent<OutputType | undefined>): Promise<Deployment> {
92
+ const state = remote.versionState;
93
+ if (state === undefined || state === "live" || state === "paused" || !transport.publish) {
94
+ return deployment(remote.agentId, "unchanged", remote.liveVersion);
95
+ }
96
+ return deployment(remote.agentId, "updated", await transport.publish(remote.agentId, VERSION_NOTE));
70
97
  }
71
98
 
72
99
  async function deployWith(agent: Agent<OutputType | undefined>, transport: Transport, strict: boolean, adopt?: string): Promise<Deployment> {
@@ -82,14 +109,46 @@ async function deployWith(agent: Agent<OutputType | undefined>, transport: Trans
82
109
  if (others.length) {
83
110
  throw new UserError(`cannot adopt ${adopt}: agent "${agent.name}" is already deployed as ${others.join(", ")}`);
84
111
  }
85
- await transport.updateAgent(adopt, agent);
86
- return { agentId: adopt, action: "updated" };
112
+ return deployment(adopt, "updated", liveVersion(await transport.updateAgent(adopt, agent)));
87
113
  }
88
114
  if (found.length > 1) throw new DuplicateAgentsError(found.map((r) => r.agentId));
89
- if (found.length === 0) return { agentId: (await transport.createAgent(agent)).agentId, action: "created" };
115
+ if (found.length === 0) {
116
+ const created = await transport.createAgent(agent);
117
+ return deployment(created.agentId, "created", liveVersion(created));
118
+ }
90
119
  return update(transport, found[0], agent, strict);
91
120
  }
92
121
 
122
+ /**
123
+ * The id of the deployed agent named `agent.name`, for a run with `deploy: false`: reads only, writes nothing. The run
124
+ * gets the live version, whatever definition it holds; a definition that differs from the one last deployed from the
125
+ * SDK is warned about, since only `deploy(agent)` publishes it.
126
+ */
127
+ async function findDeployed(agent: Agent<OutputType | undefined>, transport: Transport): Promise<string> {
128
+ const found = await transport.findAgents(agent.name);
129
+ if (found.length > 1) throw new DuplicateAgentsError(found.map((r) => r.agentId));
130
+ if (found.length === 0) {
131
+ throw new NotDeployedError(
132
+ `agent "${agent.name}" is not deployed. Deploy it first with deploy(agent), or run it with deploy: true`,
133
+ );
134
+ }
135
+ const remote = found[0];
136
+ if (storedHash(remote) !== agent.specHash()) {
137
+ console.warn(`agent "${agent.name}" (${remote.agentId}) was deployed from a different definition; this run uses ` +
138
+ "the live version. Call deploy(agent) to publish your definition");
139
+ }
140
+ return remote.agentId;
141
+ }
142
+
143
+ /**
144
+ * Create or update the hosted agent named `agent.name` so end users get this definition.
145
+ *
146
+ * A new or changed definition is saved as the next version and made live (`created` / `updated`). An unchanged one
147
+ * writes nothing (`unchanged`): dashboard edits, a rollback and a pause stay as they are. A changed definition also
148
+ * saves any edits the owner left in the draft, so check the draft first. `strict: true` throws `DriftError` instead of
149
+ * overwriting fields edited outside the SDK. `adopt: agentId` takes over an agent made elsewhere. `version` is the live
150
+ * version (the paused one while paused).
151
+ */
93
152
  export async function deploy(
94
153
  agent: Agent<OutputType | undefined>,
95
154
  opts: { client?: Configuration; transport?: Transport; strict?: boolean; adopt?: string } = {},
@@ -99,7 +158,13 @@ export async function deploy(
99
158
  return serialized(agent.name, () => deployWith(agent, transport, opts.strict ?? false, opts.adopt));
100
159
  }
101
160
 
102
- export async function undeploy(
161
+ /**
162
+ * Delete the agent named `name` and all its versions; resolves true if one was deleted. It cannot be undone.
163
+ *
164
+ * To take an agent offline and bring it back later, pause it instead: `new AgentsApi(config).undeployAgent({ agentId })`,
165
+ * then `resumeAgent({ agentId })`.
166
+ */
167
+ export async function remove(
103
168
  name: string,
104
169
  opts: { client?: Configuration; transport?: Transport } = {},
105
170
  ): Promise<boolean> {
@@ -112,7 +177,24 @@ export async function undeploy(
112
177
  });
113
178
  }
114
179
 
115
- // Per-name tail: every deploy/undeploy of a name (cached or direct) queues behind the previous one, so they never
180
+ let undeployWarned = false;
181
+
182
+ /**
183
+ * @deprecated Renamed {@link remove}: it deletes the agent. The API's `undeploy` route (`AgentsApi.undeployAgent`)
184
+ * pauses an agent instead, so the old name read as a pause.
185
+ */
186
+ export async function undeploy(
187
+ name: string,
188
+ opts: { client?: Configuration; transport?: Transport } = {},
189
+ ): Promise<boolean> {
190
+ if (!undeployWarned) {
191
+ undeployWarned = true;
192
+ console.warn("undeploy() deletes the agent and is renamed remove(); to pause an agent instead, use AgentsApi.undeployAgent");
193
+ }
194
+ return remove(name, opts);
195
+ }
196
+
197
+ // Per-name tail: every deploy/remove of a name (cached or direct) queues behind the previous one, so they never
116
198
  // overlap. forget() does not touch it.
117
199
  const tails = new Map<string, Promise<unknown>>();
118
200
 
@@ -139,26 +221,37 @@ interface Entry {
139
221
 
140
222
  const cache = new Map<string, WeakMap<object, Entry>>();
141
223
 
142
- /** Drop cached deployments of agent `name` (any owner); called by deploy() and undeploy(). */
224
+ /** Drop cached deployments and lookups of agent `name` (any owner); called by deploy() and remove(). */
143
225
  export function forget(name: string): void {
144
- cache.delete(name);
226
+ cache.delete(cacheKey(name, true));
227
+ cache.delete(cacheKey(name, false));
228
+ }
229
+
230
+ // With deploy: false the agent is only looked up, cached apart so a lookup never stands in for a deploy.
231
+ function cacheKey(name: string, deploy: boolean): string {
232
+ return `${deploy ? "deploy" : "lookup"}:${name}`;
145
233
  }
146
234
 
147
235
  /**
148
- * The server id for `agent`, deploying it first unless this owner already deployed this exact definition.
149
- * Keyed by name, as the server is: a variant with the same name redeploys, chained after any in-flight deploy so
150
- * deploys of one name never overlap.
236
+ * The server id for `agent`, deploying it first unless this owner already deployed this exact definition; with
237
+ * `deploy` false, the deployed agent's id, looked up without writing. Keyed by name, as the server is: a variant with
238
+ * the same name redeploys, chained after any in-flight deploy so deploys of one name never overlap.
151
239
  */
152
- export function agentIdFor(agent: Agent<OutputType | undefined>, transport: Transport, owner: object): Promise<string> {
240
+ export function agentIdFor(
241
+ agent: Agent<OutputType | undefined>, transport: Transport, owner: object, deploy = true,
242
+ ): Promise<string> {
153
243
  const hash = agent.specHash();
154
- let owners = cache.get(agent.name);
244
+ const key = cacheKey(agent.name, deploy);
245
+ let owners = cache.get(key);
155
246
  if (!owners) {
156
247
  owners = new WeakMap();
157
- cache.set(agent.name, owners);
248
+ cache.set(key, owners);
158
249
  }
159
250
  const prev = owners.get(owner);
160
251
  if (prev && prev.hash === hash) return prev.id;
161
- const id = serialized(agent.name, () => deployWith(agent, transport, false)).then((d) => d.agentId);
252
+ const id = deploy
253
+ ? serialized(agent.name, () => deployWith(agent, transport, false)).then((d) => d.agentId)
254
+ : serialized(agent.name, () => findDeployed(agent, transport));
162
255
  const entry: Entry = { hash, id };
163
256
  owners.set(owner, entry);
164
257
  const slot = owners;
@@ -54,7 +54,7 @@ export class MaxTokensExceededError extends AgentsError {}
54
54
 
55
55
  export class MaxToolCallsExceededError extends AgentsError {}
56
56
 
57
- /** The agent has not been deployed. */
57
+ /** No agent is deployed under this name (thrown by a run with `deploy: false`). */
58
58
  export class NotDeployedError extends AgentsError {}
59
59
 
60
60
  /** A feature the SDK does not support yet. */
@@ -9,7 +9,7 @@ export type { Event, ClarifyQuestion, FunctionCallRequest, OutputCitation } from
9
9
  export { SettingsTransport } from "./settingsTransport.js";
10
10
  export type { PendingFunctionCalls, RemoteAgent, SettingsWarning, TurnStream, Transport } from "./transport.js";
11
11
  export type { FunctionResult } from "./functionTool.js";
12
- export { deploy, undeploy, setDefaultClient } from "./deploy.js";
12
+ export { deploy, remove, undeploy, setDefaultClient } from "./deploy.js";
13
13
  export type { Deployment } from "./deploy.js";
14
14
  export { run, RunResult, StreamedRunResult } from "./run.js";
15
15
  export type { RunOptions, RunStreamEvent, ClarifyHandler, StopReason } from "./run.js";
@@ -34,6 +34,10 @@ export interface RunOptions {
34
34
  /** Throw an error thrown by a function tool's `execute` instead of sending it to the model (for tests). The turn
35
35
  * then stays paused on the server; `RunState.fromSession` continues it. */
36
36
  raiseErrors?: boolean;
37
+ /** `true` (the default) deploys the agent first unless this process already deployed this definition. `false`
38
+ * never writes: it runs the live version of the deployed agent named `agent.name`, and throws `NotDeployedError`
39
+ * when there is none. Use it on servers, and deploy from CI or a release step. */
40
+ deploy?: boolean;
37
41
  /** Not supported: the server caps turns per agent; set `new Agent({ limits: { maxTurns } })`. */
38
42
  maxTurns?: never;
39
43
  }
@@ -584,7 +588,7 @@ async function execute(p: Prepared, controller: AbortController, emit: Emit): Pr
584
588
  if (p.input instanceof RunState) {
585
589
  interruptions = await loop.answerPending(p.input);
586
590
  } else {
587
- const agentId = await raceAbort(agentIdFor(p.agent, p.transport, p.owner), signal);
591
+ const agentId = await raceAbort(agentIdFor(p.agent, p.transport, p.owner, p.opts.deploy ?? true), signal);
588
592
  const stream = await loop.start(agentId, p.opts.conversationId ?? null, p.input);
589
593
  const interruption = await loop.drive(stream);
590
594
  interruptions = interruption ? [interruption] : [];
@@ -773,7 +777,7 @@ export class StreamedRunResult<T = string> implements AsyncIterable<RunStreamEve
773
777
 
774
778
  /**
775
779
  * Run `agent` on `input` (a message, or a RunState holding answers), deploying it first if this owner has not
776
- * deployed this exact definition. With `stream: true`, resolves at once with a StreamedRunResult.
780
+ * deployed this exact definition (unless `deploy: false`). With `stream: true`, resolves at once with a StreamedRunResult.
777
781
  */
778
782
  export function run<O extends OutputType | undefined = undefined>(
779
783
  agent: Agent<O>, input: string | RunState, opts: RunOptions & { stream: true },
@@ -14,6 +14,7 @@ import { NotSupportedByServerError, RunError, UserError } from "./errors.js";
14
14
  import { chunksFromUiMessage, fromUiChunk } from "./events.js";
15
15
  import type { Event } from "./events.js";
16
16
  import type { FunctionResult } from "./functionTool.js";
17
+ import { VERSION_NOTE } from "./transport.js";
17
18
  import type { PendingFunctionCalls, RemoteAgent, SettingsWarning, Transport, TurnStream } from "./transport.js";
18
19
 
19
20
  const PAGE = 100;
@@ -102,6 +103,24 @@ function firstDetail(error: Record<string, unknown> | null): Record<string, unkn
102
103
  return first !== null && typeof first === "object" && !Array.isArray(first) ? { ...first } : {};
103
104
  }
104
105
 
106
+ /** A deploy's 409 MISSING_DEPENDENCIES (the version uses a skill, app, knowledge base or sub-agent that was deleted
107
+ * since) as a UserError naming each one, else null. */
108
+ async function missingDependencies(err: unknown, agentId: string): Promise<UserError | null> {
109
+ if ((await reason(err, 409)) !== "MISSING_DEPENDENCIES") return null;
110
+ const missing = firstDetail(await chatError(err as ResponseError))["missing"];
111
+ const items = Array.isArray(missing)
112
+ ? (missing as unknown[]).filter((m): m is Record<string, unknown> => m !== null && typeof m === "object")
113
+ : [];
114
+ const named = items.map((m) => `${m["kind"]} '${m["name"]}' (${m["id"]})`).join(", ");
115
+ return new UserError(`agent ${agentId}: the new version can't go live because it uses something that was deleted` +
116
+ `${named ? ": " + named : ""}. Remove it from the agent, then deploy again`);
117
+ }
118
+
119
+ /** `AgentResource.versionState`; undefined from a server without versions (or an agent that is not managed). */
120
+ function versionStateOf(resource: { versionState?: string | null }): string | undefined {
121
+ return resource.versionState ?? undefined;
122
+ }
123
+
105
124
  function retryAfterMs(err: ResponseError): number {
106
125
  const seconds = Number(err.response.headers.get("retry-after") ?? 2);
107
126
  if (!Number.isFinite(seconds) || seconds < 0) return 2000;
@@ -275,6 +294,7 @@ export class SettingsTransport implements Transport {
275
294
  }
276
295
  let envelope: Envelope;
277
296
  let warnings: SettingsWarning[];
297
+ let live: number | undefined;
278
298
  // The create response never echoes settings, so support is read back from the settings route, which 404s
279
299
  // when the server has settings switched off (create then silently drops them).
280
300
  try {
@@ -298,7 +318,7 @@ export class SettingsTransport implements Transport {
298
318
  // Accepted unchecked (webhooks switched off): refused once they are on.
299
319
  for (const sentence of unbound) console.warn(`agent ${resource.id}: ${sentence}`);
300
320
  checkMetadata(envelope, agent);
301
- await this.agents.deployAgent({ agentId: resource.id });
321
+ live = await this.goLive(resource.id, versionStateOf(resource), agent);
302
322
  } catch (err) {
303
323
  // Don't leave an orphan agent behind; a failing cleanup must not mask the original error.
304
324
  try {
@@ -308,13 +328,13 @@ export class SettingsTransport implements Transport {
308
328
  }
309
329
  throw err;
310
330
  }
311
- return {
331
+ return withVersion({
312
332
  agentId: resource.id,
313
333
  name: agent.name,
314
334
  instructions: agent.instructions,
315
335
  settings: { ...(envelope.settings ?? {}) },
316
336
  warnings,
317
- };
337
+ }, live, versionStateOf(resource));
318
338
  }
319
339
 
320
340
  /** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
@@ -374,7 +394,8 @@ export class SettingsTransport implements Transport {
374
394
  async updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent> {
375
395
  const settings = agent.toSettings();
376
396
  // findAgents searches by display name, so an adopted (or dashboard-renamed) agent must carry sdk_name.
377
- if ((await this.agents.getAgent({ agentId })).name !== agent.name) {
397
+ const current = await this.agents.getAgent({ agentId });
398
+ if (current.name !== agent.name) {
378
399
  await this.agents.updateAgent({ agentId, agentUpdate: { name: agent.name } });
379
400
  }
380
401
  // Rejections are only visible after the server stored the settings, so keep what was there to put it back.
@@ -413,14 +434,48 @@ export class SettingsTransport implements Transport {
413
434
  throw err;
414
435
  }
415
436
  checkMetadata(envelope, agent);
416
- await this.agents.deployAgent({ agentId }); // idempotent; moves an adopted draft to deployed
417
- return {
437
+ const live = await this.goLive(agentId, versionStateOf(current), agent);
438
+ return withVersion({
418
439
  agentId,
419
440
  name: agent.name,
420
441
  instructions: agent.instructions,
421
442
  settings: { ...(envelope.settings ?? {}) },
422
443
  warnings,
423
- };
444
+ }, live, versionStateOf(current));
445
+ }
446
+
447
+ /** Make what was just written what end users get. A server without versions (no `versionState`) gets the bodiless
448
+ * deploy 0.3 sent; otherwise the draft is saved as a version and that version deployed. */
449
+ private async goLive(agentId: string, versionState: string | undefined, agent: Agent<OutputType | undefined>): Promise<number | undefined> {
450
+ if (versionState === undefined) {
451
+ await this.agents.deployAgent({ agentId }); // idempotent; moves an adopted draft to deployed
452
+ return undefined;
453
+ }
454
+ return this.publish(agentId, VERSION_NOTE);
455
+ }
456
+
457
+ /**
458
+ * Save the draft as the next version and make it live. 409 NO_CHANGES means the newest saved version already is the
459
+ * draft, so that version is deployed, by its number (never "the newest", which a save landing in between could
460
+ * change).
461
+ */
462
+ async publish(agentId: string, note: string): Promise<number | undefined> {
463
+ let version: number;
464
+ try {
465
+ version = (await this.agents.saveVersion({ agentId, agentVersionCreate: { note } })).version;
466
+ } catch (err) {
467
+ if ((await reason(err, 409)) !== "NO_CHANGES") throw err;
468
+ const newest = (await this.agents.getDraft({ agentId })).basedOnVersion;
469
+ if (newest === undefined || newest === null) throw err;
470
+ version = newest;
471
+ }
472
+ let resource;
473
+ try {
474
+ resource = await this.agents.deployAgent({ agentId, agentDeploy: { version } });
475
+ } catch (err) {
476
+ throw (await missingDependencies(err, agentId)) ?? err;
477
+ }
478
+ return resource.liveVersion ?? undefined;
424
479
  }
425
480
 
426
481
  async deleteAgent(agentId: string): Promise<void> {
@@ -621,11 +676,28 @@ export class SettingsTransport implements Transport {
621
676
  return (await this.agents.getInstructions({ agentId })).data;
622
677
  }
623
678
 
624
- private remote(resource: { id: string; name: string; settings?: { [key: string]: any } | null }, instructions: string): RemoteAgent {
625
- return { agentId: resource.id, name: resource.name, instructions, settings: { ...(resource.settings ?? {}) }, warnings: [] };
679
+ private remote(
680
+ resource: { id: string; name: string; settings?: { [key: string]: any } | null; versionState?: string | null; liveVersion?: number | null },
681
+ instructions: string,
682
+ ): RemoteAgent {
683
+ const remote: RemoteAgent = {
684
+ agentId: resource.id, name: resource.name, instructions, settings: { ...(resource.settings ?? {}) }, warnings: [],
685
+ };
686
+ // Left out, not set to undefined, when the server has no versions: the shape a 0.3 transport returned.
687
+ if (resource.liveVersion !== undefined && resource.liveVersion !== null) remote.liveVersion = resource.liveVersion;
688
+ const state = versionStateOf(resource);
689
+ if (state !== undefined) remote.versionState = state;
690
+ return remote;
626
691
  }
627
692
  }
628
693
 
694
+ /** `remote` with the version fields set when known (left out otherwise, as a server without versions returns it). After a
695
+ * publish the agent is live whatever state it was read in. */
696
+ function withVersion(remote: RemoteAgent, live: number | undefined, state: string | undefined): RemoteAgent {
697
+ if (live !== undefined) return { ...remote, liveVersion: live, versionState: "live" };
698
+ return state === undefined ? remote : { ...remote, versionState: state };
699
+ }
700
+
629
701
  /** The server's 422 CHAT_VALIDATION / invalid_agent_settings rejection as a UserError, else null. */
630
702
  async function invalidSettings(err: unknown): Promise<UserError | null> {
631
703
  if (!(err instanceof ResponseError) || err.response.status !== 422) return null;
@@ -16,8 +16,17 @@ export interface RemoteAgent {
16
16
  instructions: string;
17
17
  settings: Record<string, unknown>;
18
18
  warnings: SettingsWarning[];
19
+ /** The version end users get (`AgentResource.liveVersion`); undefined when nothing is live or the server has no
20
+ * versions. */
21
+ liveVersion?: number;
22
+ /** `"live"`, `"paused"` or `"not_live"` (`AgentResource.versionState`); undefined when the server has no versions,
23
+ * in which case deploy() never calls `publish`. */
24
+ versionState?: string;
19
25
  }
20
26
 
27
+ /** The note on every version deploy() saves, so the dashboard's version list shows which came from code. */
28
+ export const VERSION_NOTE = "Deployed from the SDK";
29
+
21
30
  /** Async iterable of Events; the ids are filled in as the stream progresses. */
22
31
  export interface TurnStream extends AsyncIterable<Event> {
23
32
  readonly conversationId: string | null;
@@ -42,6 +51,9 @@ export interface Transport {
42
51
  createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
43
52
  updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
44
53
  deleteAgent(agentId: string): Promise<void>;
54
+ /** Save the draft as the next version and make that version live; resolves to the live version. Called only for
55
+ * an agent whose `versionState` is set. Optional so a transport written before versions still type-checks. */
56
+ publish?(agentId: string, note: string): Promise<number | undefined>;
45
57
  startTurn(agentId: string, conversationId: string | null, text: string, signal?: AbortSignal): Promise<TurnStream>;
46
58
  answerClarify(
47
59
  conversationId: string,
@@ -0,0 +1,93 @@
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 AgentAttachmentDiff
20
+ */
21
+ export interface AgentAttachmentDiff {
22
+ /**
23
+ *
24
+ * @type {Array<string>}
25
+ * @memberof AgentAttachmentDiff
26
+ */
27
+ added: Array<string>;
28
+ /**
29
+ *
30
+ * @type {Array<string>}
31
+ * @memberof AgentAttachmentDiff
32
+ */
33
+ removed: Array<string>;
34
+ /**
35
+ *
36
+ * @type {Array<string>}
37
+ * @memberof AgentAttachmentDiff
38
+ */
39
+ switchedOn: Array<string>;
40
+ /**
41
+ *
42
+ * @type {Array<string>}
43
+ * @memberof AgentAttachmentDiff
44
+ */
45
+ switchedOff: Array<string>;
46
+ }
47
+
48
+ /**
49
+ * Check if a given object implements the AgentAttachmentDiff interface.
50
+ */
51
+ export function instanceOfAgentAttachmentDiff(value: object): value is AgentAttachmentDiff {
52
+ if (!('added' in value) || value['added'] === undefined) return false;
53
+ if (!('removed' in value) || value['removed'] === undefined) return false;
54
+ if (!('switchedOn' in value) || value['switchedOn'] === undefined) return false;
55
+ if (!('switchedOff' in value) || value['switchedOff'] === undefined) return false;
56
+ return true;
57
+ }
58
+
59
+ export function AgentAttachmentDiffFromJSON(json: any): AgentAttachmentDiff {
60
+ return AgentAttachmentDiffFromJSONTyped(json, false);
61
+ }
62
+
63
+ export function AgentAttachmentDiffFromJSONTyped(json: any, ignoreDiscriminator: boolean): AgentAttachmentDiff {
64
+ if (json == null) {
65
+ return json;
66
+ }
67
+ return {
68
+
69
+ 'added': json['added'],
70
+ 'removed': json['removed'],
71
+ 'switchedOn': json['switchedOn'],
72
+ 'switchedOff': json['switchedOff'],
73
+ };
74
+ }
75
+
76
+ export function AgentAttachmentDiffToJSON(json: any): AgentAttachmentDiff {
77
+ return AgentAttachmentDiffToJSONTyped(json, false);
78
+ }
79
+
80
+ export function AgentAttachmentDiffToJSONTyped(value?: AgentAttachmentDiff | null, ignoreDiscriminator: boolean = false): any {
81
+ if (value == null) {
82
+ return value;
83
+ }
84
+
85
+ return {
86
+
87
+ 'added': value['added'],
88
+ 'removed': value['removed'],
89
+ 'switchedOn': value['switchedOn'],
90
+ 'switchedOff': value['switchedOff'],
91
+ };
92
+ }
93
+