Turns
A session owns conversation history. A turn owns one submitted unit of work.
| Method | Waits for completion | Returns | Use it when |
|---|---|---|---|
run(prompt) | Yes | { text } | The caller needs the final answer |
run<T>(prompt) | Yes | Validated T | The caller needs domain data, not prose |
send(message) | No | AiTurnHandle | The caller needs observation, cancellation, or an exact-turn fork |
notify(...) | No | void | Background work must report without impersonating the user |
Completed text
import { function command<const TId extends string, TResult>(commandValue: CommandInput<TId, TResult>): Command<TId, TResult>Declare an action the user runs from the command palette or a keybinding. Reach for this when a person triggers the behavior. The `title` is what they read in the palette, `category` groups the entry, and `when` decides whether it shows up at all. The handler takes no argument, only a context. Whatever it returns is the command's result: `ctx.commands.execute(thisCommand)` resolves with that type, and the build compiles the same type into the result contract the host enforces, so return JSON data or nothing. Two neighbours are easy to confuse. `slashCommand` is also user-triggered, but it is typed inside a chat session and receives free text plus the live AI session. `tool` is not user-triggered at all, the model decides to call it mid-turn. The result goes in the mod's top-level `commands` array, alongside any slash commands. The `id` is the address a keybinding or a `command:` hook targets, so keep it stable.command, function defineMod(definition: ModDefinition): ModThe entry point of the SDK. A mod's module default-exports one `defineMod` call and nothing else. The returned value is data. It registers nothing, starts nothing, and touches no host state. The host folds it twice. At build time it runs the module in a throwaway sandbox and reads the value to derive the serializable manifest. At runtime it folds the same value again to wire your handlers into their lanes: ext-host for commands, tools, effects, and hooks; the sandboxed renderer for views. That double fold is why the module must be pure. It is re-executed to produce the manifest, so anything at the top level, a file read, a network call, a timer, a `console` line, runs during a build with no host attached. Put behavior inside handlers: `run`, `activate`, `handle`.defineMod } from '@modular/sdk'; export default function defineMod(definition: ModDefinition): ModThe entry point of the SDK. A mod's module default-exports one `defineMod` call and nothing else. The returned value is data. It registers nothing, starts nothing, and touches no host state. The host folds it twice. At build time it runs the module in a throwaway sandbox and reads the value to derive the serializable manifest. At runtime it folds the same value again to wire your handlers into their lanes: ext-host for commands, tools, effects, and hooks; the sandboxed renderer for views. That double fold is why the module must be pure. It is re-executed to produce the manifest, so anything at the top level, a file read, a network call, a timer, a `console` line, runs during a build with no host attached. Put behavior inside handlers: `run`, `activate`, `handle`.defineMod({ metadata: ModMetadatametadata: { ModMetadata.displayName: stringdisplayName: 'Summaries', ModMetadata.description: stringdescription: 'Generate concise summaries', }, commands?: readonly ModCommand<string>[] | undefinedcommands: [ function command<"summaries.workspace", void>(commandValue: CommandInput<"summaries.workspace", void>): Command<"summaries.workspace", void>Declare an action the user runs from the command palette or a keybinding. Reach for this when a person triggers the behavior. The `title` is what they read in the palette, `category` groups the entry, and `when` decides whether it shows up at all. The handler takes no argument, only a context. Whatever it returns is the command's result: `ctx.commands.execute(thisCommand)` resolves with that type, and the build compiles the same type into the result contract the host enforces, so return JSON data or nothing. Two neighbours are easy to confuse. `slashCommand` is also user-triggered, but it is typed inside a chat session and receives free text plus the live AI session. `tool` is not user-triggered at all, the model decides to call it mid-turn. The result goes in the mod's top-level `commands` array, alongside any slash commands. The `id` is the address a keybinding or a `command:` hook targets, so keep it stable.command({ id: "summaries.workspace"id: 'summaries.workspace', title: stringtitle: 'Summarize Workspace', run: (call: CommandCall) => Awaitable<void>run: async ({ ctx: CommandContextctx }) => { const const session: AiSessionHandlesession = await ctx: CommandContextctx.ContextBase.ai: AiRuntimeApiOne off answers, agents, models, and sessions.ai.AiRuntimeApi.sessions: AiSessionsApisessions.AiSessionsApi.create(config?: AiSessionCreateInput): Promise<AiSessionHandle>create({ AiSessionConfig.title?: string | undefinedtitle: 'Summary' }); const const result: AiRunResultresult = await const session: AiSessionHandlesession.AiSessionHandle.run(prompt: string, options?: AiSendOptions): Promise<AiRunResult>run( 'Summarize the current workspace in five concrete bullets.' ); ctx: CommandContextctx.ContextBase.logger: LoggerYour mod's log channel.logger.Logger.info(message: string, ...args: readonly unknown[]): voidinfo(const result: AiRunResultresult.AiRunResult.text: stringtext); }, }), ], });
The text overload returns AiRunResult.
It rejects when the turn fails or is cancelled.
Validated domain data
The structured overload derives a runtime contract from the TypeScript type argument. The model response must satisfy that contract before the promise resolves.
import { function command<const TId extends string, TResult>(commandValue: CommandInput<TId, TResult>): Command<TId, TResult>Declare an action the user runs from the command palette or a keybinding. Reach for this when a person triggers the behavior. The `title` is what they read in the palette, `category` groups the entry, and `when` decides whether it shows up at all. The handler takes no argument, only a context. Whatever it returns is the command's result: `ctx.commands.execute(thisCommand)` resolves with that type, and the build compiles the same type into the result contract the host enforces, so return JSON data or nothing. Two neighbours are easy to confuse. `slashCommand` is also user-triggered, but it is typed inside a chat session and receives free text plus the live AI session. `tool` is not user-triggered at all, the model decides to call it mid-turn. The result goes in the mod's top-level `commands` array, alongside any slash commands. The `id` is the address a keybinding or a `command:` hook targets, so keep it stable.command, function defineMod(definition: ModDefinition): ModThe entry point of the SDK. A mod's module default-exports one `defineMod` call and nothing else. The returned value is data. It registers nothing, starts nothing, and touches no host state. The host folds it twice. At build time it runs the module in a throwaway sandbox and reads the value to derive the serializable manifest. At runtime it folds the same value again to wire your handlers into their lanes: ext-host for commands, tools, effects, and hooks; the sandboxed renderer for views. That double fold is why the module must be pure. It is re-executed to produce the manifest, so anything at the top level, a file read, a network call, a timer, a `console` line, runs during a build with no host attached. Put behavior inside handlers: `run`, `activate`, `handle`.defineMod } from '@modular/sdk'; interface ReleaseRisk { readonly ReleaseRisk.area: "data" | "interface" | "runtime"area: 'data' | 'runtime' | 'interface'; readonly ReleaseRisk.severity: "high" | "low" | "medium"severity: 'low' | 'medium' | 'high'; readonly ReleaseRisk.evidence: readonly string[]evidence: readonly string[]; } interface ReleaseReview { readonly ReleaseReview.summary: stringsummary: string; readonly ReleaseReview.risks: readonly ReleaseRisk[]risks: readonly ReleaseRisk[]; } export default function defineMod(definition: ModDefinition): ModThe entry point of the SDK. A mod's module default-exports one `defineMod` call and nothing else. The returned value is data. It registers nothing, starts nothing, and touches no host state. The host folds it twice. At build time it runs the module in a throwaway sandbox and reads the value to derive the serializable manifest. At runtime it folds the same value again to wire your handlers into their lanes: ext-host for commands, tools, effects, and hooks; the sandboxed renderer for views. That double fold is why the module must be pure. It is re-executed to produce the manifest, so anything at the top level, a file read, a network call, a timer, a `console` line, runs during a build with no host attached. Put behavior inside handlers: `run`, `activate`, `handle`.defineMod({ metadata: ModMetadatametadata: { ModMetadata.displayName: stringdisplayName: 'Release Review', ModMetadata.description: stringdescription: 'Produce validated release reviews', }, commands?: readonly ModCommand<string>[] | undefinedcommands: [ function command<"release-review.structured", void>(commandValue: CommandInput<"release-review.structured", void>): Command<"release-review.structured", void>Declare an action the user runs from the command palette or a keybinding. Reach for this when a person triggers the behavior. The `title` is what they read in the palette, `category` groups the entry, and `when` decides whether it shows up at all. The handler takes no argument, only a context. Whatever it returns is the command's result: `ctx.commands.execute(thisCommand)` resolves with that type, and the build compiles the same type into the result contract the host enforces, so return JSON data or nothing. Two neighbours are easy to confuse. `slashCommand` is also user-triggered, but it is typed inside a chat session and receives free text plus the live AI session. `tool` is not user-triggered at all, the model decides to call it mid-turn. The result goes in the mod's top-level `commands` array, alongside any slash commands. The `id` is the address a keybinding or a `command:` hook targets, so keep it stable.command({ id: "release-review.structured"id: 'release-review.structured', title: stringtitle: 'Run Structured Release Review', run: (call: CommandCall) => Awaitable<void>run: async ({ ctx: CommandContextctx }) => { const const session: AiSessionHandlesession = await ctx: CommandContextctx.ContextBase.ai: AiRuntimeApiOne off answers, agents, models, and sessions.ai.AiRuntimeApi.sessions: AiSessionsApisessions.AiSessionsApi.create(config?: AiSessionCreateInput): Promise<AiSessionHandle>create({ AiSessionConfig.title?: string | undefinedtitle: 'Release review' }); const const review: ReleaseReviewreview = await const session: AiSessionHandlesession.AiSessionHandle.run<ReleaseReview>(prompt: string, options?: AiSendOptions): Promise<ReleaseReview>run<ReleaseReview>( 'Return a release review that matches the requested structure.' ); ctx: CommandContextctx.ContextBase.logger: LoggerYour mod's log channel.logger.Logger.info(message: string, ...args: readonly unknown[]): voidinfo(`${const review: ReleaseReviewreview.ReleaseReview.risks: readonly ReleaseRisk[]risks.ReadonlyArray<T>.length: numberGets the length of the array. This is a number one higher than the highest element defined in an array.length} risks: ${const review: ReleaseReviewreview.ReleaseReview.summary: stringsummary}`); }, }), ], });
run<T> rejects on turn failure, cancellation, missing delivery, or invalid
data. Do not catch that error and parse the prose as a fallback. That would
discard the guarantee the structured overload exists to provide.
Observe and cancel a submission
send accepts a typed prompt and returns immediately after the host accepts
the submission. System notifications go through notify, not send.
import { function slashCommand<const TId extends string, TResult>(slashCommandValue: SlashCommandInput<TId, TResult>): SlashCommand<TId, TResult>Declare a command the user types inside a chat session. The `id` is the name typed after the slash, `description` is the line shown in the typeahead, and `argumentHint` is the placeholder for whatever the user types after the name. `argument` declares whether that text is `'required'`, `'optional'`, or `'none'`. The host trims it, answers a missing required argument with the usage line, and hands the handler `{ ctx, argument }`, where `ctx` carries the AI session the command was typed into. Use this instead of `command` when the behavior belongs to a conversation and needs the session. Use `command` when it belongs to the workbench and runs from the palette. Use `tool` when the model, not the user, should decide to run it. Slash commands go in the same top-level `commands` array as palette commands.slashCommand, function defineMod(definition: ModDefinition): ModThe entry point of the SDK. A mod's module default-exports one `defineMod` call and nothing else. The returned value is data. It registers nothing, starts nothing, and touches no host state. The host folds it twice. At build time it runs the module in a throwaway sandbox and reads the value to derive the serializable manifest. At runtime it folds the same value again to wire your handlers into their lanes: ext-host for commands, tools, effects, and hooks; the sandboxed renderer for views. That double fold is why the module must be pure. It is re-executed to produce the manifest, so anything at the top level, a file read, a network call, a timer, a `console` line, runs during a build with no host attached. Put behavior inside handlers: `run`, `activate`, `handle`.defineMod } from '@modular/sdk'; const const investigate: SlashCommand<"investigate", string>investigate = function slashCommand<"investigate", string>(slashCommandValue: SlashCommandInput<"investigate", string>): SlashCommand<"investigate", string>Declare a command the user types inside a chat session. The `id` is the name typed after the slash, `description` is the line shown in the typeahead, and `argumentHint` is the placeholder for whatever the user types after the name. `argument` declares whether that text is `'required'`, `'optional'`, or `'none'`. The host trims it, answers a missing required argument with the usage line, and hands the handler `{ ctx, argument }`, where `ctx` carries the AI session the command was typed into. Use this instead of `command` when the behavior belongs to a conversation and needs the session. Use `command` when it belongs to the workbench and runs from the palette. Use `tool` when the model, not the user, should decide to run it. Slash commands go in the same top-level `commands` array as palette commands.slashCommand({ id: "investigate"id: 'investigate', description: stringdescription: 'Start an investigation in the current conversation.', argumentHint?: string | undefinedargumentHint: '<question>', argument: "optional"argument: 'optional', run: (call: SlashCommandCall<string | undefined>) => Awaitable<string>run: async ({ argument: string | undefinedargument, ctx: SlashCommandContextctx }) => { const const question: string | undefinedquestion = argument: string | undefinedargument?.String.trim(): stringRemoves the leading and trailing white space and line terminator characters from a string.trim(); if (const question: string | undefinedquestion === undefined: undefinedundefined || const question: stringquestion.String.length: numberReturns the length of a String object.length === 0) { return 'Usage: /investigate <question>'; } const const turn: AiTurnHandleturn = await ctx: SlashCommandContextctx.session: AiSessionHandleThe chat session the command was typed into.session.AiSessionHandle.send(message: AiPromptMessage, options?: AiSendOptions): Promise<AiTurnHandle>send({ AiPromptMessage.type: "prompt"type: 'prompt', AiPromptMessage.text: stringtext: const question: stringquestion, }); const const terminal: AiTurnTerminalSnapshot<unknown>terminal = await const turn: AiTurnHandleturn.AiTurnHandle.completion(): Promise<AiTurnTerminalSnapshot>completion(); switch (const terminal: AiTurnTerminalSnapshot<unknown>terminal.kind: "cancelled" | "completed" | "failed"kind) { case 'completed': returnconst terminal: { readonly kind: 'completed'; readonly submissionId: SubmissionId; readonly sessionId: SessionId; readonly turnId: TurnId; readonly result: AiRunResult; readonly delivery: AiStructuredDelivery<unknown>; }terminal.result: AiRunResultresult.AiRunResult.text: stringtext; case 'failed': return `Investigation failed: ${const terminal: { readonly kind: 'failed'; readonly submissionId: SubmissionId; readonly sessionId: SessionId; readonly target: AiTurnTarget; readonly error: { readonly message: string; }; }terminal.error: { readonly message: string; }error.message: stringmessage}`; case 'cancelled': return 'Investigation cancelled.'; } }, }); export default function defineMod(definition: ModDefinition): ModThe entry point of the SDK. A mod's module default-exports one `defineMod` call and nothing else. The returned value is data. It registers nothing, starts nothing, and touches no host state. The host folds it twice. At build time it runs the module in a throwaway sandbox and reads the value to derive the serializable manifest. At runtime it folds the same value again to wire your handlers into their lanes: ext-host for commands, tools, effects, and hooks; the sandboxed renderer for views. That double fold is why the module must be pure. It is re-executed to produce the manifest, so anything at the top level, a file read, a network call, a timer, a `console` line, runs during a build with no host attached. Put behavior inside handlers: `run`, `activate`, `handle`.defineMod({ metadata: ModMetadatametadata: { ModMetadata.displayName: stringdisplayName: 'Investigation', ModMetadata.description: stringdescription: 'Conversation investigation commands', }, commands?: readonly ModCommand<string>[] | undefinedcommands: [const investigate: SlashCommand<"investigate", string>investigate], });
AiTurnHandle exposes:
| Member | Contract |
|---|---|
submissionId | Stable identity for this submission |
get() | Current queued, running, needs-input, or terminal snapshot |
observe(listener) | Snapshot changes until the listener is disposed |
completion() | One terminal completed, failed, or cancelled value |
cancel() | Requests cancellation and returns the terminal snapshot |
fork(config?) | Forks immediately after this completed turn |
Notifications and attention
session.notify({ attention, title, body }) puts a system notification into
the session. The host marks it as a system event; a mod cannot claim that the
user sent it.
Every notification joins the conversation record. The required attention
field is your explicit decision about how much of the agent's attention it
requests. The three levels are a strict ladder — each adds one step of agent
involvement:
attention | Record | Agent reads it | Agent answers it |
|---|---|---|---|
'none' | Yes | Never | Never |
'read' | Yes | At its next turn | Never |
'respond' | Yes | Now | Yes, with a turn of its own |
Choose by what the event deserves, not by what feels safe:
'none'— markers and bookkeeping the user should see but the agent never needs. A fork's branch point. An audit stamp.'read'— lifecycle facts the agent should know without being interrupted. Background work kicked off. A long process reached a checkpoint.'respond'— events that call for action. A finished task's report. A failure that needs a decision.
notify has no default attention: silence and interruption are both explicit
choices. It is fire-and-forget — every attention level returns void.
Tasks
session.tasks composes notifications into a task lifecycle so every async
process announces itself the same way:
import { function slashCommand<const TId extends string, TResult>(slashCommandValue: SlashCommandInput<TId, TResult>): SlashCommand<TId, TResult>Declare a command the user types inside a chat session. The `id` is the name typed after the slash, `description` is the line shown in the typeahead, and `argumentHint` is the placeholder for whatever the user types after the name. `argument` declares whether that text is `'required'`, `'optional'`, or `'none'`. The host trims it, answers a missing required argument with the usage line, and hands the handler `{ ctx, argument }`, where `ctx` carries the AI session the command was typed into. Use this instead of `command` when the behavior belongs to a conversation and needs the session. Use `command` when it belongs to the workbench and runs from the palette. Use `tool` when the model, not the user, should decide to run it. Slash commands go in the same top-level `commands` array as palette commands.slashCommand, function defineMod(definition: ModDefinition): ModThe entry point of the SDK. A mod's module default-exports one `defineMod` call and nothing else. The returned value is data. It registers nothing, starts nothing, and touches no host state. The host folds it twice. At build time it runs the module in a throwaway sandbox and reads the value to derive the serializable manifest. At runtime it folds the same value again to wire your handlers into their lanes: ext-host for commands, tools, effects, and hooks; the sandboxed renderer for views. That double fold is why the module must be pure. It is re-executed to produce the manifest, so anything at the top level, a file read, a network call, a timer, a `console` line, runs during a build with no host attached. Put behavior inside handlers: `run`, `activate`, `handle`.defineMod } from '@modular/sdk'; const const audit: SlashCommand<"audit", void>audit = function slashCommand<"audit", void>(slashCommandValue: SlashCommandInput<"audit", void>): SlashCommand<"audit", void>Declare a command the user types inside a chat session. The `id` is the name typed after the slash, `description` is the line shown in the typeahead, and `argumentHint` is the placeholder for whatever the user types after the name. `argument` declares whether that text is `'required'`, `'optional'`, or `'none'`. The host trims it, answers a missing required argument with the usage line, and hands the handler `{ ctx, argument }`, where `ctx` carries the AI session the command was typed into. Use this instead of `command` when the behavior belongs to a conversation and needs the session. Use `command` when it belongs to the workbench and runs from the palette. Use `tool` when the model, not the user, should decide to run it. Slash commands go in the same top-level `commands` array as palette commands.slashCommand({ id: "audit"id: 'audit', description: stringdescription: 'Audit the workspace in a background fork.', argument: "none"argument: 'none', run: (call: SlashCommandCall) => Awaitable<void>run: async ({ ctx: SlashCommandContextctx }) => { const const child: AiSessionHandlechild = await ctx: SlashCommandContextctx.session: AiSessionHandleThe chat session the command was typed into.session.AiSessionHandle.fork(config?: AiSessionForkConfig): Promise<AiSessionHandle>fork(); const const task: AiTaskHandletask = await ctx: SlashCommandContextctx.session: AiSessionHandleThe chat session the command was typed into.session.AiSessionHandle.tasks: AiTasksApitasks.AiTasksApi.start(config: AiTaskConfig): Promise<AiTaskHandle>start({ AiTaskConfig.label: stringlabel: 'Workspace audit', AiTaskConfig.detail?: string | undefineddetail: `Session ${const child: AiSessionHandlechild.AiSessionHandle.id: string & $brand<"SessionId">id} is auditing the workspace.`, }); try { const const summary: AiRunResultsummary = await const child: AiSessionHandlechild.AiSessionHandle.run(prompt: string, options?: AiSendOptions): Promise<AiRunResult>run('Audit the workspace, then summarize.'); await const task: AiTaskHandletask.AiTaskHandle.complete(report: AiTaskReport): Promise<void>Post the finished report at its declared attention level.complete({ AiTaskReport.attention: AiAttentionattention: 'respond', AiTaskReport.title: stringtitle: 'Audit finished', AiTaskReport.body: stringbody: const summary: AiRunResultsummary.AiRunResult.text: stringtext, }); } catch (var error: unknownerror) { await const task: AiTaskHandletask.AiTaskHandle.fail(reason: string): Promise<void>Post the failure at `respond` attention: failures demand an answer.fail(var error: unknownerror instanceof var Error: ErrorConstructorError ? var error: Errorerror.Error.message: stringmessage : var String: (value?: any) => stringAllows manipulation and formatting of text strings and determination and location of substrings within strings.String(var error: unknownerror)); } }, }); export default function defineMod(definition: ModDefinition): ModThe entry point of the SDK. A mod's module default-exports one `defineMod` call and nothing else. The returned value is data. It registers nothing, starts nothing, and touches no host state. The host folds it twice. At build time it runs the module in a throwaway sandbox and reads the value to derive the serializable manifest. At runtime it folds the same value again to wire your handlers into their lanes: ext-host for commands, tools, effects, and hooks; the sandboxed renderer for views. That double fold is why the module must be pure. It is re-executed to produce the manifest, so anything at the top level, a file read, a network call, a timer, a `console` line, runs during a build with no host attached. Put behavior inside handlers: `run`, `activate`, `handle`.defineMod({ metadata: ModMetadatametadata: { ModMetadata.displayName: stringdisplayName: 'Audit', ModMetadata.description: stringdescription: 'Background workspace audits', }, commands?: readonly ModCommand<string>[] | undefinedcommands: [const audit: SlashCommand<"audit", void>audit], });
start posts the kickoff at read attention by default, so the agent knows
the task exists without being interrupted. complete posts the outcome at
the attention you declare. fail posts at respond — failures demand an
answer.