blun-king-cli 9.1.19 → 9.1.20
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/update-notice.js +106 -7
- package/blun.mjs +2212 -361
- package/package.json +1 -1
package/blun.mjs
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// BLUN_BUILD_INPUT_SHA256:
|
|
2
|
+
// BLUN_BUILD_INPUT_SHA256:174c2b539d18926415abba5d8148da0982699f4c5f397fc12a30c3d6718ac8ea
|
|
3
3
|
import { fileURLToPath as __cjsShimFileURLToPath } from 'node:url';
|
|
4
4
|
import { dirname as __cjsShimDirname } from 'node:path';
|
|
5
5
|
const __filename = __cjsShimFileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = __cjsShimDirname(__filename);
|
|
7
7
|
import { createRequire } from "node:module";
|
|
8
8
|
import crypto$1, { createHash, randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
|
|
9
|
-
import * as fs$
|
|
9
|
+
import * as fs$16 from "node:fs";
|
|
10
10
|
import Kt, { accessSync, appendFileSync, chmodSync, closeSync, constants, copyFileSync, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, promises, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
|
|
11
|
-
import * as path$
|
|
11
|
+
import * as path$16 from "node:path";
|
|
12
12
|
import path, { basename, dirname, extname, isAbsolute, join, normalize, posix, relative, resolve, sep, win32 } from "node:path";
|
|
13
13
|
import { Blob as Blob$1, Buffer as Buffer$1, File as File$1 } from "node:buffer";
|
|
14
14
|
import * as nodeOs from "node:os";
|
|
15
15
|
import os, { arch, homedir, hostname, networkInterfaces, platform, release, tmpdir, type, userInfo } from "node:os";
|
|
16
|
-
import
|
|
16
|
+
import ro, { access, appendFile, chmod, constants as constants$1, copyFile, cp, link, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
17
17
|
import { execFile, execFileSync, execSync, spawn, spawnSync } from "node:child_process";
|
|
18
18
|
import * as sysPath from "path";
|
|
19
|
-
import
|
|
19
|
+
import js, { basename as basename$1, dirname as dirname$1, join as join$1, parse } from "path";
|
|
20
20
|
import I, { existsSync as existsSync$1, promises as promises$1, readdirSync as readdirSync$1, stat as stat$1, statSync as statSync$1, unwatchFile, watch, watchFile } from "fs";
|
|
21
21
|
import { Readable } from "stream";
|
|
22
22
|
import zi from "assert";
|
|
@@ -1167,7 +1167,7 @@ function normalizeBlunToolSchema(schema) {
|
|
|
1167
1167
|
}
|
|
1168
1168
|
function ensureBlunPropertyTypes(schema) {
|
|
1169
1169
|
const normalized = cloneJsonValue(schema);
|
|
1170
|
-
if (!isRecord$
|
|
1170
|
+
if (!isRecord$23(normalized)) throw new Error("JSON Schema root must normalize to an object.");
|
|
1171
1171
|
recurseSchema(normalized);
|
|
1172
1172
|
return normalized;
|
|
1173
1173
|
}
|
|
@@ -1228,7 +1228,7 @@ function resolveLocalJsonPointer(root, ref) {
|
|
|
1228
1228
|
let current = root;
|
|
1229
1229
|
for (const rawPart of ref.slice(2).split("/")) {
|
|
1230
1230
|
const part = unescapeJsonPointerPart(rawPart);
|
|
1231
|
-
if (isRecord$
|
|
1231
|
+
if (isRecord$23(current)) {
|
|
1232
1232
|
if (!hasOwn(current, part)) return { found: false };
|
|
1233
1233
|
current = current[part];
|
|
1234
1234
|
} else if (Array.isArray(current)) {
|
|
@@ -1250,20 +1250,20 @@ function parseJsonPointerArrayIndex(part) {
|
|
|
1250
1250
|
return Number(part);
|
|
1251
1251
|
}
|
|
1252
1252
|
function recurseSchema(node) {
|
|
1253
|
-
if (!isRecord$
|
|
1253
|
+
if (!isRecord$23(node)) return;
|
|
1254
1254
|
visitChildSchemas(node, normalizeProperty);
|
|
1255
1255
|
}
|
|
1256
1256
|
function visitChildSchemas(node, visit) {
|
|
1257
1257
|
for (const { key, kind } of CHILD_SCHEMA_SLOTS) {
|
|
1258
1258
|
const value = node[key];
|
|
1259
1259
|
if (kind === "single") {
|
|
1260
|
-
if (isRecord$
|
|
1260
|
+
if (isRecord$23(value)) visit(value);
|
|
1261
1261
|
} else if (kind === "array") {
|
|
1262
1262
|
if (Array.isArray(value)) for (const item of value) visit(item);
|
|
1263
1263
|
} else if (kind === "map") {
|
|
1264
|
-
if (isRecord$
|
|
1264
|
+
if (isRecord$23(value)) for (const item of Object.values(value)) visit(item);
|
|
1265
1265
|
} else if (kind === "schema-or-array") {
|
|
1266
|
-
if (isRecord$
|
|
1266
|
+
if (isRecord$23(value)) visit(value);
|
|
1267
1267
|
else if (Array.isArray(value)) for (const item of value) visit(item);
|
|
1268
1268
|
}
|
|
1269
1269
|
}
|
|
@@ -1275,7 +1275,7 @@ function childSchemaKeysForParentType(parentType) {
|
|
|
1275
1275
|
});
|
|
1276
1276
|
}
|
|
1277
1277
|
function normalizeProperty(node) {
|
|
1278
|
-
if (!isRecord$
|
|
1278
|
+
if (!isRecord$23(node)) return;
|
|
1279
1279
|
if (!hasOwn(node, "type") && !hasAnyKey(node, TYPE_COMPLETION_SKIP_KEYS)) {
|
|
1280
1280
|
const enumValues = node["enum"];
|
|
1281
1281
|
if (Array.isArray(enumValues) && enumValues.length > 0) node["type"] = inferTypeFromValues(enumValues);
|
|
@@ -1359,14 +1359,14 @@ function hasAnyKey(obj, keys) {
|
|
|
1359
1359
|
}
|
|
1360
1360
|
function cloneJsonValue(value) {
|
|
1361
1361
|
if (Array.isArray(value)) return value.map((item) => cloneJsonValue(item));
|
|
1362
|
-
if (isRecord$
|
|
1362
|
+
if (isRecord$23(value)) {
|
|
1363
1363
|
const cloned = {};
|
|
1364
1364
|
for (const [key, child] of Object.entries(value)) cloned[key] = cloneJsonValue(child);
|
|
1365
1365
|
return cloned;
|
|
1366
1366
|
}
|
|
1367
1367
|
return value;
|
|
1368
1368
|
}
|
|
1369
|
-
function isRecord$
|
|
1369
|
+
function isRecord$23(value) {
|
|
1370
1370
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1371
1371
|
}
|
|
1372
1372
|
function hasOwn(obj, key) {
|
|
@@ -1587,7 +1587,7 @@ function isProviderRateLimitError(error) {
|
|
|
1587
1587
|
if (error instanceof APIProviderRateLimitError) return true;
|
|
1588
1588
|
const statusCode = getStatusCode(error);
|
|
1589
1589
|
if (statusCode !== void 0) return statusCode === 429;
|
|
1590
|
-
const lowerMessage = errorMessage$
|
|
1590
|
+
const lowerMessage = errorMessage$13(error).toLowerCase();
|
|
1591
1591
|
return PROVIDER_RATE_LIMIT_MESSAGE_PATTERNS.some((pattern) => pattern.test(lowerMessage));
|
|
1592
1592
|
}
|
|
1593
1593
|
function getStatusCode(error) {
|
|
@@ -1605,7 +1605,7 @@ function getStatusCode(error) {
|
|
|
1605
1605
|
const responseStatus = responseRecord["status"];
|
|
1606
1606
|
return typeof responseStatus === "number" ? responseStatus : void 0;
|
|
1607
1607
|
}
|
|
1608
|
-
function errorMessage$
|
|
1608
|
+
function errorMessage$13(error) {
|
|
1609
1609
|
return error instanceof Error ? error.message : String(error);
|
|
1610
1610
|
}
|
|
1611
1611
|
var ChatProviderError, APIConnectionError, APITimeoutError, APIStatusError, APIContextOverflowError, APIProviderRateLimitError, APIPaymentRequiredError, APIEmptyResponseError, CompactionStallError$1, NETWORK_RE, TIMEOUT_RE, CONTEXT_OVERFLOW_MESSAGE_PATTERNS, PROVIDER_RATE_LIMIT_MESSAGE_PATTERNS, PROVIDER_QUOTA_EXHAUSTED_MESSAGE_PATTERN, PROVIDER_QUOTA_EXHAUSTED_CONTEXT_PATTERNS, TOOL_EXCHANGE_ADJACENCY_MESSAGE_PATTERNS, STRUCTURAL_REQUEST_MESSAGE_PATTERNS;
|
|
@@ -1824,7 +1824,7 @@ function retryAfterHeaderMs(headers) {
|
|
|
1824
1824
|
const fromDate = Math.max(0, retryAt - Date.now());
|
|
1825
1825
|
return fromDate <= MAX_RETRY_DELAY_MS ? fromDate : null;
|
|
1826
1826
|
}
|
|
1827
|
-
async function readJson(response) {
|
|
1827
|
+
async function readJson$1(response) {
|
|
1828
1828
|
const body = await response.text();
|
|
1829
1829
|
if (body.trim().length === 0) throw new ChatProviderError("Provider returned an empty JSON response.");
|
|
1830
1830
|
try {
|
|
@@ -1924,7 +1924,7 @@ var init_fetch_http_client = __esmMin((() => {
|
|
|
1924
1924
|
signal: options?.signal
|
|
1925
1925
|
}, options?.maxRetries);
|
|
1926
1926
|
if (isStream) return parseServerSentJson(response);
|
|
1927
|
-
return readJson(response);
|
|
1927
|
+
return readJson$1(response);
|
|
1928
1928
|
}
|
|
1929
1929
|
async uploadFile(params, options) {
|
|
1930
1930
|
const form = new FormData();
|
|
@@ -1932,7 +1932,7 @@ var init_fetch_http_client = __esmMin((() => {
|
|
|
1932
1932
|
form.append("file", params.file);
|
|
1933
1933
|
const headers = this.requestHeaders();
|
|
1934
1934
|
headers.delete("content-type");
|
|
1935
|
-
const uploaded = await readJson(await this.fetchWithRetries("/files", {
|
|
1935
|
+
const uploaded = await readJson$1(await this.fetchWithRetries("/files", {
|
|
1936
1936
|
method: "POST",
|
|
1937
1937
|
headers,
|
|
1938
1938
|
body: form,
|
|
@@ -2072,11 +2072,11 @@ var init_blun_files = __esmMin((() => {
|
|
|
2072
2072
|
async uploadVideo(input, options) {
|
|
2073
2073
|
let file;
|
|
2074
2074
|
if (typeof input === "string") {
|
|
2075
|
-
if (!fs$
|
|
2076
|
-
const filename = path$
|
|
2075
|
+
if (!fs$16.existsSync(input)) throw new ChatProviderError(`Video file not found: ${input}`);
|
|
2076
|
+
const filename = path$16.basename(input);
|
|
2077
2077
|
const mimeType = guessMimeTypeFromExt(filename);
|
|
2078
2078
|
if (mimeType === void 0 || !mimeType.startsWith("video/")) throw new ChatProviderError(`BlunFiles.uploadVideo: file extension does not indicate a video type: ${filename}`);
|
|
2079
|
-
const data = await fs$
|
|
2079
|
+
const data = await fs$16.promises.readFile(input);
|
|
2080
2080
|
file = new File$1([new Blob$1([new Uint8Array(data)], { type: mimeType })], filename, { type: mimeType });
|
|
2081
2081
|
} else {
|
|
2082
2082
|
if (!input.mimeType.startsWith("video/")) throw new ChatProviderError(`Expected a video mime type, got ${input.mimeType}`);
|
|
@@ -5436,16 +5436,16 @@ function esc(str) {
|
|
|
5436
5436
|
function slugify(input) {
|
|
5437
5437
|
return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
5438
5438
|
}
|
|
5439
|
-
function isObject$
|
|
5439
|
+
function isObject$5(data) {
|
|
5440
5440
|
return typeof data === "object" && data !== null && !Array.isArray(data);
|
|
5441
5441
|
}
|
|
5442
5442
|
function isPlainObject$4(o) {
|
|
5443
|
-
if (isObject$
|
|
5443
|
+
if (isObject$5(o) === false) return false;
|
|
5444
5444
|
const ctor = o.constructor;
|
|
5445
5445
|
if (ctor === void 0) return true;
|
|
5446
5446
|
if (typeof ctor !== "function") return true;
|
|
5447
5447
|
const prot = ctor.prototype;
|
|
5448
|
-
if (isObject$
|
|
5448
|
+
if (isObject$5(prot) === false) return false;
|
|
5449
5449
|
if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
|
|
5450
5450
|
return true;
|
|
5451
5451
|
}
|
|
@@ -5454,7 +5454,7 @@ function shallowClone(o) {
|
|
|
5454
5454
|
if (Array.isArray(o)) return [...o];
|
|
5455
5455
|
return o;
|
|
5456
5456
|
}
|
|
5457
|
-
function escapeRegex$
|
|
5457
|
+
function escapeRegex$3(str) {
|
|
5458
5458
|
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
5459
5459
|
}
|
|
5460
5460
|
function clone$1(inst, def, params) {
|
|
@@ -6201,7 +6201,7 @@ var init_checks$2 = __esmMin((() => {
|
|
|
6201
6201
|
});
|
|
6202
6202
|
$ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
|
|
6203
6203
|
$ZodCheck.init(inst, def);
|
|
6204
|
-
const escapedRegex = escapeRegex$
|
|
6204
|
+
const escapedRegex = escapeRegex$3(def.includes);
|
|
6205
6205
|
const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
|
|
6206
6206
|
def.pattern = pattern;
|
|
6207
6207
|
inst._zod.onattach.push((inst) => {
|
|
@@ -6224,7 +6224,7 @@ var init_checks$2 = __esmMin((() => {
|
|
|
6224
6224
|
});
|
|
6225
6225
|
$ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
|
|
6226
6226
|
$ZodCheck.init(inst, def);
|
|
6227
|
-
const pattern = new RegExp(`^${escapeRegex$
|
|
6227
|
+
const pattern = new RegExp(`^${escapeRegex$3(def.prefix)}.*`);
|
|
6228
6228
|
def.pattern ?? (def.pattern = pattern);
|
|
6229
6229
|
inst._zod.onattach.push((inst) => {
|
|
6230
6230
|
const bag = inst._zod.bag;
|
|
@@ -6246,7 +6246,7 @@ var init_checks$2 = __esmMin((() => {
|
|
|
6246
6246
|
});
|
|
6247
6247
|
$ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
|
|
6248
6248
|
$ZodCheck.init(inst, def);
|
|
6249
|
-
const pattern = new RegExp(`.*${escapeRegex$
|
|
6249
|
+
const pattern = new RegExp(`.*${escapeRegex$3(def.suffix)}$`);
|
|
6250
6250
|
def.pattern ?? (def.pattern = pattern);
|
|
6251
6251
|
inst._zod.onattach.push((inst) => {
|
|
6252
6252
|
const bag = inst._zod.bag;
|
|
@@ -7008,7 +7008,7 @@ var init_schemas$2 = __esmMin((() => {
|
|
|
7008
7008
|
}
|
|
7009
7009
|
return propValues;
|
|
7010
7010
|
});
|
|
7011
|
-
const isObject = isObject$
|
|
7011
|
+
const isObject = isObject$5;
|
|
7012
7012
|
const catchall = def.catchall;
|
|
7013
7013
|
let value;
|
|
7014
7014
|
inst._zod.parse = (payload, ctx) => {
|
|
@@ -7108,7 +7108,7 @@ var init_schemas$2 = __esmMin((() => {
|
|
|
7108
7108
|
return (payload, ctx) => fn(shape, payload, ctx);
|
|
7109
7109
|
};
|
|
7110
7110
|
let fastpass;
|
|
7111
|
-
const isObject = isObject$
|
|
7111
|
+
const isObject = isObject$5;
|
|
7112
7112
|
const jit = !globalConfig.jitless;
|
|
7113
7113
|
const fastEnabled = jit && allowsEval.value;
|
|
7114
7114
|
const catchall = def.catchall;
|
|
@@ -7203,7 +7203,7 @@ var init_schemas$2 = __esmMin((() => {
|
|
|
7203
7203
|
});
|
|
7204
7204
|
inst._zod.parse = (payload, ctx) => {
|
|
7205
7205
|
const input = payload.value;
|
|
7206
|
-
if (!isObject$
|
|
7206
|
+
if (!isObject$5(input)) {
|
|
7207
7207
|
payload.issues.push({
|
|
7208
7208
|
code: "invalid_type",
|
|
7209
7209
|
expected: "object",
|
|
@@ -7341,7 +7341,7 @@ var init_schemas$2 = __esmMin((() => {
|
|
|
7341
7341
|
const values = getEnumValues(def.entries);
|
|
7342
7342
|
const valuesSet = new Set(values);
|
|
7343
7343
|
inst._zod.values = valuesSet;
|
|
7344
|
-
inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex$
|
|
7344
|
+
inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex$3(o) : o.toString()).join("|")})$`);
|
|
7345
7345
|
inst._zod.parse = (payload, _ctx) => {
|
|
7346
7346
|
const input = payload.value;
|
|
7347
7347
|
if (valuesSet.has(input)) return payload;
|
|
@@ -7359,7 +7359,7 @@ var init_schemas$2 = __esmMin((() => {
|
|
|
7359
7359
|
if (def.values.length === 0) throw new Error("Cannot create literal schema with no valid values");
|
|
7360
7360
|
const values = new Set(def.values);
|
|
7361
7361
|
inst._zod.values = values;
|
|
7362
|
-
inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex$
|
|
7362
|
+
inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex$3(o) : o ? escapeRegex$3(o.toString()) : String(o)).join("|")})$`);
|
|
7363
7363
|
inst._zod.parse = (payload, _ctx) => {
|
|
7364
7364
|
const input = payload.value;
|
|
7365
7365
|
if (values.has(input)) return payload;
|
|
@@ -9987,6 +9987,7 @@ var init_schema = __esmMin((() => {
|
|
|
9987
9987
|
ServicesConfigSchema = object({
|
|
9988
9988
|
blunSearch: BlunServiceConfigSchema.optional(),
|
|
9989
9989
|
blunFetch: BlunServiceConfigSchema.optional(),
|
|
9990
|
+
blunMedia: BlunServiceConfigSchema.optional(),
|
|
9990
9991
|
visionReader: VisionReaderConfigSchema.optional()
|
|
9991
9992
|
});
|
|
9992
9993
|
McpServerCommonFields = {
|
|
@@ -10081,6 +10082,7 @@ var init_schema = __esmMin((() => {
|
|
|
10081
10082
|
ServicesConfigPatchSchema = object({
|
|
10082
10083
|
blunSearch: BlunServiceConfigPatchSchema.optional(),
|
|
10083
10084
|
blunFetch: BlunServiceConfigPatchSchema.optional(),
|
|
10085
|
+
blunMedia: BlunServiceConfigPatchSchema.optional(),
|
|
10084
10086
|
visionReader: VisionReaderConfigPatchSchema.optional()
|
|
10085
10087
|
});
|
|
10086
10088
|
BlunConfigPatchSchema = object({
|
|
@@ -10431,7 +10433,7 @@ function tokenFromWire(wire) {
|
|
|
10431
10433
|
var init_types$17 = __esmMin((() => {}));
|
|
10432
10434
|
//#endregion
|
|
10433
10435
|
//#region ../../packages/oauth/src/utils.ts
|
|
10434
|
-
function isRecord$
|
|
10436
|
+
function isRecord$22(value) {
|
|
10435
10437
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10436
10438
|
}
|
|
10437
10439
|
var init_utils$1 = __esmMin((() => {}));
|
|
@@ -10755,7 +10757,7 @@ var init_storage = __esmMin((() => {
|
|
|
10755
10757
|
} catch {
|
|
10756
10758
|
return;
|
|
10757
10759
|
}
|
|
10758
|
-
if (!isRecord$
|
|
10760
|
+
if (!isRecord$22(parsed)) return void 0;
|
|
10759
10761
|
return tokenFromWire(parsed);
|
|
10760
10762
|
}
|
|
10761
10763
|
async save(name, token) {
|
|
@@ -10849,15 +10851,15 @@ function extractApiErrorMessage(value) {
|
|
|
10849
10851
|
}
|
|
10850
10852
|
return;
|
|
10851
10853
|
}
|
|
10852
|
-
if (!isRecord$
|
|
10854
|
+
if (!isRecord$22(value)) return void 0;
|
|
10853
10855
|
for (const key of DIRECT_ERROR_KEYS) {
|
|
10854
10856
|
const message = stringField$4(value, key);
|
|
10855
10857
|
if (message !== void 0) return message;
|
|
10856
10858
|
}
|
|
10857
10859
|
const error = value["error"];
|
|
10858
|
-
const errorString = nonEmptyString$
|
|
10860
|
+
const errorString = nonEmptyString$7(error);
|
|
10859
10861
|
if (errorString !== void 0) return errorString;
|
|
10860
|
-
if (isRecord$
|
|
10862
|
+
if (isRecord$22(error)) for (const key of NESTED_ERROR_KEYS) {
|
|
10861
10863
|
const message = stringField$4(error, key);
|
|
10862
10864
|
if (message !== void 0) return message;
|
|
10863
10865
|
}
|
|
@@ -10877,9 +10879,9 @@ async function readApiErrorMessage(response, fallback) {
|
|
|
10877
10879
|
return extractApiErrorMessage(parsed) ?? fallback;
|
|
10878
10880
|
}
|
|
10879
10881
|
function stringField$4(record, key) {
|
|
10880
|
-
return nonEmptyString$
|
|
10882
|
+
return nonEmptyString$7(record[key]);
|
|
10881
10883
|
}
|
|
10882
|
-
function nonEmptyString$
|
|
10884
|
+
function nonEmptyString$7(value) {
|
|
10883
10885
|
if (typeof value !== "string") return void 0;
|
|
10884
10886
|
const trimmed = value.trim();
|
|
10885
10887
|
return trimmed.length > 0 ? trimmed : void 0;
|
|
@@ -10947,7 +10949,7 @@ async function postForm(url, params, deviceHeaders, options) {
|
|
|
10947
10949
|
let data = {};
|
|
10948
10950
|
try {
|
|
10949
10951
|
const parsed = await response.json();
|
|
10950
|
-
if (isRecord$
|
|
10952
|
+
if (isRecord$22(parsed)) data = parsed;
|
|
10951
10953
|
} catch {}
|
|
10952
10954
|
return {
|
|
10953
10955
|
status,
|
|
@@ -11423,7 +11425,7 @@ var require_clone$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
11423
11425
|
//#endregion
|
|
11424
11426
|
//#region ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/graceful-fs.js
|
|
11425
11427
|
var require_graceful_fs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
11426
|
-
var fs$
|
|
11428
|
+
var fs$15 = __require("fs");
|
|
11427
11429
|
var polyfills = require_polyfills();
|
|
11428
11430
|
var legacy = require_legacy_streams();
|
|
11429
11431
|
var clone = require_clone$1();
|
|
@@ -11452,36 +11454,36 @@ var require_graceful_fs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
11452
11454
|
m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
|
|
11453
11455
|
console.error(m);
|
|
11454
11456
|
};
|
|
11455
|
-
if (!fs$
|
|
11456
|
-
publishQueue(fs$
|
|
11457
|
-
fs$
|
|
11457
|
+
if (!fs$15[gracefulQueue]) {
|
|
11458
|
+
publishQueue(fs$15, global[gracefulQueue] || []);
|
|
11459
|
+
fs$15.close = (function(fs$close) {
|
|
11458
11460
|
function close(fd, cb) {
|
|
11459
|
-
return fs$close.call(fs$
|
|
11461
|
+
return fs$close.call(fs$15, fd, function(err) {
|
|
11460
11462
|
if (!err) resetQueue();
|
|
11461
11463
|
if (typeof cb === "function") cb.apply(this, arguments);
|
|
11462
11464
|
});
|
|
11463
11465
|
}
|
|
11464
11466
|
Object.defineProperty(close, previousSymbol, { value: fs$close });
|
|
11465
11467
|
return close;
|
|
11466
|
-
})(fs$
|
|
11467
|
-
fs$
|
|
11468
|
+
})(fs$15.close);
|
|
11469
|
+
fs$15.closeSync = (function(fs$closeSync) {
|
|
11468
11470
|
function closeSync(fd) {
|
|
11469
|
-
fs$closeSync.apply(fs$
|
|
11471
|
+
fs$closeSync.apply(fs$15, arguments);
|
|
11470
11472
|
resetQueue();
|
|
11471
11473
|
}
|
|
11472
11474
|
Object.defineProperty(closeSync, previousSymbol, { value: fs$closeSync });
|
|
11473
11475
|
return closeSync;
|
|
11474
|
-
})(fs$
|
|
11476
|
+
})(fs$15.closeSync);
|
|
11475
11477
|
if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) process.on("exit", function() {
|
|
11476
|
-
debug(fs$
|
|
11477
|
-
__require("assert").equal(fs$
|
|
11478
|
+
debug(fs$15[gracefulQueue]);
|
|
11479
|
+
__require("assert").equal(fs$15[gracefulQueue].length, 0);
|
|
11478
11480
|
});
|
|
11479
11481
|
}
|
|
11480
|
-
if (!global[gracefulQueue]) publishQueue(global, fs$
|
|
11481
|
-
module.exports = patch(clone(fs$
|
|
11482
|
-
if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$
|
|
11483
|
-
module.exports = patch(fs$
|
|
11484
|
-
fs$
|
|
11482
|
+
if (!global[gracefulQueue]) publishQueue(global, fs$15[gracefulQueue]);
|
|
11483
|
+
module.exports = patch(clone(fs$15));
|
|
11484
|
+
if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$15.__patched) {
|
|
11485
|
+
module.exports = patch(fs$15);
|
|
11486
|
+
fs$15.__patched = true;
|
|
11485
11487
|
}
|
|
11486
11488
|
function patch(fs) {
|
|
11487
11489
|
polyfills(fs);
|
|
@@ -11736,23 +11738,23 @@ var require_graceful_fs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
11736
11738
|
}
|
|
11737
11739
|
function enqueue(elem) {
|
|
11738
11740
|
debug("ENQUEUE", elem[0].name, elem[1]);
|
|
11739
|
-
fs$
|
|
11741
|
+
fs$15[gracefulQueue].push(elem);
|
|
11740
11742
|
retry();
|
|
11741
11743
|
}
|
|
11742
11744
|
var retryTimer;
|
|
11743
11745
|
function resetQueue() {
|
|
11744
11746
|
var now = Date.now();
|
|
11745
|
-
for (var i = 0; i < fs$
|
|
11746
|
-
fs$
|
|
11747
|
-
fs$
|
|
11747
|
+
for (var i = 0; i < fs$15[gracefulQueue].length; ++i) if (fs$15[gracefulQueue][i].length > 2) {
|
|
11748
|
+
fs$15[gracefulQueue][i][3] = now;
|
|
11749
|
+
fs$15[gracefulQueue][i][4] = now;
|
|
11748
11750
|
}
|
|
11749
11751
|
retry();
|
|
11750
11752
|
}
|
|
11751
11753
|
function retry() {
|
|
11752
11754
|
clearTimeout(retryTimer);
|
|
11753
11755
|
retryTimer = void 0;
|
|
11754
|
-
if (fs$
|
|
11755
|
-
var elem = fs$
|
|
11756
|
+
if (fs$15[gracefulQueue].length === 0) return;
|
|
11757
|
+
var elem = fs$15[gracefulQueue].shift();
|
|
11756
11758
|
var fn = elem[0];
|
|
11757
11759
|
var args = elem[1];
|
|
11758
11760
|
var err = elem[2];
|
|
@@ -11771,7 +11773,7 @@ var require_graceful_fs = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
11771
11773
|
if (sinceAttempt >= Math.min(sinceStart * 1.2, 100)) {
|
|
11772
11774
|
debug("RETRY", fn.name, args);
|
|
11773
11775
|
fn.apply(null, args.concat([startTime]));
|
|
11774
|
-
} else fs$
|
|
11776
|
+
} else fs$15[gracefulQueue].push(elem);
|
|
11775
11777
|
}
|
|
11776
11778
|
if (retryTimer === void 0) retryTimer = setTimeout(retry, 0);
|
|
11777
11779
|
}
|
|
@@ -12123,7 +12125,7 @@ var require_mtime_precision = /* @__PURE__ */ __commonJSMin(((exports, module) =
|
|
|
12123
12125
|
//#endregion
|
|
12124
12126
|
//#region ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/lockfile.js
|
|
12125
12127
|
var require_lockfile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
12126
|
-
const path$
|
|
12128
|
+
const path$15 = __require("path");
|
|
12127
12129
|
const fs = require_graceful_fs();
|
|
12128
12130
|
const retry = require_retry$3();
|
|
12129
12131
|
const onExit = require_signal_exit();
|
|
@@ -12133,7 +12135,7 @@ var require_lockfile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
12133
12135
|
return options.lockfilePath || `${file}.lock`;
|
|
12134
12136
|
}
|
|
12135
12137
|
function resolveCanonicalPath(file, options, callback) {
|
|
12136
|
-
if (!options.realpath) return callback(null, path$
|
|
12138
|
+
if (!options.realpath) return callback(null, path$15.resolve(file));
|
|
12137
12139
|
options.fs.realpath(file, callback);
|
|
12138
12140
|
}
|
|
12139
12141
|
function acquireLock(file, options, callback) {
|
|
@@ -12859,9 +12861,9 @@ function blunContextWindowsUrl(oauthHost) {
|
|
|
12859
12861
|
return `${(oauthHost ?? process.env["BLUN_OAUTH_HOST"] ?? "https://account.blun.ai").replace(/\/+$/, "")}/api/verbrauch/tarife`;
|
|
12860
12862
|
}
|
|
12861
12863
|
function parseManagedContextWindow(payload, plan) {
|
|
12862
|
-
if (!isRecord$
|
|
12864
|
+
if (!isRecord$22(payload)) return void 0;
|
|
12863
12865
|
const contextWindows = payload["kontext"];
|
|
12864
|
-
if (!isRecord$
|
|
12866
|
+
if (!isRecord$22(contextWindows)) return void 0;
|
|
12865
12867
|
const value = contextWindows[plan];
|
|
12866
12868
|
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
|
|
12867
12869
|
}
|
|
@@ -12896,7 +12898,7 @@ function parseManagedUsagePayload(payload) {
|
|
|
12896
12898
|
const plan = typeof rec["plan"] === "string" && rec["plan"].trim().length > 0 ? rec["plan"].trim() : void 0;
|
|
12897
12899
|
const contextWindowTokens = managedContextWindowFrom(rec);
|
|
12898
12900
|
const unlimited = rec["unlimited"] === true;
|
|
12899
|
-
const stand = isRecord$
|
|
12901
|
+
const stand = isRecord$22(rec["stand"]) ? rec["stand"] : void 0;
|
|
12900
12902
|
if (stand !== void 0) for (const [sourceKey, id, label] of ACCOUNT_USAGE_WINDOWS) {
|
|
12901
12903
|
const row = toAccountUsageRow(stand[sourceKey], id, label, unlimited);
|
|
12902
12904
|
if (row !== null) limits.push(row);
|
|
@@ -12906,9 +12908,9 @@ function parseManagedUsagePayload(payload) {
|
|
|
12906
12908
|
const item = rawLimits[idx];
|
|
12907
12909
|
if (!item || typeof item !== "object") continue;
|
|
12908
12910
|
const detailRaw = item["detail"];
|
|
12909
|
-
const detail = isRecord$
|
|
12911
|
+
const detail = isRecord$22(detailRaw) ? detailRaw : item;
|
|
12910
12912
|
const windowRaw = item["window"];
|
|
12911
|
-
const row = toUsageRow(detail, limitLabel(item, detail, isRecord$
|
|
12913
|
+
const row = toUsageRow(detail, limitLabel(item, detail, isRecord$22(windowRaw) ? windowRaw : {}, idx));
|
|
12912
12914
|
if (row !== null) limits.push(row);
|
|
12913
12915
|
}
|
|
12914
12916
|
return {
|
|
@@ -12932,7 +12934,7 @@ function managedContextWindowFrom(payload) {
|
|
|
12932
12934
|
return values.every((value) => value === first) ? first : void 0;
|
|
12933
12935
|
}
|
|
12934
12936
|
function toAccountUsageRow(raw, id, label, accountUnlimited) {
|
|
12935
|
-
if (!isRecord$
|
|
12937
|
+
if (!isRecord$22(raw)) return null;
|
|
12936
12938
|
const used = toInt(raw["verbraucht"]);
|
|
12937
12939
|
const unlimited = accountUnlimited || raw["unlimited"] === true;
|
|
12938
12940
|
const fraction = raw["anteil"];
|
|
@@ -12965,7 +12967,7 @@ function toAccountUsageRow(raw, id, label, accountUnlimited) {
|
|
|
12965
12967
|
};
|
|
12966
12968
|
}
|
|
12967
12969
|
function toUsageRow(raw, defaultLabel) {
|
|
12968
|
-
if (!isRecord$
|
|
12970
|
+
if (!isRecord$22(raw)) return null;
|
|
12969
12971
|
const unlimited = raw["unlimited"] === true;
|
|
12970
12972
|
const limit = toInt(raw["limit"]);
|
|
12971
12973
|
let used = toInt(raw["used"]);
|
|
@@ -13086,7 +13088,7 @@ function isManagedQuotaErrorMessage(message) {
|
|
|
13086
13088
|
return /you(?:'|’)?ve reached your usage limit/.test(normalized) && /billing cycle|quota will be (?:refreshed|reset)|purchase extra usage/.test(normalized);
|
|
13087
13089
|
}
|
|
13088
13090
|
function hasManagedUsageShape(payload) {
|
|
13089
|
-
if (!isRecord$
|
|
13091
|
+
if (!isRecord$22(payload)) return false;
|
|
13090
13092
|
let recognized = false;
|
|
13091
13093
|
if ("context_window_tokens" in payload || "contextWindowTokens" in payload) {
|
|
13092
13094
|
recognized = true;
|
|
@@ -13102,15 +13104,15 @@ function hasManagedUsageShape(payload) {
|
|
|
13102
13104
|
if (!Array.isArray(limits)) return false;
|
|
13103
13105
|
for (let index = 0; index < limits.length; index++) {
|
|
13104
13106
|
const item = limits[index];
|
|
13105
|
-
if (!isRecord$
|
|
13106
|
-
const detail = isRecord$
|
|
13107
|
-
if (toUsageRow(detail, limitLabel(item, detail, isRecord$
|
|
13107
|
+
if (!isRecord$22(item)) return false;
|
|
13108
|
+
const detail = isRecord$22(item["detail"]) ? item["detail"] : item;
|
|
13109
|
+
if (toUsageRow(detail, limitLabel(item, detail, isRecord$22(item["window"]) ? item["window"] : {}, index)) === null) return false;
|
|
13108
13110
|
}
|
|
13109
13111
|
}
|
|
13110
13112
|
if ("stand" in payload) {
|
|
13111
13113
|
recognized = true;
|
|
13112
13114
|
const stand = payload["stand"];
|
|
13113
|
-
if (!isRecord$
|
|
13115
|
+
if (!isRecord$22(stand)) return false;
|
|
13114
13116
|
const windows = ACCOUNT_USAGE_WINDOWS.filter(([sourceKey]) => sourceKey in stand);
|
|
13115
13117
|
if (windows.length === 0) return false;
|
|
13116
13118
|
const unlimited = payload["unlimited"] === true;
|
|
@@ -13206,8 +13208,8 @@ function userExtras(existing, remoteOwnedFields) {
|
|
|
13206
13208
|
return out;
|
|
13207
13209
|
}
|
|
13208
13210
|
function mergeRefreshedModelAlias(existing, remote, remoteOwnedFields) {
|
|
13209
|
-
const current = isRecord$
|
|
13210
|
-
const overrides = cloneOverrides(isRecord$
|
|
13211
|
+
const current = isRecord$22(existing) ? existing : {};
|
|
13212
|
+
const overrides = cloneOverrides(isRecord$22(current["overrides"]) ? current["overrides"] : void 0);
|
|
13211
13213
|
return {
|
|
13212
13214
|
...userExtras(current, remoteOwnedFields),
|
|
13213
13215
|
...remote,
|
|
@@ -13389,7 +13391,7 @@ function parseModelContextLength(item, modelId) {
|
|
|
13389
13391
|
return values[0];
|
|
13390
13392
|
}
|
|
13391
13393
|
function toModelInfo(item) {
|
|
13392
|
-
if (!isRecord$
|
|
13394
|
+
if (!isRecord$22(item) || typeof item["id"] !== "string" || item["id"].length === 0) return;
|
|
13393
13395
|
const contextLength = parseModelContextLength(item, item["id"]);
|
|
13394
13396
|
const displayName = item["display_name"];
|
|
13395
13397
|
const normalizedDisplayName = typeof displayName === "string" && displayName.length > 0 ? displayName : void 0;
|
|
@@ -13476,7 +13478,7 @@ async function fetchManagedBlunCodeModels(options) {
|
|
|
13476
13478
|
throw new Error(message);
|
|
13477
13479
|
}
|
|
13478
13480
|
const payload = await response.json();
|
|
13479
|
-
if (!isRecord$
|
|
13481
|
+
if (!isRecord$22(payload) || !Array.isArray(payload["data"])) throw new Error(`Unexpected models response for ${baseUrl}.`);
|
|
13480
13482
|
return payload["data"].map((item) => toModelInfo(item)).filter((item) => item !== void 0);
|
|
13481
13483
|
}
|
|
13482
13484
|
throw new Error(`Failed to list BLUN models for ${baseUrl}.`);
|
|
@@ -13519,11 +13521,11 @@ function applyManagedBlunCodeConfig(config, options) {
|
|
|
13519
13521
|
apiKey
|
|
13520
13522
|
};
|
|
13521
13523
|
const upstreamKeys = new Set(options.models.map((m) => managedModelKey(m.id)));
|
|
13522
|
-
for (const [key, model] of Object.entries(existingModels)) if (RETIRED_BLUN_MODEL_KEYS.has(key) || isRecord$
|
|
13524
|
+
for (const [key, model] of Object.entries(existingModels)) if (RETIRED_BLUN_MODEL_KEYS.has(key) || isRecord$22(model) && model["provider"] === "managed:blun" && !upstreamKeys.has(key)) delete existingModels[key];
|
|
13523
13525
|
for (const model of options.models) {
|
|
13524
13526
|
const capabilities = capabilitiesForModel(model);
|
|
13525
13527
|
const key = managedModelKey(model.id);
|
|
13526
|
-
const existing = isRecord$
|
|
13528
|
+
const existing = isRecord$22(existingModels[key]) ? existingModels[key] : {};
|
|
13527
13529
|
const supportsAdaptiveThinking = capabilities?.includes("thinking") === true || capabilities?.includes("always_thinking") === true;
|
|
13528
13530
|
existingModels[key] = mergeRefreshedModelAlias(existing, {
|
|
13529
13531
|
provider: BLUN_PROVIDER_NAME$1,
|
|
@@ -13555,6 +13557,10 @@ function applyManagedBlunCodeConfig(config, options) {
|
|
|
13555
13557
|
blunFetch: {
|
|
13556
13558
|
baseUrl: `${auxiliaryBaseUrl}/fetch`,
|
|
13557
13559
|
...serviceCredential
|
|
13560
|
+
},
|
|
13561
|
+
blunMedia: {
|
|
13562
|
+
baseUrl,
|
|
13563
|
+
...serviceCredential
|
|
13558
13564
|
}
|
|
13559
13565
|
};
|
|
13560
13566
|
return {
|
|
@@ -13567,7 +13573,7 @@ function applyManagedBlunCodeLogoutConfig(config) {
|
|
|
13567
13573
|
let removedDefaultModel = false;
|
|
13568
13574
|
const existingModels = config.models ?? {};
|
|
13569
13575
|
for (const [key, model] of Object.entries(existingModels)) {
|
|
13570
|
-
if (!isRecord$
|
|
13576
|
+
if (!isRecord$22(model) || model["provider"] !== "managed:blun") continue;
|
|
13571
13577
|
delete existingModels[key];
|
|
13572
13578
|
if (config.defaultModel === key) removedDefaultModel = true;
|
|
13573
13579
|
}
|
|
@@ -13577,6 +13583,7 @@ function applyManagedBlunCodeLogoutConfig(config) {
|
|
|
13577
13583
|
if (config.services !== void 0) {
|
|
13578
13584
|
delete config.services.blunSearch;
|
|
13579
13585
|
delete config.services.blunFetch;
|
|
13586
|
+
delete config.services.blunMedia;
|
|
13580
13587
|
if (Object.keys(config.services).length === 0) config.services = void 0;
|
|
13581
13588
|
}
|
|
13582
13589
|
}
|
|
@@ -13606,7 +13613,7 @@ function selectDefaultModel(config, models, options) {
|
|
|
13606
13613
|
function canPreserveDefaultModel(existingModels, defaultModel, managedModels) {
|
|
13607
13614
|
if (managedModels.has(defaultModel)) return true;
|
|
13608
13615
|
const existing = existingModels[defaultModel];
|
|
13609
|
-
return isRecord$
|
|
13616
|
+
return isRecord$22(existing) && existing["provider"] !== "managed:blun";
|
|
13610
13617
|
}
|
|
13611
13618
|
function assertPositiveContextLength(model) {
|
|
13612
13619
|
if (!Number.isInteger(model.contextLength) || model.contextLength <= 0) throw new Error(`BLUN model "${model.id}" must include a positive context_length.`);
|
|
@@ -13684,13 +13691,13 @@ function blunManagedQuotaUrl(oauthHost) {
|
|
|
13684
13691
|
return `${(oauthHost ?? process.env["BLUN_OAUTH_HOST"] ?? "https://account.blun.ai").replace(/\/+$/, "")}${MANAGED_QUOTA_PATH}`;
|
|
13685
13692
|
}
|
|
13686
13693
|
function parseManagedQuotaPayload(payload) {
|
|
13687
|
-
if (!isRecord$
|
|
13688
|
-
const plan = nonEmptyString$
|
|
13694
|
+
if (!isRecord$22(payload)) return void 0;
|
|
13695
|
+
const plan = nonEmptyString$6(payload["plan"]);
|
|
13689
13696
|
const paid = payload["bezahlt"];
|
|
13690
13697
|
const creditCents = payload["guthaben_cent"];
|
|
13691
|
-
const billingKind = nonEmptyString$
|
|
13698
|
+
const billingKind = nonEmptyString$6(payload["art"]);
|
|
13692
13699
|
const globalUnlimited = payload["unlimited"];
|
|
13693
|
-
if (plan === void 0 || typeof paid !== "boolean" || !Number.isSafeInteger(creditCents) || creditCents < 0 || billingKind === void 0 || globalUnlimited !== void 0 && typeof globalUnlimited !== "boolean" || !isRecord$
|
|
13700
|
+
if (plan === void 0 || typeof paid !== "boolean" || !Number.isSafeInteger(creditCents) || creditCents < 0 || billingKind === void 0 || globalUnlimited !== void 0 && typeof globalUnlimited !== "boolean" || !isRecord$22(payload["stand"])) return;
|
|
13694
13701
|
if (!hasStrictQuotaStand(payload["stand"], globalUnlimited === true)) return void 0;
|
|
13695
13702
|
const limits = parseManagedUsagePayload(payload).limits;
|
|
13696
13703
|
if (limits.length !== REQUIRED_WINDOWS.length || REQUIRED_WINDOWS.some(([, id]) => limits.filter((row) => row.id === id).length !== 1)) return;
|
|
@@ -13752,7 +13759,7 @@ async function managedQuotaErrorCode(response) {
|
|
|
13752
13759
|
if (response.status !== 403) return "unavailable";
|
|
13753
13760
|
return isManagedQuotaErrorMessage(await readApiErrorMessage(response, "")) ? "unavailable" : "unauthenticated";
|
|
13754
13761
|
}
|
|
13755
|
-
function nonEmptyString$
|
|
13762
|
+
function nonEmptyString$6(value) {
|
|
13756
13763
|
if (typeof value !== "string") return void 0;
|
|
13757
13764
|
const normalized = value.trim();
|
|
13758
13765
|
return normalized.length === 0 ? void 0 : normalized;
|
|
@@ -13760,7 +13767,7 @@ function nonEmptyString$5(value) {
|
|
|
13760
13767
|
function hasStrictQuotaStand(stand, globalUnlimited) {
|
|
13761
13768
|
return REQUIRED_WINDOWS.every(([sourceKey]) => {
|
|
13762
13769
|
const row = stand[sourceKey];
|
|
13763
|
-
if (!isRecord$
|
|
13770
|
+
if (!isRecord$22(row)) return false;
|
|
13764
13771
|
const used = row["verbraucht"];
|
|
13765
13772
|
const rowUnlimited = row["unlimited"];
|
|
13766
13773
|
if (rowUnlimited !== void 0 && typeof rowUnlimited !== "boolean") return false;
|
|
@@ -14312,15 +14319,15 @@ function readModel(config, alias) {
|
|
|
14312
14319
|
const model = config.models?.[alias];
|
|
14313
14320
|
return model === void 0 ? void 0 : model;
|
|
14314
14321
|
}
|
|
14315
|
-
function nonEmptyString$
|
|
14322
|
+
function nonEmptyString$5(value) {
|
|
14316
14323
|
const trimmed = value?.trim();
|
|
14317
14324
|
return trimmed === void 0 || trimmed.length === 0 ? void 0 : trimmed;
|
|
14318
14325
|
}
|
|
14319
14326
|
function providerApiKey$1(provider) {
|
|
14320
|
-
return nonEmptyString$
|
|
14327
|
+
return nonEmptyString$5(provider.apiKey) ?? nonEmptyString$5(provider.env?.["BLUN_API_KEY"]);
|
|
14321
14328
|
}
|
|
14322
14329
|
function providerBaseUrl(provider) {
|
|
14323
|
-
return nonEmptyString$
|
|
14330
|
+
return nonEmptyString$5(provider.baseUrl) ?? nonEmptyString$5(provider.env?.["BLUN_BASE_URL"]);
|
|
14324
14331
|
}
|
|
14325
14332
|
function collectModelIdsForAliases(config, aliasKeys) {
|
|
14326
14333
|
const ids = /* @__PURE__ */ new Set();
|
|
@@ -14386,7 +14393,7 @@ async function refreshProviderModels(host, options = {}) {
|
|
|
14386
14393
|
failed
|
|
14387
14394
|
};
|
|
14388
14395
|
}
|
|
14389
|
-
const managedApiKey = nonEmptyString$
|
|
14396
|
+
const managedApiKey = nonEmptyString$5(managedProvider?.apiKey);
|
|
14390
14397
|
const managedHasOAuth = managedProvider?.oauth !== void 0;
|
|
14391
14398
|
if (managedWanted && managedProvider !== void 0 && managedProvider.type === "blun" && (managedApiKey !== void 0 || managedHasOAuth)) try {
|
|
14392
14399
|
if (managedApiKey !== void 0 && managedHasOAuth) throw new Error("Managed BLUN OAuth and API key credentials are mutually exclusive.");
|
|
@@ -14593,7 +14600,7 @@ async function syncDir(dirPath) {
|
|
|
14593
14600
|
*/
|
|
14594
14601
|
function syncFd(fd) {
|
|
14595
14602
|
return new Promise((resolve, reject) => {
|
|
14596
|
-
fs$
|
|
14603
|
+
fs$16.fsync(fd, (err) => {
|
|
14597
14604
|
if (err) {
|
|
14598
14605
|
reject(err);
|
|
14599
14606
|
return;
|
|
@@ -16051,6 +16058,8 @@ function servicesToToml(services, rawServices) {
|
|
|
16051
16058
|
else delete out["blun_search"];
|
|
16052
16059
|
if (services.blunFetch !== void 0) out["blun_fetch"] = serviceToToml(services.blunFetch);
|
|
16053
16060
|
else delete out["blun_fetch"];
|
|
16061
|
+
if (services.blunMedia !== void 0) out["blun_media"] = serviceToToml(services.blunMedia);
|
|
16062
|
+
else delete out["blun_media"];
|
|
16054
16063
|
if (services.visionReader !== void 0) out["vision_reader"] = visionReaderToToml(services.visionReader);
|
|
16055
16064
|
else delete out["vision_reader"];
|
|
16056
16065
|
return out;
|
|
@@ -20925,11 +20934,11 @@ function parseSkillText(options) {
|
|
|
20925
20934
|
throw error;
|
|
20926
20935
|
}
|
|
20927
20936
|
const frontmatter = parsed.data ?? {};
|
|
20928
|
-
if (!isRecord$
|
|
20937
|
+
if (!isRecord$21(frontmatter)) throw new SkillParseError(`Frontmatter in ${options.skillMdPath} must be a mapping at the top level`);
|
|
20929
20938
|
const metadata = normalizeMetadata(frontmatter);
|
|
20930
20939
|
if (!isSupportedSkillType(metadata.type)) throw new UnsupportedSkillTypeError(metadata.type ?? String(frontmatter["type"]));
|
|
20931
|
-
const name = nonEmptyString$
|
|
20932
|
-
const description = nonEmptyString$
|
|
20940
|
+
const name = nonEmptyString$4(metadata.name);
|
|
20941
|
+
const description = nonEmptyString$4(metadata.description);
|
|
20933
20942
|
if (isDirectorySkill && (name === void 0 || description === void 0)) throw new SkillParseError(`Missing required frontmatter field ${name === void 0 ? "\"name\"" : "\"description\""} in ${options.skillMdPath}`);
|
|
20934
20943
|
const skillPath = posix$2.resolve(options.skillMdPath);
|
|
20935
20944
|
const content = parsed.body.trim();
|
|
@@ -20989,11 +20998,11 @@ function normalizeMetadata(raw) {
|
|
|
20989
20998
|
const key = METADATA_ALIASES[rawKey] ?? rawKey;
|
|
20990
20999
|
out[key] = value;
|
|
20991
21000
|
}
|
|
20992
|
-
const type = nonEmptyString$
|
|
21001
|
+
const type = nonEmptyString$4(out["type"]);
|
|
20993
21002
|
if (type !== void 0) out["type"] = type;
|
|
20994
|
-
const name = nonEmptyString$
|
|
21003
|
+
const name = nonEmptyString$4(out["name"]);
|
|
20995
21004
|
if (name !== void 0) out["name"] = name;
|
|
20996
|
-
const description = nonEmptyString$
|
|
21005
|
+
const description = nonEmptyString$4(out["description"]);
|
|
20997
21006
|
if (description !== void 0) out["description"] = description;
|
|
20998
21007
|
return out;
|
|
20999
21008
|
}
|
|
@@ -21035,10 +21044,10 @@ function tokenizeArgs(raw) {
|
|
|
21035
21044
|
if (hasContent) out.push(current);
|
|
21036
21045
|
return out;
|
|
21037
21046
|
}
|
|
21038
|
-
function nonEmptyString$
|
|
21047
|
+
function nonEmptyString$4(value) {
|
|
21039
21048
|
return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
21040
21049
|
}
|
|
21041
|
-
function isRecord$
|
|
21050
|
+
function isRecord$21(value) {
|
|
21042
21051
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
21043
21052
|
}
|
|
21044
21053
|
var import_regexp_escape, FrontmatterError, SkillParseError, UnsupportedSkillTypeError, FENCE, METADATA_ALIASES;
|
|
@@ -21087,14 +21096,14 @@ var init_parser$1 = __esmMin((() => {
|
|
|
21087
21096
|
function parseCommandText(input) {
|
|
21088
21097
|
const { text, commandPath, pluginId } = input;
|
|
21089
21098
|
const parsed = parseFrontmatter(text);
|
|
21090
|
-
const frontmatter = isRecord$
|
|
21099
|
+
const frontmatter = isRecord$20(parsed.data) ? parsed.data : {};
|
|
21091
21100
|
const baseName = input.fallbackName ?? path.basename(commandPath).replace(/\.md$/i, "");
|
|
21092
|
-
const name = nonEmptyString$
|
|
21101
|
+
const name = nonEmptyString$3(frontmatter["name"]) ?? baseName;
|
|
21093
21102
|
const body = parsed.body.trim();
|
|
21094
21103
|
return {
|
|
21095
21104
|
pluginId,
|
|
21096
21105
|
name,
|
|
21097
|
-
description: nonEmptyString$
|
|
21106
|
+
description: nonEmptyString$3(frontmatter["description"]) ?? descriptionFromBody(body),
|
|
21098
21107
|
body,
|
|
21099
21108
|
path: path.resolve(commandPath)
|
|
21100
21109
|
};
|
|
@@ -21121,7 +21130,7 @@ function expandCommandArguments(body, args) {
|
|
|
21121
21130
|
if (!body.includes("$ARGUMENTS") && args.length > 0) return `${replaced}\n\nARGUMENTS: ${args}`;
|
|
21122
21131
|
return replaced;
|
|
21123
21132
|
}
|
|
21124
|
-
function nonEmptyString$
|
|
21133
|
+
function nonEmptyString$3(value) {
|
|
21125
21134
|
return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
21126
21135
|
}
|
|
21127
21136
|
function descriptionFromBody(body) {
|
|
@@ -21129,7 +21138,7 @@ function descriptionFromBody(body) {
|
|
|
21129
21138
|
if (firstLine === void 0) return "No description provided.";
|
|
21130
21139
|
return firstLine.length > 240 ? `${firstLine.slice(0, 239)}…` : firstLine;
|
|
21131
21140
|
}
|
|
21132
|
-
function isRecord$
|
|
21141
|
+
function isRecord$20(value) {
|
|
21133
21142
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
21134
21143
|
}
|
|
21135
21144
|
var init_commands = __esmMin((() => {
|
|
@@ -25104,7 +25113,7 @@ var require_loader = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
25104
25113
|
};
|
|
25105
25114
|
return _setPrototypeOf(o, p);
|
|
25106
25115
|
}
|
|
25107
|
-
var path$
|
|
25116
|
+
var path$14 = __require("path");
|
|
25108
25117
|
module.exports = /* @__PURE__ */ function(_EmitterObj) {
|
|
25109
25118
|
_inheritsLoose(Loader, _EmitterObj);
|
|
25110
25119
|
function Loader() {
|
|
@@ -25112,7 +25121,7 @@ var require_loader = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
25112
25121
|
}
|
|
25113
25122
|
var _proto = Loader.prototype;
|
|
25114
25123
|
_proto.resolve = function resolve(from, to) {
|
|
25115
|
-
return path$
|
|
25124
|
+
return path$14.resolve(path$14.dirname(from), to);
|
|
25116
25125
|
};
|
|
25117
25126
|
_proto.isRelative = function isRelative(filename) {
|
|
25118
25127
|
return filename.indexOf("./") === 0 || filename.indexOf("../") === 0;
|
|
@@ -26768,8 +26777,8 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
26768
26777
|
};
|
|
26769
26778
|
return _setPrototypeOf(o, p);
|
|
26770
26779
|
}
|
|
26771
|
-
var fs$
|
|
26772
|
-
var path$
|
|
26780
|
+
var fs$14 = __require("fs");
|
|
26781
|
+
var path$13 = __require("path");
|
|
26773
26782
|
var Loader = require_loader();
|
|
26774
26783
|
var PrecompiledLoader = require_precompiled_loader().PrecompiledLoader;
|
|
26775
26784
|
var chokidar;
|
|
@@ -26784,7 +26793,7 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
26784
26793
|
_this.noCache = !!opts.noCache;
|
|
26785
26794
|
if (searchPaths) {
|
|
26786
26795
|
searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths];
|
|
26787
|
-
_this.searchPaths = searchPaths.map(path$
|
|
26796
|
+
_this.searchPaths = searchPaths.map(path$13.normalize);
|
|
26788
26797
|
} else _this.searchPaths = ["."];
|
|
26789
26798
|
if (opts.watch) {
|
|
26790
26799
|
try {
|
|
@@ -26792,10 +26801,10 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
26792
26801
|
} catch (e) {
|
|
26793
26802
|
throw new Error("watch requires chokidar to be installed");
|
|
26794
26803
|
}
|
|
26795
|
-
var paths = _this.searchPaths.filter(fs$
|
|
26804
|
+
var paths = _this.searchPaths.filter(fs$14.existsSync);
|
|
26796
26805
|
var watcher = chokidar.watch(paths);
|
|
26797
26806
|
watcher.on("all", function(event, fullname) {
|
|
26798
|
-
fullname = path$
|
|
26807
|
+
fullname = path$13.resolve(fullname);
|
|
26799
26808
|
if (event === "change" && fullname in _this.pathsToNames) _this.emit("update", _this.pathsToNames[fullname], fullname);
|
|
26800
26809
|
});
|
|
26801
26810
|
watcher.on("error", function(error) {
|
|
@@ -26809,9 +26818,9 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
26809
26818
|
var fullpath = null;
|
|
26810
26819
|
var paths = this.searchPaths;
|
|
26811
26820
|
for (var i = 0; i < paths.length; i++) {
|
|
26812
|
-
var basePath = path$
|
|
26813
|
-
var p = path$
|
|
26814
|
-
if (p.indexOf(basePath) === 0 && fs$
|
|
26821
|
+
var basePath = path$13.resolve(paths[i]);
|
|
26822
|
+
var p = path$13.resolve(paths[i], name);
|
|
26823
|
+
if (p.indexOf(basePath) === 0 && fs$14.existsSync(p)) {
|
|
26815
26824
|
fullpath = p;
|
|
26816
26825
|
break;
|
|
26817
26826
|
}
|
|
@@ -26819,7 +26828,7 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
26819
26828
|
if (!fullpath) return null;
|
|
26820
26829
|
this.pathsToNames[fullpath] = name;
|
|
26821
26830
|
var source = {
|
|
26822
|
-
src: fs$
|
|
26831
|
+
src: fs$14.readFileSync(fullpath, "utf-8"),
|
|
26823
26832
|
path: fullpath,
|
|
26824
26833
|
noCache: this.noCache
|
|
26825
26834
|
};
|
|
@@ -26867,7 +26876,7 @@ var require_node_loaders = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
26867
26876
|
}
|
|
26868
26877
|
this.pathsToNames[fullpath] = name;
|
|
26869
26878
|
var source = {
|
|
26870
|
-
src: fs$
|
|
26879
|
+
src: fs$14.readFileSync(fullpath, "utf-8"),
|
|
26871
26880
|
path: fullpath,
|
|
26872
26881
|
noCache: this.noCache
|
|
26873
26882
|
};
|
|
@@ -27169,13 +27178,13 @@ var require_globals = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
27169
27178
|
//#endregion
|
|
27170
27179
|
//#region ../../node_modules/.pnpm/nunjucks@3.2.4_chokidar@4.0.3/node_modules/nunjucks/src/express-app.js
|
|
27171
27180
|
var require_express_app = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
27172
|
-
var path$
|
|
27181
|
+
var path$12 = __require("path");
|
|
27173
27182
|
module.exports = function express(env, app) {
|
|
27174
27183
|
function NunjucksView(name, opts) {
|
|
27175
27184
|
this.name = name;
|
|
27176
27185
|
this.path = name;
|
|
27177
27186
|
this.defaultEngine = opts.defaultEngine;
|
|
27178
|
-
this.ext = path$
|
|
27187
|
+
this.ext = path$12.extname(name);
|
|
27179
27188
|
if (!this.ext && !this.defaultEngine) throw new Error("No default engine was specified and no extension was provided.");
|
|
27180
27189
|
if (!this.ext) this.name += this.ext = (this.defaultEngine[0] !== "." ? "." : "") + this.defaultEngine;
|
|
27181
27190
|
}
|
|
@@ -27611,8 +27620,8 @@ var require_precompile_global = /* @__PURE__ */ __commonJSMin(((exports, module)
|
|
|
27611
27620
|
//#endregion
|
|
27612
27621
|
//#region ../../node_modules/.pnpm/nunjucks@3.2.4_chokidar@4.0.3/node_modules/nunjucks/src/precompile.js
|
|
27613
27622
|
var require_precompile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
27614
|
-
var fs$
|
|
27615
|
-
var path$
|
|
27623
|
+
var fs$13 = __require("fs");
|
|
27624
|
+
var path$11 = __require("path");
|
|
27616
27625
|
var _prettifyError = require_lib$7()._prettifyError;
|
|
27617
27626
|
var compiler = require_compiler();
|
|
27618
27627
|
var Environment = require_environment().Environment;
|
|
@@ -27636,27 +27645,27 @@ var require_precompile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
27636
27645
|
var env = opts.env || new Environment([]);
|
|
27637
27646
|
var wrapper = opts.wrapper || precompileGlobal;
|
|
27638
27647
|
if (opts.isString) return precompileString(input, opts);
|
|
27639
|
-
var pathStats = fs$
|
|
27648
|
+
var pathStats = fs$13.existsSync(input) && fs$13.statSync(input);
|
|
27640
27649
|
var precompiled = [];
|
|
27641
27650
|
var templates = [];
|
|
27642
27651
|
function addTemplates(dir) {
|
|
27643
|
-
fs$
|
|
27644
|
-
var filepath = path$
|
|
27645
|
-
var subpath = filepath.substr(path$
|
|
27646
|
-
var stat = fs$
|
|
27652
|
+
fs$13.readdirSync(dir).forEach(function(file) {
|
|
27653
|
+
var filepath = path$11.join(dir, file);
|
|
27654
|
+
var subpath = filepath.substr(path$11.join(input, "/").length);
|
|
27655
|
+
var stat = fs$13.statSync(filepath);
|
|
27647
27656
|
if (stat && stat.isDirectory()) {
|
|
27648
27657
|
subpath += "/";
|
|
27649
27658
|
if (!match(subpath, opts.exclude)) addTemplates(filepath);
|
|
27650
27659
|
} else if (match(subpath, opts.include)) templates.push(filepath);
|
|
27651
27660
|
});
|
|
27652
27661
|
}
|
|
27653
|
-
if (pathStats.isFile()) precompiled.push(_precompile(fs$
|
|
27662
|
+
if (pathStats.isFile()) precompiled.push(_precompile(fs$13.readFileSync(input, "utf-8"), opts.name || input, env));
|
|
27654
27663
|
else if (pathStats.isDirectory()) {
|
|
27655
27664
|
addTemplates(input);
|
|
27656
27665
|
for (var i = 0; i < templates.length; i++) {
|
|
27657
|
-
var name = templates[i].replace(path$
|
|
27666
|
+
var name = templates[i].replace(path$11.join(input, "/"), "");
|
|
27658
27667
|
try {
|
|
27659
|
-
precompiled.push(_precompile(fs$
|
|
27668
|
+
precompiled.push(_precompile(fs$13.readFileSync(templates[i], "utf-8"), name, env));
|
|
27660
27669
|
} catch (e) {
|
|
27661
27670
|
if (opts.force) console.error(e);
|
|
27662
27671
|
else throw e;
|
|
@@ -28340,7 +28349,7 @@ var init_load = __esmMin((() => {
|
|
|
28340
28349
|
//#region ../../packages/agent-core/src/profile/default/agent.yaml?raw
|
|
28341
28350
|
var agent_default$1;
|
|
28342
28351
|
var init_agent$3 = __esmMin((() => {
|
|
28343
|
-
agent_default$1 = "name: agent\ndescription: Default BLUN King agent\n\nsystemPromptPath: ./system.md\npromptVars:\n roleAdditional: ''\n\ntools:\n - Read\n - Write\n - Edit\n - Grep\n - Glob\n - Bash\n - TaskList\n - TaskOutput\n - TaskStop\n - CronCreate\n - CronList\n - CronDelete\n - ReadMediaFile\n - TodoList\n - Skill\n - WebSearch\n - Agent\n - AgentSwarm\n - FetchURL\n - AskUserQuestion\n - MistakeRecord\n - CodebaseSearch\n - EnterPlanMode\n - ExitPlanMode\n - CreateGoal\n - GetGoal\n - SetGoalBudget\n - UpdateGoal\n - mcp__*\n\nsubagents:\n coder:\n description: General software engineering agent — the only subagent type with file-editing tools; use it for any delegated task that must modify code.\n explore:\n description: Fast codebase exploration with prompt-enforced read-only behavior.\n plan:\n description: Read-only implementation planning and architecture design.\n";
|
|
28352
|
+
agent_default$1 = "name: agent\ndescription: Default BLUN King agent\n\nsystemPromptPath: ./system.md\npromptVars:\n roleAdditional: ''\n\ntools:\n - Read\n - Write\n - Edit\n - Grep\n - Glob\n - Bash\n - TaskList\n - TaskOutput\n - TaskStop\n - CronCreate\n - CronList\n - CronDelete\n - ReadMediaFile\n - TodoList\n - Skill\n - WebSearch\n - Agent\n - AgentSwarm\n - FetchURL\n - GenerateImage\n - GenerateVideo\n - GenerateSpeech\n - GetMedia\n - AskUserQuestion\n - MistakeRecord\n - CodebaseSearch\n - EnterPlanMode\n - ExitPlanMode\n - CreateGoal\n - GetGoal\n - SetGoalBudget\n - UpdateGoal\n - mcp__*\n\nsubagents:\n coder:\n description: General software engineering agent — the only subagent type with file-editing tools; use it for any delegated task that must modify code.\n explore:\n description: Fast codebase exploration with prompt-enforced read-only behavior.\n plan:\n description: Read-only implementation planning and architecture design.\n";
|
|
28344
28353
|
}));
|
|
28345
28354
|
//#endregion
|
|
28346
28355
|
//#region ../../packages/agent-core/src/profile/default/coder.yaml?raw
|
|
@@ -28476,7 +28485,7 @@ function isAbortError$4(err) {
|
|
|
28476
28485
|
if (err instanceof Error) return err.name === "AbortError";
|
|
28477
28486
|
return false;
|
|
28478
28487
|
}
|
|
28479
|
-
function errorMessage$
|
|
28488
|
+
function errorMessage$12(err) {
|
|
28480
28489
|
if (err instanceof Error) return err.message;
|
|
28481
28490
|
return String(err);
|
|
28482
28491
|
}
|
|
@@ -28700,7 +28709,7 @@ function normalizePersistedTask$1(task) {
|
|
|
28700
28709
|
}
|
|
28701
28710
|
function legacyPersistedTaskToInfo$1(task) {
|
|
28702
28711
|
const status = legacyStatusToCurrent$1(task);
|
|
28703
|
-
const stopReason = optionalNonEmptyString$
|
|
28712
|
+
const stopReason = optionalNonEmptyString$2(task.stop_reason);
|
|
28704
28713
|
const timeoutMs = typeof task.timeout_ms === "number" ? task.timeout_ms : void 0;
|
|
28705
28714
|
const base = {
|
|
28706
28715
|
taskId: task.task_id,
|
|
@@ -28715,8 +28724,8 @@ function legacyPersistedTaskToInfo$1(task) {
|
|
|
28715
28724
|
if (task.task_id.startsWith("agent-")) return {
|
|
28716
28725
|
...base,
|
|
28717
28726
|
kind: "agent",
|
|
28718
|
-
agentId: optionalNonEmptyString$
|
|
28719
|
-
subagentType: optionalNonEmptyString$
|
|
28727
|
+
agentId: optionalNonEmptyString$2(task.agent_id),
|
|
28728
|
+
subagentType: optionalNonEmptyString$2(task.subagent_type)
|
|
28720
28729
|
};
|
|
28721
28730
|
return {
|
|
28722
28731
|
...base,
|
|
@@ -28732,15 +28741,15 @@ function legacyStatusToCurrent$1(task) {
|
|
|
28732
28741
|
return task.status;
|
|
28733
28742
|
}
|
|
28734
28743
|
function isReadablePersistedTask$1(obj) {
|
|
28735
|
-
return isRecord$
|
|
28744
|
+
return isRecord$19(obj) && (typeof obj["taskId"] === "string" || typeof obj["task_id"] === "string");
|
|
28736
28745
|
}
|
|
28737
28746
|
function isLegacyPersistedTask$1(task) {
|
|
28738
28747
|
return "task_id" in task;
|
|
28739
28748
|
}
|
|
28740
|
-
function isRecord$
|
|
28749
|
+
function isRecord$19(value) {
|
|
28741
28750
|
return typeof value === "object" && value !== null;
|
|
28742
28751
|
}
|
|
28743
|
-
function optionalNonEmptyString$
|
|
28752
|
+
function optionalNonEmptyString$2(value) {
|
|
28744
28753
|
if (value === void 0) return void 0;
|
|
28745
28754
|
const trimmed = value.trim();
|
|
28746
28755
|
return trimmed.length > 0 ? trimmed : void 0;
|
|
@@ -28914,7 +28923,7 @@ var init_agent_task = __esmMin((() => {
|
|
|
28914
28923
|
}
|
|
28915
28924
|
await sink.settle({
|
|
28916
28925
|
status: "failed",
|
|
28917
|
-
stopReason: errorMessage$
|
|
28926
|
+
stopReason: errorMessage$12(error)
|
|
28918
28927
|
});
|
|
28919
28928
|
} finally {
|
|
28920
28929
|
sink.signal.removeEventListener("abort", requestAbort);
|
|
@@ -29040,7 +29049,7 @@ var init_process_task = __esmMin((() => {
|
|
|
29040
29049
|
this.exitCode = this.proc.exitCode;
|
|
29041
29050
|
settlement = {
|
|
29042
29051
|
status: sink.signal.aborted ? "killed" : "failed",
|
|
29043
|
-
stopReason: sink.signal.aborted ? void 0 : errorMessage$
|
|
29052
|
+
stopReason: sink.signal.aborted ? void 0 : errorMessage$12(error)
|
|
29044
29053
|
};
|
|
29045
29054
|
} finally {
|
|
29046
29055
|
sink.signal.removeEventListener("abort", requestStop);
|
|
@@ -29114,7 +29123,7 @@ var init_question_task = __esmMin((() => {
|
|
|
29114
29123
|
}
|
|
29115
29124
|
await sink.settle({
|
|
29116
29125
|
status: "failed",
|
|
29117
|
-
stopReason: errorMessage$
|
|
29126
|
+
stopReason: errorMessage$12(error)
|
|
29118
29127
|
});
|
|
29119
29128
|
}
|
|
29120
29129
|
}
|
|
@@ -29676,7 +29685,7 @@ var init_background = __esmMin((() => {
|
|
|
29676
29685
|
})).catch((error) => {
|
|
29677
29686
|
settleWorker({
|
|
29678
29687
|
status: entry.abortController.signal.aborted ? "killed" : "failed",
|
|
29679
|
-
stopReason: entry.abortController.signal.aborted ? void 0 : errorMessage$
|
|
29688
|
+
stopReason: entry.abortController.signal.aborted ? void 0 : errorMessage$12(error)
|
|
29680
29689
|
});
|
|
29681
29690
|
});
|
|
29682
29691
|
const timeout = resettableTimeoutOutcome(entry.options.timeoutMs, { kind: "timeout" });
|
|
@@ -36221,7 +36230,7 @@ var require_gifframe = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
36221
36230
|
//#region ../../node_modules/.pnpm/gifwrap@0.10.1/node_modules/gifwrap/src/gifutil.js
|
|
36222
36231
|
var require_gifutil = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
36223
36232
|
/** @namespace GifUtil */
|
|
36224
|
-
const fs$
|
|
36233
|
+
const fs$12 = __require("fs");
|
|
36225
36234
|
const ImageQ = require_image_q();
|
|
36226
36235
|
const BitmapImage = require_bitmapimage();
|
|
36227
36236
|
const { GifFrame } = require_gifframe();
|
|
@@ -36488,7 +36497,7 @@ var require_gifutil = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
36488
36497
|
}
|
|
36489
36498
|
function _readBinary(path) {
|
|
36490
36499
|
return new Promise((resolve, reject) => {
|
|
36491
|
-
fs$
|
|
36500
|
+
fs$12.readFile(path, (err, buffer) => {
|
|
36492
36501
|
if (err) return reject(err);
|
|
36493
36502
|
return resolve(buffer);
|
|
36494
36503
|
});
|
|
@@ -36496,7 +36505,7 @@ var require_gifutil = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
36496
36505
|
}
|
|
36497
36506
|
function _writeBinary(path, buffer) {
|
|
36498
36507
|
return new Promise((resolve, reject) => {
|
|
36499
|
-
fs$
|
|
36508
|
+
fs$12.writeFile(path, buffer, (err) => {
|
|
36500
36509
|
if (err) return reject(err);
|
|
36501
36510
|
return resolve();
|
|
36502
36511
|
});
|
|
@@ -62314,7 +62323,7 @@ var init_file_type = __esmMin((() => {
|
|
|
62314
62323
|
}
|
|
62315
62324
|
async fromFile(path) {
|
|
62316
62325
|
this.options.signal?.throwIfAborted();
|
|
62317
|
-
const fileHandle = await
|
|
62326
|
+
const fileHandle = await ro.open(path, constants.O_RDONLY | constants.O_NONBLOCK);
|
|
62318
62327
|
const fileStat = await fileHandle.stat();
|
|
62319
62328
|
if (!fileStat.isFile()) {
|
|
62320
62329
|
await fileHandle.close();
|
|
@@ -72819,7 +72828,7 @@ async function processBitmapFont(file, font) {
|
|
|
72819
72828
|
...font,
|
|
72820
72829
|
chars,
|
|
72821
72830
|
kernings,
|
|
72822
|
-
pages: await Promise.all(font.pages.map(async (page) => CharacterJimp.read(
|
|
72831
|
+
pages: await Promise.all(font.pages.map(async (page) => CharacterJimp.read(js.join(js.dirname(file), page))))
|
|
72823
72832
|
};
|
|
72824
72833
|
}
|
|
72825
72834
|
var import_parse_bmfont_ascii, import_lib$1, import_parse_bmfont_binary, convertXML, isWebWorker, CharacterJimp, HEADER;
|
|
@@ -73836,10 +73845,10 @@ function escapeXml(value) {
|
|
|
73836
73845
|
function locationKey(messageIndex, partIndex) {
|
|
73837
73846
|
return `${String(messageIndex)}:${String(partIndex)}`;
|
|
73838
73847
|
}
|
|
73839
|
-
function isRecord$
|
|
73848
|
+
function isRecord$18(value) {
|
|
73840
73849
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
73841
73850
|
}
|
|
73842
|
-
function isNonNegativeInteger(value) {
|
|
73851
|
+
function isNonNegativeInteger$1(value) {
|
|
73843
73852
|
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
73844
73853
|
}
|
|
73845
73854
|
function abortReason(signal) {
|
|
@@ -74035,7 +74044,7 @@ var init_vision_reader = __esmMin((() => {
|
|
|
74035
74044
|
reason: "malformed"
|
|
74036
74045
|
};
|
|
74037
74046
|
}
|
|
74038
|
-
if (!isRecord$
|
|
74047
|
+
if (!isRecord$18(payload) || payload["done"] !== true || typeof payload["response"] !== "string" || !isNonNegativeInteger$1(payload["prompt_eval_count"]) || !isNonNegativeInteger$1(payload["eval_count"])) return {
|
|
74039
74048
|
ok: false,
|
|
74040
74049
|
reason: "malformed"
|
|
74041
74050
|
};
|
|
@@ -80671,7 +80680,7 @@ var require_buffer_from = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
80671
80680
|
//#region ../../node_modules/.pnpm/source-map-support@0.5.21/node_modules/source-map-support/source-map-support.js
|
|
80672
80681
|
var require_source_map_support = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
80673
80682
|
var SourceMapConsumer = require_source_map().SourceMapConsumer;
|
|
80674
|
-
var path$
|
|
80683
|
+
var path$10 = __require("path");
|
|
80675
80684
|
var fs;
|
|
80676
80685
|
try {
|
|
80677
80686
|
fs = __require("fs");
|
|
@@ -80748,15 +80757,15 @@ var require_source_map_support = /* @__PURE__ */ __commonJSMin(((exports, module
|
|
|
80748
80757
|
});
|
|
80749
80758
|
function supportRelativeURL(file, url) {
|
|
80750
80759
|
if (!file) return url;
|
|
80751
|
-
var dir = path$
|
|
80760
|
+
var dir = path$10.dirname(file);
|
|
80752
80761
|
var match = /^\w+:\/\/[^\/]*/.exec(dir);
|
|
80753
80762
|
var protocol = match ? match[0] : "";
|
|
80754
80763
|
var startPath = dir.slice(protocol.length);
|
|
80755
80764
|
if (protocol && /^\/\w\:/.test(startPath)) {
|
|
80756
80765
|
protocol += "/";
|
|
80757
|
-
return protocol + path$
|
|
80766
|
+
return protocol + path$10.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
|
|
80758
80767
|
}
|
|
80759
|
-
return protocol + path$
|
|
80768
|
+
return protocol + path$10.resolve(dir.slice(protocol.length), url);
|
|
80760
80769
|
}
|
|
80761
80770
|
function retrieveSourceMapURL(source) {
|
|
80762
80771
|
var fileData;
|
|
@@ -229699,7 +229708,7 @@ async function runHook(command, input, options) {
|
|
|
229699
229708
|
} : void 0
|
|
229700
229709
|
});
|
|
229701
229710
|
} catch (error) {
|
|
229702
|
-
return allowResult({ stderr: errorMessage$
|
|
229711
|
+
return allowResult({ stderr: errorMessage$11(error) });
|
|
229703
229712
|
}
|
|
229704
229713
|
return new Promise((resolve) => {
|
|
229705
229714
|
let stdout = "";
|
|
@@ -229747,7 +229756,7 @@ async function runHook(command, input, options) {
|
|
|
229747
229756
|
child.on("error", (error) => {
|
|
229748
229757
|
settle(allowResult({
|
|
229749
229758
|
stdout,
|
|
229750
|
-
stderr: stderr + errorMessage$
|
|
229759
|
+
stderr: stderr + errorMessage$11(error)
|
|
229751
229760
|
}));
|
|
229752
229761
|
});
|
|
229753
229762
|
child.on("close", (code) => {
|
|
@@ -229867,10 +229876,10 @@ function killProcessTreeWindows(child, force) {
|
|
|
229867
229876
|
} catch {}
|
|
229868
229877
|
}
|
|
229869
229878
|
}
|
|
229870
|
-
function isRecord$
|
|
229879
|
+
function isRecord$17(value) {
|
|
229871
229880
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
229872
229881
|
}
|
|
229873
|
-
function errorMessage$
|
|
229882
|
+
function errorMessage$11(error) {
|
|
229874
229883
|
return error instanceof Error ? error.message : String(error);
|
|
229875
229884
|
}
|
|
229876
229885
|
var DEFAULT_TIMEOUT_SECONDS, KILL_GRACE_MS$2, OptionalStringSchema, HookSpecificOutputSchema, HookJsonOutputSchema;
|
|
@@ -229883,7 +229892,7 @@ var init_runner = __esmMin((() => {
|
|
|
229883
229892
|
if (typeof value === "string") return value;
|
|
229884
229893
|
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
|
|
229885
229894
|
}, string().optional());
|
|
229886
|
-
HookSpecificOutputSchema = preprocess((value) => isRecord$
|
|
229895
|
+
HookSpecificOutputSchema = preprocess((value) => isRecord$17(value) ? value : void 0, looseObject({
|
|
229887
229896
|
message: OptionalStringSchema,
|
|
229888
229897
|
permissionDecision: unknown().optional(),
|
|
229889
229898
|
permissionDecisionReason: OptionalStringSchema
|
|
@@ -230793,7 +230802,7 @@ function parsePersonalMemoryRecall(output) {
|
|
|
230793
230802
|
} catch {
|
|
230794
230803
|
return { kind: "invalid" };
|
|
230795
230804
|
}
|
|
230796
|
-
if (!isRecord$
|
|
230805
|
+
if (!isRecord$16(parsed) || !isRecord$16(parsed["personal_memory"])) return { kind: "invalid" };
|
|
230797
230806
|
const memory = parsed["personal_memory"];
|
|
230798
230807
|
const savedRaw = memory["saved"];
|
|
230799
230808
|
const threadsRaw = memory["threads"];
|
|
@@ -230802,7 +230811,7 @@ function parsePersonalMemoryRecall(output) {
|
|
|
230802
230811
|
if (savedRaw.length > MAX_SAVED_MEMORIES || threadsRaw.length > MAX_THREADS || historyRaw.length > 0) return { kind: "invalid" };
|
|
230803
230812
|
const saved = [];
|
|
230804
230813
|
for (const value of savedRaw) {
|
|
230805
|
-
if (!isRecord$
|
|
230814
|
+
if (!isRecord$16(value)) return { kind: "invalid" };
|
|
230806
230815
|
const text = boundedTrimmedString(value["text"], MAX_MEMORY_TEXT_CHARS);
|
|
230807
230816
|
const confidence = value["confidence"];
|
|
230808
230817
|
if (text === void 0 || typeof confidence !== "string" || !CONFIDENCE_VALUES.has(confidence)) return { kind: "invalid" };
|
|
@@ -230813,7 +230822,7 @@ function parsePersonalMemoryRecall(output) {
|
|
|
230813
230822
|
}
|
|
230814
230823
|
const threads = [];
|
|
230815
230824
|
for (const value of threadsRaw) {
|
|
230816
|
-
if (!isRecord$
|
|
230825
|
+
if (!isRecord$16(value)) return { kind: "invalid" };
|
|
230817
230826
|
const title = boundedTrimmedString(value["title"], MAX_THREAD_TITLE_CHARS);
|
|
230818
230827
|
const summary = boundedTrimmedString(value["summary"], MAX_THREAD_SUMMARY_CHARS);
|
|
230819
230828
|
if (title === void 0 || summary === void 0) return { kind: "invalid" };
|
|
@@ -230867,7 +230876,7 @@ function boundedTrimmedString(value, maxChars) {
|
|
|
230867
230876
|
const trimmed = value.trim();
|
|
230868
230877
|
return trimmed.length > 0 ? trimmed : void 0;
|
|
230869
230878
|
}
|
|
230870
|
-
function isRecord$
|
|
230879
|
+
function isRecord$16(value) {
|
|
230871
230880
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
230872
230881
|
}
|
|
230873
230882
|
var PERSONAL_MEMORY_HOST_RECALL_HANDLER$1, RECALL_LIMIT, RECALL_TIMEOUT_MS, MAX_QUERY_CHARS, MAX_WIRE_CHARS, MAX_SAVED_MEMORIES, MAX_THREADS, MAX_MEMORY_TEXT_CHARS, MAX_THREAD_TITLE_CHARS, MAX_THREAD_SUMMARY_CHARS, CONFIDENCE_VALUES, TELEGRAM_GROUP_MARKER_RE, TELEGRAM_MARKER_RE, TELEGRAM_CHANNEL_RE, TELEGRAM_SOURCE_RE, TELEGRAM_CHAT_ID_RE, TELEGRAM_SENDER_LINE_RE, TELEGRAM_ATTACHMENT_BLOCK_RE, TELEGRAM_ATTACHMENT_NOTICE_RE, TELEGRAM_IMAGE_ATTACHMENT_RE, GENERIC_IMAGE_QUERY, GENERIC_FILE_QUERY, GENERIC_EMPTY_QUERY, PERSONAL_MEMORY_RECALL_VARIANT, PersonalMemoryRecallInjector;
|
|
@@ -231657,7 +231666,7 @@ function createEvidenceApi(dependencies) {
|
|
|
231657
231666
|
var init_mission_contract_evidence = __esmMin((() => {}));
|
|
231658
231667
|
//#endregion
|
|
231659
231668
|
//#region ../../packages/agent-core/src/agent/injection/mission-contract.js
|
|
231660
|
-
var missionContractApi, SCHEMA_VERSION, CONTRACT_STATUSES, REQUIREMENT_TYPES, normalize$2, createDraft, validate$1, publicContract, contractPrompt, redact, createEvidenceState, recordToolStart, recordToolResult, recordFile, recordUrl, recordScreenshot, recordSecurity, recordDecision, recordCheckpoint, evaluateCriteria, canonicalString$1, sha256$
|
|
231669
|
+
var missionContractApi, SCHEMA_VERSION, CONTRACT_STATUSES, REQUIREMENT_TYPES, normalize$2, createDraft, validate$1, publicContract, contractPrompt, redact, createEvidenceState, recordToolStart, recordToolResult, recordFile, recordUrl, recordScreenshot, recordSecurity, recordDecision, recordCheckpoint, evaluateCriteria, canonicalString$1, sha256$4, finalizeEvidence;
|
|
231661
231670
|
var init_mission_contract = __esmMin((() => {
|
|
231662
231671
|
init_mission_contract_evidence();
|
|
231663
231672
|
missionContractApi = (function(root, factory) {
|
|
@@ -231935,7 +231944,7 @@ var init_mission_contract = __esmMin((() => {
|
|
|
231935
231944
|
})
|
|
231936
231945
|
};
|
|
231937
231946
|
});
|
|
231938
|
-
({SCHEMA_VERSION, CONTRACT_STATUSES, REQUIREMENT_TYPES, normalize: normalize$2, createDraft, validate: validate$1, publicContract, contractPrompt, redact, createEvidenceState, recordToolStart, recordToolResult, recordFile, recordUrl, recordScreenshot, recordSecurity, recordDecision, recordCheckpoint, evaluateCriteria, canonicalString: canonicalString$1, sha256: sha256$
|
|
231947
|
+
({SCHEMA_VERSION, CONTRACT_STATUSES, REQUIREMENT_TYPES, normalize: normalize$2, createDraft, validate: validate$1, publicContract, contractPrompt, redact, createEvidenceState, recordToolStart, recordToolResult, recordFile, recordUrl, recordScreenshot, recordSecurity, recordDecision, recordCheckpoint, evaluateCriteria, canonicalString: canonicalString$1, sha256: sha256$4, finalizeEvidence} = missionContractApi);
|
|
231939
231948
|
}));
|
|
231940
231949
|
//#endregion
|
|
231941
231950
|
//#region ../../packages/agent-core/src/agent/injection/mission-contract-bridge.ts
|
|
@@ -242727,7 +242736,7 @@ function parseToolCallArguments$1(raw) {
|
|
|
242727
242736
|
success: true,
|
|
242728
242737
|
data: {},
|
|
242729
242738
|
parseFailed: true,
|
|
242730
|
-
error: errorMessage$
|
|
242739
|
+
error: errorMessage$12(error)
|
|
242731
242740
|
};
|
|
242732
242741
|
}
|
|
242733
242742
|
}
|
|
@@ -242914,7 +242923,7 @@ async function prepareToolCall(step, call) {
|
|
|
242914
242923
|
toolCallId: call.toolCall.id,
|
|
242915
242924
|
error
|
|
242916
242925
|
});
|
|
242917
|
-
return settleError(effectiveArgs, error instanceof PathSecurityError ? error.message : `Tool "${call.toolName}" failed to resolve execution: ${errorMessage$
|
|
242926
|
+
return settleError(effectiveArgs, error instanceof PathSecurityError ? error.message : `Tool "${call.toolName}" failed to resolve execution: ${errorMessage$12(error)}`);
|
|
242918
242927
|
}
|
|
242919
242928
|
const displayFields = toolCallDisplayFieldsFromExecution(execution);
|
|
242920
242929
|
const settleAborted = () => settleError(effectiveArgs, abortedToolOutput(call.toolName, step.signal), displayFields);
|
|
@@ -242977,7 +242986,7 @@ async function runPrepareToolExecutionHook(step, call) {
|
|
|
242977
242986
|
return {
|
|
242978
242987
|
kind: "hookFailed",
|
|
242979
242988
|
args,
|
|
242980
|
-
output: `prepareToolExecution hook failed for "${call.toolName}": ${errorMessage$
|
|
242989
|
+
output: `prepareToolExecution hook failed for "${call.toolName}": ${errorMessage$12(error)}`
|
|
242981
242990
|
};
|
|
242982
242991
|
}
|
|
242983
242992
|
const effectiveArgs = hookResult?.updatedArgs ?? args;
|
|
@@ -243019,7 +243028,7 @@ async function runAuthorizeToolExecutionHook(step, call, args, execution) {
|
|
|
243019
243028
|
};
|
|
243020
243029
|
return {
|
|
243021
243030
|
block: true,
|
|
243022
|
-
reason: `authorizeToolExecution hook failed for "${call.toolName}": ${errorMessage$
|
|
243031
|
+
reason: `authorizeToolExecution hook failed for "${call.toolName}": ${errorMessage$12(error)}`
|
|
243023
243032
|
};
|
|
243024
243033
|
}
|
|
243025
243034
|
}
|
|
@@ -243046,7 +243055,7 @@ async function runRunnableToolCall(step, call, effectiveArgs, metadata, executio
|
|
|
243046
243055
|
toolCallId: toolCall.id,
|
|
243047
243056
|
error
|
|
243048
243057
|
});
|
|
243049
|
-
return makeErrorToolResult(call, effectiveArgs, aborted ? abortedToolOutput(toolName, signal) : `Tool "${toolName}" failed: ${errorMessage$
|
|
243058
|
+
return makeErrorToolResult(call, effectiveArgs, aborted ? abortedToolOutput(toolName, signal) : `Tool "${toolName}" failed: ${errorMessage$12(error)}`);
|
|
243050
243059
|
}
|
|
243051
243060
|
return makeToolResult(call, effectiveArgs, toolResult);
|
|
243052
243061
|
}
|
|
@@ -243079,7 +243088,7 @@ async function finalizePendingToolResult(step, pendingResult) {
|
|
|
243079
243088
|
toolCallId: pendingResult.toolCall.id,
|
|
243080
243089
|
error
|
|
243081
243090
|
});
|
|
243082
|
-
const output = aborted ? `Tool "${pendingResult.toolName}" aborted during finalizeToolResult hook.` : `finalizeToolResult hook failed for "${pendingResult.toolName}": ${errorMessage$
|
|
243091
|
+
const output = aborted ? `Tool "${pendingResult.toolName}" aborted during finalizeToolResult hook.` : `finalizeToolResult hook failed for "${pendingResult.toolName}": ${errorMessage$12(error)}`;
|
|
243083
243092
|
return {
|
|
243084
243093
|
...pendingResult,
|
|
243085
243094
|
stopTurn: pendingResult.stopTurn,
|
|
@@ -243338,8 +243347,8 @@ async function executeLoopStep(deps) {
|
|
|
243338
243347
|
log?.error("strict resend still rejected by provider; request remains wire-invalid", {
|
|
243339
243348
|
turnStep: `${turnId}.${String(currentStep)}`,
|
|
243340
243349
|
model: llm.modelName,
|
|
243341
|
-
originalError: errorMessage$
|
|
243342
|
-
strictError: errorMessage$
|
|
243350
|
+
originalError: errorMessage$12(error),
|
|
243351
|
+
strictError: errorMessage$12(strictError)
|
|
243343
243352
|
});
|
|
243344
243353
|
throw strictError;
|
|
243345
243354
|
}
|
|
@@ -243591,7 +243600,7 @@ async function runTurn(input) {
|
|
|
243591
243600
|
usage
|
|
243592
243601
|
};
|
|
243593
243602
|
}
|
|
243594
|
-
dispatchEvent(makeInterruptedEvent(isMaxStepsExceededError(error) ? "max_steps" : "error", steps, activeStep, errorMessage$
|
|
243603
|
+
dispatchEvent(makeInterruptedEvent(isMaxStepsExceededError(error) ? "max_steps" : "error", steps, activeStep, errorMessage$12(error)));
|
|
243595
243604
|
throw error;
|
|
243596
243605
|
}
|
|
243597
243606
|
return {
|
|
@@ -247004,7 +247013,7 @@ var init_classic = __esmMin((() => {
|
|
|
247004
247013
|
//#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/index.js
|
|
247005
247014
|
var init_v4 = __esmMin((() => {
|
|
247006
247015
|
init_classic();
|
|
247007
|
-
})), LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, RELATED_TASK_META_KEY, AssertObjectSchema, ProgressTokenSchema, CursorSchema, TaskMetadataSchema, RelatedTaskMetadataSchema, RequestMetaSchema, BaseRequestParamsSchema, TaskAugmentedRequestParamsSchema, isTaskAugmentedRequestParams, RequestSchema, NotificationsParamsSchema, NotificationSchema, ResultSchema, RequestIdSchema, JSONRPCRequestSchema, isJSONRPCRequest, JSONRPCNotificationSchema, isJSONRPCNotification, JSONRPCResultResponseSchema, isJSONRPCResultResponse, ErrorCode, JSONRPCErrorResponseSchema, isJSONRPCErrorResponse, JSONRPCMessageSchema, EmptyResultSchema, CancelledNotificationParamsSchema, CancelledNotificationSchema, IconSchema, IconsSchema, BaseMetadataSchema, ImplementationSchema, FormElicitationCapabilitySchema, ElicitationCapabilitySchema, ClientTasksCapabilitySchema, ServerTasksCapabilitySchema, ClientCapabilitiesSchema, InitializeRequestParamsSchema, InitializeRequestSchema, ServerCapabilitiesSchema, InitializeResultSchema, InitializedNotificationSchema, isInitializedNotification, PingRequestSchema, ProgressSchema, ProgressNotificationParamsSchema, ProgressNotificationSchema, PaginatedRequestParamsSchema, PaginatedRequestSchema, PaginatedResultSchema, TaskStatusSchema, TaskSchema, CreateTaskResultSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, ResourceContentsSchema, TextResourceContentsSchema, Base64Schema, BlobResourceContentsSchema, RoleSchema, AnnotationsSchema, ResourceSchema, ResourceTemplateSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListResourceTemplatesRequestSchema, ListResourceTemplatesResultSchema, ResourceRequestParamsSchema, ReadResourceRequestParamsSchema, ReadResourceRequestSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, SubscribeRequestParamsSchema, SubscribeRequestSchema, UnsubscribeRequestParamsSchema, UnsubscribeRequestSchema, ResourceUpdatedNotificationParamsSchema, ResourceUpdatedNotificationSchema, PromptArgumentSchema, PromptSchema, ListPromptsRequestSchema, ListPromptsResultSchema, GetPromptRequestParamsSchema, GetPromptRequestSchema, TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, EmbeddedResourceSchema, ResourceLinkSchema, ContentBlockSchema, PromptMessageSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ToolAnnotationsSchema, ToolExecutionSchema, ToolSchema, ListToolsRequestSchema, ListToolsResultSchema, CallToolResultSchema, CallToolRequestParamsSchema, CallToolRequestSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, LoggingLevelSchema, SetLevelRequestParamsSchema, SetLevelRequestSchema, LoggingMessageNotificationParamsSchema, LoggingMessageNotificationSchema, ModelHintSchema, ModelPreferencesSchema, ToolChoiceSchema, ToolResultContentSchema, SamplingContentSchema, SamplingMessageContentBlockSchema, SamplingMessageSchema, CreateMessageRequestParamsSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema, LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema, EnumSchemaSchema, PrimitiveSchemaDefinitionSchema, ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema, ElicitRequestParamsSchema, ElicitRequestSchema, ElicitationCompleteNotificationParamsSchema, ElicitationCompleteNotificationSchema, ElicitResultSchema, ResourceTemplateReferenceSchema, PromptReferenceSchema, CompleteRequestParamsSchema, CompleteRequestSchema, CompleteResultSchema, RootSchema, ListRootsRequestSchema, ListRootsResultSchema, RootsListChangedNotificationSchema, McpError, UrlElicitationRequiredError;
|
|
247016
|
+
})), LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, RELATED_TASK_META_KEY, AssertObjectSchema, ProgressTokenSchema, CursorSchema, TaskMetadataSchema, RelatedTaskMetadataSchema, RequestMetaSchema, BaseRequestParamsSchema, TaskAugmentedRequestParamsSchema, isTaskAugmentedRequestParams, RequestSchema, NotificationsParamsSchema, NotificationSchema, ResultSchema, RequestIdSchema, JSONRPCRequestSchema, isJSONRPCRequest, JSONRPCNotificationSchema, isJSONRPCNotification, JSONRPCResultResponseSchema, isJSONRPCResultResponse, ErrorCode, JSONRPCErrorResponseSchema, isJSONRPCErrorResponse, JSONRPCMessageSchema, EmptyResultSchema, CancelledNotificationParamsSchema, CancelledNotificationSchema, IconSchema, IconsSchema, BaseMetadataSchema, ImplementationSchema, FormElicitationCapabilitySchema, ElicitationCapabilitySchema, ClientTasksCapabilitySchema, ServerTasksCapabilitySchema, ClientCapabilitiesSchema, InitializeRequestParamsSchema, InitializeRequestSchema, ServerCapabilitiesSchema, InitializeResultSchema, InitializedNotificationSchema, isInitializedNotification, PingRequestSchema, ProgressSchema, ProgressNotificationParamsSchema, ProgressNotificationSchema, PaginatedRequestParamsSchema, PaginatedRequestSchema, PaginatedResultSchema, TaskStatusSchema, TaskSchema, CreateTaskResultSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, ResourceContentsSchema, TextResourceContentsSchema, Base64Schema, BlobResourceContentsSchema, RoleSchema, AnnotationsSchema, ResourceSchema, ResourceTemplateSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListResourceTemplatesRequestSchema, ListResourceTemplatesResultSchema, ResourceRequestParamsSchema, ReadResourceRequestParamsSchema, ReadResourceRequestSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, SubscribeRequestParamsSchema, SubscribeRequestSchema, UnsubscribeRequestParamsSchema, UnsubscribeRequestSchema, ResourceUpdatedNotificationParamsSchema, ResourceUpdatedNotificationSchema, PromptArgumentSchema, PromptSchema$1, ListPromptsRequestSchema, ListPromptsResultSchema, GetPromptRequestParamsSchema, GetPromptRequestSchema, TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, EmbeddedResourceSchema, ResourceLinkSchema, ContentBlockSchema, PromptMessageSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ToolAnnotationsSchema, ToolExecutionSchema, ToolSchema, ListToolsRequestSchema, ListToolsResultSchema, CallToolResultSchema, CallToolRequestParamsSchema, CallToolRequestSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, LoggingLevelSchema, SetLevelRequestParamsSchema, SetLevelRequestSchema, LoggingMessageNotificationParamsSchema, LoggingMessageNotificationSchema, ModelHintSchema, ModelPreferencesSchema, ToolChoiceSchema, ToolResultContentSchema, SamplingContentSchema, SamplingMessageContentBlockSchema, SamplingMessageSchema, CreateMessageRequestParamsSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema, LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema, EnumSchemaSchema, PrimitiveSchemaDefinitionSchema, ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema, ElicitRequestParamsSchema, ElicitRequestSchema, ElicitationCompleteNotificationParamsSchema, ElicitationCompleteNotificationSchema, ElicitResultSchema, ResourceTemplateReferenceSchema, PromptReferenceSchema, CompleteRequestParamsSchema, CompleteRequestSchema, CompleteResultSchema, RootSchema, ListRootsRequestSchema, ListRootsResultSchema, RootsListChangedNotificationSchema, McpError, UrlElicitationRequiredError;
|
|
247008
247017
|
var init_types$4 = __esmMin((() => {
|
|
247009
247018
|
init_v4();
|
|
247010
247019
|
LATEST_PROTOCOL_VERSION = "2025-11-25";
|
|
@@ -247646,7 +247655,7 @@ uri: string() });
|
|
|
247646
247655
|
*/
|
|
247647
247656
|
required: optional(boolean$1())
|
|
247648
247657
|
});
|
|
247649
|
-
PromptSchema = object({
|
|
247658
|
+
PromptSchema$1 = object({
|
|
247650
247659
|
...BaseMetadataSchema.shape,
|
|
247651
247660
|
...IconsSchema.shape,
|
|
247652
247661
|
/**
|
|
@@ -247664,7 +247673,7 @@ uri: string() });
|
|
|
247664
247673
|
_meta: optional(looseObject({}))
|
|
247665
247674
|
});
|
|
247666
247675
|
ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") });
|
|
247667
|
-
ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: array(PromptSchema) });
|
|
247676
|
+
ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: array(PromptSchema$1) });
|
|
247668
247677
|
GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
247669
247678
|
/**
|
|
247670
247679
|
* The name of the prompt or prompt template.
|
|
@@ -251881,7 +251890,7 @@ var init_ask_user = __esmMin((() => {
|
|
|
251881
251890
|
} catch (error) {
|
|
251882
251891
|
return {
|
|
251883
251892
|
isError: true,
|
|
251884
|
-
output: errorMessage$
|
|
251893
|
+
output: errorMessage$12(error)
|
|
251885
251894
|
};
|
|
251886
251895
|
}
|
|
251887
251896
|
const status = backgroundManager.getTask(taskId)?.status ?? "running";
|
|
@@ -252315,7 +252324,7 @@ function Yn(s, t) {
|
|
|
252315
252324
|
function Kn(s, t) {
|
|
252316
252325
|
s.head = new ue$1(t, void 0, s.head, s), s.tail || (s.tail = s.head), s.length++;
|
|
252317
252326
|
}
|
|
252318
|
-
var zr, Ur, Ds, Wr, Gr, Zr, Q$1, J$1, nt$1, De$1, qt, Ne$1, Ns, Ae$1, As, z$1, Mt, g$1, Qt, Bt, b$1, N$1, _$1, bi, Ie$1, L$1, S, _i, Oi, Is, Ti, Z$1, xi, Ce$1, Jt$1, Rt, C, jt, Yr, Kr, Vr, $r, Fe$1, Li, Xr, qr, A$1, Jr, ht, H$1, te, m$1, Ni, tt$1, Ai, ki, vi, ie$1, ke$1, Ut$1, Ht, Ii, Pt, at, U$1, ot, Y$1, zt, Ci, j$1, ee$1, Fi, ve$1, gt$2, Me, bt, _t, Be$1, et$1, Wt$1, jr, Fs, ks, vs, Ms, Bs, tn, se$1, K$1, sn, M$1, rn, zs, nn, Bi, Tt, Gt, Pi, re, Pe$1, ze$1, Ue, He$1, We$1, Ge$1, Ze$1, Ye$1, Ke$1, Us, hn, an, Hs, ln, cn, Ws, Gs, Hi, ne, dn, Ui, oe$1, Ve$1, un, F$1, mn, xt, Wi, pn, lt, En, wn, Sn, ct, yn, Rn, gn, Gi, bn, Lt, ft, On, Tn, xn, f, $e$1, Dt, Nn, Xi, qi, An, B$1, Nt, it, Zi, Zs, V$1, he$1, dt, Ys, p, st$1, ut, Yi, At, w$1, Xe$1, qe$1, Ki, Ks, Vs, ae$1, Vi, Qe$1, Yt$1, $$1, Je$1, It, je$1, ti, $s, In, le$1, $i, Xs, Cn, rt$1, mt, vn, Qi, Mn, Bn, Ct, Ji, zn, qs, ce$1, ei, ji, Un, Hn, ts, Qs, rr, Wn, tr, er, ir, is$2, sr, fe$1, ii, ss, si, rs, ns, os$6, hs, pt, ri, as, es, q$1, de$1, ni, oi, Gn, hi, ue$1, pi, nr, li, me$1, W$1, pe$2, Et, Ft$1, Ee$1, ai, G, ls, ci, or, ds, us, fi, di, hr, cs, ui, lr, fs$
|
|
252327
|
+
var zr, Ur, Ds, Wr, Gr, Zr, Q$1, J$1, nt$1, De$1, qt, Ne$1, Ns, Ae$1, As, z$1, Mt, g$1, Qt, Bt, b$1, N$1, _$1, bi, Ie$1, L$1, S, _i, Oi, Is, Ti, Z$1, xi, Ce$1, Jt$1, Rt, C, jt, Yr, Kr, Vr, $r, Fe$1, Li, Xr, qr, A$1, Jr, ht, H$1, te, m$1, Ni, tt$1, Ai, ki, vi, ie$1, ke$1, Ut$1, Ht, Ii, Pt, at, U$1, ot, Y$1, zt, Ci, j$1, ee$1, Fi, ve$1, gt$2, Me, bt, _t, Be$1, et$1, Wt$1, jr, Fs, ks, vs, Ms, Bs, tn, se$1, K$1, sn, M$1, rn, zs, nn, Bi, Tt, Gt, Pi, re, Pe$1, ze$1, Ue, He$1, We$1, Ge$1, Ze$1, Ye$1, Ke$1, Us, hn, an, Hs, ln, cn, Ws, Gs, Hi, ne, dn, Ui, oe$1, Ve$1, un, F$1, mn, xt, Wi, pn, lt, En, wn, Sn, ct, yn, Rn, gn, Gi, bn, Lt, ft, On, Tn, xn, f, $e$1, Dt, Nn, Xi, qi, An, B$1, Nt, it, Zi, Zs, V$1, he$1, dt, Ys, p, st$1, ut, Yi, At, w$1, Xe$1, qe$1, Ki, Ks, Vs, ae$1, Vi, Qe$1, Yt$1, $$1, Je$1, It, je$1, ti, $s, In, le$1, $i, Xs, Cn, rt$1, mt, vn, Qi, Mn, Bn, Ct, Ji, zn, qs, ce$1, ei, ji, Un, Hn, ts, Qs, rr, Wn, tr, er, ir, is$2, sr, fe$1, ii, ss, si, rs, ns, os$6, hs, pt, ri, as, es, q$1, de$1, ni, oi, Gn, hi, ue$1, pi, nr, li, me$1, W$1, pe$2, Et, Ft$1, Ee$1, ai, G, ls, ci, or, ds, us, fi, di, hr, cs, ui, lr, fs$11, wt, kt, Vn, $n, fr, dr, Xn, qn, Er, wr, ur, Sr, yr, Rr, jn, to, eo, mr, ms, ps, Ei, io, Es, so, ws, Se$1, St, no, gr, Ss, br, oo, _r, ys, Or, Vt$1, Tr, ao, lo, yi, Lr, Dr, _s, Nr, Os, P$1, Ts, xs, gi, Ar, Ir, Re, Cr, Fr, Rs, yt, O$1, Ri, kr, $t, gs, bs, Ls, ge$1, be, _e$1, Oe$1, Te$1, uo, mo, po, vr, Xt$1, ye$1, xe$1, Eo, wo, So, yo, Ro, go, bo, _o, vt, To;
|
|
252319
252328
|
var init_index_min = __esmMin((() => {
|
|
252320
252329
|
zr = Object.defineProperty;
|
|
252321
252330
|
Ur = (s, t) => {
|
|
@@ -253843,7 +253852,7 @@ while (this[Zs](this[st$1].shift()));
|
|
|
253843
253852
|
let [o, h] = ce$1(this.path);
|
|
253844
253853
|
o && typeof h == "string" && (this.path = h, r = o);
|
|
253845
253854
|
}
|
|
253846
|
-
this.win32 = !!i.win32 || process.platform === "win32", this.win32 && (this.path = Qs(this.path.replaceAll(/\\/g, "/")), t = t.replaceAll(/\\/g, "/")), this.absolute = f(i.absolute ||
|
|
253855
|
+
this.win32 = !!i.win32 || process.platform === "win32", this.win32 && (this.path = Qs(this.path.replaceAll(/\\/g, "/")), t = t.replaceAll(/\\/g, "/")), this.absolute = f(i.absolute || js.resolve(this.cwd, t)), this.path === "" && (this.path = "./"), r && this.warn("TAR_ENTRY_INFO", `stripping ${r} from absolute path`, {
|
|
253847
253856
|
entry: this,
|
|
253848
253857
|
path: r + this.path
|
|
253849
253858
|
});
|
|
@@ -253926,7 +253935,7 @@ while (this[Zs](this[st$1].shift()));
|
|
|
253926
253935
|
}
|
|
253927
253936
|
[sr](t) {
|
|
253928
253937
|
if (!this.stat) throw new Error("cannot create link entry without stat");
|
|
253929
|
-
this.type = "Link", this.linkpath = f(
|
|
253938
|
+
this.type = "Link", this.linkpath = f(js.relative(this.cwd, t)), this.stat.size = 0, this[fe$1](), this.end();
|
|
253930
253939
|
}
|
|
253931
253940
|
[er]() {
|
|
253932
253941
|
if (!this.stat) throw new Error("cannot create file entry without stat");
|
|
@@ -254285,7 +254294,7 @@ while (this[Zs](this[st$1].shift()));
|
|
|
254285
254294
|
constructor(t, e) {
|
|
254286
254295
|
this.path = t || "./", this.absolute = e;
|
|
254287
254296
|
}
|
|
254288
|
-
}, nr = Buffer.alloc(1024), li = Symbol("onStat"), me$1 = Symbol("ended"), W$1 = Symbol("queue"), pe$2 = Symbol("pendingLinks"), Et = Symbol("current"), Ft$1 = Symbol("process"), Ee$1 = Symbol("processing"), ai = Symbol("processJob"), G = Symbol("jobs"), ls = Symbol("jobDone"), ci = Symbol("addFSEntry"), or = Symbol("addTarEntry"), ds = Symbol("stat"), us = Symbol("readdir"), fi = Symbol("onreaddir"), di = Symbol("pipe"), hr = Symbol("entry"), cs = Symbol("entryOpt"), ui = Symbol("writeEntryClass"), lr = Symbol("write"), fs$
|
|
254297
|
+
}, nr = Buffer.alloc(1024), li = Symbol("onStat"), me$1 = Symbol("ended"), W$1 = Symbol("queue"), pe$2 = Symbol("pendingLinks"), Et = Symbol("current"), Ft$1 = Symbol("process"), Ee$1 = Symbol("processing"), ai = Symbol("processJob"), G = Symbol("jobs"), ls = Symbol("jobDone"), ci = Symbol("addFSEntry"), or = Symbol("addTarEntry"), ds = Symbol("stat"), us = Symbol("readdir"), fi = Symbol("onreaddir"), di = Symbol("pipe"), hr = Symbol("entry"), cs = Symbol("entryOpt"), ui = Symbol("writeEntryClass"), lr = Symbol("write"), fs$11 = Symbol("ondrain"), wt = class extends A$1 {
|
|
254289
254298
|
sync = !1;
|
|
254290
254299
|
opt;
|
|
254291
254300
|
cwd;
|
|
@@ -254318,8 +254327,8 @@ while (this[Zs](this[st$1].shift()));
|
|
|
254318
254327
|
if ((t.gzip ? 1 : 0) + (t.brotli ? 1 : 0) + (t.zstd ? 1 : 0) > 1) throw new TypeError("gzip, brotli, zstd are mutually exclusive");
|
|
254319
254328
|
if (t.gzip && (typeof t.gzip != "object" && (t.gzip = {}), this.portable && (t.gzip.portable = !0), this.zip = new ze$1(t.gzip)), t.brotli && (typeof t.brotli != "object" && (t.brotli = {}), this.zip = new We$1(t.brotli)), t.zstd && (typeof t.zstd != "object" && (t.zstd = {}), this.zip = new Ye$1(t.zstd)), !this.zip) throw new Error("impossible");
|
|
254320
254329
|
let e = this.zip;
|
|
254321
|
-
e.on("data", (i) => super.write(i)), e.on("end", () => super.end()), e.on("drain", () => this[fs$
|
|
254322
|
-
} else this.on("drain", this[fs$
|
|
254330
|
+
e.on("data", (i) => super.write(i)), e.on("end", () => super.end()), e.on("drain", () => this[fs$11]()), this.on("resume", () => e.resume());
|
|
254331
|
+
} else this.on("drain", this[fs$11]);
|
|
254323
254332
|
this.noDirRecurse = !!t.noDirRecurse, this.follow = !!t.follow, this.noMtime = !!t.noMtime, t.mtime && (this.mtime = t.mtime), this.filter = typeof t.filter == "function" ? t.filter : () => !0, this[W$1] = new hi(), this[G] = 0, this.jobs = Number(t.jobs) || 4, this[Ee$1] = !1, this[me$1] = !1;
|
|
254324
254333
|
}
|
|
254325
254334
|
[lr](t) {
|
|
@@ -254336,7 +254345,7 @@ while (this[Zs](this[st$1].shift()));
|
|
|
254336
254345
|
return typeof t == "string" ? this[ci](t) : this[or](t), this.flowing;
|
|
254337
254346
|
}
|
|
254338
254347
|
[or](t) {
|
|
254339
|
-
let e = f(
|
|
254348
|
+
let e = f(js.resolve(this.cwd, t.path));
|
|
254340
254349
|
if (!this.filter(t.path, t)) t.resume();
|
|
254341
254350
|
else {
|
|
254342
254351
|
let i = new pi(t.path, e);
|
|
@@ -254345,7 +254354,7 @@ while (this[Zs](this[st$1].shift()));
|
|
|
254345
254354
|
this[Ft$1]();
|
|
254346
254355
|
}
|
|
254347
254356
|
[ci](t) {
|
|
254348
|
-
let e = f(
|
|
254357
|
+
let e = f(js.resolve(this.cwd, t));
|
|
254349
254358
|
this[W$1].push(new pi(t, e)), this[Ft$1]();
|
|
254350
254359
|
}
|
|
254351
254360
|
[ds](t) {
|
|
@@ -254446,7 +254455,7 @@ while (this[Zs](this[st$1].shift()));
|
|
|
254446
254455
|
this.emit("error", e);
|
|
254447
254456
|
}
|
|
254448
254457
|
}
|
|
254449
|
-
[fs$
|
|
254458
|
+
[fs$11]() {
|
|
254450
254459
|
this[Et] && this[Et].entry && this[Et].entry.resume();
|
|
254451
254460
|
}
|
|
254452
254461
|
[di](t) {
|
|
@@ -254612,7 +254621,7 @@ while (this[Zs](this[st$1].shift()));
|
|
|
254612
254621
|
E ? e(E) : x && a ? Es(x, o, h, (Le) => y(Le)) : n ? Kt.chmod(s, r, e) : e();
|
|
254613
254622
|
};
|
|
254614
254623
|
if (s === d) return no(s, y);
|
|
254615
|
-
if (l) return
|
|
254624
|
+
if (l) return ro.mkdir(s, {
|
|
254616
254625
|
mode: r,
|
|
254617
254626
|
recursive: !0
|
|
254618
254627
|
}).then((E) => y(null, E ?? void 0), y);
|
|
@@ -255371,7 +255380,7 @@ var require_pend = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
255371
255380
|
//#endregion
|
|
255372
255381
|
//#region ../../node_modules/.pnpm/yauzl@3.3.0/node_modules/yauzl/fd-slicer.js
|
|
255373
255382
|
var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
255374
|
-
var fs$
|
|
255383
|
+
var fs$10 = __require("fs");
|
|
255375
255384
|
var util$6 = __require("util");
|
|
255376
255385
|
var stream$2 = __require("stream");
|
|
255377
255386
|
var Readable = stream$2.Readable;
|
|
@@ -255396,7 +255405,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
255396
255405
|
FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
|
|
255397
255406
|
var self = this;
|
|
255398
255407
|
self.pend.go(function(cb) {
|
|
255399
|
-
fs$
|
|
255408
|
+
fs$10.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer) {
|
|
255400
255409
|
cb();
|
|
255401
255410
|
callback(err, bytesRead, buffer);
|
|
255402
255411
|
});
|
|
@@ -255405,7 +255414,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
255405
255414
|
FdSlicer.prototype.write = function(buffer, offset, length, position, callback) {
|
|
255406
255415
|
var self = this;
|
|
255407
255416
|
self.pend.go(function(cb) {
|
|
255408
|
-
fs$
|
|
255417
|
+
fs$10.write(self.fd, buffer, offset, length, position, function(err, written, buffer) {
|
|
255409
255418
|
cb();
|
|
255410
255419
|
callback(err, written, buffer);
|
|
255411
255420
|
});
|
|
@@ -255425,7 +255434,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
255425
255434
|
self.refCount -= 1;
|
|
255426
255435
|
if (self.refCount > 0) return;
|
|
255427
255436
|
if (self.refCount < 0) throw new Error("invalid unref");
|
|
255428
|
-
if (self.autoClose) fs$
|
|
255437
|
+
if (self.autoClose) fs$10.close(self.fd, onCloseDone);
|
|
255429
255438
|
function onCloseDone(err) {
|
|
255430
255439
|
if (err) self.emit("error", err);
|
|
255431
255440
|
else self.emit("close");
|
|
@@ -255456,7 +255465,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
255456
255465
|
self.context.pend.go(function(cb) {
|
|
255457
255466
|
if (self.destroyed) return cb();
|
|
255458
255467
|
var buffer = Buffer.allocUnsafe(toRead);
|
|
255459
|
-
fs$
|
|
255468
|
+
fs$10.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) {
|
|
255460
255469
|
if (err) self.destroy(err);
|
|
255461
255470
|
else if (bytesRead === 0) {
|
|
255462
255471
|
self.destroyed = true;
|
|
@@ -255502,7 +255511,7 @@ var require_fd_slicer = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
255502
255511
|
}
|
|
255503
255512
|
self.context.pend.go(function(cb) {
|
|
255504
255513
|
if (self.destroyed) return cb();
|
|
255505
|
-
fs$
|
|
255514
|
+
fs$10.write(self.context.fd, buffer, 0, buffer.length, self.pos, function(err, bytes) {
|
|
255506
255515
|
if (err) {
|
|
255507
255516
|
self.destroy();
|
|
255508
255517
|
cb();
|
|
@@ -261057,6 +261066,163 @@ var init_mistake_record = __esmMin((() => {
|
|
|
261057
261066
|
};
|
|
261058
261067
|
}));
|
|
261059
261068
|
//#endregion
|
|
261069
|
+
//#region ../../packages/agent-core/src/tools/builtin/media/blun-media.ts
|
|
261070
|
+
function contentPartFor(mimeType, url) {
|
|
261071
|
+
if (mimeType.startsWith("image/")) return {
|
|
261072
|
+
type: "image_url",
|
|
261073
|
+
imageUrl: { url }
|
|
261074
|
+
};
|
|
261075
|
+
if (mimeType.startsWith("audio/")) return {
|
|
261076
|
+
type: "audio_url",
|
|
261077
|
+
audioUrl: { url }
|
|
261078
|
+
};
|
|
261079
|
+
if (mimeType.startsWith("video/")) return {
|
|
261080
|
+
type: "video_url",
|
|
261081
|
+
videoUrl: { url }
|
|
261082
|
+
};
|
|
261083
|
+
}
|
|
261084
|
+
function errorMessage$10(error) {
|
|
261085
|
+
return error instanceof Error ? error.message : String(error);
|
|
261086
|
+
}
|
|
261087
|
+
var PromptSchema, MediaIdSchema, GenerateImageInputSchema, GenerateVideoInputSchema, GenerateSpeechInputSchema, GetMediaInputSchema, REQUEST_NOTE, MediaGenerationTool, GenerateImageTool, GenerateVideoTool, GenerateSpeechTool, GetMediaTool;
|
|
261088
|
+
var init_blun_media$1 = __esmMin((() => {
|
|
261089
|
+
init_zod$1();
|
|
261090
|
+
init_tool_access();
|
|
261091
|
+
init_input_schema();
|
|
261092
|
+
init_rule_match();
|
|
261093
|
+
PromptSchema = string().trim().min(1).max(2e4);
|
|
261094
|
+
MediaIdSchema = string().trim().min(1).max(200).regex(/^[A-Za-z0-9_-]+$/);
|
|
261095
|
+
GenerateImageInputSchema = object({ prompt: PromptSchema.describe("A complete visual description of the image to generate.") });
|
|
261096
|
+
GenerateVideoInputSchema = object({ prompt: PromptSchema.describe("A complete visual description of the video to generate.") });
|
|
261097
|
+
GenerateSpeechInputSchema = object({ input: PromptSchema.describe("The exact text to synthesize as speech.") });
|
|
261098
|
+
GetMediaInputSchema = object({ id: MediaIdSchema.describe("The media job id returned by a generation tool.") });
|
|
261099
|
+
REQUEST_NOTE = "The request is asynchronous. Use GetMedia with the returned id to check progress and retrieve the result.";
|
|
261100
|
+
MediaGenerationTool = class {
|
|
261101
|
+
provider;
|
|
261102
|
+
constructor(provider) {
|
|
261103
|
+
this.provider = provider;
|
|
261104
|
+
}
|
|
261105
|
+
resolveExecution(args) {
|
|
261106
|
+
const subject = this.subject(args);
|
|
261107
|
+
const preview = subject.length > 60 ? `${subject.slice(0, 60)}...` : subject;
|
|
261108
|
+
return {
|
|
261109
|
+
accesses: ToolAccesses.all(),
|
|
261110
|
+
description: `${this.name}: ${preview}`,
|
|
261111
|
+
approvalRule: literalRulePattern(this.name, subject),
|
|
261112
|
+
matchesRule: (ruleArgs) => matchesGlobRuleSubject(ruleArgs, subject),
|
|
261113
|
+
execute: (ctx) => this.execution(args, ctx)
|
|
261114
|
+
};
|
|
261115
|
+
}
|
|
261116
|
+
async execution(args, ctx) {
|
|
261117
|
+
try {
|
|
261118
|
+
const job = await this.submit(args, {
|
|
261119
|
+
signal: ctx.signal,
|
|
261120
|
+
toolCallId: ctx.toolCallId
|
|
261121
|
+
});
|
|
261122
|
+
return {
|
|
261123
|
+
output: `Media job ${job.id} accepted with status ${job.status}. ${REQUEST_NOTE}`,
|
|
261124
|
+
isError: false
|
|
261125
|
+
};
|
|
261126
|
+
} catch (error) {
|
|
261127
|
+
return {
|
|
261128
|
+
isError: true,
|
|
261129
|
+
output: `Media request failed: ${errorMessage$10(error)}`
|
|
261130
|
+
};
|
|
261131
|
+
}
|
|
261132
|
+
}
|
|
261133
|
+
};
|
|
261134
|
+
GenerateImageTool = class extends MediaGenerationTool {
|
|
261135
|
+
name = "GenerateImage";
|
|
261136
|
+
description = "Generate a new image from text with BLUN IMAGINE. Use this when the user asks to create an image, illustration, logo, or visual. This starts a billed asynchronous media job.";
|
|
261137
|
+
parameters = toInputJsonSchema(GenerateImageInputSchema);
|
|
261138
|
+
subject(args) {
|
|
261139
|
+
return args.prompt;
|
|
261140
|
+
}
|
|
261141
|
+
submit(args, options) {
|
|
261142
|
+
return this.provider.generateImage(args.prompt, options);
|
|
261143
|
+
}
|
|
261144
|
+
};
|
|
261145
|
+
GenerateVideoTool = class extends MediaGenerationTool {
|
|
261146
|
+
name = "GenerateVideo";
|
|
261147
|
+
description = "Generate a new video from text with BLUN media models. Use this for motion or text-to-video requests, not for understanding an existing video. This starts a billed asynchronous media job.";
|
|
261148
|
+
parameters = toInputJsonSchema(GenerateVideoInputSchema);
|
|
261149
|
+
subject(args) {
|
|
261150
|
+
return args.prompt;
|
|
261151
|
+
}
|
|
261152
|
+
submit(args, options) {
|
|
261153
|
+
return this.provider.generateVideo(args.prompt, options);
|
|
261154
|
+
}
|
|
261155
|
+
};
|
|
261156
|
+
GenerateSpeechTool = class extends MediaGenerationTool {
|
|
261157
|
+
name = "GenerateSpeech";
|
|
261158
|
+
description = "Synthesize spoken audio from exact text with BLUN VOICE. Use this for voice or speech generation. This starts a billed asynchronous media job.";
|
|
261159
|
+
parameters = toInputJsonSchema(GenerateSpeechInputSchema);
|
|
261160
|
+
subject(args) {
|
|
261161
|
+
return args.input;
|
|
261162
|
+
}
|
|
261163
|
+
submit(args, options) {
|
|
261164
|
+
return this.provider.generateSpeech(args.input, options);
|
|
261165
|
+
}
|
|
261166
|
+
};
|
|
261167
|
+
GetMediaTool = class {
|
|
261168
|
+
provider;
|
|
261169
|
+
name = "GetMedia";
|
|
261170
|
+
description = "Check a BLUN media job. If it is complete, return the generated image, audio, or video. Use only ids returned by GenerateImage, GenerateVideo, or GenerateSpeech.";
|
|
261171
|
+
parameters = toInputJsonSchema(GetMediaInputSchema);
|
|
261172
|
+
constructor(provider) {
|
|
261173
|
+
this.provider = provider;
|
|
261174
|
+
}
|
|
261175
|
+
resolveExecution(args) {
|
|
261176
|
+
return {
|
|
261177
|
+
accesses: ToolAccesses.all(),
|
|
261178
|
+
description: `GetMedia: ${args.id}`,
|
|
261179
|
+
approvalRule: literalRulePattern(this.name, args.id),
|
|
261180
|
+
matchesRule: (ruleArgs) => matchesGlobRuleSubject(ruleArgs, args.id),
|
|
261181
|
+
execute: (ctx) => this.execution(args, ctx)
|
|
261182
|
+
};
|
|
261183
|
+
}
|
|
261184
|
+
async execution(args, ctx) {
|
|
261185
|
+
try {
|
|
261186
|
+
const result = await this.provider.getMedia(args.id, {
|
|
261187
|
+
signal: ctx.signal,
|
|
261188
|
+
toolCallId: ctx.toolCallId
|
|
261189
|
+
});
|
|
261190
|
+
if (result.kind === "status") {
|
|
261191
|
+
const terminalError = [
|
|
261192
|
+
"failed",
|
|
261193
|
+
"expired",
|
|
261194
|
+
"blocked"
|
|
261195
|
+
].includes(result.status.trim().toLowerCase());
|
|
261196
|
+
const source = result.sourceId === void 0 ? "" : ` Source job ${result.sourceId}${result.sourceStatus === void 0 ? "" : ` status: ${result.sourceStatus}`}.`;
|
|
261197
|
+
const retryable = result.retryable === void 0 ? "" : ` Retryable: ${result.retryable ? "yes" : "no"}.`;
|
|
261198
|
+
return {
|
|
261199
|
+
output: `Media job ${result.id} status: ${result.status}.${source}${retryable}`,
|
|
261200
|
+
isError: terminalError
|
|
261201
|
+
};
|
|
261202
|
+
}
|
|
261203
|
+
const url = `data:${result.mimeType};base64,${Buffer.from(result.data).toString("base64")}`;
|
|
261204
|
+
const mediaPart = contentPartFor(result.mimeType, url);
|
|
261205
|
+
if (mediaPart === void 0) return {
|
|
261206
|
+
isError: true,
|
|
261207
|
+
output: `Media job ${result.id} returned unsupported content type ${result.mimeType}.`
|
|
261208
|
+
};
|
|
261209
|
+
return {
|
|
261210
|
+
output: [{
|
|
261211
|
+
type: "text",
|
|
261212
|
+
text: `Media job ${result.id} is complete.`
|
|
261213
|
+
}, mediaPart],
|
|
261214
|
+
isError: false
|
|
261215
|
+
};
|
|
261216
|
+
} catch (error) {
|
|
261217
|
+
return {
|
|
261218
|
+
isError: true,
|
|
261219
|
+
output: `Media lookup failed: ${errorMessage$10(error)}`
|
|
261220
|
+
};
|
|
261221
|
+
}
|
|
261222
|
+
}
|
|
261223
|
+
};
|
|
261224
|
+
}));
|
|
261225
|
+
//#endregion
|
|
261060
261226
|
//#region ../../packages/agent-core/src/tools/builtin/index.ts
|
|
261061
261227
|
var init_builtin = __esmMin((() => {
|
|
261062
261228
|
init_task_list();
|
|
@@ -261087,6 +261253,7 @@ var init_builtin = __esmMin((() => {
|
|
|
261087
261253
|
init_web_search();
|
|
261088
261254
|
init_codebase_search();
|
|
261089
261255
|
init_mistake_record();
|
|
261256
|
+
init_blun_media$1();
|
|
261090
261257
|
}));
|
|
261091
261258
|
//#endregion
|
|
261092
261259
|
//#region ../../packages/agent-core/src/agent/tool/types.ts
|
|
@@ -261511,6 +261678,10 @@ var init_tool$1 = __esmMin((() => {
|
|
|
261511
261678
|
this.agent.subagentHost && new AgentSwarmTool(this.agent.subagentHost, this.agent.swarmMode),
|
|
261512
261679
|
toolServices?.webSearcher && new WebSearchTool(toolServices.webSearcher),
|
|
261513
261680
|
toolServices?.urlFetcher && new FetchURLTool(toolServices.urlFetcher),
|
|
261681
|
+
toolServices?.media && new GenerateImageTool(toolServices.media),
|
|
261682
|
+
toolServices?.media && new GenerateVideoTool(toolServices.media),
|
|
261683
|
+
toolServices?.media && new GenerateSpeechTool(toolServices.media),
|
|
261684
|
+
toolServices?.media && new GetMediaTool(toolServices.media),
|
|
261514
261685
|
new MistakeRecordTool(this.agent),
|
|
261515
261686
|
new CodebaseSearchTool(cwd)
|
|
261516
261687
|
].filter((tool) => !!tool).map((tool) => [tool.name, tool]));
|
|
@@ -292063,7 +292234,7 @@ var init_proxy = __esmMin((() => {
|
|
|
292063
292234
|
var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
292064
292235
|
module.exports = isexe;
|
|
292065
292236
|
isexe.sync = sync;
|
|
292066
|
-
var fs$
|
|
292237
|
+
var fs$8 = __require("fs");
|
|
292067
292238
|
function checkPathExt(path, options) {
|
|
292068
292239
|
var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
|
|
292069
292240
|
if (!pathext) return true;
|
|
@@ -292080,12 +292251,12 @@ var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
292080
292251
|
return checkPathExt(path, options);
|
|
292081
292252
|
}
|
|
292082
292253
|
function isexe(path, options, cb) {
|
|
292083
|
-
fs$
|
|
292254
|
+
fs$8.stat(path, function(er, stat) {
|
|
292084
292255
|
cb(er, er ? false : checkStat(stat, path, options));
|
|
292085
292256
|
});
|
|
292086
292257
|
}
|
|
292087
292258
|
function sync(path, options) {
|
|
292088
|
-
return checkStat(fs$
|
|
292259
|
+
return checkStat(fs$8.statSync(path), path, options);
|
|
292089
292260
|
}
|
|
292090
292261
|
}));
|
|
292091
292262
|
//#endregion
|
|
@@ -292093,14 +292264,14 @@ var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
292093
292264
|
var require_mode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
292094
292265
|
module.exports = isexe;
|
|
292095
292266
|
isexe.sync = sync;
|
|
292096
|
-
var fs$
|
|
292267
|
+
var fs$7 = __require("fs");
|
|
292097
292268
|
function isexe(path, options, cb) {
|
|
292098
|
-
fs$
|
|
292269
|
+
fs$7.stat(path, function(er, stat) {
|
|
292099
292270
|
cb(er, er ? false : checkStat(stat, options));
|
|
292100
292271
|
});
|
|
292101
292272
|
}
|
|
292102
292273
|
function sync(path, options) {
|
|
292103
|
-
return checkStat(fs$
|
|
292274
|
+
return checkStat(fs$7.statSync(path), options);
|
|
292104
292275
|
}
|
|
292105
292276
|
function checkStat(stat, options) {
|
|
292106
292277
|
return stat.isFile() && checkMode(stat, options);
|
|
@@ -292164,7 +292335,7 @@ var require_isexe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
292164
292335
|
//#region ../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js
|
|
292165
292336
|
var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
292166
292337
|
const isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
|
|
292167
|
-
const path$
|
|
292338
|
+
const path$9 = __require("path");
|
|
292168
292339
|
const COLON = isWindows ? ";" : ":";
|
|
292169
292340
|
const isexe = require_isexe();
|
|
292170
292341
|
const getNotFoundError = (cmd) => Object.assign(/* @__PURE__ */ new Error(`not found: ${cmd}`), { code: "ENOENT" });
|
|
@@ -292194,7 +292365,7 @@ var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
292194
292365
|
if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
|
|
292195
292366
|
const ppRaw = pathEnv[i];
|
|
292196
292367
|
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
|
|
292197
|
-
const pCmd = path$
|
|
292368
|
+
const pCmd = path$9.join(pathPart, cmd);
|
|
292198
292369
|
resolve(subStep(!pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd, i, 0));
|
|
292199
292370
|
});
|
|
292200
292371
|
const subStep = (p, i, ii) => new Promise((resolve, reject) => {
|
|
@@ -292215,7 +292386,7 @@ var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
292215
292386
|
for (let i = 0; i < pathEnv.length; i++) {
|
|
292216
292387
|
const ppRaw = pathEnv[i];
|
|
292217
292388
|
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
|
|
292218
|
-
const pCmd = path$
|
|
292389
|
+
const pCmd = path$9.join(pathPart, cmd);
|
|
292219
292390
|
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
|
|
292220
292391
|
for (let j = 0; j < pathExt.length; j++) {
|
|
292221
292392
|
const cur = p + pathExt[j];
|
|
@@ -292246,7 +292417,7 @@ var require_path_key = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
292246
292417
|
//#endregion
|
|
292247
292418
|
//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js
|
|
292248
292419
|
var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
292249
|
-
const path$
|
|
292420
|
+
const path$8 = __require("path");
|
|
292250
292421
|
const which = require_which();
|
|
292251
292422
|
const getPathKey = require_path_key();
|
|
292252
292423
|
function resolveCommandAttempt(parsed, withoutPathExt) {
|
|
@@ -292261,12 +292432,12 @@ var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) =>
|
|
|
292261
292432
|
try {
|
|
292262
292433
|
resolved = which.sync(parsed.command, {
|
|
292263
292434
|
path: env[getPathKey({ env })],
|
|
292264
|
-
pathExt: withoutPathExt ? path$
|
|
292435
|
+
pathExt: withoutPathExt ? path$8.delimiter : void 0
|
|
292265
292436
|
});
|
|
292266
292437
|
} catch (e) {} finally {
|
|
292267
292438
|
if (shouldSwitchCwd) process.chdir(cwd);
|
|
292268
292439
|
}
|
|
292269
|
-
if (resolved) resolved = path$
|
|
292440
|
+
if (resolved) resolved = path$8.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
|
|
292270
292441
|
return resolved;
|
|
292271
292442
|
}
|
|
292272
292443
|
function resolveCommand(parsed) {
|
|
@@ -292315,16 +292486,16 @@ var require_shebang_command = /* @__PURE__ */ __commonJSMin(((exports, module) =
|
|
|
292315
292486
|
//#endregion
|
|
292316
292487
|
//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js
|
|
292317
292488
|
var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
292318
|
-
const fs$
|
|
292489
|
+
const fs$6 = __require("fs");
|
|
292319
292490
|
const shebangCommand = require_shebang_command();
|
|
292320
292491
|
function readShebang(command) {
|
|
292321
292492
|
const size = 150;
|
|
292322
292493
|
const buffer = Buffer.alloc(size);
|
|
292323
292494
|
let fd;
|
|
292324
292495
|
try {
|
|
292325
|
-
fd = fs$
|
|
292326
|
-
fs$
|
|
292327
|
-
fs$
|
|
292496
|
+
fd = fs$6.openSync(command, "r");
|
|
292497
|
+
fs$6.readSync(fd, buffer, 0, size, 0);
|
|
292498
|
+
fs$6.closeSync(fd);
|
|
292328
292499
|
} catch (e) {}
|
|
292329
292500
|
return shebangCommand(buffer.toString());
|
|
292330
292501
|
}
|
|
@@ -292333,7 +292504,7 @@ var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
292333
292504
|
//#endregion
|
|
292334
292505
|
//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js
|
|
292335
292506
|
var require_parse$5 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
292336
|
-
const path$
|
|
292507
|
+
const path$7 = __require("path");
|
|
292337
292508
|
const resolveCommand = require_resolveCommand();
|
|
292338
292509
|
const escape = require_escape();
|
|
292339
292510
|
const readShebang = require_readShebang();
|
|
@@ -292356,7 +292527,7 @@ var require_parse$5 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
292356
292527
|
const needsShell = !isExecutableRegExp.test(commandFile);
|
|
292357
292528
|
if (parsed.options.forceShell || needsShell) {
|
|
292358
292529
|
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
|
|
292359
|
-
parsed.command = path$
|
|
292530
|
+
parsed.command = path$7.normalize(parsed.command);
|
|
292360
292531
|
parsed.command = escape.command(parsed.command);
|
|
292361
292532
|
parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
|
|
292362
292533
|
parsed.args = [
|
|
@@ -294283,7 +294454,7 @@ async function parseManifest(pluginRoot) {
|
|
|
294283
294454
|
}]
|
|
294284
294455
|
};
|
|
294285
294456
|
}
|
|
294286
|
-
if (!isObject$
|
|
294457
|
+
if (!isObject$4(raw)) return {
|
|
294287
294458
|
manifestKind,
|
|
294288
294459
|
manifestPath,
|
|
294289
294460
|
shadowedManifestPath,
|
|
@@ -294430,7 +294601,7 @@ async function resolvePluginPathField(input) {
|
|
|
294430
294601
|
}
|
|
294431
294602
|
function readSessionStart(raw, diagnostics) {
|
|
294432
294603
|
if (raw === void 0) return void 0;
|
|
294433
|
-
if (!isObject$
|
|
294604
|
+
if (!isObject$4(raw)) {
|
|
294434
294605
|
diagnostics.push({
|
|
294435
294606
|
severity: "warn",
|
|
294436
294607
|
message: "\"sessionStart\" must be an object"
|
|
@@ -294449,7 +294620,7 @@ function readSessionStart(raw, diagnostics) {
|
|
|
294449
294620
|
}
|
|
294450
294621
|
async function readMcpServers(pluginRoot, raw, diagnostics) {
|
|
294451
294622
|
if (raw === void 0) return void 0;
|
|
294452
|
-
if (!isObject$
|
|
294623
|
+
if (!isObject$4(raw)) {
|
|
294453
294624
|
diagnostics.push({
|
|
294454
294625
|
severity: "warn",
|
|
294455
294626
|
message: "\"mcpServers\" must be an object"
|
|
@@ -294600,7 +294771,7 @@ async function normalizePluginMcpServer(input) {
|
|
|
294600
294771
|
}
|
|
294601
294772
|
function readAuthor(raw) {
|
|
294602
294773
|
if (typeof raw === "string") return { name: raw };
|
|
294603
|
-
if (!isObject$
|
|
294774
|
+
if (!isObject$4(raw)) return void 0;
|
|
294604
294775
|
const name = stringField$3(raw, "name");
|
|
294605
294776
|
const email = stringField$3(raw, "email");
|
|
294606
294777
|
if (name === void 0 && email === void 0) return void 0;
|
|
@@ -294610,7 +294781,7 @@ function readAuthor(raw) {
|
|
|
294610
294781
|
};
|
|
294611
294782
|
}
|
|
294612
294783
|
function readInterface(raw) {
|
|
294613
|
-
if (!isObject$
|
|
294784
|
+
if (!isObject$4(raw)) return void 0;
|
|
294614
294785
|
const out = {
|
|
294615
294786
|
displayName: stringField$3(raw, "displayName"),
|
|
294616
294787
|
shortDescription: stringField$3(raw, "shortDescription"),
|
|
@@ -294631,7 +294802,7 @@ function stringArrayField$1(raw, key) {
|
|
|
294631
294802
|
if (!Array.isArray(value) || !value.every((entry) => typeof entry === "string")) return;
|
|
294632
294803
|
return value;
|
|
294633
294804
|
}
|
|
294634
|
-
function isObject$
|
|
294805
|
+
function isObject$4(value) {
|
|
294635
294806
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
294636
294807
|
}
|
|
294637
294808
|
function isWithin$1(child, parent) {
|
|
@@ -302337,7 +302508,7 @@ var init_sort = __esmMin((() => {
|
|
|
302337
302508
|
}));
|
|
302338
302509
|
//#endregion
|
|
302339
302510
|
//#region ../../node_modules/.pnpm/css-select@5.2.2/node_modules/css-select/lib/esm/attributes.js
|
|
302340
|
-
function escapeRegex$
|
|
302511
|
+
function escapeRegex$2(value) {
|
|
302341
302512
|
return value.replace(reChars, "\\$&");
|
|
302342
302513
|
}
|
|
302343
302514
|
function shouldIgnoreCase(selector, options) {
|
|
@@ -302430,7 +302601,7 @@ var init_attributes = __esmMin((() => {
|
|
|
302430
302601
|
const { adapter } = options;
|
|
302431
302602
|
const { name, value } = data;
|
|
302432
302603
|
if (/\s/.test(value)) return import_boolbase$5.default.falseFunc;
|
|
302433
|
-
const regex = new RegExp(`(?:^|\\s)${escapeRegex$
|
|
302604
|
+
const regex = new RegExp(`(?:^|\\s)${escapeRegex$2(value)}(?:$|\\s)`, shouldIgnoreCase(data, options) ? "i" : "");
|
|
302434
302605
|
return function element(elem) {
|
|
302435
302606
|
const attr = adapter.getAttributeValue(elem, name);
|
|
302436
302607
|
return attr != null && attr.length >= value.length && regex.test(attr) && next(elem);
|
|
@@ -302480,7 +302651,7 @@ var init_attributes = __esmMin((() => {
|
|
|
302480
302651
|
const { name, value } = data;
|
|
302481
302652
|
if (value === "") return import_boolbase$5.default.falseFunc;
|
|
302482
302653
|
if (shouldIgnoreCase(data, options)) {
|
|
302483
|
-
const regex = new RegExp(escapeRegex$
|
|
302654
|
+
const regex = new RegExp(escapeRegex$2(value), "i");
|
|
302484
302655
|
return function anyIC(elem) {
|
|
302485
302656
|
const attr = adapter.getAttributeValue(elem, name);
|
|
302486
302657
|
return attr != null && attr.length >= value.length && regex.test(attr) && next(elem);
|
|
@@ -308946,6 +309117,137 @@ var init_blun_web_search = __esmMin((() => {
|
|
|
308946
309117
|
};
|
|
308947
309118
|
}));
|
|
308948
309119
|
//#endregion
|
|
309120
|
+
//#region ../../packages/agent-core/src/tools/providers/blun-media.ts
|
|
309121
|
+
async function parseBlockedStatus(response, id) {
|
|
309122
|
+
let payload = {};
|
|
309123
|
+
try {
|
|
309124
|
+
payload = await response.json();
|
|
309125
|
+
} catch {}
|
|
309126
|
+
const sourceId = payload["source_id"];
|
|
309127
|
+
const sourceStatus = payload["source_status"];
|
|
309128
|
+
const retryable = payload["retryable"];
|
|
309129
|
+
return {
|
|
309130
|
+
kind: "status",
|
|
309131
|
+
id,
|
|
309132
|
+
status: "blocked",
|
|
309133
|
+
...typeof sourceId === "string" && sourceId.length > 0 ? { sourceId } : {},
|
|
309134
|
+
...typeof sourceStatus === "string" && sourceStatus.length > 0 ? { sourceStatus } : {},
|
|
309135
|
+
...typeof retryable === "boolean" ? { retryable } : {}
|
|
309136
|
+
};
|
|
309137
|
+
}
|
|
309138
|
+
function parseJob(payload) {
|
|
309139
|
+
const id = payload["id"];
|
|
309140
|
+
const status = payload["status"];
|
|
309141
|
+
if (typeof id !== "string" || id.length === 0 || typeof status !== "string" || status.length === 0) throw new Error("Media request returned an invalid job response.");
|
|
309142
|
+
return {
|
|
309143
|
+
id,
|
|
309144
|
+
status
|
|
309145
|
+
};
|
|
309146
|
+
}
|
|
309147
|
+
function parseStatus(payload, expectedId) {
|
|
309148
|
+
const id = typeof payload["id"] === "string" && payload["id"].length > 0 ? payload["id"] : expectedId;
|
|
309149
|
+
const status = payload["status"];
|
|
309150
|
+
if (typeof status !== "string" || status.length === 0) throw new Error("Media lookup returned an invalid status response.");
|
|
309151
|
+
return {
|
|
309152
|
+
kind: "status",
|
|
309153
|
+
id,
|
|
309154
|
+
status
|
|
309155
|
+
};
|
|
309156
|
+
}
|
|
309157
|
+
async function assertSuccess(response, operation) {
|
|
309158
|
+
if (response.ok) return;
|
|
309159
|
+
let detail = "";
|
|
309160
|
+
try {
|
|
309161
|
+
detail = (await response.text()).trim();
|
|
309162
|
+
} catch {}
|
|
309163
|
+
throw new Error(`${operation} failed: HTTP ${String(response.status)}${detail ? `: ${detail}` : ""}`);
|
|
309164
|
+
}
|
|
309165
|
+
var BlunMediaService;
|
|
309166
|
+
var init_blun_media = __esmMin((() => {
|
|
309167
|
+
BlunMediaService = class {
|
|
309168
|
+
tokenProvider;
|
|
309169
|
+
apiKey;
|
|
309170
|
+
baseUrl;
|
|
309171
|
+
defaultHeaders;
|
|
309172
|
+
customHeaders;
|
|
309173
|
+
fetchImpl;
|
|
309174
|
+
constructor(options) {
|
|
309175
|
+
this.tokenProvider = options.tokenProvider;
|
|
309176
|
+
this.apiKey = options.apiKey;
|
|
309177
|
+
this.baseUrl = options.baseUrl.replace(/\/+$/, "");
|
|
309178
|
+
this.defaultHeaders = options.defaultHeaders ?? {};
|
|
309179
|
+
this.customHeaders = options.customHeaders ?? {};
|
|
309180
|
+
this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
309181
|
+
}
|
|
309182
|
+
generateImage(prompt, options) {
|
|
309183
|
+
return this.submit("/images/generations", { prompt }, options);
|
|
309184
|
+
}
|
|
309185
|
+
generateVideo(prompt, options) {
|
|
309186
|
+
return this.submit("/videos/generations", { prompt }, options);
|
|
309187
|
+
}
|
|
309188
|
+
generateSpeech(input, options) {
|
|
309189
|
+
return this.submit("/audio/speech", { input }, options);
|
|
309190
|
+
}
|
|
309191
|
+
async getMedia(id, options) {
|
|
309192
|
+
const response = await this.request(`/media/${encodeURIComponent(id)}`, { method: "GET" }, options);
|
|
309193
|
+
if (response.status === 409) return parseBlockedStatus(response, id);
|
|
309194
|
+
if (response.status === 410) return {
|
|
309195
|
+
kind: "status",
|
|
309196
|
+
id,
|
|
309197
|
+
status: "expired"
|
|
309198
|
+
};
|
|
309199
|
+
await assertSuccess(response, "Media lookup");
|
|
309200
|
+
const mimeType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
|
|
309201
|
+
if (mimeType === "application/json" || mimeType.endsWith("+json")) return parseStatus(await response.json(), id);
|
|
309202
|
+
if (!mimeType.startsWith("image/") && !mimeType.startsWith("audio/") && !mimeType.startsWith("video/")) throw new Error(`Media lookup returned unsupported content type ${mimeType || "(missing)"}`);
|
|
309203
|
+
return {
|
|
309204
|
+
kind: "file",
|
|
309205
|
+
id,
|
|
309206
|
+
mimeType,
|
|
309207
|
+
data: new Uint8Array(await response.arrayBuffer())
|
|
309208
|
+
};
|
|
309209
|
+
}
|
|
309210
|
+
async submit(path, body, options) {
|
|
309211
|
+
const response = await this.request(path, {
|
|
309212
|
+
method: "POST",
|
|
309213
|
+
body: JSON.stringify(body)
|
|
309214
|
+
}, options);
|
|
309215
|
+
await assertSuccess(response, "Media request");
|
|
309216
|
+
return parseJob(await response.json());
|
|
309217
|
+
}
|
|
309218
|
+
async request(path, init, options) {
|
|
309219
|
+
const firstToken = await this.resolveToken(false);
|
|
309220
|
+
const first = await this.fetchWithToken(path, init, options, firstToken);
|
|
309221
|
+
if (first.status !== 401 || this.tokenProvider === void 0) return first;
|
|
309222
|
+
const refreshed = await this.resolveToken(true);
|
|
309223
|
+
return this.fetchWithToken(path, init, options, refreshed);
|
|
309224
|
+
}
|
|
309225
|
+
fetchWithToken(path, init, options, token) {
|
|
309226
|
+
return this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
309227
|
+
...init,
|
|
309228
|
+
signal: options?.signal,
|
|
309229
|
+
headers: {
|
|
309230
|
+
...this.defaultHeaders,
|
|
309231
|
+
Authorization: `Bearer ${token}`,
|
|
309232
|
+
...init.body === void 0 ? {} : { "Content-Type": "application/json" },
|
|
309233
|
+
...options?.toolCallId === void 0 ? {} : { "X-Msh-Tool-Call-Id": options.toolCallId },
|
|
309234
|
+
...this.customHeaders
|
|
309235
|
+
}
|
|
309236
|
+
});
|
|
309237
|
+
}
|
|
309238
|
+
async resolveToken(force) {
|
|
309239
|
+
if (this.tokenProvider !== void 0) try {
|
|
309240
|
+
return force ? await this.tokenProvider.getAccessToken({ force: true }) : await this.tokenProvider.getAccessToken();
|
|
309241
|
+
} catch (error) {
|
|
309242
|
+
if (this.apiKey !== void 0 && this.apiKey.length > 0) return this.apiKey;
|
|
309243
|
+
throw error;
|
|
309244
|
+
}
|
|
309245
|
+
if (this.apiKey !== void 0 && this.apiKey.length > 0) return this.apiKey;
|
|
309246
|
+
throw new Error("BLUN media service is not configured: missing API key or OAuth token provider.");
|
|
309247
|
+
}
|
|
309248
|
+
};
|
|
309249
|
+
}));
|
|
309250
|
+
//#endregion
|
|
308949
309251
|
//#region ../../packages/agent-core/src/session/export/manifest.ts
|
|
308950
309252
|
function buildExportManifest(args) {
|
|
308951
309253
|
return {
|
|
@@ -309314,7 +309616,7 @@ var require_dist$5 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
309314
309616
|
//#endregion
|
|
309315
309617
|
//#region ../../node_modules/.pnpm/yazl@3.3.1/node_modules/yazl/index.js
|
|
309316
309618
|
var require_yazl = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
309317
|
-
var fs$
|
|
309619
|
+
var fs$5 = __require("fs");
|
|
309318
309620
|
var Transform$2 = __require("stream").Transform;
|
|
309319
309621
|
var PassThrough$2 = __require("stream").PassThrough;
|
|
309320
309622
|
var zlib$1 = __require("zlib");
|
|
@@ -309343,14 +309645,14 @@ var require_yazl = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
309343
309645
|
if (shouldIgnoreAdding(self)) return;
|
|
309344
309646
|
var entry = new Entry(metadataPath, false, options);
|
|
309345
309647
|
self.entries.push(entry);
|
|
309346
|
-
fs$
|
|
309648
|
+
fs$5.stat(realPath, function(err, stats) {
|
|
309347
309649
|
if (err) return self.emit("error", err);
|
|
309348
309650
|
if (!stats.isFile()) return self.emit("error", /* @__PURE__ */ new Error("not a file: " + realPath));
|
|
309349
309651
|
entry.uncompressedSize = stats.size;
|
|
309350
309652
|
if (options.mtime == null) entry.setLastModDate(stats.mtime);
|
|
309351
309653
|
if (options.mode == null) entry.setFileAttributesMode(stats.mode);
|
|
309352
309654
|
entry.setFileDataPumpFunction(function() {
|
|
309353
|
-
var readStream = fs$
|
|
309655
|
+
var readStream = fs$5.createReadStream(realPath);
|
|
309354
309656
|
entry.state = Entry.FILE_DATA_IN_PROGRESS;
|
|
309355
309657
|
readStream.on("error", function(err) {
|
|
309356
309658
|
self.emit("error", err);
|
|
@@ -310046,12 +310348,12 @@ function assertBlunProviderType(provider) {
|
|
|
310046
310348
|
if (provider.type !== "blun") throw new BlunError(ErrorCodes.MODEL_CONFIG_INVALID, "Only the BLUN provider type is supported.");
|
|
310047
310349
|
}
|
|
310048
310350
|
function providerValue(configured, env, envKey) {
|
|
310049
|
-
return nonEmptyString$
|
|
310351
|
+
return nonEmptyString$2(configured) ?? envValue(env, envKey);
|
|
310050
310352
|
}
|
|
310051
310353
|
function envValue(env, key) {
|
|
310052
|
-
return nonEmptyString$
|
|
310354
|
+
return nonEmptyString$2(env?.[key]);
|
|
310053
310355
|
}
|
|
310054
|
-
function nonEmptyString$
|
|
310356
|
+
function nonEmptyString$2(value) {
|
|
310055
310357
|
const trimmed = value?.trim();
|
|
310056
310358
|
return trimmed === void 0 || trimmed.length === 0 ? void 0 : trimmed;
|
|
310057
310359
|
}
|
|
@@ -310682,10 +310984,10 @@ async function appendForkedMarkers(state) {
|
|
|
310682
310984
|
time: Date.now()
|
|
310683
310985
|
};
|
|
310684
310986
|
const agents = state["agents"];
|
|
310685
|
-
if (!isRecord$
|
|
310987
|
+
if (!isRecord$15(agents)) return;
|
|
310686
310988
|
const paths = /* @__PURE__ */ new Set();
|
|
310687
310989
|
for (const agentMeta of Object.values(agents)) {
|
|
310688
|
-
if (!isRecord$
|
|
310990
|
+
if (!isRecord$15(agentMeta)) continue;
|
|
310689
310991
|
const homedir = agentMeta["homedir"];
|
|
310690
310992
|
if (typeof homedir !== "string") continue;
|
|
310691
310993
|
paths.add(join$4(homedir, "wire.jsonl"));
|
|
@@ -310697,7 +310999,7 @@ async function appendForkedMarkers(state) {
|
|
|
310697
310999
|
}));
|
|
310698
311000
|
}
|
|
310699
311001
|
function customMetadataForFork(value) {
|
|
310700
|
-
if (!isRecord$
|
|
311002
|
+
if (!isRecord$15(value)) return {};
|
|
310701
311003
|
const custom = {};
|
|
310702
311004
|
for (const [key, entry] of Object.entries(value)) {
|
|
310703
311005
|
if (key === "goal" || key === "managedQuotaWarningThreshold") continue;
|
|
@@ -310752,10 +311054,10 @@ function normalizeForkTitle(title, fallback) {
|
|
|
310752
311054
|
return typeof fallback === "string" && fallback.trim().length > 0 ? fallback : "New Session";
|
|
310753
311055
|
}
|
|
310754
311056
|
function rewriteAgentHomedirs(value, sourceDir, targetDir) {
|
|
310755
|
-
if (!isRecord$
|
|
311057
|
+
if (!isRecord$15(value)) return {};
|
|
310756
311058
|
const agents = {};
|
|
310757
311059
|
for (const [agentId, agentMeta] of Object.entries(value)) {
|
|
310758
|
-
if (!isRecord$
|
|
311060
|
+
if (!isRecord$15(agentMeta)) {
|
|
310759
311061
|
agents[agentId] = agentMeta;
|
|
310760
311062
|
continue;
|
|
310761
311063
|
}
|
|
@@ -310773,7 +311075,7 @@ function remapSessionPath(value, sourceDir, targetDir) {
|
|
|
310773
311075
|
if (rel.startsWith("..") || isAbsolute$2(rel)) return value;
|
|
310774
311076
|
return join$4(targetDir, rel);
|
|
310775
311077
|
}
|
|
310776
|
-
function isRecord$
|
|
311078
|
+
function isRecord$15(value) {
|
|
310777
311079
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
310778
311080
|
}
|
|
310779
311081
|
async function statIfExists(path) {
|
|
@@ -311021,7 +311323,7 @@ var init_session_store$1 = __esmMin((() => {
|
|
|
311021
311323
|
} catch (error) {
|
|
311022
311324
|
throw new BlunError(ErrorCodes.SESSION_STATE_NOT_FOUND, `Session "${input.sourceId}" state.json was not found`, { cause: error });
|
|
311023
311325
|
}
|
|
311024
|
-
if (!isRecord$
|
|
311326
|
+
if (!isRecord$15(parsed)) throw new BlunError(ErrorCodes.SESSION_STATE_INVALID, `Session "${input.sourceId}" state.json is invalid`);
|
|
311025
311327
|
const title = normalizeForkTitle(input.title, parsed["title"]);
|
|
311026
311328
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
311027
311329
|
const next = {
|
|
@@ -311196,14 +311498,14 @@ async function readGitExecPath(deps, gitExe) {
|
|
|
311196
311498
|
}
|
|
311197
311499
|
}
|
|
311198
311500
|
function gitBashCandidatesFromGitExe(gitExe) {
|
|
311199
|
-
const normalizedGitExe = path$
|
|
311200
|
-
const gitDir = path$
|
|
311201
|
-
const gitDirName = path$
|
|
311501
|
+
const normalizedGitExe = path$16.win32.normalize(normalizeWindowsPath(gitExe));
|
|
311502
|
+
const gitDir = path$16.win32.dirname(normalizedGitExe);
|
|
311503
|
+
const gitDirName = path$16.win32.basename(gitDir).toLowerCase();
|
|
311202
311504
|
if (gitDirName !== "cmd" && gitDirName !== "bin") return;
|
|
311203
|
-
return gitBashCandidatesFromGitRoot(path$
|
|
311505
|
+
return gitBashCandidatesFromGitRoot(path$16.win32.dirname(gitDir));
|
|
311204
311506
|
}
|
|
311205
311507
|
function gitBashCandidatesFromGitExecPath(execPath) {
|
|
311206
|
-
const normalized = path$
|
|
311508
|
+
const normalized = path$16.win32.normalize(normalizeWindowsPath(execPath));
|
|
311207
311509
|
const parts = normalized.split("\\");
|
|
311208
311510
|
for (let i = parts.length - 1; i >= 0; i -= 1) {
|
|
311209
311511
|
const segment = parts[i]?.toLowerCase();
|
|
@@ -311212,16 +311514,16 @@ function gitBashCandidatesFromGitExecPath(execPath) {
|
|
|
311212
311514
|
if (root.length > 0) return gitBashCandidatesFromGitRoot(root);
|
|
311213
311515
|
}
|
|
311214
311516
|
}
|
|
311215
|
-
return gitBashCandidatesFromGitRoot(path$
|
|
311517
|
+
return gitBashCandidatesFromGitRoot(path$16.win32.join(normalized, "..", ".."));
|
|
311216
311518
|
}
|
|
311217
311519
|
function gitBashCandidatesFromGitRoot(root) {
|
|
311218
|
-
return [path$
|
|
311520
|
+
return [path$16.win32.normalize(path$16.win32.join(root, "bin", "bash.exe")), path$16.win32.normalize(path$16.win32.join(root, "usr", "bin", "bash.exe"))];
|
|
311219
311521
|
}
|
|
311220
311522
|
function normalizeWindowsPath(path) {
|
|
311221
311523
|
return path.replaceAll("/", "\\");
|
|
311222
311524
|
}
|
|
311223
311525
|
function isAbsoluteWindowsPath(path) {
|
|
311224
|
-
return path$
|
|
311526
|
+
return path$16.win32.isAbsolute(normalizeWindowsPath(path));
|
|
311225
311527
|
}
|
|
311226
311528
|
function dedupeWindowsPaths(paths) {
|
|
311227
311529
|
const deduped = [];
|
|
@@ -312204,6 +312506,7 @@ async function createRuntimeConfig(input) {
|
|
|
312204
312506
|
const localFetcher = new LocalFetchURLProvider();
|
|
312205
312507
|
const searchService = input.config.services?.blunSearch;
|
|
312206
312508
|
const fetchService = input.config.services?.blunFetch;
|
|
312509
|
+
const mediaService = input.config.services?.blunMedia;
|
|
312207
312510
|
return {
|
|
312208
312511
|
urlFetcher: fetchService?.baseUrl === void 0 ? localFetcher : new BlunFetchURLProvider({
|
|
312209
312512
|
baseUrl: fetchService.baseUrl,
|
|
@@ -312215,17 +312518,22 @@ async function createRuntimeConfig(input) {
|
|
|
312215
312518
|
baseUrl: searchService.baseUrl,
|
|
312216
312519
|
defaultHeaders: input.blunRequestHeaders,
|
|
312217
312520
|
...serviceCredentials(searchService, input.resolveOAuthTokenProvider)
|
|
312521
|
+
}),
|
|
312522
|
+
media: mediaService?.baseUrl === void 0 ? void 0 : new BlunMediaService({
|
|
312523
|
+
baseUrl: mediaService.baseUrl,
|
|
312524
|
+
defaultHeaders: input.blunRequestHeaders,
|
|
312525
|
+
...serviceCredentials(mediaService, input.resolveOAuthTokenProvider)
|
|
312218
312526
|
})
|
|
312219
312527
|
};
|
|
312220
312528
|
}
|
|
312221
312529
|
function serviceCredentials(service, resolveOAuthTokenProvider) {
|
|
312222
312530
|
return {
|
|
312223
|
-
apiKey: nonEmptyString(service.apiKey),
|
|
312531
|
+
apiKey: nonEmptyString$1(service.apiKey),
|
|
312224
312532
|
tokenProvider: service.oauth !== void 0 ? resolveOAuthTokenProvider?.(BLUN_PROVIDER_NAME, service.oauth) : void 0,
|
|
312225
312533
|
customHeaders: service.customHeaders
|
|
312226
312534
|
};
|
|
312227
312535
|
}
|
|
312228
|
-
function nonEmptyString(value) {
|
|
312536
|
+
function nonEmptyString$1(value) {
|
|
312229
312537
|
const trimmed = value?.trim();
|
|
312230
312538
|
return trimmed === void 0 || trimmed.length === 0 ? void 0 : trimmed;
|
|
312231
312539
|
}
|
|
@@ -312309,6 +312617,7 @@ var init_core_impl = __esmMin((() => {
|
|
|
312309
312617
|
init_local_fetch_url();
|
|
312310
312618
|
init_blun_fetch_url();
|
|
312311
312619
|
init_blun_web_search();
|
|
312620
|
+
init_blun_media();
|
|
312312
312621
|
init_version();
|
|
312313
312622
|
init_thinking();
|
|
312314
312623
|
init_agent();
|
|
@@ -324034,7 +324343,7 @@ var SDKRpcClientBase = class {
|
|
|
324034
324343
|
type: "error",
|
|
324035
324344
|
sessionId: request.sessionId,
|
|
324036
324345
|
agentId: request.agentId,
|
|
324037
|
-
...makeErrorPayload(ErrorCodes.SESSION_APPROVAL_HANDLER_ERROR, errorMessage$
|
|
324346
|
+
...makeErrorPayload(ErrorCodes.SESSION_APPROVAL_HANDLER_ERROR, errorMessage$9(error))
|
|
324038
324347
|
});
|
|
324039
324348
|
return {
|
|
324040
324349
|
decision: "cancelled",
|
|
@@ -324052,7 +324361,7 @@ var SDKRpcClientBase = class {
|
|
|
324052
324361
|
type: "error",
|
|
324053
324362
|
sessionId: request.sessionId,
|
|
324054
324363
|
agentId: request.agentId,
|
|
324055
|
-
...makeErrorPayload(ErrorCodes.SESSION_QUESTION_HANDLER_ERROR, errorMessage$
|
|
324364
|
+
...makeErrorPayload(ErrorCodes.SESSION_QUESTION_HANDLER_ERROR, errorMessage$9(error))
|
|
324056
324365
|
});
|
|
324057
324366
|
return null;
|
|
324058
324367
|
}
|
|
@@ -324072,7 +324381,7 @@ var SDKRpcClientBase = class {
|
|
|
324072
324381
|
return await handler(request);
|
|
324073
324382
|
} catch (error) {
|
|
324074
324383
|
return {
|
|
324075
|
-
output: `Tool handler error for "${request.toolName ?? "(unknown)"}": ${errorMessage$
|
|
324384
|
+
output: `Tool handler error for "${request.toolName ?? "(unknown)"}": ${errorMessage$9(error)}`,
|
|
324076
324385
|
isError: true
|
|
324077
324386
|
};
|
|
324078
324387
|
}
|
|
@@ -324096,7 +324405,7 @@ var ClientAPI = class {
|
|
|
324096
324405
|
return this.client.toolCall(request);
|
|
324097
324406
|
}
|
|
324098
324407
|
};
|
|
324099
|
-
function errorMessage$
|
|
324408
|
+
function errorMessage$9(error) {
|
|
324100
324409
|
return error instanceof Error ? error.message : String(error);
|
|
324101
324410
|
}
|
|
324102
324411
|
//#endregion
|
|
@@ -325910,8 +326219,8 @@ var require_suggestSimilar = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
325910
326219
|
var require_command = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
325911
326220
|
const EventEmitter$12 = __require("node:events").EventEmitter;
|
|
325912
326221
|
const childProcess = __require("node:child_process");
|
|
325913
|
-
const path$
|
|
325914
|
-
const fs$
|
|
326222
|
+
const path$6 = __require("node:path");
|
|
326223
|
+
const fs$4 = __require("node:fs");
|
|
325915
326224
|
const process$2 = __require("node:process");
|
|
325916
326225
|
const { Argument, humanReadableArgName } = require_argument();
|
|
325917
326226
|
const { CommanderError } = require_error$2();
|
|
@@ -326794,7 +327103,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
|
|
|
326794
327103
|
* @param {string} subcommandName
|
|
326795
327104
|
*/
|
|
326796
327105
|
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
326797
|
-
if (fs$
|
|
327106
|
+
if (fs$4.existsSync(executableFile)) return;
|
|
326798
327107
|
const executableMissing = `'${executableFile}' does not exist
|
|
326799
327108
|
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
326800
327109
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
@@ -326817,10 +327126,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
|
|
|
326817
327126
|
".cjs"
|
|
326818
327127
|
];
|
|
326819
327128
|
function findFile(baseDir, baseName) {
|
|
326820
|
-
const localBin = path$
|
|
326821
|
-
if (fs$
|
|
326822
|
-
if (sourceExt.includes(path$
|
|
326823
|
-
const foundExt = sourceExt.find((ext) => fs$
|
|
327129
|
+
const localBin = path$6.resolve(baseDir, baseName);
|
|
327130
|
+
if (fs$4.existsSync(localBin)) return localBin;
|
|
327131
|
+
if (sourceExt.includes(path$6.extname(baseName))) return void 0;
|
|
327132
|
+
const foundExt = sourceExt.find((ext) => fs$4.existsSync(`${localBin}${ext}`));
|
|
326824
327133
|
if (foundExt) return `${localBin}${foundExt}`;
|
|
326825
327134
|
}
|
|
326826
327135
|
this._checkForMissingMandatoryOptions();
|
|
@@ -326830,21 +327139,21 @@ Expecting one of '${allowedValues.join("', '")}'`);
|
|
|
326830
327139
|
if (this._scriptPath) {
|
|
326831
327140
|
let resolvedScriptPath;
|
|
326832
327141
|
try {
|
|
326833
|
-
resolvedScriptPath = fs$
|
|
327142
|
+
resolvedScriptPath = fs$4.realpathSync(this._scriptPath);
|
|
326834
327143
|
} catch {
|
|
326835
327144
|
resolvedScriptPath = this._scriptPath;
|
|
326836
327145
|
}
|
|
326837
|
-
executableDir = path$
|
|
327146
|
+
executableDir = path$6.resolve(path$6.dirname(resolvedScriptPath), executableDir);
|
|
326838
327147
|
}
|
|
326839
327148
|
if (executableDir) {
|
|
326840
327149
|
let localFile = findFile(executableDir, executableFile);
|
|
326841
327150
|
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
326842
|
-
const legacyName = path$
|
|
327151
|
+
const legacyName = path$6.basename(this._scriptPath, path$6.extname(this._scriptPath));
|
|
326843
327152
|
if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
|
|
326844
327153
|
}
|
|
326845
327154
|
executableFile = localFile || executableFile;
|
|
326846
327155
|
}
|
|
326847
|
-
launchWithNode = sourceExt.includes(path$
|
|
327156
|
+
launchWithNode = sourceExt.includes(path$6.extname(executableFile));
|
|
326848
327157
|
let proc;
|
|
326849
327158
|
if (process$2.platform !== "win32") if (launchWithNode) {
|
|
326850
327159
|
args.unshift(executableFile);
|
|
@@ -327548,7 +327857,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
|
|
|
327548
327857
|
* @return {Command}
|
|
327549
327858
|
*/
|
|
327550
327859
|
nameFromFilename(filename) {
|
|
327551
|
-
this._name = path$
|
|
327860
|
+
this._name = path$6.basename(filename, path$6.extname(filename));
|
|
327552
327861
|
return this;
|
|
327553
327862
|
}
|
|
327554
327863
|
/**
|
|
@@ -333628,7 +333937,7 @@ var AcpSession = class {
|
|
|
333628
333937
|
break;
|
|
333629
333938
|
}
|
|
333630
333939
|
} catch (error) {
|
|
333631
|
-
await this.emitLocalCommandMessage(`/${name} failed: ${errorMessage$
|
|
333940
|
+
await this.emitLocalCommandMessage(`/${name} failed: ${errorMessage$8(error)}`);
|
|
333632
333941
|
}
|
|
333633
333942
|
return { stopReason: "end_turn" };
|
|
333634
333943
|
}
|
|
@@ -334019,7 +334328,7 @@ var AcpSession = class {
|
|
|
334019
334328
|
}
|
|
334020
334329
|
}
|
|
334021
334330
|
};
|
|
334022
|
-
function errorMessage$
|
|
334331
|
+
function errorMessage$8(error) {
|
|
334023
334332
|
return error instanceof Error ? error.message : String(error);
|
|
334024
334333
|
}
|
|
334025
334334
|
function formatHelpReport(commands) {
|
|
@@ -336508,8 +336817,8 @@ function createAccountMemoryClient(auth, options = {}) {
|
|
|
336508
336817
|
}
|
|
336509
336818
|
function readAccountMemoryConsentStatus(payload) {
|
|
336510
336819
|
const settings = unwrapPayload(payload)?.["settings"];
|
|
336511
|
-
const dataControls = isRecord$
|
|
336512
|
-
if (!isRecord$
|
|
336820
|
+
const dataControls = isRecord$14(settings) ? settings["data_controls"] : void 0;
|
|
336821
|
+
if (!isRecord$14(dataControls)) throw new Error("Account memory returned an invalid response.");
|
|
336513
336822
|
if (dataControls["memory_consent_asked"] !== true) return "never_asked";
|
|
336514
336823
|
if (dataControls["allow_memory"] === true) return "enabled";
|
|
336515
336824
|
if (dataControls["allow_memory"] === false) return "disabled";
|
|
@@ -336632,8 +336941,8 @@ function memoryContextSummary(facts, included) {
|
|
|
336632
336941
|
})}`;
|
|
336633
336942
|
}
|
|
336634
336943
|
function unwrapPayload(value) {
|
|
336635
|
-
if (!isRecord$
|
|
336636
|
-
return isRecord$
|
|
336944
|
+
if (!isRecord$14(value)) return void 0;
|
|
336945
|
+
return isRecord$14(value["data"]) ? value["data"] : value;
|
|
336637
336946
|
}
|
|
336638
336947
|
function readFacts(root) {
|
|
336639
336948
|
let rawFacts = [];
|
|
@@ -336641,7 +336950,7 @@ function readFacts(root) {
|
|
|
336641
336950
|
else {
|
|
336642
336951
|
const factsJson = parseFactsJson(root["facts_json"]);
|
|
336643
336952
|
if (Array.isArray(factsJson)) rawFacts = factsJson;
|
|
336644
|
-
else if (isRecord$
|
|
336953
|
+
else if (isRecord$14(factsJson) && Array.isArray(factsJson["facts"])) rawFacts = factsJson["facts"];
|
|
336645
336954
|
}
|
|
336646
336955
|
const facts = [];
|
|
336647
336956
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -336670,7 +336979,7 @@ function parseFactsJson(value) {
|
|
|
336670
336979
|
}
|
|
336671
336980
|
}
|
|
336672
336981
|
function normalizeFact(value) {
|
|
336673
|
-
const raw = typeof value === "string" ? value : isRecord$
|
|
336982
|
+
const raw = typeof value === "string" ? value : isRecord$14(value) && typeof value["text"] === "string" ? value["text"] : void 0;
|
|
336674
336983
|
if (raw === void 0) return void 0;
|
|
336675
336984
|
const normalized = raw.replaceAll(/\s+/gu, " ").trim();
|
|
336676
336985
|
if (normalized.length === 0) return void 0;
|
|
@@ -336679,7 +336988,7 @@ function normalizeFact(value) {
|
|
|
336679
336988
|
truncated: normalized.length > ACCOUNT_MEMORY_MAX_FACT_CHARS
|
|
336680
336989
|
};
|
|
336681
336990
|
}
|
|
336682
|
-
function isRecord$
|
|
336991
|
+
function isRecord$14(value) {
|
|
336683
336992
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
336684
336993
|
}
|
|
336685
336994
|
//#endregion
|
|
@@ -337848,7 +338157,7 @@ async function updateTuiAppearance(appearance, filePath = getTuiConfigPath()) {
|
|
|
337848
338157
|
throw new TuiConfigParseError(DEFAULT_TUI_CONFIG);
|
|
337849
338158
|
}
|
|
337850
338159
|
} catch (error) {
|
|
337851
|
-
if (!isNotFound$
|
|
338160
|
+
if (!isNotFound$3(error)) throw error;
|
|
337852
338161
|
}
|
|
337853
338162
|
const next = TuiConfigSchema.parse({
|
|
337854
338163
|
...current,
|
|
@@ -337946,7 +338255,7 @@ async function writeTuiConfigAtomic(config, filePath) {
|
|
|
337946
338255
|
throw error;
|
|
337947
338256
|
}
|
|
337948
338257
|
}
|
|
337949
|
-
function isNotFound$
|
|
338258
|
+
function isNotFound$3(error) {
|
|
337950
338259
|
return typeof error === "object" && error !== null && error.code === "ENOENT";
|
|
337951
338260
|
}
|
|
337952
338261
|
function renderAppearanceConfig(appearance) {
|
|
@@ -337966,7 +338275,7 @@ function escapeTomlBasicString(value) {
|
|
|
337966
338275
|
//#region src/cli/sub/doctor.ts
|
|
337967
338276
|
init_zod$1();
|
|
337968
338277
|
async function handleDoctor(deps, options) {
|
|
337969
|
-
const resolved = resolveDeps(deps);
|
|
338278
|
+
const resolved = resolveDeps$1(deps);
|
|
337970
338279
|
const specs = await buildCheckSpecs(resolved, options, resolved.cwd());
|
|
337971
338280
|
const results = await Promise.all(specs.map((spec) => checkTomlFile(resolved, spec)));
|
|
337972
338281
|
const issueCount = results.filter((result) => result.status === "ERROR").length;
|
|
@@ -337993,11 +338302,11 @@ function registerDoctorCommand(parent, deps) {
|
|
|
337993
338302
|
});
|
|
337994
338303
|
}
|
|
337995
338304
|
async function runDoctorCommand(deps, options) {
|
|
337996
|
-
const resolved = resolveDeps(deps);
|
|
338305
|
+
const resolved = resolveDeps$1(deps);
|
|
337997
338306
|
const code = await handleDoctor(resolved, options);
|
|
337998
338307
|
if (code !== 0) resolved.exit(code);
|
|
337999
338308
|
}
|
|
338000
|
-
function resolveDeps(deps) {
|
|
338309
|
+
function resolveDeps$1(deps) {
|
|
338001
338310
|
let configRpc = deps?.configRpc;
|
|
338002
338311
|
const getConfigRpc = () => {
|
|
338003
338312
|
configRpc ??= createBlunConfigRpc();
|
|
@@ -338120,7 +338429,7 @@ function formatErrorMessage$4(error, filePath) {
|
|
|
338120
338429
|
function findValidationIssues(error) {
|
|
338121
338430
|
if (!(error instanceof Error)) return void 0;
|
|
338122
338431
|
const details = "details" in error ? error.details : void 0;
|
|
338123
|
-
if (!isRecord$
|
|
338432
|
+
if (!isRecord$13(details)) return void 0;
|
|
338124
338433
|
const validationIssues = details["validationIssues"];
|
|
338125
338434
|
return isValidationIssueArray(validationIssues) ? validationIssues : void 0;
|
|
338126
338435
|
}
|
|
@@ -338128,11 +338437,11 @@ function isValidationIssueArray(value) {
|
|
|
338128
338437
|
return Array.isArray(value) && value.every(isValidationIssue);
|
|
338129
338438
|
}
|
|
338130
338439
|
function isValidationIssue(value) {
|
|
338131
|
-
if (!isRecord$
|
|
338440
|
+
if (!isRecord$13(value) || typeof value["message"] !== "string") return false;
|
|
338132
338441
|
const path = value["path"];
|
|
338133
338442
|
return Array.isArray(path) && path.every((segment) => typeof segment === "string" || typeof segment === "number");
|
|
338134
338443
|
}
|
|
338135
|
-
function isRecord$
|
|
338444
|
+
function isRecord$13(value) {
|
|
338136
338445
|
return typeof value === "object" && value !== null;
|
|
338137
338446
|
}
|
|
338138
338447
|
function findZodError(error) {
|
|
@@ -338397,7 +338706,7 @@ async function handleExport(deps, sessionId, output, opts) {
|
|
|
338397
338706
|
});
|
|
338398
338707
|
deps.stdout.write(`${result.zipPath}\n`);
|
|
338399
338708
|
} catch (error) {
|
|
338400
|
-
deps.stderr.write(`${errorMessage$
|
|
338709
|
+
deps.stderr.write(`${errorMessage$7(error)}\n`);
|
|
338401
338710
|
deps.exit(1);
|
|
338402
338711
|
}
|
|
338403
338712
|
}
|
|
@@ -338500,7 +338809,7 @@ async function confirmPreviousSession(summary) {
|
|
|
338500
338809
|
rl.close();
|
|
338501
338810
|
}
|
|
338502
338811
|
}
|
|
338503
|
-
function errorMessage$
|
|
338812
|
+
function errorMessage$7(error) {
|
|
338504
338813
|
return error instanceof Error ? error.message : String(error);
|
|
338505
338814
|
}
|
|
338506
338815
|
//#endregion
|
|
@@ -338511,6 +338820,1444 @@ function registerLoginCommand(parent) {
|
|
|
338511
338820
|
});
|
|
338512
338821
|
}
|
|
338513
338822
|
//#endregion
|
|
338823
|
+
//#region src/mistakes/inflow-client.ts
|
|
338824
|
+
const MISTAKE_INVENTORY_STATUSES = [
|
|
338825
|
+
"counted",
|
|
338826
|
+
"uncounted",
|
|
338827
|
+
"unverified"
|
|
338828
|
+
];
|
|
338829
|
+
const MISTAKE_ACTUALITY_STATUSES = [
|
|
338830
|
+
"fresh",
|
|
338831
|
+
"stale",
|
|
338832
|
+
"unverified"
|
|
338833
|
+
];
|
|
338834
|
+
const MISTAKE_SOURCE_FORMS = [
|
|
338835
|
+
"case_collection",
|
|
338836
|
+
"class_collection",
|
|
338837
|
+
"finding_collection",
|
|
338838
|
+
"lesson_collection",
|
|
338839
|
+
"state_collection",
|
|
338840
|
+
"mixed",
|
|
338841
|
+
"unknown"
|
|
338842
|
+
];
|
|
338843
|
+
const MISTAKE_RECORD_TYPES = [
|
|
338844
|
+
"case",
|
|
338845
|
+
"class",
|
|
338846
|
+
"finding",
|
|
338847
|
+
"lesson",
|
|
338848
|
+
"state",
|
|
338849
|
+
"unknown"
|
|
338850
|
+
];
|
|
338851
|
+
const MISTAKE_RELATION_TYPES = [
|
|
338852
|
+
"instance_of",
|
|
338853
|
+
"lesson_from",
|
|
338854
|
+
"state_of",
|
|
338855
|
+
"independently_corroborates"
|
|
338856
|
+
];
|
|
338857
|
+
const MISTAKE_WATCHDOG_STATUSES = [
|
|
338858
|
+
"disabled",
|
|
338859
|
+
"green",
|
|
338860
|
+
"yellow",
|
|
338861
|
+
"red"
|
|
338862
|
+
];
|
|
338863
|
+
const DEFAULT_DEPS$2 = {
|
|
338864
|
+
fetch: globalThis.fetch,
|
|
338865
|
+
now: () => /* @__PURE__ */ new Date(),
|
|
338866
|
+
randomUUID
|
|
338867
|
+
};
|
|
338868
|
+
const SOURCE_ID_RE = /^[a-z0-9][a-z0-9._-]{0,79}$/;
|
|
338869
|
+
const SHA256_RE = /^[a-f0-9]{64}$/;
|
|
338870
|
+
const UUID_RE$1 = /^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;
|
|
338871
|
+
const ENVELOPE_KEYS = [
|
|
338872
|
+
"version",
|
|
338873
|
+
"client_event_id",
|
|
338874
|
+
"source_id",
|
|
338875
|
+
"source_form",
|
|
338876
|
+
"declared_record_types",
|
|
338877
|
+
"original_name",
|
|
338878
|
+
"captured_at",
|
|
338879
|
+
"inventory",
|
|
338880
|
+
"declared_raw_bytes",
|
|
338881
|
+
"declared_raw_sha256",
|
|
338882
|
+
"payload_base64",
|
|
338883
|
+
"declarations"
|
|
338884
|
+
];
|
|
338885
|
+
const INVENTORY_KEYS = [
|
|
338886
|
+
"scope",
|
|
338887
|
+
"bestandsstatus",
|
|
338888
|
+
"aktualitaetsstatus",
|
|
338889
|
+
"declared_entry_count",
|
|
338890
|
+
"last_raw_observed_at"
|
|
338891
|
+
];
|
|
338892
|
+
const STATE_ACTION_KEYS = [
|
|
338893
|
+
"version",
|
|
338894
|
+
"action_id",
|
|
338895
|
+
"action",
|
|
338896
|
+
"target_event_id",
|
|
338897
|
+
"acted_at",
|
|
338898
|
+
"server_sequence",
|
|
338899
|
+
"principal_id",
|
|
338900
|
+
"reason"
|
|
338901
|
+
];
|
|
338902
|
+
const MAX_MISTAKE_SOURCE_BYTES = 20 * 1024 * 1024;
|
|
338903
|
+
function normalizeMistakeSourceId(value) {
|
|
338904
|
+
const normalized = value.normalize("NFKC").trim().toLocaleLowerCase("en-US");
|
|
338905
|
+
if (!SOURCE_ID_RE.test(normalized)) throw new Error("source id must use 1-80 lowercase letters, digits, dots, underscores, or hyphens");
|
|
338906
|
+
return normalized;
|
|
338907
|
+
}
|
|
338908
|
+
function assertSafeMistakeInflowEndpoint(value) {
|
|
338909
|
+
let url;
|
|
338910
|
+
try {
|
|
338911
|
+
url = new URL(value);
|
|
338912
|
+
} catch {
|
|
338913
|
+
throw new Error("mistake inflow endpoint is not a valid URL");
|
|
338914
|
+
}
|
|
338915
|
+
if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") throw new Error("mistake inflow endpoint must not contain credentials, a query, or a fragment");
|
|
338916
|
+
if (url.pathname !== "/" && url.pathname !== "") throw new Error("mistake inflow endpoint must not include a path");
|
|
338917
|
+
if (url.protocol === "https:") return url;
|
|
338918
|
+
if (url.protocol !== "http:" || !isPrivateHttpHost(url.hostname)) throw new Error("plain HTTP mistake inflow is allowed only on loopback or Tailscale addresses");
|
|
338919
|
+
return url;
|
|
338920
|
+
}
|
|
338921
|
+
function isPrivateHttpHost(hostname) {
|
|
338922
|
+
if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]") return true;
|
|
338923
|
+
const parts = hostname.split(".").map(Number);
|
|
338924
|
+
const first = parts[0];
|
|
338925
|
+
const second = parts[1];
|
|
338926
|
+
return parts.length === 4 && parts.every((part) => Number.isInteger(part) && part >= 0 && part <= 255) && first === 100 && second !== void 0 && second >= 64 && second <= 127;
|
|
338927
|
+
}
|
|
338928
|
+
function assertIsoTimestamp$2(value, label) {
|
|
338929
|
+
const parsed = new Date(value);
|
|
338930
|
+
if (!Number.isFinite(parsed.valueOf()) || !/(?:Z|[+-]\d{2}:\d{2})$/.test(value)) throw new Error(`${label} must be an ISO-8601 timestamp with a timezone`);
|
|
338931
|
+
return value;
|
|
338932
|
+
}
|
|
338933
|
+
function assertEntryCount(value) {
|
|
338934
|
+
if (value === void 0) return null;
|
|
338935
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new Error("declared entry count must be a non-negative safe integer");
|
|
338936
|
+
return value;
|
|
338937
|
+
}
|
|
338938
|
+
function parseMistakeRecordDeclarations(value, sourceId, declaredRecordTypes) {
|
|
338939
|
+
if (!isRecord$12(value) || !hasOnlyKeys(value, [
|
|
338940
|
+
"version",
|
|
338941
|
+
"records",
|
|
338942
|
+
"relations"
|
|
338943
|
+
]) || value["version"] !== 1) throw new Error("record declarations must use version 1 and contain only records and relations");
|
|
338944
|
+
if (!Array.isArray(value["records"]) || value["records"].length > 1e5 || !Array.isArray(value["relations"]) || value["relations"].length > 1e5) throw new Error("record declarations require records and relations arrays of at most 100000 items");
|
|
338945
|
+
normalizeMistakeSourceId(sourceId);
|
|
338946
|
+
const allowedRecordTypes = new Set(declaredRecordTypes);
|
|
338947
|
+
if (allowedRecordTypes.size === 0 || [...allowedRecordTypes].some((type) => !MISTAKE_RECORD_TYPES.includes(type))) throw new Error("declared source record types are invalid");
|
|
338948
|
+
const recordIds = /* @__PURE__ */ new Set();
|
|
338949
|
+
return {
|
|
338950
|
+
version: 1,
|
|
338951
|
+
records: value["records"].map((candidate, index) => {
|
|
338952
|
+
if (!isRecord$12(candidate) || !hasOnlyKeys(candidate, [
|
|
338953
|
+
"source_record_id",
|
|
338954
|
+
"type",
|
|
338955
|
+
"raw_locator"
|
|
338956
|
+
])) throw new Error(`record declaration ${index} is invalid`);
|
|
338957
|
+
const recordId = candidate["source_record_id"];
|
|
338958
|
+
const type = candidate["type"];
|
|
338959
|
+
const rawLocator = candidate["raw_locator"];
|
|
338960
|
+
if (typeof recordId !== "string" || !isValidRecordId(recordId)) throw new Error(`record declaration ${index} has an invalid record id`);
|
|
338961
|
+
if (recordIds.has(recordId)) throw new Error(`duplicate record id: ${recordId}`);
|
|
338962
|
+
if (typeof type !== "string" || !MISTAKE_RECORD_TYPES.includes(type) || !allowedRecordTypes.has(type)) throw new Error(`record ${recordId} uses a type not declared by its source`);
|
|
338963
|
+
if (typeof rawLocator !== "string" || !isSafeRawLocator(rawLocator)) throw new Error(`record ${recordId} has an invalid raw locator`);
|
|
338964
|
+
recordIds.add(recordId);
|
|
338965
|
+
return {
|
|
338966
|
+
source_record_id: recordId,
|
|
338967
|
+
type,
|
|
338968
|
+
raw_locator: rawLocator
|
|
338969
|
+
};
|
|
338970
|
+
}),
|
|
338971
|
+
relations: value["relations"].map((candidate, index) => {
|
|
338972
|
+
if (!isRecord$12(candidate) || !hasOnlyKeys(candidate, [
|
|
338973
|
+
"from_source_record_id",
|
|
338974
|
+
"type",
|
|
338975
|
+
"to"
|
|
338976
|
+
])) throw new Error(`record relation ${index} is invalid`);
|
|
338977
|
+
const fromRecordId = candidate["from_source_record_id"];
|
|
338978
|
+
const type = candidate["type"];
|
|
338979
|
+
const target = candidate["to"];
|
|
338980
|
+
if (typeof fromRecordId !== "string" || !isValidRecordId(fromRecordId) || !recordIds.has(fromRecordId)) throw new Error(`record relation ${index} must start at a declared local record`);
|
|
338981
|
+
if (typeof type !== "string" || !MISTAKE_RELATION_TYPES.includes(type)) throw new Error(`record relation ${index} has an invalid relation type`);
|
|
338982
|
+
if (!isRecord$12(target) || !hasOnlyKeys(target, ["source_id", "source_record_id"])) throw new Error(`record relation ${index} has an invalid target`);
|
|
338983
|
+
const targetSourceId = target["source_id"];
|
|
338984
|
+
const targetRecordId = target["source_record_id"];
|
|
338985
|
+
if (typeof targetSourceId !== "string" || !isNormalizedSourceId(targetSourceId)) throw new Error(`record relation ${index} has an invalid target source id`);
|
|
338986
|
+
if (typeof targetRecordId !== "string" || !isValidRecordId(targetRecordId)) throw new Error(`record relation ${index} has an invalid target record id`);
|
|
338987
|
+
return {
|
|
338988
|
+
from_source_record_id: fromRecordId,
|
|
338989
|
+
type,
|
|
338990
|
+
to: {
|
|
338991
|
+
source_id: targetSourceId,
|
|
338992
|
+
source_record_id: targetRecordId
|
|
338993
|
+
}
|
|
338994
|
+
};
|
|
338995
|
+
})
|
|
338996
|
+
};
|
|
338997
|
+
}
|
|
338998
|
+
async function queueMistakeObservation(input, outboxDir, deps = DEFAULT_DEPS$2) {
|
|
338999
|
+
const sourceStat = await lstat(input.filePath);
|
|
339000
|
+
if (sourceStat.isSymbolicLink()) throw new Error("mistake source must not be a symbolic link");
|
|
339001
|
+
if (!sourceStat.isFile()) throw new Error("mistake source must be a regular file");
|
|
339002
|
+
if (sourceStat.size > 20971520) throw new Error(`mistake source exceeds ${MAX_MISTAKE_SOURCE_BYTES} bytes`);
|
|
339003
|
+
const sourceHandle = await open(input.filePath, "r");
|
|
339004
|
+
let raw;
|
|
339005
|
+
try {
|
|
339006
|
+
const openedStat = await sourceHandle.stat();
|
|
339007
|
+
if (!openedStat.isFile() || openedStat.dev !== sourceStat.dev || openedStat.ino !== sourceStat.ino) throw new Error("mistake source changed while it was being opened");
|
|
339008
|
+
raw = await sourceHandle.readFile();
|
|
339009
|
+
} finally {
|
|
339010
|
+
await sourceHandle.close();
|
|
339011
|
+
}
|
|
339012
|
+
if (raw.byteLength > 20971520) throw new Error(`mistake source exceeds ${MAX_MISTAKE_SOURCE_BYTES} bytes`);
|
|
339013
|
+
const clientEventId = input.clientEventId ?? deps.randomUUID();
|
|
339014
|
+
if (!UUID_RE$1.test(clientEventId)) throw new Error("client event id must be a UUID");
|
|
339015
|
+
const capturedAt = assertIsoTimestamp$2(input.capturedAt ?? deps.now().toISOString(), "captured at");
|
|
339016
|
+
const lastRawObservedAt = input.lastRawObservedAt === void 0 ? null : assertIsoTimestamp$2(input.lastRawObservedAt, "last raw observed at");
|
|
339017
|
+
const recordTypes = [...new Set(input.recordTypes)];
|
|
339018
|
+
if (recordTypes.length === 0 || recordTypes.some((type) => !MISTAKE_RECORD_TYPES.includes(type))) throw new Error("at least one valid declared record type is required");
|
|
339019
|
+
if (!MISTAKE_SOURCE_FORMS.includes(input.sourceForm)) throw new Error("invalid source form");
|
|
339020
|
+
if (!MISTAKE_INVENTORY_STATUSES.includes(input.bestandsstatus)) throw new Error("invalid bestandsstatus");
|
|
339021
|
+
if (!MISTAKE_ACTUALITY_STATUSES.includes(input.aktualitaetsstatus)) throw new Error("invalid aktualitaetsstatus");
|
|
339022
|
+
const declaredEntryCount = assertEntryCount(input.declaredEntryCount);
|
|
339023
|
+
assertInventoryInvariants(input.bestandsstatus, input.aktualitaetsstatus, declaredEntryCount, lastRawObservedAt, capturedAt);
|
|
339024
|
+
const sourceId = normalizeMistakeSourceId(input.sourceId);
|
|
339025
|
+
const declarations = input.declarations === void 0 ? void 0 : parseMistakeRecordDeclarations(input.declarations, sourceId, recordTypes);
|
|
339026
|
+
const envelope = {
|
|
339027
|
+
version: 1,
|
|
339028
|
+
client_event_id: clientEventId,
|
|
339029
|
+
source_id: sourceId,
|
|
339030
|
+
source_form: input.sourceForm,
|
|
339031
|
+
declared_record_types: recordTypes,
|
|
339032
|
+
original_name: basename(input.filePath),
|
|
339033
|
+
captured_at: capturedAt,
|
|
339034
|
+
inventory: {
|
|
339035
|
+
scope: "lower_bound",
|
|
339036
|
+
bestandsstatus: input.bestandsstatus,
|
|
339037
|
+
aktualitaetsstatus: input.aktualitaetsstatus,
|
|
339038
|
+
declared_entry_count: declaredEntryCount,
|
|
339039
|
+
last_raw_observed_at: lastRawObservedAt
|
|
339040
|
+
},
|
|
339041
|
+
declared_raw_bytes: raw.byteLength,
|
|
339042
|
+
declared_raw_sha256: createHash("sha256").update(raw).digest("hex"),
|
|
339043
|
+
payload_base64: raw.toString("base64"),
|
|
339044
|
+
declarations
|
|
339045
|
+
};
|
|
339046
|
+
const eventsDir = join(outboxDir, "events");
|
|
339047
|
+
await ensureDurableMistakeDirectory(eventsDir);
|
|
339048
|
+
await durableExclusiveWrite(join(eventsDir, `${clientEventId}.json`), `${JSON.stringify(envelope)}\n`);
|
|
339049
|
+
return envelope;
|
|
339050
|
+
}
|
|
339051
|
+
function endpointUrl(endpoint, path) {
|
|
339052
|
+
const base = assertSafeMistakeInflowEndpoint(endpoint);
|
|
339053
|
+
return new URL(path, base);
|
|
339054
|
+
}
|
|
339055
|
+
async function readJsonResponse(response) {
|
|
339056
|
+
const text = await response.text();
|
|
339057
|
+
try {
|
|
339058
|
+
return JSON.parse(text);
|
|
339059
|
+
} catch {
|
|
339060
|
+
throw new Error(`mistake inflow returned non-JSON HTTP ${response.status}`);
|
|
339061
|
+
}
|
|
339062
|
+
}
|
|
339063
|
+
function isReceipt(value) {
|
|
339064
|
+
if (typeof value !== "object" || value === null) return false;
|
|
339065
|
+
const item = value;
|
|
339066
|
+
return item["version"] === 1 && item["accepted"] === true && typeof item["event_id"] === "string" && UUID_RE$1.test(item["event_id"]) && typeof item["client_event_id"] === "string" && UUID_RE$1.test(item["client_event_id"]) && typeof item["source_id"] === "string" && isNormalizedSourceId(item["source_id"]) && typeof item["canonical_agent_id"] === "string" && isNormalizedSourceId(item["canonical_agent_id"]) && typeof item["received_at"] === "string" && isIsoTimestamp(item["received_at"]) && item["raw_count"] === 1 && item["accepted_count"] === 1 && item["rejected_count"] === 0 && Number.isSafeInteger(item["raw_bytes"]) && item["raw_bytes"] >= 0 && typeof item["raw_sha256"] === "string" && SHA256_RE.test(item["raw_sha256"]) && isNullableEntryCount(item["declared_entry_count"]);
|
|
339067
|
+
}
|
|
339068
|
+
async function deliverQueuedObservation(clientEventId, options, deps = DEFAULT_DEPS$2) {
|
|
339069
|
+
if (!UUID_RE$1.test(clientEventId)) throw new Error("client event id must be a UUID");
|
|
339070
|
+
const envelope = parseQueuedEnvelope(await readFile(join(options.outboxDir, "events", `${clientEventId}.json`), "utf8"), clientEventId);
|
|
339071
|
+
const controller = new AbortController();
|
|
339072
|
+
const timeout = setTimeout(() => {
|
|
339073
|
+
controller.abort();
|
|
339074
|
+
}, 15e3);
|
|
339075
|
+
let response;
|
|
339076
|
+
try {
|
|
339077
|
+
response = await deps.fetch(endpointUrl(options.endpoint, "/v1/observations"), {
|
|
339078
|
+
method: "POST",
|
|
339079
|
+
headers: {
|
|
339080
|
+
authorization: `Bearer ${options.token}`,
|
|
339081
|
+
"content-type": "application/json"
|
|
339082
|
+
},
|
|
339083
|
+
body: JSON.stringify(envelope),
|
|
339084
|
+
signal: controller.signal,
|
|
339085
|
+
redirect: "error"
|
|
339086
|
+
});
|
|
339087
|
+
} finally {
|
|
339088
|
+
clearTimeout(timeout);
|
|
339089
|
+
}
|
|
339090
|
+
const body = await readJsonResponse(response);
|
|
339091
|
+
if (response.status !== 202 || !isReceipt(body)) {
|
|
339092
|
+
const bodyError = typeof body === "object" && body !== null ? body["error"] : void 0;
|
|
339093
|
+
const message = typeof bodyError === "string" ? bodyError : `HTTP ${response.status}`;
|
|
339094
|
+
throw new Error(`mistake inflow rejected ${clientEventId}: ${message}`);
|
|
339095
|
+
}
|
|
339096
|
+
if (!receiptMatchesEnvelope(body, envelope)) throw new Error(`mistake inflow receipt mismatch for ${clientEventId}`);
|
|
339097
|
+
const receiptsDir = join(options.outboxDir, "receipts", clientEventId);
|
|
339098
|
+
await ensureDurableMistakeDirectory(receiptsDir);
|
|
339099
|
+
const receiptPath = join(receiptsDir, `${body.event_id}.json`);
|
|
339100
|
+
try {
|
|
339101
|
+
await durableExclusiveWrite(receiptPath, `${JSON.stringify(body)}\n`);
|
|
339102
|
+
} catch (error) {
|
|
339103
|
+
if (!isAlreadyExists$1(error)) throw error;
|
|
339104
|
+
const existing = await readReceipt(receiptPath);
|
|
339105
|
+
if (existing !== null && existing.event_id === body.event_id && receiptMatchesEnvelope(existing, envelope)) {
|
|
339106
|
+
if (!receiptsEqual(existing, body)) throw new Error(`conflicting local receipt for ${clientEventId}`, { cause: error });
|
|
339107
|
+
} else await durableExclusiveWrite(join(receiptsDir, `${body.event_id}.${randomUUID()}.json`), `${JSON.stringify(body)}\n`);
|
|
339108
|
+
}
|
|
339109
|
+
return body;
|
|
339110
|
+
}
|
|
339111
|
+
async function uploadMistakeObservation(input, options, deps = DEFAULT_DEPS$2) {
|
|
339112
|
+
return deliverQueuedObservation((await queueMistakeObservation(input, options.outboxDir, deps)).client_event_id, options, deps);
|
|
339113
|
+
}
|
|
339114
|
+
async function drainMistakeOutbox(options, deps = DEFAULT_DEPS$2) {
|
|
339115
|
+
const eventsDir = join(options.outboxDir, "events");
|
|
339116
|
+
await ensureDurableMistakeDirectory(eventsDir);
|
|
339117
|
+
const names = (await readdir(eventsDir)).filter((name) => UUID_RE$1.test(name.replace(/\.json$/, "")) && name.endsWith(".json")).toSorted();
|
|
339118
|
+
const delivered = [];
|
|
339119
|
+
const failed = [];
|
|
339120
|
+
const pending = [];
|
|
339121
|
+
for (const name of names) {
|
|
339122
|
+
const clientEventId = name.slice(0, -5);
|
|
339123
|
+
try {
|
|
339124
|
+
const envelope = parseQueuedEnvelope(await readFile(join(eventsDir, name), "utf8"), clientEventId);
|
|
339125
|
+
if (await findVerifiedLocalReceipt(envelope, options.outboxDir) !== null) continue;
|
|
339126
|
+
pending.push(envelope);
|
|
339127
|
+
} catch (error) {
|
|
339128
|
+
failed.push({
|
|
339129
|
+
clientEventId,
|
|
339130
|
+
error: errorMessage$6(error)
|
|
339131
|
+
});
|
|
339132
|
+
}
|
|
339133
|
+
}
|
|
339134
|
+
pending.sort(compareObservationOrder);
|
|
339135
|
+
for (const envelope of pending) try {
|
|
339136
|
+
delivered.push(await deliverQueuedObservation(envelope.client_event_id, options, deps));
|
|
339137
|
+
} catch (error) {
|
|
339138
|
+
failed.push({
|
|
339139
|
+
clientEventId: envelope.client_event_id,
|
|
339140
|
+
error: errorMessage$6(error)
|
|
339141
|
+
});
|
|
339142
|
+
}
|
|
339143
|
+
return {
|
|
339144
|
+
delivered,
|
|
339145
|
+
failed
|
|
339146
|
+
};
|
|
339147
|
+
}
|
|
339148
|
+
async function getMistakeInflowStatus(endpoint, token, deps = DEFAULT_DEPS$2) {
|
|
339149
|
+
const response = await deps.fetch(endpointUrl(endpoint, "/v1/status"), {
|
|
339150
|
+
headers: { authorization: `Bearer ${token}` },
|
|
339151
|
+
redirect: "error"
|
|
339152
|
+
});
|
|
339153
|
+
const body = await readJsonResponse(response);
|
|
339154
|
+
if (response.status !== 200) throw new Error(`mistake inflow status failed: HTTP ${response.status}`);
|
|
339155
|
+
if (!isMistakeInflowStatus(body)) throw new Error("mistake inflow status returned an invalid payload");
|
|
339156
|
+
return body;
|
|
339157
|
+
}
|
|
339158
|
+
async function changeMistakeObservationState(action, eventId, reason, endpoint, token, deps = DEFAULT_DEPS$2) {
|
|
339159
|
+
if (!UUID_RE$1.test(eventId)) throw new Error("event id must be a UUID");
|
|
339160
|
+
const trimmedReason = reason.trim();
|
|
339161
|
+
if (trimmedReason.length < 3 || trimmedReason.length > 500) throw new Error("reason must contain 3-500 characters");
|
|
339162
|
+
const actionId = deps.randomUUID();
|
|
339163
|
+
if (!UUID_RE$1.test(actionId)) throw new Error("generated action id must be a UUID");
|
|
339164
|
+
const response = await deps.fetch(endpointUrl(endpoint, `/v1/observations/${eventId}:${action}`), {
|
|
339165
|
+
method: "POST",
|
|
339166
|
+
headers: {
|
|
339167
|
+
authorization: `Bearer ${token}`,
|
|
339168
|
+
"content-type": "application/json"
|
|
339169
|
+
},
|
|
339170
|
+
body: JSON.stringify({
|
|
339171
|
+
action_id: actionId,
|
|
339172
|
+
reason: trimmedReason
|
|
339173
|
+
}),
|
|
339174
|
+
redirect: "error"
|
|
339175
|
+
});
|
|
339176
|
+
const body = await readJsonResponse(response);
|
|
339177
|
+
if (response.status !== 201) {
|
|
339178
|
+
const bodyError = typeof body === "object" && body !== null ? body["error"] : void 0;
|
|
339179
|
+
const detail = typeof bodyError === "string" ? bodyError : `HTTP ${response.status}`;
|
|
339180
|
+
throw new Error(`mistake inflow ${action} failed: ${detail}`);
|
|
339181
|
+
}
|
|
339182
|
+
if (!isStateActionReceipt(body) || body.action_id !== actionId || body.action !== action || body.target_event_id !== eventId || body.reason !== trimmedReason) throw new Error(`mistake inflow ${action} returned a mismatched action receipt`);
|
|
339183
|
+
return body;
|
|
339184
|
+
}
|
|
339185
|
+
function parseQueuedEnvelope(text, expectedClientEventId) {
|
|
339186
|
+
let value;
|
|
339187
|
+
try {
|
|
339188
|
+
value = JSON.parse(text);
|
|
339189
|
+
} catch {
|
|
339190
|
+
throw new Error(`queued mistake event ${expectedClientEventId} is not valid JSON`);
|
|
339191
|
+
}
|
|
339192
|
+
if (typeof value !== "object" || value === null) throw new Error(`queued mistake event ${expectedClientEventId} is invalid`);
|
|
339193
|
+
const item = value;
|
|
339194
|
+
if (!hasOnlyKeys(item, ENVELOPE_KEYS) || item["version"] !== 1 || item["client_event_id"] !== expectedClientEventId || !UUID_RE$1.test(expectedClientEventId)) throw new Error(`queued mistake event ${expectedClientEventId} has an invalid identity`);
|
|
339195
|
+
if (typeof item["source_id"] !== "string" || !isNormalizedSourceId(item["source_id"])) throw new Error(`queued mistake event ${expectedClientEventId} has an invalid source`);
|
|
339196
|
+
if (typeof item["source_form"] !== "string" || !MISTAKE_SOURCE_FORMS.includes(item["source_form"])) throw new Error(`queued mistake event ${expectedClientEventId} has an invalid source form`);
|
|
339197
|
+
const recordTypes = item["declared_record_types"];
|
|
339198
|
+
if (!Array.isArray(recordTypes) || recordTypes.length === 0 || new Set(recordTypes).size !== recordTypes.length || recordTypes.some((type) => typeof type !== "string" || !MISTAKE_RECORD_TYPES.includes(type))) throw new Error(`queued mistake event ${expectedClientEventId} has invalid record types`);
|
|
339199
|
+
if (typeof item["original_name"] !== "string" || item["original_name"] === "" || basename(item["original_name"]) !== item["original_name"]) throw new Error(`queued mistake event ${expectedClientEventId} has an invalid original name`);
|
|
339200
|
+
if (typeof item["captured_at"] !== "string" || !isIsoTimestamp(item["captured_at"])) throw new Error(`queued mistake event ${expectedClientEventId} has an invalid capture time`);
|
|
339201
|
+
const inventory = item["inventory"];
|
|
339202
|
+
if (typeof inventory !== "object" || inventory === null) throw new Error(`queued mistake event ${expectedClientEventId} has invalid inventory metadata`);
|
|
339203
|
+
const inventoryItem = inventory;
|
|
339204
|
+
if (!hasOnlyKeys(inventoryItem, INVENTORY_KEYS) || inventoryItem["scope"] !== "lower_bound" || typeof inventoryItem["bestandsstatus"] !== "string" || !MISTAKE_INVENTORY_STATUSES.includes(inventoryItem["bestandsstatus"]) || typeof inventoryItem["aktualitaetsstatus"] !== "string" || !MISTAKE_ACTUALITY_STATUSES.includes(inventoryItem["aktualitaetsstatus"]) || !isNullableEntryCount(inventoryItem["declared_entry_count"]) || inventoryItem["last_raw_observed_at"] !== null && (typeof inventoryItem["last_raw_observed_at"] !== "string" || !isIsoTimestamp(inventoryItem["last_raw_observed_at"]))) throw new Error(`queued mistake event ${expectedClientEventId} has invalid inventory metadata`);
|
|
339205
|
+
try {
|
|
339206
|
+
assertInventoryInvariants(inventoryItem["bestandsstatus"], inventoryItem["aktualitaetsstatus"], inventoryItem["declared_entry_count"], inventoryItem["last_raw_observed_at"], item["captured_at"]);
|
|
339207
|
+
} catch (error) {
|
|
339208
|
+
throw new Error(`queued mistake event ${expectedClientEventId} has contradictory inventory metadata`, { cause: error });
|
|
339209
|
+
}
|
|
339210
|
+
if (!Number.isSafeInteger(item["declared_raw_bytes"]) || item["declared_raw_bytes"] < 0 || item["declared_raw_bytes"] > 20971520 || typeof item["declared_raw_sha256"] !== "string" || !SHA256_RE.test(item["declared_raw_sha256"]) || typeof item["payload_base64"] !== "string") throw new Error(`queued mistake event ${expectedClientEventId} has invalid payload metadata`);
|
|
339211
|
+
const payload = Buffer.from(item["payload_base64"], "base64");
|
|
339212
|
+
if (payload.toString("base64") !== item["payload_base64"] || payload.byteLength !== item["declared_raw_bytes"] || createHash("sha256").update(payload).digest("hex") !== item["declared_raw_sha256"]) throw new Error(`queued mistake event ${expectedClientEventId} failed payload integrity verification`);
|
|
339213
|
+
if (item["declarations"] !== void 0) try {
|
|
339214
|
+
parseMistakeRecordDeclarations(item["declarations"], item["source_id"], recordTypes);
|
|
339215
|
+
} catch (error) {
|
|
339216
|
+
throw new Error(`queued mistake event ${expectedClientEventId} has invalid record declarations`, { cause: error });
|
|
339217
|
+
}
|
|
339218
|
+
return value;
|
|
339219
|
+
}
|
|
339220
|
+
async function findVerifiedLocalReceipt(envelope, outboxDir) {
|
|
339221
|
+
const receiptRoot = join(outboxDir, "receipts");
|
|
339222
|
+
const paths = [join(receiptRoot, `${envelope.client_event_id}.json`)];
|
|
339223
|
+
const eventReceiptDir = join(receiptRoot, envelope.client_event_id);
|
|
339224
|
+
try {
|
|
339225
|
+
const names = (await readdir(eventReceiptDir)).filter((name) => name.endsWith(".json")).toSorted();
|
|
339226
|
+
paths.push(...names.map((name) => join(eventReceiptDir, name)));
|
|
339227
|
+
} catch (error) {
|
|
339228
|
+
if (!isNotFound$2(error)) throw error;
|
|
339229
|
+
}
|
|
339230
|
+
for (const path of paths) {
|
|
339231
|
+
const candidate = await readReceipt(path);
|
|
339232
|
+
if (candidate !== null && receiptMatchesEnvelope(candidate, envelope)) return candidate;
|
|
339233
|
+
}
|
|
339234
|
+
return null;
|
|
339235
|
+
}
|
|
339236
|
+
async function readReceipt(path) {
|
|
339237
|
+
try {
|
|
339238
|
+
const value = JSON.parse(await readFile(path, "utf8"));
|
|
339239
|
+
return isReceipt(value) ? value : null;
|
|
339240
|
+
} catch (error) {
|
|
339241
|
+
if (isNotFound$2(error) || error instanceof SyntaxError) return null;
|
|
339242
|
+
throw error;
|
|
339243
|
+
}
|
|
339244
|
+
}
|
|
339245
|
+
function receiptMatchesEnvelope(receipt, envelope) {
|
|
339246
|
+
return receipt.client_event_id === envelope.client_event_id && receipt.source_id === envelope.source_id && receipt.raw_bytes === envelope.declared_raw_bytes && receipt.raw_sha256 === envelope.declared_raw_sha256 && receipt.declared_entry_count === envelope.inventory.declared_entry_count;
|
|
339247
|
+
}
|
|
339248
|
+
function receiptsEqual(left, right) {
|
|
339249
|
+
return left.version === right.version && left.accepted === right.accepted && left.event_id === right.event_id && left.client_event_id === right.client_event_id && left.source_id === right.source_id && left.canonical_agent_id === right.canonical_agent_id && left.received_at === right.received_at && left.raw_count === right.raw_count && left.accepted_count === right.accepted_count && left.rejected_count === right.rejected_count && left.raw_bytes === right.raw_bytes && left.raw_sha256 === right.raw_sha256 && left.declared_entry_count === right.declared_entry_count;
|
|
339250
|
+
}
|
|
339251
|
+
function isStateActionReceipt(value) {
|
|
339252
|
+
if (!isRecord$12(value) || !hasOnlyKeys(value, STATE_ACTION_KEYS)) return false;
|
|
339253
|
+
const reason = value["reason"];
|
|
339254
|
+
return value["version"] === 1 && typeof value["action_id"] === "string" && UUID_RE$1.test(value["action_id"]) && (value["action"] === "remove" || value["action"] === "restore") && typeof value["target_event_id"] === "string" && UUID_RE$1.test(value["target_event_id"]) && typeof value["acted_at"] === "string" && isIsoTimestamp(value["acted_at"]) && Number.isSafeInteger(value["server_sequence"]) && value["server_sequence"] >= 1 && typeof value["principal_id"] === "string" && isNormalizedSourceId(value["principal_id"]) && typeof reason === "string" && reason.trim() === reason && reason.length >= 3 && reason.length <= 500;
|
|
339255
|
+
}
|
|
339256
|
+
function compareObservationOrder(left, right) {
|
|
339257
|
+
const leftObservedAt = left.inventory.last_raw_observed_at ?? left.captured_at;
|
|
339258
|
+
const rightObservedAt = right.inventory.last_raw_observed_at ?? right.captured_at;
|
|
339259
|
+
return Date.parse(leftObservedAt) - Date.parse(rightObservedAt) || Date.parse(left.captured_at) - Date.parse(right.captured_at) || left.source_id.localeCompare(right.source_id) || left.client_event_id.localeCompare(right.client_event_id);
|
|
339260
|
+
}
|
|
339261
|
+
async function ensureDurableMistakeDirectory(path, deps) {
|
|
339262
|
+
const io = deps ?? {
|
|
339263
|
+
lstat,
|
|
339264
|
+
mkdir,
|
|
339265
|
+
syncDirectory
|
|
339266
|
+
};
|
|
339267
|
+
const missing = [];
|
|
339268
|
+
let cursor = resolve(path);
|
|
339269
|
+
while (true) try {
|
|
339270
|
+
const existing = await io.lstat(cursor);
|
|
339271
|
+
if (existing.isSymbolicLink() || !existing.isDirectory()) throw new Error(`mistake outbox path is not a real directory: ${cursor}`);
|
|
339272
|
+
break;
|
|
339273
|
+
} catch (error) {
|
|
339274
|
+
if (!isNotFound$2(error)) throw error;
|
|
339275
|
+
missing.push(cursor);
|
|
339276
|
+
const parent = dirname(cursor);
|
|
339277
|
+
if (parent === cursor) throw new Error(`mistake outbox has no existing parent: ${path}`, { cause: error });
|
|
339278
|
+
cursor = parent;
|
|
339279
|
+
}
|
|
339280
|
+
for (const directory of missing.toReversed()) {
|
|
339281
|
+
try {
|
|
339282
|
+
await io.mkdir(directory, { mode: 448 });
|
|
339283
|
+
} catch (error) {
|
|
339284
|
+
if (!isAlreadyExists$1(error)) throw error;
|
|
339285
|
+
const raced = await io.lstat(directory);
|
|
339286
|
+
if (raced.isSymbolicLink() || !raced.isDirectory()) throw new Error(`mistake outbox path is not a real directory: ${directory}`, { cause: error });
|
|
339287
|
+
}
|
|
339288
|
+
await io.syncDirectory(dirname(directory));
|
|
339289
|
+
}
|
|
339290
|
+
}
|
|
339291
|
+
async function durableExclusiveWrite(path, contents) {
|
|
339292
|
+
const directory = dirname(path);
|
|
339293
|
+
const temporaryPath = join(directory, `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
|
|
339294
|
+
let handle;
|
|
339295
|
+
let failure;
|
|
339296
|
+
try {
|
|
339297
|
+
handle = await open(temporaryPath, "wx", 384);
|
|
339298
|
+
await handle.writeFile(contents, "utf8");
|
|
339299
|
+
await handle.sync();
|
|
339300
|
+
await handle.close();
|
|
339301
|
+
handle = void 0;
|
|
339302
|
+
await link(temporaryPath, path);
|
|
339303
|
+
await syncDirectory(directory);
|
|
339304
|
+
} catch (error) {
|
|
339305
|
+
failure = error;
|
|
339306
|
+
}
|
|
339307
|
+
if (handle !== void 0) try {
|
|
339308
|
+
await handle.close();
|
|
339309
|
+
} catch (error) {
|
|
339310
|
+
failure ??= error;
|
|
339311
|
+
}
|
|
339312
|
+
try {
|
|
339313
|
+
await unlink(temporaryPath);
|
|
339314
|
+
await syncDirectory(directory);
|
|
339315
|
+
} catch (error) {
|
|
339316
|
+
if (!isNotFound$2(error)) failure ??= error;
|
|
339317
|
+
}
|
|
339318
|
+
if (failure !== void 0) throw failure;
|
|
339319
|
+
}
|
|
339320
|
+
async function syncDirectory(path) {
|
|
339321
|
+
let handle;
|
|
339322
|
+
try {
|
|
339323
|
+
handle = await open(path, "r");
|
|
339324
|
+
await handle.sync();
|
|
339325
|
+
} catch (error) {
|
|
339326
|
+
if (process.platform !== "win32" || !isUnsupportedDirectorySync(error)) throw error;
|
|
339327
|
+
} finally {
|
|
339328
|
+
await handle?.close().catch(() => void 0);
|
|
339329
|
+
}
|
|
339330
|
+
}
|
|
339331
|
+
function isNormalizedSourceId(value) {
|
|
339332
|
+
try {
|
|
339333
|
+
return normalizeMistakeSourceId(value) === value;
|
|
339334
|
+
} catch {
|
|
339335
|
+
return false;
|
|
339336
|
+
}
|
|
339337
|
+
}
|
|
339338
|
+
function isIsoTimestamp(value) {
|
|
339339
|
+
try {
|
|
339340
|
+
assertIsoTimestamp$2(value, "timestamp");
|
|
339341
|
+
return true;
|
|
339342
|
+
} catch {
|
|
339343
|
+
return false;
|
|
339344
|
+
}
|
|
339345
|
+
}
|
|
339346
|
+
function isNullableEntryCount(value) {
|
|
339347
|
+
return value === null || Number.isSafeInteger(value) && value >= 0;
|
|
339348
|
+
}
|
|
339349
|
+
function assertInventoryInvariants(bestandsstatus, aktualitaetsstatus, declaredEntryCount, lastRawObservedAt, capturedAt) {
|
|
339350
|
+
if (bestandsstatus === "counted" && declaredEntryCount === null) throw new Error("counted inventory requires a declared entry count");
|
|
339351
|
+
if (bestandsstatus !== "counted" && declaredEntryCount !== null) throw new Error(`${bestandsstatus} inventory must not declare an entry count`);
|
|
339352
|
+
if (aktualitaetsstatus === "fresh" && lastRawObservedAt === null) throw new Error("fresh inventory requires a last raw observed timestamp");
|
|
339353
|
+
if (capturedAt !== void 0 && lastRawObservedAt !== null && Date.parse(lastRawObservedAt) > Date.parse(capturedAt)) throw new Error("last raw observed timestamp must not be later than captured at");
|
|
339354
|
+
}
|
|
339355
|
+
function isRecord$12(value) {
|
|
339356
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
339357
|
+
}
|
|
339358
|
+
function hasOnlyKeys(value, allowedKeys) {
|
|
339359
|
+
return Object.keys(value).every((key) => allowedKeys.includes(key));
|
|
339360
|
+
}
|
|
339361
|
+
function isValidRecordId(value) {
|
|
339362
|
+
const length = [...value].length;
|
|
339363
|
+
return length >= 1 && length <= 200 && value.normalize("NFKC").trim() === value && !hasControlCharacter(value);
|
|
339364
|
+
}
|
|
339365
|
+
function isSafeRawLocator(value) {
|
|
339366
|
+
const length = [...value].length;
|
|
339367
|
+
return length >= 1 && length <= 1e3 && !hasControlCharacter(value);
|
|
339368
|
+
}
|
|
339369
|
+
function hasControlCharacter(value) {
|
|
339370
|
+
return [...value].some((character) => {
|
|
339371
|
+
const codePoint = character.codePointAt(0);
|
|
339372
|
+
return codePoint !== void 0 && (codePoint < 32 || codePoint === 127);
|
|
339373
|
+
});
|
|
339374
|
+
}
|
|
339375
|
+
function isMistakeInflowStatus(value) {
|
|
339376
|
+
if (typeof value !== "object" || value === null) return false;
|
|
339377
|
+
const item = value;
|
|
339378
|
+
if (item["version"] !== 1 || item["scope"] !== "lower_bound" || typeof item["generated_at"] !== "string" || !isIsoTimestamp(item["generated_at"]) || !isNonNegativeInteger(item["stale_after_seconds"]) || !Array.isArray(item["sources"])) return false;
|
|
339379
|
+
const sourceIds = /* @__PURE__ */ new Set();
|
|
339380
|
+
for (const source of item["sources"]) {
|
|
339381
|
+
if (!isMistakeSourceStatus(source)) return false;
|
|
339382
|
+
const sourceId = source["source_id"];
|
|
339383
|
+
if (sourceIds.has(sourceId)) return false;
|
|
339384
|
+
sourceIds.add(sourceId);
|
|
339385
|
+
}
|
|
339386
|
+
return true;
|
|
339387
|
+
}
|
|
339388
|
+
function isMistakeSourceStatus(value) {
|
|
339389
|
+
if (typeof value !== "object" || value === null) return false;
|
|
339390
|
+
const item = value;
|
|
339391
|
+
const recordTypes = item["record_types"];
|
|
339392
|
+
const watchdogReasons = item["watchdog_reasons"];
|
|
339393
|
+
if (!(typeof item["source_id"] === "string" && isNormalizedSourceId(item["source_id"]) && typeof item["raw_agent_id"] === "string" && item["raw_agent_id"].trim() !== "" && typeof item["canonical_agent_id"] === "string" && isNormalizedSourceId(item["canonical_agent_id"]) && typeof item["source_form"] === "string" && MISTAKE_SOURCE_FORMS.includes(item["source_form"]) && Array.isArray(recordTypes) && recordTypes.length > 0 && new Set(recordTypes).size === recordTypes.length && recordTypes.every((type) => typeof type === "string" && MISTAKE_RECORD_TYPES.includes(type)) && typeof item["bestandsstatus"] === "string" && MISTAKE_INVENTORY_STATUSES.includes(item["bestandsstatus"]) && typeof item["aktualitaetsstatus"] === "string" && MISTAKE_ACTUALITY_STATUSES.includes(item["aktualitaetsstatus"]) && isNullableEntryCount(item["declared_entry_count"]) && isNullableIsoTimestamp(item["last_raw_observed_at"]) && isNullableIsoTimestamp(item["last_attempt_at"]) && isNullableIsoTimestamp(item["last_success_at"]) && isNonNegativeInteger(item["successful_observations"]) && isNonNegativeInteger(item["active_observations"]) && isNonNegativeInteger(item["rejected_attempts"]) && isNonNegativeInteger(item["seconds_since_success_or_monitor_start"]) && typeof item["watchdog"] === "string" && MISTAKE_WATCHDOG_STATUSES.includes(item["watchdog"]) && Array.isArray(watchdogReasons) && watchdogReasons.every((reason) => typeof reason === "string" && reason.trim() !== ""))) return false;
|
|
339394
|
+
try {
|
|
339395
|
+
assertInventoryInvariants(item["bestandsstatus"], item["aktualitaetsstatus"], item["declared_entry_count"], item["last_raw_observed_at"]);
|
|
339396
|
+
return true;
|
|
339397
|
+
} catch {
|
|
339398
|
+
return false;
|
|
339399
|
+
}
|
|
339400
|
+
}
|
|
339401
|
+
function isNullableIsoTimestamp(value) {
|
|
339402
|
+
return value === null || typeof value === "string" && isIsoTimestamp(value);
|
|
339403
|
+
}
|
|
339404
|
+
function isNonNegativeInteger(value) {
|
|
339405
|
+
return Number.isSafeInteger(value) && value >= 0;
|
|
339406
|
+
}
|
|
339407
|
+
function isAlreadyExists$1(error) {
|
|
339408
|
+
return typeof error === "object" && error !== null && error.code === "EEXIST";
|
|
339409
|
+
}
|
|
339410
|
+
function isNotFound$2(error) {
|
|
339411
|
+
return typeof error === "object" && error !== null && error.code === "ENOENT";
|
|
339412
|
+
}
|
|
339413
|
+
function isUnsupportedDirectorySync(error) {
|
|
339414
|
+
if (typeof error !== "object" || error === null) return false;
|
|
339415
|
+
return [
|
|
339416
|
+
"EACCES",
|
|
339417
|
+
"EBADF",
|
|
339418
|
+
"EINVAL",
|
|
339419
|
+
"EPERM"
|
|
339420
|
+
].includes(error.code ?? "");
|
|
339421
|
+
}
|
|
339422
|
+
function errorMessage$6(error) {
|
|
339423
|
+
return error instanceof Error ? error.message : String(error);
|
|
339424
|
+
}
|
|
339425
|
+
//#endregion
|
|
339426
|
+
//#region src/mistakes/source-sync.ts
|
|
339427
|
+
const DIRECTORY_SNAPSHOT_FORMAT = "blun.mistakes.directory-snapshot.v1";
|
|
339428
|
+
const TOKEN_ENV_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
339429
|
+
const UUID_RE = /^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;
|
|
339430
|
+
const TRANSPORT_STALE_AFTER_SECONDS = 1440 * 60;
|
|
339431
|
+
const DEFAULT_DEPS$1 = {
|
|
339432
|
+
drain: (options) => drainMistakeOutbox(options),
|
|
339433
|
+
upload: (input, options) => uploadMistakeObservation(input, options),
|
|
339434
|
+
now: () => /* @__PURE__ */ new Date()
|
|
339435
|
+
};
|
|
339436
|
+
async function loadMistakeSourceSyncConfig(configPath) {
|
|
339437
|
+
const absolutePath = resolve(configPath);
|
|
339438
|
+
const fileStat = await lstat(absolutePath);
|
|
339439
|
+
if (fileStat.isSymbolicLink() || !fileStat.isFile()) throw new Error("mistake source config must be a regular, non-symlink file");
|
|
339440
|
+
let value;
|
|
339441
|
+
try {
|
|
339442
|
+
value = JSON.parse(await readFile(absolutePath, "utf8"));
|
|
339443
|
+
} catch (error) {
|
|
339444
|
+
if (error instanceof SyntaxError) throw new Error("mistake source config is not valid JSON", { cause: error });
|
|
339445
|
+
throw error;
|
|
339446
|
+
}
|
|
339447
|
+
return parseConfig(value, dirname(absolutePath));
|
|
339448
|
+
}
|
|
339449
|
+
async function buildSourceSnapshot(adapter) {
|
|
339450
|
+
return adapter.type === "file" ? buildFileSnapshot(adapter.path) : buildDirectorySnapshot(adapter.path, {
|
|
339451
|
+
include: adapter.include,
|
|
339452
|
+
recursive: adapter.recursive
|
|
339453
|
+
});
|
|
339454
|
+
}
|
|
339455
|
+
async function buildDirectorySnapshot(path, options = {}) {
|
|
339456
|
+
const root = resolve(path);
|
|
339457
|
+
const rootStat = await lstat(root);
|
|
339458
|
+
if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) throw new Error(`directory source must be a regular, non-symlink directory: ${root}`);
|
|
339459
|
+
const canonicalRoot = await realpath(root);
|
|
339460
|
+
const include = options.include === void 0 ? void 0 : validateIncludePatterns(options.include, "directory include");
|
|
339461
|
+
const recursive = options.recursive ?? true;
|
|
339462
|
+
const files = await readDirectoryFiles(root, canonicalRoot, recursive, include === void 0 ? void 0 : compileIncludePatterns(include));
|
|
339463
|
+
if (include !== void 0 && files.length === 0) throw new Error(`directory include matched no regular files: ${include.join(", ")}`);
|
|
339464
|
+
const orderedFiles = files.toSorted((left, right) => Buffer.compare(Buffer.from(left.path), Buffer.from(right.path)));
|
|
339465
|
+
const totalBytes = orderedFiles.reduce((sum, file) => sum + file.bytes, 0);
|
|
339466
|
+
const latestMtimeMs = orderedFiles.reduce((latest, file) => latest === null || file.mtimeMs > latest ? file.mtimeMs : latest, null);
|
|
339467
|
+
const document = {
|
|
339468
|
+
format: DIRECTORY_SNAPSHOT_FORMAT,
|
|
339469
|
+
version: 1,
|
|
339470
|
+
file_count: orderedFiles.length,
|
|
339471
|
+
total_bytes: totalBytes,
|
|
339472
|
+
latest_mtime: latestMtimeMs === null ? null : new Date(Math.trunc(latestMtimeMs)).toISOString(),
|
|
339473
|
+
selection: {
|
|
339474
|
+
include: include === void 0 ? null : include.toSorted(compareUtf8),
|
|
339475
|
+
recursive
|
|
339476
|
+
},
|
|
339477
|
+
files: orderedFiles.map(({ mtimeMs: _mtimeMs, ...file }) => file)
|
|
339478
|
+
};
|
|
339479
|
+
const payload = Buffer.from(`${JSON.stringify(document)}\n`, "utf8");
|
|
339480
|
+
assertSnapshotSize(payload);
|
|
339481
|
+
return snapshotResult("directory", "directory-snapshot.json", payload, orderedFiles.length, totalBytes, document.latest_mtime);
|
|
339482
|
+
}
|
|
339483
|
+
async function syncMistakeSources(options, deps = DEFAULT_DEPS$1) {
|
|
339484
|
+
const configPath = resolve(options.configPath);
|
|
339485
|
+
const config = await loadMistakeSourceSyncConfig(configPath);
|
|
339486
|
+
const baseOutbox = resolve(options.outboxDir ?? config.outbox ?? join(dirname(configPath), ".mistake-inflow-outbox"));
|
|
339487
|
+
const startedAt = deps.now().toISOString();
|
|
339488
|
+
const results = [];
|
|
339489
|
+
for (const source of config.sources.toSorted((left, right) => compareUtf8(left.sourceId, right.sourceId))) {
|
|
339490
|
+
if (source.adapter.type === "unsupported") {
|
|
339491
|
+
results.push({
|
|
339492
|
+
source_id: source.sourceId,
|
|
339493
|
+
agent_id: source.agentId,
|
|
339494
|
+
adapter: "unsupported",
|
|
339495
|
+
bestandsstatus: source.bestandsstatus,
|
|
339496
|
+
aktualitaetsstatus: source.aktualitaetsstatus,
|
|
339497
|
+
status: "blocked",
|
|
339498
|
+
retry: null,
|
|
339499
|
+
entry_count: entryCountResult(source),
|
|
339500
|
+
snapshot: null,
|
|
339501
|
+
reason: source.adapter.reason
|
|
339502
|
+
});
|
|
339503
|
+
continue;
|
|
339504
|
+
}
|
|
339505
|
+
const sourceOutbox = join(baseOutbox, "sources", source.sourceId);
|
|
339506
|
+
let retry = null;
|
|
339507
|
+
try {
|
|
339508
|
+
await assertOutboxOutsideSource(source.adapter, sourceOutbox);
|
|
339509
|
+
const endpoint = options.endpoint ?? source.endpoint ?? config.endpoint;
|
|
339510
|
+
if (!endpoint) throw new Error("no endpoint configured");
|
|
339511
|
+
const tokenEnv = source.tokenEnv;
|
|
339512
|
+
if (!tokenEnv) throw new Error("supported source has no token_env");
|
|
339513
|
+
const token = options.env[tokenEnv];
|
|
339514
|
+
if (!token || token.trim() === "") throw new Error(`missing bearer token in ${tokenEnv}`);
|
|
339515
|
+
const connection = {
|
|
339516
|
+
endpoint,
|
|
339517
|
+
token,
|
|
339518
|
+
outboxDir: sourceOutbox
|
|
339519
|
+
};
|
|
339520
|
+
retry = await deps.drain(connection);
|
|
339521
|
+
if (retry.failed.length > 0) throw new Error(`retry failed for ${retry.failed.length} queued observation(s)`);
|
|
339522
|
+
const snapshot = await buildSourceSnapshot(source.adapter);
|
|
339523
|
+
assertEntryCountBasis(source, snapshot);
|
|
339524
|
+
const declarations = source.declarationsPath === void 0 ? void 0 : await readExplicitDeclarations(source.declarationsPath, source.sourceId, source.recordTypes);
|
|
339525
|
+
const capturedAt = deps.now().toISOString();
|
|
339526
|
+
const input = observationInput(source, snapshot, capturedAt, declarations);
|
|
339527
|
+
const existing = await findVerifiedSnapshotReceipt(source, snapshot, input, sourceOutbox);
|
|
339528
|
+
const heartbeatIntervalSeconds = source.heartbeatIntervalSeconds ?? config.heartbeatIntervalSeconds;
|
|
339529
|
+
if (existing !== null && receiptIsWithinHeartbeat(existing, capturedAt, heartbeatIntervalSeconds)) {
|
|
339530
|
+
results.push(resultForSnapshot(source, snapshot, "unchanged", retry, existing));
|
|
339531
|
+
continue;
|
|
339532
|
+
}
|
|
339533
|
+
const materializedPath = await materializeSnapshot(snapshot, sourceOutbox);
|
|
339534
|
+
const receipt = await deps.upload({
|
|
339535
|
+
...input,
|
|
339536
|
+
filePath: materializedPath
|
|
339537
|
+
}, connection);
|
|
339538
|
+
assertReceiptIdentity(receipt, source, snapshot, input.declaredEntryCount);
|
|
339539
|
+
results.push(resultForSnapshot(source, snapshot, existing === null ? "uploaded" : "heartbeat", retry, receipt, existing ?? void 0));
|
|
339540
|
+
} catch (error) {
|
|
339541
|
+
results.push({
|
|
339542
|
+
source_id: source.sourceId,
|
|
339543
|
+
agent_id: source.agentId,
|
|
339544
|
+
adapter: source.adapter.type,
|
|
339545
|
+
bestandsstatus: source.bestandsstatus,
|
|
339546
|
+
aktualitaetsstatus: source.aktualitaetsstatus,
|
|
339547
|
+
status: "failed",
|
|
339548
|
+
retry: retry === null ? null : {
|
|
339549
|
+
delivered: retry.delivered.length,
|
|
339550
|
+
failed: retry.failed.length
|
|
339551
|
+
},
|
|
339552
|
+
entry_count: entryCountResult(source, false),
|
|
339553
|
+
snapshot: null,
|
|
339554
|
+
reason: errorMessage$5(error)
|
|
339555
|
+
});
|
|
339556
|
+
}
|
|
339557
|
+
}
|
|
339558
|
+
return {
|
|
339559
|
+
version: 1,
|
|
339560
|
+
config_path: configPath,
|
|
339561
|
+
started_at: startedAt,
|
|
339562
|
+
finished_at: deps.now().toISOString(),
|
|
339563
|
+
results
|
|
339564
|
+
};
|
|
339565
|
+
}
|
|
339566
|
+
async function watchMistakeSources(options, deps = DEFAULT_DEPS$1) {
|
|
339567
|
+
if (!Number.isSafeInteger(options.intervalMs) || options.intervalMs < 1e3) throw new Error("watch interval must be at least 1000 milliseconds");
|
|
339568
|
+
while (!options.signal?.aborted) {
|
|
339569
|
+
await options.onRun(await syncMistakeSources(options, deps));
|
|
339570
|
+
await waitForInterval(options.intervalMs, options.signal);
|
|
339571
|
+
}
|
|
339572
|
+
}
|
|
339573
|
+
function parseConfig(value, configDir) {
|
|
339574
|
+
const root = objectValue(value, "config");
|
|
339575
|
+
exactKeys(root, [
|
|
339576
|
+
"version",
|
|
339577
|
+
"endpoint",
|
|
339578
|
+
"outbox",
|
|
339579
|
+
"heartbeat_interval_seconds",
|
|
339580
|
+
"sources"
|
|
339581
|
+
], "config");
|
|
339582
|
+
if (root["version"] !== 1) throw new Error("mistake source config version must be 1");
|
|
339583
|
+
const endpoint = optionalNonEmptyString$1(root["endpoint"], "config.endpoint");
|
|
339584
|
+
const outboxValue = optionalNonEmptyString$1(root["outbox"], "config.outbox");
|
|
339585
|
+
const heartbeatIntervalSeconds = heartbeatInterval(root["heartbeat_interval_seconds"], "config.heartbeat_interval_seconds") ?? 43200;
|
|
339586
|
+
const sourcesValue = root["sources"];
|
|
339587
|
+
if (!Array.isArray(sourcesValue) || sourcesValue.length === 0) throw new Error("config.sources must be a non-empty array");
|
|
339588
|
+
const sources = sourcesValue.map((source, index) => parseSource(source, index, configDir));
|
|
339589
|
+
const sourceIds = sources.map((source) => source.sourceId);
|
|
339590
|
+
if (new Set(sourceIds).size !== sourceIds.length) throw new Error("config contains duplicate normalized source ids");
|
|
339591
|
+
const tokenEnvs = sources.flatMap((source) => source.tokenEnv === void 0 ? [] : [source.tokenEnv]);
|
|
339592
|
+
if (new Set(tokenEnvs).size !== tokenEnvs.length) throw new Error("each supported source must use its own token_env");
|
|
339593
|
+
return {
|
|
339594
|
+
version: 1,
|
|
339595
|
+
endpoint,
|
|
339596
|
+
outbox: outboxValue === void 0 ? void 0 : configuredPath(outboxValue, configDir, "config.outbox"),
|
|
339597
|
+
heartbeatIntervalSeconds,
|
|
339598
|
+
sources
|
|
339599
|
+
};
|
|
339600
|
+
}
|
|
339601
|
+
function parseSource(value, index, configDir) {
|
|
339602
|
+
const label = `config.sources[${index}]`;
|
|
339603
|
+
const source = objectValue(value, label);
|
|
339604
|
+
exactKeys(source, [
|
|
339605
|
+
"source_id",
|
|
339606
|
+
"agent_id",
|
|
339607
|
+
"endpoint",
|
|
339608
|
+
"token_env",
|
|
339609
|
+
"heartbeat_interval_seconds",
|
|
339610
|
+
"source_form",
|
|
339611
|
+
"record_types",
|
|
339612
|
+
"bestandsstatus",
|
|
339613
|
+
"aktualitaetsstatus",
|
|
339614
|
+
"declared_entry_count",
|
|
339615
|
+
"entry_count_basis",
|
|
339616
|
+
"declarations_path",
|
|
339617
|
+
"adapter"
|
|
339618
|
+
], label);
|
|
339619
|
+
const sourceId = normalizeMistakeSourceId(nonEmptyString(source["source_id"], `${label}.source_id`));
|
|
339620
|
+
const agentId = normalizeMistakeSourceId(nonEmptyString(source["agent_id"], `${label}.agent_id`));
|
|
339621
|
+
const sourceForm = enumValue(source["source_form"], MISTAKE_SOURCE_FORMS, `${label}.source_form`);
|
|
339622
|
+
const recordTypes = enumArray(source["record_types"], MISTAKE_RECORD_TYPES, `${label}.record_types`);
|
|
339623
|
+
const bestandsstatus = enumValue(source["bestandsstatus"], MISTAKE_INVENTORY_STATUSES, `${label}.bestandsstatus`);
|
|
339624
|
+
const aktualitaetsstatus = enumValue(source["aktualitaetsstatus"], MISTAKE_ACTUALITY_STATUSES, `${label}.aktualitaetsstatus`);
|
|
339625
|
+
const endpoint = optionalNonEmptyString$1(source["endpoint"], `${label}.endpoint`);
|
|
339626
|
+
const tokenEnv = optionalNonEmptyString$1(source["token_env"], `${label}.token_env`);
|
|
339627
|
+
const heartbeatIntervalSeconds = heartbeatInterval(source["heartbeat_interval_seconds"], `${label}.heartbeat_interval_seconds`);
|
|
339628
|
+
const declaredEntryCount = optionalCount(source["declared_entry_count"], `${label}.declared_entry_count`);
|
|
339629
|
+
const entryCountBasis = optionalEnumValue(source["entry_count_basis"], ["files", "declared"], `${label}.entry_count_basis`);
|
|
339630
|
+
const declarationsValue = optionalNonEmptyString$1(source["declarations_path"], `${label}.declarations_path`);
|
|
339631
|
+
const declarationsPath = declarationsValue === void 0 ? void 0 : configuredPath(declarationsValue, configDir, `${label}.declarations_path`);
|
|
339632
|
+
const adapter = parseAdapter(source["adapter"], label, configDir);
|
|
339633
|
+
if (bestandsstatus === "counted" && declaredEntryCount === void 0) throw new Error(`${label}.declared_entry_count is required when bestandsstatus is counted`);
|
|
339634
|
+
if (bestandsstatus === "counted" && entryCountBasis === void 0) throw new Error(`${label}.entry_count_basis is required when bestandsstatus is counted`);
|
|
339635
|
+
if (bestandsstatus !== "counted" && declaredEntryCount !== void 0) throw new Error(`${label}.declared_entry_count is forbidden unless bestandsstatus is counted`);
|
|
339636
|
+
if (bestandsstatus !== "counted" && entryCountBasis !== void 0) throw new Error(`${label}.entry_count_basis is forbidden unless bestandsstatus is counted`);
|
|
339637
|
+
if (adapter.type === "unsupported") {
|
|
339638
|
+
if (bestandsstatus !== "unverified" || aktualitaetsstatus !== "unverified") throw new Error(`${label} unsupported adapters must use unverified inventory and actuality statuses`);
|
|
339639
|
+
if (tokenEnv !== void 0 || endpoint !== void 0 || heartbeatIntervalSeconds !== void 0 || declarationsPath !== void 0) throw new Error(`${label} unsupported adapters must not declare endpoint, token_env, heartbeat_interval_seconds, or declarations_path`);
|
|
339640
|
+
} else if (tokenEnv === void 0 || !TOKEN_ENV_RE.test(tokenEnv)) throw new Error(`${label}.token_env must name a dedicated environment variable`);
|
|
339641
|
+
return {
|
|
339642
|
+
sourceId,
|
|
339643
|
+
agentId,
|
|
339644
|
+
endpoint,
|
|
339645
|
+
tokenEnv,
|
|
339646
|
+
heartbeatIntervalSeconds,
|
|
339647
|
+
sourceForm,
|
|
339648
|
+
recordTypes,
|
|
339649
|
+
bestandsstatus,
|
|
339650
|
+
aktualitaetsstatus,
|
|
339651
|
+
declaredEntryCount,
|
|
339652
|
+
entryCountBasis,
|
|
339653
|
+
declarationsPath,
|
|
339654
|
+
adapter
|
|
339655
|
+
};
|
|
339656
|
+
}
|
|
339657
|
+
function parseAdapter(value, sourceLabel, configDir) {
|
|
339658
|
+
const label = `${sourceLabel}.adapter`;
|
|
339659
|
+
const adapter = objectValue(value, label);
|
|
339660
|
+
const type = adapter["type"];
|
|
339661
|
+
if (type === "file" || type === "directory") {
|
|
339662
|
+
if (type === "file") {
|
|
339663
|
+
exactKeys(adapter, ["type", "path"], label);
|
|
339664
|
+
return {
|
|
339665
|
+
type,
|
|
339666
|
+
path: configuredPath(nonEmptyString(adapter["path"], `${label}.path`), configDir, `${label}.path`)
|
|
339667
|
+
};
|
|
339668
|
+
}
|
|
339669
|
+
exactKeys(adapter, [
|
|
339670
|
+
"type",
|
|
339671
|
+
"path",
|
|
339672
|
+
"include",
|
|
339673
|
+
"recursive"
|
|
339674
|
+
], label);
|
|
339675
|
+
const include = adapter["include"] === void 0 ? void 0 : validateIncludePatterns(adapter["include"], `${label}.include`);
|
|
339676
|
+
const recursive = adapter["recursive"] === void 0 ? true : booleanValue(adapter["recursive"], `${label}.recursive`);
|
|
339677
|
+
return {
|
|
339678
|
+
type,
|
|
339679
|
+
path: configuredPath(nonEmptyString(adapter["path"], `${label}.path`), configDir, `${label}.path`),
|
|
339680
|
+
include,
|
|
339681
|
+
recursive
|
|
339682
|
+
};
|
|
339683
|
+
}
|
|
339684
|
+
if (type === "unsupported") {
|
|
339685
|
+
exactKeys(adapter, [
|
|
339686
|
+
"type",
|
|
339687
|
+
"kind",
|
|
339688
|
+
"reason"
|
|
339689
|
+
], label);
|
|
339690
|
+
return {
|
|
339691
|
+
type,
|
|
339692
|
+
kind: nonEmptyString(adapter["kind"], `${label}.kind`),
|
|
339693
|
+
reason: nonEmptyString(adapter["reason"], `${label}.reason`)
|
|
339694
|
+
};
|
|
339695
|
+
}
|
|
339696
|
+
throw new Error(`${label}.type must be file, directory, or unsupported`);
|
|
339697
|
+
}
|
|
339698
|
+
async function buildFileSnapshot(path) {
|
|
339699
|
+
const absolutePath = resolve(path);
|
|
339700
|
+
const before = await lstat(absolutePath);
|
|
339701
|
+
if (before.isSymbolicLink() || !before.isFile()) throw new Error(`file source must be a regular, non-symlink file: ${absolutePath}`);
|
|
339702
|
+
const handle = await openWithoutFollowing(absolutePath);
|
|
339703
|
+
let payload;
|
|
339704
|
+
try {
|
|
339705
|
+
const opened = await handle.stat();
|
|
339706
|
+
if (!opened.isFile()) throw new Error(`file source changed while reading: ${absolutePath}`);
|
|
339707
|
+
if (before.size !== opened.size || before.mtimeMs !== opened.mtimeMs) throw new Error(`file source changed while opening: ${absolutePath}`);
|
|
339708
|
+
payload = await handle.readFile();
|
|
339709
|
+
const after = await handle.stat();
|
|
339710
|
+
if (opened.size !== after.size || opened.mtimeMs !== after.mtimeMs) throw new Error(`file source changed while reading: ${absolutePath}`);
|
|
339711
|
+
} finally {
|
|
339712
|
+
await handle.close();
|
|
339713
|
+
}
|
|
339714
|
+
assertSnapshotSize(payload);
|
|
339715
|
+
return snapshotResult("file", basename(absolutePath), payload, 1, payload.byteLength, new Date(Math.trunc(before.mtimeMs)).toISOString());
|
|
339716
|
+
}
|
|
339717
|
+
async function readDirectoryFiles(root, canonicalRoot, recursive, matches) {
|
|
339718
|
+
const files = [];
|
|
339719
|
+
async function visit(directory) {
|
|
339720
|
+
const entries = (await readdir(directory, { withFileTypes: true })).toSorted((left, right) => Buffer.compare(Buffer.from(left.name), Buffer.from(right.name)));
|
|
339721
|
+
for (const entry of entries) {
|
|
339722
|
+
const absolutePath = join(directory, entry.name);
|
|
339723
|
+
const entryStat = await lstat(absolutePath);
|
|
339724
|
+
if (entry.isSymbolicLink() || entryStat.isSymbolicLink()) throw new Error(`directory source contains a symlink: ${absolutePath}`);
|
|
339725
|
+
const relativePath = canonicalRelativePath(root, absolutePath);
|
|
339726
|
+
assertContained(canonicalRoot, await realpath(absolutePath), absolutePath);
|
|
339727
|
+
if (entryStat.isDirectory()) {
|
|
339728
|
+
if (recursive) await visit(absolutePath);
|
|
339729
|
+
continue;
|
|
339730
|
+
}
|
|
339731
|
+
if (!entryStat.isFile()) throw new Error(`directory source contains a non-regular entry: ${absolutePath}`);
|
|
339732
|
+
if (matches !== void 0 && !matches(relativePath)) continue;
|
|
339733
|
+
const handle = await openWithoutFollowing(absolutePath);
|
|
339734
|
+
let content;
|
|
339735
|
+
try {
|
|
339736
|
+
const before = await handle.stat();
|
|
339737
|
+
if (!before.isFile()) throw new Error(`directory source entry changed while reading: ${absolutePath}`);
|
|
339738
|
+
if (entryStat.size !== before.size || entryStat.mtimeMs !== before.mtimeMs) throw new Error(`directory source entry changed while opening: ${absolutePath}`);
|
|
339739
|
+
content = await handle.readFile();
|
|
339740
|
+
const after = await handle.stat();
|
|
339741
|
+
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs) throw new Error(`directory source entry changed while reading: ${absolutePath}`);
|
|
339742
|
+
} finally {
|
|
339743
|
+
await handle.close();
|
|
339744
|
+
}
|
|
339745
|
+
files.push({
|
|
339746
|
+
path: relativePath,
|
|
339747
|
+
bytes: content.byteLength,
|
|
339748
|
+
sha256: sha256$3(content),
|
|
339749
|
+
mtime: new Date(Math.trunc(entryStat.mtimeMs)).toISOString(),
|
|
339750
|
+
content_base64: content.toString("base64"),
|
|
339751
|
+
mtimeMs: entryStat.mtimeMs
|
|
339752
|
+
});
|
|
339753
|
+
}
|
|
339754
|
+
}
|
|
339755
|
+
await visit(root);
|
|
339756
|
+
const secondScan = await scanDirectoryMetadata(root, canonicalRoot, recursive, matches);
|
|
339757
|
+
const firstScan = files.map((file) => ({
|
|
339758
|
+
path: file.path,
|
|
339759
|
+
bytes: file.bytes,
|
|
339760
|
+
mtimeMs: file.mtimeMs
|
|
339761
|
+
})).toSorted(compareMetadata);
|
|
339762
|
+
if (JSON.stringify(firstScan) !== JSON.stringify(secondScan)) throw new Error("directory source changed while snapshotting");
|
|
339763
|
+
return files;
|
|
339764
|
+
}
|
|
339765
|
+
async function scanDirectoryMetadata(root, canonicalRoot, recursive, matches) {
|
|
339766
|
+
const files = [];
|
|
339767
|
+
async function visit(directory) {
|
|
339768
|
+
const entries = (await readdir(directory, { withFileTypes: true })).toSorted((left, right) => Buffer.compare(Buffer.from(left.name), Buffer.from(right.name)));
|
|
339769
|
+
for (const entry of entries) {
|
|
339770
|
+
const absolutePath = join(directory, entry.name);
|
|
339771
|
+
const entryStat = await lstat(absolutePath);
|
|
339772
|
+
if (entry.isSymbolicLink() || entryStat.isSymbolicLink()) throw new Error(`directory source contains a symlink: ${absolutePath}`);
|
|
339773
|
+
const relativePath = canonicalRelativePath(root, absolutePath);
|
|
339774
|
+
assertContained(canonicalRoot, await realpath(absolutePath), absolutePath);
|
|
339775
|
+
if (entryStat.isDirectory()) {
|
|
339776
|
+
if (recursive) await visit(absolutePath);
|
|
339777
|
+
continue;
|
|
339778
|
+
}
|
|
339779
|
+
if (!entryStat.isFile()) throw new Error(`directory source contains a non-regular entry: ${absolutePath}`);
|
|
339780
|
+
if (matches === void 0 || matches(relativePath)) files.push({
|
|
339781
|
+
path: relativePath,
|
|
339782
|
+
bytes: entryStat.size,
|
|
339783
|
+
mtimeMs: entryStat.mtimeMs
|
|
339784
|
+
});
|
|
339785
|
+
}
|
|
339786
|
+
}
|
|
339787
|
+
await visit(root);
|
|
339788
|
+
return files.toSorted(compareMetadata);
|
|
339789
|
+
}
|
|
339790
|
+
function compareMetadata(left, right) {
|
|
339791
|
+
return compareUtf8(left.path, right.path) || left.bytes - right.bytes || left.mtimeMs - right.mtimeMs;
|
|
339792
|
+
}
|
|
339793
|
+
async function openWithoutFollowing(path) {
|
|
339794
|
+
const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
|
|
339795
|
+
try {
|
|
339796
|
+
return await open(path, constants.O_RDONLY | noFollow);
|
|
339797
|
+
} catch (error) {
|
|
339798
|
+
if (isSymlinkOpenError(error)) throw new Error(`refusing to follow source symlink: ${path}`, { cause: error });
|
|
339799
|
+
throw error;
|
|
339800
|
+
}
|
|
339801
|
+
}
|
|
339802
|
+
function canonicalRelativePath(root, path) {
|
|
339803
|
+
const value = relative(root, path);
|
|
339804
|
+
const segments = value.split(sep);
|
|
339805
|
+
if (value === "" || isAbsolute(value) || segments.some((segment) => segment === "" || segment === "." || segment === "..")) throw new Error(`source entry escapes its configured directory: ${path}`);
|
|
339806
|
+
const canonical = segments.join("/");
|
|
339807
|
+
if (canonical.startsWith("/") || canonical.includes("/../") || canonical.includes("\\")) throw new Error(`source entry has an unsafe relative path: ${path}`);
|
|
339808
|
+
return canonical;
|
|
339809
|
+
}
|
|
339810
|
+
function assertContained(root, candidate, originalPath) {
|
|
339811
|
+
const value = relative(root, candidate);
|
|
339812
|
+
if (value === ".." || value.startsWith(`..${sep}`) || isAbsolute(value)) throw new Error(`source entry resolves outside its configured directory: ${originalPath}`);
|
|
339813
|
+
}
|
|
339814
|
+
function snapshotResult(adapterType, originalName, payload, fileCount, totalBytes, latestMtime) {
|
|
339815
|
+
return {
|
|
339816
|
+
adapterType,
|
|
339817
|
+
originalName,
|
|
339818
|
+
payload,
|
|
339819
|
+
rawBytes: payload.byteLength,
|
|
339820
|
+
rawSha256: sha256$3(payload),
|
|
339821
|
+
fileCount,
|
|
339822
|
+
totalBytes,
|
|
339823
|
+
latestMtime
|
|
339824
|
+
};
|
|
339825
|
+
}
|
|
339826
|
+
function observationInput(source, snapshot, capturedAt, declarations) {
|
|
339827
|
+
return {
|
|
339828
|
+
sourceId: source.sourceId,
|
|
339829
|
+
sourceForm: source.sourceForm,
|
|
339830
|
+
recordTypes: source.recordTypes,
|
|
339831
|
+
bestandsstatus: source.bestandsstatus,
|
|
339832
|
+
aktualitaetsstatus: source.aktualitaetsstatus,
|
|
339833
|
+
declaredEntryCount: source.declaredEntryCount,
|
|
339834
|
+
lastRawObservedAt: snapshot.latestMtime ?? void 0,
|
|
339835
|
+
capturedAt,
|
|
339836
|
+
declarations
|
|
339837
|
+
};
|
|
339838
|
+
}
|
|
339839
|
+
async function readExplicitDeclarations(path, sourceId, recordTypes) {
|
|
339840
|
+
const fileStat = await lstat(path);
|
|
339841
|
+
if (fileStat.isSymbolicLink() || !fileStat.isFile()) throw new Error(`declarations_path must be a regular, non-symlink file: ${path}`);
|
|
339842
|
+
const handle = await openWithoutFollowing(path);
|
|
339843
|
+
let text;
|
|
339844
|
+
try {
|
|
339845
|
+
const opened = await handle.stat();
|
|
339846
|
+
if (fileStat.size !== opened.size || fileStat.mtimeMs !== opened.mtimeMs) throw new Error(`declarations_path changed while opening: ${path}`);
|
|
339847
|
+
text = await handle.readFile("utf8");
|
|
339848
|
+
const after = await handle.stat();
|
|
339849
|
+
if (opened.size !== after.size || opened.mtimeMs !== after.mtimeMs) throw new Error(`declarations_path changed while reading: ${path}`);
|
|
339850
|
+
} finally {
|
|
339851
|
+
await handle.close();
|
|
339852
|
+
}
|
|
339853
|
+
let value;
|
|
339854
|
+
try {
|
|
339855
|
+
value = JSON.parse(text);
|
|
339856
|
+
} catch (error) {
|
|
339857
|
+
throw new Error(`declarations_path is not valid JSON: ${path}`, { cause: error });
|
|
339858
|
+
}
|
|
339859
|
+
return parseMistakeRecordDeclarations(value, sourceId, recordTypes);
|
|
339860
|
+
}
|
|
339861
|
+
async function materializeSnapshot(snapshot, outboxDir) {
|
|
339862
|
+
const directory = join(outboxDir, "snapshots", snapshot.rawSha256);
|
|
339863
|
+
await mkdir(directory, {
|
|
339864
|
+
recursive: true,
|
|
339865
|
+
mode: 448
|
|
339866
|
+
});
|
|
339867
|
+
const path = join(directory, snapshot.originalName);
|
|
339868
|
+
try {
|
|
339869
|
+
await writeFile(path, snapshot.payload, {
|
|
339870
|
+
flag: "wx",
|
|
339871
|
+
mode: 384
|
|
339872
|
+
});
|
|
339873
|
+
} catch (error) {
|
|
339874
|
+
if (!isAlreadyExists(error)) throw error;
|
|
339875
|
+
if (!(await readFile(path)).equals(snapshot.payload)) throw new Error(`snapshot cache conflict for ${snapshot.rawSha256}`, { cause: error });
|
|
339876
|
+
}
|
|
339877
|
+
return path;
|
|
339878
|
+
}
|
|
339879
|
+
async function findVerifiedSnapshotReceipt(source, snapshot, input, outboxDir) {
|
|
339880
|
+
const eventsDir = join(outboxDir, "events");
|
|
339881
|
+
let names;
|
|
339882
|
+
try {
|
|
339883
|
+
names = (await readdir(eventsDir)).filter((name) => name.endsWith(".json")).toSorted();
|
|
339884
|
+
} catch (error) {
|
|
339885
|
+
if (isNotFound$1(error)) return null;
|
|
339886
|
+
throw error;
|
|
339887
|
+
}
|
|
339888
|
+
let newest = null;
|
|
339889
|
+
for (const name of names) {
|
|
339890
|
+
const event = await readJson(join(eventsDir, name));
|
|
339891
|
+
if (!eventMatchesSnapshot(event, source, snapshot, input)) continue;
|
|
339892
|
+
const clientEventId = event.client_event_id;
|
|
339893
|
+
const paths = [join(outboxDir, "receipts", `${clientEventId}.json`)];
|
|
339894
|
+
try {
|
|
339895
|
+
const receiptNames = (await readdir(join(outboxDir, "receipts", clientEventId))).filter((receiptName) => receiptName.endsWith(".json")).toSorted();
|
|
339896
|
+
paths.push(...receiptNames.map((receiptName) => join(outboxDir, "receipts", clientEventId, receiptName)));
|
|
339897
|
+
} catch (error) {
|
|
339898
|
+
if (!isNotFound$1(error)) throw error;
|
|
339899
|
+
}
|
|
339900
|
+
for (const path of paths) {
|
|
339901
|
+
const receipt = await readJson(path);
|
|
339902
|
+
if (receiptMatchesSnapshot(receipt, source, snapshot, event.inventory.declared_entry_count, event.client_event_id)) {
|
|
339903
|
+
if (newest === null || compareReceiptsByReceivedAt(receipt, newest) > 0) newest = receipt;
|
|
339904
|
+
}
|
|
339905
|
+
}
|
|
339906
|
+
}
|
|
339907
|
+
return newest;
|
|
339908
|
+
}
|
|
339909
|
+
function compareReceiptsByReceivedAt(left, right) {
|
|
339910
|
+
return Date.parse(left.received_at) - Date.parse(right.received_at) || compareUtf8(left.event_id, right.event_id);
|
|
339911
|
+
}
|
|
339912
|
+
function receiptIsWithinHeartbeat(receipt, nowIso, heartbeatIntervalSeconds) {
|
|
339913
|
+
const ageMilliseconds = Date.parse(nowIso) - Date.parse(receipt.received_at);
|
|
339914
|
+
return ageMilliseconds >= 0 && ageMilliseconds < heartbeatIntervalSeconds * 1e3;
|
|
339915
|
+
}
|
|
339916
|
+
function eventMatchesSnapshot(value, source, snapshot, input) {
|
|
339917
|
+
if (!isObject$3(value)) return false;
|
|
339918
|
+
const inventory = value["inventory"];
|
|
339919
|
+
if (!isObject$3(inventory)) return false;
|
|
339920
|
+
const payloadBase64 = value["payload_base64"];
|
|
339921
|
+
if (typeof payloadBase64 !== "string") return false;
|
|
339922
|
+
const payload = Buffer.from(payloadBase64, "base64");
|
|
339923
|
+
return payload.toString("base64") === payloadBase64 && payload.equals(snapshot.payload) && value["version"] === 1 && value["source_id"] === source.sourceId && value["source_form"] === source.sourceForm && arraysEqual(value["declared_record_types"], source.recordTypes) && value["declared_raw_bytes"] === snapshot.rawBytes && value["declared_raw_sha256"] === snapshot.rawSha256 && sha256$3(payload) === snapshot.rawSha256 && inventory["scope"] === "lower_bound" && inventory["bestandsstatus"] === source.bestandsstatus && inventory["aktualitaetsstatus"] === source.aktualitaetsstatus && inventory["declared_entry_count"] === (input.declaredEntryCount ?? null) && inventory["last_raw_observed_at"] === (input.lastRawObservedAt ?? null) && declarationsEqual(value["declarations"], input.declarations) && typeof value["client_event_id"] === "string" && UUID_RE.test(value["client_event_id"]);
|
|
339924
|
+
}
|
|
339925
|
+
function receiptMatchesSnapshot(value, source, snapshot, declaredEntryCount, expectedClientEventId) {
|
|
339926
|
+
if (!isObject$3(value)) return false;
|
|
339927
|
+
return value["version"] === 1 && value["accepted"] === true && value["source_id"] === source.sourceId && value["canonical_agent_id"] === source.agentId && value["raw_count"] === 1 && value["accepted_count"] === 1 && value["rejected_count"] === 0 && value["raw_bytes"] === snapshot.rawBytes && value["raw_sha256"] === snapshot.rawSha256 && value["declared_entry_count"] === declaredEntryCount && typeof value["event_id"] === "string" && UUID_RE.test(value["event_id"]) && typeof value["client_event_id"] === "string" && UUID_RE.test(value["client_event_id"]) && (expectedClientEventId === void 0 || value["client_event_id"] === expectedClientEventId) && typeof value["received_at"] === "string" && Number.isFinite(Date.parse(value["received_at"]));
|
|
339928
|
+
}
|
|
339929
|
+
function assertReceiptIdentity(receipt, source, snapshot, declaredEntryCount) {
|
|
339930
|
+
if (!receiptMatchesSnapshot(receipt, source, snapshot, declaredEntryCount ?? null, receipt.client_event_id)) throw new Error(`receipt identity mismatch for ${source.sourceId}`);
|
|
339931
|
+
}
|
|
339932
|
+
function resultForSnapshot(source, snapshot, status, retry, receipt, previousReceipt) {
|
|
339933
|
+
return {
|
|
339934
|
+
source_id: source.sourceId,
|
|
339935
|
+
agent_id: source.agentId,
|
|
339936
|
+
adapter: source.adapter.type,
|
|
339937
|
+
bestandsstatus: source.bestandsstatus,
|
|
339938
|
+
aktualitaetsstatus: source.aktualitaetsstatus,
|
|
339939
|
+
status,
|
|
339940
|
+
retry: {
|
|
339941
|
+
delivered: retry.delivered.length,
|
|
339942
|
+
failed: retry.failed.length
|
|
339943
|
+
},
|
|
339944
|
+
entry_count: entryCountResult(source),
|
|
339945
|
+
snapshot: {
|
|
339946
|
+
file_count: snapshot.fileCount,
|
|
339947
|
+
total_bytes: snapshot.totalBytes,
|
|
339948
|
+
raw_bytes: snapshot.rawBytes,
|
|
339949
|
+
raw_sha256: snapshot.rawSha256,
|
|
339950
|
+
latest_mtime: snapshot.latestMtime
|
|
339951
|
+
},
|
|
339952
|
+
receipt,
|
|
339953
|
+
...previousReceipt === void 0 ? {} : { previous_receipt_received_at: previousReceipt.received_at }
|
|
339954
|
+
};
|
|
339955
|
+
}
|
|
339956
|
+
function configuredPath(value, configDir, label) {
|
|
339957
|
+
if (isAbsolute(value)) return resolve(value);
|
|
339958
|
+
if (value.replaceAll("\\", "/").split("/").some((segment) => segment === "..")) throw new Error(`${label} must not traverse above the config directory; use an absolute path instead`);
|
|
339959
|
+
return resolve(configDir, value);
|
|
339960
|
+
}
|
|
339961
|
+
async function assertOutboxOutsideSource(adapter, outboxDir) {
|
|
339962
|
+
if (adapter.type !== "directory") return;
|
|
339963
|
+
const sourceStat = await lstat(adapter.path);
|
|
339964
|
+
if (sourceStat.isSymbolicLink() || !sourceStat.isDirectory()) throw new Error(`directory source must be a regular, non-symlink directory: ${adapter.path}`);
|
|
339965
|
+
const position = relative(await realpath(adapter.path), await canonicalProspectivePath(outboxDir));
|
|
339966
|
+
if (position === "" || !isAbsolute(position) && position !== ".." && !position.startsWith(`..${sep}`)) throw new Error(`outbox must not be the directory source or be contained by it: ${adapter.path}`);
|
|
339967
|
+
}
|
|
339968
|
+
async function canonicalProspectivePath(path) {
|
|
339969
|
+
let cursor = resolve(path);
|
|
339970
|
+
const tail = [];
|
|
339971
|
+
while (true) try {
|
|
339972
|
+
await lstat(cursor);
|
|
339973
|
+
return resolve(await realpath(cursor), ...tail.toReversed());
|
|
339974
|
+
} catch (error) {
|
|
339975
|
+
if (!isNotFound$1(error)) throw error;
|
|
339976
|
+
const parent = dirname(cursor);
|
|
339977
|
+
if (parent === cursor) throw error;
|
|
339978
|
+
tail.push(basename(cursor));
|
|
339979
|
+
cursor = parent;
|
|
339980
|
+
}
|
|
339981
|
+
}
|
|
339982
|
+
function objectValue(value, label) {
|
|
339983
|
+
if (!isObject$3(value) || Array.isArray(value)) throw new Error(`${label} must be an object`);
|
|
339984
|
+
return value;
|
|
339985
|
+
}
|
|
339986
|
+
function exactKeys(value, keys, label) {
|
|
339987
|
+
const allowed = new Set(keys);
|
|
339988
|
+
const unknown = Object.keys(value).filter((key) => !allowed.has(key));
|
|
339989
|
+
if (unknown.length > 0) throw new Error(`${label} contains unknown fields: ${unknown.join(", ")}`);
|
|
339990
|
+
}
|
|
339991
|
+
function nonEmptyString(value, label) {
|
|
339992
|
+
if (typeof value !== "string" || value.trim() === "") throw new Error(`${label} must be a non-empty string`);
|
|
339993
|
+
return value.trim();
|
|
339994
|
+
}
|
|
339995
|
+
function optionalNonEmptyString$1(value, label) {
|
|
339996
|
+
return value === void 0 ? void 0 : nonEmptyString(value, label);
|
|
339997
|
+
}
|
|
339998
|
+
function optionalCount(value, label) {
|
|
339999
|
+
if (value === void 0) return void 0;
|
|
340000
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${label} must be a non-negative integer`);
|
|
340001
|
+
return value;
|
|
340002
|
+
}
|
|
340003
|
+
function heartbeatInterval(value, label) {
|
|
340004
|
+
if (value === void 0) return void 0;
|
|
340005
|
+
if (!Number.isSafeInteger(value) || value < 60 || value >= TRANSPORT_STALE_AFTER_SECONDS) throw new Error(`${label} must be an integer from 60 through 86399 seconds`);
|
|
340006
|
+
return value;
|
|
340007
|
+
}
|
|
340008
|
+
function optionalEnumValue(value, allowed, label) {
|
|
340009
|
+
return value === void 0 ? void 0 : enumValue(value, allowed, label);
|
|
340010
|
+
}
|
|
340011
|
+
function enumValue(value, allowed, label) {
|
|
340012
|
+
if (typeof value !== "string" || !allowed.includes(value)) throw new Error(`${label} must be one of: ${allowed.join(", ")}`);
|
|
340013
|
+
return value;
|
|
340014
|
+
}
|
|
340015
|
+
function enumArray(value, allowed, label) {
|
|
340016
|
+
if (!Array.isArray(value) || value.length === 0 || value.some((item) => typeof item !== "string" || !allowed.includes(item))) throw new Error(`${label} must contain one or more of: ${allowed.join(", ")}`);
|
|
340017
|
+
const unique = [...new Set(value)];
|
|
340018
|
+
if (unique.length !== value.length) throw new Error(`${label} must not contain duplicates`);
|
|
340019
|
+
return unique;
|
|
340020
|
+
}
|
|
340021
|
+
function arraysEqual(value, expected) {
|
|
340022
|
+
return Array.isArray(value) && value.length === expected.length && value.every((item, index) => item === expected[index]);
|
|
340023
|
+
}
|
|
340024
|
+
function booleanValue(value, label) {
|
|
340025
|
+
if (typeof value !== "boolean") throw new Error(`${label} must be a boolean`);
|
|
340026
|
+
return value;
|
|
340027
|
+
}
|
|
340028
|
+
function validateIncludePatterns(value, label) {
|
|
340029
|
+
if (!Array.isArray(value) || value.length === 0) throw new Error(`${label} must be a non-empty array`);
|
|
340030
|
+
const patterns = value.map((candidate, index) => {
|
|
340031
|
+
if (typeof candidate !== "string" || candidate === "" || candidate.startsWith("/") || candidate.includes("\\") || candidate.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) throw new Error(`${label}[${index}] must be a safe relative glob using forward slashes`);
|
|
340032
|
+
if ([...candidate].length > 300 || candidate.includes("\0")) throw new Error(`${label}[${index}] is too long or unsafe`);
|
|
340033
|
+
return candidate;
|
|
340034
|
+
});
|
|
340035
|
+
if (new Set(patterns).size !== patterns.length) throw new Error(`${label} must not contain duplicates`);
|
|
340036
|
+
return patterns;
|
|
340037
|
+
}
|
|
340038
|
+
function compileIncludePatterns(patterns) {
|
|
340039
|
+
const expressions = patterns.map((pattern) => new RegExp(`^${globExpression(pattern)}$`, "u"));
|
|
340040
|
+
return (path) => expressions.some((expression) => expression.test(path));
|
|
340041
|
+
}
|
|
340042
|
+
function globExpression(pattern) {
|
|
340043
|
+
let expression = "";
|
|
340044
|
+
for (let index = 0; index < pattern.length; index += 1) {
|
|
340045
|
+
const character = pattern[index];
|
|
340046
|
+
if (character === "*" && pattern[index + 1] === "*") if (pattern[index + 2] === "/") {
|
|
340047
|
+
expression += "(?:.*/)?";
|
|
340048
|
+
index += 2;
|
|
340049
|
+
} else {
|
|
340050
|
+
expression += ".*";
|
|
340051
|
+
index += 1;
|
|
340052
|
+
}
|
|
340053
|
+
else if (character === "*") expression += "[^/]*";
|
|
340054
|
+
else if (character === "?") expression += "[^/]";
|
|
340055
|
+
else expression += escapeRegex$1(character);
|
|
340056
|
+
}
|
|
340057
|
+
return expression;
|
|
340058
|
+
}
|
|
340059
|
+
function escapeRegex$1(value) {
|
|
340060
|
+
return /[\\^$.*+?()[\]{}|]/.test(value) ? `\\${value}` : value;
|
|
340061
|
+
}
|
|
340062
|
+
function compareUtf8(left, right) {
|
|
340063
|
+
return Buffer.compare(Buffer.from(left), Buffer.from(right));
|
|
340064
|
+
}
|
|
340065
|
+
function assertEntryCountBasis(source, snapshot) {
|
|
340066
|
+
if (source.entryCountBasis === "files" && source.declaredEntryCount !== snapshot.fileCount) throw new Error(`declared entry count ${source.declaredEntryCount} does not match snapshot file count ${snapshot.fileCount}`);
|
|
340067
|
+
}
|
|
340068
|
+
function entryCountResult(source, checked = true) {
|
|
340069
|
+
return {
|
|
340070
|
+
declared: source.declaredEntryCount ?? null,
|
|
340071
|
+
basis: source.entryCountBasis ?? null,
|
|
340072
|
+
verification: source.entryCountBasis === "files" ? checked ? "matched_file_count" : "not_checked" : source.entryCountBasis === "declared" ? "not_derivable_from_raw_files" : "not_declared"
|
|
340073
|
+
};
|
|
340074
|
+
}
|
|
340075
|
+
function declarationsEqual(value, expected) {
|
|
340076
|
+
return expected === void 0 ? value === void 0 : JSON.stringify(value) === JSON.stringify(expected);
|
|
340077
|
+
}
|
|
340078
|
+
async function readJson(path) {
|
|
340079
|
+
try {
|
|
340080
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
340081
|
+
} catch (error) {
|
|
340082
|
+
if (isNotFound$1(error) || error instanceof SyntaxError) return null;
|
|
340083
|
+
throw error;
|
|
340084
|
+
}
|
|
340085
|
+
}
|
|
340086
|
+
function assertSnapshotSize(payload) {
|
|
340087
|
+
if (payload.byteLength > 20971520) throw new Error(`source snapshot exceeds ${MAX_MISTAKE_SOURCE_BYTES} bytes`);
|
|
340088
|
+
}
|
|
340089
|
+
function sha256$3(value) {
|
|
340090
|
+
return createHash("sha256").update(value).digest("hex");
|
|
340091
|
+
}
|
|
340092
|
+
function isObject$3(value) {
|
|
340093
|
+
return typeof value === "object" && value !== null;
|
|
340094
|
+
}
|
|
340095
|
+
function isAlreadyExists(error) {
|
|
340096
|
+
return isObject$3(error) && error["code"] === "EEXIST";
|
|
340097
|
+
}
|
|
340098
|
+
function isNotFound$1(error) {
|
|
340099
|
+
return isObject$3(error) && error["code"] === "ENOENT";
|
|
340100
|
+
}
|
|
340101
|
+
function isSymlinkOpenError(error) {
|
|
340102
|
+
return isObject$3(error) && ["ELOOP", "EMLINK"].includes(String(error["code"]));
|
|
340103
|
+
}
|
|
340104
|
+
function errorMessage$5(error) {
|
|
340105
|
+
return error instanceof Error ? error.message : String(error);
|
|
340106
|
+
}
|
|
340107
|
+
function waitForInterval(milliseconds, signal) {
|
|
340108
|
+
if (signal?.aborted) return Promise.resolve();
|
|
340109
|
+
let timeout;
|
|
340110
|
+
const delay = new Promise((resolveDelay) => {
|
|
340111
|
+
timeout = setTimeout(resolveDelay, milliseconds);
|
|
340112
|
+
});
|
|
340113
|
+
if (signal === void 0) return delay;
|
|
340114
|
+
let stop;
|
|
340115
|
+
const aborted = new Promise((resolveAbort) => {
|
|
340116
|
+
stop = resolveAbort;
|
|
340117
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
340118
|
+
});
|
|
340119
|
+
return Promise.race([delay, aborted]).finally(() => {
|
|
340120
|
+
if (timeout !== void 0) clearTimeout(timeout);
|
|
340121
|
+
if (stop !== void 0) signal.removeEventListener("abort", stop);
|
|
340122
|
+
});
|
|
340123
|
+
}
|
|
340124
|
+
//#endregion
|
|
340125
|
+
//#region src/cli/sub/mistakes.ts
|
|
340126
|
+
const DEFAULT_TOKEN_ENV = "BLUN_MISTAKE_INFLOW_TOKEN";
|
|
340127
|
+
const DEFAULT_ENDPOINT_ENV = "BLUN_MISTAKE_INFLOW_URL";
|
|
340128
|
+
function registerMistakesCommand(parent, overrides = {}) {
|
|
340129
|
+
const deps = resolveDeps(overrides);
|
|
340130
|
+
const mistakes = parent.command("mistakes").description("Upload and inspect append-only mistake source snapshots.");
|
|
340131
|
+
mistakes.command("upload").description("Queue a source snapshot locally, then upload it.").argument("<path>", "Source file to upload.").requiredOption("--source <id>", "Registered source id.").addOption(choiceOption("--form <form>", "Source form.", MISTAKE_SOURCE_FORMS, "unknown")).option("--record-types <types>", "Comma-separated declared record types.", "unknown").option("--entries <count>", "Declared logical entry count.", parseNonNegativeInteger).addOption(choiceOption("--bestandsstatus <status>", "Inventory status.", MISTAKE_INVENTORY_STATUSES, "unverified")).addOption(choiceOption("--aktualitaetsstatus <status>", "Actuality status.", MISTAKE_ACTUALITY_STATUSES, "unverified")).option("--last-entry-at <timestamp>", "Timestamp of the newest raw entry.").option("--endpoint <url>", `Inflow URL (or ${DEFAULT_ENDPOINT_ENV}).`).option("--token-env <name>", "Environment variable containing the bearer token.", DEFAULT_TOKEN_ENV).option("--outbox <path>", "Local durable outbox directory.").action(async (path, options) => {
|
|
340132
|
+
await run$1(deps, async () => {
|
|
340133
|
+
const connection = connectionOptions(deps, options);
|
|
340134
|
+
const receipt = await uploadMistakeObservation({
|
|
340135
|
+
filePath: resolve(path),
|
|
340136
|
+
sourceId: options.source,
|
|
340137
|
+
sourceForm: options.form,
|
|
340138
|
+
recordTypes: parseRecordTypes(options.recordTypes),
|
|
340139
|
+
bestandsstatus: options.bestandsstatus,
|
|
340140
|
+
aktualitaetsstatus: options.aktualitaetsstatus,
|
|
340141
|
+
declaredEntryCount: options.entries,
|
|
340142
|
+
lastRawObservedAt: options.lastEntryAt,
|
|
340143
|
+
capturedAt: deps.now().toISOString()
|
|
340144
|
+
}, connection);
|
|
340145
|
+
deps.stdout.write(`${JSON.stringify(receipt)}\n`);
|
|
340146
|
+
});
|
|
340147
|
+
});
|
|
340148
|
+
mistakes.command("retry").description("Retry every queued snapshot that has no verified receipt.").option("--endpoint <url>", `Inflow URL (or ${DEFAULT_ENDPOINT_ENV}).`).option("--token-env <name>", "Environment variable containing the bearer token.", DEFAULT_TOKEN_ENV).option("--outbox <path>", "Local durable outbox directory.").action(async (options) => {
|
|
340149
|
+
await run$1(deps, async () => {
|
|
340150
|
+
const result = await drainMistakeOutbox(connectionOptions(deps, options));
|
|
340151
|
+
deps.stdout.write(`${JSON.stringify(result)}\n`);
|
|
340152
|
+
if (result.failed.length > 0) deps.exit(1);
|
|
340153
|
+
});
|
|
340154
|
+
});
|
|
340155
|
+
mistakes.command("sync").description("Retry and upload every configured file or directory source once.").requiredOption("--config <path>", "Source registry JSON file.").option("--endpoint <url>", "Override the configured inflow URL for every supported source.").option("--outbox <path>", "Override the configured local outbox root.").action(async (options) => {
|
|
340156
|
+
await run$1(deps, async () => {
|
|
340157
|
+
const result = await syncMistakeSources({
|
|
340158
|
+
configPath: resolve(options.config),
|
|
340159
|
+
env: deps.env,
|
|
340160
|
+
endpoint: options.endpoint,
|
|
340161
|
+
outboxDir: options.outbox === void 0 ? void 0 : resolve(options.outbox)
|
|
340162
|
+
});
|
|
340163
|
+
deps.stdout.write(`${JSON.stringify(result)}\n`);
|
|
340164
|
+
if (result.results.some((item) => item.status === "failed" || item.status === "blocked")) deps.exit(2);
|
|
340165
|
+
});
|
|
340166
|
+
});
|
|
340167
|
+
mistakes.command("watch").description("Run source sync repeatedly in the foreground until interrupted.").requiredOption("--config <path>", "Source registry JSON file.").option("--endpoint <url>", "Override the configured inflow URL for every supported source.").option("--outbox <path>", "Override the configured local outbox root.").option("--interval <seconds>", "Foreground sync interval in seconds.", parseWatchInterval, 300).action(async (options) => {
|
|
340168
|
+
await run$1(deps, async () => {
|
|
340169
|
+
const controller = new AbortController();
|
|
340170
|
+
const stop = () => controller.abort();
|
|
340171
|
+
process.once("SIGINT", stop);
|
|
340172
|
+
process.once("SIGTERM", stop);
|
|
340173
|
+
try {
|
|
340174
|
+
await watchMistakeSources({
|
|
340175
|
+
configPath: resolve(options.config),
|
|
340176
|
+
env: deps.env,
|
|
340177
|
+
endpoint: options.endpoint,
|
|
340178
|
+
outboxDir: options.outbox === void 0 ? void 0 : resolve(options.outbox),
|
|
340179
|
+
intervalMs: options.interval * 1e3,
|
|
340180
|
+
signal: controller.signal,
|
|
340181
|
+
onRun: (result) => {
|
|
340182
|
+
deps.stdout.write(`${JSON.stringify(result)}\n`);
|
|
340183
|
+
}
|
|
340184
|
+
});
|
|
340185
|
+
} finally {
|
|
340186
|
+
process.off("SIGINT", stop);
|
|
340187
|
+
process.off("SIGTERM", stop);
|
|
340188
|
+
}
|
|
340189
|
+
});
|
|
340190
|
+
});
|
|
340191
|
+
mistakes.command("status").description("Show per-source inventory, actuality, and 24-hour watchdog state.").option("--endpoint <url>", `Inflow URL (or ${DEFAULT_ENDPOINT_ENV}).`).option("--token-env <name>", "Environment variable containing the bearer token.", DEFAULT_TOKEN_ENV).option("--no-fail-on-red", "Return success even when one or more sources are red.").action(async (options) => {
|
|
340192
|
+
await run$1(deps, async () => {
|
|
340193
|
+
const connection = connectionOptions(deps, options);
|
|
340194
|
+
const status = await getMistakeInflowStatus(connection.endpoint, connection.token);
|
|
340195
|
+
deps.stdout.write(`${JSON.stringify(status)}\n`);
|
|
340196
|
+
if (options.failOnRed && hasRedSource(status)) deps.exit(2);
|
|
340197
|
+
});
|
|
340198
|
+
});
|
|
340199
|
+
for (const action of ["remove", "restore"]) mistakes.command(action).description(action === "remove" ? "Append a manual removal marker without deleting raw data." : "Append a restore marker for a previously removed observation.").argument("<eventId>", "Observation event id.").requiredOption("--reason <text>", "Auditable reason for the state change.").option("--endpoint <url>", `Inflow URL (or ${DEFAULT_ENDPOINT_ENV}).`).option("--token-env <name>", "Environment variable containing the bearer token.", DEFAULT_TOKEN_ENV).action(async (eventId, options) => {
|
|
340200
|
+
await run$1(deps, async () => {
|
|
340201
|
+
const connection = connectionOptions(deps, options);
|
|
340202
|
+
const result = await changeMistakeObservationState(action, eventId, options.reason, connection.endpoint, connection.token);
|
|
340203
|
+
deps.stdout.write(`${JSON.stringify(result)}\n`);
|
|
340204
|
+
});
|
|
340205
|
+
});
|
|
340206
|
+
}
|
|
340207
|
+
async function run$1(deps, operation) {
|
|
340208
|
+
try {
|
|
340209
|
+
await operation();
|
|
340210
|
+
} catch (error) {
|
|
340211
|
+
deps.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
340212
|
+
deps.exit(1);
|
|
340213
|
+
}
|
|
340214
|
+
}
|
|
340215
|
+
function connectionOptions(deps, options) {
|
|
340216
|
+
const endpoint = options.endpoint ?? deps.env[DEFAULT_ENDPOINT_ENV];
|
|
340217
|
+
if (!endpoint) throw new Error(`missing --endpoint or ${DEFAULT_ENDPOINT_ENV}`);
|
|
340218
|
+
const token = deps.env[options.tokenEnv];
|
|
340219
|
+
if (!token || token.trim() === "") throw new Error(`missing bearer token in ${options.tokenEnv}`);
|
|
340220
|
+
return {
|
|
340221
|
+
endpoint,
|
|
340222
|
+
token,
|
|
340223
|
+
outboxDir: resolve(options.outbox ?? join(resolveBlunHome$1(), "mistake", "inflow-outbox"))
|
|
340224
|
+
};
|
|
340225
|
+
}
|
|
340226
|
+
function parseRecordTypes(value) {
|
|
340227
|
+
const values = [...new Set(value.split(",").map((item) => item.trim()).filter(Boolean))];
|
|
340228
|
+
if (values.length === 0 || values.some((value) => !MISTAKE_RECORD_TYPES.includes(value))) throw new Error(`record types must be one or more of: ${MISTAKE_RECORD_TYPES.join(", ")}`);
|
|
340229
|
+
return values;
|
|
340230
|
+
}
|
|
340231
|
+
function parseNonNegativeInteger(value) {
|
|
340232
|
+
if (!/^\d+$/.test(value)) throw new Error("entry count must be a non-negative integer");
|
|
340233
|
+
const parsed = Number(value);
|
|
340234
|
+
if (!Number.isSafeInteger(parsed)) throw new Error("entry count is too large");
|
|
340235
|
+
return parsed;
|
|
340236
|
+
}
|
|
340237
|
+
function parseWatchInterval(value) {
|
|
340238
|
+
if (!/^\d+$/.test(value)) throw new Error("watch interval must be a positive integer");
|
|
340239
|
+
const parsed = Number(value);
|
|
340240
|
+
if (!Number.isSafeInteger(parsed) || parsed < 1) throw new Error("watch interval must be at least one second");
|
|
340241
|
+
return parsed;
|
|
340242
|
+
}
|
|
340243
|
+
function hasRedSource(value) {
|
|
340244
|
+
if (typeof value !== "object" || value === null) return false;
|
|
340245
|
+
const sources = value["sources"];
|
|
340246
|
+
return Array.isArray(sources) && sources.some((source) => typeof source === "object" && source !== null && source["watchdog"] === "red");
|
|
340247
|
+
}
|
|
340248
|
+
function choiceOption(flags, description, choices, defaultValue) {
|
|
340249
|
+
return new Option(flags, description).choices([...choices]).default(defaultValue);
|
|
340250
|
+
}
|
|
340251
|
+
function resolveDeps(overrides) {
|
|
340252
|
+
return {
|
|
340253
|
+
env: overrides.env ?? process.env,
|
|
340254
|
+
now: overrides.now ?? (() => /* @__PURE__ */ new Date()),
|
|
340255
|
+
stdout: overrides.stdout ?? process.stdout,
|
|
340256
|
+
stderr: overrides.stderr ?? process.stderr,
|
|
340257
|
+
exit: overrides.exit ?? ((code) => process.exit(code))
|
|
340258
|
+
};
|
|
340259
|
+
}
|
|
340260
|
+
//#endregion
|
|
338514
340261
|
//#region src/personal-memory/phase1-contract.json
|
|
338515
340262
|
var clientOperations = {
|
|
338516
340263
|
"settingsRead": {
|
|
@@ -338829,9 +340576,9 @@ function isErrno$1(error, code) {
|
|
|
338829
340576
|
return error.code === code;
|
|
338830
340577
|
}
|
|
338831
340578
|
function outputFailure(error, cleanupError) {
|
|
338832
|
-
return new Error(`${errorMessage$
|
|
340579
|
+
return new Error(`${errorMessage$4(error)} Output reservation cleanup failed: ${errorMessage$4(cleanupError)}`, { cause: new AggregateError([error, cleanupError], "Output reservation cleanup failed.") });
|
|
338833
340580
|
}
|
|
338834
|
-
function errorMessage$
|
|
340581
|
+
function errorMessage$4(error) {
|
|
338835
340582
|
return error instanceof Error ? error.message : String(error);
|
|
338836
340583
|
}
|
|
338837
340584
|
//#endregion
|
|
@@ -339445,7 +341192,7 @@ async function handleProof(deps, options) {
|
|
|
339445
341192
|
await reservation.write(proof);
|
|
339446
341193
|
} catch (error) {
|
|
339447
341194
|
await reservation?.abort().catch(() => void 0);
|
|
339448
|
-
deps.stderr.write(`${errorMessage$
|
|
341195
|
+
deps.stderr.write(`${errorMessage$3(error)}\n`);
|
|
339449
341196
|
deps.exit(1);
|
|
339450
341197
|
}
|
|
339451
341198
|
deps.stdout.write(`${outputPath}\n`);
|
|
@@ -339477,7 +341224,7 @@ function createDefaultProofDeps(overrides = {}) {
|
|
|
339477
341224
|
function defaultProofFilename(now) {
|
|
339478
341225
|
return `proof-${now.toISOString().replaceAll(/[:.]/g, "-")}.json`;
|
|
339479
341226
|
}
|
|
339480
|
-
function errorMessage$
|
|
341227
|
+
function errorMessage$3(error) {
|
|
339481
341228
|
return error instanceof Error ? error.message : String(error);
|
|
339482
341229
|
}
|
|
339483
341230
|
function samePath$2(left, right) {
|
|
@@ -343691,10 +345438,10 @@ var require_atomic_sleep = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
343691
345438
|
//#endregion
|
|
343692
345439
|
//#region ../../node_modules/.pnpm/sonic-boom@4.2.1/node_modules/sonic-boom/index.js
|
|
343693
345440
|
var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
343694
|
-
const fs$
|
|
345441
|
+
const fs$3 = __require("fs");
|
|
343695
345442
|
const EventEmitter$10 = __require("events");
|
|
343696
345443
|
const inherits$6 = __require("util").inherits;
|
|
343697
|
-
const path$
|
|
345444
|
+
const path$5 = __require("path");
|
|
343698
345445
|
const sleep = require_atomic_sleep();
|
|
343699
345446
|
const assert$8 = __require("assert");
|
|
343700
345447
|
const BUSY_WRITE_TIMEOUT = 100;
|
|
@@ -343734,17 +345481,17 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
343734
345481
|
const flags = sonic.append ? "a" : "w";
|
|
343735
345482
|
const mode = sonic.mode;
|
|
343736
345483
|
if (sonic.sync) try {
|
|
343737
|
-
if (sonic.mkdir) fs$
|
|
343738
|
-
fileOpened(null, fs$
|
|
345484
|
+
if (sonic.mkdir) fs$3.mkdirSync(path$5.dirname(file), { recursive: true });
|
|
345485
|
+
fileOpened(null, fs$3.openSync(file, flags, mode));
|
|
343739
345486
|
} catch (err) {
|
|
343740
345487
|
fileOpened(err);
|
|
343741
345488
|
throw err;
|
|
343742
345489
|
}
|
|
343743
|
-
else if (sonic.mkdir) fs$
|
|
345490
|
+
else if (sonic.mkdir) fs$3.mkdir(path$5.dirname(file), { recursive: true }, (err) => {
|
|
343744
345491
|
if (err) return fileOpened(err);
|
|
343745
|
-
fs$
|
|
345492
|
+
fs$3.open(file, flags, mode, fileOpened);
|
|
343746
345493
|
});
|
|
343747
|
-
else fs$
|
|
345494
|
+
else fs$3.open(file, flags, mode, fileOpened);
|
|
343748
345495
|
}
|
|
343749
345496
|
function SonicBoom(opts) {
|
|
343750
345497
|
if (!(this instanceof SonicBoom)) return new SonicBoom(opts);
|
|
@@ -343782,8 +345529,8 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
343782
345529
|
this.flush = flushBuffer;
|
|
343783
345530
|
this.flushSync = flushBufferSync;
|
|
343784
345531
|
this._actualWrite = actualWriteBuffer;
|
|
343785
|
-
fsWriteSync = () => fs$
|
|
343786
|
-
fsWrite = () => fs$
|
|
345532
|
+
fsWriteSync = () => fs$3.writeSync(this.fd, this._writingBuf);
|
|
345533
|
+
fsWrite = () => fs$3.write(this.fd, this._writingBuf, this.release);
|
|
343787
345534
|
} else if (contentMode === void 0 || contentMode === kContentModeUtf8) {
|
|
343788
345535
|
this._writingBuf = "";
|
|
343789
345536
|
this.write = write;
|
|
@@ -343791,12 +345538,12 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
343791
345538
|
this.flushSync = flushSync;
|
|
343792
345539
|
this._actualWrite = actualWrite;
|
|
343793
345540
|
fsWriteSync = () => {
|
|
343794
|
-
if (Buffer.isBuffer(this._writingBuf)) return fs$
|
|
343795
|
-
return fs$
|
|
345541
|
+
if (Buffer.isBuffer(this._writingBuf)) return fs$3.writeSync(this.fd, this._writingBuf);
|
|
345542
|
+
return fs$3.writeSync(this.fd, this._writingBuf, "utf8");
|
|
343796
345543
|
};
|
|
343797
345544
|
fsWrite = () => {
|
|
343798
|
-
if (Buffer.isBuffer(this._writingBuf)) return fs$
|
|
343799
|
-
return fs$
|
|
345545
|
+
if (Buffer.isBuffer(this._writingBuf)) return fs$3.write(this.fd, this._writingBuf, this.release);
|
|
345546
|
+
return fs$3.write(this.fd, this._writingBuf, "utf8", this.release);
|
|
343800
345547
|
};
|
|
343801
345548
|
} else throw new Error(`SonicBoom supports "${kContentModeUtf8}" and "${kContentModeBuffer}", but passed ${contentMode}`);
|
|
343802
345549
|
if (typeof fd === "number") {
|
|
@@ -343841,7 +345588,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
343841
345588
|
return;
|
|
343842
345589
|
}
|
|
343843
345590
|
}
|
|
343844
|
-
if (this._fsync) fs$
|
|
345591
|
+
if (this._fsync) fs$3.fsyncSync(this.fd);
|
|
343845
345592
|
const len = this._len;
|
|
343846
345593
|
if (this._reopening) {
|
|
343847
345594
|
this._writing = false;
|
|
@@ -343938,7 +345685,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
343938
345685
|
this._flushPending = true;
|
|
343939
345686
|
const onDrain = () => {
|
|
343940
345687
|
if (!this._fsync) try {
|
|
343941
|
-
fs$
|
|
345688
|
+
fs$3.fsync(this.fd, (err) => {
|
|
343942
345689
|
this._flushPending = false;
|
|
343943
345690
|
cb(err);
|
|
343944
345691
|
});
|
|
@@ -344015,7 +345762,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
344015
345762
|
if (this._writing) return;
|
|
344016
345763
|
const fd = this.fd;
|
|
344017
345764
|
this.once("ready", () => {
|
|
344018
|
-
if (fd !== this.fd) fs$
|
|
345765
|
+
if (fd !== this.fd) fs$3.close(fd, (err) => {
|
|
344019
345766
|
if (err) return this.emit("error", err);
|
|
344020
345767
|
});
|
|
344021
345768
|
});
|
|
@@ -344046,7 +345793,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
344046
345793
|
while (this._bufs.length || buf.length) {
|
|
344047
345794
|
if (buf.length <= 0) buf = this._bufs[0];
|
|
344048
345795
|
try {
|
|
344049
|
-
const n = Buffer.isBuffer(buf) ? fs$
|
|
345796
|
+
const n = Buffer.isBuffer(buf) ? fs$3.writeSync(this.fd, buf) : fs$3.writeSync(this.fd, buf, "utf8");
|
|
344050
345797
|
const releasedBufObj = releaseWritingBuf(buf, this._len, n);
|
|
344051
345798
|
buf = releasedBufObj.writingBuf;
|
|
344052
345799
|
this._len = releasedBufObj.len;
|
|
@@ -344057,7 +345804,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
344057
345804
|
}
|
|
344058
345805
|
}
|
|
344059
345806
|
try {
|
|
344060
|
-
fs$
|
|
345807
|
+
fs$3.fsyncSync(this.fd);
|
|
344061
345808
|
} catch {}
|
|
344062
345809
|
}
|
|
344063
345810
|
function flushBufferSync() {
|
|
@@ -344071,7 +345818,7 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
344071
345818
|
while (this._bufs.length || buf.length) {
|
|
344072
345819
|
if (buf.length <= 0) buf = mergeBuf(this._bufs[0], this._lens[0]);
|
|
344073
345820
|
try {
|
|
344074
|
-
const n = fs$
|
|
345821
|
+
const n = fs$3.writeSync(this.fd, buf);
|
|
344075
345822
|
buf = buf.subarray(n);
|
|
344076
345823
|
this._len = Math.max(this._len - n, 0);
|
|
344077
345824
|
if (buf.length <= 0) {
|
|
@@ -344093,24 +345840,24 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
344093
345840
|
this._writing = true;
|
|
344094
345841
|
this._writingBuf = this._writingBuf.length ? this._writingBuf : this._bufs.shift() || "";
|
|
344095
345842
|
if (this.sync) try {
|
|
344096
|
-
release(null, Buffer.isBuffer(this._writingBuf) ? fs$
|
|
345843
|
+
release(null, Buffer.isBuffer(this._writingBuf) ? fs$3.writeSync(this.fd, this._writingBuf) : fs$3.writeSync(this.fd, this._writingBuf, "utf8"));
|
|
344097
345844
|
} catch (err) {
|
|
344098
345845
|
release(err);
|
|
344099
345846
|
}
|
|
344100
|
-
else fs$
|
|
345847
|
+
else fs$3.write(this.fd, this._writingBuf, release);
|
|
344101
345848
|
}
|
|
344102
345849
|
function actualWriteBuffer() {
|
|
344103
345850
|
const release = this.release;
|
|
344104
345851
|
this._writing = true;
|
|
344105
345852
|
this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift());
|
|
344106
345853
|
if (this.sync) try {
|
|
344107
|
-
release(null, fs$
|
|
345854
|
+
release(null, fs$3.writeSync(this.fd, this._writingBuf));
|
|
344108
345855
|
} catch (err) {
|
|
344109
345856
|
release(err);
|
|
344110
345857
|
}
|
|
344111
345858
|
else {
|
|
344112
345859
|
if (kCopyBuffer) this._writingBuf = Buffer.from(this._writingBuf);
|
|
344113
|
-
fs$
|
|
345860
|
+
fs$3.write(this.fd, this._writingBuf, release);
|
|
344114
345861
|
}
|
|
344115
345862
|
}
|
|
344116
345863
|
function actualClose(sonic) {
|
|
@@ -344124,10 +345871,10 @@ var require_sonic_boom = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
344124
345871
|
sonic._lens = [];
|
|
344125
345872
|
assert$8(typeof sonic.fd === "number", `sonic.fd must be a number, got ${typeof sonic.fd}`);
|
|
344126
345873
|
try {
|
|
344127
|
-
fs$
|
|
345874
|
+
fs$3.fsync(sonic.fd, closeWrapped);
|
|
344128
345875
|
} catch {}
|
|
344129
345876
|
function closeWrapped() {
|
|
344130
|
-
if (sonic.fd !== 1 && sonic.fd !== 2) fs$
|
|
345877
|
+
if (sonic.fd !== 1 && sonic.fd !== 2) fs$3.close(sonic.fd, done);
|
|
344131
345878
|
else done();
|
|
344132
345879
|
}
|
|
344133
345880
|
function done(err) {
|
|
@@ -366750,8 +368497,8 @@ var require_constants$2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
366750
368497
|
//#endregion
|
|
366751
368498
|
//#region ../../../../node_modules/node-gyp-build/node-gyp-build.js
|
|
366752
368499
|
var require_node_gyp_build$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
366753
|
-
var fs$
|
|
366754
|
-
var path$
|
|
368500
|
+
var fs$2 = __require("fs");
|
|
368501
|
+
var path$4 = __require("path");
|
|
366755
368502
|
var os$3 = __require("os");
|
|
366756
368503
|
var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
|
|
366757
368504
|
var vars = process.config && process.config.variables || {};
|
|
@@ -366768,20 +368515,20 @@ var require_node_gyp_build$1 = /* @__PURE__ */ __commonJSMin(((exports, module)
|
|
|
366768
368515
|
return runtimeRequire(load.resolve(dir));
|
|
366769
368516
|
}
|
|
366770
368517
|
load.resolve = load.path = function(dir) {
|
|
366771
|
-
dir = path$
|
|
368518
|
+
dir = path$4.resolve(dir || ".");
|
|
366772
368519
|
try {
|
|
366773
|
-
var name = runtimeRequire(path$
|
|
368520
|
+
var name = runtimeRequire(path$4.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
|
|
366774
368521
|
if (process.env[name + "_PREBUILD"]) dir = process.env[name + "_PREBUILD"];
|
|
366775
368522
|
} catch (err) {}
|
|
366776
368523
|
if (!prebuildsOnly) {
|
|
366777
|
-
var release = getFirst(path$
|
|
368524
|
+
var release = getFirst(path$4.join(dir, "build/Release"), matchBuild);
|
|
366778
368525
|
if (release) return release;
|
|
366779
|
-
var debug = getFirst(path$
|
|
368526
|
+
var debug = getFirst(path$4.join(dir, "build/Debug"), matchBuild);
|
|
366780
368527
|
if (debug) return debug;
|
|
366781
368528
|
}
|
|
366782
368529
|
var prebuild = resolve(dir);
|
|
366783
368530
|
if (prebuild) return prebuild;
|
|
366784
|
-
var nearby = resolve(path$
|
|
368531
|
+
var nearby = resolve(path$4.dirname(process.execPath));
|
|
366785
368532
|
if (nearby) return nearby;
|
|
366786
368533
|
var target = [
|
|
366787
368534
|
"platform=" + platform,
|
|
@@ -366797,23 +368544,23 @@ var require_node_gyp_build$1 = /* @__PURE__ */ __commonJSMin(((exports, module)
|
|
|
366797
368544
|
].filter(Boolean).join(" ");
|
|
366798
368545
|
throw new Error("No native build was found for " + target + "\n loaded from: " + dir + "\n");
|
|
366799
368546
|
function resolve(dir) {
|
|
366800
|
-
var tuple = readdirSync(path$
|
|
368547
|
+
var tuple = readdirSync(path$4.join(dir, "prebuilds")).map(parseTuple).filter(matchTuple(platform, arch)).sort(compareTuples)[0];
|
|
366801
368548
|
if (!tuple) return;
|
|
366802
|
-
var prebuilds = path$
|
|
368549
|
+
var prebuilds = path$4.join(dir, "prebuilds", tuple.name);
|
|
366803
368550
|
var winner = readdirSync(prebuilds).map(parseTags).filter(matchTags(runtime, abi)).sort(compareTags(runtime))[0];
|
|
366804
|
-
if (winner) return path$
|
|
368551
|
+
if (winner) return path$4.join(prebuilds, winner.file);
|
|
366805
368552
|
}
|
|
366806
368553
|
};
|
|
366807
368554
|
function readdirSync(dir) {
|
|
366808
368555
|
try {
|
|
366809
|
-
return fs$
|
|
368556
|
+
return fs$2.readdirSync(dir);
|
|
366810
368557
|
} catch (err) {
|
|
366811
368558
|
return [];
|
|
366812
368559
|
}
|
|
366813
368560
|
}
|
|
366814
368561
|
function getFirst(dir, filter) {
|
|
366815
368562
|
var files = readdirSync(dir).filter(filter);
|
|
366816
|
-
return files[0] && path$
|
|
368563
|
+
return files[0] && path$4.join(dir, files[0]);
|
|
366817
368564
|
}
|
|
366818
368565
|
function matchBuild(name) {
|
|
366819
368566
|
return /\.node$/.test(name);
|
|
@@ -366894,7 +368641,7 @@ var require_node_gyp_build$1 = /* @__PURE__ */ __commonJSMin(((exports, module)
|
|
|
366894
368641
|
return typeof window !== "undefined" && window.process && window.process.type === "renderer";
|
|
366895
368642
|
}
|
|
366896
368643
|
function isAlpine(platform) {
|
|
366897
|
-
return platform === "linux" && fs$
|
|
368644
|
+
return platform === "linux" && fs$2.existsSync("/etc/alpine-release");
|
|
366898
368645
|
}
|
|
366899
368646
|
load.parseTags = parseTags;
|
|
366900
368647
|
load.matchTags = matchTags;
|
|
@@ -374010,7 +375757,7 @@ var import_multipart = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((
|
|
|
374010
375757
|
const fp = require_plugin();
|
|
374011
375758
|
const { createWriteStream: createWriteStream$1 } = __require("node:fs");
|
|
374012
375759
|
const { unlink: unlink$1 } = __require("node:fs/promises");
|
|
374013
|
-
const path$
|
|
375760
|
+
const path$3 = __require("node:path");
|
|
374014
375761
|
const { generateId } = require_generateId();
|
|
374015
375762
|
const createError = require_error$1();
|
|
374016
375763
|
const streamToNull = require_stream_consumer();
|
|
@@ -374305,7 +376052,7 @@ var import_multipart = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((
|
|
|
374305
376052
|
for await (const part of parts) {
|
|
374306
376053
|
values = part.fields;
|
|
374307
376054
|
if (!part.file) continue;
|
|
374308
|
-
const filepath = path$
|
|
376055
|
+
const filepath = path$3.join(tmpdir, generateId() + path$3.extname(part.filename || "file" + i++));
|
|
374309
376056
|
const target = createWriteStream$1(filepath);
|
|
374310
376057
|
try {
|
|
374311
376058
|
this.tmpUploads.push(filepath);
|
|
@@ -387046,8 +388793,8 @@ var require_dist$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
387046
388793
|
//#endregion
|
|
387047
388794
|
//#region ../../node_modules/.pnpm/@fastify+swagger@9.7.0/node_modules/@fastify/swagger/lib/mode/static.js
|
|
387048
388795
|
var require_static = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
387049
|
-
const path$
|
|
387050
|
-
const fs$
|
|
388796
|
+
const path$2 = __require("node:path");
|
|
388797
|
+
const fs$1 = __require("node:fs");
|
|
387051
388798
|
const yaml = require_dist$1();
|
|
387052
388799
|
module.exports = function(fastify, opts, done) {
|
|
387053
388800
|
if (!opts.specification) return done(/* @__PURE__ */ new Error("specification is missing in the module options"));
|
|
@@ -387056,14 +388803,14 @@ var require_static = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
387056
388803
|
if (!opts.specification.path && !opts.specification.document) return done(/* @__PURE__ */ new Error("both specification.path and specification.document are missing, should be path to the file or swagger document spec"));
|
|
387057
388804
|
else if (opts.specification.path) {
|
|
387058
388805
|
if (typeof opts.specification.path !== "string") return done(/* @__PURE__ */ new Error("specification.path is not a string"));
|
|
387059
|
-
if (!fs$
|
|
387060
|
-
const extName = path$
|
|
388806
|
+
if (!fs$1.existsSync(path$2.resolve(opts.specification.path))) return done(/* @__PURE__ */ new Error(`${opts.specification.path} does not exist`));
|
|
388807
|
+
const extName = path$2.extname(opts.specification.path).toLowerCase();
|
|
387061
388808
|
if ([".yaml", ".json"].indexOf(extName) === -1) return done(/* @__PURE__ */ new Error("specification.path extension name is not supported, should be one from ['.yaml', '.json']"));
|
|
387062
388809
|
if (opts.specification.postProcessor && typeof opts.specification.postProcessor !== "function") return done(/* @__PURE__ */ new Error("specification.postProcessor should be a function"));
|
|
387063
388810
|
if (opts.specification.baseDir && typeof opts.specification.baseDir !== "string") return done(/* @__PURE__ */ new Error("specification.baseDir should be string"));
|
|
387064
|
-
if (!opts.specification.baseDir) opts.specification.baseDir = path$
|
|
388811
|
+
if (!opts.specification.baseDir) opts.specification.baseDir = path$2.resolve(path$2.dirname(opts.specification.path));
|
|
387065
388812
|
else while (opts.specification.baseDir.endsWith("/")) opts.specification.baseDir = opts.specification.baseDir.slice(0, -1);
|
|
387066
|
-
const source = fs$
|
|
388813
|
+
const source = fs$1.readFileSync(path$2.resolve(opts.specification.path), "utf8");
|
|
387067
388814
|
switch (extName) {
|
|
387068
388815
|
case ".yaml":
|
|
387069
388816
|
swaggerObject = yaml.parse(source);
|
|
@@ -387330,11 +389077,11 @@ var require_should_route_hide = /* @__PURE__ */ __commonJSMin(((exports, module)
|
|
|
387330
389077
|
//#endregion
|
|
387331
389078
|
//#region ../../node_modules/.pnpm/@fastify+swagger@9.7.0/node_modules/@fastify/swagger/lib/util/read-package-json.js
|
|
387332
389079
|
var require_read_package_json = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
387333
|
-
const fs
|
|
387334
|
-
const path$
|
|
389080
|
+
const fs = __require("node:fs");
|
|
389081
|
+
const path$1 = __require("node:path");
|
|
387335
389082
|
function readPackageJson() {
|
|
387336
389083
|
try {
|
|
387337
|
-
return JSON.parse(fs
|
|
389084
|
+
return JSON.parse(fs.readFileSync(path$1.join(__dirname, "..", "..", "package.json")));
|
|
387338
389085
|
} catch {
|
|
387339
389086
|
return {};
|
|
387340
389087
|
}
|
|
@@ -395793,7 +397540,7 @@ async function abortAndFail(deps, reservation, error) {
|
|
|
395793
397540
|
if (reservation !== void 0) try {
|
|
395794
397541
|
await reservation.abort();
|
|
395795
397542
|
} catch (cleanupError) {
|
|
395796
|
-
fail(deps, new Error(`${errorMessage$
|
|
397543
|
+
fail(deps, new Error(`${errorMessage$2(error)} Output reservation cleanup failed: ${errorMessage$2(cleanupError)}`, { cause: new AggregateError([error, cleanupError], "Output reservation cleanup failed.") }));
|
|
395797
397544
|
}
|
|
395798
397545
|
fail(deps, error);
|
|
395799
397546
|
}
|
|
@@ -395804,10 +397551,10 @@ function stringArray(value) {
|
|
|
395804
397551
|
return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : [];
|
|
395805
397552
|
}
|
|
395806
397553
|
function fail(deps, error) {
|
|
395807
|
-
deps.stderr.write(`${errorMessage$
|
|
397554
|
+
deps.stderr.write(`${errorMessage$2(error)}\n`);
|
|
395808
397555
|
return deps.exit(1);
|
|
395809
397556
|
}
|
|
395810
|
-
function errorMessage$
|
|
397557
|
+
function errorMessage$2(error) {
|
|
395811
397558
|
return error instanceof Error ? error.message : String(error);
|
|
395812
397559
|
}
|
|
395813
397560
|
//#endregion
|
|
@@ -396534,14 +398281,14 @@ async function run(deps, operation) {
|
|
|
396534
398281
|
try {
|
|
396535
398282
|
await operation();
|
|
396536
398283
|
} catch (error) {
|
|
396537
|
-
deps.stderr.write(`${errorMessage(error)}\n`);
|
|
398284
|
+
deps.stderr.write(`${errorMessage$1(error)}\n`);
|
|
396538
398285
|
deps.exit(1);
|
|
396539
398286
|
}
|
|
396540
398287
|
}
|
|
396541
398288
|
function writeJson(deps, value) {
|
|
396542
398289
|
deps.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
|
396543
398290
|
}
|
|
396544
|
-
function errorMessage(error) {
|
|
398291
|
+
function errorMessage$1(error) {
|
|
396545
398292
|
return error instanceof Error ? error.message : String(error);
|
|
396546
398293
|
}
|
|
396547
398294
|
//#endregion
|
|
@@ -396574,6 +398321,7 @@ function createProgram(version, onMain, onPluginNodeRunner = () => {}, onUpgrade
|
|
|
396574
398321
|
registerAcpCommand(program);
|
|
396575
398322
|
registerServerCommand(program);
|
|
396576
398323
|
registerLoginCommand(program);
|
|
398324
|
+
registerMistakesCommand(program);
|
|
396577
398325
|
registerPersonalMemoryCommand(program);
|
|
396578
398326
|
registerDoctorCommand(program);
|
|
396579
398327
|
registerVisCommand(program);
|
|
@@ -402281,9 +404029,9 @@ var TUI = class TUI extends Container {
|
|
|
402281
404029
|
const debugRedraw = process.env["PI_DEBUG_REDRAW"] === "1";
|
|
402282
404030
|
const logRedraw = (reason) => {
|
|
402283
404031
|
if (!debugRedraw) return;
|
|
402284
|
-
const logPath = path$
|
|
404032
|
+
const logPath = path$16.join(nodeOs.homedir(), ".pi", "agent", "pi-debug.log");
|
|
402285
404033
|
const msg = `[${(/* @__PURE__ */ new Date()).toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\n`;
|
|
402286
|
-
fs$
|
|
404034
|
+
fs$16.appendFileSync(logPath, msg);
|
|
402287
404035
|
};
|
|
402288
404036
|
if (this.previousLines.length === 0 && !widthChanged && !heightChanged) {
|
|
402289
404037
|
logRedraw("first render");
|
|
@@ -402430,8 +404178,8 @@ var TUI = class TUI extends Container {
|
|
|
402430
404178
|
buffer += "\x1B[?2026l";
|
|
402431
404179
|
if (process.env["PI_TUI_DEBUG"] === "1") {
|
|
402432
404180
|
const debugDir = "/tmp/tui";
|
|
402433
|
-
fs$
|
|
402434
|
-
const debugPath = path$
|
|
404181
|
+
fs$16.mkdirSync(debugDir, { recursive: true });
|
|
404182
|
+
const debugPath = path$16.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
|
|
402435
404183
|
const debugData = [
|
|
402436
404184
|
`firstChanged: ${firstChanged}`,
|
|
402437
404185
|
`viewportTop: ${viewportTop}`,
|
|
@@ -402454,7 +404202,7 @@ var TUI = class TUI extends Container {
|
|
|
402454
404202
|
"=== buffer ===",
|
|
402455
404203
|
JSON.stringify(buffer)
|
|
402456
404204
|
].join("\n");
|
|
402457
|
-
fs$
|
|
404205
|
+
fs$16.writeFileSync(debugPath, debugData);
|
|
402458
404206
|
}
|
|
402459
404207
|
this.terminal.write(buffer);
|
|
402460
404208
|
this.cursorRow = Math.max(0, newLines.length - 1);
|
|
@@ -407035,12 +408783,12 @@ function loadNativeModifiersHelper() {
|
|
|
407035
408783
|
if (process.platform !== "darwin") return void 0;
|
|
407036
408784
|
const arch = process.arch;
|
|
407037
408785
|
if (arch !== "x64" && arch !== "arm64") return void 0;
|
|
407038
|
-
const moduleDir = path$
|
|
407039
|
-
const nativePath = path$
|
|
408786
|
+
const moduleDir = path$16.dirname(fileURLToPath(import.meta.url));
|
|
408787
|
+
const nativePath = path$16.join("native", "darwin", "prebuilds", `darwin-${arch}`, "darwin-modifiers.node");
|
|
407040
408788
|
const candidates = [
|
|
407041
|
-
path$
|
|
407042
|
-
path$
|
|
407043
|
-
path$
|
|
408789
|
+
path$16.join(moduleDir, "..", nativePath),
|
|
408790
|
+
path$16.join(moduleDir, nativePath),
|
|
408791
|
+
path$16.join(path$16.dirname(process.execPath), nativePath)
|
|
407044
408792
|
];
|
|
407045
408793
|
for (const modulePath of candidates) try {
|
|
407046
408794
|
const helper = cjsRequire$1(modulePath);
|
|
@@ -407113,10 +408861,10 @@ var ProcessTerminal = class {
|
|
|
407113
408861
|
const env = process.env["PI_TUI_WRITE_LOG"] || "";
|
|
407114
408862
|
if (!env) return "";
|
|
407115
408863
|
try {
|
|
407116
|
-
if (fs$
|
|
408864
|
+
if (fs$16.statSync(env).isDirectory()) {
|
|
407117
408865
|
const now = /* @__PURE__ */ new Date();
|
|
407118
408866
|
const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}_${String(now.getHours()).padStart(2, "0")}-${String(now.getMinutes()).padStart(2, "0")}-${String(now.getSeconds()).padStart(2, "0")}`;
|
|
407119
|
-
return path$
|
|
408867
|
+
return path$16.join(env, `tui-${ts}-${process.pid}.log`);
|
|
407120
408868
|
}
|
|
407121
408869
|
} catch {}
|
|
407122
408870
|
return env;
|
|
@@ -407319,12 +409067,12 @@ var ProcessTerminal = class {
|
|
|
407319
409067
|
try {
|
|
407320
409068
|
const arch = process.arch;
|
|
407321
409069
|
if (arch !== "x64" && arch !== "arm64") return;
|
|
407322
|
-
const moduleDir = path$
|
|
407323
|
-
const nativePath = path$
|
|
409070
|
+
const moduleDir = path$16.dirname(fileURLToPath(import.meta.url));
|
|
409071
|
+
const nativePath = path$16.join("native", "win32", "prebuilds", `win32-${arch}`, "win32-console-mode.node");
|
|
407324
409072
|
const candidates = [
|
|
407325
|
-
path$
|
|
407326
|
-
path$
|
|
407327
|
-
path$
|
|
409073
|
+
path$16.join(moduleDir, "..", nativePath),
|
|
409074
|
+
path$16.join(moduleDir, nativePath),
|
|
409075
|
+
path$16.join(path$16.dirname(process.execPath), nativePath)
|
|
407328
409076
|
];
|
|
407329
409077
|
for (const modulePath of candidates) try {
|
|
407330
409078
|
cjsRequire(modulePath).enableVirtualTerminalInput?.();
|
|
@@ -407396,7 +409144,7 @@ var ProcessTerminal = class {
|
|
|
407396
409144
|
write(data) {
|
|
407397
409145
|
process.stdout.write(data);
|
|
407398
409146
|
if (this.writeLogPath) try {
|
|
407399
|
-
fs$
|
|
409147
|
+
fs$16.appendFileSync(this.writeLogPath, data, { encoding: "utf8" });
|
|
407400
409148
|
} catch {}
|
|
407401
409149
|
}
|
|
407402
409150
|
get columns() {
|
|
@@ -511439,6 +513187,103 @@ function runNativeAssetSmokeIfRequested() {
|
|
|
511439
513187
|
return true;
|
|
511440
513188
|
}
|
|
511441
513189
|
//#endregion
|
|
513190
|
+
//#region src/mistakes/automatic-sync.ts
|
|
513191
|
+
const AUTOMATIC_MISTAKE_SYNC_CONFIG_ENV = "BLUN_MISTAKE_SYNC_CONFIG";
|
|
513192
|
+
const DEFAULT_DEPS = {
|
|
513193
|
+
lstat,
|
|
513194
|
+
lock: (path) => import_proper_lockfile.default.lock(path, {
|
|
513195
|
+
realpath: false,
|
|
513196
|
+
retries: 0,
|
|
513197
|
+
stale: 3e4,
|
|
513198
|
+
update: 1e4
|
|
513199
|
+
}),
|
|
513200
|
+
watch: (options) => watchMistakeSources(options),
|
|
513201
|
+
logger: log
|
|
513202
|
+
};
|
|
513203
|
+
async function startAutomaticMistakeSync(options, deps = DEFAULT_DEPS) {
|
|
513204
|
+
const env = options.env ?? process.env;
|
|
513205
|
+
const configuredPath = env[AUTOMATIC_MISTAKE_SYNC_CONFIG_ENV]?.trim();
|
|
513206
|
+
const configPath = resolve(configuredPath && configuredPath.length > 0 ? configuredPath : join(options.homeDir, "mistake", "source-sync.json"));
|
|
513207
|
+
const inactive = () => ({
|
|
513208
|
+
active: false,
|
|
513209
|
+
configPath,
|
|
513210
|
+
stop: async () => {}
|
|
513211
|
+
});
|
|
513212
|
+
try {
|
|
513213
|
+
const stat = await deps.lstat(configPath);
|
|
513214
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
513215
|
+
deps.logger.warn("automatic mistake sync config is not a regular file", { configPath });
|
|
513216
|
+
return inactive();
|
|
513217
|
+
}
|
|
513218
|
+
} catch (error) {
|
|
513219
|
+
if (isErrorCode(error, "ENOENT")) return inactive();
|
|
513220
|
+
deps.logger.warn("automatic mistake sync config is unavailable", {
|
|
513221
|
+
configPath,
|
|
513222
|
+
error: errorMessage(error)
|
|
513223
|
+
});
|
|
513224
|
+
return inactive();
|
|
513225
|
+
}
|
|
513226
|
+
let release;
|
|
513227
|
+
try {
|
|
513228
|
+
release = await deps.lock(configPath);
|
|
513229
|
+
} catch (error) {
|
|
513230
|
+
if (isErrorCode(error, "ELOCKED")) return inactive();
|
|
513231
|
+
deps.logger.warn("automatic mistake sync lock failed", {
|
|
513232
|
+
configPath,
|
|
513233
|
+
error: errorMessage(error)
|
|
513234
|
+
});
|
|
513235
|
+
return inactive();
|
|
513236
|
+
}
|
|
513237
|
+
const controller = new AbortController();
|
|
513238
|
+
let released = false;
|
|
513239
|
+
const releaseOnce = async () => {
|
|
513240
|
+
if (released) return;
|
|
513241
|
+
released = true;
|
|
513242
|
+
try {
|
|
513243
|
+
await release();
|
|
513244
|
+
} catch {}
|
|
513245
|
+
};
|
|
513246
|
+
const watchPromise = deps.watch({
|
|
513247
|
+
configPath,
|
|
513248
|
+
env,
|
|
513249
|
+
intervalMs: options.intervalMs ?? 3e5,
|
|
513250
|
+
signal: controller.signal,
|
|
513251
|
+
onRun: (run) => logRun(deps.logger, run)
|
|
513252
|
+
}).catch((error) => {
|
|
513253
|
+
deps.logger.warn("automatic mistake sync stopped", {
|
|
513254
|
+
configPath,
|
|
513255
|
+
error: errorMessage(error)
|
|
513256
|
+
});
|
|
513257
|
+
}).finally(releaseOnce);
|
|
513258
|
+
return {
|
|
513259
|
+
active: true,
|
|
513260
|
+
configPath,
|
|
513261
|
+
stop: async () => {
|
|
513262
|
+
controller.abort();
|
|
513263
|
+
await watchPromise;
|
|
513264
|
+
}
|
|
513265
|
+
};
|
|
513266
|
+
}
|
|
513267
|
+
function logRun(logger, run) {
|
|
513268
|
+
const counts = Object.fromEntries([
|
|
513269
|
+
"uploaded",
|
|
513270
|
+
"heartbeat",
|
|
513271
|
+
"unchanged",
|
|
513272
|
+
"blocked",
|
|
513273
|
+
"failed"
|
|
513274
|
+
].map((status) => [status, run.results.filter((result) => result.status === status).length]));
|
|
513275
|
+
logger.info("automatic mistake sync completed", {
|
|
513276
|
+
configPath: run.config_path,
|
|
513277
|
+
...counts
|
|
513278
|
+
});
|
|
513279
|
+
}
|
|
513280
|
+
function isErrorCode(error, code) {
|
|
513281
|
+
return typeof error === "object" && error !== null && error.code === code;
|
|
513282
|
+
}
|
|
513283
|
+
function errorMessage(error) {
|
|
513284
|
+
return error instanceof Error ? error.message : String(error);
|
|
513285
|
+
}
|
|
513286
|
+
//#endregion
|
|
511442
513287
|
//#region src/main.ts
|
|
511443
513288
|
/**
|
|
511444
513289
|
* BLUN King entry point.
|
|
@@ -511471,9 +513316,15 @@ async function handleMainCommand(opts, version) {
|
|
|
511471
513316
|
} : { track });
|
|
511472
513317
|
if (preflightResult === "exit") process.exit(0);
|
|
511473
513318
|
const updateStartupNotice = typeof preflightResult === "object" ? preflightResult.startupNotice : void 0;
|
|
511474
|
-
|
|
513319
|
+
const mistakeSync = await startAutomaticMistakeSync({
|
|
513320
|
+
homeDir: resolveBlunHome$1(),
|
|
513321
|
+
env: process.env
|
|
513322
|
+
});
|
|
513323
|
+
if (validated.uiMode === "print") try {
|
|
511475
513324
|
await runPrompt(validated.options, version);
|
|
511476
513325
|
return { headlessCompleted: true };
|
|
513326
|
+
} finally {
|
|
513327
|
+
await mistakeSync.stop();
|
|
511477
513328
|
}
|
|
511478
513329
|
await runShell(validated.options, version, updateStartupNotice);
|
|
511479
513330
|
return { headlessCompleted: false };
|