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
15 changes: 15 additions & 0 deletions apps/server/src/kin/KinServer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as Context from "effect/Context";
import * as Option from "effect/Option";
import { KinIdentity } from "./chat/KinIdentity.ts";
import { KinChatService } from "./chat/KinChatService.ts";
import { KinChatHub } from "./chat/KinChatHub.ts";

export type Services = KinIdentity | KinChatService;

export class KinServer extends Context.Service<
KinServer,
{
readonly services: Option.Option<Context.Context<Services>>;
readonly subscribeForViewer: Option.Option<KinChatHub["Service"]["subscribeForViewer"]>;
}
>()("t3/kin/KinServer") {}
9 changes: 7 additions & 2 deletions apps/server/src/kin/chat/KinChatRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,11 @@ export class KinChatRepository extends Context.Service<
input: Scope & KinChatHistoryInput & { readonly viewerMemberId?: KinMemberId },
) => Effect.Effect<KinChatHistoryResult, RepositoryError>;
readonly messagesAfter: (
input: ChatScope & { readonly afterSeq: typeof NonNegativeInt.Type; readonly limit: number },
input: ChatScope & {
readonly afterSeq: typeof NonNegativeInt.Type;
readonly limit: number;
readonly viewerMemberId?: KinMemberId;
},
) => Effect.Effect<ReadonlyArray<KinMessage>, RepositoryError>;
readonly insertWidget: (
input: Omit<KinWidget, "revision">,
Expand Down Expand Up @@ -1181,7 +1185,8 @@ const make = Effect.gen(function* () {
Result: MessageRow,
execute:
() => sql`SELECT ${sql.literal(messageColumns)} FROM kin_messages WHERE org_id = ${input.orgId}
AND chat_id = ${input.chatId} AND seq > ${request.afterSeq} ORDER BY seq LIMIT ${request.limit}`,
AND chat_id = ${input.chatId} AND seq > ${request.afterSeq}
AND (${input.viewerMemberId ?? null} IS NULL OR status NOT IN ('suggested', 'dismissed') OR author_member_id = ${input.viewerMemberId ?? null} OR EXISTS (SELECT 1 FROM kin_chat_members WHERE org_id = ${input.orgId} AND chat_id = ${input.chatId} AND member_id = ${input.viewerMemberId ?? null} AND role = 'owner')) ORDER BY seq LIMIT ${request.limit}`,
})(input).pipe(NodeSqliteClient.readOnly);
},
Effect.mapError(toRepositoryError("KinChatRepository.messagesAfter")),
Expand Down
75 changes: 74 additions & 1 deletion apps/server/src/kin/chat/KinChatService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,12 +381,86 @@ describe("KinChatService", () => {
);
}
assert.strictEqual(Option.getOrThrow(yield* repo.getChat(chat)).lastSeq, 0);
const question = yield* service.send(person, {
chatId: chat.chatId,
body: "Track this",
clientMessageId: "widget-question",
});
const widget = yield* service.upsertWidget(agent, {
chatId: chat.chatId,
type: "task",
state,
awaiting: [person.personId],
replyTo: question.messageId,
});
assert.strictEqual(
Option.getOrThrow(yield* repo.getMessage(widget)).replyTo,
question.messageId,
);
const humanWidget = yield* service.upsertWidget(person, {
chatId: chat.chatId,
type: "task",
state,
});
assert.include(
yield* service
.upsertWidget(agent, {
chatId: chat.chatId,
widgetId: humanWidget.widgetId,
revision: 1,
type: "task",
state,
})
.pipe(Effect.flip),
{ reason: "not_allowed" },
);
const sql = yield* SqlClient.SqlClient;
const otherId = KinAgentId.make("other");
const otherThread = ThreadId.make("other-thread");
yield* repo.insertAgent({
orgId: person.orgId,
agentId: otherId,
ownerPersonId: person.personId,
displayName: "Other",
role: "builder",
createdAt: timestamp,
});
const identity = yield* Identity.KinIdentity.pipe(Effect.provide(identityLayer));
yield* identity.registerAgentThread({
orgId: person.orgId,
agentId: otherId,
threadId: otherThread,
});
const other = yield* identity.resolveAgent({
...caller,
thread: { ...caller.thread!, threadId: otherThread },
});
yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, agent_id, role, joined_at) VALUES ('other-member', ${person.orgId}, ${chat.chatId}, 'agent', ${otherId}, 'member', ${timestamp})`;
assert.include(
yield* service
.upsertWidget(other, {
chatId: chat.chatId,
widgetId: widget.widgetId,
revision: 1,
type: "task",
state,
})
.pipe(Effect.flip),
{ reason: "not_allowed" },
);
for (const update of [{}, { revision: 1, replyTo: question.messageId }])
assert.include(
yield* service
.upsertWidget(agent, {
chatId: chat.chatId,
widgetId: widget.widgetId,
type: "task",
state,
...update,
})
.pipe(Effect.flip),
{ reason: "invalid_state" },
);
assert.strictEqual(widget.revision, 1);
assert.strictEqual(
Option.getOrThrow(yield* repo.getMessage(widget)).widgetId,
Expand Down Expand Up @@ -454,7 +528,6 @@ describe("KinChatService", () => {
closed: true,
});
assert.deepStrictEqual(yield* repo.listOpenWaiting(person), []);
const sql = yield* SqlClient.SqlClient;
yield* sql`UPDATE kin_widgets SET type = 'approval' WHERE org_id = ${person.orgId} AND widget_id = ${another.widgetId}`;
assert.include(
yield* Effect.flip(
Expand Down
60 changes: 54 additions & 6 deletions apps/server/src/kin/chat/KinChatService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,12 @@ type ServiceError = Repository.RepositoryError;
type SendInput = KinMessagesSendInput & { readonly intent?: KinAgentIntent };
type WidgetUpsertInput = {
readonly chatId: KinChatId;
readonly widgetId?: KinWidgetId;
readonly revision?: number;
readonly widgetId?: KinWidgetId | undefined;
readonly revision?: number | undefined;
readonly replyTo?: KinMessageId | undefined;
readonly type: string;
readonly state: unknown;
readonly awaiting?: ReadonlyArray<KinPersonId>;
readonly awaiting?: ReadonlyArray<KinPersonId> | undefined;
readonly closed?: boolean;
};
type WaitingInput = Pick<
Expand Down Expand Up @@ -88,6 +89,14 @@ export class KinChatService extends Context.Service<
input: KinChatsCreateDirectInput,
) => Effect.Effect<KinChat, ServiceError>;
readonly send: (identity: Caller, input: SendInput) => Effect.Effect<KinMessage, ServiceError>;
readonly read: (
identity: AgentIdentity,
input: {
readonly chatId: KinChatId;
readonly afterSeq?: number | undefined;
readonly limit?: number | undefined;
},
) => Effect.Effect<ReadonlyArray<KinMessage>, ServiceError>;
readonly history: (
identity: Caller,
input: KinChatHistoryInput,
Expand Down Expand Up @@ -115,6 +124,21 @@ export class KinChatService extends Context.Service<
}
>()("t3/kin/chat/KinChatService") {}

const decodeRead = Schema.decodeUnknownEffect(
Schema.Struct({
chatId: KinChatId,
afterSeq: Schema.optional(
Schema.Number.check(
Schema.isInt(),
Schema.isGreaterThanOrEqualTo(0),
Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),
),
),
limit: Schema.optional(
Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),
),
}),
);
const decodeChatId = Schema.decodeEffect(KinChatId);
const decodeMemberId = Schema.decodeEffect(KinMemberId);
const decodeMessageId = Schema.decodeEffect(KinMessageId);
Expand Down Expand Up @@ -157,7 +181,7 @@ const make = Effect.gen(function* () {
target: {
readonly orgId?: KinOrgId;
readonly chatId?: KinChatId;
readonly widgetId?: KinWidgetId;
readonly widgetId?: KinWidgetId | undefined;
},
) {
if ("_tag" in caller) return caller;
Expand Down Expand Up @@ -590,6 +614,8 @@ const make = Effect.gen(function* () {
const request = yield* decodeSend(input).pipe(Effect.mapError(() => invalidState));
const member = yield* memberFor(identity, request.chatId);
yield* canWrite(identity, member);
if (request.mentions !== undefined && request.mentions.length > 100)
return yield* invalidState;
if (
(identity._tag === "agent" && input.intent === undefined) ||
(identity._tag === "person" && input.intent !== undefined)
Expand All @@ -609,6 +635,17 @@ const make = Effect.gen(function* () {
clientId: { kind: "send", id: request.clientMessageId },
});
}, transaction),
read: Effect.fn("KinChatService.read")(function* (identity, input) {
const request = yield* decodeRead(input).pipe(Effect.mapError(() => invalidState));
const member = yield* memberFor(identity, request.chatId);
return yield* repo.messagesAfter({
orgId: identity.orgId,
chatId: request.chatId,
afterSeq: request.afterSeq ?? 0,
limit: request.limit ?? 50,
viewerMemberId: member.memberId,
});
}, transaction),
history: Effect.fn("KinChatService.history")(
function* (identity, input) {
identity = yield* identityFor(identity, input);
Expand Down Expand Up @@ -654,7 +691,7 @@ const make = Effect.gen(function* () {
intent: identity._tag === "agent" ? "answer" : null,
kind: "text",
mentions: [],
replyTo: null,
replyTo: input.replyTo ?? null,
widgetId: null,
clientId: null,
publish: false,
Expand Down Expand Up @@ -685,7 +722,18 @@ const make = Effect.gen(function* () {
repo.getWidget({ orgId: identity.orgId, widgetId: input.widgetId }),
);
if (existing.chatId !== input.chatId) return yield* notFound;
if (existing.type !== input.type || input.revision === undefined)
if (identity._tag === "agent") {
const anchor = yield* requireRecord(
repo.getMessage({ orgId: identity.orgId, messageId: existing.messageId }),
);
if (anchor.author._tag !== "agent" || anchor.author.memberId !== member.memberId)
return yield* notAllowed;
}
if (
existing.type !== input.type ||
input.revision === undefined ||
input.replyTo !== undefined
)
return yield* invalidState;
widget = yield* repo.updateWidget({
...existing,
Expand Down
26 changes: 14 additions & 12 deletions apps/server/src/kin/layer.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,17 @@
import * as Cause from "effect/Cause";
import * as KinEnabled from "./KinEnabled.ts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as HttpRouter from "effect/http/HttpRouter";
import * as Option from "effect/Option";
import * as KinChat from "./chat/layer.ts";
import { KinIdentity } from "./chat/KinIdentity.ts";
import { KinChatService } from "./chat/KinChatService.ts";
import { KinChatHub } from "./chat/KinChatHub.ts";

type Services = KinIdentity | KinChatService;

export class KinServer extends Context.Service<
KinServer,
{
readonly services: Option.Option<Context.Context<Services>>;
readonly subscribeForViewer: Option.Option<KinChatHub["Service"]["subscribeForViewer"]>;
}
>()("t3/kin/layer/KinServer") {}
import { KinServer, type Services } from "./KinServer.ts";
export { KinServer } from "./KinServer.ts";
import type * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as KinMcp from "./mcp/layer.ts";

// LEAD-5 supplies its runner here, using this root's identity rather than building another.
const lead: Layer.Layer<never, never, Services | KinChatHub> = Layer.empty;
Expand Down Expand Up @@ -74,3 +67,12 @@ const middleware = HttpRouter.middleware<{ provides: KinServer }>()(
).layer;

export const layer = middleware.pipe(Layer.provideMerge(runtime));

export const mcpLayer = (base: Parameters<typeof KinMcp.transport>[0]) => KinMcp.transport(base);
export const mcpRegistryLayer = <E, R>(
base: Layer.Layer<McpSessionRegistry.McpSessionRegistry, E, R>,
) =>
KinMcp.registry(base).pipe(
Layer.provideMerge(layer),
Layer.provide(SqlitePersistence.layerConfig),
);
Loading