@crewx/sdk 0.9.0-rc.130 → 0.9.0-rc.131

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.
@@ -16,6 +16,7 @@ export interface ExternalResourceFinding {
16
16
  export interface InspectSkillBackendOutputOptions {
17
17
  readonly actionId: string;
18
18
  readonly dataPaths?: readonly string[];
19
+ readonly resultProjectionAllow?: readonly string[];
19
20
  readonly durationMs?: number;
20
21
  readonly timedOut?: boolean;
21
22
  readonly contentFramed?: boolean;
@@ -1,6 +1,7 @@
1
1
  import type { UiDefinitionLineageEntry } from '../ui-instance/lineage.js';
2
2
  import type { JsonObject, UiDefinition } from '../ui-instance/types.js';
3
3
  import type { UiPluginHandlerMetadata, UiPluginManifestV2, UiPluginNormalizedManifestV2 } from '../ui-plugin/types.js';
4
+ import { createWorkspaceAppScanCache, type WorkspaceAppScanCache, type WorkspaceAppScanRootIdentity } from './workspace-app-scan-cache.js';
4
5
  import { AppDiscoveryFsError, NodeAppDiscoveryFs, NodeAppDiscoveryFsAdapter, defaultAppDiscoveryFs, defaultNodeAppDiscoveryFs, type AppDiscoveryFsErrorCode } from './node-app-discovery-fs.js';
5
6
  import type { McpAppRegistry } from './types.js';
6
7
  import type { ProductAppBundleFileHash, ProductAppBundleInput, ProductAppBundleProvenance as LoadedProductAppBundleProvenance } from './product-bundle-loader.js';
@@ -17,7 +18,7 @@ export interface ProductAppBundleProvenance extends LoadedProductAppBundleProven
17
18
  readonly files: readonly ProductAppBundleFileHash[];
18
19
  }
19
20
  export type WorkspaceAppDiscoveryIncompleteReason = 'time_limit';
20
- export type WorkspaceAppDiagnosticCode = 'MANIFEST_MISSING' | 'MANIFEST_INVALID' | 'ENTRY_INVALID' | 'INITIAL_STATE_INVALID' | 'DUPLICATE_ID' | 'RESERVED_ID' | 'BUNDLE_INTEGRITY' | 'LINEAGE_INVALID' | 'LINEAGE_STALE' | 'PATH_ESCAPED' | 'LIMIT_EXCEEDED' | 'ASSET_CATALOG_INVALID' | 'EXEC_DENIED';
21
+ export type WorkspaceAppDiagnosticCode = 'MANIFEST_MISSING' | 'MANIFEST_INVALID' | 'ENTRY_INVALID' | 'INITIAL_STATE_INVALID' | 'DUPLICATE_ID' | 'RESERVED_ID' | 'BUNDLE_INTEGRITY' | 'LINEAGE_INVALID' | 'LINEAGE_STALE' | 'PATH_ESCAPED' | 'LIMIT_EXCEEDED' | 'DISCOVERY_TIME_LIMIT' | 'ASSET_CATALOG_INVALID' | 'EXEC_DENIED';
21
22
  export interface WorkspaceAppDiagnostic {
22
23
  readonly code: WorkspaceAppDiagnosticCode;
23
24
  readonly pluginId?: string;
@@ -37,6 +38,16 @@ export interface AppDiscoveryDirectoryEntry {
37
38
  readonly name: string;
38
39
  readonly kind: AppDiscoveryDirectoryEntryKind;
39
40
  }
41
+ export interface AppDiscoveryFileFingerprint {
42
+ readonly dev: bigint;
43
+ readonly ino: bigint;
44
+ readonly size: bigint;
45
+ readonly mtimeNs: bigint;
46
+ readonly ctimeNs: bigint;
47
+ readonly candidateRealPath: string;
48
+ }
49
+ export interface AppDiscoveryRootIdentity extends WorkspaceAppScanRootIdentity {
50
+ }
40
51
  export type AppDiscoveryDirectoryListing = readonly AppDiscoveryDirectoryEntry[] | readonly string[];
41
52
  export type AppDiscoveryBytes = Uint8Array | ArrayBuffer | readonly number[];
42
53
  export type AppDiscoveryMaybePromise<T> = T | PromiseLike<T>;
@@ -46,6 +57,8 @@ export interface AppDiscoveryFileSystem {
46
57
  readonly readdir?: (root: string, relativePath: string) => AppDiscoveryMaybePromise<AppDiscoveryDirectoryListing>;
47
58
  readonly readVerifiedFile?: (root: string, relativePath: string, byteLimit: number) => AppDiscoveryMaybePromise<AppDiscoveryBytes>;
48
59
  readonly readFileVerified?: (root: string, relativePath: string, byteLimit: number) => AppDiscoveryMaybePromise<AppDiscoveryBytes>;
60
+ readonly fingerprintVerifiedFile?: (root: string, relativePath: string, byteLimit: number) => AppDiscoveryMaybePromise<AppDiscoveryFileFingerprint>;
61
+ readonly getRootIdentity?: (root: string) => AppDiscoveryMaybePromise<AppDiscoveryRootIdentity>;
49
62
  }
50
63
  export interface WorkspaceAppReservedCatalog {
51
64
  readonly appIds?: Iterable<string>;
@@ -66,6 +79,7 @@ export interface WorkspaceAppDiscoveryOptions {
66
79
  readonly reservedDefinitionIds?: Iterable<string>;
67
80
  readonly reservedToolNames?: Iterable<string>;
68
81
  readonly productBundle?: ProductAppBundleInput;
82
+ readonly scanCache?: WorkspaceAppScanCache;
69
83
  }
70
84
  export interface WorkspaceAppToolNames {
71
85
  readonly read: string;
@@ -135,5 +149,5 @@ export declare function discoverWorkspaceApps(workspaceRoot: string, fs?: AppDis
135
149
  export declare function discoverWorkspaceApps(workspaceRoot: string, options?: WorkspaceAppDiscoveryOptions): Promise<WorkspaceAppDiscoveryResult>;
136
150
  export declare const discoverWorkspaceAppCandidates: typeof discoverWorkspaceApps;
137
151
  export declare const scanWorkspaceApps: typeof discoverWorkspaceApps;
138
- export { AppDiscoveryFsError, NodeAppDiscoveryFs, NodeAppDiscoveryFsAdapter, defaultAppDiscoveryFs, defaultNodeAppDiscoveryFs, };
139
- export type { AppDiscoveryFsErrorCode };
152
+ export { AppDiscoveryFsError, NodeAppDiscoveryFs, NodeAppDiscoveryFsAdapter, defaultAppDiscoveryFs, defaultNodeAppDiscoveryFs, createWorkspaceAppScanCache, };
153
+ export type { AppDiscoveryFsErrorCode, WorkspaceAppScanCache, };
@@ -3,11 +3,11 @@ export { McpAppContractError } from './errors.js';
3
3
  export { INSTALLED_APP_ENTRY, InstalledAppRefError, buildInstalledAppRef, validateInstalledAppRef, } from './installed-app-ref.js';
4
4
  export type { BuildInstalledAppRefInput, InstalledAppPackageFile, InstalledAppRef, InstalledAppRefErrorCode, } from './installed-app-ref.js';
5
5
  export { MAX_HTML_LENGTH, createMcpAppRegistry, createBuiltinMcpAppRegistry, buildMcpAppLocalRegistration, createMcpAppLocalRegistration, registerLocalMcpApp, createMcpAppWorkspaceRegistry, createWorkspaceAppRegistry, createWorkspaceMcpAppRegistry, registerMcpApp, resolveMcpAppResource, resolveLocalMcpAppResource, requireMcpAppResource, toMcpAppToolRegistration, makeUiUri, buildMcpAppBundleRegistrationInput, buildMcpAppBundleAgentActionDescriptors, planProductBundleLegacyToolNames, resolveMcpAppFixedResultCall, } from './registry.js';
6
- export { AppDiscoveryFsError, NodeAppDiscoveryFs, NodeAppDiscoveryFsAdapter, defaultAppDiscoveryFs, defaultNodeAppDiscoveryFs, deriveWorkspaceAppToolName, deriveWorkspaceAppToolNames, discoverWorkspaceAppCandidates, discoverWorkspaceApps, LOCAL_APP_TOOL_PREFIX, MCP_APP_WORKSPACE_TOOL_PREFIX, productAppBundleReservations, scanWorkspaceApps, WORKSPACE_APP_TOOL_PREFIX, } from './discovery.js';
6
+ export { AppDiscoveryFsError, NodeAppDiscoveryFs, NodeAppDiscoveryFsAdapter, defaultAppDiscoveryFs, defaultNodeAppDiscoveryFs, createWorkspaceAppScanCache, deriveWorkspaceAppToolName, deriveWorkspaceAppToolNames, discoverWorkspaceAppCandidates, discoverWorkspaceApps, LOCAL_APP_TOOL_PREFIX, MCP_APP_WORKSPACE_TOOL_PREFIX, productAppBundleReservations, scanWorkspaceApps, WORKSPACE_APP_TOOL_PREFIX, } from './discovery.js';
7
7
  export { loadProductAppBundleAssets } from './product-bundle-assets.js';
8
8
  export type { ProductAppBundleAsset, ProductAppBundleAssetCatalog, ProductAppBundleAssetLoadOptions, } from './product-bundle-assets.js';
9
9
  export type { WorkspaceAppAsset, WorkspaceAppAssetCatalog, WorkspaceAppAssetDescriptorV1, WorkspaceAppAssetLocator, } from './workspace-app-assets.js';
10
- export type { AppDiscoveryBytes, AppDiscoveryDiagnostic, AppDiscoveryDirectoryEntry, AppDiscoveryDirectoryEntryKind, AppDiscoveryDirectoryListing, AppDiscoveryFileSystem, AppDiscoveryFsErrorCode, AppDiscoveryMaybePromise, WorkspaceAppDiscoveryOptions as AppDiscoveryOptions, McpAppDiscoveryDiagnostic, WorkspaceAppBuiltinCatalog, WorkspaceAppCandidate, WorkspaceAppDiscoveryIncompleteReason, WorkspaceAppDiscoveryOptions, WorkspaceAppDiscoveryResult, WorkspaceAppDiagnostic, WorkspaceAppDiagnosticCode, WorkspaceAppDiscoverySource, WorkspaceAppResourceSnapshot, WorkspaceAppReservedCatalog, WorkspaceAppSource, WorkspaceAppToolNames, ProductAppBundleDefinitionIdentity, ProductAppBundleFileHash, ProductAppBundleIndex, ProductAppBundleInput, ProductAppBundlePackageIndex, ProductAppBundleReservations, ProductAppBundleProvenance, ProductAppBundleSnapshotMetadata, } from './discovery.js';
10
+ export type { AppDiscoveryBytes, AppDiscoveryDiagnostic, AppDiscoveryDirectoryEntry, AppDiscoveryDirectoryEntryKind, AppDiscoveryDirectoryListing, AppDiscoveryFileSystem, AppDiscoveryFileFingerprint, AppDiscoveryFsErrorCode, AppDiscoveryMaybePromise, AppDiscoveryRootIdentity, WorkspaceAppDiscoveryOptions as AppDiscoveryOptions, McpAppDiscoveryDiagnostic, WorkspaceAppBuiltinCatalog, WorkspaceAppCandidate, WorkspaceAppDiscoveryIncompleteReason, WorkspaceAppDiscoveryOptions, WorkspaceAppDiscoveryResult, WorkspaceAppDiagnostic, WorkspaceAppDiagnosticCode, WorkspaceAppDiscoverySource, WorkspaceAppResourceSnapshot, WorkspaceAppScanCache, WorkspaceAppReservedCatalog, WorkspaceAppSource, WorkspaceAppToolNames, ProductAppBundleDefinitionIdentity, ProductAppBundleFileHash, ProductAppBundleIndex, ProductAppBundleInput, ProductAppBundlePackageIndex, ProductAppBundleReservations, ProductAppBundleProvenance, ProductAppBundleSnapshotMetadata, } from './discovery.js';
11
11
  export { createWorkspaceAppCatalog, discoverWorkspaceAppCatalog, hashAppDefinition, hashCrewxAppDefinition, listWorkspaceApps, } from './catalog.js';
12
12
  export type { CrewxAppBuiltinCatalog, CrewxAppCapability, CrewxAppCatalogOptions, CrewxAppCatalogResult, CrewxAppDefinitionHashInput, CrewxAppDefinitionSummary, CrewxAppDiagnostic, CrewxAppDiagnosticCode, CrewxAppDiagnosticSource, CrewxAppInstalledProjection, CrewxAppLocalDefinitionRef, CrewxAppOrigin, CrewxAppOwnership, CrewxAppShareability, CrewxAppSharingAvailability, CrewxAppSummary, } from './types.js';
13
13
  export { MCP_APP_PROJECTION_MAX_BYTES, buildMcpAppStateDescriptor, buildMcpAppStateProjections, createMcpAppToolResult, projectMcpAppSummaryState, serializeMcpAppStateJson, serializeMcpAppStateXml, } from './projection.js';
@@ -3,6 +3,7 @@ export declare const MCP_APP_MODEL_CONTEXT_MAX_BYTES: number;
3
3
  export declare const MCP_APP_MODEL_CONTEXT_MAX_STRING_LENGTH = 2048;
4
4
  export declare const MCP_APP_MODEL_CONTEXT_MAX_ARRAY_LENGTH = 200;
5
5
  export declare const MCP_APP_MODEL_CONTEXT_MAX_DEPTH = 8;
6
+ export declare const MCP_APP_ACTION_RESULT_MAX_BYTES: number;
6
7
  export interface McpAppModelContextInput {
7
8
  readonly instanceId: string;
8
9
  readonly definitionHash: string;
@@ -20,6 +21,8 @@ export interface McpAppModelContext {
20
21
  }[];
21
22
  readonly structuredContent?: JsonObject;
22
23
  }
24
+ export declare function sanitizeMcpAppActionResult(value: unknown): JsonObject;
25
+ export declare function prepareMcpAppActionResult(value: unknown, selectedAllow: readonly string[]): JsonObject;
23
26
  export declare function sanitizeMcpAppModelContext(value: unknown): McpAppModelContext;
24
27
  export declare function serializeMcpAppModelContextXml(context: McpAppModelContext, options?: {
25
28
  readonly stale?: boolean;
@@ -1,3 +1,4 @@
1
+ import type { AppDiscoveryFileFingerprint, AppDiscoveryRootIdentity } from './discovery.js';
1
2
  export type AppDiscoveryFsErrorCode = 'NOT_FOUND' | 'READ_DENIED' | 'LIMIT_EXCEEDED' | 'PATH_ESCAPED' | 'IDENTITY_CHANGED' | 'TOCTOU' | 'UNSUPPORTED';
2
3
  export declare class AppDiscoveryFsError extends Error {
3
4
  readonly code: AppDiscoveryFsErrorCode;
@@ -9,10 +10,12 @@ export interface NodeAppDiscoveryDirectoryEntry {
9
10
  readonly kind: 'file' | 'directory' | 'symlink' | 'other';
10
11
  }
11
12
  export declare class NodeAppDiscoveryFs {
13
+ getRootIdentity(root: string): Promise<AppDiscoveryRootIdentity>;
12
14
  listDirectory(root: string, relativePath: string): Promise<readonly NodeAppDiscoveryDirectoryEntry[]>;
13
15
  readdir(root: string, relativePath: string): Promise<readonly NodeAppDiscoveryDirectoryEntry[]>;
14
16
  readDirectory(root: string, relativePath: string): Promise<readonly NodeAppDiscoveryDirectoryEntry[]>;
15
17
  readVerifiedFile(root: string, relativePath: string, byteLimit: number): Promise<Uint8Array>;
18
+ fingerprintVerifiedFile(root: string, relativePath: string, byteLimit: number): Promise<AppDiscoveryFileFingerprint>;
16
19
  readFileVerified(root: string, relativePath: string, byteLimit: number): Promise<Uint8Array>;
17
20
  }
18
21
  export declare const defaultAppDiscoveryFs: NodeAppDiscoveryFs;
@@ -2,6 +2,7 @@ import type { JsonObject, UiDefinition } from '../ui-instance/types.js';
2
2
  import type { McpAppServerStateInput, McpAppStateDescriptor, McpAppStateProjections, McpAppToolDescriptor, McpAppToolResult } from './types.js';
3
3
  export declare const MCP_APP_PROJECTION_MAX_BYTES: number;
4
4
  export declare const SENSITIVE_KEY: RegExp;
5
+ export declare function projectMcpAppActionResult(result: unknown, selectedAllow: readonly string[]): JsonObject;
5
6
  export declare function projectMcpAppSummaryState(state: unknown, definition: UiDefinition): JsonObject;
6
7
  export declare function buildMcpAppStateDescriptor(input: McpAppServerStateInput): McpAppStateDescriptor;
7
8
  export declare function serializeMcpAppStateJson(descriptor: McpAppStateDescriptor, dataPaths?: readonly string[]): string;
@@ -426,7 +426,7 @@ export interface CrewxAppSummary {
426
426
  readonly definitionHash: string;
427
427
  readonly provenance?: ProductAppBundleProvenance;
428
428
  }
429
- export type CrewxAppDiagnosticCode = 'MANIFEST_MISSING' | 'MANIFEST_INVALID' | 'ENTRY_INVALID' | 'INITIAL_STATE_INVALID' | 'DUPLICATE_ID' | 'RESERVED_ID' | 'BUNDLE_INTEGRITY' | 'LINEAGE_INVALID' | 'LINEAGE_STALE' | 'PATH_ESCAPED' | 'LIMIT_EXCEEDED' | 'ASSET_CATALOG_INVALID' | 'EXEC_DENIED' | 'SKILL_INVALID' | 'SKILL_READ_FAILED' | 'INSTALLED_MISSING' | 'INSTALLED_CONTENT_ID_MISSING' | 'INSTALLED_IDENTITY_MISMATCH' | 'BUILTIN_INVALID';
429
+ export type CrewxAppDiagnosticCode = 'MANIFEST_MISSING' | 'MANIFEST_INVALID' | 'ENTRY_INVALID' | 'INITIAL_STATE_INVALID' | 'DUPLICATE_ID' | 'RESERVED_ID' | 'BUNDLE_INTEGRITY' | 'LINEAGE_INVALID' | 'LINEAGE_STALE' | 'PATH_ESCAPED' | 'LIMIT_EXCEEDED' | 'DISCOVERY_TIME_LIMIT' | 'ASSET_CATALOG_INVALID' | 'EXEC_DENIED' | 'SKILL_INVALID' | 'SKILL_READ_FAILED' | 'INSTALLED_MISSING' | 'INSTALLED_CONTENT_ID_MISSING' | 'INSTALLED_IDENTITY_MISMATCH' | 'BUILTIN_INVALID';
430
430
  export type CrewxAppDiagnosticSource = 'apps' | 'skills' | 'bundled' | 'node_modules' | 'builtin' | 'installed';
431
431
  export interface CrewxAppDiagnostic {
432
432
  readonly code: CrewxAppDiagnosticCode;
@@ -1,4 +1,5 @@
1
1
  import type { AppDiscoveryFileSystem, WorkspaceAppCandidate, WorkspaceAppDiagnostic, WorkspaceAppSource } from './discovery.js';
2
+ import { type WorkspaceAppScanCache } from './workspace-app-scan-cache.js';
2
3
  import { type ProductAppBundleAsset } from './product-bundle-assets.js';
3
4
  export interface WorkspaceAppAssetLocator {
4
5
  readonly role: string;
@@ -34,5 +35,8 @@ export interface WorkspaceAppAssetCatalogLoadResult {
34
35
  readonly catalogs: readonly WorkspaceAppAssetCatalogDraft[];
35
36
  readonly diagnostics: readonly WorkspaceAppDiagnostic[];
36
37
  }
37
- export declare function loadWorkspaceAppAssetCatalogs(workspaceRoot: string, candidates: readonly WorkspaceAppCandidate[], filesystem?: AppDiscoveryFileSystem): Promise<WorkspaceAppAssetCatalogLoadResult>;
38
+ export declare function loadWorkspaceAppAssetCatalogs(workspaceRoot: string, candidates: readonly WorkspaceAppCandidate[], filesystem?: AppDiscoveryFileSystem, options?: {
39
+ readonly scanCache?: WorkspaceAppScanCache;
40
+ readonly candidateScanWasUnchanged?: boolean;
41
+ }): Promise<WorkspaceAppAssetCatalogLoadResult>;
38
42
  export declare function sealWorkspaceAppAssetCatalog(draft: WorkspaceAppAssetCatalogDraft, snapshotHash: string): WorkspaceAppAssetCatalog;
@@ -0,0 +1,24 @@
1
+ export interface WorkspaceAppScanRootIdentity {
2
+ readonly dev: bigint;
3
+ readonly ino: bigint;
4
+ readonly realPath: string;
5
+ }
6
+ interface WorkspaceAppScanCacheState {
7
+ rootIdentity?: WorkspaceAppScanRootIdentity;
8
+ lastCandidateScanUnchanged?: boolean;
9
+ lastCandidateKeys?: readonly string[];
10
+ scanStartedAtNs?: bigint;
11
+ lastAssetCatalogsUnchanged?: boolean;
12
+ lastSnapshot?: unknown;
13
+ lastSnapshotBuildInputs?: readonly unknown[];
14
+ readonly candidates: Map<string, unknown>;
15
+ readonly assetCatalogs: Map<string, unknown>;
16
+ }
17
+ declare const CACHE_STATE: unique symbol;
18
+ export interface WorkspaceAppScanCache {
19
+ readonly [CACHE_STATE]: WorkspaceAppScanCacheState;
20
+ }
21
+ export declare function createWorkspaceAppScanCache(): WorkspaceAppScanCache;
22
+ export declare function workspaceAppScanCacheState(cache: WorkspaceAppScanCache): WorkspaceAppScanCacheState;
23
+ export declare function resetWorkspaceAppScanCacheForRoot(cache: WorkspaceAppScanCache, identity: WorkspaceAppScanRootIdentity): WorkspaceAppScanCacheState;
24
+ export {};
@@ -144,7 +144,7 @@ ${r.join(`
144
144
  THEN COALESCE(t.cached_input_tokens, 0)
145
145
  ELSE 0
146
146
  END
147
- `,c=r?drizzleOrm.sql`WHERE ${i} AND t.started_at >= ${e} AND t.started_at < ${n} AND t.workspace_id = ${r}`:drizzleOrm.sql`WHERE ${i} AND t.started_at >= ${e} AND t.started_at < ${n}`,l=s.db.all(drizzleOrm.sql`
147
+ `,c=r?drizzleOrm.sql`WHERE ${i} AND t.started_at >= ${e} AND t.started_at < ${n} AND t.workspace_id = ${r} AND t.agent_id != 'workflow'`:drizzleOrm.sql`WHERE ${i} AND t.started_at >= ${e} AND t.started_at < ${n} AND t.agent_id != 'workflow'`,l=s.db.all(drizzleOrm.sql`
148
148
  SELECT
149
149
  t.agent_id,
150
150
  t.workspace_id,
@@ -184,6 +184,7 @@ ${r.join(`
184
184
  AND t.started_at >= ${e}
185
185
  AND t.started_at < ${n}
186
186
  AND t.workspace_id = ${r}
187
+ AND t.agent_id != 'workflow'
187
188
  GROUP BY date(t.started_at), t.agent_id
188
189
  ORDER BY date(t.started_at) ASC
189
190
  `:drizzleOrm.sql`
@@ -211,6 +212,7 @@ ${r.join(`
211
212
  WHERE ${o}
212
213
  AND t.started_at >= ${e}
213
214
  AND t.started_at < ${n}
215
+ AND t.agent_id != 'workflow'
214
216
  GROUP BY date(t.started_at), t.agent_id
215
217
  ORDER BY date(t.started_at) ASC
216
218
  `).map(d=>({date:d.date,agentId:d.agent_id,unavailableTaskCount:d.unavailable_task_count,inputTokens:d.input_tokens,outputTokens:d.output_tokens,cachedInputTokens:d.cached_input_tokens,costUsd:d.cost_usd,totalTokens:d.input_tokens+d.output_tokens}))}catch(o){throw new g("DB_ERROR","Failed to get agent usage trend",o)}finally{s.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let s=r.db.select().from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.workspace_id,n))).limit(1).get();return s?De(s):void 0}catch(s){throw new g("DB_ERROR","Failed to find task for stop",s)}finally{r.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:a.id,thread_id:a.thread_id,status:a.status,result:a.result,error:a.error,started_at:a.started_at,completed_at:a.completed_at,metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.agent_id,e.agentId),drizzleOrm.eq(a.workspace_id,e.workspaceId),drizzleOrm.sql`${a.metadata} IS NOT NULL AND json_valid(${a.metadata}) AND json_extract(${a.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(drizzleOrm.desc(a.started_at)).limit(1).get()??null}catch(r){throw new g("DB_ERROR","Failed to find latest task by metadata",r)}finally{n.close();}}markTaskFailed(e,n,r,s="failed",o){if(!this.dbExists())return;let i=this.openHandle(true);try{let u=new Date().toISOString(),d=r?drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.workspace_id,r)):drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"running")),c=i.db.select({metadata:a.metadata}).from(a).where(d).limit(1).get();if(!c)return;let l={status:s,error:n,completed_at:u};if(o){let p=ee(c.metadata);p.terminalReason=o,l.metadata=JSON.stringify(p);}i.db.update(a).set(l).where(d).run();}catch(u){throw u instanceof g?u:new g("DB_ERROR","Failed to mark task failed",u)}finally{i.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!fs$1.existsSync(i))continue;let u=U(i);try{let d=n?drizzleOrm.and(drizzleOrm.like(a.prompt,`%${e}%`),drizzleOrm.eq(a.workspace_id,n)):drizzleOrm.like(a.prompt,`%${e}%`),c=u.db.select().from(a).where(d).orderBy(drizzleOrm.asc(a.started_at)).all();for(let l of c)s.has(l.id)||(s.add(l.id),o.push(De(l)));}catch(d){throw new g("DB_ERROR","Failed to find tasks by prompt hint",d)}finally{u.close();}}return o}getProviderUsage(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=Ps(),i=In(a.status),u=fr(a.metadata),d=drizzleOrm.sql`
@@ -343,6 +345,7 @@ Message: ${n.message}
343
345
  SELECT DISTINCT child.agent_id FROM tasks child
344
346
  WHERE child.thread_id = ${e}
345
347
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
348
+ AND child.agent_id != 'workflow'
346
349
  AND ${this.topLevelTaskPredicateSql()}
347
350
  ${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
348
351
  `);for(let _ of m)c.add(_.agent_id);}catch(f){throw new g("DB_ERROR","Failed to aggregate task stats",f)}finally{p.close();}}return {taskCount:s,inputTokens:o,outputTokens:i,cachedInputTokens:u,costUsd:d,agentIds:Array.from(c)}}findTopLevelTasks(e,n,r){let s=this.resolveDbPaths(),o=new Set,i=[];for(let u of s){if(!fs$1.existsSync(u))continue;let d=U(u);try{let c;r!==void 0?c=d.db.all(drizzleOrm.sql`