-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathindex.ts
More file actions
2708 lines (2434 loc) · 92.6 KB
/
index.ts
File metadata and controls
2708 lines (2434 loc) · 92.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 { readFileSync, writeFileSync, existsSync, appendFileSync, mkdirSync } from 'fs';
import { join } from 'path';
import { randomUUID, generateKeyPairSync, sign as ed25519Sign, verify as ed25519Verify, createHmac, KeyObject } from 'crypto';
import { AdapterRegistry } from './adapters/adapter-registry';
import { InputSanitizer, SecureSwarmGateway } from './security';
import type { ConflictResolutionStrategy, AgentPriority, LockedBlackboardOptions } from './lib/locked-blackboard';
import { FileBackend } from './lib/blackboard-backend';
import type { BlackboardBackend } from './lib/blackboard-backend';
import { ConsistentBackend } from './lib/consistency';
import type { ConsistencyLevel, FlushableBackend } from './lib/consistency';
import { QualityGateAgent } from './lib/blackboard-validator';
import { Logger } from './lib/logger';
import {
IdentityVerificationError,
NamespaceViolationError,
ValidationError,
TimeoutError as NetworkAITimeoutError,
} from './lib/errors';
import type { ValidationResult, QualityGateResult, ValidationConfig, AIReviewCallback, CustomValidationRule } from './lib/blackboard-validator';
import type { IAgentAdapter, AgentPayload, AgentContext, AgentResult, AdapterConfig } from './types/agent-adapter';
const log = Logger.create('SwarmOrchestrator');
// Backward-compatible re-exports: OpenClaw types still work
// but are now optional -- the system works without openclaw-core
type OpenClawSkill = {
name: string;
version: string;
execute(action: string, params: Record<string, unknown>, context: SkillContext): Promise<SkillResult>;
};
/**
* Execution context passed to every skill invocation.
* Identifies the calling agent and associates the call with a task/session.
*/
interface SkillContext {
/** The agent initiating the request */
agentId: string;
/** Unique task identifier (optional) */
taskId?: string;
/** Session identifier for multi-turn interactions */
sessionId?: string;
/** Arbitrary metadata from the host system */
metadata?: Record<string, unknown>;
}
/**
* Unified result shape returned by every skill action.
* Includes structured error information with recovery hints.
*/
interface SkillResult {
/** Whether the action completed successfully */
success: boolean;
/** Result data (shape varies by action) */
data?: unknown;
/** Structured error when `success` is false */
error?: {
/** Machine-readable error code (e.g., `'AUTH_DENIED'`, `'GATEWAY_DENIED'`) */
code: string;
/** Human-readable error description */
message: string;
/** Whether the caller can retry or adjust and succeed */
recoverable: boolean;
/** Suggested remediation step */
suggestedAction?: string;
/** Trace metadata for debugging */
trace?: Record<string, unknown>;
};
}
// ============================================================================
// TYPE DEFINITIONS
// ============================================================================
/**
* A task to be delegated to an agent.
*
* @example
* ```typescript
* const payload: TaskPayload = {
* instruction: 'Analyze Q4 revenue trends',
* context: { department: 'finance' },
* constraints: ['read_only', 'no_pii'],
* expectedOutput: 'JSON summary with top-line metrics',
* };
* ```
*/
interface TaskPayload {
/** Natural-language instruction for the agent */
instruction: string;
/** Additional context data relevant to the task */
context?: Record<string, unknown>;
/** Restrictions or guardrails the agent must respect */
constraints?: string[];
/** Description of the expected output format */
expectedOutput?: string;
}
/**
* Internal message structure for agent-to-agent task handoffs.
* The orchestrator creates these when delegating work between agents.
*/
interface HandoffMessage {
/** Unique handoff identifier */
handoffId: string;
/** Agent initiating the handoff */
sourceAgent: string;
/** Agent receiving the task */
targetAgent: string;
/** How the target agent should process the task */
taskType: 'delegate' | 'collaborate' | 'validate';
/** The task to execute */
payload: TaskPayload;
/** Scheduling and priority metadata */
metadata: {
/** Priority level (0=low, 3=critical) */
priority: number;
/** Unix timestamp deadline */
deadline: number;
/** Parent task for sub-task tracking */
parentTaskId: string | null;
};
}
/**
* Result of a permission request through the AuthGuardian.
* Contains the grant token (if approved) and any restrictions.
*/
interface PermissionGrant {
/** Whether permission was granted */
granted: boolean;
/** Opaque token to present when using the granted resource */
grantToken: string | null;
/** ISO 8601 expiration timestamp */
expiresAt: string | null;
/** Restrictions applied to this grant (e.g., `'read_only'`, `'max_records:100'`) */
restrictions: string[];
/** Human-readable denial reason (when `granted` is false) */
reason?: string;
}
/** Full snapshot of the swarm's runtime state. */
interface SwarmState {
/** ISO 8601 timestamp when the snapshot was taken */
timestamp: string;
/** All registered agents and their current status */
activeAgents: AgentStatus[];
/** Tasks currently pending or in progress */
pendingTasks: TaskRecord[];
/** Namespace-scoped blackboard entries visible to the querying agent */
blackboardSnapshot: Record<string, BlackboardEntry>;
/** Active permission grants */
permissionGrants: ActiveGrant[];
}
/** Runtime status of a registered agent. */
interface AgentStatus {
/** Unique agent identifier */
agentId: string;
/** Current operational state */
status: 'available' | 'busy' | 'waiting_auth' | 'offline';
/** ID of the task currently being executed, or null */
currentTask: string | null;
/** ISO 8601 timestamp of the last heartbeat */
lastHeartbeat: string;
}
interface TaskRecord {
taskId: string;
agentId: string;
status: 'pending' | 'in_progress' | 'completed' | 'failed';
startedAt: string;
description: string;
}
/** A single entry stored on the shared blackboard. */
interface BlackboardEntry {
/** Entry key (namespace-prefixed, e.g., `'task:analyze'`) */
key: string;
/** Stored value (any serializable data) */
value: unknown;
/** Agent that wrote this entry */
sourceAgent: string;
/** ISO 8601 timestamp of the write */
timestamp: string;
/** Time-to-live in seconds, or null for no expiry */
ttl: number | null;
}
/** An active permission grant held by an agent. */
interface ActiveGrant {
/** Opaque grant token */
grantToken: string;
/** Resource type this grant covers (e.g., `'FILE_SYSTEM'`, `'DATABASE'`) */
resourceType: string;
/** Agent holding the grant */
agentId: string;
/** ISO 8601 expiration timestamp */
expiresAt: string;
/** Restrictions bound to this grant */
restrictions: string[];
/** Optional scope narrowing (e.g., `'read'`, `'staging_only'`) */
scope?: string;
}
/**
* Configurable resource profile -- makes the system domain-agnostic.
* Users can define any resource type (coding, finance, devops, etc.)
*/
interface ResourceProfile {
/** Base risk score 0-1 */
baseRisk: number;
/** Default restrictions applied when access is granted */
defaultRestrictions: string[];
/** Human-readable description */
description?: string;
}
/**
* Configuration for agent trust levels.
* Pass your own agents with their trust scores.
*/
interface AgentTrustConfig {
agentId: string;
trustLevel: number;
/** Namespace prefixes this agent can read from the blackboard */
allowedNamespaces?: string[];
/** Resource types this agent can request */
allowedResources?: string[];
}
/**
* Options for creating a named blackboard via `orchestrator.getBlackboard(name)`.
* All fields are optional -- sensible defaults are applied automatically.
*/
export interface NamedBlackboardOptions {
/**
* Namespace prefixes the orchestrator agent is allowed to use on this board.
* Defaults to `['*']` (full access). Pass e.g. `['analysis:', 'result:']` to
* restrict the board to specific key prefixes.
*/
allowedNamespaces?: string[];
/**
* Custom validation config applied to writes on this board.
* Falls back to the orchestrator's global config when omitted.
*/
validationConfig?: Partial<ValidationConfig>;
/**
* Pluggable storage backend for this board.
*
* - Omit (default): `FileBackend` — persisted to disk at `<workspacePath>/boards/<name>/`
* - `new MemoryBackend()`: pure in-memory, no disk writes
* - Custom class implementing `BlackboardBackend`: Redis, CRDT, cloud KV, etc.
*
* @example
* ```typescript
* // Ephemeral board (testing / short-lived tasks)
* const board = orchestrator.getBlackboard('tmp', { backend: new MemoryBackend() });
*
* // Custom Redis backend
* const board = orchestrator.getBlackboard('prod', { backend: new RedisBackend(client) });
* ```
*/
backend?: BlackboardBackend;
/**
* Consistency level applied to this board's backend.
*
* When provided, the backend is automatically wrapped in a `ConsistentBackend`
* with the specified level. Omitting this (or passing `'eventual'`) leaves the
* backend unwrapped for maximum performance.
*
* - `'eventual'` (default): no wrapping — highest throughput
* - `'session'`: read-your-writes guarantee via a local session cache
* - `'strong'`: use `board.writeAsync()` to await `backend.flush()` confirmation
*
* @example
* ```typescript
* const board = orchestrator.getBlackboard('live', {
* backend: new RedisBackend(client),
* consistency: 'strong',
* });
* ```
*/
consistency?: ConsistencyLevel;
}
/** A single task within a parallel execution batch. */
interface ParallelTask {
/** Agent type or adapter-prefixed ID to route the task to */
agentType: string;
/** The task payload to execute */
taskPayload: TaskPayload;
}
/** Result of a parallel execution batch, including synthesis and metrics. */
interface ParallelExecutionResult {
/** Combined result produced by the synthesis strategy */
synthesizedResult: unknown;
/** Per-agent results with timing */
individualResults: Array<{
agentType: string;
success: boolean;
result: unknown;
/** Wall-clock execution time in milliseconds */
executionTime: number;
}>;
/** Aggregate execution metrics */
executionMetrics: {
/** Total wall-clock time in milliseconds */
totalTime: number;
/** Fraction of tasks that succeeded (0-1) */
successRate: number;
/** Strategy used to combine results */
synthesisStrategy: string;
};
}
/**
* Strategy for combining results from parallel agent executions.
* - `'merge'` — Combine all successful results into one object
* - `'vote'` — Pick the result with the highest confidence/size
* - `'chain'` — Use the final result in sequence
* - `'first-success'` — Return the first successful result
*/
type SynthesisStrategy = 'merge' | 'vote' | 'chain' | 'first-success';
// ============================================================================
// CONFIGURATION
// ============================================================================
const CONFIG = {
blackboardPath: './swarm-blackboard.md',
maxParallelAgents: Infinity,
defaultTimeout: 30000,
enableTracing: true,
grantTokenTTL: 300000, // 5 minutes in milliseconds
maxBlackboardValueSize: 1024 * 1024, // 1 MB max per entry
auditLogPath: './data/audit_log.jsonl',
trustConfigPath: './data/trust_levels.json',
};
// ============================================================================
// DEFAULT RESOURCE PROFILES -- Universal, domain-agnostic
// Users can override/extend these for any domain (coding, finance, devops, etc.)
// ============================================================================
const DEFAULT_RESOURCE_PROFILES: Record<string, ResourceProfile> = {
// --- Financial / Enterprise ---
SAP_API: { baseRisk: 0.5, defaultRestrictions: ['read_only', 'max_records:100'], description: 'SAP enterprise API' },
FINANCIAL_API: { baseRisk: 0.7, defaultRestrictions: ['read_only', 'no_pii_fields', 'audit_required'], description: 'Financial data API' },
DATA_EXPORT: { baseRisk: 0.6, defaultRestrictions: ['anonymize_pii', 'local_only'], description: 'Data export operations' },
// --- Coding / Development ---
FILE_SYSTEM: { baseRisk: 0.5, defaultRestrictions: ['workspace_only', 'no_system_dirs', 'max_file_size:10mb'], description: 'Read/write files in workspace' },
SHELL_EXEC: { baseRisk: 0.8, defaultRestrictions: ['sandbox_only', 'no_sudo', 'timeout:30s', 'audit_required'], description: 'Execute shell commands' },
GIT: { baseRisk: 0.4, defaultRestrictions: ['local_repo_only', 'no_force_push'], description: 'Git operations' },
PACKAGE_MANAGER: { baseRisk: 0.6, defaultRestrictions: ['audit_required', 'no_global_install', 'lockfile_required'], description: 'npm/pip/cargo package management' },
BUILD_TOOL: { baseRisk: 0.5, defaultRestrictions: ['workspace_only', 'timeout:120s'], description: 'Build and compilation' },
// --- Infrastructure / DevOps ---
DOCKER: { baseRisk: 0.7, defaultRestrictions: ['no_privileged', 'no_host_network', 'audit_required'], description: 'Container operations' },
CLOUD_DEPLOY: { baseRisk: 0.9, defaultRestrictions: ['staging_only', 'approval_required', 'rollback_ready'], description: 'Cloud deployment' },
DATABASE: { baseRisk: 0.6, defaultRestrictions: ['read_only', 'max_records:1000', 'no_schema_changes'], description: 'Database access' },
// --- Communication / External ---
EXTERNAL_SERVICE: { baseRisk: 0.4, defaultRestrictions: ['rate_limit:10_per_minute'], description: 'External API calls' },
EMAIL: { baseRisk: 0.5, defaultRestrictions: ['rate_limit:5_per_minute', 'no_attachments'], description: 'Email sending' },
WEBHOOK: { baseRisk: 0.4, defaultRestrictions: ['allowed_domains_only', 'no_credentials'], description: 'Webhook dispatch' },
};
const DEFAULT_AGENT_TRUST: AgentTrustConfig[] = [
{ agentId: 'orchestrator', trustLevel: 0.9, allowedNamespaces: ['*'], allowedResources: ['*'] },
{ agentId: 'data_analyst', trustLevel: 0.8, allowedNamespaces: ['task:', 'analytics:', 'agent:'], allowedResources: ['SAP_API', 'DATABASE', 'DATA_EXPORT', 'EXTERNAL_SERVICE'] },
{ agentId: 'strategy_advisor', trustLevel: 0.7, allowedNamespaces: ['task:', 'strategy:'], allowedResources: ['EXTERNAL_SERVICE', 'DATA_EXPORT'] },
{ agentId: 'risk_assessor', trustLevel: 0.85, allowedNamespaces: ['task:', 'risk:', 'analytics:'], allowedResources: ['EXTERNAL_SERVICE', 'DATABASE'] },
// Coding agents
{ agentId: 'code_writer', trustLevel: 0.75, allowedNamespaces: ['task:', 'code:', 'build:'], allowedResources: ['FILE_SYSTEM', 'GIT', 'BUILD_TOOL', 'PACKAGE_MANAGER'] },
{ agentId: 'code_reviewer', trustLevel: 0.8, allowedNamespaces: ['task:', 'code:', 'review:'], allowedResources: ['FILE_SYSTEM', 'GIT'] },
{ agentId: 'test_runner', trustLevel: 0.75, allowedNamespaces: ['task:', 'test:', 'build:'], allowedResources: ['FILE_SYSTEM', 'SHELL_EXEC', 'BUILD_TOOL'] },
{ agentId: 'devops_agent', trustLevel: 0.7, allowedNamespaces: ['task:', 'deploy:', 'infra:'], allowedResources: ['DOCKER', 'SHELL_EXEC', 'CLOUD_DEPLOY', 'GIT'] },
];
// ============================================================================
// BLACKBOARD MANAGEMENT -- Secured with LockedBlackboard, identity verification,
// namespace scoping, value validation, and input sanitization
// ============================================================================
/**
* Namespace-scoped, identity-verified shared state for multi-agent coordination.
*
* Every write is identity-verified (agent token), namespace-checked,
* size-validated, input-sanitized, and atomically persisted through
* {@link LockedBlackboard}.
*
* @example
* ```typescript
* const bb = new SharedBlackboard('./workspace');
* bb.registerAgent('analyst', 'secret-token', ['task:', 'analytics:']);
* bb.write('task:revenue', { q4: 42_000 }, 'analyst', 3600, 'secret-token');
* const entry = bb.read('task:revenue');
* ```
*/
class SharedBlackboard {
private backend: BlackboardBackend;
private agentTokens: Map<string, string> = new Map(); // agentId -> verified token
private agentNamespaces: Map<string, string[]> = new Map(); // agentId -> allowed prefixes
constructor(backendOrPath: string | BlackboardBackend) {
if (typeof backendOrPath === 'string') {
if (!backendOrPath || backendOrPath.trim() === '') {
throw new ValidationError('basePath must be a non-empty string');
}
this.backend = new FileBackend(backendOrPath);
} else {
if (!backendOrPath || typeof backendOrPath !== 'object') {
throw new ValidationError('backend must be a BlackboardBackend instance');
}
this.backend = backendOrPath;
}
}
/**
* Register a verified agent identity. Only agents with registered tokens
* can write to the blackboard. The orchestrator registers agents after
* verifying their identity through the AuthGuardian.
*/
registerAgent(agentId: string, verificationToken: string, allowedNamespaces: string[] = ['*']): void {
if (!agentId || typeof agentId !== 'string' || agentId.trim() === '') {
throw new ValidationError('agentId must be a non-empty string');
}
if (!verificationToken || typeof verificationToken !== 'string') {
throw new ValidationError('verificationToken must be a non-empty string');
}
if (!Array.isArray(allowedNamespaces)) {
throw new ValidationError('allowedNamespaces must be an array of strings');
}
this.agentTokens.set(agentId, verificationToken);
this.agentNamespaces.set(agentId, allowedNamespaces);
}
/**
* Check if an agent is allowed to access a key based on namespace rules.
*/
private canAccessKey(agentId: string, key: string): boolean {
const namespaces = this.agentNamespaces.get(agentId);
if (!namespaces) return false;
if (namespaces.includes('*')) return true;
return namespaces.some(ns => key.startsWith(ns));
}
/**
* Verify that the calling agent is who they claim to be.
*/
private verifyAgent(agentId: string, token?: string): boolean {
const registeredToken = this.agentTokens.get(agentId);
// If no token system is configured for this agent, allow (backward compat)
if (!registeredToken) return true;
return token === registeredToken;
}
/**
* Validate value size and structure before writing.
* Prevents DoS via oversized writes and circular data.
*/
private validateValue(value: unknown): { valid: boolean; reason?: string } {
try {
const serialized = JSON.stringify(value);
if (serialized.length > CONFIG.maxBlackboardValueSize) {
return { valid: false, reason: `Value exceeds max size (${serialized.length} > ${CONFIG.maxBlackboardValueSize} bytes)` };
}
return { valid: true };
} catch {
return { valid: false, reason: 'Value cannot be serialized (circular reference or invalid structure)' };
}
}
/**
* Sanitize a key to prevent markdown injection.
*/
private sanitizeKey(key: string): string {
// Keys must be safe for markdown headings -- no #, newlines, or markdown syntax
return key.replace(/[#\n\r|`]/g, '_').slice(0, 256);
}
/**
* Read an entry from the blackboard by key.
*
* @param key - The entry key to look up
* @returns The entry, or `null` if not found or expired
* @throws {@link ValidationError} if `key` is not a non-empty string
*/
read(key: string): BlackboardEntry | null {
if (!key || typeof key !== 'string') {
throw new ValidationError('key must be a non-empty string');
}
const entry = this.backend.read(key);
if (!entry) return null;
// Normalize field name for backward compatibility
return {
key: entry.key,
value: entry.value,
sourceAgent: (entry as any).source_agent ?? (entry as any).sourceAgent ?? 'unknown',
timestamp: entry.timestamp,
ttl: entry.ttl,
};
}
/**
* Write to the blackboard with identity verification, namespace checks,
* value validation, and input sanitization. Uses LockedBlackboard for
* atomic file-system writes.
*
* @param key - The key to write
* @param value - The value (will be sanitized and size-checked)
* @param sourceAgent - Agent claiming to write (verified against registered token)
* @param ttl - Optional TTL in seconds
* @param agentToken - Optional verification token for identity check
*/
write(key: string, value: unknown, sourceAgent: string, ttl?: number, agentToken?: string): BlackboardEntry {
// 1. Verify agent identity
if (!this.verifyAgent(sourceAgent, agentToken)) {
throw new IdentityVerificationError(sourceAgent);
}
// 2. Namespace check
if (!this.canAccessKey(sourceAgent, key)) {
throw new NamespaceViolationError(sourceAgent, key);
}
// 3. Sanitize key
const safeKey = this.sanitizeKey(key);
// 4. Validate value size/structure
const validation = this.validateValue(value);
if (!validation.valid) {
throw new ValidationError(validation.reason!);
}
// 5. Sanitize value -- strip injection payloads from string content
let sanitizedValue: unknown;
try {
sanitizedValue = InputSanitizer.sanitizeObject(value);
} catch {
sanitizedValue = value; // Fall back to raw if sanitization can't handle it
}
// 6. Write through backend (atomic when using FileBackend; in-memory for MemoryBackend)
const entry = this.backend.write(safeKey, sanitizedValue, sourceAgent, ttl);
// Normalize for backward compat
return {
key: entry.key,
value: entry.value,
sourceAgent: (entry as any).source_agent ?? sourceAgent,
timestamp: entry.timestamp,
ttl: entry.ttl,
};
}
/**
* Check whether a key exists on the blackboard (not expired).
* @param key - The entry key to check
*/
exists(key: string): boolean {
return this.read(key) !== null;
}
/**
* Get a full snapshot of all blackboard entries.
*/
getSnapshot(): Record<string, BlackboardEntry> {
const raw = this.backend.getSnapshot();
const normalized: Record<string, BlackboardEntry> = {};
for (const [key, entry] of Object.entries(raw)) {
normalized[key] = {
key: entry.key,
value: entry.value,
sourceAgent: (entry as any).source_agent ?? (entry as any).sourceAgent ?? 'unknown',
timestamp: entry.timestamp,
ttl: entry.ttl,
};
}
return normalized;
}
/**
* Get a namespace-scoped snapshot -- only returns keys an agent is allowed to see.
* Prevents data leakage between agents.
*/
getScopedSnapshot(agentId: string): Record<string, BlackboardEntry> {
if (!agentId || typeof agentId !== 'string') {
throw new ValidationError('agentId must be a non-empty string');
}
const full = this.getSnapshot();
const scoped: Record<string, BlackboardEntry> = {};
for (const [key, entry] of Object.entries(full)) {
if (this.canAccessKey(agentId, key)) {
scoped[key] = entry;
}
}
return scoped;
}
/**
* Clear all entries (for testing).
*/
clear(): void {
// Write an empty state through locked backend
const keys = this.backend.listKeys();
for (const key of keys) {
this.backend.delete(key);
}
}
}
// ============================================================================
// AUTH GUARDIAN - UNIVERSAL PERMISSION WALL IMPLEMENTATION
// Now domain-agnostic: resource types, risk profiles, trust levels, and
// restrictions are all configurable. Works for coding, finance, devops, etc.
// Integrates with SecureSwarmGateway for HMAC tokens, rate limiting,
// input sanitization, and cryptographic audit logs.
// ============================================================================
/**
* Universal permission wall for multi-agent systems.
*
* Evaluates permission requests using a weighted formula of justification
* quality (40%), agent trust level (30%), and risk score (30%).
* Resource types, risk profiles, trust levels, and restrictions are all
* configurable — works for coding, finance, DevOps, or any domain.
*
* @example
* ```typescript
* const guardian = new AuthGuardian({
* trustLevels: [{ agentId: 'analyst', trustLevel: 0.8 }],
* resourceProfiles: { CUSTOM_API: { baseRisk: 0.5, defaultRestrictions: ['audit_required'] } },
* });
*
* const grant = await guardian.requestPermission(
* 'analyst', 'CUSTOM_API', 'Need to fetch Q4 revenue data for report', 'read'
* );
* if (grant.granted) {
* // Use grant.grantToken to prove authorization
* }
* ```
*/
class AuthGuardian {
private activeGrants: Map<string, ActiveGrant> = new Map();
private agentTrustLevels: Map<string, number> = new Map();
private agentTrustConfigs: Map<string, AgentTrustConfig> = new Map();
private resourceProfiles: Map<string, ResourceProfile> = new Map();
private auditLog: Array<{ timestamp: string; action: string; details: unknown }> = [];
private auditLogPath: string;
private trustConfigPath: string;
private readonly signingAlgorithm: 'hmac-sha256' | 'ed25519';
private readonly hmacSecret: string;
private readonly ed25519PrivateKey: KeyObject | null;
private readonly ed25519PublicKey: KeyObject | null;
constructor(options?: {
trustLevels?: AgentTrustConfig[];
resourceProfiles?: Record<string, ResourceProfile>;
auditLogPath?: string;
trustConfigPath?: string;
/** Signing algorithm for grant tokens. Default: 'hmac-sha256'. */
algorithm?: 'hmac-sha256' | 'ed25519';
/** HMAC secret (only used when algorithm is 'hmac-sha256'). Auto-generated if omitted. */
hmacSecret?: string;
}) {
this.auditLogPath = options?.auditLogPath ?? CONFIG.auditLogPath;
this.trustConfigPath = options?.trustConfigPath ?? CONFIG.trustConfigPath;
this.signingAlgorithm = options?.algorithm ?? 'hmac-sha256';
if (this.signingAlgorithm === 'ed25519') {
const { publicKey, privateKey } = generateKeyPairSync('ed25519');
this.ed25519PrivateKey = privateKey;
this.ed25519PublicKey = publicKey;
this.hmacSecret = '';
} else {
this.ed25519PrivateKey = null;
this.ed25519PublicKey = null;
this.hmacSecret = options?.hmacSecret ?? randomUUID();
}
// Load resource profiles (user-provided + defaults)
const profiles = { ...DEFAULT_RESOURCE_PROFILES, ...(options?.resourceProfiles ?? {}) };
for (const [name, profile] of Object.entries(profiles)) {
this.resourceProfiles.set(name, profile);
}
// Load trust levels (try disk first, then user-provided, then defaults)
const trustConfigs = options?.trustLevels ?? this.loadTrustFromDisk() ?? DEFAULT_AGENT_TRUST;
for (const config of trustConfigs) {
this.agentTrustLevels.set(config.agentId, config.trustLevel);
this.agentTrustConfigs.set(config.agentId, config);
}
// Load existing audit log from disk
this.loadAuditFromDisk();
}
/**
* Register a new resource type at runtime.
* Makes the system extensible for any domain.
*/
registerResourceType(name: string, profile: ResourceProfile): void {
if (!name || typeof name !== 'string' || name.trim() === '') {
throw new ValidationError('resource name must be a non-empty string');
}
if (!profile || typeof profile !== 'object' || typeof profile.baseRisk !== 'number') {
throw new ValidationError('profile must be an object with a numeric baseRisk');
}
if (profile.baseRisk < 0 || profile.baseRisk > 1) {
throw new ValidationError('profile.baseRisk must be between 0 and 1');
}
if (!Array.isArray(profile.defaultRestrictions)) {
throw new ValidationError('profile.defaultRestrictions must be an array');
}
this.resourceProfiles.set(name, profile);
}
/**
* Register or update an agent's trust configuration at runtime.
*/
registerAgentTrust(config: AgentTrustConfig): void {
if (!config || typeof config !== 'object') {
throw new ValidationError('config must be an object');
}
if (!config.agentId || typeof config.agentId !== 'string' || config.agentId.trim() === '') {
throw new ValidationError('config.agentId must be a non-empty string');
}
if (typeof config.trustLevel !== 'number' || config.trustLevel < 0 || config.trustLevel > 1) {
throw new ValidationError('config.trustLevel must be a number between 0 and 1');
}
this.agentTrustLevels.set(config.agentId, config.trustLevel);
this.agentTrustConfigs.set(config.agentId, config);
this.persistTrustToDisk();
}
/**
* Request permission to access a resource.
* resourceType is now a free string -- validated against registered profiles.
*/
async requestPermission(
agentId: string,
resourceType: string,
justification: string,
scope?: string
): Promise<PermissionGrant> {
if (!agentId || typeof agentId !== 'string') {
throw new ValidationError('agentId must be a non-empty string');
}
if (!resourceType || typeof resourceType !== 'string') {
throw new ValidationError('resourceType must be a non-empty string');
}
if (!justification || typeof justification !== 'string') {
throw new ValidationError('justification must be a non-empty string');
}
// Sanitize inputs
let safeAgentId: string;
let safeJustification: string;
try {
safeAgentId = InputSanitizer.sanitizeAgentId(agentId);
safeJustification = InputSanitizer.sanitizeString(justification, 2000);
} catch {
safeAgentId = agentId.replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 64) || 'unknown';
safeJustification = justification.slice(0, 2000);
}
this.log('permission_request', { agentId: safeAgentId, resourceType, justification: safeJustification, scope });
// Check if agent is allowed to access this resource type
const agentConfig = this.agentTrustConfigs.get(safeAgentId);
if (agentConfig && agentConfig.allowedResources && !agentConfig.allowedResources.includes('*')) {
if (!agentConfig.allowedResources.includes(resourceType)) {
this.log('permission_denied', { agentId: safeAgentId, resourceType, reason: 'resource_not_in_allowlist' });
return {
granted: false,
grantToken: null,
expiresAt: null,
restrictions: [],
reason: `Agent '${safeAgentId}' is not authorized to access '${resourceType}'. Allowed: ${agentConfig.allowedResources.join(', ')}`,
};
}
}
// Evaluate the permission request
const evaluation = this.evaluateRequest(safeAgentId, resourceType, safeJustification, scope);
if (!evaluation.approved) {
this.log('permission_denied', { agentId: safeAgentId, resourceType, reason: evaluation.reason });
return {
granted: false,
grantToken: null,
expiresAt: null,
restrictions: [],
reason: evaluation.reason,
};
}
// Generate grant token
const grantToken = this.generateGrantToken();
const expiresAt = new Date(Date.now() + CONFIG.grantTokenTTL).toISOString();
const grant: ActiveGrant = {
grantToken,
resourceType,
agentId: safeAgentId,
expiresAt,
restrictions: evaluation.restrictions,
scope,
};
this.activeGrants.set(grantToken, grant);
this.log('permission_granted', { grantToken, agentId: safeAgentId, resourceType, expiresAt, restrictions: evaluation.restrictions });
return {
granted: true,
grantToken,
expiresAt,
restrictions: evaluation.restrictions,
};
}
/**
* Validate a grant token and return `true` if it is active and not expired.
*
* @param token - The grant token to validate
* @returns `true` if the token is valid, `false` otherwise
*/
validateToken(token: string): boolean {
if (!token || typeof token !== 'string') return false;
const grant = this.activeGrants.get(token);
if (!grant) return false;
if (new Date(grant.expiresAt) < new Date()) {
this.activeGrants.delete(token);
return false;
}
return true;
}
/**
* Validate a token and return the bound restrictions and scope.
* Used to enforce restrictions at the point of use.
*/
/**
* Validate a token and return the full grant object (including restrictions
* and scope) for point-of-use enforcement.
*
* @param token - The grant token to validate
* @returns The grant details, or `null` if invalid/expired
*/
validateTokenWithGrant(token: string): ActiveGrant | null {
if (!token || typeof token !== 'string') return null;
const grant = this.activeGrants.get(token);
if (!grant) return null;
if (new Date(grant.expiresAt) < new Date()) {
this.activeGrants.delete(token);
return null;
}
return grant;
}
/**
* Enforce restrictions on an operation. Returns an error string if
* the operation violates any restriction, or null if allowed.
*/
/**
* Enforce restrictions on an operation. Returns an error string if
* the operation violates any restriction, or `null` if all restrictions pass.
*
* @param grantToken - The grant token authorizing the operation
* @param operation - Description of the operation to check against restrictions
* @returns Error message string if a restriction is violated, or `null` if allowed
*/
enforceRestrictions(grantToken: string, operation: {
type?: string; // 'read' | 'write' | 'delete' | 'execute'
recordCount?: number;
hasAttachments?: boolean;
targetPath?: string;
command?: string;
}): string | null {
if (!grantToken || typeof grantToken !== 'string') {
return 'Invalid or expired grant token';
}
const grant = this.validateTokenWithGrant(grantToken);
if (!grant) return 'Invalid or expired grant token';
for (const restriction of grant.restrictions) {
// Enforce read_only
if (restriction === 'read_only' && operation.type && operation.type !== 'read') {
return `Restriction 'read_only' violated: attempted '${operation.type}'`;
}
// Enforce max_records
const maxRecordsMatch = restriction.match(/^max_records:(\d+)$/);
if (maxRecordsMatch && operation.recordCount) {
const max = parseInt(maxRecordsMatch[1], 10);
if (operation.recordCount > max) {
return `Restriction '${restriction}' violated: requested ${operation.recordCount} records`;
}
}
// Enforce sandbox_only
if (restriction === 'sandbox_only' && operation.targetPath) {
if (/^\/|^[A-Z]:\\(?:Windows|Program)/i.test(operation.targetPath)) {
return `Restriction 'sandbox_only' violated: path '${operation.targetPath}' is outside sandbox`;
}
}
// Enforce no_sudo
if (restriction === 'no_sudo' && operation.command) {
if (/\bsudo\b/i.test(operation.command)) {
return `Restriction 'no_sudo' violated: command contains sudo`;
}
}
// Enforce workspace_only
if (restriction === 'workspace_only' && operation.targetPath) {
if (/\.\.[/\\]/.test(operation.targetPath)) {
return `Restriction 'workspace_only' violated: path traversal detected`;
}
}
// Enforce no_system_dirs
if (restriction === 'no_system_dirs' && operation.targetPath) {
if (/(?:\/etc|\/usr|\/var|\\Windows|\\System32)/i.test(operation.targetPath)) {
return `Restriction 'no_system_dirs' violated: system directory access`;
}
}
// Enforce no_attachments
if (restriction === 'no_attachments' && operation.hasAttachments) {
return `Restriction 'no_attachments' violated`;
}
}
return null; // All restrictions passed
}
/**
* Revoke a grant token, immediately invalidating it.
* Silently no-ops if the token doesn't exist.
*
* @param token - The grant token to revoke
*/
revokeToken(token: string): void {
this.activeGrants.delete(token);
this.log('permission_revoked', { token });
}
private evaluateRequest(
agentId: string,
resourceType: string,
justification: string,
scope?: string
): { approved: boolean; reason?: string; restrictions: string[] } {
// 1. Justification Quality (40% weight) -- now includes resource-relevance
const justificationScore = this.scoreJustification(justification, resourceType);
if (justificationScore < 0.3) {
return {
approved: false,
reason: 'Justification is insufficient. Please provide specific task context.',
restrictions: [],
};
}
// 2. Agent Trust Level (30% weight)
const trustLevel = this.agentTrustLevels.get(agentId) ?? 0.5;
if (trustLevel < 0.4) {
return {
approved: false,
reason: 'Agent trust level is below threshold. Escalate to human operator.',
restrictions: [],
};
}
// 3. Risk Assessment (30% weight)
const riskScore = this.assessRisk(resourceType, scope);
if (riskScore > 0.8) {
return {
approved: false,
reason: 'Risk assessment exceeds acceptable threshold. Narrow the requested scope.',
restrictions: [],
};
}