diff --git a/apps/server/src/kin/chat/KinChatRepository.test.ts b/apps/server/src/kin/chat/KinChatRepository.test.ts index dec105a747d7..b6d3fb2818d8 100644 --- a/apps/server/src/kin/chat/KinChatRepository.test.ts +++ b/apps/server/src/kin/chat/KinChatRepository.test.ts @@ -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( diff --git a/apps/server/src/kin/chat/KinChatRepository.ts b/apps/server/src/kin/chat/KinChatRepository.ts index a8e37e5de688..a1ac60d02e00 100644 --- a/apps/server/src/kin/chat/KinChatRepository.ts +++ b/apps/server/src/kin/chat/KinChatRepository.ts @@ -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"`; @@ -547,7 +551,7 @@ export class KinChatRepository extends Context.Service< ) => Effect.Effect, RepositoryError>; readonly getAgent: ( input: Scope & { readonly agentId: KinAgentId }, - ) => Effect.Effect, RepositoryError>; + ) => Effect.Effect, RepositoryError>; readonly getChat: ( input: Scope & { readonly chatId: KinChatId }, ) => Effect.Effect, RepositoryError>; @@ -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")), diff --git a/apps/server/src/kin/chat/KinIdentity.ts b/apps/server/src/kin/chat/KinIdentity.ts index 0d70a19dc5a3..b3679ebcaacb 100644 --- a/apps/server/src/kin/chat/KinIdentity.ts +++ b/apps/server/src/kin/chat/KinIdentity.ts @@ -112,6 +112,8 @@ export class KinIdentity extends Context.Service< readonly resolveAgent: ( scope: McpInvocationScope, ) => Effect.Effect; + /** Only the MCP roster lease can use an idle thread, never a tool caller. */ + readonly admitUpkeep: (scope: McpInvocationScope) => Effect.Effect; /** * 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. @@ -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) { @@ -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<{ diff --git a/apps/server/src/kin/host/cacheParts.ts b/apps/server/src/kin/host/cacheParts.ts new file mode 100644 index 000000000000..48b9fad860e3 --- /dev/null +++ b/apps/server/src/kin/host/cacheParts.ts @@ -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)`; + }), + ); +}); diff --git a/apps/server/src/kin/host/cacheSessions.test.ts b/apps/server/src/kin/host/cacheSessions.test.ts new file mode 100644 index 000000000000..f0e29780e9fa --- /dev/null +++ b/apps/server/src/kin/host/cacheSessions.test.ts @@ -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)), +); diff --git a/apps/server/src/kin/host/cacheSessions.ts b/apps/server/src/kin/host/cacheSessions.ts new file mode 100644 index 000000000000..fcb599a61f05 --- /dev/null +++ b/apps/server/src/kin/host/cacheSessions.ts @@ -0,0 +1,329 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- short synchronous hashes for the provider/MCP seam. +import * as NodeCrypto from "node:crypto"; +import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; +import type { + KinAgentId, + KinOrgId, + KinWakeupId, + ServerSettings, + ThreadId, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Stream from "effect/Stream"; + +import type { McpThreadInvocationScope } from "../../mcp/McpInvocationContext.ts"; +import type { + ClaudeAgentSdkQueryOpenInput, + ClaudeAgentSdkQueryOptions, + ClaudeAgentSdkQuerySession, +} from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; +import { KinServer } from "../KinServer.ts"; +import { instructionVersion } from "../lead/instructions.ts"; +import { recordUse, type CachePart, type CacheUsage } from "./cacheParts.ts"; + +export const CACHE_LIFETIME_MS = 60 * 60_000; +const hash = (value: string) => NodeCrypto.createHash("sha256").update(value).digest("hex"); +const hashJson = (value: unknown) => hash(JSON.stringify(value)); + +export type LeadingBlock = NonNullable; + +interface ObservedList { + readonly scope: McpThreadInvocationScope; + readonly sha: string; +} + +interface Observation { + readonly startedAt: number; + readonly usage: CacheUsage | undefined; +} + +interface Prepared { + readonly options: ClaudeAgentSdkQueryOptions; + readonly block: LeadingBlock; + readonly seat: CachePart["seat"]; + readonly threadId: ThreadId; + readonly authHash: string; + readonly configHash: string; + expiresAt: number; + model: string; + replayable: boolean; + observed: Observation | undefined; + offeredAt: number | undefined; + fresh: boolean; +} + +interface Lease extends ObservedList { + readonly token: string; + sessionId: string | undefined; + initializing: boolean; + readonly ready: Deferred.Deferred; +} + +interface WarmSession extends ObservedList { + readonly part: CachePart; + readonly options: ClaudeAgentSdkQueryOptions; + readonly block: LeadingBlock; + readonly modelsJson: string; + readonly configHash: string; + readonly expiresAt: number; +} + +const configHash = (settings: ServerSettings) => hash(JSON.stringify(settings.providerInstances)); + +const slot = ({ orgId, agentId, seat }: Pick) => + JSON.stringify([orgId, agentId, seat]); + +const measure = (message: SDKMessage) => { + if ( + message.type !== "stream_event" || + message.parent_tool_use_id !== null || + message.event?.type !== "message_start" + ) + return undefined; + const usage = message.event.message?.usage; + if (usage == null) return undefined; + return { + read: usage?.cache_read_input_tokens ?? 0, + written: usage?.cache_creation_input_tokens ?? 0, + input: usage?.input_tokens ?? 0, + }; +}; + +const make = () => { + const prepared = new Map(); + const lists = new Map(); + const sessions = new Map(); + const leases = new Map(); + + const prune = (now: number) => { + const expire = (map: Map) => { + for (const [key, value] of map) if (now >= value.expiresAt) map.delete(key); + }; + expire(prepared); + expire(lists); + expire(sessions); + }; + + return { + prune, + observeQuery: Effect.fn("KinCacheSessions.observeQuery")(function* ( + input: Omit< + Prepared, + | "authHash" + | "configHash" + | "expiresAt" + | "observed" + | "offeredAt" + | "fresh" + | "model" + | "replayable" + >, + settings: ServerSettings, + query: ClaudeAgentSdkQuerySession, + ) { + const servers = Object.entries(input.options.mcpServers ?? {}); + const server = servers[0]?.[1]; + const auth = server?.type === "http" ? server.headers?.Authorization : undefined; + if ( + servers.length !== 1 || + servers[0]?.[0] !== "t3-code" || + server?.type !== "http" || + auth === undefined + ) + return query; + const now = yield* Clock.currentTimeMillis; + prune(now); + const entry: Prepared = { + ...input, + options: { ...input.options, mcpServers: { "t3-code": { ...server, headers: {} } } }, + authHash: hash(auth), + configHash: configHash(settings), + model: input.options.model, + replayable: true, + expiresAt: now + CACHE_LIFETIME_MS, + observed: undefined, + offeredAt: undefined, + fresh: input.options.resume === undefined, + }; + prepared.set(input.threadId, entry); + const invalidate = Effect.sync(() => { + entry.replayable = false; + for (const [key, session] of sessions) + if (session.scope.thread.threadId === entry.threadId) sessions.delete(key); + }); + return { + ...query, + setModel: (model) => + (model === entry.model ? Effect.void : invalidate).pipe( + Effect.andThen(query.setModel(model)), + Effect.tap(() => + Effect.sync(() => { + entry.model = model; + }), + ), + ), + // In-place flags cannot safely be reconstructed as the original launch options. + applyFlagSettings: (flags) => + invalidate.pipe(Effect.andThen(query.applyFlagSettings(flags))), + offer: (message, onQueued) => + Clock.currentTimeMillis.pipe( + Effect.tap((at) => + Effect.sync(() => { + entry.offeredAt = at; + entry.expiresAt = at + CACHE_LIFETIME_MS; + entry.observed = undefined; + prepared.set(input.threadId, entry); + }), + ), + Effect.andThen(query.offer(message, onQueued)), + ), + messages: query.messages.pipe( + Stream.tap((message) => + Effect.sync(() => { + if (entry.offeredAt === undefined || entry.observed !== undefined) return; + const usage = measure(message); + if (usage === undefined) return; + entry.observed = { + startedAt: entry.offeredAt, + usage: entry.fresh ? usage : undefined, + }; + entry.fresh = false; + }), + ), + ), + } satisfies ClaudeAgentSdkQuerySession; + }), + observeList: (scope: McpThreadInvocationScope, auth: string, sha: string) => + Clock.currentTimeMillis.pipe( + Effect.map((now) => { + prune(now); + lists.set(scope.thread.threadId, { + scope, + sha, + authHash: hash(auth), + expiresAt: now + CACHE_LIFETIME_MS, + }); + }), + ), + recordTurn: Effect.fn("KinCacheSessions.recordTurn")(function* (row: { + readonly orgId: KinOrgId; + readonly agentId: KinAgentId; + readonly wakeupId: KinWakeupId; + readonly threadId: ThreadId; + readonly lastRequestAt: number | null; + }) { + const entry = prepared.get(row.threadId); + const roster = lists.get(row.threadId); + if ( + row.lastRequestAt === null || + entry === undefined || + entry.observed === undefined || + roster?.authHash !== entry.authHash + ) + return; + const observation = entry.observed; + entry.observed = undefined; + roster.expiresAt = Math.max(roster.expiresAt, row.lastRequestAt + CACHE_LIFETIME_MS); + const sql = yield* SqlClient.SqlClient; + const [lead] = yield* sql<{ modelsJson: string }>`SELECT models_json AS "modelsJson" + FROM kin_leads WHERE org_id = ${row.orgId} AND agent_id = ${row.agentId}`; + if (lead === undefined) return; + const part = { + orgId: row.orgId, + agentId: row.agentId, + seat: entry.seat, + model: entry.model, + fingerprint: hashJson([ + row.orgId, + row.agentId, + entry.seat, + roster.sha, + instructionVersion, + entry.model, + "leadingBlock", + entry.block, + ]), + } satisfies CachePart; + yield* recordUse(part, { + wakeupId: row.wakeupId, + startedAt: observation.startedAt, + lastRequestAt: row.lastRequestAt, + ...(observation.usage === undefined ? {} : { freshUsage: observation.usage }), + }); + if (!entry.replayable) return; + sessions.set(slot(part), { + part, + scope: roster.scope, + sha: roster.sha, + options: entry.options, + block: entry.block, + modelsJson: lead.modelsJson, + configHash: entry.configHash, + expiresAt: row.lastRequestAt + CACHE_LIFETIME_MS, + }); + }), + current: (part: CachePart, modelsJson: string, settings: ServerSettings) => { + const current = sessions.get(slot(part)); + return current?.modelsJson === modelsJson && current.configHash === configHash(settings) + ? current + : undefined; + }, + keep: (session: WarmSession, at: number) => { + const key = slot(session.part); + if (sessions.get(key) === session) + sessions.set(key, { ...session, expiresAt: at + CACHE_LIFETIME_MS }); + }, + lease: (session: ObservedList) => + Effect.acquireRelease( + Effect.sync(() => { + const token = NodeCrypto.randomBytes(32).toString("hex"); + const lease: Lease = { + token, + sessionId: undefined, + initializing: false, + scope: session.scope, + sha: session.sha, + ready: Deferred.makeUnsafe(), + }; + leases.set(token, lease); + return lease; + }), + ({ token }) => + Effect.sync(() => { + leases.delete(token); + }), + ), + lookup: (token: string) => leases.get(token), + }; +}; + +export class KinCacheSessions extends Context.Service>()( + "t3/kin/host/cacheSessions/KinCacheSessions", +) { + static readonly layer = Layer.sync(KinCacheSessions, make); +} + +export const cacheSessionsOf = (kin: KinServer["Service"] | undefined) => + Option.getOrUndefined( + Option.flatMap(kin?.services ?? Option.none(), (services) => + Context.getOption(services, KinCacheSessions), + ), + ); + +export const recordTurn = Effect.fn("KinSessionUpkeep.recordTurn")( + function* ( + row: { readonly orgId: KinOrgId; readonly agentId: KinAgentId; readonly wakeupId: KinWakeupId }, + threadId: ThreadId, + lastRequestAt: number | null, + ) { + const service = Option.getOrUndefined(yield* Effect.serviceOption(KinCacheSessions)); + if (service !== undefined) yield* service.recordTurn({ ...row, threadId, lastRequestAt }); + }, + Effect.catch(() => Effect.logWarning("Kin could not record cache-part use")), +); diff --git a/apps/server/src/kin/host/sessionUpkeep.test.ts b/apps/server/src/kin/host/sessionUpkeep.test.ts new file mode 100644 index 000000000000..04cd3b5ef477 --- /dev/null +++ b/apps/server/src/kin/host/sessionUpkeep.test.ts @@ -0,0 +1,521 @@ +import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; +import { assert, it } from "@effect/vitest"; +import { KinAgentId, KinChatId, KinOrgId, KinWakeupId, ThreadId } from "@t3tools/contracts"; +import * as Fiber from "effect/Fiber"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { KinChatRepository, layer as repositoryLayer } from "../chat/KinChatRepository.ts"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as TestClock from "effect/testing/TestClock"; + +import * as Budget from "../lead/KinBudget.ts"; +import * as Queue from "../lead/KinEventQueue.ts"; +import * as Hub from "../chat/KinChatHub.ts"; +import * as MemoryCache from "../memory/MemoryCache.ts"; +import * as CacheParts from "./cacheParts.ts"; +import * as Upkeep from "./sessionUpkeep.ts"; +import { collectPing, makePingRequest } from "./sessionUpkeepQuery.ts"; +import { makeMigratedSqliteLayer } from "../persistence/migratedSqlite.testkit.ts"; + +const minute = 60_000; +const now = 1_794_009_600_000; +const orgId = KinOrgId.make("tidewater"); +const agentId = KinAgentId.make("zoya"); +const threadId = ThreadId.make("kin:tidewater"); +const model = "claude-haiku-5-5"; +const part = { + orgId, + agentId, + seat: "owner" as const, + model, + fingerprint: "fixture-part", +}; + +const layer = Budget.layer.pipe( + Layer.provideMerge( + Layer.mergeAll(Queue.layer, MemoryCache.layer, Hub.layer).pipe( + Layer.provideMerge(repositoryLayer), + ), + ), + Layer.provideMerge(makeMigratedSqliteLayer()), +); + +const seed = Effect.fn("UpkeepTest.seed")(function* (gaps: ReadonlyArray) { + yield* TestClock.setTime(now); + const sql = yield* SqlClient.SqlClient; + 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')`; + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) + VALUES ('rhea-member', ${orgId}, 'rhea-zoya', 'person', 'rhea', 'owner', ${at})`; + let atMs = now - gaps.reduce((total, gap) => total + gap, 50) * minute; + for (const [i, gap] of [0, ...gaps].entries()) { + atMs += gap * minute; + const wakeupId = KinWakeupId.make(`turn-${i}`); + yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, ended_at, status, event_ids, thread_id, last_request_at) + VALUES (${wakeupId}, ${orgId}, ${agentId}, ${model}, ${atMs}, ${atMs}, 'completed', '[]', ${threadId}, ${atMs})`; + yield* CacheParts.recordUse(part, { + wakeupId, + startedAt: atMs, + lastRequestAt: atMs, + freshUsage: { + read: gap >= 60 ? 16_000 : 31_000, + written: gap >= 60 ? 19_000 : 4_000, + }, + }); + } +}); + +const usage = { read: 31_000, written: 100, input: 4, output: 1, cost: 0.008 }; +const miss = { read: 16_000, written: 19_000, input: 4, output: 1, cost: 0.16 }; +const run = ( + overrides: { + fingerprint?: string; + placement?: "leadingBlock" | "system"; + enabled?: boolean; + outcome?: { + status: "failed" | "completed"; + usage: (Omit & { cost: number | null }) | null; + }; + } = {}, +) => + Effect.gen(function* () { + const seen: string[] = []; + yield* Upkeep.check({ + enabled: overrides.enabled ?? true, + placement: overrides.placement ?? "leadingBlock", + current: () => overrides.fingerprint ?? part.fingerprint, + ping: (due) => + Effect.sync(() => { + seen.push(due.fingerprint); + return overrides.outcome ?? ({ status: "completed", usage } as const); + }), + }); + return seen; + }); + +it.effect.each([ + ["fewer than 20 gaps", Array(19).fill(65), {}, false], + ["50 minutes idle above threshold", Array(20).fill(65), {}, true], + ["changed fingerprint", Array(20).fill(65), { fingerprint: "another-part" }, false], + ["system placement", Array(20).fill(65), { placement: "system" as const }, false], + ["host switch off", Array(20).fill(65), { enabled: false }, false], + ["daily use with too few observations", Array(20).fill(24 * 60), {}, false], + [ + "no demand in the next 50 minutes despite enough samples", + Array(20).fill(180), + {}, + false, + ], +] as const)("uses only eligible gaps: %s", ([, gaps, options, due]) => + Effect.gen(function* () { + // A short sample supplies a measured warm read without reaching the 50-minute risk set. + const history = [10, ...gaps]; + yield* seed(history); + assert.deepEqual(yield* run(options), due ? [part.fingerprint] : []); + }).pipe(Effect.provide(layer)), +); + +it.effect( + "writes a detached upkeep row only for the active company, and leaves history and the queue unchanged", + () => + Effect.gen(function* () { + yield* seed([10, ...Array(20).fill(65)]); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_org_state (org_id, paused, paused_at, paused_by) + VALUES (${orgId}, 1, ${now}, 'rhea')`; + assert.deepEqual(yield* run(), []); + yield* sql`DELETE FROM kin_org_state WHERE org_id = ${orgId}`; + yield* sql`UPDATE kin_agents SET retired_at = '2026-11-09T00:00:00.000Z' WHERE agent_id = ${agentId}`; + assert.deepEqual(yield* run(), []); + yield* sql`UPDATE kin_agents SET retired_at = NULL WHERE agent_id = ${agentId}`; + assert.deepEqual(yield* run(), [part.fingerprint]); + const rows = yield* sql`SELECT thread_id, run_id, status, event_ids, tokens_json + FROM kin_wakeups WHERE kind = 'upkeep'`; + assert.deepEqual(rows, [ + { + thread_id: null, + run_id: null, + status: "completed", + event_ids: "[]", + tokens_json: JSON.stringify(usage), + }, + ]); + assert.deepEqual(yield* sql`SELECT last_seq FROM kin_chats`, [{ last_seq: 0 }]); + const repo = yield* KinChatRepository; + assert.isEmpty( + (yield* repo.history({ + orgId, + chatId: KinChatId.make("rhea-zoya"), + beforeSeq: 100, + limit: 30, + })).messages, + ); + assert.isEmpty(yield* sql`SELECT * FROM kin_events`); + assert.deepEqual(yield* run(), []); + }).pipe(Effect.provide(repositoryLayer.pipe(Layer.provideMerge(layer)))), +); + +it.effect("does not use another fingerprint's traffic and does not rewrite a dead cache", () => + Effect.gen(function* () { + yield* seed([10, ...Array(20).fill(65)]); + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE kin_wakeups SET cache_part = 'old-part' WHERE cache_part = ${part.fingerprint} AND wakeup_id = 'turn-21'`; + assert.deepEqual(yield* run(), []); + yield* sql`UPDATE kin_wakeups SET cache_part = ${part.fingerprint} WHERE cache_part = 'old-part'`; + yield* TestClock.adjust("9 minutes"); + assert.deepEqual(yield* run(), [part.fingerprint]); + yield* sql`UPDATE kin_cache_parts SET last_request_at = ${now - 50 * minute}`; + yield* TestClock.adjust("1 minute"); + assert.deepEqual(yield* run(), []); + }).pipe(Effect.provide(layer)), +); + +it.effect("accepts a measured cost exactly equal to the chance-weighted rewrite", () => + Effect.gen(function* () { + yield* seed([10, ...Array(8).fill(65), ...Array(12).fill(180)]); + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE kin_wakeups SET cache_measurement = json_set(cache_measurement, '$.written', 4447, '$.input', 1) + WHERE wakeup_id = 'turn-1'`; + assert.deepEqual(yield* run(), [part.fingerprint]); + }).pipe(Effect.provide(layer)), +); + +it.effect.each([ + ["one miss, then a newer real turn", [miss], -2 * 24 * 60, true], + ["one miss, no newer real turn", [miss], -25, false], + ["two misses in a row despite newer real turns", [miss, miss], -2 * 24 * 60, false], + ["two misses outside of fourteen days", [miss, miss], -15 * 24 * 60, true], + ["a miss, a hit, and a miss, then a newer turn", [miss, usage, miss], -2 * 24 * 60, true], + ["a real turn between two misses does not break the streak", [miss, miss], null, false], +] as const)("prices recent keep-warm history: %s", ([, pings, minutesAgo, due]) => + Effect.gen(function* () { + yield* seed([10, ...Array(20).fill(65)]); + const sql = yield* SqlClient.SqlClient; + const [turn] = yield* sql<{ at: number }>`SELECT cache_request_started_at AS at FROM kin_wakeups + WHERE wakeup_id = 'turn-10'`; + for (const [index, ping] of pings.entries()) { + const at = + minutesAgo === null + ? turn!.at + (index === 0 ? -1 : 1) + : now + (minutesAgo + index) * minute; + yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, ended_at, + status, event_ids, kind, tokens_json, last_request_at, cache_part, cache_request_started_at) + VALUES (${`historical-request-${index}`}, ${orgId}, ${agentId}, ${model}, ${at}, ${at}, + 'completed', '[]', 'upkeep', ${JSON.stringify(ping)}, ${at}, + ${part.fingerprint}, ${at})`; + } + assert.deepEqual(yield* run(), due ? [part.fingerprint] : []); + }).pipe(Effect.provide(layer)), +); + +it.effect("a ping's cost reaches the day's spend exactly once", () => + Effect.gen(function* () { + yield* seed([10, ...Array(20).fill(65)]); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_budget_limits (org_id, limits_json) VALUES (${orgId}, '{"leadUnits":4000,"workerUnits":null}')`; + assert.deepEqual(yield* run(), [part.fingerprint]); + const [upkeep] = yield* sql<{ + wakeupId: string; + }>`SELECT wakeup_id AS "wakeupId" FROM kin_wakeups WHERE kind = 'upkeep'`; + assert.deepEqual( + yield* sql`SELECT units, teammate FROM kin_budget_charges WHERE wakeup_id = ${upkeep!.wakeupId}`, + [{ units: 3208, teammate: 0 }], + ); + const budget = yield* Budget.KinBudget; + assert.include(yield* budget.get(orgId), { + leadUnits: 3208, + ownerUnits: 3208, + teammateUnits: 0, + inputTokens: 0, + cachedInputTokens: 0, + }); + assert.deepEqual((yield* budget.get(orgId)).leads, [ + { agentId, name: "Zoya", leadUnits: 3208 }, + ]); + assert.lengthOf(yield* sql`SELECT 1 FROM kin_messages WHERE body LIKE '%80%'`, 1); + yield* run(); + assert.deepEqual(yield* sql`SELECT units FROM kin_budget_charges`, [{ units: 3208 }]); + assert.equal((yield* budget.get(orgId)).leadUnits, 3208); + yield* budget.charge({ + orgId, + wakeupId: KinWakeupId.make("turn-21"), + usage: [ + { + providerTurnId: "turn-21", + turnTokenUsage: { + usageStatus: "complete", + usageScope: "main_agent", + hasSubagents: false, + inputTokens: 100, + cachedInputTokens: 25, + outputTokens: 0, + }, + }, + ], + }); + assert.include(yield* budget.get(orgId), { + inputTokens: 100, + cachedInputTokens: 25, + leadUnits: 3285.5, + }); + }).pipe(Effect.provide(layer)), +); + +it.effect("leaves the last sliver for a real turn when lowest priority is refused", () => + Effect.gen(function* () { + yield* seed([10, ...Array(20).fill(65)]); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_budget_limits (org_id, limits_json) VALUES (${orgId}, '{"leadUnits":4000,"workerUnits":null}')`; + const budget = yield* Budget.KinBudget; + const { day } = yield* budget.get(orgId); + yield* sql`UPDATE kin_budget SET lead_units = 3999 WHERE org_id = ${orgId} AND day = ${day}`; + assert.isTrue((yield* budget.admit(orgId, "P1")).allowed, "a real turn could already run"); + assert.deepEqual(yield* run(), []); + assert.isTrue((yield* budget.admit(orgId, "P1")).allowed, "the ping must not hold the turn"); + }).pipe(Effect.provide(layer)), +); + +it.effect( + "with budget to spare, a full rewrite leaves real turns and scheduled tasks admitted", + () => + Effect.gen(function* () { + yield* seed([10, ...Array(20).fill(65)]); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_budget_limits (org_id, limits_json) VALUES (${orgId}, '{"leadUnits":100000,"workerUnits":null}')`; + const budget = yield* Budget.KinBudget; + const { day } = yield* budget.get(orgId); + yield* sql`UPDATE kin_budget SET lead_units = 50000 WHERE org_id = ${orgId} AND day = ${day}`; + assert.deepEqual(yield* run({ outcome: { status: "completed", usage: miss } }), [ + part.fingerprint, + ]); + assert.equal((yield* budget.get(orgId)).leadUnits, 70608); + assert.isTrue((yield* budget.admit(orgId, "P1")).allowed); + assert.isTrue((yield* budget.admit(orgId, "P2")).allowed); + }).pipe(Effect.provide(layer)), +); + +it.effect("rechecks lowest priority at exactly 30% left after preparing a ping", () => + Effect.gen(function* () { + yield* seed([10, ...Array(20).fill(65)]); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_budget_limits (org_id, limits_json) VALUES (${orgId}, '{"leadUnits":100,"workerUnits":null}')`; + const budget = yield* Budget.KinBudget; + const { day } = yield* budget.get(orgId); + let prepared = false; + yield* Upkeep.check({ + enabled: true, + placement: "leadingBlock", + current: () => part.fingerprint, + ping: Effect.fn("UpkeepTest.prepareAtThreshold")(function* (_, stillDue) { + prepared = true; + yield* sql`UPDATE kin_budget SET lead_units = 70 WHERE org_id = ${orgId} AND day = ${day}`.pipe( + Effect.orDie, + ); + assert.isFalse(yield* stillDue); + return { status: "skipped" } as const; + }), + }); + assert.isTrue(prepared); + assert.isEmpty(yield* sql`SELECT 1 FROM kin_wakeups WHERE kind = 'upkeep'`); + }).pipe(Effect.provide(layer)), +); + +it.effect("does not estimate from just three at-risk gaps even with 25 total", () => + Effect.gen(function* () { + yield* seed([...Array(22).fill(10), 65, 65, 65]); + assert.deepEqual(yield* run(), []); + }).pipe(Effect.provide(layer)), +); + +it.effect("treats a failed ping without usage as a miss until newer real demand", () => + Effect.gen(function* () { + yield* seed([10, ...Array(20).fill(65)]); + assert.deepEqual(yield* run({ outcome: { status: "failed", usage: null } }), [ + part.fingerprint, + ]); + yield* TestClock.adjust("5 minutes"); + assert.deepEqual(yield* run(), []); + const sql = yield* SqlClient.SqlClient; + assert.isEmpty(yield* sql`SELECT * FROM kin_budget_charges`); + yield* sql`UPDATE kin_cache_parts SET last_turn_at = ${now + 15 * minute}, last_request_at = ${now + 15 * minute}`; + yield* TestClock.adjust("60 minutes"); + assert.deepEqual(yield* run(), [part.fingerprint]); + }).pipe(Effect.provide(layer)), +); + +const startFrame = { + type: "stream_event", + parent_tool_use_id: null, + event: { + type: "message_start", + message: { + id: "first", + usage: { + cache_read_input_tokens: 31_000, + cache_creation_input_tokens: 100, + input_tokens: 4, + output_tokens: 1, + }, + }, + }, +} as SDKMessage; +const deltaFrame = { + type: "stream_event", + parent_tool_use_id: null, + event: { type: "message_delta", usage: { output_tokens: 2 } }, +} as SDKMessage; + +it.effect("recovers reported usage on stream failure without charging frames twice", () => + Effect.gen(function* () { + async function* interrupted() { + yield startFrame; + yield deltaFrame; + throw new Error("fixture disconnect"); + } + const billed = yield* collectPing(interrupted()); + assert.deepEqual(billed, { status: "failed", usage: { ...usage, output: 2, cost: null } }); + }), +); + +it.effect.each([false, true])("keeps exactly the recorded usage at timeout (known=%s)", (known) => + Effect.gen(function* () { + const started = Promise.withResolvers(); + const done = Promise.withResolvers(); + async function* stalled() { + if (known) yield startFrame; + started.resolve(); + await done.promise; + } + const collecting = yield* collectPing(stalled()).pipe(Effect.forkChild); + yield* Effect.promise(() => started.promise); + yield* TestClock.adjust("90 seconds"); + done.resolve(); + const outcome = yield* Fiber.join(collecting); + assert.deepEqual(outcome, { status: "failed", usage: known ? { ...usage, cost: null } : null }); + yield* seed([10, ...Array(20).fill(65)]); + assert.deepEqual(yield* run({ outcome: { status: "failed", usage: outcome.usage } }), [ + part.fingerprint, + ]); + const sql = yield* SqlClient.SqlClient; + assert.deepEqual( + yield* sql`SELECT units, json_extract(tokens_json, '$[0].turnTokenUsage.usageStatus') AS status + FROM kin_budget_charges`, + known ? [{ units: 3208, status: "partial" }] : [], + ); + yield* TestClock.adjust("5 minutes"); + assert.deepEqual(yield* run(), []); + }).pipe(Effect.provide(layer)), +); + +it.effect("charges a first-response tool-use limit result as one completed ping", () => + Effect.gen(function* () { + let requests = 0; + async function* firstResponse() { + requests++; + yield { + type: "stream_event", + parent_tool_use_id: null, + event: { + type: "content_block_start", + content_block: { type: "tool_use", name: "kin_skip" }, + }, + } as SDKMessage; + yield { + type: "result", + subtype: "error_max_turns", + is_error: true, + num_turns: 1, + total_cost_usd: usage.cost, + usage: { + cache_read_input_tokens: usage.read, + cache_creation_input_tokens: usage.written, + input_tokens: usage.input, + output_tokens: usage.output, + }, + } as SDKMessage; + } + const result = yield* collectPing(firstResponse()); + assert.equal(requests, 1); + assert.deepEqual(result, { status: "completed", usage }); + yield* seed([10, ...Array(20).fill(65)]); + assert.deepEqual(yield* run({ outcome: result }), [part.fingerprint]); + const sql = yield* SqlClient.SqlClient; + assert.deepEqual(yield* sql`SELECT status FROM kin_wakeups WHERE kind = 'upkeep'`, [ + { status: "completed" }, + ]); + assert.deepEqual(yield* sql`SELECT units FROM kin_budget_charges`, [{ units: 3208 }]); + }).pipe(Effect.provide(layer)), +); + +it.effect("a quiet company sends no pings for a week", () => + Effect.gen(function* () { + yield* seed([]); + for (let day = 0; day < 7; day++) { + assert.deepEqual(yield* run(), []); + yield* TestClock.adjust("1 day"); + } + }).pipe(Effect.provide(layer)), +); + +it.effect("keeps the exact block and denies native, MCP, new tools and tool discovery", () => + Effect.gen(function* () { + const block = { + type: "text", + text: "Exact shared bytes\n", + cache_control: { type: "ephemeral", ttl: "1h" }, + } as const; + const request = makePingRequest( + { + block, + options: { + model, + tools: ["Read"], + permissionMode: "bypassPermissions", + sessionId: "previous", + }, + }, + "new-session", + ); + const [first] = request.message.message.content; + assert.deepEqual(first, block); + assert.isFalse(request.options.persistSession); + assert.equal(request.options.maxTurns, 1); + const matcher = request.options.hooks.PreToolUse[0]!; + assert.equal(matcher.onFailure, "block"); + assert.notProperty(matcher, "matcher"); + for (const tool_name of [ + "Read", + "WebSearch", + "mcp__t3-code__kin_send", + "ToolSearch", + "UnknownNewTool", + ]) { + const output = yield* Effect.promise(() => + matcher.hooks[0]!( + { + hook_event_name: "PreToolUse", + session_id: "new-session", + transcript_path: "", + cwd: ".", + tool_name, + tool_input: {}, + tool_use_id: "tool-id", + }, + "tool-id", + { signal: new AbortController().signal }, + ), + ); + assert.deepEqual(output, { + hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny" }, + }); + } + }), +); diff --git a/apps/server/src/kin/host/sessionUpkeep.ts b/apps/server/src/kin/host/sessionUpkeep.ts new file mode 100644 index 000000000000..a18bb20ee346 --- /dev/null +++ b/apps/server/src/kin/host/sessionUpkeep.ts @@ -0,0 +1,289 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- the provider uses independent native UUIDs. +import * as NodeCrypto from "node:crypto"; +import { KinWakeupId } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as Scheduler from "../../scheduling/Scheduler.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import { KinBudget } from "../lead/KinBudget.ts"; +import { KinDevClock } from "../DevClock.ts"; +import { + instructionPlacement, + type InstructionPlacement, +} from "../lead/turn/providers/provider.ts"; +import type { CachePart } from "./cacheParts.ts"; +import { PingUsage, send, type Ping } from "./sessionUpkeepQuery.ts"; +import { CACHE_LIFETIME_MS, KinCacheSessions } from "./cacheSessions.ts"; + +const MINUTE = 60_000; +const EVERY_MS = 5 * MINUTE; +const PING_AT = 50 * MINUTE; +const LOOKBACK = 14 * 24 * 60 * MINUTE; + +const UsageJson = Schema.fromJsonString(PingUsage); +const encodeUsage = Schema.encodeEffect(UsageJson); +const decodeUsage = Schema.decodeUnknownOption(UsageJson); + +interface Candidate extends CachePart { + readonly modelsJson: string; + readonly lastRequestAt: number; + readonly lastTurnAt: number; +} + +interface Due extends Candidate { + readonly idleMinutes: number; + readonly share: number; + readonly coldRead: number; +} + +type SendPing = (due: Due, stillDue: Effect.Effect) => Effect.Effect; + +const costUnits = (usage: Omit) => + usage.read * 0.1 + usage.written * 2 + usage.input + usage.output * 5; + +const estimate = Effect.fn("KinSessionUpkeep.estimate")(function* (part: Candidate, now: number) { + const sql = yield* SqlClient.SqlClient; + // Pings extend cache lifetime but are not demand; they must not reset the observed idle gap. + const idle = now - part.lastTurnAt; + const cutoff = now - LOOKBACK; + const [gaps] = yield* sql<{ + atRisk: number; + ended: number; + warmRead: number | null; + warmCost: number | null; + coldRead: number | null; + coldWrite: number | null; + }>` + WITH requests AS ( + SELECT cache_request_started_at AS started, cache_measurement AS usage, + MAX(last_request_at) OVER ( + ORDER BY cache_request_started_at, wakeup_id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING + ) AS preceding + FROM kin_wakeups WHERE cache_part = ${part.fingerprint} AND kind = 'turn' + AND cache_request_started_at BETWEEN ${cutoff} AND ${now} + AND last_request_at IS NOT NULL + ), gaps AS ( + SELECT started - preceding AS gap, + json_extract(usage, '$.read') AS read, json_extract(usage, '$.written') AS written, + COALESCE(json_extract(usage, '$.input'), 0) AS input + FROM requests WHERE preceding IS NOT NULL AND started > preceding + ) + SELECT COUNT(CASE WHEN gap >= ${idle} THEN 1 END) AS "atRisk", + COUNT(CASE WHEN gap BETWEEN ${idle} AND ${idle + PING_AT} THEN 1 END) AS ended, + MIN(CASE WHEN gap < ${CACHE_LIFETIME_MS} THEN read END) AS "warmRead", + MIN(CASE WHEN gap < ${CACHE_LIFETIME_MS} THEN read * 0.1 + written * 2 + input END) AS "warmCost", + MAX(CASE WHEN gap >= ${CACHE_LIFETIME_MS} THEN read END) AS "coldRead", + MIN(CASE WHEN gap >= ${CACHE_LIFETIME_MS} THEN written END) AS "coldWrite" + FROM gaps`; + if ( + gaps === undefined || + gaps.atRisk < 20 || + gaps.warmRead === null || + gaps.warmCost === null || + gaps.coldRead === null || + gaps.coldWrite === null + ) + return undefined; + const rewrite = Math.min(gaps.warmRead - gaps.coldRead, gaps.coldWrite) * 2; + if (rewrite <= 0) return undefined; + const [measured] = yield* sql<{ + tokens: string | null; + endedAt: number; + requestAt: number; + wakeupId: KinWakeupId; + status: "failed" | "completed"; + }>`SELECT tokens_json AS tokens, ended_at AS "endedAt", cache_request_started_at AS "requestAt", + wakeup_id AS "wakeupId", status + FROM kin_wakeups WHERE cache_part = ${part.fingerprint} AND kind = 'upkeep' + AND status IN ('completed', 'failed') AND cache_request_started_at BETWEEN ${cutoff} AND ${now} + ORDER BY cache_request_started_at DESC, wakeup_id DESC LIMIT 1`; + const sample = Option.getOrUndefined(decodeUsage(measured?.tokens)); + let price = + sample !== undefined && (sample.cost !== null || measured?.status === "completed") + ? costUnits(sample) + : undefined; + if (measured?.status === "completed" && price !== undefined && price > rewrite) { + // A real turn permits the retry; only another upkeep request can break its miss streak. + const [previous] = yield* sql<{ status: string; tokens: string | null }>` + SELECT status, tokens_json AS tokens FROM kin_wakeups + WHERE cache_part = ${part.fingerprint} AND kind = 'upkeep' AND cache_request_started_at >= ${cutoff} + AND (cache_request_started_at, wakeup_id) < (${measured.requestAt}, ${measured.wakeupId}) + ORDER BY cache_request_started_at DESC, wakeup_id DESC LIMIT 1`; + const prior = + previous?.status === "completed" + ? Option.getOrUndefined(decodeUsage(previous.tokens)) + : undefined; + if (prior === undefined || costUnits(prior) <= rewrite) price = undefined; + } + // A lone miss or unpriced failure waits for a newer turn before using the warm-opening estimate. + if (price === undefined && measured !== undefined && measured.endedAt >= part.lastTurnAt) + return undefined; + const ping = price ?? gaps.warmCost + 5; + const share = gaps.ended / gaps.atRisk; + return share >= ping / rewrite ? { share, coldRead: gaps.coldRead } : undefined; +}); + +export const check = Effect.fn("KinSessionUpkeep.check")(function* (input: { + readonly enabled: boolean; + readonly placement: InstructionPlacement; + readonly current: (part: Candidate) => string | undefined; + readonly ping: SendPing; + readonly wallMillis?: Effect.Effect; +}) { + if (!input.enabled || input.placement === "system") return; + const sql = yield* SqlClient.SqlClient; + const budget = yield* KinBudget; + const time = input.wallMillis ?? Clock.currentTimeMillis; + const now = yield* time; + const parts = yield* sql` + SELECT p.fingerprint, p.seat, p.model, p.org_id AS "orgId", p.agent_id AS "agentId", + p.last_request_at AS "lastRequestAt", p.last_turn_at AS "lastTurnAt", l.models_json AS "modelsJson" + FROM kin_cache_parts p JOIN kin_leads l USING (org_id, agent_id) + WHERE p.last_request_at > ${now - CACHE_LIFETIME_MS} AND p.last_request_at <= ${now - PING_AT} + ORDER BY p.last_request_at, p.fingerprint`; + for (const part of parts) { + if (input.current(part) !== part.fingerprint) continue; + const stillDue = Effect.gen(function* () { + const currentTime = yield* time; + if (currentTime - part.lastRequestAt >= CACHE_LIFETIME_MS) return false; + const [active] = yield* sql`SELECT 1 FROM kin_cache_parts p + JOIN kin_agents a USING (org_id, agent_id) + JOIN kin_leads l USING (org_id, agent_id) + LEFT JOIN kin_org_state s USING (org_id) + WHERE p.fingerprint = ${part.fingerprint} AND p.last_request_at = ${part.lastRequestAt} + AND l.models_json = ${part.modelsJson} + AND COALESCE(s.paused, 0) = 0 AND a.retired_at IS NULL AND a.paused_at IS NULL + AND NOT EXISTS (SELECT 1 FROM kin_wakeups w WHERE w.org_id = p.org_id AND w.status = 'running')`; + return ( + active !== undefined && + input.current(part) === part.fingerprint && + (yield* budget.admit(part.orgId, "P4")).allowed + ); + }); + if (!(yield* stillDue)) continue; + const result = yield* estimate(part, now); + if (result === undefined) continue; + const idleMinutes = (now - part.lastRequestAt) / MINUTE; + const startedAt = yield* time; + const sent = yield* input.ping( + { ...part, ...result, idleMinutes }, + stillDue.pipe(Effect.orElseSucceed(() => false)), + ); + const { fingerprint } = part; + if (sent.status === "skipped") { + yield* Effect.logInfo("kin.session.upkeep", { + action: "skipped", + fingerprint, + idleMinutes, + share: result.share, + }); + continue; + } + const endedAt = yield* time; + const requested = sent.status === "completed" && sent.usage !== null; + const warmed = requested && (sent.usage?.read ?? 0) > result.coldRead; + const wakeupId = KinWakeupId.make(`kin-upkeep:${NodeCrypto.randomUUID()}`); + const tokens = sent.usage === null ? null : yield* encodeUsage(sent.usage); + yield* sql.withTransaction( + Effect.gen(function* () { + yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, ended_at, + status, event_ids, kind, tokens_json, last_request_at, cache_part, cache_request_started_at) + VALUES (${wakeupId}, ${part.orgId}, ${part.agentId}, ${part.model}, ${startedAt}, ${endedAt}, + ${sent.status}, '[]', 'upkeep', ${tokens}, + ${requested ? endedAt : null}, ${fingerprint}, ${startedAt})`; + if (sent.usage !== null) { + const { input, read, written, output } = sent.usage; + yield* budget.charge({ + orgId: part.orgId, + wakeupId, + usage: [ + { + providerTurnId: wakeupId, + turnTokenUsage: { + usageScope: "main_agent", + usageStatus: + sent.status === "failed" && sent.usage.cost === null ? "partial" : "complete", + hasSubagents: false, + inputTokens: input + read + written, + cachedInputTokens: read, + cacheCreationTokens: written, + outputTokens: output, + }, + }, + ], + }); + } + if (requested) + yield* sql`UPDATE kin_cache_parts SET last_request_at = MAX(last_request_at, ${endedAt}) + WHERE fingerprint = ${fingerprint}`; + }), + ); + yield* (sent.status === "failed" ? Effect.logWarning : Effect.logInfo)("kin.session.upkeep", { + action: sent.status === "failed" ? "failed" : warmed ? "ping" : "miss", + fingerprint, + idleMinutes, + share: result.share, + tokensRead: sent.usage?.read ?? null, + tokensWritten: sent.usage?.written ?? null, + cost: sent.usage?.cost ?? null, + }); + } +}); + +export const layer = Layer.effectDiscard( + Effect.gen(function* () { + const cache = Option.getOrUndefined(yield* Effect.serviceOption(KinCacheSessions)); + if (cache === undefined) return; + const server = yield* ServerSettingsService; + const clock = Option.getOrUndefined(yield* Effect.serviceOption(KinDevClock)); + let nextAt = 0; + yield* (yield* Scheduler.Scheduler).register( + "kin-session-upkeep", + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + if (now < nextAt) return; + nextAt = now + EVERY_MS; + cache.prune(yield* clock?.wallMillis ?? Clock.currentTimeMillis); + const settings = yield* server.getSettings; + const current = (part: Candidate) => cache.current(part, part.modelsJson, settings); + yield* check({ + enabled: settings.kinSessionUpkeep, + placement: instructionPlacement("claudeAgent"), + current: (part) => current(part)?.part.fingerprint, + ...(clock === undefined ? {} : { wallMillis: clock.wallMillis }), + ping: Effect.fn("KinSessionUpkeep.ping")(function* (part, stillDue) { + const session = current(part); + if (session === undefined) return { status: "skipped" } as const; + const result = yield* send( + cache, + session, + Effect.gen(function* () { + const latest = yield* server.getSettings.pipe(Effect.option); + return ( + Option.exists( + latest, + (value) => + value.kinSessionUpkeep && + cache.current(part, part.modelsJson, value)?.part.fingerprint === + part.fingerprint, + ) && (yield* stillDue) + ); + }), + ).pipe( + Effect.scoped, + Effect.orElseSucceed(() => ({ status: "failed", usage: null }) as const), + ); + if (result.status === "completed" && result.usage !== null) + cache.keep(session, yield* clock?.wallMillis ?? Clock.currentTimeMillis); + return result; + }), + }); + }).pipe(Effect.catch(() => Effect.logWarning("Kin session upkeep check failed"))), + ); + }), +); diff --git a/apps/server/src/kin/host/sessionUpkeepQuery.ts b/apps/server/src/kin/host/sessionUpkeepQuery.ts new file mode 100644 index 000000000000..b73795816a02 --- /dev/null +++ b/apps/server/src/kin/host/sessionUpkeepQuery.ts @@ -0,0 +1,264 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- the provider uses independent native UUIDs. +import * as NodeCrypto from "node:crypto"; +import { + query, + type HookCallback, + type Options, + type SDKMessage, + type SDKUserMessage, +} from "@anthropic-ai/claude-agent-sdk"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient } from "effect/http"; + +import type { ClaudeAgentSdkQueryOptions } from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; +import type { KinCacheSessions, LeadingBlock } from "./cacheSessions.ts"; + +const UPKEEP_LINE = "Reply with one word: Ready."; + +export const PingUsage = Schema.Struct({ + read: Schema.Number, + written: Schema.Number, + input: Schema.Number, + output: Schema.Number, + cost: Schema.NullOr(Schema.Number), +}); +type PingUsage = typeof PingUsage.Type; +export type Ping = + | { readonly status: "completed" | "failed"; readonly usage: PingUsage | null } + | { readonly status: "skipped" }; + +const denyTool: HookCallback = async () => ({ + hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny" }, +}); + +export const makePingRequest = ( + input: { + readonly block: LeadingBlock; + readonly options: ClaudeAgentSdkQueryOptions; + }, + sessionId: string, +) => { + const { + resume: _resume, + resumeSessionAt: _resumeAt, + sessionId: _session, + mcpServers: _servers, + hooks: _hooks, + abortController: _abort, + stderr: _stderr, + spawnClaudeCodeProcess: _spawn, + ...options + } = input.options; + return { + message: { + type: "user", + message: { + role: "user", + content: [input.block, { type: "text", text: UPKEEP_LINE }], + }, + parent_tool_use_id: null, + session_id: sessionId, + } satisfies SDKUserMessage, + options: { + ...options, + sessionId, + persistSession: false, + maxTurns: 1, + includePartialMessages: true, + forkSession: false, + promptSuggestions: false, + supportedDialogKinds: [], + canUseTool: async () => ({ behavior: "deny", message: "" }), + onElicitation: async () => ({ action: "cancel" }), + onUserDialog: async () => ({ behavior: "cancelled" }), + hooks: { PreToolUse: [{ onFailure: "block", hooks: [denyTool] }] }, + } satisfies Options, + }; +}; + +const safeOptions = (options: ClaudeAgentSdkQueryOptions) => + options.settingSources?.length === 0 && + options.strictMcpConfig === true && + typeof options.settings === "object" && + options.settings.hooks === undefined && + options.settings.enabledPlugins === undefined && + options.managedSettings === undefined && + (options.plugins?.length ?? 0) === 0 && + options.agent === undefined && + options.agents === undefined && + Object.keys(options.extraArgs ?? {}).every((name) => name === "thinking-display"); + +type Counts = Omit; +const zero: Counts = { input: 0, read: 0, written: 0, output: 0 }; +const normalizeCount = (n: number | null | undefined) => + typeof n === "number" && Number.isSafeInteger(n) && n >= 0 ? n : undefined; +const readCounts = ( + usage: { + readonly input_tokens?: number | null; + readonly cache_read_input_tokens?: number | null; + readonly cache_creation_input_tokens?: number | null; + readonly output_tokens?: number | null; + }, + prior = zero, +): Counts => ({ + input: normalizeCount(usage.input_tokens) ?? prior.input, + read: normalizeCount(usage.cache_read_input_tokens) ?? prior.read, + written: normalizeCount(usage.cache_creation_input_tokens) ?? prior.written, + output: normalizeCount(usage.output_tokens) ?? prior.output, +}); +const sum = (a: Counts, b: Counts): Counts => ({ + input: a.input + b.input, + read: a.read + b.read, + written: a.written + b.written, + output: a.output + b.output, +}); +const hasUsage = (counts: Counts) => Object.values(counts).some((n) => n > 0); + +export const collectPing = Effect.fn("KinSessionUpkeep.collectPing")(function* ( + messages: AsyncIterable, +) { + const frames = new Map(); + let current: string | undefined; + const record = (id: string, usage: Parameters[0]) => + frames.set(id, readCounts(usage, frames.get(id))); + const observed = () => [...frames.values()].reduce(sum, zero); + const result = yield* Effect.tryPromise({ + try: async (signal) => { + for await (const message of messages) { + if (signal.aborted) return undefined; + if (message.type === "result") { + const modelCounts = Object.values(message.modelUsage ?? {}).reduce( + (total, one) => + sum( + total, + readCounts({ + input_tokens: one.inputTokens, + cache_read_input_tokens: one.cacheReadInputTokens, + cache_creation_input_tokens: one.cacheCreationInputTokens, + output_tokens: one.outputTokens, + }), + ), + zero, + ); + const reported = readCounts(message.usage ?? {}); + const counts = hasUsage(modelCounts) + ? modelCounts + : hasUsage(reported) + ? reported + : observed(); + const cost = + Number.isFinite(message.total_cost_usd) && message.total_cost_usd >= 0 + ? message.total_cost_usd + : null; + const hasResultUsage = hasUsage(modelCounts) || hasUsage(reported); + const completed = + (message.subtype === "success" && !message.is_error) || + (message.subtype === "error_max_turns" && hasResultUsage); + return { + status: completed ? "completed" : "failed", + usage: hasUsage(counts) ? { ...counts, cost: hasResultUsage ? cost : null } : null, + } as const; + } + if ( + message.type === "assistant" && + message.parent_tool_use_id === null && + message.message?.usage + ) { + record(message.message.id, message.message.usage); + } else if (message.type === "stream_event" && message.parent_tool_use_id === null) { + const event = message.event; + if (event?.type === "message_start") { + current = event.message?.id; + if (current !== undefined && event.message.usage) record(current, event.message.usage); + } else if (event?.type === "message_delta" && current !== undefined && event.usage) { + record(current, event.usage); + } + } + } + return undefined; + }, + catch: () => "result", + }).pipe( + Effect.timeout("90 seconds"), + Effect.orElseSucceed(() => undefined), + ); + if (result !== undefined) return result; + const partial = observed(); + return { + status: "failed", + usage: hasUsage(partial) ? { ...partial, cost: null } : null, + } as const; +}); + +export const send = Effect.fn("KinSessionUpkeep.send")(function* ( + cache: KinCacheSessions["Service"], + session: NonNullable>, + stillDue: Effect.Effect, +) { + const source = session.options.mcpServers?.["t3-code"]; + if ( + session.block.cache_control.ttl !== "1h" || + !safeOptions(session.options) || + source?.type !== "http" || + !URL.canParse(source.url) + ) + return { status: "skipped" } as const; + const url = new URL(source.url); + if (url.pathname !== "/kin/mcp" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)) + return { status: "skipped" } as const; + const lease = yield* cache.lease(session); + const request = makePingRequest(session, NodeCrypto.randomUUID()); + const answer = Promise.withResolvers(); + async function* prompt() { + const message = await answer.promise; + if (message !== undefined) yield message; + } + const closeMcp = Effect.suspend(() => { + if (lease.sessionId === undefined) return Effect.void; + return HttpClient.del(url, { + headers: { Authorization: `Bearer ${lease.token}`, "mcp-session-id": lease.sessionId }, + }).pipe( + Effect.provide(FetchHttpClient.layer), + Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }), + Effect.filterOrFail( + (response) => response.status === 204 || response.status === 404, + () => "mcp-close", + ), + Effect.timeout("5 seconds"), + Effect.asVoid, + Effect.catch(() => Effect.logWarning("Kin could not close its upkeep MCP session")), + Effect.interruptible, + ); + }); + yield* Effect.addFinalizer(() => closeMcp); + const runtime = yield* Effect.acquireRelease( + Effect.try({ + try: () => query({ prompt: prompt(), options: request.options }), + catch: () => "query", + }), + (runtime) => + Effect.sync(() => { + answer.resolve(undefined); + runtime.close(); + }), + ); + const setup = yield* Effect.tryPromise({ + try: async () => { + await runtime.initializationResult(); + const registration = await runtime.setMcpServers({ + "t3-code": { ...source, headers: { Authorization: `Bearer ${lease.token}` } }, + }); + return Object.keys(registration.errors).length === 0; + }, + catch: () => "setup", + }).pipe(Effect.timeoutOption("90 seconds")); + if (Option.getOrUndefined(setup) !== true) return { status: "failed", usage: null } as const; + const rosterMatches = yield* Deferred.await(lease.ready).pipe(Effect.timeoutOption("5 seconds")); + if (Option.getOrUndefined(rosterMatches) !== true || !(yield* stillDue)) + return { status: "skipped" } as const; + answer.resolve(request.message); + return yield* collectPing(runtime); +}); diff --git a/apps/server/src/kin/layer.ts b/apps/server/src/kin/layer.ts index 95a64383765a..bb96959ea7e1 100644 --- a/apps/server/src/kin/layer.ts +++ b/apps/server/src/kin/layer.ts @@ -57,6 +57,7 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import type { ServerSettingsService } from "../serverSettings.ts"; import * as KinMcp from "./mcp/layer.ts"; import * as SessionCarry from "./lead/sessionCarry.ts"; +import { KinCacheSessions } from "./host/cacheSessions.ts"; import { KinSessionContext } from "./lead/turn/sessionContext.ts"; import * as KinTasksKeyMcp from "./tasksKey/mcp.ts"; import * as Render from "./gendocs/render.ts"; @@ -92,7 +93,7 @@ const enabled = (seal: Layer.Layer) => Layer.effect( KinServer, Effect.gen(function* () { - const services = yield* Effect.context(); + const services = yield* Effect.context(); yield* requireRefreshObserver(services); const chat = yield* KinChatService; yield* (yield* KinRecords.KinRecords).attachClosing((subject) => @@ -339,7 +340,9 @@ const middleware = HttpRouter.middleware<{ provides: KinServer }>()( export const layerWithSeal = (seal: Layer.Layer) => middleware.pipe( Layer.provideMerge(runtime(seal)), - Layer.provideMerge(Layer.merge(SessionCarry.layer, KinSessionContext.layer)), + Layer.provideMerge( + Layer.mergeAll(SessionCarry.layer, KinSessionContext.layer, KinCacheSessions.layer), + ), ); export const layer = layerWithSeal(KeySeal.layer); diff --git a/apps/server/src/kin/lead/KinBudget.ts b/apps/server/src/kin/lead/KinBudget.ts index 0d3abacd1bae..3937804d41f5 100644 --- a/apps/server/src/kin/lead/KinBudget.ts +++ b/apps/server/src/kin/lead/KinBudget.ts @@ -327,7 +327,9 @@ const make = Effect.gen(function* () { COALESCE(SUM(json_extract(u.value, '$.turnTokenUsage.cachedInputTokens')), 0) AS "cachedInputTokens" FROM kin_budget_charges c, json_each(c.tokens_json) u - WHERE c.org_id = ${orgId} AND c.day = ${day}` + WHERE c.org_id = ${orgId} AND c.day = ${day} + AND NOT EXISTS (SELECT 1 FROM kin_wakeups w + WHERE w.org_id = c.org_id AND w.wakeup_id = c.wakeup_id AND w.kind = 'upkeep')` : []; return { orgId, @@ -727,7 +729,9 @@ const make = Effect.gen(function* () { Math.max(0, before.leadUnits - before.teammates) + delta * (1 - teammate); if (limit !== null && limit > 0 && teammate === 0 && ownerSpent >= WARN_AT * limit) yield* ownerNotice(input.orgId, "warning"); - yield* sql`UPDATE kin_wakeups SET tokens_json = ${tokensJson} WHERE org_id = ${input.orgId} AND wakeup_id = ${input.wakeupId}`; + // Upkeep keeps its raw SDK price sample; this charge owns the accounting ledger. + yield* sql`UPDATE kin_wakeups SET tokens_json = ${tokensJson} WHERE org_id = ${input.orgId} + AND wakeup_id = ${input.wakeupId} AND kind = 'turn'`; return { orgId: input.orgId, wakeupId: input.wakeupId, diff --git a/apps/server/src/kin/lead/KinLeadProvision.test.ts b/apps/server/src/kin/lead/KinLeadProvision.test.ts index 63c3bdb4c4ec..8da05839fc09 100644 --- a/apps/server/src/kin/lead/KinLeadProvision.test.ts +++ b/apps/server/src/kin/lead/KinLeadProvision.test.ts @@ -1444,6 +1444,17 @@ describe("KinLeadProvision", () => { assert.strictEqual(page.model.model, "claude-opus-4-6"); assert.deepStrictEqual(page.runsOn, page.model); assert.isNull(page.modelNote); + yield* sql`INSERT INTO kin_wakeups (org_id, agent_id, wakeup_id, model, kind, started_at, status, event_ids) + VALUES (${tech.orgId}, ${tech.agentId}, 'agent-page-turn', ${page.model.model}, 'turn', 0, 'completed', '[]'), + (${tech.orgId}, ${tech.agentId}, 'agent-page-ping', ${page.model.model}, 'upkeep', 0, 'completed', '[]')`; + yield* sql`INSERT INTO kin_budget (org_id, day, lead_units) VALUES (${tech.orgId}, '1970-01-01', 3308)`; + yield* sql`INSERT INTO kin_budget_charges (org_id, wakeup_id, day, units, tokens_json) + VALUES (${tech.orgId}, 'agent-page-turn', '1970-01-01', 100, '[]'), + (${tech.orgId}, 'agent-page-ping', '1970-01-01', 3208, '[]')`; + assert.deepStrictEqual((yield* ownerLevelAgentPage(target)).usedThisMonth, { + turns: 1, + tokens: 3308, + }); assert.include(page.character?.body ?? "", "# Ada"); // Each page lists the playbooks its area works by: code review is Ada's, not Social's. yield* seedPlaybooks(tech.orgId, (yield* KinIdentity).owner.personId); diff --git a/apps/server/src/kin/lead/LeadPrompt.test.ts b/apps/server/src/kin/lead/LeadPrompt.test.ts index d5c31699c4c3..d9305fcdcd5a 100644 --- a/apps/server/src/kin/lead/LeadPrompt.test.ts +++ b/apps/server/src/kin/lead/LeadPrompt.test.ts @@ -4307,7 +4307,10 @@ it.effect( VALUES (${agentId}, ${orgId}, 'Lead', 0, '{}', '[]', ${chatId})`; yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, status, event_ids) VALUES ('earlier', ${orgId}, ${agentId}, 'model', 100, 'completed', '[]')`; - const react = (messageId: string, emoji: string, at: number, woke: number | null = null) => + // A keep-warm request after the reaction is not a turn the lead saw it in. + yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, status, event_ids, kind) + VALUES ('kin-upkeep:fixture', ${orgId}, ${agentId}, 'model', 550, 'completed', '[]', 'upkeep')`; + const react =(messageId: string, emoji: string, at: number, woke: number | null = null) => sql`INSERT INTO kin_reactions (org_id, chat_id, message_id, member_id, emoji, created_at, removed_at, woke_at) VALUES (${orgId}, ${chatId}, ${messageId}, ${memberId}, ${emoji}, ${at}, NULL, ${woke})`; yield* react("landed", "❤️", 500); diff --git a/apps/server/src/kin/lead/LeadPrompt.ts b/apps/server/src/kin/lead/LeadPrompt.ts index 6e93945fdbc2..8f21c67e399f 100644 --- a/apps/server/src/kin/lead/LeadPrompt.ts +++ b/apps/server/src/kin/lead/LeadPrompt.ts @@ -1627,7 +1627,7 @@ export class KinLeadPrompt extends Context.Service< const [last] = yield* sql<{ at: number | null }>` SELECT MAX(COALESCE(prepared_at, started_at)) AS at FROM kin_wakeups WHERE org_id = ${input.orgId} AND agent_id = ${input.agentId} - AND status = 'completed' AND wakeup_id != ${input.wakeupId}`; + AND status = 'completed' AND kind = 'turn' AND wakeup_id != ${input.wakeupId}`; const since = last?.at ?? now - FEEDBACK_FIRST_WINDOW_MS; const rows = yield* sql<{ emoji: string; body: string }>` SELECT r.emoji, m.body FROM kin_reactions r diff --git a/apps/server/src/kin/lead/RoutineContent.test.ts b/apps/server/src/kin/lead/RoutineContent.test.ts index ed9f7a6ba78a..94f7a245372b 100644 --- a/apps/server/src/kin/lead/RoutineContent.test.ts +++ b/apps/server/src/kin/lead/RoutineContent.test.ts @@ -983,6 +983,28 @@ it.effect("an evening whose only news is in Kin's records is summed up, by the c assert.deepStrictEqual(JSON.parse(facts ?? "{}").today, { finished: ["W-6 Beta release to two pilot clinics (task): marked done by Owner (owner)"], }); + // A failed keep-warm request is not a failed wake-up. + const at = Date.parse("2026-11-09T00:40:00.000Z"); + yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, ended_at, + status, event_ids, kind) + VALUES ('kin-upkeep:fixture', ${orgId}, ${agentId}, 'model', ${at}, ${at}, 'failed', '[]', 'upkeep')`; + yield* sql`UPDATE kin_wakeups SET tokens_json = '{"read":31000,"written":100,"input":4,"output":1,"cost":0.008}' + WHERE wakeup_id = 'kin-upkeep:fixture'`; + yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, ended_at, + status, event_ids) + VALUES ('evening-turn', ${orgId}, ${agentId}, 'model', ${at}, ${at}, 'completed', '[]')`; + yield* sql`INSERT INTO kin_budget (org_id, day, lead_units) VALUES (${orgId}, '2026-11-09', 3286)`; + yield* sql`INSERT INTO kin_budget_charges (org_id, wakeup_id, day, units, tokens_json) + VALUES (${orgId}, 'kin-upkeep:fixture', '2026-11-09', 3208, + '[{"turnTokenUsage":{"inputTokens":31104,"cachedInputTokens":31000,"outputTokens":1}}]'), + (${orgId}, 'evening-turn', '2026-11-09', 78, + '[{"turnTokenUsage":{"inputTokens":100,"cachedInputTokens":25,"outputTokens":0}}]')`; + const after = yield* content.eveningFacts(orgId, agentId); + assert.include(JSON.parse(after ?? "{}"), { + failedWakeups: 0, + units: 3286, + cacheHitRate: 0.25, + }); }).pipe(Effect.orDie), ), ); diff --git a/apps/server/src/kin/lead/RoutineContent.ts b/apps/server/src/kin/lead/RoutineContent.ts index 1226d8026cd0..abb7e132e8a4 100644 --- a/apps/server/src/kin/lead/RoutineContent.ts +++ b/apps/server/src/kin/lead/RoutineContent.ts @@ -502,14 +502,18 @@ const make = Effect.gen(function* () { .map((item) => row(item, `was due ${timeLabel(due(item))}, still open`)); const [failed] = yield* sql<{ n: number }>` SELECT COUNT(*) AS n FROM kin_wakeups - WHERE org_id = ${orgId} AND status IN ('failed', 'timed_out') AND started_at >= ${dayStart} + WHERE org_id = ${orgId} AND status IN ('failed', 'timed_out') AND kind = 'turn' + AND started_at >= ${dayStart} ORDER BY n`; const [dreams] = yield* sql<{ n: number }>` SELECT COUNT(*) AS n FROM kin_dream_runs WHERE org_id = ${orgId} AND owner_date = ${day} AND status = 'failed' ORDER BY n`; const charges = yield* sql<{ tokens: string }>` - SELECT tokens_json AS tokens FROM kin_budget_charges - WHERE org_id = ${orgId} AND day = ${day} ORDER BY wakeup_id`; + SELECT c.tokens_json AS tokens FROM kin_budget_charges c + WHERE c.org_id = ${orgId} AND c.day = ${day} + AND NOT EXISTS (SELECT 1 FROM kin_wakeups w + WHERE w.org_id = c.org_id AND w.wakeup_id = c.wakeup_id AND w.kind = 'upkeep') + ORDER BY c.wakeup_id`; let input = 0; let cached = 0; for (const charge of charges) diff --git a/apps/server/src/kin/lead/WakeupRunner.ts b/apps/server/src/kin/lead/WakeupRunner.ts index 5ebf900b9d54..caaf5ecc74a6 100644 --- a/apps/server/src/kin/lead/WakeupRunner.ts +++ b/apps/server/src/kin/lead/WakeupRunner.ts @@ -164,6 +164,7 @@ import { KinAgentSessions } from "../mcp/KinAgentSessions.ts"; import { captureChatCursor, readCursor, sessionChanges, type Cursor } from "./sessionChanges.ts"; import { KinSessionContext, type SessionSnapshot } from "./turn/sessionContext.ts"; import { claude } from "./turn/providers/claude.ts"; +import { recordTurn as recordCachePartTurn } from "../host/cacheSessions.ts"; import { KinWorkspace } from "../gendocs/workspace.ts"; import { KinBoot, carryFacts, decideCarry, ulid, type PromptFingerprint } from "./sessionCarry.ts"; import { closeQuietRunCards, postQuietRunCard } from "./quietRunCard.ts"; @@ -919,6 +920,7 @@ const make = Effect.gen(function* () { const contextTokens = last?.tokenUsage?.usedTokens ?? null; const completedAt = last?.completedAt ?? last?.startedAt; const lastRequestAt = completedAt == null ? null : DateTime.toEpochMillis(completedAt); + yield* recordCachePartTurn(row, threadId, lastRequestAt).pipe(provideSql); const { now, wallNow } = yield* carryClocks; const lastRequestKinAt = lastRequestAt === null ? null : now - (wallNow - lastRequestAt); const [shadow] = yield* sql<{ diff --git a/apps/server/src/kin/lead/agentPage.ts b/apps/server/src/kin/lead/agentPage.ts index 4ca5fe880dff..35793b7b3326 100644 --- a/apps/server/src/kin/lead/agentPage.ts +++ b/apps/server/src/kin/lead/agentPage.ts @@ -64,7 +64,7 @@ export const ownerLevelAgentPage = Effect.fn("KinAgentPage.read")(function* (inp const today = DateTime.makeZonedUnsafe(yield* Clock.currentTimeMillis, { timeZone: zone }); const monthStart = `${DateTime.formatIsoDate(today).slice(0, 7)}-01`; const [used] = yield* sql<{ turns: number | null; tokens: number | null }>` - SELECT COUNT(DISTINCT c.wakeup_id) AS turns, SUM(c.units) AS tokens + SELECT COUNT(DISTINCT CASE WHEN w.kind = 'turn' THEN c.wakeup_id END) AS turns, SUM(c.units) AS tokens FROM kin_budget_charges c JOIN kin_wakeups w ON w.org_id = c.org_id AND w.wakeup_id = c.wakeup_id WHERE c.org_id = ${orgId} AND w.agent_id = ${agentId} AND c.day >= ${monthStart}`.pipe( diff --git a/apps/server/src/kin/lead/layer.ts b/apps/server/src/kin/lead/layer.ts index a6b993faf111..789361e587e7 100644 --- a/apps/server/src/kin/lead/layer.ts +++ b/apps/server/src/kin/lead/layer.ts @@ -9,6 +9,7 @@ import * as KinSchedules from "../triggers/kinSchedules.ts"; import * as Watchdogs from "../triggers/watchdogs.ts"; import * as HostBackupCheck from "../host/backupCheck.ts"; import * as RunningSpend from "../host/runningSpend.ts"; +import * as SessionUpkeep from "../host/sessionUpkeep.ts"; import * as OfflineCatchUp from "../host/offlineCatchUp.ts"; import * as GithubReaders from "../triggers/githubReaders.ts"; import { KinDeferralGithubReader } from "../triggers/deferralGithub.ts"; @@ -123,6 +124,7 @@ const routineRuntime = Layer.mergeAll( Watchdogs.layer, HostBackupCheck.layer, RunningSpend.layer, + SessionUpkeep.layer, KinPulse.layer, ArrivalFeed.liveLayer, KinWatchRounds.layer, diff --git a/apps/server/src/kin/lead/sessionCarry.test.ts b/apps/server/src/kin/lead/sessionCarry.test.ts index 2bf73c83a845..9fe81fab43fc 100644 --- a/apps/server/src/kin/lead/sessionCarry.test.ts +++ b/apps/server/src/kin/lead/sessionCarry.test.ts @@ -172,6 +172,15 @@ effectIt.effect("names the lane, mark source and ending behind a refusal", () => }; const wakeup = { orgId, agentId, wakeupId }; const compare = carryFacts(wakeup, input); + const withoutUpkeep = yield* compare; + yield* sql`INSERT INTO kin_wakeups (org_id, agent_id, wakeup_id, model, kind, + started_at, ended_at, last_request_at, last_request_kin_at, status, event_ids) + VALUES (${orgId}, ${agentId}, 'tidewater-upkeep', ${selection.model}, 'upkeep', + ${now}, ${now}, ${now}, ${now}, 'completed', '[]')`; + const withUpkeep = yield* compare; + expect(withUpkeep.previousWakeupId).toBe(prior!.wakeupId); + expect(withUpkeep.facts.gapMs).toBe(withoutUpkeep.facts.gapMs); + expect(withUpkeep.facts.companyGapMs).toBe(withoutUpkeep.facts.companyGapMs); for (const lane of ["bills", "review", "triage"] as const) { const confined = yield* carryFacts(wakeup, { ...input, diff --git a/apps/server/src/kin/lead/turn/providers/claude.ts b/apps/server/src/kin/lead/turn/providers/claude.ts index 55d95ce40305..dffb6678132a 100644 --- a/apps/server/src/kin/lead/turn/providers/claude.ts +++ b/apps/server/src/kin/lead/turn/providers/claude.ts @@ -12,6 +12,8 @@ import { sessionEnvironment, withConfinementHook, } from "../../../claudeConfinement.ts"; +import { cacheSessionsOf } from "../../../host/cacheSessions.ts"; +import { KinServer } from "../../../KinServer.ts"; import { type KinSessionPlan, KinSessions } from "../session.ts"; import * as SessionContext from "../sessionContext.ts"; import type { KinProvider } from "./provider.ts"; @@ -357,6 +359,7 @@ const install = (base: Layer.Layer()); return ClaudeAdapterV2.ClaudeAgentSdkQueryRunner.of({ @@ -407,22 +410,44 @@ const install = (base: Layer.Layer, params: unknown, session?: string, extra: Record = {}, server = http, + verb = "POST", ) => Effect.gen(function* () { const sent = yield* Deferred.make(); @@ -391,7 +398,7 @@ it.effect.each([true, false])( HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb( new Request(`http://localhost${path}`, { - method: "POST", + method: verb, headers: { authorization: token, "content-type": "application/json", @@ -399,7 +406,20 @@ it.effect.each([true, false])( ...(session ? { "mcp-session-id": session } : {}), ...extra, }, - body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), + ...(verb === "POST" + ? { + body: JSON.stringify( + typeof method !== "string" + ? method + : { + jsonrpc: "2.0", + ...(method.startsWith("notifications/") ? {} : { id: 1 }), + method, + params, + }, + ), + } + : {}), }), ), ), @@ -626,15 +646,201 @@ it.effect.each([true, false])( {}, initialized.headers["mcp-session-id"], ); - const toolNames = decodeToolList( - yield* Effect.promise(() => HttpServerResponse.toWeb(toolList).text()), - ).result.tools.map((tool) => tool.name); + const ownerRoster = yield* bodyOf(toolList); + const toolNames = decodeToolList(ownerRoster).result.tools.map((tool) => tool.name); // The owner's own thread: Kin's tools and T3's, GitHub connected or not. assert.includeMembers(toolNames, ["kin_chat_read", "delegate_task"]); // Asked to watch a number, an agent searching its tools finds the one that proposes it. assert.includeMembers(toolNames, ["numbers_read", "number_record", "numbers_watch"]); for (const name of ["schedule_task", "t3_thread_launch", "create_threads"]) assert.notInclude(toolNames, name); + const cache = cacheSessionsOf(kin)!; + const kinSessions = Context.get(services, KinAgentSessions); + const upkeepRoster = Effect.fn(function* ( + thread: ThreadId, + bearer: string, + ownSession: string | undefined, + ) { + const params = { + _meta: { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": {}, + "io.modelcontextprotocol/clientInfo": { name: "test", version: "1" }, + }, + }; + const stateless = (token: string, method: string, session?: string) => + request("/kin/mcp", token, method, params, session, { + "mcp-method": method, + "mcp-protocol-version": "2026-07-28", + }); + const ownDiscovery = yield* stateless(bearer, "server/discover"); + assert.equal(ownDiscovery.status, 200); + const discovery = yield* bodyOf(ownDiscovery); + const own = yield* stateless(bearer, "tools/list"); + assert.equal(own.status, 200); + const roster = yield* bodyOf(own); + if (thread !== threadId) + assert.notInclude( + decodeToolList(roster).result.tools.map((tool) => tool.name), + "delegate_task", + ); + const scope = yield* kinSessions.resolveAgent(bearer.replace(/^Bearer /, "")); + assert.isDefined(scope); + const sha = kinSessions.lastToolList(thread); + assert.isString(sha); + if (thread === threadId) + yield* Effect.scoped( + Effect.gen(function* () { + const lease = yield* cache.lease({ scope: scope!, sha: sha! }); + const credential = `Bearer ${lease.token}`; + const call = { + ...params, + name: "kin_chat_read", + arguments: { chatId: chat.chatId }, + }; + const headers = { + "mcp-method": "tools/call", + "mcp-name": call.name, + "mcp-protocol-version": "2026-07-28", + }; + assert.equal( + (yield* request("/kin/mcp", credential, "tools/call", call, undefined, headers)) + .status, + 403, + ); + const batch = [{ jsonrpc: "2.0", id: 1, method: "tools/call", params: call }]; + assert.equal( + (yield* request("/kin/mcp", credential, batch, {}, undefined, headers)).status, + 403, + ); + const real = yield* request( + "/kin/mcp", + bearer, + "tools/call", + call, + undefined, + headers, + ); + assert.equal(real.status, 200); + assert.include(yield* bodyOf(real), '"isError":false'); + }), + ); + yield* endAgentWakeups({ + orgId: person.orgId, + threadId: thread, + status: "completed", + }).pipe(Effect.provide(KinEventQueue.layer), Effect.provide(services)); + assert.equal((yield* request("/kin/mcp", bearer, "initialize", initialize)).status, 403); + const cacheToken = yield* Effect.gen(function* () { + const lease = yield* cache.lease({ scope: scope!, sha: sha! }); + const credential = `Bearer ${lease.token}`; + const discover = yield* stateless(credential, "server/discover"); + expect + .soft(discover.status, "lease negotiates the seat's stateless protocol") + .toBe(200); + if (discover.status === 200) { + assert.isUndefined(discover.headers["mcp-session-id"]); + assert.strictEqual(yield* bodyOf(discover), discovery); + } + const list = () => stateless(credential, "tools/list"); + const listed = yield* list(); + expect + .soft(listed.status, thread === threadId ? "owner roster" : "confined roster") + .toBe(200); + if (listed.status === 200) { + assert.strictEqual(yield* bodyOf(listed), roster); + assert.isTrue(yield* Deferred.await(lease.ready)); + } + for (const method of [ + "tools/call", + "ping", + "resources/list", + "prompts/list", + "events/subscribe", + "subscriptions/listen", + ]) + assert.equal((yield* stateless(credential, method)).status, 403, method); + const batch = [{ jsonrpc: "2.0", id: 1, method: "tools/list", params }]; + assert.equal( + (yield* request("/kin/mcp", credential, batch, {}, undefined, { + "mcp-method": "tools/list", + "mcp-protocol-version": "2026-07-28", + })).status, + 403, + ); + assert.equal( + (yield* request("/kin/mcp", credential, "", {}, undefined, {}, http, "GET")).status, + 403, + ); + assert.equal((yield* stateless(credential, "tools/list", ownSession)).status, 403); + assert.equal((yield* stateless(credential, "server/discover", ownSession)).status, 403); + assert.equal( + (yield* request("/kin/mcp", credential, "tools/list", {}, undefined, { + "mcp-protocol-version": "2026-07-28", + "mcp-method": "tools/call", + })).status, + 403, + ); + assert.equal( + (yield* request("/mcp", credential, "server/discover", params, undefined, { + "mcp-method": "server/discover", + "mcp-protocol-version": "2026-07-28", + })).status, + 401, + ); + const terminate = (session: string | undefined) => + request("/kin/mcp", credential, "", {}, session, {}, http, "DELETE"); + assert.equal((yield* terminate(ownSession)).status, 403); + assert.equal((yield* terminate(undefined)).status, 403); + const init = yield* request("/kin/mcp", credential, "initialize", initialize); + assert.equal(init.status, 200); + const session = init.headers["mcp-session-id"]; + assert.isString(session); + assert.equal( + (yield* request("/kin/mcp", credential, "notifications/initialized", {}, session)) + .status, + 202, + ); + const legacyList = () => request("/kin/mcp", credential, "tools/list", {}, session); + assert.equal( + (yield* legacyList()).status, + 409, + "different protocol bytes still fail closed", + ); + if (thread === threadId) { + yield* sql`UPDATE kin_agents SET paused_at = '1970-01-01T00:00:00.000Z' + WHERE org_id = ${person.orgId} AND agent_id = ${agentId}`; + const paused = yield* list(); + yield* sql`UPDATE kin_agents SET paused_at = NULL, retired_at = '1970-01-01T00:00:00.000Z' + WHERE org_id = ${person.orgId} AND agent_id = ${agentId}`; + const retired = yield* list(); + assert.deepEqual( + [paused.status, retired.status], + [403, 403], + "paused and retired leases", + ); + assert.equal((yield* terminate(session)).status, 204); + yield* sql`UPDATE kin_agents SET retired_at = NULL + WHERE org_id = ${person.orgId} AND agent_id = ${agentId}`; + } else { + assert.equal((yield* terminate(session)).status, 204); + } + assert.equal((yield* legacyList()).status, 404); + return credential; + }).pipe(Effect.scoped); + assert.equal( + (yield* request("/kin/mcp", cacheToken, "initialize", initialize)).status, + 401, + ); + }); + yield* upkeepRoster( + threadId, + issued.config.authorizationHeader, + initialized.headers["mcp-session-id"], + ); + yield* startAgentWakeup({ orgId: person.orgId, agentId, threadId }).pipe( + Effect.provide(services), + ); // Nothing a lead asks for goes to another machine, where Kin's checks don't follow it. const leadCall = (name: string, args: unknown) => request( @@ -1324,6 +1530,24 @@ it.effect.each([true, false])( assert.sameMembers(served, Object.keys(OUTSIDE_TOOLS)); // A shared thread lists only what a shared turn may run. const sharedThread = ThreadId.make("kin-shared:lead-group"); + yield* identity.registerAgentThread({ + orgId: person.orgId, + agentId, + threadId: sharedThread, + }); + yield* startAgentWakeup({ orgId: person.orgId, agentId, threadId: sharedThread }).pipe( + Effect.provide(services), + ); + const confinedBearer = (yield* registry.issue({ + threadId: sharedThread, + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + })).config.authorizationHeader; + const confinedInit = yield* request("/kin/mcp", confinedBearer, "initialize", initialize); + assert.equal(confinedInit.status, 200); + yield* upkeepRoster(sharedThread, confinedBearer, confinedInit.headers["mcp-session-id"]); + yield* startAgentWakeup({ orgId: person.orgId, agentId, threadId }).pipe( + Effect.provide(services), + ); for (const name of ["kin_chat_post", "records_query", "kin_relay", "kin_defer"]) assert.isTrue(yield* visibleOnKinEndpoint(name, sharedThread), name); for (const name of [ diff --git a/apps/server/src/kin/mcp/layer.ts b/apps/server/src/kin/mcp/layer.ts index 9103f13ac1ba..fdafb829d122 100644 --- a/apps/server/src/kin/mcp/layer.ts +++ b/apps/server/src/kin/mcp/layer.ts @@ -3,12 +3,13 @@ import type { ThreadId } from "@t3tools/contracts"; import * as NodeCrypto from "node:crypto"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import { McpProtocol } from "effect/ai"; import * as Layer from "effect/Layer"; import type * as Types from "effect/Types"; import * as Option from "effect/Option"; import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; -import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; +import { HttpEffect, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; import { parseBearerToken } from "../../auth/EnvironmentAuth.ts"; import * as McpHttpServer from "../../mcp/McpHttpServer.ts"; import { McpToolPolicy } from "./toolPolicy.ts"; @@ -26,6 +27,8 @@ import { ThreadLaunchService } from "../../orchestration-v2/ThreadLaunchService. import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; import * as SqlitePersistence from "../../persistence/Sqlite.ts"; import { KinServer } from "../KinServer.ts"; +import { cacheSessionsOf } from "../host/cacheSessions.ts"; +import * as Deferred from "effect/Deferred"; import { KinIdentity } from "../chat/KinIdentity.ts"; import { KinChatToolkit, handlers } from "./KinChatToolkit.ts"; import * as KinIssuedTokens from "./KinIssuedTokens.ts"; @@ -39,20 +42,13 @@ const registration = McpHttpServer.toolkitRegistration(KinChatToolkit, handlers, const fromJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); const toJson = Schema.encodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); -/** - * A sha256 of each `tools/list` result a lead's session was served: two sessions' lines with the - * same hash carried the same tool block, which the prompt cache needs. A streamed reply isn't read. - */ -const logToolList = Effect.fnUntraced(function* ( +const toolList = Effect.fn("KinMcp.toolList")(function* ( request: HttpServerRequest.HttpServerRequest, response: HttpServerResponse.HttpServerResponse, - thread: McpThreadCaller | undefined, - registry: KinAgentSessions["Service"], ) { if (request.method !== "POST" || response.body._tag !== "Uint8Array") return; const message = yield* Effect.orElseSucceed(request.json, () => undefined); if (!Predicate.isReadonlyObject(message) || message.method !== "tools/list") return; - // An SSE frame per line of the JSON-RPC reply, which is one line. const text = new TextDecoder() .decode(response.body.body) .trim() @@ -64,16 +60,29 @@ const logToolList = Effect.fnUntraced(function* ( const encoded = toJson(result); if (Option.isNone(encoded)) return; const served = encoded.value; - const toolListSha256 = NodeCrypto.createHash("sha256").update(served).digest("hex"); + return { + toolListSha256: NodeCrypto.createHash("sha256").update(served).digest("hex"), + toolListBytes: new TextEncoder().encode(served).length, + tools: result.tools.length, + }; +}); + +const logToolList = Effect.fn("KinMcp.logToolList")(function* ( + request: HttpServerRequest.HttpServerRequest, + response: HttpServerResponse.HttpServerResponse, + thread: McpThreadCaller | undefined, + registry: KinAgentSessions["Service"], +) { + const list = yield* toolList(request, response); + if (list === undefined) return; if (thread !== undefined) - registry.recordToolList(thread.threadId, thread.providerSessionId, toolListSha256); + registry.recordToolList(thread.threadId, thread.providerSessionId, list.toolListSha256); yield* Effect.logInfo("Kin endpoint tool list.", { threadId: thread?.threadId, providerSessionId: thread?.providerSessionId, - toolListSha256, - toolListBytes: new TextEncoder().encode(served).length, - tools: result.tools.length, + ...list, }); + return list; }); class KinBearerScope extends Context.Service()( "t3/kin/mcp/layer/KinBearerScope", @@ -103,20 +112,99 @@ const auth = HttpRouter.middleware<{ provides: KinBearerScope | KinServer | KinI >, ) { const request = yield* HttpServerRequest.HttpServerRequest; - const scope = yield* registry.resolveAgent(parseBearerToken(request) ?? ""); + const token = parseBearerToken(request) ?? ""; + const cache = cacheSessionsOf(kin); + const lease = cache?.lookup(token); + const scope = lease?.scope ?? (yield* registry.resolveAgent(token)); if (scope === undefined) return HttpServerResponse.empty({ status: 401 }); if (Option.isNone(kin.services)) return HttpServerResponse.empty({ status: 503 }); const identity = Context.get(kin.services.value, KinIdentity); - const admitted = yield* identity.resolveAgent(scope).pipe(Effect.option); - if (Option.isNone(admitted)) return HttpServerResponse.empty({ status: 403 }); + const sessionId = request.headers["mcp-session-id"]; + let method: string | undefined; + if (lease === undefined) { + const admitted = yield* identity.resolveAgent(scope).pipe(Effect.option); + if (Option.isNone(admitted)) return HttpServerResponse.empty({ status: 403 }); + } else if (request.method === "DELETE") { + if (sessionId === undefined || lease.sessionId !== sessionId) + return HttpServerResponse.empty({ status: 403 }); + method = "close"; + } else { + if (request.method !== "POST") return HttpServerResponse.empty({ status: 403 }); + const body = yield* Effect.orElseSucceed(request.json, () => undefined); + if (!Predicate.isReadonlyObject(body) || Array.isArray(body)) + return HttpServerResponse.empty({ status: 403 }); + const stateless = + request.headers["mcp-protocol-version"] === McpProtocol.v2026_07_28.protocolVersion; + method = + body.method === "server/discover" || + body.method === "tools/list" || + body.method === "initialize" || + body.method === "notifications/initialized" + ? body.method + : undefined; + if (method === undefined) return HttpServerResponse.empty({ status: 403 }); + if (stateless || method === "server/discover") { + // Stateless MCP has no session to bind; the transport checks the request metadata. + if ( + !stateless || + sessionId !== undefined || + request.headers["mcp-method"] !== method || + (method !== "server/discover" && method !== "tools/list") + ) + return HttpServerResponse.empty({ status: 403 }); + } else if ( + method !== "initialize" && + (sessionId === undefined || lease.sessionId !== sessionId) + ) { + return HttpServerResponse.empty({ status: 403 }); + } + const admitted = yield* identity.admitUpkeep(scope).pipe(Effect.option); + if (Option.isNone(admitted)) return HttpServerResponse.empty({ status: 403 }); + if (method === "initialize") { + if (sessionId !== undefined || lease.sessionId !== undefined || lease.initializing) + return HttpServerResponse.empty({ status: 403 }); + lease.initializing = true; + } + } const response = yield* effect.pipe( Effect.provideService(KinBearerScope, scope), Effect.provideService(KinServer, kin), Effect.provideService(KinIdentity, identity), + Effect.onError(() => + lease !== undefined && method === "initialize" + ? Effect.sync(() => { + lease.initializing = false; + }) + : Effect.void, + ), ); - yield* logToolList(request, response, scope.thread, registry).pipe( - Effect.catchCause((cause) => Effect.logWarning("Kin tool list log failed", { cause })), - ); + if (lease !== undefined) { + if (method === "initialize") { + // The transport attaches the negotiated id in its pre-response handler. + yield* HttpEffect.appendPreResponseHandler((_request, outgoing) => + Effect.sync(() => { + lease.sessionId = outgoing.headers["mcp-session-id"]; + lease.initializing = false; + return outgoing; + }), + ); + } + yield* Effect.logDebug("kin.session.upkeep.mcp", { method, status: response.status }); + const list = yield* toolList(request, response); + if (list !== undefined) { + const matches = list.toolListSha256 === lease.sha; + yield* Deferred.succeed(lease.ready, matches); + if (!matches) return HttpServerResponse.empty({ status: 409 }); + } + } else { + const list = yield* logToolList(request, response, scope.thread, registry).pipe( + Effect.catchCause(() => + Effect.logWarning("Kin tool list log failed").pipe(Effect.as(undefined)), + ), + ); + if (list !== undefined && cache !== undefined) + yield* cache.observeList(scope, `Bearer ${token}`, list.toolListSha256); + } return response; }) satisfies Auth; }), diff --git a/apps/server/src/kin/numbers/KinNumbers.test.ts b/apps/server/src/kin/numbers/KinNumbers.test.ts index 1374e9a5733f..f6fdb0b4a22d 100644 --- a/apps/server/src/kin/numbers/KinNumbers.test.ts +++ b/apps/server/src/kin/numbers/KinNumbers.test.ts @@ -29,6 +29,7 @@ const layer = Layer.mergeAll( owner: { _tag: "person", orgId: KinOrgId.make("invented"), personId: KinPersonId.make("rhea") }, resolve: () => Effect.succeed([]), resolveAgent: () => Effect.die("Not an identity test"), + admitUpkeep: () => Effect.die("Not an identity test"), agentForWakeup: () => Effect.succeedNone, registerAgentThread: () => Effect.void, endAgentThread: () => Effect.succeed(false), diff --git a/apps/server/src/kin/people/leaver.test.ts b/apps/server/src/kin/people/leaver.test.ts index e7558d3684b5..9b6207acbc0e 100644 --- a/apps/server/src/kin/people/leaver.test.ts +++ b/apps/server/src/kin/people/leaver.test.ts @@ -877,6 +877,8 @@ const HOLDS_SOMEONE: Record = { kin_bill_requests: "person_id", // Past decisions stay company history; they are not ongoing authority for the decider. kin_bill_senders: "decided_by_person_id", + // Cache history grants nothing; paused or retired agents cannot send an upkeep request. + kin_cache_parts: "agent_id", kin_chat_levels: "agent_id", kin_chat_members: "agent_id member_id person_id", // Who pinned a card, shown like a message's author; any writable member unpins, readers' access decides. diff --git a/apps/server/src/kin/persistence/KinMigrations.test.ts b/apps/server/src/kin/persistence/KinMigrations.test.ts index 7297387521c0..d2ac42658a37 100644 --- a/apps/server/src/kin/persistence/KinMigrations.test.ts +++ b/apps/server/src/kin/persistence/KinMigrations.test.ts @@ -73,6 +73,7 @@ const tableNames = [ "kin_budget", "kin_budget_charges", "kin_budget_limits", + "kin_cache_parts", "kin_card_plans", "kin_chat_levels", "kin_chat_members", @@ -580,6 +581,7 @@ describe("Kin migrations", () => { { name: "idx_kin_bill_reads_batch" }, { name: "idx_kin_bill_reads_event" }, { name: "idx_kin_bill_reads_preview" }, + { name: "idx_kin_cache_parts_recent" }, { name: "idx_kin_chat_members_agent" }, { name: "idx_kin_chat_members_person" }, { name: "idx_kin_chat_pins_source" }, @@ -656,6 +658,7 @@ describe("Kin migrations", () => { { name: "idx_kin_waiting_message_id" }, { name: "idx_kin_waiting_open_widget_person" }, { name: "idx_kin_waiting_person_resolved_at" }, + { name: "idx_kin_wakeups_cache_part" }, { name: "idx_kin_wakeups_running_lead" }, { name: "idx_kin_wakeups_started" }, { name: "idx_kin_wakeups_unretired_agent" }, @@ -809,6 +812,8 @@ describe("Kin migrations", () => { yield* sql`ALTER TABLE kin_events DROP COLUMN held_by`; yield* sql`ALTER TABLE kin_events DROP COLUMN replied_at`; yield* sql`ALTER TABLE kin_events DROP COLUMN budget_deferred`; + yield* sql`DROP INDEX idx_kin_wakeups_cache_part`; + yield* sql`DROP TABLE kin_cache_parts`; for (const column of [ "enqueued_at", "prepared_at", @@ -825,6 +830,9 @@ describe("Kin migrations", () => { "context_tokens", "last_request_at", "last_request_kin_at", + "cache_part", + "cache_request_started_at", + "cache_measurement", "ending", ]) yield* sql`ALTER TABLE kin_wakeups DROP COLUMN ${sql(column)}`; @@ -2389,6 +2397,7 @@ describe("Kin migrations", () => { [242, "RemovedRuleLimits"], [243, "BillCorrections"], [244, "CarryClocks"], + [245, "CacheParts"], ]); assert.deepStrictEqual(yield* sql`SELECT * FROM kin_bill_reads`, [ { @@ -2459,6 +2468,7 @@ describe("Kin migrations", () => { [242, "RemovedRuleLimits"], [243, "BillCorrections"], [244, "CarryClocks"], + [245, "CacheParts"], ]); assert.deepStrictEqual(yield* ids, [ { org: "org-ambermill", attachment: ambermill, preview: billPhotoPreviewId(ambermill) }, @@ -2485,6 +2495,7 @@ describe("Kin migrations", () => { [242, "RemovedRuleLimits"], [243, "BillCorrections"], [244, "CarryClocks"], + [245, "CacheParts"], ]); assert.deepStrictEqual( yield* sql`SELECT * FROM kin_bill_reads ORDER BY org_id, sha256`, @@ -2590,12 +2601,13 @@ describe("Kin migrations", () => { [242, "RemovedRuleLimits"], [243, "BillCorrections"], [244, "CarryClocks"], + [245, "CacheParts"], ]); assert.deepStrictEqual(yield* sql`SELECT * FROM kin_bill_reads ORDER BY sha256`, [ { ...before[0], preview_id: billPhotoPreviewId(photo) }, { ...before[1], preview_id: null }, ]); - assert.deepStrictEqual(kinMigrations.at(-1), [244, "CarryClocks"]); + assert.deepStrictEqual(kinMigrations.at(-1), [245, "CacheParts"]); assert.deepStrictEqual(yield* runKinMigrations(), []); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); @@ -3191,13 +3203,17 @@ describe("Kin migrations", () => { }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); - it.effect("K244 adds a nullable company timestamp without reinterpreting old requests", () => + it.effect("K244 and K245 add cache clocks and parts without reinterpreting old requests", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* runKinMigrations(); const [column] = yield* sql`SELECT name FROM pragma_table_info('kin_wakeups') WHERE name = 'last_request_kin_at'`; if (column !== undefined) yield* sql`ALTER TABLE kin_wakeups DROP COLUMN last_request_kin_at`; + yield* sql`DROP INDEX idx_kin_wakeups_cache_part`; + yield* sql`DROP TABLE kin_cache_parts`; + for (const name of ["cache_part", "cache_request_started_at", "cache_measurement"]) + yield* sql`ALTER TABLE kin_wakeups DROP COLUMN ${sql(name)}`; yield* sql`DELETE FROM kin_sql_migrations WHERE migration_id >= 244`; yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) VALUES ('org', 'Kin', 1)`; yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, created_at) @@ -3210,13 +3226,24 @@ describe("Kin migrations", () => { VALUES ('org', 'lead', 'Lead', 1, '{}', '[]', 'chat')`; yield* sql`INSERT INTO kin_wakeups (org_id, agent_id, wakeup_id, model, started_at, status, event_ids, last_request_at) VALUES ('org', 'lead', 'turn', 'test', 1, 'completed', '[]', 42)`; - assert.deepStrictEqual(yield* runKinMigrations(), [[244, "CarryClocks"]]); - const requests = sql`SELECT last_request_at, last_request_kin_at FROM kin_wakeups`; - assert.deepStrictEqual(yield* requests, [{ last_request_at: 42, last_request_kin_at: null }]); + assert.deepStrictEqual(yield* runKinMigrations(), [ + [244, "CarryClocks"], + [245, "CacheParts"], + ]); + const requests = sql`SELECT last_request_at, last_request_kin_at, cache_part FROM kin_wakeups`; + assert.deepStrictEqual(yield* requests, [ + { last_request_at: 42, last_request_kin_at: null, cache_part: null }, + ]); + assert.isEmpty(yield* sql`SELECT * FROM kin_cache_parts`); yield* sql`UPDATE kin_wakeups SET last_request_kin_at = 100`; - yield* sql`DELETE FROM kin_sql_migrations WHERE migration_id = 244`; - assert.deepStrictEqual(yield* runKinMigrations(), [[244, "CarryClocks"]]); - assert.deepStrictEqual(yield* requests, [{ last_request_at: 42, last_request_kin_at: 100 }]); + yield* sql`DELETE FROM kin_sql_migrations WHERE migration_id >= 244`; + assert.deepStrictEqual(yield* runKinMigrations(), [ + [244, "CarryClocks"], + [245, "CacheParts"], + ]); + assert.deepStrictEqual(yield* requests, [ + { last_request_at: 42, last_request_kin_at: 100, cache_part: null }, + ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); @@ -3422,6 +3449,9 @@ describe("Kin migrations", () => { context_tokens: null, last_request_at: null, last_request_kin_at: null, + cache_part: null, + cache_request_started_at: null, + cache_measurement: null, ending: null, }, kin_events: { diff --git a/apps/server/src/kin/persistence/KinMigrations.ts b/apps/server/src/kin/persistence/KinMigrations.ts index 8921de181018..a54799b2a0ae 100644 --- a/apps/server/src/kin/persistence/KinMigrations.ts +++ b/apps/server/src/kin/persistence/KinMigrations.ts @@ -165,6 +165,7 @@ import BillPreviewIds from "./migrations/K241_BillPreviewIds.ts"; import RemovedRuleLimits from "./migrations/K242_RemovedRuleLimits.ts"; import BillCorrections from "./migrations/K243_BillCorrections.ts"; import CarryClocks from "./migrations/K244_CarryClocks.ts"; +import CacheParts from "./migrations/K245_CacheParts.ts"; import * as Effect from "effect/Effect"; import * as Migrator from "effect/sql/Migrator"; @@ -411,6 +412,7 @@ const migrations = { "242_RemovedRuleLimits": RemovedRuleLimits, "243_BillCorrections": BillCorrections, "244_CarryClocks": CarryClocks, + "245_CacheParts": CacheParts, }; const loader = Migrator.fromRecord(migrations); diff --git a/apps/server/src/kin/persistence/migrations/K245_CacheParts.ts b/apps/server/src/kin/persistence/migrations/K245_CacheParts.ts new file mode 100644 index 000000000000..9249ca24194a --- /dev/null +++ b/apps/server/src/kin/persistence/migrations/K245_CacheParts.ts @@ -0,0 +1,28 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE TABLE IF NOT EXISTS kin_cache_parts ( + fingerprint TEXT NOT NULL PRIMARY KEY, + org_id TEXT NOT NULL, + seat TEXT NOT NULL CHECK (seat IN ('owner', 'confined')), + agent_id TEXT NOT NULL, + model TEXT NOT NULL, + last_request_at INTEGER NOT NULL, + last_turn_at INTEGER NOT NULL, + FOREIGN KEY (org_id, agent_id) REFERENCES kin_leads(org_id, agent_id) + )`; + const columns = yield* sql<{ name: string }>`PRAGMA table_info(kin_wakeups)`; + for (const [name, definition] of [ + ["cache_part", "TEXT"], + ["cache_request_started_at", "INTEGER"], + ["cache_measurement", "TEXT"], + ] as const) { + if (!columns.some((column) => column.name === name)) + yield* sql`ALTER TABLE kin_wakeups ADD COLUMN ${sql(name)} ${sql.literal(definition)}`; + } + yield* sql`CREATE INDEX IF NOT EXISTS idx_kin_wakeups_cache_part + ON kin_wakeups(cache_part, cache_request_started_at) WHERE cache_part IS NOT NULL`; + yield* sql`CREATE INDEX IF NOT EXISTS idx_kin_cache_parts_recent ON kin_cache_parts(last_request_at)`; +}); diff --git a/packages/contracts/src/settings.kin.test.ts b/packages/contracts/src/settings.kin.test.ts index f4cc50c21fe2..d16a17be5115 100644 --- a/packages/contracts/src/settings.kin.test.ts +++ b/packages/contracts/src/settings.kin.test.ts @@ -26,9 +26,9 @@ it("defaults Claude instructions to the first block and round-trips explicit pla } }); -it("defaults upkeep off and accepts bounded compaction patches", () => { +it("defaults upkeep on and accepts bounded compaction patches", () => { expect(decodeServerSettings({})).toMatchObject({ - kinSessionUpkeep: false, + kinSessionUpkeep: true, kinSessionCompactAtTokens: 500_000, }); expect( @@ -42,6 +42,10 @@ it("defaults upkeep off and accepts bounded compaction patches", () => { kinSessionUpkeep: true, kinSessionCompactAtTokens: 100_000, }); + expect( + decodeServerSettings(encodeServerSettings(decodeServerSettings({ kinSessionUpkeep: false }))) + .kinSessionUpkeep, + ).toBe(false); expect( decodeServerSettings({ kinSessionCompactAtTokens: 900_000 }).kinSessionCompactAtTokens, ).toBe(800_000); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 6a9e823cff26..fccf83fd0d66 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1421,7 +1421,7 @@ export const ServerSettings = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed("first_block" as const)), ), kinSessionCarry: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), - kinSessionUpkeep: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + kinSessionUpkeep: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), kinSessionCompactAtTokens: KinSessionCompactAtTokens.pipe( Schema.withDecodingDefault(Effect.succeed(500_000)), ), diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.ts index d232369813e1..61f3b707ec18 100644 --- a/packages/shared/src/serverSettings.test.ts +++ b/packages/shared/src/serverSettings.test.ts @@ -91,6 +91,17 @@ describe("fallbackTextGenerationModelSelection", () => { }); describe("serverSettings helpers", () => { + it("leaves the host's upkeep setting unchanged when clients patch settings", () => { + for (const on of [true, false]) { + const current = { ...DEFAULT_SERVER_SETTINGS, kinSessionUpkeep: on }; + const patch = decodeServerSettingsPatch({ kinSessionUpkeep: !on, kinSessionCarry: false }); + expect(applyServerSettingsPatch(current, patch)).toMatchObject({ + kinSessionUpkeep: on, + kinSessionCarry: false, + }); + } + }); + it("translates a shipped client's idle compaction switch into a mode", () => { const off = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { idleCompaction: "off" }); expect([off.idleCompaction, off.compactIdleThreads]).toEqual(["off", false]); diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts index 3efb906c6a89..eff46e742b28 100644 --- a/packages/shared/src/serverSettings.ts +++ b/packages/shared/src/serverSettings.ts @@ -401,6 +401,8 @@ export function applyServerSettingsPatch( backgroundActivity, worktreeCleanup: worktreeCleanupPatch, kinBackgroundModelSelection, + // Keep existing clients wire-compatible; only the host settings file sets this. + kinSessionUpkeep: _hostOnlyUpkeep, // Merged per entry below; its `null` removals must not reach deepMerge. usageLimitSources: usageLimitSourcesPatch, textGenerators: textGeneratorsPatch,