Match d43aa02 metadata validation and exact DTO; distinguish missing safe-projection workflow scope from human review evidence. Preserve action normalization and explicit kill-switch capability. TDD regression RED verified; disposable admin 61 files / 381 tests, app+node TypeScript and build pass.
124 lines
11 KiB
TypeScript
124 lines
11 KiB
TypeScript
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<string, ServerAction> = {
|
|
SUBMIT_GATE1:{id:'SUBMIT_GATE1',label:'Submit Gate1',toState:'GATE1_PENDING'},
|
|
APPROVE_GATE1:{id:'APPROVE_GATE1',label:'Approve Gate1',gate:1,decision:'APPROVED'},
|
|
REJECT_GATE1:{id:'REJECT_GATE1',label:'Reject Gate1',gate:1,decision:'REJECTED'},
|
|
QUEUE_PREPARE:{id:'QUEUE_PREPARE',label:'Queue PREPARE',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<string, unknown>; availableActions: ServerAction[]; runs?: Run[]; decisions?: Record<string, unknown>[]; events?: Record<string, unknown>[]; budgetLedger?: Record<string, unknown>[] }
|
|
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.disabledReason)return action.disabledReason;
|
|
if(task.operationMode==='MUTATE_PRODUCTION'||['RELEASING','PRODUCTION_VERIFYING','LIVE_VERIFIED'].includes(action.toState??''))return 'Production actions are unavailable in this panel';
|
|
if(task.state==='EXPIRED')return 'Expired proposal: create a fresh proposal';
|
|
if((action.toState&&action.gate)||(!action.toState&&(![1,2].includes(action.gate??0)||!['APPROVED','REJECTED'].includes(action.decision??''))))return 'Unsupported server action';
|
|
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:'Stale version or idempotency conflict. Refresh authoritative state and review a fresh decision.',retryable:false};
|
|
if(status===410)return {message:'Proposal or approval expired. Refresh; expired proposals require a new proposal.',retryable:false};
|
|
if(status===401||status===403)return {message:'Backend denied this action. Refresh permissions before continuing.',retryable:false};
|
|
if(status&&status>=400&&status<500)return {message:'Backend rejected this action (HTTP '+status+'). Refresh and review the proposal.',retryable:false};
|
|
return {message:(error instanceof Error?error.message:'Backend request unavailable')+' — Outcome unknown. Retry only the identical payload/key, or refresh to reconcile.',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<T>(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 'Proposal requires key (1..120), title (1..255), department (1..50)';
|
|
}
|
|
export const orchestration = {
|
|
async create(input:CreateTaskInput):Promise<unknown> {
|
|
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<Task> {
|
|
const data=unwrap<Task>((await api.get('/admin/orchestration/tasks/'+encodeURIComponent(id))).data);
|
|
if (!data?.id || !Number.isInteger(data.version)) throw new Error('Invalid task detail');
|
|
return {...data,availableActions:normalizeActions(data.availableActions)};
|
|
},
|
|
async resource(name:Resource):Promise<ResourceSnapshot> {
|
|
const data=unwrap<ResourceSnapshot>((await api.get('/admin/orchestration/'+name)).data);
|
|
if (!Array.isArray(data?.items) || !data.measuredAt) throw new Error('Invalid resource snapshot');
|
|
return data;
|
|
},
|
|
async kill(level:KillLevel,reason:string):Promise<unknown> {
|
|
if (!killLevels.includes(level) || !reason.trim()) throw new Error('Kill switch level and reason required');
|
|
return (await api.put('/admin/orchestration/kill-switch',{level,reason})).data;
|
|
},
|
|
async chat(sessionId:string,message:string,idempotencyKey:string):Promise<ChatMessage> {
|
|
if (!sessionId.trim() || !message.trim() || !idempotencyKey) throw new Error('Session and message required');
|
|
const data=unwrap<ChatMessage>((await api.post('/admin/orchestration/chat/messages',{sessionId,message,idempotencyKey})).data);
|
|
if (!data?.id || data.role!=='assistant' || typeof data.content!=='string') throw new Error('Invalid typed chat reply');
|
|
return data;
|
|
},
|
|
async command(task: Task, requested: ServerAction, input: CommandInput): Promise<unknown> {
|
|
const action = normalizeActions(task.availableActions).find(a => a.id === requested.id);
|
|
if (!action || action.disabledReason) throw new Error('Action is not advertised or is disabled');
|
|
const blocked=actionBlockReason(task,action);if(blocked)throw new Error(blocked);
|
|
if (!input.idempotencyKey || !Number.isInteger(task.version)) throw new Error('Version and idempotency key required');
|
|
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('Future expiry required');
|
|
if(['APPROVE_GATE1','REJECT_GATE1'].includes(action.id)&&Date.parse(input.expiresAt)>Date.now()+86400000)throw new Error('Gate1 expiry must be within 24 hours');
|
|
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('Unsupported server action');
|
|
return (await api.put(base + '/transition', {toState:action.toState,expectedVersion:task.version,idempotencyKey:input.idempotencyKey,reason:input.reason})).data;
|
|
},
|
|
async tasks(): Promise<Task[]> {
|
|
const { data } = await api.get('/admin/orchestration/tasks');
|
|
const rows = Array.isArray(data) ? data : data.data;
|
|
if (!Array.isArray(rows)) throw new Error('Invalid orchestration task response');
|
|
return rows.map(row => ({ ...row, availableActions: normalizeActions(row.availableActions) }));
|
|
},
|
|
};
|