-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathagent.ts
More file actions
1118 lines (1019 loc) · 53.5 KB
/
Copy pathagent.ts
File metadata and controls
1118 lines (1019 loc) · 53.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
/**
* MIT No Attribution
*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import * as path from 'path';
import * as bedrock from '@aws-cdk/aws-bedrock-alpha';
import { ArnFormat, AspectPriority, Aspects, Stack, StackProps, RemovalPolicy, CfnOutput, CfnResource, Duration, Fn, Lazy } from 'aws-cdk-lib';
import * as agentcore from 'aws-cdk-lib/aws-bedrockagentcore';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
// ecr_assets import is only needed when the ECS block below is uncommented
// import * as ecr_assets from 'aws-cdk-lib/aws-ecr-assets';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as logs from 'aws-cdk-lib/aws-logs';
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager';
import * as cr from 'aws-cdk-lib/custom-resources';
import { NagSuppressions } from 'cdk-nag';
import { Construct, IConstruct } from 'constructs';
import { AgentMemory } from '../constructs/agent-memory';
import { AgentSessionRole } from '../constructs/agent-session-role';
import { AgentVpc } from '../constructs/agent-vpc';
import { ApprovalMetricsPublisherConsumer } from '../constructs/approval-metrics-publisher-consumer';
import { AttachmentsBucket } from '../constructs/attachments-bucket';
import { resolveBedrockModelIds } from '../constructs/bedrock-models';
import { Blueprint } from '../constructs/blueprint';
import { CedarWasmLayer } from '../constructs/cedar-wasm-layer';
import { ConcurrencyReconciler } from '../constructs/concurrency-reconciler';
import { DnsFirewall } from '../constructs/dns-firewall';
// import { EcsAgentCluster } from '../constructs/ecs-agent-cluster';
import { FanOutConsumer } from '../constructs/fanout-consumer';
import { GitHubScreenshotIntegration } from '../constructs/github-screenshot-integration';
import { JiraIntegration } from '../constructs/jira-integration';
import { LinearIntegration } from '../constructs/linear-integration';
import { PendingUploadCleanup } from '../constructs/pending-upload-cleanup';
import { RepoTable } from '../constructs/repo-table';
import { SlackIntegration } from '../constructs/slack-integration';
import { StrandedTaskReconciler } from '../constructs/stranded-task-reconciler';
import { TaskApi } from '../constructs/task-api';
import { TaskApprovalsTable } from '../constructs/task-approvals-table';
import { TaskDashboard } from '../constructs/task-dashboard';
import { TaskEventsTable } from '../constructs/task-events-table';
import { TaskNudgesTable } from '../constructs/task-nudges-table';
import { TaskOrchestrator } from '../constructs/task-orchestrator';
import { TaskTable } from '../constructs/task-table';
import { TraceArtifactsBucket } from '../constructs/trace-artifacts-bucket';
import { UserConcurrencyTable } from '../constructs/user-concurrency-table';
import { WebhookTable } from '../constructs/webhook-table';
/** Max length of the Bedrock Guardrail name (CloudFormation constraint). */
const GUARDRAIL_NAME_MAX_LENGTH = 50;
/** AgentCore Runtime session lifecycle ceiling (hours) — the AgentCore maximum. */
const RUNTIME_SESSION_TIMEOUT_HOURS = 8;
/** Index of the stage segment in a split API Gateway URL. */
const API_URL_STAGE_SEGMENT_INDEX = 3;
export class AgentStack extends Stack {
constructor(scope: Construct, id: string, props: StackProps = {}) {
super(scope, id, props);
// Build context is repo root (not agent/) so the Dockerfile can COPY
// sibling trees the agent reads at runtime — currently
// ``contracts/constants.json`` (S9 cross-language constants — see
// ``contracts/README.md``). Future shared assets (parity fixtures,
// schema files) drop into ``contracts/`` without further build-context
// changes. Pattern lifted from ``merge/akw-integration``.
const repoRoot = path.join(__dirname, '..', '..', '..');
const artifact = agentcore.AgentRuntimeArtifact.fromAsset(repoRoot, {
file: 'agent/Dockerfile',
});
// Task state persistence
const taskTable = new TaskTable(this, 'TaskTable');
const taskEventsTable = new TaskEventsTable(this, 'TaskEventsTable');
const taskNudgesTable = new TaskNudgesTable(this, 'TaskNudgesTable');
// Cedar HITL approval-gate state (design §10.1). Agent writes PENDING
// rows + GSI query powers `bgagent pending`; Chunk 5 wires the
// Approve/Deny Lambdas + fan-out consumer.
//
// Construct id is ``TaskApprovalsTableV2`` — the original
// ``TaskApprovalsTable`` logical id was abandoned mid-development
// after the first ship of the ``user_id-status-index`` GSI. Adding
// ``matching_rule_ids`` to the projection required a destructive
// recreate (DDB rejects in-place ``nonKeyAttributes`` edits), so
// the construct id changed to force CloudFormation to create the
// new table under a fresh logical resource while tearing down the
// old one. Acceptable in dev; in a future prod migration the
// dual-index pattern is preferred (see §10.1 of the design doc).
const taskApprovalsTable = new TaskApprovalsTable(this, 'TaskApprovalsTableV2');
const userConcurrencyTable = new UserConcurrencyTable(this, 'UserConcurrencyTable');
const webhookTable = new WebhookTable(this, 'WebhookTable');
const repoTable = new RepoTable(this, 'RepoTable');
// Cedar-wasm Lambda layer (§15.2 task 10). Instantiated here so the
// asset is in the synthed template; Chunk 5 handlers (Approve,
// Deny, GetPolicies, CreateTask) attach the layer via
// ``fn.addLayers(cedarWasmLayer.layer)``.
const cedarWasmLayer = new CedarWasmLayer(this, 'CedarWasmLayer');
// --trace trajectory storage (design §10.1). Opt-in per task; only
// written when the submit payload sets ``trace: true``.
const traceArtifactsBucket = new TraceArtifactsBucket(this, 'TraceArtifactsBucket');
// Attachment storage — images, files, and URL-fetched content for tasks.
const attachmentsBucket = new AttachmentsBucket(this, 'AttachmentsBucket');
NagSuppressions.addResourceSuppressions(attachmentsBucket.bucket, [
{
id: 'AwsSolutions-S1',
reason: 'Task attachments: writes from create-task and orchestrator Lambdas only; reads by agent via IAM role. 90-day lifecycle; versioning + screening prevent TOCTOU. Access logging not justified for this use case.',
},
]);
// Server access logging intentionally disabled. Rationale:
// - writes: only the agent runtime IAM role (``grantPut`` below).
// - reads: only via short-lived presigned URL issued by
// ``get-trace-url`` after a Cognito auth check + ownership
// check against the TaskRecord.
// - 7-day object TTL bounds blast radius.
// - adding a log bucket would double S3 footprint for a debug-only
// feature users explicitly opt into with ``--trace``.
// Note: default CloudTrail does NOT capture S3 object-level
// events (PutObject / GetObject via presigned URL), so there is
// intentionally no object-level audit trail for this bucket. That
// is an accepted trade-off for a sample-project debug feature —
// the cost/complexity of CloudTrail data events or a log bucket
// is not justified for opt-in ``--trace`` usage. If a future
// requirement needs audit, the right fix is a CloudTrail data
// event selector on this bucket, not server access logs.
NagSuppressions.addResourceSuppressions(traceArtifactsBucket.bucket, [
{
id: 'AwsSolutions-S1',
reason: 'Debug-only artifacts (design §10.1) with 7-day TTL; writes confined to runtime IAM role by grantPut; reads only via short-lived presigned URLs from an authn\'d handler. Object-level audit intentionally omitted — cost/complexity of CloudTrail data events or a log bucket is not justified for opt-in --trace usage.',
},
]);
// --- Repository onboarding ---
const blueprintRepo = process.env.BLUEPRINT_REPO ?? this.node.tryGetContext('blueprintRepo') ?? 'awslabs/agent-plugins';
const agentPluginsBlueprint = new Blueprint(this, 'AgentPluginsBlueprint', {
repo: blueprintRepo,
repoTable: repoTable.table,
});
const blueprints = [agentPluginsBlueprint];
// The AwsCustomResource singleton Lambda used by Blueprint constructs
NagSuppressions.addResourceSuppressionsByPath(this, [
`${this.stackName}/AWS679f53fac002430cb0da5b7982bd2287/ServiceRole/Resource`,
`${this.stackName}/AWS679f53fac002430cb0da5b7982bd2287/Resource`,
], [
{
id: 'AwsSolutions-IAM4',
reason: 'AwsCustomResource singleton Lambda uses AWS managed AWSLambdaBasicExecutionRole — required by CDK custom-resources framework',
},
{
id: 'AwsSolutions-L1',
reason: 'AwsCustomResource singleton Lambda runtime is managed by the CDK custom-resources framework',
},
]);
// Log groups (created before runtime so we can reference the name in env vars)
const applicationLogGroup = new logs.LogGroup(this, 'RuntimeApplicationLogGroup', {
logGroupName: `/aws/vendedlogs/bedrock-agentcore/runtime/APPLICATION_LOGS/${this.stackName}`,
retention: logs.RetentionDays.THREE_MONTHS,
removalPolicy: RemovalPolicy.DESTROY,
});
const usageLogGroup = new logs.LogGroup(this, 'RuntimeUsageLogGroup', {
logGroupName: `/aws/vendedlogs/bedrock-agentcore/runtime/USAGE_LOGS/${this.stackName}`,
retention: logs.RetentionDays.THREE_MONTHS,
removalPolicy: RemovalPolicy.DESTROY,
});
// GitHub token stored in Secrets Manager — agent fetches at startup via ARN
const githubTokenSecret = new secretsmanager.Secret(this, 'GitHubTokenSecret', {
description: 'GitHub personal access token for the background agent',
removalPolicy: RemovalPolicy.DESTROY,
});
NagSuppressions.addResourceSuppressions(githubTokenSecret, [
{
id: 'AwsSolutions-SMG4',
reason: 'GitHub PAT is managed externally — automatic rotation is not applicable',
},
]);
// Network isolation — VPC with restricted egress
// AgentCore only supports a subset of physical availability zones per
// region (for us-east-1: use1-az1, use1-az2, use1-az4). AZ *names* are
// aliased per-account, so the default maxAzs selection can land in an
// unsupported zone and cause a deploy failure. Use the CDK context key
// `agentcore:availabilityZones` to pin to account-specific AZ names whose
// physical zone IDs are AgentCore-supported.
//
// Discover your mapping:
// aws ec2 describe-availability-zones --region us-east-1 \
// --query 'AvailabilityZones[].[ZoneName,ZoneId]' --output text
//
// Then set in cdk.context.json or via -c:
// "agentcore:availabilityZones": ["us-east-1b", "us-east-1c"]
const agentCoreAzs = this.node.tryGetContext('agentcore:availabilityZones') as string[] | undefined;
const agentVpc = new AgentVpc(this, 'AgentVpc', {
...(agentCoreAzs ? { availabilityZones: agentCoreAzs } : {}),
});
// DNS Firewall — domain-level egress filtering (observation mode for initial deployment)
const additionalDomains = [...new Set(blueprints.flatMap(b => b.egressAllowlist))];
new DnsFirewall(this, 'DnsFirewall', {
vpc: agentVpc.vpc,
additionalAllowedDomains: additionalDomains,
observationMode: true,
});
// --- AgentCore Memory (cross-task learning) ---
const agentMemory = new AgentMemory(this, 'AgentMemory');
// --- Bedrock Guardrail for prompt injection detection ---
// (Declared early so TaskApi — constructed before the runtimes — can reference it.)
const inputGuardrail = new bedrock.Guardrail(this, 'InputGuardrail', {
guardrailName: `task-input-guardrail-${this.stackName}`.slice(0, GUARDRAIL_NAME_MAX_LENGTH),
description: 'Screens task submissions for prompt injection attacks',
contentFilters: [
{
type: bedrock.ContentFilterType.PROMPT_ATTACK,
// MEDIUM blocks on MEDIUM+HIGH confidence; LOW-confidence
// detections are ignored. Observed during PR #52 Scenario
// 7-extended deploy validation: at HIGH (blocks LOW too) the
// PROMPT_ATTACK classifier is stochastic at the LOW tier and
// flags ordinary imperative-mood task descriptions and
// ordinary PR bodies (pr_iteration hydration). MEDIUM matches
// the Bedrock documentation's default for non-adversarial
// user input. The previous threshold blocked legitimate
// natural-language submissions (e.g. "Make no changes, just
// inspect README.md and finish.", "enumerate every plugin in
// extreme detail") and legitimate pr_iteration hydrations
// against PRs containing normal imperative documentation.
inputStrength: bedrock.ContentFilterStrength.MEDIUM,
outputStrength: bedrock.ContentFilterStrength.NONE,
},
],
});
inputGuardrail.createVersion('Initial version');
// --- TaskApi is constructed before the orchestrator (which it needs the
// ARN of) and before the Runtime (which it needs the ARN of, for the
// cancel-task Lambda's stop-session permission). We break both cycles
// with Lazy strings that resolve to CloudFormation tokens at synth time.
let orchestratorArnHolder: string | undefined;
const lazyOrchestratorArn = Lazy.string({
produce: () => {
if (!orchestratorArnHolder) {
throw new Error('Orchestrator ARN was accessed before the TaskOrchestrator was created');
}
return orchestratorArnHolder;
},
});
// Runtime ARN placeholder — the runtime is created AFTER TaskApi so the
// Lambda handlers can get their env var via a Lazy.string reference.
let runtimeArnHolder: string | undefined;
const lazyRuntimeArn = Lazy.string({
produce: () => {
if (!runtimeArnHolder) {
throw new Error('Runtime ARN was accessed before Runtime was created');
}
return runtimeArnHolder;
},
});
// SessionRole ARN placeholder — the per-task SessionRole (#209) is created
// AFTER the Runtime (it lists runtime.role as an assuming principal), but
// its ARN must be injected into the runtime's environment so the agent can
// assume it. Break the cycle with a Lazy.string, same pattern as above.
let sessionRoleArnHolder: string | undefined;
const lazySessionRoleArn = Lazy.string({
produce: () => {
if (!sessionRoleArnHolder) {
throw new Error('SessionRole ARN was accessed before AgentSessionRole was created');
}
return sessionRoleArnHolder;
},
});
// --- Task API (REST API + Cognito + Lambda handlers) ---
const taskApi = new TaskApi(this, 'TaskApi', {
taskTable: taskTable.table,
taskEventsTable: taskEventsTable.table,
taskNudgesTable: taskNudgesTable.table,
taskApprovalsTable: taskApprovalsTable.table,
cedarWasmLayer: cedarWasmLayer.layer,
repoTable: repoTable.table,
webhookTable: webhookTable.table,
orchestratorFunctionArn: lazyOrchestratorArn,
guardrailId: inputGuardrail.guardrailId,
guardrailVersion: inputGuardrail.guardrailVersion,
agentCoreStopSessionRuntimeArn: lazyRuntimeArn,
traceArtifactsBucket: traceArtifactsBucket.bucket,
attachmentsBucket: attachmentsBucket.bucket,
userConcurrencyTable: userConcurrencyTable.table,
});
// --- AgentCore Runtime (IAM-authed orchestrator path) ---
//
// One runtime, invoked by OrchestratorFn via SigV4. See
// `docs/design/INTERACTIVE_AGENTS.md` §3.1 and AD-1.
const runtimeEnvironmentVariables = {
GITHUB_TOKEN_SECRET_ARN: githubTokenSecret.secretArn,
AWS_REGION: process.env.AWS_REGION ?? 'us-east-1',
CLAUDE_CODE_USE_BEDROCK: '1',
ANTHROPIC_LOG: 'debug',
// Cross-region inference-profile id (``us.`` prefix), NOT the bare
// foundation-model id: Claude 4.x can't be invoked on-demand by bare id
// (400 "on-demand throughput isn't supported"). Must match a granted
// profile (see bedrock-models.ts). runner.py re-sets this at spawn time.
ANTHROPIC_DEFAULT_HAIKU_MODEL: 'us.anthropic.claude-haiku-4-5-20251001-v1:0',
TASK_TABLE_NAME: taskTable.table.tableName,
TASK_EVENTS_TABLE_NAME: taskEventsTable.table.tableName,
NUDGES_TABLE_NAME: taskNudgesTable.table.tableName,
// Cedar HITL approval gates (§6.5). Agent's task_state primitives
// use this to write PENDING rows + transition tasks to
// AWAITING_APPROVAL; absent → hook fails closed with
// ``approval_write_failed`` (the `ApprovalTablesUnavailable` path).
TASK_APPROVALS_TABLE_NAME: taskApprovalsTable.table.tableName,
// Hint for the hook's remaining-maxLifetime calculation (§6.5
// pseudocode line 793). Kept in sync with the AgentCore
// lifecycle configuration below so drift is visible. 8 hours.
AGENTCORE_MAX_LIFETIME_S: '28800',
USER_CONCURRENCY_TABLE_NAME: userConcurrencyTable.table.tableName,
// Per-task SessionRole (#209): the agent assumes this with session tags
// {user_id, repo, task_id} and uses the scoped creds for tenant-data
// (DDB/S3) access. Resolved lazily — the role lists runtime.role as an
// assuming principal, so it is created after the runtime.
AGENT_SESSION_ROLE_ARN: lazySessionRoleArn,
// --trace artifact store (§10.1). The agent writes the JSONL
// trajectory to ``traces/<user_id>/<task_id>.jsonl.gz`` on
// terminal state when the submit payload enabled ``trace``.
TRACE_ARTIFACTS_BUCKET_NAME: traceArtifactsBucket.bucket.bucketName,
// Repo-less deliverable artifacts (#248 Phase 3): a deliver_artifact step
// uploads its product to ``artifacts/<task_id>/`` in the same bucket.
ARTIFACTS_BUCKET_NAME: traceArtifactsBucket.bucket.bucketName,
LOG_GROUP_NAME: applicationLogGroup.logGroupName,
MEMORY_ID: agentMemory.memory.memoryId,
MAX_TURNS: '100',
// Session storage: the S3-backed FUSE mount at /mnt/workspace does NOT
// support flock(). Only caches whose tools never call flock() go there.
// Everything else stays on local ephemeral disk.
//
// Local disk (tools use flock):
// AGENT_WORKSPACE — omitted, defaults to /workspace
// MISE_DATA_DIR — mise's pipx backend sets UV_TOOL_DIR inside installs/,
// and uv flocks that directory → must be local.
MISE_DATA_DIR: '/tmp/mise-data',
UV_CACHE_DIR: '/tmp/uv-cache',
// Persistent mount (no flock):
CLAUDE_CONFIG_DIR: '/mnt/workspace/.claude-config',
npm_config_cache: '/mnt/workspace/.npm-cache',
// ENABLE_CLI_TELEMETRY: '1',
};
const runtimeNetworkConfig = agentcore.RuntimeNetworkConfiguration.usingVpc(this, {
vpc: agentVpc.vpc,
vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS },
securityGroups: [agentVpc.runtimeSecurityGroup],
});
// LifecycleConfiguration — both timers set to the AgentCore 8h maximum so
// long-running tasks (approval waits, heavy builds) are not evicted.
const lifecycleConfiguration: agentcore.LifecycleConfiguration = {
idleRuntimeSessionTimeout: Duration.hours(RUNTIME_SESSION_TIMEOUT_HOURS),
maxLifetime: Duration.hours(RUNTIME_SESSION_TIMEOUT_HOURS),
};
// Construct id 'Runtime' is load-bearing — renaming it forces CFN to
// CREATE the new resource before DELETING the old one, violating
// AgentCore's account-level runtimeName uniqueness and triggering an
// UPDATE_ROLLBACK.
const runtime = new agentcore.Runtime(this, 'Runtime', {
agentRuntimeArtifact: artifact,
networkConfiguration: runtimeNetworkConfig,
environmentVariables: runtimeEnvironmentVariables,
lifecycleConfiguration: lifecycleConfiguration,
loggingConfigs: [
{
logType: agentcore.LogType.APPLICATION_LOGS,
destination: agentcore.LoggingDestination.cloudWatchLogs(applicationLogGroup),
},
{
logType: agentcore.LogType.USAGE_LOGS,
destination: agentcore.LoggingDestination.cloudWatchLogs(usageLogGroup),
},
],
});
runtimeArnHolder = runtime.agentRuntimeArn;
// --- Session storage (preview) ---
// The L2 construct does not yet expose filesystemConfigurations; use the
// CFN escape hatch. /mnt/workspace mount backs the persistent cache
// shared across tasks in the same repo.
const cfnRuntime = runtime.node.defaultChild as CfnResource;
cfnRuntime.addPropertyOverride('FilesystemConfigurations', [
{
SessionStorage: {
MountPath: '/mnt/workspace',
},
},
]);
// --- IAM grants ---
// Per-session IAM scoping (#209): tenant-data access (the four
// task_id-partitioned tables + the agent's trace/attachment S3 objects)
// is NOT granted to the runtime ExecutionRole. Instead the agent assumes a
// per-task SessionRole (created below) with session tags
// {user_id, repo, task_id}, and that role carries the tenant-data grants
// constrained by aws:PrincipalTag conditions. The runtime role keeps only
// non-tenant / shared access:
// - UserConcurrencyTable: user-scoped counter (agent path does not write
// it today; left here for the reconciler/orchestrator parity).
// - GitHub PAT secret: read once at startup, before the agent assumes the
// SessionRole.
// - CloudWatch Logs + AgentCore Memory: shared/non-tenant.
userConcurrencyTable.table.grantReadWriteData(runtime);
githubTokenSecret.grantRead(runtime);
applicationLogGroup.grantWrite(runtime);
agentMemory.grantReadWrite(runtime);
// Grant the runtime invoke on each configured foundation model + its US
// cross-Region inference profile. The model set is a single source of truth
// (constructs/bedrock-models.ts, #434), shared with the ECS task role and
// overridable via the `bedrockModels` CDK context. Each invokable is also
// collected so the same set is granted to the SessionRole below (#215 cost
// attribution) — the two grants derive from one list and can't drift.
// Scoping stays per-model (no Resource:'*'); account-level Bedrock access
// remains the outer gate.
const invokableBedrockModels: bedrock.IBedrockInvokable[] = [];
for (const modelId of resolveBedrockModelIds(this.node)) {
const foundationModel = new bedrock.BedrockFoundationModel(modelId, {
supportsAgents: true,
supportsCrossRegion: true,
});
const crossRegionProfile = bedrock.CrossRegionInferenceProfile.fromConfig({
geoRegion: bedrock.CrossRegionInferenceProfileRegion.US,
model: foundationModel,
});
foundationModel.grantInvoke(runtime);
crossRegionProfile.grantInvoke(runtime);
invokableBedrockModels.push(foundationModel, crossRegionProfile);
}
// --- Per-task SessionRole (#209) ---
// Holds the tenant-data grants (the four task_id-partitioned tables, plus
// per-user-prefixed trace writes and attachment reads), each constrained
// by aws:PrincipalTag conditions so a compromised session reaches only its
// own task's data. The agent assumes this with refreshable credentials
// (1h role-chaining cap, tasks run to 8h). Trust admits the runtime
// ExecutionRole as the assuming principal; the ECS task role is added in
// the ECS block below when that backend is enabled.
const agentSessionRole = new AgentSessionRole(this, 'AgentSessionRole', {
assumingRoles: [runtime.role],
taskScopedTables: [
taskTable.table,
taskEventsTable.table,
taskApprovalsTable.table,
taskNudgesTable.table,
],
traceArtifactsBucket: traceArtifactsBucket.bucket,
attachmentsBucket: attachmentsBucket.bucket,
// #215: session-tagged Bedrock grant for cost attribution — the same
// invokables grantInvoke-ed to the runtime above, so the grants stay in
// lockstep.
invokableModels: invokableBedrockModels,
});
sessionRoleArnHolder = agentSessionRole.role.roleArn;
// X-Ray tracing disabled — requires account-level UpdateTraceSegmentDestination
// which needs CloudWatch Logs resource policy propagation. Re-enable via
// tracingEnabled: true once resolved.
NagSuppressions.addResourceSuppressions(runtime, [
{
id: 'AwsSolutions-IAM5',
reason: 'AgentCore runtime requires wildcard permissions for CloudWatch Logs, Bedrock model invocation, and cross-region inference profiles — generated by CDK L2 construct grants',
},
], true);
// Chunk 10 deploy-prep: the Cedar HITL additions (TaskApprovalsTable
// grant + extra env vars) pushed the runtime
// execution role past CDK's per-inline-policy size limit, causing CDK
// to auto-split excess statements into ``OverflowPolicy1`` / etc.
// Those overflow policies inherit the same wildcard
// ``bedrock:InvokeModel*`` / CloudWatch / cross-region-inference
// actions as the base policy but live at paths that any suppression
// placed at constructor time does NOT reach (CDK creates the
// overflow policies lazily during synth ``prepare()``, after the
// construct tree has been frozen). Use an Aspect that visits every
// node during synth and matches overflow-policy children of the
// runtime ExecutionRole so any present or future overflow is
// suppressed automatically without hardcoding
// ``OverflowPolicy<N>`` indices.
const overflowSuppressionAspect = {
visit(node: IConstruct) {
const nodePath = node.node.path;
if (
nodePath.includes('/Runtime/ExecutionRole/OverflowPolicy')
&& nodePath.endsWith('/Resource')
) {
NagSuppressions.addResourceSuppressions(node, [
{
id: 'AwsSolutions-IAM5',
reason:
'CDK-generated overflow policy on the runtime ExecutionRole inherits the same wildcard Bedrock / CloudWatch actions suppressed on the base policy. Auto-split triggers when the role exceeds the inline-policy size limit; suppression applies to all overflow policies via an Aspect so future splits are covered.',
},
]);
}
},
};
// MUTATING priority: runs before cdk-nag's READONLY aspect so the
// suppression is in place when the nag checks visit the overflow
// policy. Default priority would race with cdk-nag (registered in
// ``main.ts``) and the suppression would arrive too late.
Aspects.of(this).add(overflowSuppressionAspect, { priority: AspectPriority.MUTATING });
new CfnOutput(this, 'RuntimeArn', {
value: runtime.agentRuntimeArn,
description: 'ARN of the AgentCore runtime',
});
new CfnOutput(this, 'TaskTableName', {
value: taskTable.table.tableName,
description: 'Name of the DynamoDB task state table',
});
new CfnOutput(this, 'TaskEventsTableName', {
value: taskEventsTable.table.tableName,
description: 'Name of the DynamoDB task events audit table',
});
new CfnOutput(this, 'TaskNudgesTableName', {
value: taskNudgesTable.table.tableName,
description: 'Name of the DynamoDB task nudges table (Phase 2)',
});
new CfnOutput(this, 'TaskApprovalsTableName', {
value: taskApprovalsTable.table.tableName,
description: 'Name of the DynamoDB task approvals table (Cedar HITL)',
});
new CfnOutput(this, 'CedarWasmLayerArn', {
value: cedarWasmLayer.layer.layerVersionArn,
description: 'ARN of the Cedar-wasm Lambda layer (consumed by Chunk 5 REST handlers)',
});
new CfnOutput(this, 'UserConcurrencyTableName', {
value: userConcurrencyTable.table.tableName,
description: 'Name of the DynamoDB user concurrency table',
});
new CfnOutput(this, 'WebhookTableName', {
value: webhookTable.table.tableName,
description: 'Name of the DynamoDB webhook table',
});
new CfnOutput(this, 'RepoTableName', {
value: repoTable.table.tableName,
description: 'Name of the DynamoDB repo config table',
});
new CfnOutput(this, 'GitHubTokenSecretArn', {
value: githubTokenSecret.secretArn,
description: 'ARN of the Secrets Manager secret for the GitHub token',
});
new CfnOutput(this, 'TraceArtifactsBucketName', {
value: traceArtifactsBucket.bucket.bucketName,
description: 'Name of the S3 bucket storing --trace trajectory artifacts (design §10.1)',
});
// --- ECS Fargate compute backend (optional) ---
// To enable ECS as an alternative compute backend, uncomment the block below
// and the EcsAgentCluster import at the top of this file. Repos can then use
// compute_type: 'ecs' in their blueprint config to route tasks to ECS Fargate.
//
// const agentImageAsset = new ecr_assets.DockerImageAsset(this, 'AgentImage', {
// directory: repoRoot,
// file: 'agent/Dockerfile',
// platform: ecr_assets.Platform.LINUX_ARM64,
// });
//
// const ecsCluster = new EcsAgentCluster(this, 'EcsAgentCluster', {
// vpc: agentVpc.vpc,
// agentImageAsset,
// taskTable: taskTable.table,
// taskEventsTable: taskEventsTable.table,
// userConcurrencyTable: userConcurrencyTable.table,
// githubTokenSecret,
// memoryId: agentMemory.memory.memoryId,
// // Per-session IAM scoping (#209): the ECS task role assumes the same
// // SessionRole as the AgentCore runtime for tenant-data access. The
// // construct admits the task role to the trust and injects
// // AGENT_SESSION_ROLE_ARN into the container.
// agentSessionRole,
// });
// --- Task Orchestrator (durable Lambda function) ---
const orchestrator = new TaskOrchestrator(this, 'TaskOrchestrator', {
taskTable: taskTable.table,
taskEventsTable: taskEventsTable.table,
userConcurrencyTable: userConcurrencyTable.table,
repoTable: repoTable.table,
runtimeArn: runtime.agentRuntimeArn,
githubTokenSecretArn: githubTokenSecret.secretArn,
memoryId: agentMemory.memory.memoryId,
guardrailId: inputGuardrail.guardrailId,
guardrailVersion: inputGuardrail.guardrailVersion,
attachmentsBucket: attachmentsBucket.bucket,
// To wire ECS, uncomment the ecsCluster block above and add:
// ecsConfig: {
// clusterArn: ecsCluster.cluster.clusterArn,
// taskDefinitionArn: ecsCluster.taskDefinition.taskDefinitionArn,
// subnets: agentVpc.vpc.selectSubnets({ subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS }).subnetIds.join(','),
// securityGroup: ecsCluster.securityGroup.securityGroupId,
// containerName: ecsCluster.containerName,
// taskRoleArn: ecsCluster.taskRoleArn,
// executionRoleArn: ecsCluster.executionRoleArn,
// },
});
// Now that the orchestrator exists, resolve the Lazy used by TaskApi at synth.
orchestratorArnHolder = orchestrator.alias.functionArn;
// Grant the orchestrator Lambda read+write access to memory
// (reads during context hydration, writes for fallback episodes)
agentMemory.grantReadWrite(orchestrator.fn);
// --- Concurrency counter reconciler (drift correction) ---
new ConcurrencyReconciler(this, 'ConcurrencyReconciler', {
taskTable: taskTable.table,
userConcurrencyTable: userConcurrencyTable.table,
});
// --- Stranded-task reconciler ---
// Catches SUBMITTED / HYDRATING tasks whose pipeline never started
// (orchestrator Lambda crash between TaskTable write and InvokeAgentRuntime,
// container crash during startup, etc.). Transitions to FAILED with a
// `task_stranded` event.
new StrandedTaskReconciler(this, 'StrandedTaskReconciler', {
taskTable: taskTable.table,
taskEventsTable: taskEventsTable.table,
userConcurrencyTable: userConcurrencyTable.table,
});
// --- Pending-upload cleanup rule ---
// Auto-cancels PENDING_UPLOADS tasks that were never confirmed within
// 30 minutes (client crash, abandoned session, network failure).
// Cleans up orphaned S3 objects under the task's attachment prefix.
new PendingUploadCleanup(this, 'PendingUploadCleanup', {
taskTable: taskTable.table,
taskEventsTable: taskEventsTable.table,
attachmentsBucket: attachmentsBucket.bucket,
});
// FanOutConsumer is constructed below LinearIntegration so the
// Linear dispatcher can receive ``linearIntegration.workspaceRegistryTable``.
// --- Cedar HITL approval metrics publisher (Chunk 8, §11.3 / IMPL-28) ---
// Consumer #2 of the TaskEventsTable stream (FanOutConsumer is #1).
// Reads agent_milestone records for approval events and emits
// CloudWatch EMF for the dashboard widgets below. See the
// 2-consumer architectural note in `task-events-table.ts` —
// adding a third consumer here requires the Kinesis Data Streams
// for DynamoDB migration.
new ApprovalMetricsPublisherConsumer(this, 'ApprovalMetricsPublisherConsumer', {
taskEventsTable: taskEventsTable.table,
});
// --- Operator dashboard ---
new TaskDashboard(this, 'TaskDashboard', {
applicationLogGroup,
runtimeArn: runtime.agentRuntimeArn,
});
// --- Slack integration (always deployed — secrets populated post-deploy) ---
const slackIntegration = new SlackIntegration(this, 'SlackIntegration', {
api: taskApi.api,
userPool: taskApi.userPool,
taskTable: taskTable.table,
taskEventsTable: taskEventsTable.table,
repoTable: repoTable.table,
orchestratorFunctionArn: orchestrator.alias.functionArn,
guardrailId: inputGuardrail.guardrailId,
guardrailVersion: inputGuardrail.guardrailVersion,
});
// --- Slack App setup outputs ---
// Pre-filled manifest URL: opens Slack's "Create New App" page with all
// URLs, scopes, and events pre-configured. User just clicks Create.
const apiHost = Fn.select(2, Fn.split('/', taskApi.api.url));
const apiStage = Fn.select(API_URL_STAGE_SEGMENT_INDEX, Fn.split('/', taskApi.api.url));
const apiBase = Fn.join('', ['https://', apiHost, '/', apiStage]);
// Build the YAML manifest as a string using Fn.join (API URL tokens resolve at deploy time).
// Slack's ?new_app=1&manifest_json= endpoint accepts URL-encoded JSON.
const manifestJson = Fn.join('', [
'{"_metadata":{"major_version":1,"minor_version":1},',
'"display_information":{"name":"Shoof","description":"Submit coding tasks to autonomous background agents","background_color":"#1a1a2e"},',
'"features":{"app_home":{"messages_tab_enabled":true,"messages_tab_read_only_enabled":false},"bot_user":{"display_name":"Shoof","always_online":true},',
'"slash_commands":[{"command":"/bgagent","url":"', apiBase, '/slack/commands","description":"Link your account or get help with Shoof","usage_hint":"link | help","should_escape":false}]},',
'"oauth_config":{"scopes":{"bot":["app_mentions:read","commands","chat:write","chat:write.public","channels:read","groups:read","im:history","im:write","users:read","reactions:write"]},',
'"redirect_urls":["', apiBase, '/slack/oauth/callback"]},',
'"settings":{"event_subscriptions":{"request_url":"', apiBase, '/slack/events","bot_events":["app_mention","message.im","app_uninstalled","tokens_revoked"]},',
'"interactivity":{"is_enabled":true,"request_url":"', apiBase, '/slack/interactions"},',
'"org_deploy_enabled":false,"socket_mode_enabled":false,"token_rotation_enabled":false}}',
]);
new CfnOutput(this, 'SlackAppManifestJson', {
value: manifestJson,
description: 'Slack App manifest JSON — the CLI URL-encodes this into the create URL',
});
new CfnOutput(this, 'SlackSigningSecretArn', {
value: slackIntegration.signingSecret.secretArn,
description: 'Secrets Manager ARN for the Slack signing secret — populate after creating the Slack App',
});
new CfnOutput(this, 'SlackClientSecretArn', {
value: slackIntegration.clientSecret.secretArn,
description: 'Secrets Manager ARN for the Slack client secret — populate after creating the Slack App',
});
new CfnOutput(this, 'SlackClientIdSecretArn', {
value: slackIntegration.clientIdSecret.secretArn,
description: 'Secrets Manager ARN for the Slack client ID — populate after creating the Slack App',
});
new CfnOutput(this, 'SlackInstallationTableName', {
value: slackIntegration.installationTable.tableName,
description: 'Name of the DynamoDB Slack installation table',
});
new CfnOutput(this, 'SlackUserMappingTableName', {
value: slackIntegration.userMappingTable.tableName,
description: 'Name of the DynamoDB Slack user mapping table',
});
// --- Linear integration (inbound webhook + agent-side MCP outbound) ---
const linearIntegration = new LinearIntegration(this, 'LinearIntegration', {
api: taskApi.api,
userPool: taskApi.userPool,
taskTable: taskTable.table,
taskEventsTable: taskEventsTable.table,
repoTable: repoTable.table,
orchestratorFunctionArn: orchestrator.alias.functionArn,
guardrailId: inputGuardrail.guardrailId,
guardrailVersion: inputGuardrail.guardrailVersion,
});
// Phase 2.0b-O2: agent runtime reads the per-workspace Linear OAuth
// token directly from Secrets Manager. The CLI (`bgagent linear setup`)
// creates `bgagent-linear-oauth-<slug>` secrets at install time;
// the secret JSON contains access_token, refresh_token, expires_at,
// and the OAuth client_id/client_secret. The orchestrator passes
// `linear_oauth_secret_arn` to the agent via task.channel_metadata,
// so the agent looks up the exact ARN — no discovery needed.
//
// Agent has GetSecretValue ONLY — no Put. Review item S1: agent
// runtime executes untrusted repo code, so write access to all
// workspace tokens is too broad a blast radius (a compromised
// agent could overwrite any workspace's token). Lambdas (trusted
// code in this stack) handle the in-place refresh path; the agent
// proceeds with whatever token Lambdas have most-recently written.
// For a 24h Linear access-token TTL, the practical impact is that
// a stale token in the cache forces the agent's next call to fail
// closed — preferable to a trust gap.
runtime.role.addToPrincipalPolicy(new iam.PolicyStatement({
actions: ['secretsmanager:GetSecretValue'],
resources: [
Stack.of(this).formatArn({
service: 'secretsmanager',
resource: 'secret',
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
resourceName: 'bgagent-linear-oauth-*',
}),
],
}));
// Phase 2.0b-O2: pipe the workspace registry table + per-workspace
// OAuth-secret-prefix grant into the orchestrator so the concurrency-cap
// rejection path can post a Linear comment + ❌. The orchestrator only
// resolves a token when `task.channel_source === 'linear'`, but the
// IAM grant is unconditional (per-workspace secrets are created lazily
// by `bgagent linear setup`).
linearIntegration.workspaceRegistryTable.grantReadData(orchestrator.fn);
orchestrator.fn.addEnvironment(
'LINEAR_WORKSPACE_REGISTRY_TABLE_NAME',
linearIntegration.workspaceRegistryTable.tableName,
);
orchestrator.fn.addToRolePolicy(new iam.PolicyStatement({
actions: ['secretsmanager:GetSecretValue', 'secretsmanager:PutSecretValue'],
resources: [
Stack.of(this).formatArn({
service: 'secretsmanager',
resource: 'secret',
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
resourceName: 'bgagent-linear-oauth-*',
}),
],
}));
new CfnOutput(this, 'LinearWebhookSecretArn', {
value: linearIntegration.webhookSecret.secretArn,
description: 'Secrets Manager ARN for the Linear webhook signing secret — populate via `bgagent linear setup`',
});
new CfnOutput(this, 'LinearProjectMappingTableName', {
value: linearIntegration.projectMappingTable.tableName,
description: 'Name of the DynamoDB Linear project → repo mapping table',
});
new CfnOutput(this, 'LinearUserMappingTableName', {
value: linearIntegration.userMappingTable.tableName,
description: 'Name of the DynamoDB Linear user mapping table',
});
new CfnOutput(this, 'LinearWorkspaceRegistryTableName', {
value: linearIntegration.workspaceRegistryTable.tableName,
description: 'Name of the DynamoDB Linear workspace registry — `bgagent linear setup` writes a row per OAuth-installed workspace',
});
// --- Jira Cloud integration (inbound webhook + agent-side REST outbound) ---
const jiraIntegration = new JiraIntegration(this, 'JiraIntegration', {
api: taskApi.api,
userPool: taskApi.userPool,
taskTable: taskTable.table,
taskEventsTable: taskEventsTable.table,
repoTable: repoTable.table,
orchestratorFunctionArn: orchestrator.alias.functionArn,
guardrailId: inputGuardrail.guardrailId,
guardrailVersion: inputGuardrail.guardrailVersion,
});
// Agent runtime reads the per-tenant Jira OAuth token directly from
// Secrets Manager. The CLI (`bgagent jira setup`) creates
// `bgagent-jira-oauth-<cloudId>` secrets at install time; the secret
// JSON contains access_token, refresh_token, expires_at, and the
// OAuth client_id/client_secret. The orchestrator passes
// `jira_oauth_secret_arn` to the agent via task.channel_metadata,
// so the agent looks up the exact ARN — no discovery needed.
//
// Agent has GetSecretValue ONLY — no Put. Same trust model as the
// Linear adapter: a compromised agent must not be able to overwrite
// any tenant's OAuth bundle. Lambdas (trusted code in this stack)
// own the in-place refresh path; the agent proceeds with whatever
// token Lambdas have most-recently written.
runtime.role.addToPrincipalPolicy(new iam.PolicyStatement({
actions: ['secretsmanager:GetSecretValue'],
resources: [
Stack.of(this).formatArn({
service: 'secretsmanager',
resource: 'secret',
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
resourceName: 'bgagent-jira-oauth-*',
}),
],
}));
// Pipe the workspace registry table + per-tenant OAuth-secret-prefix
// grant into the orchestrator so the concurrency-cap rejection path
// (`notifyJiraOnConcurrencyCap` in orchestrate-task.ts) can post a Jira
// comment. The orchestrator only resolves a token when
// `task.channel_source === 'jira'`, but the IAM grant is unconditional
// (per-tenant secrets are created lazily by setup). Put is needed because
// resolving an expiring token refreshes it in place (the orchestrator is
// a trusted Lambda; unlike the agent it owns the rotated-token write-back).
jiraIntegration.workspaceRegistryTable.grantReadData(orchestrator.fn);
orchestrator.fn.addEnvironment(
'JIRA_WORKSPACE_REGISTRY_TABLE_NAME',
jiraIntegration.workspaceRegistryTable.tableName,
);
orchestrator.fn.addToRolePolicy(new iam.PolicyStatement({
actions: ['secretsmanager:GetSecretValue', 'secretsmanager:PutSecretValue'],
resources: [
Stack.of(this).formatArn({
service: 'secretsmanager',
resource: 'secret',
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
resourceName: 'bgagent-jira-oauth-*',
}),
],
}));
new CfnOutput(this, 'JiraWebhookSecretArn', {
value: jiraIntegration.webhookSecret.secretArn,
description: 'Secrets Manager ARN for the Jira webhook signing secret — populate via `bgagent jira setup`',
});
new CfnOutput(this, 'JiraProjectMappingTableName', {
value: jiraIntegration.projectMappingTable.tableName,
description: 'Name of the DynamoDB Jira project → repo mapping table',
});
new CfnOutput(this, 'JiraUserMappingTableName', {
value: jiraIntegration.userMappingTable.tableName,
description: 'Name of the DynamoDB Jira user mapping table',
});
new CfnOutput(this, 'JiraWorkspaceRegistryTableName', {
value: jiraIntegration.workspaceRegistryTable.tableName,
description: 'Name of the DynamoDB Jira workspace registry — `bgagent jira setup` writes a row per OAuth-installed tenant',
});
// --- Fan-out plane consumer ---
// Consumes TaskEventsTable DynamoDB Streams and dispatches events to
// Slack / GitHub / Linear / email per per-channel default filters.
// GitHub dispatcher edits a single issue comment in place; Slack
// dispatcher (issue #64) reads per-workspace bot tokens from
// ``bgagent/slack/*``; Linear dispatcher (issue #239) posts a single
// deterministic final-status comment with cost/turns/duration.
// Email remains a log-only stub until SES wires.
new FanOutConsumer(this, 'FanOutConsumer', {
taskEventsTable: taskEventsTable.table,
taskTable: taskTable.table,
repoTable: repoTable.table,
githubTokenSecret,
// Slack bot-token grant is guarded on this prop — pass the
// ``bgagent/slack/*`` prefix so the FanOutConsumer can read
// workspace tokens. Same scope SlackIntegration uses for its
// own writers (PR #79 review #2).
slackSecretArnPattern: Stack.of(this).formatArn({
service: 'secretsmanager',
resource: 'secret',
resourceName: 'bgagent/slack/*',
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
}),
// Linear dispatcher reads workspace registry rows + per-workspace
// OAuth-secret JSON. Same scope `bgagent-linear-oauth-*` as the
// orchestrator and webhook processor — Lambdas in this stack share
// the rotated-token write path; the agent runtime gets read-only.
linearWorkspaceRegistryTable: linearIntegration.workspaceRegistryTable,
linearOauthSecretArnPattern: Stack.of(this).formatArn({
service: 'secretsmanager',
resource: 'secret',
resourceName: 'bgagent-linear-oauth-*',
arnFormat: ArnFormat.COLON_RESOURCE_NAME,
}),
});
// --- GitHub deployment-status → screenshot pipeline ---
// Listens for GitHub deployment_status events from any provider
// (Vercel, Amplify Hosting, Netlify, GitHub Actions custom CD),
// screenshots the `deployment.environment_url` via AgentCore
// Browser, posts the image into a fresh PR comment. Default-on:
// any repo whose GitHub webhook is configured will get
// screenshotted on successful preview deploys; no opt-in flag.
const githubScreenshot = new GitHubScreenshotIntegration(this, 'GitHubScreenshotIntegration', {
api: taskApi.api,
githubTokenSecret,
// When the screenshot lands on a PR linked to a Linear issue
// (identifier in the PR title/body), also post the screenshot
// as a comment on that Linear issue. Wired through the existing
// workspace registry so token resolution reuses the per-workspace
// OAuth secrets created by `bgagent linear setup`.
linearWorkspaceRegistryTable: linearIntegration.workspaceRegistryTable,
});
new CfnOutput(this, 'GitHubWebhookUrl', {
value: `${taskApi.api.url}github/webhook`,
description: 'URL to configure as the GitHub webhook target on demo repos (deployment_status events)',
});
new CfnOutput(this, 'GitHubWebhookSecretArn', {
value: githubScreenshot.webhookSecret.secretArn,
description: 'Secrets Manager ARN for the GitHub webhook signing secret — paste GitHub\'s value here after configuring the webhook',
});
new CfnOutput(this, 'ScreenshotBucketName', {
value: githubScreenshot.screenshotBucket.bucket.bucketName,
description: 'Private S3 bucket hosting preview-deploy screenshots (served via CloudFront)',
});
new CfnOutput(this, 'ScreenshotCloudFrontDomain', {
value: githubScreenshot.screenshotBucket.distribution.domainName,
description: 'CloudFront domain that serves the screenshot bucket anonymously to GitHub PR / Linear renders',
});