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
4 changes: 4 additions & 0 deletions apps/server/evals/toolUse/cannedTools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,10 @@ export function makeCannedRoomHandlers(
outcome: "asked_user",
detail: "A card asks the user to accept the change.",
})),
secret_request: answer("secret_request", () => ({
outcome: "asked_user",
detail: "The user was asked on a card. A message arrives when they answer.",
})),
alert_assistants: answer("alert_assistants", () => ({
outcome: "no_receiver",
detail: "No assistant is set up to receive alerts.",
Expand Down

Large diffs are not rendered by default.

Large diffs are not rendered by default.

241 changes: 176 additions & 65 deletions apps/server/integration/replay/fixtures/revert-turn/claude.ndjson

Large diffs are not rendered by default.

43 changes: 21 additions & 22 deletions apps/server/integration/replay/fixtures/simple-turn/claude.ndjson

Large diffs are not rendered by default.

224 changes: 95 additions & 129 deletions apps/server/integration/replay/fixtures/subagent/claude.ndjson

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions apps/server/src/assistants/AssistantEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ const THREAD_CANCEL_REASON: Partial<Record<OrchestrationEvent["type"], string>>
/** An answered request, or one closed for it (its session stopped, its turn was interrupted). */
const requestCloseReason = (event: OrchestrationEvent): string => {
if (event.type === "thread.settings-change-requested") return "replaced";
if (event.type === "thread.secret-request-created") return "replaced";
if (event.type === "thread.secret-request-settled" && event.payload.ending === "cancelled") {
return "closed";
}
if (event.type === "thread.settings-change-settled" && event.payload.ending === "cancelled") {
return "closed";
}
Expand Down
20 changes: 20 additions & 0 deletions apps/server/src/auth/Layers/ServerSecretStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,23 @@ it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {
}).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
);

it.effect("removes a crashed write's leftover temp copy when it starts", () =>
Effect.gen(function* () {
const config = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.makeDirectory(config.secretsDir, { recursive: true });
const leftover = `${config.secretsDir}/session-signing-key.bin.0c1d.tmp`;
yield* fileSystem.writeFileString(leftover, "a plain copy");

const secretStore = yield* Effect.service(ServerSecretStore).pipe(
Effect.provide(ServerSecretStoreLive),
);

expect(yield* fileSystem.exists(leftover)).toBe(false);
expect(yield* secretStore.list("")).toEqual([]);
}).pipe(Effect.provide(Layer.merge(makeServerConfigLayer(), NodeServices.layer))),
);

it.effect("uses restrictive permissions for the secret directory and files", () =>
Effect.gen(function* () {
const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = [];
Expand All @@ -198,6 +215,9 @@ it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {
...fileSystem,
makeDirectory: () => Effect.void,
writeFile: () => Effect.void,
// `set` writes its temp file through an owner-only open.
open: () => Effect.succeed({ writeAll: () => Effect.void, sync: Effect.void } as never),
readDirectory: () => Effect.succeed([]),
rename: () => Effect.void,
chmod: (path, mode) =>
Effect.sync(() => {
Expand Down
24 changes: 23 additions & 1 deletion apps/server/src/auth/Layers/ServerSecretStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,21 @@ export const makeServerSecretStore = Effect.gen(function* () {
),
);

// A crash between `set`'s write and its rename leaves a plain copy behind
// under a temp name that `list` never shows: remove those before any write.
yield* fileSystem.readDirectory(serverConfig.secretsDir).pipe(
Effect.flatMap((entries) =>
Effect.forEach(
entries.filter((entry) => entry.endsWith(".tmp")),
(entry) => fileSystem.remove(path.join(serverConfig.secretsDir, entry)),
{ discard: true },
),
),
Effect.catch((cause) =>
Effect.logWarning("couldn't remove leftover secret temp files", { cause }),
),
);

const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);

const isPlatformError = (u: unknown): u is PlatformError.PlatformError =>
Expand All @@ -54,7 +69,14 @@ export const makeServerSecretStore = Effect.gen(function* () {
const secretPath = resolveSecretPath(name);
const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`;
return Effect.gen(function* () {
yield* fileSystem.writeFile(tempPath, value);
// Private from the moment it exists, not narrowed after the write.
yield* Effect.scoped(
Effect.gen(function* () {
const file = yield* fileSystem.open(tempPath, { flag: "wx", mode: 0o600 });
yield* file.writeAll(value);
yield* file.sync;
}),
);
yield* fileSystem.chmod(tempPath, 0o600);
yield* fileSystem.rename(tempPath, secretPath);
yield* fileSystem.chmod(secretPath, 0o600);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ describe("CheckpointDiffQueryLive", () => {
listThreadTurnOverlapsSince: () => Effect.die("unused"),
listThreadIdsWithOpenAgentRequests: () => Effect.die("unused"),
listClaimedSettingsChanges: () => Effect.die("unused"),
listSecretRequests: () => Effect.die("unused"),
listThreadShells: () => Effect.succeed([]),
getThreadShellById: () => Effect.succeed(Option.none()),
getTurnActivities: () => Effect.succeed([]),
Expand Down Expand Up @@ -234,6 +235,7 @@ describe("CheckpointDiffQueryLive", () => {
listThreadTurnOverlapsSince: () => Effect.die("unused"),
listThreadIdsWithOpenAgentRequests: () => Effect.die("unused"),
listClaimedSettingsChanges: () => Effect.die("unused"),
listSecretRequests: () => Effect.die("unused"),
listThreadShells: () => Effect.succeed([]),
getThreadShellById: () => Effect.succeed(Option.none()),
getTurnActivities: () => Effect.succeed([]),
Expand Down Expand Up @@ -368,6 +370,7 @@ describe("CheckpointDiffQueryLive", () => {
listThreadTurnOverlapsSince: () => Effect.die("unused"),
listThreadIdsWithOpenAgentRequests: () => Effect.die("unused"),
listClaimedSettingsChanges: () => Effect.die("unused"),
listSecretRequests: () => Effect.die("unused"),
listThreadShells: () => Effect.succeed([]),
getThreadShellById: () => Effect.succeed(Option.none()),
getTurnActivities: () => Effect.succeed([]),
Expand Down Expand Up @@ -452,6 +455,7 @@ describe("CheckpointDiffQueryLive", () => {
listThreadTurnOverlapsSince: () => Effect.die("unused"),
listThreadIdsWithOpenAgentRequests: () => Effect.die("unused"),
listClaimedSettingsChanges: () => Effect.die("unused"),
listSecretRequests: () => Effect.die("unused"),
listThreadShells: () => Effect.succeed([]),
getThreadShellById: () => Effect.succeed(Option.none()),
getTurnActivities: () => Effect.succeed([]),
Expand Down Expand Up @@ -532,6 +536,7 @@ describe("CheckpointDiffQueryLive", () => {
listThreadTurnOverlapsSince: () => Effect.die("unused"),
listThreadIdsWithOpenAgentRequests: () => Effect.die("unused"),
listClaimedSettingsChanges: () => Effect.die("unused"),
listSecretRequests: () => Effect.die("unused"),
listThreadShells: () => Effect.succeed([]),
getThreadShellById: () => Effect.succeed(Option.none()),
getTurnActivities: () => Effect.succeed([]),
Expand Down Expand Up @@ -595,6 +600,7 @@ describe("CheckpointDiffQueryLive", () => {
listThreadTurnOverlapsSince: () => Effect.die("unused"),
listThreadIdsWithOpenAgentRequests: () => Effect.die("unused"),
listClaimedSettingsChanges: () => Effect.die("unused"),
listSecretRequests: () => Effect.die("unused"),
listThreadShells: () => Effect.succeed([]),
getThreadShellById: () => Effect.succeed(Option.none()),
getTurnActivities: () => Effect.succeed([]),
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/cli/marketingStudioSeed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ const makeServerConfig = (input: MarketingStudioSeedInput): ServerConfigShape =>
environmentIdPath: NodePath.join(stateDir, "environment-id"),
serverRuntimeStatePath: NodePath.join(stateDir, "server-runtime.json"),
secretsDir: NodePath.join(stateDir, "secrets"),
agentSecretsDir: NodePath.join(stateDir, "agent-secrets"),
speechModelsDir: NodePath.join(input.baseDir, "models", "speech"),
};
};
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ export interface ServerDerivedPaths {
readonly environmentIdPath: string;
readonly serverRuntimeStatePath: string;
readonly secretsDir: string;
/** Keys agents asked for, kept for their commands (docs/design/secret-requests.md). */
readonly agentSecretsDir: string;
/** Shared by dev and userdata: speech models are large and platform-wide. */
readonly speechModelsDir: string;
}
Expand Down Expand Up @@ -148,6 +150,7 @@ export const deriveServerPaths = Effect.fn(function* (
environmentIdPath: join(stateDir, "environment-id"),
serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
secretsDir: join(stateDir, "secrets"),
agentSecretsDir: join(stateDir, "agent-secrets"),
speechModelsDir: join(baseDir, "models", "speech"),
};
});
Expand Down
17 changes: 17 additions & 0 deletions apps/server/src/guide/topics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,23 @@ The art is walled off: it runs in a worker in a sandboxed frame with no network,
body: `An agent can change many settings when you ask: the theme, streaming replies, the model new threads start with, the writing model, which alerts you get, where links open and more (the guide says which, place by place). A model it picks starts at that model's default reasoning, and it can't pick a provider billed per use. It puts a card above the message box listing each change, from what to what, and where it lands: this computer's settings, or the app you accept it in, since settings like {place:appearance.theme} are kept by each app. Alert switches change only where alerts are on (a phone or a browser), and {place:general.openLinksIn} only in the desktop app; the card says so if you're somewhere else. Nothing changes until you press Change; Not now changes nothing. The agent hears how it went at its next turn. The theme can also be one from the theme library, by name; a theme new to that device starts as a trial with Keep and Undo (see \`themes\`).

Settings that give agents more reach ({place:threads.agentThreads}, {place:threads.enableRooms}, access levels, linked computers, plugins and sign-ins), that archive or delete threads, or that share data ({place:general.usageAnalytics}) are yours alone: an agent links them for you instead.`,
},
{
id: "secret-requests",
title: "Agents ask for keys on a card",
keywords: [
"api key",
"token",
"password",
"secret",
"env file",
".env",
"credentials",
"paste key",
],
body: `When an agent needs an API key, token or password, it asks on a card above the message box instead of in chat. The card shows the name, the agent's reason, and, in Threadlines' own words, where the key goes: a NAME=value line in a git-ignored env file in the thread's folder (like .env.local), or a private file for the agent's commands that is removed after 24 hours. Save sends it to the thread's computer; Not now saves nothing. The agent hears the outcome, never the value.

What this promises: Threadlines doesn't put the key in the chat, its stored events, logs or other apps. What it doesn't: the agent runs as you on that computer, so it can still read the file, and if it prints the key, the model sees it. A key pasted into chat is already in the conversation; replace it if that matters. Answering needs an encrypted connection to that computer. Archiving, moving or deleting the thread removes its private files, and a saved row for a private file has Remove now.`,
},
{
id: "updates",
Expand Down
5 changes: 4 additions & 1 deletion apps/server/src/mcp/McpHttpServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import * as PreviewAutomationBroker from "../preview/PreviewAutomationBroker.ts"
import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";
import { ProviderService } from "../provider/Services/ProviderService.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import { AgentSecretRequests } from "../secrets/AgentSecretRequests.ts";
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
import * as McpHttpServer from "./McpHttpServer.ts";
import { normalizeMcpHttpResponse } from "./McpHttpServer.ts";
Expand Down Expand Up @@ -147,7 +148,7 @@ describe("McpSessionRegistry", () => {
registry.credentialFor({ sessionKey: THREAD, browser: true, room: true, guideOnly: true }),
);
expect([...((await Effect.runPromise(registry.resolve(main.token)))?.roomTools ?? [])]).toEqual(
["app_guide", "settings_change", "alert_assistants"],
["app_guide", "settings_change", "secret_request", "alert_assistants"],
);
const side = await Effect.runPromise(
registry.credentialFor({
Expand Down Expand Up @@ -208,6 +209,7 @@ const roomServerStubs = (
Layer.succeed(ProviderRegistry, { getProviders: Effect.succeed([]) } as never),
Layer.succeed(ProviderService, { listSessions: () => Effect.succeed([]) } as never),
Layer.succeed(GitVcsDriver, {} as never),
Layer.succeed(AgentSecretRequests, { destinations: {} } as never),
ServerSettingsService.layerTest(settings),
PreviewAutomationBroker.layer,
);
Expand Down Expand Up @@ -453,6 +455,7 @@ describe("MCP endpoints", () => {
expect("tools" in result.guideOnlyRoom ? result.guideOnlyRoom.tools : []).toEqual([
"alert_assistants",
"app_guide",
"secret_request",
"settings_change",
]);
for (const listed of [result.browser, result.scheduledRunRoom]) {
Expand Down
15 changes: 15 additions & 0 deletions apps/server/src/mcp/McpRoomServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ import { offeredModels } from "../settingsChanges/modelChoices.ts";
import { makeSettingsChangeToolHandler } from "./settingsChangeToolHandlers.ts";
import { ThemeLibrary } from "../themes/ThemeLibrary.ts";
import { SettingsChangeToolkit } from "./settingsChangeTools.ts";
import { makeSecretRequestToolHandler } from "./secretRequestToolHandlers.ts";
import { SecretRequestToolkit } from "./secretRequestTools.ts";
import { AgentSecretRequests } from "../secrets/AgentSecretRequests.ts";
import { makeAlertAssistantsToolHandler } from "./alertAssistantsToolHandlers.ts";
import { AlertAssistantsToolkit } from "./alertAssistantsTools.ts";
import { AssistantAlerts } from "../assistants/AssistantAlerts.ts";
Expand All @@ -82,6 +85,7 @@ export const RoomEndpointToolkit = Toolkit.merge(
ScheduleToolkit,
GuideToolkit,
SettingsChangeToolkit,
SecretRequestToolkit,
AlertAssistantsToolkit,
);

Expand Down Expand Up @@ -119,6 +123,9 @@ const ROOM_TOOL_REACH = {
// Only shows a card on the caller's own thread, but asks to change app-wide
// settings: refused while outside work limits the caller.
settings_change: "changes",
// Only shows a card on the caller's own thread, and the key lands in its
// own folder or its own private file.
secret_request: "own",
// Only marks the caller's own turn, but sends word of it off this computer:
// refused while outside work limits the caller.
alert_assistants: "changes",
Expand Down Expand Up @@ -413,6 +420,13 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer(
)
: Effect.succeed([]),
});
const secretRequests = yield* AgentSecretRequests;
const secretRequest = makeSecretRequestToolHandler({
engine,
readThread,
threadFolder: secretRequests.threadFolder,
destinations: secretRequests.destinations,
});
const assistantAlerts = yield* Effect.serviceOption(AssistantAlerts);
const alertAssistants = makeAlertAssistantsToolHandler({
readThread,
Expand Down Expand Up @@ -511,6 +525,7 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer(
own("scheduled_run_finish", (scope) => scheduleHandlers.scheduled_run_finish(scope, input)),
settings_change: (input) =>
changes("settings_change", (scope) => settingsChange(scope, input)),
secret_request: (input) => own("secret_request", (scope) => secretRequest(scope, input)),
alert_assistants: () => changes("alert_assistants", alertAssistants),
// Listed only to runtimes granted it; a call from any other is refused
// too (a review runtime reads the checkout and nothing else). Refused
Expand Down
8 changes: 6 additions & 2 deletions apps/server/src/mcp/guideTools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@
import * as Schema from "effect/Schema";
import { Tool, Toolkit } from "effect/ai";

import { GUIDE_TOOL_NAME, SETTINGS_CHANGE_TOOL_NAME } from "./roomToolAccess.ts";
import {
GUIDE_TOOL_NAME,
SECRET_REQUEST_TOOL_NAME,
SETTINGS_CHANGE_TOOL_NAME,
} from "./roomToolAccess.ts";

export const AppGuideResult = Schema.Struct({
outcome: Schema.Literals(["ok", "no_match", "refused"]),
Expand Down Expand Up @@ -49,5 +53,5 @@ export function buildGuideInstructions(input: {
/** What precedes the tool's name for this provider. */
readonly toolPrefix: string;
}): string {
return `<threadlines_guide>\nYou run inside Threadlines, the app the user drives you from. Questions about it (its threads, settings, linked computers, what you can or can't do here and why) are answered by \`${input.toolPrefix}${GUIDE_TOOL_NAME}\`, which knows this computer's actual settings; your memory and the web don't. Call it directly, before answering, and link the places it names with the links it gives. To change a setting the user asks for, call \`${input.toolPrefix}${SETTINGS_CHANGE_TOOL_NAME}\`; they accept it on a card.\n</threadlines_guide>`;
return `<threadlines_guide>\nYou run inside Threadlines, the app the user drives you from. Questions about it (its threads, settings, linked computers, what you can or can't do here and why) are answered by \`${input.toolPrefix}${GUIDE_TOOL_NAME}\`, which knows this computer's actual settings; your memory and the web don't. Call it directly, before answering, and link the places it names with the links it gives. To change a setting the user asks for, call \`${input.toolPrefix}${SETTINGS_CHANGE_TOOL_NAME}\`; they accept it on a card. When you need an API key, token or password from the user, call \`${input.toolPrefix}${SECRET_REQUEST_TOOL_NAME}\`. Never ask them to paste one into chat.\n</threadlines_guide>`;
}
4 changes: 4 additions & 0 deletions apps/server/src/mcp/roomToolAccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,17 @@ export const GUIDE_TOOL_NAME = "app_guide";
/** Asking to change Threadlines settings, on a card the user answers (settingsChangeTools.ts). */
export const SETTINGS_CHANGE_TOOL_NAME = "settings_change";

/** Asking the user for a key on a private card (secretRequestTools.ts). */
export const SECRET_REQUEST_TOOL_NAME = "secret_request";

/** Alerting the user's assistants when the turn ends, when asked to (alertAssistantsTools.ts). */
export const ALERT_ASSISTANTS_TOOL_NAME = "alert_assistants";

/** The app's own tools: every local thread's own runtime gets them, room tools or not. */
export const APP_TOOL_NAMES = [
GUIDE_TOOL_NAME,
SETTINGS_CHANGE_TOOL_NAME,
SECRET_REQUEST_TOOL_NAME,
ALERT_ASSISTANTS_TOOL_NAME,
] as const;

Expand Down
Loading
Loading