Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/L
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
import { ChildThreadReactor } from "../src/orchestration/Services/ChildThreadReactor.ts";
import { GoalWaitReactor } from "../src/orchestration/Services/GoalWaitReactor.ts";
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
import { ThreadContextSeedBuilderLive } from "../src/provider/contextSeed/ThreadContextSeedBuilder.ts";
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
Expand Down Expand Up @@ -416,6 +417,12 @@ export const makeOrchestrationIntegrationHarness = (
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(GoalWaitReactor, {
start: () => Effect.void,
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(ThreadDiffStatBaselineReactor, {
start: () => Effect.void,
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/guide/topics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ While an agent works, the arrow beside the send button picks how a message goes:

After a reply to your message, Claude or Codex can suggest what you might send next: gray text in the empty message box, taken with Tab (Use on a phone), hidden with Escape. Claude makes its own and skips them when you're on track to run out of usage early, unless {place:threads.claudeSuggestions} is on. Codex's are made by Threadlines with one extra Codex answer each, only after messages you sent, never while a usage limit is 90% used, and {place:threads.codexSuggestions} turns them off.

A goal (type /goal and what to reach in the message box) keeps the agent working toward it across turns; the bar above the message box shows it, with pause, resume and clear. A Codex goal pauses by itself while the thread waits for your answer on a card or for threads it started to report back, so it doesn't spend turns asking whether you answered yet; the bar says why, and it carries on once the wait is over. Pausing, resuming or clearing it yourself in between is yours to keep. Claude's goals have no pause and carry on as before.

When Claude or Codex asks multiple-choice questions, a card takes the place of the message box. Besides answering, you can Skip a question, close the card with its X (the agent goes on without answers), or choose Reply in chat: the message box comes back, and the next message you send, text only, is your answer. The agent is told exactly which you did. Questions from other agents, such as a yes/no confirmation, still need an answer or Stop.

When a thread is done it wraps up and moves to the Wrapped shelf at the bottom of the sidebar; {place:threads.whenDone} says when that happens on its own. An agent coming back later (a check-back) doesn't keep a thread out of Wrapped: the thread returns to the list when the agent does. Old threads can be archived for you: {place:archived.cleanup}.
Expand Down
206 changes: 206 additions & 0 deletions apps/server/src/orchestration/Layers/GoalWaitReactor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
import { randomUUID } from "node:crypto";

import {
CommandId,
type OrchestrationEvent,
type OrchestrationThread,
type ThreadId,
} from "@threadlines/contracts";
import { makeDrainableWorker } from "@threadlines/shared/DrainableWorker";
import { goalWaitOf, goalWaitStep, turnAboutToStart } from "@threadlines/shared/goalWaitPause";
import { sessionSlotParticipantId } from "@threadlines/shared/threadParticipants";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";

import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ScheduledTasks } from "../../scheduled/ScheduledTasks.ts";
import { GoalWaitReactor, type GoalWaitReactorShape } from "../Services/GoalWaitReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";

const nowIso = Effect.map(DateTime.now, DateTime.formatIso);

/**
* Events that can change what a thread waits on, or its goal: its cards (the
* threads, settings, invites and commands its agent asked for), the threads
* it started, its queue and session (a turn about to start or running) and
* its goal.
* Everything else (streamed text, tool calls) leaves both alone.
*/
const WAIT_EVENT_PREFIXES = [
"thread.child-request",
"thread.child-requests-reset",
"thread.child-deliveries-cancelled",
"thread.remote-child-updated",
"thread.settings-change-",
"thread.agent-request",
"thread.command-request",
"thread.command-run-",
"thread.follow-up-",
"thread.session-set",
// A revert can take a waiting command card or its run away.
"thread.reverted",
// An agent leaving takes its invite and its requests with it.
"thread.participant-",
"thread.goal-state-set",
] as const;

const changesWait = (event: OrchestrationEvent): boolean =>
event.aggregateKind === "thread" &&
WAIT_EVENT_PREFIXES.some((prefix) => event.type.startsWith(prefix));

/**
* The user acted on the goal: paused, resumed, edited or cleared it, or
* pressed Stop. The decider sees most of these itself; a thread whose only
* wait is a scheduled-task card it can't see, so this says so.
*/
const userActedOnGoal = (event: OrchestrationEvent): boolean =>
(event.type === "thread.goal-set-requested" && event.payload.origin !== "automatic") ||
event.type === "thread.goal-clear-requested" ||
event.type === "thread.turn-interrupt-requested" ||
event.type === "thread.session-stop-requested";

/** What a look at a thread carries besides its state. */
interface SyncFlags {
readonly userActed: boolean;
readonly retryResume: boolean;
}

export const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
const scheduledTasks = yield* Effect.serviceOption(ScheduledTasks);

const scheduleWaiting = Option.isSome(scheduledTasks)
? scheduledTasks.value.waitingThreadIds
: Effect.succeed(new Set<ThreadId>() as ReadonlySet<ThreadId>);

/**
* Only a provider that can pause a goal gets one paused (Codex). Claude's
* goal is a hook inside one turn with no pause; the others have no goals.
*/
const canPauseGoal = (thread: OrchestrationThread) => {
const holderId = sessionSlotParticipantId(thread.session);
const instanceId =
thread.session?.providerInstanceId ??
thread.participants.find((entry) => entry.id === holderId)?.modelSelection.instanceId ??
thread.modelSelection.instanceId;
return providerService.getCapabilities(instanceId).pipe(
Effect.map(
(capabilities) =>
capabilities.threadGoals === "supported" &&
capabilities.threadGoalPause !== "unsupported",
),
Effect.orElseSucceed(() => false),
);
};

const syncThread = Effect.fn("GoalWaitReactor.syncThread")(function* (
threadId: ThreadId,
flags: SyncFlags,
) {
const thread = yield* projectionSnapshotQuery.getThreadDetailById(threadId).pipe(
Effect.map(Option.getOrUndefined),
Effect.orElseSucceed(() => undefined),
);
if (thread === undefined || thread.goal === null || thread.deletedAt !== null) return;
const scheduleAnswerWaiting = (yield* scheduleWaiting).has(threadId);
// The decider decides again, from the thread as it stands then; this
// only spares it a command when nothing would change.
const step = goalWaitStep({
goal: thread.goal,
waiting: goalWaitOf(thread, scheduleAnswerWaiting) !== null,
turnStarting: turnAboutToStart(thread),
userActed: flags.userActed,
retryResume: flags.retryResume,
});
// Forgetting a mark sends the provider nothing; a pause or resume needs
// a provider that has one.
if (step === null || (step.send !== null && !(yield* canPauseGoal(thread)))) return;
yield* orchestrationEngine
.dispatch({
type: "thread.goal.wait.sync",
commandId: CommandId.make(`goal-wait-sync:${threadId}:${randomUUID()}`),
threadId,
scheduleAnswerWaiting,
...(flags.userActed ? { userActed: true } : {}),
...(flags.retryResume ? { retryResume: true } : {}),
createdAt: yield* nowIso,
})
.pipe(
Effect.asVoid,
Effect.catchCause((cause) =>
Effect.logWarning("goal wait sync failed", { threadId, cause: Cause.pretty(cause) }),
),
);
});

// A thread already queued is looked at once, read as it stands then; the
// flags of every request for it in between add up.
const queued = new Map<ThreadId, SyncFlags>();
const worker = yield* makeDrainableWorker((threadId: ThreadId) =>
Effect.suspend(() => {
const flags = queued.get(threadId) ?? { userActed: false, retryResume: false };
queued.delete(threadId);
return syncThread(threadId, flags);
}),
);
const enqueue = (threadId: ThreadId, flags: Partial<SyncFlags> = {}) =>
Effect.suspend(() => {
const pending = queued.get(threadId);
const next = {
userActed: (pending?.userActed ?? false) || flags.userActed === true,
retryResume: (pending?.retryResume ?? false) || flags.retryResume === true,
};
queued.set(threadId, next);
return pending === undefined ? worker.enqueue(threadId) : Effect.void;
});

const start: GoalWaitReactorShape["start"] = Effect.fn("start")(function* () {
const events = yield* orchestrationEngine.subscribeDomainEvents;
yield* Effect.forkScoped(
Stream.runForEach(events, (event) =>
userActedOnGoal(event)
? enqueue(event.aggregateId as ThreadId, { userActed: true })
: changesWait(event)
? enqueue(event.aggregateId as ThreadId)
: Effect.void,
),
);
// A scheduled-task card shown or answered changes no thread event.
if (Option.isSome(scheduledTasks)) {
let previous: ReadonlySet<ThreadId> = yield* scheduleWaiting;
yield* Effect.forkScoped(
Stream.runForEach(scheduledTasks.value.changes.pipe(Stream.ignoreCause), () =>
Effect.gen(function* () {
const current = yield* scheduleWaiting;
const changed = [...current, ...previous].filter(
(threadId) => current.has(threadId) !== previous.has(threadId),
);
previous = current;
yield* Effect.forEach(changed, (threadId) => enqueue(threadId), { discard: true });
}),
),
);
}
// Cards answered or threads finished while the server was down, and a
// resume a restart cut off before the provider confirmed it.
const snapshot = yield* projectionSnapshotQuery
.getShellSnapshot()
.pipe(Effect.orElseSucceed(() => ({ threads: [] as const })));
yield* Effect.forEach(
snapshot.threads.filter((thread) => thread.goal !== null),
(thread) => enqueue(thread.id, { retryResume: true }),
{ discard: true },
);
});

return { start, drain: worker.drain } satisfies GoalWaitReactorShape;
});

export const GoalWaitReactorLive = Layer.effect(GoalWaitReactor, make);
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { afterEach, describe, expect, it } from "vite-plus/test";

import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ChildThreadReactor } from "../Services/ChildThreadReactor.ts";
import { GoalWaitReactor } from "../Services/GoalWaitReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
Expand All @@ -24,7 +25,7 @@ describe("OrchestrationReactor", () => {
runtime = null;
});

it("starts provider ingestion, provider command, child thread, checkpoint, thread deletion, and diff-stat baseline reactors", async () => {
it("starts provider ingestion, provider command, child thread, goal wait, checkpoint, thread deletion, and diff-stat baseline reactors", async () => {
const started: string[] = [];

runtime = ManagedRuntime.make(
Expand Down Expand Up @@ -58,6 +59,15 @@ describe("OrchestrationReactor", () => {
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(GoalWaitReactor, {
start: () => {
started.push("goal-wait-reactor");
return Effect.void;
},
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(CheckpointReactor, {
start: () => {
Expand Down Expand Up @@ -96,6 +106,7 @@ describe("OrchestrationReactor", () => {
"provider-runtime-ingestion",
"provider-command-reactor",
"child-thread-reactor",
"goal-wait-reactor",
"checkpoint-reactor",
"thread-deletion-reactor",
"thread-diffstat-baseline-reactor",
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/orchestration/Layers/OrchestrationReactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from "../Services/OrchestrationReactor.ts";
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ChildThreadReactor } from "../Services/ChildThreadReactor.ts";
import { GoalWaitReactor } from "../Services/GoalWaitReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
Expand All @@ -16,6 +17,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;
const providerCommandReactor = yield* ProviderCommandReactor;
const childThreadReactor = yield* ChildThreadReactor;
const goalWaitReactor = yield* GoalWaitReactor;
const checkpointReactor = yield* CheckpointReactor;
const threadDeletionReactor = yield* ThreadDeletionReactor;
const threadDiffStatBaselineReactor = yield* ThreadDiffStatBaselineReactor;
Expand All @@ -25,6 +27,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
yield* providerCommandReactor.start();
// After the sessions the previous process left are settled.
yield* childThreadReactor.start();
yield* goalWaitReactor.start();
yield* checkpointReactor.start();
yield* threadDeletionReactor.start();
yield* threadDiffStatBaselineReactor.start();
Expand Down
16 changes: 16 additions & 0 deletions apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4154,6 +4154,20 @@ const make = Effect.gen(function* () {
if (!thread) {
return;
}
// A pause or resume Threadlines made for a wait goes out only while the
// goal still carries it: the user took the goal over, or the provider
// ended or blocked it, since it was decided (docs/design/goal-wait-pause.md).
if (event.payload.origin === "automatic") {
const goal = thread.goal;
const stillOurs =
event.payload.status === "paused"
? // Paused already: a resume of ours may still be on its way.
goal?.waitPause === "paused" && (goal.status === "active" || goal.status === "paused")
: goal?.waitPause === "resuming" && goal.status === "paused";
if (!stillOurs) {
return;
}
}
// Goals live provider-side, so the thread needs a live session before the
// goal RPC. Cold threads get their session started (or resumed) here. In a
// room the goal belongs to the agent holding the session slot. The
Expand Down Expand Up @@ -4226,6 +4240,8 @@ const make = Effect.gen(function* () {
threadId: goalHolderSessionKey,
modelSelection: goalModelSelection,
...(context !== undefined ? { context } : {}),
// A pause or resume for a wait (thread.goal.wait.sync) is ours, not the user's.
...(event.payload.origin !== undefined ? { origin: event.payload.origin } : {}),
...(event.payload.objective !== undefined
? { objective: event.payload.objective }
: resumed !== null
Expand Down
30 changes: 30 additions & 0 deletions apps/server/src/orchestration/Services/GoalWaitReactor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* GoalWaitReactor - pauses a thread's goal while the thread waits, and
* resumes it when the wait ends (docs/design/goal-wait-pause.md).
*
* Watches the events that change what a thread with a goal waits on (its
* cards, the threads it started, its session, its goal) and the scheduler's
* waiting cards, and sends `thread.goal.wait.sync` for each thread whose goal
* should change. The decider holds the rule; this only asks it at the right
* moments, and only for goals whose provider can pause one.
*
* @module GoalWaitReactor
*/
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type * as Scope from "effect/Scope";

export interface GoalWaitReactorShape {
/**
* Start watching, and bring every goal in line once (a restart may have
* left a card answered while the server was down).
*/
readonly start: () => Effect.Effect<void, never, Scope.Scope>;

/** Resolves once every thread queued so far has been looked at. For tests. */
readonly drain: Effect.Effect<void>;
}

export class GoalWaitReactor extends Context.Service<GoalWaitReactor, GoalWaitReactorShape>()(
"threadlines/orchestration/Services/GoalWaitReactor",
) {}
Loading
Loading