@mindstudio-ai/agent 0.1.21 → 0.1.23

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
@@ -50,6 +50,15 @@ interface AgentOptions {
50
50
  */
51
51
  reuseThreadId?: boolean;
52
52
  }
53
+ /** A debug log event emitted during streaming step execution. */
54
+ interface StepLogEvent {
55
+ /** Log message text. */
56
+ value: string;
57
+ /** Step display name, e.g. "Generate Image", "Scrape URL". */
58
+ tag: string;
59
+ /** Unix timestamp in milliseconds. */
60
+ ts: number;
61
+ }
53
62
  /** Options for a single step execution call. */
54
63
  interface StepExecutionOptions {
55
64
  /**
@@ -64,6 +73,16 @@ interface StepExecutionOptions {
64
73
  * history or variable state.
65
74
  */
66
75
  threadId?: string;
76
+ /**
77
+ * Called for each debug log event during step execution. When set, the SDK
78
+ * uses SSE streaming to receive real-time progress updates from the API.
79
+ * When omitted, the endpoint returns a single JSON response as before.
80
+ *
81
+ * Log content and frequency varies by step type — image generation emits
82
+ * 2-3 logs, scrape steps emit per-URL progress, LLM steps may emit model
83
+ * selection and token info.
84
+ */
85
+ onLog?: (event: StepLogEvent) => void;
67
86
  }
68
87
  /** Execution metadata returned alongside every step result. */
69
88
  interface StepExecutionMeta {
@@ -612,6 +631,17 @@ interface TableConfig {
612
631
  * (which need @@user@@ prefix handling) and for validation.
613
632
  */
614
633
  columns: AppDatabaseColumnSchema[];
634
+ /**
635
+ * Unique constraints declared via defineTable options.
636
+ * Each entry is an array of column names that form a unique constraint.
637
+ * e.g. [['email'], ['userId', 'orgId']]
638
+ */
639
+ unique?: string[][];
640
+ /**
641
+ * Default values for columns, applied client-side in push() and upsert().
642
+ * Explicit values in the input override defaults.
643
+ */
644
+ defaults?: Record<string, unknown>;
615
645
  /**
616
646
  * Execute one or more SQL queries against the managed database in a
617
647
  * single round trip. All queries run on the same SQLite connection,
@@ -716,6 +746,7 @@ declare class Query<T> implements PromiseLike<T[]> {
716
746
  */
717
747
  static _processResults<T>(result: SqlResult, compiled: CompiledQuery<T>): T[];
718
748
  then<TResult1 = T[], TResult2 = never>(onfulfilled?: ((value: T[]) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
749
+ catch<TResult2 = never>(onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<T[] | TResult2>;
719
750
  private _execute;
720
751
  private _compilePredicates;
721
752
  private _fetchAndFilterInJs;
@@ -794,6 +825,7 @@ declare class Mutation<TResult> implements PromiseLike<TResult> {
794
825
  */
795
826
  static fromExecutor<T>(config: TableConfig, executor: () => Promise<T>): Mutation<T>;
796
827
  then<T1 = TResult, T2 = never>(onfulfilled?: ((value: TResult) => T1 | PromiseLike<T1>) | null, onrejected?: ((reason: unknown) => T2 | PromiseLike<T2>) | null): Promise<T1 | T2>;
828
+ catch<T2 = never>(onrejected?: ((reason: unknown) => T2 | PromiseLike<T2>) | null): Promise<TResult | T2>;
797
829
  /**
798
830
  * @internal Compile this mutation into SQL for batch execution.
799
831
  * Returns the queries and a result processor.
@@ -859,6 +891,20 @@ declare class Table<T> {
859
891
  */
860
892
  removeAll(predicate: Predicate<T>): Mutation<number>;
861
893
  clear(): Mutation<void>;
894
+ /**
895
+ * Insert a row, or update it if a row with the same unique key already
896
+ * exists. The conflict key must match a `unique` constraint declared in
897
+ * defineTable options. Returns the created or updated row.
898
+ *
899
+ * Uses SQLite's `INSERT ... ON CONFLICT ... DO UPDATE SET ... RETURNING *`.
900
+ *
901
+ * @param conflictKey - Column name(s) that form the unique constraint.
902
+ * Pass a single string for single-column unique, or an array for compound.
903
+ * @param data - Row data to insert (or update on conflict). Defaults apply.
904
+ */
905
+ upsert(conflictKey: (keyof Omit<T, SystemFields> & string) | (keyof Omit<T, SystemFields> & string)[], data: PushInput<T>): Mutation<T>;
906
+ /** @internal Validate that the given columns match a declared unique constraint. */
907
+ private _validateUniqueConstraint;
862
908
  }
863
909
 
864
910
  /**
@@ -912,7 +958,7 @@ declare class Table<T> {
912
958
  /**
913
959
  * Options for `db.defineTable()`.
914
960
  */
915
- interface DefineTableOptions {
961
+ interface DefineTableOptions<T = unknown> {
916
962
  /**
917
963
  * Database name or ID to target. Required when the app has multiple
918
964
  * databases and the table name alone is ambiguous.
@@ -925,6 +971,39 @@ interface DefineTableOptions {
925
971
  * - Multiple databases → searched by table name
926
972
  */
927
973
  database?: string;
974
+ /**
975
+ * Unique constraints for the table. Each entry is an array of column
976
+ * names that together must be unique. The SDK communicates these to
977
+ * the platform which creates the corresponding SQLite UNIQUE indexes.
978
+ *
979
+ * Required for `upsert()` — the conflict key must match a declared
980
+ * unique constraint.
981
+ *
982
+ * @example
983
+ * ```ts
984
+ * // Single column unique
985
+ * db.defineTable<User>('users', { unique: [['email']] });
986
+ *
987
+ * // Compound unique
988
+ * db.defineTable<Membership>('memberships', { unique: [['userId', 'orgId']] });
989
+ *
990
+ * // Multiple constraints
991
+ * db.defineTable<User>('users', { unique: [['email'], ['slug']] });
992
+ * ```
993
+ */
994
+ unique?: (keyof T & string)[][];
995
+ /**
996
+ * Default values for columns, applied client-side in `push()` and
997
+ * `upsert()`. Explicit values in the input override defaults.
998
+ *
999
+ * @example
1000
+ * ```ts
1001
+ * db.defineTable<Order>('orders', {
1002
+ * defaults: { status: 'pending', retryCount: 0 },
1003
+ * });
1004
+ * ```
1005
+ */
1006
+ defaults?: Partial<Omit<T, SystemFields>>;
928
1007
  }
929
1008
 
930
1009
  /**
@@ -955,7 +1034,7 @@ interface Db {
955
1034
  * const Orders = db.defineTable<Order>('orders', { database: 'main' });
956
1035
  * ```
957
1036
  */
958
- defineTable<T>(name: string, options?: DefineTableOptions): Table<T & SystemColumns>;
1037
+ defineTable<T>(name: string, options?: DefineTableOptions<T>): Table<T & SystemColumns>;
959
1038
  /** Returns the current time as a unix timestamp (ms). Equivalent to `Date.now()`. */
960
1039
  now(): number;
961
1040
  /** Returns milliseconds for n days. Composable with `+`. */
@@ -1067,6 +1146,11 @@ declare class MindStudioAgent$1 {
1067
1146
  * ```
1068
1147
  */
1069
1148
  executeStep<TOutput = unknown>(stepType: string, step: Record<string, unknown>, options?: StepExecutionOptions): Promise<StepExecutionResult<TOutput>>;
1149
+ /**
1150
+ * @internal Streaming step execution — sends `Accept: text/event-stream`
1151
+ * and parses SSE events for real-time debug logs.
1152
+ */
1153
+ private _executeStepStreaming;
1070
1154
  /**
1071
1155
  * Execute multiple steps in parallel in a single request.
1072
1156
  *
@@ -2506,10 +2590,7 @@ interface FetchYoutubeChannelStepInput {
2506
2590
  /** YouTube channel URL (e.g. https://www.youtube.com/@ChannelName or /channel/ID) */
2507
2591
  channelUrl: string;
2508
2592
  }
2509
- interface FetchYoutubeChannelStepOutput {
2510
- /** Channel metadata and video listings */
2511
- channel: Record<string, unknown>;
2512
- }
2593
+ type FetchYoutubeChannelStepOutput = Record<string, unknown>;
2513
2594
  interface FetchYoutubeCommentsStepInput {
2514
2595
  /** YouTube video URL to fetch comments for */
2515
2596
  videoUrl: string;
@@ -2545,10 +2626,7 @@ interface FetchYoutubeVideoStepInput {
2545
2626
  /** YouTube video URL to fetch metadata for */
2546
2627
  videoUrl: string;
2547
2628
  }
2548
- interface FetchYoutubeVideoStepOutput {
2549
- /** Video metadata including title, description, stats, and channel info */
2550
- video: Record<string, unknown>;
2551
- }
2629
+ type FetchYoutubeVideoStepOutput = Record<string, unknown>;
2552
2630
  interface GenerateChartStepInput {
2553
2631
  /** Chart configuration including type, data, and rendering options */
2554
2632
  chart: {
@@ -4318,10 +4396,7 @@ interface SearchYoutubeTrendsStepInput {
4318
4396
  /** Country code (e.g. "US") */
4319
4397
  gl: string;
4320
4398
  }
4321
- interface SearchYoutubeTrendsStepOutput {
4322
- /** Trending video data for the selected category and region */
4323
- trends: Record<string, unknown>;
4324
- }
4399
+ type SearchYoutubeTrendsStepOutput = Record<string, unknown>;
4325
4400
  interface SendEmailStepInput {
4326
4401
  /** Email subject line */
4327
4402
  subject: string;
@@ -7869,4 +7944,4 @@ declare const stream: (data: string | Record<string, unknown>) => Promise<void>;
7869
7944
  */
7870
7945
  declare const resolveUser: (userId: string) => Promise<ResolvedUser | null>;
7871
7946
 
7872
- export { type Accessor, type ActiveCampaignAddNoteStepInput, type ActiveCampaignAddNoteStepOutput, type ActiveCampaignCreateContactStepInput, type ActiveCampaignCreateContactStepOutput, type AddSubtitlesToVideoStepInput, type AddSubtitlesToVideoStepOutput, type AgentInfo, type AgentOptions, type AirtableCreateUpdateRecordStepInput, type AirtableCreateUpdateRecordStepOutput, type AirtableDeleteRecordStepInput, type AirtableDeleteRecordStepOutput, type AirtableGetRecordStepInput, type AirtableGetRecordStepOutput, type AirtableGetTableRecordsStepInput, type AirtableGetTableRecordsStepOutput, type AnalyzeImageStepInput, type AnalyzeImageStepOutput, type AnalyzeVideoStepInput, type AnalyzeVideoStepOutput, type AppAuthContext, type AppContextResult, type AppDatabase, type AppDatabaseColumnSchema, type AppDatabaseTable, type AppRoleAssignment, AuthContext, type BatchStepInput, type BatchStepResult, type CaptureThumbnailStepInput, type CaptureThumbnailStepOutput, type CheckAppRoleStepInput, type CheckAppRoleStepOutput, type CodaCreateUpdatePageStepInput, type CodaCreateUpdatePageStepOutput, type CodaCreateUpdateRowStepInput, type CodaCreateUpdateRowStepOutput, type CodaFindRowStepInput, type CodaFindRowStepOutput, type CodaGetPageStepInput, type CodaGetPageStepOutput, type CodaGetTableRowsStepInput, type CodaGetTableRowsStepOutput, type Connection, type ConnectorActionDetail, type ConnectorService, type ConvertPdfToImagesStepInput, type ConvertPdfToImagesStepOutput, type CreateDataSourceStepInput, type CreateDataSourceStepOutput, type CreateGmailDraftStepInput, type CreateGmailDraftStepOutput, type CreateGoogleCalendarEventStepInput, type CreateGoogleCalendarEventStepOutput, type CreateGoogleDocStepInput, type CreateGoogleDocStepOutput, type CreateGoogleSheetStepInput, type CreateGoogleSheetStepOutput, type Db, type DefineTableOptions, type DeleteDataSourceDocumentStepInput, type DeleteDataSourceDocumentStepOutput, type DeleteDataSourceStepInput, type DeleteDataSourceStepOutput, type DeleteGmailEmailStepInput, type DeleteGmailEmailStepOutput, type DeleteGoogleCalendarEventStepInput, type DeleteGoogleCalendarEventStepOutput, type DeleteGoogleSheetRowsStepInput, type DeleteGoogleSheetRowsStepOutput, type DetectChangesStepInput, type DetectChangesStepOutput, type DetectPIIStepInput, type DetectPIIStepOutput, type DiscordEditMessageStepInput, type DiscordEditMessageStepOutput, type DiscordSendFollowUpStepInput, type DiscordSendFollowUpStepOutput, type DiscordSendMessageStepInput, type DiscordSendMessageStepOutput, type DownloadVideoStepInput, type DownloadVideoStepOutput, type EnhanceImageGenerationPromptStepInput, type EnhanceImageGenerationPromptStepOutput, type EnhanceVideoGenerationPromptStepInput, type EnhanceVideoGenerationPromptStepOutput, type EnrichPersonStepInput, type EnrichPersonStepOutput, type ExecuteStepBatchOptions, type ExecuteStepBatchResult, type ExtractAudioFromVideoStepInput, type ExtractAudioFromVideoStepOutput, type ExtractTextStepInput, type ExtractTextStepOutput, type FetchDataSourceDocumentStepInput, type FetchDataSourceDocumentStepOutput, type FetchGoogleDocStepInput, type FetchGoogleDocStepOutput, type FetchGoogleSheetStepInput, type FetchGoogleSheetStepOutput, type FetchSlackChannelHistoryStepInput, type FetchSlackChannelHistoryStepOutput, type FetchYoutubeCaptionsStepInput, type FetchYoutubeCaptionsStepOutput, type FetchYoutubeChannelStepInput, type FetchYoutubeChannelStepOutput, type FetchYoutubeCommentsStepInput, type FetchYoutubeCommentsStepOutput, type FetchYoutubeVideoStepInput, type FetchYoutubeVideoStepOutput, type GenerateAssetStepInput, type GenerateAssetStepOutput, type GenerateChartStepInput, type GenerateChartStepOutput, type GenerateImageStepInput, type GenerateImageStepOutput, type GenerateLipsyncStepInput, type GenerateLipsyncStepOutput, type GenerateMusicStepInput, type GenerateMusicStepOutput, type GeneratePdfStepInput, type GeneratePdfStepOutput, type GenerateStaticVideoFromImageStepInput, type GenerateStaticVideoFromImageStepOutput, type GenerateTextStepInput, type GenerateTextStepOutput, type GenerateVideoStepInput, type GenerateVideoStepOutput, type GetGmailAttachmentsStepInput, type GetGmailAttachmentsStepOutput, type GetGmailDraftStepInput, type GetGmailDraftStepOutput, type GetGmailEmailStepInput, type GetGmailEmailStepOutput, type GetGmailUnreadCountStepInput, type GetGmailUnreadCountStepOutput, type GetGoogleCalendarEventStepInput, type GetGoogleCalendarEventStepOutput, type GetGoogleDriveFileStepInput, type GetGoogleDriveFileStepOutput, type GetGoogleSheetInfoStepInput, type GetGoogleSheetInfoStepOutput, type GetMediaMetadataStepInput, type GetMediaMetadataStepOutput, type HttpRequestStepInput, type HttpRequestStepOutput, type HubspotCreateCompanyStepInput, type HubspotCreateCompanyStepOutput, type HubspotCreateContactStepInput, type HubspotCreateContactStepOutput, type HubspotGetCompanyStepInput, type HubspotGetCompanyStepOutput, type HubspotGetContactStepInput, type HubspotGetContactStepOutput, type HunterApiCompanyEnrichmentStepInput, type HunterApiCompanyEnrichmentStepOutput, type HunterApiDomainSearchStepInput, type HunterApiDomainSearchStepOutput, type HunterApiEmailFinderStepInput, type HunterApiEmailFinderStepOutput, type HunterApiEmailVerificationStepInput, type HunterApiEmailVerificationStepOutput, type HunterApiPersonEnrichmentStepInput, type HunterApiPersonEnrichmentStepOutput, type ImageFaceSwapStepInput, type ImageFaceSwapStepOutput, type ImageRemoveWatermarkStepInput, type ImageRemoveWatermarkStepOutput, type InsertVideoClipsStepInput, type InsertVideoClipsStepOutput, type ListAgentsResult, type ListDataSourcesStepInput, type ListDataSourcesStepOutput, type ListGmailDraftsStepInput, type ListGmailDraftsStepOutput, type ListGmailLabelsStepInput, type ListGmailLabelsStepOutput, type ListGoogleCalendarEventsStepInput, type ListGoogleCalendarEventsStepOutput, type ListGoogleDriveFilesStepInput, type ListGoogleDriveFilesStepOutput, type ListRecentGmailEmailsStepInput, type ListRecentGmailEmailsStepOutput, type LogicStepInput, type LogicStepOutput, type MakeDotComRunScenarioStepInput, type MakeDotComRunScenarioStepOutput, type MergeAudioStepInput, type MergeAudioStepOutput, type MergeVideosStepInput, type MergeVideosStepOutput, MindStudioAgent, MindStudioError, type MindStudioModel, type MindStudioModelSummary, type MixAudioIntoVideoStepInput, type MixAudioIntoVideoStepOutput, type ModelType, type MonacoSnippet, type MonacoSnippetField, type MonacoSnippetFieldType, type MuteVideoStepInput, type MuteVideoStepOutput, type N8nRunNodeStepInput, type N8nRunNodeStepOutput, type NotionCreatePageStepInput, type NotionCreatePageStepOutput, type NotionUpdatePageStepInput, type NotionUpdatePageStepOutput, type PeopleSearchStepInput, type PeopleSearchStepOutput, type PostToLinkedInStepInput, type PostToLinkedInStepOutput, type PostToSlackChannelStepInput, type PostToSlackChannelStepOutput, type PostToXStepInput, type PostToXStepOutput, type PostToZapierStepInput, type PostToZapierStepOutput, type Predicate, type PushInput, Query, type QueryAppDatabaseStepInput, type QueryAppDatabaseStepOutput, type QueryDataSourceStepInput, type QueryDataSourceStepOutput, type QueryExternalDatabaseStepInput, type QueryExternalDatabaseStepOutput, type RedactPIIStepInput, type RedactPIIStepOutput, type RemoveBackgroundFromImageStepInput, type RemoveBackgroundFromImageStepOutput, type ReplyToGmailEmailStepInput, type ReplyToGmailEmailStepOutput, type ResizeVideoStepInput, type ResizeVideoStepOutput, type ResolvedUser, Roles, type RunAgentOptions, type RunAgentResult, type RunFromConnectorRegistryStepInput, type RunFromConnectorRegistryStepOutput, type RunPackagedWorkflowStepInput, type RunPackagedWorkflowStepOutput, type ScrapeFacebookPageStepInput, type ScrapeFacebookPageStepOutput, type ScrapeFacebookPostsStepInput, type ScrapeFacebookPostsStepOutput, type ScrapeInstagramCommentsStepInput, type ScrapeInstagramCommentsStepOutput, type ScrapeInstagramMentionsStepInput, type ScrapeInstagramMentionsStepOutput, type ScrapeInstagramPostsStepInput, type ScrapeInstagramPostsStepOutput, type ScrapeInstagramProfileStepInput, type ScrapeInstagramProfileStepOutput, type ScrapeInstagramReelsStepInput, type ScrapeInstagramReelsStepOutput, type ScrapeLinkedInCompanyStepInput, type ScrapeLinkedInCompanyStepOutput, type ScrapeLinkedInProfileStepInput, type ScrapeLinkedInProfileStepOutput, type ScrapeMetaThreadsProfileStepInput, type ScrapeMetaThreadsProfileStepOutput, type ScrapeUrlStepInput, type ScrapeUrlStepOutput, type ScrapeXPostStepInput, type ScrapeXPostStepOutput, type ScrapeXProfileStepInput, type ScrapeXProfileStepOutput, type ScreenshotUrlStepInput, type ScreenshotUrlStepOutput, type SearchGmailEmailsStepInput, type SearchGmailEmailsStepOutput, type SearchGoogleCalendarEventsStepInput, type SearchGoogleCalendarEventsStepOutput, type SearchGoogleDriveStepInput, type SearchGoogleDriveStepOutput, type SearchGoogleImagesStepInput, type SearchGoogleImagesStepOutput, type SearchGoogleNewsStepInput, type SearchGoogleNewsStepOutput, type SearchGoogleStepInput, type SearchGoogleStepOutput, type SearchGoogleTrendsStepInput, type SearchGoogleTrendsStepOutput, type SearchPerplexityStepInput, type SearchPerplexityStepOutput, type SearchXPostsStepInput, type SearchXPostsStepOutput, type SearchYoutubeStepInput, type SearchYoutubeStepOutput, type SearchYoutubeTrendsStepInput, type SearchYoutubeTrendsStepOutput, type SendEmailStepInput, type SendEmailStepOutput, type SendGmailDraftStepInput, type SendGmailDraftStepOutput, type SendGmailMessageStepInput, type SendGmailMessageStepOutput, type SendSMSStepInput, type SendSMSStepOutput, type SetGmailReadStatusStepInput, type SetGmailReadStatusStepOutput, type SetRunTitleStepInput, type SetRunTitleStepOutput, type SetVariableStepInput, type SetVariableStepOutput, type StepCostEstimateEntry, type StepExecutionMeta, type StepExecutionOptions, type StepExecutionResult, type StepInputMap, type StepMetadata, type StepMethods, type StepName, type StepOutputMap, type SystemFields, Table, type TelegramEditMessageStepInput, type TelegramEditMessageStepOutput, type TelegramReplyToMessageStepInput, type TelegramReplyToMessageStepOutput, type TelegramSendAudioStepInput, type TelegramSendAudioStepOutput, type TelegramSendFileStepInput, type TelegramSendFileStepOutput, type TelegramSendImageStepInput, type TelegramSendImageStepOutput, type TelegramSendMessageStepInput, type TelegramSendMessageStepOutput, type TelegramSendVideoStepInput, type TelegramSendVideoStepOutput, type TelegramSetTypingStepInput, type TelegramSetTypingStepOutput, type TextToSpeechStepInput, type TextToSpeechStepOutput, type TranscribeAudioStepInput, type TranscribeAudioStepOutput, type TrimMediaStepInput, type TrimMediaStepOutput, type UpdateGmailLabelsStepInput, type UpdateGmailLabelsStepOutput, type UpdateGoogleCalendarEventStepInput, type UpdateGoogleCalendarEventStepOutput, type UpdateGoogleDocStepInput, type UpdateGoogleDocStepOutput, type UpdateGoogleSheetStepInput, type UpdateGoogleSheetStepOutput, type UpdateInput, type UploadDataSourceDocumentStepInput, type UploadDataSourceDocumentStepOutput, type UploadFileResult, type UpscaleImageStepInput, type UpscaleImageStepOutput, type UpscaleVideoStepInput, type UpscaleVideoStepOutput, type User, type UserInfoResult, type UserMessageStepInput, type UserMessageStepOutput, type VideoFaceSwapStepInput, type VideoFaceSwapStepOutput, type VideoRemoveBackgroundStepInput, type VideoRemoveBackgroundStepOutput, type VideoRemoveWatermarkStepInput, type VideoRemoveWatermarkStepOutput, type WatermarkImageStepInput, type WatermarkImageStepOutput, type WatermarkVideoStepInput, type WatermarkVideoStepOutput, auth, blockTypeAliases, db, mindstudio as default, mindstudio, monacoSnippets, resolveUser, stepMetadata, stream };
7947
+ export { type Accessor, type ActiveCampaignAddNoteStepInput, type ActiveCampaignAddNoteStepOutput, type ActiveCampaignCreateContactStepInput, type ActiveCampaignCreateContactStepOutput, type AddSubtitlesToVideoStepInput, type AddSubtitlesToVideoStepOutput, type AgentInfo, type AgentOptions, type AirtableCreateUpdateRecordStepInput, type AirtableCreateUpdateRecordStepOutput, type AirtableDeleteRecordStepInput, type AirtableDeleteRecordStepOutput, type AirtableGetRecordStepInput, type AirtableGetRecordStepOutput, type AirtableGetTableRecordsStepInput, type AirtableGetTableRecordsStepOutput, type AnalyzeImageStepInput, type AnalyzeImageStepOutput, type AnalyzeVideoStepInput, type AnalyzeVideoStepOutput, type AppAuthContext, type AppContextResult, type AppDatabase, type AppDatabaseColumnSchema, type AppDatabaseTable, type AppRoleAssignment, AuthContext, type BatchStepInput, type BatchStepResult, type CaptureThumbnailStepInput, type CaptureThumbnailStepOutput, type CheckAppRoleStepInput, type CheckAppRoleStepOutput, type CodaCreateUpdatePageStepInput, type CodaCreateUpdatePageStepOutput, type CodaCreateUpdateRowStepInput, type CodaCreateUpdateRowStepOutput, type CodaFindRowStepInput, type CodaFindRowStepOutput, type CodaGetPageStepInput, type CodaGetPageStepOutput, type CodaGetTableRowsStepInput, type CodaGetTableRowsStepOutput, type Connection, type ConnectorActionDetail, type ConnectorService, type ConvertPdfToImagesStepInput, type ConvertPdfToImagesStepOutput, type CreateDataSourceStepInput, type CreateDataSourceStepOutput, type CreateGmailDraftStepInput, type CreateGmailDraftStepOutput, type CreateGoogleCalendarEventStepInput, type CreateGoogleCalendarEventStepOutput, type CreateGoogleDocStepInput, type CreateGoogleDocStepOutput, type CreateGoogleSheetStepInput, type CreateGoogleSheetStepOutput, type Db, type DefineTableOptions, type DeleteDataSourceDocumentStepInput, type DeleteDataSourceDocumentStepOutput, type DeleteDataSourceStepInput, type DeleteDataSourceStepOutput, type DeleteGmailEmailStepInput, type DeleteGmailEmailStepOutput, type DeleteGoogleCalendarEventStepInput, type DeleteGoogleCalendarEventStepOutput, type DeleteGoogleSheetRowsStepInput, type DeleteGoogleSheetRowsStepOutput, type DetectChangesStepInput, type DetectChangesStepOutput, type DetectPIIStepInput, type DetectPIIStepOutput, type DiscordEditMessageStepInput, type DiscordEditMessageStepOutput, type DiscordSendFollowUpStepInput, type DiscordSendFollowUpStepOutput, type DiscordSendMessageStepInput, type DiscordSendMessageStepOutput, type DownloadVideoStepInput, type DownloadVideoStepOutput, type EnhanceImageGenerationPromptStepInput, type EnhanceImageGenerationPromptStepOutput, type EnhanceVideoGenerationPromptStepInput, type EnhanceVideoGenerationPromptStepOutput, type EnrichPersonStepInput, type EnrichPersonStepOutput, type ExecuteStepBatchOptions, type ExecuteStepBatchResult, type ExtractAudioFromVideoStepInput, type ExtractAudioFromVideoStepOutput, type ExtractTextStepInput, type ExtractTextStepOutput, type FetchDataSourceDocumentStepInput, type FetchDataSourceDocumentStepOutput, type FetchGoogleDocStepInput, type FetchGoogleDocStepOutput, type FetchGoogleSheetStepInput, type FetchGoogleSheetStepOutput, type FetchSlackChannelHistoryStepInput, type FetchSlackChannelHistoryStepOutput, type FetchYoutubeCaptionsStepInput, type FetchYoutubeCaptionsStepOutput, type FetchYoutubeChannelStepInput, type FetchYoutubeChannelStepOutput, type FetchYoutubeCommentsStepInput, type FetchYoutubeCommentsStepOutput, type FetchYoutubeVideoStepInput, type FetchYoutubeVideoStepOutput, type GenerateAssetStepInput, type GenerateAssetStepOutput, type GenerateChartStepInput, type GenerateChartStepOutput, type GenerateImageStepInput, type GenerateImageStepOutput, type GenerateLipsyncStepInput, type GenerateLipsyncStepOutput, type GenerateMusicStepInput, type GenerateMusicStepOutput, type GeneratePdfStepInput, type GeneratePdfStepOutput, type GenerateStaticVideoFromImageStepInput, type GenerateStaticVideoFromImageStepOutput, type GenerateTextStepInput, type GenerateTextStepOutput, type GenerateVideoStepInput, type GenerateVideoStepOutput, type GetGmailAttachmentsStepInput, type GetGmailAttachmentsStepOutput, type GetGmailDraftStepInput, type GetGmailDraftStepOutput, type GetGmailEmailStepInput, type GetGmailEmailStepOutput, type GetGmailUnreadCountStepInput, type GetGmailUnreadCountStepOutput, type GetGoogleCalendarEventStepInput, type GetGoogleCalendarEventStepOutput, type GetGoogleDriveFileStepInput, type GetGoogleDriveFileStepOutput, type GetGoogleSheetInfoStepInput, type GetGoogleSheetInfoStepOutput, type GetMediaMetadataStepInput, type GetMediaMetadataStepOutput, type HttpRequestStepInput, type HttpRequestStepOutput, type HubspotCreateCompanyStepInput, type HubspotCreateCompanyStepOutput, type HubspotCreateContactStepInput, type HubspotCreateContactStepOutput, type HubspotGetCompanyStepInput, type HubspotGetCompanyStepOutput, type HubspotGetContactStepInput, type HubspotGetContactStepOutput, type HunterApiCompanyEnrichmentStepInput, type HunterApiCompanyEnrichmentStepOutput, type HunterApiDomainSearchStepInput, type HunterApiDomainSearchStepOutput, type HunterApiEmailFinderStepInput, type HunterApiEmailFinderStepOutput, type HunterApiEmailVerificationStepInput, type HunterApiEmailVerificationStepOutput, type HunterApiPersonEnrichmentStepInput, type HunterApiPersonEnrichmentStepOutput, type ImageFaceSwapStepInput, type ImageFaceSwapStepOutput, type ImageRemoveWatermarkStepInput, type ImageRemoveWatermarkStepOutput, type InsertVideoClipsStepInput, type InsertVideoClipsStepOutput, type ListAgentsResult, type ListDataSourcesStepInput, type ListDataSourcesStepOutput, type ListGmailDraftsStepInput, type ListGmailDraftsStepOutput, type ListGmailLabelsStepInput, type ListGmailLabelsStepOutput, type ListGoogleCalendarEventsStepInput, type ListGoogleCalendarEventsStepOutput, type ListGoogleDriveFilesStepInput, type ListGoogleDriveFilesStepOutput, type ListRecentGmailEmailsStepInput, type ListRecentGmailEmailsStepOutput, type LogicStepInput, type LogicStepOutput, type MakeDotComRunScenarioStepInput, type MakeDotComRunScenarioStepOutput, type MergeAudioStepInput, type MergeAudioStepOutput, type MergeVideosStepInput, type MergeVideosStepOutput, MindStudioAgent, MindStudioError, type MindStudioModel, type MindStudioModelSummary, type MixAudioIntoVideoStepInput, type MixAudioIntoVideoStepOutput, type ModelType, type MonacoSnippet, type MonacoSnippetField, type MonacoSnippetFieldType, type MuteVideoStepInput, type MuteVideoStepOutput, type N8nRunNodeStepInput, type N8nRunNodeStepOutput, type NotionCreatePageStepInput, type NotionCreatePageStepOutput, type NotionUpdatePageStepInput, type NotionUpdatePageStepOutput, type PeopleSearchStepInput, type PeopleSearchStepOutput, type PostToLinkedInStepInput, type PostToLinkedInStepOutput, type PostToSlackChannelStepInput, type PostToSlackChannelStepOutput, type PostToXStepInput, type PostToXStepOutput, type PostToZapierStepInput, type PostToZapierStepOutput, type Predicate, type PushInput, Query, type QueryAppDatabaseStepInput, type QueryAppDatabaseStepOutput, type QueryDataSourceStepInput, type QueryDataSourceStepOutput, type QueryExternalDatabaseStepInput, type QueryExternalDatabaseStepOutput, type RedactPIIStepInput, type RedactPIIStepOutput, type RemoveBackgroundFromImageStepInput, type RemoveBackgroundFromImageStepOutput, type ReplyToGmailEmailStepInput, type ReplyToGmailEmailStepOutput, type ResizeVideoStepInput, type ResizeVideoStepOutput, type ResolvedUser, Roles, type RunAgentOptions, type RunAgentResult, type RunFromConnectorRegistryStepInput, type RunFromConnectorRegistryStepOutput, type RunPackagedWorkflowStepInput, type RunPackagedWorkflowStepOutput, type ScrapeFacebookPageStepInput, type ScrapeFacebookPageStepOutput, type ScrapeFacebookPostsStepInput, type ScrapeFacebookPostsStepOutput, type ScrapeInstagramCommentsStepInput, type ScrapeInstagramCommentsStepOutput, type ScrapeInstagramMentionsStepInput, type ScrapeInstagramMentionsStepOutput, type ScrapeInstagramPostsStepInput, type ScrapeInstagramPostsStepOutput, type ScrapeInstagramProfileStepInput, type ScrapeInstagramProfileStepOutput, type ScrapeInstagramReelsStepInput, type ScrapeInstagramReelsStepOutput, type ScrapeLinkedInCompanyStepInput, type ScrapeLinkedInCompanyStepOutput, type ScrapeLinkedInProfileStepInput, type ScrapeLinkedInProfileStepOutput, type ScrapeMetaThreadsProfileStepInput, type ScrapeMetaThreadsProfileStepOutput, type ScrapeUrlStepInput, type ScrapeUrlStepOutput, type ScrapeXPostStepInput, type ScrapeXPostStepOutput, type ScrapeXProfileStepInput, type ScrapeXProfileStepOutput, type ScreenshotUrlStepInput, type ScreenshotUrlStepOutput, type SearchGmailEmailsStepInput, type SearchGmailEmailsStepOutput, type SearchGoogleCalendarEventsStepInput, type SearchGoogleCalendarEventsStepOutput, type SearchGoogleDriveStepInput, type SearchGoogleDriveStepOutput, type SearchGoogleImagesStepInput, type SearchGoogleImagesStepOutput, type SearchGoogleNewsStepInput, type SearchGoogleNewsStepOutput, type SearchGoogleStepInput, type SearchGoogleStepOutput, type SearchGoogleTrendsStepInput, type SearchGoogleTrendsStepOutput, type SearchPerplexityStepInput, type SearchPerplexityStepOutput, type SearchXPostsStepInput, type SearchXPostsStepOutput, type SearchYoutubeStepInput, type SearchYoutubeStepOutput, type SearchYoutubeTrendsStepInput, type SearchYoutubeTrendsStepOutput, type SendEmailStepInput, type SendEmailStepOutput, type SendGmailDraftStepInput, type SendGmailDraftStepOutput, type SendGmailMessageStepInput, type SendGmailMessageStepOutput, type SendSMSStepInput, type SendSMSStepOutput, type SetGmailReadStatusStepInput, type SetGmailReadStatusStepOutput, type SetRunTitleStepInput, type SetRunTitleStepOutput, type SetVariableStepInput, type SetVariableStepOutput, type StepCostEstimateEntry, type StepExecutionMeta, type StepExecutionOptions, type StepExecutionResult, type StepInputMap, type StepLogEvent, type StepMetadata, type StepMethods, type StepName, type StepOutputMap, type SystemFields, Table, type TelegramEditMessageStepInput, type TelegramEditMessageStepOutput, type TelegramReplyToMessageStepInput, type TelegramReplyToMessageStepOutput, type TelegramSendAudioStepInput, type TelegramSendAudioStepOutput, type TelegramSendFileStepInput, type TelegramSendFileStepOutput, type TelegramSendImageStepInput, type TelegramSendImageStepOutput, type TelegramSendMessageStepInput, type TelegramSendMessageStepOutput, type TelegramSendVideoStepInput, type TelegramSendVideoStepOutput, type TelegramSetTypingStepInput, type TelegramSetTypingStepOutput, type TextToSpeechStepInput, type TextToSpeechStepOutput, type TranscribeAudioStepInput, type TranscribeAudioStepOutput, type TrimMediaStepInput, type TrimMediaStepOutput, type UpdateGmailLabelsStepInput, type UpdateGmailLabelsStepOutput, type UpdateGoogleCalendarEventStepInput, type UpdateGoogleCalendarEventStepOutput, type UpdateGoogleDocStepInput, type UpdateGoogleDocStepOutput, type UpdateGoogleSheetStepInput, type UpdateGoogleSheetStepOutput, type UpdateInput, type UploadDataSourceDocumentStepInput, type UploadDataSourceDocumentStepOutput, type UploadFileResult, type UpscaleImageStepInput, type UpscaleImageStepOutput, type UpscaleVideoStepInput, type UpscaleVideoStepOutput, type User, type UserInfoResult, type UserMessageStepInput, type UserMessageStepOutput, type VideoFaceSwapStepInput, type VideoFaceSwapStepOutput, type VideoRemoveBackgroundStepInput, type VideoRemoveBackgroundStepOutput, type VideoRemoveWatermarkStepInput, type VideoRemoveWatermarkStepOutput, type WatermarkImageStepInput, type WatermarkImageStepOutput, type WatermarkVideoStepInput, type WatermarkVideoStepOutput, auth, blockTypeAliases, db, mindstudio as default, mindstudio, monacoSnippets, resolveUser, stepMetadata, stream };
package/dist/index.js CHANGED
@@ -297,6 +297,18 @@ function buildUpdate(table, id, data, columns) {
297
297
  params
298
298
  };
299
299
  }
300
+ function buildUpsert(table, data, conflictColumns, columns) {
301
+ const filtered = stripSystemColumns(data);
302
+ const keys = Object.keys(filtered);
303
+ const placeholders = keys.map(() => "?").join(", ");
304
+ const params = keys.map(
305
+ (k) => serializeColumnParam(filtered[k], k, columns)
306
+ );
307
+ const updateKeys = keys.filter((k) => !conflictColumns.includes(k));
308
+ const conflict = conflictColumns.join(", ");
309
+ const sql = updateKeys.length > 0 ? `INSERT INTO ${table} (${keys.join(", ")}) VALUES (${placeholders}) ON CONFLICT(${conflict}) DO UPDATE SET ${updateKeys.map((k) => `${k} = excluded.${k}`).join(", ")} RETURNING *` : `INSERT INTO ${table} (${keys.join(", ")}) VALUES (${placeholders}) ON CONFLICT(${conflict}) DO NOTHING RETURNING *`;
310
+ return { sql, params };
311
+ }
300
312
  function buildDelete(table, where, whereParams) {
301
313
  let sql = `DELETE FROM ${table}`;
302
314
  if (where) sql += ` WHERE ${where}`;
@@ -1006,6 +1018,9 @@ var Query = class _Query {
1006
1018
  then(onfulfilled, onrejected) {
1007
1019
  return this._execute().then(onfulfilled, onrejected);
1008
1020
  }
1021
+ catch(onrejected) {
1022
+ return this._execute().catch(onrejected);
1023
+ }
1009
1024
  // -------------------------------------------------------------------------
1010
1025
  // Execution internals
1011
1026
  // -------------------------------------------------------------------------
@@ -1121,6 +1136,9 @@ var Mutation = class _Mutation {
1121
1136
  then(onfulfilled, onrejected) {
1122
1137
  return this._execute().then(onfulfilled, onrejected);
1123
1138
  }
1139
+ catch(onrejected) {
1140
+ return this._execute().catch(onrejected);
1141
+ }
1124
1142
  // -------------------------------------------------------------------------
1125
1143
  // Batch compilation — used by db.batch()
1126
1144
  // -------------------------------------------------------------------------
@@ -1227,7 +1245,9 @@ var Table = class {
1227
1245
  }
1228
1246
  push(data) {
1229
1247
  const isArray = Array.isArray(data);
1230
- const items = isArray ? data : [data];
1248
+ const items = (isArray ? data : [data]).map(
1249
+ (item) => this._config.defaults ? { ...this._config.defaults, ...item } : item
1250
+ );
1231
1251
  const queries = items.map(
1232
1252
  (item) => buildInsert(
1233
1253
  this._config.tableName,
@@ -1306,6 +1326,60 @@ var Table = class {
1306
1326
  const query = buildDelete(this._config.tableName);
1307
1327
  return new Mutation(this._config, [query], () => void 0);
1308
1328
  }
1329
+ /**
1330
+ * Insert a row, or update it if a row with the same unique key already
1331
+ * exists. The conflict key must match a `unique` constraint declared in
1332
+ * defineTable options. Returns the created or updated row.
1333
+ *
1334
+ * Uses SQLite's `INSERT ... ON CONFLICT ... DO UPDATE SET ... RETURNING *`.
1335
+ *
1336
+ * @param conflictKey - Column name(s) that form the unique constraint.
1337
+ * Pass a single string for single-column unique, or an array for compound.
1338
+ * @param data - Row data to insert (or update on conflict). Defaults apply.
1339
+ */
1340
+ upsert(conflictKey, data) {
1341
+ const conflictColumns = Array.isArray(conflictKey) ? conflictKey : [conflictKey];
1342
+ this._validateUniqueConstraint(conflictColumns);
1343
+ const withDefaults = this._config.defaults ? { ...this._config.defaults, ...data } : data;
1344
+ const query = buildUpsert(
1345
+ this._config.tableName,
1346
+ withDefaults,
1347
+ conflictColumns,
1348
+ this._config.columns
1349
+ );
1350
+ return new Mutation(
1351
+ this._config,
1352
+ [query],
1353
+ (results) => deserializeRow(
1354
+ results[0].rows[0],
1355
+ this._config.columns
1356
+ )
1357
+ );
1358
+ }
1359
+ // -------------------------------------------------------------------------
1360
+ // Internal helpers
1361
+ // -------------------------------------------------------------------------
1362
+ /** @internal Validate that the given columns match a declared unique constraint. */
1363
+ _validateUniqueConstraint(columns) {
1364
+ if (!this._config.unique?.length) {
1365
+ throw new MindStudioError(
1366
+ `Cannot upsert on ${this._config.tableName}: no unique constraints declared. Add unique: [[${columns.map((c) => `'${c}'`).join(", ")}]] to defineTable options.`,
1367
+ "no_unique_constraint",
1368
+ 400
1369
+ );
1370
+ }
1371
+ const sorted = [...columns].sort().join(",");
1372
+ const match = this._config.unique.some(
1373
+ (u) => [...u].sort().join(",") === sorted
1374
+ );
1375
+ if (!match) {
1376
+ throw new MindStudioError(
1377
+ `Cannot upsert on (${columns.join(", ")}): no matching unique constraint declared on ${this._config.tableName}.`,
1378
+ "no_unique_constraint",
1379
+ 400
1380
+ );
1381
+ }
1382
+ }
1309
1383
  };
1310
1384
 
1311
1385
  // src/db/index.ts
@@ -1317,6 +1391,8 @@ function createDb(databases, executeBatch) {
1317
1391
  databaseId: resolved.databaseId,
1318
1392
  tableName: name,
1319
1393
  columns: resolved.columns,
1394
+ unique: options?.unique,
1395
+ defaults: options?.defaults,
1320
1396
  executeBatch: (queries) => executeBatch(resolved.databaseId, queries)
1321
1397
  };
1322
1398
  return new Table(config);
@@ -1987,6 +2063,13 @@ var MindStudioAgent = class {
1987
2063
  * ```
1988
2064
  */
1989
2065
  async executeStep(stepType, step, options) {
2066
+ if (options?.onLog) {
2067
+ return this._executeStepStreaming(
2068
+ stepType,
2069
+ step,
2070
+ options
2071
+ );
2072
+ }
1990
2073
  const threadId = options?.threadId ?? (this._reuseThreadId ? this._threadId : void 0);
1991
2074
  const { data, headers } = await request(this._httpConfig, "POST", `/steps/${stepType}/execute`, {
1992
2075
  step,
@@ -2031,6 +2114,160 @@ var MindStudioAgent = class {
2031
2114
  $billingEvents: billingEvents != null ? JSON.parse(billingEvents) : void 0
2032
2115
  };
2033
2116
  }
2117
+ /**
2118
+ * @internal Streaming step execution — sends `Accept: text/event-stream`
2119
+ * and parses SSE events for real-time debug logs.
2120
+ */
2121
+ async _executeStepStreaming(stepType, step, options) {
2122
+ const threadId = options.threadId ?? (this._reuseThreadId ? this._threadId : void 0);
2123
+ const url = `${this._httpConfig.baseUrl}/developer/v2/steps/${stepType}/execute`;
2124
+ const body = {
2125
+ step,
2126
+ ...options.appId != null && { appId: options.appId },
2127
+ ...threadId != null && { threadId },
2128
+ ...this._streamId != null && { streamId: this._streamId }
2129
+ };
2130
+ await this._httpConfig.rateLimiter.acquire();
2131
+ let res;
2132
+ try {
2133
+ res = await fetch(url, {
2134
+ method: "POST",
2135
+ headers: {
2136
+ Authorization: `Bearer ${this._httpConfig.token}`,
2137
+ "Content-Type": "application/json",
2138
+ "User-Agent": "@mindstudio-ai/agent",
2139
+ Accept: "text/event-stream"
2140
+ },
2141
+ body: JSON.stringify(body)
2142
+ });
2143
+ } catch (err) {
2144
+ this._httpConfig.rateLimiter.release();
2145
+ throw err;
2146
+ }
2147
+ this._httpConfig.rateLimiter.updateFromHeaders(res.headers);
2148
+ if (!res.ok) {
2149
+ this._httpConfig.rateLimiter.release();
2150
+ const errorBody = await res.json().catch(() => ({}));
2151
+ throw new MindStudioError(
2152
+ errorBody.message || `${res.status} ${res.statusText}`,
2153
+ errorBody.code || "api_error",
2154
+ res.status,
2155
+ errorBody
2156
+ );
2157
+ }
2158
+ const headers = res.headers;
2159
+ try {
2160
+ const reader = res.body.getReader();
2161
+ const decoder = new TextDecoder();
2162
+ let buffer = "";
2163
+ let doneEvent = null;
2164
+ while (true) {
2165
+ const { done, value } = await reader.read();
2166
+ if (done) break;
2167
+ buffer += decoder.decode(value, { stream: true });
2168
+ const lines = buffer.split("\n");
2169
+ buffer = lines.pop() ?? "";
2170
+ for (const line of lines) {
2171
+ if (!line.startsWith("data: ")) continue;
2172
+ try {
2173
+ const event = JSON.parse(line.slice(6));
2174
+ if (event.type === "log") {
2175
+ options.onLog({
2176
+ value: event.value,
2177
+ tag: event.tag,
2178
+ ts: event.ts
2179
+ });
2180
+ } else if (event.type === "done") {
2181
+ doneEvent = {
2182
+ output: event.output,
2183
+ outputUrl: event.outputUrl,
2184
+ billingCost: event.billingCost,
2185
+ billingEvents: event.billingEvents
2186
+ };
2187
+ } else if (event.type === "error") {
2188
+ throw new MindStudioError(
2189
+ event.error || "Step execution failed",
2190
+ "step_error",
2191
+ 500
2192
+ );
2193
+ }
2194
+ } catch (err) {
2195
+ if (err instanceof MindStudioError) throw err;
2196
+ }
2197
+ }
2198
+ }
2199
+ if (buffer.startsWith("data: ")) {
2200
+ try {
2201
+ const event = JSON.parse(buffer.slice(6));
2202
+ if (event.type === "done") {
2203
+ doneEvent = {
2204
+ output: event.output,
2205
+ outputUrl: event.outputUrl,
2206
+ billingCost: event.billingCost,
2207
+ billingEvents: event.billingEvents
2208
+ };
2209
+ } else if (event.type === "error") {
2210
+ throw new MindStudioError(
2211
+ event.error || "Step execution failed",
2212
+ "step_error",
2213
+ 500
2214
+ );
2215
+ } else if (event.type === "log") {
2216
+ options.onLog({
2217
+ value: event.value,
2218
+ tag: event.tag,
2219
+ ts: event.ts
2220
+ });
2221
+ }
2222
+ } catch (err) {
2223
+ if (err instanceof MindStudioError) throw err;
2224
+ }
2225
+ }
2226
+ if (!doneEvent) {
2227
+ throw new MindStudioError(
2228
+ "Stream ended without a done event",
2229
+ "stream_error",
2230
+ 500
2231
+ );
2232
+ }
2233
+ let output;
2234
+ if (doneEvent.output != null) {
2235
+ output = doneEvent.output;
2236
+ } else if (doneEvent.outputUrl) {
2237
+ const s3Res = await fetch(doneEvent.outputUrl);
2238
+ if (!s3Res.ok) {
2239
+ throw new MindStudioError(
2240
+ `Failed to fetch output from S3: ${s3Res.status} ${s3Res.statusText}`,
2241
+ "output_fetch_error",
2242
+ s3Res.status
2243
+ );
2244
+ }
2245
+ const envelope = await s3Res.json();
2246
+ output = envelope.value;
2247
+ } else {
2248
+ output = void 0;
2249
+ }
2250
+ const returnedThreadId = headers.get("x-mindstudio-thread-id") ?? "";
2251
+ if (this._reuseThreadId && returnedThreadId) {
2252
+ this._threadId = returnedThreadId;
2253
+ }
2254
+ const returnedAppId = headers.get("x-mindstudio-app-id");
2255
+ if (!this._appId && returnedAppId) {
2256
+ this._appId = returnedAppId;
2257
+ }
2258
+ const remaining = headers.get("x-ratelimit-remaining");
2259
+ return {
2260
+ ...output,
2261
+ $appId: headers.get("x-mindstudio-app-id") ?? "",
2262
+ $threadId: returnedThreadId,
2263
+ $rateLimitRemaining: remaining != null ? parseInt(remaining, 10) : void 0,
2264
+ $billingCost: doneEvent.billingCost,
2265
+ $billingEvents: doneEvent.billingEvents
2266
+ };
2267
+ } finally {
2268
+ this._httpConfig.rateLimiter.release();
2269
+ }
2270
+ }
2034
2271
  /**
2035
2272
  * Execute multiple steps in parallel in a single request.
2036
2273
  *
@@ -2516,6 +2753,8 @@ var MindStudioAgent = class {
2516
2753
  databaseId: "",
2517
2754
  tableName: name,
2518
2755
  columns: [],
2756
+ unique: options?.unique,
2757
+ defaults: options?.defaults,
2519
2758
  executeBatch: async (queries) => {
2520
2759
  await agent.ensureContext();
2521
2760
  const databases = agent._context.databases;
@@ -2754,9 +2993,9 @@ var monacoSnippets = {
2754
2993
  "fetchGoogleSheet": { fields: [["spreadsheetId", "string"], ["range", "string"], ["exportType", ["csv", "json"]]], outputKeys: ["content"] },
2755
2994
  "fetchSlackChannelHistory": { fields: [["channelId", "string"]], outputKeys: ["messages"] },
2756
2995
  "fetchYoutubeCaptions": { fields: [["videoUrl", "string"], ["exportType", ["text", "json"]], ["language", "string"]], outputKeys: ["transcripts"] },
2757
- "fetchYoutubeChannel": { fields: [["channelUrl", "string"]], outputKeys: ["channel"] },
2996
+ "fetchYoutubeChannel": { fields: [["channelUrl", "string"]], outputKeys: [] },
2758
2997
  "fetchYoutubeComments": { fields: [["videoUrl", "string"], ["exportType", ["text", "json"]], ["limitPages", "string"]], outputKeys: ["comments"] },
2759
- "fetchYoutubeVideo": { fields: [["videoUrl", "string"]], outputKeys: ["video"] },
2998
+ "fetchYoutubeVideo": { fields: [["videoUrl", "string"]], outputKeys: [] },
2760
2999
  "generateAsset": { fields: [["source", "string"], ["sourceType", ["html", "markdown", "spa", "raw", "dynamic", "customInterface"]], ["outputFormat", ["pdf", "png", "html", "mp4", "openGraph"]], ["pageSize", ["full", "letter", "A4", "custom"]], ["testData", "object"]], outputKeys: ["url"] },
2761
3000
  "generateChart": { fields: [["chart", "object"]], outputKeys: ["chartUrl"] },
2762
3001
  "generateImage": { fields: [["prompt", "string"]], outputKeys: ["imageUrl"] },
@@ -2840,7 +3079,7 @@ var monacoSnippets = {
2840
3079
  "searchPerplexity": { fields: [["query", "string"], ["exportType", ["text", "json"]]], outputKeys: ["results"] },
2841
3080
  "searchXPosts": { fields: [["query", "string"], ["scope", ["recent", "all"]], ["options", "object"]], outputKeys: ["posts"] },
2842
3081
  "searchYoutube": { fields: [["query", "string"], ["limitPages", "string"], ["filter", "string"], ["filterType", "string"]], outputKeys: ["results"] },
2843
- "searchYoutubeTrends": { fields: [["bp", ["now", "music", "gaming", "films"]], ["hl", "string"], ["gl", "string"]], outputKeys: ["trends"] },
3082
+ "searchYoutubeTrends": { fields: [["bp", ["now", "music", "gaming", "films"]], ["hl", "string"], ["gl", "string"]], outputKeys: [] },
2844
3083
  "sendEmail": { fields: [["subject", "string"], ["body", "string"]], outputKeys: ["recipients"] },
2845
3084
  "sendGmailDraft": { fields: [["draftId", "string"]], outputKeys: [] },
2846
3085
  "sendGmailMessage": { fields: [["to", "string"], ["subject", "string"], ["message", "string"], ["messageType", ["plain", "html", "markdown"]]], outputKeys: ["messageId"] },
@@ -3188,7 +3427,7 @@ var stepMetadata = {
3188
3427
  description: "Retrieve metadata and recent videos for a YouTube channel.",
3189
3428
  usageNotes: "- Accepts a YouTube channel URL (e.g. https://www.youtube.com/@ChannelName or /channel/ID).\n- Returns channel info and video listings as a JSON object.",
3190
3429
  inputSchema: { "type": "object", "properties": { "channelUrl": { "type": "string", "description": "YouTube channel URL (e.g. https://www.youtube.com/@ChannelName or /channel/ID)" } }, "required": ["channelUrl"] },
3191
- outputSchema: { "type": "object", "properties": { "channel": { "type": "object", "description": "Channel metadata and video listings" } }, "required": ["channel"] }
3430
+ outputSchema: { "type": "object" }
3192
3431
  },
3193
3432
  "fetchYoutubeComments": {
3194
3433
  stepType: "fetchYoutubeComments",
@@ -3202,7 +3441,7 @@ var stepMetadata = {
3202
3441
  description: "Retrieve metadata for a YouTube video (title, description, stats, channel info).",
3203
3442
  usageNotes: "- Returns video metadata, channel info, and engagement stats.\n- Video format data is excluded from the response.",
3204
3443
  inputSchema: { "type": "object", "properties": { "videoUrl": { "type": "string", "description": "YouTube video URL to fetch metadata for" } }, "required": ["videoUrl"] },
3205
- outputSchema: { "type": "object", "properties": { "video": { "type": "object", "description": "Video metadata including title, description, stats, and channel info" } }, "required": ["video"] }
3444
+ outputSchema: { "type": "object" }
3206
3445
  },
3207
3446
  "generateAsset": {
3208
3447
  stepType: "generatePdf",
@@ -3807,7 +4046,7 @@ var stepMetadata = {
3807
4046
  description: "Retrieve trending videos on YouTube by category and region.",
3808
4047
  usageNotes: '- Categories: "now" (trending now), "music", "gaming", "films".\n- Supports country and language filtering.',
3809
4048
  inputSchema: { "type": "object", "properties": { "bp": { "enum": ["now", "music", "gaming", "films"], "type": "string", "description": 'Trending category: "now" (trending now), "music", "gaming", or "films"' }, "hl": { "type": "string", "description": 'Language code (e.g. "en")' }, "gl": { "type": "string", "description": 'Country code (e.g. "US")' } }, "required": ["bp", "hl", "gl"] },
3810
- outputSchema: { "type": "object", "properties": { "trends": { "type": "object", "description": "Trending video data for the selected category and region" } }, "required": ["trends"] }
4049
+ outputSchema: { "type": "object" }
3811
4050
  },
3812
4051
  "sendEmail": {
3813
4052
  stepType: "sendEmail",