@mitralab.io/sdk-core 0.3.8 → 0.3.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +80 -0
- package/README.md +42 -17
- package/contracts/README.md +9 -0
- package/contracts/manifest.json +11 -1
- package/contracts/v0.3.10/sdk-parity.json +2902 -0
- package/contracts/v0.3.9/sdk-parity.json +2902 -0
- package/dist/index.cjs +467 -12
- package/dist/index.d.cts +216 -1
- package/dist/index.d.ts +216 -1
- package/dist/index.js +465 -12
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -22,6 +22,7 @@ var index_exports = {};
|
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
API_KEY_EXCHANGE_PATH: () => API_KEY_EXCHANGE_PATH,
|
|
24
24
|
AgentTaskTurnError: () => AgentTaskTurnError,
|
|
25
|
+
FileTransferError: () => FileTransferError,
|
|
25
26
|
SdkCoreConfigurationError: () => SdkCoreConfigurationError,
|
|
26
27
|
SdkCoreResponseError: () => SdkCoreResponseError,
|
|
27
28
|
appAccessTokenPath: () => appAccessTokenPath,
|
|
@@ -37,6 +38,7 @@ __export(index_exports, {
|
|
|
37
38
|
createCustomQueriesModule: () => createCustomQueriesModule,
|
|
38
39
|
createDataSourcesModule: () => createDataSourcesModule,
|
|
39
40
|
createEntitiesModule: () => createEntitiesModule,
|
|
41
|
+
createFilesModule: () => createFilesModule,
|
|
40
42
|
createFunctionsAdminModule: () => createFunctionsAdminModule,
|
|
41
43
|
createFunctionsModule: () => createFunctionsModule,
|
|
42
44
|
createImportsModule: () => createImportsModule,
|
|
@@ -746,6 +748,55 @@ function expectImportExecution(value, context, errors = defaultSdkCoreErrorFacto
|
|
|
746
748
|
if (!isNullableString(execution.errorMessage)) invalidField(context, "errorMessage", errors);
|
|
747
749
|
return execution;
|
|
748
750
|
}
|
|
751
|
+
function expectFileMetadata(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
752
|
+
const file = expectObject(value, context, errors);
|
|
753
|
+
for (const field of ["id", "name", "contentType", "createdAt"]) {
|
|
754
|
+
if (typeof file[field] !== "string") invalidField(context, field, errors);
|
|
755
|
+
}
|
|
756
|
+
if (!isInteger(file.sizeBytes)) invalidField(context, "sizeBytes", errors);
|
|
757
|
+
if (!isOneOf(file.kind, ["TEMPORARY", "PERMANENT"])) {
|
|
758
|
+
invalidField(context, "kind", errors);
|
|
759
|
+
}
|
|
760
|
+
if (!isOneOf(file.visibility, ["PRIVATE", "RESTRICTED", "APP"])) {
|
|
761
|
+
invalidField(context, "visibility", errors);
|
|
762
|
+
}
|
|
763
|
+
if (!isOneOf(file.status, ["PENDING", "READY", "DELETED"])) {
|
|
764
|
+
invalidField(context, "status", errors);
|
|
765
|
+
}
|
|
766
|
+
if (!isOneOf(file.createdBy, ["USER", "FUNCTION"])) {
|
|
767
|
+
invalidField(context, "createdBy", errors);
|
|
768
|
+
}
|
|
769
|
+
for (const field of ["ownerUserId", "confirmedAt", "expiresAt"]) {
|
|
770
|
+
if (!isNullableString(file[field])) invalidField(context, field, errors);
|
|
771
|
+
}
|
|
772
|
+
return file;
|
|
773
|
+
}
|
|
774
|
+
function expectFileUpload(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
775
|
+
const upload = expectObject(value, context, errors);
|
|
776
|
+
for (const field of ["fileId", "uploadUrl", "uploadMethod", "expiresAt"]) {
|
|
777
|
+
if (typeof upload[field] !== "string" || !upload[field]) invalidField(context, field, errors);
|
|
778
|
+
}
|
|
779
|
+
if (!isStringRecord(upload.uploadHeaders)) invalidField(context, "uploadHeaders", errors);
|
|
780
|
+
return upload;
|
|
781
|
+
}
|
|
782
|
+
function expectFileReadUrl(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
783
|
+
const read = expectObject(value, context, errors);
|
|
784
|
+
if (typeof read.url !== "string" || !read.url) invalidField(context, "url", errors);
|
|
785
|
+
if (typeof read.expiresAt !== "string") invalidField(context, "expiresAt", errors);
|
|
786
|
+
return read;
|
|
787
|
+
}
|
|
788
|
+
function expectFileReadUrls(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
789
|
+
const response = expectObject(value, context, errors);
|
|
790
|
+
expectObjectArray(response.results, `${context} results`, errors).forEach(
|
|
791
|
+
(item, position) => {
|
|
792
|
+
const itemContext = `${context} result ${position}`;
|
|
793
|
+
if (typeof item.fileId !== "string") invalidField(itemContext, "fileId", errors);
|
|
794
|
+
if (typeof item.errorCode === "string") return;
|
|
795
|
+
expectFileReadUrl(item, itemContext, errors);
|
|
796
|
+
}
|
|
797
|
+
);
|
|
798
|
+
return response;
|
|
799
|
+
}
|
|
749
800
|
function expectMessageAccepted(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
750
801
|
const response = expectObject(value, context, errors);
|
|
751
802
|
if (typeof response.messageId !== "string") invalidField(context, "messageId", errors);
|
|
@@ -2371,6 +2422,248 @@ function createEntitiesModule(transport, errors = defaultSdkCoreErrorFactory) {
|
|
|
2371
2422
|
});
|
|
2372
2423
|
}
|
|
2373
2424
|
|
|
2425
|
+
// src/fileTransferError.ts
|
|
2426
|
+
var FileTransferError = class extends Error {
|
|
2427
|
+
fileId;
|
|
2428
|
+
step;
|
|
2429
|
+
/**
|
|
2430
|
+
* HTTP status storage answered in `send` and `download`; null when storage gave no status or the
|
|
2431
|
+
* content failed to arrive, and always in `confirm`.
|
|
2432
|
+
*/
|
|
2433
|
+
status;
|
|
2434
|
+
/**
|
|
2435
|
+
* True when the `PENDING` file a failed `send` left behind was deleted. False when that delete
|
|
2436
|
+
* failed too, and always in `confirm` and `download`, where nothing is deleted.
|
|
2437
|
+
*/
|
|
2438
|
+
cleanedUp;
|
|
2439
|
+
constructor(message, details) {
|
|
2440
|
+
super(message, details.cause === void 0 ? void 0 : { cause: details.cause });
|
|
2441
|
+
this.name = "FileTransferError";
|
|
2442
|
+
this.fileId = details.fileId;
|
|
2443
|
+
this.step = details.step;
|
|
2444
|
+
this.status = details.status ?? null;
|
|
2445
|
+
this.cleanedUp = details.cleanedUp ?? false;
|
|
2446
|
+
}
|
|
2447
|
+
};
|
|
2448
|
+
|
|
2449
|
+
// src/modules/files.ts
|
|
2450
|
+
var MAX_READ_URLS = 100;
|
|
2451
|
+
var UNTYPED_CONTENT = "application/octet-stream";
|
|
2452
|
+
var REDACTED = "<redacted>";
|
|
2453
|
+
var MAX_CAUSE_DEPTH = 5;
|
|
2454
|
+
var MIN_SECRET_LENGTH = 16;
|
|
2455
|
+
var UNREADABLE_STORAGE_ERROR = "storage failed with an error the Core cannot show";
|
|
2456
|
+
function createFilesModule(transport, options = {}, errors = defaultSdkCoreErrorFactory) {
|
|
2457
|
+
const path = (fileId) => `/api/v1/files/${encodePathSegment(fileId, "file id", errors)}`;
|
|
2458
|
+
const storageFetch = () => {
|
|
2459
|
+
if (options.fetch) return options.fetch;
|
|
2460
|
+
const global = globalThis.fetch;
|
|
2461
|
+
if (typeof global !== "function") {
|
|
2462
|
+
configurationError("fetch is not available: pass files.fetch to the Core", errors);
|
|
2463
|
+
}
|
|
2464
|
+
return global;
|
|
2465
|
+
};
|
|
2466
|
+
const requestUpload = async (input) => expectFileUpload(
|
|
2467
|
+
await transport.request("/api/v1/files", { method: "POST", body: input }),
|
|
2468
|
+
"File upload response",
|
|
2469
|
+
errors
|
|
2470
|
+
);
|
|
2471
|
+
const confirmUpload = async (fileId) => expectFileMetadata(
|
|
2472
|
+
await transport.request(`${path(fileId)}/confirm`, { method: "POST" }),
|
|
2473
|
+
"Confirm file upload response",
|
|
2474
|
+
errors
|
|
2475
|
+
);
|
|
2476
|
+
const getUrl = async (fileId, { expiresInSeconds } = {}) => expectFileReadUrl(
|
|
2477
|
+
await transport.request(`${path(fileId)}/read-url`, {
|
|
2478
|
+
method: "POST",
|
|
2479
|
+
...expiresInSeconds === void 0 ? {} : { body: { expiresInSeconds } }
|
|
2480
|
+
}),
|
|
2481
|
+
"File read URL response",
|
|
2482
|
+
errors
|
|
2483
|
+
);
|
|
2484
|
+
const deleteFile = async (fileId) => {
|
|
2485
|
+
expectEmpty(
|
|
2486
|
+
await transport.request(path(fileId), { method: "DELETE" }),
|
|
2487
|
+
"Delete file response",
|
|
2488
|
+
errors
|
|
2489
|
+
);
|
|
2490
|
+
};
|
|
2491
|
+
const sendContent = async (fetch, upload, content, signal) => {
|
|
2492
|
+
const failure = await putContent(fetch, upload, content, signal);
|
|
2493
|
+
if (failure === null) return;
|
|
2494
|
+
const cleanedUp = await deleteFile(upload.fileId).then(
|
|
2495
|
+
() => true,
|
|
2496
|
+
() => false
|
|
2497
|
+
);
|
|
2498
|
+
if (failure.aborted && signal !== void 0) throw abortReason(signal);
|
|
2499
|
+
throw new FileTransferError(`File ${upload.fileId} was not sent: ${failure.reason}`, {
|
|
2500
|
+
fileId: upload.fileId,
|
|
2501
|
+
step: "send",
|
|
2502
|
+
status: failure.status,
|
|
2503
|
+
cause: "error" in failure ? storageCause(failure.error, upload.uploadUrl) : void 0,
|
|
2504
|
+
cleanedUp
|
|
2505
|
+
});
|
|
2506
|
+
};
|
|
2507
|
+
const confirmSent = async (fileId) => {
|
|
2508
|
+
try {
|
|
2509
|
+
return await confirmUpload(fileId);
|
|
2510
|
+
} catch (error) {
|
|
2511
|
+
throw new FileTransferError(
|
|
2512
|
+
`File ${fileId} was sent but not confirmed: ${messageOf(error)}`,
|
|
2513
|
+
{
|
|
2514
|
+
fileId,
|
|
2515
|
+
step: "confirm",
|
|
2516
|
+
cause: error
|
|
2517
|
+
}
|
|
2518
|
+
);
|
|
2519
|
+
}
|
|
2520
|
+
};
|
|
2521
|
+
return {
|
|
2522
|
+
requestUpload,
|
|
2523
|
+
confirmUpload,
|
|
2524
|
+
async upload(content, uploadOptions) {
|
|
2525
|
+
const fetch = storageFetch();
|
|
2526
|
+
const input = uploadInput(content, uploadOptions, errors);
|
|
2527
|
+
const { signal } = uploadOptions;
|
|
2528
|
+
if (signal?.aborted) throw abortReason(signal);
|
|
2529
|
+
const upload = await requestUpload(input);
|
|
2530
|
+
await sendContent(fetch, upload, content, signal);
|
|
2531
|
+
return confirmSent(upload.fileId);
|
|
2532
|
+
},
|
|
2533
|
+
getUrl,
|
|
2534
|
+
async getUrls(fileIds, { expiresInSeconds } = {}) {
|
|
2535
|
+
requireBatchSize(fileIds, "fileIds", MAX_READ_URLS, errors);
|
|
2536
|
+
return expectFileReadUrls(
|
|
2537
|
+
await transport.request("/api/v1/files/read-urls", {
|
|
2538
|
+
method: "POST",
|
|
2539
|
+
body: { fileIds, ...expiresInSeconds === void 0 ? {} : { expiresInSeconds } }
|
|
2540
|
+
}),
|
|
2541
|
+
"File read URLs response",
|
|
2542
|
+
errors
|
|
2543
|
+
);
|
|
2544
|
+
},
|
|
2545
|
+
async download(fileId, { signal } = {}) {
|
|
2546
|
+
const fetch = storageFetch();
|
|
2547
|
+
if (signal?.aborted) throw abortReason(signal);
|
|
2548
|
+
const { url } = await getUrl(fileId);
|
|
2549
|
+
return fetchContent(fetch, fileId, url, signal);
|
|
2550
|
+
},
|
|
2551
|
+
async get(fileId) {
|
|
2552
|
+
return expectFileMetadata(
|
|
2553
|
+
await transport.request(path(fileId), { method: "GET" }),
|
|
2554
|
+
"File response",
|
|
2555
|
+
errors
|
|
2556
|
+
);
|
|
2557
|
+
},
|
|
2558
|
+
delete: deleteFile
|
|
2559
|
+
};
|
|
2560
|
+
}
|
|
2561
|
+
function uploadInput(content, options, errors) {
|
|
2562
|
+
const name = options.name ?? fileNameOf(content);
|
|
2563
|
+
if (!name) configurationError("name is required when the content is not a named File", errors);
|
|
2564
|
+
const contentType = options.contentType || content.type || UNTYPED_CONTENT;
|
|
2565
|
+
return {
|
|
2566
|
+
name,
|
|
2567
|
+
contentType,
|
|
2568
|
+
sizeBytes: content.size,
|
|
2569
|
+
kind: options.kind,
|
|
2570
|
+
visibility: options.visibility,
|
|
2571
|
+
...options.appOwned === void 0 ? {} : { appOwned: options.appOwned }
|
|
2572
|
+
};
|
|
2573
|
+
}
|
|
2574
|
+
function fileNameOf(content) {
|
|
2575
|
+
const name = content.name;
|
|
2576
|
+
return typeof name === "string" ? name : void 0;
|
|
2577
|
+
}
|
|
2578
|
+
async function putContent(fetch, upload, content, signal) {
|
|
2579
|
+
try {
|
|
2580
|
+
const response = await fetch(upload.uploadUrl, {
|
|
2581
|
+
method: upload.uploadMethod,
|
|
2582
|
+
headers: upload.uploadHeaders,
|
|
2583
|
+
body: content,
|
|
2584
|
+
redirect: "error",
|
|
2585
|
+
...signal === void 0 ? {} : { signal }
|
|
2586
|
+
});
|
|
2587
|
+
discardBody(response);
|
|
2588
|
+
if (response.ok) return null;
|
|
2589
|
+
return {
|
|
2590
|
+
reason: `storage answered ${response.status}`,
|
|
2591
|
+
status: response.status,
|
|
2592
|
+
aborted: false
|
|
2593
|
+
};
|
|
2594
|
+
} catch (error) {
|
|
2595
|
+
return {
|
|
2596
|
+
reason: "the transfer to storage failed",
|
|
2597
|
+
status: null,
|
|
2598
|
+
aborted: signal?.aborted === true,
|
|
2599
|
+
error
|
|
2600
|
+
};
|
|
2601
|
+
}
|
|
2602
|
+
}
|
|
2603
|
+
async function fetchContent(fetch, fileId, url, signal) {
|
|
2604
|
+
let response;
|
|
2605
|
+
try {
|
|
2606
|
+
response = await fetch(url, {
|
|
2607
|
+
method: "GET",
|
|
2608
|
+
redirect: "error",
|
|
2609
|
+
...signal === void 0 ? {} : { signal }
|
|
2610
|
+
});
|
|
2611
|
+
if (response.ok) return await response.blob();
|
|
2612
|
+
} catch (error) {
|
|
2613
|
+
if (signal?.aborted) throw abortReason(signal);
|
|
2614
|
+
throw new FileTransferError(
|
|
2615
|
+
`File ${fileId} was not downloaded: the transfer from storage failed`,
|
|
2616
|
+
{ fileId, step: "download", cause: storageCause(error, url) }
|
|
2617
|
+
);
|
|
2618
|
+
}
|
|
2619
|
+
discardBody(response);
|
|
2620
|
+
throw new FileTransferError(
|
|
2621
|
+
`File ${fileId} was not downloaded: storage answered ${response.status}`,
|
|
2622
|
+
{ fileId, step: "download", status: response.status }
|
|
2623
|
+
);
|
|
2624
|
+
}
|
|
2625
|
+
function storageCause(thrown, link) {
|
|
2626
|
+
const secrets = linkSecrets(link);
|
|
2627
|
+
const redact = (text) => secrets.reduce((result, secret) => result.replaceAll(secret, REDACTED), text);
|
|
2628
|
+
const rebuild = (value, depth) => {
|
|
2629
|
+
if (!(value instanceof Error)) {
|
|
2630
|
+
const opaque = typeof value === "function" || typeof value === "object" && value !== null;
|
|
2631
|
+
return new Error(opaque ? UNREADABLE_STORAGE_ERROR : redact(String(value)));
|
|
2632
|
+
}
|
|
2633
|
+
const below = depth < MAX_CAUSE_DEPTH && value.cause != null ? rebuild(value.cause, depth + 1) : void 0;
|
|
2634
|
+
const error = new Error(
|
|
2635
|
+
redact(String(value.message)),
|
|
2636
|
+
below === void 0 ? void 0 : { cause: below }
|
|
2637
|
+
);
|
|
2638
|
+
error.name = redact(String(value.name));
|
|
2639
|
+
if (typeof value.stack === "string") error.stack = redact(value.stack);
|
|
2640
|
+
const { code } = value;
|
|
2641
|
+
return typeof code === "string" ? Object.assign(error, { code: redact(code) }) : error;
|
|
2642
|
+
};
|
|
2643
|
+
try {
|
|
2644
|
+
return rebuild(thrown, 1);
|
|
2645
|
+
} catch {
|
|
2646
|
+
return new Error(UNREADABLE_STORAGE_ERROR);
|
|
2647
|
+
}
|
|
2648
|
+
}
|
|
2649
|
+
function linkSecrets(link) {
|
|
2650
|
+
const start = link.indexOf("?");
|
|
2651
|
+
const query = start < 0 ? "" : link.slice(start + 1);
|
|
2652
|
+
const raw = query.split("&").map((pair) => pair.slice(pair.indexOf("=") + 1));
|
|
2653
|
+
const decoded = [...new URLSearchParams(query).values()];
|
|
2654
|
+
const values = [...raw, ...decoded].filter((value) => value.length >= MIN_SECRET_LENGTH);
|
|
2655
|
+
return [link, query, ...values].filter((secret) => secret.length > 0);
|
|
2656
|
+
}
|
|
2657
|
+
function discardBody(response) {
|
|
2658
|
+
void Promise.resolve().then(() => response.body?.cancel()).catch(() => void 0);
|
|
2659
|
+
}
|
|
2660
|
+
function abortReason(signal) {
|
|
2661
|
+
return signal.reason ?? new DOMException("This operation was aborted", "AbortError");
|
|
2662
|
+
}
|
|
2663
|
+
function messageOf(error) {
|
|
2664
|
+
return error instanceof Error ? error.message : String(error);
|
|
2665
|
+
}
|
|
2666
|
+
|
|
2374
2667
|
// src/modules/functions.ts
|
|
2375
2668
|
var DefaultFunctionsModule = class {
|
|
2376
2669
|
constructor(transport, errors, options) {
|
|
@@ -3380,6 +3673,7 @@ function createSdkCore(options) {
|
|
|
3380
3673
|
customQueries: createCustomQueriesModule(options.transports.dataManager, errors),
|
|
3381
3674
|
dataSources: createDataSourcesModule(options.transports.dataManager, errors),
|
|
3382
3675
|
entities: createEntitiesModule(options.transports.dataManager, errors),
|
|
3676
|
+
files: createFilesModule(options.transports.dataManager, options.files, errors),
|
|
3383
3677
|
functions: createFunctionsModule(options.transports.functions, options.functions, errors),
|
|
3384
3678
|
functionsAdmin,
|
|
3385
3679
|
imports: createImportsModule(options.transports.dataManager, errors),
|
|
@@ -4272,6 +4566,14 @@ function errorCode(error) {
|
|
|
4272
4566
|
const code = candidate.code ?? candidate.details?.code ?? candidate.details?.error_code;
|
|
4273
4567
|
return typeof code === "string" ? code : void 0;
|
|
4274
4568
|
}
|
|
4569
|
+
function refusalSentence(error) {
|
|
4570
|
+
if (!error || typeof error !== "object" || errorCode(error) === void 0) return void 0;
|
|
4571
|
+
const candidate = error;
|
|
4572
|
+
const refused = error instanceof AgentTaskTurnError || typeof candidate.status === "number" && candidate.status >= 400;
|
|
4573
|
+
if (!refused) return void 0;
|
|
4574
|
+
const sentence = asObject2(candidate.details)?.message ?? asObject2(candidate.body)?.message ?? errorMessage2(error);
|
|
4575
|
+
return typeof sentence === "string" && sentence.trim() ? sentence : void 0;
|
|
4576
|
+
}
|
|
4275
4577
|
function delay(milliseconds) {
|
|
4276
4578
|
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
4277
4579
|
}
|
|
@@ -4351,6 +4653,46 @@ function historyCursorOf(history) {
|
|
|
4351
4653
|
}
|
|
4352
4654
|
return { sequence, ...newest.boxLog === void 0 ? {} : { boxLog: newest.boxLog } };
|
|
4353
4655
|
}
|
|
4656
|
+
var SUBAGENT_END_STATUSES = /* @__PURE__ */ new Set([
|
|
4657
|
+
"completed",
|
|
4658
|
+
"failed",
|
|
4659
|
+
"cancelled",
|
|
4660
|
+
"interrupted"
|
|
4661
|
+
]);
|
|
4662
|
+
function samePiece(held, row) {
|
|
4663
|
+
if (held.id === row.id) return true;
|
|
4664
|
+
if (!held.id.startsWith("live:")) return false;
|
|
4665
|
+
if (held.kind === "user" && row.kind === "user" && held.clientMessageId !== void 0) {
|
|
4666
|
+
return held.clientMessageId === row.clientMessageId;
|
|
4667
|
+
}
|
|
4668
|
+
if (row.itemId === void 0) return false;
|
|
4669
|
+
if (held.kind !== row.kind || held.itemId !== row.itemId) return false;
|
|
4670
|
+
return held.kind !== "tool" || row.kind === "tool" && held.tool.phase === row.tool.phase;
|
|
4671
|
+
}
|
|
4672
|
+
function heldIsNewer(held, row) {
|
|
4673
|
+
const heldLast = held.lastSequence ?? held.sequence;
|
|
4674
|
+
const rowLast = row.lastSequence ?? row.sequence;
|
|
4675
|
+
if (heldLast === void 0 || rowLast === void 0) return false;
|
|
4676
|
+
if (held.boxLog !== void 0 && held.boxLog !== row.boxLog) return false;
|
|
4677
|
+
return heldLast > rowLast;
|
|
4678
|
+
}
|
|
4679
|
+
function heldHasRow(held, row) {
|
|
4680
|
+
if (held.kind !== "agent" && held.kind !== "reasoning") return true;
|
|
4681
|
+
return held.sequence !== void 0 && row.sequence !== void 0 && held.sequence <= row.sequence;
|
|
4682
|
+
}
|
|
4683
|
+
function oldestRowOf(history) {
|
|
4684
|
+
return history.find((item) => !item.id.startsWith("live:"));
|
|
4685
|
+
}
|
|
4686
|
+
function rowOrHeld(held, row, liveComparable) {
|
|
4687
|
+
if (!liveComparable || !heldIsNewer(held, row) || !heldHasRow(held, row)) return row;
|
|
4688
|
+
return {
|
|
4689
|
+
...held,
|
|
4690
|
+
id: row.id,
|
|
4691
|
+
...row.sequence === void 0 ? {} : { sequence: row.sequence },
|
|
4692
|
+
...held.lastSequence === void 0 && held.sequence === void 0 ? {} : { lastSequence: held.lastSequence ?? held.sequence },
|
|
4693
|
+
...row.boxLog === void 0 ? {} : { boxLog: row.boxLog }
|
|
4694
|
+
};
|
|
4695
|
+
}
|
|
4354
4696
|
function hasOlderRows(page) {
|
|
4355
4697
|
return page.page.totalPages > page.page.number + 1;
|
|
4356
4698
|
}
|
|
@@ -4562,6 +4904,9 @@ var CoreAgentTaskSession = class {
|
|
|
4562
4904
|
// Whether the box the channel follows counts in the log of the history's rows. A box whose hello
|
|
4563
4905
|
// names another log, or reports a log shorter than the history's, has sequences that start over.
|
|
4564
4906
|
rowsInChannelLog = true;
|
|
4907
|
+
// The log the hello of the channel named. A reread compares its rows with it every time: the
|
|
4908
|
+
// flag above starts over at each reread, and a page from the old log may come again.
|
|
4909
|
+
channelLog;
|
|
4565
4910
|
olderRead = null;
|
|
4566
4911
|
get taskId() {
|
|
4567
4912
|
return this._taskId;
|
|
@@ -4661,7 +5006,7 @@ var CoreAgentTaskSession = class {
|
|
|
4661
5006
|
include: "plan"
|
|
4662
5007
|
});
|
|
4663
5008
|
this.historyLimit = options.limit;
|
|
4664
|
-
this.
|
|
5009
|
+
await this.rereadHistory(page);
|
|
4665
5010
|
const history = this.history;
|
|
4666
5011
|
this.emit("historyLoaded", { history });
|
|
4667
5012
|
return history;
|
|
@@ -4680,7 +5025,7 @@ var CoreAgentTaskSession = class {
|
|
|
4680
5025
|
return this.olderRead.promise;
|
|
4681
5026
|
}
|
|
4682
5027
|
async readOlder(generation) {
|
|
4683
|
-
const oldest = this._history
|
|
5028
|
+
const oldest = oldestRowOf(this._history);
|
|
4684
5029
|
if (!this._taskId || !this._hasOlder || !oldest) return [];
|
|
4685
5030
|
let page;
|
|
4686
5031
|
try {
|
|
@@ -4696,17 +5041,110 @@ var CoreAgentTaskSession = class {
|
|
|
4696
5041
|
throw error;
|
|
4697
5042
|
}
|
|
4698
5043
|
if (generation !== this.historyGeneration || this.isClosed()) return [];
|
|
4699
|
-
const
|
|
5044
|
+
const rows = [...page.content].reverse().map(toAgentTimelineItem);
|
|
5045
|
+
const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
|
|
5046
|
+
const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
|
|
5047
|
+
const taken = /* @__PURE__ */ new Set();
|
|
5048
|
+
const older = rows.map((row) => {
|
|
5049
|
+
const held = this._history.find(
|
|
5050
|
+
(item) => !taken.has(item) && item.id.startsWith("live:") && samePiece(item, row)
|
|
5051
|
+
);
|
|
5052
|
+
if (held === void 0) return row;
|
|
5053
|
+
taken.add(held);
|
|
5054
|
+
return rowOrHeld(held, row, liveComparable);
|
|
5055
|
+
});
|
|
4700
5056
|
this._hasOlder = hasOlderRows(page);
|
|
4701
|
-
this._history = [...older, ...this._history];
|
|
5057
|
+
this._history = [...older, ...this._history.filter((item) => !taken.has(item))];
|
|
4702
5058
|
this.emit("historyLoaded", { history: this.history });
|
|
4703
5059
|
return older;
|
|
4704
5060
|
}
|
|
5061
|
+
// A page that starts at a piece held live, with live pieces before it that no row of the page
|
|
5062
|
+
// takes, skipped rows the Copilot wrote between two rereads (more than a page of them): kept as
|
|
5063
|
+
// they are, those pieces never get their rows, and `loadOlder` only reads before the oldest row.
|
|
5064
|
+
// The rows before the page are read as `loadOlder` reads them, until the page reaches a row the
|
|
5065
|
+
// history holds or the gap's pieces all have their rows. A read of a history since replaced
|
|
5066
|
+
// lands nowhere (#145).
|
|
5067
|
+
async rereadHistory(page) {
|
|
5068
|
+
const generation = this.historyGeneration;
|
|
5069
|
+
let current = page;
|
|
5070
|
+
let extended = false;
|
|
5071
|
+
while (this._taskId && hasOlderRows(current) && this.skipsRows(current, extended)) {
|
|
5072
|
+
const oldest = current.content[current.content.length - 1];
|
|
5073
|
+
if (!oldest) break;
|
|
5074
|
+
let older;
|
|
5075
|
+
try {
|
|
5076
|
+
older = await this.dependencies.tasks.listMessages(this._taskId, {
|
|
5077
|
+
before: oldest.id,
|
|
5078
|
+
...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
|
|
5079
|
+
sort: "createdAt,desc",
|
|
5080
|
+
kinds: "all",
|
|
5081
|
+
include: "plan"
|
|
5082
|
+
});
|
|
5083
|
+
} catch (error) {
|
|
5084
|
+
if (generation !== this.historyGeneration || this.isClosed()) return;
|
|
5085
|
+
throw error;
|
|
5086
|
+
}
|
|
5087
|
+
if (generation !== this.historyGeneration || this.isClosed()) return;
|
|
5088
|
+
current = { content: [...current.content, ...older.content], page: older.page };
|
|
5089
|
+
extended = true;
|
|
5090
|
+
}
|
|
5091
|
+
this.replaceHistory(current);
|
|
5092
|
+
}
|
|
5093
|
+
// Newest first, as the Copilot answers. Once rows before the page were read, a row the history
|
|
5094
|
+
// does not hold at all (one the session never heard) is still inside the gap.
|
|
5095
|
+
skipsRows(page, extended) {
|
|
5096
|
+
const rows = page.content.map(toAgentTimelineItem);
|
|
5097
|
+
const first = rows[rows.length - 1];
|
|
5098
|
+
if (!first) return false;
|
|
5099
|
+
const anchor = this._history.findIndex((item) => samePiece(item, first));
|
|
5100
|
+
if (anchor < 0) return extended;
|
|
5101
|
+
if (!this._history[anchor]?.id.startsWith("live:")) return false;
|
|
5102
|
+
for (let index = anchor - 1; index >= 0; index -= 1) {
|
|
5103
|
+
const held = this._history[index];
|
|
5104
|
+
if (!held?.id.startsWith("live:")) return false;
|
|
5105
|
+
if (!rows.some((row) => samePiece(held, row))) return true;
|
|
5106
|
+
}
|
|
5107
|
+
return false;
|
|
5108
|
+
}
|
|
5109
|
+
// The recovery rereads only the newest 100 rows while the turn runs: the older pages already
|
|
5110
|
+
// read stay, or what sits in them (the cards of subagents still running) vanishes until
|
|
5111
|
+
// `loadOlder` (#145). A page that does not reach the history it already has replaces it.
|
|
4705
5112
|
replaceHistory(page) {
|
|
4706
|
-
this.
|
|
5113
|
+
const oldest = oldestRowOf(this._history)?.id;
|
|
5114
|
+
const rows = [...page.content].reverse().map(toAgentTimelineItem);
|
|
5115
|
+
const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
|
|
5116
|
+
const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
|
|
4707
5117
|
this.rowsInChannelLog = true;
|
|
4708
|
-
|
|
4709
|
-
|
|
5118
|
+
const first = rows[0];
|
|
5119
|
+
const anchor = first ? this._history.findIndex((item) => samePiece(item, first)) : -1;
|
|
5120
|
+
const kept = anchor < 0 ? [] : this._history.slice(0, anchor).filter((item) => !rows.some((row) => samePiece(item, row)));
|
|
5121
|
+
const replaced = anchor < 0 ? this._history : this._history.slice(anchor);
|
|
5122
|
+
if (anchor < 0) this._hasOlder = hasOlderRows(page);
|
|
5123
|
+
const used = /* @__PURE__ */ new Set();
|
|
5124
|
+
const merged = rows.map((row) => {
|
|
5125
|
+
const held = this._history.find((item) => !used.has(item) && samePiece(item, row));
|
|
5126
|
+
if (held === void 0) return row;
|
|
5127
|
+
used.add(held);
|
|
5128
|
+
return rowOrHeld(held, row, liveComparable);
|
|
5129
|
+
});
|
|
5130
|
+
const cursor = liveComparable ? historyCursorOf(rows) : void 0;
|
|
5131
|
+
const unrecorded = cursor === void 0 ? [] : replaced.filter(
|
|
5132
|
+
(item) => !used.has(item) && item.id.startsWith("live:") && item.sequence !== void 0 && (item.kind === "plan" || item.sequence > cursor.sequence)
|
|
5133
|
+
);
|
|
5134
|
+
this._history = [...kept, ...merged, ...unrecorded];
|
|
5135
|
+
if (anchor < 0 || oldestRowOf(this._history)?.id !== oldest) this.historyGeneration += 1;
|
|
5136
|
+
if (cursor === void 0) return;
|
|
5137
|
+
for (const subagent of this.subagentsById.values()) {
|
|
5138
|
+
const row = this._history.find(
|
|
5139
|
+
(item) => item.kind === "tool" && item.tool.toolId === subagent.toolId
|
|
5140
|
+
);
|
|
5141
|
+
const rowStatus = row?.kind === "tool" ? row.subagent?.status : void 0;
|
|
5142
|
+
if (rowStatus !== void 0 && SUBAGENT_END_STATUSES.has(rowStatus)) continue;
|
|
5143
|
+
const applied = this.subagentSequences.get(subagent.subagentId);
|
|
5144
|
+
if (SUBAGENT_END_STATUSES.has(subagent.status) || applied !== void 0 && applied > cursor.sequence) {
|
|
5145
|
+
this.writeSubagentOnSpawn(subagent);
|
|
5146
|
+
}
|
|
5147
|
+
}
|
|
4710
5148
|
}
|
|
4711
5149
|
editQueueItem(id, text) {
|
|
4712
5150
|
this.requireOpen();
|
|
@@ -4805,7 +5243,7 @@ var CoreAgentTaskSession = class {
|
|
|
4805
5243
|
});
|
|
4806
5244
|
const dispatch = this.dispatchSend(prompt, options, clientMessageId, handedOver, waiter).catch((error) => {
|
|
4807
5245
|
waiter?.reject(error);
|
|
4808
|
-
this.
|
|
5246
|
+
this.emitSendError(error);
|
|
4809
5247
|
if (this._status === "streaming") {
|
|
4810
5248
|
this.settleSteers((steered) => steered.reject(error));
|
|
4811
5249
|
this.setStatus("idle");
|
|
@@ -4873,7 +5311,7 @@ var CoreAgentTaskSession = class {
|
|
|
4873
5311
|
taken = await admitted;
|
|
4874
5312
|
} catch (error) {
|
|
4875
5313
|
handedOver();
|
|
4876
|
-
this.
|
|
5314
|
+
this.emitSendError(error);
|
|
4877
5315
|
return fail(error);
|
|
4878
5316
|
}
|
|
4879
5317
|
if (!taken) {
|
|
@@ -4943,7 +5381,7 @@ var CoreAgentTaskSession = class {
|
|
|
4943
5381
|
}).catch((error) => {
|
|
4944
5382
|
this.forgetSteer(steered);
|
|
4945
5383
|
waiter?.reject(error);
|
|
4946
|
-
this.
|
|
5384
|
+
this.emitSendError(error);
|
|
4947
5385
|
}).finally(() => {
|
|
4948
5386
|
this.pendingSteers -= 1;
|
|
4949
5387
|
});
|
|
@@ -5135,7 +5573,7 @@ var CoreAgentTaskSession = class {
|
|
|
5135
5573
|
kinds: "all",
|
|
5136
5574
|
include: "plan"
|
|
5137
5575
|
});
|
|
5138
|
-
this.
|
|
5576
|
+
await this.rereadHistory(page);
|
|
5139
5577
|
this.emit("historyLoaded", { history: this.history });
|
|
5140
5578
|
const rows = page.content.filter(isChatRow);
|
|
5141
5579
|
const recovered = rows.find(
|
|
@@ -5289,6 +5727,7 @@ var CoreAgentTaskSession = class {
|
|
|
5289
5727
|
break;
|
|
5290
5728
|
case "hello": {
|
|
5291
5729
|
const lastSequence = payload?.lastSequence;
|
|
5730
|
+
if (typeof payload?.boxLog === "number") this.channelLog = payload.boxLog;
|
|
5292
5731
|
const history = historyCursorOf(this._history);
|
|
5293
5732
|
const rowsLog = [...this._history].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
|
|
5294
5733
|
if (typeof payload?.boxLog === "number" && rowsLog !== void 0 && payload.boxLog !== rowsLog || typeof lastSequence === "number" && history !== void 0 && lastSequence < history.sequence) {
|
|
@@ -5765,6 +6204,12 @@ var CoreAgentTaskSession = class {
|
|
|
5765
6204
|
...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
|
|
5766
6205
|
};
|
|
5767
6206
|
this.subagentsById.set(subagentId, subagent);
|
|
6207
|
+
this.writeSubagentOnSpawn(subagent);
|
|
6208
|
+
this.emit("subagent", { ...subagent, ...sequenceOf(event) });
|
|
6209
|
+
}
|
|
6210
|
+
// The call that spawned it carries its last state, as the history records it.
|
|
6211
|
+
writeSubagentOnSpawn(subagent) {
|
|
6212
|
+
const { toolId, subagentId, status } = subagent;
|
|
5768
6213
|
const index = this._history.findIndex(
|
|
5769
6214
|
(item) => item.kind === "tool" && item.tool.toolId === toolId
|
|
5770
6215
|
);
|
|
@@ -5782,7 +6227,6 @@ var CoreAgentTaskSession = class {
|
|
|
5782
6227
|
}
|
|
5783
6228
|
};
|
|
5784
6229
|
}
|
|
5785
|
-
this.emit("subagent", { ...subagent, ...sequenceOf(event) });
|
|
5786
6230
|
}
|
|
5787
6231
|
finishTurn(reason, usage, end = {}) {
|
|
5788
6232
|
if (this._status !== "streaming" && this._status !== "cancelled") return;
|
|
@@ -5880,6 +6324,15 @@ var CoreAgentTaskSession = class {
|
|
|
5880
6324
|
error: `${prefix}: ${errorMessage2(error)}`
|
|
5881
6325
|
});
|
|
5882
6326
|
}
|
|
6327
|
+
emitSendError(error) {
|
|
6328
|
+
const sentence = refusalSentence(error);
|
|
6329
|
+
if (sentence === void 0) {
|
|
6330
|
+
this.emitError("Failed to send Agent prompt", error);
|
|
6331
|
+
return;
|
|
6332
|
+
}
|
|
6333
|
+
const code = errorCode(error);
|
|
6334
|
+
this.emit("error", { ...code ? { code } : {}, error: sentence });
|
|
6335
|
+
}
|
|
5883
6336
|
setStatus(status) {
|
|
5884
6337
|
if (this._status === status) return;
|
|
5885
6338
|
if (status !== "streaming" && status !== "cancelled") {
|
|
@@ -5984,6 +6437,7 @@ async function resolveApiKeyToken(call, appId, apiKey, errors = defaultSdkCoreEr
|
|
|
5984
6437
|
0 && (module.exports = {
|
|
5985
6438
|
API_KEY_EXCHANGE_PATH,
|
|
5986
6439
|
AgentTaskTurnError,
|
|
6440
|
+
FileTransferError,
|
|
5987
6441
|
SdkCoreConfigurationError,
|
|
5988
6442
|
SdkCoreResponseError,
|
|
5989
6443
|
appAccessTokenPath,
|
|
@@ -5999,6 +6453,7 @@ async function resolveApiKeyToken(call, appId, apiKey, errors = defaultSdkCoreEr
|
|
|
5999
6453
|
createCustomQueriesModule,
|
|
6000
6454
|
createDataSourcesModule,
|
|
6001
6455
|
createEntitiesModule,
|
|
6456
|
+
createFilesModule,
|
|
6002
6457
|
createFunctionsAdminModule,
|
|
6003
6458
|
createFunctionsModule,
|
|
6004
6459
|
createImportsModule,
|