-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathworkflow-engine.ts
More file actions
1889 lines (1662 loc) · 60.5 KB
/
workflow-engine.ts
File metadata and controls
1889 lines (1662 loc) · 60.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
WORKFLOW_STAGES,
type AgentHandle,
type FinalWorkflowReportRecord,
type TaskRecord,
type WorkflowRuntime,
type WorkflowStage,
type WorkflowStatus,
} from "../../shared/workflow-runtime.js";
import type {
WorkflowOrganizationDepartment,
WorkflowOrganizationNode,
WorkflowOrganizationSnapshot,
} from "../../shared/organization-schema.js";
import type { ExternalAgentNode } from "../../shared/organization-schema.js";
import { A2AClient } from "./a2a-client.js";
import type { PhaseAssignment } from "../../shared/role-schema.js";
import type { ExecutionPlan } from "../../shared/executor/contracts.js";
import type { AutonomyConfig } from "../../shared/autonomy-types.js";
import type { TaskAllocator } from "./task-allocator.js";
import type { CompetitionEngine, CompetitionTaskRequest } from "./competition-engine.js";
import type { TaskforceManager } from "./taskforce-manager.js";
import type { TaskRequest } from "./self-assessment.js";
import type { ExecutionBridge, BridgeResult } from "./execution-bridge.js";
import { Agent } from "./agent.js";
import { getAIConfig } from "./ai-config.js";
import {
generateWorkflowOrganization,
materializeWorkflowOrganization,
persistOrganizationDebugLog,
skillRegistry,
} from "./dynamic-organization.js";
import { SkillActivator } from "./skill-activator.js";
import { SkillMonitor } from "./skill-monitor.js";
import { serverRuntime } from "../runtime/server-runtime.js";
import {
buildWorkflowDirectiveContext,
buildWorkflowInputSignature,
type WorkflowInputAttachment,
} from "../../shared/workflow-input.js";
import type { TokenService } from "../permission/token-service.js";
import { guestLifecycleManager } from "./guest-lifecycle.js";
import { isGuestId } from "../../shared/guest-agent-utils.js";
interface WorkflowStartOptions {
attachments?: WorkflowInputAttachment[];
directiveContext?: string;
inputSignature?: string;
}
export const V3_STAGES = WORKFLOW_STAGES;
export type Stage = WorkflowStage;
interface ManagerPlan {
plan_summary: string;
tasks: Array<{
worker_id: string;
description: string;
}>;
}
interface ReviewScore {
accuracy: number;
completeness: number;
actionability: number;
format: number;
total: number;
feedback: string;
}
interface VerifyResult {
items: Array<{ point: string; addressed: boolean; comment: string }>;
unaddressed_ratio: number;
verdict: "pass" | "needs_v3";
}
interface WorkflowIssue {
stage: Stage;
scope: "workflow" | "task" | "agent";
severity: "warning" | "error";
message: string;
timestamp: string;
taskId?: number;
agentId?: string;
}
function createWorkflowId(): string {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return `wf_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
}
function bestDeliverable(task: TaskRecord): string {
return task.deliverable_v3 || task.deliverable_v2 || task.deliverable || "(no deliverable)";
}
async function runWithConcurrencyLimit<T>(
items: T[],
limit: number,
handler: (item: T) => Promise<void>
): Promise<void> {
const concurrency = Math.max(1, limit);
let index = 0;
const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
while (index < items.length) {
const current = items[index++];
await handler(current);
}
});
await Promise.all(workers);
}
export class WorkflowEngine {
/** Optional autonomy configuration 鈥?when enabled, activates intelligent task allocation. */
autonomyConfig?: AutonomyConfig;
/** Intelligent task allocator 鈥?used only when autonomyConfig.enabled is true. */
taskAllocator?: TaskAllocator;
/** Competition engine for high-value tasks 鈥?used only when autonomyConfig.enabled is true. */
competitionEngine?: CompetitionEngine;
/** Taskforce manager for collaborative tasks 鈥?used only when autonomyConfig.enabled is true. */
taskforceManager?: TaskforceManager;
/** Optional ExecutionBridge 鈥?when set, bridges workflow deliverables to Docker execution after the execution stage. */
executionBridge?: ExecutionBridge;
/** Optional permission token service 鈥?when set, issues CapabilityTokens to agents at workflow start. */
tokenService?: TokenService;
/** Lazy A2A client for routing tasks to external framework agents. */
private a2aClient = new A2AClient();
constructor(private readonly runtime: WorkflowRuntime) {}
/** Type guard: checks whether a node is an ExternalAgentNode. */
private isExternalAgent(node: WorkflowOrganizationNode): node is ExternalAgentNode {
return "frameworkType" in node && "a2aEndpoint" in node;
}
protected get repo() {
return this.runtime.workflowRepo;
}
protected emit(event: Parameters<WorkflowRuntime["eventEmitter"]["emit"]>[0]) {
this.runtime.eventEmitter.emit(event);
}
protected isTemporaryLLMError(error: unknown): boolean {
return this.runtime.llmProvider.isTemporarilyUnavailable?.(error) || false;
}
private getWorkflowDirectiveContext(workflowId: string, fallbackDirective: string) {
const workflow = this.repo.getWorkflow(workflowId);
const inputContext = workflow?.results?.input?.directiveContext;
return typeof inputContext === "string" && inputContext.trim()
? inputContext
: fallbackDirective;
}
async startWorkflow(
directive: string,
options: WorkflowStartOptions = {}
): Promise<string> {
const workflowId = createWorkflowId();
const attachments = Array.isArray(options.attachments) ? options.attachments : [];
const directiveContext =
options.directiveContext ||
buildWorkflowDirectiveContext(directive, attachments);
const inputSignature =
options.inputSignature ||
buildWorkflowInputSignature(directive, attachments);
this.repo.createWorkflow(workflowId, directive, []);
this.repo.updateWorkflow(workflowId, {
status: "running",
started_at: new Date().toISOString(),
results: {
input: {
attachments,
directiveContext,
signature: inputSignature,
},
},
});
this.runPipeline(workflowId, directiveContext).catch((error: any) => {
const workflow = this.repo.getWorkflow(workflowId);
this.repo.updateWorkflow(workflowId, {
status: "failed",
results: {
...(workflow?.results || {}),
last_error: error.message,
failed_stage: workflow?.current_stage || null,
},
});
this.emit({ type: "workflow_error", workflowId, error: error.message });
});
return workflowId;
}
private async runPipeline(workflowId: string, directive: string): Promise<void> {
try {
const organization = await this.runDirection(workflowId, directive);
await this.emitStageCompleted(workflowId, "direction");
await this.runPlanning(workflowId, organization);
await this.emitStageCompleted(workflowId, "planning");
await this.runExecution(workflowId, organization);
await this.emitStageCompleted(workflowId, "execution");
// 鈹€鈹€ ExecutionBridge: bridge deliverables to Docker executor 鈹€鈹€
await this.bridgeToExecutor(workflowId);
await this.runReview(workflowId, organization);
await this.emitStageCompleted(workflowId, "review");
await this.runMetaAudit(workflowId, organization);
await this.emitStageCompleted(workflowId, "meta_audit");
await this.runRevision(workflowId);
await this.emitStageCompleted(workflowId, "revision");
await this.runVerify(workflowId);
await this.emitStageCompleted(workflowId, "verify");
await this.runSummary(workflowId, organization);
await this.emitStageCompleted(workflowId, "summary");
await this.runFeedback(workflowId, organization);
await this.emitStageCompleted(workflowId, "feedback");
await this.runEvolution(workflowId);
await this.emitStageCompleted(workflowId, "evolution");
let finalStatus = this.getCompletionStatus(workflowId);
this.repo.updateWorkflow(workflowId, {
status: finalStatus,
completed_at: new Date().toISOString(),
});
try {
this.persistFinalReport(workflowId, organization);
} catch (reportError: any) {
this.recordWorkflowIssue(workflowId, {
stage: "summary",
scope: "workflow",
severity: "warning",
message: `Final report persistence failed: ${reportError.message}`,
});
finalStatus = "completed_with_errors";
const workflow = this.repo.getWorkflow(workflowId);
this.repo.updateWorkflow(workflowId, {
status: finalStatus,
results: {
...(workflow?.results || {}),
report_error: reportError.message,
},
});
}
this.runtime.memoryRepo.materializeWorkflowMemories(workflowId);
// Clean up all guest agents after mission completion (Requirements 5.5)
try {
await guestLifecycleManager.onMissionComplete(workflowId);
} catch (cleanupError: any) {
console.warn(
`[WorkflowEngine] Guest agent cleanup after completion failed: ${cleanupError.message}`,
);
}
this.emit({
type: "workflow_complete",
workflowId,
status: finalStatus,
summary:
finalStatus === "completed_with_errors"
? "Workflow completed with recoverable errors"
: "Workflow completed successfully",
});
} catch (error: any) {
const workflow = this.repo.getWorkflow(workflowId);
this.repo.updateWorkflow(workflowId, {
status: "failed",
results: {
...(workflow?.results || {}),
last_error: error.message,
failed_stage: workflow?.current_stage || null,
},
});
this.runtime.memoryRepo.materializeWorkflowMemories(workflowId);
// Clean up all guest agents after mission failure (Requirements 5.5)
try {
await guestLifecycleManager.onMissionFailed(workflowId);
} catch (cleanupError: any) {
console.warn(
`[WorkflowEngine] Guest agent cleanup after failure failed: ${cleanupError.message}`,
);
}
this.emit({ type: "workflow_error", workflowId, error: error.message });
throw error;
}
}
/** Execution-type role IDs used for allowSelfReview detection */
private static readonly EXECUTION_ROLES = new Set(["coder", "writer"]);
/** Review-type role IDs used for allowSelfReview detection */
private static readonly REVIEW_ROLES = new Set(["reviewer", "qa"]);
/**
* Handle role switching between phases.
* Detects agent-role assignment differences and executes role switches.
* @see Requirements 5.2, 5.3, 5.4
*/
private async handlePhaseRoleSwitch(
workflowId: string,
currentStepKey: string,
nextStepKey: string,
plan: ExecutionPlan
): Promise<void> {
const currentStep = plan.steps.find(s => s.key === currentStepKey);
const nextStep = plan.steps.find(s => s.key === nextStepKey);
if (!currentStep?.assignments?.length || !nextStep?.assignments?.length) {
return;
}
// Build lookup of current assignments by agentId
const currentMap = new Map<string, string>();
for (const a of currentStep.assignments) {
currentMap.set(a.agentId, a.roleId);
}
// Enforce allowSelfReview constraint (default false)
const allAgentIds = Array.from(new Set([
...currentStep.assignments.map(a => a.agentId),
...nextStep.assignments.map(a => a.agentId),
]));
const adjustedAssignments = this.enforceAllowSelfReview(
nextStep.assignments,
currentStep.assignments,
allAgentIds,
false, // allowSelfReview defaults to false
);
// Detect differences and execute role switches
for (const nextAssignment of adjustedAssignments) {
const currentRoleId = currentMap.get(nextAssignment.agentId) ?? null;
// Skip if the agent keeps the same role
if (currentRoleId === nextAssignment.roleId) {
continue;
}
try {
const agentHandle = this.getAgent(nextAssignment.agentId);
// Only perform role switching on concrete Agent instances (server runtime)
if (agentHandle instanceof Agent) {
await agentHandle.switchRole(nextAssignment.roleId, workflowId);
console.log(
`[WorkflowEngine] Phase role switch: agent=${nextAssignment.agentId} ` +
`from=${currentRoleId} to=${nextAssignment.roleId} ` +
`(${currentStepKey} 鈫?${nextStepKey})`,
);
}
} catch (err) {
console.warn(
`[WorkflowEngine] Role switch failed for agent ${nextAssignment.agentId}: ` +
`${err instanceof Error ? err.message : err}`,
);
this.recordWorkflowIssue(workflowId, {
stage: nextStepKey as Stage,
scope: "agent",
severity: "warning",
agentId: nextAssignment.agentId,
message: `Phase role switch failed (${currentRoleId} 鈫?${nextAssignment.roleId}): ${
err instanceof Error ? err.message : String(err)
}`,
});
}
}
}
/**
* When allowSelfReview is false (default), prevent an agent from reviewing
* its own output when switching from execution role to review role.
* @see Requirements 5.3, 5.4
*/
private enforceAllowSelfReview(
assignments: PhaseAssignment[],
previousAssignments: PhaseAssignment[],
allAgentIds: string[],
allowSelfReview: boolean
): PhaseAssignment[] {
if (allowSelfReview) {
return assignments;
}
// Build set of agents that had execution roles in the previous phase
const executionAgents = new Set<string>();
for (const prev of previousAssignments) {
if (WorkflowEngine.EXECUTION_ROLES.has(prev.roleId.toLowerCase())) {
executionAgents.add(prev.agentId);
}
}
if (executionAgents.size === 0) {
return assignments;
}
const result: PhaseAssignment[] = [];
for (const assignment of assignments) {
const isReviewRole = WorkflowEngine.REVIEW_ROLES.has(assignment.roleId.toLowerCase());
const wasExecutor = executionAgents.has(assignment.agentId);
if (isReviewRole && wasExecutor) {
// Find an alternative agent that was NOT an executor in the previous phase
const alternativeAgentId = allAgentIds.find(
id =>
id !== assignment.agentId &&
!executionAgents.has(id) &&
// Ensure the alternative isn't already assigned a review role in this batch
!result.some(r => r.agentId === id && r.roleId === assignment.roleId),
);
if (alternativeAgentId) {
console.log(
`[WorkflowEngine] allowSelfReview=false: reassigning review ` +
`from ${assignment.agentId} to ${alternativeAgentId} (role=${assignment.roleId})`,
);
result.push({ agentId: alternativeAgentId, roleId: assignment.roleId });
} else {
// No alternative available 鈥?keep original assignment with a warning
console.warn(
`[WorkflowEngine] allowSelfReview=false: no alternative agent available ` +
`for review role ${assignment.roleId}, keeping ${assignment.agentId}`,
);
result.push(assignment);
}
} else {
result.push(assignment);
}
}
return result;
}
private emitStage(workflowId: string, stage: Stage): void {
this.repo.updateWorkflow(workflowId, { current_stage: stage });
this.emit({ type: "stage_change", workflowId, stage });
}
/**
* Emit a stage_complete event and invoke the optional onStageCompleted callback.
* Called from runPipeline after each stage finishes successfully.
*/
private async emitStageCompleted(workflowId: string, completedStage: string): Promise<void> {
this.emit({ type: "stage_complete", workflowId, stage: completedStage });
try {
await this.runtime.onStageCompleted?.(workflowId, completedStage);
} catch (err) {
console.warn(
`[WorkflowEngine] onStageCompleted callback failed for ${workflowId}/${completedStage}:`,
err instanceof Error ? err.message : err,
);
}
}
/**
* Bridge workflow deliverables to Docker executor after the execution stage.
* Collects all task deliverables, resolves the linked missionId, and calls
* ExecutionBridge.bridge(). Failures are recorded as workflow issues but
* never block the pipeline.
*/
private async bridgeToExecutor(workflowId: string): Promise<void> {
if (!this.executionBridge) return;
const missionId = this.runtime.resolveMissionId?.(workflowId);
if (!missionId) {
console.warn(
`[WorkflowEngine] bridgeToExecutor: no missionId found for workflow ${workflowId}, skipping.`,
);
return;
}
// Collect all task deliverables for this workflow
const tasks = this.repo.getTasksByWorkflow(workflowId);
const deliverables = tasks
.map((t) => bestDeliverable(t))
.filter((d) => d !== "(no deliverable)");
if (deliverables.length === 0) {
return;
}
// Collect mission metadata from workflow results
const workflow = this.repo.getWorkflow(workflowId);
const metadata: Record<string, unknown> = {
workflowId,
...(workflow?.results?.input ?? {}),
};
try {
const result: BridgeResult = await this.executionBridge.bridge(
missionId,
deliverables,
metadata,
);
if (result.triggered) {
console.log(
`[WorkflowEngine] ExecutionBridge triggered for workflow ${workflowId}: ` +
`jobId=${result.jobId ?? "n/a"}, reason=${result.reason}`,
);
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.warn(
`[WorkflowEngine] bridgeToExecutor failed for workflow ${workflowId}: ${message}`,
);
this.recordWorkflowIssue(workflowId, {
stage: "execution",
scope: "workflow",
severity: "warning",
message: `ExecutionBridge failed: ${message}`,
});
}
}
private recordWorkflowIssue(
workflowId: string,
issue: Omit<WorkflowIssue, "timestamp">
): void {
const workflow = this.repo.getWorkflow(workflowId);
if (!workflow) return;
const issues = Array.isArray(workflow.results?.workflow_issues)
? [...workflow.results.workflow_issues]
: [];
issues.push({ ...issue, timestamp: new Date().toISOString() });
this.repo.updateWorkflow(workflowId, {
results: {
...(workflow.results || {}),
workflow_issues: issues,
},
});
}
private hasWorkflowIssues(workflowId: string): boolean {
const workflow = this.repo.getWorkflow(workflowId);
return (
Array.isArray(workflow?.results?.workflow_issues) &&
workflow.results.workflow_issues.length > 0
);
}
private getCompletionStatus(workflowId: string): WorkflowStatus {
return this.hasWorkflowIssues(workflowId)
? "completed_with_errors"
: "completed";
}
private getOrganization(workflowId: string): WorkflowOrganizationSnapshot {
const workflow = this.repo.getWorkflow(workflowId);
const organization = workflow?.results?.organization as WorkflowOrganizationSnapshot | undefined;
if (!organization?.nodes?.length) {
throw new Error("Workflow organization is not available.");
}
return organization;
}
private getNodeMap(organization: WorkflowOrganizationSnapshot) {
return new Map(organization.nodes.map(node => [node.id, node]));
}
private getRootNode(organization: WorkflowOrganizationSnapshot): WorkflowOrganizationNode {
const root = organization.nodes.find(node => node.id === organization.rootNodeId);
if (!root) {
throw new Error("Root organization node not found.");
}
return root;
}
private getManagerNode(
organization: WorkflowOrganizationSnapshot,
department: WorkflowOrganizationDepartment
): WorkflowOrganizationNode {
const node = organization.nodes.find(item => item.id === department.managerNodeId);
if (!node) {
throw new Error(`Manager node missing for department ${department.id}.`);
}
return node;
}
private getWorkersForManager(
organization: WorkflowOrganizationSnapshot,
managerNode: WorkflowOrganizationNode
): WorkflowOrganizationNode[] {
return organization.nodes.filter(
node => node.parentId === managerNode.id && node.role === "worker"
);
}
private getAuditNodes(organization: WorkflowOrganizationSnapshot): WorkflowOrganizationNode[] {
return organization.nodes.filter(node => node.execution.mode === "audit");
}
private getAgent(agentId: string): AgentHandle {
return this.runtime.agentDirectory.get(agentId) || Agent.fromDB(agentId) || (() => {
throw new Error(`Agent ${agentId} is not available.`);
})();
}
private applyDefaultReview(task: TaskRecord, feedback: string): void {
this.repo.updateTask(task.id, {
score_accuracy: 3,
score_completeness: 3,
score_actionability: 3,
score_format: 3,
total_score: 12,
manager_feedback: feedback,
status: "reviewed",
});
}
private async runDirection(
workflowId: string,
directive: string
): Promise<WorkflowOrganizationSnapshot> {
this.emitStage(workflowId, "direction");
const rootStatusPlaceholder = `wf-${workflowId.replace(/[^a-zA-Z0-9]/g, "").slice(0, 10).toLowerCase()}-root`;
this.emit({
type: "agent_active",
agentId: rootStatusPlaceholder,
action: "analyzing",
workflowId,
});
const aiConfig = getAIConfig();
const { organization, debug } = await generateWorkflowOrganization({
workflowId,
directive,
llmProvider: this.runtime.llmProvider,
model: aiConfig.model,
});
materializeWorkflowOrganization(organization);
// Issue CapabilityTokens for each agent in the organization (opt-in)
if (this.tokenService) {
for (const node of organization.nodes) {
try {
const capToken = this.tokenService.issueToken(node.agentId);
const agent = this.getAgent(node.agentId);
if (agent instanceof Agent && typeof agent.setPermissionToken === "function") {
agent.setPermissionToken(capToken.token);
}
} catch {
// Token issuance failure must not block workflow execution
// Agent will operate without permission checks (backward compatible)
}
}
}
const debugLogPath = persistOrganizationDebugLog(organization, debug);
const rootNode = this.getRootNode(organization);
this.repo.updateWorkflow(workflowId, {
departments_involved: organization.departments.map(item => item.id),
results: {
...(this.repo.getWorkflow(workflowId)?.results || {}),
organization,
organization_debug: {
...debug,
logPath: debugLogPath,
},
},
});
this.emit({
type: "agent_active",
agentId: rootNode.agentId,
action: "analyzing",
workflowId,
});
for (const department of organization.departments) {
const managerNode = this.getManagerNode(organization, department);
await this.runtime.messageBus.send(
rootNode.agentId,
managerNode.agentId,
department.direction,
workflowId,
"direction",
{
departmentLabel: department.label,
strategy: department.strategy,
maxConcurrency: department.maxConcurrency,
skills: managerNode.skills.map(skill => skill.id),
mcp: managerNode.mcp.map(item => item.id),
}
);
}
this.emit({
type: "agent_active",
agentId: rootNode.agentId,
action: "idle",
workflowId,
});
return organization;
}
private async runPlanning(
workflowId: string,
organization: WorkflowOrganizationSnapshot
): Promise<void> {
this.emitStage(workflowId, "planning");
const managers = organization.departments.map(department => ({
department,
managerNode: this.getManagerNode(organization, department),
}));
await Promise.all(
managers.map(async ({ department, managerNode }) => {
const manager = this.getAgent(managerNode.agentId);
const workers = this.getWorkersForManager(organization, managerNode);
const inbox = await this.runtime.messageBus.getInbox(managerNode.agentId, workflowId);
const directionMessage = inbox.find(message => message.stage === "direction");
if (!directionMessage) return;
this.emit({
type: "agent_active",
agentId: managerNode.agentId,
action: "planning",
workflowId,
});
const plan = await manager.invokeJson<ManagerPlan>(
`You are planning work for ${department.label}.
Department direction:
${directionMessage.content}
Execution policy:
- strategy: ${department.strategy}
- max concurrency: ${department.maxConcurrency}
Available workers:
${workers
.map(
worker =>
`- ${worker.agentId}: ${worker.name} / ${worker.title}\n responsibility: ${worker.responsibility}\n skills: ${worker.skills.map(skill => skill.name).join(", ")}\n MCP: ${worker.mcp.map(item => item.name).join(", ")}`
)
.join("\n")}
Return valid JSON only:
{
"plan_summary": "brief department execution plan",
"tasks": [
{
"worker_id": "one of the worker ids above",
"description": "clear executable task"
}
]
}
Rules:
- Only assign work to listed worker ids.
- Give the smallest set of tasks that still covers the department direction.
- Make each task specific enough that the worker can respond directly.`,
undefined,
{ workflowId, stage: "planning" }
);
for (const task of plan.tasks || []) {
const workerNode = workers.find(worker => worker.agentId === task.worker_id);
if (!workerNode) continue;
// 鈹€鈹€鈹€ Autonomy-aware task allocation 鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€
let assignedWorkerNode = workerNode;
if (this.autonomyConfig?.enabled && this.taskAllocator) {
try {
const taskRequest: TaskRequest = {
taskId: `${workflowId}-${department.id}-${task.worker_id}-${Date.now()}`,
requiredSkills: workerNode.skills.map(s => s.id),
requiredSkillWeights: new Map(
workerNode.skills.map(s => [s.id, 1.0]),
),
};
const allocationDecision = await this.taskAllocator.allocateTask(taskRequest);
// Handle TASKFORCE strategy 鈥?form a taskforce when REQUEST_ASSIST
if (
allocationDecision.strategy === 'TASKFORCE' &&
this.taskforceManager
) {
try {
const session = await this.taskforceManager.formTaskforce(
taskRequest,
allocationDecision.assignedAgentId,
);
console.log(
`[WorkflowEngine] Taskforce formed: ${session.taskforceId} ` +
`for task ${taskRequest.taskId}, lead=${session.leadAgentId}`,
);
} catch (tfErr) {
console.warn(
`[WorkflowEngine] Taskforce formation failed, using allocated agent: ` +
`${tfErr instanceof Error ? tfErr.message : tfErr}`,
);
}
}
// Check if competition mode should be triggered
if (this.competitionEngine && allocationDecision.assessments.length > 0) {
const bestFitness = Math.max(
...allocationDecision.assessments.map(a => a.fitnessScore),
);
const competitionTask: CompetitionTaskRequest = {
...taskRequest,
priority: 'normal',
qualityRequirement: 'normal',
dataSecurityLevel: 'normal',
estimatedDurationMs: 60_000,
manualCompetition: false,
historicalFailRate: 0,
descriptionAmbiguity: 0,
};
if (this.competitionEngine.shouldTrigger(competitionTask, bestFitness)) {
try {
const contestants = this.competitionEngine.selectContestants(
allocationDecision.assessments.map(a => a.agentId),
this.autonomyConfig.competition.defaultContestantCount,
);
if (contestants.length >= 2) {
const deadline = this.competitionEngine.computeDeadline(
competitionTask.estimatedDurationMs,
);
const session = await this.competitionEngine.runCompetition(
competitionTask,
contestants,
deadline,
);
console.log(
`[WorkflowEngine] Competition started: ${session.id} ` +
`for task ${taskRequest.taskId}, contestants=${contestants.length}`,
);
}
} catch (compErr) {
console.warn(
`[WorkflowEngine] Competition failed, using direct allocation: ` +
`${compErr instanceof Error ? compErr.message : compErr}`,
);
}
}
}
// Resolve the allocated agent to a worker node (if different)
if (allocationDecision.assignedAgentId && allocationDecision.assignedAgentId !== workerNode.agentId) {
const alternativeNode = workers.find(
w => w.agentId === allocationDecision.assignedAgentId,
);
if (alternativeNode) {
assignedWorkerNode = alternativeNode;
console.log(
`[WorkflowEngine] Autonomy re-assigned task from ` +
`${workerNode.agentId} to ${assignedWorkerNode.agentId} ` +
`(strategy=${allocationDecision.strategy})`,
);
}
}
} catch (autonomyErr) {
// Autonomy allocation failed 鈥?fall back to static assignment
console.warn(
`[WorkflowEngine] Autonomy allocation failed, using static assignment: ` +
`${autonomyErr instanceof Error ? autonomyErr.message : autonomyErr}`,
);
}
}
// 鈹€鈹€鈹€ End autonomy-aware allocation 鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€
const taskRow = this.repo.createTask({
workflow_id: workflowId,
worker_id: assignedWorkerNode.agentId,
manager_id: managerNode.agentId,
department: department.id,
description: task.description,
deliverable: null,
deliverable_v2: null,
deliverable_v3: null,
score_accuracy: null,
score_completeness: null,
score_actionability: null,
score_format: null,
total_score: null,
manager_feedback: null,
meta_audit_feedback: null,
verify_result: null,
version: 1,
status: "assigned",
});
await this.runtime.messageBus.send(
managerNode.agentId,
assignedWorkerNode.agentId,
task.description,
workflowId,
"planning",
{
taskId: taskRow.id,
departmentId: department.id,
departmentLabel: department.label,
managerPlan: plan.plan_summary || "",
}
);
}
this.emit({
type: "agent_active",
agentId: managerNode.agentId,
action: "idle",
workflowId,
});
})
);
}
private async runExecution(
workflowId: string,
organization: WorkflowOrganizationSnapshot
): Promise<void> {
this.emitStage(workflowId, "execution");
for (const department of organization.departments) {
const managerNode = this.getManagerNode(organization, department);
const departmentTasks = this.repo
.getTasksByWorkflow(workflowId)
.filter(task => task.manager_id === managerNode.agentId);
await runWithConcurrencyLimit(
departmentTasks,
department.maxConcurrency,
async task => {
const worker = this.getAgent(task.worker_id);
// Log when a guest agent is assigned a task (Requirements 5.1)
if (isGuestId(task.worker_id)) {
console.log(
`[WorkflowEngine] Guest agent ${task.worker_id} assigned task ${task.id} in execution stage`,
);
}
this.emit({
type: "agent_active",
agentId: task.worker_id,
action: "executing",
workflowId,
});
this.repo.updateTask(task.id, { status: "executing" });
this.emit({
type: "task_update",
workflowId,
taskId: task.id,
workerId: task.worker_id,
status: "executing",
});
// Check if worker is an external agent — route via A2A
const extWorkerNode = organization.nodes.find(n => n.agentId === task.worker_id);
if (extWorkerNode && this.isExternalAgent(extWorkerNode)) {
try {
const response = await this.a2aClient.invoke(
{
targetAgent: extWorkerNode.name,
task: task.description,
context: `Department: ${department.label}`,
capabilities: [],
streamMode: false,
},
extWorkerNode.frameworkType,
extWorkerNode.a2aEndpoint,
extWorkerNode.a2aAuth,
);
const deliverable = response.result?.output ?? response.error?.message ?? "No output";