Attachments
Attachments carry typed context beside prompt text. They do not become part of the system prompt and do not require authors to interpolate large values into a string.
Three attachment kinds
AiAttachment is a discriminated union:
| Kind | Carries | Required fields |
|---|---|---|
text | Model-readable text | label, modelRepresentation |
binary | Encoded binary content | label, data, contentType |
resource | A resource address | label, uri |
Every kind may include displayKind, which describes how the attachment should
be presented without changing its model payload.
Attach text to a one-shot answer
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, type type AiAttachment = AiBinaryAttachment | AiResourceAttachment | AiTextAttachmentAiAttachment } 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: 'Decision Review', ModMetadata.description: stringdescription: 'Review decisions with explicit context', }, commands?: readonly ModCommand<string>[] | undefinedcommands: [ function command<"decision-review.example", void>(commandValue: CommandInput<"decision-review.example", void>): Command<"decision-review.example", 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: "decision-review.example"id: 'decision-review.example', title: stringtitle: 'Review Example Decision', run: (call: CommandCall) => Awaitable<void>run: async ({ ctx: CommandContextctx }) => { const const attachments: readonly AiAttachment[]attachments: readonly type AiAttachment = AiBinaryAttachment | AiResourceAttachment | AiTextAttachmentAiAttachment[] = [ { AiTextAttachment.kind: "text"kind: 'text', AiAttachmentBase.label: stringlabel: 'Decision record', AiAttachmentBase.displayKind?: string | undefineddisplayKind: 'document', AiTextAttachment.modelRepresentation: stringmodelRepresentation: 'Decision: sessions own history; turns own submission lifecycle.', }, ]; const const answer: stringanswer = await ctx: CommandContextctx.ContextBase.ai: AiRuntimeApiOne off answers, agents, models, and sessions.ai.AiRuntimeApi.ask(prompt: string, options?: AiAskOptions): Promise<string>ask( 'Identify the invariant and one consequence.', { AiAskOptions.attachments?: readonly AiAttachment[] | undefinedattachments } ); ctx: CommandContextctx.ui: UiCapabilityNotifications, dialogs, quick input, and progress.ui.UiCapability.notification: UiNotificationCapabilitynotification.UiNotificationCapability.info(notice: UiNotice): voidinfo({ UiNotice.message: stringmessage: const answer: stringanswer }); }, }), ], });
Attach a workspace resource to a session turn
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,const Uri: typeof Uri type Uri = UriUri, type type AiAttachment = AiBinaryAttachment | AiResourceAttachment | AiTextAttachmentAiAttachment } 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: 'Resource Review', ModMetadata.description: stringdescription: 'Review workspace resources in AI sessions', }, commands?: readonly ModCommand<string>[] | undefinedcommands: [ function command<"resource-review.readme", void>(commandValue: CommandInput<"resource-review.readme", void>): Command<"resource-review.readme", 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: "resource-review.readme"id: 'resource-review.readme', title: stringtitle: 'Review Workspace README', 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) { return; } const const readme: AiAttachmentreadme: type AiAttachment = AiBinaryAttachment | AiResourceAttachment | AiTextAttachmentAiAttachment = { AiResourceAttachment.kind: "resource"kind: 'resource', AiAttachmentBase.label: stringlabel: 'Workspace README', AiResourceAttachment.uri: stringuri: const Uri: typeof UriUri.Uri.joinPath(base: Uri, ...pathSegments: string[]): UriCreate a new uri which path is the result of joining the path of the base uri with the provided path segments. - Note 1: `joinPath` only affects the path component and all other components (scheme, authority, query, and fragment) are left as they are. - Note 2: The base uri must have a path; an error is thrown otherwise. The path segments are normalized in the following ways: - sequences of path separators (`/` or `\`) are replaced with a single separator - for `file`-uris on windows, the backslash-character (`\`) is considered a path-separator - the `..`-segment denotes the parent segment, the `.` denotes the current segment - paths have a root which always remains, for instance on windows drive-letters are roots so that is true: `joinPath(Uri.file('file:///c:/root'), '../../other').fsPath === 'c:/other'`joinPath(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, 'README.md').Uri.toString(skipEncoding?: boolean): stringReturns a string representation of this Uri. The representation and normalization of a URI depends on the scheme. * The resulting string can be safely used with Uri.parse. * The resulting string shall *not* be used for display purposes. *Note* that the implementation will encode _aggressive_ which often leads to unexpected, but not incorrect, results. For instance, colons are encoded to `%3A` which might be unexpected in file-uri. Also `&` and `=` will be encoded which might be unexpected for http-uris. For stability reasons this cannot be changed anymore. If you suffer from too aggressive encoding you should use the `skipEncoding`-argument: `uri.toString(true)`.toString(), AiResourceAttachment.contentType?: string | undefinedcontentType: 'text/markdown', }; 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: 'README 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, }); const const result: AiRunResultresult = await const session: AiSessionHandlesession.AiSessionHandle.run(prompt: string, options?: AiSendOptions): Promise<AiRunResult>run( 'Summarize the purpose and list the documented commands.', { AiSendOptions.attachments?: readonly AiAttachment[] | undefinedattachments: [const readme: AiResourceAttachmentreadme] } ); 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.ask receives attachments as its second argument. session.run and
session.send receive them through AiSendOptions.
Ownership rules
labelis for people and model context inspection.modelRepresentationis the exact text supplied for a text attachment.uriidentifies a resource. Keep the prompt focused on what to do with it.contentTypedescribes binary or resource content. Do not infer it from the label.- Attachments belong to one submitted prompt. They are not mutable session state and should not be used as a second persistence system.