Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions apps/server/src/kin/cli/lead.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,9 @@ const charterFlag = Flag.String("charter").pipe(

const workerProjectsFlag = Flag.String("worker-project").pipe(
Flag.withSchema(ProjectId),
Flag.withDescription("A project the lead's workers may run in. Repeat for more."),
Flag.withDescription(
"A project the lead is held to in chats its owner didn't put it in. Repeat for more. The owner's own chats with it reach every repository in the worker environment.",
),
Flag.atLeast(0),
);

Expand Down Expand Up @@ -270,7 +272,7 @@ const projectsCommand = Command.make("projects", {
json: jsonFlag,
}).pipe(
Command.withDescription(
"Replace a live lead's worker projects. Pass none to clear them. Applies to its next tool call.",
"Replace the projects a live lead is held to in chats its owner didn't put it in. Pass none to clear them. Applies to its next tool call.",
),
Command.withHandler((flags) =>
runOnHost(flags, (provision) =>
Expand Down
412 changes: 412 additions & 0 deletions apps/server/src/kin/lead/Handoff.test.ts

Large diffs are not rendered by default.

355 changes: 355 additions & 0 deletions apps/server/src/kin/lead/Handoff.ts

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion apps/server/src/kin/lead/KinEventQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,10 @@ const make = Effect.gen(function* () {
case "chat.message":
case "widget.action":
case "chat.reaction":
if (event.provenance._tag === "human") {
// The owner's request, passed on by another lead: it waits its turn as a due
// reminder does, and never jumps the budget as the owner's own message would.
if (event._tag === "chat.message" && event.origin !== undefined) priority = "P1";
else if (event.provenance._tag === "human") {
const owners = yield* sql`
SELECT 1 FROM kin_chat_members
WHERE org_id = ${event.orgId} AND chat_id = ${event.chatId}
Expand Down
46 changes: 38 additions & 8 deletions apps/server/src/kin/lead/KinLevels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export const effectiveLevel = Effect.fn("KinLevels.effectiveLevel")(function* (i

export const lowest = (a: KinLevel, b: KinLevel) => (atLeast(a, b) ? b : a);

/** The chat a due deferral was asked from, and the lead that was asked there. */
/** The chat a due deferral or a passed-on request was first asked in, and the lead asked there. */
export interface KinOrigin {
readonly agentId: KinAgentId;
readonly chatId: KinChatId;
Expand All @@ -109,23 +109,53 @@ export const originLevel = (orgId: KinOrgId, origin: KinOrigin) =>
);

/**
* The lowest level of the chats the wake-up's due deferrals were asked from, or undefined when
* none was asked from outside its owner chat. Read from the stored events only.
* Whether the lead's owner placed it in `chatId` (`ownerPlacedSql`). False for a retired lead or a
* chat in another org.
*/
export const originCap = Effect.fn("KinLevels.originCap")(function* (input: {
export const ownerPlaced = Effect.fn("KinLevels.ownerPlaced")(function* (
orgId: KinOrgId,
origin: KinOrigin,
) {
const sql = yield* SqlClient.SqlClient;
const [row] = yield* sql<{ ownerPlaced: number }>`
SELECT ${ownerPlacedSql(sql, origin.chatId)} AS "ownerPlaced" FROM kin_leads l
JOIN kin_agents a ON a.org_id = l.org_id AND a.agent_id = l.agent_id
WHERE l.org_id = ${orgId} AND l.agent_id = ${origin.agentId}
AND a.role = 'lead' AND a.retired_at IS NULL
ORDER BY l.agent_id`.pipe(Effect.mapError(toPersistenceSqlError("KinLevels.ownerPlaced")));
return row?.ownerPlaced === 1;
});

/**
* The chats the wake-up's due deferrals and passed-on requests were first asked in, read from the
* stored events only. Both the level cap and worker reach read this, so neither can drop one.
*/
export const origins = Effect.fn("KinLevels.origins")(function* (input: {
readonly orgId: KinOrgId;
readonly agentId: KinAgentId;
readonly wakeupId: string;
}) {
const sql = yield* SqlClient.SqlClient;
const origins = yield* sql<{ agentId: KinAgentId; chatId: KinChatId }>`
return yield* sql<KinOrigin>`
SELECT DISTINCT json_extract(json, '$.origin.agentId') AS "agentId",
json_extract(json, '$.origin.chatId') AS "chatId" FROM kin_events
WHERE org_id = ${input.orgId} AND agent_id = ${input.agentId} AND wakeup_id = ${input.wakeupId}
AND tag = 'deferral.due' AND json_extract(json, '$.origin.chatId') IS NOT NULL
ORDER BY 1, 2`.pipe(Effect.mapError(toPersistenceSqlError("KinLevels.originCap")));
AND tag IN ('deferral.due', 'chat.message')
AND json_extract(json, '$.origin.chatId') IS NOT NULL
Comment on lines +143 to +144

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Isolate origin-capped handoffs from ordinary owner-message batches

If a handoff from an L0/L1 chat and a direct owner request are queued for the receiving lead together, the new origin cap also downgrades the unrelated owner request and prevents work that its own L2 chat permits. KinEventQueue.LANE_OF assigns every chat.message its destination chat, so claim batches these events together; steer can likewise add an owner's message to a running handoff wake-up. This query then applies the handoff's lower cap to the entire wake-up. Give origin-bearing handoffs an isolated lane, as origin-bearing deferral.due events already have, so their restrictions do not consume otherwise-authorized owner requests.

Useful? React with 👍 / 👎.

ORDER BY 1, 2`.pipe(Effect.mapError(toPersistenceSqlError("KinLevels.origins")));
});

/**
* The lowest level of the chats the wake-up's due deferrals and passed-on requests were first
* asked in, or undefined when none was asked outside its owner chat.
*/
export const originCap = Effect.fn("KinLevels.originCap")(function* (input: {
readonly orgId: KinOrgId;
readonly agentId: KinAgentId;
readonly wakeupId: string;
}) {
let cap: KinLevel | undefined;
for (const origin of origins) {
for (const origin of yield* origins(input)) {
const level = yield* originLevel(input.orgId, origin);
cap = cap === undefined ? level : lowest(cap, level);
}
Expand Down
4 changes: 4 additions & 0 deletions apps/server/src/kin/lead/LeadMemory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import * as Writer from "../memory/MemoryWriter.ts";
import * as Scan from "../memory/secretScan.ts";
import * as TriggerService from "../triggers/KinTriggerService.ts";
import { fixtureItem } from "../memory/__fixtures__/items.ts";
import { KinHandoff } from "./Handoff.ts";
import * as Lead from "./LeadMemory.ts";
import { KinWorkers } from "./Workers.ts";
import * as KinRepoReads from "../github/KinRepoReads.ts";
Expand Down Expand Up @@ -77,6 +78,7 @@ const client = McpSchema.McpServerClient.of({
const registration = McpHttpServer.toolkitRegistration(KinLeadToolkit, handlers).pipe(
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
Layer.provide(Layer.mock(KinWorkers)({})),
Layer.provide(Layer.mock(KinHandoff)({})),
Layer.provide(KinRepoReads.notConnectedLayer),
Layer.provide(
Layer.mock(Threads.ThreadManagementService)({
Expand Down Expand Up @@ -297,6 +299,8 @@ it.live(
"kin_delegate",
"kin_follow_up",
"kin_worker_stop",
"kin_leads",
"kin_hand_off",
"kin_ask",
"kin_react",
"memory_search",
Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/kin/lead/LeadPrompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,8 @@ function boundedRecent(
}
return quoteLines("recent chat", lines.toReversed());
}
const messageBodyLimit = 8_000;
/** The most of a message body a lead is shown; past it the prompt cuts the text. */
export const messageBodyLimit = 8_000;
const textFieldLimit = 2_000;
const eventsLimit = 60_000;

Expand Down
Loading