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
3 changes: 2 additions & 1 deletion sdk/python/incode_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__ = [
Expand All @@ -42,6 +42,7 @@
"TaskResult",
"TaskUsage",
"Session",
"SessionInfo",
"PromptStream",
"allow_all",
"reject_all",
Expand Down
52 changes: 50 additions & 2 deletions sdk/python/incode_sdk/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
12 changes: 12 additions & 0 deletions sdk/python/tests/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
Plan,
PromptResult,
Session,
SessionInfo,
ThoughtChunk,
ToolCall,
ToolCallUpdate,
Expand Down Expand Up @@ -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):
Expand Down
19 changes: 19 additions & 0 deletions sdk/testing/fake_incode.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down
9 changes: 8 additions & 1 deletion sdk/typescript/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
40 changes: 39 additions & 1 deletion sdk/typescript/src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,32 @@ export type PermissionHandler = (request: PermissionRequest) => MaybePromise<Per
export type ReadFileHandler = (request: ReadFileRequest) => MaybePromise<string>;
export type WriteFileHandler = (request: WriteFileRequest) => MaybePromise<void>;

/**
* 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. */
Expand Down Expand Up @@ -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<Json[]> {
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<SessionInfo[]> {
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 {
Expand Down
18 changes: 18 additions & 0 deletions sdk/typescript/test/session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
Loading