@mindstudio-ai/agent 0.1.176 → 0.1.177

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/analytics/index.d.ts +384 -0
  3. package/dist/auth/index.d.ts +113 -0
  4. package/dist/browser/index.d.ts +332 -0
  5. package/dist/cli.js +27 -27
  6. package/dist/client.d.ts +767 -0
  7. package/dist/config.d.ts +13 -0
  8. package/dist/context.d.ts +125 -0
  9. package/dist/datasources/index.d.ts +52 -0
  10. package/dist/datasources/source.d.ts +1074 -0
  11. package/dist/db/aggregate.d.ts +101 -0
  12. package/dist/db/index.d.ts +280 -0
  13. package/dist/db/mutation.d.ts +65 -0
  14. package/dist/db/predicate.d.ts +85 -0
  15. package/dist/db/query.d.ts +233 -0
  16. package/dist/db/raw.d.ts +36 -0
  17. package/dist/db/readBatching.d.ts +36 -0
  18. package/dist/db/scanHints.d.ts +8 -0
  19. package/dist/db/sql.d.ts +136 -0
  20. package/dist/db/table.d.ts +146 -0
  21. package/dist/db/time.d.ts +17 -0
  22. package/dist/db/types.d.ts +237 -0
  23. package/dist/db-ws.d.ts +35 -0
  24. package/dist/email/index.d.ts +396 -0
  25. package/dist/errors.d.ts +34 -0
  26. package/dist/events/index.d.ts +127 -0
  27. package/dist/files/index.d.ts +62 -0
  28. package/dist/files/store.d.ts +244 -0
  29. package/dist/generated/metadata.d.ts +8 -0
  30. package/dist/generated/snippets.d.ts +8 -0
  31. package/dist/generated/steps.d.ts +2745 -0
  32. package/dist/generated/types.d.ts +4234 -0
  33. package/dist/http.d.ts +22 -0
  34. package/dist/index.d.ts +59 -13329
  35. package/dist/index.js +15 -15
  36. package/dist/index.js.map +7 -1
  37. package/dist/jewel/index.d.ts +325 -0
  38. package/dist/mapper/index.d.ts +229 -0
  39. package/dist/rate-limit.d.ts +25 -0
  40. package/dist/reader/index.d.ts +170 -0
  41. package/dist/respond.d.ts +68 -0
  42. package/dist/task/index.d.ts +18 -0
  43. package/dist/task/local.d.ts +48 -0
  44. package/dist/task/schema.d.ts +120 -0
  45. package/dist/task/types.d.ts +203 -0
  46. package/dist/types.d.ts +591 -0
  47. package/dist/voice/index.d.ts +87 -0
  48. package/package.json +6 -12
  49. package/dist/postinstall.js +0 -12115
@@ -0,0 +1,767 @@
1
+ import { type HttpClientConfig } from './http.js';
2
+ import { AuthContext } from './auth/index.js';
3
+ import { type Db } from './db/index.js';
4
+ import { type Files } from './files/index.js';
5
+ import type { JewelsApi } from './jewel/index.js';
6
+ import { type DataSources } from './datasources/index.js';
7
+ import { type Voice } from './voice/index.js';
8
+ import { type Analytics } from './analytics/index.js';
9
+ import { type Email } from './email/index.js';
10
+ import { type Events } from './events/index.js';
11
+ import { type Browser } from './browser/index.js';
12
+ import type { RunTaskOptionsWithExample, RunTaskOptionsWithSchema, RunTaskResult } from './task/index.js';
13
+ import type { JsonObjectSchema, FromSchema } from './task/schema.js';
14
+ import type { AgentOptions, StepExecutionOptions, StepExecutionResult, ListAgentsResult, UserInfoResult, RunAgentOptions, RunAgentResult, MindStudioModel, MindStudioModelSummary, ModelType, ConnectorService, ConnectorActionDetail, Connection, StepCostEstimateEntry, UploadFileResult, ResolvedUser, ReportIssueInput, ReportedIssue, AppContextResult, BatchStepInput, ExecuteStepBatchOptions, ExecuteStepBatchResult, PackagedWorkflow } from './types.js';
15
+ /**
16
+ * Client for the MindStudio direct step execution API.
17
+ *
18
+ * Inside MindStudio apps, use the `mindstudio` singleton (auth is automatic):
19
+ * ```ts
20
+ * import { mindstudio } from '@mindstudio-ai/agent';
21
+ * const { imageUrl } = await mindstudio.generateImage({ prompt: "a sunset" });
22
+ * ```
23
+ *
24
+ * For external usage with an API key:
25
+ * ```ts
26
+ * const agent = new MindStudioAgent({ apiKey: "your-key" });
27
+ * const { imageUrl } = await agent.generateImage({ prompt: "a sunset" });
28
+ * ```
29
+ *
30
+ * Authentication is resolved in order:
31
+ * 1. `CALLBACK_TOKEN` environment variable (auto-set inside MindStudio — always takes priority)
32
+ * 2. `apiKey` passed to the constructor
33
+ * 3. `MINDSTUDIO_API_KEY` environment variable
34
+ * 4. `~/.mindstudio/config.json` (set via `mindstudio login`)
35
+ *
36
+ * Base URL is resolved in order:
37
+ * 1. `baseUrl` passed to the constructor
38
+ * 2. `MINDSTUDIO_BASE_URL` environment variable
39
+ * 3. `REMOTE_HOSTNAME` environment variable (auto-set inside MindStudio custom functions)
40
+ * 4. `~/.mindstudio/config.json`
41
+ * 5. `https://v1.mindstudio-api.com` (production default)
42
+ *
43
+ * Rate limiting is handled automatically:
44
+ * - Concurrent requests are queued to stay within the server's concurrency
45
+ * limit, per execution inside MindStudio
46
+ * - 429 responses are retried automatically using the `Retry-After` header
47
+ */
48
+ export declare class MindStudioAgent {
49
+ /** @internal */
50
+ readonly _httpConfig: HttpClientConfig;
51
+ /** @internal */
52
+ private _reuseThreadId;
53
+ /** @internal */
54
+ private _threadId;
55
+ /** @internal Stream ID for SSE token streaming. Set by sandbox via STREAM_ID env var. */
56
+ private _streamId;
57
+ /**
58
+ * @internal App ID for context resolution. Resolved from:
59
+ * constructor appId → MINDSTUDIO_APP_ID env → sandbox globals →
60
+ * auto-detected from first executeStep response header.
61
+ */
62
+ private _appId;
63
+ /**
64
+ * @internal Cached app context (auth + databases). Populated by
65
+ * ensureContext() and cached for the lifetime of the instance.
66
+ */
67
+ private _context;
68
+ /**
69
+ * @internal Deduplication promise for ensureContext(). Ensures only one
70
+ * context fetch is in-flight at a time, even if multiple db/auth
71
+ * operations trigger it concurrently.
72
+ */
73
+ private _contextPromise;
74
+ /** @internal Cached AuthContext instance, created during context hydration. */
75
+ private _auth;
76
+ /** @internal Cached Db namespace instance, created during context hydration. */
77
+ private _db;
78
+ /** @internal Cached Files namespace instance (lazy; no context hydration needed). */
79
+ private _files;
80
+ private _dataSources;
81
+ private _voice;
82
+ private _analytics;
83
+ private _email;
84
+ private _events;
85
+ private _browser;
86
+ /** @internal Auth type — 'internal' for CALLBACK_TOKEN (managed mode), 'apiKey' otherwise. */
87
+ private _authType;
88
+ /** @internal Usage source sent on step executions (from MINDSTUDIO_REQUEST_SOURCE).
89
+ * Only set for api-key (CLI) auth so in-app/managed runtime is unaffected. */
90
+ private _requestSource;
91
+ /**
92
+ * @internal Resolve the current auth token. Checks ALS request context
93
+ * first, then CALLBACK_TOKEN env var, then static config token.
94
+ */
95
+ private get _token();
96
+ /**
97
+ * @internal HTTP config with ALS-aware baseUrl and token resolution.
98
+ * Used instead of `_httpConfig` at all `request()` call sites.
99
+ */
100
+ private get _currentHttpConfig();
101
+ /**
102
+ * @internal Stream ID with ALS-aware resolution.
103
+ */
104
+ private get _currentStreamId();
105
+ /**
106
+ * @internal Get resolved app context from ALS or instance cache.
107
+ */
108
+ private _getContext;
109
+ constructor(options?: AgentOptions);
110
+ /**
111
+ * Execute any step by its type name. This is the low-level method that all
112
+ * typed step methods delegate to. Use it as an escape hatch for step types
113
+ * not yet covered by the generated methods.
114
+ *
115
+ * ```ts
116
+ * const result = await agent.executeStep("generateImage", { prompt: "hello", mode: "background" });
117
+ * ```
118
+ */
119
+ executeStep<TOutput = unknown>(stepType: string, step: Record<string, unknown>, options?: StepExecutionOptions): Promise<StepExecutionResult<TOutput>>;
120
+ /**
121
+ * @internal Async step execution — POST, then poll until the step finishes.
122
+ * Runs inside one concurrency slot (see `withSlot`).
123
+ */
124
+ private _executeStepPolled;
125
+ /**
126
+ * @internal Streaming step execution — sends `Accept: text/event-stream`
127
+ * and parses SSE events for real-time debug logs.
128
+ */
129
+ private _executeStepStreaming;
130
+ /**
131
+ * Execute multiple steps in parallel in a single request.
132
+ *
133
+ * All steps run in parallel on the server. Results are returned in the same
134
+ * order as the input. Individual step failures do not affect other steps —
135
+ * partial success is possible.
136
+ *
137
+ * ```ts
138
+ * const { results } = await agent.executeStepBatch([
139
+ * { stepType: 'generateImage', step: { prompt: 'a sunset' } },
140
+ * { stepType: 'textToSpeech', step: { text: 'Hello world' } },
141
+ * ]);
142
+ * ```
143
+ */
144
+ executeStepBatch(steps: BatchStepInput[], options?: ExecuteStepBatchOptions): Promise<ExecuteStepBatchResult>;
145
+ /**
146
+ * @internal Async batch execution — POST, then poll until the batch settles.
147
+ * Runs inside one concurrency slot (see `withSlot`).
148
+ */
149
+ private _executeStepBatchPolled;
150
+ /**
151
+ * Run a task agent — a multi-step tool-use loop that composes SDK actions
152
+ * to produce structured output. The model receives the prompt and tools,
153
+ * calls actions as needed, and returns structured JSON.
154
+ *
155
+ * Tools can be SDK actions, your own app's methods, and/or inline functions
156
+ * defined right in your code, in any combination. App methods run as the
157
+ * user who invoked the method that started the task, with their roles.
158
+ * Function tools run in this process — a thrown error is fed back to the
159
+ * model as tool output, and there are no `defaults` (close over what you
160
+ * need instead).
161
+ *
162
+ * Prefer `outputSchema` (plain JSON Schema, tool-definition dialect):
163
+ * output is validated every turn with automatic repair, `result.output` is
164
+ * typed by inference from the schema — no generic argument, no manual
165
+ * validation — and the call either returns conforming output or throws
166
+ * (`task_output_schema_mismatch`).
167
+ *
168
+ * ```ts
169
+ * const result = await agent.runTask({
170
+ * prompt: 'Find canonical info for this restaurant, then save it.',
171
+ * input: { restaurantName: 'Tartine Bakery SF' },
172
+ * tools: [
173
+ * 'searchGoogle',
174
+ * 'fetchUrl',
175
+ * { appMethod: 'saveRestaurant', description: 'Persist the researched restaurant.' },
176
+ * {
177
+ * name: 'checkExisting',
178
+ * description: 'Look up whether we already track this restaurant.',
179
+ * inputSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
180
+ * execute: async (input) => Restaurants.findByName(String(input.name)),
181
+ * },
182
+ * ],
183
+ * outputSchema: {
184
+ * type: 'object',
185
+ * properties: {
186
+ * name: { type: 'string' },
187
+ * url: { type: ['string', 'null'] },
188
+ * kind: { enum: ['bakery', 'cafe', 'restaurant'] },
189
+ * },
190
+ * required: ['name', 'kind'],
191
+ * },
192
+ * model: 'claude-4-6-sonnet',
193
+ * });
194
+ * result.output.kind; // typed as 'bakery' | 'cafe' | 'restaurant'
195
+ * ```
196
+ *
197
+ * The legacy alternative, `structuredOutputExample`, shapes output by
198
+ * example only: `output` is typed by the caller's generic argument and
199
+ * must be validated manually (check `parsedSuccessfully` first).
200
+ */
201
+ runTask<const S extends JsonObjectSchema>(options: RunTaskOptionsWithSchema<S>): Promise<RunTaskResult<FromSchema<S>>>;
202
+ runTask<T = unknown>(options: RunTaskOptionsWithExample): Promise<RunTaskResult<T>>;
203
+ /**
204
+ * Register background work with the platform so the sandbox stays alive
205
+ * until it settles (bounded at ~30 minutes) instead of being reaped as
206
+ * idle, and so an interruption is recorded in the request log if the
207
+ * sandbox is torn down anyway.
208
+ *
209
+ * Use it for the fire-and-forget pattern — kick off slow work, return
210
+ * early, write results back when it finishes:
211
+ *
212
+ * ```ts
213
+ * mindstudio.waitUntil(
214
+ * enrichRecord(id)
215
+ * .then((data) => Records.update(id, { ...data, status: 'ready' }))
216
+ * .catch(() => Records.update(id, { status: 'failed' })),
217
+ * );
218
+ * return { status: 'processing' };
219
+ * ```
220
+ *
221
+ * Failures of the registered promise are caught and logged to the request
222
+ * log — they can never crash the sandbox. Outside a managed sandbox this
223
+ * degrades to just that error-catching. If you need the result, keep your
224
+ * own reference to the promise and `await` it — `waitUntil` returns void.
225
+ */
226
+ waitUntil(promise: Promise<unknown>): void;
227
+ private _runTaskInner;
228
+ /**
229
+ * Get the authenticated user's identity and organization info.
230
+ *
231
+ * ```ts
232
+ * const info = await agent.getUserInfo();
233
+ * console.log(info.displayName, info.organizationName);
234
+ * ```
235
+ */
236
+ getUserInfo(): Promise<UserInfoResult>;
237
+ /**
238
+ * List all pre-built agents in the organization.
239
+ *
240
+ * ```ts
241
+ * const { apps } = await agent.listAgents();
242
+ * for (const app of apps) console.log(app.name, app.id);
243
+ * ```
244
+ */
245
+ listAgents(): Promise<ListAgentsResult>;
246
+ /**
247
+ * Run a pre-built agent and wait for the result.
248
+ *
249
+ * Uses async polling internally — the request returns immediately with a
250
+ * callback token, then polls until the run completes or fails.
251
+ *
252
+ * ```ts
253
+ * const result = await agent.runAgent({
254
+ * appId: 'your-agent-id',
255
+ * variables: { query: 'hello' },
256
+ * });
257
+ * console.log(result.result);
258
+ * ```
259
+ */
260
+ runAgent(options: RunAgentOptions): Promise<RunAgentResult>;
261
+ /** @internal Used by generated action methods. */
262
+ _request<T>(method: 'GET' | 'POST', path: string, body?: unknown): Promise<{
263
+ data: T;
264
+ headers: Headers;
265
+ }>;
266
+ /** List all available AI models. */
267
+ listModels(): Promise<{
268
+ models: MindStudioModel[];
269
+ }>;
270
+ /** List AI models filtered by type. */
271
+ listModelsByType(modelType: ModelType): Promise<{
272
+ models: MindStudioModel[];
273
+ }>;
274
+ /** List all available AI models (summary). Returns only id, name, type, and tags. */
275
+ listModelsSummary(): Promise<{
276
+ models: MindStudioModelSummary[];
277
+ }>;
278
+ /** List AI models (summary) filtered by type. */
279
+ listModelsSummaryByType(modelType: ModelType): Promise<{
280
+ models: MindStudioModelSummary[];
281
+ }>;
282
+ /**
283
+ * List available OAuth connector services (Slack, Google, HubSpot, etc.).
284
+ *
285
+ * These are third-party integrations from the MindStudio Connector Registry.
286
+ * For most tasks, use actions directly instead.
287
+ */
288
+ listConnectors(): Promise<{
289
+ services: ConnectorService[];
290
+ }>;
291
+ /** Get details for a single OAuth connector service. */
292
+ getConnector(serviceId: string): Promise<{
293
+ service: ConnectorService;
294
+ }>;
295
+ /** Get the full configuration for an OAuth connector action, including input fields. */
296
+ getConnectorAction(serviceId: string, actionId: string): Promise<{
297
+ action: ConnectorActionDetail;
298
+ }>;
299
+ /** List OAuth connections for the organization. These are authenticated third-party service links. */
300
+ listConnections(): Promise<{
301
+ connections: Connection[];
302
+ }>;
303
+ /** List packaged workflows available to the organization. */
304
+ listPackagedWorkflows(): Promise<{
305
+ packagedWorkflows: PackagedWorkflow[];
306
+ }>;
307
+ /** Estimate the cost of executing an action before running it. */
308
+ estimateStepCost(stepType: string, step?: Record<string, unknown>, options?: {
309
+ appId?: string;
310
+ workflowId?: string;
311
+ }): Promise<{
312
+ costType?: string;
313
+ estimates?: StepCostEstimateEntry[];
314
+ }>;
315
+ /**
316
+ * Send a stream chunk to the caller via SSE.
317
+ *
318
+ * When invoked from a method that was called with `stream: true`, chunks
319
+ * are delivered in real-time as Server-Sent Events. When there is no active
320
+ * stream (no `STREAM_ID`), calls are silently ignored — so it's safe to
321
+ * call unconditionally.
322
+ *
323
+ * Accepts strings (sent as `type: 'token'`) or structured data (sent as
324
+ * `type: 'data'`). The caller receives each chunk as an SSE event.
325
+ *
326
+ * @example
327
+ * ```ts
328
+ * // Stream text tokens
329
+ * await agent.stream('Processing item 1...');
330
+ *
331
+ * // Stream structured data
332
+ * await agent.stream({ progress: 50, currentItem: 'abc' });
333
+ * ```
334
+ */
335
+ stream: (data: string | Record<string, unknown>) => Promise<void>;
336
+ /**
337
+ * The `auth` namespace — synchronous role-based access control.
338
+ *
339
+ * Provides the current user's identity and roles. All methods are
340
+ * synchronous since the role map is preloaded during context hydration.
341
+ *
342
+ * **Important**: Context must be hydrated before accessing `auth`.
343
+ * - Inside the MindStudio sandbox: automatic (populated from globals)
344
+ * - Outside the sandbox: call `await agent.ensureContext()` first,
345
+ * or access `auth` after any `db` operation (which auto-hydrates)
346
+ *
347
+ * @throws {MindStudioError} if context has not been hydrated yet
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * await agent.ensureContext();
352
+ * agent.auth.requireRole(Roles.admin);
353
+ * const admins = agent.auth.getUsersByRole(Roles.admin);
354
+ * ```
355
+ */
356
+ get auth(): AuthContext;
357
+ /**
358
+ * The `db` namespace — chainable collection API over managed databases.
359
+ *
360
+ * Use `db.defineTable<T>(name)` to get a typed Table<T>, then call
361
+ * collection methods (filter, sortBy, push, update, etc.) on it.
362
+ *
363
+ * Context is auto-hydrated on first query execution — you can safely
364
+ * call `defineTable()` at module scope without triggering any HTTP.
365
+ *
366
+ * @example
367
+ * ```ts
368
+ * const Orders = agent.db.defineTable<Order>('orders');
369
+ * const active = await Orders.filter(o => o.status === 'active').take(10);
370
+ * ```
371
+ */
372
+ get db(): Db;
373
+ /**
374
+ * Hydrate the app context (auth + database metadata). This must be
375
+ * called before using `auth` synchronously. For `db`, hydration happens
376
+ * automatically on first query.
377
+ *
378
+ * Context is fetched once and cached for the instance's lifetime.
379
+ * Calling `ensureContext()` multiple times is safe (no-op after first).
380
+ *
381
+ * Context sources (checked in order):
382
+ * 1. Sandbox globals (`globalThis.ai.auth`, `globalThis.ai.databases`)
383
+ * 2. HTTP: `GET /developer/v2/helpers/app-context?appId={appId}`
384
+ *
385
+ * @throws {MindStudioError} if no `appId` is available
386
+ *
387
+ * @example
388
+ * ```ts
389
+ * await agent.ensureContext();
390
+ * // auth is now available synchronously
391
+ * agent.auth.requireRole(Roles.admin);
392
+ * ```
393
+ */
394
+ ensureContext(): Promise<void>;
395
+ /**
396
+ * @internal Fetch and cache app context, then create auth + db instances.
397
+ *
398
+ * In managed mode (CALLBACK_TOKEN), the platform resolves the app from
399
+ * the token — no appId needed. With an API key, appId is required.
400
+ */
401
+ private _hydrateContext;
402
+ /**
403
+ * @internal Apply a resolved context object — creates AuthContext and Db.
404
+ * Used by both the HTTP path and sandbox hydration.
405
+ */
406
+ private _applyContext;
407
+ /**
408
+ * @internal Try to hydrate context synchronously from sandbox globals.
409
+ * Called in the constructor when CALLBACK_TOKEN auth is detected.
410
+ *
411
+ * The MindStudio sandbox pre-populates `globalThis.ai` with:
412
+ * - `ai.auth`: { userId, roleAssignments[] }
413
+ * - `ai.databases`: [{ id, name, tables[] }]
414
+ */
415
+ private _trySandboxHydration;
416
+ /**
417
+ * The `files` namespace — typed, private-by-default file storage (the twin of
418
+ * `db`). No context hydration needed: the hook token identifies the app
419
+ * server-side and stores are code-defined (access travels per call).
420
+ *
421
+ * @example
422
+ * ```ts
423
+ * const Uploads = agent.files.defineStore('uploads');
424
+ * const f = await Uploads.put(buffer, { contentType: 'image/png' });
425
+ * return { url: f.url };
426
+ * ```
427
+ */
428
+ get files(): Files;
429
+ /**
430
+ * The `analytics` namespace — read the app's own traffic + event analytics
431
+ * (auto-tracked pageviews and engagement, `analytics.track()` events). One
432
+ * general `query()` (metrics × dimensions × filters × time) plus
433
+ * `funnel()`, `paths()`, `live()`, `sources()`, `map()`, `aiSources()`,
434
+ * `crawlers.*`. See {@link Analytics} for the lifetime-rollup vs
435
+ * 90-day-events split.
436
+ *
437
+ * @example
438
+ * ```ts
439
+ * const top = await agent.analytics.query({
440
+ * metrics: ['pageviews', 'visitors'],
441
+ * dimensions: ['path'],
442
+ * dateRange: 'all',
443
+ * });
444
+ * ```
445
+ */
446
+ get analytics(): Analytics;
447
+ /**
448
+ * The `events` namespace — server→client realtime. `publish()` pushes to
449
+ * named channels; `grant()` mints the subscribe token a client presents to
450
+ * the platform-held events stream. See {@link Events} for the channel-shape
451
+ * and at-most-once semantics.
452
+ *
453
+ * @example
454
+ * ```ts
455
+ * import { auth, events } from '@mindstudio-ai/agent';
456
+ *
457
+ * export async function watchJobs() {
458
+ * auth.requireRole('operator');
459
+ * return await events.grant(`jobs:${auth.userId}`); // { token, expiresAt, ttlSeconds }
460
+ * }
461
+ * ```
462
+ */
463
+ get events(): Events;
464
+ /**
465
+ * The `browser` namespace — a real Chrome your app drives. `open()` starts
466
+ * a session; every action answers with the page afterward. See
467
+ * {@link Browser}.
468
+ */
469
+ get browser(): Browser;
470
+ /**
471
+ * Outbound email: sending, the per-recipient delivery log, blast stats, and
472
+ * this app's unsubscribe list.
473
+ *
474
+ * `email.send()` is the send path — the `sendEmail` action still works and runs
475
+ * the same code, but `send()` returns a receipt including the `batchId` you read
476
+ * stats back with. Note `category` defaults to `'marketing'`; see
477
+ * {@link Email.send}.
478
+ *
479
+ * @example
480
+ * ```ts
481
+ * import { email } from '@mindstudio-ai/agent';
482
+ *
483
+ * await email.send({
484
+ * to: 'a@b.com',
485
+ * subject: 'Your receipt',
486
+ * body: 'Thanks!',
487
+ * category: 'transactional',
488
+ * });
489
+ *
490
+ * // A support lookup: did this person get their mail?
491
+ * const { messages } = await email.messages({ recipient: 'a@b.com' });
492
+ *
493
+ * // How did the August newsletter do?
494
+ * const blast = await email.batch('newsletter-2026-08');
495
+ * ```
496
+ */
497
+ get email(): Email;
498
+ /**
499
+ * Jewel surfaces: arrival-shaped triggers (`propose`) and the app-native
500
+ * approval queue (`queue.list` / `queue.resolve`). See {@link JewelsApi}.
501
+ */
502
+ get jewels(): JewelsApi;
503
+ /**
504
+ * Raw hook-token call shared by the jewels surfaces (mirrors reportIssue).
505
+ * No retries: propose holds the request for the jewel run and is idempotent
506
+ * by key anyway; resolve applies a method and must never double-fire.
507
+ */
508
+ private _jewelsRequest;
509
+ /**
510
+ * Searchable document corpora.
511
+ *
512
+ * @example
513
+ * ```ts
514
+ * const Policies = agent.dataSources.defineDataSource('policies');
515
+ * const { results } = await Policies.search('what are the payment terms?');
516
+ * ```
517
+ */
518
+ get dataSources(): DataSources;
519
+ /**
520
+ * Telephony: outbound calls answered by this app's voice agent.
521
+ *
522
+ * @example
523
+ * ```ts
524
+ * await agent.voice.call({ to: '+13105551234', assumeIdentity: true });
525
+ * ```
526
+ */
527
+ get voice(): Voice;
528
+ /**
529
+ * @internal Transport for the `files` namespace — POST /_internal/v2/files/<op>
530
+ * with the raw hook token (mirrors `_executeDbBatch`).
531
+ *
532
+ * Waits out the platform's per-app limit on file calls: its 429 comes before
533
+ * the call does anything, whatever the op, so the call is sent again every
534
+ * few seconds for a little over the limit's one-minute window, and only then
535
+ * throws `rate_limited`. An app moving files flat out runs at the limit
536
+ * rather than failing past it.
537
+ */
538
+ private _filesRequest;
539
+ /**
540
+ * @internal Transport for the `dataSources` namespace —
541
+ * POST /_internal/v2/datasources/<op> with the raw hook token.
542
+ */
543
+ private _dataSourcesRequest;
544
+ /**
545
+ * @internal Transport for the `voice` namespace —
546
+ * POST /_internal/v2/voice/<op> with the raw hook token.
547
+ */
548
+ private _voiceRequest;
549
+ /**
550
+ * @internal Transport for the `analytics` namespace —
551
+ * POST /_internal/v2/analytics/<op> with the raw hook token.
552
+ *
553
+ * Retries a single 429 after a short jittered backoff: analytics reads are
554
+ * idempotent and a 429 means the read never executed, so one retry lets a
555
+ * momentary burst (a page's fan-out racing a live poller) self-heal instead
556
+ * of surfacing as empty data. Deliberately single-shot and scoped to this
557
+ * namespace — the other brokered transports keep their semantics.
558
+ */
559
+ /**
560
+ * Brokered email transport. No 429 retry, unlike analytics: this namespace
561
+ * carries writes (suppress / unsuppress), and silently retrying a mutation is a
562
+ * different risk from retrying an idempotent read. A caller that wants one can
563
+ * retry a read itself.
564
+ */
565
+ private _emailRequest;
566
+ /**
567
+ * @internal Transport for the `events` namespace —
568
+ * POST /_internal/v2/app-events/<op> with the raw hook token.
569
+ *
570
+ * No 429 retry: a retried publish is a duplicate nudge, and grants are
571
+ * cheap for the caller to re-request. Errors throw (unlike `stream()`) —
572
+ * publishing is an explicit act, and "nobody was listening" is expressed as
573
+ * `delivered: 0`, never as an HTTP failure.
574
+ */
575
+ private _eventsRequest;
576
+ /**
577
+ * @internal Transport for the `browser` namespace —
578
+ * POST /_internal/v2/browser/<op> with the raw hook token. No 429 retry:
579
+ * an action repeated is a second click.
580
+ */
581
+ private _browserRequest;
582
+ private _analyticsRequest;
583
+ /**
584
+ * @internal Shared shape for the brokered `/_internal/v2/<ns>/<op>` data
585
+ * planes. Factored out rather than copied per namespace so error handling
586
+ * can't drift between them.
587
+ */
588
+ private _brokeredRequest;
589
+ /** @internal Reads started together share a round trip (`db/readBatching.ts`). */
590
+ private readonly _dbReads;
591
+ /**
592
+ * @internal Execute a batch of SQL queries against a managed database.
593
+ * Used as the `executeBatch` callback for Table/Query instances. Reads one
594
+ * request starts in the same tick go to the platform as one batch.
595
+ */
596
+ private _executeDbBatch;
597
+ /**
598
+ * @internal Send one batch: `POST /_internal/v2/db/query` directly with the
599
+ * hook token (raw, no Bearer prefix), or its DB WebSocket. All queries run
600
+ * on a single SQLite connection, enabling RETURNING clauses and
601
+ * multi-statement batches.
602
+ */
603
+ private _sendDbBatch;
604
+ /**
605
+ * @internal Sync a user's roles to the platform after a successful
606
+ * auth table write. Calls POST /_internal/v2/auth/sync-user.
607
+ * Fire-and-forget: errors are caught and logged, never propagated.
608
+ */
609
+ private _syncRoles;
610
+ /**
611
+ * @internal Create a lazy Db proxy that auto-hydrates context.
612
+ *
613
+ * defineTable() returns Table instances immediately (no async needed).
614
+ * But the Table's executeBatch callback is wrapped to call ensureContext()
615
+ * before the first query, so context is fetched lazily.
616
+ */
617
+ private _createLazyDb;
618
+ /**
619
+ * Resolve a single user ID to display info (name, email, profile picture).
620
+ *
621
+ * Use this when you have a `User`-typed field value and need the person's
622
+ * display name, email, or avatar. Returns null if the user ID is not found.
623
+ *
624
+ * Also available as a top-level import:
625
+ * ```ts
626
+ * import { resolveUser } from '@mindstudio-ai/agent';
627
+ * ```
628
+ *
629
+ * @param userId - The user ID to resolve (a `User` branded string or plain UUID)
630
+ * @returns Resolved user info, or null if not found
631
+ *
632
+ * @example
633
+ * ```ts
634
+ * const user = await agent.resolveUser(order.requestedBy);
635
+ * if (user) {
636
+ * console.log(user.name); // "Jane Smith"
637
+ * console.log(user.email); // "jane@example.com"
638
+ * console.log(user.profilePictureUrl); // "https://..." or null
639
+ * }
640
+ * ```
641
+ */
642
+ resolveUser(userId: string): Promise<ResolvedUser | null>;
643
+ /**
644
+ * Resolve multiple user IDs to display info in a single request.
645
+ * Maximum 100 user IDs per request.
646
+ *
647
+ * Use this for batch resolution when you have multiple user references
648
+ * to display (e.g. all approvers on a purchase order, all team members).
649
+ *
650
+ * @param userIds - Array of user IDs to resolve (max 100)
651
+ * @returns Object with `users` array of resolved user info
652
+ *
653
+ * @example
654
+ * ```ts
655
+ * // Resolve all approvers at once
656
+ * const approverIds = approvals.map(a => a.assignedTo);
657
+ * const { users } = await agent.resolveUsers(approverIds);
658
+ *
659
+ * for (const u of users) {
660
+ * console.log(`${u.name} (${u.email})`);
661
+ * }
662
+ * ```
663
+ */
664
+ resolveUsers(userIds: string[]): Promise<{
665
+ users: ResolvedUser[];
666
+ }>;
667
+ /**
668
+ * File a bug report or feature idea into this app's issue tracker.
669
+ *
670
+ * For building an in-app "Report a bug" feature: wire the frontend UI to
671
+ * an app backend method that calls this. The issue lands in the app's
672
+ * issue tracker, visible to the app's team and available to the Remy agent.
673
+ *
674
+ * **Backend / managed-context only.** It authenticates with the app's hook
675
+ * token (the same credential used for `db` queries), and the app id is
676
+ * derived from that token server-side. Calling it outside a managed
677
+ * context (e.g. with a plain API key) will fail with `401`.
678
+ *
679
+ * Rate limited per app (20 / 60s). On the limit this throws a
680
+ * `MindStudioError` with `code === 'rate_limited'` and `status === 429` —
681
+ * catch it to show a graceful "try again shortly" message. Every call
682
+ * creates a new issue (no dedupe), so guard against double-submit in the UI.
683
+ *
684
+ * @returns The filed issue. Show `issue.number` to confirm "Reported as #42".
685
+ *
686
+ * @example
687
+ * ```ts
688
+ * // app backend method, e.g. exported as `reportBug`
689
+ * export async function reportBug({ title, details, userEmail }) {
690
+ * try {
691
+ * const { number } = await mindstudio.reportIssue({
692
+ * title,
693
+ * body: details,
694
+ * kind: 'bug',
695
+ * reporter: userEmail, // free-form label; omit for anonymous
696
+ * });
697
+ * return { ok: true, issueNumber: number };
698
+ * } catch (e) {
699
+ * if (e instanceof MindStudioError && e.code === 'rate_limited') {
700
+ * return { ok: false, retry: true };
701
+ * }
702
+ * throw e;
703
+ * }
704
+ * }
705
+ * ```
706
+ */
707
+ reportIssue(input: ReportIssueInput): Promise<ReportedIssue>;
708
+ /**
709
+ * Invalidate the prerendered snapshot(s) for the current app so crawlers get
710
+ * a fresh render on their next visit. Call after content behind a prerendered
711
+ * page changes (e.g. a short URL's target). Omit `paths` (or pass an empty
712
+ * array) to purge every snapshot for the app.
713
+ *
714
+ * `paths` are this app's OWN route paths (`/u/abc`), which purge the page
715
+ * whatever host it is served on, or full URLs (`https://site-a.com/u/abc`),
716
+ * which purge it on that host only. If another app mounts this one under a
717
+ * path prefix, the copies cached at that prefix are purged too — no need to
718
+ * know or pass the mount path.
719
+ *
720
+ * Raw hook-token call (mirrors `reportIssue`) — the appId comes from the
721
+ * token. Backend / managed-context only.
722
+ *
723
+ * ```ts
724
+ * await mindstudio.invalidatePrerender(['/u/abc']);
725
+ * ```
726
+ */
727
+ invalidatePrerender(paths?: string[]): Promise<{
728
+ purged: number | 'all';
729
+ }>;
730
+ /**
731
+ * Get auth and database context for an app.
732
+ *
733
+ * Returns role assignments and managed database schemas. Useful for
734
+ * hydrating `auth` and `db` namespaces when running outside the sandbox.
735
+ *
736
+ * When called with a CALLBACK_TOKEN (managed mode), `appId` is optional —
737
+ * the platform resolves the app from the token. With an API key, `appId`
738
+ * is required.
739
+ *
740
+ * ```ts
741
+ * const ctx = await agent.getAppContext('your-app-id');
742
+ * console.log(ctx.auth.roleAssignments, ctx.databases);
743
+ * ```
744
+ */
745
+ getAppContext(appId?: string): Promise<AppContextResult>;
746
+ /** Update the display name of the authenticated user/agent. */
747
+ changeName(displayName: string): Promise<void>;
748
+ /** Update the profile picture of the authenticated user/agent. */
749
+ changeProfilePicture(url: string): Promise<void>;
750
+ /**
751
+ * Upload a file to the MindStudio CDN.
752
+ *
753
+ * Gets a presigned upload request from the API, POSTs the file as
754
+ * multipart/form-data, and returns the permanent public URL.
755
+ *
756
+ * @deprecated For app file storage use the `files` store
757
+ * (`files.defineStore(...).put(...)`) — private by default, app-scoped, and
758
+ * served on the app's own domain. `uploadFile` uploads to the shared account
759
+ * media CDN; it remains only for account-level assets (e.g. an agent avatar
760
+ * passed to `changeProfilePicture`).
761
+ */
762
+ uploadFile(content: Buffer | Uint8Array, options: {
763
+ extension: string;
764
+ type?: string;
765
+ filename?: string;
766
+ }): Promise<UploadFileResult>;
767
+ }