@hivemagnus/ardent 3.1.4 → 3.2.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/README.md +475 -4
- package/dist/a2a-client.d.ts +26 -4
- package/dist/a2a-client.js +91 -23
- package/dist/a2a-push-inbox.d.ts +2 -0
- package/dist/a2a-push-inbox.js +7 -0
- package/dist/a2a-push.d.ts +1 -1
- package/dist/a2a-push.js +26 -18
- package/dist/a2a-server.d.ts +17 -0
- package/dist/a2a-server.js +91 -14
- package/dist/a2a.d.ts +19 -1
- package/dist/a2a.js +197 -27
- package/dist/api.d.ts +2 -0
- package/dist/api.js +160 -22
- package/dist/artifact-manifests.d.ts +344 -5
- package/dist/artifact-manifests.js +413 -20
- package/dist/artifact-transfer.d.ts +113 -0
- package/dist/artifact-transfer.js +517 -0
- package/dist/artifacts.d.ts +86 -0
- package/dist/artifacts.js +249 -1
- package/dist/backend-events.d.ts +2 -1
- package/dist/backend-events.js +1 -1
- package/dist/channel-catchup.d.ts +67 -0
- package/dist/channel-catchup.js +108 -0
- package/dist/channels.d.ts +35 -0
- package/dist/channels.js +152 -4
- package/dist/cli.js +28 -3
- package/dist/codex-protocol.d.ts +22 -0
- package/dist/codex-protocol.js +19 -0
- package/dist/codex.d.ts +32 -3
- package/dist/codex.js +91 -17
- package/dist/config.d.ts +25 -2
- package/dist/config.js +41 -4
- package/dist/development.d.ts +6 -6
- package/dist/execution-state.d.ts +245 -0
- package/dist/execution-state.js +236 -0
- package/dist/execution.d.ts +135 -0
- package/dist/execution.js +178 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.js +5 -3
- package/dist/job-engine.d.ts +2 -1
- package/dist/job-engine.js +33 -4
- package/dist/lineage.d.ts +106 -0
- package/dist/lineage.js +145 -0
- package/dist/llamacpp.d.ts +32 -2
- package/dist/llamacpp.js +69 -33
- package/dist/mattermost.d.ts +8 -0
- package/dist/mattermost.js +250 -36
- package/dist/mission-tools.js +41 -5
- package/dist/missions.d.ts +5 -1
- package/dist/missions.js +10 -5
- package/dist/plugin-evidence.js +2 -1
- package/dist/plugin-sdk.d.ts +3 -0
- package/dist/plugin-sdk.js +3 -0
- package/dist/plugins.d.ts +108 -2
- package/dist/plugins.js +131 -1
- package/dist/preview.d.ts +1 -0
- package/dist/preview.js +4 -1
- package/dist/recovery.d.ts +155 -0
- package/dist/recovery.js +216 -0
- package/dist/research.d.ts +1 -1
- package/dist/retry.d.ts +143 -0
- package/dist/retry.js +127 -0
- package/dist/runtime.d.ts +56 -4
- package/dist/runtime.js +727 -125
- package/dist/store.d.ts +62 -7
- package/dist/store.js +86 -15
- package/dist/team-artifacts.d.ts +130 -112
- package/dist/team-artifacts.js +123 -151
- package/dist/team-child.d.ts +4 -1
- package/dist/team-child.js +21 -2
- package/dist/team-contract.d.ts +1 -1
- package/dist/telegram.d.ts +2 -0
- package/dist/telegram.js +83 -47
- package/dist/tool-scheduler.d.ts +84 -0
- package/dist/tool-scheduler.js +226 -0
- package/dist/tools.d.ts +78 -4
- package/dist/tools.js +34 -7
- package/package.json +15 -8
- package/profiles/assistant/config.yaml +2 -1
package/dist/artifacts.js
CHANGED
|
@@ -1,13 +1,77 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
2
|
import { constants } from 'node:fs';
|
|
3
|
-
import { mkdir, open, rename, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { lstat, mkdir, open, rename, unlink, writeFile } from 'node:fs/promises';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
|
+
import { Readable, Transform } from 'node:stream';
|
|
5
6
|
import { z } from 'zod';
|
|
6
7
|
export const ArtifactSchema = z.object({ id: z.string().regex(/^[a-f0-9]{64}$/), sha256: z.string().regex(/^[a-f0-9]{64}$/), bytes: z.number().int().nonnegative(), media_type: z.string(), name: z.string() }).strict();
|
|
7
8
|
/** Default per-artifact limit (`artifacts.max_bytes`). */
|
|
8
9
|
export const ARTIFACT_DEFAULT_MAX_BYTES = 2 * 1024 * 1024;
|
|
9
10
|
/** Largest per-artifact limit a profile may configure; also the bound on reading a stored artifact. */
|
|
10
11
|
export const ARTIFACT_MAX_BYTES_LIMIT = 64 * 1024 * 1024;
|
|
12
|
+
const DIGEST = /^[a-f0-9]{64}$/;
|
|
13
|
+
const NAME = /^[A-Za-z0-9._-]{1,128}$/;
|
|
14
|
+
export class ArtifactStoreError extends Error {
|
|
15
|
+
code;
|
|
16
|
+
constructor(message, code) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.name = 'ArtifactStoreError';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function missing(error) {
|
|
23
|
+
return Boolean(error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT');
|
|
24
|
+
}
|
|
25
|
+
function sourceStream(source) {
|
|
26
|
+
if (source instanceof Readable)
|
|
27
|
+
return source;
|
|
28
|
+
if (Symbol.asyncIterator in source)
|
|
29
|
+
return source;
|
|
30
|
+
return Readable.fromWeb(source);
|
|
31
|
+
}
|
|
32
|
+
async function writeAll(file, bytes) {
|
|
33
|
+
for (let offset = 0; offset < bytes.byteLength;)
|
|
34
|
+
offset += (await file.write(bytes, offset, bytes.byteLength - offset)).bytesWritten;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Pass bytes through while hashing them, holding back the last chunk until the
|
|
38
|
+
* digest matches, so a reader of tampered bytes never sees a complete body.
|
|
39
|
+
*/
|
|
40
|
+
function verifyingStream(expected) {
|
|
41
|
+
const hash = createHash('sha256');
|
|
42
|
+
let held;
|
|
43
|
+
return new Transform({
|
|
44
|
+
transform(chunk, _encoding, done) {
|
|
45
|
+
hash.update(chunk);
|
|
46
|
+
const previous = held;
|
|
47
|
+
held = chunk;
|
|
48
|
+
done(null, previous);
|
|
49
|
+
},
|
|
50
|
+
flush(done) {
|
|
51
|
+
if (hash.digest('hex') !== expected) {
|
|
52
|
+
done(new Error('Artifact bytes differ from their ID'));
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
done(null, held);
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Feed `length` bytes of an open file from `start` to `hash` through one
|
|
61
|
+
* reused buffer, so hashing a large file allocates nothing per chunk.
|
|
62
|
+
*/
|
|
63
|
+
export async function hashFileRange(file, hash, start, length) {
|
|
64
|
+
const buffer = Buffer.allocUnsafe(Math.min(Math.max(length, 1), 256 * 1024));
|
|
65
|
+
let done = 0;
|
|
66
|
+
while (done < length) {
|
|
67
|
+
const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.byteLength, length - done), start + done);
|
|
68
|
+
if (bytesRead === 0)
|
|
69
|
+
break;
|
|
70
|
+
hash.update(buffer.subarray(0, bytesRead));
|
|
71
|
+
done += bytesRead;
|
|
72
|
+
}
|
|
73
|
+
return done;
|
|
74
|
+
}
|
|
11
75
|
export function formatBytes(bytes) {
|
|
12
76
|
return bytes % (1024 * 1024) === 0 ? `${bytes / (1024 * 1024)} MiB` : bytes % 1024 === 0 ? `${bytes / 1024} KiB` : `${bytes} bytes`;
|
|
13
77
|
}
|
|
@@ -42,6 +106,190 @@ export class ArtifactStore {
|
|
|
42
106
|
throw error;
|
|
43
107
|
});
|
|
44
108
|
}
|
|
109
|
+
/** Where resumable transfers keep their partial files; inside the store so a finished file is one rename away. */
|
|
110
|
+
get partialDirectory() { return join(this.directory, '.partial'); }
|
|
111
|
+
/** Size of a stored artifact, or undefined when it is absent. Never follows a symbolic link. */
|
|
112
|
+
async stat(id) {
|
|
113
|
+
if (!DIGEST.test(id))
|
|
114
|
+
throw new ArtifactStoreError('Invalid artifact ID', 'INVALID_ARTIFACT');
|
|
115
|
+
try {
|
|
116
|
+
const info = await lstat(join(this.directory, id));
|
|
117
|
+
if (!info.isFile() || info.size > ARTIFACT_MAX_BYTES_LIMIT)
|
|
118
|
+
throw new Error('Artifact file is unsafe');
|
|
119
|
+
return { id, sha256: id, size: info.size };
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (missing(error))
|
|
123
|
+
return undefined;
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Stream stored bytes, optionally one inclusive range. With `verify`, a read
|
|
129
|
+
* of the whole artifact checks the digest as it streams and fails before the
|
|
130
|
+
* final chunk when the bytes differ. A partial read is never verified.
|
|
131
|
+
*/
|
|
132
|
+
async openRead(id, range = {}, options = {}) {
|
|
133
|
+
if (!DIGEST.test(id))
|
|
134
|
+
throw new ArtifactStoreError('Invalid artifact ID', 'INVALID_ARTIFACT');
|
|
135
|
+
let file;
|
|
136
|
+
try {
|
|
137
|
+
file = await open(join(this.directory, id), constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
throw missing(error) ? new ArtifactStoreError('Artifact not found', 'NOT_FOUND') : error;
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
const info = await file.stat();
|
|
144
|
+
if (!info.isFile() || info.size > ARTIFACT_MAX_BYTES_LIMIT)
|
|
145
|
+
throw new Error('Artifact file is unsafe');
|
|
146
|
+
const size = info.size;
|
|
147
|
+
const start = range.start ?? 0;
|
|
148
|
+
const end = range.end ?? size - 1;
|
|
149
|
+
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 ||
|
|
150
|
+
(size === 0 ? start !== 0 || end !== -1 : start > end || end >= size))
|
|
151
|
+
throw new ArtifactStoreError('Artifact range is not satisfiable', 'RANGE_NOT_SATISFIABLE');
|
|
152
|
+
let stream;
|
|
153
|
+
if (size === 0) {
|
|
154
|
+
await file.close();
|
|
155
|
+
stream = Readable.from([]);
|
|
156
|
+
}
|
|
157
|
+
else
|
|
158
|
+
stream = file.createReadStream({ start, end, autoClose: true });
|
|
159
|
+
if (options.verify && start === 0 && end === size - 1) {
|
|
160
|
+
const source = stream;
|
|
161
|
+
const verifier = verifyingStream(id);
|
|
162
|
+
source.once('error', error => verifier.destroy(error));
|
|
163
|
+
verifier.once('close', () => { if (!source.destroyed)
|
|
164
|
+
source.destroy(); });
|
|
165
|
+
stream = source.pipe(verifier);
|
|
166
|
+
}
|
|
167
|
+
return { stream, size, sha256: id, start, end };
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
await file.close().catch(() => { });
|
|
171
|
+
throw error;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/** Hash stored bytes as a stream; throws when they differ from their ID. Returns the size. */
|
|
175
|
+
async verify(id) {
|
|
176
|
+
if (!DIGEST.test(id))
|
|
177
|
+
throw new ArtifactStoreError('Invalid artifact ID', 'INVALID_ARTIFACT');
|
|
178
|
+
let file;
|
|
179
|
+
try {
|
|
180
|
+
file = await open(join(this.directory, id), constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
throw missing(error) ? new ArtifactStoreError('Artifact not found', 'NOT_FOUND') : error;
|
|
184
|
+
}
|
|
185
|
+
try {
|
|
186
|
+
const info = await file.stat();
|
|
187
|
+
if (!info.isFile() || info.size > ARTIFACT_MAX_BYTES_LIMIT)
|
|
188
|
+
throw new Error('Artifact file is unsafe');
|
|
189
|
+
const hash = createHash('sha256');
|
|
190
|
+
if (await hashFileRange(file, hash, 0, info.size) !== info.size || hash.digest('hex') !== id)
|
|
191
|
+
throw new Error('Artifact bytes differ from their ID');
|
|
192
|
+
return info.size;
|
|
193
|
+
}
|
|
194
|
+
finally {
|
|
195
|
+
await file.close();
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Store bytes from a stream without holding them in memory: a private
|
|
200
|
+
* temporary file, an incremental SHA-256, a size bound, fsync, then an atomic
|
|
201
|
+
* rename to the digest. Every refusal happens before the rename.
|
|
202
|
+
*/
|
|
203
|
+
async putStream(source, options) {
|
|
204
|
+
if (!NAME.test(options.name))
|
|
205
|
+
throw new ArtifactStoreError('Invalid artifact name', 'INVALID_ARTIFACT');
|
|
206
|
+
if (options.maxBytes !== undefined && (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 0))
|
|
207
|
+
throw new ArtifactStoreError('Invalid artifact byte limit', 'INVALID_ARTIFACT');
|
|
208
|
+
const limit = Math.min(options.maxBytes ?? this.maxBytes, this.maxBytes);
|
|
209
|
+
if (options.expectedSha256 !== undefined && !DIGEST.test(options.expectedSha256))
|
|
210
|
+
throw new ArtifactStoreError('Invalid expected SHA-256', 'INVALID_ARTIFACT');
|
|
211
|
+
if (options.expectedSize !== undefined && (!Number.isSafeInteger(options.expectedSize) || options.expectedSize < 0))
|
|
212
|
+
throw new ArtifactStoreError('Invalid expected size', 'INVALID_ARTIFACT');
|
|
213
|
+
if (options.expectedSize !== undefined && options.expectedSize > limit)
|
|
214
|
+
throw new ArtifactStoreError(`Artifact exceeds ${formatBytes(limit)}`, 'ARTIFACT_TOO_LARGE');
|
|
215
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
216
|
+
const temporary = join(this.directory, `.put.${randomUUID()}.tmp`);
|
|
217
|
+
const file = await open(temporary, 'wx', 0o600);
|
|
218
|
+
let closed = false;
|
|
219
|
+
try {
|
|
220
|
+
const hash = createHash('sha256');
|
|
221
|
+
let size = 0;
|
|
222
|
+
for await (const chunk of sourceStream(source)) {
|
|
223
|
+
options.signal?.throwIfAborted();
|
|
224
|
+
const bytes = chunk instanceof Uint8Array ? chunk : typeof chunk === 'string' ? Buffer.from(chunk) : undefined;
|
|
225
|
+
if (!bytes)
|
|
226
|
+
throw new ArtifactStoreError('Artifact stream yielded a non-byte chunk', 'INVALID_ARTIFACT');
|
|
227
|
+
size += bytes.byteLength;
|
|
228
|
+
if (size > limit)
|
|
229
|
+
throw new ArtifactStoreError(`Artifact exceeds ${formatBytes(limit)}`, 'ARTIFACT_TOO_LARGE');
|
|
230
|
+
if (options.expectedSize !== undefined && size > options.expectedSize)
|
|
231
|
+
throw new ArtifactStoreError('Artifact is larger than its expected size', 'SIZE_MISMATCH');
|
|
232
|
+
hash.update(bytes);
|
|
233
|
+
options.inspect?.write(bytes);
|
|
234
|
+
await writeAll(file, bytes);
|
|
235
|
+
}
|
|
236
|
+
options.signal?.throwIfAborted();
|
|
237
|
+
options.inspect?.end();
|
|
238
|
+
if (options.expectedSize !== undefined && size !== options.expectedSize)
|
|
239
|
+
throw new ArtifactStoreError('Artifact is smaller than its expected size', 'SIZE_MISMATCH');
|
|
240
|
+
const digest = hash.digest('hex');
|
|
241
|
+
if (options.expectedSha256 !== undefined && digest !== options.expectedSha256)
|
|
242
|
+
throw new ArtifactStoreError('Artifact bytes differ from the expected SHA-256', 'DIGEST_MISMATCH');
|
|
243
|
+
await file.sync();
|
|
244
|
+
closed = true;
|
|
245
|
+
await file.close();
|
|
246
|
+
await rename(temporary, join(this.directory, digest));
|
|
247
|
+
return { id: digest, sha256: digest, bytes: size, media_type: options.mediaType, name: options.name };
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
if (!closed)
|
|
251
|
+
await file.close().catch(() => { });
|
|
252
|
+
await unlink(temporary).catch(() => { });
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Move a complete file (for example a finished transfer's partial file on the
|
|
258
|
+
* same file system) into the store under its digest. The bytes are hashed
|
|
259
|
+
* again first. If the digest is already stored, the file is discarded, so a
|
|
260
|
+
* repeated call is harmless.
|
|
261
|
+
*/
|
|
262
|
+
async adoptFile(path, expected) {
|
|
263
|
+
if (!DIGEST.test(expected.sha256))
|
|
264
|
+
throw new ArtifactStoreError('Invalid artifact ID', 'INVALID_ARTIFACT');
|
|
265
|
+
const existing = await this.stat(expected.sha256);
|
|
266
|
+
if (existing) {
|
|
267
|
+
await unlink(path).catch((error) => { if (!missing(error))
|
|
268
|
+
throw error; });
|
|
269
|
+
if (existing.size !== expected.size)
|
|
270
|
+
throw new Error('Stored artifact size differs from its manifest');
|
|
271
|
+
return existing;
|
|
272
|
+
}
|
|
273
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
274
|
+
const hash = createHash('sha256');
|
|
275
|
+
let size = 0;
|
|
276
|
+
try {
|
|
277
|
+
const info = await file.stat();
|
|
278
|
+
if (!info.isFile() || info.size !== expected.size || info.size > ARTIFACT_MAX_BYTES_LIMIT)
|
|
279
|
+
throw new ArtifactStoreError('File size differs from the expected size', 'SIZE_MISMATCH');
|
|
280
|
+
size = await hashFileRange(file, hash, 0, info.size);
|
|
281
|
+
}
|
|
282
|
+
finally {
|
|
283
|
+
await file.close();
|
|
284
|
+
}
|
|
285
|
+
if (size !== expected.size)
|
|
286
|
+
throw new ArtifactStoreError('File size differs from the expected size', 'SIZE_MISMATCH');
|
|
287
|
+
if (hash.digest('hex') !== expected.sha256)
|
|
288
|
+
throw new ArtifactStoreError('File bytes differ from the expected SHA-256', 'DIGEST_MISMATCH');
|
|
289
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
290
|
+
await rename(path, join(this.directory, expected.sha256));
|
|
291
|
+
return { id: expected.sha256, sha256: expected.sha256, size };
|
|
292
|
+
}
|
|
45
293
|
async get(id) {
|
|
46
294
|
if (!/^[a-f0-9]{64}$/.test(id))
|
|
47
295
|
throw new Error('Invalid artifact ID');
|
package/dist/backend-events.d.ts
CHANGED
|
@@ -18,6 +18,7 @@ export declare const BackendEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
18
18
|
llamacpp: "llamacpp";
|
|
19
19
|
codex: "codex";
|
|
20
20
|
}>;
|
|
21
|
+
id: z.ZodOptional<z.ZodString>;
|
|
21
22
|
name: z.ZodString;
|
|
22
23
|
result: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
23
24
|
ok: z.ZodLiteral<true>;
|
|
@@ -27,8 +28,8 @@ export declare const BackendEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
27
28
|
code: z.ZodString;
|
|
28
29
|
message: z.ZodString;
|
|
29
30
|
effect: z.ZodEnum<{
|
|
30
|
-
none: "none";
|
|
31
31
|
unknown: "unknown";
|
|
32
|
+
none: "none";
|
|
32
33
|
}>;
|
|
33
34
|
}, z.core.$strict>], "ok">;
|
|
34
35
|
}, z.core.$strict>, z.ZodObject<{
|
package/dist/backend-events.js
CHANGED
|
@@ -3,6 +3,6 @@ import { ToolResultSchema } from './tools.js';
|
|
|
3
3
|
export const BackendEventSchema = z.discriminatedUnion('kind', [
|
|
4
4
|
z.object({ kind: z.literal('started'), backend: z.enum(['llamacpp', 'codex']) }).strict(),
|
|
5
5
|
z.object({ kind: z.literal('text_delta'), backend: z.enum(['llamacpp', 'codex']), text: z.string() }).strict(),
|
|
6
|
-
z.object({ kind: z.literal('tool_result'), backend: z.enum(['llamacpp', 'codex']), name: z.string(), result: ToolResultSchema }).strict(),
|
|
6
|
+
z.object({ kind: z.literal('tool_result'), backend: z.enum(['llamacpp', 'codex']), id: z.string().optional(), name: z.string(), result: ToolResultSchema }).strict(),
|
|
7
7
|
z.object({ kind: z.literal('completed'), backend: z.enum(['llamacpp', 'codex']), output_chars: z.number().int().nonnegative(), tool_calls: z.number().int().nonnegative(), reasoning_chars: z.number().int().nonnegative(), usage: z.object({ promptTokens: z.number().optional(), completionTokens: z.number().optional() }).nullable() }).strict()
|
|
8
8
|
]);
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type Database from './sqlite.js';
|
|
3
|
+
/** Why part of a channel's history was not walked: the walk bound was reached, or the server no longer holds it. */
|
|
4
|
+
export type CatchupGapReason = 'walk_bound' | 'retention';
|
|
5
|
+
export type CatchupRunState = 'catching_up' | 'complete' | 'gap' | 'interrupted';
|
|
6
|
+
export type CatchupCounters = {
|
|
7
|
+
recovered: number;
|
|
8
|
+
skipped_stale: number;
|
|
9
|
+
already_claimed: number;
|
|
10
|
+
pages: number;
|
|
11
|
+
};
|
|
12
|
+
export declare const CatchupStatusSchema: z.ZodObject<{
|
|
13
|
+
account: z.ZodString;
|
|
14
|
+
channel: z.ZodString;
|
|
15
|
+
state: z.ZodEnum<{
|
|
16
|
+
catching_up: "catching_up";
|
|
17
|
+
complete: "complete";
|
|
18
|
+
gap: "gap";
|
|
19
|
+
idle: "idle";
|
|
20
|
+
}>;
|
|
21
|
+
recovered: z.ZodNumber;
|
|
22
|
+
skipped_stale: z.ZodNumber;
|
|
23
|
+
already_claimed: z.ZodNumber;
|
|
24
|
+
pages: z.ZodNumber;
|
|
25
|
+
started_ms: z.ZodNullable<z.ZodNumber>;
|
|
26
|
+
finished_ms: z.ZodNullable<z.ZodNumber>;
|
|
27
|
+
gaps: z.ZodNumber;
|
|
28
|
+
last_gap: z.ZodNullable<z.ZodObject<{
|
|
29
|
+
from_ms: z.ZodNumber;
|
|
30
|
+
to_ms: z.ZodNumber;
|
|
31
|
+
reason: z.ZodEnum<{
|
|
32
|
+
walk_bound: "walk_bound";
|
|
33
|
+
retention: "retention";
|
|
34
|
+
}>;
|
|
35
|
+
detected_ms: z.ZodNumber;
|
|
36
|
+
}, z.core.$strip>>;
|
|
37
|
+
}, z.core.$strip>;
|
|
38
|
+
export type CatchupStatus = z.infer<typeof CatchupStatusSchema>;
|
|
39
|
+
declare const GapRow: z.ZodObject<{
|
|
40
|
+
from_ms: z.ZodNumber;
|
|
41
|
+
to_ms: z.ZodNumber;
|
|
42
|
+
reason: z.ZodEnum<{
|
|
43
|
+
walk_bound: "walk_bound";
|
|
44
|
+
retention: "retention";
|
|
45
|
+
}>;
|
|
46
|
+
detected_ms: z.ZodNumber;
|
|
47
|
+
}, z.core.$strip>;
|
|
48
|
+
/**
|
|
49
|
+
* Durable record of channel catch-up walks: one row per walk that found work,
|
|
50
|
+
* and one row per permanent gap. Gaps are facts about history, never retried.
|
|
51
|
+
*/
|
|
52
|
+
export declare class CatchupJournal {
|
|
53
|
+
#private;
|
|
54
|
+
readonly db: Database;
|
|
55
|
+
constructor(db: Database);
|
|
56
|
+
/** Records a permanent gap once; detecting the same gap again changes nothing. */
|
|
57
|
+
recordGap(platform: string, account: string, channel: string, fromMs: number, toMs: number, reason: CatchupGapReason, detectedMs?: number): void;
|
|
58
|
+
gaps(platform: string, account: string, channel: string): z.infer<typeof GapRow>[];
|
|
59
|
+
startRun(platform: string, account: string, channel: string, trigger: 'connect' | 'timer', pages: number): number;
|
|
60
|
+
updateRun(id: number, counters: CatchupCounters): void;
|
|
61
|
+
finishRun(id: number, counters: CatchupCounters, state: Exclude<CatchupRunState, 'catching_up'>, gap: CatchupGapReason | null): void;
|
|
62
|
+
/** A walk that a stopped process left open is closed as interrupted; the next walk resumes from the saved boundary. */
|
|
63
|
+
closeOpenRuns(platform: string, account: string): void;
|
|
64
|
+
/** Latest walk per channel with a saved boundary or a recorded walk. A channel never walked with work is `idle`. */
|
|
65
|
+
status(platform: string, limit?: number): CatchupStatus[];
|
|
66
|
+
}
|
|
67
|
+
export {};
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export const CatchupStatusSchema = z.object({
|
|
3
|
+
account: z.string(), channel: z.string(),
|
|
4
|
+
state: z.enum(['idle', 'catching_up', 'complete', 'gap']),
|
|
5
|
+
recovered: z.number().int(), skipped_stale: z.number().int(), already_claimed: z.number().int(), pages: z.number().int(),
|
|
6
|
+
started_ms: z.number().int().nullable(), finished_ms: z.number().int().nullable(),
|
|
7
|
+
gaps: z.number().int(),
|
|
8
|
+
last_gap: z.object({ from_ms: z.number().int(), to_ms: z.number().int(), reason: z.enum(['walk_bound', 'retention']), detected_ms: z.number().int() }).nullable()
|
|
9
|
+
});
|
|
10
|
+
const GapRow = z.object({ from_ms: z.number().int(), to_ms: z.number().int(), reason: z.enum(['walk_bound', 'retention']), detected_ms: z.number().int() });
|
|
11
|
+
const RunRow = z.object({ account: z.string(), channel: z.string(), state: z.enum(['catching_up', 'complete', 'gap', 'interrupted']),
|
|
12
|
+
recovered: z.number().int(), skipped_stale: z.number().int(), already_claimed: z.number().int(), pages: z.number().int(),
|
|
13
|
+
started_ms: z.number().int(), finished_ms: z.number().int().nullable() });
|
|
14
|
+
/** Finished runs kept per channel; older ones are pruned. */
|
|
15
|
+
const RUNS_KEPT = 100;
|
|
16
|
+
/**
|
|
17
|
+
* Durable record of channel catch-up walks: one row per walk that found work,
|
|
18
|
+
* and one row per permanent gap. Gaps are facts about history, never retried.
|
|
19
|
+
*/
|
|
20
|
+
export class CatchupJournal {
|
|
21
|
+
db;
|
|
22
|
+
constructor(db) {
|
|
23
|
+
this.db = db;
|
|
24
|
+
db.exec(`CREATE TABLE IF NOT EXISTS channel_catchup_gaps (
|
|
25
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT, platform TEXT NOT NULL, account TEXT NOT NULL, channel TEXT NOT NULL,
|
|
26
|
+
from_ms INTEGER NOT NULL, to_ms INTEGER NOT NULL, reason TEXT NOT NULL CHECK(reason IN ('walk_bound','retention')),
|
|
27
|
+
detected_ms INTEGER NOT NULL, UNIQUE(platform, account, channel, from_ms, reason));
|
|
28
|
+
CREATE TABLE IF NOT EXISTS channel_catchup_runs (
|
|
29
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT, platform TEXT NOT NULL, account TEXT NOT NULL, channel TEXT NOT NULL,
|
|
30
|
+
trigger TEXT NOT NULL CHECK(trigger IN ('connect','timer')),
|
|
31
|
+
state TEXT NOT NULL CHECK(state IN ('catching_up','complete','gap','interrupted')),
|
|
32
|
+
started_ms INTEGER NOT NULL, finished_ms INTEGER,
|
|
33
|
+
recovered INTEGER NOT NULL DEFAULT 0, skipped_stale INTEGER NOT NULL DEFAULT 0,
|
|
34
|
+
already_claimed INTEGER NOT NULL DEFAULT 0, pages INTEGER NOT NULL DEFAULT 0,
|
|
35
|
+
gap TEXT CHECK(gap IS NULL OR gap IN ('walk_bound','retention')));
|
|
36
|
+
CREATE INDEX IF NOT EXISTS channel_catchup_runs_channel ON channel_catchup_runs(platform, account, channel, id);`);
|
|
37
|
+
this.#migrateReconcileGaps();
|
|
38
|
+
}
|
|
39
|
+
/** Ardent 3.1 recorded an over-long reconcile window as an unread `…:reconcile_gap` cursor. Move each into the gap table once. */
|
|
40
|
+
#migrateReconcileGaps() {
|
|
41
|
+
const rows = z.array(z.object({ key: z.string(), value: z.string(), updated_ms: z.number().int() }))
|
|
42
|
+
.parse(this.db.prepare("SELECT key,value,updated_ms FROM channel_cursors WHERE key LIKE 'mattermost:%:%:reconcile_gap'").all());
|
|
43
|
+
if (!rows.length)
|
|
44
|
+
return;
|
|
45
|
+
this.db.transaction(() => {
|
|
46
|
+
for (const row of rows) {
|
|
47
|
+
const [, account, channel] = row.key.split(':');
|
|
48
|
+
const range = /^(\d+):(\d+)$/.exec(row.value);
|
|
49
|
+
if (account && channel && range)
|
|
50
|
+
this.recordGap('mattermost', account, channel, Number(range[1]), Number(range[2]), 'walk_bound', row.updated_ms);
|
|
51
|
+
this.db.prepare('DELETE FROM channel_cursors WHERE key=?').run(row.key);
|
|
52
|
+
}
|
|
53
|
+
})();
|
|
54
|
+
}
|
|
55
|
+
/** Records a permanent gap once; detecting the same gap again changes nothing. */
|
|
56
|
+
recordGap(platform, account, channel, fromMs, toMs, reason, detectedMs = Date.now()) {
|
|
57
|
+
this.db.prepare(`INSERT INTO channel_catchup_gaps(platform,account,channel,from_ms,to_ms,reason,detected_ms) VALUES (?,?,?,?,?,?,?)
|
|
58
|
+
ON CONFLICT(platform,account,channel,from_ms,reason) DO NOTHING`).run(platform, account, channel, fromMs, Math.max(fromMs, toMs), reason, detectedMs);
|
|
59
|
+
}
|
|
60
|
+
gaps(platform, account, channel) {
|
|
61
|
+
return z.array(GapRow).parse(this.db.prepare('SELECT from_ms,to_ms,reason,detected_ms FROM channel_catchup_gaps WHERE platform=? AND account=? AND channel=? ORDER BY id').all(platform, account, channel));
|
|
62
|
+
}
|
|
63
|
+
startRun(platform, account, channel, trigger, pages) {
|
|
64
|
+
const result = this.db.prepare(`INSERT INTO channel_catchup_runs(platform,account,channel,trigger,state,started_ms,pages) VALUES (?,?,?,?,'catching_up',?,?)`)
|
|
65
|
+
.run(platform, account, channel, trigger, Date.now(), pages);
|
|
66
|
+
return Number(result.lastInsertRowid);
|
|
67
|
+
}
|
|
68
|
+
updateRun(id, counters) {
|
|
69
|
+
this.db.prepare('UPDATE channel_catchup_runs SET recovered=?,skipped_stale=?,already_claimed=?,pages=? WHERE id=?')
|
|
70
|
+
.run(counters.recovered, counters.skipped_stale, counters.already_claimed, counters.pages, id);
|
|
71
|
+
}
|
|
72
|
+
finishRun(id, counters, state, gap) {
|
|
73
|
+
this.db.transaction(() => {
|
|
74
|
+
this.db.prepare('UPDATE channel_catchup_runs SET recovered=?,skipped_stale=?,already_claimed=?,pages=?,state=?,gap=?,finished_ms=? WHERE id=?')
|
|
75
|
+
.run(counters.recovered, counters.skipped_stale, counters.already_claimed, counters.pages, state, gap, Date.now(), id);
|
|
76
|
+
this.db.prepare(`DELETE FROM channel_catchup_runs WHERE id IN (SELECT r.id FROM channel_catchup_runs r JOIN channel_catchup_runs c
|
|
77
|
+
ON c.platform=r.platform AND c.account=r.account AND c.channel=r.channel WHERE c.id=? AND r.finished_ms IS NOT NULL
|
|
78
|
+
ORDER BY r.id DESC LIMIT -1 OFFSET ?)`).run(id, RUNS_KEPT);
|
|
79
|
+
})();
|
|
80
|
+
}
|
|
81
|
+
/** A walk that a stopped process left open is closed as interrupted; the next walk resumes from the saved boundary. */
|
|
82
|
+
closeOpenRuns(platform, account) {
|
|
83
|
+
this.db.prepare("UPDATE channel_catchup_runs SET state='interrupted',finished_ms=? WHERE platform=? AND account=? AND finished_ms IS NULL").run(Date.now(), platform, account);
|
|
84
|
+
}
|
|
85
|
+
/** Latest walk per channel with a saved boundary or a recorded walk. A channel never walked with work is `idle`. */
|
|
86
|
+
status(platform, limit = 200) {
|
|
87
|
+
const channels = new Map();
|
|
88
|
+
const keys = z.array(z.object({ key: z.string() })).parse(this.db.prepare(`SELECT key FROM channel_cursors WHERE key LIKE ? OR key LIKE ? ORDER BY key LIMIT ?`)
|
|
89
|
+
.all(`${platform}:%:%:last`, `${platform}:%:%:last_ms`, limit * 2));
|
|
90
|
+
for (const { key } of keys) {
|
|
91
|
+
const parts = key.split(':');
|
|
92
|
+
if (parts.length === 4 && parts[1] && parts[2])
|
|
93
|
+
channels.set(`${parts[1]}:${parts[2]}`, { account: parts[1], channel: parts[2] });
|
|
94
|
+
}
|
|
95
|
+
const runs = z.array(RunRow).parse(this.db.prepare(`SELECT account,channel,state,recovered,skipped_stale,already_claimed,pages,started_ms,finished_ms
|
|
96
|
+
FROM channel_catchup_runs WHERE id IN (SELECT max(id) FROM channel_catchup_runs WHERE platform=? GROUP BY account,channel)`).all(platform));
|
|
97
|
+
const latest = new Map(runs.map(run => [`${run.account}:${run.channel}`, run]));
|
|
98
|
+
for (const run of runs)
|
|
99
|
+
channels.set(`${run.account}:${run.channel}`, { account: run.account, channel: run.channel });
|
|
100
|
+
return [...channels.values()].slice(0, limit).map(({ account, channel }) => {
|
|
101
|
+
const run = latest.get(`${account}:${channel}`);
|
|
102
|
+
const gaps = this.gaps(platform, account, channel);
|
|
103
|
+
return { account, channel, state: !run || run.state === 'interrupted' ? 'idle' : run.state,
|
|
104
|
+
recovered: run?.recovered ?? 0, skipped_stale: run?.skipped_stale ?? 0, already_claimed: run?.already_claimed ?? 0, pages: run?.pages ?? 0,
|
|
105
|
+
started_ms: run?.started_ms ?? null, finished_ms: run?.finished_ms ?? null, gaps: gaps.length, last_gap: gaps.at(-1) ?? null };
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
}
|
package/dist/channels.d.ts
CHANGED
|
@@ -30,6 +30,27 @@ export declare const ChannelEvent: z.ZodObject<{
|
|
|
30
30
|
bot_message: z.ZodBoolean;
|
|
31
31
|
}, z.core.$strict>;
|
|
32
32
|
export type ChannelEvent = z.infer<typeof ChannelEvent>;
|
|
33
|
+
/** Where a reply to an inbound update goes; recorded with the inbound claim so recovered tasks can still answer. */
|
|
34
|
+
export declare const ReplyTarget: z.ZodObject<{
|
|
35
|
+
thread: z.ZodNullable<z.ZodString>;
|
|
36
|
+
account: z.ZodString;
|
|
37
|
+
user: z.ZodString;
|
|
38
|
+
channel_type: z.ZodOptional<z.ZodEnum<{
|
|
39
|
+
telegram_private: "telegram_private";
|
|
40
|
+
telegram_group: "telegram_group";
|
|
41
|
+
telegram_supergroup: "telegram_supergroup";
|
|
42
|
+
mattermost_dm: "mattermost_dm";
|
|
43
|
+
mattermost_channel: "mattermost_channel";
|
|
44
|
+
}>>;
|
|
45
|
+
conversation: z.ZodString;
|
|
46
|
+
platform: z.ZodEnum<{
|
|
47
|
+
telegram: "telegram";
|
|
48
|
+
mattermost: "mattermost";
|
|
49
|
+
}>;
|
|
50
|
+
update_id: z.ZodString;
|
|
51
|
+
reply_to: z.ZodNullable<z.ZodString>;
|
|
52
|
+
}, z.core.$strict>;
|
|
53
|
+
export type ReplyTarget = z.infer<typeof ReplyTarget>;
|
|
33
54
|
export type ChannelReply = {
|
|
34
55
|
text: string;
|
|
35
56
|
taskId: string | null;
|
|
@@ -44,6 +65,20 @@ export declare class ChannelCore {
|
|
|
44
65
|
readonly env: NodeJS.ProcessEnv;
|
|
45
66
|
readonly jobs?: JobEngine | undefined;
|
|
46
67
|
constructor(runtime: ArdentRuntime, env?: NodeJS.ProcessEnv, jobs?: JobEngine | undefined);
|
|
68
|
+
/**
|
|
69
|
+
* Answer the updates whose task execution recovery resumed, settled or
|
|
70
|
+
* continued after a restart, once each. A recovered task has no in-process
|
|
71
|
+
* handler waiting for it, so this waits for it (or for its continuation) and
|
|
72
|
+
* then sends through the same record-before-send path: an update that
|
|
73
|
+
* already has a delivery is never sent again. Call at adapter start and
|
|
74
|
+
* whenever `runtime.onTaskSettled` fires. Returns the replies sent.
|
|
75
|
+
*/
|
|
76
|
+
deliverRecovered(platform: string, account: string, deliverFor: (target: ReplyTarget) => ChannelDelivery): Promise<number>;
|
|
77
|
+
/**
|
|
78
|
+
* Keep answering recovered updates until `signal` aborts: once now, then
|
|
79
|
+
* after every task this runtime settles. Resolves when stopped and idle.
|
|
80
|
+
*/
|
|
81
|
+
watchRecovered(platform: string, account: string, deliverFor: (target: ReplyTarget) => ChannelDelivery, signal: AbortSignal): Promise<void>;
|
|
47
82
|
handle(raw: unknown, deliver: ChannelDelivery): Promise<{
|
|
48
83
|
duplicate: boolean;
|
|
49
84
|
taskId: string | null;
|