@clearideas/agent-runtime-store-local 0.1.0-alpha.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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +8 -0
- package/dist/artifact-store.file.d.ts +9 -0
- package/dist/artifact-store.file.js +91 -0
- package/dist/event-sinks.d.ts +15 -0
- package/dist/event-sinks.js +37 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/manifest-source.file.d.ts +8 -0
- package/dist/manifest-source.file.js +50 -0
- package/dist/path-component.d.ts +2 -0
- package/dist/path-component.js +7 -0
- package/dist/run-manifest-source.file.d.ts +7 -0
- package/dist/run-manifest-source.file.js +47 -0
- package/dist/run-store.file.d.ts +20 -0
- package/dist/run-store.file.js +236 -0
- package/dist/run-store.memory.d.ts +20 -0
- package/dist/run-store.memory.js +141 -0
- package/package.json +61 -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/NOTICE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# @clearideas/agent-runtime-store-local
|
|
2
|
+
|
|
3
|
+
Local adapters for in-memory state, atomic JSON files, JSON/YAML manifest
|
|
4
|
+
loading, console and JSONL events, and integrity-checked file artifacts.
|
|
5
|
+
|
|
6
|
+
`FileRunStore` is for a single process. Atomic replacement prevents partial JSON reads but
|
|
7
|
+
does not arbitrate concurrent processes. Use `@clearideas/agent-runtime-store-sqlite` or another
|
|
8
|
+
compare-and-swap store when multiple processes can resume the same run.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ArtifactRef } from "@clearideas/agent-runtime-contracts";
|
|
2
|
+
import type { ArtifactData, ArtifactInput, ArtifactStore } from "@clearideas/agent-runtime-core";
|
|
3
|
+
/** Stores artifact bytes and metadata beneath a caller-owned local directory. */
|
|
4
|
+
export declare class FileArtifactStore implements ArtifactStore {
|
|
5
|
+
#private;
|
|
6
|
+
constructor(rootDirectory: string);
|
|
7
|
+
put(input: ArtifactInput): Promise<ArtifactRef>;
|
|
8
|
+
get(ref: ArtifactRef): Promise<ArtifactData>;
|
|
9
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, open, readFile, rename, unlink } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { safePathComponent } from "./path-component.js";
|
|
6
|
+
const writeAtomically = async (filePath, data) => {
|
|
7
|
+
await mkdir(path.dirname(filePath), { recursive: true });
|
|
8
|
+
const temporaryPath = path.join(path.dirname(filePath), `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`);
|
|
9
|
+
let handle;
|
|
10
|
+
try {
|
|
11
|
+
handle = await open(temporaryPath, "wx", 0o600);
|
|
12
|
+
await handle.writeFile(data);
|
|
13
|
+
await handle.sync();
|
|
14
|
+
await handle.close();
|
|
15
|
+
handle = undefined;
|
|
16
|
+
await rename(temporaryPath, filePath);
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
await handle?.close().catch(() => undefined);
|
|
20
|
+
await unlink(temporaryPath).catch(() => undefined);
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
/** Stores artifact bytes and metadata beneath a caller-owned local directory. */
|
|
25
|
+
export class FileArtifactStore {
|
|
26
|
+
#rootDirectory;
|
|
27
|
+
constructor(rootDirectory) {
|
|
28
|
+
if (!rootDirectory.trim())
|
|
29
|
+
throw new Error("FileArtifactStore requires a root directory.");
|
|
30
|
+
this.#rootDirectory = path.resolve(rootDirectory);
|
|
31
|
+
}
|
|
32
|
+
async put(input) {
|
|
33
|
+
if (!input.name.trim())
|
|
34
|
+
throw new Error("Artifact name cannot be empty.");
|
|
35
|
+
if (!input.mediaType.trim())
|
|
36
|
+
throw new Error("Artifact media type cannot be empty.");
|
|
37
|
+
const id = `artifact_${randomUUID()}`;
|
|
38
|
+
const bytes = typeof input.data === "string"
|
|
39
|
+
? Buffer.from(input.data, "utf8")
|
|
40
|
+
: Buffer.from(input.data);
|
|
41
|
+
const dataPath = this.#dataPath(id);
|
|
42
|
+
const ref = {
|
|
43
|
+
id,
|
|
44
|
+
name: input.name,
|
|
45
|
+
mediaType: input.mediaType,
|
|
46
|
+
uri: pathToFileURL(dataPath).href,
|
|
47
|
+
size: bytes.byteLength,
|
|
48
|
+
sha256: createHash("sha256").update(bytes).digest("hex"),
|
|
49
|
+
...(input.metadata ? { metadata: input.metadata } : {}),
|
|
50
|
+
};
|
|
51
|
+
await writeAtomically(dataPath, bytes);
|
|
52
|
+
await writeAtomically(this.#metadataPath(id), `${JSON.stringify({ ref }, null, 2)}\n`);
|
|
53
|
+
return ref;
|
|
54
|
+
}
|
|
55
|
+
async get(ref) {
|
|
56
|
+
const stored = JSON.parse(await readFile(this.#metadataPath(ref.id), "utf8"));
|
|
57
|
+
if (stored.ref.id !== ref.id)
|
|
58
|
+
throw new Error(`Artifact metadata id mismatch: ${ref.id}`);
|
|
59
|
+
if (stored.ref.name !== ref.name ||
|
|
60
|
+
stored.ref.mediaType !== ref.mediaType) {
|
|
61
|
+
throw new Error(`Artifact reference mismatch: ${ref.id}`);
|
|
62
|
+
}
|
|
63
|
+
const data = await readFile(this.#dataPath(ref.id));
|
|
64
|
+
const digest = createHash("sha256").update(data).digest("hex");
|
|
65
|
+
if ((stored.ref.sha256 && stored.ref.sha256 !== digest) ||
|
|
66
|
+
(ref.sha256 && ref.sha256 !== digest) ||
|
|
67
|
+
(stored.ref.sha256 && ref.sha256 && stored.ref.sha256 !== ref.sha256)) {
|
|
68
|
+
throw new Error(`Artifact integrity check failed: ${ref.id}`);
|
|
69
|
+
}
|
|
70
|
+
if ((stored.ref.size != null && stored.ref.size !== data.byteLength) ||
|
|
71
|
+
(ref.size != null && ref.size !== data.byteLength) ||
|
|
72
|
+
(stored.ref.size != null &&
|
|
73
|
+
ref.size != null &&
|
|
74
|
+
stored.ref.size !== ref.size)) {
|
|
75
|
+
throw new Error(`Artifact size check failed: ${ref.id}`);
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
ref: stored.ref,
|
|
79
|
+
data,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
#artifactDirectory(id) {
|
|
83
|
+
return path.join(this.#rootDirectory, "artifacts", safePathComponent(id, "Artifact id"));
|
|
84
|
+
}
|
|
85
|
+
#dataPath(id) {
|
|
86
|
+
return path.join(this.#artifactDirectory(id), "data");
|
|
87
|
+
}
|
|
88
|
+
#metadataPath(id) {
|
|
89
|
+
return path.join(this.#artifactDirectory(id), "metadata.json");
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { RunEvent } from "@clearideas/agent-runtime-contracts";
|
|
2
|
+
import type { EventSink } from "@clearideas/agent-runtime-core";
|
|
3
|
+
/** Emits structured one-event-per-line output to stdout or an injected writer. */
|
|
4
|
+
export declare class ConsoleEventSink implements EventSink {
|
|
5
|
+
#private;
|
|
6
|
+
constructor(write?: (line: string) => void);
|
|
7
|
+
emit(event: RunEvent): void;
|
|
8
|
+
}
|
|
9
|
+
/** Appends events in invocation order to a replayable JSONL file. */
|
|
10
|
+
export declare class JsonlEventSink implements EventSink {
|
|
11
|
+
#private;
|
|
12
|
+
constructor(filePath: string);
|
|
13
|
+
emit(event: RunEvent): Promise<void>;
|
|
14
|
+
flush(): Promise<void>;
|
|
15
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { appendFile, mkdir } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
const serializeEvent = (event) => `${JSON.stringify(event)}\n`;
|
|
4
|
+
/** Emits structured one-event-per-line output to stdout or an injected writer. */
|
|
5
|
+
export class ConsoleEventSink {
|
|
6
|
+
#write;
|
|
7
|
+
constructor(write = (line) => process.stdout.write(line)) {
|
|
8
|
+
this.#write = write;
|
|
9
|
+
}
|
|
10
|
+
emit(event) {
|
|
11
|
+
this.#write(serializeEvent(event));
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** Appends events in invocation order to a replayable JSONL file. */
|
|
15
|
+
export class JsonlEventSink {
|
|
16
|
+
#filePath;
|
|
17
|
+
#queue = Promise.resolve();
|
|
18
|
+
constructor(filePath) {
|
|
19
|
+
if (!filePath.trim())
|
|
20
|
+
throw new Error("JsonlEventSink requires a file path.");
|
|
21
|
+
this.#filePath = path.resolve(filePath);
|
|
22
|
+
}
|
|
23
|
+
emit(event) {
|
|
24
|
+
const operation = this.#queue.then(async () => {
|
|
25
|
+
await mkdir(path.dirname(this.#filePath), { recursive: true });
|
|
26
|
+
await appendFile(this.#filePath, serializeEvent(event), {
|
|
27
|
+
encoding: "utf8",
|
|
28
|
+
mode: 0o600,
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
this.#queue = operation.catch(() => undefined);
|
|
32
|
+
return operation;
|
|
33
|
+
}
|
|
34
|
+
async flush() {
|
|
35
|
+
await this.#queue;
|
|
36
|
+
}
|
|
37
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { FileArtifactStore } from "./artifact-store.file.js";
|
|
2
|
+
export { ConsoleEventSink, JsonlEventSink } from "./event-sinks.js";
|
|
3
|
+
export { FileAgentManifestSource } from "./manifest-source.file.js";
|
|
4
|
+
export { FileAgentRunManifestSource } from "./run-manifest-source.file.js";
|
|
5
|
+
export { FileRunStore } from "./run-store.file.js";
|
|
6
|
+
export { MemoryRunStore } from "./run-store.memory.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { FileArtifactStore } from "./artifact-store.file.js";
|
|
2
|
+
export { ConsoleEventSink, JsonlEventSink } from "./event-sinks.js";
|
|
3
|
+
export { FileAgentManifestSource } from "./manifest-source.file.js";
|
|
4
|
+
export { FileAgentRunManifestSource } from "./run-manifest-source.file.js";
|
|
5
|
+
export { FileRunStore } from "./run-store.file.js";
|
|
6
|
+
export { MemoryRunStore } from "./run-store.memory.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type AgentManifest } from "@clearideas/agent-runtime-contracts";
|
|
2
|
+
import type { AgentManifestSource } from "@clearideas/agent-runtime-core";
|
|
3
|
+
/** Loads and validates JSON or YAML manifests from a constrained directory. */
|
|
4
|
+
export declare class FileAgentManifestSource implements AgentManifestSource {
|
|
5
|
+
#private;
|
|
6
|
+
constructor(rootDirectory: string, defaultReference?: string);
|
|
7
|
+
loadManifest(reference?: string | undefined): Promise<AgentManifest>;
|
|
8
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { readFile, realpath } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { parseAgentManifest, } from "@clearideas/agent-runtime-contracts";
|
|
4
|
+
import { parse as parseYaml } from "yaml";
|
|
5
|
+
const isInside = (root, candidate) => {
|
|
6
|
+
const relative = path.relative(root, candidate);
|
|
7
|
+
return (relative === "" ||
|
|
8
|
+
(!relative.startsWith(`..${path.sep}`) &&
|
|
9
|
+
relative !== ".." &&
|
|
10
|
+
!path.isAbsolute(relative)));
|
|
11
|
+
};
|
|
12
|
+
/** Loads and validates JSON or YAML manifests from a constrained directory. */
|
|
13
|
+
export class FileAgentManifestSource {
|
|
14
|
+
#rootDirectory;
|
|
15
|
+
#defaultReference;
|
|
16
|
+
constructor(rootDirectory, defaultReference) {
|
|
17
|
+
if (!rootDirectory.trim())
|
|
18
|
+
throw new Error("FileAgentManifestSource requires a root directory.");
|
|
19
|
+
this.#rootDirectory = path.resolve(rootDirectory);
|
|
20
|
+
this.#defaultReference = defaultReference;
|
|
21
|
+
}
|
|
22
|
+
async loadManifest(reference = this.#defaultReference) {
|
|
23
|
+
if (!reference?.trim())
|
|
24
|
+
throw new Error("A manifest reference is required.");
|
|
25
|
+
const filePath = this.#resolveReference(reference);
|
|
26
|
+
const extension = path.extname(filePath).toLowerCase();
|
|
27
|
+
if (![".json", ".yaml", ".yml"].includes(extension)) {
|
|
28
|
+
throw new Error(`Unsupported manifest format "${extension || "(none)"}". Use .json, .yaml, or .yml.`);
|
|
29
|
+
}
|
|
30
|
+
const [realRoot, realFile] = await Promise.all([
|
|
31
|
+
realpath(this.#rootDirectory),
|
|
32
|
+
realpath(filePath),
|
|
33
|
+
]);
|
|
34
|
+
if (!isInside(realRoot, realFile)) {
|
|
35
|
+
throw new Error("Manifest reference resolves outside the configured root.");
|
|
36
|
+
}
|
|
37
|
+
const source = await readFile(realFile, "utf8");
|
|
38
|
+
const input = extension === ".json" ? JSON.parse(source) : parseYaml(source);
|
|
39
|
+
return parseAgentManifest(input);
|
|
40
|
+
}
|
|
41
|
+
#resolveReference(reference) {
|
|
42
|
+
if (path.isAbsolute(reference))
|
|
43
|
+
throw new Error("Manifest references must be relative to the configured root.");
|
|
44
|
+
const candidate = path.resolve(this.#rootDirectory, reference);
|
|
45
|
+
if (!isInside(this.#rootDirectory, candidate)) {
|
|
46
|
+
throw new Error("Manifest reference escapes the configured root.");
|
|
47
|
+
}
|
|
48
|
+
return candidate;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
/** Maps untrusted identifiers to fixed-size, traversal-safe path components. */
|
|
3
|
+
export const safePathComponent = (value, label) => {
|
|
4
|
+
if (!value.trim())
|
|
5
|
+
throw new Error(`${label} cannot be empty.`);
|
|
6
|
+
return createHash("sha256").update(value, "utf8").digest("hex");
|
|
7
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type AgentRunManifest } from "@clearideas/agent-runtime-contracts";
|
|
2
|
+
/** Loads and validates an agent run manifest from a constrained directory. */
|
|
3
|
+
export declare class FileAgentRunManifestSource {
|
|
4
|
+
#private;
|
|
5
|
+
constructor(rootDirectory: string, defaultReference?: string);
|
|
6
|
+
loadAgentRunManifest(reference?: string | undefined): Promise<AgentRunManifest>;
|
|
7
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { readFile, realpath } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { parseAgentRunManifest, } from "@clearideas/agent-runtime-contracts";
|
|
4
|
+
import { parse as parseYaml } from "yaml";
|
|
5
|
+
const isInside = (root, candidate) => {
|
|
6
|
+
const relative = path.relative(root, candidate);
|
|
7
|
+
return (relative === "" ||
|
|
8
|
+
(!relative.startsWith(`..${path.sep}`) &&
|
|
9
|
+
relative !== ".." &&
|
|
10
|
+
!path.isAbsolute(relative)));
|
|
11
|
+
};
|
|
12
|
+
/** Loads and validates an agent run manifest from a constrained directory. */
|
|
13
|
+
export class FileAgentRunManifestSource {
|
|
14
|
+
#rootDirectory;
|
|
15
|
+
#defaultReference;
|
|
16
|
+
constructor(rootDirectory, defaultReference) {
|
|
17
|
+
if (!rootDirectory.trim()) {
|
|
18
|
+
throw new Error("FileAgentRunManifestSource requires a root directory.");
|
|
19
|
+
}
|
|
20
|
+
this.#rootDirectory = path.resolve(rootDirectory);
|
|
21
|
+
this.#defaultReference = defaultReference;
|
|
22
|
+
}
|
|
23
|
+
async loadAgentRunManifest(reference = this.#defaultReference) {
|
|
24
|
+
if (!reference?.trim())
|
|
25
|
+
throw new Error("An agent run manifest reference is required.");
|
|
26
|
+
if (path.isAbsolute(reference)) {
|
|
27
|
+
throw new Error("Agent run manifest references must be relative to the configured root.");
|
|
28
|
+
}
|
|
29
|
+
const filePath = path.resolve(this.#rootDirectory, reference);
|
|
30
|
+
if (!isInside(this.#rootDirectory, filePath)) {
|
|
31
|
+
throw new Error("Agent run manifest reference escapes the configured root.");
|
|
32
|
+
}
|
|
33
|
+
const extension = path.extname(filePath).toLowerCase();
|
|
34
|
+
if (![".json", ".yaml", ".yml"].includes(extension)) {
|
|
35
|
+
throw new Error(`Unsupported agent run manifest format "${extension || "(none)"}". Use .json, .yaml, or .yml.`);
|
|
36
|
+
}
|
|
37
|
+
const [realRoot, realFile] = await Promise.all([
|
|
38
|
+
realpath(this.#rootDirectory),
|
|
39
|
+
realpath(filePath),
|
|
40
|
+
]);
|
|
41
|
+
if (!isInside(realRoot, realFile)) {
|
|
42
|
+
throw new Error("Agent run manifest reference resolves outside the configured root.");
|
|
43
|
+
}
|
|
44
|
+
const source = await readFile(realFile, "utf8");
|
|
45
|
+
return parseAgentRunManifest(extension === ".json" ? JSON.parse(source) : parseYaml(source));
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { RunCheckpoint, RunError } from "@clearideas/agent-runtime-contracts";
|
|
2
|
+
import type { CompletedRunRecord, ResumeRunOptions, RunRecord, RunStore } from "@clearideas/agent-runtime-core";
|
|
3
|
+
/**
|
|
4
|
+
* Durable zero-service persistence for one Agent Runtime process. Atomic file
|
|
5
|
+
* replacement protects readers from partial JSON, but cross-process resume
|
|
6
|
+
* arbitration requires SqliteRunStore or another CAS-capable adapter.
|
|
7
|
+
*/
|
|
8
|
+
export declare class FileRunStore implements RunStore {
|
|
9
|
+
#private;
|
|
10
|
+
constructor(rootDirectory: string);
|
|
11
|
+
createRun(record: RunRecord): Promise<void>;
|
|
12
|
+
loadRun(runId: string): Promise<RunRecord | null>;
|
|
13
|
+
loadLatestCheckpoint(runId: string): Promise<RunCheckpoint | null>;
|
|
14
|
+
resumeRun(runId: string, resumedAt: string, options?: ResumeRunOptions): Promise<number>;
|
|
15
|
+
saveCheckpoint(checkpoint: RunCheckpoint): Promise<void>;
|
|
16
|
+
suspendRun(runId: string, suspendedAt: string, expectedAttempt: number): Promise<void>;
|
|
17
|
+
completeRun(record: CompletedRunRecord): Promise<void>;
|
|
18
|
+
failRun(runId: string, error: RunError, failedAt: string, expectedAttempt: number): Promise<void>;
|
|
19
|
+
cancelRun(runId: string, cancelledAt: string, expectedAttempt: number): Promise<void>;
|
|
20
|
+
}
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { access, mkdir, open, readFile, rename, unlink, } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { safePathComponent } from "./path-component.js";
|
|
5
|
+
const RUN_FILE = "run.json";
|
|
6
|
+
const CHECKPOINT_FILE = "checkpoint.json";
|
|
7
|
+
const pathExists = async (filePath) => {
|
|
8
|
+
try {
|
|
9
|
+
await access(filePath);
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
if (error?.code === "ENOENT")
|
|
14
|
+
return false;
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
const readJson = async (filePath) => {
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(await readFile(filePath, "utf8"));
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
if (error?.code === "ENOENT")
|
|
24
|
+
return null;
|
|
25
|
+
throw error;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Writes complete JSON documents through a same-directory temporary file and
|
|
30
|
+
* atomic rename, so readers observe either the old document or the new one.
|
|
31
|
+
*/
|
|
32
|
+
const writeJsonAtomically = async (filePath, value) => {
|
|
33
|
+
await mkdir(path.dirname(filePath), { recursive: true });
|
|
34
|
+
const temporaryPath = path.join(path.dirname(filePath), `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`);
|
|
35
|
+
let handle;
|
|
36
|
+
try {
|
|
37
|
+
handle = await open(temporaryPath, "wx", 0o600);
|
|
38
|
+
await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
39
|
+
await handle.sync();
|
|
40
|
+
await handle.close();
|
|
41
|
+
handle = undefined;
|
|
42
|
+
await rename(temporaryPath, filePath);
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
await handle?.close().catch(() => undefined);
|
|
46
|
+
await unlink(temporaryPath).catch(() => undefined);
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Durable zero-service persistence for one Agent Runtime process. Atomic file
|
|
52
|
+
* replacement protects readers from partial JSON, but cross-process resume
|
|
53
|
+
* arbitration requires SqliteRunStore or another CAS-capable adapter.
|
|
54
|
+
*/
|
|
55
|
+
export class FileRunStore {
|
|
56
|
+
#rootDirectory;
|
|
57
|
+
#runLocks = new Map();
|
|
58
|
+
constructor(rootDirectory) {
|
|
59
|
+
if (!rootDirectory.trim())
|
|
60
|
+
throw new Error("FileRunStore requires a root directory.");
|
|
61
|
+
this.#rootDirectory = path.resolve(rootDirectory);
|
|
62
|
+
}
|
|
63
|
+
async createRun(record) {
|
|
64
|
+
return this.#withRunLock(record.runId, async () => {
|
|
65
|
+
const filePath = this.#runFile(record.runId);
|
|
66
|
+
if (await pathExists(filePath))
|
|
67
|
+
throw new Error(`Run already exists: ${record.runId}`);
|
|
68
|
+
await writeJsonAtomically(filePath, record);
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
async loadRun(runId) {
|
|
72
|
+
return readJson(this.#runFile(runId));
|
|
73
|
+
}
|
|
74
|
+
async loadLatestCheckpoint(runId) {
|
|
75
|
+
return readJson(this.#checkpointFile(runId));
|
|
76
|
+
}
|
|
77
|
+
async resumeRun(runId, resumedAt, options) {
|
|
78
|
+
return this.#withRunLock(runId, async () => {
|
|
79
|
+
const existing = await this.#requireRun(runId);
|
|
80
|
+
if (existing.status === "completed" || existing.status === "cancelled") {
|
|
81
|
+
throw new Error(`Run ${runId} is already ${existing.status}`);
|
|
82
|
+
}
|
|
83
|
+
if (existing.status === "running" &&
|
|
84
|
+
options?.allowRunningTakeover !== true) {
|
|
85
|
+
throw new Error(`Run ${runId} is still owned by a running attempt`);
|
|
86
|
+
}
|
|
87
|
+
const attempt = (existing.attempt ?? 1) + 1;
|
|
88
|
+
await writeJsonAtomically(this.#runFile(runId), {
|
|
89
|
+
...existing,
|
|
90
|
+
status: "running",
|
|
91
|
+
attempt,
|
|
92
|
+
updatedAt: resumedAt,
|
|
93
|
+
});
|
|
94
|
+
return attempt;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
async saveCheckpoint(checkpoint) {
|
|
98
|
+
return this.#withRunLock(checkpoint.runId, async () => {
|
|
99
|
+
const run = await this.#requireRun(checkpoint.runId);
|
|
100
|
+
if (run.status !== "created" &&
|
|
101
|
+
run.status !== "running" &&
|
|
102
|
+
run.status !== "suspended") {
|
|
103
|
+
throw new Error(`Cannot checkpoint ${run.status} run ${checkpoint.runId}`);
|
|
104
|
+
}
|
|
105
|
+
if ((checkpoint.attempt ?? 1) !== (run.attempt ?? 1)) {
|
|
106
|
+
throw new Error(`Run ${checkpoint.runId} is owned by another attempt`);
|
|
107
|
+
}
|
|
108
|
+
const current = await this.loadLatestCheckpoint(checkpoint.runId);
|
|
109
|
+
if (current) {
|
|
110
|
+
if (current.sequence === checkpoint.sequence) {
|
|
111
|
+
if (JSON.stringify(current) === JSON.stringify(checkpoint))
|
|
112
|
+
return;
|
|
113
|
+
throw new Error(`Checkpoint sequence or id conflicts for run ${checkpoint.runId}`);
|
|
114
|
+
}
|
|
115
|
+
if (checkpoint.sequence !== current.sequence + 1) {
|
|
116
|
+
throw new Error(`Checkpoint ${checkpoint.sequence} for run ${checkpoint.runId} does not follow committed sequence ${current.sequence}`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
else if (checkpoint.sequence !== 1) {
|
|
120
|
+
throw new Error(`First checkpoint for run ${checkpoint.runId} must have sequence 1`);
|
|
121
|
+
}
|
|
122
|
+
await writeJsonAtomically(this.#checkpointFile(checkpoint.runId), checkpoint);
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
async suspendRun(runId, suspendedAt, expectedAttempt) {
|
|
126
|
+
return this.#withRunLock(runId, async () => {
|
|
127
|
+
const existing = await this.#requireRun(runId);
|
|
128
|
+
if (existing.status === "suspended" &&
|
|
129
|
+
(existing.attempt ?? 1) === expectedAttempt)
|
|
130
|
+
return;
|
|
131
|
+
if (existing.status !== "created" && existing.status !== "running") {
|
|
132
|
+
throw new Error(`Cannot suspend ${existing.status} run ${runId}`);
|
|
133
|
+
}
|
|
134
|
+
if ((existing.attempt ?? 1) !== expectedAttempt) {
|
|
135
|
+
throw new Error(`Run ${runId} is owned by another attempt`);
|
|
136
|
+
}
|
|
137
|
+
await writeJsonAtomically(this.#runFile(runId), {
|
|
138
|
+
...existing,
|
|
139
|
+
status: "suspended",
|
|
140
|
+
updatedAt: suspendedAt,
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
async completeRun(record) {
|
|
145
|
+
return this.#withRunLock(record.runId, async () => {
|
|
146
|
+
const existing = await this.#requireRun(record.runId);
|
|
147
|
+
if (existing.status === "completed") {
|
|
148
|
+
if (JSON.stringify(existing) === JSON.stringify(record))
|
|
149
|
+
return;
|
|
150
|
+
throw new Error(`Run ${record.runId} has conflicting completed data`);
|
|
151
|
+
}
|
|
152
|
+
if (existing.status !== "created" &&
|
|
153
|
+
existing.status !== "running" &&
|
|
154
|
+
existing.status !== "suspended") {
|
|
155
|
+
throw new Error(`Cannot complete ${existing.status} run ${record.runId}`);
|
|
156
|
+
}
|
|
157
|
+
if ((record.attempt ?? 1) !== (existing.attempt ?? 1)) {
|
|
158
|
+
throw new Error(`Run ${record.runId} is owned by another attempt`);
|
|
159
|
+
}
|
|
160
|
+
await writeJsonAtomically(this.#runFile(record.runId), record);
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
async failRun(runId, error, failedAt, expectedAttempt) {
|
|
164
|
+
return this.#withRunLock(runId, async () => {
|
|
165
|
+
const existing = await this.#requireRun(runId);
|
|
166
|
+
if (existing.status !== "created" &&
|
|
167
|
+
existing.status !== "running" &&
|
|
168
|
+
existing.status !== "suspended") {
|
|
169
|
+
throw new Error(`Cannot fail ${existing.status} run ${runId}`);
|
|
170
|
+
}
|
|
171
|
+
if ((existing.attempt ?? 1) !== expectedAttempt) {
|
|
172
|
+
throw new Error(`Run ${runId} is owned by another attempt`);
|
|
173
|
+
}
|
|
174
|
+
const failedRecord = {
|
|
175
|
+
...existing,
|
|
176
|
+
status: "failed",
|
|
177
|
+
updatedAt: failedAt,
|
|
178
|
+
error,
|
|
179
|
+
failedAt,
|
|
180
|
+
};
|
|
181
|
+
await writeJsonAtomically(this.#runFile(runId), failedRecord);
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
async cancelRun(runId, cancelledAt, expectedAttempt) {
|
|
185
|
+
return this.#withRunLock(runId, async () => {
|
|
186
|
+
const existing = await this.#requireRun(runId);
|
|
187
|
+
if (existing.status === "cancelled")
|
|
188
|
+
return;
|
|
189
|
+
if (existing.status !== "created" &&
|
|
190
|
+
existing.status !== "running" &&
|
|
191
|
+
existing.status !== "suspended") {
|
|
192
|
+
throw new Error(`Cannot cancel ${existing.status} run ${runId}`);
|
|
193
|
+
}
|
|
194
|
+
if ((existing.attempt ?? 1) !== expectedAttempt) {
|
|
195
|
+
throw new Error(`Run ${runId} is owned by another attempt`);
|
|
196
|
+
}
|
|
197
|
+
await writeJsonAtomically(this.#runFile(runId), {
|
|
198
|
+
...existing,
|
|
199
|
+
status: "cancelled",
|
|
200
|
+
updatedAt: cancelledAt,
|
|
201
|
+
});
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
async #withRunLock(runId, operation) {
|
|
205
|
+
const previous = this.#runLocks.get(runId) ?? Promise.resolve();
|
|
206
|
+
let release;
|
|
207
|
+
const current = previous.then(() => new Promise((resolve) => {
|
|
208
|
+
release = resolve;
|
|
209
|
+
}));
|
|
210
|
+
this.#runLocks.set(runId, current);
|
|
211
|
+
await previous;
|
|
212
|
+
try {
|
|
213
|
+
return await operation();
|
|
214
|
+
}
|
|
215
|
+
finally {
|
|
216
|
+
release();
|
|
217
|
+
if (this.#runLocks.get(runId) === current)
|
|
218
|
+
this.#runLocks.delete(runId);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
async #requireRun(runId) {
|
|
222
|
+
const record = await this.loadRun(runId);
|
|
223
|
+
if (!record)
|
|
224
|
+
throw new Error(`Run not found: ${runId}`);
|
|
225
|
+
return record;
|
|
226
|
+
}
|
|
227
|
+
#runDirectory(runId) {
|
|
228
|
+
return path.join(this.#rootDirectory, "runs", safePathComponent(runId, "Run id"));
|
|
229
|
+
}
|
|
230
|
+
#runFile(runId) {
|
|
231
|
+
return path.join(this.#runDirectory(runId), RUN_FILE);
|
|
232
|
+
}
|
|
233
|
+
#checkpointFile(runId) {
|
|
234
|
+
return path.join(this.#runDirectory(runId), CHECKPOINT_FILE);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { RunCheckpoint, RunError } from "@clearideas/agent-runtime-contracts";
|
|
2
|
+
import type { CompletedRunRecord, ResumeRunOptions, RunRecord, RunStore } from "@clearideas/agent-runtime-core";
|
|
3
|
+
export type FailedRunRecord = RunRecord & {
|
|
4
|
+
status: "failed";
|
|
5
|
+
error: RunError;
|
|
6
|
+
failedAt: string;
|
|
7
|
+
};
|
|
8
|
+
/** In-process persistence for tests, embedded use, and short-lived local runs. */
|
|
9
|
+
export declare class MemoryRunStore implements RunStore {
|
|
10
|
+
#private;
|
|
11
|
+
createRun(record: RunRecord): Promise<void>;
|
|
12
|
+
loadRun(runId: string): Promise<RunRecord | null>;
|
|
13
|
+
loadLatestCheckpoint(runId: string): Promise<RunCheckpoint | null>;
|
|
14
|
+
resumeRun(runId: string, resumedAt: string, options?: ResumeRunOptions): Promise<number>;
|
|
15
|
+
saveCheckpoint(checkpoint: RunCheckpoint): Promise<void>;
|
|
16
|
+
suspendRun(runId: string, suspendedAt: string, expectedAttempt: number): Promise<void>;
|
|
17
|
+
completeRun(record: CompletedRunRecord): Promise<void>;
|
|
18
|
+
failRun(runId: string, error: RunError, failedAt: string, expectedAttempt: number): Promise<void>;
|
|
19
|
+
cancelRun(runId: string, cancelledAt: string, expectedAttempt: number): Promise<void>;
|
|
20
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
const clone = (value) => structuredClone(value);
|
|
2
|
+
/** In-process persistence for tests, embedded use, and short-lived local runs. */
|
|
3
|
+
export class MemoryRunStore {
|
|
4
|
+
#runs = new Map();
|
|
5
|
+
#checkpoints = new Map();
|
|
6
|
+
async createRun(record) {
|
|
7
|
+
if (this.#runs.has(record.runId)) {
|
|
8
|
+
throw new Error(`Run already exists: ${record.runId}`);
|
|
9
|
+
}
|
|
10
|
+
this.#runs.set(record.runId, clone(record));
|
|
11
|
+
}
|
|
12
|
+
async loadRun(runId) {
|
|
13
|
+
const record = this.#runs.get(runId);
|
|
14
|
+
return record ? clone(record) : null;
|
|
15
|
+
}
|
|
16
|
+
async loadLatestCheckpoint(runId) {
|
|
17
|
+
const checkpoint = this.#checkpoints.get(runId);
|
|
18
|
+
return checkpoint ? clone(checkpoint) : null;
|
|
19
|
+
}
|
|
20
|
+
async resumeRun(runId, resumedAt, options) {
|
|
21
|
+
const existing = this.#requireRun(runId);
|
|
22
|
+
if (existing.status === "completed" || existing.status === "cancelled") {
|
|
23
|
+
throw new Error(`Run ${runId} is already ${existing.status}`);
|
|
24
|
+
}
|
|
25
|
+
if (existing.status === "running" &&
|
|
26
|
+
options?.allowRunningTakeover !== true) {
|
|
27
|
+
throw new Error(`Run ${runId} is still owned by a running attempt`);
|
|
28
|
+
}
|
|
29
|
+
const attempt = (existing.attempt ?? 1) + 1;
|
|
30
|
+
this.#runs.set(runId, {
|
|
31
|
+
...clone(existing),
|
|
32
|
+
status: "running",
|
|
33
|
+
attempt,
|
|
34
|
+
updatedAt: resumedAt,
|
|
35
|
+
});
|
|
36
|
+
return attempt;
|
|
37
|
+
}
|
|
38
|
+
async saveCheckpoint(checkpoint) {
|
|
39
|
+
const run = this.#requireRun(checkpoint.runId);
|
|
40
|
+
if (run.status !== "created" &&
|
|
41
|
+
run.status !== "running" &&
|
|
42
|
+
run.status !== "suspended") {
|
|
43
|
+
throw new Error(`Cannot checkpoint ${run.status} run ${checkpoint.runId}`);
|
|
44
|
+
}
|
|
45
|
+
if ((checkpoint.attempt ?? 1) !== (run.attempt ?? 1)) {
|
|
46
|
+
throw new Error(`Run ${checkpoint.runId} is owned by another attempt`);
|
|
47
|
+
}
|
|
48
|
+
const current = this.#checkpoints.get(checkpoint.runId);
|
|
49
|
+
if (current) {
|
|
50
|
+
if (current.sequence === checkpoint.sequence) {
|
|
51
|
+
if (JSON.stringify(current) === JSON.stringify(checkpoint))
|
|
52
|
+
return;
|
|
53
|
+
throw new Error(`Checkpoint sequence or id conflicts for run ${checkpoint.runId}`);
|
|
54
|
+
}
|
|
55
|
+
if (checkpoint.sequence !== current.sequence + 1) {
|
|
56
|
+
throw new Error(`Checkpoint ${checkpoint.sequence} for run ${checkpoint.runId} does not follow committed sequence ${current.sequence}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
else if (checkpoint.sequence !== 1) {
|
|
60
|
+
throw new Error(`First checkpoint for run ${checkpoint.runId} must have sequence 1`);
|
|
61
|
+
}
|
|
62
|
+
this.#checkpoints.set(checkpoint.runId, clone(checkpoint));
|
|
63
|
+
}
|
|
64
|
+
async suspendRun(runId, suspendedAt, expectedAttempt) {
|
|
65
|
+
const existing = this.#requireRun(runId);
|
|
66
|
+
if (existing.status === "suspended" &&
|
|
67
|
+
(existing.attempt ?? 1) === expectedAttempt)
|
|
68
|
+
return;
|
|
69
|
+
if (existing.status !== "created" && existing.status !== "running") {
|
|
70
|
+
throw new Error(`Cannot suspend ${existing.status} run ${runId}`);
|
|
71
|
+
}
|
|
72
|
+
if ((existing.attempt ?? 1) !== expectedAttempt) {
|
|
73
|
+
throw new Error(`Run ${runId} is owned by another attempt`);
|
|
74
|
+
}
|
|
75
|
+
this.#runs.set(runId, {
|
|
76
|
+
...clone(existing),
|
|
77
|
+
status: "suspended",
|
|
78
|
+
updatedAt: suspendedAt,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
async completeRun(record) {
|
|
82
|
+
const existing = this.#requireRun(record.runId);
|
|
83
|
+
if (existing.status === "completed") {
|
|
84
|
+
if (JSON.stringify(existing) === JSON.stringify(record))
|
|
85
|
+
return;
|
|
86
|
+
throw new Error(`Run ${record.runId} has conflicting completed data`);
|
|
87
|
+
}
|
|
88
|
+
if (existing.status !== "created" &&
|
|
89
|
+
existing.status !== "running" &&
|
|
90
|
+
existing.status !== "suspended") {
|
|
91
|
+
throw new Error(`Cannot complete ${existing.status} run ${record.runId}`);
|
|
92
|
+
}
|
|
93
|
+
if ((record.attempt ?? 1) !== (existing.attempt ?? 1)) {
|
|
94
|
+
throw new Error(`Run ${record.runId} is owned by another attempt`);
|
|
95
|
+
}
|
|
96
|
+
this.#runs.set(record.runId, clone(record));
|
|
97
|
+
}
|
|
98
|
+
async failRun(runId, error, failedAt, expectedAttempt) {
|
|
99
|
+
const existing = this.#requireRun(runId);
|
|
100
|
+
if (existing.status !== "created" &&
|
|
101
|
+
existing.status !== "running" &&
|
|
102
|
+
existing.status !== "suspended") {
|
|
103
|
+
throw new Error(`Cannot fail ${existing.status} run ${runId}`);
|
|
104
|
+
}
|
|
105
|
+
if ((existing.attempt ?? 1) !== expectedAttempt) {
|
|
106
|
+
throw new Error(`Run ${runId} is owned by another attempt`);
|
|
107
|
+
}
|
|
108
|
+
const failedRecord = {
|
|
109
|
+
...existing,
|
|
110
|
+
status: "failed",
|
|
111
|
+
updatedAt: failedAt,
|
|
112
|
+
error: clone(error),
|
|
113
|
+
failedAt,
|
|
114
|
+
};
|
|
115
|
+
this.#runs.set(runId, failedRecord);
|
|
116
|
+
}
|
|
117
|
+
async cancelRun(runId, cancelledAt, expectedAttempt) {
|
|
118
|
+
const existing = this.#requireRun(runId);
|
|
119
|
+
if (existing.status === "cancelled")
|
|
120
|
+
return;
|
|
121
|
+
if (existing.status !== "created" &&
|
|
122
|
+
existing.status !== "running" &&
|
|
123
|
+
existing.status !== "suspended") {
|
|
124
|
+
throw new Error(`Cannot cancel ${existing.status} run ${runId}`);
|
|
125
|
+
}
|
|
126
|
+
if ((existing.attempt ?? 1) !== expectedAttempt) {
|
|
127
|
+
throw new Error(`Run ${runId} is owned by another attempt`);
|
|
128
|
+
}
|
|
129
|
+
this.#runs.set(runId, {
|
|
130
|
+
...existing,
|
|
131
|
+
status: "cancelled",
|
|
132
|
+
updatedAt: cancelledAt,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
#requireRun(runId) {
|
|
136
|
+
const record = this.#runs.get(runId);
|
|
137
|
+
if (!record)
|
|
138
|
+
throw new Error(`Run not found: ${runId}`);
|
|
139
|
+
return record;
|
|
140
|
+
}
|
|
141
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@clearideas/agent-runtime-store-local",
|
|
3
|
+
"version": "0.1.0-alpha.1",
|
|
4
|
+
"description": "Memory, file, console, and JSONL adapters for Clear Ideas Agent Runtime.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "Clear Ideas Incorporated",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/clearideas/agent-runtime.git",
|
|
10
|
+
"directory": "packages/store-local"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "restricted",
|
|
14
|
+
"provenance": false,
|
|
15
|
+
"registry": "https://registry.npmjs.org/"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"NOTICE",
|
|
20
|
+
"README.md"
|
|
21
|
+
],
|
|
22
|
+
"type": "module",
|
|
23
|
+
"main": "dist/index.js",
|
|
24
|
+
"types": "dist/index.d.ts",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"default": "./dist/index.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsc -b tsconfig.json --force",
|
|
33
|
+
"type-check": "tsc -p tsconfig.json --noEmit",
|
|
34
|
+
"test": "vitest run",
|
|
35
|
+
"prepack": "npm run build && node ../../scripts/prepare-package-license.mjs",
|
|
36
|
+
"postpack": "node ../../scripts/cleanup-package-license.mjs"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@clearideas/agent-runtime-contracts": "0.1.0-alpha.1",
|
|
40
|
+
"@clearideas/agent-runtime-core": "0.1.0-alpha.1",
|
|
41
|
+
"yaml": "^2.9.0"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@types/node": "^25.6.0",
|
|
45
|
+
"typescript": "^6.0.3",
|
|
46
|
+
"vitest": "^4.0.18"
|
|
47
|
+
},
|
|
48
|
+
"engines": {
|
|
49
|
+
"node": ">=24"
|
|
50
|
+
},
|
|
51
|
+
"homepage": "https://github.com/clearideas/agent-runtime#readme",
|
|
52
|
+
"bugs": {
|
|
53
|
+
"url": "https://github.com/clearideas/agent-runtime/issues"
|
|
54
|
+
},
|
|
55
|
+
"keywords": [
|
|
56
|
+
"ai",
|
|
57
|
+
"agents",
|
|
58
|
+
"agent-runtime",
|
|
59
|
+
"workflows"
|
|
60
|
+
]
|
|
61
|
+
}
|