Line data Source code
1 : import {
2 : zAgentAdmissionError,
3 : zAgentAnswerAccepted,
4 : zAgentAskKind,
5 : zAgentAskResolvedData,
6 : zAgentAttachmentRejected,
7 : zAgentCancelAccepted,
8 : zAgentError as zGeneratedAgentError,
9 : zAgentExtensionChangedData as zGeneratedAgentExtensionChangedData,
10 : zAgentIdentity as zGeneratedAgentIdentity,
11 : zAgentMessage as zGeneratedAgentMessage,
12 : zAgentPendingAskBase,
13 : zAgentRunMode as zGeneratedAgentRunMode,
14 : zAgentThreadListResponse as zGeneratedAgentThreadListResponse,
15 : zAgentToolCallData as zGeneratedAgentToolCallData,
16 : zAgentThinkingEntry,
17 : zAgentTurnAccepted as zGeneratedAgentTurnAccepted,
18 : zAgentTurnUsage as zGeneratedAgentTurnUsage,
19 : zToolCallSummary,
20 : zWorkflowListResponse
21 : } from '@comfyorg/ingest-types/zod'
22 : import type {
23 : AgentAnswerAccepted,
24 : AgentAskKind,
25 : AgentCancelAccepted,
26 : AgentRunMode as AgentRunModePreference,
27 : AgentThreadSummary,
28 : AgentTurnAccepted as GeneratedAgentTurnAccepted
29 : } from '@comfyorg/ingest-types'
30 : import { z } from 'zod'
31 :
32 : import { isNodeLocatorId } from '@comfyorg/graph-model/nodeIdentification'
33 :
34 : export { zAgentAdmissionError, zAgentCancelAccepted }
35 : export type {
36 : AgentAnswerAccepted,
37 : AgentCancelAccepted,
38 : AgentRunModePreference,
39 : AgentThreadSummary
40 : }
41 :
42 : /**
43 : * The 202 from the answer route. A backend that predates the committed-answer
44 : * body sends only `status`, so `selected` is optional here.
45 : */
46 2 : export const zAgentAnswerReceipt = zAgentAnswerAccepted.partial({
47 : selected: true
48 : })
49 : export type AgentAnswerReceipt = z.infer<typeof zAgentAnswerReceipt>
50 :
51 2 : const zTurnId = z.string().brand<'TurnId'>()
52 : export type TurnId = z.infer<typeof zTurnId>
53 2 : export const toTurnId = (value: string): TurnId => zTurnId.parse(value)
54 :
55 2 : export const zAgentTurnAccepted = zGeneratedAgentTurnAccepted
56 : .extend({
57 : workflow_id: z.string().optional()
58 : })
59 : .passthrough()
60 : export type AgentTurnAccepted = GeneratedAgentTurnAccepted & {
61 : workflow_id?: string
62 : }
63 :
64 2 : export const RENDERED_ASK_KINDS = [
65 : 'run_approval',
66 : 'ask_user',
67 : 'delete_approval',
68 : 'paused'
69 : ] as const satisfies readonly AgentAskKind[]
70 : export type RenderedAskKind = (typeof RENDERED_ASK_KINDS)[number]
71 :
72 2 : const zTolerantPendingAsk = zAgentPendingAskBase.extend({
73 : kind: zAgentAskKind.or(z.literal('unknown')).catch('unknown'),
74 : context: z.unknown().optional()
75 : })
76 :
77 2 : export const zAgentRunMode = zGeneratedAgentRunMode.superRefine(
78 : ({ mode, credit_limit }, ctx) => {
79 2 : if (
80 : mode === 'auto_limited' &&
81 : (credit_limit === null ||
82 : !Number.isInteger(credit_limit) ||
83 : credit_limit <= 0)
84 : ) {
85 0 : ctx.addIssue({
86 : code: 'custom',
87 : path: ['credit_limit'],
88 : message: 'auto_limited requires a positive credit limit'
89 : })
90 : }
91 2 : if (mode !== 'auto_limited' && credit_limit !== null) {
92 0 : ctx.addIssue({
93 : code: 'custom',
94 : path: ['credit_limit'],
95 : message: 'credit limit is only valid for auto_limited'
96 : })
97 : }
98 : }
99 : )
100 : export type AgentRunModeValue = AgentRunModePreference['mode']
101 :
102 2 : const SKILL_NAME_MAX = 256
103 :
104 : /**
105 : * Display-only, so an over-long name is clamped. Rejecting it would drop
106 : * the live frame or the whole persisted transcript.
107 : */
108 2 : const zSkillName = z
109 : .string()
110 : .transform((skill) => Array.from(skill).slice(0, SKILL_NAME_MAX).join(''))
111 : .nullish()
112 :
113 : /**
114 : * One entry of a persisted assistant row's `content.tool_calls` (see
115 : * `agentTranscript.ts`'s `parseToolCallEntry`), the reload-path counterpart
116 : * to the live WebSocket's `zAgentToolCallData` above. Sourced from the
117 : * generated `ToolCallSummary` schema (Comfy-Org/cloud#10360), but relaxed:
118 : * the generated schema requires `tool_call_id`, narrows `status` to the
119 : * closed `'success' | 'error'` wire vocabulary, and requires `duration_ms`
120 : * to be an integer, which is only true for rows persisted after that
121 : * backend change landed. Real historical rows can still carry a bare `id`
122 : * with no `tool_call_id`, a `status` of `'ok'` (an older success alias —
123 : * see `toolCallOk` in `agentTranscript.ts`), or a non-finite/negative
124 : * `duration_ms`. `parseToolCallEntry` picks only the fields it actually
125 : * reads from this, so an unrelated field (e.g. a strict
126 : * `started_at`/`finished_at` datetime) never gates the entry.
127 : */
128 2 : export const zPersistedToolCallSummary = zToolCallSummary.extend({
129 : id: z.string(),
130 : // `.nullish()`, matching `zSkillName` above: a Go pointer field serialized
131 : // without `omitempty` sends an explicit `null` rather than omitting the
132 : // key, and `.optional()` alone rejects that, failing this entry's
133 : // `safeParse` and dropping the whole tool-call row.
134 : tool_call_id: z.string().nullish(),
135 : status: z.string().nullish(),
136 : // `z.custom`, not `z.number()`: Zod 4's `z.number()` also rejects
137 : // `Infinity`/`-Infinity` (Zod 3 only rejected `NaN`), which would fail
138 : // this entry's `safeParse` and drop the whole tool-call row over a bad
139 : // `duration_ms` alone. `NaN` stays rejected here, matching the
140 : // pre-existing Zod 3 behavior; `parseDurationMs` in `agentTranscript.ts`
141 : // already does the real finite/non-negative check and omits the field
142 : // for `Infinity`/`-Infinity` instead of failing the whole entry.
143 : duration_ms: z
144 : .custom<number>((val) => typeof val === 'number' && !Number.isNaN(val))
145 : .nullish(),
146 : skill: zSkillName
147 : })
148 : export type PersistedToolCallSummary = z.infer<typeof zPersistedToolCallSummary>
149 :
150 : /**
151 : * One persisted `content.thinking` entry: a model round's thinking text,
152 : * anchored to that round's first tool call when it made one.
153 : */
154 2 : export const zPersistedThinkingEntry = zAgentThinkingEntry
155 : .pick({ text: true })
156 : .extend({ tool_call_id: z.string().nullish() })
157 :
158 : /**
159 : * The message-parse boundary's `content.tool_calls` field is deliberately
160 : * `z.array(z.unknown())`, not the stricter `zPersistedToolCallSummary`
161 : * above: `agentRestClient.ts`'s `request()` calls `.parse()` (throws) on
162 : * the whole `AgentMessages` array, so a single non-conforming historical
163 : * tool-call row must never fail the entire conversation-history load.
164 : * `agentTranscript.ts`'s `parseToolCallEntry` runs its own `safeParse`
165 : * per entry and degrades just that one row instead.
166 : *
167 : * The generated `AgentMessage.content` schema also keeps a
168 : * `[key: string]: unknown` index signature on its TS type but no matching
169 : * `.passthrough()` on its zod schema — the `.passthrough()` below re-widens
170 : * it so a persisted row's other `content` fields (`text`, `attachments`,
171 : * `attachment_refs`, `workflow_references`, ...; see `agentTranscript.ts`)
172 : * keep parsing.
173 : */
174 2 : const zAgentMessageContent = z
175 : .object({
176 : // `z.unknown()`, not `z.array(z.unknown())`: a Go nil slice persisted
177 : // without `omitempty` sends `tool_calls: null`, and any other historical
178 : // row could carry a non-array value here too. `zAgentMessages.parse()`
179 : // throws on the whole history for a schema mismatch, so this field must
180 : // accept anything; `agentTranscript.ts`'s `parseToolCalls` already
181 : // guards with `Array.isArray` and degrades just that one row's tool
182 : // calls instead.
183 : tool_calls: z.unknown().optional()
184 : })
185 : .passthrough()
186 :
187 2 : export const zAgentMessage = zGeneratedAgentMessage
188 : .extend({
189 : content: zAgentMessageContent.optional(),
190 : pending_ask: zTolerantPendingAsk.optional()
191 : })
192 : .passthrough()
193 :
194 2 : export const zAgentMessages = z.array(zAgentMessage)
195 : export type AgentMessages = z.infer<typeof zAgentMessages>
196 :
197 2 : export const zAgentThreads = zGeneratedAgentThreadListResponse.passthrough()
198 :
199 2 : export const zCloudWorkflowIndex = zWorkflowListResponse
200 : .pick({ pagination: true })
201 : .extend({
202 : data: z.array(
203 : z.object({ id: z.string(), name: z.string().optional() }).passthrough()
204 : )
205 : })
206 : export type CloudWorkflowEntry = z.infer<
207 : typeof zCloudWorkflowIndex
208 : >['data'][number]
209 :
210 2 : export const zAgentError = z.union([zGeneratedAgentError, zAgentAdmissionError])
211 :
212 2 : export const zAttachmentRejection = zAgentAttachmentRejected.pick({
213 : rejected: true,
214 : rejected_count: true,
215 : type: true
216 : })
217 :
218 2 : export const zLoopbackOnlyRefusal = zGeneratedAgentError
219 : .extend({
220 : error: z.string().trim().min(1),
221 : code: z.literal('agent_loopback_only')
222 : })
223 : .passthrough()
224 :
225 : /**
226 : * The 403 body the agent service returns when it will not serve the turn's
227 : * `workflow_id` to the caller's workspace, whether the row is gone or belongs
228 : * elsewhere. The message is the only discriminator on the wire: a 403 refusing
229 : * the thread or the message carries the same shape with a different subject.
230 : */
231 2 : export const zDisownedWorkflowError = z.object({
232 : error: z.literal('workflow not found or access denied')
233 : })
234 :
235 : /**
236 : * The 409 body the agent service returns when the thread already has a turn in
237 : * progress (`rejectTurnInProgress` in `services/agent/server/agent_handler.go`).
238 : * `type` is the discriminator — a 409 from the cancel or answer endpoints
239 : * carries no `type` at all — and the two ids name the turn that holds the
240 : * thread, so the client can re-attach to it instead of reporting a dead end.
241 : *
242 : * Both ids are optional on the wire: the server resolves them best-effort and
243 : * documents that a lookup failure "still yields the 409, just without the id".
244 : * A conflict with no ids is still a conflict, so the discriminator alone has to
245 : * be enough to recognise one.
246 : */
247 2 : export const zTurnInProgressError = z
248 : .object({
249 : type: z.literal('TURN_IN_PROGRESS'),
250 : active_message_id: z.string().optional(),
251 : turn_id: z.string().optional()
252 : })
253 : .passthrough()
254 :
255 2 : const zAgentThinkingData = z
256 : .object({
257 : delta: z.string(),
258 : message_id: z.string(),
259 : thread_id: z.string()
260 : })
261 : .passthrough()
262 :
263 2 : const zAgentToolCallData = zGeneratedAgentToolCallData
264 : .extend({
265 : skill: zSkillName,
266 : args: z.never().optional(),
267 : workflow_id: zGeneratedAgentToolCallData.shape.workflow_id.catch(undefined),
268 : op_ids: zGeneratedAgentToolCallData.shape.op_ids.catch(undefined),
269 : doc_seq: zGeneratedAgentToolCallData.shape.doc_seq.catch(undefined),
270 : doc_lineage_seq:
271 : zGeneratedAgentToolCallData.shape.doc_lineage_seq.catch(undefined),
272 : job_id: z
273 : .string()
274 : .min(1)
275 : .max(128)
276 : .refine(
277 : (value) =>
278 : !value.includes('\u0000') &&
279 : !value.includes('\n') &&
280 : !value.includes('\r') &&
281 : !value.includes('\t')
282 : )
283 : .optional()
284 : .catch(undefined),
285 : job_workflow_id: z.string().min(1).optional().catch(undefined)
286 : })
287 : .passthrough()
288 :
289 2 : const zAgentMessageDeltaData = z
290 : .object({
291 : delta: z.string(),
292 : message_id: z.string(),
293 : thread_id: z.string()
294 : })
295 : .passthrough()
296 :
297 : // The whole answer so far while the model is still writing it: each draft
298 : // replaces the last, and an empty text withdraws it.
299 2 : const zAgentMessageDraftData = z
300 : .object({
301 : text: z.string(),
302 : message_id: z.string(),
303 : thread_id: z.string()
304 : })
305 : .passthrough()
306 :
307 2 : const zAgentUsage = z
308 : .object({
309 : input_tokens: z.number().nullish(),
310 : output_tokens: z.number().nullish(),
311 : total_tokens: z.number().nullish(),
312 : cache_read_input_tokens: z.number().nullish(),
313 : cache_creation_input_tokens: z.number().nullish(),
314 : charge_micro_usd: zGeneratedAgentTurnUsage.shape.charge_micro_usd
315 : })
316 : .passthrough()
317 :
318 2 : const zAgentMessageDoneData = z
319 : .object({
320 : message_id: z.string(),
321 : thread_id: z.string(),
322 : usage: zAgentUsage.nullish().catch(undefined)
323 : })
324 : .passthrough()
325 :
326 2 : const zAgentActiveTabData = z
327 : .object({
328 : workflow_id: z.string(),
329 : node_locator_id: z
330 : .string()
331 : .max(256)
332 : .refine((value): boolean => isNodeLocatorId(value))
333 : .optional(),
334 : name: z.string().optional(),
335 : thread_id: z.string().optional(),
336 : message_id: z.string().optional()
337 : })
338 : .passthrough()
339 : export type AgentActiveTabData = z.infer<typeof zAgentActiveTabData>
340 :
341 2 : const zAgentThinkingEvent = z.object({
342 : type: z.literal('agent_thinking'),
343 : data: zAgentThinkingData
344 : })
345 :
346 2 : const zAgentToolCallEvent = z.object({
347 : type: z.literal('agent_tool_call'),
348 : data: zAgentToolCallData
349 : })
350 :
351 2 : const zAgentMessageDeltaEvent = z.object({
352 : type: z.literal('agent_message_delta'),
353 : data: zAgentMessageDeltaData
354 : })
355 :
356 2 : const zAgentMessageDraftEvent = z.object({
357 : type: z.literal('agent_message_draft'),
358 : data: zAgentMessageDraftData
359 : })
360 :
361 2 : const zAgentThinkingDraftEvent = z.object({
362 : type: z.literal('agent_thinking_draft'),
363 : data: zAgentMessageDraftData
364 : })
365 :
366 2 : const zAgentMessageDoneEvent = z.object({
367 : type: z.literal('agent_message_done'),
368 : data: zAgentMessageDoneData
369 : })
370 :
371 2 : const zAgentActiveTabEvent = z.object({
372 : type: z.literal('agent_active_tab'),
373 : data: zAgentActiveTabData
374 : })
375 :
376 2 : const zAgentAskEvent = z.object({
377 : type: z.literal('agent_ask'),
378 : data: zTolerantPendingAsk.extend({ thread_id: z.string() })
379 : })
380 :
381 2 : const zAgentAskResolvedEvent = z.object({
382 : type: z.literal('agent_ask_resolved'),
383 : data: zAgentAskResolvedData
384 : })
385 :
386 2 : const zAgentExtensionChangedEvent = z.object({
387 : type: z.literal('agent_extension_changed'),
388 : data: zGeneratedAgentExtensionChangedData
389 : .extend({
390 : pack: zGeneratedAgentExtensionChangedData.shape.pack
391 : .max(256)
392 : .refine((pack) => !/[\p{Cc}\p{Cf}]/u.test(pack))
393 : })
394 : .passthrough()
395 : })
396 :
397 2 : export const zAgentWsEvent = z.discriminatedUnion('type', [
398 : zAgentThinkingEvent,
399 : zAgentToolCallEvent,
400 : zAgentMessageDeltaEvent,
401 : zAgentMessageDraftEvent,
402 : zAgentThinkingDraftEvent,
403 : zAgentMessageDoneEvent,
404 : zAgentActiveTabEvent,
405 : zAgentAskEvent,
406 : zAgentAskResolvedEvent,
407 : zAgentExtensionChangedEvent
408 : ])
409 : export type AgentWsEvent = z.infer<typeof zAgentWsEvent>
410 :
411 2 : const AGENT_WS_EVENT_TYPES: ReadonlySet<AgentWsEvent['type']> = new Set(
412 : zAgentWsEvent.options.map((option) => option.shape.type.value)
413 : )
414 :
415 1 : export function isAgentEvent(type: string): type is AgentWsEvent['type'] {
416 1 : return AGENT_WS_EVENT_TYPES.has(type as AgentWsEvent['type'])
417 : }
418 :
419 1 : export function parseAgentWsEvent(
420 : value: unknown
421 : ): z.ZodSafeParseResult<AgentWsEvent> {
422 1 : return zAgentWsEvent.safeParse(value)
423 : }
424 :
425 2 : export const zAgentIdentity = zGeneratedAgentIdentity.extend({
426 : user_id: z.string().min(1)
427 : })
428 :
429 : /** The server's `agent` feature, pushed again on every change. */
430 : export interface AgentServerFeature {
431 : state: 'starting' | 'ready' | 'failed'
432 : reason?: string | null
433 : }
|