From 3dfa5d3b314b853d5186cfb76496531c60825b19 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:27:23 +0530 Subject: [PATCH 1/2] feat(kin): leads show live status from the first second; no more seen or warm process A message for a lead now shows its working line at once ("Reading memory", or "Queued" behind a running wake-up), and the line names each phase from one server table: Thinking, the tool's label, Writing. Updates go out only when the label changes. The warm provider session path is removed: every wake-up starts fresh and ends. Co-Authored-By: Claude Opus 5.5 --- .../chats/components/KinPresenceLine.tsx | 6 +- .../src/kin/chat/KinChatService.test.ts | 4 +- apps/server/src/kin/lead/ChatWake.test.ts | 77 ++++++----- apps/server/src/kin/lead/ChatWake.ts | 35 +++-- apps/server/src/kin/lead/KinStop.ts | 6 +- apps/server/src/kin/lead/LeadPrompt.test.ts | 110 +-------------- apps/server/src/kin/lead/LeadPrompt.ts | 62 ++------- apps/server/src/kin/lead/WakeupRunner.test.ts | 81 +++-------- .../src/kin/lead/WakeupRunner.testkit.ts | 7 +- apps/server/src/kin/lead/WakeupRunner.ts | 122 ++--------------- apps/server/src/kin/reply/KinPresence.ts | 57 +++++--- .../src/kin/reply/KinReplyBridge.test.ts | 126 +++++++++++++----- apps/server/src/kin/reply/KinReplyBridge.ts | 104 ++++++++++++--- apps/server/src/kin/reply/classify.ts | 23 +++- docs/kin/KT.md | 2 +- docs/kin/PLAN.md | 12 +- docs/kin/specs/chat.md | 2 +- docs/kin/specs/lead.md | 20 ++- ops/kin/host/README.md | 4 +- .../src/kin/kinChatFeed.test.ts | 7 + .../client-runtime/src/kin/kinChatFixtures.ts | 4 +- packages/client-runtime/src/kin/kinLive.ts | 19 +-- packages/contracts/src/kinChat.ts | 5 +- 23 files changed, 394 insertions(+), 501 deletions(-) diff --git a/apps/mobile/src/features/chats/components/KinPresenceLine.tsx b/apps/mobile/src/features/chats/components/KinPresenceLine.tsx index 9a5caa214dbfa..a8ceb8297095e 100644 --- a/apps/mobile/src/features/chats/components/KinPresenceLine.tsx +++ b/apps/mobile/src/features/chats/components/KinPresenceLine.tsx @@ -53,8 +53,8 @@ export function useKinPresenceNow(active: boolean): number { export type KinStopState = "idle" | "stopping" | "failed"; /** - * What the lead is doing, in one line above the composer: pulsing dots while it has only seen - * or is starting, else its avatar and a gently breathing line while it works. The row keeps its + * What the lead is doing, in one line above the composer: pulsing dots while it is queued or + * starting, else its avatar and a gently breathing line while it works. The row keeps its * height when empty, so a reply landing never shifts the feed. */ export function KinPresenceLine(props: { @@ -75,7 +75,7 @@ export function KinPresenceLine(props: { if (announcement !== null) AccessibilityInfo.announceForAccessibility(announcement); }, [announcement]); const reduceMotion = useReduceMotionEnabled(); - // Motion only while a run is live and seen; Reduce Motion leaves the row still. + // Motion only while a run is live and on screen; Reduce Motion leaves the row still. const animate = line !== null && props.visible && !reduceMotion; const { onStop } = props; diff --git a/apps/server/src/kin/chat/KinChatService.test.ts b/apps/server/src/kin/chat/KinChatService.test.ts index 09b825c72a57d..ef6825705afee 100644 --- a/apps/server/src/kin/chat/KinChatService.test.ts +++ b/apps/server/src/kin/chat/KinChatService.test.ts @@ -1429,8 +1429,8 @@ describe("KinChatService", () => { const working = Effect.map(Queue.take(updates), (event) => event._tag === "chat" ? event.chat.working : event._tag, ); - // "seen" leaves the row as it was, so the list sends nothing for it. - yield* presence.set(person.orgId, chat.chatId, { ...line, state: "seen" }); + // "paused" leaves the row as it was, so the list sends nothing for it. + yield* presence.set(person.orgId, chat.chatId, { ...line, state: "paused" }); yield* presence.set(person.orgId, chat.chatId, { ...line, state: "thinking" }); assert.strictEqual(yield* working, true); yield* presence.clear(person.orgId, chat.chatId, agentId); diff --git a/apps/server/src/kin/lead/ChatWake.test.ts b/apps/server/src/kin/lead/ChatWake.test.ts index ea8d30537182b..3677c28546486 100644 --- a/apps/server/src/kin/lead/ChatWake.test.ts +++ b/apps/server/src/kin/lead/ChatWake.test.ts @@ -219,13 +219,13 @@ describe("ChatWake", () => { results.map((result) => result.duplicate), [false, true, false, false], ); - // The owner sees `seen` as soon as the message is queued, before any wake-up claims it. + // The working line shows as soon as the message is queued, before any wake-up claims it. const presence = yield* Presence.KinPresence; assert.deepStrictEqual( presence .snapshot(KinOrgId.make("a"), KinChatId.make("chat-a")) - .presence.map((line) => [line.agentId, line.state, line.wakeupId]), - [["lead-a", "seen", null]], + .presence.map((line) => [line.agentId, line.state, line.label, line.wakeupId]), + [["lead-a", "starting", "Reading memory", null]], ); const stored = yield* storedEvents(); assert.deepStrictEqual( @@ -259,41 +259,46 @@ describe("ChatWake", () => { }).pipe(Effect.provide(services)), ); - it.effect("shows `seen` for a waking reaction and drops it once the reaction is withdrawn", () => - Effect.gen(function* () { - yield* seed("a"); - yield* storeMessage(message("a", "lead-latest", { seq: 1, agent: true })); - const { settle } = yield* start(); - const hub = yield* Hub.KinChatHub; - const presence = yield* Presence.KinPresence; - const lines = () => - presence - .snapshot(KinOrgId.make("a"), KinChatId.make("chat-a")) - .presence.map((line) => line.state); - const reaction = (removedAt: string | null) => - hub.publish({ - type: "reaction.updated", - orgId: KinOrgId.make("a"), - chatId: KinChatId.make("chat-a"), - reaction: { + it.effect( + "shows Queued for a waking reaction behind a running wake-up, gone once withdrawn", + () => + Effect.gen(function* () { + yield* seed("a"); + yield* storeMessage(message("a", "lead-latest", { seq: 1, agent: true })); + const { settle } = yield* start(); + const hub = yield* Hub.KinChatHub; + const presence = yield* Presence.KinPresence; + const lines = () => + presence + .snapshot(KinOrgId.make("a"), KinChatId.make("chat-a")) + .presence.map((line) => [line.state, line.label]); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, status, event_ids) + VALUES ('running', 'a', 'lead-a', 'fixture', 0, 'running', '[]')`; + const reaction = (removedAt: string | null) => + hub.publish({ + type: "reaction.updated", orgId: KinOrgId.make("a"), chatId: KinChatId.make("chat-a"), - messageId: KinMessageId.make("lead-latest"), - memberId: KinMemberId.make("owner-member-a"), - emoji: "๐Ÿ‘Ž", - createdAt, - removedAt, - }, - woke: removedAt === null, - by: message("a", "m1").author, - }); - yield* reaction(null); - yield* settle; - assert.deepStrictEqual(lines(), ["seen"]); - yield* reaction(createdAt); - yield* settle; - assert.deepStrictEqual(lines(), []); - }).pipe(Effect.provide(services)), + reaction: { + orgId: KinOrgId.make("a"), + chatId: KinChatId.make("chat-a"), + messageId: KinMessageId.make("lead-latest"), + memberId: KinMemberId.make("owner-member-a"), + emoji: "๐Ÿ‘Ž", + createdAt, + removedAt, + }, + woke: removedAt === null, + by: message("a", "m1").author, + }); + yield* reaction(null); + yield* settle; + assert.deepStrictEqual(lines(), [["starting", "Queued"]]); + yield* reaction(createdAt); + yield* settle; + assert.deepStrictEqual(lines(), []); + }).pipe(Effect.provide(services)), ); it.effect("never wakes a lead for its own posts or after retirement, live or on catch-up", () => diff --git a/apps/server/src/kin/lead/ChatWake.ts b/apps/server/src/kin/lead/ChatWake.ts index 88209fc5a0b6c..925647a5163f1 100644 --- a/apps/server/src/kin/lead/ChatWake.ts +++ b/apps/server/src/kin/lead/ChatWake.ts @@ -1,5 +1,6 @@ import { KinAgentId, + type KinChatId, KinEventId, KinMessageId, KinOrgId, @@ -23,7 +24,7 @@ import { toPersistenceSqlError } from "../../persistence/Errors.ts"; import { forkParked } from "../../serverActivation.ts"; import { KinChatHub, type KinChatHubEvent } from "../chat/KinChatHub.ts"; import { KinChatRepository } from "../chat/KinChatRepository.ts"; -import { KinPresence, syncSeen } from "../reply/KinPresence.ts"; +import { KinPresence, queueLabel, syncQueued } from "../reply/KinPresence.ts"; import { KinEventQueue } from "./KinEventQueue.ts"; const decodeTap = Schema.decodeUnknownEffect( @@ -46,6 +47,17 @@ const make = Effect.gen(function* () { const repo = yield* KinChatRepository; const queue = yield* KinEventQueue; const presence = yield* Effect.serviceOption(KinPresence); + // The working line shows the moment a message is accepted, before any wake-up claims it. + const showQueued = Effect.fn("KinChatWake.showQueued")( + function* (orgId: KinOrgId, chatId: KinChatId, agentId: KinAgentId) { + if (Option.isNone(presence)) return; + const label = yield* queueLabel(orgId, agentId).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + ); + yield* presence.value.queued(orgId, chatId, agentId, label, yield* Clock.currentTimeMillis); + }, + Effect.catchCause((cause) => Effect.logWarning("Kin queue line failed", { cause })), + ); const wake = Effect.fn("KinChatWake.wake")( function* (message: KinMessage) { @@ -111,21 +123,14 @@ const make = Effect.gen(function* () { ), }), ); - // The first thing the sender sees, well before a wake-up claims the message. - if (queued && Option.isSome(presence)) - yield* presence.value.seen( - message.orgId, - message.chatId, - agentId, - yield* Clock.currentTimeMillis, - ); + if (queued) yield* showQueued(message.orgId, message.chatId, agentId); } }, Effect.catchCause((cause) => Effect.logError("Kin chat wake-up failed", { cause })), ); // A waking reaction (the chat service decides) becomes `chat.reaction`; withdrawing it before - // a wake-up claims it cancels the event and its `seen`. Other reactions are feedback only. + // a wake-up claims it cancels the event and its working line. Other reactions are feedback only. const react = Effect.fn("KinChatWake.react")( function* (event: Extract) { const { reaction } = event; @@ -138,7 +143,7 @@ const make = Effect.gen(function* () { ); if (Option.isSome(presence)) for (const row of expired) - yield* syncSeen(presence.value, reaction.orgId, KinAgentId.make(row.agentId)).pipe( + yield* syncQueued(presence.value, reaction.orgId, KinAgentId.make(row.agentId)).pipe( Effect.provideService(SqlClient.SqlClient, sql), ); return; @@ -176,13 +181,7 @@ const make = Effect.gen(function* () { ), }), ); - if (queued && Option.isSome(presence)) - yield* presence.value.seen( - reaction.orgId, - reaction.chatId, - agentId, - yield* Clock.currentTimeMillis, - ); + if (queued) yield* showQueued(reaction.orgId, reaction.chatId, agentId); }, Effect.catchCause((cause) => Effect.logError("Kin reaction wake-up failed", { cause })), ); diff --git a/apps/server/src/kin/lead/KinStop.ts b/apps/server/src/kin/lead/KinStop.ts index fdebfdb4f7238..5028755a55edc 100644 --- a/apps/server/src/kin/lead/KinStop.ts +++ b/apps/server/src/kin/lead/KinStop.ts @@ -38,7 +38,7 @@ import { PersistenceSqlError, toPersistenceSqlError } from "../../persistence/Er import * as Hub from "../chat/KinChatHub.ts"; import type { PersonIdentity } from "../chat/KinIdentity.ts"; import * as Chat from "../chat/KinChatRepository.ts"; -import { KinPresence, syncSeen } from "../reply/KinPresence.ts"; +import { KinPresence, syncQueued } from "../reply/KinPresence.ts"; import type * as Routines from "../triggers/routines.ts"; import * as Queue from "./KinEventQueue.ts"; import { isOrgOwner, isOrgPaused, STOP_REASON } from "./orgState.ts"; @@ -334,11 +334,11 @@ const make = Effect.gen(function* () { ); if (resumed !== undefined) { yield* publish(input.orgId, resumed); - // Messages the pause expired no longer wait, so their `seen` goes too. + // Messages the pause expired no longer wait, so their working line goes too. if (Option.isSome(presence)) for (const lead of yield* sql<{ agentId: string }>`SELECT agent_id AS "agentId" FROM kin_leads WHERE org_id = ${input.orgId} ORDER BY agent_id`) - yield* syncSeen(presence.value, input.orgId, KinAgentId.make(lead.agentId)).pipe( + yield* syncQueued(presence.value, input.orgId, KinAgentId.make(lead.agentId)).pipe( Effect.provideService(SqlClient.SqlClient, sql), ); if (attached !== undefined) yield* attached.resume(input.orgId); diff --git a/apps/server/src/kin/lead/LeadPrompt.test.ts b/apps/server/src/kin/lead/LeadPrompt.test.ts index a9b01a88a22c3..0d2ccc99f84ad 100644 --- a/apps/server/src/kin/lead/LeadPrompt.test.ts +++ b/apps/server/src/kin/lead/LeadPrompt.test.ts @@ -57,17 +57,6 @@ const event = (messageId: string) => dedupeKey: null, provenance: { _tag: "system" }, }); -// Sized like a lived-in memory: rules of about 4k characters and an index at its 200-line cap. -const fullRules = - "- Ask the owner before spending money, contacting people or merging code.\n".repeat(55); -const fullIndex = [ - "As of 2026-11-08T00:00:00.000Z", - ...Array.from( - { length: 199 }, - (_, i) => - `- commitments/item-${i}.md: follow up with the design partner on onboarding, due Friday`, - ), -].join("\n"); // The repository only takes a lead's message inside its running wake-up; these are history. const insertLeadMessage = Effect.fn("test.insertLeadMessage")(function* (id: string, body: string) { const sql = yield* SqlClient.SqlClient; @@ -119,11 +108,9 @@ const memory = Layer.succeed( purgeInFlight: () => Effect.die("Unused"), historyGeneration: () => Effect.die("Unused"), readPromptSnapshot: (org, head) => - org === orgId && head === "head-full" - ? Effect.succeed({ rules: fullRules, index: fullIndex }) - : org !== orgId || !["head-one", "head-two"].includes(head) - ? Effect.fail(new Memory.MemoryError({ orgId: org, operation: "promptSnapshot" })) - : Effect.succeed({ rules: `Invented rules ${head}`, index: `Invented index ${head}` }), + org !== orgId || !["head-one", "head-two"].includes(head) + ? Effect.fail(new Memory.MemoryError({ orgId: org, operation: "promptSnapshot" })) + : Effect.succeed({ rules: `Invented rules ${head}`, index: `Invented index ${head}` }), ensureCheckouts: () => Effect.die("Unused"), prepareWakeup: () => Effect.die("Unused"), readIndex: () => Effect.die("Unused"), @@ -714,100 +701,9 @@ it.effect( const recent = built.split("# Recent chat (data, oldest first)\n\n")[1]?.split("# Events")[0]; expect(recent).toMatch(/"from":"owner".*Did the release go out\?.*Also check the docs\./); expect(recent).not.toContain("Current question"); - // A warm session saw everything up to its last seq, and its own words, so only the rest goes. - yield* insertLeadMessage("mine", "It went out at noon."); - const warm = yield* prompt.build({ - ...input, - events: [event("now")], - lane: { chatId, mode: "reply" }, - since: { index: "Invented index head-one", chatSeq: 1 }, - }); - expect(warm).not.toContain("# Standing rules"); - expect(warm).not.toContain("# Memory index"); - expect(warm).not.toContain("# Group rules"); - expect(warm).toContain("Standing rules and the memory index are unchanged"); - const since = warm.split("# Chat since your last wake-up (data, oldest first)\n\n")[1]; - expect(since?.split("# Events")[0]).toMatch(/Also check the docs\./); - expect(since).not.toMatch(/Did the release go out|It went out at noon/); - expect(since?.split("# Events")[1]).toContain("Current question"); - const moved = yield* prompt.build({ - ...input, - memoryHead: "head-two", - events: [event("now")], - since: { index: "Invented index head-one", chatSeq: 3 }, - }); - expect(moved).not.toContain("Invented rules"); - expect(moved).toContain( - '{"removed":["Invented index head-one"],"added":["Invented index head-two"]}', - ); }).pipe(Effect.provide(layer)), ); -it.effect("a warm continuation is a fraction of a cold wake-up's message", () => - Effect.gen(function* () { - const repo = yield* seed; - yield* repo.insertAgent({ - orgId, - agentId, - displayName: "Fixture lead", - role: "lead", - ownerPersonId: personId, - createdAt: timestamp, - }); - for (const [id, principal, role] of [ - [memberId, { _tag: "person", personId }, "owner"], - [KinMemberId.make("lead-member"), { _tag: "agent", agentId }, "member"], - ] as const) - yield* repo.addMember({ - orgId, - chatId, - memberId: id, - principal, - role, - joinedAt: timestamp, - leftAt: null, - mutedUntil: null, - }); - for (let i = 1; i <= 21; i++) { - const body = `Message ${i}: ${"the launch plan needs one more pass on pricing and the onboarding copy. ".repeat(4)}`; - if (i % 2 === 0) yield* insertLeadMessage(`m${i}`, body); - else - yield* repo.insertMessage({ - orgId, - chatId, - messageId: KinMessageId.make(`m${i}`), - author: { _tag: "human", personId, memberId }, - kind: "text", - body, - intent: null, - mentions: [], - replyTo: null, - widgetId: null, - floorRunId: null, - status: "posted", - sentBy: null, - createdAt: timestamp, - editedAt: null, - clientMessageId: null, - }); - } - const prompt = yield* KinLeadPrompt; - const wake = { ...input, memoryHead: "head-full", events: [event("m21")] }; - const lane = { chatId, mode: "reply" } as const; - const cold = yield* prompt.build({ ...wake, lane }); - const warm = yield* prompt.build({ ...wake, lane, since: { index: fullIndex, chatSeq: 20 } }); - const wrote = yield* prompt.build({ - ...wake, - lane, - since: { index: fullIndex.replace(/\n[^\n]*$/, "\n- claims/old.md: retired"), chatSeq: 20 }, - }); - // About four characters a token: cold is about 7.6k tokens of message, warm about 300. - expect(cold.length).toBeGreaterThan(25_000); - expect(warm.length).toBeLessThan(1_500); - expect(wrote.length).toBeLessThan(1_800); - }).pipe(Effect.provide(layer)), -); - it.effect( "carries the owner's feedback reactions since the last finished wake-up, and a ๐Ÿ‘Ž asks what was wrong", () => diff --git a/apps/server/src/kin/lead/LeadPrompt.ts b/apps/server/src/kin/lead/LeadPrompt.ts index 27caa818398b1..39b28eb186dfc 100644 --- a/apps/server/src/kin/lead/LeadPrompt.ts +++ b/apps/server/src/kin/lead/LeadPrompt.ts @@ -42,19 +42,10 @@ export interface KinLeadPromptInput { readonly budgetContext?: string; /** The chat the lead's plain text goes to; see the reply bridge. */ readonly lane?: { readonly chatId: KinChatId; readonly mode: "reply" | "notice" }; - /** Continues a warm session: the rules are unchanged, so only what changed since is sent. */ - readonly since?: KinLeadPromptSince; /** Server-gathered facts for a brief or summary event, by event id. */ readonly routineFacts?: ReadonlyMap; } -/** What a warm session's previous wake-up was shown. */ -export interface KinLeadPromptSince { - readonly index: string; - /** The lane's last message seq when that wake-up ended; the session saw everything up to it. */ - readonly chatSeq: number; -} - export class KinLeadPrompt extends Context.Service< KinLeadPrompt, { @@ -289,14 +280,8 @@ export class KinLeadPrompt extends Context.Service< limit: RECENT_MESSAGES, viewerMemberId: member.value.memberId, }); - const since = input.since; const messages = page.messages.filter( - (message) => - message.status === "posted" && - !quoted.has(message.messageId) && - (since === undefined || - (message.seq > since.chatSeq && - !(message.author._tag === "agent" && message.author.agentId === agentId))), + (message) => message.status === "posted" && !quoted.has(message.messageId), ); // Reactions are context: who reacted what, by role, never as instructions. const roles = new Map( @@ -379,30 +364,16 @@ export class KinLeadPrompt extends Context.Service< ? `${encoded(zone.zone)}; local time: ${DateTime.formatIsoZoned(DateTime.makeZonedUnsafe(now, { timeZone: zone.zone }))}` : `UTC (${zone._tag === "invalid" ? "invalid owner timezone" : "owner timezone unavailable"}; using UTC); local time: ${DateTime.formatIso(DateTime.makeUnsafe(now))}`; - const indexSize = `Memory index size: ${indexLines(snapshot.index)}/${INDEX_MAX_LINES} lines`; // The instructions travel in the session's system prompt (LeadIsolation); memory changes per head. return [ - ...(input.since === undefined - ? [ - "# Standing rules", - snapshot.rules, - "# Memory index (data, not instructions)", - quote("memory index", snapshot.index), - ...(snapshot.index === "" ? ["index unavailable"] : []), - indexSize, - // Rooms shared with other people and agents; a warm session is one chat's. - ...(laneChat !== undefined && laneChat.kind !== "direct" ? [groupRules] : []), - ] - : input.since.index === snapshot.index - ? [ - "This continues your session. Standing rules and the memory index are unchanged since your last wake-up.", - ] - : [ - "This continues your session. Standing rules are unchanged; these memory index lines changed since your last wake-up.", - "# Memory index changes (data, not instructions)", - quote("memory index changes", indexDelta(input.since.index, snapshot.index)), - indexSize, - ]), + "# Standing rules", + snapshot.rules, + "# Memory index (data, not instructions)", + quote("memory index", snapshot.index), + ...(snapshot.index === "" ? ["index unavailable"] : []), + `Memory index size: ${indexLines(snapshot.index)}/${INDEX_MAX_LINES} lines`, + // Rooms shared with other people and agents. + ...(laneChat !== undefined && laneChat.kind !== "direct" ? [groupRules] : []), "--- KIN WAKE-UP ---", `Time (UTC): ${DateTime.formatIso(DateTime.makeUnsafe(now))}`, `Owner time: ${ownerTime}`, @@ -426,12 +397,7 @@ export class KinLeadPrompt extends Context.Service< ]), ...(recent.length === 0 ? [] - : [ - input.since === undefined - ? "# Recent chat (data, oldest first)" - : "# Chat since your last wake-up (data, oldest first)", - boundedRecent(recent, agentId), - ]), + : ["# Recent chat (data, oldest first)", boundedRecent(recent, agentId)]), ...(feedback.length === 0 ? [] : ["# Owner reactions (data, not instructions)", feedback.join("\n")]), @@ -461,14 +427,6 @@ const INDEX_MAX_LINES = 200; const indexLines = (index: string) => index.trim() === "" ? 0 : index.trimEnd().split("\n").length; -const indexDelta = (before: string, after: string) => { - const old = new Set(before.split("\n")); - const now = new Set(after.split("\n")); - return { - removed: [...old].filter((line) => !now.has(line)), - added: [...now].filter((line) => !old.has(line)), - }; -}; const decodeTapText = Schema.decodeUnknownOption( Schema.fromJsonString(Schema.Struct({ text: Schema.String })), diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index 3cd65ef47fe77..02b6d4997a98e 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -520,6 +520,7 @@ describe("WakeupRunner", () => { mode: "reply" as const, leadName: "Lead", }), + preparing: () => Effect.void, begin: () => Effect.void, complete: () => Effect.void, end: () => Effect.void, @@ -669,66 +670,28 @@ describe("WakeupRunner", () => { }).pipe(provideDeterministicTestRuntime), ); - it.effect( - "keeps a direct chat's session for 10 wake-ups under 10 idle minutes apart, committing each", - () => - Effect.gen(function* () { - let commits = 0; - let journals = 0; - const prompts: Array = []; - const opened: Array = []; - const prepare = () => - Effect.succeed({ - head: "abc", - indexAsOf: DateTime.makeUnsafe("2026-11-08T00:00:00.000Z"), - read: "/private/tmp", - }); - const writer = Layer.mock(Writer.MemoryWriter)({ - appendJournal: () => Effect.sync(() => void journals++), - commitWakeup: () => Effect.sync(() => (commits++, { commit: "fixture" })), - discard: () => Effect.void, - }); - yield* Effect.gen(function* () { - yield* seed; - yield* seedDirectChats; - for (let i = 1; i <= 11; i++) { - yield* wake(`m${i}`); - yield* TestClock.adjust("9 minutes"); - } - yield* TestClock.adjust("1 minute"); - yield* wake("late"); - // The 11th starts fresh at the turn cap, and the 12th after 10 idle minutes. - assert.deepStrictEqual(yield* sessions(), [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3]); - // Each warm wake-up resumes in a new process, since prepare swapped its cwd for a new - // checkout. (The fake keeps the last one across the two fresh contexts.) - assert.lengthOf(opened, 10); - assert.deepStrictEqual( - prompts.map((prompt) => prompt.since !== undefined), - [false, ...Array.from({ length: 9 }, () => true), false, false], - ); - assert.strictEqual(commits, 12); - assert.strictEqual(journals, 12); - }).pipe(Effect.provide(harness({ writer, prompts, opened, prepare }))); - }).pipe(provideDeterministicTestRuntime), - ); - it.effect.each(["another direct chat", "a level change", "new standing rules"] as const)( - "starts a fresh session for %s", - (change) => - Effect.gen(function* () { - let rules = "rules"; - const snapshot = () => Effect.sync(() => ({ rules, index: "index" })); - yield* Effect.gen(function* () { - yield* seed; - yield* seedDirectChats; - const sql = yield* SqlClient.SqlClient; - yield* wake("first"); + it.effect("starts every wake-up in a fresh session with the full prompt, committing each", () => + Effect.gen(function* () { + let commits = 0; + const prompts: Array = []; + const writer = Layer.mock(Writer.MemoryWriter)({ + appendJournal: () => Effect.void, + commitWakeup: () => Effect.sync(() => (commits++, { commit: "fixture" })), + discard: () => Effect.void, + }); + yield* Effect.gen(function* () { + yield* seed; + yield* seedDirectChats; + // Back to back in one direct chat, at one level and model: still no session carries over. + for (const id of ["m1", "m2", "m3"]) { + yield* wake(id); yield* TestClock.adjust("1 minute"); - if (change === "a level change") yield* sql`UPDATE kin_leads SET level = 'L1'`; - if (change === "new standing rules") rules = "new rules"; - yield* wake("second", change === "another direct chat" ? "other-direct" : "direct"); - assert.deepStrictEqual(yield* sessions(), [1, 2]); - }).pipe(Effect.provide(harness({ snapshot }))); - }).pipe(provideDeterministicTestRuntime), + } + assert.deepStrictEqual(yield* sessions(), [1, 2, 3]); + assert.lengthOf(prompts, 3); + assert.strictEqual(commits, 3); + }).pipe(Effect.provide(harness({ writer, prompts }))); + }).pipe(provideDeterministicTestRuntime), ); it.effect("interrupts mid-wake-up without counting an attempt and admits the next claim", () => diff --git a/apps/server/src/kin/lead/WakeupRunner.testkit.ts b/apps/server/src/kin/lead/WakeupRunner.testkit.ts index 7d10be597d52b..aa156135437c3 100644 --- a/apps/server/src/kin/lead/WakeupRunner.testkit.ts +++ b/apps/server/src/kin/lead/WakeupRunner.testkit.ts @@ -147,9 +147,6 @@ type HarnessOptions = { readonly steering?: Deferred.Deferred; /** Every prompt the runner builds, in order. */ readonly prompts?: Array; - readonly snapshot?: Memory.Memory["Service"]["readPromptSnapshot"]; - /** Every provider process the fake adapter opens. */ - readonly opened?: Array; /** Called on every `readyLeads` pass the runner makes. */ readonly onReadyLeads?: () => void; /** The project id bootstrap returns, read on each call. */ @@ -179,7 +176,6 @@ function parts(options: HarnessOptions) { planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), openSession: (session) => Effect.gen(function* () { - options.opened?.push(session.providerSessionId); const now = yield* DateTime.now; const events = yield* PubSub.unbounded(); const open = new Map< @@ -516,8 +512,7 @@ function parts(options: HarnessOptions) { read: "/private/tmp", })), ensureCheckouts: () => Effect.succeed({ writer: "/private/tmp", read: "/private/tmp" }), - readPromptSnapshot: - options.snapshot ?? (() => Effect.succeed({ rules: "rules", index: "index" })), + readPromptSnapshot: () => Effect.succeed({ rules: "rules", index: "index" }), }), ); const stack = Layer.mergeAll( diff --git a/apps/server/src/kin/lead/WakeupRunner.ts b/apps/server/src/kin/lead/WakeupRunner.ts index 84c129987cd7d..911357029b735 100644 --- a/apps/server/src/kin/lead/WakeupRunner.ts +++ b/apps/server/src/kin/lead/WakeupRunner.ts @@ -1,10 +1,7 @@ import { CommandId, KinAgentId, - KinChatId, - type KinEvent, KinLead, - type KinLevel, KinMessageId, KinOrgId, KinWakeupId, @@ -30,9 +27,7 @@ import * as Schema from "effect/Schema"; import type * as Scope from "effect/Scope"; import * as SqlClient from "effect/sql/SqlClient"; import { isSqlError } from "effect/sql/SqlError"; -import { modelSelectionsEqual } from "@t3tools/shared/model"; -import * as ProviderSessionManager from "../../orchestration-v2/ProviderSessionManager.ts"; import * as ThreadLaunchService from "../../orchestration-v2/ThreadLaunchService.ts"; import * as ThreadManagementService from "../../orchestration-v2/ThreadManagementService.ts"; import { toPersistenceSqlError } from "../../persistence/Errors.ts"; @@ -76,24 +71,6 @@ const orgLoopWaitMs = ( const next = ready.find((candidate) => !active.has(candidate.agentId)); return next === undefined ? 60_000 : Math.min(60_000, Math.max(1, next.readyAt - now)); }; -/** A direct chat keeps its provider session for this long idle, for at most this many wake-ups. */ -const WARM_IDLE_MS = 600_000; -const WARM_MAX_WAKEUPS = 10; -type WarmSession = { - readonly threadId: ThreadId; - readonly chatId: KinChatId; - readonly level: KinLevel; - readonly model: ModelSelection; - readonly wakeups: number; - readonly endedAt: number; - readonly rules: string; - readonly index: string; - readonly chatSeq: number; -}; -const chatOf = (event: KinEvent) => - event._tag === "chat.message" || event._tag === "widget.action" || event._tag === "chat.reaction" - ? event.chatId - : undefined; export class KinWakeupError extends Schema.TaggedError()("KinWakeupError", { orgId: KinOrgId, @@ -206,7 +183,6 @@ const make = Effect.gen(function* () { const launch = yield* ThreadLaunchService.ThreadLaunchService; const threads = yield* ThreadManagementService.ThreadManagementService; const settings = yield* ServerSettingsService; - const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2; const paused = (orgId: KinOrgId) => isOrgPaused(orgId).pipe(Effect.provideService(SqlClient.SqlClient, sql)); const threadActivity = Effect.fn("WakeupRunner.threadActivity")(function* (orgId: KinOrgId) { @@ -233,37 +209,6 @@ const make = Effect.gen(function* () { return yield* decodeLead(row); }); const retired = new Set(); - // In memory on purpose: after a restart the first wake-up is fresh, which is always safe. - const warm = new Map(); - const warmKey = (orgId: KinOrgId, agentId: KinAgentId) => `${orgId}\u0000${agentId}`; - // A process whose cwd was removed can't run; the next run resumes the conversation in a new one. - const releaseProcess = Effect.fn("WakeupRunner.releaseProcess")(function* (threadId: ThreadId) { - const own = (yield* threads.getThreadProjection(threadId)).providerThreads.filter( - (providerThread) => providerThread.appThreadId === threadId, - ); - let released = true; - for (const providerSessionId of new Set(own.map((thread) => thread.providerSessionId))) - if (providerSessionId !== null && (yield* sessions.isLive(providerSessionId))) - released &&= yield* sessions.releaseUnlessBusy({ - providerSessionId, - ownProviderThreadIds: own.map((thread) => thread.id), - reason: "idle_timeout", - detail: "Kin wake-up ended", - }); - return released; - }); - /** The direct chat every event of this wake-up came from, if there is exactly one. */ - const directChat = Effect.fn("WakeupRunner.directChat")(function* ( - orgId: KinOrgId, - events: ReadonlyArray, - ) { - const chats = new Set(events.map(chatOf)); - const [chatId] = chats; - if (chats.size !== 1 || chatId === undefined) return undefined; - const direct = - yield* sql`SELECT 1 FROM kin_chats WHERE org_id = ${orgId} AND chat_id = ${chatId} AND kind = 'direct' AND archived_at IS NULL`; - return direct.length > 0 ? chatId : undefined; - }); const retire = Effect.fn("WakeupRunner.retire")(function* (record: typeof LeadRow.Type) { if (retired.has(record.agentId)) return; yield* queue.expireAgent(record.orgId, record.agentId); @@ -582,10 +527,9 @@ const make = Effect.gen(function* () { launchedAt: number | null; firstTokenAt: number | null; postedAt: number | null; - resumed: number | null; }>`SELECT status, enqueued_at AS "enqueuedAt", started_at AS "claimedAt", prepared_at AS "preparedAt", launched_at AS "launchedAt", - first_token_at AS "firstTokenAt", posted_at AS "postedAt", resumed + first_token_at AS "firstTokenAt", posted_at AS "postedAt" FROM kin_wakeups WHERE org_id = ${orgId} AND wakeup_id = ${wakeupId} ORDER BY wakeup_id`.pipe(Effect.mapError(toPersistenceSqlError("WakeupRunner.logLatency"))); const enqueuedAt = row?.enqueuedAt; @@ -595,7 +539,6 @@ const make = Effect.gen(function* () { orgId, wakeupId, status: row.status, - warm: row.resumed === 1, claimedMs: since(row.claimedAt), preparedMs: since(row.preparedAt), launchedMs: since(row.launchedAt), @@ -731,6 +674,14 @@ const make = Effect.gen(function* () { const lane = Option.isSome(bridge) ? Option.getOrUndefined(yield* bridge.value.lane({ orgId, agentId, wakeupId })) : undefined; + if (Option.isSome(bridge) && lane !== undefined) + yield* bridge.value.preparing({ + orgId, + agentId, + wakeupId, + lane, + startedAt: row.startedAt, + }); const pinned = yield* memory.prepareWakeup(orgId, wakeupId, { lead: agentId }).pipe( Effect.tapError((error) => Effect.logError("Kin memory preparation failed", { @@ -845,37 +796,6 @@ const make = Effect.gen(function* () { !cheapOnly && (urgent.length > 0 || events.some((event) => event._tag === "routine")) ? current.models.strong : current.models.cheap; - // A warm session is one chat's, at one level and model; anything else starts fresh. - const previous = warm.get(warmKey(orgId, agentId)); - warm.delete(warmKey(orgId, agentId)); - const direct = yield* directChat(orgId, events); - const seen = - direct === undefined - ? undefined - : yield* memory.readPromptSnapshot(orgId, pinned.head, { lead: agentId }); - const resumable = - previous !== undefined && - seen !== undefined && - previous.chatId === direct && - previous.threadId === existingThreadId && - previous.level === current.level && - modelSelectionsEqual(previous.model, modelSelection) && - previous.wakeups < WARM_MAX_WAKEUPS && - row.startedAt - previous.endedAt < WARM_IDLE_MS && - // New standing rules are a new contract, so they get a fresh session. - previous.rules === seen.rules; - // Prepare swapped in a new read checkout, so a warm session resumes in a new process. - const resumes = - resumable && - (yield* releaseProcess(previous.threadId).pipe( - Effect.catchCause((cause) => - Effect.logWarning("Kin lead process release failed", { - orgId, - wakeupId, - cause, - }).pipe(Effect.as(false)), - ), - )); const text = yield* prompt.build({ orgId, agentId, @@ -885,7 +805,6 @@ const make = Effect.gen(function* () { budgetContext, routineFacts, ...(lane === undefined ? {} : { lane }), - ...(resumes ? { since: { index: previous.index, chatSeq: previous.chatSeq } } : {}), }); const threadId = existingThreadId ?? ThreadId.make(`kin:${yield* ulid}`); row = { ...row, threadId }; @@ -950,8 +869,7 @@ const make = Effect.gen(function* () { text, attachments: [], mode: "queue", - // Without a fresh context the run continues the same provider conversation. - ...(resumes ? {} : { freshContext: true }), + freshContext: true, modelSelection, createdBy: "system", creationSource: "server", @@ -960,8 +878,7 @@ const make = Effect.gen(function* () { if (run === undefined) return yield* new KinWakeupError({ orgId, agentId, cause: "missing_run" }); row = { ...row, runId: run.id }; - yield* sql`UPDATE kin_wakeups SET run_id = ${run.id}, launched_at = ${yield* Clock.currentTimeMillis}, - resumed = ${resumes ? 1 : 0} + yield* sql`UPDATE kin_wakeups SET run_id = ${run.id}, launched_at = ${yield* Clock.currentTimeMillis} WHERE org_id = ${orgId} AND wakeup_id = ${wakeupId} AND agent_id = ${agentId} AND status = 'running'`; // A pause that landed during launch found no run to stop; stop it here instead. if (yield* paused(orgId)) @@ -971,22 +888,7 @@ const make = Effect.gen(function* () { runId: run.id, commandId: CommandId.make(`kin-stop-launch:${wakeupId}`), }); - const status = yield* wait(row, project.id); - if (status !== "completed" || direct === undefined || seen === undefined) return; - const [chat] = yield* sql<{ - lastSeq: number; - }>`SELECT last_seq AS "lastSeq" FROM kin_chats WHERE org_id = ${orgId} AND chat_id = ${direct}`; - warm.set(warmKey(orgId, agentId), { - threadId, - chatId: direct, - level: current.level, - model: modelSelection, - wakeups: resumes ? previous.wakeups + 1 : 1, - endedAt: yield* Clock.currentTimeMillis, - rules: seen.rules, - index: seen.index, - chatSeq: chat?.lastSeq ?? 0, - }); + yield* wait(row, project.id); }).pipe( Effect.onExit((exit) => Exit.isFailure(exit) diff --git a/apps/server/src/kin/reply/KinPresence.ts b/apps/server/src/kin/reply/KinPresence.ts index a1d71a035b066..4fa9ba8843cd2 100644 --- a/apps/server/src/kin/reply/KinPresence.ts +++ b/apps/server/src/kin/reply/KinPresence.ts @@ -15,6 +15,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import { toPersistenceSqlError } from "../../persistence/Errors.ts"; import * as Hub from "../chat/KinChatHub.ts"; +import { PHASE_LABELS } from "./classify.ts"; /** Draft deltas go out at most this often per chat. */ const DRAFT_THROTTLE_MS = 250; @@ -44,15 +45,19 @@ export class KinPresence extends Context.Service< chatId: KinChatId, agentId: KinAgentId, ) => Effect.Effect; - /** `seen` for a queued message, unless the agent already shows something in that chat. */ - readonly seen: ( + /** + * The line for a message still in the queue, unless a wake-up already shows one in that + * chat. + */ + readonly queued: ( orgId: KinOrgId, chatId: KinChatId, agentId: KinAgentId, + label: QueueLabel, at: number, ) => Effect.Effect; - /** Drops the agent's `seen` lines in every chat of the organization except `keep`. */ - readonly clearSeen: ( + /** Drops the agent's queue lines in every chat of the organization except `keep`. */ + readonly clearQueued: ( orgId: KinOrgId, agentId: KinAgentId, keep: ReadonlySet, @@ -75,6 +80,8 @@ export class KinPresence extends Context.Service< } >()("t3/kin/reply/KinPresence") {} +type QueueLabel = (typeof PHASE_LABELS)["queued" | "preparing"]; + const same = (a: Presence | undefined, b: Presence) => a !== undefined && a.state === b.state && @@ -146,25 +153,28 @@ const make = Effect.gen(function* () { }); return KinPresence.of({ set, - seen: Effect.fn("KinPresence.seen")(function* (orgId, chatId, agentId, at) { - if (lines.get(keyOf(orgId, chatId))?.presence.has(agentId)) return; - const iso = DateTime.formatIso(DateTime.makeUnsafe(at)); + queued: Effect.fn("KinPresence.queued")(function* (orgId, chatId, agentId, label, at) { + const current = lines.get(keyOf(orgId, chatId))?.presence.get(agentId); + if (current !== undefined && current.wakeupId !== null) return; + // A label change keeps the line's start, so its timer doesn't restart. + const iso = current?.startedAt ?? DateTime.formatIso(DateTime.makeUnsafe(at)); yield* set(orgId, chatId, { agentId, wakeupId: null, - state: "seen", - label: null, + state: "starting", + label, startedAt: iso, since: iso, }); }), - clearSeen: Effect.fn("KinPresence.clearSeen")(function* (orgId, agentId, keep) { + clearQueued: Effect.fn("KinPresence.clearQueued")(function* (orgId, agentId, keep) { const prefix = `${orgId}\u0000`; for (const [key, found] of lines) { if (!key.startsWith(prefix)) continue; const chatId = KinChatId.make(key.slice(prefix.length)); if (keep.has(chatId)) continue; - if (found.presence.get(agentId)?.state !== "seen") continue; + const current = found.presence.get(agentId); + if (current === undefined || current.wakeupId !== null) continue; found.presence.delete(agentId); prune(orgId, chatId); yield* hub.publish({ type: "presence.updated", orgId, chatId, agentId, presence: null }); @@ -250,16 +260,29 @@ const waitingChats = Effect.fn("KinPresence.waitingChats")( Effect.mapError(toPersistenceSqlError("KinPresence.waitingChats")), ); +/** Which queue label a waiting message gets: "Queued" while the lead runs a wake-up. */ +export const queueLabel = Effect.fn("KinPresence.queueLabel")( + function* (orgId: KinOrgId, agentId: KinAgentId) { + const sql = yield* SqlClient.SqlClient; + const running = yield* sql`SELECT 1 FROM kin_wakeups + WHERE org_id = ${orgId} AND agent_id = ${agentId} AND status = 'running' LIMIT 1`; + return running.length > 0 ? PHASE_LABELS.queued : PHASE_LABELS.preparing; + }, + Effect.mapError(toPersistenceSqlError("KinPresence.queueLabel")), +); + /** - * After queued events left the queue without a wake-up taking their chat (expired, withdrawn, - * or a wake-up ended): `seen` stays only where something still waits, and returns there. + * After queued events left the queue or a wake-up claimed or ended: a queue line stays only + * where something still waits, and shows there with the current label. */ -export const syncSeen = Effect.fn("KinPresence.syncSeen")( +export const syncQueued = Effect.fn("KinPresence.syncQueued")( function* (presence: KinPresence["Service"], orgId: KinOrgId, agentId: KinAgentId) { const waiting = yield* waitingChats(orgId, agentId); - yield* presence.clearSeen(orgId, agentId, waiting); + yield* presence.clearQueued(orgId, agentId, waiting); + if (waiting.size === 0) return; + const label = yield* queueLabel(orgId, agentId); const now = yield* Clock.currentTimeMillis; - for (const chatId of waiting) yield* presence.seen(orgId, chatId, agentId, now); + for (const chatId of waiting) yield* presence.queued(orgId, chatId, agentId, label, now); }, - Effect.catchCause((cause) => Effect.logWarning("Kin seen sync failed", { cause })), + Effect.catchCause((cause) => Effect.logWarning("Kin queue line sync failed", { cause })), ); diff --git a/apps/server/src/kin/reply/KinReplyBridge.test.ts b/apps/server/src/kin/reply/KinReplyBridge.test.ts index 5a7555b788cce..3fb778320f85c 100644 --- a/apps/server/src/kin/reply/KinReplyBridge.test.ts +++ b/apps/server/src/kin/reply/KinReplyBridge.test.ts @@ -10,6 +10,9 @@ import { KinMessageId, KinWakeupId, MessageId, + NodeId, + ProviderThreadId, + ProviderTurnId, RunId, ThreadId, TurnItemId, @@ -24,7 +27,6 @@ import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; -import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; import * as SqlClient from "effect/sql/SqlClient"; @@ -148,6 +150,24 @@ const itemEvent = (item: OrchestrationV2TurnItem): OrchestrationV2DomainEvent => payload: item, }); +const turnEvent = (id: string): OrchestrationV2DomainEvent => ({ + id: EventId.make(`event:turn:${id}`), + threadId, + occurredAt: at, + type: "provider-turn.updated", + payload: { + id: ProviderTurnId.make("turn"), + providerThreadId: ProviderThreadId.make("provider-thread"), + nodeId: NodeId.make("node"), + runAttemptId: null, + nativeTurnRef: null, + ordinal: 1, + status: "running", + startedAt: at, + completedAt: null, + }, +}); + /** A lead at `level` with its direct chat; `ask` is an owner message that wakes it. */ const setup = Effect.fn("test.setup")(function* (input: { readonly level?: "L0" | "L1"; @@ -275,36 +295,59 @@ it.effect("posts the lead run's plain text to the chat it answers, as one agent }).pipe(Effect.provide(layer)), ); -it.effect("shows a short note before a tool call only on the presence line", () => +it.effect("labels each phase of a wake-up once per change and clears when the reply settles", () => Effect.gen(function* () { const { fake, runId, complete, posted, bridge, owner, wakeupId, services, sql, direct } = yield* setup({ ask: "Remind me Friday" }); + const presence = Context.get(services, KinPresence); + const shown = () => + presence + .snapshot(owner.orgId, direct.chatId) + .presence.map((line) => [line.state, line.label, line.wakeupId]); + // Begun, before the model starts: never `seen`. + assert.deepStrictEqual(shown(), [["starting", "Reading memory", wakeupId]]); + const updates = yield* Queue.unbounded(); const all = yield* Context.get(services, KinChatHub).subscribeAll; - const note = text("a", 1, "Checking your reminders", runId); - const call = tool("b", 2, "mcp__kin__kin_defer", runId); - const answer = text("c", 3, "Done: I'll remind you Friday at 9:00.", runId); - const labels = yield* all.pipe( - Stream.filterMap((event) => - event.type === "presence.updated" && event.presence !== null - ? Result.succeed(event.presence.label) - : Result.failVoid, + yield* all.pipe( + Stream.runForEach((event) => + event.type === "presence.updated" + ? Queue.offer(updates, event.presence?.label ?? null) + : Effect.void, ), - Stream.takeUntil((label) => label === "Checking your reminders"), - Stream.runCollect, Effect.forkScoped, ); - for (const item of [note, call]) yield* Queue.offer(fake.live, itemEvent(item)); - assert.include(yield* Fiber.join(labels), "Checking your reminders"); + const note = text("a", 1, "Checking your reminders", runId); + const call = tool("b", 2, "mcp__kin__kin_defer", runId); + const calling = { ...call, status: "running" } as OrchestrationV2TurnItem; + const answer = text("c", 3, "Done: I'll remind you Friday at 9:00.", runId); + const streaming = (body: string) => + ({ ...answer, text: body, streaming: true }) as OrchestrationV2TurnItem; + // Repeats of a phase (a second turn update, the tool's progress, each text delta) send nothing. + for (const event of [ + turnEvent("1"), + turnEvent("2"), + itemEvent(note), + itemEvent(calling), + itemEvent(calling), + itemEvent(call), + itemEvent(streaming("Done:")), + itemEvent(streaming("Done: I'll remind")), + ]) + yield* Queue.offer(fake.live, event); + // The model's own note before the call is never the label: the table's words are. + assert.deepStrictEqual(yield* Queue.takeN(updates, 4), [ + "Thinking", + "Setting a reminder", + "Thinking", + "Writing", + ]); fake.items = [note, call, answer]; - const cleared = yield* all.pipe( - Stream.filter((event) => event.type === "presence.updated" && event.presence === null), - Stream.take(1), - Stream.runCollect, - Effect.forkScoped, - ); yield* complete; // The reply is settled: what the wake-up does next isn't work on the owner's message. - assert.lengthOf(yield* Fiber.join(cleared), 1); + assert.strictEqual(yield* Queue.take(updates), null); + // A late event after settle doesn't bring the line back. + yield* Queue.offer(fake.live, itemEvent(calling)); + yield* Queue.offer(fake.live, turnEvent("3")); assert.deepStrictEqual( (yield* posted).map((row) => row.body), ["Done: I'll remind you Friday at 9:00."], @@ -315,13 +358,35 @@ it.effect("shows a short note before a tool call only on the presence line", () [{ firstToken: 1, posted: 1 }], ); yield* bridge.end({ orgId: owner.orgId, agentId, wakeupId }); - const presence = Context.get(services, KinPresence); - assert.deepStrictEqual(presence.snapshot(owner.orgId, direct.chatId).presence, []); - // A wake-up that ends before it begins drops `seen` where no message waits any more. - yield* presence.seen(owner.orgId, direct.chatId, agentId, 0); - assert.lengthOf(presence.snapshot(owner.orgId, direct.chatId).presence, 1); + assert.deepStrictEqual(shown(), []); + // A wake-up's line wins over a queue line, and a queue line's relabel keeps its start. + yield* presence.queued(owner.orgId, direct.chatId, agentId, "Reading memory", 0); + yield* presence.queued(owner.orgId, direct.chatId, agentId, "Queued", 5_000); + assert.deepStrictEqual( + presence + .snapshot(owner.orgId, direct.chatId) + .presence.map((line) => [line.label, line.startedAt]), + [["Queued", "1970-01-01T00:00:00.000Z"]], + ); + // A wake-up that ends before it begins drops the queue line where no message waits any more. yield* bridge.end({ orgId: owner.orgId, agentId, wakeupId: KinWakeupId.make("never-began") }); - assert.deepStrictEqual(presence.snapshot(owner.orgId, direct.chatId).presence, []); + assert.deepStrictEqual(shown(), []); + assert.strictEqual(yield* Queue.size(updates), 3); + }).pipe(Effect.provide(layer)), +); + +it.effect("holds a claimed wake-up's line from its claim, and drops it if it never begins", () => + Effect.gen(function* () { + const { bridge, owner, services, direct } = yield* setup({ ask: "Hi" }); + const presence = Context.get(services, KinPresence); + const shown = () => + presence.snapshot(owner.orgId, direct.chatId).presence.map((line) => line.wakeupId); + const next = KinWakeupId.make("next"); + const lane = { chatId: direct.chatId, mode: "reply", leadName: "Ada" } as const; + yield* bridge.preparing({ orgId: owner.orgId, agentId, wakeupId: next, lane, startedAt: 0 }); + assert.deepStrictEqual(shown(), [next]); + yield* bridge.end({ orgId: owner.orgId, agentId, wakeupId: next }); + assert.deepStrictEqual(shown(), []); }).pipe(Effect.provide(layer)), ); @@ -347,19 +412,20 @@ it.effect( assert.lengthOf(yield* posted, 1); const [reply] = yield* sql<{ messageId: KinMessageId }>`SELECT message_id AS "messageId" FROM kin_messages WHERE chat_id = ${direct.chatId} AND author_kind = 'agent' ORDER BY seq`; - const seen = (state: "seen" | null) => + const seen = (label: "Queued" | null) => all.pipe( Stream.filter( (event) => event.type === "presence.updated" && - (state === null ? event.presence === null : event.presence?.state === state), + (label === null ? event.presence === null : event.presence?.label === label), ), Stream.take(1), Stream.runCollect, Effect.forkScoped, ); // While the wake-up still runs (its memory commit), the owner ๐Ÿ‘Žs and withdraws it. - const shown = yield* seen("seen"); + // The wake-up still runs, so the reaction waits behind it. + const shown = yield* seen("Queued"); yield* chats.react(owner, { messageId: reply!.messageId, emoji: "๐Ÿ‘Ž", on: true }); assert.lengthOf(yield* Fiber.join(shown), 1); const gone = yield* seen(null); diff --git a/apps/server/src/kin/reply/KinReplyBridge.ts b/apps/server/src/kin/reply/KinReplyBridge.ts index 3e79610a066dd..61f931313d34a 100644 --- a/apps/server/src/kin/reply/KinReplyBridge.ts +++ b/apps/server/src/kin/reply/KinReplyBridge.ts @@ -44,11 +44,12 @@ import { draftReplyText, isToolItem, NOTE_MAX_CHARS, + PHASE_LABELS, stripTrailingSilenceMarker, toolLabel, type SegmentNext, } from "./classify.ts"; -import { KinPresence, syncSeen } from "./KinPresence.ts"; +import { KinPresence, syncQueued } from "./KinPresence.ts"; /** One rescue turn asks for the reply the run owed; its text is posted like any other. */ const RESCUE_PROMPT = @@ -116,6 +117,10 @@ type Wake = { lastOutputAt: number; state: KinPresenceState; label: string | null; + // What a stall interrupted, so the line returns to it when output resumes. + live: { readonly state: KinPresenceState; readonly label: string | null }; + // The highest item ordinal seen live: only the latest tool's end turns the line to Thinking. + latest: number; since: number; stall: Fiber.Fiber | undefined; // What the line's timer counts from: the wake-up's start, then each posted reply. @@ -135,6 +140,14 @@ export class KinReplyBridge extends Context.Service< readonly agentId: KinAgentId; readonly wakeupId: KinWakeupId; }) => Effect.Effect>; + /** A wake-up claimed its events and is preparing: its lane reads "Reading memory". */ + readonly preparing: (input: { + readonly orgId: KinOrgId; + readonly agentId: KinAgentId; + readonly wakeupId: KinWakeupId; + readonly lane: Lane; + readonly startedAt: number; + }) => Effect.Effect; /** Starts mirroring the wake-up's thread into its lane. Call before its run starts. */ readonly begin: (input: { readonly orgId: KinOrgId; @@ -167,7 +180,7 @@ export class KinReplyBridge extends Context.Service< readonly lane: Lane; readonly outcome: FailedOutcome; }) => Effect.Effect; - /** Clears the wake-up's line; `seen` stays, or comes back, where a message still waits. */ + /** Clears the wake-up's line; a queue line stays, or comes back, where a message still waits. */ readonly end: (input: { readonly orgId: KinOrgId; readonly agentId: KinAgentId; @@ -229,6 +242,11 @@ const make = Effect.gen(function* () { const scope = yield* Effect.scope; const wakes = new Map(); const byWakeup = new Map(); + // Wake-ups between their claim and `begin`, and the chat whose line they hold. + const prepared = new Map< + KinWakeupId, + { readonly orgId: KinOrgId; readonly agentId: KinAgentId; readonly chatId: KinChatId } + >(); const iso = (millis: number) => DateTime.formatIso(DateTime.makeUnsafe(millis)); const stamp = Effect.fn("KinReplyBridge.stamp")( @@ -260,6 +278,7 @@ const make = Effect.gen(function* () { if (wake.state === state && wake.label === label && since === undefined) return; wake.state = state; wake.label = label; + if (state !== "stalled") wake.live = { state, label }; wake.since = since ?? (yield* Clock.currentTimeMillis); yield* presence.set(wake.orgId, wake.lane.chatId, { agentId: wake.agentId, @@ -418,6 +437,7 @@ const make = Effect.gen(function* () { const onItem = Effect.fnUntraced(function* (wake: Wake, item: OrchestrationV2TurnItem) { const now = yield* Clock.currentTimeMillis; wake.lastOutputAt = now; + wake.latest = Math.max(wake.latest, item.ordinal); if (item.type === "assistant_message") { const segment = segmentFor(wake, item.id, item.ordinal, now); for (const earlier of pendingBefore(wake, item.ordinal)) yield* decide(wake, earlier, "text"); @@ -426,7 +446,7 @@ const make = Effect.gen(function* () { segment.ordinal = item.ordinal; if (segment.text.trim() !== "") yield* stamp(wake, "first_token_at"); if (item.streaming) { - yield* show(wake, "writing", null); + yield* show(wake, "writing", PHASE_LABELS.writing); // Drafts are append-only, so a marker shown here could not be taken back at the end. const draft = draftReplyText(segment.text); if ( @@ -448,20 +468,18 @@ const make = Effect.gen(function* () { const later = wake.tools.some((ordinal) => ordinal > segment.ordinal) ? "tool" : null; return yield* decide(wake, segment, later); } - if (item.type === "reasoning") return yield* show(wake, "thinking", null); + if (item.type === "reasoning") return yield* show(wake, "thinking", PHASE_LABELS.thinking); if (!isToolItem(item)) return; - const previousTool = Math.max(-1, ...wake.tools.filter((ordinal) => ordinal < item.ordinal)); if (!wake.tools.includes(item.ordinal)) wake.tools.push(item.ordinal); for (const earlier of pendingBefore(wake, item.ordinal)) yield* decide(wake, earlier, "tool"); - // A note written right before this call is its label; otherwise the fixed table's. - const note = wake.notes.at(-1); - yield* show( - wake, - "working", - note !== undefined && note.ordinal > previousTool && note.ordinal < item.ordinal - ? cutLabel(note.text) - : toolLabel(item), - ); + if (item.ordinal < wake.latest) return; + if (item.status === "pending" || item.status === "running" || item.status === "waiting") { + const label = toolLabel(item); + if (label !== null) yield* show(wake, "working", label); + return; + } + // The latest call ended: the model is deciding what comes next. + yield* show(wake, "thinking", PHASE_LABELS.thinking); }); const onEvent = Effect.fnUntraced(function* (event: OrchestrationV2DomainEvent) { @@ -475,8 +493,15 @@ const make = Effect.gen(function* () { if (event.type === "turn-item.updated") return yield* onItem(wake, event.payload); if (event.type === "provider-turn.updated" || event.type === "run.updated") { wake.lastOutputAt = yield* Clock.currentTimeMillis; - if (wake.state === "stalled") yield* show(wake, "working", null); + if (wake.state === "stalled") yield* show(wake, wake.live.state, wake.live.label); } + // The provider has the turn: the model is running. + if ( + event.type === "provider-turn.updated" && + event.payload.status === "running" && + wake.live.state === "starting" + ) + yield* show(wake, "thinking", PHASE_LABELS.thinking); }), ) .pipe( @@ -584,7 +609,7 @@ const make = Effect.gen(function* () { creationSource: "server", }); const run = sent.run; - yield* wake.lock.withPermits(1)(show(wake, "thinking", null)); + yield* wake.lock.withPermits(1)(show(wake, "thinking", PHASE_LABELS.thinking)); const timeoutMs = Math.max( 0, Math.min(RESCUE_TIMEOUT_MS, until - (yield* Clock.currentTimeMillis)), @@ -604,7 +629,7 @@ const make = Effect.gen(function* () { }); }); - // Ends the wake-up's line and drafts for good; `seen` lines are the queue's, not the wake-up's. + // Ends the wake-up's line and drafts for good; queue lines are the queue's, not the wake-up's. const settleLine = (wake: Wake) => wake.lock.withPermits(1)( Effect.gen(function* () { @@ -696,15 +721,50 @@ const make = Effect.gen(function* () { readonly wakeupId: KinWakeupId; }) { const { orgId, agentId, wakeupId } = input; + const held = prepared.get(wakeupId); + if (held !== undefined && held.orgId === orgId) { + prepared.delete(wakeupId); + if (byWakeup.get(wakeupId) === undefined) + yield* presence.clear(orgId, held.chatId, held.agentId); + } const wake = byWakeup.get(wakeupId); if (wake !== undefined && wake.orgId === orgId) { byWakeup.delete(wakeupId); if (wakes.get(wake.threadId) === wake) wakes.delete(wake.threadId); yield* settleLine(wake); } - yield* syncSeen(presence, orgId, agentId).pipe(Effect.provideService(SqlClient.SqlClient, sql)); + yield* syncQueued(presence, orgId, agentId).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + ); }); + const preparing = Effect.fn("KinReplyBridge.preparing")( + function* (input: { + readonly orgId: KinOrgId; + readonly agentId: KinAgentId; + readonly wakeupId: KinWakeupId; + readonly lane: Lane; + readonly startedAt: number; + }) { + if (byWakeup.has(input.wakeupId) || prepared.has(input.wakeupId)) return; + const { orgId, agentId, wakeupId, lane, startedAt } = input; + prepared.set(wakeupId, { orgId, agentId, chatId: lane.chatId }); + yield* presence.set(orgId, lane.chatId, { + agentId, + wakeupId, + state: "starting", + label: PHASE_LABELS.preparing, + startedAt: iso(startedAt), + since: iso(startedAt), + }); + // Messages in other chats now wait behind this wake-up. + yield* syncQueued(presence, orgId, agentId).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + ); + }, + Effect.catchCause((cause) => Effect.logWarning("Kin preparing line failed", { cause })), + ); + const begin = Effect.fn("KinReplyBridge.begin")( function* (input: { readonly orgId: KinOrgId; @@ -730,7 +790,9 @@ const make = Effect.gen(function* () { answered: false, lastOutputAt: now, state: "starting", - label: null, + label: PHASE_LABELS.preparing, + live: { state: "starting", label: PHASE_LABELS.preparing }, + latest: -1, since: input.startedAt, stall: undefined, timerFrom: input.startedAt, @@ -741,7 +803,8 @@ const make = Effect.gen(function* () { if (previous !== undefined) yield* end(previous); wakes.set(input.threadId, wake); byWakeup.set(input.wakeupId, wake); - yield* show(wake, "starting", null, input.startedAt); + prepared.delete(input.wakeupId); + yield* show(wake, "starting", PHASE_LABELS.preparing, input.startedAt); wake.stall = yield* watchStall(wake).pipe(Effect.forkIn(scope)); }, Effect.catchCause((cause) => Effect.logWarning("Kin reply bridge could not start", { cause })), @@ -756,6 +819,7 @@ const make = Effect.gen(function* () { return KinReplyBridge.of({ lane, + preparing, begin, complete, steered, diff --git a/apps/server/src/kin/reply/classify.ts b/apps/server/src/kin/reply/classify.ts index 5f6e530ae01cd..2c22a85ee9ac1 100644 --- a/apps/server/src/kin/reply/classify.ts +++ b/apps/server/src/kin/reply/classify.ts @@ -97,15 +97,30 @@ const TOOL_TYPES: ReadonlySet = new Set([ ]); export const isToolItem = (item: OrchestrationV2TurnItem) => TOOL_TYPES.has(item.type); -// Labels come from this table, never from the model's own words about what it is doing. -const LABELS: ReadonlyArray = [ +// The presence line's only words. Each is fixed text: never tool arguments or model text. +export const PHASE_LABELS = { + queued: "Queued", + preparing: "Reading memory", + thinking: "Thinking", + writing: "Writing", + tool: "Working", +} as const; +// Null leaves the line as it was: the call is bookkeeping, not work the owner waits on. +const TOOL_LABELS: ReadonlyArray = [ [/(?:^|__|\.)(?:memory_search|memory_read|Read|Grep|Glob)$/, "Checking memory"], + [/(?:^|__|\.)memory_\w+$/, "Updating memory"], [/(?:^|__|\.)kin_defer$/, "Setting a reminder"], [/(?:^|__|\.)kin_delegate$/, "Starting a worker"], + [/(?:^|__|\.)kin_follow_up$/, "Messaging a worker"], + [/(?:^|__|\.)kin_worker_stop$/, "Stopping a worker"], + [/(?:^|__|\.)kin_ask$/, "Preparing a question"], + [/(?:^|__|\.)kin_schedule$/, "Scheduling"], [/(?:^|__|\.)request_action$/, "Preparing a request"], + [/(?:^|__|\.)(?:kin_react|kin_journal|kin_end)$/, null], ]; -export function toolLabel(item: OrchestrationV2TurnItem): string { +export function toolLabel(item: OrchestrationV2TurnItem): string | null { if (item.type === "file_search") return "Checking memory"; const name = item.type === "dynamic_tool" ? (item.toolName ?? "") : (item.title ?? ""); - return LABELS.find(([pattern]) => pattern.test(name))?.[1] ?? "Working"; + const found = TOOL_LABELS.find(([pattern]) => pattern.test(name)); + return found === undefined ? PHASE_LABELS.tool : found[1]; } diff --git a/docs/kin/KT.md b/docs/kin/KT.md index 336e7077457c7..e7ebbaf38895c 100644 --- a/docs/kin/KT.md +++ b/docs/kin/KT.md @@ -39,7 +39,7 @@ Kin code lives in its own files. Upstream files get a hook of a line or two at m ## How a message flows 1. **Chat.** A client calls `kin.messages.send`. `KinChatService` checks membership, stores the message with the next sequence number, and calls `KinFloor.open`, which opens a floor run and grants a turn. In a direct chat that is the lead; in a group it is the mentioned agent, and with no mention it will be the group's lead (W3-1). After commit, `KinChatHub` publishes the message to every member's stream. -2. **Queue.** `ChatWake` turns the message into a `chat.message` event in `KinEventQueue` (`kin_events`) and shows "seen" at once. Triggers, worker reports and approval results become events the same way. Code sets each event's priority; an owner message is P0. +2. **Queue.** `ChatWake` turns the message into a `chat.message` event in `KinEventQueue` (`kin_events`) and shows the lead's working line ("Reading memory", or "Queued" behind a running wake-up) at once. Triggers, worker reports and approval results become events the same way. Code sets each event's priority; an owner message is P0. 3. **Wake-up.** `WakeupRunner` waits briefly for a burst to finish, then claims a batch of events for one lead and one chat. It checks the stop switch and budget, prepares a read-only memory checkout, builds the prompt (`LeadPrompt`) and runs the lead as a T3 thread. A message that arrives during a wake-up is steered into it. 4. **Lead.** The lead runs on Claude with no shell. It acts only through Kin's MCP tools: memory, deferrals, workers, cards, `request_action`. Its plain text is its reply. 5. **Reply bridge.** `KinReplyBridge` reads the lead's text as it streams and posts it through `LevelGate`, so membership, the floor and permissions apply. diff --git a/docs/kin/PLAN.md b/docs/kin/PLAN.md index 18b33f2a4fd7c..9e3056bfc72ff 100644 --- a/docs/kin/PLAN.md +++ b/docs/kin/PLAN.md @@ -22,12 +22,12 @@ The road from today's Kin to [VISION.md](VISION.md), in waves. The task ids (CHA ## Wave 0: make what exists work -| Task | Goal | Acceptance | -| ----------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | -| W0-1 Push live | Lock-screen pushes for replies, reminders and cards | With the app closed, a lead reply reaches a locked iPhone within 5 s and opens the right chat; a reminder does the same; no APNs refusals | -| W0-2 Latency | Something visible in under 1 s, first words in seconds | Stage times recorded per wake-up; p50 first visible state < 1 s, first token < 8 s cold and < 4 s warm on the host. **Merged** (#133) | -| W0-3 Live checks | Know what's broken on each surface and fix it | Checklist run on iOS, web and desktop against a seeded dev server; every failure fixed or listed. **Merged** (#134) | -| W0-4 Reply polish | Replies feel live and failures are visible | Claude drafts stream; a failed wake-up shows a notice and a retry at once; refusals name their reason; the warm provider process is reused | +| Task | Goal | Acceptance | +| ----------------- | ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | +| W0-1 Push live | Lock-screen pushes for replies, reminders and cards | With the app closed, a lead reply reaches a locked iPhone within 5 s and opens the right chat; a reminder does the same; no APNs refusals | +| W0-2 Latency | Something visible in under 1 s, first words in seconds | Stage times recorded per wake-up; p50 first visible state < 1 s, first token < 8 s cold and < 4 s warm on the host. **Merged** (#133) | +| W0-3 Live checks | Know what's broken on each surface and fix it | Checklist run on iOS, web and desktop against a seeded dev server; every failure fixed or listed. **Merged** (#134) | +| W0-4 Reply polish | Replies feel live and failures are visible | Claude drafts stream; a failed wake-up shows a notice and a retry at once; refusals name their reason; the presence line names each phase | ## Wave 1: close the loop diff --git a/docs/kin/specs/chat.md b/docs/kin/specs/chat.md index 446a782fa2d55..2f2006522604c 100644 --- a/docs/kin/specs/chat.md +++ b/docs/kin/specs/chat.md @@ -357,7 +357,7 @@ export const KinChatStreamEvent = Schema.Union([ ]); ``` -- **Reactions** (K026 `kin_reactions`) are one per member per message, WhatsApp style: picking a new emoji replaces yours in the same transaction, and picking the same one again removes it. This holds for a lead's `kin_react` too. A `backlog` carries the chat's live reactions in full, so a client replaces its set; `kin.chat.history` carries those on its page. What a reaction means is decided in code, never by the model, and only for the owner in their direct chat, on a lead message from the last day. A yes/no emoji (๐Ÿ‘ โœ… / ๐Ÿ‘Ž โŒ) on an open choice card with one `yes` and one `no` option answers it through the same compare-and-set as a tap (`via: "reaction"`). One on the lead's latest message that asks something (it contains `?`) wakes the lead as an answer. A ๐Ÿ‘Ž on any other lead message wakes it to ask, in one short line, what was wrong. Either wake is a P0 `chat.reaction` event that shows `seen`, steers into a running wake-up in that chat, and opens a floor run. It happens at most once per message and once per chat per 30 s, and withdrawing the reaction before a wake-up claims it cancels the event and its `seen`. Every other reaction is feedback: it wakes nothing and shows no presence. The next wake-up's prompt carries it as server-written lines (`Since your last turn the owner reacted ๐Ÿ‘ to: ""`), covering reactions since the lead's last completed wake-up was prompted. Approval, level, review, deferral and owner-check cards refuse reactions, so a reaction can never stand in for a signed grant. A lead reacts only through `kin_react`, in its wake-up's chat, behind the same level gate as a post. Its reaction counts as the reply only when every message the wake-up owed was the owner's text without a `?`. +- **Reactions** (K026 `kin_reactions`) are one per member per message, WhatsApp style: picking a new emoji replaces yours in the same transaction, and picking the same one again removes it. This holds for a lead's `kin_react` too. A `backlog` carries the chat's live reactions in full, so a client replaces its set; `kin.chat.history` carries those on its page. What a reaction means is decided in code, never by the model, and only for the owner in their direct chat, on a lead message from the last day. A yes/no emoji (๐Ÿ‘ โœ… / ๐Ÿ‘Ž โŒ) on an open choice card with one `yes` and one `no` option answers it through the same compare-and-set as a tap (`via: "reaction"`). One on the lead's latest message that asks something (it contains `?`) wakes the lead as an answer. A ๐Ÿ‘Ž on any other lead message wakes it to ask, in one short line, what was wrong. Either wake is a P0 `chat.reaction` event that shows the lead's working line, steers into a running wake-up in that chat, and opens a floor run. It happens at most once per message and once per chat per 30 s, and withdrawing the reaction before a wake-up claims it cancels the event and its line. Every other reaction is feedback: it wakes nothing and shows no presence. The next wake-up's prompt carries it as server-written lines (`Since your last turn the owner reacted ๐Ÿ‘ to: ""`), covering reactions since the lead's last completed wake-up was prompted. Approval, level, review, deferral and owner-check cards refuse reactions, so a reaction can never stand in for a signed grant. A lead reacts only through `kin_react`, in its wake-up's chat, behind the same level gate as a post. Its reaction counts as the reply only when every message the wake-up owed was the owner's text without a `?`. - **Live state:** `backlog` also carries the chat's current `presence` lines and open `drafts`, so a reconnect shows them at once. A draft delta appends `text` at `offset`, at most one per 250 ms per chat; a client whose draft length differs ignores deltas until `end`, the durable message, or the next backlog. Presence is sent only on change, never as a tick. `contracts/src/kinChat.ts` holds the shapes. diff --git a/docs/kin/specs/lead.md b/docs/kin/specs/lead.md index da482ab2ebe4b..a02e22cb57e97 100644 --- a/docs/kin/specs/lead.md +++ b/docs/kin/specs/lead.md @@ -7,7 +7,7 @@ Status: draft, 7 Nov 2026. Covers DESIGN.md sections 3, 4 (the `Memory` interfac A lead is a T3 thread that Kin wakes up. Each wake-up: 1. takes the next batch of events for one organization from its queue, -2. starts a provider session that loads the lead's instructions, `rules.md` and `INDEX.md` (a direct-chat conversation may continue the previous one instead; see [Warm direct-chat sessions](#warm-direct-chat-sessions)), +2. starts a provider session that loads the lead's instructions, `rules.md` and `INDEX.md` in a fresh provider process, 3. lets the lead act through Kin tools only (post, delegate, request an action, read and write memory), 4. commits memory and the journal in one git commit, and exits. @@ -217,7 +217,7 @@ Restart: recovery runs independently in each organization loop and logs failures Kin foreign keys include `org_id` so config, wake-up, worker, shadow-entry and pause relationships cannot cross organizations. K002 adds composite unique indexes on the referenced K001 identities without rewriting those records. The database enforces at most one `running` wake-up per lead with a partial unique index. Thread and run ids are nullable until launch returns; they never reference upstream tables. -Table `kin_wakeups` (**new**): `org_id, wakeup_id, agent_id, thread_id, run_id, model, started_at, ended_at, status ('running' | 'completed' | 'failed' | 'interrupted' | 'timed_out' | 'released'), event_ids, tokens_json, tools_json, memory_commit`. K028 adds the reply-latency stages as epoch ms, NULL when a stage never happened: `enqueued_at` (earliest claimed event's `queued_at`), `prepared_at`, `launched_at`, `first_token_at` (first assistant text), `posted_at` (first reply the bridge posted), plus `resumed` (1 for a warm wake-up). `started_at` is the claim. The runner logs one `Kin wake-up latency` line per wake-up; `ops/kin/host/README.md` has the p50/p90 query. +Table `kin_wakeups` (**new**): `org_id, wakeup_id, agent_id, thread_id, run_id, model, started_at, ended_at, status ('running' | 'completed' | 'failed' | 'interrupted' | 'timed_out' | 'released'), event_ids, tokens_json, tools_json, memory_commit`. K028 adds the reply-latency stages as epoch ms, NULL when a stage never happened: `enqueued_at` (earliest claimed event's `queued_at`), `prepared_at`, `launched_at`, `first_token_at` (first assistant text), `posted_at` (first reply the bridge posted). `resumed` is no longer written (warm wake-ups are gone). `started_at` is the claim. The runner logs one `Kin wake-up latency` line per wake-up; `ops/kin/host/README.md` has the p50/p90 query. Setup once per organization (`Memory.ensureCheckouts` owns the checkouts; the wake-up runner owns project bootstrap): @@ -232,7 +232,7 @@ Each wake-up: 3. Pick the model: `models.strong` if the batch holds a P0 or P1 event, a contradiction question or a `routine`; otherwise `models.cheap`. 4. `Memory.prepareWakeup(orgId)`: validate the writer (its tip matches the SQLite anchor, no unfinished git operation), build that lead's read checkout from scratch beside the old one at the anchored head and swap it in with two renames (old aside, new in), so the directory is the old checkout, the new one or briefly absent, never a mix, and rebuild `INDEX.md` first if its "As of" line is older than 36 hours. The integrity check and the default-branch sync with the remote (`Memory.syncCheckout`: `fsck`, then `ls-remote`, fetch and merge as below) run off the reply path, at start and every five minutes. The first wake-up after a start, or after a failed sync, runs that sync inline first and refuses to start while it fails, so a bad checkout is refused exactly as before; only the timing of the check moved. Network git (`ls-remote`, `fetch`, `push`) times out after 30 s, since it holds the writer lock. 5. Build the prompt (below). -6. First wake-up: `ThreadLaunchService.launch({ commandId: "kin-wakeup:", projectId, title: "", modelSelection, runtimeMode: "full-access", interactionMode: "default", workspaceStrategy: { type: "root" }, initialMessage: { text: prompt, attachments: [] }, createdBy: "system", creationSource: "server" })`, then store `threadId` on `KinLead`. Later wake-ups: `ThreadManagementService.sendToThread({ commandId, threadId, messageId: "kin-wakeup-msg:", text: prompt, mode: "queue", freshContext: true, modelSelection, createdBy: "system", creationSource: "server" })`, without `freshContext` for a warm wake-up. One thread holds the lead's history for people to read; every wake-up starts a fresh provider process with its cwd set to the read clone, as LEAD-3 requires. +6. First wake-up: `ThreadLaunchService.launch({ commandId: "kin-wakeup:", projectId, title: "", modelSelection, runtimeMode: "full-access", interactionMode: "default", workspaceStrategy: { type: "root" }, initialMessage: { text: prompt, attachments: [] }, createdBy: "system", creationSource: "server" })`, then store `threadId` on `KinLead`. Later wake-ups: `ThreadManagementService.sendToThread({ commandId, threadId, messageId: "kin-wakeup-msg:", text: prompt, mode: "queue", freshContext: true, modelSelection, createdBy: "system", creationSource: "server" })`. One thread holds the lead's history for people to read; every wake-up starts a fresh provider process with its cwd set to the read clone, as LEAD-3 requires. 7. Register the durable lead thread through `KinIdentity.registerAgentThread` before launching or sending; keep it registered between wake-ups and call `endAgentThread` on retirement. `KinIdentity.resolveAgent` and the `insertMessage` write transaction additionally require a persisted running wake-up matching the org, agent and server-resolved caller thread, whose active run belongs to the wake-up (including restart and usage-limit continuations), whose root is exactly `kin_wakeups.run_id` when recorded, otherwise the lowest-ordinal run on that thread with `kin-wakeup-msg:`. The wake-up also adopts later runs whose root message is `kin-steer-msg::` (a late steer) or `kin-rescue-msg:` (the reply rescue), with an ordinal above the recorded `run_id`; the helpers live in `KinIdentity.ts`. Its persisted message, including an adopted run's, must belong to that root and have `createdBy=system` and `creationSource=server`, and every continuation's message must have `createdBy=agent` and `creationSource=server`. Other paths can produce that provenance (server notification wakes, and client-written scheduled tasks, whose upsert accepts `createdBy`/`creationSource`), but none of them sets a restart or usage-limit continuation link: client dispatches that set one are forced to `createdBy=user`, so only the server's recovery workers produce both. The id itself is client-suppliable, and durable registration is not authority outside a wake-up. Webhook inbox threads (`kin_webhook_sources.inbox_thread_id`) cannot be registered, even across organizations. Register `threadId โ†’ { orgId, agentId, wakeupId, level }` in `KinLeadRegistry`, a scoped overlap guard, not a tool authority source. It is filled before the first launch or later send and cleared after the run ends, including interruption. Retired leads never launch: their queued events become `expired` and their durable thread registration is ended. Launch/send do not expose a preassigned run id or pre-execution callback; early tool calls before the runner records `run_id` are allowed under the lowest-ordinal root rule. @@ -241,11 +241,7 @@ Known input-integrity gap: clients can steer an active wake-up with `steer_activ 8. `waitForThread({ threadId, runId, timeoutMs })` until the deadline: 15 minutes, extended by steers (see coalescing). When the run ends, the runner waits for any adopted steer run that is still queued or active. On timeout, `interruptThread`, wait up to 30 seconds for the run to settle, then capture usage and mark `timed_out`. If it has not settled, log that it may continue; captured usage is a snapshot, not a final total. Closing the runner scope interrupts and requeues unfinished wake-ups without counting an attempt. 9. Finish: `Memory.commitWakeup` (one commit holding the staged item writes and the journal entry), reset the read checkout, record token usage from the run's provider turns into `kin_wakeups.tokens_json` and `KinBudget`, mark events `done`, and `settleThread`. -#### Warm direct-chat sessions - -A wake-up whose events all come from one `direct` chat may continue the previous wake-up's provider conversation instead of starting a fresh one, which saves reloading rules, the index and recent chat. It continues only when the previous wake-up was for the same organization, lead, thread and chat, at the same level and model selection, completed, ended less than 10 minutes before this one started, and the session has had fewer than 10 wake-ups. Anything else starts fresh: another chat or any non-chat event in the batch, a level or model change, changed `rules.md`, a failed, timed-out or stopped wake-up, or a server restart (the session record lives only in the runner's memory). Every wake-up still claims, admits, renews floor grants, commits memory and the journal, charges its own runs and finishes on its own. - -A warm wake-up sends the run without `freshContext`, so the orchestrator stays on the same provider thread. Since `prepareWakeup` swapped in a new read checkout, the runner releases the idle provider process before the warm send (`ProviderSessionManagerV2.releaseUnlessBusy`), and stays cold when it can't; the next run then opens a new process in the new checkout that resumes the conversation: the Claude adapter passes the SDK's `resume: ` once the native thread has a persisted turn. The message omits the rules (unchanged by definition), says the index is unchanged or quotes only the added and removed index lines, and lists only chat messages after the last seq the session saw, excluding the lead's own. The divider and everything below it are as in a cold wake-up. +Every wake-up is cold: a message arrives, a wake-up starts a fresh provider process with fresh context and the full prompt, and it ends. No provider session or process is kept between wake-ups. If the lead writes files by hand in the read checkout, step 9's reset throws the changes away. A non-empty `git status --porcelain` before the reset is logged in the journal as "Lead edited memory files directly; discarded." @@ -316,7 +312,9 @@ The `/kin/mcp` endpoint deliberately exposes only Kin tools, never T3 tools (inc ### Replies -A lead's plain text is its reply. The reply bridge (`kin/reply/KinReplyBridge.ts`) reads the lead thread's assistant text, from the live orchestration stream (the Claude adapter streams `text_delta`s as they are written, so a draft grows live) and, when the run ends, from its projection, and posts it through `KinLevelGate.post` with the server's own identity for the running wake-up (`KinIdentity.agentForWakeup`), so membership, mute, the floor, notice limits and L0 shadowing apply exactly as to `kin_chat_post`. Routing comes from stored rows: a wake-up's text goes to the chat of its highest-priority claimed human message or card tap, else to `ownerChatId` as a notice, where `NO_REPLY` posts nothing. Plain code classifies each segment: long or structured text posts; a short single-paragraph segment followed by a tool call is a status note shown only on the presence line. Each segment posts once by `clientMessageId` `reply:`. Presence and drafts are live only. `ChatWake` shows `seen` as soon as a human message, card tap or waking reaction is queued for the lead, unless the lead already shows a line in that chat; a wake-up's `begin` replaces it with `starting`. Once the run's reply is settled, its line clears, so the memory commit after it never reads as work on the owner's message, and work after a posted reply restarts the line's timer. Whenever queued chat events leave without a wake-up taking them (a wake-up's end, a withdrawn reaction, a resume that expires them), `seen` stays only in chats where a ready one still waits. A message steered into a notice wake-up makes it owe a reply in the same chat. +A lead's plain text is its reply. The reply bridge (`kin/reply/KinReplyBridge.ts`) reads the lead thread's assistant text, from the live orchestration stream (the Claude adapter streams `text_delta`s as they are written, so a draft grows live) and, when the run ends, from its projection, and posts it through `KinLevelGate.post` with the server's own identity for the running wake-up (`KinIdentity.agentForWakeup`), so membership, mute, the floor, notice limits and L0 shadowing apply exactly as to `kin_chat_post`. Routing comes from stored rows: a wake-up's text goes to the chat of its highest-priority claimed human message or card tap, else to `ownerChatId` as a notice, where `NO_REPLY` posts nothing. Plain code classifies each segment: long or structured text posts; a short single-paragraph segment followed by a tool call is a status note, kept for the journal and the owed-reply fallback, never shown. Each segment posts once by `clientMessageId` `reply:`. Presence and drafts are live only. + +The presence line says what the lead is doing from the moment a message is accepted; there is no `seen` for a lead. Its words come only from `PHASE_LABELS` and the tool table in `kin/reply/classify.ts`, never from tool arguments, model text or user text, and the server sends an update only when the state or label changes. `ChatWake` shows a `starting` line as soon as a human message, card tap or waking reaction is queued, unless a wake-up already shows one in that chat: "Queued" while the lead runs a wake-up, else "Reading memory". The claim (`KinReplyBridge.preparing`) takes the lane's line for its wake-up as "Reading memory" and relabels lines in other chats "Queued"; then "Thinking" once the provider turn runs and after each tool call ends; a tool's own label while it runs ("Checking memory", "Updating memory", "Setting a reminder", "Starting a worker", "Messaging a worker", "Preparing a question", "Scheduling", "Working" for an unknown tool; `kin_react`, `kin_journal` and `kin_end` leave the line as it was); "Writing" while text streams. A stall shows no output and returns to the interrupted label when output resumes. Once the run's reply is settled, its line clears, so the memory commit after it never reads as work on the owner's message, and work after a posted reply restarts the line's timer; a late event never brings it back. Whenever queued chat events leave or a wake-up ends (a withdrawn reaction, a resume that expires them, a wake-up that never began), a queue line stays only in chats where a ready one still waits. Clients show `seen` from older servers as no line. A message steered into a notice wake-up makes it owe a reply in the same chat. Create deferrals only with `kin_defer`. Use `memory_write` update/invalidate on a stored deferral to change only `status` (`done`/`cancelled`) and `invalid_at`. The server preserves `chat`, `source_event`, `what` and `on_due`; attempts to change them are refused. Closing or cancelling disarms the deferral. @@ -634,7 +632,7 @@ Upstream files touched, one line each: - Coalescing: 20 relevant `github` events within the two-minute notice window produce one `kin_wakeups` row holding 20 event ids; memory-repository and untracked traffic never enter that queue. - One writer: two events 1 s apart in different lanes while a wake-up runs give two serial wake-ups, never overlapping (assert on `started_at` and `ended_at`); a human message in the running lane is steered into it instead. - Fresh session: the second wake-up's run has a different provider thread id from the first, and its prompt holds no text from the first run (`DeterministicRuntime`). -- Warm session: direct-chat wake-ups less than 10 idle minutes apart share one provider thread for 10 wake-ups, keeping its idle process and each committing memory; the 11th, one after 10 idle minutes, one in another chat, one after a permission change and one after new rules each start fresh. +- Fresh sessions: back-to-back wake-ups in one direct chat, at one level and model, each start a new provider conversation with the full prompt and each commit memory. - Prompt prefix: two prompts at the same memory commit are byte-identical above the divider. - Tool visibility: a non-lead thread's tool list has no `kin_*` or `memory_*` tools; `AgentContextBudget.test.ts` passes unchanged. - Cross-organization: a lead thread registered for org A cannot read or write org B memory, whatever ids it passes. @@ -715,7 +713,7 @@ LEAD-14. Withdrawn (owner, 10 Nov 2026): there is no shadow week to rehearse. Operators or owners can call server-only `Memory.recover(orgId)` after losing a writer or to reconcile its anchors. It fetches remote main and shadow heads, keeps and pushes an anchored shadow head the remote lacks or that fast-forwards the remote's (a refused push leaves the lead's only copy here), preserves other surviving unpushed anchored work on a conflict branch, recreates a missing writer, records remote anchors and notifies. This method must never be registered as an agent tool. For writers predating K011 anchors, stop the runner and delete only that organization's writer directory, then bootstrap again. Do not delete anchored writers to recover unpushed work; call `recover` first. Recovery cannot restore commits lost with a deleted writer before they reached any remote. -Each prepare swaps in a new read checkout, so no provider process outlives it in its cwd. A cold wake-up starts fresh context; a warm direct-chat wake-up releases the lead's idle process and resumes the conversation in a new one. +Each prepare swaps in a new read checkout, so no provider process outlives it in its cwd. Every wake-up starts fresh context in a new process. **Running on the Kin host.** System, global and repository git config are excluded, so memory git never sees the host's credentials. `MemoryConfig.layer` reads `KIN_MEMORY_CREDENTIAL_HELPER` (a helper name or absolute path, for HTTPS) and `KIN_MEMORY_SSH_COMMAND` (an ssh command naming its key file, for SSH) and every memory clone, fetch and push uses them; a value that fails `purgePush.ts`'s reference checks fails Kin startup, naming the variable but not the value. They go to memory git only, as `-c credential.helper` and `GIT_SSH_COMMAND`; a server-wide `GIT_SSH_COMMAND` would reach every agent's git. Repository credential helpers cannot override them. Configure the Kin host's dedicated server user and credentials before enabling writes; never put credentials in memory, repository config, or lead instructions. See also โ€œRunning on the Kin hostโ€ in `triggers.md`. diff --git a/ops/kin/host/README.md b/ops/kin/host/README.md index 462ab10e649b2..31e9331873e16 100644 --- a/ops/kin/host/README.md +++ b/ops/kin/host/README.md @@ -129,7 +129,7 @@ Only attested keys are listed. A simulator, or a phone that couldn't prove its k ## Reply latency -Each wake-up logs one `Kin wake-up latency` line with every stage's ms since its first message was queued: claimed, memory prepared, provider launched, first token, reply posted, and whether it was warm. For p50 and p90 over the last 20 owner-message wake-ups, read the database without writing to it: +Each wake-up logs one `Kin wake-up latency` line with every stage's ms since its first message was queued: claimed, memory prepared, provider launched, first token, reply posted. Wake-ups from before warm sessions were removed still group as `warm`. For p50 and p90 over the last 20 owner-message wake-ups, read the database without writing to it: ```bash sqlite3 -readonly ~/.t3/userdata/statev2.sqlite " @@ -156,7 +156,7 @@ SELECT CASE warm WHEN 1 THEN 'warm' ELSE 'cold' END AS session, stage, c AS wake FROM r GROUP BY warm, stage ORDER BY warm, stage;" ``` -`seen` shows in the chat as soon as the message is queued, before any of these stages. +The lead's working line shows in the chat as soon as the message is queued, before any of these stages. ## Workers diff --git a/packages/client-runtime/src/kin/kinChatFeed.test.ts b/packages/client-runtime/src/kin/kinChatFeed.test.ts index a0b4a86f25970..bcb212d72bcfc 100644 --- a/packages/client-runtime/src/kin/kinChatFeed.test.ts +++ b/packages/client-runtime/src/kin/kinChatFeed.test.ts @@ -471,6 +471,8 @@ describe("kinPresenceLine", () => { ); expect(text(presence({ state: "working", label: "x".repeat(80) }), 0)).toHaveLength(60); expect(kinPresenceNeedsClock(presence({ state: "working" }))).toBe(false); + // Older servers' `seen` shows nothing: the line starts with the wake-up's own state. + expect(kinPresenceLine(presence({ state: "seen", wakeupId: null }), start)).toBeNull(); }); it("shows a slow start's wait after 20 s, announcing it once", () => { @@ -482,6 +484,11 @@ describe("kinPresenceLine", () => { kinPresenceLine(starting, start + 35_000)?.announcement, ); expect(kinPresenceNeedsClock(starting)).toBe(true); + const queued = presence({ state: "starting", label: "Queued", wakeupId: null }); + expect(text(queued, KIN_SLOW_START_AFTER_MS - 1)).toBe("Queued"); + expect(text(queued, 65_000)).toBe("Queued ยท 1:05"); + expect(kinPresenceLine(queued, start + 65_000)?.announcement).toBe("Queued"); + expect(kinPresenceNeedsClock(queued)).toBe(true); }); it("counts a stall's minutes from the last output, never under 2", () => { diff --git a/packages/client-runtime/src/kin/kinChatFixtures.ts b/packages/client-runtime/src/kin/kinChatFixtures.ts index b5ae9cef345a7..db990948fc7cc 100644 --- a/packages/client-runtime/src/kin/kinChatFixtures.ts +++ b/packages/client-runtime/src/kin/kinChatFixtures.ts @@ -174,9 +174,9 @@ export function kinFixtureReplyScript( createdAt: iso(doneMs), }; return [ - presence(0, "thinking"), + presence(0, "thinking", "Thinking"), presence(1_500, "working", "Checking memory"), - presence(3_500, "writing"), + presence(3_500, "writing", "Writing"), ...deltas, { atMs: doneMs, event: { _tag: "message", message } }, { diff --git a/packages/client-runtime/src/kin/kinLive.ts b/packages/client-runtime/src/kin/kinLive.ts index bbb6edfbc4a85..bb32c2f66c360 100644 --- a/packages/client-runtime/src/kin/kinLive.ts +++ b/packages/client-runtime/src/kin/kinLive.ts @@ -129,12 +129,14 @@ export interface KinPresenceLine { readonly stalled: boolean; /** Short form for the header subtitle. */ readonly subtitle: string; - /** Pulsing dots while the lead has only seen or is starting, a shimmer while it works. */ + /** Pulsing dots while the lead is queued or starting, a shimmer while it works. */ readonly motion: "dots" | "shimmer" | "still"; } -const MOTION: Record = { - seen: "dots", +// `seen` comes only from older servers; a lead's line then waits for its wake-up. +type ShownState = Exclude; + +const MOTION: Record = { starting: "dots", thinking: "shimmer", working: "shimmer", @@ -152,8 +154,7 @@ const elapsed = (ms: number) => { return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; }; -const DEFAULT_TEXT: Record, string> = { - seen: "Seen", +const DEFAULT_TEXT: Record, string> = { starting: "Startingโ€ฆ", thinking: "Thinkingโ€ฆ", working: "Workingโ€ฆ", @@ -170,7 +171,7 @@ export function kinPresenceLine( presence: KinPresence | undefined, now: number, ): KinPresenceLine | null { - if (presence === undefined) return null; + if (presence === undefined || presence.state === "seen") return null; if (presence.state === "stalled") { const minutes = Math.max(2, Math.floor((now - Date.parse(presence.since)) / 60_000)); return { @@ -190,10 +191,10 @@ export function kinPresenceLine( subtitle: text, motion: MOTION[presence.state], }; - if (presence.state !== "starting" || label) return line; + if (presence.state !== "starting") return line; const waited = now - Date.parse(presence.startedAt); return waited >= KIN_SLOW_START_AFTER_MS - ? { ...line, text: `Starting ยท ${elapsed(waited)}` } + ? { ...line, text: `${label ? clip(label) : "Starting"} ยท ${elapsed(waited)}` } : line; } @@ -211,5 +212,5 @@ export function kinPresenceTimerStart(presence: KinPresence | undefined): string /** Whether the line reads differently as time passes, so it needs the clock. */ export function kinPresenceNeedsClock(presence: KinPresence | undefined): boolean { - return presence?.state === "stalled" || (presence?.state === "starting" && !presence.label); + return presence?.state === "stalled" || presence?.state === "starting"; } diff --git a/packages/contracts/src/kinChat.ts b/packages/contracts/src/kinChat.ts index 3d7c01950cda5..e90eaa6a1f018 100644 --- a/packages/contracts/src/kinChat.ts +++ b/packages/contracts/src/kinChat.ts @@ -243,6 +243,7 @@ export const KinChoiceCardState = Schema.Struct({ export type KinChoiceCardState = typeof KinChoiceCardState.Type; export const KinPresenceState = Schema.Literals([ + // Older servers only; clients show no line for it. "seen", "starting", "thinking", @@ -262,8 +263,8 @@ export const KinPresence = Schema.Struct({ agentId: KinAgentId, wakeupId: Schema.NullOr(KinWakeupId), state: KinPresenceState, - // A fixed label ("Checking memory"), a short note from the agent, or a refusal - // ("Couldn't post: notice limit"), at most 60 characters. + // What the agent is doing, from the server's fixed table ("Reading memory", "Setting a + // reminder") or a refusal ("Couldn't post: limit"); never model or user text. At most 60. label: Schema.NullOr(KinText.check(Schema.isMaxLength(60))), startedAt: IsoDateTime, since: IsoDateTime, From a7bd91ec95a9854b6397b0ab131a7e170300a57c Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:37:28 +0530 Subject: [PATCH 2/2] feat(kin): label the new GitHub read and cancel tools on the presence line Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/reply/classify.ts | 2 ++ docs/kin/specs/lead.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/server/src/kin/reply/classify.ts b/apps/server/src/kin/reply/classify.ts index 2c22a85ee9ac1..57cf1fcb65f0d 100644 --- a/apps/server/src/kin/reply/classify.ts +++ b/apps/server/src/kin/reply/classify.ts @@ -115,6 +115,8 @@ const TOOL_LABELS: ReadonlyArray = [ [/(?:^|__|\.)kin_worker_stop$/, "Stopping a worker"], [/(?:^|__|\.)kin_ask$/, "Preparing a question"], [/(?:^|__|\.)kin_schedule$/, "Scheduling"], + [/(?:^|__|\.)kin_cancel$/, "Cancelling a reminder"], + [/(?:^|__|\.)kin_github_\w+$/, "Checking GitHub"], [/(?:^|__|\.)request_action$/, "Preparing a request"], [/(?:^|__|\.)(?:kin_react|kin_journal|kin_end)$/, null], ]; diff --git a/docs/kin/specs/lead.md b/docs/kin/specs/lead.md index 93ed6deff8a00..82e3b9fb48668 100644 --- a/docs/kin/specs/lead.md +++ b/docs/kin/specs/lead.md @@ -321,7 +321,7 @@ The `kin_github_*` tools (`github/KinRepoReads.ts`) let a lead answer PR and CI A lead's plain text is its reply. The reply bridge (`kin/reply/KinReplyBridge.ts`) reads the lead thread's assistant text, from the live orchestration stream (the Claude adapter streams `text_delta`s as they are written, so a draft grows live) and, when the run ends, from its projection, and posts it through `KinLevelGate.post` with the server's own identity for the running wake-up (`KinIdentity.agentForWakeup`), so membership, mute, the floor, notice limits and L0 shadowing apply exactly as to `kin_chat_post`. Routing comes from stored rows: a wake-up's text goes to the chat of its highest-priority claimed human message or card tap, else to `ownerChatId` as a notice, where `NO_REPLY` posts nothing. Plain code classifies each segment: long or structured text posts; a short single-paragraph segment followed by a tool call is a status note, kept for the journal and the owed-reply fallback, never shown. Each segment posts once by `clientMessageId` `reply:`. Presence and drafts are live only. -The presence line says what the lead is doing from the moment a message is accepted; there is no `seen` for a lead. Its words come only from `PHASE_LABELS` and the tool table in `kin/reply/classify.ts`, never from tool arguments, model text or user text, and the server sends an update only when the state or label changes. `ChatWake` shows a `starting` line as soon as a human message, card tap or waking reaction is queued, unless a wake-up already shows one in that chat: "Queued" while the lead runs a wake-up, else "Reading memory". The claim (`KinReplyBridge.preparing`) takes the lane's line for its wake-up as "Reading memory" and relabels lines in other chats "Queued"; then "Thinking" once the provider turn runs and after each tool call ends; a tool's own label while it runs ("Checking memory", "Updating memory", "Setting a reminder", "Starting a worker", "Messaging a worker", "Preparing a question", "Scheduling", "Working" for an unknown tool; `kin_react`, `kin_journal` and `kin_end` leave the line as it was); "Writing" while text streams. A stall shows no output and returns to the interrupted label when output resumes. Once the run's reply is settled, its line clears, so the memory commit after it never reads as work on the owner's message, and work after a posted reply restarts the line's timer; a late event never brings it back. Whenever queued chat events leave or a wake-up ends (a withdrawn reaction, a resume that expires them, a wake-up that never began), a queue line stays only in chats where a ready one still waits. Clients show `seen` from older servers as no line. A message steered into a notice wake-up makes it owe a reply in the same chat. +The presence line says what the lead is doing from the moment a message is accepted; there is no `seen` for a lead. Its words come only from `PHASE_LABELS` and the tool table in `kin/reply/classify.ts`, never from tool arguments, model text or user text, and the server sends an update only when the state or label changes. `ChatWake` shows a `starting` line as soon as a human message, card tap or waking reaction is queued, unless a wake-up already shows one in that chat: "Queued" while the lead runs a wake-up, else "Reading memory". The claim (`KinReplyBridge.preparing`) takes the lane's line for its wake-up as "Reading memory" and relabels lines in other chats "Queued"; then "Thinking" once the provider turn runs and after each tool call ends; a tool's own label while it runs ("Checking memory", "Updating memory", "Setting a reminder", "Starting a worker", "Messaging a worker", "Preparing a question", "Scheduling", "Cancelling a reminder", "Checking GitHub", "Working" for an unknown tool; `kin_react`, `kin_journal` and `kin_end` leave the line as it was); "Writing" while text streams. A stall shows no output and returns to the interrupted label when output resumes. Once the run's reply is settled, its line clears, so the memory commit after it never reads as work on the owner's message, and work after a posted reply restarts the line's timer; a late event never brings it back. Whenever queued chat events leave or a wake-up ends (a withdrawn reaction, a resume that expires them, a wake-up that never began), a queue line stays only in chats where a ready one still waits. Clients show `seen` from older servers as no line. A message steered into a notice wake-up makes it owe a reply in the same chat. Create deferrals only with `kin_defer`, and cancel one with `kin_cancel`. Use `memory_write` update/invalidate on a stored deferral to change only `status` (`done`/`cancelled`) and `invalid_at`. The server preserves `chat`, `source_event`, `what` and `on_due`; attempts to change them are refused. Closing or cancelling disarms the deferral.