Skip to content
39 changes: 30 additions & 9 deletions apps/server/src/kin/host/cacheDaily.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ const wake = Effect.fn("CacheDailyTest.wake")(function* (
readonly tokens?: string | null;
readonly sent?: "fresh" | "carried" | "refill";
readonly reason?: string;
/** Raw `carry_json`, as the compaction writer stores it. */
readonly carry?: string;
readonly units?: number;
/** A wake-up that never started a model run has none. */
readonly run?: string | null;
Expand All @@ -68,9 +70,10 @@ const wake = Effect.fn("CacheDailyTest.wake")(function* (
const start = options.at ?? at;
const status = options.status ?? "completed";
const carry =
options.sent === undefined
options.carry ??
(options.sent === undefined
? null
: JSON.stringify({ sent: options.sent, reason: options.reason });
: JSON.stringify({ sent: options.sent, reason: options.reason }));
const kind = options.kind ?? "turn";
const run = options.run === undefined ? (kind === "turn" ? `run-${id}` : null) : options.run;
yield* sql`INSERT INTO kin_wakeups (org_id, wakeup_id, agent_id, model, started_at, ended_at,
Expand Down Expand Up @@ -223,20 +226,38 @@ it.effect("a keep-warm row is not a turn and its spend is counted once", () =>
tokens: '{"input":0,"read":100,"written":0,"output":1,"cost":0.001}',
});
yield* wake("no-usage", { kind: "upkeep", tokens: null });
// A compaction shares the upkeep kind (sessionCompaction.ts); it is never a failed ping.
yield* wake("compacted", {
kind: "upkeep",
status: "failed",
carry: '{"action":"compaction","cachePart":"part-1"}',
tokens: '{"input":2,"read":1000,"written":0,"output":3,"cost":0.002}',
});
const day = yield* figure;
assert.strictEqual(day.turns, 1);
assert.strictEqual(day.turnBudgetUnits, 100);
assert.deepStrictEqual(day.upkeep.tokens, {
input: 10,
cacheRead: 600,
input: 12,
cacheRead: 1600,
cacheWrite: 50,
output: 2,
output: 5,
});
assert.strictEqual(day.upkeep.count, 3);
assert.strictEqual(day.upkeep.failedOrWithoutUsage, 2);
assert.strictEqual(day.upkeep.count, 4);
assert.strictEqual(day.upkeep.failedOrWithoutUsage, 3);
assert.strictEqual(day.upkeep.budgetUnits, 25);
assert.strictEqual(day.upkeep.costUsd, 0.006);
assert.closeTo(day.costPerTurnUsd!, 0.0182, 1e-12);
assert.strictEqual(day.upkeep.costUsd, 0.008);
assert.deepStrictEqual(
day.upkeep.byKind.map(({ kind, count, failedOrWithoutUsage }) => ({
kind,
count,
failedOrWithoutUsage,
})),
[
{ kind: "compaction", count: 1, failedOrWithoutUsage: 1 },
{ kind: "upkeep", count: 3, failedOrWithoutUsage: 2 },
],
);
assert.closeTo(day.costPerTurnUsd!, 0.0202, 1e-12);
}),
),
);
Expand Down
11 changes: 7 additions & 4 deletions apps/server/src/kin/host/cacheDaily.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ const meteredLedger = `CASE WHEN u.type = 'object' THEN
json_extract(u.value, '$.turnTokenUsage.cacheCreationTokens'),
json_extract(u.value, '$.turnTokenUsage.outputTokens')) IS NOT NULL ELSE 0 END`;
const meteredRaw = `json_type(w.tokens_json, '$.input') IN ('integer', 'real') AND w.kind <> 'turn'`;
// A compaction is stored as an upkeep row (sessionCompaction.ts) but is its own kind here.
const kindOf = `CASE WHEN w.kind = 'upkeep' AND json_extract(w.carry_json, '$.action') = 'compaction'
THEN 'compaction' ELSE w.kind END`;

const readDay = Effect.fn("KinCacheDaily.readDay")(function* (
orgId: KinOrgId,
Expand All @@ -88,7 +91,7 @@ const readDay = Effect.fn("KinCacheDaily.readDay")(function* (

const counts = yield* sql<Counts>`
WITH activity AS (
SELECT w.kind, w.status, w.ended_at, c.units,
SELECT ${sql.literal(kindOf)} AS kind, w.status, w.ended_at, c.units,
CASE WHEN w.kind <> 'turn' OR w.status = 'completed' THEN 1 ELSE 0 END AS counted,
CASE WHEN w.kind = 'turn' THEN json_extract(w.carry_json, '$.sent') END AS sent,
CASE WHEN w.kind = 'turn' AND json_extract(w.carry_json, '$.sent') = 'fresh'
Expand All @@ -110,14 +113,14 @@ const readDay = Effect.fn("KinCacheDaily.readDay")(function* (

const metered = yield* sql<Metered>`
WITH wakeups AS MATERIALIZED (
SELECT w.kind, w.model, w.tokens_json FROM kin_wakeups w WHERE ${inDay}
SELECT ${sql.literal(kindOf)} AS kind, w.model, w.tokens_json FROM kin_wakeups w WHERE ${inDay}
), usage AS (
SELECT w.kind, w.model,
json_extract(w.tokens_json, '$.input') AS input,
COALESCE(json_extract(w.tokens_json, '$.read'), 0) AS cached,
COALESCE(json_extract(w.tokens_json, '$.written'), 0) AS written,
-- A keep-warm request is only sent on an hour's cache (sessionUpkeepQuery.send).
CASE WHEN w.kind = 'upkeep' THEN COALESCE(json_extract(w.tokens_json, '$.written'), 0)
-- Keep-warm and compaction requests are only sent on an hour's cache (sessionUpkeepQuery.ts).
CASE WHEN w.kind IN ('upkeep', 'compaction') THEN COALESCE(json_extract(w.tokens_json, '$.written'), 0)
ELSE 0 END AS written1h,
COALESCE(json_extract(w.tokens_json, '$.output'), 0) AS output,
json_extract(w.tokens_json, '$.cost') AS reported
Expand Down
12 changes: 8 additions & 4 deletions apps/server/src/kin/host/sessionUpkeep.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import * as CacheParts from "./cacheParts.ts";
import * as Upkeep from "./sessionUpkeep.ts";
import { collectPing, makeCompactionRequest, makePingRequest } from "./sessionUpkeepQuery.ts";
import { makeMigratedSqliteLayer } from "../persistence/migratedSqlite.testkit.ts";
import { KEEP_WARM_PROMPT } from "../lead/LeadPrompt.ts";

const minute = 60_000;
const now = 1_794_009_600_000;
Expand Down Expand Up @@ -78,7 +79,7 @@ const miss = { read: 16_000, written: 19_000, input: 4, output: 1, cost: 0.16 };
const run = (
overrides: {
fingerprint?: string;
placement?: "leadingBlock" | "system";
placement?: "first_block" | "system";
enabled?: boolean;
outcome?: {
status: "failed" | "completed";
Expand All @@ -90,7 +91,7 @@ const run = (
const seen: string[] = [];
yield* Upkeep.check({
enabled: overrides.enabled ?? true,
placement: overrides.placement ?? "leadingBlock",
placement: overrides.placement ?? "first_block",
current: () => overrides.fingerprint ?? part.fingerprint,
ping: (due) =>
Effect.sync(() => {
Expand Down Expand Up @@ -327,7 +328,7 @@ it.effect("rechecks lowest priority at exactly 30% left after preparing a ping",
let prepared = false;
yield* Upkeep.check({
enabled: true,
placement: "leadingBlock",
placement: "first_block",
current: () => part.fingerprint,
ping: Effect.fn("UpkeepTest.prepareAtThreshold")(function* (_, stillDue) {
prepared = true;
Expand Down Expand Up @@ -575,7 +576,10 @@ it.effect.each(["ping", "compaction"] as const)(
}
assert.deepEqual(summaries, ["Dispatch has an open rate question."]);
} else {
assert.deepEqual(request.message.message.content[0], block);
assert.deepEqual(request.message.message.content, [
block,
{ type: "text", text: KEEP_WARM_PROMPT },
]);
assert.include(request.options, { maxTurns: 1 });
}
assert.isFalse(request.options.persistSession);
Expand Down
25 changes: 12 additions & 13 deletions apps/server/src/kin/host/sessionUpkeep.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- the provider uses independent native UUIDs.
import * as NodeCrypto from "node:crypto";
import { KinWakeupId } from "@t3tools/contracts";
import { KinWakeupId, type ServerSettings } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
Expand All @@ -12,19 +12,16 @@ 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 { DAY_MS, MINUTE_MS } from "../durations.ts";
import { instructionPlacement } from "../lead/turn/providers/provider.ts";
import type { CachePart } from "./cacheParts.ts";
import { tick as compactIdleSessions } from "./sessionCompaction.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 EVERY_MS = 5 * MINUTE_MS;
const PING_AT = 50 * MINUTE_MS;
const LOOKBACK = 14 * DAY_MS;

const UsageJson = Schema.fromJsonString(PingUsage);
const encodeUsage = Schema.encodeEffect(UsageJson);
Expand Down Expand Up @@ -132,12 +129,13 @@ const estimate = Effect.fn("KinSessionUpkeep.estimate")(function* (part: Candida

export const check = Effect.fn("KinSessionUpkeep.check")(function* (input: {
readonly enabled: boolean;
readonly placement: InstructionPlacement;
/** The host's setting: under "system" nothing is shared between sessions, so a ping only spends. */
readonly placement: ServerSettings["kinInstructionPlacement"];
readonly current: (part: Candidate) => string | undefined;
readonly ping: SendPing;
readonly wallMillis?: Effect.Effect<number>;
}) {
if (!input.enabled || input.placement === "system") return;
if (!input.enabled || instructionPlacement("claudeAgent", input.placement) === "system") return;
const sql = yield* SqlClient.SqlClient;
const budget = yield* KinBudget;
const time = input.wallMillis ?? Clock.currentTimeMillis;
Expand Down Expand Up @@ -170,7 +168,7 @@ export const check = Effect.fn("KinSessionUpkeep.check")(function* (input: {
if (!(yield* stillDue)) continue;
const result = yield* estimate(part, now);
if (result === undefined) continue;
const idleMinutes = (now - part.lastRequestAt) / MINUTE;
const idleMinutes = (now - part.lastRequestAt) / MINUTE_MS;
const startedAt = yield* time;
const sent = yield* input.ping(
{ ...part, ...result, idleMinutes },
Expand Down Expand Up @@ -258,7 +256,7 @@ export const layer = Layer.effectDiscard(
const current = (part: Candidate) => cache.current(part, part.modelsJson, settings);
yield* check({
enabled: settings.kinSessionUpkeep,
placement: instructionPlacement("claudeAgent"),
placement: settings.kinInstructionPlacement,
current: (part) => current(part)?.part.fingerprint,
...(clock === undefined ? {} : { wallMillis: clock.wallMillis }),
ping: Effect.fn("KinSessionUpkeep.ping")(function* (part, stillDue) {
Expand All @@ -274,6 +272,7 @@ export const layer = Layer.effectDiscard(
latest,
(value) =>
value.kinSessionUpkeep &&
value.kinInstructionPlacement !== "system" &&
cache.current(part, part.modelsJson, value)?.part.fingerprint ===
part.fingerprint,
) && (yield* stillDue)
Expand Down
10 changes: 6 additions & 4 deletions apps/server/src/kin/host/sessionUpkeepQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ import { FetchHttpClient, HttpClient } from "effect/http";

import type { ClaudeAgentSdkQueryOptions } from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
import type { KinCacheSessions, LeadingBlock } from "./cacheSessions.ts";
import { COMPACT_INSTRUCTIONS, SESSION_CONTEXT_CHARS } from "../lead/LeadPrompt.ts";
import {
COMPACT_INSTRUCTIONS,
KEEP_WARM_PROMPT,
SESSION_CONTEXT_CHARS,
} from "../lead/LeadPrompt.ts";
import {
growthOf,
hasUsage,
Expand All @@ -27,8 +31,6 @@ import {
type SessionUsage,
} from "./sessionUsage.ts";

const UPKEEP_LINE = "Reply with one word: Ready.";

export const PingUsage = Schema.Struct({
read: Schema.Number,
written: Schema.Number,
Expand Down Expand Up @@ -68,7 +70,7 @@ export const makePingRequest = (
type: "user",
message: {
role: "user",
content: [input.block, { type: "text", text: UPKEEP_LINE }],
content: [input.block, { type: "text", text: KEEP_WARM_PROMPT }],
},
parent_tool_use_id: null,
session_id: sessionId,
Expand Down
23 changes: 23 additions & 0 deletions apps/server/src/kin/lead/LeadPrompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1228,6 +1228,29 @@ it.effect(
}).pipe(Effect.provide(layer)),
);

it.effect("a confined carry does not keep a teammate's stale live status", () =>
Effect.gen(function* () {
const { sharedInput } = yield* richPromptFixture;
const sql = yield* SqlClient.SqlClient;
const prompt = yield* KinLeadPrompt;
const first = yield* sharedInput("confined-first");
const saved = {
...(yield* prompt.buildSession(first)),
...(yield* readCursor(orgId, chatId, null)),
heldChatChanges: [],
};
yield* sql`UPDATE kin_people SET away_until = '2099-01-01' WHERE person_id = ${teammateId}`;
const next = yield* sharedInput("confined-second");
expect(yield* prompt.build(next)).toContain("away until 2099-01-01");
const current = yield* prompt.buildSession(next);
// Either the session starts fresh or the carried addition says what changed.
if (current.confinedStandingKey === saved.confinedStandingKey)
expect([current.confinedDelta(saved), current.message].join("\n")).toContain(
"away until 2099-01-01",
);
}).pipe(Effect.provide(layer)),
);

const originalIndexAt = "2026-11-20T14:05:00.000Z";
const rebuiltIndexAt = "2026-11-22T14:05:00.000Z";
const datedIndexMemory = Layer.effect(
Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/kin/lead/LeadPrompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3859,8 +3859,9 @@ const renderSession = (
return {
confinedStandingKey: NodeCrypto.createHash("sha256")
.update(
// The whole text: a shared seat has no seatNow to carry a teammate's live status.
JSON.stringify([
standingKey,
standing,
confinedHeader,
Object.entries(snapshotSignatures({ sections, index }).sections).filter(
([section]) => section !== "header" && section !== "recentChat",
Expand Down
56 changes: 56 additions & 0 deletions apps/server/src/kin/lead/WakeupRunner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3642,6 +3642,62 @@ describe("WakeupRunner", () => {
),
);

it.effect.each([
["mcp__kin__list_tasks", "fresh", "standing"],
["ToolSearch", "carried", null],
] as const)("a confined room after a %s call", ([tool, sent, reason]) =>
Effect.gen(function* () {
yield* seedCarryRoom;
yield* wake("tidewater-first", "room");
yield* wake("tidewater-second", "room");
assert.include((yield* carryRows).at(-1), { sent, reason });
}).pipe(
Effect.provide(carryHarness({ toolOutputs: [{ tool, output: "Invented task W-6" }] })),
provideDeterministicTestRuntime,
),
);

// Pins J3c's restart answer: only the owner seat re-proves its saved roster before its tools
// are listed again, so a confined chat with the same readers starts fresh after a restart.
it.effect("after a restart a confined room has no tool-list proof and starts fresh", () => {
let restarted = false;
return Effect.gen(function* () {
yield* seedCarryRoom;
yield* wake("tidewater-first", "room");
restarted = true;
yield* wake("tidewater-second", "room").pipe(
Effect.provide(
Layer.fresh(WakeupRunner.layer).pipe(
Layer.provideMerge(
Layer.merge(
Layer.fresh(KinSessionContext.layer).pipe(Layer.provide(presentFixtureSession)),
Layer.succeed(KinBoot, "new-boot"),
),
),
),
),
);
const [, second] = yield* carryRows;
assert.include(second, { reason: "tool_list", sent: "fresh" });
}).pipe(
Effect.provide(
harnessWith(
{ settings: { kinSessionCarry: true } },
Layer.mergeAll(
KinSessionContext.layer.pipe(Layer.provide(presentFixtureSession)),
Layer.succeed(KinBoot, "fixture-boot"),
Layer.mock(KinAgentSessions)({
recordToolList: () => {},
lastToolList: () => (restarted ? null : "a".repeat(64)),
}),
Layer.mock(KinWorkspace)({ recipes: () => Effect.succeed([]) }),
),
),
),
provideDeterministicTestRuntime,
);
});

it.effect(
"teammates carry only their own chat; a co-owner seat with file tools starts fresh",
() =>
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/kin/lead/instructions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { InstructionPlacement } from "./turn/providers/provider.ts";

export const instructionVersion = 123;
export const instructionVersion = 122;

/**
* Kin's own lines are the application's, as the SDK asks a custom prompt to say. Where a real
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/kin/lead/turn/conformance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,9 @@ it.each([
pair.map(({ placement }) => placement),
["system", "system"],
);
assert.isTrue(pair.every(({ text }) => text.startsWith("instructions-version: 123\n")));
assert.isTrue(pair.every(({ text }) => text.startsWith("instructions-version: 122\n")));
const wire = JSON.stringify(
pair.map(({ text }) => text.replace(/^instructions-version: 123/, "instructions-version: 121")),
pair.map(({ text }) => text.replace(/^instructions-version: 122/, "instructions-version: 121")),
);
assert.strictEqual(NodeCrypto.createHash("sha256").update(wire).digest("hex"), expected);
});
Expand Down
Loading
Loading