@cuylabs/agent-session-store-postgres 5.0.0
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.
- package/LICENSE +201 -0
- package/README.md +63 -0
- package/dist/index.d.ts +96 -0
- package/dist/index.js +341 -0
- package/package.json +58 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# @cuylabs/agent-session-store-postgres
|
|
2
|
+
|
|
3
|
+
PostgreSQL-backed `SessionStore` for `@cuylabs/agent-core`.
|
|
4
|
+
|
|
5
|
+
Use this backend when agents need durable session state across restarts or
|
|
6
|
+
scale-out instances, including Azure App Service with Azure Database for
|
|
7
|
+
PostgreSQL Flexible Server.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { SessionManager } from "@cuylabs/agent-core";
|
|
11
|
+
import { PostgresSessionStore } from "@cuylabs/agent-session-store-postgres";
|
|
12
|
+
|
|
13
|
+
const sessionManager = new SessionManager(
|
|
14
|
+
new PostgresSessionStore({
|
|
15
|
+
connectionString: process.env.AGENT_SESSION_POSTGRES_URL,
|
|
16
|
+
poolOptions: {
|
|
17
|
+
ssl: { rejectUnauthorized: true },
|
|
18
|
+
},
|
|
19
|
+
}),
|
|
20
|
+
);
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
For scaled Azure App Service deployments, also pass the Postgres-backed turn
|
|
24
|
+
lock to `createAgent()` so multiple app instances cannot run turns for the same
|
|
25
|
+
session concurrently:
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { createAgent, SessionManager } from "@cuylabs/agent-core";
|
|
29
|
+
import {
|
|
30
|
+
PostgresSessionStore,
|
|
31
|
+
PostgresSessionTurnLock,
|
|
32
|
+
} from "@cuylabs/agent-session-store-postgres";
|
|
33
|
+
|
|
34
|
+
const connectionString = process.env.AGENT_SESSION_POSTGRES_URL;
|
|
35
|
+
|
|
36
|
+
const agent = createAgent({
|
|
37
|
+
model,
|
|
38
|
+
sessionManager: new SessionManager(
|
|
39
|
+
new PostgresSessionStore({ connectionString }),
|
|
40
|
+
),
|
|
41
|
+
sessionTurnLock: new PostgresSessionTurnLock({ connectionString }),
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The store is append-only and stores each session entry as `jsonb`. By default
|
|
46
|
+
it creates the `public.agent_session_entries` table on first use.
|
|
47
|
+
|
|
48
|
+
The turn lock uses PostgreSQL advisory locks and holds a dedicated database
|
|
49
|
+
connection only while the agent turn is running. It does not hold a database
|
|
50
|
+
transaction open during LLM/tool execution.
|
|
51
|
+
|
|
52
|
+
## Azure PostgreSQL
|
|
53
|
+
|
|
54
|
+
For Azure Database for PostgreSQL Flexible Server, configure an App Service
|
|
55
|
+
application setting such as:
|
|
56
|
+
|
|
57
|
+
```text
|
|
58
|
+
AGENT_SESSION_POSTGRES_URL=postgresql://user:password@server.postgres.database.azure.com:5432/database?sslmode=require
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
If your deployment uses an Azure-managed CA bundle, pass the CA through
|
|
62
|
+
`poolOptions.ssl`. For private networks and managed identity, create the
|
|
63
|
+
`pg.Pool` in the host app and pass it as `pool`.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { SessionStore, SessionHeader, SessionEntry, FileEntry, SessionInfo, SessionTurnLock, SessionTurnLockAcquireOptions, ReleaseSessionTurnLock } from '@cuylabs/agent-core/sessions';
|
|
2
|
+
import { Pool, PoolConfig } from 'pg';
|
|
3
|
+
|
|
4
|
+
interface PostgresSessionStoreOptions {
|
|
5
|
+
/**
|
|
6
|
+
* PostgreSQL connection string. For Azure Database for PostgreSQL, use the
|
|
7
|
+
* application setting that contains your Flexible Server connection string.
|
|
8
|
+
*/
|
|
9
|
+
connectionString?: string;
|
|
10
|
+
/**
|
|
11
|
+
* Reuse a host-managed pool. When provided, close() will not end the pool.
|
|
12
|
+
*/
|
|
13
|
+
pool?: Pool;
|
|
14
|
+
/**
|
|
15
|
+
* Additional node-postgres pool options.
|
|
16
|
+
*/
|
|
17
|
+
poolOptions?: Omit<PoolConfig, "connectionString">;
|
|
18
|
+
/**
|
|
19
|
+
* Database schema that owns the session table.
|
|
20
|
+
*
|
|
21
|
+
* @default "public"
|
|
22
|
+
*/
|
|
23
|
+
schema?: string;
|
|
24
|
+
/**
|
|
25
|
+
* Table used to store append-only session entries.
|
|
26
|
+
*
|
|
27
|
+
* @default "agent_session_entries"
|
|
28
|
+
*/
|
|
29
|
+
tableName?: string;
|
|
30
|
+
/**
|
|
31
|
+
* Create the schema/table on first use.
|
|
32
|
+
*
|
|
33
|
+
* @default true
|
|
34
|
+
*/
|
|
35
|
+
ensureSchema?: boolean;
|
|
36
|
+
}
|
|
37
|
+
declare class PostgresSessionStore implements SessionStore {
|
|
38
|
+
private readonly pool;
|
|
39
|
+
private readonly ownsPool;
|
|
40
|
+
private readonly schema;
|
|
41
|
+
private readonly tableName;
|
|
42
|
+
private readonly tableRef;
|
|
43
|
+
private readonly ensureSchemaOnUse;
|
|
44
|
+
private initialized;
|
|
45
|
+
private initializing?;
|
|
46
|
+
constructor(options?: PostgresSessionStoreOptions);
|
|
47
|
+
create(header: SessionHeader): Promise<void>;
|
|
48
|
+
append(sessionId: string, entry: SessionEntry): Promise<void>;
|
|
49
|
+
appendBatch(sessionId: string, entries: SessionEntry[]): Promise<void>;
|
|
50
|
+
read(sessionId: string): Promise<FileEntry[]>;
|
|
51
|
+
delete(sessionId: string): Promise<boolean>;
|
|
52
|
+
exists(sessionId: string): Promise<boolean>;
|
|
53
|
+
list(): Promise<SessionInfo[]>;
|
|
54
|
+
clear(): Promise<void>;
|
|
55
|
+
close(): Promise<void>;
|
|
56
|
+
private ensureInitialized;
|
|
57
|
+
private initialize;
|
|
58
|
+
private lockSession;
|
|
59
|
+
private getSessionPath;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
interface PostgresSessionTurnLockOptions {
|
|
63
|
+
/**
|
|
64
|
+
* PostgreSQL connection string. Defaults to AGENT_SESSION_POSTGRES_URL.
|
|
65
|
+
*/
|
|
66
|
+
connectionString?: string;
|
|
67
|
+
/**
|
|
68
|
+
* Reuse a host-managed pool. When provided, close() will not end the pool.
|
|
69
|
+
*/
|
|
70
|
+
pool?: Pool;
|
|
71
|
+
/**
|
|
72
|
+
* Additional node-postgres pool options.
|
|
73
|
+
*/
|
|
74
|
+
poolOptions?: Omit<PoolConfig, "connectionString">;
|
|
75
|
+
/**
|
|
76
|
+
* Default maximum time to wait for a turn lock.
|
|
77
|
+
*/
|
|
78
|
+
lockTimeoutMs?: number;
|
|
79
|
+
/**
|
|
80
|
+
* Poll interval while waiting for a held advisory lock.
|
|
81
|
+
*
|
|
82
|
+
* @default 100
|
|
83
|
+
*/
|
|
84
|
+
pollIntervalMs?: number;
|
|
85
|
+
}
|
|
86
|
+
declare class PostgresSessionTurnLock implements SessionTurnLock {
|
|
87
|
+
private readonly pool;
|
|
88
|
+
private readonly ownsPool;
|
|
89
|
+
private readonly lockTimeoutMs?;
|
|
90
|
+
private readonly pollIntervalMs;
|
|
91
|
+
constructor(options?: PostgresSessionTurnLockOptions);
|
|
92
|
+
acquire(sessionId: string, options?: SessionTurnLockAcquireOptions): Promise<ReleaseSessionTurnLock>;
|
|
93
|
+
close(): Promise<void>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export { PostgresSessionStore, type PostgresSessionStoreOptions, PostgresSessionTurnLock, type PostgresSessionTurnLockOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
// src/storage.ts
|
|
2
|
+
import { extractSessionInfo } from "@cuylabs/agent-core/sessions";
|
|
3
|
+
import pg from "pg";
|
|
4
|
+
|
|
5
|
+
// src/identifiers.ts
|
|
6
|
+
function quoteIdentifier(identifier) {
|
|
7
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(identifier)) {
|
|
8
|
+
throw new Error(`Invalid PostgreSQL identifier: ${identifier}`);
|
|
9
|
+
}
|
|
10
|
+
return `"${identifier}"`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// src/storage.ts
|
|
14
|
+
var PostgresSessionStore = class {
|
|
15
|
+
pool;
|
|
16
|
+
ownsPool;
|
|
17
|
+
schema;
|
|
18
|
+
tableName;
|
|
19
|
+
tableRef;
|
|
20
|
+
ensureSchemaOnUse;
|
|
21
|
+
initialized = false;
|
|
22
|
+
initializing;
|
|
23
|
+
constructor(options = {}) {
|
|
24
|
+
if (options.pool && options.connectionString) {
|
|
25
|
+
throw new Error("Provide either pool or connectionString, not both");
|
|
26
|
+
}
|
|
27
|
+
const connectionString = options.connectionString ?? process.env.AGENT_SESSION_POSTGRES_URL;
|
|
28
|
+
if (!options.pool && !connectionString) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
"PostgresSessionStore requires pool, connectionString, or AGENT_SESSION_POSTGRES_URL"
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
this.pool = options.pool ?? new pg.Pool({
|
|
34
|
+
...options.poolOptions,
|
|
35
|
+
connectionString
|
|
36
|
+
});
|
|
37
|
+
this.ownsPool = !options.pool;
|
|
38
|
+
this.schema = options.schema ?? "public";
|
|
39
|
+
this.tableName = options.tableName ?? "agent_session_entries";
|
|
40
|
+
this.tableRef = `${quoteIdentifier(this.schema)}.${quoteIdentifier(
|
|
41
|
+
this.tableName
|
|
42
|
+
)}`;
|
|
43
|
+
this.ensureSchemaOnUse = options.ensureSchema ?? true;
|
|
44
|
+
}
|
|
45
|
+
async create(header) {
|
|
46
|
+
await this.ensureInitialized();
|
|
47
|
+
try {
|
|
48
|
+
await this.pool.query(
|
|
49
|
+
`INSERT INTO ${this.tableRef} (session_id, position, entry)
|
|
50
|
+
VALUES ($1, 0, $2::jsonb)`,
|
|
51
|
+
[header.id, JSON.stringify(header)]
|
|
52
|
+
);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (isUniqueViolation(error)) {
|
|
55
|
+
throw new Error(`Session already exists: ${header.id}`);
|
|
56
|
+
}
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async append(sessionId, entry) {
|
|
61
|
+
await this.appendBatch(sessionId, [entry]);
|
|
62
|
+
}
|
|
63
|
+
async appendBatch(sessionId, entries) {
|
|
64
|
+
if (entries.length === 0) return;
|
|
65
|
+
await this.ensureInitialized();
|
|
66
|
+
const client = await this.pool.connect();
|
|
67
|
+
try {
|
|
68
|
+
await client.query("BEGIN");
|
|
69
|
+
await this.lockSession(client, sessionId);
|
|
70
|
+
const exists = await client.query(
|
|
71
|
+
`SELECT 1 FROM ${this.tableRef}
|
|
72
|
+
WHERE session_id = $1 AND position = 0`,
|
|
73
|
+
[sessionId]
|
|
74
|
+
);
|
|
75
|
+
if (exists.rowCount === 0) {
|
|
76
|
+
throw new Error(`Session not found: ${sessionId}`);
|
|
77
|
+
}
|
|
78
|
+
const positionResult = await client.query(
|
|
79
|
+
`SELECT COALESCE(MAX(position), 0) + 1 AS next_position
|
|
80
|
+
FROM ${this.tableRef}
|
|
81
|
+
WHERE session_id = $1`,
|
|
82
|
+
[sessionId]
|
|
83
|
+
);
|
|
84
|
+
const nextPosition = Number(positionResult.rows[0]?.next_position ?? 1);
|
|
85
|
+
const values = [sessionId];
|
|
86
|
+
const placeholders = entries.map((entry, index) => {
|
|
87
|
+
values.push(nextPosition + index, JSON.stringify(entry));
|
|
88
|
+
const offset = index * 2 + 2;
|
|
89
|
+
return `($1, $${offset}, $${offset + 1}::jsonb)`;
|
|
90
|
+
});
|
|
91
|
+
await client.query(
|
|
92
|
+
`INSERT INTO ${this.tableRef} (session_id, position, entry)
|
|
93
|
+
VALUES ${placeholders.join(", ")}`,
|
|
94
|
+
values
|
|
95
|
+
);
|
|
96
|
+
await client.query("COMMIT");
|
|
97
|
+
} catch (error) {
|
|
98
|
+
await rollbackQuietly(client);
|
|
99
|
+
throw error;
|
|
100
|
+
} finally {
|
|
101
|
+
client.release();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async read(sessionId) {
|
|
105
|
+
await this.ensureInitialized();
|
|
106
|
+
const result = await this.pool.query(
|
|
107
|
+
`SELECT entry FROM ${this.tableRef}
|
|
108
|
+
WHERE session_id = $1
|
|
109
|
+
ORDER BY position ASC`,
|
|
110
|
+
[sessionId]
|
|
111
|
+
);
|
|
112
|
+
if (result.rowCount === 0) {
|
|
113
|
+
throw new Error(`Session not found: ${sessionId}`);
|
|
114
|
+
}
|
|
115
|
+
return result.rows.map((row) => normalizeEntry(row.entry));
|
|
116
|
+
}
|
|
117
|
+
async delete(sessionId) {
|
|
118
|
+
await this.ensureInitialized();
|
|
119
|
+
const result = await this.pool.query(
|
|
120
|
+
`DELETE FROM ${this.tableRef}
|
|
121
|
+
WHERE session_id = $1`,
|
|
122
|
+
[sessionId]
|
|
123
|
+
);
|
|
124
|
+
return (result.rowCount ?? 0) > 0;
|
|
125
|
+
}
|
|
126
|
+
async exists(sessionId) {
|
|
127
|
+
await this.ensureInitialized();
|
|
128
|
+
const result = await this.pool.query(
|
|
129
|
+
`SELECT 1 FROM ${this.tableRef}
|
|
130
|
+
WHERE session_id = $1 AND position = 0
|
|
131
|
+
LIMIT 1`,
|
|
132
|
+
[sessionId]
|
|
133
|
+
);
|
|
134
|
+
return (result.rowCount ?? 0) > 0;
|
|
135
|
+
}
|
|
136
|
+
async list() {
|
|
137
|
+
await this.ensureInitialized();
|
|
138
|
+
const result = await this.pool.query(
|
|
139
|
+
`SELECT session_id, jsonb_agg(entry ORDER BY position ASC) AS entries
|
|
140
|
+
FROM ${this.tableRef}
|
|
141
|
+
GROUP BY session_id`
|
|
142
|
+
);
|
|
143
|
+
const infos = [];
|
|
144
|
+
for (const row of result.rows) {
|
|
145
|
+
try {
|
|
146
|
+
const entries = normalizeEntries(row.entries);
|
|
147
|
+
const info = extractSessionInfo(
|
|
148
|
+
entries,
|
|
149
|
+
this.getSessionPath(row.session_id)
|
|
150
|
+
);
|
|
151
|
+
if (info) {
|
|
152
|
+
infos.push(info);
|
|
153
|
+
}
|
|
154
|
+
} catch {
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
infos.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
|
|
158
|
+
return infos;
|
|
159
|
+
}
|
|
160
|
+
async clear() {
|
|
161
|
+
await this.ensureInitialized();
|
|
162
|
+
await this.pool.query(`DELETE FROM ${this.tableRef}`);
|
|
163
|
+
}
|
|
164
|
+
async close() {
|
|
165
|
+
if (this.ownsPool) {
|
|
166
|
+
await this.pool.end();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async ensureInitialized() {
|
|
170
|
+
if (this.initialized) return;
|
|
171
|
+
if (!this.initializing) {
|
|
172
|
+
this.initializing = this.initialize();
|
|
173
|
+
}
|
|
174
|
+
await this.initializing;
|
|
175
|
+
}
|
|
176
|
+
async initialize() {
|
|
177
|
+
if (this.ensureSchemaOnUse) {
|
|
178
|
+
await this.pool.query(
|
|
179
|
+
`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(this.schema)}`
|
|
180
|
+
);
|
|
181
|
+
await this.pool.query(
|
|
182
|
+
`CREATE TABLE IF NOT EXISTS ${this.tableRef} (
|
|
183
|
+
session_id TEXT NOT NULL,
|
|
184
|
+
position INTEGER NOT NULL,
|
|
185
|
+
entry JSONB NOT NULL,
|
|
186
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
187
|
+
PRIMARY KEY (session_id, position)
|
|
188
|
+
)`
|
|
189
|
+
);
|
|
190
|
+
await this.pool.query(
|
|
191
|
+
`CREATE INDEX IF NOT EXISTS ${quoteIdentifier(
|
|
192
|
+
`${this.tableName}_session_position_idx`
|
|
193
|
+
)}
|
|
194
|
+
ON ${this.tableRef} (session_id, position)`
|
|
195
|
+
);
|
|
196
|
+
await this.pool.query(
|
|
197
|
+
`CREATE INDEX IF NOT EXISTS ${quoteIdentifier(
|
|
198
|
+
`${this.tableName}_entry_type_idx`
|
|
199
|
+
)}
|
|
200
|
+
ON ${this.tableRef} ((entry->>'type'))`
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
this.initialized = true;
|
|
204
|
+
}
|
|
205
|
+
async lockSession(client, sessionId) {
|
|
206
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtext($1))", [
|
|
207
|
+
sessionId
|
|
208
|
+
]);
|
|
209
|
+
}
|
|
210
|
+
getSessionPath(sessionId) {
|
|
211
|
+
return `postgres://${this.schema}.${this.tableName}/${sessionId}`;
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
function normalizeEntry(value) {
|
|
215
|
+
if (typeof value === "string") {
|
|
216
|
+
return JSON.parse(value);
|
|
217
|
+
}
|
|
218
|
+
return value;
|
|
219
|
+
}
|
|
220
|
+
function normalizeEntries(value) {
|
|
221
|
+
if (typeof value === "string") {
|
|
222
|
+
return JSON.parse(value);
|
|
223
|
+
}
|
|
224
|
+
return value;
|
|
225
|
+
}
|
|
226
|
+
function isUniqueViolation(error) {
|
|
227
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "23505";
|
|
228
|
+
}
|
|
229
|
+
async function rollbackQuietly(client) {
|
|
230
|
+
try {
|
|
231
|
+
await client.query("ROLLBACK");
|
|
232
|
+
} catch {
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// src/lock.ts
|
|
237
|
+
import pg2 from "pg";
|
|
238
|
+
var PostgresSessionTurnLock = class {
|
|
239
|
+
pool;
|
|
240
|
+
ownsPool;
|
|
241
|
+
lockTimeoutMs;
|
|
242
|
+
pollIntervalMs;
|
|
243
|
+
constructor(options = {}) {
|
|
244
|
+
if (options.pool && options.connectionString) {
|
|
245
|
+
throw new Error("Provide either pool or connectionString, not both");
|
|
246
|
+
}
|
|
247
|
+
const connectionString = options.connectionString ?? process.env.AGENT_SESSION_POSTGRES_URL;
|
|
248
|
+
if (!options.pool && !connectionString) {
|
|
249
|
+
throw new Error(
|
|
250
|
+
"PostgresSessionTurnLock requires pool, connectionString, or AGENT_SESSION_POSTGRES_URL"
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
this.pool = options.pool ?? new pg2.Pool({
|
|
254
|
+
...options.poolOptions,
|
|
255
|
+
connectionString
|
|
256
|
+
});
|
|
257
|
+
this.ownsPool = !options.pool;
|
|
258
|
+
this.lockTimeoutMs = options.lockTimeoutMs;
|
|
259
|
+
this.pollIntervalMs = options.pollIntervalMs ?? 100;
|
|
260
|
+
}
|
|
261
|
+
async acquire(sessionId, options = {}) {
|
|
262
|
+
throwIfAborted(options.signal);
|
|
263
|
+
const timeoutMs = options.timeoutMs ?? this.lockTimeoutMs;
|
|
264
|
+
const deadline = timeoutMs === void 0 ? void 0 : Date.now() + timeoutMs;
|
|
265
|
+
const client = await this.pool.connect();
|
|
266
|
+
try {
|
|
267
|
+
while (true) {
|
|
268
|
+
throwIfAborted(options.signal);
|
|
269
|
+
const result = await client.query(
|
|
270
|
+
"SELECT pg_try_advisory_lock(hashtext($1)) AS locked",
|
|
271
|
+
[sessionId]
|
|
272
|
+
);
|
|
273
|
+
if (result.rows[0]?.locked === true) {
|
|
274
|
+
return createRelease(client, sessionId);
|
|
275
|
+
}
|
|
276
|
+
if (deadline !== void 0 && Date.now() >= deadline) {
|
|
277
|
+
throw new Error(
|
|
278
|
+
`Timed out acquiring Postgres session turn lock for ${sessionId} after ${timeoutMs}ms`
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
await delay(
|
|
282
|
+
deadline === void 0 ? this.pollIntervalMs : Math.min(this.pollIntervalMs, Math.max(0, deadline - Date.now())),
|
|
283
|
+
options.signal
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
} catch (error) {
|
|
287
|
+
client.release();
|
|
288
|
+
throw error;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
async close() {
|
|
292
|
+
if (this.ownsPool) {
|
|
293
|
+
await this.pool.end();
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
function createRelease(client, sessionId) {
|
|
298
|
+
let released = false;
|
|
299
|
+
return async () => {
|
|
300
|
+
if (released) return;
|
|
301
|
+
released = true;
|
|
302
|
+
try {
|
|
303
|
+
await client.query(
|
|
304
|
+
"SELECT pg_advisory_unlock(hashtext($1)) AS unlocked",
|
|
305
|
+
[sessionId]
|
|
306
|
+
);
|
|
307
|
+
} finally {
|
|
308
|
+
client.release();
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
async function delay(ms, signal) {
|
|
313
|
+
if (ms <= 0) return;
|
|
314
|
+
throwIfAborted(signal);
|
|
315
|
+
await new Promise((resolve, reject) => {
|
|
316
|
+
const timeout = setTimeout(() => {
|
|
317
|
+
signal?.removeEventListener("abort", onAbort);
|
|
318
|
+
resolve();
|
|
319
|
+
}, ms);
|
|
320
|
+
function onAbort() {
|
|
321
|
+
clearTimeout(timeout);
|
|
322
|
+
reject(createAbortError());
|
|
323
|
+
}
|
|
324
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
325
|
+
timeout.unref?.();
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
function throwIfAborted(signal) {
|
|
329
|
+
if (signal?.aborted) {
|
|
330
|
+
throw createAbortError();
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
function createAbortError() {
|
|
334
|
+
const error = new Error("Session turn lock acquisition aborted");
|
|
335
|
+
error.name = "AbortError";
|
|
336
|
+
return error;
|
|
337
|
+
}
|
|
338
|
+
export {
|
|
339
|
+
PostgresSessionStore,
|
|
340
|
+
PostgresSessionTurnLock
|
|
341
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@cuylabs/agent-session-store-postgres",
|
|
3
|
+
"version": "5.0.0",
|
|
4
|
+
"description": "PostgreSQL session store for @cuylabs/agent-core",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md"
|
|
18
|
+
],
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"pg": "^8.16.3",
|
|
21
|
+
"@cuylabs/agent-core": "^5.0.0"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@types/node": "^22.0.0",
|
|
25
|
+
"@types/pg": "^8.16.0",
|
|
26
|
+
"tsup": "^8.0.0",
|
|
27
|
+
"typescript": "^5.7.0",
|
|
28
|
+
"vitest": "^4.0.18"
|
|
29
|
+
},
|
|
30
|
+
"keywords": [
|
|
31
|
+
"agent",
|
|
32
|
+
"session-store",
|
|
33
|
+
"postgres",
|
|
34
|
+
"postgresql",
|
|
35
|
+
"azure"
|
|
36
|
+
],
|
|
37
|
+
"author": "cuylabs",
|
|
38
|
+
"license": "Apache-2.0",
|
|
39
|
+
"repository": {
|
|
40
|
+
"type": "git",
|
|
41
|
+
"url": "https://github.com/cuylabs-ai/agents-ts.git",
|
|
42
|
+
"directory": "packages/agent-session-store-postgres"
|
|
43
|
+
},
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=20"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build": "tsup src/index.ts --format esm --dts --clean",
|
|
52
|
+
"dev": "tsup src/index.ts --format esm --dts --watch",
|
|
53
|
+
"typecheck": "tsc --noEmit",
|
|
54
|
+
"test": "vitest run",
|
|
55
|
+
"test:watch": "vitest",
|
|
56
|
+
"clean": "rm -rf dist"
|
|
57
|
+
}
|
|
58
|
+
}
|