-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathindex.ts
More file actions
1702 lines (1536 loc) · 59.6 KB
/
index.ts
File metadata and controls
1702 lines (1536 loc) · 59.6 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
/**
* SwarmOrchestrator - Multi-Agent Orchestration Framework for TypeScript/Node.js
*
* Connects 12 AI frameworks (LangChain, AutoGen, CrewAI, OpenAI Assistants, LlamaIndex,
* Semantic Kernel, Haystack, DSPy, Agno, MCP, OpenClaw) via a shared atomic blackboard,
* FSM governance, per-agent token budget enforcement, and HMAC audit trails.
* OpenClaw skill interface is implemented for backward compatibility.
*
* @module SwarmOrchestrator
* @version 4.0.17
* @license MIT
*/
import { mkdirSync } from 'fs';
import { join } from 'path';
import { randomUUID } from 'crypto';
import { AdapterRegistry } from './adapters/adapter-registry';
import { InputSanitizer, SecureSwarmGateway, PromptInjectionShield } from './security';
import { FileBackend } from './lib/blackboard-backend';
import type { BlackboardBackend } from './lib/blackboard-backend';
import { ConsistentBackend } from './lib/consistency';
import { QualityGateAgent } from './lib/blackboard-validator';
import { Logger } from './lib/logger';
import {
ValidationError,
TimeoutError as NetworkAITimeoutError,
} from './lib/errors';
import type { ValidationConfig, AIReviewCallback } from './lib/blackboard-validator';
import type { IAgentAdapter, AgentPayload, AgentContext, AdapterConfig } from './types/agent-adapter';
// Extracted modules (Phase 1.1 — split god-file)
import { SharedBlackboard } from './lib/shared-blackboard';
import { AuthGuardian } from './lib/auth-guardian';
import { ExplainabilityTracer } from './lib/explainability';
import type { DecisionCard, DecisionFactor } from './lib/explainability';
import { OrchestratorEventBus } from './lib/event-bus';
import { AgentConversationLog } from './lib/agent-conversation';
import { OTelBridge } from './lib/otel-bridge';
import { createOrchestratorMetrics } from './lib/metrics';
import type { MetricsRegistry } from './lib/metrics';
import { CostHeatmap } from './lib/cost-heatmap';
import { AnomalyDetector } from './lib/anomaly-detector';
import { OrchestratorLifecycleHooks } from './lib/lifecycle-hooks';
import { TaskDecomposer } from './lib/task-decomposer';
import {
CONFIG,
} from './lib/orchestrator-types';
import type {
OpenClawSkill,
SkillContext,
SkillResult,
TaskPayload,
HandoffMessage,
PermissionGrant,
SwarmState,
AgentStatus,
TaskRecord,
BlackboardEntry,
ActiveGrant,
ResourceProfile,
AgentTrustConfig,
NamedBlackboardOptions,
ParallelTask,
ParallelExecutionResult,
SynthesisStrategy,
} from './lib/orchestrator-types';
const log = Logger.create('SwarmOrchestrator');
// Types, interfaces, CONFIG, and default profiles are now in ./lib/orchestrator-types.ts
// SharedBlackboard is now in ./lib/shared-blackboard.ts
// AuthGuardian is now in ./lib/auth-guardian.ts
// TaskDecomposer is now in ./lib/task-decomposer.ts
// ============================================================================
// SWARM ORCHESTRATOR - MAIN SKILL IMPLEMENTATION
// ============================================================================
/**
* The main orchestrator class — coordinates agents, permissions, blackboard,
* quality gates, and adapter routing in a single entry point.
*
* Implements the OpenClaw skill interface for backward compatibility and
* can also be used standalone via {@link createSwarmOrchestrator}.
*
* @example
* ```typescript
* import { createSwarmOrchestrator, LangChainAdapter } from 'network-ai';
*
* const orchestrator = createSwarmOrchestrator({
* adapters: [{ adapter: new LangChainAdapter() }],
* trustLevels: [{ agentId: 'my-agent', trustLevel: 0.8 }],
* });
*
* const result = await orchestrator.execute('delegate_task', {
* targetAgent: 'my-agent',
* taskPayload: { instruction: 'Summarize the quarterly report' },
* }, { agentId: 'orchestrator' });
* ```
*/
export class SwarmOrchestrator implements OpenClawSkill {
name = 'SwarmOrchestrator';
version = '3.1.0';
private blackboard: SharedBlackboard;
private authGuardian: AuthGuardian;
private taskDecomposer: TaskDecomposer;
private agentRegistry: Map<string, AgentStatus> = new Map();
private gateway: SecureSwarmGateway;
private qualityGate: QualityGateAgent;
private injectionShield: PromptInjectionShield;
public readonly tracer: ExplainabilityTracer;
public readonly eventBus: OrchestratorEventBus;
public readonly conversationLog: AgentConversationLog;
public readonly otel: OTelBridge;
public readonly metrics: ReturnType<typeof createOrchestratorMetrics>;
public readonly heatmap: CostHeatmap;
public readonly anomalyDetector: AnomalyDetector;
public readonly lifecycleHooks: OrchestratorLifecycleHooks;
/** Named isolated blackboards, keyed by board name */
private namedBlackboards: Map<string, SharedBlackboard> = new Map();
/** Root workspace path -- used as the parent for named board subdirectories */
private _workspacePath: string;
/** The adapter registry -- routes requests to the right agent framework */
public readonly adapters: AdapterRegistry;
constructor(
workspacePath: string = process.cwd(),
adapterRegistry?: AdapterRegistry,
options?: {
trustLevels?: AgentTrustConfig[];
resourceProfiles?: Record<string, ResourceProfile>;
validationConfig?: Partial<ValidationConfig>;
qualityThreshold?: number;
aiReviewCallback?: AIReviewCallback;
}
) {
if (workspacePath !== undefined && typeof workspacePath !== 'string') {
throw new ValidationError('workspacePath must be a string');
}
if (workspacePath !== undefined && workspacePath.trim() === '') {
throw new ValidationError('workspacePath must not be empty');
}
this._workspacePath = workspacePath;
this.blackboard = new SharedBlackboard(workspacePath);
this.authGuardian = new AuthGuardian({
trustLevels: options?.trustLevels,
resourceProfiles: options?.resourceProfiles,
});
this.adapters = adapterRegistry ?? new AdapterRegistry();
this.taskDecomposer = new TaskDecomposer(this.blackboard, this.authGuardian, this.adapters);
this.gateway = new SecureSwarmGateway();
this.qualityGate = new QualityGateAgent({
validationConfig: options?.validationConfig,
qualityThreshold: options?.qualityThreshold,
aiReviewCallback: options?.aiReviewCallback,
});
this.injectionShield = new PromptInjectionShield();
this.tracer = new ExplainabilityTracer();
this.eventBus = new OrchestratorEventBus({ snapshotInterval: 100 });
this.conversationLog = new AgentConversationLog();
this.otel = new OTelBridge();
this.metrics = createOrchestratorMetrics();
this.heatmap = new CostHeatmap();
this.anomalyDetector = new AnomalyDetector();
this.lifecycleHooks = new OrchestratorLifecycleHooks();
// Register the orchestrator agent on the blackboard with full access
this.blackboard.registerAgent('orchestrator', 'system-orchestrator-token', ['*']);
}
/**
* Add an agent framework adapter (LangChain, AutoGen, CrewAI, MCP, custom, etc.)
* This is the plug-and-play entry point.
*/
async addAdapter(adapter: IAgentAdapter, config: AdapterConfig = {}): Promise<void> {
if (!adapter || typeof adapter !== 'object') {
throw new ValidationError('adapter is required and must be an object');
}
if (typeof adapter.name !== 'string' || adapter.name.trim() === '') {
throw new ValidationError('adapter.name must be a non-empty string');
}
await this.adapters.addAdapter(adapter, config);
}
/**
* Main entry point for the skill.
* Now integrates SecureSwarmGateway: every request flows through
* input sanitization, rate limiting, and agent ID validation.
*/
async execute(action: string, params: Record<string, unknown>, context: SkillContext): Promise<SkillResult> {
if (!action || typeof action !== 'string') {
return {
success: false,
error: {
code: 'INVALID_PARAMS',
message: 'action is required and must be a non-empty string',
recoverable: false,
},
};
}
if (!params || typeof params !== 'object' || Array.isArray(params)) {
return {
success: false,
error: {
code: 'INVALID_PARAMS',
message: 'params is required and must be a plain object',
recoverable: false,
},
};
}
if (!context || typeof context !== 'object' || !context.agentId || typeof context.agentId !== 'string') {
return {
success: false,
error: {
code: 'INVALID_PARAMS',
message: 'context is required and must include a non-empty agentId string',
recoverable: false,
},
};
}
const traceId = randomUUID();
// P0: Route through SecureSwarmGateway -- sanitization + rate limiting
const gatewayResult = await this.gateway.handleSecureRequest(
context.agentId,
action,
params,
);
if (!gatewayResult.allowed) {
return {
success: false,
error: {
code: 'GATEWAY_DENIED',
message: `Security gateway denied request: ${gatewayResult.reason}`,
recoverable: true,
suggestedAction: 'Check agent ID, rate limits, or input format',
},
};
}
// Use sanitized params from gateway
const safeParams = gatewayResult.sanitizedParams ?? params;
if (CONFIG.enableTracing) {
try {
this.blackboard.write(`trace:${traceId}`, {
action,
startTime: new Date().toISOString(),
}, context.agentId, undefined, 'system-orchestrator-token');
} catch {
// Non-fatal -- tracing failure shouldn't block execution
}
}
try {
switch (action) {
case 'delegate_task':
return await this.delegateTask(safeParams, context);
case 'query_swarm_state':
return await this.querySwarmState(safeParams, context);
case 'spawn_parallel_agents':
return await this.spawnParallelAgents(safeParams, context);
case 'request_permission':
return await this.handlePermissionRequest(safeParams, context);
case 'update_blackboard':
return await this.handleBlackboardUpdate(safeParams, context);
case 'quality_gate_status':
return this.handleQualityGateStatus();
case 'review_quarantine':
return this.handleQuarantineReview(safeParams);
default:
return {
success: false,
error: {
code: 'UNKNOWN_ACTION',
message: `Unknown action: ${action}`,
recoverable: false,
},
};
}
} catch (error) {
return {
success: false,
error: {
code: 'EXECUTION_ERROR',
message: error instanceof Error ? error.message : 'Unknown error',
recoverable: true,
trace: { traceId, action },
},
};
}
}
// -------------------------------------------------------------------------
// CAPABILITY: delegate_task
// -------------------------------------------------------------------------
private async delegateTask(params: Record<string, unknown>, context: SkillContext): Promise<SkillResult> {
const targetAgent = params.targetAgent as string;
const taskPayload = params.taskPayload as TaskPayload;
const priority = (params.priority as string) ?? 'normal';
const timeout = (params.timeout as number) ?? CONFIG.defaultTimeout;
const requiresAuth = (params.requiresAuth as boolean) ?? false;
const resourceType = (params.resourceType as string) ?? 'EXTERNAL_SERVICE';
const delegationTraceId = this.tracer.record({
source: 'SwarmOrchestrator',
decision: 'delegation_start',
outcome: 'initiated',
agentId: context.agentId,
factors: [
{ name: 'targetAgent', value: targetAgent },
{ name: 'priority', value: priority },
{ name: 'requiresAuth', value: requiresAuth },
{ name: 'timeout', value: timeout },
],
});
this.eventBus.publish('orchestrator', 'delegation_start', 'info', {
targetAgent, priority, requiresAuth, timeout, traceId: delegationTraceId,
}, context.agentId, delegationTraceId);
this.metrics.delegationsTotal.inc({ agent: targetAgent });
const delegationStartMs = Date.now();
// Orchestrator-level beforeSpawn hook
const spawnCtx = await this.lifecycleHooks.runBeforeSpawn({
agentId: targetAgent,
instruction: taskPayload.instruction,
priority,
requiresAuth,
metadata: { timeout, resourceType },
aborted: false,
});
if (spawnCtx.aborted) {
return {
success: false,
error: {
code: 'LIFECYCLE_ABORTED',
message: spawnCtx.abortReason ?? 'Aborted by beforeSpawn hook',
recoverable: true,
},
};
}
// Check permission wall if required -- now returns bound restrictions
let grantToken: string | null = null;
if (requiresAuth) {
const authResult = await this.authGuardian.requestPermission(
context.agentId,
resourceType,
`Delegating task to ${targetAgent}: ${taskPayload.instruction}`,
'delegate'
);
if (!authResult.granted) {
this.tracer.record({
source: 'AuthGuardian', decision: 'permission_check', outcome: 'denied',
agentId: context.agentId, parentTraceId: delegationTraceId,
factors: [{ name: 'reason', value: authResult.reason }],
});
this.eventBus.publish('auth', 'permission_denied', 'warn', {
reason: authResult.reason, resourceType,
}, context.agentId, delegationTraceId);
this.metrics.permissionDenials.inc({ agent: context.agentId });
return {
success: false,
error: {
code: 'AUTH_DENIED',
message: `Permission denied: ${authResult.reason}`,
recoverable: true,
suggestedAction: 'Provide more specific justification or narrow scope',
},
};
}
grantToken = authResult.grantToken;
// Enforce restrictions at point of use
if (grantToken) {
const restrictionViolation = this.authGuardian.enforceRestrictions(grantToken, {
type: 'execute',
});
if (restrictionViolation) {
return {
success: false,
error: {
code: 'RESTRICTION_VIOLATED',
message: restrictionViolation,
recoverable: true,
suggestedAction: 'Request a grant with broader scope',
},
};
}
}
}
// Check blackboard for existing work
const cacheKey = `task:${targetAgent}:${JSON.stringify(taskPayload).slice(0, 50)}`;
const existingWork = this.blackboard.read(cacheKey);
if (existingWork) {
return {
success: true,
data: {
taskId: 'cached',
status: 'completed',
result: existingWork.value,
agentTrace: ['blackboard-cache'],
fromCache: true,
},
};
}
// Build handoff message
const handoff: HandoffMessage = {
handoffId: randomUUID(),
sourceAgent: context.agentId,
targetAgent,
taskType: 'delegate',
payload: taskPayload,
metadata: {
priority: this.priorityToNumber(priority),
deadline: Date.now() + timeout,
parentTaskId: context.taskId ?? null,
},
};
// Execute via adapter registry (routes to the right framework)
try {
// Sanitize instruction before sending to adapter
let sanitizedInstruction = taskPayload.instruction;
try {
sanitizedInstruction = InputSanitizer.sanitizeString(taskPayload.instruction, 10000);
} catch { /* use original if sanitization fails */ }
// Prompt injection detection
const injectionResult = this.injectionShield.analyze(sanitizedInstruction);
if (!injectionResult.safe) {
this.tracer.record({
source: 'PromptInjectionShield', decision: 'injection_scan', outcome: 'blocked',
agentId: context.agentId, parentTraceId: delegationTraceId,
factors: [
{ name: 'score', value: injectionResult.score },
{ name: 'matchedRules', value: injectionResult.matchedRules },
],
});
this.eventBus.publish('injection', 'blocked', 'error', {
score: injectionResult.score, rules: injectionResult.matchedRules,
}, context.agentId, delegationTraceId);
this.metrics.injectionBlocks.inc({ agent: context.agentId });
return {
success: false,
error: {
code: 'PROMPT_INJECTION_BLOCKED',
message: `Prompt injection detected (score=${injectionResult.score.toFixed(2)}, rules: ${injectionResult.matchedRules.join(', ')})`,
recoverable: true,
suggestedAction: 'Rephrase the instruction to remove injection patterns',
},
};
}
// P1: Namespace-scoped snapshot -- target agent only sees keys it's allowed to see
const scopedSnapshot = this.blackboard.getScopedSnapshot(targetAgent);
const agentPayload: AgentPayload = {
action: 'execute',
params: {},
handoff: {
handoffId: handoff.handoffId,
sourceAgent: handoff.sourceAgent,
targetAgent: handoff.targetAgent,
taskType: handoff.taskType,
instruction: sanitizedInstruction,
context: taskPayload.context,
constraints: taskPayload.constraints,
expectedOutput: taskPayload.expectedOutput,
metadata: handoff.metadata as unknown as Record<string, unknown>,
},
blackboardSnapshot: scopedSnapshot as Record<string, unknown>,
};
const agentContext: AgentContext = {
agentId: context.agentId,
taskId: context.taskId,
sessionId: context.sessionId,
};
const otelSpan = this.otel.startDelegation(context.agentId, targetAgent, handoff.handoffId);
const result = await Promise.race([
this.adapters.executeAgent(targetAgent, agentPayload, agentContext),
this.timeoutPromise(timeout),
]);
otelSpan.setAttribute('agent.result.success', result.success);
otelSpan.end();
// P1: Sanitize adapter output before caching
let sanitizedResult = result;
try {
sanitizedResult = InputSanitizer.sanitizeObject(result) as typeof result;
} catch { /* use raw if sanitization fails */ }
// Quality gate: validate result before committing to blackboard
const gateResult = await this.qualityGate.gate(cacheKey, sanitizedResult, targetAgent, {
taskInstruction: taskPayload.instruction,
expectedOutput: taskPayload.expectedOutput,
});
this.tracer.record({
source: 'QualityGateAgent', decision: 'quality_gate', outcome: gateResult.decision,
agentId: targetAgent, parentTraceId: delegationTraceId,
factors: [
{ name: 'score', value: gateResult.validation.score },
{ name: 'issueCount', value: gateResult.validation.issues.length },
],
});
this.eventBus.publish('quality', gateResult.decision, gateResult.decision === 'reject' ? 'warn' : 'info', {
score: gateResult.validation.score, issueCount: gateResult.validation.issues.length,
}, targetAgent, delegationTraceId);
if (gateResult.decision === 'reject') {
this.metrics.qualityRejections.inc({ agent: targetAgent });
return {
success: false,
error: {
code: 'QUALITY_REJECTED',
message: `Result from ${targetAgent} failed quality validation: ${gateResult.validation.issues.filter(i => i.severity === 'error').map(i => i.message).join('; ')}`,
recoverable: gateResult.validation.recoverable,
suggestedAction: gateResult.validation.issues.find(i => i.suggestion)?.suggestion,
},
};
}
if (gateResult.decision === 'quarantine') {
// Still return the result but flag it
return {
success: true,
data: {
taskId: handoff.handoffId,
status: 'quarantined',
result: sanitizedResult,
agentTrace: [context.agentId, targetAgent],
qualityGate: {
decision: 'quarantine',
quarantineKey: gateResult.quarantineKey,
score: gateResult.validation.score,
issues: gateResult.validation.issues,
reviewNotes: gateResult.reviewNotes,
},
},
};
}
// Approved -- cache result
this.blackboard.write(cacheKey, sanitizedResult, context.agentId, 1800, 'system-orchestrator-token'); // 30 min TTL
this.metrics.delegationDurationMs.observe({ agent: targetAgent }, Date.now() - delegationStartMs);
this.heatmap.record(targetAgent, {
durationMs: Date.now() - delegationStartMs,
inputTokens: 0, outputTokens: 0, success: true,
});
this.anomalyDetector.observe(targetAgent, {
latencyMs: Date.now() - delegationStartMs, tokens: 0, success: true,
});
const resultMeta = (sanitizedResult as unknown as Record<string, unknown>)?.metadata as Record<string, unknown> | undefined;
this.conversationLog.recordTurn(targetAgent, {
instruction: taskPayload.instruction,
result: JSON.stringify(sanitizedResult).slice(0, 2000),
success: true,
tokensUsed: resultMeta?.tokensUsed as number | undefined,
executionTimeMs: resultMeta?.executionTimeMs as number | undefined,
adapter: resultMeta?.adapter as string | undefined,
qualityDecision: gateResult.decision,
correlationId: delegationTraceId,
sourceAgent: context.agentId,
});
// Orchestrator-level afterComplete hook
await this.lifecycleHooks.runAfterComplete({
agentId: targetAgent,
instruction: taskPayload.instruction,
result: sanitizedResult,
durationMs: Date.now() - delegationStartMs,
tokensUsed: (resultMeta?.tokensUsed as number) ?? 0,
metadata: { qualityDecision: gateResult.decision },
});
return {
success: true,
data: {
taskId: handoff.handoffId,
status: 'completed',
result: sanitizedResult,
agentTrace: [context.agentId, targetAgent],
qualityGate: {
decision: 'approve',
score: gateResult.validation.score,
},
},
};
} catch (error) {
this.metrics.delegationErrors.inc({ agent: targetAgent });
this.conversationLog.recordTurn(targetAgent, {
instruction: taskPayload.instruction,
success: false,
errorCode: 'DELEGATION_FAILED',
correlationId: delegationTraceId,
sourceAgent: context.agentId,
});
this.eventBus.publish('orchestrator', 'delegation_failed', 'error', {
error: error instanceof Error ? error.message : 'unknown',
}, targetAgent, delegationTraceId);
// Orchestrator-level onFailure hook
const failCtx = await this.lifecycleHooks.runOnFailure({
agentId: targetAgent,
instruction: taskPayload.instruction,
error: error instanceof Error ? error : String(error),
durationMs: Date.now() - delegationStartMs,
metadata: {},
suppress: false,
});
if (failCtx.suppress) {
return { success: true, data: { status: 'suppressed', agentTrace: [context.agentId, targetAgent] } };
}
return {
success: false,
error: {
code: 'DELEGATION_FAILED',
message: error instanceof Error ? error.message : 'Task delegation failed',
recoverable: true,
},
};
}
}
// -------------------------------------------------------------------------
// CAPABILITY: query_swarm_state
// -------------------------------------------------------------------------
private async querySwarmState(params: Record<string, unknown>, context: SkillContext): Promise<SkillResult> {
const scope = (params.scope as string) ?? 'all';
const agentFilter = params.agentFilter as string[] | undefined;
const _includeHistory = (params.includeHistory as boolean) ?? false;
const state: Partial<SwarmState> = {
timestamp: new Date().toISOString(),
};
if (scope === 'all' || scope === 'agents') {
let agents = Array.from(this.agentRegistry.values());
if (agentFilter) {
agents = agents.filter(a => agentFilter.includes(a.agentId));
}
state.activeAgents = agents;
}
if (scope === 'all' || scope === 'blackboard') {
// P1: Namespace-scoped -- agent only sees keys it's allowed to access
state.blackboardSnapshot = this.blackboard.getScopedSnapshot(context.agentId);
}
if (scope === 'all' || scope === 'permissions') {
state.permissionGrants = this.authGuardian.getActiveGrants();
}
if (scope === 'all' || scope === 'tasks') {
// Extract tasks from scoped blackboard
const snapshot = this.blackboard.getScopedSnapshot(context.agentId);
state.pendingTasks = Object.entries(snapshot)
.filter(([key]) => key.startsWith('task:'))
.map(([, entry]) => ({
taskId: entry.key,
agentId: entry.sourceAgent,
status: 'in_progress' as const,
startedAt: entry.timestamp,
description: String(entry.value),
}));
}
return {
success: true,
data: state,
};
}
// -------------------------------------------------------------------------
// CAPABILITY: spawn_parallel_agents
// -------------------------------------------------------------------------
private async spawnParallelAgents(
params: Record<string, unknown>,
context: SkillContext
): Promise<SkillResult> {
const tasks = params.tasks as ParallelTask[];
const synthesisStrategy = (params.synthesisStrategy as SynthesisStrategy) ?? 'merge';
if (!tasks || !Array.isArray(tasks) || tasks.length === 0) {
return {
success: false,
error: {
code: 'INVALID_PARAMS',
message: 'Tasks array is required and must not be empty',
recoverable: false,
},
};
}
try {
const result = await this.taskDecomposer.executeParallel(tasks, synthesisStrategy, context);
return {
success: true,
data: result,
};
} catch (error) {
return {
success: false,
error: {
code: 'PARALLEL_EXECUTION_FAILED',
message: error instanceof Error ? error.message : 'Parallel execution failed',
recoverable: true,
},
};
}
}
// -------------------------------------------------------------------------
// CAPABILITY: request_permission
// -------------------------------------------------------------------------
private async handlePermissionRequest(
params: Record<string, unknown>,
context: SkillContext
): Promise<SkillResult> {
const resourceType = params.resourceType as string;
const justification = params.justification as string;
const scope = params.scope as string | undefined;
if (!resourceType || !justification) {
return {
success: false,
error: {
code: 'INVALID_PARAMS',
message: 'resourceType and justification are required',
recoverable: false,
},
};
}
const grant = await this.authGuardian.requestPermission(
context.agentId,
resourceType,
justification,
scope
);
return {
success: grant.granted,
data: grant,
};
}
// -------------------------------------------------------------------------
// CAPABILITY: update_blackboard
// -------------------------------------------------------------------------
private async handleBlackboardUpdate(
params: Record<string, unknown>,
context: SkillContext
): Promise<SkillResult> {
const key = params.key as string;
const value = params.value;
const ttl = params.ttl as number | undefined;
if (!key || value === undefined) {
return {
success: false,
error: {
code: 'INVALID_PARAMS',
message: 'key and value are required',
recoverable: false,
},
};
}
const previousValue = this.blackboard.read(key)?.value ?? null;
// Quality gate: validate before writing to blackboard
const gateResult = await this.qualityGate.gate(key, value, context.agentId);
if (gateResult.decision === 'reject') {
return {
success: false,
error: {
code: 'QUALITY_REJECTED',
message: `Blackboard write rejected: ${gateResult.validation.issues.filter(i => i.severity === 'error').map(i => i.message).join('; ')}`,
recoverable: gateResult.validation.recoverable,
suggestedAction: gateResult.validation.issues.find(i => i.suggestion)?.suggestion,
},
};
}
if (gateResult.decision === 'quarantine') {
return {
success: true,
data: {
success: true,
quarantined: true,
quarantineKey: gateResult.quarantineKey,
qualityScore: gateResult.validation.score,
issues: gateResult.validation.issues,
previousValue,
},
};
}
this.blackboard.write(key, value, context.agentId, ttl, 'system-orchestrator-token');
return {
success: true,
data: {
success: true,
previousValue,
qualityScore: gateResult.validation.score,
},
};
}
// -------------------------------------------------------------------------
// QUALITY GATE MANAGEMENT
// -------------------------------------------------------------------------
/** Returns quality gate metrics and quarantined entries */
private handleQualityGateStatus(): SkillResult {
return {
success: true,
data: {
metrics: this.qualityGate.getMetrics(),
quarantined: this.qualityGate.getQuarantined(),
},
};
}
/** Approve or reject a quarantined entry */
private handleQuarantineReview(params: Record<string, unknown>): SkillResult {
const quarantineId = params.quarantineId as string;
const decision = params.decision as 'approve' | 'reject';
if (!quarantineId || !decision) {
return {
success: false,
error: {
code: 'INVALID_PARAMS',
message: 'quarantineId and decision ("approve" or "reject") are required',
recoverable: false,
},
};
}
let entry: unknown;
if (decision === 'approve') {
entry = this.qualityGate.approveQuarantined(quarantineId);
if (entry) {
// Write the approved entry to the blackboard
this.blackboard.write(`approved:${quarantineId}`, entry, 'orchestrator', undefined, 'system-orchestrator-token');
}
} else {
entry = this.qualityGate.rejectQuarantined(quarantineId);
}
return {
success: !!entry,
data: entry ? { quarantineId, decision, resolved: true } : undefined,
error: entry ? undefined : {
code: 'NOT_FOUND',
message: `Quarantine entry ${quarantineId} not found`,
recoverable: false,
},
};
}
/** Expose the quality gate for external configuration */
public getQualityGate(): QualityGateAgent {
return this.qualityGate;
}
// -------------------------------------------------------------------------
// NAMED MULTI-BLACKBOARD API (Phase 5)
// -------------------------------------------------------------------------
/**
* Get or create a named, isolated blackboard managed by this orchestrator.
*
* Each named board is stored in its own subdirectory:
* `<workspacePath>/boards/<name>/`
*
* Calling `getBlackboard(name)` a second time returns the same instance --
* no duplicate boards are created.
*
* All existing APIs (`orchestrator.blackboard`, adapters, AuthGuardian, etc.)
* are completely unaffected. This is a purely additive method.
*
* @example
* ```typescript
* const board = orchestrator.getBlackboard('project-alpha');
* board.registerAgent('analyst', 'tok-1', ['analysis:']);
* board.write('analysis:result', { score: 0.9 }, 'analyst', 3600, 'tok-1');
* const entry = board.read('analysis:result');
* ```
*
* @param name - Board name: alphanumeric, hyphens and underscores only
* @param options - Optional creation options (ignored on subsequent calls)
* @returns The isolated `SharedBlackboard` instance for this name
* @throws {@link ValidationError} if `name` is empty or contains invalid characters
*/
public getBlackboard(name: string, options?: NamedBlackboardOptions): SharedBlackboard {
if (!name || typeof name !== 'string' || name.trim() === '') {
throw new ValidationError('name must be a non-empty string');
}
if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
throw new ValidationError(
'name must contain only alphanumeric characters, hyphens, or underscores'
);
}
// Return existing board (idempotent)
if (this.namedBlackboards.has(name)) {
return this.namedBlackboards.get(name)!;
}
let board: SharedBlackboard;
let selectedBackend: BlackboardBackend;
if (options?.backend) {
// Custom backend — no disk directory needed
selectedBackend = options.backend;
log.info('Named blackboard created (custom backend)', { name });
} else {
// Default: file backend persisted to <workspacePath>/boards/<name>/
const boardPath = join(this._workspacePath, 'boards', name);
mkdirSync(boardPath, { recursive: true });
selectedBackend = new FileBackend(boardPath);
log.info('Named blackboard created', { name, boardPath: join(this._workspacePath, 'boards', name) });
}
// Auto-wrap with ConsistentBackend when a non-default consistency level is requested
if (options?.consistency && options.consistency !== 'eventual') {
selectedBackend = new ConsistentBackend(selectedBackend, options.consistency);
log.info('Named blackboard wrapped with ConsistentBackend', { name, consistency: options.consistency });
}
board = new SharedBlackboard(selectedBackend);
// Register the orchestrator agent on this board
board.registerAgent(
'orchestrator',
'system-orchestrator-token',
options?.allowedNamespaces ?? ['*'],
);
this.namedBlackboards.set(name, board);
return board;
}
/**
* Returns the names of all currently active named blackboards.
*
* @example
* ```typescript
* orchestrator.getBlackboard('alpha');
* orchestrator.getBlackboard('beta');
* orchestrator.listBlackboards(); // ['alpha', 'beta']
* ```
*/
public listBlackboards(): string[] {
return Array.from(this.namedBlackboards.keys());
}
/**
* Returns `true` if a named blackboard with the given name is currently active.
*
* @param name - The board name to check
*/
public hasBlackboard(name: string): boolean {
if (!name || typeof name !== 'string') return false;
return this.namedBlackboards.has(name);
}
/**