@harperfast/harper 5.2.0 → 5.2.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/bin/copyDb.ts +21 -4
- package/bin/harper.ts +20 -51
- package/bin/help.ts +216 -0
- package/components/Application.ts +236 -46
- package/components/ApplicationScope.ts +26 -0
- package/components/EntryHandler.ts +410 -105
- package/components/RuntimeModuleTracker.ts +189 -0
- package/components/Scope.ts +68 -24
- package/components/componentLoader.ts +70 -16
- package/components/deployLifecycle.ts +119 -33
- package/components/mcp/tools/operations.ts +6 -0
- package/components/operations.js +4 -6
- package/config/configUtils.ts +12 -9
- package/config-root.schema.json +10 -0
- package/dataLayer/harperBridge/ResourceBridge.ts +26 -5
- package/dataLayer/hdbInfoController.ts +8 -0
- package/dataLayer/schemaDescribe.ts +2 -1
- package/dist/bin/copyDb.js +13 -2
- package/dist/bin/copyDb.js.map +1 -1
- package/dist/bin/harper.d.ts +6 -0
- package/dist/bin/harper.js +18 -50
- package/dist/bin/harper.js.map +1 -1
- package/dist/bin/help.d.ts +8 -0
- package/dist/bin/help.js +192 -0
- package/dist/bin/help.js.map +1 -0
- package/dist/components/Application.d.ts +16 -1
- package/dist/components/Application.js +210 -38
- package/dist/components/Application.js.map +1 -1
- package/dist/components/ApplicationScope.d.ts +7 -0
- package/dist/components/ApplicationScope.js +22 -0
- package/dist/components/ApplicationScope.js.map +1 -1
- package/dist/components/EntryHandler.d.ts +4 -4
- package/dist/components/EntryHandler.js +386 -95
- package/dist/components/EntryHandler.js.map +1 -1
- package/dist/components/RuntimeModuleTracker.d.ts +11 -0
- package/dist/components/RuntimeModuleTracker.js +189 -0
- package/dist/components/RuntimeModuleTracker.js.map +1 -0
- package/dist/components/Scope.d.ts +1 -0
- package/dist/components/Scope.js +69 -22
- package/dist/components/Scope.js.map +1 -1
- package/dist/components/componentLoader.js +69 -10
- package/dist/components/componentLoader.js.map +1 -1
- package/dist/components/deployLifecycle.d.ts +6 -2
- package/dist/components/deployLifecycle.js +109 -31
- package/dist/components/deployLifecycle.js.map +1 -1
- package/dist/components/mcp/tools/operations.js +6 -0
- package/dist/components/mcp/tools/operations.js.map +1 -1
- package/dist/components/operations.js +4 -6
- package/dist/components/operations.js.map +1 -1
- package/dist/config/configUtils.js +13 -9
- package/dist/config/configUtils.js.map +1 -1
- package/dist/dataLayer/harperBridge/ResourceBridge.js +12 -5
- package/dist/dataLayer/harperBridge/ResourceBridge.js.map +1 -1
- package/dist/dataLayer/hdbInfoController.js +4 -0
- package/dist/dataLayer/hdbInfoController.js.map +1 -1
- package/dist/dataLayer/schemaDescribe.js +2 -1
- package/dist/dataLayer/schemaDescribe.js.map +1 -1
- package/dist/resources/DatabaseTransaction.d.ts +55 -0
- package/dist/resources/DatabaseTransaction.js +282 -103
- package/dist/resources/DatabaseTransaction.js.map +1 -1
- package/dist/resources/ResourceInterface.d.ts +8 -2
- package/dist/resources/ResourceInterface.js.map +1 -1
- package/dist/resources/Resources.js +22 -4
- package/dist/resources/Resources.js.map +1 -1
- package/dist/resources/Table.d.ts +6 -5
- package/dist/resources/Table.js +92 -15
- package/dist/resources/Table.js.map +1 -1
- package/dist/resources/analytics/write.js +6 -6
- package/dist/resources/analytics/write.js.map +1 -1
- package/dist/resources/blob.d.ts +0 -1
- package/dist/resources/blob.js +15 -7
- package/dist/resources/blob.js.map +1 -1
- package/dist/resources/databases.d.ts +22 -5
- package/dist/resources/databases.js +118 -9
- package/dist/resources/databases.js.map +1 -1
- package/dist/resources/jsResource.d.ts +4 -26
- package/dist/resources/jsResource.js +5 -59
- package/dist/resources/jsResource.js.map +1 -1
- package/dist/resources/models/Models.d.ts +11 -1
- package/dist/resources/models/Models.js +10 -1
- package/dist/resources/models/Models.js.map +1 -1
- package/dist/resources/models/backendRegistry.d.ts +9 -0
- package/dist/resources/models/backendRegistry.js +10 -0
- package/dist/resources/models/backendRegistry.js.map +1 -1
- package/dist/resources/models/openaiStream.d.ts +16 -1
- package/dist/resources/models/openaiStream.js +113 -21
- package/dist/resources/models/openaiStream.js.map +1 -1
- package/dist/resources/models/v1/chatCompletions.d.ts +54 -0
- package/dist/resources/models/v1/chatCompletions.js +115 -0
- package/dist/resources/models/v1/chatCompletions.js.map +1 -0
- package/dist/resources/models/v1/embeddings.d.ts +11 -0
- package/dist/resources/models/v1/embeddings.js +71 -0
- package/dist/resources/models/v1/embeddings.js.map +1 -0
- package/dist/resources/models/v1/errors.d.ts +54 -0
- package/dist/resources/models/v1/errors.js +130 -0
- package/dist/resources/models/v1/errors.js.map +1 -0
- package/dist/resources/models/v1/index.d.ts +36 -0
- package/dist/resources/models/v1/index.js +75 -0
- package/dist/resources/models/v1/index.js.map +1 -0
- package/dist/resources/models/v1/models.d.ts +26 -0
- package/dist/resources/models/v1/models.js +44 -0
- package/dist/resources/models/v1/models.js.map +1 -0
- package/dist/resources/models/v1/translation.d.ts +133 -0
- package/dist/resources/models/v1/translation.js +298 -0
- package/dist/resources/models/v1/translation.js.map +1 -0
- package/dist/resources/roles.d.ts +1 -1
- package/dist/resources/roles.js +54 -7
- package/dist/resources/roles.js.map +1 -1
- package/dist/security/jsLoader.js +84 -33
- package/dist/security/jsLoader.js.map +1 -1
- package/dist/security/role.js +4 -0
- package/dist/security/role.js.map +1 -1
- package/dist/security/superUserGuard.d.ts +7 -0
- package/dist/security/superUserGuard.js +23 -0
- package/dist/security/superUserGuard.js.map +1 -0
- package/dist/security/tokenAuthentication.d.ts +0 -1
- package/dist/security/tokenAuthentication.js +6 -2
- package/dist/security/tokenAuthentication.js.map +1 -1
- package/dist/security/user.d.ts +6 -1
- package/dist/security/user.js +23 -1
- package/dist/security/user.js.map +1 -1
- package/dist/server/http.d.ts +23 -2
- package/dist/server/http.js +99 -12
- package/dist/server/http.js.map +1 -1
- package/dist/server/operationsServer.d.ts +0 -2
- package/dist/server/operationsServer.js.map +1 -1
- package/dist/server/serverHelpers/multipartParser.js +9 -0
- package/dist/server/serverHelpers/multipartParser.js.map +1 -1
- package/dist/server/serverHelpers/operationAuthorizationState.d.ts +2 -0
- package/dist/server/serverHelpers/operationAuthorizationState.js +13 -0
- package/dist/server/serverHelpers/operationAuthorizationState.js.map +1 -0
- package/dist/server/serverHelpers/registeredOperations.d.ts +3 -2
- package/dist/server/serverHelpers/registeredOperations.js +14 -13
- package/dist/server/serverHelpers/registeredOperations.js.map +1 -1
- package/dist/server/serverHelpers/serverHandlers.js +19 -3
- package/dist/server/serverHelpers/serverHandlers.js.map +1 -1
- package/dist/server/serverHelpers/serverUtilities.d.ts +1 -1
- package/dist/server/serverHelpers/serverUtilities.js +10 -7
- package/dist/server/serverHelpers/serverUtilities.js.map +1 -1
- package/dist/server/static.js +57 -18
- package/dist/server/static.js.map +1 -1
- package/dist/server/storageReclamation.d.ts +17 -0
- package/dist/server/storageReclamation.js +90 -6
- package/dist/server/storageReclamation.js.map +1 -1
- package/dist/server/threads/socketRouter.js +20 -0
- package/dist/server/threads/socketRouter.js.map +1 -1
- package/dist/server/threads/threadServer.js +12 -0
- package/dist/server/threads/threadServer.js.map +1 -1
- package/dist/sqlEngine/diff/differential.js +7 -3
- package/dist/sqlEngine/diff/differential.js.map +1 -1
- package/dist/sqlTranslator/index.js +6 -1
- package/dist/sqlTranslator/index.js.map +1 -1
- package/dist/upgrade/upgradePrompt.d.ts +2 -2
- package/dist/upgrade/upgradePrompt.js +22 -3
- package/dist/upgrade/upgradePrompt.js.map +1 -1
- package/dist/utility/errors/commonErrors.d.ts +1 -0
- package/dist/utility/errors/commonErrors.js +1 -0
- package/dist/utility/errors/commonErrors.js.map +1 -1
- package/dist/utility/hdbTerms.d.ts +2 -0
- package/dist/utility/hdbTerms.js +2 -0
- package/dist/utility/hdbTerms.js.map +1 -1
- package/dist/utility/install/installer.js +32 -0
- package/dist/utility/install/installer.js.map +1 -1
- package/dist/utility/logging/harper_logger.d.ts +7 -0
- package/dist/utility/logging/harper_logger.js +57 -24
- package/dist/utility/logging/harper_logger.js.map +1 -1
- package/npm-shrinkwrap.json +197 -193
- package/package.json +9 -7
- package/resources/DatabaseTransaction.ts +310 -101
- package/resources/ResourceInterface.ts +8 -2
- package/resources/Resources.ts +22 -4
- package/resources/Table.ts +321 -243
- package/resources/analytics/write.ts +22 -20
- package/resources/blob.ts +15 -8
- package/resources/databases.ts +123 -12
- package/resources/jsResource.ts +5 -62
- package/resources/models/Models.ts +14 -1
- package/resources/models/backendRegistry.ts +10 -0
- package/resources/models/openaiStream.ts +131 -19
- package/resources/models/v1/chatCompletions.ts +128 -0
- package/resources/models/v1/embeddings.ts +70 -0
- package/resources/models/v1/errors.ts +141 -0
- package/resources/models/v1/index.ts +72 -0
- package/resources/models/v1/models.ts +53 -0
- package/resources/models/v1/translation.ts +362 -0
- package/resources/roles.ts +67 -7
- package/security/jsLoader.ts +84 -30
- package/security/role.ts +7 -0
- package/security/superUserGuard.ts +20 -0
- package/security/tokenAuthentication.ts +6 -3
- package/security/user.ts +26 -1
- package/server/DESIGN.md +45 -34
- package/server/http.ts +100 -13
- package/server/operationsServer.ts +0 -2
- package/server/serverHelpers/multipartParser.ts +9 -0
- package/server/serverHelpers/operationAuthorizationState.ts +11 -0
- package/server/serverHelpers/registeredOperations.ts +19 -15
- package/server/serverHelpers/serverHandlers.js +20 -3
- package/server/serverHelpers/serverUtilities.ts +10 -7
- package/server/static.ts +75 -20
- package/server/storageReclamation.ts +104 -8
- package/server/threads/socketRouter.ts +20 -0
- package/server/threads/threadServer.js +11 -0
- package/sqlTranslator/index.ts +6 -1
- package/static/defaultConfig.yaml +2 -0
- package/studio/web/assets/{Chat-DoVWScmq.js → Chat-aApwhRmz.js} +2 -2
- package/studio/web/assets/{Chat-DoVWScmq.js.map → Chat-aApwhRmz.js.map} +1 -1
- package/studio/web/assets/{FloatingChat-UZ2NsUOZ.js → FloatingChat-sC0H91n9.js} +4 -4
- package/studio/web/assets/{FloatingChat-UZ2NsUOZ.js.map → FloatingChat-sC0H91n9.js.map} +1 -1
- package/studio/web/assets/{apiToken-BUI_04o7.js → apiToken-DZ8JhHOI.js} +2 -2
- package/studio/web/assets/{apiToken-BUI_04o7.js.map → apiToken-DZ8JhHOI.js.map} +1 -1
- package/studio/web/assets/{applications-D03NA7wW.js → applications-9SEVLIO5.js} +2 -2
- package/studio/web/assets/{applications-D03NA7wW.js.map → applications-9SEVLIO5.js.map} +1 -1
- package/studio/web/assets/{index-Bh_CNAHr.js → index-Dy3uDGXb.js} +6 -6
- package/studio/web/assets/{index-Bh_CNAHr.js.map → index-Dy3uDGXb.js.map} +1 -1
- package/studio/web/assets/{index.lazy-Dx3MpyDC.js → index.lazy-CN1zq4I4.js} +4 -4
- package/studio/web/assets/{index.lazy-Dx3MpyDC.js.map → index.lazy-CN1zq4I4.js.map} +1 -1
- package/studio/web/assets/{notifications-0edoFTsb.js → notifications-BFAF07xr.js} +2 -2
- package/studio/web/assets/{notifications-0edoFTsb.js.map → notifications-BFAF07xr.js.map} +1 -1
- package/studio/web/assets/{notifications-CwKhipK7.js → notifications-CKlYVvVN.js} +2 -2
- package/studio/web/assets/{notifications-CwKhipK7.js.map → notifications-CKlYVvVN.js.map} +1 -1
- package/studio/web/assets/{profile-DUfEPQtx.js → profile-A1zhEdFG.js} +2 -2
- package/studio/web/assets/{profile-DUfEPQtx.js.map → profile-A1zhEdFG.js.map} +1 -1
- package/studio/web/assets/{setComponentFile-DMPo4UjC.js → setComponentFile-SEtBt_GV.js} +2 -2
- package/studio/web/assets/{setComponentFile-DMPo4UjC.js.map → setComponentFile-SEtBt_GV.js.map} +1 -1
- package/studio/web/assets/{setup-B56Oz1_u.js → setup-BisINqdH.js} +2 -2
- package/studio/web/assets/{setup-B56Oz1_u.js.map → setup-BisINqdH.js.map} +1 -1
- package/studio/web/assets/{status-BAod7p3o.js → status-BuQoCc7l.js} +2 -2
- package/studio/web/assets/{status-BAod7p3o.js.map → status-BuQoCc7l.js.map} +1 -1
- package/studio/web/assets/{swagger-ui-react-lQrBxfwM.js → swagger-ui-react-CAi_s1PC.js} +2 -2
- package/studio/web/assets/{swagger-ui-react-lQrBxfwM.js.map → swagger-ui-react-CAi_s1PC.js.map} +1 -1
- package/studio/web/assets/{tsMode-CrHCRjTK.js → tsMode-DT74tlkM.js} +2 -2
- package/studio/web/assets/{tsMode-CrHCRjTK.js.map → tsMode-DT74tlkM.js.map} +1 -1
- package/studio/web/assets/{useEntityRestURL-DoaBMEvU.js → useEntityRestURL-CGRGc1n7.js} +2 -2
- package/studio/web/assets/{useEntityRestURL-DoaBMEvU.js.map → useEntityRestURL-CGRGc1n7.js.map} +1 -1
- package/studio/web/index.html +1 -1
- package/upgrade/upgradePrompt.ts +22 -3
- package/utility/errors/commonErrors.ts +2 -0
- package/utility/hdbTerms.ts +2 -0
- package/utility/install/installer.ts +37 -0
- package/utility/logging/harper_logger.ts +57 -26
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { readFile } from 'node:fs/promises';
|
|
1
|
+
import { readFile, realpath } from 'node:fs/promises';
|
|
2
2
|
import { statfs } from 'node:fs/promises';
|
|
3
|
-
import { join } from 'node:path';
|
|
3
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
4
4
|
import { getWorkerIndex, getWorkerCount } from '../server/threads/manageThreads.js';
|
|
5
5
|
import { logger } from '../utility/logging/logger.ts';
|
|
6
6
|
import { CONFIG_PARAMS } from '../utility/hdbTerms.ts';
|
|
@@ -27,6 +27,56 @@ export type QuotaStatusData = {
|
|
|
27
27
|
updatedAt: number;
|
|
28
28
|
};
|
|
29
29
|
|
|
30
|
+
/**
|
|
31
|
+
* Resolves `target` to its real (symlink-free) path. `target` itself may not exist yet (e.g. a
|
|
32
|
+
* table's storage directory that hasn't been created), so walk up to the nearest existing
|
|
33
|
+
* ancestor, resolve that, and rejoin the not-yet-existing remainder lexically — this still
|
|
34
|
+
* catches a symlinked *parent* directory, which is the case that actually matters for quota
|
|
35
|
+
* scoping (leaf directories are created by Harper itself, not symlinked).
|
|
36
|
+
*/
|
|
37
|
+
async function resolveRealPath(target: string): Promise<string> {
|
|
38
|
+
try {
|
|
39
|
+
return await realpath(target);
|
|
40
|
+
} catch {
|
|
41
|
+
const parent = dirname(target);
|
|
42
|
+
if (parent === target) return resolve(target);
|
|
43
|
+
return join(await resolveRealPath(parent), basename(target));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Whether `target` resolves to a path inside `root`. quota-status.json is scoped to a single
|
|
49
|
+
* ROOTPATH; a database or table configured with its own STORAGE_PATH (or a STORAGE_BLOBPATHS
|
|
50
|
+
* entry) can live on an entirely different volume, and must not be reported against the root's
|
|
51
|
+
* quota. Compares real (symlink-resolved) paths, not just lexically-normalized ones — a `..`-free
|
|
52
|
+
* path can still be a symlink into another volume, and `resolve()` alone wouldn't catch that.
|
|
53
|
+
*/
|
|
54
|
+
async function isPathWithinRoot(root: string, target: string): Promise<boolean> {
|
|
55
|
+
const [resolvedRoot, resolvedTarget] = await Promise.all([resolveRealPath(root), resolveRealPath(target)]);
|
|
56
|
+
const relativePath = relative(resolvedRoot, resolvedTarget);
|
|
57
|
+
if (relativePath === '') return true;
|
|
58
|
+
if (isAbsolute(relativePath)) return false;
|
|
59
|
+
// Check the first segment specifically (`..`), not a `..`-prefix match — a child directory
|
|
60
|
+
// literally named e.g. `..data` (the Kubernetes ConfigMap/Secret atomic-update symlink
|
|
61
|
+
// convention) is not a parent-traversal and must not be rejected as escaping the root.
|
|
62
|
+
const firstSegment = relativePath.split(sep)[0];
|
|
63
|
+
return firstSegment !== '..';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Guards against a syntactically valid but semantically broken quota-status.json (missing or
|
|
68
|
+
* negative usage, non-positive quota, non-finite timestamp) being read as "100% free" or worse.
|
|
69
|
+
*/
|
|
70
|
+
function isValidQuotaStatus(status: QuotaStatusData): boolean {
|
|
71
|
+
return (
|
|
72
|
+
Number.isFinite(status.updatedAt) &&
|
|
73
|
+
Number.isFinite(status.quotaBytes) &&
|
|
74
|
+
status.quotaBytes > 0 &&
|
|
75
|
+
Number.isFinite(status.usedBytes) &&
|
|
76
|
+
status.usedBytes >= 0
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
30
80
|
/**
|
|
31
81
|
* Reads the quota-status.json file written by host-manager.
|
|
32
82
|
* Returns undefined if the file is absent or malformed; does not apply age filtering.
|
|
@@ -70,15 +120,61 @@ export function onStorageReclamation(
|
|
|
70
120
|
}
|
|
71
121
|
let reclamationTimer: NodeJS.Timeout;
|
|
72
122
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
123
|
+
export type StorageSpaceStats = {
|
|
124
|
+
available: number;
|
|
125
|
+
free: number;
|
|
126
|
+
size: number;
|
|
127
|
+
// Whether these numbers reflect a quota (accurate for what Harper can actually write) or
|
|
128
|
+
// raw filesystem-level statfs (can be wildly wrong under a quota-limited data directory).
|
|
129
|
+
basis: 'quota' | 'filesystem';
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Get available/free/size storage stats for a path, preferring a fresh quota-status.json (see
|
|
134
|
+
* getQuotaStatus) over statfs. statfs describes the filesystem, which is misleading whenever
|
|
135
|
+
* the data directory is quota-limited on a larger shared volume (#1976).
|
|
136
|
+
*/
|
|
137
|
+
export async function getStorageSpaceStats(path: string): Promise<StorageSpaceStats> {
|
|
138
|
+
const rootPath = envMgr.get(CONFIG_PARAMS.ROOTPATH);
|
|
76
139
|
const status = await getQuotaStatus();
|
|
77
|
-
|
|
78
|
-
|
|
140
|
+
const statusAge = status ? Date.now() - status.updatedAt : undefined;
|
|
141
|
+
if (
|
|
142
|
+
status &&
|
|
143
|
+
isValidQuotaStatus(status) &&
|
|
144
|
+
rootPath &&
|
|
145
|
+
// A negative age (clock skew, or a corrupt/future updatedAt) is not "fresh" — treat it the
|
|
146
|
+
// same as stale rather than trusting quota data indefinitely.
|
|
147
|
+
statusAge >= 0 &&
|
|
148
|
+
statusAge < QUOTA_STATUS_MAX_AGE_MS &&
|
|
149
|
+
// Checked last: it's the only async/IO-bound condition, so short-circuit it behind the
|
|
150
|
+
// cheap synchronous checks above.
|
|
151
|
+
(await isPathWithinRoot(rootPath, path))
|
|
152
|
+
) {
|
|
153
|
+
const available = Math.max(0, status.quotaBytes - status.usedBytes);
|
|
154
|
+
return { available, free: available, size: status.quotaBytes, basis: 'quota' };
|
|
79
155
|
}
|
|
80
156
|
const fsStats = await statfs(path);
|
|
81
|
-
return
|
|
157
|
+
return {
|
|
158
|
+
available: fsStats.bavail * fsStats.bsize,
|
|
159
|
+
free: fsStats.bfree * fsStats.bsize,
|
|
160
|
+
size: fsStats.blocks * fsStats.bsize,
|
|
161
|
+
basis: 'filesystem',
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Ratio of available to total size, guarding the 0/0 = NaN case (a zero-size statfs/quota result,
|
|
167
|
+
* e.g. an empty or misconfigured mount) so a full disk still reports a ratio of 0 rather than NaN.
|
|
168
|
+
*/
|
|
169
|
+
export function computeAvailableRatio(available: number, size: number): number {
|
|
170
|
+
return size > 0 ? available / size : 0;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// If a fresh quota-status.json exists (written by host-manager every ~90s), use quota-based ratio.
|
|
174
|
+
// Otherwise fall back to statfs for the registered path.
|
|
175
|
+
const defaultGetAvailableSpaceRatio = async (path: string): Promise<number> => {
|
|
176
|
+
const { available, size } = await getStorageSpaceStats(path);
|
|
177
|
+
return computeAvailableRatio(available, size);
|
|
82
178
|
};
|
|
83
179
|
let getAvailableSpaceRatio: (path: string) => Promise<number> = defaultGetAvailableSpaceRatio;
|
|
84
180
|
|
|
@@ -8,6 +8,12 @@ import { join } from 'path';
|
|
|
8
8
|
|
|
9
9
|
const workers = [];
|
|
10
10
|
const workersReady = [];
|
|
11
|
+
// startHTTPThreads() can be called more than once in-process (e.g. a test harness adding more
|
|
12
|
+
// worker threads to an already-running server via addThreads()). The crash-path sweep below must
|
|
13
|
+
// run only on the very first call — a later call happens after real mirrors are already bound, and
|
|
14
|
+
// sweeping the sockets directory then would delete their live files, reintroducing the exact outage
|
|
15
|
+
// this guards against.
|
|
16
|
+
let sweptSocketsDirectory = false;
|
|
11
17
|
|
|
12
18
|
if (isMainThread) {
|
|
13
19
|
process.on('uncaughtException', (error) => {
|
|
@@ -23,6 +29,20 @@ if (isMainThread) {
|
|
|
23
29
|
}
|
|
24
30
|
|
|
25
31
|
export async function startHTTPThreads(threadCount = 2, dynamicThreads?: boolean) {
|
|
32
|
+
// Crash-path defense: a hard crash can skip a worker's exit-time UDS cleanup and leave stale
|
|
33
|
+
// mirror files behind. This runs before any worker below can start (and thus before any mirror
|
|
34
|
+
// can bind), so it can only ever clear files nothing is using yet — never a live mirror. The
|
|
35
|
+
// inode ownership guard in cleanupUdsFiles()/markUdsBindFailed() (see http.ts) is the matching
|
|
36
|
+
// defense for the in-process rolling-restart case, which this sweep does not cover.
|
|
37
|
+
// Lazy dynamic import (not a top-level one), matching server/status/index.ts's own lazy import of
|
|
38
|
+
// http.ts: http.ts's module graph reaches security/auth.ts, whose module-scope table() call needs
|
|
39
|
+
// config already initialized — pulling that graph in at this file's own top level (which
|
|
40
|
+
// bin/run.ts imports before parsing argv / initializing config) breaks startup with "Unable to
|
|
41
|
+
// determine database storage path" before main() ever runs.
|
|
42
|
+
if (isMainThread && !sweptSocketsDirectory) {
|
|
43
|
+
sweptSocketsDirectory = true;
|
|
44
|
+
(await import('../http.ts')).cleanupSocketsDirectory();
|
|
45
|
+
}
|
|
26
46
|
recordHostname().catch((err) => harperLogger.error?.('Error recording hostname for analytics:', err));
|
|
27
47
|
// Drive transaction-log cooling from the main thread (the registry is a
|
|
28
48
|
// process-global singleton; see startTransactionLogCooling). Runs for all
|
|
@@ -275,6 +275,11 @@ function listenOnDomainSocket(port, server) {
|
|
|
275
275
|
}
|
|
276
276
|
function onListening() {
|
|
277
277
|
server.removeListener('error', onError);
|
|
278
|
+
// Record ownership of the inode we just bound, so cleanupUdsFiles()/markUdsBindFailed()
|
|
279
|
+
// (see http.ts) can tell this worker's own file apart from a replacement's later rebind
|
|
280
|
+
// at the same path (see registerUdsCleanupPaths). A no-op for domain sockets that aren't
|
|
281
|
+
// UDS mirrors (e.g. the operations API's primary socket), which were never registered.
|
|
282
|
+
httpComponent.recordUdsBindSuccess(port);
|
|
278
283
|
harperLogger.info('Domain socket listening on ' + port);
|
|
279
284
|
resolve({ port, name: server.name, protocol_name: server.protocol_name });
|
|
280
285
|
}
|
|
@@ -387,6 +392,9 @@ function listenOnPorts() {
|
|
|
387
392
|
callback?.();
|
|
388
393
|
},
|
|
389
394
|
};
|
|
395
|
+
// createUwsServer() only resolves once uWS's own listen_unix() confirms the bind, so
|
|
396
|
+
// ownership is confirmed now (see http.ts's ownership-aware cleanupUdsFiles()).
|
|
397
|
+
if (cfg.socketPath) httpComponent.recordUdsBindSuccess(cfg.socketPath);
|
|
390
398
|
harperLogger.info('uWS listening on ' + (cfg.socketPath ?? cfg.port));
|
|
391
399
|
return { port: key };
|
|
392
400
|
})
|
|
@@ -517,6 +525,9 @@ async function listenOnPortsBun() {
|
|
|
517
525
|
});
|
|
518
526
|
SERVERS[udsPath] = udsServer;
|
|
519
527
|
httpComponent.registerUdsCleanupPaths(udsPath, yamlPath);
|
|
528
|
+
// Bun.serve() above already succeeded (a bind failure throws synchronously into the
|
|
529
|
+
// surrounding catch), so this worker's ownership of udsPath is confirmed now.
|
|
530
|
+
httpComponent.recordUdsBindSuccess(udsPath);
|
|
520
531
|
|
|
521
532
|
const writeMetadata = () => httpComponent.writeUdsMetadata(yamlPath, port, config.pseudoServer);
|
|
522
533
|
config.tlsSelector.ready.then(writeMetadata);
|
package/sqlTranslator/index.ts
CHANGED
|
@@ -17,6 +17,7 @@ import * as terms from '../utility/hdbTerms.ts';
|
|
|
17
17
|
import { handleHDBError } from '../utility/errors/hdbError.ts';
|
|
18
18
|
import { HTTP_STATUS_CODES } from '../utility/errors/commonErrors.ts';
|
|
19
19
|
import * as sqlEngineRouter from '../sqlEngine/router.ts';
|
|
20
|
+
import { isOperationAuthorizationBypassed } from '../server/serverHelpers/operationAuthorizationState.ts';
|
|
20
21
|
|
|
21
22
|
//here we call to define and import custom functions to alasql
|
|
22
23
|
alasqlFunctionImporter(alasql);
|
|
@@ -129,7 +130,11 @@ export function processAST(jsonMessage: any, parsedSqlObject: any, callback: any
|
|
|
129
130
|
try {
|
|
130
131
|
let sqlFunction = nullFunction;
|
|
131
132
|
|
|
132
|
-
|
|
133
|
+
// Trusted bypass is dispatch/async-context state (set by chooseOperation's caller via
|
|
134
|
+
// runWithOperationAuthorizationBypass), never body state — jsonMessage.bypass_auth is
|
|
135
|
+
// caller-controlled and is stripped before operation code sees it (see
|
|
136
|
+
// server/serverHelpers/serverHandlers.js and components/mcp/tools/operations.ts).
|
|
137
|
+
if (!isOperationAuthorizationBypassed() && !parsedSqlObject.permissions_checked) {
|
|
133
138
|
let permissionsCheck = checkASTPermissions(jsonMessage, parsedSqlObject);
|
|
134
139
|
if (permissionsCheck && permissionsCheck.length > 0) {
|
|
135
140
|
return callback(UNAUTHORIZED_RESPONSE, permissionsCheck);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,t}from"./rolldown-runtime-CNC7AqOf.js";import{C as n,S as r,_ as i,a,b as o,c as s,d as c,h as l,i as u,l as d,m as f,p,r as m,s as h,t as g,u as _,v,w as ee,x as y,y as b}from"./vendor-core-xUefYpUO.js";import{i as x,t as S}from"./button-oQgW4t1x.js";import{C as te,I as ne,N as re,j as ie}from"./vendor-tanstack-0SjDjtT0.js";import{a as ae}from"./vendor-datadog-DyjkTkvg.js";import{r as oe}from"./vendor-react-DeL8Gtgl.js";import{Rt as C}from"./vendor-ui-Bj22lHGK.js";import{t as w}from"./createLucideIcon-BDx8noBh.js";import{l as se,t as ce}from"./react-CjDfh48f.js";import{i as le,n as ue,r as de,t as fe}from"./x-C3uc0qMD.js";import{c as pe,f as me,g as he,h as ge,i as _e,l as ve,m as ye,p as be,r as xe,t as Se,u as Ce}from"./setComponentFile-
|
|
1
|
+
import{a as e,t}from"./rolldown-runtime-CNC7AqOf.js";import{C as n,S as r,_ as i,a,b as o,c as s,d as c,h as l,i as u,l as d,m as f,p,r as m,s as h,t as g,u as _,v,w as ee,x as y,y as b}from"./vendor-core-xUefYpUO.js";import{i as x,t as S}from"./button-oQgW4t1x.js";import{C as te,I as ne,N as re,j as ie}from"./vendor-tanstack-0SjDjtT0.js";import{a as ae}from"./vendor-datadog-DyjkTkvg.js";import{r as oe}from"./vendor-react-DeL8Gtgl.js";import{Rt as C}from"./vendor-ui-Bj22lHGK.js";import{t as w}from"./createLucideIcon-BDx8noBh.js";import{l as se,t as ce}from"./react-CjDfh48f.js";import{i as le,n as ue,r as de,t as fe}from"./x-C3uc0qMD.js";import{c as pe,f as me,g as he,h as ge,i as _e,l as ve,m as ye,p as be,r as xe,t as Se,u as Ce}from"./setComponentFile-SEtBt_GV.js";import{n as we}from"./queryClient-CbA8wM7J.js";import{n as Te}from"./setLocalStorage-CD_L8p_D.js";import{t as Ee}from"./useLocalStorage-hkNSGGg8.js";import{o as De}from"./pollUnlessForbidden-HHdQZW1N.js";import{$n as Oe,At as ke,Bn as Ae,Gn as je,Gt as Me,Hn as Ne,Jn as Pe,L as Fe,Nt as Ie,Ot as Le,Qn as Re,R as ze,Un as Be,_t as Ve,ar as He,c as Ue,dn as We,ir as Ge,jt as Ke,kt as qe,lr as Je,nr as Ye,o as Xe,ot as Ze,q as Qe,s as $e,u as et,ut as tt}from"./index-Dy3uDGXb.js";import{t as nt}from"./useEntityRestURL-CGRGc1n7.js";import{n as rt}from"./getAnalytics-ChWFgfXd.js";var it=w(`between-horizontal-start`,[[`rect`,{width:`13`,height:`7`,x:`8`,y:`3`,rx:`1`,key:`pkso9a`}],[`path`,{d:`m2 9 3 3-3 3`,key:`1agib5`}],[`rect`,{width:`13`,height:`7`,x:`8`,y:`14`,rx:`1`,key:`1q5fc1`}]]),at=w(`book`,[[`path`,{d:`M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20`,key:`k3hazp`}]]),ot=w(`chart-area`,[[`path`,{d:`M3 3v16a2 2 0 0 0 2 2h16`,key:`c24i48`}],[`path`,{d:`M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z`,key:`q0gr47`}]]),st=w(`circle-x`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m15 9-6 6`,key:`1uzhvr`}],[`path`,{d:`m9 9 6 6`,key:`z0biqf`}]]),ct=w(`file-pen`,[[`path`,{d:`M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34`,key:`o6klzx`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z`,key:`zhnas1`}]]),lt=w(`logs`,[[`path`,{d:`M3 5h1`,key:`1mv5vm`}],[`path`,{d:`M3 12h1`,key:`lp3yf2`}],[`path`,{d:`M3 19h1`,key:`w6f3n9`}],[`path`,{d:`M8 5h1`,key:`1nxr5w`}],[`path`,{d:`M8 12h1`,key:`1con00`}],[`path`,{d:`M8 19h1`,key:`k7p10e`}],[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}]]),ut=w(`message-square-heart`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7.5 9.5c0 .687.265 1.383.697 1.844l3.009 3.264a1.14 1.14 0 0 0 .407.314 1 1 0 0 0 .783-.004 1.14 1.14 0 0 0 .398-.31l3.008-3.264A2.77 2.77 0 0 0 16.5 9.5 2.5 2.5 0 0 0 12 8a2.5 2.5 0 0 0-4.5 1.5`,key:`1faxuh`}]]),dt=w(`send`,[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`,key:`1ffxy3`}],[`path`,{d:`m21.854 2.147-10.94 10.939`,key:`12cjpa`}]]),ft=w(`wrench`,[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z`,key:`1ngwbx`}]]);async function pt(){await x.delete(`/Chat/Messages/`)}var T=e(ae(),1),E=oe();function mt({setMessages:e}){let[t,n]=(0,T.useState)(!1);return(0,E.jsxs)(`button`,{type:`button`,className:`clear-chat-button gap-1`,onClick:(0,T.useCallback)(async()=>{if(!t){n(!0);try{await pt(),e([])}catch(e){console.error(`Failed to clear chat:`,e)}finally{n(!1)}}},[t,e]),disabled:t,title:`Clear chat`,children:[t?(0,E.jsx)(Re,{className:`animate-spin`,size:18}):(0,E.jsx)(Be,{size:18}),`Clear`]})}async function ht(){let{data:e}=await x.get(`/Chat/Messages/`);return e}var gt=`vercel.ai.error`,_t=Symbol.for(gt),vt,yt,D=class e extends (yt=Error,vt=_t,yt){constructor({name:e,message:t,cause:n}){super(t),this[vt]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,gt)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};function bt(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.toString():JSON.stringify(e)}var xt=`AI_InvalidArgumentError`,St=`vercel.ai.error.${xt}`,Ct=Symbol.for(St),wt,Tt,Et=class extends (Tt=D,wt=Ct,Tt){constructor({message:e,cause:t,argument:n}){super({name:xt,message:e,cause:t}),this[wt]=!0,this.argument=n}static isInstance(e){return D.hasMarker(e,St)}},Dt=`AI_JSONParseError`,Ot=`vercel.ai.error.${Dt}`,kt=Symbol.for(Ot),At,jt,Mt=class extends (jt=D,At=kt,jt){constructor({text:e,cause:t}){super({name:Dt,message:`JSON parsing failed: Text: ${e}.
|
|
2
2
|
Error message: ${bt(t)}`,cause:t}),this[At]=!0,this.text=e}static isInstance(e){return D.hasMarker(e,Ot)}},Nt=`AI_TypeValidationError`,Pt=`vercel.ai.error.${Nt}`,Ft=Symbol.for(Pt),It,Lt,O=class e extends (Lt=D,It=Ft,Lt){constructor({value:e,cause:t,context:n}){let r=`Type validation failed`;if(n?.field&&(r+=` for ${n.field}`),n?.entityName||n?.entityId){r+=` (`;let e=[];n.entityName&&e.push(n.entityName),n.entityId&&e.push(`id: "${n.entityId}"`),r+=e.join(`, `),r+=`)`}super({name:Nt,message:`${r}: Value: ${JSON.stringify(e)}.
|
|
3
3
|
Error message: ${bt(t)}`,cause:t}),this[It]=!0,this.value=e,this.context=n}static isInstance(e){return D.hasMarker(e,Pt)}static wrap({value:t,cause:n,context:r}){return e.isInstance(n)&&n.value===t&&n.context?.field===r?.field&&n.context?.entityName===r?.entityName&&n.context?.entityId===r?.entityId?n:new e({value:t,cause:n,context:r})}},Rt=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},zt=10,Bt=13,k=32;function Vt(e){}function Ht(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Vt,onError:n=Vt,onRetry:r=Vt,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
|
|
4
4
|
`)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new Rt(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(`
|
|
@@ -1946,4 +1946,4 @@ jsResource:
|
|
|
1946
1946
|
`,"using-blob-datatype":"---\nname: using-blob-datatype\ndescription: How to use the Blob data type for efficient binary storage in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Blob Type\n - reference/v5/database/api.md#Streaming\n - reference/v5/database/api.md#`BlobOptions`\n - reference/v5/database/api.md#Blob Coercion\n sourceCommit: f37a8c4021e20d5c74c1d339a6b6c8c196b5603e\n inputHash: 92e03eb0b830f335\n---\n\n# Using the Blob Data Type\n\nInstructions for the agent to follow when storing and retrieving large binary content using the `Blob` data type in Harper.\n\n## When to Use\n\nApply this rule when a schema field needs to store large binary content such as images, video, audio, or large HTML — typically content larger than 20KB. Use `Blob` instead of `Bytes` when streaming support and out-of-record storage are required. See [handling-binary-data.md](handling-binary-data.md) for broader binary data guidance.\n\n## How It Works\n\n1. **Declare a `Blob` field in your schema**: Add a field typed as `Blob` to your `@table` type.\n\n ```graphql\n type MyTable @table {\n id: Any! @primaryKey\n data: Blob\n }\n ```\n\n2. **Create and store a blob with `createBlob()`**: Pass a buffer or stream to `createBlob()`, then `put` the record.\n\n ```javascript\n let blob = createBlob(largeBuffer);\n await MyTable.put({ id: 'my-record', data: blob });\n ```\n\n3. **Retrieve blob data using standard Web API methods**: The `Blob` type implements the Web API `Blob` interface. Use `.bytes()`, `.text()`, `.arrayBuffer()`, `.stream()`, or `.slice()` as needed.\n\n ```javascript\n let record = await MyTable.get('my-record');\n let buffer = await record.data.bytes(); // ArrayBuffer\n let text = await record.data.text(); // string\n let stream = record.data.stream(); // ReadableStream\n ```\n\n4. **Use `saveBeforeCommit` when full write must precede commit**: By default, `Blob` is not ACID-compliant — a record can reference a blob before it is fully written. Set `saveBeforeCommit: true` to block the transaction until the blob is fully saved.\n\n ```javascript\n let blob = createBlob(stream, { saveBeforeCommit: true });\n await MyTable.put({ id: 'my-record', data: blob });\n // put() resolves only after blob is fully written and record is committed\n ```\n\n5. **Register an error handler when returning a blob via REST**: Interrupted streams must be handled explicitly.\n\n ```javascript\n export class MyEndpoint extends MyTable {\n static async get(target) {\n const record = super.get(target);\n let blob = record.data;\n blob.on('error', () => {\n MyTable.invalidate(target);\n });\n return { status: 200, headers: {}, body: blob };\n }\n }\n ```\n\n6. **Rely on automatic coercion where applicable**: When a field is typed as `Blob` in the schema, any string or buffer assigned via `put`, `patch`, or `publish` is automatically coerced to a `Blob` — no manual `createBlob()` call is needed in those cases.\n\n### `BlobOptions` reference\n\nPass an options object as the second argument to `createBlob()`.\n\n| Option | Type | Default | Description |\n| ------------------ | --------- | ----------- | ------------------------------------------------------------------------------------------------------------------------ |\n| `type` | `string` | `undefined` | MIME type to associate with the blob (e.g., `image/jpeg`). Readable via `blob.type` and used when serving HTTP. |\n| `size` | `number` | `undefined` | Size of the data in bytes, if known ahead of time. Otherwise inferred from a buffer or determined as a stream completes. |\n| `saveBeforeCommit` | `boolean` | `false` | Wait until the blob is fully written before the transaction commits. |\n| `compress` | `boolean` | `false` | Compress the stored data with deflate. |\n| `flush` | `boolean` | `false` | Flush the file to disk after writing, before the `createBlob` promise chain resolves. |\n\n## Examples\n\n**Store an image with a MIME type:**\n\n```javascript\nlet blob = createBlob(imageBuffer, { type: 'image/jpeg' });\nawait Photo.put({ id, data: blob });\n```\n\n**Stream a blob in as it streams out (low-latency passthrough):**\n\n```javascript\nlet blob = createBlob(incomingStream);\n// blob exists, but data is still streaming to storage\nawait MyTable.put({ id: 'my-record', data: blob });\n\nlet record = await MyTable.get('my-record');\n// blob data is accessible as it arrives\nlet outgoingStream = record.data.stream();\n```\n\n**Guarantee full write before commit using `saveBeforeCommit`:**\n\n```javascript\nlet blob = createBlob(stream, { saveBeforeCommit: true });\nawait MyTable.put({ id: 'my-record', data: blob });\n```\n\n## Notes\n\n- `Blob` stores data separately from the record. If you need the binary data to be a true, ACID-committed part of the record, use a `Bytes` field instead.\n- All standard Web API `Blob` methods — `.text()`, `.arrayBuffer()`, `.stream()`, `.slice()`, and `.bytes()` — are available on retrieved blob fields.\n- Without `saveBeforeCommit: true`, blobs are **not** ACID-compliant by default; a record can reference a blob before it is fully written to storage.\n","v5-upgrade":"---\nname: v5-upgrade\ndescription: >-\n Breaking changes and recommended updates when migrating a Harper application\n to v5.\nmetadata:\n mode: generate\n sources:\n - release-notes/v5-lincoln/v5-migration.md\n sourceCommit: de2aaf1c759a7ff5b93e862ba704153e2a392fcb\n inputHash: 80314689f3a7f42e\n---\n\n# Upgrading a Harper Application to v5\n\nInstructions for the agent to follow when migrating an existing Harper application to version 5, addressing the breaking changes and adopting the recommended patterns.\n\n## When to Use\n\nApply this rule when upgrading a Harper application from v4.x (or earlier) to v5, or when code written against older APIs behaves differently after a v5 upgrade — for example a record that can no longer be mutated, a query that returns stale data, or a `spawn` call that now throws. Harper v5 introduces breaking changes; applications built on documented APIs need the updates below, while code relying on undocumented behavior or timing may need broader review.\n\n## How It Works\n\n1. **Adopt the `harper` package name**: HarperDB is now Harper, and the package was renamed. Install the open source edition with `npm i -g harper` and the pro edition with `npm i -g @harperfast/harper-pro`. Update application imports from `harperdb` to `harper`:\n\n ```javascript\n import { tables } from 'harper';\n ```\n\n2. **Opt in to install scripts when required**: Harper now installs packages with `--ignore-scripts` to guard against accidental script execution, a common security risk. If an application genuinely needs install scripts to run (for example to build native binaries), pass the `allowInstallScripts` option when deploying.\n\n3. **Update `Table.get` return-value handling**: `Table.get` now returns a plain, frozen record object rather than an instance of the table class, so instance methods are no longer available on the result. The commonly used `wasLoadedFromSource()` method is gone; cache-vs-origin information now lives on the request `target` as `target.loadedFromSource`. Pass a `RequestTarget` to `Table.get` and read the flag from it. Because the record is frozen, create a copy instead of mutating it in place.\n\n4. **Account for automatic transaction context**: With RocksDB, transactions are fully supported by the storage engine, and Harper v5 uses asynchronous context tracking to carry the current transaction across calls automatically. A nested `Table.get` now reads within the current transaction's snapshot, so it will not observe newly written data until you commit. Access the context through `getContext()` and either commit the current transaction (`getContext().transaction.commit()`) or run the read inside a fresh `transaction(...)` to see the latest data. This matters most for code executing outside the context of a Harper request.\n\n5. **Register spawnable commands**: Spawning processes is now tightly controlled. `spawn`, `exec`, and `execFile` may only run executables listed in the `applications.allowedSpawnCommands` configuration, and each call must pass a `name` in its `options` so that only a single named process is started across Harper's multiple threads. Use a distinct `name` when you deliberately need a separate process.\n\n6. **Return Response-like objects to set headers**: If a REST method returns an object with a `headers` property, Harper uses it as the response headers.\n\n7. **Replace `blob.save()`**: The `blob.save()` method has been removed. Pass the `saveBeforeCommit` flag in the options to the `Blob` constructor instead.\n\n8. **Configure the VM module loader**: v5 loads application modules through Node.js's VM module API, giving each application its own module cache and an application-scoped `harper` module. All of this is controlled by the `applications` section of `harperdb-config.yaml`:\n - `moduleLoader` — `vm-current-context` (default), `vm`, `native`, or `compartment`. The default shares intrinsics with Harper for best compatibility; choose `vm` only if you need per-application intrinsics, and `native` to disable the VM loader entirely (restores pre-v5 loading, but per-app `logger`/`config` context is unavailable).\n - `lockdown` — `freeze-after-load` (default), `freeze`, `ses`, or `none`. Freezing intrinsics prevents prototype-pollution attacks; set `lockdown: none` only as a temporary workaround if a dependency mutates built-in prototypes.\n - `allowedDirectory` — `app` (default) restricts module loading to the application's own directory tree; set `any` if the app must load files from outside it in production.\n - `allowedBuiltinModules` — an optional allowlist restricting which Node.js built-ins the application may import (all are allowed if omitted).\n - `dependencyLoader` — `auto` (default), `app`, or `native`, controlling how npm dependencies are loaded through or around the VM loader.\n\n## Examples\n\n**Updating `Table.get` and its cache check:**\n\n```javascript\n// Old (v4.x)\nconst record = await Table.get(id);\nif (record.wasLoadedFromSource()) {\n // loaded from origin, not cache\n}\n\n// New (v5)\nconst target = new RequestTarget(); // passed in when overriding `get`\ntarget.id = id;\nconst record = await Table.get(target);\nif (target.loadedFromSource) {\n // loaded from origin, not cache\n}\n```\n\n**Committing the transaction to read fresh data:**\n\n```javascript\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { getContext, transaction } from 'harper';\n\nclass MyResource {\n static async get(target) {\n // The current transaction is a consistent snapshot; commit it to see updates.\n await getContext().transaction.commit();\n while ((await transaction(() => Table.get(target))).status !== 'ready') {\n delay(100);\n }\n return Table.get(target);\n }\n}\n```\n\n**Module loader and security configuration in `harperdb-config.yaml`:**\n\n```yaml\napplications:\n lockdown: freeze-after-load # default\n moduleLoader: vm-current-context # vm-current-context (default) | vm | native | compartment\n dependencyLoader: auto # auto (default) | app | native\n allowedDirectory: app # app (default) | any\n allowedSpawnCommands:\n - npm\n - node\n # allowedBuiltinModules: [] # if omitted, all Node.js built-ins are allowed\n```\n\n## Recommended Changes\n\nBeyond the required fixes above, Harper v5 encourages these patterns for new and migrated code:\n\n- Implement endpoints with `static` methods on Resources/Tables, reading request information from the request `target` argument (or from `getContext()`).\n- Rely on automatic context propagation rather than threading context through every call manually; access it via `getContext()` exported from `harper`.\n- Access Harper functions and APIs through the `harper` package rather than through global variables.\n","vector-indexing":'---\nname: vector-indexing\ndescription: How to enable and query vector indexes for similarity search in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Vector Indexing\n sourceCommit: 4fe4c9c95e0974eaa77032f6f10e36fbd8ec64ac\n inputHash: d90b1b74597d08a6\n---\n\n# Vector Indexing\n\nInstructions for the agent to enable HNSW vector indexes on table fields and query them for similarity search in Harper.\n\n## When to Use\n\nApply this rule when adding a vector similarity search capability to a Harper table — for example, storing text embeddings and querying for nearest neighbors, filtering by distance threshold, or tuning index construction and search parameters. Use it alongside [adding-tables-with-schemas.md](adding-tables-with-schemas.md) when defining the schema that hosts the vector field.\n\n## How It Works\n\n1. **Declare the vector index on a field**: Add `@indexed(type: "HNSW")` to a `[Float]` field inside a `@table` type. This creates an HNSW (Hierarchical Navigable Small World) index for approximate nearest-neighbor search.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float] @indexed(type: "HNSW")\n }\n ```\n\n2. **Query by nearest neighbors using `sort`**: Call `.search()` with a `sort` descriptor that specifies the indexed `attribute` and a `target` vector. Use `limit` to cap results.\n\n ```javascript\n let results = Document.search({\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n3. **Combine with filter conditions**: Add a `conditions` array alongside `sort` to pre-filter records before ranking by similarity.\n\n ```javascript\n let results = Document.search({\n conditions: [{ attribute: \'price\', comparator: \'lt\', value: 50 }],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n4. **Filter by distance threshold**: To return only records within a similarity cutoff (without ranking), place `target` directly on the condition alongside `comparator` and `value`. This bounds result quality rather than ranking by similarity.\n\n ```javascript\n let results = Document.search({\n conditions: {\n attribute: \'textEmbeddings\',\n comparator: \'lt\',\n value: 0.1,\n target: searchVector,\n },\n });\n ```\n\n5. **Include computed distance in results**: Use the special `$distance` field in `select` to return the distance from the target vector. Available in both `sort`-based and threshold-based queries.\n\n ```javascript\n let results = Document.search({\n select: [\'name\', \'$distance\'],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n6. **Tune per-query search options**: Pass `distance` and `ef` directly on the `sort` descriptor to override index defaults for a single query.\n\n ```javascript\n let results = Document.search({\n sort: { attribute: \'textEmbeddings\', target: searchVector, distance: \'dotProduct\', ef: 200 },\n limit: 5,\n });\n ```\n\n - `distance` — overrides the distance function for this query: `"cosine"`, `"euclidean"`, or `"dotProduct"`.\n - `ef` — overrides the search exploration budget. Higher values improve recall at the cost of latency.\n\n7. **Configure HNSW index parameters**: Pass parameters directly in the `@indexed` directive. Structural parameters (`distance`, `M`, `efConstruction`, `quantization`) trigger an index rebuild when changed; `efConstructionSearch` does not.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float]\n @indexed(type: "HNSW", distance: "euclidean", optimizeRouting: 0, efConstructionSearch: 100)\n }\n ```\n\n8. **Enable vector quantization**: Use `quantization: "int8"` to store vectors as 8-bit integers, reducing index size and memory usage. Harper re-ranks nearest-neighbor `sort` results against full-precision vectors automatically.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float] @indexed(type: "HNSW", quantization: "int8")\n }\n ```\n\n## Examples\n\nFull schema with custom HNSW parameters and a nearest-neighbor query with distance output:\n\n```graphql\ntype Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float]\n @indexed(type: "HNSW", distance: "euclidean", optimizeRouting: 0, efConstructionSearch: 100)\n}\n```\n\n```javascript\n// Nearest-neighbor search with distance scores\nlet results = Document.search({\n select: [\'name\', \'$distance\'],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n});\n\n// Distance-threshold query (no ranking)\nlet closeMatches = Document.search({\n conditions: {\n attribute: \'textEmbeddings\',\n comparator: \'lt\',\n value: 0.1,\n target: searchVector,\n },\n});\n```\n\n## Notes\n\n### HNSW Parameters\n\n| Parameter | Default | Description |\n| ---------------------- | ----------------- | ------------------------------------------------------------------------------------------------------ |\n| `distance` | `"cosine"` | Distance function: `"cosine"`, `"euclidean"`, or `"dotProduct"` |\n| `efConstruction` | `100` | Max nodes explored during index construction. Higher = better recall, lower = better performance |\n| `M` | `16` | Preferred connections per graph layer. Higher = more space, better recall for high-dimensional data |\n| `optimizeRouting` | `0.5` | Heuristic aggressiveness for omitting redundant connections (0 = off, 1 = most aggressive) |\n| `mL` | computed from `M` | Normalization factor for level generation |\n| `efConstructionSearch` | auto-scaled | Max nodes explored during search. When unset, auto-scales with index size; setting it fixes the budget |\n| `quantization` | — | `"int8"` stores vectors quantized to int8 |\n\n- The `distance` option on a per-query `sort` descriptor accepts `"cosine"`, `"euclidean"`, or `"dotProduct"`.\n- When no `ef` is passed and `efConstructionSearch` (or `efConstruction`) is not explicitly set on the index, the search budget auto-scales with index size.\n- `efConstruction` seeds the initial value of `efConstructionSearch`; setting either one fixes the search budget.\n- The correct parameter name is `efConstructionSearch` (not `efSearchConstruction`).\n- `$distance` is available in both `sort`-based ranking and `conditions`-based threshold queries.\n- For `quantization: "int8"`, distance-threshold (`lt`/`le`) queries filter on approximate distance; `sort` queries re-rank against full-precision vectors.\n'},sa={name:`readHarperSkill`,description:`Returns documentation for a Harper skill or best practice. Skills provide guidance on developing Harper applications.`,inputSchema:v({skill:m(aa)})};async function ca({input:{skill:e}}){return{success:!!oa[e],message:oa[e]||`No skill found with the name ${e}`}}var la={...sa,icon:at,execute:ca},ua={name:`readLogs`,description:`Returns the matching logs from the server.`,inputSchema:v({log_name:m([`hdb.log`,`system.log`]).default(`hdb.log`),limit:o().or(a()).optional(),level:m([`notify`,`error`,`warn`,`info`,`debug`,`trace`,`undefined`]).or(a()).optional(),from:o().or(a()).optional(),until:o().or(a()).optional()})};async function da({input:e,instanceClientParams:t}){try{return{success:!0,data:await Xe({...t,logFilters:e,replicated:t.entityType===`cluster`})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var fa={...ua,icon:lt,execute:da},pa={name:`readTableRecords`,description:`Retrieves some or all table records from a database on the server.`,inputSchema:v({database:o().trim(),table:o().trim(),pageIndex:i().default(0),pageSize:i().default(10),primaryKey:o(),conditions:s(v({search_attribute:o(),search_type:m([`between`,`eq`,`equals`,`greater_than`,`greater_than_equal`,`less_than`,`less_than_equal`,`ne`,`not_equal`,`starts_with`]),search_value:h()})),sort:v({attribute:o(),descending:d()})})};async function ma({input:{database:e,table:t,conditions:n,primaryKey:r,...i},instanceClientParams:a}){try{if(!n.length){let{data:n}=await qe({...a,databaseName:e,tableName:t,onlyIfCached:!0,searchAttribute:r,...i});return{success:!0,data:n}}let{data:o}=await ze({...a,databaseName:e,tableName:t,onlyIfCached:!0,conditions:n,...i});return{success:!0,data:o}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ha={...pa,icon:Pe,execute:ma},ga={name:`restartHTTPService`,description:`Restarts the HTTP service on the server to allow schema and resource changes to be applied.`,inputSchema:v({})};async function _a({instanceClientParams:e,baseURL:t}){let n=C.loading(`Restarting HTTP service...`,{description:`This may take a bit.`,duration:3e5});try{await Ve({...e,operation:`restart_service`,replicated:e.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return C.success(`Done!`,{description:`HTTP Service restarted!`,id:n,duration:5e3}),{success:!0,message:`HTTP Service restarted!`,webURL:t}}var va={...ga,icon:Re,execute:_a,requiresApproval:!0},ya={name:`setComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:v({path:o().trim(),payload:o(),encoding:m([`utf8`,`ASCII`,`binary`,`hex`,`base64`,`utf16le`,`latin1`,`ucs2`])})};async function ba({input:{path:e,encoding:t,payload:n},instanceClientParams:r}){try{let i=e.split(`/`),a=i.shift(),o=i.join(`/`),s=await Se({...r,file:o,project:a,payload:n,encoding:t});return await we.invalidateQueries({queryKey:[r.entityId,`get_component_file`,a,o]}),Ie(`ReloadApplicationRootEntries`,!0),{success:!0,data:s}}catch(e){return{success:!1,message:`Error: ${e}`}}}var xa={...ya,icon:ct,execute:ba,requiresApproval:!0},Sa={name:`updateTableRecords`,description:`Updates records in a particular table in a particular database on the server.`,inputSchema:v({database:o().trim(),table:o().trim(),records:s(h())})};async function Ca({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await $e({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await we.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var wa={readHarperSkill:la,createApp:Di,readLogs:fa,getAnalytics:Ii,listAnalyticsMetrics:ia,restartHTTPService:va,collectFeedback:wi,getUserContext:Zi,getComponentFile:zi,getComponents:Hi,setComponentFile:xa,dropComponentFile:Ni,getDescribeAll:Gi,getDescribeTable:Ji,insertTableRecords:ea,readTableRecords:ha,updateTableRecords:{...Sa,icon:it,execute:Ca,requiresApproval:!0},deleteTableRecords:Ai};function Ta(e){return wa[e]}function Ea(e){return e.state===`input-available`&&!!Ta(Qr(e))?.requiresApproval}function Da(e){let t=[];for(let[n,r]of(e??[]).entries()){if(G(r)){if(Ea(r)){t.push({kind:`part`,part:r,index:n});continue}let e=t.at(-1);e?.kind===`tool-group`?e.parts.push(r):t.push({kind:`tool-group`,parts:[r],index:n});continue}Jr(r)&&r.text.length>0&&t.push({kind:`part`,part:r,index:n})}return t}function Oa({part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i}){let[a,o]=(0,T.useState)(!1),[s,c]=(0,T.useState)(!1),l=Qr(e),u=Ta(l),d=u?.icon||Ge,f=u?.requiresApproval,p=(0,T.useMemo)(()=>!e.input||typeof e.input==`object`&&Object.keys(e.input).length===0,[e.input]),m=(0,T.useMemo)(()=>{let t=JSON.stringify(e.input,null,` `);return{json:t,lines:t?t.split(`
|
|
1947
1947
|
`).length:0}},[e.input]),h=(0,T.useMemo)(()=>{let t=JSON.stringify(e.output,null,` `);return{json:t,lines:t?t.split(`
|
|
1948
1948
|
`).length:0}},[e.output]);return(0,E.jsxs)(`div`,{className:`tool-invocation ${e.state}`,children:[(0,E.jsxs)(`div`,{className:`tool-info`,children:[(0,E.jsxs)(`div`,{className:`tool-name`,children:[(0,E.jsx)(d,{size:14}),(0,E.jsx)(`span`,{children:l})]}),(0,E.jsxs)(`div`,{className:`tool-status`,children:[e.state===`input-streaming`&&(0,E.jsx)(`span`,{children:`Thinking...`}),e.state===`input-available`&&(0,E.jsx)(`span`,{children:i?`Executing...`:f?`Awaiting Approval...`:`Executing...`}),e.state===`output-available`&&(e.output?.error?(0,E.jsx)(st,{size:14,className:`text-destructive`}):(0,E.jsx)(le,{size:14}))]})]}),e.state!==`input-streaming`&&(0,E.jsxs)(`div`,{className:`tool-io`,children:[!p&&(0,E.jsxs)(`div`,{className:`tool-args`,children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,E.jsx)(`strong`,{children:`Input:`}),m.lines>3&&(0,E.jsx)(S,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>o(!a),children:a?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ue,{size:12}),`Hide`]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(de,{size:12}),`Show`]})})]}),(0,E.jsx)(`div`,{className:a?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:m.json})]}),e.state===`input-available`&&f&&(0,E.jsxs)(`div`,{className:`flex gap-2 mt-3 pt-3 border-t`,children:[(0,E.jsxs)(S,{size:`sm`,className:`h-8 text-xs bg-green-600 hover:bg-green-700 text-white`,onClick:()=>t?.(e.toolCallId),disabled:i,children:[i?(0,E.jsx)(Ye,{className:`mr-2 h-3 w-3 animate-spin`}):null,`Approve`]}),(0,E.jsx)(S,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>r?.(e.toolCallId),disabled:i,children:`Always Approve`}),(0,E.jsx)(S,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>n?.(e.toolCallId),disabled:i,children:`Deny`})]}),e.state===`output-available`&&(0,E.jsx)(E.Fragment,{children:u?.render?u.render(e):(0,E.jsxs)(`div`,{className:`tool-result`,children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,E.jsx)(`strong`,{children:`Result:`}),h.lines>3&&(0,E.jsx)(S,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>c(!s),children:s?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ue,{size:12}),`Hide`]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(de,{size:12}),`Show`]})})]}),(0,E.jsx)(`div`,{className:s?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:h.json})]})})]})]})}function ka({parts:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){let[a,o]=(0,T.useState)(!1),s=e.some(e=>e.state!==`output-available`&&e.state!==`output-error`),c=e.some(e=>e.state===`output-error`||e.state===`output-available`&&e.output?.error),l=e.length===1?Qr(e[0]):void 0,u=l&&Ta(l)?.icon||ft,d=l??`${e.length} tools`;return(0,E.jsxs)(`div`,{className:`tool-group`,children:[(0,E.jsxs)(`button`,{type:`button`,className:`tool-group-summary`,"aria-expanded":a,onClick:()=>o(!a),children:[a?(0,E.jsx)(de,{size:14}):(0,E.jsx)(Je,{size:14}),(0,E.jsx)(u,{size:14}),(0,E.jsx)(`span`,{children:s?`Using ${d}...`:`Used ${d}`}),(0,E.jsx)(`span`,{className:`tool-group-status`,children:s?(0,E.jsx)(Ye,{size:14,className:`animate-spin`}):c?(0,E.jsx)(st,{size:14,className:`text-destructive`}):(0,E.jsx)(le,{size:14})})]}),a&&e.map(e=>(0,E.jsx)(Oa,{part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(e.toolCallId)},e.toolCallId))]})}function Aa({message:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){return e.parts?.some(e=>Jr(e)&&e.text.length>0||G(e))?(0,E.jsxs)(ce.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`message-bubble ${e.role===`user`?`user`:`assistant`}`,children:[(0,E.jsx)(`div`,{className:`avatar`,children:e.role===`user`?(0,E.jsx)(Ae,{size:18}):(0,E.jsx)(se,{size:18})}),(0,E.jsx)(`div`,{className:`content`,children:Da(e.parts).map(e=>{if(e.kind===`tool-group`)return(0,E.jsx)(ka,{parts:e.parts,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i},e.parts[0].toolCallId);let{part:a,index:o}=e;return Jr(a)?(0,E.jsx)(`div`,{className:`text-block`,children:a.text},o):G(a)?(0,E.jsx)(Oa,{part:a,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(a.toolCallId)},o):null})})]},e.id):null}function ja(e,t){if(e!==`submitted`&&e!==`streaming`)return!1;if(t?.role!==`assistant`)return!0;let n=t.parts?.at(-1);return n?Jr(n)?n.state!==`streaming`||n.text.length===0:!G(n)||n.state===`output-available`||n.state===`output-error`:!0}function Ma(){return(0,E.jsxs)(ce.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.2},className:`message-bubble assistant`,children:[(0,E.jsx)(`div`,{className:`avatar`,children:(0,E.jsx)(se,{size:18})}),(0,E.jsxs)(`div`,{className:`content thinking-indicator`,role:`status`,"aria-label":`Harper Agent is thinking`,children:[(0,E.jsx)(`span`,{className:`thinking-dot`}),(0,E.jsx)(`span`,{className:`thinking-dot`}),(0,E.jsx)(`span`,{className:`thinking-dot`})]})]})}function Na(e){return ie({queryKey:[`getMyUsage`,e],queryFn:async()=>{let{data:t}=await x.get(`/Chat/Usage/${e}`);return t}})}function Pa(){let{organizationId:e}=te({strict:!1});return re(Na(e))}function Fa(){let{data:e,isLoading:t,error:n}=Pa();if(t||n||!e)return null;let{usageUSD:r,monthlyLimitUSD:i,usageBarPercent:a}=e,o=e=>new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`}).format(e);return(0,E.jsxs)(`div`,{className:`usage-container`,children:[(0,E.jsxs)(`div`,{className:`usage-info`,children:[(0,E.jsx)(`span`,{children:`Monthly Org Usage`}),(0,E.jsxs)(`span`,{children:[o(r),` / `,o(i)]}),(0,E.jsxs)(`span`,{children:[Math.round(a),`%`]})]}),(0,E.jsx)(`div`,{className:`usage-bar-bg`,children:(0,E.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${a}%`}})})]})}function Ia({autoFocus:e,closeChat:t}){let n=te({strict:!1}),{organizationId:r}=n,[i,a]=ke(`ApplicationChat`,``),[o,s]=(0,T.useState)(!0),[c,l]=(0,T.useState)({}),[u,d]=(0,T.useState)(new Set),[f,p]=Ee(Te.ChatAlwaysApprovedTools,[]),m=new Set(f),h=nt(),g=De(),_=ne(),{messages:v,sendMessage:ee,status:y,addToolOutput:b,setMessages:x}=yi({transport:ci(r),generateId:A(),sendAutomaticallyWhen:si,onFinish(){_.invalidateQueries({queryKey:[`getMyUsage`]})},async onToolCall({toolCall:e}){if(e.dynamic)return;let t=Ta(e.toolName);if(t){if(t.requiresApproval&&!m.has(e.toolName)){let t={type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input};l(n=>({...n,[e.toolCallId]:t}));return}let r=await t.execute({input:e.input,instanceClientParams:g,baseURL:h,params:n});b({tool:e.toolName,toolCallId:e.toolCallId,output:r})}}}),S=(0,T.useCallback)(async e=>{let t=c[e];if(t){d(t=>{let n=new Set(t);return n.add(e),n});try{let r=Ta(t.toolName);if(r){let i=await r.execute({input:t.input,instanceClientParams:g,baseURL:h,params:n});b({tool:t.toolName,toolCallId:t.toolCallId,output:i}),l(t=>{let n={...t};return delete n[e],n})}}finally{d(t=>{let n=new Set(t);return n.delete(e),n})}}},[c,g,h,b,n]),re=(0,T.useCallback)(e=>{let t=c[e];t&&(b({tool:t.toolName,toolCallId:t.toolCallId,output:{error:`User denied the tool execution.`}}),l(t=>{let n={...t};return delete n[e],n}))},[c,b]),ie=(0,T.useCallback)(async e=>{let t=c[e];t&&(p(e=>Le([...e,t.toolName])),await S(e))},[c,p,S]);(0,T.useEffect)(()=>{(async()=>{try{let e=await ht();Array.isArray(e)&&x(e)}catch(e){console.error(`Failed to fetch initial messages:`,e)}finally{s(!1)}})()},[x]);let ae=y===`streaming`||y===`submitted`,oe=(0,T.useRef)(null);return(0,T.useEffect)(()=>{oe.current?.scrollIntoView({behavior:`smooth`})},[v]),(0,E.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,E.jsxs)(`div`,{className:`flex items-start justify-between gap-6 px-4 py-2.5 border-b border-border bg-card`,children:[(0,E.jsxs)(`div`,{className:`flex flex-col gap-1 min-w-0 flex-1`,children:[(0,E.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,E.jsx)(se,{className:`text-primary`,size:20}),(0,E.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Harper Agent`})]}),(0,E.jsx)(Fa,{})]}),(0,E.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,E.jsx)(mt,{setMessages:x}),(0,E.jsx)(`button`,{onClick:t,className:`p-1 hover:bg-accent rounded-md transition-colors text-muted-foreground hover:text-foreground`,title:`Close chat`,children:(0,E.jsx)(fe,{size:20})})]})]}),(0,E.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,E.jsxs)(`div`,{className:`chat-interface h-full w-full`,children:[(0,E.jsxs)(`div`,{className:`messages-area`,children:[o&&(0,E.jsx)(xi,{}),!o&&v.length===0&&(0,E.jsxs)(`div`,{className:`empty-state`,children:[(0,E.jsx)(se,{size:48}),(0,E.jsx)(`p`,{children:`Ask me to create a Harper app!`})]}),v.map(e=>(0,E.jsx)(Aa,{message:e,onApprove:S,onDeny:re,onAlwaysApprove:ie,approvingToolCallIds:u},e.id)),ja(y,v.at(-1))&&(0,E.jsx)(Ma,{}),(0,E.jsx)(`div`,{ref:oe})]}),(0,E.jsx)(bi,{input:i,setInput:a,onSubmit:e=>{e.preventDefault(),i.trim()&&!ae&&!o&&(ee({text:i}),a(``))},disabled:o,autoFocus:e})]})})]})}export{Ia as Chat};
|
|
1949
|
-
//# sourceMappingURL=Chat-
|
|
1949
|
+
//# sourceMappingURL=Chat-aApwhRmz.js.map
|