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
33 changes: 18 additions & 15 deletions apps/room-web/app/room-lab/application/ports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export interface TurnLog {
* re-serve their tools on the same one, so the URL the agent's `session/new`
* holds stays valid for the session's life.
*/
export interface RoomToolHostInput {
interface RoomToolHostInput {
agentId: RoomLabAgentId;
/** This activation's Room tools; they replace whatever the endpoint serves. */
tools: ToolDefinition[];
Expand Down Expand Up @@ -143,7 +143,7 @@ export type RoomSettingsReader = () => RoomSettings;
* points are `RoomStreamStore` (admit, speak, pass, readSlice); the registry is
* the control plane's roster port; the turn contract lives in `./turn`.
*/
export type { RoomStreamStore, ToolDefinition, TurnHarness, TurnPermissionPolicy, TurnResult };
export type { ToolDefinition, TurnHarness, TurnPermissionPolicy, TurnResult };

/**
* The record plus the session side-channels the turn reads it with: the
Expand Down Expand Up @@ -208,18 +208,21 @@ export interface RoomRound {
* and hands the post to the child room's dispatcher. The host owns it, because
* the child room is outside this service's own record.
*/
/** What opening (or reusing) the pair's private room is asked with. */
export interface RoomDmOpenInput {
parentRoomId: string;
from: RoomLabAgentId;
to: RoomLabAgentId;
body: string;
/** The waking event's depth; the child post carries one more. */
triggerDepth: number;
/** The parent event whose activation opened or reused the room. */
triggerSeq: number;
/** The round the exchange's turns charge, rooted in this room. */
roundRoomId: string;
roundSeq: number;
}

export interface RoomDmGateway {
open(input: {
parentRoomId: string;
from: RoomLabAgentId;
to: RoomLabAgentId;
body: string;
/** The waking event's depth; the child post carries one more. */
triggerDepth: number;
/** The parent event whose activation opened or reused the room. */
triggerSeq: number;
/** The round the exchange's turns charge, rooted in this room. */
roundRoomId: string;
roundSeq: number;
}): Promise<{ roomId: string; seq: number }>;
open(input: RoomDmOpenInput): Promise<{ roomId: string; seq: number }>;
}
14 changes: 3 additions & 11 deletions apps/room-web/app/room-lab/application/room-dm.server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { RoomEvent } from '@rivus/agent-room';
import type { RoomLabAgentId } from '../domain/agent-registry';
import type { RoomDmOpenInput } from './ports';
import { copy } from '../copy';
import { newRoomIdentity } from '../infrastructure/room-home.server';
import type { RoomRecordStore, RoomRound } from './ports';
Expand All @@ -12,7 +13,7 @@ import type { RoomRecordStore, RoomRound } from './ports';
* round spans the private rooms opened inside it). The record stamps the seq,
* which is why the parse reads five parts.
*/
export function dmMessageId(round: RoomRound, triggerSeq: number): string {
function dmMessageId(round: RoomRound, triggerSeq: number): string {
return `dm:${round.roomId}:${round.seq}:${triggerSeq}`;
}

Expand Down Expand Up @@ -68,16 +69,7 @@ export interface RoomDmDeps {
export class RoomDm {
constructor(private readonly deps: RoomDmDeps) {}

async open(input: {
parentRoomId: string;
from: RoomLabAgentId;
to: RoomLabAgentId;
body: string;
triggerDepth: number;
triggerSeq: number;
roundRoomId: string;
roundSeq: number;
}): Promise<{ roomId: string; seq: number }> {
async open(input: RoomDmOpenInput): Promise<{ roomId: string; seq: number }> {
const pair = [input.from, input.to].sort();
const round: RoomRound = { roomId: input.roundRoomId, seq: input.roundSeq };
const found = this.deps.findPrivate(input.parentRoomId, pair);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import { SqliteRoomStore } from '../infrastructure/sqlite-room-store.server';
import { SqliteAgentRegistry } from '../infrastructure/sqlite-agent-registry.server';
import { SqliteTurnLog } from '../infrastructure/sqlite-turn-log.server';
import { INHERITED_AGENT_ROLE } from '../infrastructure/agent-seed.server';
import { RoomCatalog, RoomCatalogInvariantError, type RoomWakeMode } from '../domain/room-catalog';
import { RoomCatalog, type RoomWakeMode } from '../domain/room-catalog';
import { isAgentId, type AgentRegistry, type RoomLabAgentId } from '../domain/agent-registry';
import {
deriveAgentAvailability,
Expand Down Expand Up @@ -835,6 +835,3 @@ export class RoomLabHost {
),
};
}

export { RoomCatalogInvariantError };
export { RoomInputError };
22 changes: 9 additions & 13 deletions apps/room-web/app/room-lab/application/room-tools.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { RoomEvent, RoomId, RoomSeq, SpeakResult } from '@rivus/agent-room'
import type { AgentSessionId } from '@rivus/agent-room';
import type { ToolDefinition } from './turn';
import type { RoomLabAgentId } from '../read-model';
import { ROOM_MESSAGE_LIMIT } from '../domain/room-message';
import { ROOM_MESSAGE_LIMIT, trimmedBody } from '../domain/room-message';
import { HELD_LIMIT } from './ports';

/**
Expand Down Expand Up @@ -85,13 +85,11 @@ export function roomSpeakTool(
if (handle.spoke) {
return { error: 'already-spoke' };
}
const body = typeof input.body === 'string' ? input.body.trim() : '';
if (!body) {
return { error: 'body-required' };
}
if (body.length > ROOM_MESSAGE_LIMIT) {
return { error: 'body-too-long' };
const parsedBody = trimmedBody(input.body);
if (!parsedBody.ok) {
return { error: parsedBody.error };
}
const body = parsedBody.body;
const addressedTo = Array.isArray(input.addressedTo)
? input.addressedTo.filter((id): id is string => typeof id === 'string')
: [];
Expand Down Expand Up @@ -147,13 +145,11 @@ export function roomDmTool(
if (!to) {
return { error: 'to-required' };
}
const body = typeof input.body === 'string' ? input.body.trim() : '';
if (!body) {
return { error: 'body-required' };
}
if (body.length > ROOM_MESSAGE_LIMIT) {
return { error: 'body-too-long' };
const parsedBody = trimmedBody(input.body);
if (!parsedBody.ok) {
return { error: parsedBody.error };
}
const body = parsedBody.body;
if (to === handle.agentId) {
return { error: 'dm-self' };
}
Expand Down
10 changes: 0 additions & 10 deletions apps/room-web/app/room-lab/application/turn.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,5 @@
import type { SessionUpdate } from '@agentclientprotocol/sdk';
import type { McpServerConfig, PermissionDecision, PermissionRequest, PromptBlock } from '@rivus/agent-kit/acp';

/**
* The endpoint's own turn contract — the slots a turn carries and how it ends.
* It was the control-plane package's `Harness`; with the ACP driving adopted
* from `@rivus/agent-kit`'s `/acp`, the contract lives with the endpoint that
* fills it, and the kit's own shapes (`PromptBlock`, `McpServerConfig`,
* `PermissionRequest`) travel across the boundary unchanged.
*/
export type { SessionUpdate };

/**
* One tool the endpoint contributes to a member's session. The endpoint's
* ToolServer hosts the definitions as one streamable-HTTP MCP endpoint per
Expand Down
2 changes: 0 additions & 2 deletions apps/room-web/app/room-lab/copy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,5 +148,3 @@ export const copy = {
roundBudgetReached: '本轮已达调用上限',
},
} as const;

export type StatusKey = keyof typeof copy.status;
16 changes: 16 additions & 0 deletions apps/room-web/app/room-lab/domain/room-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,22 @@ export const ROOM_MENTION_SOURCE = String.raw`(?<![a-z0-9._%+-])@(all|[a-z][a-z0

const MENTION_PATTERN = new RegExp(ROOM_MENTION_SOURCE, 'gi');

/** A trimmed room message body, or the error code the room tools report. */
export function trimmedBody(
body: unknown,
):
| { readonly ok: true; readonly body: string }
| { readonly ok: false; readonly error: 'body-required' | 'body-too-long' } {
const text = typeof body === 'string' ? body.trim() : '';
if (!text) {
return { ok: false, error: 'body-required' };
}
if (text.length > ROOM_MESSAGE_LIMIT) {
return { ok: false, error: 'body-too-long' };
}
return { ok: true, body: text };
}

export interface RoomMessage {
body: string;
addressedTo: RoomLabAgentId[];
Expand Down
8 changes: 4 additions & 4 deletions apps/room-web/app/room-lab/infrastructure/agent-acp.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ export interface RoomAgentSpec {
* is bounded by (a cancel that does not settle in time invalidates the
* session's binding and closes the connection).
*/
export const ROOM_ACP_HANDSHAKE_TIMEOUT_MS = 45_000;
export const ROOM_ACP_REQUEST_TIMEOUT_MS = 30_000;
const ROOM_ACP_HANDSHAKE_TIMEOUT_MS = 45_000;
const ROOM_ACP_REQUEST_TIMEOUT_MS = 30_000;
export const ROOM_ACP_CANCEL_TIMEOUT_MS = 5_000;

/** The client name the old connector announced; carried over. */
Expand Down Expand Up @@ -121,7 +121,7 @@ function builtinBaseFor(agent: RoomAgentSpec): AcpProfile | undefined {
}

/** Splits an `agents` row's command line: the first word is the program. */
export function splitCommandLine(line: string): { command: string; args: readonly string[] } {
function splitCommandLine(line: string): { command: string; args: readonly string[] } {
const words = line.trim().split(/\s+/).filter(Boolean);
return { command: words[0] ?? '', args: words.slice(1) };
}
Expand Down Expand Up @@ -199,7 +199,7 @@ function connectOptions(agent: RoomAgentSpec, cwd: string, onPermission?: TurnPe
}

/** One line a turn row or a failure notice can carry about a prompt error. */
export function describePromptError(error: PromptError): string {
function describePromptError(error: PromptError): string {
switch (error._tag) {
case 'TurnInProgress':
return `the session's turn ${error.turn} is still running`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export const DEFAULT_AGENT_SEEDS: readonly AgentSeed[] = [
/** What an id that only exists in an old library gets until it is edited. */
export const INHERITED_AGENT_ROLE = '成员';

export function inheritedAgentSeed(id: string): AgentSeed {
function inheritedAgentSeed(id: string): AgentSeed {
return {
id,
label: id,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { RoomEvent, RoomSeq } from '@rivus/agent-room';

/** What both writers bind: a `RoomEvent`, or a legacy row whose optionals are absent. */
export type InsertableRoomEvent = Omit<RoomEvent, 'addressedTo' | 'origin' | 'wakeDepth'> & {
addressedTo?: RoomEvent['addressedTo'];
origin?: RoomEvent['origin'];
wakeDepth?: RoomEvent['wakeDepth'];
};

/**
* The `room_events` insert both sqlite stores speak: one prepared statement
* shape and one row binder, so the initial write and the unit-of-work diff
* cannot drift.
*/
export function prepareRoomEventInsert(
db: { prepare(sql: string): { run(...values: unknown[]): unknown } },
roomId: string,
): { run(event: InsertableRoomEvent, seq: RoomSeq): unknown } {
const insertEvent = db.prepare(`
INSERT INTO room_events (
room_id, seq, message_id, transport_message_id, author_kind, author_id, kind, body, addressed_to, origin, wake_depth, at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
return {
run(event: InsertableRoomEvent, seq: RoomSeq) {
return insertEvent.run(
roomId,
seq,
event.messageId,
event.transportMessageId ?? null,
event.author.kind,
event.author.id,
event.kind,
event.body,
JSON.stringify(event.addressedTo ?? []),
event.origin ?? 'endpoint',
event.wakeDepth ?? 0,
event.at,
);
},
};
}
59 changes: 33 additions & 26 deletions apps/room-web/app/room-lab/infrastructure/room-lease.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
createLeaseManager,
sqliteLeaseRepository,
type LeaseConfigInvalid,
type LeaseHandle,
type LeaseHeld,
type LeaseLost,
type LeaseRepositoryFailure,
Expand All @@ -22,8 +21,8 @@ import * as Layer from 'effect/Layer';
* timing is the old one: renewed every 15 s, judged stale by an observer after
* 120 s without a confirmed renewal.
*/
export const ROOM_LEASE_TTL_MS = 120_000;
export const ROOM_LEASE_HEARTBEAT_MS = 15_000;
const ROOM_LEASE_TTL_MS = 120_000;
const ROOM_LEASE_HEARTBEAT_MS = 15_000;

/** The lease environment the host's assembly root provides to every lane activation. */
export function roomLeaseRepositoryLayer(
Expand All @@ -33,15 +32,15 @@ export function roomLeaseRepositoryLayer(
}

/** The lease configuration is out of range, or the heartbeat does not fit twice into the TTL. */
export class RoomLeaseConfigError extends Error {
class RoomLeaseConfigError extends Error {
constructor(message: string) {
super(message);
this.name = 'RoomLeaseConfigError';
}
}

/** The lease repository could not read or write a record; the lease's state is unknown, not changed. */
export class RoomLeaseStoreError extends Error {
class RoomLeaseStoreError extends Error {
readonly key: string;
readonly reason: LeaseRepositoryFailure['reason'];

Expand All @@ -54,7 +53,7 @@ export class RoomLeaseStoreError extends Error {
}

/** Another live holder keeps the key. */
export class RoomLeaseHeldError extends Error {
class RoomLeaseHeldError extends Error {
readonly key: string;
readonly holderPid: number | undefined;

Expand All @@ -67,7 +66,7 @@ export class RoomLeaseHeldError extends Error {
}

/** This acquisition no longer holds the lease: taken over, released, vanished, or expired. */
export class RoomLeaseLostError extends Error {
class RoomLeaseLostError extends Error {
readonly key: string;
readonly reason: LeaseLost['reason'];

Expand All @@ -79,26 +78,37 @@ export class RoomLeaseLostError extends Error {
}
}

function isTagged(error: unknown, tag: string): boolean {
return typeof error === 'object' && error !== null && '_tag' in error && error._tag === tag;
/** The kit's lease failure tags this host maps onto its own Error surface. */
const ROOM_LEASE_TAGS = [
'LeaseHeld',
'LeaseLost',
'FenceRejected',
'LeaseConfigInvalid',
'LeaseRepositoryFailure',
] as const;

type RoomLeaseTag = (typeof ROOM_LEASE_TAGS)[number];

function leaseTag(error: unknown): RoomLeaseTag | undefined {
if (typeof error !== 'object' || error === null || !('_tag' in error)) {
return undefined;
}
return ROOM_LEASE_TAGS.find((tag) => error._tag === tag);
}

/** Translates the kit's tagged lease errors into the Error surface the Promise side rejects with. */
export function toLeaseError(error: unknown, key: string): Error {
if (isTagged(error, 'LeaseHeld')) {
return new RoomLeaseHeldError(error as LeaseHeld);
}
if (isTagged(error, 'LeaseLost')) {
return new RoomLeaseLostError(error as LeaseLost);
}
if (isTagged(error, 'FenceRejected')) {
return new Error(`member lease ${key} fenced a write with an older generation`);
}
if (isTagged(error, 'LeaseConfigInvalid')) {
return new RoomLeaseConfigError((error as LeaseConfigInvalid).message);
}
if (isTagged(error, 'LeaseRepositoryFailure')) {
return new RoomLeaseStoreError(error as LeaseRepositoryFailure);
switch (leaseTag(error)) {
case 'LeaseHeld':
return new RoomLeaseHeldError(error as LeaseHeld);
case 'LeaseLost':
return new RoomLeaseLostError(error as LeaseLost);
case 'FenceRejected':
return new Error(`member lease ${key} fenced a write with an older generation`);
case 'LeaseConfigInvalid':
return new RoomLeaseConfigError((error as LeaseConfigInvalid).message);
case 'LeaseRepositoryFailure':
return new RoomLeaseStoreError(error as LeaseRepositoryFailure);
}
if (error instanceof Error) {
return error;
Expand All @@ -119,6 +129,3 @@ export function createRoomLeaseManager(): Effect.Effect<
export function roomLeasePath(roomHome: string): string {
return join(roomHome, 'member-leases.sqlite');
}

/** One held member lease, as the lane activation keeps it for its turn's fenced writes. */
export type HeldRoomLease = LeaseHandle;
Loading
Loading