@standardagents/builder 0.10.1-next.bbd142a → 0.11.0-next.99fb790

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.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export { AgentPluginOptions, agentbuilder } from './plugin.js';
2
2
  import { DurableObjectStorage } from '@cloudflare/workers-types';
3
- import { z, ZodString, ZodNumber, ZodBoolean, ZodNull, ZodLiteral, ZodEnum, ZodOptional, ZodNullable, ZodDefault, ZodArray, ZodObject, ZodRecord, ZodUnion } from 'zod';
3
+ import { ZodObject, ZodRawShape } from 'zod';
4
+ import { ToolResult as ToolResult$1, HookSignatures, ControllerContext, Controller, ModelDefinition as ModelDefinition$1, ToolArgs, PromptTextPart, SubpromptConfig as SubpromptConfig$2, ReasoningConfig, SideConfig as SideConfig$1 } from '@standardagents/spec';
5
+ export { AgentType, HookSignatures, ImageContent, ModelCapabilities, ModelProvider, PromptInput, PromptTextPart, ReasoningConfig, StructuredPrompt, TextContent, Tool, ToolArgs, ToolArgsNode, ToolArgsRawShape, ToolContent, defineAgent, defineHook, defineModel, definePrompt, defineThreadEndpoint, defineTool } from '@standardagents/spec';
4
6
  import { DurableObject } from 'cloudflare:workers';
5
7
  import 'vite';
6
8
 
@@ -144,122 +146,6 @@ declare class StreamManager {
144
146
  forceClose(): void;
145
147
  }
146
148
 
147
- /**
148
- * Content item types that can be returned by tools
149
- */
150
- interface TextContent {
151
- type: "text";
152
- text: string;
153
- }
154
- interface ImageContent {
155
- type: "image";
156
- data: string;
157
- mimeType: string;
158
- }
159
- type ToolContent = TextContent | ImageContent;
160
- /** Decrement helper to stop recursion at depth 0 */
161
- type Dec<N extends number> = N extends 10 ? 9 : N extends 9 ? 8 : N extends 8 ? 7 : N extends 7 ? 6 : N extends 6 ? 5 : N extends 5 ? 4 : N extends 4 ? 3 : N extends 3 ? 2 : N extends 2 ? 1 : N extends 1 ? 0 : 0;
162
- /**
163
- * Allowed Zod node for tool arguments.
164
- * Tweak this union as your single source of truth for what’s allowed.
165
- * Increase the default depth if you need crazier nesting.
166
- */
167
- type ToolArgsNode<D extends number = 7> = ZodString | ZodNumber | ZodBoolean | ZodNull | ZodLiteral<string | number | boolean | null> | ZodEnum<Record<string, string>> | (D extends 0 ? never : ZodOptional<ToolArgsNode<Dec<D>>>) | (D extends 0 ? never : ZodNullable<ToolArgsNode<Dec<D>>>) | (D extends 0 ? never : ZodDefault<ToolArgsNode<Dec<D>>>) | (D extends 0 ? never : ZodArray<ToolArgsNode<Dec<D>>>) | (D extends 0 ? never : ZodObject<Record<string, ToolArgsNode<Dec<D>>>>) | (D extends 0 ? never : ZodRecord<ZodString, ToolArgsNode<Dec<D>>>) | (D extends 0 ? never : ZodUnion<[
168
- ToolArgsNode<Dec<D>>,
169
- ToolArgsNode<Dec<D>>,
170
- ...ToolArgsNode<Dec<D>>[]
171
- ]>);
172
- /**
173
- * Raw shape for an object whose values are ToolArgsNode.
174
- * This is what users write inside z.object({ ... }).
175
- */
176
- type ToolArgsRawShape<D extends number = 7> = Record<string, ToolArgsNode<D>>;
177
- /** The top-level schema must be an object for OpenAI tools. */
178
- type ToolArgs<D extends number = 7> = z.ZodObject<ToolArgsRawShape<D>>;
179
- type StructuredToolReturn = ToolArgs;
180
- /**
181
- * Defines a tool function. Tools accept the current flow state as well as the arguments being passed to them.
182
- */
183
- type Tool<Args extends ToolArgs | null = null> = Args extends ToolArgs ? (flow: FlowState, args: z.infer<Args>) => Promise<ToolResult> : (flow: FlowState) => Promise<ToolResult>;
184
- /**
185
- * @param toolDescription - Description of what the tool does.
186
- * @param args - The arguments for the tool.
187
- * @param tool - The tool function.
188
- * @returns A tuple containing the description, arguments and the tool function.
189
- */
190
- declare function defineTool<Args extends ToolArgs>(toolDescription: string, args: Args, tool: Tool<Args>): [string, Args, Tool<Args>, null];
191
- declare function defineTool(toolDescription: string, tool: Tool<null>): [string, null, Tool<null>, null];
192
- declare function defineTool<Args extends ToolArgs, RetValue extends StructuredToolReturn>(toolDescription: string, args: Args, tool: Tool<Args>, returnSchema: RetValue): [string, Args, Tool<Args>, RetValue];
193
-
194
- /**
195
- * Hook signatures for all available hooks
196
- */
197
- interface HookSignatures {
198
- /**
199
- * Called before messages are filtered and sent to the LLM
200
- * Receives SQL row data with all columns before transformation
201
- * Return value is transformed into chat completion format
202
- */
203
- filter_messages: (state: FlowState, rows: Message[]) => Promise<Message[]>;
204
- /**
205
- * Called after message history is loaded and before sending to LLM
206
- * Receives messages in chat completion format (already transformed)
207
- */
208
- prefilter_llm_history: (state: FlowState, messages: Array<{
209
- role: string;
210
- content: string | null;
211
- tool_calls?: any;
212
- tool_call_id?: string;
213
- name?: string;
214
- }>) => Promise<Array<{
215
- role: string;
216
- content: string | null;
217
- tool_calls?: any;
218
- tool_call_id?: string;
219
- name?: string;
220
- }>>;
221
- /**
222
- * Called before a message is created in the database
223
- */
224
- before_create_message: (state: FlowState, message: Record<string, any>) => Promise<Record<string, any>>;
225
- /**
226
- * Called after a message is created in the database
227
- */
228
- after_create_message: (state: FlowState, message: Record<string, any>) => Promise<void>;
229
- /**
230
- * Called before a message is updated in the database
231
- */
232
- before_update_message: (state: FlowState, messageId: string, updates: Record<string, any>) => Promise<Record<string, any>>;
233
- /**
234
- * Called after a message is updated in the database
235
- */
236
- after_update_message: (state: FlowState, message: Message) => Promise<void>;
237
- /**
238
- * Called before a tool result is stored in the database
239
- */
240
- before_store_tool_result: (state: FlowState, toolCall: Record<string, any>, toolResult: Record<string, any>) => Promise<Record<string, any>>;
241
- /**
242
- * Called after a successful tool call
243
- */
244
- after_tool_call_success: (state: FlowState, toolCall: ToolCall, toolResult: ToolResult) => Promise<ToolResult | null>;
245
- /**
246
- * Called after a failed tool call
247
- */
248
- after_tool_call_failure: (state: FlowState, toolCall: ToolCall, toolResult: ToolResult) => Promise<ToolResult | null>;
249
- }
250
- /**
251
- * Define a hook with strict typing based on hook name
252
- *
253
- * @example
254
- * ```typescript
255
- * export default defineHook('filter_messages', async (state, rows) => {
256
- * // Only include messages from last 10 turns
257
- * return rows.slice(-10);
258
- * });
259
- * ```
260
- */
261
- declare function defineHook<K extends keyof HookSignatures>(hookName: K, implementation: HookSignatures[K]): HookSignatures[K];
262
-
263
149
  /**
264
150
  * Agent configuration from D1 agents table
265
151
  */
@@ -274,15 +160,15 @@ interface Agent {
274
160
  side_a_stop_on_response: boolean;
275
161
  side_a_stop_tool: string | null;
276
162
  side_a_stop_tool_response_property: string | null;
277
- side_a_max_turns: number | null;
278
- side_a_end_conversation_tool: string | null;
163
+ side_a_max_steps: number | null;
164
+ side_a_end_session_tool: string | null;
279
165
  side_b_label: string | null;
280
166
  side_b_agent_prompt: string | null;
281
167
  side_b_stop_on_response: boolean;
282
168
  side_b_stop_tool: string | null;
283
169
  side_b_stop_tool_response_property: string | null;
284
- side_b_max_turns: number | null;
285
- side_b_end_conversation_tool: string | null;
170
+ side_b_max_steps: number | null;
171
+ side_b_end_session_tool: string | null;
286
172
  }
287
173
  /**
288
174
  * Message in OpenAI chat completion format
@@ -335,6 +221,12 @@ interface ThreadMetadata {
335
221
  type HookRegistry = {
336
222
  [K in keyof HookSignatures]?: () => Promise<HookSignatures[K]>;
337
223
  };
224
+ /**
225
+ * Native tool module type - represents a loaded tool definition.
226
+ * Tools can have args (with validation schema) or no args.
227
+ * Uses local Zod types for compatibility with z.toJSONSchema().
228
+ */
229
+ type NativeToolModule = [description: string, argsSchema: ZodObject<ZodRawShape>, toolFn: (state: any, args: Record<string, unknown>) => Promise<ToolResult$1>] | [description: string, argsSchema: null, toolFn: (state: any) => Promise<ToolResult$1>];
338
230
  /**
339
231
  * Thread instance (forward reference to avoid circular dependency)
340
232
  */
@@ -349,13 +241,38 @@ interface ThreadInstance {
349
241
  getLogs(limit?: number, offset?: number, order?: "asc" | "desc"): Promise<LogData[]>;
350
242
  getThreadMeta(threadId: string): Promise<ThreadMetadata | null>;
351
243
  shouldStop(): Promise<boolean>;
352
- tools(): Record<string, () => Promise<ReturnType<typeof defineTool>>>;
244
+ tools(): Record<string, () => Promise<NativeToolModule>>;
353
245
  hooks(): HookRegistry;
354
246
  loadModel(name: string): Promise<any>;
355
247
  loadPrompt(name: string): Promise<any>;
356
248
  loadAgent(name: string): Promise<any>;
357
249
  getPromptNames(): string[];
358
250
  getAgentNames(): string[];
251
+ writeFile(path: string, data: ArrayBuffer | string, mimeType: string, options?: Record<string, unknown>): Promise<any>;
252
+ readFile(path: string): Promise<ArrayBuffer | null>;
253
+ statFile(path: string): Promise<any>;
254
+ readdirFile(path: string): Promise<any[]>;
255
+ unlinkFile(path: string): Promise<void>;
256
+ mkdirFile(path: string): Promise<any>;
257
+ rmdirFile(path: string): Promise<void>;
258
+ getFileStats(): Promise<any>;
259
+ grepFiles(pattern: string): Promise<any[]>;
260
+ findFiles(pattern: string): Promise<any>;
261
+ getFileThumbnail(path: string): Promise<ArrayBuffer | null>;
262
+ readFileChunk(path: string, chunkIndex: number): Promise<{
263
+ success: boolean;
264
+ data?: string;
265
+ error?: string;
266
+ }>;
267
+ scheduleEffect(threadId: string, effectName: string, effectArgs: Record<string, unknown>, delayMs?: number): Promise<string>;
268
+ getScheduledEffects(name?: string): Promise<Array<{
269
+ id: string;
270
+ name: string;
271
+ args: Record<string, unknown>;
272
+ scheduledAt: number;
273
+ createdAt: number;
274
+ }>>;
275
+ removeScheduledEffect(id: string): Promise<boolean>;
359
276
  insertOrphanedToolCall(params: {
360
277
  content?: string;
361
278
  toolCallId: string;
@@ -389,9 +306,9 @@ type FlowCallWithRetries = FlowCall & {
389
306
  reasons: string[];
390
307
  };
391
308
  /**
392
- * Tool configuration for a prompt - defines options for when a tool is used
309
+ * Sub-prompt configuration - defines options for when a sub-prompt is called as a tool
393
310
  */
394
- interface ToolConfig$1 {
311
+ interface SubpromptConfig$1 {
395
312
  name: string;
396
313
  initUserMessageProperty?: string;
397
314
  includeTextResponse?: boolean;
@@ -412,8 +329,6 @@ interface PromptData {
412
329
  required_schema: string;
413
330
  include_chat: boolean;
414
331
  include_past_tools: boolean;
415
- before_tool: string | null;
416
- after_tool: string | null;
417
332
  prompts: string;
418
333
  created_at: number;
419
334
  /** @deprecated All prompts are now automatically exposed as tools */
@@ -424,10 +339,8 @@ interface PromptData {
424
339
  reasoning_max_tokens: number | null;
425
340
  reasoning_exclude: boolean;
426
341
  include_reasoning: boolean;
427
- maxImagePixels: number | null;
428
342
  recentImageThreshold: number | null;
429
- _tools?: (string | ToolConfig$1)[];
430
- _handoffAgents?: string[];
343
+ _tools?: (string | SubpromptConfig$1)[];
431
344
  _requiredSchema?: any;
432
345
  }
433
346
  /**
@@ -447,9 +360,9 @@ interface FlowState {
447
360
  sideB: PromptData | null;
448
361
  };
449
362
  prompt: PromptData;
450
- turnCount: number;
451
- sideATurnCount: number;
452
- sideBTurnCount: number;
363
+ stepCount: number;
364
+ sideAStepCount: number;
365
+ sideBStepCount: number;
453
366
  stopped: boolean;
454
367
  stoppedBy?: "a" | "b";
455
368
  forcedNextSide?: "side_a" | "side_b";
@@ -556,6 +469,16 @@ interface ToolDefinition {
556
469
  parameters?: Record<string, any>;
557
470
  };
558
471
  }
472
+ /**
473
+ * Image returned by an LLM response (e.g., from image generation models)
474
+ * Format follows OpenAI/OpenRouter chat completions API
475
+ */
476
+ interface LLMResponseImage {
477
+ type: "image_url";
478
+ image_url: {
479
+ url: string;
480
+ };
481
+ }
559
482
  /**
560
483
  * LLM response
561
484
  */
@@ -566,6 +489,7 @@ interface LLMResponse {
566
489
  reasoning_content?: string | null;
567
490
  reasoning_details?: any[];
568
491
  tool_calls?: ToolCall[];
492
+ images?: LLMResponseImage[];
569
493
  finish_reason: string;
570
494
  usage: {
571
495
  prompt_tokens: number;
@@ -581,6 +505,17 @@ interface LLMResponse {
581
505
  provider?: string;
582
506
  };
583
507
  }
508
+ /**
509
+ * Attachment returned by a tool (e.g., generated images)
510
+ * Stored in thread filesystem and linked to the tool message
511
+ */
512
+ interface ToolAttachment {
513
+ name: string;
514
+ mimeType: string;
515
+ data: string;
516
+ width?: number;
517
+ height?: number;
518
+ }
584
519
  /**
585
520
  * Tool result
586
521
  */
@@ -597,6 +532,16 @@ interface ToolResult {
597
532
  result?: string;
598
533
  error?: string;
599
534
  stack?: string;
535
+ /**
536
+ * File attachments returned by the tool.
537
+ *
538
+ * Can contain either:
539
+ * - ToolAttachment: New files with base64 data to be stored
540
+ * - AttachmentRef: References to existing files in the thread filesystem
541
+ *
542
+ * New attachments are stored under /attachments/ directory.
543
+ */
544
+ attachments?: Array<ToolAttachment | AttachmentRef>;
600
545
  }
601
546
  /**
602
547
  * Flow execution result
@@ -605,20 +550,20 @@ interface FlowResult {
605
550
  messages: Message[];
606
551
  stopped: boolean;
607
552
  stoppedBy?: "a" | "b";
608
- turnCount: number;
553
+ stepCount: number;
609
554
  stream: ReadableStream<Uint8Array>;
610
555
  }
611
556
  /**
612
557
  * Telemetry event types
613
558
  */
614
559
  type TelemetryEvent = {
615
- type: "turn_started";
616
- turn: number;
560
+ type: "step_started";
561
+ step: number;
617
562
  side: "a" | "b";
618
563
  timestamp: number;
619
564
  } | {
620
- type: "turn_completed";
621
- turn: number;
565
+ type: "step_completed";
566
+ step: number;
622
567
  stopped: boolean;
623
568
  timestamp: number;
624
569
  } | {
@@ -739,6 +684,10 @@ interface FileRecord {
739
684
  metadata?: Record<string, unknown> | null;
740
685
  isDirectory: boolean;
741
686
  createdAt: number;
687
+ width?: number | null;
688
+ height?: number | null;
689
+ isChunked?: boolean;
690
+ chunkCount?: number;
742
691
  }
743
692
  /**
744
693
  * Image-specific metadata stored in FileRecord.metadata
@@ -777,43 +726,178 @@ interface FileStats {
777
726
  fileCount: number;
778
727
  }
779
728
 
729
+ /**
730
+ * Router and endpoint definition module for AgentBuilder.
731
+ *
732
+ * This module re-exports endpoint types from @standardagents/spec and provides
733
+ * the runtime router implementation for handling HTTP requests.
734
+ *
735
+ * @module
736
+ */
737
+
738
+ /**
739
+ * Durable Object namespace interface.
740
+ * This is Cloudflare-specific and used by the builder runtime.
741
+ */
742
+ interface DurableObjectNamespace$1<T = unknown> {
743
+ idFromName(name: string): DurableObjectId;
744
+ idFromString(id: string): DurableObjectId;
745
+ newUniqueId(): DurableObjectId;
746
+ get(id: DurableObjectId): DurableObjectStub$1<T>;
747
+ }
748
+ /**
749
+ * Durable Object ID interface.
750
+ */
751
+ interface DurableObjectId {
752
+ toString(): string;
753
+ equals(other: DurableObjectId): boolean;
754
+ }
755
+ /**
756
+ * Durable Object stub interface.
757
+ * The generic type T represents the RPC methods available on the stub.
758
+ */
759
+ type DurableObjectStub$1<T = unknown> = {
760
+ id: DurableObjectId;
761
+ name?: string;
762
+ fetch(request: Request | string, requestInitr?: RequestInit): Promise<Response>;
763
+ } & T;
764
+ /**
765
+ * Log entry from DurableThread.getLogs()
766
+ */
767
+ interface LogEntry {
768
+ id: string;
769
+ message_id: string;
770
+ provider: string;
771
+ model: string;
772
+ model_name: string | null;
773
+ prompt_name: string | null;
774
+ tools_called: string | null;
775
+ parent_log_id: string | null;
776
+ retry_of_log_id: string | null;
777
+ error: string | null;
778
+ cost_total: number | null;
779
+ is_complete: number;
780
+ created_at: number;
781
+ request_body: string | null;
782
+ }
783
+ /**
784
+ * Agent definition returned from loadAgent()
785
+ */
786
+ interface AgentDefinition$1 {
787
+ name: string;
788
+ title?: string;
789
+ type?: string;
790
+ description?: string;
791
+ icon?: string;
792
+ defaultPrompt?: string;
793
+ defaultModel?: string;
794
+ tools?: string[];
795
+ [key: string]: unknown;
796
+ }
797
+ /**
798
+ * Response from getThreadMeta()
799
+ */
800
+ interface ThreadMetaResponse {
801
+ thread: ThreadRegistryEntry$1;
802
+ agent: AgentDefinition$1 | null;
803
+ stats: {
804
+ messageCount: number;
805
+ logCount: number;
806
+ lastActivity: number | null;
807
+ };
808
+ }
809
+ /**
810
+ * RPC methods exposed by DurableThread for external callers.
811
+ */
812
+ interface DurableThreadRpc {
813
+ stop(): Promise<Response>;
814
+ getMessages(limit?: number, offset?: number, order?: "ASC" | "DESC", includeSilent?: boolean, maxDepth?: number): Promise<{
815
+ messages: unknown[];
816
+ total: number;
817
+ hasMore: boolean;
818
+ }>;
819
+ deleteMessage(messageId: string): Promise<{
820
+ success: boolean;
821
+ error?: string;
822
+ }>;
823
+ updateMessageContent(messageId: string, content: string): Promise<{
824
+ success: boolean;
825
+ error?: string;
826
+ }>;
827
+ getLogs(limit?: number, offset?: number, order?: "ASC" | "DESC"): Promise<{
828
+ logs: LogEntry[];
829
+ total: number;
830
+ hasMore: boolean;
831
+ }>;
832
+ getLogDetails(logId: string): Promise<unknown>;
833
+ getThreadMeta(threadId: string): Promise<ThreadMetaResponse | null>;
834
+ deleteThread(): Promise<void>;
835
+ }
836
+ /**
837
+ * Thread registry entry from DurableAgentBuilder.
838
+ */
839
+ interface ThreadRegistryEntry$1 {
840
+ id: string;
841
+ agent_name: string;
842
+ user_id: string | null;
843
+ tags: string[] | null;
844
+ created_at: number;
845
+ }
846
+ /**
847
+ * RPC methods exposed by DurableAgentBuilder for external callers.
848
+ */
849
+ interface DurableAgentBuilderRpc {
850
+ createThread(params: {
851
+ agent_name: string;
852
+ user_id?: string;
853
+ tags?: string[];
854
+ }): Promise<ThreadRegistryEntry$1>;
855
+ getThread(threadId: string): Promise<ThreadRegistryEntry$1 | null>;
856
+ listThreads(params?: {
857
+ agent_name?: string;
858
+ user_id?: string;
859
+ limit?: number;
860
+ offset?: number;
861
+ }): Promise<{
862
+ threads: ThreadRegistryEntry$1[];
863
+ total: number;
864
+ }>;
865
+ deleteThread(threadId: string): Promise<void>;
866
+ getUserByUsername(username: string): Promise<unknown>;
867
+ createSession(session: {
868
+ user_id: string;
869
+ token_hash: string;
870
+ expires_at: number;
871
+ }): Promise<void>;
872
+ loadAgent(name: string): Promise<AgentDefinition$1>;
873
+ }
780
874
  /**
781
875
  * Minimum required environment bindings for thread endpoints.
782
876
  * User's Env interface should extend this.
783
877
  *
784
- * Uses Rpc.DurableObjectBranded to allow users to specify their own
785
- * Durable Object types that extend DurableThread/DurableAgentBuilder.
878
+ * This is Cloudflare-specific and used by the builder runtime.
786
879
  */
787
880
  interface ThreadEnv {
788
- AGENT_BUILDER_THREAD: DurableObjectNamespace<Rpc.DurableObjectBranded>;
789
- AGENT_BUILDER: DurableObjectNamespace<Rpc.DurableObjectBranded>;
881
+ AGENT_BUILDER_THREAD: DurableObjectNamespace$1<DurableThreadRpc>;
882
+ AGENT_BUILDER: DurableObjectNamespace$1<DurableAgentBuilderRpc>;
790
883
  [key: string]: unknown;
791
884
  }
792
885
  /**
793
- * Virtual module registry types (injected at runtime by plugin)
886
+ * Builder-specific controller context with typed env.
887
+ *
888
+ * This extends the spec's ControllerContext with proper typing for
889
+ * Cloudflare environment bindings.
794
890
  */
795
- type VirtualModuleLoader<T> = () => Promise<T>;
796
- type VirtualModuleRegistry<T> = Record<string, VirtualModuleLoader<T>>;
891
+ interface BuilderControllerContext<Env extends ThreadEnv = ThreadEnv> extends Omit<ControllerContext, 'env'> {
892
+ env: Env;
893
+ }
797
894
  /**
798
- * Controller context passed to route handlers.
799
- * Includes optional virtual module registries that are injected at runtime.
895
+ * Builder-specific controller type with typed env.
896
+ */
897
+ type BuilderController<Env extends ThreadEnv = ThreadEnv> = (context: BuilderControllerContext<Env>) => ReturnType<Controller>;
898
+ /**
899
+ * Thread endpoint context with access to thread instance and metadata.
800
900
  */
801
- interface ControllerContext<Env = any> {
802
- req: Request;
803
- params: Record<string, string>;
804
- env: Env;
805
- url: URL;
806
- agents?: VirtualModuleRegistry<unknown>;
807
- agentNames?: string[];
808
- prompts?: VirtualModuleRegistry<unknown>;
809
- promptNames?: string[];
810
- models?: VirtualModuleRegistry<unknown>;
811
- modelNames?: string[];
812
- tools?: VirtualModuleRegistry<unknown>;
813
- hooks?: VirtualModuleRegistry<unknown>;
814
- config?: Record<string, unknown>;
815
- }
816
- type Controller<Env = any> = (context: ControllerContext<Env>) => string | Promise<string> | Response | Promise<Response> | ReadableStream | Promise<ReadableStream> | null | Promise<null> | void | Promise<void> | Promise<object> | object;
817
901
  interface ThreadEndpointContext {
818
902
  req: Request;
819
903
  thread: {
@@ -821,22 +905,24 @@ interface ThreadEndpointContext {
821
905
  metadata: ThreadMetadata;
822
906
  };
823
907
  }
824
- declare function defineController<Env = any>(controller: Controller<Env>): Controller<Env>;
908
+
825
909
  /**
826
- * Define a thread-specific endpoint that has access to the thread's DurableObject instance and metadata.
827
- * This wraps defineController and automatically looks up the thread by ID from the URL params.
910
+ * Define a controller with typed Cloudflare environment bindings.
828
911
  *
829
- * @param handler - Function that receives the request and thread context
830
- * @returns A Controller that can be used with the router
912
+ * This is the builder's version of defineController that provides
913
+ * proper typing for AGENT_BUILDER_THREAD and other CF bindings.
831
914
  *
832
915
  * @example
833
- * // agentbuilder/api/status.ts
834
- * export default defineThreadEndpoint(async (req, { thread }) => {
835
- * const messages = await thread.instance.getMessages();
836
- * return Response.json({ status: "ok", messageCount: messages.length });
916
+ * ```typescript
917
+ * import { defineController } from '../router/index.js';
918
+ *
919
+ * export default defineController(async ({ req, env }) => {
920
+ * const stub = env.AGENT_BUILDER.get(env.AGENT_BUILDER.idFromName('singleton'));
921
+ * // ...
837
922
  * });
923
+ * ```
838
924
  */
839
- declare function defineThreadEndpoint<Env extends ThreadEnv = ThreadEnv>(handler: (req: Request, context: ThreadEndpointContext["thread"]) => Response | Promise<Response>): Controller<Env>;
925
+ declare function defineController<Env extends ThreadEnv = ThreadEnv>(controller: BuilderController<Env>): BuilderController<Env>;
840
926
 
841
927
  /**
842
928
  * Authentication middleware for protecting API routes
@@ -932,6 +1018,17 @@ declare class DurableThread<Env extends ThreadEnv = ThreadEnv> extends DurableOb
932
1018
  * @returns Record of agent name to agent loader function
933
1019
  */
934
1020
  agents(): Record<string, () => Promise<any>>;
1021
+ /**
1022
+ * Returns the effects registry for lazy-loading effect definitions.
1023
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
1024
+ *
1025
+ * Effects are scheduled operations that run outside the tool execution context,
1026
+ * ideal for delayed notifications, webhooks, and cleanup tasks.
1027
+ *
1028
+ * @throws Error if not implemented in a subclass
1029
+ * @returns Record of effect name to effect loader function
1030
+ */
1031
+ effects(): Record<string, () => Promise<any>>;
935
1032
  /**
936
1033
  * Load a model definition by name.
937
1034
  */
@@ -956,6 +1053,49 @@ declare class DurableThread<Env extends ThreadEnv = ThreadEnv> extends DurableOb
956
1053
  * List available agent names.
957
1054
  */
958
1055
  getAgentNames(): string[];
1056
+ /**
1057
+ * Load an effect definition by name.
1058
+ */
1059
+ loadEffect(name: string): Promise<any>;
1060
+ /**
1061
+ * List available effect names.
1062
+ */
1063
+ getEffectNames(): string[];
1064
+ /**
1065
+ * Get thread metadata from DurableAgentBuilder.
1066
+ * Used for creating ThreadState outside of flow execution.
1067
+ */
1068
+ getThreadMetadata(threadId: string): Promise<ThreadMetadata>;
1069
+ /**
1070
+ * Schedule an effect for future execution.
1071
+ *
1072
+ * @param threadId - Thread ID for the effect execution context
1073
+ * @param effectName - Name of the effect to schedule
1074
+ * @param effectArgs - Arguments to pass to the effect handler
1075
+ * @param delayMs - Delay in milliseconds before execution (default: 0)
1076
+ * @returns UUID of the scheduled effect
1077
+ */
1078
+ scheduleEffect(threadId: string, effectName: string, effectArgs: Record<string, unknown>, delayMs?: number): Promise<string>;
1079
+ /**
1080
+ * Get scheduled effects for this thread.
1081
+ *
1082
+ * @param name - Optional effect name to filter by
1083
+ * @returns Array of scheduled effect records
1084
+ */
1085
+ getScheduledEffects(name?: string): Promise<Array<{
1086
+ id: string;
1087
+ name: string;
1088
+ args: Record<string, unknown>;
1089
+ scheduledAt: number;
1090
+ createdAt: number;
1091
+ }>>;
1092
+ /**
1093
+ * Remove a scheduled effect.
1094
+ *
1095
+ * @param id - The effect ID returned by scheduleEffect
1096
+ * @returns true if the effect was found and removed, false otherwise
1097
+ */
1098
+ removeScheduledEffect(id: string): Promise<boolean>;
959
1099
  /**
960
1100
  * Ensures the database schema is up to date.
961
1101
  * This method is called on the first request to the Durable Object.
@@ -1044,6 +1184,7 @@ declare class DurableThread<Env extends ThreadEnv = ThreadEnv> extends DurableOb
1044
1184
  }>;
1045
1185
  /**
1046
1186
  * Delete a message (RPC method)
1187
+ * Also cleans up any attachment files stored on the thread filesystem
1047
1188
  */
1048
1189
  deleteMessage(messageId: string): Promise<{
1049
1190
  success: boolean;
@@ -1186,6 +1327,8 @@ declare class DurableThread<Env extends ThreadEnv = ThreadEnv> extends DurableOb
1186
1327
  id: any;
1187
1328
  title: any;
1188
1329
  type: any;
1330
+ description: any;
1331
+ icon: any;
1189
1332
  side_a_label: any;
1190
1333
  side_b_label: any;
1191
1334
  } | null;
@@ -1251,7 +1394,7 @@ declare class DurableThread<Env extends ThreadEnv = ThreadEnv> extends DurableOb
1251
1394
  private broadcastMessageChunk;
1252
1395
  /**
1253
1396
  * Broadcast a telemetry event to all connected message WebSocket clients
1254
- * Used for execution status updates (turn_started, tool_started, etc.)
1397
+ * Used for execution status updates (step_started, tool_started, etc.)
1255
1398
  */
1256
1399
  private broadcastTelemetry;
1257
1400
  /**
@@ -1287,6 +1430,11 @@ declare class DurableThread<Env extends ThreadEnv = ThreadEnv> extends DurableOb
1287
1430
  * This is the actual execution logic, separate from the public execute() RPC method
1288
1431
  */
1289
1432
  private executeFlow;
1433
+ /**
1434
+ * Internal method: Execute an effect (called by alarm queue)
1435
+ * Effects run outside the tool execution context.
1436
+ */
1437
+ private executeEffect;
1290
1438
  /**
1291
1439
  * Internal method: Process a message (called by alarm queue)
1292
1440
  * This is the actual message processing logic, separate from the public sendMessage() RPC method
@@ -1538,6 +1686,59 @@ declare class DurableThread<Env extends ThreadEnv = ThreadEnv> extends DurableOb
1538
1686
  error: any;
1539
1687
  files?: undefined;
1540
1688
  }>;
1689
+ /**
1690
+ * Start a chunked file upload.
1691
+ * Creates file record with is_chunked=1 and chunk_count=null.
1692
+ * Caller should then use writeFileChunk() to write chunks.
1693
+ */
1694
+ startChunkedUpload(path: string, totalSize: number, mimeType: string, options?: {
1695
+ metadata?: Record<string, unknown>;
1696
+ width?: number;
1697
+ height?: number;
1698
+ }): Promise<{
1699
+ success: boolean;
1700
+ chunkSize?: number;
1701
+ expectedChunks?: number;
1702
+ error?: string;
1703
+ }>;
1704
+ /**
1705
+ * Write a single chunk of a chunked file upload.
1706
+ * @param path - File path
1707
+ * @param chunkIndex - 0-based chunk index
1708
+ * @param data - Base64 encoded chunk data
1709
+ */
1710
+ writeFileChunk(path: string, chunkIndex: number, data: string): Promise<{
1711
+ success: boolean;
1712
+ error?: string;
1713
+ }>;
1714
+ /**
1715
+ * Complete a chunked file upload.
1716
+ * Validates all chunks are present and sets chunk_count.
1717
+ */
1718
+ completeChunkedUpload(path: string, expectedChunks: number, options?: {
1719
+ thumbnail?: string;
1720
+ }): Promise<{
1721
+ success: boolean;
1722
+ file?: FileRecord;
1723
+ error?: string;
1724
+ }>;
1725
+ /**
1726
+ * Read a single chunk of a file.
1727
+ * Use for streaming large files to client.
1728
+ */
1729
+ readFileChunk(path: string, chunkIndex: number): Promise<{
1730
+ success: boolean;
1731
+ data?: string;
1732
+ error?: string;
1733
+ }>;
1734
+ /**
1735
+ * Get file info including chunking metadata.
1736
+ */
1737
+ getFileInfo(path: string): Promise<{
1738
+ success: boolean;
1739
+ file?: FileRecord;
1740
+ error?: string;
1741
+ }>;
1541
1742
  }
1542
1743
 
1543
1744
  /**
@@ -1868,181 +2069,44 @@ declare class DurableAgentBuilder<Env extends AgentBuilderEnv = AgentBuilderEnv>
1868
2069
  /**
1869
2070
  * Model definition module for AgentBuilder.
1870
2071
  *
1871
- * Models define LLM configurations including provider, model ID, pricing,
1872
- * and fallback chains. Models are referenced by name from prompts.
2072
+ * This module re-exports model types from @standardagents/spec and provides
2073
+ * a builder-specific version of ModelDefinition that supports the generated
2074
+ * AgentBuilder.Models type for fallback references.
1873
2075
  *
1874
2076
  * @module
1875
2077
  */
2078
+
1876
2079
  /**
1877
- * Supported LLM provider types.
1878
- * Each provider requires a corresponding API key environment variable:
1879
- * - `openai` → `OPENAI_API_KEY`
1880
- * - `openrouter` → `OPENROUTER_API_KEY`
1881
- * - `anthropic` → `ANTHROPIC_API_KEY`
1882
- * - `google` → `GOOGLE_API_KEY`
1883
- * - `test` → No API key required (for testing with scripted responses)
1884
- */
1885
- type ModelProvider = 'openai' | 'openrouter' | 'anthropic' | 'google' | 'test';
1886
- /**
1887
- * Model definition configuration.
2080
+ * Model definition configuration with AgentBuilder-specific fallback typing.
1888
2081
  *
1889
- * @template N - The model name as a string literal type for type inference
2082
+ * Extends the base ModelDefinition from @standardagents/spec to support
2083
+ * the generated AgentBuilder.Models type for type-safe fallback references.
1890
2084
  *
1891
- * @example
1892
- * ```typescript
1893
- * import { defineModel } from '@standardagents/builder';
1894
- *
1895
- * export default defineModel({
1896
- * name: 'gpt-4o',
1897
- * provider: 'openai',
1898
- * model: 'gpt-4o',
1899
- * fallbacks: ['gpt-4-turbo', 'gpt-3.5-turbo'],
1900
- * inputPrice: 2.5,
1901
- * outputPrice: 10,
1902
- * });
1903
- * ```
2085
+ * @template N - The model name as a string literal type for type inference
1904
2086
  */
1905
- interface ModelDefinition<N extends string = string> {
1906
- /**
1907
- * Unique name for this model definition.
1908
- * Used as the identifier when referencing from prompts.
1909
- * Should be descriptive and consistent (e.g., 'gpt-4o', 'claude-3-opus').
1910
- */
1911
- name: N;
1912
- /**
1913
- * The LLM provider to use for API calls.
1914
- * The corresponding API key environment variable must be set.
1915
- */
1916
- provider: ModelProvider;
1917
- /**
1918
- * The actual model identifier sent to the provider API.
1919
- *
1920
- * For OpenAI: 'gpt-4o', 'gpt-4-turbo', 'gpt-3.5-turbo', etc.
1921
- * For OpenRouter: 'openai/gpt-4o', 'anthropic/claude-3-opus', etc.
1922
- * For Anthropic: 'claude-3-opus-20240229', 'claude-3-sonnet-20240229', etc.
1923
- * For Google: 'gemini-1.5-pro', 'gemini-1.5-flash', etc.
1924
- */
1925
- model: string;
1926
- /**
1927
- * Optional list of additional provider prefixes for OpenRouter.
1928
- * Allows routing through specific providers when using OpenRouter.
1929
- *
1930
- * @example ['anthropic', 'google'] - prefer Anthropic, fallback to Google
1931
- */
1932
- includedProviders?: string[];
2087
+ interface ModelDefinition<N extends string = string> extends Omit<ModelDefinition$1<N>, 'fallbacks'> {
1933
2088
  /**
1934
2089
  * Fallback models to try if this model fails.
1935
- * Referenced by model name (must be defined in agentbuilder/models/).
2090
+ * Referenced by model name (must be defined in agents/models/).
1936
2091
  * Tried in order after primary model exhausts retries.
1937
2092
  *
1938
2093
  * @example ['gpt-4', 'gpt-3.5-turbo']
1939
2094
  */
1940
2095
  fallbacks?: AgentBuilder.Models[];
1941
- /**
1942
- * Cost per 1 million input tokens in USD.
1943
- * Used for cost tracking and reporting in logs.
1944
- */
1945
- inputPrice?: number;
1946
- /**
1947
- * Cost per 1 million output tokens in USD.
1948
- * Used for cost tracking and reporting in logs.
1949
- */
1950
- outputPrice?: number;
1951
- /**
1952
- * Cost per 1 million cached input tokens in USD.
1953
- * Some providers offer reduced pricing for cached/repeated prompts.
1954
- */
1955
- cachedPrice?: number;
1956
- /**
1957
- * Model capabilities - features this model supports.
1958
- */
1959
- capabilities?: {
1960
- /**
1961
- * Whether the model supports vision (image understanding).
1962
- * When true, image attachments will be sent to the model as part of the request.
1963
- * Models like GPT-4o, Claude 3, and Gemini support vision.
1964
- */
1965
- vision?: boolean;
1966
- /**
1967
- * Whether the model supports function calling (tool use).
1968
- * Most modern models support this, defaults to true if not specified.
1969
- */
1970
- functionCalling?: boolean;
1971
- /**
1972
- * Whether the model supports structured outputs (JSON mode).
1973
- */
1974
- structuredOutputs?: boolean;
1975
- };
1976
2096
  }
1977
- /**
1978
- * Defines an LLM model configuration.
1979
- *
1980
- * Models are the foundation of the agent system - they specify which
1981
- * AI model to use and how to connect to it. Models can have fallbacks
1982
- * for reliability and include pricing for cost tracking.
1983
- *
1984
- * @template N - The model name as a string literal type
1985
- * @param options - Model configuration options
1986
- * @returns The model definition for registration
1987
- *
1988
- * @example
1989
- * ```typescript
1990
- * // agentbuilder/models/gpt_4o.ts
1991
- * import { defineModel } from '@standardagents/builder';
1992
- *
1993
- * export default defineModel({
1994
- * name: 'gpt-4o',
1995
- * provider: 'openai',
1996
- * model: 'gpt-4o',
1997
- * fallbacks: ['gpt-4-turbo'],
1998
- * inputPrice: 2.5,
1999
- * outputPrice: 10,
2000
- * });
2001
- * ```
2002
- *
2003
- * @example
2004
- * ```typescript
2005
- * // Using OpenRouter with provider preferences
2006
- * export default defineModel({
2007
- * name: 'claude-3-opus',
2008
- * provider: 'openrouter',
2009
- * model: 'anthropic/claude-3-opus',
2010
- * includedProviders: ['anthropic'],
2011
- * });
2012
- * ```
2013
- */
2014
- declare function defineModel<N extends string>(options: ModelDefinition<N>): ModelDefinition<N>;
2015
2097
 
2016
2098
  /**
2017
2099
  * Prompt definition module for AgentBuilder.
2018
2100
  *
2019
- * Prompts define LLM interaction configurations including the system prompt,
2020
- * model selection, available tools, and various behavioral options.
2101
+ * This module re-exports prompt types from @standardagents/spec and provides
2102
+ * builder-specific versions that use the generated AgentBuilder namespace types.
2021
2103
  *
2022
2104
  * @module
2023
2105
  */
2024
2106
 
2025
2107
  /**
2026
- * A text part of a prompt - static text content.
2027
- *
2028
- * @example
2029
- * ```typescript
2030
- * { type: 'text', content: 'You are a helpful assistant.\n\n' }
2031
- * ```
2032
- */
2033
- interface PromptTextPart {
2034
- type: 'text';
2035
- /** The text content */
2036
- content: string;
2037
- }
2038
- /**
2039
- * A prompt inclusion part - includes another prompt's content.
2040
- * Uses AgentBuilder.Prompts for type-safe autocomplete of prompt names.
2041
- *
2042
- * @example
2043
- * ```typescript
2044
- * { type: 'include', prompt: 'responder_rules' }
2045
- * ```
2108
+ * A prompt inclusion part with type-safe autocomplete.
2109
+ * Uses AgentBuilder.Prompts for type-safe prompt name references.
2046
2110
  */
2047
2111
  interface PromptIncludePart {
2048
2112
  type: 'include';
@@ -2051,448 +2115,107 @@ interface PromptIncludePart {
2051
2115
  }
2052
2116
  /**
2053
2117
  * A single part of a structured prompt.
2054
- * Discriminated union on `type` field for TypeScript narrowing.
2055
2118
  */
2056
2119
  type PromptPart = PromptTextPart | PromptIncludePart;
2057
2120
  /**
2058
- * A structured prompt is an array of prompt parts.
2059
- * Provides type-safe composition with other prompts via autocomplete.
2060
- *
2061
- * @example
2062
- * ```typescript
2063
- * prompt: [
2064
- * { type: 'text', content: 'You are a helpful assistant.\n\n' },
2065
- * { type: 'include', prompt: 'common_rules' },
2066
- * { type: 'text', content: '\n\nBe concise.' },
2067
- * ]
2068
- * ```
2121
+ * Prompt content can be a string or structured array with type-safe includes.
2069
2122
  */
2070
- type StructuredPrompt = PromptPart[];
2123
+ type PromptContent = string | PromptPart[];
2071
2124
  /**
2072
- * The prompt content can be either a plain string or a structured array.
2073
- *
2074
- * @example
2075
- * ```typescript
2076
- * // Simple string prompt:
2077
- * prompt: 'You are a helpful assistant.'
2078
- *
2079
- * // Structured prompt with includes:
2080
- * prompt: [
2081
- * { type: 'text', content: 'You are a helpful assistant.\n\n' },
2082
- * { type: 'include', prompt: 'common_rules' },
2083
- * ]
2084
- * ```
2125
+ * Sub-prompt configuration with type-safe name references.
2085
2126
  */
2086
- type PromptContent = string | StructuredPrompt;
2087
- /**
2088
- * Tool configuration for including a tool in a prompt.
2089
- *
2090
- * @template T - The tool name type (for type-safe tool references)
2091
- */
2092
- interface ToolConfig<T extends string = AgentBuilder.Callables> {
2093
- /**
2094
- * Name of the tool to include.
2095
- * Must be a tool, prompt, or agent defined in agentbuilder/.
2096
- */
2127
+ interface SubpromptConfig<T extends string = AgentBuilder.Callables> extends Omit<SubpromptConfig$2<T>, 'name'> {
2128
+ /** Name of the sub-prompt (type-safe with autocomplete) */
2097
2129
  name: T;
2098
- /**
2099
- * Include text response content from sub-prompt execution in the tool result.
2100
- * @default true
2101
- */
2102
- includeTextResponse?: boolean;
2103
- /**
2104
- * Include tool call details from sub-prompt execution in the tool result.
2105
- * @default true
2106
- */
2107
- includeToolCalls?: boolean;
2108
- /**
2109
- * Include error details from sub-prompt execution in the tool result.
2110
- * @default true
2111
- */
2112
- includeErrors?: boolean;
2113
- /**
2114
- * Property from the tool call arguments to use as the initial user message
2115
- * when this tool triggers a sub-prompt execution.
2116
- *
2117
- * @example
2118
- * If the tool is called with `{ query: "search term", limit: 10 }` and
2119
- * `initUserMessageProperty: 'query'`, the sub-prompt will receive
2120
- * "search term" as the initial user message.
2121
- */
2122
- initUserMessageProperty?: string;
2123
2130
  }
2124
2131
  /**
2125
- * Reasoning configuration for models that support extended thinking.
2126
- * Applies to models like OpenAI o1, Anthropic Claude with extended thinking,
2127
- * Google Gemini with thinking, and Qwen with reasoning.
2132
+ * @deprecated Use SubpromptConfig instead
2128
2133
  */
2129
- interface ReasoningConfig {
2130
- /**
2131
- * Effort level for reasoning models.
2132
- * Higher effort = more thinking tokens = potentially better results.
2133
- *
2134
- * - `low`: Minimal reasoning, faster responses
2135
- * - `medium`: Balanced reasoning and speed
2136
- * - `high`: Maximum reasoning, slower but more thorough
2137
- *
2138
- * @default undefined (use model defaults)
2139
- */
2140
- effort?: 'low' | 'medium' | 'high';
2141
- /**
2142
- * Maximum tokens to allocate for reasoning.
2143
- * Applies to models that support token limits on reasoning
2144
- * (Anthropic, Gemini, Qwen).
2145
- */
2146
- maxTokens?: number;
2147
- /**
2148
- * Use reasoning internally but exclude from the response.
2149
- * Model thinks through the problem but only returns the final answer.
2150
- * Useful for cleaner outputs while maintaining reasoning quality.
2151
- */
2152
- exclude?: boolean;
2153
- /**
2154
- * Include reasoning content in the message history for multi-turn context.
2155
- * When true, reasoning is preserved and visible to subsequent turns.
2156
- * @default false
2157
- */
2158
- include?: boolean;
2159
- }
2134
+ type ToolConfig<T extends string = AgentBuilder.Callables> = SubpromptConfig<T>;
2135
+
2160
2136
  /**
2161
- * Prompt definition configuration.
2137
+ * Prompt definition configuration with AgentBuilder-specific typing.
2138
+ *
2139
+ * Provides type-safe references to models, tools, and agents via the
2140
+ * generated AgentBuilder namespace.
2162
2141
  *
2163
2142
  * @template N - The prompt name as a string literal type
2164
2143
  * @template S - The Zod schema type for requiredSchema (inferred automatically)
2165
- *
2166
- * @example
2167
- * ```typescript
2168
- * import { definePrompt } from '@standardagents/builder';
2169
- * import { z } from 'zod';
2170
- *
2171
- * export default definePrompt({
2172
- * name: 'customer_support',
2173
- * toolDescription: 'Handle customer support inquiries',
2174
- * model: 'gpt-4o',
2175
- * // Simple string prompt:
2176
- * prompt: `You are a helpful customer support agent.
2177
- * Always be polite and try to resolve issues quickly.`,
2178
- * // Or structured prompt with type-safe includes:
2179
- * // prompt: [
2180
- * // { type: 'text', content: 'You are a helpful customer support agent.\n\n' },
2181
- * // { type: 'include', prompt: 'common_rules' },
2182
- * // ],
2183
- * tools: ['search_knowledge_base', 'create_ticket'],
2184
- * requiredSchema: z.object({
2185
- * query: z.string().describe('The customer inquiry'),
2186
- * }),
2187
- * });
2188
- * ```
2189
2144
  */
2190
- interface PromptDefinition<N extends string = string, S extends z.ZodTypeAny = z.ZodTypeAny> {
2191
- /**
2192
- * Unique name for this prompt.
2193
- * Used as the identifier when referencing from agents or as a tool.
2194
- * Should be snake_case (e.g., 'customer_support', 'data_analyst').
2195
- */
2145
+ interface PromptDefinition<N extends string = string, S extends ToolArgs = ToolArgs> {
2146
+ /** Unique name for this prompt. */
2196
2147
  name: N;
2197
- /**
2198
- * Description shown when this prompt is exposed as a tool.
2199
- * Should clearly describe what this prompt does for LLM tool selection.
2200
- */
2148
+ /** Description shown when this prompt is exposed as a tool. */
2201
2149
  toolDescription: string;
2202
- /**
2203
- * The system prompt content sent to the LLM.
2204
- *
2205
- * Can be either:
2206
- * 1. A plain string - simple prompt text
2207
- * 2. A structured array - for composing prompts with type-safe includes
2208
- *
2209
- * @example
2210
- * ```typescript
2211
- * // Simple string prompt:
2212
- * prompt: 'You are a helpful assistant.'
2213
- *
2214
- * // Structured prompt with type-safe includes:
2215
- * prompt: [
2216
- * { type: 'text', content: 'You are a helpful assistant.\n\n' },
2217
- * { type: 'include', prompt: 'common_rules' }, // autocomplete for prompt names!
2218
- * { type: 'text', content: '\n\nBe concise.' },
2219
- * ]
2220
- * ```
2221
- */
2150
+ /** The system prompt content with type-safe includes. */
2222
2151
  prompt: PromptContent;
2223
- /**
2224
- * Model to use for this prompt.
2225
- * Must reference a model defined in agentbuilder/models/.
2226
- * Provides autocomplete when types are generated.
2227
- */
2152
+ /** Model to use (type-safe with autocomplete). */
2228
2153
  model: AgentBuilder.Models;
2229
2154
  /**
2230
2155
  * @deprecated All prompts are now automatically exposed as tools.
2231
- * This property is ignored and will be removed in a future version.
2232
2156
  */
2233
2157
  exposeAsTool?: boolean;
2234
- /**
2235
- * Include full chat history in the LLM context.
2236
- * When true, all previous messages in the conversation are included.
2237
- * @default false
2238
- */
2158
+ /** Include full chat history in the LLM context. @default false */
2239
2159
  includeChat?: boolean;
2240
- /**
2241
- * Include results from past tool calls in the LLM context.
2242
- * When true, previous tool call results are visible to the LLM.
2243
- * @default false
2244
- */
2160
+ /** Include results from past tool calls. @default false */
2245
2161
  includePastTools?: boolean;
2246
- /**
2247
- * Allow parallel execution of multiple tool calls.
2248
- * When true, if the LLM requests multiple tools, they execute concurrently.
2249
- * @default false
2250
- */
2162
+ /** Allow parallel execution of multiple tool calls. @default false */
2251
2163
  parallelToolCalls?: boolean;
2252
- /**
2253
- * Tool calling strategy for the LLM.
2254
- *
2255
- * - `auto`: Model decides when to call tools (default)
2256
- * - `none`: Disable tool calling entirely
2257
- * - `required`: Force the model to call at least one tool
2258
- *
2259
- * @default 'auto'
2260
- */
2164
+ /** Tool calling strategy. @default 'auto' */
2261
2165
  toolChoice?: 'auto' | 'none' | 'required';
2262
- /**
2263
- * Zod schema for validating inputs when this prompt is called as a tool.
2264
- *
2265
- * The schema provides:
2266
- * - Runtime validation of tool call arguments
2267
- * - Type inference for the prompt's input type
2268
- * - Auto-generated JSON Schema for LLM tool definitions
2269
- *
2270
- * Use `.describe()` on schema fields to provide descriptions for the LLM.
2271
- *
2272
- * @example
2273
- * ```typescript
2274
- * requiredSchema: z.object({
2275
- * query: z.string().describe('The search query'),
2276
- * limit: z.number().optional().default(10).describe('Max results'),
2277
- * })
2278
- * ```
2279
- */
2166
+ /** Zod schema for validating inputs when called as a tool. */
2280
2167
  requiredSchema?: S;
2281
- /**
2282
- * Tools available to this prompt.
2283
- * Can be simple tool names or detailed configurations.
2284
- *
2285
- * Tools can be:
2286
- * - Custom tools defined in agentbuilder/tools/
2287
- * - Other prompts with exposeAsTool: true
2288
- * - Agents with exposeAsTool: true
2289
- *
2290
- * @example
2291
- * ```typescript
2292
- * tools: [
2293
- * 'search_docs', // Simple reference
2294
- * { name: 'create_ticket', includeErrors: false }, // With config
2295
- * ]
2296
- * ```
2297
- */
2298
- tools?: (AgentBuilder.Callables | ToolConfig)[];
2299
- /**
2300
- * Agents that can receive handoffs from this prompt.
2301
- * Enables multi-agent workflows where this prompt can transfer
2302
- * the conversation to a specialized agent.
2303
- */
2304
- handoffAgents?: AgentBuilder.Agents[];
2305
- /**
2306
- * Tool to execute before the LLM request.
2307
- * Useful for data fetching, context preparation, or preprocessing.
2308
- * The tool result is available in the prompt context.
2309
- */
2310
- beforeTool?: AgentBuilder.Callables;
2311
- /**
2312
- * Tool to execute after the LLM response.
2313
- * Useful for post-processing, logging, or side effects.
2314
- */
2315
- afterTool?: AgentBuilder.Callables;
2316
- /**
2317
- * Reasoning configuration for models that support extended thinking.
2318
- * Configure effort level, token limits, and visibility of reasoning.
2319
- */
2168
+ /** Tools available to this prompt (type-safe with autocomplete). To enable handoffs, include ai_human agent names. */
2169
+ tools?: (AgentBuilder.Callables | SubpromptConfig)[];
2170
+ /** Reasoning configuration for extended thinking models. */
2320
2171
  reasoning?: ReasoningConfig;
2321
- /**
2322
- * Maximum pixels for image attachments before client-side resize.
2323
- * Images exceeding this limit are scaled down while preserving aspect ratio.
2324
- * Images smaller than this limit are not resized up.
2325
- *
2326
- * Common values:
2327
- * - 262144 (256K): 512x512 equivalent - thumbnails, low cost
2328
- * - 1048576 (1M): 1024x1024 equivalent - good quality (default)
2329
- * - 2073600 (2M): 1440x1440 equivalent - high quality
2330
- * - 4194304 (4M): 2048x2048 equivalent - maximum detail
2331
- *
2332
- * @default 1048576 (1M pixels, ~1024x1024)
2333
- *
2334
- * @example
2335
- * ```typescript
2336
- * // High quality images for detailed analysis
2337
- * maxImagePixels: 2073600
2338
- *
2339
- * // Lower quality for cost-sensitive applications
2340
- * maxImagePixels: 262144
2341
- * ```
2342
- */
2343
- maxImagePixels?: number;
2344
- /**
2345
- * Number of recent messages to keep actual images for in context.
2346
- * Messages older than this threshold will have their images replaced
2347
- * with text descriptions to save context window space.
2348
- *
2349
- * This helps manage context window usage in long conversations with
2350
- * many image attachments by summarizing older images.
2351
- *
2352
- * @default 10
2353
- *
2354
- * @example
2355
- * ```typescript
2356
- * // Keep more images in context for image-heavy workflows
2357
- * recentImageThreshold: 20
2358
- *
2359
- * // Aggressively summarize to save context
2360
- * recentImageThreshold: 5
2361
- * ```
2362
- */
2172
+ /** Number of recent messages to keep actual images for. @default 10 */
2363
2173
  recentImageThreshold?: number;
2364
2174
  }
2365
- /**
2366
- * Helper type to extract the inferred input type from a prompt's Zod schema.
2367
- *
2368
- * @template T - The prompt definition type
2369
- *
2370
- * @example
2371
- * ```typescript
2372
- * const searchPrompt = definePrompt({
2373
- * name: 'search',
2374
- * requiredSchema: z.object({ query: z.string(), limit: z.number() }),
2375
- * // ...
2376
- * });
2377
- *
2378
- * type SearchInput = PromptInput<typeof searchPrompt>;
2379
- * // { query: string; limit: number }
2380
- * ```
2381
- */
2382
- type PromptInput<T extends PromptDefinition<any, any>> = T['requiredSchema'] extends z.ZodTypeAny ? z.infer<T['requiredSchema']> : never;
2383
- /**
2384
- * Defines a prompt configuration for LLM interactions.
2385
- *
2386
- * Prompts are the primary way to configure how agents interact with LLMs.
2387
- * They specify the system prompt, available tools, input validation,
2388
- * and various behavioral options.
2389
- *
2390
- * @template N - The prompt name as a string literal type
2391
- * @template S - The Zod schema type for requiredSchema
2392
- * @param options - Prompt configuration options
2393
- * @returns The prompt definition for registration
2394
- *
2395
- * @example
2396
- * ```typescript
2397
- * // agentbuilder/prompts/customer_support.ts
2398
- * import { definePrompt } from '@standardagents/builder';
2399
- * import { z } from 'zod';
2400
- *
2401
- * export default definePrompt({
2402
- * name: 'customer_support',
2403
- * toolDescription: 'Handle customer support inquiries',
2404
- * model: 'gpt-4o',
2405
- * prompt: `You are a helpful customer support agent.
2406
- * Always be polite and try to resolve issues quickly.
2407
- * If you cannot help, offer to escalate to a human.`,
2408
- * tools: ['search_knowledge_base', 'create_ticket'],
2409
- * handoffAgents: ['escalation_agent'],
2410
- * includeChat: true,
2411
- * exposeAsTool: true,
2412
- * requiredSchema: z.object({
2413
- * query: z.string().describe('The customer inquiry'),
2414
- * }),
2415
- * });
2416
- * ```
2417
- */
2418
- declare function definePrompt<N extends string, S extends z.ZodTypeAny = never>(options: PromptDefinition<N, S>): PromptDefinition<N, S>;
2419
2175
 
2420
2176
  /**
2421
2177
  * Agent definition module for AgentBuilder.
2422
2178
  *
2423
- * Agents orchestrate conversations between AI models (dual_ai) or between
2424
- * AI and human users (ai_human). They define the prompts, stop conditions,
2425
- * and behavioral rules for each side of the conversation.
2179
+ * This module re-exports agent types from @standardagents/spec and provides
2180
+ * builder-specific versions that use the generated AgentBuilder namespace types.
2426
2181
  *
2427
2182
  * @module
2428
2183
  */
2184
+
2429
2185
  /**
2430
- * Agent conversation type.
2431
- *
2432
- * - `ai_human`: AI conversing with a human user (most common)
2433
- * - `dual_ai`: Two AI participants conversing with each other
2434
- */
2435
- type AgentType = 'ai_human' | 'dual_ai';
2436
- /**
2437
- * Configuration for one side of an agent conversation.
2438
- *
2439
- * Each side has a prompt, stop conditions, and turn limits.
2440
- * For `ai_human` agents, only sideA (the AI) needs configuration.
2441
- * For `dual_ai` agents, both sides need configuration.
2186
+ * Side configuration with type-safe autocomplete.
2187
+ * Uses AgentBuilder.Prompts and AgentBuilder.Callables for type-safe references.
2442
2188
  */
2443
- interface SideConfig {
2444
- /**
2445
- * Custom label for this side of the conversation.
2446
- * Used in UI and logs for clarity.
2447
- *
2448
- * @example 'Support Agent', 'Customer', 'ATC', 'Pilot'
2449
- */
2450
- label?: string;
2189
+ interface SideConfig extends Omit<SideConfig$1, 'prompt' | 'stopTool' | 'endSessionTool'> {
2451
2190
  /**
2452
- * The prompt to use for this side.
2453
- * Must reference a prompt defined in agentbuilder/prompts/.
2191
+ * The prompt to use for this side (type-safe with autocomplete).
2192
+ * Must reference a prompt defined in agents/prompts/.
2454
2193
  */
2455
2194
  prompt: AgentBuilder.Prompts;
2456
2195
  /**
2457
- * Stop this side's turn when it returns a text response (no tool calls).
2458
- * When true, the side's turn ends after producing a message without tools.
2459
- * @default true
2460
- */
2461
- stopOnResponse?: boolean;
2462
- /**
2463
- * Stop this side's turn when a specific tool is called.
2196
+ * Stop this side's turn when a specific tool is called (type-safe with autocomplete).
2464
2197
  * Overrides stopOnResponse when the named tool is invoked.
2465
2198
  * Requires stopToolResponseProperty to extract the result.
2466
2199
  */
2467
2200
  stopTool?: AgentBuilder.Callables;
2468
2201
  /**
2469
- * Property to extract from the stop tool's result.
2470
- * Required when stopTool is set.
2471
- * The extracted value is used to determine the conversation outcome.
2472
- */
2473
- stopToolResponseProperty?: string;
2474
- /**
2475
- * Maximum turns for this side before forcing a stop.
2476
- * Safety limit to prevent runaway conversations.
2477
- * A turn is one complete request/response cycle.
2478
- */
2479
- maxTurns?: number;
2480
- /**
2481
- * Tool that ends the entire conversation when called.
2482
- * Different from stopTool - this ends the conversation for both sides,
2202
+ * Tool that ends the entire session when called (type-safe with autocomplete).
2203
+ * Different from stopTool - this ends the session for both sides,
2483
2204
  * not just this side's turn.
2484
2205
  */
2485
- endConversationTool?: AgentBuilder.Callables;
2206
+ endSessionTool?: AgentBuilder.Callables;
2486
2207
  /**
2487
2208
  * Enable manual stop condition handling via hooks.
2488
- * When true, stop conditions are evaluated by custom hook logic
2489
- * instead of the built-in rules.
2209
+ * Builder-specific feature for custom stop logic.
2490
2210
  * @default false
2491
2211
  */
2492
2212
  manualStopCondition?: boolean;
2493
2213
  }
2494
2214
  /**
2495
- * Agent definition configuration.
2215
+ * Agent definition configuration with AgentBuilder-specific typing.
2216
+ *
2217
+ * Provides type-safe references to prompts and tools via the
2218
+ * generated AgentBuilder namespace.
2496
2219
  *
2497
2220
  * @template N - The agent name as a string literal type
2498
2221
  *
@@ -2509,126 +2232,45 @@ interface SideConfig {
2509
2232
  * prompt: 'customer_support',
2510
2233
  * stopOnResponse: true,
2511
2234
  * },
2512
- * tags: ['support', 'tier-1'],
2513
2235
  * });
2514
2236
  * ```
2515
2237
  */
2516
2238
  interface AgentDefinition<N extends string = string> {
2517
- /**
2518
- * Unique name for this agent.
2519
- * Used as the identifier for thread creation and handoffs.
2520
- * Should be snake_case (e.g., 'support_agent', 'research_flow').
2521
- */
2239
+ /** Unique name for this agent. */
2522
2240
  name: N;
2523
2241
  /**
2524
2242
  * Human-readable title for the agent.
2525
- * Optional - if not provided, the name will be used.
2526
2243
  * @deprecated Use name instead. Title will be removed in a future version.
2527
2244
  */
2528
2245
  title?: string;
2529
2246
  /**
2530
2247
  * Agent conversation type.
2531
- *
2532
2248
  * - `ai_human`: AI conversing with a human user (default)
2533
2249
  * - `dual_ai`: Two AI participants conversing
2534
- *
2535
2250
  * @default 'ai_human'
2536
2251
  */
2537
- type?: AgentType;
2252
+ type?: 'ai_human' | 'dual_ai';
2538
2253
  /**
2539
2254
  * Maximum total turns across both sides.
2540
2255
  * Only applies to `dual_ai` agents.
2541
- * Prevents infinite loops in AI-to-AI conversations.
2542
2256
  */
2543
2257
  maxSessionTurns?: number;
2544
- /**
2545
- * Configuration for Side A.
2546
- * For `ai_human`: This is the AI side.
2547
- * For `dual_ai`: This is the first AI participant.
2548
- */
2258
+ /** Configuration for Side A (type-safe with autocomplete). */
2549
2259
  sideA: SideConfig;
2550
- /**
2551
- * Configuration for Side B.
2552
- * For `ai_human`: Optional, the human side doesn't need config.
2553
- * For `dual_ai`: Required, the second AI participant.
2554
- */
2260
+ /** Configuration for Side B (type-safe with autocomplete). */
2555
2261
  sideB?: SideConfig;
2556
2262
  /**
2557
2263
  * Expose this agent as a tool for other prompts.
2558
- * Enables agent composition and handoffs.
2559
- * When true, other prompts can invoke this agent as a tool.
2560
2264
  * @default false
2561
2265
  */
2562
2266
  exposeAsTool?: boolean;
2563
- /**
2564
- * Description shown when agent is used as a tool.
2565
- * Required if exposeAsTool is true.
2566
- * Should clearly describe what this agent does.
2567
- */
2267
+ /** Description shown when agent is used as a tool. */
2568
2268
  toolDescription?: string;
2569
- /**
2570
- * Tags for categorization and filtering.
2571
- * Useful for organizing agents in the UI and filtering in queries.
2572
- *
2573
- * @example ['customer-service', 'tier-1', 'english']
2574
- */
2575
- tags?: string[];
2269
+ /** Brief description of what this agent does. */
2270
+ description?: string;
2271
+ /** Icon URL or absolute path for the agent. */
2272
+ icon?: string;
2576
2273
  }
2577
- /**
2578
- * Defines an agent configuration.
2579
- *
2580
- * Agents orchestrate conversations between AI models, or between AI and
2581
- * human users. They use prompts to configure each side of the conversation
2582
- * and define stop conditions to control conversation flow.
2583
- *
2584
- * @template N - The agent name as a string literal type
2585
- * @param options - Agent configuration options
2586
- * @returns The agent definition for registration
2587
- *
2588
- * @example
2589
- * ```typescript
2590
- * // agentbuilder/agents/support_agent.ts
2591
- * import { defineAgent } from '@standardagents/builder';
2592
- *
2593
- * export default defineAgent({
2594
- * name: 'support_agent',
2595
- * title: 'Customer Support Agent',
2596
- * type: 'ai_human',
2597
- * sideA: {
2598
- * label: 'Support',
2599
- * prompt: 'customer_support',
2600
- * stopOnResponse: true,
2601
- * endConversationTool: 'close_ticket',
2602
- * },
2603
- * exposeAsTool: true,
2604
- * toolDescription: 'Hand off to customer support',
2605
- * tags: ['support', 'tier-1'],
2606
- * });
2607
- * ```
2608
- *
2609
- * @example
2610
- * ```typescript
2611
- * // Dual AI agent (two AIs conversing)
2612
- * export default defineAgent({
2613
- * name: 'debate_agent',
2614
- * title: 'AI Debate',
2615
- * type: 'dual_ai',
2616
- * maxSessionTurns: 10,
2617
- * sideA: {
2618
- * label: 'Pro',
2619
- * prompt: 'debate_pro',
2620
- * stopOnResponse: true,
2621
- * },
2622
- * sideB: {
2623
- * label: 'Con',
2624
- * prompt: 'debate_con',
2625
- * stopOnResponse: true,
2626
- * endConversationTool: 'conclude_debate',
2627
- * },
2628
- * });
2629
- * ```
2630
- */
2631
- declare function defineAgent<N extends string>(options: AgentDefinition<N>): AgentDefinition<N>;
2632
2274
 
2633
2275
  /**
2634
2276
  * Generate a TypeScript file for a model definition.
@@ -2706,9 +2348,6 @@ interface PromptFileData {
2706
2348
  parallelToolCalls?: boolean;
2707
2349
  toolChoice?: 'auto' | 'none' | 'required';
2708
2350
  tools?: (string | ToolConfigInput)[];
2709
- handoffAgents?: string[];
2710
- beforeTool?: string;
2711
- afterTool?: string;
2712
2351
  reasoning?: {
2713
2352
  effort?: 'low' | 'medium' | 'high';
2714
2353
  maxTokens?: number;
@@ -3793,4 +3432,4 @@ declare class GitHubApiError extends Error {
3793
3432
  constructor(message: string, status: number, details?: unknown);
3794
3433
  }
3795
3434
 
3796
- export { type Agent, type AgentBuilderEnv, type AgentDefinition, type AgentType, type AttachmentRef, type AuthContext, type AuthUser, type BroadcastOptions, type Controller, type ControllerContext, DurableAgentBuilder, DurableThread, type Env, type FileRecord, type FileStats, type FlowResult, type FlowState, FlowStateSdk, type FlowStateWithSdk, GitHubApiError, GitHubClient, type GitHubCommitResult, type GitHubConfig, type GitHubFileChange, type GrepResult, type HookSignatures, type ImageContent, type ImageContentPart, type ImageContextConfig, type ImageMetadata, type InjectMessageOptions$1 as InjectMessageOptions, type LLMResponse, type Message, type MessageContent, type ModelDefinition, type ModelProvider, type MultimodalContent, type PromptContent, type PromptDefinition, type PromptIncludePart, type PromptInput, type PromptPart, type PromptTextPart, type Provider, type ReasoningConfig, type RequestContext, type SideConfig, type StorageBackend, type StructuredPrompt, type StructuredToolReturn, type TelemetryEvent, type TextContent, type TextContentPart, type ThreadEndpointContext, type ThreadEnv, type ThreadInstance, type ThreadMetadata, type ThreadRegistryEntry, type Tool, type ToolArgs, type ToolArgsNode, type ToolArgsRawShape, type ToolCall, type ToolConfig, type ToolContent, type ToolResult, type UpdateThreadParams, type User, authenticate, buildImageDescription, cat, defineAgent, defineController, defineHook, defineModel, definePrompt, defineThreadEndpoint, defineTool, emitThreadEvent, enhanceFlowState, exists, find, forceTurn, generateAgentFile, generateImageDescription, generateModelFile, generatePromptFile, getFileStats, getMessages, getMessagesToSummarize, getThumbnail, getUnsummarizedImageAttachments, grep, hasImageAttachments, head, injectMessage, linkFile, mkdir, optimizeImageContext, queueTool, readFile, readdir, reloadHistory, replaceImagesWithDescriptions, requireAdmin, requireAuth, rmdir, stat, tail, unlink, updateThread, writeFile, writeImage };
3435
+ export { type Agent, type AgentBuilderEnv, type AgentDefinition, type AttachmentRef, type AuthContext, type AuthUser, type BroadcastOptions, type BuilderController as Controller, type BuilderControllerContext as ControllerContext, DurableAgentBuilder, DurableThread, type Env, type FileRecord, type FileStats, type FlowResult, type FlowState, FlowStateSdk, type FlowStateWithSdk, GitHubApiError, GitHubClient, type GitHubCommitResult, type GitHubConfig, type GitHubFileChange, type GrepResult, type ImageContentPart, type ImageContextConfig, type ImageMetadata, type InjectMessageOptions$1 as InjectMessageOptions, type LLMResponse, type Message, type MessageContent, type ModelDefinition, type MultimodalContent, type PromptContent, type PromptDefinition, type PromptIncludePart, type PromptPart, type Provider, type RequestContext, type SideConfig, type StorageBackend, type SubpromptConfig, type TelemetryEvent, type TextContentPart, type ThreadEndpointContext, type ThreadEnv, type ThreadInstance, type ThreadMetadata, type ThreadRegistryEntry, type ToolCall, type ToolConfig, type ToolResult, type UpdateThreadParams, type User, authenticate, buildImageDescription, cat, defineController, emitThreadEvent, enhanceFlowState, exists, find, forceTurn, generateAgentFile, generateImageDescription, generateModelFile, generatePromptFile, getFileStats, getMessages, getMessagesToSummarize, getThumbnail, getUnsummarizedImageAttachments, grep, hasImageAttachments, head, injectMessage, linkFile, mkdir, optimizeImageContext, queueTool, readFile, readdir, reloadHistory, replaceImagesWithDescriptions, requireAdmin, requireAuth, rmdir, stat, tail, unlink, updateThread, writeFile, writeImage };