@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
@@ -74,6 +74,7 @@ import {
74
74
  import type { OperationMeteringRecord } from "../metering/record.ts";
75
75
  import type { AgentSessionMeteringState } from "../metering/state.ts";
76
76
  import { installSqliteFts, migrateSqliteAgentSchema } from "./sqlite-schema.ts";
77
+ import { conversationsUsingProviderSession } from "./sqlite-provider-sessions.ts";
77
78
  import { SqliteInternalInferenceRepository } from "../internal-inference/persistence/sqlite-repository.ts";
78
79
  import type { InternalInferenceRepository } from "../internal-inference/persistence/repository.ts";
79
80
  import type { ConversationRecoveryCheckpointRepository } from "../checkpointing/contracts.ts";
@@ -101,6 +102,8 @@ interface ConversationRow {
101
102
  last_human_message_at: string | null;
102
103
  deleted_at: string | null;
103
104
  metadata: string | null;
105
+ adopted: number;
106
+ adopt_provider_session_id: string | null;
104
107
  }
105
108
 
106
109
  interface IdentityRow {
@@ -420,14 +423,17 @@ class SqliteConversationPersistence implements ConversationPersistence {
420
423
  assertInstant(now, "conversation createdAt");
421
424
  runSql(this.database,
422
425
  `INSERT INTO conversations(
423
- agent_conversation_id, agent_session_id, title, created_at, updated_at, metadata
424
- ) VALUES (?, ?, ?, ?, ?, ?)`,
426
+ agent_conversation_id, agent_session_id, title, created_at, updated_at, metadata,
427
+ adopted, adopt_provider_session_id
428
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
425
429
  input.agentConversationId,
426
430
  input.agentSessionId,
427
431
  input.title ?? null,
428
432
  now,
429
433
  now,
430
434
  input.metadata ?? null,
435
+ input.adoptProviderSessionId === undefined ? 0 : 1,
436
+ input.adoptProviderSessionId ?? null,
431
437
  );
432
438
  const participants = input.participants?.length
433
439
  ? input.participants
@@ -623,6 +629,19 @@ class SqliteConversationRecordPersistence implements ConversationRecordPersisten
623
629
  return Object.freeze(appended);
624
630
  }
625
631
 
632
+ async deleteForConversation(agentConversationId: AgentConversationId): Promise<number> {
633
+ return await this.runWrite(() => {
634
+ requireConversation(this.database, agentConversationId);
635
+ // Counted first: the changes count of a DELETE also includes the detail rows and full-text entries
636
+ // that go with each record (ON DELETE CASCADE and triggers), which are not records.
637
+ const count = this.database.query<{ n: number }, [string]>(
638
+ "SELECT COUNT(*) AS n FROM conversation_records WHERE agent_conversation_id = ?",
639
+ ).get(agentConversationId)?.n ?? 0;
640
+ this.database.query("DELETE FROM conversation_records WHERE agent_conversation_id = ?").run(agentConversationId);
641
+ return Number(count);
642
+ });
643
+ }
644
+
626
645
  async get(recordId: string): Promise<ConversationRecord | null> {
627
646
  const row = this.database.query<ConversationRecordRow, [string]>(
628
647
  "SELECT * FROM conversation_records WHERE record_id = ?",
@@ -946,6 +965,10 @@ class SqliteProviderSessionPersistence implements ProviderSessionPersistence {
946
965
  ).get(agentConversationId);
947
966
  return row ? providerSessionFromRow(row) : null;
948
967
  }
968
+
969
+ async conversationsUsing(internalSessionId: string): Promise<readonly AgentConversationId[]> {
970
+ return conversationsUsingProviderSession(this.database, internalSessionId);
971
+ }
949
972
  }
950
973
 
951
974
  class SqliteMeteringPersistence implements MeteringPersistence {
@@ -1703,11 +1726,12 @@ class SqliteAuditOutboxPersistence implements AuditOutboxPersistence {
1703
1726
  item.createdAt,
1704
1727
  );
1705
1728
  runSql(this.database,
1729
+ // The state's fingerprint is the Agent's base policy and only `initialize` writes it: an entry
1730
+ // carries the fingerprint of the policy that projected it, which a conversation's override changes.
1706
1731
  `UPDATE agent_audit_state
1707
- SET last_allocated_sequence = ?, capture_fingerprint = ?, updated_at = ?
1732
+ SET last_allocated_sequence = ?, updated_at = ?
1708
1733
  WHERE singleton = 1`,
1709
1734
  auditSequence,
1710
- item.captureFingerprint,
1711
1735
  item.createdAt,
1712
1736
  );
1713
1737
  return auditOutboxFromRow(this.database.query<Record<string, unknown>, [string]>(
@@ -1898,6 +1922,8 @@ function summaryFromRowWithParticipants(
1898
1922
  updatedAt: row.updated_at,
1899
1923
  latestSequence: Number(row.latest_sequence),
1900
1924
  ...(row.deleted_at !== null ? { deletedAt: row.deleted_at } : {}),
1925
+ ...(row.adopted ? { adopted: true } : {}),
1926
+ ...(row.adopt_provider_session_id !== null ? { adoptProviderSessionId: row.adopt_provider_session_id } : {}),
1901
1927
  ...(row.metadata !== null ? { metadata: row.metadata } : {}),
1902
1928
  });
1903
1929
  }
@@ -0,0 +1,35 @@
1
+ import type { Database } from "bun:sqlite";
2
+ import type { AgentConversationId } from "../agent-ids.ts";
3
+
4
+ /**
5
+ * Conversations that own a provider session: the one it is active in, and the ones that asked to adopt it and
6
+ * have not attached it yet (an adoption that failed before the session was recorded still holds its claim).
7
+ * Deleted conversations hold nothing.
8
+ */
9
+ export function conversationsUsingProviderSession(
10
+ database: Database,
11
+ internalSessionId: string,
12
+ ): readonly AgentConversationId[] {
13
+ const rows = database.query<{ agent_conversation_id: string }, [string, string]>(
14
+ `SELECT c.agent_conversation_id
15
+ FROM conversations c
16
+ WHERE c.deleted_at IS NULL
17
+ AND (
18
+ EXISTS (
19
+ SELECT 1 FROM provider_sessions p
20
+ WHERE p.agent_conversation_id = c.agent_conversation_id
21
+ AND p.internal_session_id = ?
22
+ AND p.deactivated_at IS NULL
23
+ )
24
+ OR (
25
+ c.adopt_provider_session_id = ?
26
+ AND NOT EXISTS (
27
+ SELECT 1 FROM provider_sessions p
28
+ WHERE p.agent_conversation_id = c.agent_conversation_id AND p.deactivated_at IS NULL
29
+ )
30
+ )
31
+ )
32
+ ORDER BY c.created_at, c.agent_conversation_id`,
33
+ ).all(internalSessionId, internalSessionId);
34
+ return Object.freeze(rows.map((row) => row.agent_conversation_id as AgentConversationId));
35
+ }
@@ -1,6 +1,6 @@
1
1
  import type { Database } from "bun:sqlite";
2
2
 
3
- export const SQLITE_AGENT_SCHEMA_VERSION = 12;
3
+ export const SQLITE_AGENT_SCHEMA_VERSION = 14;
4
4
 
5
5
  const BASE_SCHEMA = `
6
6
  CREATE TABLE IF NOT EXISTS schema_migrations (
@@ -25,7 +25,9 @@ CREATE TABLE IF NOT EXISTS conversations (
25
25
  latest_sequence INTEGER NOT NULL DEFAULT 0 CHECK (latest_sequence >= 0),
26
26
  last_human_message_at TEXT,
27
27
  deleted_at TEXT,
28
- metadata TEXT
28
+ metadata TEXT,
29
+ adopted INTEGER NOT NULL DEFAULT 0 CHECK (adopted IN (0, 1)),
30
+ adopt_provider_session_id TEXT
29
31
  );
30
32
 
31
33
  CREATE INDEX IF NOT EXISTS conversations_updated_idx
@@ -252,6 +254,8 @@ CREATE TABLE IF NOT EXISTS provider_sessions (
252
254
 
253
255
  CREATE INDEX IF NOT EXISTS provider_sessions_conversation_idx
254
256
  ON provider_sessions(agent_conversation_id, activated_at, provider_session_record_id);
257
+ CREATE INDEX IF NOT EXISTS provider_sessions_internal_idx
258
+ ON provider_sessions(internal_session_id);
255
259
  CREATE UNIQUE INDEX IF NOT EXISTS provider_sessions_one_active_idx
256
260
  ON provider_sessions(agent_conversation_id) WHERE deactivated_at IS NULL;
257
261
 
@@ -372,12 +376,20 @@ CREATE TABLE IF NOT EXISTS conversation_recovery_checkpoints (
372
376
  revision INTEGER NOT NULL CHECK (revision >= 1),
373
377
  covered_sequence INTEGER NOT NULL CHECK (covered_sequence >= 1),
374
378
  previous_checkpoint_id TEXT REFERENCES conversation_recovery_checkpoints(checkpoint_id),
375
- generator_internal_inference_id TEXT NOT NULL UNIQUE REFERENCES internal_inferences(internal_inference_id),
376
- summary TEXT NOT NULL CHECK (length(summary) > 0),
379
+ generator_internal_inference_id TEXT UNIQUE REFERENCES internal_inferences(internal_inference_id),
380
+ source TEXT NOT NULL DEFAULT 'internal_inference'
381
+ CHECK (source IN ('internal_inference', 'adoption_recap', 'adoption_baseline')),
382
+ summary TEXT NOT NULL,
383
+ responses_counted_after_sequence INTEGER CHECK (responses_counted_after_sequence IS NULL OR responses_counted_after_sequence >= 0),
377
384
  created_at TEXT NOT NULL,
378
385
  metadata TEXT,
379
386
  UNIQUE (agent_conversation_id, revision),
380
- UNIQUE (agent_conversation_id, covered_sequence)
387
+ UNIQUE (agent_conversation_id, covered_sequence),
388
+ CHECK (
389
+ (source = 'internal_inference' AND generator_internal_inference_id IS NOT NULL AND length(summary) > 0)
390
+ OR (source = 'adoption_recap' AND generator_internal_inference_id IS NULL AND length(summary) > 0)
391
+ OR (source = 'adoption_baseline' AND generator_internal_inference_id IS NULL AND summary = '')
392
+ )
381
393
  );
382
394
 
383
395
  CREATE INDEX IF NOT EXISTS recovery_checkpoints_latest_idx
@@ -545,7 +557,7 @@ export function migrateSqliteAgentSchema(database: Database): void {
545
557
  "SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
546
558
  ).get()?.version ?? 0)
547
559
  : 0;
548
- if (existing !== 0 && ![8, 9, 10, 11, SQLITE_AGENT_SCHEMA_VERSION].includes(existing)) {
560
+ if (existing !== 0 && ![8, 9, 10, 11, 12, 13, SQLITE_AGENT_SCHEMA_VERSION].includes(existing)) {
549
561
  throw new Error(
550
562
  `SQLite agent schema ${existing} is incompatible with ${SQLITE_AGENT_SCHEMA_VERSION}; recreate the database`,
551
563
  );
@@ -553,7 +565,7 @@ export function migrateSqliteAgentSchema(database: Database): void {
553
565
  // Admitting the `error` kind means rebuilding conversation_records: its kind CHECK is a
554
566
  // closed list SQLite cannot alter in place. Foreign keys must be off for that drop, or
555
567
  // the implicit delete would cascade into every detail table.
556
- const rebuildRecords = existing > 0 && existing < 12;
568
+ const rebuildRecords = existing > 0 && existing < 14;
557
569
  if (rebuildRecords) database.exec("PRAGMA foreign_keys = OFF");
558
570
  try {
559
571
  database.exec("BEGIN IMMEDIATE");
@@ -589,6 +601,19 @@ export function migrateSqliteAgentSchema(database: Database): void {
589
601
  throw new Error("SQLite schema migration to version 12 left foreign key violations");
590
602
  }
591
603
  }
604
+ if (version > 0 && version < 13) {
605
+ // Adoption: whether the conversation was created from an existing provider session, and which
606
+ // one it asked for (kept so a failed adoption can be retried).
607
+ database.exec("ALTER TABLE conversations ADD COLUMN adopted INTEGER NOT NULL DEFAULT 0 CHECK (adopted IN (0, 1))");
608
+ database.exec("ALTER TABLE conversations ADD COLUMN adopt_provider_session_id TEXT");
609
+ }
610
+ if (version > 0 && version < 14) {
611
+ rebuildRecoveryCheckpointsForAdoption(database);
612
+ const violations = database.query<Record<string, unknown>, []>("PRAGMA foreign_key_check").all();
613
+ if (violations.length > 0) {
614
+ throw new Error("SQLite schema migration to version 14 left foreign key violations");
615
+ }
616
+ }
592
617
  if (version < SQLITE_AGENT_SCHEMA_VERSION) {
593
618
  database.query<unknown, [number, string]>(
594
619
  "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
@@ -604,6 +629,48 @@ export function migrateSqliteAgentSchema(database: Database): void {
604
629
  }
605
630
  }
606
631
 
632
+ /**
633
+ * Rebuild `conversation_recovery_checkpoints` so a checkpoint may have no generator and an empty summary
634
+ * (adoption checkpoints), with a `source` and the adoption response-count base. SQLite cannot relax a
635
+ * NOT NULL or a CHECK in place. Foreign keys are off (see the caller). The old table's index goes with it and
636
+ * is recreated on the new one.
637
+ */
638
+ function rebuildRecoveryCheckpointsForAdoption(database: Database): void {
639
+ database.exec("ALTER TABLE conversation_recovery_checkpoints RENAME TO conversation_recovery_checkpoints_v13");
640
+ database.exec("DROP INDEX IF EXISTS recovery_checkpoints_latest_idx");
641
+ database.exec(`
642
+ CREATE TABLE conversation_recovery_checkpoints (
643
+ checkpoint_id TEXT PRIMARY KEY,
644
+ agent_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
645
+ revision INTEGER NOT NULL CHECK (revision >= 1),
646
+ covered_sequence INTEGER NOT NULL CHECK (covered_sequence >= 1),
647
+ previous_checkpoint_id TEXT REFERENCES conversation_recovery_checkpoints(checkpoint_id),
648
+ generator_internal_inference_id TEXT UNIQUE REFERENCES internal_inferences(internal_inference_id),
649
+ source TEXT NOT NULL DEFAULT 'internal_inference'
650
+ CHECK (source IN ('internal_inference', 'adoption_recap', 'adoption_baseline')),
651
+ summary TEXT NOT NULL,
652
+ responses_counted_after_sequence INTEGER CHECK (responses_counted_after_sequence IS NULL OR responses_counted_after_sequence >= 0),
653
+ created_at TEXT NOT NULL,
654
+ metadata TEXT,
655
+ UNIQUE (agent_conversation_id, revision),
656
+ UNIQUE (agent_conversation_id, covered_sequence),
657
+ CHECK (
658
+ (source = 'internal_inference' AND generator_internal_inference_id IS NOT NULL AND length(summary) > 0)
659
+ OR (source = 'adoption_recap' AND generator_internal_inference_id IS NULL AND length(summary) > 0)
660
+ OR (source = 'adoption_baseline' AND generator_internal_inference_id IS NULL AND summary = '')
661
+ )
662
+ )`);
663
+ database.exec(`INSERT INTO conversation_recovery_checkpoints(
664
+ checkpoint_id, agent_conversation_id, revision, covered_sequence, previous_checkpoint_id,
665
+ generator_internal_inference_id, source, summary, created_at, metadata
666
+ ) SELECT checkpoint_id, agent_conversation_id, revision, covered_sequence, previous_checkpoint_id,
667
+ generator_internal_inference_id, 'internal_inference', summary, created_at, metadata
668
+ FROM conversation_recovery_checkpoints_v13`);
669
+ database.exec("DROP TABLE conversation_recovery_checkpoints_v13");
670
+ database.exec(`CREATE INDEX IF NOT EXISTS recovery_checkpoints_latest_idx
671
+ ON conversation_recovery_checkpoints(agent_conversation_id, revision DESC)`);
672
+ }
673
+
607
674
  /**
608
675
  * Rebuild `conversation_records` so its `kind` CHECK admits `error`.
609
676
  *
@@ -189,6 +189,9 @@ export class AcpTransport {
189
189
  listSessions(params: schema.ListSessionsRequest): Promise<schema.ListSessionsResponse> {
190
190
  return this.conn().listSessions(params);
191
191
  }
192
+ deleteSession(params: schema.DeleteSessionRequest): Promise<schema.DeleteSessionResponse> {
193
+ return this.conn().deleteSession(params);
194
+ }
192
195
  prompt(params: schema.PromptRequest): Promise<schema.PromptResponse> {
193
196
  return this.conn().prompt(params);
194
197
  }