@prismshadow/penguin-server · packages/server/src/runtime/session-manager.ts:4206

SessionServiceIface

interface

No JSDoc comment in source yet.

API

@Interface()
export abstract class SessionServiceIface {
  abstract toInfo(
      row: SessionRow,
      hasTrace: boolean,
      orgIds?: ReadonlyMap<string, string>,
      view?: ListingView,
    ): Promise<SessionInfo>;
  abstract hasTrace(row: SessionRow): Promise<boolean>;
  abstract listingOf(row: SessionRow, view?: ListingView): Promise<SessionCategory | null>;
  abstract listSessions(
      projectId: string,
      agentId: string,
      opts?: {
        paging?: SessionListPaging;
        order?: SessionListOrder;
        category?: SessionCategory;
        workspaceGroup?: string;
        withCounts?: boolean;
        excludeOrg?: boolean;
        view?: ListingView;
      },
    ): Promise<{
      sessions: SessionInfo[];
      counts?: SessionCategoryCounts;
      workspaceCounts?: Record<string, SessionCategoryCounts>;
      workspaceLatest?: Record<string, string>;
      workspaceLatestActive?: Record<string, string>;
    }>;
  abstract archivedRows(
      projectId: string,
      agentId: string,
      view?: ListingView,
    ): Promise<ArchivedRow[]>;
  abstract activeRows(
      projectId: string,
      agentId: string,
      view?: ListingView,
    ): Promise<SessionRow[]>;
  abstract sessionStats(
      projectId: string,
      agentId: string,
      days: number,
    ): Promise<{ sessionCount: number; activity: number[] }>;
  abstract adoptUnmanagedTraceSessions(): Promise<number>;
  abstract createSession(args: {
      projectId: string;
      agentId: string;
      /** Upstream id of the session's model; always paired with provider. Omit both for the Project's default reference. */
      modelId?: string;
      /** The provider group for `modelId`; always paired with modelId, never inferred. */
      provider?: string;
      workspace?: string;
      thinkingLevel?: ThinkingLevelName;
      approvalMode?: ApprovalMode;
      /** The composer's sandbox picks; omitted halves take the server's settings. */
      sandbox?: Partial<SessionSandbox>;
      /** Whether the creator is an administrator (may loosen past the settings). Default false. */
      isAdmin?: boolean;
      /**
       * What kind of conversation this is, recorded in the Session's session_meta: `schedule`
       * from the scheduler, `company` from the organization runtime, `cli` from `penguin run`
       * (the only source a request may name), `api` from an Agent API run; absent means `user`,
       * a person's conversation.
       */
      source?: SessionSource;
      /**
       * Creating-client hint stored on the index row (`POST .../sessions` body `client`):
       * "cli" from the CLI, defaulting to "web". "org" and "api" are not accepted over HTTP —
       * the organization runtime and the Agent API's run handler call this method directly and
       * are the only callers that pass them, so no request can claim either provenance for
       * itself ("api" is what lets the Agent API continue a Session).
       */
      client?: "web" | "cli" | "org" | "api" | "workbench";
    }): Promise<SessionInfo>;
  abstract defaultSandbox(): SandboxSettings;
  abstract pickSandbox(
      row: SessionRow,
      pick: Partial<SessionSandbox>,
      isAdmin: boolean,
    ): SandboxSettings;
  abstract updateSandbox(sessionId: string, policy: SandboxSettings): void;
  abstract latestTracePath(row: SessionRow): Promise<string | undefined>;
}

Contract Topology

Static AST wiring across @Module / @Provide / @Use

Members (13)

toInfo

toInfo(row: SessionRow, hasTrace: boolean, orgIds?: ReadonlyMap<string, string>, view?: ListingView): Promise<SessionInfo>

DB row -> SessionInfo (run status and pending approval count come from session-manager). Async because source is derived from session_meta: a registry miss (Session predating this process) falls back to reading the Trace head once (see sourceOf). traces is the list flow's one-walk discovery result; without it a miss locates the shard itself. archived is the listing rule's answer (listCategory), not the bare mark: a background Session the user never kept reads archived, and a subagent with a stray mark does not.

orgIds is the list flow's one-query organization map (see listSessions); without it the organization is a point lookup, which is what the single-Session paths want. view is who is reading (sourceSeenBy): a server that adopted this one sees its earlier Sessions as CLI tasks, in source and archived alike.

@paramrowSessionRow
@paramhasTraceboolean
@paramorgIds?ReadonlyMap<string, string>
@paramview?ListingView
@returnsPromise<SessionInfo>

hasTrace

hasTrace(row: SessionRow): Promise<boolean>

Whether this Session already has a Trace record (a Task has been run): answered by the index (reconciled first).

@paramrowSessionRow
@returnsPromise<boolean>

listingOf

listingOf(row: SessionRow, view?: ListingView): Promise<SessionCategory | null>

Where one row is listed, for a caller holding just the row (a PATCH, the archive page's batches). A row the registry already classified costs nothing; any other is looked up through the trace index once (hasTrace reconciles the Agent), so a subagent Session is known for one even before any list has walked it.

@paramrowSessionRow
@paramview?ListingView
@returnsPromise<SessionCategory | null>

listSessions

listSessions(projectId: string, agentId: string, opts?: { paging?: SessionListPaging; order?: SessionListOrder; category?: SessionCategory; workspaceGroup?: string; withCounts?: boolean; excludeOrg?: boolean; view?: ListingView; }): Promise<{ sessions: SessionInfo[]; counts?: SessionCategoryCounts; workspaceCounts?: Record<string, SessionCategoryCounts>; workspaceLatest?: Record<string, string>; workspaceLatestActive?: Record<string, string>; }>

List, sorted by createdAt descending — or, with order: "activity", by lastActiveAt descending (ties by sessionId, see compareActivityDesc). Every row is served straight from the DB*, whichever client created it, with no Trace directory scanning — the answer to many-session sidebar reloads re-walking the filesystem on every request (#139). Sessions living only in the Trace directory were adopted into the index by the boot-time sweep (adoptUnmanagedTraceSessions), so listing never discovers. One lazy discovery walk still runs for a list call that contains rows this process has not classified yet (no in-process source entry): it supplies the Trace locations for the one-time head reads and backfills the has_trace cache; once every row is classified, list calls touch only the DB.

Optional paging returns just that slice (the sidebar pages with limit+1 to detect "has more"); slicing happens before toInfo, so per-request source derivation (lazy Trace-head reads) stays bounded by the page size.

The before form pages the activity order by cursor: only rows strictly below it are walked and served. An offset cannot page that order, because a row below the offset that becomes active moves above it and the next page would skip a row; a cursor stays put — the moved row is simply not served again (the client learns of it from session_state). The offset form keeps serving the created order exactly as before.

category filters to one list (the sidebar's active, the archive page's archived) before paging, so offset/limit page within the category. Filtering needs each walked row's category (a possible Trace-head read per row, cached in the sources registry); without withCounts the walk stops as soon as the requested page is complete. withCounts classifies every row, a cursor or not, and returns per-category totals over the whole list — plus the same totals broken down by Workspace path, and each path's newest Session's createdAt, once over every category (workspaceLatest, the Workspace picker's "recently used") and once over the active ones (workspaceLatestActive) — so the sidebar can list every Workspace that holds active Sessions (not only the ones its loaded pages happen to touch) and place the groups by the recency of what they show, all without loading them.

workspaceGroup filters the same way, to one Workspace group (see workspace-group.ts), so a sidebar grouped by Workspace pages each group down its OWN stream instead of sharing one per-Agent cursor — without it, one group's "load more" consumes the page its siblings were about to read, and their rows move on screen untouched. The two filters compose; the returned counts stay whole-Agent either way.

A subagent or company Session — a child its parent's Agent panel opens, company mode's desk and ticket Sessions — belongs to no category (listCategory), whatever its marks: every classified form of the list (category, workspaceGroup or withCounts) leaves it out of the page, the totals, the Workspace breakdown and its stamps alike. The plain form, which classifies nothing, still serves every row.

excludeOrg drops the rows an organization owns (its desk and ticket sessions, and the sub-sessions they spawned) from the stream BEFORE anything else looks at it — the page, counts, workspaceCounts, both Workspace stamps and the limit+1 "has more" all describe the same own-rows stream. It is what development mode's list asks for: that list draws the user's own conversations, and a total or a stamp that still counted a desk or a ticket session would make its Workspace appear as a group the list can never fill. The rule above does not replace it: a person's conversation attached to a ticket is stamped org but stays user, and a row the organization caches name before the reconcile pass stamps it reads as user. Without the flag every row is served, whichever client created it, but for that rule.

view is who reads the list (sourceSeenBy): every row is classified and served as that reader sees it.

@paramprojectIdstring
@paramagentIdstring
@paramopts?{ paging?: SessionListPaging; order?: SessionListOrder; category?: SessionCategory; workspaceGroup?: string; withCounts?: boolean; excludeOrg?: boolean; view?: ListingView; }
@returnsPromise<{ sessions: SessionInfo[]; counts?: SessionCategoryCounts; workspaceCounts?: Record<string, SessionCategoryCounts>; workspaceLatest?: Record<string, string>; workspaceLatestActive?: Record<string, string>; }>

archivedRows

archivedRows(projectId: string, agentId: string, view?: ListingView): Promise<ArchivedRow[]>

The archive page's walk (services/archived-sessions-service.ts): every row of the Agent the listing rule files as archived — the rows listSessions serves with category: "archived" and excludeOrg, classified the same way — with the source each was classified by and whether it has a Trace. It builds no SessionInfo: the page makes one (toInfo) only for the rows a response carries, so a request costs a classification per archived row, not a full row view per archived row. view is who reads it, as for listSessions.

@paramprojectIdstring
@paramagentIdstring
@paramview?ListingView
@returnsPromise<ArchivedRow[]>

activeRows

activeRows(projectId: string, agentId: string, view?: ListingView): Promise<SessionRow[]>

The sidebar's share of the Agent (services/workspace-archive.ts, the "delete workspace" route): every row the listing rule files as active — the rows listSessions serves with category: "active" and excludeOrg, classified the same way, loaded or not. view is who reads it, as for listSessions.

@paramprojectIdstring
@paramagentIdstring
@paramview?ListingView
@returnsPromise<SessionRow[]>

sessionStats

sessionStats(projectId: string, agentId: string, days: number): Promise<{ sessionCount: number; activity: number[] }>

Session stats (Agents list card): total count = size of the union of DB index ∪ Trace directory discovery; activity = number of active Sessions per day over the last days days (deduplicated count of Sessions created that day or with a Trace record that day; index 0 = earliest, last index = today). Counts only — does not backfill index rows.

@paramprojectIdstring
@paramagentIdstring
@paramdaysnumber
@returnsPromise<{ sessionCount: number; activity: number[] }>

adoptUnmanagedTraceSessions

adoptUnmanagedTraceSessions(): Promise<number>

Startup adoption sweep: walks the whole trace tree once per boot and adopts every unmanaged Session (a Trace with no index row — legacy CLI-direct runs) as a client: "cli" row, so lists stay pure-SQLite afterwards. Enumerates <root>/<project>/agents/<agent>/ directories directly — legacy Traces can live under Projects the DB has never seen — and reuses the existing discovery/adoption path per Agent (mtime-gated TraceIndexService reconcile, then registration-time facts; adoption reads no file itself). Idempotent (insertOrIgnore), so re-running — e.g. after a hot swap re-assembles the business surface — only costs the gated reconcile. Returns the number of rows adopted.

@returnsPromise<number>

createSession

createSession(args: { projectId: string; agentId: string; modelId?: string; provider?: string; workspace?: string; thinkingLevel?: ThinkingLevelName; approvalMode?: ApprovalMode; sandbox?: Partial<SessionSandbox>; isAdmin?: boolean; source?: SessionSource; client?: "web" | "cli" | "org" | "api" | "workbench"; }): Promise<SessionInfo>

Create a Session: the model reference is a complete (provider, modelId) pair. Half a reference is a client error, never something to resolve — the missing half is never guessed, since a guessed provider would send an entry's credential to a vendor nobody named. Omitting both falls back to the Project's default reference (400 prompting to configure a model first if there is none). workspace is already validated by the route guard. The new Session is added to the active table (idle).

@paramargs{ projectId: string; agentId: string; modelId?: string; provider?: string; workspace?: string; thinkingLevel?: ThinkingLevelName; approvalMode?: ApprovalMode; sandbox?: Partial<SessionSandbox>; isAdmin?: boolean; source?: SessionSource; client?: "web" | "cli" | "org" | "api" | "workbench"; }
@returnsPromise<SessionInfo>

defaultSandbox

defaultSandbox(): SandboxSettings

The policy a new Session starts with: the server's Sandbox settings.

@returnsSandboxSettings

pickSandbox

pickSandbox(row: SessionRow, pick: Partial<SessionSandbox>, isAdmin: boolean): SandboxSettings

The policy a pick would give one Session, checked — the non-admin ceiling and what this server can enforce — and not written: a PATCH checks every field before it writes any.

@paramrowSessionRow
@parampickPartial<SessionSandbox>
@paramisAdminboolean
@returnsSandboxSettings

updateSandbox

updateSandbox(sessionId: string, policy: SandboxSettings): void

Stores one Session's policy (pickSandbox's): its next command runs under it.

@paramsessionIdstring
@parampolicySandboxSettings
@returnsvoid

latestTracePath

latestTracePath(row: SessionRow): Promise<string | undefined>

Absolute path of a Session's latest Trace file (the current context shard); undefined when no Trace exists. Costs a directory walk, so only the single-session GET includes it in the DTO (see SessionInfo.tracePath) — the web's /model switch hands it to the new session's [model_switch_from] block so the model can read the source history itself when it needs it.

@paramrowSessionRow
@returnsPromise<string | undefined>