From 47cbabf54547650505326b51bbe68efec0ef2a4c Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:38:38 +0530 Subject: [PATCH 1/4] feat(kin): report the owner's daily cache figure Count completed turns, fresh starts and upkeep on the owner's local day. Price the metered totals with Usage's settings and rate table, expose the figure only to the owner, and log yesterday's figure once per day. T3-file: apps/server/src/ws.ts: Supply the existing Usage service to the Kin handler. T3-file: apps/server/src/usage/UsageService.ts: Share the live pricing settings and rate cache without starting a transcript scan. T3-file: apps/server/src/usage/UsageService.test.ts: Verify changing the Usage price changes the aggregated estimate by the same amount. T3-file: apps/server/src/usage/usagePricing.ts: Reuse the request rate arithmetic for aggregated ledgers without treating a day as one request. People-change: The owner host records daily cache reads, fresh starts and upkeep costs. No screen changes yet. Co-Authored-By: GPT-6.2 Sol --- apps/server/src/kin/host/cacheDaily.test.ts | 310 ++++++++++++++++++ apps/server/src/kin/host/cacheDaily.ts | 297 +++++++++++++++++ apps/server/src/kin/host/rpcHandlers.ts | 23 ++ apps/server/src/kin/lead/WakeupRunner.test.ts | 2 + apps/server/src/kin/lead/layer.test.ts | 2 + apps/server/src/kin/lead/layer.ts | 2 + apps/server/src/kin/mcp/layer.test.ts | 2 + apps/server/src/kin/rpcAccess.test.ts | 15 + apps/server/src/kin/rpcHandlers.ts | 4 +- apps/server/src/kin/tasksKey/reach.test.ts | 1 + apps/server/src/usage/UsageService.test.ts | 16 + apps/server/src/usage/UsageService.ts | 32 +- apps/server/src/usage/usagePricing.ts | 9 +- apps/server/src/ws.ts | 2 +- packages/client-runtime/src/kin/kinClient.ts | 4 + .../src/state/commandPermissions.test.ts | 4 +- packages/contracts/src/auth.kin.test.ts | 14 + packages/contracts/src/kinHostCare.ts | 60 +++- packages/contracts/src/kinRpcs.ts | 4 +- 19 files changed, 795 insertions(+), 8 deletions(-) create mode 100644 apps/server/src/kin/host/cacheDaily.test.ts create mode 100644 apps/server/src/kin/host/cacheDaily.ts diff --git a/apps/server/src/kin/host/cacheDaily.test.ts b/apps/server/src/kin/host/cacheDaily.test.ts new file mode 100644 index 000000000000..d5620bcb91b7 --- /dev/null +++ b/apps/server/src/kin/host/cacheDaily.test.ts @@ -0,0 +1,310 @@ +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import { assert, it } from "@effect/vitest"; +import { KinOrgId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Logger from "effect/Logger"; +import * as KeyValueStore from "effect/persistence/KeyValueStore"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as TestClock from "effect/testing/TestClock"; +import * as Scheduler from "../../scheduling/Scheduler.ts"; +import * as UsageService from "../../usage/UsageService.ts"; +import { runKinMigrations } from "../persistence/KinMigrations.ts"; +import * as CacheDaily from "./cacheDaily.ts"; + +const orgId = KinOrgId.make("tidewater"); +const localDate = "2026-11-28"; +const at = Date.parse("2026-11-28T12:00:00Z"); +const ledger = (input = 100, cacheRead = 9800, cacheWrite = 100, output = 40) => + JSON.stringify([ + { + providerTurnId: "test-ledger", + turnTokenUsage: { + usageStatus: "complete", + inputTokens: input + cacheRead + cacheWrite, + cachedInputTokens: cacheRead, + cacheCreationTokens: cacheWrite, + outputTokens: output, + models: ["fixture-native"], + }, + }, + ]); + +const seed = Effect.gen(function* () { + yield* runKinMigrations(); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_orgs VALUES (${orgId}, 'Tidewater Freight', '2026-11-15T00:00:00.000Z')`; + yield* sql`INSERT INTO kin_trigger_settings VALUES (${orgId}, 'Asia/Kolkata', '08:00', '18:00', + '02:00', 0, 1, '09:00', '{}')`; + yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, access, created_at) + VALUES ('rhea', ${orgId}, 'rhea', 'Rhea', 'owner', '2026-11-15T00:00:00.000Z')`; + yield* sql`INSERT INTO kin_agents (agent_id, org_id, display_name, role, owner_person_id, created_at) + VALUES ('dispatch', ${orgId}, 'Dispatch', 'lead', 'rhea', '2026-11-15T00:00:00.000Z')`; + yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, direct_key, last_seq, created_at) + VALUES ('rhea-dispatch', ${orgId}, 'direct', 'rhea-dispatch', 0, '2026-11-15T00:00:00.000Z')`; + yield* sql`INSERT INTO kin_leads (agent_id, org_id, name, level_since, models_json, worker_projects_json, owner_chat_id) + VALUES ('dispatch', ${orgId}, 'Dispatch', 0, '{}', '[]', 'rhea-dispatch')`; +}); + +const wake = Effect.fn("CacheDailyTest.wake")(function* ( + id: string, + options: { + readonly at?: number; + readonly kind?: string; + readonly status?: string; + readonly tokens?: string | null; + readonly sent?: "fresh" | "carried" | "refill"; + readonly reason?: string; + readonly units?: number; + } = {}, +) { + const sql = yield* SqlClient.SqlClient; + const start = options.at ?? at; + const status = options.status ?? "completed"; + const carry = + options.sent === undefined + ? null + : JSON.stringify({ sent: options.sent, reason: options.reason }); + yield* sql`INSERT INTO kin_wakeups (org_id, wakeup_id, agent_id, model, started_at, ended_at, + status, event_ids, kind, tokens_json, carry_json) + VALUES (${orgId}, ${id}, 'dispatch', 'fixture', ${start}, ${status === "running" ? null : start + 1000}, + ${status}, '[]', ${options.kind ?? "turn"}, ${options.tokens === undefined ? ledger() : options.tokens}, ${carry})`; + if (options.units !== undefined) { + yield* sql`INSERT INTO kin_budget (org_id, day) VALUES (${orgId}, ${localDate}) ON CONFLICT DO NOTHING`; + yield* sql`INSERT INTO kin_budget_charges (org_id, wakeup_id, day, units, tokens_json) + VALUES (${orgId}, ${id}, ${localDate}, ${options.units}, '[]')`; + } +}); + +const services = CacheDaily.layer.pipe( + Layer.provideMerge(NodeSqliteClient.layer({ filename: ":memory:" })), + Layer.provide( + Layer.mock(UsageService.UsageService)({ + priceAggregatedUsage: (rows) => + Effect.succeed( + rows.map( + ({ totals, reportedCostUsd }) => + reportedCostUsd ?? + (totals.uncachedInputTokens + + totals.cacheCreationTokens + + totals.outputTokens + + totals.cachedInputTokens * 0.1) / + 100_000, + ), + ), + }), + ), +); + +const figure = CacheDaily.KinCacheDaily.pipe( + Effect.flatMap((cache) => cache.day({ orgId, localDate })), +); +const withFixture = (effect: Effect.Effect) => + seed.pipe(Effect.andThen(effect), Effect.provide(services)); + +it.effect("read share, carried and fresh counts and reasons for a fixed day of rows", () => + withFixture( + Effect.gen(function* () { + yield* wake("carried", { sent: "carried", units: 100 }); + yield* wake("refill", { sent: "refill" }); + yield* wake("outside", { sent: "fresh", reason: "outside_read" }); + yield* wake("first", { sent: "fresh", reason: "new_chat" }); + yield* wake("new-reason", { sent: "fresh", reason: "a_future_reason" }); + yield* wake("outside-again", { sent: "fresh", reason: "outside_read" }); + yield* wake("shadow-mode", { sent: "fresh" }); + yield* wake("before-stamps"); + yield* wake("failed-turn", { status: "failed", sent: "fresh", units: 999 }); + yield* wake("running", { status: "running", tokens: null }); + const day = yield* figure; + assert.strictEqual(day.turns, 8); + assert.deepStrictEqual(day.tokens, { + input: 800, + cacheRead: 78400, + cacheWrite: 800, + output: 320, + }); + assert.strictEqual(day.readShare, 0.98); + assert.strictEqual(day.carried, 2); + assert.strictEqual(day.fresh, 5); + assert.deepStrictEqual(day.freshByReason, { + outside_read: 2, + new_chat: 1, + a_future_reason: 1, + }); + assert.strictEqual(day.turnBudgetUnits, 100); + assert.closeTo(day.costPerTurnUsd!, 0.0122, 1e-12); + }), + ), +); + +it.effect("a keep-warm row is not a turn and its spend is counted once", () => + withFixture( + Effect.gen(function* () { + yield* wake("turn", { units: 100 }); + yield* wake("ping", { + kind: "upkeep", + units: 25, + tokens: '{"input":10,"read":500,"written":50,"output":1,"cost":0.005}', + }); + yield* wake("failed", { + kind: "upkeep", + status: "failed", + tokens: '{"input":0,"read":100,"written":0,"output":1,"cost":0.001}', + }); + yield* wake("no-usage", { kind: "upkeep", tokens: null }); + const day = yield* figure; + assert.strictEqual(day.turns, 1); + assert.strictEqual(day.turnBudgetUnits, 100); + assert.deepStrictEqual(day.upkeep.tokens, { + input: 10, + cacheRead: 600, + cacheWrite: 50, + output: 2, + }); + assert.strictEqual(day.upkeep.count, 3); + assert.strictEqual(day.upkeep.failedOrWithoutUsage, 2); + assert.strictEqual(day.upkeep.budgetUnits, 25); + assert.strictEqual(day.upkeep.costUsd, 0.006); + assert.closeTo(day.costPerTurnUsd!, 0.0182, 1e-12); + }), + ), +); + +it.effect("an unknown kind is counted under its own name", () => + withFixture( + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + // The next kind needs its own migration; only this fixture admits it on K245. + yield* sql`PRAGMA ignore_check_constraints = ON`; + + yield* wake("compact", { kind: "a_future_kind", units: 50, tokens: ledger(7, 9, 11, 4) }); + yield* sql`PRAGMA ignore_check_constraints = OFF`; + + const day = yield* figure; + assert.strictEqual(day.turns, 0); + assert.strictEqual(day.upkeep.count, 1); + assert.closeTo(day.upkeep.byKind[0]?.costUsd ?? -1, 0.000229, 1e-12); + assert.deepStrictEqual( + day.upkeep.byKind.map(({ costUsd: _, ...row }) => row), + [ + { + kind: "a_future_kind", + count: 1, + failedOrWithoutUsage: 0, + budgetUnits: 50, + tokens: { input: 7, cacheRead: 9, cacheWrite: 11, output: 4 }, + }, + ], + ); + assert.isNull(day.costPerTurnUsd); + }), + ), +); + +it.effect( + "the day's bounds follow the owner's zone, including a zone change and both DST transitions", + () => + withFixture( + Effect.gen(function* () { + const cache = yield* CacheDaily.KinCacheDaily; + const sql = yield* SqlClient.SqlClient; + yield* wake("23:59", { at: Date.parse("2026-11-28T18:29:00Z") }); + yield* wake("00:01", { at: Date.parse("2026-11-28T18:31:00Z") }); + assert.strictEqual((yield* figure).turns, 1); + yield* TestClock.setTime(Date.parse("2026-11-28T18:35:00Z")); + const today = yield* cache.day({ orgId }); + assert.strictEqual(today.localDate, "2026-11-29"); + assert.strictEqual(today.turns, 1); + yield* sql`UPDATE kin_trigger_settings SET time_zone = 'America/New_York' WHERE org_id = ${orgId}`; + assert.strictEqual((yield* cache.day({ orgId })).turns, 2); + yield* wake("fall-last", { at: Date.parse("2026-11-02T04:59:59Z") }); + yield* wake("fall-next", { at: Date.parse("2026-11-02T05:00:00Z") }); + assert.strictEqual((yield* cache.day({ orgId, localDate: "2026-11-01" })).turns, 1); + yield* wake("spring-last", { at: Date.parse("2026-03-09T03:59:59Z") }); + yield* wake("spring-next", { at: Date.parse("2026-03-09T04:00:00Z") }); + assert.strictEqual((yield* cache.day({ orgId, localDate: "2026-03-08" })).turns, 1); + }), + ), +); + +it.effect("an empty day returns zeros and a null read share", () => + withFixture( + Effect.gen(function* () { + const zero = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 }; + assert.deepStrictEqual(yield* figure, { + localDate, + turns: 0, + turnsWithoutUsage: 0, + tokens: zero, + readShare: null, + carried: 0, + fresh: 0, + freshByReason: {}, + turnBudgetUnits: 0, + turnCostUsd: 0, + costPerTurnUsd: null, + upkeep: { + count: 0, + failedOrWithoutUsage: 0, + budgetUnits: 0, + tokens: zero, + costUsd: 0, + byKind: [], + }, + }); + }), + ), +); + +it.effect("the daily log line carries yesterday's figure, once, even when paused", () => + withFixture( + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_org_state (org_id, paused, paused_at, paused_by) + VALUES (${orgId}, 1, ${at}, 'rhea')`; + yield* wake("yesterday"); + yield* wake("today", { at: Date.parse("2026-11-28T18:31:00Z") }); + const logs: unknown[] = []; + const logger = Logger.make(({ message }) => { + if (Array.isArray(message) && message[0] === "kin.cache.daily") logs.push(message[1]); + }); + const jobs: Effect.Effect[] = []; + const scheduler = Scheduler.Scheduler.of({ + register: (_name: string, run: Effect.Effect) => + Effect.context().pipe( + Effect.tap((context) => + Effect.sync(() => { + jobs.push(run.pipe(Effect.provideContext(context), Effect.orDie)); + }), + ), + Effect.asVoid, + ), + }); + const store = yield* KeyValueStore.KeyValueStore; + const tick = Effect.scoped( + Effect.gen(function* () { + yield* Layer.build(CacheDaily.job); + const run = jobs.pop(); + if (run === undefined) return yield* Effect.die("The daily figure was not registered"); + yield* run; + }), + ).pipe( + Effect.provideService(Scheduler.Scheduler, scheduler), + Effect.provideService(KeyValueStore.KeyValueStore, store), + Effect.provide(Logger.layer([logger])), + ); + yield* TestClock.setTime(Date.parse("2026-11-28T18:34:59Z")); + yield* tick; + assert.deepStrictEqual(logs, []); + yield* TestClock.adjust(1000); + yield* tick; + yield* tick; // Rebuilds the job with the same marker, as on a restart. + assert.deepStrictEqual(logs, [yield* figure]); + yield* TestClock.adjust(24 * 3_600_000); + yield* tick; + yield* TestClock.adjust(24 * 3_600_000); + yield* tick; + assert.include(logs[2], { localDate: "2026-11-30", turns: 0, turnBudgetUnits: 0 }); + }).pipe(Effect.provide(KeyValueStore.layerMemory)), + ), +); diff --git a/apps/server/src/kin/host/cacheDaily.ts b/apps/server/src/kin/host/cacheDaily.ts new file mode 100644 index 000000000000..a6348a105b0d --- /dev/null +++ b/apps/server/src/kin/host/cacheDaily.ts @@ -0,0 +1,297 @@ +import type { KinCacheDailyInput, KinCacheDailyResult, KinOrgId } from "@t3tools/contracts"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as KeyValueStore from "effect/persistence/KeyValueStore"; +import * as SqlClient from "effect/sql/SqlClient"; +import type { SqlError } from "effect/sql/SqlError"; +import { ServerConfig } from "../../config.ts"; +import * as Scheduler from "../../scheduling/Scheduler.ts"; +import * as UsageService from "../../usage/UsageService.ts"; +import { dayIn } from "../work/money.ts"; +import { endOfDay, ownerZone, startOfDay } from "../work/recordRows.ts"; + +type Tokens = KinCacheDailyResult["tokens"]; +type UsageByKind = Omit; +type Counts = { + readonly kind: string; + readonly sent: string | null; + readonly reason: string | null; + readonly count: number; + readonly withoutUsage: number; + readonly failedOrWithoutUsage: number; + readonly budgetUnits: number; +}; +type Metered = Tokens & { + readonly kind: string; + readonly model: string; + readonly reportedCostUsd: number | null; +}; + +export class KinCacheDaily extends Context.Service< + KinCacheDaily, + { + readonly day: ( + input: KinCacheDailyInput & { readonly orgId: KinOrgId }, + ) => Effect.Effect; + } +>()("t3/kin/host/cacheDaily/KinCacheDaily") {} + +const empty = (): UsageByKind => ({ + count: 0, + failedOrWithoutUsage: 0, + tokens: { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 }, + budgetUnits: 0, + costUsd: 0, +}); +const addTokens = (a: Tokens, b: Tokens): Tokens => ({ + input: a.input + b.input, + cacheRead: a.cacheRead + b.cacheRead, + cacheWrite: a.cacheWrite + b.cacheWrite, + output: a.output + b.output, +}); +const addCost = (a: number | null, b: number | null) => (a === null || b === null ? null : a + b); + +// The wake-up writer's provider ledger includes cache reads and writes in input; the upkeep SDK +// writes the four disjoint counts directly. Local commands and context-size fallbacks aren't usage. +const meteredLedger = `CASE WHEN u.type = 'object' THEN + json_extract(u.value, '$.turnTokenUsage.usageStatus') IN ('complete', 'partial') + AND COALESCE(json_extract(u.value, '$.turnTokenUsage.localCommand'), 0) = 0 + AND COALESCE(json_extract(u.value, '$.turnTokenUsage.inputTokens'), + json_extract(u.value, '$.turnTokenUsage.cachedInputTokens'), + 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'`; + +const readDay = Effect.fn("KinCacheDaily.readDay")(function* ( + orgId: KinOrgId, + requested: string | undefined, + now: number, +) { + const sql = yield* SqlClient.SqlClient; + const zone = yield* ownerZone(orgId); + const localDate = requested ?? dayIn(now, zone); + const from = startOfDay(localDate, zone); + const until = endOfDay(localDate, zone) + 1; + const inDay = sql`w.org_id = ${orgId} AND w.started_at >= ${from} AND w.started_at < ${until} + AND (w.kind <> 'turn' OR w.status = 'completed')`; + + const counts = yield* sql` + WITH activity AS ( + SELECT w.kind, w.status, w.ended_at, c.units, + 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' + AND json_type(w.carry_json, '$.reason') = 'text' THEN json_extract(w.carry_json, '$.reason') + END AS reason, + CASE WHEN ${sql.literal(meteredRaw)} OR EXISTS ( + SELECT 1 FROM json_each(CASE WHEN json_type(w.tokens_json) = 'array' THEN w.tokens_json END) u + WHERE ${sql.literal(meteredLedger)} + ) THEN 1 ELSE 0 END AS metered + FROM kin_wakeups w + LEFT JOIN kin_budget_charges c ON c.org_id = w.org_id AND c.wakeup_id = w.wakeup_id + WHERE ${inDay} + ) + SELECT kind, sent, reason, COUNT(*) AS count, SUM(1 - metered) AS "withoutUsage", + SUM(CASE WHEN status NOT IN ('running', 'completed') + OR (ended_at IS NOT NULL AND metered = 0) THEN 1 ELSE 0 END) AS "failedOrWithoutUsage", + COALESCE(SUM(units), 0) AS "budgetUnits" + FROM activity GROUP BY kind, sent, reason ORDER BY kind, sent, reason`; + + const metered = yield* sql` + WITH wakeups AS MATERIALIZED ( + SELECT w.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, + COALESCE(json_extract(w.tokens_json, '$.output'), 0) AS output, + json_extract(w.tokens_json, '$.cost') AS reported + FROM wakeups w WHERE ${sql.literal(meteredRaw)} + UNION ALL + SELECT w.kind, + CASE WHEN json_array_length(u.value, '$.turnTokenUsage.models') = 1 + THEN COALESCE(json_extract(u.value, '$.turnTokenUsage.models[0]'), w.model) + ELSE w.model END AS model, + MAX(0, COALESCE(json_extract(u.value, '$.turnTokenUsage.inputTokens'), 0) + - COALESCE(json_extract(u.value, '$.turnTokenUsage.cachedInputTokens'), 0) + - COALESCE(json_extract(u.value, '$.turnTokenUsage.cacheCreationTokens'), 0)) AS input, + COALESCE(json_extract(u.value, '$.turnTokenUsage.cachedInputTokens'), 0) AS cached, + COALESCE(json_extract(u.value, '$.turnTokenUsage.cacheCreationTokens'), 0) AS written, + COALESCE(json_extract(u.value, '$.turnTokenUsage.outputTokens'), 0) AS output, + NULL AS reported + FROM wakeups w, json_each(CASE WHEN json_type(w.tokens_json) = 'array' THEN w.tokens_json END) u + WHERE ${sql.literal(meteredLedger)} + ) + SELECT kind, model, SUM(input) AS input, SUM(cached) AS "cacheRead", + SUM(written) AS "cacheWrite", SUM(output) AS output, SUM(reported) AS "reportedCostUsd" + FROM usage GROUP BY kind, model, reported IS NOT NULL ORDER BY kind, model, reported IS NOT NULL`; + return { localDate, counts, metered }; +}); + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const usage = yield* UsageService.UsageService; + const day: KinCacheDaily["Service"]["day"] = Effect.fn("KinCacheDaily.day")(function* ({ + orgId, + localDate: requested, + }) { + const now = yield* Clock.currentTimeMillis; + const { localDate, counts, metered } = yield* NodeSqliteClient.readOnly( + sql.withTransaction( + readDay(orgId, requested, now).pipe(Effect.provideService(SqlClient.SqlClient, sql)), + ), + ); + const prices = yield* usage + .priceAggregatedUsage( + metered.map(({ model, input, cacheRead, cacheWrite, output, reportedCostUsd }) => ({ + model, + totals: { + uncachedInputTokens: input, + cachedInputTokens: cacheRead, + cacheCreationTokens: cacheWrite, + outputTokens: output, + reasoningTokens: 0, + }, + reportedCostUsd, + })), + ) + .pipe(Effect.orElseSucceed(() => metered.map(() => null))); + + const byKind = new Map([["turn", empty()]]); + const reasons = new Map(); + let carried = 0; + let fresh = 0; + let turnsWithoutUsage = 0; + for (const row of counts) { + const prior = byKind.get(row.kind) ?? empty(); + byKind.set(row.kind, { + ...prior, + count: prior.count + row.count, + failedOrWithoutUsage: prior.failedOrWithoutUsage + row.failedOrWithoutUsage, + budgetUnits: prior.budgetUnits + row.budgetUnits, + }); + if (row.kind !== "turn") continue; + turnsWithoutUsage += row.withoutUsage; + if (row.sent === "carried" || row.sent === "refill") carried += row.count; + if (row.sent !== "fresh") continue; + fresh += row.count; + if (row.reason !== null) reasons.set(row.reason, (reasons.get(row.reason) ?? 0) + row.count); + } + for (const [index, row] of metered.entries()) { + const prior = byKind.get(row.kind) ?? empty(); + byKind.set(row.kind, { + ...prior, + tokens: addTokens(prior.tokens, row), + costUsd: addCost(prior.costUsd, prices[index] ?? null), + }); + } + const turn = byKind.get("turn") ?? empty(); + byKind.delete("turn"); + const kinds = Array.from(byKind, ([kind, totals]) => ({ kind, ...totals })); + const upkeep = kinds.reduce( + (acc, row) => ({ + count: acc.count + row.count, + failedOrWithoutUsage: acc.failedOrWithoutUsage + row.failedOrWithoutUsage, + budgetUnits: acc.budgetUnits + row.budgetUnits, + tokens: addTokens(acc.tokens, row.tokens), + costUsd: addCost(acc.costUsd, row.costUsd), + }), + empty(), + ); + const { input, cacheRead, cacheWrite } = turn.tokens; + const incoming = input + cacheRead + cacheWrite; + const turnCostUsd = turnsWithoutUsage > 0 ? null : turn.costUsd; + const combined = addCost(turnCostUsd, upkeep.costUsd); + return { + localDate, + turns: turn.count, + turnsWithoutUsage, + tokens: turn.tokens, + readShare: incoming === 0 ? null : cacheRead / incoming, + carried, + fresh, + freshByReason: Object.fromEntries(reasons), + turnBudgetUnits: turn.budgetUnits, + turnCostUsd, + costPerTurnUsd: turn.count === 0 || combined === null ? null : combined / turn.count, + upkeep: { ...upkeep, byKind: kinds }, + }; + }); + return KinCacheDaily.of({ day }); +}); + +export const layer = Layer.effect(KinCacheDaily, make); + +const LOG_DELAY_MS = 5 * 60_000; + +export const job = Layer.effectDiscard( + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const cache = yield* KinCacheDaily; + const marks = yield* KeyValueStore.KeyValueStore; + const scheduler = yield* Scheduler.Scheduler; + const seen = new Map(); + let nextCheck = 0; + const logOrg = Effect.fn("KinCacheDaily.logOrg")(function* (orgId: KinOrgId, now: number) { + const zone = yield* ownerZone(orgId); + const today = dayIn(now, zone); + const midnight = startOfDay(today, zone); + if (now < midnight + LOG_DELAY_MS) return; + const yesterday = DateTime.formatIsoDate( + DateTime.subtract(DateTime.makeUnsafe(today), { days: 1 }), + ); + const logged = seen.get(orgId) ?? (yield* marks.get(orgId)); + if (logged !== undefined && logged >= yesterday) { + seen.set(orgId, logged); + return; + } + const figure = yield* cache.day({ orgId, localDate: yesterday }); + // The scheduler serializes this source. Remember the day before emitting so restarts don't replay it. + yield* marks + .set(orgId, yesterday) + .pipe( + Effect.andThen( + Effect.logInfo("kin.cache.daily", figure).pipe(Effect.annotateLogs({ orgId })), + ), + Effect.uninterruptible, + ); + }); + yield* scheduler.register( + "kin-cache-daily", + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + if (now < nextCheck) return; + nextCheck = now + 60_000; + const orgs = yield* sql<{ + orgId: KinOrgId; + }>`SELECT org_id AS "orgId" FROM kin_orgs ORDER BY org_id`; + for (const { orgId } of orgs) { + yield* logOrg(orgId, now).pipe( + Effect.catch(() => Effect.logWarning("Kin daily cache figure failed", { orgId })), + ); + } + }), + ); + }), +); + +export const jobLayer = job.pipe( + Layer.provide(layer), + Layer.provide( + Layer.unwrap( + Effect.gen(function* () { + const { stateDir } = yield* ServerConfig; + const path = yield* Path.Path; + return KeyValueStore.layerFileSystem(path.join(stateDir, "kin-cache-daily")); + }), + ), + ), + Layer.catch(() => + Layer.effectDiscard(Effect.logWarning("Kin daily cache figure could not be scheduled")), + ), +); diff --git a/apps/server/src/kin/host/rpcHandlers.ts b/apps/server/src/kin/host/rpcHandlers.ts index 29089e39c45d..49527f7dd0b1 100644 --- a/apps/server/src/kin/host/rpcHandlers.ts +++ b/apps/server/src/kin/host/rpcHandlers.ts @@ -4,11 +4,14 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as RpcGroup from "effect/rpc/RpcGroup"; +import * as SqlClient from "effect/sql/SqlClient"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import * as UsageService from "../../usage/UsageService.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; import { KinServer } from "../KinServer.ts"; import { KinHostCare } from "./KinHostCare.ts"; +import * as CacheDaily from "./cacheDaily.ts"; const group = RpcGroup.make(...KinHostRpcs); const isKinError = Schema.is(KinChatError); @@ -21,6 +24,7 @@ const notFound = new KinChatError({ reason: "not_found", message: "No such org h */ export const makeKinHostHandlers = Effect.fn("makeKinHostHandlers")(function* ( session: AuthenticatedSession, + usage: UsageService.UsageService["Service"] | undefined, ) { const kin = yield* Effect.serviceOption(KinServer); const run = Effect.fn("KinHostCare.rpc")( @@ -36,7 +40,26 @@ export const makeKinHostHandlers = Effect.fn("makeKinHostHandlers")(function* ( }, Effect.mapError((error) => (isKinError(error) ? error : unavailable)), ); + const services = Option.flatMap(kin, (k) => k.services); + const daily = + Option.isNone(services) || usage === undefined + ? undefined + : { + orgId: Context.get(services.value, KinIdentity).owner.orgId, + sql: Context.get(services.value, SqlClient.SqlClient), + usage, + }; return group.of({ + "kin.host.cacheDaily": (input) => + daily === undefined + ? Effect.fail(unavailable) + : CacheDaily.KinCacheDaily.pipe( + Effect.flatMap((cache) => cache.day({ ...input, orgId: daily.orgId })), + Effect.provide(CacheDaily.layer), + Effect.provideService(SqlClient.SqlClient, daily.sql), + Effect.provideService(UsageService.UsageService, daily.usage), + Effect.mapError(() => unavailable), + ), "kin.host.status": (input) => run(input.orgId, (care) => care.status(input.orgId)), "kin.host.freeSpace": (input) => run(input.orgId, (care) => care.freeSpace(input.orgId)), "kin.host.backUpNow": (input) => run(input.orgId, (care) => care.backUpNow(input.orgId)), diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index 5359731647c4..ef6dc7249499 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -1,3 +1,4 @@ +import * as UsageService from "../../usage/UsageService.ts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as ServerConfig from "../../config.ts"; import * as DocumentText from "../../provider/DocumentText.ts"; @@ -6267,6 +6268,7 @@ describe("WakeupRunner", () => { Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}), Layer.mock(ProjectService.ProjectService)({}), Layer.mock(ServerSettings.ServerSettingsService)({}), + Layer.mock(UsageService.UsageService)({}), Layer.mock(KinIssuedTokens.KinIssuedTokens)({}), Layer.mock(KinLeadPrompt)({ build: () => Effect.succeed("unused") }), Layer.mock(DocumentText.DocumentText)({}), diff --git a/apps/server/src/kin/lead/layer.test.ts b/apps/server/src/kin/lead/layer.test.ts index 4e71c7252abd..2c18cd59f078 100644 --- a/apps/server/src/kin/lead/layer.test.ts +++ b/apps/server/src/kin/lead/layer.test.ts @@ -1,3 +1,4 @@ +import * as UsageService from "../../usage/UsageService.ts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; @@ -53,6 +54,7 @@ import { kinInstructions } from "./turn/session.ts"; import { event, harness, seed, orgId } from "./WakeupRunner.testkit.ts"; const external = Layer.mergeAll( + Layer.mock(UsageService.UsageService)({}), // The lead runtime attaches its memory reader for deferral card taps. Layer.mock(ChatService.KinChatService)({ attachDeferralItems: () => Effect.void }), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), diff --git a/apps/server/src/kin/lead/layer.ts b/apps/server/src/kin/lead/layer.ts index 789361e587e7..35ab70c37fcf 100644 --- a/apps/server/src/kin/lead/layer.ts +++ b/apps/server/src/kin/lead/layer.ts @@ -8,6 +8,7 @@ import * as ScheduledTasks from "../triggers/scheduledTasks.ts"; import * as KinSchedules from "../triggers/kinSchedules.ts"; import * as Watchdogs from "../triggers/watchdogs.ts"; import * as HostBackupCheck from "../host/backupCheck.ts"; +import * as CacheDaily from "../host/cacheDaily.ts"; import * as RunningSpend from "../host/runningSpend.ts"; import * as SessionUpkeep from "../host/sessionUpkeep.ts"; import * as OfflineCatchUp from "../host/offlineCatchUp.ts"; @@ -124,6 +125,7 @@ const routineRuntime = Layer.mergeAll( Watchdogs.layer, HostBackupCheck.layer, RunningSpend.layer, + CacheDaily.jobLayer, SessionUpkeep.layer, KinPulse.layer, ArrivalFeed.liveLayer, diff --git a/apps/server/src/kin/mcp/layer.test.ts b/apps/server/src/kin/mcp/layer.test.ts index 595b073c8138..7f0660794489 100644 --- a/apps/server/src/kin/mcp/layer.test.ts +++ b/apps/server/src/kin/mcp/layer.test.ts @@ -1,3 +1,4 @@ +import * as UsageService from "../../usage/UsageService.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ClaudeAdapter from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; import * as CodexAdapter from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; @@ -252,6 +253,7 @@ const toolHandlerServices = Layer.mergeAll( serverSettings, Layer.mock(SourceControlRepositoryService)({}), Layer.mock(ThreadLaunchService)({}), + Layer.mock(UsageService.UsageService)({}), Layer.mock(ThreadManagementService)({ getThreadShell: (id) => Effect.succeed(liveThreadShell(id)), }), diff --git a/apps/server/src/kin/rpcAccess.test.ts b/apps/server/src/kin/rpcAccess.test.ts index da95fb8618c7..442495f27d75 100644 --- a/apps/server/src/kin/rpcAccess.test.ts +++ b/apps/server/src/kin/rpcAccess.test.ts @@ -1,5 +1,6 @@ import { assert, it } from "@effect/vitest"; import { + AuthDiagnosticsReadScope, AuthKinChatScope, AuthKinTasksScope, AuthSessionId, @@ -224,9 +225,23 @@ it.layer(layerKinAuthTest("kin-rpc-access-"))("KIN_RPC_ACCESS", (it) => { if (yield* allowed("meera", method)) table.member.push(method); } assert.deepStrictEqual(table.owner, methods); + const daily = "kin.host.cacheDaily"; + assert.include(table.owner, daily); + assert.notInclude(table.coOwner, daily); + assert.notInclude(table.member, daily); + assert.strictEqual(yield* allowed("stranger", daily), false); + assert.strictEqual(Reflect.get(CLIENT_GUARDED_RPC_SCOPES, daily), AuthDiagnosticsReadScope); + for (const scope of [AuthKinTasksScope, AuthKinChatScope]) { + assert.strictEqual( + (yield* authorizeRpc([scope], daily, {}).pipe(Effect.exit))._tag, + "Failure", + ); + } + yield* authorizeRpc([AuthDiagnosticsReadScope], daily, {}); assert.deepStrictEqual( methods.filter((method) => !table.coOwner.includes(method)), [ + "kin.host.cacheDaily", "kin.people.setAccess", "kin.people.setOwnerName", // What Kin suggested to the owner, and his answers: his alone. diff --git a/apps/server/src/kin/rpcHandlers.ts b/apps/server/src/kin/rpcHandlers.ts index 640f62664b07..bb16237473f9 100644 --- a/apps/server/src/kin/rpcHandlers.ts +++ b/apps/server/src/kin/rpcHandlers.ts @@ -21,6 +21,7 @@ import * as Rpc from "effect/rpc/Rpc"; import * as RpcGroup from "effect/rpc/RpcGroup"; import * as RpcSchema from "effect/rpc/RpcSchema"; import type { AuthenticatedSession } from "../auth/EnvironmentAuth.ts"; +import type { UsageService } from "../usage/UsageService.ts"; import { makeKinApprovalHandlers } from "./approvals/rpcHandlers.ts"; import { KinIdentity } from "./chat/KinIdentity.ts"; import { makeKinChatHandlers } from "./chat/rpcHandlers.ts"; @@ -131,6 +132,7 @@ export const forPerson = export const makeKinHandlers = Effect.fn("makeKinHandlers")(function* ( session: AuthenticatedSession, + usage?: UsageService["Service"], ) { const kin = yield* Effect.serviceOption(KinServer); const bankReader = yield* Effect.serviceOption(BankAlertReader); @@ -153,7 +155,7 @@ export const makeKinHandlers = Effect.fn("makeKinHandlers")(function* ( ...(yield* makeKinRecommendHandlers(session)), ...(yield* makeKinBankSenderHandlers(session)), ...(yield* makeKinBillSenderHandlers(session)), - ...(yield* makeKinHostHandlers(session)), + ...(yield* makeKinHostHandlers(session, usage)), ...(yield* makeKinWatchHandlers(session)), }); const personSees = forPerson(session, services); diff --git a/apps/server/src/kin/tasksKey/reach.test.ts b/apps/server/src/kin/tasksKey/reach.test.ts index 2ea33a64fb25..1f196fc45ab9 100644 --- a/apps/server/src/kin/tasksKey/reach.test.ts +++ b/apps/server/src/kin/tasksKey/reach.test.ts @@ -712,6 +712,7 @@ const reach: Readonly | string>> = { "kin.billSenders.readSince": "stays in the app: 5 (host, company sections and settings)", "kin.recommendations.list": "not a person action (screens only: Settings → Recommendations)", "kin.recommendations.askAgain": "stays in the app: 5 (host, company sections and settings)", + "kin.host.cacheDaily": "not a person action (owner-only Usage read)", "kin.host.status": "not a person action (screens only: host screen)", "kin.host.freeSpace": "stays in the app: 5 (host, company sections and settings)", "kin.host.backUpNow": "stays in the app: 5 (host, company sections and settings)", diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index d2bc0c296fbc..dab0c5681869 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -3143,6 +3143,11 @@ describe("UsageService", () => { const original = yield* service.readSummary(WINDOW); assert.strictEqual(original.buckets[0]?.costUsd, 0); assert.strictEqual(original.buckets[0]?.unpricedRecords, 1); + const metered = { model: "example-model", totals: original.buckets[0]!.totals }; + const price = (reportedCostUsd: number | null) => + service.priceAggregatedUsage([{ ...metered, reportedCostUsd }]); + assert.deepStrictEqual(yield* price(null), [null]); + assert.deepStrictEqual(yield* price(0.002), [0.002]); yield* settingsService.updateSettings({ usagePriceOverrides: { @@ -3154,6 +3159,8 @@ describe("UsageService", () => { assert.strictEqual(overridden.buckets[0]?.costSource, "modelPriced"); assert.strictEqual(overridden.buckets[0]?.unpricedRecords, 0); assert.deepStrictEqual(overridden.buckets[0]?.totals, original.buckets[0]?.totals); + assert.deepStrictEqual(yield* price(null), [overridden.buckets[0]!.costUsd]); + assert.deepStrictEqual(yield* price(0.002), [overridden.buckets[0]!.costUsd]); yield* settingsService.updateSettings({ usagePriceOverrides: { @@ -3162,6 +3169,15 @@ describe("UsageService", () => { }); const edited = yield* service.readSummary(WINDOW); assert.closeTo(edited.buckets[0]?.costUsd ?? -1, 0.00012, 1e-12); + yield* settingsService.updateSettings({ + usageModelAliases: { "fixture-alias": "example-model" }, + }); + assert.deepStrictEqual( + yield* service.priceAggregatedUsage([ + { ...metered, model: "fixture-alias", reportedCostUsd: null }, + ]), + [edited.buckets[0]!.costUsd], + ); yield* settingsService.updateSettings({ usagePriceOverrides: { "example-model": null } }); const restored = yield* service.readSummary(WINDOW); diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index 3ff200426665..5114d22a8582 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -49,6 +49,8 @@ import { createOverrideRateTable, isUnlistedModel, parseRateTable, + priceUsage, + type PricedRecord, type RateTable, } from "./usagePricing.ts"; import { @@ -161,11 +163,16 @@ const decodeCachedSources = Schema.decodeUnknownOption( }), ); +type AggregatePriceInput = Pick; + export class UsageService extends Context.Service< UsageService, { readonly readSummary: (input: UsageSummaryInput) => Effect.Effect; readonly refreshRates: Effect.Effect; + readonly priceAggregatedUsage: ( + rows: ReadonlyArray, + ) => Effect.Effect, UsageReadError>; } >()("t3/usage/UsageService") {} @@ -361,6 +368,29 @@ export const make = Effect.gen(function* () { ), ); + const priceAggregatedUsage = Effect.fn("UsageService.priceAggregatedUsage")(function* ( + rows: ReadonlyArray, + ) { + if (rows.length === 0) return []; + const settings = yield* readSettings; + const overrides = createOverrideRateTable(settings.usagePriceOverrides); + const aliases = resolveModelAliases(settings.usageModelAliases); + const mapped = rows.map((row) => ({ ...row, model: aliases.get(row.model) ?? row.model })); + const needsRates = new Set( + mapped + .filter((row) => row.reportedCostUsd === null && !overrides.has(row.model.trim())) + .map((row) => row.model), + ); + if (needsRates.size > 0) { + yield* ensureRates(false); + yield* refreshForUnlistedModels(needsRates); + } + return mapped.map((row) => { + const priced = priceUsage(rates, { ...row, speed: "standard" }, overrides, "aggregate"); + return priced.costSource === "unpriced" ? null : priced.costUsd; + }); + }); + const usageInstances = Effect.fn("UsageService.usageInstances")(function* ( driver: ProviderDriver, settings: ServerSettingsValue, @@ -1269,7 +1299,7 @@ export const make = Effect.gen(function* () { return yield* Deferred.await(deferred); }); - return { readSummary, refreshRates, awaitPersisted } as const; + return { readSummary, refreshRates, priceAggregatedUsage, awaitPersisted } as const; }); export const layer = Layer.effect(UsageService, make); diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts index a9ffc691643f..f6b7f61ad538 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -364,6 +364,7 @@ export function priceUsage( table: RateTable, record: PricedRecord, overrides?: RateTable, + mode: "request" | "aggregate" = "request", ): PricedUsage { const { model, totals, reportedCostUsd } = record; const override = overrides?.get(model.trim()); @@ -382,11 +383,15 @@ export function priceUsage( return reported === null ? unsplit(0, "unpriced") : unsplit(reported, "providerReported"); } - const listCost = costByCategory(record, ratesAt(rate, record.speed, totals)); + // An aggregate cannot tell which requests actually crossed a context tier. + const listCost = costByCategory( + record, + mode === "aggregate" ? rate : ratesAt(rate, record.speed, totals), + ); const listCostUsd = sumCategories(listCost); if (reported !== null && listCostUsd <= 0) return unsplit(reported, "providerReported"); const premiumUsd = - record.speed === "standard" + mode === "aggregate" || record.speed === "standard" ? 0 : listCostUsd - sumCategories(costByCategory(record, ratesAt(rate, "standard", totals))); const scale = reported === null ? 1 : reported / listCostUsd; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 3f8efc9e33bf..a7f96607d2ba 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2042,7 +2042,7 @@ export const layerWsRpc = ( }); const handlers = ServerWsRpcGroup.of({ - ...(yield* makeKinHandlers(currentSession)), + ...(yield* makeKinHandlers(currentSession, usage)), [WS_METHODS.issuesList]: (input) => issues.list(input), [WS_METHODS.issuesDetail]: (input) => issues.detail(input), [WS_METHODS.issuesComments]: (input) => issues.comments(input), diff --git a/packages/client-runtime/src/kin/kinClient.ts b/packages/client-runtime/src/kin/kinClient.ts index 5dcce448ebc3..706588de5f31 100644 --- a/packages/client-runtime/src/kin/kinClient.ts +++ b/packages/client-runtime/src/kin/kinClient.ts @@ -1531,6 +1531,10 @@ export function makeKinClient( staleTimeMs: 30_000, refreshTrigger: kinRefreshOn("budget"), }), + cacheDaily: createKinRpcCommand(runtime, { + label: "kin:host:cache-daily", + tag: "kin.host.cacheDaily", + }), budgetSet: createKinRpcCommand(runtime, { label: "kin:budget:set", tag: "kin.budget.set", diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index e8e8977465b2..9552b36f010a 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -8,6 +8,7 @@ import { describe, expect, it } from "@effect/vitest"; import { vi } from "vite-plus/test"; import { AuthAccessReadScope, + AuthDiagnosticsReadScope, AuthKinChatScope, KIN_RPC_SCOPES, AuthAccessWriteScope, @@ -73,7 +74,7 @@ const setup = Effect.gen(function* () { describe("command permissions", () => { // Who may call a Kin method is Kin's rule (`KIN_RPC_ACCESS`), checked by kind on the host and in - // `createKinRpcCommand`. The connection needs Kin's chat grant, or operate for the host CLI's. + // `createKinRpcCommand`. The connection also needs that method's scope. it.effect.each(Object.entries(KIN_RPC_SCOPES))( "requires the destination grant for %s", ([method, scope]) => @@ -83,6 +84,7 @@ describe("command permissions", () => { const permissions = createCommandPermissions(runtime, method); const others = [ AuthKinChatScope, + AuthDiagnosticsReadScope, AuthOrchestrationReadScope, AuthOrchestrationOperateScope, AuthSettingsWriteScope, diff --git a/packages/contracts/src/auth.kin.test.ts b/packages/contracts/src/auth.kin.test.ts index e13f3255cad7..cf6e05d016e9 100644 --- a/packages/contracts/src/auth.kin.test.ts +++ b/packages/contracts/src/auth.kin.test.ts @@ -1,6 +1,8 @@ import { expect, it } from "vite-plus/test"; +import * as Schema from "effect/Schema"; import { + AuthDiagnosticsReadScope, AuthEnvironmentScope, AuthKinChatScope, AuthKinTasksScope, @@ -9,6 +11,7 @@ import { sessionIsChatOnly, } from "./auth.ts"; import { clientRpcRequiredScopes } from "./clientRpcPermissions.ts"; +import { KinCacheDailyInput } from "./kinHostCare.ts"; import { KinBankSenderRpcs } from "./kinBankSenders.ts"; import { KIN_RPC_AGGREGATES, KIN_RPC_SCOPES, kinRpcAccess } from "./kinRpcs.ts"; @@ -51,3 +54,14 @@ it.each(billSenderRpcs)("guards billing sender %s for owners and co-owners", (me expect(clientRpcRequiredScopes(tag, undefined)).toEqual([AuthKinChatScope]); expect(kinRpcAccess(tag as Parameters[0])).toBe("owner_level"); }); + +it("requires the Usage grant and the org owner for daily cache figures, with a real local date", () => { + const tag = "kin.host.cacheDaily"; + expect(clientRpcRequiredScopes(tag, {})).toEqual([AuthDiagnosticsReadScope]); + expect(kinRpcAccess(tag)).toBe("org_owner"); + const accepts = Schema.is(KinCacheDailyInput); + expect(accepts({})).toBe(true); + expect(accepts({ localDate: "2028-02-29" })).toBe(true); + for (const localDate of ["2026-02-29", "2026-02-30", "2026-13-01", "2026-11-28T00:00:00Z", null]) + expect(accepts({ localDate })).toBe(false); +}); diff --git a/packages/contracts/src/kinHostCare.ts b/packages/contracts/src/kinHostCare.ts index 5226fa46b549..6fcf3dc20428 100644 --- a/packages/contracts/src/kinHostCare.ts +++ b/packages/contracts/src/kinHostCare.ts @@ -1,7 +1,13 @@ +import * as DateTime from "effect/DateTime"; +import * as Option from "effect/Option"; import * as Rpc from "effect/rpc/Rpc"; import * as Schema from "effect/Schema"; -import { AuthKinChatScope, EnvironmentAuthorizationError } from "./auth.ts"; +import { + AuthDiagnosticsReadScope, + AuthKinChatScope, + EnvironmentAuthorizationError, +} from "./auth.ts"; import { IsoDateTime, KinText, KinTrimmedText, NonNegativeInt } from "./baseSchemas.ts"; import { KinAgentId, KinChatError, KinOrgId, KinWidgetId } from "./kinChat.ts"; @@ -357,11 +363,57 @@ export type KinHostBackUpResult = typeof KinHostBackUpResult.Type; export const KinHostRetryResult = Schema.Struct({ requeued: NonNegativeInt }); export type KinHostRetryResult = typeof KinHostRetryResult.Type; +const CacheLocalDate = Schema.String.check( + Schema.isPattern(/^\d{4}-\d{2}-\d{2}$/), + Schema.makeFilter((day: string) => { + const at = DateTime.make(`${day}T00:00:00Z`); + return Option.isSome(at) && DateTime.formatIsoDate(at.value) === day; + }), +); + +export const KinCacheDailyInput = Schema.Struct({ localDate: Schema.optionalKey(CacheLocalDate) }); +export type KinCacheDailyInput = typeof KinCacheDailyInput.Type; + +const CacheTokens = Schema.Struct({ + input: NonNegativeInt, + cacheRead: NonNegativeInt, + cacheWrite: NonNegativeInt, + output: NonNegativeInt, +}); +const CacheAmount = Schema.Number.check(Schema.isFinite(), Schema.isGreaterThanOrEqualTo(0)); +const CacheUpkeep = { + count: NonNegativeInt, + failedOrWithoutUsage: NonNegativeInt, + tokens: CacheTokens, + budgetUnits: CacheAmount, + costUsd: Schema.NullOr(CacheAmount), +}; +export const KinCacheDailyResult = Schema.Struct({ + localDate: CacheLocalDate, + turns: NonNegativeInt, + turnsWithoutUsage: NonNegativeInt, + tokens: CacheTokens, + readShare: Schema.NullOr(Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1 }))), + carried: NonNegativeInt, + fresh: NonNegativeInt, + freshByReason: Schema.Record(Schema.String, NonNegativeInt), + turnBudgetUnits: CacheAmount, + // Ledger-based USD estimate; null means that some turn usage could not be priced. + turnCostUsd: Schema.NullOr(CacheAmount), + costPerTurnUsd: Schema.NullOr(CacheAmount), + upkeep: Schema.Struct({ + ...CacheUpkeep, + byKind: Schema.Array(Schema.Struct({ kind: Schema.String, ...CacheUpkeep })), + }), +}); +export type KinCacheDailyResult = typeof KinCacheDailyResult.Type; + const KIN_HOST_WS_METHODS = { status: "kin.host.status", freeSpace: "kin.host.freeSpace", backUpNow: "kin.host.backUpNow", retry: "kin.host.retry", + cacheDaily: "kin.host.cacheDaily", } as const; const error = Schema.Union([KinChatError, EnvironmentAuthorizationError]); @@ -383,6 +435,11 @@ export const KinHostRpcs = [ success: KinHostRetryResult, error, }), + Rpc.make(KIN_HOST_WS_METHODS.cacheDaily, { + payload: KinCacheDailyInput, + success: KinCacheDailyResult, + error, + }), ] as const; export const KIN_HOST_RPC_SCOPES = { @@ -390,6 +447,7 @@ export const KIN_HOST_RPC_SCOPES = { [KIN_HOST_WS_METHODS.freeSpace]: AuthKinChatScope, [KIN_HOST_WS_METHODS.backUpNow]: AuthKinChatScope, [KIN_HOST_WS_METHODS.retry]: AuthKinChatScope, + [KIN_HOST_WS_METHODS.cacheDaily]: AuthDiagnosticsReadScope, } as const; const GB = 1024 ** 3; diff --git a/packages/contracts/src/kinRpcs.ts b/packages/contracts/src/kinRpcs.ts index 0e37ea52c2f9..e9688552ae10 100644 --- a/packages/contracts/src/kinRpcs.ts +++ b/packages/contracts/src/kinRpcs.ts @@ -302,7 +302,7 @@ export const KIN_RPC_SCOPES = { /** * Who may call each Kin method, from the caller's stored kind (`kin_people.access`): `person` is * anyone in the org, the service deciding the rest; `owner_level` the owner or a co-owner; - * `org_owner` the owner alone. Every Kin method takes the Kin session scope, so this is the gate + * `org_owner` the owner alone. In addition to the method’s scope, this is the gate * the server applies before the handler and the clients read to offer a control. */ export type KinRpcAccess = "person" | "owner_level" | "org_owner"; @@ -556,6 +556,7 @@ const KIN_RPC_ACCESS = { // What Kin suggested to the owner and his answers: his alone, as the cards are. "kin.recommendations.list": "org_owner", "kin.recommendations.askAgain": "org_owner", + "kin.host.cacheDaily": "org_owner", "kin.host.status": "owner_level", "kin.host.freeSpace": "owner_level", "kin.host.backUpNow": "owner_level", @@ -690,6 +691,7 @@ export const KIN_RPC_AGGREGATES = { "kin.billSenders.readSince": "kin-work", "kin.recommendations.list": "kin-recommendations", "kin.recommendations.askAgain": "kin-recommendations", + "kin.host.cacheDaily": "kin-host", "kin.host.status": "kin-host", "kin.host.freeSpace": "kin-host", "kin.host.backUpNow": "kin-host", From 4d26f9812d1b5b2ffdc346637d069d6e536b6a26 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:56:22 +0530 Subject: [PATCH 2/4] feat(kin): show the day's cache figure on Usage Today's and yesterday's Kin cache figure sits at the top of Usage on web, desktop and phone, for the owner only. One shared function turns the host's figure into words: the read share, cost per turn, turns, fresh starts with their reasons in plain words, and what keeping the cache warm cost. A missing figure reads "not available", an unknown reason counts as "other". People-change: The owner sees two lines on the Usage page: how much of Kin's input came from the cache today and yesterday, what a turn cost, and why sessions started fresh. Co-Authored-By: Claude Opus 5.5 --- .../src/features/chats/state/kinClient.ts | 1 + .../src/features/usage/UsageKinCacheLine.tsx | 87 ++++++++++++ .../src/features/usage/UsageRouteScreen.tsx | 10 +- .../components/usage/UsageKinCacheLine.tsx | 85 ++++++++++++ apps/web/src/components/usage/UsagePage.tsx | 4 + apps/web/src/kin/kinClient.ts | 1 + docs/user/usage.md | 5 + .../src/kin/kinCacheDaily.test.ts | 126 ++++++++++++++++++ .../client-runtime/src/kin/kinCacheDaily.ts | 119 +++++++++++++++++ packages/client-runtime/src/kin/kinClient.ts | 29 +++- 10 files changed, 463 insertions(+), 4 deletions(-) create mode 100644 apps/mobile/src/features/usage/UsageKinCacheLine.tsx create mode 100644 apps/web/src/components/usage/UsageKinCacheLine.tsx create mode 100644 packages/client-runtime/src/kin/kinCacheDaily.test.ts create mode 100644 packages/client-runtime/src/kin/kinCacheDaily.ts diff --git a/apps/mobile/src/features/chats/state/kinClient.ts b/apps/mobile/src/features/chats/state/kinClient.ts index b724ef3d6578..99b0aca37c70 100644 --- a/apps/mobile/src/features/chats/state/kinClient.ts +++ b/apps/mobile/src/features/chats/state/kinClient.ts @@ -118,6 +118,7 @@ export const refreshKinAccessMe = kin.refreshAccessMe; export const refreshKinAgents = kin.refreshKinAgents; export const refreshKinBriefs = kin.refreshKinBriefs; export const refreshKinHost = kin.refreshKinHost; +export const refreshKinCacheDays = kin.refreshKinCacheDays; const approvalRead = createKinRpcCommand(connectionAtomRuntime, { label: "kin:approval:read", diff --git a/apps/mobile/src/features/usage/UsageKinCacheLine.tsx b/apps/mobile/src/features/usage/UsageKinCacheLine.tsx new file mode 100644 index 000000000000..07ebea23a331 --- /dev/null +++ b/apps/mobile/src/features/usage/UsageKinCacheLine.tsx @@ -0,0 +1,87 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + KIN_CACHE_DAILY_COPY, + kinCacheDayLine, + kinCacheLabel, +} from "@t3tools/client-runtime/kin/kinCacheDaily"; +import type { EnvironmentId } from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { AsyncResult } from "effect/reactivity"; +import { View } from "react-native"; + +import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import { kinClient, refreshKinCacheDays } from "../chats/state/kinClient"; + +const LINE = "text-sm leading-5 text-foreground-muted"; + +/** Kin's cache line for each selected host whose owner reads it here; nothing for anyone else. */ +export function UsageKinCacheLines(props: { + readonly environments: readonly { + readonly environmentId: EnvironmentId; + readonly label: string; + }[]; +}) { + return props.environments.map((environment) => ( + 1 ? environment.label : null} + /> + )); +} + +function KinCacheGate(props: { + readonly environmentId: EnvironmentId; + readonly label: string | null; +}) { + const allowed = useAtomValue(kinClient.cacheDaily.permissionAtom(props.environmentId)); + return allowed ? : null; +} + +function DayLine(props: { readonly label: string; readonly body: string }) { + return ( + + {props.label}: {props.body} + + ); +} + +function KinCacheLines(props: { + readonly environmentId: EnvironmentId; + readonly label: string | null; +}) { + const result = useAtomValue( + kinClient.cacheDays({ environmentId: props.environmentId, input: {} }), + ); + const days = Option.getOrNull(AsyncResult.value(result)); + const failed = days === null && AsyncResult.isFailure(result); + return ( + + {props.label === null ? null : ( + {props.label} + )} + {days !== null ? ( + [kinCacheDayLine("today", days.day), kinCacheDayLine("yesterday", days.before)].map( + (line) => , + ) + ) : failed ? ( + + {KIN_CACHE_DAILY_COPY.failed} +