Open History to see the last commit
1import type { InferSchemaType, ModelMessage, SchemaInput } from '@tanstack/ai'
2import type { LogRecord, SessionIndexEntry } from '@tanstack/ai-persistence'
3import type { CredentialsAccess } from './auth'
4import type { ToolStep } from './durable-tool'
5import type { SessionSnapshot } from './session/index'
6import type { SessionEntryChange, SessionEntryUpdate } from './session-entry'
7import type {
8 ChatTurnResult,
9 Operation,
10 HarnessUser,
11 MediaRecord,
12 MediaUpload,
13 Receipt,
14 RunContext,
15 ThreadSettings,
16} from './types'
17
18/** A question a command asks the user. The host renders it from the schema. */
19export interface Question<TSchema extends SchemaInput | undefined = undefined> {
20 message: string
21 /** The answer's shape. Without one, the answer is any text. */
22 schema?: TSchema
23 /**
24 * The answer is a secret, for example an API key or a password. Hosts hide
25 * it while the user types, and the session does not keep it in the log.
26 */
27 secret?: boolean
28 /**
29 * A page the user must open before they answer, for example a sign-in or a
30 * verify page. Hosts show the link. The session does not open it.
31 */
32 url?: string
33 /**
34 * When the question expires with no answer, in epoch milliseconds. Then
35 * the wait ends `expired`, and `ask` rejects. Default: no limit.
36 */
37 expiresAt?: number
38 /**
39 * Stop the wait. The wait ends `cancelled`, and `ask` rejects with the
40 * reason of the signal.
41 */
42 signal?: AbortSignal
43 /**
44 * A live wait of a tool call, by its name: the harness keeps the answer
45 * in the memory of this host, so the host keeps the session while it
46 * waits. Only an MCP elicitation (`'mcp-elicitation'`) asks this way. The
47 * wait belongs to `run`, the run of the tool call: its user may answer,
48 * and the wait ends `cancelled` when that run stops.
49 */
50 live?: { name: 'mcp-elicitation'; run: RunContext }
51}
52
53export type AnswerOf<TSchema> = TSchema extends SchemaInput
54 ? InferSchemaType<TSchema>
55 : string
56
57/**
58 * The parts of the session a plugin can use. `TMetadata` is the type of the
59 * session index `metadata`, from the `metadataSchema` of the plugin.
60 */
61export interface PluginSessionApi<TMetadata = Record<string, unknown>> {
62 threadId: string
63 /**
64 * The user this API acts for. In a command: who runs the command. In a
65 * turn plugin: the sender of its turn. In a session plugin: the user
66 * that opened the session, never the sender of a running turn. For the
67 * user of a tool call, read `ctx.context.run.user`.
68 */
69 user: HarnessUser | undefined
70 snapshot: () => SessionSnapshot
71 /**
72 * Start a chat turn, as if the user typed `text`. While a turn runs, the new
73 * turn waits in the queue. Cancel the returned turn to drop it before it starts.
74 * The turn runs as `options.user`: pass the user whose work it
75 * continues, for example `ctx.context.run.user` of the run that
76 * started the work. Default: `user` of this API. It never runs as
77 * the sender of another running turn.
78 */
79 send: (
80 text: string,
81 options?: { user?: HarnessUser },
82 ) => Operation<ChatTurnResult>
83 /**
84 * Add `text` to the transcript as an assistant note, not as a user prompt.
85 * When no turn runs, the note is written at once. Else it is written before
86 * the next turn starts. With `wake: true`, a new turn that sends `text` is
87 * also queued, so the model can act on the note. Resolves when the note is
88 * written or queued and the wake turn is queued, not when that turn ends.
89 * The wake turn runs as `options.user`, as `send` does.
90 */
91 note: (
92 text: string,
93 options?: { wake?: boolean; user?: HarnessUser },
94 ) => Promise<void>
95 /** The saved transcript. */
96 transcript: () => Promise<Array<ModelMessage>>
97 /**
98 * The kept records of `type` of this thread, oldest first: the last ones
99 * that the `keepRecords` of the plugins name. The log snapshot keeps
100 * them, so they stay after the store drops old records.
101 *
102 * @example
103 * ```ts
104 * const steps = await ctx.session.keptRecords('acme/steps:step')
105 * ```
106 */
107 keptRecords: (type: string) => Promise<Array<LogRecord>>
108 /** Replace the saved transcript (for example after a summary). */
109 replaceTranscript: (messages: Array<ModelMessage>) => Promise<void>
110 /**
111 * The session index entry of this thread. `undefined` when the host has
112 * no `stores.sessions`, or the thread has no entry.
113 */
114 indexEntry: () => Promise<SessionIndexEntry<TMetadata> | undefined>
115 /**
116 * Change the session index entry of this thread. Each field you pass
117 * replaces the stored one. Pass a function of the current entry to change
118 * part of a field: it runs again when another host wrote first. The
119 * `metadataSchema` of the plugin and of the harness check `metadata`, and
120 * a refused value throws `SessionMetadataError`. Resolves to the changed
121 * entry. Without `stores.sessions`, or for a thread with no entry, it
122 * writes nothing and resolves to `undefined`.
123 *
124 * @example
125 * ```ts
126 * await ctx.session.updateIndexEntry({ title: 'Fix the login bug' })
127 * ```
128 */
129 updateIndexEntry: (
130 update: SessionEntryUpdate<
131 TMetadata,
132 Omit<SessionEntryChange<TMetadata>, 'pinned'> &
133 Pick<SessionIndexEntry, 'usage'>
134 >,
135 ) => Promise<SessionIndexEntry<TMetadata> | undefined>
136 /**
137 * Ask the user in a live wait of a tool call, and wait for the answer:
138 * only an MCP elicitation asks this way (see `live`). Hosts show it (the
139 * CLI prompts, ACP shows an elicitation). The log keeps the question as a
140 * wait of that run, so every host shows it. Rejects when the session
141 * closes, when the run stops, when `signal` aborts, and when the question
142 * expires.
143 *
144 * Without `live`, it throws: no process waits for a user. In a command, a
145 * durable tool, or an agent run, use `step.ask`. To let the model ask, add
146 * the `question` tool. To ask before a tool call, give the tool its
147 * resources (`PermissionResources`), and `permissions()` asks before the
148 * call runs.
149 */
150 ask: <TSchema extends SchemaInput | undefined = undefined>(
151 question: Question<TSchema>,
152 ) => Promise<AnswerOf<TSchema>>
153 /**
154 * Tell clients that the user must sign in. Hosts show the link (the CLI
155 * opens the browser) or the device code.
156 *
157 * In a command (an OAuth login), it also opens a live `sign-in` wait of
158 * the command run. The wait ends `answered` when the command completes,
159 * and `cancelled` when it fails. At `expiresAt` (default: 15 minutes), the
160 * wait ends `expired`, and the command is cancelled.
161 */
162 authRequired: (info: {
163 connector: string
164 url?: string
165 userCode?: string
166 /** When the sign-in expires, in epoch milliseconds. */
167 expiresAt?: number
168 }) => void
169 /** Change a session setting, the same as a client. Applies at the next turn. */
170 setPluginSetting: (change: {
171 key: string
172 value: unknown
173 }) => Promise<Receipt>
174 /**
175 * The stored settings of the thread (`session.updateThreadSettings`). Read them at
176 * each call, for example the working folder `cwd`: a change applies from
177 * the next turn.
178 */
179 threadSettings: () => ThreadSettings
180 /**
181 * Store a file in the media store of this session, as `session.putMedia`
182 * does. Put `mediaPart(record)` in a tool result: the transcript and the
183 * log keep a small `harness-media:` reference, and the model gets the
184 * bytes.
185 */
186 putMedia: (upload: MediaUpload<Uint8Array>) => Promise<MediaRecord>
187}
188
189/** What a command handler receives besides its input. */
190export interface CommandContext {
191 signal: AbortSignal
192 /** The session, for the user who runs the command: `session.prompt` runs as that user. */
193 session: PluginSessionApi
194 /** Who runs the command. Default: the user that opened the session. */
195 user?: HarnessUser
196 /**
197 * The credentials of the user who runs the command. Save a sign-in here,
198 * so it belongs to that user. The same as `run.credentials`.
199 */
200 credentials: CredentialsAccess
201 /**
202 * The run of the command: the user who runs it, and that user's
203 * credentials and model provider keys (`run.keys`).
204 */
205 run: RunContext
206 /**
207 * The steps of the command. To ask the user, call `step.ask`: the log
208 * keeps the question, so a user on any machine can answer it. When the
209 * host stops while the command waits, the next host runs the command
210 * again from the top: put each side effect before the ask in `step.do`,
211 * and it does not run twice.
212 *
213 * @example
214 * ```ts
215 * run: async (_input, { step, credentials }) => {
216 * const key = await step.ask({ name: 'key', message: 'Paste your key', secret: true })
217 * await credentials.set({ id: 'acme', credential: { type: 'api_key', value: key } })
218 * }
219 * ```
220 */
221 step: ToolStep
222}
223
224/** A user action: a slash command, a button, a dashboard action. Not a model tool. */
225export interface CommandDefinition<
226 TSchema extends SchemaInput | undefined = SchemaInput | undefined,
227> {
228 description: string
229 /**
230 * The input shape, checked before `run`. Without one, `run` gets the input
231 * as sent, typed `unknown`: narrow it before use.
232 */
233 input?: TSchema
234 run: (
235 input: TSchema extends SchemaInput ? InferSchemaType<TSchema> : unknown,
236 ctx: CommandContext,
237 ) => unknown
238}
239
240/** A command with any input type. */
241export type AnyCommand = CommandDefinition<any>
242
243/**
244 * Define a command with a typed input.
245 *
246 * @example
247 * ```ts
248 * const clear = defineCommand({
249 * description: 'Remove every todo',
250 * run: async () => ({ removed: await db.clear() }),
251 * })
252 * ```
253 */
254export function defineCommand<
255 const TSchema extends SchemaInput | undefined = undefined,
256>(command: CommandDefinition<TSchema>): CommandDefinition<TSchema> {
257 return command
258}