Sessions
A session owns a durable conversation: history, model, working directory, metadata, status, and lineage.
one answer durable conversation ctx.ai.ask(prompt) ctx.ai.sessions.create(config) │ │ ▼ ▼ string AiSessionHandle │ run · send · notify · tasks · fork · spawn
One-shot answers
Use ctx.ai.ask when the caller needs text and no session handle afterward.
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: 'Release Notes', ModMetadata.description: stringdescription: 'Generate release notes from the current workspace', }, commands?: readonly ModCommand<string>[] | undefinedcommands: [ function command<"release-notes.draft", void>(commandValue: CommandInput<"release-notes.draft", void>): Command<"release-notes.draft", 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-notes.draft"id: 'release-notes.draft', title: stringtitle: 'Draft Release Notes', run: (call: CommandCall) => Awaitable<void>run: async ({ ctx: CommandContextctx }) => { const const text: stringtext = await ctx: CommandContextctx.ContextBase.ai: AiRuntimeApiOne off answers, agents, models, and sessions.ai.AiRuntimeApi.ask(prompt: string, options?: AiAskOptions): Promise<string>ask( 'Draft concise release notes for the current workspace changes.' ); ctx: CommandContextctx.ui: UiCapabilityNotifications, dialogs, quick input, and progress.ui.UiCapability.notification: UiNotificationCapabilitynotification.UiNotificationCapability.info(notice: UiNotice): voidinfo({ UiNotice.message: stringmessage: const text: stringtext }); }, }), ], });
ask accepts an options object with optional attachments
and an optional config. It still returns only the answer text. Use a
session when the caller needs identity, history, follow-up work, or
lifecycle control.
Create a durable session
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: 'Release Review', ModMetadata.description: stringdescription: 'Run durable release reviews', }, commands?: readonly ModCommand<string>[] | undefinedcommands: [ function command<"release-review.start", void>(commandValue: CommandInput<"release-review.start", void>): Command<"release-review.start", 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.start"id: 'release-review.start', title: stringtitle: 'Start Release Review', run: (call: CommandCall) => Awaitable<void>run: async ({ ctx: CommandContextctx }) => { const const folder: WorkspaceFolder | undefinedfolder = ctx: CommandContextctx.ContextBase.workspace: WorkspaceApiFolders, files, and configuration of the open workspace.workspace.WorkspaceApi.workspaceFolders: readonly WorkspaceFolder[] | undefinedList of workspace folders (0-N) that are open in the editor. `undefined` when no workspace has been opened. Refer to https://code.visualstudio.com/docs/editor/workspaces for more information on workspaces.workspaceFolders?.[0]; if (const folder: WorkspaceFolder | undefinedfolder === undefined: undefinedundefined) { ctx: CommandContextctx.ContextBase.logger: LoggerYour mod's log channel.logger.Logger.warn(message: string, ...args: readonly unknown[]): voidwarn('Open a workspace folder before starting a review.'); return; } 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', AiSessionConfig.workingDirectory?: string | undefinedworkingDirectory: const folder: WorkspaceFolderfolder.WorkspaceFolder.uri: UriThe associated uri for this workspace folder. *Note:* The Uri-type was intentionally chosen such that future releases of the editor can support workspace folders that are not stored on the local disk, e.g. `ftp://server/workspaces/foo`.uri.Uri.fsPath: stringThe string representing the corresponding file system path of this Uri. Will handle UNC paths and normalize windows drive letters to lower-case. Also uses the platform specific path separator. * Will *not* validate the path for invalid characters and semantics. * Will *not* look at the scheme of this Uri. * The resulting string shall *not* be used for display purposes but for disk operations, like `readFile` et al. The *difference* to the path-property is the use of the platform specific path separator and the handling of UNC paths. The sample below outlines the difference: ```ts const u = URI.parse('file://server/c$/folder/file.txt') u.authority === 'server' u.path === '/c$/folder/file.txt' u.fsPath === '\\server\c$\folder\file.txt' ```fsPath, AiSessionConfig.foreground?: boolean | undefinedforeground: true, }); const const result: AiRunResultresult = await const session: AiSessionHandlesession.AiSessionHandle.run(prompt: string, options?: AiSendOptions): Promise<AiRunResult>run( 'Review correctness, migration risk, rollback, and observability.' ); ctx: CommandContextctx.ContextBase.logger: LoggerYour mod's log channel.logger.Logger.info(message: string, ...args: readonly unknown[]): voidinfo(const result: AiRunResultresult.AiRunResult.text: stringtext); }, }), ], });
ctx.ai.sessions.create() creates a root session. The returned
AiSessionHandle is the live
capability. The catalog stores metadata; the handle performs conversation work.
Session configuration
AiSessionConfig contains only
creation-time choices:
| Member | Meaning |
|---|---|
model | Explicit model route; otherwise inherit the caller or workspace choice |
title | Human-readable session title |
workingDirectory | Workspace used by tools and the model |
autoApprove | default, autoApprove, or autopilot |
appendSystemPrompt | Additional system instructions for this session |
foreground | Open the created session immediately |
Use sessions.rename(...) to change the title after creation.
Typed session metadata
Use a metadata declaration when a mod needs durable typed data attached to a
session. Declare the value once, include it in the mod's data slot, and bind
it through an AiSessionHandle:
import { 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, function metadata<TValue>(input: MetadataDeclarationInput<TValue>, ...contracts: readonly [] | readonly [GeneratedRuntimeContract]): MetadataDeclaration<TValue>metadata, 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 } from '@modular/sdk'; typetype ReleaseGoal = { readonly kind: 'active'; readonly objective: string; } | { readonly kind: 'complete'; readonly objective: string; }ReleaseGoal = | { readonly kind: "active"kind: 'active'; readonly objective: stringobjective: string } | { readonly kind: "complete"kind: 'complete'; readonly objective: stringobjective: string }; const const releaseGoal: MetadataDeclaration<ReleaseGoal>releaseGoal = function metadata<ReleaseGoal>(input: MetadataDeclarationInput<ReleaseGoal>, ...contracts: readonly [] | readonly [GeneratedRuntimeContract]): MetadataDeclaration<ReleaseGoal>metadata<type ReleaseGoal = { readonly kind: 'active'; readonly objective: string; } | { readonly kind: 'complete'; readonly objective: string; }ReleaseGoal>({ MetadataDeclarationInput<ReleaseGoal>.id: stringid: 'release-goal', MetadataDeclarationInput<ReleaseGoal>.initial: ReleaseGoalinitial: { kind: "active"kind: 'active', objective: stringobjective: 'Review correctness and migration risk', }, MetadataDeclarationInput<ReleaseGoal>.fork: MetadataForkPolicyfork: 'inherit', }); 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 Goal', ModMetadata.description: stringdescription: 'Track the goal of a release review session', }, data?: readonly MetadataDeclaration<unknown>[] | undefineddata: [const releaseGoal: MetadataDeclaration<ReleaseGoal>releaseGoal], commands?: readonly ModCommand<string>[] | undefinedcommands: [ function slashCommand<string, void>(slashCommandValue: SlashCommandInput<string, void>): SlashCommand<string, 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: stringid: 'release-goal-complete', description: stringdescription: 'Complete the current session release goal', argument: "none"argument: 'none', run: (call: SlashCommandCall) => Awaitable<void>run: async ({ ctx: SlashCommandContextctx }) => { const const goal: BoundMetadata<ReleaseGoal>goal = ctx: SlashCommandContextctx.session: AiSessionHandleThe chat session the command was typed into.session.AiSessionHandle.metadata<ReleaseGoal>(declaration: MetadataDeclaration<ReleaseGoal>): BoundMetadata<ReleaseGoal>metadata(const releaseGoal: MetadataDeclaration<ReleaseGoal>releaseGoal); await const goal: BoundMetadata<ReleaseGoal>goal.BoundMetadata<ReleaseGoal>.update(transform: MetadataUpdate<ReleaseGoal>): Promise<void>update(current: ReleaseGoalcurrent => { switch (current: ReleaseGoalcurrent.kind: "active" | "complete"kind) { case 'active': return { kind: "complete"kind: 'complete', objective: stringobjective:current: { readonly kind: 'active'; readonly objective: string; }current.objective: stringobjective, }; case 'complete': returncurrent: { readonly kind: 'complete'; readonly objective: string; }current; } }); }, }), ], });
The bound cell has one complete value:
| Member | Meaning |
|---|---|
value | Current validated value |
set(next) | Commit a complete replacement |
update(current => next) | Transform the newest committed value |
reset() | Restore the declaration's initial value |
subscribe(listener) | Observe accepted values and return an unsubscribe function |
update() may invoke the transformation again when another writer commits
first. Keep it pure: return a complete next value and perform side effects only
after the promise resolves. Values exposed by the cell are recursively frozen.
Revisions, conflict retries, compare-and-set, and stored envelopes are host
machinery, not part of the mod API.
Fork policy is declared with the value. inherit carries the committed value
into the child session. reset starts the child at initial. Calling
reset() also restores initial; it does not remove the declaration or create
an absent state.
session.metadata() with no argument reads the session's current catalog
metadata. session.metadata(declaration) binds a typed declaration. Product
fields such as title, color, and icon are direct optional values in the catalog;
typed mod data stays behind its declaration binding.
Views can consume a bound cell with useModMetadata() from
@modular/sdk/view. The hook re-renders after accepted values without exposing
the host's observable implementation.
Current session or catalog
Inside a tool or slash command, ctx.session is already the current session.
Use it instead of looking the same session up again.
| Need | Surface |
|---|---|
| Work in the current conversation | ctx.session |
| Create a new root conversation | ctx.ai.sessions.create() |
| Require a known session | ctx.ai.sessions.get(id) |
| Probe for an optional session | ctx.ai.sessions.find(id) |
| Render or inspect the catalog | ctx.ai.sessions.list() or observe() |
Catalog lifecycle
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: 'Session Catalog', ModMetadata.description: stringdescription: 'Manage AI sessions', }, commands?: readonly ModCommand<string>[] | undefinedcommands: [ function command<"sessions.archive-finished", void>(commandValue: CommandInput<"sessions.archive-finished", void>): Command<"sessions.archive-finished", 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: "sessions.archive-finished"id: 'sessions.archive-finished', title: stringtitle: 'Archive Finished AI Sessions', run: (call: CommandCall) => Awaitable<void>run: async ({ ctx: CommandContextctx }) => { const const sessions: readonly AiSessionMetadata[]sessions = await ctx: CommandContextctx.ContextBase.ai: AiRuntimeApiOne off answers, agents, models, and sessions.ai.AiRuntimeApi.sessions: AiSessionsApisessions.AiSessionsApi.list(): Promise<readonly AiSessionMetadata[]>list(); const const finished: AiSessionMetadata[]finished = const sessions: readonly AiSessionMetadata[]sessions.ReadonlyArray<AiSessionMetadata>.filter(predicate: (value: AiSessionMetadata, index: number, array: readonly AiSessionMetadata[]) => unknown, thisArg?: any): AiSessionMetadata[]Returns the elements of an array that meet the condition specified in a callback function.filter( session: AiSessionMetadatasession => session: AiSessionMetadatasession.AiSessionMetadata.status: AiSessionStatusstatus === 'completed' && !session: AiSessionMetadatasession.AiSessionMetadata.isArchived: booleanisArchived ); for (const const session: AiSessionMetadatasession of const finished: AiSessionMetadata[]finished) { await ctx: CommandContextctx.ContextBase.ai: AiRuntimeApiOne off answers, agents, models, and sessions.ai.AiRuntimeApi.sessions: AiSessionsApisessions.AiSessionsApi.archive(sessionId: SessionId): Promise<void>archive(const session: AiSessionMetadatasession.AiSessionMetadata.id: string & $brand<"SessionId">id); } }, }), ], });
The catalog operations have distinct semantics:
| Method | Result |
|---|---|
rename(id, title) | Changes the mutable display title |
archive(id) | Hides the session from the active list but keeps history |
unarchive(id) | Returns an archived session to the active list |
delete(id) | Returns { kind: 'deleted' } or { kind: 'cancelled' } |
Do not treat archive as deletion, and do not assume deletion succeeded without checking its discriminated result.