Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
import { BACKGROUND_WAIT_STALE_MINUTES } from "@t3tools/contracts";
import {
staleTimeoutMs,
waitActivityMs,
waitIntentionallyHeld,
} from "../orchestration-v2/waitStaleness.ts";
import {
CommandId,
EnvironmentId,
Expand Down Expand Up @@ -2876,6 +2882,14 @@ const make = Effect.gen(function* () {
// delegations deliver through the blocking tool call until `awaitTask`
// gives up the wait (timeout, cancelled call) and upgrades the wake.
completionWake: input.mode === "wait" ? "settled_only" : "always",
...(input.mode === "wait"
? {
staleTimeoutMs: staleTimeoutMs(
input.staleTimeoutMinutes,
BACKGROUND_WAIT_STALE_MINUTES,
),
}
: {}),
})
.pipe(
Effect.mapError((error) =>
Expand Down Expand Up @@ -3721,7 +3735,29 @@ const make = Effect.gen(function* () {
: [];
const wakesCaller =
ownedTask && !childRequests.some((request) => request.status === "pending");
const progressShell =
result.timedOut && input.untilDelegatedWorkSettled === true
? yield* threadManagement
.getThreadShell(input.threadId)
.pipe(Effect.orElseSucceed(() => null))
: null;
const progress =
progressShell === null
? {}
: {
progressAtMs: Math.max(
waitActivityMs(progressShell),
yield* threadManagement
.getWaitActivityMs(progressShell.id, progressShell.latestRunId)
.pipe(Effect.orElseSucceed(() => 0)),
),
intentionallyHeld: waitIntentionallyHeld(
progressShell,
yield* Clock.currentTimeMillis,
),
};
return {
...progress,
threadId: input.threadId,
runId: result.run?.id ?? null,
status,
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/mcp/toolkits/orchestrator/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ const handlers = {
threadId: caller.thread.threadId,
taskIds: input.taskIds,
awaited: input.waiting ?? true,
staleTimeoutMinutes: input.staleTimeoutMinutes,
})
.pipe(
Effect.mapError(
Expand Down
6 changes: 4 additions & 2 deletions apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
StaleTimeoutMinutes,
OrchestratorMcpCapabilitiesInput,
OrchestratorMcpCapabilitiesResult,
OrchestrationV2StopWorkflowInput,
Expand Down Expand Up @@ -90,7 +91,7 @@ const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", {

const DelegateTaskTool = Tool.make("delegate_task", {
description:
"Start one child agent with only `task`. No parent history. Separate checkout or PR per child: `isolation:'worktree'`. Keep `taskId` for `task_status` and `task_cancel`. No secrets in `task`.",
"Start one child agent with only `task`. No parent history. Separate checkout or PR per child: `isolation:'worktree'`. Keep `taskId` for `task_status` and `task_cancel`. In `mode:'wait'`, T3 wakes the parent once per quiet period after 45 minutes without child activity. Change this with `staleTimeoutMinutes`. The separate `timeoutMs` limits only the tool call. No secrets in `task`.",
parameters: OrchestratorMcpDelegateTaskInput,
success: OrchestratorMcpDelegateTaskResult,
failure: OrchestratorMcpFailure,
Expand Down Expand Up @@ -147,13 +148,14 @@ const WorkflowStopTool = Tool.make("t3_workflow_stop", {

const BackgroundWaitTool = Tool.make("t3_background_wait", {
description:
"Keep this thread in Working while background work runs. Pass its task ID once started. Not for work left running (dev server, watcher). `waiting=false` clears. Doesn't stop tasks. Claude/OpenCode only.",
"Keep this thread in Working while background work runs. Pass its task ID once started. Not for work left running (dev server, watcher). `waiting=false` clears. Doesn't stop tasks. T3 wakes you once per quiet period after 45 minutes without progress. Set `staleTimeoutMinutes` to change the deadline. Claude/OpenCode only.",
parameters: Schema.Struct({
taskIds: Schema.Array(TrimmedNonEmptyString).check(
Schema.isMinLength(1),
Schema.isMaxLength(20),
),
waiting: Schema.optional(Schema.Boolean),
staleTimeoutMinutes: StaleTimeoutMinutes,
}),
success: Schema.Struct({
matched: Schema.Array(Schema.String),
Expand Down
21 changes: 14 additions & 7 deletions apps/server/src/mcp/toolkits/pullRequests/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,18 +199,25 @@ const make = Effect.gen(function* () {

// The domain service owns the registration span.
const setWatching = Effect.fnUntraced(function* (
input: PullRequestTargetInput,
input: PullRequestTargetInput & { readonly staleTimeoutMinutes?: number | undefined },
watching: boolean,
) {
const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests");
const threadId = input.threadId ?? scope.thread?.threadId;
if (threadId === undefined) return yield* new PullRequestThreadRequiredError();
return yield* watches.setWatching({ threadId, target: input, watching }).pipe(
Effect.catchTags({
PullRequestWatchThreadNotFoundError: (error) =>
threadNotFound(engine, scope, error.threadId, error.message),
}),
);
return yield* watches
.setWatching({
threadId,
target: input,
watching,
staleTimeoutMinutes: input.staleTimeoutMinutes,
})
.pipe(
Effect.catchTags({
PullRequestWatchThreadNotFoundError: (error) =>
threadNotFound(engine, scope, error.threadId, error.message),
}),
);
});

const locateAll = Effect.fn("PullRequestsToolkit.locateAll")(function* (
Expand Down
8 changes: 6 additions & 2 deletions apps/server/src/mcp/toolkits/pullRequests/tools.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
StaleTimeoutMinutes,
McpCapabilityUnavailableError,
OrchestratorMcpEnvironmentTarget,
OrchestratorMcpFailure,
Expand Down Expand Up @@ -326,8 +327,11 @@ const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", {

const WatchPullRequestTool = Tool.make("watch_pull_request", {
description:
"Watch an open PR for this thread, linking it first if needed. T3 wakes you on failed checks, passed required checks, new comments or reviews, or conflicts. Handle old comments first. Only later ones wake you. After this call, end your turn. The watch stays on after each wake, so do not call this again on a wake. A wake is not a merge decision. Check readiness yourself.",
parameters: PullRequestTargetInput,
"Watch an open PR for this thread, linking it first if needed. T3 wakes you on failed checks, passed required checks, new comments or reviews, or conflicts. Handle old comments first. Only later ones wake you. After this call, end your turn. The watch stays on after each wake, so do not call this again on a wake. A wake is not a merge decision. Check readiness yourself. T3 also wakes you once per quiet period after 30 minutes without progress. Set `staleTimeoutMinutes` to change that deadline.",
parameters: Schema.Struct({
...PullRequestTargetInput.fields,
staleTimeoutMinutes: StaleTimeoutMinutes,
}),
success: WatchPullRequestResult,
failure: PullRequestToolError,
dependencies: watchDependencies,
Expand Down
44 changes: 43 additions & 1 deletion apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6936,13 +6936,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
nativeThreadId: string,
task: OrchestrationV2PendingBackgroundTask,
) {
const now = yield* Clock.currentTimeMillis;
const startedMonitor = yield* Ref.modify(
pendingBackgroundTasksByNativeThread,
(current) => {
const roster = new Map(rosterForNativeThread(current, nativeThreadId));
const startedMonitor =
task.kind === "monitor" && roster.get(task.taskId)?.kind !== "monitor";
roster.set(task.taskId, task);
roster.set(task.taskId, startedMonitor ? { ...task, progressAtMs: now } : task);
return [startedMonitor, new Map(current).set(nativeThreadId, roster)] as const;
},
);
Expand Down Expand Up @@ -10633,6 +10634,40 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
return subagent?.task.status === "running" ? settled : null;
});

const backgroundTaskProgress = new Map<string, string>();
const recordBackgroundTaskProgress = Effect.fnUntraced(function* (
nativeThreadId: string,
message: Extract<SDKMessage, { type: "system"; subtype: "task_progress" }>,
) {
const signature = `${message.run_id ?? ""}:${message.usage.total_tokens}:${message.usage.tool_uses}:${message.summary ?? ""}`;
if (backgroundTaskProgress.get(message.task_id) === signature) return;
const now = DateTime.toEpochMillis(yield* DateTime.now);
const changed = yield* Ref.modify(pendingBackgroundTasksByNativeThread, (current) => {
const roster = current.get(nativeThreadId);
const task = roster?.get(message.task_id);
if (task === undefined) return [false, current] as const;
return [
true,
new Map(current).set(
nativeThreadId,
new Map(roster).set(message.task_id, { ...task, progressAtMs: now }),
),
] as const;
});
if (!changed) return;
backgroundTaskProgress.delete(message.task_id);
backgroundTaskProgress.set(message.task_id, signature);
for (const oldest of backgroundTaskProgress.keys()) {
if (backgroundTaskProgress.size <= 64) break;
backgroundTaskProgress.delete(oldest);
}
const active = yield* Ref.get(activeTurn);
yield* emitRosterUpdate(
nativeThreadId,
active?.nativeThreadId === nativeThreadId ? active : null,
);
});

const handleSdkMessageFrame = Effect.fnUntraced(function* (input: {
readonly query: ClaudeAgentSdkQuerySession;
readonly message: SDKMessage;
Expand Down Expand Up @@ -10665,6 +10700,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
}
return;
}
if (
message.type === "system" &&
message.subtype === "task_progress" &&
input.replayed !== true
) {
yield* recordBackgroundTaskProgress(liveQuery.nativeThreadId, message);
}
// Track before routing: idle-wake Monitors report tasks before replaying their tool calls.
yield* trackClaudeMonitorCalls(message);
yield* trackClaudeScheduledWakeup(liveQuery.nativeThreadId, message);
Expand Down
37 changes: 37 additions & 0 deletions apps/server/src/orchestration-v2/ModelAlertReactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1057,6 +1057,7 @@ export const make = Effect.gen(function* () {
const shell = yield* projections.getThreadShell(ThreadId.make(alert.threadId));
if (shell === null) return null;
const holds = threadEventStillHolds({
hasStalenessWait: yield* hasActiveStalenessWait(shell, REJUDGE_TRIGGER[alert.kind]),
alert,
shell,
stuckMinutes: (yield* settings.getSettings).watcherStuckMinutes,
Expand All @@ -1068,6 +1069,23 @@ export const make = Effect.gen(function* () {
});

/** What the shell does not carry: open delegated tasks elsewhere, and children's last activity. */
const hasActiveStalenessWait = Effect.fnUntraced(function* (
shell: OrchestrationV2ThreadShell,
trigger: ThreadEventTrigger,
) {
return (
trigger === "sweep" &&
shell.activeRunId !== null &&
((yield* projections.getThread(shell.id)).stalenessWaits ?? []).some(
(wait) =>
wait.kind === "delegate" ||
shell.pendingBackgroundTasks?.some(
(task) => task.taskId === wait.taskId && task.awaited === true,
),
)
);
});

const judgeContext = Effect.fnUntraced(function* (
shell: OrchestrationV2ThreadShell,
trigger: ThreadEventTrigger,
Expand Down Expand Up @@ -1474,6 +1492,7 @@ export const make = Effect.gen(function* () {
const nowMs = yield* Clock.currentTimeMillis;
const context = yield* judgeContext(shell, trigger, remoteTasks, queuedThreads);
const judged = judgeThread({
hasStalenessWait: yield* hasActiveStalenessWait(shell, trigger),
shell,
trigger,
nowMs,
Expand Down Expand Up @@ -1622,6 +1641,24 @@ export const make = Effect.gen(function* () {
yield* sweepResumes.pipe(
Effect.catchCause((cause) => Effect.logWarning("resume sweep failed", { cause })),
);
const now = yield* Clock.currentTimeMillis;
yield* Effect.forEach(
yield* projections.listStalenessWaitThreads,
(threadId) =>
engine
.dispatch({
type: "thread.wait-staleness.update",
commandId: CommandId.make(`server:wait-staleness:${threadId}:${now}`),
threadId,
operation: { type: "sweep" },
})
.pipe(
Effect.catchCause((cause) =>
Effect.logWarning("wait staleness sweep failed", { threadId, cause }),
),
),
{ discard: true },
);
const index = yield* projections.listActiveShellIndex();
const queuedThreads = new Set(yield* projections.getRecoveryThreadIds("queued-runs"));
// One scan of the delegated tasks for the whole sweep, not one per thread.
Expand Down
Loading
Loading