:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(terminal): connect pi to posthog ai (#105315)
Marius Andrad8017240d3af
diff --git a/frontend/src/scenes/terminal/posthogCommands.test.ts b/frontend/src/scenes/terminal/posthogCommands.test.tsindex 1ddf866ff89e..7efe625d3072 100644--- a/frontend/src/scenes/terminal/posthogCommands.test.ts+++ b/frontend/src/scenes/terminal/posthogCommands.test.ts@@ -117,6 +117,8 @@ describe('PostHog terminal commands', () => {it.each([['notebook-delete', 'shortnote'],['notebook-update', 'shortnote', '--deleted'],+ ['notebook-update', 'shortnote', '--title', 'Updated'],+ ['notebook-create', '--title', 'New notebook'],['example/echo', '--text', 'hello'],])('blocks %s until the user approves its exact arguments', async (...argv) => {let answer!: (approved: boolean) => void@@ -130,10 +132,12 @@ describe('PostHog terminal commands', () => {const outcome = operation.catch((error: Error) => error)await waitFor(() => expect(confirm).toHaveBeenCalledTimes(1))expect(notebooksPartialUpdate).not.toHaveBeenCalled()+ expect(notebooksCreate).not.toHaveBeenCalled()expect(mcpServerInstallationsCallToolCreate).not.toHaveBeenCalled()answer(false)await expect(outcome).resolves.toEqual(expect.objectContaining({ message: 'Canceled. No changes made.' }))expect(notebooksPartialUpdate).not.toHaveBeenCalled()+ expect(notebooksCreate).not.toHaveBeenCalled()expect(mcpServerInstallationsCallToolCreate).not.toHaveBeenCalled()})@@ -214,7 +218,7 @@ describe('PostHog terminal commands', () => {structured_content: { echoed: true },})const signal = new AbortController().signal- filesystem = new PosthogFilesystem('42', signal, confirm)+ filesystem = new PosthogFilesystem('42', signal, confirm, true)await filesystem.load()commands = new PosthogCommands('42', signal, filesystem, navigate)})diff --git a/frontend/src/scenes/terminal/posthogCommands.ts b/frontend/src/scenes/terminal/posthogCommands.tsindex 4aa3dcad355c..6e822fe261b1 100644--- a/frontend/src/scenes/terminal/posthogCommands.ts+++ b/frontend/src/scenes/terminal/posthogCommands.ts@@ -512,6 +512,12 @@ export class PosthogCommands {: `Run ${tool.name} in project ${this.projectId}. This deletes the specified notebook for everyone in the project.`,items: [tool.description, JSON.stringify(args, null, 2)],})+ } else if (!tool.readOnly) {+ await this.filesystem.confirmWrite({+ title: 'Change PostHog data?',+ description: `Run ${tool.name} in project ${this.projectId}. This affects everyone in the project.`,+ items: [tool.description, JSON.stringify(args, null, 2)],+ })}return tool.invoke(args)}diff --git a/frontend/src/scenes/terminal/posthogFilesystem.test.ts b/frontend/src/scenes/terminal/posthogFilesystem.test.tsindex 45bb4d6ada0c..1e94f9c6504f 100644--- a/frontend/src/scenes/terminal/posthogFilesystem.test.ts+++ b/frontend/src/scenes/terminal/posthogFilesystem.test.ts@@ -594,21 +594,36 @@ describe('PostHog filesystem projection', () => {})- it.each(['remove', 'json'] as const)('fails closed without a confirmation handler for %s', async (operation) => {- const fs = new PosthogFilesystem('42', new AbortController().signal)- await fs.load()- const node =- operation === 'remove'- ? fs.root.children!.get('files')!.children!.get('Research')!.children!.get('Notes.md')!+ it.each(['remove', 'json', 'edit-json', 'markdown', 'mkdir', 'rename'] as const)(+ 'fails closed without a confirmation handler for %s',+ async (operation) => {+ const fs = new PosthogFilesystem('42', new AbortController().signal, undefined, true)+ await fs.load()+ const files = fs.root.children!.get('files')!+ const node = ['remove', 'markdown', 'rename'].includes(operation)+ ? files.children!.get('Research')!.children!.get('Notes.md')!: fs.root.children!.get('api')!.children!.get('notebook')!.children!.get('note1.json')!- const pending =- operation === 'remove'- ? node.remove!()- : (await node.open!()).save!(new TextEncoder().encode(JSON.stringify({ deleted: true })))- await expect(pending).rejects.toThrow('Canceled. No changes made.')- expect(fileSystemDestroy).not.toHaveBeenCalled()- expect(notebooksPartialUpdate).not.toHaveBeenCalled()- })+ const pending =+ operation === 'remove'+ ? node.remove!()+ : operation === 'mkdir'+ ? files.mkdir!('New folder')+ : operation === 'rename'+ ? node.rename!(files, 'Renamed.md')+ : (await node.open!()).save!(+ new TextEncoder().encode(+ operation === 'markdown'+ ? '# Changed'+ : JSON.stringify(operation === 'json' ? { deleted: true } : { title: 'Changed' })+ )+ )+ await expect(pending).rejects.toThrow('Canceled. No changes made.')+ expect(fileSystemDestroy).not.toHaveBeenCalled()+ expect(fileSystemCreate).not.toHaveBeenCalled()+ expect(apiMutator).not.toHaveBeenCalled()+ expect(notebooksPartialUpdate).not.toHaveBeenCalled()+ }+ )it('rejects moves of implicit folders without creating records or changing their contents', async () => {const fs = new PosthogFilesystem('42', new AbortController().signal)diff --git a/frontend/src/scenes/terminal/posthogFilesystem.ts b/frontend/src/scenes/terminal/posthogFilesystem.tsindex 09725144c3ff..39b2dc7c806b 100644--- a/frontend/src/scenes/terminal/posthogFilesystem.ts+++ b/frontend/src/scenes/terminal/posthogFilesystem.ts@@ -139,11 +139,10 @@ inside /posthog/files. Keep .md, .sql, or .json extensions when renaming files.Moves preserve object IDs and folder contents. Existing destinations cannot bereplaced. Folders inferred from file paths cannot be moved; move their files instead.Use rm to remove files, rmdir for empty folders, and rm -r for folder trees.-Deletes require a blocking confirmation. Click a button to approve or cancel;-keyboard input cannot approve a deletion. rm groups all its PostHog targets into+Project writes and connected tools require a blocking confirmation. Click a button+to approve or cancel; keyboard input cannot approve changes. rm groups its PostHog targets intoone confirmation. Other programs confirm each removal. Local Linux files do notrequire confirmation. Delete local and PostHog files in separate commands.-JSON saves that mark an object deleted and connected tools also ask for confirmation.Removing the last file reference deletes the PostHog object, using your permissions.Files open for writing must be closed before removal. Use ph notebook-create to create notebooks.Work in /tmp for programs that save by renaming a temporary file,@@ -182,7 +181,11 @@ For a break, try these commands. Each downloads on first use:Ctrl+C also stops the train and Matrix animation.The browser downloads verified packages from GitHub and caches them when storageis available. Stopping the terminal discards the installed files and local sessions.-pi runs offline: model calls, login, and package downloads need a network bridge.+pi uses PostHog AI through your signed-in session and defaults to Claude Opus 5.+Use /model in pi to choose Opus 5, Sonnet 5, Sonnet 4.6, or Haiku 4.5.+Try pi -p 'What can ph tools do?'+Run one pi session at a time. AI credit limits apply. Gateway setup is required.+The VM has no general network access, so external login and package downloads are unavailable.Use /tmp for local scripts and pi sessions; mounted PostHog files keep their API rules.Project file sizes stay zero until opened; ncdu does not download their contents.Bundled tool licenses and source links are in /opt/posthog-tools/licenses.@@ -335,7 +338,8 @@ export class PosthogFilesystem extends TerminalFilesystem {constructor(private projectId: string,private signal: AbortSignal,- private confirm: ConfirmTerminalOperation = async () => false+ private confirm: ConfirmTerminalOperation = async () => false,+ private confirmWrites = false) {super()this.text('README.txt', this.root, TERMINAL_README)@@ -357,6 +361,11 @@ export class PosthogFilesystem extends TerminalFilesystem {throw new FilesystemError(116)}const parts = [...directory.parts, this.storedName(name)]+ await this.confirmWrite({+ title: 'Create a PostHog folder?',+ description: `Create a folder in project ${this.projectId}. This affects everyone in the project.`,+ items: [joinPath(parts)],+ })const entry = await fileSystemCreate(this.projectId,{ path: joinPath(parts), type: 'folder' },@@ -396,6 +405,12 @@ export class PosthogFilesystem extends TerminalFilesystem {}}+ async confirmWrite(confirmation: TerminalConfirmation): Promise<void> {+ if (this.confirmWrites) {+ await this.confirmOperation(confirmation)+ }+ }+private removalConfirmation(nodes: TerminalNode[]): TerminalConfirmation {return {title: 'Delete PostHog files and folders?',@@ -540,6 +555,11 @@ export class PosthogFilesystem extends TerminalFilesystem {// Creating an implicit folder before moving it cannot be rolled back safely when it has children.throw new FilesystemError(95)}+ await this.confirmWrite({+ title: 'Move a PostHog file or folder?',+ description: `Move or rename an item in project ${this.projectId}. This affects everyone in the project.`,+ items: [`${this.mountedPath(node)} → /posthog/files/${joinPath(parts)}`],+ })// The generated move body describes a filesystem row, but this action requires new_path.await apiMutator<FileSystemApi>(getFileSystemMoveCreateUrl(this.projectId, entry.id), {method: 'POST',@@ -707,6 +727,12 @@ export class PosthogFilesystem extends TerminalFilesystem {description: `Save a deletion to ${entry.type} ${entry.ref} in project ${this.projectId}. This affects everyone in the project.`,items: [JSON.stringify(payload, null, 2)],})+ } else {+ await this.confirmWrite({+ title: 'Save changes to a PostHog object?',+ description: `Update ${entry.type} ${entry.ref} in project ${this.projectId}. This affects everyone in the project.`,+ items: [JSON.stringify(payload, null, 2)],+ })}if (entry.type === 'notebook' && 'content' in payload && !('text_content' in payload)) {const node = markdownNode(payload.content)@@ -754,6 +780,11 @@ export class PosthogFilesystem extends TerminalFilesystem {if (markdown === saved) {return}+ await this.confirmWrite({+ title: 'Save changes to a PostHog notebook?',+ description: `Update notebook ${entry.ref} in project ${this.projectId}. This affects everyone in the project.`,+ items: [markdown],+ })notebook = await notebooksPartialUpdate(this.projectId,entry.ref!,diff --git a/frontend/src/scenes/terminal/terminal-packages.json b/frontend/src/scenes/terminal/terminal-packages.jsonindex 02a2a355bba6..bcb6fcda8e17 100644--- a/frontend/src/scenes/terminal/terminal-packages.json+++ b/frontend/src/scenes/terminal/terminal-packages.json@@ -17,8 +17,9 @@"name": "pi","version": "0.87.1","file": "archives/pi-0.87.1.tar.gz",- "sha256": "ad9261590d1617edfb52a2fd8b71351079a37cc18515fd4b6b85f6d8d2511b6d",- "size": 20423074,+ "baseUrl": "https://raw.githubusercontent.com/PostHog/terminal-assets/1668348dce762ca6e86b48b431501c2efadce026",+ "sha256": "79721a95bbeaec1131d0b1c99392eb28785114619b1357a955647e5ff6591a4a",+ "size": 20423132,"archiveSize": 76257280,"dependencies": ["node"],"commands": {diff --git a/frontend/src/scenes/terminal/terminalAI.test.ts b/frontend/src/scenes/terminal/terminalAI.test.tsnew file mode 100644index 000000000000..a4ca3a61ff4b--- /dev/null+++ b/frontend/src/scenes/terminal/terminalAI.test.ts@@ -0,0 +1,129 @@+import { waitFor } from '@testing-library/react'+import { ReadableStream } from 'node:stream/web'++import { TerminalAI } from './terminalAI'+import { TerminalFile, TerminalFilesystem } from './terminalFilesystem'++describe('terminal AI bridge', () => {+ const originalFetch = globalThis.fetch+ const originalAny = Object.getOwnPropertyDescriptor(AbortSignal, 'any')+ let filesystem: TerminalFilesystem+ let stream: ReadableStreamDefaultController<Uint8Array>+ let session: AbortController+ const encoder = new TextEncoder()+ const decoder = new TextDecoder()+ const file = (name: string): Promise<TerminalFile> =>+ filesystem.root.children!.get('.ai')!.children!.get(name)!.open!()+ const write = async (name: string, value: string): Promise<void> => (await file(name)).save!(encoder.encode(value))+ const request = (id: string): Promise<void> => write('request', JSON.stringify({ id, body: { messages: [] } }))+ const read = async (): Promise<{ id: string; body: string; done: boolean; error?: string }> =>+ JSON.parse(decoder.decode((await file('response')).bytes))++ beforeEach(() => {+ session = new AbortController()+ Object.defineProperty(AbortSignal, 'any', {+ configurable: true,+ value: (signals: AbortSignal[]) => {+ const controller = new AbortController()+ for (const signal of signals) {+ signal.addEventListener('abort', () => controller.abort(), { once: true })+ }+ return controller.signal+ },+ })+ globalThis.fetch = jest.fn(async () => ({+ status: 200,+ body: new ReadableStream<Uint8Array>({ start: (controller) => (stream = controller) }),+ })) as jest.Mock+ filesystem = new TerminalFilesystem()+ new TerminalAI(filesystem, '42', session.signal)+ })++ afterEach(() => {+ jest.useRealTimers()+ globalThis.fetch = originalFetch+ if (originalAny) {+ Object.defineProperty(AbortSignal, 'any', originalAny)+ } else {+ delete (AbortSignal as Partial<typeof AbortSignal>).any+ }+ })++ it('streams split Unicode without replaying chunks and uses only the current project', async () => {+ await request('first')+ const bytes = encoder.encode('data: "你好"\n\n')+ stream.enqueue(bytes.slice(0, 8))+ await Promise.resolve()+ const first = await read()+ stream.enqueue(bytes.slice(8))+ stream.close()+ const chunks = [first.body]+ await waitFor(async () => {+ const frame = await read()+ chunks.push(frame.body)+ expect(frame.done).toBe(true)+ })+ expect(chunks.join('')).toBe('data: "你好"\n\n')+ expect((await read()).body).toBe('')+ expect(fetch).toHaveBeenCalledWith(+ '/api/projects/42/terminal_ai/',+ expect.objectContaining({+ credentials: 'same-origin',+ redirect: 'error',+ method: 'POST',+ })+ )+ })++ it.each(['cancel', 'stop'])('aborts a generation on %s and refuses concurrent requests', async (action) => {+ await request('first')+ await expect(request('second')).rejects.toMatchObject({ errno: 16 })+ const signal = (fetch as jest.Mock).mock.calls[0][1].signal as AbortSignal+ if (action === 'cancel') {+ await write('cancel', 'second')+ expect(signal.aborted).toBe(false)+ await write('cancel', 'first')+ } else {+ session.abort()+ }+ expect(signal.aborted).toBe(true)+ if (action === 'cancel') {+ await expect(request('retry')).rejects.toMatchObject({ errno: 16 })+ }+ stream.close()+ await waitFor(async () => expect((await read()).done).toBe(true))+ if (action === 'cancel') {+ await request('retry')+ expect(await read()).toMatchObject({ id: 'retry', done: false })+ stream.close()+ await waitFor(async () => expect((await read()).done).toBe(true))+ }+ })++ it('keeps active generations alive and aborts after 120 seconds without a chunk', async () => {+ jest.useFakeTimers()+ await request('long-running')+ const signal = (fetch as jest.Mock).mock.calls[0][1].signal as AbortSignal+ await jest.advanceTimersByTimeAsync(119_000)+ stream.enqueue(encoder.encode('data: first\n\n'))+ await jest.advanceTimersByTimeAsync(119_000)+ expect(signal.aborted).toBe(false)+ expect(await read()).toMatchObject({ body: 'data: first\n\n', done: false })+ await jest.advanceTimersByTimeAsync(1000)+ expect(signal.aborted).toBe(true)+ stream.close()+ await jest.advanceTimersByTimeAsync(0)+ expect((await read()).done).toBe(true)+ expect(jest.getTimerCount()).toBe(0)+ })++ it('reports a failed request and allows a retry', async () => {+ ;(fetch as jest.Mock).mockRejectedValueOnce(new Error('Connection failed'))+ await request('failed')+ expect(await read()).toMatchObject({ id: 'failed', error: 'Connection failed', done: true })+ await request('retry')+ expect(await read()).toMatchObject({ id: 'retry', status: 200, done: false })+ stream.close()+ await waitFor(async () => expect((await read()).done).toBe(true))+ })+})diff --git a/frontend/src/scenes/terminal/terminalAI.ts b/frontend/src/scenes/terminal/terminalAI.tsnew file mode 100644index 000000000000..fbe93e06141b--- /dev/null+++ b/frontend/src/scenes/terminal/terminalAI.ts@@ -0,0 +1,142 @@+import { getCookie } from 'lib/api'++import { getTerminalAiCreateUrl } from 'products/posthog_ai/frontend/generated/api'++import { FilesystemError, TerminalFilesystem } from './terminalFilesystem'++interface Generation {+ id: string+ controller: AbortController+ body: string+ status: number+ done: boolean+ error?: string+}++export class TerminalAI {+ private generation?: Generation+ private encoder = new TextEncoder()+ private decoder = new TextDecoder('utf-8', { fatal: true })++ constructor(filesystem: TerminalFilesystem, projectId: string, signal: AbortSignal) {+ const directory = filesystem.directory('.ai', filesystem.root)+ filesystem.file('response', directory, async () => {+ const generation = this.generation+ const bytes = this.encoder.encode(+ JSON.stringify(+ generation+ ? {+ id: generation.id,+ body: generation.body,+ status: generation.status,+ done: generation.done,+ error: generation.error,+ }+ : { id: null, done: true }+ )+ )+ if (generation) {+ generation.body = ''+ }+ return { bytes }+ })+ filesystem.file(+ 'request',+ directory,+ async () => ({+ bytes: new Uint8Array(),+ save: async (bytes) => {+ if (signal.aborted) {+ throw new DOMException('The terminal stopped.', 'AbortError')+ }+ if (this.generation && !this.generation.done) {+ throw new FilesystemError(16)+ }+ if (bytes.length > 1024 * 1024) {+ throw new Error('The conversation exceeds 1 MiB. Start a new pi session.')+ }+ const request = JSON.parse(this.decoder.decode(bytes))+ if (typeof request.id !== 'string' || !/^[a-zA-Z0-9-]{1,64}$/.test(request.id) || !request.body) {+ throw new Error('Invalid pi request. Start a new pi session.')+ }+ const generation: Generation = {+ id: request.id,+ controller: new AbortController(),+ body: '',+ status: 0,+ done: false,+ }+ this.generation = generation+ // A pending 9P save blocks other writes, including cancellation and pi's tools.+ void this.stream(projectId, request.body, generation, signal)+ },+ }),+ true+ )+ filesystem.file(+ 'cancel',+ directory,+ async () => ({+ bytes: new Uint8Array(),+ save: async (bytes) => {+ if (this.decoder.decode(bytes) === this.generation?.id) {+ this.generation.controller.abort()+ }+ },+ }),+ true+ )+ }++ private async stream(projectId: string, body: unknown, generation: Generation, signal: AbortSignal): Promise<void> {+ const idle = new AbortController()+ let idleTimer = setTimeout(() => idle.abort(), 120_000)+ try {+ const response = await fetch(getTerminalAiCreateUrl(projectId), {+ method: 'POST',+ credentials: 'same-origin',+ redirect: 'error',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': getCookie('posthog_csrftoken') || '',+ },+ body: JSON.stringify(body),+ signal: AbortSignal.any([signal, generation.controller.signal, idle.signal]),+ })+ generation.status = response.status+ const reader = response.body?.getReader()+ if (!reader) {+ throw new Error('PostHog AI returned no response. Try again.')+ }+ const decoder = new TextDecoder()+ let size = 0+ try {+ while (true) {+ const chunk = await reader.read()+ clearTimeout(idleTimer)+ idleTimer = setTimeout(() => idle.abort(), 120_000)+ if (chunk.done) {+ generation.body += decoder.decode()+ break+ }+ size += chunk.value.length+ if (size > 2 * 1024 * 1024) {+ throw new Error('The model response is too large. Ask for a shorter response.')+ }+ generation.body += decoder.decode(chunk.value, { stream: true })+ }+ } finally {+ try {+ await reader.cancel()+ } finally {+ reader.releaseLock()+ }+ }+ } catch (error) {+ generation.error = error instanceof Error ? error.message : 'PostHog AI failed. Try again.'+ } finally {+ clearTimeout(idleTimer)+ generation.done = true+ }+ }+}diff --git a/frontend/src/scenes/terminal/terminalLogic.test.ts b/frontend/src/scenes/terminal/terminalLogic.test.tsindex 02c25b8c84b5..1bf1a1f32d22 100644--- a/frontend/src/scenes/terminal/terminalLogic.test.ts+++ b/frontend/src/scenes/terminal/terminalLogic.test.ts@@ -46,6 +46,7 @@ jest.mock('./posthogFilesystem', () => ({})),}))jest.mock('./posthogCommands', () => ({ PosthogCommands: jest.fn() }))+jest.mock('./terminalAI', () => ({ TerminalAI: jest.fn() }))describe('terminal lifecycle', () => {beforeEach(() => {diff --git a/frontend/src/scenes/terminal/terminalLogic.ts b/frontend/src/scenes/terminal/terminalLogic.tsindex 1e88f842da07..d484a9dca89b 100644--- a/frontend/src/scenes/terminal/terminalLogic.ts+++ b/frontend/src/scenes/terminal/terminalLogic.ts@@ -14,6 +14,7 @@ import type { ProjectTreeRef } from '~/types'import { NinePServer } from './ninepServer'import { PosthogCommands } from './posthogCommands'import { PosthogFilesystem } from './posthogFilesystem'+import { TerminalAI } from './terminalAI'import { TerminalConfirmation } from './terminalConfirmation'import { terminalDockLogic } from './terminalDockLogic'import { TerminalRuntime } from './terminalRuntime'@@ -441,45 +442,51 @@ export const terminalLogic = kea<terminalLogicType>([actions.setStatus('loading')try {let confirmationQueue = Promise.resolve(false)- const filesystem = new PosthogFilesystem(String(projectId), controller.signal, (confirmation) => {- const pending = confirmationQueue.then(() => {- if (controller.signal.aborted) {- return false- }- return new Promise<boolean>((resolve) => {- disposables.add(- () => {- const blockKeyboard = (event: KeyboardEvent): void => {- event.preventDefault()- event.stopImmediatePropagation()- }- for (const type of ['keydown', 'keypress', 'keyup'] as const) {- window.addEventListener(type, blockKeyboard, true)- }- cache.answerConfirmation = (approved: boolean): void => {- resolve(approved)- disposables.dispose('confirmation')- }- actions.setConfirmation(confirmation)- return () => {- resolve(false)- cache.answerConfirmation = null- actions.setConfirmation(null)+ const filesystem = new PosthogFilesystem(+ String(projectId),+ controller.signal,+ (confirmation) => {+ const pending = confirmationQueue.then(() => {+ if (controller.signal.aborted) {+ return false+ }+ return new Promise<boolean>((resolve) => {+ disposables.add(+ () => {+ const blockKeyboard = (event: KeyboardEvent): void => {+ event.preventDefault()+ event.stopImmediatePropagation()+ }for (const type of ['keydown', 'keypress', 'keyup'] as const) {- window.removeEventListener(type, blockKeyboard, true)+ window.addEventListener(type, blockKeyboard, true)+ }+ cache.answerConfirmation = (approved: boolean): void => {+ resolve(approved)+ disposables.dispose('confirmation')}- }- },- 'confirmation',- { pauseOnPageHidden: false }- )+ actions.setConfirmation(confirmation)+ return () => {+ resolve(false)+ cache.answerConfirmation = null+ actions.setConfirmation(null)+ for (const type of ['keydown', 'keypress', 'keyup'] as const) {+ window.removeEventListener(type, blockKeyboard, true)+ }+ }+ },+ 'confirmation',+ { pauseOnPageHidden: false }+ )+ })})- })- confirmationQueue = pending- return pending- })+ confirmationQueue = pending+ return pending+ },+ true+ )cache.filesystem = filesystemnew PosthogCommands(String(projectId), controller.signal, filesystem, (url) => router.actions.push(url))+ new TerminalAI(filesystem, String(projectId), controller.signal)actions.setStatus('booting')const server = new NinePServer(filesystem, (error) => {if (!controller.signal.aborted) {diff --git a/frontend/src/scenes/terminal/terminalPackages.test.ts b/frontend/src/scenes/terminal/terminalPackages.test.tsindex 74d62edfc1b0..12e04d222928 100644--- a/frontend/src/scenes/terminal/terminalPackages.test.ts+++ b/frontend/src/scenes/terminal/terminalPackages.test.ts@@ -37,12 +37,12 @@ describe('optional terminal packages', () => {return true}),}- const mount = (signal = new AbortController().signal): TerminalFilesystem => {+ const mount = (signal = new AbortController().signal, baseUrl?: string): TerminalFilesystem => {const filesystem = new TerminalFilesystem()new TerminalPackages(filesystem,signal,- { example: pkg },+ { example: { ...pkg, baseUrl } },'https://raw.githubusercontent.com/example/tools/pinned').mount()return filesystem@@ -88,20 +88,23 @@ describe('optional terminal packages', () => {}})- it('downloads only when opened, shares concurrent reads, and reuses verified downloads across sessions', async () => {- const filesystem = mount()- expect(fetch).not.toHaveBeenCalled()- const [first, second] = await Promise.all([open(filesystem), open(filesystem)])- expect(first.bytes).toEqual(archive)- expect(second.bytes).toEqual(archive)- expect(fetch).toHaveBeenCalledTimes(1)- expect(fetch).toHaveBeenCalledWith(- expect.stringContaining('/pinned/example.tar.gz'),- expect.objectContaining({ credentials: 'omit', redirect: 'error', referrerPolicy: 'no-referrer' })- )- expect((await open(mount())).bytes).toEqual(archive)- expect(fetch).toHaveBeenCalledTimes(1)- })+ it.each([undefined, 'https://raw.githubusercontent.com/example/tools/package-pin'])(+ 'downloads lazily and reuses verified downloads with package source %s',+ async (baseUrl) => {+ const filesystem = mount(undefined, baseUrl)+ expect(fetch).not.toHaveBeenCalled()+ const [first, second] = await Promise.all([open(filesystem), open(filesystem)])+ expect(first.bytes).toEqual(archive)+ expect(second.bytes).toEqual(archive)+ expect(fetch).toHaveBeenCalledTimes(1)+ expect(fetch).toHaveBeenCalledWith(+ `${baseUrl ?? 'https://raw.githubusercontent.com/example/tools/pinned'}/example.tar.gz`,+ expect.objectContaining({ credentials: 'omit', redirect: 'error', referrerPolicy: 'no-referrer' })+ )+ expect((await open(mount(undefined, baseUrl))).bytes).toEqual(archive)+ expect(fetch).toHaveBeenCalledTimes(1)+ }+ )it.each(['network', 'checksum', 'size', 'cached checksum'])('allows retry after a %s failure without exposing unverified bytes',diff --git a/frontend/src/scenes/terminal/terminalPackages.ts b/frontend/src/scenes/terminal/terminalPackages.tsindex e44a10e3ec95..07e6461b2d83 100644--- a/frontend/src/scenes/terminal/terminalPackages.ts+++ b/frontend/src/scenes/terminal/terminalPackages.ts@@ -5,6 +5,7 @@ export interface TerminalPackage {name: stringversion: stringfile: string+ baseUrl?: stringsha256: stringsize: numberarchiveSize: number@@ -25,7 +26,7 @@ export class TerminalPackages {) {}private async download(pkg: TerminalPackage): Promise<Uint8Array> {- const url = `${this.baseUrl}/${pkg.file}`+ const url = `${pkg.baseUrl ?? this.baseUrl}/${pkg.file}`let cache: Cache | undefinedtry {cache = await globalThis.caches?.open(CACHE_NAME)diff --git a/products/posthog_ai/backend/presentation/__init__.py b/products/posthog_ai/backend/presentation/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/posthog_ai/backend/presentation/terminal_ai.py b/products/posthog_ai/backend/presentation/terminal_ai.pynew file mode 100644index 000000000000..18b8a617f369--- /dev/null+++ b/products/posthog_ai/backend/presentation/terminal_ai.py@@ -0,0 +1,173 @@+import json+from collections.abc import Iterator+from enum import StrEnum+from typing import Literal, cast+from uuid import uuid4++from django.conf import settings+from django.http import HttpResponse, StreamingHttpResponse++import httpx+import structlog+from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import extend_schema+from loginas.utils import is_impersonated_session+from pydantic import BaseModel, ConfigDict, Field, JsonValue, ValidationError+from pydantic_core import PydanticSerializationError+from rest_framework.exceptions import (+ APIException,+ PermissionDenied,+ ValidationError as RequestValidationError,+)+from rest_framework.request import Request+from rest_framework.viewsets import GenericViewSet++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.streaming import sse_streaming_response+from posthog.auth import SessionAuthentication+from posthog.exceptions import QuotaLimitExceeded+from posthog.llm.gateway_client import ai_gateway_headers, resolve_ai_gateway_config+from posthog.models.user import User+from posthog.ph_client import feature_enabled_or_false+from posthog.rate_limit import AIBurstRateThrottle, AISustainedRateThrottle+from posthog.renderers import SafeJSONRenderer, ServerSentEventRenderer++from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited+from ee.hogai.utils.asgi import SyncIterableToAsync+from ee.hogai.utils.feature_flags import is_privacy_mode_enabled++logger = structlog.get_logger(__name__)+++class TerminalAIMessage(BaseModel):+ role: Literal["user", "assistant"] = Field(description="Author of this conversation message.")+ content: str | list[dict[str, JsonValue]] = Field(description="Anthropic text, image, or tool content blocks.")+++class TerminalAITool(BaseModel):+ model_config = ConfigDict(extra="forbid")++ name: str = Field(max_length=128, description="Name of a tool executed inside the terminal.")+ description: str = Field(default="", max_length=20000, description="What the tool does.")+ input_schema: dict[str, JsonValue] = Field(description="JSON schema for the tool's arguments.")+ cache_control: dict[str, str] | None = Field(default=None, description="Provider prompt cache settings.")+ eager_input_streaming: bool | None = Field(default=None, description="Stream tool arguments as they are generated.")+++class TerminalAIModel(StrEnum):+ OPUS_5 = "claude-opus-5"+ SONNET_5 = "claude-sonnet-5"+ SONNET_4_6 = "claude-sonnet-4-6"+ HAIKU_4_5 = "claude-haiku-4-5"+++class TerminalAIRequest(BaseModel):+ model_config = ConfigDict(extra="forbid")++ model: TerminalAIModel = Field(description="Model served by the PostHog provider.")+ messages: list[TerminalAIMessage] = Field(+ min_length=1, max_length=1000, description="Conversation and tool results."+ )+ max_tokens: int = Field(ge=1, le=8192, description="Maximum output tokens for this generation.")+ stream: Literal[True] = Field(default=True, description="Always stream the model response.")+ system: str | list[dict[str, JsonValue]] | None = Field(default=None, description="Agent instructions.")+ tools: list[TerminalAITool] = Field(default_factory=list, max_length=100, description="Tools executed by pi.")+ temperature: float | None = Field(default=None, ge=0, le=1, description="Sampling temperature.")+++class TerminalAIUnavailable(APIException):+ status_code = 503+ default_detail = (+ "PostHog AI is not configured for this terminal. Ask your administrator to configure the AI gateway."+ )+++def _stream_generation(url: str, headers: dict[str, str], body: str) -> Iterator[bytes]:+ try:+ with httpx.Client(trust_env=False, timeout=httpx.Timeout(120, connect=10)) as client:+ with client.stream("POST", url, headers=headers, content=body) as response:+ if response.is_success:+ yield from response.iter_bytes()+ return+ message = {+ 400: "The model rejected the conversation. Start a new pi session or shorten the prompt.",+ 402: "PostHog AI has reached its spending limit. Check your billing settings.",+ 429: "PostHog AI is busy. Wait a moment and try again.",+ }.get(response.status_code, "PostHog AI could not complete the request. Try again in a moment.")+ logger.warning("terminal_ai_gateway_request_failed", status=response.status_code)+ except httpx.HTTPError as exc:+ # The exception class, not its text: an httpx message can carry the gateway URL.+ logger.warning("terminal_ai_gateway_transport_failed", error=type(exc).__name__)+ message = "The connection to PostHog AI failed. Try again in a moment."+ error = {"type": "error", "error": {"type": "api_error", "message": message}}+ yield f"event: error\ndata: {json.dumps(error)}\n\n".encode()+++class TerminalAIViewSet(TeamAndOrgViewSetMixin, GenericViewSet):+ scope_object = "conversation"+ authentication_classes = [SessionAuthentication]+ throttle_classes = [AIBurstRateThrottle, AISustainedRateThrottle]+ renderer_classes = [SafeJSONRenderer, ServerSentEventRenderer]++ @extend_schema(+ request=TerminalAIRequest,+ responses={(200, "text/event-stream"): OpenApiTypes.STR},+ description=(+ "Stream a terminal model response through PostHog AI. Requires organization approval for AI data processing. "+ "SDK consumers must use getTerminalAiCreateUrl() with streaming fetch. "+ "The generated JSON client buffers the response and cannot parse SSE."+ ),+ )+ def create(self, request: Request, **kwargs: object) -> HttpResponse | StreamingHttpResponse:+ if not isinstance(request.successful_authenticator, SessionAuthentication):+ raise PermissionDenied("Sign in to use PostHog AI in the terminal.")+ if self.team.organization.is_ai_data_processing_approved is not True:+ raise PermissionDenied(+ "Enable AI data processing in organization settings to use PostHog AI in the terminal."+ )+ user = cast(User, request.user)+ if not feature_enabled_or_false(+ "posthog-terminal",+ str(user.distinct_id),+ groups={"organization": str(self.team.organization_id)},+ ):+ raise PermissionDenied("The terminal is not enabled for this account.")+ if is_team_limited(self.team.api_token, QuotaResource.AI_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY):+ raise QuotaLimitExceeded("Your organization reached its AI credit limit. Check your billing settings.")+ gateway = resolve_ai_gateway_config()+ if gateway is None:+ raise TerminalAIUnavailable()+ try:+ content_length = int(request.META.get("CONTENT_LENGTH") or 0)+ except (TypeError, ValueError):+ raise RequestValidationError("Invalid request size. Start a new pi session.")+ if content_length > 1024 * 1024:+ raise RequestValidationError("The conversation exceeds 1 MiB. Start a new pi session.")+ try:+ if len(json.dumps(request.data, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) > 1024 * 1024:+ raise RequestValidationError("The conversation exceeds 1 MiB. Start a new pi session.")+ body = TerminalAIRequest.model_validate(request.data).model_dump_json(exclude_none=True)+ except (ValidationError, UnicodeEncodeError, PydanticSerializationError):+ raise RequestValidationError("Invalid model request. Use pi's PostHog provider.")+ # Keep the gateway credential server-side; derive attribution and policy headers from the authenticated session.+ headers = (+ ai_gateway_headers(+ ai_product="posthog_ai",+ distinct_id=user.distinct_id,+ trace_id=str(uuid4()),+ properties={"team_id": str(self.team_id), "ai_stage": "terminal"},+ )+ or {}+ )+ headers.update(+ {"x-api-key": gateway.api_key, "anthropic-version": "2023-06-01", "Content-Type": "application/json"}+ )+ if is_impersonated_session(request):+ headers["X-PostHog-Billable"] = "false"+ if is_privacy_mode_enabled(self.team):+ headers["X-PostHog-Privacy-Mode"] = "true"+ stream = _stream_generation(f"{gateway.url.rstrip('/')}/messages", headers, body)+ return sse_streaming_response(+ SyncIterableToAsync(stream) if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else stream,+ endpoint="terminal_ai",+ )diff --git a/products/posthog_ai/backend/presentation/test_terminal_ai.py b/products/posthog_ai/backend/presentation/test_terminal_ai.pynew file mode 100644index 000000000000..ef9117d01ef1--- /dev/null+++ b/products/posthog_ai/backend/presentation/test_terminal_ai.py@@ -0,0 +1,202 @@+import json+from collections.abc import Callable, Iterator+from typing import cast++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.http import StreamingHttpResponse+from django.test import override_settings++import httpx+from asgiref.sync import async_to_sync+from parameterized import parameterized++from posthog.models import Organization, PersonalAPIKey, Team+from posthog.models.utils import generate_random_token_personal, hash_key_value++UPSTREAM_DIAGNOSTICS = "private upstream diagnostics"+++def _rejecting_handler(_: httpx.Request) -> httpx.Response:+ return httpx.Response(503, text=UPSTREAM_DIAGNOSTICS)+++def _unreachable_handler(_: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError(UPSTREAM_DIAGNOSTICS)+++@override_settings(AI_GATEWAY_URL="https://ai-gateway.test/v1", AI_GATEWAY_API_KEY="phs_test_only")+class TestTerminalAI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.enabled = self.enterContext(+ patch("products.posthog_ai.backend.presentation.terminal_ai.feature_enabled_or_false", return_value=True)+ )+ self.limited = self.enterContext(+ patch("products.posthog_ai.backend.presentation.terminal_ai.is_team_limited", return_value=False)+ )+ self.enterContext(+ patch("products.posthog_ai.backend.presentation.terminal_ai.is_privacy_mode_enabled", return_value=True)+ )+ self.url = f"/api/projects/{self.team.id}/terminal_ai/"+ self.body = {+ "model": "claude-opus-5",+ "messages": [{"role": "user", "content": "Say hello"}],+ "max_tokens": 100,+ "stream": True,+ }++ @parameterized.expand(+ [+ ("anonymous", 401),+ ("api_key", 403),+ ("other_project", 403),+ ("flag_disabled", 403),+ ("consent_denied", 403),+ ("consent_unset", 403),+ ("quota", 402),+ ]+ )+ def test_access_denied_before_gateway_call(self, scenario: str, expected_status: int) -> None:+ if scenario == "anonymous":+ self.client.logout()+ elif scenario == "api_key":+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Terminal test key",+ user=self.user,+ secure_value=hash_key_value(token),+ scopes=["conversation:write"],+ )+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")+ elif scenario == "other_project":+ team = Team.objects.create(organization=Organization.objects.create(name="Another organization"))+ self.url = f"/api/projects/{team.id}/terminal_ai/"+ elif scenario == "flag_disabled":+ self.enabled.return_value = False+ elif scenario in ("consent_denied", "consent_unset"):+ self.organization.is_ai_data_processing_approved = False if scenario == "consent_denied" else None+ self.organization.save(update_fields=["is_ai_data_processing_approved"])+ else:+ self.limited.return_value = True+ with patch("products.posthog_ai.backend.presentation.terminal_ai._stream_generation") as stream:+ response = self.client.post(self.url, self.body, format="json")+ assert response.status_code == expected_status+ stream.assert_not_called()++ @parameterized.expand(+ [+ ("model", "unapproved-model"),+ ("max_tokens", 100000),+ ("extra_headers", {"x-api-key": "fake"}),+ ("messages", [{"role": "user", "content": "\ud800"}]),+ ]+ )+ def test_invalid_requests_do_not_reach_gateway(self, key: str, value: object) -> None:+ with patch("products.posthog_ai.backend.presentation.terminal_ai._stream_generation") as stream:+ response = self.client.post(+ self.url, json.dumps({**self.body, key: value}), content_type="application/json"+ )+ assert response.status_code == 400+ stream.assert_not_called()++ @parameterized.expand(+ [+ ("claude-opus-5", "Say hello"),+ ("claude-sonnet-5", "Say hello"),+ ("claude-sonnet-4-6", "Say hello"),+ ("claude-haiku-4-5", "你好🌍" * 60000),+ ]+ )+ def test_stream_preserves_tool_calls_and_trusted_attribution(self, model: str, content: str) -> None:+ self.body["model"] = model+ self.body["messages"] = [{"role": "user", "content": content}]+ event = b'event: content_block_start\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"tool_1","name":"bash","input":{}}}\n\n'+ requests: list[httpx.Request] = []++ def gateway(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ return httpx.Response(200, content=event, headers={"Content-Type": "text/event-stream"})++ client = httpx.Client(transport=httpx.MockTransport(gateway))+ with (+ patch("products.posthog_ai.backend.presentation.terminal_ai.httpx.Client", return_value=client),+ patch("products.posthog_ai.backend.presentation.terminal_ai.is_impersonated_session", return_value=True),+ ):+ response = self.client.post(+ self.url,+ json.dumps(self.body, ensure_ascii=False),+ content_type="application/json",+ HTTP_ACCEPT="text/event-stream",+ )+ assert response.status_code == 200+ assert b"".join(cast(StreamingHttpResponse, response)) == event+ assert len(requests) == 1+ request = requests[0]+ assert str(request.url) == "https://ai-gateway.test/v1/messages"+ assert request.headers["x-api-key"] == "phs_test_only"+ assert request.headers["X-PostHog-Distinct-Id"] == self.user.distinct_id+ assert request.headers["X-PostHog-Product"] == "posthog_ai"+ assert request.headers["X-PostHog-Privacy-Mode"] == "true"+ assert request.headers["X-PostHog-Billable"] == "false"+ assert json.loads(request.headers["X-PostHog-Properties"])["team_id"] == str(self.team.id)+ assert json.loads(request.content)["model"] == model+ assert json.loads(request.content)["messages"] == self.body["messages"]++ @parameterized.expand([("unicode",), ("whitespace",)])+ def test_oversized_request_does_not_reach_gateway(self, scenario: str) -> None:+ if scenario == "unicode":+ self.body["messages"] = [{"role": "user", "content": "🌍" * (256 * 1024)}]+ payload = json.dumps(self.body, ensure_ascii=False)+ if scenario == "whitespace":+ payload += " " * (1024 * 1024)+ with patch("products.posthog_ai.backend.presentation.terminal_ai._stream_generation") as stream:+ response = self.client.post(self.url, payload, content_type="application/json")+ assert response.status_code == 400+ stream.assert_not_called()++ @parameterized.expand(+ [+ ("rejected", _rejecting_handler, "terminal_ai_gateway_request_failed"),+ ("unreachable", _unreachable_handler, "terminal_ai_gateway_transport_failed"),+ ]+ )+ def test_gateway_errors_stay_private_and_are_logged(+ self, _name: str, handler: Callable[[httpx.Request], httpx.Response], event: str+ ) -> None:+ client = httpx.Client(transport=httpx.MockTransport(handler))+ with patch("products.posthog_ai.backend.presentation.terminal_ai.httpx.Client", return_value=client):+ with patch("products.posthog_ai.backend.presentation.terminal_ai.logger") as logger:+ response = self.client.post(self.url, self.body, format="json")+ body = b"".join(cast(StreamingHttpResponse, response))+ assert b"event: error" in body+ assert b"Try again" in body+ assert UPSTREAM_DIAGNOSTICS.encode() not in body+ assert logger.warning.call_args[0][0] == event+ assert UPSTREAM_DIAGNOSTICS not in str(logger.warning.call_args)+ assert "phs_test_only" not in str(logger.warning.call_args)++ @override_settings(SERVER_GATEWAY_INTERFACE="ASGI")+ def test_asgi_delivers_first_chunk_before_upstream_finishes(self) -> None:+ finished = False++ def stream() -> Iterator[bytes]:+ nonlocal finished+ yield b"data: first\n\n"+ finished = True++ with patch("products.posthog_ai.backend.presentation.terminal_ai._stream_generation", return_value=stream()):+ response = cast(StreamingHttpResponse, self.client.post(self.url, self.body, format="json"))+ assert response.status_code == 200++ async def consume() -> None:+ iterator = aiter(response)+ assert await anext(iterator) == b"data: first\n\n"+ assert not finished+ with self.assertRaises(StopAsyncIteration):+ await anext(iterator)+ assert finished++ async_to_sync(consume)()diff --git a/products/posthog_ai/backend/routes.py b/products/posthog_ai/backend/routes.pyindex a68a90185a02..22252ed457b3 100644--- a/products/posthog_ai/backend/routes.py+++ b/products/posthog_ai/backend/routes.py@@ -1,9 +1,11 @@from posthog.api.routing import RouterRegistryfrom products.posthog_ai.backend.api import MCPToolsViewSet+from products.posthog_ai.backend.presentation.terminal_ai import TerminalAIViewSetdef register_routes(routers: RouterRegistry) -> None:+ routers.projects.register(r"terminal_ai", TerminalAIViewSet, "project_terminal_ai", ["team_id"])routers.projects.register(r"mcp_tools",MCPToolsViewSet,diff --git a/products/posthog_ai/frontend/generated/api.schemas.ts b/products/posthog_ai/frontend/generated/api.schemas.tsindex 2d684101fd9a..2ca44de9e758 100644--- a/products/posthog_ai/frontend/generated/api.schemas.ts+++ b/products/posthog_ai/frontend/generated/api.schemas.ts@@ -659,6 +659,97 @@ export interface DocsSearchResponseApi {content: string}+/**+ * Agent instructions.+ */+export type TerminalAIRequestApiSystem = string | { [key: string]: JsonValueApi }[] | null++export type TerminalAIModelApi = (typeof TerminalAIModelApi)[keyof typeof TerminalAIModelApi]++export const TerminalAIModelApi = {+ ClaudeOpus5: 'claude-opus-5',+ ClaudeSonnet5: 'claude-sonnet-5',+ ClaudeSonnet46: 'claude-sonnet-4-6',+ ClaudeHaiku45: 'claude-haiku-4-5',+} as const++export type TerminalAIMessageRoleEnumApi =+ (typeof TerminalAIMessageRoleEnumApi)[keyof typeof TerminalAIMessageRoleEnumApi]++export const TerminalAIMessageRoleEnumApi = {+ User: 'user',+ Assistant: 'assistant',+} as const++/**+ * Anthropic text, image, or tool content blocks.+ */+export type TerminalAIMessageApiContent = string | { [key: string]: JsonValueApi }[]++export interface TerminalAIMessageApi {+ /** Author of this conversation message. */+ role: TerminalAIMessageRoleEnumApi+ /** Anthropic text, image, or tool content blocks. */+ content: TerminalAIMessageApiContent+}++/**+ * JSON schema for the tool's arguments.+ */+export type TerminalAIToolApiInputSchema = { [key: string]: JsonValueApi }++/**+ * Provider prompt cache settings.+ */+export type TerminalAIToolApiCacheControl = { [key: string]: string } | null++export interface TerminalAIToolApi {+ /**+ * Name of a tool executed inside the terminal.+ * @maxLength 128+ */+ name: string+ /**+ * What the tool does.+ * @maxLength 20000+ */+ description?: string+ /** JSON schema for the tool's arguments. */+ input_schema: TerminalAIToolApiInputSchema+ /** Provider prompt cache settings. */+ cache_control?: TerminalAIToolApiCacheControl+ /** Stream tool arguments as they are generated. */+ eager_input_streaming?: boolean | null+}++export interface TerminalAIRequestApi {+ /** Model served by the PostHog provider. */+ model: TerminalAIModelApi+ /**+ * Conversation and tool results.+ * @minItems 1+ * @maxItems 1000+ */+ messages: TerminalAIMessageApi[]+ /**+ * Maximum output tokens for this generation.+ * @minimum 1+ * @maximum 8192+ */+ max_tokens: number+ /** Always stream the model response. */+ stream?: true+ /** Agent instructions. */+ system?: TerminalAIRequestApiSystem+ /**+ * Tools executed by pi.+ * @maxItems 100+ */+ tools?: TerminalAIToolApi[]+ /** Sampling temperature. */+ temperature?: number | null+}+export type ConversationsListParams = {/*** Number of results to return per page.@@ -680,3 +771,14 @@ export type CoreMemoryListParams = {*/offset?: number}++export type TerminalAiCreateParams = {+ format?: TerminalAiCreateFormat+}++export type TerminalAiCreateFormat = (typeof TerminalAiCreateFormat)[keyof typeof TerminalAiCreateFormat]++export const TerminalAiCreateFormat = {+ Json: 'json',+ Txt: 'txt',+} as constdiff --git a/products/posthog_ai/frontend/generated/api.ts b/products/posthog_ai/frontend/generated/api.tsindex a12dc6f55f48..4a5034df3edd 100644--- a/products/posthog_ai/frontend/generated/api.ts+++ b/products/posthog_ai/frontend/generated/api.ts@@ -26,6 +26,8 @@ import type {PatchedMaxCoreMemoryApi,SandboxMessageResponseApi,SandboxOpenApi,+ TerminalAIRequestApi,+ TerminalAiCreateParams,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -441,3 +443,36 @@ export const docsSearch = async (body: JSON.stringify(docsSearchRequestApi),})}++export const getTerminalAiCreateUrl = (projectId: string, params?: TerminalAiCreateParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/terminal_ai/?${stringifiedParams}`+ : `/api/projects/${projectId}/terminal_ai/`+}++/**+ * Stream a terminal model response through PostHog AI. Requires organization approval for AI data processing. SDK consumers must use getTerminalAiCreateUrl() with streaming fetch. The generated JSON client buffers the response and cannot parse SSE.+ */+export const terminalAiCreate = async (+ projectId: string,+ terminalAIRequestApi: TerminalAIRequestApi,+ params?: TerminalAiCreateParams,+ options?: RequestInit+): Promise<string> => {+ return apiMutator<string>(getTerminalAiCreateUrl(projectId, params), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(terminalAIRequestApi),+ })+}diff --git a/products/posthog_ai/frontend/generated/api.zod.ts b/products/posthog_ai/frontend/generated/api.zod.tsindex a8cd6bdb323a..7744b5e84d5f 100644--- a/products/posthog_ai/frontend/generated/api.zod.ts+++ b/products/posthog_ai/frontend/generated/api.zod.ts@@ -239,3 +239,82 @@ export const DocsSearchBody = /* @__PURE__ */ zod.object({'Natural-language description of what to find in the PostHog documentation. Inkeep performs hybrid (semantic + full-text) RAG, so phrase the query the way a user would ask the question.'),})++/**+ * Stream a terminal model response through PostHog AI. Requires organization approval for AI data processing. SDK consumers must use getTerminalAiCreateUrl() with streaming fetch. The generated JSON client buffers the response and cannot parse SSE.+ */+export const terminalAiCreateBodyMessagesMax = 1000++export const terminalAiCreateBodyMaxTokensMax = 8192++export const terminalAiCreateBodyStreamDefault = true+export const terminalAiCreateBodyToolsItemNameMax = 128++export const terminalAiCreateBodyToolsItemDescriptionDefault = ``+export const terminalAiCreateBodyToolsItemDescriptionMax = 20000++export const terminalAiCreateBodyToolsMax = 100++export const terminalAiCreateBodyTemperatureOneMin = 0+export const terminalAiCreateBodyTemperatureOneMax = 1++export const TerminalAiCreateBody = /* @__PURE__ */ zod.object({+ model: zod+ .enum(['claude-opus-5', 'claude-sonnet-5', 'claude-sonnet-4-6', 'claude-haiku-4-5'])+ .describe('Model served by the PostHog provider.'),+ messages: zod+ .array(+ zod.object({+ role: zod.enum(['user', 'assistant']).describe('Author of this conversation message.'),+ content: zod+ .union([zod.string(), zod.array(zod.record(zod.string(), zod.unknown()))])+ .describe('Anthropic text, image, or tool content blocks.'),+ })+ )+ .min(1)+ .max(terminalAiCreateBodyMessagesMax)+ .describe('Conversation and tool results.'),+ max_tokens: zod+ .number()+ .min(1)+ .max(terminalAiCreateBodyMaxTokensMax)+ .describe('Maximum output tokens for this generation.'),+ stream: zod.boolean().default(terminalAiCreateBodyStreamDefault).describe('Always stream the model response.'),+ system: zod+ .union([zod.string(), zod.array(zod.record(zod.string(), zod.unknown())), zod.null()])+ .optional()+ .describe('Agent instructions.'),+ tools: zod+ .array(+ zod.object({+ name: zod+ .string()+ .max(terminalAiCreateBodyToolsItemNameMax)+ .describe('Name of a tool executed inside the terminal.'),+ description: zod+ .string()+ .max(terminalAiCreateBodyToolsItemDescriptionMax)+ .default(terminalAiCreateBodyToolsItemDescriptionDefault)+ .describe('What the tool does.'),+ input_schema: zod.record(zod.string(), zod.unknown()).describe("JSON schema for the tool's arguments."),+ cache_control: zod+ .union([zod.record(zod.string(), zod.string()), zod.null()])+ .optional()+ .describe('Provider prompt cache settings.'),+ eager_input_streaming: zod+ .union([zod.boolean(), zod.null()])+ .optional()+ .describe('Stream tool arguments as they are generated.'),+ })+ )+ .max(terminalAiCreateBodyToolsMax)+ .optional()+ .describe('Tools executed by pi.'),+ temperature: zod+ .union([+ zod.number().min(terminalAiCreateBodyTemperatureOneMin).max(terminalAiCreateBodyTemperatureOneMax),+ zod.null(),+ ])+ .optional()+ .describe('Sampling temperature.'),+})diff --git a/products/posthog_ai/mcp/tools.yaml b/products/posthog_ai/mcp/tools.yamlindex 3c750c398342..a98ec5887118 100644--- a/products/posthog_ai/mcp/tools.yaml+++ b/products/posthog_ai/mcp/tools.yaml@@ -134,3 +134,6 @@ tools:mcp-tools-create:operation: mcp_tools_createenabled: false+ terminal-ai-create:+ operation: terminal_ai_create+ enabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 581fefac95ab..806e47494120 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -97680,6 +97680,98 @@ export namespace Schemas {PooledSamples: 'pooled_samples',} as const;+ /**+ * Anthropic text, image, or tool content blocks.+ */+ export type TerminalAIMessageContent = string | {[key: string]: JsonValue}[];++ export type TerminalAIMessageRoleEnum = typeof TerminalAIMessageRoleEnum[keyof typeof TerminalAIMessageRoleEnum];+++ export const TerminalAIMessageRoleEnum = {+ User: 'user',+ Assistant: 'assistant',+ } as const;++ export interface TerminalAIMessage {+ /** Author of this conversation message. */+ role: TerminalAIMessageRoleEnum;+ /** Anthropic text, image, or tool content blocks. */+ content: TerminalAIMessageContent;+ }++ export type TerminalAIModel = typeof TerminalAIModel[keyof typeof TerminalAIModel];+++ export const TerminalAIModel = {+ ClaudeOpus5: 'claude-opus-5',+ ClaudeSonnet5: 'claude-sonnet-5',+ ClaudeSonnet46: 'claude-sonnet-4-6',+ ClaudeHaiku45: 'claude-haiku-4-5',+ } as const;++ /**+ * Agent instructions.+ */+ export type TerminalAIRequestSystem = string | {[key: string]: JsonValue}[] | null;++ /**+ * JSON schema for the tool's arguments.+ */+ export type TerminalAIToolInputSchema = {[key: string]: JsonValue};++ /**+ * Provider prompt cache settings.+ */+ export type TerminalAIToolCacheControl = {[key: string]: string} | null;++ export interface TerminalAITool {+ /**+ * Name of a tool executed inside the terminal.+ * @maxLength 128+ */+ name: string;+ /**+ * What the tool does.+ * @maxLength 20000+ */+ description?: string;+ /** JSON schema for the tool's arguments. */+ input_schema: TerminalAIToolInputSchema;+ /** Provider prompt cache settings. */+ cache_control?: TerminalAIToolCacheControl;+ /** Stream tool arguments as they are generated. */+ eager_input_streaming?: boolean | null;+ }++ export interface TerminalAIRequest {+ /** Model served by the PostHog provider. */+ model: TerminalAIModel;+ /**+ * Conversation and tool results.+ * @minItems 1+ * @maxItems 1000+ */+ messages: TerminalAIMessage[];+ /**+ * Maximum output tokens for this generation.+ * @minimum 1+ * @maximum 8192+ */+ max_tokens: number;+ /** Always stream the model response. */+ stream?: true;+ /** Agent instructions. */+ system?: TerminalAIRequestSystem;+ /**+ * Tools executed by pi.+ * @maxItems 100+ */+ tools?: TerminalAITool[];+ /** Sampling temperature. */+ temperature?: number | null;+ }+export type TestHogRequestConditionsItem = { [key: string]: unknown };export interface TestHogTargetConfig {@@ -114362,6 +114454,18 @@ export namespace Schemas {offset?: number;};+ export type TerminalAiCreateParams = {+ format?: TerminalAiCreateFormat;+ };++ export type TerminalAiCreateFormat = typeof TerminalAiCreateFormat[keyof typeof TerminalAiCreateFormat];+++ export const TerminalAiCreateFormat = {+ Json: 'json',+ Txt: 'txt',+ } as const;+export type TracingSpansAttributesRetrieveParams = {/*** Type of attributes: "span_attribute" for span-level attributes, "span_resource_attribute" for resource-level attributes.