cencori 1.8.3 → 1.10.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 (48) hide show
  1. package/README.md +89 -1
  2. package/dist/agents/index.d.mts +433 -0
  3. package/dist/agents/index.d.ts +433 -0
  4. package/dist/agents/index.js +897 -0
  5. package/dist/agents/index.js.map +1 -0
  6. package/dist/agents/index.mjs +870 -0
  7. package/dist/agents/index.mjs.map +1 -0
  8. package/dist/ai/index.d.mts +14 -1
  9. package/dist/ai/index.d.ts +14 -1
  10. package/dist/ai/index.js +43 -3
  11. package/dist/ai/index.js.map +1 -1
  12. package/dist/ai/index.mjs +43 -3
  13. package/dist/ai/index.mjs.map +1 -1
  14. package/dist/compute/index.d.mts +1 -1
  15. package/dist/compute/index.d.ts +1 -1
  16. package/dist/documents/index.d.mts +1 -1
  17. package/dist/documents/index.d.ts +1 -1
  18. package/dist/index.d.mts +50 -9
  19. package/dist/index.d.ts +50 -9
  20. package/dist/index.js +67 -13
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +67 -13
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/judgment/index.d.mts +1 -1
  25. package/dist/judgment/index.d.ts +1 -1
  26. package/dist/memory/index.d.mts +1 -1
  27. package/dist/memory/index.d.ts +1 -1
  28. package/dist/react/index.d.mts +6 -6
  29. package/dist/react/index.d.ts +6 -6
  30. package/dist/storage/index.d.mts +5 -7
  31. package/dist/storage/index.d.ts +5 -7
  32. package/dist/storage/index.js +6 -8
  33. package/dist/storage/index.js.map +1 -1
  34. package/dist/storage/index.mjs +6 -8
  35. package/dist/storage/index.mjs.map +1 -1
  36. package/dist/telemetry/index.d.mts +1 -1
  37. package/dist/telemetry/index.d.ts +1 -1
  38. package/dist/{types-CAhDuNTz.d.mts → types-D91o22Gb.d.mts} +28 -1
  39. package/dist/{types-CAhDuNTz.d.ts → types-D91o22Gb.d.ts} +28 -1
  40. package/dist/vision/index.d.mts +1 -1
  41. package/dist/vision/index.d.ts +1 -1
  42. package/dist/voice/index.d.mts +1 -1
  43. package/dist/voice/index.d.ts +1 -1
  44. package/dist/web/index.d.mts +1 -1
  45. package/dist/web/index.d.ts +1 -1
  46. package/dist/workflow/index.d.mts +1 -1
  47. package/dist/workflow/index.d.ts +1 -1
  48. package/package.json +11 -3
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/agents-sdk/schema.ts","../../src/agents-sdk/tool.ts","../../src/agents-sdk/errors.ts","../../src/agents-sdk/transport.ts","../../src/agents-sdk/run.ts","../../src/agents-sdk/agent.ts","../../src/agents-sdk/index.ts"],"sourcesContent":["/**\n * Schemas for tool parameters and structured output, without depending on a\n * validation library. Anything implementing Standard Schema works (zod 3.24+,\n * zod 4, valibot, arktype); JSON Schema is read from Standard JSON Schema\n * (zod 4.2+), a schema's own toJSONSchema(), or given directly as an object.\n */\n\n/** The Standard Schema interface (https://standardschema.dev), inlined. */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n readonly '~standard': {\n readonly version: 1;\n readonly vendor: string;\n readonly validate: (value: unknown) =>\n | StandardResult<Output>\n | Promise<StandardResult<Output>>;\n readonly types?: { readonly input: Input; readonly output: Output } | undefined;\n readonly jsonSchema?: {\n readonly input: (options: { target: string }) => Record<string, unknown>;\n readonly output: (options: { target: string }) => Record<string, unknown>;\n };\n };\n}\n\ntype StandardResult<Output> =\n | { readonly value: Output; readonly issues?: undefined }\n | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray<PropertyKey | { key: PropertyKey }> }> };\n\n/** A JSON Schema object, passed through as is. */\nexport type JsonSchema = Record<string, unknown>;\n\n/** What tool parameters and outputType accept. */\nexport type SchemaLike<T = unknown> = StandardSchemaV1<unknown, T> | JsonSchema;\n\n/** The type a schema validates to; `unknown` for plain JSON Schema. */\nexport type InferSchema<S> = S extends StandardSchemaV1<unknown, infer O> ? O : unknown;\n\nfunction isStandard(schema: unknown): schema is StandardSchemaV1 {\n return typeof schema === 'object' && schema !== null && '~standard' in schema\n && typeof (schema as StandardSchemaV1)['~standard']?.validate === 'function';\n}\n\n/** JSON Schema for a tool's parameters or an output type. */\nexport function toJsonSchema(schema: SchemaLike | undefined): JsonSchema {\n if (!schema) return { type: 'object', properties: {}, additionalProperties: false };\n let json: JsonSchema | undefined;\n if (isStandard(schema)) {\n const std = schema['~standard'];\n if (std.jsonSchema) {\n json = std.jsonSchema.input({ target: 'draft-2020-12' });\n } else if (typeof (schema as { toJSONSchema?: unknown }).toJSONSchema === 'function') {\n json = (schema as unknown as { toJSONSchema: () => JsonSchema }).toJSONSchema();\n } else if (std.vendor === 'zod' && (schema as { _def?: { typeName?: unknown } })._def?.typeName) {\n json = zod3ToJsonSchema(schema as unknown as Zod3);\n } else {\n throw new TypeError(\n `This ${std.vendor} schema can't be converted to JSON Schema. Use zod 4, a library that implements Standard JSON Schema, or pass a JSON Schema object.`,\n );\n }\n } else {\n json = schema;\n }\n // Providers want the bare schema; the $schema keyword only adds noise.\n const { $schema: _ignored, ...rest } = json as JsonSchema & { $schema?: unknown };\n return rest;\n}\n\nexport class SchemaValidationError extends Error {\n readonly issues: ReadonlyArray<{ message: string; path?: string }>;\n constructor(what: string, issues: ReadonlyArray<{ message: string; path?: string }>) {\n super(`${what}: ${issues.map((i) => (i.path ? `${i.path}: ${i.message}` : i.message)).join('; ')}`);\n this.name = 'SchemaValidationError';\n this.issues = issues;\n }\n}\n\n/** Validate a value against a Standard Schema; JSON Schema values pass through unchecked. */\nexport async function validate<T>(schema: SchemaLike<T> | undefined, value: unknown, what: string): Promise<T> {\n if (!schema || !isStandard(schema)) return value as T;\n const result = await schema['~standard'].validate(value);\n if (result.issues) {\n throw new SchemaValidationError(what, result.issues.map((issue) => ({\n message: issue.message,\n path: issue.path?.map((p) => String(typeof p === 'object' && p !== null && 'key' in p ? p.key : p)).join('.') || undefined,\n })));\n }\n return result.value as T;\n}\n\n/** zod 3 keeps its structure in _def; it has no JSON Schema output of its own. */\ninterface Zod3 {\n _def: Record<string, unknown> & { typeName: string; description?: string };\n description?: string;\n}\n\n/**\n * JSON Schema for the zod 3 types tool parameters use. Anything else throws,\n * naming the type, rather than sending the model a wrong schema.\n */\nfunction zod3ToJsonSchema(schema: Zod3): JsonSchema {\n const def = schema._def;\n const describe = (json: JsonSchema): JsonSchema =>\n def.description ? { ...json, description: def.description } : json;\n switch (def.typeName) {\n case 'ZodString': return describe({ type: 'string' });\n case 'ZodNumber': {\n const checks = (def.checks as Array<{ kind: string }> | undefined) ?? [];\n return describe({ type: checks.some((c) => c.kind === 'int') ? 'integer' : 'number' });\n }\n case 'ZodBigInt': return describe({ type: 'integer' });\n case 'ZodBoolean': return describe({ type: 'boolean' });\n case 'ZodNull': return describe({ type: 'null' });\n case 'ZodDate': return describe({ type: 'string', format: 'date-time' });\n case 'ZodAny':\n case 'ZodUnknown': return describe({});\n case 'ZodLiteral': return describe({ const: def.value });\n case 'ZodEnum': return describe({ type: 'string', enum: def.values as unknown[] });\n case 'ZodNativeEnum': return describe({ enum: Object.values(def.values as Record<string, unknown>) });\n case 'ZodArray': return describe({ type: 'array', items: zod3ToJsonSchema(def.type as Zod3) });\n case 'ZodTuple': return describe({ type: 'array', prefixItems: (def.items as Zod3[]).map(zod3ToJsonSchema) });\n case 'ZodRecord': return describe({ type: 'object', additionalProperties: zod3ToJsonSchema(def.valueType as Zod3) });\n case 'ZodUnion':\n case 'ZodDiscriminatedUnion': {\n const options = (Array.isArray(def.options) ? def.options : [...(def.options as Map<unknown, Zod3>).values()]) as Zod3[];\n return describe({ anyOf: options.map(zod3ToJsonSchema) });\n }\n case 'ZodNullable': return describe({ anyOf: [zod3ToJsonSchema(def.innerType as Zod3), { type: 'null' }] });\n case 'ZodOptional':\n case 'ZodDefault':\n case 'ZodCatch':\n case 'ZodReadonly':\n case 'ZodBranded': {\n const inner = zod3ToJsonSchema((def.innerType ?? def.type) as Zod3);\n return def.description ? { ...inner, description: def.description } : inner;\n }\n case 'ZodEffects': return describe(zod3ToJsonSchema(def.schema as Zod3));\n case 'ZodLazy': return describe(zod3ToJsonSchema((def.getter as () => Zod3)()));\n case 'ZodObject': {\n const shape = (typeof def.shape === 'function' ? (def.shape as () => Record<string, Zod3>)() : def.shape) as Record<string, Zod3>;\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n for (const [key, value] of Object.entries(shape)) {\n properties[key] = zod3ToJsonSchema(value);\n const kind = value._def.typeName;\n if (kind !== 'ZodOptional' && kind !== 'ZodDefault') required.push(key);\n }\n return describe({\n type: 'object',\n properties,\n ...(required.length ? { required } : {}),\n additionalProperties: def.unknownKeys === 'passthrough',\n });\n }\n default:\n throw new TypeError(`zod type ${def.typeName} isn't supported in tool parameters. Use zod 4 or pass a JSON Schema object.`);\n }\n}\n","import { toJsonSchema, validate, type InferSchema, type JsonSchema, type SchemaLike } from './schema';\nimport type { RunContext } from './context';\n\nexport const TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;\n\n/** Whether a call needs a human's approval before it runs. */\nexport type NeedsApproval<Args, Ctx> =\n | boolean\n | ((runContext: RunContext<Ctx>, args: Args, callId: string) => boolean | Promise<boolean>);\n\nexport interface ToolOptions<S extends SchemaLike, Ctx = unknown, Out = unknown> {\n /** Name the model calls it by: letters, digits, _ and -, at most 64. */\n name: string;\n /** What it does and when to use it. The model reads this. */\n description: string;\n /** Parameters: a zod (or any Standard Schema) object, or a JSON Schema object. */\n parameters?: S;\n /** Runs the tool. Return anything; non-strings are sent to the model as JSON. */\n execute: (args: InferSchema<S>, runContext: RunContext<Ctx>, details: { callId: string }) => Out | Promise<Out>;\n /**\n * Ask a human before running it. `true` also records the request and the\n * decision in your project's governance ledger; a function decides per call.\n */\n needsApproval?: NeedsApproval<InferSchema<S>, Ctx>;\n /** What the model sees when execute throws. Default: the error's message. */\n errorFunction?: (error: unknown, runContext: RunContext<Ctx>) => string | Promise<string>;\n}\n\nexport interface FunctionTool<Ctx = unknown> {\n readonly type: 'function';\n readonly name: string;\n readonly description: string;\n readonly parameters: JsonSchema;\n readonly needsApproval: NeedsApproval<unknown, Ctx>;\n /** Validate the model's arguments, run the tool, and return what the model sees. */\n invoke(runContext: RunContext<Ctx>, rawArguments: string, callId: string): Promise<string>;\n /** Parse and validate arguments (used to decide on approval before running). */\n parseArguments(rawArguments: string): Promise<unknown>;\n}\n\nfunction stringify(value: unknown): string {\n if (typeof value === 'string') return value;\n if (value === undefined) return '';\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Define a tool the agent can call. It runs in your process, with your\n * credentials and data; Cencori only sees its name, arguments and result.\n *\n * ```ts\n * const getOrder = tool({\n * name: 'get_order',\n * description: 'Look up an order by id',\n * parameters: z.object({ id: z.string() }),\n * execute: async ({ id }) => db.orders.find(id),\n * });\n * ```\n */\nexport function tool<S extends SchemaLike, Ctx = unknown, Out = unknown>(options: ToolOptions<S, Ctx, Out>): FunctionTool<Ctx> {\n if (!TOOL_NAME_PATTERN.test(options.name)) {\n throw new TypeError(`Tool name \"${options.name}\" must be 1-64 letters, digits, _ or -.`);\n }\n const jsonSchema = toJsonSchema(options.parameters);\n\n const parseArguments = async (rawArguments: string): Promise<unknown> => {\n let parsed: unknown = {};\n if (rawArguments && rawArguments.trim()) {\n try {\n parsed = JSON.parse(rawArguments);\n } catch {\n throw new SyntaxError(`The arguments for ${options.name} are not valid JSON.`);\n }\n }\n return validate(options.parameters, parsed, `Invalid arguments for ${options.name}`);\n };\n\n return {\n type: 'function',\n name: options.name,\n description: options.description,\n parameters: jsonSchema,\n needsApproval: (options.needsApproval ?? false) as NeedsApproval<unknown, Ctx>,\n parseArguments,\n async invoke(runContext, rawArguments, callId) {\n try {\n const args = await parseArguments(rawArguments);\n const out = await options.execute(args as InferSchema<S>, runContext, { callId });\n return stringify(out);\n } catch (error) {\n if (options.errorFunction) return options.errorFunction(error, runContext);\n const message = error instanceof Error ? error.message : String(error);\n return `Error running ${options.name}: ${message}`;\n }\n },\n };\n}\n","/** Base class for errors thrown by cencori/agents. */\nexport class AgentsError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AgentsError';\n }\n}\n\n/** The run used up maxTurns model calls without a final answer. */\nexport class MaxTurnsExceededError extends AgentsError {\n readonly sessionId: string;\n constructor(maxTurns: number, sessionId: string) {\n super(`The run exceeded maxTurns (${maxTurns}) without a final answer. Raise maxTurns or check for a tool loop.`);\n this.name = 'MaxTurnsExceededError';\n this.sessionId = sessionId;\n }\n}\n\n/** A guardrail's tripwire fired; the run stopped. */\nexport class GuardrailTripwireTriggered extends AgentsError {\n readonly guardrail: string;\n readonly kind: 'input' | 'output';\n readonly outputInfo: unknown;\n constructor(kind: 'input' | 'output', guardrail: string, outputInfo: unknown) {\n super(`${kind === 'input' ? 'Input' : 'Output'} guardrail \"${guardrail}\" tripped.`);\n this.name = kind === 'input' ? 'InputGuardrailTripwireTriggered' : 'OutputGuardrailTripwireTriggered';\n this.guardrail = guardrail;\n this.kind = kind;\n this.outputInfo = outputInfo;\n }\n}\n\n/**\n * Cencori refused or failed a request, or the turn failed (a project policy\n * blocked it, the model provider errored, credits ran out...).\n */\nexport class CencoriRunError extends AgentsError {\n readonly status?: number;\n readonly code?: string;\n readonly sessionId?: string;\n constructor(message: string, details: { status?: number; code?: string; sessionId?: string } = {}) {\n super(message);\n this.name = 'CencoriRunError';\n this.status = details.status;\n this.code = details.code;\n this.sessionId = details.sessionId;\n }\n}\n","import { CencoriRunError } from './errors';\n\nconst DEFAULT_BASE_URL = 'https://cencori.com';\n\nexport interface TransportOptions {\n /** Secret project key (csk_...). Defaults to the CENCORI_API_KEY environment variable. */\n apiKey?: string;\n /** Defaults to CENCORI_BASE_URL, then https://cencori.com. */\n baseUrl?: string;\n /** Custom fetch (tests, proxies, edge runtimes). */\n fetch?: typeof fetch;\n signal?: AbortSignal;\n}\n\n/** One server-sent event from a session turn. */\nexport interface SessionStreamEvent {\n event: string;\n data: Record<string, unknown>;\n}\n\n/** A tool call the turn paused on. */\nexport interface PausedAction {\n action_id: string;\n tool: string;\n arguments: string;\n needs_approval?: boolean;\n}\n\nexport interface TurnBody {\n input: string | Array<Record<string, unknown>>;\n model: string;\n instructions?: string;\n tools?: Array<Record<string, unknown>>;\n response_format?: Record<string, unknown>;\n temperature?: number;\n max_output_tokens?: number;\n memory?: Record<string, unknown>;\n user?: string;\n metadata?: Record<string, string>;\n reasoning_effort?: 'none' | 'low' | 'medium' | 'high';\n}\n\nexport interface ResumeNext {\n instructions?: string;\n model?: string;\n tools?: Array<Record<string, unknown>>;\n}\n\nfunction env(name: string): string | undefined {\n try {\n return typeof process !== 'undefined' ? process.env?.[name] : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport class Transport {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n private readonly signal?: AbortSignal;\n\n constructor(options: TransportOptions = {}) {\n const apiKey = options.apiKey ?? env('CENCORI_API_KEY');\n if (!apiKey) {\n throw new CencoriRunError('No Cencori API key. Pass apiKey or set CENCORI_API_KEY (a secret project key, csk_...).', { code: 'missing_api_key' });\n }\n this.apiKey = apiKey;\n this.baseUrl = (options.baseUrl ?? env('CENCORI_BASE_URL') ?? DEFAULT_BASE_URL).replace(/\\/+$/, '');\n this.fetchImpl = options.fetch ?? fetch;\n this.signal = options.signal;\n }\n\n private async post(path: string, body: unknown, sessionId?: string): Promise<Response> {\n const response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n method: 'POST',\n headers: {\n 'CENCORI_API_KEY': this.apiKey,\n 'Content-Type': 'application/json',\n 'Accept': 'text/event-stream, application/json',\n },\n body: JSON.stringify(body),\n signal: this.signal,\n });\n if (!response.ok) throw await errorFrom(response, sessionId);\n return response;\n }\n\n /**\n * Create a session and run its first turn in one request. Servers that\n * predate this answer with the plain session JSON; the turn then goes in a\n * second request, as before.\n */\n async createSessionWithTurn(metadata: Record<string, unknown>, body: TurnBody): Promise<{ sessionId: string; response: Response }> {\n const turn = { ...body, stream: true, pause_on_tool_calls: true };\n const response = await this.fetchImpl(`${this.baseUrl}/v1/sessions`, {\n method: 'POST',\n headers: {\n 'CENCORI_API_KEY': this.apiKey,\n 'Content-Type': 'application/json',\n 'Accept': 'text/event-stream, application/json',\n },\n body: JSON.stringify({ metadata, turn }),\n signal: this.signal,\n });\n const headerId = response.headers.get('X-Cencori-Session-Id') ?? undefined;\n if (!response.ok) throw await errorFrom(response, headerId);\n if (headerId) return { sessionId: headerId, response };\n const created = await response.json() as { id?: string };\n if (!created.id) throw new CencoriRunError('Cencori did not return a session id.');\n return { sessionId: created.id, response: await this.turn(created.id, body) };\n }\n\n turn(sessionId: string, body: TurnBody): Promise<Response> {\n return this.post(`/v1/sessions/${encodeURIComponent(sessionId)}/turns`, {\n ...body,\n stream: true,\n pause_on_tool_calls: true,\n }, sessionId);\n }\n\n resume(sessionId: string, actionId: string, toolResults: Array<{ action_id: string; output: string }>, next?: ResumeNext): Promise<Response> {\n return this.post(`/v1/sessions/${encodeURIComponent(sessionId)}/approve`, {\n action_id: actionId,\n tool_results: toolResults,\n ...(next ? { next } : {}),\n }, sessionId);\n }\n}\n\nasync function errorFrom(response: Response, sessionId?: string): Promise<CencoriRunError> {\n let message = `Cencori returned ${response.status}`;\n let code: string | undefined;\n try {\n const body = await response.json() as { error?: { message?: string; code?: string } | string };\n if (typeof body.error === 'string') message = body.error;\n else if (body.error?.message) {\n message = body.error.message;\n code = body.error.code;\n }\n } catch {\n /* not JSON */\n }\n return new CencoriRunError(message, { status: response.status, code, sessionId });\n}\n\n/** Parse a session turn's SSE stream into events. */\nexport async function* readSessionEvents(response: Response): AsyncGenerator<SessionStreamEvent> {\n if (!response.body) return;\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n let event = 'message';\n let data: string[] = [];\n\n const flush = (): SessionStreamEvent | null => {\n if (data.length === 0) {\n event = 'message';\n return null;\n }\n const raw = data.join('\\n');\n data = [];\n const name = event;\n event = 'message';\n try {\n return { event: name, data: JSON.parse(raw) as Record<string, unknown> };\n } catch {\n return { event: name, data: { raw } };\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let newline: number;\n while ((newline = buffer.indexOf('\\n')) >= 0) {\n const line = buffer.slice(0, newline).replace(/\\r$/, '');\n buffer = buffer.slice(newline + 1);\n if (line === '') {\n const parsed = flush();\n if (parsed) yield parsed;\n } else if (line.startsWith('event:')) {\n event = line.slice(6).trim();\n } else if (line.startsWith('data:')) {\n data.push(line.slice(5).replace(/^ /, ''));\n }\n }\n }\n buffer += decoder.decode();\n if (buffer.trim()) {\n for (const line of buffer.split('\\n')) {\n if (line.startsWith('event:')) event = line.slice(6).trim();\n else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));\n }\n }\n const last = flush();\n if (last) yield last;\n } finally {\n reader.releaseLock();\n }\n}\n","import { Agent } from './agent';\nimport type { RunContext } from './context';\nimport { AgentsError, CencoriRunError, GuardrailTripwireTriggered, MaxTurnsExceededError } from './errors';\nimport { toJsonSchema, validate } from './schema';\nimport type { FunctionTool } from './tool';\nimport { readSessionEvents, Transport, type PausedAction, type ResumeNext, type TransportOptions } from './transport';\n\nexport interface RunOptions<Ctx = unknown> extends TransportOptions {\n /** Your value for tools, guardrails and dynamic instructions. Stays in your process. */\n context?: Ctx;\n /** Continue an earlier conversation: pass the sessionId from a previous result. */\n sessionId?: string;\n /** Most model calls this run may make (each tool round is one). Default 10. */\n maxTurns?: number;\n /** Stream events as they happen; see StreamedRunResult. */\n stream?: boolean;\n /** Turn on Cencori memory for this user: recalled before, written after. */\n memory?: { userId: string; [key: string]: unknown };\n /** Your end user's id: per-user quotas, billing and memory. */\n user?: string;\n /** Extra metadata on the session (strings). */\n metadata?: Record<string, string>;\n}\n\n/** A tool call waiting for a human. Approve or reject it on result.state, then run again. */\nexport interface ToolApprovalItem {\n type: 'tool_approval';\n callId: string;\n toolName: string;\n /** The model's arguments, as JSON text. */\n arguments: string;\n agentName: string;\n}\n\nexport type RunItem =\n | { type: 'message'; agentName: string; text: string }\n | { type: 'tool_call'; agentName: string; callId: string; toolName: string; arguments: string }\n | { type: 'tool_output'; agentName: string; callId: string; toolName: string; output: string }\n | { type: 'handoff'; from: string; to: string };\n\nexport interface Usage {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n}\n\nexport type RunStreamEvent =\n | { type: 'agent_updated'; agent: Agent<any> }\n | { type: 'text_delta'; delta: string; agentName: string }\n | { type: 'tool_call'; callId: string; toolName: string; arguments: string; agentName: string }\n | { type: 'tool_output'; callId: string; toolName: string; output: string; agentName: string }\n | { type: 'handoff'; from: string; to: string }\n | { type: 'interruption'; interruptions: ToolApprovalItem[] };\n\ninterface PendingPause {\n actionId: string;\n actions: PausedAction[];\n text: string;\n}\n\ninterface SerializedRunState {\n v: 1;\n sessionId: string;\n agentName: string;\n turnsUsed: number;\n usage: Usage;\n pending: PendingPause;\n decisions: Record<string, { approved: boolean; message?: string }>;\n}\n\n/**\n * A paused run: tool calls are waiting for a human. Approve or reject each,\n * then pass the state back to run(). Serializable with JSON.stringify, so the\n * decision can come minutes or hours later from another process (Cencori\n * keeps a paused session for 24 hours).\n */\nexport class RunState {\n readonly sessionId: string;\n readonly agentName: string;\n readonly turnsUsed: number;\n readonly usage: Usage;\n /** @internal */\n readonly pending: PendingPause;\n private readonly decisions: Map<string, { approved: boolean; message?: string }>;\n\n /** @internal */\n constructor(init: Omit<SerializedRunState, 'v' | 'decisions'> & { decisions?: SerializedRunState['decisions'] }) {\n this.sessionId = init.sessionId;\n this.agentName = init.agentName;\n this.turnsUsed = init.turnsUsed;\n this.usage = init.usage;\n this.pending = init.pending;\n this.decisions = new Map(Object.entries(init.decisions ?? {}));\n }\n\n approve(item: ToolApprovalItem | string): void {\n this.decisions.set(typeof item === 'string' ? item : item.callId, { approved: true });\n }\n\n /** The model is told the call was rejected, with your message if given. */\n reject(item: ToolApprovalItem | string, options: { message?: string } = {}): void {\n this.decisions.set(typeof item === 'string' ? item : item.callId, { approved: false, message: options.message });\n }\n\n /** @internal */\n decision(callId: string): { approved: boolean; message?: string } | undefined {\n return this.decisions.get(callId);\n }\n\n toJSON(): SerializedRunState {\n return {\n v: 1,\n sessionId: this.sessionId,\n agentName: this.agentName,\n turnsUsed: this.turnsUsed,\n usage: this.usage,\n pending: this.pending,\n decisions: Object.fromEntries(this.decisions),\n };\n }\n\n static fromJSON(json: string | SerializedRunState): RunState {\n const data = (typeof json === 'string' ? JSON.parse(json) : json) as SerializedRunState;\n if (data?.v !== 1 || !data.sessionId || !data.pending) throw new AgentsError('Not a cencori/agents run state.');\n return new RunState(data);\n }\n}\n\nexport interface RunResult<Output = string> {\n /** The final answer: text, or the parsed outputType. Undefined while interrupted. */\n finalOutput: Output | undefined;\n /** The Cencori session: pass it as sessionId to continue the conversation. */\n sessionId: string;\n /** The agent that gave the final answer (after any handoffs). */\n lastAgent: Agent<any>;\n /** Tool calls waiting for approval; empty when the run finished. */\n interruptions: ToolApprovalItem[];\n /** Set when interrupted: approve or reject, then run(agent, state). */\n state: RunState | undefined;\n /** Messages, tool calls and handoffs in this run, in order. */\n newItems: RunItem[];\n usage: Usage;\n}\n\n/** run(..., { stream: true }): iterate events as they happen, then await completed. */\nexport interface StreamedRunResult<Output = string> extends AsyncIterable<RunStreamEvent> {\n /** Resolves with the result once the run ends (after you finish iterating, or on its own). */\n readonly completed: Promise<RunResult<Output>>;\n /** Only the text deltas. */\n toTextStream(): AsyncIterable<string>;\n}\n\nconst DEFAULT_MAX_TURNS = 10;\n\nfunction collectAgents(start: Agent<any>): Map<string, Agent<any>> {\n const seen = new Map<string, Agent<any>>();\n const visit = (agent: Agent<any>) => {\n if (seen.has(agent.name)) return;\n seen.set(agent.name, agent);\n agent.handoffs.forEach(visit);\n };\n visit(start);\n return seen;\n}\n\nfunction wireTools(agent: Agent<any>): Array<Record<string, unknown>> {\n const tools: Array<Record<string, unknown>> = agent.tools.map((t) => ({\n type: 'function',\n function: { name: t.name, description: t.description, parameters: t.parameters },\n // Only an unconditional approval is the server's to hold and record; a\n // conditional one is decided here, per call.\n ...(t.needsApproval === true ? { needsApproval: true } : {}),\n }));\n for (const target of agent.handoffs) {\n tools.push({\n type: 'function',\n function: {\n name: Agent.handoffToolName(target),\n description: target.handoffDescription\n ? `Hand the conversation to ${target.name}: ${target.handoffDescription}`\n : `Hand the conversation to the ${target.name} agent.`,\n parameters: { type: 'object', properties: {}, additionalProperties: false },\n },\n });\n }\n return tools;\n}\n\nfunction addUsage(total: Usage, usage: unknown): Usage {\n const u = (usage ?? {}) as { input_tokens?: number; output_tokens?: number; total_tokens?: number };\n return {\n inputTokens: total.inputTokens + (u.input_tokens ?? 0),\n outputTokens: total.outputTokens + (u.output_tokens ?? 0),\n totalTokens: total.totalTokens + (u.total_tokens ?? 0),\n };\n}\n\n/** The final text of a completed turn: the streamed deltas, else the output items. */\nfunction completedText(streamed: string, data: Record<string, unknown>): string {\n if (streamed) return streamed;\n const out = data.output as Record<string, unknown> | undefined;\n if (typeof out?.text === 'string') return out.text;\n let text = '';\n if (Array.isArray(out?.output)) {\n for (const item of out.output as Array<Record<string, unknown>>) {\n if (item.type !== 'message' || !Array.isArray(item.content)) continue;\n for (const c of item.content as Array<Record<string, unknown>>) {\n if (c.type === 'output_text' && typeof c.text === 'string') text += c.text;\n }\n }\n }\n return text;\n}\n\ntype TurnOutcome =\n | { kind: 'completed'; text: string; usage: unknown }\n | { kind: 'paused'; pause: PendingPause };\n\n/** Read one turn's stream: emit deltas and tool calls, end on pause or completion. */\nasync function* consumeTurn(response: Response, agentName: string, sessionId: string): AsyncGenerator<RunStreamEvent, TurnOutcome> {\n let text = '';\n for await (const { event, data } of readSessionEvents(response)) {\n switch (event) {\n case 'output_text.delta': {\n const delta = typeof data.delta === 'string' ? data.delta : '';\n if (delta) {\n text += delta;\n yield { type: 'text_delta', delta, agentName };\n }\n break;\n }\n case 'turn.paused': {\n const actions = Array.isArray(data.actions)\n ? (data.actions as PausedAction[])\n : [{ action_id: String(data.action_id), tool: String(data.tool), arguments: JSON.stringify((data.arguments as Record<string, unknown>)?.[String(data.tool)] ?? {}) }];\n return { kind: 'paused', pause: { actionId: String(data.action_id), actions, text } };\n }\n case 'turn.completed':\n return { kind: 'completed', text: completedText(text, data), usage: data.usage };\n case 'turn.failed': {\n const output = data.output as { error?: string } | undefined;\n throw new CencoriRunError(output?.error ?? 'The turn failed.', { code: 'turn_failed', sessionId });\n }\n case 'error': {\n const err = (data.error ?? data) as { message?: string; code?: string };\n throw new CencoriRunError(err.message ?? 'The turn failed.', { code: err.code, sessionId });\n }\n default:\n break;\n }\n }\n throw new CencoriRunError('The turn ended without a result.', { code: 'stream_ended', sessionId });\n}\n\nasync function* runLoop<Ctx>(\n startAgent: Agent<Ctx, any>,\n input: string | RunState,\n options: RunOptions<Ctx>,\n): AsyncGenerator<RunStreamEvent, RunResult<unknown>> {\n const transport = new Transport(options);\n const agents = collectAgents(startAgent);\n const maxTurns = options.maxTurns ?? DEFAULT_MAX_TURNS;\n const items: RunItem[] = [];\n\n const contextFor = (agent: Agent<any>, sessionId: string): RunContext<Ctx> => {\n const ctx: RunContext<Ctx> & { __runOptions?: RunOptions<Ctx> } = {\n context: options.context as Ctx,\n sessionId,\n agentName: agent.name,\n signal: options.signal,\n };\n Object.defineProperty(ctx, '__runOptions', { value: options, enumerable: false });\n return ctx;\n };\n\n const nextFor = async (agent: Agent<any>, sessionId: string): Promise<ResumeNext> => ({\n instructions: (await agent.resolveInstructions(contextFor(agent, sessionId))) ?? '',\n model: agent.model,\n tools: wireTools(agent),\n });\n\n let agent: Agent<any>;\n let sessionId: string;\n let turnsUsed: number;\n let usage: Usage;\n let response: Response | undefined;\n let pending: PendingPause | undefined;\n let resumedState: RunState | undefined;\n\n if (input instanceof RunState) {\n resumedState = input;\n const found = agents.get(input.agentName);\n if (!found) throw new AgentsError(`The run state belongs to agent \"${input.agentName}\", which isn't reachable from \"${startAgent.name}\".`);\n agent = found;\n sessionId = input.sessionId;\n turnsUsed = input.turnsUsed;\n usage = input.usage;\n pending = input.pending;\n } else {\n agent = startAgent;\n turnsUsed = 0;\n usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n // A new run's session is created together with its first turn (one round trip).\n sessionId = options.sessionId ?? '';\n\n // Input guardrails run on the first agent, before any model call.\n const runContext = contextFor(agent, sessionId);\n for (const guardrail of agent.inputGuardrails) {\n const verdict = await guardrail.execute({ input, agent, runContext });\n if (verdict.tripwireTriggered) throw new GuardrailTripwireTriggered('input', guardrail.name, verdict.outputInfo);\n }\n\n yield { type: 'agent_updated', agent };\n turnsUsed++;\n const firstTools = wireTools(agent);\n const firstTurn = {\n input,\n model: agent.model,\n instructions: await agent.resolveInstructions(runContext),\n tools: firstTools.length ? firstTools : undefined,\n ...(agent.outputType\n ? { response_format: { type: 'json_schema', json_schema: { name: 'final_output', schema: toJsonSchema(agent.outputType) } } }\n : {}),\n ...(agent.modelSettings.temperature !== undefined ? { temperature: agent.modelSettings.temperature } : {}),\n ...(agent.modelSettings.maxTokens !== undefined ? { max_output_tokens: agent.modelSettings.maxTokens } : {}),\n ...(agent.modelSettings.reasoningEffort ? { reasoning_effort: agent.modelSettings.reasoningEffort } : {}),\n ...(options.memory ? { memory: options.memory } : {}),\n ...(options.user ? { user: options.user } : {}),\n metadata: { sdk: 'cencori/agents', agent: agent.name },\n };\n if (sessionId) {\n response = await transport.turn(sessionId, firstTurn);\n } else {\n const created = await transport.createSessionWithTurn({\n ...(options.metadata ?? {}),\n sdk: 'cencori/agents',\n agent: startAgent.name,\n }, firstTurn);\n sessionId = created.sessionId;\n response = created.response;\n }\n }\n\n while (true) {\n if (response) {\n const outcome: TurnOutcome = yield* consumeTurn(response, agent.name, sessionId);\n response = undefined;\n if (outcome.kind === 'completed') {\n usage = addUsage(usage, outcome.usage);\n let finalOutput: unknown = outcome.text;\n if (agent.outputType) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(outcome.text);\n } catch {\n throw new CencoriRunError(`${agent.name} did not return valid JSON for its outputType.`, { code: 'invalid_output', sessionId });\n }\n finalOutput = await validate(agent.outputType, parsed, `${agent.name}'s output`);\n }\n items.push({ type: 'message', agentName: agent.name, text: outcome.text });\n const runContext = contextFor(agent, sessionId);\n for (const guardrail of agent.outputGuardrails) {\n const verdict = await guardrail.execute({ output: finalOutput, agent, runContext });\n if (verdict.tripwireTriggered) throw new GuardrailTripwireTriggered('output', guardrail.name, verdict.outputInfo);\n }\n return { finalOutput, sessionId, lastAgent: agent, interruptions: [], state: undefined, newItems: items, usage };\n }\n pending = outcome.pause;\n if (outcome.pause.text) items.push({ type: 'message', agentName: agent.name, text: outcome.pause.text });\n for (const action of outcome.pause.actions) {\n items.push({ type: 'tool_call', agentName: agent.name, callId: action.action_id, toolName: action.tool, arguments: action.arguments });\n yield { type: 'tool_call', callId: action.action_id, toolName: action.tool, arguments: action.arguments, agentName: agent.name };\n }\n }\n if (!pending) throw new AgentsError('Nothing to continue.');\n\n // Decide each paused call: run it, hand off, or wait for a human.\n const runContext = contextFor(agent, sessionId);\n const toolsByName = new Map<string, FunctionTool<any>>(agent.tools.map((t) => [t.name, t]));\n const handoffsByName = new Map<string, Agent<any>>(agent.handoffs.map((a) => [Agent.handoffToolName(a), a]));\n const interruptions: ToolApprovalItem[] = [];\n for (const action of pending.actions) {\n const t = toolsByName.get(action.tool);\n if (!t || resumedState?.decision(action.action_id)) continue;\n let needs = action.needs_approval === true || t.needsApproval === true;\n if (!needs && typeof t.needsApproval === 'function') {\n try {\n needs = await t.needsApproval(runContext, await t.parseArguments(action.arguments), action.action_id);\n } catch {\n needs = false; // invalid arguments: invoke reports the error to the model\n }\n }\n if (needs) {\n interruptions.push({ type: 'tool_approval', callId: action.action_id, toolName: action.tool, arguments: action.arguments, agentName: agent.name });\n }\n }\n if (interruptions.length > 0) {\n const state = new RunState({ sessionId, agentName: agent.name, turnsUsed, usage, pending });\n yield { type: 'interruption', interruptions };\n return { finalOutput: undefined, sessionId, lastAgent: agent, interruptions, state, newItems: items, usage };\n }\n\n if (turnsUsed >= maxTurns) throw new MaxTurnsExceededError(maxTurns, sessionId);\n\n let handoffTo: Agent<any> | undefined;\n const results = await Promise.all(pending.actions.map(async (action) => {\n const target = handoffsByName.get(action.tool);\n if (target) {\n if (handoffTo && handoffTo !== target) {\n return { action, output: `Not transferred: the conversation already went to ${handoffTo.name}.` };\n }\n handoffTo = target;\n return { action, output: `Transferred to ${target.name}. You are now ${target.name}; continue the conversation.` };\n }\n const decision = resumedState?.decision(action.action_id);\n if (decision && !decision.approved) {\n return { action, output: `The user rejected this call${decision.message ? `: ${decision.message}` : '.'} Don't retry it.` };\n }\n const t = toolsByName.get(action.tool);\n if (!t) return { action, output: `Error: there is no tool named ${action.tool}.` };\n return { action, output: await t.invoke(runContext, action.arguments, action.action_id) };\n }));\n for (const { action, output } of results) {\n if (handoffsByName.has(action.tool)) continue;\n items.push({ type: 'tool_output', agentName: agent.name, callId: action.action_id, toolName: action.tool, output });\n yield { type: 'tool_output', callId: action.action_id, toolName: action.tool, output, agentName: agent.name };\n }\n\n let next: ResumeNext | undefined;\n if (handoffTo) {\n const from = agent.name;\n agent = handoffTo;\n next = await nextFor(agent, sessionId);\n items.push({ type: 'handoff', from, to: agent.name });\n yield { type: 'handoff', from, to: agent.name };\n yield { type: 'agent_updated', agent };\n }\n\n turnsUsed++;\n resumedState = undefined;\n response = await transport.resume(\n sessionId,\n pending.actionId,\n results.map(({ action, output }) => ({ action_id: action.action_id, output })),\n next,\n );\n pending = undefined;\n }\n}\n\n/**\n * Run an agent until it answers, pausing tool calls run in your process.\n *\n * ```ts\n * const result = await run(support, 'Where is order 1042?');\n * result.finalOutput; // \"It shipped yesterday...\"\n * ```\n *\n * Pass `{ stream: true }` for events as they happen, `{ sessionId }` to\n * continue a conversation, or a RunState to resume after approvals.\n */\nexport function run<Ctx, Out>(agent: Agent<Ctx, Out>, input: string | RunState, options: RunOptions<Ctx> & { stream: true }): StreamedRunResult<Out>;\nexport function run<Ctx, Out>(agent: Agent<Ctx, Out>, input: string | RunState, options?: RunOptions<Ctx> & { stream?: false }): Promise<RunResult<Out>>;\nexport function run<Ctx, Out>(agent: Agent<Ctx, Out>, input: string | RunState, options: RunOptions<Ctx> = {}): Promise<RunResult<unknown>> | StreamedRunResult<unknown> {\n if (options.stream) return streamed(agent, input, options);\n return (async () => {\n const loop = runLoop(agent, input, options);\n while (true) {\n const step = await loop.next();\n if (step.done) return step.value;\n }\n })();\n}\n\nfunction streamed<Ctx>(agent: Agent<Ctx, any>, input: string | RunState, options: RunOptions<Ctx>): StreamedRunResult<unknown> {\n const loop = runLoop(agent, input, options);\n let resolve!: (r: RunResult<unknown>) => void;\n let reject!: (e: unknown) => void;\n const completed = new Promise<RunResult<unknown>>((res, rej) => { resolve = res; reject = rej; });\n // Callers that only await completed shouldn't see an unhandled rejection twice.\n completed.catch(() => {});\n let started = false;\n\n const events = async function* (): AsyncGenerator<RunStreamEvent> {\n if (started) throw new AgentsError('A streamed run can be iterated once.');\n started = true;\n try {\n while (true) {\n const step = await loop.next();\n if (step.done) {\n resolve(step.value);\n return;\n }\n yield step.value;\n }\n } catch (error) {\n reject(error);\n throw error;\n }\n };\n\n let iterator: AsyncGenerator<RunStreamEvent> | undefined;\n return {\n [Symbol.asyncIterator]() {\n iterator ??= events();\n return iterator;\n },\n get completed() {\n // Awaiting completed without iterating drains the run.\n if (!started) {\n void (async () => {\n try {\n for await (const _event of this) { /* drain */ }\n } catch {\n /* surfaced through completed */\n }\n })();\n }\n return completed;\n },\n async *toTextStream() {\n for await (const event of this) {\n if (event.type === 'text_delta') yield event.delta;\n }\n },\n };\n}\n","import type { RunContext } from './context';\nimport type { SchemaLike, StandardSchemaV1 } from './schema';\nimport { tool, TOOL_NAME_PATTERN, type FunctionTool } from './tool';\nimport type { RunOptions } from './run';\n\n/** Checks the user's input before the first model call. */\nexport interface InputGuardrail<Ctx = unknown> {\n name: string;\n execute: (args: { input: string; agent: Agent<Ctx, any>; runContext: RunContext<Ctx> }) =>\n GuardrailResult | Promise<GuardrailResult>;\n}\n\n/** Checks the final answer before the run returns it. */\nexport interface OutputGuardrail<Ctx = unknown> {\n name: string;\n execute: (args: { output: unknown; agent: Agent<Ctx, any>; runContext: RunContext<Ctx> }) =>\n GuardrailResult | Promise<GuardrailResult>;\n}\n\nexport interface GuardrailResult {\n /** true stops the run with a GuardrailTripwireTriggered error. */\n tripwireTriggered: boolean;\n /** Anything you want back on the error. */\n outputInfo?: unknown;\n}\n\nexport interface ModelSettings {\n temperature?: number;\n maxTokens?: number;\n /**\n * How hard a reasoning model thinks before answering. Lower is faster;\n * 'none' skips thinking where the model allows it. Default: the model's own.\n */\n reasoningEffort?: 'none' | 'low' | 'medium' | 'high';\n}\n\nexport interface AgentOptions<Ctx = unknown, Out = string> {\n /** Shown in traces, and used for handoff tool names (transfer_to_<name>). */\n name: string;\n /** System prompt. A function gets the run context, for per-user instructions. */\n instructions?: string | ((runContext: RunContext<Ctx>) => string | Promise<string>);\n /**\n * Any model in the Cencori catalog: 'claude-sonnet-4-5', 'gemini-2.5-flash'...\n * Default: DEFAULT_MODEL, GPT OSS 120B on Cerebras (fast, calls tools).\n */\n model?: string;\n tools?: FunctionTool<Ctx>[];\n /** Agents this one can hand the conversation to. */\n handoffs?: Agent<Ctx, any>[];\n /** Tells other agents when to hand off to this one. */\n handoffDescription?: string;\n /** Structured final output: a zod (or Standard Schema) object, or a JSON Schema. */\n outputType?: StandardSchemaV1<unknown, Out> | Record<string, unknown>;\n modelSettings?: ModelSettings;\n inputGuardrails?: InputGuardrail<Ctx>[];\n outputGuardrails?: OutputGuardrail<Ctx>[];\n}\n\n/** The model an agent uses when none is given: GPT OSS 120B on Cerebras, chosen for speed. */\nexport const DEFAULT_MODEL = 'gpt-oss-120b';\n\nfunction toolSafe(name: string): string {\n const safe = name.toLowerCase().replace(/[^a-z0-9_-]+/g, '_').replace(/^_+|_+$/g, '');\n return safe || 'agent';\n}\n\n/**\n * An agent: a model, instructions and tools. It holds no state; run() drives\n * it in a Cencori session.\n *\n * ```ts\n * const support = new Agent({\n * name: 'Support',\n * instructions: 'Answer order questions. Be brief.',\n * model: 'claude-sonnet-4-5',\n * tools: [getOrder],\n * });\n * ```\n */\nexport class Agent<Ctx = unknown, Out = string> {\n readonly name: string;\n readonly instructions: AgentOptions<Ctx, Out>['instructions'];\n readonly model: string;\n readonly tools: FunctionTool<Ctx>[];\n readonly handoffs: Agent<Ctx, any>[];\n readonly handoffDescription?: string;\n readonly outputType?: SchemaLike;\n readonly modelSettings: ModelSettings;\n readonly inputGuardrails: InputGuardrail<Ctx>[];\n readonly outputGuardrails: OutputGuardrail<Ctx>[];\n\n constructor(options: AgentOptions<Ctx, Out>) {\n if (!options.name?.trim()) throw new TypeError('An agent needs a name.');\n if (options.model !== undefined && !options.model.trim()) throw new TypeError(`Agent \"${options.name}\" needs a model.`);\n this.name = options.name;\n this.instructions = options.instructions;\n this.model = options.model ?? DEFAULT_MODEL;\n this.tools = options.tools ?? [];\n this.handoffs = options.handoffs ?? [];\n this.handoffDescription = options.handoffDescription;\n this.outputType = options.outputType;\n this.modelSettings = options.modelSettings ?? {};\n this.inputGuardrails = options.inputGuardrails ?? [];\n this.outputGuardrails = options.outputGuardrails ?? [];\n\n const names = new Set<string>();\n for (const t of [...this.tools.map((t) => t.name), ...this.handoffs.map((a) => Agent.handoffToolName(a))]) {\n if (names.has(t)) throw new TypeError(`Agent \"${this.name}\" has two tools named \"${t}\".`);\n names.add(t);\n }\n }\n\n /** A copy with some options changed. */\n clone(overrides: Partial<AgentOptions<Ctx, Out>>): Agent<Ctx, Out> {\n return new Agent<Ctx, Out>({\n name: this.name,\n instructions: this.instructions,\n model: this.model,\n tools: this.tools,\n handoffs: this.handoffs,\n handoffDescription: this.handoffDescription,\n outputType: this.outputType as AgentOptions<Ctx, Out>['outputType'],\n modelSettings: this.modelSettings,\n inputGuardrails: this.inputGuardrails,\n outputGuardrails: this.outputGuardrails,\n ...overrides,\n });\n }\n\n /** The tool name a handoff to this agent goes by. */\n static handoffToolName(agent: Agent<any>): string {\n const name = `transfer_to_${toolSafe(agent.name)}`.slice(0, 64);\n if (!TOOL_NAME_PATTERN.test(name)) throw new TypeError(`Can't make a handoff tool name for \"${agent.name}\".`);\n return name;\n }\n\n /** Instructions for this run, resolving a function if given. */\n async resolveInstructions(runContext: RunContext<Ctx>): Promise<string | undefined> {\n if (typeof this.instructions === 'function') return this.instructions(runContext);\n return this.instructions;\n }\n\n /**\n * Use this agent as a tool of another: it runs on its own (in its own\n * session) and returns its final answer, while the calling agent keeps the\n * conversation. Compare handoffs, where this agent would take it over.\n */\n asTool(options: { toolName?: string; toolDescription?: string; runOptions?: Pick<RunOptions<Ctx>, 'maxTurns' | 'apiKey' | 'baseUrl'> } = {}): FunctionTool<Ctx> {\n const agent = this;\n return tool({\n name: options.toolName ?? toolSafe(this.name).slice(0, 64),\n description: options.toolDescription ?? this.handoffDescription ?? `Ask the ${this.name} agent.`,\n parameters: {\n type: 'object',\n properties: { input: { type: 'string', description: `What to ask ${this.name}.` } },\n required: ['input'],\n additionalProperties: false,\n },\n async execute(args, runContext) {\n const { run } = await import('./run');\n const { input } = args as { input: string };\n const inherited = (runContext as RunContext<Ctx> & { __runOptions?: RunOptions<Ctx> }).__runOptions;\n const result = await run(agent, input, {\n // Same transport as the calling run: key, endpoint and any custom fetch.\n apiKey: inherited?.apiKey,\n baseUrl: inherited?.baseUrl,\n fetch: inherited?.fetch,\n user: inherited?.user,\n ...options.runOptions,\n context: runContext.context,\n signal: runContext.signal,\n metadata: { parent_session_id: runContext.sessionId, ...(inherited?.metadata ?? {}) },\n });\n return result.finalOutput;\n },\n });\n }\n}\n","/**\n * cencori/agents: build agents in code, run them on Cencori.\n *\n * Your tools run in your process; the agent loop, sessions, approvals,\n * memory, guardrails, billing and traces run on Cencori, with any model in\n * the catalog.\n */\nexport { Agent, DEFAULT_MODEL } from './agent';\nexport type { AgentOptions, InputGuardrail, OutputGuardrail, GuardrailResult, ModelSettings } from './agent';\nexport { tool } from './tool';\nexport type { FunctionTool, ToolOptions, NeedsApproval } from './tool';\nexport { run, RunState } from './run';\nexport type { RunOptions, RunResult, StreamedRunResult, RunStreamEvent, RunItem, ToolApprovalItem, Usage } from './run';\nexport type { RunContext } from './context';\nexport { AgentsError, CencoriRunError, GuardrailTripwireTriggered, MaxTurnsExceededError } from './errors';\nexport { SchemaValidationError } from './schema';\nexport type { SchemaLike, StandardSchemaV1, JsonSchema } from './schema';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAS,WAAW,QAA6C;AAC7D,SAAO,OAAO,WAAW,YAAY,WAAW,QAAQ,eAAe,UAChE,OAAQ,OAA4B,WAAW,GAAG,aAAa;AAC1E;AAGO,SAAS,aAAa,QAA4C;AACrE,MAAI,CAAC,OAAQ,QAAO,EAAE,MAAM,UAAU,YAAY,CAAC,GAAG,sBAAsB,MAAM;AAClF,MAAI;AACJ,MAAI,WAAW,MAAM,GAAG;AACpB,UAAM,MAAM,OAAO,WAAW;AAC9B,QAAI,IAAI,YAAY;AAChB,aAAO,IAAI,WAAW,MAAM,EAAE,QAAQ,gBAAgB,CAAC;AAAA,IAC3D,WAAW,OAAQ,OAAsC,iBAAiB,YAAY;AAClF,aAAQ,OAAyD,aAAa;AAAA,IAClF,WAAW,IAAI,WAAW,SAAU,OAA6C,MAAM,UAAU;AAC7F,aAAO,iBAAiB,MAAyB;AAAA,IACrD,OAAO;AACH,YAAM,IAAI;AAAA,QACN,QAAQ,IAAI,MAAM;AAAA,MACtB;AAAA,IACJ;AAAA,EACJ,OAAO;AACH,WAAO;AAAA,EACX;AAEA,QAAM,EAAE,SAAS,UAAU,GAAG,KAAK,IAAI;AACvC,SAAO;AACX;AAYA,eAAsB,SAAY,QAAmC,OAAgB,MAA0B;AAC3G,MAAI,CAAC,UAAU,CAAC,WAAW,MAAM,EAAG,QAAO;AAC3C,QAAM,SAAS,MAAM,OAAO,WAAW,EAAE,SAAS,KAAK;AACvD,MAAI,OAAO,Q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