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
1 change: 1 addition & 0 deletions apps/server/src/kin/chat/KinChatRepository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,7 @@ describe("KinChatRepository", () => {
assert.deepStrictEqual(Option.getOrThrow(yield* repo.getAgent({ orgId, agentId })), {
...agent,
retiredAt: null,
pausedAt: null,
});
assert.deepStrictEqual(yield* repo.listAgents({ orgId }), [{ ...agent, retiredAt: null }]);
assert.deepStrictEqual(
Expand Down
11 changes: 8 additions & 3 deletions apps/server/src/kin/chat/KinChatRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,10 @@ const AgentIdentityRow = Schema.Struct({
...KinAgent.fields,
retiredAt: Schema.NullOr(IsoDateTime),
});
const AgentActivityRow = Schema.Struct({
...AgentIdentityRow.fields,
pausedAt: Schema.NullOr(IsoDateTime),
});
const agentColumns = `agent_id AS "agentId", org_id AS "orgId", display_name AS "displayName", role AS "role", owner_person_id AS "ownerPersonId"`;
const ChatRow = KinChat;
const chatColumns = `org_id AS "orgId", chat_id AS "chatId", kind AS "kind", title AS "title", team_id AS "teamId", last_seq AS "lastSeq", last_message_at AS "lastMessageAt", created_at AS "createdAt", archived_at AS "archivedAt", lead_agent_id AS "leadAgentId"`;
Expand Down Expand Up @@ -547,7 +551,7 @@ export class KinChatRepository extends Context.Service<
) => Effect.Effect<Option.Option<KinPerson>, RepositoryError>;
readonly getAgent: (
input: Scope & { readonly agentId: KinAgentId },
) => Effect.Effect<Option.Option<typeof AgentIdentityRow.Type>, RepositoryError>;
) => Effect.Effect<Option.Option<typeof AgentActivityRow.Type>, RepositoryError>;
readonly getChat: (
input: Scope & { readonly chatId: KinChatId },
) => Effect.Effect<Option.Option<KinChat>, RepositoryError>;
Expand Down Expand Up @@ -990,9 +994,10 @@ const make = Effect.gen(function* () {
function (input: Scope & { readonly agentId: KinAgentId }) {
return SqlSchema.findOneOption({
Request: Schema.Unknown,
Result: AgentIdentityRow,
Result: AgentActivityRow,
execute: () =>
sql`SELECT ${sql.literal(agentColumns)}, retired_at AS "retiredAt" FROM kin_agents WHERE org_id = ${input.orgId} AND agent_id = ${input.agentId}`,
sql`SELECT ${sql.literal(agentColumns)}, retired_at AS "retiredAt", paused_at AS "pausedAt"
FROM kin_agents WHERE org_id = ${input.orgId} AND agent_id = ${input.agentId}`,
})(input).pipe(NodeSqliteClient.readOnly);
},
Effect.mapError(toRepositoryError("KinChatRepository.getAgent")),
Expand Down
61 changes: 38 additions & 23 deletions apps/server/src/kin/chat/KinIdentity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ export class KinIdentity extends Context.Service<
readonly resolveAgent: (
scope: McpInvocationScope,
) => Effect.Effect<AgentIdentity, IdentityError>;
/** Only the MCP roster lease can use an idle thread, never a tool caller. */
readonly admitUpkeep: (scope: McpInvocationScope) => Effect.Effect<void, IdentityError>;
/**
* The server's own identity for a running wake-up's lead, read from stored rows only: the
* running `kin_wakeups` row, its active agent thread and an unretired agent.
Expand Down Expand Up @@ -166,6 +168,29 @@ export class KinIdentity extends Context.Service<
).pipe(Effect.as(false)),
),
);
const activeAgent = Effect.fn("KinIdentity.activeAgent")(function* (
scope: McpInvocationScope,
) {
const caller = scope.thread;
if (caller === undefined || caller.subagent === true)
return yield* new KinChatError({
reason: "not_allowed",
message: "Kin agent identity required.",
});
const row = yield* repository.findAgentThread(caller.threadId);
if (Option.isNone(row) || row.value.endedAt !== null)
return yield* new KinChatError({
reason: "not_allowed",
message: "Kin agent thread is not active.",
});
const agent = yield* repository.getAgent(row.value);
if (Option.isNone(agent) || agent.value.retiredAt !== null)
return yield* new KinChatError({
reason: "not_allowed",
message: "Kin agent identity required.",
});
return { caller, thread: row.value, agent: agent.value };
});
return KinIdentity.of({
owner: { _tag: "person", orgId: owner.orgId, personId: owner.personId },
resolve: Effect.fn("KinIdentity.resolve")(function* (session) {
Expand Down Expand Up @@ -211,39 +236,29 @@ export class KinIdentity extends Context.Service<
return [{ _tag: "person", orgId: owner.orgId, personId: owner.personId }];
}),
resolveAgent: Effect.fn("KinIdentity.resolveAgent")(function* (scope) {
const caller = scope.thread;
if (caller === undefined || caller.subagent === true)
return yield* new KinChatError({
reason: "not_allowed",
message: "Kin agent identity required.",
});
const row = yield* repository.findAgentThread(caller.threadId);
if (Option.isNone(row) || row.value.endedAt !== null) {
return yield* new KinChatError({
reason: "not_allowed",
message: "Kin agent thread is not active.",
});
}
if (!(yield* repository.hasRunningWakeup({ ...row.value, caller })))
const { caller, thread, agent } = yield* activeAgent(scope);
if (!(yield* repository.hasRunningWakeup({ ...thread, caller })))
return yield* new KinChatError({
reason: "not_allowed",
message: "Kin wake-up is not running.",
});
const agent = yield* repository.getAgent(row.value);
if (Option.isNone(agent) || agent.value.retiredAt !== null)
return yield* new KinChatError({
reason: "not_allowed",
message: "Kin agent identity required.",
});
return {
_tag: "agent",
caller,
orgId: row.value.orgId,
agentId: agent.value.agentId,
ownerPersonId: agent.value.ownerPersonId,
orgId: thread.orgId,
agentId: agent.agentId,
ownerPersonId: agent.ownerPersonId,
threadId: caller.threadId,
};
}),
admitUpkeep: Effect.fn("KinIdentity.admitUpkeep")(function* (scope) {
const { agent } = yield* activeAgent(scope);
if (agent.pausedAt !== null)
return yield* new KinChatError({
reason: "not_allowed",
message: "Kin agent is paused.",
});
}),
agentForWakeup: Effect.fn("KinIdentity.agentForWakeup")(
function* (input) {
const rows = yield* sql<{
Expand Down
57 changes: 57 additions & 0 deletions apps/server/src/kin/host/cacheParts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import type { KinAgentId, KinOrgId, KinWakeupId } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/sql/SqlClient";

export interface CachePart {
readonly fingerprint: string;
readonly orgId: KinOrgId;
readonly agentId: KinAgentId;
readonly seat: "owner" | "confined";
readonly model: string;
}

export interface CacheUsage {
readonly read: number;
readonly written: number;
readonly input?: number;
}

const encodeUsage = Schema.encodeEffect(
Schema.fromJsonString(
Schema.Struct({
read: Schema.Number,
written: Schema.Number,
input: Schema.optionalKey(Schema.Number),
}),
),
);

export const recordUse = Effect.fn("KinCacheParts.recordUse")(function* (
part: CachePart,
turn: {
readonly wakeupId: KinWakeupId;
readonly startedAt: number;
readonly lastRequestAt: number;
readonly freshUsage?: CacheUsage;
},
) {
const sql = yield* SqlClient.SqlClient;
yield* sql.withTransaction(
Effect.gen(function* () {
const usage = turn.freshUsage === undefined ? null : yield* encodeUsage(turn.freshUsage);
const stamped = yield* sql`UPDATE kin_wakeups SET cache_part = ${part.fingerprint},
cache_request_started_at = ${turn.startedAt},
cache_measurement = ${usage}
WHERE org_id = ${part.orgId} AND agent_id = ${part.agentId} AND wakeup_id = ${turn.wakeupId}
AND kind = 'turn' AND cache_part IS NULL RETURNING wakeup_id`;
if (stamped.length === 0) return;
yield* sql`INSERT INTO kin_cache_parts (fingerprint, org_id, seat, agent_id, model,
last_request_at, last_turn_at) VALUES (${part.fingerprint}, ${part.orgId}, ${part.seat},
${part.agentId}, ${part.model}, ${turn.lastRequestAt}, ${turn.lastRequestAt})
ON CONFLICT(fingerprint) DO UPDATE SET
last_request_at = MAX(last_request_at, excluded.last_request_at),
last_turn_at = MAX(last_turn_at, excluded.last_turn_at)`;
}),
);
});
158 changes: 158 additions & 0 deletions apps/server/src/kin/host/cacheSessions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk";
import { assert, it } from "@effect/vitest";
import {
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
KinAgentId,
KinOrgId,
KinWakeupId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/sql/SqlClient";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";

import type { ClaudeAgentSdkQuerySession } from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
import { makeMigratedSqliteLayer } from "../persistence/migratedSqlite.testkit.ts";
import { KinCacheSessions } from "./cacheSessions.ts";
import type { CachePart } from "./cacheParts.ts";

const orgId = KinOrgId.make("tidewater");
const agentId = KinAgentId.make("zoya");
const threadId = ThreadId.make("kin:tidewater");
const model = "claude-haiku-5-5";
const headers = { Authorization: "Bearer invented-fixture" };

const layer = Layer.merge(KinCacheSessions.layer, makeMigratedSqliteLayer());

it.effect(
"keeps the normal queue acknowledgement, live observations and selected model distinct",
() =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const cache = yield* KinCacheSessions;
const at = "1970-01-01T00:00:00.000Z";
yield* sql`INSERT INTO kin_orgs VALUES (${orgId}, 'Tidewater Freight', ${at})`;
yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, access, created_at)
VALUES ('rhea', ${orgId}, 'rhea', 'Rhea', 'owner', ${at})`;
yield* sql`INSERT INTO kin_agents (agent_id, org_id, display_name, role, owner_person_id, created_at)
VALUES (${agentId}, ${orgId}, 'Zoya', 'lead', 'rhea', ${at})`;
yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, direct_key, last_seq, created_at)
VALUES ('rhea-zoya', ${orgId}, 'direct', 'rhea-zoya', 0, ${at})`;
yield* sql`INSERT INTO kin_leads (agent_id, org_id, name, level_since, models_json, worker_projects_json, owner_chat_id)
VALUES (${agentId}, ${orgId}, 'Zoya', 0, '{}', '[]', 'rhea-zoya')`;

const message = {
type: "stream_event",
event: {
type: "message_start",
message: { usage: { input_tokens: 1, cache_read_input_tokens: 31_000 } },
},
session_id: "native",
parent_tool_use_id: null,
} as SDKMessage;
const unused = Effect.die("not used by this test");
const query = yield* cache.observeQuery(
{
options: {
sessionId: "native",
model,
permissionMode: "default",
tools: [],
mcpServers: { "t3-code": { type: "http", url: "http://127.0.0.1/kin/mcp", headers } },
},
threadId,
seat: "owner",
block: {
type: "text",
text: "Fixture instructions",
cache_control: { type: "ephemeral", ttl: "1h" },
},
},
DEFAULT_SERVER_SETTINGS,
{
offer: (_message, queued) => Effect.sync(() => queued?.()),
messages: Stream.make(
{ ...message, event: { type: "message_start" } } as SDKMessage,
message,
),
setModel: () => Effect.void,
applyFlagSettings: () => unused,
setPermissionMode: () => unused,
renameSession: () => unused,
stopTask: () => unused,
backgroundTasks: () => unused,
mcpServerStatus: unused,
readMcpResource: () => unused,
mcpAuthenticate: () => unused,
mcpSubmitOAuthCallbackUrl: () => unused,
reconnectMcpServer: () => unused,
callMcpTool: () => unused,
listPermissionRules: unused,
interrupt: unused,
close: unused,
} satisfies ClaudeAgentSdkQuerySession,
);
yield* cache.observeList(
{
environmentId: EnvironmentId.make("tidewater"),
requestNamespace: "fixture",
issuedAt: 0,
client: undefined,
capabilities: new Set(),
thread: {
threadId,
providerSessionId: "provider-fixture",
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
},
},
headers.Authorization,
"fixture-roster",
);
const request = Effect.fn("CacheSessionsTest.offer")(function* (wakeupId: KinWakeupId) {
const timestamp = yield* Clock.currentTimeMillis;
yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, ended_at, status, event_ids, thread_id)
VALUES (${wakeupId}, ${orgId}, ${agentId}, ${model}, ${timestamp}, ${timestamp}, 'completed', '[]', ${threadId})`;
let queued = false;
yield* query.offer(
{
type: "user",
message: { role: "user", content: "Ready?" },
session_id: "native",
parent_tool_use_id: null,
},
() => {
queued = true;
},
);
yield* Stream.runDrain(query.messages);
yield* cache.recordTurn({ orgId, agentId, wakeupId, threadId, lastRequestAt: timestamp });
return queued;
});
assert.isTrue(yield* request(KinWakeupId.make("first")));
yield* TestClock.adjust("50 minutes");
yield* request(KinWakeupId.make("second"));
yield* TestClock.adjust("15 minutes");
cache.prune(yield* Clock.currentTimeMillis);
yield* request(KinWakeupId.make("third"));
const [part] = yield* sql<
CachePart & { at: number }
>`SELECT fingerprint, org_id AS "orgId", agent_id AS "agentId",
model, seat, last_request_at AS at FROM kin_cache_parts`;
assert.isDefined(part);
assert.equal(part!.at, yield* Clock.currentTimeMillis);
assert.isDefined(cache.current(part!, "{}", DEFAULT_SERVER_SETTINGS));
yield* query.setModel("another-claude-model");
assert.isUndefined(cache.current(part!, "{}", DEFAULT_SERVER_SETTINGS));
yield* request(KinWakeupId.make("different-model"));
const rows = yield* sql<{ model: string }>`SELECT model FROM kin_cache_parts ORDER BY model`;
assert.deepEqual(
rows.map((row) => row.model),
["another-claude-model", model],
);
}).pipe(Effect.provide(layer)),
);
Loading
Loading