@mitralab.io/sdk-core 0.3.0-beta.2 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +173 -7
- package/README.md +11 -4
- package/contracts/README.md +12 -5
- package/contracts/manifest.json +6 -1
- package/contracts/v0.3.1/sdk-parity.json +2902 -0
- package/dist/index.cjs +888 -98
- package/dist/index.d.cts +438 -27
- package/dist/index.d.ts +438 -27
- package/dist/index.js +888 -98
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -120,6 +120,9 @@ function isObject(value) {
|
|
|
120
120
|
function isNullableString(value) {
|
|
121
121
|
return value === null || typeof value === "string";
|
|
122
122
|
}
|
|
123
|
+
function isNonEmptyString(value) {
|
|
124
|
+
return typeof value === "string" && value.length > 0;
|
|
125
|
+
}
|
|
123
126
|
function isNullableBoolean(value) {
|
|
124
127
|
return value === null || typeof value === "boolean";
|
|
125
128
|
}
|
|
@@ -753,6 +756,83 @@ function expectMessageAccepted(value, context, errors = defaultSdkCoreErrorFacto
|
|
|
753
756
|
if (typeof response.messageId !== "string") invalidField(context, "messageId", errors);
|
|
754
757
|
return response;
|
|
755
758
|
}
|
|
759
|
+
function expectEmailTemplate(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
760
|
+
const template = expectObject(value, context, errors);
|
|
761
|
+
if (typeof template.id !== "string") invalidField(context, "id", errors);
|
|
762
|
+
if (!isNonEmptyString(template.type)) invalidField(context, "type", errors);
|
|
763
|
+
if (!isNullableString(template.senderIdentityId)) {
|
|
764
|
+
invalidField(context, "senderIdentityId", errors);
|
|
765
|
+
}
|
|
766
|
+
if (typeof template.subject !== "string") invalidField(context, "subject", errors);
|
|
767
|
+
if (typeof template.htmlBody !== "string") invalidField(context, "htmlBody", errors);
|
|
768
|
+
if (!isNullableString(template.textBody)) invalidField(context, "textBody", errors);
|
|
769
|
+
if (typeof template.platformDefault !== "boolean") {
|
|
770
|
+
invalidField(context, "platformDefault", errors);
|
|
771
|
+
}
|
|
772
|
+
if (typeof template.createdAt !== "string") invalidField(context, "createdAt", errors);
|
|
773
|
+
if (typeof template.updatedAt !== "string") invalidField(context, "updatedAt", errors);
|
|
774
|
+
return template;
|
|
775
|
+
}
|
|
776
|
+
function expectEmailTemplateTypeCatalog(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
777
|
+
const catalog = expectObject(value, context, errors);
|
|
778
|
+
if (!isNonEmptyString(catalog.type)) invalidField(context, "type", errors);
|
|
779
|
+
expectObjectArray(catalog.variables, `${context} variables`, errors).forEach(
|
|
780
|
+
(variable, position) => {
|
|
781
|
+
const variableContext = `${context} variable ${position}`;
|
|
782
|
+
if (typeof variable.name !== "string") invalidField(variableContext, "name", errors);
|
|
783
|
+
if (typeof variable.required !== "boolean") {
|
|
784
|
+
invalidField(variableContext, "required", errors);
|
|
785
|
+
}
|
|
786
|
+
if (!isNullableString(variable.description)) {
|
|
787
|
+
invalidField(variableContext, "description", errors);
|
|
788
|
+
}
|
|
789
|
+
if (!isNullableString(variable.preview)) invalidField(variableContext, "preview", errors);
|
|
790
|
+
}
|
|
791
|
+
);
|
|
792
|
+
return catalog;
|
|
793
|
+
}
|
|
794
|
+
function expectEmailTemplatePreview(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
795
|
+
const preview = expectObject(value, context, errors);
|
|
796
|
+
if (typeof preview.subject !== "string") invalidField(context, "subject", errors);
|
|
797
|
+
if (typeof preview.htmlBody !== "string") invalidField(context, "htmlBody", errors);
|
|
798
|
+
if (!isNullableString(preview.textBody)) invalidField(context, "textBody", errors);
|
|
799
|
+
return preview;
|
|
800
|
+
}
|
|
801
|
+
function expectEmailSender(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
802
|
+
const sender = expectObject(value, context, errors);
|
|
803
|
+
if (typeof sender.id !== "string") invalidField(context, "id", errors);
|
|
804
|
+
if (typeof sender.email !== "string") invalidField(context, "email", errors);
|
|
805
|
+
if (typeof sender.displayName !== "string") invalidField(context, "displayName", errors);
|
|
806
|
+
if (!isNonEmptyString(sender.status)) invalidField(context, "status", errors);
|
|
807
|
+
if (typeof sender.sharedWithCurrentWorkspace !== "boolean") {
|
|
808
|
+
invalidField(context, "sharedWithCurrentWorkspace", errors);
|
|
809
|
+
}
|
|
810
|
+
if (typeof sender.ownerConfirmationPending !== "boolean") {
|
|
811
|
+
invalidField(context, "ownerConfirmationPending", errors);
|
|
812
|
+
}
|
|
813
|
+
if (typeof sender.createdAt !== "string") invalidField(context, "createdAt", errors);
|
|
814
|
+
if (typeof sender.updatedAt !== "string") invalidField(context, "updatedAt", errors);
|
|
815
|
+
return sender;
|
|
816
|
+
}
|
|
817
|
+
function expectEmailSettings(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
818
|
+
const settings = expectObject(value, context, errors);
|
|
819
|
+
if (typeof settings.appId !== "string") invalidField(context, "appId", errors);
|
|
820
|
+
if (!isNullableString(settings.senderIdentityId)) {
|
|
821
|
+
invalidField(context, "senderIdentityId", errors);
|
|
822
|
+
}
|
|
823
|
+
if (!isNullableString(settings.displayName)) invalidField(context, "displayName", errors);
|
|
824
|
+
if (!isNullableString(settings.replyTo)) invalidField(context, "replyTo", errors);
|
|
825
|
+
if (typeof settings.ownTemplateSendsFromBrand !== "boolean") {
|
|
826
|
+
invalidField(context, "ownTemplateSendsFromBrand", errors);
|
|
827
|
+
}
|
|
828
|
+
const senderContext = `${context} effectiveSender`;
|
|
829
|
+
const sender = expectObject(settings.effectiveSender, senderContext, errors);
|
|
830
|
+
if (typeof sender.email !== "string") invalidField(senderContext, "email", errors);
|
|
831
|
+
if (!isNullableString(sender.displayName)) invalidField(senderContext, "displayName", errors);
|
|
832
|
+
if (!isNonEmptyString(sender.source)) invalidField(senderContext, "source", errors);
|
|
833
|
+
if (!isNullableString(sender.reason)) invalidField(senderContext, "reason", errors);
|
|
834
|
+
return settings;
|
|
835
|
+
}
|
|
756
836
|
function expectAgentDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
757
837
|
const agent = expectObject(value, context, errors);
|
|
758
838
|
if (typeof agent.id !== "string") invalidField(context, "id", errors);
|
|
@@ -1014,7 +1094,8 @@ function expectAgentTaskChannel(value, context, errors = defaultSdkCoreErrorFact
|
|
|
1014
1094
|
if (typeof channel.wsUrl !== "string" || !channel.wsUrl) invalidField(context, "wsUrl", errors);
|
|
1015
1095
|
return {
|
|
1016
1096
|
wsUrl: channel.wsUrl,
|
|
1017
|
-
lastSequence: isInteger(channel.lastSequence) && channel.lastSequence > 0 ? channel.lastSequence : 0
|
|
1097
|
+
lastSequence: isInteger(channel.lastSequence) && channel.lastSequence > 0 ? channel.lastSequence : 0,
|
|
1098
|
+
...isInteger(channel.boxLog) ? { boxLog: channel.boxLog } : {}
|
|
1018
1099
|
};
|
|
1019
1100
|
}
|
|
1020
1101
|
function expectAgentMessage(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
@@ -1126,6 +1207,14 @@ function expectCredentialUsage(value, context, errors = defaultSdkCoreErrorFacto
|
|
|
1126
1207
|
}
|
|
1127
1208
|
return usage;
|
|
1128
1209
|
}
|
|
1210
|
+
function expectAgentReadyProvider(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
1211
|
+
const entry = expectObject(value, context, errors);
|
|
1212
|
+
if (typeof entry.provider !== "string") invalidField(context, "provider", errors);
|
|
1213
|
+
if (!isNullableString(entry.providerName)) invalidField(context, "providerName", errors);
|
|
1214
|
+
expectObjectArray(entry.models, `${context} models`, errors, expectAgentModel);
|
|
1215
|
+
if (entry.usage !== null) expectCredentialUsage(entry.usage, `${context} usage`, errors);
|
|
1216
|
+
return entry;
|
|
1217
|
+
}
|
|
1129
1218
|
var CREDENTIAL_USAGE_NOT_FOUND = "CREDENTIAL_USAGE_NOT_FOUND";
|
|
1130
1219
|
async function readCredentialUsage(request, context, errors = defaultSdkCoreErrorFactory) {
|
|
1131
1220
|
let value;
|
|
@@ -1414,6 +1503,17 @@ function createAgentCredentialsModule(transport, errors = defaultSdkCoreErrorFac
|
|
|
1414
1503
|
expectAgentModel
|
|
1415
1504
|
);
|
|
1416
1505
|
},
|
|
1506
|
+
async providers(agentId, options) {
|
|
1507
|
+
return expectObjectArray(
|
|
1508
|
+
await transport.request("/api/v1/models/providers", {
|
|
1509
|
+
method: "GET",
|
|
1510
|
+
params: { agentId, ...scopeParams(options).params }
|
|
1511
|
+
}),
|
|
1512
|
+
"Ready provider response",
|
|
1513
|
+
errors,
|
|
1514
|
+
expectAgentReadyProvider
|
|
1515
|
+
);
|
|
1516
|
+
},
|
|
1417
1517
|
async usage(provider, options) {
|
|
1418
1518
|
return readCredentialUsage(
|
|
1419
1519
|
transport.request(`/api/v1/credentials/${providerSegment(provider)}/usage`, {
|
|
@@ -1686,7 +1786,13 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
|
|
|
1686
1786
|
const page = expectPage(
|
|
1687
1787
|
await transport.request(`${path(id)}/messages`, {
|
|
1688
1788
|
method: "GET",
|
|
1689
|
-
params: {
|
|
1789
|
+
params: {
|
|
1790
|
+
page: options.page,
|
|
1791
|
+
size: options.size,
|
|
1792
|
+
sort: options.sort,
|
|
1793
|
+
kinds: options.kinds,
|
|
1794
|
+
before: options.before
|
|
1795
|
+
}
|
|
1690
1796
|
}),
|
|
1691
1797
|
context,
|
|
1692
1798
|
errors
|
|
@@ -2924,7 +3030,23 @@ function createMembersModule(transport, errors = defaultSdkCoreErrorFactory) {
|
|
|
2924
3030
|
}
|
|
2925
3031
|
|
|
2926
3032
|
// src/modules/messenger.ts
|
|
2927
|
-
function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
|
|
3033
|
+
function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory, getAppId) {
|
|
3034
|
+
const templatePath = (type) => `/api/v1/email/templates/${encodePathSegment(type, "email template type", errors)}`;
|
|
3035
|
+
const senderPath = (senderId) => `/api/v1/email/identities/${encodePathSegment(senderId, "email sender id", errors)}`;
|
|
3036
|
+
const currentAppId = () => {
|
|
3037
|
+
const appId = getAppId?.();
|
|
3038
|
+
if (!appId) configurationError("An appId is required for app email calls", errors);
|
|
3039
|
+
return appId;
|
|
3040
|
+
};
|
|
3041
|
+
const settingsPath = () => `/api/v1/email/apps/${encodePathSegment(currentAppId(), "app id", errors)}/settings`;
|
|
3042
|
+
const preview = async (type, appId) => expectEmailTemplatePreview(
|
|
3043
|
+
await transport.request(`${templatePath(type)}/preview`, {
|
|
3044
|
+
method: "GET",
|
|
3045
|
+
params: { appId }
|
|
3046
|
+
}),
|
|
3047
|
+
"Email template preview response",
|
|
3048
|
+
errors
|
|
3049
|
+
);
|
|
2928
3050
|
return {
|
|
2929
3051
|
async notify(content) {
|
|
2930
3052
|
return expectMessageAccepted(
|
|
@@ -2945,6 +3067,120 @@ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
|
|
|
2945
3067
|
"Send email response",
|
|
2946
3068
|
errors
|
|
2947
3069
|
);
|
|
3070
|
+
},
|
|
3071
|
+
async listEmailTemplates() {
|
|
3072
|
+
return expectObjectArray(
|
|
3073
|
+
await transport.request("/api/v1/email/templates", {
|
|
3074
|
+
method: "GET",
|
|
3075
|
+
params: { appId: currentAppId() }
|
|
3076
|
+
}),
|
|
3077
|
+
"Email template list response",
|
|
3078
|
+
errors,
|
|
3079
|
+
expectEmailTemplate
|
|
3080
|
+
);
|
|
3081
|
+
},
|
|
3082
|
+
async getEmailTemplateType(type) {
|
|
3083
|
+
return expectEmailTemplateTypeCatalog(
|
|
3084
|
+
await transport.request(
|
|
3085
|
+
`/api/v1/email/template-types/${encodePathSegment(type, "email template type", errors)}`,
|
|
3086
|
+
{ method: "GET" }
|
|
3087
|
+
),
|
|
3088
|
+
"Email template type response",
|
|
3089
|
+
errors
|
|
3090
|
+
);
|
|
3091
|
+
},
|
|
3092
|
+
async getEmailTemplate(type) {
|
|
3093
|
+
return expectEmailTemplate(
|
|
3094
|
+
await transport.request(templatePath(type), {
|
|
3095
|
+
method: "GET",
|
|
3096
|
+
params: { appId: currentAppId() }
|
|
3097
|
+
}),
|
|
3098
|
+
"Email template response",
|
|
3099
|
+
errors
|
|
3100
|
+
);
|
|
3101
|
+
},
|
|
3102
|
+
async upsertEmailTemplate(type, input) {
|
|
3103
|
+
const appId = currentAppId();
|
|
3104
|
+
const template = expectEmailTemplate(
|
|
3105
|
+
await transport.request(templatePath(type), {
|
|
3106
|
+
method: "PUT",
|
|
3107
|
+
body: templateBody(appId, input)
|
|
3108
|
+
}),
|
|
3109
|
+
"Upsert email template response",
|
|
3110
|
+
errors
|
|
3111
|
+
);
|
|
3112
|
+
try {
|
|
3113
|
+
return { template, preview: await preview(type, appId) };
|
|
3114
|
+
} catch (previewError) {
|
|
3115
|
+
return { template, preview: null, previewError };
|
|
3116
|
+
}
|
|
3117
|
+
},
|
|
3118
|
+
async previewEmailTemplate(type) {
|
|
3119
|
+
return preview(type, currentAppId());
|
|
3120
|
+
},
|
|
3121
|
+
async deleteEmailTemplate(type) {
|
|
3122
|
+
expectEmpty(
|
|
3123
|
+
await transport.request(templatePath(type), {
|
|
3124
|
+
method: "DELETE",
|
|
3125
|
+
params: { appId: currentAppId() }
|
|
3126
|
+
}),
|
|
3127
|
+
"Delete email template response",
|
|
3128
|
+
errors
|
|
3129
|
+
);
|
|
3130
|
+
},
|
|
3131
|
+
async listEmailSenders() {
|
|
3132
|
+
return expectObjectArray(
|
|
3133
|
+
await transport.request("/api/v1/email/identities/workspace", { method: "GET" }),
|
|
3134
|
+
"Email sender list response",
|
|
3135
|
+
errors,
|
|
3136
|
+
expectEmailSender
|
|
3137
|
+
);
|
|
3138
|
+
},
|
|
3139
|
+
async registerEmailSender(input) {
|
|
3140
|
+
return expectEmailSender(
|
|
3141
|
+
await transport.request("/api/v1/email/identities", {
|
|
3142
|
+
method: "POST",
|
|
3143
|
+
body: { email: input.email, displayName: input.displayName }
|
|
3144
|
+
}),
|
|
3145
|
+
"Register email sender response",
|
|
3146
|
+
errors
|
|
3147
|
+
);
|
|
3148
|
+
},
|
|
3149
|
+
async resendEmailSenderVerification(senderId) {
|
|
3150
|
+
return expectEmailSender(
|
|
3151
|
+
await transport.request(`${senderPath(senderId)}/resend-verification`, {
|
|
3152
|
+
method: "POST"
|
|
3153
|
+
}),
|
|
3154
|
+
"Resend email sender verification response",
|
|
3155
|
+
errors
|
|
3156
|
+
);
|
|
3157
|
+
},
|
|
3158
|
+
async confirmEmailSender(senderId, code) {
|
|
3159
|
+
return expectEmailSender(
|
|
3160
|
+
await transport.request(`${senderPath(senderId)}/confirm`, {
|
|
3161
|
+
method: "POST",
|
|
3162
|
+
body: { code }
|
|
3163
|
+
}),
|
|
3164
|
+
"Confirm email sender response",
|
|
3165
|
+
errors
|
|
3166
|
+
);
|
|
3167
|
+
},
|
|
3168
|
+
async getEmailSettings() {
|
|
3169
|
+
return expectEmailSettings(
|
|
3170
|
+
await transport.request(settingsPath(), { method: "GET" }),
|
|
3171
|
+
"Email settings response",
|
|
3172
|
+
errors
|
|
3173
|
+
);
|
|
3174
|
+
},
|
|
3175
|
+
async updateEmailSettings(input) {
|
|
3176
|
+
return expectEmailSettings(
|
|
3177
|
+
await transport.request(settingsPath(), {
|
|
3178
|
+
method: "PUT",
|
|
3179
|
+
body: settingsBody(input)
|
|
3180
|
+
}),
|
|
3181
|
+
"Update email settings response",
|
|
3182
|
+
errors
|
|
3183
|
+
);
|
|
2948
3184
|
}
|
|
2949
3185
|
};
|
|
2950
3186
|
}
|
|
@@ -2960,6 +3196,21 @@ function rawEmailPayload(input) {
|
|
|
2960
3196
|
...input.text === void 0 ? {} : { text: input.text }
|
|
2961
3197
|
};
|
|
2962
3198
|
}
|
|
3199
|
+
function templateBody(appId, input) {
|
|
3200
|
+
return {
|
|
3201
|
+
appId,
|
|
3202
|
+
subject: input.subject,
|
|
3203
|
+
htmlBody: input.htmlBody,
|
|
3204
|
+
...input.textBody === void 0 ? {} : { textBody: input.textBody }
|
|
3205
|
+
};
|
|
3206
|
+
}
|
|
3207
|
+
function settingsBody(input) {
|
|
3208
|
+
return {
|
|
3209
|
+
...input.senderIdentityId === void 0 ? {} : { senderIdentityId: input.senderIdentityId },
|
|
3210
|
+
...input.displayName === void 0 ? {} : { displayName: input.displayName },
|
|
3211
|
+
...input.replyTo === void 0 ? {} : { replyTo: input.replyTo }
|
|
3212
|
+
};
|
|
3213
|
+
}
|
|
2963
3214
|
|
|
2964
3215
|
// src/modules/publicFunctions.ts
|
|
2965
3216
|
function createPublicFunctionsModule(transport, errors = defaultSdkCoreErrorFactory) {
|
|
@@ -3277,7 +3528,7 @@ function createSdkCore(options) {
|
|
|
3277
3528
|
integrationResources: createIntegrationResourcesModule(options.transports.integration, errors),
|
|
3278
3529
|
integrationTemplates: createIntegrationTemplatesModule(options.transports.integration, errors),
|
|
3279
3530
|
members,
|
|
3280
|
-
messenger: createMessengerModule(messengerTransport, errors),
|
|
3531
|
+
messenger: createMessengerModule(messengerTransport, errors, options.getAppId),
|
|
3281
3532
|
publicFunctions: createPublicFunctionsModule(options.transports.publicFunctions, errors),
|
|
3282
3533
|
queries: createQueriesModule(options.transports.dataManager, errors),
|
|
3283
3534
|
sql: createSqlModule(options.transports.dataManager, errors),
|
|
@@ -3318,7 +3569,7 @@ function newClientMessageId() {
|
|
|
3318
3569
|
}
|
|
3319
3570
|
function admissionFor(link, event) {
|
|
3320
3571
|
const payload = asObject(event.payload);
|
|
3321
|
-
if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0)) {
|
|
3572
|
+
if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0 || payload?.command !== void 0)) {
|
|
3322
3573
|
return void 0;
|
|
3323
3574
|
}
|
|
3324
3575
|
const id = event.type === "stepStart" ? asObject(payload?.lifecycle)?.clientMessageId : payload?.clientMessageId;
|
|
@@ -3364,6 +3615,14 @@ function boxAddress(wsUrl) {
|
|
|
3364
3615
|
const url = new URL(wsUrl);
|
|
3365
3616
|
return `${url.origin}${url.pathname}`;
|
|
3366
3617
|
}
|
|
3618
|
+
function helloOf(event) {
|
|
3619
|
+
if (event.type !== "hello") return void 0;
|
|
3620
|
+
const payload = asObject(event.payload);
|
|
3621
|
+
const threadId = payload?.threadId;
|
|
3622
|
+
const lastSequence = payload?.lastSequence;
|
|
3623
|
+
if (typeof threadId !== "string" || typeof lastSequence !== "number") return void 0;
|
|
3624
|
+
return { threadId, lastSequence };
|
|
3625
|
+
}
|
|
3367
3626
|
function boxRoute(wsUrl, route) {
|
|
3368
3627
|
const url = new URL(wsUrl);
|
|
3369
3628
|
url.protocol = url.protocol === "wss:" ? "https:" : "http:";
|
|
@@ -3457,8 +3716,7 @@ var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
|
|
|
3457
3716
|
"steer",
|
|
3458
3717
|
"textDelta",
|
|
3459
3718
|
"thinking",
|
|
3460
|
-
"toolCall"
|
|
3461
|
-
"toolResult"
|
|
3719
|
+
"toolCall"
|
|
3462
3720
|
]);
|
|
3463
3721
|
var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
|
|
3464
3722
|
function turnAfter(event, inTurn) {
|
|
@@ -3471,6 +3729,12 @@ function turnAfter(event, inTurn) {
|
|
|
3471
3729
|
}
|
|
3472
3730
|
return inTurn;
|
|
3473
3731
|
}
|
|
3732
|
+
function followsTurn(link, event) {
|
|
3733
|
+
if (event.type === "messageQueued") return false;
|
|
3734
|
+
if (event.type !== "stepFinish" && event.type !== "error") return true;
|
|
3735
|
+
const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
|
|
3736
|
+
return typeof turnId !== "string" || link.turnId === void 0 || turnId === link.turnId;
|
|
3737
|
+
}
|
|
3474
3738
|
function lostTurnFrame(turnId) {
|
|
3475
3739
|
return {
|
|
3476
3740
|
type: "stepFinish",
|
|
@@ -3542,7 +3806,7 @@ var AgentDirectChannel = class {
|
|
|
3542
3806
|
enabled() {
|
|
3543
3807
|
return this.options.apiUrl !== void 0 && this.tasks.channel !== void 0;
|
|
3544
3808
|
}
|
|
3545
|
-
async open(taskId, observer, signal, transport) {
|
|
3809
|
+
async open(taskId, observer, signal, transport, historyCursor) {
|
|
3546
3810
|
if (!this.enabled()) return this.fallback.open(taskId, observer, signal, transport);
|
|
3547
3811
|
const mode = this.modeFor(transport);
|
|
3548
3812
|
const answer = mode ? await this.requestChannel(taskId) : { declined: { reason: transport === "websocket" ? "websocket" : "http_unsupported" } };
|
|
@@ -3552,7 +3816,7 @@ var AgentDirectChannel = class {
|
|
|
3552
3816
|
return this.fallback.open(taskId, observer, signal, transport);
|
|
3553
3817
|
}
|
|
3554
3818
|
try {
|
|
3555
|
-
return await this.openDirect(taskId, mode, answer, observer, signal);
|
|
3819
|
+
return await this.openDirect(taskId, mode, answer, observer, signal, historyCursor);
|
|
3556
3820
|
} catch (error) {
|
|
3557
3821
|
if (signal?.aborted) throw error;
|
|
3558
3822
|
observer.onEvent(
|
|
@@ -3677,26 +3941,36 @@ var AgentDirectChannel = class {
|
|
|
3677
3941
|
* only when the redial gives up, when the Copilot no longer offers the box, or when there is
|
|
3678
3942
|
* no turn to resume: dialing an idle box again would wake it for nobody.
|
|
3679
3943
|
*
|
|
3680
|
-
* Opening
|
|
3681
|
-
*
|
|
3682
|
-
*
|
|
3944
|
+
* Opening asks for the replay from where the session's history ends, with the same request the
|
|
3945
|
+
* redial makes: what the history has, the replay does not repeat, and what the Copilot has not
|
|
3946
|
+
* recorded yet (the turn running now, or one it is still behind on) comes in the replay before
|
|
3947
|
+
* any live frame. When the Copilot says the box log is another one than the history's newest,
|
|
3948
|
+
* nothing of it is in the history and the replay starts at its beginning. A history with no
|
|
3949
|
+
* box sequence asks for nothing, and the open starts at the sequence the Copilot reported.
|
|
3683
3950
|
*/
|
|
3684
|
-
async openDirect(taskId, mode, channel, observer, signal) {
|
|
3951
|
+
async openDirect(taskId, mode, channel, observer, signal, historyCursor) {
|
|
3685
3952
|
const link = { wire: null, inTurn: false, turnId: void 0, admissions: [] };
|
|
3686
3953
|
let box = boxAddress(channel.wsUrl);
|
|
3687
|
-
let
|
|
3954
|
+
let thread;
|
|
3955
|
+
const otherLog = historyCursor?.boxLog !== void 0 && channel.boxLog !== void 0 && historyCursor.boxLog !== channel.boxLog;
|
|
3956
|
+
const historyFrom = historyCursor === void 0 ? void 0 : otherLog ? 0 : historyCursor.sequence;
|
|
3957
|
+
let cursor = historyFrom ?? channel.lastSequence;
|
|
3688
3958
|
const abort = new AbortController();
|
|
3689
3959
|
const onAbort = () => abort.abort(signal?.reason);
|
|
3690
3960
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3691
3961
|
const onFrame = (event) => {
|
|
3962
|
+
const hello = helloOf(event);
|
|
3963
|
+
if (hello) thread = hello.threadId;
|
|
3692
3964
|
if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
|
|
3693
3965
|
if (isSubagentFrame(event)) {
|
|
3694
3966
|
observer.onEvent(event);
|
|
3695
3967
|
return;
|
|
3696
3968
|
}
|
|
3697
|
-
|
|
3698
|
-
|
|
3699
|
-
|
|
3969
|
+
if (followsTurn(link, event)) {
|
|
3970
|
+
const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
|
|
3971
|
+
if (typeof turnId === "string" && event.type !== "toolResult") link.turnId = turnId;
|
|
3972
|
+
link.inTurn = turnAfter(event, link.inTurn);
|
|
3973
|
+
}
|
|
3700
3974
|
observer.onEvent(event);
|
|
3701
3975
|
if (event.type === "stepStart") admissionFor(link, event)?.settle(true);
|
|
3702
3976
|
else if (event.type === "error") admissionFor(link, event)?.settle(false);
|
|
@@ -3717,13 +3991,21 @@ var AgentDirectChannel = class {
|
|
|
3717
3991
|
onFrame,
|
|
3718
3992
|
onLost,
|
|
3719
3993
|
replayFrom: (next) => {
|
|
3720
|
-
const
|
|
3721
|
-
|
|
3722
|
-
|
|
3723
|
-
|
|
3724
|
-
|
|
3725
|
-
|
|
3726
|
-
|
|
3994
|
+
const decide = (hello) => {
|
|
3995
|
+
const nextBox = boxAddress(next.wsUrl);
|
|
3996
|
+
const zeroed = next.lastSequence === 0 && cursor > 0;
|
|
3997
|
+
const otherBox = hello !== void 0 && (hello.threadId !== thread || hello.lastSequence < cursor);
|
|
3998
|
+
if (nextBox === box && !zeroed && !otherBox) return cursor;
|
|
3999
|
+
if (link.inTurn) onFrame(lostTurnFrame(link.turnId));
|
|
4000
|
+
box = nextBox;
|
|
4001
|
+
if (mode === "websocket") {
|
|
4002
|
+
cursor = 0;
|
|
4003
|
+
return 0;
|
|
4004
|
+
}
|
|
4005
|
+
cursor = next.lastSequence;
|
|
4006
|
+
return void 0;
|
|
4007
|
+
};
|
|
4008
|
+
return mode === "websocket" && thread !== void 0 ? decide : decide(void 0);
|
|
3727
4009
|
}
|
|
3728
4010
|
}).then((outcome) => {
|
|
3729
4011
|
if (outcome instanceof Error) for (const pending of link.admissions) pending.fail(outcome);
|
|
@@ -3733,11 +4015,17 @@ var AgentDirectChannel = class {
|
|
|
3733
4015
|
}
|
|
3734
4016
|
});
|
|
3735
4017
|
};
|
|
4018
|
+
const afterHello = (hello) => {
|
|
4019
|
+
if (hello !== void 0 && hello.lastSequence < cursor) cursor = 0;
|
|
4020
|
+
return cursor;
|
|
4021
|
+
};
|
|
4022
|
+
const replay = historyFrom === void 0 ? {} : mode === "websocket" ? { replayAfterHello: afterHello } : { replayFrom: historyFrom };
|
|
3736
4023
|
try {
|
|
3737
4024
|
link.wire = await this.connect(taskId, mode, channel, {
|
|
3738
4025
|
signal: abort.signal,
|
|
3739
4026
|
onFrame,
|
|
3740
|
-
onLost
|
|
4027
|
+
onLost,
|
|
4028
|
+
...replay
|
|
3741
4029
|
});
|
|
3742
4030
|
} catch (error) {
|
|
3743
4031
|
signal?.removeEventListener("abort", onAbort);
|
|
@@ -3820,7 +4108,8 @@ var AgentDirectChannel = class {
|
|
|
3820
4108
|
onFrame: handlers.onFrame,
|
|
3821
4109
|
onLost: handlers.onLost,
|
|
3822
4110
|
signal,
|
|
3823
|
-
...replayFrom ===
|
|
4111
|
+
...typeof replayFrom === "function" ? { replayAfterHello: replayFrom } : {},
|
|
4112
|
+
...typeof replayFrom === "number" ? { replayFrom } : {}
|
|
3824
4113
|
});
|
|
3825
4114
|
return { kind: "wire", wire };
|
|
3826
4115
|
} catch (error) {
|
|
@@ -3969,6 +4258,7 @@ var AgentDirectChannel = class {
|
|
|
3969
4258
|
const Socket = this.webSocket();
|
|
3970
4259
|
if (!Socket) return Promise.reject(new TypeError("WebSocket is not available."));
|
|
3971
4260
|
const { signal, replayFrom } = options;
|
|
4261
|
+
let replayAfterHello = options.replayAfterHello;
|
|
3972
4262
|
return new Promise((resolve, reject) => {
|
|
3973
4263
|
const socket = new Socket(url);
|
|
3974
4264
|
let opened = false;
|
|
@@ -4051,7 +4341,13 @@ var AgentDirectChannel = class {
|
|
|
4051
4341
|
handlers.onmessage = (message) => {
|
|
4052
4342
|
touch();
|
|
4053
4343
|
const event = parseEvent(message.data);
|
|
4054
|
-
if (event)
|
|
4344
|
+
if (!event) return;
|
|
4345
|
+
if (replayAfterHello) {
|
|
4346
|
+
const fromSequence = replayAfterHello(helloOf(event));
|
|
4347
|
+
replayAfterHello = void 0;
|
|
4348
|
+
if (fromSequence !== void 0) send(JSON.stringify({ type: "replay", fromSequence }));
|
|
4349
|
+
}
|
|
4350
|
+
options.onFrame(asDelta(event));
|
|
4055
4351
|
};
|
|
4056
4352
|
handlers.onclose = (event) => {
|
|
4057
4353
|
clearTimeout(timer);
|
|
@@ -4120,14 +4416,44 @@ function messageInput(prompt, options) {
|
|
|
4120
4416
|
content: prompt,
|
|
4121
4417
|
...options.agentType ? { agentType: options.agentType } : {},
|
|
4122
4418
|
...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
|
|
4123
|
-
mode:
|
|
4419
|
+
...options.mode ? { mode: options.mode } : {}
|
|
4420
|
+
};
|
|
4421
|
+
}
|
|
4422
|
+
function backgroundTasksOf(value) {
|
|
4423
|
+
if (!Array.isArray(value)) return [];
|
|
4424
|
+
return value.flatMap((entry) => {
|
|
4425
|
+
const task = asObject2(entry);
|
|
4426
|
+
if (typeof task?.taskId !== "string" || typeof task.kind !== "string") return [];
|
|
4427
|
+
return [
|
|
4428
|
+
{
|
|
4429
|
+
taskId: task.taskId,
|
|
4430
|
+
kind: task.kind,
|
|
4431
|
+
...typeof task.description === "string" ? { description: task.description } : {},
|
|
4432
|
+
...typeof task.childThreadId === "string" ? { childThreadId: task.childThreadId } : {}
|
|
4433
|
+
}
|
|
4434
|
+
];
|
|
4435
|
+
});
|
|
4436
|
+
}
|
|
4437
|
+
function pieceIdentityOf(event, payload) {
|
|
4438
|
+
const turnId = asObject2(payload?.lifecycle)?.turnId;
|
|
4439
|
+
return {
|
|
4440
|
+
...sequenceOf(event),
|
|
4441
|
+
...typeof payload?.itemId === "string" ? { itemId: payload.itemId } : {},
|
|
4442
|
+
...typeof turnId === "string" ? { turnId } : {}
|
|
4124
4443
|
};
|
|
4125
4444
|
}
|
|
4126
|
-
function
|
|
4445
|
+
function itemDeltaOf(payload) {
|
|
4446
|
+
return typeof payload?.itemDelta === "string" ? { itemDelta: payload.itemDelta } : {};
|
|
4447
|
+
}
|
|
4448
|
+
function sequenceOf(event) {
|
|
4449
|
+
return typeof event.sequence === "number" ? { sequence: event.sequence } : {};
|
|
4450
|
+
}
|
|
4451
|
+
function toolEventOf(event, payload, phase) {
|
|
4127
4452
|
return {
|
|
4128
4453
|
tool: typeof payload?.name === "string" ? payload.name : "",
|
|
4129
4454
|
phase,
|
|
4130
|
-
timestamp,
|
|
4455
|
+
timestamp: event.timestamp,
|
|
4456
|
+
...pieceIdentityOf(event, payload),
|
|
4131
4457
|
...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
|
|
4132
4458
|
...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
|
|
4133
4459
|
...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
|
|
@@ -4139,7 +4465,68 @@ function epochOf(value) {
|
|
|
4139
4465
|
const parsed = Date.parse(value);
|
|
4140
4466
|
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
4141
4467
|
}
|
|
4468
|
+
function timelineIdentityOf(message) {
|
|
4469
|
+
return {
|
|
4470
|
+
...typeof message.sequence === "number" ? { sequence: message.sequence } : {},
|
|
4471
|
+
...typeof message.lastSequence === "number" ? { lastSequence: message.lastSequence } : {},
|
|
4472
|
+
...typeof message.boxLog === "number" ? { boxLog: message.boxLog } : {},
|
|
4473
|
+
...typeof message.itemId === "string" ? { itemId: message.itemId } : {},
|
|
4474
|
+
...typeof message.reason === "string" ? { reason: message.reason } : {}
|
|
4475
|
+
};
|
|
4476
|
+
}
|
|
4477
|
+
function historyCursorOf(history) {
|
|
4478
|
+
const newest = [...history].reverse().find((item) => typeof item.sequence === "number");
|
|
4479
|
+
if (!newest) return void 0;
|
|
4480
|
+
let sequence = 0;
|
|
4481
|
+
for (const item of history) {
|
|
4482
|
+
if (item.boxLog === newest.boxLog && typeof item.sequence === "number") {
|
|
4483
|
+
sequence = Math.max(sequence, item.lastSequence ?? item.sequence);
|
|
4484
|
+
}
|
|
4485
|
+
}
|
|
4486
|
+
return { sequence, ...newest.boxLog === void 0 ? {} : { boxLog: newest.boxLog } };
|
|
4487
|
+
}
|
|
4488
|
+
function hasOlderRows(page) {
|
|
4489
|
+
return page.page.totalPages > page.page.number + 1;
|
|
4490
|
+
}
|
|
4491
|
+
function isChatRow(message) {
|
|
4492
|
+
return (message.type === "TEXT" || message.type === "ERROR" || message.type === "TOOL_USE") && message.parentToolId === void 0;
|
|
4493
|
+
}
|
|
4494
|
+
var REQUEST_ROW_KINDS = {
|
|
4495
|
+
APPROVAL: "approval",
|
|
4496
|
+
USER_INPUT_REQUEST: "userInputRequest"
|
|
4497
|
+
};
|
|
4498
|
+
function parseJson(text) {
|
|
4499
|
+
try {
|
|
4500
|
+
return JSON.parse(text);
|
|
4501
|
+
} catch {
|
|
4502
|
+
return void 0;
|
|
4503
|
+
}
|
|
4504
|
+
}
|
|
4142
4505
|
function toAgentTimelineItem(message) {
|
|
4506
|
+
if (message.type === "REASONING") {
|
|
4507
|
+
return {
|
|
4508
|
+
id: message.id,
|
|
4509
|
+
kind: "reasoning",
|
|
4510
|
+
text: message.content,
|
|
4511
|
+
at: message.createdAt,
|
|
4512
|
+
...timelineIdentityOf(message),
|
|
4513
|
+
...parentToolIdOf(message.parentToolId)
|
|
4514
|
+
};
|
|
4515
|
+
}
|
|
4516
|
+
const requestKind = REQUEST_ROW_KINDS[message.type];
|
|
4517
|
+
if (requestKind) {
|
|
4518
|
+
const payload = asObject2(parseJson(message.content));
|
|
4519
|
+
if (payload) {
|
|
4520
|
+
return {
|
|
4521
|
+
id: message.id,
|
|
4522
|
+
kind: requestKind,
|
|
4523
|
+
payload,
|
|
4524
|
+
at: message.createdAt,
|
|
4525
|
+
...timelineIdentityOf(message),
|
|
4526
|
+
...parentToolIdOf(message.parentToolId)
|
|
4527
|
+
};
|
|
4528
|
+
}
|
|
4529
|
+
}
|
|
4143
4530
|
if (message.type === "TOOL_USE") {
|
|
4144
4531
|
try {
|
|
4145
4532
|
const payload = JSON.parse(message.content);
|
|
@@ -4150,11 +4537,14 @@ function toAgentTimelineItem(message) {
|
|
|
4150
4537
|
tool: {
|
|
4151
4538
|
tool: typeof payload.name === "string" ? payload.name : "",
|
|
4152
4539
|
...typeof payload.toolId === "string" ? { toolId: payload.toolId } : {},
|
|
4540
|
+
...parentToolIdOf(payload.parentToolId ?? message.parentToolId),
|
|
4153
4541
|
...payload.input !== void 0 ? { input: payload.input } : {},
|
|
4154
4542
|
...payload.content !== void 0 ? { content: payload.content } : payload.output !== void 0 ? { content: payload.output } : {},
|
|
4155
4543
|
phase: payload.output !== void 0 || payload.content !== void 0 ? "result" : "call"
|
|
4156
4544
|
},
|
|
4157
|
-
at: message.createdAt
|
|
4545
|
+
at: message.createdAt,
|
|
4546
|
+
...timelineIdentityOf(message),
|
|
4547
|
+
...asObject2(message.subagent) ? { subagent: message.subagent } : {}
|
|
4158
4548
|
};
|
|
4159
4549
|
}
|
|
4160
4550
|
} catch {
|
|
@@ -4165,9 +4555,18 @@ function toAgentTimelineItem(message) {
|
|
|
4165
4555
|
kind: message.sender === "USER" ? "user" : "agent",
|
|
4166
4556
|
text: message.content,
|
|
4167
4557
|
at: message.createdAt,
|
|
4168
|
-
...message.usage ? { usage: message.usage } : {}
|
|
4558
|
+
...message.usage ? { usage: message.usage } : {},
|
|
4559
|
+
...timelineIdentityOf(message),
|
|
4560
|
+
...typeof message.clientMessageId === "string" ? { clientMessageId: message.clientMessageId } : {},
|
|
4561
|
+
...parentToolIdOf(message.parentToolId)
|
|
4169
4562
|
};
|
|
4170
4563
|
}
|
|
4564
|
+
function liveAtOf(event) {
|
|
4565
|
+
return new Date(typeof event.timestamp === "number" ? event.timestamp : Date.now()).toISOString();
|
|
4566
|
+
}
|
|
4567
|
+
function parentToolIdOf(value) {
|
|
4568
|
+
return typeof value === "string" ? { parentToolId: value } : {};
|
|
4569
|
+
}
|
|
4171
4570
|
function createAgentTaskSessionManager(options) {
|
|
4172
4571
|
const sessions = /* @__PURE__ */ new Map();
|
|
4173
4572
|
const channel = new AgentDirectChannel(options.tasks, options.eventSource, options.directChannel);
|
|
@@ -4260,6 +4659,22 @@ var CoreAgentTaskSession = class {
|
|
|
4260
4659
|
openingAwaitsStart = false;
|
|
4261
4660
|
turnBaselineIds = /* @__PURE__ */ new Set();
|
|
4262
4661
|
subagentsById = /* @__PURE__ */ new Map();
|
|
4662
|
+
subagentSequences = /* @__PURE__ */ new Map();
|
|
4663
|
+
queueItems = [];
|
|
4664
|
+
_backgroundTasks = [];
|
|
4665
|
+
/** The text of each message this session sent, by its `clientMessageId`. */
|
|
4666
|
+
sentTexts = /* @__PURE__ */ new Map();
|
|
4667
|
+
// Messages of this session `accepted` was already emitted for. The frame that names a message
|
|
4668
|
+
// emits it in its place in the stream, so a turn delivered in one tick gives the same events as
|
|
4669
|
+
// one spaced out; the admission the send awaits only covers a box or a Copilot that names none.
|
|
4670
|
+
acceptedIds = [];
|
|
4671
|
+
// Taken by the first channel of `session({ taskId })`; no later channel asks for a replay.
|
|
4672
|
+
openingCursor;
|
|
4673
|
+
historyLimit;
|
|
4674
|
+
_hasOlder = false;
|
|
4675
|
+
// Moves whenever `history` is replaced, so a `loadOlder` still reading drops what it read.
|
|
4676
|
+
historyGeneration = 0;
|
|
4677
|
+
olderRead = null;
|
|
4263
4678
|
get taskId() {
|
|
4264
4679
|
return this._taskId;
|
|
4265
4680
|
}
|
|
@@ -4279,19 +4694,18 @@ var CoreAgentTaskSession = class {
|
|
|
4279
4694
|
return this._content;
|
|
4280
4695
|
}
|
|
4281
4696
|
get queue() {
|
|
4282
|
-
return [];
|
|
4697
|
+
return [...this.queueItems];
|
|
4283
4698
|
}
|
|
4284
4699
|
get subagents() {
|
|
4285
4700
|
return [...this.subagentsById.values()];
|
|
4286
4701
|
}
|
|
4287
4702
|
send(prompt, options = {}) {
|
|
4288
4703
|
this.requireOpen();
|
|
4289
|
-
if (!prompt.trim()) return;
|
|
4290
|
-
if (this.isBusy())
|
|
4291
|
-
|
|
4292
|
-
|
|
4293
|
-
|
|
4294
|
-
this.startDispatch(prompt, options);
|
|
4704
|
+
if (!prompt.trim()) return void 0;
|
|
4705
|
+
if (this.isBusy()) return this.steer(prompt, options);
|
|
4706
|
+
const clientMessageId = newClientMessageId();
|
|
4707
|
+
this.startDispatch(prompt, options, clientMessageId);
|
|
4708
|
+
return clientMessageId;
|
|
4295
4709
|
}
|
|
4296
4710
|
sendAndWait(prompt, options = {}) {
|
|
4297
4711
|
this.requireOpen();
|
|
@@ -4300,13 +4714,14 @@ var CoreAgentTaskSession = class {
|
|
|
4300
4714
|
if (waiter.settled) return waiter.promise;
|
|
4301
4715
|
const sendOptions = {
|
|
4302
4716
|
...options.agentType ? { agentType: options.agentType } : {},
|
|
4303
|
-
...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
|
|
4717
|
+
...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
|
|
4718
|
+
...options.mode ? { mode: options.mode } : {}
|
|
4304
4719
|
};
|
|
4305
4720
|
if (this.isBusy()) {
|
|
4306
4721
|
this.steer(prompt, sendOptions, waiter);
|
|
4307
4722
|
return waiter.promise;
|
|
4308
4723
|
}
|
|
4309
|
-
this.startDispatch(prompt, sendOptions, waiter);
|
|
4724
|
+
this.startDispatch(prompt, sendOptions, newClientMessageId(), waiter);
|
|
4310
4725
|
return waiter.promise;
|
|
4311
4726
|
}
|
|
4312
4727
|
async cancel() {
|
|
@@ -4353,18 +4768,91 @@ var CoreAgentTaskSession = class {
|
|
|
4353
4768
|
if (!this._taskId) return [];
|
|
4354
4769
|
const page = await this.dependencies.tasks.listMessages(this._taskId, {
|
|
4355
4770
|
...options.limit !== void 0 ? { size: options.limit } : {},
|
|
4356
|
-
sort: "createdAt,desc"
|
|
4771
|
+
sort: "createdAt,desc",
|
|
4772
|
+
kinds: "all"
|
|
4357
4773
|
});
|
|
4358
|
-
this.
|
|
4774
|
+
this.historyLimit = options.limit;
|
|
4775
|
+
this.replaceHistory(page);
|
|
4359
4776
|
const history = this.history;
|
|
4360
4777
|
this.emit("historyLoaded", { history });
|
|
4361
4778
|
return history;
|
|
4362
4779
|
}
|
|
4363
|
-
|
|
4780
|
+
get hasOlder() {
|
|
4781
|
+
return this._hasOlder;
|
|
4782
|
+
}
|
|
4783
|
+
loadOlder() {
|
|
4784
|
+
if (this.olderRead?.generation !== this.historyGeneration) {
|
|
4785
|
+
const generation = this.historyGeneration;
|
|
4786
|
+
const promise = this.readOlder(generation).finally(() => {
|
|
4787
|
+
if (this.olderRead?.promise === promise) this.olderRead = null;
|
|
4788
|
+
});
|
|
4789
|
+
this.olderRead = { generation, promise };
|
|
4790
|
+
}
|
|
4791
|
+
return this.olderRead.promise;
|
|
4792
|
+
}
|
|
4793
|
+
async readOlder(generation) {
|
|
4794
|
+
const oldest = this._history.find((item) => !item.id.startsWith("live:"));
|
|
4795
|
+
if (!this._taskId || !this._hasOlder || !oldest) return [];
|
|
4796
|
+
let page;
|
|
4797
|
+
try {
|
|
4798
|
+
page = await this.dependencies.tasks.listMessages(this._taskId, {
|
|
4799
|
+
before: oldest.id,
|
|
4800
|
+
...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
|
|
4801
|
+
sort: "createdAt,desc",
|
|
4802
|
+
kinds: "all"
|
|
4803
|
+
});
|
|
4804
|
+
} catch (error) {
|
|
4805
|
+
if (generation !== this.historyGeneration || this.isClosed()) return [];
|
|
4806
|
+
throw error;
|
|
4807
|
+
}
|
|
4808
|
+
if (generation !== this.historyGeneration || this.isClosed()) return [];
|
|
4809
|
+
const older = [...page.content].reverse().map(toAgentTimelineItem);
|
|
4810
|
+
this._hasOlder = hasOlderRows(page);
|
|
4811
|
+
this._history = [...older, ...this._history];
|
|
4812
|
+
this.emit("historyLoaded", { history: this.history });
|
|
4813
|
+
return older;
|
|
4814
|
+
}
|
|
4815
|
+
replaceHistory(page) {
|
|
4816
|
+
this.historyGeneration += 1;
|
|
4817
|
+
this._hasOlder = hasOlderRows(page);
|
|
4818
|
+
this._history = [...page.content].reverse().map(toAgentTimelineItem);
|
|
4364
4819
|
}
|
|
4365
|
-
|
|
4820
|
+
editQueueItem(id, text) {
|
|
4821
|
+
this.requireOpen();
|
|
4822
|
+
if (this.sentTexts.has(id)) this.sentTexts.set(id, text);
|
|
4823
|
+
void this.sendInput({ type: "queued-run.edit", clientMessageId: id, text }).catch(
|
|
4824
|
+
(error) => {
|
|
4825
|
+
this.emitError("Failed to edit the queued Agent message", error);
|
|
4826
|
+
}
|
|
4827
|
+
);
|
|
4828
|
+
}
|
|
4829
|
+
removeQueueItem(id) {
|
|
4830
|
+
this.requireOpen();
|
|
4831
|
+
void this.sendInput({ type: "queued-run.cancel", clientMessageId: id }).catch(
|
|
4832
|
+
(error) => {
|
|
4833
|
+
this.emitError("Failed to remove the queued Agent message", error);
|
|
4834
|
+
}
|
|
4835
|
+
);
|
|
4366
4836
|
}
|
|
4367
4837
|
clearQueue() {
|
|
4838
|
+
for (const item of this.queueItems) this.removeQueueItem(item.id);
|
|
4839
|
+
}
|
|
4840
|
+
steerQueueItem(id) {
|
|
4841
|
+
this.requireOpen();
|
|
4842
|
+
void this.sendInput({ type: "queued-message.promote-to-steer", clientMessageId: id }).catch(
|
|
4843
|
+
(error) => {
|
|
4844
|
+
this.emitError("Failed to steer the queued Agent message", error);
|
|
4845
|
+
}
|
|
4846
|
+
);
|
|
4847
|
+
}
|
|
4848
|
+
resumeQueue() {
|
|
4849
|
+
this.requireOpen();
|
|
4850
|
+
void this.sendInput({ type: "queue.resume" }).catch((error) => {
|
|
4851
|
+
this.emitError("Failed to resume the Agent queue", error);
|
|
4852
|
+
});
|
|
4853
|
+
}
|
|
4854
|
+
get backgroundTasks() {
|
|
4855
|
+
return this._backgroundTasks;
|
|
4368
4856
|
}
|
|
4369
4857
|
stopSubagent(subagentId) {
|
|
4370
4858
|
this.requireOpen();
|
|
@@ -4405,9 +4893,10 @@ var CoreAgentTaskSession = class {
|
|
|
4405
4893
|
if (this.isClosed()) return false;
|
|
4406
4894
|
await this.loadHistory();
|
|
4407
4895
|
if (this.isClosed()) return false;
|
|
4896
|
+
this.openingCursor = historyCursorOf(this._history);
|
|
4408
4897
|
await this.ensureChannel();
|
|
4409
4898
|
if (this.isClosed()) return false;
|
|
4410
|
-
this.setStatus("idle");
|
|
4899
|
+
if (this._status === "opening") this.setStatus("idle");
|
|
4411
4900
|
return true;
|
|
4412
4901
|
} catch (error) {
|
|
4413
4902
|
if (this.isClosed()) return false;
|
|
@@ -4416,13 +4905,14 @@ var CoreAgentTaskSession = class {
|
|
|
4416
4905
|
return false;
|
|
4417
4906
|
}
|
|
4418
4907
|
}
|
|
4419
|
-
startDispatch(prompt, options, waiter) {
|
|
4908
|
+
startDispatch(prompt, options, clientMessageId, waiter) {
|
|
4909
|
+
this.sentTexts.set(clientMessageId, prompt);
|
|
4420
4910
|
this.dispatching = true;
|
|
4421
4911
|
let handedOver;
|
|
4422
4912
|
this.handOff = new Promise((resolve) => {
|
|
4423
4913
|
handedOver = resolve;
|
|
4424
4914
|
});
|
|
4425
|
-
const dispatch = this.dispatchSend(prompt, options, handedOver, waiter).catch((error) => {
|
|
4915
|
+
const dispatch = this.dispatchSend(prompt, options, clientMessageId, handedOver, waiter).catch((error) => {
|
|
4426
4916
|
waiter?.reject(error);
|
|
4427
4917
|
this.emitError("Failed to send Agent prompt", error);
|
|
4428
4918
|
if (this._status === "streaming") {
|
|
@@ -4432,25 +4922,26 @@ var CoreAgentTaskSession = class {
|
|
|
4432
4922
|
return false;
|
|
4433
4923
|
}).finally(() => {
|
|
4434
4924
|
handedOver();
|
|
4435
|
-
this.
|
|
4436
|
-
|
|
4925
|
+
if (this.dispatch === dispatch) {
|
|
4926
|
+
this.dispatching = false;
|
|
4927
|
+
this.dispatch = null;
|
|
4928
|
+
}
|
|
4437
4929
|
});
|
|
4438
4930
|
this.dispatch = dispatch;
|
|
4439
4931
|
}
|
|
4440
|
-
async dispatchSend(prompt, options, handedOver, waiter) {
|
|
4932
|
+
async dispatchSend(prompt, options, clientMessageId, handedOver, waiter) {
|
|
4441
4933
|
if (this.openingPromise && !await this.openingPromise) {
|
|
4442
4934
|
throw new Error("Agent task session could not be opened.");
|
|
4443
4935
|
}
|
|
4444
|
-
if (this.isClosed()
|
|
4936
|
+
if (this.isClosed()) return false;
|
|
4445
4937
|
await this.ensureTask();
|
|
4446
4938
|
const input = messageInput(prompt, options);
|
|
4447
4939
|
if (this.isClosed()) {
|
|
4448
|
-
await this.
|
|
4940
|
+
await this.handOver(input, clientMessageId).catch(() => void 0);
|
|
4449
4941
|
return false;
|
|
4450
4942
|
}
|
|
4451
|
-
if (waiter?.settled) return false;
|
|
4452
4943
|
await this.ensureChannel();
|
|
4453
|
-
if (this.isClosed()
|
|
4944
|
+
if (this.isClosed()) return false;
|
|
4454
4945
|
await this.captureTurnBaseline();
|
|
4455
4946
|
this._content = "";
|
|
4456
4947
|
this.recoveryUsed = false;
|
|
@@ -4460,13 +4951,13 @@ var CoreAgentTaskSession = class {
|
|
|
4460
4951
|
this.activeWaiter = waiter;
|
|
4461
4952
|
this.setStatus("streaming");
|
|
4462
4953
|
this.emit("turnStart", {});
|
|
4463
|
-
this.openingMessageId =
|
|
4954
|
+
this.openingMessageId = clientMessageId;
|
|
4464
4955
|
this.openingAwaitsStart = true;
|
|
4465
4956
|
const { admitted, direct } = await this.handOver(input, this.openingMessageId);
|
|
4466
4957
|
if (!direct) this.openingAwaitsStart = false;
|
|
4467
4958
|
handedOver();
|
|
4468
4959
|
if (!await admitted) return false;
|
|
4469
|
-
this.
|
|
4960
|
+
this.acceptOnce(clientMessageId);
|
|
4470
4961
|
return true;
|
|
4471
4962
|
}
|
|
4472
4963
|
// A message sent while a turn runs, or is being opened, goes out at once: the box takes it into
|
|
@@ -4490,6 +4981,7 @@ var CoreAgentTaskSession = class {
|
|
|
4490
4981
|
} else {
|
|
4491
4982
|
this.strayedSteers.push(steered);
|
|
4492
4983
|
}
|
|
4984
|
+
this.sentTexts.set(steered.clientMessageId, prompt);
|
|
4493
4985
|
const input = messageInput(prompt, options);
|
|
4494
4986
|
this.pendingSteers += 1;
|
|
4495
4987
|
const handed = this.handOff.then(async () => {
|
|
@@ -4511,7 +5003,7 @@ var CoreAgentTaskSession = class {
|
|
|
4511
5003
|
return;
|
|
4512
5004
|
}
|
|
4513
5005
|
if (!steered.queued) this.steerTaken(steered);
|
|
4514
|
-
this.
|
|
5006
|
+
this.acceptOnce(steered.clientMessageId);
|
|
4515
5007
|
}).catch((error) => {
|
|
4516
5008
|
this.forgetSteer(steered);
|
|
4517
5009
|
waiter?.reject(error);
|
|
@@ -4519,6 +5011,7 @@ var CoreAgentTaskSession = class {
|
|
|
4519
5011
|
}).finally(() => {
|
|
4520
5012
|
this.pendingSteers -= 1;
|
|
4521
5013
|
});
|
|
5014
|
+
return steered.clientMessageId;
|
|
4522
5015
|
}
|
|
4523
5016
|
// The box took the steer. Into the turn it was sent to, when that turn still runs; into a turn
|
|
4524
5017
|
// of its own, when that one ended before the box got to the message.
|
|
@@ -4565,7 +5058,7 @@ var CoreAgentTaskSession = class {
|
|
|
4565
5058
|
else if (steered.waiter) settle(steered.waiter);
|
|
4566
5059
|
}
|
|
4567
5060
|
}
|
|
4568
|
-
openTurnFor(waiter) {
|
|
5061
|
+
openTurnFor(waiter, start = {}) {
|
|
4569
5062
|
if (this.isClosed()) return;
|
|
4570
5063
|
if (this._status !== "streaming" && this._status !== "cancelled") {
|
|
4571
5064
|
this._content = "";
|
|
@@ -4576,7 +5069,7 @@ var CoreAgentTaskSession = class {
|
|
|
4576
5069
|
this.turnBaselineIds = new Set(this._history.map((item) => item.id));
|
|
4577
5070
|
void this.captureTurnBaseline().catch(() => void 0);
|
|
4578
5071
|
this.setStatus("streaming");
|
|
4579
|
-
this.emit("turnStart",
|
|
5072
|
+
this.emit("turnStart", start);
|
|
4580
5073
|
}
|
|
4581
5074
|
if (!waiter) return;
|
|
4582
5075
|
if (!this.activeWaiter) this.activeWaiter = waiter;
|
|
@@ -4619,6 +5112,8 @@ var CoreAgentTaskSession = class {
|
|
|
4619
5112
|
const abort = new AbortController();
|
|
4620
5113
|
this.connectionAbort = abort;
|
|
4621
5114
|
const source = this._task?.agentId ? this.dependencies.channel : this.dependencies.eventSource;
|
|
5115
|
+
const historyCursor = this.openingCursor;
|
|
5116
|
+
this.openingCursor = void 0;
|
|
4622
5117
|
this.connectionPromise = source.open(
|
|
4623
5118
|
this._taskId,
|
|
4624
5119
|
{
|
|
@@ -4626,7 +5121,8 @@ var CoreAgentTaskSession = class {
|
|
|
4626
5121
|
onDisconnect: (error) => this.handleDisconnect(error)
|
|
4627
5122
|
},
|
|
4628
5123
|
abort.signal,
|
|
4629
|
-
this.options.transport
|
|
5124
|
+
this.options.transport,
|
|
5125
|
+
historyCursor
|
|
4630
5126
|
).then((connection) => {
|
|
4631
5127
|
if (this.isClosed() || this._status === "error") {
|
|
4632
5128
|
connection.close();
|
|
@@ -4672,7 +5168,8 @@ var CoreAgentTaskSession = class {
|
|
|
4672
5168
|
if (!this._taskId) return;
|
|
4673
5169
|
const page = await this.dependencies.tasks.listMessages(this._taskId, {
|
|
4674
5170
|
size: 100,
|
|
4675
|
-
sort: "createdAt,desc"
|
|
5171
|
+
sort: "createdAt,desc",
|
|
5172
|
+
kinds: "all"
|
|
4676
5173
|
});
|
|
4677
5174
|
this.turnBaselineIds = new Set(page.content.map((message) => message.id));
|
|
4678
5175
|
}
|
|
@@ -4680,11 +5177,13 @@ var CoreAgentTaskSession = class {
|
|
|
4680
5177
|
if (!this._taskId) return false;
|
|
4681
5178
|
const page = await this.dependencies.tasks.listMessages(this._taskId, {
|
|
4682
5179
|
size: 100,
|
|
4683
|
-
sort: "createdAt,desc"
|
|
5180
|
+
sort: "createdAt,desc",
|
|
5181
|
+
kinds: "all"
|
|
4684
5182
|
});
|
|
4685
|
-
this.
|
|
5183
|
+
this.replaceHistory(page);
|
|
4686
5184
|
this.emit("historyLoaded", { history: this.history });
|
|
4687
|
-
const
|
|
5185
|
+
const rows = page.content.filter(isChatRow);
|
|
5186
|
+
const recovered = rows.find(
|
|
4688
5187
|
(message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE" && (message.type === "ERROR" || this.closesThisTurn(message))
|
|
4689
5188
|
);
|
|
4690
5189
|
if (!recovered) {
|
|
@@ -4693,7 +5192,7 @@ var CoreAgentTaskSession = class {
|
|
|
4693
5192
|
this.endedPollsWithoutRow += 1;
|
|
4694
5193
|
if (this.endedPollsWithoutRow < ENDED_POLLS_BEFORE_NEWEST) return false;
|
|
4695
5194
|
}
|
|
4696
|
-
const newest =
|
|
5195
|
+
const newest = rows.find(
|
|
4697
5196
|
(message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
|
|
4698
5197
|
);
|
|
4699
5198
|
if (!newest) return false;
|
|
@@ -4737,11 +5236,13 @@ var CoreAgentTaskSession = class {
|
|
|
4737
5236
|
);
|
|
4738
5237
|
}
|
|
4739
5238
|
const turnRunning = this._status === "streaming" || this._status === "cancelled";
|
|
4740
|
-
const
|
|
5239
|
+
const id = clientMessageId === void 0 ? {} : { clientMessageId };
|
|
5240
|
+
const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content, ...id } : {
|
|
4741
5241
|
type: "message",
|
|
4742
5242
|
content: input.content,
|
|
4743
5243
|
...input.agentType ? { agentType: input.agentType } : {},
|
|
4744
|
-
...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {}
|
|
5244
|
+
...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {},
|
|
5245
|
+
...id
|
|
4745
5246
|
};
|
|
4746
5247
|
await this.dependencies.tasks.sendInput(this._taskId, rest);
|
|
4747
5248
|
return { admitted: Promise.resolve(true), direct: false };
|
|
@@ -4761,6 +5262,7 @@ var CoreAgentTaskSession = class {
|
|
|
4761
5262
|
return;
|
|
4762
5263
|
}
|
|
4763
5264
|
const lifecycle = asObject2(payload?.lifecycle);
|
|
5265
|
+
if (this.endsQueuedMessage(event, payload, lifecycle)) return;
|
|
4764
5266
|
if (this.repeatsTheRunningTurn(event, lifecycle)) return;
|
|
4765
5267
|
if (event.type === "stepStart" || event.type === "steer") {
|
|
4766
5268
|
const id = lifecycle?.clientMessageId;
|
|
@@ -4777,35 +5279,70 @@ var CoreAgentTaskSession = class {
|
|
|
4777
5279
|
// texto e o que faz a resposta recuperada aparecer; sem isso ela chega e morre aqui.
|
|
4778
5280
|
case "textDelta":
|
|
4779
5281
|
case "textChunk":
|
|
4780
|
-
this.consumeDelta(payload, "text");
|
|
5282
|
+
this.consumeDelta(event, payload, "text");
|
|
4781
5283
|
break;
|
|
4782
5284
|
case "thinking":
|
|
4783
|
-
this.consumeDelta(payload, "thinking");
|
|
5285
|
+
this.consumeDelta(event, payload, "thinking");
|
|
4784
5286
|
break;
|
|
4785
5287
|
case "toolCall":
|
|
4786
|
-
if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "call"
|
|
5288
|
+
if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(event, payload, "call");
|
|
4787
5289
|
break;
|
|
5290
|
+
// A result can come after its turn ended: a subagent in the background settles later, and
|
|
5291
|
+
// the box sends its result under the turn that called it. It reaches the app as that tool's
|
|
5292
|
+
// result and touches no turn.
|
|
4788
5293
|
case "toolResult":
|
|
4789
|
-
|
|
5294
|
+
this.emitTool(event, payload, "result");
|
|
4790
5295
|
break;
|
|
4791
5296
|
case "workspace":
|
|
4792
|
-
this.emit("workspace", {
|
|
5297
|
+
this.emit("workspace", {
|
|
5298
|
+
payload: event.payload,
|
|
5299
|
+
timestamp: event.timestamp,
|
|
5300
|
+
...sequenceOf(event)
|
|
5301
|
+
});
|
|
4793
5302
|
break;
|
|
4794
5303
|
case "stepStart":
|
|
5304
|
+
if (!this.isFinishedTurnFrame(lifecycle)) {
|
|
5305
|
+
this.liveQuestion(event, payload?.text, lifecycle?.clientMessageId);
|
|
5306
|
+
}
|
|
5307
|
+
if (typeof lifecycle?.turnId === "string" && !this.isFinishedTurnFrame(lifecycle) && this._status !== "streaming" && this._status !== "cancelled") {
|
|
5308
|
+
this.openTurnFor(void 0, {
|
|
5309
|
+
...typeof payload?.text === "string" ? { text: payload.text } : {},
|
|
5310
|
+
...typeof lifecycle.clientMessageId === "string" ? { clientMessageId: lifecycle.clientMessageId } : {},
|
|
5311
|
+
...pieceIdentityOf(event, payload)
|
|
5312
|
+
});
|
|
5313
|
+
}
|
|
5314
|
+
this.leaveQueue(lifecycle?.clientMessageId);
|
|
4795
5315
|
this.steerOpenedBy(asObject2(payload?.lifecycle));
|
|
5316
|
+
this.acceptNamed(lifecycle?.clientMessageId);
|
|
4796
5317
|
break;
|
|
4797
5318
|
case "steer":
|
|
5319
|
+
this.liveQuestion(event, payload?.text, lifecycle?.clientMessageId);
|
|
5320
|
+
this.leaveQueue(lifecycle?.clientMessageId);
|
|
4798
5321
|
this.steerOpenedBy(lifecycle);
|
|
5322
|
+
this.acceptNamed(lifecycle?.clientMessageId);
|
|
4799
5323
|
this.emit("steered", {
|
|
4800
5324
|
text: typeof payload?.text === "string" ? payload.text : "",
|
|
4801
|
-
messageId: typeof payload?.messageId === "string" ? payload.messageId : ""
|
|
5325
|
+
messageId: typeof payload?.messageId === "string" ? payload.messageId : "",
|
|
5326
|
+
...typeof payload?.turnId === "string" ? { turnId: payload.turnId } : {},
|
|
5327
|
+
...sequenceOf(event),
|
|
5328
|
+
...typeof lifecycle?.clientMessageId === "string" ? { clientMessageId: lifecycle.clientMessageId } : {}
|
|
4802
5329
|
});
|
|
4803
5330
|
break;
|
|
5331
|
+
case "backgroundTasks":
|
|
5332
|
+
this._backgroundTasks = backgroundTasksOf(payload?.tasks);
|
|
5333
|
+
this.emit("backgroundTasks", { tasks: this._backgroundTasks });
|
|
5334
|
+
break;
|
|
4804
5335
|
case "messageQueued":
|
|
5336
|
+
if (payload?.cancelled === true) {
|
|
5337
|
+
this.cancelQueued(payload, lifecycle);
|
|
5338
|
+
break;
|
|
5339
|
+
}
|
|
5340
|
+
this.applyQueued(event, payload, lifecycle);
|
|
4805
5341
|
this.steerQueuedBy(asObject2(payload?.lifecycle));
|
|
5342
|
+
this.acceptNamed(lifecycle?.clientMessageId);
|
|
4806
5343
|
break;
|
|
4807
5344
|
case "subagentUpdate":
|
|
4808
|
-
this.applySubagent(payload);
|
|
5345
|
+
this.applySubagent(event, payload);
|
|
4809
5346
|
break;
|
|
4810
5347
|
case "providerUsage": {
|
|
4811
5348
|
const usage = providerUsageOf(payload);
|
|
@@ -4818,9 +5355,14 @@ var CoreAgentTaskSession = class {
|
|
|
4818
5355
|
const usage = agentTurnUsageOf(payload?.usage);
|
|
4819
5356
|
const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
|
|
4820
5357
|
if (finished !== void 0 && this.finishedTurnIds.includes(finished)) break;
|
|
5358
|
+
if (finished === void 0 && lifecycle2 && this.turnIds.size > 0) break;
|
|
5359
|
+
const end = {
|
|
5360
|
+
...sequenceOf(event),
|
|
5361
|
+
...finished === void 0 ? {} : { turnId: finished }
|
|
5362
|
+
};
|
|
4821
5363
|
if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
|
|
4822
5364
|
this.rememberFinishedTurn(lifecycle2);
|
|
4823
|
-
this.finishTurn("interrupted", usage);
|
|
5365
|
+
this.finishTurn("interrupted", usage, end);
|
|
4824
5366
|
break;
|
|
4825
5367
|
}
|
|
4826
5368
|
if (reason === "stop" || reason === "endTurn") {
|
|
@@ -4835,7 +5377,7 @@ var CoreAgentTaskSession = class {
|
|
|
4835
5377
|
});
|
|
4836
5378
|
}
|
|
4837
5379
|
} else {
|
|
4838
|
-
this.finishTurn(reason, usage);
|
|
5380
|
+
this.finishTurn(reason, usage, end);
|
|
4839
5381
|
}
|
|
4840
5382
|
}
|
|
4841
5383
|
break;
|
|
@@ -4843,8 +5385,9 @@ var CoreAgentTaskSession = class {
|
|
|
4843
5385
|
case "error": {
|
|
4844
5386
|
const code = typeof payload?.code === "string" ? payload.code : void 0;
|
|
4845
5387
|
const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
|
|
4846
|
-
this.emit("error", { ...code ? { code } : {}, error: message });
|
|
5388
|
+
this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
|
|
4847
5389
|
if (!payload?.lifecycle && payload?.requestId !== void 0) break;
|
|
5390
|
+
if (typeof payload?.command === "string") break;
|
|
4848
5391
|
const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
|
|
4849
5392
|
if (typeof refused === "string") {
|
|
4850
5393
|
if (refused !== this.openingMessageId) {
|
|
@@ -4860,10 +5403,119 @@ var CoreAgentTaskSession = class {
|
|
|
4860
5403
|
}
|
|
4861
5404
|
break;
|
|
4862
5405
|
}
|
|
5406
|
+
case "approval":
|
|
5407
|
+
case "user_input_request":
|
|
5408
|
+
this.liveRequest(event, payload);
|
|
5409
|
+
break;
|
|
4863
5410
|
default:
|
|
4864
5411
|
break;
|
|
4865
5412
|
}
|
|
4866
5413
|
}
|
|
5414
|
+
// The box admits every message with a `messageQueued` of no position; only one with a position
|
|
5415
|
+
// is in T3's queue.
|
|
5416
|
+
applyQueued(event, payload, lifecycle) {
|
|
5417
|
+
const id = payload?.clientMessageId ?? lifecycle?.clientMessageId;
|
|
5418
|
+
const position = payload?.position;
|
|
5419
|
+
if (typeof id !== "string" || typeof position !== "number") return;
|
|
5420
|
+
const known = this.queueItems.find((item2) => item2.id === id);
|
|
5421
|
+
if (this.alreadyApplied(known?.sequence, event)) return;
|
|
5422
|
+
const item = {
|
|
5423
|
+
id,
|
|
5424
|
+
text: typeof payload?.text === "string" ? payload.text : known?.text ?? "",
|
|
5425
|
+
createdAt: known?.createdAt ?? event.timestamp,
|
|
5426
|
+
position,
|
|
5427
|
+
...typeof payload?.queueHeld === "boolean" ? { queueHeld: payload.queueHeld } : {},
|
|
5428
|
+
...sequenceOf(event),
|
|
5429
|
+
...typeof lifecycle?.turnId === "string" ? { turnId: lifecycle.turnId } : {}
|
|
5430
|
+
};
|
|
5431
|
+
this.queueItems = known ? this.queueItems.map((current) => current === known ? item : current) : [...this.queueItems, item];
|
|
5432
|
+
this.emit("queueChange", { queue: this.queue });
|
|
5433
|
+
}
|
|
5434
|
+
// The box took the message out of T3's queue on a `queued-run.cancel`, with no terminal of its
|
|
5435
|
+
// own: it leaves the queue and only its own `sendAndWait` ends. The message that opened this
|
|
5436
|
+
// session's turn was that turn, still waiting behind another one, which ends with it.
|
|
5437
|
+
cancelQueued(payload, lifecycle) {
|
|
5438
|
+
const id = payload.clientMessageId ?? lifecycle?.clientMessageId;
|
|
5439
|
+
if (typeof id !== "string") return;
|
|
5440
|
+
this.leaveQueue(id);
|
|
5441
|
+
const cancelled = new AgentTaskTurnError("The queued Agent message was cancelled.");
|
|
5442
|
+
if (id === this.openingMessageId) {
|
|
5443
|
+
this.cancelOpening(cancelled);
|
|
5444
|
+
return;
|
|
5445
|
+
}
|
|
5446
|
+
const steered = [...this.steers, ...this.strayedSteers].find(
|
|
5447
|
+
(pending) => pending.clientMessageId === id
|
|
5448
|
+
);
|
|
5449
|
+
if (!steered) return;
|
|
5450
|
+
this.forgetSteer(steered);
|
|
5451
|
+
steered.waiter?.reject(cancelled);
|
|
5452
|
+
}
|
|
5453
|
+
// A frame naming one of this session's messages in flight is the box taking it.
|
|
5454
|
+
acceptNamed(id) {
|
|
5455
|
+
if (typeof id !== "string") return;
|
|
5456
|
+
if (id === this.openingMessageId) this.dispatching = false;
|
|
5457
|
+
const ours = id === this.openingMessageId || [...this.steers, ...this.strayedSteers].some((pending) => pending.clientMessageId === id);
|
|
5458
|
+
if (ours) this.acceptOnce(id);
|
|
5459
|
+
}
|
|
5460
|
+
acceptOnce(id) {
|
|
5461
|
+
if (this.acceptedIds.includes(id)) return;
|
|
5462
|
+
this.acceptedIds.push(id);
|
|
5463
|
+
if (this.acceptedIds.length > 32) this.acceptedIds.shift();
|
|
5464
|
+
this.emit("accepted", {});
|
|
5465
|
+
}
|
|
5466
|
+
// As in T3, cancelling a queued run only takes that run out: no turn ends with it. The message
|
|
5467
|
+
// this session opened its turn with never ran, so only its own `sendAndWait` is rejected. A
|
|
5468
|
+
// message of this session still queued behind it keeps the session waiting for the turn the
|
|
5469
|
+
// box opens for it; with none, nothing of this session runs and it goes back to idle.
|
|
5470
|
+
cancelOpening(cancelled) {
|
|
5471
|
+
this.openingMessageId = void 0;
|
|
5472
|
+
if (!this.openingAwaitsStart) return;
|
|
5473
|
+
this.openingAwaitsStart = false;
|
|
5474
|
+
this.activeWaiter?.reject(cancelled);
|
|
5475
|
+
this.activeWaiter = void 0;
|
|
5476
|
+
if (this._status !== "streaming" && this._status !== "cancelled") return;
|
|
5477
|
+
if (this.steers.length === 0 && this.strayedSteers.length === 0) this.setStatus("idle");
|
|
5478
|
+
}
|
|
5479
|
+
// After a replay the box sends the queue and the subagents as they are, each a copy of the line
|
|
5480
|
+
// that said it last, with that line's sequence: state this session may already hold.
|
|
5481
|
+
alreadyApplied(applied, event) {
|
|
5482
|
+
return applied !== void 0 && typeof event.sequence === "number" && event.sequence <= applied;
|
|
5483
|
+
}
|
|
5484
|
+
leaveQueue(id) {
|
|
5485
|
+
const item = this.queueItems.find((current) => current.id === id);
|
|
5486
|
+
if (!item) return void 0;
|
|
5487
|
+
this.queueItems = this.queueItems.filter((current) => current !== item);
|
|
5488
|
+
this.emit("queueChange", { queue: this.queue });
|
|
5489
|
+
return item;
|
|
5490
|
+
}
|
|
5491
|
+
// A queued message that ends before running (taken out of the queue, or dropped by T3) closes
|
|
5492
|
+
// with a terminal of its own while another turn may run: it leaves the queue and ends its own
|
|
5493
|
+
// `sendAndWait`, and the running turn goes on. The opening message of this session's turn is
|
|
5494
|
+
// that turn, and ends it as before.
|
|
5495
|
+
endsQueuedMessage(event, payload, lifecycle) {
|
|
5496
|
+
if (event.type !== "error" && event.type !== "stepFinish" || !lifecycle) return false;
|
|
5497
|
+
const id = payload?.clientMessageId ?? lifecycle.clientMessageId;
|
|
5498
|
+
const turnId = lifecycle.turnId;
|
|
5499
|
+
const item = this.queueItems.find(
|
|
5500
|
+
(current) => current.id === id || turnId !== void 0 && current.turnId === turnId
|
|
5501
|
+
);
|
|
5502
|
+
if (!item) return false;
|
|
5503
|
+
this.leaveQueue(item.id);
|
|
5504
|
+
if (item.id === this.openingMessageId) return false;
|
|
5505
|
+
const message = typeof payload?.message === "string" ? payload.message : "The queued Agent message ended before it ran.";
|
|
5506
|
+
if (event.type === "error") {
|
|
5507
|
+
const code = typeof payload?.code === "string" ? payload.code : void 0;
|
|
5508
|
+
this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
|
|
5509
|
+
}
|
|
5510
|
+
const steered = [...this.steers, ...this.strayedSteers].find(
|
|
5511
|
+
(pending) => pending.clientMessageId === item.id
|
|
5512
|
+
);
|
|
5513
|
+
if (steered) {
|
|
5514
|
+
this.forgetSteer(steered);
|
|
5515
|
+
steered.waiter?.reject(new AgentTaskTurnError(message));
|
|
5516
|
+
}
|
|
5517
|
+
return true;
|
|
5518
|
+
}
|
|
4867
5519
|
repeatsTheRunningTurn(event, lifecycle) {
|
|
4868
5520
|
if (this._status !== "streaming" && this._status !== "cancelled") return false;
|
|
4869
5521
|
const turnId = lifecycle?.turnId;
|
|
@@ -4891,7 +5543,7 @@ var CoreAgentTaskSession = class {
|
|
|
4891
5543
|
this.finishedTurnIds.push(turnId);
|
|
4892
5544
|
if (this.finishedTurnIds.length > 8) this.finishedTurnIds.shift();
|
|
4893
5545
|
}
|
|
4894
|
-
consumeDelta(payload, kind) {
|
|
5546
|
+
consumeDelta(event, payload, kind) {
|
|
4895
5547
|
const lifecycle = asObject2(payload?.lifecycle);
|
|
4896
5548
|
const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
|
|
4897
5549
|
if (turnId && this.finishedTurnIds.includes(turnId)) return;
|
|
@@ -4903,40 +5555,160 @@ var CoreAgentTaskSession = class {
|
|
|
4903
5555
|
this.emit("turnStart", {});
|
|
4904
5556
|
}
|
|
4905
5557
|
if (kind === "text") this._content += text;
|
|
4906
|
-
this.
|
|
5558
|
+
this.liveText(event, payload, kind);
|
|
5559
|
+
this.emit("delta", {
|
|
5560
|
+
delta: text,
|
|
5561
|
+
kind,
|
|
5562
|
+
...itemDeltaOf(payload),
|
|
5563
|
+
...pieceIdentityOf(event, payload)
|
|
5564
|
+
});
|
|
5565
|
+
}
|
|
5566
|
+
emitTool(event, payload, phase) {
|
|
5567
|
+
const tool = toolEventOf(event, payload, phase);
|
|
5568
|
+
this.liveTool(tool, event);
|
|
5569
|
+
this.emit("tool", tool);
|
|
5570
|
+
}
|
|
5571
|
+
// The conversation as it happens: the box's frames grow `history` while a turn runs, one item
|
|
5572
|
+
// per piece of T3, the same pieces the Copilot records and the reload at the turn's end brings
|
|
5573
|
+
// back in the same order. A piece the loaded history already has keeps growing in place, and a
|
|
5574
|
+
// frame it already holds (a replay after a reconnect or an F5) changes nothing.
|
|
5575
|
+
livePiece(match, create, update) {
|
|
5576
|
+
const index = this._history.findIndex(match);
|
|
5577
|
+
const current = this._history[index];
|
|
5578
|
+
if (current === void 0) this._history.push(create());
|
|
5579
|
+
else this._history[index] = update(current);
|
|
5580
|
+
}
|
|
5581
|
+
// The question enters the conversation where the box took it: its turn's `stepStart`, or the
|
|
5582
|
+
// `steer` that took it into the running turn. Until then it is in `queue`.
|
|
5583
|
+
liveQuestion(event, boxText, clientMessageId) {
|
|
5584
|
+
const id = typeof clientMessageId === "string" ? clientMessageId : void 0;
|
|
5585
|
+
const text = (id !== void 0 ? this.sentTexts.get(id) : void 0) ?? boxText;
|
|
5586
|
+
if (typeof text !== "string" || !text) return;
|
|
5587
|
+
const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
|
|
5588
|
+
this.livePiece(
|
|
5589
|
+
(item) => item.kind === "user" && (id !== void 0 && item.clientMessageId === id || sequence !== void 0 && item.sequence === sequence && item.text === text),
|
|
5590
|
+
() => ({
|
|
5591
|
+
id: `live:user:${id ?? sequence ?? this._history.length}`,
|
|
5592
|
+
kind: "user",
|
|
5593
|
+
text,
|
|
5594
|
+
at: liveAtOf(event),
|
|
5595
|
+
...sequence === void 0 ? {} : { sequence },
|
|
5596
|
+
...id === void 0 ? {} : { clientMessageId: id }
|
|
5597
|
+
}),
|
|
5598
|
+
(item) => item
|
|
5599
|
+
);
|
|
5600
|
+
}
|
|
5601
|
+
liveText(event, payload, kind, parentToolId) {
|
|
5602
|
+
const itemId = typeof payload?.itemId === "string" ? payload.itemId : void 0;
|
|
5603
|
+
if (itemId === void 0) return;
|
|
5604
|
+
const piece = itemDeltaOf(payload).itemDelta ?? (typeof payload?.text === "string" ? payload.text : "");
|
|
5605
|
+
const itemKind = kind === "thinking" ? "reasoning" : "agent";
|
|
5606
|
+
const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
|
|
5607
|
+
this.livePiece(
|
|
5608
|
+
(item) => item.kind === itemKind && item.itemId === itemId,
|
|
5609
|
+
() => ({
|
|
5610
|
+
id: `live:${itemKind}:${itemId}`,
|
|
5611
|
+
kind: itemKind,
|
|
5612
|
+
text: piece,
|
|
5613
|
+
at: liveAtOf(event),
|
|
5614
|
+
itemId,
|
|
5615
|
+
...sequence === void 0 ? {} : { sequence },
|
|
5616
|
+
...parentToolIdOf(parentToolId)
|
|
5617
|
+
}),
|
|
5618
|
+
(item) => {
|
|
5619
|
+
const held = item.lastSequence ?? item.sequence;
|
|
5620
|
+
if (!("text" in item) || sequence !== void 0 && held !== void 0 && sequence <= held)
|
|
5621
|
+
return item;
|
|
5622
|
+
return {
|
|
5623
|
+
...item,
|
|
5624
|
+
text: item.text + piece,
|
|
5625
|
+
...sequence === void 0 ? {} : { lastSequence: sequence }
|
|
5626
|
+
};
|
|
5627
|
+
}
|
|
5628
|
+
);
|
|
5629
|
+
}
|
|
5630
|
+
liveTool(tool, event) {
|
|
5631
|
+
const toolId = tool.toolId;
|
|
5632
|
+
if (toolId === void 0) return;
|
|
5633
|
+
this.livePiece(
|
|
5634
|
+
(item) => item.kind === "tool" && item.tool.toolId === toolId && item.tool.phase === tool.phase,
|
|
5635
|
+
() => ({
|
|
5636
|
+
id: tool.phase === "result" ? `live:tool:${toolId}:result` : `live:tool:${toolId}`,
|
|
5637
|
+
kind: "tool",
|
|
5638
|
+
tool,
|
|
5639
|
+
at: liveAtOf(event),
|
|
5640
|
+
...tool.sequence === void 0 ? {} : { sequence: tool.sequence },
|
|
5641
|
+
...tool.itemId === void 0 ? {} : { itemId: tool.itemId }
|
|
5642
|
+
}),
|
|
5643
|
+
(item) => item.kind === "tool" ? { ...item, tool: { ...item.tool, ...tool, input: tool.input ?? item.tool.input } } : item
|
|
5644
|
+
);
|
|
4907
5645
|
}
|
|
4908
|
-
|
|
4909
|
-
|
|
5646
|
+
// An approval or a question T3 asks mid-turn enters where it came, with the frame's payload as
|
|
5647
|
+
// it came, as the Copilot records it (`APPROVAL` and `USER_INPUT_REQUEST` rows). It still
|
|
5648
|
+
// reaches the app as a `raw` event, as before.
|
|
5649
|
+
liveRequest(event, payload, parentToolId) {
|
|
5650
|
+
if (!payload) return;
|
|
5651
|
+
const kind = event.type === "approval" ? "approval" : "userInputRequest";
|
|
5652
|
+
const itemId = typeof payload.itemId === "string" ? payload.itemId : void 0;
|
|
5653
|
+
const sequence = typeof event.sequence === "number" ? event.sequence : void 0;
|
|
5654
|
+
if (itemId === void 0 && sequence === void 0) return;
|
|
5655
|
+
this.livePiece(
|
|
5656
|
+
(item) => item.kind === kind && (itemId !== void 0 ? item.itemId === itemId : item.sequence === sequence),
|
|
5657
|
+
() => ({
|
|
5658
|
+
id: `live:${kind}:${itemId ?? sequence}`,
|
|
5659
|
+
kind,
|
|
5660
|
+
payload,
|
|
5661
|
+
at: liveAtOf(event),
|
|
5662
|
+
...sequence === void 0 ? {} : { sequence },
|
|
5663
|
+
...itemId === void 0 ? {} : { itemId },
|
|
5664
|
+
...parentToolIdOf(parentToolId)
|
|
5665
|
+
}),
|
|
5666
|
+
(item) => item
|
|
5667
|
+
);
|
|
4910
5668
|
}
|
|
4911
|
-
// A child thread's frames are the subagent's conversation: they open no turn
|
|
4912
|
-
// and
|
|
5669
|
+
// A child thread's frames are the subagent's conversation: they open no turn and settle no
|
|
5670
|
+
// message. Its text and tools still reach `delta`, `content` and `tool` as they did in 0.2.13,
|
|
5671
|
+
// which knew no subagents, so an app that only bumps the version sees what it saw before.
|
|
4913
5672
|
handleSubagentFrame(event, payload) {
|
|
4914
5673
|
const parentToolId = payload.parentToolId;
|
|
4915
5674
|
switch (event.type) {
|
|
4916
5675
|
case "textDelta":
|
|
4917
5676
|
case "textChunk":
|
|
4918
|
-
case "thinking":
|
|
4919
|
-
|
|
4920
|
-
|
|
4921
|
-
|
|
4922
|
-
|
|
4923
|
-
|
|
5677
|
+
case "thinking": {
|
|
5678
|
+
const delta = typeof payload.text === "string" ? payload.text : "";
|
|
5679
|
+
const kind = event.type === "thinking" ? "thinking" : "text";
|
|
5680
|
+
const identity = { ...itemDeltaOf(payload), ...pieceIdentityOf(event, payload) };
|
|
5681
|
+
if (kind === "text") this._content += delta;
|
|
5682
|
+
this.liveText(event, payload, kind, parentToolId);
|
|
5683
|
+
this.emit("delta", { delta, kind, parentToolId, ...identity });
|
|
5684
|
+
this.emit("subagentDelta", { parentToolId, delta, kind, ...identity });
|
|
4924
5685
|
break;
|
|
5686
|
+
}
|
|
4925
5687
|
case "toolCall":
|
|
4926
|
-
case "toolResult":
|
|
4927
|
-
|
|
4928
|
-
...toolEventOf(payload, event.type === "toolCall" ? "call" : "result"
|
|
5688
|
+
case "toolResult": {
|
|
5689
|
+
const tool = {
|
|
5690
|
+
...toolEventOf(event, payload, event.type === "toolCall" ? "call" : "result"),
|
|
4929
5691
|
parentToolId
|
|
4930
|
-
}
|
|
5692
|
+
};
|
|
5693
|
+
this.liveTool(tool, event);
|
|
5694
|
+
this.emit("tool", tool);
|
|
5695
|
+
this.emit("subagentTool", tool);
|
|
5696
|
+
break;
|
|
5697
|
+
}
|
|
5698
|
+
case "approval":
|
|
5699
|
+
case "user_input_request":
|
|
5700
|
+
this.liveRequest(event, payload, parentToolId);
|
|
4931
5701
|
break;
|
|
4932
5702
|
default:
|
|
4933
5703
|
break;
|
|
4934
5704
|
}
|
|
4935
5705
|
}
|
|
4936
|
-
applySubagent(payload) {
|
|
5706
|
+
applySubagent(event, payload) {
|
|
4937
5707
|
const subagentId = payload?.subagentId;
|
|
4938
5708
|
const toolId = payload?.toolId;
|
|
4939
5709
|
if (typeof subagentId !== "string" || typeof toolId !== "string") return;
|
|
5710
|
+
if (this.alreadyApplied(this.subagentSequences.get(subagentId), event)) return;
|
|
5711
|
+
if (typeof event.sequence === "number") this.subagentSequences.set(subagentId, event.sequence);
|
|
4940
5712
|
const status = typeof payload?.status === "string" ? payload.status : this.subagentsById.get(subagentId)?.status;
|
|
4941
5713
|
if (status === void 0) return;
|
|
4942
5714
|
const startedAt = epochOf(payload?.startedAt);
|
|
@@ -4951,9 +5723,26 @@ var CoreAgentTaskSession = class {
|
|
|
4951
5723
|
...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
|
|
4952
5724
|
};
|
|
4953
5725
|
this.subagentsById.set(subagentId, subagent);
|
|
4954
|
-
this.
|
|
5726
|
+
const index = this._history.findIndex(
|
|
5727
|
+
(item) => item.kind === "tool" && item.tool.toolId === toolId
|
|
5728
|
+
);
|
|
5729
|
+
const spawn = this._history[index];
|
|
5730
|
+
if (spawn?.kind === "tool") {
|
|
5731
|
+
this._history[index] = {
|
|
5732
|
+
...spawn,
|
|
5733
|
+
subagent: {
|
|
5734
|
+
...spawn.subagent,
|
|
5735
|
+
toolId,
|
|
5736
|
+
subagentId,
|
|
5737
|
+
status,
|
|
5738
|
+
...subagent.progress === void 0 ? {} : { progress: subagent.progress },
|
|
5739
|
+
...subagent.childThreadId === void 0 ? {} : { childThreadId: subagent.childThreadId }
|
|
5740
|
+
}
|
|
5741
|
+
};
|
|
5742
|
+
}
|
|
5743
|
+
this.emit("subagent", { ...subagent, ...sequenceOf(event) });
|
|
4955
5744
|
}
|
|
4956
|
-
finishTurn(reason, usage) {
|
|
5745
|
+
finishTurn(reason, usage, end = {}) {
|
|
4957
5746
|
if (this._status !== "streaming" && this._status !== "cancelled") return;
|
|
4958
5747
|
if (this.cancelTimer) clearTimeout(this.cancelTimer);
|
|
4959
5748
|
this.cancelTimer = null;
|
|
@@ -4971,7 +5760,8 @@ var CoreAgentTaskSession = class {
|
|
|
4971
5760
|
task,
|
|
4972
5761
|
content: this._content,
|
|
4973
5762
|
reason,
|
|
4974
|
-
...usage ? { usage } : {}
|
|
5763
|
+
...usage ? { usage } : {},
|
|
5764
|
+
...end
|
|
4975
5765
|
};
|
|
4976
5766
|
this.emit("turnEnd", result);
|
|
4977
5767
|
this.activeWaiter?.resolve(result);
|