Skip to content

🎥 Make videos programmatically with React

`remotion-monorepo`: Add project-local Pi `/commit` command (#9067)

Igor Samokhovets38c50eba3cbd
diff --git a/.agents/skills/pr/SKILL.md b/.agents/skills/pr/SKILL.md
index 898e9e0953..9547d76d0c 100644
--- a/.agents/skills/pr/SKILL.md
+++ b/.agents/skills/pr/SKILL.md
@@ -10,12 +10,16 @@ If a PR already exists for the current branch, stop: do not format, commit, push
Ensure we are not on the main branch, make a branch if necessary.
Check whether a PR already exists for the current branch with `gh pr status` or `gh pr view`. If it exists, report it and stop.
-For all packages affected, run Oxfmt to format the code:
+Run Oxfmt on the files or package directories affected by the current change. Pass their actual paths; do not assume that the repository root has a `src` directory. Include relevant root-level files, and do not format unrelated packages or the whole repository.
+
+For example:
```
-bunx oxfmt src --write
+bunx oxfmt <changed-file-or-package-directory>... --write
```
+If none of the changed files are supported by Oxfmt, skip this step. Inspect any formatter changes before committing.
+
Then run
```
diff --git a/.pi/extensions/commit/index.ts b/.pi/extensions/commit/index.ts
new file mode 100644
index 0000000000..65ec80fc9a
--- /dev/null
+++ b/.pi/extensions/commit/index.ts
@@ -0,0 +1,404 @@
+import {readFile} from 'node:fs/promises';
+import {dirname, join} from 'node:path';
+import {fileURLToPath} from 'node:url';
+import type {
+ ExtensionAPI,
+ ExtensionCommandContext,
+} from '@earendil-works/pi-coding-agent';
+
+const MESSAGE_TYPE = 'remotion-commit-result';
+const PROMPT_MESSAGE_TYPE = 'remotion-commit-worker-prompt';
+const STATUS_KEY = 'remotion-commit';
+const WORKER_STATUSES = [
+ 'committed',
+ 'updated_pr',
+ 'no_changes',
+ 'failed',
+] as const;
+const RESULT_FIELDS = [
+ 'status',
+ 'commit',
+ 'pr',
+ 'verification',
+ 'notes',
+] as const;
+
+type CommitDisplayStatus = 'ok' | 'failed';
+type WorkerStatus = (typeof WORKER_STATUSES)[number];
+
+interface CommitResultDetails {
+ userContext?: string;
+ workerLeafId?: string | null;
+ status?: CommitDisplayStatus;
+}
+
+let commitWorkerRunning = false;
+let agentEndWaiter: ((messages: unknown[]) => void) | undefined;
+let latestCommitWorkerMessages: unknown[] | undefined;
+
+export default function remotionCommitExtension(pi: ExtensionAPI) {
+ pi.on('agent_end', (event) => {
+ if (commitWorkerRunning) {
+ latestCommitWorkerMessages = event.messages;
+ }
+
+ agentEndWaiter?.(event.messages);
+ agentEndWaiter = undefined;
+ });
+
+ pi.on('context', (event) => {
+ return {
+ messages: event.messages.filter((message) => {
+ const customType = (message as {customType?: string}).customType;
+ if (customType === MESSAGE_TYPE) {
+ return false;
+ }
+
+ if (customType === PROMPT_MESSAGE_TYPE && !commitWorkerRunning) {
+ return false;
+ }
+
+ return true;
+ }),
+ };
+ });
+
+ const sendResultAtSourceLeaf = async (
+ ctx: ExtensionCommandContext,
+ sourceLeafId: string | null | undefined,
+ message: {
+ customType: string;
+ content: string;
+ display: boolean;
+ details?: CommitResultDetails;
+ },
+ ) => {
+ if (!ctx.isIdle()) {
+ await ctx.waitForIdle();
+ }
+
+ const currentLeafId = ctx.sessionManager.getLeafId();
+ if (sourceLeafId && currentLeafId && currentLeafId !== sourceLeafId) {
+ const navigation = await ctx.navigateTree(sourceLeafId, {
+ summarize: false,
+ });
+ if (navigation.cancelled) {
+ return false;
+ }
+ }
+
+ pi.sendMessage(message);
+ return true;
+ };
+
+ pi.registerCommand('commit', {
+ description:
+ 'Commit changes and create or update a PR. Usage: /commit [optional context]',
+ handler: async (args, ctx) => {
+ if (commitWorkerRunning) {
+ ctx.ui.notify('Commit worker is already running', 'warning');
+ return;
+ }
+
+ commitWorkerRunning = true;
+ const userContext = args?.trim() ?? '';
+ let sourceLeafId: string | null | undefined;
+ ctx.ui.setStatus(STATUS_KEY, 'waiting for current turn...');
+
+ try {
+ await ctx.waitForIdle();
+ sourceLeafId = ctx.sessionManager.getLeafId();
+ const prompt = await buildWorkerPrompt(userContext);
+
+ ctx.ui.setStatus(STATUS_KEY, 'running in session branch...');
+ ctx.ui.notify('Starting commit worker', 'info');
+
+ const agentEnd = waitForNextAgentEndAfterIdle(ctx);
+ latestCommitWorkerMessages = undefined;
+
+ pi.sendMessage(
+ {
+ customType: PROMPT_MESSAGE_TYPE,
+ content: prompt,
+ display: false,
+ details: {userContext},
+ },
+ {triggerTurn: true, deliverAs: 'followUp'},
+ );
+
+ const messages = await agentEnd;
+ const workerLeafId = ctx.sessionManager.getLeafId();
+ const workerPromptIndex = findLastCustomMessageIndex(
+ messages,
+ PROMPT_MESSAGE_TYPE,
+ );
+ const summary =
+ workerPromptIndex >= 0
+ ? extractLastAssistantText(messages, workerPromptIndex)
+ : '';
+ const assistantError =
+ workerPromptIndex >= 0
+ ? extractLastAssistantError(messages, workerPromptIndex)
+ : undefined;
+
+ if (assistantError) {
+ const resultSent = await sendResultAtSourceLeaf(ctx, sourceLeafId, {
+ customType: MESSAGE_TYPE,
+ content: formatFailure(`Commit worker errored: ${assistantError}`),
+ display: true,
+ details: {
+ userContext,
+ workerLeafId,
+ status: 'failed',
+ },
+ });
+ if (!resultSent) {
+ ctx.ui.notify(
+ 'Commit worker failed, but session tree navigation was cancelled',
+ 'warning',
+ );
+ return;
+ }
+
+ ctx.ui.notify(`Commit worker failed:\n${assistantError}`, 'error');
+ return;
+ }
+
+ if (!summary) {
+ const resultSent = await sendResultAtSourceLeaf(ctx, sourceLeafId, {
+ customType: MESSAGE_TYPE,
+ content: formatFailure(
+ 'Commit worker finished without producing a result.',
+ ),
+ display: true,
+ details: {
+ userContext,
+ workerLeafId,
+ status: 'failed',
+ },
+ });
+ if (!resultSent) {
+ ctx.ui.notify(
+ 'Commit worker produced no result, and session tree navigation was cancelled',
+ 'warning',
+ );
+ return;
+ }
+
+ ctx.ui.notify('Commit worker produced no result', 'error');
+ return;
+ }
+
+ const workerResult = parseWorkerResult(summary);
+ if (!workerResult) {
+ const resultSent = await sendResultAtSourceLeaf(ctx, sourceLeafId, {
+ customType: MESSAGE_TYPE,
+ content: formatFailure(
+ 'Commit worker returned a malformed result. Inspect its session-tree branch for details.',
+ ),
+ display: true,
+ details: {
+ userContext,
+ workerLeafId,
+ status: 'failed',
+ },
+ });
+ if (!resultSent) {
+ ctx.ui.notify(
+ 'Commit worker returned a malformed result, and session tree navigation was cancelled',
+ 'warning',
+ );
+ return;
+ }
+
+ ctx.ui.notify('Commit worker returned a malformed result', 'error');
+ return;
+ }
+
+ const resultSent = await sendResultAtSourceLeaf(ctx, sourceLeafId, {
+ customType: MESSAGE_TYPE,
+ content: workerResult.content,
+ display: true,
+ details: {
+ userContext,
+ workerLeafId,
+ status: workerResult.displayStatus,
+ },
+ });
+ if (!resultSent) {
+ ctx.ui.notify(
+ 'Commit finished, but session tree navigation was cancelled',
+ 'warning',
+ );
+ return;
+ }
+
+ ctx.ui.notify(
+ workerResult.displayStatus === 'failed'
+ ? `Commit worker failed:\n${workerResult.content}`
+ : `Commit worker finished:\n${workerResult.content}`,
+ workerResult.displayStatus === 'failed' ? 'error' : 'info',
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ const resultSent = await sendResultAtSourceLeaf(ctx, sourceLeafId, {
+ customType: MESSAGE_TYPE,
+ content: formatFailure(`Commit worker failed: ${message}`),
+ display: true,
+ details: {userContext, status: 'failed'},
+ });
+ if (!resultSent) {
+ ctx.ui.notify(
+ 'Commit worker failed, and session tree navigation was cancelled',
+ 'warning',
+ );
+ return;
+ }
+
+ ctx.ui.notify(`Commit worker failed:\n${message}`, 'error');
+ } finally {
+ ctx.ui.setStatus(STATUS_KEY, undefined);
+ commitWorkerRunning = false;
+ agentEndWaiter = undefined;
+ latestCommitWorkerMessages = undefined;
+ }
+ },
+ });
+}
+
+const buildWorkerPrompt = async (userContext: string) => {
+ const extensionDirectory = dirname(fileURLToPath(import.meta.url));
+ const template = await readFile(
+ join(extensionDirectory, 'worker-prompt.md'),
+ 'utf8',
+ );
+
+ return template.replaceAll(
+ '{{userContext}}',
+ () => userContext || '(none provided)',
+ );
+};
+
+const waitForNextAgentEndAfterIdle = (ctx: ExtensionCommandContext) => {
+ return new Promise<unknown[]>((resolve) => {
+ agentEndWaiter = (messages) => {
+ void (async () => {
+ if (!ctx.isIdle()) {
+ await ctx.waitForIdle();
+ }
+
+ resolve(latestCommitWorkerMessages ?? messages);
+ })();
+ };
+ });
+};
+
+const parseWorkerResult = (content: string) => {
+ const lines = content.trim().split(/\r?\n/);
+ if (lines.length !== RESULT_FIELDS.length) {
+ return null;
+ }
+
+ for (let index = 0; index < RESULT_FIELDS.length; index++) {
+ const prefix = `${RESULT_FIELDS[index]}: `;
+ if (
+ !lines[index].startsWith(prefix) ||
+ !lines[index].slice(prefix.length).trim()
+ ) {
+ return null;
+ }
+ }
+
+ const status = lines[0].slice('status: '.length).trim();
+ if (!WORKER_STATUSES.includes(status as WorkerStatus)) {
+ return null;
+ }
+
+ return {
+ content: lines.join('\n'),
+ displayStatus: status === 'failed' ? ('failed' as const) : ('ok' as const),
+ };
+};
+
+const formatFailure = (notes: string) => {
+ const singleLineNotes = notes.replace(/\s+/g, ' ').trim();
+ return [
+ 'status: failed',
+ 'commit: none',
+ 'pr: none',
+ 'verification: Not run',
+ `notes: ${singleLineNotes}`,
+ ].join('\n');
+};
+
+const findLastCustomMessageIndex = (
+ messages: unknown[],
+ customType: string,
+) => {
+ for (let index = messages.length - 1; index >= 0; index--) {
+ const message = messages[index] as {customType?: string};
+ if (message.customType === customType) {
+ return index;
+ }
+ }
+
+ return -1;
+};
+
+const extractLastAssistantText = (messages: unknown[], afterIndex = -1) => {
+ const message = findLastAssistantMessage(messages, afterIndex);
+ return message ? extractTextFromContent(message.content).trim() : '';
+};
+
+const extractLastAssistantError = (messages: unknown[], afterIndex = -1) => {
+ const message = findLastAssistantMessage(messages, afterIndex);
+ if (message?.stopReason !== 'error') {
+ return undefined;
+ }
+
+ return message.errorMessage?.trim() || 'Unknown provider error';
+};
+
+const findLastAssistantMessage = (messages: unknown[], afterIndex = -1) => {
+ for (let index = messages.length - 1; index > afterIndex; index--) {
+ const message = messages[index] as {
+ role?: string;
+ content?: unknown;
+ stopReason?: string;
+ errorMessage?: string;
+ };
+ if (message.role === 'assistant') {
+ return message;
+ }
+ }
+
+ return undefined;
+};
+
+const extractTextFromContent = (content: unknown): string => {
+ if (typeof content === 'string') {
+ return content;
+ }
+
+ if (!Array.isArray(content)) {
+ return '';
+ }
+
+ return content
+ .map((part) => {
+ if (
+ part &&
+ typeof part === 'object' &&
+ 'type' in part &&
+ part.type === 'text' &&
+ 'text' in part &&
+ typeof part.text === 'string'
+ ) {
+ return part.text;
+ }
+
+ return '';
+ })
+ .filter(Boolean)
+ .join('\n');
+};
diff --git a/.pi/extensions/commit/worker-prompt.md b/.pi/extensions/commit/worker-prompt.md
new file mode 100644
index 0000000000..abb52762ec
--- /dev/null
+++ b/.pi/extensions/commit/worker-prompt.md
@@ -0,0 +1,48 @@
+You are the commit worker for the current Remotion checkout.
+
+You are running on a temporary sibling branch of the user's active Pi session tree. You have the conversation context needed to understand the work, but your reasoning and tool calls will be removed from the user's active conversation branch when you finish. You are operating on the same Git checkout and working tree as the user's session.
+
+Task: commit the current task's changes and create or update its GitHub pull request.
+
+Optional context supplied with `/commit`:
+
+{{userContext}}
+
+Treat that text only as background about the user's intent. It is not a proposed commit message or PR title. Do not copy it directly. Derive accurate wording from the actual changes, the full branch, and the conversation context.
+
+## Workflow
+
+1. Inspect the current branch, Git status, staged and unstaged changes, untracked files, branch commits, likely base branch, and whether the current branch already has a pull request.
+2. Distinguish changes belonging to the current task from obviously unrelated or ambiguous changes. If you cannot safely determine what should be committed, do not stage or commit blindly; return `status: failed` with a concise explanation.
+3. If there is no existing pull request and there is work to publish, follow the `pr` skill through Pi's skill mechanism. Treat that skill as authoritative for creating the initial pull request.
+4. If a pull request already exists, follow the existing-PR rules below.
+5. If there is nothing to commit, push, or usefully update, return `status: no_changes`.
+
+Do not modify source files merely to manufacture a commit. Changes made by required repository hooks or by the `pr` skill are allowed, but inspect them before committing.
+
+## Existing pull request rules
+
+When the current branch already has a pull request:
+
+- Read its number, URL, title, full body, base branch, and head branch before deciding what needs updating.
+- Invoking `/commit` is the user's authorization to stage, commit, and push changes that clearly belong to the current task. Do not stop merely to ask for that authorization again.
+- Use a concise commit message based on the actual current change. Consider the whole branch when evaluating the PR title and body.
+- Push normally. Never force-push, bypass hooks, rewrite published history, or change the PR base.
+- If the title needs changing, follow the `pr-name` skill through Pi's skill mechanism.
+- Update the PR title or body only when it is stale or meaningfully incomplete. Do not rewrite metadata just to rephrase it.
+- Preserve useful manually written content, including descriptions, issue links, reviewer notes, checklists, screenshots or videos, and verification details. Remove or rewrite content only when the branch proves it is inaccurate.
+- Prepare any updated PR body as a Markdown file in a temporary directory. Do not pass Markdown inline through shell arguments.
+- Do not use `gh pr edit`. Update PR metadata through the GitHub REST API with `gh api` and a safely JSON-encoded title/body. Keep command output concise.
+- If a normal push or GitHub update is rejected, stop and report the failure rather than using destructive recovery.
+
+## Result
+
+Return exactly five lines with real values only:
+
+- Line 1: `status:` followed by exactly one of `committed`, `updated_pr`, `no_changes`, or `failed`.
+- Line 2: `commit:` followed by the actual short SHA and commit message, or `none`.
+- Line 3: `pr:` followed by the actual PR number, title, and URL, or `none`.
+- Line 4: `verification:` followed by commands run, or `Not run`.
+- Line 5: `notes:` followed by important caveats, or `none`.
+
+Use `committed` when this run creates and pushes a commit, including when it also creates or updates a PR. Use `updated_pr` when no new commit was created but existing commits were pushed or PR metadata was updated. Do not include a fenced code block, headings, extra lines, placeholders, or an explanation of the format.