@hearsay-tools/squawk 0.19.0-dev.9075 → 0.19.0-dev.9086

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.
Files changed (103) hide show
  1. package/dist/boot.d.ts +1 -1
  2. package/dist/boot.js +3 -1
  3. package/dist/boot.js.map +1 -1
  4. package/dist/built-in-cli-commands.js +1 -1
  5. package/dist/built-in-cli-commands.js.map +1 -1
  6. package/dist/built-in-launch-parts.js +1 -1
  7. package/dist/built-in-launch-parts.js.map +1 -1
  8. package/dist/built-in-run-slots.d.ts +1 -1
  9. package/dist/built-in-run-slots.js +7 -3
  10. package/dist/built-in-run-slots.js.map +1 -1
  11. package/dist/core/live-topic-registry.d.ts +29 -0
  12. package/dist/core/live-topic-registry.js +68 -0
  13. package/dist/core/live-topic-registry.js.map +1 -0
  14. package/dist/core/server-hook-registry.d.ts +2 -0
  15. package/dist/core/server-hook-registry.js.map +1 -1
  16. package/dist/delegation/results.js +4 -3
  17. package/dist/delegation/results.js.map +1 -1
  18. package/dist/delegation/routes.d.ts +15 -15
  19. package/dist/delegation/transport.d.ts +10 -10
  20. package/dist/features/reports/capability.d.ts +3 -0
  21. package/dist/features/reports/capability.js +6 -0
  22. package/dist/features/reports/capability.js.map +1 -0
  23. package/dist/features/reports/index.d.ts +13 -0
  24. package/dist/features/reports/index.js +12 -0
  25. package/dist/features/reports/index.js.map +1 -0
  26. package/dist/features/reports/live-topic.d.ts +5 -0
  27. package/dist/{server/reports-topic.js → features/reports/live-topic.js} +10 -7
  28. package/dist/features/reports/live-topic.js.map +1 -0
  29. package/dist/{artifacts → features/reports}/reports-index.d.ts +5 -5
  30. package/dist/{artifacts → features/reports}/reports-index.js +8 -9
  31. package/dist/features/reports/reports-index.js.map +1 -0
  32. package/dist/{artifacts → features/reports}/reports-watch.d.ts +3 -3
  33. package/dist/{artifacts → features/reports}/reports-watch.js +2 -2
  34. package/dist/features/reports/reports-watch.js.map +1 -0
  35. package/dist/{server/reports-api.d.ts → features/reports/routes.d.ts} +6 -2
  36. package/dist/features/reports/routes.js +32 -0
  37. package/dist/features/reports/routes.js.map +1 -0
  38. package/dist/features/reports/server-hook.d.ts +8 -0
  39. package/dist/features/reports/server-hook.js +25 -0
  40. package/dist/features/reports/server-hook.js.map +1 -0
  41. package/dist/plugin/api.d.ts +3 -0
  42. package/dist/plugin/api.js +10 -1
  43. package/dist/plugin/api.js.map +1 -1
  44. package/dist/plugin/cli.js +1 -1
  45. package/dist/plugin/cli.js.map +1 -1
  46. package/dist/plugin/index.d.ts +1 -0
  47. package/dist/plugin/index.js.map +1 -1
  48. package/dist/runs/run-archive.d.ts +72 -72
  49. package/dist/server/activity-routes.js +0 -2
  50. package/dist/server/activity-routes.js.map +1 -1
  51. package/dist/{artifacts/resolve.js → server/file-link.js} +3 -3
  52. package/dist/server/file-link.js.map +1 -0
  53. package/dist/server/plugin-live-topics.d.ts +18 -0
  54. package/dist/server/plugin-live-topics.js +120 -0
  55. package/dist/server/plugin-live-topics.js.map +1 -0
  56. package/dist/server/project-context.js +0 -2
  57. package/dist/server/project-context.js.map +1 -1
  58. package/dist/server/project-run-files.js +1 -1
  59. package/dist/server/project-run-files.js.map +1 -1
  60. package/dist/server/repo-routes.d.ts +13 -13
  61. package/dist/server/runs-routes.d.ts +20 -20
  62. package/dist/server/runs-routes.js +2 -2
  63. package/dist/server/runs-routes.js.map +1 -1
  64. package/dist/server/server.d.ts +309 -482
  65. package/dist/server/server.js +3 -4
  66. package/dist/server/server.js.map +1 -1
  67. package/dist/server/start-server.js +6 -3
  68. package/dist/server/start-server.js.map +1 -1
  69. package/dist/{artifacts/cli.js → task-files/artifact-cli.js} +2 -2
  70. package/dist/task-files/artifact-cli.js.map +1 -0
  71. package/dist/{artifacts/store.d.ts → task-files/artifact-kind.d.ts} +14 -17
  72. package/dist/task-files/artifact-kind.js +123 -0
  73. package/dist/task-files/artifact-kind.js.map +1 -0
  74. package/dist/task-files/kind.d.ts +55 -0
  75. package/dist/task-files/kind.js +68 -0
  76. package/dist/task-files/kind.js.map +1 -0
  77. package/dist/{artifacts → task-files}/lifecycle.d.ts +0 -1
  78. package/dist/{artifacts → task-files}/lifecycle.js +3 -28
  79. package/dist/task-files/lifecycle.js.map +1 -0
  80. package/dist/task-files/removal-slot.d.ts +3 -0
  81. package/dist/task-files/removal-slot.js +20 -0
  82. package/dist/task-files/removal-slot.js.map +1 -0
  83. package/dist/task-files/store.d.ts +37 -0
  84. package/dist/{artifacts → task-files}/store.js +150 -155
  85. package/dist/task-files/store.js.map +1 -0
  86. package/dist/workflows/continuation-admission.d.ts +72 -72
  87. package/dist/workflows/run/wait-engine.d.ts +72 -72
  88. package/package.json +4 -4
  89. package/dist/artifacts/cli.js.map +0 -1
  90. package/dist/artifacts/lifecycle.js.map +0 -1
  91. package/dist/artifacts/removal-slot.d.ts +0 -3
  92. package/dist/artifacts/removal-slot.js +0 -7
  93. package/dist/artifacts/removal-slot.js.map +0 -1
  94. package/dist/artifacts/reports-index.js.map +0 -1
  95. package/dist/artifacts/reports-watch.js.map +0 -1
  96. package/dist/artifacts/resolve.js.map +0 -1
  97. package/dist/artifacts/store.js.map +0 -1
  98. package/dist/server/reports-api.js +0 -22
  99. package/dist/server/reports-api.js.map +0 -1
  100. package/dist/server/reports-topic.d.ts +0 -5
  101. package/dist/server/reports-topic.js.map +0 -1
  102. /package/dist/{artifacts/resolve.d.ts → server/file-link.d.ts} +0 -0
  103. /package/dist/{artifacts/cli.d.ts → task-files/artifact-cli.d.ts} +0 -0
@@ -1,4 +1,3 @@
1
1
  /** Generated run-owned location; never let inherited parent session paths leak into a child. */
2
2
  export declare function provisionArtifactDirectory(dataDir: string, runId: string): string;
3
- export declare function removeArtifacts(dataDir: string, runId: string): void;
4
3
  export declare function artifactInstructions(directory: string | undefined): string;
@@ -1,34 +1,9 @@
1
- import { mkdirSync, realpathSync, rmSync, statSync } from 'node:fs';
2
- import { dirname } from 'node:path';
3
- import { artifactDirectory } from './store.js';
4
1
  import { fileURLToPath } from 'node:url';
2
+ import { artifactKind } from './artifact-kind.js';
3
+ import { provisionTaskFileDirectory } from './store.js';
5
4
  /** Generated run-owned location; never let inherited parent session paths leak into a child. */
6
5
  export function provisionArtifactDirectory(dataDir, runId) {
7
- try {
8
- const directory = artifactDirectory(dataDir, runId);
9
- const parent = dirname(directory);
10
- if (realpathSync(parent) !== parent)
11
- return '';
12
- try {
13
- mkdirSync(directory, { mode: 0o700 });
14
- }
15
- catch (error) {
16
- if (error.code !== 'EEXIST')
17
- return '';
18
- }
19
- return realpathSync(directory) === directory && statSync(directory).isDirectory() ? directory : '';
20
- }
21
- catch {
22
- return '';
23
- }
24
- }
25
- export function removeArtifacts(dataDir, runId) {
26
- const directory = artifactDirectory(dataDir, runId);
27
- const parent = dirname(directory);
28
- if (realpathSync(parent) !== parent)
29
- throw Error('Artifact storage redirected');
30
- // rm removes a final symlink itself, never the directory it points at.
31
- rmSync(directory, { recursive: true, force: true });
6
+ return provisionTaskFileDirectory(artifactKind, dataDir, runId);
32
7
  }
33
8
  const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
34
9
  export function artifactInstructions(directory) {
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycle.js","sourceRoot":"","sources":["../../src/task-files/lifecycle.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AAExD,gGAAgG;AAChG,MAAM,UAAU,0BAA0B,CAAC,OAAe,EAAE,KAAa;IACvE,OAAO,0BAA0B,CAAC,YAAY,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAClE,CAAC;AAED,MAAM,KAAK,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,IAAI,KAAK,CAAC,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC;AACvE,MAAM,UAAU,oBAAoB,CAAC,SAA6B;IAChE,IAAI,CAAC,SAAS;QAAE,OAAO,oIAAoI,CAAC;IAC5J,MAAM,MAAM,GAAG,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC/C,MAAM,KAAK,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,aAAa,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAC9F,MAAM,OAAO,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,EAAE,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,mBAAmB,CAAC;IAClJ,OAAO,4GAA4G,OAAO,8kBAA8kB,CAAC;AAC3sB,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { RemovalCleanup } from '../runs/removal-slots.ts';
2
+ /** Removes every registered task file kind's folder for a run when its history goes. */
3
+ export declare const taskFilesRemovalCleanup: RemovalCleanup;
@@ -0,0 +1,20 @@
1
+ import { registeredTaskFileKinds } from './kind.js';
2
+ import { removeTaskFiles } from './store.js';
3
+ /** Removes every registered task file kind's folder for a run when its history goes. */
4
+ export const taskFilesRemovalCleanup = {
5
+ name: 'task-files',
6
+ removed(runId, dataDir) {
7
+ const failures = [];
8
+ for (const kind of registeredTaskFileKinds()) {
9
+ try {
10
+ removeTaskFiles(kind, dataDir, runId);
11
+ }
12
+ catch (error) {
13
+ failures.push(error);
14
+ }
15
+ }
16
+ if (failures.length)
17
+ throw failures[0];
18
+ },
19
+ };
20
+ //# sourceMappingURL=removal-slot.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"removal-slot.js","sourceRoot":"","sources":["../../src/task-files/removal-slot.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,wFAAwF;AACxF,MAAM,CAAC,MAAM,uBAAuB,GAAmB;IACrD,IAAI,EAAE,YAAY;IAClB,OAAO,CAAC,KAAK,EAAE,OAAO;QACpB,MAAM,QAAQ,GAAc,EAAE,CAAC;QAC/B,KAAK,MAAM,IAAI,IAAI,uBAAuB,EAAE,EAAE,CAAC;YAC7C,IAAI,CAAC;gBAAC,eAAe,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;YAAC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAAC,CAAC;QACxF,CAAC;QACD,IAAI,QAAQ,CAAC,MAAM;YAAE,MAAM,QAAQ,CAAC,CAAC,CAAC,CAAC;IACzC,CAAC;CACF,CAAC"}
@@ -0,0 +1,37 @@
1
+ import type { TaskFileKind, TaskFileRecord } from './kind.ts';
2
+ export type TaskFileIndexResult<T> = {
3
+ state: 'read';
4
+ value: T;
5
+ } | {
6
+ state: 'missing';
7
+ } | {
8
+ state: 'indeterminate';
9
+ error: unknown;
10
+ };
11
+ /** Resolve only the trusted data root; runs and task redirects remain forbidden. */
12
+ export declare function taskFileRunsRoot(dataDir: string): string;
13
+ /** Build the task-file directory for a kind under an already-resolved runs root. */
14
+ export declare function taskFileDirectoryInRunsRoot(kind: Pick<TaskFileKind, 'folderSuffix'>, runsRoot: string, runId: string): string;
15
+ export declare function taskFileDirectory(kind: Pick<TaskFileKind, 'folderSuffix'>, runsDataDir: string, runId: string): string;
16
+ /** Return the stored content file path for one entry inside a kind's run directory. */
17
+ export declare function taskFileContentPath(directory: string, id: string): string;
18
+ /** Provision a run-owned directory for a kind without following a redirected parent or folder. */
19
+ export declare function provisionTaskFileDirectory(kind: Pick<TaskFileKind, 'folderSuffix'>, dataDir: string, runId: string): string;
20
+ /** Remove a run's folder for a kind. A redirected parent throws; a missing folder is not an error. */
21
+ export declare function removeTaskFiles(kind: Pick<TaskFileKind, 'folderSuffix'>, dataDir: string, runId: string): void;
22
+ export declare function publishTaskFile<TRecord extends TaskFileRecord>(kind: TaskFileKind<TRecord>, directory: string, runId: string, source: string): Promise<TRecord>;
23
+ export declare function readTaskFile<TRecord extends TaskFileRecord>(kind: TaskFileKind<TRecord>, directory: string, runId: string, id: string): Promise<{
24
+ metadata: TRecord;
25
+ bytes: Buffer;
26
+ } | null>;
27
+ export declare function readTaskFileRecord<TRecord extends TaskFileRecord>(kind: TaskFileKind<TRecord>, directory: string, runId: string, id: string): Promise<TRecord | null>;
28
+ /** Internal index read: an I/O failure cannot prove that a published snapshot is gone. */
29
+ export declare function readTaskFileRecordForIndex<TRecord extends TaskFileRecord>(kind: TaskFileKind<TRecord>, directory: string, runId: string, id: string): Promise<TaskFileIndexResult<TRecord>>;
30
+ /** Shares the public list's validated bounded walk and per-entry reader, preserving uncertain IDs. */
31
+ export declare function scanTaskFilesForIndex<TRecord extends TaskFileRecord>(kind: TaskFileKind<TRecord>, directory: string, runId: string): Promise<TaskFileIndexResult<{
32
+ records: TRecord[];
33
+ indeterminate: string[];
34
+ }>>;
35
+ /** Page checks use the same validated storage components and per-file cap as the reader. */
36
+ export declare function checkTaskFileContentForIndex(kind: Pick<TaskFileKind, 'id' | 'folderSuffix' | 'limits'>, directory: string, runId: string, id: string, size: number): Promise<TaskFileIndexResult<boolean>>;
37
+ export declare function listTaskFiles<TRecord extends TaskFileRecord>(kind: TaskFileKind<TRecord>, directory: string, runId: string): Promise<TRecord[]>;
@@ -1,113 +1,81 @@
1
1
  import { runDataDir } from '../legacy-runs.js';
2
2
  import { randomUUID, createHash } from 'node:crypto';
3
- import { constants, realpathSync } from 'node:fs';
3
+ import { constants, mkdirSync, realpathSync, rmSync, statSync } from 'node:fs';
4
4
  import { mkdir, open, opendir, realpath, lstat, rename, rm, writeFile } from 'node:fs/promises';
5
5
  import { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';
6
6
  import { hostname } from 'node:os';
7
7
  import { setTimeout as delay } from 'node:timers/promises';
8
8
  import { z } from 'zod';
9
- import { publishedArtifactSchema } from '../contract/index.js';
10
9
  import { assertProjectAdmitted, projectWriteRefused } from '../project-fence.js';
11
- const MAX_FILE_BYTES = 10 * 1024 * 1024;
12
10
  const MAX_METADATA_BYTES = 32 * 1024;
13
- const MAX_RUN_BYTES = 64 * 1024 * 1024;
14
- const MAX_ARTIFACTS = 64;
15
11
  const MAX_DIRECTORY_ENTRIES = 1024;
16
- class InvalidArtifactError extends Error {
12
+ class InvalidTaskFileError extends Error {
17
13
  }
18
- class ArtifactLimitError extends Error {
14
+ class TaskFileLimitError extends Error {
19
15
  }
20
- class RedirectedArtifactError extends Error {
16
+ class RedirectedTaskFileError extends Error {
21
17
  }
22
18
  const readFlags = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK;
23
- const TITLE_PREFIX_BYTES = 64 * 1024;
24
- const TITLE_ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', AMP: '&', LT: '<', GT: '>', QUOT: '"' };
25
- // HTML numeric-reference replacements; the five unmapped C1 controls stay controls.
26
- const TITLE_NUMERIC = {
27
- 128: 0x20ac, 130: 0x201a, 131: 0x192, 132: 0x201e, 133: 0x2026, 134: 0x2020, 135: 0x2021,
28
- 136: 0x2c6, 137: 0x2030, 138: 0x160, 139: 0x2039, 140: 0x152, 142: 0x17d,
29
- 145: 0x2018, 146: 0x2019, 147: 0x201c, 148: 0x201d, 149: 0x2022, 150: 0x2013, 151: 0x2014,
30
- 152: 0x2dc, 153: 0x2122, 154: 0x161, 155: 0x203a, 156: 0x153, 158: 0x17e, 159: 0x178,
31
- };
32
- /** Read display text only. RCDATA markup stays literal; nothing is loaded or executed. */
33
- export function artifactTitle(name, bytes) {
34
- if (!/\.html?$/i.test(name))
35
- return undefined;
36
- const html = bytes.subarray(0, TITLE_PREFIX_BYTES).toString('utf8');
37
- // Consume whole quoted attributes before interpreting another tag, including in templates.
38
- const tail = String.raw `(?:[^"'>]|"[^"]*"|'[^']*')*>`;
39
- const incomplete = String.raw `<[a-z/](?:[^"'>]|"[^"]*(?:"|$)|'[^']*(?:'|$))*$`;
40
- const tags = new RegExp(String.raw `<!--(?:>|->|[\s\S]*?(?:--!?>|$))|<![^>]*(?:>|$)|<\?[^>]*(?:>|$)|<\/[^a-z>][^>]*(?:>|$)|<\/>|<(\/?)([a-z][^\s/>]*)(?=[\s/>])${tail}|(${incomplete})`, 'gi');
41
- let templateDepth = 0;
42
- let foreignDepth = 0;
43
- for (let tag = tags.exec(html); tag; tag = tags.exec(html)) {
44
- const kind = tag[2]?.toLowerCase();
45
- if (tag[3])
46
- return undefined;
47
- if (!kind)
48
- continue;
49
- const closing = tag[1] === '/';
50
- if (/^(?:svg|math)$/.test(kind)) {
51
- if (closing)
52
- foreignDepth = Math.max(0, foreignDepth - 1);
53
- else if (!tag[0].endsWith('/>'))
54
- foreignDepth++;
55
- continue;
56
- }
57
- if (kind === 'template') {
58
- templateDepth = closing ? Math.max(0, templateDepth - 1) : templateDepth + 1;
59
- continue;
60
- }
61
- if (closing)
62
- continue;
63
- if (kind === 'plaintext')
64
- return undefined;
65
- if (kind === 'title' && templateDepth + foreignDepth === 0) {
66
- const end = new RegExp(String.raw `<\/title(?=[\s/>])${tail}`, 'gi');
67
- end.lastIndex = tags.lastIndex;
68
- const close = end.exec(html);
69
- if (!close)
70
- return undefined;
71
- const title = html.slice(tags.lastIndex, close.index).replace(/&(#(?:x[\da-f]+|\d+)|amp|lt|gt|quot|apos|nbsp);/gi, (entity, code) => {
72
- if (!code.startsWith('#'))
73
- return TITLE_ENTITIES[code] ?? entity;
74
- const numeric = code[1]?.toLowerCase() === 'x' ? Number.parseInt(code.slice(2), 16) : Number(code.slice(1));
75
- const value = TITLE_NUMERIC[numeric] ?? numeric;
76
- return value > 0 && value <= 0x10ffff && !(value >= 0xd800 && value <= 0xdfff) ? String.fromCodePoint(value) : '\uFFFD';
77
- }).replace(/[\u0000-\u0008\u000b\u000e-\u001f\u007f-\u009f]/g, '').replace(/\s+/g, ' ').trim().slice(0, 200).replace(/[\uD800-\uDBFF]$/, '');
78
- return title || undefined;
79
- }
80
- // Skip raw text even in a template: its literal closing tags cannot end the template.
81
- if (/^(?:script|style|textarea|xmp|noscript|iframe|noembed|noframes|title)$/.test(kind)) {
82
- const end = new RegExp(String.raw `<\/${kind}(?=[\s/>])${tail}`, 'gi');
83
- end.lastIndex = tags.lastIndex;
84
- if (!end.exec(html))
85
- return undefined;
86
- tags.lastIndex = end.lastIndex;
87
- }
88
- }
89
- return undefined;
90
- }
91
- function validateContext(directory, runId) {
19
+ function validateContext(kind, directory, runId) {
92
20
  z.uuid().parse(runId);
93
- if (!isAbsolute(directory) || basename(directory) !== `${runId}-artifacts`)
94
- throw new Error('Invalid artifact task directory');
21
+ if (!isAbsolute(directory) || basename(directory) !== `${runId}-${kind.folderSuffix}`) {
22
+ throw new Error(`Invalid task file directory for kind '${kind.id}'`);
23
+ }
95
24
  }
96
25
  /** Resolve only the trusted data root; runs and task redirects remain forbidden. */
97
- export function artifactRunsRoot(dataDir) {
26
+ export function taskFileRunsRoot(dataDir) {
98
27
  return join(realpathSync(resolve(dataDir)), 'runs');
99
28
  }
100
- export function artifactDirectory(runsDataDir, runId) {
29
+ /** Build the task-file directory for a kind under an already-resolved runs root. */
30
+ export function taskFileDirectoryInRunsRoot(kind, runsRoot, runId) {
31
+ z.uuid().parse(runId);
32
+ return join(runsRoot, `${runId}-${kind.folderSuffix}`);
33
+ }
34
+ export function taskFileDirectory(kind, runsDataDir, runId) {
101
35
  z.uuid().parse(runId);
102
36
  const dataDir = runDataDir(runsDataDir, runId);
103
37
  let root;
104
38
  try {
105
- root = artifactRunsRoot(dataDir);
39
+ root = taskFileRunsRoot(dataDir);
106
40
  }
107
41
  catch {
108
42
  root = join(resolve(dataDir), 'runs');
109
43
  } // Preserve unavailable-storage behavior for public readers.
110
- return join(root, `${runId}-artifacts`);
44
+ return join(root, `${runId}-${kind.folderSuffix}`);
45
+ }
46
+ /** Return the stored content file path for one entry inside a kind's run directory. */
47
+ export function taskFileContentPath(directory, id) {
48
+ z.uuid().parse(id);
49
+ return join(directory, id, 'content');
50
+ }
51
+ /** Provision a run-owned directory for a kind without following a redirected parent or folder. */
52
+ export function provisionTaskFileDirectory(kind, dataDir, runId) {
53
+ try {
54
+ const directory = taskFileDirectory(kind, dataDir, runId);
55
+ const parent = dirname(directory);
56
+ if (realpathSync(parent) !== parent)
57
+ return '';
58
+ try {
59
+ mkdirSync(directory, { mode: 0o700 });
60
+ }
61
+ catch (error) {
62
+ if (error.code !== 'EEXIST')
63
+ return '';
64
+ }
65
+ return realpathSync(directory) === directory && statSync(directory).isDirectory() ? directory : '';
66
+ }
67
+ catch {
68
+ return '';
69
+ }
70
+ }
71
+ /** Remove a run's folder for a kind. A redirected parent throws; a missing folder is not an error. */
72
+ export function removeTaskFiles(kind, dataDir, runId) {
73
+ const directory = taskFileDirectory(kind, dataDir, runId);
74
+ const parent = dirname(directory);
75
+ if (realpathSync(parent) !== parent)
76
+ throw new Error('Task file storage redirected');
77
+ // rm removes a final symlink itself, never the directory it points at.
78
+ rmSync(directory, { recursive: true, force: true });
111
79
  }
112
80
  function sameFile(a, b) {
113
81
  return a.dev === b.dev && a.ino === b.ino;
@@ -116,16 +84,17 @@ function sameSnapshot(a, b) {
116
84
  return sameFile(a, b) && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs && a.nlink === b.nlink;
117
85
  }
118
86
  /** Never use readFile on untrusted descriptors: a growing file otherwise bypasses the size check. */
119
- async function boundedRead(path, limit, stored = false, prefixBytes, expectedSize) {
87
+ async function boundedRead(path, limit, stored = false, prefixBytes, expectedSize, kindId) {
120
88
  const file = await open(path, readFlags);
121
89
  try {
122
90
  const before = await file.stat({ bigint: true });
123
- if (before.size > BigInt(limit))
124
- throw new ArtifactLimitError('Artifact must be a bounded regular file');
91
+ if (before.size > BigInt(limit)) {
92
+ throw new TaskFileLimitError(`Task file exceeds byte limit${kindId ? ` for kind '${kindId}'` : ''} (${limit} bytes)`);
93
+ }
125
94
  if (!before.isFile() || (stored && before.nlink !== 1n))
126
- throw new InvalidArtifactError('Artifact must be a bounded regular file');
95
+ throw new InvalidTaskFileError('Task file must be a bounded regular file');
127
96
  if (expectedSize !== undefined && before.size !== BigInt(expectedSize))
128
- throw new InvalidArtifactError('Artifact size mismatch');
97
+ throw new InvalidTaskFileError('Task file size mismatch');
129
98
  const expectedRead = Math.min(Number(before.size), prefixBytes ?? Number(before.size));
130
99
  const buffer = Buffer.alloc(prefixBytes === undefined ? expectedRead + 1 : expectedRead);
131
100
  let count = 0;
@@ -137,8 +106,9 @@ async function boundedRead(path, limit, stored = false, prefixBytes, expectedSiz
137
106
  }
138
107
  const after = await file.stat({ bigint: true });
139
108
  const current = await lstat(path, { bigint: true });
140
- if (count !== expectedRead || !sameSnapshot(before, after) || !sameFile(after, current) || current.isSymbolicLink())
141
- throw new Error('File changed while publishing or reading artifact');
109
+ if (count !== expectedRead || !sameSnapshot(before, after) || !sameFile(after, current) || current.isSymbolicLink()) {
110
+ throw new Error('File changed while publishing or reading task file');
111
+ }
142
112
  return buffer.subarray(0, count);
143
113
  }
144
114
  finally {
@@ -149,7 +119,7 @@ async function boundedRead(path, limit, stored = false, prefixBytes, expectedSiz
149
119
  * descriptors; other platforms revalidate identity before/after use, not a same-user sandbox. */
150
120
  async function storageDirectory(path, create = false) {
151
121
  const absolute = resolve(path);
152
- // A writer re-checks the migration fence of `<dataDir>/runs/<task>-artifacts` before each write.
122
+ // A writer re-checks the migration fence of `<dataDir>/runs/<task>-<suffix>` before each write.
153
123
  const admitted = () => { if (create)
154
124
  assertProjectAdmitted(dirname(dirname(absolute))); };
155
125
  let file;
@@ -172,8 +142,9 @@ async function storageDirectory(path, create = false) {
172
142
  const original = await handle.stat({ bigint: true });
173
143
  const check = async () => {
174
144
  admitted();
175
- if (await realpath(absolute) !== absolute || !sameFile(original, await lstat(absolute, { bigint: true })))
176
- throw new RedirectedArtifactError('Redirected artifact storage');
145
+ if (await realpath(absolute) !== absolute || !sameFile(original, await lstat(absolute, { bigint: true }))) {
146
+ throw new RedirectedTaskFileError('Redirected task file storage');
147
+ }
177
148
  };
178
149
  await check();
179
150
  return { path: process.platform === 'linux' ? `/proc/self/fd/${handle.fd}` : absolute, check, close: () => handle.close(), admit: admitted,
@@ -185,7 +156,7 @@ async function storageDirectory(path, create = false) {
185
156
  }
186
157
  }
187
158
  /** Internal index access uses the reader's anchored, no-follow storage validation. */
188
- async function inspectArtifactStorageForIndex(directory, inspect) {
159
+ async function inspectStorageForIndex(directory, inspect) {
189
160
  let root;
190
161
  try {
191
162
  root = await storageDirectory(directory);
@@ -207,7 +178,7 @@ async function* entries(path) {
207
178
  let count = 0;
208
179
  for await (const entry of stream) {
209
180
  if (++count > MAX_DIRECTORY_ENTRIES)
210
- throw new Error('Artifact directory entry limit exceeded');
181
+ throw new Error('Task file directory entry limit exceeded');
211
182
  yield entry.name;
212
183
  }
213
184
  }
@@ -281,7 +252,7 @@ async function acquireLock(root) {
281
252
  throw error;
282
253
  }
283
254
  if (performance.now() >= deadline)
284
- throw new Error('Artifact publication lock is busy or has an unverifiable owner');
255
+ throw new Error('Task file publication lock is busy or has an unverifiable owner');
285
256
  await reclaimDeadLock(root);
286
257
  await delay(20);
287
258
  }
@@ -291,21 +262,26 @@ async function acquireLock(root) {
291
262
  await rm(candidate, { recursive: true, force: true });
292
263
  }
293
264
  }
294
- async function checkCapacity(root, incomingBytes) {
265
+ async function checkCapacity(kind, root, incomingBytes) {
266
+ if (incomingBytes > kind.limits.maxRunBytes) {
267
+ throw new TaskFileLimitError(`Task file byte limit exceeded for kind '${kind.id}' (${kind.limits.maxRunBytes} bytes)`);
268
+ }
295
269
  let count = 0;
296
270
  let bytes = 0;
297
271
  for await (const id of entries(root.path)) {
298
272
  if (!z.uuid().safeParse(id).success && !/^\.pending-[0-9a-f-]{36}$/i.test(id))
299
273
  continue;
300
- if (++count >= MAX_ARTIFACTS)
301
- throw new Error('Artifact count limit exceeded');
274
+ if (++count >= kind.limits.maxFiles) {
275
+ throw new TaskFileLimitError(`Task file count limit exceeded for kind '${kind.id}' (${kind.limits.maxFiles} files)`);
276
+ }
302
277
  let entry;
303
278
  try {
304
279
  entry = await open(join(root.path, id), readFlags | constants.O_DIRECTORY);
305
280
  const pinned = process.platform === 'linux' ? `/proc/self/fd/${entry.fd}` : join(root.path, id);
306
281
  const stat = await lstat(join(pinned, 'content'), { bigint: true });
307
- if (!stat.isFile() || stat.nlink !== 1n || stat.size > BigInt(MAX_FILE_BYTES))
308
- throw new Error('Unsafe stored artifact');
282
+ if (!stat.isFile() || stat.nlink !== 1n || stat.size > BigInt(kind.limits.maxFileBytes)) {
283
+ throw new Error('Unsafe stored task file');
284
+ }
309
285
  bytes += Number(stat.size);
310
286
  }
311
287
  catch (error) {
@@ -315,12 +291,13 @@ async function checkCapacity(root, incomingBytes) {
315
291
  finally {
316
292
  await entry?.close();
317
293
  }
318
- if (bytes + incomingBytes > MAX_RUN_BYTES)
319
- throw new Error('Artifact task byte limit exceeded');
294
+ if (bytes + incomingBytes > kind.limits.maxRunBytes) {
295
+ throw new TaskFileLimitError(`Task file byte limit exceeded for kind '${kind.id}' (${kind.limits.maxRunBytes} bytes)`);
296
+ }
320
297
  }
321
298
  }
322
- export async function publishArtifact(directory, runId, source) {
323
- validateContext(directory, runId);
299
+ export async function publishTaskFile(kind, directory, runId, source) {
300
+ validateContext(kind, directory, runId);
324
301
  const root = await storageDirectory(directory, true);
325
302
  let release;
326
303
  let pending;
@@ -335,15 +312,24 @@ export async function publishArtifact(directory, runId, source) {
335
312
  await rm(join(root.path, id), { recursive: true, force: true });
336
313
  }
337
314
  }
338
- const bytes = await boundedRead(source, MAX_FILE_BYTES);
315
+ const bytes = await boundedRead(source, kind.limits.maxFileBytes, false, undefined, undefined, kind.id);
339
316
  // A same-size rewrite inside one timestamp tick leaves the stat snapshot above
340
317
  // unchanged, so reread and compare: any mutation that landed before this second
341
318
  // read surfaces as differing bytes. Later mutations stay covered by the snapshot.
342
- const reread = await boundedRead(source, MAX_FILE_BYTES);
319
+ const reread = await boundedRead(source, kind.limits.maxFileBytes, false, undefined, undefined, kind.id);
343
320
  if (!bytes.equals(reread))
344
- throw new InvalidArtifactError('File changed while publishing or reading artifact');
345
- await checkCapacity(root, bytes.length);
346
- const metadata = publishedArtifactSchema.parse({ id: randomUUID(), runId, name: basename(source), sourcePath: resolve(source), createdAt: new Date().toISOString(), size: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') });
321
+ throw new InvalidTaskFileError('File changed while publishing or reading task file');
322
+ await checkCapacity(kind, root, bytes.length);
323
+ const metadata = kind.recordSchema.parse(kind.buildRecord({
324
+ id: randomUUID(),
325
+ runId,
326
+ name: basename(source),
327
+ sourcePath: resolve(source),
328
+ createdAt: new Date().toISOString(),
329
+ size: bytes.length,
330
+ sha256: createHash('sha256').update(bytes).digest('hex'),
331
+ bytes,
332
+ }));
347
333
  pending = join(root.path, `.pending-${metadata.id}`);
348
334
  await root.check();
349
335
  root.admit();
@@ -354,8 +340,9 @@ export async function publishArtifact(directory, runId, source) {
354
340
  await writeFile(join(pinned, 'content'), bytes, { mode: 0o600, flag: 'wx' });
355
341
  root.admit();
356
342
  await writeFile(join(pinned, 'metadata.json'), JSON.stringify(metadata), { mode: 0o600, flag: 'wx' });
357
- if (!sameFile(await staging.stat({ bigint: true }), await lstat(pending, { bigint: true })))
358
- throw new Error('Redirected artifact staging');
343
+ if (!sameFile(await staging.stat({ bigint: true }), await lstat(pending, { bigint: true }))) {
344
+ throw new Error('Redirected task file staging');
345
+ }
359
346
  await root.check();
360
347
  root.admit();
361
348
  await rename(pending, join(root.path, metadata.id));
@@ -378,7 +365,11 @@ export async function publishArtifact(directory, runId, source) {
378
365
  }
379
366
  }
380
367
  }
381
- async function readEntry(root, runId, id, metadataOnly = false, strict = false) {
368
+ function prefixLimit(kind, metadata) {
369
+ const requested = kind.metadataPrefixBytes?.(metadata) ?? 0;
370
+ return Math.max(0, Math.min(kind.limits.maxFileBytes, requested));
371
+ }
372
+ async function readEntry(kind, root, runId, id, metadataOnly = false, strict = false) {
382
373
  if (!z.uuid().safeParse(id).success)
383
374
  return null;
384
375
  let entry;
@@ -386,19 +377,20 @@ async function readEntry(root, runId, id, metadataOnly = false, strict = false)
386
377
  await root.check();
387
378
  entry = await open(join(root.path, id), readFlags | constants.O_DIRECTORY);
388
379
  const path = process.platform === 'linux' ? `/proc/self/fd/${entry.fd}` : join(root.path, id);
389
- const metadata = publishedArtifactSchema.parse(JSON.parse((await boundedRead(join(path, 'metadata.json'), MAX_METADATA_BYTES, true)).toString('utf8')));
380
+ const metadata = kind.recordSchema.parse(JSON.parse((await boundedRead(join(path, 'metadata.json'), MAX_METADATA_BYTES, true)).toString('utf8')));
390
381
  if (metadata.runId !== runId || metadata.id !== id)
391
382
  return null;
392
- if (metadata.size > MAX_FILE_BYTES)
393
- throw new ArtifactLimitError('Artifact file byte limit exceeded');
394
- const prefix = /\.html?$/i.test(metadata.name) ? TITLE_PREFIX_BYTES : 0;
395
- const bytes = await boundedRead(join(path, 'content'), MAX_FILE_BYTES, true, metadataOnly ? prefix : undefined, metadata.size);
383
+ if (metadata.size > kind.limits.maxFileBytes) {
384
+ throw new TaskFileLimitError(`Task file byte limit exceeded for kind '${kind.id}' (${kind.limits.maxFileBytes} bytes)`);
385
+ }
386
+ const bytes = await boundedRead(join(path, 'content'), kind.limits.maxFileBytes, true, metadataOnly ? prefixLimit(kind, metadata) : undefined, metadata.size, kind.id);
396
387
  if (!metadataOnly && createHash('sha256').update(bytes).digest('hex') !== metadata.sha256)
397
388
  return null;
398
- if (!sameFile(await entry.stat({ bigint: true }), await lstat(join(root.path, id), { bigint: true })))
399
- throw new RedirectedArtifactError('Redirected artifact storage');
389
+ if (!sameFile(await entry.stat({ bigint: true }), await lstat(join(root.path, id), { bigint: true }))) {
390
+ throw new RedirectedTaskFileError('Redirected task file storage');
391
+ }
400
392
  await root.check();
401
- return { metadata: { ...metadata, title: artifactTitle(metadata.name, bytes) }, bytes };
393
+ return { metadata: kind.computeOnRead ? kind.computeOnRead(metadata, bytes) : metadata, bytes };
402
394
  }
403
395
  catch (error) {
404
396
  if (strict)
@@ -409,12 +401,12 @@ async function readEntry(root, runId, id, metadataOnly = false, strict = false)
409
401
  await entry?.close();
410
402
  }
411
403
  }
412
- async function readStoredArtifact(directory, runId, id, metadataOnly, strict = false) {
404
+ async function readStoredTaskFile(kind, directory, runId, id, metadataOnly, strict = false) {
413
405
  let root;
414
406
  try {
415
- validateContext(directory, runId);
407
+ validateContext(kind, directory, runId);
416
408
  root = await storageDirectory(directory);
417
- return await readEntry(root, runId, id, metadataOnly, strict);
409
+ return await readEntry(kind, root, runId, id, metadataOnly, strict);
418
410
  }
419
411
  catch (error) {
420
412
  if (strict)
@@ -425,40 +417,41 @@ async function readStoredArtifact(directory, runId, id, metadataOnly, strict = f
425
417
  await root?.close();
426
418
  }
427
419
  }
428
- export async function readArtifact(directory, runId, id) {
429
- return readStoredArtifact(directory, runId, id, false);
420
+ export async function readTaskFile(kind, directory, runId, id) {
421
+ return readStoredTaskFile(kind, directory, runId, id, false);
430
422
  }
431
- export async function readArtifactMetadata(directory, runId, id) {
432
- return (await readStoredArtifact(directory, runId, id, true))?.metadata ?? null;
423
+ export async function readTaskFileRecord(kind, directory, runId, id) {
424
+ return (await readStoredTaskFile(kind, directory, runId, id, true))?.metadata ?? null;
433
425
  }
434
426
  function indexReadFailure(error) {
435
- if (error instanceof InvalidArtifactError || error instanceof SyntaxError || error instanceof z.ZodError || error.code === 'ENOENT')
427
+ if (error instanceof InvalidTaskFileError || error instanceof SyntaxError || error instanceof z.ZodError || error.code === 'ENOENT') {
436
428
  return { state: 'missing' };
429
+ }
437
430
  return { state: 'indeterminate', error };
438
431
  }
439
432
  /** Internal index read: an I/O failure cannot prove that a published snapshot is gone. */
440
- export async function readArtifactMetadataForIndex(directory, runId, id) {
433
+ export async function readTaskFileRecordForIndex(kind, directory, runId, id) {
441
434
  try {
442
- const entry = await readStoredArtifact(directory, runId, id, true, true);
443
- return entry ? { state: 'read', artifact: entry.metadata } : { state: 'missing' };
435
+ const entry = await readStoredTaskFile(kind, directory, runId, id, true, true);
436
+ return entry ? { state: 'read', value: entry.metadata } : { state: 'missing' };
444
437
  }
445
438
  catch (error) {
446
439
  return indexReadFailure(error);
447
440
  }
448
441
  }
449
442
  /** Shares the public list's validated bounded walk and per-entry reader, preserving uncertain IDs. */
450
- export async function scanArtifactsForIndex(directory, runId) {
451
- validateContext(directory, runId);
452
- return inspectArtifactStorageForIndex(directory, async (root) => {
453
- const artifacts = [], indeterminate = [];
443
+ export async function scanTaskFilesForIndex(kind, directory, runId) {
444
+ validateContext(kind, directory, runId);
445
+ return inspectStorageForIndex(directory, async (root) => {
446
+ const records = [], indeterminate = [];
454
447
  let bytes = 0;
455
448
  for await (const id of entries(root.path)) {
456
449
  let entry;
457
450
  try {
458
- entry = await readEntry(root, runId, id, true, true);
451
+ entry = await readEntry(kind, root, runId, id, true, true);
459
452
  }
460
453
  catch (error) {
461
- if (error instanceof ArtifactLimitError)
454
+ if (error instanceof TaskFileLimitError)
462
455
  throw error; // A cap failure invalidates the whole scan.
463
456
  if (indexReadFailure(error).state === 'indeterminate')
464
457
  indeterminate.push(id);
@@ -466,44 +459,46 @@ export async function scanArtifactsForIndex(directory, runId) {
466
459
  }
467
460
  if (!entry)
468
461
  continue;
469
- artifacts.push(entry.metadata);
462
+ records.push(entry.metadata);
470
463
  bytes += entry.metadata.size;
471
- if (artifacts.length > MAX_ARTIFACTS || bytes > MAX_RUN_BYTES)
472
- throw new ArtifactLimitError('Artifact task capacity exceeded');
464
+ if (records.length > kind.limits.maxFiles || bytes > kind.limits.maxRunBytes) {
465
+ throw new TaskFileLimitError(`Task file capacity limit exceeded for kind '${kind.id}' (${kind.limits.maxFiles} files, ${kind.limits.maxRunBytes} bytes)`);
466
+ }
473
467
  }
474
- return { artifacts, indeterminate };
468
+ return { records, indeterminate };
475
469
  });
476
470
  }
477
471
  /** Page checks use the same validated storage components and per-file cap as the reader. */
478
- export async function checkArtifactContentForIndex(directory, runId, id, size) {
479
- validateContext(directory, runId);
472
+ export async function checkTaskFileContentForIndex(kind, directory, runId, id, size) {
473
+ validateContext(kind, directory, runId);
480
474
  z.uuid().parse(id);
481
- return inspectArtifactStorageForIndex(join(directory, id), async (root) => {
475
+ return inspectStorageForIndex(join(directory, id), async (root) => {
482
476
  const file = await lstat(join(root.path, 'content'));
483
477
  if (file.isSymbolicLink())
484
- throw new RedirectedArtifactError('Redirected artifact storage');
485
- if (file.size > MAX_FILE_BYTES)
486
- throw new ArtifactLimitError('Artifact file byte limit exceeded');
478
+ throw new RedirectedTaskFileError('Redirected task file storage');
479
+ if (file.size > kind.limits.maxFileBytes) {
480
+ throw new TaskFileLimitError(`Task file byte limit exceeded for kind '${kind.id}' (${kind.limits.maxFileBytes} bytes)`);
481
+ }
487
482
  return file.isFile() && file.nlink === 1 && file.size === size;
488
483
  });
489
484
  }
490
- export async function listArtifacts(directory, runId) {
485
+ export async function listTaskFiles(kind, directory, runId) {
491
486
  let root;
492
487
  try {
493
- validateContext(directory, runId);
488
+ validateContext(kind, directory, runId);
494
489
  root = await storageDirectory(directory);
495
- const artifacts = [];
490
+ const records = [];
496
491
  let bytes = 0;
497
492
  for await (const id of entries(root.path)) {
498
- const entry = await readEntry(root, runId, id);
493
+ const entry = await readEntry(kind, root, runId, id);
499
494
  if (entry) {
500
495
  bytes += entry.metadata.size;
501
- artifacts.push(entry.metadata);
502
- if (artifacts.length > MAX_ARTIFACTS || bytes > MAX_RUN_BYTES)
496
+ records.push(entry.metadata);
497
+ if (records.length > kind.limits.maxFiles || bytes > kind.limits.maxRunBytes)
503
498
  return [];
504
499
  }
505
500
  }
506
- return artifacts.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
501
+ return records.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
507
502
  }
508
503
  catch {
509
504
  return [];