@hivemagnus/ardent 3.1.3 → 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 +504 -16
- 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 +16 -9
- package/profiles/assistant/config.yaml +2 -1
package/dist/mattermost.js
CHANGED
|
@@ -3,11 +3,16 @@ import WebSocket from 'ws';
|
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { ChannelCore, DeliveryRejectedError } from './channels.js';
|
|
5
5
|
import { resolveReference } from './config.js';
|
|
6
|
+
import { AttemptError, lastAttemptError, responseFailure, retryWithPolicy } from './retry.js';
|
|
6
7
|
const User = z.object({ id: z.string().min(1), username: z.string().min(1), is_bot: z.boolean().optional() }).passthrough();
|
|
7
8
|
const Post = z.object({ id: z.string().min(1), user_id: z.string().min(1), channel_id: z.string().min(1), message: z.string().default(''), root_id: z.string().nullish().transform(value => value ?? ''), file_ids: z.array(z.string()).default([]), create_at: z.number().int().nonnegative() }).passthrough();
|
|
8
9
|
const Frame = z.object({ event: z.string().optional(), data: z.record(z.string(), z.unknown()).optional(), status: z.string().optional(), seq_reply: z.number().optional() }).passthrough();
|
|
9
10
|
const PostList = z.object({ order: z.array(z.string()), posts: z.record(z.string(), Post) }).passthrough();
|
|
10
11
|
const FileInfo = z.object({ id: z.string(), name: z.string(), mime_type: z.string(), size: z.number().int().nonnegative() }).passthrough();
|
|
12
|
+
/** Durable catch-up boundary of one channel: the newest post up to which every older post was settled. */
|
|
13
|
+
const Boundary = z.object({ last_ms: z.number().int().nonnegative(), last_post_id: z.string().min(1).max(256).nullable() }).strict();
|
|
14
|
+
/** Mattermost and ChatterMost return at most 200 posts per page. */
|
|
15
|
+
const CATCHUP_PAGE = 200;
|
|
11
16
|
function splitMessage(text) {
|
|
12
17
|
if (!text)
|
|
13
18
|
return ['(empty response)'];
|
|
@@ -61,23 +66,41 @@ export class MattermostAdapter {
|
|
|
61
66
|
this.#token = token;
|
|
62
67
|
this.#core = new ChannelCore(runtime, env, jobs);
|
|
63
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* One REST call. A `429` is repeated under the `mattermost` retry policy: a
|
|
71
|
+
* rate-limited request was not processed, so sending it again cannot post a
|
|
72
|
+
* reply twice, and a catch-up burst of replies would otherwise lose every reply
|
|
73
|
+
* past the server's limit. No other failure is repeated.
|
|
74
|
+
*/
|
|
64
75
|
async #request(path, init = {}) {
|
|
65
76
|
const headers = new Headers(init.headers);
|
|
66
77
|
headers.set('Authorization', `Bearer ${this.#token}`);
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
78
|
+
try {
|
|
79
|
+
return await retryWithPolicy('mattermost', async () => {
|
|
80
|
+
const response = await fetch(`${this.#base}/api/v4${path}`, { ...init, headers, signal: init.signal ?? AbortSignal.timeout(10_000), redirect: 'error' });
|
|
81
|
+
if (response.ok)
|
|
82
|
+
return response;
|
|
83
|
+
const message = `Mattermost ${path} returned ${response.status}`;
|
|
84
|
+
await response.body?.cancel();
|
|
85
|
+
if (response.status === 429)
|
|
86
|
+
throw new AttemptError(message, responseFailure(response));
|
|
87
|
+
if (response.status >= 400 && response.status < 500)
|
|
88
|
+
throw new DeliveryRejectedError(message);
|
|
89
|
+
throw new Error(message);
|
|
90
|
+
}, { effect: 'idempotent', signal: init.signal ?? undefined });
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
const last = lastAttemptError(error);
|
|
94
|
+
// A request still rate-limited after its retries was refused, as any other 4xx.
|
|
95
|
+
throw last instanceof AttemptError ? new DeliveryRejectedError(last.message) : last;
|
|
73
96
|
}
|
|
74
|
-
return response;
|
|
75
97
|
}
|
|
76
98
|
async initialize() {
|
|
77
99
|
const me = User.parse(await (await this.#request('/users/me')).json());
|
|
78
100
|
if (me.is_bot === false)
|
|
79
101
|
throw new Error('Mattermost token does not identify a bot');
|
|
80
102
|
this.#me = me;
|
|
103
|
+
this.runtime.store.catchup.closeOpenRuns('mattermost', me.id);
|
|
81
104
|
return { botId: me.id, username: me.username };
|
|
82
105
|
}
|
|
83
106
|
async #attachment(fileId, signal) {
|
|
@@ -100,13 +123,9 @@ export class MattermostAdapter {
|
|
|
100
123
|
const me = this.#me;
|
|
101
124
|
if (!me)
|
|
102
125
|
throw new Error('Mattermost adapter has not initialized');
|
|
103
|
-
if (
|
|
126
|
+
if (!this.#eligible(post, channelType))
|
|
104
127
|
return;
|
|
105
128
|
const isDm = channelType === 'D';
|
|
106
|
-
if (!isDm && !this.config.allowed_channel_ids.includes(post.channel_id))
|
|
107
|
-
return;
|
|
108
|
-
if (!isDm && this.config.require_mention && !mentionPattern(me.username).test(post.message))
|
|
109
|
-
return;
|
|
110
129
|
const attachments = [];
|
|
111
130
|
for (const fileId of post.file_ids.slice(0, 5)) {
|
|
112
131
|
if (signal?.aborted)
|
|
@@ -122,20 +141,78 @@ export class MattermostAdapter {
|
|
|
122
141
|
return;
|
|
123
142
|
if (freshOnly && this.runtime.store.hasInbound('mattermost', me.id, post.id))
|
|
124
143
|
return;
|
|
125
|
-
const cursorKey = `mattermost:${me.id}:${post.channel_id}:last_ms`;
|
|
126
|
-
const previous = Number(this.runtime.store.cursor(cursorKey) ?? '0');
|
|
127
144
|
// A post may be longer than one channel event. Cut it here: a rejected event
|
|
128
145
|
// would fail every later reconciliation that still lists the post.
|
|
129
146
|
const text = (isDm ? post.message : post.message.replace(mentionPattern(me.username), '$1').trim()).slice(0, MAX_EVENT_TEXT);
|
|
130
147
|
const event = { platform: 'mattermost', channel_type: isDm ? 'mattermost_dm' : 'mattermost_channel',
|
|
131
148
|
account: me.id, user: post.user_id, conversation: post.channel_id, thread: post.root_id || null, update_id: post.id, reply_to: post.id, text, attachments, authorized: true, bot_message: false };
|
|
132
|
-
const operation = this.#core.handle(event, async (reply) => this.#deliver(post, channelType, reply)).catch(error => {
|
|
149
|
+
const operation = this.#core.handle(event, async (reply) => this.#deliver({ channel_id: post.channel_id, root_id: post.root_id, id: post.id }, channelType, reply)).catch(error => {
|
|
133
150
|
this.runtime.store.setCursor(`mattermost:${me.id}:last_error`, error instanceof Error ? error.message.slice(0, 500) : 'unknown');
|
|
134
151
|
});
|
|
135
|
-
|
|
152
|
+
// A live post never moves an existing boundary: posts missed before it are
|
|
153
|
+
// still owed to catch-up. It only starts the boundary of a channel not yet seen.
|
|
154
|
+
if (!this.#boundary(post.channel_id))
|
|
155
|
+
this.#saveBoundary(post.channel_id, { last_ms: post.create_at, last_post_id: null });
|
|
136
156
|
this.#pending.add(operation);
|
|
137
157
|
void operation.finally(() => this.#pending.delete(operation));
|
|
138
158
|
}
|
|
159
|
+
#eligible(post, channelType) {
|
|
160
|
+
const me = this.#me;
|
|
161
|
+
if (!me || post.user_id === me.id || !this.config.allowed_user_ids.includes(post.user_id))
|
|
162
|
+
return false;
|
|
163
|
+
if (channelType === 'D')
|
|
164
|
+
return true;
|
|
165
|
+
return this.config.allowed_channel_ids.includes(post.channel_id) && (!this.config.require_mention || mentionPattern(me.username).test(post.message));
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* The saved boundary of a channel, or undefined for a channel never seen. A
|
|
169
|
+
* cursor from Ardent 3.1 (`…:last_ms` only) reads as a boundary without a post
|
|
170
|
+
* id; a newer `…:last_ms` (written by an older runtime after a downgrade) wins.
|
|
171
|
+
*/
|
|
172
|
+
#boundary(channelId) {
|
|
173
|
+
const me = this.#me;
|
|
174
|
+
if (!me)
|
|
175
|
+
throw new Error('Mattermost adapter has not initialized');
|
|
176
|
+
const legacyValue = this.runtime.store.cursor(`mattermost:${me.id}:${channelId}:last_ms`);
|
|
177
|
+
const legacyMs = legacyValue === undefined ? undefined : Number(legacyValue);
|
|
178
|
+
const legacy = legacyMs === undefined ? undefined : { last_ms: Number.isSafeInteger(legacyMs) && legacyMs >= 0 ? legacyMs : 0, last_post_id: null };
|
|
179
|
+
const saved = this.runtime.store.cursor(`mattermost:${me.id}:${channelId}:last`);
|
|
180
|
+
let parsed;
|
|
181
|
+
try {
|
|
182
|
+
parsed = saved === undefined ? undefined : Boundary.parse(JSON.parse(saved));
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
parsed = undefined;
|
|
186
|
+
}
|
|
187
|
+
if (parsed && (!legacy || legacy.last_ms <= parsed.last_ms))
|
|
188
|
+
return parsed;
|
|
189
|
+
if (legacy)
|
|
190
|
+
return legacy;
|
|
191
|
+
return saved === undefined ? undefined : { last_ms: 0, last_post_id: null };
|
|
192
|
+
}
|
|
193
|
+
#saveBoundary(channelId, boundary) {
|
|
194
|
+
const me = this.#me;
|
|
195
|
+
if (!me)
|
|
196
|
+
throw new Error('Mattermost adapter has not initialized');
|
|
197
|
+
this.runtime.store.setCursor(`mattermost:${me.id}:${channelId}:last`, JSON.stringify(Boundary.parse(boundary)));
|
|
198
|
+
// Kept for a runtime rolled back to 3.1, which reads only this key.
|
|
199
|
+
this.runtime.store.setCursor(`mattermost:${me.id}:${channelId}:last_ms`, String(boundary.last_ms));
|
|
200
|
+
}
|
|
201
|
+
async #page(channelId, before, readSignal) {
|
|
202
|
+
const query = `per_page=${CATCHUP_PAGE}${before ? `&before=${encodeURIComponent(before)}` : ''}`;
|
|
203
|
+
const listing = PostList.parse(await (await this.#request(`/channels/${encodeURIComponent(channelId)}/posts?${query}`, { signal: readSignal() })).json());
|
|
204
|
+
// Newest first, as the server orders it; ties break on id so the walk is deterministic.
|
|
205
|
+
return listing.order.map(id => listing.posts[id]).filter((item) => item !== undefined)
|
|
206
|
+
.sort((a, b) => b.create_at - a.create_at || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0));
|
|
207
|
+
}
|
|
208
|
+
/** Answer posts whose task execution recovery resumed or continued, until `signal` aborts. Call after `initialize`. */
|
|
209
|
+
watchRecovered(signal) {
|
|
210
|
+
const me = this.#me;
|
|
211
|
+
if (!me)
|
|
212
|
+
throw new Error('Mattermost adapter has not initialized');
|
|
213
|
+
return this.#core.watchRecovered('mattermost', me.id, target => reply => this.#deliver({ channel_id: target.conversation, root_id: target.thread ?? '',
|
|
214
|
+
id: target.reply_to ?? target.update_id }, target.channel_type === 'mattermost_dm' ? 'D' : 'O', reply), signal);
|
|
215
|
+
}
|
|
139
216
|
async #deliver(post, channelType, reply) {
|
|
140
217
|
const ids = [];
|
|
141
218
|
let last = null;
|
|
@@ -165,6 +242,12 @@ export class MattermostAdapter {
|
|
|
165
242
|
}
|
|
166
243
|
return last;
|
|
167
244
|
}
|
|
245
|
+
/**
|
|
246
|
+
* Catch up every readable channel. Runs when a connection opens (`freshOnly`
|
|
247
|
+
* false: a claimed post without a recorded reply finishes its owner path) and
|
|
248
|
+
* on the 30 s timer (`freshOnly`: claimed posts are left alone). Returns the
|
|
249
|
+
* number of posts handed to the channel path.
|
|
250
|
+
*/
|
|
168
251
|
async reconcile(freshOnly = false, signal) {
|
|
169
252
|
if (freshOnly && this.runtime.store.admissionFence())
|
|
170
253
|
return 0;
|
|
@@ -179,31 +262,150 @@ export class MattermostAdapter {
|
|
|
179
262
|
break;
|
|
180
263
|
if (channel.type !== 'D' && !this.config.allowed_channel_ids.includes(channel.id))
|
|
181
264
|
continue;
|
|
182
|
-
|
|
265
|
+
count += await this.#catchUp(channel.id, channel.type, freshOnly, signal, readSignal);
|
|
266
|
+
}
|
|
267
|
+
return count;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Walk one channel back from its newest post to the saved boundary in pages of
|
|
271
|
+
* 200 (`before=<oldest id seen>`), bounded by `catchup.max_posts` posts from
|
|
272
|
+
* others and twice that many pages' worth of history, then settle
|
|
273
|
+
* the posts oldest first. Each post is claimed atomically, so live events and
|
|
274
|
+
* catch-up can interleave without a second task or reply; a post already
|
|
275
|
+
* claimed is never answered again. The boundary moves only past posts settled
|
|
276
|
+
* in order, so an interrupted walk resumes where it stopped.
|
|
277
|
+
*/
|
|
278
|
+
async #catchUp(channelId, channelType, freshOnly, signal, readSignal) {
|
|
279
|
+
const me = this.#me;
|
|
280
|
+
const store = this.runtime.store;
|
|
281
|
+
const boundary = this.#boundary(channelId);
|
|
282
|
+
if (!boundary) {
|
|
283
|
+
// First sight of a channel: claim its recent history without answering it.
|
|
284
|
+
const posts = await this.#page(channelId, undefined, readSignal);
|
|
285
|
+
if (signal?.aborted)
|
|
286
|
+
return 0;
|
|
287
|
+
for (const post of posts)
|
|
288
|
+
store.claimInbound('mattermost', me.id, post.id);
|
|
289
|
+
const newest = posts[0];
|
|
290
|
+
// An empty channel starts at 0: every later post is new, whatever the clocks say.
|
|
291
|
+
this.#saveBoundary(channelId, newest ? { last_ms: newest.create_at, last_post_id: newest.id } : { last_ms: 0, last_post_id: null });
|
|
292
|
+
return 0;
|
|
293
|
+
}
|
|
294
|
+
// The bot's own replies sit in the same history; they do not use the budget,
|
|
295
|
+
// so the page bound leaves room for one reply per post.
|
|
296
|
+
const maxPosts = this.config.catchup.max_posts;
|
|
297
|
+
const maxPages = 2 * Math.ceil(maxPosts / CATCHUP_PAGE);
|
|
298
|
+
const newer = [];
|
|
299
|
+
let others = 0, pages = 0, reached = false, full = false, gap = null, before;
|
|
300
|
+
while (!reached && !gap) {
|
|
301
|
+
const page = await this.#page(channelId, before, readSignal);
|
|
302
|
+
pages++;
|
|
303
|
+
if (signal?.aborted)
|
|
304
|
+
return 0;
|
|
305
|
+
for (const post of page) {
|
|
306
|
+
if (post.id === boundary.last_post_id || post.create_at < boundary.last_ms) {
|
|
307
|
+
reached = true;
|
|
308
|
+
break;
|
|
309
|
+
}
|
|
310
|
+
if (post.user_id !== me.id && others++ >= maxPosts) {
|
|
311
|
+
full = true;
|
|
312
|
+
break;
|
|
313
|
+
}
|
|
314
|
+
newer.push(post);
|
|
315
|
+
}
|
|
316
|
+
if (reached)
|
|
317
|
+
break;
|
|
318
|
+
if (full) {
|
|
319
|
+
gap = 'walk_bound';
|
|
320
|
+
break;
|
|
321
|
+
}
|
|
322
|
+
if (page.length === 0) {
|
|
323
|
+
// The pivot post vanished, or retention removed history the boundary still needs.
|
|
324
|
+
if (pages > 1 || boundary.last_post_id !== null)
|
|
325
|
+
gap = 'retention';
|
|
326
|
+
break;
|
|
327
|
+
}
|
|
328
|
+
if (page.length < CATCHUP_PAGE) {
|
|
329
|
+
// The start of the channel's history. Without a boundary post id (a 3.1
|
|
330
|
+
// cursor or an empty channel) that is the boundary; otherwise it was removed.
|
|
331
|
+
if (boundary.last_post_id !== null)
|
|
332
|
+
gap = 'retention';
|
|
333
|
+
break;
|
|
334
|
+
}
|
|
335
|
+
if (pages >= maxPages) {
|
|
336
|
+
gap = 'walk_bound';
|
|
337
|
+
break;
|
|
338
|
+
}
|
|
339
|
+
before = page.at(-1)?.id;
|
|
340
|
+
}
|
|
341
|
+
const posts = newer.reverse();
|
|
342
|
+
const oldest = posts[0];
|
|
343
|
+
if (gap)
|
|
344
|
+
store.catchup.recordGap('mattermost', me.id, channelId, boundary.last_ms, oldest?.create_at ?? Date.now(), gap);
|
|
345
|
+
const counters = { recovered: 0, skipped_stale: 0, already_claimed: 0, pages };
|
|
346
|
+
const unsettled = posts.some(post => this.#eligible(post, channelType) && !store.hasInbound('mattermost', me.id, post.id));
|
|
347
|
+
const runId = unsettled || gap ? store.catchup.startRun('mattermost', me.id, channelId, freshOnly ? 'timer' : 'connect', pages) : undefined;
|
|
348
|
+
const staleBefore = Date.now() - this.config.catchup.max_age_hours * 3_600_000;
|
|
349
|
+
const inboundType = channelType === 'D' ? 'mattermost_dm' : 'mattermost_channel';
|
|
350
|
+
let settled;
|
|
351
|
+
// Never move the boundary backwards, for example behind a concurrent reconcile() call.
|
|
352
|
+
const advance = (next) => {
|
|
353
|
+
const current = this.#boundary(channelId);
|
|
354
|
+
if (!current || current.last_ms <= next.last_ms)
|
|
355
|
+
this.#saveBoundary(channelId, next);
|
|
356
|
+
};
|
|
357
|
+
let index = 0;
|
|
358
|
+
let count = 0;
|
|
359
|
+
let failure;
|
|
360
|
+
for (const post of posts) {
|
|
183
361
|
if (signal?.aborted)
|
|
184
362
|
break;
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
363
|
+
try {
|
|
364
|
+
if (!this.#eligible(post, channelType)) { /* not addressed to this bot */ }
|
|
365
|
+
else if (store.hasInbound('mattermost', me.id, post.id)) {
|
|
366
|
+
counters.already_claimed++;
|
|
367
|
+
if (!freshOnly) {
|
|
368
|
+
await this.handlePost(post, channelType, signal, false);
|
|
369
|
+
count++;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
else if (post.create_at < staleBefore) {
|
|
373
|
+
if (store.claimInbound('mattermost', me.id, post.id, inboundType, 'skipped_stale').claimed)
|
|
374
|
+
counters.skipped_stale++;
|
|
375
|
+
else
|
|
376
|
+
counters.already_claimed++;
|
|
377
|
+
}
|
|
378
|
+
else {
|
|
379
|
+
await this.handlePost(post, channelType, signal, freshOnly);
|
|
380
|
+
count++;
|
|
381
|
+
counters.recovered++;
|
|
382
|
+
}
|
|
193
383
|
}
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
384
|
+
catch (error) {
|
|
385
|
+
failure = error;
|
|
386
|
+
break;
|
|
387
|
+
}
|
|
388
|
+
// A post cut short by shutdown may not be claimed yet; it stays owed.
|
|
389
|
+
if (signal?.aborted)
|
|
390
|
+
break;
|
|
391
|
+
settled = { last_ms: post.create_at, last_post_id: post.id };
|
|
392
|
+
if (++index % 50 === 0) {
|
|
393
|
+
advance(settled);
|
|
394
|
+
if (runId !== undefined)
|
|
395
|
+
store.catchup.updateRun(runId, counters);
|
|
205
396
|
}
|
|
206
397
|
}
|
|
398
|
+
const complete = !failure && !signal?.aborted;
|
|
399
|
+
if (settled)
|
|
400
|
+
advance(settled);
|
|
401
|
+
// A recorded gap is permanent. With nothing settled past it, forget the lost
|
|
402
|
+
// boundary post so the next walk does not report the same gap again.
|
|
403
|
+
else if (gap && complete && boundary.last_post_id !== null)
|
|
404
|
+
this.#saveBoundary(channelId, { last_ms: boundary.last_ms, last_post_id: null });
|
|
405
|
+
if (runId !== undefined)
|
|
406
|
+
store.catchup.finishRun(runId, counters, complete ? (gap ? 'gap' : 'complete') : 'interrupted', gap);
|
|
407
|
+
if (failure)
|
|
408
|
+
throw failure;
|
|
207
409
|
return count;
|
|
208
410
|
}
|
|
209
411
|
async connectOnce(signal) {
|
|
@@ -291,6 +493,18 @@ export class MattermostAdapter {
|
|
|
291
493
|
}
|
|
292
494
|
async run(signal) {
|
|
293
495
|
await this.initialize();
|
|
496
|
+
// Tasks execution recovery resumed or continued have no waiting handler; answer them once each.
|
|
497
|
+
const stop = new AbortController();
|
|
498
|
+
const recovered = this.watchRecovered(AbortSignal.any([signal, stop.signal]));
|
|
499
|
+
try {
|
|
500
|
+
await this.#connectLoop(signal);
|
|
501
|
+
}
|
|
502
|
+
finally {
|
|
503
|
+
stop.abort();
|
|
504
|
+
await recovered;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
async #connectLoop(signal) {
|
|
294
508
|
let failures = 0;
|
|
295
509
|
while (!signal.aborted) {
|
|
296
510
|
try {
|
package/dist/mission-tools.js
CHANGED
|
@@ -49,11 +49,38 @@ async function readWorkspaceFile(workspaceDir, path, maxBytes) {
|
|
|
49
49
|
await file.close();
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* Reconcile a call that records a journal event: applied when the task holds
|
|
54
|
+
* exactly that event from after the dispatch, otherwise not applied (the
|
|
55
|
+
* record is a local SQLite write, so its absence is proof).
|
|
56
|
+
*/
|
|
57
|
+
function reconcileEvent(deps, event, note) {
|
|
58
|
+
return async (input, ctx) => {
|
|
59
|
+
const found = deps.store.db.prepare('SELECT 1 FROM events WHERE task_id=? AND kind=? AND created_ms>=? AND detail_json=? LIMIT 1')
|
|
60
|
+
.get(deps.task.id, event, ctx.dispatchedMs, JSON.stringify(input));
|
|
61
|
+
return found ? { status: 'applied', value: { recorded: true, event, note } } : { status: 'not_applied' };
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** Reconcile a registration from the manifest row its idempotency key recorded. */
|
|
65
|
+
function reconcileArtifact(deps) {
|
|
66
|
+
return async (_input, ctx) => {
|
|
67
|
+
const record = deps.artifacts.registeredFor(deps.task.id, ctx.idempotencyKey);
|
|
68
|
+
return record ? { status: 'applied', value: registered(record) } : { status: 'not_applied' };
|
|
69
|
+
};
|
|
70
|
+
}
|
|
52
71
|
/** `development_note`: a durable note about how the agent works. Direct tasks always have it; missions need `tool:development_note`. */
|
|
53
72
|
export function registerDevelopmentNoteTool(registry, deps, contexts) {
|
|
54
73
|
registry.register(defineTool({ name: 'development_note', description: 'Record a durable note about your own development: what you learned, how you work best, or a method you changed. Kinds such as self_understanding, method, lesson. Do not store secrets.',
|
|
55
74
|
input: DevelopmentNoteInput, output: z.object({ id: z.string(), kind: z.string(), title: z.string() }).strict(),
|
|
56
|
-
effect: 'artifact-write', contexts, timeoutMs: 5_000,
|
|
75
|
+
effect: 'artifact-write', contexts, timeoutMs: 5_000,
|
|
76
|
+
// The record is a local SQLite row: its presence or absence proves the outcome.
|
|
77
|
+
reconcile: async (input, ctx) => {
|
|
78
|
+
const raw = deps.store.db.prepare('SELECT id,kind,title FROM development_records WHERE task_id=? AND kind=? AND title=? AND created_ms>=? ORDER BY created_ms LIMIT 1')
|
|
79
|
+
.get(deps.task.id, input.kind, input.title, ctx.dispatchedMs);
|
|
80
|
+
const row = z.object({ id: z.string(), kind: z.string(), title: z.string() }).safeParse(raw);
|
|
81
|
+
return row.success ? { status: 'applied', value: row.data } : { status: 'not_applied' };
|
|
82
|
+
},
|
|
83
|
+
handler: async (input) => {
|
|
57
84
|
const record = deps.development.add({ ...input, author: 'agent', epistemic: 'agent_reported', taskId: deps.task.id });
|
|
58
85
|
return { id: record.id, kind: record.kind, title: record.title };
|
|
59
86
|
} }));
|
|
@@ -73,16 +100,19 @@ export function registerMissionTools(registry, deps, granted) {
|
|
|
73
100
|
registry.register(defineTool({ name: 'team_handoff', description: 'Ask the team coordinator to hand work to another team role. This records the request; the coordinator decides whether to start it.',
|
|
74
101
|
input: z.object({ to_role: line(128), objective: line(4000), deliverables: z.array(line(500)).max(16).optional(), note: line(2000).optional() }).strict(),
|
|
75
102
|
output: Recorded, effect: 'artifact-write', contexts: ['mission'], timeoutMs: 5_000,
|
|
103
|
+
reconcile: reconcileEvent(deps, 'team_handoff', 'Handoff request recorded for the coordinator. Ardent does not start other agents; continue or finish your turn.'),
|
|
76
104
|
handler: async (input) => record('team_handoff', input, 'Handoff request recorded for the coordinator. Ardent does not start other agents; continue or finish your turn.') }));
|
|
77
105
|
if (has('team_ask_user'))
|
|
78
106
|
registry.register(defineTool({ name: 'team_ask_user', description: 'Ask the user a question you cannot answer from the mission or tools. Your turn ends after this call and the task finishes as input_required.',
|
|
79
107
|
input: z.object({ question: line(1200), options: z.array(line(300)).max(8).optional() }).strict(),
|
|
80
108
|
output: Recorded, effect: 'artifact-write', contexts: ['mission'], timeoutMs: 5_000,
|
|
109
|
+
reconcile: reconcileEvent(deps, 'team_ask_user', 'Question recorded. Finish now with one short sentence for the user; the task ends as input_required.'),
|
|
81
110
|
handler: async (input) => record('team_ask_user', input, 'Question recorded. Finish now with one short sentence for the user; the task ends as input_required.') }));
|
|
82
111
|
if (has('team_propose_decision'))
|
|
83
112
|
registry.register(defineTool({ name: 'team_propose_decision', description: 'Propose a team decision for the user to accept. This records the proposal; only the user decides.',
|
|
84
113
|
input: z.object({ title: line(200), statement: line(4000), rationale: line(4000).optional() }).strict(),
|
|
85
114
|
output: Recorded, effect: 'artifact-write', contexts: ['mission'], timeoutMs: 5_000,
|
|
115
|
+
reconcile: reconcileEvent(deps, 'team_propose_decision', 'Decision proposal recorded for the user.'),
|
|
86
116
|
handler: async (input) => record('team_propose_decision', input, 'Decision proposal recorded for the user.') }));
|
|
87
117
|
if (has('artifact_write'))
|
|
88
118
|
registry.register(defineTool({ name: 'artifact_write', description: `Save a deliverable file (Markdown, text, JSON, CSV, SVG, PNG, JPEG, WebP, PDF or DOCX; at most ${formatBytes(maxBytes)}). Give exactly one of text, base64 or workspace_path. Set revises_sha256 to replace an earlier version.`,
|
|
@@ -90,25 +120,31 @@ export function registerMissionTools(registry, deps, granted) {
|
|
|
90
120
|
base64: z.string().min(1).max(Math.ceil(maxBytes / 3) * 4).regex(/^[A-Za-z0-9+/]+={0,2}$/).optional(),
|
|
91
121
|
workspace_path: line(512).optional(), revises_sha256: digest.optional() }).strict()
|
|
92
122
|
.refine(value => [value.text, value.base64, value.workspace_path].filter(item => item !== undefined).length === 1, 'Give exactly one of text, base64 or workspace_path'),
|
|
93
|
-
output: Registered, effect: 'artifact-write', contexts: ['mission'], timeoutMs: 30_000,
|
|
123
|
+
output: Registered, effect: 'artifact-write', contexts: ['mission'], timeoutMs: 30_000,
|
|
124
|
+
// Content-addressed and keyed by the call's idempotency key: a repeat returns the same registration.
|
|
125
|
+
idempotent: true, reconcile: reconcileArtifact(deps), handler: async (input, _signal, ctx) => {
|
|
94
126
|
const bytes = input.text !== undefined ? Buffer.from(input.text, 'utf8')
|
|
95
127
|
: input.base64 !== undefined ? Buffer.from(input.base64, 'base64')
|
|
96
128
|
: await readWorkspaceFile(deps.workspaceDir, input.workspace_path ?? '', maxBytes);
|
|
97
129
|
return registered(await deps.artifacts.register({ taskId: deps.task.id, name: input.name, mime: input.mime, bytes,
|
|
98
|
-
source: 'artifact_write', revisesSha256: input.revises_sha256 }));
|
|
130
|
+
source: 'artifact_write', revisesSha256: input.revises_sha256, idempotencyKey: ctx?.idempotencyKey }));
|
|
99
131
|
} }));
|
|
100
132
|
if (has('development_note'))
|
|
101
133
|
registerDevelopmentNoteTool(registry, deps, ['mission']);
|
|
102
134
|
if (has('document_render'))
|
|
103
135
|
registry.register(defineTool({ name: 'document_render', description: 'Render Markdown to a PDF or DOCX deliverable and save it as an artifact. ```svg blocks become vector figures in PDF only; images are embedded in DOCX only from PNG or JPEG data: URIs.',
|
|
104
136
|
input: z.object({ source_markdown: z.string().min(1).max(MAX_RENDER_SOURCE_CHARS), format: z.enum(['pdf', 'docx']), name: safeName, revises_sha256: digest.optional() }).strict(),
|
|
105
|
-
output: Registered, effect: 'artifact-write', contexts: ['mission'], timeoutMs: 60_000,
|
|
137
|
+
output: Registered, effect: 'artifact-write', contexts: ['mission'], timeoutMs: 60_000,
|
|
138
|
+
idempotent: true, reconcile: reconcileArtifact(deps), handler: async (input, _signal, ctx) => {
|
|
139
|
+
const prior = ctx ? deps.artifacts.registeredFor(deps.task.id, ctx.idempotencyKey) : undefined;
|
|
140
|
+
if (prior)
|
|
141
|
+
return registered(prior);
|
|
106
142
|
const extension = `.${input.format}`;
|
|
107
143
|
const name = input.name.toLowerCase().endsWith(extension) ? input.name : `${input.name.slice(0, 128 - extension.length)}${extension}`;
|
|
108
144
|
const title = name.slice(0, -extension.length);
|
|
109
145
|
const bytes = input.format === 'pdf' ? await renderPdf(input.source_markdown, title) : await renderDocx(input.source_markdown, title);
|
|
110
146
|
return registered(await deps.artifacts.register({ taskId: deps.task.id, name,
|
|
111
147
|
mime: input.format === 'pdf' ? 'application/pdf' : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
112
|
-
bytes, source: 'document_render', revisesSha256: input.revises_sha256 }));
|
|
148
|
+
bytes, source: 'document_render', revisesSha256: input.revises_sha256, idempotencyKey: ctx?.idempotencyKey }));
|
|
113
149
|
} }));
|
|
114
150
|
}
|
package/dist/missions.d.ts
CHANGED
|
@@ -41,6 +41,7 @@ export declare const MissionSubmit: z.ZodObject<{
|
|
|
41
41
|
}, z.core.$strict>>>;
|
|
42
42
|
labels: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
43
43
|
idempotency_key: z.ZodString;
|
|
44
|
+
execution: z.ZodOptional<z.ZodUnknown>;
|
|
44
45
|
}, z.core.$strict>;
|
|
45
46
|
export type MissionSubmit = z.infer<typeof MissionSubmit>;
|
|
46
47
|
/** What a mission task journals at acceptance. */
|
|
@@ -99,4 +100,7 @@ export declare function contextItemMessages(items: readonly ContextItem[]): Chat
|
|
|
99
100
|
* result whose summary is the reply. A recorded team_ask_user makes the result
|
|
100
101
|
* input_required. Artifacts always come from the task's own registrations.
|
|
101
102
|
*/
|
|
102
|
-
export declare function missionTeamResult(store: TaskStore, task: Task, mission: TeamMission, answer: string, submitted?: unknown
|
|
103
|
+
export declare function missionTeamResult(store: TaskStore, task: Task, mission: TeamMission, answer: string, submitted?: unknown, continuation?: {
|
|
104
|
+
priorTaskIds: readonly string[];
|
|
105
|
+
uncertainEffects: readonly string[];
|
|
106
|
+
}): TeamResult;
|
package/dist/missions.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
+
import { ExecutionInput } from './execution.js';
|
|
2
3
|
import { TEAM_VERSION, CoreTeamAction, TeamMission, TeamResult, validateTeamResult } from './team-contract.js';
|
|
3
4
|
/** Bound on the combined text of a mission's context items. */
|
|
4
5
|
export const MAX_CONTEXT_ITEM_BYTES = 64 * 1024;
|
|
@@ -14,7 +15,9 @@ export const MissionSubmit = z.object({
|
|
|
14
15
|
context_items: z.array(ContextItem).max(64).optional()
|
|
15
16
|
.refine(items => Buffer.byteLength((items ?? []).map(item => item.title + item.text).join(''), 'utf8') <= MAX_CONTEXT_ITEM_BYTES, `Context items exceed ${MAX_CONTEXT_ITEM_BYTES / 1024} KiB`),
|
|
16
17
|
labels: MissionLabels.optional(),
|
|
17
|
-
idempotency_key: z.string().min(1).max(128)
|
|
18
|
+
idempotency_key: z.string().min(1).max(128),
|
|
19
|
+
/** Optional execution context v1 (attribution only). An invalid value is treated as absent. */
|
|
20
|
+
execution: ExecutionInput.optional()
|
|
18
21
|
}).strict();
|
|
19
22
|
/** What a mission task journals at acceptance. */
|
|
20
23
|
export const MissionRecord = z.object({ mission: TeamMission, context_items: z.array(ContextItem), labels: z.record(z.string(), z.string()) }).strict();
|
|
@@ -63,9 +66,10 @@ function boundedText(value, bytes) {
|
|
|
63
66
|
* result whose summary is the reply. A recorded team_ask_user makes the result
|
|
64
67
|
* input_required. Artifacts always come from the task's own registrations.
|
|
65
68
|
*/
|
|
66
|
-
export function missionTeamResult(store, task, mission, answer, submitted) {
|
|
69
|
+
export function missionTeamResult(store, task, mission, answer, submitted, continuation = { priorTaskIds: [], uncertainEffects: [] }) {
|
|
67
70
|
const envelope = missionEnvelope(task, mission);
|
|
68
|
-
|
|
71
|
+
// A recovery continuation also reports what the tasks it continues registered and observed.
|
|
72
|
+
const events = [...[...continuation.priorTaskIds].reverse().flatMap(id => store.events(id, 0, 500)), ...store.events(task.id, 0, 500)];
|
|
69
73
|
const byName = new Map();
|
|
70
74
|
for (const event of events) {
|
|
71
75
|
if (event.kind !== 'artifact_registered')
|
|
@@ -99,7 +103,8 @@ export function missionTeamResult(store, task, mission, answer, submitted) {
|
|
|
99
103
|
if (candidate !== undefined && !asked?.success) {
|
|
100
104
|
try {
|
|
101
105
|
const parsed = TeamResult.parse(candidate);
|
|
102
|
-
const merged = { ...parsed, artifacts: [...artifacts, ...parsed.artifacts.filter(item => !byName.has(item.name) && known.has(item.reference))].slice(0, 32)
|
|
106
|
+
const merged = { ...parsed, artifacts: [...artifacts, ...parsed.artifacts.filter(item => !byName.has(item.name) && known.has(item.reference))].slice(0, 32),
|
|
107
|
+
uncertain_effects: [...new Set([...parsed.uncertain_effects, ...continuation.uncertainEffects])] };
|
|
103
108
|
return validateTeamResult(JSON.stringify(merged), envelope, known);
|
|
104
109
|
}
|
|
105
110
|
catch (error) {
|
|
@@ -112,7 +117,7 @@ export function missionTeamResult(store, task, mission, answer, submitted) {
|
|
|
112
117
|
version: TEAM_VERSION, mission_id: mission.id, mission_revision: mission.revision, task_id: task.id,
|
|
113
118
|
outcome: asked?.success ? 'input_required' : 'partial', summary,
|
|
114
119
|
checks: mission.acceptance_criteria.map(criterion => ({ criterion, status: 'unknown', evidence: [] })),
|
|
115
|
-
artifacts, uncertain_effects: [],
|
|
120
|
+
artifacts, uncertain_effects: [...continuation.uncertainEffects],
|
|
116
121
|
...(asked?.success ? { clarification: { missing_fact: boundedText(asked.data.question, 1200),
|
|
117
122
|
choices: (asked.data.options ?? []).slice(0, 8).map((label, index) => ({ id: `option-${index + 1}`, label: boundedText(label, 300) })),
|
|
118
123
|
blocked_task: task.id, intended_respondent: 'operator' } } : {})
|
package/dist/plugin-evidence.js
CHANGED
|
@@ -22,7 +22,8 @@ export async function collectPluginTeamEvidence(runtime, task, envelope, env) {
|
|
|
22
22
|
!envelope.mission.allowed_actions.some(action => action.startsWith(`extension:${plugin.name}:`)))
|
|
23
23
|
throw new Error('Plugin artifact lacks an exact mission grant');
|
|
24
24
|
for (const artifact of evidence.artifacts) {
|
|
25
|
-
|
|
25
|
+
// Stream-hash the bytes: verification never holds a large artifact in memory.
|
|
26
|
+
await runtime.artifacts.verify(artifact.sha256);
|
|
26
27
|
const prior = artifacts.find(item => item.name === artifact.name);
|
|
27
28
|
if (prior && prior.sha256 !== artifact.sha256)
|
|
28
29
|
throw new Error('Conflicting plugin artifact name');
|
package/dist/plugin-sdk.d.ts
CHANGED
|
@@ -4,7 +4,10 @@ export * from './plugins.js';
|
|
|
4
4
|
export * from './config.js';
|
|
5
5
|
export * from './store.js';
|
|
6
6
|
export * from './tools.js';
|
|
7
|
+
export { toolIdempotencyKey } from './tool-scheduler.js';
|
|
7
8
|
export * from './artifacts.js';
|
|
9
|
+
export * from './artifact-manifests.js';
|
|
10
|
+
export { ArtifactTransfers, ArtifactTransferError, ArtifactImportRequestSchema, ArtifactImportSchema, ArtifactImportStateSchema, peerTransferV2, type ArtifactImport, type ArtifactImportRequest, type ArtifactImportState, type ArtifactTransferOptions } from './artifact-transfer.js';
|
|
8
11
|
export * from './a2a-peers.js';
|
|
9
12
|
export * from './codex.js';
|
|
10
13
|
export * from './context.js';
|
package/dist/plugin-sdk.js
CHANGED
|
@@ -4,7 +4,10 @@ export * from './plugins.js';
|
|
|
4
4
|
export * from './config.js';
|
|
5
5
|
export * from './store.js';
|
|
6
6
|
export * from './tools.js';
|
|
7
|
+
export { toolIdempotencyKey } from './tool-scheduler.js';
|
|
7
8
|
export * from './artifacts.js';
|
|
9
|
+
export * from './artifact-manifests.js';
|
|
10
|
+
export { ArtifactTransfers, ArtifactTransferError, ArtifactImportRequestSchema, ArtifactImportSchema, ArtifactImportStateSchema, peerTransferV2 } from './artifact-transfer.js';
|
|
8
11
|
export * from './a2a-peers.js';
|
|
9
12
|
export * from './codex.js';
|
|
10
13
|
export * from './context.js';
|