From 72f77c025557a34ab3da8f8b9a284aa4ff5d1ede Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:04:07 +0530 Subject: [PATCH 01/11] feat(kin): keep shared instructions warm when demand pays Use each part's measured request history to schedule a detached Claude cache ping. Give its SDK process the normal instruction block and roster but no tool authority. T3-file: apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts: keep the base leading-block expectation valid with the SDK's string-or-block-array type. People-change: A busy company's agents can reuse their instructions sooner; a quiet company does not pay for keep-warm requests. Co-Authored-By: GPT-6.2 Sol --- apps/server/src/kin/host/cacheParts.ts | 57 +++ apps/server/src/kin/host/cacheSessions.ts | 299 ++++++++++++++ .../server/src/kin/host/sessionUpkeep.test.ts | 232 +++++++++++ apps/server/src/kin/host/sessionUpkeep.ts | 387 ++++++++++++++++++ apps/server/src/kin/layer.ts | 7 +- apps/server/src/kin/lead/WakeupRunner.ts | 2 + apps/server/src/kin/lead/layer.ts | 2 + apps/server/src/kin/lead/sessionCarry.test.ts | 9 + .../src/kin/lead/turn/providers/claude.ts | 49 ++- apps/server/src/kin/mcp/layer.test.ts | 33 ++ apps/server/src/kin/mcp/layer.ts | 71 +++- apps/server/src/kin/people/leaver.test.ts | 2 + .../src/kin/persistence/KinMigrations.test.ts | 46 ++- .../src/kin/persistence/KinMigrations.ts | 2 + .../persistence/migrations/K245_CacheParts.ts | 28 ++ .../Adapters/ClaudeAdapterV2.test.ts | 2 +- packages/contracts/src/settings.kin.test.ts | 8 +- packages/contracts/src/settings.ts | 2 +- packages/shared/src/serverSettings.test.ts | 11 + packages/shared/src/serverSettings.ts | 2 + 20 files changed, 1206 insertions(+), 45 deletions(-) create mode 100644 apps/server/src/kin/host/cacheParts.ts create mode 100644 apps/server/src/kin/host/cacheSessions.ts create mode 100644 apps/server/src/kin/host/sessionUpkeep.test.ts create mode 100644 apps/server/src/kin/host/sessionUpkeep.ts create mode 100644 apps/server/src/kin/persistence/migrations/K245_CacheParts.ts 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.ts b/apps/server/src/kin/host/cacheSessions.ts new file mode 100644 index 000000000000..f7d7f2326fa4 --- /dev/null +++ b/apps/server/src/kin/host/cacheSessions.ts @@ -0,0 +1,299 @@ +// @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 Predicate from "effect/Predicate"; +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; + readonly expiresAt: number; + observed: Observation | undefined; + offeredAt: number | undefined; + fresh: boolean; +} + +interface Lease extends ObservedList { + 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; + return { + read: usage.cache_read_input_tokens ?? 0, + written: usage.cache_creation_input_tokens ?? 0, + input: usage.input_tokens, + }; +}; + +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" + >, + 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), + expiresAt: now + CACHE_LIFETIME_MS, + observed: undefined, + offeredAt: undefined, + fresh: input.options.resume === undefined, + }; + prepared.set(input.threadId, entry); + return { + ...query, + offer: (message) => + Clock.currentTimeMillis.pipe( + Effect.tap((at) => + Effect.sync(() => { + entry.offeredAt = at; + entry.observed = undefined; + prepared.set(input.threadId, entry); + }), + ), + Effect.andThen(query.offer(message)), + ), + 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; + 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.options.model, + fingerprint: hashJson([ + row.orgId, + row.agentId, + entry.seat, + roster.sha, + instructionVersion, + entry.options.model, + "leadingBlock", + entry.block, + ]), + } satisfies CachePart; + yield* recordUse(part, { + wakeupId: row.wakeupId, + startedAt: observation.startedAt, + lastRequestAt: row.lastRequestAt, + ...(observation.usage === undefined ? {} : { freshUsage: observation.usage }), + }); + 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 = { + scope: session.scope, + sha: session.sha, + ready: Deferred.makeUnsafe(), + }; + leases.set(token, lease); + return { token, ...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 isCacheListRequest = (method: string, body: unknown) => + method === "POST" && + Predicate.isReadonlyObject(body) && + (body.method === "initialize" || + body.method === "notifications/initialized" || + body.method === "tools/list"); + +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..b6530eaea5f7 --- /dev/null +++ b/apps/server/src/kin/host/sessionUpkeep.test.ts @@ -0,0 +1,232 @@ +import { assert, it } from "@effect/vitest"; +import { KinAgentId, KinChatId, KinOrgId, KinWakeupId, ThreadId } from "@t3tools/contracts"; +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 CacheParts from "./cacheParts.ts"; +import * as Upkeep from "./sessionUpkeep.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 = 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')`; + 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 run = ( + overrides: { + fingerprint?: string; + placement?: "leadingBlock" | "system"; + enabled?: boolean; + } = {}, +) => + 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 { 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 = gaps.map((gap, i) => (i === 0 ? 10 : gap)); + 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(19).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(19).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-0'`; + 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("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 = Upkeep.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); + 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..c637dad0ca77 --- /dev/null +++ b/apps/server/src/kin/host/sessionUpkeep.ts @@ -0,0 +1,387 @@ +// @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 SDKUserMessage, +} from "@anthropic-ai/claude-agent-sdk"; +import * as Clock from "effect/Clock"; +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 Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import type { ClaudeAgentSdkQueryOptions } from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; +import * as Scheduler from "../../scheduling/Scheduler.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import { KinDevClock } from "../DevClock.ts"; +import { + instructionPlacement, + type InstructionPlacement, +} from "../lead/turn/providers/provider.ts"; +import type { CachePart } from "./cacheParts.ts"; +import { CACHE_LIFETIME_MS, KinCacheSessions, type LeadingBlock } from "./cacheSessions.ts"; + +const MINUTE = 60_000; +const EVERY_MS = 5 * MINUTE; +const PING_AT = 50 * MINUTE; +const LOOKBACK = 14 * 24 * 60 * MINUTE; +const UPKEEP_LINE = "Reply with one word: Ready."; + +const PingUsage = Schema.Struct({ + read: Schema.Number, + written: Schema.Number, + input: Schema.Number, + output: Schema.Number, + cost: Schema.Number, +}); +type PingUsage = typeof PingUsage.Type; +const UsageJson = Schema.fromJsonString(PingUsage); +const encodeUsage = Schema.encodeEffect(UsageJson); +const decodeUsage = Schema.decodeUnknownOption(UsageJson); + +type Ping = + | { readonly status: "completed" | "failed"; readonly usage: PingUsage | null } + | { readonly status: "skipped" }; + +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 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, + 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 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<{ + samples: number; + 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(*) AS samples, 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.samples < 20 || + gaps.atRisk === 0 || + 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 }>`SELECT tokens_json AS tokens + FROM kin_wakeups WHERE cache_part = ${part.fingerprint} AND kind = 'upkeep' + AND status = 'completed' AND started_at >= ${cutoff} + AND json_extract(tokens_json, '$.read') > ${gaps.coldRead} + ORDER BY cache_request_started_at DESC LIMIT 1`; + // A warm ordinary opening bounds the ping's shorter input until the ping has its own measurement. + const sample = Option.getOrUndefined(decodeUsage(measured?.tokens)); + const ping = sample === undefined ? gaps.warmCost + 5 : costUnits(sample); + 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 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; + }); + 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 = `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 (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, + }); + } +}); + +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"); + +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 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* Effect.tryPromise({ + try: async () => { + for await (const message of runtime) { + if (message.type !== "result") continue; + const usage = { + read: message.usage.cache_read_input_tokens ?? 0, + written: message.usage.cache_creation_input_tokens ?? 0, + input: message.usage.input_tokens, + output: message.usage.output_tokens, + cost: message.total_cost_usd, + }; + return { + status: message.subtype === "success" && !message.is_error ? "completed" : "failed", + usage, + } as const; + } + return { status: "failed", usage: null } as const; + }, + catch: () => "result", + }).pipe(Effect.timeout("90 seconds")); +}); + +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/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/WakeupRunner.ts b/apps/server/src/kin/lead/WakeupRunner.ts index 8229aaf5f1ad..54f105fe2079 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/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 dd656b3ec3a4..84927be089cf 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"; @@ -352,6 +354,7 @@ const install = (base: Layer.Layer()); return ClaudeAdapterV2.ClaudeAgentSdkQueryRunner.of({ @@ -402,22 +405,44 @@ const install = (base: Layer.Layer request( diff --git a/apps/server/src/kin/mcp/layer.ts b/apps/server/src/kin/mcp/layer.ts index 9103f13ac1ba..32886211d2ff 100644 --- a/apps/server/src/kin/mcp/layer.ts +++ b/apps/server/src/kin/mcp/layer.ts @@ -26,6 +26,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, isCacheListRequest } 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 +41,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 +59,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 +111,45 @@ 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 }); + if (lease === undefined) { + const admitted = yield* identity.resolveAgent(scope).pipe(Effect.option); + if (Option.isNone(admitted)) return HttpServerResponse.empty({ status: 403 }); + } else { + const body = yield* Effect.orElseSucceed(request.json, () => undefined); + if ( + !identity.isAgentThread(scope.thread.threadId) || + !isCacheListRequest(request.method, body) + ) + return HttpServerResponse.empty({ status: 403 }); + } const response = yield* effect.pipe( Effect.provideService(KinBearerScope, scope), Effect.provideService(KinServer, kin), Effect.provideService(KinIdentity, identity), ); - yield* logToolList(request, response, scope.thread, registry).pipe( - Effect.catchCause((cause) => Effect.logWarning("Kin tool list log failed", { cause })), - ); + if (lease !== undefined) { + 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/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/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 3c5c8c453c8c..31ffa8c13242 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -3489,7 +3489,7 @@ describe("ClaudeAdapterV2 MCP credential channel", () => { // The session's rules are only ever in its first block: a goal must not use it up. assert.deepEqual(yield* offer(ordinary), [ openingBlock, - { type: "text", text: ordinary.message.content }, + { type: "text", text: "Original T3 prompt." }, ]); assert.deepEqual(yield* offer(ordinary), ordinary.message.content); }).pipe(Effect.scoped), diff --git a/packages/contracts/src/settings.kin.test.ts b/packages/contracts/src/settings.kin.test.ts index c42e0533df17..15b65ee37129 100644 --- a/packages/contracts/src/settings.kin.test.ts +++ b/packages/contracts/src/settings.kin.test.ts @@ -16,9 +16,9 @@ it("an explicit false stays off", () => { expect(decodeServerSettings(saved).kinSessionCarry).toBe(false); }); -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( @@ -32,6 +32,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 ae807e9ed88e..52839b4130e5 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1418,7 +1418,7 @@ export const ServerSettings = Schema.Struct({ /** Kin: a turn's progress updates leave the chat once its reply is posted; nothing is deleted. */ kinClearUpdatesAfterReply: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), 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, From 1cdee183c99d0e3dd2aec62b4dac282994b0163e Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:05:00 +0530 Subject: [PATCH 02/11] chore(kin): document the host-settings test boundary T3-file: packages/shared/src/serverSettings.test.ts: verify the shared patch implementation cannot toggle a host-only setting without removing the existing wire field. People-change: None; records why the test belongs at the shared settings boundary. Co-Authored-By: GPT-6.2 Sol From fcd08aacc265a97fbb8dccedec31c858901d3aca Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:11:55 +0530 Subject: [PATCH 03/11] fix(kin): preserve live Claude turn acknowledgements Forward the accepted-offer acknowledgement. Keep part observations fresh over a long-running query and refuse to warm a stale launch after a live model or flag change. People-change: Ordinary chats still acknowledge queued replies when cache measurement is on. Co-Authored-By: GPT-6.2 Sol --- .../server/src/kin/host/cacheSessions.test.ts | 155 ++++++++++++++++++ apps/server/src/kin/host/cacheSessions.ts | 49 +++++- 2 files changed, 195 insertions(+), 9 deletions(-) create mode 100644 apps/server/src/kin/host/cacheSessions.test.ts 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..53f8bad62fad --- /dev/null +++ b/apps/server/src/kin/host/cacheSessions.test.ts @@ -0,0 +1,155 @@ +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), + 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 index f7d7f2326fa4..9237a22d4226 100644 --- a/apps/server/src/kin/host/cacheSessions.ts +++ b/apps/server/src/kin/host/cacheSessions.ts @@ -51,7 +51,9 @@ interface Prepared { readonly threadId: ThreadId; readonly authHash: string; readonly configHash: string; - readonly expiresAt: number; + expiresAt: number; + model: string; + replayable: boolean; observed: Observation | undefined; offeredAt: number | undefined; fresh: boolean; @@ -84,9 +86,9 @@ const measure = (message: SDKMessage) => { return undefined; const { usage } = message.event.message; return { - read: usage.cache_read_input_tokens ?? 0, - written: usage.cache_creation_input_tokens ?? 0, - input: usage.input_tokens, + read: usage?.cache_read_input_tokens ?? 0, + written: usage?.cache_creation_input_tokens ?? 0, + input: usage?.input_tokens ?? 0, }; }; @@ -110,7 +112,14 @@ const make = () => { observeQuery: Effect.fn("KinCacheSessions.observeQuery")(function* ( input: Omit< Prepared, - "authHash" | "configHash" | "expiresAt" | "observed" | "offeredAt" | "fresh" + | "authHash" + | "configHash" + | "expiresAt" + | "observed" + | "offeredAt" + | "fresh" + | "model" + | "replayable" >, settings: ServerSettings, query: ClaudeAgentSdkQuerySession, @@ -132,24 +141,44 @@ const make = () => { 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, - offer: (message) => + 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)), + Effect.andThen(query.offer(message, onQueued)), ), messages: query.messages.pipe( Stream.tap((message) => @@ -197,6 +226,7 @@ const make = () => { 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}`; @@ -205,14 +235,14 @@ const make = () => { orgId: row.orgId, agentId: row.agentId, seat: entry.seat, - model: entry.options.model, + model: entry.model, fingerprint: hashJson([ row.orgId, row.agentId, entry.seat, roster.sha, instructionVersion, - entry.options.model, + entry.model, "leadingBlock", entry.block, ]), @@ -223,6 +253,7 @@ const make = () => { lastRequestAt: row.lastRequestAt, ...(observation.usage === undefined ? {} : { freshUsage: observation.usage }), }); + if (!entry.replayable) return; sessions.set(slot(part), { part, scope: roster.scope, From ebed2f1d43c25e5fd07d17aeecf89791dbba6a76 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:36:50 +0530 Subject: [PATCH 04/11] fix(kin): price the next keep-warm ping from the last one, hit or miss A ping that missed the cache rewrote the whole block, but only hits were used to price the next ping, so a prefix that never matched kept pinging at rewrite cost. The latest completed ping now prices the next one, and a miss stops pings for that part. People-change: A company whose keep-warm requests stop matching no longer pays for them repeatedly. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/host/sessionUpkeep.test.ts | 14 ++++++++++++++ apps/server/src/kin/host/sessionUpkeep.ts | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/apps/server/src/kin/host/sessionUpkeep.test.ts b/apps/server/src/kin/host/sessionUpkeep.test.ts index b6530eaea5f7..61995933466b 100644 --- a/apps/server/src/kin/host/sessionUpkeep.test.ts +++ b/apps/server/src/kin/host/sessionUpkeep.test.ts @@ -167,6 +167,20 @@ it.effect("accepts a measured cost exactly equal to the chance-weighted rewrite" }).pipe(Effect.provide(layer)), ); +it.effect("a ping that rewrote the block prices the next one", () => + Effect.gen(function* () { + yield* seed([10, ...Array(19).fill(65)]); + const sql = yield* SqlClient.SqlClient; + const missed = JSON.stringify({ read: 16_000, written: 19_000, input: 4, output: 1, cost: 0.16 }); + 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 ('kin-upkeep:missed', ${orgId}, ${agentId}, ${model}, ${now - 2 * 60 * minute}, + ${now - 2 * 60 * minute}, 'completed', '[]', 'upkeep', ${missed}, ${now - 2 * 60 * minute}, + ${part.fingerprint}, ${now - 2 * 60 * minute})`; + assert.deepEqual(yield* run(), []); + }).pipe(Effect.provide(layer)), +); + it.effect("a quiet company sends no pings for a week", () => Effect.gen(function* () { yield* seed([]); diff --git a/apps/server/src/kin/host/sessionUpkeep.ts b/apps/server/src/kin/host/sessionUpkeep.ts index c637dad0ca77..6c2f9dc91598 100644 --- a/apps/server/src/kin/host/sessionUpkeep.ts +++ b/apps/server/src/kin/host/sessionUpkeep.ts @@ -161,9 +161,9 @@ const estimate = Effect.fn("KinSessionUpkeep.estimate")(function* (part: Candida const [measured] = yield* sql<{ tokens: string }>`SELECT tokens_json AS tokens FROM kin_wakeups WHERE cache_part = ${part.fingerprint} AND kind = 'upkeep' AND status = 'completed' AND started_at >= ${cutoff} - AND json_extract(tokens_json, '$.read') > ${gaps.coldRead} ORDER BY cache_request_started_at DESC LIMIT 1`; // A warm ordinary opening bounds the ping's shorter input until the ping has its own measurement. + // A ping that missed and rewrote the block prices the next one, so a prefix that never matches stops. const sample = Option.getOrUndefined(decodeUsage(measured?.tokens)); const ping = sample === undefined ? gaps.warmCost + 5 : costUnits(sample); const share = gaps.ended / gaps.atRisk; From 071ec06740241e1324f05522eff0127f7f341542 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:36:50 +0530 Subject: [PATCH 05/11] fix(kin): keep-warm rows are not turns for reactions or failed wake-ups A completed keep-warm row moved the lead's "since your last turn" mark, so the owner's reactions before a ping never reached the next turn; a failed one counted in the evening summary's failed wake-ups. Both reads now count only kind = 'turn'. People-change: The owner's reactions reach the lead's next turn even after a keep-warm request; the evening summary no longer reports keep-warm failures as failed wake-ups. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/lead/LeadPrompt.test.ts | 5 ++++- apps/server/src/kin/lead/LeadPrompt.ts | 2 +- apps/server/src/kin/lead/RoutineContent.test.ts | 7 +++++++ apps/server/src/kin/lead/RoutineContent.ts | 3 ++- 4 files changed, 14 insertions(+), 3 deletions(-) diff --git a/apps/server/src/kin/lead/LeadPrompt.test.ts b/apps/server/src/kin/lead/LeadPrompt.test.ts index 3f739cbebc24..a437b1260df7 100644 --- a/apps/server/src/kin/lead/LeadPrompt.test.ts +++ b/apps/server/src/kin/lead/LeadPrompt.test.ts @@ -4211,7 +4211,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 e0466e01a428..5903ed91a37d 100644 --- a/apps/server/src/kin/lead/LeadPrompt.ts +++ b/apps/server/src/kin/lead/LeadPrompt.ts @@ -1624,7 +1624,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..b992be7902cd 100644 --- a/apps/server/src/kin/lead/RoutineContent.test.ts +++ b/apps/server/src/kin/lead/RoutineContent.test.ts @@ -983,6 +983,13 @@ 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')`; + const after = yield* content.eveningFacts(orgId, agentId); + assert.strictEqual(JSON.parse(after ?? "{}").failedWakeups, 0); }).pipe(Effect.orDie), ), ); diff --git a/apps/server/src/kin/lead/RoutineContent.ts b/apps/server/src/kin/lead/RoutineContent.ts index 1226d8026cd0..8cbc7b5cdc18 100644 --- a/apps/server/src/kin/lead/RoutineContent.ts +++ b/apps/server/src/kin/lead/RoutineContent.ts @@ -502,7 +502,8 @@ 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 From 6c7d8a4f661998e3a3f32b28b6e3cad743ea4310 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:01:14 +0530 Subject: [PATCH 06/11] fix(kin): charge keep-warm spend and stop after one response MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bill known usage through KinBudget, require a real at-risk sample, and stop on unknown-cost results until a real turn supplies evidence. Keep the normal stream safe and close only the leased MCP session. People-change: Keep-warm requests count once toward the owner’s budget and shown spend, without adding chat turns. Co-Authored-By: GPT-6.2 Sol --- .../server/src/kin/host/cacheSessions.test.ts | 5 +- apps/server/src/kin/host/cacheSessions.ts | 20 +- .../server/src/kin/host/sessionUpkeep.test.ts | 240 +++++++++++++++- apps/server/src/kin/host/sessionUpkeep.ts | 209 +++----------- .../server/src/kin/host/sessionUpkeepQuery.ts | 264 ++++++++++++++++++ apps/server/src/kin/lead/KinBudget.ts | 4 +- .../src/kin/lead/KinLeadProvision.test.ts | 11 + .../src/kin/lead/RoutineContent.test.ts | 12 +- apps/server/src/kin/lead/agentPage.ts | 2 +- apps/server/src/kin/mcp/layer.test.ts | 15 +- apps/server/src/kin/mcp/layer.ts | 34 ++- 11 files changed, 632 insertions(+), 184 deletions(-) create mode 100644 apps/server/src/kin/host/sessionUpkeepQuery.ts diff --git a/apps/server/src/kin/host/cacheSessions.test.ts b/apps/server/src/kin/host/cacheSessions.test.ts index 53f8bad62fad..f0e29780e9fa 100644 --- a/apps/server/src/kin/host/cacheSessions.test.ts +++ b/apps/server/src/kin/host/cacheSessions.test.ts @@ -76,7 +76,10 @@ it.effect( DEFAULT_SERVER_SETTINGS, { offer: (_message, queued) => Effect.sync(() => queued?.()), - messages: Stream.make(message), + messages: Stream.make( + { ...message, event: { type: "message_start" } } as SDKMessage, + message, + ), setModel: () => Effect.void, applyFlagSettings: () => unused, setPermissionMode: () => unused, diff --git a/apps/server/src/kin/host/cacheSessions.ts b/apps/server/src/kin/host/cacheSessions.ts index 9237a22d4226..3ec6e2bd4d38 100644 --- a/apps/server/src/kin/host/cacheSessions.ts +++ b/apps/server/src/kin/host/cacheSessions.ts @@ -60,6 +60,9 @@ interface Prepared { } interface Lease extends ObservedList { + readonly token: string; + sessionId: string | undefined; + initializing: boolean; readonly ready: Deferred.Deferred; } @@ -81,10 +84,11 @@ const measure = (message: SDKMessage) => { if ( message.type !== "stream_event" || message.parent_tool_use_id !== null || - message.event.type !== "message_start" + message.event?.type !== "message_start" ) return undefined; - const { usage } = message.event.message; + 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, @@ -280,13 +284,16 @@ const make = () => { Effect.acquireRelease( Effect.sync(() => { const token = NodeCrypto.randomBytes(32).toString("hex"); - const lease = { + const lease: Lease = { + token, + sessionId: undefined, + initializing: false, scope: session.scope, sha: session.sha, ready: Deferred.makeUnsafe(), }; leases.set(token, lease); - return { token, ...lease }; + return lease; }), ({ token }) => Effect.sync(() => { @@ -303,7 +310,10 @@ export class KinCacheSessions extends Context.Service +export const isCacheListRequest = ( + method: string, + body: unknown, +): body is { readonly method: "initialize" | "notifications/initialized" | "tools/list" } => method === "POST" && Predicate.isReadonlyObject(body) && (body.method === "initialize" || diff --git a/apps/server/src/kin/host/sessionUpkeep.test.ts b/apps/server/src/kin/host/sessionUpkeep.test.ts index 61995933466b..d352b5000835 100644 --- a/apps/server/src/kin/host/sessionUpkeep.test.ts +++ b/apps/server/src/kin/host/sessionUpkeep.test.ts @@ -1,13 +1,20 @@ +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; @@ -24,7 +31,14 @@ const part = { fingerprint: "fixture-part", }; -const layer = makeMigratedSqliteLayer(); +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); @@ -39,6 +53,8 @@ const seed = Effect.fn("UpkeepTest.seed")(function* (gaps: ReadonlyArray 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; @@ -63,6 +79,10 @@ const run = ( fingerprint?: string; placement?: "leadingBlock" | "system"; enabled?: boolean; + outcome?: { + status: "failed" | "completed"; + usage: (Omit & { cost: number | null }) | null; + }; } = {}, ) => Effect.gen(function* () { @@ -74,7 +94,7 @@ const run = ( ping: (due) => Effect.sync(() => { seen.push(due.fingerprint); - return { status: "completed", usage } as const; + return overrides.outcome ?? ({ status: "completed", usage } as const); }), }); return seen; @@ -96,7 +116,7 @@ it.effect.each([ ] 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 = gaps.map((gap, i) => (i === 0 ? 10 : gap)); + const history = [10, ...gaps]; yield* seed(history); assert.deepEqual(yield* run(options), due ? [part.fingerprint] : []); }).pipe(Effect.provide(layer)), @@ -106,7 +126,7 @@ 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(19).fill(65)]); + 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')`; @@ -144,9 +164,9 @@ it.effect( it.effect("does not use another fingerprint's traffic and does not rewrite a dead cache", () => Effect.gen(function* () { - yield* seed([10, ...Array(19).fill(65)]); + 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-0'`; + 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"); @@ -169,9 +189,15 @@ it.effect("accepts a measured cost exactly equal to the chance-weighted rewrite" it.effect("a ping that rewrote the block prices the next one", () => Effect.gen(function* () { - yield* seed([10, ...Array(19).fill(65)]); + yield* seed([10, ...Array(20).fill(65)]); const sql = yield* SqlClient.SqlClient; - const missed = JSON.stringify({ read: 16_000, written: 19_000, input: 4, output: 1, cost: 0.16 }); + const missed = JSON.stringify({ + read: 16_000, + written: 19_000, + input: 4, + output: 1, + cost: 0.16, + }); 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 ('kin-upkeep:missed', ${orgId}, ${agentId}, ${model}, ${now - 2 * 60 * minute}, @@ -181,6 +207,201 @@ it.effect("a ping that rewrote the block prices the next one", () => }).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: 31104, + cachedInputTokens: 31000, + }); + 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); + }).pipe(Effect.provide(layer)), +); + +it.effect("does not send while the owner's lead limit is reached", () => + 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); + yield* sql`UPDATE kin_budget SET lead_units = 100 WHERE org_id = ${orgId} AND day = ${day}`; + assert.deepEqual(yield* run(), []); + }).pipe(Effect.provide(layer)), +); + +it.effect("rechecks spend if the budget fills while the ping is preparing", () => + 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.prepareAtLimit")(function* (_, stillDue) { + prepared = true; + yield* sql`UPDATE kin_budget SET lead_units = 100 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 FROM kin_budget_charges`, + known ? [{ units: 3208 }] : [], + ); + 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([]); @@ -198,7 +419,7 @@ it.effect("keeps the exact block and denies native, MCP, new tools and tool disc text: "Exact shared bytes\n", cache_control: { type: "ephemeral", ttl: "1h" }, } as const; - const request = Upkeep.makePingRequest( + const request = makePingRequest( { block, options: { @@ -213,6 +434,7 @@ it.effect("keeps the exact block and denies native, MCP, new tools and tool disc 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"); diff --git a/apps/server/src/kin/host/sessionUpkeep.ts b/apps/server/src/kin/host/sessionUpkeep.ts index 6c2f9dc91598..e304e289aa03 100644 --- a/apps/server/src/kin/host/sessionUpkeep.ts +++ b/apps/server/src/kin/host/sessionUpkeep.ts @@ -1,52 +1,34 @@ // @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 SDKUserMessage, -} from "@anthropic-ai/claude-agent-sdk"; +import { KinWakeupId } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; -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 Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; -import type { ClaudeAgentSdkQueryOptions } from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; 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 { CACHE_LIFETIME_MS, KinCacheSessions, type LeadingBlock } from "./cacheSessions.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 UPKEEP_LINE = "Reply with one word: Ready."; -const PingUsage = Schema.Struct({ - read: Schema.Number, - written: Schema.Number, - input: Schema.Number, - output: Schema.Number, - cost: Schema.Number, -}); -type PingUsage = typeof PingUsage.Type; const UsageJson = Schema.fromJsonString(PingUsage); const encodeUsage = Schema.encodeEffect(UsageJson); const decodeUsage = Schema.decodeUnknownOption(UsageJson); -type Ping = - | { readonly status: "completed" | "failed"; readonly usage: PingUsage | null } - | { readonly status: "skipped" }; - interface Candidate extends CachePart { readonly modelsJson: string; readonly lastRequestAt: number; @@ -61,54 +43,7 @@ interface Due extends Candidate { type SendPing = (due: Due, stillDue: Effect.Effect) => Effect.Effect; -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, - 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 costUnits = (usage: Omit) => +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) { @@ -117,7 +52,6 @@ const estimate = Effect.fn("KinSessionUpkeep.estimate")(function* (part: Candida const idle = now - part.lastTurnAt; const cutoff = now - LOOKBACK; const [gaps] = yield* sql<{ - samples: number; atRisk: number; ended: number; warmRead: number | null; @@ -139,7 +73,7 @@ const estimate = Effect.fn("KinSessionUpkeep.estimate")(function* (part: Candida COALESCE(json_extract(usage, '$.input'), 0) AS input FROM requests WHERE preceding IS NOT NULL AND started > preceding ) - SELECT COUNT(*) AS samples, COUNT(CASE WHEN gap >= ${idle} THEN 1 END) AS "atRisk", + 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", @@ -148,8 +82,7 @@ const estimate = Effect.fn("KinSessionUpkeep.estimate")(function* (part: Candida FROM gaps`; if ( gaps === undefined || - gaps.samples < 20 || - gaps.atRisk === 0 || + gaps.atRisk < 20 || gaps.warmRead === null || gaps.warmCost === null || gaps.coldRead === null || @@ -158,14 +91,21 @@ const estimate = Effect.fn("KinSessionUpkeep.estimate")(function* (part: Candida return undefined; const rewrite = Math.min(gaps.warmRead - gaps.coldRead, gaps.coldWrite) * 2; if (rewrite <= 0) return undefined; - const [measured] = yield* sql<{ tokens: string }>`SELECT tokens_json AS tokens + const [measured] = yield* sql<{ + tokens: string | null; + endedAt: number; + status: "failed" | "completed"; + }>`SELECT tokens_json AS tokens, ended_at AS "endedAt", status FROM kin_wakeups WHERE cache_part = ${part.fingerprint} AND kind = 'upkeep' - AND status = 'completed' AND started_at >= ${cutoff} - ORDER BY cache_request_started_at DESC LIMIT 1`; + AND status IN ('completed', 'failed') AND started_at >= ${cutoff} + ORDER BY cache_request_started_at DESC, wakeup_id DESC LIMIT 1`; // A warm ordinary opening bounds the ping's shorter input until the ping has its own measurement. // A ping that missed and rewrote the block prices the next one, so a prefix that never matches stops. const sample = Option.getOrUndefined(decodeUsage(measured?.tokens)); - const ping = sample === undefined ? gaps.warmCost + 5 : costUnits(sample); + // An unfinished request can cost a full rewrite; even certainty cannot justify repeating it. + const priced = sample !== undefined && (sample.cost !== null || measured?.status === "completed"); + if (!priced && measured !== undefined && measured.endedAt >= part.lastTurnAt) return undefined; + const ping = priced ? costUnits(sample) : gaps.warmCost + 5; const share = gaps.ended / gaps.atRisk; return share >= ping / rewrite ? { share, coldRead: gaps.coldRead } : undefined; }); @@ -179,6 +119,7 @@ export const check = Effect.fn("KinSessionUpkeep.check")(function* (input: { }) { 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` @@ -200,7 +141,11 @@ export const check = Effect.fn("KinSessionUpkeep.check")(function* (input: { 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; + return ( + active !== undefined && + input.current(part) === part.fingerprint && + !(yield* budget.admit(part.orgId, "P1")).atLimit + ); }); if (!(yield* stillDue)) continue; const result = yield* estimate(part, now); @@ -224,7 +169,7 @@ export const check = Effect.fn("KinSessionUpkeep.check")(function* (input: { const endedAt = yield* time; const requested = sent.status === "completed" && sent.usage !== null; const warmed = requested && (sent.usage?.read ?? 0) > result.coldRead; - const wakeupId = `kin-upkeep:${NodeCrypto.randomUUID()}`; + const wakeupId = KinWakeupId.make(`kin-upkeep:${NodeCrypto.randomUUID()}`); const tokens = sent.usage === null ? null : yield* encodeUsage(sent.usage); yield* sql.withTransaction( Effect.gen(function* () { @@ -233,6 +178,27 @@ export const check = Effect.fn("KinSessionUpkeep.check")(function* (input: { 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: "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}`; @@ -250,89 +216,6 @@ export const check = Effect.fn("KinSessionUpkeep.check")(function* (input: { } }); -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"); - -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 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* Effect.tryPromise({ - try: async () => { - for await (const message of runtime) { - if (message.type !== "result") continue; - const usage = { - read: message.usage.cache_read_input_tokens ?? 0, - written: message.usage.cache_creation_input_tokens ?? 0, - input: message.usage.input_tokens, - output: message.usage.output_tokens, - cost: message.total_cost_usd, - }; - return { - status: message.subtype === "success" && !message.is_error ? "completed" : "failed", - usage, - } as const; - } - return { status: "failed", usage: null } as const; - }, - catch: () => "result", - }).pipe(Effect.timeout("90 seconds")); -}); - export const layer = Layer.effectDiscard( Effect.gen(function* () { const cache = Option.getOrUndefined(yield* Effect.serviceOption(KinCacheSessions)); 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/lead/KinBudget.ts b/apps/server/src/kin/lead/KinBudget.ts index 0d3abacd1bae..4178269e743f 100644 --- a/apps/server/src/kin/lead/KinBudget.ts +++ b/apps/server/src/kin/lead/KinBudget.ts @@ -727,7 +727,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/RoutineContent.test.ts b/apps/server/src/kin/lead/RoutineContent.test.ts index b992be7902cd..b9d79bbbd0f2 100644 --- a/apps/server/src/kin/lead/RoutineContent.test.ts +++ b/apps/server/src/kin/lead/RoutineContent.test.ts @@ -988,8 +988,18 @@ it.effect("an evening whose only news is in Kin's records is summed up, by the c 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_budget (org_id, day, lead_units) VALUES (${orgId}, '2026-11-09', 3208)`; + 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}}]')`; const after = yield* content.eveningFacts(orgId, agentId); - assert.strictEqual(JSON.parse(after ?? "{}").failedWakeups, 0); + assert.include(JSON.parse(after ?? "{}"), { + failedWakeups: 0, + units: 3208, + cacheHitRate: 31_000 / 31_104, + }); }).pipe(Effect.orDie), ), ); 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/mcp/layer.test.ts b/apps/server/src/kin/mcp/layer.test.ts index 02ee6f1886e4..595b073c8138 100644 --- a/apps/server/src/kin/mcp/layer.test.ts +++ b/apps/server/src/kin/mcp/layer.test.ts @@ -371,6 +371,7 @@ it.effect.each([true, false])( session?: string, extra: Record = {}, server = http, + verb = "POST", ) => Effect.gen(function* () { const sent = yield* Deferred.make(); @@ -392,7 +393,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", @@ -400,7 +401,9 @@ 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({ jsonrpc: "2.0", id: 1, method, params }) } + : {}), }), ), ), @@ -662,6 +665,14 @@ it.effect.each([true, false])( ); assert.equal(attempted.status, 403); assert.equal((yield* request("/mcp", credential, "initialize", initialize)).status, 401); + const terminate = (session: string | undefined) => + request("/kin/mcp", credential, "", {}, session, {}, http, "DELETE"); + assert.equal((yield* terminate(initialized.headers["mcp-session-id"])).status, 403); + assert.equal((yield* terminate(session)).status, 204); + assert.equal( + (yield* request("/kin/mcp", credential, "tools/list", {}, session)).status, + 404, + ); return credential; }).pipe(Effect.scoped); assert.equal( diff --git a/apps/server/src/kin/mcp/layer.ts b/apps/server/src/kin/mcp/layer.ts index 32886211d2ff..98134275313d 100644 --- a/apps/server/src/kin/mcp/layer.ts +++ b/apps/server/src/kin/mcp/layer.ts @@ -8,7 +8,7 @@ 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"; @@ -118,9 +118,15 @@ const auth = HttpRouter.middleware<{ provides: KinBearerScope | KinServer | KinI 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 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 { const body = yield* Effect.orElseSucceed(request.json, () => undefined); if ( @@ -128,13 +134,39 @@ const auth = HttpRouter.middleware<{ provides: KinBearerScope | KinServer | KinI !isCacheListRequest(request.method, body) ) return HttpServerResponse.empty({ status: 403 }); + method = body.method; + if (method === "initialize") { + if (sessionId !== undefined || lease.sessionId !== undefined || lease.initializing) + return HttpServerResponse.empty({ status: 403 }); + lease.initializing = true; + } else if (sessionId === undefined || lease.sessionId !== sessionId) { + return HttpServerResponse.empty({ status: 403 }); + } } 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, + ), ); 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; From 9168a1a3e08eb793135fde71beb9cc50276f0e90 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:20:59 +0530 Subject: [PATCH 07/11] fix(kin): negotiate the same MCP roster for cache upkeep Claude used stateless discovery for agent turns but fell back to a different descriptor schema for a stateful upkeep lease. Pin the documented stateful handshake for both leading-block queries and recheck active-agent admission before serving a lease. People-change: Keep-warm requests can now reuse the same tools a fresh agent session sees, and paused or retired agents cannot open upkeep sessions. Co-Authored-By: GPT-6.2 Sol --- .../src/kin/chat/KinChatRepository.test.ts | 1 + apps/server/src/kin/chat/KinChatRepository.ts | 11 +- apps/server/src/kin/chat/KinIdentity.ts | 61 +++--- .../server/src/kin/host/sessionUpkeep.test.ts | 2 + .../__snapshots__/claude.test.ts.snap | 8 +- .../kin/lead/turn/providers/claude.test.ts | 5 + .../src/kin/lead/turn/providers/claude.ts | 2 + apps/server/src/kin/mcp/layer.test.ts | 179 ++++++++++++++---- apps/server/src/kin/mcp/layer.ts | 7 +- 9 files changed, 205 insertions(+), 71 deletions(-) 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/sessionUpkeep.test.ts b/apps/server/src/kin/host/sessionUpkeep.test.ts index d352b5000835..02ed32862c6a 100644 --- a/apps/server/src/kin/host/sessionUpkeep.test.ts +++ b/apps/server/src/kin/host/sessionUpkeep.test.ts @@ -427,6 +427,7 @@ it.effect("keeps the exact block and denies native, MCP, new tools and tool disc tools: ["Read"], permissionMode: "bypassPermissions", sessionId: "previous", + env: { MCP_PROTOCOL_NEGOTIATION: "legacy" }, }, }, "new-session", @@ -435,6 +436,7 @@ it.effect("keeps the exact block and denies native, MCP, new tools and tool disc assert.deepEqual(first, block); assert.isFalse(request.options.persistSession); assert.equal(request.options.maxTurns, 1); + assert.equal(request.options.env?.MCP_PROTOCOL_NEGOTIATION, "legacy"); const matcher = request.options.hooks.PreToolUse[0]!; assert.equal(matcher.onFailure, "block"); assert.notProperty(matcher, "matcher"); diff --git a/apps/server/src/kin/lead/turn/providers/__snapshots__/claude.test.ts.snap b/apps/server/src/kin/lead/turn/providers/__snapshots__/claude.test.ts.snap index 866619bd3b76..ff3d8fff2d5d 100644 --- a/apps/server/src/kin/lead/turn/providers/__snapshots__/claude.test.ts.snap +++ b/apps/server/src/kin/lead/turn/providers/__snapshots__/claude.test.ts.snap @@ -10,17 +10,17 @@ exports[`every seat's options match Kin byte for byte > delegated without lookup exports[`every seat's options match Kin byte for byte > dream 1`] = `"7a15b18823863542dfbb28ceb5fbb88fde6a2f57d15b70d911ac1f4d0e5854e6"`; -exports[`every seat's options match Kin byte for byte > owner with lookup 1`] = `"e09eade85507c9719e169537aef3b3259f42696781b8538a3426459aba971b77"`; +exports[`every seat's options match Kin byte for byte > owner with lookup 1`] = `"e0ecd0b03135a58db9efa7905f0dec3cde8afd36011ec619cfed02c52e17fd3d"`; -exports[`every seat's options match Kin byte for byte > owner without lookup 1`] = `"d27c64316f11b601f8415da697f84ac6ed6cd6a87fb2c207cb59eb804659891c"`; +exports[`every seat's options match Kin byte for byte > owner without lookup 1`] = `"b09c0d23b13e4231a2d3ba3c8b297d7fdc6efd22fd8d84976ef3c16f01bd7e99"`; exports[`every seat's options match Kin byte for byte > review 1`] = `"e8bf99c959c5de4e4e266edc91de2feffb029a57afc8ea2bf3d0cd45b706d024"`; exports[`every seat's options match Kin byte for byte > review without lookup 1`] = `"ebd1ded9ba7e50f62d9d98ad6be9b9befaa704b3caf6d94a496573f71007672e"`; -exports[`every seat's options match Kin byte for byte > shared 1`] = `"b363ea3add88f1eb6d5721294594e158217b968d6302845dd8c8bbfe2bc92bf9"`; +exports[`every seat's options match Kin byte for byte > shared 1`] = `"6c23c40cb75c8a450753c076639f9e5c3ddfca92c916272ec713c51293668566"`; -exports[`every seat's options match Kin byte for byte > shared without lookup 1`] = `"bc118769ef4fcc61e124d46c85eb116cd62439bae26dd1d330f5cab133de0f6a"`; +exports[`every seat's options match Kin byte for byte > shared without lookup 1`] = `"d28d612fa11d68d62b35870772591dac1f28d97784cb5975497cc681b2dea6d7"`; exports[`every seat's options match Kin byte for byte > triage 1`] = `"1defebe09b6d04791f7f341cf716949e6ca0b3f538064db58b73f02d2d9cf959"`; diff --git a/apps/server/src/kin/lead/turn/providers/claude.test.ts b/apps/server/src/kin/lead/turn/providers/claude.test.ts index 7258123b1db9..0fe3dbd92f1d 100644 --- a/apps/server/src/kin/lead/turn/providers/claude.test.ts +++ b/apps/server/src/kin/lead/turn/providers/claude.test.ts @@ -235,6 +235,7 @@ it.effect("every seat's options match Kin byte for byte", () => ? "confined" : undefined; if (instructionSeat !== undefined) { + assert.strictEqual(options.env?.MCP_PROTOCOL_NEGOTIATION, "legacy", seat); // A fresh owner or confined session sends no Kin system text, with the marked rules first. assert.deepStrictEqual(options.systemPrompt, { type: "custom", @@ -517,11 +518,13 @@ it.effect.each([ ENABLE_TOOL_SEARCH: "true", CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1", MCP_CONNECTION_NONBLOCKING: "0", + MCP_PROTOCOL_NEGOTIATION: "legacy", }, } satisfies typeof leadRest; assert.deepStrictEqual(leadRest, confinedBaseline); const { hooks: sharedHooks, ...sharedRest } = sharedOpened ?? lead; assert.deepStrictEqual(sharedRest, confinedBaseline); + const { MCP_PROTOCOL_NEGOTIATION: _negotiation, ...shortSeatEnv } = confinedBaseline.env; for (const [seat, expectedPrompt] of [ [reviewOpened, REVIEW_SEAT_INSTRUCTIONS], [billsOpened, BILLS_SEAT_INSTRUCTIONS], @@ -529,6 +532,7 @@ it.effect.each([ const { hooks, ...rest } = seat ?? lead; assert.deepStrictEqual(rest, { ...confinedBaseline, + env: shortSeatEnv, systemPrompt: { type: "custom", prompt: expectedPrompt, snapshot: false }, tools: ["ToolSearch"], disallowedTools: [...(lead.disallowedTools ?? []), ...builtinTools], @@ -777,6 +781,7 @@ it.effect( ENABLE_TOOL_SEARCH: "true", CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1", MCP_CONNECTION_NONBLOCKING: "0", + MCP_PROTOCOL_NEGOTIATION: "legacy", CLAUDE_CODE_PROMPT_CACHE_TTL: "1h", }); assert.deepStrictEqual(fullSettings, { diff --git a/apps/server/src/kin/lead/turn/providers/claude.ts b/apps/server/src/kin/lead/turn/providers/claude.ts index 84927be089cf..638577528a68 100644 --- a/apps/server/src/kin/lead/turn/providers/claude.ts +++ b/apps/server/src/kin/lead/turn/providers/claude.ts @@ -290,6 +290,8 @@ const apply = ( : {}), // Wait for Kin's tools before the first request; a different tool block misses the cache. ...(plan.seat === "delegated" ? {} : { MCP_CONNECTION_NONBLOCKING: "0" }), + // The roster-only upkeep lease accepts the stateful handshake, not stateless discovery. + ...(session.leadingInstructions === undefined ? {} : { MCP_PROTOCOL_NEGOTIATION: "legacy" }), }, }; }; diff --git a/apps/server/src/kin/mcp/layer.test.ts b/apps/server/src/kin/mcp/layer.test.ts index 595b073c8138..77d7604b9777 100644 --- a/apps/server/src/kin/mcp/layer.test.ts +++ b/apps/server/src/kin/mcp/layer.test.ts @@ -23,7 +23,12 @@ import { pairSession } from "../auth/ProofKeySessions.testkit.ts"; import { FetchHttpClient } from "effect/http"; import { ProcessRunner } from "../../processRunner.ts"; import { ProviderInstanceRegistry } from "../../provider/ProviderInstanceRegistry.ts"; -import { authorityLayerWithDatabase, startAgentWakeup } from "../chat/WakeupAuthority.testkit.ts"; +import { + authorityLayerWithDatabase, + endAgentWakeups, + startAgentWakeup, +} from "../chat/WakeupAuthority.testkit.ts"; +import * as KinEventQueue from "../lead/KinEventQueue.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import { McpProviderSessions } from "@t3tools/provider-core/server/McpProviderSessions"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; @@ -630,9 +635,8 @@ 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. @@ -641,43 +645,126 @@ it.effect.each([true, false])( assert.notInclude(toolNames, name); const cache = cacheSessionsOf(kin)!; const kinSessions = Context.get(services, KinAgentSessions); - const scope = yield* kinSessions.resolveAgent( - issued.config.authorizationHeader.replace(/^Bearer /, ""), - ); - assert.isDefined(scope); - const sha = kinSessions.lastToolList(threadId); - assert.isString(sha); - const cacheToken = yield* Effect.gen(function* () { - const lease = yield* cache.lease({ scope: scope!, sha: sha! }); - const credential = `Bearer ${lease.token}`; - const init = yield* request("/kin/mcp", credential, "initialize", initialize); - assert.equal(init.status, 200); - const session = init.headers["mcp-session-id"]; - const listed = yield* request("/kin/mcp", credential, "tools/list", {}, session); - assert.equal(listed.status, 200); - assert.isTrue(yield* Deferred.await(lease.ready)); - const attempted = yield* request( + const upkeepRoster = Effect.fn(function* ( + thread: ThreadId, + bearer: string, + ownSession: string | undefined, + ) { + // Model Claude's stateless probe unless the actual Kin launch options pin legacy. + const args: { + session: string | undefined; + headers: Record; + params: unknown; + } = + offered[0]?.env?.MCP_PROTOCOL_NEGOTIATION === "legacy" + ? { session: ownSession, headers: {}, params: {} } + : { + session: undefined, + headers: { + "mcp-method": "tools/list", + "mcp-protocol-version": "2026-07-28", + }, + params: { + _meta: { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": {}, + "io.modelcontextprotocol/clientInfo": { name: "test", version: "1" }, + }, + }, + }; + const own = yield* request( "/kin/mcp", - credential, - "tools/call", - { name: "kin_chat_read", arguments: {} }, - session, + bearer, + "tools/list", + args.params, + args.session, + args.headers, ); - assert.equal(attempted.status, 403); - assert.equal((yield* request("/mcp", credential, "initialize", initialize)).status, 401); - const terminate = (session: string | undefined) => - request("/kin/mcp", credential, "", {}, session, {}, http, "DELETE"); - assert.equal((yield* terminate(initialized.headers["mcp-session-id"])).status, 403); - assert.equal((yield* terminate(session)).status, 204); + 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); + 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}`; + assert.equal( + (yield* request("/kin/mcp", credential, "server/discover", {}, undefined, { + "mcp-method": "server/discover", + "mcp-protocol-version": "2026-07-28", + })).status, + 403, + ); + const init = yield* request("/kin/mcp", credential, "initialize", initialize); + assert.equal(init.status, 200); + const session = init.headers["mcp-session-id"]; + const list = () => request("/kin/mcp", credential, "tools/list", {}, session); + 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); + expect.soft(yield* Deferred.await(lease.ready)).toBe(true); + const attempted = yield* request( + "/kin/mcp", + credential, + "tools/call", + { name: "kin_chat_read", arguments: {} }, + session, + ); + assert.equal(attempted.status, 403); + assert.equal( + (yield* request("/mcp", credential, "initialize", initialize)).status, + 401, + ); + const terminate = (session: string | undefined) => + request("/kin/mcp", credential, "", {}, session, {}, http, "DELETE"); + assert.equal((yield* terminate(initialized.headers["mcp-session-id"])).status, 403); + 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* list()).status, 404); + return credential; + }).pipe(Effect.scoped); assert.equal( - (yield* request("/kin/mcp", credential, "tools/list", {}, session)).status, - 404, + (yield* request("/kin/mcp", cacheToken, "initialize", initialize)).status, + 401, ); - 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) => @@ -1368,6 +1455,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 98134275313d..96695968e020 100644 --- a/apps/server/src/kin/mcp/layer.ts +++ b/apps/server/src/kin/mcp/layer.ts @@ -129,11 +129,10 @@ const auth = HttpRouter.middleware<{ provides: KinBearerScope | KinServer | KinI method = "close"; } else { const body = yield* Effect.orElseSucceed(request.json, () => undefined); - if ( - !identity.isAgentThread(scope.thread.threadId) || - !isCacheListRequest(request.method, body) - ) + if (!isCacheListRequest(request.method, body)) return HttpServerResponse.empty({ status: 403 }); + const admitted = yield* identity.admitUpkeep(scope).pipe(Effect.option); + if (Option.isNone(admitted)) return HttpServerResponse.empty({ status: 403 }); method = body.method; if (method === "initialize") { if (sessionId !== undefined || lease.sessionId !== undefined || lease.initializing) From deb3fdf6ecd57c9d022ca1eea765394e61ec2800 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:23:21 +0530 Subject: [PATCH 08/11] test(kin): make the numbers identity fixture exhaustive Reflect the roster lease admission in the unrelated numbers fixture, which denies identity operations it does not exercise. People-change: No change to how numbers or upkeep work. Co-Authored-By: GPT-6.2 Sol --- apps/server/src/kin/numbers/KinNumbers.test.ts | 1 + 1 file changed, 1 insertion(+) 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), From 38f50051f0e974b22199bdad56fed777c44cf922 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:33:50 +0530 Subject: [PATCH 09/11] =?UTF-8?q?fix(kin):=20let=20upkeep=20negotiate=20th?= =?UTF-8?q?e=20seat=E2=80=99s=20MCP=20protocol?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Allow stateless discovery and listing through lease admission while preserving the full roster comparison and existing stateful session restrictions. Restore real Claude sessions to their original protocol selection and launch options. People-change: Keep-warm requests use the same protocol as agent turns without changing what a real turn can see or do. Co-Authored-By: GPT-6.2 Sol --- apps/server/src/kin/host/cacheSessions.ts | 11 -- .../server/src/kin/host/sessionUpkeep.test.ts | 2 - .../__snapshots__/claude.test.ts.snap | 8 +- .../kin/lead/turn/providers/claude.test.ts | 5 - .../src/kin/lead/turn/providers/claude.ts | 2 - apps/server/src/kin/mcp/layer.test.ts | 146 +++++++++++------- apps/server/src/kin/mcp/layer.ts | 34 +++- 7 files changed, 125 insertions(+), 83 deletions(-) diff --git a/apps/server/src/kin/host/cacheSessions.ts b/apps/server/src/kin/host/cacheSessions.ts index 3ec6e2bd4d38..fcb599a61f05 100644 --- a/apps/server/src/kin/host/cacheSessions.ts +++ b/apps/server/src/kin/host/cacheSessions.ts @@ -13,7 +13,6 @@ 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 Predicate from "effect/Predicate"; import * as Option from "effect/Option"; import * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; @@ -310,16 +309,6 @@ export class KinCacheSessions extends Context.Service - method === "POST" && - Predicate.isReadonlyObject(body) && - (body.method === "initialize" || - body.method === "notifications/initialized" || - body.method === "tools/list"); - export const cacheSessionsOf = (kin: KinServer["Service"] | undefined) => Option.getOrUndefined( Option.flatMap(kin?.services ?? Option.none(), (services) => diff --git a/apps/server/src/kin/host/sessionUpkeep.test.ts b/apps/server/src/kin/host/sessionUpkeep.test.ts index 02ed32862c6a..d352b5000835 100644 --- a/apps/server/src/kin/host/sessionUpkeep.test.ts +++ b/apps/server/src/kin/host/sessionUpkeep.test.ts @@ -427,7 +427,6 @@ it.effect("keeps the exact block and denies native, MCP, new tools and tool disc tools: ["Read"], permissionMode: "bypassPermissions", sessionId: "previous", - env: { MCP_PROTOCOL_NEGOTIATION: "legacy" }, }, }, "new-session", @@ -436,7 +435,6 @@ it.effect("keeps the exact block and denies native, MCP, new tools and tool disc assert.deepEqual(first, block); assert.isFalse(request.options.persistSession); assert.equal(request.options.maxTurns, 1); - assert.equal(request.options.env?.MCP_PROTOCOL_NEGOTIATION, "legacy"); const matcher = request.options.hooks.PreToolUse[0]!; assert.equal(matcher.onFailure, "block"); assert.notProperty(matcher, "matcher"); diff --git a/apps/server/src/kin/lead/turn/providers/__snapshots__/claude.test.ts.snap b/apps/server/src/kin/lead/turn/providers/__snapshots__/claude.test.ts.snap index ff3d8fff2d5d..866619bd3b76 100644 --- a/apps/server/src/kin/lead/turn/providers/__snapshots__/claude.test.ts.snap +++ b/apps/server/src/kin/lead/turn/providers/__snapshots__/claude.test.ts.snap @@ -10,17 +10,17 @@ exports[`every seat's options match Kin byte for byte > delegated without lookup exports[`every seat's options match Kin byte for byte > dream 1`] = `"7a15b18823863542dfbb28ceb5fbb88fde6a2f57d15b70d911ac1f4d0e5854e6"`; -exports[`every seat's options match Kin byte for byte > owner with lookup 1`] = `"e0ecd0b03135a58db9efa7905f0dec3cde8afd36011ec619cfed02c52e17fd3d"`; +exports[`every seat's options match Kin byte for byte > owner with lookup 1`] = `"e09eade85507c9719e169537aef3b3259f42696781b8538a3426459aba971b77"`; -exports[`every seat's options match Kin byte for byte > owner without lookup 1`] = `"b09c0d23b13e4231a2d3ba3c8b297d7fdc6efd22fd8d84976ef3c16f01bd7e99"`; +exports[`every seat's options match Kin byte for byte > owner without lookup 1`] = `"d27c64316f11b601f8415da697f84ac6ed6cd6a87fb2c207cb59eb804659891c"`; exports[`every seat's options match Kin byte for byte > review 1`] = `"e8bf99c959c5de4e4e266edc91de2feffb029a57afc8ea2bf3d0cd45b706d024"`; exports[`every seat's options match Kin byte for byte > review without lookup 1`] = `"ebd1ded9ba7e50f62d9d98ad6be9b9befaa704b3caf6d94a496573f71007672e"`; -exports[`every seat's options match Kin byte for byte > shared 1`] = `"6c23c40cb75c8a450753c076639f9e5c3ddfca92c916272ec713c51293668566"`; +exports[`every seat's options match Kin byte for byte > shared 1`] = `"b363ea3add88f1eb6d5721294594e158217b968d6302845dd8c8bbfe2bc92bf9"`; -exports[`every seat's options match Kin byte for byte > shared without lookup 1`] = `"d28d612fa11d68d62b35870772591dac1f28d97784cb5975497cc681b2dea6d7"`; +exports[`every seat's options match Kin byte for byte > shared without lookup 1`] = `"bc118769ef4fcc61e124d46c85eb116cd62439bae26dd1d330f5cab133de0f6a"`; exports[`every seat's options match Kin byte for byte > triage 1`] = `"1defebe09b6d04791f7f341cf716949e6ca0b3f538064db58b73f02d2d9cf959"`; diff --git a/apps/server/src/kin/lead/turn/providers/claude.test.ts b/apps/server/src/kin/lead/turn/providers/claude.test.ts index 0fe3dbd92f1d..7258123b1db9 100644 --- a/apps/server/src/kin/lead/turn/providers/claude.test.ts +++ b/apps/server/src/kin/lead/turn/providers/claude.test.ts @@ -235,7 +235,6 @@ it.effect("every seat's options match Kin byte for byte", () => ? "confined" : undefined; if (instructionSeat !== undefined) { - assert.strictEqual(options.env?.MCP_PROTOCOL_NEGOTIATION, "legacy", seat); // A fresh owner or confined session sends no Kin system text, with the marked rules first. assert.deepStrictEqual(options.systemPrompt, { type: "custom", @@ -518,13 +517,11 @@ it.effect.each([ ENABLE_TOOL_SEARCH: "true", CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1", MCP_CONNECTION_NONBLOCKING: "0", - MCP_PROTOCOL_NEGOTIATION: "legacy", }, } satisfies typeof leadRest; assert.deepStrictEqual(leadRest, confinedBaseline); const { hooks: sharedHooks, ...sharedRest } = sharedOpened ?? lead; assert.deepStrictEqual(sharedRest, confinedBaseline); - const { MCP_PROTOCOL_NEGOTIATION: _negotiation, ...shortSeatEnv } = confinedBaseline.env; for (const [seat, expectedPrompt] of [ [reviewOpened, REVIEW_SEAT_INSTRUCTIONS], [billsOpened, BILLS_SEAT_INSTRUCTIONS], @@ -532,7 +529,6 @@ it.effect.each([ const { hooks, ...rest } = seat ?? lead; assert.deepStrictEqual(rest, { ...confinedBaseline, - env: shortSeatEnv, systemPrompt: { type: "custom", prompt: expectedPrompt, snapshot: false }, tools: ["ToolSearch"], disallowedTools: [...(lead.disallowedTools ?? []), ...builtinTools], @@ -781,7 +777,6 @@ it.effect( ENABLE_TOOL_SEARCH: "true", CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1", MCP_CONNECTION_NONBLOCKING: "0", - MCP_PROTOCOL_NEGOTIATION: "legacy", CLAUDE_CODE_PROMPT_CACHE_TTL: "1h", }); assert.deepStrictEqual(fullSettings, { diff --git a/apps/server/src/kin/lead/turn/providers/claude.ts b/apps/server/src/kin/lead/turn/providers/claude.ts index 638577528a68..84927be089cf 100644 --- a/apps/server/src/kin/lead/turn/providers/claude.ts +++ b/apps/server/src/kin/lead/turn/providers/claude.ts @@ -290,8 +290,6 @@ const apply = ( : {}), // Wait for Kin's tools before the first request; a different tool block misses the cache. ...(plan.seat === "delegated" ? {} : { MCP_CONNECTION_NONBLOCKING: "0" }), - // The roster-only upkeep lease accepts the stateful handshake, not stateless discovery. - ...(session.leadingInstructions === undefined ? {} : { MCP_PROTOCOL_NEGOTIATION: "legacy" }), }, }; }; diff --git a/apps/server/src/kin/mcp/layer.test.ts b/apps/server/src/kin/mcp/layer.test.ts index 77d7604b9777..3417745bca3d 100644 --- a/apps/server/src/kin/mcp/layer.test.ts +++ b/apps/server/src/kin/mcp/layer.test.ts @@ -371,7 +371,7 @@ it.effect.each([true, false])( const request = ( path: string, token: string, - method: string, + method: string | ReadonlyArray, params: unknown, session?: string, extra: Record = {}, @@ -407,7 +407,18 @@ it.effect.each([true, false])( ...extra, }, ...(verb === "POST" - ? { body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) } + ? { + body: JSON.stringify( + typeof method !== "string" + ? method + : { + jsonrpc: "2.0", + ...(method.startsWith("notifications/") ? {} : { id: 1 }), + method, + params, + }, + ), + } : {}), }), ), @@ -650,36 +661,22 @@ it.effect.each([true, false])( bearer: string, ownSession: string | undefined, ) { - // Model Claude's stateless probe unless the actual Kin launch options pin legacy. - const args: { - session: string | undefined; - headers: Record; - params: unknown; - } = - offered[0]?.env?.MCP_PROTOCOL_NEGOTIATION === "legacy" - ? { session: ownSession, headers: {}, params: {} } - : { - session: undefined, - headers: { - "mcp-method": "tools/list", - "mcp-protocol-version": "2026-07-28", - }, - params: { - _meta: { - "io.modelcontextprotocol/protocolVersion": "2026-07-28", - "io.modelcontextprotocol/clientCapabilities": {}, - "io.modelcontextprotocol/clientInfo": { name: "test", version: "1" }, - }, - }, - }; - const own = yield* request( - "/kin/mcp", - bearer, - "tools/list", - args.params, - args.session, - args.headers, - ); + 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) @@ -700,38 +697,79 @@ it.effect.each([true, false])( const cacheToken = yield* Effect.gen(function* () { const lease = yield* cache.lease({ scope: scope!, sha: sha! }); const credential = `Bearer ${lease.token}`; - assert.equal( - (yield* request("/kin/mcp", credential, "server/discover", {}, undefined, { - "mcp-method": "server/discover", - "mcp-protocol-version": "2026-07-28", - })).status, - 403, - ); - const init = yield* request("/kin/mcp", credential, "initialize", initialize); - assert.equal(init.status, 200); - const session = init.headers["mcp-session-id"]; - const list = () => request("/kin/mcp", credential, "tools/list", {}, session); + 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); - expect.soft(yield* Deferred.await(lease.ready)).toBe(true); - const attempted = yield* request( - "/kin/mcp", - credential, + if (listed.status === 200) { + assert.strictEqual(yield* bodyOf(listed), roster); + assert.isTrue(yield* Deferred.await(lease.ready)); + } + for (const method of [ "tools/call", - { name: "kin_chat_read", arguments: {} }, - session, + "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(attempted.status, 403); assert.equal( - (yield* request("/mcp", credential, "initialize", initialize)).status, + (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(initialized.headers["mcp-session-id"])).status, 403); + 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}`; @@ -750,7 +788,7 @@ it.effect.each([true, false])( } else { assert.equal((yield* terminate(session)).status, 204); } - assert.equal((yield* list()).status, 404); + assert.equal((yield* legacyList()).status, 404); return credential; }).pipe(Effect.scoped); assert.equal( diff --git a/apps/server/src/kin/mcp/layer.ts b/apps/server/src/kin/mcp/layer.ts index 96695968e020..fdafb829d122 100644 --- a/apps/server/src/kin/mcp/layer.ts +++ b/apps/server/src/kin/mcp/layer.ts @@ -3,6 +3,7 @@ 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"; @@ -26,7 +27,7 @@ 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, isCacheListRequest } from "../host/cacheSessions.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"; @@ -128,18 +129,41 @@ const auth = HttpRouter.middleware<{ provides: KinBearerScope | KinServer | KinI 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 (!isCacheListRequest(request.method, body)) + 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 }); - method = body.method; if (method === "initialize") { if (sessionId !== undefined || lease.sessionId !== undefined || lease.initializing) return HttpServerResponse.empty({ status: 403 }); lease.initializing = true; - } else if (sessionId === undefined || lease.sessionId !== sessionId) { - return HttpServerResponse.empty({ status: 403 }); } } const response = yield* effect.pipe( From 9f6755321fd55860dfee207eec6c3d52b944bfc6 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:37:05 +0530 Subject: [PATCH 10/11] fix(kin): put cache upkeep behind real work MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use the budget’s speculative-work admission rule at both gates, recover from a lone cache miss after real demand, and keep upkeep’s token usage out of turn cache-hit rates without changing its charge. People-change: Keep-warm requests yield at low budget, recover after a one-off miss, and no longer inflate the cache-hit rate shown for turns. Co-Authored-By: GPT-6.2 Sol --- .../server/src/kin/host/sessionUpkeep.test.ts | 99 ++++++++++++++----- apps/server/src/kin/host/sessionUpkeep.ts | 38 +++++-- apps/server/src/kin/lead/KinBudget.ts | 4 +- .../src/kin/lead/RoutineContent.test.ts | 13 ++- apps/server/src/kin/lead/RoutineContent.ts | 7 +- apps/server/src/kin/mcp/layer.test.ts | 37 +++++++ 6 files changed, 158 insertions(+), 40 deletions(-) diff --git a/apps/server/src/kin/host/sessionUpkeep.test.ts b/apps/server/src/kin/host/sessionUpkeep.test.ts index d352b5000835..62725f712f9d 100644 --- a/apps/server/src/kin/host/sessionUpkeep.test.ts +++ b/apps/server/src/kin/host/sessionUpkeep.test.ts @@ -74,6 +74,7 @@ const seed = Effect.fn("UpkeepTest.seed")(function* (gaps: ReadonlyArray }); 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; @@ -187,23 +188,31 @@ it.effect("accepts a measured cost exactly equal to the chance-weighted rewrite" }).pipe(Effect.provide(layer)), ); -it.effect("a ping that rewrote the block prices the next one", () => +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 miss, a real turn, and a miss, then a newer turn", [miss, miss], null, true], +] 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 missed = JSON.stringify({ - read: 16_000, - written: 19_000, - input: 4, - output: 1, - cost: 0.16, - }); - yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, ended_at, + 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 ('kin-upkeep:missed', ${orgId}, ${agentId}, ${model}, ${now - 2 * 60 * minute}, - ${now - 2 * 60 * minute}, 'completed', '[]', 'upkeep', ${missed}, ${now - 2 * 60 * minute}, - ${part.fingerprint}, ${now - 2 * 60 * minute})`; - assert.deepEqual(yield* run(), []); + 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)), ); @@ -225,8 +234,8 @@ it.effect("a ping's cost reaches the day's spend exactly once", () => leadUnits: 3208, ownerUnits: 3208, teammateUnits: 0, - inputTokens: 31104, - cachedInputTokens: 31000, + inputTokens: 0, + cachedInputTokens: 0, }); assert.deepEqual((yield* budget.get(orgId)).leads, [ { agentId, name: "Zoya", leadUnits: 3208 }, @@ -235,22 +244,65 @@ it.effect("a ping's cost reaches the day's spend exactly once", () => 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("does not send while the owner's lead limit is reached", () => +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":100,"workerUnits":null}')`; + 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 = 100 WHERE org_id = ${orgId} AND day = ${day}`; + 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("rechecks spend if the budget fills while the ping is preparing", () => +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; @@ -262,9 +314,9 @@ it.effect("rechecks spend if the budget fills while the ping is preparing", () = enabled: true, placement: "leadingBlock", current: () => part.fingerprint, - ping: Effect.fn("UpkeepTest.prepareAtLimit")(function* (_, stillDue) { + ping: Effect.fn("UpkeepTest.prepareAtThreshold")(function* (_, stillDue) { prepared = true; - yield* sql`UPDATE kin_budget SET lead_units = 100 WHERE org_id = ${orgId} AND day = ${day}`.pipe( + yield* sql`UPDATE kin_budget SET lead_units = 70 WHERE org_id = ${orgId} AND day = ${day}`.pipe( Effect.orDie, ); assert.isFalse(yield* stillDue); @@ -354,8 +406,9 @@ it.effect.each([false, true])("keeps exactly the recorded usage at timeout (know ]); const sql = yield* SqlClient.SqlClient; assert.deepEqual( - yield* sql`SELECT units FROM kin_budget_charges`, - known ? [{ units: 3208 }] : [], + 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(), []); diff --git a/apps/server/src/kin/host/sessionUpkeep.ts b/apps/server/src/kin/host/sessionUpkeep.ts index e304e289aa03..6e6b7d1febdd 100644 --- a/apps/server/src/kin/host/sessionUpkeep.ts +++ b/apps/server/src/kin/host/sessionUpkeep.ts @@ -94,18 +94,35 @@ const estimate = Effect.fn("KinSessionUpkeep.estimate")(function* (part: Candida 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", status + }>`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 started_at >= ${cutoff} + 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`; - // A warm ordinary opening bounds the ping's shorter input until the ping has its own measurement. - // A ping that missed and rewrote the block prices the next one, so a prefix that never matches stops. const sample = Option.getOrUndefined(decodeUsage(measured?.tokens)); - // An unfinished request can cost a full rewrite; even certainty cannot justify repeating it. - const priced = sample !== undefined && (sample.cost !== null || measured?.status === "completed"); - if (!priced && measured !== undefined && measured.endedAt >= part.lastTurnAt) return undefined; - const ping = priced ? costUnits(sample) : gaps.warmCost + 5; + let price = + sample !== undefined && (sample.cost !== null || measured?.status === "completed") + ? costUnits(sample) + : undefined; + if (measured?.status === "completed" && price !== undefined && price > rewrite) { + const [previous] = yield* sql<{ kind: string; status: string; tokens: string | null }>` + SELECT kind, status, tokens_json AS tokens FROM kin_wakeups + WHERE cache_part = ${part.fingerprint} 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?.kind === "upkeep" && 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; }); @@ -144,7 +161,7 @@ export const check = Effect.fn("KinSessionUpkeep.check")(function* (input: { return ( active !== undefined && input.current(part) === part.fingerprint && - !(yield* budget.admit(part.orgId, "P1")).atLimit + (yield* budget.admit(part.orgId, "P4")).allowed ); }); if (!(yield* stillDue)) continue; @@ -188,7 +205,8 @@ export const check = Effect.fn("KinSessionUpkeep.check")(function* (input: { providerTurnId: wakeupId, turnTokenUsage: { usageScope: "main_agent", - usageStatus: "complete", + usageStatus: + sent.status === "failed" && sent.usage.cost === null ? "partial" : "complete", hasSubagents: false, inputTokens: input + read + written, cachedInputTokens: read, diff --git a/apps/server/src/kin/lead/KinBudget.ts b/apps/server/src/kin/lead/KinBudget.ts index 4178269e743f..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, diff --git a/apps/server/src/kin/lead/RoutineContent.test.ts b/apps/server/src/kin/lead/RoutineContent.test.ts index b9d79bbbd0f2..94f7a245372b 100644 --- a/apps/server/src/kin/lead/RoutineContent.test.ts +++ b/apps/server/src/kin/lead/RoutineContent.test.ts @@ -990,15 +990,20 @@ it.effect("an evening whose only news is in Kin's records is summed up, by the c 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_budget (org_id, day, lead_units) VALUES (${orgId}, '2026-11-09', 3208)`; + 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}}]')`; + '[{"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: 3208, - cacheHitRate: 31_000 / 31_104, + 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 8cbc7b5cdc18..abb7e132e8a4 100644 --- a/apps/server/src/kin/lead/RoutineContent.ts +++ b/apps/server/src/kin/lead/RoutineContent.ts @@ -509,8 +509,11 @@ const make = Effect.gen(function* () { 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/mcp/layer.test.ts b/apps/server/src/kin/mcp/layer.test.ts index 3417745bca3d..50f546a9d62b 100644 --- a/apps/server/src/kin/mcp/layer.test.ts +++ b/apps/server/src/kin/mcp/layer.test.ts @@ -688,6 +688,43 @@ it.effect.each([true, false])( 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, From b27d5845f11d207c97a5fa03a11019df1752a7cd Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:47:02 +0530 Subject: [PATCH 11/11] fix(kin): preserve upkeep miss streaks across real turns A real turn releases the wait after a lone miss; it cannot break the sequence of upkeep outcomes or the second miss would never suppress a retry. People-change: Two consecutive keep-warm misses stop repeat spending even when real work ran between them. Co-Authored-By: GPT-6.2 Sol --- apps/server/src/kin/host/sessionUpkeep.test.ts | 2 +- apps/server/src/kin/host/sessionUpkeep.ts | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/apps/server/src/kin/host/sessionUpkeep.test.ts b/apps/server/src/kin/host/sessionUpkeep.test.ts index 62725f712f9d..04cd3b5ef477 100644 --- a/apps/server/src/kin/host/sessionUpkeep.test.ts +++ b/apps/server/src/kin/host/sessionUpkeep.test.ts @@ -194,7 +194,7 @@ it.effect.each([ ["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 miss, a real turn, and a miss, then a newer turn", [miss, miss], null, 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)]); diff --git a/apps/server/src/kin/host/sessionUpkeep.ts b/apps/server/src/kin/host/sessionUpkeep.ts index 6e6b7d1febdd..a18bb20ee346 100644 --- a/apps/server/src/kin/host/sessionUpkeep.ts +++ b/apps/server/src/kin/host/sessionUpkeep.ts @@ -108,13 +108,14 @@ const estimate = Effect.fn("KinSessionUpkeep.estimate")(function* (part: Candida ? costUnits(sample) : undefined; if (measured?.status === "completed" && price !== undefined && price > rewrite) { - const [previous] = yield* sql<{ kind: string; status: string; tokens: string | null }>` - SELECT kind, status, tokens_json AS tokens FROM kin_wakeups - WHERE cache_part = ${part.fingerprint} AND cache_request_started_at >= ${cutoff} + // 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?.kind === "upkeep" && previous.status === "completed" + previous?.status === "completed" ? Option.getOrUndefined(decodeUsage(previous.tokens)) : undefined; if (prior === undefined || costUnits(prior) <= rewrite) price = undefined;