) =>
+ Cause.hasInterruptsOnly(cause)
+ ? Effect.failCause(cause as Cause.Cause)
+ : Effect.fail(new IssueLinkFailedError({ cause }));
+
+ /** A tool that changes `threadId`, or the caller's own thread when it is omitted. */
+ const writesThread = (
+ handle: (params: P) => Effect.Effect,
+ ) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle);
+
+ return {
+ list_issues: McpToolAccess.reads((input) =>
+ Effect.gen(function* () {
+ const { projectId } = yield* requireProjectScope(input.projectId);
+ const result = yield* issues.list({
+ projectId,
+ state: input.state ?? "open",
+ ...(input.query === undefined ? {} : { query: input.query }),
+ ...(input.limit === undefined ? {} : { limit: input.limit }),
+ ...(input.cursors === undefined ? {} : { cursors: input.cursors }),
+ });
+ return {
+ issues: result.entries.map((entry) => ({
+ projectId: entry.projectId,
+ tracker: entry.tracker,
+ host: entry.host,
+ scope: entry.scope,
+ key: entry.key,
+ url: entry.url,
+ displayKey: entry.displayKey,
+ title: entry.title,
+ state: entry.state,
+ author: entry.author?.login ?? null,
+ assignees: entry.assignees.map((actor) => actor.login),
+ labels: entry.labels.map((label) => label.name),
+ updatedAt: entry.updatedAt,
+ commentCount: entry.commentCount,
+ })),
+ nextCursors: result.nextCursors,
+ errors: result.errors.map((error) => ({
+ projectId: error.projectId,
+ message: error.message,
+ })),
+ };
+ }),
+ ),
+ read_issue: McpToolAccess.reads((input) =>
+ Effect.gen(function* () {
+ const target = yield* resolveTarget(input);
+ const detail = yield* issues.detail(refOf(target));
+ return {
+ ...identityOf(target),
+ url: target.url ?? detail.url,
+ displayKey: detail.displayKey,
+ title: detail.title,
+ state: detail.state,
+ writable: detail.writable,
+ capabilities: detail.capabilities,
+ states: detail.states,
+ author: detail.author?.login ?? null,
+ assignees: detail.assignees.map((actor) => actor.login),
+ labels: detail.labels.map((label) => label.name),
+ createdAt: detail.createdAt,
+ updatedAt: detail.updatedAt,
+ closedAt: detail.closedAt,
+ body: detail.body,
+ comments: detail.comments.map((comment) => ({
+ id: comment.id,
+ author: comment.author?.login ?? null,
+ body: comment.body,
+ createdAt: comment.createdAt,
+ })),
+ commentsTruncated: detail.commentsCursor !== null,
+ linkedPullRequests: detail.linkedPullRequests.map((pullRequest) => ({
+ url: pullRequest.url,
+ title: pullRequest.title,
+ state: pullRequest.state,
+ closesIssue: pullRequest.closesIssue,
+ })),
+ };
+ }),
+ ),
+ create_issue: McpToolAccess.writesWithCapability((input) =>
+ Effect.gen(function* () {
+ const scope = yield* requireProjectScope(input.projectId);
+ const created = yield* issues.create({
+ ...scope,
+ title: input.title,
+ body: input.body ?? "",
+ labels: input.labels ?? [],
+ assignees: input.assignees ?? [],
+ });
+ return {
+ ...scope,
+ key: created.key,
+ url: created.url,
+ displayKey: created.displayKey,
+ };
+ }),
+ ),
+ comment_on_issue: McpToolAccess.writesWithCapability((input) =>
+ Effect.gen(function* () {
+ const target = yield* resolveTarget(input);
+ yield* issues.comment({ ...refOf(target), body: input.body });
+ return identityOf(target);
+ }),
+ ),
+ set_issue_state: McpToolAccess.writesWithCapability((input) =>
+ Effect.gen(function* () {
+ const target = yield* resolveTarget(input);
+ yield* issues.setState({
+ ...refOf(target),
+ state: input.state,
+ });
+ return identityOf(target);
+ }),
+ ),
+ link_issue: writesThread((input) =>
+ Effect.gen(function* () {
+ const thread = yield* requireThread(input.threadId);
+ const target = yield* resolveTarget({
+ ...input,
+ projectId: input.projectId ?? thread.projectId,
+ });
+ // Reading the issue proves it exists and names it for the thread's row.
+ const detail = yield* issues.detail(refOf(target));
+ const url = target.url ?? detail.url;
+ const { alreadyLinked } = yield* threadIssues
+ .link({
+ threadId: thread.id,
+ ref: refOf(target),
+ url,
+ displayKey: detail.displayKey,
+ title: detail.title,
+ source: "agent",
+ })
+ .pipe(Effect.catchCause(linkFailure));
+ return { ...identityOf(target), url, alreadyLinked };
+ }),
+ ),
+ unlink_issue: writesThread((input) =>
+ Effect.gen(function* () {
+ const thread = yield* requireThread(input.threadId);
+ const target = yield* resolveTarget({
+ ...input,
+ projectId: input.projectId ?? thread.projectId,
+ });
+ const existing = (thread.issues ?? []).find((link) => threadIssueKeysEqual(link, target));
+ if (existing === undefined) return { ...identityOf(target), wasLinked: false };
+ const { wasLinked } = yield* threadIssues
+ .unlink({ threadId: thread.id, key: target })
+ .pipe(Effect.catchCause(linkFailure));
+ return { ...identityOf(target), url: existing.url, wasLinked };
+ }),
+ ),
+ list_thread_issues: McpToolAccess.reads((input) =>
+ requireThread(input.threadId).pipe(Effect.map(listThreadIssues)),
+ ),
+ } satisfies McpToolAccess.Handlers;
+});
+
+export const layer = McpToolAccess.toLayer(IssuesToolkit, make);
diff --git a/apps/server/src/mcp/toolkits/issues/tools.ts b/apps/server/src/mcp/toolkits/issues/tools.ts
new file mode 100644
index 0000000000000..20de86b1f9dea
--- /dev/null
+++ b/apps/server/src/mcp/toolkits/issues/tools.ts
@@ -0,0 +1,385 @@
+import {
+ IssueCapabilities,
+ IssueListState,
+ IssueOperationError,
+ IssueState,
+ IssueTrackerKind,
+ IssueUnavailableError,
+ McpCapabilityUnavailableError,
+ OrchestratorMcpFailure,
+ ProjectId,
+ ThreadId,
+ ThreadIssueLinkSource,
+ TrimmedNonEmptyString,
+} from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+import * as Tool from "effect/ai/Tool";
+import * as Toolkit from "effect/ai/Toolkit";
+
+import * as IssueService from "../../../issue/IssueService.ts";
+import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
+import * as ThreadIssueService from "../../../orchestration-v2/ThreadIssueService.ts";
+import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
+import * as ProjectService from "../../../project/ProjectService.ts";
+import * as McpInvocationContext from "../../McpInvocationContext.ts";
+
+const dependencies = [
+ McpInvocationContext.McpInvocationContext,
+ ThreadManagementService.ThreadManagementService,
+ Orchestrator.OrchestratorV2,
+ ProjectService.ProjectService,
+ IssueService.IssueService,
+ ThreadIssueService.ThreadIssueService,
+];
+
+/**
+ * Either the issue's URL, or its key within a project's tracker. A key alone is read through the
+ * project named, or the caller's own thread's project; a URL is read through whichever project
+ * here is a checkout of that repository, read-only when none is.
+ */
+export const IssueTargetInput = Schema.Struct({
+ url: Schema.optional(
+ TrimmedNonEmptyString.annotate({
+ description: "The issue's web URL. Preferred when you have it.",
+ }),
+ ),
+ key: Schema.optional(
+ TrimmedNonEmptyString.annotate({
+ description: "The issue's key in the project's tracker, such as its number.",
+ }),
+ ),
+ projectId: Schema.optional(
+ ProjectId.annotate({
+ description: "Project whose tracker holds key. Defaults to this thread's project.",
+ }),
+ ),
+});
+export type IssueTargetInput = typeof IssueTargetInput.Type;
+
+const ThreadTargetInput = Schema.Struct({
+ threadId: Schema.optional(
+ ThreadId.annotate({ description: "Thread to act on. Omit for this thread." }),
+ ),
+});
+
+export class IssueTargetIncompleteError extends Schema.TaggedError()(
+ "IssueTargetIncompleteError",
+ {},
+) {
+ override get message(): string {
+ return "Pass either url, or key (with projectId when not running inside a T3 thread).";
+ }
+}
+
+export class IssueProjectRequiredError extends Schema.TaggedError()(
+ "IssueProjectRequiredError",
+ {},
+) {
+ override get message(): string {
+ return "Pass projectId: this MCP client is not running inside a T3 thread.";
+ }
+}
+
+export class IssueThreadRequiredError extends Schema.TaggedError()(
+ "IssueThreadRequiredError",
+ {},
+) {
+ override get message(): string {
+ return "Pass threadId: this MCP client is not running inside a T3 thread.";
+ }
+}
+
+export class IssueThreadNotFoundError extends Schema.TaggedError()(
+ "IssueThreadNotFoundError",
+ { threadId: Schema.String },
+) {
+ override get message(): string {
+ return `Thread ${this.threadId} was not found.`;
+ }
+}
+
+export class IssueProjectNotFoundError extends Schema.TaggedError()(
+ "IssueProjectNotFoundError",
+ { projectId: Schema.String },
+) {
+ override get message(): string {
+ return `Project ${this.projectId} was not found or has no issue tracker.`;
+ }
+}
+
+export class IssueLinkFailedError extends Schema.TaggedError()(
+ "IssueLinkFailedError",
+ { cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return "Could not change the issue link.";
+ }
+}
+
+export const IssueToolError = Schema.Union([
+ OrchestratorMcpFailure,
+ McpCapabilityUnavailableError,
+ IssueUnavailableError,
+ IssueOperationError,
+ IssueTargetIncompleteError,
+ IssueProjectRequiredError,
+ IssueThreadRequiredError,
+ IssueThreadNotFoundError,
+ IssueProjectNotFoundError,
+ IssueLinkFailedError,
+]);
+export type IssueToolError = typeof IssueToolError.Type;
+
+/** How a tool names an issue back: enough to pass to any other issue tool. */
+const IssueKeyIdentity = {
+ projectId: ProjectId,
+ tracker: IssueTrackerKind,
+ host: Schema.String,
+ scope: Schema.String,
+ key: Schema.String,
+};
+const IssueIdentity = { ...IssueKeyIdentity, url: Schema.String };
+/** A write named by key alone never read the issue, so it has no URL to hand back. */
+const IssueIdentityAfterWrite = { ...IssueKeyIdentity, url: Schema.optional(Schema.String) };
+
+export const IssueEntry = Schema.Struct({
+ ...IssueIdentity,
+ displayKey: Schema.String,
+ title: Schema.String,
+ state: IssueState,
+ author: Schema.NullOr(Schema.String),
+ assignees: Schema.Array(Schema.String),
+ labels: Schema.Array(Schema.String),
+ updatedAt: Schema.String,
+ commentCount: Schema.Int,
+});
+export type IssueEntry = typeof IssueEntry.Type;
+
+export const ListIssuesResult = Schema.Struct({
+ issues: Schema.Array(IssueEntry),
+ /** Pass back as `cursors` to read the next slice of each scope that has one. */
+ nextCursors: Schema.Record(Schema.String, Schema.String),
+ errors: Schema.Array(Schema.Struct({ projectId: ProjectId, message: Schema.String })),
+});
+export type ListIssuesResult = typeof ListIssuesResult.Type;
+
+export const ReadIssueResult = Schema.Struct({
+ ...IssueIdentity,
+ displayKey: Schema.String,
+ title: Schema.String,
+ state: IssueState,
+ /** False for an issue outside every project's own scope: it can be read, not changed. */
+ writable: Schema.Boolean,
+ capabilities: IssueCapabilities,
+ states: Schema.Array(IssueState),
+ author: Schema.NullOr(Schema.String),
+ assignees: Schema.Array(Schema.String),
+ labels: Schema.Array(Schema.String),
+ createdAt: Schema.String,
+ updatedAt: Schema.String,
+ closedAt: Schema.NullOr(Schema.String),
+ body: Schema.String,
+ comments: Schema.Array(
+ Schema.Struct({
+ id: Schema.String,
+ author: Schema.NullOr(Schema.String),
+ body: Schema.String,
+ createdAt: Schema.String,
+ }),
+ ),
+ /** Older comments exist beyond the page returned. */
+ commentsTruncated: Schema.Boolean,
+ linkedPullRequests: Schema.Array(
+ Schema.Struct({
+ url: Schema.String,
+ title: Schema.String,
+ state: Schema.String,
+ closesIssue: Schema.Boolean,
+ }),
+ ),
+});
+export type ReadIssueResult = typeof ReadIssueResult.Type;
+
+export const CreateIssueResult = Schema.Struct({
+ ...IssueIdentity,
+ displayKey: Schema.String,
+});
+export type CreateIssueResult = typeof CreateIssueResult.Type;
+
+export const IssueWriteResult = Schema.Struct({ ...IssueIdentityAfterWrite });
+
+export const ThreadIssueEntry = Schema.Struct({
+ ...IssueIdentity,
+ source: ThreadIssueLinkSource,
+ /** As the tracker named the issue when it was linked; `read_issue` has its current state. */
+ displayKey: Schema.String,
+ title: Schema.String,
+});
+export type ThreadIssueEntry = typeof ThreadIssueEntry.Type;
+
+export const LinkIssueResult = Schema.Struct({
+ ...IssueIdentity,
+ alreadyLinked: Schema.Boolean.annotate({
+ description: "True when the issue was linked to this thread before the call.",
+ }),
+});
+export type LinkIssueResult = typeof LinkIssueResult.Type;
+
+export const UnlinkIssueResult = Schema.Struct({
+ ...IssueIdentityAfterWrite,
+ wasLinked: Schema.Boolean.annotate({
+ description: "False when the issue was not linked to this thread to begin with.",
+ }),
+});
+export type UnlinkIssueResult = typeof UnlinkIssueResult.Type;
+
+export const ListThreadIssuesResult = Schema.Struct({
+ issues: Schema.Array(ThreadIssueEntry),
+});
+export type ListThreadIssuesResult = typeof ListThreadIssuesResult.Type;
+
+const ListIssuesTool = Tool.make("list_issues", {
+ description:
+ "List issues in a project's tracker, newest updated first. Pass the returned nextCursors as cursors for the next page.",
+ parameters: Schema.Struct({
+ projectId: Schema.optional(
+ ProjectId.annotate({ description: "Defaults to this thread's project." }),
+ ),
+ state: Schema.optional(IssueListState.annotate({ description: "Defaults to open." })),
+ query: Schema.optional(
+ TrimmedNonEmptyString.check(Schema.isMaxLength(200)).annotate({
+ description: "Free text the tracker matches itself.",
+ }),
+ ),
+ limit: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))),
+ cursors: Schema.optional(Schema.Record(Schema.String, Schema.String)),
+ }),
+ success: ListIssuesResult,
+ failure: IssueToolError,
+ dependencies,
+})
+ .annotate(Tool.Title, "List issues")
+ .annotate(Tool.Readonly, true)
+ .annotate(Tool.Destructive, false)
+ .annotate(Tool.Idempotent, true)
+ .annotate(Tool.OpenWorld, true);
+
+const ReadIssueTool = Tool.make("read_issue", {
+ description:
+ "Read an issue: body, state, labels, assignees, recent comments and linked pull requests. Pass its url, or its key.",
+ parameters: IssueTargetInput,
+ success: ReadIssueResult,
+ failure: IssueToolError,
+ dependencies,
+})
+ .annotate(Tool.Title, "Read issue")
+ .annotate(Tool.Readonly, true)
+ .annotate(Tool.Destructive, false)
+ .annotate(Tool.Idempotent, true)
+ .annotate(Tool.OpenWorld, true);
+
+const CreateIssueTool = Tool.make("create_issue", {
+ description: "File an issue in a project's tracker.",
+ parameters: Schema.Struct({
+ projectId: Schema.optional(
+ ProjectId.annotate({ description: "Defaults to this thread's project." }),
+ ),
+ title: TrimmedNonEmptyString.check(Schema.isMaxLength(1024)),
+ body: Schema.optional(Schema.String.check(Schema.isMaxLength(65_536))),
+ labels: Schema.optional(Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(50))),
+ assignees: Schema.optional(Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(25))),
+ }),
+ success: CreateIssueResult,
+ failure: IssueToolError,
+ dependencies,
+})
+ .annotate(Tool.Title, "Create issue")
+ .annotate(Tool.Readonly, false)
+ .annotate(Tool.Destructive, false)
+ .annotate(Tool.Idempotent, false)
+ .annotate(Tool.OpenWorld, true);
+
+const CommentOnIssueTool = Tool.make("comment_on_issue", {
+ description: "Post a comment on an issue.",
+ parameters: Schema.Struct({
+ ...IssueTargetInput.fields,
+ body: Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536)),
+ }),
+ success: IssueWriteResult,
+ failure: IssueToolError,
+ dependencies,
+})
+ .annotate(Tool.Title, "Comment on issue")
+ .annotate(Tool.Readonly, false)
+ .annotate(Tool.Destructive, false)
+ .annotate(Tool.Idempotent, false)
+ .annotate(Tool.OpenWorld, true);
+
+const SetIssueStateTool = Tool.make("set_issue_state", {
+ description: "Move an issue to one of its states. read_issue lists them under states.",
+ parameters: Schema.Struct({
+ ...IssueTargetInput.fields,
+ state: TrimmedNonEmptyString.annotate({
+ description: "A state name from read_issue's states.",
+ }),
+ }),
+ success: IssueWriteResult,
+ failure: IssueToolError,
+ dependencies,
+})
+ .annotate(Tool.Title, "Set issue state")
+ .annotate(Tool.Readonly, false)
+ .annotate(Tool.Destructive, false)
+ .annotate(Tool.Idempotent, true)
+ .annotate(Tool.OpenWorld, true);
+
+const LinkIssueTool = Tool.make("link_issue", {
+ description:
+ "Link an issue to a thread so T3 Code shows it beside the thread. Link every issue you work on or file.",
+ parameters: Schema.Struct({ ...IssueTargetInput.fields, ...ThreadTargetInput.fields }),
+ success: LinkIssueResult,
+ failure: IssueToolError,
+ dependencies,
+})
+ .annotate(Tool.Title, "Link issue to thread")
+ .annotate(Tool.Readonly, false)
+ .annotate(Tool.Destructive, false)
+ .annotate(Tool.Idempotent, true)
+ .annotate(Tool.OpenWorld, false);
+
+const UnlinkIssueTool = Tool.make("unlink_issue", {
+ description: "Remove an issue link from a thread. The issue itself is not changed.",
+ parameters: Schema.Struct({ ...IssueTargetInput.fields, ...ThreadTargetInput.fields }),
+ success: UnlinkIssueResult,
+ failure: IssueToolError,
+ dependencies,
+})
+ .annotate(Tool.Title, "Unlink issue from thread")
+ .annotate(Tool.Readonly, false)
+ .annotate(Tool.Destructive, true)
+ .annotate(Tool.Idempotent, true)
+ .annotate(Tool.OpenWorld, false);
+
+const ListThreadIssuesTool = Tool.make("list_thread_issues", {
+ description: "List the issues linked to a thread.",
+ parameters: ThreadTargetInput,
+ success: ListThreadIssuesResult,
+ failure: IssueToolError,
+ dependencies,
+})
+ .annotate(Tool.Title, "List thread issues")
+ .annotate(Tool.Readonly, true)
+ .annotate(Tool.Destructive, false)
+ .annotate(Tool.Idempotent, true)
+ .annotate(Tool.OpenWorld, false);
+
+export const IssuesToolkit = Toolkit.make(
+ ListIssuesTool,
+ ReadIssueTool,
+ CreateIssueTool,
+ CommentOnIssueTool,
+ SetIssueStateTool,
+ LinkIssueTool,
+ UnlinkIssueTool,
+ ListThreadIssuesTool,
+);
diff --git a/apps/server/src/mcp/toolkits/registry.ts b/apps/server/src/mcp/toolkits/registry.ts
index 42cbb58c95696..ef98fc2293410 100644
--- a/apps/server/src/mcp/toolkits/registry.ts
+++ b/apps/server/src/mcp/toolkits/registry.ts
@@ -8,6 +8,7 @@ import { AttachmentToolkit } from "./attachment/tools.ts";
import { DeviceToolkit } from "./device/tools.ts";
import { EnvironmentToolkit } from "./environment/tools.ts";
import { HtmlToolkit } from "./html/tools.ts";
+import { IssuesToolkit } from "./issues/tools.ts";
import { KitshnToolkit } from "./kitshn/tools.ts";
import { MachineMapToolkit } from "./machineMap/tools.ts";
import { MessageToolkit } from "./message/tools.ts";
@@ -56,6 +57,7 @@ export const McpToolkits = {
previewControls: PreviewControlsToolkit,
device: DeviceToolkit,
pullRequests: PullRequestsToolkit,
+ issues: IssuesToolkit,
html: HtmlToolkit,
message: MessageToolkit,
// Fork: the machine tools on kitshn (MM-801).
diff --git a/apps/server/src/observability/Metrics.ts b/apps/server/src/observability/Metrics.ts
index 76561d735b021..bdf64da9511c4 100644
--- a/apps/server/src/observability/Metrics.ts
+++ b/apps/server/src/observability/Metrics.ts
@@ -35,6 +35,17 @@ export const orchestrationEffectQueueWait = Metric.timer("t3_orchestration_effec
"Time from an orchestration effect's temporal availability until claim, including same-thread blocking.",
});
+// A failed batch (transport errors and 408/429/500/502/503/504 after 3 retries) is dropped with
+// every push for the next 60 s, logged only at Debug. Incremental exports it as a monotonic counter.
+export const otlpExportAttemptFailuresTotal = Metric.counter(
+ "t3_otlp_export_attempt_failures_total",
+ {
+ description:
+ "Failed OTLP export attempts by signal and reason. Retries count too, so a dropped batch counts up to four.",
+ incremental: true,
+ },
+);
+
export const providerSessionsTotal = Metric.counter("t3_provider_sessions_total", {
description: "Total provider session lifecycle operations.",
});
diff --git a/apps/server/src/observability/Observability.ts b/apps/server/src/observability/Observability.ts
index 166d8ac194a8c..1b0414e43b8a3 100644
--- a/apps/server/src/observability/Observability.ts
+++ b/apps/server/src/observability/Observability.ts
@@ -17,6 +17,7 @@ import * as ResourceAttribution from "../resourceTelemetry/ResourceAttribution.t
import * as ServerLogger from "../serverLogger.ts";
import * as BrowserTraceCollector from "./BrowserTraceCollector.ts";
import * as HeapAttribution from "./HeapAttribution.ts";
+import * as OtlpExportFailures from "./OtlpExportFailures.ts";
export const layer = Layer.unwrap(
Effect.gen(function* () {
@@ -61,7 +62,7 @@ export const layer = Layer.unwrap(
exportInterval: `${traces.exportIntervalMs} millis`,
headers: traces.headers,
resource,
- });
+ }).pipe(Effect.provide(OtlpExportFailures.layer("traces")));
const tracer = yield* makeLocalFileTracer({
filePath: config.serverTracePath,
@@ -90,7 +91,10 @@ export const layer = Layer.unwrap(
exportInterval: `${metrics.exportIntervalMs} millis`,
headers: metrics.headers,
resource,
- }).pipe(Layer.provide(SharedObservability.layerOtlpSerialization(metrics.protocol)));
+ }).pipe(
+ Layer.provide(OtlpExportFailures.layer("metrics")),
+ Layer.provide(SharedObservability.layerOtlpSerialization(metrics.protocol)),
+ );
const layerOtelWarnings = Layer.effectDiscard(
Effect.forEach(config.otelEnvironment.warnings, (warning) => Effect.logWarning(warning)),
diff --git a/apps/server/src/observability/OtlpExportFailures.test.ts b/apps/server/src/observability/OtlpExportFailures.test.ts
new file mode 100644
index 0000000000000..5481c0996a785
--- /dev/null
+++ b/apps/server/src/observability/OtlpExportFailures.test.ts
@@ -0,0 +1,78 @@
+import { assert, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Metric from "effect/Metric";
+import {
+ HttpBody,
+ HttpClient,
+ HttpClientError,
+ HttpClientRequest,
+ HttpClientResponse,
+} from "effect/http";
+import { OtlpSerialization } from "effect/observability";
+import { describe } from "vite-plus/test";
+
+import { otlpExportAttemptFailuresTotal } from "./Metrics.ts";
+import * as OtlpExportFailures from "./OtlpExportFailures.ts";
+
+const failures = (reason: string) =>
+ Metric.value(
+ Metric.withAttributes(otlpExportAttemptFailuresTotal, { signal: "logs", reason }),
+ ).pipe(Effect.map((state) => state.count));
+
+describe("OtlpExportFailures", () => {
+ it.effect("counts each failed attempt by reason and leaves successes alone", () => {
+ const outcomes: Array = [503, "transport", 200];
+ const client = HttpClient.make((request) => {
+ const outcome = outcomes.shift() ?? 200;
+ return outcome === "transport"
+ ? Effect.fail(
+ new HttpClientError.HttpClientError({
+ reason: new HttpClientError.TransportError({ request }),
+ }),
+ )
+ : Effect.succeed(
+ HttpClientResponse.fromWeb(request, new Response(null, { status: outcome })),
+ );
+ });
+ const serialization = OtlpSerialization.OtlpSerialization.of({
+ traces: () => HttpBody.empty,
+ metrics: () => HttpBody.empty,
+ logs: () => {
+ throw new Error("unencodable attribute");
+ },
+ });
+ const layer = OtlpExportFailures.layer("logs").pipe(
+ Layer.provide(Layer.succeed(HttpClient.HttpClient, client)),
+ Layer.provide(Layer.succeed(OtlpSerialization.OtlpSerialization, serialization)),
+ );
+
+ return Effect.gen(function* () {
+ const counted = yield* HttpClient.HttpClient;
+ const encode = yield* OtlpSerialization.OtlpSerialization;
+ const request = HttpClientRequest.post("http://localhost:4318/v1/logs");
+ yield* counted.execute(request);
+ yield* Effect.flip(counted.execute(request));
+ yield* counted.execute(request);
+ assert.throws(() => encode.logs({ resourceLogs: [] }), "unencodable attribute");
+
+ const transport = yield* Metric.value(
+ Metric.withAttributes(otlpExportAttemptFailuresTotal, {
+ signal: "logs",
+ reason: "transport",
+ }),
+ );
+ // OTLP marks the sum monotonic only for an incremental counter.
+ assert.isTrue(transport.incremental);
+ assert.deepStrictEqual(
+ [
+ yield* failures("status_503"),
+ yield* failures("transport"),
+ yield* failures("encode"),
+ yield* failures("status_200"),
+ ],
+ [1, 1, 1, 0],
+ );
+ }).pipe(Effect.provide(layer), Effect.provideService(Metric.MetricRegistry, new Map()));
+ });
+});
diff --git a/apps/server/src/observability/OtlpExportFailures.ts b/apps/server/src/observability/OtlpExportFailures.ts
new file mode 100644
index 0000000000000..db9d089f1aecd
--- /dev/null
+++ b/apps/server/src/observability/OtlpExportFailures.ts
@@ -0,0 +1,54 @@
+import type { OtlpSignal } from "@t3tools/contracts";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Metric from "effect/Metric";
+import { HttpClient } from "effect/http";
+import type { HttpBody } from "effect/http";
+import { OtlpSerialization } from "effect/observability";
+
+import { otlpExportAttemptFailuresTotal } from "./Metrics.ts";
+
+/**
+ * Re-provides the HttpClient and OtlpSerialization one OTLP exporter uses, counting its failed
+ * attempts on the metrics channel. The exporter applies `filterStatusOk` and its retries outside
+ * this client, so a non-2xx arrives here as a response and each retry is counted.
+ */
+export const layer = (signal: OtlpSignal) =>
+ Layer.effectContext(
+ Effect.gen(function* () {
+ const context = yield* Effect.context();
+ const client = yield* HttpClient.HttpClient;
+ const serialization = yield* OtlpSerialization.OtlpSerialization;
+ const failures = (reason: string) =>
+ Metric.withAttributes(otlpExportAttemptFailuresTotal, { signal, reason });
+ // Encoding runs synchronously inside the exporter, before any request exists.
+ const counted =
+ (encode: (data: A) => HttpBody.HttpBody) =>
+ (data: A) => {
+ try {
+ return encode(data);
+ } catch (error) {
+ failures("encode").updateUnsafe(1, context);
+ throw error;
+ }
+ };
+ return Context.make(
+ HttpClient.HttpClient,
+ client.pipe(
+ HttpClient.tap((response) =>
+ response.status >= 200 && response.status < 300
+ ? Effect.void
+ : Metric.update(failures(`status_${response.status}`), 1),
+ ),
+ HttpClient.tapError(() => Metric.update(failures("transport"), 1)),
+ ),
+ ).pipe(
+ Context.add(OtlpSerialization.OtlpSerialization, {
+ traces: counted(serialization.traces),
+ metrics: counted(serialization.metrics),
+ logs: counted(serialization.logs),
+ }),
+ );
+ }),
+ );
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index 849f38dc5720d..d4a0d7ac77756 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -144,6 +144,19 @@ const RPC_AGGREGATES = {
[WS_METHODS.pullRequestsRequestReviewers]: "pull-requests",
[WS_METHODS.pullRequestsLabelCandidates]: "pull-requests",
[WS_METHODS.pullRequestsSetLabels]: "pull-requests",
+ [WS_METHODS.issuesList]: "issues",
+ [WS_METHODS.issuesDetail]: "issues",
+ [WS_METHODS.issuesComments]: "issues",
+ [WS_METHODS.issuesTemplates]: "issues",
+ [WS_METHODS.issuesCandidates]: "issues",
+ [WS_METHODS.issuesCreate]: "issues",
+ [WS_METHODS.issuesComment]: "issues",
+ [WS_METHODS.issuesUpdate]: "issues",
+ [WS_METHODS.issuesSetState]: "issues",
+ [WS_METHODS.issuesReact]: "issues",
+ [WS_METHODS.issueTrackersList]: "issues",
+ [WS_METHODS.issueTrackersConnect]: "issues",
+ [WS_METHODS.issueTrackersBindProject]: "issues",
[WS_METHODS.sourceControlLookupRepository]: "source-control",
[WS_METHODS.sourceControlCloneRepository]: "source-control",
[WS_METHODS.sourceControlPublishRepository]: "source-control",
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
index 863f2279ef2a3..52123f19ef059 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
@@ -11,6 +11,7 @@ import { AcpRegistryCatalog } from "@t3tools/provider-acp-registry/server/AcpReg
import { decodeAcpReplayTranscript, makeAcpReplayRuntime } from "./AcpAdapterV2.testkit.ts";
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
+import * as NodeHttp from "node:http";
import * as NodePath from "node:path";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
@@ -103,6 +104,7 @@ import {
const DEFAULT_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({});
const DROID_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({ agentId: "factory-droid" });
+const DEVIN_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({ agentId: "devin" });
const OMP_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({
source: "local",
commandPath: "/usr/local/bin/omp",
@@ -2037,6 +2039,39 @@ describe("AcpAdapterV2", () => {
answers: { q0: "blue" },
result: { action: "accept", content: { q0: "blue" } },
},
+ {
+ scenario: "Devin allowOther choice accepts a typed answer",
+ settings: DEVIN_SETTINGS,
+ meta: { "cognition.ai/allowOther": true },
+ schema: {
+ type: "object",
+ properties: {
+ q0: {
+ type: "string",
+ title: "Fruit",
+ description: "Which fruit?",
+ oneOf: [
+ { const: "Apple", title: "Apple" },
+ { const: "Banana", title: "Banana" },
+ ],
+ },
+ },
+ required: ["q0"],
+ },
+ questions: [
+ {
+ id: "q0",
+ header: "Fruit",
+ question: "Which fruit?",
+ options: [
+ { label: "Apple", description: "Apple", value: "Apple" },
+ { label: "Banana", description: "Banana", value: "Banana" },
+ ],
+ },
+ ],
+ answers: { q0: "Mango" },
+ result: { action: "accept", content: { q0: "Mango" } },
+ },
])("Registry elicitation $scenario", (fixture) => {
const { schema, questions, answers, result } = fixture;
const withAttachments = "withAttachments" in fixture && fixture.withAttachments;
@@ -2120,6 +2155,7 @@ describe("AcpAdapterV2", () => {
sessionId: "droid-session",
message: "Your answer?",
requestedSchema: schema,
+ ...("meta" in fixture ? { _meta: fixture.meta } : {}),
},
},
},
@@ -5796,6 +5832,128 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest)),
);
+ it.live("Stop closes an MCP-over-ACP call stalled on its SSE response", () =>
+ Effect.gen(function* () {
+ const responseStarted = yield* Deferred.make();
+ const responseClosed = yield* Deferred.make();
+ const server = yield* Effect.acquireRelease(
+ Effect.promise(
+ () =>
+ new Promise((resolve) => {
+ const server = NodeHttp.createServer((_request, response) => {
+ response.on("close", () => Deferred.doneUnsafe(responseClosed, Effect.void));
+ response.writeHead(200, { "content-type": "text/event-stream" });
+ response.write('data: {"jsonrpc":"2.0","method":"notifications/progress"}\n\n');
+ Deferred.doneUnsafe(responseStarted, Effect.void);
+ });
+ server.listen(0, "127.0.0.1", () => resolve(server));
+ }),
+ ),
+ (server) =>
+ Effect.sync(() => {
+ server.closeAllConnections();
+ server.close();
+ }),
+ );
+ const address = server.address();
+ if (address === null || typeof address === "string") {
+ return yield* Effect.die("Expected a TCP address");
+ }
+ type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
+ let mcpConnect: Parameters[0] | undefined;
+ let mcpMessage: Parameters[0] | undefined;
+ const instanceId = ProviderInstanceId.make("acp-test-stop-mcp-call");
+ const threadId = ThreadId.make("thread-acp-stop-mcp-call");
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
+ yield* (yield* McpProviderSessions.McpProviderSessions).set({
+ environmentId: EnvironmentId.make("environment-acp-stop-mcp-call"),
+ threadId,
+ providerSessionId: "mcp-session-acp-stop-mcp-call",
+ providerInstanceId: instanceId,
+ endpoint: `http://127.0.0.1:${address.port}/mcp`,
+ authorizationHeader: "Bearer stop-mcp-call-token",
+ browserToolsAvailable: false,
+ });
+ const adapter = yield* makeAcpAdapterV2({
+ instanceId,
+ flavor: {
+ driver: ACP_TEST_DRIVER,
+ capabilities: AcpProviderCapabilitiesV2,
+ interruptPromptOnCancel: true,
+ makeRuntime: makeMockRuntime({
+ childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
+ mockAgentPath: yield* bundledMockAgentPath,
+ environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" },
+ wrapRuntime: (runtime) => ({
+ ...runtime,
+ handleMcpConnect: (handler) =>
+ Effect.sync(() => {
+ mcpConnect = handler;
+ }).pipe(Effect.andThen(runtime.handleMcpConnect(handler))),
+ handleMcpMessage: (handler) =>
+ Effect.sync(() => {
+ mcpMessage = handler;
+ }).pipe(Effect.andThen(runtime.handleMcpMessage(handler))),
+ }),
+ }),
+ },
+ selfInvocation: yield* resolveSelfInvocation(),
+ clientTerminals: {},
+ });
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd: process.cwd(),
+ });
+ const modelSelection = { instanceId, model: "default" } as const;
+ const runtime = yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("provider-session-acp-stop-mcp-call"),
+ modelSelection,
+ runtimePolicy,
+ });
+ const providerThread = yield* runtime.ensureThread({
+ threadId,
+ modelSelection,
+ runtimePolicy,
+ });
+ const turnFiber = yield* runtime
+ .startTurn(
+ makeTurnInput({
+ threadId,
+ providerThread,
+ instanceId,
+ runtimePolicy,
+ now: yield* DateTime.now,
+ }),
+ )
+ .pipe(Effect.forkScoped);
+ if (mcpConnect === undefined || mcpMessage === undefined) {
+ return yield* Effect.die("ACP runtime must register MCP-over-ACP handlers");
+ }
+ const { connectionId } = yield* mcpConnect(
+ { serverId: "t3-code" },
+ { requestId: "stop-mcp-connect", method: "mcp/connect" },
+ );
+ const call = yield* mcpMessage(
+ { connectionId, method: "tools/call", params: { name: "task_status", arguments: {} } },
+ { requestId: "stop-mcp-call", method: "mcp/message" },
+ ).pipe(Effect.exit, Effect.forkScoped);
+ yield* Deferred.await(responseStarted);
+
+ yield* runtime.interruptTurn({
+ providerThread,
+ providerTurnId: idAllocator.derive.providerTurn({
+ driver: ACP_TEST_DRIVER,
+ nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
+ }),
+ });
+ assert.isTrue(Exit.isFailure(yield* Fiber.join(call)));
+ yield* Deferred.await(responseClosed);
+ yield* Fiber.join(turnFiber);
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.effect.each([
{
label: "grants an ID-only execute approval its tracked command",
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index baa15a7f92d6b..9a0ed2daa823a 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -8973,6 +8973,20 @@ describe("ClaudeAdapterV2 background wake turns", () => {
targetThreadId: ThreadId.make("thread-claude-fork-after-compact-rollback"),
});
assert.equal(forkCalls[0]?.options.upToMessageId, earlierCursor);
+ // A running later turn writes past the head, so the head cannot bound a fork.
+ const busyForkError = yield* harness.runtime
+ .forkThread({
+ sourceProviderThread: pastSilentTurn.providerThread,
+ sourceProviderTurns: [
+ ...turnsAcrossSilent.slice(0, 2),
+ { ...turnsAcrossSilent[2]!, status: "running", completedAt: null },
+ ],
+ providerTurnId: providerTurn.id,
+ targetThreadId: ThreadId.make("thread-claude-fork-while-source-runs"),
+ })
+ .pipe(Effect.flip);
+ assert.instanceOf(busyForkError, ProviderAdapter.ProviderAdapterForkThreadError);
+ assert.equal(forkCalls.length, 1);
const interruptedBeforeCompact = yield* rollbackTo(
[
{
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index e24d84f4afbf2..070bab0257116 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -525,6 +525,7 @@ export const ClaudeProviderCapabilitiesV2 = {
canRollbackThread: true,
canForkThread: true,
canForkFromTurn: true,
+ canForkWhileSourceRunning: true,
canForkFromSubagentThread: false,
exposesNativeThreadId: true,
},
@@ -1454,490 +1455,486 @@ export const layerQueryRunner: Layer.Layer<
return { refresh: refresh(true).pipe(Effect.asVoid), stop };
};
- return ClaudeAgentSdkQueryRunner.of({
- allocateSessionId: random.uuidV4(),
- open: Effect.fn("ClaudeAgentSdkQueryRunner.open")(
- function* (input: ClaudeAgentSdkQueryOpenInput) {
- const protocolLogger = makeClaudeAgentSdkProtocolLogger({
- nativeEventLogger,
- threadId: input.threadId,
- providerSessionId: input.providerSessionId,
+ // The open span below is the tracing boundary for both attempts.
+ const openQuery = Effect.fnUntraced(function* (input: ClaudeAgentSdkQueryOpenInput) {
+ const protocolLogger = makeClaudeAgentSdkProtocolLogger({
+ nativeEventLogger,
+ threadId: input.threadId,
+ providerSessionId: input.providerSessionId,
+ });
+ const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
+ protocolLogger === undefined ? Effect.void : protocolLogger(event);
+ // A failed open shuts down its queue before retrying, so the old CLI cannot take the prompt.
+ const promptQueue = yield* Queue.unbounded();
+ const prompt = Stream.fromQueue(promptQueue).pipe(
+ Stream.catchCause((cause) =>
+ Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
+ ),
+ Stream.toAsyncIterable,
+ );
+ // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments.
+ const { mcpServers, ...sdkOptions } = input.options;
+ // Jobs the agent starts inherit the thread, so port discovery can attribute their servers.
+ let resumeSessionAt = sdkOptions.resumeSessionAt;
+ if (input.resume && sdkOptions.resume !== undefined) {
+ const messages = yield* runClaudeWorker({
+ method: "getSessionMessages",
+ sessionId: sdkOptions.resume,
+ options: sdkOptions.cwd === undefined ? {} : { dir: sdkOptions.cwd },
+ environment: sdkOptions.env ?? hostEnvironment,
+ }).pipe(
+ Effect.flatMap(decodeClaudeHistoryMessages),
+ Effect.mapError((cause) => queryRunnerError(cause, "getSessionMessages")),
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
+ Effect.provideService(Path.Path, path),
+ );
+ const boundary =
+ resumeSessionAt === undefined
+ ? messages.length
+ : messages.findIndex((message) => message.uuid === resumeSessionAt) + 1;
+ resumeSessionAt = claudeResumeSessionAt(messages.slice(0, boundary)) ?? resumeSessionAt;
+ }
+ const queryOptions = {
+ ...sdkOptions,
+ ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }),
+ env: {
+ ...(sdkOptions.env ?? hostEnvironment),
+ ...(input.resume
+ ? {
+ CLAUDE_CODE_RESUME_INTERRUPTED_TURN: "1",
+ CLAUDE_CODE_RESUME_REASON: "user_resume",
+ }
+ : {}),
+ [PortScanner.AGENT_THREAD_ENV]: input.threadId,
+ },
+ };
+ // The SDK can prepend a scope wrapper to native binaries; script entries run through node.
+ const binaryPath = queryOptions.pathToClaudeCodeExecutable;
+ const launch =
+ binaryPath === undefined || CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext))
+ ? undefined
+ : yield* agentScope.wrap({
+ command: binaryPath,
+ args: [],
+ name: "claude",
+ threadId: input.threadId,
+ env: queryOptions.env,
+ });
+ const options =
+ launch === undefined || launch.args.length === 0
+ ? queryOptions
+ : {
+ ...queryOptions,
+ pathToClaudeCodeExecutable: launch.command,
+ executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])],
+ };
+ const unit = launch?.unit;
+ const stopScope = unit === undefined ? undefined : () => void runFork(agentScope.stop(unit));
+ // Only a CLI that fails before its first message explains itself on
+ // stderr. The known root refusal becomes a curated failure; any other
+ // stderr can hold private text, so it stays out of turn failures.
+ let stderrTail = "";
+ let stderrClosed: Promise = Promise.resolve();
+ let answered = false;
+ let conversationMissing = false;
+ const appendStderr = (text: string) => {
+ if (answered) return;
+ stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH);
+ };
+ let refreshDescendants: Effect.Effect = Effect.void;
+ const spawnProcess =
+ options.spawnClaudeCodeProcess ??
+ ((spawnOptions: ClaudeSpawnOptions) => {
+ if (platform !== "win32") {
+ // Node can report "exit" before it has read the stderr the CLI wrote.
+ let stderrDone = () => {};
+ stderrClosed = new Promise((resolve) => (stderrDone = resolve));
+ const child = spawnClaudeProcessGroup(
+ spawnOptions,
+ stopScope,
+ appendStderr,
+ stderrDone,
+ providerProcesses.register,
+ );
+ if (unit === undefined && child.pid !== undefined) {
+ const tracker = trackDescendants(child.pid);
+ const polling = runFork(
+ tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))),
+ );
+ child.once("exit", () =>
+ runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))),
+ );
+ refreshDescendants = tracker.refresh;
+ }
+ return child;
+ }
+ const child = SpawnWorker.spawnPiped(spawnOptions.command, spawnOptions.args, {
+ cwd: spawnOptions.cwd,
+ env: spawnOptions.env,
+ signal: spawnOptions.signal,
+ windowsHide: true,
});
- const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
- protocolLogger === undefined ? Effect.void : protocolLogger(event);
- // A failed open shuts down its queue before retrying, so the old CLI cannot take the prompt.
- const promptQueue = yield* Queue.unbounded();
- const prompt = Stream.fromQueue(promptQueue).pipe(
- Stream.catchCause((cause) =>
- Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
+ child.stderr.setEncoding("utf8").on("data", (chunk: string) => options.stderr?.(chunk));
+ return child;
+ });
+ let spawnedProcess: ClaudeSpawnedProcess | undefined;
+ let processExited = false;
+ let processExit: Promise | undefined;
+ const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => {
+ const child = spawnProcess(spawnOptions);
+ spawnedProcess = child;
+ // A spawn that fails emits only "error".
+ const releaseAgent = portDiscovery.trackAgent();
+ child.once("exit", releaseAgent);
+ child.on("error", releaseAgent);
+ processExited = child.exitCode !== null || child.signalCode != null;
+ processExit = new Promise((resolve) => {
+ if (processExited) resolve();
+ else
+ child.once("exit", () => {
+ processExited = true;
+ resolve();
+ });
+ });
+ return child;
+ };
+ const queryRuntime = yield* Effect.uninterruptibleMask((restore) =>
+ Effect.try({
+ try: () =>
+ withoutClaudeCanUseToolShadowedWarning(() =>
+ query({
+ prompt,
+ options: { ...options, spawnClaudeCodeProcess },
+ }),
),
- Stream.toAsyncIterable,
- );
- // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments.
- const { mcpServers, ...sdkOptions } = input.options;
- // Jobs the agent starts inherit the thread, so port discovery can attribute their servers.
- let resumeSessionAt = sdkOptions.resumeSessionAt;
- if (input.resume && sdkOptions.resume !== undefined) {
- const messages = yield* runClaudeWorker({
- method: "getSessionMessages",
- sessionId: sdkOptions.resume,
- options: sdkOptions.cwd === undefined ? {} : { dir: sdkOptions.cwd },
- environment: sdkOptions.env ?? hostEnvironment,
- }).pipe(
- Effect.flatMap(decodeClaudeHistoryMessages),
- Effect.mapError((cause) => queryRunnerError(cause, "getSessionMessages")),
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
- Effect.provideService(Path.Path, path),
- );
- const boundary =
- resumeSessionAt === undefined
- ? messages.length
- : messages.findIndex((message) => message.uuid === resumeSessionAt) + 1;
- resumeSessionAt = claudeResumeSessionAt(messages.slice(0, boundary)) ?? resumeSessionAt;
- }
- const queryOptions = {
- ...sdkOptions,
- ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }),
- env: {
- ...(sdkOptions.env ?? hostEnvironment),
- ...(input.resume
- ? {
- CLAUDE_CODE_RESUME_INTERRUPTED_TURN: "1",
- CLAUDE_CODE_RESUME_REASON: "user_resume",
- }
- : {}),
- [PortScanner.AGENT_THREAD_ENV]: input.threadId,
- },
- };
- // The SDK can prepend a scope wrapper to native binaries; script entries run through node.
- const binaryPath = queryOptions.pathToClaudeCodeExecutable;
- const launch =
- binaryPath === undefined ||
- CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext))
- ? undefined
- : yield* agentScope.wrap({
- command: binaryPath,
- args: [],
- name: "claude",
- threadId: input.threadId,
- env: queryOptions.env,
- });
- const options =
- launch === undefined || launch.args.length === 0
- ? queryOptions
- : {
- ...queryOptions,
- pathToClaudeCodeExecutable: launch.command,
- executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])],
- };
- const unit = launch?.unit;
- const stopScope =
- unit === undefined ? undefined : () => void runFork(agentScope.stop(unit));
- // Only a CLI that fails before its first message explains itself on
- // stderr. The known root refusal becomes a curated failure; any other
- // stderr can hold private text, so it stays out of turn failures.
- let stderrTail = "";
- let stderrClosed: Promise = Promise.resolve();
- let answered = false;
- let conversationMissing = false;
- const appendStderr = (text: string) => {
- if (answered) return;
- stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH);
- };
- let refreshDescendants: Effect.Effect = Effect.void;
- const spawnProcess =
- options.spawnClaudeCodeProcess ??
- ((spawnOptions: ClaudeSpawnOptions) => {
- if (platform !== "win32") {
- // Node can report "exit" before it has read the stderr the CLI wrote.
- let stderrDone = () => {};
- stderrClosed = new Promise((resolve) => (stderrDone = resolve));
- const child = spawnClaudeProcessGroup(
- spawnOptions,
- stopScope,
- appendStderr,
- stderrDone,
- providerProcesses.register,
- );
- if (unit === undefined && child.pid !== undefined) {
- const tracker = trackDescendants(child.pid);
- const polling = runFork(
- tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))),
+ catch: (cause) => queryRunnerError(cause, "query"),
+ }).pipe(
+ Effect.tap((queryRuntime) =>
+ restore(
+ Effect.gen(function* () {
+ if (mcpServers !== undefined) {
+ const timedOut = (phase: ClaudeMcpRegistrationTimeoutError["phase"]) => () =>
+ Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", {
+ threadId: input.threadId,
+ providerSessionId: input.providerSessionId,
+ phase,
+ }).pipe(
+ Effect.andThen(
+ Effect.fail(
+ queryRunnerError(new ClaudeMcpRegistrationTimeoutError({ phase }), phase),
+ ),
+ ),
+ );
+ // The SDK leaves query() boot unbounded, and it takes about a minute on a host
+ // with CPUs 12x oversubscribed, so it gets its own, longer deadline.
+ yield* Effect.promise(() =>
+ queryRuntime.initializationResult().catch(() => undefined),
+ ).pipe(
+ Effect.timeoutOrElse({
+ duration: CLAUDE_BOOT_TIMEOUT,
+ orElse: timedOut("initialize"),
+ }),
);
- child.once("exit", () =>
- runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))),
+ // Errors and mcp_status can echo headers; log only server names.
+ const failed = yield* Effect.tryPromise({
+ try: () => queryRuntime.setMcpServers(mcpServers),
+ catch: (cause) => queryRunnerError(cause, "setMcpServers"),
+ }).pipe(
+ Effect.map((result) => Object.keys(result.errors)),
+ Effect.orElseSucceed(() => Object.keys(mcpServers)),
+ Effect.timeoutOrElse({
+ duration: CLAUDE_MCP_REGISTRATION_TIMEOUT,
+ orElse: timedOut("setMcpServers"),
+ }),
);
- refreshDescendants = tracker.refresh;
+ if (failed.length > 0) {
+ yield* Effect.logWarning("orchestration-v2.claude-mcp-servers-unavailable", {
+ threadId: input.threadId,
+ servers: failed,
+ });
+ }
}
- return child;
- }
- const child = SpawnWorker.spawnPiped(spawnOptions.command, spawnOptions.args, {
- cwd: spawnOptions.cwd,
- env: spawnOptions.env,
- signal: spawnOptions.signal,
- windowsHide: true,
- });
- child.stderr
- .setEncoding("utf8")
- .on("data", (chunk: string) => options.stderr?.(chunk));
- return child;
- });
- let spawnedProcess: ClaudeSpawnedProcess | undefined;
- let processExited = false;
- let processExit: Promise | undefined;
- const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => {
- const child = spawnProcess(spawnOptions);
- spawnedProcess = child;
- // A spawn that fails emits only "error".
- const releaseAgent = portDiscovery.trackAgent();
- child.once("exit", releaseAgent);
- child.on("error", releaseAgent);
- processExited = child.exitCode !== null || child.signalCode != null;
- processExit = new Promise((resolve) => {
- if (processExited) resolve();
- else
- child.once("exit", () => {
- processExited = true;
- resolve();
+ yield* logProtocolEvent({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: {
+ type: "query.open",
+ options: loggedClaudeQueryOptions(input.options),
+ },
});
- });
- return child;
- };
- const queryRuntime = yield* Effect.uninterruptibleMask((restore) =>
- Effect.try({
- try: () =>
- withoutClaudeCanUseToolShadowedWarning(() =>
- query({
- prompt,
- options: { ...options, spawnClaudeCodeProcess },
- }),
- ),
- catch: (cause) => queryRunnerError(cause, "query"),
- }).pipe(
- Effect.tap((queryRuntime) =>
- restore(
- Effect.gen(function* () {
- if (mcpServers !== undefined) {
- const timedOut = (phase: ClaudeMcpRegistrationTimeoutError["phase"]) => () =>
- Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", {
- threadId: input.threadId,
- providerSessionId: input.providerSessionId,
- phase,
- }).pipe(
- Effect.andThen(
- Effect.fail(
- queryRunnerError(
- new ClaudeMcpRegistrationTimeoutError({ phase }),
- phase,
- ),
- ),
- ),
- );
- // The SDK leaves query() boot unbounded, and it takes about a minute on a host
- // with CPUs 12x oversubscribed, so it gets its own, longer deadline.
- yield* Effect.promise(() =>
- queryRuntime.initializationResult().catch(() => undefined),
- ).pipe(
- Effect.timeoutOrElse({
- duration: CLAUDE_BOOT_TIMEOUT,
- orElse: timedOut("initialize"),
- }),
- );
- // Errors and mcp_status can echo headers; log only server names.
- const failed = yield* Effect.tryPromise({
- try: () => queryRuntime.setMcpServers(mcpServers),
- catch: (cause) => queryRunnerError(cause, "setMcpServers"),
- }).pipe(
- Effect.map((result) => Object.keys(result.errors)),
- Effect.orElseSucceed(() => Object.keys(mcpServers)),
- Effect.timeoutOrElse({
- duration: CLAUDE_MCP_REGISTRATION_TIMEOUT,
- orElse: timedOut("setMcpServers"),
- }),
- );
- if (failed.length > 0) {
- yield* Effect.logWarning(
- "orchestration-v2.claude-mcp-servers-unavailable",
- {
- threadId: input.threadId,
- servers: failed,
- },
- );
- }
- }
- yield* logProtocolEvent({
- direction: "outgoing",
- stage: "decoded",
- payload: {
- type: "query.open",
- options: loggedClaudeQueryOptions(input.options),
+ }),
+ ).pipe(
+ Effect.onError(() =>
+ Queue.shutdown(promptQueue).pipe(
+ // SDK disposal can return before process exit; await the owned child's exit before retrying.
+ Effect.andThen(
+ Effect.tryPromise({
+ try: async () => {
+ if (spawnedProcess !== undefined && !processExited) {
+ spawnedProcess.kill("SIGKILL");
+ }
+ await processExit;
},
- });
- }),
- ).pipe(
- Effect.onError(() =>
- Queue.shutdown(promptQueue).pipe(
- // SDK disposal can return before process exit; await the owned child's exit before retrying.
- Effect.andThen(
- Effect.tryPromise({
- try: async () => {
- if (spawnedProcess !== undefined && !processExited) {
- spawnedProcess.kill("SIGKILL");
- }
- await processExit;
- },
- catch: (cause) => queryRunnerError(cause, "close"),
- }).pipe(Effect.timeout("10 seconds")),
- ),
- Effect.ensuring(
- Effect.tryPromise({
- try: () => queryRuntime[Symbol.asyncDispose](),
- catch: (cause) => queryRunnerError(cause, "close"),
- }).pipe(Effect.orDie),
- ),
- Effect.orDie,
- ),
+ catch: (cause) => queryRunnerError(cause, "close"),
+ }).pipe(Effect.timeout("10 seconds")),
),
+ Effect.ensuring(
+ Effect.tryPromise({
+ try: () => queryRuntime[Symbol.asyncDispose](),
+ catch: (cause) => queryRunnerError(cause, "close"),
+ }).pipe(Effect.orDie),
+ ),
+ Effect.orDie,
),
),
),
- );
+ ),
+ ),
+ );
- return {
- messages: Stream.fromAsyncIterable(
- claudeQueryMessages(queryRuntime),
- (cause) => cause,
- ).pipe(
- Stream.catch((cause) =>
- Stream.fromEffect(
- Effect.gen(function* () {
- if (!answered) {
- yield* Effect.promise(() => stderrClosed).pipe(
- Effect.timeoutOption(CLAUDE_STDERR_DRAIN_TIMEOUT),
- );
- }
- const refusedRoot = !answered && stderrTail.includes(CLAUDE_ROOT_REFUSAL);
- return yield* queryRunnerError(
- refusedRoot
- ? new ClaudeCodeRootRefusalError({ cause })
- : conversationMissing ||
- (!answered && stderrTail.includes(CLAUDE_CONVERSATION_NOT_FOUND))
- ? new ClaudeConversationNotFoundError({ cause })
- : cause,
- "fromAsyncIterable",
- );
- }),
- ),
- ),
- Stream.tap((message) =>
- Effect.sync(() => {
- answered = true;
- if (
- message.type === "result" &&
- message.subtype !== "success" &&
- message.errors.some((error) => error.startsWith(CLAUDE_CONVERSATION_NOT_FOUND))
- ) {
- conversationMissing = true;
- }
- }),
- ),
- Stream.tap((message) =>
- logProtocolEvent({
- direction: "incoming",
- stage: "decoded",
- payload: message,
- }),
- ),
+ return {
+ messages: Stream.fromAsyncIterable(
+ claudeQueryMessages(queryRuntime),
+ (cause) => cause,
+ ).pipe(
+ Stream.catch((cause) =>
+ Stream.fromEffect(
+ Effect.gen(function* () {
+ if (!answered) {
+ yield* Effect.promise(() => stderrClosed).pipe(
+ Effect.timeoutOption(CLAUDE_STDERR_DRAIN_TIMEOUT),
+ );
+ }
+ const refusedRoot = !answered && stderrTail.includes(CLAUDE_ROOT_REFUSAL);
+ return yield* queryRunnerError(
+ refusedRoot
+ ? new ClaudeCodeRootRefusalError({ cause })
+ : conversationMissing ||
+ (!answered && stderrTail.includes(CLAUDE_CONVERSATION_NOT_FOUND))
+ ? new ClaudeConversationNotFoundError({ cause })
+ : cause,
+ "fromAsyncIterable",
+ );
+ }),
),
- offer: (message, onQueued) =>
- Effect.uninterruptibleMask((restore) =>
- restore(Queue.offer(promptQueue, message)).pipe(
- Effect.tap(() => Effect.sync(() => onQueued?.())),
- ),
- ).pipe(
- Effect.asVoid,
- Effect.tap(() =>
- logProtocolEvent({
- direction: "outgoing",
- stage: "decoded",
- payload: {
- type: "prompt.offer",
- message,
- },
- }),
- ),
- ),
- setModel: (model) =>
- Effect.tryPromise({
- try: () => queryRuntime.setModel(model),
- catch: (cause) => queryRunnerError(cause, "setModel"),
- }).pipe(
- Effect.tap(() =>
- logProtocolEvent({
- direction: "outgoing",
- stage: "decoded",
- payload: {
- type: "query.set_model",
- model,
- },
- }),
- ),
- ),
- applyFlagSettings: (settings) =>
- Effect.tryPromise({
- try: () => queryRuntime.applyFlagSettings(settings),
- catch: (cause) => queryRunnerError(cause, "applyFlagSettings"),
- }).pipe(
- Effect.tap(() =>
- logProtocolEvent({
- direction: "outgoing",
- stage: "decoded",
- payload: {
- type: "query.apply_flag_settings",
- settings,
- },
- }),
- ),
- ),
- setPermissionMode: (mode) =>
- Effect.tryPromise({
- try: () => queryRuntime.setPermissionMode(mode),
- catch: (cause) => queryRunnerError(cause, "setPermissionMode"),
- }).pipe(
- Effect.tap(() =>
- logProtocolEvent({
- direction: "outgoing",
- stage: "decoded",
- payload: {
- type: "query.set_permission_mode",
- mode,
- },
- }),
- ),
- ),
- renameSession: (title) =>
- Effect.tryPromise({
- try: () =>
- sendClaudeControlRequest(queryRuntime, {
- subtype: "rename_session",
- title,
- source: "host",
- }),
- catch: (cause) => queryRunnerError(cause, "renameSession"),
- }).pipe(
- Effect.asVoid,
- Effect.tap(() =>
- logProtocolEvent({
- direction: "outgoing",
- stage: "decoded",
- payload: {
- type: "query.rename_session",
- title,
- },
- }),
- ),
- ),
- stopTask: (taskId) =>
- Effect.tryPromise({
- try: () => queryRuntime.stopTask(taskId),
- catch: (cause) => queryRunnerError(cause, "stopTask"),
- }).pipe(
- Effect.tap(() =>
- logProtocolEvent({
- direction: "outgoing",
- stage: "decoded",
- payload: { type: "query.stop_task", taskId },
- }),
- ),
- ),
- backgroundTasks: (toolUseId) =>
- Effect.tryPromise({
- try: () => queryRuntime.backgroundTasks(toolUseId),
- catch: (cause) => queryRunnerError(cause, "backgroundTasks"),
- }).pipe(
- Effect.tap(() =>
- logProtocolEvent({
- direction: "outgoing",
- stage: "decoded",
- payload: { type: "query.background_tasks", toolUseId },
- }),
- ),
- ),
- mcpServerStatus: Effect.tryPromise({
- try: () => queryRuntime.mcpServerStatus(),
- catch: (cause) => queryRunnerError(cause, "mcpServerStatus"),
+ ),
+ Stream.tap((message) =>
+ Effect.sync(() => {
+ answered = true;
+ if (
+ message.type === "result" &&
+ message.subtype !== "success" &&
+ message.errors.some((error) => error.startsWith(CLAUDE_CONVERSATION_NOT_FOUND))
+ ) {
+ conversationMissing = true;
+ }
+ }),
+ ),
+ Stream.tap((message) =>
+ logProtocolEvent({
+ direction: "incoming",
+ stage: "decoded",
+ payload: message,
}),
- readMcpResource: ({ server, uri }) =>
- Effect.tryPromise({
- try: () => queryRuntime.readMcpResource(server, uri),
- catch: (cause) => queryRunnerError(cause, "readMcpResource"),
+ ),
+ ),
+ offer: (message, onQueued) =>
+ Effect.uninterruptibleMask((restore) =>
+ restore(Queue.offer(promptQueue, message)).pipe(
+ Effect.tap(() => Effect.sync(() => onQueued?.())),
+ ),
+ ).pipe(
+ Effect.asVoid,
+ Effect.tap(() =>
+ logProtocolEvent({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: {
+ type: "prompt.offer",
+ message,
+ },
}),
- callMcpTool: (call) =>
- Effect.tryPromise({
- try: () =>
- sendClaudeControlRequest(queryRuntime, {
- subtype: "mcp_call",
- tool: call.tool,
- arguments: call.arguments,
- result_not_for_model: true,
- }),
- catch: (cause) => queryRunnerError(cause, "callMcpTool"),
+ ),
+ ),
+ setModel: (model) =>
+ Effect.tryPromise({
+ try: () => queryRuntime.setModel(model),
+ catch: (cause) => queryRunnerError(cause, "setModel"),
+ }).pipe(
+ Effect.tap(() =>
+ logProtocolEvent({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: {
+ type: "query.set_model",
+ model,
+ },
}),
- listPermissionRules: Effect.tryPromise({
- try: () =>
- sendClaudeControlRequest(queryRuntime, { subtype: "list_permission_rules" }),
- catch: (cause) => queryRunnerError(cause, "listPermissionRules"),
- }).pipe(
- Effect.flatMap(decodeClaudePermissionRules),
- // A settings file Claude couldn't parse was skipped, so its rules are missing from the list.
- Effect.filterOrFail(
- ({ state }) => (state.errors ?? []).length === 0,
- ({ state }) => new Error(`Claude skipped ${state.errors?.length} settings file(s)`),
- ),
- Effect.map(({ state }) => state.rules),
- Effect.mapError((cause) => queryRunnerError(cause, "listPermissionRules")),
),
- interrupt: Effect.tryPromise({
- try: () => queryRuntime.interrupt(),
- catch: (cause) => queryRunnerError(cause, "interrupt"),
- }).pipe(
- Effect.tap(() =>
- logProtocolEvent({
- direction: "outgoing",
- stage: "decoded",
- payload: {
- type: "query.interrupt",
- },
- }),
- ),
+ ),
+ applyFlagSettings: (settings) =>
+ Effect.tryPromise({
+ try: () => queryRuntime.applyFlagSettings(settings),
+ catch: (cause) => queryRunnerError(cause, "applyFlagSettings"),
+ }).pipe(
+ Effect.tap(() =>
+ logProtocolEvent({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: {
+ type: "query.apply_flag_settings",
+ settings,
+ },
+ }),
),
- // A job started since the last poll is recorded before the CLI is told to exit.
- close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe(
- Effect.andThen(Queue.shutdown(promptQueue)),
- Effect.andThen(closeClaudeQuery(queryRuntime)),
- Effect.tap(() =>
- logProtocolEvent({
- direction: "outgoing",
- stage: "decoded",
- payload: {
- type: "query.close",
- },
- }),
- ),
+ ),
+ setPermissionMode: (mode) =>
+ Effect.tryPromise({
+ try: () => queryRuntime.setPermissionMode(mode),
+ catch: (cause) => queryRunnerError(cause, "setPermissionMode"),
+ }).pipe(
+ Effect.tap(() =>
+ logProtocolEvent({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: {
+ type: "query.set_permission_mode",
+ mode,
+ },
+ }),
),
- } satisfies ClaudeAgentSdkQuerySession;
- },
- // Fresh IDs may already have a metadata-only transcript; only resumed opens can reuse their ID.
- (effect, input) =>
- effect.pipe(
- Effect.retry({
- times: 1,
- while: (error) =>
- input.options.resume !== undefined &&
- isClaudeMcpRegistrationTimeoutError(error.cause),
+ ),
+ renameSession: (title) =>
+ Effect.tryPromise({
+ try: () =>
+ sendClaudeControlRequest(queryRuntime, {
+ subtype: "rename_session",
+ title,
+ source: "host",
+ }),
+ catch: (cause) => queryRunnerError(cause, "renameSession"),
+ }).pipe(
+ Effect.asVoid,
+ Effect.tap(() =>
+ logProtocolEvent({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: {
+ type: "query.rename_session",
+ title,
+ },
+ }),
+ ),
+ ),
+ stopTask: (taskId) =>
+ Effect.tryPromise({
+ try: () => queryRuntime.stopTask(taskId),
+ catch: (cause) => queryRunnerError(cause, "stopTask"),
+ }).pipe(
+ Effect.tap(() =>
+ logProtocolEvent({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: { type: "query.stop_task", taskId },
+ }),
+ ),
+ ),
+ backgroundTasks: (toolUseId) =>
+ Effect.tryPromise({
+ try: () => queryRuntime.backgroundTasks(toolUseId),
+ catch: (cause) => queryRunnerError(cause, "backgroundTasks"),
+ }).pipe(
+ Effect.tap(() =>
+ logProtocolEvent({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: { type: "query.background_tasks", toolUseId },
+ }),
+ ),
+ ),
+ mcpServerStatus: Effect.tryPromise({
+ try: () => queryRuntime.mcpServerStatus(),
+ catch: (cause) => queryRunnerError(cause, "mcpServerStatus"),
+ }),
+ readMcpResource: ({ server, uri }) =>
+ Effect.tryPromise({
+ try: () => queryRuntime.readMcpResource(server, uri),
+ catch: (cause) => queryRunnerError(cause, "readMcpResource"),
+ }),
+ callMcpTool: (call) =>
+ Effect.tryPromise({
+ try: () =>
+ sendClaudeControlRequest(queryRuntime, {
+ subtype: "mcp_call",
+ tool: call.tool,
+ arguments: call.arguments,
+ result_not_for_model: true,
+ }),
+ catch: (cause) => queryRunnerError(cause, "callMcpTool"),
+ }),
+ listPermissionRules: Effect.tryPromise({
+ try: () => sendClaudeControlRequest(queryRuntime, { subtype: "list_permission_rules" }),
+ catch: (cause) => queryRunnerError(cause, "listPermissionRules"),
+ }).pipe(
+ Effect.flatMap(decodeClaudePermissionRules),
+ // A settings file Claude couldn't parse was skipped, so its rules are missing from the list.
+ Effect.filterOrFail(
+ ({ state }) => (state.errors ?? []).length === 0,
+ ({ state }) => new Error(`Claude skipped ${state.errors?.length} settings file(s)`),
+ ),
+ Effect.map(({ state }) => state.rules),
+ Effect.mapError((cause) => queryRunnerError(cause, "listPermissionRules")),
+ ),
+ interrupt: Effect.tryPromise({
+ try: () => queryRuntime.interrupt(),
+ catch: (cause) => queryRunnerError(cause, "interrupt"),
+ }).pipe(
+ Effect.tap(() =>
+ logProtocolEvent({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: {
+ type: "query.interrupt",
+ },
}),
),
- ),
+ ),
+ // A job started since the last poll is recorded before the CLI is told to exit.
+ close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe(
+ Effect.andThen(Queue.shutdown(promptQueue)),
+ Effect.andThen(closeClaudeQuery(queryRuntime)),
+ Effect.tap(() =>
+ logProtocolEvent({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: {
+ type: "query.close",
+ },
+ }),
+ ),
+ ),
+ } satisfies ClaudeAgentSdkQuerySession;
+ });
+
+ return ClaudeAgentSdkQueryRunner.of({
+ allocateSessionId: random.uuidV4(),
+ open: Effect.fn("ClaudeAgentSdkQueryRunner.open")(function* (
+ input: ClaudeAgentSdkQueryOpenInput,
+ ) {
+ // A fresh ID may already have a transcript, so a fresh session retries under a new ID;
+ // the adapter adopts it from the init message, as it does after /clear.
+ return yield* openQuery(input).pipe(
+ Effect.catchIf(
+ (error) => isClaudeMcpRegistrationTimeoutError(error.cause),
+ Effect.fnUntraced(function* () {
+ const { resume, ...options } = input.options;
+ if (resume !== undefined) return yield* openQuery(input);
+ const sessionId = yield* random.uuidV4();
+ return yield* openQuery({ ...input, options: { ...options, sessionId } });
+ }),
+ ),
+ );
+ }),
forkSession: Effect.fn("ClaudeAgentSdkQueryRunner.forkSession")(function* (
input: ClaudeAgentSdkSessionForkInput,
) {
@@ -2769,10 +2766,8 @@ const resolveClaudeForkUpToMessageId = Effect.fn("ClaudeAdapterV2.resolveForkUpT
return boundaryNativeId;
}
- const terminalTurnsAfterBoundary = sourceTurns
- .slice(boundaryIndex + 1)
- .filter(isTerminalProviderTurn);
- if (terminalTurnsAfterBoundary.length === 0) {
+ // The head only marks this boundary when no later turn, finished or still running, wrote after it.
+ if (sourceTurns.length === boundaryIndex + 1) {
// Rollback pins the head but leaves the rolled-back turns in Claude's transcript.
return yield* getNativeConversationHeadId(input.sourceProviderThread);
}
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
index 28072c29d7fda..f1ef42a005e41 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
@@ -464,21 +464,24 @@ it.effect("cancels a stalled registration without retrying or retaining its prom
}).pipe(Effect.provide(realQueryRunner)),
);
-it.effect("does not reuse a fresh session ID after MCP registration times out", () =>
+it.effect("retries a fresh session once after MCP registration times out", () =>
Effect.gen(function* () {
const registrationStarted = Promise.withResolvers();
const disposed = vi.fn(async () => {});
- const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
- () =>
- ({
- initializationResult: async () => ({}),
- setMcpServers: () => {
- registrationStarted.resolve();
- return new Promise(() => {});
- },
- [Symbol.asyncDispose]: disposed,
- }) as unknown as ClaudeSdk.Query,
- );
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => {
+ const first = querySpy.mock.calls.length === 1;
+ return {
+ initializationResult: async () => ({}),
+ setMcpServers: () => {
+ registrationStarted.resolve();
+ return first
+ ? new Promise(() => {})
+ : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} });
+ },
+ close: vi.fn(),
+ [Symbol.asyncDispose]: disposed,
+ } as unknown as ClaudeSdk.Query;
+ });
yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
const runner = yield* ClaudeAgentSdkQueryRunner;
const { resume, ...options } = resumedMcpQueryInput.options;
@@ -492,9 +495,13 @@ it.effect("does not reuse a fresh session ID after MCP registration times out",
yield* TestClock.adjust("90 seconds");
const result = yield* Fiber.join(opening);
- assert.equal(result._tag, "Failure");
- assert.equal(querySpy.mock.calls.length, 1);
+ assert.equal(result._tag, "Success");
+ if (result._tag === "Success") yield* result.success.close;
+ assert.equal(querySpy.mock.calls.length, 2);
assert.equal(disposed.mock.calls.length, 1);
+ // A fresh ID may already have a transcript, so the retry must not open it as fresh again.
+ const retry = querySpy.mock.calls[1]![0].options;
+ assert.isFalse(retry?.sessionId === resume && retry?.resume === undefined);
}).pipe(Effect.provide(realQueryRunner)),
);
@@ -503,37 +510,42 @@ it.effect.each([
["times out a CLI that never boots", "5 minutes", false],
] as const)("%s", ([, bootWait, boots]) =>
Effect.gen(function* () {
- const waiting = Promise.withResolvers();
+ const attempts = [Promise.withResolvers(), Promise.withResolvers()];
const booted = Promise.withResolvers();
- const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
- () =>
- ({
- initializationResult: () => {
- waiting.resolve();
- return booted.promise;
- },
- // The CLI answers control requests only after it has booted.
- setMcpServers: async () => {
- waiting.resolve();
- await booted.promise;
- return { added: ["t3-code"], removed: [], errors: {} };
- },
- close: vi.fn(),
- [Symbol.asyncDispose]: async () => {},
- }) as unknown as ClaudeSdk.Query,
- );
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => {
+ const waiting = attempts[querySpy.mock.calls.length - 1]!;
+ return {
+ initializationResult: () => {
+ waiting.resolve();
+ return booted.promise;
+ },
+ // The CLI answers control requests only after it has booted.
+ setMcpServers: async () => {
+ waiting.resolve();
+ await booted.promise;
+ return { added: ["t3-code"], removed: [], errors: {} };
+ },
+ close: vi.fn(),
+ [Symbol.asyncDispose]: async () => {},
+ } as unknown as ClaudeSdk.Query;
+ });
yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
const runner = yield* ClaudeAgentSdkQueryRunner;
const { resume, ...options } = resumedMcpQueryInput.options;
const opening = yield* runner
.open({ ...resumedMcpQueryInput, options: { ...options, sessionId: resume } })
.pipe(Effect.result, Effect.forkChild);
- yield* Effect.promise(() => waiting.promise);
+ yield* Effect.promise(() => attempts[0]!.promise);
yield* TestClock.adjust(bootWait);
if (boots) booted.resolve();
+ else {
+ yield* Effect.promise(() => attempts[1]!.promise);
+ yield* TestClock.adjust(bootWait);
+ }
const result = yield* Fiber.join(opening);
assert.equal(result._tag, boots ? "Success" : "Failure");
+ assert.equal(querySpy.mock.calls.length, boots ? 1 : 2);
if (result._tag === "Success") yield* result.success.close;
else
assert.equal(
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
index 3951bfcd4ed58..e53e11203fecf 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
@@ -1820,6 +1820,96 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
+ it.effect("a steer that changes the service tier updates Codex's next-turn settings", () =>
+ Effect.gen(function* () {
+ const nativeThreadId = "steer-tier-thread";
+ const nativeTurnId = "steer-tier-turn";
+ const harness = yield* makeCodexReplayHarness(
+ makeCodexReplayTranscript({
+ scenario: "steer-service-tier",
+ entries: [
+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Work." }),
+ {
+ type: "expect_outbound",
+ label: "thread/settings/update",
+ frame: {
+ id: 4,
+ method: "thread/settings/update",
+ params: { threadId: nativeThreadId, serviceTier: "fast" },
+ },
+ },
+ { type: "emit_inbound", frame: { id: 4, result: {} } },
+ {
+ type: "expect_outbound",
+ label: "turn/steer",
+ frame: {
+ id: 5,
+ method: "turn/steer",
+ params: {
+ threadId: nativeThreadId,
+ expectedTurnId: nativeTurnId,
+ input: [{ type: "text", text: "Hurry up." }],
+ },
+ },
+ },
+ { type: "emit_inbound", frame: { id: 5, result: { turnId: nativeTurnId } } },
+ {
+ type: "emit_inbound",
+ frame: {
+ method: "turn/completed",
+ params: {
+ threadId: nativeThreadId,
+ turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
+ },
+ },
+ },
+ ],
+ }),
+ );
+ const turnInput = makeCodexTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("steer-tier-attempt"),
+ text: "Work.",
+ });
+ yield* harness.runtime.startTurn(turnInput);
+ yield* harness.until(() =>
+ harness.events.some(
+ (event) =>
+ event.type === "provider_turn.updated" &&
+ event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId,
+ ),
+ );
+ const providerTurnId = harness.events.flatMap((event) =>
+ event.type === "provider_turn.updated" ? [event.providerTurn.id] : [],
+ )[0];
+ assert.isDefined(providerTurnId);
+ if (providerTurnId === undefined) return;
+ yield* harness.runtime.steerTurn({
+ ...turnInput,
+ providerTurnId,
+ modelSelection: {
+ ...CODEX_TEST_MODEL_SELECTION,
+ options: [{ id: "serviceTier", value: "fast" }],
+ },
+ message: { ...turnInput.message, text: "Hurry up." },
+ });
+ yield* harness.firstTerminal;
+ assert.equal(harness.terminalEvents()[0]?.status, "completed");
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ );
+
it.effect("keeps native image views available to the clients", () =>
Effect.gen(function* () {
const nativeThreadId = "image-view-thread";
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
index 12ac4987437f3..804bc749153cf 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
@@ -8112,6 +8112,20 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
);
}
+ const serviceTier =
+ adapterOptions.resolveRuntime === undefined
+ ? getCodexServiceTierOptionValue(turnInput.modelSelection)
+ : undefined;
+ if (serviceTier !== undefined) {
+ // turn/steer carries no settings, and the turns Codex starts on its own reuse the thread's.
+ yield* client.request("thread/settings/update", { threadId, serviceTier }).pipe(
+ Effect.catch((cause) =>
+ Effect.logWarning("orchestration-v2.codex-steer-service-tier-failed", {
+ cause,
+ }),
+ ),
+ );
+ }
const codexInput = yield* toCodexInput(turnInput);
yield* client.request("turn/steer", {
expectedTurnId: activeTurn.nativeTurnId,
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
index e4c985daa1652..cd1bdc9044a5c 100644
--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
@@ -8074,12 +8074,13 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
);
it.effect.each([
- { status: "complete", reconnect: false },
- { status: "paused", reconnect: false },
- { status: "complete", reconnect: true },
+ { status: "complete", reconnect: false, silent: false },
+ { status: "paused", reconnect: false, silent: false },
+ { status: "complete", reconnect: true, silent: false },
+ { status: "paused", reconnect: false, silent: true },
] as const)(
- "keeps an OpenCode goal turn open until $status, with reconnect $reconnect",
- ({ status, reconnect }) =>
+ "keeps an OpenCode goal turn open until $status, with reconnect $reconnect and silent $silent",
+ ({ status, reconnect, silent }) =>
Effect.gen(function* () {
const recovered = reconnected({ [SESSION]: { type: "running" } });
const { runtime, thread } = yield* resumed(
@@ -8092,6 +8093,8 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
reply("session.command", null),
event("rpc.opencode.goal.changed", { sessionID: SESSION, goal: nativeGoal("active") }),
event("session.execution.succeeded", { sessionID: SESSION }),
+ out("rpc.call", ""),
+ reply("rpc.call", { output: nativeGoal(silent ? status : "active") }),
...(status === "complete"
? reconnect
? [
@@ -8104,7 +8107,14 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
]
: [event("session.execution.started", { sessionID: SESSION })]
: []),
- event("rpc.opencode.goal.changed", { sessionID: SESSION, goal: nativeGoal(status) }),
+ ...(silent
+ ? []
+ : [
+ event("rpc.opencode.goal.changed", {
+ sessionID: SESSION,
+ goal: nativeGoal(status),
+ }),
+ ]),
...(status === "complete"
? [
event("session.text.ended", {
@@ -8251,6 +8261,64 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}),
);
+ it.effect("a goal refresh that reconnect supersedes leaves the turn to reconnect's read", () =>
+ Effect.gen(function* () {
+ const gate = makeProviderReplayGate(["before-reconnect", "reconnect-reading"]);
+ const recovered = reconnected({ [SESSION]: { type: "running" } });
+ const elsewhere = { sessionID: "ses_elsewhere", goal: null };
+ const { runtime, thread } = yield* resumed(
+ [
+ out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "