sarvam-agents-client 0.2.3 → 0.3.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 (101) hide show
  1. package/dist/apis/AgentsApi.d.ts +4 -4
  2. package/dist/apis/AgentsApi.js +4 -4
  3. package/dist/apis/AppsApi.d.ts +1 -0
  4. package/dist/apis/AppsApi.js +3 -0
  5. package/dist/apis/QueueApi.d.ts +1 -0
  6. package/dist/apis/QueueApi.js +3 -0
  7. package/dist/apis/ResponsesApi.d.ts +2 -0
  8. package/dist/apis/ResponsesApi.js +6 -0
  9. package/dist/compose/agent.d.ts +10 -3
  10. package/dist/compose/agent.js +8 -0
  11. package/dist/compose/deploy.d.ts +3 -2
  12. package/dist/compose/errors.d.ts +17 -0
  13. package/dist/compose/errors.js +17 -0
  14. package/dist/compose/events.d.ts +34 -0
  15. package/dist/compose/events.js +25 -2
  16. package/dist/compose/index.d.ts +2 -1
  17. package/dist/compose/output.d.ts +29 -0
  18. package/dist/compose/output.js +451 -0
  19. package/dist/compose/run.d.ts +39 -14
  20. package/dist/compose/run.js +53 -3
  21. package/dist/compose/runState.d.ts +2 -1
  22. package/dist/compose/settingsTransport.d.ts +3 -2
  23. package/dist/compose/transport.d.ts +3 -2
  24. package/dist/esm/apis/AgentsApi.d.ts +4 -4
  25. package/dist/esm/apis/AgentsApi.js +4 -4
  26. package/dist/esm/apis/AppsApi.d.ts +1 -0
  27. package/dist/esm/apis/AppsApi.js +3 -0
  28. package/dist/esm/apis/QueueApi.d.ts +1 -0
  29. package/dist/esm/apis/QueueApi.js +3 -0
  30. package/dist/esm/apis/ResponsesApi.d.ts +2 -0
  31. package/dist/esm/apis/ResponsesApi.js +6 -0
  32. package/dist/esm/compose/agent.d.ts +10 -3
  33. package/dist/esm/compose/agent.js +8 -0
  34. package/dist/esm/compose/deploy.d.ts +3 -2
  35. package/dist/esm/compose/errors.d.ts +17 -0
  36. package/dist/esm/compose/errors.js +17 -0
  37. package/dist/esm/compose/events.d.ts +34 -0
  38. package/dist/esm/compose/events.js +25 -2
  39. package/dist/esm/compose/index.d.ts +2 -1
  40. package/dist/esm/compose/output.d.ts +29 -0
  41. package/dist/esm/compose/output.js +445 -0
  42. package/dist/esm/compose/run.d.ts +39 -14
  43. package/dist/esm/compose/run.js +54 -4
  44. package/dist/esm/compose/runState.d.ts +2 -1
  45. package/dist/esm/compose/settingsTransport.d.ts +3 -2
  46. package/dist/esm/compose/transport.d.ts +3 -2
  47. package/dist/esm/models/AppResource.d.ts +29 -0
  48. package/dist/esm/models/AppResource.js +16 -0
  49. package/dist/esm/models/AppToolsResponse.d.ts +3 -4
  50. package/dist/esm/models/AppToolsResponse.js +3 -2
  51. package/dist/esm/models/AppView.d.ts +48 -0
  52. package/dist/esm/models/AppView.js +23 -0
  53. package/dist/esm/models/McpSecurityAppealView.d.ts +50 -0
  54. package/dist/esm/models/McpSecurityAppealView.js +47 -0
  55. package/dist/esm/models/McpSecurityView.d.ts +105 -0
  56. package/dist/esm/models/McpSecurityView.js +66 -0
  57. package/dist/esm/models/MessagesResponse.d.ts +6 -0
  58. package/dist/esm/models/MessagesResponse.js +2 -0
  59. package/dist/esm/models/ResponseDetail.d.ts +32 -0
  60. package/dist/esm/models/ResponseDetail.js +10 -0
  61. package/dist/esm/models/index.d.ts +2 -0
  62. package/dist/esm/models/index.js +2 -0
  63. package/dist/models/AppResource.d.ts +29 -0
  64. package/dist/models/AppResource.js +17 -1
  65. package/dist/models/AppToolsResponse.d.ts +3 -4
  66. package/dist/models/AppToolsResponse.js +3 -2
  67. package/dist/models/AppView.d.ts +48 -0
  68. package/dist/models/AppView.js +24 -1
  69. package/dist/models/McpSecurityAppealView.d.ts +50 -0
  70. package/dist/models/McpSecurityAppealView.js +54 -0
  71. package/dist/models/McpSecurityView.d.ts +105 -0
  72. package/dist/models/McpSecurityView.js +73 -0
  73. package/dist/models/MessagesResponse.d.ts +6 -0
  74. package/dist/models/MessagesResponse.js +2 -0
  75. package/dist/models/ResponseDetail.d.ts +32 -0
  76. package/dist/models/ResponseDetail.js +10 -0
  77. package/dist/models/index.d.ts +2 -0
  78. package/dist/models/index.js +2 -0
  79. package/package.json +4 -3
  80. package/src/apis/AgentsApi.ts +4 -4
  81. package/src/apis/AppsApi.ts +5 -0
  82. package/src/apis/QueueApi.ts +5 -0
  83. package/src/apis/ResponsesApi.ts +10 -0
  84. package/src/compose/agent.ts +21 -6
  85. package/src/compose/deploy.ts +6 -5
  86. package/src/compose/errors.ts +28 -1
  87. package/src/compose/events.ts +49 -1
  88. package/src/compose/index.ts +2 -1
  89. package/src/compose/output.ts +415 -0
  90. package/src/compose/run.ts +93 -21
  91. package/src/compose/runState.ts +2 -1
  92. package/src/compose/settingsTransport.ts +4 -3
  93. package/src/compose/transport.ts +3 -2
  94. package/src/models/AppResource.ts +42 -0
  95. package/src/models/AppToolsResponse.ts +11 -4
  96. package/src/models/AppView.ts +73 -0
  97. package/src/models/McpSecurityAppealView.ts +89 -0
  98. package/src/models/McpSecurityView.ts +169 -0
  99. package/src/models/MessagesResponse.ts +8 -0
  100. package/src/models/ResponseDetail.ts +40 -0
  101. package/src/models/index.ts +2 -0
@@ -106,6 +106,8 @@ export * from './InputMessage.js';
106
106
  export * from './InstructionsBody.js';
107
107
  export * from './InstructionsResponse.js';
108
108
  export * from './ListModels403Response.js';
109
+ export * from './McpSecurityAppealView.js';
110
+ export * from './McpSecurityView.js';
109
111
  export * from './MessagePart.js';
110
112
  export * from './MessagesResponse.js';
111
113
  export * from './MintUploadUrl403Response.js';
@@ -124,6 +124,8 @@ __exportStar(require("./InputMessage.js"), exports);
124
124
  __exportStar(require("./InstructionsBody.js"), exports);
125
125
  __exportStar(require("./InstructionsResponse.js"), exports);
126
126
  __exportStar(require("./ListModels403Response.js"), exports);
127
+ __exportStar(require("./McpSecurityAppealView.js"), exports);
128
+ __exportStar(require("./McpSecurityView.js"), exports);
127
129
  __exportStar(require("./MessagePart.js"), exports);
128
130
  __exportStar(require("./MessagesResponse.js"), exports);
129
131
  __exportStar(require("./MintUploadUrl403Response.js"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sarvam-agents-client",
3
- "version": "0.2.3",
3
+ "version": "0.3.0",
4
4
  "description": "Client for the Sarvam Agents API: chat with an agent, exchange files with it, and set it up from your own code.",
5
5
  "author": "Sarvam AI <support@sarvam.ai>",
6
6
  "license": "MIT",
@@ -43,12 +43,13 @@
43
43
  },
44
44
  "scripts": {
45
45
  "build": "tsc && tsc -p tsconfig.esm.json && node -e \"require('fs').writeFileSync('dist/esm/package.json', '{\\\"type\\\": \\\"module\\\"}')\"",
46
- "test": "node --test test/*.test.mjs test/compose/*.test.mjs test/live/*.test.mjs",
46
+ "test": "tsc -p test/types/tsconfig.json && node --test test/*.test.mjs test/compose/*.test.mjs test/live/*.test.mjs",
47
47
  "prepublishOnly": "npm run build && npm test"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@types/node": "^18.19.130",
51
- "typescript": "5.6.3"
51
+ "typescript": "5.6.3",
52
+ "zod": "^4.6.7"
52
53
  },
53
54
  "typesVersions": {
54
55
  "*": {
@@ -306,7 +306,7 @@ export class AgentsApi extends runtime.BaseAPI {
306
306
  }
307
307
 
308
308
  /**
309
- * Owner-only soft delete. Also drops the agent\'s ``managed_agents`` row (if any) so a deleted agent never lingers as a managed agent.
309
+ * Owner-only soft delete. The managed state lives on the agent row, so a deleted agent stops being a managed agent with it.
310
310
  * Delete Agent
311
311
  */
312
312
  async deleteAgentRaw(requestParameters: DeleteAgentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<void>> {
@@ -340,7 +340,7 @@ export class AgentsApi extends runtime.BaseAPI {
340
340
  }
341
341
 
342
342
  /**
343
- * Owner-only soft delete. Also drops the agent\'s ``managed_agents`` row (if any) so a deleted agent never lingers as a managed agent.
343
+ * Owner-only soft delete. The managed state lives on the agent row, so a deleted agent stops being a managed agent with it.
344
344
  * Delete Agent
345
345
  */
346
346
  async deleteAgent(requestParameters: DeleteAgentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<void> {
@@ -803,7 +803,7 @@ export class AgentsApi extends runtime.BaseAPI {
803
803
  }
804
804
 
805
805
  /**
806
- * Flat, scope-filterable agent catalog (contract replaces v1\'s grouped ``GET /v1/agents``; the FE re-groups client-side from each row\'s ``scope``). One gateway call returns the caller\'s full visible set (the triple powers the gateway\'s ``visibility_scope`` clause). We then drop the operator-seeded editor agents, re-apply the visibility predicate (defence in depth — the gateway is identity-agnostic), and apply the ``?scope=``/``q`` filters before counting, so ``total`` is authoritative for the returned set. ``origin=managed_agents`` keeps only managed agents the caller owns (:func:`is_owner`). A teammate\'s published managed agent is visible to the caller but its sessions are owner-only, so listing it would only lead to a 403 on the session log. It always takes the fetch-all path below: the SQL catalog pages at the gateway, which knows nothing about ``managed_agents``, so filtering its page here would return short pages and a wrong ``total``. Catalog-only filters are therefore a 400 with ``origin`` rather than silently ignored.
806
+ * Flat, scope-filterable agent catalog (contract replaces v1\'s grouped ``GET /v1/agents``; the FE re-groups client-side from each row\'s ``scope``). One gateway call returns the caller\'s full visible set (the triple powers the gateway\'s ``visibility_scope`` clause). We then drop the operator-seeded editor agents, re-apply the visibility predicate (defence in depth — the gateway is identity-agnostic), and apply the ``?scope=``/``q`` filters before counting, so ``total`` is authoritative for the returned set. ``origin=managed_agents`` keeps only managed agents the caller owns (:func:`is_owner`). A teammate\'s published managed agent is visible to the caller but its sessions are owner-only, so listing it would only lead to a 403 on the session log. It always takes the fetch-all path below: the SQL catalog pages at the gateway, which has no managed filter, so filtering its page here would return short pages and a wrong ``total``. Catalog-only filters are therefore a 400 with ``origin`` rather than silently ignored.
807
807
  * List Agents
808
808
  */
809
809
  async listAgentsRaw(requestParameters: ListAgentsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<EntityListAgentResource>> {
@@ -878,7 +878,7 @@ export class AgentsApi extends runtime.BaseAPI {
878
878
  }
879
879
 
880
880
  /**
881
- * Flat, scope-filterable agent catalog (contract replaces v1\'s grouped ``GET /v1/agents``; the FE re-groups client-side from each row\'s ``scope``). One gateway call returns the caller\'s full visible set (the triple powers the gateway\'s ``visibility_scope`` clause). We then drop the operator-seeded editor agents, re-apply the visibility predicate (defence in depth — the gateway is identity-agnostic), and apply the ``?scope=``/``q`` filters before counting, so ``total`` is authoritative for the returned set. ``origin=managed_agents`` keeps only managed agents the caller owns (:func:`is_owner`). A teammate\'s published managed agent is visible to the caller but its sessions are owner-only, so listing it would only lead to a 403 on the session log. It always takes the fetch-all path below: the SQL catalog pages at the gateway, which knows nothing about ``managed_agents``, so filtering its page here would return short pages and a wrong ``total``. Catalog-only filters are therefore a 400 with ``origin`` rather than silently ignored.
881
+ * Flat, scope-filterable agent catalog (contract replaces v1\'s grouped ``GET /v1/agents``; the FE re-groups client-side from each row\'s ``scope``). One gateway call returns the caller\'s full visible set (the triple powers the gateway\'s ``visibility_scope`` clause). We then drop the operator-seeded editor agents, re-apply the visibility predicate (defence in depth — the gateway is identity-agnostic), and apply the ``?scope=``/``q`` filters before counting, so ``total`` is authoritative for the returned set. ``origin=managed_agents`` keeps only managed agents the caller owns (:func:`is_owner`). A teammate\'s published managed agent is visible to the caller but its sessions are owner-only, so listing it would only lead to a 403 on the session log. It always takes the fetch-all path below: the SQL catalog pages at the gateway, which has no managed filter, so filtering its page here would return short pages and a wrong ``total``. Catalog-only filters are therefore a 400 with ``origin`` rather than silently ignored.
882
882
  * List Agents
883
883
  */
884
884
  async listAgents(requestParameters: ListAgentsRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<EntityListAgentResource> {
@@ -110,6 +110,7 @@ export interface ListAppsRequest {
110
110
  offset?: number;
111
111
  category?: Array<AppCategory> | null;
112
112
  includeFilterOptions?: boolean;
113
+ custom?: boolean;
113
114
  }
114
115
 
115
116
  export interface UnbindAppRequest {
@@ -571,6 +572,10 @@ export class AppsApi extends runtime.BaseAPI {
571
572
  queryParameters['includeFilterOptions'] = requestParameters['includeFilterOptions'];
572
573
  }
573
574
 
575
+ if (requestParameters['custom'] != null) {
576
+ queryParameters['custom'] = requestParameters['custom'];
577
+ }
578
+
574
579
  const headerParameters: runtime.HTTPHeaders = {};
575
580
 
576
581
  if (this.configuration && this.configuration.accessToken) {
@@ -52,6 +52,7 @@ export interface QueueMessageRequest {
52
52
  xClientFeatures?: string | null;
53
53
  xClientPlatform?: string | null;
54
54
  xClientVersion?: string | null;
55
+ xLoginId?: string | null;
55
56
  }
56
57
 
57
58
  export interface RemoveQueuedRequest {
@@ -163,6 +164,10 @@ export class QueueApi extends runtime.BaseAPI {
163
164
  headerParameters['X-Client-Version'] = String(requestParameters['xClientVersion']);
164
165
  }
165
166
 
167
+ if (requestParameters['xLoginId'] != null) {
168
+ headerParameters['X-Login-Id'] = String(requestParameters['xLoginId']);
169
+ }
170
+
166
171
  if (this.configuration && this.configuration.accessToken) {
167
172
  const token = this.configuration.accessToken;
168
173
  const tokenString = await token("bearerAuth", []);
@@ -39,6 +39,7 @@ export interface CreateResponseRequest {
39
39
  xClientFeatures?: string | null;
40
40
  xClientPlatform?: string | null;
41
41
  xClientVersion?: string | null;
42
+ xLoginId?: string | null;
42
43
  }
43
44
 
44
45
  export interface ReconnectStreamRequest {
@@ -55,6 +56,7 @@ export interface StopResponseRequest {
55
56
  conversationId: string;
56
57
  xClientPlatform?: string | null;
57
58
  xClientVersion?: string | null;
59
+ xLoginId?: string | null;
58
60
  }
59
61
 
60
62
  /**
@@ -91,6 +93,10 @@ export class ResponsesApi extends runtime.BaseAPI {
91
93
  headerParameters['X-Client-Version'] = String(requestParameters['xClientVersion']);
92
94
  }
93
95
 
96
+ if (requestParameters['xLoginId'] != null) {
97
+ headerParameters['X-Login-Id'] = String(requestParameters['xLoginId']);
98
+ }
99
+
94
100
  if (this.configuration && this.configuration.accessToken) {
95
101
  const token = this.configuration.accessToken;
96
102
  const tokenString = await token("bearerAuth", []);
@@ -223,6 +229,10 @@ export class ResponsesApi extends runtime.BaseAPI {
223
229
  headerParameters['X-Client-Version'] = String(requestParameters['xClientVersion']);
224
230
  }
225
231
 
232
+ if (requestParameters['xLoginId'] != null) {
233
+ headerParameters['X-Login-Id'] = String(requestParameters['xLoginId']);
234
+ }
235
+
226
236
  if (this.configuration && this.configuration.accessToken) {
227
237
  const token = this.configuration.accessToken;
228
238
  const tokenString = await token("bearerAuth", []);
@@ -2,6 +2,8 @@ import { NotSupportedError, UserError } from "./errors.js";
2
2
  import { settingsFingerprint } from "./fingerprint.js";
3
3
  import { BUILTIN_NAMES, checkWebSearchOptions } from "./builtins.js";
4
4
  import { BuiltinTool } from "./tools.js";
5
+ import { checkOutputType, outputSchema } from "./output.js";
6
+ import type { OutputType } from "./output.js";
5
7
 
6
8
  const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;
7
9
  const REASONING = ["off", "none", "low", "medium", "high", "xhigh", "max"];
@@ -21,7 +23,7 @@ export interface Limits {
21
23
  maxTokensPerTurn?: number;
22
24
  }
23
25
 
24
- export interface AgentOptions {
26
+ export interface AgentOptions<TOutput extends OutputType | undefined = undefined> {
25
27
  name: string;
26
28
  instructions?: string;
27
29
  model?: string;
@@ -33,6 +35,8 @@ export interface AgentOptions {
33
35
  tools?: BuiltinTool[];
34
36
  limits?: Limits;
35
37
  metadata?: Record<string, string>;
38
+ /** The shape of the final answer: `{ type: "json_schema", schema }` or a zod schema. `finalOutput` follows it. */
39
+ outputType?: TOutput;
36
40
  }
37
41
 
38
42
  function deepFreeze<T>(value: T): T {
@@ -56,7 +60,7 @@ function isFiniteNumber(n: unknown): boolean {
56
60
  }
57
61
 
58
62
  /** Runs on the raw options, before the JSON clone turns NaN/Infinity into null. */
59
- function checkNumbers(opts: AgentOptions): void {
63
+ function checkNumbers(opts: AgentOptions<OutputType | undefined>): void {
60
64
  const ms = opts.modelSettings;
61
65
  if (ms !== undefined && ms !== null) {
62
66
  if (ms.temperature !== undefined && !(isFiniteNumber(ms.temperature) && ms.temperature >= 0 && ms.temperature <= 2)) {
@@ -91,8 +95,8 @@ function dropNulls<T extends object>(value: T | null | undefined): T | undefined
91
95
  }
92
96
 
93
97
  /** JS callers spreading JSON configs pass null for unset fields; null means unset everywhere (like Python's None). */
94
- function normalize(raw: AgentOptions): AgentOptions {
95
- const opts = dropNulls(raw) as AgentOptions;
98
+ function normalize<T extends OutputType | undefined>(raw: AgentOptions<T>): AgentOptions<T> {
99
+ const opts = dropNulls(raw) as AgentOptions<T>;
96
100
  if (opts.modelSettings !== undefined) opts.modelSettings = dropNulls(opts.modelSettings);
97
101
  if (opts.limits !== undefined) opts.limits = dropNulls(opts.limits);
98
102
  return opts;
@@ -104,7 +108,10 @@ const LIMIT_KEYS: [keyof Limits, string][] = [
104
108
  ["maxTokensPerTurn", "max_tokens_per_turn"],
105
109
  ];
106
110
 
107
- export class Agent {
111
+ /** An agent with any output type: use it for helpers that accept every agent (plain `Agent` means a text agent). */
112
+ export type AnyAgent = Agent<OutputType | undefined>;
113
+
114
+ export class Agent<TOutput extends OutputType | undefined = undefined> {
108
115
  readonly name: string;
109
116
  readonly instructions: string;
110
117
  readonly model?: string;
@@ -114,8 +121,10 @@ export class Agent {
114
121
  readonly tools?: readonly BuiltinTool[];
115
122
  readonly limits?: Limits;
116
123
  readonly metadata?: Record<string, string>;
124
+ /** Kept by reference and not frozen: a zod schema must stay usable. Non-enumerable, so deepFreeze skips it. */
125
+ declare readonly outputType: TOutput;
117
126
 
118
- constructor(rawOpts: AgentOptions) {
127
+ constructor(rawOpts: AgentOptions<TOutput>) {
119
128
  const opts = normalize(rawOpts);
120
129
  for (const tool of opts.tools ?? []) {
121
130
  if (tool instanceof Agent) {
@@ -132,6 +141,7 @@ export class Agent {
132
141
  this.tools = clone(opts.tools);
133
142
  this.limits = clone(opts.limits);
134
143
  this.metadata = clone(opts.metadata);
144
+ Object.defineProperty(this, "outputType", { value: opts.outputType, enumerable: false, writable: false });
135
145
  this.check();
136
146
  deepFreeze(this);
137
147
  }
@@ -140,6 +150,10 @@ export class Agent {
140
150
  if (typeof this.name !== "string" || !SLUG.test(this.name)) {
141
151
  throw new UserError(`name: ${JSON.stringify(this.name)} must match ${SLUG.source}`);
142
152
  }
153
+ if (this.outputType !== undefined) {
154
+ checkOutputType(this.outputType);
155
+ outputSchema(this.outputType as OutputType); // refuse what the server would, before anything is sent
156
+ }
143
157
  for (const [key, value] of [["model", this.model], ["endpoint", this.endpoint]] as [string, unknown][]) {
144
158
  if (value !== undefined && (typeof value !== "string" || value === "")) {
145
159
  throw new UserError(`${key}: must be a non-empty string`);
@@ -235,6 +249,7 @@ export class Agent {
235
249
  }
236
250
  out["builtin_tools"] = tools;
237
251
  }
252
+ if (this.outputType !== undefined) out["output_schema"] = outputSchema(this.outputType as OutputType);
238
253
  return out;
239
254
  }
240
255
 
@@ -1,6 +1,7 @@
1
1
  /** deploy()/undeploy(): 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
+ import type { OutputType } from "./output.js";
4
5
  import { DriftError, DuplicateAgentsError, UserError } from "./errors.js";
5
6
  import { canonicalJson, fingerprintBody, settingsFingerprint } from "./fingerprint.js";
6
7
  import { SettingsTransport } from "./settingsTransport.js";
@@ -37,7 +38,7 @@ function storedHash(remote: RemoteAgent): string | undefined {
37
38
  return typeof h === "string" ? h : undefined;
38
39
  }
39
40
 
40
- function changedFields(remote: RemoteAgent, agent: Agent): string[] {
41
+ function changedFields(remote: RemoteAgent, agent: Agent<OutputType | undefined>): string[] {
41
42
  const want = fingerprintBody(agent.toSettings());
42
43
  const have = fingerprintBody(remote.settings);
43
44
  const keys: string[] = [];
@@ -53,7 +54,7 @@ function changedFields(remote: RemoteAgent, agent: Agent): string[] {
53
54
  return keys;
54
55
  }
55
56
 
56
- async function update(transport: Transport, remote: RemoteAgent, agent: Agent, strict: boolean): Promise<Deployment> {
57
+ async function update(transport: Transport, remote: RemoteAgent, agent: Agent<OutputType | undefined>, strict: boolean): Promise<Deployment> {
57
58
  const stored = storedHash(remote);
58
59
  if (stored !== undefined && settingsFingerprint(remote.instructions, remote.settings) !== stored) {
59
60
  const changed = changedFields(remote, agent);
@@ -68,7 +69,7 @@ async function update(transport: Transport, remote: RemoteAgent, agent: Agent, s
68
69
  return { agentId: remote.agentId, action: "updated" };
69
70
  }
70
71
 
71
- async function deployWith(agent: Agent, transport: Transport, strict: boolean, adopt?: string): Promise<Deployment> {
72
+ async function deployWith(agent: Agent<OutputType | undefined>, transport: Transport, strict: boolean, adopt?: string): Promise<Deployment> {
72
73
  const found = await transport.findAgents(agent.name);
73
74
  if (adopt !== undefined) {
74
75
  const target = await transport.readAgent(adopt);
@@ -90,7 +91,7 @@ async function deployWith(agent: Agent, transport: Transport, strict: boolean, a
90
91
  }
91
92
 
92
93
  export async function deploy(
93
- agent: Agent,
94
+ agent: Agent<OutputType | undefined>,
94
95
  opts: { client?: Configuration; transport?: Transport; strict?: boolean; adopt?: string } = {},
95
96
  ): Promise<Deployment> {
96
97
  const transport = resolveTransport(opts.client, opts.transport);
@@ -148,7 +149,7 @@ export function forget(name: string): void {
148
149
  * Keyed by name, as the server is: a variant with the same name redeploys, chained after any in-flight deploy so
149
150
  * deploys of one name never overlap.
150
151
  */
151
- export function agentIdFor(agent: Agent, transport: Transport, owner: object): Promise<string> {
152
+ export function agentIdFor(agent: Agent<OutputType | undefined>, transport: Transport, owner: object): Promise<string> {
152
153
  const hash = agent.specHash();
153
154
  let owners = cache.get(agent.name);
154
155
  if (!owners) {
@@ -19,7 +19,34 @@ export class UserError extends AgentsError {
19
19
  }
20
20
  }
21
21
 
22
- export class ModelBehaviorError extends AgentsError {}
22
+ /** Where a `ModelBehaviorError` came from: the server's check, or the `outputType`'s own `parse`. */
23
+ export type ModelBehaviorErrorSource = "server" | "local_parse";
24
+
25
+ /**
26
+ * The agent's answer didn't match its `outputType`. `source` says where: `"server"` (no answer matched the schema
27
+ * after the server's retry; `rawText` is the model's last attempt) or `"local_parse"` (the server accepted the answer
28
+ * but the `outputType`'s `parse` refused it, for example a zod refinement; `rawText` is the server's JSON,
29
+ * re-serialised).
30
+ */
31
+ export class ModelBehaviorError extends AgentsError {
32
+ readonly rawText: string;
33
+ readonly errors: string[];
34
+ /** The server's `outputNote`: the turn's size-refused `final_answer` was not the answer. */
35
+ readonly note: string | undefined;
36
+ readonly source: ModelBehaviorErrorSource;
37
+ /** The run's conversation, set when a run rejects with this, so the caller can continue it (`conversationId`) or
38
+ * fetch its `ResponseDetail`. */
39
+ conversationId: string | undefined = undefined;
40
+
41
+ constructor(rawText = "", errors: string[] = [], note?: string, source: ModelBehaviorErrorSource = "server") {
42
+ const prefix = source === "server" ? "model output rejected" : "model output rejected by outputType";
43
+ super(errors.length ? `${prefix}: ` + errors.join("; ") : rawText);
44
+ this.rawText = rawText;
45
+ this.errors = errors.slice();
46
+ this.note = note;
47
+ this.source = source;
48
+ }
49
+ }
23
50
 
24
51
  export class MaxTurnsExceededError extends AgentsError {}
25
52
 
@@ -14,6 +14,15 @@ export interface FunctionCallRequest {
14
14
  arguments: Record<string, unknown>;
15
15
  }
16
16
 
17
+ /** A source the structured output cited: the server's citation-manifest entry, passed through as sent. */
18
+ export interface OutputCitation {
19
+ cite_id: string;
20
+ type?: string;
21
+ url?: string;
22
+ title?: string;
23
+ [key: string]: unknown;
24
+ }
25
+
17
26
  export type Event =
18
27
  | { kind: "text_start"; id: string }
19
28
  | { kind: "text_delta"; delta: string; id?: string }
@@ -24,6 +33,27 @@ export type Event =
24
33
  | { kind: "clarify_requested"; requestId: string; questions: ClarifyQuestion[] }
25
34
  | { kind: "function_calls_requested"; requestId: string; calls: FunctionCallRequest[]; expiresAt?: string }
26
35
  | { kind: "stopped"; reason: string }
36
+ /** The turn's structured output (`data-output`); `output` is null and `skipped` says why when the turn ended
37
+ * without one: `limit`, `budget`, `paused` or `suppressed` (a cron turn that ended `[SILENT]`), passed through as
38
+ * sent, so a newer server's value arrives unchanged. */
39
+ | {
40
+ kind: "output";
41
+ output: unknown;
42
+ skipped?: string;
43
+ /** How the server produced it (`tool_in_loop`, `tool_oversize`, `forced_tool`, `native`, `prompted`), passed
44
+ * through as sent. `tool_oversize`: the model's `final_answer` was too large for the tool loop and the server
45
+ * validated it afterwards. */
46
+ mode?: string;
47
+ /** The sources `output` cited, first citation first; absent when it cited none. `output` itself carries no
48
+ * `[cite:...]` markers. */
49
+ citations?: OutputCitation[];
50
+ /** Set when the turn's `final_answer` was refused for size and was not the answer: `oversize_answer_invalid`
51
+ * (it did not validate) or `oversize_answer_dropped` (too large to check), so `output` came from the model's
52
+ * later text. */
53
+ note?: string;
54
+ }
55
+ /** No answer matched the agent's output schema (`data-output-error`); `note` as on `output`. */
56
+ | { kind: "output_error"; errors: string[]; rawText: string; note?: string }
27
57
  /** An agent.json limit ended the turn (`data-turn-limit`); the wrap-up answer still follows. `capKind` is the
28
58
  * server's cap name: `max_turns`, `tool_calls` or `tokens`. `limit` is the agent.json `limits` key that set it
29
59
  * (`max_turns`, `max_tool_calls_per_turn` or `max_tokens_per_turn`) and `value` the configured number; both are
@@ -127,8 +157,26 @@ function map(chunk: Record<string, unknown>): Event | null {
127
157
  return { kind: "turn_failed", code: str(chunk["code"], "turn_failed"), message: text(chunk["errorText"]) };
128
158
  case "finish":
129
159
  return { kind: "turn_finished", reason: str(chunk["finishReason"], "stop") };
160
+ case "data-output": {
161
+ const ev: Event = { kind: "output", output: data["output"] ?? null };
162
+ if (typeof data["skipped"] === "string" && data["skipped"]) ev.skipped = data["skipped"];
163
+ if (typeof data["mode"] === "string" && data["mode"]) ev.mode = data["mode"];
164
+ const citations = Array.isArray(data["citations"]) ? data["citations"].filter(isObject) : [];
165
+ if (citations.length) ev.citations = citations as OutputCitation[];
166
+ if (typeof data["note"] === "string" && data["note"]) ev.note = data["note"];
167
+ return ev;
168
+ }
169
+ case "data-output-error": {
170
+ const errors = data["errors"];
171
+ const ev: Event = {
172
+ kind: "output_error",
173
+ errors: Array.isArray(errors) ? errors.map(String) : typeof errors === "string" ? [errors] : [],
174
+ rawText: text(data["rawText"]),
175
+ };
176
+ if (typeof data["note"] === "string" && data["note"]) ev.note = data["note"];
177
+ return ev;
178
+ }
130
179
  default:
131
- // data-output and data-output-error are unknown until structured output lands.
132
180
  return { kind: "unknown", chunk };
133
181
  }
134
182
  }
@@ -2,12 +2,13 @@ export * from "./errors.js";
2
2
  export * from "./fingerprint.js";
3
3
  export * from "./tools.js";
4
4
  export * from "./agent.js";
5
- export type { Event, ClarifyQuestion, FunctionCallRequest } from "./events.js";
5
+ export type { Event, ClarifyQuestion, FunctionCallRequest, OutputCitation } from "./events.js";
6
6
  export { SettingsTransport } from "./settingsTransport.js";
7
7
  export type { RemoteAgent, SettingsWarning, TurnStream, Transport } from "./transport.js";
8
8
  export { deploy, undeploy, setDefaultClient } from "./deploy.js";
9
9
  export type { Deployment } from "./deploy.js";
10
10
  export { run, RunResult, StreamedRunResult } from "./run.js";
11
11
  export type { RunOptions, RunStreamEvent, ClarifyHandler, StopReason } from "./run.js";
12
+ export type { JsonSchemaOutputType, OutputType, ResolvedOutput, SchemaLikeOutputType } from "./output.js";
12
13
  export { RunState } from "./runState.js";
13
14
  export type { Interruption } from "./runState.js";