diff --git a/src/agent/__tests__/__snapshots__/commandments.test.ts.snap b/src/agent/__tests__/__snapshots__/commandments.test.ts.snap index d0d37085b..55a1beaea 100644 --- a/src/agent/__tests__/__snapshots__/commandments.test.ts.snap +++ b/src/agent/__tests__/__snapshots__/commandments.test.ts.snap @@ -25,7 +25,7 @@ When a skill provides a numbered or bulleted list of questions, translate the en After \`wizard_ask\` returns, use the answers directly — do not re-ask in text, and do not call \`wizard_ask\` again to confirm a field the user already answered. Correcting a rejected value is the one exception, and it is expected: when whatever you handed an answer to rejects it — a connection that fails, a host or key the API calls invalid, a permission error — ask again for only the fields that were wrong, reuse the same \`subject\`, and say what was rejected and what a valid value looks like. A value the user could fix in one keystroke is never a reason to abandon the step for a link they have to follow themselves. Stop after a couple of attempts on one subject. A dismissed or timed-out ask is not this case — the result names the fields it did not collect and why, and that is a decline, so fall back instead of re-asking. Use the Task tools to plan and track the whole run so the user always sees where you are. Create the task list once you understand the work — after you load and skim the skill workflow, not before — in a single tool call, in the order you will run them, with one task per stage covering the whole run through to instrumenting events, creating the dashboard, and writing the setup report. Give each an imperative subject AND an \`activeForm\` (the present-continuous label the panel shows while it runs, e.g. subject "Install SDK" / activeForm "Installing SDK"). Keep the list current: add a task the moment you discover work it is missing. -Try to keep exactly ONE task \`in_progress\`. \`TaskUpdate\` it to \`in_progress\` right before you start that stage, and to \`completed\` the instant you finish it — one at a time, never batched at the end. Only mark \`completed\` when the work is genuinely done; if the build fails, a step is partial, or you hit a blocker, keep it \`in_progress\` and add a task for the fix. +Try to keep exactly ONE task \`in_progress\`. \`TaskUpdate\` it to \`in_progress\` right before you start that stage, and to \`completed\` the instant you finish it — one at a time, never batched at the end. Never spend a whole turn on \`TaskUpdate\` alone: when transitioning between stages, pair \`TaskUpdate\` (\`completed\` for the finished stage and \`in_progress\` for the next) with the next stage’s first tool call in the same turn. Only mark \`completed\` when the work is genuinely done; if the build fails, a step is partial, or you hit a blocker, keep it \`in_progress\` and add a task for the fix. After you complete a task, take the next one in order (lowest id first — earlier stages set up later ones), mark it \`in_progress\`, and continue. Driving the list in order top to bottom is how you finish every stage. Each task subject is SHORT — a few words naming only the stage of work: "Analyze project", "Install SDK", "Initialize PostHog", "Instrument events", "Set env vars", "Verify", "Create dashboard". No file or directory names, no framework/router/package names, no specific event names, and no parenthetical "(...)" detail. The detail belongs in the work and the \`activeForm\`, not the subject." `; @@ -81,7 +81,7 @@ When a skill provides a numbered or bulleted list of questions, translate the en After \`wizard_ask\` returns, use the answers directly — do not re-ask in text, and do not call \`wizard_ask\` again to confirm a field the user already answered. Correcting a rejected value is the one exception, and it is expected: when whatever you handed an answer to rejects it — a connection that fails, a host or key the API calls invalid, a permission error — ask again for only the fields that were wrong, reuse the same \`subject\`, and say what was rejected and what a valid value looks like. A value the user could fix in one keystroke is never a reason to abandon the step for a link they have to follow themselves. Stop after a couple of attempts on one subject. A dismissed or timed-out ask is not this case — the result names the fields it did not collect and why, and that is a decline, so fall back instead of re-asking. Use the Task tools to plan and track the whole run so the user always sees where you are. Create the task list once you understand the work — after you load and skim the skill workflow, not before — in a single tool call, in the order you will run them, with one task per stage covering the whole run through to instrumenting events, creating the dashboard, and writing the setup report. Give each an imperative subject AND an \`activeForm\` (the present-continuous label the panel shows while it runs, e.g. subject "Install SDK" / activeForm "Installing SDK"). Keep the list current: add a task the moment you discover work it is missing. -Try to keep exactly ONE task \`in_progress\`. \`TaskUpdate\` it to \`in_progress\` right before you start that stage, and to \`completed\` the instant you finish it — one at a time, never batched at the end. Only mark \`completed\` when the work is genuinely done; if the build fails, a step is partial, or you hit a blocker, keep it \`in_progress\` and add a task for the fix. +Try to keep exactly ONE task \`in_progress\`. \`TaskUpdate\` it to \`in_progress\` right before you start that stage, and to \`completed\` the instant you finish it — one at a time, never batched at the end. Never spend a whole turn on \`TaskUpdate\` alone: when transitioning between stages, pair \`TaskUpdate\` (\`completed\` for the finished stage and \`in_progress\` for the next) with the next stage’s first tool call in the same turn. Only mark \`completed\` when the work is genuinely done; if the build fails, a step is partial, or you hit a blocker, keep it \`in_progress\` and add a task for the fix. After you complete a task, take the next one in order (lowest id first — earlier stages set up later ones), mark it \`in_progress\`, and continue. Driving the list in order top to bottom is how you finish every stage. Each task subject is SHORT — a few words naming only the stage of work: "Analyze project", "Install SDK", "Initialize PostHog", "Instrument events", "Set env vars", "Verify", "Create dashboard". No file or directory names, no framework/router/package names, no specific event names, and no parenthetical "(...)" detail. The detail belongs in the work and the \`activeForm\`, not the subject. @@ -182,7 +182,7 @@ ALWAYS surface a custom-scout proposal in step 6b: bring the user your one or tw Rank candidates at the discriminator level, not the category level. "Covered" only means an enabled scout would actually FIRE for that failure mode: a conversion-rate watcher does not catch entry volume collapsing; a Stripe-transaction watcher does not catch a lead form going silent. A surface whose failure mode has no firing condition among the enabled scouts is your strongest candidate. Be honest in the option descriptions: if a candidate overlaps something an enabled scout partially watches, say so in its description rather than dropping the candidate. The user chooses with full information; you do not gatekeep on their behalf. Use the Task tools to plan and track the whole run so the user always sees where you are. Create the task list once you understand the work — after you load and skim the skill workflow, not before — in a single tool call, in the order you will run them, with one task per stage covering the whole run through to instrumenting events, creating the dashboard, and writing the setup report. Give each an imperative subject AND an \`activeForm\` (the present-continuous label the panel shows while it runs, e.g. subject "Install SDK" / activeForm "Installing SDK"). Keep the list current: add a task the moment you discover work it is missing. -Try to keep exactly ONE task \`in_progress\`. \`TaskUpdate\` it to \`in_progress\` right before you start that stage, and to \`completed\` the instant you finish it — one at a time, never batched at the end. Only mark \`completed\` when the work is genuinely done; if the build fails, a step is partial, or you hit a blocker, keep it \`in_progress\` and add a task for the fix. +Try to keep exactly ONE task \`in_progress\`. \`TaskUpdate\` it to \`in_progress\` right before you start that stage, and to \`completed\` the instant you finish it — one at a time, never batched at the end. Never spend a whole turn on \`TaskUpdate\` alone: when transitioning between stages, pair \`TaskUpdate\` (\`completed\` for the finished stage and \`in_progress\` for the next) with the next stage’s first tool call in the same turn. Only mark \`completed\` when the work is genuinely done; if the build fails, a step is partial, or you hit a blocker, keep it \`in_progress\` and add a task for the fix. After you complete a task, take the next one in order (lowest id first — earlier stages set up later ones), mark it \`in_progress\`, and continue. Driving the list in order top to bottom is how you finish every stage. Each task subject is SHORT — a few words naming only the stage of work: "Analyze project", "Install SDK", "Initialize PostHog", "Instrument events", "Set env vars", "Verify", "Create dashboard". No file or directory names, no framework/router/package names, no specific event names, and no parenthetical "(...)" detail. The detail belongs in the work and the \`activeForm\`, not the subject. diff --git a/src/agent/__tests__/commandments.test.ts b/src/agent/__tests__/commandments.test.ts index ff7ab84b6..d5726d0c9 100644 --- a/src/agent/__tests__/commandments.test.ts +++ b/src/agent/__tests__/commandments.test.ts @@ -49,7 +49,7 @@ describe('commandments by axis', () => { 'never reach an orchestrator task on %s', (harness) => { expect(prompt(harness, Sequence.orchestrator)).not.toMatch( - /TaskUpdate|TaskCreate|Task tools|task list/, + /TaskUpdate|TaskCreate|TaskGet|TaskList|Task tools|task list/i, ); }, ); diff --git a/src/agent/__tests__/initialize-agent.test.ts b/src/agent/__tests__/initialize-agent.test.ts index 35ce80971..377c148aa 100644 --- a/src/agent/__tests__/initialize-agent.test.ts +++ b/src/agent/__tests__/initialize-agent.test.ts @@ -1,9 +1,12 @@ import { BASE_ALLOWED_TOOLS, + TaskTool, initializeAgent, + resolveRunToolLists, type AgentConfig, } from '@agent/agent-interface'; import { WIZARD_TOOL_NAMES, createWizardToolsServer } from '@agent/tools'; +import { Sequence } from '@shared/constants'; import { HostResolution } from '@shared/host-resolution'; import type { WizardRunOptions } from '@utils/types'; @@ -84,3 +87,21 @@ it('leaves publish_program_result out of the tools every program gets', () => { WIZARD_TOOL_NAMES.publishProgramResult, ); }); + +it('removes linear Task* tools on orchestrator runs while keeping them on linear runs', () => { + const orch = resolveRunToolLists({ + sequence: Sequence.orchestrator, + disallowedTools: ['enqueue_task'], + }); + for (const tool of Object.values(TaskTool)) { + expect(orch.allowedTools).not.toContain(tool); + expect(orch.disallowedTools).toContain(tool); + } + expect(orch.disallowedTools).toContain('enqueue_task'); + + const linear = resolveRunToolLists({ sequence: Sequence.linear }); + for (const tool of Object.values(TaskTool)) { + expect(linear.allowedTools).toContain(tool); + expect(linear.disallowedTools).not.toContain(tool); + } +}); diff --git a/src/agent/agent-interface.ts b/src/agent/agent-interface.ts index 4ca0994a5..2fe9d1a98 100644 --- a/src/agent/agent-interface.ts +++ b/src/agent/agent-interface.ts @@ -1080,12 +1080,7 @@ export async function runAgent( // Per-program allow/disallow lists tweak BASE_ALLOWED_TOOLS. Skills are // enabled via the `skills` query option; PostHog MCP tools come through // `mcpServers`. Neither belongs in this list. - const disallow = new Set(agentConfig.disallowedTools ?? []); - const allowedTools = ( - agentConfig.readOnly - ? READ_ONLY_TOOLS - : [...BASE_ALLOWED_TOOLS, ...(agentConfig.allowedTools ?? [])] - ).filter((t) => !disallow.has(t) && !CAN_USE_TOOL_FILE_TOOLS.has(t)); + const { allowedTools, disallowedTools } = resolveRunToolLists(agentConfig); // Subagents dispatched via the Agent tool don't inherit the parent's // MCP servers by default — so general-purpose subagents can't see the @@ -1148,9 +1143,8 @@ export async function runAgent( // (sdk.d.ts: AgentDefinition has its own disallowedTools, and // `tools: undefined` means "inherit all"). Without this, a program // that disallows wizard_ask still leaks it to dispatched subagents. - disallowedTools: agentConfig.disallowedTools - ? [...agentConfig.disallowedTools] - : undefined, + disallowedTools: + disallowedTools.length > 0 ? disallowedTools : undefined, }, }, // Load skills from project's .claude/skills/ directory @@ -1168,6 +1162,7 @@ export async function runAgent( // 'Skill' in allowedTools in favor of this option.) skills: agentConfig.readOnly ? [] : 'all', allowedTools, + ...(disallowedTools.length > 0 ? { disallowedTools } : {}), sandbox: { enabled: true, // SDK 0.2.91 made failIfUnavailable default to true when enabled is @@ -1275,7 +1270,7 @@ export async function runAgent( { readOnly: agentConfig.readOnly, wizardAskPending: agentConfig.getPendingQuestion?.() != null, - disallowedTools: agentConfig.disallowedTools, + disallowedTools, onDebug: (line) => debugLine(emit, options, line), }, ); @@ -1923,7 +1918,7 @@ export const BASE_ALLOWED_TOOLS: readonly string[] = [ 'Glob', 'Bash', // Task list tools (replaced TodoWrite in 0.3.142). Commandments instruct - // the agent to call TaskCreate/TaskUpdate to surface progress in the TUI. + // linear agents to call TaskCreate/TaskUpdate to surface progress in the TUI. ...Object.values(TaskTool), 'ListMcpResourcesTool', // publish_program_result is opt-in: a program that writes the result lists it in allowedTools. @@ -1932,6 +1927,34 @@ export const BASE_ALLOWED_TOOLS: readonly string[] = [ ), ]; +/** + * Resolve effective allow/disallow tool lists for an Anthropic SDK run. + * Linear Task* tools are stripped and disallowed on orchestrator runs so + * linear todo tools never pollute task sessions or their subagents. + */ +export function resolveRunToolLists(config: { + sequence: Sequence; + readOnly?: boolean; + allowedTools?: readonly string[]; + disallowedTools?: readonly string[]; +}): { allowedTools: string[]; disallowedTools: string[] } { + const disallowedTools = [ + ...new Set([ + ...(config.disallowedTools ?? []), + ...(config.sequence === Sequence.orchestrator + ? Object.values(TaskTool) + : []), + ]), + ]; + const disallow = new Set(disallowedTools); + const allowedTools = ( + config.readOnly + ? READ_ONLY_TOOLS + : [...BASE_ALLOWED_TOOLS, ...(config.allowedTools ?? [])] + ).filter((t) => !disallow.has(t) && !CAN_USE_TOOL_FILE_TOOLS.has(t)); + return { allowedTools, disallowedTools }; +} + type TaskEntry = { id?: string; source?: string; diff --git a/src/agent/runner/__tests__/switchboard.test.ts b/src/agent/runner/__tests__/switchboard.test.ts index 2d213b57b..5e3276ba0 100644 --- a/src/agent/runner/__tests__/switchboard.test.ts +++ b/src/agent/runner/__tests__/switchboard.test.ts @@ -352,6 +352,7 @@ describe('switchboard model allow-list', () => { 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-6-sol', + 'gpt-6.2-sol', ]; const bare = (model: string): string => model.replace(/^openai\//, ''); diff --git a/src/agent/runner/sequence/linear.ts b/src/agent/runner/sequence/linear.ts index 9a4d8efee..aa997b98e 100644 --- a/src/agent/runner/sequence/linear.ts +++ b/src/agent/runner/sequence/linear.ts @@ -85,10 +85,16 @@ async function executeLinear( ); if (signal?.aborted) return aborted(); if (installResult.kind !== 'ok') { - return failed(installFailure(run.integrationLabel, installResult)); + if (!run.optionalSkill) { + return failed(installFailure(run.integrationLabel, installResult)); + } + logToFile( + `[agent-runner] optional skill ${run.skillId} install failed (${installResult.kind}); falling back to runtime discovery`, + ); + } else { + skillPath = installResult.path; + logToFile(`[agent-runner] skill installed at ${skillPath}`); } - skillPath = installResult.path; - logToFile(`[agent-runner] skill installed at ${skillPath}`); } let sdkSkillPaths: string[] = []; diff --git a/src/agent/runner/shared/types.ts b/src/agent/runner/shared/types.ts index 0e31883cd..367f2ba78 100644 --- a/src/agent/runner/shared/types.ts +++ b/src/agent/runner/shared/types.ts @@ -53,6 +53,8 @@ export interface AgentRunDefinition { integrationLabel: string; /** Skill ID to pre-install. Omit for agent-driven skill discovery. */ skillId?: string; + /** When true, a failed pre-install logs and falls back to runtime discovery instead of aborting. */ + optionalSkill?: boolean; /** Additional program-specific prompt instructions. Appended after the default project prompt. */ customPrompt?: (ctx: PromptContext) => string; prompt?: (ctx: PromptContext) => string; // replaces the assembled project prompt; linear diff --git a/src/agent/runner/switchboard/commandments.ts b/src/agent/runner/switchboard/commandments.ts index 8ee788ec8..8e29e7d3a 100644 --- a/src/agent/runner/switchboard/commandments.ts +++ b/src/agent/runner/switchboard/commandments.ts @@ -15,28 +15,12 @@ import { Harness, Sequence } from '@shared/constants'; import { WIZARD_COMMANDMENTS } from '../../commandments'; import { piRuntimeNotes, type RuntimeCaps } from '../harness/pi/runtime-notes'; +import { LINEAR_COMMANDMENTS } from './linear-commandments'; // ── Sequence axis ─────────────────────────────────────────────────────── -/** - * LINEAR only. One session drives the whole run and holds the Task tools; an - * orchestrator task session holds none of them and reports through - * `complete_task`, so naming them there only earns a "no task tool available" - * remark. True on every harness — both mount the Task tools on linear and - * neither does for a task session. - */ -const TASK_LIST_MANAGEMENT = [ - 'Use the Task tools to plan and track the whole run so the user always sees where you are. Create the task list once you understand the work — after you load and skim the skill workflow, not before — in a single tool call, in the order you will run them, with one task per stage covering the whole run through to instrumenting events, creating the dashboard, and writing the setup report. Give each an imperative subject AND an `activeForm` (the present-continuous label the panel shows while it runs, e.g. subject "Install SDK" / activeForm "Installing SDK"). Keep the list current: add a task the moment you discover work it is missing.', - - 'Try to keep exactly ONE task `in_progress`. `TaskUpdate` it to `in_progress` right before you start that stage, and to `completed` the instant you finish it — one at a time, never batched at the end. Only mark `completed` when the work is genuinely done; if the build fails, a step is partial, or you hit a blocker, keep it `in_progress` and add a task for the fix.', - - 'After you complete a task, take the next one in order (lowest id first — earlier stages set up later ones), mark it `in_progress`, and continue. Driving the list in order top to bottom is how you finish every stage.', - - 'Each task subject is SHORT — a few words naming only the stage of work: "Analyze project", "Install SDK", "Initialize PostHog", "Instrument events", "Set env vars", "Verify", "Create dashboard". No file or directory names, no framework/router/package names, no specific event names, and no parenthetical "(...)" detail. The detail belongs in the work and the `activeForm`, not the subject.', -]; - const SEQUENCE_COMMANDMENTS: Record = { - [Sequence.linear]: TASK_LIST_MANAGEMENT, + [Sequence.linear]: LINEAR_COMMANDMENTS, [Sequence.orchestrator]: [], }; diff --git a/src/agent/runner/switchboard/flags/schemes.ts b/src/agent/runner/switchboard/flags/schemes.ts index cf3cd14e3..d5b283567 100644 --- a/src/agent/runner/switchboard/flags/schemes.ts +++ b/src/agent/runner/switchboard/flags/schemes.ts @@ -9,6 +9,7 @@ import { GPT5_6_LUNA_MODEL, GPT5_6_SOL_MODEL, GPT5_6_TERRA_MODEL, + GPT6_2_SOL_MODEL, Harness, Sequence, SONNET_5_MODEL, @@ -25,6 +26,7 @@ const MODEL_FLAG_VARIANTS: Record = { 'gpt-5-6-luna': GPT5_6_LUNA_MODEL, 'gpt-5-6-terra': GPT5_6_TERRA_MODEL, 'gpt-5-6-sol': GPT5_6_SOL_MODEL, + 'gpt-6-2-sol': GPT6_2_SOL_MODEL, 'sonnet-5': SONNET_5_MODEL, }; diff --git a/src/agent/runner/switchboard/linear-commandments.ts b/src/agent/runner/switchboard/linear-commandments.ts new file mode 100644 index 000000000..cff82c40c --- /dev/null +++ b/src/agent/runner/switchboard/linear-commandments.ts @@ -0,0 +1,23 @@ +/** + * Linear-only commandments. + * + * Only `Sequence.linear` runs mount the Task* todo tools (`TaskCreate`, + * `TaskUpdate`, `TaskGet`, `TaskList`) to drive the TUI progress panel and + * completion guard. Orchestrator tasks report through `complete_task` and + * never mount Task* tools, so none of this guidance may reach an orchestrator + * session. + */ + +export const LINEAR_TASK_LIST_COMMANDMENTS: readonly string[] = [ + 'Use the Task tools to plan and track the whole run so the user always sees where you are. Create the task list once you understand the work — after you load and skim the skill workflow, not before — in a single tool call, in the order you will run them, with one task per stage covering the whole run through to instrumenting events, creating the dashboard, and writing the setup report. Give each an imperative subject AND an `activeForm` (the present-continuous label the panel shows while it runs, e.g. subject "Install SDK" / activeForm "Installing SDK"). Keep the list current: add a task the moment you discover work it is missing.', + + 'Try to keep exactly ONE task `in_progress`. `TaskUpdate` it to `in_progress` right before you start that stage, and to `completed` the instant you finish it — one at a time, never batched at the end. Never spend a whole turn on `TaskUpdate` alone: when transitioning between stages, pair `TaskUpdate` (`completed` for the finished stage and `in_progress` for the next) with the next stage’s first tool call in the same turn. Only mark `completed` when the work is genuinely done; if the build fails, a step is partial, or you hit a blocker, keep it `in_progress` and add a task for the fix.', + + 'After you complete a task, take the next one in order (lowest id first — earlier stages set up later ones), mark it `in_progress`, and continue. Driving the list in order top to bottom is how you finish every stage.', + + 'Each task subject is SHORT — a few words naming only the stage of work: "Analyze project", "Install SDK", "Initialize PostHog", "Instrument events", "Set env vars", "Verify", "Create dashboard". No file or directory names, no framework/router/package names, no specific event names, and no parenthetical "(...)" detail. The detail belongs in the work and the `activeForm`, not the subject.', +]; + +export const LINEAR_COMMANDMENTS: readonly string[] = [ + ...LINEAR_TASK_LIST_COMMANDMENTS, +]; diff --git a/src/agent/runner/switchboard/models.ts b/src/agent/runner/switchboard/models.ts index 48488de29..3a741e4b5 100644 --- a/src/agent/runner/switchboard/models.ts +++ b/src/agent/runner/switchboard/models.ts @@ -6,6 +6,7 @@ import { GPT5_6_SOL_MODEL, GPT5_6_TERRA_MODEL, GPT6_SOL_MODEL, + GPT6_2_SOL_MODEL, HAIKU_TRIAGE_MODEL, Harness, } from '@shared/constants'; @@ -61,6 +62,7 @@ export const MODEL_CAPABILITIES: Record = { [GPT5_6_TERRA_MODEL]: { reasoning: true, thinkingLevel: 'medium' }, [GPT5_6_SOL_MODEL]: { reasoning: true, thinkingLevel: 'medium' }, [GPT6_SOL_MODEL]: { reasoning: true, thinkingLevel: 'medium' }, + [GPT6_2_SOL_MODEL]: { reasoning: true, thinkingLevel: 'medium' }, }; /** @@ -75,6 +77,7 @@ export const MINT_ALLOWED_EFFORTS: Record = { [GPT5_6_SOL_MODEL]: ['medium'], [GPT5_6_TERRA_MODEL]: ['low', 'medium', 'high'], [GPT6_SOL_MODEL]: ['low', 'medium', 'high'], + [GPT6_2_SOL_MODEL]: ['low', 'medium', 'high'], }; // Local model choices; gateway admission also requires allowed models, efforts, and prompt compatibility. diff --git a/src/headless/run.ts b/src/headless/run.ts index ae8688993..15a739e27 100644 --- a/src/headless/run.ts +++ b/src/headless/run.ts @@ -238,6 +238,7 @@ async function main( store.session.debug && errorStack ? `\n\n${errorStack}` : ''; const docsUrl = store.session.frameworkConfig?.metadata.docsUrl ?? + config.docsUrl ?? (typeof config.run === 'object' ? config.run.docsUrl : undefined) ?? POSTHOG_DOCS_URL; // A coded failure is a decision with its own message; anything else is diff --git a/src/programs/ai-observability/__tests__/detect-skill.test.ts b/src/programs/ai-observability/__tests__/detect-skill.test.ts new file mode 100644 index 000000000..0bd0ff956 --- /dev/null +++ b/src/programs/ai-observability/__tests__/detect-skill.test.ts @@ -0,0 +1,333 @@ +import { execFileSync } from 'child_process'; +import { mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import type { PromptContext } from '@agent/types'; +import { detectUnambiguousAioSkill } from '../detect-skill'; +import { config as aioProgramConfig } from '../index'; + +describe('detectUnambiguousAioSkill', () => { + let dir: string; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'aio-detect-')); + }); + + afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + const write = (rel: string, content: string) => { + const full = join(dir, rel); + mkdirSync(join(full, '..'), { recursive: true }); + writeFileSync(full, content); + }; + + it('picks ai-observability-openai-node for a plain OpenAI Node app', () => { + write( + 'package.json', + JSON.stringify({ dependencies: { openai: '^4.77.0' } }), + ); + write('src/index.ts', "import OpenAI from 'openai'; new OpenAI();"); + expect(detectUnambiguousAioSkill(dir)).toBe('ai-observability-openai-node'); + }); + + it('picks framework over single underlying provider (Vercel AI SDK + OpenAI)', () => { + write( + 'package.json', + JSON.stringify({ dependencies: { ai: '^6.0.0', openai: '^4.77.0' } }), + ); + write('src/index.ts', "import { generateText } from 'ai';"); + expect(detectUnambiguousAioSkill(dir)).toBe('ai-observability-vercel-ai'); + }); + + it('returns undefined when a single framework coexists with multiple providers', () => { + write( + 'package.json', + JSON.stringify({ + dependencies: { + ai: '^6.0.0', + openai: '^4.77.0', + '@anthropic-ai/sdk': '^0.30.0', + }, + }), + ); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + }); + + it('returns undefined when a single framework has a gateway baseURL override', () => { + write( + 'package.json', + JSON.stringify({ dependencies: { ai: '^6.0.0', openai: '^4.77.0' } }), + ); + write( + 'src/client.ts', + "const client = new OpenAI({ baseURL: 'https://openrouter.ai/api/v1' });", + ); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + }); + + it('picks ai-observability-openai-python from PEP 621 pyproject.toml', () => { + write( + 'pyproject.toml', + '[project]\ndependencies = ["openai>=1.50.0", "fastapi>=0.115"]\n', + ); + write('main.py', 'from openai import OpenAI\nclient = OpenAI()\n'); + expect(detectUnambiguousAioSkill(dir)).toBe( + 'ai-observability-openai-python', + ); + }); + + it('picks ai-observability-openai-python from [tool.poetry.dependencies]', () => { + write( + 'pyproject.toml', + '[tool.poetry.dependencies]\npython = "^3.11"\nopenai = "^1.50.0"\n', + ); + write('app.py', 'from openai import OpenAI\n'); + expect(detectUnambiguousAioSkill(dir)).toBe( + 'ai-observability-openai-python', + ); + }); + + it('ignores quoted package names outside dependency sections in pyproject.toml', () => { + write( + 'pyproject.toml', + '[project]\nname = "openai"\ndescription = "Integrates with openai and anthropic"\nkeywords = ["openai"]\ndependencies = ["fastapi>=0.115"]\n', + ); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + }); + + it('returns undefined when OpenAI uses a gateway baseURL override', () => { + write( + 'package.json', + JSON.stringify({ dependencies: { openai: '^4.77.0' } }), + ); + write( + 'src/index.ts', + "new OpenAI({ baseURL: 'https://api.groq.com/openai/v1' });", + ); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + }); + + it('returns undefined for pre-1.0 openai pins', () => { + write('requirements.txt', 'openai==0.28.1\n'); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + }); + + it('returns undefined when multiple plain providers exist', () => { + write( + 'package.json', + JSON.stringify({ + dependencies: { openai: '^7.0.0', '@anthropic-ai/sdk': '^1.0.0' }, + }), + ); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + }); + + it('returns undefined for pnpm workspaces, package.json workspaces, and go.mod', () => { + write('pnpm-workspace.yaml', 'packages:\n - apps/*\n'); + write( + 'package.json', + JSON.stringify({ dependencies: { openai: '^7.0.0' } }), + ); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + + rmSync(join(dir, 'pnpm-workspace.yaml')); + write( + 'package.json', + JSON.stringify({ + workspaces: ['apps/*'], + dependencies: { openai: '^7.0.0' }, + }), + ); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + + write( + 'package.json', + JSON.stringify({ dependencies: { openai: '^7.0.0' } }), + ); + write('go.mod', 'module example.com/app\ngo 1.25\n'); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + }); + + it('returns undefined for mixed Node and Python LLM dependencies', () => { + write( + 'package.json', + JSON.stringify({ dependencies: { openai: '^4.77.0' } }), + ); + write('requirements.txt', 'anthropic>=0.40.0\n'); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + }); + + it('falls back to undefined when source file count exceeds maxScanFiles', () => { + write( + 'package.json', + JSON.stringify({ dependencies: { openai: '^4.77.0' } }), + ); + write('src/a.ts', 'export const a = 1;'); + write('src/b.ts', 'export const b = 2;'); + write('src/c.ts', 'export const c = 3;'); + + expect(detectUnambiguousAioSkill(dir, { maxScanFiles: 3 })).toBe( + 'ai-observability-openai-node', + ); + expect(detectUnambiguousAioSkill(dir, { maxScanFiles: 2 })).toBeUndefined(); + }); + + it('does not loop on symlinked directories when scanning for gateway overrides', () => { + write( + 'package.json', + JSON.stringify({ dependencies: { openai: '^4.77.0' } }), + ); + write('src/index.ts', "import OpenAI from 'openai'; new OpenAI();"); + symlinkSync(dir, join(dir, 'src/loop')); + + expect(detectUnambiguousAioSkill(dir)).toBe('ai-observability-openai-node'); + }); + + it('returns undefined when no LLM SDK is declared (manual-capture fallback)', () => { + write('package.json', JSON.stringify({ dependencies: { hono: '^4.0.0' } })); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + }); + + it('maps unscoped mastra package to ai-observability-mastra', () => { + write( + 'package.json', + JSON.stringify({ + dependencies: { mastra: '^0.10.0', openai: '^4.77.0' }, + }), + ); + write('src/index.ts', "import { Mastra } from 'mastra';"); + expect(detectUnambiguousAioSkill(dir)).toBe('ai-observability-mastra'); + }); + + it('returns undefined for Azure OpenAI using the openai SDK', () => { + write('requirements.txt', 'openai>=1.50.0\n'); + write( + 'app.py', + 'from openai import AzureOpenAI\nclient = AzureOpenAI(azure_endpoint="https://my.openai.azure.com")\n', + ); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + }); + + it('detects split LangChain and LlamaIndex integration packages as frameworks', () => { + write('requirements.txt', 'langchain-openai>=0.2.0\nopenai>=1.50.0\n'); + expect(detectUnambiguousAioSkill(dir)).toBe( + 'ai-observability-langchain-python', + ); + + write( + 'requirements.txt', + 'llama-index-core>=0.11.0\nllama-index-llms-openai>=0.2.0\nopenai>=1.50.0\n', + ); + expect(detectUnambiguousAioSkill(dir)).toBe('ai-observability-llamaindex'); + + rmSync(join(dir, 'requirements.txt')); + write( + 'package.json', + JSON.stringify({ + dependencies: { '@langchain/openai': '^0.3.0', openai: '^4.77.0' }, + }), + ); + expect(detectUnambiguousAioSkill(dir)).toBe( + 'ai-observability-langchain-node', + ); + + // Exact match @langchain/langgraph is not double-counted by the @langchain/ prefix. + write( + 'package.json', + JSON.stringify({ + dependencies: { '@langchain/langgraph': '^0.2.0' }, + }), + ); + expect(detectUnambiguousAioSkill(dir)).toBe( + 'ai-observability-langgraph-node', + ); + }); + + it('detects gateway overrides in .env files and .jsx/.mts/.cts sources', () => { + write( + 'package.json', + JSON.stringify({ dependencies: { openai: '^4.77.0' } }), + ); + write('.env.local', 'OPENAI_BASE_URL=https://openrouter.ai/api/v1\n'); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + + rmSync(join(dir, '.env.local')); + write( + 'src/client.mts', + "new OpenAI({ baseURL: 'https://openrouter.ai/api/v1' });", + ); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + + rmSync(join(dir, 'src/client.mts')); + write( + 'src/App.jsx', + "new OpenAI({ baseURL: 'https://api.groq.com/openai/v1' });", + ); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + }); + + it('falls back to undefined when source tree exceeds gateway scan depth', () => { + write( + 'package.json', + JSON.stringify({ dependencies: { openai: '^4.77.0' } }), + ); + write( + 'a/b/c/d/e/f/client.ts', + "new OpenAI({ baseURL: 'https://openrouter.ai/api/v1' });", + ); + expect(detectUnambiguousAioSkill(dir)).toBeUndefined(); + }); + + it('skips symlinked manifests pointing to a FIFO without blocking', () => { + if (process.platform === 'win32') return; + write( + 'package.json', + JSON.stringify({ dependencies: { openai: '^4.77.0' } }), + ); + const fifoPath = join(dir, 'pipe.fifo'); + execFileSync('mkfifo', [fifoPath]); + symlinkSync(fifoPath, join(dir, 'requirements.txt')); + + expect(detectUnambiguousAioSkill(dir)).toBe('ai-observability-openai-node'); + }); + + it('exposes static docsUrl on ai-observability ProgramConfig', () => { + expect(aioProgramConfig.docsUrl).toBe( + 'https://posthog.com/docs/ai-observability', + ); + }); + + it('wires optional pre-install and prompt fallback through ai-observability config.run()', async () => { + write( + 'package.json', + JSON.stringify({ dependencies: { openai: '^4.77.0' } }), + ); + write('src/index.ts', "import OpenAI from 'openai'; new OpenAI();"); + + if (typeof aioProgramConfig.run !== 'function') { + throw new Error('expected ai-observability config.run to be a function'); + } + const runDef = await aioProgramConfig.run( + { installDir: dir } as never, + {} as never, + ); + expect(runDef.skillId).toBe('ai-observability-openai-node'); + expect(runDef.optionalSkill).toBe(true); + + const baseCtx = {} as PromptContext; + const preinstalledPrompt = runDef.customPrompt?.({ + ...baseCtx, + skillPath: '.posthog-wizard-cache/skills/ai-observability-openai-node', + }); + expect(preinstalledPrompt).toContain('at the skill path below'); + expect(preinstalledPrompt).toContain('skip `load_skill_menu`'); + + // If optional skill installation fails at preflight, ctx.skillPath is absent + // and the prompt falls back to runtime load_skill_menu discovery. + const fallbackPrompt = runDef.customPrompt?.(baseCtx); + expect(fallbackPrompt).toContain('Call `load_skill_menu`'); + expect(fallbackPrompt).not.toContain('was pre-installed for you'); + }); +}); diff --git a/src/programs/ai-observability/detect-skill.ts b/src/programs/ai-observability/detect-skill.ts new file mode 100644 index 000000000..a77ca7f58 --- /dev/null +++ b/src/programs/ai-observability/detect-skill.ts @@ -0,0 +1,307 @@ +/** + * Conservative pre-install resolver for `wizard ai-observability`. + * + * Returns a context-mill `ai-observability-*` skill id ONLY when the project's + * root manifest names a single unambiguous framework or provider matching the + * ordered rules in `1-begin.md`, with no monorepo workspace, no Go/mixed-runtime + * ambiguity, no pre-1.0 `openai` pin, and no gateway `baseURL` override. + * + * Returns `undefined` for every ambiguous or custom case so the agent falls back + * to `load_skill_menu` + `install_skill` at runtime. + */ + +import { existsSync } from 'fs'; +import { extname, join } from 'path'; +import { safeReadFile, walkProjectFiles } from '@utils/bounded-fs'; +import { parsePackageJson } from '@utils/package-json'; +import { + parsePyprojectToml, + parseRequirementsTxt, +} from '@services/project-discovery'; + +const NODE_FRAMEWORK_SKILLS: ReadonlyArray = [ + ['@openai/agents', 'ai-observability-openai-agents'], + ['@anthropic-ai/claude-agent-sdk', 'ai-observability-claude-agent-sdk'], + ['@langchain/langgraph', 'ai-observability-langgraph-node'], + ['@langchain/core', 'ai-observability-langchain-node'], + ['langchain', 'ai-observability-langchain-node'], + ['ai', 'ai-observability-vercel-ai'], + ['llamaindex', 'ai-observability-llamaindex'], + ['mastra', 'ai-observability-mastra'], + ['@mastra/core', 'ai-observability-mastra'], + ['@google/adk', 'ai-observability-google-adk'], + ['@instructor-ai/instructor', 'ai-observability-instructor-node'], + ['convex', 'ai-observability-convex'], +]; + +const NODE_FRAMEWORK_PREFIXES: ReadonlyArray = [ + ['@langchain/', 'ai-observability-langchain-node'], + ['@llamaindex/', 'ai-observability-llamaindex'], +]; + +const NODE_PROVIDER_SKILLS: ReadonlyArray = [ + ['openai', 'ai-observability-openai-node'], + ['@anthropic-ai/sdk', 'ai-observability-anthropic-node'], + ['@google/genai', 'ai-observability-google-node'], + ['@google/generative-ai', 'ai-observability-google-node'], + ['@mistralai/mistralai', 'ai-observability-mistral-node'], + ['cohere-ai', 'ai-observability-cohere-node'], + ['portkey-ai', 'ai-observability-portkey-node'], +]; + +const PYTHON_FRAMEWORK_SKILLS: ReadonlyArray = [ + ['openai-agents', 'ai-observability-openai-agents'], + ['claude-agent-sdk', 'ai-observability-claude-agent-sdk'], + ['langgraph', 'ai-observability-langgraph-python'], + ['langchain', 'ai-observability-langchain-python'], + ['langchain-core', 'ai-observability-langchain-python'], + ['llama-index', 'ai-observability-llamaindex'], + ['crewai', 'ai-observability-crewai'], + ['pyautogen', 'ai-observability-autogen'], + ['autogen-agentchat', 'ai-observability-autogen'], + ['dspy', 'ai-observability-dspy'], + ['dspy-ai', 'ai-observability-dspy'], + ['pydantic-ai', 'ai-observability-pydantic-ai'], + ['semantic-kernel', 'ai-observability-semantic-kernel'], + ['smolagents', 'ai-observability-smolagents'], + ['mirascope', 'ai-observability-mirascope'], + ['instructor', 'ai-observability-instructor-python'], + ['litellm', 'ai-observability-litellm'], +]; + +const PYTHON_FRAMEWORK_PREFIXES: ReadonlyArray = [ + ['langchain-', 'ai-observability-langchain-python'], + ['llama-index-', 'ai-observability-llamaindex'], +]; + +const PYTHON_PROVIDER_SKILLS: ReadonlyArray = [ + ['openai', 'ai-observability-openai-python'], + ['anthropic', 'ai-observability-anthropic-python'], + ['google-genai', 'ai-observability-google-python'], + ['google-generativeai', 'ai-observability-google-python'], + ['mistralai', 'ai-observability-mistral-python'], + ['cohere', 'ai-observability-cohere-python'], + ['portkey-ai', 'ai-observability-portkey-python'], +]; + +const GATEWAY_OVERRIDE_RE = + /\b(OPENAI_BASE_URL|baseURL|base_url|AzureOpenAI|azure_endpoint|azureEndpoint|AZURE_OPENAI_ENDPOINT|AZURE_OPENAI_API_KEY)\b|api\.groq\.com|openrouter\.ai|api\.together\.xyz|localhost:11434|openai\.azure\.com/; +const CODE_EXTS = new Set([ + '.ts', + '.tsx', + '.mts', + '.cts', + '.js', + '.jsx', + '.mjs', + '.cjs', + '.py', +]); +export const MAX_GATEWAY_SCAN_FILES = 200; +const GATEWAY_SCAN_DEPTH = 5; + +function isGatewayScanTarget(name: string): boolean { + return ( + name === '.env' || name.startsWith('.env.') || CODE_EXTS.has(extname(name)) + ); +} + +function parsePyDeps(installDir: string): Map { + const deps = new Map(); + const record = (parsed: Record) => { + for (const [name, spec] of Object.entries(parsed)) { + const existing = deps.get(name); + if (existing) { + existing.push(spec); + } else { + deps.set(name, [spec]); + } + } + }; + + const req = safeReadFile(join(installDir, 'requirements.txt')); + if (req) record(parseRequirementsTxt(req)); + + const pyproject = safeReadFile(join(installDir, 'pyproject.toml')); + if (pyproject) record(parsePyprojectToml(pyproject)); + + return deps; +} + +function isPreOneOpenAi(spec: string | undefined): boolean { + if (!spec) return false; + const m = /(\d+)\.\d+/.exec(spec); + return m !== null && Number(m[1]) === 0; +} + +/** + * Returns true if any scanned source or `.env*` file configures a custom + * gateway/Azure/baseURL override OR if the project exceeds the bounded scan + * depth or file cap (conservative fallback). + */ +function mayHaveGatewayOverride( + installDir: string, + maxScanFiles = MAX_GATEWAY_SCAN_FILES, +): boolean { + let scanned = 0; + let found = false; + let capped = false; + + const complete = walkProjectFiles( + installDir, + (name, fullPath) => { + if (found || capped) return; + if (!isGatewayScanTarget(name)) return; + scanned += 1; + if (scanned > maxScanFiles) { + capped = true; + return; + } + const content = safeReadFile(fullPath); + if (content && GATEWAY_OVERRIDE_RE.test(content)) { + found = true; + } + }, + GATEWAY_SCAN_DEPTH, + { followSymlinks: false, incompleteOnDepthLimit: true }, + ); + + return found || capped || !complete; +} + +function uniqueMatches( + depNames: ReadonlySet, + table: ReadonlyArray, + prefixes: ReadonlyArray = [], +): string[] { + const hits = new Set(); + const exactMatched = new Set(); + for (const [pkg, skillId] of table) { + if (depNames.has(pkg)) { + hits.add(skillId); + exactMatched.add(pkg); + } + } + if (prefixes.length > 0) { + for (const dep of depNames) { + if (exactMatched.has(dep)) continue; + for (const [prefix, skillId] of prefixes) { + if (dep.startsWith(prefix)) { + hits.add(skillId); + break; + } + } + } + } + return [...hits]; +} + +/** + * Resolve an unambiguous `ai-observability-*` skill id for `installDir`, or + * `undefined` when runtime menu discovery is safer. + */ +export function detectUnambiguousAioSkill( + installDir: string, + opts?: { maxScanFiles?: number }, +): string | undefined { + // Go projects or workspaces can house LLM calls in sub-packages or require Go >= 1.25 checks. + if ( + existsSync(join(installDir, 'go.mod')) || + existsSync(join(installDir, 'pnpm-workspace.yaml')) + ) { + return undefined; + } + + const pkgText = safeReadFile(join(installDir, 'package.json')); + const pkg = pkgText ? parsePackageJson(pkgText) : null; + if (pkg && 'workspaces' in pkg && pkg.workspaces) return undefined; + + const nodeDeps = new Map(); + if (pkg) { + for (const [k, v] of Object.entries({ + ...pkg.dependencies, + ...pkg.devDependencies, + })) { + if (typeof v === 'string') nodeDeps.set(k, v); + } + } + const pyDeps = parsePyDeps(installDir); + + const nodeSet = new Set(nodeDeps.keys()); + const pySet = new Set(pyDeps.keys()); + + const nodeFrameworks = uniqueMatches( + nodeSet, + NODE_FRAMEWORK_SKILLS, + NODE_FRAMEWORK_PREFIXES, + ); + const nodeProviders = uniqueMatches(nodeSet, NODE_PROVIDER_SKILLS); + const pyFrameworks = uniqueMatches( + pySet, + PYTHON_FRAMEWORK_SKILLS, + PYTHON_FRAMEWORK_PREFIXES, + ); + const pyProviders = uniqueMatches(pySet, PYTHON_PROVIDER_SKILLS); + + const hasNode = nodeFrameworks.length > 0 || nodeProviders.length > 0; + const hasPy = pyFrameworks.length > 0 || pyProviders.length > 0; + + // Mixed Node + Python LLM dependencies stay ambiguous. + if (hasNode && hasPy) return undefined; + if (!hasNode && !hasPy) return undefined; + + const maxScanFiles = opts?.maxScanFiles ?? MAX_GATEWAY_SCAN_FILES; + + if (hasNode) { + if (nodeFrameworks.length > 1) return undefined; + if (nodeFrameworks.length === 1) { + // Framework wins over one underlying provider, but multiple providers, + // pre-1.0 OpenAI, or gateway overrides fall back to runtime discovery. + if ( + nodeProviders.length > 1 || + (nodeProviders.includes('ai-observability-openai-node') && + isPreOneOpenAi(nodeDeps.get('openai'))) || + mayHaveGatewayOverride(installDir, maxScanFiles) + ) { + return undefined; + } + return nodeFrameworks[0]; + } + if (nodeProviders.length !== 1) return undefined; + const only = nodeProviders[0]; + if ( + only === 'ai-observability-openai-node' && + (isPreOneOpenAi(nodeDeps.get('openai')) || + mayHaveGatewayOverride(installDir, maxScanFiles)) + ) { + return undefined; + } + return only; + } + + if (pyFrameworks.length > 1) return undefined; + if (pyFrameworks.length === 1) { + const pyOpenAiSpecs = pyDeps.get('openai') ?? []; + if ( + pyProviders.length > 1 || + (pyProviders.includes('ai-observability-openai-python') && + pyOpenAiSpecs.some((spec) => isPreOneOpenAi(spec))) || + mayHaveGatewayOverride(installDir, maxScanFiles) + ) { + return undefined; + } + return pyFrameworks[0]; + } + if (pyProviders.length !== 1) return undefined; + const onlyPy = pyProviders[0]; + if (onlyPy === 'ai-observability-openai-python') { + const pyOpenAiSpecs = pyDeps.get('openai') ?? []; + if ( + pyOpenAiSpecs.some((spec) => isPreOneOpenAi(spec)) || + mayHaveGatewayOverride(installDir, maxScanFiles) + ) { + return undefined; + } + } + return onlyPy; +} diff --git a/src/programs/ai-observability/index.ts b/src/programs/ai-observability/index.ts index 6521cd915..f7554b318 100644 --- a/src/programs/ai-observability/index.ts +++ b/src/programs/ai-observability/index.ts @@ -1,18 +1,52 @@ -import { Harness, Sequence, GPT5_6_TERRA_MODEL } from '@shared/constants'; +import { Harness, Sequence, GPT6_2_SOL_MODEL } from '@shared/constants'; import type { ProgramConfig } from '@programs/program-contract'; import { headlessOption, regionOption } from '@shared/headless-mode'; +import { detectUnambiguousAioSkill } from './detect-skill'; const AI_OBSERVABILITY_REPORT_FILE = 'posthog-ai-observability-report.md'; +const AI_OBSERVABILITY_DOCS_URL = 'https://posthog.com/docs/ai-observability'; + +function buildAioPrompt(preinstalledSkillId?: string): string { + const skillStep = preinstalledSkillId + ? `Skill \`${preinstalledSkillId}\` was pre-installed for you at the skill path below. Read its \`SKILL.md\` and references directly — skip \`load_skill_menu\` and \`install_skill\` unless inspecting the code shows a different variant (such as a gateway \`baseURL\` override or a framework wrapping the calls) applies.` + : `This flow has no pre-installed skill — you install the right one yourself: + +1. Call \`load_skill_menu\` with \`category: "ai-observability"\`. The menu is + the source of truth: one variant per (LLM provider × language), plus a + \`manual-capture\` variant for projects with no vendor SDK. + +2. Scan the project manifest (\`package.json\`, \`pyproject.toml\`, + \`requirements.txt\`) for a vendor LLM SDK and pick the variant that matches + it — the language follows the manifest (\`package.json\` → Node, Python + tooling → Python). Multiple SDKs (e.g. LangChain wrapping OpenAI) → prefer + the higher abstraction. No vendor SDK → the \`manual-capture\` variant. + Genuinely ambiguous → \`wizard_ask\` with a multi-choice picker. + +3. Call \`install_skill\` with the picked variant id. Then follow that skill's + \`SKILL.md\` and references end-to-end. The skill itself will install + packages, wire OTel, set env vars, and describe verification.`; + + return `Instrument this project's LLM calls with PostHog AI Observability. + +${skillStep} + +Make only additive changes — do not touch existing PostHog init, identify +calls, event capture, or dashboards. Those belong to other skills. Keep every +existing dependency in the project manifest at its current version (never +upgrade an already-installed package or vendor SDK). Instrument only the +production application's LLM calls — leave developer tooling such as +benchmarks, evals, and model comparison scripts untouched. The final report +is written to ./${AI_OBSERVABILITY_REPORT_FILE}.`; +} /** * `wizard ai-observability` — wrap the project's LLM client calls so they emit * `$ai_generation` events into AI Observability. * - * No `run.skillId`: the context-mill `ai-observability` group ships one variant - * per (LLM provider × language) and the wizard does no provider detection — - * the agent loads the menu, matches the manifest's vendor SDK, and installs - * the right variant itself (see `customPrompt`). Stays flat while a single - * "add AIO to a project" flow is the only action. + * Pre-installs the `ai-observability-*` variant when the root manifest has a + * single unambiguous framework or provider (skipping the runtime menu + install + * round-trip); falls back to runtime discovery on ambiguous, multi-provider, + * gateway, or monorepo projects. */ export const config: ProgramConfig = { rankWith: ['decisions'], @@ -20,8 +54,8 @@ export const config: ProgramConfig = { binding: { sequence: Sequence.linear, harness: Harness.pi, - model: GPT5_6_TERRA_MODEL, - thinkingLevel: 'high', + model: GPT6_2_SOL_MODEL, + thinkingLevel: 'low', }, command: 'ai-observability', description: 'Add PostHog AI Observability to your LLM calls', @@ -29,38 +63,19 @@ export const config: ProgramConfig = { sdkFeature: 'aiObservability', cliOptions: { ...headlessOption, ...regionOption }, reportFile: AI_OBSERVABILITY_REPORT_FILE, - run: { - integrationLabel: 'ai-observability', - // No `skillId`: linear.ts skips its pre-install step (see the gate on - // `linear.ts:47`), so the agent must load the menu and install the right - // variant itself. The prompt below tells it how. - customPrompt: - () => `Instrument this project's LLM calls with PostHog AI Observability. - -This flow has no pre-installed skill — you install the right one yourself: - -1. Call \`load_skill_menu\` with \`category: "ai-observability"\`. The menu is - the source of truth: one variant per (LLM provider × language), plus a - \`manual-capture\` variant for projects with no vendor SDK. - -2. Scan the project manifest (\`package.json\`, \`pyproject.toml\`, - \`requirements.txt\`) for a vendor LLM SDK and pick the variant that matches - it — the language follows the manifest (\`package.json\` → Node, Python - tooling → Python). Multiple SDKs (e.g. LangChain wrapping OpenAI) → prefer - the higher abstraction. No vendor SDK → the \`manual-capture\` variant. - Genuinely ambiguous → \`wizard_ask\` with a multi-choice picker. - -3. Call \`install_skill\` with the picked variant id. Then follow that skill's - \`SKILL.md\` and references end-to-end. The skill itself will install - packages, wire OTel, set env vars, and describe verification. - -Make only additive changes — do not touch existing PostHog init, identify -calls, event capture, or dashboards. Those belong to other skills. The -final report is written to ./${AI_OBSERVABILITY_REPORT_FILE}.`, - successMessage: `AI Observability configured! View the report at ./${AI_OBSERVABILITY_REPORT_FILE}`, - reportFile: AI_OBSERVABILITY_REPORT_FILE, - docsUrl: 'https://posthog.com/docs/ai-observability', - spinnerMessage: 'Setting up AI Observability...', - estimatedDurationMinutes: 5, + docsUrl: AI_OBSERVABILITY_DOCS_URL, + run: (session) => { + const skillId = detectUnambiguousAioSkill(session.installDir); + return Promise.resolve({ + integrationLabel: 'ai-observability', + ...(skillId && { skillId, optionalSkill: true }), + customPrompt: (ctx) => + buildAioPrompt(ctx.skillPath ? skillId : undefined), + successMessage: `AI Observability configured! View the report at ./${AI_OBSERVABILITY_REPORT_FILE}`, + reportFile: AI_OBSERVABILITY_REPORT_FILE, + docsUrl: AI_OBSERVABILITY_DOCS_URL, + spinnerMessage: 'Setting up AI Observability...', + estimatedDurationMinutes: 5, + }); }, }; diff --git a/src/programs/ai-observability/test/e2e.json b/src/programs/ai-observability/test/e2e.json index ad2affef8..0facf7ac3 100644 --- a/src/programs/ai-observability/test/e2e.json +++ b/src/programs/ai-observability/test/e2e.json @@ -11,7 +11,7 @@ "variations": [ { "name": "default", - "summary": "linear / pi / terra-high — parity with main" + "summary": "linear / pi / gpt-6.2-sol-low" } ], "path": [ diff --git a/src/programs/posthog-integration/agent/ai-observability.md b/src/programs/posthog-integration/agent/ai-observability.md index 72ccc278f..d72c5363d 100644 --- a/src/programs/posthog-integration/agent/ai-observability.md +++ b/src/programs/posthog-integration/agent/ai-observability.md @@ -2,8 +2,8 @@ type: ai-observability flow: integration-v2 label: Add AI Observability -model_pi: openai/gpt-5.6-terra -effort_pi: high +model_pi: openai/gpt-6.2-sol +effort_pi: low model_sdk: claude-sonnet-5 effort_sdk: high skills: [] diff --git a/src/programs/posthog-integration/agent/capture.md b/src/programs/posthog-integration/agent/capture.md index 25f336369..0075fa540 100644 --- a/src/programs/posthog-integration/agent/capture.md +++ b/src/programs/posthog-integration/agent/capture.md @@ -2,8 +2,8 @@ type: capture flow: integration-v2 label: Capture events -model_pi: openai/gpt-5.6-terra -effort_pi: medium +model_pi: openai/gpt-6.2-sol +effort_pi: low model_sdk: claude-sonnet-5 effort_sdk: high skills: [integration-capture, posthog-best-practices] diff --git a/src/programs/posthog-integration/agent/dashboard.md b/src/programs/posthog-integration/agent/dashboard.md index eafb1226b..d1207c1fb 100644 --- a/src/programs/posthog-integration/agent/dashboard.md +++ b/src/programs/posthog-integration/agent/dashboard.md @@ -2,7 +2,7 @@ type: dashboard flow: integration-v2 label: Create a starter dashboard -model_pi: openai/gpt-5.6-terra +model_pi: openai/gpt-6.2-sol effort_pi: low model_sdk: claude-sonnet-5 effort_sdk: high diff --git a/src/programs/posthog-integration/agent/error-tracking.md b/src/programs/posthog-integration/agent/error-tracking.md index 348634f65..9f525eb2a 100644 --- a/src/programs/posthog-integration/agent/error-tracking.md +++ b/src/programs/posthog-integration/agent/error-tracking.md @@ -2,7 +2,7 @@ type: error-tracking flow: integration-v2 label: Add error tracking -model_pi: openai/gpt-5.6-terra +model_pi: openai/gpt-6.2-sol effort_pi: low model_sdk: claude-sonnet-5 effort_sdk: high diff --git a/src/programs/posthog-integration/agent/identify.md b/src/programs/posthog-integration/agent/identify.md index 42a4d8cb0..2bc3986c5 100644 --- a/src/programs/posthog-integration/agent/identify.md +++ b/src/programs/posthog-integration/agent/identify.md @@ -2,8 +2,8 @@ type: identify flow: integration-v2 label: Wire user identification -model_pi: openai/gpt-5.6-terra -effort_pi: medium +model_pi: openai/gpt-6.2-sol +effort_pi: low model_sdk: claude-sonnet-5 effort_sdk: high skills: [integration-identify, posthog-best-practices] diff --git a/src/programs/posthog-integration/agent/init.md b/src/programs/posthog-integration/agent/init.md index 52cac00f2..caa35e214 100644 --- a/src/programs/posthog-integration/agent/init.md +++ b/src/programs/posthog-integration/agent/init.md @@ -2,7 +2,7 @@ type: init flow: integration-v2 label: Set up PostHog initialization -model_pi: openai/gpt-5.6-terra +model_pi: openai/gpt-6.2-sol effort_pi: low model_sdk: claude-sonnet-5 effort_sdk: medium diff --git a/src/programs/posthog-integration/agent/install.md b/src/programs/posthog-integration/agent/install.md index 2356182dd..e8681daba 100644 --- a/src/programs/posthog-integration/agent/install.md +++ b/src/programs/posthog-integration/agent/install.md @@ -2,7 +2,7 @@ type: install flow: integration-v2 label: Add the PostHog SDK to the manifest -model_pi: openai/gpt-5.6-terra +model_pi: openai/gpt-6.2-sol effort_pi: low model_sdk: claude-haiku-4-5 skills: [integration-install] diff --git a/src/programs/posthog-integration/agent/logs.md b/src/programs/posthog-integration/agent/logs.md index ec768eaed..f44f49e4b 100644 --- a/src/programs/posthog-integration/agent/logs.md +++ b/src/programs/posthog-integration/agent/logs.md @@ -2,8 +2,8 @@ type: logs flow: integration-v2 label: Add log capture -model_pi: openai/gpt-5.6-terra -effort_pi: medium +model_pi: openai/gpt-6.2-sol +effort_pi: low model_sdk: claude-sonnet-5 effort_sdk: high skills: [] diff --git a/src/programs/posthog-integration/agent/mcp-analytics.md b/src/programs/posthog-integration/agent/mcp-analytics.md index dd4dd34b7..baa94fbd6 100644 --- a/src/programs/posthog-integration/agent/mcp-analytics.md +++ b/src/programs/posthog-integration/agent/mcp-analytics.md @@ -2,8 +2,8 @@ type: mcp-analytics flow: integration-v2 label: Add MCP analytics -model_pi: openai/gpt-5.6-terra -effort_pi: medium +model_pi: openai/gpt-6.2-sol +effort_pi: low model_sdk: claude-sonnet-5 effort_sdk: high skills: [] diff --git a/src/programs/posthog-integration/agent/report.md b/src/programs/posthog-integration/agent/report.md index 4b23013a6..bc5c8e590 100644 --- a/src/programs/posthog-integration/agent/report.md +++ b/src/programs/posthog-integration/agent/report.md @@ -3,7 +3,7 @@ type: report flow: integration-v2 label: Write the setup report sink: true -model_pi: openai/gpt-5.6-terra +model_pi: openai/gpt-6.2-sol effort_pi: low model_sdk: claude-sonnet-5 effort_sdk: high diff --git a/src/programs/posthog-integration/agent/review.md b/src/programs/posthog-integration/agent/review.md index d6d67804e..5e5775a2c 100644 --- a/src/programs/posthog-integration/agent/review.md +++ b/src/programs/posthog-integration/agent/review.md @@ -4,8 +4,8 @@ flow: integration-v2 label: Verify and review the integration timeoutSeconds: 600 onTimeout: continue -model_pi: openai/gpt-5.6-sol -effort_pi: medium +model_pi: openai/gpt-6.2-sol +effort_pi: low model_sdk: claude-sonnet-5 effort_sdk: high skills: [posthog-best-practices, integration-build] diff --git a/src/programs/posthog-integration/agent/warehouse.md b/src/programs/posthog-integration/agent/warehouse.md index 54768bfe1..c52d463e3 100644 --- a/src/programs/posthog-integration/agent/warehouse.md +++ b/src/programs/posthog-integration/agent/warehouse.md @@ -3,8 +3,8 @@ type: warehouse flow: integration-v2 label: Connect your data sources runnerSeeded: true -model_pi: openai/gpt-5.6-terra -effort_pi: medium +model_pi: openai/gpt-6.2-sol +effort_pi: low model_sdk: claude-sonnet-5 effort_sdk: medium skills: [integration-warehouse, integration-mcp] diff --git a/src/programs/posthog-integration/index.ts b/src/programs/posthog-integration/index.ts index b0d9c8fb2..12bd2a0ee 100644 --- a/src/programs/posthog-integration/index.ts +++ b/src/programs/posthog-integration/index.ts @@ -35,7 +35,7 @@ import type { import { FRAMEWORK_REGISTRY } from '@services/frameworks'; import { abortNoFrameworkDetected } from '../shared/abort-no-framework'; import { - GPT5_6_SOL_MODEL, + GPT6_2_SOL_MODEL, Harness, SETUP_REPORT_FILE, Sequence, @@ -324,8 +324,8 @@ export const config: ProgramConfig = { binding: { sequence: Sequence.orchestrator, harness: Harness.pi, - model: GPT5_6_SOL_MODEL, - thinkingLevel: 'medium', + model: GPT6_2_SOL_MODEL, + thinkingLevel: 'low', }, agentFlow: 'integration-v2', agentPrompts: () => import('./agent-prompts').then((m) => m.AGENT_PROMPTS), diff --git a/src/programs/program-contract/program-step.ts b/src/programs/program-contract/program-step.ts index d8e8bcc20..19bab5e2f 100644 --- a/src/programs/program-contract/program-step.ts +++ b/src/programs/program-contract/program-step.ts @@ -283,6 +283,12 @@ export interface ProgramConfig { * read it synchronously without resolving a deferred `run` function. */ reportFile?: string; + /** + * Documentation URL for manual setup fallback. Mirrors `run.docsUrl` at the + * top level so error screens, headless aborts, and spellbooks can read it + * synchronously when `run` is a function. + */ + docsUrl?: string; /** * Agent-authored event-plan artifact to mirror into the wizard session. * Relative to `session.installDir`. Programs that do not produce an event diff --git a/src/programs/program-runner/__tests__/program-registry.test.ts b/src/programs/program-runner/__tests__/program-registry.test.ts index 65a4f2d67..9af767c24 100644 --- a/src/programs/program-runner/__tests__/program-registry.test.ts +++ b/src/programs/program-runner/__tests__/program-registry.test.ts @@ -15,7 +15,7 @@ import { DEFAULT_AGENT_MODEL, GPT5_6_SOL_MODEL, GPT6_SOL_MODEL, - GPT5_6_TERRA_MODEL, + GPT6_2_SOL_MODEL, Harness, Sequence, } from '@shared/constants'; @@ -66,8 +66,10 @@ describe('program bindings', () => { ); expect(routes).toEqual({ 'posthog-integration': { - ...linearOnSol, sequence: Sequence.orchestrator, + harness: Harness.pi, + model: GPT6_2_SOL_MODEL, + thinkingLevel: 'low', }, 'mcp-analytics': linearOnSol, 'replay-vision': { @@ -78,8 +80,8 @@ describe('program bindings', () => { 'ai-observability': { sequence: Sequence.linear, harness: Harness.pi, - model: GPT5_6_TERRA_MODEL, - thinkingLevel: 'high', + model: GPT6_2_SOL_MODEL, + thinkingLevel: 'low', }, metrics: orchestratorOnPi, audit: linearOnSol, diff --git a/src/programs/program-runner/detect-program.ts b/src/programs/program-runner/detect-program.ts index 4667cb51f..35e7cadf1 100644 --- a/src/programs/program-runner/detect-program.ts +++ b/src/programs/program-runner/detect-program.ts @@ -155,6 +155,7 @@ export function detectionFailure( if (!detectError) return null; const code = detectErrorCode(detectError.kind); const docsUrl = + config.docsUrl ?? (typeof config.run === 'object' ? config.run.docsUrl : undefined) ?? POSTHOG_DOCS_URL; return { diff --git a/src/services/project-discovery/index.ts b/src/services/project-discovery/index.ts index 068df4136..1d84baed2 100644 --- a/src/services/project-discovery/index.ts +++ b/src/services/project-discovery/index.ts @@ -69,3 +69,4 @@ export { walkRepo, type RepoFiles, } from './walk'; +export { parsePyprojectToml, parseRequirementsTxt } from './manifests/pypi'; diff --git a/src/shared/constants.ts b/src/shared/constants.ts index d50d410ef..3ee6ef9a9 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -30,6 +30,7 @@ export const GPT5_6_LUNA_MODEL = 'openai/gpt-5.6-luna'; export const GPT5_6_TERRA_MODEL = 'openai/gpt-5.6-terra'; export const GPT5_6_SOL_MODEL = 'openai/gpt-5.6-sol'; export const GPT6_SOL_MODEL = 'openai/gpt-6-sol'; +export const GPT6_2_SOL_MODEL = 'openai/gpt-6.2-sol'; // ── Agent runner routing axes ──────────────────────────────────────── diff --git a/src/shared/utils/__tests__/bounded-fs-walk.test.ts b/src/shared/utils/__tests__/bounded-fs-walk.test.ts index e6fcfaee7..8ea8d37c8 100644 --- a/src/shared/utils/__tests__/bounded-fs-walk.test.ts +++ b/src/shared/utils/__tests__/bounded-fs-walk.test.ts @@ -112,6 +112,19 @@ describe('walkProjectFiles', () => { expect(walkProjectFiles(root, vi.fn())).toBe(true); }); + it('marks a depth-truncated walk incomplete only when incompleteOnDepthLimit is set', () => { + fs.mkdirSync(path.join(root, 'a', 'b', 'c'), { recursive: true }); + fs.writeFileSync(path.join(root, 'a', 'b', 'c', 'deep.ts'), ''); + + expect(walkProjectFiles(root, vi.fn(), 1)).toBe(true); + expect( + walkProjectFiles(root, vi.fn(), 1, { incompleteOnDepthLimit: true }), + ).toBe(false); + expect( + walkProjectFiles(root, vi.fn(), 3, { incompleteOnDepthLimit: true }), + ).toBe(true); + }); + it('reports a walk that skipped a directory it could not open as partial', () => { const opendirSync = fs.opendirSync; vi.spyOn(fs, 'opendirSync').mockImplementation((dir, options) => { diff --git a/src/shared/utils/bounded-fs.ts b/src/shared/utils/bounded-fs.ts index 7a7dcd029..350b4fd72 100644 --- a/src/shared/utils/bounded-fs.ts +++ b/src/shared/utils/bounded-fs.ts @@ -183,6 +183,11 @@ export interface WalkOptions { followSymlinks?: boolean; /** A directory the walk does not enter, by full path. */ skipDir?: (fullPath: string) => boolean; + /** + * Mark the walk incomplete (return `false`) when a non-ignored subdirectory + * is pruned because it exceeds `maxDepth`. Defaults to false. + */ + incompleteOnDepthLimit?: boolean; } /** @@ -201,7 +206,11 @@ export function walkProjectFiles( rootDir: string, onFile: (name: string, fullPath: string) => void, maxDepth = 3, - { followSymlinks = true, skipDir }: WalkOptions = {}, + { + followSymlinks = true, + skipDir, + incompleteOnDepthLimit = false, + }: WalkOptions = {}, ): boolean { const visited = new Set(); let filesSeen = 0; @@ -273,7 +282,11 @@ export function walkProjectFiles( if (isDir) { if (entry.name.startsWith('.')) continue; // skip hidden directories if (skipDir?.(fullPath)) continue; - if (depth < maxDepth) stack.push({ dir: fullPath, depth: depth + 1 }); + if (depth < maxDepth) { + stack.push({ dir: fullPath, depth: depth + 1 }); + } else if (incompleteOnDepthLimit) { + complete = false; + } } else if (isFile) { filesSeen += 1; onFile(entry.name, fullPath); @@ -299,7 +312,8 @@ export function readProjectFile( maxBytes = MAX_PROJECT_FILE_BYTES, ): string | null { try { - if (fs.statSync(filePath).size > maxBytes) return null; + const stat = fs.statSync(filePath); + if (!stat.isFile() || stat.size > maxBytes) return null; return fs.readFileSync(filePath, 'utf-8'); } catch { return null; diff --git a/src/tui/services/__tests__/wizard-spellbook.test.ts b/src/tui/services/__tests__/wizard-spellbook.test.ts index deefcffa3..da0c98a04 100644 --- a/src/tui/services/__tests__/wizard-spellbook.test.ts +++ b/src/tui/services/__tests__/wizard-spellbook.test.ts @@ -158,4 +158,29 @@ describe('writeWizardSpellbook', () => { fs.stat(path.join(path.dirname(rejected.path), 'skills', skill.id)), ).rejects.toThrow(); }); + + it('uses top-level program.docsUrl when program.run is a function', async () => { + vi.mocked(fetchSkillMenu).mockResolvedValue(null); + const dynamicProgram: ProgramConfig = { + id: 'ai-observability', + description: 'Add PostHog AI Observability', + docsUrl: 'https://posthog.com/docs/ai-observability', + run: () => + Promise.resolve({ + integrationLabel: 'ai-observability', + successMessage: 'done', + reportFile: 'posthog-ai-observability-report.md', + docsUrl: 'https://posthog.com/docs/ai-observability', + spinnerMessage: 'working', + estimatedDurationMinutes: 5, + }), + }; + + const result = await writeWizardSpellbook( + buildSession({ installDir }), + dynamicProgram, + ); + const content = await fs.readFile(result.path, 'utf8'); + expect(content).toContain('https://posthog.com/docs/ai-observability'); + }); }); diff --git a/src/tui/services/wizard-spellbook.ts b/src/tui/services/wizard-spellbook.ts index e1dbb523c..33ff73764 100644 --- a/src/tui/services/wizard-spellbook.ts +++ b/src/tui/services/wizard-spellbook.ts @@ -72,7 +72,8 @@ function spellbookText( ): string { const framework = session.frameworkConfig?.metadata; const runDocs = - typeof program.run === 'object' ? program.run.docsUrl : undefined; + program.docsUrl ?? + (typeof program.run === 'object' ? program.run.docsUrl : undefined); const docs = [ ...new Set([framework?.docsUrl, runDocs, POSTHOG_DOCS_URL]), ].filter((url): url is string => Boolean(url));