Chancellor / orchestratorService.ts
VoidBreach's picture
Upload 62 files
35b8b9c verified
Raw History Blame Contribute Delete
6.54 kB
import { TaskWorkflow } from '../types';
import { DatasetService } from './datasetService';
import { ObservabilityService } from './observabilityService';
export const OrchestratorService = {
async initiateStellarOrchestration(
goal: string,
corpusType: 'ARXIV' | 'NASA',
): Promise<TaskWorkflow> {
ObservabilityService.logAction('STELLAR_ORCHESTRATION_INIT', { goal, corpusType });
// 1. Ingest Data
await DatasetService.ingestScholasticCorpus(corpusType);
// 2. Create Workflow
const workflow: TaskWorkflow = {
id: `WORKFLOW-${Date.now()}`,
goal,
steps: [
{ id: 'INGEST', description: 'Corpus Ingested', status: 'complete' },
{ id: 'DISTILL', description: 'Data Distillation', status: 'pending' },
{ id: 'HYPOTHESIS', description: 'Hypothesis Generation', status: 'pending' },
{ id: 'VALIDATE', description: 'Cross-Validation', status: 'pending' },
],
currentStepIndex: 1, // Moving to Distill
assignedAgentIds: [],
};
ObservabilityService.logAction('STELLAR_ORCHESTRATION_READY', { workflowId: workflow.id });
return workflow;
},
async advanceWorkflow(workflow: TaskWorkflow): Promise<TaskWorkflow> {
if (!workflow || !workflow.steps) {
ObservabilityService.logError(
'Invalid workflow object',
'STELLAR_ORCHESTRATION_NULL_WORKFLOW',
);
return workflow;
}
if (workflow.currentStepIndex >= workflow.steps.length) return workflow;
const currentStep = workflow.steps[workflow.currentStepIndex];
ObservabilityService.logAction('STELLAR_ORCHESTRATION_STEP', { stepId: currentStep.id });
// Perform logic based on step
switch (currentStep.id) {
case 'DISTILL':
// Logic: Distill raw data into insights
break;
case 'HYPOTHESIS':
// Logic: Generate theories
break;
case 'VALIDATE':
// Logic: Rigorous cross-validation
break;
}
currentStep.status = 'complete';
workflow.currentStepIndex++;
if (workflow.currentStepIndex < workflow.steps.length) {
workflow.steps[workflow.currentStepIndex].status = 'active';
}
return workflow;
},
createWorkflow(goal: string, assignedAgentIds: string[]): TaskWorkflow {
return {
id: `WORKFLOW-${Date.now()}`,
goal,
steps: [{ id: 'S1', description: 'Initiating planning', status: 'pending' }],
currentStepIndex: 0,
assignedAgentIds,
};
},
async estimateTaskExecution(taskDescription: string): Promise<number> {
// Advanced Heuristic: Scholastic Complexity Index
const baseComplexity = taskDescription.length / 10;
// Cognitive Load Multipliers
const heavyKeywords = [
{ word: 'synthesis', multiplier: 1.8 },
{ word: 'orchestrate', multiplier: 1.5 },
{ word: 'decompile', multiplier: 2.2 },
{ word: 'analyze', multiplier: 1.3 },
{ word: 'quantum', multiplier: 2.5 },
{ word: 'biometric', multiplier: 1.9 },
{ word: 'singularity', multiplier: 3.0 },
{ word: 'recursive', multiplier: 1.7 },
{ word: 'cryptic', multiplier: 1.4 },
];
let multiplier = 1;
heavyKeywords.forEach(({ word, multiplier: m }) => {
if (taskDescription.toLowerCase().includes(word)) multiplier *= m;
});
// Penalty for lack of structure in prompt
if (taskDescription.split(' ').length < 5) multiplier *= 1.5;
const estimate = baseComplexity * 10 * multiplier;
// Log for observability
ObservabilityService.logAction('TASK_ESTIMATION', {
taskDescription: taskDescription.substring(0, 30),
estimate,
});
return estimate;
},
async performAgentStitching(
workflow: TaskWorkflow,
chancellorFn: (p: string) => Promise<string>,
): Promise<TaskWorkflow> {
ObservabilityService.logAction('AGENT_STITCHING_INIT', { workflowId: workflow.id });
const prompt = `
SCHOLASTIC_ACADEMY: AGENT_STITCHING_PROTOCOL
The current task has exceeded the sub-second cognitive reflex threshold (>400ms).
G-TASK: "${workflow.goal}"
CHANCELLOR_REQUIREMENT:
Decompose this scholastic intent into exactly 4 parallelized sub-tasks.
For each segment, assign a specialist role (SCOUT, ARCHITECT, ENFORCER, LIBRARIAN) and identify appropriate tool calls.
TOOL_REGISTRY_AVAILABLE:
- queryGrandLibrary: Access archived dissertations.
- scoutResearch: Fetch academic findings from external clusters.
- acquireWealth: Gain technical/architectural assets.
- auditIntegrity: Verify scholastic alignment.
- neuralSynthesis: Integrate findings into the neuro-hive.
OUTPUT_FORMAT: JSON array of steps.
[{
"id": "STITCH-1",
"description": "Clear academic instruction",
"assignedAgentId": "AGENT_ROLE_PLACEHOLDER",
"targetTools": ["toolName1", "toolName2"],
"executionEstimateMs": 120
}]
Note: assignedAgentId should be one of the provided roles.
`;
try {
const response = await chancellorFn(prompt);
// Strip markdown code blocks if present
const jsonMatch = response.match(/\[[\s\S]*\]/);
const cleanJson = jsonMatch ? jsonMatch[0] : response.replace(/```json|```/g, '').trim();
const stitchedStepsRaw = JSON.parse(cleanJson);
const stitchedSteps = Array.isArray(stitchedStepsRaw)
? stitchedStepsRaw
: stitchedStepsRaw.steps || [];
workflow.steps = (stitchedSteps || []).map((s: any) => ({
...s,
status: 'pending',
}));
workflow.isStitched = true;
ObservabilityService.logAction('AGENT_STITCHING_SUCCESS', {
workflowId: workflow.id,
stepCount: workflow.steps.length,
totalEstimate: workflow.steps.reduce(
(acc: number, s: any) => acc + (s.executionEstimateMs || 0),
0,
),
});
} catch (err) {
ObservabilityService.logError('AGENT_STITCHING_FAILED', 'STALL_ERROR');
// Fallback: Default segmentation
workflow.steps = [
{
id: 'S1',
description: 'Emergency Scout: Fragmented Intent',
status: 'pending',
assignedAgentId: 'SCOUT',
},
{
id: 'S2',
description: 'Emergency Architect: Structural Recovery',
status: 'pending',
assignedAgentId: 'ARCHITECT',
},
];
workflow.isStitched = true;
}
return workflow;
},
};