llmist 9.1.1 → 9.2.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.
package/dist/index.d.ts CHANGED
@@ -7739,14 +7739,30 @@ declare class GadgetCallParser {
7739
7739
  }
7740
7740
 
7741
7741
  /**
7742
- * Helper functions for gadget authors to easily return media outputs.
7742
+ * Helper functions for gadget authors.
7743
7743
  *
7744
- * These functions provide type-specific conveniences while using the
7745
- * generic GadgetMediaOutput system underneath.
7744
+ * This module provides:
7745
+ * 1. Response formatting helpers (gadgetSuccess, gadgetError, withErrorHandling)
7746
+ * 2. Media output helpers (resultWithImage, resultWithAudio, etc.)
7746
7747
  *
7747
- * @example
7748
+ * @example Response helpers
7749
+ * ```typescript
7750
+ * import { gadgetSuccess, gadgetError, withErrorHandling } from "llmist";
7751
+ *
7752
+ * // Simple response formatting
7753
+ * return gadgetSuccess({ url: "https://example.com", title: "Example" });
7754
+ * return gadgetError("Element not found", { selector: ".missing" });
7755
+ *
7756
+ * // Automatic error handling wrapper
7757
+ * const safeExecute = withErrorHandling(async (params) => {
7758
+ * // your code here - errors are automatically caught and formatted
7759
+ * return gadgetSuccess({ result: "done" });
7760
+ * });
7761
+ * ```
7762
+ *
7763
+ * @example Media output helpers
7748
7764
  * ```typescript
7749
- * import { resultWithImage } from "llmist/gadgets";
7765
+ * import { resultWithImage } from "llmist";
7750
7766
  *
7751
7767
  * const screenshotGadget = createGadget({
7752
7768
  * name: "Screenshot",
@@ -7763,6 +7779,72 @@ declare class GadgetCallParser {
7763
7779
  * ```
7764
7780
  */
7765
7781
 
7782
+ /**
7783
+ * Create a success response as JSON string.
7784
+ *
7785
+ * This is a convenience helper for gadgets that return JSON-formatted responses.
7786
+ * It automatically adds `success: true` and stringifies the result.
7787
+ *
7788
+ * @param data - Additional data to include in the response
7789
+ * @returns JSON string with success: true and provided data
7790
+ *
7791
+ * @example
7792
+ * ```typescript
7793
+ * return gadgetSuccess({ url: page.url(), title: await page.title() });
7794
+ * // Returns: '{"success":true,"url":"...","title":"..."}'
7795
+ * ```
7796
+ */
7797
+ declare function gadgetSuccess(data?: Record<string, unknown>): string;
7798
+ /**
7799
+ * Create an error response as JSON string.
7800
+ *
7801
+ * This is a convenience helper for gadgets that return JSON-formatted errors.
7802
+ * It stringifies the error message and any additional details.
7803
+ *
7804
+ * @param message - Error message
7805
+ * @param details - Additional error details (e.g., suggestions, context)
7806
+ * @returns JSON string with error message and details
7807
+ *
7808
+ * @example
7809
+ * ```typescript
7810
+ * return gadgetError("Element not found", { selector: ".missing", suggestions: ["Try #id instead"] });
7811
+ * // Returns: '{"error":"Element not found","selector":".missing","suggestions":[...]}'
7812
+ * ```
7813
+ */
7814
+ declare function gadgetError(message: string, details?: Record<string, unknown>): string;
7815
+ /**
7816
+ * Safely extract error message from unknown error type.
7817
+ *
7818
+ * Handles both Error instances and other thrown values.
7819
+ *
7820
+ * @param error - Unknown error value
7821
+ * @returns String error message
7822
+ */
7823
+ declare function getErrorMessage(error: unknown): string;
7824
+ /**
7825
+ * Wrap a gadget execute function with automatic error handling.
7826
+ *
7827
+ * This higher-order function catches any errors thrown during execution
7828
+ * and converts them to properly formatted error responses.
7829
+ *
7830
+ * @param execute - The execute function to wrap
7831
+ * @returns A wrapped function that catches errors and returns gadgetError responses
7832
+ *
7833
+ * @example
7834
+ * ```typescript
7835
+ * const safeExecute = withErrorHandling(async (params: MyParams) => {
7836
+ * // Your code here - if it throws, error is caught and formatted
7837
+ * const result = await riskyOperation(params.id);
7838
+ * return gadgetSuccess({ result });
7839
+ * });
7840
+ *
7841
+ * // In gadget:
7842
+ * execute(params) {
7843
+ * return safeExecute(params);
7844
+ * }
7845
+ * ```
7846
+ */
7847
+ declare function withErrorHandling<TParams>(execute: (params: TParams, ctx?: ExecutionContext) => Promise<string> | string): (params: TParams, ctx?: ExecutionContext) => Promise<string>;
7766
7848
  /**
7767
7849
  * Create a GadgetMediaOutput from raw data.
7768
7850
  *
@@ -8534,6 +8616,793 @@ declare class OpenAIChatProvider extends BaseProviderAdapter {
8534
8616
  }
8535
8617
  declare function createOpenAIProviderFromEnv(): OpenAIChatProvider | null;
8536
8618
 
8619
+ /**
8620
+ * Formatting utilities for gadget authors and CLI output.
8621
+ *
8622
+ * Provides common formatting functions for:
8623
+ * - Text truncation
8624
+ * - Byte size formatting
8625
+ * - Date formatting
8626
+ * - Duration formatting
8627
+ *
8628
+ * @module utils/format
8629
+ *
8630
+ * @example
8631
+ * ```typescript
8632
+ * import { format } from "llmist";
8633
+ *
8634
+ * format.truncate("Long text...", 10); // "Long tex..."
8635
+ * format.bytes(1536); // "1.5 KB"
8636
+ * format.date("2024-01-15T10:30:00Z"); // "Jan 15, 2024 10:30 AM"
8637
+ * format.duration(125000); // "2m 5s"
8638
+ * ```
8639
+ */
8640
+ /**
8641
+ * Truncate text to a maximum length, adding suffix if truncated.
8642
+ *
8643
+ * @param text - Text to truncate
8644
+ * @param maxLength - Maximum length including suffix
8645
+ * @param suffix - Suffix to append when truncated (default: "...")
8646
+ * @returns Truncated text
8647
+ *
8648
+ * @example
8649
+ * ```typescript
8650
+ * truncate("Hello, World!", 10); // "Hello, ..."
8651
+ * truncate("Short", 10); // "Short"
8652
+ * truncate("Custom", 6, "…"); // "Custo…"
8653
+ * ```
8654
+ */
8655
+ declare function truncate(text: string, maxLength: number, suffix?: string): string;
8656
+ /**
8657
+ * Format bytes as human-readable string.
8658
+ *
8659
+ * @param bytes - Number of bytes
8660
+ * @param decimals - Number of decimal places (default: 1)
8661
+ * @returns Formatted string (e.g., "1.5 KB", "2.3 MB")
8662
+ *
8663
+ * @example
8664
+ * ```typescript
8665
+ * formatBytes(0); // "0 B"
8666
+ * formatBytes(1024); // "1 KB"
8667
+ * formatBytes(1536); // "1.5 KB"
8668
+ * formatBytes(1048576); // "1 MB"
8669
+ * ```
8670
+ */
8671
+ declare function formatBytes(bytes: number, decimals?: number): string;
8672
+ /**
8673
+ * Format ISO date string as human-readable date.
8674
+ *
8675
+ * @param isoDate - ISO date string (e.g., "2024-01-15T10:30:00Z")
8676
+ * @param options - Intl.DateTimeFormat options
8677
+ * @returns Formatted date string
8678
+ *
8679
+ * @example
8680
+ * ```typescript
8681
+ * formatDate("2024-01-15T10:30:00Z");
8682
+ * // "Jan 15, 2024, 10:30 AM" (in local timezone)
8683
+ *
8684
+ * formatDate("2024-01-15T10:30:00Z", { dateStyle: "short" });
8685
+ * // "1/15/24"
8686
+ * ```
8687
+ */
8688
+ declare function formatDate(isoDate: string, options?: Intl.DateTimeFormatOptions): string;
8689
+ /**
8690
+ * Format duration in milliseconds as human-readable string.
8691
+ *
8692
+ * @param ms - Duration in milliseconds
8693
+ * @param options - Formatting options
8694
+ * @returns Formatted duration string
8695
+ *
8696
+ * @example
8697
+ * ```typescript
8698
+ * formatDuration(500); // "500ms"
8699
+ * formatDuration(1500); // "1.5s"
8700
+ * formatDuration(65000); // "1m 5s"
8701
+ * formatDuration(3725000); // "1h 2m 5s"
8702
+ * ```
8703
+ */
8704
+ declare function formatDuration(ms: number, options?: {
8705
+ compact?: boolean;
8706
+ }): string;
8707
+ /**
8708
+ * Format namespace object for convenient access.
8709
+ *
8710
+ * @example
8711
+ * ```typescript
8712
+ * import { format } from "llmist";
8713
+ *
8714
+ * format.truncate("text", 5);
8715
+ * format.bytes(1024);
8716
+ * format.date("2024-01-15");
8717
+ * format.duration(5000);
8718
+ * ```
8719
+ */
8720
+ declare const format: {
8721
+ readonly truncate: typeof truncate;
8722
+ readonly bytes: typeof formatBytes;
8723
+ readonly date: typeof formatDate;
8724
+ readonly duration: typeof formatDuration;
8725
+ };
8726
+
8727
+ /**
8728
+ * Timing utilities for gadget authors.
8729
+ *
8730
+ * Provides common timing functions for:
8731
+ * - Random delays (human-like timing)
8732
+ * - Timeout handling
8733
+ * - Retry logic with backoff
8734
+ *
8735
+ * @module utils/timing
8736
+ *
8737
+ * @example
8738
+ * ```typescript
8739
+ * import { timing } from "llmist";
8740
+ *
8741
+ * // Human-like delays for browser automation
8742
+ * await timing.humanDelay(50, 150);
8743
+ *
8744
+ * // Add timeout to async operations
8745
+ * const result = await timing.withTimeout(
8746
+ * () => fetchData(),
8747
+ * 5000,
8748
+ * signal
8749
+ * );
8750
+ *
8751
+ * // Retry with exponential backoff
8752
+ * const data = await timing.withRetry(
8753
+ * () => unreliableApi(),
8754
+ * { maxRetries: 3, delay: 1000, backoff: "exponential" }
8755
+ * );
8756
+ * ```
8757
+ */
8758
+ /**
8759
+ * Generate a random delay within a range.
8760
+ *
8761
+ * @param min - Minimum delay in milliseconds
8762
+ * @param max - Maximum delay in milliseconds
8763
+ * @returns Random integer between min and max (inclusive)
8764
+ *
8765
+ * @example
8766
+ * ```typescript
8767
+ * const delay = randomDelay(50, 150); // e.g., 87
8768
+ * ```
8769
+ */
8770
+ declare function randomDelay(min: number, max: number): number;
8771
+ /**
8772
+ * Sleep for a random duration (for human-like timing).
8773
+ *
8774
+ * Useful for browser automation to appear more human-like.
8775
+ *
8776
+ * @param min - Minimum delay in milliseconds (default: 50)
8777
+ * @param max - Maximum delay in milliseconds (default: 150)
8778
+ * @returns Promise that resolves after the random delay
8779
+ *
8780
+ * @example
8781
+ * ```typescript
8782
+ * // Default human-like delay (50-150ms)
8783
+ * await humanDelay();
8784
+ *
8785
+ * // Custom range for slower actions
8786
+ * await humanDelay(100, 300);
8787
+ * ```
8788
+ */
8789
+ declare function humanDelay(min?: number, max?: number): Promise<void>;
8790
+ /**
8791
+ * Execute an async function with a timeout.
8792
+ *
8793
+ * @param fn - Async function to execute
8794
+ * @param timeoutMs - Timeout in milliseconds
8795
+ * @param signal - Optional AbortSignal for early cancellation
8796
+ * @returns Promise that resolves with the function result or rejects on timeout
8797
+ * @throws Error with "Operation timed out" message if timeout is exceeded
8798
+ *
8799
+ * @example
8800
+ * ```typescript
8801
+ * const result = await withTimeout(
8802
+ * () => fetch("https://api.example.com/data"),
8803
+ * 5000
8804
+ * );
8805
+ *
8806
+ * // With abort signal
8807
+ * const controller = new AbortController();
8808
+ * const result = await withTimeout(
8809
+ * () => longRunningTask(),
8810
+ * 30000,
8811
+ * controller.signal
8812
+ * );
8813
+ * ```
8814
+ */
8815
+ declare function withTimeout<T>(fn: () => Promise<T>, timeoutMs: number, signal?: AbortSignal): Promise<T>;
8816
+ /**
8817
+ * Options for retry logic.
8818
+ */
8819
+ interface RetryOptions {
8820
+ /** Maximum number of retry attempts (default: 3) */
8821
+ maxRetries?: number;
8822
+ /** Initial delay between retries in milliseconds (default: 1000) */
8823
+ delay?: number;
8824
+ /** Backoff strategy: "linear" adds delay, "exponential" doubles it (default: "exponential") */
8825
+ backoff?: "linear" | "exponential";
8826
+ /** Maximum delay cap in milliseconds (default: 30000) */
8827
+ maxDelay?: number;
8828
+ /** Optional function to determine if error is retryable (default: all errors) */
8829
+ shouldRetry?: (error: unknown, attempt: number) => boolean;
8830
+ /** Optional callback on each retry attempt */
8831
+ onRetry?: (error: unknown, attempt: number, delay: number) => void;
8832
+ }
8833
+ /**
8834
+ * Execute an async function with retry logic.
8835
+ *
8836
+ * @param fn - Async function to execute
8837
+ * @param options - Retry options
8838
+ * @returns Promise that resolves with the function result or rejects after all retries exhausted
8839
+ *
8840
+ * @example
8841
+ * ```typescript
8842
+ * // Basic retry with defaults (3 retries, exponential backoff)
8843
+ * const result = await withRetry(() => unreliableApi());
8844
+ *
8845
+ * // Custom retry configuration
8846
+ * const result = await withRetry(
8847
+ * () => fetchWithErrors(),
8848
+ * {
8849
+ * maxRetries: 5,
8850
+ * delay: 500,
8851
+ * backoff: "exponential",
8852
+ * shouldRetry: (error) => error.status === 429 || error.status >= 500,
8853
+ * onRetry: (error, attempt, delay) => {
8854
+ * console.log(`Retry ${attempt} after ${delay}ms`);
8855
+ * }
8856
+ * }
8857
+ * );
8858
+ * ```
8859
+ */
8860
+ declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
8861
+ /**
8862
+ * Timing namespace object for convenient access.
8863
+ *
8864
+ * @example
8865
+ * ```typescript
8866
+ * import { timing } from "llmist";
8867
+ *
8868
+ * await timing.humanDelay();
8869
+ * const result = await timing.withTimeout(() => fetch(url), 5000);
8870
+ * const data = await timing.withRetry(() => api.call(), { maxRetries: 3 });
8871
+ * ```
8872
+ */
8873
+ declare const timing: {
8874
+ readonly randomDelay: typeof randomDelay;
8875
+ readonly humanDelay: typeof humanDelay;
8876
+ readonly withTimeout: typeof withTimeout;
8877
+ readonly withRetry: typeof withRetry;
8878
+ };
8879
+
8880
+ /**
8881
+ * Session management interface and base class for gadget packages.
8882
+ *
8883
+ * Provides a standardized way to manage sessions (browser instances, API clients, etc.)
8884
+ * across gadgets. This enables:
8885
+ * - Consistent session lifecycle management
8886
+ * - Per-agent session isolation
8887
+ * - Automatic cleanup
8888
+ *
8889
+ * @module session/manager
8890
+ *
8891
+ * @example
8892
+ * ```typescript
8893
+ * import { BaseSessionManager, ISessionManager } from "llmist";
8894
+ *
8895
+ * // Extend for browser sessions
8896
+ * class BrowserSessionManager extends BaseSessionManager<Page, BrowserConfig> {
8897
+ * async createSession(config?: BrowserConfig): Promise<string> {
8898
+ * const browser = await launchBrowser(config);
8899
+ * const page = await browser.newPage();
8900
+ * const id = this.generateId("p");
8901
+ * this.sessions.set(id, page);
8902
+ * return id;
8903
+ * }
8904
+ *
8905
+ * async closeSession(id: string): Promise<void> {
8906
+ * const page = this.sessions.get(id);
8907
+ * if (page) {
8908
+ * await page.close();
8909
+ * this.sessions.delete(id);
8910
+ * }
8911
+ * }
8912
+ * }
8913
+ * ```
8914
+ */
8915
+ /**
8916
+ * Interface for session managers.
8917
+ *
8918
+ * Session managers track and manage external resources (browser pages, API connections, etc.)
8919
+ * that need to be shared across multiple gadgets and properly cleaned up.
8920
+ *
8921
+ * @typeParam TSession - Type of session object (e.g., Page, APIClient)
8922
+ * @typeParam TConfig - Configuration type for creating sessions
8923
+ */
8924
+ interface ISessionManager<TSession = unknown, TConfig = unknown> {
8925
+ /**
8926
+ * Create a new session.
8927
+ *
8928
+ * @param config - Optional configuration for the session
8929
+ * @returns Promise resolving to the session ID
8930
+ */
8931
+ createSession(config?: TConfig): Promise<string>;
8932
+ /**
8933
+ * Get a session by ID.
8934
+ *
8935
+ * @param id - Session ID
8936
+ * @returns Session object or undefined if not found
8937
+ */
8938
+ getSession(id: string): TSession | undefined;
8939
+ /**
8940
+ * Get a session by ID, throwing if not found.
8941
+ *
8942
+ * @param id - Session ID
8943
+ * @returns Session object
8944
+ * @throws Error if session not found
8945
+ */
8946
+ requireSession(id: string): TSession;
8947
+ /**
8948
+ * Close and remove a session.
8949
+ *
8950
+ * @param id - Session ID to close
8951
+ */
8952
+ closeSession(id: string): Promise<void>;
8953
+ /**
8954
+ * Close all sessions.
8955
+ */
8956
+ closeAll(): Promise<void>;
8957
+ /**
8958
+ * List all active session IDs.
8959
+ *
8960
+ * @returns Array of session IDs
8961
+ */
8962
+ listSessions(): string[];
8963
+ /**
8964
+ * Check if a session exists.
8965
+ *
8966
+ * @param id - Session ID
8967
+ * @returns True if session exists
8968
+ */
8969
+ hasSession(id: string): boolean;
8970
+ }
8971
+ /**
8972
+ * Base implementation of session manager with common functionality.
8973
+ *
8974
+ * Extend this class to create domain-specific session managers.
8975
+ * You only need to implement `createSession` and `closeSession`.
8976
+ *
8977
+ * @typeParam TSession - Type of session object
8978
+ * @typeParam TConfig - Configuration type for creating sessions
8979
+ *
8980
+ * @example
8981
+ * ```typescript
8982
+ * class APIClientManager extends BaseSessionManager<APIClient, APIConfig> {
8983
+ * async createSession(config?: APIConfig): Promise<string> {
8984
+ * const client = new APIClient(config);
8985
+ * const id = this.generateId("api");
8986
+ * this.sessions.set(id, client);
8987
+ * return id;
8988
+ * }
8989
+ *
8990
+ * async closeSession(id: string): Promise<void> {
8991
+ * const client = this.sessions.get(id);
8992
+ * if (client) {
8993
+ * await client.disconnect();
8994
+ * this.sessions.delete(id);
8995
+ * }
8996
+ * }
8997
+ * }
8998
+ * ```
8999
+ */
9000
+ declare abstract class BaseSessionManager<TSession, TConfig = unknown> implements ISessionManager<TSession, TConfig> {
9001
+ /** Map of session ID to session object */
9002
+ protected sessions: Map<string, TSession>;
9003
+ /** Counter for generating unique session IDs */
9004
+ protected idCounter: number;
9005
+ /**
9006
+ * Generate a unique session ID with the given prefix.
9007
+ *
9008
+ * @param prefix - Prefix for the ID (e.g., "p" for pages, "b" for browsers)
9009
+ * @returns Unique ID like "p1", "p2", etc.
9010
+ */
9011
+ protected generateId(prefix: string): string;
9012
+ /**
9013
+ * Create a new session.
9014
+ * Must be implemented by subclasses.
9015
+ */
9016
+ abstract createSession(config?: TConfig): Promise<string>;
9017
+ /**
9018
+ * Close and remove a session.
9019
+ * Must be implemented by subclasses.
9020
+ */
9021
+ abstract closeSession(id: string): Promise<void>;
9022
+ /**
9023
+ * Get a session by ID.
9024
+ */
9025
+ getSession(id: string): TSession | undefined;
9026
+ /**
9027
+ * Get a session by ID, throwing if not found.
9028
+ */
9029
+ requireSession(id: string): TSession;
9030
+ /**
9031
+ * List all active session IDs.
9032
+ */
9033
+ listSessions(): string[];
9034
+ /**
9035
+ * Check if a session exists.
9036
+ */
9037
+ hasSession(id: string): boolean;
9038
+ /**
9039
+ * Close all sessions.
9040
+ * Closes sessions in reverse order (most recent first).
9041
+ */
9042
+ closeAll(): Promise<void>;
9043
+ }
9044
+ /**
9045
+ * Simple in-memory session manager for testing or lightweight use cases.
9046
+ *
9047
+ * Sessions are just stored objects with no special cleanup logic.
9048
+ *
9049
+ * @example
9050
+ * ```typescript
9051
+ * const manager = new SimpleSessionManager<MyData>();
9052
+ * const id = await manager.createSession({ value: 42 });
9053
+ * const data = manager.requireSession(id); // { value: 42 }
9054
+ * await manager.closeSession(id);
9055
+ * ```
9056
+ */
9057
+ declare class SimpleSessionManager<TSession> extends BaseSessionManager<TSession, TSession> {
9058
+ /**
9059
+ * Create a session by storing the provided data.
9060
+ */
9061
+ createSession(data?: TSession): Promise<string>;
9062
+ /**
9063
+ * Close a session by removing it from the map.
9064
+ */
9065
+ closeSession(id: string): Promise<void>;
9066
+ /**
9067
+ * Set session data directly.
9068
+ */
9069
+ setSession(id: string, data: TSession): void;
9070
+ }
9071
+
9072
+ /**
9073
+ * Subagent creation helper for gadget authors.
9074
+ *
9075
+ * Simplifies the common pattern of creating subagents from within gadgets.
9076
+ * Handles:
9077
+ * - Getting host exports (AgentBuilder, LLMist) from context
9078
+ * - Model resolution with "inherit" support
9079
+ * - Parent context sharing for cost tracking
9080
+ * - Common configuration options
9081
+ *
9082
+ * @module agent/subagent
9083
+ *
9084
+ * @example
9085
+ * ```typescript
9086
+ * import { createSubagent, Gadget, z } from "llmist";
9087
+ * import type { ExecutionContext } from "llmist";
9088
+ *
9089
+ * class BrowseWeb extends Gadget({
9090
+ * name: "BrowseWeb",
9091
+ * schema: z.object({
9092
+ * task: z.string(),
9093
+ * url: z.string().url(),
9094
+ * model: z.string().optional(),
9095
+ * }),
9096
+ * }) {
9097
+ * async execute(params: this["params"], ctx?: ExecutionContext) {
9098
+ * const agent = createSubagent(ctx!, {
9099
+ * name: "BrowseWeb",
9100
+ * gadgets: [Navigate, Click, Screenshot],
9101
+ * systemPrompt: BROWSER_SYSTEM_PROMPT,
9102
+ * model: params.model, // Optional override
9103
+ * maxIterations: 15,
9104
+ * }).ask(params.task);
9105
+ *
9106
+ * for await (const event of agent.run()) {
9107
+ * // Process events...
9108
+ * }
9109
+ *
9110
+ * return result;
9111
+ * }
9112
+ * }
9113
+ * ```
9114
+ */
9115
+
9116
+ /**
9117
+ * Options for creating a subagent.
9118
+ */
9119
+ interface SubagentOptions {
9120
+ /**
9121
+ * Name of the subagent (used for config resolution).
9122
+ * Should match the gadget name in CLI config, e.g., "BrowseWeb".
9123
+ */
9124
+ name: string;
9125
+ /**
9126
+ * Gadgets to register with the subagent.
9127
+ */
9128
+ gadgets: AbstractGadget[];
9129
+ /**
9130
+ * System prompt for the subagent.
9131
+ */
9132
+ systemPrompt?: string;
9133
+ /**
9134
+ * Model to use. If not provided, inherits from parent or uses default.
9135
+ * Can be a runtime parameter from gadget params.
9136
+ */
9137
+ model?: string;
9138
+ /**
9139
+ * Default model if no other source provides one.
9140
+ * @default "sonnet"
9141
+ */
9142
+ defaultModel?: string;
9143
+ /**
9144
+ * Maximum iterations for the agent loop.
9145
+ */
9146
+ maxIterations?: number;
9147
+ /**
9148
+ * Default max iterations if not specified.
9149
+ * @default 15
9150
+ */
9151
+ defaultMaxIterations?: number;
9152
+ /**
9153
+ * Agent hooks for observers, interceptors, controllers.
9154
+ */
9155
+ hooks?: AgentHooks;
9156
+ /**
9157
+ * Temperature for LLM calls.
9158
+ */
9159
+ temperature?: number;
9160
+ }
9161
+ /**
9162
+ * Create a subagent from within a gadget.
9163
+ *
9164
+ * This helper simplifies the common pattern of creating nested agents.
9165
+ * It automatically:
9166
+ * - Gets the correct AgentBuilder from host exports
9167
+ * - Resolves model with "inherit" support from CLI config
9168
+ * - Shares the parent's execution tree for cost tracking
9169
+ * - Forwards the abort signal for proper cancellation
9170
+ *
9171
+ * @param ctx - ExecutionContext passed to gadget's execute()
9172
+ * @param options - Subagent configuration options
9173
+ * @returns Configured AgentBuilder ready for .ask()
9174
+ *
9175
+ * @example
9176
+ * ```typescript
9177
+ * // Basic usage
9178
+ * const agent = createSubagent(ctx, {
9179
+ * name: "BrowseWeb",
9180
+ * gadgets: [Navigate, Click],
9181
+ * }).ask("Go to google.com");
9182
+ *
9183
+ * // With all options
9184
+ * const agent = createSubagent(ctx, {
9185
+ * name: "BrowseWeb",
9186
+ * gadgets: [Navigate, Click, Screenshot],
9187
+ * systemPrompt: "You are a browser automation agent...",
9188
+ * model: params.model, // Runtime override
9189
+ * defaultModel: "sonnet",
9190
+ * maxIterations: 20,
9191
+ * hooks: {
9192
+ * observers: {
9193
+ * onLLMCallReady: () => refreshPageState(),
9194
+ * },
9195
+ * },
9196
+ * }).ask(params.task);
9197
+ *
9198
+ * for await (const event of agent.run()) {
9199
+ * // Events flow through shared tree automatically
9200
+ * }
9201
+ * ```
9202
+ */
9203
+ declare function createSubagent(ctx: ExecutionContext, options: SubagentOptions): AgentBuilder;
9204
+ /**
9205
+ * Check if an execution context has valid host exports.
9206
+ *
9207
+ * Useful for conditional logic when gadgets may run standalone or via agent.
9208
+ *
9209
+ * @param ctx - Execution context
9210
+ * @returns True if host exports are available
9211
+ */
9212
+ declare function hasHostExports(ctx?: ExecutionContext): boolean;
9213
+
9214
+ /**
9215
+ * Package manifest types for llmist gadget packages.
9216
+ *
9217
+ * These types define the structure of the `llmist` field in package.json
9218
+ * for gadget packages. This enables:
9219
+ * - Preset-based gadget loading
9220
+ * - Subagent discovery
9221
+ * - Factory function support
9222
+ * - Session management metadata
9223
+ *
9224
+ * @module package/manifest
9225
+ *
9226
+ * @example package.json
9227
+ * ```json
9228
+ * {
9229
+ * "name": "dhalsim",
9230
+ * "llmist": {
9231
+ * "gadgets": "./dist/index.js",
9232
+ * "factory": "./dist/index.js",
9233
+ * "presets": {
9234
+ * "minimal": ["Navigate", "GetFullPageContent"],
9235
+ * "readonly": ["Navigate", "GetFullPageContent", "Screenshot"],
9236
+ * "all": "*"
9237
+ * },
9238
+ * "subagents": {
9239
+ * "BrowseWeb": {
9240
+ * "entryPoint": "./dist/index.js",
9241
+ * "export": "Dhalsim",
9242
+ * "description": "Autonomous web browser agent",
9243
+ * "defaultModel": "sonnet",
9244
+ * "maxIterations": 15
9245
+ * }
9246
+ * },
9247
+ * "session": {
9248
+ * "factory": "getSessionManager",
9249
+ * "type": "browser"
9250
+ * }
9251
+ * }
9252
+ * }
9253
+ * ```
9254
+ */
9255
+ /**
9256
+ * Subagent definition in the manifest.
9257
+ */
9258
+ interface SubagentManifestEntry {
9259
+ /**
9260
+ * Entry point file path relative to package root.
9261
+ * @example "./dist/index.js"
9262
+ */
9263
+ entryPoint: string;
9264
+ /**
9265
+ * Export name from the entry point.
9266
+ * @example "Dhalsim" or "BrowseWeb"
9267
+ */
9268
+ export: string;
9269
+ /**
9270
+ * Human-readable description of what this subagent does.
9271
+ */
9272
+ description?: string;
9273
+ /**
9274
+ * List of gadget names this subagent uses internally.
9275
+ * Useful for documentation and dependency tracking.
9276
+ */
9277
+ uses?: string[];
9278
+ /**
9279
+ * Default model for this subagent.
9280
+ * Can be "inherit" to use parent's model.
9281
+ * @default "inherit"
9282
+ */
9283
+ defaultModel?: string;
9284
+ /**
9285
+ * Default maximum iterations.
9286
+ * @default 15
9287
+ */
9288
+ maxIterations?: number;
9289
+ }
9290
+ /**
9291
+ * Session factory metadata in the manifest.
9292
+ */
9293
+ interface SessionManifestEntry {
9294
+ /**
9295
+ * Export name of the session factory function.
9296
+ * @example "getSessionManager"
9297
+ */
9298
+ factory: string;
9299
+ /**
9300
+ * Type of session for categorization.
9301
+ * @example "browser", "api", "database"
9302
+ */
9303
+ type: string;
9304
+ }
9305
+ /**
9306
+ * Preset definition - either an array of gadget names or "*" for all.
9307
+ */
9308
+ type PresetDefinition = string[] | "*";
9309
+ /**
9310
+ * llmist package manifest structure.
9311
+ *
9312
+ * This is the shape of the `llmist` field in package.json
9313
+ * for gadget packages.
9314
+ */
9315
+ interface LLMistPackageManifest {
9316
+ /**
9317
+ * Entry point for all gadgets.
9318
+ * The module should export gadgets or a gadgets array.
9319
+ * @example "./dist/index.js"
9320
+ */
9321
+ gadgets?: string;
9322
+ /**
9323
+ * Entry point for factory functions.
9324
+ * Should export `createGadgetsByPreset(preset)` and/or `createGadgetsByName(names)`.
9325
+ * @example "./dist/index.js"
9326
+ */
9327
+ factory?: string;
9328
+ /**
9329
+ * Subagent definitions.
9330
+ * Key is the subagent name as it appears in CLI config.
9331
+ */
9332
+ subagents?: Record<string, SubagentManifestEntry>;
9333
+ /**
9334
+ * Preset definitions.
9335
+ * Key is preset name, value is array of gadget names or "*" for all.
9336
+ * @example { "minimal": ["Navigate", "Screenshot"], "all": "*" }
9337
+ */
9338
+ presets?: Record<string, PresetDefinition>;
9339
+ /**
9340
+ * Session factory metadata.
9341
+ */
9342
+ session?: SessionManifestEntry;
9343
+ }
9344
+ /**
9345
+ * Factory function types that packages can export.
9346
+ */
9347
+ interface GadgetFactoryExports {
9348
+ /**
9349
+ * Create gadgets by preset name.
9350
+ */
9351
+ createGadgetsByPreset?: (preset: string, config?: unknown) => unknown;
9352
+ /**
9353
+ * Create gadgets by specific names.
9354
+ */
9355
+ createGadgetsByName?: (names: string[], config?: unknown) => unknown;
9356
+ /**
9357
+ * Create all gadgets with optional config.
9358
+ */
9359
+ createGadgets?: (config?: unknown) => unknown;
9360
+ }
9361
+ /**
9362
+ * Read and parse the llmist manifest from a package.json object.
9363
+ *
9364
+ * @param packageJson - Parsed package.json object
9365
+ * @returns Manifest or undefined if not present
9366
+ *
9367
+ * @example
9368
+ * ```typescript
9369
+ * import { readFileSync } from "fs";
9370
+ *
9371
+ * const pkg = JSON.parse(readFileSync("package.json", "utf-8"));
9372
+ * const manifest = parseManifest(pkg);
9373
+ *
9374
+ * if (manifest?.presets?.minimal) {
9375
+ * console.log("Minimal preset:", manifest.presets.minimal);
9376
+ * }
9377
+ * ```
9378
+ */
9379
+ declare function parseManifest(packageJson: Record<string, unknown>): LLMistPackageManifest | undefined;
9380
+ /**
9381
+ * Check if a manifest has a specific preset.
9382
+ */
9383
+ declare function hasPreset(manifest: LLMistPackageManifest | undefined, presetName: string): boolean;
9384
+ /**
9385
+ * Get gadget names for a preset.
9386
+ * Returns undefined if preset not found, empty array if preset is invalid.
9387
+ */
9388
+ declare function getPresetGadgets(manifest: LLMistPackageManifest | undefined, presetName: string): string[] | "*" | undefined;
9389
+ /**
9390
+ * Check if a manifest has subagent definitions.
9391
+ */
9392
+ declare function hasSubagents(manifest: LLMistPackageManifest | undefined): boolean;
9393
+ /**
9394
+ * Get subagent entry by name.
9395
+ */
9396
+ declare function getSubagent(manifest: LLMistPackageManifest | undefined, name: string): SubagentManifestEntry | undefined;
9397
+ /**
9398
+ * List all subagent names in a manifest.
9399
+ */
9400
+ declare function listSubagents(manifest: LLMistPackageManifest | undefined): string[];
9401
+ /**
9402
+ * List all preset names in a manifest.
9403
+ */
9404
+ declare function listPresets(manifest: LLMistPackageManifest | undefined): string[];
9405
+
8537
9406
  /**
8538
9407
  * Get host llmist exports from execution context.
8539
9408
  *
@@ -8573,4 +9442,4 @@ declare function createOpenAIProviderFromEnv(): OpenAIChatProvider | null;
8573
9442
  */
8574
9443
  declare function getHostExports(ctx: ExecutionContext): HostExports;
8575
9444
 
8576
- export { AbortException, AbstractGadget, type AddGadgetParams, type AddLLMCallParams, type AfterGadgetExecutionAction, type AfterGadgetExecutionControllerContext, type AfterLLMCallAction, type AfterLLMCallControllerContext, type AfterLLMErrorAction, Agent, AgentBuilder, type AgentHooks, type AgentOptions, AnthropicMessagesProvider, type AudioContentPart, type AudioMimeType, type AudioSource, type BaseExecutionEvent, type BeforeGadgetExecutionAction, type BeforeLLMCallAction, type ChunkInterceptorContext, type CompactionConfig, type CompactionContext, type CompactionEvent, CompactionManager, type CompactionResult, type CompactionStats, type CompactionStrategy, type CompleteGadgetParams, type CompleteLLMCallParams, type ContentPart, type Controllers, ConversationManager, type CostEstimate, type CostReportingLLMist, type CreateGadgetConfig, DEFAULT_COMPACTION_CONFIG, DEFAULT_HINTS, DEFAULT_PROMPTS, DEFAULT_RETRY_CONFIG, DEFAULT_SUMMARIZATION_PROMPT, type EventHandlers, type ExecutionContext, type ExecutionEvent, type ExecutionEventType, type ExecutionNode, type ExecutionNodeType, ExecutionTree, FALLBACK_CHARS_PER_TOKEN, GADGET_ARG_PREFIX, GADGET_END_PREFIX, GADGET_START_PREFIX, Gadget, type GadgetCallEvent, GadgetCallParser, type GadgetClass, type GadgetCompleteEvent, type GadgetConfig, type GadgetErrorEvent, type GadgetEvent, type GadgetExample, type GadgetExecuteResult, type GadgetExecuteResultWithMedia, type GadgetExecuteReturn, type GadgetExecutionControllerContext, type GadgetExecutionResult, GadgetExecutor, type GadgetMediaOutput, type GadgetNode, type GadgetOrClass, GadgetOutputStore, type GadgetParameterInterceptorContext, GadgetRegistry, type GadgetResultInterceptorContext, type GadgetSkippedEvent, type GadgetStartEvent, type GadgetState, GeminiGenerativeProvider, type HintContext, type HintTemplate, type HintsConfig, type HistoryMessage, HookPresets, type HostExports, type HumanInputRequiredEvent, HumanInputRequiredException, HybridStrategy, type IConversationManager, type ImageBase64Source, type ImageContentPart, type ImageGenerationOptions, type ImageGenerationResult, type ImageMimeType, type ImageModelSpec, type ImageSource, type ImageUrlSource, type Interceptors, type IterationHintOptions, type LLMCallCompleteEvent, type LLMCallControllerContext, type LLMCallErrorEvent, type LLMCallInfo, type LLMCallNode, type LLMCallStartEvent, type LLMCallStreamEvent, type LLMErrorControllerContext, type LLMEvent, type LLMGenerationOptions, type LLMMessage, LLMMessageBuilder, type LLMStream, type LLMStreamChunk, LLMist, type LLMistOptions, type LoggerOptions, type LoggingOptions, MODEL_ALIASES, type MediaKind, type MediaMetadata, MediaStore, type MessageContent, type MessageInterceptorContext, type MessageRole, type MessageTurn, type ModelDescriptor, type ModelFeatures, ModelIdentifierParser, type ModelLimits, type ModelPricing, ModelRegistry, type ModelSpec, type NodeId, type ObserveChunkContext, type ObserveCompactionContext, type ObserveGadgetCompleteContext, type ObserveGadgetStartContext, type ObserveLLMCallContext, type ObserveLLMCompleteContext, type ObserveLLMErrorContext, type Observers, OpenAIChatProvider, type ParallelGadgetHintOptions, type ParsedGadgetCall, type PromptContext, type PromptTemplate, type PromptTemplateConfig, type ProviderAdapter, type ProviderIdentifier, type ResolveValueOptions, type ResolvedCompactionConfig, type ResolvedRetryConfig, type RetryConfig, SlidingWindowStrategy, type SpeechGenerationOptions, type SpeechGenerationResult, type SpeechModelSpec, type StoredMedia, type StoredOutput, type StreamCompleteEvent, type StreamEvent, type StreamProcessingResult, StreamProcessor, type StreamProcessorOptions, type SubagentConfig, type SubagentConfigMap, type SubagentContext, type SubagentEvent, type SubagentStreamEvent, SummarizationStrategy, TaskCompletionSignal, type TextContentPart, type TextEvent, type TextGenerationOptions, type TextOnlyAction, type TextOnlyContext, type TextOnlyCustomHandler, type TextOnlyGadgetConfig, type TextOnlyHandler, type TextOnlyStrategy, TimeoutException, type TokenUsage, type TrailingMessage, type TrailingMessageContext, type CompactionEvent$1 as TreeCompactionEvent, type GadgetSkippedEvent$1 as TreeGadgetSkippedEvent, type ValidationIssue, type ValidationResult, type VisionAnalyzeOptions, type VisionAnalyzeResult, audioFromBase64, audioFromBuffer, collectEvents, collectText, complete, createAnthropicProviderFromEnv, createGadget, createGadgetOutputViewer, createGeminiProviderFromEnv, createHints, createLogger, createMediaOutput, createOpenAIProviderFromEnv, defaultLogger, detectAudioMimeType, detectImageMimeType, discoverProviderAdapters, extractMessageText, filterByDepth, filterByParent, filterRootEvents, formatLLMError, getHostExports, getModelId, getProvider, groupByParent, hasProviderPrefix, imageFromBase64, imageFromBuffer, imageFromUrl, isAbortError, isAudioPart, isDataUrl, isGadgetEvent, isImagePart, isLLMEvent, isRetryableError, isRootEvent, isSubagentEvent, isTextPart, iterationProgressHint, normalizeMessageContent, parallelGadgetHint, parseDataUrl, resolveConfig, resolveHintTemplate, resolveModel, resolvePromptTemplate, resolveRetryConfig, resolveRulesTemplate, resolveSubagentModel, resolveValue, resultWithAudio, resultWithFile, resultWithImage, resultWithImages, resultWithMedia, runWithHandlers, schemaToJSONSchema, stream, text, toBase64, validateAndApplyDefaults, validateGadgetParams, validateGadgetSchema };
9445
+ export { AbortException, AbstractGadget, type AddGadgetParams, type AddLLMCallParams, type AfterGadgetExecutionAction, type AfterGadgetExecutionControllerContext, type AfterLLMCallAction, type AfterLLMCallControllerContext, type AfterLLMErrorAction, Agent, AgentBuilder, type AgentHooks, type AgentOptions, AnthropicMessagesProvider, type AudioContentPart, type AudioMimeType, type AudioSource, type BaseExecutionEvent, BaseSessionManager, type BeforeGadgetExecutionAction, type BeforeLLMCallAction, type ChunkInterceptorContext, type CompactionConfig, type CompactionContext, type CompactionEvent, CompactionManager, type CompactionResult, type CompactionStats, type CompactionStrategy, type CompleteGadgetParams, type CompleteLLMCallParams, type ContentPart, type Controllers, ConversationManager, type CostEstimate, type CostReportingLLMist, type CreateGadgetConfig, DEFAULT_COMPACTION_CONFIG, DEFAULT_HINTS, DEFAULT_PROMPTS, DEFAULT_RETRY_CONFIG, DEFAULT_SUMMARIZATION_PROMPT, type EventHandlers, type ExecutionContext, type ExecutionEvent, type ExecutionEventType, type ExecutionNode, type ExecutionNodeType, ExecutionTree, FALLBACK_CHARS_PER_TOKEN, GADGET_ARG_PREFIX, GADGET_END_PREFIX, GADGET_START_PREFIX, Gadget, type GadgetCallEvent, GadgetCallParser, type GadgetClass, type GadgetCompleteEvent, type GadgetConfig, type GadgetErrorEvent, type GadgetEvent, type GadgetExample, type GadgetExecuteResult, type GadgetExecuteResultWithMedia, type GadgetExecuteReturn, type GadgetExecutionControllerContext, type GadgetExecutionResult, GadgetExecutor, type GadgetFactoryExports, type GadgetMediaOutput, type GadgetNode, type GadgetOrClass, GadgetOutputStore, type GadgetParameterInterceptorContext, GadgetRegistry, type GadgetResultInterceptorContext, type GadgetSkippedEvent, type GadgetStartEvent, type GadgetState, GeminiGenerativeProvider, type HintContext, type HintTemplate, type HintsConfig, type HistoryMessage, HookPresets, type HostExports, type HumanInputRequiredEvent, HumanInputRequiredException, HybridStrategy, type IConversationManager, type ISessionManager, type ImageBase64Source, type ImageContentPart, type ImageGenerationOptions, type ImageGenerationResult, type ImageMimeType, type ImageModelSpec, type ImageSource, type ImageUrlSource, type Interceptors, type IterationHintOptions, type LLMCallCompleteEvent, type LLMCallControllerContext, type LLMCallErrorEvent, type LLMCallInfo, type LLMCallNode, type LLMCallStartEvent, type LLMCallStreamEvent, type LLMErrorControllerContext, type LLMEvent, type LLMGenerationOptions, type LLMMessage, LLMMessageBuilder, type LLMStream, type LLMStreamChunk, LLMist, type LLMistOptions, type LLMistPackageManifest, type LoggerOptions, type LoggingOptions, MODEL_ALIASES, type MediaKind, type MediaMetadata, MediaStore, type MessageContent, type MessageInterceptorContext, type MessageRole, type MessageTurn, type ModelDescriptor, type ModelFeatures, ModelIdentifierParser, type ModelLimits, type ModelPricing, ModelRegistry, type ModelSpec, type NodeId, type ObserveChunkContext, type ObserveCompactionContext, type ObserveGadgetCompleteContext, type ObserveGadgetStartContext, type ObserveLLMCallContext, type ObserveLLMCompleteContext, type ObserveLLMErrorContext, type Observers, OpenAIChatProvider, type ParallelGadgetHintOptions, type ParsedGadgetCall, type PresetDefinition, type PromptContext, type PromptTemplate, type PromptTemplateConfig, type ProviderAdapter, type ProviderIdentifier, type ResolveValueOptions, type ResolvedCompactionConfig, type ResolvedRetryConfig, type RetryConfig, type RetryOptions, type SessionManifestEntry, SimpleSessionManager, SlidingWindowStrategy, type SpeechGenerationOptions, type SpeechGenerationResult, type SpeechModelSpec, type StoredMedia, type StoredOutput, type StreamCompleteEvent, type StreamEvent, type StreamProcessingResult, StreamProcessor, type StreamProcessorOptions, type SubagentConfig, type SubagentConfigMap, type SubagentContext, type SubagentEvent, type SubagentManifestEntry, type SubagentOptions, type SubagentStreamEvent, SummarizationStrategy, TaskCompletionSignal, type TextContentPart, type TextEvent, type TextGenerationOptions, type TextOnlyAction, type TextOnlyContext, type TextOnlyCustomHandler, type TextOnlyGadgetConfig, type TextOnlyHandler, type TextOnlyStrategy, TimeoutException, type TokenUsage, type TrailingMessage, type TrailingMessageContext, type CompactionEvent$1 as TreeCompactionEvent, type GadgetSkippedEvent$1 as TreeGadgetSkippedEvent, type ValidationIssue, type ValidationResult, type VisionAnalyzeOptions, type VisionAnalyzeResult, audioFromBase64, audioFromBuffer, collectEvents, collectText, complete, createAnthropicProviderFromEnv, createGadget, createGadgetOutputViewer, createGeminiProviderFromEnv, createHints, createLogger, createMediaOutput, createOpenAIProviderFromEnv, createSubagent, defaultLogger, detectAudioMimeType, detectImageMimeType, discoverProviderAdapters, extractMessageText, filterByDepth, filterByParent, filterRootEvents, format, formatBytes, formatDate, formatDuration, formatLLMError, gadgetError, gadgetSuccess, getErrorMessage, getHostExports, getModelId, getPresetGadgets, getProvider, getSubagent, groupByParent, hasHostExports, hasPreset, hasProviderPrefix, hasSubagents, humanDelay, imageFromBase64, imageFromBuffer, imageFromUrl, isAbortError, isAudioPart, isDataUrl, isGadgetEvent, isImagePart, isLLMEvent, isRetryableError, isRootEvent, isSubagentEvent, isTextPart, iterationProgressHint, listPresets, listSubagents, normalizeMessageContent, parallelGadgetHint, parseDataUrl, parseManifest, randomDelay, resolveConfig, resolveHintTemplate, resolveModel, resolvePromptTemplate, resolveRetryConfig, resolveRulesTemplate, resolveSubagentModel, resolveValue, resultWithAudio, resultWithFile, resultWithImage, resultWithImages, resultWithMedia, runWithHandlers, schemaToJSONSchema, stream, text, timing, toBase64, truncate, validateAndApplyDefaults, validateGadgetParams, validateGadgetSchema, withErrorHandling, withRetry, withTimeout };