Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/import*as fs from'fs';import{ Sequencer, SequencerByKey }from'../../../base/common/async.js';importtype{ Database, RunResult }from'@vscode/sqlite3';importtype{ IFileEditContent, IFileEditRecord, ILocalTurnRecord, IReviewedFileRecord, ISessionDatabase }from'../common/sessionDataService.js';import{ dirname }from'../../../base/common/path.js';import{URI}from'../../../base/common/uri.js';import Message
version
sql
sessionDatabaseMigrations ISessionDatabaseMigration
version
sql
version
sql
version
sql
version
sql
version
sql
version
sql
version
sql
version
sql
version
sql
version
sql
db Database sql
resolve reject
dbsql err err err
db Database sql params changes lastID
resolve reject
dbsql params RunResult err Error
err
err
changes changes lastID lastID
db Database sql params Record
resolve reject
dbsql params err Error row Record
err
err
row
db Database sql params Record
resolve reject
dbsql params err Error rows Record
err
err
rows
db Database
resolve reject
dberr err err
path Database
resolve reject
sqlite3
db defaultpath err Error
err
err
db
reject
db Database migrations ISessionDatabaseMigration
db
row db
currentVersion rowuser_version
pending migrations
m mversion currentVersion
a b aversion bversion
pendinglength
db
migration pending
db migrationsql
db
db
err
db
err
_dbPromise Database
_closed
_fileEditSequencer
_metadataSequencer
_transactionSequencer
_turnUsageSequencer
db Database
_turnUsageSequencer
_pendingWrites
_path
_migrations ISessionDatabaseMigration sessionDatabaseMigrations
path migrations ISessionDatabaseMigration sessionDatabaseMigrations SessionDatabase
inst path migrations
inst
inst
Database
_closed
_dbPromise
_dbPromise
fspromises_path recursive
db _path
db _migrations
err
db
_dbPromise
err
_closed
db
db
err
_dbPromise
err
_dbPromise
db
rows db
rowsr rname
turnId
db
db turnId
turnId
db
db turnId
turnId eventId
db
db turnId
db eventId turnId
turnId
db
row db turnId
rowevent_id
turnId
db
row
db
turnId
rowevent_id
db
row db
rowevent_id
turnId usage
db
db turnId
db turnId usage
Map
_turnUsageSequencer
db
rows
db
result
row rows
usage rowusage
resultrowturn_id usage
eventId rowevent_id
eventId
resulteventId usage
result
turnId delegation
db
db turnId
db turnId delegation
Map
db
rows
db
result
row rows
delegation rowdelegation
resultrowturn_id delegation
eventId rowevent_id
eventId
resulteventId delegation
result
turnId ref
db
db turnId
db ref turnId
turnId
db
row db turnId
rowcheckpoint_ref
turnId
db
row
db
turnId
rowcheckpoint_ref
db
rows db
rowsr rcheckpoint_ref
turnId
db
db
turnId
turnId
db
db
turnId
db
db
record ILocalTurnRecord
db
db
recordturnId recordchatUri recordanchorTurnId recordseq recordpayload
ILocalTurnRecord
db
rows db
rowsr
turnId rturn_id
chatUri rchat_uri
anchorTurnId ranchor_turn_id
seq rseq
payload rpayload
turnIds
turnIdslength
db
placeholders turnIds
db turnIds
edit IFileEditRecord IFileEditContent
_fileEditSequencereditfilePath
db
db editturnId
db
editturnId
edittoolCallId
editfilePath
editkind
editoriginalPath
editbeforeContent BuffereditbeforeContent
editafterContent BuffereditafterContent
editaddedLines
editremovedLines
toolCallIds IFileEditRecord
toolCallIdslength
db
placeholders toolCallIds
rows
db
toolCallIds
rowsrow
turnId rowturn_id
toolCallId rowtool_call_id
filePath rowfile_path
kind rowedit_type IFileEditRecord
originalPath roworiginal_path
addedLines rowadded_lines
removedLines rowremoved_lines
IFileEditRecord
db
rows
db
rowsrow
turnId rowturn_id
toolCallId rowtool_call_id
filePath rowfile_path
kind rowedit_type IFileEditRecord
originalPath roworiginal_path
addedLines rowadded_lines
removedLines rowremoved_lines
turnId IFileEditRecord
db
rows
db
turnId
rowsrow
turnId rowturn_id
toolCallId rowtool_call_id
filePath rowfile_path
kind rowedit_type IFileEditRecord
originalPath roworiginal_path
addedLines rowadded_lines
removedLines rowremoved_lines
toolCallId filePath IFileEditContent
_fileEditSequencerfilePath
db
row
db
toolCallId filePath
row
beforeContent rowbefore_content rowbefore_content
afterContent rowafter_content rowafter_content
key
db
row db key
rowvalue
obj
keys Objectobj
result
keyslength
result
db
placeholders keys
rows db keys
key keys
resultkey
row rows
resultrowkey rowvalue
result
key value
_metadataSequencer
db
db key value
values ReadonlyRecord
_metadataSequencer
db
_transactionSequencer
db
key value Objectvalues
db key value
db
err
db
err
key values ReadonlyRecord copies ReadonlyRecord
_metadataSequencer
db
_transactionSequencer
db
existing db key
existing
db
targetKey value Objectvalues
db targetKey value
targetKey sourceKey Objectcopies
db targetKey sourceKey
db
err
db
err
chat draft Message
chatUri chat
db
draft
db chatUri
db chatUri draft
chat Message
db
row db chat
rowdraft
rowdraft Message
uri nonce
db
db uri nonce
uri nonce
db
db uri nonce
IReviewedFileRecord
db
rows db
rowstoReviewedFileRecord
uri IReviewedFileRecord
db
rows db uri
rowstoReviewedFileRecord
uri nonce
db
row db uri nonce
row
mapping ReadonlyMap eventIds ReadonlyMap
db
_transactionSequencer
db
db
oldIds mapping
oldIdslength
placeholders oldIds
db
oldIds
oldId newId mapping
db newId oldId
db newId oldId
turnId eventId eventIds
db eventId turnId
oldIdslength
placeholders oldIds
db
oldIds
oldId newId mapping
db newId oldId
db newId oldId
oldId newId mapping
db newId oldId
db newId oldId
db
err
db
err
_pendingWritessize
_pendingWrites
targetPath
db
db targetPath
p
_pendingWritesp
_pendingWritesp
puntrack untrack
p
_closed _dbPromisedb db
row Record IReviewedFileRecord
uri rowuri
nonce rownonce
value Uint8Array
value
valuebuffer valuebyteOffset valuebyteLength
value
value
value
value
/**
* A single numbered migration. Migrations are applied in order of
* {@link version} and tracked via `PRAGMA user_version`.
*/
export
interface
ISessionDatabaseMigration
{
/** Monotonically-increasing version number (1-based). */
readonly
:
number
;
/** SQL to execute for this migration. */
readonly
:
string
;
}
/**
* The set of migrations that define the current session database schema.
* New migrations should be **appended** to this array with the next version
* number. Never reorder or mutate existing entries.
*/
export
const
:
readonly
[
]
=
[
{
:
1
,
:
[
`CREATE TABLE IF NOT EXISTS turns (
id TEXT PRIMARY KEY NOT NULL
)`
,
`CREATE TABLE IF NOT EXISTS file_edits (
turn_id TEXT NOT NULL REFERENCES turns(id) ON DELETE CASCADE,
tool_call_id TEXT NOT NULL,
file_path TEXT NOT NULL,
before_content BLOB NOT NULL,
after_content BLOB NOT NULL,
added_lines INTEGER,
removed_lines INTEGER,
PRIMARY KEY (tool_call_id, file_path)
)`
,
]
.
join
(
';\n'
)
,
}
,
{
:
2
,
:
`CREATE TABLE IF NOT EXISTS session_metadata (
key TEXT PRIMARY KEY NOT NULL,
value TEXT NOT NULL
)`
,
}
,
{
:
3
,
:
[
// Recreate file_edits with new columns: edit_type, original_path,
// and nullable before_content/after_content.
`CREATE TABLE file_edits_v3 (
turn_id TEXT NOT NULL REFERENCES turns(id) ON DELETE CASCADE,
tool_call_id TEXT NOT NULL,
file_path TEXT NOT NULL,
edit_type TEXT NOT NULL DEFAULT 'edit',
original_path TEXT,
before_content BLOB,
after_content BLOB,
added_lines INTEGER,
removed_lines INTEGER,
PRIMARY KEY (tool_call_id, file_path)
)`
`CREATE TABLE IF NOT EXISTS chat_drafts (
chat_uri TEXT PRIMARY KEY NOT NULL,
draft TEXT NOT NULL
)`
,
}
,
{
:
7
,
:
`CREATE TABLE IF NOT EXISTS reviewed_files (
uri TEXT NOT NULL,
nonce TEXT NOT NULL,
PRIMARY KEY (uri, nonce)
)`
,
}
,
{
:
8
,
:
`CREATE TABLE IF NOT EXISTS local_turns (
turn_id TEXT PRIMARY KEY NOT NULL,
chat_uri TEXT NOT NULL,
anchor_turn_id TEXT,
seq INTEGER NOT NULL,
payload TEXT NOT NULL
)`
,
}
,
{
:
9
,
// `turn_usage` is a child of `turns` so every prune path (`deleteTurn`,
// `truncateFromTurn`, `deleteTurnsAfter`, `deleteAllTurns`, and the fork
// remap) reaches it by cascade and the table cannot grow unbounded.
//
// The foreign key forces `setTurnUsage` to `INSERT OR IGNORE` a parent row,
// and rows created that way carry `event_id IS NULL`. That is safe here:
// `getFirstTurnEventId` / `getNextTurnEventId` scan by rowid and are read
// only by the Copilot agent (Claude resolves fork/truncate boundaries from
// its own persisted mapping), and in a Copilot database `setTurnEventId`
// runs on `user.message` — before any usage is reported — so the parent row
// already exists and the insert is a no-op. Were usage ever to land first,
// `setTurnEventId` fills the existing row in (`UPDATE … WHERE event_id IS
// NULL`) and the position is still correct, since a turn's usage precedes
// the next turn. Each peer chat gets its own database (see
// `SessionDataService`), so a peer turn cannot interleave with another
// chat's turns either.
:
`CREATE TABLE IF NOT EXISTS turn_usage (
turn_id TEXT PRIMARY KEY NOT NULL REFERENCES turns(id) ON DELETE CASCADE,
usage TEXT NOT NULL
)`
,
}
,
{
:
10
,
:
`CREATE TABLE IF NOT EXISTS turn_delegation (
turn_id TEXT PRIMARY KEY NOT NULL REFERENCES turns(id) ON DELETE CASCADE,
delegation TEXT NOT NULL
)`
,
}
,
]
;
// ---- Promise wrappers around callback-based @vscode/sqlite3 API -----------
function
dbExec
(
:
,
:
string
)
:
Promise
<
void
>
{
return
new
Promise
(
(
,
)
=>
{
.
exec
(
,
=>
?
reject
(
)
:
resolve
(
)
)
;
}
)
;
}
function
dbRun
(
:
,
:
string
,
:
unknown
[
]
)
:
Promise
<
{
:
number
;
:
number
}
>
{
return
new
Promise
(
(
,
)
=>
{
.
run
(
,
,
function
(
this
:
,
:
|
null
)
{
if
(
)
{
return
reject
(
)
;
}
resolve
(
{
:
this
.
,
:
this
.
}
)
;
}
)
;
}
)
;
}
function
dbGet
(
:
,
:
string
,
:
unknown
[
]
)
:
Promise
<
<
string
,
unknown
>
|
undefined
>
{
return
new
Promise
(
(
,
)
=>
{
.
get
(
,
,
(
:
|
null
,
:
<
string
,
unknown
>
|
undefined
)
=>
{
if
(
)
{
return
reject
(
)
;
}
resolve
(
)
;
}
)
;
}
)
;
}
function
dbAll
(
:
,
:
string
,
:
unknown
[
]
)
:
Promise
<
<
string
,
unknown
>
[
]
>
{
return
new
Promise
(
(
,
)
=>
{
.
all
(
,
,
(
:
|
null
,
:
<
string
,
unknown
>
[
]
)
=>
{
if
(
)
{
return
reject
(
)
;
}
resolve
(
)
;
}
)
;
}
)
;
}
function
dbClose
(
:
)
:
Promise
<
void
>
{
return
new
Promise
(
(
,
)
=>
{
.
close
(
=>
?
reject
(
)
:
resolve
(
)
)
;
}
)
;
}
function
dbOpen
(
:
string
)
:
Promise
<
>
{
return
new
Promise
(
(
,
)
=>
{
import
(
'@vscode/sqlite3'
)
.
then
(
=>
{
const
=
new
sqlite3
.
.
Database
(
,
(
:
|
null
)
=>
{
if
(
)
{
return
reject
(
)
;
}
resolve
(
)
;
}
)
;
}
,
)
;
}
)
;
}
/**
* Applies any pending {@link ISessionDatabaseMigration migrations} to a
* database. Migrations whose version is greater than the current
* `PRAGMA user_version` are run inside a serialized transaction. After all
* migrations complete the pragma is updated to the highest applied version.
*/
export
async
function
runMigrations
(
:
,
:
readonly
[
]
)
:
Promise
<
void
>
{
// Enable foreign key enforcement — must be set outside a transaction
// and every time a connection is opened.
await
dbExec
(
,
'PRAGMA foreign_keys = ON'
)
;
const
=
await
dbGet
(
,
'PRAGMA user_version'
,
[
]
)
;
const
=
(
?.
as
number
|
undefined
)
??
0
;
const
=
.
filter
(
=>
.
>
)
.
sort
(
(
,
)
=>
.
-
.
)
;
if
(
.
===
0
)
{
return
;
}
await
dbExec
(
,
'BEGIN TRANSACTION'
)
;
try
{
for
(
const
of
)
{
await
dbExec
(
,
.
)
;
// PRAGMA cannot be parameterized; the version is a trusted literal.
await
dbExec
(
,
`PRAGMA user_version = ${migration.version}`
)
;
}
await
dbExec
(
,
'COMMIT'
)
;
}
catch
(
)
{
await
dbExec
(
,
'ROLLBACK'
)
;
throw
;
}
}
/**
* A wrapper around a `@vscode/sqlite3` {@link Database} instance with
* lazy initialisation.
*
* The underlying connection is opened on the first async method call
* (not at construction time), allowing the object to be created
* synchronously and shared via a {@link ReferenceCollection}.
*
* Calling {@link dispose} closes the connection.
*/
export
class
SessionDatabase
implements
ISessionDatabase
{
protected
:
Promise
<
>
|
undefined
;
protected
:
Promise
<
void
>
|
true
|
undefined
;
private
readonly
=
new
SequencerByKey<string>
(
)
;
private
readonly
=
new
Sequencer
(
)
;
private
readonly
=
new
Sequencer
(
)
;
/**
* Serializes every `turn_usage` access — writes, prunes, the fork remap, and the restore read
* alike. `@vscode/sqlite3` runs in parallelized mode (see {@link _metadataSequencer}), so a
* fire-and-forget `setTurnUsage` submitted before a truncation can otherwise complete *after*
* it and resurrect a row the truncation was meant to remove, and a read can otherwise overtake
* a write it was submitted after. Mutations must go through {@link _mutateTurnUsage} rather
* than queueing on this directly, so they are tracked for {@link whenIdle}.
*/
private
readonly
=
new
Sequencer
(
)
;
/**
* Runs a mutation that touches `turn_usage`, tracked for {@link whenIdle}
* and serialized against every other such mutation.
*/
private
_mutateTurnUsage
(
operation
:
(
:
)
=>
Promise
<
void
>
)
:
Promise
<
void
>
{
return
this
.
_track
(
(
)
=>
this
.
.
queue
(
async
(
)
=>
operation
(
await
this
.
_ensureDb
(
)
)
)
)
;
}
/**
* In-flight write operations. Tracked so {@link whenIdle} can await them
* before the process exits — without this, a `SIGTERM` arriving between
* a fire-and-forget mutating call (e.g. `setMetadata`) being invoked and
* its underlying SQLite query completing would silently drop the write.
* Every public mutating method routes its returned promise through
* {@link _track}; reads (`getMetadata`, `getFileEdits`, ...) skip
* tracking since shutdown does not need to wait for them.
*/
private
readonly
=
new
Set<Promise<unknown>>
(
)
;
constructor
(
private
readonly
:
string
,
private
readonly
:
readonly
[
]
=
,
)
{
}
/**
* Opens (or creates) a SQLite database at {@link path} and applies
* any pending migrations. Only used in tests where synchronous
* construction + immediate readiness is desired.
*/
static
async
open
(
:
string
,
:
readonly
[
]
=
)
:
Promise
<
>
{
const
=
new
SessionDatabase
(
,
)
;
await
.
_ensureDb
(
)
;
return
;
}
protected
_ensureDb
(
)
:
Promise
<
>
{
if
(
this
.
)
{
return
Promise
.
reject
(
new
Error
(
'SessionDatabase has been disposed'
)
)
;
}
if
(
!
this
.
)
{
this
.
=
(
async
(
)
=>
{
// Ensure the parent directory exists before SQLite tries to
// create the database file.
await
.
.
mkdir
(
dirname
(
this
.
)
,
{
:
true
}
)
;
const
=
await
dbOpen
(
this
.
)
;
try
{
await
runMigrations
(
,
this
.
)
;
}
catch
(
)
{
await
dbClose
(
)
;
this
.
=
undefined
;
throw
;
}
// If dispose() was called while we were opening, close immediately.
if
(
this
.
)
{
await
dbClose
(
)
;
throw
new
Error
(
'SessionDatabase has been disposed'
)
;
}
return
;
}
)
(
)
.
catch
(
=>
{
this
.
=
undefined
;
throw
;
}
)
;
}
return
this
.
;
}
/**
* Returns the names of all user-created tables in the database.
* Useful for testing migration behavior.
*/
async
getAllTables
(
)
:
Promise
<
string
[
]
>
{
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbAll
(
,
`SELECT name FROM sqlite_master WHERE type='table' ORDER BY name`
// File edits and turn usage cascade-delete via their foreign keys.
await
dbRun
(
,
'DELETE FROM turns WHERE id = ?'
,
[
]
)
;
}
)
;
}
setTurnEventId
(
:
string
,
:
string
)
:
Promise
<
void
>
{
return
this
.
_track
(
async
(
)
=>
{
const
=
await
this
.
_ensureDb
(
)
;
await
dbRun
(
,
'INSERT OR IGNORE INTO turns (id) VALUES (?)'
,
[
]
)
;
// Only set the event ID if not already set — steering messages
// trigger additional user.message events within the same turn,
// and we must preserve the first (boundary) event ID.
await
dbRun
(
,
'UPDATE turns SET event_id = ? WHERE id = ? AND event_id IS NULL'
,
[
,
]
)
;
}
)
;
}
async
getTurnEventId
(
:
string
)
:
Promise
<
string
|
undefined
>
{
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbGet
(
,
'SELECT event_id FROM turns WHERE id = ?1 OR event_id = ?1 LIMIT 1'
,
[
]
)
;
return
?.
as
string
|
undefined
??
undefined
;
}
async
getNextTurnEventId
(
:
string
)
:
Promise
<
string
|
undefined
>
{
const
=
await
this
.
_ensureDb
(
)
;
// `turns.id` is the canonical turn key — either a live `request_xxx`
// dispatched by the client or, for sessions restored from disk, the
// SDK envelope id surfaced by `mapSessionEvents`. The `event_id`
// fallback covers the case where the caller asks about a turn that
// was set up live (id=`request_xxx`) but is now being referenced
// via the SDK event id, or vice versa.
const
=
await
dbGet
(
,
`SELECT event_id FROM turns
WHERE rowid > (
SELECT rowid FROM turns WHERE id = ?1 OR event_id = ?1 LIMIT 1
)
ORDER BY rowid LIMIT 1`
,
[
]
,
)
;
return
?.
as
string
|
undefined
??
undefined
;
}
async
getFirstTurnEventId
(
)
:
Promise
<
string
|
undefined
>
{
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbGet
(
,
'SELECT event_id FROM turns ORDER BY rowid LIMIT 1'
,
[
]
)
;
return
?.
as
string
|
undefined
??
undefined
;
}
setTurnUsage
(
:
string
,
:
string
)
:
Promise
<
void
>
{
return
this
.
_mutateTurnUsage
(
async
=>
{
// Ensure the turn exists — lazily insert since the turn record may not
// have been created by an explicit createTurn() call. This is what makes
// the row reachable by the cascade on every prune path; see migration 9
// for why creating it cannot perturb turn ordering.
await
dbRun
(
,
'INSERT OR IGNORE INTO turns (id) VALUES (?)'
,
[
]
)
;
await
dbRun
(
,
'INSERT OR REPLACE INTO turn_usage (turn_id, usage) VALUES (?, ?)'
,
[
,
]
)
;
}
)
;
}
async
getTurnUsages
(
)
:
Promise
<
<
string
,
string
>>
{
// Queued on the same sequencer as the writes, not run directly: `setTurnUsage` is
// fire-and-forget and `@vscode/sqlite3` is parallelized, so a restore that reads straight
// through can miss a write submitted before it and permanently rebuild that turn without
// its cost. Read-after-write ordering is what makes the overlay deterministic.
return
this
.
.
queue
(
async
(
)
=>
{
const
=
await
this
.
_ensureDb
(
)
;
// Left-join `turns` so a usage row recorded against a live request id is
// also reachable by the SDK event id a restored turn is keyed by.
const
=
await
dbAll
(
,
`SELECT u.turn_id AS turn_id, t.event_id AS event_id, u.usage AS usage
FROM turn_usage u LEFT JOIN turns t ON t.id = u.turn_id`
,
[
]
,
)
;
const
=
new
Map<string,string>
(
)
;
for
(
const
of
)
{
const
=
.
as
string
;
.
set
(
.
as
string
,
)
;
const
=
.
as
string
|
null
;
if
(
)
{
.
set
(
,
)
;
}
}
return
;
}
)
;
}
setTurnDelegation
(
:
string
,
:
string
)
:
Promise
<
void
>
{
return
this
.
_track
(
async
(
)
=>
{
const
=
await
this
.
_ensureDb
(
)
;
await
dbRun
(
,
'INSERT OR IGNORE INTO turns (id) VALUES (?)'
,
[
]
)
;
await
dbRun
(
,
'INSERT OR REPLACE INTO turn_delegation (turn_id, delegation) VALUES (?, ?)'
,
[
,
]
)
;
}
)
;
}
async
getTurnDelegations
(
)
:
Promise
<
<
string
,
string
>>
{
await
this
.
whenIdle
(
)
;
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbAll
(
,
`SELECT d.turn_id AS turn_id, t.event_id AS event_id, d.delegation AS delegation
FROM turn_delegation d LEFT JOIN turns t ON t.id = d.turn_id`
,
[
]
,
)
;
const
=
new
Map<string,string>
(
)
;
for
(
const
of
)
{
const
=
.
as
string
;
.
set
(
.
as
string
,
)
;
const
=
.
as
string
|
null
;
if
(
)
{
.
set
(
,
)
;
}
}
return
;
}
setTurnCheckpointRef
(
:
string
,
:
string
)
:
Promise
<
void
>
{
return
this
.
_track
(
async
(
)
=>
{
const
=
await
this
.
_ensureDb
(
)
;
await
dbRun
(
,
'INSERT OR IGNORE INTO turns (id) VALUES (?)'
,
[
]
)
;
await
dbRun
(
,
'UPDATE turns SET checkpoint_ref = ? WHERE id = ?'
,
[
,
]
)
;
}
)
;
}
async
getTurnCheckpointRef
(
:
string
)
:
Promise
<
string
|
undefined
>
{
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbGet
(
,
'SELECT checkpoint_ref FROM turns WHERE id = ?1 OR event_id = ?1 LIMIT 1'
,
[
]
)
;
return
?.
as
string
|
undefined
??
undefined
;
}
async
getPreviousCheckpointRef
(
:
string
)
:
Promise
<
string
|
undefined
>
{
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbGet
(
,
`SELECT checkpoint_ref FROM turns
WHERE rowid < (SELECT rowid FROM turns WHERE id = ?1 OR event_id = ?1 LIMIT 1)
AND checkpoint_ref IS NOT NULL
ORDER BY rowid DESC LIMIT 1`
,
[
]
,
)
;
return
?.
as
string
|
undefined
??
undefined
;
}
async
getAllCheckpointRefs
(
)
:
Promise
<
string
[
]
>
{
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbAll
(
,
'SELECT checkpoint_ref FROM turns WHERE checkpoint_ref IS NOT NULL ORDER BY rowid'
,
[
]
)
;
return
.
map
(
=>
.
as
string
)
;
}
truncateFromTurn
(
:
string
)
:
Promise
<
void
>
{
return
this
.
_mutateTurnUsage
(
async
=>
{
// Delete the target turn and all turns inserted after it (by rowid order).
// File edits and turn usage cascade-delete via their foreign keys.
await
dbRun
(
,
`DELETE FROM turns WHERE rowid >= (SELECT rowid FROM turns WHERE id = ?)`
,
[
]
,
)
;
}
)
;
}
deleteTurnsAfter
(
:
string
)
:
Promise
<
void
>
{
return
this
.
_mutateTurnUsage
(
async
=>
{
// Delete all turns inserted after the given turn (by rowid order),
// keeping the given turn itself. File edits and turn usage
// cascade-delete via their foreign keys.
await
dbRun
(
,
`DELETE FROM turns WHERE rowid > (SELECT rowid FROM turns WHERE id = ?)`
,
[
]
,
)
;
}
)
;
}
deleteAllTurns
(
)
:
Promise
<
void
>
{
return
this
.
_mutateTurnUsage
(
async
=>
{
// File edits and turn usage cascade-delete via their foreign keys.
await
dbExec
(
,
'DELETE FROM turns'
)
;
}
)
;
}
// ---- Local (host-injected) turns ------------------------------------
insertLocalTurn
(
:
)
:
Promise
<
void
>
{
return
this
.
_track
(
async
(
)
=>
{
const
=
await
this
.
_ensureDb
(
)
;
await
dbRun
(
,
'INSERT OR REPLACE INTO local_turns (turn_id, chat_uri, anchor_turn_id, seq, payload) VALUES (?, ?, ?, ?, ?)'
,
[
.
,
.
,
.
??
null
,
.
,
.
]
,
)
;
}
)
;
}
async
getLocalTurns
(
)
:
Promise
<
[
]
>
{
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbAll
(
,
'SELECT turn_id, chat_uri, anchor_turn_id, seq, payload FROM local_turns ORDER BY seq'
,
[
]
)
;
return
.
map
(
=>
(
{
:
.
as
string
,
:
.
as
string
,
:
(
.
as
string
|
null
)
??
undefined
,
:
.
as
number
,
:
.
as
string
,
}
)
)
;
}
deleteLocalTurns
(
:
readonly
string
[
]
)
:
Promise
<
void
>
{
return
this
.
_track
(
async
(
)
=>
{
if
(
.
===
0
)
{
return
;
}
const
=
await
this
.
_ensureDb
(
)
;
const
=
.
map
(
(
)
=>
'?'
)
.
join
(
','
)
;
await
dbRun
(
,
`DELETE FROM local_turns WHERE turn_id IN (${placeholders})`
`SELECT turn_id, tool_call_id, file_path, edit_type, original_path, added_lines, removed_lines
FROM file_edits
WHERE tool_call_id IN (${placeholders})
ORDER BY rowid`
,
,
)
;
return
.
map
(
=>
(
{
:
.
as
string
,
:
.
as
string
,
:
.
as
string
,
:
(
.
as
[
'kind'
]
)
??
'edit'
,
:
.
as
string
|
undefined
??
undefined
,
:
.
as
number
|
undefined
??
undefined
,
:
.
as
number
|
undefined
??
undefined
,
}
)
)
;
}
async
getAllFileEdits
(
)
:
Promise
<
[
]
>
{
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbAll
(
,
`SELECT turn_id, tool_call_id, file_path, edit_type, original_path, added_lines, removed_lines
FROM file_edits
ORDER BY rowid`
,
[
]
,
)
;
return
.
map
(
=>
(
{
:
.
as
string
,
:
.
as
string
,
:
.
as
string
,
:
(
.
as
[
'kind'
]
)
??
'edit'
,
:
.
as
string
|
undefined
??
undefined
,
:
.
as
number
|
undefined
??
undefined
,
:
.
as
number
|
undefined
??
undefined
,
}
)
)
;
}
async
getFileEditsByTurn
(
:
string
)
:
Promise
<
[
]
>
{
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbAll
(
,
`SELECT turn_id, tool_call_id, file_path, edit_type, original_path, added_lines, removed_lines
FROM file_edits
WHERE turn_id = ?
ORDER BY rowid`
,
[
]
,
)
;
return
.
map
(
=>
(
{
:
.
as
string
,
:
.
as
string
,
:
.
as
string
,
:
(
.
as
[
'kind'
]
)
??
'edit'
,
:
.
as
string
|
undefined
??
undefined
,
:
.
as
number
|
undefined
??
undefined
,
:
.
as
number
|
undefined
??
undefined
,
}
)
)
;
}
async
readFileEditContent
(
:
string
,
:
string
)
:
Promise
<
|
undefined
>
{
return
this
.
.
queue
(
,
async
(
)
=>
{
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbGet
(
,
`SELECT before_content, after_content
FROM file_edits
WHERE tool_call_id = ? AND file_path = ?`
'INSERT OR IGNORE INTO reviewed_files (uri, nonce) VALUES (?, ?)'
,
[
.
toString
(
)
,
]
)
;
}
)
;
}
unmarkFileReviewed
(
:
URI
,
:
string
)
:
Promise
<
void
>
{
return
this
.
_track
(
async
(
)
=>
{
const
=
await
this
.
_ensureDb
(
)
;
await
dbRun
(
,
'DELETE FROM reviewed_files WHERE uri = ? AND nonce = ?'
,
[
.
toString
(
)
,
]
)
;
}
)
;
}
async
getReviewedFiles
(
)
:
Promise
<
[
]
>
{
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbAll
(
,
'SELECT uri, nonce FROM reviewed_files ORDER BY rowid'
,
[
]
)
;
return
.
map
(
)
;
}
async
getReviewedFilesForUri
(
:
URI
)
:
Promise
<
[
]
>
{
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbAll
(
,
'SELECT uri, nonce FROM reviewed_files WHERE uri = ? ORDER BY rowid'
,
[
.
toString
(
)
]
)
;
return
.
map
(
)
;
}
async
isFileReviewed
(
:
URI
,
:
string
)
:
Promise
<
boolean
>
{
const
=
await
this
.
_ensureDb
(
)
;
const
=
await
dbGet
(
,
'SELECT 1 FROM reviewed_files WHERE uri = ? AND nonce = ? LIMIT 1'
,
[
.
toString
(
)
,
]
)
;
return
!
!
;
}
remapTurnIds
(
:
<
string
,
string
>
,
?
:
<
string
,
string
>
)
:
Promise
<
void
>
{
// Mutates `turn_usage`, so it must serialize with every other such
// mutation — a usage write racing the fork transaction would otherwise
// land against either the old or the new turn id unpredictably.
return
this
.
_mutateTurnUsage
(
async
=>
{
await
this
.
.
queue
(
async
(
)
=>
{
// Defer FK checks to commit time so we can update turns.id and
// file_edits.turn_id in any order without mid-statement violations.
// This pragma auto-resets after the transaction ends.
await
dbExec
(
,
'PRAGMA defer_foreign_keys = ON'
)
;
await
dbExec
(
,
'BEGIN TRANSACTION'
)
;
try
{
// Delete turns not present in the mapping (e.g. turns beyond
// the fork point). File edits cascade-delete via FK.
const
=
[
...
.
keys
(
)
]
;
if
(
.
>
0
)
{
const
=
.
map
(
(
)
=>
'?'
)
.
join
(
','
)
;
await
dbRun
(
,
`DELETE FROM turns WHERE id NOT IN (${placeholders})`
,
,
)
;
}
// Remap the remaining turn IDs to their new values
for
(
const
[
,
]
of
)
{
await
dbRun
(
,
'UPDATE turns SET id = ? WHERE id = ?'
,
[
,
]
)
;
await
dbRun
(
,
'UPDATE file_edits SET turn_id = ? WHERE turn_id = ?'
,
[
,
]
)
;
}
for
(
const
[
,
]
of
??
[
]
)
{
await
dbRun
(
,
'UPDATE turns SET event_id = ? WHERE id = ?'
,
[
,
]
)
;
}
if
(
.
>
0
)
{
const
=
.
map
(
(
)
=>
'?'
)
.
join
(
','
)
;
await
dbRun
(
,
`DELETE FROM local_turns WHERE turn_id NOT IN (${placeholders})`
,
,
)
;
}
for
(
const
[
,
]
of
)
{
await
dbRun
(
,
'UPDATE local_turns SET turn_id = ? WHERE turn_id = ?'
,
[
,
]
)
;
await
dbRun
(
,
'UPDATE local_turns SET anchor_turn_id = ? WHERE anchor_turn_id = ?'
,
[
,
]
)
;
}
// Rows past the fork point were already removed by the `turns`
// delete above, via the same cascade as file edits. The surviving
// ids still need remapping (the FK cascades deletes, not updates),
// or the forked session would restore with no gauge and zero cost.
for
(
const
[
,
]
of
)
{
await
dbRun
(
,
'UPDATE turn_usage SET turn_id = ? WHERE turn_id = ?'
,
[
,
]
)
;
await
dbRun
(
,
'UPDATE turn_delegation SET turn_id = ? WHERE turn_id = ?'
,
[
,
]
)
;
}
await
dbExec
(
,
'COMMIT'
)
;
}
catch
(
)
{
await
dbExec
(
,
'ROLLBACK'
)
;
throw
;
}
}
)
;
}
)
;
}
/**
* Resolves once all currently in-flight write operations have settled.
* Used by graceful shutdown to flush pending fire-and-forget writes
* before the process exits. Should be called from a path where no
* further writes are expected; loops until idle to also drain any
* writes that get queued while we're awaiting.
*/
async
whenIdle
(
)
:
Promise
<
void
>
{
while
(
this
.
.
>
0
)
{
await
Promise
.
allSettled
(
[
...
this
.
]
)
;
}
}
async
vacuumInto
(
:
string
)
{
const
=
await
this
.
_ensureDb
(
)
;
await
dbRun
(
,
'VACUUM INTO ?'
,
[
]
)
;
}
/**
* Wrap a mutating operation's promise so {@link whenIdle} can await it.
* Invoke at the **outermost** layer of every public mutating method so
* that any internal awaits (notably `_ensureDb()`) are covered too —
* tracking only the leaf `dbRun`/`dbExec` would miss the window
* between the method being called and the query actually being queued.
*/