@jini-ai/integrations 0.4.2 → 0.4.3
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 +13 -0
- package/dist/api-connections/access-token.d.ts +9 -0
- package/dist/api-connections/access-token.js +92 -0
- package/dist/api-connections/account-actions.d.ts +40 -0
- package/dist/api-connections/account-actions.js +110 -0
- package/dist/api-connections/attempt-state.d.ts +28 -0
- package/dist/api-connections/attempt-state.js +73 -0
- package/dist/api-connections/authorization.d.ts +45 -0
- package/dist/api-connections/authorization.js +120 -0
- package/dist/api-connections/deps.d.ts +41 -0
- package/dist/api-connections/deps.js +13 -0
- package/dist/api-connections/descriptor.d.ts +6 -0
- package/dist/api-connections/descriptor.js +111 -0
- package/dist/api-connections/errors.d.ts +23 -0
- package/dist/api-connections/errors.js +24 -0
- package/dist/api-connections/finish-authorization.d.ts +24 -0
- package/dist/api-connections/finish-authorization.js +117 -0
- package/dist/api-connections/index.d.ts +18 -0
- package/dist/api-connections/index.js +10 -0
- package/dist/api-connections/install-credential.d.ts +19 -0
- package/dist/api-connections/install-credential.js +12 -0
- package/dist/api-connections/keys.d.ts +27 -0
- package/dist/api-connections/keys.js +22 -0
- package/dist/api-connections/ports.d.ts +73 -0
- package/dist/api-connections/ports.js +2 -0
- package/dist/api-connections/records.d.ts +27 -0
- package/dist/api-connections/records.js +52 -0
- package/dist/api-connections/request-checks.d.ts +18 -0
- package/dist/api-connections/request-checks.js +67 -0
- package/dist/api-connections/service.d.ts +25 -0
- package/dist/api-connections/service.js +26 -0
- package/dist/api-connections/status.d.ts +28 -0
- package/dist/api-connections/status.js +36 -0
- package/dist/api-connections/token-store/errors.d.ts +20 -0
- package/dist/api-connections/token-store/errors.js +38 -0
- package/dist/api-connections/token-store/index.d.ts +6 -0
- package/dist/api-connections/token-store/index.js +6 -0
- package/dist/api-connections/token-store/record.d.ts +69 -0
- package/dist/api-connections/token-store/record.js +97 -0
- package/dist/api-connections/token-store/vault-token-store.d.ts +26 -0
- package/dist/api-connections/token-store/vault-token-store.js +215 -0
- package/dist/api-connections/types.d.ts +101 -0
- package/dist/api-connections/types.js +9 -0
- package/dist/credentialed-http/auth-schemes.js +8 -4
- package/dist/credentialed-http/credentialed-request.js +47 -77
- package/dist/credentialed-http/response-redaction.d.ts +5 -0
- package/dist/credentialed-http/response-redaction.js +62 -0
- package/dist/media-providers/catalog.d.ts +3 -1
- package/dist/media-providers/catalog.js +3 -1
- package/dist/media-providers/dispatch/async-operation-store.d.ts +31 -0
- package/dist/media-providers/dispatch/async-operation-store.js +75 -37
- package/dist/media-providers/dispatch/builtin-vendors.d.ts +1 -1
- package/dist/media-providers/dispatch/context.js +10 -2
- package/dist/media-providers/dispatch/engine.d.ts +6 -3
- package/dist/media-providers/dispatch/engine.js +99 -109
- package/dist/media-providers/dispatch/index.d.ts +4 -2
- package/dist/media-providers/dispatch/index.js +3 -1
- package/dist/media-providers/dispatch/media-provider-registry.d.ts +62 -0
- package/dist/media-providers/dispatch/media-provider-registry.js +141 -0
- package/dist/media-providers/dispatch/node.d.ts +13 -0
- package/dist/media-providers/dispatch/node.js +24 -0
- package/dist/media-providers/dispatch/openai-compatible.d.ts +1 -1
- package/dist/media-providers/dispatch/openai-compatible.js +90 -87
- package/dist/media-providers/dispatch/operation-runtime.js +116 -89
- package/dist/media-providers/dispatch/outbound.d.ts +8 -4
- package/dist/media-providers/dispatch/outbound.js +27 -26
- package/dist/media-providers/dispatch/providers/aihubmix.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/aihubmix.js +61 -56
- package/dist/media-providers/dispatch/providers/custom-image.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/elevenlabs.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/fishaudio.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/grok.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/imagerouter-video-async.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +53 -49
- package/dist/media-providers/dispatch/providers/imagerouter.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/imagerouter.js +11 -24
- package/dist/media-providers/dispatch/providers/minimax.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/nanobanana.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/nanobanana.js +22 -30
- package/dist/media-providers/dispatch/providers/openai.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/openai.js +51 -47
- package/dist/media-providers/dispatch/providers/openrouter.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/openrouter.js +52 -37
- package/dist/media-providers/dispatch/providers/senseaudio.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/senseaudio.js +47 -28
- package/dist/media-providers/dispatch/providers/volcengine.d.ts +1 -1
- package/dist/media-providers/dispatch/response-parsers.js +37 -21
- package/dist/media-providers/dispatch/sqlite-async-operation-store.js +9 -29
- package/dist/media-providers/dispatch/ssrf-guard.d.ts +3 -2
- package/dist/media-providers/dispatch/ssrf-guard.js +6 -5
- package/dist/media-providers/dispatch/types.d.ts +76 -2
- package/dist/media-providers/dispatch/vendor-adapter.d.ts +2 -43
- package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
- package/dist/media-providers/dispatch/vendor-registry-core.d.ts +24 -0
- package/dist/media-providers/dispatch/vendor-registry-core.js +34 -0
- package/dist/media-providers/dispatch/vendor-registry.d.ts +10 -36
- package/dist/media-providers/dispatch/vendor-registry.js +14 -42
- package/dist/media-providers/policy.js +25 -17
- package/dist/media-providers/providers.d.ts +5 -0
- package/dist/media-providers/providers.js +2 -0
- package/dist/media-providers/sqlite-task-store.js +12 -80
- package/dist/media-providers/staging.js +77 -58
- package/dist/media-providers/task-lifecycle.d.ts +33 -0
- package/dist/media-providers/task-lifecycle.js +124 -0
- package/dist/media-providers/task-store.js +8 -86
- package/dist/media-providers/ui-defaults.d.ts +10 -0
- package/dist/media-providers/ui-defaults.js +167 -0
- package/dist/media-providers/video-request.js +112 -90
- package/dist/webhooks/delivery.d.ts +14 -0
- package/dist/webhooks/delivery.js +41 -10
- package/dist/webhooks/index.d.ts +1 -0
- package/dist/webhooks/index.js +1 -0
- package/dist/webhooks/ports.d.ts +23 -0
- package/dist/webhooks/worker.d.ts +83 -0
- package/dist/webhooks/worker.js +105 -0
- package/package.json +31 -8
|
@@ -1,50 +1,21 @@
|
|
|
1
|
+
import { VendorAdapterRegistry } from './vendor-registry-core.js';
|
|
2
|
+
export { VendorAdapterRegistry } from './vendor-registry-core.js';
|
|
1
3
|
import { registerBuiltinVendorAdapters } from './builtin-vendors.js';
|
|
2
|
-
|
|
3
|
-
table = new Map();
|
|
4
|
-
/** Registers `adapter` for `(providerId, routeKey)`. Throws if that pair is already registered — a vendor module should register each of its (provider, surface) pairs exactly once, at module load. */
|
|
5
|
-
register({ providerId, routeKey, adapter }) {
|
|
6
|
-
let bySurface = this.table.get(providerId);
|
|
7
|
-
if (!bySurface) {
|
|
8
|
-
bySurface = new Map();
|
|
9
|
-
this.table.set(providerId, bySurface);
|
|
10
|
-
}
|
|
11
|
-
if (bySurface.has(routeKey)) {
|
|
12
|
-
throw new Error(`a vendor adapter is already registered for "${providerId}" / "${routeKey}"`);
|
|
13
|
-
}
|
|
14
|
-
bySurface.set(routeKey, adapter);
|
|
15
|
-
}
|
|
16
|
-
/** Looks up the adapter registered for `(providerId, routeKey)`, or `undefined` if none is registered. */
|
|
17
|
-
get({ providerId, routeKey }) {
|
|
18
|
-
return this.table.get(providerId)?.get(routeKey);
|
|
19
|
-
}
|
|
20
|
-
/** Whether an adapter is registered for `(providerId, routeKey)`. */
|
|
21
|
-
has({ providerId, routeKey }) {
|
|
22
|
-
return this.table.get(providerId)?.has(routeKey) ?? false;
|
|
23
|
-
}
|
|
24
|
-
/** Every `(providerId, routeKey)` pair currently registered — used by tests (and any diagnostics a host wants) to enumerate exactly which vendors run through the generic engine. */
|
|
25
|
-
list() {
|
|
26
|
-
const out = [];
|
|
27
|
-
for (const [providerId, bySurface] of this.table) {
|
|
28
|
-
for (const routeKey of bySurface.keys()) {
|
|
29
|
-
out.push([providerId, routeKey]);
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
return out;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
/** Creates a fresh, empty registry — mainly useful for tests that want isolation from the shared `mediaVendorRegistry` singleton. */
|
|
4
|
+
/** Creates a fresh, empty registry for host-owned registrations. */
|
|
36
5
|
export function createVendorAdapterRegistry() {
|
|
37
6
|
return new VendorAdapterRegistry();
|
|
38
7
|
}
|
|
39
|
-
/**
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
* own vendor adapters without touching this module's set) can still call
|
|
44
|
-
* `createVendorAdapterRegistry()` directly instead of using this singleton.
|
|
8
|
+
/** Creates a fresh registry populated by the existing builtin-registration owner.
|
|
9
|
+
* @deprecated Adapters only, no catalogue: plugin vendors cannot validate through it. Build one
|
|
10
|
+
* `createMediaProviderRegistry()` at composition and pass it as `registry` and `catalog`.
|
|
11
|
+
* @returns An independent registry; duplicate route registration still throws.
|
|
45
12
|
*/
|
|
46
|
-
|
|
47
|
-
|
|
13
|
+
export function createBuiltinVendorAdapterRegistry(_required = {}, _options = {}) {
|
|
14
|
+
const registry = createVendorAdapterRegistry();
|
|
15
|
+
registerBuiltinVendorAdapters({ registry });
|
|
16
|
+
return registry;
|
|
17
|
+
}
|
|
18
|
+
// Preserve lazy singleton contents for existing callers; engines never consult it.
|
|
48
19
|
class BuiltinVendorAdapterRegistry extends VendorAdapterRegistry {
|
|
49
20
|
initialized = false;
|
|
50
21
|
initialize() {
|
|
@@ -71,5 +42,6 @@ class BuiltinVendorAdapterRegistry extends VendorAdapterRegistry {
|
|
|
71
42
|
return super.list();
|
|
72
43
|
}
|
|
73
44
|
}
|
|
45
|
+
/** @deprecated Build one createMediaProviderRegistry() per host composition and inject it instead. */
|
|
74
46
|
export const mediaVendorRegistry = new BuiltinVendorAdapterRegistry();
|
|
75
47
|
//# sourceMappingURL=vendor-registry.js.map
|
|
@@ -4,6 +4,30 @@
|
|
|
4
4
|
// not passing a policy at all — media generation is a real-money, costly
|
|
5
5
|
// capability, not something that should be on by default.
|
|
6
6
|
export const DEFAULT_MEDIA_EXECUTION_POLICY = { mode: 'disabled' };
|
|
7
|
+
/** A missing or empty allowlist means "no restriction on that dimension". */
|
|
8
|
+
function isRestricted(allowlist) {
|
|
9
|
+
return allowlist !== undefined && allowlist.length > 0;
|
|
10
|
+
}
|
|
11
|
+
function surfaceDenial(policy, surface) {
|
|
12
|
+
if (!isRestricted(policy.allowedSurfaces) || policy.allowedSurfaces.includes(surface))
|
|
13
|
+
return null;
|
|
14
|
+
return { code: 'MEDIA_SURFACE_DENIED', message: `media surface "${surface}" is not allowed for this run` };
|
|
15
|
+
}
|
|
16
|
+
function modelDenial(policy, model) {
|
|
17
|
+
// SEC-RB-010: a model allowlist must not be bypassable by omitting the
|
|
18
|
+
// model field. If the host restricted models at all, an unspecified
|
|
19
|
+
// (or blank-after-normalization) model can't be verified against that
|
|
20
|
+
// allowlist and must be denied, not silently waved through.
|
|
21
|
+
const normalizedModel = model?.trim();
|
|
22
|
+
if (!isRestricted(policy.allowedModels))
|
|
23
|
+
return null;
|
|
24
|
+
if (normalizedModel && policy.allowedModels.includes(normalizedModel))
|
|
25
|
+
return null;
|
|
26
|
+
return {
|
|
27
|
+
code: 'MEDIA_MODEL_DENIED',
|
|
28
|
+
message: `media model ${normalizedModel ? `"${normalizedModel}"` : '(none specified)'} is not allowed for this run`,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
7
31
|
/**
|
|
8
32
|
* Reference `MediaPolicy`: an enabled/disabled + surface/model allowlist
|
|
9
33
|
* gate, ported verbatim from the origin's `mediaExecutionPolicyDenial`. A
|
|
@@ -18,23 +42,7 @@ export function createAllowlistMediaPolicy(_required, optional = {}) {
|
|
|
18
42
|
if (policy.mode === 'disabled') {
|
|
19
43
|
return { code: 'MEDIA_EXECUTION_DISABLED', message: 'media generation is disabled for this run' };
|
|
20
44
|
}
|
|
21
|
-
|
|
22
|
-
return { code: 'MEDIA_SURFACE_DENIED', message: `media surface "${target.surface}" is not allowed for this run` };
|
|
23
|
-
}
|
|
24
|
-
// SEC-RB-010: a model allowlist must not be bypassable by omitting the
|
|
25
|
-
// model field. If the host restricted models at all, an unspecified
|
|
26
|
-
// (or blank-after-normalization) model can't be verified against that
|
|
27
|
-
// allowlist and must be denied, not silently waved through.
|
|
28
|
-
const normalizedModel = target.model?.trim();
|
|
29
|
-
if (policy.allowedModels && policy.allowedModels.length > 0) {
|
|
30
|
-
if (!normalizedModel || !policy.allowedModels.includes(normalizedModel)) {
|
|
31
|
-
return {
|
|
32
|
-
code: 'MEDIA_MODEL_DENIED',
|
|
33
|
-
message: `media model ${normalizedModel ? `"${normalizedModel}"` : '(none specified)'} is not allowed for this run`,
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
return null;
|
|
45
|
+
return surfaceDenial(policy, target.surface) ?? modelDenial(policy, target.model);
|
|
38
46
|
},
|
|
39
47
|
};
|
|
40
48
|
}
|
|
@@ -41,6 +41,11 @@ export declare function canonicalMediaProviderId({ id }: {
|
|
|
41
41
|
export declare function normalizeMediaProviderMap<T>({ providers }: {
|
|
42
42
|
providers: Readonly<Record<string, T>>;
|
|
43
43
|
}, _optional?: Record<string, never>): Record<string, T>;
|
|
44
|
+
/** Host-injected UI policy; reuse the catalog's existing identity and normalization owner. */
|
|
45
|
+
export declare const mediaProviderCatalogPolicy: {
|
|
46
|
+
canonicalMediaProviderId: typeof canonicalMediaProviderId;
|
|
47
|
+
normalizeMediaProviderMap: typeof normalizeMediaProviderMap;
|
|
48
|
+
};
|
|
44
49
|
export declare const MEDIA_PROVIDERS: readonly MediaProvider[];
|
|
45
50
|
export declare const IMAGE_MODELS: readonly MediaModel[];
|
|
46
51
|
export declare const VIDEO_MODELS: readonly MediaModel[];
|
|
@@ -28,6 +28,8 @@ export function normalizeMediaProviderMap({ providers }, _optional = {}) {
|
|
|
28
28
|
...entries.filter(([id]) => canonicalMediaProviderId({ id }) === id),
|
|
29
29
|
]);
|
|
30
30
|
}
|
|
31
|
+
/** Host-injected UI policy; reuse the catalog's existing identity and normalization owner. */
|
|
32
|
+
export const mediaProviderCatalogPolicy = { canonicalMediaProviderId, normalizeMediaProviderMap };
|
|
31
33
|
export const MEDIA_PROVIDERS = [
|
|
32
34
|
{ id: 'openai', label: 'OpenAI', hint: 'gpt-image-2 / dall-e-3', integrated: true, defaultBaseUrl: VENDOR_API_BASE_URLS.openai },
|
|
33
35
|
{ id: 'volcengine', label: 'Volcengine Ark (Doubao)', hint: 'Seedance 2.0 / Seedream', integrated: true, defaultBaseUrl: VENDOR_API_BASE_URLS.volcengine },
|
|
@@ -1,30 +1,9 @@
|
|
|
1
1
|
import { loadMediaSqliteOpener } from './sqlite-driver.adapter.js';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
'interrupted',
|
|
8
|
-
]);
|
|
9
|
-
const TERMINAL_STATUSES = new Set(['done', 'failed', 'interrupted']);
|
|
10
|
-
// Mirrors task-store.ts's own ALLOWED_TRANSITIONS exactly (CR-013: enum
|
|
11
|
-
// membership alone doesn't prove a transition is legal, e.g. done -> running).
|
|
12
|
-
const ALLOWED_TRANSITIONS = {
|
|
13
|
-
queued: new Set(['queued', 'running', 'done', 'failed', 'interrupted']),
|
|
14
|
-
running: new Set(['running', 'done', 'failed', 'interrupted']),
|
|
15
|
-
done: new Set(['done']),
|
|
16
|
-
failed: new Set(['failed']),
|
|
17
|
-
interrupted: new Set(['interrupted']),
|
|
18
|
-
};
|
|
19
|
-
const INTERRUPTED_ERROR = {
|
|
20
|
-
message: 'media task interrupted by daemon restart',
|
|
21
|
-
code: 'DAEMON_RESTART',
|
|
22
|
-
};
|
|
23
|
-
function assertValidStatus(status) {
|
|
24
|
-
if (!VALID_STATUSES.has(status)) {
|
|
25
|
-
throw new RangeError(`Invalid media task status: "${status}"`);
|
|
26
|
-
}
|
|
27
|
-
}
|
|
2
|
+
// Shared with task-store.ts's in-memory adapter (task-lifecycle.ts), so the
|
|
3
|
+
// two cannot drift: CR-013's transition graph (enum membership alone doesn't
|
|
4
|
+
// prove a transition is legal, e.g. done -> running), duplicate-free status
|
|
5
|
+
// sets, and the create/patch/reconcile row arithmetic all live there once.
|
|
6
|
+
import { applyTaskPatch, assertValidTerminalTtl, buildNewTask, reconcileAction } from './task-lifecycle.js';
|
|
28
7
|
/**
|
|
29
8
|
* Reconstructs a `MediaTask` from a stored row. `surface`/`model` are
|
|
30
9
|
* conditionally spread — matching `task-store.ts`'s own in-memory adapter,
|
|
@@ -129,24 +108,7 @@ export async function createSqliteMediaTaskStore(required, options = {}) {
|
|
|
129
108
|
if (getStmt.get(input.id)) {
|
|
130
109
|
throw new Error(`media task "${input.id}" already exists`);
|
|
131
110
|
}
|
|
132
|
-
const
|
|
133
|
-
assertValidStatus(status);
|
|
134
|
-
const now = Date.now();
|
|
135
|
-
const startedAt = input.startedAt ?? now;
|
|
136
|
-
const task = {
|
|
137
|
-
id: input.id,
|
|
138
|
-
ownerRef: input.ownerRef,
|
|
139
|
-
status,
|
|
140
|
-
progress: input.progress ? [...input.progress] : [],
|
|
141
|
-
file: input.file == null ? null : structuredClone(input.file),
|
|
142
|
-
error: input.error == null ? null : { ...input.error },
|
|
143
|
-
startedAt,
|
|
144
|
-
endedAt: null,
|
|
145
|
-
createdAt: now,
|
|
146
|
-
updatedAt: now,
|
|
147
|
-
...(input.surface !== undefined ? { surface: input.surface } : {}),
|
|
148
|
-
...(input.model !== undefined ? { model: input.model } : {}),
|
|
149
|
-
};
|
|
111
|
+
const task = buildNewTask(input, Date.now());
|
|
150
112
|
writeRow(task, true);
|
|
151
113
|
return task;
|
|
152
114
|
});
|
|
@@ -154,28 +116,7 @@ export async function createSqliteMediaTaskStore(required, options = {}) {
|
|
|
154
116
|
const row = getStmt.get(id);
|
|
155
117
|
if (!row)
|
|
156
118
|
return null;
|
|
157
|
-
const
|
|
158
|
-
const status = patch.status ?? existing.status;
|
|
159
|
-
assertValidStatus(status);
|
|
160
|
-
if (!ALLOWED_TRANSITIONS[existing.status].has(status)) {
|
|
161
|
-
throw new RangeError(`Invalid media task transition: "${existing.status}" -> "${status}"`);
|
|
162
|
-
}
|
|
163
|
-
const surface = 'surface' in patch ? (patch.surface ?? undefined) : existing.surface;
|
|
164
|
-
const model = 'model' in patch ? (patch.model ?? undefined) : existing.model;
|
|
165
|
-
const next = {
|
|
166
|
-
id: existing.id,
|
|
167
|
-
ownerRef: existing.ownerRef,
|
|
168
|
-
status,
|
|
169
|
-
progress: patch.progress ? [...patch.progress] : existing.progress,
|
|
170
|
-
file: 'file' in patch ? (patch.file == null ? null : structuredClone(patch.file)) : existing.file,
|
|
171
|
-
error: 'error' in patch ? (patch.error == null ? null : { ...patch.error }) : existing.error,
|
|
172
|
-
startedAt: existing.startedAt,
|
|
173
|
-
endedAt: 'endedAt' in patch ? (patch.endedAt ?? null) : existing.endedAt,
|
|
174
|
-
createdAt: existing.createdAt,
|
|
175
|
-
updatedAt: Date.now(),
|
|
176
|
-
...(surface !== undefined ? { surface } : {}),
|
|
177
|
-
...(model !== undefined ? { model } : {}),
|
|
178
|
-
};
|
|
119
|
+
const next = applyTaskPatch(rowToTask(row), patch, Date.now());
|
|
179
120
|
writeRow(next, false);
|
|
180
121
|
return next;
|
|
181
122
|
});
|
|
@@ -186,19 +127,12 @@ export async function createSqliteMediaTaskStore(required, options = {}) {
|
|
|
186
127
|
let deleted = 0;
|
|
187
128
|
for (const row of selectAllStmt.all()) {
|
|
188
129
|
const task = rowToTask(row);
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
status: 'interrupted',
|
|
193
|
-
error: INTERRUPTED_ERROR,
|
|
194
|
-
endedAt: task.endedAt ?? now,
|
|
195
|
-
updatedAt: now,
|
|
196
|
-
};
|
|
197
|
-
writeRow(next, false);
|
|
130
|
+
const action = reconcileAction(task, now, cutoff);
|
|
131
|
+
if (action.kind === 'interrupt') {
|
|
132
|
+
writeRow(action.next, false);
|
|
198
133
|
interrupted += 1;
|
|
199
|
-
continue;
|
|
200
134
|
}
|
|
201
|
-
if (
|
|
135
|
+
else if (action.kind === 'delete') {
|
|
202
136
|
deleteStmt.run(task.id);
|
|
203
137
|
deleted += 1;
|
|
204
138
|
}
|
|
@@ -225,9 +159,7 @@ export async function createSqliteMediaTaskStore(required, options = {}) {
|
|
|
225
159
|
deleteStmt.run(id);
|
|
226
160
|
},
|
|
227
161
|
async reconcileOnBoot(options) {
|
|
228
|
-
|
|
229
|
-
throw new RangeError(`Invalid terminalTtlMs: ${options.terminalTtlMs} must be a non-negative finite number`);
|
|
230
|
-
}
|
|
162
|
+
assertValidTerminalTtl(options.terminalTtlMs);
|
|
231
163
|
return reconcileTxn(options);
|
|
232
164
|
},
|
|
233
165
|
async close() {
|
|
@@ -58,6 +58,77 @@ async function pruneStagedAttachments(stagingDir, maxAgeMs) {
|
|
|
58
58
|
}
|
|
59
59
|
}));
|
|
60
60
|
}
|
|
61
|
+
// Fail closed, not open: an explicitly-supplied uploadRoot that doesn't
|
|
62
|
+
// resolve is a caller configuration error, not an "unrestricted" signal
|
|
63
|
+
// (SEC-RB-003 — the prior behavior collapsed "no uploadRoot" and
|
|
64
|
+
// "unresolvable uploadRoot" into the same no-restriction case, letting
|
|
65
|
+
// any host-readable file be staged when uploadRoot merely failed to
|
|
66
|
+
// resolve). Omitting uploadRoot entirely is still allowed, but then only
|
|
67
|
+
// paths already inside `cwd` can be staged — nothing outside `cwd` can
|
|
68
|
+
// be copied in without a resolvable uploadRoot to authorize it.
|
|
69
|
+
async function resolveUploadRoot(uploadRoot) {
|
|
70
|
+
if (uploadRoot == null)
|
|
71
|
+
return null;
|
|
72
|
+
try {
|
|
73
|
+
return await fs.promises.realpath(uploadRoot);
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
throw new Error(`attachment staging: uploadRoot ${JSON.stringify(uploadRoot)} could not be resolved: ${error.message}`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** Creates `stagingDir`, refuses a symlinked one, and prunes stale entries. */
|
|
80
|
+
async function prepareStagingDir(stagingDir, maxAgeMs) {
|
|
81
|
+
await fs.promises.mkdir(stagingDir, { recursive: true });
|
|
82
|
+
// The staging directory is a destination this component writes into
|
|
83
|
+
// and later prunes/deletes from — refuse to operate through a symlink
|
|
84
|
+
// here, since a pre-planted symlink would redirect writes/deletes
|
|
85
|
+
// outside `root` (SEC-RB-003).
|
|
86
|
+
const stagingDirLstat = await fs.promises.lstat(stagingDir);
|
|
87
|
+
if (stagingDirLstat.isSymbolicLink()) {
|
|
88
|
+
throw new Error(`attachment staging: staging directory ${stagingDir} is a symlink, refusing to use it`);
|
|
89
|
+
}
|
|
90
|
+
await pruneStagedAttachments(stagingDir, maxAgeMs);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Stages one already-validated, non-blank path. Returns the path to submit,
|
|
94
|
+
* or null when the file is advisory-skippable (not a file, outside
|
|
95
|
+
* uploadRoot, too large). Throws `MissingUploadRootError` for an outside-cwd
|
|
96
|
+
* file with no uploadRoot; any other error is the caller's to swallow.
|
|
97
|
+
*/
|
|
98
|
+
async function stageOne(inputPath, ctx) {
|
|
99
|
+
const real = await fs.promises.realpath(path.resolve(inputPath));
|
|
100
|
+
const stat = await fs.promises.stat(real);
|
|
101
|
+
if (!stat.isFile())
|
|
102
|
+
return null;
|
|
103
|
+
if (isWithinRoot(ctx.rootReal, real))
|
|
104
|
+
return real;
|
|
105
|
+
// Outside cwd: this is the "copy an external file into staging"
|
|
106
|
+
// path, which requires an authorized uploadRoot — deny by default.
|
|
107
|
+
if (ctx.uploadRootReal == null) {
|
|
108
|
+
throw new MissingUploadRootError('attachment staging: files outside cwd require an uploadRoot');
|
|
109
|
+
}
|
|
110
|
+
if (!isWithinRoot(ctx.uploadRootReal, real))
|
|
111
|
+
return null;
|
|
112
|
+
if (stat.size > ctx.maxBytesPerFile)
|
|
113
|
+
return null;
|
|
114
|
+
const destination = path.join(ctx.stagingDir, `${randomUUID()}-${path.basename(real)}`);
|
|
115
|
+
await fs.promises.copyFile(real, destination);
|
|
116
|
+
return destination;
|
|
117
|
+
}
|
|
118
|
+
/** `stageOne` with the advisory-input policy: malformed or missing files are skipped, authorization failures escape. */
|
|
119
|
+
async function stageOneAdvisory(inputPath, ctx) {
|
|
120
|
+
if (typeof inputPath !== 'string' || inputPath.trim().length === 0)
|
|
121
|
+
return null;
|
|
122
|
+
try {
|
|
123
|
+
return await stageOne(inputPath, ctx);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
if (error instanceof MissingUploadRootError)
|
|
127
|
+
throw error;
|
|
128
|
+
// Ignore malformed or missing files; attachments are advisory input.
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
61
132
|
/** Creates a filesystem-backed `AttachmentStaging` rooted at `cwd`. */
|
|
62
133
|
export function createFsAttachmentStaging({ cwd }, options = {}) {
|
|
63
134
|
const stagingDirName = options.stagingDirName ?? DEFAULT_STAGING_DIRNAME;
|
|
@@ -74,33 +145,8 @@ export function createFsAttachmentStaging({ cwd }, options = {}) {
|
|
|
74
145
|
if (imagePaths.length > maxItems) {
|
|
75
146
|
throw new Error(`attachment staging: ${imagePaths.length} paths exceeds the ${maxItems}-item limit`);
|
|
76
147
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
// (SEC-RB-003 — the prior behavior collapsed "no uploadRoot" and
|
|
80
|
-
// "unresolvable uploadRoot" into the same no-restriction case, letting
|
|
81
|
-
// any host-readable file be staged when uploadRoot merely failed to
|
|
82
|
-
// resolve). Omitting uploadRoot entirely is still allowed, but then only
|
|
83
|
-
// paths already inside `cwd` can be staged — nothing outside `cwd` can
|
|
84
|
-
// be copied in without a resolvable uploadRoot to authorize it.
|
|
85
|
-
let uploadRootReal = null;
|
|
86
|
-
if (uploadRoot != null) {
|
|
87
|
-
try {
|
|
88
|
-
uploadRootReal = await fs.promises.realpath(uploadRoot);
|
|
89
|
-
}
|
|
90
|
-
catch (error) {
|
|
91
|
-
throw new Error(`attachment staging: uploadRoot ${JSON.stringify(uploadRoot)} could not be resolved: ${error.message}`);
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
await fs.promises.mkdir(stagingDir, { recursive: true });
|
|
95
|
-
// The staging directory is a destination this component writes into
|
|
96
|
-
// and later prunes/deletes from — refuse to operate through a symlink
|
|
97
|
-
// here, since a pre-planted symlink would redirect writes/deletes
|
|
98
|
-
// outside `root` (SEC-RB-003).
|
|
99
|
-
const stagingDirLstat = await fs.promises.lstat(stagingDir);
|
|
100
|
-
if (stagingDirLstat.isSymbolicLink()) {
|
|
101
|
-
throw new Error(`attachment staging: staging directory ${stagingDir} is a symlink, refusing to use it`);
|
|
102
|
-
}
|
|
103
|
-
await pruneStagedAttachments(stagingDir, maxAgeMs);
|
|
148
|
+
const uploadRootReal = await resolveUploadRoot(uploadRoot);
|
|
149
|
+
await prepareStagingDir(stagingDir, maxAgeMs);
|
|
104
150
|
// `root` is guaranteed to exist at this point (the recursive mkdir above
|
|
105
151
|
// created it if it didn't already). Resolve its real path once so the
|
|
106
152
|
// "already inside cwd" check below compares like-for-like against
|
|
@@ -109,39 +155,12 @@ export function createFsAttachmentStaging({ cwd }, options = {}) {
|
|
|
109
155
|
// prefix (e.g. macOS's /tmp -> /private/tmp, /var -> /private/var),
|
|
110
156
|
// causing an unnecessary copy instead of returning the path as-is.
|
|
111
157
|
const rootReal = await fs.promises.realpath(root).catch(() => root);
|
|
158
|
+
const ctx = { rootReal, uploadRootReal, stagingDir, maxBytesPerFile };
|
|
112
159
|
const staged = [];
|
|
113
160
|
for (const inputPath of imagePaths) {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
const resolved = path.resolve(inputPath);
|
|
118
|
-
const real = await fs.promises.realpath(resolved);
|
|
119
|
-
const stat = await fs.promises.stat(real);
|
|
120
|
-
if (!stat.isFile())
|
|
121
|
-
continue;
|
|
122
|
-
if (isWithinRoot(rootReal, real)) {
|
|
123
|
-
staged.push(real);
|
|
124
|
-
continue;
|
|
125
|
-
}
|
|
126
|
-
// Outside cwd: this is the "copy an external file into staging"
|
|
127
|
-
// path, which requires an authorized uploadRoot — deny by default.
|
|
128
|
-
if (uploadRootReal == null) {
|
|
129
|
-
throw new MissingUploadRootError('attachment staging: files outside cwd require an uploadRoot');
|
|
130
|
-
}
|
|
131
|
-
if (!isWithinRoot(uploadRootReal, real))
|
|
132
|
-
continue;
|
|
133
|
-
if (stat.size > maxBytesPerFile)
|
|
134
|
-
continue;
|
|
135
|
-
const basename = path.basename(real);
|
|
136
|
-
const destination = path.join(stagingDir, `${randomUUID()}-${basename}`);
|
|
137
|
-
await fs.promises.copyFile(real, destination);
|
|
138
|
-
staged.push(destination);
|
|
139
|
-
}
|
|
140
|
-
catch (error) {
|
|
141
|
-
if (error instanceof MissingUploadRootError)
|
|
142
|
-
throw error;
|
|
143
|
-
// Ignore malformed or missing files; attachments are advisory input.
|
|
144
|
-
}
|
|
161
|
+
const result = await stageOneAdvisory(inputPath, ctx);
|
|
162
|
+
if (result !== null)
|
|
163
|
+
staged.push(result);
|
|
145
164
|
}
|
|
146
165
|
return staged;
|
|
147
166
|
},
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Storage-agnostic `MediaTask` lifecycle rules shared by every
|
|
3
|
+
* `MediaTaskStore` adapter (`createInMemoryMediaTaskStore` in
|
|
4
|
+
* `task-store.ts`, `createSqliteMediaTaskStore` in `sqlite-task-store.ts`).
|
|
5
|
+
* Each adapter used to carry its own copy of the status sets, the
|
|
6
|
+
* transition graph and the create/patch/reconcile row arithmetic; keeping a
|
|
7
|
+
* single copy here means the two adapters cannot drift apart. Internal to
|
|
8
|
+
* the package (not re-exported from the barrel).
|
|
9
|
+
*/
|
|
10
|
+
import type { MediaTask, MediaTaskCreateInput, MediaTaskPatch, MediaTaskStatus } from './task-store.js';
|
|
11
|
+
export declare const TERMINAL_STATUSES: ReadonlySet<MediaTaskStatus>;
|
|
12
|
+
/** Builds the stored row for `create()`; the caller checks for a duplicate id first. */
|
|
13
|
+
export declare function buildNewTask(input: MediaTaskCreateInput, now: number): MediaTask;
|
|
14
|
+
/** Validates `patch` against `existing` (status enum, then transition graph) and returns the next stored row. */
|
|
15
|
+
export declare function applyTaskPatch(existing: MediaTask, patch: MediaTaskPatch, now: number): MediaTask;
|
|
16
|
+
export declare function assertValidTerminalTtl(terminalTtlMs: number): void;
|
|
17
|
+
/** What boot-time reconciliation does to one stored task. */
|
|
18
|
+
export type ReconcileAction = {
|
|
19
|
+
readonly kind: 'interrupt';
|
|
20
|
+
readonly next: MediaTask;
|
|
21
|
+
} | {
|
|
22
|
+
readonly kind: 'delete';
|
|
23
|
+
} | {
|
|
24
|
+
readonly kind: 'keep';
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* A restart mid-flight has no way to resume a `queued`/`running` task, so it
|
|
28
|
+
* becomes `interrupted` (keeping an already-set `endedAt`); a terminal task
|
|
29
|
+
* whose `endedAt` (or, failing that, `updatedAt`) is older than `cutoff` is
|
|
30
|
+
* deleted. A task interrupted in this pass is never also deleted in it.
|
|
31
|
+
*/
|
|
32
|
+
export declare function reconcileAction(task: MediaTask, now: number, cutoff: number): ReconcileAction;
|
|
33
|
+
//# sourceMappingURL=task-lifecycle.d.ts.map
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// CR-013: `assertValidStatus` alone only proves enum membership, not that a
|
|
2
|
+
// transition is legal — it allowed e.g. `done` -> `running`. This is the
|
|
3
|
+
// actual lifecycle graph the store's own docs claim
|
|
4
|
+
// (queued -> running -> done|failed|interrupted); same-state is included so
|
|
5
|
+
// a caller can `update()` progress/file without also having to re-derive the
|
|
6
|
+
// current status, but nothing can leave a terminal state once reached.
|
|
7
|
+
const ALLOWED_TRANSITIONS = {
|
|
8
|
+
// `queued` may go straight to a terminal state too (a caller isn't
|
|
9
|
+
// required to make a separate "now running" update before finishing).
|
|
10
|
+
queued: new Set(['queued', 'running', 'done', 'failed', 'interrupted']),
|
|
11
|
+
running: new Set(['running', 'done', 'failed', 'interrupted']),
|
|
12
|
+
done: new Set(['done']),
|
|
13
|
+
failed: new Set(['failed']),
|
|
14
|
+
interrupted: new Set(['interrupted']),
|
|
15
|
+
};
|
|
16
|
+
const VALID_STATUSES = new Set(Object.keys(ALLOWED_TRANSITIONS));
|
|
17
|
+
export const TERMINAL_STATUSES = new Set(['done', 'failed', 'interrupted']);
|
|
18
|
+
const INTERRUPTED_ERROR = {
|
|
19
|
+
message: 'media task interrupted by daemon restart',
|
|
20
|
+
code: 'DAEMON_RESTART',
|
|
21
|
+
};
|
|
22
|
+
function assertValidStatus(status) {
|
|
23
|
+
if (!VALID_STATUSES.has(status)) {
|
|
24
|
+
throw new RangeError(`Invalid media task status: "${status}"`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function snapshotFile(file) {
|
|
28
|
+
return file == null ? null : structuredClone(file);
|
|
29
|
+
}
|
|
30
|
+
function snapshotError(error) {
|
|
31
|
+
return error == null ? null : { ...error };
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* `surface`/`model` are conditionally spread — this package's
|
|
35
|
+
* `exactOptionalPropertyTypes: true` tsconfig rejects assigning `undefined`
|
|
36
|
+
* to an optional field, so a task without a `surface`/`model` has no key at
|
|
37
|
+
* all, not a key set to `undefined`.
|
|
38
|
+
*/
|
|
39
|
+
function labelFields(surface, model) {
|
|
40
|
+
return {
|
|
41
|
+
...(surface !== undefined ? { surface } : {}),
|
|
42
|
+
...(model !== undefined ? { model } : {}),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** Builds the stored row for `create()`; the caller checks for a duplicate id first. */
|
|
46
|
+
export function buildNewTask(input, now) {
|
|
47
|
+
const status = input.status ?? 'queued';
|
|
48
|
+
assertValidStatus(status);
|
|
49
|
+
return {
|
|
50
|
+
id: input.id,
|
|
51
|
+
ownerRef: input.ownerRef,
|
|
52
|
+
status,
|
|
53
|
+
progress: input.progress ? [...input.progress] : [],
|
|
54
|
+
file: snapshotFile(input.file),
|
|
55
|
+
error: snapshotError(input.error),
|
|
56
|
+
startedAt: input.startedAt ?? now,
|
|
57
|
+
endedAt: null,
|
|
58
|
+
createdAt: now,
|
|
59
|
+
updatedAt: now,
|
|
60
|
+
...labelFields(input.surface, input.model),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/** A key present in the patch (even as `null`/`undefined`) replaces the stored value; an absent key keeps it. */
|
|
64
|
+
function patchedLabels(existing, patch) {
|
|
65
|
+
const surface = 'surface' in patch ? (patch.surface ?? undefined) : existing.surface;
|
|
66
|
+
const model = 'model' in patch ? (patch.model ?? undefined) : existing.model;
|
|
67
|
+
return labelFields(surface, model);
|
|
68
|
+
}
|
|
69
|
+
function patchedPayload(existing, patch) {
|
|
70
|
+
return {
|
|
71
|
+
progress: patch.progress ? [...patch.progress] : existing.progress,
|
|
72
|
+
file: 'file' in patch ? snapshotFile(patch.file) : existing.file,
|
|
73
|
+
error: 'error' in patch ? snapshotError(patch.error) : existing.error,
|
|
74
|
+
endedAt: 'endedAt' in patch ? (patch.endedAt ?? null) : existing.endedAt,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/** Validates `patch` against `existing` (status enum, then transition graph) and returns the next stored row. */
|
|
78
|
+
export function applyTaskPatch(existing, patch, now) {
|
|
79
|
+
const status = patch.status ?? existing.status;
|
|
80
|
+
assertValidStatus(status);
|
|
81
|
+
// CR-013: enum membership alone doesn't prove the transition is legal
|
|
82
|
+
// (e.g. `done` -> `running`) — check the actual lifecycle graph too.
|
|
83
|
+
if (!ALLOWED_TRANSITIONS[existing.status].has(status)) {
|
|
84
|
+
throw new RangeError(`Invalid media task transition: "${existing.status}" -> "${status}"`);
|
|
85
|
+
}
|
|
86
|
+
const payload = patchedPayload(existing, patch);
|
|
87
|
+
return {
|
|
88
|
+
id: existing.id,
|
|
89
|
+
ownerRef: existing.ownerRef,
|
|
90
|
+
status,
|
|
91
|
+
progress: payload.progress,
|
|
92
|
+
file: payload.file,
|
|
93
|
+
error: payload.error,
|
|
94
|
+
startedAt: existing.startedAt,
|
|
95
|
+
endedAt: payload.endedAt,
|
|
96
|
+
createdAt: existing.createdAt,
|
|
97
|
+
updatedAt: now,
|
|
98
|
+
...patchedLabels(existing, patch),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
export function assertValidTerminalTtl(terminalTtlMs) {
|
|
102
|
+
if (!Number.isFinite(terminalTtlMs) || terminalTtlMs < 0) {
|
|
103
|
+
throw new RangeError(`Invalid terminalTtlMs: ${terminalTtlMs} must be a non-negative finite number`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* A restart mid-flight has no way to resume a `queued`/`running` task, so it
|
|
108
|
+
* becomes `interrupted` (keeping an already-set `endedAt`); a terminal task
|
|
109
|
+
* whose `endedAt` (or, failing that, `updatedAt`) is older than `cutoff` is
|
|
110
|
+
* deleted. A task interrupted in this pass is never also deleted in it.
|
|
111
|
+
*/
|
|
112
|
+
export function reconcileAction(task, now, cutoff) {
|
|
113
|
+
if (task.status === 'queued' || task.status === 'running') {
|
|
114
|
+
return {
|
|
115
|
+
kind: 'interrupt',
|
|
116
|
+
next: { ...task, status: 'interrupted', error: INTERRUPTED_ERROR, endedAt: task.endedAt ?? now, updatedAt: now },
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
if (TERMINAL_STATUSES.has(task.status) && (task.endedAt ?? task.updatedAt) < cutoff) {
|
|
120
|
+
return { kind: 'delete' };
|
|
121
|
+
}
|
|
122
|
+
return { kind: 'keep' };
|
|
123
|
+
}
|
|
124
|
+
//# sourceMappingURL=task-lifecycle.js.map
|