🎥 Make videos programmatically with React
Internal: Remove Pi /commit extension
Igor Samokhovets7dea65a989a9
diff --git a/.pi/extensions/commit/index.test.ts b/.pi/extensions/commit/index.test.tsdeleted file mode 100644index a6a892b369..0000000000--- a/.pi/extensions/commit/index.test.ts+++ /dev/null@@ -1,136 +0,0 @@-import {expect, test} from 'bun:test';-import type {- ExtensionAPI,- ExtensionCommandContext,-} from '@earendil-works/pi-coding-agent';-import remotionCommitExtension from './index';--type Handler = (- event: Record<string, unknown>,- ctx: ExtensionCommandContext,-) => unknown | Promise<unknown>;-type CommandHandler = (- args: string,- ctx: ExtensionCommandContext,-) => unknown | Promise<unknown>;--test('queues user messages outside the temporary commit worker branch with prompt expansion enabled', async () => {- const handlers = new Map<string, Handler>();- let commitCommand: CommandHandler | undefined;- let leafId = 'source-leaf';- let workerStartedResolve: (() => void) | undefined;- const workerStarted = new Promise<void>((resolve) => {- workerStartedResolve = resolve;- });- const sentUserMessages: Array<{- content: unknown;- options: unknown;- }> = [];- const sentCustomMessages: Array<{customType: string}> = [];-- const pi = {- on(event: string, handler: Handler) {- handlers.set(event, handler);- },- registerCommand(_name: string, options: {handler: CommandHandler}) {- commitCommand = options.handler;- },- sendMessage(message: {customType: string}) {- sentCustomMessages.push(message);- if (message.customType === 'remotion-commit-worker-prompt') {- leafId = 'worker-leaf';- workerStartedResolve?.();- }- },- sendUserMessage(content: unknown, options: unknown) {- sentUserMessages.push({content, options});- },- } as unknown as ExtensionAPI;- const context = {- isIdle: () => true,- waitForIdle: async () => undefined,- navigateTree: async (targetId: string) => {- leafId = targetId;- return {cancelled: false};- },- sessionManager: {- getLeafId: () => leafId,- },- ui: {- notify: () => undefined,- setStatus: () => undefined,- },- } as unknown as ExtensionCommandContext;-- remotionCommitExtension(pi);- const commandPromise = commitCommand?.('', context);- await workerStarted;-- const steerResult = await handlers.get('input')?.(- {- text: 'Do not steer the worker',- source: 'interactive',- streamingBehavior: 'steer',- },- context,- );- const followUpResult = await handlers.get('input')?.(- {- text: 'Run this after the worker exits',- source: 'interactive',- streamingBehavior: 'followUp',- },- context,- );-- expect(steerResult).toEqual({action: 'handled'});- expect(followUpResult).toEqual({action: 'handled'});- expect(sentUserMessages).toEqual([]);- expect(leafId).toBe('worker-leaf');-- await handlers.get('agent_end')?.(- {- messages: [- {customType: 'remotion-commit-worker-prompt'},- {- role: 'assistant',- content: [- {- type: 'text',- text: [- 'status: no_changes',- 'commit: none',- 'pr: none',- 'verification: Not run',- 'notes: none',- ].join('\n'),- },- ],- },- ],- },- context,- );- await commandPromise;-- expect(leafId).toBe('source-leaf');- expect(sentCustomMessages.at(-1)?.customType).toBe('remotion-commit-result');- expect(sentUserMessages).toEqual([- {- content: 'Do not steer the worker',- options: {expandPromptTemplates: true},- },- ]);-- await handlers.get('agent_start')?.({}, context);- expect(sentUserMessages).toEqual([- {- content: 'Do not steer the worker',- options: {expandPromptTemplates: true},- },- {- content: 'Run this after the worker exits',- options: {deliverAs: 'followUp', expandPromptTemplates: true},- },- ]);-});diff --git a/.pi/extensions/commit/index.ts b/.pi/extensions/commit/index.tsdeleted file mode 100644index c625abc180..0000000000--- a/.pi/extensions/commit/index.ts+++ /dev/null@@ -1,495 +0,0 @@-import {readFile} from 'node:fs/promises';-import {dirname, join} from 'node:path';-import {fileURLToPath} from 'node:url';-import type {- ExtensionAPI,- ExtensionCommandContext,- InputEvent,-} 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;-}--interface QueuedUserMessage {- text: string;- images: NonNullable<InputEvent['images']>;-}--let commitWorkerRunning = false;-let agentEndWaiter: ((messages: unknown[]) => void) | undefined;-let latestCommitWorkerMessages: unknown[] | undefined;-const queuedUserMessages: QueuedUserMessage[] = [];-const queuedFollowUpUserMessages: QueuedUserMessage[] = [];--export default function remotionCommitExtension(pi: ExtensionAPI) {- const sendQueuedUserMessage = (- message: QueuedUserMessage,- deliverAs?: 'steer' | 'followUp',- ) => {- const content =- message.images.length === 0- ? message.text- : [{type: 'text' as const, text: message.text}, ...message.images];-- if (deliverAs) {- pi.sendUserMessage(content, {- deliverAs,- expandPromptTemplates: true,- });- } else {- pi.sendUserMessage(content, {expandPromptTemplates: true});- }- };-- const releaseQueuedUserMessages = () => {- const [firstMessage, ...followUpMessages] = queuedUserMessages.splice(0);- if (!firstMessage) {- return;- }-- queuedFollowUpUserMessages.push(...followUpMessages);- sendQueuedUserMessage(firstMessage);- };-- pi.on('input', (event, ctx) => {- if (!commitWorkerRunning || event.source === 'extension') {- return {action: 'continue'};- }-- queuedUserMessages.push({- text: event.text,- images: event.images ? [...event.images] : [],- });- ctx.ui.notify(- `Message queued until the commit worker exits (${queuedUserMessages.length} pending)`,- 'info',- );- return {action: 'handled'};- });-- pi.on('agent_start', () => {- if (commitWorkerRunning || queuedFollowUpUserMessages.length === 0) {- return;- }-- const followUpMessages = queuedFollowUpUserMessages.splice(0);- for (const message of followUpMessages) {- sendQueuedUserMessage(message, 'followUp');- }- });-- 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;- let returnedToSourceBranch = false;- ctx.ui.setStatus(STATUS_KEY, 'waiting for current turn...');-- const sendResult = async (- message: Parameters<typeof sendResultAtSourceLeaf>[2],- ) => {- const resultSent = await sendResultAtSourceLeaf(- ctx,- sourceLeafId,- message,- );- returnedToSourceBranch = resultSent;- return resultSent;- };-- 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 sendResult({- 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 sendResult({- 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 sendResult({- 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 sendResult({- 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 sendResult({- 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;-- if (returnedToSourceBranch && queuedUserMessages.length > 0) {- const queuedMessageCount = queuedUserMessages.length;- ctx.ui.notify(- `Commit worker exited; releasing ${queuedMessageCount} queued message${queuedMessageCount === 1 ? '' : 's'}`,- 'info',- );- releaseQueuedUserMessages();- } else if (queuedUserMessages.length > 0) {- ctx.ui.notify(- `${queuedUserMessages.length} message${queuedUserMessages.length === 1 ? ' remains' : 's remain'} queued because the commit worker branch could not be exited`,- 'warning',- );- }- }- },- });-}--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.mddeleted file mode 100644index abb52762ec..0000000000--- a/.pi/extensions/commit/worker-prompt.md+++ /dev/null@@ -1,48 +0,0 @@-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.