@qlairoslabs/acp-client 0.10.2 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CONSUMER_GUIDE.md +177 -5
  2. package/package.json +1 -1
  3. package/src/agent/adoption/checkpoint-floor.ts +47 -0
  4. package/src/agent/adoption/config.ts +57 -0
  5. package/src/agent/adoption/index.ts +10 -0
  6. package/src/agent/adoption/provider-session-delete.ts +27 -0
  7. package/src/agent/adoption/provider-sessions.ts +73 -0
  8. package/src/agent/adoption/recap.ts +15 -0
  9. package/src/agent/adoption/replay.ts +98 -0
  10. package/src/agent/config.ts +182 -0
  11. package/src/agent/conversation-manager.ts +1048 -0
  12. package/src/agent/manager-settings.ts +46 -0
  13. package/src/agent/persisted-lifecycle.ts +309 -0
  14. package/src/agent/persistence-policy/index.ts +8 -0
  15. package/src/agent/persistence-policy/resolver.ts +118 -0
  16. package/src/agent/persistence-policy/types.ts +50 -0
  17. package/src/agent/record-capture.ts +243 -0
  18. package/src/agent-conversation-contracts.ts +2 -0
  19. package/src/agent-conversation-errors.ts +24 -0
  20. package/src/agent-conversation-owner.ts +2 -0
  21. package/src/agent-session.ts +117 -3
  22. package/src/agent.ts +63 -1233
  23. package/src/audit/config.ts +29 -0
  24. package/src/audit/index.ts +1 -0
  25. package/src/checkpointing/contracts.ts +30 -3
  26. package/src/checkpointing/persistence/sqlite-repository.ts +49 -8
  27. package/src/checkpointing/recovery.ts +4 -2
  28. package/src/checkpointing/strategy.ts +36 -7
  29. package/src/client.ts +22 -1
  30. package/src/controller.ts +3 -0
  31. package/src/identity/checkpoint-backed.ts +2 -2
  32. package/src/index.ts +14 -0
  33. package/src/internal-inference/contracts.ts +23 -0
  34. package/src/internal-inference/coordination/manager.ts +22 -8
  35. package/src/persistence/backend.ts +17 -0
  36. package/src/persistence/sqlite-backend.ts +30 -4
  37. package/src/persistence/sqlite-provider-sessions.ts +35 -0
  38. package/src/persistence/sqlite-schema.ts +74 -7
  39. package/src/transport/acp-transport.ts +3 -0
package/CONSUMER_GUIDE.md CHANGED
@@ -920,12 +920,75 @@ deprecated `result.text` property is only a compatibility projection and inserts
920
920
  line between messages. `formatResponseMessages()` makes any deliberate flattening policy
921
921
  consumer-owned.
922
922
 
923
+ ## Choose what each conversation persists
924
+
925
+ One Agent has one set of persistence defaults (`capture`, the audit log's `capture`, `meteringPersistence`), and every
926
+ conversation it owns uses them. A consumer that hosts different kinds of conversations in one Agent (user chats,
927
+ agent-to-agent channels, adopted sessions) can persist less for some of them with a **resolver**:
928
+
929
+ ```ts
930
+ const agent = await Agent.open({
931
+ persistence: { kind: "sqlite", path },
932
+ adapters,
933
+ capture: { message: "none" }, // default: keep no message content
934
+ checkpointing: {},
935
+ auditLog: { directory, capture: { message: "none" } },
936
+ conversationPersistence: ({ agentConversationId, title, metadata, participants, adopted }) =>
937
+ isUserChat(agentConversationId)
938
+ ? {
939
+ capture: { message: "content" }, // keep content, and so recovery
940
+ auditLog: false, // stay out of the audit stream
941
+ meteringRecords: "none", // no detailed metering history
942
+ }
943
+ : undefined, // everything else: the Agent's defaults
944
+ });
945
+ ```
946
+
947
+ The resolver returns an **override** over the Agent's defaults, or `undefined`: keys it sets replace the Agent's value
948
+ (`protocol` counts as one key, so its level and method filters are replaced together), keys it omits follow the Agent,
949
+ and `undefined`, `{}` or `{ capture: {} }` mean the Agent's defaults. The library never infers a policy: what a
950
+ conversation *is* stays the consumer's business, and the context carries only what the library knows (id,
951
+ participants, title, metadata, and whether it was created by adopting a provider session).
952
+
953
+ | key | what it changes |
954
+ |---|---|
955
+ | `capture` | The canonical record kinds stored, and at what level (`none`, `metadata`, `content`, `raw`). |
956
+ | `auditLog` | `false`: no audit entry about the conversation, and none caused by its records (`identity` entries, internal-inference entries). `{ capture }`: what its audit entries capture. Agent-scope kinds (`agent_lifecycle`, `identity`, `internal_inference`) cannot be tuned per conversation. Requires the Agent to have an audit log (`false` is accepted anyway). |
957
+ | `meteringRecords` | Retention of the detailed metering records of the conversation, including those of its internal inferences: `"all"`, `"none"` or `{ retain: n }`. The bounded metering state is always kept. |
958
+
959
+ **Contract.** The resolver is synchronous, free of side effects, and stable for a given conversation. It is called when a
960
+ conversation starts (`create()` and `open()`), once, and the result is held for the life of the live conversation: a
961
+ change in the resolver's answers applies the next time it is opened. It is also called, just before the write, for
962
+ writes about a conversation that is not live (a checkpoint finishing, an audit observation). A resolver that throws, or
963
+ returns something invalid, is a caller mistake: the start rejects with that error and writes no row, no error record and
964
+ no provider session. A background write whose policy cannot be resolved fails that write; it is never done under the
965
+ Agent's defaults, which could record more than the consumer allowed.
966
+
967
+ **What it covers.** Every write made for the conversation: its records and audit entries, the error records of a failed
968
+ start, load or recovery, the checkpoint completion record (stored at the conversation's `native_action` level, and audited as
969
+ the conversation says), and the detailed metering records of its inferences. Always persisted, whatever the policy: the
970
+ conversation row, provider-session mappings, the bounded metering state, identity delivery cursors, internal-inference jobs.
971
+
972
+ **Audit fingerprints.** Each audit entry carries the fingerprint of the policy that projected it: for a conversation with
973
+ its own audit capture, that conversation's; for everything else, the Agent's. `agent.audit.status().captureFingerprint` is
974
+ always the Agent's own.
975
+
976
+ **Checkpointing.** Checkpoints summarize stored messages, so a conversation that stores none (`message: "none"`) is never
977
+ checkpointed, `checkpointing.request()` for it does nothing, a lost provider session throws instead of recovering, and it
978
+ contributes nothing to other conversations' identity. An Agent may therefore enable checkpointing with a default of
979
+ `message: "none"` and let the conversations that need recovery override to `content`. `message: "metadata"` is refused
980
+ while checkpointing is enabled, at the Agent and per conversation.
981
+
982
+ **Limits.** A policy is not retroactive: records and audit entries already written stay. A conversation still *receives*
983
+ identity from its siblings (controlling that needs a per-conversation identity switch, not provided). One Agent is one
984
+ SQLite file and one audit destination; different storage locations need a second Agent.
985
+
923
986
  ## Send a message while a turn is running
924
987
 
925
988
  A prompt sent while a turn runs waits. How it waits is its **delivery**:
926
989
 
927
- - `"queue"` (the default): it runs after the running turn ends, as its own turn.
928
- - `"steer"`: it is delivered at the next tool boundary. The library cancels the running turn once a
990
+ - `"queue"`: it runs after the running turn ends, as its own turn.
991
+ - `"steer"` (the default): it is delivered at the next tool boundary. The library cancels the running turn once a
929
992
  tool call has settled and nothing else is running, then sends the message, so the agent gets the
930
993
  information without losing the work it has done. If the turn ends first, the message is sent as the
931
994
  next prompt, so a message is never delivered later than the end of the turn. A text-only turn is not
@@ -944,13 +1007,13 @@ const answer = await note; // the turn that carried the message
944
1007
  `prompt()` and `promptFrom()` return a handle: the promise of that prompt's result, plus `id` and
945
1008
  `withdraw()`. A prompt that does not have to wait runs immediately and `delivery` has no effect.
946
1009
 
947
- Set the default for prompts that do not say, per Agent or per conversation. It is `"queue"` unless you
948
- change it:
1010
+ Set the default for prompts that do not say, per Agent or per conversation. It is `"steer"` unless you
1011
+ change it (before this was `"queue"`; set `busyDelivery: "queue"` to keep the old behaviour):
949
1012
 
950
1013
  ```ts
951
1014
  const agent = await Agent.open({
952
1015
  // ...
953
- conversationDefaults: { busyDelivery: "steer" },
1016
+ conversationDefaults: { busyDelivery: "queue" },
954
1017
  });
955
1018
  ```
956
1019
 
@@ -1019,6 +1082,115 @@ is its own. Measured with the `test11-steerTurn` smoke test:
1019
1082
  normally despite a late cancel is `completed`, and `endedBy` is absent.
1020
1083
  - Pending messages live in memory only. They are lost if the process stops, like queued prompts.
1021
1084
 
1085
+ ## Adopt a session the provider already holds
1086
+
1087
+ A harness may hold sessions this library did not create (made in its own UI, by another client, before the
1088
+ conversation existed here). `agent.conversations.create({ adopt })` brings one in as a conversation of the Agent: it
1089
+ is created around the session and loaded with `session/load` instead of starting a new provider thread.
1090
+
1091
+ ```ts
1092
+ // Which sessions does the provider hold, and which are already owned by a conversation?
1093
+ const sessions = await agent.conversations.listProviderSessions({ limit: 20 });
1094
+ for (const session of sessions) console.log(session.providerSessionId, session.title, session.adoptedBy);
1095
+
1096
+ const conversation = await agent.conversations.create({
1097
+ adopt: { providerSessionId: sessions[0].providerSessionId },
1098
+ });
1099
+ await conversation.prompt("Where were we?"); // continues the provider's own session
1100
+ ```
1101
+
1102
+ `listProviderSessions({ adapterId?, cwd?, limit? })` starts the harness for the call and asks it (`session/list`, so
1103
+ the provider decides the order and which sessions it reports). It throws `ProviderSessionListUnsupportedError` if the
1104
+ agent does not advertise `session/list`.
1105
+
1106
+ ### What adopting stores
1107
+
1108
+ The provider keeps the history; adoption does not copy it unless asked.
1109
+
1110
+ | option | effect |
1111
+ |---|---|
1112
+ | `importHistory: true` / `{ last: n }` | Also store the history the load replays: messages, tool calls and thoughts, through the same capture policy as a live turn (a kind the conversation does not capture is not stored). A turn starts at each user message. Stored records are marked `imported: true` and carry the time of the import, since a replay has no timestamps. |
1113
+ | `recap: true` | Ask the model to summarize its own history, as a hidden turn on the adopted session, and store the answer as an assistant message (`origin: "adoption_recap"` in its metadata) ahead of the imported turns. It is not shown as a user message, and `create()` returns once it is answered. The model decides how to compress a long history. |
1114
+
1115
+ Defaults: when the Agent has an identity runtime that shares conversations, `recap` is on and the last two turns are
1116
+ imported; otherwise nothing beyond what happens from now on is stored. A recap lets the Agent's *other* conversations learn
1117
+ about this one: identity delivers stored messages to them. A recap that fails is recorded as an error
1118
+ (`adoption_recap_failed`, retryable) and the conversation still works, but is not in the Agent's memory.
1119
+
1120
+ Adopting needs the conversation to capture messages at `content` or `raw` (otherwise it would join the Agent's memory
1121
+ empty); a conversation that must store nothing is driven with `acp-client` instead. A conversation persistence resolver can
1122
+ tell an adopted conversation by `adopted: true` in its context and choose what it stores.
1123
+
1124
+ ### Failures and ownership
1125
+
1126
+ - **One owner.** A provider session can belong to one conversation. Adopting one that another conversation owns (or has
1127
+ asked to adopt) throws `ProviderSessionInUseError`, whose `ownedBy` names it, so a UI can open that one instead. The check
1128
+ and the new row are one transaction. Deleting the conversation frees the session. A persistence backend that cannot tell
1129
+ who owns a session cannot adopt one.
1130
+ - **The session cannot be loaded** (it no longer exists, the agent does not support `session/load`, degraded mode): a
1131
+ `ProviderSessionError` is thrown and the failure is recorded, and the conversation row **stays**. Opening that conversation
1132
+ later retries the load of the session it asked for; it never starts a new session in its place. Retrying records the
1133
+ session on success but does not repeat the history import or the recap.
1134
+ - **After a restart** an adopted conversation opens like any other: by loading its recorded provider session.
1135
+
1136
+ ### Where checkpointing starts
1137
+
1138
+ Summarizing stored messages is a prompt, and a long history does not fit one (Codex refuses a message past 1,048,576
1139
+ characters), so an adopted conversation's checkpoints never look at the history that came before its adoption. When the
1140
+ conversation checkpoints, adoption places a **floor**: a checkpoint covering everything up to 50 messages before the end of
1141
+ what is stored (or the recap, when the history is shorter than that).
1142
+
1143
+ - With a recap, the floor's summary *is* the recap. It stands for the whole provider history, imported or not, and a
1144
+ recovery seeds the recap plus the messages after the floor.
1145
+ - Without a recap, the floor is a baseline with no summary: a recovery seeds only the messages after it, and identity
1146
+ delivers the stored messages as it would without a checkpoint.
1147
+ - A conversation with no recap and 50 messages or fewer stored gets no floor; its first scheduled checkpoint summarizes them.
1148
+ - Every stored message stays readable (listing, pagination, search); only summarizing starts after the floor. Checkpoints that
1149
+ follow chain from it.
1150
+ - The checkpoint schedule (responses 1, 5, 10, ...) counts responses after what the adoption stored, as for a new conversation.
1151
+ - A checkpoint whose records do not fit one prompt (700,000 characters) fails with `checkpoint_source_too_large` and is not
1152
+ retried. Only a conversation that stores a very long run of messages between two checkpoints can reach it.
1153
+
1154
+ ### Limits to know about
1155
+
1156
+ - Replays differ by harness (measured on Codex and OpenCode with `smoke-tests/session-replay-probe`): both send message
1157
+ boundaries, tool calls and, for OpenCode, thoughts; neither sends timestamps or usage. Codex replays the tool call of a turn
1158
+ that was cancelled mid-tool after the next turn's user message, and it is imported where it arrives.
1159
+ - The recap is a hidden turn on the adopted session itself, so the provider's own history then contains the question and the
1160
+ answer. The model is asked not to use tools; ACP gives no way to forbid them for one turn. A later adoption of the same
1161
+ session does not import that question or its answer as turns.
1162
+ - With `importHistory: true`, every imported message is also delivered to the Agent's other conversations (within identity's
1163
+ budget): prefer the default tail with a recap for long sessions.
1164
+ - The first prompt after an adoption runs on a thread whose usage counters did not start at zero, so its metering is
1165
+ attributable only after a baseline.
1166
+
1167
+ ## Clear a transcript, delete a conversation
1168
+
1169
+ ```ts
1170
+ // Remove what is stored, keep the conversation (its title, participants and provider session).
1171
+ await agent.conversations.clearTranscript(id); // { recordsDeleted, checkpointsDeleted: 0 }
1172
+ await agent.conversations.clearTranscript(id, { checkpoints: true }); // also its recovery checkpoints
1173
+
1174
+ // Delete the conversation; optionally ask the provider to delete its session too.
1175
+ const { providerDeleted } = await agent.conversations.delete(id, { providerSession: "best-effort", checkpoints: true });
1176
+ // providerDeleted: true | "unsupported" | false
1177
+ ```
1178
+
1179
+ `clearTranscript` physically deletes every stored record of the conversation (messages, tool calls, and the rest). It
1180
+ refuses a conversation that is running an operation. Sequence numbers are not reused, so new records continue after the
1181
+ deleted ones. `delete` is a soft delete as before (the records stay, the conversation stops being listed, and a provider
1182
+ session it owned can be adopted again); a string second argument is still read as the deletion time.
1183
+
1184
+ Both are **local** deletions, not forgetting:
1185
+
1186
+ - The provider's own session is untouched unless you ask `delete` for `providerSession: "best-effort"`. That sends
1187
+ `session/delete`, which not every agent offers: Codex advertises it, OpenCode does not (`"unsupported"`). A failure is
1188
+ reported as `false` and does not undo the local deletion.
1189
+ - Recovery checkpoints summarize the records being deleted. They are kept unless `checkpoints: true`, so by default the Agent's
1190
+ other conversations can still receive a summary of cleared content.
1191
+ - Audit entries already written, content already delivered into other conversations, and identity state derived from the
1192
+ records are not removed. No event is published when records are deleted, so a UI has to refresh.
1193
+
1022
1194
  ## Observe state, context, and usage
1023
1195
 
1024
1196
  Read a snapshot first, then subscribe to changes:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.10.2",
3
+ "version": "0.11.1",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -0,0 +1,47 @@
1
+ import type { AgentConversationId } from "../../agent-ids.ts";
2
+ import { createConversationRecoveryCheckpointId } from "../../checkpointing/ids.ts";
3
+ import type { ConversationRecoveryCheckpointRepository } from "../../checkpointing/contracts.ts";
4
+
5
+ /** Messages left after the floor, so a recovery or a first checkpoint still sees the end of the history. */
6
+ export const DEFAULT_ADOPTION_TAIL_MESSAGES = 50;
7
+
8
+ export interface AdoptionRecapPlacement {
9
+ readonly summary: string;
10
+ /** Sequence of the stored recap message. */
11
+ readonly sequence: number;
12
+ }
13
+
14
+ /**
15
+ * Where checkpointing starts for an adopted conversation, so that nothing ever summarizes the history that
16
+ * came before it. Summarizing stored records is a prompt, and a long history does not fit one (a harness
17
+ * refuses a message past about a million characters), so the floor sits `tailMessages` before the end of
18
+ * what is stored: the recap's own message when that is later, so a conversation whose history is short
19
+ * keeps the recap as the first thing it recovers from.
20
+ *
21
+ * With a recap the checkpoint's summary is the recap, which covers the whole provider history; without one the
22
+ * checkpoint is a baseline with no summary, and recovery seeds only the messages after it. A conversation
23
+ * with no recap and no more than `tailMessages` stored messages has nothing to place a floor under, and gets
24
+ * none: its first scheduled checkpoint summarizes those few messages.
25
+ *
26
+ * The checkpoint schedule counts responses after the stored history, so an import does not use up the
27
+ * milestones a new conversation starts with.
28
+ */
29
+ export async function publishAdoptionFloor(
30
+ repository: ConversationRecoveryCheckpointRepository,
31
+ conversationId: AgentConversationId,
32
+ options: { readonly recap?: AdoptionRecapPlacement; readonly tailMessages?: number },
33
+ ): Promise<boolean> {
34
+ const tail = Math.max(0, options.tailMessages ?? DEFAULT_ADOPTION_TAIL_MESSAGES);
35
+ const lastSequence = await repository.latestMessageSequence(conversationId);
36
+ const floor = Math.max(options.recap?.sequence ?? 0, lastSequence - tail);
37
+ if (floor < 1) return false;
38
+ await repository.publish({
39
+ checkpointId: createConversationRecoveryCheckpointId(),
40
+ agentConversationId: conversationId,
41
+ coveredSequence: floor,
42
+ source: options.recap ? "adoption_recap" : "adoption_baseline",
43
+ summary: options.recap?.summary ?? "",
44
+ responsesCountedAfterSequence: lastSequence,
45
+ });
46
+ return true;
47
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Adopt an existing provider session as a new conversation: the conversation is created around the session
3
+ * and loaded with `session/load`, instead of starting a new provider thread.
4
+ */
5
+ export interface AdoptProviderSessionConfig {
6
+ /** The provider's id for the session to adopt (the `sessionId` `session/list` reports). */
7
+ readonly providerSessionId: string;
8
+ /**
9
+ * Also store the history the load replays, through the normal capture path (so a conversation that does
10
+ * not capture a kind stores none of it). `true` imports all of it; `{ last: n }` the last `n` turns, a turn
11
+ * starting at each user message. Default: the last `DEFAULT_RECAP_TAIL_TURNS` turns when a recap is made,
12
+ * otherwise `false` (the provider still holds the history, and only what happens from now on is stored).
13
+ */
14
+ readonly importHistory?: boolean | { readonly last: number };
15
+ /**
16
+ * Ask the model to summarize its own history, and store the answer as an assistant message (marked as a
17
+ * recap) ahead of the imported turns, so the Agent's other conversations learn about this one: identity
18
+ * delivers stored messages to them. The question is a hidden turn on the adopted session: it is not shown
19
+ * in the conversation, and `create()` returns once it has been answered. The model decides how to compress
20
+ * a long history; the library never summarizes one itself. Default: `true` when the Agent has an identity
21
+ * runtime that shares conversations, otherwise `false`. A failed recap is recorded as an error and the
22
+ * conversation stays usable, but is not in the Agent's memory.
23
+ */
24
+ readonly recap?: boolean;
25
+ }
26
+
27
+ /** Turns stored after a recap when the consumer does not say how much history to import. */
28
+ export const DEFAULT_RECAP_TAIL_TURNS = 2;
29
+
30
+ export interface NormalizedAdoption {
31
+ readonly providerSessionId: string;
32
+ /** `false`, or how much of the replay to store (`last` absent means all of it). */
33
+ readonly importHistory: false | { readonly last?: number };
34
+ readonly recap: boolean;
35
+ }
36
+
37
+ export function normalizeAdoption(
38
+ config: AdoptProviderSessionConfig,
39
+ defaults: { readonly recap: boolean } = { recap: false },
40
+ ): NormalizedAdoption {
41
+ if (config === null || typeof config !== "object") throw new Error("adopt must be an object");
42
+ const id = config.providerSessionId;
43
+ if (typeof id !== "string" || !id.trim()) throw new Error("adopt.providerSessionId cannot be blank");
44
+ if (config.recap !== undefined && typeof config.recap !== "boolean") throw new Error("adopt.recap must be a boolean");
45
+ const recap = config.recap ?? defaults.recap;
46
+ const history = config.importHistory;
47
+ if (history === undefined) {
48
+ return { providerSessionId: id, recap, importHistory: recap ? { last: DEFAULT_RECAP_TAIL_TURNS } : false };
49
+ }
50
+ if (history === false) return { providerSessionId: id, recap, importHistory: false };
51
+ if (history === true) return { providerSessionId: id, recap, importHistory: {} };
52
+ const last = (history as { last?: unknown }).last;
53
+ if (typeof last !== "number" || !Number.isInteger(last) || last < 1) {
54
+ throw new Error("adopt.importHistory.last must be a positive integer");
55
+ }
56
+ return { providerSessionId: id, recap, importHistory: { last } };
57
+ }
@@ -0,0 +1,10 @@
1
+ export { DEFAULT_RECAP_TAIL_TURNS, normalizeAdoption } from "./config.ts";
2
+ export { RECAP_INSTRUCTION, RECAP_ORIGIN } from "./recap.ts";
3
+ export type { AdoptProviderSessionConfig, NormalizedAdoption } from "./config.ts";
4
+ export { turnsFromReplay, selectTail, withoutRecapTurns } from "./replay.ts";
5
+ export { publishAdoptionFloor, DEFAULT_ADOPTION_TAIL_MESSAGES } from "./checkpoint-floor.ts";
6
+ export type { AdoptionRecapPlacement } from "./checkpoint-floor.ts";
7
+ export { deleteProviderSession } from "./provider-session-delete.ts";
8
+ export { listProviderSessions, DEFAULT_PROVIDER_SESSION_LIMIT } from "./provider-sessions.ts";
9
+ export type { ListProviderSessionsOptions, ProviderSessionListing, ProviderSessionSummary } from "./provider-sessions.ts";
10
+ export type { ImportedItem, ImportedTurn } from "./replay.ts";
@@ -0,0 +1,27 @@
1
+ import { AcpClient } from "../../client.ts";
2
+ import type { ProviderSessionListing } from "./provider-sessions.ts";
3
+
4
+ /**
5
+ * Ask the provider to delete one of its sessions (`session/delete`). Best effort: not every agent offers it, and
6
+ * a failure leaves the session where it was. Starts the harness for the call and stops it again.
7
+ *
8
+ * - `true`: the provider deleted it.
9
+ * - `"unsupported"`: the agent does not advertise `session/delete`.
10
+ * - `false`: it could not be done (the harness did not start, or refused).
11
+ */
12
+ export async function deleteProviderSession(
13
+ access: Omit<ProviderSessionListing, "owners">,
14
+ providerSessionId: string,
15
+ ): Promise<true | false | "unsupported"> {
16
+ const client = new AcpClient({ adapter: access.adapter, ...access.client, defaultPermission: "cancel" });
17
+ try {
18
+ await client.connect();
19
+ if (!client.capabilities.agent.sessionCapabilities.delete) return "unsupported";
20
+ await client.deleteSession(providerSessionId);
21
+ return true;
22
+ } catch {
23
+ return false;
24
+ } finally {
25
+ await client.stop().catch(() => undefined);
26
+ }
27
+ }
@@ -0,0 +1,73 @@
1
+ import type { Adapter } from "../../adapters.ts";
2
+ import type { AgentConversationId } from "../../agent-ids.ts";
3
+ import { ProviderSessionListUnsupportedError } from "../../agent-conversation-errors.ts";
4
+ import { AcpClient, type AcpClientConfig } from "../../client.ts";
5
+
6
+ /** A session the provider holds, as `session/list` reports it, and the conversation that owns it, if any. */
7
+ export interface ProviderSessionSummary {
8
+ readonly providerSessionId: string;
9
+ readonly cwd: string;
10
+ readonly title?: string;
11
+ readonly updatedAt?: string;
12
+ /** The conversation that already owns this session (or asked to adopt it), so a UI can open it instead. */
13
+ readonly adoptedBy?: AgentConversationId;
14
+ }
15
+
16
+ export interface ListProviderSessionsOptions {
17
+ /** Which adapter to ask. Defaults to the Agent's default adapter. */
18
+ readonly adapterId?: string;
19
+ /** Only sessions of this working directory. Defaults to the conversations' default `cwd`, if any. */
20
+ readonly cwd?: string;
21
+ /** Stop after this many sessions (default 100). */
22
+ readonly limit?: number;
23
+ }
24
+
25
+ export const DEFAULT_PROVIDER_SESSION_LIMIT = 100;
26
+
27
+ /** What a listing needs from the Agent: how to start the harness, and who owns a session. */
28
+ export interface ProviderSessionListing {
29
+ readonly adapterId: string;
30
+ readonly adapter: Adapter;
31
+ readonly client: Pick<AcpClientConfig, "launcher" | "execPrefix" | "env" | "cwd" | "clientInfo" | "logger">;
32
+ owners(providerSessionId: string): Promise<readonly AgentConversationId[]>;
33
+ }
34
+
35
+ /**
36
+ * Ask the provider which sessions it holds. This starts the harness for the duration of the call (a listing
37
+ * has no conversation to ride on) and stops it again. Sessions are listed as the provider orders them.
38
+ */
39
+ export async function listProviderSessions(
40
+ listing: ProviderSessionListing,
41
+ options: ListProviderSessionsOptions = {},
42
+ ): Promise<readonly ProviderSessionSummary[]> {
43
+ const limit = options.limit ?? DEFAULT_PROVIDER_SESSION_LIMIT;
44
+ if (!Number.isInteger(limit) || limit < 1) throw new Error("limit must be a positive integer");
45
+ const cwd = options.cwd ?? listing.client.cwd;
46
+ const client = new AcpClient({ adapter: listing.adapter, ...listing.client, ...(cwd ? { cwd } : {}), defaultPermission: "cancel" });
47
+ const sessions: ProviderSessionSummary[] = [];
48
+ try {
49
+ await client.connect();
50
+ if (!client.capabilities.agent.sessionCapabilities.list) {
51
+ throw new ProviderSessionListUnsupportedError(listing.adapterId);
52
+ }
53
+ let cursor: string | undefined;
54
+ do {
55
+ const page = await client.listSessions({ ...(cwd ? { cwd } : {}), ...(cursor ? { cursor } : {}) });
56
+ for (const entry of page.sessions) {
57
+ const owner = (await listing.owners(entry.sessionId))[0];
58
+ sessions.push(Object.freeze({
59
+ providerSessionId: entry.sessionId,
60
+ cwd: entry.cwd,
61
+ ...(entry.title ? { title: entry.title } : {}),
62
+ ...(entry.updatedAt ? { updatedAt: entry.updatedAt } : {}),
63
+ ...(owner ? { adoptedBy: owner } : {}),
64
+ }));
65
+ if (sessions.length >= limit) return Object.freeze(sessions);
66
+ }
67
+ cursor = page.nextCursor;
68
+ } while (cursor);
69
+ return Object.freeze(sessions);
70
+ } finally {
71
+ await client.stop().catch(() => undefined);
72
+ }
73
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The question a recap asks the model about its own history. It is sent as a hidden turn on the adopted
3
+ * session, so the model answers from the history it already holds, however long it is; what to keep and
4
+ * what to drop is its decision.
5
+ */
6
+ export const RECAP_INSTRUCTION = [
7
+ "This is an automated request to summarize this conversation for the memory of the agent that now owns it.",
8
+ "Do not run commands, use tools, or modify any files.",
9
+ "Write a self-contained summary of the conversation so far: what the user is trying to achieve, what has been decided,",
10
+ "what has been done and what state things are in, any open tasks or questions, and key facts that would be needed",
11
+ "to continue the work. Keep it as short as it can be while keeping those.",
12
+ ].join(" ");
13
+
14
+ /** Marks the assistant message that holds a recap, so a reader can tell it from something the model said. */
15
+ export const RECAP_ORIGIN = "adoption_recap";
@@ -0,0 +1,98 @@
1
+ import type { ActivityEvent } from "../../types.ts";
2
+ import { RECAP_INSTRUCTION } from "./recap.ts";
3
+ import { extractResponseChunk, toActivityEvent } from "../../updates.ts";
4
+
5
+ /** One piece of an imported turn, in the order the provider replayed it. */
6
+ export type ImportedItem =
7
+ | { readonly kind: "user"; text: string; readonly messageId?: string }
8
+ | { readonly kind: "assistant"; text: string; readonly messageId?: string }
9
+ | { readonly kind: "activity"; readonly event: ActivityEvent };
10
+
11
+ /** A turn of replayed history. It starts at a user message, except possibly the first. */
12
+ export interface ImportedTurn {
13
+ readonly items: ImportedItem[];
14
+ }
15
+
16
+ /** Activity worth storing. Command lists, mode, config, usage and session-info updates are not history. */
17
+ const STORED_ACTIVITY = new Set(["thinking", "tool", "tool_update", "plan", "plan_update", "plan_removed"]);
18
+
19
+ /**
20
+ * Turn the raw `session/update` notifications of a `session/load` replay into turns.
21
+ *
22
+ * A replay has no turn markers. Message boundaries are the provider's `messageId` where it gives one (both
23
+ * Codex and OpenCode do), and a turn starts at each user message. Tool calls are kept in the position the
24
+ * replay gives them: a harness may place the tool call of a turn that was cancelled mid-tool after the next
25
+ * turn's user message, and that is carried over as it arrives.
26
+ */
27
+ export function turnsFromReplay(notifications: readonly unknown[]): ImportedTurn[] {
28
+ const turns: ImportedTurn[] = [];
29
+ let current: ImportedTurn | null = null;
30
+ const lastItem = (): ImportedItem | undefined => current?.items.at(-1);
31
+
32
+ for (const notification of notifications) {
33
+ const update = (notification as { update?: Record<string, unknown> } | null)?.update;
34
+ if (!update || typeof update.sessionUpdate !== "string") continue;
35
+
36
+ const response = extractResponseChunk(update as never);
37
+ if (response) {
38
+ if (!current) {
39
+ current = { items: [] };
40
+ turns.push(current);
41
+ }
42
+ const last = lastItem();
43
+ if (last?.kind === "assistant" && last.messageId === response.messageId) {
44
+ last.text += response.text;
45
+ } else {
46
+ current.items.push({
47
+ kind: "assistant",
48
+ text: response.text,
49
+ ...(response.messageId !== undefined ? { messageId: response.messageId } : {}),
50
+ });
51
+ }
52
+ continue;
53
+ }
54
+
55
+ const event = toActivityEvent(update as never);
56
+ if (!event) continue;
57
+ if (event.kind === "user_message") {
58
+ const last = lastItem();
59
+ if (last?.kind === "user" && last.messageId === event.messageId) {
60
+ last.text += event.text;
61
+ continue;
62
+ }
63
+ current = { items: [] };
64
+ turns.push(current);
65
+ current.items.push({
66
+ kind: "user",
67
+ text: event.text,
68
+ ...(event.messageId !== undefined ? { messageId: event.messageId } : {}),
69
+ });
70
+ continue;
71
+ }
72
+ if (!STORED_ACTIVITY.has(event.kind)) continue;
73
+ if (!current) {
74
+ current = { items: [] };
75
+ turns.push(current);
76
+ }
77
+ current.items.push({ kind: "activity", event });
78
+ }
79
+ return turns;
80
+ }
81
+
82
+ /** The last `n` turns, or all of them. */
83
+ export function selectTail(turns: readonly ImportedTurn[], last: number | undefined): ImportedTurn[] {
84
+ return last === undefined ? [...turns] : turns.slice(-last);
85
+ }
86
+
87
+ /**
88
+ * Drop the turns that are an earlier adoption's recap: the question is a turn of the provider's own history
89
+ * once it has been asked, so a later adoption of the same session replays it. It is not something the
90
+ * participants said, and the answer is the recap, which this adoption makes (or does not) for itself.
91
+ */
92
+ export function withoutRecapTurns(turns: readonly ImportedTurn[]): ImportedTurn[] {
93
+ const question = RECAP_INSTRUCTION.trim();
94
+ return turns.filter((turn) => {
95
+ const first = turn.items.find((item) => item.kind === "user");
96
+ return !(first && first.text.trim() === question);
97
+ });
98
+ }