Repository navigation
Conversation
🔒 Aisle Security AnalysisWe found 4 potential security issue(s) in this PR:
1. 🟠 API key leaked to provider plugin stream function via automatic injection
DescriptionIn This is risky because Vulnerable flow:
Vulnerable code: const apiKey = await authStorage.getApiKey(model.provider);
return inner(m, context, { ...options, apiKey: apiKey ?? options?.apiKey });RecommendationDo not automatically disclose stored credentials to plugin-supplied stream functions. Options to fix:
return inner(m, context, {
...options,
getApiKey: async () => authStorage.getApiKey(model.provider),
});
return async (m, context, options) => {
if (options?.apiKey) return inner(m, context, options);
const apiKey = await authStorage.getApiKey(model.provider);
return inner(m, context, { ...options, apiKey });
};Additionally, document and enforce a trust boundary for provider plugins; if plugins can be workspace-supplied, treat them as untrusted and sandbox or restrict secret access. 2. 🟡 Heartbeat prompt/ack pairs no longer filtered from replay history (prompt injection & context DoS)
DescriptionThe embedded runner previously removed heartbeat prompt/ack pairs (a user message containing the heartbeat task prompt followed by an assistant This change removes that filtering and now truncates/forwards history based directly on
Previously this was mitigated by RecommendationRe-introduce heartbeat-pair suppression (or an equivalent invariant) before history truncation and before sending messages to the provider. Options:
import { filterHeartbeatPairs } from "../../../auto-reply/heartbeat-filter.js";
import { resolveHeartbeatSummaryForAgent } from "../../../infra/heartbeat-summary.js";
const heartbeatSummary = params.config && sessionAgentId
? resolveHeartbeatSummaryForAgent(params.config, sessionAgentId)
: undefined;
const heartbeatFiltered = filterHeartbeatPairs(
validated,
heartbeatSummary?.ackMaxChars,
heartbeatSummary?.prompt,
);
const truncated = limitHistoryTurns(heartbeatFiltered, historyLimit);
Also consider excluding heartbeat turns from 3. 🟡 WebSocket transport ignores resolvedApiKey and may use wrong provider key (credential mix-up)
DescriptionIn
Impact:
Vulnerable code: const wsApiKey = shouldUseWebSocketTransport
? await params.authStorage.getApiKey(params.provider)
: undefined;RecommendationUse the same API key resolution logic as HTTP/provider transports by preferring For example: const wsApiKey = shouldUseWebSocketTransport
? (params.resolvedApiKey?.trim() || (await params.authStorage.getApiKey(params.model.provider)))
: undefined;This ensures:
4. 🟡 Prompt injection via unescaped runtimeCapabilities in system prompt runtime line
Description
In this diff, the previous
Vulnerable code: runtimeChannel
? `capabilities=${runtimeCapabilities.length > 0 ? runtimeCapabilities.join(",") : "none"}`
: ""If an attacker can influence configured capabilities (e.g., via a compromised plugin/config channel, multi-tenant config injection, or other untrusted capability sources), they can inject additional prompt sections/instructions by including newlines, e.g. RecommendationRe-introduce strict normalization/escaping for capability identifiers before placing them into the system prompt. Recommended approach (allowlist + strip control chars): function normalizeCapabilityId(raw: string): string | undefined {
const s = raw.trim().toLowerCase();
// prevent prompt-breaking characters
if (!s || /[\r\n\t|]/.test(s)) return undefined;
// keep to a safe identifier character set
if (!/^[a-z0-9._-]+$/.test(s)) return undefined;
return s;
}
const safeCaps = runtimeCapabilities
.map((c) => normalizeCapabilityId(String(c)))
.filter((c): c is string => Boolean(c));
const capLine = `capabilities=${safeCaps.length ? safeCaps.join(",") : "none"}`;Alternatively, restore the previous Analyzed PR: #63456 at commit Last updated on: 2026-04-09T00:57:15Z |
Greptile SummaryThis PR scopes the workspace guidance in Confidence Score: 5/5Safe to merge — all remaining findings are P2 or lower. The core change (isCodingContext guard on workspace guidance) is correct, well-tested, and has no logical edge cases. The SYSTEM_PROMPT_CACHE_BOUNDARY constant is still used throughout the pipeline in other test files; its removal from buildAgentSystemPrompt's output is an intentional refactor, not a regression. Removed tests correspond to prompt sections that were intentionally pruned. No P0 or P1 issues found. No files require special attention.
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1382808cea
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return { | ||
| replayMetadata: buildAttemptReplayMetadata({ | ||
| toolMetas: toolMetasNormalized, | ||
| didSendViaMessagingTool: didSendViaMessagingTool(), | ||
| successfulCronAdds: getSuccessfulCronAdds(), | ||
| }), | ||
| itemLifecycle: getItemLifecycle(), | ||
| aborted, | ||
| timedOut, | ||
| idleTimedOut, | ||
| timedOutDuringCompaction, | ||
| promptError, |
There was a problem hiding this comment.
Preserve attempt replay metadata and item lifecycle fields
The attempt result returned here no longer includes replayMetadata or itemLifecycle, but downstream logic in run.ts/run/incomplete-turn.ts dereferences those fields without guards when evaluating incomplete-turn and planning-only retry behavior. On normal non-aborted turns, this can raise a runtime TypeError (for example when checking attempt.itemLifecycle.startedCount) after the model call has already completed, causing the run to fail in post-processing.
Useful? React with 👍 / 👎.
| const { bootstrapFiles: hookAdjustedBootstrapFiles, contextFiles } = | ||
| await resolveBootstrapContextForRun({ | ||
| workspaceDir: effectiveWorkspace, | ||
| config: params.config, | ||
| sessionKey: params.sessionKey, |
There was a problem hiding this comment.
Honor continuation-skip before bootstrap context injection
This now unconditionally resolves bootstrap context, which bypasses the documented agents.defaults.contextInjection: "continuation-skip" flow that should skip reinjection after a completed bootstrap turn. In continuation sessions, repeatedly reinjecting workspace bootstrap/context files increases prompt size every turn and can negate the overflow/performance protections that continuation mode is meant to provide.
Useful? React with 👍 / 👎.
| const appendPrompt = buildEmbeddedSystemPrompt({ | ||
| workspaceDir: effectiveWorkspace, | ||
| context: { | ||
| config: params.config, | ||
| agentDir: params.agentDir, | ||
| workspaceDir: effectiveWorkspace, | ||
| provider: params.provider, | ||
| modelId: params.modelId, | ||
| promptMode: effectivePromptMode, | ||
| runtimeChannel, | ||
| runtimeCapabilities, | ||
| agentId: sessionAgentId, | ||
| }, | ||
| defaultThinkLevel: params.thinkLevel, | ||
| reasoningLevel: params.reasoningLevel ?? "off", | ||
| extraSystemPrompt: params.extraSystemPrompt, |
There was a problem hiding this comment.
Respect configured systemPromptOverride for embedded runs
The embedded attempt now always uses the assembled prompt from buildEmbeddedSystemPrompt, but no longer checks the config-based override path (agents.defaults.systemPromptOverride / per-agent override). That silently drops an existing contract for users who pin a custom system prompt, and creates inconsistent behavior versus other runner paths that still resolve and apply that override.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Pull request overview
This PR updates the agent system prompt construction so “workspace guidance” and related repo-style reminders are only injected in coding/repo contexts, avoiding repo-specific nudges in general assistant/product sessions.
Changes:
- Scope workspace guidance by detecting coding contexts via
runtimeInfo.repoRoot, and add tests for coding vs non-coding prompt behavior. - Revamp the “Tooling” section to list available tools (with summaries) when tool names are provided.
- Refactor embedded runner attempt flow and prompt assembly to support the new prompt behavior (including commit-reminder gating).
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| src/agents/system-prompt.ts | Adjusts workspace guidance behavior and rewrites tooling/approval guidance in the system prompt. |
| src/agents/system-prompt.test.ts | Updates prompt assertions and adds tests for coding vs non-coding workspace guidance. |
| src/agents/pi-embedded-runner/run/attempt.ts | Refactors embedded attempt execution and system prompt assembly, including gating commit reminders by coding context. |
Comments suppressed due to low confidence (1)
src/agents/pi-embedded-runner/run/attempt.ts:1965
- runEmbeddedAttempt() now returns an object missing required EmbeddedRunAttemptResult fields (e.g., idleTimedOut, promptErrorSource, replayMetadata, itemLifecycle). This will fail TypeScript (and callers expecting these fields) unless the result type is updated accordingly. Either restore these fields in the return value or change EmbeddedRunAttemptResult to match the new shape and update downstream users/tests.
return {
aborted,
timedOut,
timedOutDuringCompaction,
promptError,
sessionIdUsed,
bootstrapPromptWarningSignaturesSeen: bootstrapPromptWarning.warningSignaturesSeen,
bootstrapPromptWarningSignature: bootstrapPromptWarning.signature,
systemPromptReport,
messagesSnapshot,
assistantTexts,
toolMetas: toolMetasNormalized,
lastAssistant,
lastToolError: getLastToolError?.(),
didSendViaMessagingTool: didSendViaMessagingTool(),
messagingToolSentTexts: getMessagingToolSentTexts(),
messagingToolSentMediaUrls: getMessagingToolSentMediaUrls(),
messagingToolSentTargets: getMessagingToolSentTargets(),
successfulCronAdds: getSuccessfulCronAdds(),
cloudCodeAssistFormatError: Boolean(
lastAssistant?.errorMessage && isCloudCodeAssistFormatError(lastAssistant.errorMessage),
),
attemptUsage: getUsageTotals(),
compactionCount: getCompactionCount(),
// Client tool call detected (OpenResponses hosted tools)
clientToolCall: clientToolCallDetected ?? undefined,
yieldDetected: yieldDetected || undefined,
};
| cfg: params.config, | ||
| trigger: params.trigger, | ||
| }); | ||
| const idleTimeoutMs = resolveLlmIdleTimeoutMs(params.config); |
There was a problem hiding this comment.
resolveLlmIdleTimeoutMs() is being called with params.config, but the function signature expects an options object (e.g., { cfg, trigger }). As written, config-derived timeouts and the cron-trigger disable path won’t apply (and this should also be a TS type error). Pass { cfg: params.config, trigger: params.trigger } (or update resolveLlmIdleTimeoutMs signature) to preserve configured behavior.
| const idleTimeoutMs = resolveLlmIdleTimeoutMs(params.config); | |
| const idleTimeoutMs = resolveLlmIdleTimeoutMs({ | |
| cfg: params.config, | |
| trigger: params.trigger, | |
| }); |
| const ttsHint = params.config ? buildTtsSystemPromptHint(params.config) : undefined; | ||
| const ownerDisplay = resolveOwnerDisplaySetting(params.config); | ||
| const heartbeatPrompt = shouldInjectHeartbeatPrompt({ | ||
| config: params.config, | ||
| agentId: sessionAgentId, | ||
| defaultAgentId, | ||
| isDefaultAgent, | ||
| trigger: params.trigger, | ||
| }) | ||
| ? resolveHeartbeatPromptForSystemPrompt({ | ||
| config: params.config, | ||
| agentId: sessionAgentId, | ||
| defaultAgentId, | ||
| }) | ||
| ? resolveHeartbeatPrompt(params.config?.agents?.defaults?.heartbeat?.prompt) | ||
| : undefined; |
There was a problem hiding this comment.
Heartbeat prompt injection now bypasses the existing per-agent/config-aware logic: shouldInjectHeartbeatPrompt() is called without config/agentId/defaultAgentId, and heartbeatPrompt is resolved only from config.agents.defaults.heartbeat.prompt. This ignores per-agent heartbeat overrides and config flags like includeSystemPromptSection=false. Prefer using resolveHeartbeatPromptForSystemPrompt({config, agentId: sessionAgentId, defaultAgentId}) and pass the same ids into shouldInjectHeartbeatPrompt().
| export function buildAgentSystemPrompt(params: { | ||
| workspaceDir: string; | ||
| defaultThinkLevel?: ThinkLevel; | ||
| reasoningLevel?: ReasoningLevel; | ||
| extraSystemPrompt?: string; | ||
| ownerNumbers?: string[]; | ||
| ownerDisplay?: OwnerIdDisplay; | ||
| ownerDisplaySecret?: string; | ||
| reasoningTagHint?: boolean; | ||
| toolNames?: string[]; | ||
| toolSummaries?: Record<string, string>; | ||
| modelAliasLines?: string[]; | ||
| userTimezone?: string; | ||
| userTime?: string; | ||
| userTimeFormat?: ResolvedTimeFormat; | ||
| contextFiles?: EmbeddedContextFile[]; | ||
| skillsPrompt?: string; | ||
| heartbeatPrompt?: string; | ||
| docsPath?: string; | ||
| workspaceNotes?: string[]; | ||
| ttsHint?: string; | ||
| /** Controls which hardcoded sections to include. Defaults to "full". */ | ||
| promptMode?: PromptMode; | ||
| /** Whether ACP-specific routing guidance should be included. Defaults to true. */ | ||
| acpEnabled?: boolean; | ||
| runtimeInfo?: { | ||
| agentId?: string; | ||
| host?: string; | ||
| os?: string; | ||
| arch?: string; | ||
| node?: string; | ||
| provider?: string; | ||
| model?: string; | ||
| defaultModel?: string; | ||
| shell?: string; | ||
| channel?: string; | ||
| capabilities?: string[]; | ||
| repoRoot?: string; | ||
| }; | ||
| messageToolHints?: string[]; | ||
| sandboxInfo?: EmbeddedSandboxInfo; | ||
| /** Reaction guidance for the agent (for Telegram minimal/extensive modes). */ | ||
| reactionGuidance?: { | ||
| level: "minimal" | "extensive"; | ||
| channel: string; | ||
| }; | ||
| /** Whether to include the active memory plugin prompt guidance in the base system prompt. Defaults to true. */ | ||
| includeMemorySection?: boolean; | ||
| memoryCitationsMode?: MemoryCitationsMode; | ||
| promptContribution?: ProviderSystemPromptContribution; | ||
| }) { |
There was a problem hiding this comment.
buildAgentSystemPrompt() no longer accepts includeMemorySection/promptContribution, but there are in-repo call sites and tests still passing them (e.g., src/agents/pi-embedded-runner/system-prompt.ts passes includeMemorySection and promptContribution; src/agents/system-prompt.memory.test.ts passes includeMemorySection:false). This will break compilation/tests. Either keep these params in buildAgentSystemPrompt or update all callers/tests and remove the related plumbing in buildEmbeddedSystemPrompt.
| const runtimeChannel = params.runtimeChannel?.trim().toLowerCase(); | ||
| if ( | ||
| runtimeChannel === "discord" || | ||
| runtimeChannel === "slack" || | ||
| runtimeChannel === "telegram" || | ||
| runtimeChannel === "webchat" | ||
| ) { | ||
| return "When exec returns approval-pending on Discord, Slack, Telegram, or WebChat, rely on the native approval card/buttons when they appear and do not also send plain chat /approve instructions. Only include the concrete /approve command if the tool result says chat approvals are unavailable or only manual approval is possible."; | ||
| } | ||
| return "When exec returns approval-pending, include the concrete /approve command from tool output as plain chat text for the user, and do not ask for a different or rotated code."; |
There was a problem hiding this comment.
buildExecApprovalPromptGuidance() hardcodes the set of “native approval” channels to Discord/Slack/Telegram/WebChat, but the codebase supports native exec approvals on other channels (e.g., Matrix via approvalCapability.native / supportsNativeExecApprovalClient()). This will cause incorrect /approve guidance (duplicating manual instructions) on those channels. Consider delegating to supportsNativeExecApprovalClient() or resolveChannelApprovalCapability(getChannelPlugin(channel)) instead of hardcoding.
| const runtimeChannel = params.runtimeChannel?.trim().toLowerCase(); | |
| if ( | |
| runtimeChannel === "discord" || | |
| runtimeChannel === "slack" || | |
| runtimeChannel === "telegram" || | |
| runtimeChannel === "webchat" | |
| ) { | |
| return "When exec returns approval-pending on Discord, Slack, Telegram, or WebChat, rely on the native approval card/buttons when they appear and do not also send plain chat /approve instructions. Only include the concrete /approve command if the tool result says chat approvals are unavailable or only manual approval is possible."; | |
| } | |
| return "When exec returns approval-pending, include the concrete /approve command from tool output as plain chat text for the user, and do not ask for a different or rotated code."; | |
| void params; | |
| return "When exec returns approval-pending, rely on the native approval card/buttons when they appear and do not also send plain chat /approve instructions. Only include the concrete /approve command from tool output if the tool result says chat approvals are unavailable or only manual approval is possible, and do not ask for a different or rotated code."; |
|
Thanks for the context here. I swept through the related work, and this is now duplicate or superseded. Keep open for explicit maintainer handling: the useful prompt-scoping idea is not on current main, but this branch is dirty, missing real behavior proof, and introduces concrete build, agent-runtime, auth, and prompt-safety regressions. Canonical path: Close this stale PR as superseded: Replace with a narrow prompt-only branch. Recreate only the workspace-guidance scoping on current main and leave embedded-runner stream, auth, replay, and cache-boundary code unchanged unless a focused follow-up proves each contract. So I’m closing this here because the remaining work is already tracked in the canonical issue. Review detailsBest possible solution: Close this stale PR as superseded: Replace with a narrow prompt-only branch. Recreate only the workspace-guidance scoping on current main and leave embedded-runner stream, auth, replay, and cache-boundary code unchanged unless a focused follow-up proves each contract. Do we have a high-confidence way to reproduce the issue? Yes for the blocking PR regressions from source inspection and CI logs: the branch has stale imports, wrong call shapes, missing attempt result fields, and changed credential/replay paths. I did not run tests locally because this review is read-only. Is this the best way to solve the issue? No. The prompt-scoping idea is useful, but this is not the best fix because it couples a small prompt-policy change to a broad stale embedded-runner rewrite; the safer solution is a narrow current-main prompt change with targeted tests and real behavior proof. Security review: Security review needs attention: The diff changes credential routing and prompt/replay safeguards in agent runtime code, creating concrete security-boundary concerns.
AGENTS.md: found and applied where relevant. What I checked:
Likely related people:
Codex review notes: model internal, reasoning high; reviewed against 010b61746379. |
|
Thanks @ImLukeF. Closing this stale branch rather than carrying its current diff forward. The underlying workspace-scoping idea is reasonable, but the exact head is based on the April prompt/runner implementation and now replaces large current sections: alongside the one |
Summary
Testing