From 321285ec54f4956c780a746993f959eb084f477e Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:06:43 +0800 Subject: [PATCH 1/3] refactor: share the provider/service shapes and drop the knip export staging The 45 staged clones are shared code now, so the duplicates gate runs with only conventions ignored: - feishu-task-provider writes every record through one upsertRecord and maps runner/session fields through runnerFields; leaf providers share pendingTasksFrom/taskByIdFrom; the payload interfaces compose RunnerSessionFields and Pick instead of re-listing the columns - the execute and review runner loops share createHeartbeatWriter (the throttle, the timestamp advance, the failure reporting), and the runner callbacks the adapters receive are its callbacks(); git-backed services share runGit; the product CLIs share taskCommandArgs, loadCommandConfig and taskServiceFrom; init/source share the gh repo probe - room-web and agent-room share sessionForwarders, cloneSession, AgentSessionAggregate.fromStored and assertSessionInRoom; the sqlite stores bind event rows through one prepareRoomEventInsert; the room tools validate bodies through trimmedBody; RoomDmGateway.open's input is one RoomDmOpenInput - agent-finder-cli's probe recipes build through one probe() factory, and both resume command tables go through resumeCommandFrom knip runs without exclude: ['exports', 'types']: 54 internally-used exports lost the keyword and 5 dead declarations are gone. The gate lands as pnpm duplicates. --- .../app/room-lab/application/ports.ts | 33 +- .../room-lab/application/room-dm.server.ts | 14 +- .../application/room-lab-host.server.ts | 5 +- .../room-lab/application/room-tools.server.ts | 22 +- .../room-web/app/room-lab/application/turn.ts | 10 - apps/room-web/app/room-lab/copy.ts | 2 - .../app/room-lab/domain/room-message.ts | 14 + .../infrastructure/agent-acp.server.ts | 8 +- .../infrastructure/agent-seed.server.ts | 2 +- .../room-event-insert.server.ts | 42 ++ .../infrastructure/room-lease.server.ts | 53 +-- .../infrastructure/room-leases.server.ts | 11 - .../sqlite-room-store.server.ts | 23 +- .../sqlite-room-unit-of-work.server.ts | 48 +-- .../infrastructure/sqlite-turn-log.server.ts | 2 +- .../app/room-lab/presentation/agent-color.ts | 2 +- .../app/room-lab/presentation/composer-doc.ts | 2 +- .../presentation/composer-mention.tsx | 2 +- .../app/room-lab/presentation/mention-chip.ts | 2 +- .../room-lab/presentation/room-composer.tsx | 3 - apps/room-web/app/room-lab/read-model.ts | 4 +- knip.ts | 1 - package.json | 1 + .../agent-finder-cli/bin/agent-finder.mjs | 4 +- .../agent-finder-cli/src/discovery/agents.ts | 2 +- .../src/discovery/legacy-probe-recipes.ts | 91 ++--- packages/agent-finder-cli/src/package-info.ts | 7 +- .../src/sessions/resume-form.ts | 15 + .../agent-finder-cli/src/sessions/resume.ts | 8 +- .../src/agent-session/domain/agent-session.ts | 5 + .../src/agent-session/domain/model.ts | 27 ++ packages/agent-room/src/index.ts | 2 +- packages/agent-room/src/room/domain/model.ts | 1 + packages/agent-room/src/room/domain/pass.ts | 11 +- packages/agent-room/src/room/domain/room.ts | 5 +- .../src/room/domain/session-guard.ts | 18 + packages/agent-room/src/room/domain/speak.ts | 19 +- .../memory-room-stream-store.ts | 50 +-- .../agent-task-loop/bin/agent-task-loop.mjs | 16 +- packages/agent-task-loop/src/adapters/base.ts | 2 +- .../src/adapters/claude-lines.ts | 47 +++ .../agent-task-loop/src/adapters/claude.ts | 77 ++-- .../agent-task-loop/src/commands/cleanup.ts | 12 +- .../src/commands/command-context.ts | 29 ++ .../agent-task-loop/src/commands/complete.ts | 12 +- .../agent-task-loop/src/commands/create.ts | 12 +- .../agent-task-loop/src/commands/gh-repo.ts | 15 + packages/agent-task-loop/src/commands/init.ts | 14 +- .../agent-task-loop/src/commands/reject.ts | 4 +- .../agent-task-loop/src/commands/resume.ts | 8 +- packages/agent-task-loop/src/commands/run.ts | 4 +- .../agent-task-loop/src/commands/schema.ts | 4 +- .../agent-task-loop/src/commands/source.ts | 18 +- .../agent-task-loop/src/commands/start.ts | 4 +- packages/agent-task-loop/src/commands/sync.ts | 12 +- .../agent-task-loop/src/commands/watch.ts | 6 +- packages/agent-task-loop/src/config/schema.ts | 16 +- .../src/orchestration/errors.ts | 10 +- .../src/orchestration/lease.ts | 24 +- .../src/orchestration/types.ts | 12 +- packages/agent-task-loop/src/package-info.ts | 10 +- .../src/services/delivery-check-service.ts | 7 +- .../src/services/execution-service.ts | 71 +--- .../src/services/git-publish-service.ts | 5 +- .../agent-task-loop/src/services/git-run.ts | 15 + .../agent-task-loop/src/services/heartbeat.ts | 101 +++++ .../src/services/publish-context-service.ts | 7 +- .../src/services/review-loop-runner.ts | 49 +-- .../src/services/review-loop-service.ts | 59 +-- .../src/session/resume-form.ts | 15 + .../agent-task-loop/src/session/resume.ts | 7 +- .../task-management/feishu-task-provider.ts | 366 ++++++------------ .../github-issues-task-provider.ts | 36 +- .../src/task-management/runtime-state.ts | 4 +- .../task-management/stateful-task-provider.ts | 3 +- .../src/task-management/task-provider.ts | 68 ++-- .../src/task-management/task-state-store.ts | 2 +- .../task-manager/task-manager-application.ts | 12 +- .../agent-task-loop/src/tui/logic/layout.ts | 2 +- 79 files changed, 868 insertions(+), 900 deletions(-) create mode 100644 apps/room-web/app/room-lab/infrastructure/room-event-insert.server.ts create mode 100644 packages/agent-finder-cli/src/sessions/resume-form.ts create mode 100644 packages/agent-room/src/room/domain/session-guard.ts create mode 100644 packages/agent-task-loop/src/adapters/claude-lines.ts create mode 100644 packages/agent-task-loop/src/commands/command-context.ts create mode 100644 packages/agent-task-loop/src/commands/gh-repo.ts create mode 100644 packages/agent-task-loop/src/services/git-run.ts create mode 100644 packages/agent-task-loop/src/services/heartbeat.ts create mode 100644 packages/agent-task-loop/src/session/resume-form.ts diff --git a/apps/room-web/app/room-lab/application/ports.ts b/apps/room-web/app/room-lab/application/ports.ts index 4e3366bb..1060735f 100644 --- a/apps/room-web/app/room-lab/application/ports.ts +++ b/apps/room-web/app/room-lab/application/ports.ts @@ -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[]; @@ -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 @@ -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 }>; } diff --git a/apps/room-web/app/room-lab/application/room-dm.server.ts b/apps/room-web/app/room-lab/application/room-dm.server.ts index b11832b2..274e3375 100644 --- a/apps/room-web/app/room-lab/application/room-dm.server.ts +++ b/apps/room-web/app/room-lab/application/room-dm.server.ts @@ -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'; @@ -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}`; } @@ -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); diff --git a/apps/room-web/app/room-lab/application/room-lab-host.server.ts b/apps/room-web/app/room-lab/application/room-lab-host.server.ts index 4a288bfe..52b60d1e 100644 --- a/apps/room-web/app/room-lab/application/room-lab-host.server.ts +++ b/apps/room-web/app/room-lab/application/room-lab-host.server.ts @@ -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, @@ -835,6 +835,3 @@ export class RoomLabHost { ), }; } - -export { RoomCatalogInvariantError }; -export { RoomInputError }; diff --git a/apps/room-web/app/room-lab/application/room-tools.server.ts b/apps/room-web/app/room-lab/application/room-tools.server.ts index e12bee9e..e6eda171 100644 --- a/apps/room-web/app/room-lab/application/room-tools.server.ts +++ b/apps/room-web/app/room-lab/application/room-tools.server.ts @@ -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'; /** @@ -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') : []; @@ -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' }; } diff --git a/apps/room-web/app/room-lab/application/turn.ts b/apps/room-web/app/room-lab/application/turn.ts index c4147a7f..ffdfdbf3 100644 --- a/apps/room-web/app/room-lab/application/turn.ts +++ b/apps/room-web/app/room-lab/application/turn.ts @@ -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 diff --git a/apps/room-web/app/room-lab/copy.ts b/apps/room-web/app/room-lab/copy.ts index 0c4d9cf4..5602f857 100644 --- a/apps/room-web/app/room-lab/copy.ts +++ b/apps/room-web/app/room-lab/copy.ts @@ -148,5 +148,3 @@ export const copy = { roundBudgetReached: '本轮已达调用上限', }, } as const; - -export type StatusKey = keyof typeof copy.status; diff --git a/apps/room-web/app/room-lab/domain/room-message.ts b/apps/room-web/app/room-lab/domain/room-message.ts index 70316481..f487cb35 100644 --- a/apps/room-web/app/room-lab/domain/room-message.ts +++ b/apps/room-web/app/room-lab/domain/room-message.ts @@ -14,6 +14,20 @@ export const ROOM_MENTION_SOURCE = String.raw`(? ROOM_MESSAGE_LIMIT) { + return { ok: false, error: 'body-too-long' }; + } + return { ok: true, body: text }; +} + export interface RoomMessage { body: string; addressedTo: RoomLabAgentId[]; diff --git a/apps/room-web/app/room-lab/infrastructure/agent-acp.server.ts b/apps/room-web/app/room-lab/infrastructure/agent-acp.server.ts index e6938103..d122e8c6 100644 --- a/apps/room-web/app/room-lab/infrastructure/agent-acp.server.ts +++ b/apps/room-web/app/room-lab/infrastructure/agent-acp.server.ts @@ -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. */ @@ -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) }; } @@ -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`; diff --git a/apps/room-web/app/room-lab/infrastructure/agent-seed.server.ts b/apps/room-web/app/room-lab/infrastructure/agent-seed.server.ts index 16f0b320..1ab0fb41 100644 --- a/apps/room-web/app/room-lab/infrastructure/agent-seed.server.ts +++ b/apps/room-web/app/room-lab/infrastructure/agent-seed.server.ts @@ -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, diff --git a/apps/room-web/app/room-lab/infrastructure/room-event-insert.server.ts b/apps/room-web/app/room-lab/infrastructure/room-event-insert.server.ts new file mode 100644 index 00000000..7bbf7523 --- /dev/null +++ b/apps/room-web/app/room-lab/infrastructure/room-event-insert.server.ts @@ -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 & { + 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, + ); + }, + }; +} diff --git a/apps/room-web/app/room-lab/infrastructure/room-lease.server.ts b/apps/room-web/app/room-lab/infrastructure/room-lease.server.ts index a9c35166..0e3406f9 100644 --- a/apps/room-web/app/room-lab/infrastructure/room-lease.server.ts +++ b/apps/room-web/app/room-lab/infrastructure/room-lease.server.ts @@ -5,7 +5,6 @@ import { createLeaseManager, sqliteLeaseRepository, type LeaseConfigInvalid, - type LeaseHandle, type LeaseHeld, type LeaseLost, type LeaseRepositoryFailure, @@ -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( @@ -33,7 +32,7 @@ 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'; @@ -41,7 +40,7 @@ export class RoomLeaseConfigError extends Error { } /** 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']; @@ -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; @@ -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']; @@ -79,26 +78,31 @@ 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; @@ -119,6 +123,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; diff --git a/apps/room-web/app/room-lab/infrastructure/room-leases.server.ts b/apps/room-web/app/room-lab/infrastructure/room-leases.server.ts index 41082bef..30add120 100644 --- a/apps/room-web/app/room-lab/infrastructure/room-leases.server.ts +++ b/apps/room-web/app/room-lab/infrastructure/room-leases.server.ts @@ -1,6 +1,5 @@ import type { LeaseHandle, - LeaseLost, LeaseManager, LeaseRepository, LeaseRepositoryFailure, @@ -58,13 +57,3 @@ export class ActiveRoomLeases implements RoomLeases { } } } - -/** Whether a lease record reads as held for the member status display. */ -export function isLeaseHeld(record: LeaseSnapshot | undefined, staleAfterMs: number): boolean { - if (!record || !record.holder) { - return false; - } - return Date.now() - record.renewedAt < staleAfterMs; -} - -export type { LeaseLost }; diff --git a/apps/room-web/app/room-lab/infrastructure/sqlite-room-store.server.ts b/apps/room-web/app/room-lab/infrastructure/sqlite-room-store.server.ts index 11e2f71b..865f34cc 100644 --- a/apps/room-web/app/room-lab/infrastructure/sqlite-room-store.server.ts +++ b/apps/room-web/app/room-lab/infrastructure/sqlite-room-store.server.ts @@ -1,6 +1,8 @@ import { existsSync, mkdirSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import { DatabaseSync } from 'node:sqlite'; + +import { prepareRoomEventInsert } from './room-event-insert.server'; import type { AgentSession, RoomEvent, RoomId } from '@rivus/agent-room'; import { RoomCatalog, type RoomRecord, type RoomWakeMode } from '../domain/room-catalog'; import { AgentRegistry, type AgentDefinition, type RoomLabAgentId } from '../domain/agent-registry'; @@ -345,26 +347,9 @@ export class SqliteRoomStore { this.inTransaction(() => { this.db.prepare('DELETE FROM room_events WHERE room_id = ?').run(roomId); this.db.prepare('DELETE FROM agent_sessions WHERE room_id = ?').run(roomId); - const insertEvent = this.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `); + const insertEvent = prepareRoomEventInsert(this.db, roomId); for (const event of events) { - insertEvent.run( - roomId, - event.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, - ); + insertEvent.run(event, event.seq); } const insertSession = this.db.prepare(` INSERT INTO agent_sessions ( diff --git a/apps/room-web/app/room-lab/infrastructure/sqlite-room-unit-of-work.server.ts b/apps/room-web/app/room-lab/infrastructure/sqlite-room-unit-of-work.server.ts index bcf30214..969c6cef 100644 --- a/apps/room-web/app/room-lab/infrastructure/sqlite-room-unit-of-work.server.ts +++ b/apps/room-web/app/room-lab/infrastructure/sqlite-room-unit-of-work.server.ts @@ -1,8 +1,11 @@ import { DatabaseSync } from 'node:sqlite'; + +import { prepareRoomEventInsert } from './room-event-insert.server'; import { AgentSessionAggregate, Room, RoomStreamService, + cloneSession, sessionKey, type AgentId, type AgentSession, @@ -72,16 +75,6 @@ function toSession(row: SessionRow): AgentSession { }; } -function cloneSession(session: AgentSession): AgentSession { - return { - id: { - ...session.id, - roomId: { ...session.id.roomId }, - }, - seenSeq: session.seenSeq, - }; -} - /** * One room's record and cursors over the sqlite tables. A unit of work is one * `BEGIN IMMEDIATE` around three steps — re-read the room's rows, run the @@ -183,13 +176,15 @@ export class SqliteRoomUnitOfWork implements RoomUnitOfWork { } private openRoom(id: RoomId): Room { + // The unit's own event slice is what the domain work reads; the assert keeps + // a stray id from silently reading another room's rows. this.assertRoom(id); return new Room(id, this.events); } private loadSession(id: AgentSessionId): AgentSessionAggregate { const existing = this.sessions.get(sessionKey(id)); - return new AgentSessionAggregate(id, existing ? { seenSeq: existing.seenSeq } : undefined); + return AgentSessionAggregate.fromStored(id, existing ? { seenSeq: existing.seenSeq } : undefined); } private reload(): void { @@ -213,10 +208,7 @@ export class SqliteRoomUnitOfWork implements RoomUnitOfWork { this.sessions.set(sessionKey(session.id), session); } this.dbHead = this.events.at(-1)?.seq ?? 0; - this.dbSessions.clear(); - for (const session of this.sessions.values()) { - this.dbSessions.set(sessionKey(session.id), cloneSession(session)); - } + this.syncDbSessions(); } /** @@ -227,29 +219,12 @@ export class SqliteRoomUnitOfWork implements RoomUnitOfWork { */ private write(): void { const roomId = this.roomId.conversationId; - const insertEvent = this.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `); + const insertEvent = prepareRoomEventInsert(this.db, roomId); for (const event of this.events) { if (event.seq <= this.dbHead) { continue; } - insertEvent.run( - roomId, - event.seq, - event.messageId, - event.transportMessageId ?? null, - event.author.kind, - event.author.id, - event.kind, - event.body, - JSON.stringify(event.addressedTo), - event.origin, - event.wakeDepth, - event.at, - ); + insertEvent.run(event, event.seq); } const upsertSession = this.db.prepare(` INSERT INTO agent_sessions ( @@ -270,6 +245,11 @@ export class SqliteRoomUnitOfWork implements RoomUnitOfWork { ); } this.dbHead = this.events.at(-1)?.seq ?? this.dbHead; + this.syncDbSessions(); + } + + /** The diff base's session snapshots: defensive copies of this unit's own. */ + private syncDbSessions(): void { this.dbSessions.clear(); for (const session of this.sessions.values()) { this.dbSessions.set(sessionKey(session.id), cloneSession(session)); diff --git a/apps/room-web/app/room-lab/infrastructure/sqlite-turn-log.server.ts b/apps/room-web/app/room-lab/infrastructure/sqlite-turn-log.server.ts index 32f1dacd..32f00b26 100644 --- a/apps/room-web/app/room-lab/infrastructure/sqlite-turn-log.server.ts +++ b/apps/room-web/app/room-lab/infrastructure/sqlite-turn-log.server.ts @@ -2,7 +2,7 @@ import type { DatabaseSync } from 'node:sqlite'; import type { RoomTurnView } from '../read-model'; /** How a turn ended: it spoke, it stayed silent, it ran out of time, or it failed. */ -export type TurnOutcome = 'posted' | 'passed' | 'timeout' | 'failed'; +type TurnOutcome = 'posted' | 'passed' | 'timeout' | 'failed'; /** * One row of `turns` (docs/architecture/agent-collaboration.md): when a member's turn started, what woke it, diff --git a/apps/room-web/app/room-lab/presentation/agent-color.ts b/apps/room-web/app/room-lab/presentation/agent-color.ts index e474e254..ac9157b3 100644 --- a/apps/room-web/app/room-lab/presentation/agent-color.ts +++ b/apps/room-web/app/room-lab/presentation/agent-color.ts @@ -27,7 +27,7 @@ const DOT = [ ] as const; export const NEUTRAL_TILE = 'bg-accent text-accent-foreground'; -export const NEUTRAL_INK = 'text-accent-foreground'; +const NEUTRAL_INK = 'text-accent-foreground'; export const NEUTRAL_DOT = 'bg-accent-foreground text-accent'; function pick(scale: readonly string[], color: number | undefined, fallback: string): string { diff --git a/apps/room-web/app/room-lab/presentation/composer-doc.ts b/apps/room-web/app/room-lab/presentation/composer-doc.ts index 6a7bc799..782b6703 100644 --- a/apps/room-web/app/room-lab/presentation/composer-doc.ts +++ b/apps/room-web/app/room-lab/presentation/composer-doc.ts @@ -14,7 +14,7 @@ import type { RoomLabAgentId } from '../read-model'; * chip into loose text (or the reverse) the first time a send fails. */ -export const MENTION_NODE = 'mention'; +const MENTION_NODE = 'mention'; /** Ids a rebuild is allowed to turn back into chips: the room's own agent ids plus `'all'`. */ export type MentionId = RoomLabAgentId; diff --git a/apps/room-web/app/room-lab/presentation/composer-mention.tsx b/apps/room-web/app/room-lab/presentation/composer-mention.tsx index 53ed0496..498851ae 100644 --- a/apps/room-web/app/room-lab/presentation/composer-mention.tsx +++ b/apps/room-web/app/room-lab/presentation/composer-mention.tsx @@ -34,7 +34,7 @@ function place(element: HTMLElement, rect: DOMRect | null) { element.style.zIndex = '40'; } -export function roomMentionSuggestion(bridge: MentionBridge): Omit { +function roomMentionSuggestion(bridge: MentionBridge): Omit { return { char: '@', items: ({ query }) => diff --git a/apps/room-web/app/room-lab/presentation/mention-chip.ts b/apps/room-web/app/room-lab/presentation/mention-chip.ts index 9f197613..26994f23 100644 --- a/apps/room-web/app/room-lab/presentation/mention-chip.ts +++ b/apps/room-web/app/room-lab/presentation/mention-chip.ts @@ -26,7 +26,7 @@ const CHIP = const DOT = 'inline-flex size-3.5 shrink-0 items-center justify-center rounded-full text-[8px] leading-none font-semibold'; -export const ALL_MENTION_CHIP: MentionChip = { +const ALL_MENTION_CHIP: MentionChip = { letters: '@', text: 'all', chipClass: `${CHIP} ${NEUTRAL_TILE}`, diff --git a/apps/room-web/app/room-lab/presentation/room-composer.tsx b/apps/room-web/app/room-lab/presentation/room-composer.tsx index 75c82a1c..6b3a29e5 100644 --- a/apps/room-web/app/room-lab/presentation/room-composer.tsx +++ b/apps/room-web/app/room-lab/presentation/room-composer.tsx @@ -2,7 +2,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { At } from '@phosphor-icons/react/dist/ssr/At'; import { ArrowUp } from '@phosphor-icons/react/dist/ssr/ArrowUp'; import { EditorContent, useEditor } from '@tiptap/react'; -import type { Editor } from '@tiptap/core'; import { Document } from '@tiptap/extension-document'; import { Paragraph } from '@tiptap/extension-paragraph'; import { Text } from '@tiptap/extension-text'; @@ -228,5 +227,3 @@ export function RoomComposer({ ); } - -export type { Editor }; diff --git a/apps/room-web/app/room-lab/read-model.ts b/apps/room-web/app/room-lab/read-model.ts index f9fa7234..55d7a714 100644 --- a/apps/room-web/app/room-lab/read-model.ts +++ b/apps/room-web/app/room-lab/read-model.ts @@ -128,12 +128,12 @@ export interface RoomCatalogItemView { children?: RoomCatalogItemView[]; } -export interface AgentDeskSeat { +interface AgentDeskSeat { id: string; title: string; } -export interface AgentDeskItem extends RoomAgentProbeItem { +interface AgentDeskItem extends RoomAgentProbeItem { seatedIn: AgentDeskSeat[]; /** The member's own row; empty when it adds nothing to a turn. */ systemPrompt: string; diff --git a/knip.ts b/knip.ts index 9c30cd02..0d68a407 100644 --- a/knip.ts +++ b/knip.ts @@ -7,7 +7,6 @@ import type { KnipConfig } from 'knip'; // policy's configuration and tag hints still fail the run. const config: KnipConfig = { ...knip, - exclude: ['exports', 'types'], workspaces: { '.': { entry: ['tests/**/*.test.mjs'], diff --git a/package.json b/package.json index b7a6061e..ed1d9544 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "agent-finder": "pnpm --filter @rivus/agent-finder-cli dev", "build": "pnpm -r build", "changeset": "changeset", + "duplicates": "jscpd --config node_modules/@perfectpan/lint-config/jscpd.json packages apps scripts tests --ignore '**/node_modules/**,**/dist/**,**/.next/**,**/build/**,**/.react-router/**,**/*.test.ts,**/*.test.mjs,**/*.test.tsx' --format 'typescript,javascript'", "duplicates:audit": "jscpd --config node_modules/@perfectpan/lint-config/jscpd-audit.json packages apps scripts tests --absolute --output tmp/duplicates-audit --ignore '**/node_modules/**,**/dist/**,**/.next/**,**/build/**,**/.react-router/**' --format 'typescript,javascript'", "format": "vp fmt", "format:check": "vp fmt --check", diff --git a/packages/agent-finder-cli/bin/agent-finder.mjs b/packages/agent-finder-cli/bin/agent-finder.mjs index baa6969e..372c558e 100755 --- a/packages/agent-finder-cli/bin/agent-finder.mjs +++ b/packages/agent-finder-cli/bin/agent-finder.mjs @@ -1,11 +1,11 @@ #!/usr/bin/env node -import { existsSync } from 'node:fs'; import path from 'node:path'; +import { existsSync } from 'node:fs'; import { spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; -const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const packageRoot = fileURLToPath(new URL('..', import.meta.url)); const distEntrypoint = path.join(packageRoot, 'dist', 'cli.js'); const sourceEntrypoint = path.join(packageRoot, 'src', 'cli.ts'); const tsxLoader = path.join(packageRoot, 'node_modules', 'tsx', 'dist', 'loader.mjs'); diff --git a/packages/agent-finder-cli/src/discovery/agents.ts b/packages/agent-finder-cli/src/discovery/agents.ts index 73f55a3f..12c7f24a 100644 --- a/packages/agent-finder-cli/src/discovery/agents.ts +++ b/packages/agent-finder-cli/src/discovery/agents.ts @@ -15,7 +15,7 @@ import { legacyProbeRecipes } from './legacy-probe-recipes.js'; * The kit's built-in recipes plus the MoonBit catalog's remaining agents. `detectAgents` reports the built-ins in * their table order first, then the legacy ones; the MoonBit scanner used the catalog file order instead. */ -export const allProbeRecipes: ProbeRecipes = { +const allProbeRecipes: ProbeRecipes = { ...Object.fromEntries(builtinProviders.flatMap(({ id, discovery }) => (discovery ? [[id, discovery]] : []))), ...legacyProbeRecipes, }; diff --git a/packages/agent-finder-cli/src/discovery/legacy-probe-recipes.ts b/packages/agent-finder-cli/src/discovery/legacy-probe-recipes.ts index 3760f13e..b33e798e 100644 --- a/packages/agent-finder-cli/src/discovery/legacy-probe-recipes.ts +++ b/packages/agent-finder-cli/src/discovery/legacy-probe-recipes.ts @@ -16,7 +16,8 @@ const CLI_VERSION_PROBE = { sideEffects: [], } as const; -function cli( +function probe( + kind: 'cli' | 'app' | 'extension', agent: CodingAgentId, displayName: string, commands: readonly string[], @@ -29,63 +30,19 @@ function cli( specificationVersion: 'discovery-v1', agent, displayName, - kind: 'cli', - commands, - appPaths, - configPaths, - mcpConfigPaths, - version: CLI_VERSION_PROBE, - warnings, - }; -} - -function app( - agent: CodingAgentId, - displayName: string, - commands: readonly string[], - configPaths: readonly string[], - appPaths: readonly string[], - mcpConfigPaths: readonly string[], - warnings: readonly string[], -): ProbeRecipe { - return { - specificationVersion: 'discovery-v1', - agent, - displayName, - kind: 'app', - commands, - appPaths, - configPaths, - mcpConfigPaths, - warnings, - }; -} - -function extension( - agent: CodingAgentId, - displayName: string, - commands: readonly string[], - configPaths: readonly string[], - appPaths: readonly string[], - mcpConfigPaths: readonly string[], - warnings: readonly string[], -): ProbeRecipe { - return { - specificationVersion: 'discovery-v1', - agent, - displayName, - kind: 'extension', + kind, commands, appPaths, configPaths, mcpConfigPaths, + ...(kind === 'cli' ? { version: CLI_VERSION_PROBE } : {}), warnings, }; } /** The MoonBit catalog's agents in catalog order, minus the six the kit detects with its own built-in recipes. */ export const legacyProbeRecipes: Readonly> = { - openhands: app( + openhands: probe('app', 'openhands', 'OpenHands', ['openhands'], @@ -94,7 +51,7 @@ export const legacyProbeRecipes: Readonly> = { [], ['OpenHands may be local, containerized, or remote; discovery is conservative.'], ), - cline: extension( + cline: probe('extension', 'cline', 'Cline', [], @@ -103,7 +60,7 @@ export const legacyProbeRecipes: Readonly> = { [], ['Cline extension presence is not validated without reading extension metadata.'], ), - codebuddy: cli( + codebuddy: probe('cli', 'codebuddy', 'CodeBuddy', ['codebuddy'], @@ -112,7 +69,7 @@ export const legacyProbeRecipes: Readonly> = { [], ['CodeBuddy command and config paths may vary by distribution.'], ), - 'command-code': cli( + 'command-code': probe('cli', 'command-code', 'Command Code', ['command-code'], @@ -121,7 +78,7 @@ export const legacyProbeRecipes: Readonly> = { [], ['Command Code provider metadata needs validation.'], ), - 'kiro-cli': cli( + 'kiro-cli': probe('cli', 'kiro-cli', 'Kiro CLI', ['kiro'], @@ -130,7 +87,7 @@ export const legacyProbeRecipes: Readonly> = { [], ['Kiro CLI provider metadata needs validation.'], ), - antigravity: app( + antigravity: probe('app', 'antigravity', 'Antigravity', ['antigravity'], @@ -139,7 +96,7 @@ export const legacyProbeRecipes: Readonly> = { [], ['Antigravity provider metadata needs validation.'], ), - 'roo-code': extension( + 'roo-code': probe('extension', 'roo-code', 'Roo Code', [], @@ -148,7 +105,7 @@ export const legacyProbeRecipes: Readonly> = { [], ['Roo Code extension presence is not validated without reading extension metadata.'], ), - 'github-copilot': cli( + 'github-copilot': probe('cli', 'github-copilot', 'GitHub Copilot', ['gh', 'copilot'], @@ -157,8 +114,8 @@ export const legacyProbeRecipes: Readonly> = { [], ['GitHub Copilot CLI support is detected conservatively through command metadata.'], ), - amp: cli('amp', 'Amp', ['amp'], ['~/.amp'], [], [], ['Amp provider metadata needs validation.']), - openclaw: cli( + amp: probe('cli', 'amp', 'Amp', ['amp'], ['~/.amp'], [], [], ['Amp provider metadata needs validation.']), + openclaw: probe('cli', 'openclaw', 'OpenClaw', ['openclaw'], @@ -167,7 +124,7 @@ export const legacyProbeRecipes: Readonly> = { [], ['OpenClaw provider metadata needs validation.'], ), - neovate: cli( + neovate: probe('cli', 'neovate', 'Neovate', ['neovate'], @@ -176,8 +133,8 @@ export const legacyProbeRecipes: Readonly> = { [], ['Neovate provider metadata needs validation.'], ), - qoder: cli('qoder', 'Qoder', ['qoder'], ['~/.qoder'], [], [], ['Qoder provider metadata needs validation.']), - zencoder: cli( + qoder: probe('cli', 'qoder', 'Qoder', ['qoder'], ['~/.qoder'], [], [], ['Qoder provider metadata needs validation.']), + zencoder: probe('cli', 'zencoder', 'Zencoder', ['zencoder'], @@ -186,7 +143,7 @@ export const legacyProbeRecipes: Readonly> = { [], ['Zencoder provider metadata needs validation.'], ), - 'kimi-code-cli': cli( + 'kimi-code-cli': probe('cli', 'kimi-code-cli', 'Kimi Code CLI', ['kimi'], @@ -195,7 +152,7 @@ export const legacyProbeRecipes: Readonly> = { [], ['Kimi Code CLI provider metadata needs validation.'], ), - windsurf: app( + windsurf: probe('app', 'windsurf', 'Windsurf', ['windsurf'], @@ -204,7 +161,7 @@ export const legacyProbeRecipes: Readonly> = { ['~/.codeium/windsurf/mcp_config.json', '~/Library/Application Support/Windsurf/User/mcp.json'], [], ), - 'vscode-copilot': extension( + 'vscode-copilot': probe('extension', 'vscode-copilot', 'VS Code Copilot', ['code'], @@ -213,7 +170,7 @@ export const legacyProbeRecipes: Readonly> = { ['~/Library/Application Support/Code/User/mcp.json'], ['VS Code Copilot extension presence is not validated without reading extension metadata.'], ), - 'codex-desktop': app( + 'codex-desktop': probe('app', 'codex-desktop', 'Codex Desktop', [], @@ -222,7 +179,7 @@ export const legacyProbeRecipes: Readonly> = { ['~/.codex/config.toml'], [], ), - aider: cli('aider', 'aider', ['aider'], ['~/.aider.conf.yml', '~/.config/aider'], [], [], []), - hermes: cli('hermes', 'Hermes', ['hermes'], ['~/.hermes'], [], [], ['Hermes provider metadata needs validation.']), - trae: cli('trae', 'Trae', ['trae'], ['~/.trae'], [], [], ['Trae provider metadata needs validation.']), + aider: probe('cli', 'aider', 'aider', ['aider'], ['~/.aider.conf.yml', '~/.config/aider'], [], [], []), + hermes: probe('cli', 'hermes', 'Hermes', ['hermes'], ['~/.hermes'], [], [], ['Hermes provider metadata needs validation.']), + trae: probe('cli', 'trae', 'Trae', ['trae'], ['~/.trae'], [], [], ['Trae provider metadata needs validation.']), }; diff --git a/packages/agent-finder-cli/src/package-info.ts b/packages/agent-finder-cli/src/package-info.ts index 8d7f91f4..cd5c78a2 100644 --- a/packages/agent-finder-cli/src/package-info.ts +++ b/packages/agent-finder-cli/src/package-info.ts @@ -5,10 +5,7 @@ import { fileURLToPath } from 'node:url'; // The source file and the bundled dist/cli.js both sit one directory below the package root. const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +/** This package's version, read from its package.json at run time. */ export function getPackageVersion(): string { - const packageJson = JSON.parse(readFileSync(path.join(packageRoot, 'package.json'), 'utf8')) as { - version: string; - }; - - return packageJson.version; + return (JSON.parse(readFileSync(path.join(packageRoot, 'package.json'), 'utf8')) as { version: string }).version; } diff --git a/packages/agent-finder-cli/src/sessions/resume-form.ts b/packages/agent-finder-cli/src/sessions/resume-form.ts new file mode 100644 index 00000000..63be42a0 --- /dev/null +++ b/packages/agent-finder-cli/src/sessions/resume-form.ts @@ -0,0 +1,15 @@ +/** + * The copyable resume command for a session: the agent's builder applied to the + * session id, or `null` for an unknown agent or a missing id. + */ +export function resumeCommandFrom string>( + resumeCommands: Readonly>>, + agent: string | undefined, + sessionId: string | undefined | null, +): string | null { + return sessionId + ? agent !== undefined + ? (resumeCommands[agent]?.(sessionId) ?? null) + : null + : null; +} diff --git a/packages/agent-finder-cli/src/sessions/resume.ts b/packages/agent-finder-cli/src/sessions/resume.ts index 2120ba15..4315b6a5 100644 --- a/packages/agent-finder-cli/src/sessions/resume.ts +++ b/packages/agent-finder-cli/src/sessions/resume.ts @@ -1,5 +1,7 @@ import type { CodingAgentId } from '@rivus/agent-kit/catalog'; +import { resumeCommandFrom } from './resume-form'; + /** * The one application-side table of copyable resume commands. `@rivus/agent-kit` * deliberately leaves resume knowledge to hosts, so every resume string this @@ -20,9 +22,5 @@ export function resumeCommandFor( agent: CodingAgentId | undefined, sessionId: string | undefined | null, ): string | null { - if (!sessionId) { - return null; - } - const build = agent === undefined ? undefined : RESUME_COMMANDS[agent]; - return build ? build(sessionId) : null; + return resumeCommandFrom(RESUME_COMMANDS, agent, sessionId); } diff --git a/packages/agent-room/src/agent-session/domain/agent-session.ts b/packages/agent-room/src/agent-session/domain/agent-session.ts index b05785b8..8720f823 100644 --- a/packages/agent-room/src/agent-session/domain/agent-session.ts +++ b/packages/agent-room/src/agent-session/domain/agent-session.ts @@ -35,6 +35,11 @@ function cloneSessionId(id: AgentSessionId): AgentSessionId { /** Aggregate root for one agent runtime generation's read cursor. */ export class AgentSessionAggregate { + /** Rebuilds the aggregate from its stored snapshot, starting fresh when none was stored. */ + static fromStored(id: AgentSessionId, stored?: { readonly seenSeq: number }): AgentSessionAggregate { + return new AgentSessionAggregate(id, stored); + } + private seen: RoomSeq; private readonly sessionId: AgentSessionId; diff --git a/packages/agent-room/src/agent-session/domain/model.ts b/packages/agent-room/src/agent-session/domain/model.ts index 42edcb31..f504b9fe 100644 --- a/packages/agent-room/src/agent-session/domain/model.ts +++ b/packages/agent-room/src/agent-session/domain/model.ts @@ -7,6 +7,33 @@ export interface AgentSessionId { runtimeGenerationId: RuntimeGenerationId; } +/** + * The session reads/writes every `RoomStreamStore` facade forwards to its unit + * of work, as spreadable methods. + */ +export function sessionForwarders(unitOfWork: { + ensureSession(id: AgentSessionId): AgentSession; + inspectSession(id: AgentSessionId): AgentSession | undefined; + advanceSeen(id: AgentSessionId, seq: RoomSeq): AgentSession; +}) { + return { + ensureSession: (id: AgentSessionId): AgentSession => unitOfWork.ensureSession(id), + inspectSession: (id: AgentSessionId): AgentSession | undefined => unitOfWork.inspectSession(id), + advanceSeen: (id: AgentSessionId, seq: RoomSeq): AgentSession => unitOfWork.advanceSeen(id, seq), + }; +} + +/** A defensive copy of a stored session snapshot: the id's nested room id copies too. */ +export function cloneSession(session: AgentSession): AgentSession { + return { + id: { + ...session.id, + roomId: { ...session.id.roomId }, + }, + seenSeq: session.seenSeq, + }; +} + export function sessionKey(id: AgentSessionId): string { return JSON.stringify([ id.tenantId, diff --git a/packages/agent-room/src/index.ts b/packages/agent-room/src/index.ts index d26c2aab..869a8d21 100644 --- a/packages/agent-room/src/index.ts +++ b/packages/agent-room/src/index.ts @@ -1,5 +1,5 @@ export type { AgentSession, AgentSessionId } from './agent-session/domain/model'; -export { sessionKey } from './agent-session/domain/model'; +export { cloneSession, sessionForwarders, sessionKey } from './agent-session/domain/model'; export { AgentSessionAggregate } from './agent-session/domain/agent-session'; export { AGENT_SESSION_VALIDATION_CODE, AgentSessionValidationError } from './agent-session/domain/errors'; diff --git a/packages/agent-room/src/room/domain/model.ts b/packages/agent-room/src/room/domain/model.ts index e1b7ac36..7519e5ee 100644 --- a/packages/agent-room/src/room/domain/model.ts +++ b/packages/agent-room/src/room/domain/model.ts @@ -70,3 +70,4 @@ export interface RoomSlice { events: RoomEvent[]; head: RoomSeq; } + diff --git a/packages/agent-room/src/room/domain/pass.ts b/packages/agent-room/src/room/domain/pass.ts index ef4e859f..ed58067f 100644 --- a/packages/agent-room/src/room/domain/pass.ts +++ b/packages/agent-room/src/room/domain/pass.ts @@ -1,7 +1,6 @@ import { AgentSessionAggregate } from '../../agent-session/domain/agent-session'; import type { AgentSessionId } from '../../agent-session/domain/model'; -import { RoomValidationError } from './errors'; -import { sameRoomId } from './model'; +import { assertSessionInRoom } from './session-guard'; import { Room } from './room'; import type { RoomSeq } from './model'; @@ -21,13 +20,7 @@ export type PassInput = Pick; * pending-wake rule brings the member back for anything it did not read. */ export function pass(room: Room, session: AgentSessionAggregate, input: PassInput): PassResult { - const sessionId = session.id; - if (!sameRoomId(room.id, sessionId.roomId)) { - throw new RoomValidationError('agent session belongs to a different room'); - } - if (sessionId.tenantId !== room.id.tenantId) { - throw new RoomValidationError('agent session tenant does not match the room tenant'); - } + assertSessionInRoom(room, session); session.advanceSeen(input.readUpToSeq); return { outcome: 'passed' }; } diff --git a/packages/agent-room/src/room/domain/room.ts b/packages/agent-room/src/room/domain/room.ts index 77f16674..1a02691e 100644 --- a/packages/agent-room/src/room/domain/room.ts +++ b/packages/agent-room/src/room/domain/room.ts @@ -41,13 +41,14 @@ function validateRoomState(id: RoomId, events: RoomEvent[]): void { } } -function assertSeq(seq: RoomSeq, label: string): void { +/** A non-negative safe integer, as every sequence argument must be. */ +export function assertSeq(seq: RoomSeq, label: string): void { if (!Number.isSafeInteger(seq) || seq < 0) { throw new RoomValidationError(`${label} must be a non-negative integer`); } } -export function cloneRoomEvent(event: RoomEvent): RoomEvent { +function cloneRoomEvent(event: RoomEvent): RoomEvent { return { ...event, roomId: { ...event.roomId }, diff --git a/packages/agent-room/src/room/domain/session-guard.ts b/packages/agent-room/src/room/domain/session-guard.ts new file mode 100644 index 00000000..bea59aca --- /dev/null +++ b/packages/agent-room/src/room/domain/session-guard.ts @@ -0,0 +1,18 @@ +import type { AgentSessionAggregate } from '../../agent-session/domain/agent-session'; +import { RoomValidationError } from './errors'; +import { sameRoomId } from './model'; +import type { Room } from './room'; + +/** + * The membership checks every room command opens with: the session must live in + * this room, under this room's tenant. + */ +export function assertSessionInRoom(room: Room, session: AgentSessionAggregate): void { + const sessionId = session.id; + if (!sameRoomId(room.id, sessionId.roomId)) { + throw new RoomValidationError('agent session belongs to a different room'); + } + if (sessionId.tenantId !== room.id.tenantId) { + throw new RoomValidationError('agent session tenant does not match the room tenant'); + } +} diff --git a/packages/agent-room/src/room/domain/speak.ts b/packages/agent-room/src/room/domain/speak.ts index 8ec92c77..90cb4167 100644 --- a/packages/agent-room/src/room/domain/speak.ts +++ b/packages/agent-room/src/room/domain/speak.ts @@ -1,8 +1,8 @@ import { AgentSessionAggregate } from '../../agent-session/domain/agent-session'; import { sessionKey, type AgentSessionId } from '../../agent-session/domain/model'; import { RoomValidationError } from './errors'; -import { sameRoomId } from './model'; -import { Room } from './room'; +import { assertSessionInRoom } from './session-guard'; +import { assertSeq, type Room } from './room'; import type { AgentId, RoomEvent, RoomSeq } from './model'; export interface SpeakCommand { @@ -22,12 +22,6 @@ export type SpeakResult = export type SpeakInput = Pick; -function assertSeq(seq: RoomSeq, label: string): void { - if (!Number.isSafeInteger(seq) || seq < 0) { - throw new RoomValidationError(`${label} must be a non-negative integer`); - } -} - function eventAt(room: Room, seq: RoomSeq): RoomEvent { assertSeq(seq, 'trigger sequence'); // Restored streams are contiguous from 1, so the event at seq exists exactly @@ -46,14 +40,9 @@ function eventAt(room: Room, seq: RoomSeq): RoomEvent { * the same turn. */ export function speak(room: Room, session: AgentSessionAggregate, input: SpeakInput, at: string): SpeakResult { - const sessionId = session.id; - if (!sameRoomId(room.id, sessionId.roomId)) { - throw new RoomValidationError('agent session belongs to a different room'); - } - if (sessionId.tenantId !== room.id.tenantId) { - throw new RoomValidationError('agent session tenant does not match the room tenant'); - } + assertSessionInRoom(room, session); assertSeq(input.readUpToSeq, 'read up to sequence'); + const sessionId = session.id; const newer = room.eventsAfter(input.readUpToSeq, sessionId.agentId); if (newer.length > 0) { diff --git a/packages/agent-room/src/room/infrastructure/memory-room-stream-store.ts b/packages/agent-room/src/room/infrastructure/memory-room-stream-store.ts index 0cce6b57..b15c56a8 100644 --- a/packages/agent-room/src/room/infrastructure/memory-room-stream-store.ts +++ b/packages/agent-room/src/room/infrastructure/memory-room-stream-store.ts @@ -1,5 +1,11 @@ import { AgentSessionAggregate } from '../../agent-session/domain/agent-session'; -import type { AgentSession, AgentSessionId } from '../../agent-session/domain/model'; +import { + cloneSession, + sessionForwarders, + sessionKey, + type AgentSession, + type AgentSessionId, +} from '../../agent-session/domain/model'; import type { RoomStreamStore } from '../application/room-stream-store'; import { RoomStreamService } from '../application/room-stream-service'; import type { RoomUnitOfWork } from '../application/room-unit-of-work'; @@ -17,25 +23,6 @@ function roomStorageKey(id: RoomId): string { return JSON.stringify([id.tenantId, id.conversationId]); } -function sessionStorageKey(id: AgentSessionId): string { - return JSON.stringify([ - id.tenantId, - id.agentId, - id.roomId.tenantId, - id.roomId.conversationId, - id.runtimeGenerationId, - ]); -} - -function cloneSession(session: AgentSession): AgentSession { - return { - id: { - ...session.id, - roomId: { ...session.id.roomId }, - }, - seenSeq: session.seenSeq, - }; -} export class MemoryRoomUnitOfWork implements RoomUnitOfWork { private readonly rooms = new Map(); @@ -63,19 +50,19 @@ export class MemoryRoomUnitOfWork implements RoomUnitOfWork { const sessionSnapshot = session.snapshot(); this.beforeCommit?.(); this.rooms.set(roomStorageKey(id.roomId), roomSnapshot); - this.sessions.set(sessionStorageKey(id), sessionSnapshot); + this.sessions.set(sessionKey(id), sessionSnapshot); return result; } ensureSession(id: AgentSessionId): AgentSession { const session = this.loadSession(id); const snapshot = session.snapshot(); - this.sessions.set(sessionStorageKey(id), snapshot); + this.sessions.set(sessionKey(id), snapshot); return snapshot; } inspectSession(id: AgentSessionId): AgentSession | undefined { - const snapshot = this.sessions.get(sessionStorageKey(id)); + const snapshot = this.sessions.get(sessionKey(id)); return snapshot ? cloneSession(snapshot) : undefined; } @@ -88,15 +75,15 @@ export class MemoryRoomUnitOfWork implements RoomUnitOfWork { } private loadSession(id: AgentSessionId): AgentSessionAggregate { - const existing = this.sessions.get(sessionStorageKey(id)); - return new AgentSessionAggregate(id, existing ? { seenSeq: existing.seenSeq } : undefined); + // A stored snapshot already carries `seenSeq`; an absent one starts fresh. + return AgentSessionAggregate.fromStored(id, this.sessions.get(sessionKey(id))); } private changeSession(id: AgentSessionId, change: (session: AgentSessionAggregate) => void): AgentSession { const session = this.loadSession(id); change(session); const snapshot = session.snapshot(); - this.sessions.set(sessionStorageKey(id), snapshot); + this.sessions.set(sessionKey(id), snapshot); return snapshot; } } @@ -104,22 +91,27 @@ export class MemoryRoomUnitOfWork implements RoomUnitOfWork { export class MemoryRoomStreamStore implements RoomStreamStore { private readonly unitOfWork: MemoryRoomUnitOfWork; private readonly service: RoomStreamService; + private sessionAccess: ReturnType | undefined; constructor(options: MemoryRoomStreamStoreOptions = {}) { this.unitOfWork = new MemoryRoomUnitOfWork(options.beforeCommit); this.service = new RoomStreamService(this.unitOfWork, options.now ?? Date.now); } + private forwarders(): ReturnType { + return (this.sessionAccess ??= sessionForwarders(this.unitOfWork)); + } + ensureSession(id: AgentSessionId): AgentSession { - return this.unitOfWork.ensureSession(id); + return this.forwarders().ensureSession(id); } inspectSession(id: AgentSessionId): AgentSession | undefined { - return this.unitOfWork.inspectSession(id); + return this.forwarders().inspectSession(id); } advanceSeen(id: AgentSessionId, seq: RoomSeq): AgentSession { - return this.unitOfWork.advanceSeen(id, seq); + return this.forwarders().advanceSeen(id, seq); } async admit(input: AdmitRoomEvent): Promise { diff --git a/packages/agent-task-loop/bin/agent-task-loop.mjs b/packages/agent-task-loop/bin/agent-task-loop.mjs index d414a6e9..8aa26f74 100755 --- a/packages/agent-task-loop/bin/agent-task-loop.mjs +++ b/packages/agent-task-loop/bin/agent-task-loop.mjs @@ -13,18 +13,20 @@ const tsxLoader = path.join(packageRoot, 'node_modules', 'tsx', 'dist', 'loader. const forceSource = process.env.AGENT_TASK_LOOP_FORCE_SOURCE === '1'; const canRunFromSource = existsSync(sourceEntrypoint) && existsSync(tsxLoader); const fromSource = forceSource || canRunFromSource; -const command = process.execPath; const args = fromSource ? ['--import', tsxLoader, sourceEntrypoint, ...process.argv.slice(2)] : [distEntrypoint, ...process.argv.slice(2)]; +// tsx discovers tsconfig.json from the working directory. Invoked from a +// checkout root without a root tsconfig, it falls back to the classic JSX +// transform and the TUI dies with "React is not defined". Pin the package's +// own tsconfig for the source run (#141); the dist run needs no tsx. +const childEnv = fromSource + ? { ...process.env, TSX_TSCONFIG_PATH: path.join(packageRoot, 'tsconfig.json') } + : process.env; -const result = spawnSync(command, args, { +const result = spawnSync(process.execPath, args, { cwd: process.cwd(), - // tsx discovers tsconfig.json from the working directory. Invoked from a - // checkout root without a root tsconfig, it falls back to the classic JSX - // transform and the TUI dies with "React is not defined". Pin the package's - // own tsconfig for the source run (#141); the dist run needs no tsx. - env: fromSource ? { ...process.env, TSX_TSCONFIG_PATH: path.join(packageRoot, 'tsconfig.json') } : process.env, + env: childEnv, stdio: 'inherit', }); diff --git a/packages/agent-task-loop/src/adapters/base.ts b/packages/agent-task-loop/src/adapters/base.ts index 55070414..15f945cb 100644 --- a/packages/agent-task-loop/src/adapters/base.ts +++ b/packages/agent-task-loop/src/adapters/base.ts @@ -1,7 +1,7 @@ import { execa } from 'execa'; import type { TaskRecord } from '../types/task'; -export interface AgentExecutionResult { +interface AgentExecutionResult { status: 'success' | 'failure'; summary: string; workspacePath?: string; diff --git a/packages/agent-task-loop/src/adapters/claude-lines.ts b/packages/agent-task-loop/src/adapters/claude-lines.ts new file mode 100644 index 00000000..77a75622 --- /dev/null +++ b/packages/agent-task-loop/src/adapters/claude-lines.ts @@ -0,0 +1,47 @@ +/** + * The Claude CLI's stream-json events, as both the output formatter and the + * progress/summary extractors read them. + */ + +export interface ClaudeStreamEvent { + type?: string; + subtype?: string; + event?: { type?: string; content_block?: { type?: string; name?: string }; delta?: { type?: string; text?: string } }; + result?: unknown; + is_error?: boolean; +} + +/** The event a stream-json line carries, or undefined for a line that is not one. */ +export function claudeStreamEvent(line: string): ClaudeStreamEvent | undefined { + try { + const event = JSON.parse(line) as ClaudeStreamEvent; + if (event.type === undefined) { + return undefined; + } + return event; + } catch { + return undefined; + } +} + +/** A stream event's `stream_event` payload, when the event nests one. */ +export function claudeInnerEvent(event: ClaudeStreamEvent): ClaudeStreamEvent['event'] | undefined { + return event.event; +} + +/** The result events an output holds, last line first. */ +export function claudeResultEvents(output: string): ClaudeStreamEvent[] { + const events: ClaudeStreamEvent[] = []; + const lines = output + .split('\n') + .map((line) => line.trim()) + .filter(Boolean); + for (let index = lines.length - 1; index >= 0; index -= 1) { + try { + events.push(JSON.parse(lines[index]!) as ClaudeStreamEvent); + } catch { + continue; + } + } + return events; +} diff --git a/packages/agent-task-loop/src/adapters/claude.ts b/packages/agent-task-loop/src/adapters/claude.ts index b49422fa..917168c6 100644 --- a/packages/agent-task-loop/src/adapters/claude.ts +++ b/packages/agent-task-loop/src/adapters/claude.ts @@ -1,37 +1,32 @@ import type { AgentAdapter } from './base'; import { runAgentCommand } from './base'; +import { claudeInnerEvent, claudeResultEvents, claudeStreamEvent } from './claude-lines'; function formatClaudeEvent(line: string): string { - try { - const event = JSON.parse(line) as Record; - - if (event.type === 'stream_event') { - // event.event comes from an external JSON stream and may be missing at runtime. - const payload: Record | undefined = event.event; - - if (payload?.type === 'content_block_start' && payload.content_block?.type === 'tool_use') { - return `\n[claude] tool=${String(payload.content_block.name)}\n`; - } + const event = claudeStreamEvent(line); + if (event === undefined) { + return `${line}\n`; + } - if (payload?.type === 'content_block_delta' && payload.delta?.type === 'text_delta') { - return String(payload.delta.text ?? ''); - } + if (event.type === 'stream_event') { + const payload = claudeInnerEvent(event); - return ''; + if (payload?.type === 'content_block_start' && payload.content_block?.type === 'tool_use') { + return `\n[claude] tool=${String(payload.content_block.name)}\n`; } - if (event.type === 'result') { - if (event.subtype === 'success') { - return `\n[claude] completed\n`; - } - - return `\n[claude] failed\n`; + if (payload?.type === 'content_block_delta' && payload.delta?.type === 'text_delta') { + return String(payload.delta.text ?? ''); } return ''; - } catch { - return `${line}\n`; } + + if (event.type === 'result') { + return event.subtype === 'success' ? `\n[claude] completed\n` : `\n[claude] failed\n`; + } + + return ''; } function extractClaudeProgress(line: string): string | undefined { @@ -78,42 +73,20 @@ function extractClaudeSession(line: string): { sessionId?: string } | undefined } function extractClaudeSummary(output: string): string { - const lines = output - .split('\n') - .map((line) => line.trim()) - .filter(Boolean); - - for (let index = lines.length - 1; index >= 0; index -= 1) { - try { - const event = JSON.parse(lines[index]!) as Record; - if (event.type === 'result' && event.subtype === 'success' && typeof event.result === 'string') { - return event.result; - } - } catch { - continue; - } + const found = claudeResultEvents(output).find( + (event) => event.type === 'result' && event.subtype === 'success' && typeof event.result === 'string', + ); + if (found && typeof found.result === 'string') { + return found.result; } - return 'claude execution completed'; } function extractClaudeError(output: string): string | undefined { - const lines = output - .split('\n') - .map((line) => line.trim()) - .filter(Boolean); - - for (let index = lines.length - 1; index >= 0; index -= 1) { - try { - const event = JSON.parse(lines[index]!) as Record; - if (event.type === 'result' && event.is_error) { - return typeof event.result === 'string' ? event.result : 'claude execution failed'; - } - } catch { - continue; - } + const found = claudeResultEvents(output).find((event) => event.type === 'result' && event.is_error); + if (found) { + return typeof found.result === 'string' ? found.result : 'claude execution failed'; } - return undefined; } diff --git a/packages/agent-task-loop/src/commands/cleanup.ts b/packages/agent-task-loop/src/commands/cleanup.ts index a9653269..3a16bcc0 100644 --- a/packages/agent-task-loop/src/commands/cleanup.ts +++ b/packages/agent-task-loop/src/commands/cleanup.ts @@ -1,5 +1,5 @@ import { defineCommand } from 'citty'; -import { loadConfig } from '../config/load-config'; +import { loadCommandConfig, taskCommandArgs } from './command-context'; import { assertRuntimeConfig } from '../config/runtime-guard'; import { CleanupService } from '../services/cleanup-service'; import { PublishContextService } from '../services/publish-context-service'; @@ -20,16 +20,10 @@ export const cleanupCommand = defineCommand({ type: 'boolean', default: false, }, - config: { - type: 'string', - }, - json: { - type: 'boolean', - default: false, - }, + ...taskCommandArgs, }, async run({ args }) { - const config = await loadConfig(typeof args.config === 'string' ? args.config : undefined); + const config = await loadCommandConfig(args); assertRuntimeConfig(config); const service = new CleanupService({ diff --git a/packages/agent-task-loop/src/commands/command-context.ts b/packages/agent-task-loop/src/commands/command-context.ts new file mode 100644 index 00000000..3e84a2c8 --- /dev/null +++ b/packages/agent-task-loop/src/commands/command-context.ts @@ -0,0 +1,29 @@ +import { loadConfig } from '../config/load-config'; +import { assertRuntimeConfig } from '../config/runtime-guard'; +import { TaskService } from '../services/task-service'; + +/** + * What every task command parses and resolves before its service: the shared + * `--config` and `--json` argument fragments, and the config the `--config` + * override names. + */ +export const taskCommandArgs = { + config: { + type: 'string' as const, + }, + json: { + type: 'boolean' as const, + default: false, + }, +}; + +export async function loadCommandConfig(args: { config?: unknown }): Promise>> { + return loadConfig(typeof args.config === 'string' ? args.config : undefined); +} + +/** The runtime-checked config and its task service every task command starts with. */ +export async function taskServiceFrom(args: { config?: unknown }): Promise { + const config = await loadCommandConfig(args); + assertRuntimeConfig(config); + return new TaskService(config); +} diff --git a/packages/agent-task-loop/src/commands/complete.ts b/packages/agent-task-loop/src/commands/complete.ts index 74ad95ca..efe4725e 100644 --- a/packages/agent-task-loop/src/commands/complete.ts +++ b/packages/agent-task-loop/src/commands/complete.ts @@ -1,5 +1,5 @@ import { defineCommand } from 'citty'; -import { loadConfig } from '../config/load-config'; +import { loadCommandConfig, taskCommandArgs } from './command-context'; import { assertRuntimeConfig } from '../config/runtime-guard'; import { CompleteService } from '../services/complete-service'; import { GitHubPullRequestService } from '../services/github-pull-request-service'; @@ -39,16 +39,10 @@ export const completeCommand = defineCommand({ type: 'string', required: true, }, - config: { - type: 'string', - }, - json: { - type: 'boolean', - default: false, - }, + ...taskCommandArgs, }, async run({ args }) { - const config = await loadConfig(typeof args.config === 'string' ? args.config : undefined); + const config = await loadCommandConfig(args); assertRuntimeConfig(config); const taskService = new TaskService(config); const service = new CompleteService({ diff --git a/packages/agent-task-loop/src/commands/create.ts b/packages/agent-task-loop/src/commands/create.ts index b09df3c6..3266c051 100644 --- a/packages/agent-task-loop/src/commands/create.ts +++ b/packages/agent-task-loop/src/commands/create.ts @@ -1,7 +1,7 @@ import readline from 'node:readline'; import { defineCommand } from 'citty'; import { z } from 'zod'; -import { loadConfig } from '../config/load-config'; +import { loadCommandConfig, taskCommandArgs } from './command-context'; import { listSources } from '../config/source-config'; import { TaskService } from '../services/task-service'; import type { CreateTaskPayload } from '../task-management/task-provider'; @@ -203,13 +203,7 @@ export const createCommand = defineCommand({ type: 'string', description: 'Task source id (feishu or github:/)', }, - config: { - type: 'string', - }, - json: { - type: 'boolean', - default: false, - }, + ...taskCommandArgs, }, async run({ args }) { const prompted = await promptForMissing({ @@ -223,7 +217,7 @@ export const createCommand = defineCommand({ }); const inputs = validateInputs(prompted); - const config = await loadConfig(typeof args.config === 'string' ? args.config : undefined); + const config = await loadCommandConfig(args); const sourceSummaries = listSources(config); const sourceIds = sourceSummaries.map((source) => source.id); const defaultSource = sourceSummaries.find((source) => source.isDefault)?.id ?? sourceIds[0]; diff --git a/packages/agent-task-loop/src/commands/gh-repo.ts b/packages/agent-task-loop/src/commands/gh-repo.ts new file mode 100644 index 00000000..e9bf46af --- /dev/null +++ b/packages/agent-task-loop/src/commands/gh-repo.ts @@ -0,0 +1,15 @@ +import { execFileSync } from 'node:child_process'; + +/** Best-effort `gh repo view` lookup to prefill owner/repo. Returns undefined on any failure. */ +export function detectGitHubRepo(): { owner: string; repo: string } | undefined { + try { + const out = execFileSync('gh', ['repo', 'view', '--json', 'owner,name'], { encoding: 'utf8' }); + const parsed = JSON.parse(out) as { owner?: { login?: string }; name?: string }; + if (parsed.owner?.login && parsed.name) { + return { owner: parsed.owner.login, repo: parsed.name }; + } + } catch { + // gh missing or not in a repo — fall through to manual entry. + } + return undefined; +} diff --git a/packages/agent-task-loop/src/commands/init.ts b/packages/agent-task-loop/src/commands/init.ts index 075d86ff..1a4729b5 100644 --- a/packages/agent-task-loop/src/commands/init.ts +++ b/packages/agent-task-loop/src/commands/init.ts @@ -1,3 +1,4 @@ +import { detectGitHubRepo } from './gh-repo'; import { execFileSync } from 'node:child_process'; import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; import path from 'node:path'; @@ -106,19 +107,6 @@ async function confirmInstall(): Promise { return answer.trim().toLowerCase() === 'y'; } -/** Best-effort `gh repo view` lookup to prefill owner/repo. Returns undefined on any failure. */ -function detectGitHubRepo(): { owner: string; repo: string } | undefined { - try { - const out = execFileSync('gh', ['repo', 'view', '--json', 'owner,name'], { encoding: 'utf8' }); - const parsed = JSON.parse(out) as { owner?: { login?: string }; name?: string }; - if (parsed.owner?.login && parsed.name) { - return { owner: parsed.owner.login, repo: parsed.name }; - } - } catch { - // gh missing or not in a repo — fall through to manual entry. - } - return undefined; -} async function ensureLarkCli(): Promise { if (await isLarkCliAvailable()) { diff --git a/packages/agent-task-loop/src/commands/reject.ts b/packages/agent-task-loop/src/commands/reject.ts index c5b49e4b..52b6f56a 100644 --- a/packages/agent-task-loop/src/commands/reject.ts +++ b/packages/agent-task-loop/src/commands/reject.ts @@ -1,5 +1,5 @@ import { defineCommand } from 'citty'; -import { loadConfig } from '../config/load-config'; +import { loadCommandConfig } from './command-context'; import { assertRuntimeConfig } from '../config/runtime-guard'; import { RejectService } from '../services/reject-service'; import { ReviewLoopRunner } from '../services/review-loop-runner'; @@ -29,7 +29,7 @@ export const rejectCommand = defineCommand({ }, }, async run({ args }) { - const config = await loadConfig(typeof args.config === 'string' ? args.config : undefined); + const config = await loadCommandConfig(args); assertRuntimeConfig(config); const reason = String(args.reason).trim(); if (!reason) { diff --git a/packages/agent-task-loop/src/commands/resume.ts b/packages/agent-task-loop/src/commands/resume.ts index 45b0e3f4..0228a89b 100644 --- a/packages/agent-task-loop/src/commands/resume.ts +++ b/packages/agent-task-loop/src/commands/resume.ts @@ -1,8 +1,6 @@ import { defineCommand } from 'citty'; -import { loadConfig } from '../config/load-config'; -import { assertRuntimeConfig } from '../config/runtime-guard'; +import { taskServiceFrom } from './command-context'; import { resumeCommandFor } from '../session/resume'; -import { TaskService } from '../services/task-service'; export const resumeCommand = defineCommand({ meta: { @@ -19,9 +17,7 @@ export const resumeCommand = defineCommand({ }, }, async run({ args }) { - const config = await loadConfig(typeof args.config === 'string' ? args.config : undefined); - assertRuntimeConfig(config); - const taskService = new TaskService(config); + const taskService = await taskServiceFrom(args); const task = await taskService.getTaskById(String(args.task)); if (!task) { diff --git a/packages/agent-task-loop/src/commands/run.ts b/packages/agent-task-loop/src/commands/run.ts index 6a4935e0..add0d6e8 100644 --- a/packages/agent-task-loop/src/commands/run.ts +++ b/packages/agent-task-loop/src/commands/run.ts @@ -3,7 +3,7 @@ import { claudeAdapter } from '../adapters/claude'; import { cocoAdapter } from '../adapters/coco'; import { codexAdapter } from '../adapters/codex'; import { glmAdapter } from '../adapters/glm'; -import { loadConfig } from '../config/load-config'; +import { loadCommandConfig } from './command-context'; import { assertRuntimeConfig } from '../config/runtime-guard'; import { ExecutionService } from '../services/execution-service'; import { resolveTaskExecutionContext } from '../services/task-context-service'; @@ -41,7 +41,7 @@ export const runCommand = defineCommand({ }, async run({ args }) { const agent = args.agent as TargetAgent; - const config = await loadConfig(typeof args.config === 'string' ? args.config : undefined); + const config = await loadCommandConfig(args); assertRuntimeConfig(config); const taskService = new TaskService(config); const tasks = await taskService.listPendingTasks(agent); diff --git a/packages/agent-task-loop/src/commands/schema.ts b/packages/agent-task-loop/src/commands/schema.ts index 7bc4cc03..ae8b64db 100644 --- a/packages/agent-task-loop/src/commands/schema.ts +++ b/packages/agent-task-loop/src/commands/schema.ts @@ -1,5 +1,5 @@ import { defineCommand } from 'citty'; -import { loadConfig } from '../config/load-config'; +import { loadCommandConfig } from './command-context'; import { assertRuntimeConfig } from '../config/runtime-guard'; import { TaskTableSchemaService } from '../services/schema-service'; import { printCommandOutput } from './command-output'; @@ -23,7 +23,7 @@ export const schemaCommand = defineCommand({ }, }, async run({ args }) { - const config = await loadConfig(typeof args.config === 'string' ? args.config : undefined); + const config = await loadCommandConfig(args); assertRuntimeConfig(config); if (!config.feishu) { diff --git a/packages/agent-task-loop/src/commands/source.ts b/packages/agent-task-loop/src/commands/source.ts index 9e05d619..613bec6f 100644 --- a/packages/agent-task-loop/src/commands/source.ts +++ b/packages/agent-task-loop/src/commands/source.ts @@ -1,4 +1,4 @@ -import { execFileSync } from 'node:child_process'; +import { detectGitHubRepo } from './gh-repo'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import path from 'node:path'; import readline from 'node:readline'; @@ -57,19 +57,7 @@ async function ask(question: string): Promise { } } -/** Best-effort `gh repo view` to prefill owner/repo. */ -function detectRepo(): { owner: string; repo: string } | undefined { - try { - const out = execFileSync('gh', ['repo', 'view', '--json', 'owner,name'], { encoding: 'utf8' }); - const parsed = JSON.parse(out) as { owner?: { login?: string }; name?: string }; - if (parsed.owner?.login && parsed.name) { - return { owner: parsed.owner.login, repo: parsed.name }; - } - } catch { - // gh missing / not in a repo - } - return undefined; -} + const isTty = (): boolean => Boolean(process.stdin.isTTY && process.stdout.isTTY); @@ -146,7 +134,7 @@ export const sourceAddCommand = defineCommand({ raw.owner = args.owner; raw.repo = args.repo; if ((!raw.owner || !raw.repo) && isTty()) { - const detected = detectRepo(); + const detected = detectGitHubRepo(); raw.owner = raw.owner || (await ask(`GitHub owner${detected ? ` [${detected.owner}]` : ''}: `)) || detected?.owner; raw.repo = raw.repo || (await ask(`GitHub repo${detected ? ` [${detected.repo}]` : ''}: `)) || detected?.repo; diff --git a/packages/agent-task-loop/src/commands/start.ts b/packages/agent-task-loop/src/commands/start.ts index 5d6f31d2..cff0acc2 100644 --- a/packages/agent-task-loop/src/commands/start.ts +++ b/packages/agent-task-loop/src/commands/start.ts @@ -1,5 +1,5 @@ import { defineCommand } from 'citty'; -import { loadConfig } from '../config/load-config'; +import { loadCommandConfig } from './command-context'; import { assertRuntimeConfig } from '../config/runtime-guard'; import { ReviewLoopRunner } from '../services/review-loop-runner'; import { TaskService } from '../services/task-service'; @@ -29,7 +29,7 @@ export const startCommand = defineCommand({ }, }, async run({ args }) { - const config = await loadConfig(typeof args.config === 'string' ? args.config : undefined); + const config = await loadCommandConfig(args); assertRuntimeConfig(config); const taskService = new TaskService(config); let targetAgent: TargetAgent | undefined; diff --git a/packages/agent-task-loop/src/commands/sync.ts b/packages/agent-task-loop/src/commands/sync.ts index e7a0a57f..8d363003 100644 --- a/packages/agent-task-loop/src/commands/sync.ts +++ b/packages/agent-task-loop/src/commands/sync.ts @@ -1,5 +1,5 @@ import { defineCommand } from 'citty'; -import { loadConfig } from '../config/load-config'; +import { loadCommandConfig, taskCommandArgs } from './command-context'; import { printCommandOutput } from './command-output'; export const syncCommand = defineCommand({ @@ -8,16 +8,10 @@ export const syncCommand = defineCommand({ description: 'Validate local config', }, args: { - config: { - type: 'string', - }, - json: { - type: 'boolean', - default: false, - }, + ...taskCommandArgs, }, async run({ args }) { - const config = await loadConfig(typeof args.config === 'string' ? args.config : undefined); + const config = await loadCommandConfig(args); const result = { projects: Object.keys(config.projects).length, repositories: Object.keys(config.repositories).length, diff --git a/packages/agent-task-loop/src/commands/watch.ts b/packages/agent-task-loop/src/commands/watch.ts index b2f954af..642b6dc5 100644 --- a/packages/agent-task-loop/src/commands/watch.ts +++ b/packages/agent-task-loop/src/commands/watch.ts @@ -1,13 +1,13 @@ import fs from 'node:fs/promises'; import { defineCommand } from 'citty'; -import { loadConfig } from '../config/load-config'; +import { loadCommandConfig } from './command-context'; import { assertRuntimeConfig } from '../config/runtime-guard'; import { TaskService } from '../services/task-service'; import { TaskRunnerLivenessService } from '../services/task-runner-liveness-service'; import type { TaskRecord } from '../types/task'; const TERMINAL_STATUSES = new Set(['待决策', '待发布', '待验收', '已完成', '已失败']); -export const INITIAL_LOG_TAIL_BYTES = 64 * 1024; +const INITIAL_LOG_TAIL_BYTES = 64 * 1024; async function sleep(ms: number): Promise { await new Promise((resolve) => setTimeout(resolve, ms)); @@ -148,7 +148,7 @@ export const watchCommand = defineCommand({ }, }, async run({ args }) { - const config = await loadConfig(typeof args.config === 'string' ? args.config : undefined); + const config = await loadCommandConfig(args); assertRuntimeConfig(config); const taskService = new TaskService(config); const livenessService = new TaskRunnerLivenessService(); diff --git a/packages/agent-task-loop/src/config/schema.ts b/packages/agent-task-loop/src/config/schema.ts index f58eb230..4970cb4e 100644 --- a/packages/agent-task-loop/src/config/schema.ts +++ b/packages/agent-task-loop/src/config/schema.ts @@ -1,13 +1,13 @@ import { z } from 'zod'; -export const agentConfigSchema = z.object({ +const agentConfigSchema = z.object({ name: z.enum(['claude', 'codex', 'coco', 'glm']), command: z.string().min(1), args: z.array(z.string()).default([]), env: z.record(z.string(), z.string()).default({}), }); -export const repositoryConfigSchema = z.object({ +const repositoryConfigSchema = z.object({ key: z.string().min(1), localPath: z.string().min(1), defaultBranch: z.string().min(1), @@ -18,7 +18,7 @@ export const repositoryConfigSchema = z.object({ workspaceStrategy: z.enum(['existing-repo', 'worktree']), }); -export const projectConfigSchema = z.object({ +const projectConfigSchema = z.object({ key: z.string().min(1), name: z.string().min(1), defaultRepository: z.string().min(1), @@ -27,14 +27,14 @@ export const projectConfigSchema = z.object({ taskTemplatePrompt: z.string().default(''), }); -export const githubRepoConfigSchema = z.object({ +const githubRepoConfigSchema = z.object({ owner: z.string().min(1), repo: z.string().min(1), /** Per-repo override of the issues source's `defaultAgent`. */ defaultAgent: z.enum(['claude', 'codex', 'coco', 'glm']).optional(), }); -export const githubIssuesConfigSchema = z +const githubIssuesConfigSchema = z .object({ /** Single-repo shorthand: `owner` + `repo`. Use `repositories` for several. */ owner: z.string().min(1).optional(), @@ -57,9 +57,7 @@ export const githubIssuesConfigSchema = z } }); -export type GitHubRepoConfig = z.infer; - -export const feishuConfigSchema = z.object({ +const feishuConfigSchema = z.object({ baseToken: z.string().min(1), tableId: z.string().min(1), viewId: z.string().optional(), @@ -84,8 +82,6 @@ export const appConfigSchema = z } }); -export type FeishuConfig = z.infer; - export type GitHubIssuesConfig = z.infer; /** The pre-zod shape of githubIssues as it appears in the raw config file (defaultAgent optional). */ diff --git a/packages/agent-task-loop/src/orchestration/errors.ts b/packages/agent-task-loop/src/orchestration/errors.ts index f1ade514..77bee8ce 100644 --- a/packages/agent-task-loop/src/orchestration/errors.ts +++ b/packages/agent-task-loop/src/orchestration/errors.ts @@ -1,8 +1,8 @@ -export const ORCHESTRATION_CONFLICT_CODE = 'orchestration-conflict'; -export const ORCHESTRATION_NOT_FOUND_CODE = 'orchestration-not-found'; -export const ORCHESTRATION_SEAT_CODE = 'orchestration-seat'; -export const ORCHESTRATION_TEMPLATE_CODE = 'orchestration-template'; -export const ORCHESTRATION_RUN_CODE = 'orchestration-run'; +const ORCHESTRATION_CONFLICT_CODE = 'orchestration-conflict'; +const ORCHESTRATION_NOT_FOUND_CODE = 'orchestration-not-found'; +const ORCHESTRATION_SEAT_CODE = 'orchestration-seat'; +const ORCHESTRATION_TEMPLATE_CODE = 'orchestration-template'; +const ORCHESTRATION_RUN_CODE = 'orchestration-run'; export class OrchestrationConflictError extends Error { readonly code = ORCHESTRATION_CONFLICT_CODE; diff --git a/packages/agent-task-loop/src/orchestration/lease.ts b/packages/agent-task-loop/src/orchestration/lease.ts index eb3729f9..26fc804e 100644 --- a/packages/agent-task-loop/src/orchestration/lease.ts +++ b/packages/agent-task-loop/src/orchestration/lease.ts @@ -39,7 +39,7 @@ export function taskOrchestrationKey(taskId: string): string { } /** The per-key directory the file lease repository and the run-state store share. */ -export function defaultTaskLeaseDir(): string { +function defaultTaskLeaseDir(): string { return path.join(os.homedir(), '.agent-orchestration', 'runs'); } @@ -98,26 +98,34 @@ export class TaskLeaseStoreError 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 the orchestrator maps onto its own errors. */ +const TASK_LEASE_TAGS = ['LeaseHeld', 'LeaseLost', 'FenceRejected', 'LeaseConfigInvalid', 'LeaseRepositoryFailure'] as const; + +type TaskLeaseTag = (typeof TASK_LEASE_TAGS)[number]; + +function leaseTag(error: unknown): TaskLeaseTag | undefined { + if (typeof error !== 'object' || error === null || !('_tag' in error)) { + return undefined; + } + return TASK_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')) { + if (leaseTag(error) === 'LeaseHeld') { const held = error as LeaseHeld; return new OrchestrationConflictError(key, held.holder.pid); } - if (isTagged(error, 'LeaseLost')) { + if (leaseTag(error) === 'LeaseLost') { return new TaskLeaseLostError(error as LeaseLost); } - if (isTagged(error, 'FenceRejected')) { + if (leaseTag(error) === 'FenceRejected') { return new OrchestrationConflictError(key); } - if (isTagged(error, 'LeaseConfigInvalid')) { + if (leaseTag(error) === 'LeaseConfigInvalid') { return new TaskLeaseConfigError((error as { message: string }).message); } - if (isTagged(error, 'LeaseRepositoryFailure')) { + if (leaseTag(error) === 'LeaseRepositoryFailure') { return new TaskLeaseStoreError(error as LeaseRepositoryFailure); } if (error instanceof Error) { diff --git a/packages/agent-task-loop/src/orchestration/types.ts b/packages/agent-task-loop/src/orchestration/types.ts index c429fa90..beac922d 100644 --- a/packages/agent-task-loop/src/orchestration/types.ts +++ b/packages/agent-task-loop/src/orchestration/types.ts @@ -16,7 +16,7 @@ export interface SeatBind extends SeatBinding { env?: Record; } -export interface RunContextInput { +interface RunContextInput { goal?: string; ref?: Record; } @@ -28,20 +28,20 @@ export interface OpenRunInput { context?: RunContextInput; } -export interface FactEntry { +interface FactEntry { seat: string; text: string; at: string; } -export interface MailEntry { +interface MailEntry { from: string; to: string; body: string; at: string; } -export type SeatStatus = 'idle' | 'running' | 'exited'; +type SeatStatus = 'idle' | 'running' | 'exited'; export interface SeatState { cmd?: string; @@ -80,13 +80,13 @@ export interface ObservedRun { }; } -export interface SpawnResult { +interface SpawnResult { stdout: string; stderr: string; exitCode: number; } -export interface ProcessRunnerInput { +interface ProcessRunnerInput { cmd: string; args: string[]; cwd: string; diff --git a/packages/agent-task-loop/src/package-info.ts b/packages/agent-task-loop/src/package-info.ts index 4bd821bd..43627eee 100644 --- a/packages/agent-task-loop/src/package-info.ts +++ b/packages/agent-task-loop/src/package-info.ts @@ -1,13 +1,9 @@ import { readFileSync } from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +/** This package's version, read from its package.json at run time (source and dist both sit one level down). */ export function getPackageVersion(): string { - const packageJson = JSON.parse(readFileSync(path.join(packageRoot, 'package.json'), 'utf8')) as { + const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string; }; - - return packageJson.version; + return manifest.version; } diff --git a/packages/agent-task-loop/src/services/delivery-check-service.ts b/packages/agent-task-loop/src/services/delivery-check-service.ts index 15395a4d..3bc663b0 100644 --- a/packages/agent-task-loop/src/services/delivery-check-service.ts +++ b/packages/agent-task-loop/src/services/delivery-check-service.ts @@ -1,5 +1,7 @@ import { execa } from 'execa'; +import { runGit, type ExecLike } from './git-run'; + export interface DeliveryCheckInput { workspacePath: string; baseRef: string; @@ -13,8 +15,6 @@ export interface DeliveryCheckResult { reason: 'published' | 'working-tree-changes' | 'new-commit' | 'none'; } -type ExecLike = typeof execa; - export class DeliveryCheckService { constructor(private readonly exec: ExecLike = execa) {} @@ -43,7 +43,6 @@ export class DeliveryCheckService { } private runGit(args: string[], signal?: AbortSignal) { - signal?.throwIfAborted(); - return signal ? this.exec('git', args, { cancelSignal: signal }) : this.exec('git', args); + return runGit(this.exec, args, signal); } } diff --git a/packages/agent-task-loop/src/services/execution-service.ts b/packages/agent-task-loop/src/services/execution-service.ts index 4bed2338..3fc406a4 100644 --- a/packages/agent-task-loop/src/services/execution-service.ts +++ b/packages/agent-task-loop/src/services/execution-service.ts @@ -7,6 +7,7 @@ import type { TaskMutationFence, TaskService } from './task-service'; import { appendSessionHistory, formatSessionHistoryEntry } from './session-history'; import { formatFailureMessage, type FailureMessageFormatter } from './failure-message'; +import { createHeartbeatWriter } from './heartbeat'; function buildSessionName(task: TaskRecord): string { return `${task.taskId}-${task.targetAgent}` .toLowerCase() @@ -67,41 +68,17 @@ export class ExecutionService { let latestProgressSummary = `已认领任务,正在准备工作区并启动 ${task.targetAgent}`; let latestSessionId = task.sessionId; let latestSessionHistory = task.sessionHistory; - let latestRunnerPid = task.runnerPid; - let latestHeartbeatAt = new Date().toISOString(); let lastRecordedSessionKey: string | undefined; - let lastHeartbeatPersistedAt = 0; - const persistHeartbeat = async (force = false) => { - signal?.throwIfAborted(); - const now = Date.now(); - if (!force && now - lastHeartbeatPersistedAt < 15_000) { - return; - } - - latestHeartbeatAt = new Date(now).toISOString(); - lastHeartbeatPersistedAt = now; - try { - await this.persist(() => - this.deps.taskService.updateRunnerState(task, { - runnerPid: latestRunnerPid, - runnerKind: 'execute', - runnerAgent: task.targetAgent, - runnerRound: round, - lastHeartbeatAt: latestHeartbeatAt, - }), - ); - } catch (error) { - signal?.throwIfAborted(); - if (this.deps.onHeartbeatError) { - this.deps.onHeartbeatError(error); - } else { - const message = error instanceof Error ? error.message : String(error); - writeLog(`\n[agent-task-loop] heartbeat update failed: ${message}\n`); - } - } - signal?.throwIfAborted(); - }; - const writeProgress = async (summary: string) => { + const heartbeat = createHeartbeatWriter({ + signal, + runner: { agent: task.targetAgent, round }, + persist: async (update) => { + await this.persist(() => this.deps.taskService.updateRunnerState(task, update)); + }, + onHeartbeatError: this.deps.onHeartbeatError, + }); + heartbeat.pid(task.runnerPid); + const writeProgress = async (summary: string) => { if (!summary || summary === latestProgressSummary) { return; } @@ -110,17 +87,13 @@ export class ExecutionService { latestProgressSummary = summary; await this.persist(() => this.deps.taskService.updateTaskProgress(task, { + ...heartbeat.payload(), progressSummary: summary, workspacePath, logPath, sessionId: latestSessionId, sessionName, sessionHistory: latestSessionHistory, - runnerPid: latestRunnerPid, - runnerKind: 'execute', - runnerAgent: task.targetAgent, - runnerRound: round, - lastHeartbeatAt: latestHeartbeatAt, }), ); signal?.throwIfAborted(); @@ -154,17 +127,13 @@ export class ExecutionService { signal?.throwIfAborted(); await this.persist(() => this.deps.taskService.updateTaskProgress(task, { + ...heartbeat.payload(), progressSummary: latestProgressSummary, workspacePath, logPath, sessionId: nextSessionId, sessionName: nextSessionName, sessionHistory: latestSessionHistory, - runnerPid: latestRunnerPid, - runnerKind: 'execute', - runnerAgent: task.targetAgent, - runnerRound: round, - lastHeartbeatAt: latestHeartbeatAt, }), ); signal?.throwIfAborted(); @@ -186,11 +155,7 @@ export class ExecutionService { sessionId: latestSessionId, sessionName, sessionHistory: latestSessionHistory, - runnerPid: latestRunnerPid, - runnerKind: 'execute', - runnerAgent: task.targetAgent, - runnerRound: round, - lastHeartbeatAt: latestHeartbeatAt, + ...heartbeat.payload(), }), ); signal?.throwIfAborted(); @@ -207,13 +172,7 @@ export class ExecutionService { env: this.deps.adapterCommand.env, sessionName, signal, - onSpawn: async (payload) => { - latestRunnerPid = payload.pid; - await persistHeartbeat(true); - }, - onHeartbeat: async () => { - await persistHeartbeat(); - }, + ...heartbeat.callbacks(), onOutput: writeLog, onProgress: writeProgress, onSession: writeSession, diff --git a/packages/agent-task-loop/src/services/git-publish-service.ts b/packages/agent-task-loop/src/services/git-publish-service.ts index e260db20..2a040cee 100644 --- a/packages/agent-task-loop/src/services/git-publish-service.ts +++ b/packages/agent-task-loop/src/services/git-publish-service.ts @@ -3,7 +3,7 @@ import os from 'node:os'; import path from 'node:path'; import { execa } from 'execa'; -type ExecLike = typeof execa; +import { runGit, type ExecLike } from './git-run'; export class GitPublishService { constructor(private readonly exec: ExecLike = execa) {} @@ -81,7 +81,6 @@ export class GitPublishService { } private runGit(args: string[], signal?: AbortSignal) { - signal?.throwIfAborted(); - return signal ? this.exec('git', args, { cancelSignal: signal }) : this.exec('git', args); + return runGit(this.exec, args, signal); } } diff --git a/packages/agent-task-loop/src/services/git-run.ts b/packages/agent-task-loop/src/services/git-run.ts new file mode 100644 index 00000000..639ddb88 --- /dev/null +++ b/packages/agent-task-loop/src/services/git-run.ts @@ -0,0 +1,15 @@ +import { execa } from 'execa'; + +/** The spawn seam the git-backed services inject for tests. */ +export type ExecLike = typeof execa; + +/** + * One `git` invocation through the injected runner: the abort signal, when the + * caller carries one, becomes the child's cancel signal. The call stays + * two-arg when there is no signal, so the runner's overload resolution (and + * any test's argument assertions) see exactly the historical shape. + */ +export function runGit(exec: ExecLike, args: string[], signal?: AbortSignal) { + signal?.throwIfAborted(); + return signal ? exec('git', args, { cancelSignal: signal }) : exec('git', args); +} diff --git a/packages/agent-task-loop/src/services/heartbeat.ts b/packages/agent-task-loop/src/services/heartbeat.ts new file mode 100644 index 00000000..d460bbfb --- /dev/null +++ b/packages/agent-task-loop/src/services/heartbeat.ts @@ -0,0 +1,101 @@ +import type { TaskRunnerKind } from '../task-management/task-provider'; + +/** The runner identity a heartbeat write carries. */ +export interface RunnerHeartbeat { + runnerPid?: number; + runnerKind: TaskRunnerKind; + runnerAgent: string; + runnerRound: number; + lastHeartbeatAt: string; +} + +/** + * The heartbeat loop a runner loop shares: at most one write per interval, the + * timestamp advancing on every persist, and the caller's own persistence seam + * (`this.persist`, a mutation fence) carrying the write. A write failure is + * reported, not raised — the run continues on a stale heartbeat. + */ +export function createHeartbeatWriter(options: { + signal?: AbortSignal; + /** Throttle interval in milliseconds between persisted beats. */ + readonly intervalMs?: number; + /** Who runs and at which round; the pid changes as the child restarts. */ + readonly runner: { readonly agent: string; readonly round: number }; + /** The persistence seam: the caller's own transaction/fence wrapper. */ + readonly persist: (update: RunnerHeartbeat) => Promise; + /** Called with a failed write when the caller wants more than the log line. */ + readonly onHeartbeatError?: (error: unknown) => void; +}) { + const intervalMs = options.intervalMs ?? 15_000; + let latestRunnerPid: number | undefined; + let latestHeartbeatAt = new Date().toISOString(); + let lastHeartbeatPersistedAt = 0; + + const write = async (): Promise => { + latestHeartbeatAt = new Date().toISOString(); + lastHeartbeatPersistedAt = Date.now(); + try { + await options.persist({ + runnerPid: latestRunnerPid, + runnerKind: 'execute', + runnerAgent: options.runner.agent, + runnerRound: options.runner.round, + lastHeartbeatAt: latestHeartbeatAt, + }); + } catch (error) { + options.signal?.throwIfAborted(); + if (options.onHeartbeatError) { + options.onHeartbeatError(error); + } else { + const message = error instanceof Error ? error.message : String(error); + console.error(`\n[agent-task-loop] heartbeat update failed: ${message}\n`); + } + } + options.signal?.throwIfAborted(); + }; + + return { + /** Records the child's pid for the next persisted beat. */ + pid(pid: number | undefined): void { + latestRunnerPid = pid; + }, + /** The timestamp the progress writes should carry. */ + get timestamp(): string { + return latestHeartbeatAt; + }, + /** The runner identity as the current write carries it. */ + payload(): RunnerHeartbeat { + return { + runnerPid: latestRunnerPid, + runnerKind: 'execute', + runnerAgent: options.runner.agent, + runnerRound: options.runner.round, + lastHeartbeatAt: latestHeartbeatAt, + }; + }, + /** The spawn/heartbeat callback pair a runner loop hands its adapter. */ + callbacks(): { + onSpawn: (payload: { pid?: number }) => Promise; + onHeartbeat: () => Promise; + } { + return { + onSpawn: async (payload) => { + this.pid(payload.pid); + await this.persist(true); + }, + onHeartbeat: async () => { + await this.persist(); + }, + }; + }, + /** Persists a beat unless one was persisted within the interval. */ + async persist(force = false): Promise { + options.signal?.throwIfAborted(); + const now = Date.now(); + if (!force && now - lastHeartbeatPersistedAt < intervalMs) { + return; + } + await write(); + }, + }; +} diff --git a/packages/agent-task-loop/src/services/publish-context-service.ts b/packages/agent-task-loop/src/services/publish-context-service.ts index 9038fc38..4d718e19 100644 --- a/packages/agent-task-loop/src/services/publish-context-service.ts +++ b/packages/agent-task-loop/src/services/publish-context-service.ts @@ -1,5 +1,7 @@ import { execa } from 'execa'; +import { runGit, type ExecLike } from './git-run'; + export interface PublishContext { workspacePath: string; branch: string; @@ -10,8 +12,6 @@ export interface PublishContext { status: string; } -type ExecLike = typeof execa; - export class PublishContextService { constructor(private readonly exec: ExecLike = execa) {} @@ -51,7 +51,6 @@ export class PublishContextService { } private runGit(args: string[], signal?: AbortSignal) { - signal?.throwIfAborted(); - return signal ? this.exec('git', args, { cancelSignal: signal }) : this.exec('git', args); + return runGit(this.exec, args, signal); } } diff --git a/packages/agent-task-loop/src/services/review-loop-runner.ts b/packages/agent-task-loop/src/services/review-loop-runner.ts index cef6eaf3..9efaa170 100644 --- a/packages/agent-task-loop/src/services/review-loop-runner.ts +++ b/packages/agent-task-loop/src/services/review-loop-runner.ts @@ -1,3 +1,4 @@ +import { createHeartbeatWriter } from './heartbeat'; import { claudeAdapter } from '../adapters/claude'; import { cocoAdapter } from '../adapters/coco'; import { codexAdapter } from '../adapters/codex'; @@ -148,47 +149,25 @@ export class ReviewLoopRunner { adapter: adapters[reviewerAgent], command: this.deps.config.agents[reviewerAgent], }); - let latestRunnerPid: number | undefined; - let latestHeartbeatAt = new Date().toISOString(); - let lastHeartbeatPersistedAt = 0; - const persistHeartbeat = async (force = false) => { - signal?.throwIfAborted(); - const now = Date.now(); - if (!force && now - lastHeartbeatPersistedAt < 15_000) { - return; - } - - latestHeartbeatAt = new Date(now).toISOString(); - lastHeartbeatPersistedAt = now; - try { + const heartbeat = createHeartbeatWriter({ + signal, + runner: { agent: reviewerAgent, round: input.reviewRound }, + persist: async (update) => { await mutationFence.run(() => this.deps.taskService.updateRunnerState(input.task as Pick, { - runnerPid: latestRunnerPid, + ...update, runnerKind: 'review', - runnerAgent: reviewerAgent, - runnerRound: input.reviewRound, - lastHeartbeatAt: latestHeartbeatAt, }), ); - } catch (error) { - signal?.throwIfAborted(); - if (this.deps.onBackgroundError) { - this.deps.onBackgroundError(error); - } else { - const message = error instanceof Error ? error.message : String(error); - console.warn(`[agent-task-loop] review heartbeat update failed: ${message}`); - } - } - signal?.throwIfAborted(); - }; + }, + onHeartbeatError: this.deps.onBackgroundError, + }); signal?.throwIfAborted(); await mutationFence.run(() => this.deps.taskService.updateRunnerState(input.task as Pick, { + ...heartbeat.payload(), runnerKind: 'review', - runnerAgent: reviewerAgent, - runnerRound: input.reviewRound, - lastHeartbeatAt: latestHeartbeatAt, }), ); signal?.throwIfAborted(); @@ -197,13 +176,7 @@ export class ReviewLoopRunner { ...input, reviewerAgent, signal, - onSpawn: async (payload) => { - latestRunnerPid = payload.pid; - await persistHeartbeat(true); - }, - onHeartbeat: async () => { - await persistHeartbeat(); - }, + ...heartbeat.callbacks(), }); }, isTaskDeliverable: async (deliveryInput) => { diff --git a/packages/agent-task-loop/src/services/review-loop-service.ts b/packages/agent-task-loop/src/services/review-loop-service.ts index 1c82564f..472afcef 100644 --- a/packages/agent-task-loop/src/services/review-loop-service.ts +++ b/packages/agent-task-loop/src/services/review-loop-service.ts @@ -5,6 +5,34 @@ import { appendSessionHistory, formatSessionHistoryEntry } from './session-histo import { formatFailureMessage, type FailureMessageFormatter } from './failure-message'; import type { TaskMutationFence } from './task-service'; +/** + * The acceptance write both review-loop outcomes share: the verdict is a pass, + * the review session's identity rides along, and the outcome carries its own + * status and progress wording. + */ +function acceptanceUpdate( + input: { round: number; task: { executionSessionId?: string; executionSessionName?: string; sessionHistory?: string } }, + review: { sessionId?: string; sessionName?: string }, + overrides: { status?: '待发布' | '待决策'; progressSummary?: string; lastError?: string }, +) { + return { + status: overrides.status ?? ('待发布' as const), + currentOwner: '用户', + reviewRound: input.round, + reviewVerdict: '通过' as const, + reviewFindings: '', + ...(input.task.executionSessionId !== undefined ? { executionSessionId: input.task.executionSessionId } : {}), + ...(input.task.executionSessionName !== undefined + ? { executionSessionName: input.task.executionSessionName } + : {}), + ...(review.sessionId !== undefined ? { reviewSessionId: review.sessionId } : {}), + ...(review.sessionName !== undefined ? { reviewSessionName: review.sessionName } : {}), + ...(input.task.sessionHistory !== undefined ? { sessionHistory: input.task.sessionHistory } : {}), + ...(overrides.progressSummary !== undefined ? { progressSummary: overrides.progressSummary } : {}), + ...(overrides.lastError !== undefined ? { lastError: overrides.lastError } : {}), + }; +} + export class ReviewLoopService { constructor( private readonly deps: { @@ -209,18 +237,10 @@ export class ReviewLoopService { this.assertActive(); await this.persist(() => this.deps.updateReviewState(input.task, { - status: '待发布', - currentOwner: '用户', - reviewRound: input.round, - reviewVerdict: '通过', - reviewFindings: '', - executionSessionId: input.task.executionSessionId, - executionSessionName: input.task.executionSessionName, - reviewSessionId: review.sessionId, - reviewSessionName: review.sessionName, - sessionHistory: input.task.sessionHistory, - progressSummary: '自动推送远端分支失败,请先处理发布问题', - lastError: formatFailureMessage(this.deps.formatFailure, error, 'Task publication failed'), + ...acceptanceUpdate(input, review, { + progressSummary: '自动推送远端分支失败,请先处理发布问题', + lastError: formatFailureMessage(this.deps.formatFailure, error, 'Task publication failed'), + }), runnerKind: '', runnerAgent: '', }), @@ -232,17 +252,10 @@ export class ReviewLoopService { this.assertActive(); await this.persist(() => this.deps.updateReviewState(input.task, { - status: isDeliverable ? '待发布' : '待决策', - currentOwner: '用户', - reviewRound: input.round, - reviewVerdict: '通过', - reviewFindings: '', - executionSessionId: input.task.executionSessionId, - executionSessionName: input.task.executionSessionName, - reviewSessionId: review.sessionId, - reviewSessionName: review.sessionName, - sessionHistory: input.task.sessionHistory, - progressSummary: isDeliverable ? acceptanceProgressSummary : '诊断已完成,等待用户确定修复方向', + ...acceptanceUpdate(input, review, { + status: isDeliverable ? '待发布' : '待决策', + progressSummary: isDeliverable ? acceptanceProgressSummary : '诊断已完成,等待用户确定修复方向', + }), runnerKind: '', runnerAgent: '', }), diff --git a/packages/agent-task-loop/src/session/resume-form.ts b/packages/agent-task-loop/src/session/resume-form.ts new file mode 100644 index 00000000..f740bcb2 --- /dev/null +++ b/packages/agent-task-loop/src/session/resume-form.ts @@ -0,0 +1,15 @@ +/** + * The copyable resume command for a session, from a per-agent builder table. + * `null` when the agent has no known resume form or the session id is missing. + */ +export function resumeCommandFrom string>( + resumeCommands: Readonly>>, + agent: string | undefined, + sessionId: string | undefined | null, +): string | null { + if (!sessionId) { + return null; + } + const build = agent === undefined ? undefined : resumeCommands[agent]; + return build ? build(sessionId) : null; +} diff --git a/packages/agent-task-loop/src/session/resume.ts b/packages/agent-task-loop/src/session/resume.ts index 6fccbcc7..342f3967 100644 --- a/packages/agent-task-loop/src/session/resume.ts +++ b/packages/agent-task-loop/src/session/resume.ts @@ -1,3 +1,4 @@ +import { resumeCommandFrom } from './resume-form'; import type { TargetAgent } from '../types/task'; /** @@ -19,9 +20,5 @@ const RESUME_COMMANDS: Partial string * the agent has no known resume form (coco, glm) or the session id is missing. */ export function resumeCommandFor(agent: TargetAgent | undefined, sessionId: string | undefined | null): string | null { - if (!sessionId) { - return null; - } - const build = agent === undefined ? undefined : RESUME_COMMANDS[agent]; - return build ? build(sessionId) : null; + return resumeCommandFrom(RESUME_COMMANDS, agent, sessionId); } diff --git a/packages/agent-task-loop/src/task-management/feishu-task-provider.ts b/packages/agent-task-loop/src/task-management/feishu-task-provider.ts index 5fbc5773..f266689a 100644 --- a/packages/agent-task-loop/src/task-management/feishu-task-provider.ts +++ b/packages/agent-task-loop/src/task-management/feishu-task-provider.ts @@ -1,3 +1,4 @@ +import { pendingTasksFrom, taskByIdFrom, type RunnerSessionFields } from './task-provider'; import type { AppConfig } from '../config/schema'; import type { AcceptanceVerdict, ReviewVerdict, TargetAgent, TaskRecord, TaskStatus } from '../types/task'; import { runLarkCli } from '../services/lark-cli'; @@ -152,7 +153,7 @@ function optionalCellText(value: unknown): string | undefined { return value ? cellText(value) : undefined; } -export const FEISHU_SOURCE = 'feishu'; +const FEISHU_SOURCE = 'feishu'; export class FeishuTaskProvider implements SourceProvider { readonly source = FEISHU_SOURCE; @@ -171,13 +172,11 @@ export class FeishuTaskProvider implements SourceProvider { return this.config.feishu; } - async listPendingTasks(agent: TargetAgent): Promise { - return (await this.listTasks()).filter((task) => task.targetAgent === agent && task.status === '待处理'); - } + readonly listPendingTasks = (agent: TargetAgent): Promise => + pendingTasksFrom(() => this.listTasks(), agent); - async getTaskById(taskId: string): Promise { - return (await this.listTasks()).find((task) => task.taskId === taskId); - } + readonly getTaskById = (taskId: string): Promise => + taskByIdFrom(() => this.listTasks(), taskId); async createTask(payload: CreateTaskPayload): Promise { // No --record-id ⇒ record-upsert inserts a brand-new row. @@ -253,7 +252,28 @@ export class FeishuTaskProvider implements SourceProvider { }; } - async claimTask(task: TaskRef, payload: ClaimTaskPayload): Promise { + private runnerFields(payload: RunnerSessionFields): Record { + return { + WorkspacePath: payload.workspacePath, + LogPath: payload.logPath, + ProgressSummary: payload.progressSummary, + SessionId: payload.sessionId, + SessionName: payload.sessionName, + SessionHistory: payload.sessionHistory, + RunnerPid: payload.runnerPid, + RunnerKind: payload.runnerKind, + RunnerAgent: payload.runnerAgent, + RunnerRound: payload.runnerRound, + LastHeartbeatAt: payload.lastHeartbeatAt, + }; + } + + /** One record write: resolve the record id, then upsert the fields through lark-cli. */ + private async upsertRecord( + task: TaskRef, + fields: Record, + options?: { touchUpdatedAt?: boolean }, + ): Promise { const taskRef = await this.resolveRecordRef(task); await runLarkCli([ 'base', @@ -264,265 +284,129 @@ export class FeishuTaskProvider implements SourceProvider { this.feishu.tableId, ...(taskRef.recordId ? ['--record-id', taskRef.recordId] : []), '--json', - JSON.stringify( - buildRecordPayload(task.taskId, { - Status: '执行中', - ClaimedBy: payload.claimedBy, - ClaimedAt: payload.claimedAt, - RunId: payload.runId, - WorkspacePath: payload.workspacePath, - LogPath: payload.logPath, - ProgressSummary: payload.progressSummary, - SessionId: payload.sessionId, - SessionName: payload.sessionName, - SessionHistory: payload.sessionHistory, - RunnerPid: payload.runnerPid, - RunnerKind: payload.runnerKind, - RunnerAgent: payload.runnerAgent, - RunnerRound: payload.runnerRound, - LastHeartbeatAt: payload.lastHeartbeatAt, - CurrentOwner: payload.claimedBy.split('@')[0], - LastError: '', - }), - ), + JSON.stringify(buildRecordPayload(task.taskId, fields, options)), ]); } + async claimTask(task: TaskRef, payload: ClaimTaskPayload): Promise { + await this.upsertRecord(task, { + Status: '执行中', + ClaimedBy: payload.claimedBy, + ClaimedAt: payload.claimedAt, + RunId: payload.runId, + ...this.runnerFields(payload), + CurrentOwner: payload.claimedBy.split('@')[0], + LastError: '', + }); + } + async updateTaskProgress(task: TaskRef, payload: UpdateTaskProgressPayload): Promise { - const taskRef = await this.resolveRecordRef(task); - await runLarkCli([ - 'base', - '+record-upsert', - '--base-token', - this.feishu.baseToken, - '--table-id', - this.feishu.tableId, - ...(taskRef.recordId ? ['--record-id', taskRef.recordId] : []), - '--json', - JSON.stringify( - buildRecordPayload(task.taskId, { - ProgressSummary: payload.progressSummary, - WorkspacePath: payload.workspacePath, - LogPath: payload.logPath, - SessionId: payload.sessionId, - SessionName: payload.sessionName, - SessionHistory: payload.sessionHistory, - RunnerPid: payload.runnerPid, - RunnerKind: payload.runnerKind, - RunnerAgent: payload.runnerAgent, - RunnerRound: payload.runnerRound, - LastHeartbeatAt: payload.lastHeartbeatAt, - }), - ), - ]); + await this.upsertRecord(task, this.runnerFields(payload)); } async updateRunnerState(task: TaskRef, payload: UpdateRunnerStatePayload): Promise { - const taskRef = await this.resolveRecordRef(task); - await runLarkCli([ - 'base', - '+record-upsert', - '--base-token', - this.feishu.baseToken, - '--table-id', - this.feishu.tableId, - ...(taskRef.recordId ? ['--record-id', taskRef.recordId] : []), - '--json', - JSON.stringify( - buildRecordPayload(task.taskId, { - RunnerPid: payload.runnerPid, - RunnerKind: payload.runnerKind, - RunnerAgent: payload.runnerAgent, - RunnerRound: payload.runnerRound, - LastHeartbeatAt: payload.lastHeartbeatAt, - }), - ), - ]); + await this.upsertRecord(task, { + RunnerPid: payload.runnerPid, + RunnerKind: payload.runnerKind, + RunnerAgent: payload.runnerAgent, + RunnerRound: payload.runnerRound, + LastHeartbeatAt: payload.lastHeartbeatAt, + }); } async updateTaskAssignment(task: TaskRef, payload: UpdateTaskAssignmentPayload): Promise { - const taskRef = await this.resolveRecordRef(task); - await runLarkCli([ - 'base', - '+record-upsert', - '--base-token', - this.feishu.baseToken, - '--table-id', - this.feishu.tableId, - ...(taskRef.recordId ? ['--record-id', taskRef.recordId] : []), - '--json', - JSON.stringify( - buildRecordPayload(task.taskId, { - TargetAgent: [payload.targetAgent], - CurrentOwner: payload.currentOwner, - ProgressSummary: payload.progressSummary, - LastError: payload.lastError, - WorkspacePath: payload.workspacePath, - }), - ), - ]); + await this.upsertRecord(task, { + TargetAgent: [payload.targetAgent], + CurrentOwner: payload.currentOwner, + ProgressSummary: payload.progressSummary, + LastError: payload.lastError, + WorkspacePath: payload.workspacePath, + }); } async markTaskSucceeded(task: TaskRef, payload: MarkTaskSucceededPayload): Promise { - const taskRef = await this.resolveRecordRef(task); - await runLarkCli([ - 'base', - '+record-upsert', - '--base-token', - this.feishu.baseToken, - '--table-id', - this.feishu.tableId, - ...(taskRef.recordId ? ['--record-id', taskRef.recordId] : []), - '--json', - JSON.stringify( - buildRecordPayload(task.taskId, { - Status: '待验收', - ResultSummary: payload.resultSummary, - WorkspacePath: payload.workspacePath, - LogPath: payload.logPath, - ProgressSummary: payload.progressSummary, - SessionId: payload.sessionId, - SessionName: payload.sessionName, - SessionHistory: payload.sessionHistory, - PRLink: payload.prLink, - LastError: '', - }), - ), - ]); + await this.upsertRecord(task, { + Status: '待验收', + ResultSummary: payload.resultSummary, + ...this.runnerFields(payload), + PRLink: payload.prLink, + LastError: '', + }); } async markTaskFailed(task: TaskRef, payload: MarkTaskFailedPayload): Promise { - const taskRef = await this.resolveRecordRef(task); - await runLarkCli([ - 'base', - '+record-upsert', - '--base-token', - this.feishu.baseToken, - '--table-id', - this.feishu.tableId, - ...(taskRef.recordId ? ['--record-id', taskRef.recordId] : []), - '--json', - JSON.stringify( - buildRecordPayload(task.taskId, { - Status: '已失败', - LastError: payload.lastError, - WorkspacePath: payload.workspacePath, - LogPath: payload.logPath, - ProgressSummary: payload.progressSummary, - SessionId: payload.sessionId, - SessionName: payload.sessionName, - SessionHistory: payload.sessionHistory, - }), - ), - ]); + await this.upsertRecord(task, { + Status: '已失败', + LastError: payload.lastError, + ...this.runnerFields(payload), + }); } async updateReviewState(task: TaskRef, payload: UpdateReviewStatePayload): Promise { - const taskRef = await this.resolveRecordRef(task); const shouldClearRunner = !RUNNING_STATUSES.has(payload.status); - await runLarkCli([ - 'base', - '+record-upsert', - '--base-token', - this.feishu.baseToken, - '--table-id', - this.feishu.tableId, - ...(taskRef.recordId ? ['--record-id', taskRef.recordId] : []), - '--json', - JSON.stringify( - buildRecordPayload(task.taskId, { - Status: [payload.status], - CurrentOwner: payload.currentOwner, - ReviewRound: payload.reviewRound, - ReviewVerdict: payload.reviewVerdict ? [payload.reviewVerdict] : undefined, - ReviewFindings: payload.reviewFindings, - AcceptanceRound: payload.acceptanceRound, - AcceptanceVerdict: payload.acceptanceVerdict ? [payload.acceptanceVerdict] : undefined, - AcceptanceFeedback: payload.acceptanceFeedback, - ExecutionSessionId: payload.executionSessionId, - ExecutionSessionName: payload.executionSessionName, - ReviewSessionId: payload.reviewSessionId, - ReviewSessionName: payload.reviewSessionName, - ReviewLogPath: payload.reviewLogPath, - SessionHistory: payload.sessionHistory, - RunnerPid: shouldClearRunner ? null : payload.runnerPid, - RunnerKind: shouldClearRunner ? '' : (payload.runnerKind ?? ''), - RunnerAgent: shouldClearRunner ? '' : (payload.runnerAgent ?? ''), - RunnerRound: shouldClearRunner ? null : payload.runnerRound, - LastHeartbeatAt: shouldClearRunner ? '' : payload.lastHeartbeatAt, - ProgressSummary: payload.progressSummary, - ResultSummary: payload.resultSummary, - WorkspacePath: payload.workspacePath, - LogPath: payload.logPath, - LastError: payload.lastError, - }), - ), - ]); + await this.upsertRecord(task, { + Status: [payload.status], + CurrentOwner: payload.currentOwner, + ReviewRound: payload.reviewRound, + ReviewVerdict: payload.reviewVerdict ? [payload.reviewVerdict] : undefined, + ReviewFindings: payload.reviewFindings, + AcceptanceRound: payload.acceptanceRound, + AcceptanceVerdict: payload.acceptanceVerdict ? [payload.acceptanceVerdict] : undefined, + AcceptanceFeedback: payload.acceptanceFeedback, + ExecutionSessionId: payload.executionSessionId, + ExecutionSessionName: payload.executionSessionName, + ReviewSessionId: payload.reviewSessionId, + ReviewSessionName: payload.reviewSessionName, + ReviewLogPath: payload.reviewLogPath, + SessionHistory: payload.sessionHistory, + RunnerPid: shouldClearRunner ? null : payload.runnerPid, + RunnerKind: shouldClearRunner ? '' : (payload.runnerKind ?? ''), + RunnerAgent: shouldClearRunner ? '' : (payload.runnerAgent ?? ''), + RunnerRound: shouldClearRunner ? null : payload.runnerRound, + LastHeartbeatAt: shouldClearRunner ? '' : payload.lastHeartbeatAt, + ProgressSummary: payload.progressSummary, + ResultSummary: payload.resultSummary, + WorkspacePath: payload.workspacePath, + LogPath: payload.logPath, + LastError: payload.lastError, + }); } async updatePublishResult(task: TaskRef, payload: UpdatePublishResultPayload): Promise { - const taskRef = await this.resolveRecordRef(task); - await runLarkCli([ - 'base', - '+record-upsert', - '--base-token', - this.feishu.baseToken, - '--table-id', - this.feishu.tableId, - ...(taskRef.recordId ? ['--record-id', taskRef.recordId] : []), - '--json', - JSON.stringify( - buildRecordPayload(task.taskId, { - PRLink: payload.prLink, - PublishBranch: payload.publishBranch, - PublishCommit: payload.publishCommit, - PublishedAt: payload.publishedAt, - ProgressSummary: payload.progressSummary, - ResultSummary: payload.resultSummary, - SessionHistory: payload.sessionHistory, - LastError: payload.lastError, - }), - ), - ]); + await this.upsertRecord(task, { + PRLink: payload.prLink, + PublishBranch: payload.publishBranch, + PublishCommit: payload.publishCommit, + PublishedAt: payload.publishedAt, + ProgressSummary: payload.progressSummary, + ResultSummary: payload.resultSummary, + SessionHistory: payload.sessionHistory, + LastError: payload.lastError, + }); } async updateCleanupState(task: TaskRef, payload: UpdateCleanupStatePayload): Promise { - const taskRef = await this.resolveRecordRef(task); - await runLarkCli([ - 'base', - '+record-upsert', - '--base-token', - this.feishu.baseToken, - '--table-id', - this.feishu.tableId, - ...(taskRef.recordId ? ['--record-id', taskRef.recordId] : []), - '--json', - JSON.stringify( - buildRecordPayload( - task.taskId, - { - CurrentOwner: payload.currentOwner, - ProgressSummary: payload.progressSummary, - WorkspacePath: '', - LogPath: '', - ReviewLogPath: '', - RunnerPid: null, - RunnerKind: '', - RunnerAgent: '', - RunnerRound: null, - LastHeartbeatAt: '', - LastError: '', - ReviewVerdict: [], - ReviewFindings: '', - AcceptanceVerdict: [], - AcceptanceFeedback: '', - }, - { - touchUpdatedAt: true, - }, - ), - ), - ]); + await this.upsertRecord( + task, + { + CurrentOwner: payload.currentOwner, + ProgressSummary: payload.progressSummary, + WorkspacePath: '', + LogPath: '', + ReviewLogPath: '', + RunnerPid: null, + RunnerKind: '', + RunnerAgent: '', + RunnerRound: null, + LastHeartbeatAt: '', + LastError: '', + ReviewVerdict: [], + ReviewFindings: '', + AcceptanceVerdict: [], + AcceptanceFeedback: '', + }, + { touchUpdatedAt: true }, + ); } private mapFields(fields: Record, recordId?: string): TaskRecord { diff --git a/packages/agent-task-loop/src/task-management/github-issues-task-provider.ts b/packages/agent-task-loop/src/task-management/github-issues-task-provider.ts index b44e257d..6e3d98b5 100644 --- a/packages/agent-task-loop/src/task-management/github-issues-task-provider.ts +++ b/packages/agent-task-loop/src/task-management/github-issues-task-provider.ts @@ -1,17 +1,19 @@ import { TARGET_AGENTS, type TargetAgent, type TaskRecord, type TaskStatus } from '../types/task'; -import type { - ClaimTaskPayload, - CreateTaskPayload, - MarkTaskFailedPayload, - MarkTaskSucceededPayload, - SourceProvider, - TaskRef, - UpdateCleanupStatePayload, - UpdatePublishResultPayload, - UpdateReviewStatePayload, - UpdateRunnerStatePayload, - UpdateTaskAssignmentPayload, - UpdateTaskProgressPayload, +import { + pendingTasksFrom, + taskByIdFrom, + type ClaimTaskPayload, + type CreateTaskPayload, + type MarkTaskFailedPayload, + type MarkTaskSucceededPayload, + type SourceProvider, + type TaskRef, + type UpdateCleanupStatePayload, + type UpdatePublishResultPayload, + type UpdateReviewStatePayload, + type UpdateRunnerStatePayload, + type UpdateTaskAssignmentPayload, + type UpdateTaskProgressPayload, } from './task-provider'; export const GITHUB_SOURCE = 'github'; @@ -226,12 +228,12 @@ export class GitHubIssuesTaskProvider implements SourceProvider { return all; } - async listPendingTasks(agent: TargetAgent): Promise { - return (await this.listTasks()).filter((task) => task.targetAgent === agent && task.status === '待处理'); + listPendingTasks(agent: TargetAgent): Promise { + return pendingTasksFrom(() => this.listTasks(), agent); } - async getTaskById(taskId: string): Promise { - return (await this.listTasks()).find((task) => task.taskId === taskId); + getTaskById(taskId: string): Promise { + return taskByIdFrom(() => this.listTasks(), taskId); } async createTask(payload: CreateTaskPayload): Promise { diff --git a/packages/agent-task-loop/src/task-management/runtime-state.ts b/packages/agent-task-loop/src/task-management/runtime-state.ts index bf7f3408..2beb1692 100644 --- a/packages/agent-task-loop/src/task-management/runtime-state.ts +++ b/packages/agent-task-loop/src/task-management/runtime-state.ts @@ -14,7 +14,7 @@ import type { TaskRecord } from '../types/task'; * `project`, `priority`, `targetAgent`, `source`, `recordId`, `createdAt`, * `description`, `repository`, `updatedAt`) which stay owned by the backend. */ -export const RUNTIME_KEYS = [ +const RUNTIME_KEYS = [ 'status', 'sessionId', 'sessionName', @@ -50,7 +50,7 @@ export const RUNTIME_KEYS = [ 'publishedAt', ] as const; -export type RuntimeKey = (typeof RUNTIME_KEYS)[number]; +type RuntimeKey = (typeof RUNTIME_KEYS)[number]; /** The mirrored run-time subset. Values may be cleared ('' / 0 / null) on purpose. */ export type RuntimeTaskState = { [K in RuntimeKey]?: TaskRecord[K] }; diff --git a/packages/agent-task-loop/src/task-management/stateful-task-provider.ts b/packages/agent-task-loop/src/task-management/stateful-task-provider.ts index dd349979..63d0b51e 100644 --- a/packages/agent-task-loop/src/task-management/stateful-task-provider.ts +++ b/packages/agent-task-loop/src/task-management/stateful-task-provider.ts @@ -1,5 +1,6 @@ import type { TargetAgent, TaskRecord } from '../types/task'; import { overlayRuntimeState, pickRuntimeState, type RuntimeTaskState } from './runtime-state'; +import { pendingTasksFrom } from './task-provider'; /** * Run-time fields cleared on cleanup, mirroring Feishu's `updateCleanupState`. @@ -99,7 +100,7 @@ export class StatefulTaskProvider implements TaskProvider { // 待处理 on its raw record; only after overlaying the run-time store does the // true status (执行中 / 已失败 / 已完成 / …) appear. Delegating the filter to // the inner provider would re-offer such a task as pending — re-claimable. - return (await this.listTasks()).filter((task) => task.targetAgent === agent && task.status === '待处理'); + return pendingTasksFrom(() => this.listTasks(), agent); } async getTaskById(taskId: string): Promise { diff --git a/packages/agent-task-loop/src/task-management/task-provider.ts b/packages/agent-task-loop/src/task-management/task-provider.ts index 6e15a397..99610723 100644 --- a/packages/agent-task-loop/src/task-management/task-provider.ts +++ b/packages/agent-task-loop/src/task-management/task-provider.ts @@ -2,7 +2,7 @@ import type { AcceptanceVerdict, ReviewVerdict, TaskRecord, TargetAgent, TaskSta export type TaskRef = Pick; export type TaskRunnerKind = 'execute' | 'review'; -export type TaskRunnerKindUpdate = TaskRunnerKind | ''; +type TaskRunnerKindUpdate = TaskRunnerKind | ''; export interface CreateTaskPayload { taskId: string; @@ -15,10 +15,11 @@ export interface CreateTaskPayload { source?: string; } -export interface ClaimTaskPayload { - claimedBy: string; - claimedAt: string; - runId: string; +/** + * The runner/session bookkeeping a claim and a progress write carry — one shape, + * so the providers' column mappings and the services' writes cannot drift. + */ +export interface RunnerSessionFields { workspacePath?: string; logPath?: string; progressSummary?: string; @@ -32,20 +33,16 @@ export interface ClaimTaskPayload { lastHeartbeatAt?: string; } -export interface UpdateTaskProgressPayload { - progressSummary: string; - workspacePath?: string; - logPath?: string; - sessionId?: string; - sessionName?: string; - sessionHistory?: string; - runnerPid?: number; - runnerKind?: TaskRunnerKind; - runnerAgent?: string; - runnerRound?: number; - lastHeartbeatAt?: string; +export interface ClaimTaskPayload extends RunnerSessionFields { + claimedBy: string; + claimedAt: string; + runId: string; } +export type UpdateTaskProgressPayload = Omit & { + progressSummary: string; +}; + export interface UpdateRunnerStatePayload { runnerPid?: number; runnerKind?: TaskRunnerKind; @@ -83,7 +80,18 @@ export interface MarkTaskFailedPayload { sessionHistory?: string; } -export interface UpdateReviewStatePayload { +/** The review/session bookkeeping a review-state write carries, as the record spells it. */ +type ReviewSessionFields = Pick< + TaskRecord, + | 'executionSessionId' + | 'executionSessionName' + | 'reviewSessionId' + | 'reviewSessionName' + | 'reviewLogPath' + | 'sessionHistory' +>; + +export interface UpdateReviewStatePayload extends ReviewSessionFields { status: TaskStatus; currentOwner?: string; reviewRound?: number; @@ -92,12 +100,6 @@ export interface UpdateReviewStatePayload { acceptanceRound?: number; acceptanceVerdict?: AcceptanceVerdict; acceptanceFeedback?: string; - executionSessionId?: string; - executionSessionName?: string; - reviewSessionId?: string; - reviewSessionName?: string; - reviewLogPath?: string; - sessionHistory?: string; progressSummary?: string; resultSummary?: string; workspacePath?: string; @@ -142,6 +144,24 @@ export interface TaskProvider { updateCleanupState(task: TaskRef, payload: UpdateCleanupStatePayload): Promise; } +/** + * The list-based reads every leaf provider answers the same way: filter the + * full list for the agent's pending tasks, and find one task by id. + */ +export function pendingTasksFrom( + listTasks: () => Promise, + agent: TargetAgent, +): Promise { + return listTasks().then((tasks) => tasks.filter((task) => task.targetAgent === agent && task.status === '待处理')); +} + +export function taskByIdFrom( + listTasks: () => Promise, + taskId: string, +): Promise { + return listTasks().then((tasks) => tasks.find((task) => task.taskId === taskId)); +} + /** * A leaf provider that owns exactly one backend (Feishu, GitHub Issues, …). * It stamps `source` on every record it returns; a multi-source aggregator diff --git a/packages/agent-task-loop/src/task-management/task-state-store.ts b/packages/agent-task-loop/src/task-management/task-state-store.ts index 4582b295..df01f171 100644 --- a/packages/agent-task-loop/src/task-management/task-state-store.ts +++ b/packages/agent-task-loop/src/task-management/task-state-store.ts @@ -22,7 +22,7 @@ export interface TaskStateStore { * ids never map to the same segment (e.g. `github:a_b/c` vs `github:a/b_c`, both * of which would otherwise sanitize to `github_a_b_c`). */ -export function safeSegment(id: string): string { +function safeSegment(id: string): string { const readable = id.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 60); const hash = createHash('sha1').update(id).digest('hex').slice(0, 8); return `${readable}-${hash}`; diff --git a/packages/agent-task-loop/src/task-manager/task-manager-application.ts b/packages/agent-task-loop/src/task-manager/task-manager-application.ts index c05df3e2..d5b56ddc 100644 --- a/packages/agent-task-loop/src/task-manager/task-manager-application.ts +++ b/packages/agent-task-loop/src/task-manager/task-manager-application.ts @@ -5,27 +5,27 @@ import { TaskManagerInputError, TaskManagerOperationError } from './task-manager export { TaskManagerInputError, TaskManagerOperationError } from './task-manager-error'; -export interface ListTasksInput { +interface ListTasksInput { limit: number; status?: TaskStatus; targetAgent?: TargetAgent; } -export interface TaskListResult { +interface TaskListResult { count: number; tasks: PublicTaskDto[]; truncated: boolean; } -export interface GetTaskInput { +interface GetTaskInput { taskId: string; } -export interface GetTaskResult { +interface GetTaskResult { task: PublicTaskDto; } -export interface TaskMutationResult { +interface TaskMutationResult { action: 'created'; taskId: string; } @@ -36,7 +36,7 @@ export interface StartTaskInput { maxRounds: number; } -export interface TaskStartResult { +interface TaskStartResult { action: 'review-loop-completed'; task: PublicTaskDto; taskId: string; diff --git a/packages/agent-task-loop/src/tui/logic/layout.ts b/packages/agent-task-loop/src/tui/logic/layout.ts index e6634ac3..05545261 100644 --- a/packages/agent-task-loop/src/tui/logic/layout.ts +++ b/packages/agent-task-loop/src/tui/logic/layout.ts @@ -19,7 +19,7 @@ export const BADGE_WIDTH = 2; export const PRIORITY_WIDTH = 3; /** Width of the selection marker cell ("❯ ") at the start of a list row. */ -export const MARKER_WIDTH = 2; +const MARKER_WIDTH = 2; /** Width of the task-id cell in a list row. */ export const TASK_ID_WIDTH = 9; From 4f85066266de3b79ca9d2a5e6894de19ed118349 Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:29:27 +0800 Subject: [PATCH 2/3] style: format the shared modules --- .../app/room-lab/application/ports.ts | 2 +- .../app/room-lab/domain/room-message.ts | 4 +- .../infrastructure/room-lease.server.ts | 8 ++- .../src/discovery/legacy-probe-recipes.ts | 56 +++++++++++++------ .../src/sessions/resume-form.ts | 6 +- packages/agent-room/src/room/domain/model.ts | 1 - .../memory-room-stream-store.ts | 1 - packages/agent-task-loop/src/commands/init.ts | 1 - .../agent-task-loop/src/commands/source.ts | 2 - .../src/orchestration/lease.ts | 8 ++- .../src/services/execution-service.ts | 2 +- .../src/services/review-loop-service.ts | 9 +-- .../src/task-management/task-provider.ts | 10 +--- 13 files changed, 67 insertions(+), 43 deletions(-) diff --git a/apps/room-web/app/room-lab/application/ports.ts b/apps/room-web/app/room-lab/application/ports.ts index 1060735f..390b0ed7 100644 --- a/apps/room-web/app/room-lab/application/ports.ts +++ b/apps/room-web/app/room-lab/application/ports.ts @@ -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 { ToolDefinition, TurnHarness, TurnPermissionPolicy, TurnResult }; +export type { ToolDefinition, TurnHarness, TurnPermissionPolicy, TurnResult }; /** * The record plus the session side-channels the turn reads it with: the diff --git a/apps/room-web/app/room-lab/domain/room-message.ts b/apps/room-web/app/room-lab/domain/room-message.ts index f487cb35..b63cc987 100644 --- a/apps/room-web/app/room-lab/domain/room-message.ts +++ b/apps/room-web/app/room-lab/domain/room-message.ts @@ -17,7 +17,9 @@ 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' } { +): + | { 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' }; diff --git a/apps/room-web/app/room-lab/infrastructure/room-lease.server.ts b/apps/room-web/app/room-lab/infrastructure/room-lease.server.ts index 0e3406f9..ce193604 100644 --- a/apps/room-web/app/room-lab/infrastructure/room-lease.server.ts +++ b/apps/room-web/app/room-lab/infrastructure/room-lease.server.ts @@ -79,7 +79,13 @@ class RoomLeaseLostError extends Error { } /** 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; +const ROOM_LEASE_TAGS = [ + 'LeaseHeld', + 'LeaseLost', + 'FenceRejected', + 'LeaseConfigInvalid', + 'LeaseRepositoryFailure', +] as const; type RoomLeaseTag = (typeof ROOM_LEASE_TAGS)[number]; diff --git a/packages/agent-finder-cli/src/discovery/legacy-probe-recipes.ts b/packages/agent-finder-cli/src/discovery/legacy-probe-recipes.ts index b33e798e..cb04f5ee 100644 --- a/packages/agent-finder-cli/src/discovery/legacy-probe-recipes.ts +++ b/packages/agent-finder-cli/src/discovery/legacy-probe-recipes.ts @@ -42,7 +42,8 @@ function probe( /** The MoonBit catalog's agents in catalog order, minus the six the kit detects with its own built-in recipes. */ export const legacyProbeRecipes: Readonly> = { - openhands: probe('app', + openhands: probe( + 'app', 'openhands', 'OpenHands', ['openhands'], @@ -51,7 +52,8 @@ export const legacyProbeRecipes: Readonly> = { [], ['OpenHands may be local, containerized, or remote; discovery is conservative.'], ), - cline: probe('extension', + cline: probe( + 'extension', 'cline', 'Cline', [], @@ -60,7 +62,8 @@ export const legacyProbeRecipes: Readonly> = { [], ['Cline extension presence is not validated without reading extension metadata.'], ), - codebuddy: probe('cli', + codebuddy: probe( + 'cli', 'codebuddy', 'CodeBuddy', ['codebuddy'], @@ -69,7 +72,8 @@ export const legacyProbeRecipes: Readonly> = { [], ['CodeBuddy command and config paths may vary by distribution.'], ), - 'command-code': probe('cli', + 'command-code': probe( + 'cli', 'command-code', 'Command Code', ['command-code'], @@ -78,7 +82,8 @@ export const legacyProbeRecipes: Readonly> = { [], ['Command Code provider metadata needs validation.'], ), - 'kiro-cli': probe('cli', + 'kiro-cli': probe( + 'cli', 'kiro-cli', 'Kiro CLI', ['kiro'], @@ -87,7 +92,8 @@ export const legacyProbeRecipes: Readonly> = { [], ['Kiro CLI provider metadata needs validation.'], ), - antigravity: probe('app', + antigravity: probe( + 'app', 'antigravity', 'Antigravity', ['antigravity'], @@ -96,7 +102,8 @@ export const legacyProbeRecipes: Readonly> = { [], ['Antigravity provider metadata needs validation.'], ), - 'roo-code': probe('extension', + 'roo-code': probe( + 'extension', 'roo-code', 'Roo Code', [], @@ -105,7 +112,8 @@ export const legacyProbeRecipes: Readonly> = { [], ['Roo Code extension presence is not validated without reading extension metadata.'], ), - 'github-copilot': probe('cli', + 'github-copilot': probe( + 'cli', 'github-copilot', 'GitHub Copilot', ['gh', 'copilot'], @@ -115,7 +123,8 @@ export const legacyProbeRecipes: Readonly> = { ['GitHub Copilot CLI support is detected conservatively through command metadata.'], ), amp: probe('cli', 'amp', 'Amp', ['amp'], ['~/.amp'], [], [], ['Amp provider metadata needs validation.']), - openclaw: probe('cli', + openclaw: probe( + 'cli', 'openclaw', 'OpenClaw', ['openclaw'], @@ -124,7 +133,8 @@ export const legacyProbeRecipes: Readonly> = { [], ['OpenClaw provider metadata needs validation.'], ), - neovate: probe('cli', + neovate: probe( + 'cli', 'neovate', 'Neovate', ['neovate'], @@ -134,7 +144,8 @@ export const legacyProbeRecipes: Readonly> = { ['Neovate provider metadata needs validation.'], ), qoder: probe('cli', 'qoder', 'Qoder', ['qoder'], ['~/.qoder'], [], [], ['Qoder provider metadata needs validation.']), - zencoder: probe('cli', + zencoder: probe( + 'cli', 'zencoder', 'Zencoder', ['zencoder'], @@ -143,7 +154,8 @@ export const legacyProbeRecipes: Readonly> = { [], ['Zencoder provider metadata needs validation.'], ), - 'kimi-code-cli': probe('cli', + 'kimi-code-cli': probe( + 'cli', 'kimi-code-cli', 'Kimi Code CLI', ['kimi'], @@ -152,7 +164,8 @@ export const legacyProbeRecipes: Readonly> = { [], ['Kimi Code CLI provider metadata needs validation.'], ), - windsurf: probe('app', + windsurf: probe( + 'app', 'windsurf', 'Windsurf', ['windsurf'], @@ -161,7 +174,8 @@ export const legacyProbeRecipes: Readonly> = { ['~/.codeium/windsurf/mcp_config.json', '~/Library/Application Support/Windsurf/User/mcp.json'], [], ), - 'vscode-copilot': probe('extension', + 'vscode-copilot': probe( + 'extension', 'vscode-copilot', 'VS Code Copilot', ['code'], @@ -170,7 +184,8 @@ export const legacyProbeRecipes: Readonly> = { ['~/Library/Application Support/Code/User/mcp.json'], ['VS Code Copilot extension presence is not validated without reading extension metadata.'], ), - 'codex-desktop': probe('app', + 'codex-desktop': probe( + 'app', 'codex-desktop', 'Codex Desktop', [], @@ -180,6 +195,15 @@ export const legacyProbeRecipes: Readonly> = { [], ), aider: probe('cli', 'aider', 'aider', ['aider'], ['~/.aider.conf.yml', '~/.config/aider'], [], [], []), - hermes: probe('cli', 'hermes', 'Hermes', ['hermes'], ['~/.hermes'], [], [], ['Hermes provider metadata needs validation.']), + hermes: probe( + 'cli', + 'hermes', + 'Hermes', + ['hermes'], + ['~/.hermes'], + [], + [], + ['Hermes provider metadata needs validation.'], + ), trae: probe('cli', 'trae', 'Trae', ['trae'], ['~/.trae'], [], [], ['Trae provider metadata needs validation.']), }; diff --git a/packages/agent-finder-cli/src/sessions/resume-form.ts b/packages/agent-finder-cli/src/sessions/resume-form.ts index 63be42a0..1a0764a5 100644 --- a/packages/agent-finder-cli/src/sessions/resume-form.ts +++ b/packages/agent-finder-cli/src/sessions/resume-form.ts @@ -7,9 +7,5 @@ export function resumeCommandFrom string>( agent: string | undefined, sessionId: string | undefined | null, ): string | null { - return sessionId - ? agent !== undefined - ? (resumeCommands[agent]?.(sessionId) ?? null) - : null - : null; + return sessionId ? (agent !== undefined ? (resumeCommands[agent]?.(sessionId) ?? null) : null) : null; } diff --git a/packages/agent-room/src/room/domain/model.ts b/packages/agent-room/src/room/domain/model.ts index 7519e5ee..e1b7ac36 100644 --- a/packages/agent-room/src/room/domain/model.ts +++ b/packages/agent-room/src/room/domain/model.ts @@ -70,4 +70,3 @@ export interface RoomSlice { events: RoomEvent[]; head: RoomSeq; } - diff --git a/packages/agent-room/src/room/infrastructure/memory-room-stream-store.ts b/packages/agent-room/src/room/infrastructure/memory-room-stream-store.ts index b15c56a8..7ecf1db9 100644 --- a/packages/agent-room/src/room/infrastructure/memory-room-stream-store.ts +++ b/packages/agent-room/src/room/infrastructure/memory-room-stream-store.ts @@ -23,7 +23,6 @@ function roomStorageKey(id: RoomId): string { return JSON.stringify([id.tenantId, id.conversationId]); } - export class MemoryRoomUnitOfWork implements RoomUnitOfWork { private readonly rooms = new Map(); private readonly sessions = new Map(); diff --git a/packages/agent-task-loop/src/commands/init.ts b/packages/agent-task-loop/src/commands/init.ts index 1a4729b5..9850e797 100644 --- a/packages/agent-task-loop/src/commands/init.ts +++ b/packages/agent-task-loop/src/commands/init.ts @@ -107,7 +107,6 @@ async function confirmInstall(): Promise { return answer.trim().toLowerCase() === 'y'; } - async function ensureLarkCli(): Promise { if (await isLarkCliAvailable()) { return true; diff --git a/packages/agent-task-loop/src/commands/source.ts b/packages/agent-task-loop/src/commands/source.ts index 613bec6f..c4ede482 100644 --- a/packages/agent-task-loop/src/commands/source.ts +++ b/packages/agent-task-loop/src/commands/source.ts @@ -57,8 +57,6 @@ async function ask(question: string): Promise { } } - - const isTty = (): boolean => Boolean(process.stdin.isTTY && process.stdout.isTTY); /** A CLI flag that must resolve to a non-empty trimmed string, with a clear message. */ diff --git a/packages/agent-task-loop/src/orchestration/lease.ts b/packages/agent-task-loop/src/orchestration/lease.ts index 26fc804e..4c7297a0 100644 --- a/packages/agent-task-loop/src/orchestration/lease.ts +++ b/packages/agent-task-loop/src/orchestration/lease.ts @@ -99,7 +99,13 @@ export class TaskLeaseStoreError extends Error { } /** The kit's lease failure tags the orchestrator maps onto its own errors. */ -const TASK_LEASE_TAGS = ['LeaseHeld', 'LeaseLost', 'FenceRejected', 'LeaseConfigInvalid', 'LeaseRepositoryFailure'] as const; +const TASK_LEASE_TAGS = [ + 'LeaseHeld', + 'LeaseLost', + 'FenceRejected', + 'LeaseConfigInvalid', + 'LeaseRepositoryFailure', +] as const; type TaskLeaseTag = (typeof TASK_LEASE_TAGS)[number]; diff --git a/packages/agent-task-loop/src/services/execution-service.ts b/packages/agent-task-loop/src/services/execution-service.ts index 3fc406a4..84ad45c5 100644 --- a/packages/agent-task-loop/src/services/execution-service.ts +++ b/packages/agent-task-loop/src/services/execution-service.ts @@ -78,7 +78,7 @@ export class ExecutionService { onHeartbeatError: this.deps.onHeartbeatError, }); heartbeat.pid(task.runnerPid); - const writeProgress = async (summary: string) => { + const writeProgress = async (summary: string) => { if (!summary || summary === latestProgressSummary) { return; } diff --git a/packages/agent-task-loop/src/services/review-loop-service.ts b/packages/agent-task-loop/src/services/review-loop-service.ts index 472afcef..34c92234 100644 --- a/packages/agent-task-loop/src/services/review-loop-service.ts +++ b/packages/agent-task-loop/src/services/review-loop-service.ts @@ -11,7 +11,10 @@ import type { TaskMutationFence } from './task-service'; * status and progress wording. */ function acceptanceUpdate( - input: { round: number; task: { executionSessionId?: string; executionSessionName?: string; sessionHistory?: string } }, + input: { + round: number; + task: { executionSessionId?: string; executionSessionName?: string; sessionHistory?: string }; + }, review: { sessionId?: string; sessionName?: string }, overrides: { status?: '待发布' | '待决策'; progressSummary?: string; lastError?: string }, ) { @@ -22,9 +25,7 @@ function acceptanceUpdate( reviewVerdict: '通过' as const, reviewFindings: '', ...(input.task.executionSessionId !== undefined ? { executionSessionId: input.task.executionSessionId } : {}), - ...(input.task.executionSessionName !== undefined - ? { executionSessionName: input.task.executionSessionName } - : {}), + ...(input.task.executionSessionName !== undefined ? { executionSessionName: input.task.executionSessionName } : {}), ...(review.sessionId !== undefined ? { reviewSessionId: review.sessionId } : {}), ...(review.sessionName !== undefined ? { reviewSessionName: review.sessionName } : {}), ...(input.task.sessionHistory !== undefined ? { sessionHistory: input.task.sessionHistory } : {}), diff --git a/packages/agent-task-loop/src/task-management/task-provider.ts b/packages/agent-task-loop/src/task-management/task-provider.ts index 99610723..d43cd277 100644 --- a/packages/agent-task-loop/src/task-management/task-provider.ts +++ b/packages/agent-task-loop/src/task-management/task-provider.ts @@ -148,17 +148,11 @@ export interface TaskProvider { * The list-based reads every leaf provider answers the same way: filter the * full list for the agent's pending tasks, and find one task by id. */ -export function pendingTasksFrom( - listTasks: () => Promise, - agent: TargetAgent, -): Promise { +export function pendingTasksFrom(listTasks: () => Promise, agent: TargetAgent): Promise { return listTasks().then((tasks) => tasks.filter((task) => task.targetAgent === agent && task.status === '待处理')); } -export function taskByIdFrom( - listTasks: () => Promise, - taskId: string, -): Promise { +export function taskByIdFrom(listTasks: () => Promise, taskId: string): Promise { return listTasks().then((tasks) => tasks.find((task) => task.taskId === taskId)); } From 5cee190e41374668cb785fbd1ef50133a5b969f2 Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:02:05 +0800 Subject: [PATCH 3/3] fix: reject non-object lines in claudeResultEvents MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A bare null line is valid JSON and valid to parse, but the result consumers read .type on every returned element — a trailing null turned a successful run into an execution failure (and error extraction into a throw), which the inline try/catch of the pre-extraction code used to absorb. Only non-null objects enter the list now. --- packages/agent-task-loop/src/adapters/claude-lines.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/agent-task-loop/src/adapters/claude-lines.ts b/packages/agent-task-loop/src/adapters/claude-lines.ts index 77a75622..f84d1b8b 100644 --- a/packages/agent-task-loop/src/adapters/claude-lines.ts +++ b/packages/agent-task-loop/src/adapters/claude-lines.ts @@ -38,7 +38,12 @@ export function claudeResultEvents(output: string): ClaudeStreamEvent[] { .filter(Boolean); for (let index = lines.length - 1; index >= 0; index -= 1) { try { - events.push(JSON.parse(lines[index]!) as ClaudeStreamEvent); + // A bare `null` (or any non-object) is valid JSON but not an event; the + // result consumers read `.type` on every element, so it must not enter. + const parsed: unknown = JSON.parse(lines[index]!); + if (parsed !== null && typeof parsed === 'object') { + events.push(parsed as ClaudeStreamEvent); + } } catch { continue; }