From b08dbd1a92eb9c73353f916856a0abe42cf45303 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:34:21 +0000 Subject: [PATCH] fix(tracing): trace each agent's system prompt when the agent switches mid-loop Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- packages/opencode/src/session/prompt.ts | 16 +- .../session/system-prompt-trace-loop.test.ts | 175 ++++++++++++++++++ 2 files changed, 186 insertions(+), 5 deletions(-) create mode 100644 packages/opencode/test/session/system-prompt-trace-loop.test.ts diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 93187d0201..e65003b699 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -780,6 +780,9 @@ export namespace SessionPrompt { let structuredOutput: unknown | undefined let step = 0 + // altimate_change start — the agent whose system prompt this loop run last traced + let systemPromptTracedFor: string | undefined + // altimate_change end // altimate_change start — the agent's `steps` cap counts model requests only. `step` also // counts iterations that run a compaction or a subtask and `continue`, which ended capped // agents several requests early. @@ -2149,11 +2152,12 @@ export namespace SessionPrompt { const deferredText: MessageV2.TextPart[] = [] // altimate_change end - // altimate_change start - trace system prompt once per loop() call. - // The system prompt is functionally identical across steps within a single - // loop() invocation (same agent, same environment). Agent switches re-enter - // loop() with step reset to 0, so each agent's prompt is traced separately. - if (step === 1) { + // altimate_change start - trace the system prompt once per agent per loop() call. + // It is identical across steps while the agent stays the same, but an agent switch + // inside the loop (plan_exit's builder message, a newly queued request) does not + // reset `step`, so the switch is detected by name. + if (agent.name !== systemPromptTracedFor) { + systemPromptTracedFor = agent.name Tracer.active?.logSpan({ name: "system-prompt", startTime: Date.now(), @@ -2161,6 +2165,8 @@ export namespace SessionPrompt { input: { agent: agent.name, step }, output: { parts: system.length, content: system.join("\n\n") }, }) + } + if (step === 1) { // altimate_change start (AI-7519) — emit the parent bootstrap span // covering everything from loop() entry to just-before-first-generation. // Companion sub-spans (bootstrap.session-get, bootstrap.config-get, diff --git a/packages/opencode/test/session/system-prompt-trace-loop.test.ts b/packages/opencode/test/session/system-prompt-trace-loop.test.ts new file mode 100644 index 0000000000..6349cbc6d6 --- /dev/null +++ b/packages/opencode/test/session/system-prompt-trace-loop.test.ts @@ -0,0 +1,175 @@ +/** + * The system-prompt span through the real prompt loop: an agent switch inside one loop run + * traces the new agent's prompt, and a step that keeps the agent does not trace it again. + */ +import { expect } from "bun:test" +import { Effect, Fiber, Layer } from "effect" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { Session } from "@/session/session" +import { SessionPrompt } from "../../src/session/prompt" +import { SessionSummary } from "../../src/session/summary" +import { Database } from "@opencode-ai/core/database/database" +import { SessionProjector } from "@opencode-ai/core/session/projector" +import { Tracer } from "../../src/altimate/observability/tracing" +import { pollWithTimeout, testEffect } from "../lib/effect" +import { TestLLMServer } from "../lib/llm-server" +import { provideTmpdirServerLegacy } from "./legacy-instance" +import { LSP } from "@/lsp/lsp" +import { MCP } from "../../src/mcp" +import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" +import { RuntimeFlags } from "@/effect/runtime-flags" + +const mcp = Layer.succeed( + MCP.Service, + MCP.Service.of({ + status: () => Effect.succeed({}), + clients: () => Effect.succeed({}), + tools: () => Effect.succeed({}), + prompts: () => Effect.succeed({}), + resources: () => Effect.succeed({}), + add: () => Effect.succeed({ status: { status: "disabled" as const } }), + connect: () => Effect.void, + disconnect: () => Effect.void, + remove: () => Effect.void, + getPrompt: () => Effect.succeed(undefined), + readResource: () => Effect.succeed(undefined), + startAuth: () => Effect.die("unexpected MCP auth"), + authenticate: () => Effect.die("unexpected MCP auth"), + finishAuth: () => Effect.die("unexpected MCP auth"), + removeAuth: () => Effect.void, + supportsOAuth: () => Effect.succeed(false), + hasStoredTokens: () => Effect.succeed(false), + getAuthStatus: () => Effect.succeed("not_authenticated" as const), + entry: () => Effect.succeed(undefined), + listMeta: () => Effect.succeed(undefined), + snapshot: () => Effect.succeed({ tools: {}, meta: undefined }), + }), +) + +const lsp = Layer.succeed( + LSP.Service, + LSP.Service.of({ + init: () => Effect.void, + status: () => Effect.succeed([]), + hasClients: () => Effect.succeed(false), + touchFile: () => Effect.void, + diagnostics: () => Effect.succeed({}), + hover: () => Effect.succeed(undefined), + definition: () => Effect.succeed([]), + references: () => Effect.succeed([]), + implementation: () => Effect.succeed([]), + documentSymbol: () => Effect.succeed([]), + workspaceSymbol: () => Effect.succeed([]), + prepareCallHierarchy: () => Effect.succeed([]), + incomingCalls: () => Effect.succeed([]), + outgoingCalls: () => Effect.succeed([]), + }), +) + +const root = LayerNode.group([ + SessionPrompt.node, + Session.node, + SessionProjector.node, + SessionSummary.node, + Database.node, + CrossSpawnSpawner.node, + LayerNode.make(TestLLMServer.layer, []), +]) +const it = testEffect( + LayerNode.buildLayer(root, { + replacements: [ + LayerNode.replace(MCP.node, mcp), + LayerNode.replace(LSP.node, lsp), + LayerNode.replace(RuntimeFlags.node, RuntimeFlags.layer({ experimentalEventSystem: true })), + ], + }), +) + +// An OpenAI-compatible provider served by the test LLM server. +const providerCfg = (url: string) => ({ + provider: { + "altimate-backend": { + name: "Altimate (test)", + id: "altimate-backend", + env: [], + npm: "@ai-sdk/openai-compatible", + models: { + "test-model": { + id: "test-model", + name: "Test Model", + attachment: false, + reasoning: false, + temperature: false, + tool_call: true, + release_date: "2025-01-01", + limit: { context: 100000, output: 10000 }, + cost: { input: 0, output: 0 }, + options: {}, + }, + }, + options: { apiKey: "test-key", baseURL: url }, + }, + }, + model: "altimate-backend/test-model", +}) + +type Span = { name: string; input?: { agent?: string } } + +// Records spans; every other trace method is a no-op. +function recordingTrace(spans: Span[]) { + return new Proxy( + {}, + { + get: (_, key) => (key === "logSpan" ? (span: Span) => spans.push(span) : () => undefined), + }, + ) as unknown as Tracer +} + +it.live("an agent switch inside one loop run traces the new agent's system prompt", () => + provideTmpdirServerLegacy( + Effect.fnUntraced(function* ({ llm }) { + const prompt = yield* SessionPrompt.Service + const sessions = yield* Session.Service + const session = yield* sessions.create({ + title: "system prompt per agent", + permission: [{ permission: "*", pattern: "*", action: "allow" }], + }) + const spans: Span[] = [] + Tracer.setActive(recordingTrace(spans)) + yield* Effect.addFinalizer(() => Effect.sync(() => Tracer.setActive(null))) + + let release!: () => void + const gate = new Promise((resolve) => (release = resolve)) + yield* llm.hold("first answer", gate) + yield* llm.text("second answer") + + yield* prompt.prompt({ + sessionID: session.id, + agent: "build", + noReply: true, + parts: [{ type: "text", text: "first request" }], + }) + const run = yield* prompt.loop({ sessionID: session.id }).pipe(Effect.forkChild) + // The first step has picked its agent once its request reaches the model. + yield* pollWithTimeout( + llm.hits.pipe(Effect.map((hits) => (hits.some((hit) => JSON.stringify(hit.body).includes("first request")) ? true : undefined))), + "the first step never called the model", + ) + // A request for another agent joins the running loop, as plan_exit's builder message does. + yield* prompt.prompt({ + sessionID: session.id, + agent: "plan", + noReply: true, + parts: [{ type: "text", text: "second request" }], + }) + release() + yield* Fiber.join(run) + + const traced = spans.filter((span) => span.name === "system-prompt").map((span) => span.input?.agent) + expect(traced).toEqual(["builder", "plan"]) + expect(spans.filter((span) => span.name === "bootstrap")).toHaveLength(1) + }), + { git: true, config: providerCfg }, + ), + { timeout: 30_000 }, +)