@mindstudio-ai/agent 0.1.41 → 0.1.42

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
@@ -1195,11 +1195,23 @@ declare class MindStudioAgent$1 {
1195
1195
  /** @internal Auth type — 'internal' for CALLBACK_TOKEN (managed mode), 'apiKey' otherwise. */
1196
1196
  private _authType;
1197
1197
  /**
1198
- * @internal Resolve the current auth token. For internal (CALLBACK_TOKEN)
1199
- * auth, re-reads the env var each time so that long-lived singleton
1200
- * instances pick up token rotations from the host process.
1198
+ * @internal Resolve the current auth token. Checks ALS request context
1199
+ * first, then CALLBACK_TOKEN env var, then static config token.
1201
1200
  */
1202
1201
  private get _token();
1202
+ /**
1203
+ * @internal HTTP config with ALS-aware baseUrl and token resolution.
1204
+ * Used instead of `_httpConfig` at all `request()` call sites.
1205
+ */
1206
+ private get _currentHttpConfig();
1207
+ /**
1208
+ * @internal Stream ID with ALS-aware resolution.
1209
+ */
1210
+ private get _currentStreamId();
1211
+ /**
1212
+ * @internal Get resolved app context from ALS or instance cache.
1213
+ */
1214
+ private _getContext;
1203
1215
  constructor(options?: AgentOptions);
1204
1216
  /**
1205
1217
  * Execute any step by its type name. This is the low-level method that all
@@ -4543,6 +4555,17 @@ interface SendGmailMessageStepOutput {
4543
4555
  /** Gmail message ID of the sent email */
4544
4556
  messageId: string;
4545
4557
  }
4558
+ interface SendSlackDirectMessageStepInput {
4559
+ /** Slack user ID of the recipient */
4560
+ slackUserId: string;
4561
+ /** Message format: "string" for plain text/markdown, "blocks" for Slack Block Kit JSON */
4562
+ messageType: "string" | "blocks";
4563
+ /** Message content (plain text/markdown for "string" type, or JSON for "blocks" type) */
4564
+ message: string;
4565
+ /** Slack OAuth connection ID (leave empty to allow user to select) */
4566
+ connectionId?: string;
4567
+ }
4568
+ type SendSlackDirectMessageStepOutput = unknown;
4546
4569
  interface SendSMSStepInput {
4547
4570
  /** SMS message body text */
4548
4571
  body: string;
@@ -4950,7 +4973,7 @@ type GenerateAssetStepOutput = GeneratePdfStepOutput;
4950
4973
  type GenerateTextStepInput = UserMessageStepInput;
4951
4974
  type GenerateTextStepOutput = UserMessageStepOutput;
4952
4975
  /** Union of all available step type names. */
4953
- type StepName = "activeCampaignAddNote" | "activeCampaignCreateContact" | "addSubtitlesToVideo" | "airtableCreateUpdateRecord" | "airtableDeleteRecord" | "airtableGetRecord" | "airtableGetTableRecords" | "analyzeImage" | "analyzeVideo" | "captureThumbnail" | "checkAppRole" | "codaCreateUpdatePage" | "codaCreateUpdateRow" | "codaFindRow" | "codaGetPage" | "codaGetTableRows" | "convertPdfToImages" | "createDataSource" | "createGmailDraft" | "createGoogleCalendarEvent" | "createGoogleDoc" | "createGoogleSheet" | "deleteDataSource" | "deleteDataSourceDocument" | "deleteGmailEmail" | "deleteGoogleCalendarEvent" | "deleteGoogleSheetRows" | "detectChanges" | "detectPII" | "discordEditMessage" | "discordSendFollowUp" | "discordSendMessage" | "downloadVideo" | "enhanceImageGenerationPrompt" | "enhanceVideoGenerationPrompt" | "enrichPerson" | "extractAudioFromVideo" | "extractText" | "fetchDataSourceDocument" | "fetchGoogleDoc" | "fetchGoogleSheet" | "fetchSlackChannelHistory" | "fetchYoutubeCaptions" | "fetchYoutubeChannel" | "fetchYoutubeComments" | "fetchYoutubeVideo" | "generateChart" | "generateImage" | "generateLipsync" | "generateMusic" | "generatePdf" | "generateStaticVideoFromImage" | "generateVideo" | "getGmailAttachments" | "getGmailDraft" | "getGmailEmail" | "getGmailUnreadCount" | "getGoogleCalendarEvent" | "getGoogleDriveFile" | "getGoogleSheetInfo" | "getMediaMetadata" | "httpRequest" | "hubspotCreateCompany" | "hubspotCreateContact" | "hubspotGetCompany" | "hubspotGetContact" | "hunterApiCompanyEnrichment" | "hunterApiDomainSearch" | "hunterApiEmailFinder" | "hunterApiEmailVerification" | "hunterApiPersonEnrichment" | "imageFaceSwap" | "imageRemoveWatermark" | "insertVideoClips" | "listDataSources" | "listGmailDrafts" | "listGmailLabels" | "listGoogleCalendarEvents" | "listGoogleDriveFiles" | "listRecentGmailEmails" | "logic" | "makeDotComRunScenario" | "mergeAudio" | "mergeVideos" | "mixAudioIntoVideo" | "muteVideo" | "n8nRunNode" | "notionCreatePage" | "notionUpdatePage" | "peopleSearch" | "postToLinkedIn" | "postToSlackChannel" | "postToX" | "postToZapier" | "queryAppDatabase" | "queryDataSource" | "queryExternalDatabase" | "redactPII" | "removeBackgroundFromImage" | "replyToGmailEmail" | "resizeVideo" | "runFromConnectorRegistry" | "runPackagedWorkflow" | "scrapeFacebookPage" | "scrapeFacebookPosts" | "scrapeInstagramComments" | "scrapeInstagramMentions" | "scrapeInstagramPosts" | "scrapeInstagramProfile" | "scrapeInstagramReels" | "scrapeLinkedInCompany" | "scrapeLinkedInProfile" | "scrapeMetaThreadsProfile" | "scrapeUrl" | "scrapeXPost" | "scrapeXProfile" | "screenshotUrl" | "searchGmailEmails" | "searchGoogle" | "searchGoogleCalendarEvents" | "searchGoogleDrive" | "searchGoogleImages" | "searchGoogleNews" | "searchGoogleTrends" | "searchPerplexity" | "searchXPosts" | "searchYoutube" | "searchYoutubeTrends" | "sendEmail" | "sendGmailDraft" | "sendGmailMessage" | "sendSMS" | "setGmailReadStatus" | "setRunTitle" | "setVariable" | "telegramEditMessage" | "telegramReplyToMessage" | "telegramSendAudio" | "telegramSendFile" | "telegramSendImage" | "telegramSendMessage" | "telegramSendVideo" | "telegramSetTyping" | "textToSpeech" | "transcribeAudio" | "trimMedia" | "updateGmailLabels" | "updateGoogleCalendarEvent" | "updateGoogleDoc" | "updateGoogleSheet" | "uploadDataSourceDocument" | "upscaleImage" | "upscaleVideo" | "userMessage" | "videoFaceSwap" | "videoRemoveBackground" | "videoRemoveWatermark" | "watermarkImage" | "watermarkVideo";
4976
+ type StepName = "activeCampaignAddNote" | "activeCampaignCreateContact" | "addSubtitlesToVideo" | "airtableCreateUpdateRecord" | "airtableDeleteRecord" | "airtableGetRecord" | "airtableGetTableRecords" | "analyzeImage" | "analyzeVideo" | "captureThumbnail" | "checkAppRole" | "codaCreateUpdatePage" | "codaCreateUpdateRow" | "codaFindRow" | "codaGetPage" | "codaGetTableRows" | "convertPdfToImages" | "createDataSource" | "createGmailDraft" | "createGoogleCalendarEvent" | "createGoogleDoc" | "createGoogleSheet" | "deleteDataSource" | "deleteDataSourceDocument" | "deleteGmailEmail" | "deleteGoogleCalendarEvent" | "deleteGoogleSheetRows" | "detectChanges" | "detectPII" | "discordEditMessage" | "discordSendFollowUp" | "discordSendMessage" | "downloadVideo" | "enhanceImageGenerationPrompt" | "enhanceVideoGenerationPrompt" | "enrichPerson" | "extractAudioFromVideo" | "extractText" | "fetchDataSourceDocument" | "fetchGoogleDoc" | "fetchGoogleSheet" | "fetchSlackChannelHistory" | "fetchYoutubeCaptions" | "fetchYoutubeChannel" | "fetchYoutubeComments" | "fetchYoutubeVideo" | "generateChart" | "generateImage" | "generateLipsync" | "generateMusic" | "generatePdf" | "generateStaticVideoFromImage" | "generateVideo" | "getGmailAttachments" | "getGmailDraft" | "getGmailEmail" | "getGmailUnreadCount" | "getGoogleCalendarEvent" | "getGoogleDriveFile" | "getGoogleSheetInfo" | "getMediaMetadata" | "httpRequest" | "hubspotCreateCompany" | "hubspotCreateContact" | "hubspotGetCompany" | "hubspotGetContact" | "hunterApiCompanyEnrichment" | "hunterApiDomainSearch" | "hunterApiEmailFinder" | "hunterApiEmailVerification" | "hunterApiPersonEnrichment" | "imageFaceSwap" | "imageRemoveWatermark" | "insertVideoClips" | "listDataSources" | "listGmailDrafts" | "listGmailLabels" | "listGoogleCalendarEvents" | "listGoogleDriveFiles" | "listRecentGmailEmails" | "logic" | "makeDotComRunScenario" | "mergeAudio" | "mergeVideos" | "mixAudioIntoVideo" | "muteVideo" | "n8nRunNode" | "notionCreatePage" | "notionUpdatePage" | "peopleSearch" | "postToLinkedIn" | "postToSlackChannel" | "postToX" | "postToZapier" | "queryAppDatabase" | "queryDataSource" | "queryExternalDatabase" | "redactPII" | "removeBackgroundFromImage" | "replyToGmailEmail" | "resizeVideo" | "runFromConnectorRegistry" | "runPackagedWorkflow" | "scrapeFacebookPage" | "scrapeFacebookPosts" | "scrapeInstagramComments" | "scrapeInstagramMentions" | "scrapeInstagramPosts" | "scrapeInstagramProfile" | "scrapeInstagramReels" | "scrapeLinkedInCompany" | "scrapeLinkedInProfile" | "scrapeMetaThreadsProfile" | "scrapeUrl" | "scrapeXPost" | "scrapeXProfile" | "screenshotUrl" | "searchGmailEmails" | "searchGoogle" | "searchGoogleCalendarEvents" | "searchGoogleDrive" | "searchGoogleImages" | "searchGoogleNews" | "searchGoogleTrends" | "searchPerplexity" | "searchXPosts" | "searchYoutube" | "searchYoutubeTrends" | "sendEmail" | "sendGmailDraft" | "sendGmailMessage" | "sendSlackDirectMessage" | "sendSMS" | "setGmailReadStatus" | "setRunTitle" | "setVariable" | "telegramEditMessage" | "telegramReplyToMessage" | "telegramSendAudio" | "telegramSendFile" | "telegramSendImage" | "telegramSendMessage" | "telegramSendVideo" | "telegramSetTyping" | "textToSpeech" | "transcribeAudio" | "trimMedia" | "updateGmailLabels" | "updateGoogleCalendarEvent" | "updateGoogleDoc" | "updateGoogleSheet" | "uploadDataSourceDocument" | "upscaleImage" | "upscaleVideo" | "userMessage" | "videoFaceSwap" | "videoRemoveBackground" | "videoRemoveWatermark" | "watermarkImage" | "watermarkVideo";
4954
4977
  /** Maps step names to their input types. */
4955
4978
  interface StepInputMap {
4956
4979
  activeCampaignAddNote: ActiveCampaignAddNoteStepInput;
@@ -5084,6 +5107,7 @@ interface StepInputMap {
5084
5107
  sendEmail: SendEmailStepInput;
5085
5108
  sendGmailDraft: SendGmailDraftStepInput;
5086
5109
  sendGmailMessage: SendGmailMessageStepInput;
5110
+ sendSlackDirectMessage: SendSlackDirectMessageStepInput;
5087
5111
  sendSMS: SendSMSStepInput;
5088
5112
  setGmailReadStatus: SetGmailReadStatusStepInput;
5089
5113
  setRunTitle: SetRunTitleStepInput;
@@ -5246,6 +5270,7 @@ interface StepOutputMap {
5246
5270
  sendEmail: SendEmailStepOutput;
5247
5271
  sendGmailDraft: SendGmailDraftStepOutput;
5248
5272
  sendGmailMessage: SendGmailMessageStepOutput;
5273
+ sendSlackDirectMessage: SendSlackDirectMessageStepOutput;
5249
5274
  sendSMS: SendSMSStepOutput;
5250
5275
  setGmailReadStatus: SetGmailReadStatusStepOutput;
5251
5276
  setRunTitle: SetRunTitleStepOutput;
@@ -7458,6 +7483,25 @@ interface StepMethods {
7458
7483
  * ```
7459
7484
  */
7460
7485
  sendGmailMessage(step: SendGmailMessageStepInput, options?: StepExecutionOptions): Promise<StepExecutionResult<SendGmailMessageStepOutput>>;
7486
+ /**
7487
+ * Send a direct message to a Slack user via a connected bot.
7488
+ *
7489
+ * @remarks
7490
+ * - The user is responsible for connecting their Slack workspace
7491
+ * - The recipient is identified by their Slack user ID
7492
+ * - Supports both simple text messages and Slack blocks messages
7493
+ * - Text messages can use limited markdown (slack-only formatting—e.g., headers are just rendered as bold)
7494
+ *
7495
+ * @example
7496
+ * ```typescript
7497
+ * const result = await agent.sendSlackDirectMessage({
7498
+ * slackUserId: ``,
7499
+ * messageType: "string",
7500
+ * message: ``,
7501
+ * });
7502
+ * ```
7503
+ */
7504
+ sendSlackDirectMessage(step: SendSlackDirectMessageStepInput, options?: StepExecutionOptions): Promise<StepExecutionResult<SendSlackDirectMessageStepOutput>>;
7461
7505
  /**
7462
7506
  * Send an SMS or MMS message to a phone number configured via OAuth connection.
7463
7507
  *
@@ -7931,6 +7975,67 @@ declare class MindStudioError extends Error {
7931
7975
  toJSON(): Record<string, unknown>;
7932
7976
  }
7933
7977
 
7978
+ /**
7979
+ * AsyncLocalStorage-based request context for concurrent execution.
7980
+ *
7981
+ * When the sandbox wraps each handler call in `runWithContext()`, all SDK
7982
+ * reads (auth, db, callback token, base URL) pull from the request-scoped
7983
+ * store instead of process globals. This enables concurrent request
7984
+ * processing on persistent sandbox workers without identity leakage.
7985
+ *
7986
+ * Fully backwards compatible — when no ALS store is active, all getters
7987
+ * fall back to the existing global/env-based behavior.
7988
+ */
7989
+
7990
+ /**
7991
+ * Per-request context provided by the sandbox execution service.
7992
+ * Contains everything the SDK needs to resolve auth, databases, and
7993
+ * API endpoints for a specific request.
7994
+ */
7995
+ interface RequestContext {
7996
+ /** Hook/callback token for this request's auth. */
7997
+ callbackToken: string;
7998
+ /** API base URL for this request (e.g. from REMOTE_HOSTNAME). */
7999
+ remoteHostname?: string;
8000
+ /** Auth context: userId + role assignments for this request's user. */
8001
+ auth?: AppAuthContext;
8002
+ /** Database metadata for this request's app. */
8003
+ databases?: AppDatabase[];
8004
+ /** Auth table config (managed columns) for this request's app. */
8005
+ authConfig?: AuthTableConfig;
8006
+ /** Stream ID for SSE streaming in this request. */
8007
+ streamId?: string;
8008
+ }
8009
+ /**
8010
+ * Get the current request context from AsyncLocalStorage, if any.
8011
+ * Returns undefined when not running inside `runWithContext()`.
8012
+ * @internal
8013
+ */
8014
+ declare function getRequestContext(): RequestContext | undefined;
8015
+ /**
8016
+ * Run an async function with a scoped request context. Inside `fn`, all
8017
+ * SDK reads (auth, db, callback token, base URL) pull from `ctx` instead
8018
+ * of process globals.
8019
+ *
8020
+ * This enables concurrent request processing — multiple `runWithContext()`
8021
+ * calls can execute in parallel without identity leakage.
8022
+ *
8023
+ * @example
8024
+ * ```ts
8025
+ * import { runWithContext } from '@mindstudio-ai/agent';
8026
+ *
8027
+ * await runWithContext({
8028
+ * callbackToken: req.callbackToken,
8029
+ * auth: req.auth,
8030
+ * databases: req.databases,
8031
+ * }, async () => {
8032
+ * // auth.userId returns this request's user, not the global one
8033
+ * const user = await Users.get(auth.userId);
8034
+ * });
8035
+ * ```
8036
+ */
8037
+ declare function runWithContext<T>(ctx: RequestContext, fn: () => T | Promise<T>): T | Promise<T>;
8038
+
7934
8039
  type MonacoSnippetFieldType = 'string' | 'number' | 'boolean' | 'array' | 'object' | string[];
7935
8040
  type MonacoSnippetField = [name: string, type: MonacoSnippetFieldType];
7936
8041
  interface MonacoSnippet {
@@ -8020,4 +8125,4 @@ declare const stream: (data: string | Record<string, unknown>) => Promise<void>;
8020
8125
  */
8021
8126
  declare const resolveUser: (userId: string) => Promise<ResolvedUser | null>;
8022
8127
 
8023
- 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 AuthTableConfig, 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 };
8128
+ 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 AuthTableConfig, 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 RequestContext, 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 SendSlackDirectMessageStepInput, type SendSlackDirectMessageStepOutput, 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, getRequestContext, mindstudio, monacoSnippets, resolveUser, runWithContext, stepMetadata, stream };
package/dist/index.js CHANGED
@@ -80,6 +80,16 @@ function sleep(ms) {
80
80
  return new Promise((resolve) => setTimeout(resolve, ms));
81
81
  }
82
82
 
83
+ // src/context.ts
84
+ import { AsyncLocalStorage } from "async_hooks";
85
+ var als = new AsyncLocalStorage();
86
+ function getRequestContext() {
87
+ return als.getStore();
88
+ }
89
+ function runWithContext(ctx, fn) {
90
+ return als.run(ctx, fn);
91
+ }
92
+
83
93
  // src/rate-limit.ts
84
94
  var DEFAULTS = {
85
95
  internal: { concurrency: 10, callCap: 500 },
@@ -2073,6 +2083,9 @@ function applyStepMethods(AgentClass) {
2073
2083
  proto.sendGmailMessage = function(step, options) {
2074
2084
  return this.executeStep("sendGmailMessage", step, options);
2075
2085
  };
2086
+ proto.sendSlackDirectMessage = function(step, options) {
2087
+ return this.executeStep("sendSlackDirectMessage", step, options);
2088
+ };
2076
2089
  proto.sendSMS = function(step, options) {
2077
2090
  return this.executeStep("sendSMS", step, options);
2078
2091
  };
@@ -3116,6 +3129,13 @@ var stepMetadata = {
3116
3129
  inputSchema: { "type": "object", "properties": { "to": { "type": "string", "description": "Recipient email address(es), comma-separated for multiple" }, "subject": { "type": "string", "description": "Email subject line" }, "message": { "type": "string", "description": "Email body content" }, "connectionId": { "type": "string", "description": "Google OAuth connection ID" }, "messageType": { "enum": ["plain", "html", "markdown"], "type": "string", "description": 'Body format: "plain", "html", or "markdown"' } }, "required": ["to", "subject", "message", "messageType"] },
3117
3130
  outputSchema: { "type": "object", "properties": { "messageId": { "type": "string", "description": "Gmail message ID of the sent email" } }, "required": ["messageId"] }
3118
3131
  },
3132
+ "sendSlackDirectMessage": {
3133
+ stepType: "sendSlackDirectMessage",
3134
+ description: "Send a direct message to a Slack user via a connected bot.",
3135
+ usageNotes: "- The user is responsible for connecting their Slack workspace\n- The recipient is identified by their Slack user ID\n- Supports both simple text messages and Slack blocks messages\n- Text messages can use limited markdown (slack-only formatting\u2014e.g., headers are just rendered as bold)",
3136
+ inputSchema: { "type": "object", "properties": { "slackUserId": { "type": "string", "description": "Slack user ID of the recipient" }, "messageType": { "enum": ["string", "blocks"], "type": "string", "description": 'Message format: "string" for plain text/markdown, "blocks" for Slack Block Kit JSON' }, "message": { "type": "string", "description": 'Message content (plain text/markdown for "string" type, or JSON for "blocks" type)' }, "connectionId": { "type": "string", "description": "Slack OAuth connection ID (leave empty to allow user to select)" } }, "required": ["slackUserId", "messageType", "message"] },
3137
+ outputSchema: { "description": "This step does not produce output data." }
3138
+ },
3119
3139
  "sendSMS": {
3120
3140
  stepType: "sendSMS",
3121
3141
  description: "Send an SMS or MMS message to a phone number configured via OAuth connection.",
@@ -3362,16 +3382,44 @@ var MindStudioAgent = class {
3362
3382
  /** @internal Auth type — 'internal' for CALLBACK_TOKEN (managed mode), 'apiKey' otherwise. */
3363
3383
  _authType;
3364
3384
  /**
3365
- * @internal Resolve the current auth token. For internal (CALLBACK_TOKEN)
3366
- * auth, re-reads the env var each time so that long-lived singleton
3367
- * instances pick up token rotations from the host process.
3385
+ * @internal Resolve the current auth token. Checks ALS request context
3386
+ * first, then CALLBACK_TOKEN env var, then static config token.
3368
3387
  */
3369
3388
  get _token() {
3389
+ const rctx = getRequestContext();
3390
+ if (rctx?.callbackToken) return rctx.callbackToken;
3370
3391
  if (this._authType === "internal" && process.env.CALLBACK_TOKEN) {
3371
3392
  return process.env.CALLBACK_TOKEN;
3372
3393
  }
3373
3394
  return this._httpConfig.token;
3374
3395
  }
3396
+ /**
3397
+ * @internal HTTP config with ALS-aware baseUrl and token resolution.
3398
+ * Used instead of `_httpConfig` at all `request()` call sites.
3399
+ */
3400
+ get _currentHttpConfig() {
3401
+ const rctx = getRequestContext();
3402
+ if (rctx?.remoteHostname) {
3403
+ return { ...this._httpConfig, baseUrl: rctx.remoteHostname, token: this._token };
3404
+ }
3405
+ return this._httpConfig;
3406
+ }
3407
+ /**
3408
+ * @internal Stream ID with ALS-aware resolution.
3409
+ */
3410
+ get _currentStreamId() {
3411
+ return getRequestContext()?.streamId ?? this._streamId;
3412
+ }
3413
+ /**
3414
+ * @internal Get resolved app context from ALS or instance cache.
3415
+ */
3416
+ _getContext() {
3417
+ const rctx = getRequestContext();
3418
+ if (rctx?.auth && rctx?.databases) {
3419
+ return { auth: rctx.auth, databases: rctx.databases, authConfig: rctx.authConfig };
3420
+ }
3421
+ return this._context;
3422
+ }
3375
3423
  constructor(options = {}) {
3376
3424
  const config = loadConfig();
3377
3425
  const { token, authType } = resolveToken(options.apiKey, config);
@@ -3407,12 +3455,12 @@ var MindStudioAgent = class {
3407
3455
  options
3408
3456
  );
3409
3457
  }
3410
- const threadId = options?.threadId ?? (this._reuseThreadId ? this._threadId : void 0);
3458
+ const threadId = options?.threadId ?? (this._reuseThreadId && !getRequestContext() ? this._threadId : void 0);
3411
3459
  const { data, headers } = await request(this._httpConfig, "POST", `/steps/${stepType}/execute`, {
3412
3460
  step,
3413
3461
  ...options?.appId != null && { appId: options.appId },
3414
3462
  ...threadId != null && { threadId },
3415
- ...this._streamId != null && { streamId: this._streamId }
3463
+ ...this._currentStreamId != null && { streamId: this._currentStreamId }
3416
3464
  });
3417
3465
  let output;
3418
3466
  if (data.output != null) {
@@ -3432,11 +3480,11 @@ var MindStudioAgent = class {
3432
3480
  output = void 0;
3433
3481
  }
3434
3482
  const returnedThreadId = headers.get("x-mindstudio-thread-id") ?? "";
3435
- if (this._reuseThreadId && returnedThreadId) {
3483
+ if (this._reuseThreadId && returnedThreadId && !getRequestContext()) {
3436
3484
  this._threadId = returnedThreadId;
3437
3485
  }
3438
3486
  const returnedAppId = headers.get("x-mindstudio-app-id");
3439
- if (!this._appId && returnedAppId) {
3487
+ if (!this._appId && returnedAppId && !getRequestContext()) {
3440
3488
  this._appId = returnedAppId;
3441
3489
  }
3442
3490
  const remaining = headers.get("x-ratelimit-remaining");
@@ -3456,13 +3504,13 @@ var MindStudioAgent = class {
3456
3504
  * and parses SSE events for real-time debug logs.
3457
3505
  */
3458
3506
  async _executeStepStreaming(stepType, step, options) {
3459
- const threadId = options.threadId ?? (this._reuseThreadId ? this._threadId : void 0);
3460
- const url = `${this._httpConfig.baseUrl}/developer/v2/steps/${stepType}/execute`;
3507
+ const threadId = options.threadId ?? (this._reuseThreadId && !getRequestContext() ? this._threadId : void 0);
3508
+ const url = `${this._currentHttpConfig.baseUrl}/developer/v2/steps/${stepType}/execute`;
3461
3509
  const body = {
3462
3510
  step,
3463
3511
  ...options.appId != null && { appId: options.appId },
3464
3512
  ...threadId != null && { threadId },
3465
- ...this._streamId != null && { streamId: this._streamId }
3513
+ ...this._currentStreamId != null && { streamId: this._currentStreamId }
3466
3514
  };
3467
3515
  await this._httpConfig.rateLimiter.acquire();
3468
3516
  let res;
@@ -3599,11 +3647,11 @@ var MindStudioAgent = class {
3599
3647
  output = void 0;
3600
3648
  }
3601
3649
  const returnedThreadId = headers.get("x-mindstudio-thread-id") ?? "";
3602
- if (this._reuseThreadId && returnedThreadId) {
3650
+ if (this._reuseThreadId && returnedThreadId && !getRequestContext()) {
3603
3651
  this._threadId = returnedThreadId;
3604
3652
  }
3605
3653
  const returnedAppId = headers.get("x-mindstudio-app-id");
3606
- if (!this._appId && returnedAppId) {
3654
+ if (!this._appId && returnedAppId && !getRequestContext()) {
3607
3655
  this._appId = returnedAppId;
3608
3656
  }
3609
3657
  const remaining = headers.get("x-ratelimit-remaining");
@@ -3634,7 +3682,7 @@ var MindStudioAgent = class {
3634
3682
  * ```
3635
3683
  */
3636
3684
  async executeStepBatch(steps, options) {
3637
- const threadId = options?.threadId ?? (this._reuseThreadId ? this._threadId : void 0);
3685
+ const threadId = options?.threadId ?? (this._reuseThreadId && !getRequestContext() ? this._threadId : void 0);
3638
3686
  const { data } = await request(this._httpConfig, "POST", "/steps/execute-batch", {
3639
3687
  steps: steps.map((s) => ({ ...s, stepType: resolveStepType(s.stepType) })),
3640
3688
  ...options?.appId != null && { appId: options.appId },
@@ -3672,7 +3720,7 @@ var MindStudioAgent = class {
3672
3720
  };
3673
3721
  })
3674
3722
  );
3675
- if (this._reuseThreadId && data.threadId) {
3723
+ if (this._reuseThreadId && data.threadId && !getRequestContext()) {
3676
3724
  this._threadId = data.threadId;
3677
3725
  }
3678
3726
  return {
@@ -3742,7 +3790,7 @@ var MindStudioAgent = class {
3742
3790
  ...options.metadata != null && { metadata: options.metadata }
3743
3791
  });
3744
3792
  const token = data.callbackToken;
3745
- const pollUrl = `${this._httpConfig.baseUrl}/developer/v2/agents/run/poll/${token}`;
3793
+ const pollUrl = `${this._currentHttpConfig.baseUrl}/developer/v2/agents/run/poll/${token}`;
3746
3794
  while (true) {
3747
3795
  await sleep2(pollInterval);
3748
3796
  const res = await fetch(pollUrl, {
@@ -3898,9 +3946,10 @@ var MindStudioAgent = class {
3898
3946
  * ```
3899
3947
  */
3900
3948
  stream = async (data) => {
3901
- if (!this._streamId) return;
3902
- const url = `${this._httpConfig.baseUrl}/_internal/v2/stream-chunk`;
3903
- const body = typeof data === "string" ? { streamId: this._streamId, type: "token", text: data } : { streamId: this._streamId, type: "data", data };
3949
+ const streamId = this._currentStreamId;
3950
+ if (!streamId) return;
3951
+ const url = `${this._currentHttpConfig.baseUrl}/_internal/v2/stream-chunk`;
3952
+ const body = typeof data === "string" ? { streamId, type: "token", text: data } : { streamId, type: "data", data };
3904
3953
  const res = await fetch(url, {
3905
3954
  method: "POST",
3906
3955
  headers: {
@@ -3938,6 +3987,10 @@ var MindStudioAgent = class {
3938
3987
  * ```
3939
3988
  */
3940
3989
  get auth() {
3990
+ const rctx = getRequestContext();
3991
+ if (rctx?.auth) {
3992
+ return new AuthContext(rctx.auth);
3993
+ }
3941
3994
  if (this._authType === "internal") {
3942
3995
  const ai = globalThis.ai;
3943
3996
  if (ai?.auth) {
@@ -3972,6 +4025,9 @@ var MindStudioAgent = class {
3972
4025
  * ```
3973
4026
  */
3974
4027
  get db() {
4028
+ if (getRequestContext()) {
4029
+ return this._createLazyDb();
4030
+ }
3975
4031
  if (!this._db) {
3976
4032
  this._trySandboxHydration();
3977
4033
  }
@@ -4000,6 +4056,7 @@ var MindStudioAgent = class {
4000
4056
  * ```
4001
4057
  */
4002
4058
  async ensureContext() {
4059
+ if (this._getContext()) return;
4003
4060
  if (this._context) return;
4004
4061
  if (!this._contextPromise) {
4005
4062
  this._contextPromise = this._hydrateContext();
@@ -4046,6 +4103,7 @@ var MindStudioAgent = class {
4046
4103
  * - `ai.databases`: [{ id, name, tables[] }]
4047
4104
  */
4048
4105
  _trySandboxHydration() {
4106
+ if (getRequestContext()) return;
4049
4107
  const ai = globalThis.ai;
4050
4108
  if (ai?.auth && ai?.databases) {
4051
4109
  this._applyContext({
@@ -4064,7 +4122,7 @@ var MindStudioAgent = class {
4064
4122
  * enabling RETURNING clauses and multi-statement batches.
4065
4123
  */
4066
4124
  async _executeDbBatch(databaseId, queries) {
4067
- const url = `${this._httpConfig.baseUrl}/_internal/v2/db/query`;
4125
+ const url = `${this._currentHttpConfig.baseUrl}/_internal/v2/db/query`;
4068
4126
  const res = await fetch(url, {
4069
4127
  method: "POST",
4070
4128
  headers: {
@@ -4107,7 +4165,7 @@ var MindStudioAgent = class {
4107
4165
  */
4108
4166
  async _syncRoles(userId, roles) {
4109
4167
  try {
4110
- const url = `${this._httpConfig.baseUrl}/_internal/v2/auth/sync-user`;
4168
+ const url = `${this._currentHttpConfig.baseUrl}/_internal/v2/auth/sync-user`;
4111
4169
  const res = await fetch(url, {
4112
4170
  method: "POST",
4113
4171
  headers: {
@@ -4152,14 +4210,15 @@ var MindStudioAgent = class {
4152
4210
  defaults: options?.defaults,
4153
4211
  executeBatch: async (queries) => {
4154
4212
  await agent.ensureContext();
4155
- const ac = agent._context.authConfig;
4213
+ const ctx = agent._getContext();
4214
+ const ac = ctx.authConfig;
4156
4215
  if (ac && ac.table === name && !tableConfig.managedColumns) {
4157
4216
  tableConfig.managedColumns = ac.columns;
4158
4217
  if (ac.columns.roles) {
4159
4218
  tableConfig.syncRoles = agent._syncRoles.bind(agent);
4160
4219
  }
4161
4220
  }
4162
- const databases = agent._context.databases;
4221
+ const databases = ctx.databases;
4163
4222
  let targetDb;
4164
4223
  if (databaseHint) {
4165
4224
  targetDb = databases.find(
@@ -4187,7 +4246,13 @@ var MindStudioAgent = class {
4187
4246
  batch: ((...queries) => {
4188
4247
  return (async () => {
4189
4248
  await agent.ensureContext();
4190
- return agent._db.batch(...queries);
4249
+ const resolvedDb = agent._db ?? createDb(
4250
+ agent._getContext().databases,
4251
+ agent._executeDbBatch.bind(agent),
4252
+ agent._getContext().authConfig,
4253
+ agent._syncRoles.bind(agent)
4254
+ );
4255
+ return resolvedDb.batch(...queries);
4191
4256
  })();
4192
4257
  })
4193
4258
  };
@@ -4285,13 +4350,13 @@ var MindStudioAgent = class {
4285
4350
  // -------------------------------------------------------------------------
4286
4351
  /** Update the display name of the authenticated user/agent. */
4287
4352
  async changeName(displayName) {
4288
- await request(this._httpConfig, "POST", "/account/change-name", {
4353
+ await request(this._currentHttpConfig, "POST", "/account/change-name", {
4289
4354
  name: displayName
4290
4355
  });
4291
4356
  }
4292
4357
  /** Update the profile picture of the authenticated user/agent. */
4293
4358
  async changeProfilePicture(url) {
4294
- await request(this._httpConfig, "POST", "/account/change-profile-picture", {
4359
+ await request(this._currentHttpConfig, "POST", "/account/change-profile-picture", {
4295
4360
  url
4296
4361
  });
4297
4362
  }
@@ -4490,6 +4555,7 @@ var monacoSnippets = {
4490
4555
  "sendEmail": { fields: [["subject", "string"], ["body", "string"]], outputKeys: ["recipients"] },
4491
4556
  "sendGmailDraft": { fields: [["draftId", "string"]], outputKeys: [] },
4492
4557
  "sendGmailMessage": { fields: [["to", "string"], ["subject", "string"], ["message", "string"], ["messageType", ["plain", "html", "markdown"]]], outputKeys: ["messageId"] },
4558
+ "sendSlackDirectMessage": { fields: [["slackUserId", "string"], ["messageType", ["string", "blocks"]], ["message", "string"]], outputKeys: [] },
4493
4559
  "sendSMS": { fields: [["body", "string"]], outputKeys: [] },
4494
4560
  "setGmailReadStatus": { fields: [["messageIds", "string"], ["markAsRead", "boolean"]], outputKeys: [] },
4495
4561
  "setRunTitle": { fields: [["title", "string"]], outputKeys: [] },
@@ -4569,9 +4635,11 @@ export {
4569
4635
  blockTypeAliases,
4570
4636
  db,
4571
4637
  index_default as default,
4638
+ getRequestContext,
4572
4639
  mindstudio,
4573
4640
  monacoSnippets,
4574
4641
  resolveUser,
4642
+ runWithContext,
4575
4643
  stepMetadata,
4576
4644
  stream
4577
4645
  };