sailfork / t3code-github / packages/ contracts/ src/ orchestrationV2.ts

import { OrchestrationMessageContext } from "./composerContext.ts";
import { withRecordIdTable } from "./orchestrationV2IdTable.ts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SchemaAST from "effect/SchemaAST";
import * as SchemaGetter from "effect/SchemaGetter";
import * as SchemaTransformation from "effect/SchemaTransformation";

import {
  CheckpointId,
  CheckpointRef,
  CheckpointScopeId,
  CommandId,
  ContextHandoffId,
  ContextTransferId,
  EventId,
  GuestMessageId,
  GuestShareId,
  IsoDateTime,
  MessageId,
  EnvironmentId,
  NodeId,
  ForwardCompatibleUnion,
  ForwardCompatibleUnionArray,
  hasUnknownUnionTag,
  isUnknownUnionMember,
  NonNegativeInt,
  PlanId,
  PositiveInt,
  ProjectId,
  ProviderSessionId,
  ProviderThreadId,
  ProviderTurnId,
  RawEventId,
  RunAttemptId,
  RunId,
  RuntimeRequestId,
  ScheduledTaskId,
  ThreadId,
  TrimmedNonEmptyString,
  TurnItemId,
} from "./baseSchemas.ts";
import { AuthMcpClientAccess } from "./auth.ts";
import { ChatAttachment } from "./chatAttachment.ts";
import { ThreadGuestShare } from "./guestShare.ts";
import { StoredThreadTags, ThreadTag } from "./threadTags.ts";
import {
  OrchestrationSearchThreadsInput,
  OrchestrationSearchThreadsResult,
} from "./threadSearch.ts";
import {
  OrchestrationGetFullThreadDiffInput,
  OrchestrationGetFullThreadDiffResult,
  OrchestrationGetTurnDiffInput,
  OrchestrationGetTurnDiffResult,
} from "./checkpointDiff.ts";
import { ModelSelection } from "./modelSelection.ts";
import {
  ThreadLinkedPullRequest,
  ThreadPullRequestLink,
  ThreadPullRequestKey,
  ThreadPullRequestLinkSource,
  ThreadPullRequestSnapshot,
  ThreadPullRequestStack,
  ThreadPullRequestWatch,
} from "./threadPullRequest.ts";
import {
  ProviderApprovalDecision,
  ProviderApprovalFullAccessOverride,
  ProviderApprovalOption,
  ProviderInteractionMode,
  ProviderRequestKind,
  ProviderUserInputAnswers,
  UserInputAttachments,
  UserInputAttachmentAnswerPayload,
  RuntimeMode,
} from "./providerPolicy.ts";
import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
import { OrchestrationProjectShell } from "./orchestrationProject.ts";
import {
  TurnTokenUsage,
  ToolActivitySurface,
  ToolActivityIcon,
  ToolActivitySource,
} from "./providerRuntime.ts";
import { ThreadTokenUsageSnapshot } from "./providerRuntime.ts";

export const OrchestrationV2Actor = Schema.Literals(["user", "agent", "system"]);
export type OrchestrationV2Actor = typeof OrchestrationV2Actor.Type;

export const OrchestrationV2CreationSource = Schema.Literals([
  "web",
  "mobile",
  "mcp",
  "provider",
  "server",
]);
export type OrchestrationV2CreationSource = typeof OrchestrationV2CreationSource.Type;

export const OrchestrationV2ThreadHistoryOrigin = Schema.Literals(["native", "v1_import"]);
export type OrchestrationV2ThreadHistoryOrigin = typeof OrchestrationV2ThreadHistoryOrigin.Type;

const OrchestrationV2CreationFields = {
  createdBy: OrchestrationV2Actor,
  creationSource: OrchestrationV2CreationSource,
} as const;

/**
 * The linked environment whose agent started this work here: the MCP client
 * session it signed in with, that session's label, and the access it was
 * paired with. Set when the thread is created and never changed; work derived
 * from it carries the same origin.
 */
export const OrchestrationV2LinkOrigin = Schema.Struct({
  sessionId: TrimmedNonEmptyString,
  label: Schema.String,
  access: Schema.optional(AuthMcpClientAccess),
});
export type OrchestrationV2LinkOrigin = typeof OrchestrationV2LinkOrigin.Type;

/**
 * Work from a link paired below full access may change only work from the same
 * link. A full-access link's agents already run as this environment's user,
 * so fencing T3's own tools would stop nothing they could not do anyway. An
 * origin stamped before access was recorded stays fenced.
 */
export const linkOriginIsFenced = (origin: OrchestrationV2LinkOrigin) =>
  origin.access !== "full-access";

/**
 * The thread in a linked environment that delegated this one, when it did:
 * this thread is that parent's subagent, run here instead of there.
 */
export const OrchestrationV2DelegatedFrom = Schema.Struct({
  environmentId: EnvironmentId,
  threadId: ThreadId,
  title: Schema.String,
});
export type OrchestrationV2DelegatedFrom = typeof OrchestrationV2DelegatedFrom.Type;

export const OrchestrationV2NativeRefStrength = Schema.Literals(["strong", "weak", "none"]);
export type OrchestrationV2NativeRefStrength = typeof OrchestrationV2NativeRefStrength.Type;

export const OrchestrationV2ProviderRef = Schema.Struct({
  driver: ProviderDriverKind,
  nativeId: Schema.NullOr(TrimmedNonEmptyString),
  strength: OrchestrationV2NativeRefStrength,
  fingerprint: Schema.optional(TrimmedNonEmptyString),
  ordinal: Schema.optional(NonNegativeInt),
});
export type OrchestrationV2ProviderRef = typeof OrchestrationV2ProviderRef.Type;

export const OrchestrationV2AppThreadLineage = Schema.Struct({
  parentThreadId: Schema.NullOr(ThreadId),
  relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])),
  rootThreadId: ThreadId,
  sideChat: Schema.optional(Schema.Boolean),
});
export type OrchestrationV2AppThreadLineage = typeof OrchestrationV2AppThreadLineage.Type;

/** Subagents and side chats live inside their parent's view, never in thread lists. */
export const isListedThreadLineage = (lineage: OrchestrationV2AppThreadLineage): boolean =>
  lineage.relationshipToParent !== "subagent" && lineage.sideChat !== true;

export const OrchestrationV2ContextTransferType = Schema.Literals([
  "fork",
  "provider_handoff",
  "merge_back",
  "subagent_spawn",
  "subagent_result",
]);
export type OrchestrationV2ContextTransferType = typeof OrchestrationV2ContextTransferType.Type;

export const OrchestrationV2ContextSourcePoint = Schema.Struct({
  threadId: ThreadId,
  runId: Schema.optional(RunId),
  checkpointId: Schema.optional(CheckpointId),
  turnItemId: Schema.optional(TurnItemId),
  providerThreadRef: Schema.optional(OrchestrationV2ProviderRef),
  providerTurnRef: Schema.optional(OrchestrationV2ProviderRef),
});
export type OrchestrationV2ContextSourcePoint = typeof OrchestrationV2ContextSourcePoint.Type;

export const OrchestrationV2ThreadForkSourcePoint = Schema.Union([
  Schema.Struct({ type: Schema.Literal("latest_stable") }),
  Schema.Struct({ type: Schema.Literal("run"), runId: RunId }),
  Schema.Struct({ type: Schema.Literal("checkpoint"), checkpointId: CheckpointId }),
]);
export type OrchestrationV2ThreadForkSourcePoint = typeof OrchestrationV2ThreadForkSourcePoint.Type;

export const OrchestrationV2ContextTransferResolution = Schema.Union([
  Schema.Struct({
    strategy: Schema.Literal("native_fork"),
    providerThreadRef: OrchestrationV2ProviderRef,
  }),
  Schema.Struct({
    strategy: Schema.Literal("portable_context"),
    contextHandoffId: ContextHandoffId,
  }),
  Schema.Struct({
    strategy: Schema.Literal("delta_context"),
    contextHandoffId: ContextHandoffId,
  }),
  Schema.Struct({
    strategy: Schema.Literal("fork_delta_context"),
    contextHandoffId: ContextHandoffId,
  }),
  Schema.Struct({
    strategy: Schema.Literal("checkpoint_context"),
    contextHandoffId: ContextHandoffId,
  }),
]);
export type OrchestrationV2ContextTransferResolution =
  typeof OrchestrationV2ContextTransferResolution.Type;

export const OrchestrationV2ProviderTurnTokenUsage = Schema.Struct({
  usedTokens: NonNegativeInt,
  maxTokens: Schema.optional(Schema.NullOr(NonNegativeInt)),
  inputTokens: Schema.optional(NonNegativeInt),
  cachedInputTokens: Schema.optional(NonNegativeInt),
  outputTokens: Schema.optional(NonNegativeInt),
  reasoningOutputTokens: Schema.optional(NonNegativeInt),
  promptCacheTtlMs: Schema.optional(PositiveInt),
  autoCompactThreshold: Schema.optional(PositiveInt),
  promptCacheExpiresAt: Schema.optional(Schema.String),
  updatedAt: Schema.String,
});
export type OrchestrationV2ProviderTurnTokenUsage =
  typeof OrchestrationV2ProviderTurnTokenUsage.Type;

export const OrchestrationV2ContextTransfer = Schema.Struct({
  id: ContextTransferId,
  type: OrchestrationV2ContextTransferType,
  sourceThreadId: ThreadId,
  targetThreadId: ThreadId,
  sourcePoint: OrchestrationV2ContextSourcePoint,
  basePoint: Schema.NullOr(OrchestrationV2ContextSourcePoint),
  sourceProviderInstanceId: Schema.NullOr(ProviderInstanceId),
  sourceTokenUsage: Schema.optional(OrchestrationV2ProviderTurnTokenUsage),
  targetProviderInstanceId: Schema.NullOr(ProviderInstanceId),
  targetRunId: Schema.NullOr(RunId),
  status: Schema.Literals([
    "pending",
    "resolved_native",
    "resolved_portable",
    "failed",
    "consumed",
    "superseded",
  ]),
  resolution: Schema.NullOr(OrchestrationV2ContextTransferResolution),
  createdBy: OrchestrationV2Actor,
  error: Schema.NullOr(Schema.String),
  createdAt: Schema.DateTimeUtc,
  updatedAt: Schema.DateTimeUtc,
  consumedAt: Schema.NullOr(Schema.DateTimeUtc),
});
export type OrchestrationV2ContextTransfer = typeof OrchestrationV2ContextTransfer.Type;

export const OrchestrationV2SessionCapabilities = Schema.Struct({
  supportsMultipleProviderThreadsPerSession: Schema.Boolean,
  supportsModelSwitchInSession: Schema.Boolean,
  supportsProviderSwitchingViaHandoff: Schema.Boolean,
  supportsRuntimeModeSwitchInSession: Schema.Boolean,
  pendingRequestsSurviveRestart: Schema.Boolean,
});
export type OrchestrationV2SessionCapabilities = typeof OrchestrationV2SessionCapabilities.Type;

export const OrchestrationV2ThreadCapabilities = Schema.Struct({
  canCreateEmptyThread: Schema.Boolean,
  canReadThreadSnapshot: Schema.Boolean,
  canRollbackThread: Schema.Boolean,
  canForkThread: Schema.Boolean,
  canForkFromTurn: Schema.Boolean,
  canForkFromSubagentThread: Schema.Boolean,
  exposesNativeThreadId: Schema.Boolean,
});
export type OrchestrationV2ThreadCapabilities = typeof OrchestrationV2ThreadCapabilities.Type;

export const OrchestrationV2TurnCapabilities = Schema.Struct({
  exposesNativeTurnId: Schema.Boolean,
  emitsTurnStarted: Schema.Boolean,
  emitsTurnCompleted: Schema.Boolean,
  supportsInterrupt: Schema.Boolean,
  supportsActiveSteering: Schema.Boolean,
  // Some native steering mechanisms cancel pending tools before consuming the message.
  activeSteeringInterruptsTools: Schema.optional(Schema.Boolean),
  // Some take text only, so a steer with attachments restarts the turn instead.
  activeSteeringAcceptsAttachments: Schema.optional(Schema.Boolean),
  supportsSteeringByInterruptRestart: Schema.Boolean,
  supportsQueuedMessages: Schema.Boolean,
  terminalStatusQuality: Schema.Literals(["strong", "weak", "none"]),
});
export type OrchestrationV2TurnCapabilities = typeof OrchestrationV2TurnCapabilities.Type;

export const OrchestrationV2StreamingCapabilities = Schema.Struct({
  streamsAssistantText: Schema.Boolean,
  streamsReasoning: Schema.Boolean,
  streamsToolOutput: Schema.Boolean,
  streamsPlanText: Schema.Boolean,
  emitsMessageCompleted: Schema.Boolean,
});
export type OrchestrationV2StreamingCapabilities = typeof OrchestrationV2StreamingCapabilities.Type;

export const OrchestrationV2ToolCapabilities = Schema.Struct({
  exposesToolItemIds: Schema.Boolean,
  emitsToolStarted: Schema.Boolean,
  emitsToolCompleted: Schema.Boolean,
  emitsToolOutput: Schema.Boolean,
  supportsMcpTools: Schema.Boolean,
  supportsDynamicToolCallbacks: Schema.Boolean,
});
export type OrchestrationV2ToolCapabilities = typeof OrchestrationV2ToolCapabilities.Type;

export const OrchestrationV2ApprovalCapabilities = Schema.Struct({
  supportsCommandApproval: Schema.Boolean,
  supportsFileReadApproval: Schema.Boolean,
  supportsFileChangeApproval: Schema.Boolean,
  supportsApplyPatchApproval: Schema.Boolean,
  approvalsHaveNativeRequestIds: Schema.Boolean,
  approvalCallbacksAreLiveOnly: Schema.Boolean,
  approvalsCanOriginateFromSubagents: Schema.Boolean,
});
export type OrchestrationV2ApprovalCapabilities = typeof OrchestrationV2ApprovalCapabilities.Type;

export const OrchestrationV2PlanningCapabilities = Schema.Struct({
  emitsPlanUpdated: Schema.Boolean,
  emitsTodoList: Schema.Boolean,
  emitsProposedPlan: Schema.Boolean,
  supportsStructuredQuestions: Schema.Boolean,
  planDeltasHaveItemIds: Schema.Boolean,
});
export type OrchestrationV2PlanningCapabilities = typeof OrchestrationV2PlanningCapabilities.Type;

export const OrchestrationV2SubagentCapabilities = Schema.Struct({
  supportsSubagents: Schema.Boolean,
  exposesSubagentThreadIds: Schema.Boolean,
  emitsSubagentLifecycle: Schema.Boolean,
  canWaitForSubagents: Schema.Boolean,
  canCloseSubagents: Schema.Boolean,
  canForkSubagentThread: Schema.Boolean,
});
export type OrchestrationV2SubagentCapabilities = typeof OrchestrationV2SubagentCapabilities.Type;

export const OrchestrationV2ContextCapabilities = Schema.Struct({
  acceptsSystemContext: Schema.Boolean,
  acceptsDeveloperContext: Schema.Boolean,
  acceptsSyntheticUserContext: Schema.Boolean,
  canGenerateSummaries: Schema.Boolean,
  canConsumeHandoffSummaries: Schema.Boolean,
  supportsDeltaHandoff: Schema.Boolean,
  supportsFullThreadHandoff: Schema.Boolean,
  maxRecommendedHandoffChars: Schema.NullOr(PositiveInt),
});
export type OrchestrationV2ContextCapabilities = typeof OrchestrationV2ContextCapabilities.Type;

export const OrchestrationV2CheckpointCapabilities = Schema.Struct({
  appCanCheckpointFilesystem: Schema.Boolean,
  supportsNestedCheckpointScopes: Schema.Boolean,
  providerCanRollbackConversation: Schema.Boolean,
  providerRollbackReturnsSnapshot: Schema.Boolean,
  providerCanReadConversationSnapshot: Schema.Boolean,
});
export type OrchestrationV2CheckpointCapabilities =
  typeof OrchestrationV2CheckpointCapabilities.Type;

export const OrchestrationV2RuntimePolicyCapabilities = Schema.Struct({
  enforcement: Schema.Literals(["native", "client-boundary"]),
});
export type OrchestrationV2RuntimePolicyCapabilities =
  typeof OrchestrationV2RuntimePolicyCapabilities.Type;

export const OrchestrationV2IdentityCapabilities = Schema.Struct({
  nativeThreadIds: OrchestrationV2NativeRefStrength,
  nativeTurnIds: OrchestrationV2NativeRefStrength,
  nativeItemIds: OrchestrationV2NativeRefStrength,
  nativeRequestIds: OrchestrationV2NativeRefStrength,
});
export type OrchestrationV2IdentityCapabilities = typeof OrchestrationV2IdentityCapabilities.Type;

export const OrchestrationV2ProviderCapabilities = Schema.Struct({
  sessions: OrchestrationV2SessionCapabilities,
  threads: OrchestrationV2ThreadCapabilities,
  turns: OrchestrationV2TurnCapabilities,
  streaming: OrchestrationV2StreamingCapabilities,
  tools: OrchestrationV2ToolCapabilities,
  approvals: OrchestrationV2ApprovalCapabilities,
  planning: OrchestrationV2PlanningCapabilities,
  subagents: OrchestrationV2SubagentCapabilities,
  context: OrchestrationV2ContextCapabilities,
  checkpointing: OrchestrationV2CheckpointCapabilities,
  identity: OrchestrationV2IdentityCapabilities,
  // Replay defaults old events to the weaker client-boundary guarantee.
  runtimePolicy: OrchestrationV2RuntimePolicyCapabilities.pipe(
    Schema.withDecodingDefault(Effect.succeed({ enforcement: "client-boundary" as const })),
  ),
});
export type OrchestrationV2ProviderCapabilities = typeof OrchestrationV2ProviderCapabilities.Type;

export const OrchestrationV2LimitRecovery = Schema.Struct({
  requestId: Schema.optional(CommandId),
  runId: RunId,
  resetAt: IsoDateTime,
  autoResume: Schema.Boolean,
  snooze: Schema.optional(Schema.Boolean),
});
export type OrchestrationV2LimitRecovery = typeof OrchestrationV2LimitRecovery.Type;

export const OrchestrationV2LimitRecoveryUpdate = Schema.Struct({
  runId: RunId,
  resetAt: IsoDateTime,
  autoResume: Schema.optional(Schema.Boolean),
  snooze: Schema.optional(Schema.Boolean),
}).check(
  Schema.makeFilter(
    (update) =>
      update.autoResume !== undefined ||
      update.snooze !== undefined ||
      "A recovery update must include autoResume or snooze.",
  ),
);
export type OrchestrationV2LimitRecoveryUpdate = typeof OrchestrationV2LimitRecoveryUpdate.Type;

/**
 * `score` is an open count that halves every two weeks, as of `openedAt`.
 * `picks` stores lowercase palette queries, newest first.
 * Times are epoch milliseconds for ranking arithmetic.
 */
export const OrchestrationV2ThreadOpens = Schema.Struct({
  openedAt: Schema.Finite,
  score: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
  picks: Schema.Array(
    Schema.Struct({ query: Schema.String.check(Schema.isMaxLength(32)), at: Schema.Finite }),
  ).check(Schema.isMaxLength(3)),
});
export type OrchestrationV2ThreadOpens = typeof OrchestrationV2ThreadOpens.Type;

// Open stats only rank search results, so a value this build cannot read (an
// older or newer shape) becomes null instead of failing the whole thread.
const LenientThreadOpens = Schema.NullOr(OrchestrationV2ThreadOpens).pipe(
  Schema.catchDecoding(() => Effect.succeedSome(null)),
);

export const OrchestrationV2AppThread = Schema.Struct({
  ...OrchestrationV2CreationFields,
  id: ThreadId,
  projectId: ProjectId,
  title: TrimmedNonEmptyString,
  providerInstanceId: ProviderInstanceId,
  modelSelection: ModelSelection,
  runtimeMode: RuntimeMode,
  interactionMode: ProviderInteractionMode,
  branch: Schema.NullOr(TrimmedNonEmptyString),
  worktreePath: Schema.NullOr(TrimmedNonEmptyString),
  linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
  pullRequests: Schema.optional(Schema.Array(ThreadPullRequestLink)),
  branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)),
  activeProviderThreadId: Schema.NullOr(ProviderThreadId),
  historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin),
  linkOrigin: Schema.optional(OrchestrationV2LinkOrigin),
  delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom),
  lineage: OrchestrationV2AppThreadLineage,
  forkedFrom: Schema.NullOr(
    Schema.Union([
      Schema.Struct({ type: Schema.Literal("run"), threadId: ThreadId, runId: RunId }),
      Schema.Struct({ type: Schema.Literal("node"), nodeId: NodeId }),
      Schema.Struct({
        type: Schema.Literal("provider_thread"),
        providerThreadId: ProviderThreadId,
        providerTurnId: Schema.optional(ProviderTurnId),
      }),
    ]),
  ),
  createdAt: Schema.DateTimeUtc,
  updatedAt: Schema.DateTimeUtc,
  archivedAt: Schema.NullOr(Schema.DateTimeUtc),
  settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])).pipe(
    Schema.withDecodingDefault(Effect.succeed(null)),
  ),
  settledAt: Schema.NullOr(Schema.DateTimeUtc).pipe(
    Schema.withDecodingDefault(Effect.succeed(null)),
  ),
  unsettledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
  snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
  snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
  lastSnoozeWakeAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
  limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecovery)),
  guestShare: Schema.optional(Schema.NullOr(ThreadGuestShare)),
  pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
  autoSettleDisabledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
  pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
  activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
  /** Absent on threads written before tags existed; read as empty. */
  tags: Schema.optional(StoredThreadTags),
  lastVisitedAt: Schema.NullOr(Schema.DateTimeUtc).pipe(
    Schema.withDecodingDefault(Effect.succeed(null)),
  ),
  opens: Schema.optional(LenientThreadOpens),
  titleRegeneration: Schema.optional(
    Schema.NullOr(
      Schema.Struct({
        requestId: CommandId,
        startedAt: Schema.DateTimeUtc,
      }),
    ),
  ),
  rollbackRequestId: Schema.optional(CommandId),
  rollbackFailure: Schema.optional(
    Schema.NullOr(
      Schema.Struct({
        requestId: CommandId,
        message: TrimmedNonEmptyString,
      }),
    ),
  ),
  deletedAt: Schema.NullOr(Schema.DateTimeUtc),
});
export type OrchestrationV2AppThread = typeof OrchestrationV2AppThread.Type;

/** Provider-native children cannot receive messages; T3 delegate_task children can. */
export function isProviderNativeSubagentThread(
  thread: Pick<OrchestrationV2AppThread, "lineage" | "creationSource">,
): boolean {
  return thread.lineage.relationshipToParent === "subagent" && thread.creationSource === "provider";
}

export const IDLE_COMPACTION_TEXT = "/compact";

interface CompactionMessageFields {
  readonly role: string;
  readonly text: string;
  readonly attachments?: ReadonlyArray<unknown> | undefined;
  readonly createdBy?: OrchestrationV2Actor | undefined;
  readonly creationSource?: OrchestrationV2CreationSource | undefined;
  readonly idleCompaction?: OrchestrationV2IdleCompaction | undefined;
}

/** A prompt that only asks the provider to compact, so its turn is the compaction itself. */
export function isCompactionCommandMessage(message: CompactionMessageFields): boolean {
  return (
    message.role === "user" &&
    message.text.trim().toLowerCase() === IDLE_COMPACTION_TEXT &&
    (message.attachments?.length ?? 0) === 0
  );
}

export type OrchestrationV2GoalCommand =
  | { readonly type: "show" }
  | { readonly type: "clear" }
  | { readonly type: "pause" }
  | { readonly type: "resume" }
  | { readonly type: "set"; readonly objective: string };

/** Reads a `/goal` control message. Messages with attachments are ordinary prompts. */
export function parseGoalCommand(message: {
  readonly text: string;
  readonly attachments?: ReadonlyArray<unknown> | undefined;
}): OrchestrationV2GoalCommand | null {
  if ((message.attachments?.length ?? 0) > 0) return null;
  const match = /^\/goal(?:\s+([\s\S]*))?$/u.exec(message.text.trim());
  if (match === null) return null;
  const argument = (match[1] ?? "").trim();
  switch (argument.toLowerCase()) {
    case "":
    case "edit":
      return { type: "show" };
    case "clear":
      return { type: "clear" };
    case "pause":
      return { type: "pause" };
    case "resume":
      return { type: "resume" };
    default:
      return { type: "set", objective: argument };
  }
}

/** Why T3 Code sent this `/compact` on its own, or undefined for one someone asked for. */
export function idleCompactionOf(
  message: CompactionMessageFields,
): OrchestrationV2IdleCompaction | undefined {
  if (!isCompactionCommandMessage(message)) return undefined;
  if (message.idleCompaction !== undefined) return message.idleCompaction;
  // Servers before `idleCompaction` marked their own as agent-created.
  return message.createdBy === "agent" && message.creationSource === "server"
    ? "beforeCacheExpires"
    : undefined;
}

export const OrchestrationV2RunStatus = Schema.Literals([
  "preparing",
  "queued",
  "starting",
  "running",
  "waiting",
  "completed",
  "interrupted",
  "failed",
  "cancelled",
  "rolled_back",
]);
export type OrchestrationV2RunStatus = typeof OrchestrationV2RunStatus.Type;

export const OrchestrationV2DelegatedCompletionTaskDeliveryState = Schema.Literals([
  "pending",
  "claimed",
  "acknowledged",
  "delivered",
  "disposed",
]);
export type OrchestrationV2DelegatedCompletionTaskDeliveryState =
  typeof OrchestrationV2DelegatedCompletionTaskDeliveryState.Type;

export const OrchestrationV2DelegatedCompletionTaskDelivery = Schema.Struct({
  state: OrchestrationV2DelegatedCompletionTaskDeliveryState,
  observedByRunId: Schema.NullOr(RunId),
});
export type OrchestrationV2DelegatedCompletionTaskDelivery =
  typeof OrchestrationV2DelegatedCompletionTaskDelivery.Type;

export const OrchestrationV2DelegatedCompletionDelivery = Schema.Struct({
  generation: PositiveInt,
  messageId: MessageId,
  taskIds: Schema.Array(NodeId),
});
export type OrchestrationV2DelegatedCompletionDelivery =
  typeof OrchestrationV2DelegatedCompletionDelivery.Type;

export const OrchestrationV2DelegatedCompletionCohort = Schema.Struct({
  disposition: Schema.Literals(["open", "stopped", "disposed"]),
  nextGeneration: PositiveInt,
  delivery: Schema.NullOr(OrchestrationV2DelegatedCompletionDelivery),
});
export type OrchestrationV2DelegatedCompletionCohort =
  typeof OrchestrationV2DelegatedCompletionCohort.Type;

export const OrchestrationV2RestartCancelledBackgroundWork = Schema.Struct({
  kind: Schema.Literals(["subagent", "shell", "monitor", "task"]),
  label: TrimmedNonEmptyString,
  id: Schema.optional(TrimmedNonEmptyString),
  /** The agent was waiting on this work, so its restart note wakes the agent even for a shell. */
  awaited: Schema.optional(Schema.Literal(true)),
});
export type OrchestrationV2RestartCancelledBackgroundWork =
  typeof OrchestrationV2RestartCancelledBackgroundWork.Type;

export const OrchestrationV2RunBackgroundWorkCancelled = Schema.Struct({
  runId: RunId,
  restartCancelledBackgroundWork: Schema.Array(OrchestrationV2RestartCancelledBackgroundWork),
});
export type OrchestrationV2RunBackgroundWorkCancelled =
  typeof OrchestrationV2RunBackgroundWorkCancelled.Type;

export const OrchestrationV2ThreadLaunchWorkspaceStrategy = Schema.Union([
  Schema.Struct({
    type: Schema.Literal("root"),
    branch: Schema.optional(TrimmedNonEmptyString),
  }),
  Schema.Struct({
    type: Schema.Literal("existing_worktree"),
    worktreePath: TrimmedNonEmptyString,
    branch: Schema.optional(TrimmedNonEmptyString),
  }),
  Schema.Struct({
    type: Schema.Literal("worktree"),
    baseRef: TrimmedNonEmptyString,
    branch: Schema.optional(TrimmedNonEmptyString),
    startFromOrigin: Schema.optional(Schema.Boolean),
  }),
]);
export type OrchestrationV2ThreadLaunchWorkspaceStrategy =
  typeof OrchestrationV2ThreadLaunchWorkspaceStrategy.Type;

export const ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE = "workspace_preparation_failed";

export const OrchestrationV2Run = Schema.Struct({
  id: RunId,
  threadId: ThreadId,
  ordinal: PositiveInt,
  providerInstanceId: ProviderInstanceId,
  modelSelection: ModelSelection,
  providerThreadId: Schema.NullOr(ProviderThreadId),
  userMessageId: MessageId,
  rootNodeId: Schema.NullOr(NodeId),
  activeAttemptId: Schema.NullOr(RunAttemptId),
  status: OrchestrationV2RunStatus,
  queuePosition: Schema.optional(Schema.NullOr(PositiveInt)),
  queueHeld: Schema.optional(Schema.Boolean),
  requestedAt: Schema.DateTimeUtc,
  startedAt: Schema.NullOr(Schema.DateTimeUtc),
  completedAt: Schema.NullOr(Schema.DateTimeUtc),
  checkpointId: Schema.NullOr(CheckpointId),
  contextHandoffId: Schema.NullOr(ContextHandoffId),
  restartContinuationOfRunId: Schema.optional(RunId),
  usageLimitContinuationOfRunId: Schema.optional(RunId),
  delegatedTaskId: Schema.optional(NodeId),
  workStartedAt: Schema.optional(Schema.DateTimeUtc),
  restartCancelledBackgroundWork: Schema.optional(
    Schema.Array(OrchestrationV2RestartCancelledBackgroundWork),
  ),
  sourcePlanRef: Schema.optional(
    Schema.Struct({
      threadId: ThreadId,
      planId: PlanId,
    }),
  ),
  delegatedCompletion: Schema.optional(OrchestrationV2DelegatedCompletionCohort),
  workspacePreparation: Schema.optional(OrchestrationV2ThreadLaunchWorkspaceStrategy),
  /** Starts a new provider conversation; earlier runs stay visible but never reach the provider. */
  freshContext: Schema.optional(Schema.Boolean),
});
export type OrchestrationV2Run = typeof OrchestrationV2Run.Type;

export function orchestrationV2RunWorkStartedAt(
  run: Pick<OrchestrationV2Run, "workStartedAt" | "startedAt" | "requestedAt">,
): OrchestrationV2Run["requestedAt"] {
  return run.workStartedAt ?? run.startedAt ?? run.requestedAt;
}

/**
 * Work started now would run in the project checkout, not the worktree the thread asked for. A
 * failed or interrupted setup leaves the request standing until a worktree exists.
 */
export function orchestrationV2WorktreePending(
  worktreePath: string | null,
  runs: ReadonlyArray<Pick<OrchestrationV2Run, "status" | "workspacePreparation">>,
): boolean {
  return (
    worktreePath === null &&
    runs.some(
      (run) =>
        (run.status === "preparing" || run.status === "failed" || run.status === "interrupted") &&
        run.workspacePreparation?.type === "worktree",
    )
  );
}

export const OrchestrationV2RunAttempt = Schema.Struct({
  id: RunAttemptId,
  // Provider-thread rows can be reused after recovery; retain the native input destination.
  nativeThreadId: Schema.optional(Schema.String),
  runId: RunId,
  attemptOrdinal: PositiveInt,
  rootNodeId: NodeId,
  providerInstanceId: ProviderInstanceId,
  providerThreadId: ProviderThreadId,
  providerTurnId: Schema.NullOr(ProviderTurnId),
  reason: Schema.Literals(["initial", "steering_restart", "retry", "provider_recovery"]),
  status: Schema.Literals([
    "pending",
    "running",
    "completed",
    "interrupted",
    "failed",
    "cancelled",
    "superseded",
  ]),
  startedAt: Schema.NullOr(Schema.DateTimeUtc),
  completedAt: Schema.NullOr(Schema.DateTimeUtc),
});
export type OrchestrationV2RunAttempt = typeof OrchestrationV2RunAttempt.Type;

export const OrchestrationV2ExecutionNode = Schema.Struct({
  id: NodeId,
  threadId: ThreadId,
  runId: Schema.NullOr(RunId),
  parentNodeId: Schema.NullOr(NodeId),
  rootNodeId: NodeId,
  kind: Schema.Literals([
    "root_turn",
    "assistant_message",
    "reasoning",
    "plan",
    "todo_list",
    "tool_call",
    "approval_request",
    "user_input_request",
    "subagent",
    "hook",
    "system",
  ]),
  status: Schema.Literals([
    "idle",
    "pending",
    "running",
    "waiting",
    "completed",
    "interrupted",
    "failed",
    "cancelled",
    "rolled_back",
  ]),
  countsForRun: Schema.Boolean,
  providerThreadId: Schema.NullOr(ProviderThreadId),
  providerTurnId: Schema.NullOr(ProviderTurnId),
  nativeItemRef: Schema.NullOr(OrchestrationV2ProviderRef),
  runtimeRequestId: Schema.NullOr(RuntimeRequestId),
  checkpointScopeId: Schema.NullOr(CheckpointScopeId),
  startedAt: Schema.NullOr(Schema.DateTimeUtc),
  completedAt: Schema.NullOr(Schema.DateTimeUtc),
});
export type OrchestrationV2ExecutionNode = typeof OrchestrationV2ExecutionNode.Type;

/** Append-only: phases discovered at runtime join when they start. */
export const OrchestrationV2WorkflowPhase = Schema.Struct({
  index: NonNegativeInt,
  title: TrimmedNonEmptyString,
});
export type OrchestrationV2WorkflowPhase = typeof OrchestrationV2WorkflowPhase.Type;

/** Nested timestamps use epoch milliseconds; only top-level DateTimeUtc fields are remapped for JSON. */
export const OrchestrationV2WorkflowAgent = Schema.Struct({
  index: NonNegativeInt,
  label: TrimmedNonEmptyString,
  agentId: Schema.optional(TrimmedNonEmptyString),
  childThreadId: Schema.optional(ThreadId),
  state: Schema.Literals(["queued", "running", "completed", "failed"]),
  phaseIndex: Schema.optional(NonNegativeInt),
  phaseTitle: Schema.optional(TrimmedNonEmptyString),
  model: Schema.optional(TrimmedNonEmptyString),
  effort: Schema.optional(TrimmedNonEmptyString),
  speed: Schema.optional(TrimmedNonEmptyString),
  attempt: Schema.optional(NonNegativeInt),
  totalTokens: Schema.optional(NonNegativeInt),
  toolCalls: Schema.optional(NonNegativeInt),
  durationMs: Schema.optional(NonNegativeInt),
  queuedAt: Schema.optional(NonNegativeInt),
  startedAt: Schema.optional(NonNegativeInt),
  completedAt: Schema.optional(NonNegativeInt),
  prompt: Schema.optional(Schema.NonEmptyString),
  result: Schema.optional(Schema.NonEmptyString),
});
export type OrchestrationV2WorkflowAgent = typeof OrchestrationV2WorkflowAgent.Type;

export const OrchestrationV2WorkflowRunHandles = Schema.Struct({
  runId: Schema.optional(TrimmedNonEmptyString),
  transcriptDir: Schema.optional(TrimmedNonEmptyString),
  scriptPath: Schema.optional(TrimmedNonEmptyString),
});
export type OrchestrationV2WorkflowRunHandles = typeof OrchestrationV2WorkflowRunHandles.Type;

export const OrchestrationV2SubagentWorkflow = Schema.Struct({
  name: Schema.optional(TrimmedNonEmptyString),
  runHandles: Schema.optional(OrchestrationV2WorkflowRunHandles),
  phases: Schema.Array(OrchestrationV2WorkflowPhase),
  agents: Schema.Array(OrchestrationV2WorkflowAgent),
  totalTokens: Schema.optional(NonNegativeInt),
  toolCalls: Schema.optional(NonNegativeInt),
  durationMs: Schema.optional(NonNegativeInt),
});
export type OrchestrationV2SubagentWorkflow = typeof OrchestrationV2SubagentWorkflow.Type;

/**
 * Wire-only, for clients that opted in with `acceptDedupedBodies` or `dedupeBodies=1`: the field
 * was blanked because an earlier record on the same response or stream holds the same value.
 * Restore with `@t3tools/shared/orchestrationV2DedupedBodies`; never store or forward a marked
 * value. Clients restore only these fields, so blanking another field needs a new opt-in.
 */
const DedupedBodyMarker = Schema.optionalKey(Schema.Literal(true));

/**
 * Where an app-owned task runs when it runs in a linked environment instead
 * of in a child thread here: that environment and the ordinary thread it runs
 * as there. Such a task has no `childThreadId`.
 */
export const OrchestrationV2RemoteTaskChild = Schema.Struct({
  environmentId: EnvironmentId,
  threadId: ThreadId,
  label: Schema.String,
  /** The run there that carries the task; absent on tasks recorded before it was kept. */
  runId: Schema.optional(RunId),
  /**
   * Nothing is left to stop there: a stop reached it, was refused for good, or the thread
   * or link is gone. A run ending there by itself sets it too, unless the task here was
   * cancelled or stopped and still owes a stop, which its follower keeps sending across
   * restarts. `false`: a Stop here owes one to a task that already had its result.
   */
  stoppedThere: Schema.optional(Schema.Boolean),
  /**
   * Stops asked for here once the task had its result. The count names the
   * one owed, so each reaches the thread there once however often it is sent.
   */
  stopCount: Schema.optional(NonNegativeInt),
});
export type OrchestrationV2RemoteTaskChild = typeof OrchestrationV2RemoteTaskChild.Type;

export const OrchestrationV2Subagent = Schema.Struct({
  id: NodeId,
  threadId: ThreadId,
  runId: Schema.NullOr(RunId),
  parentNodeId: NodeId,
  origin: Schema.Literals(["provider_native", "app_owned"]),
  createdBy: OrchestrationV2Actor,
  driver: ProviderDriverKind,
  providerInstanceId: ProviderInstanceId,
  providerThreadId: Schema.NullOr(ProviderThreadId),
  childThreadId: Schema.NullOr(ThreadId),
  remoteChild: Schema.optional(OrchestrationV2RemoteTaskChild),
  nativeTaskRef: Schema.NullOr(OrchestrationV2ProviderRef),
  prompt: Schema.String,
  title: Schema.NullOr(Schema.String),
  model: Schema.NullOr(Schema.String),
  modelSelection: Schema.optional(ModelSelection),
  completionWake: Schema.optional(Schema.Literals(["always", "settled_only"])),
  completionDelivery: Schema.optional(OrchestrationV2DelegatedCompletionTaskDelivery),
  status: Schema.Literals([
    "idle",
    "pending",
    "running",
    "waiting",
    "completed",
    "failed",
    "cancelled",
    "interrupted",
  ]),
  progress: Schema.optional(Schema.String),
  workflow: Schema.optional(OrchestrationV2SubagentWorkflow),
  result: Schema.NullOr(Schema.String),
  startedAt: Schema.NullOr(Schema.DateTimeUtc),
  completedAt: Schema.NullOr(Schema.DateTimeUtc),
  updatedAt: Schema.DateTimeUtc,
  /** Same as this subagent's previous record on this stream: its snapshot or `subagent.updated`. */
  promptOmitted: DedupedBodyMarker,
  resultOmitted: DedupedBodyMarker,
});
export type OrchestrationV2Subagent = typeof OrchestrationV2Subagent.Type;

export function isOrchestrationV2WorkActive(
  status: OrchestrationV2ExecutionNode["status"],
): boolean {
  return status === "pending" || status === "running" || status === "waiting";
}

export const OrchestrationV2CheckpointScope = Schema.Struct({
  id: CheckpointScopeId,
  threadId: ThreadId,
  runId: Schema.NullOr(RunId),
  nodeId: NodeId,
  parentScopeId: Schema.NullOr(CheckpointScopeId),
  providerThreadId: Schema.NullOr(ProviderThreadId),
  kind: Schema.Literals(["root_run", "subagent", "tool", "provider_thread", "manual"]),
  ordinalWithinParent: NonNegativeInt,
  advancesAppRunCount: Schema.Boolean,
  cwd: TrimmedNonEmptyString,
  createdAt: Schema.DateTimeUtc,
});
export type OrchestrationV2CheckpointScope = typeof OrchestrationV2CheckpointScope.Type;

export const OrchestrationV2ProviderSession = Schema.Struct({
  id: ProviderSessionId,
  driver: ProviderDriverKind,
  providerInstanceId: ProviderInstanceId,
  status: Schema.Literals(["starting", "ready", "running", "waiting", "stopped", "error"]),
  cwd: TrimmedNonEmptyString,
  model: Schema.NullOr(TrimmedNonEmptyString),
  capabilities: OrchestrationV2ProviderCapabilities,
  extensionStatuses: Schema.optional(
    Schema.Array(
      Schema.Struct({
        key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),
        text: TrimmedNonEmptyString.check(Schema.isMaxLength(4096)),
      }),
    ).check(Schema.isMaxLength(32)),
  ).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
  createdAt: Schema.DateTimeUtc,
  updatedAt: Schema.DateTimeUtc,
  lastError: Schema.NullOr(Schema.String),
});
export type OrchestrationV2ProviderSession = typeof OrchestrationV2ProviderSession.Type;

export const OrchestrationV2ProviderSessionDetached = Schema.Struct({
  providerSessionId: ProviderSessionId,
  detachedAt: Schema.DateTimeUtc,
  reason: Schema.optional(Schema.String),
});
export type OrchestrationV2ProviderSessionDetached =
  typeof OrchestrationV2ProviderSessionDetached.Type;

function encodedKind(member: Schema.Top): string {
  const encoded = SchemaAST.toEncoded(member.ast);
  const kind = SchemaAST.isObjects(encoded)
    ? encoded.propertySignatures.find((property) => property.name === "kind")?.type
    : undefined;
  if (kind !== undefined && SchemaAST.isLiteral(kind) && typeof kind.literal === "string") {
    return kind.literal;
  }
  throw new Error("Each member of a kind union needs a literal string `kind`.");
}

function kindUnionWithFallback<
  const Members extends ReadonlyArray<Schema.Top & { readonly Encoded: { readonly kind: string } }>,
  Unknown extends Schema.Top,
>(
  members: Members,
  unknown: (kind: Schema.optional<Schema.String>) => Unknown,
  fallback: (value: Unknown["Type"]) => Schema.Union<Members>["Encoded"],
) {
  const knownKinds: ReadonlySet<string> = new Set(members.map(encodedKind));
  const unknownKind = unknown(
    Schema.optional(
      Schema.String.check(
        Schema.makeFilter(
          (kind: string) => !knownKinds.has(kind) || "A known kind must decode in full.",
        ),
      ),
    ),
  ).pipe(
    Schema.decodeTo(Schema.Union(members), {
      decode: SchemaGetter.transform(fallback),
      encode: SchemaGetter.forbidden(() => "Unknown kinds are decode-only."),
    }),
  );
  return Schema.Union([...members, unknownKind]);
}

const PendingBackgroundTaskFields = {
  taskId: TrimmedNonEmptyString,
  description: Schema.optional(TrimmedNonEmptyString),
  /** The subagent task that started this work and waits on it. */
  parentTaskId: Schema.optional(TrimmedNonEmptyString),
  /**
   * The agent declared it resumes when this work ends, so the thread holds like it does for a
   * subagent. Only the agent knows whether a command is a wait or a dev server it left running.
   */
  awaited: Schema.optional(Schema.Literal(true)),
};

export const OrchestrationV2PendingBackgroundTask = kindUnionWithFallback(
  [
    Schema.Struct({
      ...PendingBackgroundTaskFields,
      kind: Schema.Literal("subagent"),
      /** The owning provider thread's instance, populated in derived pending work. */
      providerInstanceId: Schema.optional(ProviderInstanceId),
      childThreadId: Schema.optional(ThreadId),
    }),
    Schema.Struct({ ...PendingBackgroundTaskFields, kind: Schema.Literal("command") }),
    Schema.Struct({ ...PendingBackgroundTaskFields, kind: Schema.Literal("monitor") }),
    Schema.Struct({ ...PendingBackgroundTaskFields, kind: Schema.Literal("background_task") }),
  ],
  (kind) => Schema.Struct({ ...PendingBackgroundTaskFields, kind }),
  ({ taskId, description, parentTaskId }) => ({
    taskId,
    ...(description === undefined ? {} : { description }),
    ...(parentTaskId === undefined ? {} : { parentTaskId }),
    kind: "background_task",
  }),
);
export type OrchestrationV2PendingBackgroundTask = typeof OrchestrationV2PendingBackgroundTask.Type;

export const OrchestrationV2ProviderThreadNativeMetadata = Schema.Struct({
  modelSelection: Schema.optional(ModelSelection),
  title: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
  updatedAt: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
  itemIdentityVersion: Schema.optional(Schema.Literal(2)),
  forkHeadMessageId: Schema.optional(TrimmedNonEmptyString),
  claudeAttachmentBudget: Schema.optional(
    Schema.Struct({ bytesUsed: NonNegativeInt, pagesUsed: NonNegativeInt }),
  ),
});
export type OrchestrationV2ProviderThreadNativeMetadata =
  typeof OrchestrationV2ProviderThreadNativeMetadata.Type;

export const OrchestrationV2ProviderGoalStatus = Schema.Literals([
  "active",
  "paused",
  "blocked",
  "usage_limited",
  "budget_limited",
  "complete",
]);
export type OrchestrationV2ProviderGoalStatus = typeof OrchestrationV2ProviderGoalStatus.Type;

export const OrchestrationV2ProviderGoal = Schema.Struct({
  objective: TrimmedNonEmptyString,
  status: OrchestrationV2ProviderGoalStatus,
  tokensUsed: Schema.optional(NonNegativeInt),
  tokenBudget: Schema.optional(Schema.NullOr(NonNegativeInt)),
  timeUsedSeconds: Schema.optional(NonNegativeInt),
  checks: Schema.optional(NonNegativeInt),
  lastCheck: Schema.optional(Schema.String),
});
export type OrchestrationV2ProviderGoal = typeof OrchestrationV2ProviderGoal.Type;

export const OrchestrationV2ProviderThread = Schema.Struct({
  id: ProviderThreadId,
  driver: ProviderDriverKind,
  providerInstanceId: ProviderInstanceId,
  providerSessionId: Schema.NullOr(ProviderSessionId),
  appThreadId: Schema.NullOr(ThreadId),
  ownerNodeId: Schema.NullOr(NodeId),
  nativeThreadRef: Schema.NullOr(OrchestrationV2ProviderRef),
  nativeConversationHeadRef: Schema.NullOr(OrchestrationV2ProviderRef),
  status: Schema.Literals(["not_loaded", "idle", "active", "archived", "closed", "error"]),
  firstRunOrdinal: Schema.NullOr(PositiveInt),
  lastRunOrdinal: Schema.NullOr(PositiveInt),
  handoffIds: Schema.Array(ContextHandoffId),
  forkedFrom: Schema.NullOr(
    Schema.Struct({
      providerThreadId: ProviderThreadId,
      providerTurnId: Schema.optional(ProviderTurnId),
      checkpointId: Schema.optional(CheckpointId),
    }),
  ),
  pendingBackgroundTasks: Schema.optional(Schema.Array(OrchestrationV2PendingBackgroundTask)).pipe(
    Schema.withDecodingDefault(Effect.succeed([])),
  ),
  contextUsage: Schema.optional(Schema.NullOr(ThreadTokenUsageSnapshot)).pipe(
    Schema.withDecodingDefault(Effect.succeed(null)),
  ),
  nativeMetadata: Schema.optional(Schema.NullOr(OrchestrationV2ProviderThreadNativeMetadata)).pipe(
    Schema.withDecodingDefault(Effect.succeed(null)),
  ),
  goal: Schema.optional(Schema.NullOr(OrchestrationV2ProviderGoal)).pipe(
    Schema.withDecodingDefault(Effect.succeed(null)),
  ),
  createdAt: Schema.DateTimeUtc,
  updatedAt: Schema.DateTimeUtc,
});
export type OrchestrationV2ProviderThread = typeof OrchestrationV2ProviderThread.Type;

export const OrchestrationV2HistoricalMessage = Schema.Struct({
  role: Schema.Literals(["user", "assistant"]),
  text: Schema.String,
  runStatus: Schema.optional(Schema.String),
  threadId: ThreadId,
  runId: Schema.NullOr(RunId),
  itemId: TurnItemId,
  providerThreadId: Schema.NullOr(ProviderThreadId),
  status: Schema.String,
  kind: Schema.String,
});
export type OrchestrationV2HistoricalMessage = typeof OrchestrationV2HistoricalMessage.Type;

export const OrchestrationV2ContextHandoff = Schema.Struct({
  id: ContextHandoffId,
  transferId: Schema.optional(Schema.NullOr(ContextTransferId)),
  threadId: ThreadId,
  targetRunId: RunId,
  fromProviderThreadIds: Schema.Array(ProviderThreadId),
  toProviderThreadId: ProviderThreadId,
  coveredRunOrdinals: Schema.Struct({
    from: PositiveInt,
    to: PositiveInt,
  }),
  strategy: Schema.Literals([
    "delta_since_target_last_seen",
    "fork_delta_summary",
    "full_thread_summary",
    "checkpoint_summary",
    "manual_context",
  ]),
  status: Schema.Literals(["pending", "ready", "failed", "superseded"]),
  summaryMessageId: Schema.NullOr(MessageId),
  summaryText: Schema.String,
  history: Schema.optional(
    Schema.Struct({
      messages: Schema.Array(OrchestrationV2HistoricalMessage),
      coverage: Schema.String,
      omittedItems: NonNegativeInt,
      omittedItemIds: Schema.optional(Schema.Array(TurnItemId)),
    }),
  ),
  delivery: Schema.optional(
    Schema.Struct({
      nativeThreadId: Schema.String,
      status: Schema.Literals(["pending", "injected", "inline"]),
      itemIds: Schema.Array(TurnItemId),
      omittedItemIds: Schema.optional(Schema.Array(TurnItemId)),
    }),
  ),
  detailInTurnItem: Schema.optional(Schema.Literal(true)),
  createdByProviderInstanceId: Schema.NullOr(ProviderInstanceId),
  createdAt: Schema.DateTimeUtc,
  updatedAt: Schema.DateTimeUtc,
});
export type OrchestrationV2ContextHandoff = typeof OrchestrationV2ContextHandoff.Type;

export const OrchestrationV2ProviderTurn = Schema.Struct({
  id: ProviderTurnId,
  providerThreadId: ProviderThreadId,
  nodeId: NodeId,
  runAttemptId: Schema.NullOr(RunAttemptId),
  nativeTurnRef: Schema.NullOr(OrchestrationV2ProviderRef),
  ordinal: PositiveInt,
  status: Schema.Literals([
    "pending",
    "running",
    "completed",
    "interrupted",
    "failed",
    "cancelled",
  ]),
  startedAt: Schema.NullOr(Schema.DateTimeUtc),
  completedAt: Schema.NullOr(Schema.DateTimeUtc),
  tokenUsage: Schema.optional(OrchestrationV2ProviderTurnTokenUsage),
  turnTokenUsage: Schema.optional(TurnTokenUsage),
});
export type OrchestrationV2ProviderTurn = typeof OrchestrationV2ProviderTurn.Type;

/** Codex goals can span multiple native turns within one attempt. */
export function latestProviderTurnForAttempt<
  Turn extends Pick<OrchestrationV2ProviderTurn, "runAttemptId" | "ordinal">,
>(
  providerTurns: ReadonlyArray<Turn>,
  attemptId: RunAttemptId | null | undefined,
): Turn | undefined {
  let latest: Turn | undefined;
  for (const turn of providerTurns) {
    if (attemptId == null || turn.runAttemptId !== attemptId) continue;
    if (latest === undefined || turn.ordinal > latest.ordinal) latest = turn;
  }
  return latest;
}

export const OrchestrationV2RuntimeRequest = Schema.Struct({
  id: RuntimeRequestId,
  nodeId: NodeId,
  providerTurnId: Schema.NullOr(ProviderTurnId),
  nativeRequestRef: Schema.NullOr(OrchestrationV2ProviderRef),
  kind: Schema.Union([
    ProviderRequestKind,
    Schema.Literals(["dynamic_tool_call", "user_input", "auth_refresh"]),
  ]),
  status: Schema.Literals(["pending", "resolved", "expired", "cancelled"]),
  responseCapability: Schema.Union([
    Schema.Struct({
      type: Schema.Literal("live"),
      providerSessionId: ProviderSessionId,
      supportsFeedback: Schema.optional(Schema.Boolean),
    }),
    Schema.Struct({ type: Schema.Literal("message") }),
    Schema.Struct({ type: Schema.Literal("not_resumable"), reason: Schema.String }),
  ]),
  createdAt: Schema.DateTimeUtc,
  resolvedAt: Schema.NullOr(Schema.DateTimeUtc),
  decision: Schema.optional(ProviderApprovalDecision),
  feedback: Schema.optional(Schema.String),
  answers: Schema.optional(ProviderUserInputAnswers),
});
export type OrchestrationV2RuntimeRequest = typeof OrchestrationV2RuntimeRequest.Type;

const SubagentNotificationSource = Schema.Struct({
  kind: Schema.Literal("subagent"),
  childThreadId: Schema.optional(ThreadId),
});
const CommandNotificationSource = Schema.Struct({ kind: Schema.Literal("command") });

/** Encode legacy background_command/background_task shapes first so older clients accept command/subagent sources. */
export const OrchestrationV2NotificationSource = kindUnionWithFallback(
  [
    Schema.Struct({
      kind: Schema.Literal("delegated_task"),
      taskIds: Schema.Array(NodeId),
      childThreadId: Schema.optional(ThreadId),
    }),
    Schema.Struct({
      kind: Schema.Literal("background_task"),
      work: Schema.Literal("subagent"),
      childThreadId: Schema.optional(ThreadId),
    }).pipe(
      Schema.decodeTo(Schema.toType(SubagentNotificationSource), {
        decode: SchemaGetter.transform(({ childThreadId }) =>
          childThreadId === undefined
            ? { kind: "subagent" as const }
            : { kind: "subagent" as const, childThreadId },
        ),
        encode: SchemaGetter.transform(({ childThreadId }) => ({
          kind: "background_task" as const,
          work: "subagent" as const,
          ...(childThreadId === undefined ? {} : { childThreadId }),
        })),
      }),
    ),
    Schema.Struct({ kind: Schema.Literal("background_command").transform("command") }),
    SubagentNotificationSource,
    CommandNotificationSource,
    Schema.Struct({ kind: Schema.Literal("monitor") }),
    Schema.Struct({ kind: Schema.Literal("background_task") }),
    Schema.Struct({ kind: Schema.Literal("system") }),
  ],
  (kind) => Schema.Struct({ kind }),
  () => ({ kind: "background_task" }),
);
export type OrchestrationV2NotificationSource = typeof OrchestrationV2NotificationSource.Type;

export const OrchestrationV2Notification = Schema.Struct({
  source: OrchestrationV2NotificationSource,
  outcome: Schema.Literals(["completed", "failed", "cancelled", "updated", "unknown"]),
  summary: TrimmedNonEmptyString,
  detail: Schema.optional(Schema.String),
});
export type OrchestrationV2Notification = typeof OrchestrationV2Notification.Type;

/** Why T3 Code compacted a thread on its own, on the `/compact` it sent. */
export const OrchestrationV2IdleCompaction = Schema.Literals(["beforeCacheExpires", "onReturn"]);
export type OrchestrationV2IdleCompaction = typeof OrchestrationV2IdleCompaction.Type;

export const OrchestrationV2ConversationMessage = Schema.Struct({
  notification: Schema.optional(OrchestrationV2Notification),
  ...OrchestrationV2CreationFields,
  scheduledTaskId: Schema.optional(ScheduledTaskId),
  senderThreadId: Schema.optional(ThreadId),
  idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
  /**
   * The message is the script a provider-native workflow run executes, not prose. Clients show
   * the workflow's opening instead and keep the script behind a disclosure.
   */
  workflowScript: Schema.optional(Schema.Boolean),
  id: MessageId,
  threadId: ThreadId,
  runId: Schema.NullOr(RunId),
  nodeId: Schema.NullOr(NodeId),
  role: Schema.Literals(["user", "assistant", "system"]),
  text: Schema.String,
  context: Schema.optional(OrchestrationMessageContext),
  attachments: Schema.Array(ChatAttachment),
  streaming: Schema.Boolean,
  createdAt: Schema.DateTimeUtc,
  updatedAt: Schema.DateTimeUtc,
  delegatedCompletion: Schema.optional(
    Schema.Struct({
      parentRunId: RunId,
      generation: PositiveInt,
      taskIds: Schema.Array(NodeId),
    }),
  ),
});
export type OrchestrationV2ConversationMessage = typeof OrchestrationV2ConversationMessage.Type;

export const OrchestrationV2PlanStep = Schema.Struct({
  id: TrimmedNonEmptyString,
  text: TrimmedNonEmptyString,
  status: Schema.Literals(["pending", "running", "completed"]),
  durationAnchorAt: Schema.optional(IsoDateTime),
  durationMs: Schema.optional(NonNegativeInt),
});
export type OrchestrationV2PlanStep = typeof OrchestrationV2PlanStep.Type;

export const OrchestrationV2UserInputQuestion = Schema.Struct({
  id: TrimmedNonEmptyString,
  header: TrimmedNonEmptyString,
  question: TrimmedNonEmptyString,
  options: Schema.Array(
    Schema.Struct({
      label: TrimmedNonEmptyString,
      description: TrimmedNonEmptyString,
      value: Schema.optional(Schema.String),
      preview: Schema.optional(Schema.String),
    }),
  ),
  multiSelect: Schema.optional(Schema.Boolean),
  allowCustomAnswer: Schema.optional(Schema.Boolean),
  initialAnswer: Schema.optional(Schema.String),
  required: Schema.optional(Schema.Boolean),
});
export type OrchestrationV2UserInputQuestion = typeof OrchestrationV2UserInputQuestion.Type;

const OrchestrationV2PlanArtifactBaseFields = {
  id: PlanId,
  threadId: ThreadId,
  runId: Schema.NullOr(RunId),
  nodeId: NodeId,
  status: Schema.Literals(["draft", "active", "completed", "superseded"]),
  detailInTurnItem: Schema.optional(Schema.Literal(true)),
} as const;

export const OrchestrationV2PlanArtifact = Schema.Union([
  Schema.Struct({
    ...OrchestrationV2PlanArtifactBaseFields,
    kind: Schema.Literal("proposed_plan"),
    markdown: Schema.String,
  }),
  Schema.Struct({
    ...OrchestrationV2PlanArtifactBaseFields,
    kind: Schema.Literal("todo_list"),
    steps: Schema.Array(OrchestrationV2PlanStep),
    explanation: Schema.optional(Schema.String),
  }),
]);
export type OrchestrationV2PlanArtifact = typeof OrchestrationV2PlanArtifact.Type;

export const OrchestrationV2CheckpointFileSummary = Schema.Struct({
  path: TrimmedNonEmptyString,
  kind: TrimmedNonEmptyString,
  additions: NonNegativeInt,
  deletions: NonNegativeInt,
});
export type OrchestrationV2CheckpointFileSummary = typeof OrchestrationV2CheckpointFileSummary.Type;

/** Sent only when the wire carries a prefix of `files`; the totals cover the full list. */
export const OrchestrationV2CheckpointFileTotals = Schema.Struct({
  count: NonNegativeInt,
  additions: NonNegativeInt,
  deletions: NonNegativeInt,
});
export type OrchestrationV2CheckpointFileTotals = typeof OrchestrationV2CheckpointFileTotals.Type;

export const OrchestrationV2Checkpoint = Schema.Struct({
  id: CheckpointId,
  threadId: ThreadId,
  scopeId: CheckpointScopeId,
  runId: Schema.NullOr(RunId),
  nodeId: NodeId,
  parentCheckpointId: Schema.NullOr(CheckpointId),
  ordinalWithinScope: NonNegativeInt,
  appRunOrdinal: Schema.NullOr(PositiveInt),
  ref: CheckpointRef,
  status: Schema.Literals(["ready", "missing", "error", "stale"]),
  files: Schema.Array(OrchestrationV2CheckpointFileSummary),
  filesTotal: Schema.optionalKey(OrchestrationV2CheckpointFileTotals),
  capturedAt: Schema.DateTimeUtc,
});
export type OrchestrationV2Checkpoint = typeof OrchestrationV2Checkpoint.Type;

export const OrchestrationV2CheckpointRollbackRequest = Schema.Struct({
  scopeId: CheckpointScopeId,
  checkpointId: CheckpointId,
  requestedAt: Schema.DateTimeUtc,
});
export type OrchestrationV2CheckpointRollbackRequest =
  typeof OrchestrationV2CheckpointRollbackRequest.Type;

export class OrchestrationV2CheckpointUnavailableError extends Schema.TaggedError<OrchestrationV2CheckpointUnavailableError>()(
  "OrchestrationV2CheckpointUnavailableError",
  {
    threadId: ThreadId,
    target: Schema.String,
  },
) {
  override get message(): string {
    return `Rollback target ${this.target} is unavailable for thread ${this.threadId}.`;
  }
}

export const OrchestrationV2TurnItemStatus = Schema.Literals([
  "idle",
  "pending",
  "running",
  "waiting",
  "completed",
  "failed",
  "cancelled",
  "interrupted",
]);

export type OrchestrationV2TurnItemStatus = typeof OrchestrationV2TurnItemStatus.Type;

export const OrchestrationV2FileChangeDetail = Schema.Struct({
  operation: TrimmedNonEmptyString,
  path: TrimmedNonEmptyString,
  oldPath: Schema.optional(TrimmedNonEmptyString),
  fileType: Schema.optional(TrimmedNonEmptyString),
  mimeType: Schema.optional(TrimmedNonEmptyString),
});
export type OrchestrationV2FileChangeDetail = typeof OrchestrationV2FileChangeDetail.Type;

export const OrchestrationV2ProviderFailureClass = Schema.Literals([
  "usage_limit",
  "provider_error",
  "transport_error",
  "permission_error",
  "validation_error",
  "unknown",
]);
export type OrchestrationV2ProviderFailureClass = typeof OrchestrationV2ProviderFailureClass.Type;

const OrchestrationV2ProviderFailureMessage = TrimmedNonEmptyString.check(
  Schema.isMaxLength(4_096),
);
const OrchestrationV2ProviderFailureCode = TrimmedNonEmptyString.check(Schema.isMaxLength(128));

/** Producers must redact credentials before construction. */
export const OrchestrationV2ProviderFailure = Schema.Struct({
  class: OrchestrationV2ProviderFailureClass,
  message: OrchestrationV2ProviderFailureMessage,
  code: Schema.NullOr(OrchestrationV2ProviderFailureCode),
  retryable: Schema.NullOr(Schema.Boolean),
  resetAt: Schema.optional(Schema.NullOr(IsoDateTime)),
});
export type OrchestrationV2ProviderFailure = typeof OrchestrationV2ProviderFailure.Type;

export const OrchestrationV2ProviderRetry = Schema.Struct({
  attempt: PositiveInt,
  maxAttempts: Schema.NullOr(PositiveInt),
  retryDelayMs: Schema.NullOr(NonNegativeInt),
});
export type OrchestrationV2ProviderRetry = typeof OrchestrationV2ProviderRetry.Type;

export const OrchestrationV2UserMessageInputIntent = Schema.Literals([
  "turn_start",
  "queued_turn",
  "steer",
  "promoted_queued_to_steer",
]);
export type OrchestrationV2UserMessageInputIntent =
  typeof OrchestrationV2UserMessageInputIntent.Type;

/** A same-harness model or effort change that took effect with this message. */
export const OrchestrationV2ModelSwitch = Schema.Struct({
  from: ModelSelection,
  to: ModelSelection,
});
export type OrchestrationV2ModelSwitch = typeof OrchestrationV2ModelSwitch.Type;

const OrchestrationV2TurnItemBaseFields = {
  /** Wire-only cursor for collapsed work; persisted items keep their complete history. */
  deferredWork: Schema.optionalKey(
    Schema.Struct({
      cursor: TrimmedNonEmptyString,
      itemCount: PositiveInt,
      lastOrdinal: NonNegativeInt,
    }),
  ),
  toolNonExecutionKind: Schema.optional(Schema.String),
  toolSurface: Schema.optional(ToolActivitySurface),
  toolIcon: Schema.optional(ToolActivityIcon),
  toolSource: Schema.optional(ToolActivitySource),
  id: TurnItemId,
  threadId: ThreadId,
  runId: Schema.NullOr(RunId),
  nodeId: Schema.NullOr(NodeId),
  providerThreadId: Schema.NullOr(ProviderThreadId),
  providerTurnId: Schema.NullOr(ProviderTurnId),
  nativeItemRef: Schema.NullOr(OrchestrationV2ProviderRef),
  parentItemId: Schema.NullOr(TurnItemId),
  ordinal: NonNegativeInt,
  status: OrchestrationV2TurnItemStatus,
  title: Schema.NullOr(Schema.String),
  startedAt: Schema.NullOr(Schema.DateTimeUtc),
  completedAt: Schema.NullOr(Schema.DateTimeUtc),
  updatedAt: Schema.DateTimeUtc,
} as const;

export const OrchestrationV2FileSearchResult = Schema.Struct({
  fileName: TrimmedNonEmptyString,
  line: Schema.optional(PositiveInt),
  column: Schema.optional(PositiveInt),
  preview: Schema.optional(Schema.String),
});
export type OrchestrationV2FileSearchResult = typeof OrchestrationV2FileSearchResult.Type;

export const OrchestrationV2WebSearchResult = Schema.Struct({
  title: Schema.optional(Schema.String),
  url: Schema.optional(TrimmedNonEmptyString),
  snippet: Schema.optional(Schema.String),
});
export type OrchestrationV2WebSearchResult = typeof OrchestrationV2WebSearchResult.Type;

export const OrchestrationV2SecretRequestStatus = Schema.Literals([
  "pending",
  "saved",
  "declined",
  "cancelled",
]);
export type OrchestrationV2SecretRequestStatus = typeof OrchestrationV2SecretRequestStatus.Type;

/** `file`: the value goes to an owner-only file the agent's shell commands can read. */
export const OrchestrationV2SecretRequestDelivery = Schema.Literal("file");

const OrchestrationV2SecretRequestFields = {
  type: Schema.Literal("secret_request"),
  label: TrimmedNonEmptyString,
  reason: Schema.String,
  placeholder: Schema.optional(Schema.String),
  delivery: Schema.optional(OrchestrationV2SecretRequestDelivery),
  secretStatus: OrchestrationV2SecretRequestStatus,
} as const;

export const OrchestrationV2LinkRequestStatus = Schema.Literals([
  "pending",
  "linked",
  "declined",
  "cancelled",
  "failed",
]);
export type OrchestrationV2LinkRequestStatus = typeof OrchestrationV2LinkRequestStatus.Type;

/**
 * An agent asked the user to link another environment. The user picks the
 * access; the pairing code never passes through orchestration, so the item
 * carries only what was asked and how it ended.
 */
const OrchestrationV2LinkRequestFields = {
  type: Schema.Literal("link_request"),
  /** The address the agent named, if it named one. */
  url: Schema.optional(TrimmedNonEmptyString),
  reason: Schema.String,
  /**
   * The environment the agent named, or the one answering at `url`. Without
   * either the user picks the machine in the card.
   */
  environmentId: Schema.optional(EnvironmentId),
  label: Schema.optional(Schema.String),
  /** A phrase from the user's words, such as "vps", that preselects a machine. */
  hint: Schema.optional(Schema.String),
  /** The access the agent suggested; the user's choice is final. */
  requestedAccess: Schema.optional(AuthMcpClientAccess),
  linkStatus: OrchestrationV2LinkRequestStatus,
  linkedEnvironmentId: Schema.optional(EnvironmentId),
  linkedLabel: Schema.optional(Schema.String),
  linkedAccess: Schema.optional(AuthMcpClientAccess),
  failure: Schema.optional(Schema.String),
} as const;

export const OrchestrationV2TurnItem = Schema.Union([
  Schema.Struct({
    ...OrchestrationV2TurnItemBaseFields,
    type: Schema.Literal("notification"),
    ...OrchestrationV2Notification.fields,
  }),
  Schema.Struct({
    ...OrchestrationV2TurnItemBaseFields,
    ...OrchestrationV2CreationFields,
    type: Schema.Literal("user_message"),
    messageId: MessageId,
    scheduledTaskId: Schema.optional(ScheduledTaskId),
    senderThreadId: Schema.optional(ThreadId),
    idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
    workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript,
    freshContext: OrchestrationV2Run.fields.freshContext,
    inputIntent: OrchestrationV2UserMessageInputIntent,
    text: Schema.String,
    /** Same as the text of message `messageId`. */
    textOmitted: DedupedBodyMarker,
    context: Schema.optional(OrchestrationMessageContext),
    attachments: Schema.Array(ChatAttachment),
    modelSwitch: Schema.optional(OrchestrationV2ModelSwitch),
  }),
  Schema.Struct({
    ...OrchestrationV2TurnItemBaseFields,
    type: Schema.Literal("assistant_message"),
    messageId: MessageId,
    text: Schema.String,
    textOmitted: DedupedBodyMarker,
    attachments: Schema.optional(Schema.Array(ChatAttachment)),
    streaming: Schema.Boolean,
  }),
  Schema.Struct({
    ...OrchestrationV2TurnItemBaseFields,
    type: Schema.Literal("reasoning"),
    text: Schema.String,
    streaming: Schema.Boolean,
  }),
  Schema.Struct({
    ...OrchestrationV2TurnItemBaseFields,
    type: Schema.Literal("proposed_plan"),
    planId: PlanId,
    markdown: Schema.String,
    streaming: Schema.Boolean,
  }),
  Schema.Struct({
    ...OrchestrationV2TurnItemBaseFields,
    type: Schema.Literal("todo_list"),
    planId: PlanId,
    steps: Schema.Array(OrchestrationV2PlanStep),
    explanation: Schema.optional(Schema.String),
  }),
  Schema.Struct({
    ...OrchestrationV2TurnItemBaseFields,
    type: Schema.Literal("user_input_request"),
    requestId: RuntimeRequestId,
    questions: Schema.Array(OrchestrationV2UserInputQuestion),
    questionAnswer: Schema.optional(UserInputAttachmentAnswerPayload),
    responseMode: Schema.optional(Schema.Literal("message")),
  }),
  Schema.Struct({
    ...OrchestrationV2TurnItemBaseFields,
    type: Schema.Literal("file_change"),
    fileName: TrimmedNonEmptyString,
    additions: Schema.optional(NonNegativeInt),
    deletions: Schema.optional(NonNegativeInt),
    diffStr: Schema.optional(Schema.String),
    oldStr: Schema.optional(Schema.String),
    newStr: Schema.optional(Schema.String),
    changes: Schema.optional(Schema.Array(OrchestrationV2FileChangeDetail)),
  }),
  Schema.Struct({
    ...OrchestrationV2TurnItemBaseFields,
    type: Schema.Literal("command_execution"),
    input: Schema.String,
    output: Schema.optional(Schema.String),
    /** Set on the wire when output was withheld; fetch it with getTurnItem. */
    outputOmitted: Schema.optional(Schema.Boolean),
    outputIndicatesFailure: Schema.optional(Schema.Boolean),
    exitCode: Schema.optional(Schema.Int),
    /** Set when the command is a monitor, so background work lists it as a monitor. */
    monitor: Schema.optional(Schema.Boolean),
  }),
  Schema.Struct({
    ...OrchestrationV2TurnItemBaseFields,
    type: Schema.Literal("file_search"),
    pattern: Schema.optional(Schema.String),
    results: Schema.optional(Schema.Array(OrchestrationV2FileSearchResult)),
  }),
  Schema.Struct({
    ...OrchestrationV2TurnItemBaseFields,
    type: Schema.Literal("web_search"),
    patterns: Schema.optional(Schema.Array(Schema.String)),
    results: Schema.optional(Schema.Array(OrchestrationV2WebSearchResult)),
  }),
  Schema.Struct({
    ...OrchestrationV2TurnItemBaseFields,
    type: Schema.Literal("approval_request"),
    requestId: RuntimeRequestId,
    requestKind: ProviderRequestKind,
    prompt: Schema.optional(Schema.String),
    reason: Schema.optional(Schema.String),
    fullAccessOverride: Schema.optional(ProviderApprovalFullAccessOverride),