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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"test:watch": "vitest"
},
"dependencies": {
"@ellipsis-dev/sdk": "^0.1.0",
"commander": "^12.1.0",
"ink": "^5.0.1",
"ink-spinner": "^5.0.0",
Expand Down
55 changes: 20 additions & 35 deletions src/commands/connect.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { Command } from 'commander'
import React from 'react'
import { render } from 'ink'
import { SessionTranscriptStore } from '@ellipsis-dev/sdk/store'
import { ApiClient } from '../lib/api'
import { requireToken, resolveApiBase, resolveAppBase } from '../lib/config'
import { runAction, usdNumberFromMillicents } from '../lib/output'
import { foldCosts, isConnectVisibleRecord, recordToItems, type CCEvent } from '../lib/events'
import { runAction } from '../lib/output'
import { sessionUrl } from '../lib/urls'
import { resolveWsBase } from '../lib/ws'
import { makeOpenSocket, resolveWsBase } from '../lib/stream'
import { ConnectApp } from '../ui/ConnectApp'
import type { AgentSession } from '../lib/types'

Expand Down Expand Up @@ -93,7 +93,7 @@ export async function runConnect(
): Promise<void> {
const api = new ApiClient()
const token = requireToken()
const wsBase = resolveWsBase(resolveApiBase())
const openSocket = makeOpenSocket(token, resolveWsBase(resolveApiBase()))

const [session, me] = await Promise.all([api.getAgentSession(sessionId), api.whoami()])
const c = connectability(session)
Expand All @@ -104,48 +104,33 @@ export async function runConnect(
const url = sessionUrl(resolveAppBase(), me.customer_login, sessionId)

// No scrollback preamble: the app owns the whole surface, Claude Code-style.
// The banner (brand + version + session link) and the footer carry the
// session identity/status; a watch-only reason surfaces as the app's notice.
// The footer carries the session identity/status; a watch-only reason
// surfaces as the app's notice.

// Fetch the stored records to seed the transcript (unless --no-records), the
// live-refresh cursor (so live updates only append what's new), and the
// opening spend. Records are ordered by feed_seq (the shared transcript +
// lifecycle feed). Lifecycle rows are filtered except the sandbox-ready
// conversation note (isConnectVisibleRecord): connect shows the
// conversation, and the live activity line + footer carry session state.
const records = await api.getAgentSessionRecords(sessionId)
const ordered = [...records].sort((a, b) => a.feed_seq - b.feed_seq)
const initialMaxFeedSeq = ordered.reduce((m, s) => Math.max(m, s.feed_seq), 0)
const initialItems = showRecords
? ordered
.filter(isConnectVisibleRecord)
.flatMap((st) => recordToItems(st, `s${st.feed_seq}`))
: []
const initialCost = foldCosts(ordered.map((st) => st.payload as CCEvent))
// The server's ledger total at connect time; live updates arrive as
// cost_millicents on status/done frames.
const initialServerCostUsd = usdNumberFromMillicents(
session.cost_tokens + session.cost_sandbox_cpu + session.cost_sandbox_memory + session.cost_fee,
)
// Seed ONE transcript store with the stored records and the fetched session
// — synthetic frames through the same ingest path the live stream uses, so
// the first paint is instant and streamSession resumes past the seeded
// cursor instead of replaying history. --no-records skips *rendering* the
// seeded history (minRenderFeedSeq), not re-streaming it.
const store = new SessionTranscriptStore()
const page = await api.getAgentSessionRecordsPage(sessionId)
const ordered = [...page.records].sort((a, b) => a.feed_seq - b.feed_seq)
if (ordered.length) store.ingest({ type: 'records_append', records: ordered })
store.ingest({ type: 'messages', messages: page.messages ?? [] })
store.ingest({ type: 'session', session })

// Written by the app when it exits because the conversation closed (terminal;
// nothing left to reconnect to), so the detach sign-off below stays honest.
const exitState = { closed: false }
const app = render(
React.createElement(ConnectApp, {
api,
token,
sessionId,
wsBase,
store,
openSocket,
canSend,
initialItems,
// Always advance the cursor past existing records: --no-records skips
// *rendering* history, not re-streaming it live.
initialMaxFeedSeq,
initialStatus: session.surface?.status ?? session.status,
minRenderFeedSeq: showRecords ? 0 : store.cursor,
sessionUrl: url,
initialCost,
initialServerCostUsd,
initialNotice: reason ?? null,
// The session's one model, fixed at creation (backend tokens_model).
model: typeof session.tokens_model === 'string' ? session.tokens_model : null,
Expand Down
13 changes: 7 additions & 6 deletions src/commands/session.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,17 @@ import {
} from '../lib/args'
import { sessionUrl } from '../lib/urls'
import {
resolveWsBase,
sessionStatusWord,
streamSession,
StreamUnavailableError,
type StreamFrame,
type StreamOutcome,
} from '../lib/ws'
import { isConnectVisibleRecord, recordToItems } from '../lib/events'
} from '@ellipsis-dev/sdk/stream'
import { isConnectVisibleRecord, recordToItems } from '@ellipsis-dev/sdk/store'
import { makeOpenSocket, resolveWsBase } from '../lib/stream'
import type {
AgentSession,
AgentSessionWire,
AgentSessionSource,
AgentSessionStatus,
GithubAccountSnippet,
Expand Down Expand Up @@ -808,7 +809,7 @@ export async function watchSessionStreaming(
json?: boolean,
): Promise<void> {
const token = requireToken()
const wsBase = resolveWsBase(resolveApiBase())
const openSocket = makeOpenSocket(token, resolveWsBase(resolveApiBase()))

// Session frames are LWW snapshots resent on any change (cost ticks
// included), so collapse to status-word transitions — both to keep the
Expand All @@ -819,7 +820,7 @@ export async function watchSessionStreaming(
const onFrame = (frame: StreamFrame) => {
if (frame.type === 'session' || frame.type === 'snapshot') {
const word = sessionStatusWord(
(frame as { session: AgentSession }).session,
(frame as unknown as { session: AgentSessionWire }).session,
)
if (word === lastStatus) return
lastStatus = word
Expand All @@ -834,7 +835,7 @@ export async function watchSessionStreaming(

let outcome: StreamOutcome
try {
outcome = await streamSession({ token, sessionId, wsBase, onFrame })
outcome = await streamSession({ sessionId, openSocket, onFrame })
} catch (err) {
if (err instanceof StreamUnavailableError) {
if (!json) {
Expand Down
31 changes: 22 additions & 9 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,11 @@ import type {
StartSandboxBuildRequest,
} from './types'

// Thin REST client over the public `/v1` API. The typed request/response
// surface mirrors ellipsis/src/public_api/routers/v1/v1_router.py and will move
// to @ellipsis/sdk (generated from the backend OpenAPI spec) once that package
// exists; this CLI then imports it instead of hand-rolling types.
// Thin REST client over the public `/v1` API. The session-stream surface
// types come from @ellipsis-dev/sdk (generated from the backend's schema, via
// lib/types re-exports); the rest of the typed surface remains a hand-rolled
// mirror of ellipsis/src/public_api/routers/v1/v1_router.py until the SDK's
// OpenAPI surface widens beyond the protocol endpoints.

export class ApiError extends Error {
constructor(
Expand Down Expand Up @@ -208,11 +209,23 @@ export class ApiClient {
// The session's full stored transcript as native session_records (transcript
// + lifecycle), ordered by feed_seq.
async getAgentSessionRecords(sessionId: string): Promise<SessionRecord[]> {
const res = await this.request<ListSessionRecordsResponse>(
'GET',
`/v1/sessions/${encodeURIComponent(sessionId)}/records`,
)
return res.records
const res = await this.getAgentSessionRecordsPage(sessionId)
// The OpenAPI response type marks defaulted fields optional; on the wire
// the server always serializes every field (the frames-schema flavor).
return res.records as SessionRecord[]
}

// The full records response (records + the open inbox slice +
// has_more/earliest_feed_seq), optionally resuming past a feed_seq cursor
// (protocol §4.3) — what the connect UI's REST poll fallback feeds its
// transcript store from.
getAgentSessionRecordsPage(
sessionId: string,
options: { afterSeq?: number } = {},
): Promise<ListSessionRecordsResponse> {
const query =
options.afterSeq != null && options.afterSeq > 0 ? `?after_seq=${options.afterSeq}` : ''
return this.request('GET', `/v1/sessions/${encodeURIComponent(sessionId)}/records${query}`)
}

// The session's conversation structure — turns and inbox messages, each
Expand Down
Loading