Skip to main content

Custom Storage Connectors (StorageConnector)

StorageConnector lets an application keep ISH records in a database or service it already operates. You provide five functions for reading, writing, searching, conditionally updating, and deleting records. ISH applies the same persistence rules regardless of which database stores those records. ISH does not bundle a driver for PostgreSQL, SQL Server, Redis, or another external database.

from ish import ConnectorPersistence

class Store:
def get(self, collection, key): ...
def put(self, collection, key, record): ...
def put_if(self, collection, key, record, expected_revision): ...
def query(self, collection, filters, order_by, descending, limit): ...
def delete(self, collection, key): ...

store = ConnectorPersistence(Store())
agent = Agent(model=model, persistence=store)

Connector contract​

Implement get, put, put_if, query, and delete for the logical collections used by the runtime. Records are JSON objects and keys are opaque strings. put_if must be atomic:

  • With no expected version, insert only if the key is absent. Return false if another record already uses the key.
  • With an expected version, replace the record only if its current version matches. Advance the version as part of the same update and return false if another writer changed it first.
  • query applies exact field filters, optional field ordering, direction, and limit. Preserve deterministic ordering when values compare equally by using the key as a tie-breaker.

Use a transaction or the database's compare-and-set primitive. Do not implement put_if as a separate read followed by a write.

Register a connector​

The SDK constructors create a persistence handle. Agents, durable workflows, approval snapshots, and saved run progress then use the connector through the same persistence rules as SQLite.

The connector must be safe for concurrent calls. TypeScript connectors may return a value synchronously or a Promise during asynchronous agent and workflow execution. Close the persistence store when its users are finished; this releases the native callback registration and invokes the host cleanup hook once.

PostgreSQL with pg​

The following pattern uses a JSONB record table with a unique (collection, record_key) key. put_if uses one statement so insert and revision checks remain atomic.

CREATE TABLE ish_records (
collection text NOT NULL,
record_key text NOT NULL,
revision bigint NOT NULL DEFAULT 0,
record jsonb NOT NULL,
PRIMARY KEY (collection, record_key)
);
import type { Pool } from "pg";

class PostgresConnector implements StorageConnector {
constructor(private pool: Pool) {}
async get(collection: string, key: string) {
const r = await this.pool.query(
"SELECT record FROM ish_records WHERE collection=$1 AND record_key=$2",
[collection, key]);
return r.rows[0]?.record ?? null;
}
async put(collection: string, key: string, record: JsonObject) {
await this.pool.query(`INSERT INTO ish_records(collection,record_key,revision,record)
VALUES($1,$2,COALESCE(($3->>'revision')::bigint,0),$3)
ON CONFLICT(collection,record_key) DO UPDATE SET
revision=EXCLUDED.revision, record=EXCLUDED.record`, [collection,key,record]);
}
async putIf(collection: string, key: string, record: JsonObject, expected?: number) {
if (expected === undefined) {
const r = await this.pool.query(`INSERT INTO ish_records(collection,record_key,revision,record)
VALUES($1,$2,COALESCE(($3->>'revision')::bigint,0),$3)
ON CONFLICT DO NOTHING RETURNING 1`, [collection,key,record]);
return r.rowCount === 1;
}
const r = await this.pool.query(`UPDATE ish_records SET revision=COALESCE(($4->>'revision')::bigint,revision+1), record=$4
WHERE collection=$1 AND record_key=$2 AND revision=$3`, [collection,key,expected,record]);
return r.rowCount === 1;
}
async query(collection: string, filters: JsonObject, orderBy?: string, descending=false, limit?: number) {
const params: unknown[] = [collection];
const predicates = Object.entries(filters).map(([path, value]) => {
params.push(path, JSON.stringify(value));
const pathParam = `$${params.length - 1}`;
const valueParam = `$${params.length}`;
return `jsonb_extract_path(record, VARIADIC string_to_array(${pathParam}::text, '.')) = ${valueParam}::jsonb`;
});
let sql = "SELECT record_key, record FROM ish_records WHERE collection=$1";
if (predicates.length) sql += ` AND ${predicates.join(" AND ")}`;
if (orderBy) {
params.push(orderBy);
const pathParam = `$${params.length}`;
sql += ` ORDER BY jsonb_extract_path(record, VARIADIC string_to_array(${pathParam}::text, '.')) ${descending ? "DESC" : "ASC"} NULLS FIRST, record_key ASC`;
} else {
sql += " ORDER BY record_key ASC";
}
if (limit !== undefined) {
params.push(limit);
sql += ` LIMIT $${params.length}`;
}
const r = await this.pool.query(sql, params);
return r.rows.map((row) => row.record);
}
async delete(collection: string, key: string) {
const r = await this.pool.query("DELETE FROM ish_records WHERE collection=$1 AND record_key=$2", [collection,key]);
return r.rowCount === 1;
}
}

The query example binds field paths and values as parameters, applies exact JSONB field matches, and returns deterministic key order when no field order is requested. Production adapters should still add indexes suited to their collection filters and define the table's revision column consistently with the serialized record.

SQL Server / MSSQL​

Use a primary key on (collection, record_key). An insert-if-absent can use a serializable transaction or a key-range locked insert; revision updates use a conditional UPDATE.

// With an open Microsoft.Data.SqlClient SqlConnection and transaction:
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "UPDATE IshRecords SET Revision=@next, RecordJson=@json " +
"WHERE Collection=@collection AND RecordKey=@key AND Revision=@expected";
command.Parameters.AddWithValue("@next", nextRevision);
command.Parameters.AddWithValue("@json", json);
command.Parameters.AddWithValue("@collection", collection);
command.Parameters.AddWithValue("@key", key);
command.Parameters.AddWithValue("@expected", expectedRevision);
var updated = await command.ExecuteNonQueryAsync();
return updated == 1; // false means stale/missing revision

When inserting without an expected version, use one database operation that fails cleanly if the key already exists; report that conflict as false and pass connection or schema errors back to the caller. Bind values as parameters and return decoded JSON records. Do not build SQL by concatenating collection names or filter values.

Redis​

Store each record as JSON under a namespaced key. SET ... NX implements insert-if-absent. Use a Lua script to make revision comparison and replacement one atomic Redis operation.

-- KEYS[1] is the record key; ARGV[1] expected revision; ARGV[2] next JSON.
local current = redis.call('GET', KEYS[1])
if not current then return 0 end
local decoded = cjson.decode(current)
if tonumber(decoded.revision or -1) ~= tonumber(ARGV[1]) then return 0 end
redis.call('SET', KEYS[1], ARGV[2])
return 1

For insertion, use SET key json NX and map a nil reply to false. Implement query with a collection index (for example, a Redis Set of record keys) rather than scanning unrelated keys. Ensure writes to the record and collection index are transactional, such as with Lua or MULTI/EXEC and watched keys.

Backward compatibility​

Python's SQLPersistence remains a sqlite: DSN convenience wrapper around the shared SQLite WAL logger. It does not select PostgreSQL or MySQL drivers. Use StorageConnector when an existing external database or connection pool should own persistence records.

See SQLite storage for local durability settings and Approval snapshots for pausing and safely resuming a run.