@jini-ai/daemon 0.5.0 → 0.5.1

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/CHANGELOG.md CHANGED
@@ -1,4 +1,9 @@
1
- ## Unreleased
1
+ ## 0.5.1 — 2026-10-05
2
+
3
+ - The `@jini-ai/db` peer range is `^0.2.0 || ^0.3.0` (daemon uses only db's kernel and store entries, which 0.3.0 leaves unchanged), so a host on db 0.3.0 installs without a peer conflict.
4
+ - Internal `@jini-ai/*` runtime dependencies are caret ranges (`workspace:^`) instead of exact pins.
5
+
6
+ ## Unreleased (shipped in 0.5.0)
2
7
 
3
8
  ### Fixes
4
9
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/daemon",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "The stateful agent daemon runtime: run lifecycle, durable event-log port, the tool-execution boundary, agent executor, terminal sessions, and routines.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -116,10 +116,10 @@
116
116
  "registry": "https://registry.npmjs.org"
117
117
  },
118
118
  "dependencies": {
119
- "@jini-ai/core": "0.4.0",
120
- "@jini-ai/agent-runtime": "0.4.0",
121
- "@jini-ai/protocol": "0.4.0",
122
- "@jini-ai/platform": "0.5.0"
119
+ "@jini-ai/agent-runtime": "^0.4.0",
120
+ "@jini-ai/core": "^0.4.1",
121
+ "@jini-ai/protocol": "^0.4.0",
122
+ "@jini-ai/platform": "^0.5.1"
123
123
  },
124
124
  "devDependencies": {
125
125
  "@vitest/coverage-v8": "^2.1.9",
@@ -132,13 +132,13 @@
132
132
  "@types/pg": "8.23.1",
133
133
  "express": "^4.21.0",
134
134
  "@types/express": "^4.17.21",
135
- "@jini-ai/db": "0.2.0",
135
+ "@jini-ai/chat": "0.5.2",
136
136
  "@jini-ai/http-kit": "0.4.0",
137
- "@jini-ai/chat": "0.5.0"
137
+ "@jini-ai/db": "0.3.0"
138
138
  },
139
139
  "peerDependencies": {
140
140
  "node-pty": "^1.1.0",
141
- "@jini-ai/db": "^0.2.0",
141
+ "@jini-ai/db": "^0.2.0 || ^0.3.0",
142
142
  "kysely": "^0.29.6",
143
143
  "better-sqlite3": "^13.0.0",
144
144
  "@electric-sql/pglite": "0.5.8",
@@ -1,14 +0,0 @@
1
- /**
2
- * @module artifacts
3
- *
4
- * The generic artifact-store kernel port, ported from OD's
5
- * `apps/daemon/src/artifacts/` (6 files). See `source-map.md` for full
6
- * per-file provenance and the design decisions behind each generalization.
7
- */
8
- export * from './manifest.js';
9
- export * from './store.js';
10
- export * from './publication-guard.js';
11
- export * from './runtime-compat.js';
12
- export * from './stub-guard.js';
13
- export * from './text-suppression.js';
14
- //# sourceMappingURL=index.d.ts.map
@@ -1,14 +0,0 @@
1
- /**
2
- * @module artifacts
3
- *
4
- * The generic artifact-store kernel port, ported from OD's
5
- * `apps/daemon/src/artifacts/` (6 files). See `source-map.md` for full
6
- * per-file provenance and the design decisions behind each generalization.
7
- */
8
- export * from './manifest.js';
9
- export * from './store.js';
10
- export * from './publication-guard.js';
11
- export * from './runtime-compat.js';
12
- export * from './stub-guard.js';
13
- export * from './text-suppression.js';
14
- //# sourceMappingURL=index.js.map
@@ -1,90 +0,0 @@
1
- /**
2
- * @module artifacts/manifest
3
- *
4
- * Generic artifact-manifest validation: bounded-length string checks, path-
5
- * traversal rejection on `entry`/`primary`/`supportingFiles`, a JSON-size
6
- * cap on `metadata`, and version/timestamp stamping. Ported from OD's
7
- * `apps/daemon/src/artifacts/manifest.ts`.
8
- *
9
- * De-branded: the origin's `kind`/`renderer` fields were validated against
10
- * hardcoded `ALLOWED_KINDS`/`ALLOWED_RENDERERS` sets that bake in OD's own
11
- * artifact taxonomy — including a literal `'design-system'` kind, OD's own
12
- * product concept, not a generic engine noun. Both sets are now a
13
- * caller-supplied {@link ArtifactManifestTaxonomy} instead of module
14
- * constants — a host (like an OD adapter) supplies its own kind/renderer/
15
- * export vocabulary; the validation *mechanism* (bounded strings, traversal
16
- * rejection, size caps, version stamping) is what this module owns. `status`
17
- * (`'streaming' | 'complete' | 'error'`) is kept as a fixed literal union —
18
- * that's a generic artifact-lifecycle concept, not a product taxonomy.
19
- */
20
- export type ArtifactStatus = 'streaming' | 'complete' | 'error';
21
- /**
22
- * A host's own artifact-kind/renderer/export vocabulary. The engine treats
23
- * every value as an opaque string it only bounds-checks and validates
24
- * membership against — it assigns no meaning to any particular kind name.
25
- */
26
- export interface ArtifactManifestTaxonomy {
27
- readonly allowedKinds: ReadonlySet<string>;
28
- readonly allowedRenderers: ReadonlySet<string>;
29
- readonly allowedExports: ReadonlySet<string>;
30
- }
31
- /** A taxonomy that accepts nothing — forces a host to supply its own before any manifest can validate. */
32
- export declare const emptyArtifactManifestTaxonomy: ArtifactManifestTaxonomy;
33
- export interface ArtifactManifest {
34
- readonly version: number;
35
- readonly kind: string;
36
- readonly title: string;
37
- readonly entry: string;
38
- readonly renderer: string;
39
- readonly status: ArtifactStatus;
40
- readonly exports: readonly string[];
41
- readonly primary?: string | true;
42
- readonly supportingFiles?: readonly string[];
43
- readonly createdAt: string;
44
- readonly updatedAt: string;
45
- /** Generic "what produced or relates to this artifact" reference (OD: a skill id). Opaque to the engine. */
46
- readonly sourceContextId?: string;
47
- readonly metadata?: Readonly<Record<string, unknown>>;
48
- }
49
- type JsonRecord = Record<string, unknown>;
50
- type ValidationResult = {
51
- ok: true;
52
- value: ArtifactManifest | null;
53
- } | {
54
- ok: false;
55
- error: string;
56
- };
57
- export interface ValidateManifestOptions {
58
- /** Keep an existing `updatedAt` instead of stamping the current time (used when re-parsing a persisted manifest). */
59
- preserveUpdatedAt?: boolean;
60
- }
61
- /**
62
- * Validates a freeform manifest payload against `taxonomy`, returning a
63
- * sanitized, stamped {@link ArtifactManifest} on success. `manifest == null`
64
- * is a valid "no manifest supplied" outcome (`{ ok: true, value: null }`) —
65
- * callers that require a manifest check for `value === null` themselves
66
- * (see `store.ts`'s `resolveArtifactManifest`).
67
- */
68
- export declare function validateArtifactManifestInput(manifest: unknown, entry: unknown, taxonomy: ArtifactManifestTaxonomy, options?: ValidateManifestOptions): ValidationResult;
69
- /** Normalizes a validated manifest payload into the stamped, canonical {@link ArtifactManifest} shape. */
70
- export declare function sanitizeManifest(manifest: JsonRecord, entry: string, options?: ValidateManifestOptions): ArtifactManifest;
71
- /**
72
- * Re-validates a manifest read back from persistence (e.g. a sidecar file),
73
- * preserving its original `updatedAt`. Returns `null` on any validation
74
- * failure or version mismatch/parse error rather than throwing — a corrupt
75
- * or stale sidecar should degrade to "no manifest", not crash the reader.
76
- */
77
- export declare function parsePersistedManifest(raw: string, fallbackEntry: string, taxonomy: ArtifactManifestTaxonomy): ArtifactManifest | null;
78
- /**
79
- * Injectable seam for a host's own "what kind of artifact is this path"
80
- * heuristic (OD: extension-based HTML/deck/markdown/svg inference). The
81
- * engine has no default beyond "infer nothing" — see
82
- * {@link noopManifestInferrer} — a host wires in its own file-kind
83
- * classification (per the task brief: "keep OD's file-kind classification
84
- * as adapter").
85
- */
86
- export type ManifestInferrer = (entry: string) => Partial<ArtifactManifest> | null;
87
- /** Infers nothing — every create call must supply an explicit manifest. */
88
- export declare const noopManifestInferrer: ManifestInferrer;
89
- export {};
90
- //# sourceMappingURL=manifest.d.ts.map
@@ -1,229 +0,0 @@
1
- /**
2
- * @module artifacts/manifest
3
- *
4
- * Generic artifact-manifest validation: bounded-length string checks, path-
5
- * traversal rejection on `entry`/`primary`/`supportingFiles`, a JSON-size
6
- * cap on `metadata`, and version/timestamp stamping. Ported from OD's
7
- * `apps/daemon/src/artifacts/manifest.ts`.
8
- *
9
- * De-branded: the origin's `kind`/`renderer` fields were validated against
10
- * hardcoded `ALLOWED_KINDS`/`ALLOWED_RENDERERS` sets that bake in OD's own
11
- * artifact taxonomy — including a literal `'design-system'` kind, OD's own
12
- * product concept, not a generic engine noun. Both sets are now a
13
- * caller-supplied {@link ArtifactManifestTaxonomy} instead of module
14
- * constants — a host (like an OD adapter) supplies its own kind/renderer/
15
- * export vocabulary; the validation *mechanism* (bounded strings, traversal
16
- * rejection, size caps, version stamping) is what this module owns. `status`
17
- * (`'streaming' | 'complete' | 'error'`) is kept as a fixed literal union —
18
- * that's a generic artifact-lifecycle concept, not a product taxonomy.
19
- */
20
- const MANIFEST_VERSION = 1;
21
- const MAX_TITLE_LENGTH = 200;
22
- const MAX_SOURCE_CONTEXT_ID_LENGTH = 128;
23
- const MAX_SUPPORTING_FILE_LENGTH = 260;
24
- const MAX_SUPPORTING_FILES = 128;
25
- const MAX_METADATA_BYTES = 16 * 1024;
26
- const ALLOWED_STATUS = new Set(['streaming', 'complete', 'error']);
27
- /** A taxonomy that accepts nothing — forces a host to supply its own before any manifest can validate. */
28
- export const emptyArtifactManifestTaxonomy = {
29
- allowedKinds: new Set(),
30
- allowedRenderers: new Set(),
31
- allowedExports: new Set(),
32
- };
33
- function isPlainObject(value) {
34
- if (!value || typeof value !== 'object' || Array.isArray(value))
35
- return false;
36
- const proto = Object.getPrototypeOf(value);
37
- return proto === Object.prototype || proto === null;
38
- }
39
- function validateBoundedString(value, field, maxLen, { allowEmpty = false } = {}) {
40
- if (typeof value !== 'string')
41
- return `${field} must be a string`;
42
- if (!allowEmpty && value.length === 0)
43
- return `${field} is required`;
44
- if (value.length > maxLen)
45
- return `${field} exceeds max length (${maxLen})`;
46
- return null;
47
- }
48
- function validateSupportingPath(value) {
49
- if (typeof value !== 'string')
50
- return 'supportingFiles entries must be strings';
51
- if (value.length === 0)
52
- return 'supportingFiles entries cannot be empty';
53
- if (value.length > MAX_SUPPORTING_FILE_LENGTH) {
54
- return `supportingFiles entries exceed max length (${MAX_SUPPORTING_FILE_LENGTH})`;
55
- }
56
- if (/^[A-Za-z]:/.test(value) || value.startsWith('/')) {
57
- return 'supportingFiles cannot contain absolute paths';
58
- }
59
- if (value.includes('\u0000'))
60
- return 'supportingFiles cannot contain null bytes';
61
- const normalized = value.replace(/\\/g, '/');
62
- if (normalized.includes('..'))
63
- return 'supportingFiles cannot contain traversal segments';
64
- const parts = normalized.split('/').filter(Boolean);
65
- if (parts.length === 0 || parts.some((p) => p === '.' || p === '..')) {
66
- return 'supportingFiles cannot contain traversal segments';
67
- }
68
- return null;
69
- }
70
- /**
71
- * Validates a freeform manifest payload against `taxonomy`, returning a
72
- * sanitized, stamped {@link ArtifactManifest} on success. `manifest == null`
73
- * is a valid "no manifest supplied" outcome (`{ ok: true, value: null }`) —
74
- * callers that require a manifest check for `value === null` themselves
75
- * (see `store.ts`'s `resolveArtifactManifest`).
76
- */
77
- export function validateArtifactManifestInput(manifest, entry, taxonomy, options = {}) {
78
- if (manifest == null)
79
- return { ok: true, value: null };
80
- if (!isPlainObject(manifest)) {
81
- return { ok: false, error: 'artifactManifest must be an object' };
82
- }
83
- const kindErr = validateBoundedString(manifest.kind, 'artifactManifest.kind', 64);
84
- if (kindErr)
85
- return { ok: false, error: kindErr };
86
- // Cast, not a runtime guard: validateBoundedString's first check is
87
- // `typeof value !== 'string'`, which already returned above for any
88
- // non-string `kind` — this only narrows the type for `taxonomy.allowedKinds.has`.
89
- if (!taxonomy.allowedKinds.has(manifest.kind)) {
90
- return { ok: false, error: 'artifactManifest.kind is not allowed' };
91
- }
92
- const rendererErr = validateBoundedString(manifest.renderer, 'artifactManifest.renderer', 64);
93
- if (rendererErr)
94
- return { ok: false, error: rendererErr };
95
- // Same reasoning as `kind` above.
96
- if (!taxonomy.allowedRenderers.has(manifest.renderer)) {
97
- return { ok: false, error: 'artifactManifest.renderer is not allowed' };
98
- }
99
- if (!Array.isArray(manifest.exports) || manifest.exports.length === 0) {
100
- return { ok: false, error: 'artifactManifest.exports must be a non-empty array' };
101
- }
102
- for (const exp of manifest.exports) {
103
- if (typeof exp !== 'string') {
104
- return { ok: false, error: 'artifactManifest.exports must contain strings' };
105
- }
106
- if (!taxonomy.allowedExports.has(exp)) {
107
- return { ok: false, error: `artifactManifest.exports contains unsupported value: ${exp}` };
108
- }
109
- }
110
- if (manifest.status !== undefined) {
111
- if (typeof manifest.status !== 'string') {
112
- return { ok: false, error: 'artifactManifest.status must be a string' };
113
- }
114
- if (!ALLOWED_STATUS.has(manifest.status)) {
115
- return { ok: false, error: 'artifactManifest.status is not allowed' };
116
- }
117
- }
118
- if (manifest.primary !== undefined) {
119
- if (manifest.primary !== true) {
120
- const primaryErr = validateSupportingPath(manifest.primary);
121
- if (primaryErr)
122
- return { ok: false, error: `artifactManifest.primary ${primaryErr}` };
123
- }
124
- }
125
- if (manifest.supportingFiles !== undefined) {
126
- if (!Array.isArray(manifest.supportingFiles)) {
127
- return { ok: false, error: 'artifactManifest.supportingFiles must be an array' };
128
- }
129
- if (manifest.supportingFiles.length > MAX_SUPPORTING_FILES) {
130
- return {
131
- ok: false,
132
- error: `artifactManifest.supportingFiles exceeds max items (${MAX_SUPPORTING_FILES})`,
133
- };
134
- }
135
- for (const rel of manifest.supportingFiles) {
136
- const relErr = validateSupportingPath(rel);
137
- if (relErr)
138
- return { ok: false, error: relErr };
139
- }
140
- }
141
- if (manifest.title !== undefined) {
142
- const titleErr = validateBoundedString(manifest.title, 'artifactManifest.title', MAX_TITLE_LENGTH, {
143
- allowEmpty: false,
144
- });
145
- if (titleErr)
146
- return { ok: false, error: titleErr };
147
- }
148
- if (manifest.sourceContextId !== undefined) {
149
- const sourceErr = validateBoundedString(manifest.sourceContextId, 'artifactManifest.sourceContextId', MAX_SOURCE_CONTEXT_ID_LENGTH, { allowEmpty: true });
150
- if (sourceErr)
151
- return { ok: false, error: sourceErr };
152
- }
153
- if (manifest.metadata !== undefined) {
154
- if (!isPlainObject(manifest.metadata)) {
155
- return { ok: false, error: 'artifactManifest.metadata must be a plain object' };
156
- }
157
- // JSON.stringify always returns a string (never undefined) when called
158
- // directly on a plain object — undefined-return only happens when the
159
- // top-level argument itself is a function/symbol/undefined, which
160
- // isPlainObject above already rejected.
161
- const serialized = JSON.stringify(manifest.metadata);
162
- if (Buffer.byteLength(serialized, 'utf8') > MAX_METADATA_BYTES) {
163
- return {
164
- ok: false,
165
- error: `artifactManifest.metadata exceeds max size (${MAX_METADATA_BYTES} bytes)`,
166
- };
167
- }
168
- }
169
- const manifestEntry = typeof manifest.entry === 'string' && manifest.entry.trim() ? manifest.entry.trim() : entry;
170
- const entryErr = validateSupportingPath(manifestEntry);
171
- if (entryErr) {
172
- return { ok: false, error: `artifactManifest.entry ${entryErr}` };
173
- }
174
- const safeEntry = manifestEntry.replace(/\\/g, '/');
175
- return { ok: true, value: sanitizeManifest(manifest, safeEntry, options) };
176
- }
177
- /** Normalizes a validated manifest payload into the stamped, canonical {@link ArtifactManifest} shape. */
178
- export function sanitizeManifest(manifest, entry, options = {}) {
179
- const now = new Date().toISOString();
180
- const supportingFiles = Array.isArray(manifest.supportingFiles)
181
- ? manifest.supportingFiles.map((x) => String(x).replace(/\\/g, '/'))
182
- : undefined;
183
- const primary = manifest.primary === true
184
- ? true
185
- : typeof manifest.primary === 'string'
186
- ? manifest.primary.replace(/\\/g, '/')
187
- : undefined;
188
- return {
189
- version: MANIFEST_VERSION,
190
- kind: manifest.kind,
191
- title: manifest.title || entry,
192
- entry,
193
- renderer: manifest.renderer,
194
- status: typeof manifest.status === 'string' && ALLOWED_STATUS.has(manifest.status)
195
- ? manifest.status
196
- : 'complete',
197
- exports: manifest.exports,
198
- ...(primary !== undefined ? { primary } : {}),
199
- ...(supportingFiles !== undefined ? { supportingFiles } : {}),
200
- createdAt: typeof manifest.createdAt === 'string' ? manifest.createdAt : now,
201
- updatedAt: options.preserveUpdatedAt && typeof manifest.updatedAt === 'string'
202
- ? manifest.updatedAt
203
- : now,
204
- ...(manifest.sourceContextId !== undefined ? { sourceContextId: manifest.sourceContextId } : {}),
205
- ...(manifest.metadata !== undefined ? { metadata: manifest.metadata } : {}),
206
- };
207
- }
208
- /**
209
- * Re-validates a manifest read back from persistence (e.g. a sidecar file),
210
- * preserving its original `updatedAt`. Returns `null` on any validation
211
- * failure or version mismatch/parse error rather than throwing — a corrupt
212
- * or stale sidecar should degrade to "no manifest", not crash the reader.
213
- */
214
- export function parsePersistedManifest(raw, fallbackEntry, taxonomy) {
215
- try {
216
- const parsed = JSON.parse(raw);
217
- if (!isPlainObject(parsed) || parsed.version !== MANIFEST_VERSION)
218
- return null;
219
- const entry = typeof parsed.entry === 'string' && parsed.entry ? parsed.entry : fallbackEntry;
220
- const result = validateArtifactManifestInput(parsed, entry, taxonomy, { preserveUpdatedAt: true });
221
- return result.ok ? result.value : null;
222
- }
223
- catch {
224
- return null;
225
- }
226
- }
227
- /** Infers nothing — every create call must supply an explicit manifest. */
228
- export const noopManifestInferrer = () => null;
229
- //# sourceMappingURL=manifest.js.map
@@ -1,28 +0,0 @@
1
- export declare const ARTIFACT_PUBLICATION_BLOCKED_CODE: "ARTIFACT_PUBLICATION_BLOCKED";
2
- export interface PublicationGuardConfig {
3
- /** Artifact kinds this guard scans. A kind not in this set is never blocked, whatever its content. */
4
- readonly guardedKinds: ReadonlySet<string>;
5
- /** Substrings that mark an artifact as containing an unresolved placeholder. Matching is case-sensitive. */
6
- readonly blockedPlaceholders: readonly string[];
7
- }
8
- /** A guard that blocks nothing — no guarded kinds, no placeholder markers configured. */
9
- export declare const emptyPublicationGuardConfig: PublicationGuardConfig;
10
- export declare class ArtifactPublicationBlockedError extends Error {
11
- readonly code: "ARTIFACT_PUBLICATION_BLOCKED";
12
- readonly placeholders: readonly string[];
13
- constructor(placeholders: readonly string[]);
14
- }
15
- export declare function isPublicationGuardedKind(kind: unknown, config: PublicationGuardConfig): boolean;
16
- /** Returns every configured placeholder marker found in `value`'s stringified content, in declaration order. */
17
- export declare function findBlockedPlaceholders(value: unknown, config: PublicationGuardConfig): string[];
18
- export declare function shouldBlockPublication(value: unknown, config: PublicationGuardConfig): boolean;
19
- export declare function buildArtifactPublicationBlockedMessage(placeholders: readonly string[]): string;
20
- /**
21
- * Throws {@link ArtifactPublicationBlockedError} when `value` (for a
22
- * `kind` in `config.guardedKinds`) contains any of `config.blockedPlaceholders`.
23
- * No-ops for a kind outside `config.guardedKinds` — a guard scoped to
24
- * user-facing rendered documents shouldn't reject content in other kinds
25
- * where the same substrings could be legitimate.
26
- */
27
- export declare function assertArtifactPublicationAllowed(kind: unknown, value: unknown, config: PublicationGuardConfig): void;
28
- //# sourceMappingURL=publication-guard.d.ts.map
@@ -1,77 +0,0 @@
1
- /**
2
- * @module artifacts/publication-guard
3
- *
4
- * A pre-publish content guard: blocks an artifact write when its body
5
- * contains a caller-declared "unresolved placeholder" marker, scoped to a
6
- * caller-declared set of guarded kinds. Ported from OD's
7
- * `apps/daemon/src/artifacts/publication-guard.ts`.
8
- *
9
- * De-branded: the origin hardcoded `UNRESOLVED_ARTIFACT_PLACEHOLDERS` — five
10
- * literal strings ("Name to confirm", "$X.XM", ...) lifted from one specific
11
- * bundled example template's pitch-deck fill-in-the-blank convention — and
12
- * `PUBLICATION_GUARDED_ARTIFACT_KINDS = {'html', 'deck'}`. Both are entirely
13
- * OD's own content, not a generic engine mechanism, so this module now takes
14
- * a caller-supplied {@link PublicationGuardConfig} (empty by default — a
15
- * guard that never blocks anything until a host configures it) instead of
16
- * baking in that one template's marker strings. The guard *mechanism*
17
- * (scan a guarded-kind body for any configured marker, throw before
18
- * publish) is what this module owns.
19
- */
20
- import { Buffer } from 'node:buffer';
21
- export const ARTIFACT_PUBLICATION_BLOCKED_CODE = 'ARTIFACT_PUBLICATION_BLOCKED';
22
- /** A guard that blocks nothing — no guarded kinds, no placeholder markers configured. */
23
- export const emptyPublicationGuardConfig = {
24
- guardedKinds: new Set(),
25
- blockedPlaceholders: [],
26
- };
27
- export class ArtifactPublicationBlockedError extends Error {
28
- code = ARTIFACT_PUBLICATION_BLOCKED_CODE;
29
- placeholders;
30
- constructor(placeholders) {
31
- super(buildArtifactPublicationBlockedMessage(placeholders));
32
- this.name = 'ArtifactPublicationBlockedError';
33
- this.placeholders = [...placeholders];
34
- }
35
- }
36
- export function isPublicationGuardedKind(kind, config) {
37
- return typeof kind === 'string' && config.guardedKinds.has(kind);
38
- }
39
- function stringifyArtifactContent(value) {
40
- if (typeof value === 'string')
41
- return value;
42
- if (Buffer.isBuffer(value))
43
- return value.toString('utf8');
44
- if (value instanceof Uint8Array)
45
- return Buffer.from(value).toString('utf8');
46
- return '';
47
- }
48
- /** Returns every configured placeholder marker found in `value`'s stringified content, in declaration order. */
49
- export function findBlockedPlaceholders(value, config) {
50
- const text = stringifyArtifactContent(value);
51
- if (!text)
52
- return [];
53
- return config.blockedPlaceholders.filter((placeholder) => text.includes(placeholder));
54
- }
55
- export function shouldBlockPublication(value, config) {
56
- return findBlockedPlaceholders(value, config).length > 0;
57
- }
58
- export function buildArtifactPublicationBlockedMessage(placeholders) {
59
- const list = placeholders.length > 0 ? placeholders.join(', ') : 'unknown placeholders';
60
- return `Artifact still contains unresolved placeholders: ${list}. Resolve them before publishing.`;
61
- }
62
- /**
63
- * Throws {@link ArtifactPublicationBlockedError} when `value` (for a
64
- * `kind` in `config.guardedKinds`) contains any of `config.blockedPlaceholders`.
65
- * No-ops for a kind outside `config.guardedKinds` — a guard scoped to
66
- * user-facing rendered documents shouldn't reject content in other kinds
67
- * where the same substrings could be legitimate.
68
- */
69
- export function assertArtifactPublicationAllowed(kind, value, config) {
70
- if (!isPublicationGuardedKind(kind, config))
71
- return;
72
- const placeholders = findBlockedPlaceholders(value, config);
73
- if (placeholders.length > 0) {
74
- throw new ArtifactPublicationBlockedError(placeholders);
75
- }
76
- }
77
- //# sourceMappingURL=publication-guard.js.map
@@ -1,37 +0,0 @@
1
- /**
2
- * @module artifacts/runtime-compat
3
- *
4
- * The runtime-compat injection seam: a hook that gets a chance to rewrite an
5
- * artifact's body before it's served, for CDN/library-loading quirks a host
6
- * knows about but the engine can't. Ported from OD's
7
- * `apps/daemon/src/artifacts/runtime-compat.ts`.
8
- *
9
- * De-branded: the origin, `normalizeArtifactRuntimeImports`, is entirely a
10
- * fix for one specific third-party CDN-bundle bug (the vanilla `dist/
11
- * motion.js` UMD script tag lacking React hooks, rewritten to `dist/
12
- * framer-motion.js`) that OD's own system prompt steers models toward
13
- * hitting. That rewrite rule is product/library-specific knowledge, not a
14
- * generic engine mechanism — per the task brief ("keep OD's specific logic
15
- * as adapter"), it is not ported. What *is* generic and kept is the
16
- * seam itself: a host may need to rewrite an artifact body for any number
17
- * of environment-specific reasons (a different CDN quirk, a different
18
- * runtime library entirely) before it reaches a renderer, so the engine
19
- * defines the hook type and a safe default (identity) rather than hardcode
20
- * any one library's fix.
21
- */
22
- /**
23
- * Rewrites an artifact body before it is served, keyed by the artifact's
24
- * file name (a host typically gates on file extension, as OD's origin did
25
- * with `.html`/`.htm`). Returns the body unchanged when no rewrite applies.
26
- */
27
- export type RuntimeCompatNormalizer = (name: string, body: unknown) => unknown;
28
- /** Applies no rewrite — returns `body` unchanged. Safe default until a host supplies its own normalizer(s). */
29
- export declare const noopRuntimeCompatNormalizer: RuntimeCompatNormalizer;
30
- /**
31
- * Composes several normalizers into one, applying each in order — the
32
- * output of one becomes the input to the next. Lets a host layer multiple
33
- * independent CDN/library fixes without each needing to know about the
34
- * others.
35
- */
36
- export declare function composeRuntimeCompatNormalizers(normalizers: readonly RuntimeCompatNormalizer[]): RuntimeCompatNormalizer;
37
- //# sourceMappingURL=runtime-compat.d.ts.map
@@ -1,33 +0,0 @@
1
- /**
2
- * @module artifacts/runtime-compat
3
- *
4
- * The runtime-compat injection seam: a hook that gets a chance to rewrite an
5
- * artifact's body before it's served, for CDN/library-loading quirks a host
6
- * knows about but the engine can't. Ported from OD's
7
- * `apps/daemon/src/artifacts/runtime-compat.ts`.
8
- *
9
- * De-branded: the origin, `normalizeArtifactRuntimeImports`, is entirely a
10
- * fix for one specific third-party CDN-bundle bug (the vanilla `dist/
11
- * motion.js` UMD script tag lacking React hooks, rewritten to `dist/
12
- * framer-motion.js`) that OD's own system prompt steers models toward
13
- * hitting. That rewrite rule is product/library-specific knowledge, not a
14
- * generic engine mechanism — per the task brief ("keep OD's specific logic
15
- * as adapter"), it is not ported. What *is* generic and kept is the
16
- * seam itself: a host may need to rewrite an artifact body for any number
17
- * of environment-specific reasons (a different CDN quirk, a different
18
- * runtime library entirely) before it reaches a renderer, so the engine
19
- * defines the hook type and a safe default (identity) rather than hardcode
20
- * any one library's fix.
21
- */
22
- /** Applies no rewrite — returns `body` unchanged. Safe default until a host supplies its own normalizer(s). */
23
- export const noopRuntimeCompatNormalizer = (_name, body) => body;
24
- /**
25
- * Composes several normalizers into one, applying each in order — the
26
- * output of one becomes the input to the next. Lets a host layer multiple
27
- * independent CDN/library fixes without each needing to know about the
28
- * others.
29
- */
30
- export function composeRuntimeCompatNormalizers(normalizers) {
31
- return (name, body) => normalizers.reduce((current, normalize) => normalize(name, current), body);
32
- }
33
- //# sourceMappingURL=runtime-compat.js.map
@@ -1,85 +0,0 @@
1
- /**
2
- * @module artifacts/store
3
- *
4
- * `ArtifactStore` — the generic artifact-store kernel port. Ported from OD's
5
- * `apps/daemon/src/artifacts/create.ts` create/manifest-resolution flow;
6
- * "artifacts feel like a kernel-adjacent concept tied to runs producing
7
- * output" per this task's brief — homed in `@jini/daemon` alongside
8
- * `EventLog` (same async-port + in-memory-reference-implementation shape as
9
- * `event-log.ts`), not `@jini/core` (which owns pure registries/DI, not
10
- * stateful storage).
11
- *
12
- * De-branded: the origin's `createProjectArtifactFile` took OD's own
13
- * product-shaped workspace/file-tree writer (a function keyed on OD's own
14
- * workspace-root and workspace-id nouns) as its injected dependency, and a
15
- * companion `postCreateArtifactRequest` built a request body for OD's own
16
- * per-workspace HTTP file-upload route. Neither is a generic engine concern
17
- * (a workspace model and an HTTP route shape are product surfaces), so this
18
- * port defines `ArtifactStore.create/get/list` directly against an
19
- * in-memory reference map — the origin's writer/request-builder pair were
20
- * the composition points a real OD adapter would wire against this port
21
- * from, not something to port verbatim. OD's HTML-prototype file-kind
22
- * inference (`inferLegacyManifest`) stays adapter-owned — see
23
- * `manifest.ts`'s `ManifestInferrer` seam.
24
- */
25
- import { type ArtifactManifest, type ArtifactManifestTaxonomy, type ManifestInferrer } from './manifest.js';
26
- export declare class ArtifactManifestRequiredError extends Error {
27
- readonly code: "ARTIFACT_MANIFEST_REQUIRED";
28
- constructor(name: string);
29
- }
30
- export declare class ArtifactManifestInvalidError extends Error {
31
- readonly code: "ARTIFACT_MANIFEST_INVALID";
32
- constructor(message: string);
33
- }
34
- export interface CreateArtifactInput {
35
- readonly name: string;
36
- readonly content: string;
37
- readonly encoding?: 'utf8' | 'base64';
38
- /** Explicit manifest fields, or `undefined` to fall back to the store's {@link ManifestInferrer}. */
39
- readonly artifactManifest?: unknown;
40
- }
41
- export interface ArtifactRecord {
42
- readonly name: string;
43
- readonly content: Buffer;
44
- readonly manifest: ArtifactManifest;
45
- }
46
- /**
47
- * A replayable, ordered artifact-manifest resolver: given a create request,
48
- * either the caller-supplied manifest (validated against `taxonomy`) or the
49
- * result of `inferManifest(name)` (also validated) becomes the record's
50
- * manifest. Throws {@link ArtifactManifestRequiredError} when neither
51
- * source produces one, {@link ArtifactManifestInvalidError} when the
52
- * resolved manifest fails validation.
53
- */
54
- export declare function resolveArtifactManifest(input: CreateArtifactInput, taxonomy: ArtifactManifestTaxonomy, inferManifest: ManifestInferrer): ArtifactManifest;
55
- /**
56
- * A store of named artifacts with validated manifests. Kernel port —
57
- * `@jini/daemon` ships `createInMemoryArtifactStore` as the reference
58
- * implementation; a durable adapter (`@jini/sqlite`) can implement the same
59
- * interface against real persistence.
60
- */
61
- export interface ArtifactStore {
62
- /**
63
- * Creates or overwrites the artifact named `input.name`, resolving its
64
- * manifest per {@link resolveArtifactManifest}.
65
- * @throws {ArtifactManifestRequiredError} No manifest supplied and the inferrer produced none.
66
- * @throws {ArtifactManifestInvalidError} The resolved manifest failed taxonomy validation.
67
- */
68
- create(input: CreateArtifactInput): Promise<ArtifactRecord>;
69
- /** Returns the named artifact, or `null` if it doesn't exist. */
70
- get(name: string): Promise<ArtifactRecord | null>;
71
- /** Returns every stored artifact, most-recently-updated first. */
72
- list(): Promise<ArtifactRecord[]>;
73
- }
74
- export interface InMemoryArtifactStoreOptions {
75
- readonly taxonomy?: ArtifactManifestTaxonomy;
76
- readonly inferManifest?: ManifestInferrer;
77
- }
78
- /**
79
- * Reference `ArtifactStore` implementation: an in-memory `Map` keyed by
80
- * artifact name. No durable persistence — matching this task's scope (a
81
- * real persistent adapter is a future storage task's concern, mirroring
82
- * `event-log.ts`'s own in-memory-only reference implementation).
83
- */
84
- export declare function createInMemoryArtifactStore(options?: InMemoryArtifactStoreOptions): ArtifactStore;
85
- //# sourceMappingURL=store.d.ts.map
@@ -1,92 +0,0 @@
1
- /**
2
- * @module artifacts/store
3
- *
4
- * `ArtifactStore` — the generic artifact-store kernel port. Ported from OD's
5
- * `apps/daemon/src/artifacts/create.ts` create/manifest-resolution flow;
6
- * "artifacts feel like a kernel-adjacent concept tied to runs producing
7
- * output" per this task's brief — homed in `@jini/daemon` alongside
8
- * `EventLog` (same async-port + in-memory-reference-implementation shape as
9
- * `event-log.ts`), not `@jini/core` (which owns pure registries/DI, not
10
- * stateful storage).
11
- *
12
- * De-branded: the origin's `createProjectArtifactFile` took OD's own
13
- * product-shaped workspace/file-tree writer (a function keyed on OD's own
14
- * workspace-root and workspace-id nouns) as its injected dependency, and a
15
- * companion `postCreateArtifactRequest` built a request body for OD's own
16
- * per-workspace HTTP file-upload route. Neither is a generic engine concern
17
- * (a workspace model and an HTTP route shape are product surfaces), so this
18
- * port defines `ArtifactStore.create/get/list` directly against an
19
- * in-memory reference map — the origin's writer/request-builder pair were
20
- * the composition points a real OD adapter would wire against this port
21
- * from, not something to port verbatim. OD's HTML-prototype file-kind
22
- * inference (`inferLegacyManifest`) stays adapter-owned — see
23
- * `manifest.ts`'s `ManifestInferrer` seam.
24
- */
25
- import { emptyArtifactManifestTaxonomy, noopManifestInferrer, validateArtifactManifestInput, } from './manifest.js';
26
- export class ArtifactManifestRequiredError extends Error {
27
- code = 'ARTIFACT_MANIFEST_REQUIRED';
28
- constructor(name) {
29
- super(`artifactManifest is required for ${name}; no safe default manifest can be inferred`);
30
- this.name = 'ArtifactManifestRequiredError';
31
- }
32
- }
33
- export class ArtifactManifestInvalidError extends Error {
34
- code = 'ARTIFACT_MANIFEST_INVALID';
35
- constructor(message) {
36
- super(`invalid artifactManifest: ${message}`);
37
- this.name = 'ArtifactManifestInvalidError';
38
- }
39
- }
40
- /**
41
- * A replayable, ordered artifact-manifest resolver: given a create request,
42
- * either the caller-supplied manifest (validated against `taxonomy`) or the
43
- * result of `inferManifest(name)` (also validated) becomes the record's
44
- * manifest. Throws {@link ArtifactManifestRequiredError} when neither
45
- * source produces one, {@link ArtifactManifestInvalidError} when the
46
- * resolved manifest fails validation.
47
- */
48
- export function resolveArtifactManifest(input, taxonomy, inferManifest) {
49
- const manifest = input.artifactManifest !== undefined && input.artifactManifest !== null
50
- ? input.artifactManifest
51
- : inferManifest(input.name);
52
- if (manifest) {
53
- const validated = validateArtifactManifestInput(manifest, input.name, taxonomy);
54
- if (!validated.ok) {
55
- throw new ArtifactManifestInvalidError(validated.error);
56
- }
57
- // `manifest != null` above and `validateArtifactManifestInput` only
58
- // returns `{ ok: true, value: null }` when its own `manifest` param is
59
- // `== null` — so `validated.value` is non-null here.
60
- return validated.value;
61
- }
62
- throw new ArtifactManifestRequiredError(input.name);
63
- }
64
- /**
65
- * Reference `ArtifactStore` implementation: an in-memory `Map` keyed by
66
- * artifact name. No durable persistence — matching this task's scope (a
67
- * real persistent adapter is a future storage task's concern, mirroring
68
- * `event-log.ts`'s own in-memory-only reference implementation).
69
- */
70
- export function createInMemoryArtifactStore(options = {}) {
71
- const taxonomy = options.taxonomy ?? emptyArtifactManifestTaxonomy;
72
- const inferManifest = options.inferManifest ?? noopManifestInferrer;
73
- const records = new Map();
74
- return {
75
- async create(input) {
76
- const manifest = resolveArtifactManifest(input, taxonomy, inferManifest);
77
- const content = input.encoding === 'base64'
78
- ? Buffer.from(input.content, 'base64')
79
- : Buffer.from(input.content, 'utf8');
80
- const record = { name: input.name, content, manifest };
81
- records.set(input.name, record);
82
- return record;
83
- },
84
- async get(name) {
85
- return records.get(name) ?? null;
86
- },
87
- async list() {
88
- return Array.from(records.values()).sort((a, b) => b.manifest.updatedAt.localeCompare(a.manifest.updatedAt));
89
- },
90
- };
91
- }
92
- //# sourceMappingURL=store.js.map
@@ -1,73 +0,0 @@
1
- export type ArtifactStubGuardMode = 'reject' | 'warn' | 'off';
2
- export interface ArtifactStubGuardConfig {
3
- readonly mode: ArtifactStubGuardMode;
4
- readonly minRetainedRatio: number;
5
- readonly minPriorBytes: number;
6
- /** File-name extensions (including the leading dot) this guard scans for prior siblings, e.g. `['.html', '.htm']`. */
7
- readonly siblingExtensions: readonly string[];
8
- }
9
- export interface PriorArtifactSibling {
10
- readonly name: string;
11
- readonly size: number;
12
- }
13
- export interface ArtifactStubGuardWarning {
14
- readonly code: 'ARTIFACT_REGRESSION';
15
- readonly message: string;
16
- readonly identifier: string;
17
- readonly newSize: number;
18
- readonly priorSize: number;
19
- readonly priorName: string;
20
- }
21
- export interface EvaluateArtifactStubGuardInput {
22
- readonly scanDir: string;
23
- readonly identifier: string;
24
- readonly newSize: number;
25
- readonly config: ArtifactStubGuardConfig;
26
- }
27
- export interface EvaluateArtifactStubGuardResult {
28
- readonly outcome: 'pass' | 'warn' | 'reject';
29
- readonly warning?: ArtifactStubGuardWarning;
30
- }
31
- export declare class ArtifactRegressionError extends Error {
32
- readonly code = "ARTIFACT_REGRESSION";
33
- readonly identifier: string;
34
- readonly newSize: number;
35
- readonly priorSize: number;
36
- readonly priorName: string;
37
- constructor(message: string, details: {
38
- identifier: string;
39
- newSize: number;
40
- priorSize: number;
41
- priorName: string;
42
- });
43
- }
44
- export declare const DEFAULT_ARTIFACT_STUB_GUARD_CONFIG: ArtifactStubGuardConfig;
45
- /** Slugifies a free-form identifier into a filename-safe basename (lowercase, `[a-z0-9_-]`, max 60 chars). */
46
- export declare function slugifyArtifactIdentifier(value: string): string;
47
- /** Fallback basename used when a slugified identifier is empty (e.g. an all-non-ASCII identifier strips to nothing). */
48
- export declare const EMPTY_SLUG_FALLBACK_NAME = "artifact";
49
- /**
50
- * Two identifiers refer to the same artifact lineage when they're literally
51
- * equal, or one is the canonical slug form of the other (and that slug is
52
- * non-empty). Slug equality alone is not enough: a slugifier that truncates
53
- * at a fixed length would otherwise falsely bridge two distinct identifiers
54
- * that only diverge past that length — requiring one side to *be* the slug
55
- * form of the other avoids that while still bridging e.g. "Landing Page" and
56
- * "landing-page".
57
- */
58
- export declare function artifactIdentifiersMatch(a: string, b: string): boolean;
59
- /**
60
- * Finds prior siblings on disk that share an identifier with a newly-written
61
- * artifact, matching `<identifier>(-N)?.<ext>` for any of `config.siblingExtensions`.
62
- * The scan deliberately includes any file at the same path as the new write
63
- * — when a write overwrites an existing file with the same name, the file
64
- * currently on disk is the prior content (the overwrite happens after this
65
- * scan runs).
66
- */
67
- export declare function findPriorArtifactSiblings(scanDir: string, identifier: string, config: Pick<ArtifactStubGuardConfig, 'siblingExtensions'>): Promise<PriorArtifactSibling[]>;
68
- /** Reads guard config from `ARTIFACT_STUB_GUARD` / `ARTIFACT_STUB_GUARD_MIN_RATIO` / `ARTIFACT_STUB_GUARD_MIN_PRIOR_BYTES`, falling back to `defaults` for any unset/invalid value. */
69
- export declare function readArtifactStubGuardConfigFromEnv(env?: NodeJS.ProcessEnv, defaults?: ArtifactStubGuardConfig): ArtifactStubGuardConfig;
70
- /** Pure decision function: given the prior siblings on disk, decides whether the new body is a stub regression. Split from the disk scan so unit tests stay fast and can pre-fetch siblings. */
71
- export declare function classifyArtifactStubGuard(priors: readonly PriorArtifactSibling[], identifier: string, newSize: number, config: ArtifactStubGuardConfig): EvaluateArtifactStubGuardResult;
72
- export declare function evaluateArtifactStubGuard(input: EvaluateArtifactStubGuardInput): Promise<EvaluateArtifactStubGuardResult>;
73
- //# sourceMappingURL=stub-guard.d.ts.map
@@ -1,198 +0,0 @@
1
- import { readFile, readdir, stat } from 'node:fs/promises';
2
- import path from 'node:path';
3
- export class ArtifactRegressionError extends Error {
4
- code = 'ARTIFACT_REGRESSION';
5
- identifier;
6
- newSize;
7
- priorSize;
8
- priorName;
9
- constructor(message, details) {
10
- super(message);
11
- this.name = 'ArtifactRegressionError';
12
- this.identifier = details.identifier;
13
- this.newSize = details.newSize;
14
- this.priorSize = details.priorSize;
15
- this.priorName = details.priorName;
16
- }
17
- }
18
- export const DEFAULT_ARTIFACT_STUB_GUARD_CONFIG = {
19
- mode: 'warn',
20
- minRetainedRatio: 0.2,
21
- minPriorBytes: 4096,
22
- siblingExtensions: ['.html', '.htm'],
23
- };
24
- function escapeRegExp(value) {
25
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
26
- }
27
- /** Slugifies a free-form identifier into a filename-safe basename (lowercase, `[a-z0-9_-]`, max 60 chars). */
28
- export function slugifyArtifactIdentifier(value) {
29
- return value
30
- .toLowerCase()
31
- .replace(/[^a-z0-9_-]+/g, '-')
32
- .replace(/^-+|-+$/g, '')
33
- .slice(0, 60);
34
- }
35
- /** Fallback basename used when a slugified identifier is empty (e.g. an all-non-ASCII identifier strips to nothing). */
36
- export const EMPTY_SLUG_FALLBACK_NAME = 'artifact';
37
- /**
38
- * Two identifiers refer to the same artifact lineage when they're literally
39
- * equal, or one is the canonical slug form of the other (and that slug is
40
- * non-empty). Slug equality alone is not enough: a slugifier that truncates
41
- * at a fixed length would otherwise falsely bridge two distinct identifiers
42
- * that only diverge past that length — requiring one side to *be* the slug
43
- * form of the other avoids that while still bridging e.g. "Landing Page" and
44
- * "landing-page".
45
- */
46
- export function artifactIdentifiersMatch(a, b) {
47
- if (a === b)
48
- return true;
49
- const slugA = slugifyArtifactIdentifier(a);
50
- if (slugA.length === 0)
51
- return false;
52
- const slugB = slugifyArtifactIdentifier(b);
53
- if (slugA !== slugB)
54
- return false;
55
- return a === slugA || b === slugB;
56
- }
57
- async function readSidecarIdentifier(scanDir, entryName) {
58
- try {
59
- const raw = await readFile(path.join(scanDir, `${entryName}.artifact.json`), 'utf8');
60
- const parsed = JSON.parse(raw);
61
- const id = parsed?.metadata?.identifier;
62
- return typeof id === 'string' && id.length > 0 ? id : null;
63
- }
64
- catch {
65
- return null;
66
- }
67
- }
68
- function extensionAlternation(extensions) {
69
- return extensions.map((ext) => escapeRegExp(ext)).join('|');
70
- }
71
- function legacyCandidateIdentifiers(filename, extensionPattern, suffixPattern) {
72
- const fullBasename = filename.replace(extensionPattern, '');
73
- const stripped = filename.replace(suffixPattern, '');
74
- const candidates = [];
75
- if (fullBasename.length > 0)
76
- candidates.push(fullBasename);
77
- if (stripped.length > 0 && stripped !== fullBasename)
78
- candidates.push(stripped);
79
- return candidates;
80
- }
81
- /**
82
- * Finds prior siblings on disk that share an identifier with a newly-written
83
- * artifact, matching `<identifier>(-N)?.<ext>` for any of `config.siblingExtensions`.
84
- * The scan deliberately includes any file at the same path as the new write
85
- * — when a write overwrites an existing file with the same name, the file
86
- * currently on disk is the prior content (the overwrite happens after this
87
- * scan runs).
88
- */
89
- export async function findPriorArtifactSiblings(scanDir, identifier, config) {
90
- if (identifier.length === 0)
91
- return [];
92
- const extAlternation = extensionAlternation(config.siblingExtensions);
93
- if (!extAlternation)
94
- return [];
95
- const extensionPattern = new RegExp(`(?:${extAlternation})$`, 'i');
96
- const suffixPattern = new RegExp(`(?:-\\d+)?(?:${extAlternation})$`, 'i');
97
- const tokens = new Set();
98
- tokens.add(identifier);
99
- const slug = slugifyArtifactIdentifier(identifier);
100
- if (slug.length > 0)
101
- tokens.add(slug);
102
- else
103
- tokens.add(EMPTY_SLUG_FALLBACK_NAME);
104
- const alternation = Array.from(tokens, escapeRegExp).join('|');
105
- const pattern = new RegExp(`^(?:${alternation})(?:-\\d+)?(?:${extAlternation})$`, 'i');
106
- let entries;
107
- try {
108
- entries = await readdir(scanDir, { withFileTypes: true });
109
- }
110
- catch {
111
- return [];
112
- }
113
- const results = [];
114
- for (const entry of entries) {
115
- if (!entry.isFile())
116
- continue;
117
- if (!pattern.test(entry.name))
118
- continue;
119
- const sidecarIdentifier = await readSidecarIdentifier(scanDir, entry.name);
120
- // `legacyCandidateIdentifiers` always returns at least one non-empty
121
- // candidate here: `entry.name` already matched `pattern` above, which
122
- // requires its basename to start with one of `tokens` (all non-empty),
123
- // so an explicit `candidateIdentifiers.length === 0` guard would be
124
- // dead code — an empty array's `.some()` below already `continue`s.
125
- const candidateIdentifiers = sidecarIdentifier !== null
126
- ? [sidecarIdentifier]
127
- : legacyCandidateIdentifiers(entry.name, extensionPattern, suffixPattern);
128
- if (!candidateIdentifiers.some((c) => artifactIdentifiersMatch(identifier, c)))
129
- continue;
130
- try {
131
- const st = await stat(path.join(scanDir, entry.name));
132
- results.push({ name: entry.name, size: st.size });
133
- }
134
- catch {
135
- // Ignore unreadable entries — they don't influence the guard decision.
136
- }
137
- }
138
- return results;
139
- }
140
- /** Reads guard config from `ARTIFACT_STUB_GUARD` / `ARTIFACT_STUB_GUARD_MIN_RATIO` / `ARTIFACT_STUB_GUARD_MIN_PRIOR_BYTES`, falling back to `defaults` for any unset/invalid value. */
141
- export function readArtifactStubGuardConfigFromEnv(env = process.env, defaults = DEFAULT_ARTIFACT_STUB_GUARD_CONFIG) {
142
- const rawMode = (env.ARTIFACT_STUB_GUARD ?? '').toLowerCase();
143
- const mode = rawMode === 'reject' || rawMode === 'warn' || rawMode === 'off' ? rawMode : defaults.mode;
144
- const ratioRaw = Number(env.ARTIFACT_STUB_GUARD_MIN_RATIO);
145
- // Accept (0, 1] so a caller can set 1 to reject any shrinkage. Values <=0 or >1 fall back to default.
146
- const minRetainedRatio = Number.isFinite(ratioRaw) && ratioRaw > 0 && ratioRaw <= 1 ? ratioRaw : defaults.minRetainedRatio;
147
- const minPriorBytesRaw = Number(env.ARTIFACT_STUB_GUARD_MIN_PRIOR_BYTES);
148
- const minPriorBytes = Number.isInteger(minPriorBytesRaw) && minPriorBytesRaw > 0 ? minPriorBytesRaw : defaults.minPriorBytes;
149
- return { mode, minRetainedRatio, minPriorBytes, siblingExtensions: defaults.siblingExtensions };
150
- }
151
- function buildWarning(identifier, newSize, prior) {
152
- return {
153
- code: 'ARTIFACT_REGRESSION',
154
- message: `New artifact body for identifier "${identifier}" is ${newSize} bytes, ` +
155
- `but the largest prior sibling "${prior.name}" is ${prior.size} bytes. ` +
156
- 'This pattern usually means the write emitted a placeholder instead of the full document. ' +
157
- 'Set the guard mode to "warn" to record the warning without rejecting, or "off" to disable the guard entirely.',
158
- identifier,
159
- newSize,
160
- priorSize: prior.size,
161
- priorName: prior.name,
162
- };
163
- }
164
- /** Pure decision function: given the prior siblings on disk, decides whether the new body is a stub regression. Split from the disk scan so unit tests stay fast and can pre-fetch siblings. */
165
- export function classifyArtifactStubGuard(priors, identifier, newSize, config) {
166
- if (config.mode === 'off')
167
- return { outcome: 'pass' };
168
- if (identifier.length === 0)
169
- return { outcome: 'pass' };
170
- if (priors.length === 0)
171
- return { outcome: 'pass' };
172
- let largestSoFar = null;
173
- for (const prior of priors) {
174
- if (largestSoFar === null || prior.size > largestSoFar.size)
175
- largestSoFar = prior;
176
- }
177
- // Non-null assertion, not a runtime guard: `priors.length === 0` already
178
- // returned above, so this loop always runs at least once, and its first
179
- // iteration always satisfies `largestSoFar === null` — it's always
180
- // assigned by the time the loop finishes.
181
- const largest = largestSoFar;
182
- if (largest.size < config.minPriorBytes)
183
- return { outcome: 'pass' };
184
- const threshold = largest.size * config.minRetainedRatio;
185
- if (newSize >= threshold)
186
- return { outcome: 'pass' };
187
- const warning = buildWarning(identifier, newSize, largest);
188
- return { outcome: config.mode === 'reject' ? 'reject' : 'warn', warning };
189
- }
190
- export async function evaluateArtifactStubGuard(input) {
191
- if (input.config.mode === 'off')
192
- return { outcome: 'pass' };
193
- if (input.identifier.length === 0)
194
- return { outcome: 'pass' };
195
- const priors = await findPriorArtifactSiblings(input.scanDir, input.identifier, input.config);
196
- return classifyArtifactStubGuard(priors, input.identifier, input.newSize, input.config);
197
- }
198
- //# sourceMappingURL=stub-guard.js.map
@@ -1,68 +0,0 @@
1
- /**
2
- * @module artifacts/text-suppression
3
- *
4
- * A streaming-text state machine that suppresses a tagged block (matched by
5
- * caller-supplied open/close patterns) from user-visible output while it's
6
- * still arriving — used to hide an artifact's raw markup from chat prose
7
- * while it streams in, without buffering the whole response first. Ported
8
- * from OD's `apps/daemon/src/artifacts/text-suppression.ts`.
9
- *
10
- * The core (`createTaggedTextSuppressor`) was already fully generic in the
11
- * origin — it takes its open/close regexes and open/close prefix-match
12
- * predicates as parameters, no product coupling. What needed de-branding
13
- * were the origin's two pre-built instances: `createDsmlArtifactTextSuppressor`
14
- * hardcoded OD's own "DSML" markup-language tag name family
15
- * (`<|DSML artifact>`/`<artifact>`) as its open/close patterns.
16
- * `createXmlTagTextSuppressor` below replaces it — a generic factory taking
17
- * the caller's own tag-name list instead of a hardcoded vocabulary. The
18
- * `tool_call`/`edit` pairing the origin's other instance
19
- * (`createToolCallTextSuppressor`) suppressed is a generic agent-protocol
20
- * convention, not OD-branded, and is kept as a named default instance.
21
- */
22
- export type StreamTextEvent = {
23
- readonly type: 'text_delta';
24
- readonly delta: string;
25
- };
26
- export type StreamEventSink = (event: StreamTextEvent) => void;
27
- export interface ArtifactTextSuppressor {
28
- strip(text: string): string;
29
- flush(): string;
30
- isSuppressing(): boolean;
31
- hasPendingCandidate(): boolean;
32
- stats(): ArtifactTextSuppressorStats;
33
- }
34
- export interface ArtifactTextSuppressorStats {
35
- readonly suppressedChars: number;
36
- readonly suppressedChunks: number;
37
- readonly openedBlocks: number;
38
- readonly closedBlocks: number;
39
- readonly pendingCandidateChars: number;
40
- readonly suppressing: boolean;
41
- }
42
- /**
43
- * Builds a suppressor for a tagged block delimited by `openRe`/`closeRe`.
44
- * `isPossibleOpen`/`isPossibleClose` decide whether a trailing `<...`
45
- * fragment (with no closing `>` yet) *could* still become a match once more
46
- * text arrives — this is what lets the suppressor hold back a
47
- * not-yet-decidable tail across streaming chunk boundaries instead of
48
- * either emitting a tag fragment early or hanging indefinitely on a `<` that
49
- * turns out to be unrelated text.
50
- */
51
- export declare function createTaggedTextSuppressor(args: {
52
- openRe: RegExp;
53
- closeRe: RegExp;
54
- isPossibleOpen: (text: string) => boolean;
55
- isPossibleClose: (text: string) => boolean;
56
- }): ArtifactTextSuppressor;
57
- /** Feeds `text` through `suppressor` and emits a `text_delta` on `onEvent` only when something survives. Returns whether an event was emitted. */
58
- export declare function emitWithTextSuppressor(suppressor: ArtifactTextSuppressor, onEvent: StreamEventSink, text: string): boolean;
59
- /**
60
- * Builds a suppressor for an XML-like `<tagName ...>...</tagName>` block (or
61
- * a bracket-pipe variant `<|tagName ...>...<|/tagName|>`), matched
62
- * case-insensitively against any of `tagNames`. Replaces the origin's
63
- * hardcoded "DSML" tag-name family with a caller-supplied vocabulary.
64
- */
65
- export declare function createXmlTagTextSuppressor(tagNames: readonly string[]): ArtifactTextSuppressor;
66
- /** Suppresses a `<tool_call>...</tool_call>` or `<edit>...</edit>` block — a generic agent-protocol convention, not product-branded. */
67
- export declare function createToolCallTextSuppressor(): ArtifactTextSuppressor;
68
- //# sourceMappingURL=text-suppression.d.ts.map
@@ -1,184 +0,0 @@
1
- /**
2
- * @module artifacts/text-suppression
3
- *
4
- * A streaming-text state machine that suppresses a tagged block (matched by
5
- * caller-supplied open/close patterns) from user-visible output while it's
6
- * still arriving — used to hide an artifact's raw markup from chat prose
7
- * while it streams in, without buffering the whole response first. Ported
8
- * from OD's `apps/daemon/src/artifacts/text-suppression.ts`.
9
- *
10
- * The core (`createTaggedTextSuppressor`) was already fully generic in the
11
- * origin — it takes its open/close regexes and open/close prefix-match
12
- * predicates as parameters, no product coupling. What needed de-branding
13
- * were the origin's two pre-built instances: `createDsmlArtifactTextSuppressor`
14
- * hardcoded OD's own "DSML" markup-language tag name family
15
- * (`<|DSML artifact>`/`<artifact>`) as its open/close patterns.
16
- * `createXmlTagTextSuppressor` below replaces it — a generic factory taking
17
- * the caller's own tag-name list instead of a hardcoded vocabulary. The
18
- * `tool_call`/`edit` pairing the origin's other instance
19
- * (`createToolCallTextSuppressor`) suppressed is a generic agent-protocol
20
- * convention, not OD-branded, and is kept as a named default instance.
21
- */
22
- const MAX_CANDIDATE_LENGTH = 512;
23
- /**
24
- * Builds a suppressor for a tagged block delimited by `openRe`/`closeRe`.
25
- * `isPossibleOpen`/`isPossibleClose` decide whether a trailing `<...`
26
- * fragment (with no closing `>` yet) *could* still become a match once more
27
- * text arrives — this is what lets the suppressor hold back a
28
- * not-yet-decidable tail across streaming chunk boundaries instead of
29
- * either emitting a tag fragment early or hanging indefinitely on a `<` that
30
- * turns out to be unrelated text.
31
- */
32
- export function createTaggedTextSuppressor(args) {
33
- let suppressing = false;
34
- let candidate = '';
35
- let suppressedChars = 0;
36
- let suppressedChunks = 0;
37
- let openedBlocks = 0;
38
- let closedBlocks = 0;
39
- function noteSuppressed(text) {
40
- if (text.length <= 0)
41
- return;
42
- suppressedChars += text.length;
43
- suppressedChunks += 1;
44
- }
45
- function strip(text) {
46
- const current = `${candidate}${text}`;
47
- candidate = '';
48
- if (suppressing) {
49
- const close = args.closeRe.exec(current);
50
- if (!close || close.index === undefined) {
51
- const closeCandidateStart = possibleTagStart(current, args.isPossibleClose);
52
- if (closeCandidateStart !== -1) {
53
- candidate = current.slice(closeCandidateStart);
54
- noteSuppressed(current.slice(0, closeCandidateStart));
55
- }
56
- else {
57
- noteSuppressed(current);
58
- }
59
- return '';
60
- }
61
- suppressing = false;
62
- const end = close.index + close[0].length;
63
- closedBlocks += 1;
64
- noteSuppressed(current.slice(0, end));
65
- return strip(current.slice(end));
66
- }
67
- const open = args.openRe.exec(current);
68
- if (open && open.index !== undefined) {
69
- suppressing = true;
70
- openedBlocks += 1;
71
- const prefix = current.slice(0, open.index);
72
- const tail = current.slice(open.index + open[0].length);
73
- noteSuppressed(open[0]);
74
- return `${prefix}${strip(tail)}`;
75
- }
76
- const candidateStart = possibleTagStart(current, args.isPossibleOpen);
77
- if (candidateStart === -1)
78
- return current;
79
- candidate = current.slice(candidateStart);
80
- return current.slice(0, candidateStart);
81
- }
82
- function flush() {
83
- const text = candidate;
84
- candidate = '';
85
- return suppressing ? '' : text;
86
- }
87
- function isSuppressing() {
88
- return suppressing;
89
- }
90
- function hasPendingCandidate() {
91
- return candidate.length > 0;
92
- }
93
- function stats() {
94
- return {
95
- suppressedChars,
96
- suppressedChunks,
97
- openedBlocks,
98
- closedBlocks,
99
- pendingCandidateChars: candidate.length,
100
- suppressing,
101
- };
102
- }
103
- return { strip, flush, isSuppressing, hasPendingCandidate, stats };
104
- }
105
- /** Feeds `text` through `suppressor` and emits a `text_delta` on `onEvent` only when something survives. Returns whether an event was emitted. */
106
- export function emitWithTextSuppressor(suppressor, onEvent, text) {
107
- const delta = suppressor.strip(text);
108
- if (!delta)
109
- return false;
110
- onEvent({ type: 'text_delta', delta });
111
- return true;
112
- }
113
- function possibleTagStart(text, predicate) {
114
- const min = Math.max(0, text.length - MAX_CANDIDATE_LENGTH);
115
- let index = text.lastIndexOf('<');
116
- while (index >= min) {
117
- const tail = text.slice(index);
118
- if (predicate(tail))
119
- return index;
120
- if (index === 0)
121
- break;
122
- index = text.lastIndexOf('<', index - 1);
123
- }
124
- return -1;
125
- }
126
- // `text` is always a `possibleTagStart` tail slice starting at a `<`
127
- // position (its only caller) — no `!text.startsWith('<')` re-check needed.
128
- function compactTagCandidate(text, stripChars) {
129
- if (text.includes('>'))
130
- return null;
131
- return text.toLowerCase().replace(stripChars, '');
132
- }
133
- /**
134
- * Builds a suppressor for an XML-like `<tagName ...>...</tagName>` block (or
135
- * a bracket-pipe variant `<|tagName ...>...<|/tagName|>`), matched
136
- * case-insensitively against any of `tagNames`. Replaces the origin's
137
- * hardcoded "DSML" tag-name family with a caller-supplied vocabulary.
138
- */
139
- export function createXmlTagTextSuppressor(tagNames) {
140
- const canonicals = tagNames.map((t) => t.toLowerCase());
141
- const namesPattern = canonicals.map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
142
- const openRe = new RegExp(`(?:<\\s*\\|?\\s*(?:${namesPattern})\\b[^>]*>)`, 'i');
143
- const closeRe = new RegExp(`(?:<\\/(?:${namesPattern})>|<\\s*\\|?\\s*\\/\\s*(?:${namesPattern})\\s*\\|?\\s*>)`, 'i');
144
- function isPossibleOpen(text) {
145
- const compact = compactTagCandidate(text, /[<|,\s]/g);
146
- if (compact === null)
147
- return false;
148
- return compact.length === 0 || canonicals.some((c) => c.startsWith(compact) || compact.startsWith(c));
149
- }
150
- function isPossibleClose(text) {
151
- const compact = compactTagCandidate(text, /[<|/\s]/g);
152
- if (compact === null)
153
- return false;
154
- return compact.length === 0 || canonicals.some((c) => c.startsWith(compact) || compact.startsWith(c));
155
- }
156
- return createTaggedTextSuppressor({ openRe, closeRe, isPossibleOpen, isPossibleClose });
157
- }
158
- const TOOL_CALL_OPEN_RE = /(?:<\s*tool_call\b[^>]*>|<\s*edit\s*>)/i;
159
- const TOOL_CALL_CLOSE_RE = /(?:<\/\s*tool_call\s*>|<\/\s*edit\s*>)/i;
160
- const TOOL_CALL_CANONICALS = ['toolcall', 'edit'];
161
- // Same reasoning as compactTagCandidate above: `text` always starts with
162
- // `<` here (a `possibleTagStart` tail slice) — no re-check needed.
163
- function isPossibleToolCallOpen(text) {
164
- if (text.includes('>'))
165
- return false;
166
- const compact = text.toLowerCase().replace(/[<|,\s_-]/g, '');
167
- return compact.length === 0 || TOOL_CALL_CANONICALS.some((c) => c.startsWith(compact) || compact.startsWith(c));
168
- }
169
- function isPossibleToolCallClose(text) {
170
- if (text.includes('>'))
171
- return false;
172
- const compact = text.toLowerCase().replace(/[<|/\s_-]/g, '');
173
- return compact.length === 0 || TOOL_CALL_CANONICALS.some((c) => c.startsWith(compact) || compact.startsWith(c));
174
- }
175
- /** Suppresses a `<tool_call>...</tool_call>` or `<edit>...</edit>` block — a generic agent-protocol convention, not product-branded. */
176
- export function createToolCallTextSuppressor() {
177
- return createTaggedTextSuppressor({
178
- openRe: TOOL_CALL_OPEN_RE,
179
- closeRe: TOOL_CALL_CLOSE_RE,
180
- isPossibleOpen: isPossibleToolCallOpen,
181
- isPossibleClose: isPossibleToolCallClose,
182
- });
183
- }
184
- //# sourceMappingURL=text-suppression.js.map