diff --git a/apps/server/src/kin/chat/KinChatService.test.ts b/apps/server/src/kin/chat/KinChatService.test.ts index 40d859afd190f..e35248d3d71e0 100644 --- a/apps/server/src/kin/chat/KinChatService.test.ts +++ b/apps/server/src/kin/chat/KinChatService.test.ts @@ -1,7 +1,7 @@ import { environment } from "./TaskCard.testkit.ts"; import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts"; import { CommandId } from "@t3tools/contracts"; -import { startWakeupRun, authorityLayer } from "./WakeupAuthority.testkit.ts"; +import { startWakeupRun, authorityLayer, startAgentWakeup } from "./WakeupAuthority.testkit.ts"; import { assert, describe, it } from "@effect/vitest"; import { AuthSessionId, @@ -88,7 +88,7 @@ const state = Schema.decodeSync(KinTaskCardState)({ lastError: null, updatedAt: timestamp, }); -const seed = Effect.gen(function* () { +const seed = Effect.fn("test.seed")(function* (notice = false) { const repo = yield* Repository.KinChatRepository; const service = yield* Service.KinChatService; const identity = yield* Identity.KinIdentity.pipe(Effect.provide(identityLayer)); @@ -107,10 +107,19 @@ const seed = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* sql`INSERT INTO kin_leads (agent_id, org_id, name, level_since, models_json, worker_projects_json, owner_chat_id) VALUES (${agentId}, ${person.orgId}, 'Lead', 0, '{}', '[]', ${chat.chatId})`; - yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, thread_id, model, started_at, status, event_ids) - VALUES ('service-wakeup', ${person.orgId}, ${agentId}, ${threadId}, 'test', 0, 'running', '[]')`; - const run = yield* startWakeupRun(threadId, "service-wakeup"); - yield* sql`UPDATE kin_wakeups SET run_id = ${run.id} WHERE wakeup_id = 'service-wakeup'`; + const prompt = notice + ? undefined + : yield* service.send(person, { + chatId: chat.chatId, + body: "Owner question", + clientMessageId: "seed-human", + }); + yield* startAgentWakeup({ + orgId: person.orgId, + agentId, + threadId, + ...(prompt === undefined ? {} : { message: prompt }), + }); yield* startWakeupRun(state.threadId!, "worker"); const agent = yield* identity.resolveAgent(caller); return { repo, service, identity, person, agent, chat }; @@ -121,7 +130,7 @@ describe("KinChatService", () => { "creates exactly two members, derives authors from identity, and deduplicates sends", () => Effect.gen(function* () { - const { repo, service, person, agent, chat } = yield* seed; + const { repo, service, person, agent, chat } = yield* seed(); const retries = yield* Effect.all( Array.from({ length: 5 }, () => service.createDirect(person, { orgId: person.orgId, agentId }), @@ -162,7 +171,7 @@ describe("KinChatService", () => { chatId: chat.chatId, clientMessageId: "first", body: "Evidence", - intent: "evidence", + intent: "answer", }); assert.deepStrictEqual(posted.author, { _tag: "agent", @@ -177,13 +186,13 @@ describe("KinChatService", () => { chatId: chat.chatId, clientMessageId: "first", body: "Evidence", - intent: "answer", + intent: "evidence", }), ), { reason: "not_allowed" }, ); assert.strictEqual(posted.authorRole, "member"); - assert.strictEqual(posted.seq, 2); + assert.strictEqual(posted.seq, 3); const resumed = decodeThreadId("new-thread"); yield* repo.registerAgentThread({ orgId: agent.orgId, @@ -213,7 +222,7 @@ describe("KinChatService", () => { ]) assert.include(yield* Effect.flip(operation), { reason: "invalid_state" }); assert.deepStrictEqual( - (yield* service.history(person, { chatId: chat.chatId, beforeSeq: 3, limit: 1 })) + (yield* service.history(person, { chatId: chat.chatId, beforeSeq: 4, limit: 1 })) .messages, [posted], ); @@ -245,7 +254,7 @@ describe("KinChatService", () => { .pipe(Effect.flip), { reason: "not_allowed" }, ); - yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE wakeup_id = 'service-wakeup'`; + yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE org_id = ${person.orgId} AND thread_id = ${threadId}`; assert.include( yield* service .upsertWidget(agent, { @@ -263,7 +272,7 @@ describe("KinChatService", () => { it.effect("hides foreign org ids on every method and checks active membership and roles", () => Effect.gen(function* () { - const { repo, service, person, agent, chat } = yield* seed; + const { repo, service, person, agent, chat } = yield* seed(); const widget = yield* service.createTaskCard({ orgId: person.orgId, chatId: chat.chatId, @@ -427,7 +436,7 @@ describe("KinChatService", () => { it.effect("creates trusted cards idempotently and enforces ownership and server fields", () => Effect.gen(function* () { - const { repo, service, person, agent, chat } = yield* seed; + const { repo, service, person, agent, chat } = yield* seed(); for (const caller of [agent, person]) assert.include( yield* service @@ -460,7 +469,7 @@ describe("KinChatService", () => { ); assert.strictEqual( (yield* repo.history({ ...chat, beforeSeq: 99, limit: 100 })).messages.length, - 1, + 2, ); const anchor = Option.getOrThrow(yield* repo.getMessage(widget)); assert.include(anchor.author, { _tag: "agent", agentId: agent.agentId }); @@ -487,7 +496,7 @@ describe("KinChatService", () => { yield* identity.registerAgentThread({ ...person, agentId: otherId, threadId: otherThread }); const sql = yield* SqlClient.SqlClient; yield* sql`INSERT INTO kin_leads (agent_id, org_id, name, level_since, models_json, worker_projects_json, owner_chat_id) VALUES (${otherId}, ${person.orgId}, 'Other', 0, '{}', '[]', ${chat.chatId})`; - yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE wakeup_id = 'service-wakeup'`; + yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE org_id = ${person.orgId} AND thread_id = ${threadId}`; const otherRun = yield* startWakeupRun(otherThread, "other-wakeup"); yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, thread_id, run_id, model, started_at, status, event_ids) VALUES ('other-wakeup', ${person.orgId}, ${otherId}, ${otherThread}, ${otherRun.id}, 'test', 0, 'running', '[]')`; const other = yield* identity.resolveAgent({ @@ -517,7 +526,7 @@ describe("KinChatService", () => { { reason: "not_allowed" }, ); yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE wakeup_id = 'other-wakeup'`; - yield* sql`UPDATE kin_wakeups SET status = 'running' WHERE wakeup_id = 'service-wakeup'`; + yield* sql`UPDATE kin_wakeups SET status = 'running' WHERE org_id = ${person.orgId} AND thread_id = ${threadId}`; const updated = yield* service.upsertWidget(agent, { chatId: chat.chatId, widgetId: widget.widgetId, @@ -599,7 +608,7 @@ describe("KinChatService", () => { .pipe(Effect.flip), { reason: "widget_changed" }, ); - yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE wakeup_id = 'service-wakeup'`; + yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE org_id = ${person.orgId} AND thread_id = ${threadId}`; const serverThread = ThreadId.make("server-only"); yield* startWakeupRun(serverThread, "server-only"); assert.strictEqual( @@ -613,7 +622,7 @@ describe("KinChatService", () => { "publishes question waiting and reply resolution, rolls back atomically, and keeps read state monotonic", () => Effect.gen(function* () { - const { repo, service, person, agent, chat } = yield* seed; + const { repo, service, person, agent, chat } = yield* seed(true); const hub = yield* Hub.KinChatHub; const events = yield* Stream.toQueue(yield* hub.subscribeForViewer(person), { capacity: "unbounded", @@ -776,7 +785,7 @@ describe("KinChatService", () => { ); it.effect("filters every hub event against current viewer membership at delivery", () => Effect.gen(function* () { - const { repo, service, person, agent, chat } = yield* seed; + const { repo, service, person, agent, chat } = yield* seed(true); const hub = yield* Hub.KinChatHub; const viewer = yield* hub.subscribeForViewer(person); const other = yield* repo.createChat({ @@ -802,7 +811,7 @@ describe("KinChatService", () => { chatId: other.chatId, body: "Private", clientMessageId: "private", - intent: "answer", + intent: "evidence", }); const widget = yield* service.createTaskCard({ orgId: person.orgId, @@ -900,7 +909,7 @@ describe("KinChatService", () => { "requires an owner to remove members and publishes cancelled waiting only after commit", () => Effect.gen(function* () { - const { repo, service, person, chat } = yield* seed; + const { repo, service, person, chat } = yield* seed(); const hub = yield* Hub.KinChatHub; const sql = yield* SqlClient.SqlClient; const other = { ...person, personId: KinPersonId.make("other-person") }; diff --git a/apps/server/src/kin/chat/KinChatService.ts b/apps/server/src/kin/chat/KinChatService.ts index d0ecddd81a4c0..a1da120e5de07 100644 --- a/apps/server/src/kin/chat/KinChatService.ts +++ b/apps/server/src/kin/chat/KinChatService.ts @@ -1,3 +1,4 @@ +import * as Floor from "../floor/KinFloor.ts"; import { ServerEnvironment } from "../../environment/ServerEnvironment.ts"; import { OrchestratorV2 } from "../../orchestration-v2/Orchestrator.ts"; import * as TaskCard from "../widgets/taskCard.ts"; @@ -55,7 +56,10 @@ type Viewers = ReadonlyArray; type Caller = Identity | Viewers; type PersonCaller = PersonIdentity | Viewers; type ServiceError = Repository.RepositoryError; -type SendInput = KinMessagesSendInput & { readonly intent?: KinAgentIntent }; +type SendInput = KinMessagesSendInput & { + readonly intent?: KinAgentIntent; + readonly floorGrant?: string | undefined; +}; type WidgetUpsertInput = { readonly chatId: KinChatId; readonly widgetId?: KinWidgetId | undefined; @@ -190,6 +194,7 @@ const requireRecord = Effect.fn("KinChatService.requireRecord")(function* invalidState)); - return yield* post(identity, member, { + const existing = yield* repo.findClientMessage({ + orgId: identity.orgId, + chatId: request.chatId, + memberId: member.memberId, + kind: "send", + clientId: request.clientMessageId, + }); + const chat = yield* requireRecord(repo.getChat(member)); + const authorization = + identity._tag === "agent" && Option.isNone(existing) + ? yield* floor.authorize(identity, chat, intent ?? "answer", input.floorGrant) + : { runId: null }; + const message = yield* post(identity, member, { ...request, kind: "text", intent, + floorRunId: authorization.runId, mentions: request.mentions ?? [], replyTo: request.replyTo ?? null, widgetId: null, clientId: { kind: "send", id: request.clientMessageId }, }); + if (Option.isNone(existing) && identity._tag === "agent" && authorization.runId === null) + yield* floor.recordNotice(identity, message); + return message; }, transaction), read: Effect.fn("KinChatService.read")(function* (identity, input) { const request = yield* decodeRead(input).pipe(Effect.mapError(() => invalidState)); @@ -1130,4 +1155,7 @@ const make = Effect.gen(function* () { }); }); -export const layer = Layer.effect(KinChatService, make).pipe(Layer.provideMerge(TaskCard.layer)); +export const layer = Layer.effect(KinChatService, make).pipe( + Layer.provideMerge(TaskCard.layer), + Layer.provide(Floor.layer), +); diff --git a/apps/server/src/kin/chat/WakeupAuthority.testkit.ts b/apps/server/src/kin/chat/WakeupAuthority.testkit.ts index f700879c5b0c7..f9113e8b328d4 100644 --- a/apps/server/src/kin/chat/WakeupAuthority.testkit.ts +++ b/apps/server/src/kin/chat/WakeupAuthority.testkit.ts @@ -1,11 +1,22 @@ import { CommandId, + KinOrgId, + KinEventId, + KinWakeupId, + type KinEvent, + type KinMessage, + type KinAgentId, MessageId, ProjectId, ProviderDriverKind, ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as TestClock from "effect/testing/TestClock"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as KinEventQueue from "../lead/KinEventQueue.ts"; +import * as SqlClient from "effect/sql/SqlClient"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Orchestrator from "../../orchestration-v2/Orchestrator.ts"; @@ -72,3 +83,62 @@ export const startWakeupRun = Effect.fn("test.startWakeupRun")(function* ( }); return (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!; }); + +export const startAgentWakeup = Effect.fn("test.startAgentWakeup")(function* (input: { + readonly orgId: KinOrgId; + readonly agentId: KinAgentId; + readonly threadId: ThreadId; + readonly message?: KinMessage; +}) { + const sql = yield* SqlClient.SqlClient; + const queue = yield* KinEventQueue.KinEventQueue; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const previous = yield* sql<{ + wakeup_id: string; + run_id: string | null; + }>`SELECT wakeup_id, run_id FROM kin_wakeups + WHERE org_id = ${input.orgId} AND status = 'running' ORDER BY wakeup_id`; + for (const wakeup of previous) { + yield* queue.finish({ + orgId: input.orgId, + wakeupId: KinWakeupId.make(wakeup.wakeup_id), + status: "completed", + }); + const projection = yield* orchestrator.getThreadProjection(input.threadId); + const run = projection.runs.find((run) => run.id === wakeup.run_id); + if (run !== undefined) + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make(`interrupt:${wakeup.wakeup_id}`), + threadId: input.threadId, + runId: run.id, + }); + } + const wakeupId = KinWakeupId.make(SecureRandom.uuidV4Unsafe()); + const base = { + orgId: input.orgId, + agentId: input.agentId, + eventId: KinEventId.make(`event:${wakeupId}`), + receivedAt: yield* DateTime.now, + dedupeKey: null, + }; + const event: KinEvent = + input.message === undefined + ? { ...base, _tag: "routine", provenance: { _tag: "system" }, routine: "morning_brief" } + : { + ...base, + _tag: "chat.message", + provenance: input.message.author, + chatId: input.message.chatId, + messageId: input.message.messageId, + }; + yield* queue.enqueue(event); + yield* TestClock.adjust(input.message === undefined ? 20_000 : 2_000); + yield* Effect.scoped( + queue.claim({ orgId: input.orgId, agentId: input.agentId, wakeupId, model: "test" }), + ); + const run = yield* startWakeupRun(input.threadId, wakeupId); + yield* sql`UPDATE kin_wakeups SET thread_id = ${input.threadId}, run_id = ${run.id} + WHERE org_id = ${input.orgId} AND wakeup_id = ${wakeupId}`; + return wakeupId; +}, Effect.provide(KinEventQueue.layer)); diff --git a/apps/server/src/kin/floor/FloorManager.test.ts b/apps/server/src/kin/floor/FloorManager.test.ts new file mode 100644 index 0000000000000..7d00d0e00820f --- /dev/null +++ b/apps/server/src/kin/floor/FloorManager.test.ts @@ -0,0 +1,118 @@ +import { assert, it } from "@effect/vitest"; +import { KinAgentId, KinChatId, KinMessageId } from "@t3tools/contracts"; +import { + decideFloor, + FLOOR_BID_WINDOW_MS, + noticeIntentAllowed, + replyIntentAllowed, + type FloorRun, +} from "./FloorManager.ts"; + +const lead = KinAgentId.make("lead"); +const qa = KinAgentId.make("qa"); +const release = KinAgentId.make("release"); +const run: FloorRun = { + runId: "run", + chatId: KinChatId.make("chat"), + openedBy: KinMessageId.make("human"), + mentionQueue: [], + agentTurns: 0, + lastSpeaker: null, + spoken: [], + grant: null, + state: "open", +}; +const bids = [ + { agentId: lead, role: "lead", reason: "answer", intent: "answer", at: 10 }, + { agentId: qa, role: "qa", reason: "tests", intent: "evidence", at: 20 }, + { agentId: release, role: "release", reason: "release", intent: "decision", at: 30 }, +] as const; +it.each([ + { + name: "mentions precede bids", + state: { mentionQueue: [release, qa] }, + text: "test", + now: 0, + expected: { _tag: "grant", agentId: release }, + }, + { + name: "last speaker mention skipped", + state: { mentionQueue: [lead, qa], lastSpeaker: lead }, + expected: { _tag: "grant", agentId: qa }, + }, + { name: "wait for bids", now: 1_999, expected: { _tag: "wait" } }, + { name: "plain question prefers chat lead", expected: { _tag: "grant", agentId: lead } }, + { + name: "test words prefer QA", + text: "testing", + expected: { _tag: "grant", agentId: qa }, + }, + ...["deploy", "deployment", "release", "deploying", "released"].map( + (text) => + ({ + name: `${text} prefers release`, + text, + expected: { _tag: "grant", agentId: release }, + }) as const, + ), + { + name: "role ties use earliest bid", + text: "test", + bids: [{ ...bids[1], agentId: release, at: 25 }, bids[1]], + expected: { _tag: "grant", agentId: qa }, + }, + { + name: "last speaker bid skipped", + state: { lastSpeaker: lead }, + expected: { _tag: "grant", agentId: qa }, + }, + { + name: "six turns closes before mentions", + state: { agentTurns: 6, mentionQueue: [qa] }, + expected: { _tag: "close", reason: "turn_budget" }, + }, + { + name: "answer refused after first turn", + state: { agentTurns: 1 }, + bids: [bids[0]], + expected: { _tag: "close", reason: "nothing_to_add" }, + }, + { + name: "question refused after first turn", + state: { agentTurns: 1 }, + bids: [{ ...bids[0], intent: "question" }], + expected: { _tag: "close", reason: "nothing_to_add" }, + }, + { name: "no bids closes", bids: [], expected: { _tag: "close", reason: "no_bids" } }, + { + name: "late bids cannot win", + bids: [{ ...bids[0], at: 2_001 }], + expected: { _tag: "close", reason: "nothing_to_add" }, + }, +] as const)("$name", (row) => { + assert.deepStrictEqual( + decideFloor({ + run: { ...run, ...("state" in row ? row.state : {}) }, + bids: "bids" in row ? row.bids : bids, + text: "text" in row ? row.text : "Question?", + leadAgentId: lead, + bidWindowOpenedAt: 0, + now: "now" in row ? row.now : FLOOR_BID_WINDOW_MS, + }), + row.expected, + ); +}); +it.each(["answer", "question", "evidence", "objection", "decision"] as const)( + "reply and notice intents: %s", + (intent) => { + assert.isTrue(replyIntentAllowed(0, intent)); + assert.strictEqual( + replyIntentAllowed(1, intent), + ["evidence", "objection", "decision"].includes(intent), + ); + assert.strictEqual( + noticeIntentAllowed(intent), + ["evidence", "decision", "question"].includes(intent), + ); + }, +); diff --git a/apps/server/src/kin/floor/FloorManager.ts b/apps/server/src/kin/floor/FloorManager.ts new file mode 100644 index 0000000000000..b174fe5a2d4df --- /dev/null +++ b/apps/server/src/kin/floor/FloorManager.ts @@ -0,0 +1,79 @@ +import type { + KinAgentId, + KinAgentIntent, + KinAgentRole, + KinChatId, + KinMessageId, +} from "@t3tools/contracts"; + +export const FLOOR_MAX_AGENT_TURNS = 6; +export const FLOOR_BID_WINDOW_MS = 2_000; +export const FLOOR_GRANT_TTL_MS = 5 * 60_000; + +export interface FloorRun { + readonly runId: string; + readonly chatId: KinChatId; + readonly openedBy: KinMessageId; + readonly mentionQueue: ReadonlyArray; + readonly agentTurns: number; + readonly lastSpeaker: KinAgentId | null; + readonly spoken: ReadonlyArray; + readonly grant: { + readonly agentId: KinAgentId; + readonly token: string; + readonly expiresAt: number; + } | null; + readonly state: "open" | "closed"; +} +interface FloorBid { + readonly agentId: KinAgentId; + readonly role: KinAgentRole; + readonly reason: string; + readonly intent: KinAgentIntent; + readonly at: number; +} +type FloorDecision = + | { readonly _tag: "grant"; readonly agentId: KinAgentId } + | { readonly _tag: "wait" } + | { readonly _tag: "close"; readonly reason: "turn_budget" | "no_bids" | "nothing_to_add" }; + +export const replyIntentAllowed = (turns: number, intent: KinAgentIntent) => + turns === 0 || intent === "evidence" || intent === "objection" || intent === "decision"; +export const noticeIntentAllowed = (intent: KinAgentIntent) => + intent === "evidence" || intent === "decision" || intent === "question"; + +export function decideFloor(input: { + readonly run: FloorRun; + readonly bids: ReadonlyArray; + readonly text: string; + readonly leadAgentId: KinAgentId; + readonly bidWindowOpenedAt: number; + readonly now: number; +}): FloorDecision { + const { run } = input; + if (run.agentTurns >= FLOOR_MAX_AGENT_TURNS) return { _tag: "close", reason: "turn_budget" }; + if (run.state === "closed") return { _tag: "close", reason: "nothing_to_add" }; + const mentioned = run.mentionQueue.find((agent) => agent !== run.lastSpeaker); + if (mentioned !== undefined) return { _tag: "grant", agentId: mentioned }; + if (input.now < input.bidWindowOpenedAt + FLOOR_BID_WINDOW_MS) return { _tag: "wait" }; + const role = /\b(test|tests|testing|bug|bugs)\b/i.test(input.text) + ? "qa" + : /\b(deploy|deploying|deployment|release|released)\b/i.test(input.text) + ? "release" + : "lead"; + const score = (bid: FloorBid) => + role === "lead" ? Number(bid.agentId === input.leadAgentId) : Number(bid.role === role); + const bids = input.bids.filter( + (bid) => + bid.at >= input.bidWindowOpenedAt && + bid.at <= input.bidWindowOpenedAt + FLOOR_BID_WINDOW_MS && + bid.at <= input.now && + bid.agentId !== run.lastSpeaker && + replyIntentAllowed(run.agentTurns, bid.intent), + ); + bids.sort((a, b) => score(b) - score(a) || a.at - b.at || a.agentId.localeCompare(b.agentId)); + const first = bids[0]; + return first === undefined + ? { _tag: "close", reason: input.bids.length === 0 ? "no_bids" : "nothing_to_add" } + : { _tag: "grant", agentId: first.agentId }; +} diff --git a/apps/server/src/kin/floor/KinFloor.ts b/apps/server/src/kin/floor/KinFloor.ts new file mode 100644 index 0000000000000..e895bb0cde605 --- /dev/null +++ b/apps/server/src/kin/floor/KinFloor.ts @@ -0,0 +1,263 @@ +import { + KinChatError, + KinAgentId, + KinAgentRole, + KinMemberId, + KinMessageId, + type KinAgentIntent, + type KinChat, + type KinMessage, + type KinOrgId, + type KinChatId, +} from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import type { SqlError } from "effect/sql/SqlError"; +import * as SqlClient from "effect/sql/SqlClient"; +import { toPersistenceSqlError, type PersistenceSqlError } from "../../persistence/Errors.ts"; +import type { AgentIdentity } from "../chat/KinIdentity.ts"; +import { + decideFloor, + FLOOR_GRANT_TTL_MS, + FLOOR_MAX_AGENT_TURNS, + noticeIntentAllowed, + replyIntentAllowed, +} from "./FloorManager.ts"; + +const encodeAgents = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(KinAgentId))); +const decodeMembers = Schema.decodeUnknownEffect( + Schema.Array( + Schema.Struct({ + agent_id: KinAgentId, + member_id: KinMemberId, + role: KinAgentRole, + }), + ), +); +const decodeRun = Schema.decodeUnknownEffect( + Schema.Struct({ + run_id: Schema.String, + agent_turns: Schema.Int, + last_speaker: Schema.NullOr(KinAgentId), + state: Schema.Literals(["open", "closed"]), + opened_by: KinMessageId, + mention_queue: Schema.fromJsonString(Schema.Array(KinAgentId)), + spoken: Schema.fromJsonString(Schema.Array(KinAgentId)), + }), +); +const invalidIntent = new KinChatError({ + reason: "invalid_state", + message: "The intent or grant is invalid for this wake-up.", +}); +const isKinChatError = Schema.is(KinChatError); +const notGranted = new KinChatError({ + reason: "floor_not_granted", + message: "The floor is not granted.", +}); +type Scope = { readonly orgId: KinOrgId; readonly chatId: KinChatId }; +type Authorization = { readonly runId: string | null }; +export class KinFloor extends Context.Service< + KinFloor, + { + readonly open: (message: KinMessage, chat: KinChat) => Effect.Effect; + readonly authorize: ( + identity: AgentIdentity, + chat: KinChat, + intent: KinAgentIntent, + token?: string, + ) => Effect.Effect; + readonly recordNotice: ( + identity: AgentIdentity, + message: KinMessage, + ) => Effect.Effect; + } +>()("t3/kin/floor/KinFloor") {} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const issue = Effect.fn("KinFloor.issue")(function* ( + scope: Scope & { readonly runId: string; readonly agentId: KinAgentId }, + now: number, + ) { + yield* sql`INSERT INTO kin_floor_grants (org_id, token, run_id, chat_id, agent_id, expires_at) + SELECT r.org_id, ${SecureRandom.uuidV4Unsafe()}, r.run_id, r.chat_id, a.agent_id, ${now + FLOOR_GRANT_TTL_MS} + FROM kin_floor_runs r JOIN kin_chat_members m ON m.org_id = r.org_id AND m.chat_id = r.chat_id + JOIN kin_agents a ON a.org_id = m.org_id AND a.agent_id = m.agent_id + WHERE r.org_id = ${scope.orgId} AND r.chat_id = ${scope.chatId} AND r.run_id = ${scope.runId} + AND r.state = 'open' AND a.agent_id = ${scope.agentId} AND a.retired_at IS NULL AND m.left_at IS NULL + ORDER BY m.member_id LIMIT 1 + ON CONFLICT DO NOTHING RETURNING token`; + }); + const close = Effect.fn("KinFloor.close")(function* (scope: Scope) { + yield* sql`UPDATE kin_floor_runs SET state = 'closed' WHERE org_id = ${scope.orgId} AND chat_id = ${scope.chatId} AND state = 'open'`; + yield* sql`UPDATE kin_floor_grants SET expires_at = MIN(expires_at, ${yield* Clock.currentTimeMillis}) + WHERE org_id = ${scope.orgId} AND chat_id = ${scope.chatId} AND consumed_at IS NULL`; + }); + const open = Effect.fn("KinFloor.open")( + function* (message: KinMessage, chat: KinChat) { + if (message.author._tag !== "human" || message.status !== "posted") return; + const now = yield* Clock.currentTimeMillis; + yield* close(message); + const agents = yield* sql` + SELECT a.agent_id, m.member_id, a.role FROM kin_chat_members m + JOIN kin_agents a ON a.org_id = m.org_id AND a.agent_id = m.agent_id + WHERE m.org_id = ${message.orgId} AND m.chat_id = ${message.chatId} + AND m.left_at IS NULL AND a.retired_at IS NULL + ORDER BY CASE a.role WHEN 'lead' THEN 0 ELSE 1 END, m.joined_at, a.agent_id`.pipe( + Effect.flatMap(decodeMembers), + ); + const lead = agents[0]; + const mentions = message.mentions.flatMap((id) => + agents.filter((agent) => agent.member_id === id).map((agent) => agent.agent_id), + ); + const mentionQueue = + chat.kind === "direct" && lead !== undefined ? [lead.agent_id] : mentions; + const runId = SecureRandom.uuidV4Unsafe(); + yield* sql`INSERT INTO kin_floor_runs (org_id, run_id, chat_id, opened_by, mention_queue, state, opened_at) + VALUES (${message.orgId}, ${runId}, ${message.chatId}, ${message.messageId}, ${yield* encodeAgents(mentionQueue)}, 'open', ${now}) + ON CONFLICT DO NOTHING RETURNING run_id`; + if (lead === undefined) return; + const decision = decideFloor({ + run: { + runId, + chatId: chat.chatId, + openedBy: message.messageId, + mentionQueue, + agentTurns: 0, + lastSpeaker: null, + spoken: [], + grant: null, + state: "open", + }, + bids: [], + text: message.body, + leadAgentId: lead.agent_id, + bidWindowOpenedAt: now, + now, + }); + // Group tokens remain internal until phase-2 wake-up delivery. + if (decision._tag !== "grant") return; + yield* issue({ ...message, runId, agentId: decision.agentId }, now); + }, + Effect.mapError(toPersistenceSqlError("KinFloor.open")), + ); + + const authorize = Effect.fn("KinFloor.authorize")( + function* ( + identity: AgentIdentity, + chat: KinChat, + intent: KinAgentIntent, + token?: string, + ): Effect.fn.Return { + const now = yield* Clock.currentTimeMillis; + // Notice authority comes from the running wake-up's stored events, never tool input. + const wakeups = yield* sql<{ + notices: number; + replies: number; + total: number; + expected: number; + }>` + SELECT COUNT(e.event_id) AS total, json_array_length(w.event_ids) AS expected, + COALESCE(SUM(CASE WHEN e.tag IN ('routine', 'github', 'deferral.due', 'worker.report', 'watchdog', 'action.resolved', 'resume') THEN 1 ELSE 0 END), 0) AS notices, + COALESCE(SUM(CASE WHEN e.tag IN ('chat.message', 'widget.action') THEN 1 ELSE 0 END), 0) AS replies + FROM kin_wakeups w JOIN kin_events e ON e.org_id = w.org_id AND e.agent_id = w.agent_id + AND e.wakeup_id = w.wakeup_id AND e.event_id IN (SELECT value FROM json_each(w.event_ids)) + WHERE w.org_id = ${identity.orgId} AND w.agent_id = ${identity.agentId} + AND w.thread_id = ${identity.threadId} AND w.status = 'running' + GROUP BY w.wakeup_id, w.event_ids + ORDER BY w.started_at, w.wakeup_id`; + const wakeup = wakeups[0]; + if ( + wakeup !== undefined && + wakeup.total > 0 && + wakeup.expected === wakeup.total && + wakeup.notices === wakeup.total && + wakeup.replies === 0 + ) { + if (!noticeIntentAllowed(intent) || token !== undefined) return yield* invalidIntent; + const recent = yield* sql<{ message_id: string }>`SELECT message_id FROM kin_floor_notices + WHERE org_id = ${identity.orgId} AND chat_id = ${chat.chatId} AND agent_id = ${identity.agentId} + AND posted_at > ${now - 3_600_000} ORDER BY posted_at, message_id LIMIT 10`; + if (recent.length >= 10) + return yield* new KinChatError({ + reason: "limit", + message: "Agent notice limit reached.", + }); + return { runId: null }; + } + const runs = yield* sql` + SELECT run_id, agent_turns, last_speaker, state, opened_by, mention_queue, spoken FROM kin_floor_runs + WHERE org_id = ${identity.orgId} AND chat_id = ${chat.chatId} + ORDER BY opened_at DESC, rowid DESC LIMIT 1`; + const run = runs[0] === undefined ? undefined : yield* decodeRun(runs[0]); + if (run?.agent_turns === FLOOR_MAX_AGENT_TURNS || run?.state === "closed") + return yield* new KinChatError({ reason: "floor_closed", message: "The floor is closed." }); + if (run === undefined) return yield* notGranted; + if (!replyIntentAllowed(run.agent_turns, intent)) return yield* invalidIntent; + if (run.last_speaker === identity.agentId) return yield* notGranted; + if (chat.kind !== "direct" && token === undefined) return yield* notGranted; + const grants = yield* sql<{ token: string }>`SELECT token FROM kin_floor_grants + WHERE org_id = ${identity.orgId} AND chat_id = ${chat.chatId} AND agent_id = ${identity.agentId} + AND run_id = ${run.run_id} AND consumed_at IS NULL AND expires_at > ${now} + AND (${token ?? null} IS NULL OR token = ${token ?? null}) + ORDER BY expires_at, token LIMIT 1`; + const grant = grants[0]; + if (grant === undefined) return yield* notGranted; + const consumed = yield* sql`UPDATE kin_floor_grants SET consumed_at = ${now} + WHERE org_id = ${identity.orgId} AND chat_id = ${chat.chatId} AND agent_id = ${identity.agentId} + AND run_id = ${run.run_id} AND token = ${grant.token} AND consumed_at IS NULL AND expires_at > ${now} + RETURNING token`; + if (consumed.length !== 1) return yield* notGranted; + yield* sql`UPDATE kin_floor_runs SET agent_turns = agent_turns + 1, last_speaker = ${identity.agentId}, + spoken = json_insert(spoken, '$[#]', ${identity.agentId}), + mention_queue = (SELECT COALESCE(json_group_array(value), '[]') FROM json_each(mention_queue) WHERE value != ${identity.agentId} ORDER BY key), + state = CASE WHEN agent_turns + 1 >= ${FLOOR_MAX_AGENT_TURNS} THEN 'closed' ELSE 'open' END + WHERE org_id = ${identity.orgId} AND run_id = ${run.run_id}`; + const remaining = run.mention_queue.filter((agent) => agent !== identity.agentId); + // With no bids, only the remaining mentions can win; leadAgentId is unused. + const next = decideFloor({ + run: { + runId: run.run_id, + chatId: chat.chatId, + openedBy: run.opened_by, + mentionQueue: remaining, + agentTurns: run.agent_turns + 1, + lastSpeaker: identity.agentId, + spoken: [...run.spoken, identity.agentId], + grant: null, + state: run.agent_turns + 1 >= FLOOR_MAX_AGENT_TURNS ? "closed" : "open", + }, + bids: [], + text: "", + leadAgentId: identity.agentId, + bidWindowOpenedAt: now, + now, + }); + if (next._tag === "grant") { + yield* issue( + { orgId: identity.orgId, chatId: chat.chatId, runId: run.run_id, agentId: next.agentId }, + now, + ); + } + return { runId: run.run_id }; + }, + Effect.mapError((error) => + isKinChatError(error) ? error : toPersistenceSqlError("KinFloor.authorize")(error), + ), + ); + + const recordNotice = Effect.fn("KinFloor.recordNotice")( + function* (identity: AgentIdentity, message: KinMessage) { + yield* sql`INSERT INTO kin_floor_notices (org_id, message_id, chat_id, agent_id, posted_at) + VALUES (${identity.orgId}, ${message.messageId}, ${message.chatId}, ${identity.agentId}, ${yield* Clock.currentTimeMillis}) + ON CONFLICT DO NOTHING RETURNING message_id`; + }, + Effect.mapError(toPersistenceSqlError("KinFloor.recordNotice")), + ); + return KinFloor.of({ open, authorize, recordNotice }); +}); +export const layer = Layer.effect(KinFloor, make); diff --git a/apps/server/src/kin/mcp/KinChatToolkit.test.ts b/apps/server/src/kin/mcp/KinChatToolkit.test.ts index 7381462d8f4a7..fe1daae9d4361 100644 --- a/apps/server/src/kin/mcp/KinChatToolkit.test.ts +++ b/apps/server/src/kin/mcp/KinChatToolkit.test.ts @@ -1,5 +1,8 @@ import { environment } from "../chat/TaskCard.testkit.ts"; -import { authorityLayer, startWakeupRun } from "../chat/WakeupAuthority.testkit.ts"; +import { authorityLayer, startAgentWakeup } from "../chat/WakeupAuthority.testkit.ts"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as TestClock from "effect/testing/TestClock"; +import { FLOOR_GRANT_TTL_MS } from "../floor/FloorManager.ts"; import * as FileSystem from "effect/FileSystem"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; @@ -8,6 +11,10 @@ import { AuthStandardClientScopes, EnvironmentId, KinAgentId, + KinMessageId, + KinMemberId, + KinOrgId, + KinPersonId, ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; @@ -15,6 +22,7 @@ import * as ConfigProvider from "effect/ConfigProvider"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Result from "effect/Result"; import * as Option from "effect/Option"; import * as SqlClient from "effect/sql/SqlClient"; import { McpSchema, McpServer } from "effect/ai"; @@ -134,7 +142,7 @@ const errorOf = (result: McpSchema.CallToolResult) => { const error: unknown = JSON.parse(text); return error; }; -const seed = Effect.gen(function* () { +const seed = Effect.fn("test.seed")(function* (notice = false) { const kin = yield* Kin.KinServer; const services = Option.getOrThrow(kin.services); const identity = Context.get(services, KinIdentity); @@ -156,9 +164,19 @@ const seed = Effect.gen(function* () { const chat = yield* chatService.createDirect(person, { orgId: person.orgId, agentId }); yield* sql`INSERT INTO kin_leads (agent_id, org_id, name, level_since, models_json, worker_projects_json, owner_chat_id) VALUES (${agentId}, ${person.orgId}, 'Lead', 0, '{}', '[]', ${chat.chatId})`; - const run = yield* startWakeupRun(threadId, "toolkit-wakeup"); - yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, thread_id, run_id, model, started_at, status, event_ids) - VALUES ('toolkit-wakeup', ${person.orgId}, ${agentId}, ${threadId}, ${run.id}, 'test', 0, 'running', '[]')`; + const prompt = notice + ? undefined + : yield* chatService.send(person, { + chatId: chat.chatId, + body: "Owner question", + clientMessageId: "seed-human", + }); + yield* startAgentWakeup({ + orgId: person.orgId, + agentId, + threadId, + ...(prompt === undefined ? {} : { message: prompt }), + }); return { identity, chatService, person, chat, sql }; }); @@ -166,7 +184,7 @@ it.effect( "shares WS identity, stores agent authors, reads roles, and preserves retry identity", () => Effect.gen(function* () { - const { chat, person, chatService, sql } = yield* seed; + const { chat, person, chatService, sql } = yield* seed(); assert.lengthOf(yield* visible.pipe(Effect.provideService(McpInvocationContext, scope)), 3); const registry = yield* McpSessions.McpSessionRegistry; for (const request of [ @@ -197,19 +215,19 @@ it.effect( Effect.provideService(McpInvocationContext, scope), ); const rows = yield* read(agent, { chatId: chat.chatId }); - assert.lengthOf(rows, 1); + assert.lengthOf(rows, 2); const suggestion = yield* chatService.send(person, { chatId: chat.chatId, body: "Private suggestion", clientMessageId: "suggestion", }); yield* sql`UPDATE kin_messages SET status = 'suggested' WHERE message_id = ${suggestion.messageId}`; - assert.deepStrictEqual(yield* read(agent, { chatId: chat.chatId, limit: 1 }), rows); + assert.deepStrictEqual(yield* read(agent, { chatId: chat.chatId, limit: 2 }), rows); assert.deepStrictEqual( - yield* read(agent, { chatId: chat.chatId, afterSeq: rows[0]?.seq ?? 0 }), + yield* read(agent, { chatId: chat.chatId, afterSeq: rows.at(-1)?.seq ?? 0 }), [], ); - assert.include(rows[0]?.author, { + assert.include(rows[1]?.author, { _tag: "agent", agentId, threadId, @@ -257,7 +275,7 @@ it.effect.each(["ordinary", "subagent", "ended", "retired", "muted"] as const)( "refuses %s callers", (mode) => Effect.gen(function* () { - const { chat, identity, person, sql } = yield* seed; + const { chat, identity, person, sql } = yield* seed(); const caller = mode === "ordinary" ? { ...scope, thread: { ...thread, threadId: ThreadId.make("ordinary") } } @@ -314,7 +332,7 @@ it.effect.each(["ordinary", "subagent", "ended", "retired", "muted"] as const)( it.effect("hides foreign chats with the same not_found error", () => Effect.gen(function* () { - const { sql } = yield* seed; + const { sql } = yield* seed(); yield* sql`INSERT INTO kin_orgs VALUES ('foreign', 'Foreign', '1970-01-01T00:00:00.000Z')`; yield* sql`INSERT INTO kin_chats VALUES ('foreign-chat', 'foreign', 'team_group', NULL, NULL, NULL, 0, NULL, '1970-01-01T00:00:00.000Z', NULL)`; for (const chatId of ["missing", "foreign-chat"]) { @@ -354,7 +372,7 @@ it.effect.each([{}, { KIN_ENABLED: false }, { KIN_ENABLED: "maybe" }])( it.effect("admits only active provider agents at /kin/mcp", () => Effect.scoped( Effect.gen(function* () { - const { identity, person, sql } = yield* seed; + const { identity, person, sql } = yield* seed(); const kin = yield* Kin.KinServer; const providerScope = { ...scope, thread }; const authRegistry = Layer.mock(McpSessions.McpSessionRegistry)({ @@ -398,9 +416,9 @@ it.effect("admits only active provider agents at /kin/mcp", () => ); assert.strictEqual((yield* request("missing")).status, 401); assert.strictEqual((yield* request("ordinary")).status, 403); - yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE wakeup_id = 'toolkit-wakeup'`; + yield* sql`UPDATE kin_wakeups SET status = 'completed' WHERE org_id = ${person.orgId} AND thread_id = ${threadId}`; assert.strictEqual((yield* request("agent")).status, 403); - yield* sql`UPDATE kin_wakeups SET status = 'running' WHERE wakeup_id = 'toolkit-wakeup'`; + yield* sql`UPDATE kin_wakeups SET status = 'running' WHERE org_id = ${person.orgId} AND thread_id = ${threadId}`; assert.strictEqual((yield* request("agent")).status, 200); yield* identity.endAgentThread({ orgId: person.orgId, threadId }); assert.strictEqual((yield* request("agent")).status, 403); @@ -415,7 +433,7 @@ it.effect("invalidates credentials when registration changes their endpoint", () const resolve = (issued: typeof ordinary) => registry.resolve(issued.config.authorizationHeader.slice(7)); assert.isDefined(yield* resolve(ordinary)); - const { identity, person } = yield* seed; + const { identity, person } = yield* seed(); assert.isUndefined(yield* resolve(ordinary)); const agent = yield* registry.issue(thread); assert.strictEqual(agent.config.endpoint, "http://127.0.0.1:43123/kin/mcp"); @@ -430,7 +448,7 @@ it.effect("invalidates credentials when registration changes their endpoint", () it.effect.each(["deleted", "archived"] as const)("refuses writes from %s threads", (mode) => Effect.gen(function* () { - const { chat } = yield* seed; + const { chat } = yield* seed(); for (const [name, input] of [ ["kin_chat_post", { chatId: chat.chatId, body: "No", intent: "answer" }], [ @@ -483,3 +501,371 @@ it.effect("keeps trusted persistence, waiting and hub APIs outside the toolkit", assert.notMatch(source, /\.addWaiting\(|\.subscribeForViewer\(/); }).pipe(Effect.provide(NodeServices.layer)), ); + +type FloorPost = Omit[1], "clientMessageId"> & { + readonly clientMessageId?: string; +}; +const sendFloor = Effect.fn("test.sendFloor")(function* (input: FloorPost) { + const { agent, send } = yield* agentServices.pipe( + Effect.provideService(McpInvocationContext, scope), + ); + return yield* send(agent, { + ...input, + clientMessageId: input.clientMessageId ?? SecureRandom.uuidV4Unsafe(), + }).pipe(Effect.result); +}); +const failureOf = (result: Result.Result) => Result.getOrThrow(Result.flip(result)); + +it.effect( + "enforces implicit direct grants atomically, keeps retries, and permits wake-up notices outside runs", + () => + Effect.gen(function* () { + const { chat, person, chatService, sql } = yield* seed(); + const { agent } = yield* agentServices.pipe( + Effect.provideService(McpInvocationContext, scope), + ); + yield* sql`DELETE FROM kin_floor_grants WHERE org_id = ${person.orgId}`; + yield* sql`DELETE FROM kin_floor_runs WHERE org_id = ${person.orgId}`; + const post = { + chatId: chat.chatId, + body: "Answer", + intent: "answer", + clientMessageId: "floor-reply", + } as const; + assert.include(failureOf(yield* sendFloor(post)), { reason: "floor_not_granted" }); + const prompt = { chatId: chat.chatId, body: "Please answer", clientMessageId: "floor-human" }; + const human = yield* chatService.send(person, prompt); + const [grant] = yield* sql<{ + token: string; + run_id: string; + }>`SELECT token, run_id FROM kin_floor_grants WHERE org_id = ${person.orgId} AND chat_id = ${chat.chatId} ORDER BY token`; + assert.isDefined(grant); + assert.include(failureOf(yield* sendFloor({ ...post, floorGrant: "forged" })), { + reason: "floor_not_granted", + }); + assert.include( + failureOf(yield* sendFloor({ ...post, replyTo: KinMessageId.make("foreign-message") })), + { + reason: "not_found", + message: "Kin record not found.", + }, + ); + for (const corrupt of [ + { mention_queue: "not-json" }, + { mention_queue: '[" "]' }, + { last_speaker: " " }, + ]) { + const [before] = yield* sql<{ + mention_queue: string; + }>`SELECT mention_queue FROM kin_floor_runs WHERE run_id = ${grant.run_id}`; + yield* sql`UPDATE kin_floor_runs SET ${sql.update(corrupt)} WHERE run_id = ${grant.run_id}`; + assert.strictEqual(failureOf(yield* sendFloor(post))._tag, "PersistenceSqlError"); + yield* sql`UPDATE kin_floor_runs SET mention_queue = ${before!.mention_queue}, last_speaker = NULL WHERE run_id = ${grant.run_id}`; + } + yield* sql`UPDATE kin_floor_runs SET agent_turns = 1, last_speaker = 'other' WHERE run_id = ${grant.run_id}`; + assert.include(failureOf(yield* sendFloor(post)), { reason: "invalid_state" }); + yield* sql`UPDATE kin_floor_runs SET agent_turns = 0, last_speaker = NULL WHERE run_id = ${grant.run_id}`; + const first = yield* sendFloor(post); + assert.isTrue(Result.isSuccess(first)); + assert.deepStrictEqual(yield* sendFloor(post), first); + assert.include(failureOf(yield* sendFloor({ ...post, body: "Changed" })), { + reason: "not_allowed", + }); + assert.deepStrictEqual(yield* chatService.send(person, prompt), human); + for (const intent of ["answer", "evidence", "question"] as const) { + assert.include( + failureOf( + yield* sendFloor({ + ...post, + intent, + clientMessageId: `second-${intent}`, + floorGrant: grant.token, + }), + ), + { reason: intent === "evidence" ? "floor_not_granted" : "invalid_state" }, + ); + } + const { read } = yield* agentServices.pipe( + Effect.provideService(McpInvocationContext, scope), + ); + assert.strictEqual( + (yield* read(agent, { chatId: chat.chatId })).at(-1)?.floorRunId, + grant.run_id, + ); + yield* startAgentWakeup({ orgId: person.orgId, agentId, threadId }); + for (const invalid of [ + { intent: "answer" as const }, + { intent: "objection" as const }, + { intent: "evidence" as const, floorGrant: grant.token }, + ]) { + assert.include( + failureOf( + yield* sendFloor({ + ...post, + ...invalid, + clientMessageId: `invalid-notice-${invalid.intent}`, + }), + ), + { reason: "invalid_state" }, + ); + } + assert.isFalse( + (yield* sendFloor({ + ...post, + body: "Routine evidence", + intent: "evidence", + clientMessageId: "notice", + }))._tag === "Failure", + ); + assert.isNull((yield* read(agent, { chatId: chat.chatId })).at(-1)?.floorRunId); + assert.deepStrictEqual( + yield* sql`SELECT agent_turns FROM kin_floor_runs WHERE org_id = ${person.orgId} AND run_id = ${grant.run_id} ORDER BY run_id`, + [{ agent_turns: 1 }], + ); + const concurrentHuman = yield* chatService.send(person, { + ...prompt, + clientMessageId: "concurrent-human", + }); + yield* startAgentWakeup({ orgId: person.orgId, agentId, threadId, message: concurrentHuman }); + const concurrent = yield* Effect.forEach( + ["a", "b"], + (key) => + sendFloor({ + ...post, + clientMessageId: `concurrent-${key}`, + intent: "evidence", + }), + { concurrency: "unbounded" }, + ); + assert.strictEqual(concurrent.filter((result) => Result.isSuccess(result)).length, 1); + assert.include(failureOf(concurrent.find((result) => Result.isFailure(result))!), { + reason: "floor_not_granted", + }); + yield* startAgentWakeup({ orgId: person.orgId, agentId, threadId }); + assert.include(failureOf(yield* sendFloor({ ...post, clientMessageId: "notice-answer" })), { + reason: "invalid_state", + }); + }).pipe(Effect.provide(layer)), +); + +it.effect( + "expires and releases grants on time and new human messages, and scopes tokens to chat, org and agent", + () => + Effect.gen(function* () { + const { chat, person, chatService, sql } = yield* seed(); + yield* sql`DELETE FROM kin_floor_grants WHERE org_id = ${person.orgId}`; + yield* sql`DELETE FROM kin_floor_runs WHERE org_id = ${person.orgId}`; + const human = (id: string) => + chatService.send(person, { chatId: chat.chatId, body: "Question", clientMessageId: id }); + yield* human("human-1"); + const [grant] = yield* sql<{ + token: string; + run_id: string; + }>`SELECT token, run_id FROM kin_floor_grants WHERE org_id = ${person.orgId} AND chat_id = ${chat.chatId} ORDER BY token`; + assert.isDefined(grant); + const post = { + chatId: chat.chatId, + body: "Answer", + intent: "answer", + floorGrant: grant.token, + } as const; + yield* TestClock.adjust(FLOOR_GRANT_TTL_MS); + assert.include(failureOf(yield* sendFloor(post)), { reason: "floor_not_granted" }); + yield* human("human-2"); + assert.include(failureOf(yield* sendFloor(post)), { reason: "floor_not_granted" }); + const [fresh] = yield* sql<{ + token: string; + run_id: string; + }>`SELECT token, run_id FROM kin_floor_grants WHERE org_id = ${person.orgId} AND run_id != ${grant.run_id} ORDER BY token`; + assert.isDefined(fresh); + // Corrupt-scope rows simulate otherwise valid server tokens belonging to another principal. + const otherAgent = KinAgentId.make("other-agent"); + yield* sql`INSERT INTO kin_agents (org_id, agent_id, display_name, role, owner_person_id, created_at) + VALUES (${person.orgId}, ${otherAgent}, 'Other', 'qa', ${person.personId}, '1970-01-01T00:00:00.000Z')`; + const other = yield* chatService.createDirect(person, { + orgId: person.orgId, + agentId: otherAgent, + }); + for (const change of ["agent", "chat"] as const) { + yield* sql`UPDATE kin_floor_grants SET agent_id = ${change === "agent" ? otherAgent : agentId}, chat_id = ${change === "chat" ? other.chatId : chat.chatId} + WHERE org_id = ${person.orgId} AND token = ${fresh.token}`; + assert.include(failureOf(yield* sendFloor({ ...post, floorGrant: fresh.token })), { + reason: "floor_not_granted", + }); + } + yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) VALUES ('foreign-org', 'Foreign', '1970-01-01T00:00:00.000Z')`; + yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, created_at) + VALUES ('foreign-person', 'foreign-org', 'foreign', 'Foreign', '1970-01-01T00:00:00.000Z')`; + yield* sql`INSERT INTO kin_agents (org_id, agent_id, display_name, role, owner_person_id, created_at) + VALUES ('foreign-org', 'foreign-agent', 'Foreign', 'lead', 'foreign-person', '1970-01-01T00:00:00.000Z')`; + const foreignPerson = { + _tag: "person", + orgId: KinOrgId.make("foreign-org"), + personId: KinPersonId.make("foreign-person"), + } as const; + const foreignChat = yield* chatService.createDirect(foreignPerson, { + orgId: foreignPerson.orgId, + agentId: KinAgentId.make("foreign-agent"), + }); + yield* chatService.send(foreignPerson, { + chatId: foreignChat.chatId, + body: "Foreign question", + clientMessageId: "foreign-human", + }); + const [foreignGrant] = yield* sql<{ + token: string; + }>`SELECT token FROM kin_floor_grants WHERE org_id = ${foreignPerson.orgId} ORDER BY token`; + assert.isDefined(foreignGrant); + assert.include(failureOf(yield* sendFloor({ ...post, floorGrant: foreignGrant.token })), { + reason: "floor_not_granted", + }); + assert.include( + failureOf( + yield* sendFloor({ + ...post, + chatId: foreignChat.chatId, + floorGrant: foreignGrant.token, + }), + ), + { reason: "not_found", message: "Kin record not found." }, + ); + yield* sql`UPDATE kin_floor_grants SET agent_id = ${agentId}, chat_id = ${chat.chatId} WHERE org_id = ${person.orgId} AND token = ${fresh.token}`; + assert.isFalse((yield* sendFloor({ ...post, floorGrant: fresh.token }))._tag === "Failure"); + yield* human("human-3"); + assert.include(failureOf(yield* sendFloor({ ...post, floorGrant: fresh.token })), { + reason: "floor_not_granted", + }); + assert.isFalse( + (yield* sendFloor({ + chatId: post.chatId, + body: post.body, + intent: post.intent, + }))._tag === "Failure", + ); + }).pipe(Effect.provide(layer)), +); + +it.effect( + "limits agent notices to ten per rolling hour without charging retries or server notices", + () => + Effect.gen(function* () { + const { chat, person, chatService, sql } = yield* seed(true); + const post = { + chatId: chat.chatId, + body: "Notice", + intent: "evidence", + clientMessageId: "notice-0", + } as const; + const first = yield* sendFloor(post); + assert.isTrue(Result.isSuccess(first)); + for (let n = 1; n < 10; n++) + assert.isFalse( + (yield* sendFloor({ ...post, clientMessageId: `notice-${n}` }))._tag === "Failure", + ); + assert.deepStrictEqual(yield* sendFloor(post), first); + assert.include(failureOf(yield* sendFloor({ ...post, clientMessageId: "limited" })), { + reason: "limit", + }); + yield* chatService.notice({ + orgId: person.orgId, + chatId: chat.chatId, + messageId: KinMessageId.make("server-notice"), + body: "Server notice", + }); + assert.deepStrictEqual( + yield* sql`SELECT COUNT(*) AS count FROM kin_floor_notices WHERE org_id = ${person.orgId} AND chat_id = ${chat.chatId} ORDER BY message_id`, + [{ count: 10 }], + ); + yield* TestClock.adjust(3_600_000); + assert.isFalse( + (yield* sendFloor({ ...post, clientMessageId: "new-hour" }))._tag === "Failure", + ); + }).pipe(Effect.provide(layer)), +); + +it.effect( + "requires explicit group grants and keeps the six-turn door closed until a human speaks", + () => + Effect.gen(function* () { + const { chat, person, chatService, sql } = yield* seed(); + yield* sql`DELETE FROM kin_floor_grants WHERE org_id = ${person.orgId}`; + yield* sql`DELETE FROM kin_floor_runs WHERE org_id = ${person.orgId}`; + yield* sql`UPDATE kin_chats SET kind = 'team_group', direct_key = NULL WHERE org_id = ${person.orgId} AND chat_id = ${chat.chatId}`; + const [member] = yield* sql<{ + member_id: string; + }>`SELECT member_id FROM kin_chat_members WHERE org_id = ${person.orgId} AND chat_id = ${chat.chatId} AND agent_id = ${agentId} ORDER BY member_id`; + assert.isDefined(member); + yield* sql`INSERT INTO kin_agents (org_id, agent_id, display_name, role, owner_person_id, created_at) + VALUES (${person.orgId}, 'queued-qa', 'QA', 'qa', ${person.personId}, '1970-01-01T00:00:00.000Z')`; + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, agent_id, role, joined_at) + VALUES ('queued-qa-member', ${person.orgId}, ${chat.chatId}, 'agent', 'queued-qa', 'member', '1970-01-01T00:00:00.000Z')`; + yield* chatService.send(person, { + chatId: chat.chatId, + body: "Please answer", + mentions: [KinMemberId.make(member.member_id), KinMemberId.make("queued-qa-member")], + clientMessageId: "group-human", + }); + const [grant] = yield* sql<{ + token: string; + run_id: string; + }>`SELECT token, run_id FROM kin_floor_grants WHERE org_id = ${person.orgId} AND chat_id = ${chat.chatId} ORDER BY token`; + assert.isDefined(grant); + const post = { + chatId: chat.chatId, + body: "Answer", + intent: "answer", + clientMessageId: "group-answer", + } as const; + assert.include(failureOf(yield* sendFloor(post)), { reason: "floor_not_granted" }); + assert.include(errorOf(yield* call("kin_chat_post", { ...post, floorGrant: grant.token })), { + reason: "floor_not_granted", + }); + const first = yield* sendFloor({ ...post, floorGrant: grant.token }); + assert.isTrue(Result.isSuccess(first)); + assert.deepStrictEqual( + yield* sql`SELECT agent_id FROM kin_floor_grants + WHERE org_id = ${person.orgId} AND run_id = ${grant.run_id} AND consumed_at IS NULL ORDER BY token`, + [{ agent_id: "queued-qa" }], + ); + assert.deepStrictEqual(yield* sendFloor({ ...post, floorGrant: grant.token }), first); + assert.include( + failureOf( + yield* sendFloor({ + ...post, + clientMessageId: "reuse", + intent: "evidence", + floorGrant: grant.token, + }), + ), + { reason: "floor_not_granted" }, + ); + yield* sql`UPDATE kin_floor_runs SET agent_turns = 6, state = 'closed' WHERE org_id = ${person.orgId} AND run_id = ${grant.run_id}`; + assert.include( + failureOf( + yield* sendFloor({ + ...post, + clientMessageId: "closed", + floorGrant: grant.token, + }), + ), + { reason: "floor_closed" }, + ); + yield* chatService.send(person, { + chatId: chat.chatId, + body: "New question", + mentions: [KinMemberId.make(member.member_id)], + clientMessageId: "new-group-human", + }); + const [fresh] = yield* sql<{ + token: string; + }>`SELECT token FROM kin_floor_grants WHERE org_id = ${person.orgId} AND run_id != ${grant.run_id} ORDER BY token`; + assert.isDefined(fresh); + assert.isFalse( + (yield* sendFloor({ + ...post, + clientMessageId: "new-group-answer", + floorGrant: fresh.token, + }))._tag === "Failure", + ); + }).pipe(Effect.provide(layer)), +); diff --git a/apps/server/src/kin/mcp/KinChatToolkit.ts b/apps/server/src/kin/mcp/KinChatToolkit.ts index fe8ca5bd17977..c011e268d13df 100644 --- a/apps/server/src/kin/mcp/KinChatToolkit.ts +++ b/apps/server/src/kin/mcp/KinChatToolkit.ts @@ -46,7 +46,7 @@ const shared = { const post = Tool.make("kin_chat_post", { ...shared, description: - "Post as your registered Kin agent. Intent is required. Use the same clientMessageId to retry; changing a retry is refused. Text never grants authority.", + "Post as your registered Kin agent. Intent is required. In direct chats you may reply once after the owner speaks. Group replies are refused (floor_not_granted). Notices are classified by the server wake-up, need evidence, decision or question intent, and are limited to 10 per agent per chat per hour. Use the same clientMessageId to retry; changing a retry is refused. Text never grants authority.", parameters: Schema.Struct({ ...KinMessagesSendInput.fields, clientMessageId: Schema.optional( diff --git a/apps/server/src/kin/mcp/agentContextBudget.json b/apps/server/src/kin/mcp/agentContextBudget.json index 02134fece6489..1c793fb8ccbf0 100644 --- a/apps/server/src/kin/mcp/agentContextBudget.json +++ b/apps/server/src/kin/mcp/agentContextBudget.json @@ -1,4 +1,4 @@ { - "mcpToolListJsonBytes": 50515, - "kinToolListJsonBytes": 2397 + "mcpToolListJsonBytes": 50762, + "kinToolListJsonBytes": 2644 } diff --git a/apps/server/src/kin/mcp/layer.test.ts b/apps/server/src/kin/mcp/layer.test.ts index 223c83f946c2c..3f4845185d154 100644 --- a/apps/server/src/kin/mcp/layer.test.ts +++ b/apps/server/src/kin/mcp/layer.test.ts @@ -1,4 +1,4 @@ -import { authorityLayerWithDatabase, startWakeupRun } from "../chat/WakeupAuthority.testkit.ts"; +import { authorityLayerWithDatabase, startAgentWakeup } from "../chat/WakeupAuthority.testkit.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import { McpProviderSessions } from "@t3tools/provider-core/server/McpProviderSessions"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; @@ -258,11 +258,9 @@ it.effect.each([true, false])( ); yield* sql`INSERT INTO kin_leads (agent_id, org_id, name, level_since, models_json, worker_projects_json, owner_chat_id) VALUES (${agentId}, ${person.orgId}, 'Lead', 0, '{}', '[]', ${chat.chatId})`; - const run = yield* startWakeupRun(threadId, "composition-wakeup").pipe( + yield* startAgentWakeup({ orgId: person.orgId, agentId, threadId }).pipe( Effect.provide(services), ); - yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, thread_id, run_id, model, started_at, status, event_ids) - VALUES ('composition-wakeup', ${person.orgId}, ${agentId}, ${threadId}, ${run.id}, 'test', 0, 'running', '[]')`; const initialized = yield* request( "/kin/mcp", issued.config.authorizationHeader, diff --git a/apps/server/src/kin/persistence/KinMigrations.test.ts b/apps/server/src/kin/persistence/KinMigrations.test.ts index 06b1360b63dc7..49fcc7b9498e4 100644 --- a/apps/server/src/kin/persistence/KinMigrations.test.ts +++ b/apps/server/src/kin/persistence/KinMigrations.test.ts @@ -20,6 +20,9 @@ const tableNames = [ "kin_chats", "kin_cursor", "kin_events", + "kin_floor_grants", + "kin_floor_notices", + "kin_floor_runs", "kin_leads", "kin_memory_reads", "kin_messages", @@ -89,6 +92,7 @@ describe("Kin migrations", () => { { migration_id: 5, name: "OneChatOwner" }, { migration_id: 6, name: "Pings" }, { migration_id: 7, name: "Budget" }, + { migration_id: 8, name: "Floor" }, ]); assert.deepStrictEqual( upstreamBefore.map((row) => [row.migration_id, row.name] as const), @@ -99,6 +103,9 @@ describe("Kin migrations", () => { ["kin_trigger_fires", ["fired_at"]], ["kin_trigger_inbox", ["received_at", "consumed_at"]], ["kin_ping_ledger", ["pinged_at", "escalated_at"]], + ["kin_floor_runs", ["opened_at"]], + ["kin_floor_grants", ["expires_at", "consumed_at"]], + ["kin_floor_notices", ["posted_at"]], ] as const) { const columns = yield* sql<{ name: string; type: string }>` SELECT name, type FROM pragma_table_info(${table}) @@ -135,6 +142,7 @@ describe("Kin migrations", () => { { migration_id: 5, name: "OneChatOwner" }, { migration_id: 6, name: "Pings" }, { migration_id: 7, name: "Budget" }, + { migration_id: 8, name: "Floor" }, ]); assert.deepStrictEqual(yield* upstreamHistory, upstreamBefore); assert.deepStrictEqual(yield* sql`SELECT * FROM kin_orgs`, [ @@ -155,6 +163,10 @@ describe("Kin migrations", () => { { name: "idx_kin_events_dedupe" }, { name: "idx_kin_events_queue" }, { name: "idx_kin_events_wakeup" }, + { name: "idx_kin_floor_grant_scope" }, + { name: "idx_kin_floor_latest" }, + { name: "idx_kin_floor_notices_rate" }, + { name: "idx_kin_floor_open" }, { name: "idx_kin_people_org_person" }, { name: "idx_kin_ping_items_item" }, { name: "idx_kin_ping_items_pending" }, @@ -204,6 +216,7 @@ describe("Kin migrations", () => { [5, "OneChatOwner"], [6, "Pings"], [7, "Budget"], + [8, "Floor"], ]); const before = yield* kinSchema; assert.deepStrictEqual( @@ -221,6 +234,9 @@ describe("Kin migrations", () => { VALUES ('existing-chat', 'org', 'project_group', 0, ${timestamp})`; yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) VALUES ('existing-owner', 'org', 'existing-chat', 'person', 'owner', 'owner', ${timestamp})`; + yield* sql`DROP TABLE kin_floor_notices`; + yield* sql`DROP TABLE kin_floor_grants`; + yield* sql`DROP TABLE kin_floor_runs`; yield* sql`DROP TABLE kin_ping_deliveries`; yield* sql`DROP TABLE kin_ping_escalations`; yield* sql`DROP TABLE kin_ping_items`; @@ -232,6 +248,7 @@ describe("Kin migrations", () => { [5, "OneChatOwner"], [6, "Pings"], [7, "Budget"], + [8, "Floor"], ]); assert.deepStrictEqual( yield* sql`SELECT member_id FROM kin_chat_members WHERE org_id = 'org' ORDER BY member_id`, @@ -251,6 +268,7 @@ describe("Kin migrations", () => { { migration_id: 5, name: "OneChatOwner" }, { migration_id: 6, name: "Pings" }, { migration_id: 7, name: "Budget" }, + { migration_id: 8, name: "Floor" }, ]); assert.deepStrictEqual(yield* runKinMigrations(), []); assert.deepStrictEqual(yield* runMigrations(), []); diff --git a/apps/server/src/kin/persistence/KinMigrations.ts b/apps/server/src/kin/persistence/KinMigrations.ts index b5dfea8b629ee..d9df0a3102951 100644 --- a/apps/server/src/kin/persistence/KinMigrations.ts +++ b/apps/server/src/kin/persistence/KinMigrations.ts @@ -8,6 +8,7 @@ import MemoryReads from "./migrations/K004_MemoryReads.ts"; import OneChatOwner from "./migrations/K005_OneChatOwner.ts"; import Pings from "./migrations/K006_Pings.ts"; import Budget from "./migrations/K007_Budget.ts"; +import Floor from "./migrations/K008_Floor.ts"; const run = Migrator.make({}); const loader = Migrator.fromRecord({ @@ -18,6 +19,7 @@ const loader = Migrator.fromRecord({ "5_OneChatOwner": OneChatOwner, "6_Pings": Pings, "7_Budget": Budget, + "8_Floor": Floor, }); export const runKinMigrations = Effect.fn("KinMigrations.run")(function* () { diff --git a/apps/server/src/kin/persistence/migrations/K008_Floor.ts b/apps/server/src/kin/persistence/migrations/K008_Floor.ts new file mode 100644 index 0000000000000..08d9b07beba5f --- /dev/null +++ b/apps/server/src/kin/persistence/migrations/K008_Floor.ts @@ -0,0 +1,47 @@ +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 kin_floor_runs ( + org_id TEXT NOT NULL REFERENCES kin_orgs(org_id), + run_id TEXT NOT NULL, + chat_id TEXT NOT NULL, + opened_by TEXT NOT NULL REFERENCES kin_messages(message_id), + mention_queue TEXT NOT NULL, + spoken TEXT NOT NULL DEFAULT '[]', + agent_turns INTEGER NOT NULL DEFAULT 0 CHECK (agent_turns BETWEEN 0 AND 6), + last_speaker TEXT, + state TEXT NOT NULL CHECK (state IN ('open', 'closed')), + opened_at INTEGER NOT NULL, + PRIMARY KEY (org_id, run_id), + FOREIGN KEY (org_id, chat_id) REFERENCES kin_chats(org_id, chat_id) + )`; + yield* sql`CREATE UNIQUE INDEX idx_kin_floor_open ON kin_floor_runs(org_id, chat_id) WHERE state = 'open'`; + yield* sql`CREATE INDEX idx_kin_floor_latest ON kin_floor_runs(org_id, chat_id, opened_at DESC)`; + yield* sql`CREATE TABLE kin_floor_grants ( + org_id TEXT NOT NULL REFERENCES kin_orgs(org_id), + token TEXT NOT NULL, + run_id TEXT NOT NULL, + chat_id TEXT NOT NULL, + agent_id TEXT NOT NULL, + expires_at INTEGER NOT NULL, + consumed_at INTEGER, + PRIMARY KEY (org_id, token), + FOREIGN KEY (org_id, run_id) REFERENCES kin_floor_runs(org_id, run_id), + FOREIGN KEY (org_id, chat_id) REFERENCES kin_chats(org_id, chat_id), + FOREIGN KEY (org_id, agent_id) REFERENCES kin_agents(org_id, agent_id) + )`; + yield* sql`CREATE INDEX idx_kin_floor_grant_scope ON kin_floor_grants(org_id, chat_id, agent_id, run_id, expires_at) WHERE consumed_at IS NULL`; + yield* sql`CREATE TABLE kin_floor_notices ( + org_id TEXT NOT NULL REFERENCES kin_orgs(org_id), + message_id TEXT NOT NULL REFERENCES kin_messages(message_id), + chat_id TEXT NOT NULL, + agent_id TEXT NOT NULL, + posted_at INTEGER NOT NULL, + PRIMARY KEY (org_id, message_id), + FOREIGN KEY (org_id, chat_id) REFERENCES kin_chats(org_id, chat_id), + FOREIGN KEY (org_id, agent_id) REFERENCES kin_agents(org_id, agent_id) + )`; + yield* sql`CREATE INDEX idx_kin_floor_notices_rate ON kin_floor_notices(org_id, chat_id, agent_id, posted_at)`; +}); diff --git a/docs/kin/specs/chat.md b/docs/kin/specs/chat.md index e955050ba867d..d11675c9871d8 100644 --- a/docs/kin/specs/chat.md +++ b/docs/kin/specs/chat.md @@ -202,7 +202,7 @@ export const KinWidget = Schema.Struct({ ``` - **State schemas** are registered per type in `apps/server/src/kin/widgets/registry.ts` (**new**). Owners: `task` (this spec, registered in CHAT-5; updater in CHAT-8), `approval` (approvals spec, drawn from `KinPendingAction`), `deferral` (lead spec), `decision`, `poll`, `checklist`, `form`, `date` (this spec, phase 2, CHAT-13). An unknown type, or state that fails its schema, is refused at upsert. CHAT-5 registers only `task`; other owners add their schemas with their features. -- **Acting:** `kin.widgets.act({ widgetId, revision, actionId, value?, clientActionId })` posts a `widget_action` message authored by the session's person, with `{ widgetId, revision, actionId, value }` as its structured body. The lead acts on it under its own permissions. A stale `revision` fails with `widget_changed`. +- **Acting:** `kin.widgets.act({ widgetId, revision, actionId, value?, clientActionId })` posts a `widget_action` message authored by the session's person, with `{ widgetId, revision, actionId, value }` as its structured body. A widget action is a human turn: it opens a new floor run and revokes the lead's unused grant from the previous run. The lead acts on it under its own permissions. A stale `revision` fails with `widget_changed`. - **Approval cards never go through `act`.** `act` refuses `type: "approval"` with `use_approvals`. Approving is the approvals spec's signed-grant RPC (section 9.2). Approval widgets are created only by the approvals spec's server code; the MCP upsert tool refuses that type too, so an agent can't draw one. - **Generated widgets** carry `source`, the lead thread's turn item that produced the MCP App resource. The client renders it with the existing `ThreadMcpApp`, which already calls `mcpApps.*` RPCs scoped to `{ threadId, itemId }`. This works for the owner only, since those RPCs need `orchestration:*` scopes. Members seeing generated widgets is an open question. - **Live widgets** (phase 3) carry `feed`; a server feeder updates `state` in place. @@ -294,7 +294,7 @@ K001 (phase 1, includes everything phase 2 needs for existing rows): K001 uses `TEXT` for ids, ISO timestamps and JSON, and `INTEGER` for sequences and revisions. Optional or nullable schema fields are nullable; system-author identity fields and `client_message_id` for non-client posts are nullable. `author_owner_person_id` snapshots the agent author's required `ownerPersonId`. Waiting `message_id` and `widget_id` are nullable references; `resolution` is nullable free text because resolution values are not a closed set. Message `widget_id` has no foreign key to avoid a message/widget insert cycle. Org foreign keys and other Kin-only references are enforced; org-consistent relationships and chat ownership cardinality are checked by the service. -The next free migration number (phase 2): `kin_floor_runs`, `kin_floor_bids`, `kin_judge_log` (below). New tables only. +K008 stores floor runs, grants and notice accounting. Phase 2 adds `kin_floor_bids` and `kin_judge_log` at the next free migration numbers. New tables only. **Seq allocation:** in one `sql.withTransaction`: `UPDATE kin_chats SET last_seq = last_seq + 1, last_message_at = ? WHERE chat_id = ? AND org_id = ? RETURNING last_seq`, then insert the message with that seq. Look up an existing `(chat_id, author_member_id, client_message_id)` inside the transaction before allocating a seq. Store sends as `send:` and widget actions as `act:` so the namespaces cannot collide. History returns the newest page before `beforeSeq` in ascending seq order, with `hasMore` from one extra row. Message and widget ids are server-generated; widget revisions start at 1 and are server-owned. Publish to the in-process hub only after commit. @@ -374,7 +374,7 @@ Kin serves these tools at **`/kin/mcp`**, alongside the existing T3 tools, never `kin_chat_post` accepts an optional `clientMessageId` retry key. Reusing it with identical content returns the stored row; changed content fails `not_allowed`. Omission creates a fresh post on each call. Bodies are nonblank, at most 16,000 characters, and contain no NUL; mentions are capped at 100. Reads are per-call, ascending after a non-negative safe-integer `afterSeq`, with a default limit of 50 and a maximum of 100, and preserve the viewer's suggestion visibility. No agent stream is exposed. -Task-card creation is server-only and unavailable through this toolkit. Updates require `widgetId` plus the expected `revision`; missing revision is refused and stale revision fails `widget_changed`. The anchor is immutable, and an agent can update only cards anchored by its own member. Neither trusted waiting APIs nor hub subscriptions are exposed. `approval` is refused by the service. `kin_floor_bid` and `floorGrant` are phase 2 and absent from the phase-1 toolkit. +Task-card creation is server-only and unavailable through this toolkit. Updates require `widgetId` plus the expected `revision`; missing revision is refused and stale revision fails `widget_changed`. The anchor is immutable, and an agent can update only cards anchored by its own member. Neither trusted waiting APIs nor hub subscriptions are exposed. `approval` is refused by the service. `kin_floor_bid` is phase 2 and absent from the phase-1 toolkit. CHAT-9 keeps group grant tokens internal; direct-chat grants are implicit. CHAT-11 and the phase-2 floor-bid work must deliver group grants through the agent wake-up before exposing `floorGrant` in `kin_chat_post`. Until then, a mentioned agent in a group cannot reply. Grants expire after five minutes and are single-use. Trusted server notices (`KinChatService.notice`) bypass the floor and agent-notice quota; agent notices are classified from the running wake-up's stored events, never from a model-provided flag. Notice classification applies to the entire wake-up across all of the agent's chats, not only the destination chat. A batch containing chat events is treated as replies. ### Floor manager (plain code) @@ -413,7 +413,7 @@ export const FLOOR_BID_WINDOW_MS = 2_000; - **Rule 3:** a bid or mention from `lastSpeaker` is skipped. Only a human message clears `lastSpeaker`. - **Rule 4:** at `agentTurns === 6` the run closes with `turn_budget`. Later agent posts get `floor_closed` until a human speaks. - **Rule 5:** the first agent turn after a human may be `answer` or `question`. Later turns must be `evidence`, `objection` or `decision`; others are refused. -- **Enforcement:** `kin_chat_post` in a group needs `floorGrant`, the grant token. A post without a valid token fails with `floor_not_granted`. A post uses the grant up, adds one to `agentTurns`, sets `lastSpeaker`, and stores `floorRunId` on the message. +- **Enforcement (phase 2):** `kin_chat_post` in a group needs `floorGrant`, the grant token. A post without a valid token fails with `floor_not_granted`. A post uses the grant up, adds one to `agentTurns`, sets `lastSpeaker`, and stores `floorRunId` on the message. - **Replies vs notices:** posts woken by a `KinEvent` that is not a chat message (routine, webhook, deferral, worker report) are notices. They need no grant, don't open or count in a run, and must use `evidence`, `decision` or `question` (interface rule 2). They are limited to 10 per agent per chat per hour; status belongs in widget updates. - **Direct chats** (phase 1): one agent, so rules 1 and 2 always pick it and no bids are needed. Rules 3, 4 and 5 still apply to replies: the server opens a run on each owner message and grants the lead implicitly. - **Who bids:** waking an agent costs a lead session (lead spec, budget). The floor manager names who to wake: mentioned agents, else the chat's lead. Other agents in the chat get a `floor.offer` KinEvent only when the lead spec's budget allows; they may bid with `kin_floor_bid` or ignore it. @@ -546,11 +546,11 @@ Run with `cd apps/server && vp test run src/kin` and `cd packages/contracts && v **CHAT-8. Task cards.** What: `TaskCardUpdater` following `streamDomainEvents` and `getThreadShell`, startup recheck. Files: `apps/server/src/kin/chat/TaskCardUpdater.ts`, `widgets/taskCard.ts`, tests. Depends on: CHAT-5, CHAT-7. Done when: the task card test passes, and a real `delegate_task` integration test with a server-created card shows the card change state in `kin.chat.subscribe` output. Owner: backend. -**CHAT-9. Floor manager.** What: pure `FloorManager.ts` (rules 1 to 5, replies vs notices), floor tables at the next free migration number, grant tokens in `kin_chat_post`, implicit grants in direct chats, notice rate limit. Files: `apps/server/src/kin/floor/FloorManager.ts`, `migrations/KNNN_Floor.ts` (next free number), tests. Depends on: CHAT-7. Done when: floor table tests pass and a direct-chat test shows a second unprompted reply refused with `floor_not_granted` while a notice passes. Owner: backend. +**CHAT-9. Floor manager.** What: pure `FloorManager.ts` (rules 1 to 5, replies vs notices), floor tables at K008, internal group grant tokens pending phase-2 wake-up delivery, implicit grants in direct chats, notice rate limit. Files: `apps/server/src/kin/floor/FloorManager.ts`, `migrations/KNNN_Floor.ts` (next free number), tests. Depends on: CHAT-7. Done when: floor table tests pass and a direct-chat test shows a second unprompted reply refused with `floor_not_granted` while a notice passes. Owner: backend. **CHAT-10. Judge in shadow.** What: `Judge` service, `NoopJudge`, `JudgeShadow`, `kin_judge_log`, thresholds, import-boundary test. Files: `apps/server/src/kin/floor/Judge.ts`, `JudgeShadow.ts`, `NoopJudge.ts`, tests. Depends on: CHAT-9. Done when: the judge tests pass and `kin_judge_log` gets one row per human message in a group test. Owner: backend. -**CHAT-11. Groups, members and the `kin:chat` scope** (phase 2). What: `createGroup`, members add, remove, setRole, mute; session bindings; `kin:chat` scope hook in `auth.ts`; move `KIN_CHAT_RPC_SCOPES` to it; owner-only role checks. Files: `KinChatService.ts`, `KinIdentity.ts`, `kinChat.ts`, `auth.ts` hook. Depends on: CHAT-6, and the member sign-in work for DESIGN gap 8 (unowned; see Open questions). Done when: a session holding only `kin:chat` can use every `kin.*` method for its chats and gets `EnvironmentAuthorizationError` on `orchestration.subscribeShell` and `terminal.open`. Owner: backend. +**CHAT-11. Groups, members and the `kin:chat` scope** (phase 2). What: `createGroup`, members add, remove, setRole, mute; session bindings; `kin:chat` scope hook in `auth.ts`; move `KIN_CHAT_RPC_SCOPES` to it; owner-only role checks; deliver group floor grants through agent wake-ups. Files: `KinChatService.ts`, `KinIdentity.ts`, `kinChat.ts`, `auth.ts` hook. Depends on: CHAT-6, and the member sign-in work for DESIGN gap 8 (unowned; see Open questions). Done when: a session holding only `kin:chat` can use every `kin.*` method for its chats and gets `EnvironmentAuthorizationError` on `orchestration.subscribeShell` and `terminal.open`. Owner: backend. **CHAT-12. Guests, suggest-only** (phase 2). What: guest role, `suggested` status, `kin.suggestions.resolve`, limits and name check copied from `guestShare.ts`, viewer filtering in streams, waiting rows for the owner. Files: `KinChatService.ts`, `rpcHandlers.ts`, tests. Depends on: CHAT-11. Done when: a guest's message is not visible to agents (`kin_chat_read`) or members until the owner sends it, and a fourth waiting suggestion fails `limit`. Owner: backend. diff --git a/evals/mcp-tool-use/cases/kin.ndjson b/evals/mcp-tool-use/cases/kin.ndjson index 475ec2fc4ca23..0161c6d4236dd 100644 --- a/evals/mcp-tool-use/cases/kin.ndjson +++ b/evals/mcp-tool-use/cases/kin.ndjson @@ -1,2 +1,3 @@ {"id": "kin-agent-post-and-task", "area": "kin", "kind": "bad", "pattern": "Kin agents update server-created task cards without creating them", "experience": "Task cards are created only by the trusted worker launcher; agents can update their own existing cards.", "privacy": "commit-safe", "source": {"request": "GLDRoger/t3code PR #32 independent review, round 2"}, "setup": {"role": "top", "context": "You are a registered Kin agent in environment environment, thread lead-thread. Current time is 2026-01-01T00:00:00.000Z. This thread can call Kin tools.", "world": {"repo": "acme/app", "kinAgent": true}, "mocks": {"kin_chat_read": [], "kin_chat_post": {"messageId": "message-1"}, "kin_widget_upsert": {"widgetId": "widget-1", "revision": 1}}}, "prompt": "Read chat chat-1, then post the evidence 'All focused checks passed' with retry key checks-1. Close your existing task card widget-1 at revision 1 in that chat. Its state is taskId checks-1, title Focused checks, environment environment, local thread worker-thread, status done, updatedAt 2026-01-01T00:00:00.000Z, with no remote environment, model, last error or pull requests. Do not create any task card or use shell commands.", "expect": {"calls": [{"tool": "kin_chat_read", "args": {"chatId": "chat-1"}}, {"tool": "kin_chat_post", "args": {"chatId": "chat-1", "body": "All focused checks passed", "intent": "evidence", "clientMessageId": "checks-1"}}, {"tool": "kin_widget_upsert", "args": {"chatId": "chat-1", "widgetId": "widget-1", "revision": 1, "type": "task", "closed": true, "state.taskId": "checks-1", "state.threadId": "worker-thread"}}], "order": ["kin_chat_read", "kin_chat_post", "kin_widget_upsert"], "shellMustNot": [".+"], "callsMustNot": [{"tool": "kin_chat_post", "args": {"author": "~agent"}}, {"tool": "kin_widget_upsert", "args": {"type": "approval"}}]}} {"id": "kin-ordinary-thread-control", "area": "kin", "kind": "control", "pattern": "Ordinary threads retain T3 tools without Kin tools", "experience": "CHAT-7's opt-in toolkit must not redirect ordinary thread reads into Kin chat.", "privacy": "commit-safe", "source": {"request": "GLDRoger/t3code PR #32 round 2 scope control"}, "setup": {"role": "top", "context": "This is an ordinary T3 thread, not a registered Kin agent.", "world": {"repo": "acme/app"}, "mocks": {"t3_thread_read": {"thread": {"id": "00000000-0000-4000-8000-000000000001", "status": "idle"}, "messages": []}}}, "prompt": "Read thread 00000000-0000-4000-8000-000000000001 and report its status. Do not post or modify anything.", "expect": {"calls": [{"tool": "t3_thread_read", "args": {"threadId": "00000000-0000-4000-8000-000000000001"}}], "notCalls": ["kin_chat_post", "kin_chat_read", "kin_widget_upsert"]}} +{"id":"kin-direct-reply-implicit-floor","area":"kin","kind":"control","pattern":"Direct replies use the server's implicit grant without minting tokens","experience":"CHAT-9 keeps owner-prompted direct-chat replies simple; no model chooses authority.","privacy":"commit-safe","source":{"request":"CHAT-9 direct chat control"},"setup":{"role":"top","context":"You are a registered Kin agent in environment environment, thread lead-thread. This thread can call Kin tools. The owner just asked a question in direct chat direct-1.","world":{"repo":"acme/app","kinAgent":true},"mocks":{"kin_chat_post":{"messageId":"message-2"}}},"prompt":"Answer the owner's direct-chat question with 'Yes, the focused tests passed', intent answer and retry key answer-1. Do not use the shell or create a floor token.","expect":{"calls":[{"tool":"kin_chat_post","args":{"chatId":"direct-1","body":"Yes, the focused tests passed","intent":"answer","clientMessageId":"answer-1"}}],"shellMustNot":[".+"],"notCalls":["kin_floor_bid"],"maxCalls":{"kin_chat_post":1}}}