@mindstudio-ai/agent 0.1.175 → 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 (50) hide show
  1. package/CHANGELOG.md +14 -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 +52 -33
  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 -13323
  35. package/dist/index.js +39 -20
  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/llms.txt +1 -1
  49. package/package.json +6 -12
  50. package/dist/postinstall.js +0 -12096
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Readers — customer code run over every document a data source builds.
3
+ *
4
+ * A mapper is app code on the way in (a raw object becomes documents) and
5
+ * must be pure. A READER is app code on the way out: once a document is
6
+ * built, its reader reads it and writes what it found into the app's own
7
+ * tables. Writing is its purpose. It is how an app discovers what its
8
+ * documents say: which equipment a passage names, what relations it states,
9
+ * which people it quotes, as the app's own domain defines them.
10
+ *
11
+ * ```ts
12
+ * // datasources/manuals.reader.ts
13
+ * export default defineReader(Manuals, {
14
+ * read: async (document) => {
15
+ * const found = await extractRelations(await document.chunks());
16
+ * await Evidence.removeAll((r, $) => r.documentId === $.id, { id: document.id });
17
+ * await Evidence.push(found.map((f) => ({ ...f, documentId: document.id, sourceId: document.sourceId })));
18
+ * },
19
+ * removed: async (documentId) => {
20
+ * await Evidence.removeAll((r, $) => r.documentId === $.id, { id: documentId });
21
+ * },
22
+ * cleared: async (sourceId) => {
23
+ * await Evidence.removeAll((r, $) => r.sourceId === $.id, { id: sourceId });
24
+ * },
25
+ * });
26
+ * ```
27
+ *
28
+ * The one rule: **a reader may be called more than once for the same
29
+ * document, so it replaces that document's rows as a set, and deletes them on
30
+ * `removed`.** Deliveries are level-triggered: the platform says only that a
31
+ * document changed and reads its state when it delivers, so a document built
32
+ * and removed before its delivery is one `removed`, and the app's rows always
33
+ * end on what the corpus holds.
34
+ *
35
+ * - `read(document)` — a document arrived: its first build on the source's
36
+ * active version. Never for index maintenance (a rebuild, a relink, a
37
+ * re-vectorize) or an in-place metadata change: the reader is about what the
38
+ * text says, and the app already knows what it asserted.
39
+ * - `removed(documentId)` — the document is gone. Only the id: removal clears
40
+ * what named the document.
41
+ * - `cleared(sourceId)` — the whole source was deleted, once, so the app can
42
+ * drop that source's rows in one statement. Optional.
43
+ * - `relinked(document)` — a document already read was re-tagged by a new
44
+ * dictionary: its passages carry different entities, its text is the same.
45
+ * For rows derived from the tags. Optional.
46
+ * A throw fails that delivery; the platform retries it. `document.bytes()`
47
+ * reads the file the document came from, for a reader that needs the drawing
48
+ * itself rather than its text.
49
+ *
50
+ * A reader runs against the app's LIVE release (or the dev session under
51
+ * `reader test --dev`), never a pinned one: app databases are per release, so
52
+ * a reader bound to a superseded release would write where nobody reads. It
53
+ * is whatever live declares, and activates by publishing.
54
+ *
55
+ * Declared in `mindstudio.json`, beside or instead of a mapper:
56
+ * ```json
57
+ * "dataSources": [{ "slug": "manuals", "reader": { "path": "dist/datasources/manuals.reader.ts" } }]
58
+ * ```
59
+ */
60
+ import type { DataSourceChunk, DocumentMetadata } from '../datasources/source.js';
61
+ /** A built document, as `read` receives it. */
62
+ export interface ReaderDocument {
63
+ id: string;
64
+ /** The data source it belongs to: key your rows by it for `cleared`. */
65
+ sourceId: string;
66
+ filename: string | null;
67
+ contentType: string | null;
68
+ /** The identity a mapped source replaces by; null on unmapped sources. */
69
+ externalId: string | null;
70
+ metadata: DocumentMetadata | null;
71
+ /** The entities the document asserts, sorted. */
72
+ entities: string[];
73
+ pageCount: number | null;
74
+ chunkCount: number | null;
75
+ createdAt: string;
76
+ /**
77
+ * A short-lived link to the file the document came from: the uploaded
78
+ * file, or on a mapped source the raw object the mapper read. Valid for the
79
+ * delivery; null when the file is no longer kept.
80
+ */
81
+ url: string | null;
82
+ /**
83
+ * The document's passages as indexed: text, page, heading path, and each
84
+ * passage's entities (its document's asserted ones and those its text
85
+ * names from the source's dictionary). Read once, then held.
86
+ */
87
+ chunks(): Promise<DataSourceChunk[]>;
88
+ /** The bytes behind {@link url}: a drawing's image, a PDF's pages. Read once, then held. */
89
+ bytes(): Promise<Uint8Array>;
90
+ }
91
+ type MaybePromise<T> = T | Promise<T>;
92
+ export interface ReaderConfig {
93
+ read: (document: ReaderDocument) => MaybePromise<void>;
94
+ removed: (documentId: string) => MaybePromise<void>;
95
+ cleared?: (sourceId: string) => MaybePromise<void>;
96
+ /**
97
+ * A document already read was re-tagged: the source's dictionary changed,
98
+ * and its passages' entities with it. The document arrives as `read` gets
99
+ * it, chunks and all, carrying the new entities, so rows derived from the
100
+ * tags (links from assets to documents) can follow. Nothing about the text
101
+ * changed, so this is no reason to extract again. Optional: without it a
102
+ * relink delivers nothing.
103
+ */
104
+ relinked?: (document: ReaderDocument) => MaybePromise<void>;
105
+ }
106
+ type DocumentDelivery = {
107
+ document: Omit<ReaderDocument, 'chunks' | 'bytes'>;
108
+ /** The passages, when the platform carried them inline. */
109
+ chunks?: DataSourceChunk[];
110
+ };
111
+ /** One delivery as the platform hands it to the executor. */
112
+ export type ReadDelivery = ({
113
+ kind: 'read';
114
+ } & DocumentDelivery) | ({
115
+ kind: 'relinked';
116
+ } & DocumentDelivery) | {
117
+ kind: 'removed';
118
+ documentId: string;
119
+ } | {
120
+ kind: 'cleared';
121
+ sourceId: string;
122
+ };
123
+ export interface ReadRunParams {
124
+ v: 1;
125
+ deliveries: ReadDelivery[];
126
+ /** Per-delivery budget, in milliseconds. */
127
+ timeoutMs?: number;
128
+ /** Deliveries run at once inside the frame. */
129
+ concurrency?: number;
130
+ }
131
+ export interface ReadRunResult {
132
+ /** The document id, or the source id for `cleared`. */
133
+ ref: string;
134
+ kind: ReadDelivery['kind'];
135
+ ok: boolean;
136
+ error?: {
137
+ message: string;
138
+ stack?: string;
139
+ };
140
+ durationMs: number;
141
+ }
142
+ /** What one executor call returns: one result per delivery, in order. */
143
+ export interface ReadRunRecord {
144
+ v: 1;
145
+ source: string;
146
+ outcomes: ReadRunResult[];
147
+ /** The optional hooks this reader defines, so the platform sends only what one handles. */
148
+ hooks: {
149
+ relinked: boolean;
150
+ };
151
+ startedAt: number;
152
+ durationMs: number;
153
+ }
154
+ /** The callable executor with its config attached. */
155
+ export interface Reader {
156
+ (params: ReadRunParams): Promise<ReadRunRecord>;
157
+ readonly kind: 'reader';
158
+ /** The data source's slug. */
159
+ readonly source: string;
160
+ readonly config: ReaderConfig;
161
+ }
162
+ /**
163
+ * Define a reader — the code that reads every document a data source builds
164
+ * into the app's own tables. See the module doc for the contract.
165
+ */
166
+ export declare function defineReader(source: {
167
+ readonly name: string;
168
+ chunks(documentId: string): Promise<DataSourceChunk[]>;
169
+ }, config: ReaderConfig): Reader;
170
+ export {};
@@ -0,0 +1,68 @@
1
+ import type { FileAccess } from './files/store.js';
2
+ /** The largest inline body, in bytes. A larger one is a stored file: `respond.file`. */
3
+ export declare const RESPONSE_BODY_MAX_BYTES: number;
4
+ /** Response headers. An array sends the header once per value (`Set-Cookie`). */
5
+ export type HttpResponseHeaders = Record<string, string | string[]>;
6
+ export interface HttpResponseInit {
7
+ /** 200 to 599. Defaults to 200. */
8
+ status?: number;
9
+ headers?: HttpResponseHeaders;
10
+ }
11
+ export interface HttpResponseOptions extends HttpResponseInit {
12
+ /** Text, or bytes (`Uint8Array` or `Buffer`). */
13
+ body?: string | Uint8Array;
14
+ }
15
+ /** A stored file to answer with: what a store's `put`, `get` or `list` returns. */
16
+ export interface HttpResponseFile {
17
+ store: string;
18
+ key: string;
19
+ access: FileAccess;
20
+ }
21
+ /** A response a method returns. Build one with {@link respond}. */
22
+ export declare class HttpResponse {
23
+ readonly status: number;
24
+ readonly headers: HttpResponseHeaders;
25
+ readonly body?: string | Uint8Array;
26
+ readonly file?: HttpResponseFile;
27
+ constructor(options: HttpResponseOptions & {
28
+ file?: HttpResponseFile;
29
+ });
30
+ toJSON(): Record<string, unknown>;
31
+ }
32
+ /**
33
+ * Answer an API or webhook request with an HTTP response of the method's own:
34
+ * a status, headers and a text or binary body.
35
+ *
36
+ * Only for a method whose answer is HTTP itself. A method that returns data
37
+ * keeps returning it, and every caller gets it; a method that returns a
38
+ * response can only be called through the API and webhook interfaces. A
39
+ * failure any caller should see is still a thrown `MindStudioError`.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * import { respond } from '@mindstudio-ai/agent';
44
+ *
45
+ * export async function voiceCall() {
46
+ * return respond.text('<Response><Say>Hello</Say></Response>', {
47
+ * headers: { 'Content-Type': 'text/xml' },
48
+ * });
49
+ * }
50
+ * ```
51
+ */
52
+ export declare const respond: ((options?: HttpResponseOptions) => HttpResponse) & {
53
+ /** Text, as `text/plain; charset=utf-8` unless the headers name a type. */
54
+ text(body: string, init?: HttpResponseInit): HttpResponse;
55
+ /** JSON, with a status or headers of the method's choosing. */
56
+ json(value: unknown, init?: HttpResponseInit): HttpResponse;
57
+ /** A redirect: 301, 302 (the default), 303, 307 or 308. */
58
+ redirect(url: string, status?: number): HttpResponse;
59
+ /**
60
+ * A stored file, sent at the request's own URL with no redirect for the
61
+ * client to follow. The bytes come straight from storage, never through
62
+ * the method, so a file of any size works, and range requests too. The
63
+ * stored content type is sent unless the headers name one.
64
+ */
65
+ file(file: HttpResponseFile, init?: {
66
+ headers?: HttpResponseHeaders;
67
+ }): HttpResponse;
68
+ };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Task agents — the public types, and the tool mapping and dev-mode logging
3
+ * the loop in `local.ts` uses.
4
+ *
5
+ * The developer provides a prompt, a set of SDK actions as tools, and an
6
+ * output schema or example. The loop (model → tool calls → results → repeat)
7
+ * runs in the caller's process, over the API's per-turn route.
8
+ */
9
+ import type { TaskToolConfig, RunTaskResult, TaskWireTool } from './types.js';
10
+ export type { TaskToolConfig, RunTaskOptions, RunTaskOptionsWithExample, RunTaskOptionsWithSchema, RunTaskResult, TaskEvent, TaskUsage, TaskToolCall, } from './types.js';
11
+ export type { JsonSchema, JsonObjectSchema, JsonSchemaTypeName, FromSchema, SchemaValidationError, } from './schema.js';
12
+ /** Map developer tool configs to API request format with alias resolution. */
13
+ export declare function mapTools(tools: TaskToolConfig[]): TaskWireTool[];
14
+ export declare function sleep(ms: number): Promise<void>;
15
+ /** Check if running in managed/sandbox mode (dev tunnel or ALS). */
16
+ export declare function isDevMode(): boolean;
17
+ /** Log task result summary to console in dev mode. */
18
+ export declare function logTaskResult(result: RunTaskResult<unknown>): void;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * SDK-owned task loop.
3
+ *
4
+ * The loop lives in the caller's process (sandbox pod, dev tunnel, or the
5
+ * developer's own server) and uses the API as a stateless per-turn transport
6
+ * (`POST /developer/v2/task/turn`), the same shape Remy uses its chat
7
+ * endpoint. That's what makes tasks survive platform deploys: API pods are
8
+ * recycled on every roll and used to take in-flight server-side loops with
9
+ * them, while the processes that call `runTask()` are not.
10
+ *
11
+ * Each turn is retried on transient transport failures with per-attempt event
12
+ * buffering — a failed attempt's partial output never reaches the accumulated
13
+ * messages or the caller's `onEvent`. Tool calls execute from here (steps via
14
+ * the normal step-execute path, app methods via `/task/invoke-method`) and are
15
+ * NOT retried blindly: they have side effects, and a failure is fed back to
16
+ * the model as tool output for it to work around.
17
+ *
18
+ * The legacy whole-task routes remain server-side for SDK versions pinned in
19
+ * already-shipped releases.
20
+ */
21
+ import { type HttpClientConfig } from '../http.js';
22
+ import type { RunTaskOptions, RunTaskResult } from './types.js';
23
+ /**
24
+ * Merge the developer's tool defaults over the model's tool call arguments.
25
+ * Defaults win on every key they specify, including nested fields — the model
26
+ * decides what to do, the developer pins which model/config it does it with.
27
+ * Only plain objects recurse; arrays and everything else replace wholesale.
28
+ */
29
+ export declare function mergeToolInput(modelInput: Record<string, unknown>, defaults: Record<string, unknown>): Record<string, unknown>;
30
+ export interface ToolExecutionResult {
31
+ output: unknown;
32
+ billingCost: number;
33
+ isError: boolean;
34
+ }
35
+ export interface TaskLoopDeps {
36
+ httpConfig: HttpClientConfig;
37
+ /** Executes a step tool. Must not throw — failures come back as
38
+ * `{ output: { error }, isError: true }` for the model to work around. */
39
+ executeStepTool: (stepType: string, input: Record<string, unknown>) => Promise<ToolExecutionResult>;
40
+ /** Executes an app-method tool. Same no-throw contract. `call` names the
41
+ * task and tool call, which the platform records on the method's
42
+ * request-log row so the task's trace can point at it. */
43
+ executeMethodTool: (methodId: string, input: Record<string, unknown>, call: {
44
+ traceId: string;
45
+ toolCallId: string;
46
+ }) => Promise<ToolExecutionResult>;
47
+ }
48
+ export declare function runTaskLocal<T = unknown>(deps: TaskLoopDeps, options: RunTaskOptions): Promise<RunTaskResult<T>>;
@@ -0,0 +1,120 @@
1
+ /**
2
+ * JSON Schema support for task-agent structured output.
3
+ *
4
+ * The dialect is a deliberately bounded subset of JSON Schema — the shape
5
+ * used for Anthropic tool `input_schema` / OpenAI function parameters:
6
+ * `type` (including type arrays for nullability), `properties`, `required`,
7
+ * `additionalProperties`, `items`, `enum`, `const`. Everything in this file
8
+ * covers exactly that subset and nothing more, on both levels:
9
+ *
10
+ * - {@link FromSchema} maps a schema *value* to the TypeScript type it
11
+ * describes (compile time).
12
+ * - {@link validateAgainstSchema} checks a runtime value against the same
13
+ * constructs (runtime).
14
+ *
15
+ * Keeping the two in one module is the point: what the type infers is what
16
+ * the validator enforces. Schemas using keywords outside the subset are
17
+ * rejected loudly by {@link assertSupportedSchema} rather than silently
18
+ * half-enforced.
19
+ */
20
+ export type JsonSchemaTypeName = 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';
21
+ /**
22
+ * A schema in the supported dialect. Every position is readonly so inline
23
+ * literals inferred via `const` type parameters (which produce readonly
24
+ * tuples/objects) are assignable.
25
+ */
26
+ export interface JsonSchema {
27
+ readonly type?: JsonSchemaTypeName | readonly JsonSchemaTypeName[];
28
+ readonly properties?: Readonly<Record<string, JsonSchema>>;
29
+ readonly required?: readonly string[];
30
+ readonly additionalProperties?: boolean;
31
+ readonly items?: JsonSchema;
32
+ readonly enum?: readonly (string | number | boolean | null)[];
33
+ readonly const?: string | number | boolean | null;
34
+ readonly description?: string;
35
+ }
36
+ /**
37
+ * The root schema for task output must be an object schema. The literal
38
+ * `type: 'object'` requirement also anchors overload resolution on
39
+ * `runTask` — without it, nearly any object type would satisfy the schema
40
+ * overload's constraint (every `JsonSchema` property is optional).
41
+ */
42
+ export interface JsonObjectSchema extends JsonSchema {
43
+ readonly type: 'object';
44
+ readonly properties: Readonly<Record<string, JsonSchema>>;
45
+ }
46
+ /**
47
+ * Infers the TypeScript type described by a schema literal.
48
+ *
49
+ * ```ts
50
+ * const schema = {
51
+ * type: 'object',
52
+ * properties: {
53
+ * action: { enum: ['approve', 'reject'] },
54
+ * note: { type: ['string', 'null'] },
55
+ * },
56
+ * required: ['action'],
57
+ * } as const satisfies JsonObjectSchema;
58
+ *
59
+ * type Out = FromSchema<typeof schema>;
60
+ * // { action: 'approve' | 'reject'; note?: string | null }
61
+ * ```
62
+ */
63
+ export type FromSchema<S> = S extends {
64
+ const: infer C;
65
+ } ? C : S extends {
66
+ enum: readonly (infer E)[];
67
+ } ? E : S extends {
68
+ type: readonly (infer TN extends JsonSchemaTypeName)[];
69
+ } ? FromTypeName<TN, S> : S extends {
70
+ type: infer TN extends JsonSchemaTypeName;
71
+ } ? FromTypeName<TN, S> : unknown;
72
+ /** Distributes over union type names, so `['string','null']` → `string | null`. */
73
+ type FromTypeName<TN extends JsonSchemaTypeName, S> = (TN extends 'string' ? string : never) | (TN extends 'number' | 'integer' ? number : never) | (TN extends 'boolean' ? boolean : never) | (TN extends 'null' ? null : never) | (TN extends 'array' ? S extends {
74
+ items: infer I;
75
+ } ? FromSchema<I>[] : unknown[] : never) | (TN extends 'object' ? FromObjectSchema<S> : never);
76
+ type RequiredKeys<S> = S extends {
77
+ required: readonly (infer R extends string)[];
78
+ } ? R : never;
79
+ type FromObjectSchema<S> = S extends {
80
+ properties: infer P;
81
+ } ? Prettify<{
82
+ [K in Extract<keyof P, RequiredKeys<S>>]: FromSchema<P[K]>;
83
+ } & {
84
+ [K in Exclude<keyof P, RequiredKeys<S>>]?: FromSchema<P[K]>;
85
+ }> : Record<string, unknown>;
86
+ /** Collapses the required/optional intersection into one readable object type. */
87
+ type Prettify<T> = {
88
+ [K in keyof T]: T[K];
89
+ } & {};
90
+ export interface SchemaValidationError {
91
+ /** JSONPath-style location, e.g. `$.items[2].severity`. */
92
+ path: string;
93
+ /** Human-readable problem, e.g. `expected one of "low" | "high", got "critical"`. */
94
+ message: string;
95
+ }
96
+ /**
97
+ * Validate a value against a schema in the supported dialect. Returns a flat
98
+ * list of every violation (empty = valid). Checks exactly the constructs
99
+ * {@link FromSchema} maps: type (including type arrays), enum, const,
100
+ * required, properties, items, and `additionalProperties: false`. Extra
101
+ * properties are allowed unless `additionalProperties` is explicitly false,
102
+ * matching JSON Schema semantics.
103
+ */
104
+ export declare function validateAgainstSchema(value: unknown, schema: JsonSchema): SchemaValidationError[];
105
+ /** Bulleted list for the repair message sent back to the model. */
106
+ export declare function formatValidationErrors(errors: SchemaValidationError[]): string;
107
+ /**
108
+ * Reject schemas that use keywords outside the supported dialect. Without
109
+ * this, an `oneOf` or `$ref` would be silently unenforced (the validator
110
+ * skips what it doesn't know) while still shaping the model's output —
111
+ * exactly the kind of quiet half-contract this feature exists to eliminate.
112
+ * Throws `task_output_schema_unsupported`.
113
+ */
114
+ export declare function assertSupportedSchema(schema: JsonObjectSchema): void;
115
+ /**
116
+ * Strip a wrapping markdown code fence (```json ... ```) from model output.
117
+ * Used only in schema mode — the example path keeps its historical behavior.
118
+ */
119
+ export declare function stripCodeFences(text: string): string;
120
+ export {};
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Types for the task agent runtime.
3
+ *
4
+ * A task agent is a multi-step tool-use loop: the model receives a prompt
5
+ * and a set of SDK actions as tools, calls them as needed, and produces
6
+ * structured output — validated against the developer's `outputSchema`, or
7
+ * shaped by a `structuredOutputExample`.
8
+ */
9
+ import type { JsonObjectSchema } from './schema.js';
10
+ /**
11
+ * Tool configuration for {@link RunTaskOptions.tools}.
12
+ * - String: SDK method name (e.g. `'searchGoogle'`).
13
+ * - `{ method }`: SDK method name with default input overrides.
14
+ * - `{ appMethod }`: one of your own app's methods, called as the invoking
15
+ * user with their roles.
16
+ * - `{ name, execute }`: an inline function tool, executed right here in your
17
+ * process. No platform dispatch, no billing — just your code.
18
+ *
19
+ * Defaults win over whatever the model passes for the same field, including
20
+ * nested fields — the model decides what to do, you pin how it's done.
21
+ * Function tools take no defaults: close over what you need instead.
22
+ */
23
+ export type TaskToolConfig = string | {
24
+ method: string;
25
+ defaults?: Record<string, unknown>;
26
+ } | {
27
+ appMethod: string;
28
+ /**
29
+ * How this method should be framed for *this* task. Falls back to the
30
+ * method's own description. Worth writing: the same method often serves
31
+ * different purposes across tasks, and the description is what tells the
32
+ * model when to reach for it.
33
+ */
34
+ description?: string;
35
+ defaults?: Record<string, unknown>;
36
+ } | {
37
+ /** Tool name the model sees. Letters, digits, `_`, `-`; max 64 chars. */
38
+ name: string;
39
+ /** What the tool does and when to reach for it — all the model gets. */
40
+ description: string;
41
+ /** JSON Schema for the input (tool-definition dialect). Omitted means
42
+ * the tool takes no arguments. */
43
+ inputSchema?: JsonObjectSchema;
44
+ /**
45
+ * Runs in this process when the model calls the tool. A thrown error is
46
+ * fed back to the model as `{ error }` tool output to work around — it
47
+ * never fails the task. Note: calling `runTask` from inside a function
48
+ * tool is not depth-capped (the server cap rides the method's token,
49
+ * which a function tool reuses) — recursion is yours to bound.
50
+ */
51
+ execute: (input: Record<string, unknown>) => Promise<unknown> | unknown;
52
+ /**
53
+ * For a tool whose result is the state of something now (a page, a
54
+ * board), which a newer result makes stale: a key shared by the tools
55
+ * that report that state. Each successful result replaces the earlier
56
+ * ones under the same key in what the model is sent with a one-line
57
+ * note, so a long run keeps only the latest in full. `toolCalls`,
58
+ * `onEvent` and the trace still carry every result.
59
+ */
60
+ supersedes?: string;
61
+ };
62
+ /** Options shared by both output modes of {@link MindStudioAgent.runTask}. */
63
+ interface RunTaskOptionsBase {
64
+ /** System prompt — defines the agent's behavior and approach. */
65
+ prompt: string;
66
+ /** Structured input for this task instance. Passed as the user message. */
67
+ input: Record<string, unknown>;
68
+ /** SDK actions, app methods, and/or inline function tools to make
69
+ * available to the model. */
70
+ tools: TaskToolConfig[];
71
+ /**
72
+ * Model ID for the task agent. Must support tool use. Tuned model lines
73
+ * (`tuned/{appId}/{methodId}`) are supported — that's how a jewel is
74
+ * promoted onto its own fine-tuned model; tool support depends on the
75
+ * tuned model's base (qwen bases: yes) and is enforced server-side with a
76
+ * deterministic error.
77
+ */
78
+ model: string;
79
+ /** Max loop iterations before forcing final output. Default 20, max 100. */
80
+ maxTurns?: number;
81
+ /**
82
+ * How much of each tool result reaches the model, in characters of its
83
+ * JSON. Default 50,000. A larger result is cut to this, and the model gets
84
+ * a record that says so instead: `{ truncated: true, totalChars, shownChars,
85
+ * content }`, `content` being the beginning of the result's JSON. The call's
86
+ * entry in `toolCalls` is marked `truncated` too. Every result stays in the
87
+ * transcript, which is resent on every later turn, so raising this costs
88
+ * tokens on every turn after a large result, and the whole transcript has to
89
+ * fit the model's context window.
90
+ */
91
+ maxToolOutputChars?: number;
92
+ /** App ID to execute within. */
93
+ appId?: string;
94
+ /** Thread ID for state persistence. */
95
+ threadId?: string;
96
+ /**
97
+ * Event callback: text chunks, thinking, tool call starts and results,
98
+ * errors, and the final `done` event with the structured output. A turn's
99
+ * events arrive together once the turn succeeds, so a retried attempt never
100
+ * reaches it. It doesn't change how the task runs.
101
+ */
102
+ onEvent?: (event: TaskEvent) => void;
103
+ }
104
+ /**
105
+ * Example mode: the output shape is suggested by example only. `output` is
106
+ * whatever `JSON.parse` produced (or the raw string when
107
+ * `parsedSuccessfully` is false) — callers must validate it themselves.
108
+ */
109
+ export interface RunTaskOptionsWithExample extends RunTaskOptionsBase {
110
+ /** Expected output shape. Pass a JSON string or an object (will be stringified automatically). */
111
+ structuredOutputExample: string | Record<string, unknown>;
112
+ outputSchema?: never;
113
+ }
114
+ /**
115
+ * Schema mode: the output contract is a plain JSON Schema (the Anthropic
116
+ * tool `input_schema` dialect subset — type/properties/required/enum/items,
117
+ * nullability via type arrays like `['string', 'null']`). Output is
118
+ * validated every turn with automatic repair, `result.output` is typed by
119
+ * inference from the schema value, and `runTask` either returns conforming
120
+ * output or throws (`task_output_schema_mismatch`) — it never resolves with
121
+ * garbage.
122
+ */
123
+ export interface RunTaskOptionsWithSchema<S extends JsonObjectSchema = JsonObjectSchema> extends RunTaskOptionsBase {
124
+ /** Plain JSON Schema for the output. Root must be `type: 'object'`. */
125
+ outputSchema: S;
126
+ structuredOutputExample?: never;
127
+ }
128
+ /** Options for {@link MindStudioAgent.runTask} — one of the two output modes. */
129
+ export type RunTaskOptions = RunTaskOptionsWithExample | RunTaskOptionsWithSchema;
130
+ /** An event from a streaming task agent execution. */
131
+ export interface TaskEvent {
132
+ type: 'text' | 'thinking' | 'thinking_complete' | 'tool_use' | 'tool_input_delta' | 'tool_input_args' | 'tool_call_start' | 'tool_call_result' | 'error' | 'done';
133
+ [key: string]: unknown;
134
+ }
135
+ /** Summary of a single tool call within a task execution. */
136
+ export interface TaskToolCall {
137
+ name: string;
138
+ success: boolean;
139
+ durationMs: number;
140
+ /** The result was over `maxToolOutputChars`, so the model got only its beginning. */
141
+ truncated?: boolean;
142
+ }
143
+ /** Usage stats from a task agent execution. */
144
+ export interface TaskUsage {
145
+ inputTokens: number;
146
+ outputTokens: number;
147
+ /** Prompt tokens written to and read from the model's prompt cache. */
148
+ cacheCreationTokens?: number;
149
+ cacheReadTokens?: number;
150
+ /** Total cost in nanodollars (1/1,000,000,000th of a US dollar). */
151
+ totalBillingCost: number;
152
+ }
153
+ /** Result of {@link MindStudioAgent.runTask}. */
154
+ export interface RunTaskResult<T = unknown> {
155
+ /** Structured output from the task agent, parsed as JSON. */
156
+ output: T;
157
+ /** Raw model text before JSON parse. Useful for debugging when output is garbage. */
158
+ outputRaw: string;
159
+ /** Whether the output was valid JSON. When false, `output` is the raw string. */
160
+ parsedSuccessfully: boolean;
161
+ /** Number of loop iterations used. */
162
+ turns: number;
163
+ /**
164
+ * The task used every turn in `maxTurns` and was then asked, with its
165
+ * tools taken away, for its final output: `output` is whatever it could
166
+ * say from what it had gathered by then.
167
+ */
168
+ hitMaxTurns: boolean;
169
+ /**
170
+ * Why the model stopped on the turn that produced `output`: `end_turn`, or
171
+ * `max_tokens` when the answer was cut at the output limit (`repetition`
172
+ * when the platform cut an answer that had begun repeating itself). Null
173
+ * when that model call failed, and `output` is empty.
174
+ */
175
+ stopReason: string | null;
176
+ /** Token and cost usage. */
177
+ usage: TaskUsage;
178
+ /** Summary of every tool call made during execution. */
179
+ toolCalls: TaskToolCall[];
180
+ /**
181
+ * Stable id for this task's model transcript. The platform records every
182
+ * task's transcript server-side per turn under it, for 90 days, and only
183
+ * the id rides the result: `remy-admin tasks get <traceId>` reads it back.
184
+ * Inside a jewel, also attach it to the propose/grade return
185
+ * (`trace: task.traceId`) to preserve the full transcript with the pair —
186
+ * the training row and the audit trail.
187
+ */
188
+ traceId: string;
189
+ }
190
+ /** @internal One tool as a turn request carries it to the API. */
191
+ export type TaskWireTool = {
192
+ stepType: string;
193
+ defaults?: Record<string, unknown>;
194
+ } | {
195
+ appMethod: string;
196
+ description?: string;
197
+ defaults?: Record<string, unknown>;
198
+ } | {
199
+ name: string;
200
+ description: string;
201
+ inputSchema: JsonObjectSchema;
202
+ };
203
+ export {};