@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/team-artifacts.js
CHANGED
|
@@ -1,36 +1,40 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
import {
|
|
4
|
-
import { ArdentA2AClient } from './a2a-client.js';
|
|
3
|
+
import { ARTIFACT_TRANSFER_ERRORS, ARTIFACT_TRANSFER_V1_MAX_BYTES, ARTIFACT_TRANSFER_V2_URN } from '@hivemagnus/hive-common/artifact';
|
|
5
4
|
import { collectPluginTeamEvidence } from './plugin-evidence.js';
|
|
5
|
+
import { ARTIFACT_MAX_BYTES_LIMIT } from './artifacts.js';
|
|
6
|
+
import { ArtifactManifest11Schema, ArtifactManifestSchema, ArtifactRenditionSchema, manifestV11, TeamArtifactManifestSchema } from './artifact-manifests.js';
|
|
7
|
+
export { TeamArtifactManifestSchema } from './artifact-manifests.js';
|
|
6
8
|
const digest = z.string().regex(/^[a-f0-9]{64}$/);
|
|
7
9
|
const identifier = z.string().regex(/^[a-f0-9]{32}$/);
|
|
8
10
|
const safeName = z.string().regex(/^[A-Za-z0-9._-]{1,128}$/);
|
|
9
|
-
const Manifest =
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
supersedes_sha256: digest.nullable(), acceptance_status: z.enum(['unreviewed', 'approved', 'partial', 'rejected']),
|
|
14
|
-
name: safeName, mime: z.string().min(1), sha256: digest, size: z.number().int().min(0).max(2 * 1024 * 1024),
|
|
15
|
-
created_at: z.number().finite(), expires_at: z.number().finite(),
|
|
16
|
-
provenance: z.object({ producer: z.string().min(1), source_id: z.string(), producer_task_id: z.string().min(1),
|
|
17
|
-
lineage: z.array(z.object({ producer: z.string().min(1), source_id: z.string() }).strict()).min(1).max(4) }).strict(),
|
|
18
|
-
recovery: z.object({ on_expiry: z.literal('request_verified_reexport') }).strict(), artifact_id: identifier
|
|
19
|
-
}).strict();
|
|
20
|
-
/** Artifact manifest schema shared by peer exports and the local artifact registry. */
|
|
21
|
-
export const TeamArtifactManifestSchema = Manifest;
|
|
11
|
+
const Manifest = TeamArtifactManifestSchema;
|
|
12
|
+
/** An export manifest as stored: 1.0 for a v1-sized export, 1.1 above 2 MiB or for a rendition. */
|
|
13
|
+
const StoredManifest = z.discriminatedUnion('schema_version', [ArtifactManifestSchema, ArtifactManifest11Schema]);
|
|
14
|
+
/** The v1 transfer descriptor: one A2A text part, at most 2 MiB. Unchanged by transfer v2. */
|
|
22
15
|
export const TeamArtifactDescriptorSchema = z.object({ artifact_id: identifier, name: safeName, mime: z.string().min(1), sha256: digest,
|
|
23
|
-
size: z.number().int().min(0).max(
|
|
16
|
+
size: z.number().int().min(0).max(ARTIFACT_TRANSFER_V1_MAX_BYTES), producer_task_id: z.string().min(1), artifact_manifest: Manifest }).strict();
|
|
17
|
+
const teamPath = (suffix) => z.string().max(600).regex(new RegExp(`^/team/artifacts/[a-f0-9]{32}${suffix}\\?context=[A-Za-z0-9%._~-]{1,400}$`));
|
|
18
|
+
/**
|
|
19
|
+
* The transfer-v2 descriptor: an A2A data part with media type
|
|
20
|
+
* `ARTIFACT_TRANSFER_V2_MEDIA_TYPE`. Paths resolve against the exporting
|
|
21
|
+
* peer's pinned A2A origin.
|
|
22
|
+
*/
|
|
23
|
+
export const TeamArtifactDescriptorV2Schema = z.object({ manifest_1_1: ArtifactManifest11Schema, content_path: teamPath(''),
|
|
24
|
+
renditions_path: teamPath('/renditions'), size: z.number().int().min(0).max(ARTIFACT_MAX_BYTES_LIMIT), sha256: digest }).strict()
|
|
25
|
+
.refine(value => value.size === value.manifest_1_1.size && value.sha256 === value.manifest_1_1.sha256, 'Descriptor differs from its manifest');
|
|
26
|
+
/** The explicit result a v1 consumer receives for an export larger than the v1 limit. */
|
|
27
|
+
export const TeamArtifactRequiresV2Schema = z.object({ error: z.literal(ARTIFACT_TRANSFER_ERRORS.requiresV2), capability: z.literal(ARTIFACT_TRANSFER_V2_URN),
|
|
28
|
+
message: z.string(), artifact_id: identifier, name: safeName, mime: z.string().min(1), sha256: digest,
|
|
29
|
+
size: z.number().int().min(0).max(ARTIFACT_MAX_BYTES_LIMIT), producer_task_id: z.string().min(1) }).strict();
|
|
24
30
|
const LocalRow = z.object({ id: identifier, peer: z.string(), context_id: z.string(), a2a_task_id: z.string(),
|
|
25
31
|
digest, name: safeName, mime: z.string(), size: z.number(), manifest_json: z.string(), status: z.string(), expires: z.number() });
|
|
26
32
|
const TransferRow = z.object({ id: digest, owner: z.string(), local_task_id: z.string(), peer: z.string(),
|
|
27
33
|
remote_task_id: z.string(), remote_context_id: z.string(), remote_artifact_id: identifier,
|
|
28
34
|
digest, manifest_json: z.string(), status: z.string() });
|
|
29
|
-
const MAX_BYTES = 2 * 1024 * 1024;
|
|
30
35
|
const TTL_SECONDS = 7 * 24 * 3600;
|
|
31
|
-
function
|
|
32
|
-
|
|
33
|
-
return task.artifacts.flatMap(artifact => artifact.parts.flatMap(part => part.content?.$case === 'text' && typeof part.content.value === 'string' ? [part.content.value] : []));
|
|
36
|
+
function contentPath(id, contextId, suffix = '') {
|
|
37
|
+
return `/team/artifacts/${id}${suffix}?context=${encodeURIComponent(contextId)}`;
|
|
34
38
|
}
|
|
35
39
|
/** Peer artifact receipts. A transfer is retained evidence, never a delivery claim. */
|
|
36
40
|
export class TeamArtifacts {
|
|
@@ -74,37 +78,78 @@ export class TeamArtifacts {
|
|
|
74
78
|
entries.push(...extensions.artifacts.map(item => ({ name: item.name, mime: item.mime, digest: item.sha256, producer: item.producer, sourceId: item.source })));
|
|
75
79
|
const result = [];
|
|
76
80
|
for (const entry of entries) {
|
|
77
|
-
const
|
|
78
|
-
const
|
|
79
|
-
if (
|
|
80
|
-
throw new Error('Team artifact
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
81
|
+
const row = await this.#export(bound.caller, bound.context_id, a2aTaskId, entry);
|
|
82
|
+
const exported = this.#exported(row);
|
|
83
|
+
if (!exported)
|
|
84
|
+
throw new Error('Team artifact export is inconsistent');
|
|
85
|
+
result.push(exported);
|
|
86
|
+
// Renditions are exported with their original so a v2 peer can choose one; they are listed, not announced.
|
|
87
|
+
for (const rendition of (await this.runtime.artifactManifests.renditions(entry.digest)) ?? []) {
|
|
88
|
+
if (rendition.role === 'original' || rendition.sha256 === entry.digest)
|
|
89
|
+
continue;
|
|
90
|
+
const record = this.runtime.artifactManifests.manifestV2(rendition.sha256);
|
|
91
|
+
if (!record?.manifest.rendition)
|
|
92
|
+
continue;
|
|
93
|
+
await this.#export(bound.caller, bound.context_id, a2aTaskId, { name: record.manifest.name, mime: record.manifest.mime,
|
|
94
|
+
digest: rendition.sha256, producer: record.manifest.provenance.producer, sourceId: record.manifest.provenance.source_id,
|
|
95
|
+
rendition: record.manifest.rendition });
|
|
88
96
|
}
|
|
89
|
-
const id = randomBytes(16).toString('hex');
|
|
90
|
-
const created = Date.now() / 1000;
|
|
91
|
-
const manifest = {
|
|
92
|
-
schema_version: '1.0', revision: 1, source_revision: entry.digest,
|
|
93
|
-
visibility: 'private', license: 'NOASSERTION', preview: { mode: 'download_only', mime: entry.mime },
|
|
94
|
-
supersedes_sha256: null, acceptance_status: 'unreviewed', name: entry.name, mime: entry.mime,
|
|
95
|
-
sha256: entry.digest, size, created_at: created, expires_at: created + TTL_SECONDS,
|
|
96
|
-
provenance: { producer: entry.producer, source_id: entry.sourceId, producer_task_id: a2aTaskId,
|
|
97
|
-
lineage: [{ producer: entry.producer, source_id: entry.sourceId }] },
|
|
98
|
-
recovery: { on_expiry: 'request_verified_reexport' }, artifact_id: id
|
|
99
|
-
};
|
|
100
|
-
db.prepare(`INSERT INTO a2a_team_artifacts(id,peer,context_id,a2a_task_id,digest,name,mime,size,manifest_json,status,expires)
|
|
101
|
-
VALUES (?,?,?,?,?,?,?,?,?,'available',?)`).run(id, bound.caller, bound.context_id, a2aTaskId, entry.digest, entry.name, entry.mime, size, JSON.stringify(manifest), manifest.expires_at);
|
|
102
|
-
result.push({ artifact_id: id, name: entry.name, mime: entry.mime, sha256: entry.digest, size,
|
|
103
|
-
producer_task_id: a2aTaskId, artifact_manifest: manifest });
|
|
104
97
|
}
|
|
105
98
|
return result;
|
|
106
99
|
}
|
|
107
|
-
|
|
100
|
+
/** Record one export row, or return the current one for the same task, digest and name. */
|
|
101
|
+
async #export(peer, contextId, a2aTaskId, entry) {
|
|
102
|
+
const db = this.runtime.store.db;
|
|
103
|
+
// Hash the stored bytes as a stream: the export never holds the artifact in memory.
|
|
104
|
+
const size = await this.runtime.artifacts.verify(entry.digest);
|
|
105
|
+
if (size > this.runtime.artifacts.maxBytes)
|
|
106
|
+
throw new Error('Team artifact exceeds the byte limit');
|
|
107
|
+
const previous = db.prepare(`SELECT * FROM a2a_team_artifacts WHERE a2a_task_id=? AND digest=? AND name=? AND status='available' AND expires>?`)
|
|
108
|
+
.get(a2aTaskId, entry.digest, entry.name, Date.now() / 1000);
|
|
109
|
+
if (previous)
|
|
110
|
+
return LocalRow.parse(previous);
|
|
111
|
+
const id = randomBytes(16).toString('hex');
|
|
112
|
+
const created = Date.now() / 1000;
|
|
113
|
+
const base = {
|
|
114
|
+
revision: 1, source_revision: entry.digest,
|
|
115
|
+
visibility: 'private', license: 'NOASSERTION', preview: { mode: 'download_only', mime: entry.mime },
|
|
116
|
+
supersedes_sha256: null, acceptance_status: 'unreviewed', name: entry.name, mime: entry.mime,
|
|
117
|
+
sha256: entry.digest, size, created_at: created, expires_at: created + TTL_SECONDS,
|
|
118
|
+
provenance: { producer: entry.producer, source_id: entry.sourceId, producer_task_id: a2aTaskId,
|
|
119
|
+
lineage: [{ producer: entry.producer, source_id: entry.sourceId }] },
|
|
120
|
+
recovery: { on_expiry: 'request_verified_reexport' }, artifact_id: id
|
|
121
|
+
};
|
|
122
|
+
// A v1-sized original keeps the exact 1.0 manifest v1 consumers verify.
|
|
123
|
+
const manifest = size <= ARTIFACT_TRANSFER_V1_MAX_BYTES && !entry.rendition
|
|
124
|
+
? Manifest.parse({ schema_version: '1.0', ...base })
|
|
125
|
+
: ArtifactManifest11Schema.parse({ schema_version: '1.1', ...base, ...(entry.rendition ? { rendition: entry.rendition } : {}) });
|
|
126
|
+
db.prepare(`INSERT INTO a2a_team_artifacts(id,peer,context_id,a2a_task_id,digest,name,mime,size,manifest_json,status,expires)
|
|
127
|
+
VALUES (?,?,?,?,?,?,?,?,?,'available',?)`).run(id, peer, contextId, a2aTaskId, entry.digest, entry.name, entry.mime, size, JSON.stringify(manifest), manifest.expires_at);
|
|
128
|
+
return LocalRow.parse(db.prepare('SELECT * FROM a2a_team_artifacts WHERE id=?').get(id));
|
|
129
|
+
}
|
|
130
|
+
#exported(row) {
|
|
131
|
+
const stored = StoredManifest.safeParse(JSON.parse(row.manifest_json));
|
|
132
|
+
if (!stored.success)
|
|
133
|
+
return undefined;
|
|
134
|
+
const manifest = manifestV11(stored.data);
|
|
135
|
+
const v2 = { manifest_1_1: manifest, content_path: contentPath(row.id, row.context_id),
|
|
136
|
+
renditions_path: contentPath(row.id, row.context_id, '/renditions'), size: row.size, sha256: row.digest };
|
|
137
|
+
if (stored.data.schema_version === '1.0') {
|
|
138
|
+
const v1 = Manifest.safeParse(stored.data);
|
|
139
|
+
if (!v1.success)
|
|
140
|
+
return undefined;
|
|
141
|
+
return { v2, v1: { artifact_id: row.id, name: row.name, mime: row.mime, sha256: row.digest, size: row.size,
|
|
142
|
+
producer_task_id: row.a2a_task_id, artifact_manifest: v1.data } };
|
|
143
|
+
}
|
|
144
|
+
return { v2, requires_v2: { error: ARTIFACT_TRANSFER_ERRORS.requiresV2, capability: ARTIFACT_TRANSFER_V2_URN,
|
|
145
|
+
message: `This artifact is larger than ${ARTIFACT_TRANSFER_V1_MAX_BYTES} bytes; fetch it with ${ARTIFACT_TRANSFER_V2_URN}`,
|
|
146
|
+
artifact_id: row.id, name: row.name, mime: row.mime, sha256: row.digest, size: row.size, producer_task_id: row.a2a_task_id } };
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The export a peer may fetch in a context, checked against its stored
|
|
150
|
+
* manifest and the size of the stored bytes. Bytes are read by the caller.
|
|
151
|
+
*/
|
|
152
|
+
async resolve(peer, id, contextId) {
|
|
108
153
|
if (!identifier.safeParse(id).success || !contextId || contextId.length > 128)
|
|
109
154
|
return { status: 404 };
|
|
110
155
|
const raw = this.runtime.store.db.prepare('SELECT * FROM a2a_team_artifacts WHERE id=? AND peer=? AND context_id=?').get(id, peer, contextId);
|
|
@@ -113,21 +158,42 @@ export class TeamArtifacts {
|
|
|
113
158
|
const row = LocalRow.parse(raw);
|
|
114
159
|
if (row.status !== 'available' || row.expires <= Date.now() / 1000)
|
|
115
160
|
return { status: 410 };
|
|
161
|
+
const stored = StoredManifest.safeParse(JSON.parse(row.manifest_json));
|
|
162
|
+
if (!stored.success)
|
|
163
|
+
return { status: 410 };
|
|
164
|
+
const manifest = stored.data;
|
|
165
|
+
if (manifest.artifact_id !== id || manifest.sha256 !== row.digest || manifest.expires_at !== row.expires ||
|
|
166
|
+
manifest.name !== row.name || manifest.mime !== row.mime || manifest.size !== row.size ||
|
|
167
|
+
manifest.provenance.producer_task_id !== row.a2a_task_id)
|
|
168
|
+
return { status: 410 };
|
|
116
169
|
try {
|
|
117
|
-
const
|
|
118
|
-
if (
|
|
170
|
+
const file = await this.runtime.artifacts.stat(row.digest);
|
|
171
|
+
if (!file || file.size !== row.size)
|
|
119
172
|
return { status: 409 };
|
|
120
|
-
const manifest = Manifest.parse(JSON.parse(row.manifest_json));
|
|
121
|
-
if (manifest.artifact_id !== id || manifest.sha256 !== row.digest || manifest.expires_at !== row.expires ||
|
|
122
|
-
manifest.name !== row.name || manifest.mime !== row.mime || manifest.size !== row.size ||
|
|
123
|
-
manifest.provenance.producer_task_id !== row.a2a_task_id)
|
|
124
|
-
return { status: 410 };
|
|
125
|
-
return { status: 200, bytes, descriptor: { artifact_id: id, name: row.name, mime: row.mime,
|
|
126
|
-
sha256: row.digest, size: row.size, producer_task_id: row.a2a_task_id, artifact_manifest: manifest } };
|
|
127
173
|
}
|
|
128
174
|
catch {
|
|
129
175
|
return { status: 409 };
|
|
130
176
|
}
|
|
177
|
+
const v10 = manifest.schema_version === '1.0' ? Manifest.safeParse(manifest) : undefined;
|
|
178
|
+
return { status: 200, id, peer, context_id: row.context_id, a2a_task_id: row.a2a_task_id, manifest: manifestV11(manifest),
|
|
179
|
+
...(v10?.success ? { manifest_1_0: v10.data } : {}) };
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* The exported forms of an export's artifact in the same task and context,
|
|
183
|
+
* the original first, each with the export ID and path that serves it.
|
|
184
|
+
*/
|
|
185
|
+
async renditions(resolved) {
|
|
186
|
+
const local = await this.runtime.artifactManifests.renditions(resolved.manifest.sha256) ?? [];
|
|
187
|
+
const exported = z.array(LocalRow).parse(this.runtime.store.db.prepare(`SELECT * FROM a2a_team_artifacts
|
|
188
|
+
WHERE a2a_task_id=? AND peer=? AND context_id=? AND status='available' AND expires>?`)
|
|
189
|
+
.all(resolved.a2a_task_id, resolved.peer, resolved.context_id, Date.now() / 1000));
|
|
190
|
+
const forms = local.length ? local : [ArtifactRenditionSchema.parse({ sha256: resolved.manifest.sha256,
|
|
191
|
+
role: resolved.manifest.rendition?.role ?? 'original', mime: resolved.manifest.mime, size: resolved.manifest.size,
|
|
192
|
+
purpose: resolved.manifest.rendition?.purpose ?? 'download' })];
|
|
193
|
+
return forms.flatMap(form => {
|
|
194
|
+
const row = exported.find(item => item.digest === form.sha256);
|
|
195
|
+
return row ? [{ ...form, artifact_id: row.id, content_path: contentPath(row.id, row.context_id) }] : [];
|
|
196
|
+
});
|
|
131
197
|
}
|
|
132
198
|
revokeLocal(peer, a2aTaskId, id) {
|
|
133
199
|
const changed = this.runtime.store.db.prepare(`UPDATE a2a_team_artifacts SET status='revoked'
|
|
@@ -135,100 +201,6 @@ export class TeamArtifacts {
|
|
|
135
201
|
if (changed !== 1)
|
|
136
202
|
throw new Error('Owned artifact export is unavailable');
|
|
137
203
|
}
|
|
138
|
-
async fetchHermes(input) {
|
|
139
|
-
const owned = this.runtime.store.get(input.localTaskId);
|
|
140
|
-
if (!owned || owned.caller !== input.owner || !['direct', 'peer'].includes(owned.context))
|
|
141
|
-
throw new Error('Local recipient task is not owned');
|
|
142
|
-
const id = identifier.parse(input.artifactId);
|
|
143
|
-
const expected = digest.parse(input.sha256);
|
|
144
|
-
if (!input.remoteTaskId || !input.remoteContextId)
|
|
145
|
-
throw new Error('Remote task receipt is incomplete');
|
|
146
|
-
const transferId = sha(Buffer.from(JSON.stringify([input.owner, input.localTaskId, input.peer,
|
|
147
|
-
input.remoteTaskId, input.remoteContextId, id, expected])));
|
|
148
|
-
const priorRaw = this.runtime.store.db.prepare('SELECT * FROM a2a_team_artifact_transfers WHERE id=?').get(transferId);
|
|
149
|
-
if (priorRaw) {
|
|
150
|
-
const prior = TransferRow.parse(priorRaw);
|
|
151
|
-
if (prior.status !== 'complete')
|
|
152
|
-
throw new Error('Artifact transfer requires reconciliation');
|
|
153
|
-
await this.runtime.artifacts.get(prior.digest);
|
|
154
|
-
const manifest = Manifest.parse(JSON.parse(prior.manifest_json));
|
|
155
|
-
return { artifact_id: id, name: manifest.name, mime: manifest.mime, sha256: expected, size: manifest.size,
|
|
156
|
-
producer_task_id: input.remoteTaskId, artifact_manifest: manifest, local_artifact_id: prior.digest };
|
|
157
|
-
}
|
|
158
|
-
const { card, client, authorization } = await new ArdentA2AClient(this.runtime.profileDir, this.config, this.env).open(input.peer);
|
|
159
|
-
const remote = await client.getTask({ tenant: '', id: input.remoteTaskId }, { serviceParameters: { Authorization: authorization, 'A2A-Version': '1.0' } });
|
|
160
|
-
if (remote.id !== input.remoteTaskId || remote.contextId !== input.remoteContextId ||
|
|
161
|
-
remote.status?.state !== TaskState.TASK_STATE_COMPLETED)
|
|
162
|
-
throw new Error('Remote task receipt is not complete or bound');
|
|
163
|
-
const descriptors = textParts(remote).flatMap(value => {
|
|
164
|
-
try {
|
|
165
|
-
return [TeamArtifactDescriptorSchema.parse(JSON.parse(value))];
|
|
166
|
-
}
|
|
167
|
-
catch {
|
|
168
|
-
return [];
|
|
169
|
-
}
|
|
170
|
-
});
|
|
171
|
-
const declared = descriptors.find(item => item.artifact_id === id && item.sha256 === expected &&
|
|
172
|
-
item.producer_task_id === input.remoteTaskId);
|
|
173
|
-
if (!declared)
|
|
174
|
-
throw new Error('Remote task did not declare this exact artifact');
|
|
175
|
-
const interfaceUrl = card.supportedInterfaces.find(item => item.protocolBinding.toUpperCase() === 'JSONRPC' &&
|
|
176
|
-
item.protocolVersion === '1.0')?.url;
|
|
177
|
-
if (!interfaceUrl)
|
|
178
|
-
throw new Error('Remote peer has no pinned JSON-RPC origin');
|
|
179
|
-
const url = new URL(`/team/artifacts/${id}`, interfaceUrl);
|
|
180
|
-
url.searchParams.set('context', input.remoteContextId);
|
|
181
|
-
const response = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(30_000),
|
|
182
|
-
headers: { Authorization: authorization } });
|
|
183
|
-
if (!response.ok)
|
|
184
|
-
throw new Error(`Artifact fetch HTTP ${response.status}`);
|
|
185
|
-
const lengthHeader = response.headers.get('content-length');
|
|
186
|
-
const length = lengthHeader === null ? NaN : Number(lengthHeader);
|
|
187
|
-
if (!Number.isInteger(length) || length < 0 || length > MAX_BYTES || length !== declared.size)
|
|
188
|
-
throw new Error('Artifact size differs from task receipt');
|
|
189
|
-
if (response.headers.get('x-hermes-task-id') !== input.remoteTaskId ||
|
|
190
|
-
decodeURIComponent(response.headers.get('x-artifact-name') ?? '') !== declared.name ||
|
|
191
|
-
response.headers.get('content-type')?.split(';')[0] !== declared.mime)
|
|
192
|
-
throw new Error('Artifact response differs from task receipt');
|
|
193
|
-
const encoded = response.headers.get('x-hermes-artifact-manifest');
|
|
194
|
-
if (!encoded || encoded.length > 8192)
|
|
195
|
-
throw new Error('Artifact manifest is missing or oversized');
|
|
196
|
-
const manifest = Manifest.parse(JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')));
|
|
197
|
-
if (JSON.stringify(manifest) !== JSON.stringify(declared.artifact_manifest) ||
|
|
198
|
-
manifest.expires_at <= Date.now() / 1000 || manifest.provenance.producer_task_id !== input.remoteTaskId)
|
|
199
|
-
throw new Error('Artifact manifest differs from task receipt');
|
|
200
|
-
if (!response.body)
|
|
201
|
-
throw new Error('Artifact response has no body');
|
|
202
|
-
const reader = response.body.getReader();
|
|
203
|
-
const chunks = [];
|
|
204
|
-
let total = 0;
|
|
205
|
-
try {
|
|
206
|
-
while (true) {
|
|
207
|
-
const { done, value } = await reader.read();
|
|
208
|
-
if (done)
|
|
209
|
-
break;
|
|
210
|
-
total += value.byteLength;
|
|
211
|
-
if (total > MAX_BYTES || total > length)
|
|
212
|
-
throw new Error('Artifact response exceeds declared size');
|
|
213
|
-
chunks.push(value);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
catch (error) {
|
|
217
|
-
await reader.cancel().catch(() => { });
|
|
218
|
-
throw error;
|
|
219
|
-
}
|
|
220
|
-
finally {
|
|
221
|
-
reader.releaseLock();
|
|
222
|
-
}
|
|
223
|
-
const bytes = Buffer.concat(chunks, total);
|
|
224
|
-
if (bytes.byteLength !== length || sha(bytes) !== expected)
|
|
225
|
-
throw new Error('Artifact bytes differ from task receipt');
|
|
226
|
-
const local = await this.runtime.artifacts.put(manifest.name, manifest.mime, bytes);
|
|
227
|
-
this.runtime.store.db.prepare(`INSERT INTO a2a_team_artifact_transfers(id,owner,local_task_id,peer,remote_task_id,
|
|
228
|
-
remote_context_id,remote_artifact_id,digest,manifest_json,status) VALUES (?,?,?,?,?,?,?,?,?,'complete')`)
|
|
229
|
-
.run(transferId, input.owner, input.localTaskId, input.peer, input.remoteTaskId, input.remoteContextId, id, local.id, JSON.stringify(manifest));
|
|
230
|
-
return { ...declared, local_artifact_id: local.id };
|
|
231
|
-
}
|
|
232
204
|
project(owner, localTaskId) {
|
|
233
205
|
const task = this.runtime.store.get(localTaskId);
|
|
234
206
|
if (!task || task.caller !== owner)
|
package/dist/team-child.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import type { ArdentRuntime } from './runtime.js';
|
|
3
3
|
import { TeamEnvelope, type TeamResult } from './team-contract.js';
|
|
4
|
+
import type { ExecutionContext } from './execution.js';
|
|
4
5
|
export declare const TeamChildReference: z.ZodObject<{
|
|
5
6
|
version: z.ZodLiteral<"1.0">;
|
|
6
7
|
root: z.ZodString;
|
|
@@ -14,7 +15,9 @@ export declare class TeamChildService {
|
|
|
14
15
|
readonly runtime: ArdentRuntime;
|
|
15
16
|
constructor(runtime: ArdentRuntime, env: NodeJS.ProcessEnv);
|
|
16
17
|
claim(raw: unknown, envelope: z.infer<typeof TeamEnvelope>, a2aTaskId: string, contextId: string, authenticatedCaller: string, requestFingerprint: string): Promise<TeamChildReference>;
|
|
17
|
-
attach(ref: TeamChildReference, operationId: string): void;
|
|
18
|
+
attach(ref: TeamChildReference, operationId: string, execution?: ExecutionContext): void;
|
|
19
|
+
/** The child reference whose native execution is this operation, when it has a retained claim. */
|
|
20
|
+
referenceFor(operationId: string): TeamChildReference | undefined;
|
|
18
21
|
deadline(ref: TeamChildReference): number;
|
|
19
22
|
settle(ref: TeamChildReference, outcome: TeamResult['outcome'], result: string): Promise<void>;
|
|
20
23
|
flush(): Promise<void>;
|
package/dist/team-child.js
CHANGED
|
@@ -34,6 +34,11 @@ export class TeamChildService {
|
|
|
34
34
|
child_id TEXT PRIMARY KEY, a2a_task_id TEXT NOT NULL, fingerprint TEXT NOT NULL,
|
|
35
35
|
claim_id TEXT NOT NULL, root TEXT NOT NULL, grant_json TEXT NOT NULL,
|
|
36
36
|
operation_id TEXT, settlement_json TEXT, acknowledged INTEGER NOT NULL DEFAULT 0);`);
|
|
37
|
+
// The child's execution context sits next to its grant for attribution. It is
|
|
38
|
+
// outside the grant and its digest, and admission never reads it.
|
|
39
|
+
const columns = z.array(z.object({ name: z.string() })).parse(runtime.store.db.pragma('table_info(a2a_team_child_claims)'));
|
|
40
|
+
if (!columns.some(column => column.name === 'execution_json'))
|
|
41
|
+
runtime.store.db.exec('ALTER TABLE a2a_team_child_claims ADD COLUMN execution_json TEXT');
|
|
37
42
|
}
|
|
38
43
|
#row(childId) {
|
|
39
44
|
const raw = this.runtime.store.db.prepare('SELECT * FROM a2a_team_child_claims WHERE child_id=?').get(childId);
|
|
@@ -82,13 +87,27 @@ export class TeamChildService {
|
|
|
82
87
|
db.prepare('UPDATE a2a_team_child_claims SET grant_json=? WHERE child_id=?').run(stable(grant), ref.child_id);
|
|
83
88
|
return ref;
|
|
84
89
|
}
|
|
85
|
-
attach(ref, operationId) {
|
|
90
|
+
attach(ref, operationId, execution) {
|
|
86
91
|
const row = this.#row(ref.child_id);
|
|
87
92
|
if (!row || row.grant_json === '{}')
|
|
88
93
|
throw new Error('Child execution has no retained root claim');
|
|
89
94
|
if (row.operation_id && row.operation_id !== operationId)
|
|
90
95
|
throw new Error('Child native execution identity changed');
|
|
91
|
-
this.runtime.store.db.prepare('UPDATE a2a_team_child_claims SET operation_id
|
|
96
|
+
this.runtime.store.db.prepare('UPDATE a2a_team_child_claims SET operation_id=?,execution_json=coalesce(execution_json,?) WHERE child_id=?')
|
|
97
|
+
.run(operationId, execution ? JSON.stringify(execution) : null, ref.child_id);
|
|
98
|
+
}
|
|
99
|
+
/** The child reference whose native execution is this operation, when it has a retained claim. */
|
|
100
|
+
referenceFor(operationId) {
|
|
101
|
+
const raw = this.runtime.store.db.prepare("SELECT * FROM a2a_team_child_claims WHERE operation_id=? AND grant_json!='{}' LIMIT 1").get(operationId);
|
|
102
|
+
if (!raw)
|
|
103
|
+
return undefined;
|
|
104
|
+
try {
|
|
105
|
+
const row = Row.parse(raw);
|
|
106
|
+
return { version: '1.0', root: row.root, child_id: row.child_id, sha256: Grant.parse(JSON.parse(row.grant_json)).sha256 };
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
92
111
|
}
|
|
93
112
|
deadline(ref) {
|
|
94
113
|
const row = this.#row(ref.child_id);
|
package/dist/team-contract.d.ts
CHANGED
|
@@ -93,9 +93,9 @@ export declare const TeamResult: z.ZodObject<{
|
|
|
93
93
|
unknown: "unknown";
|
|
94
94
|
failed: "failed";
|
|
95
95
|
completed: "completed";
|
|
96
|
+
cancelled: "cancelled";
|
|
96
97
|
input_required: "input_required";
|
|
97
98
|
partial: "partial";
|
|
98
|
-
cancelled: "cancelled";
|
|
99
99
|
blocked: "blocked";
|
|
100
100
|
}>;
|
|
101
101
|
summary: z.ZodString;
|
package/dist/telegram.d.ts
CHANGED
|
@@ -31,5 +31,7 @@ export declare class TelegramAdapter {
|
|
|
31
31
|
* use `deliverySignal`, so a shutdown can stop intake before cutting delivery.
|
|
32
32
|
*/
|
|
33
33
|
run(signal: AbortSignal, deliverySignal?: AbortSignal): Promise<void>;
|
|
34
|
+
/** Answer updates whose task execution recovery resumed or continued, until `signal` aborts. Call after `initialize`. */
|
|
35
|
+
watchRecovered(signal: AbortSignal, deliverySignal?: AbortSignal): Promise<void>;
|
|
34
36
|
}
|
|
35
37
|
export {};
|
package/dist/telegram.js
CHANGED
|
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
|
|
|
2
2
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { ChannelCore, DeliveryRejectedError } from './channels.js';
|
|
5
|
+
import { AttemptError, lastAttemptError, retryWithPolicy } from './retry.js';
|
|
5
6
|
const User = z.object({ id: z.number().int(), is_bot: z.boolean().default(false), username: z.string().optional() }).passthrough();
|
|
6
7
|
const Document = z.object({ file_id: z.string(), file_name: z.string().default('attachment'), mime_type: z.string().default('application/octet-stream'), file_size: z.number().int().nonnegative().optional() }).passthrough();
|
|
7
8
|
const Message = z.object({ message_id: z.number().int(), from: User.optional(), chat: z.object({ id: z.number().int(), type: z.string() }).passthrough(), text: z.string().optional(), caption: z.string().optional(), message_thread_id: z.number().int().optional(), reply_to_message: z.object({ message_id: z.number().int() }).passthrough().optional(), document: Document.optional() }).passthrough();
|
|
@@ -52,35 +53,47 @@ export class TelegramAdapter {
|
|
|
52
53
|
this.#base = baseUrl.replace(/\/$/, '');
|
|
53
54
|
this.#core = new ChannelCore(runtime, env, jobs);
|
|
54
55
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
if (response.
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
56
|
+
/**
|
|
57
|
+
* One Bot API call. A 429 that carries `retry_after` was not accepted, so it is repeated under
|
|
58
|
+
* the `telegram` policy (4 attempts, the wait capped at 60 s). `onAttempt` counts requests.
|
|
59
|
+
*/
|
|
60
|
+
async #call(method, body, signal, onAttempt) {
|
|
61
|
+
let waiting = false;
|
|
62
|
+
try {
|
|
63
|
+
return await retryWithPolicy('telegram', async () => {
|
|
64
|
+
waiting = false;
|
|
65
|
+
onAttempt?.();
|
|
66
|
+
const response = await fetch(`${this.#base}/bot${this.#token}/${method}`, {
|
|
67
|
+
method: 'POST',
|
|
68
|
+
...(body instanceof FormData ? {} : { headers: { 'Content-Type': 'application/json' } }),
|
|
69
|
+
body: body instanceof FormData ? body : JSON.stringify(body),
|
|
70
|
+
...(signal ? { signal } : {}),
|
|
71
|
+
redirect: 'error'
|
|
72
|
+
});
|
|
73
|
+
const parsed = Envelope.parse(await response.json());
|
|
74
|
+
if (response.status === 409 || parsed.error_code === 409) {
|
|
75
|
+
this.#consumerConflict = true;
|
|
76
|
+
throw new TelegramConflictError(`Telegram consumer conflict: ${parsed.description ?? 'another poller or webhook owns the bot'}`);
|
|
77
|
+
}
|
|
78
|
+
if (!response.ok || !parsed.ok) {
|
|
79
|
+
const message = `Telegram ${method} failed: ${parsed.description ?? response.status}`;
|
|
80
|
+
const rejected = response.status >= 400 && response.status < 500 ? new DeliveryRejectedError(message) : new Error(message);
|
|
81
|
+
const retryAfter = parsed.parameters?.retry_after;
|
|
82
|
+
// Only a 429 with Telegram's own `retry_after` is a definite refusal worth repeating.
|
|
83
|
+
if (response.status === 429 && retryAfter)
|
|
84
|
+
throw new AttemptError(message, { status: 429, retryAfterMs: Math.min(retryAfter, 60) * 1000 }, { cause: rejected });
|
|
85
|
+
throw rejected;
|
|
86
|
+
}
|
|
87
|
+
return parsed.result;
|
|
88
|
+
}, { effect: 'none', ...(signal ? { signal } : {}), onAttempt: record => { waiting = record.delayMs !== null; } });
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
// The abortable wait removes its listener, so a long-lived signal does not accumulate them.
|
|
92
|
+
if (waiting && signal?.aborted)
|
|
93
|
+
throw new Error('Telegram retry aborted', { cause: error });
|
|
94
|
+
const last = lastAttemptError(error);
|
|
95
|
+
throw last instanceof AttemptError && last.cause instanceof Error ? last.cause : last;
|
|
82
96
|
}
|
|
83
|
-
throw new Error(`Telegram ${method} retry limit reached`);
|
|
84
97
|
}
|
|
85
98
|
async initialize(signal) {
|
|
86
99
|
const me = User.parse(await this.#call('getMe', {}, signal));
|
|
@@ -164,23 +177,38 @@ export class TelegramAdapter {
|
|
|
164
177
|
*/
|
|
165
178
|
async run(signal, deliverySignal = signal) {
|
|
166
179
|
await this.initialize(signal);
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
180
|
+
// Tasks execution recovery resumed or continued have no waiting handler; answer them once each.
|
|
181
|
+
const stop = new AbortController();
|
|
182
|
+
const recovered = this.watchRecovered(AbortSignal.any([signal, stop.signal]), deliverySignal);
|
|
183
|
+
try {
|
|
184
|
+
let failures = 0;
|
|
185
|
+
while (!signal.aborted) {
|
|
186
|
+
try {
|
|
187
|
+
await this.pollOnce(signal, deliverySignal);
|
|
188
|
+
failures = 0;
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
if (signal.aborted)
|
|
192
|
+
break;
|
|
193
|
+
if (error instanceof TelegramConflictError)
|
|
194
|
+
throw error;
|
|
195
|
+
failures++;
|
|
196
|
+
// Abort-aware so shutdown does not wait out the reconnect backoff.
|
|
197
|
+
await sleep(Math.min(30_000, 1000 * 2 ** Math.min(failures, 5)), undefined, { signal }).catch(() => { });
|
|
198
|
+
}
|
|
181
199
|
}
|
|
200
|
+
await this.drain();
|
|
201
|
+
}
|
|
202
|
+
finally {
|
|
203
|
+
stop.abort();
|
|
204
|
+
await recovered;
|
|
182
205
|
}
|
|
183
|
-
|
|
206
|
+
}
|
|
207
|
+
/** Answer updates whose task execution recovery resumed or continued, until `signal` aborts. Call after `initialize`. */
|
|
208
|
+
watchRecovered(signal, deliverySignal = signal) {
|
|
209
|
+
if (!this.#bot)
|
|
210
|
+
throw new Error('Telegram adapter has not initialized');
|
|
211
|
+
return this.#core.watchRecovered('telegram', String(this.#bot.id), target => reply => this.#deliverTo(target, reply, deliverySignal), signal);
|
|
184
212
|
}
|
|
185
213
|
async #handleUpdate(update, ready, signal) {
|
|
186
214
|
const message = update.message;
|
|
@@ -249,7 +277,7 @@ export class TelegramAdapter {
|
|
|
249
277
|
const initialTyping = showTyping();
|
|
250
278
|
const typing = setInterval(() => { void showTyping(); }, 4000);
|
|
251
279
|
try {
|
|
252
|
-
const operation = this.#core.handle(event, async (reply) => { await initialTyping; return this.#
|
|
280
|
+
const operation = this.#core.handle(event, async (reply) => { await initialTyping; return this.#deliverTo(event, reply, signal); });
|
|
253
281
|
ready();
|
|
254
282
|
await operation;
|
|
255
283
|
}
|
|
@@ -257,12 +285,17 @@ export class TelegramAdapter {
|
|
|
257
285
|
clearInterval(typing);
|
|
258
286
|
}
|
|
259
287
|
}
|
|
260
|
-
async #
|
|
288
|
+
async #deliverTo(target, reply, signal) {
|
|
289
|
+
const message = { chat: { id: Number(target.conversation) }, message_id: Number(target.reply_to), message_thread_id: target.thread === null ? undefined : Number(target.thread) };
|
|
290
|
+
const event = target;
|
|
261
291
|
const common = { chat_id: message.chat.id, reply_parameters: { message_id: message.message_id }, ...(message.message_thread_id === undefined ? {} : { message_thread_id: message.message_thread_id }) };
|
|
262
292
|
let last = null;
|
|
293
|
+
// Every Bot API request this delivery made, retries included, lands on its delivery row.
|
|
294
|
+
let attempts = 0;
|
|
295
|
+
const counted = () => { attempts++; };
|
|
263
296
|
try {
|
|
264
297
|
for (const part of splitText(reply.text)) {
|
|
265
|
-
const response = Message.parse(await this.#call('sendMessage', { ...common, text: part }, signal));
|
|
298
|
+
const response = Message.parse(await this.#call('sendMessage', { ...common, text: part }, signal, counted));
|
|
266
299
|
last = String(response.message_id);
|
|
267
300
|
}
|
|
268
301
|
for (const [index, id] of reply.artifactIds.slice(0, 2).entries()) {
|
|
@@ -273,7 +306,7 @@ export class TelegramAdapter {
|
|
|
273
306
|
if (message.message_thread_id !== undefined)
|
|
274
307
|
form.set('message_thread_id', String(message.message_thread_id));
|
|
275
308
|
form.set('document', new Blob([new Uint8Array(bytes)], { type: 'application/octet-stream' }), index === 0 ? 'research-brief.json' : 'research-brief.md');
|
|
276
|
-
const response = Message.parse(await this.#call('sendDocument', form, signal));
|
|
309
|
+
const response = Message.parse(await this.#call('sendDocument', form, signal, counted));
|
|
277
310
|
last = String(response.message_id);
|
|
278
311
|
}
|
|
279
312
|
}
|
|
@@ -282,6 +315,9 @@ export class TelegramAdapter {
|
|
|
282
315
|
throw new Error(`Telegram delivery may be partial: ${error instanceof Error ? error.message : 'unknown error'}`);
|
|
283
316
|
throw error;
|
|
284
317
|
}
|
|
318
|
+
finally {
|
|
319
|
+
this.runtime.store.recordDeliveryAttempts(event.platform, event.account, event.update_id, attempts);
|
|
320
|
+
}
|
|
285
321
|
return last;
|
|
286
322
|
}
|
|
287
323
|
}
|