Personal Telegram developer console for GitHub

fix/workspace-recovery-validation
audit/commit-drilldown audit/finalize-workspace-menu-security audit/ops-actionability audit/pr-menu-consolidation audit/status-menu-consolidation audit/telegram-menu-e2e audit/telegram-menu-e2e-wave2 chore/actions-node24-runtime cleanup/remove-diag design/cloudflare-ops-read docs/control-plane-2-7-design docs/guide-v2-1-sync docs/menu-audit-final-sync docs/phase2-acceptance-closeout docs/phase2-multifile-design feat/bootstrap-worker feat/cloudflare-ops-read feat/cp2-multifile-final feat/cp2-multifile-workspace feat/cp3-github-write-final feat/cp4-cloudflare-ops-final feat/cp5-cicd-control-plane feat/cp6-incident-manager feat/cp7-automation-engine feat/deep-file-browser feat/final-delivery-16-20 feat/github-advanced-read feat/in-app-guide-v2 feat/navigation-recovery-ux-v2 feat/ops-console-v2-1 feat/persistent-menu-code-input feat/phase2-multifile-workspace feat/phase2-multifile-workspace-v2 feat/plugin-foundation-v1 feat/safe-github-ops feat/self-register-webhook feat/studio-g0-foundation feat/telegram-main-inline-menu feat/telegram-pr-merge feat/ux-platform-8-12 feat/v3a-readonly-copilot feat/workspace-file-upload feature/mobile-repo-browser feature/multi-file-change-set fix/approval-expiry-feedback fix/callback-resilience-and-docs fix/ci-actions-pagination fix/cloudflare-fetch-binding fix/editor-request-body-cap fix/editor-safe-file-options fix/issues-permission-release-empty-ux fix/main-menu-callback-fallback fix/phase2-file-editor-selection fix/phase2-final-ux fix/phase2-workspace-ref-persistence fix/production-auto-deploy fix/provider-write-error-feedback fix/repository-id-navigation-fallback fix/repository-pr-navigation fix/telegram-callback-updates fix/telegram-runtime-diagnostics fix/workspace-editor-flow-v2 fix/workspace-recovery-validation hardening/ci-zero-test-telegram-token hardening/pr1-destructive-totp hardening/pr2-kill-switch main multifile-workspace nexa/edit-BwJEIIY3PW nexa/edit-IPHT8irO7b nexa/edit-b4Od3BIMYd p2-multifile phase2-20261005 phase2-20261005-a phase2-20261005-b phase2-20261005-c phase2-20261005-d phase2-20261005-e phase2-20261005-f phase2-20261005-g phase2-20261005-h phase2-20261005-i phase2-20261005-j phase2-20261005-k phase2-20261005-l phase2-20261005-m phase2-20261005-n phase2-20261005-o phase2-20261005-p phase2-20261005-q phase2-20261005-r phase2-20261005-s phase2-20261005-t phase2-20261005-u phase2-20261005-v phase2-20261005-w phase2-20261005-x phase2-20261005-y phase2-20261005-z phase2-acceptance-closeout phase2-add-file-hotfix phase2-change-set phase2-design-20261005 phase2-design-final phase2-implementation phase2-multifile-implementation phase2-multifile-spec phase2-spec-final phase2-workspace phase2/multifile-workspace plan/nexa-studio-v2-reviewed security/remove-telegram-setup spec/repository-workspace-editor v3a/multifile work/multifile
js 405 lines 21.3 KB
Raw
1 import {
2 buildUnifiedDiff,
3 digestText,
4 makeTargetBranch,
5 normalizeCommitMessage,
6 validateEditableFile
7 } from '../../core/workspace-policy.js';
8 import { commitWorkspaceIntent } from './workspace-commit.js';
9
10 export { commitWorkspaceIntent } from './workspace-commit.js';
11
12 const HANDLE_10 = '[A-Za-z0-9_-]{10}';
13 const INTENT_8 = '[A-Za-z0-9_-]{8}';
14 const escapeHtml = value => String(value ?? '')
15 .replaceAll('&', '&')
16 .replaceAll('<', '&lt;')
17 .replaceAll('>', '&gt;')
18 .replaceAll('"', '&quot;');
19 const short = (value, max = 70) => {
20 const text = String(value ?? '');
21 return text.length > max ? `${text.slice(0, max - 1)}…` : text;
22 };
23
24 const ownerFrom = context => {
25 const ownerId = String(context?.ownerId ?? '');
26 if (!ownerId) throw new Error('Workspace owner is required');
27 return ownerId;
28 };
29
30 function parseCallback(data) {
31 const value = String(data || '');
32 let match = value.match(/^(?:files):(\d+)$/);
33 if (match) return { actionId: 'github.files.list', kind: 'root', repoId: Number(match[1]) };
34 match = value.match(new RegExp(`^wnav:(${HANDLE_10})$`));
35 if (match) return { actionId: 'github.workspace.navigate', kind: 'navigate', refId: match[1] };
36 match = value.match(new RegExp(`^wedit:(${HANDLE_10})$`));
37 if (match) return { actionId: 'github.workspace.create', kind: 'edit', refId: match[1] };
38 match = value.match(new RegExp(`^ws:(${HANDLE_10})$`));
39 if (match) return { actionId: 'github.workspace.view', kind: 'workspace', workspaceId: match[1] };
40 match = value.match(new RegExp(`^wfile:(${HANDLE_10})$`));
41 if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'draft_file' };
42 match = value.match(new RegExp(`^wtext:(${HANDLE_10})$`));
43 if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'draft' };
44 match = value.match(new RegExp(`^wmsg:(${HANDLE_10})$`));
45 if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'commit_message' };
46 match = value.match(new RegExp(`^wdiff:(${HANDLE_10})$`));
47 if (match) return { actionId: 'github.workspace.diff', kind: 'diff', workspaceId: match[1] };
48 match = value.match(new RegExp(`^wready:(${HANDLE_10})$`));
49 if (match) return { actionId: 'github.workspace.ready', kind: 'ready', workspaceId: match[1] };
50 match = value.match(new RegExp(`^wcancel:(${HANDLE_10})$`));
51 if (match) return { actionId: 'github.workspace.cancel', kind: 'cancel', workspaceId: match[1] };
52 match = value.match(new RegExp(`^wscommit:(\\d+):(${INTENT_8})$`));
53 if (match) return {
54 actionId: 'github.workspace.commit_branch',
55 kind: 'commit',
56 repoId: Number(match[1]),
57 intentId: match[2]
58 };
59 return null;
60 }
61
62 function workspaceButtons(workspace) {
63 return [
64 [
65 { text: '📎 بارگذاری فایل', callback_data: `wfile:${workspace.id}` },
66 { text: '📝 Paste متن', callback_data: `wtext:${workspace.id}` }
67 ],
68 [{ text: '✍️ پیام Commit', callback_data: `wmsg:${workspace.id}` }],
69 [
70 { text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` },
71 { text: '✅ آماده Commit', callback_data: `wready:${workspace.id}` }
72 ],
73 [
74 { text: '🗑 لغو Draft', callback_data: `wcancel:${workspace.id}` },
75 { text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }
76 ]
77 ];
78 }
79
80 function workspaceCommitResultView(repoId, intent, result) {
81 const rows = [
82 [{ text: '🧪 CI / Actions', callback_data: `runs:${repoId}` }]
83 ];
84 if (intent?.workspaceId) {
85 rows.push([{ text: '📝 Workspace', callback_data: `ws:${intent.workspaceId}` }]);
86 }
87 rows.push([{ text: '📦 پروژه', callback_data: `repo:${repoId}` }]);
88 return {
89 text: `✅ <b>Commit روی branch جدید ایجاد شد</b>\nBranch: <code>${escapeHtml(result.branch)}</code>\nSHA: <code>${escapeHtml(result.commitSha)}</code>${result.idempotent ? '\nوضعیت: <b>reconciled / idempotent</b>' : ''}\n\nشاخهٔ پیش‌فرض تغییر نکرده است.`,
90 reply_markup: { inline_keyboard: rows }
91 };
92 }
93
94 export function createWorkspaceController({ github, workspaces } = {}) {
95 if (!github) throw new Error('Workspace controller requires GitHub service');
96 if (!workspaces) throw new Error('Workspace controller requires durable workspace store');
97
98 const requireWorkspace = async (workspaceId, ownerId) => {
99 const workspace = await workspaces.getWorkspace({ ownerId, workspaceId });
100 if (!workspace) throw new Error('Workspace not found or expired');
101 return workspace;
102 };
103
104 const renderDirectory = async (repoId, path, ownerId) => {
105 const [repo, items] = await Promise.all([
106 github.getRepository(repoId),
107 github.listFiles(repoId, path)
108 ]);
109 const visible = items.slice(0, 30);
110 const handles = await workspaces.createNavigationRefs({
111 ownerId,
112 refs: visible.map(item => ({ repoId, path: item.path, type: item.type, sha: item.sha }))
113 });
114 const body = visible.length
115 ? visible.map(item => `${item.type === 'dir' ? '📁' : '📄'} <code>${escapeHtml(short(item.name, 100))}</code>${item.type === 'file' && item.size ? ` (${Number(item.size).toLocaleString()} B)` : ''}`).join('\n')
116 : '<i>این پوشه خالی است.</i>';
117 const rows = visible.map((item, index) => [{
118 text: `${item.type === 'dir' ? '📁' : '📄'} ${short(item.name, 46)}`,
119 callback_data: `wnav:${handles[index].refId}`
120 }]);
121 rows.push([
122 { text: '🔄 بروزرسانی', callback_data: `files:${repoId}` },
123 { text: '📦 پروژه', callback_data: `repo:${repoId}` }
124 ]);
125 return {
126 text: `📂 <b>فایل‌های ${escapeHtml(repo.name)}</b>\n${path ? `مسیر: <code>${escapeHtml(path)}</code>\n` : ''}➖➖➖➖➖➖➖➖➖➖\n${body}`,
127 reply_markup: { inline_keyboard: rows }
128 };
129 };
130
131 const getPinnedFile = async ref => {
132 const repo = await github.getRepository(ref.repoId);
133 const snapshot = await github.getBranchSnapshot(ref.repoId, repo.defaultBranch);
134 const file = await github.getFileAtRef(ref.repoId, ref.path, snapshot.headSha);
135 return { repo, snapshot, file };
136 };
137
138 const renderFile = async (refId, ownerId) => {
139 const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
140 if (!ref || ref.type !== 'file') throw new Error('Workspace file reference is missing or expired');
141 const { repo, snapshot, file } = await getPinnedFile(ref);
142 const policy = validateEditableFile({ path: file.path, text: file.content, byteLength: file.size });
143 const preview = file.content.length > 2600 ? `${file.content.slice(0, 2600)}\n…` : file.content;
144 const reason = repo.archived
145 ? 'این مخزن آرشیوشده است و ویرایش فایل در آن غیرفعال است.'
146 : policy.reason;
147 const rows = [];
148 if (!repo.archived && policy.editable) rows.push([{ text: '✏️ Edit', callback_data: `wedit:${refId}` }]);
149 rows.push([{ text: '🔙 فایل‌ها', callback_data: `files:${ref.repoId}` }, { text: '📦 پروژه', callback_data: `repo:${ref.repoId}` }]);
150 return {
151 text: `📄 <b>پیش‌نمایش فایل — ${escapeHtml(repo.name)}</b>\nمسیر: <code>${escapeHtml(file.path)}</code>\nRef: <code>${escapeHtml(snapshot.headSha.slice(0, 10))}</code>\n${reason ? `⚠️ ${escapeHtml(reason)}\n` : ''}➖➖➖➖➖➖➖➖➖➖\n<pre>${escapeHtml(preview)}</pre>`,
152 reply_markup: { inline_keyboard: rows }
153 };
154 };
155
156 const createDraft = async (refId, ownerId) => {
157 const ref = await workspaces.resolveNavigationRef({ ownerId, refId });
158 if (!ref || ref.type !== 'file') throw new Error('Workspace file reference is missing or expired');
159 const { repo, snapshot, file } = await getPinnedFile(ref);
160 if (repo.archived) throw new Error('Archived repository is not editable');
161 const policy = validateEditableFile({ path: file.path, text: file.content, byteLength: file.size });
162 if (!policy.editable) throw new Error(policy.reason || 'File is not editable');
163 const originalDigest = await digestText(file.content);
164 const workspace = await workspaces.createWorkspace({
165 ownerId,
166 repoId: Number(ref.repoId),
167 repoFullName: repo.fullName,
168 baseBranch: repo.defaultBranch,
169 baseHeadSha: snapshot.headSha,
170 baseTreeSha: snapshot.treeSha,
171 path: file.path,
172 blobSha: file.sha,
173 originalText: file.content,
174 originalDigest
175 });
176 return {
177 text: `📝 <b>Draft ساخته شد</b>\nمخزن: <code>${escapeHtml(repo.fullName)}</code>\nفایل: <code>${escapeHtml(file.path)}</code>\nBase: <code>${escapeHtml(snapshot.headSha.slice(0, 10))}</code>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
178 reply_markup: { inline_keyboard: [[{ text: '📝 باز کردن Draft', callback_data: `ws:${workspace.id}` }], [{ text: '🔙 فایل‌ها', callback_data: `files:${ref.repoId}` }]] }
179 };
180 };
181
182 const renderWorkspace = async (workspaceId, ownerId) => {
183 const workspace = await requireWorkspace(workspaceId, ownerId);
184 const changed = workspace.draftText !== workspace.originalText;
185 const commitMessage = workspace.commitMessage
186 ? `<code>${escapeHtml(short(workspace.commitMessage, 120))}</code>`
187 : '<i>ثبت نشده</i>';
188 return {
189 text: `📝 <b>Repository Workspace</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nوضعیت: <b>${escapeHtml(workspace.state || 'DRAFT')}</b>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha || '').slice(0, 10))}</code>\nتغییر محلی: <b>${changed ? 'دارد' : 'ندارد'}</b>\nپیام Commit: ${commitMessage}\n\nروش پیشنهادی: فایل متنی جایگزین را بارگذاری کنید؛ Paste متن همچنان به‌عنوان مسیر جایگزین در دسترس است. تا قبل از تأیید نهایی، هیچ تغییری در GitHub انجام نمی‌شود.`,
190 reply_markup: { inline_keyboard: workspaceButtons(workspace) }
191 };
192 };
193
194 const prepareInput = async (workspaceId, mode, ownerId) => {
195 const workspace = await requireWorkspace(workspaceId, ownerId);
196 await workspaces.setPendingInput({ ownerId, workspaceId, mode });
197 const fileMode = mode === 'draft_file';
198 const draftMode = mode === 'draft';
199 return {
200 text: fileMode
201 ? `📎 <b>فایل متنی جایگزین را ارسال کنید</b>\nمقصد در مخزن: <code>${escapeHtml(workspace.path)}</code>\n\nفایل ارسال‌شده فقط به‌عنوان محتوای جایگزین Draft استفاده می‌شود؛ نام فایل مقصد را تغییر نمی‌دهد. سقف: 3,000 کاراکتر Unicode و 12,000 بایت UTF-8 معتبر. فایل‌های باینری، LFS یا محتوای غیرمجاز رد می‌شوند.`
202 : draftMode
203 ? `📝 <b>متن جدید Draft را ارسال کنید</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nکل محتوای فایل جایگزین می‌شود. سقف: 3,000 کاراکتر Unicode و 12,000 بایت UTF-8. پیام بعدی فقط یک‌بار مصرف می‌شود.`
204 : `✍️ <b>پیام Commit را ارسال کنید</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nپیام باید غیرخالی و حداکثر 120 کاراکتر باشد. پیام بعدی فقط یک‌بار مصرف می‌شود.`,
205 reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
206 };
207 };
208
209 const applyPendingInput = async ({ pending, text, file }, ownerId) => {
210 const workspaceId = String(pending?.workspaceId || '');
211 const mode = String(pending?.mode || '');
212 if (!new RegExp(`^${HANDLE_10}$`).test(workspaceId) || !['draft', 'draft_file', 'commit_message'].includes(mode)) {
213 throw new Error('Pending workspace input is invalid');
214 }
215
216 if (mode === 'draft_file' && (!file || typeof file.text !== 'string')) {
217 throw new Error('A UTF-8 Telegram document is required for this workspace input');
218 }
219
220 const consumed = await workspaces.consumePendingInput({ ownerId, workspaceId, mode });
221 if (!consumed) throw new Error('Pending workspace input was already consumed or expired');
222 const workspace = await requireWorkspace(workspaceId, ownerId);
223
224 if (mode === 'draft' || mode === 'draft_file') {
225 const inputText = mode === 'draft_file' ? file.text : text;
226 const inputBytes = mode === 'draft_file' ? Number(file.byteLength) : undefined;
227 const policy = validateEditableFile({ path: workspace.path, text: inputText, byteLength: inputBytes });
228 if (!policy.editable) {
229 return {
230 text: `⚠️ <b>Draft تغییر نکرد</b>\n${escapeHtml(policy.reason || 'محتوای ارسال‌شده مجاز نیست.')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره ${mode === 'draft_file' ? '«بارگذاری فایل»' : '«Paste متن»'} را بزنید.`,
231 reply_markup: { inline_keyboard: [[{ text: '📝 بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
232 };
233 }
234 const digest = await digestText(policy.text);
235 const updated = await workspaces.updateDraft({ ownerId, workspaceId, text: policy.text, digest });
236 const source = mode === 'draft_file'
237 ? `\nفایل ورودی: <code>${escapeHtml(short(file.name || 'uploaded file', 100))}</code>`
238 : '';
239 return {
240 text: `✅ <b>Draft محلی ذخیره شد</b>\nفایل مقصد: <code>${escapeHtml(updated.path)}</code>${source}\nکاراکتر: <b>${policy.charLength}</b> · بایت UTF-8: <b>${policy.byteLength}</b>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
241 reply_markup: { inline_keyboard: workspaceButtons(updated) }
242 };
243 }
244
245 let message;
246 try {
247 message = normalizeCommitMessage(text);
248 } catch (error) {
249 return {
250 text: `⚠️ <b>پیام Commit ذخیره نشد</b>\n${escapeHtml(error?.message || 'Commit message is invalid')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره «پیام Commit» را بزنید.`,
251 reply_markup: { inline_keyboard: [[{ text: '📝 بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
252 };
253 }
254 const digest = await digestText(message);
255 const updated = await workspaces.setCommitMessage({ ownerId, workspaceId, message, digest });
256 return {
257 text: `✅ <b>پیام Commit ذخیره شد</b>\n<code>${escapeHtml(message)}</code>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
258 reply_markup: { inline_keyboard: workspaceButtons(updated) }
259 };
260 };
261
262 const renderDiff = async (workspaceId, ownerId) => {
263 const workspace = await requireWorkspace(workspaceId, ownerId);
264 const diff = buildUnifiedDiff({
265 path: workspace.path,
266 before: workspace.originalText,
267 after: workspace.draftText,
268 maxChars: 2400
269 });
270 const truncation = diff.truncated ? '\n⚠️ نمایش Diff کوتاه شده؛ شمارش‌ها بر اساس محتوای کامل هستند.' : '';
271 return {
272 text: `🔍 <b>Diff محلی</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n+${diff.additions} / -${diff.deletions}${truncation}\n➖➖➖➖➖➖➖➖➖➖\n<pre>${escapeHtml(diff.text)}</pre>`,
273 reply_markup: { inline_keyboard: [[{ text: '📝 Draft', callback_data: `ws:${workspace.id}` }, { text: '✅ آماده Commit', callback_data: `wready:${workspace.id}` }]] }
274 };
275 };
276
277 const sealReadyIntent = async (workspaceId, ownerId) => {
278 const workspace = await requireWorkspace(workspaceId, ownerId);
279 if (workspace.draftText === workspace.originalText) throw new Error('No draft change to commit');
280 const commitMessage = normalizeCommitMessage(workspace.commitMessage);
281 const contentDigest = await digestText(workspace.draftText);
282 const commitMessageDigest = await digestText(commitMessage);
283 const targetBranch = makeTargetBranch(workspace.id);
284 const createdAt = Number(workspace.createdAt);
285 const commitTimestamp = new Date(Number.isFinite(createdAt) ? createdAt : 0).toISOString();
286 const material = {
287 repoId: Number(workspace.repoId),
288 workspaceId: workspace.id,
289 baseBranch: workspace.baseBranch,
290 baseHeadSha: workspace.baseHeadSha,
291 baseTreeSha: workspace.baseTreeSha,
292 path: workspace.path,
293 sourceBlobSha: workspace.blobSha,
294 contentDigest,
295 commitMessageDigest,
296 targetBranch,
297 commitTimestamp
298 };
299 const intentDigest = await digestText(JSON.stringify(material));
300 const intent = await workspaces.sealIntent({
301 ownerId,
302 workspaceId,
303 intent: { ...material, intentDigest }
304 });
305 if (!intent?.id || !/^[A-Za-z0-9_-]{8}$/.test(intent.id)) throw new Error('Commit intent ID is invalid');
306 return {
307 text: `✅ <b>آمادهٔ تأیید Commit</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nBranch: <code>${escapeHtml(targetBranch)}</code>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha).slice(0, 10))}</code>\n\nمرحلهٔ بعد فقط درخواست تأیید امن را می‌سازد؛ تا تأیید معتبر مصرف نشود GitHub WRITE اجرا نمی‌شود.`,
308 reply_markup: {
309 inline_keyboard: [
310 [{ text: '✅ تأیید و Commit', callback_data: `wscommit:${workspace.repoId}:${intent.id}` }],
311 [{ text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` }, { text: '📝 Draft', callback_data: `ws:${workspace.id}` }]
312 ]
313 }
314 };
315 };
316
317 const cancelDraft = async (workspaceId, ownerId) => {
318 const workspace = await requireWorkspace(workspaceId, ownerId);
319 await workspaces.cancelWorkspace({ ownerId, workspaceId });
320 return {
321 text: `🗑 <b>Draft لغو شد</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nهیچ تغییری در GitHub انجام نشد.`,
322 reply_markup: { inline_keyboard: [[{ text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }]] }
323 };
324 };
325
326 return {
327 resolveCallback(data, context = {}) {
328 const parsed = parseCallback(data);
329 if (!parsed) return null;
330
331 if (parsed.kind === 'commit') {
332 return {
333 actionId: parsed.actionId,
334 approval: {
335 input: { repoId: parsed.repoId, intentId: parsed.intentId },
336 label: 'Commit روی branch جدید',
337 cancelCallback: `repo:${parsed.repoId}`
338 },
339 audit: { repoId: parsed.repoId, intentId: parsed.intentId },
340 execute: async () => {
341 const ownerId = ownerFrom(context);
342 const result = await commitWorkspaceIntent({
343 github,
344 workspaces,
345 ownerId,
346 repoId: parsed.repoId,
347 intentId: parsed.intentId
348 });
349 const intent = await workspaces.getIntent({ ownerId, intentId: parsed.intentId });
350 const view = workspaceCommitResultView(parsed.repoId, intent, result);
351 return {
352 ...view,
353 audit: {
354 repoId: parsed.repoId,
355 intentId: parsed.intentId,
356 workspaceId: intent?.workspaceId,
357 path: intent?.path,
358 contentDigest: intent?.contentDigest,
359 commitMessageDigest: intent?.commitMessageDigest,
360 baseHeadSha: intent?.baseHeadSha,
361 targetBranch: intent?.targetBranch,
362 commitSha: result.commitSha,
363 branch: result.branch,
364 idempotent: result.idempotent
365 }
366 };
367 }
368 };
369 }
370
371 return {
372 actionId: parsed.actionId,
373 execute: async () => {
374 const ownerId = ownerFrom(context);
375 if (parsed.kind === 'root') return renderDirectory(parsed.repoId, '', ownerId);
376 if (parsed.kind === 'workspace') return renderWorkspace(parsed.workspaceId, ownerId);
377 if (parsed.kind === 'edit') return createDraft(parsed.refId, ownerId);
378 if (parsed.kind === 'input') return prepareInput(parsed.workspaceId, parsed.mode, ownerId);
379 if (parsed.kind === 'diff') return renderDiff(parsed.workspaceId, ownerId);
380 if (parsed.kind === 'ready') return sealReadyIntent(parsed.workspaceId, ownerId);
381 if (parsed.kind === 'cancel') return cancelDraft(parsed.workspaceId, ownerId);
382 const ref = await workspaces.resolveNavigationRef({ ownerId, refId: parsed.refId });
383 if (!ref) throw new Error('Workspace navigation reference is missing or expired');
384 return ref.type === 'dir'
385 ? renderDirectory(ref.repoId, ref.path, ownerId)
386 : renderFile(parsed.refId, ownerId);
387 }
388 };
389 },
390
391 resolveMessage(payload, context = {}) {
392 const pending = payload?.pending;
393 if (!pending || !['draft', 'draft_file', 'commit_message'].includes(String(pending.mode || ''))) return null;
394 if (!new RegExp(`^${HANDLE_10}$`).test(String(pending.workspaceId || ''))) return null;
395 return {
396 actionId: 'github.workspace.input.apply',
397 execute: async () => applyPendingInput({
398 pending,
399 text: String(payload?.text ?? ''),
400 file: payload?.file && typeof payload.file === 'object' ? payload.file : null
401 }, ownerFrom(context))
402 };
403 }
404 };
405 }