| 499 | * 6. Counting system message tokens |
| 500 | */ |
| 501 | export async function buildStreamSystemContext( |
| 502 | opts: BuildStreamSystemContextOptions |
| 503 | ): Promise<StreamSystemContextResult> { |
| 504 | const { |
| 505 | runtime, |
| 506 | metadata, |
| 507 | workspacePath, |
| 508 | workspaceId, |
| 509 | agentDefinition, |
| 510 | effectiveMode, |
| 511 | agentDiscoveryRuntime, |
| 512 | agentDiscoveryPath, |
| 513 | isSubagentWorkspace, |
| 514 | effectiveAdditionalInstructions, |
| 515 | planFilePath, |
| 516 | modelString, |
| 517 | cfg, |
| 518 | providersConfig, |
| 519 | mcpServers, |
| 520 | muxScope, |
| 521 | loadDesktopCapability, |
| 522 | advisorToolAvailable, |
| 523 | } = opts; |
| 524 | |
| 525 | const workspaceLog = log.withFields({ workspaceId, workspaceName: metadata.name }); |
| 526 | |
| 527 | // Resolve the body with inheritance (prompt.append merges with base). |
| 528 | // Use agentDefinition.id (may have fallen back to exec) instead of effectiveAgentId. |
| 529 | const resolvedBody = await resolveAgentBody( |
| 530 | agentDiscoveryRuntime, |
| 531 | agentDiscoveryPath, |
| 532 | agentDefinition.id, |
| 533 | { |
| 534 | skipScopesAbove: getSkipScopesAboveForKnownScope(agentDefinition.scope), |
| 535 | } |
| 536 | ); |
| 537 | |
| 538 | let subagentAppendPrompt: string | undefined; |
| 539 | if (isSubagentWorkspace) { |
| 540 | try { |
| 541 | const resolvedFrontmatter = await resolveAgentFrontmatter( |
| 542 | agentDiscoveryRuntime, |
| 543 | agentDiscoveryPath, |
| 544 | agentDefinition.id, |
| 545 | { |
| 546 | skipScopesAbove: getSkipScopesAboveForKnownScope(agentDefinition.scope), |
| 547 | } |
| 548 | ); |
| 549 | subagentAppendPrompt = resolvedFrontmatter.subagent?.append_prompt; |
| 550 | } catch (error: unknown) { |
| 551 | workspaceLog.debug("Failed to resolve agent frontmatter for subagent append_prompt", { |
| 552 | agentId: agentDefinition.id, |
| 553 | error: getErrorMessage(error), |
| 554 | }); |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | const agentSystemPromptSections = [resolvedBody]; |