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
2 changes: 2 additions & 0 deletions apps/server/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ export class ServerConfig extends Context.Service<
readonly lazurioFolder?: string;
/** The Buddy folder beside the Folder, declared with it (`T3CODE_LAZURIO_BUDDY_FOLDER`). */
readonly lazurioBuddyFolder?: string;
/** Buddy's window's own origin, routed to this server (`T3CODE_LAZURIO_BUDDY_ORIGIN`). */
readonly lazurioBuddyOrigin?: string;
readonly lazurioToolsUrl?: string;
readonly baseDir: string;
readonly staticDir: string | undefined;
Expand Down
28 changes: 17 additions & 11 deletions apps/server/src/lazurio/buddyPrompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,23 +189,29 @@ describe("the projection a provider turn gets", () => {
}).pipe(Effect.provideService(HostProcess.Environment, BUDDY_ENV)),
);

it.effect("is upstream's for another instance of Buddy's T3 Code", () =>
// Only Buddy's window adds a page record, so its page block reaches any provider (GEN4).
it.effect(
"is Buddy's for a message with a page record on any instance, also without the switch",
() =>
Effect.gen(function* () {
for (const instanceId of [ProviderInstanceId.make("codex"), BUDDY]) {
const text = yield* projectComposerContextForProvider({ ...input, instanceId });
assert.strictEqual(text, buddyProviderText(input));
assert.include(text, "Kontext stránky");
}
}).pipe(Effect.provideService(HostProcess.Environment, { T3CODE_LAZURIO_BUDDY: "true" })),
);

it.effect("is upstream's for a message without a page record on any other instance", () =>
Effect.gen(function* () {
const plain = { text: "Ahoj", records: [] };
const text = yield* projectComposerContextForProvider({
...input,
...plain,
instanceId: ProviderInstanceId.make("codex"),
});
assert.strictEqual(text, projectUpstream(input));
assert.include(text, "<t3_context");
assert.strictEqual(text, projectUpstream(plain));
}).pipe(Effect.provideService(HostProcess.Environment, BUDDY_ENV)),
);

it.effect("is upstream's for an instance called buddy without the switch", () =>
Effect.gen(function* () {
const text = yield* projectComposerContextForProvider({ ...input, instanceId: BUDDY });
assert.strictEqual(text, projectUpstream(input));
}).pipe(Effect.provideService(HostProcess.Environment, { T3CODE_LAZURIO_BUDDY: "true" })),
);
});

// What reaches the agent: the repository's mock ACP agent stands in for Hermes and logs every
Expand Down
5 changes: 3 additions & 2 deletions apps/server/src/lazurio/buddyPrompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ export function buddyProviderText(input: {
}

/**
* The text a provider turn gets for a message: Buddy's projection for Buddy's instance, upstream's
* The text a provider turn gets for a message: Buddy's projection for Buddy's instance and for any
* message with a page record, which only Buddy's window adds (GEN4 on any provider); upstream's
* for every other.
*/
export const projectComposerContextForProvider = Effect.fn(
Expand All @@ -142,7 +143,7 @@ export const projectComposerContextForProvider = Effect.fn(
readonly records: ReadonlyArray<ComposerContextRecord>;
}) {
const environment = yield* HostProcess.Environment;
return isBuddyInstance(environment, input.instanceId)
return isBuddyInstance(environment, input.instanceId) || input.records.some(isPageRecord)
? buddyProviderText(input)
: projectUpstream(input);
});
Expand Down
31 changes: 25 additions & 6 deletions apps/server/src/lazurio/buddySurfaceDays.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts";
import { ActingSenders } from "./actingSenders.ts";
import { type ActingSendersRecord, personSeesMessage } from "./actingSenderVisibility.ts";
import { isBuddySurfaceEnvironment } from "./buddySurface.ts";
import { BUDDY_THREAD_ID } from "./buddySurfaceThread.ts";
import * as ServerConfig from "../config.ts";
import { ProjectStoreV2 } from "../orchestration-v2/ProjectStore.ts";
import { BUDDY_THREAD_ID, findSharedBuddyThread, sharedBuddyFolder } from "./buddySurfaceThread.ts";
import { authenticateOverlayRoute } from "./routeAuth.ts";

const BUDDY_DAYS_ROUTE = "/api/lazurio/buddy/days";
Expand Down Expand Up @@ -114,22 +116,39 @@ export const layer = HttpRouter.use((router) =>
// A handler sees only the request's context, so it takes the orchestrator from the layer's.
const orchestrator = yield* OrchestratorV2;
const senders = yield* ActingSenders;
const config = yield* ServerConfig.ServerConfig;
const projects = yield* ProjectStoreV2;
yield* router.add(
"GET",
BUDDY_DAYS_ROUTE,
Effect.gen(function* () {
yield* authenticateOverlayRoute(AuthOrchestrationReadScope);
if (!isBuddySurfaceEnvironment(yield* HostProcess.Environment))
return HttpServerResponse.jsonUnsafe({ error: "not-buddy" }, { status: 404 });
// GEN3: the server's one thread; GEN4: Buddy's thread of the shared server.
let threadId = BUDDY_THREAD_ID;
if (!isBuddySurfaceEnvironment(yield* HostProcess.Environment)) {
const buddyFolder = yield* sharedBuddyFolder.pipe(
Effect.provideService(ServerConfig.ServerConfig, config),
);
if (buddyFolder === undefined)
return HttpServerResponse.jsonUnsafe({ error: "not-buddy" }, { status: 404 });
const found = yield* findSharedBuddyThread(buddyFolder).pipe(
Effect.provideService(OrchestratorV2, orchestrator),
Effect.provideService(ProjectStoreV2, projects),
Effect.option,
);
const thread = Option.getOrUndefined(found)?.thread ?? null;
if (thread === null) return HttpServerResponse.jsonUnsafe({ days: [] });
threadId = thread.id;
}
const request = yield* HttpServerRequest.HttpServerRequest;
const timeZone = timeZoneOf(new URL(request.url, "http://local").searchParams.get("tz"));
const shell = yield* orchestrator.getThreadShell(BUDDY_THREAD_ID).pipe(Effect.orDie);
const shell = yield* orchestrator.getThreadShell(threadId).pipe(Effect.orDie);
if (shell === null) return HttpServerResponse.jsonUnsafe({ days: [] });
const records = yield* orchestrator
.getThreadRecords(BUDDY_THREAD_ID, ["messages"], { messageRoles: ["user"] })
.getThreadRecords(threadId, ["messages"], { messageRoles: ["user"] })
.pipe(Effect.orDie);
// As the web without the record: every message shows.
const answer = yield* senders.read(BUDDY_THREAD_ID).pipe(Effect.option);
const answer = yield* senders.read(threadId).pipe(Effect.option);
const record = Option.match(answer, {
onNone: () => null,
onSome: ({ at, records }) => ({
Expand Down
118 changes: 117 additions & 1 deletion apps/server/src/lazurio/buddySurfaceThread.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@ import * as NodeOS from "node:os";
import * as NodePath from "node:path";

import { assert, describe, it } from "@effect/vitest";
import { CommandId, ProjectId } from "@t3tools/contracts";
import { CommandId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";

import * as ServerConfig from "../config.ts";
import * as ServerSettings from "../serverSettings.ts";

import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
import { BUDDY, addProject, layerBuddyServer } from "./buddySurface.testkit.ts";
Expand Down Expand Up @@ -203,4 +207,116 @@ describe("Buddy's thread", () => {
);
},
);

describe("on the shared Chat server (GEN4, LZD-0033 R3)", () => {
/** A managed Folder and a Buddy folder beside it, as the Environment declares them. */
const makeShared = () => {
const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "buddy-shared-home-"));
const folder = NodePath.join(home, "Lazurio");
const buddy = NodePath.join(home, "Buddy");
NodeFS.mkdirSync(folder);
NodeFS.mkdirSync(buddy);
return { home, folder, buddy };
};
const shared = (folder: string, buddy: string) =>
Effect.map(ServerConfig.ServerConfig, (config) => ({
...config,
lazurioFolder: folder,
lazurioBuddyFolder: buddy,
}));
const withShared = <A, E, R>(effect: Effect.Effect<A, E, R>, folder: string, buddy: string) =>
Effect.flatMap(shared(folder, buddy), (config) =>
effect.pipe(Effect.provideService(ServerConfig.ServerConfig, config)),
);

it.live("makes one thread in Buddy's project on the Environment's default model", () => {
const { home, folder, buddy } = makeShared();
return Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const settings = yield* ServerSettings.ServerSettingsService;
// No Environment default yet: the Lazurio project's model (the Platform's recommendation).
const recommended = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6.1-sol" };
yield* settings.updateSettings({
projectSettingsOverrides: {
[ProjectId.make("project:lazurio")]: { defaultModelSelection: recommended },
},
});
yield* addProject(ProjectId.make("project:lazurio"), folder);
yield* addProject(ProjectId.make("project:buddy"), buddy);
const [first, second] = yield* Effect.all(
[
withShared(resolveBuddyThread(), folder, buddy),
withShared(resolveBuddyThread(), folder, buddy),
],
{ concurrency: 2 },
);
assert.deepStrictEqual(second, first);
assert.strictEqual(first.projectId, "project:buddy");
const shell = yield* orchestrator.getThreadShell(first.threadId);
assert.deepStrictEqual(shell?.modelSelection, recommended);
assert.notStrictEqual(shell?.providerInstanceId, BUDDY);
const snapshot = yield* orchestrator.getShellSnapshot({
projectId: ProjectId.make("project:buddy"),
});
assert.lengthOf(snapshot.threads, 1);
}).pipe(
Effect.provide(Layer.merge(layerBuddyServer, ServerSettings.layerTest())),
Effect.scoped,
Effect.provideService(HostProcess.Environment, { HOME: home }),
);
});

it.live("adopts the thread the project already has, whatever its provider", () => {
const { home, folder, buddy } = makeShared();
return Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
yield* addProject(ProjectId.make("project:buddy"), buddy);
yield* orchestrator.dispatch({
type: "thread.create",
createdBy: "user",
creationSource: "web",
commandId: CommandId.make("test:pilot-thread"),
threadId: ThreadId.make("pilot-thread"),
projectId: ProjectId.make("project:buddy"),
title: "Buddy",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-model",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
});
assert.deepStrictEqual(yield* withShared(resolveBuddyThread(), folder, buddy), {
threadId: ThreadId.make("pilot-thread"),
projectId: ProjectId.make("project:buddy"),
});
}).pipe(
Effect.provide(Layer.merge(layerBuddyServer, ServerSettings.layerTest())),
Effect.scoped,
Effect.provideService(HostProcess.Environment, { HOME: home }),
);
});

it.live(
"answers no-project before the startup made Buddy's project, and not-buddy without one",
() => {
const { home, folder, buddy } = makeShared();
return Effect.gen(function* () {
const reason = (exit: Exit.Exit<unknown, unknown>) =>
Exit.isFailure(exit) ? JSON.stringify(exit.cause) : "succeeded";
assert.include(
reason(yield* Effect.exit(withShared(resolveBuddyThread(), folder, buddy))),
"no-project",
);
assert.include(reason(yield* Effect.exit(resolveBuddyThread())), "not-buddy");
}).pipe(
Effect.provide(Layer.merge(layerBuddyServer, ServerSettings.layerTest())),
Effect.scoped,
Effect.provideService(HostProcess.Environment, { HOME: home }),
);
},
);
});
});
117 changes: 116 additions & 1 deletion apps/server/src/lazurio/buddySurfaceThread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,16 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";

import { resolveProjectSettings } from "@t3tools/shared/projectSettings";

import * as ServerConfig from "../config.ts";
import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts";
import { ProjectStoreV2 } from "../orchestration-v2/ProjectStore.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import {
BUDDY_PROVIDER_INSTANCE_ID,
buddyProjectFolder,
Expand Down Expand Up @@ -96,13 +101,123 @@ const conflict = () =>
detail: `A thread with Buddy's id "${BUDDY_THREAD_ID}" is not in Buddy's project on the instance "${BUDDY_PROVIDER_INSTANCE_ID}".`,
});

/**
* Buddy GEN4 (plan LZD-0033, R3): on the shared Chat server Buddy's project is the one over the
* declared Buddy folder, and Buddy's thread is its oldest root thread. Archiving one is
* refused and the startup brings archived ones back, so this is the conversation the person had.
*/
const sharedBuddyProject = Effect.fn("LazurioBuddySurface.sharedBuddyProject")(function* (
buddyFolder: string,
) {
const projects = yield* (yield* ProjectStoreV2).list().pipe(Effect.mapError(unavailable));
const project = projects.find((candidate) => candidate.workspaceRoot === buddyFolder);
if (project === undefined)
return yield* new BuddyThreadUnavailable({
reason: "no-project",
detail: `Buddy's project ${buddyFolder} is not in this T3 Code yet.`,
});
return project;
});

/** Buddy's thread on the shared server: the oldest root thread of Buddy's project, if any. */
export const findSharedBuddyThread = Effect.fn("LazurioBuddySurface.findSharedThread")(function* (
buddyFolder: string,
) {
const project = yield* sharedBuddyProject(buddyFolder);
const { threads } = yield* (yield* OrchestratorV2)
.getShellSnapshot({ projectId: project.projectId })
.pipe(Effect.mapError(unavailable));
const roots = threads.filter(
(thread) =>
thread.projectId === project.projectId &&
thread.lineage.parentThreadId === null &&
thread.delegatedFrom === undefined,
);
const oldest = roots.toSorted(
(left, right) =>
DateTime.toEpochMillis(left.createdAt) - DateTime.toEpochMillis(right.createdAt),
)[0];
return { project, thread: oldest ?? null };
});

/**
* Buddy's thread on the shared server, made on the project's default model the first time anyone
* asks. Its id and command derive from the project, so two first visits make one thread.
*/
const resolveSharedBuddyThread = Effect.fn("LazurioBuddySurface.resolveSharedThread")(function* (
buddyFolder: string,
) {
const { project, thread } = yield* findSharedBuddyThread(buddyFolder);
if (thread !== null)
return { threadId: thread.id, projectId: project.projectId } satisfies BuddyThread;
const settingsService = yield* Effect.serviceOption(ServerSettingsService);
if (Option.isNone(settingsService))
return yield* new BuddyThreadUnavailable({
reason: "unavailable",
detail: "This T3 Code cannot read its settings for Buddy's first thread.",
});
const settings = yield* settingsService.value.getSettings.pipe(Effect.mapError(unavailable));
// Buddy's project's own model, else the Environment's default, else the Lazurio project's, where
// a hosted Environment keeps the Platform's recommended model (modelRecommendation.ts).
const folder = (yield* ServerConfig.ServerConfig).lazurioFolder;
const folderProject = (yield* (yield* ProjectStoreV2)
.list()
.pipe(Effect.mapError(unavailable))).find((candidate) => candidate.workspaceRoot === folder);
const modelSelection =
resolveProjectSettings(settings, project.projectId).settings.defaultModelSelection ??
(folderProject === undefined
? null
: resolveProjectSettings(settings, folderProject.projectId).settings.defaultModelSelection);
if (modelSelection === null)
return yield* new BuddyThreadUnavailable({
reason: "unavailable",
detail: "This Environment has no default model for Buddy's first thread.",
});
const threadId = ThreadId.make(`lazurio-buddy:${project.projectId}`);
const orchestrator = yield* OrchestratorV2;
yield* orchestrator
.dispatch({
type: "thread.create",
createdBy: "user",
creationSource: "server",
commandId: CommandId.make(`lazurio:buddy-thread:create:${project.projectId}`),
threadId,
projectId: project.projectId,
title: "Buddy",
modelSelection,
// Buddy works with the Osobní Prostředí's full rights (root decision 0210).
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
})
.pipe(Effect.mapError(unavailable));
const created = yield* orchestrator.getThreadShell(threadId).pipe(Effect.mapError(unavailable));
if (created === null)
return yield* new BuddyThreadUnavailable({
reason: "unavailable",
detail: "Buddy's thread was deleted.",
});
return { threadId, projectId: project.projectId } satisfies BuddyThread;
});

/** The Buddy folder of a shared server that declares one (GEN4), or undefined. */
export const sharedBuddyFolder = Effect.map(ServerConfig.ServerConfig, (config) =>
typeof config.lazurioFolder === "string" && typeof config.lazurioBuddyFolder === "string"
? config.lazurioBuddyFolder
: undefined,
);

/** Buddy's thread, made in Buddy's project the first time anyone asks. */
export const resolveBuddyThread = Effect.fn("LazurioBuddySurface.resolveThread")(function* () {
if (!isBuddySurfaceEnvironment(yield* HostProcess.Environment))
if (!isBuddySurfaceEnvironment(yield* HostProcess.Environment)) {
const buddyFolder = yield* sharedBuddyFolder;
if (buddyFolder !== undefined) return yield* resolveSharedBuddyThread(buddyFolder);
return yield* new BuddyThreadUnavailable({
reason: "not-buddy",
detail: "This T3 Code is not Buddy's.",
});
}
const orchestrator = yield* OrchestratorV2;
const project = yield* buddyProject();
const existing = yield* orchestrator
Expand Down
Loading
Loading