ds-harness-remote-fast/packages/client-core/src/harness-alpha-client.ts

1304 lines
51 KiB
TypeScript

import { HarnessQuestions } from './harness-questions.js'
import { RemoteGatewayError, RemoteTypertGateway, createRemoteId, type RemoteGatewayResult, type RemoteGatewayStream } from './remote-gateway.js'
import type { RemoteClientCore } from './index.js'
export interface HarnessAlphaHostInfo {
clientVersion?: string
harnessVersion?: string
sessionFormat?: 3
}
export interface HarnessClientFrame {
rpcId: string
payload: Record<string, unknown>
}
export interface HarnessModelSelection {
provider: string
model: string
reasoningEffort?: string
}
export interface HarnessModelProviderGroup {
id: string
name: string
models: Array<{
id: string
name: string
description?: string
reasoning?: {
efforts: Array<{ id: string; name: string; description?: string }>
defaultEffort?: string
}
}>
}
export interface HarnessSessionModels {
current: HarnessModelSelection
routable: boolean
groups: HarnessModelProviderGroup[]
failures: Array<{ id: string; name: string; message: string }>
}
export interface HarnessRemoteSession {
sessionId: string
updatedAt: number
running: boolean
blank: boolean
title?: string
parentSessionId?: string
origin?: 'subagent'
cwd?: string
agentPreset?: string
projections?: {
asOfSeq?: number
values?: Record<string, unknown>
}
}
export interface HarnessAgentPresetRow {
id: string
isDefault: boolean
name?: string
description?: string
broken?: string
}
export interface HarnessAgentPresetRoster {
presets: HarnessAgentPresetRow[]
}
export interface HarnessWorkspaceView {
workspaceId: string
path: string
title: string
sessionIds: string[]
createdAt: string
updatedAt: string
}
export interface HarnessWorkspaceList {
items: HarnessWorkspaceView[]
archivedSessionIds: string[]
pinnedSessionIds?: string[]
}
export type ScheduleKind = 'after' | 'at' | 'every' | 'daily' | 'weekly' | 'cron'
export interface ScheduleDeliveryReceipt {
scheduledAt: string
deliveredAt: string
messageId: string
}
export interface ScheduleDeliveryRecord extends ScheduleDeliveryReceipt {
prompt?: string
}
export interface ScheduleCatalogEntry {
id: string
sessionId: string
kind: ScheduleKind
title: string
prompt: string
scheduledAt: string
status: 'active' | 'inactive'
afterSeconds?: number
everySeconds?: number
time?: string
timeZone?: string
weekdays?: number[]
expression?: string
lastDelivery?: ScheduleDeliveryReceipt
}
export interface ScheduleDeleteResult {
id: string
deleted?: boolean
code?: string
}
export interface ScheduleCreateRequest {
title: string
prompt: string
after_seconds?: number
at?: string | { date: string; time: string; time_zone: string }
every_seconds?: number
daily?: { time: string; time_zone: string }
weekly?: { time: string; time_zone: string; weekdays: number[] }
cron?: { expression: string; time_zone: string }
}
export type ScheduleTimingChange =
| { kind: 'at'; at: string | { date: string; time: string; time_zone: string } }
| { kind: 'every'; every_seconds: number }
| { kind: 'daily'; daily: { time: string; time_zone: string } }
| { kind: 'weekly'; weekly: { time: string; time_zone: string; weekdays: number[] } }
| { kind: 'cron'; cron: { expression: string; time_zone: string } }
export type ScheduleRecord =
| { id: string; kind: 'after'; title: string; prompt: string; afterSeconds: number; scheduledAt: string }
| { id: string; kind: 'at'; title: string; prompt: string; scheduledAt: string }
| { id: string; kind: 'every'; title: string; prompt: string; everySeconds: number; scheduledAt: string }
| { id: string; kind: 'daily'; title: string; prompt: string; time: string; timeZone: string; scheduledAt: string }
| { id: string; kind: 'weekly'; title: string; prompt: string; time: string; timeZone: string; weekdays: number[]; scheduledAt: string }
| { id: string; kind: 'cron'; title: string; prompt: string; expression: string; timeZone: string; scheduledAt: string }
export interface ScheduleUpdateRequest {
sessionId: string
id: string
expected: ScheduleRecord
change?: ScheduleTimingChange
title?: string
prompt?: string
}
export type ScheduleUpdateResult =
| { id: string; updated: boolean; record: ScheduleRecord }
| { id: string; updated: false; code: 'schedule_not_found' | 'schedule_ended' | 'schedule_conflict' }
| { code: string; message: string }
export interface ScheduleDeliveryHistoryResult {
id: string
records?: ScheduleDeliveryRecord[]
earlierRecordsUnavailable?: boolean
earlierRecordsPruned?: boolean
retention?: { days: number; records: number }
code?: string
}
export interface HarnessPluginApplication {
/** `applied`, `restart-required`, `overridden` or `cancelled`; failures throw. */
application: string
}
export interface HarnessSettingsNamespace {
ns: string
/** Serialized Schemastery envelope. */
schema: unknown
value: unknown
user?: unknown
revision: number
}
export interface HarnessSettingsDescribe {
writable: boolean
namespaces: HarnessSettingsNamespace[]
}
export type HarnessSettingsPathOp =
| { op: 'set'; path: string[]; value: unknown }
| { op: 'unset'; path: string[] }
export interface HarnessDirectoryEntry {
name: string
path: string
hidden: boolean
}
export interface HarnessDirectoryListing {
path: string
home: string
crumbs: HarnessDirectoryEntry[]
entries: HarnessDirectoryEntry[]
truncated: boolean
}
export interface HarnessHostDescriptor {
version: string
cwd: string
provider?: string
model?: string
attachedSessions: number
canOpenPath: boolean
}
export interface HarnessPromptImage {
mediaType: string
data: string
name?: string
}
export interface HarnessQuestionAnswer {
answers: Array<{ id: string; selected: string[]; custom?: string }>
}
export interface HarnessSessionEvent {
type: string
seq: number
time: number
data: Record<string, unknown>
sourceEventSeqs?: number[]
surfaceOp?: HarnessSurfaceOp
ignorable?: true
}
export type HarnessSurfaceOp =
| 'append'
| { op: 'replace'; start: number; end: number }
| { op: 'replace'; startSeq: number; endSeq: number }
export interface HarnessHistoryEntry {
event: HarnessSessionEvent
view?: { for: 'call' | 'result'; view: unknown }
}
export interface HarnessSessionHistoryPage {
events: HarnessHistoryEntry[]
hasMore: boolean
throughSeq?: number
}
type RemoteEventKind = 'approval/request' | 'user-questions/request'
interface PendingRemoteEvent {
event: RemoteEventKind
eventId: string
sessionId: string
frame: HarnessClientFrame
}
type StreamHandle = {
controller: AbortController
stream?: RemoteGatewayStream
iterator?: AsyncIterator<unknown>
}
interface AssistantStreamState {
attemptId: string
startedAfterSeq: number
turn: number
step: number
nextIndex: number
}
type SessionFollowHandle = StreamHandle & {
sessionId: string
assistant?: AssistantStreamState
}
const LEGACY_AGENT_PRESET = 'code'
const LEGACY_AGENT_PRESET_TARGET = 'ptc'
export class HarnessAlphaClient {
readonly mode = 'remote' as const
private readonly questions: HarnessQuestions
private readonly gateway: RemoteTypertGateway
private readonly sessionsCache = new Map<string, HarnessRemoteSession>()
private readonly selectedModels = new Map<string, HarnessModelSelection>()
private readonly followCursors = new Map<string, number>()
private readonly pendingEvents = new Map<string, PendingRemoteEvent>()
private events?: StreamHandle
private control?: StreamHandle
private sessionFollow?: SessionFollowHandle
private followGeneration = 0
private eventClientId?: string
private eventHostHome?: string
constructor(
core: RemoteClientCore,
private readonly host: HarnessAlphaHostInfo = {},
private readonly onFrame?: (frame: HarnessClientFrame) => void,
) {
this.gateway = new RemoteTypertGateway(core)
this.questions = new HarnessQuestions(this.gateway, (id, outcome) => this.respondEvent(id, outcome), frame => this.emitFrame(frame))
}
start(): void {
if (this.events === undefined) {
const handle = { controller: new AbortController() }
this.events = handle
void this.pumpEvents(handle).catch(error => this.emitStreamFailure(handle, this.events, error))
}
if (this.control === undefined) {
const handle = { controller: new AbortController() }
this.control = handle
void this.pumpControl(handle).catch(error => this.emitStreamFailure(handle, this.control, error))
}
}
async close(notifyRemote = true): Promise<void> {
++this.followGeneration
this.questions.close(notifyRemote)
await Promise.all([
this.closeHandle(this.sessionFollow, notifyRemote),
this.closeHandle(this.events, notifyRemote),
this.closeHandle(this.control, notifyRemote),
])
this.sessionFollow = undefined
this.events = undefined
this.control = undefined
this.pendingEvents.clear()
this.eventClientId = undefined
}
async sessionList(): Promise<HarnessRemoteSession[]> {
const result = await this.callValue<{ items: HarnessRemoteSession[] }>('session/list', { _request: {} })
const items = Array.isArray(result.items) ? result.items.map(item => normalizeSession(item)).filter((item): item is HarnessRemoteSession => item !== undefined) : []
for (const item of items) this.sessionsCache.set(item.sessionId, item)
return items
}
async sessionCreate(workspaceId?: string, cwd?: string): Promise<{ sessionId: string }> {
const result = await this.callValue<{ sessionId: string }>('session/create', {
request: workspaceId !== undefined
? { workspaceId }
: cwd !== undefined
? { cwd }
: {},
})
if (typeof result.sessionId !== 'string') {
throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host returned an invalid session creation result.')
}
return result
}
async messageFeedbackList(sessionId: string): Promise<Array<{ messageId: string; rating: 'positive' | 'negative'; version: string }>> {
const result = await this.callValue<{ items: Array<{ messageId: string; rating: 'positive' | 'negative'; version: string }> }>('messageFeedback/list', { request: { sessionId } })
if (!Array.isArray(result?.items) || result.items.some(item => typeof item?.messageId !== 'string' || typeof item.version !== 'string' || (item.rating !== 'positive' && item.rating !== 'negative'))) throw new RemoteGatewayError('INVALID_MESSAGE', 'Invalid feedback list.')
return result.items
}
async messageFeedbackPut(sessionId: string, messageId: string, rating: 'positive' | 'negative'): Promise<{ messageId: string; rating: 'positive' | 'negative'; version: string }> {
type Feedback = { messageId: string; rating: 'positive' | 'negative'; version: string }
const list = () => this.messageFeedbackList(sessionId)
const previous = (await list()).find(item => item.messageId === messageId)
const result = await this.callValue<Feedback>('messageFeedback/put', { request: { sessionId, messageId, rating, ifVersion: previous?.version ?? null } })
const saved = (await list()).find(item => item.messageId === messageId)
if (saved?.rating !== rating || typeof saved.version !== 'string' || saved.version !== result?.version) throw new RemoteGatewayError('INVALID_MESSAGE', 'Message feedback could not be verified.')
return saved
}
async sessionFork(sessionId: string, atSeq?: number): Promise<{ sessionId: string }> {
if (atSeq !== undefined && (!Number.isSafeInteger(atSeq) || atSeq < 0)) throw new RemoteGatewayError('INVALID_MESSAGE', 'Invalid fork boundary.')
const request = atSeq === undefined ? { sessionId } : { sessionId, atSeq }
const result = await this.callValue<{ sessionId: string }>('session/fork', { request })
if (typeof result?.sessionId !== 'string' || result.sessionId.length === 0) throw new RemoteGatewayError('INVALID_MESSAGE', 'Invalid fork result.')
return result
}
async sessionModels(sessionId: string): Promise<HarnessSessionModels> {
const catalog = await this.callValue<{
default: HarnessModelSelection
routableProviders?: string[]
groups: HarnessModelProviderGroup[]
failures?: Array<{ id: string; name: string; message: string }>
}>('session/modelCatalog', {})
if (typeof catalog.default?.provider !== 'string' || typeof catalog.default?.model !== 'string' || !Array.isArray(catalog.groups)) {
throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host returned an invalid model catalog.')
}
const projected = modelSelectionFromSession(this.sessionsCache.get(sessionId))
const current = this.selectedModels.get(sessionId) ?? projected ?? catalog.default
const routable = Array.isArray(catalog.routableProviders)
? catalog.routableProviders.includes(current.provider)
: catalog.groups.length > 0
return {
current,
routable,
groups: catalog.groups,
failures: Array.isArray(catalog.failures) ? catalog.failures : [],
}
}
async sessionSelectModel(sessionId: string, selection: HarnessModelSelection): Promise<HarnessModelSelection> {
const result = await this.callValue<{ selected: HarnessModelSelection }>('session/selectModel', {
request: {
sessionId,
provider: selection.provider,
model: selection.model,
...(selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort }),
},
})
if (typeof result.selected?.provider !== 'string' || typeof result.selected?.model !== 'string') {
throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host returned an invalid model selection.')
}
this.selectedModels.set(sessionId, result.selected)
return result.selected
}
async sessionExecuteCommand(sessionId: string, line: string): Promise<{ kind: 'success' | 'error'; text?: string }> {
const execution = await this.callValue<{ result: { kind: 'success' | 'error'; text?: string } } | undefined>('commands/execute', {
agentId: sessionId, line, ...(this.host.sessionFormat === 3 ? { submittedAttachments: [] } : { images: [] }),
})
if (execution === undefined) throw new RemoteGatewayError('UNSUPPORTED', 'Unknown or unavailable Host command.')
if (execution.result?.kind !== 'success' && execution.result?.kind !== 'error') throw new RemoteGatewayError('INVALID_MESSAGE', 'Invalid command result.')
return execution.result
}
async sessionSelectPermission(sessionId: string, preset: string): Promise<void> {
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(preset)) {
throw new RemoteGatewayError('INVALID_MESSAGE', 'Harness returned an invalid permission preset.')
}
const result = await this.sessionExecuteCommand(sessionId, `/permission ${preset}`)
if (result.kind === 'error') {
throw new RemoteGatewayError('COMMAND_FAILED', result.text ?? 'The Host rejected the permission preset.')
}
}
/** Read the Host's agent-preset (mode) roster for the mode picker. */
async agentPresetList(): Promise<HarnessAgentPresetRoster> {
const result = await this.callValue<{ presets?: unknown }>('agentPresets/list', {})
const rows = Array.isArray(result.presets) ? result.presets : []
return {
presets: rows.flatMap(row => {
if (!isRecord(row) || typeof row.id !== 'string' || row.id.length === 0) return []
return [{
id: row.id,
isDefault: row.isDefault === true,
...(typeof row.name === 'string' ? { name: row.name } : {}),
...(typeof row.description === 'string' ? { description: row.description } : {}),
...(typeof row.broken === 'string' ? { broken: row.broken } : {}),
}]
}),
}
}
/** Select the agent preset (mode) of a session that has not started its first turn. */
async agentPresetSelect(sessionId: string, agentPreset: string): Promise<string> {
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(agentPreset)) {
throw new RemoteGatewayError('INVALID_MESSAGE', 'Harness returned an invalid agent preset.')
}
const committed = await this.callValue<unknown>('agentPresets/select', { agentId: sessionId, agentPreset })
return typeof committed === 'string' && committed.length > 0 ? committed : agentPreset
}
/**
* Official SessionAddress: a subagent session must be addressed through its
* durable parent (`{ kind: 'subagent', parentSessionId, childSessionId }`);
* the plain session form is rejected with `session/agent-busy`.
*/
private sessionAddress(sessionId: string, parentSessionId?: string) {
return parentSessionId === undefined
? { kind: 'session' as const, sessionId }
: { kind: 'subagent' as const, parentSessionId, childSessionId: sessionId, mode: 'unknown' as const }
}
async sessionHistory(sessionId: string, beforeSeq?: number, maxMessages = 60, parentSessionId?: string): Promise<HarnessSessionHistoryPage> {
if (beforeSeq !== undefined) {
const throughSeq = this.followCursors.get(sessionId) ?? beforeSeq
const page = await this.callValue<{ records: unknown[]; hasMore: boolean }>('session/page', {
request: {
address: this.sessionAddress(sessionId, parentSessionId),
throughSeq,
beforeSeq,
maxMessages,
},
})
return {
events: historyEntriesFromRecords(Array.isArray(page.records) ? page.records : []),
hasMore: page.hasMore === true,
throughSeq,
}
}
const generation = ++this.followGeneration
await this.closeSessionFollow()
if (generation !== this.followGeneration) throw new RemoteGatewayError('CANCELLED', 'The session follow was superseded.')
const handle: SessionFollowHandle = { sessionId, controller: new AbortController() }
this.sessionFollow = handle
const opened = this.gateway.open('session/follow', {
args: {
request: {
address: this.sessionAddress(sessionId, parentSessionId),
maxMessages,
...(this.host.sessionFormat === 3 ? { assistantStream: true as const } : {}),
},
},
}, handle.controller.signal)
const source = await this.boundedFollow(opened, handle)
handle.stream = source
if (this.sessionFollow !== handle || handle.controller.signal.aborted) {
await this.closeHandle(handle, false)
throw new RemoteGatewayError('CANCELLED', 'The session follow was superseded.')
}
const iterator = source[Symbol.asyncIterator]()
handle.iterator = iterator
// The snapshot can legitimately be slow (a 4 MiB first frame over a weak
// link): bound it on a separate, generous budget rather than the open RPC's.
const first = await this.boundedFollow(iterator.next(), handle, 60_000)
if (this.sessionFollow !== handle || handle.controller.signal.aborted) {
throw new RemoteGatewayError('CANCELLED', 'The session follow was superseded.')
}
if (first.done || !isRecord(first.value) || first.value.type !== 'snapshot') {
await this.closeSessionFollow()
throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host returned an invalid session follow snapshot.')
}
const snapshot = first.value
const cursor = typeof snapshot.cursor === 'number' ? snapshot.cursor : undefined
if (cursor !== undefined) this.followCursors.set(sessionId, cursor)
if (this.host.sessionFormat === 3) handle.assistant = assistantStreamBaseline(snapshot.assistantStream)
this.applyProjectionBaseline(sessionId, snapshot.projections)
this.republishPendingSessionInteractions(sessionId, isRecord(snapshot.projections) && isRecord(snapshot.projections.values) && snapshot.projections.values.userQuestions !== undefined)
void this.pumpSessionFollow(handle, iterator).catch(error => this.emitStreamFailure(handle, this.sessionFollow, error))
return {
events: historyEntriesFromRecords(Array.isArray(snapshot.records) ? snapshot.records : []),
hasMore: snapshot.hasMore === true,
...(cursor === undefined ? {} : { throughSeq: cursor }),
}
}
async sessionPrompt(sessionId: string, text: string, requestId = createRemoteId(), images: HarnessPromptImage[] = []): Promise<void> {
const timeZone = clientTimeZone()
const content = [
...(text.length === 0 ? [] : [{ type: 'text' as const, text }]),
...images.map(image => ({
type: 'image' as const,
mediaType: image.mediaType,
data: image.data,
...(image.name === undefined ? {} : { name: image.name }),
})),
]
await this.callValue('session/prompt', {
request: {
requestId,
sessionId,
mode: 'queue',
content,
...(timeZone === undefined ? {} : { clientTimeZone: timeZone }),
},
})
}
async sessionCancel(sessionId: string): Promise<void> {
const result = await this.callValue<{ accepted: true }>('session/cancel', { request: { sessionId } })
if (result.accepted !== true) throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host did not accept the stop request.')
}
async sessionAttachment(
sessionId: string,
attachment: string | Record<string, unknown>,
): Promise<{ attachment: unknown; data: string }> {
const reference = typeof attachment === 'string' ? undefined : attachment
const attachmentId = typeof attachment === 'string'
? attachment
: typeof attachment.attachmentId === 'string' ? attachment.attachmentId : undefined
const result = await this.callValue<{ attachment?: unknown; data?: string; mediaType?: string }>('session/attachment', {
request: {
sessionId,
...(attachmentId === undefined ? {} : { attachmentId }),
...(reference === undefined ? {} : { attachment: reference }),
},
})
return {
attachment: result.attachment ?? reference ?? { mediaType: result.mediaType },
data: result.data ?? '',
}
}
/** Apply one operation to a still-pending queue occurrence (official QueueAction subset). */
async sessionUpdateQueue(sessionId: string, itemId: string, action: { kind: 'remove' | 'steer' }): Promise<void> {
const result = await this.callValue<{ accepted: true }>('session/updateQueue', { request: { sessionId, itemId, action } })
if (result.accepted !== true) throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host did not accept the queue update.')
}
async hostDescribe(): Promise<HarnessHostDescriptor> {
if (this.sessionsCache.size === 0) await this.sessionList().catch(() => [])
const canOpenPath = await this.callValue<boolean>('session/canOpenWorkspacePath', {}).catch(() => false)
return {
version: this.host.harnessVersion ?? this.host.clientVersion ?? 'v0.1.2-rc.1',
cwd: this.eventHostHome ?? '',
attachedSessions: this.sessionsCache.size,
canOpenPath,
}
}
async hostListDirectory(path?: string): Promise<HarnessDirectoryListing> {
const result = await this.callValue<HarnessDirectoryListing>('directoryPicker/list', path === undefined ? {} : { path })
if (typeof result.path !== 'string' || !Array.isArray(result.entries)) {
throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host returned an invalid directory listing.')
}
return result
}
async workspaceList(): Promise<HarnessWorkspaceList> {
const source = await this.gateway.open('workspace/follow', { args: {} })
const iterator = source[Symbol.asyncIterator]()
try {
const first = await iterator.next()
if (first.done || !isRecord(first.value) || first.value.type !== 'baseline' || !isRecord(first.value.value)) {
throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host returned an invalid workspace baseline.')
}
return normalizeWorkspaceList(first.value.value)
} finally {
await iterator.return?.()
}
}
async workspaceCreate(path: string): Promise<{ workspace: HarnessWorkspaceView; created: boolean }> {
const result = await this.callValue<{ workspace: HarnessWorkspaceView; created: boolean }>('workspace/create', { request: { path } })
if (typeof result.workspace?.workspaceId !== 'string') {
throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host returned an invalid workspace.')
}
return result
}
async workspaceRename(workspaceId: string, title: string): Promise<HarnessWorkspaceView> {
const result = await this.callValue<{ workspace: HarnessWorkspaceView }>('workspace/rename', { request: { workspaceId, title } })
if (typeof result.workspace?.workspaceId !== 'string') {
throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host returned an invalid workspace.')
}
return result.workspace
}
async workspaceDelete(workspaceId: string): Promise<void> {
await this.callValue('workspace/delete', { request: { workspaceId } })
}
async workspaceArchiveSession(sessionId: string, options?: { stopActivity?: boolean }): Promise<string[]> {
const request: { sessionId: string; stopActivity?: boolean } = {
sessionId,
stopActivity: options?.stopActivity ?? true,
}
const result = await this.callValue<{ archivedSessionIds: string[] }>('workspace/archiveSession', { request })
return Array.isArray(result.archivedSessionIds) ? result.archivedSessionIds : []
}
async workspaceUnarchiveSession(sessionId: string): Promise<string[]> {
const result = await this.callValue<{ archivedSessionIds: string[] }>('workspace/unarchiveSession', { request: { sessionId } })
return Array.isArray(result.archivedSessionIds) ? result.archivedSessionIds : []
}
async workspacePinSession(sessionId: string): Promise<string[]> {
const result = await this.callValue<{ pinnedSessionIds: string[] }>('workspace/pinSession', { request: { sessionId } })
return Array.isArray(result.pinnedSessionIds) ? result.pinnedSessionIds : []
}
async workspaceUnpinSession(sessionId: string): Promise<string[]> {
const result = await this.callValue<{ pinnedSessionIds: string[] }>('workspace/unpinSession', { request: { sessionId } })
return Array.isArray(result.pinnedSessionIds) ? result.pinnedSessionIds : []
}
async sessionRename(sessionId: string, title: string): Promise<{ title: string; seq: number }> {
return this.callValue<{ title: string; seq: number }>('session/rename', { request: { sessionId, title } })
}
async workspaceInsertBefore(workspaceId: string, beforeWorkspaceId?: string): Promise<string[]> {
const result = await this.callValue<{ workspaceIds: string[] }>('workspace/insertBefore', {
request: {
workspaceId,
...(beforeWorkspaceId === undefined ? {} : { beforeWorkspaceId }),
},
})
return Array.isArray(result.workspaceIds) ? result.workspaceIds : []
}
async scheduleCatalog(): Promise<ScheduleCatalogEntry[]> {
const result = await this.callValue<ScheduleCatalogEntry[] | { items: ScheduleCatalogEntry[] }>('schedule/catalog', {})
const list = Array.isArray(result)
? result
: result && Array.isArray((result as { items?: ScheduleCatalogEntry[] }).items)
? (result as { items: ScheduleCatalogEntry[] }).items
: null
if (list === null) {
throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host returned an invalid schedule catalog payload.')
}
return list.map(entry => {
if (typeof entry.sessionId === 'string' && entry.sessionId.length > 0) return entry
const target = (entry as unknown as Record<string, unknown>).target
if (target && typeof target === 'object' && !Array.isArray(target)) {
const targetObj = target as Record<string, unknown>
if (targetObj.kind === 'session' && typeof targetObj.sessionId === 'string' && targetObj.sessionId.length > 0) {
return { ...entry, sessionId: targetObj.sessionId }
}
}
return entry
})
}
async scheduleCreate(sessionId: string, request: ScheduleCreateRequest): Promise<ScheduleRecord> {
return this.callValue<ScheduleRecord>('schedule/create', {
request: { sessionId, ...request },
})
}
async scheduleUpdate(request: ScheduleUpdateRequest): Promise<ScheduleUpdateResult> {
return this.callValue<ScheduleUpdateResult>('schedule/update', {
request,
})
}
async scheduleDelete(sessionId: string, id: string): Promise<ScheduleDeleteResult> {
return this.callValue<ScheduleDeleteResult>('schedule/delete', { request: { sessionId, id } })
}
async scheduleHistory(sessionId: string, id: string, limit = 20, before?: string): Promise<ScheduleDeliveryHistoryResult> {
return this.callValue<ScheduleDeliveryHistoryResult>('schedule/history', {
request: { sessionId, id, limit, ...(before ? { before } : {}) },
})
}
/** Official plugin inventory; the Host hides its own Remote transport rows. */
async pluginListBundles(): Promise<unknown[]> {
const result = await this.callValue<unknown>('pluginManager/listBundles', {})
if (!Array.isArray(result)) throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host returned an invalid plugin bundle list.')
return result
}
async pluginListPlugins(): Promise<unknown[]> {
const result = await this.callValue<unknown>('pluginManager/listPlugins', {})
if (!Array.isArray(result)) throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host returned an invalid plugin list.')
return result
}
/** Switch a bundle (by package name) or one of its rows (by entry id); the Host re-checks its inventory. */
async pluginSetEnabled(kind: 'bundle' | 'plugin', target: string, enabled: boolean): Promise<HarnessPluginApplication> {
const result = kind === 'bundle'
? await this.callValue<unknown>('pluginManager/setBundleEnabled', { name: target, enabled })
: await this.callValue<unknown>('pluginManager/setPluginEnabled', { id: target, enabled })
if (!isRecord(result) || typeof result.application !== 'string') {
throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host returned an invalid plugin change result.')
}
if (result.application === 'failed') {
const error = isRecord(result.error) ? result.error : {}
throw new RemoteGatewayError(
typeof error.code === 'string' ? error.code : 'FAILED',
typeof error.diagnostic === 'string' && error.diagnostic !== '' ? error.diagnostic : 'The Host could not change the plugin.',
)
}
return { application: result.application }
}
async settingsDescribe(): Promise<HarnessSettingsDescribe> {
const result = await this.callValue<unknown>('settings/describe', {})
if (!isRecord(result) || !Array.isArray(result.namespaces)) {
throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host returned invalid settings.')
}
return {
writable: result.writable !== false,
namespaces: result.namespaces.filter(isRecord).filter(row => typeof row.ns === 'string')
.map(row => ({
ns: row.ns as string,
schema: row.schema,
value: row.value,
...(row.user === undefined ? {} : { user: row.user }),
revision: typeof row.revision === 'number' ? row.revision : 0,
})),
}
}
/** Path-addressed edits against the revision the form was read at; stale writes are refused by the Host. */
async settingsMutate(ns: string, ops: HarnessSettingsPathOp[], expectedRevision: number): Promise<void> {
const result = await this.callValue<unknown>('settings/mutate', { ns, ops, expectedRevision })
if (isRecord(result) && result.ok === false) {
const error = isRecord(result.error) ? result.error : {}
throw new RemoteGatewayError(
typeof error.code === 'string' ? error.code : 'FAILED',
typeof error.message === 'string' ? error.message : 'The Host rejected the settings change.',
)
}
}
async respondApproval(frameRpcId: string, sessionId: string, approvalId: string, outcome: 'allowed-once' | 'rejected'): Promise<void> {
const eventId = this.pendingEvents.has(frameRpcId) ? frameRpcId : approvalId
await this.respondEvent(eventId, { kind: 'result', value: outcome })
this.pendingEvents.delete(eventId)
this.emitFrame({
rpcId: '',
payload: { type: 'approval/resolved', sessionId, approvalId, outcome },
})
}
async respondQuestion(frameRpcId: string, sessionId: string, answer: HarnessQuestionAnswer): Promise<void> {
if (await this.questions.answer(frameRpcId, sessionId, answer)) return
await this.respondEvent(frameRpcId, { kind: 'result', value: answer })
this.pendingEvents.delete(frameRpcId)
this.emitFrame({
rpcId: '',
payload: { type: 'question/resolved', sessionId, questionRpcId: frameRpcId, outcome: 'answered' },
})
}
private async respondEvent(eventId: string, outcome: { kind: 'result'; value?: unknown } | { kind: 'rejected'; error: unknown }): Promise<void> {
if (this.eventClientId === undefined) {
throw new RemoteGatewayError('INVALID_MESSAGE', 'The Host event stream is not ready.')
}
await this.gateway.call('$events/result', {
args: {
clientId: this.eventClientId,
eventId,
outcome,
},
})
}
private async callValue<T>(endpoint: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<T> {
const value = await this.gateway.call<T | RemoteGatewayResult<T>>(endpoint, { args }, signal)
if (isRecord(value) && value.ok === true) return value.value as T
if (isRecord(value) && value.ok === false && isRecord(value.error)) {
const error = value.error
throw new RemoteGatewayError(
typeof error.code === 'string' ? error.code : 'internal',
typeof error.message === 'string' ? error.message : 'The Host rejected the Remote request.',
isRecord(error.details) ? error.details : {},
)
}
return value as T
}
private async pumpEvents(handle: StreamHandle): Promise<void> {
const source = await this.gateway.open('$events', { args: {} }, handle.controller.signal)
handle.stream = source
const iterator = source[Symbol.asyncIterator]()
handle.iterator = iterator
while (this.events === handle) {
const next = await iterator.next()
if (next.done) return
this.routeEventFrame(next.value)
}
}
private async pumpControl(handle: StreamHandle): Promise<void> {
const source = await this.gateway.open('session/control', { args: {} }, handle.controller.signal)
handle.stream = source
const iterator = source[Symbol.asyncIterator]()
handle.iterator = iterator
while (this.control === handle) {
const next = await iterator.next()
if (next.done) return
this.routeControlFrame(next.value)
}
}
private async pumpSessionFollow(
handle: SessionFollowHandle,
iterator: AsyncIterator<unknown>,
): Promise<void> {
while (this.sessionFollow === handle) {
const next = await iterator.next()
if (this.sessionFollow !== handle || handle.controller.signal.aborted) return
if (next.done) return
for (const entry of this.entriesFromSessionFollow(handle, next.value)) {
this.emitFrame({
rpcId: '',
payload: {
type: 'session/event',
sessionId: handle.sessionId,
event: entry.event,
...(entry.view === undefined ? {} : { view: entry.view }),
},
})
}
}
}
private entriesFromSessionFollow(handle: SessionFollowHandle, value: unknown): HarnessHistoryEntry[] {
if (this.host.sessionFormat !== 3 || !isRecord(value) || value.type !== 'assistant-stream') {
return entriesFromFollowValue(value)
}
const frame = isRecord(value.frame) ? value.frame : undefined
if (frame === undefined || typeof frame.type !== 'string') return []
if (frame.type === 'start') {
handle.assistant = assistantStreamAttempt(frame, 0)
return []
}
const attempt = handle.assistant
if (frame.type === 'end') {
if (attempt !== undefined && frame.attemptId === attempt.attemptId) handle.assistant = undefined
return []
}
if (frame.type !== 'chunk' || attempt === undefined
|| frame.attemptId !== attempt.attemptId
|| frame.index !== attempt.nextIndex
|| typeof frame.time !== 'number'
|| !isRecord(frame.chunk)) return []
attempt.nextIndex += 1
return [{
event: {
type: 'assistant/chunk',
seq: attempt.startedAfterSeq + 1 - 1 / (attempt.nextIndex + 1),
time: frame.time,
data: { turn: attempt.turn, step: attempt.step, chunk: frame.chunk },
},
}]
}
private routeEventFrame(value: unknown): void {
if (!isRecord(value) || typeof value.type !== 'string') return
if (value.type === 'ready') {
this.eventClientId = typeof value.clientId === 'string' ? value.clientId : undefined
const host = isRecord(value.host) ? value.host : undefined
this.eventHostHome = typeof host?.home === 'string' ? host.home : undefined
return
}
if (value.type === 'waterfall' && typeof value.eventId === 'string' && typeof value.agentId === 'string' && isRecord(value.request)) {
this.routeWaterfall(value.event, value.eventId, value.agentId, value.request)
return
}
if (value.type === 'cancel' && typeof value.eventId === 'string') this.cancelRemoteEvent(value.eventId)
}
private routeWaterfall(event: unknown, eventId: string, sessionId: string, request: Record<string, unknown>): void {
if (event === 'approval/request') {
const frame: HarnessClientFrame = {
rpcId: eventId,
payload: {
type: 'approval/requested',
sessionId,
approvalId: eventId,
toolName: typeof request.toolName === 'string' ? request.toolName : 'Harness tool',
...(typeof request.callId === 'string' ? { callId: request.callId } : {}),
...(typeof request.reason === 'string' ? { reason: request.reason } : {}),
},
}
this.pendingEvents.set(eventId, { event, eventId, sessionId, frame })
this.emitFrame(frame)
return
}
if (event === 'user-questions/request') {
if (this.questions.request(sessionId, eventId, request)) return
const frame: HarnessClientFrame = {
rpcId: eventId,
payload: {
type: 'question/requested',
sessionId,
questions: Array.isArray(request.questions) ? request.questions : [],
},
}
this.pendingEvents.set(eventId, { event, eventId, sessionId, frame })
this.emitFrame(frame)
}
}
private republishPendingSessionInteractions(sessionId: string, hasUserQuestionsProjection: boolean): void {
if (!hasUserQuestionsProjection) this.questions.republish(sessionId)
for (const pending of this.pendingEvents.values()) {
if (pending.sessionId === sessionId) this.emitFrame(pending.frame)
}
}
private cancelRemoteEvent(eventId: string): void {
if (this.questions.cancel(eventId)) return
const pending = this.pendingEvents.get(eventId)
if (pending === undefined) return
this.pendingEvents.delete(eventId)
if (pending.event === 'approval/request') {
this.emitFrame({
rpcId: '',
payload: { type: 'approval/resolved', sessionId: pending.sessionId, approvalId: eventId, outcome: 'cancelled' },
})
return
}
this.emitFrame({
rpcId: '',
payload: { type: 'question/resolved', sessionId: pending.sessionId, questionRpcId: eventId, outcome: 'cancelled' },
})
}
private routeControlFrame(value: unknown): void {
if (!isRecord(value) || typeof value.type !== 'string') return
if (value.type === 'baseline' && isRecord(value.value) && isRecord(value.value.projections)) {
for (const [sessionId, block] of Object.entries(value.value.projections)) this.applyProjectionBaseline(sessionId, block)
return
}
if (value.type === 'projection' && typeof value.sessionId === 'string' && typeof value.key === 'string') {
this.applyProjection(value.sessionId, value.key, value.value, typeof value.seq === 'number' ? value.seq : undefined)
}
}
private applyProjectionBaseline(sessionId: string, block: unknown): void {
if (!isRecord(block) || !isRecord(block.values)) return
const seq = typeof block.asOfSeq === 'number' ? block.asOfSeq : undefined
const values = normalizeProjectionValues(block.values)
const cached = this.sessionsCache.get(sessionId)
if (cached !== undefined) {
this.sessionsCache.set(sessionId, {
...cached,
projections: { asOfSeq: seq, values: { ...cached.projections?.values, ...values } },
})
}
for (const [key, value] of Object.entries(values)) this.applyProjection(sessionId, key, value, seq)
}
private applyProjection(sessionId: string, key: string, value: unknown, seq?: number): void {
const projectedValue = normalizeProjectionValue(key, value)
const cached = this.sessionsCache.get(sessionId)
if (cached !== undefined) {
this.sessionsCache.set(sessionId, {
...cached,
projections: {
asOfSeq: seq ?? cached.projections?.asOfSeq,
values: { ...cached.projections?.values, [key]: projectedValue },
},
})
}
if (key === 'userQuestions') this.questions.projection(sessionId, projectedValue, seq)
if (key === 'modelSelection') {
const selection = modelSelectionFromValue(projectedValue)
if (selection !== undefined) this.selectedModels.set(sessionId, selection)
}
this.emitFrame({
rpcId: '',
payload: { type: 'session/projection', sessionId, key, value: projectedValue, ...(seq === undefined ? {} : { seq }) },
})
}
private emitStreamFailure(handle: StreamHandle, active: StreamHandle | undefined, error: unknown): void {
if (active !== handle || handle.controller.signal.aborted) return
const failure = this.gateway.failure(error)
this.emitFrame({ rpcId: '', payload: { type: 'stream/closed', reason: 'failed', error: failure } })
}
private emitFrame(frame: HarnessClientFrame): void {
this.onFrame?.(frame)
}
private async closeSessionFollow(): Promise<void> {
const follow = this.sessionFollow
this.sessionFollow = undefined
await this.closeHandle(follow, true)
}
/**
* Bound one phase of opening a session follow. An unanswered open (observed
* for subagent-parent addresses) must fail loudly instead of hanging the
* caller's session switch forever.
*/
private async boundedFollow<T>(work: Promise<T>, handle: SessionFollowHandle, budgetMs = 15_000): Promise<T> {
// The raced work keeps running after a timeout: attach a sink so its late
// rejection is never an unhandled promise rejection.
void work.catch(() => undefined)
let timer: ReturnType<typeof setTimeout> | undefined
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new RemoteGatewayError('STREAM_TIMEOUT', 'The session follow did not open in time.')), budgetMs)
})
try {
return await Promise.race([work, timeout])
} catch (error) {
handle.controller.abort()
throw error
} finally {
if (timer !== undefined) clearTimeout(timer)
}
}
private async closeHandle(handle: StreamHandle | undefined, notifyRemote: boolean): Promise<void> {
if (handle === undefined) return
if (handle.stream !== undefined) {
// The close of a live follow can wait on the pump's pending read forever
// (observed when switching sessions from inside a live conversation),
// which froze the incoming open in `closeSessionFollow`. Bound it: the
// abort below is authoritative for local cleanup either way.
await Promise.race([
handle.stream.close(notifyRemote).catch(() => undefined),
new Promise(resolve => setTimeout(resolve, 2_000)),
])
handle.controller.abort()
return
}
handle.controller.abort()
}
}
function normalizeSession(value: unknown): HarnessRemoteSession | undefined {
if (!isRecord(value)
|| typeof value.sessionId !== 'string'
|| typeof value.updatedAt !== 'number'
|| typeof value.running !== 'boolean'
|| typeof value.blank !== 'boolean') return undefined
const session = value as unknown as HarnessRemoteSession
return {
...session,
...(session.agentPreset === undefined ? {} : { agentPreset: normalizeAgentPreset(session.agentPreset) as string }),
...(session.projections === undefined
? {}
: {
projections: {
...session.projections,
...(isRecord(session.projections.values)
? { values: normalizeProjectionValues(session.projections.values) }
: {}),
},
}),
}
}
function normalizeProjectionValues(values: Record<string, unknown>): Record<string, unknown> {
return Object.fromEntries(
Object.entries(values).map(([key, value]) => [key, normalizeProjectionValue(key, value)]),
)
}
function normalizeProjectionValue(key: string, value: unknown): unknown {
return key === 'agentPreset' ? normalizeAgentPreset(value) : value
}
function normalizeAgentPreset(value: unknown): unknown {
return value === LEGACY_AGENT_PRESET ? LEGACY_AGENT_PRESET_TARGET : value
}
function normalizeWorkspaceList(value: Record<string, unknown>): HarnessWorkspaceList {
return {
items: Array.isArray(value.items)
? value.items.filter(item => isRecord(item) && typeof item.workspaceId === 'string') as HarnessWorkspaceView[]
: [],
archivedSessionIds: Array.isArray(value.archivedSessionIds)
? value.archivedSessionIds.filter((item): item is string => typeof item === 'string')
: [],
pinnedSessionIds: Array.isArray(value.pinnedSessionIds)
? value.pinnedSessionIds.filter((item): item is string => typeof item === 'string')
: [],
}
}
function historyEntriesFromRecords(records: unknown[]): HarnessHistoryEntry[] {
return records.flatMap(record => {
if (!isRecord(record)) return []
if (record.type === 'event' && isRecord(record.event)) return historyEntryFromEvent(record.event)
if (record.type === 'chunks' && isRecord(record.event)) return entriesFromChunkRun(record.event)
return []
})
}
function entriesFromFollowValue(value: unknown): HarnessHistoryEntry[] {
if (!isRecord(value)) return []
if (value.type === 'event' && isRecord(value.event)) return historyEntryFromEvent(value.event)
if (value.type === 'chunks' && isRecord(value.event)) return entriesFromChunkRun(value.event)
return []
}
function historyEntryFromEvent(event: Record<string, unknown>): HarnessHistoryEntry[] {
if (typeof event.type !== 'string' || typeof event.seq !== 'number' || typeof event.time !== 'number') return []
const surfaceOp = normalizeSurfaceOp(event.surfaceOp)
return [{
event: {
type: event.type,
seq: event.seq,
time: event.time,
data: isRecord(event.data) ? event.data : {},
...(Array.isArray(event.sourceEventSeqs) ? { sourceEventSeqs: event.sourceEventSeqs.filter((item): item is number => typeof item === 'number') } : {}),
...(surfaceOp === undefined ? {} : { surfaceOp }),
...(event.ignorable === true ? { ignorable: true } : {}),
},
}]
}
function normalizeSurfaceOp(value: unknown): HarnessSurfaceOp | undefined {
if (value === 'append') return value
if (!isRecord(value) || value.op !== 'replace') return undefined
if (typeof value.startSeq === 'number' && typeof value.endSeq === 'number') {
return { op: 'replace', startSeq: value.startSeq, endSeq: value.endSeq }
}
if (typeof value.start === 'number' && typeof value.end === 'number') {
return { op: 'replace', start: value.start, end: value.end }
}
return undefined
}
function assistantStreamBaseline(value: unknown): AssistantStreamState | undefined {
if (!isRecord(value) || !isRecord(value.activeAttempt)) return undefined
return assistantStreamAttempt(value.activeAttempt)
}
function assistantStreamAttempt(value: Record<string, unknown>, defaultNextIndex?: number): AssistantStreamState | undefined {
const nextIndex = typeof value.nextIndex === 'number' ? value.nextIndex : defaultNextIndex
return typeof value.attemptId === 'string'
&& typeof value.startedAfterSeq === 'number'
&& typeof value.turn === 'number'
&& typeof value.step === 'number'
&& nextIndex !== undefined
? {
attemptId: value.attemptId,
startedAfterSeq: value.startedAfterSeq,
turn: value.turn,
step: value.step,
nextIndex,
}
: undefined
}
function entriesFromChunkRun(event: Record<string, unknown>): HarnessHistoryEntry[] {
if (typeof event.type !== 'string' || typeof event.seq !== 'number' || typeof event.time !== 'number' || !isRecord(event.data)) return []
const seq = event.seq
const data = event.data
const turn = typeof data.turn === 'number' ? data.turn : undefined
const step = typeof data.step === 'number' ? data.step : undefined
const chunkIndex = typeof data.index === 'number' ? data.index : undefined
const base = {
...(turn === undefined ? {} : { turn }),
...(step === undefined ? {} : { step }),
}
const dt = Array.isArray(data.dt) ? data.dt.filter((item): item is number => typeof item === 'number') : []
if (event.type === 'chunkrow/text-chunks' || event.type === 'chunkrow/reasoning-chunks') {
const texts = Array.isArray(data.texts) ? data.texts.filter((item): item is string => typeof item === 'string') : []
let time = event.time
return texts.map((text, offset) => {
if (offset > 0) time += dt[offset - 1] ?? 0
return {
event: {
type: 'assistant/chunk',
seq: seq + offset,
time,
data: {
...base,
chunk: {
type: event.type === 'chunkrow/text-chunks' ? 'text-delta' : 'reasoning-delta',
...(chunkIndex === undefined ? {} : { index: chunkIndex }),
text,
},
},
},
}
})
}
if (event.type !== 'chunkrow/tool-call-chunks') return []
const args = Array.isArray(data.args) ? data.args.filter((item): item is string => typeof item === 'string') : []
let time = event.time
return args.map((text, offset) => {
if (offset > 0) time += dt[offset - 1] ?? 0
return {
event: {
type: 'assistant/chunk',
seq: seq + offset,
time,
data: {
...base,
chunk: {
type: 'tool-call-delta',
...(chunkIndex === undefined ? {} : { index: chunkIndex }),
id: typeof data.id === 'string' ? data.id : undefined,
name: typeof data.name === 'string' ? data.name : undefined,
argumentsDelta: text,
},
},
},
}
})
}
function modelSelectionFromSession(session: HarnessRemoteSession | undefined): HarnessModelSelection | undefined {
return modelSelectionFromValue(session?.projections?.values?.modelSelection)
}
function modelSelectionFromValue(value: unknown): HarnessModelSelection | undefined {
if (!isRecord(value)) return undefined
const candidates = [value.next, value.lastUsed, value]
for (const candidate of candidates) {
if (!isRecord(candidate) || typeof candidate.provider !== 'string' || typeof candidate.model !== 'string') continue
return {
provider: candidate.provider,
model: candidate.model,
...(typeof candidate.reasoningEffort === 'string' ? { reasoningEffort: candidate.reasoningEffort } : {}),
}
}
return undefined
}
function clientTimeZone(): string | undefined {
try {
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone
// The Host only accepts UTC or an IANA "Area/Location" name. Devices that
// report a bare abbreviation (e.g. "GMT") are rejected at prompt time, so
// omit the field and let the Host fall back to its own default.
if (typeof zone !== 'string' || zone.length === 0) return undefined
if (zone === 'UTC') return zone
return /^[A-Za-z_]+\/[A-Za-z0-9_+-]+(?:\/[A-Za-z0-9_+-]+)?$/.test(zone) ? zone : undefined
} catch {
return undefined
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}