Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(agent): add durable session turn runner with lease and persistence

Abdurrahman Fakhrulc3311fd04724
diff --git a/lib/agent/session-turn.test.ts b/lib/agent/session-turn.test.ts
new file mode 100644
index 00000000..74e19cbf
--- /dev/null
+++ b/lib/agent/session-turn.test.ts
@@ -0,0 +1,177 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { mkdtempSync, rmSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";
+
+const root = mkdtempSync(path.join(os.tmpdir(), "mso-session-turn-test-"));
+process.env.OS_AGENT_SESSIONS_DIR = path.join(root, "sessions");
+
+const mockHandoff = vi.hoisted(() => vi.fn());
+vi.mock("@/lib/a2a/local-session", () => ({
+ handoffOwnerLocalSession: mockHandoff,
+}));
+
+const { createAgentSession, getAgentSession } = await import("./session-store");
+const { clearAllSessionTurnLeasesForTest, runDurableSessionTurn } = await import("./session-turn");
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+beforeEach(() => {
+ clearAllSessionTurnLeasesForTest();
+ mockHandoff.mockReset();
+});
+
+const capabilities: CapabilityRuntime = {
+ list: () => [],
+ invoke: vi.fn(async () => ({ content: [] })),
+};
+
+describe("durable session turn runner", () => {
+ it("persists history and an audit event for a completed turn", async () => {
+ const session = await createAgentSession("principal:alice", "cli", {
+ title: "turn-test",
+ history: [{ role: "user", text: "initial greeting" }],
+ });
+
+ mockHandoff.mockResolvedValueOnce({
+ session,
+ task: {
+ artifacts: [{ parts: [{ text: "assistant response" }] }],
+ rounds: 2,
+ toolCalls: [{ name: "test_tool", ok: true }],
+ },
+ });
+
+ const result = await runDurableSessionTurn({
+ principal: "principal:alice",
+ sessionRef: session.id,
+ objective: "perform bounded turn",
+ capabilities,
+ authority: { principal: "principal:alice", scope: "exec", workflowId: "wf-123" },
+ });
+
+ expect(result).toEqual({
+ sessionRef: session.id,
+ rounds: 2,
+ toolCalls: [{ name: "test_tool", ok: true }],
+ text: "assistant response",
+ });
+
+ expect(mockHandoff).toHaveBeenCalledWith(
+ "principal:alice",
+ session.id,
+ "perform bounded turn",
+ capabilities,
+ undefined,
+ { authority: { principal: "principal:alice", scope: "exec", workflowId: "wf-123" }, workflowId: "wf-123" },
+ );
+
+ const updated = await getAgentSession("principal:alice", session.id);
+ expect(updated?.history).toEqual([
+ { role: "user", text: "initial greeting" },
+ { role: "user", text: "perform bounded turn" },
+ { role: "assistant", text: "assistant response" },
+ ]);
+ expect(updated?.events).toHaveLength(2);
+ expect(updated?.events.at(-1)).toMatchObject({
+ kind: "workflow",
+ tool: "agent_turn",
+ state: "completed",
+ workflowId: "wf-123",
+ detail: "perform bounded turn",
+ });
+ });
+
+ it("fails closed without modifying history for unavailable or unauthorized sessions", async () => {
+ const session = await createAgentSession("principal:alice", "cli", {
+ title: "auth-test",
+ history: [{ role: "user", text: "secret data" }],
+ });
+
+ await expect(
+ runDurableSessionTurn({
+ principal: "principal:alice",
+ sessionRef: "non-existent-session-id",
+ objective: "test",
+ capabilities,
+ }),
+ ).rejects.toThrow(/session_not_found/);
+
+ await expect(
+ runDurableSessionTurn({
+ principal: "principal:bob",
+ sessionRef: session.id,
+ objective: "unauthorized access",
+ capabilities,
+ }),
+ ).rejects.toThrow(/session_not_found/);
+
+ expect(mockHandoff).not.toHaveBeenCalled();
+
+ const record = await getAgentSession("principal:alice", session.id);
+ expect(record?.history).toEqual([{ role: "user", text: "secret data" }]);
+ expect(record?.events).toHaveLength(1);
+ expect(record?.events[0].kind).toBe("created");
+ });
+
+ it("prevents interleaving writes when two turns execute concurrently on the same session", async () => {
+ const session = await createAgentSession("principal:alice", "cli", {
+ title: "lease-test",
+ history: [{ role: "user", text: "baseline" }],
+ });
+
+ let resolveTurn1!: (value: unknown) => void;
+ const turn1Pending = new Promise((resolve) => {
+ resolveTurn1 = resolve;
+ });
+ mockHandoff.mockImplementationOnce(() => turn1Pending);
+
+ const turn1Promise = runDurableSessionTurn({
+ principal: "principal:alice",
+ sessionRef: session.id,
+ objective: "turn 1 objective",
+ capabilities,
+ });
+
+ const turn2Promise = runDurableSessionTurn({
+ principal: "principal:alice",
+ sessionRef: session.id,
+ objective: "turn 2 objective",
+ capabilities,
+ });
+
+ await expect(turn2Promise).rejects.toThrow(/already in progress/);
+
+ resolveTurn1({
+ session,
+ task: { artifacts: [{ parts: [{ text: "turn 1 result" }] }] },
+ });
+ const turn1Result = await turn1Promise;
+ expect(turn1Result.text).toBe("turn 1 result");
+
+ const sessionAfterTurn1 = await getAgentSession("principal:alice", session.id);
+ expect(sessionAfterTurn1?.history).toEqual([
+ { role: "user", text: "baseline" },
+ { role: "user", text: "turn 1 objective" },
+ { role: "assistant", text: "turn 1 result" },
+ ]);
+ expect(sessionAfterTurn1?.events).toHaveLength(2);
+
+ mockHandoff.mockResolvedValueOnce({
+ session,
+ task: { artifacts: [{ parts: [{ text: "turn 3 result" }] }] },
+ });
+ const turn3Result = await runDurableSessionTurn({
+ principal: "principal:alice",
+ sessionRef: session.id,
+ objective: "turn 3 objective",
+ capabilities,
+ });
+ expect(turn3Result.text).toBe("turn 3 result");
+
+ const sessionAfterTurn3 = await getAgentSession("principal:alice", session.id);
+ expect(sessionAfterTurn3?.history).toHaveLength(5);
+ expect(sessionAfterTurn3?.events).toHaveLength(3);
+ });
+});
diff --git a/lib/agent/session-turn.ts b/lib/agent/session-turn.ts
new file mode 100644
index 00000000..369b97e6
--- /dev/null
+++ b/lib/agent/session-turn.ts
@@ -0,0 +1,168 @@
+import { randomUUID } from "node:crypto";
+import type { CapabilityRunContext } from "@/lib/capabilities/tool";
+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";
+import { resolveAgentSessionRef } from "./session-query";
+import {
+ appendAgentSessionEvent,
+ getAgentSession,
+ updateAgentSessionHistory,
+} from "./session-store";
+import { handoffOwnerLocalSession } from "@/lib/a2a/local-session";
+
+const DEFAULT_EXECUTION_LEASE_MS = 15 * 60_000;
+
+interface SessionTurnLease {
+ claimedBy: string;
+ leaseUntil: number;
+}
+
+const activeTurnLeases = new Map<string, SessionTurnLease>();
+
+export function acquireSessionTurnLease(
+ sessionId: string,
+ claimedBy: string,
+ leaseMs = DEFAULT_EXECUTION_LEASE_MS,
+ now = Date.now(),
+): boolean {
+ const existing = activeTurnLeases.get(sessionId);
+ if (existing && existing.leaseUntil > now) {
+ return false;
+ }
+ activeTurnLeases.set(sessionId, {
+ claimedBy,
+ leaseUntil: now + leaseMs,
+ });
+ return true;
+}
+
+export function releaseSessionTurnLease(
+ sessionId: string,
+ claimedBy?: string,
+): void {
+ const existing = activeTurnLeases.get(sessionId);
+ if (!existing) return;
+ if (!claimedBy || existing.claimedBy === claimedBy) {
+ activeTurnLeases.delete(sessionId);
+ }
+}
+
+export function clearAllSessionTurnLeasesForTest(): void {
+ activeTurnLeases.clear();
+}
+
+function extractTaskText(task: unknown): string {
+ if (!task || typeof task !== "object") return "";
+ const t = task as {
+ artifacts?: Array<{ parts?: Array<{ text?: string }> }>;
+ status?: { message?: { parts?: Array<{ text?: string }> }; error?: string };
+ output?: string;
+ error?: string;
+ };
+ const artifactText = t.artifacts?.flatMap((a) => a.parts ?? [])
+ .map((p) => typeof p.text === "string" ? p.text : "")
+ .filter(Boolean)
+ .join("\n")
+ .trim();
+ if (artifactText) return artifactText;
+ const statusText = t.status?.message?.parts
+ ?.map((p) => typeof p.text === "string" ? p.text : "")
+ .filter(Boolean)
+ .join("\n")
+ .trim();
+ if (statusText) return statusText;
+ if (typeof t.output === "string" && t.output.trim()) return t.output.trim();
+ if (typeof t.error === "string" && t.error.trim()) return t.error.trim();
+ if (typeof t.status?.error === "string" && t.status.error.trim()) return t.status.error.trim();
+ return "";
+}
+
+function extractRounds(turn: unknown): number {
+ if (!turn || typeof turn !== "object") return 1;
+ const t = turn as Record<string, unknown>;
+ const task = (t.task ?? {}) as Record<string, unknown>;
+ if (typeof task.rounds === "number") return task.rounds;
+ if (typeof t.rounds === "number") return t.rounds;
+ return 1;
+}
+
+function extractToolCalls(turn: unknown): Array<{ name: string; ok: boolean }> {
+ if (!turn || typeof turn !== "object") return [];
+ const t = turn as Record<string, unknown>;
+ const task = (t.task ?? {}) as Record<string, unknown>;
+ if (Array.isArray(task.toolCalls)) return task.toolCalls as Array<{ name: string; ok: boolean }>;
+ if (Array.isArray(t.toolCalls)) return t.toolCalls as Array<{ name: string; ok: boolean }>;
+ return [];
+}
+
+export interface RunDurableSessionTurnInput {
+ principal: string;
+ sessionRef: string;
+ objective: string;
+ capabilities?: CapabilityRuntime;
+ authority?: CapabilityRunContext;
+ persist?: boolean;
+}
+
+export interface DurableSessionTurnResult {
+ sessionRef: string;
+ rounds: number;
+ toolCalls: Array<{ name: string; ok: boolean }>;
+ text: string;
+}
+
+export async function runDurableSessionTurn(
+ input: RunDurableSessionTurnInput,
+): Promise<DurableSessionTurnResult> {
+ const { principal, sessionRef, objective, capabilities, authority, persist } = input;
+ if (!sessionRef || !sessionRef.trim()) throw new Error("sessionRef is required for durable agent turn");
+ if (!objective || !objective.trim()) throw new Error("agent turn requires objective");
+
+ const session = await resolveAgentSessionRef(principal, sessionRef.trim());
+ const claimant = `${principal}:${randomUUID()}`;
+ if (!acquireSessionTurnLease(session.id, claimant)) {
+ throw new Error(`session turn is already in progress for session ${session.id}`);
+ }
+
+ try {
+ const runtimeCaps: CapabilityRuntime = capabilities ?? { list: () => [], invoke: async () => ({ content: [] }) };
+ const turn = await handoffOwnerLocalSession(
+ principal,
+ session.id,
+ objective.trim(),
+ runtimeCaps,
+ undefined,
+ authority ? { authority, workflowId: authority.workflowId } : undefined,
+ );
+
+ const text = extractTaskText(turn.task);
+ const rounds = extractRounds(turn);
+ const toolCalls = extractToolCalls(turn);
+
+ if (persist !== false) {
+ const fresh = await getAgentSession(principal, session.id);
+ const existingHistory = Array.isArray(fresh?.history) ? fresh.history : [];
+ const updatedHistory = [
+ ...existingHistory,
+ { role: "user", text: objective.trim() },
+ { role: "assistant", text },
+ ];
+ await updateAgentSessionHistory(principal, session.id, updatedHistory);
+ await appendAgentSessionEvent(principal, session.id, {
+ kind: "workflow",
+ tool: "agent_turn",
+ state: "completed",
+ ...(authority?.workflowId ? { workflowId: authority.workflowId } : {}),
+ detail: objective.trim().slice(0, 500),
+ });
+ }
+
+ return {
+ sessionRef,
+ rounds,
+ toolCalls,
+ text,
+ };
+ } finally {
+ releaseSessionTurnLease(session.id, claimant);
+ }
+}