-
Notifications
You must be signed in to change notification settings - Fork 481
Expand file tree
/
Copy pathunified_prompt_step.go
More file actions
813 lines (737 loc) · 33.6 KB
/
Copy pathunified_prompt_step.go
File metadata and controls
813 lines (737 loc) · 33.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
package workflow
import (
"fmt"
"strings"
"github.com/github/gh-aw/pkg/constants"
"github.com/github/gh-aw/pkg/logger"
"github.com/github/gh-aw/pkg/sliceutil"
"github.com/github/gh-aw/pkg/stringutil"
)
var unifiedPromptLog = logger.New("workflow:unified_prompt_step")
// PromptSection represents a section of prompt text to be appended
type PromptSection struct {
// Content is the actual prompt text or a reference to a file
Content string
// IsFile indicates if Content is a filename (true) or inline text (false)
IsFile bool
// ShellCondition is an optional bash condition (without 'if' keyword) to wrap this section
// Example: "${{ github.event_name == 'issue_comment' }}" becomes a shell condition
ShellCondition string
// EnvVars contains environment variables needed for expressions in this section
EnvVars map[string]string
}
// removeConsecutiveEmptyLines removes consecutive empty lines, keeping only one
func removeConsecutiveEmptyLines(content string) string {
lines := strings.Split(content, "\n")
if len(lines) == 0 {
return content
}
var result []string
lastWasEmpty := false
for _, line := range lines {
isEmpty := strings.TrimSpace(line) == ""
if isEmpty {
// Only add if the last line wasn't empty
if !lastWasEmpty {
result = append(result, line)
lastWasEmpty = true
}
// Skip consecutive empty lines
} else {
result = append(result, line)
lastWasEmpty = false
}
}
return strings.Join(result, "\n")
}
// collectPromptSections collects all prompt sections in the order they should be appended
func (c *Compiler) collectPromptSections(data *WorkflowData) []PromptSection {
var sections []PromptSection
// 0. XPia instructions (unless disabled by feature flag)
if !isFeatureEnabled(constants.DisableXPIAPromptFeatureFlag, data) {
unifiedPromptLog.Print("Adding XPIA section")
sections = append(sections, PromptSection{
Content: xpiaPromptFile,
IsFile: true,
})
} else {
unifiedPromptLog.Print("XPIA section disabled by feature flag")
}
// 1. Temporary folder instructions (always included)
unifiedPromptLog.Print("Adding temp folder section")
sections = append(sections, PromptSection{
Content: tempFolderPromptFile,
IsFile: true,
})
// 2. Markdown generation instructions (always included)
unifiedPromptLog.Print("Adding markdown section")
sections = append(sections, PromptSection{
Content: markdownPromptFile,
IsFile: true,
})
// 3. Playwright instructions (if playwright tool is enabled)
if hasPlaywrightTool(data.ParsedTools) {
unifiedPromptLog.Print("Adding playwright section")
sections = append(sections, PromptSection{
Content: playwrightPromptFile,
IsFile: true,
})
}
// 4. Trial mode note (if in trial mode)
if c.trialMode {
unifiedPromptLog.Print("Adding trial mode section")
trialContent := fmt.Sprintf("## Note\nThis workflow is running in directory $GITHUB_WORKSPACE, but that directory actually contains the contents of the repository '%s'.", c.trialLogicalRepoSlug)
sections = append(sections, PromptSection{
Content: trialContent,
IsFile: false,
})
}
// 6. Cache memory instructions (if enabled)
if data.CacheMemoryConfig != nil && len(data.CacheMemoryConfig.Caches) > 0 {
unifiedPromptLog.Printf("Adding cache memory section: caches=%d", len(data.CacheMemoryConfig.Caches))
section := buildCacheMemoryPromptSection(data.CacheMemoryConfig)
if section != nil {
sections = append(sections, *section)
}
}
// 7. Repo memory instructions (if enabled)
if data.RepoMemoryConfig != nil && len(data.RepoMemoryConfig.Memories) > 0 {
unifiedPromptLog.Printf("Adding repo memory section: memories=%d", len(data.RepoMemoryConfig.Memories))
section := buildRepoMemoryPromptSection(data.RepoMemoryConfig)
if section != nil {
sections = append(sections, *section)
}
}
// 8. Safe outputs instructions (if enabled)
if HasSafeOutputsEnabled(data.SafeOutputs) {
unifiedPromptLog.Print("Adding safe outputs section")
// Static intro from file (gh CLI warning, temporary ID rules, noop note)
sections = append(sections, PromptSection{
Content: safeOutputsPromptFile,
IsFile: true,
})
// Per-tool sections: opening tag + tools list (inline), tool instruction files, closing tag
sections = append(sections, buildSafeOutputsSections(data.SafeOutputs)...)
}
// 8a. MCP CLI tools instructions (if any MCP servers are mounted as CLIs)
if section := buildMCPCLIPromptSection(data); section != nil {
unifiedPromptLog.Printf("Adding MCP CLI tools section: servers=%v", getMCPCLIServerNames(data))
sections = append(sections, *section)
}
// 9. GitHub context (if GitHub tool is enabled)
if hasGitHubTool(data.ParsedTools) {
unifiedPromptLog.Print("Adding GitHub context section")
// Build the combined prompt text: base github context + optional checkout list.
// The checkout list may contain ${{ github.repository }} which must go through
// the expression extractor so the placeholder substitution step can resolve it.
combinedPromptText := githubContextPromptText
// In trial mode with a logical target repository, the workflow runs on the host
// repo (github.repository) but checkout and safe outputs are redirected to the
// logical target. Rewrite the reported repository so the agent's notion of "the
// repository" matches the logical target, and add a directive so GitHub MCP calls
// that omit owner/repo don't silently operate against the host repo.
if data.TrialMode && data.TrialLogicalRepo != "" {
combinedPromptText = applyTrialLogicalRepoToGitHubContext(combinedPromptText, data.TrialLogicalRepo)
}
if checkoutsContent := buildCheckoutsPromptContent(data.CheckoutConfigs); checkoutsContent != "" {
unifiedPromptLog.Printf("Injecting checkout list into GitHub context (%d checkouts)", len(data.CheckoutConfigs))
const closeTag = "</github-context>"
if idx := strings.LastIndex(combinedPromptText, closeTag); idx >= 0 {
combinedPromptText = combinedPromptText[:idx] + checkoutsContent + combinedPromptText[idx:]
} else {
combinedPromptText += "\n" + checkoutsContent
}
}
// Extract expressions from the combined content (includes any new expressions
// introduced by the checkout list, e.g. ${{ github.repository }}).
extractor := NewExpressionExtractor()
expressionMappings, err := extractor.ExtractExpressions(combinedPromptText)
if err == nil && len(expressionMappings) > 0 {
modifiedPromptText := extractor.ReplaceExpressionsWithEnvVars(combinedPromptText)
// Build environment variables map
envVars := make(map[string]string)
for _, mapping := range expressionMappings {
envVars[mapping.EnvVar] = fmt.Sprintf("${{ %s }}", mapping.Content)
}
sections = append(sections, PromptSection{
Content: modifiedPromptText,
IsFile: false,
EnvVars: envVars,
})
}
}
// 10. GitHub tool-use guidance: directs the model to the correct mechanism for
// GitHub reads (and writes when safe-outputs is also enabled).
// When GitHub mode is gh-proxy, the agent uses the pre-authenticated gh CLI for reads
// instead of a GitHub MCP server (which is not registered). Otherwise, the GitHub
// MCP server is used for reads.
if isGitHubCLIModeEnabled(data) {
unifiedPromptLog.Print("Adding cli-proxy tool-use guidance (gh CLI for reads, no GitHub MCP server)")
cliProxyFile := cliProxyPromptFile
if HasSafeOutputsEnabled(data.SafeOutputs) {
cliProxyFile = cliProxyWithSafeOutputsPromptFile
}
sections = append(sections, PromptSection{
Content: cliProxyFile,
IsFile: true,
})
} else if hasGitHubTool(data.ParsedTools) {
// GitHub MCP tool-use guidance: clarifies that the MCP server is read-only and
// directs the model to use it for GitHub reads. When safe-outputs is also enabled,
// the guidance explicitly separates reads (GitHub MCP) from writes (safeoutputs) so
// the model is never steered away from the available read tools.
unifiedPromptLog.Print("Adding GitHub MCP tool-use guidance")
githubMCPFile := githubMCPToolsPromptFile
if HasSafeOutputsEnabled(data.SafeOutputs) {
githubMCPFile = githubMCPToolsWithSafeOutputsPromptFile
}
sections = append(sections, PromptSection{
Content: githubMCPFile,
IsFile: true,
})
}
// 11. PR context (if comment-related triggers and checkout is needed)
hasCommentTriggers := c.hasCommentRelatedTriggers(data)
needsCheckout := c.shouldAddCheckoutStep(data)
var hasContentsRead bool
if data.CachedPermissions != nil {
hasContentsRead = data.CachedPermissions.HasContentsReadAccess()
} else {
hasContentsRead = NewPermissionsParser(data.Permissions).HasContentsReadAccess()
}
if hasCommentTriggers && needsCheckout && hasContentsRead {
unifiedPromptLog.Print("Adding PR context section with condition")
// Use shell condition for PR comment detection
// This checks for issue_comment, pull_request_review_comment, or pull_request_review events
// For issue_comment, we also need to check if it's on a PR (github.event.issue.pull_request != null)
// However, for simplicity in the unified step, we'll add an environment variable to check this
shellCondition := `[ "$GITHUB_EVENT_NAME" = "issue_comment" ] && [ -n "$GH_AW_IS_PR_COMMENT" ] || [ "$GITHUB_EVENT_NAME" = "pull_request_review_comment" ] || [ "$GITHUB_EVENT_NAME" = "pull_request_review" ]`
// Add environment variable to check if issue_comment is on a PR
envVars := map[string]string{
"GH_AW_IS_PR_COMMENT": "${{ github.event.issue.pull_request && 'true' || '' }}",
}
sections = append(sections, PromptSection{
Content: prContextPromptFile,
IsFile: true,
ShellCondition: shellCondition,
EnvVars: envVars,
})
// When push_to_pull_request_branch is configured, add guidance to prefer it over
// create_pull_request when the workflow was triggered by a PR comment.
if data.SafeOutputs != nil && data.SafeOutputs.PushToPullRequestBranch != nil {
unifiedPromptLog.Print("Adding push-to-PR-branch tool preference guidance for PR comment context")
sections = append(sections, PromptSection{
Content: prContextPushToPRBranchGuidanceFile,
IsFile: true,
ShellCondition: shellCondition,
EnvVars: envVars,
})
}
}
return sections
}
// generateUnifiedPromptCreationStep generates a single workflow step (or multiple if needed) that creates
// the complete prompt file with built-in context instructions prepended to the user prompt content.
//
// This consolidates the prompt creation process:
// 1. Built-in context instructions (temp folder, playwright, safe outputs, etc.) - PREPENDED
// 2. User prompt content from markdown - APPENDED
//
// The function handles chunking for large content and ensures proper environment variable handling.
// Returns the combined expression mappings for use in the placeholder substitution step.
func (c *Compiler) generateUnifiedPromptCreationStep(yaml *strings.Builder, builtinSections []PromptSection, userPromptChunks []string, expressionMappings []*ExpressionMapping, data *WorkflowData) []*ExpressionMapping {
unifiedPromptLog.Print("Generating unified prompt creation step")
unifiedPromptLog.Printf("Built-in sections: %d, User prompt chunks: %d", len(builtinSections), len(userPromptChunks))
// Derive the heredoc delimiter from the combined prompt content so it is identical
// across builds for the same workflow and changes only when the prompt text changes.
var promptContentForHash strings.Builder
for _, section := range builtinSections {
promptContentForHash.WriteString(section.Content)
}
for _, chunk := range userPromptChunks {
promptContentForHash.WriteString(chunk)
}
delimiter := GenerateHeredocDelimiterFromContent("PROMPT", promptContentForHash.String())
// Collect all environment variables from built-in sections and user prompt expressions
allEnvVars := make(map[string]string)
// Also collect all expression mappings for the substitution step (using a map to avoid duplicates)
expressionMappingsMap := make(map[string]*ExpressionMapping)
// Add environment variables and expression mappings from built-in sections
for _, section := range builtinSections {
for key, value := range section.EnvVars {
// Extract the GitHub expression from the value (e.g., "${{ github.repository }}" -> "github.repository")
// This is needed for the substitution step
if strings.HasPrefix(value, "${{ ") && strings.HasSuffix(value, " }}") {
content := strings.TrimSpace(value[4 : len(value)-3])
// Add to both allEnvVars (for prompt creation step) and expressionMappingsMap (for substitution step)
allEnvVars[key] = value
// Only add if not already present (user prompt expressions take precedence)
if _, exists := expressionMappingsMap[key]; !exists {
expressionMappingsMap[key] = &ExpressionMapping{
EnvVar: key,
Content: content,
}
}
} else {
// For static values (not GitHub Actions expressions), only add to expressionMappingsMap
// This ensures they're only available in the substitution step, not the prompt creation step
if _, exists := expressionMappingsMap[key]; !exists {
expressionMappingsMap[key] = &ExpressionMapping{
EnvVar: key,
Content: fmt.Sprintf("'%s'", value), // Wrap in quotes for substitution
}
}
}
}
}
// Add environment variables from user prompt expressions (these override built-in ones)
for _, mapping := range expressionMappings {
allEnvVars[mapping.EnvVar] = fmt.Sprintf("${{ %s }}", mapping.Content)
expressionMappingsMap[mapping.EnvVar] = mapping
}
// Convert map back to slice for the substitution step
allExpressionMappings := make([]*ExpressionMapping, 0, len(expressionMappingsMap))
// Sort the keys to ensure stable output
sortedKeys := sliceutil.SortedKeys(expressionMappingsMap)
// Add mappings in sorted order
for _, key := range sortedKeys {
allExpressionMappings = append(allExpressionMappings, expressionMappingsMap[key])
}
// Generate the step with all environment variables
yaml.WriteString(" - name: Create prompt with built-in context\n")
yaml.WriteString(" env:\n")
yaml.WriteString(" GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt\n")
if data.SafeOutputs != nil {
yaml.WriteString(" GH_AW_SAFE_OUTPUTS: ${{ runner.temp }}/gh-aw/safeoutputs/outputs.jsonl\n")
}
// Add all environment variables in sorted order for consistency
envKeys := sliceutil.SortedKeys(allEnvVars)
for _, key := range envKeys {
fmt.Fprintf(yaml, " %s: %s\n", key, allEnvVars[key])
}
yaml.WriteString(" # poutine:ignore untrusted_checkout_exec\n")
yaml.WriteString(" run: |\n")
yaml.WriteString(" bash \"${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh\"\n")
yaml.WriteString(" {\n")
// Track if we're inside a heredoc
inHeredoc := false
// 1. Write built-in sections first (prepended), wrapped in <system> tags.
// The <system> opening tag is deferred: it is written either as the first line
// of the first inline section's heredoc, or in its own block just before the
// first file or conditional section. This allows the opening tag to share a
// heredoc block with adjacent inline content, reducing the total number of blocks.
systemTagPending := len(builtinSections) > 0
for i, section := range builtinSections {
unifiedPromptLog.Printf("Writing built-in section %d/%d: hasCondition=%v, isFile=%v",
i+1, len(builtinSections), section.ShellCondition != "", section.IsFile)
if section.ShellCondition != "" {
// Close heredoc if open, add conditional
if inHeredoc {
yaml.WriteString(" " + delimiter + "\n")
inHeredoc = false
}
// Write <system> before conditional if still pending
if systemTagPending {
yaml.WriteString(" cat << '" + delimiter + "'\n")
yaml.WriteString(" <system>\n")
yaml.WriteString(" " + delimiter + "\n")
systemTagPending = false
}
fmt.Fprintf(yaml, " if %s; then\n", section.ShellCondition)
if section.IsFile {
// File reference inside conditional
promptPath := fmt.Sprintf("%s/%s", promptsDir, section.Content)
yaml.WriteString(" " + fmt.Sprintf("cat \"%s\"\n", promptPath))
} else {
// Inline content inside conditional - open heredoc, write content, close
yaml.WriteString(" cat << '" + delimiter + "'\n")
normalizedContent := stringutil.NormalizeLeadingWhitespace(section.Content)
cleanedContent := removeConsecutiveEmptyLines(normalizedContent)
contentLines := strings.SplitSeq(cleanedContent, "\n")
for line := range contentLines {
yaml.WriteString(" " + line + "\n")
}
yaml.WriteString(" " + delimiter + "\n")
}
yaml.WriteString(" fi\n")
} else {
// Unconditional section
if section.IsFile {
// Close heredoc if open
if inHeredoc {
yaml.WriteString(" " + delimiter + "\n")
inHeredoc = false
}
// Write <system> before file if still pending
if systemTagPending {
yaml.WriteString(" cat << '" + delimiter + "'\n")
yaml.WriteString(" <system>\n")
yaml.WriteString(" " + delimiter + "\n")
systemTagPending = false
}
// Cat the file
promptPath := fmt.Sprintf("%s/%s", promptsDir, section.Content)
yaml.WriteString(" " + fmt.Sprintf("cat \"%s\"\n", promptPath))
} else {
// Inline content - open heredoc if not already open
if !inHeredoc {
yaml.WriteString(" cat << '" + delimiter + "'\n")
inHeredoc = true
// Write <system> as first line when opening the heredoc
if systemTagPending {
yaml.WriteString(" <system>\n")
systemTagPending = false
}
}
// Write content directly to open heredoc
normalizedContent := stringutil.NormalizeLeadingWhitespace(section.Content)
cleanedContent := removeConsecutiveEmptyLines(normalizedContent)
contentLines := strings.SplitSeq(cleanedContent, "\n")
for line := range contentLines {
yaml.WriteString(" " + line + "\n")
}
}
}
}
// Close </system> tag after all built-in sections.
// Merge with the open heredoc (if any) to minimise the total number of cat/heredoc
// blocks, which reduces the number of lines that change in the diff when the user
// prompt changes (each block boundary contributes two delimiter lines).
if len(builtinSections) > 0 {
if inHeredoc {
// Append </system> to the still-open heredoc and keep it open for
// the user content that follows.
yaml.WriteString(" </system>\n")
} else {
// No heredoc is open: start a new one for </system> and keep it
// open so the subsequent user content lands in the same block.
yaml.WriteString(" cat << '" + delimiter + "'\n")
yaml.WriteString(" </system>\n")
inHeredoc = true
}
}
// 2. Write user prompt chunks (appended after built-in sections).
// All chunks are written into the same heredoc block (opened above or here)
// to minimise the number of delimiter lines in the compiled lock file.
//
// The heredoc payload is a YAML block scalar, so normalizeBlankLines preserves
// it verbatim (it must, since arbitrary block scalars can carry semantically
// significant trailing whitespace and blank runs). Prompt content is markdown
// text the compiler owns, where trailing whitespace is never meaningful and
// long blank runs are noise, so it is cleaned here instead: trailing whitespace
// is trimmed from every line and consecutive blank lines are capped at
// maxConsecutiveBlankLines. userBlankRun is tracked across chunks so a run that
// straddles a chunk boundary is still collapsed.
userBlankRun := 0
for chunkIdx, chunk := range userPromptChunks {
unifiedPromptLog.Printf("Writing user prompt chunk %d/%d", chunkIdx+1, len(userPromptChunks))
// Check if this chunk is a runtime-import macro
if strings.HasPrefix(chunk, "{{#runtime-import ") && strings.HasSuffix(chunk, "}}") {
// Runtime-import macros are plain text lines processed by the
// interpolate-prompt step; they can live in the same heredoc block
// as surrounding content.
unifiedPromptLog.Print("Detected runtime-import macro, writing inline in heredoc")
if !inHeredoc {
yaml.WriteString(" cat << '" + delimiter + "'\n")
inHeredoc = true
}
yaml.WriteString(" " + chunk + "\n")
userBlankRun = 0
continue
}
// Regular chunk: write to the current heredoc (or open one).
if !inHeredoc {
yaml.WriteString(" cat << '" + delimiter + "'\n")
inHeredoc = true
}
lines := strings.SplitSeq(chunk, "\n")
for line := range lines {
trimmed := strings.TrimRight(line, " \t")
if trimmed == "" {
// Collapse over-long blank runs; emit truly empty lines (no
// indentation) so they carry no trailing whitespace.
if userBlankRun >= maxConsecutiveBlankLines {
continue
}
userBlankRun++
yaml.WriteByte('\n')
continue
}
userBlankRun = 0
yaml.WriteString(" ")
yaml.WriteString(trimmed)
yaml.WriteByte('\n')
}
}
// Close heredoc if still open
if inHeredoc {
yaml.WriteString(" " + delimiter + "\n")
}
yaml.WriteString(" } > \"$GH_AW_PROMPT\"\n")
unifiedPromptLog.Print("Unified prompt creation step generated successfully")
// Return all expression mappings for use in the placeholder substitution step
// This allows the substitution to happen AFTER runtime-import processing
return allExpressionMappings
}
var safeOutputsPromptLog = logger.New("workflow:safe_outputs_prompt")
// toolWithMaxBudget formats a tool name with a per-call budget annotation when the
// configured maximum is greater than 1. This helps agents understand that multiple
// calls to the same tool are allowed for the current workflow.
//
// Returns "toolname" when max is nil or "1" (default single-call behavior).
// Returns "toolname(max:N)" when max > 1 so agents know the real action budget.
func toolWithMaxBudget(name string, max *string) string {
if max == nil || *max == "1" {
return name
}
return fmt.Sprintf("%s(max:%s)", name, *max)
}
// buildSafeOutputsSections returns the PromptSections that form the <safe-output-tools> block.
// The block contains:
// 1. An inline opening tag with a compact Tools list (dynamic, depends on which tools are enabled).
// Any ${{ }} expressions in max: values are extracted to GH_AW_* env vars and replaced
// with __GH_AW_*__ placeholders so they do not appear in the run: heredoc, avoiding the
// GitHub Actions 21KB expression-size limit.
// 2. File references for tools that require multi-step instructions (create_pull_request,
// push_to_pull_request_branch, auto-injected create_issue notice).
// 3. An inline closing tag.
//
// The static intro (gh CLI warning, temporary ID rules, noop note) lives in
// actions/setup/md/safe_outputs_prompt.md and is included by the caller before these sections.
func buildSafeOutputsSections(safeOutputs *SafeOutputsConfig) []PromptSection {
if safeOutputs == nil {
return nil
}
safeOutputsPromptLog.Print("Building safe outputs sections")
// Build compact list of enabled tool names, annotated with max budget when > 1.
var tools []string
if safeOutputs.AddComments != nil {
tools = append(tools, toolWithMaxBudget("add_comment", safeOutputs.AddComments.Max))
}
if safeOutputs.CreateIssues != nil {
tools = append(tools, toolWithMaxBudget("create_issue", safeOutputs.CreateIssues.Max))
}
if safeOutputs.CloseIssues != nil {
tools = append(tools, toolWithMaxBudget("close_issue", safeOutputs.CloseIssues.Max))
}
if safeOutputs.UpdateIssues != nil {
tools = append(tools, toolWithMaxBudget("update_issue", safeOutputs.UpdateIssues.Max))
}
if safeOutputs.CreateDiscussions != nil {
tools = append(tools, toolWithMaxBudget("create_discussion", safeOutputs.CreateDiscussions.Max))
}
if safeOutputs.UpdateDiscussions != nil {
tools = append(tools, toolWithMaxBudget("update_discussion", safeOutputs.UpdateDiscussions.Max))
}
if safeOutputs.CloseDiscussions != nil {
tools = append(tools, toolWithMaxBudget("close_discussion", safeOutputs.CloseDiscussions.Max))
}
if safeOutputs.CreateAgentSessions != nil {
tools = append(tools, toolWithMaxBudget("create_agent_session", safeOutputs.CreateAgentSessions.Max))
}
if safeOutputs.CreatePullRequests != nil {
tools = append(tools, toolWithMaxBudget("create_pull_request", safeOutputs.CreatePullRequests.Max))
}
if safeOutputs.ClosePullRequests != nil {
tools = append(tools, toolWithMaxBudget("close_pull_request", safeOutputs.ClosePullRequests.Max))
}
if safeOutputs.UpdatePullRequests != nil {
tools = append(tools, toolWithMaxBudget("update_pull_request", safeOutputs.UpdatePullRequests.Max))
}
if safeOutputs.MarkPullRequestAsReadyForReview != nil {
tools = append(tools, toolWithMaxBudget("mark_pull_request_as_ready_for_review", safeOutputs.MarkPullRequestAsReadyForReview.Max))
}
if safeOutputs.DismissPullRequestReview != nil {
tools = append(tools, toolWithMaxBudget("dismiss_pull_request_review", safeOutputs.DismissPullRequestReview.Max))
}
if safeOutputs.CreatePullRequestReviewComments != nil {
tools = append(tools, toolWithMaxBudget("create_pull_request_review_comment", safeOutputs.CreatePullRequestReviewComments.Max))
}
if safeOutputs.SubmitPullRequestReview != nil {
tools = append(tools, toolWithMaxBudget("submit_pull_request_review", safeOutputs.SubmitPullRequestReview.Max))
}
if safeOutputs.ReplyToPullRequestReviewComment != nil {
tools = append(tools, toolWithMaxBudget("reply_to_pull_request_review_comment", safeOutputs.ReplyToPullRequestReviewComment.Max))
}
if safeOutputs.ResolvePullRequestReviewThread != nil {
tools = append(tools, toolWithMaxBudget("resolve_pull_request_review_thread", safeOutputs.ResolvePullRequestReviewThread.Max))
}
if safeOutputs.AddLabels != nil {
tools = append(tools, toolWithMaxBudget("add_labels", safeOutputs.AddLabels.Max))
}
if safeOutputs.RemoveLabels != nil {
tools = append(tools, toolWithMaxBudget("remove_labels", safeOutputs.RemoveLabels.Max))
}
if safeOutputs.ReplaceLabel != nil {
tools = append(tools, toolWithMaxBudget("replace_label", safeOutputs.ReplaceLabel.Max))
}
if safeOutputs.AddReviewer != nil {
tools = append(tools, toolWithMaxBudget("add_reviewer", safeOutputs.AddReviewer.Max))
}
if safeOutputs.AssignMilestone != nil {
tools = append(tools, toolWithMaxBudget("assign_milestone", safeOutputs.AssignMilestone.Max))
}
if safeOutputs.AssignToAgent != nil {
tools = append(tools, toolWithMaxBudget("assign_to_agent", safeOutputs.AssignToAgent.Max))
}
if safeOutputs.AssignToUser != nil {
tools = append(tools, toolWithMaxBudget("assign_to_user", safeOutputs.AssignToUser.Max))
}
if safeOutputs.UnassignFromUser != nil {
tools = append(tools, toolWithMaxBudget("unassign_from_user", safeOutputs.UnassignFromUser.Max))
}
if safeOutputs.PushToPullRequestBranch != nil {
tools = append(tools, toolWithMaxBudget("push_to_pull_request_branch", safeOutputs.PushToPullRequestBranch.Max))
}
if safeOutputs.CreateCodeScanningAlerts != nil {
tools = append(tools, toolWithMaxBudget("create_code_scanning_alert", safeOutputs.CreateCodeScanningAlerts.Max))
}
if safeOutputs.AutofixCodeScanningAlert != nil {
tools = append(tools, toolWithMaxBudget("autofix_code_scanning_alert", safeOutputs.AutofixCodeScanningAlert.Max))
}
if safeOutputs.CreateCheckRun != nil {
tools = append(tools, toolWithMaxBudget("create_check_run", safeOutputs.CreateCheckRun.Max))
}
if safeOutputs.UploadAssets != nil {
tools = append(tools, toolWithMaxBudget("upload_asset", safeOutputs.UploadAssets.Max))
}
if safeOutputs.UpdateRelease != nil {
tools = append(tools, toolWithMaxBudget("update_release", safeOutputs.UpdateRelease.Max))
}
if safeOutputs.UpdateProjects != nil {
tools = append(tools, toolWithMaxBudget("update_project", safeOutputs.UpdateProjects.Max))
}
if safeOutputs.CreateProjects != nil {
tools = append(tools, toolWithMaxBudget("create_project", safeOutputs.CreateProjects.Max))
}
if safeOutputs.CreateProjectStatusUpdates != nil {
tools = append(tools, toolWithMaxBudget("create_project_status_update", safeOutputs.CreateProjectStatusUpdates.Max))
}
if safeOutputs.LinkSubIssue != nil {
tools = append(tools, toolWithMaxBudget("link_sub_issue", safeOutputs.LinkSubIssue.Max))
}
if safeOutputs.HideComment != nil {
tools = append(tools, toolWithMaxBudget("hide_comment", safeOutputs.HideComment.Max))
}
if safeOutputs.SetIssueType != nil {
tools = append(tools, toolWithMaxBudget("set_issue_type", safeOutputs.SetIssueType.Max))
}
if safeOutputs.SetIssueField != nil {
tools = append(tools, toolWithMaxBudget("set_issue_field", safeOutputs.SetIssueField.Max))
}
if safeOutputs.DispatchWorkflow != nil {
tools = append(tools, toolWithMaxBudget("dispatch_workflow", safeOutputs.DispatchWorkflow.Max))
}
if safeOutputs.DispatchRepository != nil {
// dispatch_repository uses per-tool max values (map-of-tools pattern); no top-level max.
tools = append(tools, "dispatch_repository")
}
if safeOutputs.CallWorkflow != nil {
tools = append(tools, toolWithMaxBudget("call_workflow", safeOutputs.CallWorkflow.Max))
}
if safeOutputs.MissingTool != nil {
tools = append(tools, toolWithMaxBudget("missing_tool", safeOutputs.MissingTool.Max))
}
if safeOutputs.MissingData != nil {
tools = append(tools, toolWithMaxBudget("missing_data", safeOutputs.MissingData.Max))
}
// noop is always included: it is auto-injected by extractSafeOutputsConfig and
// must always appear in the tools list so agents can signal no-op completion.
if safeOutputs.NoOp != nil {
tools = append(tools, toolWithMaxBudget("noop", safeOutputs.NoOp.Max))
}
// Add custom job tools from SafeOutputs.Jobs (sorted for deterministic output).
if len(safeOutputs.Jobs) > 0 {
jobNames := sliceutil.SortedKeys(safeOutputs.Jobs)
for _, jobName := range jobNames {
tools = append(tools, stringutil.NormalizeSafeOutputIdentifier(jobName))
}
}
// Add custom script tools from SafeOutputs.Scripts (sorted for deterministic output).
if len(safeOutputs.Scripts) > 0 {
scriptNames := sliceutil.SortedKeys(safeOutputs.Scripts)
for _, scriptName := range scriptNames {
tools = append(tools, stringutil.NormalizeSafeOutputIdentifier(scriptName))
}
}
// Add custom action tools from SafeOutputs.Actions (sorted for deterministic output).
if len(safeOutputs.Actions) > 0 {
actionNames := sliceutil.SortedKeys(safeOutputs.Actions)
for _, actionName := range actionNames {
tools = append(tools, stringutil.NormalizeSafeOutputIdentifier(actionName))
}
}
if len(tools) == 0 {
return nil
}
var sections []PromptSection
// Build the inline opening: XML tag + compact tools list.
// Extract any ${{ }} expressions from max: values so they do not appear in the
// run: heredoc (which is subject to GitHub Actions' 21KB expression-size limit).
// Expressions are replaced with __GH_AW_...__ placeholders and added to EnvVars
// so the placeholder substitution step can resolve them at runtime.
toolsContent := "<safe-output-tools>\nTools: " + strings.Join(tools, ", ")
envVars := make(map[string]string)
extractor := NewExpressionExtractor()
exprMappings, err := extractor.ExtractExpressions(toolsContent)
if err == nil && len(exprMappings) > 0 {
safeOutputsPromptLog.Printf("Extracted %d expression(s) from safe-output-tools block", len(exprMappings))
toolsContent = extractor.ReplaceExpressionsWithEnvVars(toolsContent)
for _, mapping := range exprMappings {
envVars[mapping.EnvVar] = fmt.Sprintf("${{ %s }}", mapping.Content)
}
}
// Inline opening: XML tag + compact tools list (with placeholders for any expressions)
sections = append(sections, PromptSection{
Content: toolsContent,
IsFile: false,
EnvVars: envVars,
})
// File sections for tools with multi-step instructions
if safeOutputs.CreatePullRequests != nil {
sections = append(sections, PromptSection{Content: safeOutputsCreatePRFile, IsFile: true})
}
if safeOutputs.PushToPullRequestBranch != nil {
sections = append(sections, PromptSection{Content: safeOutputsPushToBranchFile, IsFile: true})
}
if safeOutputs.CommentMemory != nil {
sections = append(sections, PromptSection{Content: safeOutputsCommentMemoryFile, IsFile: true})
}
if safeOutputs.UploadAssets != nil {
sections = append(sections, PromptSection{
Content: "\nupload_asset: provide a file path; returns a URL; assets are published after the workflow completes (" + constants.SafeOutputsMCPServerID.String() + ").",
IsFile: false,
})
}
// Auto-injected create_issue special notice
if safeOutputs.CreateIssues != nil && safeOutputs.AutoInjectedCreateIssue {
sections = append(sections, PromptSection{Content: safeOutputsAutoCreateIssueFile, IsFile: true})
}
// Inline closing tag
sections = append(sections, PromptSection{
Content: "</safe-output-tools>",
IsFile: false,
})
return sections
}
// applyTrialLogicalRepoToGitHubContext rewrites the github-context prompt so that
// the reported repository is the trial mode logical target rather than the host
// repository (github.repository). It replaces the unconditional repository line and
// appends a directive instructing the agent to target the logical repository for
// GitHub MCP calls that omit an explicit owner/repo.
func applyTrialLogicalRepoToGitHubContext(promptText, logicalRepo string) string {
const repoLine = "- **repository**: ${{ github.repository }}"
replacement := "- **repository**: " + logicalRepo
promptText = strings.Replace(promptText, repoLine, replacement, 1)
directive := fmt.Sprintf(
"\nThis workflow is running in trial mode. The repository above (%s) is the logical target repository. When calling GitHub tools without an explicit owner/repo, use this repository.\n",
logicalRepo,
)
const closeTag = "</github-context>"
if idx := strings.LastIndex(promptText, closeTag); idx >= 0 {
promptText = promptText[:idx] + directive + promptText[idx:]
} else {
promptText += directive
}
return promptText
}