Skip to content

Commit e89c65e

Browse files
chore: sync actions from [email protected] (#200)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent 6f8e8ef commit e89c65e

15 files changed

Lines changed: 767 additions & 551 deletions

‎setup/js/action_setup_otlp.cjs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -178,11 +178,11 @@ async function run() {
178178

179179
// Always propagate trace/span context to subsequent steps in this job so
180180
// that the conclusion span can find the same trace ID.
181+
if (isValidTraceId(traceId)) writeEnvLine(githubEnv, "GITHUB_AW_OTEL_TRACE_ID", traceId, "GITHUB_AW_OTEL_TRACE_ID", "GITHUB_ENV");
182+
if (isValidSpanId(spanId)) writeEnvLine(githubEnv, "GITHUB_AW_OTEL_PARENT_SPAN_ID", spanId, "GITHUB_AW_OTEL_PARENT_SPAN_ID", "GITHUB_ENV");
183+
// Propagate setup-end timestamp so the conclusion span can measure actual
184+
// job execution duration (setup-end → conclusion-start).
181185
if (githubEnv) {
182-
if (isValidTraceId(traceId)) writeEnvLine(githubEnv, "GITHUB_AW_OTEL_TRACE_ID", traceId, "GITHUB_AW_OTEL_TRACE_ID", "GITHUB_ENV");
183-
if (isValidSpanId(spanId)) writeEnvLine(githubEnv, "GITHUB_AW_OTEL_PARENT_SPAN_ID", spanId, "GITHUB_AW_OTEL_PARENT_SPAN_ID", "GITHUB_ENV");
184-
// Propagate setup-end timestamp so the conclusion span can measure actual
185-
// job execution duration (setup-end → conclusion-start).
186186
const setupEndMs = String(Math.floor(nowMs()));
187187
writeEnvLine(githubEnv, "GITHUB_AW_OTEL_JOB_START_MS", setupEndMs, "GITHUB_AW_OTEL_JOB_START_MS", "GITHUB_ENV");
188188
}

‎setup/js/add_reaction.cjs‎

Lines changed: 42 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,21 @@ async function main() {
6060
}
6161
}
6262

63+
/**
64+
* Extract a required field from the event payload, calling setFailed if missing.
65+
* @param {unknown} value - The extracted value (already resolved by caller)
66+
* @param {string} fieldName - Human-readable field name for error messages
67+
* @param {string} errorCode - Error code prefix (ERR_NOT_FOUND or ERR_VALIDATION)
68+
* @returns {boolean} true if valid, false if missing (setFailed already called)
69+
*/
70+
function requirePayloadField(value, fieldName, errorCode) {
71+
if (value == null) {
72+
core.setFailed(`${errorCode}: ${fieldName} not found in event payload`);
73+
return false;
74+
}
75+
return true;
76+
}
77+
6378
/**
6479
* Resolve the REST API route and params for non-discussion events.
6580
* Returns null for discussion/discussion_comment/pull_request_review/unsupported events (handled separately).
@@ -73,38 +88,26 @@ function resolveRestEndpoint(eventName, owner, repo, payload) {
7388
switch (eventName) {
7489
case "issues": {
7590
const issueNumber = payload?.issue?.number;
76-
if (!issueNumber) {
77-
core.setFailed(`${ERR_NOT_FOUND}: Issue number not found in event payload`);
78-
return null;
79-
}
91+
if (!requirePayloadField(issueNumber, "Issue number", ERR_NOT_FOUND)) return null;
8092
return { route: "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions", params: { owner, repo, issue_number: issueNumber } };
8193
}
8294

8395
case "issue_comment": {
8496
const commentId = payload?.comment?.id;
85-
if (!commentId) {
86-
core.setFailed(`${ERR_VALIDATION}: Comment ID not found in event payload`);
87-
return null;
88-
}
97+
if (!requirePayloadField(commentId, "Comment ID", ERR_VALIDATION)) return null;
8998
return { route: "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", params: { owner, repo, comment_id: commentId } };
9099
}
91100

92101
case "pull_request": {
93102
const prNumber = payload?.pull_request?.number;
94-
if (!prNumber) {
95-
core.setFailed(`${ERR_NOT_FOUND}: Pull request number not found in event payload`);
96-
return null;
97-
}
103+
if (!requirePayloadField(prNumber, "Pull request number", ERR_NOT_FOUND)) return null;
98104
// PRs are "issues" for the reactions endpoint
99105
return { route: "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions", params: { owner, repo, issue_number: prNumber } };
100106
}
101107

102108
case "pull_request_review_comment": {
103109
const reviewCommentId = payload?.comment?.id;
104-
if (!reviewCommentId) {
105-
core.setFailed(`${ERR_VALIDATION}: Review comment ID not found in event payload`);
106-
return null;
107-
}
110+
if (!requirePayloadField(reviewCommentId, "Review comment ID", ERR_VALIDATION)) return null;
108111
return { route: "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", params: { owner, repo, comment_id: reviewCommentId } };
109112
}
110113

@@ -134,38 +137,36 @@ function isRestReactionEvent(eventName) {
134137
* @param {string} reaction
135138
*/
136139
async function handleGraphQLOrUnknownEvent(eventName, owner, repo, payload, reaction) {
137-
switch (eventName) {
138-
case "discussion": {
139-
const discussionNumber = payload?.discussion?.number;
140-
if (!discussionNumber) {
141-
core.setFailed(`${ERR_NOT_FOUND}: Discussion number not found in event payload`);
142-
return;
140+
let subjectId;
141+
try {
142+
switch (eventName) {
143+
case "discussion": {
144+
const discussionNumber = payload?.discussion?.number;
145+
if (!requirePayloadField(discussionNumber, "Discussion number", ERR_NOT_FOUND)) return;
146+
subjectId = await getDiscussionNodeId(owner, repo, discussionNumber);
147+
break;
143148
}
144-
try {
145-
const discussionNodeId = await getDiscussionNodeId(owner, repo, discussionNumber);
146-
await addDiscussionReaction(discussionNodeId, reaction);
147-
} catch (error) {
148-
handleReactionError(error);
149+
150+
case "discussion_comment": {
151+
const commentNodeId = payload?.comment?.node_id;
152+
if (!requirePayloadField(commentNodeId, "Discussion comment node ID", ERR_NOT_FOUND)) return;
153+
subjectId = commentNodeId;
154+
break;
149155
}
150-
return;
151-
}
152156

153-
case "discussion_comment": {
154-
const commentNodeId = payload?.comment?.node_id;
155-
if (!commentNodeId) {
156-
core.setFailed(`${ERR_NOT_FOUND}: Discussion comment node ID not found in event payload`);
157+
default:
158+
core.setFailed(`${ERR_VALIDATION}: Unsupported event type: ${eventName}`);
157159
return;
158-
}
159-
try {
160-
await addDiscussionReaction(commentNodeId, reaction);
161-
} catch (error) {
162-
handleReactionError(error);
163-
}
160+
}
161+
162+
if (subjectId == null) {
163+
core.setFailed(`${ERR_VALIDATION}: subjectId could not be resolved for event: ${eventName}`);
164164
return;
165165
}
166166

167-
default:
168-
core.setFailed(`${ERR_VALIDATION}: Unsupported event type: ${eventName}`);
167+
await addDiscussionReaction(subjectId, reaction);
168+
} catch (error) {
169+
handleReactionError(error);
169170
}
170171
}
171172

‎setup/js/ai_credits_context.cjs‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ const AI_CREDITS_RATE_LIMIT_ERROR_FIELDS = new Set(["ai_credits_rate_limit_error
1212
const AI_CREDITS_RATE_LIMIT_TEXT_FIELDS = new Set(["error", "message", "reason", "details", "detail", "type", "code"]);
1313
const AI_CREDITS_RATE_LIMIT_PATTERNS = [/ai[\s_-]*credits?.*(?:rate[\s-]*limit|limit exceeded|budget exceeded|exceeded)/i, /(?:rate[\s-]*limit|too many requests).*(?:ai[\s_-]*credits?)/i, /\bai_credits_limit_exceeded\b/i];
1414
const MAX_AI_CREDITS_EXCEEDED_FIELDS = new Set(["max_ai_credits_exceeded", "maxAiCreditsExceeded"]);
15+
/** @type {{ aiCredits: string, maxAICredits: string, rateLimitError: boolean, maxAICreditsExceeded: boolean }} */
16+
const EMPTY_AI_CREDITS_STATE = { aiCredits: "", maxAICredits: "", rateLimitError: false, maxAICreditsExceeded: false };
1517
const BUDGET_EXCEEDED_EVENT = "budget_exceeded";
1618
// The literal error type emitted by the AWF API proxy (HTTP 400) when maxAiCredits is active
1719
// and the requested model is not in the built-in pricing table.
@@ -304,9 +306,7 @@ function parseUnknownModelAICreditsFromAuditLog(auditJsonlPathOverride) {
304306
* @returns {{ aiCredits: string, maxAICredits: string, rateLimitError: boolean, maxAICreditsExceeded: boolean }}
305307
*/
306308
function parseAuditLogCombined(auditJsonlPathOverride) {
307-
/** @type {{ aiCredits: string, maxAICredits: string, rateLimitError: boolean, maxAICreditsExceeded: boolean }} */
308-
const initial = { aiCredits: "", maxAICredits: "", rateLimitError: false, maxAICreditsExceeded: false };
309-
return iterateAuditEntries(auditJsonlPathOverride, initial, null, (acc, entry) => {
309+
return iterateAuditEntries(auditJsonlPathOverride, EMPTY_AI_CREDITS_STATE, null, (acc, entry) => {
310310
const errorInfo = parseAICreditsErrorInfoFromAuditEntry(entry);
311311
const max = parseMaxAICreditsFromAuditEntry(entry);
312312
const maxAICreditsExceeded = parseMaxAICreditsExceededFromAuditEntry(entry);
@@ -376,19 +376,18 @@ function resolveAICreditsFailureState({ logProvenance = true } = {}) {
376376
* @returns {{ aiCredits: string, maxAICredits: string, rateLimitError: boolean, maxAICreditsExceeded: boolean }}
377377
*/
378378
function parseAICreditsExceededFromAgentStdio() {
379-
const initial = { aiCredits: "", maxAICredits: "", rateLimitError: false, maxAICreditsExceeded: false };
380379
try {
381380
const agentOutputFile = process.env.GH_AW_AGENT_OUTPUT;
382381
// Derive the stdio log path from GH_AW_AGENT_OUTPUT when set, but always
383382
// fall back to the well-known default so directory-valued env vars don't
384383
// silently break detection.
385384
const derivedPath = agentOutputFile ? path.join(path.dirname(agentOutputFile), "agent-stdio.log") : null;
386385
const stdioLogPath = derivedPath && fs.existsSync(derivedPath) ? derivedPath : DEFAULT_AGENT_STDIO_LOG;
387-
if (!fs.existsSync(stdioLogPath)) return initial;
386+
if (!fs.existsSync(stdioLogPath)) return EMPTY_AI_CREDITS_STATE;
388387
// Read only the tail to avoid OOM on large logs; the error token always
389388
// appears near the end of the file.
390389
const stat = fs.statSync(stdioLogPath);
391-
if (stat.size === 0) return initial;
390+
if (stat.size === 0) return EMPTY_AI_CREDITS_STATE;
392391
const readSize = Math.min(stat.size, AGENT_STDIO_LOG_MAX_TAIL);
393392
const buf = Buffer.alloc(readSize);
394393
const fd = fs.openSync(stdioLogPath, "r");
@@ -403,7 +402,7 @@ function parseAICreditsExceededFromAgentStdio() {
403402
const RE_G = new RegExp(MAX_AI_CREDITS_EXCEEDED_STDIO_RE.source, "gi");
404403
const allMatches = [...content.matchAll(RE_G)];
405404
const match = allMatches.at(-1);
406-
if (!match) return initial;
405+
if (!match) return EMPTY_AI_CREDITS_STATE;
407406
const aiCredits = parsePositiveNumberString(match[1] || "");
408407
const maxAICredits = parsePositiveNumberString(match[2] || "");
409408
return {
@@ -413,7 +412,7 @@ function parseAICreditsExceededFromAgentStdio() {
413412
maxAICreditsExceeded: true,
414413
};
415414
} catch {
416-
return initial;
415+
return EMPTY_AI_CREDITS_STATE;
417416
}
418417
}
419418

‎setup/js/collect_ndjson_output.cjs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,16 @@ async function main() {
326326

327327
const typeConfig = expectedOutputTypes[itemType];
328328
const normalizeIssueClosingKeywords = typeConfig !== null && typeof typeConfig === "object" && typeConfig.normalize_closing_keywords === true;
329+
if (itemType === "dispatch_workflow") {
330+
const hasWorkflowName = typeof item.workflow_name === "string" && item.workflow_name.trim().length > 0;
331+
if (!hasWorkflowName && typeConfig !== null && typeof typeConfig === "object" && Array.isArray(typeConfig.workflows)) {
332+
const { workflows: configuredWorkflows } = typeConfig;
333+
if (configuredWorkflows.length === 1 && typeof configuredWorkflows[0] === "string" && configuredWorkflows[0].trim().length > 0) {
334+
item.workflow_name = configuredWorkflows[0].trim();
335+
core.info(`[INGESTION] Line ${i + 1}: Inferred dispatch_workflow workflow_name='${item.workflow_name}' from safe-outputs config`);
336+
}
337+
}
338+
}
329339

330340
// Use the validation engine to validate the item
331341
if (hasValidationConfig(itemType)) {

‎setup/js/create_issue.cjs‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ const ISSUE_FIELD_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
3535
const RECENTLY_CLOSED_DEDUP_DAYS = 30;
3636
const TITLE_DEDUP_SEARCH_PER_PAGE = 100;
3737
const TITLE_DEDUP_MAX_SEARCH_PAGES = 2;
38-
const TITLE_DEDUP_MIN_SEARCH_RATE_LIMIT_REMAINING = 500;
38+
const TITLE_DEDUP_MIN_SEARCH_RATE_LIMIT_FRACTION = 0.2;
3939

4040
/**
4141
* Create a dedicated GitHub client for copilot assignment operations.
@@ -494,14 +494,16 @@ async function getRepoTitleDedupCandidates(githubClient, owner, repo) {
494494
async function shouldSkipRepoTitleDedupSearch(githubClient, owner, repo) {
495495
try {
496496
const response = await githubClient.rest.rateLimit.get();
497-
const rawRemaining = response?.data?.resources?.search?.remaining;
497+
const { remaining: rawRemaining, limit: rawLimit } = response?.data?.resources?.search ?? {};
498498
const remaining = Number(rawRemaining);
499-
if (!Number.isFinite(remaining)) {
500-
core.warning(`Could not determine search rate limit remaining for ${owner}/${repo}; proceeding with repo-level title dedup search`);
499+
const limit = Number(rawLimit);
500+
if (!Number.isFinite(remaining) || !Number.isFinite(limit)) {
501+
core.warning(`Could not determine search rate limit values for ${owner}/${repo} (remaining=${rawRemaining}, limit=${rawLimit}); proceeding with repo-level title dedup search`);
501502
return false;
502503
}
503-
if (remaining <= TITLE_DEDUP_MIN_SEARCH_RATE_LIMIT_REMAINING) {
504-
core.warning(`Skipping repo-level title dedup search for ${owner}/${repo}: search rate limit remaining is ${remaining} (threshold <= ${TITLE_DEDUP_MIN_SEARCH_RATE_LIMIT_REMAINING})`);
504+
const threshold = limit * TITLE_DEDUP_MIN_SEARCH_RATE_LIMIT_FRACTION;
505+
if (remaining <= threshold) {
506+
core.warning(`Skipping repo-level title dedup search for ${owner}/${repo}: search rate limit remaining is ${remaining}/${limit} (threshold <= ${Math.floor(threshold)})`);
505507
return true;
506508
}
507509
} catch (error) {

‎setup/js/mcp_cli_bridge.cjs‎

Lines changed: 71 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -622,6 +622,63 @@ function readStdinSync() {
622622
return Buffer.concat(chunks).toString("utf8");
623623
}
624624

625+
/**
626+
* Try to extract a specific field value from a JSON object string.
627+
*
628+
* When per-field stdin mode (`--key .`) is used and stdin contains a JSON
629+
* object, this function checks whether that object has the target key. If so,
630+
* it returns the field value, allowing agents to pipe a full JSON payload and
631+
* extract individual fields without the entire JSON string ending up as the
632+
* field value.
633+
*
634+
* Example: an agent may construct a full payload JSON and still pass individual
635+
* fields via `--key .`:
636+
* printf '{"title":"Fix bug","body":"Details here"}' \
637+
* | safeoutputs create_pull_request --title "Fix bug" --body .
638+
* Without this helper the body would be the raw JSON string. With it, the
639+
* body is correctly extracted as "Details here".
640+
*
641+
* Returns `undefined` when stdin is not a JSON object, when the key is absent
642+
* from the object, or when JSON parsing fails — in all those cases the caller
643+
* falls back to using the raw stdin content.
644+
*
645+
* @param {string} trimmedStdin - Pre-trimmed stdin content. Must have no
646+
* leading whitespace — the function uses a `startsWith('{')` fast-path to
647+
* avoid parsing non-JSON input, so leading whitespace will cause a JSON
648+
* object to be treated as non-JSON and return `undefined`. All callers
649+
* must pass `stdinContent.trim()` before invoking this function.
650+
* @param {string} canonicalKey - Canonical schema key to look up
651+
* @param {Record<string, {type?: string|string[]}>} schemaProperties - Tool input schema properties
652+
* @param {Map<string, string>} normalizedSchemaKeyMap - Map from normalized key to canonical schema key
653+
* @param {Set<string>} ambiguousNormalizedSchemaKeys - Normalized keys that map to multiple schema keys
654+
* @returns {unknown} The extracted field value, or `undefined` if not found
655+
*/
656+
function tryExtractJsonFieldFromStdin(trimmedStdin, canonicalKey, schemaProperties, normalizedSchemaKeyMap, ambiguousNormalizedSchemaKeys) {
657+
if (!trimmedStdin.startsWith("{")) {
658+
return undefined;
659+
}
660+
try {
661+
const parsed = JSON.parse(trimmedStdin);
662+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
663+
return undefined;
664+
}
665+
// Try the canonical key first, then any schema-aliased form.
666+
if (Object.prototype.hasOwnProperty.call(parsed, canonicalKey)) {
667+
return parsed[canonicalKey];
668+
}
669+
// Search for a key in the JSON that resolves to the same canonical key.
670+
for (const jsonKey of Object.keys(parsed)) {
671+
const resolved = resolveSchemaPropertyKey(jsonKey, schemaProperties, normalizedSchemaKeyMap, ambiguousNormalizedSchemaKeys);
672+
if (resolved === canonicalKey) {
673+
return parsed[jsonKey];
674+
}
675+
}
676+
return undefined;
677+
} catch {
678+
return undefined;
679+
}
680+
}
681+
625682
/**
626683
* Parse user-provided --key value pairs into a tool arguments object.
627684
* Supports both --key value and --key=value styles.
@@ -634,10 +691,15 @@ function readStdinSync() {
634691
* printf '{"issue_number":42,"body":"hello"}' | safeoutputs add_comment .
635692
*
636693
* When `stdinContent` is provided and non-empty, any '--key .' or '--key=.'
637-
* pair substitutes that field's value with the raw stdin text (per-field
638-
* stdin mode). This enables agents to pipe large text into a single field:
639-
* printf 'Long issue body...' | safeoutputs create_issue --title "Bug" --body .
640-
* When stdin is empty, the '.' is passed through as a literal value.
694+
* pair substitutes that field's value with stdin. If stdin is a JSON object
695+
* that contains the target key, the matching field value is extracted from the
696+
* JSON instead of using the entire stdin string. This prevents a common agent
697+
* mistake where the whole JSON payload ends up as a string field value:
698+
* printf '{"title":"Fix bug","body":"Details"}' \
699+
* | safeoutputs create_pull_request --title "Fix bug" --body .
700+
* When stdin is empty, the '.' is passed through as a literal value. When
701+
* stdin is non-empty but the key is absent from the JSON (or stdin is not a
702+
* JSON object), the entire trimmed stdin string is used as the field value.
641703
*
642704
* @param {string[]} args - User arguments after the tool name
643705
* @param {Record<string, {type?: string|string[]}>} [schemaProperties] - Tool input schema properties
@@ -686,7 +748,8 @@ function parseToolArgs(args, schemaProperties = {}, stdinContent = null) {
686748
const canonicalKey = resolveSchemaPropertyKey(key, schemaProperties, normalizedSchemaKeyMap, ambiguousNormalizedSchemaKeys);
687749
const rawValue = raw.slice(eqIdx + 1);
688750
if (rawValue === "." && trimmedStdin) {
689-
result[canonicalKey] = trimmedStdin;
751+
const extracted = tryExtractJsonFieldFromStdin(trimmedStdin, canonicalKey, schemaProperties, normalizedSchemaKeyMap, ambiguousNormalizedSchemaKeys);
752+
result[canonicalKey] = extracted !== undefined ? extracted : trimmedStdin;
690753
} else {
691754
result[canonicalKey] = coerceToolArgValue(canonicalKey, rawValue, schemaProperties[canonicalKey], result[canonicalKey], !hasSchemaProperties);
692755
}
@@ -697,7 +760,8 @@ function parseToolArgs(args, schemaProperties = {}, stdinContent = null) {
697760
const canonicalKey = resolveSchemaPropertyKey(raw, schemaProperties, normalizedSchemaKeyMap, ambiguousNormalizedSchemaKeys);
698761
const rawValue = args[i + 1];
699762
if (rawValue === "." && trimmedStdin) {
700-
result[canonicalKey] = trimmedStdin;
763+
const extracted = tryExtractJsonFieldFromStdin(trimmedStdin, canonicalKey, schemaProperties, normalizedSchemaKeyMap, ambiguousNormalizedSchemaKeys);
764+
result[canonicalKey] = extracted !== undefined ? extracted : trimmedStdin;
701765
} else {
702766
result[canonicalKey] = coerceToolArgValue(canonicalKey, rawValue, schemaProperties[canonicalKey], result[canonicalKey], !hasSchemaProperties);
703767
}
@@ -1441,6 +1505,7 @@ module.exports = {
14411505
parseToolArgs,
14421506
coerceToolArgValue,
14431507
unescapeCliStringArg,
1508+
tryExtractJsonFieldFromStdin,
14441509
extractJSONRPCMessages,
14451510
renderProgressMessages,
14461511
formatResponse,

0 commit comments

Comments
 (0)