@hivemagnus/ardent 2.1.2 → 2.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.
@@ -0,0 +1,169 @@
1
+ import { z } from 'zod';
2
+ import { type ArtifactStore } from './artifacts.js';
3
+ import type { TaskStore } from './store.js';
4
+ /** Media types an agent may register, with the bytes each must start with (binary) or the text it must hold. */
5
+ export declare const ARTIFACT_MIME_TYPES: {
6
+ readonly 'text/markdown': "text";
7
+ readonly 'text/plain': "text";
8
+ readonly 'application/json': "json";
9
+ readonly 'text/csv': "text";
10
+ readonly 'image/svg+xml': "svg";
11
+ readonly 'image/png': "png";
12
+ readonly 'image/jpeg': "jpeg";
13
+ readonly 'image/webp': "webp";
14
+ readonly 'application/pdf': "pdf";
15
+ readonly 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': "docx";
16
+ };
17
+ export type ArtifactMime = keyof typeof ARTIFACT_MIME_TYPES;
18
+ export declare const ArtifactMimeSchema: z.ZodEnum<{
19
+ "application/json": "application/json";
20
+ "text/plain": "text/plain";
21
+ "text/markdown": "text/markdown";
22
+ "text/csv": "text/csv";
23
+ "image/svg+xml": "image/svg+xml";
24
+ "image/png": "image/png";
25
+ "image/jpeg": "image/jpeg";
26
+ "image/webp": "image/webp";
27
+ "application/pdf": "application/pdf";
28
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
29
+ }>;
30
+ /** Local artifacts never expire unless they were produced by a preview; the manifest field is still required. */
31
+ export declare const NO_EXPIRY_SECONDS = 253402300799;
32
+ /** Manifest of a registered artifact: the peer export manifest with the profile's larger size bound. */
33
+ export declare const ArtifactManifestSchema: z.ZodObject<{
34
+ schema_version: z.ZodLiteral<"1.0">;
35
+ revision: z.ZodNumber;
36
+ source_revision: z.ZodString;
37
+ visibility: z.ZodEnum<{
38
+ private: "private";
39
+ gm: "gm";
40
+ player: "player";
41
+ }>;
42
+ license: z.ZodString;
43
+ preview: z.ZodObject<{
44
+ mode: z.ZodEnum<{
45
+ none: "none";
46
+ inline: "inline";
47
+ thumbnail: "thumbnail";
48
+ download_only: "download_only";
49
+ }>;
50
+ mime: z.ZodString;
51
+ }, z.core.$strict>;
52
+ supersedes_sha256: z.ZodNullable<z.ZodString>;
53
+ acceptance_status: z.ZodEnum<{
54
+ partial: "partial";
55
+ rejected: "rejected";
56
+ unreviewed: "unreviewed";
57
+ approved: "approved";
58
+ }>;
59
+ name: z.ZodString;
60
+ mime: z.ZodString;
61
+ sha256: z.ZodString;
62
+ created_at: z.ZodNumber;
63
+ expires_at: z.ZodNumber;
64
+ provenance: z.ZodObject<{
65
+ producer: z.ZodString;
66
+ source_id: z.ZodString;
67
+ producer_task_id: z.ZodString;
68
+ lineage: z.ZodArray<z.ZodObject<{
69
+ producer: z.ZodString;
70
+ source_id: z.ZodString;
71
+ }, z.core.$strict>>;
72
+ }, z.core.$strict>;
73
+ recovery: z.ZodObject<{
74
+ on_expiry: z.ZodLiteral<"request_verified_reexport">;
75
+ }, z.core.$strict>;
76
+ artifact_id: z.ZodString;
77
+ size: z.ZodNumber;
78
+ }, z.core.$strict>;
79
+ export type ArtifactManifest = z.infer<typeof ArtifactManifestSchema>;
80
+ /** A manifest with the task that produced it and the artifact that later revised it, if any. */
81
+ export declare const ArtifactRecordSchema: z.ZodObject<{
82
+ task_id: z.ZodString;
83
+ superseded_by_sha256: z.ZodNullable<z.ZodString>;
84
+ manifest: z.ZodObject<{
85
+ schema_version: z.ZodLiteral<"1.0">;
86
+ revision: z.ZodNumber;
87
+ source_revision: z.ZodString;
88
+ visibility: z.ZodEnum<{
89
+ private: "private";
90
+ gm: "gm";
91
+ player: "player";
92
+ }>;
93
+ license: z.ZodString;
94
+ preview: z.ZodObject<{
95
+ mode: z.ZodEnum<{
96
+ none: "none";
97
+ inline: "inline";
98
+ thumbnail: "thumbnail";
99
+ download_only: "download_only";
100
+ }>;
101
+ mime: z.ZodString;
102
+ }, z.core.$strict>;
103
+ supersedes_sha256: z.ZodNullable<z.ZodString>;
104
+ acceptance_status: z.ZodEnum<{
105
+ partial: "partial";
106
+ rejected: "rejected";
107
+ unreviewed: "unreviewed";
108
+ approved: "approved";
109
+ }>;
110
+ name: z.ZodString;
111
+ mime: z.ZodString;
112
+ sha256: z.ZodString;
113
+ created_at: z.ZodNumber;
114
+ expires_at: z.ZodNumber;
115
+ provenance: z.ZodObject<{
116
+ producer: z.ZodString;
117
+ source_id: z.ZodString;
118
+ producer_task_id: z.ZodString;
119
+ lineage: z.ZodArray<z.ZodObject<{
120
+ producer: z.ZodString;
121
+ source_id: z.ZodString;
122
+ }, z.core.$strict>>;
123
+ }, z.core.$strict>;
124
+ recovery: z.ZodObject<{
125
+ on_expiry: z.ZodLiteral<"request_verified_reexport">;
126
+ }, z.core.$strict>;
127
+ artifact_id: z.ZodString;
128
+ size: z.ZodNumber;
129
+ }, z.core.$strict>;
130
+ }, z.core.$strict>;
131
+ export type ArtifactRecord = z.infer<typeof ArtifactRecordSchema>;
132
+ /** Reject bytes that are not what their declared media type says. Text must be valid UTF-8. */
133
+ export declare function checkArtifactContent(mime: ArtifactMime, bytes: Uint8Array): void;
134
+ /**
135
+ * Registered artifacts with their manifests. A manifest is an immutable producer
136
+ * record; a later artifact may revise (supersede) an earlier one by digest.
137
+ */
138
+ export declare class ArtifactManifests {
139
+ #private;
140
+ readonly store: TaskStore;
141
+ readonly artifacts: ArtifactStore;
142
+ readonly producer: string;
143
+ constructor(store: TaskStore, artifacts: ArtifactStore, producer: string);
144
+ /**
145
+ * Store bytes for a task and record their manifest and an `artifact_registered`
146
+ * journal event. `revisesSha256` must name a current registered artifact.
147
+ */
148
+ register(input: {
149
+ taskId: string;
150
+ name: string;
151
+ mime: ArtifactMime;
152
+ bytes: Uint8Array;
153
+ source: string;
154
+ revisesSha256?: string | undefined;
155
+ ttlSeconds?: number | undefined;
156
+ }): Promise<ArtifactRecord>;
157
+ /**
158
+ * Delete the bytes of artifacts whose every manifest has expired, unless a
159
+ * task outside preview still refers to the digest in its journal.
160
+ */
161
+ sweepExpired(nowMs?: number): Promise<{
162
+ deleted: string[];
163
+ retained: string[];
164
+ }>;
165
+ /** Current (unexpired) manifests a task registered, oldest first. */
166
+ forTask(taskId: string, limit?: number): ArtifactRecord[];
167
+ /** The newest current manifest for a digest. */
168
+ manifest(sha256: string): ArtifactRecord | undefined;
169
+ }
@@ -0,0 +1,172 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import { ARTIFACT_MAX_BYTES_LIMIT, formatBytes } from './artifacts.js';
4
+ import { TeamArtifactManifestSchema } from './team-artifacts.js';
5
+ import { ProvenNoEffectError } from './tools.js';
6
+ const digest = z.string().regex(/^[a-f0-9]{64}$/);
7
+ /** Media types an agent may register, with the bytes each must start with (binary) or the text it must hold. */
8
+ export const ARTIFACT_MIME_TYPES = {
9
+ 'text/markdown': 'text', 'text/plain': 'text', 'application/json': 'json', 'text/csv': 'text', 'image/svg+xml': 'svg',
10
+ 'image/png': 'png', 'image/jpeg': 'jpeg', 'image/webp': 'webp', 'application/pdf': 'pdf',
11
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx'
12
+ };
13
+ export const ArtifactMimeSchema = z.enum(['text/markdown', 'text/plain', 'application/json', 'text/csv', 'image/svg+xml', 'image/png', 'image/jpeg',
14
+ 'image/webp', 'application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']);
15
+ /** Local artifacts never expire unless they were produced by a preview; the manifest field is still required. */
16
+ export const NO_EXPIRY_SECONDS = 253402300799;
17
+ /** Manifest of a registered artifact: the peer export manifest with the profile's larger size bound. */
18
+ export const ArtifactManifestSchema = TeamArtifactManifestSchema.extend({ size: z.number().int().min(0).max(ARTIFACT_MAX_BYTES_LIMIT) }).strict();
19
+ /** A manifest with the task that produced it and the artifact that later revised it, if any. */
20
+ export const ArtifactRecordSchema = z.object({ task_id: z.string(), superseded_by_sha256: digest.nullable(), manifest: ArtifactManifestSchema }).strict();
21
+ const Row = z.object({ artifact_id: z.string(), task_id: z.string(), sha256: digest, manifest_json: z.string(), superseded_by: digest.nullable() });
22
+ function startsWith(bytes, ...prefix) { return prefix.every((value, index) => bytes[index] === value); }
23
+ /** Reject bytes that are not what their declared media type says. Text must be valid UTF-8. */
24
+ export function checkArtifactContent(mime, bytes) {
25
+ const kind = ARTIFACT_MIME_TYPES[mime];
26
+ const fail = () => { throw new ProvenNoEffectError(`Artifact content is not valid ${mime}`, 'INVALID_ARTIFACT'); };
27
+ if (kind === 'png') {
28
+ if (!startsWith(bytes, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a))
29
+ fail();
30
+ return;
31
+ }
32
+ if (kind === 'jpeg') {
33
+ if (!startsWith(bytes, 0xff, 0xd8, 0xff))
34
+ fail();
35
+ return;
36
+ }
37
+ if (kind === 'webp') {
38
+ if (!startsWith(bytes, 0x52, 0x49, 0x46, 0x46) || Buffer.from(bytes.subarray(8, 12)).toString('latin1') !== 'WEBP')
39
+ fail();
40
+ return;
41
+ }
42
+ if (kind === 'pdf') {
43
+ if (!startsWith(bytes, 0x25, 0x50, 0x44, 0x46, 0x2d))
44
+ fail();
45
+ return;
46
+ }
47
+ if (kind === 'docx') {
48
+ if (!startsWith(bytes, 0x50, 0x4b, 0x03, 0x04))
49
+ fail();
50
+ return;
51
+ }
52
+ let text;
53
+ try {
54
+ text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
55
+ }
56
+ catch {
57
+ return fail();
58
+ }
59
+ if (kind === 'json') {
60
+ try {
61
+ JSON.parse(text);
62
+ }
63
+ catch {
64
+ fail();
65
+ }
66
+ }
67
+ if (kind === 'svg' && !/<svg[\s>]/i.test(text.slice(0, 4096)))
68
+ fail();
69
+ }
70
+ /**
71
+ * Registered artifacts with their manifests. A manifest is an immutable producer
72
+ * record; a later artifact may revise (supersede) an earlier one by digest.
73
+ */
74
+ export class ArtifactManifests {
75
+ store;
76
+ artifacts;
77
+ producer;
78
+ constructor(store, artifacts, producer) {
79
+ this.store = store;
80
+ this.artifacts = artifacts;
81
+ this.producer = producer;
82
+ store.db.exec(`CREATE TABLE IF NOT EXISTS artifact_manifests (
83
+ artifact_id TEXT PRIMARY KEY, task_id TEXT NOT NULL REFERENCES tasks(id), sha256 TEXT NOT NULL,
84
+ name TEXT NOT NULL, mime TEXT NOT NULL, size INTEGER NOT NULL, revision INTEGER NOT NULL,
85
+ supersedes_sha256 TEXT, manifest_json TEXT NOT NULL, created_ms INTEGER NOT NULL, expires_ms INTEGER NOT NULL);
86
+ CREATE INDEX IF NOT EXISTS artifact_manifests_task ON artifact_manifests(task_id, created_ms);
87
+ CREATE INDEX IF NOT EXISTS artifact_manifests_sha ON artifact_manifests(sha256, created_ms);
88
+ CREATE INDEX IF NOT EXISTS artifact_manifests_supersedes ON artifact_manifests(supersedes_sha256);
89
+ CREATE TRIGGER IF NOT EXISTS artifact_manifests_immutable BEFORE UPDATE ON artifact_manifests
90
+ BEGIN SELECT RAISE(ABORT, 'Artifact manifests are immutable'); END;
91
+ CREATE TABLE IF NOT EXISTS artifact_sweeps (sha256 TEXT PRIMARY KEY, outcome TEXT NOT NULL, swept_ms INTEGER NOT NULL);`);
92
+ }
93
+ /**
94
+ * Store bytes for a task and record their manifest and an `artifact_registered`
95
+ * journal event. `revisesSha256` must name a current registered artifact.
96
+ */
97
+ async register(input) {
98
+ // Every check that can refuse the artifact runs before any byte is stored.
99
+ if (!/^[A-Za-z0-9._-]{1,128}$/.test(input.name))
100
+ throw new ProvenNoEffectError('Invalid artifact name', 'INVALID_ARTIFACT');
101
+ if (input.bytes.length > this.artifacts.maxBytes)
102
+ throw new ProvenNoEffectError(`Artifact exceeds ${formatBytes(this.artifacts.maxBytes)}`, 'ARTIFACT_TOO_LARGE');
103
+ checkArtifactContent(input.mime, input.bytes);
104
+ const prior = input.revisesSha256 ? this.manifest(input.revisesSha256) : undefined;
105
+ if (input.revisesSha256 && !prior)
106
+ throw new ProvenNoEffectError('revises_sha256 does not name a current artifact', 'NOT_FOUND');
107
+ if (prior && prior.manifest.sha256 === createHash('sha256').update(input.bytes).digest('hex'))
108
+ throw new ProvenNoEffectError('Revision content is identical to the revised artifact', 'INVALID_ARTIFACT');
109
+ const stored = await this.artifacts.put(input.name, input.mime, input.bytes);
110
+ const created = Date.now();
111
+ const id = randomBytes(16).toString('hex');
112
+ const manifest = ArtifactManifestSchema.parse({
113
+ schema_version: '1.0', revision: prior ? prior.manifest.revision + 1 : 1, source_revision: stored.sha256,
114
+ visibility: 'private', license: 'NOASSERTION',
115
+ preview: { mode: input.mime === 'application/pdf' || ARTIFACT_MIME_TYPES[input.mime] === 'docx' ? 'download_only' : 'inline', mime: input.mime },
116
+ supersedes_sha256: prior?.manifest.sha256 ?? null, acceptance_status: 'unreviewed', name: input.name, mime: input.mime,
117
+ sha256: stored.sha256, size: stored.bytes, created_at: created / 1000,
118
+ expires_at: input.ttlSeconds ? created / 1000 + input.ttlSeconds : NO_EXPIRY_SECONDS,
119
+ provenance: { producer: this.producer, source_id: input.source, producer_task_id: input.taskId,
120
+ lineage: [{ producer: this.producer, source_id: input.source }] },
121
+ recovery: { on_expiry: 'request_verified_reexport' }, artifact_id: id
122
+ });
123
+ this.store.db.transaction(() => {
124
+ this.store.db.prepare(`INSERT INTO artifact_manifests(artifact_id,task_id,sha256,name,mime,size,revision,supersedes_sha256,manifest_json,created_ms,expires_ms)
125
+ VALUES (?,?,?,?,?,?,?,?,?,?,?)`).run(id, input.taskId, manifest.sha256, manifest.name, manifest.mime, manifest.size, manifest.revision, manifest.supersedes_sha256, JSON.stringify(manifest), created, Math.floor(manifest.expires_at * 1000));
126
+ this.store.append(input.taskId, 'artifact_registered', { artifact_id: id, name: manifest.name, mime: manifest.mime,
127
+ sha256: manifest.sha256, size: manifest.size, revision: manifest.revision, supersedes_sha256: manifest.supersedes_sha256, manifest });
128
+ })();
129
+ return { task_id: input.taskId, superseded_by_sha256: null, manifest };
130
+ }
131
+ /**
132
+ * Delete the bytes of artifacts whose every manifest has expired, unless a
133
+ * task outside preview still refers to the digest in its journal.
134
+ */
135
+ async sweepExpired(nowMs = Date.now()) {
136
+ const candidates = z.array(z.object({ sha256: digest })).parse(this.store.db.prepare(`SELECT DISTINCT m.sha256 FROM artifact_manifests m
137
+ WHERE m.expires_ms<=? AND NOT EXISTS (SELECT 1 FROM artifact_manifests n WHERE n.sha256=m.sha256 AND n.expires_ms>?)
138
+ AND NOT EXISTS (SELECT 1 FROM artifact_sweeps s WHERE s.sha256=m.sha256
139
+ AND s.swept_ms>=(SELECT max(k.created_ms) FROM artifact_manifests k WHERE k.sha256=m.sha256)) LIMIT 100`).all(nowMs, nowMs)).map(row => row.sha256);
140
+ const result = { deleted: [], retained: [] };
141
+ for (const sha of candidates) {
142
+ const referenced = this.store.db.prepare(`SELECT 1 FROM events e JOIN tasks t ON t.id=e.task_id
143
+ WHERE t.context!='preview' AND instr(e.detail_json, ?)>0 LIMIT 1`).get(sha);
144
+ if (!referenced)
145
+ await this.artifacts.delete(sha);
146
+ this.store.db.prepare('INSERT OR REPLACE INTO artifact_sweeps(sha256,outcome,swept_ms) VALUES (?,?,?)').run(sha, referenced ? 'retained' : 'deleted', nowMs);
147
+ (referenced ? result.retained : result.deleted).push(sha);
148
+ }
149
+ return result;
150
+ }
151
+ /** Current (unexpired) manifests a task registered, oldest first. */
152
+ forTask(taskId, limit = 100) {
153
+ return this.store.db.prepare(`${this.#select} WHERE m.task_id=? AND m.expires_ms>? ORDER BY m.created_ms, m.artifact_id LIMIT ?`)
154
+ .all(taskId, Date.now(), Math.max(1, Math.min(limit, 500))).map(raw => this.#record(raw));
155
+ }
156
+ /** The newest current manifest for a digest. */
157
+ manifest(sha256) {
158
+ if (!digest.safeParse(sha256).success)
159
+ return undefined;
160
+ const raw = this.store.db.prepare(`${this.#select} WHERE m.sha256=? AND m.expires_ms>? ORDER BY m.created_ms DESC, m.artifact_id DESC LIMIT 1`)
161
+ .get(sha256, Date.now());
162
+ return raw ? this.#record(raw) : undefined;
163
+ }
164
+ #select = `SELECT m.artifact_id, m.task_id, m.sha256, m.manifest_json,
165
+ (SELECT n.sha256 FROM artifact_manifests n WHERE n.supersedes_sha256=m.sha256 ORDER BY n.created_ms DESC LIMIT 1) AS superseded_by
166
+ FROM artifact_manifests m`;
167
+ #record(raw) {
168
+ const row = Row.parse(raw);
169
+ return { task_id: row.task_id, superseded_by_sha256: row.superseded_by,
170
+ manifest: ArtifactManifestSchema.parse(JSON.parse(row.manifest_json)) };
171
+ }
172
+ }
@@ -7,9 +7,17 @@ export declare const ArtifactSchema: z.ZodObject<{
7
7
  name: z.ZodString;
8
8
  }, z.core.$strict>;
9
9
  export type Artifact = z.infer<typeof ArtifactSchema>;
10
+ /** Default per-artifact limit (`artifacts.max_bytes`). */
11
+ export declare const ARTIFACT_DEFAULT_MAX_BYTES: number;
12
+ /** Largest per-artifact limit a profile may configure; also the bound on reading a stored artifact. */
13
+ export declare const ARTIFACT_MAX_BYTES_LIMIT: number;
14
+ export declare function formatBytes(bytes: number): string;
10
15
  export declare class ArtifactStore {
11
16
  readonly directory: string;
12
- constructor(directory: string);
17
+ readonly maxBytes: number;
18
+ constructor(directory: string, maxBytes?: number);
13
19
  put(name: string, mediaType: string, bytes: Uint8Array): Promise<Artifact>;
20
+ /** Remove stored bytes. Callers must prove nothing else still references them. */
21
+ delete(id: string): Promise<void>;
14
22
  get(id: string): Promise<Uint8Array>;
15
23
  }
package/dist/artifacts.js CHANGED
@@ -1,19 +1,30 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { constants } from 'node:fs';
3
- import { mkdir, open, rename, writeFile } from 'node:fs/promises';
3
+ import { mkdir, open, rename, unlink, writeFile } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { z } from 'zod';
6
6
  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
+ /** Default per-artifact limit (`artifacts.max_bytes`). */
8
+ export const ARTIFACT_DEFAULT_MAX_BYTES = 2 * 1024 * 1024;
9
+ /** Largest per-artifact limit a profile may configure; also the bound on reading a stored artifact. */
10
+ export const ARTIFACT_MAX_BYTES_LIMIT = 64 * 1024 * 1024;
11
+ export function formatBytes(bytes) {
12
+ return bytes % (1024 * 1024) === 0 ? `${bytes / (1024 * 1024)} MiB` : bytes % 1024 === 0 ? `${bytes / 1024} KiB` : `${bytes} bytes`;
13
+ }
7
14
  export class ArtifactStore {
8
15
  directory;
9
- constructor(directory) {
16
+ maxBytes;
17
+ constructor(directory, maxBytes = ARTIFACT_DEFAULT_MAX_BYTES) {
10
18
  this.directory = directory;
19
+ this.maxBytes = maxBytes;
20
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > ARTIFACT_MAX_BYTES_LIMIT)
21
+ throw new Error('Invalid artifact byte limit');
11
22
  }
12
23
  async put(name, mediaType, bytes) {
13
24
  if (!/^[A-Za-z0-9._-]{1,128}$/.test(name))
14
25
  throw new Error('Invalid artifact name');
15
- if (bytes.length > 2 * 1024 * 1024)
16
- throw new Error('Artifact exceeds 2 MiB');
26
+ if (bytes.length > this.maxBytes)
27
+ throw new Error(`Artifact exceeds ${formatBytes(this.maxBytes)}`);
17
28
  const digest = createHash('sha256').update(bytes).digest('hex');
18
29
  await mkdir(this.directory, { recursive: true, mode: 0o700 });
19
30
  const temporary = join(this.directory, `.${digest}.${process.pid}.${Date.now()}`);
@@ -21,13 +32,24 @@ export class ArtifactStore {
21
32
  await rename(temporary, join(this.directory, digest));
22
33
  return { id: digest, sha256: digest, bytes: bytes.length, media_type: mediaType, name };
23
34
  }
35
+ /** Remove stored bytes. Callers must prove nothing else still references them. */
36
+ async delete(id) {
37
+ if (!/^[a-f0-9]{64}$/.test(id))
38
+ throw new Error('Invalid artifact ID');
39
+ await unlink(join(this.directory, id)).catch((error) => {
40
+ if (!(error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT'))
41
+ throw error;
42
+ });
43
+ }
24
44
  async get(id) {
25
45
  if (!/^[a-f0-9]{64}$/.test(id))
26
46
  throw new Error('Invalid artifact ID');
27
47
  const file = await open(join(this.directory, id), constants.O_RDONLY | constants.O_NOFOLLOW);
28
48
  try {
29
49
  const stat = await file.stat();
30
- if (!stat.isFile() || stat.size > 2 * 1024 * 1024)
50
+ // Reads accept anything a profile could have stored under its largest
51
+ // permitted limit, so lowering the limit never hides earlier artifacts.
52
+ if (!stat.isFile() || stat.size > ARTIFACT_MAX_BYTES_LIMIT)
31
53
  throw new Error('Artifact file is unsafe');
32
54
  const bytes = await file.readFile();
33
55
  if (createHash('sha256').update(bytes).digest('hex') !== id)
package/dist/channels.js CHANGED
@@ -11,6 +11,9 @@ export const ChannelEvent = z.object({
11
11
  }).strict();
12
12
  export class DeliveryRejectedError extends Error {
13
13
  }
14
+ const SourceResult = z.object({ result: z.object({ ok: z.literal(true), value: z.unknown().optional() }) });
15
+ const Source = z.object({ source_id: z.string(), url: z.string().url().optional() }).passthrough();
16
+ const SourceValue = z.object({ results: z.array(Source).optional(), search: z.object({ results: z.array(Source) }).passthrough().optional() }).passthrough();
14
17
  function eventScope(event) {
15
18
  return { caller: `${event.platform}:${event.account}:${event.user}`, key: `${event.platform}:${event.account}:${event.conversation}:${event.thread ?? ''}` };
16
19
  }
@@ -22,11 +25,10 @@ function sourceReply(runtime, caller) {
22
25
  for (const event of runtime.store.events(task.id, 0, 500)) {
23
26
  if (event.kind !== 'tool_result')
24
27
  continue;
25
- const result = z.object({ result: z.object({ ok: z.literal(true), value: z.unknown().optional() }) }).safeParse(event.detail);
28
+ const result = SourceResult.safeParse(event.detail);
26
29
  if (!result.success)
27
30
  continue;
28
- const source = z.object({ source_id: z.string(), url: z.string().url().optional() }).passthrough();
29
- const value = z.object({ results: z.array(source).optional(), search: z.object({ results: z.array(source) }).passthrough().optional() }).passthrough().safeParse(result.data.result.value);
31
+ const value = SourceValue.safeParse(result.data.result.value);
30
32
  if (!value.success)
31
33
  continue;
32
34
  for (const item of [...(value.data.results ?? []), ...(value.data.search?.results ?? [])])
@@ -0,0 +1,22 @@
1
+ import { MissionSubmit } from './missions.js';
2
+ import { PreviewSubmit } from './preview.js';
3
+ /** Options as parsed by the CLI: `--name value` or a bare `--flag`. */
4
+ export type CliOptions = ReadonlyMap<string, string | true>;
5
+ type ReadText = (path: string) => Promise<string>;
6
+ /**
7
+ * `ardent mission submit --mission-file FILE [--prompt TEXT] [--idempotency-key KEY] [--session-id UUID]`.
8
+ * The file holds a `POST /api/v1/missions` body; flags replace its objective, key and session.
9
+ */
10
+ export declare function missionSubmitInput(options: CliOptions, read: ReadText): Promise<MissionSubmit>;
11
+ /**
12
+ * `ardent preview --prompt TEXT [--soul-file FILE] [--identity-file FILE] [--skills a,b | --no-skills] [--model NAME]`.
13
+ * Override files are read only to build the preview; the profile is not changed.
14
+ */
15
+ export declare function previewInput(options: CliOptions, read: ReadText): Promise<PreviewSubmit>;
16
+ /** `ardent development list [--after CURSOR] [--limit N] [--kind KIND]`. */
17
+ export declare function developmentQuery(options: CliOptions): {
18
+ after?: string;
19
+ limit?: number;
20
+ kind?: string;
21
+ };
22
+ export {};
@@ -0,0 +1,72 @@
1
+ import { z } from 'zod';
2
+ import { MissionSubmit } from './missions.js';
3
+ import { PreviewSubmit } from './preview.js';
4
+ import { DevelopmentKind } from './development.js';
5
+ function option(options, name) {
6
+ const found = options.get(name);
7
+ return typeof found === 'string' ? found : undefined;
8
+ }
9
+ /**
10
+ * `ardent mission submit --mission-file FILE [--prompt TEXT] [--idempotency-key KEY] [--session-id UUID]`.
11
+ * The file holds a `POST /api/v1/missions` body; flags replace its objective, key and session.
12
+ */
13
+ export async function missionSubmitInput(options, read) {
14
+ const file = option(options, 'mission-file');
15
+ if (!file)
16
+ throw new Error('Use mission submit --mission-file FILE [--prompt TEXT] [--idempotency-key KEY]');
17
+ const text = await read(file);
18
+ if (Buffer.byteLength(text) > 200 * 1024)
19
+ throw new Error('Mission file exceeds 200 KiB');
20
+ let value;
21
+ try {
22
+ value = JSON.parse(text);
23
+ }
24
+ catch {
25
+ throw new Error('Mission file must be JSON');
26
+ }
27
+ const body = z.record(z.string(), z.unknown()).parse(value);
28
+ const prompt = option(options, 'prompt');
29
+ const key = option(options, 'idempotency-key');
30
+ const session = option(options, 'session-id');
31
+ const parsed = MissionSubmit.safeParse({ ...body, ...(prompt ? { objective: prompt } : {}), ...(key ? { idempotency_key: key } : {}),
32
+ ...(session ? { session_id: session } : {}) });
33
+ if (!parsed.success)
34
+ throw new Error(`Invalid mission: ${parsed.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; ')}`);
35
+ return parsed.data;
36
+ }
37
+ /**
38
+ * `ardent preview --prompt TEXT [--soul-file FILE] [--identity-file FILE] [--skills a,b | --no-skills] [--model NAME]`.
39
+ * Override files are read only to build the preview; the profile is not changed.
40
+ */
41
+ export async function previewInput(options, read) {
42
+ const prompt = option(options, 'prompt');
43
+ if (!prompt)
44
+ throw new Error('Use preview --prompt TEXT [--soul-file FILE] [--identity-file FILE] [--skills a,b] [--model NAME]');
45
+ const soulFile = option(options, 'soul-file');
46
+ const identityFile = option(options, 'identity-file');
47
+ const skills = option(options, 'skills');
48
+ const model = option(options, 'model');
49
+ const parsed = PreviewSubmit.safeParse({ prompt, overrides: {
50
+ ...(soulFile ? { soul: await read(soulFile) } : {}),
51
+ ...(identityFile ? { identity: await read(identityFile) } : {}),
52
+ ...(skills !== undefined ? { skills_enabled: skills.split(',').map(item => item.trim()).filter(Boolean) } : options.has('no-skills') ? { skills_enabled: [] } : {}),
53
+ ...(model ? { model } : {})
54
+ } });
55
+ if (!parsed.success)
56
+ throw new Error(`Invalid preview: ${parsed.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; ')}`);
57
+ return parsed.data;
58
+ }
59
+ /** `ardent development list [--after CURSOR] [--limit N] [--kind KIND]`. */
60
+ export function developmentQuery(options) {
61
+ const after = option(options, 'after');
62
+ const limit = option(options, 'limit');
63
+ const kind = option(options, 'kind');
64
+ if (limit !== undefined && !/^\d{1,3}$/.test(limit))
65
+ throw new Error('--limit must be a number from 1 to 200');
66
+ const parsed = z.object({ after: z.string().min(1).max(400).optional(), limit: z.number().int().min(1).max(200).optional(), kind: DevelopmentKind.optional() })
67
+ .safeParse({ after, limit: limit === undefined ? undefined : Number(limit), kind });
68
+ if (!parsed.success)
69
+ throw new Error('Use development list [--after CURSOR] [--limit 1-200] [--kind KIND]');
70
+ return { ...(parsed.data.after ? { after: parsed.data.after } : {}), ...(parsed.data.limit ? { limit: parsed.data.limit } : {}),
71
+ ...(parsed.data.kind ? { kind: parsed.data.kind } : {}) };
72
+ }