Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
6fca57b
feat(transactional-email): add a command that sets up the first email…
Silthus Oct 22, 2026
8e6f184
fix(transactional-email): follow main's program contract and skill cl…
Silthus Oct 23, 2026
6654b67
feat(analytics): say which provider a migrate-email run moves from
Silthus Oct 31, 2026
1c077af
fix(transactional-email): link the transactional emails docs
Silthus Oct 31, 2026
a90f038
fix(analytics): drop migrated_from when a run moves on from an email …
Silthus Nov 1, 2026
6da6fc9
fix(transactional-email): link the docs from both abort outros
Silthus Nov 1, 2026
df5cfbd
refactor(transactional-email): spell out the program's binding
Silthus Nov 1, 2026
5ceda4a
fix(transactional-email): run the sending-transactional-emails skill
Silthus Nov 3, 2026
cc90dfc
feat(transactional-email): keep the email in code by default
Silthus Nov 4, 2026
f95c37b
refactor(transactional-email): leave the code-or-template choice to t…
Silthus Nov 4, 2026
8cb8ad7
docs(transactional-email): name every backend's SDK in the README
Silthus Nov 5, 2026
04b7915
Merge remote-tracking branch 'origin/main' into feat/transactional-em…
Silthus Nov 14, 2026
287887f
fix(agent): end a linear Pi run on a program's [ABORT]
Silthus Nov 14, 2026
b09af2e
test(transactional-email): assert migrated_from on the delivered event
Silthus Nov 14, 2026
226aad6
fix(pi): end a run only on a line that starts with [ABORT]
Silthus Nov 14, 2026
904543a
fix(pi): read an [ABORT] reason from the line after a bare marker
Silthus Nov 14, 2026
60445c7
fix(tui): show an agent's [ABORT] on its own outro, not the busy handoff
Silthus Nov 16, 2026
7c9de7e
test(pi): assert the abort tests' outcomes, not their prompt counts
Silthus Nov 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,22 @@ npx @posthog/wizard@latest revenue-analytics
Requires PostHog and Stripe SDKs already installed. Supports `--ci` with the
same flags as the main wizard.

### Transactional email

Send your first transactional email from your server code, such as a welcome
email after signup:

```bash
npx @posthog/wizard@latest transactional-email
```

The setup agent checks for a verified sender, writes the email in your code by
default (or as a PostHog template, if you pick that so people who don't edit
code can change the copy), asks for a project secret API key and writes it to
your env file, and adds the send with PostHog's SDK for your backend's
language, or the HTTP API.
Transactional emails are in beta and must be enabled for your project.

### Data Warehouse

Detect data sources your project already uses (Postgres, MySQL, MongoDB,
Expand Down
75 changes: 75 additions & 0 deletions src/agent/runner/harness/pi/__tests__/structured-run.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -613,6 +613,81 @@ describe.each(['linear', 'task'] as const)('%s setup signals', (mode) => {
});
});

describe("a program's [ABORT] on the linear Pi run", () => {
const withAbortCases = () => {
const inputs = runInputs(vi.fn(), null);
inputs.config.run.abortCases = [
{
match: /^no server code found$/i,
message: 'No server code found',
body: 'Run this command again from the project that runs your server.',
},
];
return inputs;
};

it('ends the run with the reason, with a task still open', async () => {
state.hang = true;
state.tasks.set('1', { status: 'in_progress' });
state.text = 'Checked the project.\n[ABORT] no server code found';

await expect(piBackend.run(withAbortCases())).resolves.toEqual({
kind: 'abort',
classification: AgentErrorType.ABORT,
message: 'no server code found',
});
});

it('reads the reason from its own text block', async () => {
state.preamble = ['Checked the project.\n[ABORT] no server code found'];
state.text = "I'll stop here.";

await expect(piBackend.run(withAbortCases())).resolves.toEqual({
kind: 'abort',
classification: AgentErrorType.ABORT,
message: 'no server code found',
});
});

it('reads a reason on the line after a bare [ABORT]', async () => {
state.text = 'Checked the project.\n[ABORT]\nno server code found';

await expect(piBackend.run(withAbortCases())).resolves.toEqual({
kind: 'abort',
classification: AgentErrorType.ABORT,
message: 'no server code found',
});
});

it('ignores an [ABORT] the reply only mentions mid-line', async () => {
state.text =
"If there's no server code I'll stop with `[ABORT] no server code found`.\nWrote the first send.";

await expect(piBackend.run(withAbortCases())).resolves.toEqual({
kind: 'success',
});
});

it('runs a program without abort cases on to its open tasks', async () => {
state.tasks.set('1', { status: 'in_progress' });
state.text = 'Checked the project.\n[ABORT] no server code found';

await expect(piBackend.run(runInputs(vi.fn(), null))).resolves.toEqual({
kind: 'failure',
classification: AgentErrorType.INCOMPLETE_TASKS,
});
});

it('ignores an [ABORT] line in the remark reply', async () => {
state.text = 'Wrote the first send.';
state.remark = '[ABORT] no server code found';

await expect(piBackend.run(withAbortCases())).resolves.toEqual({
kind: 'success',
});
});
});

describe('a task turn after complete_task', () => {
const REFUSAL = '[posthog:abort] Request is out of scope';
const runOrchestrated = (orchestrator: {
Expand Down
23 changes: 19 additions & 4 deletions src/agent/runner/harness/pi/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { AgentErrorType } from '../../../agent-interface';
import {
AgentSignals,
REMARK_INSTRUCTION,
abortReason as programAbortReason,
policyAbortReason,
} from '../../../signals';
import { AgentOutputSignals } from '../../../output-signals';
Expand Down Expand Up @@ -360,11 +361,25 @@ export const piBackend: AgentHarness = {
let timedOut = false;
let timeoutAbort: Promise<void> | undefined;
let abortReason: string | undefined;
let policyAborted = false;
let remarkTurn = false;
// The gateway's refusal marker ends the run from a work turn, never the remark.
const policyAbort = (reply: string) => {
if (remarkTurn) return;
abortReason ??= policyAbortReason(reply);
if (remarkTurn || abortReason) return;
abortReason = policyAbortReason(reply);
policyAborted = abortReason !== undefined;
if (abortReason) cancellation?.abort();
};
// So does a line that starts with [ABORT], for a program that has abort cases.
// A reply that only mentions the marker mid-line keeps the run going.
const abortOnReply = (reply: string) => {
policyAbort(reply);
if (remarkTurn || abortReason || !config.abortCases?.length) return;
const lines = reply.split(/\r?\n/);
const at = lines.findIndex((text) => /^[\s`*_>]*\[ABORT\]/.test(text));
// The reason may sit on the line after a bare marker.
abortReason =
at < 0 ? undefined : programAbortReason(lines.slice(at).join('\n'));
if (abortReason) cancellation?.abort();
};
// Read by the catch path; undefined until setup creates the extension.
Expand Down Expand Up @@ -687,7 +702,7 @@ export const piBackend: AgentHarness = {
turns.noteAssistantTurn(event.message);
const blocks = textBlocks(event.message);
const assistant = blocks.join('').trim();
policyAbort(assistant);
abortOnReply(blocks.join('\n'));
// A schema-bound answer is the turn's last block, not the joined text.
lastAssistantText = (blocks.at(-1) ?? '').trim();
if (structured) {
Expand Down Expand Up @@ -859,7 +874,7 @@ export const piBackend: AgentHarness = {
);
captureAborted(
terminal.classification,
abortReason ? 'gateway_policy' : undefined,
policyAborted ? 'gateway_policy' : undefined,
);
if (terminal.status === 401) {
return {
Expand Down
8 changes: 8 additions & 0 deletions src/cli/commands/transactional-email.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { config as transactionalEmailConfig } from '@programs/transactional-email';

import type { Command } from './command';
import { nativeCommandFactory } from './factories/native-command-factory';

export const transactionalEmailCommand: Command = nativeCommandFactory(
transactionalEmailConfig,
);
2 changes: 2 additions & 0 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { slackCommand } from './commands/slack';
import { uploadSourcemapsCommand } from './commands/upload-sourcemaps';
import { errorTrackingCommand } from './commands/error-tracking';
import { featureFlagsCommand } from './commands/feature-flags';
import { transactionalEmailCommand } from './commands/transactional-email';
import { skillCommand } from './commands/skill';
import { supportCommand } from './commands/support';

Expand All @@ -39,6 +40,7 @@ export function runCli(): void {
.use(uploadSourcemapsCommand)
.use(errorTrackingCommand)
.use(featureFlagsCommand)
.use(transactionalEmailCommand)
.use(supportCommand)
.use(skillCommand)
.init();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ describe('program bindings', () => {
'error-tracking': orchestratorOnPi,
'feature-flags': orchestratorOnPi,
'agent-skill': linearOnSol,
'transactional-email': linearOnSol,
support: orchestratorOnPi,
});
});
Expand Down
3 changes: 3 additions & 0 deletions src/programs/program-runner/program-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { config as sourceMaps } from '@programs/error-tracking-upload-source-map
import { config as errorTracking } from '@programs/error-tracking';
import { config as featureFlags } from '@programs/feature-flags';
import { config as agentSkill } from '@programs/agent-skill';
import { config as transactionalEmail } from '@programs/transactional-email';
import { config as support } from '@programs/support';

const [audit, eventsAudit] = auditPrograms;
Expand All @@ -48,6 +49,7 @@ export const PROGRAM_REGISTRY = [
replayVision,
aiObservability,
metrics,
transactionalEmail,
support,
] as const satisfies readonly ProgramConfig[];

Expand All @@ -74,6 +76,7 @@ export const Program = {
ReplayVision: replayVision.id,
AiObservability: aiObservability.id,
Metrics: metrics.id,
TransactionalEmail: transactionalEmail.id,
Support: support.id,
} as const;

Expand Down
60 changes: 60 additions & 0 deletions src/programs/transactional-email/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { GPT5_6_SOL_MODEL, Harness, Sequence } from '@shared/constants';
import type { AbortCase } from '@agent/types';
import { createSkillProgram } from '../shared/skill-program';
import type { ProgramConfig } from '@programs/program-contract';

const SKILL_ID = 'sending-transactional-emails';
const REPORT_FILE = 'posthog-transactional-email-report.md';
const DOCS_URL = 'https://posthog.com/docs/workflows/transactional-emails';

const TRANSACTIONAL_EMAIL_ABORT_CASES: AbortCase[] = [
{
match: /^transactional email api not enabled$/i,
message: "Transactional email isn't enabled for this project",
body:
'The transactional email API is in beta, and PostHog turns it on per ' +
'project. Ask PostHog in the app to enable it for your project, then ' +
'run this command again.',
docsUrl: DOCS_URL,
},
{
match: /^no server code found$/i,
message: 'No server code found',
body:
'A transactional email is sent from server code, because the send needs ' +
"a secret key. The setup agent didn't find server code in this project. " +
'Run this command again from the project that runs your server.',
docsUrl: DOCS_URL,
},
];

export const config: ProgramConfig = {
...createSkillProgram({
skillId: SKILL_ID,
command: 'transactional-email',
id: 'transactional-email',
description: 'Send your first transactional email from code',
integrationLabel: 'transactional-email',
customPrompt:
`Set up transactional email in this project with the \`${SKILL_ID}\` ` +
'skill: a verified sender, the email, the project secret API key, and ' +
Comment thread
Silthus marked this conversation as resolved.
Resolved
'the first send. Follow the skill\'s "Inside the PostHog ' +
`Wizard" section. Write the final report to ./${REPORT_FILE}: the email ` +
'the app sends, where its content lives and its template key or ID, ' +
'the files you changed, the ' +
'environment variables every deployment needs, and what the person ' +
'still has to do.',
successMessage: `Transactional email is set up. View the report at ./${REPORT_FILE}`,
reportFile: REPORT_FILE,
docsUrl: DOCS_URL,
spinnerMessage: 'Setting up transactional email...',
estimatedDurationMinutes: 5,
abortCases: TRANSACTIONAL_EMAIL_ABORT_CASES,
}),
binding: {
sequence: Sequence.linear,
harness: Harness.pi,
Comment thread
Silthus marked this conversation as resolved.
Resolved
model: GPT5_6_SOL_MODEL,
thinkingLevel: 'medium',
},
};
4 changes: 4 additions & 0 deletions src/programs/transactional-email/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "../../../tsconfig.no-tui.json",
"references": [{ "path": "../tsconfig.core.json" }]
}
2 changes: 1 addition & 1 deletion src/programs/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
{ "path": "mcp-analytics" }, { "path": "metrics" }, { "path": "migration" },
{ "path": "posthog-integration" }, { "path": "replay-vision" },
{ "path": "revenue-analytics" }, { "path": "self-driving" }, { "path": "support" },
{ "path": "warehouse-destination" },
{ "path": "transactional-email" }, { "path": "warehouse-destination" },
{ "path": "warehouse-source" }, { "path": "web-analytics-doctor" }
]
}
54 changes: 54 additions & 0 deletions src/services/session/__tests__/migrated-from.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
type SentEvent = { event: string; properties?: Record<string, unknown> };

const sent = vi.hoisted(() => [] as SentEvent[]);

vi.mock('posthog-node', () => ({
PostHog: class {
capture(event: SentEvent) {
sent.push(event);
}
shutdown() {
return Promise.resolve();
}
},
}));

async function finishedEventAfter(...skillIds: (string | null)[]) {
vi.resetModules();
sent.length = 0;
const { analytics } = await import('@utils/analytics');
const { SessionStore } = await import('../session-store');
const { buildSession } = await import('../wizard-session');
const store = new SessionStore(buildSession({}));
for (const skillId of skillIds) store.setSkillId(skillId);
await analytics.shutdown('success');
return sent.find((e) => e.event === 'setup wizard finished')?.properties;
}

describe('migrated_from on setup wizard finished', () => {
it('names the provider an email migration skill moves from', async () => {
const finished = await finishedEventAfter('migrate-email-resend');

expect(finished).toMatchObject({ migrated_from: 'resend' });
});

it('is absent from a run of any other skill', async () => {
const finished = await finishedEventAfter('migrate-statsig');

expect(finished).toBeDefined();
expect(finished?.migrated_from).toBeUndefined();
});

it.each([['migrate-statsig'], [null]])(
'is absent when the run moves on from an email migration to %s',
async (nextSkillId) => {
const finished = await finishedEventAfter(
'migrate-email-resend',
nextSkillId,
);

expect(finished).toBeDefined();
expect(finished?.migrated_from).toBeUndefined();
},
);
});
10 changes: 10 additions & 0 deletions src/services/session/session-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,10 @@ export class SessionStore {

setSkillId(skillId: string | null): void {
this.set('skillId', skillId);
analytics.setTag(
'migrated_from',
emailProviderMigratedFrom(skillId) ?? undefined,
);
}

setUnsupportedVersion(
Expand Down Expand Up @@ -638,3 +642,9 @@ export function applyAgentProgress(
}
}
}

const EMAIL_MIGRATION_SKILL = /^migrate-email-(.+)$/;

function emailProviderMigratedFrom(skillId: string | null): string | null {
return skillId?.match(EMAIL_MIGRATION_SKILL)?.[1] ?? null;
}
Loading
Loading