From cfeb93029c2ae48a4b6930bd46284dd0616066e0 Mon Sep 17 00:00:00 2001 From: blockmandev <194144408+blockmandev@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:51:33 -0600 Subject: [PATCH] sdk: list kept sessions typed, here or in every workspace (refs #21) session/list was wrapped only as raw objects for the session's own workspace, though incode answers for every workspace when no cwd is given. Session.sessions() / sessions() return SessionInfo (session id, cwd, title, updated at), newest first, with all_workspaces / allWorkspaces for the whole list; list_sessions / listSessions stay as they were. The fake now answers session/list as src/acp_agent does. --- sdk/python/incode_sdk/__init__.py | 3 +- sdk/python/incode_sdk/session.py | 52 +++++++++++++++++++++++++++-- sdk/python/tests/test_session.py | 12 +++++++ sdk/testing/fake_incode.py | 19 +++++++++++ sdk/typescript/src/index.ts | 9 ++++- sdk/typescript/src/session.ts | 40 +++++++++++++++++++++- sdk/typescript/test/session.test.ts | 18 ++++++++++ 7 files changed, 148 insertions(+), 5 deletions(-) diff --git a/sdk/python/incode_sdk/__init__.py b/sdk/python/incode_sdk/__init__.py index f35a377..cd0f7eb 100644 --- a/sdk/python/incode_sdk/__init__.py +++ b/sdk/python/incode_sdk/__init__.py @@ -30,7 +30,7 @@ WriteFileRequest, ) from .fs import FsAccessDenied, FsError, WorkspaceFS # noqa: E402 -from .session import PromptStream, Session, allow_all, reject_all # noqa: E402 +from .session import PromptStream, Session, SessionInfo, allow_all, reject_all # noqa: E402 from .task import TaskEvent, TaskResult, TaskStream, TaskUsage, run_task, stream_task # noqa: E402 __all__ = [ @@ -42,6 +42,7 @@ "TaskResult", "TaskUsage", "Session", + "SessionInfo", "PromptStream", "allow_all", "reject_all", diff --git a/sdk/python/incode_sdk/session.py b/sdk/python/incode_sdk/session.py index dc2a5bc..d0f2348 100644 --- a/sdk/python/incode_sdk/session.py +++ b/sdk/python/incode_sdk/session.py @@ -32,9 +32,46 @@ ) from .fs import INTERNAL_ERROR, INVALID_PARAMS, RESOURCE_NOT_FOUND, FsError, WorkspaceFS -__all__ = ["Session", "PromptStream", "reject_all", "allow_all", "PROTOCOL_VERSION"] +__all__ = ["Session", "PromptStream", "SessionInfo", "reject_all", "allow_all", "PROTOCOL_VERSION"] PROTOCOL_VERSION = 1 + + +class SessionInfo: + """One session incode kept, as ``session/list`` names it (src/acp_agent + ``history::list_in``): ``session_id`` to pass to ``Session.load``, the + workspace it ran in (``cwd``), its ``title`` (its first line) and when it + was last ``updated_at`` (RFC 3339), either of those ``None`` when incode + did not say. ``raw`` is the object as sent.""" + + __slots__ = ("session_id", "cwd", "title", "updated_at", "raw") + + def __init__(self, session_id: str, cwd: str, title: Optional[str], updated_at: Optional[str], raw: Dict[str, Any]): + self.session_id = session_id + self.cwd = cwd + self.title = title + self.updated_at = updated_at + self.raw = raw + + @classmethod + def from_json(cls, data: Mapping[str, Any]) -> "SessionInfo": + title = data.get("title") + updated = data.get("updatedAt") + return cls( + session_id=str(data.get("sessionId") or ""), + cwd=str(data.get("cwd") or ""), + title=title if isinstance(title, str) else None, + updated_at=updated if isinstance(updated, str) else None, + raw=dict(data), + ) + + def __repr__(self) -> str: + return "SessionInfo(session_id=%r, cwd=%r, title=%r, updated_at=%r)" % ( + self.session_id, + self.cwd, + self.title, + self.updated_at, + ) METHOD_NOT_FOUND = -32601 STDERR_TAIL_BYTES = 64 * 1024 @@ -462,9 +499,20 @@ def set_config_option(self, config_id: str, value: str) -> List[Dict[str, Any]]: return self.config_options def list_sessions(self) -> List[Dict[str, Any]]: - """``session/list`` for this workspace.""" + """``session/list`` for this workspace, as incode answered it.""" return list(self.request("session/list", {"cwd": self.workspace}).get("sessions") or []) + def sessions(self, all_workspaces: bool = False) -> List["SessionInfo"]: + """The sessions incode has kept, as :class:`SessionInfo`: this + workspace's, or with ``all_workspaces`` every workspace an ACP session + was recorded in. Most recently updated first. A session listed here + can be reopened with ``Session.load``.""" + params: Dict[str, Any] = {} if all_workspaces else {"cwd": self.workspace} + listed = self.request("session/list", params).get("sessions") or [] + infos = [SessionInfo.from_json(item) for item in listed if isinstance(item, dict)] + infos.sort(key=lambda info: info.updated_at or "", reverse=True) + return infos + # ------------------------------------------------------------ reader side def _read_stdout(self) -> None: diff --git a/sdk/python/tests/test_session.py b/sdk/python/tests/test_session.py index 9897d97..8d90c8a 100644 --- a/sdk/python/tests/test_session.py +++ b/sdk/python/tests/test_session.py @@ -18,6 +18,7 @@ Plan, PromptResult, Session, + SessionInfo, ThoughtChunk, ToolCall, ToolCallUpdate, @@ -116,6 +117,17 @@ def test_load_replays_history(self): with self.assertRaises(AcpError): self.session(load_session_id="no-such").start() + def test_sessions_lists_this_workspace_newest_first_or_every_workspace(self): + with self.session() as s: + mine = s.sessions() + self.assertEqual([i.session_id for i in mine], ["fake-session-1", "kept-session"]) + self.assertTrue(all(isinstance(i, SessionInfo) and i.cwd == self.ws for i in mine)) + self.assertEqual(mine[1].title, "an earlier session") + self.assertEqual(mine[0].updated_at, "2026-10-22T12:00:00Z") + everywhere = s.sessions(all_workspaces=True) + self.assertEqual([i.session_id for i in everywhere], ["fake-session-1"]) + self.assertEqual(len(s.list_sessions()), 2, "the raw form stays as it was") + class PromptTest(SessionTestBase): def test_prompt_streams_typed_events_then_the_result(self): diff --git a/sdk/testing/fake_incode.py b/sdk/testing/fake_incode.py index 358652d..183011e 100755 --- a/sdk/testing/fake_incode.py +++ b/sdk/testing/fake_incode.py @@ -145,6 +145,7 @@ def __init__(self): self.waiting = {} # request id -> queue for the client's answer self.waiting_lock = threading.Lock() self.sessions = {} # id -> dict(mode, agent, role, cancel Event, busy) + self.cwds = {} # id of a session/new -> its cwd, for session/list # -- output def write_raw(self, text): @@ -280,6 +281,7 @@ def m_session_new(self, rid, params): return sid = "fake-session-%d" % (len(self.sessions) + 1) s = self.open_session(sid, START_MODE) + self.cwds[sid] = params["cwd"] self.respond(rid, self.session_answer(sid, s)) self.update( sid, @@ -289,6 +291,23 @@ def m_session_new(self, rid, params): }, ) + def m_session_list(self, rid, params): + """``session/list``, as src/acp_agent does: the sessions kept in + ``cwd``, or with none named every session this process opened. The + loadable ``kept-session`` is kept in whichever ``cwd`` is asked about.""" + cwd = params.get("cwd") + sessions = [ + {"sessionId": sid, "cwd": where, "title": "fake work", "updatedAt": "2026-10-22T12:00:00Z"} + for sid, where in self.cwds.items() + if cwd is None or where == cwd + ] + if cwd is not None: + sessions.insert( + 0, + {"sessionId": "kept-session", "cwd": cwd, "title": "an earlier session", "updatedAt": "2026-10-21T09:00:00Z"}, + ) + self.respond(rid, {"sessions": sessions}) + def m_session_load(self, rid, params): if not self.check_cwd(rid, params): return diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index c200b1e..f34807f 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -33,4 +33,11 @@ export type { } from "./events.js"; export { FsAccessDenied, FsError, INTERNAL_ERROR, INVALID_PARAMS, RESOURCE_NOT_FOUND, WorkspaceFs, realPath } from "./fs.js"; export { allowAll, PROTOCOL_VERSION, PromptStream, rejectAll, Session } from "./session.js"; -export type { PermissionHandler, PromptOptions, ReadFileHandler, SessionOptions, WriteFileHandler } from "./session.js"; +export type { + PermissionHandler, + PromptOptions, + ReadFileHandler, + SessionInfo, + SessionOptions, + WriteFileHandler, +} from "./session.js"; diff --git a/sdk/typescript/src/session.ts b/sdk/typescript/src/session.ts index 392db8f..620da76 100644 --- a/sdk/typescript/src/session.ts +++ b/sdk/typescript/src/session.ts @@ -32,6 +32,32 @@ export type PermissionHandler = (request: PermissionRequest) => MaybePromise MaybePromise; export type WriteFileHandler = (request: WriteFileRequest) => MaybePromise; +/** + * One session incode kept, as `session/list` names it (src/acp_agent + * `history::list_in`): `sessionId` to pass as `loadSessionId`, the workspace it + * ran in (`cwd`), its `title` (its first line) and when it was last updated + * (`updatedAt`, RFC 3339), either `null` when incode did not say. + */ +export interface SessionInfo { + sessionId: string; + cwd: string; + title: string | null; + updatedAt: string | null; + /** The object as sent. */ + raw: Json; +} + +function sessionInfoOf(data: Json): SessionInfo { + const text = (v: unknown): string | null => (typeof v === "string" ? v : null); + return { + sessionId: text(data["sessionId"]) ?? "", + cwd: text(data["cwd"]) ?? "", + title: text(data["title"]), + updatedAt: text(data["updatedAt"]), + raw: data, + }; +} + /** The default permission handler: pick the reject option (`cancelled` if there is none). */ export const rejectAll: PermissionHandler = (request) => request.reject(); /** Allow every call once. Only for trusted, sandboxed work. */ @@ -497,11 +523,23 @@ export class Session { return this.configOptions; } - /** `session/list` for this workspace. */ + /** `session/list` for this workspace, as incode answered it. */ async listSessions(): Promise { return asArray((await this.request("session/list", { cwd: this.workspace }))["sessions"]).map(asObject); } + /** + * The sessions incode has kept, as `SessionInfo`: this workspace's, or with + * `allWorkspaces` every workspace an ACP session was recorded in. Most + * recently updated first. A session listed here can be reopened with + * `loadSessionId`. + */ + async sessions(options: { allWorkspaces?: boolean } = {}): Promise { + const params = options.allWorkspaces ? {} : { cwd: this.workspace }; + const listed = asArray((await this.request("session/list", params))["sessions"]).map(asObject); + return listed.map(sessionInfoOf).sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? "")); + } + // ------------------------------------------------------------ reader side private protocolError(line: string, error: Error): void { diff --git a/sdk/typescript/test/session.test.ts b/sdk/typescript/test/session.test.ts index b4a0629..bf40851 100644 --- a/sdk/typescript/test/session.test.ts +++ b/sdk/typescript/test/session.test.ts @@ -114,6 +114,24 @@ describe("start", () => { ); await assert.rejects(session({ loadSessionId: "no-such" }).start(), AcpError); }); + + it("lists this workspace's sessions newest first, or every workspace's", async () => { + const s = await started(); + const mine = await s.sessions(); + assert.deepEqual( + mine.map((i) => i.sessionId), + ["fake-session-1", "kept-session"], + ); + assert.ok(mine.every((i) => i.cwd === s.workspace)); + assert.equal(mine[1]?.title, "an earlier session"); + assert.equal(mine[0]?.updatedAt, "2026-10-22T12:00:00Z"); + const everywhere = await s.sessions({ allWorkspaces: true }); + assert.deepEqual( + everywhere.map((i) => i.sessionId), + ["fake-session-1"], + ); + assert.equal((await s.listSessions()).length, 2, "the raw form stays as it was"); + }); }); describe("prompt", () => {