import api from './api'; export interface ServerAction { id: string; label: string; toState?: string; gate?: 1 | 2; decision?: 'APPROVED' | 'REJECTED'; disabledReason?: string } // Only advertised IDs select commands; task state never manufactures authorization. const actionCommands: Record = { HOLD_GATE1:{id:'HOLD_GATE1',label:'تعویق تصمیم Gate1',toState:'GATE1_HELD'}, SUBMIT_GATE1:{id:'SUBMIT_GATE1',label:'ارسال برای Gate1',toState:'GATE1_PENDING'}, APPROVE_GATE1:{id:'APPROVE_GATE1',label:'تأیید کار محدود در Gate1',gate:1,decision:'APPROVED'}, REJECT_GATE1:{id:'REJECT_GATE1',label:'رد کار در Gate1',gate:1,decision:'REJECTED'}, QUEUE_PREPARE:{id:'QUEUE_PREPARE',label:'صف‌بندی آماده‌سازی',toState:'READY'}, }; export function normalizeActions(value:unknown):ServerAction[] { if(!Array.isArray(value))return []; const result:ServerAction[]=[]; for(const raw of value){ let action:ServerAction|undefined; if(typeof raw==='string')action=Object.hasOwn(actionCommands,raw)?actionCommands[raw]:undefined; else if(raw&&typeof raw==='object'&&typeof raw.id==='string'){ const fixed=Object.hasOwn(actionCommands,raw.id)?actionCommands[raw.id]:undefined; if(fixed){ if(['toState','gate','decision'].some(k=>raw[k]!==undefined&&raw[k]!==fixed[k as keyof ServerAction]))continue; action={...fixed}; }else if(!raw.toState&&[1,2].includes(raw.gate)&&['APPROVED','REJECTED'].includes(raw.decision)){ // Legacy object format may describe only dedicated gate decisions, never arbitrary transitions. action={id:raw.id,label:raw.id,gate:raw.gate,decision:raw.decision}; } if(action){ if(typeof raw.label==='string'&&raw.label.trim())action={...action,label:raw.label}; if(typeof raw.disabledReason==='string')action={...action,disabledReason:raw.disabledReason}; } } if(action&&!result.some(a=>a.id===action.id))result.push({...action}); } return result; } export interface Artifact { id: string; sha256: string; kind?: string; uri?: string } export interface Run { id: string; commitSha: string; environment: string; status: string; artifacts: Artifact[] } export interface Task { id: string; key: string; title: string; department: string; state: string; version: number; operationMode: string; budgetLimitCents: number; metadata?: Record; availableActions: ServerAction[]; runs?: Run[]; decisions?: Record[]; events?: Record[]; budgetLedger?: Record[] } export interface CommandInput { idempotencyKey: string; reason?: string; expiresAt?: string; runId?: string; artifactHash?: string } export interface TransitionDto {toState:string;expectedVersion:number;idempotencyKey:string;reason?:string} export interface GateDecisionDto {decision:'APPROVED'|'REJECTED';expectedVersion:number;idempotencyKey:string;expiresAt:string;notes?:string;runId?:string;artifactHash?:string;commitSha?:string;environment?:string} export function actionBlockReason(task:Task,action:ServerAction):string|undefined { if(action.gate===2)return 'Gate2 و انتشار در این پنل غیرفعال هستند'; if(action.disabledReason)return 'اقدام توسط سرور غیرفعال شده است: '+action.disabledReason; if(task.operationMode==='MUTATE_PRODUCTION'||['RELEASING','PRODUCTION_VERIFYING','LIVE_VERIFIED'].includes(action.toState??''))return 'عملیات Production در این پنل در دسترس نیست'; if(task.state==='EXPIRED')return 'پیشنهاد منقضی شده است؛ پیشنهاد جدید ایجاد کنید'; if((action.toState&&action.gate)||(!action.toState&&(![1,2].includes(action.gate??0)||!['APPROVED','REJECTED'].includes(action.decision??''))))return 'اقدام سرور پشتیبانی نمی‌شود'; return undefined; } export function commandFailure(error:unknown):{message:string;retryable:boolean} { const status=(error as {response?:{status?:number}})?.response?.status; if(status===409)return {message:'نسخه قدیمی یا تعارض کلید تکرار رخ داده است. وضعیت سرور را بازخوانی و تصمیم تازه را بررسی کنید.',retryable:false}; if(status===410)return {message:'پیشنهاد یا تأیید منقضی شده است. وضعیت را بازخوانی کنید؛ پیشنهاد منقضی به پیشنهاد جدید نیاز دارد.',retryable:false}; if(status===401||status===403)return {message:'سرور این اقدام را رد کرد. پیش از ادامه مجوزها را بازخوانی کنید.',retryable:false}; if(status&&status>=400&&status<500)return {message:'سرور این اقدام را رد کرد (HTTP '+status+'). وضعیت را بازخوانی و پیشنهاد را بررسی کنید.',retryable:false}; return {message:(error instanceof Error?error.message:'درخواست سرور در دسترس نیست')+' — نتیجه نامشخص است. فقط همان داده و کلید را تکرار کنید یا وضعیت را برای تطبیق بازخوانی کنید.',retryable:true}; } export type Resource = 'agents' | 'model-policy' | 'schedules' | 'releases' | 'overview'; export interface ResourceSnapshot { capabilities?: {mutations:boolean;chat:boolean;runtime:boolean;killSwitch?:boolean}; items: Array<{id:string; title?:string; status?:string; department?:string; readiness?:string; model?:string; budgetLimitCents?:number; spentCents?:number; cron?:string; timezone?:string; environment?:string; commitSha?:string; reason?:string}>; measuredAt: string } export const killLevels = ['FREEZE_NEW_WORK','STOP_AGENTS','DISABLE_MUTATIONS','EMERGENCY_HALT'] as const; export type KillLevel = typeof killLevels[number]; export interface ChatMessage {id:string;role:'assistant'|'user';content:string} function unwrap(data: T | {success:boolean;data:T}): T { if (data && typeof data === 'object' && 'success' in data) {if (!data.success) throw new Error('Orchestration request failed'); return data.data;} return data as T; } export interface CreateTaskInput {key:string;title:string;department:string;operationMode:'PREPARE';budgetLimitCents:number;metadata:{commitSha:string;scope:string;acceptanceCriteria:string[]}} export function proposalError(input:CreateTaskInput):string|undefined { if(input.operationMode!=='PREPARE')return 'Only bounded Stage PREPARE proposals are available'; if(!Number.isSafeInteger(input.budgetLimitCents)||input.budgetLimitCents<20||input.budgetLimitCents>10000)return 'PREPARE budget must be an integer 20..10000 cents'; if(typeof input.metadata?.commitSha!=='string'||!/^[a-f0-9]{40}$/.test(input.metadata.commitSha))return 'Immutable commit must be 40 lowercase hex characters'; if(typeof input.metadata?.scope!=='string'||!input.metadata.scope.trim()||input.metadata.scope.length>2000)return 'Scope must be nonblank and at most 2000 characters'; if(!Array.isArray(input.metadata?.acceptanceCriteria)||input.metadata.acceptanceCriteria.length<1||input.metadata.acceptanceCriteria.length>20||input.metadata.acceptanceCriteria.some(value=>typeof value!=='string'||!value.trim()||value.length>500))return 'Acceptance criteria must contain 1..20 nonblank strings of at most 500 characters'; if(!input.key.trim()||input.key.length>120||!input.title.trim()||input.title.length>255||!input.department.trim()||input.department.length>50)return 'کلید (۱ تا ۱۲۰)، عنوان (۱ تا ۲۵۵) و دپارتمان (۱ تا ۵۰ نویسه) الزامی است'; } export const orchestration = { async create(input:CreateTaskInput):Promise { const error=proposalError(input);if(error)throw new Error(error); // Preserve human evidence exactly; workflowScope/environment/identity remain server-owned. return (await api.post('/admin/orchestration/tasks',{key:input.key,title:input.title,department:input.department,operationMode:'PREPARE',budgetLimitCents:input.budgetLimitCents,metadata:{commitSha:input.metadata.commitSha,scope:input.metadata.scope,acceptanceCriteria:[...input.metadata.acceptanceCriteria]}})).data; }, async task(id:string):Promise { const data=unwrap((await api.get('/admin/orchestration/tasks/'+encodeURIComponent(id))).data); if (!data?.id || !Number.isInteger(data.version)) throw new Error('پاسخ جزئیات وظیفه نامعتبر است'); return {...data,availableActions:normalizeActions(data.availableActions)}; }, async resource(name:Resource):Promise { const data=unwrap((await api.get('/admin/orchestration/'+name)).data); if (!Array.isArray(data?.items) || !data.measuredAt) throw new Error('پاسخ نمای ثبت‌شده نامعتبر است'); return data; }, async kill(level:KillLevel,reason:string):Promise { if (!killLevels.includes(level) || !reason.trim()) throw new Error('سطح و دلیل توقف الزامی است'); return (await api.put('/admin/orchestration/kill-switch',{level,reason})).data; }, async chat(sessionId:string,message:string,idempotencyKey:string):Promise { if (!sessionId.trim() || !message.trim() || !idempotencyKey) throw new Error('نشست و پیام الزامی است'); const data=unwrap((await api.post('/admin/orchestration/chat/messages',{sessionId,message,idempotencyKey})).data); if (!data?.id || data.role!=='assistant' || typeof data.content!=='string') throw new Error('پاسخ گفت‌وگو نامعتبر است'); return data; }, async command(task: Task, requested: ServerAction, input: CommandInput): Promise { const action = normalizeActions(task.availableActions).find(a => a.id === requested.id); if (!action || action.disabledReason) throw new Error('اقدام اعلام نشده یا غیرفعال است'); const blocked=actionBlockReason(task,action);if(blocked)throw new Error(blocked); if (!input.idempotencyKey || !Number.isInteger(task.version)) throw new Error('نسخه و کلید جلوگیری از تکرار الزامی است'); const base = '/admin/orchestration/tasks/' + encodeURIComponent(task.id); if (action.gate && action.decision) { if (!input.expiresAt || !(Date.parse(input.expiresAt) > Date.now())) throw new Error('زمان انقضا باید در آینده باشد'); if(['APPROVE_GATE1','REJECT_GATE1'].includes(action.id)&&Date.parse(input.expiresAt)>Date.now()+86400000)throw new Error('انقضای Gate1 باید در ۲۴ ساعت آینده باشد'); let binding = {}; if (action.gate === 2 && action.decision === 'APPROVED') { const run = task.runs?.find(r => r.id === input.runId); if(run?.status!=='SUCCEEDED')throw new Error('Registered successful run binding required for Gate2 evidence'); if (!run?.commitSha || !run.environment || !run.artifacts.some(a => a.sha256 === input.artifactHash)) throw new Error('Registered immutable Gate2 binding required'); binding = {runId:run.id, artifactHash:input.artifactHash, commitSha:run.commitSha, environment:run.environment}; } return (await api.post(base + `/gates/${action.gate}/decide`, {expectedVersion:task.version,idempotencyKey:input.idempotencyKey,decision:action.decision,expiresAt:input.expiresAt,notes:input.reason,...binding})).data; } if (!action.toState) throw new Error('اقدام سرور پشتیبانی نمی‌شود'); return (await api.put(base + '/transition', {toState:action.toState,expectedVersion:task.version,idempotencyKey:input.idempotencyKey,reason:input.reason})).data; }, async tasks(): Promise { const { data } = await api.get('/admin/orchestration/tasks'); const rows = Array.isArray(data) ? data : data.data; if (!Array.isArray(rows)) throw new Error('پاسخ فهرست وظیفه‌ها نامعتبر است'); return rows.map(row => ({ ...row, availableActions: normalizeActions(row.availableActions) })); }, };