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
6 changes: 3 additions & 3 deletions apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ const ThreadListTool = Tool.make("t3_thread_list", {

const ThreadReadTool = Tool.make("t3_thread_read", {
description:
"Read any thread by id. View `messages` (default) or `activity` (all items). Newest first; older: `beforePosition=earlierPosition`; from the start: `afterPosition=-1`, then `nextPosition`. Cut-off text: `itemId`, `textOffset=nextTextOffset`. Reading a child's final result marks it delivered. In your reply, name it as its `link` verbatim.",
"Read latest first: `messages` (default) or `activity` (all). Older: `beforePosition=earlierPosition`. From start: `afterPosition=-1`, then `nextPosition`. Resume text: `itemId`, `textOffset=nextTextOffset`. Reading a child's final result marks it delivered. Cite its exact `link`.",
parameters: OrchestratorMcpThreadReadInput,
success: OrchestratorMcpThreadReadResult,
failure: OrchestratorMcpFailure,
Expand All @@ -268,7 +268,7 @@ const ThreadReadTool = Tool.make("t3_thread_read", {

const ThreadUpdateTool = Tool.make("t3_thread_update", {
description:
"Update a thread; omit `threadId` for this one. When a founder must decide, review or approve, use `action:'request_decision'` with `decision`: the thread shows in their inbox until they reply there, `resolve_decision`, or settle. `action:'route'` refiles it with `inboxRouting`; a founder's or the shared inbox needs `inboxRouting.reason`. `rename` takes `title`; `regenerate_title`. `set_standing` takes `standing` (bot persona, or null for an ordinary thread). Workspace and branch cannot change here.",
"Default: this thread. Founder must decide/review/approve: `request_decision` with `decision`; stays in their inbox until reply, `resolve_decision` or settle. `route`: `inboxRouting`, `reason` for founder/shared. `rename`: `title`; `set_standing`: `standing`. Not workspace/branch.",
// Keeps the input's action/field check, which rebuilding the struct would drop.
parameters: ThreadMetadataMcpUpdateInput.mapFields(
Struct.assign({ environmentId: OrchestratorMcpEnvironmentTarget }),
Expand All @@ -285,7 +285,7 @@ const ThreadUpdateTool = Tool.make("t3_thread_update", {

const ThreadSendTool = Tool.make("t3_thread_send", {
description:
"Send a message to any thread. The target cannot run with broader modes than yours. `mode:'auto'` starts an idle thread, steers a running turn, or queues. `queue`: new turn. `steer`: mid-turn update. `restart`: interrupt and restart. `deliveryClass` overrides `mode`: `interrupt`, `steer_at_tool_boundary` (after the next tool result), `next_turn`, `when_idle` (once nothing runs), or `digest` (never starts a turn; rides with the next one, grouped by `digestCategory`). `coalesceKey` replaces an undelivered message with the same key; past `expiresAt` an undelivered one is dropped. A send to a finished child thread starts a fresh task and returns its `taskId`. In your reply, name it as its `link` verbatim.",
"Send within your modes. `auto` starts an idle thread, steers or queues. `queue`: new turn. `steer`: mid-turn. `restart`: interrupt and restart. `deliveryClass` overrides `mode`: `steer_at_tool_boundary` after the next tool result, `when_idle` when idle, `digest` with the next turn (never starts one), grouped by `digestCategory`. `coalesceKey` replaces undelivered matches. A finished child gets a new task and returns `taskId`. Cite its exact `link`.",
parameters: OrchestratorMcpThreadSendInput,
success: OrchestratorMcpThreadSendResult,
failure: OrchestratorMcpFailure,
Expand Down
10 changes: 5 additions & 5 deletions apps/server/src/mcp/toolkits/thread/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts";

const ThreadOrganizeTool = Tool.make("t3_thread_organize", {
description:
"Pin, snooze, settle, archive, or mark a thread unread. Omit `threadId` for this thread. `snooze` needs `snoozedUntil`. Settling this thread applies at turn end. A failed turn or queued message leaves it active.",
"Organize this thread by default. `snooze` needs `snoozedUntil`. Self-settle waits for turn end; failure or a queued message keeps it active.",
parameters: Schema.Struct({
environmentId: OrchestratorMcpEnvironmentTarget,
threadId: Schema.optional(ThreadId),
Expand Down Expand Up @@ -88,7 +88,7 @@ const QUEUE_READ_ACTIONS = ["list", "read"] as const;
const QueueTool = Tool.make("t3_queue", {
...commandTool,
description:
"Manage a thread's queued messages. Omit `threadId` for this thread. list: send order, paged by `cursor` and `limit`. read: up to 16,000 chars of one. edit: replace its `text`; attachments stay. cancel. reorder: before `beforeRunId`, or to the end with null. promote_to_steer: send it now as steering to active `targetRunId`. Entries show their `deliveryClass`, `coalesceKey` and `expiresAt`; a `digest` entry never starts a turn and goes out with the next one. Writes fail once the run is no longer queued.",
"Queue for this thread by default. `list`: send order (`cursor`, `limit`). `read`: up to 16,000 chars. `edit`: text only. `cancel`. `reorder`: before `beforeRunId` (null: end). `promote_to_steer`: into active `targetRunId`. Shows delivery metadata. Digests ride its next turn. Writes require a queued run.",
parameters: Schema.Struct({
action: Schema.Literals([
...QUEUE_READ_ACTIONS,
Expand Down Expand Up @@ -133,7 +133,7 @@ const question = Schema.Struct({
const PendingRequestTool = Tool.make("t3_pending_request", {
...commandTool,
description:
"Pending user questions in a thread. Omit `threadId` for this thread. list: their ids; approvals are not listed. read: one by `requestId`. respond: answer one with `answers`; this cannot approve a permission request.",
"User questions only (default: this thread). List IDs, read by `requestId`, respond with `answers`. No permission approvals.",
parameters: Schema.Struct({
action: Schema.Literals(["list", "read", "respond"]),
environmentId: OrchestratorMcpEnvironmentTarget,
Expand All @@ -159,7 +159,7 @@ const threadConfiguration = Schema.Struct({
const ThreadConfigureTool = Tool.make("t3_thread_configure", {
...commandTool,
description:
"Read a thread's provider, model, and modes, or set its provider, model, and options with `modelSelection`. Omit `threadId` for this thread. Permission modes stay. Values from `orchestrator_capabilities`.",
"Read provider, model and modes (default: this thread). Set provider, model and options via `modelSelection` from `orchestrator_capabilities`. Preserves permission modes.",
parameters: Schema.Struct({
environmentId: OrchestratorMcpEnvironmentTarget,
threadId: Schema.optional(ThreadId),
Expand All @@ -171,7 +171,7 @@ const ThreadConfigureTool = Tool.make("t3_thread_configure", {
const ThreadTransferTool = Tool.make("t3_thread_transfer", {
...commandTool,
description:
"Move context between threads. Omit `threadId` for this thread. fork: copy it from `sourcePoint` (default latest stable run) into a new thread with the same setup; no turn runs yet. merge_back: merge it from `sourcePoint` into a related `targetThreadId` in the same project. status: its context transfers.",
"Transfer context from this thread by default. `fork`: same setup, no turn. `merge_back`: related same-project `targetThreadId`. Both take `sourcePoint` (fork defaults to latest stable run). `status`: list transfers.",
parameters: Schema.Struct({
action: Schema.Literals(["fork", "merge_back", "status"]),
environmentId: OrchestratorMcpEnvironmentTarget,
Expand Down
12 changes: 9 additions & 3 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,12 +284,15 @@ function isClaudeEnvTruthy(value: string | undefined): boolean {
const CLAUDE_COMPACT_OUTPUT_RESERVE = 20_000;
const CLAUDE_COMPACT_FLOOR_GAP = 13_000;

function claudeCompactEffectiveWindow(contextWindow: number, modelMaxTokens: number | null): number {
function claudeCompactEffectiveWindow(
contextWindow: number,
modelMaxTokens: number | null,
): number {
const window = modelMaxTokens === null ? contextWindow : Math.min(modelMaxTokens, contextWindow);
return window - CLAUDE_COMPACT_OUTPUT_RESERVE;
}

export function claudeAutoCompactPercent(
function claudeAutoCompactPercent(
threadType: { readonly contextWindow: number; readonly compactAt: number },
modelMaxTokens: number | null = null,
): string {
Expand Down Expand Up @@ -2337,7 +2340,10 @@ export function makeClaudeQueryOptions(input: {
? {}
: {
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE: claudeAutoCompactPercent(
{ contextWindow: threadType.claudeContextWindow, compactAt: threadType.compactAt },
{
contextWindow: threadType.claudeContextWindow,
compactAt: threadType.compactAt,
},
modelMaxTokens,
),
CLAUDE_CODE_PROMPT_CACHE_TTL: threadType.cacheTtl,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1504,7 +1504,7 @@ const CODEX_T3_MCP_TOOL_TIMEOUT_SEC = 65 * 60;
const CODEX_T3_DIRECT_MCP_SERVER = "t3-code-direct";
const CODEX_DIRECT_ONLY_T3_TOOLS = ["t3_thread_wait", "delegate_task"];

export function codexThreadTypeConfig(
function codexThreadTypeConfig(
threadType: ProviderAdapter.ProviderAdapterV2RuntimePolicy["threadType"],
): Readonly<Record<string, Schema.Json>> {
return threadType === undefined
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/orchestration-v2/RuntimePolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export const layerEnforcingCeiling: Layer.Layer<
}),
);

export const applyThreadTypePolicy = Effect.fn("RuntimePolicyV2.applyThreadTypePolicy")(function* (
const applyThreadTypePolicy = Effect.fn("RuntimePolicyV2.applyThreadTypePolicy")(function* (
policyPath: string,
input: { readonly thread: OrchestrationV2AppThread; readonly modelSelection: ModelSelection },
) {
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/orchestration-v2/ThreadEventAlerts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ const openPullRequests = (shell: WatchedShell) =>
);

/** A pending task, a watching PR, a delegated task or a snooze that will bring the thread back. */
export function hasWakeHandle(shell: WatchedShell, remoteTaskCount: number, nowMs: number) {
function hasWakeHandle(shell: WatchedShell, remoteTaskCount: number, nowMs: number) {
if ((shell.pendingBackgroundTasks ?? []).length > 0) return true;
if (remoteTaskCount > 0) return true;
if ((shell.pullRequests ?? []).some((link) => link.watch !== undefined)) return true;
Expand Down Expand Up @@ -148,7 +148,7 @@ export interface StrandedQueue {
readonly queueHeld?: boolean;
}

export const strandedQueueSignature = (queue: StrandedQueue) => `stranded-queue:${queue.runId}`;
const strandedQueueSignature = (queue: StrandedQueue) => `stranded-queue:${queue.runId}`;
export const isStrandedQueueSignature = (signature: string) =>
signature.startsWith("stranded-queue:");

Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/orchestration-v2/ThreadSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ export function buildSearchSnippet(text: string, matchStart: number): string {
* among "people" but never Kameron's or Jeff's. A legacy scheduled-task prompt is known by its
* server-made id; a message the server stamped with a person's client is a person's regardless.
*/
export const messageSenderCondition = (
const messageSenderCondition = (
sql: SqlClient.SqlClient,
sender: OrchestrationSearchSenderFilter | null,
) => {
Expand Down
26 changes: 11 additions & 15 deletions apps/server/src/orchestration-v2/ThreadTypePolicy.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
import * as NodeOs from "node:os";
import * as NodeOS from "node:os";

import { isDelegatedAppThread, OrchestrationV2AppThread, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Schema from "effect/Schema";

export const THREAD_TYPE_POLICY_PATH_ENV = "T3_THREAD_TYPE_POLICY_PATH";
export const THREAD_TYPES = [
"standing",
"coding",
"review",
"research",
"ops",
"conversational",
] as const;
const THREAD_TYPE_POLICY_PATH_ENV = "T3_THREAD_TYPE_POLICY_PATH";
const THREAD_TYPES = ["standing", "coding", "review", "research", "ops", "conversational"] as const;
export type ThreadType = (typeof THREAD_TYPES)[number];

const ThreadTypeName = Schema.Literals(THREAD_TYPES);
Expand Down Expand Up @@ -78,7 +71,7 @@ export const isThreadTypeModelRefusedError = Schema.is(ThreadTypeModelRefusedErr

const TITLE_TAG = /^\s*\[([a-z]+)\]/i;

export function normalizeModel(model: string): string {
function normalizeModel(model: string): string {
let value = model.trim().toLowerCase();
const slash = value.lastIndexOf("/");
if (slash >= 0) value = value.slice(slash + 1);
Expand Down Expand Up @@ -134,7 +127,7 @@ export function resolveThreadTypeLaunch(
});
}

export const SUMMARY_CAP_CHARS_PER_TOKEN = 2;
const SUMMARY_CAP_CHARS_PER_TOKEN = 2;

export function carriedSummaryWithinCap(summaryCap: number, text: string): boolean {
return Math.ceil(text.length / SUMMARY_CAP_CHARS_PER_TOKEN) <= summaryCap;
Expand All @@ -152,7 +145,7 @@ export function threadTypePolicyPath(environment: NodeJS.ProcessEnv = process.en
const override = environment[THREAD_TYPE_POLICY_PATH_ENV];
return override !== undefined && override.length > 0
? override
: `${NodeOs.homedir()}/.config/closura/thread-type-policy.json`;
: `${NodeOS.homedir()}/.config/closura/thread-type-policy.json`;
}

const decodePolicy = Schema.decodeUnknownEffect(Schema.fromJsonString(ThreadTypePolicyFile));
Expand All @@ -162,13 +155,16 @@ const warnPolicyOnce = (path: string, state: string, message: string, detail?: u
const key = `${state}|${path}`;
if (policyWarningKeys.has(key)) return Effect.void;
policyWarningKeys.add(key);
return Effect.logWarning(message, detail === undefined ? { path, state } : { path, state, detail });
return Effect.logWarning(
message,
detail === undefined ? { path, state } : { path, state, detail },
);
};

const classifyRulesCompile = (policy: ThreadTypePolicyFile): boolean => {
for (const rule of policy.classify) {
try {
new RegExp(rule.title, "i");
void new RegExp(rule.title, "i");
} catch {
return false;
}
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/process/agentScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const GiB = 1024 ** 3;
* working. Small machines still give agents at least half of RAM before
* throttling and three quarters before a kill.
*/
export function agentSliceMemoryLimits(totalBytes: number, role: AgentHostRole = "headless") {
function agentSliceMemoryLimits(totalBytes: number, role: AgentHostRole = "headless") {
if (role === "interactive") {
// A person's computer keeps 4 GB or 40% for them before agents slow, and 3 GB or 30%
// before one is killed.
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/provider/servedModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function findServedModel<Model extends Pick<ServerProviderModel, "slug" |
);
}

export function servedModelsHint(models: ReadonlyArray<ListedModel>, requested: string): string {
function servedModelsHint(models: ReadonlyArray<ListedModel>, requested: string): string {
const lastSegment = (slug: string) => slug.slice(slug.lastIndexOf("/") + 1).toLowerCase();
const wanted = lastSegment(requested);
const close = models.filter((model) => lastSegment(model.slug) === wanted);
Expand Down
6 changes: 3 additions & 3 deletions apps/server/src/resourceTelemetry/MachinePresence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ function parseKeyValues(text: string): Map<string, string> {
}

/** The graphical login's state from logind; a session that cannot be read counts as in use. */
export function linuxSessionInUse(shown: string): boolean {
function linuxSessionInUse(shown: string): boolean {
const values = parseKeyValues(shown);
return !(
values.get("Active") === "no" ||
Expand All @@ -31,7 +31,7 @@ export function linuxSessionInUse(shown: string): boolean {
}

/** A login at this machine's own screen, not a remote or text session. */
export function isLocalGraphicalSession(shown: string): boolean {
function isLocalGraphicalSession(shown: string): boolean {
const values = parseKeyValues(shown);
const type = values.get("Type");
return (type === "x11" || type === "wayland" || type === "mir") && values.get("Remote") !== "yes";
Expand All @@ -46,7 +46,7 @@ type GraphicalLogin =
| { readonly kind: "session"; readonly shown: string }
| { readonly kind: "unknown" };

export const make = Effect.gen(function* () {
const make = Effect.gen(function* () {
const platform = yield* HostProcess.Platform;
const runner = yield* ProcessRunner.ProcessRunner;
const settingsService = yield* ServerSettings.ServerSettingsService;
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/components/bots/botPresence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export function splitStandingThreads<T extends { readonly standing: unknown }>(
}

/** A shared bot belongs to both founders; every other standing bot is one's own. */
export function isSharedBotThread(thread: {
function isSharedBotThread(thread: {
readonly source: { readonly inbox?: { readonly audience?: string } | null | undefined };
}): boolean {
return thread.source.inbox?.audience === "shared";
Expand Down
7 changes: 5 additions & 2 deletions apps/web/src/components/chat/MessagesTimeline.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2413,7 +2413,7 @@ const KEPT_ACTIVITY_ROW_KINDS = new Set<MessagesTimelineRow["kind"]>([
"viewed-images",
]);

export function timelineRowIsHumanConversation(row: MessagesTimelineRow): boolean {
function timelineRowIsHumanConversation(row: MessagesTimelineRow): boolean {
if (KEPT_ACTIVITY_ROW_KINDS.has(row.kind)) return true;
// A secret or a link is answered only on its own card, so it must not fold away.
if (
Expand All @@ -2434,7 +2434,10 @@ export function timelineRowIsHumanConversation(row: MessagesTimelineRow): boolea
* streaming in and earlier history loading above it. A live turn's own rows use
* constant ids that vanish when the turn settles, so they never anchor a pill.
*/
function activityPillId(anchor: MessagesTimelineRow | undefined, run: MessagesTimelineRow[]): string {
function activityPillId(
anchor: MessagesTimelineRow | undefined,
run: MessagesTimelineRow[],
): string {
return `activity:${anchor?.id ?? run[0]!.id}`;
}

Expand Down
6 changes: 3 additions & 3 deletions apps/web/src/state/linkedSidebar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ const linkedSidebarSupplementAtom = Atom.make((get) => {
return next;
}).pipe(Atom.keepAlive, Atom.withLabel("linked-sidebar:supplement"));

export const sidebarEnvironmentIdentitiesAtom = Atom.make((get) => {
const sidebarEnvironmentIdentitiesAtom = Atom.make((get) => {
const catalog = get(environmentSummaries.identitiesAtom);
const extra = get(linkedSidebarSupplementAtom).identities;
const next = extra.length === 0 ? catalog : [...catalog, ...extra];
Expand All @@ -82,7 +82,7 @@ export const sidebarEnvironmentIdentitiesAtom = Atom.make((get) => {
: next;
}).pipe(Atom.withLabel("linked-sidebar:identities"));

export const sidebarProjectsAtom = Atom.make((get) => {
const sidebarProjectsAtom = Atom.make((get) => {
const local = get(environmentProjects.projectsAtom);
const extra = get(linkedSidebarSupplementAtom).projects;
if (extra.length === 0) return local;
Expand All @@ -95,7 +95,7 @@ export const sidebarProjectsAtom = Atom.make((get) => {
: next;
}).pipe(Atom.withLabel("linked-sidebar:projects"));

export const sidebarThreadShellsAtom = Atom.make((get) => {
const sidebarThreadShellsAtom = Atom.make((get) => {
const local = get(environmentThreadShells.quietThreadShellsAtom);
const extra = get(linkedSidebarSupplementAtom).threads;
if (extra.length === 0) return local;
Expand Down
2 changes: 2 additions & 0 deletions evals/mcp-tool-use/backgroundWait.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import * as PeerLinkRequests from "../../apps/server/src/peer/PeerLinkRequests.t
import * as PeerLinks from "../../apps/server/src/peer/PeerLinks.ts";
import * as RemoteDelegation from "../../apps/server/src/peer/RemoteDelegation.ts";
import * as SqlitePersistence from "../../apps/server/src/persistence/Sqlite.ts";
import * as ProviderRegistryMock from "../../apps/server/src/provider/testUtils/providerRegistryMock.ts";
import * as ServerSettings from "../../apps/server/src/serverSettings.ts";

const threadId = ThreadId.make("mcp-tool-use-eval");
Expand Down Expand Up @@ -83,6 +84,7 @@ export const makeBackgroundWait = Effect.fn("evaluateMcpToolUse.makeBackgroundWa
Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
get: () => Effect.succeedSome(runtime),
}),
ProviderRegistryMock.layer(),
ServerSettings.layerTest(),
CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
),
Expand Down
Loading
Loading