@mitralab.io/sdk-core 0.2.13 → 0.3.0-beta.2
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 +98 -0
- package/README.md +9 -3
- package/contracts/README.md +15 -0
- package/contracts/manifest.json +16 -1
- package/contracts/v0.3.0/sdk-parity.json +2902 -0
- package/contracts/v0.3.0-beta.1/sdk-parity.json +2902 -0
- package/contracts/v0.3.0-beta.2/sdk-parity.json +2902 -0
- package/dist/index.cjs +514 -143
- package/dist/index.d.cts +111 -2
- package/dist/index.d.ts +111 -2
- package/dist/index.js +514 -143
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -436,6 +436,9 @@ function expectAppFields(app, context, errors) {
|
|
|
436
436
|
if (!isNullableString(app.icon)) invalidField(context, "icon", errors);
|
|
437
437
|
if (!isNullableString(app.template)) invalidField(context, "template", errors);
|
|
438
438
|
if (typeof app.allowSignup !== "boolean") invalidField(context, "allowSignup", errors);
|
|
439
|
+
for (const field of ["emailLoginEnabled", "passwordLoginEnabled"]) {
|
|
440
|
+
if (field in app && typeof app[field] !== "boolean") invalidField(context, field, errors);
|
|
441
|
+
}
|
|
439
442
|
if (typeof app.externalAccessEnabled !== "boolean") {
|
|
440
443
|
invalidField(context, "externalAccessEnabled", errors);
|
|
441
444
|
}
|
|
@@ -2860,9 +2863,31 @@ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
|
|
|
2860
2863
|
"Notify user response",
|
|
2861
2864
|
errors
|
|
2862
2865
|
);
|
|
2866
|
+
},
|
|
2867
|
+
async sendEmail(input) {
|
|
2868
|
+
return expectMessageAccepted(
|
|
2869
|
+
await transport.request("/api/v1/messages/send", {
|
|
2870
|
+
method: "POST",
|
|
2871
|
+
body: { channel: "EMAIL", payload: rawEmailPayload(input) }
|
|
2872
|
+
}),
|
|
2873
|
+
"Send email response",
|
|
2874
|
+
errors
|
|
2875
|
+
);
|
|
2863
2876
|
}
|
|
2864
2877
|
};
|
|
2865
2878
|
}
|
|
2879
|
+
function rawEmailPayload(input) {
|
|
2880
|
+
return {
|
|
2881
|
+
type: "RAW",
|
|
2882
|
+
to: input.to,
|
|
2883
|
+
...input.cc === void 0 ? {} : { cc: input.cc },
|
|
2884
|
+
...input.bcc === void 0 ? {} : { bcc: input.bcc },
|
|
2885
|
+
...input.replyTo === void 0 ? {} : { replyTo: input.replyTo },
|
|
2886
|
+
subject: input.subject,
|
|
2887
|
+
html: input.html,
|
|
2888
|
+
...input.text === void 0 ? {} : { text: input.text }
|
|
2889
|
+
};
|
|
2890
|
+
}
|
|
2866
2891
|
|
|
2867
2892
|
// src/modules/publicFunctions.ts
|
|
2868
2893
|
function createPublicFunctionsModule(transport, errors = defaultSdkCoreErrorFactory) {
|
|
@@ -3214,6 +3239,29 @@ var ADMISSION_TIMEOUT_MS = 35e3;
|
|
|
3214
3239
|
var SUPERSEDED_CLOSE_CODE = 4409;
|
|
3215
3240
|
var SOCKET_OPEN = 1;
|
|
3216
3241
|
var FLEET_BOX_HOST = /^[0-9a-z][0-9a-z-]*\.(?:e2b\.app|e2b-[0-9a-z-]+\.mitralab\.ai)$/;
|
|
3242
|
+
var clientMessageSequence = 0;
|
|
3243
|
+
function newClientMessageId() {
|
|
3244
|
+
const random = globalThis.crypto?.randomUUID;
|
|
3245
|
+
return random ? random.call(globalThis.crypto) : `m-${Date.now()}-${++clientMessageSequence}`;
|
|
3246
|
+
}
|
|
3247
|
+
function admissionFor(link, event) {
|
|
3248
|
+
const payload = asObject(event.payload);
|
|
3249
|
+
if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0)) {
|
|
3250
|
+
return void 0;
|
|
3251
|
+
}
|
|
3252
|
+
const id = event.type === "stepStart" ? asObject(payload?.lifecycle)?.clientMessageId : payload?.clientMessageId;
|
|
3253
|
+
if (typeof id === "string")
|
|
3254
|
+
return link.admissions.find((pending) => pending.clientMessageId === id);
|
|
3255
|
+
return link.admissions[0];
|
|
3256
|
+
}
|
|
3257
|
+
function queuedAdmission(link, event) {
|
|
3258
|
+
const id = asObject(asObject(event.payload)?.lifecycle)?.clientMessageId;
|
|
3259
|
+
if (typeof id !== "string") return void 0;
|
|
3260
|
+
return link.admissions.find((pending) => pending.clientMessageId === id);
|
|
3261
|
+
}
|
|
3262
|
+
function isSubagentFrame(event) {
|
|
3263
|
+
return typeof asObject(event.payload)?.parentToolId === "string";
|
|
3264
|
+
}
|
|
3217
3265
|
function asObject(value) {
|
|
3218
3266
|
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3219
3267
|
}
|
|
@@ -3334,6 +3382,7 @@ function asDelta(event) {
|
|
|
3334
3382
|
}
|
|
3335
3383
|
var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
|
|
3336
3384
|
"stepStart",
|
|
3385
|
+
"steer",
|
|
3337
3386
|
"textDelta",
|
|
3338
3387
|
"thinking",
|
|
3339
3388
|
"toolCall",
|
|
@@ -3342,7 +3391,7 @@ var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
|
|
|
3342
3391
|
var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
|
|
3343
3392
|
function turnAfter(event, inTurn) {
|
|
3344
3393
|
if (TURN_FRAME_TYPES.has(event.type)) return true;
|
|
3345
|
-
if (event.type === "error") return false;
|
|
3394
|
+
if (event.type === "error") return asObject(event.payload)?.lifecycle ? false : inTurn;
|
|
3346
3395
|
if (event.type === "stepFinish") {
|
|
3347
3396
|
const payload = asObject(event.payload);
|
|
3348
3397
|
if (TURN_END_REASONS.has(payload?.reason)) return false;
|
|
@@ -3350,6 +3399,21 @@ function turnAfter(event, inTurn) {
|
|
|
3350
3399
|
}
|
|
3351
3400
|
return inTurn;
|
|
3352
3401
|
}
|
|
3402
|
+
function lostTurnFrame(turnId) {
|
|
3403
|
+
return {
|
|
3404
|
+
type: "stepFinish",
|
|
3405
|
+
payload: {
|
|
3406
|
+
reason: "interrupted",
|
|
3407
|
+
lifecycle: {
|
|
3408
|
+
...turnId === void 0 ? {} : { turnId },
|
|
3409
|
+
terminal: true,
|
|
3410
|
+
sessionIdle: true,
|
|
3411
|
+
interruptTerminal: true
|
|
3412
|
+
}
|
|
3413
|
+
},
|
|
3414
|
+
timestamp: Date.now()
|
|
3415
|
+
};
|
|
3416
|
+
}
|
|
3353
3417
|
function channelEvent(type, payload) {
|
|
3354
3418
|
return { type, payload, timestamp: Date.now() };
|
|
3355
3419
|
}
|
|
@@ -3429,9 +3493,11 @@ var AgentDirectChannel = class {
|
|
|
3429
3493
|
}
|
|
3430
3494
|
}
|
|
3431
3495
|
/**
|
|
3432
|
-
* Hands a message
|
|
3433
|
-
* wire is up right now. Null sends the caller to REST: no direct channel, a wire lost or
|
|
3434
|
-
* mid-redial, or an approval, which stays on REST.
|
|
3496
|
+
* Hands a message, an interrupt, a subagent stop or an answer to a T3 input request to the box
|
|
3497
|
+
* when the chat is on the direct channel and its wire is up right now. Null sends the caller to REST: no direct channel, a wire lost or
|
|
3498
|
+
* mid-redial, or an approval, which stays on REST. Mid-redial the Copilot is the durable path:
|
|
3499
|
+
* the box URL kept from the last channel carries a proxy ticket that lasts 60 seconds, and a
|
|
3500
|
+
* box that dropped the socket is often the one that went away.
|
|
3435
3501
|
*
|
|
3436
3502
|
* A message resolves only when the box answers for it. `stepStart` on the stream, or the 200 of
|
|
3437
3503
|
* the HTTP route, is the box starting the turn the Copilot admitted: from then on the turn runs
|
|
@@ -3444,12 +3510,12 @@ var AgentDirectChannel = class {
|
|
|
3444
3510
|
* have admitted the turn, and a second copy would start it twice. The redial replays the box
|
|
3445
3511
|
* log, where the `stepStart` of an admitted turn is.
|
|
3446
3512
|
*/
|
|
3447
|
-
send(taskId, input) {
|
|
3513
|
+
send(taskId, input, clientMessageId) {
|
|
3448
3514
|
if (input.type === "approval_response") return null;
|
|
3449
3515
|
const link = this.links.get(taskId);
|
|
3450
3516
|
if (!link?.wire) return null;
|
|
3451
3517
|
if (input.type !== "message") return link.wire.interrupt(input);
|
|
3452
|
-
|
|
3518
|
+
const messageId = clientMessageId ?? newClientMessageId();
|
|
3453
3519
|
let admission;
|
|
3454
3520
|
const admitted = new Promise((resolve, reject) => {
|
|
3455
3521
|
let timer;
|
|
@@ -3465,11 +3531,13 @@ var AgentDirectChannel = class {
|
|
|
3465
3531
|
};
|
|
3466
3532
|
const done = () => {
|
|
3467
3533
|
clearTimeout(timer);
|
|
3468
|
-
|
|
3534
|
+
link.admissions = link.admissions.filter((pending) => pending !== admission);
|
|
3469
3535
|
};
|
|
3470
3536
|
admission = {
|
|
3537
|
+
clientMessageId: messageId,
|
|
3471
3538
|
settle: (value) => {
|
|
3472
3539
|
done();
|
|
3540
|
+
if (value) link.inTurn = true;
|
|
3473
3541
|
resolve(value);
|
|
3474
3542
|
},
|
|
3475
3543
|
fail: (error) => {
|
|
@@ -3481,12 +3549,11 @@ var AgentDirectChannel = class {
|
|
|
3481
3549
|
};
|
|
3482
3550
|
arm();
|
|
3483
3551
|
});
|
|
3484
|
-
link.
|
|
3485
|
-
if (!link.wire.message(input, admission)) {
|
|
3552
|
+
link.admissions = [...link.admissions, admission];
|
|
3553
|
+
if (!link.wire.message({ ...input, clientMessageId: messageId }, admission)) {
|
|
3486
3554
|
admission.settle(false);
|
|
3487
3555
|
return null;
|
|
3488
3556
|
}
|
|
3489
|
-
link.inTurn = true;
|
|
3490
3557
|
return admitted;
|
|
3491
3558
|
}
|
|
3492
3559
|
/** `websocket` needs a socket; `http` needs fetch; `auto` prefers the socket. */
|
|
@@ -3543,7 +3610,7 @@ var AgentDirectChannel = class {
|
|
|
3543
3610
|
* text. The HTTP stream opens from the sequence the Copilot reported, which is the same thing.
|
|
3544
3611
|
*/
|
|
3545
3612
|
async openDirect(taskId, mode, channel, observer, signal) {
|
|
3546
|
-
const link = { wire: null, inTurn: false,
|
|
3613
|
+
const link = { wire: null, inTurn: false, turnId: void 0, admissions: [] };
|
|
3547
3614
|
let box = boxAddress(channel.wsUrl);
|
|
3548
3615
|
let cursor = channel.lastSequence;
|
|
3549
3616
|
const abort = new AbortController();
|
|
@@ -3551,35 +3618,46 @@ var AgentDirectChannel = class {
|
|
|
3551
3618
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3552
3619
|
const onFrame = (event) => {
|
|
3553
3620
|
if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
|
|
3621
|
+
if (isSubagentFrame(event)) {
|
|
3622
|
+
observer.onEvent(event);
|
|
3623
|
+
return;
|
|
3624
|
+
}
|
|
3625
|
+
const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
|
|
3626
|
+
if (typeof turnId === "string") link.turnId = turnId;
|
|
3554
3627
|
link.inTurn = turnAfter(event, link.inTurn);
|
|
3555
3628
|
observer.onEvent(event);
|
|
3556
|
-
if (event.type === "stepStart") link
|
|
3557
|
-
else if (event.type === "error") link
|
|
3629
|
+
if (event.type === "stepStart") admissionFor(link, event)?.settle(true);
|
|
3630
|
+
else if (event.type === "error") admissionFor(link, event)?.settle(false);
|
|
3631
|
+
else if (event.type === "messageQueued" || event.type === "steer") {
|
|
3632
|
+
queuedAdmission(link, event)?.settle(true);
|
|
3633
|
+
}
|
|
3558
3634
|
};
|
|
3559
3635
|
const onLost = (error, code) => {
|
|
3560
3636
|
link.wire = null;
|
|
3561
3637
|
if (abort.signal.aborted) return;
|
|
3562
|
-
if (!link.inTurn || code === SUPERSEDED_CLOSE_CODE) {
|
|
3563
|
-
link.
|
|
3638
|
+
if (!link.inTurn && link.admissions.length === 0 || code === SUPERSEDED_CLOSE_CODE) {
|
|
3639
|
+
for (const pending of link.admissions) pending.fail(error);
|
|
3564
3640
|
observer.onDisconnect(error);
|
|
3565
3641
|
return;
|
|
3566
3642
|
}
|
|
3567
|
-
link.
|
|
3643
|
+
for (const pending of link.admissions) pending.hold();
|
|
3568
3644
|
void this.redial(taskId, mode, error, abort.signal, observer, {
|
|
3569
3645
|
onFrame,
|
|
3570
3646
|
onLost,
|
|
3571
3647
|
replayFrom: (next) => {
|
|
3572
3648
|
const nextBox = boxAddress(next.wsUrl);
|
|
3573
|
-
|
|
3649
|
+
const zeroed = next.lastSequence === 0 && cursor > 0;
|
|
3650
|
+
if (nextBox === box && !zeroed) return cursor;
|
|
3651
|
+
if (link.inTurn) onFrame(lostTurnFrame(link.turnId));
|
|
3574
3652
|
box = nextBox;
|
|
3575
3653
|
cursor = next.lastSequence;
|
|
3576
3654
|
return void 0;
|
|
3577
3655
|
}
|
|
3578
3656
|
}).then((outcome) => {
|
|
3579
|
-
if (outcome instanceof Error) link.
|
|
3657
|
+
if (outcome instanceof Error) for (const pending of link.admissions) pending.fail(outcome);
|
|
3580
3658
|
else if (outcome) {
|
|
3581
3659
|
link.wire = outcome;
|
|
3582
|
-
link.
|
|
3660
|
+
for (const pending of link.admissions) pending.rearm();
|
|
3583
3661
|
}
|
|
3584
3662
|
});
|
|
3585
3663
|
};
|
|
@@ -3600,9 +3678,8 @@ var AgentDirectChannel = class {
|
|
|
3600
3678
|
abort.abort();
|
|
3601
3679
|
link.wire?.close();
|
|
3602
3680
|
link.wire = null;
|
|
3603
|
-
|
|
3604
|
-
|
|
3605
|
-
);
|
|
3681
|
+
const closed = new Error("The Agent session closed before the box confirmed the turn.");
|
|
3682
|
+
for (const pending of link.admissions) pending.fail(closed);
|
|
3606
3683
|
if (this.links.get(taskId) === link) this.links.delete(taskId);
|
|
3607
3684
|
}
|
|
3608
3685
|
};
|
|
@@ -3739,7 +3816,7 @@ var AgentDirectChannel = class {
|
|
|
3739
3816
|
close,
|
|
3740
3817
|
interrupt: (input) => post(input).then((response) => {
|
|
3741
3818
|
if (!response.ok) {
|
|
3742
|
-
throw new Error(`The Agent box refused the
|
|
3819
|
+
throw new Error(`The Agent box refused the ${input.type} (${response.status}).`);
|
|
3743
3820
|
}
|
|
3744
3821
|
return true;
|
|
3745
3822
|
}),
|
|
@@ -3921,9 +3998,22 @@ var AgentDirectChannel = class {
|
|
|
3921
3998
|
};
|
|
3922
3999
|
|
|
3923
4000
|
// src/agentSession.ts
|
|
3924
|
-
var AGENT_QUEUE_LIMIT = 10;
|
|
3925
4001
|
var CANCEL_SAFETY_MS = 1e4;
|
|
3926
4002
|
var RECONCILE_DELAY_MS = 1e3;
|
|
4003
|
+
var ENDED_POLLS_BEFORE_NEWEST = 3;
|
|
4004
|
+
var TURN_TAIL_TYPES = /* @__PURE__ */ new Set([
|
|
4005
|
+
"textDelta",
|
|
4006
|
+
"textChunk",
|
|
4007
|
+
"thinking",
|
|
4008
|
+
"toolCall",
|
|
4009
|
+
"toolResult",
|
|
4010
|
+
"stepFinish"
|
|
4011
|
+
]);
|
|
4012
|
+
var COPILOT_INPUT_TYPES = /* @__PURE__ */ new Set([
|
|
4013
|
+
"message",
|
|
4014
|
+
"interrupt",
|
|
4015
|
+
"approval_response"
|
|
4016
|
+
]);
|
|
3927
4017
|
function providerUsageOf(payload) {
|
|
3928
4018
|
if (!payload) return null;
|
|
3929
4019
|
try {
|
|
@@ -3952,6 +4042,31 @@ function errorCode(error) {
|
|
|
3952
4042
|
function delay(milliseconds) {
|
|
3953
4043
|
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
3954
4044
|
}
|
|
4045
|
+
function messageInput(prompt, options) {
|
|
4046
|
+
return {
|
|
4047
|
+
type: "message",
|
|
4048
|
+
content: prompt,
|
|
4049
|
+
...options.agentType ? { agentType: options.agentType } : {},
|
|
4050
|
+
...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
|
|
4051
|
+
mode: "steer"
|
|
4052
|
+
};
|
|
4053
|
+
}
|
|
4054
|
+
function toolEventOf(payload, phase, timestamp) {
|
|
4055
|
+
return {
|
|
4056
|
+
tool: typeof payload?.name === "string" ? payload.name : "",
|
|
4057
|
+
phase,
|
|
4058
|
+
timestamp,
|
|
4059
|
+
...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
|
|
4060
|
+
...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
|
|
4061
|
+
...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
|
|
4062
|
+
};
|
|
4063
|
+
}
|
|
4064
|
+
function epochOf(value) {
|
|
4065
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
4066
|
+
if (typeof value !== "string") return void 0;
|
|
4067
|
+
const parsed = Date.parse(value);
|
|
4068
|
+
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
4069
|
+
}
|
|
3955
4070
|
function toAgentTimelineItem(message) {
|
|
3956
4071
|
if (message.type === "TOOL_USE") {
|
|
3957
4072
|
try {
|
|
@@ -4025,7 +4140,6 @@ var CoreAgentTaskSession = class {
|
|
|
4025
4140
|
_status = "opening";
|
|
4026
4141
|
_history = [];
|
|
4027
4142
|
_content = "";
|
|
4028
|
-
_queue = [];
|
|
4029
4143
|
isNewSession;
|
|
4030
4144
|
listeners = /* @__PURE__ */ new Map();
|
|
4031
4145
|
connection = null;
|
|
@@ -4044,10 +4158,36 @@ var CoreAgentTaskSession = class {
|
|
|
4044
4158
|
recoveryGeneration = 0;
|
|
4045
4159
|
recoveredTerminalReason;
|
|
4046
4160
|
recoveredTerminalUsage;
|
|
4161
|
+
// Polls that found no closing row although a terminal with usage was heard.
|
|
4162
|
+
endedPollsWithoutRow = 0;
|
|
4163
|
+
// The turn ids the running turn went by, and the highest box sequence seen in it. The Copilot
|
|
4164
|
+
// stream a dropped session falls back to replays the turn from what the history has, so it
|
|
4165
|
+
// repeats frames the box socket already delivered.
|
|
4166
|
+
turnIds = /* @__PURE__ */ new Set();
|
|
4167
|
+
turnSequenceHigh = -1;
|
|
4047
4168
|
cancelTimer = null;
|
|
4048
|
-
|
|
4169
|
+
// Messages leave in the order they were sent: each one is handed over only after the one
|
|
4170
|
+
// before it was, not after it was answered.
|
|
4171
|
+
handOff = Promise.resolve();
|
|
4049
4172
|
activeWaiter;
|
|
4173
|
+
// Every steer sits in exactly one of the two lists until it is settled or forgotten: `steers`
|
|
4174
|
+
// while the turn it was sent into runs (taken ones settle with that turn), `strayedSteers` once
|
|
4175
|
+
// it waits for a turn of its own (sent with no turn, not taken when its turn ended, or queued by
|
|
4176
|
+
// the provider). A non-empty `strayedSteers` keeps the session busy, which is what stops a new
|
|
4177
|
+
// message from opening a turn the steer's answer would settle. `pendingSteers` counts the ones
|
|
4178
|
+
// the box has not answered yet, wherever they sit.
|
|
4179
|
+
steers = [];
|
|
4180
|
+
strayedSteers = [];
|
|
4181
|
+
pendingSteers = 0;
|
|
4182
|
+
// The id the message that opened the current turn went out with, so a refusal naming it fails
|
|
4183
|
+
// that turn and one naming a steer does not.
|
|
4184
|
+
openingMessageId;
|
|
4185
|
+
// The opening message went to the box, which starts its turn with a `stepStart`. Until then a
|
|
4186
|
+
// turn frame naming a turn is another turn's tail: the one before, closed here from the history
|
|
4187
|
+
// (r5 S17, dev 2026-10-19), whose live end came after the next message went out.
|
|
4188
|
+
openingAwaitsStart = false;
|
|
4050
4189
|
turnBaselineIds = /* @__PURE__ */ new Set();
|
|
4190
|
+
subagentsById = /* @__PURE__ */ new Map();
|
|
4051
4191
|
get taskId() {
|
|
4052
4192
|
return this._taskId;
|
|
4053
4193
|
}
|
|
@@ -4067,19 +4207,16 @@ var CoreAgentTaskSession = class {
|
|
|
4067
4207
|
return this._content;
|
|
4068
4208
|
}
|
|
4069
4209
|
get queue() {
|
|
4070
|
-
return
|
|
4071
|
-
|
|
4072
|
-
|
|
4073
|
-
|
|
4074
|
-
...item.agentType ? { agentType: item.agentType } : {},
|
|
4075
|
-
...item.reasoningEffort ? { reasoningEffort: item.reasoningEffort } : {}
|
|
4076
|
-
}));
|
|
4210
|
+
return [];
|
|
4211
|
+
}
|
|
4212
|
+
get subagents() {
|
|
4213
|
+
return [...this.subagentsById.values()];
|
|
4077
4214
|
}
|
|
4078
4215
|
send(prompt, options = {}) {
|
|
4079
4216
|
this.requireOpen();
|
|
4080
4217
|
if (!prompt.trim()) return;
|
|
4081
4218
|
if (this.isBusy()) {
|
|
4082
|
-
this.
|
|
4219
|
+
this.steer(prompt, options);
|
|
4083
4220
|
return;
|
|
4084
4221
|
}
|
|
4085
4222
|
this.startDispatch(prompt, options);
|
|
@@ -4094,8 +4231,7 @@ var CoreAgentTaskSession = class {
|
|
|
4094
4231
|
...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
|
|
4095
4232
|
};
|
|
4096
4233
|
if (this.isBusy()) {
|
|
4097
|
-
|
|
4098
|
-
if (queueId) waiter.queueId = queueId;
|
|
4234
|
+
this.steer(prompt, sendOptions, waiter);
|
|
4099
4235
|
return waiter.promise;
|
|
4100
4236
|
}
|
|
4101
4237
|
this.startDispatch(prompt, sendOptions, waiter);
|
|
@@ -4130,6 +4266,17 @@ var CoreAgentTaskSession = class {
|
|
|
4130
4266
|
this.emitError("Failed to answer Agent approval", error);
|
|
4131
4267
|
});
|
|
4132
4268
|
}
|
|
4269
|
+
respondUserInput(requestId, answers, attachmentsByQuestionId) {
|
|
4270
|
+
const input = {
|
|
4271
|
+
type: "runtime-request.respond",
|
|
4272
|
+
requestId,
|
|
4273
|
+
answers,
|
|
4274
|
+
...attachmentsByQuestionId ? { attachmentsByQuestionId } : {}
|
|
4275
|
+
};
|
|
4276
|
+
void this.sendInput(input).catch((error) => {
|
|
4277
|
+
this.emitError("Failed to answer Agent input request", error);
|
|
4278
|
+
});
|
|
4279
|
+
}
|
|
4133
4280
|
async loadHistory(options = {}) {
|
|
4134
4281
|
if (!this._taskId) return [];
|
|
4135
4282
|
const page = await this.dependencies.tasks.listMessages(this._taskId, {
|
|
@@ -4141,26 +4288,17 @@ var CoreAgentTaskSession = class {
|
|
|
4141
4288
|
this.emit("historyLoaded", { history });
|
|
4142
4289
|
return history;
|
|
4143
4290
|
}
|
|
4144
|
-
editQueueItem(
|
|
4145
|
-
if (!text.trim()) {
|
|
4146
|
-
this.removeQueueItem(id);
|
|
4147
|
-
return;
|
|
4148
|
-
}
|
|
4149
|
-
this._queue = this._queue.map((item) => item.id === id ? { ...item, text } : item);
|
|
4150
|
-
this.emitQueue();
|
|
4291
|
+
editQueueItem() {
|
|
4151
4292
|
}
|
|
4152
|
-
removeQueueItem(
|
|
4153
|
-
const removed = this._queue.find((item) => item.id === id);
|
|
4154
|
-
this._queue = this._queue.filter((item) => item.id !== id);
|
|
4155
|
-
removed?.waiter?.reject(new Error("Queued Agent prompt was removed."));
|
|
4156
|
-
this.emitQueue();
|
|
4293
|
+
removeQueueItem() {
|
|
4157
4294
|
}
|
|
4158
4295
|
clearQueue() {
|
|
4159
|
-
|
|
4160
|
-
|
|
4161
|
-
this.
|
|
4162
|
-
|
|
4163
|
-
|
|
4296
|
+
}
|
|
4297
|
+
stopSubagent(subagentId) {
|
|
4298
|
+
this.requireOpen();
|
|
4299
|
+
void this.sendInput({ type: "subagent.stop", subagentId }).catch((error) => {
|
|
4300
|
+
this.emitError("Failed to stop the Agent subagent", error);
|
|
4301
|
+
});
|
|
4164
4302
|
}
|
|
4165
4303
|
on(event, handler) {
|
|
4166
4304
|
let listeners = this.listeners.get(event);
|
|
@@ -4185,8 +4323,7 @@ var CoreAgentTaskSession = class {
|
|
|
4185
4323
|
const closedError = new Error("Agent task session is closed.");
|
|
4186
4324
|
this.activeWaiter?.reject(closedError);
|
|
4187
4325
|
this.activeWaiter = void 0;
|
|
4188
|
-
|
|
4189
|
-
this._queue = [];
|
|
4326
|
+
this.rejectSteers(closedError);
|
|
4190
4327
|
if (this._taskId) this.dependencies.onClose(this._taskId, this);
|
|
4191
4328
|
for (const listeners of this.listeners.values()) listeners.clear();
|
|
4192
4329
|
}
|
|
@@ -4209,31 +4346,32 @@ var CoreAgentTaskSession = class {
|
|
|
4209
4346
|
}
|
|
4210
4347
|
startDispatch(prompt, options, waiter) {
|
|
4211
4348
|
this.dispatching = true;
|
|
4212
|
-
|
|
4349
|
+
let handedOver;
|
|
4350
|
+
this.handOff = new Promise((resolve) => {
|
|
4351
|
+
handedOver = resolve;
|
|
4352
|
+
});
|
|
4353
|
+
const dispatch = this.dispatchSend(prompt, options, handedOver, waiter).catch((error) => {
|
|
4213
4354
|
waiter?.reject(error);
|
|
4214
4355
|
this.emitError("Failed to send Agent prompt", error);
|
|
4215
|
-
if (this._status === "streaming")
|
|
4216
|
-
|
|
4356
|
+
if (this._status === "streaming") {
|
|
4357
|
+
this.settleSteers((steered) => steered.reject(error));
|
|
4358
|
+
this.setStatus("idle");
|
|
4359
|
+
}
|
|
4217
4360
|
return false;
|
|
4218
4361
|
}).finally(() => {
|
|
4362
|
+
handedOver();
|
|
4219
4363
|
this.dispatching = false;
|
|
4220
4364
|
if (this.dispatch === dispatch) this.dispatch = null;
|
|
4221
|
-
if (this._status === "idle") this.flushQueue();
|
|
4222
4365
|
});
|
|
4223
4366
|
this.dispatch = dispatch;
|
|
4224
4367
|
}
|
|
4225
|
-
async dispatchSend(prompt, options, waiter) {
|
|
4368
|
+
async dispatchSend(prompt, options, handedOver, waiter) {
|
|
4226
4369
|
if (this.openingPromise && !await this.openingPromise) {
|
|
4227
4370
|
throw new Error("Agent task session could not be opened.");
|
|
4228
4371
|
}
|
|
4229
4372
|
if (this.isClosed() || waiter?.settled) return false;
|
|
4230
4373
|
await this.ensureTask();
|
|
4231
|
-
const input =
|
|
4232
|
-
type: "message",
|
|
4233
|
-
content: prompt,
|
|
4234
|
-
...options.agentType ? { agentType: options.agentType } : {},
|
|
4235
|
-
...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
|
|
4236
|
-
};
|
|
4374
|
+
const input = messageInput(prompt, options);
|
|
4237
4375
|
if (this.isClosed()) {
|
|
4238
4376
|
await this.sendInput(input).catch(() => void 0);
|
|
4239
4377
|
return false;
|
|
@@ -4250,10 +4388,134 @@ var CoreAgentTaskSession = class {
|
|
|
4250
4388
|
this.activeWaiter = waiter;
|
|
4251
4389
|
this.setStatus("streaming");
|
|
4252
4390
|
this.emit("turnStart", {});
|
|
4253
|
-
|
|
4391
|
+
this.openingMessageId = newClientMessageId();
|
|
4392
|
+
this.openingAwaitsStart = true;
|
|
4393
|
+
const { admitted, direct } = await this.handOver(input, this.openingMessageId);
|
|
4394
|
+
if (!direct) this.openingAwaitsStart = false;
|
|
4395
|
+
handedOver();
|
|
4396
|
+
if (!await admitted) return false;
|
|
4254
4397
|
this.emit("accepted", {});
|
|
4255
4398
|
return true;
|
|
4256
4399
|
}
|
|
4400
|
+
// A message sent while a turn runs, or is being opened, goes out at once: the box takes it into
|
|
4401
|
+
// that turn (the provider's own steering), queues it for a turn of its own, or gives it one when
|
|
4402
|
+
// that turn already ended. Nothing waits in this session. On the direct channel it goes with an
|
|
4403
|
+
// id the box echoes on the frame that takes it; without the channel, over REST to the Copilot,
|
|
4404
|
+
// which holds it while the box boots.
|
|
4405
|
+
//
|
|
4406
|
+
// It keeps its `agentType` and `reasoningEffort` on the box, which leaves the running turn's
|
|
4407
|
+
// model alone by itself and needs them for a message that becomes a turn of its own. Only on
|
|
4408
|
+
// the Copilot path, with a turn running, they are dropped: the Copilot restarts the live
|
|
4409
|
+
// session for a message that asks for another model, which would end that turn.
|
|
4410
|
+
steer(prompt, options, waiter) {
|
|
4411
|
+
const steered = {
|
|
4412
|
+
clientMessageId: newClientMessageId(),
|
|
4413
|
+
...waiter ? { waiter } : {},
|
|
4414
|
+
taken: false
|
|
4415
|
+
};
|
|
4416
|
+
if (this.dispatching || this._status === "streaming" || this._status === "cancelled") {
|
|
4417
|
+
this.steers.push(steered);
|
|
4418
|
+
} else {
|
|
4419
|
+
this.strayedSteers.push(steered);
|
|
4420
|
+
}
|
|
4421
|
+
const input = messageInput(prompt, options);
|
|
4422
|
+
this.pendingSteers += 1;
|
|
4423
|
+
const handed = this.handOff.then(async () => {
|
|
4424
|
+
if (this.isClosed()) throw new Error("Agent task session is closed.");
|
|
4425
|
+
await this.prepareSend();
|
|
4426
|
+
if (this.isClosed()) throw new Error("Agent task session is closed.");
|
|
4427
|
+
return this.handOver(input, steered.clientMessageId, true);
|
|
4428
|
+
});
|
|
4429
|
+
this.handOff = handed.then(
|
|
4430
|
+
() => void 0,
|
|
4431
|
+
() => void 0
|
|
4432
|
+
);
|
|
4433
|
+
void handed.then(({ admitted }) => admitted).then((admitted) => {
|
|
4434
|
+
if (!admitted) {
|
|
4435
|
+
this.forgetSteer(steered);
|
|
4436
|
+
waiter?.reject(
|
|
4437
|
+
steered.refusal ?? new AgentTaskTurnError("The Agent box did not take the message.")
|
|
4438
|
+
);
|
|
4439
|
+
return;
|
|
4440
|
+
}
|
|
4441
|
+
if (!steered.queued) this.steerTaken(steered);
|
|
4442
|
+
this.emit("accepted", {});
|
|
4443
|
+
}).catch((error) => {
|
|
4444
|
+
this.forgetSteer(steered);
|
|
4445
|
+
waiter?.reject(error);
|
|
4446
|
+
this.emitError("Failed to send Agent prompt", error);
|
|
4447
|
+
}).finally(() => {
|
|
4448
|
+
this.pendingSteers -= 1;
|
|
4449
|
+
});
|
|
4450
|
+
}
|
|
4451
|
+
// The box took the steer. Into the turn it was sent to, when that turn still runs; into a turn
|
|
4452
|
+
// of its own, when that one ended before the box got to the message.
|
|
4453
|
+
steerTaken(steered) {
|
|
4454
|
+
if (steered.taken) return;
|
|
4455
|
+
steered.taken = true;
|
|
4456
|
+
if (!this.strayedSteers.includes(steered)) return;
|
|
4457
|
+
this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
|
|
4458
|
+
this.openTurnFor(steered.waiter);
|
|
4459
|
+
}
|
|
4460
|
+
steerOpenedBy(lifecycle) {
|
|
4461
|
+
const id = lifecycle?.clientMessageId;
|
|
4462
|
+
if (typeof id !== "string") return;
|
|
4463
|
+
const steered = [...this.steers, ...this.strayedSteers].find(
|
|
4464
|
+
(pending) => pending.clientMessageId === id
|
|
4465
|
+
);
|
|
4466
|
+
if (steered) this.steerTaken(steered);
|
|
4467
|
+
}
|
|
4468
|
+
// Queued behind the running turn, the message is answered by the turn the box opens for it
|
|
4469
|
+
// later, not by this one.
|
|
4470
|
+
steerQueuedBy(lifecycle) {
|
|
4471
|
+
const id = lifecycle?.clientMessageId;
|
|
4472
|
+
if (typeof id !== "string") return;
|
|
4473
|
+
const steered = [...this.steers, ...this.strayedSteers].find(
|
|
4474
|
+
(pending) => pending.clientMessageId === id
|
|
4475
|
+
);
|
|
4476
|
+
if (!steered || steered.taken) return;
|
|
4477
|
+
steered.queued = true;
|
|
4478
|
+
if (!this.steers.includes(steered)) return;
|
|
4479
|
+
this.steers = this.steers.filter((pending) => pending !== steered);
|
|
4480
|
+
this.strayedSteers.push(steered);
|
|
4481
|
+
}
|
|
4482
|
+
forgetSteer(steered) {
|
|
4483
|
+
this.steers = this.steers.filter((pending) => pending !== steered);
|
|
4484
|
+
this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
|
|
4485
|
+
}
|
|
4486
|
+
// The turn ended: what the box took is answered by it, what it had not taken yet waits for the
|
|
4487
|
+
// turn the box opens for it.
|
|
4488
|
+
settleSteers(settle) {
|
|
4489
|
+
const steers = this.steers;
|
|
4490
|
+
this.steers = [];
|
|
4491
|
+
for (const steered of steers) {
|
|
4492
|
+
if (!steered.taken) this.strayedSteers.push(steered);
|
|
4493
|
+
else if (steered.waiter) settle(steered.waiter);
|
|
4494
|
+
}
|
|
4495
|
+
}
|
|
4496
|
+
openTurnFor(waiter) {
|
|
4497
|
+
if (this.isClosed()) return;
|
|
4498
|
+
if (this._status !== "streaming" && this._status !== "cancelled") {
|
|
4499
|
+
this._content = "";
|
|
4500
|
+
this.recoveryUsed = false;
|
|
4501
|
+
this.recoveredTerminalReason = void 0;
|
|
4502
|
+
this.recoveredTerminalUsage = void 0;
|
|
4503
|
+
this.recoveryGeneration += 1;
|
|
4504
|
+
this.turnBaselineIds = new Set(this._history.map((item) => item.id));
|
|
4505
|
+
void this.captureTurnBaseline().catch(() => void 0);
|
|
4506
|
+
this.setStatus("streaming");
|
|
4507
|
+
this.emit("turnStart", {});
|
|
4508
|
+
}
|
|
4509
|
+
if (!waiter) return;
|
|
4510
|
+
if (!this.activeWaiter) this.activeWaiter = waiter;
|
|
4511
|
+
else this.steers.push({ clientMessageId: "", waiter, taken: true });
|
|
4512
|
+
}
|
|
4513
|
+
rejectSteers(error) {
|
|
4514
|
+
const steers = [...this.steers, ...this.strayedSteers];
|
|
4515
|
+
this.steers = [];
|
|
4516
|
+
this.strayedSteers = [];
|
|
4517
|
+
for (const steered of steers) steered.waiter?.reject(error);
|
|
4518
|
+
}
|
|
4257
4519
|
async ensureTask() {
|
|
4258
4520
|
if (this._taskId) return;
|
|
4259
4521
|
if (!("create" in this.options)) throw new Error("Agent task session has no task.");
|
|
@@ -4324,10 +4586,8 @@ var CoreAgentTaskSession = class {
|
|
|
4324
4586
|
try {
|
|
4325
4587
|
await this.ensureChannel();
|
|
4326
4588
|
while (generation === this.recoveryGeneration && !this.isClosed() && (this._status === "streaming" || this._status === "cancelled")) {
|
|
4327
|
-
|
|
4328
|
-
|
|
4329
|
-
}
|
|
4330
|
-
if (this.activeWaiter?.settled) return;
|
|
4589
|
+
const reason = this.recoveredTerminalReason ?? (this._status === "cancelled" ? "interrupted" : "reconciled");
|
|
4590
|
+
if (await this.reconcilePersistedTurn(reason)) return;
|
|
4331
4591
|
await delay(RECONCILE_DELAY_MS);
|
|
4332
4592
|
}
|
|
4333
4593
|
} catch (error) {
|
|
@@ -4353,9 +4613,22 @@ var CoreAgentTaskSession = class {
|
|
|
4353
4613
|
this._history = [...page.content].reverse().map(toAgentTimelineItem);
|
|
4354
4614
|
this.emit("historyLoaded", { history: this.history });
|
|
4355
4615
|
const recovered = page.content.find(
|
|
4356
|
-
(message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
|
|
4616
|
+
(message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE" && (message.type === "ERROR" || this.closesThisTurn(message))
|
|
4357
4617
|
);
|
|
4358
|
-
if (!recovered)
|
|
4618
|
+
if (!recovered) {
|
|
4619
|
+
if (this.recoveredTerminalReason === void 0) return false;
|
|
4620
|
+
if (this.recoveredTerminalUsage !== void 0) {
|
|
4621
|
+
this.endedPollsWithoutRow += 1;
|
|
4622
|
+
if (this.endedPollsWithoutRow < ENDED_POLLS_BEFORE_NEWEST) return false;
|
|
4623
|
+
}
|
|
4624
|
+
const newest = page.content.find(
|
|
4625
|
+
(message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
|
|
4626
|
+
);
|
|
4627
|
+
if (!newest) return false;
|
|
4628
|
+
this._content = newest.content;
|
|
4629
|
+
this.finishTurn(reason, this.recoveredTerminalUsage);
|
|
4630
|
+
return true;
|
|
4631
|
+
}
|
|
4359
4632
|
if (recovered.type === "ERROR") {
|
|
4360
4633
|
const error = new AgentTaskTurnError(recovered.content);
|
|
4361
4634
|
this.emit("error", { error: error.message });
|
|
@@ -4366,17 +4639,66 @@ var CoreAgentTaskSession = class {
|
|
|
4366
4639
|
this.finishTurn(reason, recovered.usage ?? this.recoveredTerminalUsage);
|
|
4367
4640
|
return true;
|
|
4368
4641
|
}
|
|
4642
|
+
closesThisTurn(message) {
|
|
4643
|
+
if (!message.usage) return false;
|
|
4644
|
+
const prompt = message.usage.requestMessageId;
|
|
4645
|
+
return prompt === void 0 || !this.turnBaselineIds.has(prompt);
|
|
4646
|
+
}
|
|
4369
4647
|
/** True once the server took the input; false when the box refused it on the stream. */
|
|
4370
4648
|
async sendInput(input) {
|
|
4649
|
+
return (await this.handOver(input)).admitted;
|
|
4650
|
+
}
|
|
4651
|
+
// Resolves once the input left this session; `admitted` then says whether the server took it.
|
|
4652
|
+
// Wrapped so that awaiting the hand-over does not also await the answer.
|
|
4653
|
+
async handOver(input, clientMessageId, steering = false) {
|
|
4371
4654
|
if (!this._taskId) throw new Error("Agent task has not been created.");
|
|
4372
|
-
const direct = this.dependencies.channel.send(this._taskId, input);
|
|
4373
|
-
if (direct) return direct;
|
|
4374
|
-
|
|
4375
|
-
|
|
4655
|
+
const direct = this.dependencies.channel.send(this._taskId, input, clientMessageId);
|
|
4656
|
+
if (direct) return { admitted: direct, direct: true };
|
|
4657
|
+
if (input.type === "runtime-request.respond") {
|
|
4658
|
+
throw new Error(
|
|
4659
|
+
"The answer to the Agent input request was not sent: the box channel is not connected right now."
|
|
4660
|
+
);
|
|
4661
|
+
}
|
|
4662
|
+
if (!COPILOT_INPUT_TYPES.has(input.type)) {
|
|
4663
|
+
throw new Error(
|
|
4664
|
+
`The Agent ${input.type} was not sent: the box channel is not connected right now.`
|
|
4665
|
+
);
|
|
4666
|
+
}
|
|
4667
|
+
const turnRunning = this._status === "streaming" || this._status === "cancelled";
|
|
4668
|
+
const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content } : {
|
|
4669
|
+
type: "message",
|
|
4670
|
+
content: input.content,
|
|
4671
|
+
...input.agentType ? { agentType: input.agentType } : {},
|
|
4672
|
+
...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {}
|
|
4673
|
+
};
|
|
4674
|
+
await this.dependencies.tasks.sendInput(this._taskId, rest);
|
|
4675
|
+
return { admitted: Promise.resolve(true), direct: false };
|
|
4676
|
+
}
|
|
4677
|
+
async prepareSend() {
|
|
4678
|
+
if (this.openingPromise && !await this.openingPromise) {
|
|
4679
|
+
throw new Error("Agent task session could not be opened.");
|
|
4680
|
+
}
|
|
4681
|
+
await this.ensureTask();
|
|
4682
|
+
if (!this.isClosed()) await this.ensureChannel();
|
|
4376
4683
|
}
|
|
4377
4684
|
handleEvent(event) {
|
|
4378
4685
|
this.emit("raw", event);
|
|
4379
4686
|
const payload = asObject2(event.payload);
|
|
4687
|
+
if (payload && isSubagentFrame(event)) {
|
|
4688
|
+
this.handleSubagentFrame(event, payload);
|
|
4689
|
+
return;
|
|
4690
|
+
}
|
|
4691
|
+
const lifecycle = asObject2(payload?.lifecycle);
|
|
4692
|
+
if (this.repeatsTheRunningTurn(event, lifecycle)) return;
|
|
4693
|
+
if (event.type === "stepStart" || event.type === "steer") {
|
|
4694
|
+
const id = lifecycle?.clientMessageId;
|
|
4695
|
+
if (id === this.openingMessageId || id === void 0 && event.type === "stepStart") {
|
|
4696
|
+
this.openingAwaitsStart = false;
|
|
4697
|
+
this.forgetFinishedTurn(lifecycle);
|
|
4698
|
+
}
|
|
4699
|
+
} else if (this.openingAwaitsStart && TURN_TAIL_TYPES.has(event.type) && typeof lifecycle?.turnId === "string") {
|
|
4700
|
+
this.rememberFinishedTurn(lifecycle);
|
|
4701
|
+
}
|
|
4380
4702
|
switch (event.type) {
|
|
4381
4703
|
// A box transmite o texto do agente ao vivo em `textDelta` e grava o mesmo texto no log
|
|
4382
4704
|
// como `textChunk`. Uma repeticao depois de uma queda devolve chunks, entao trata-los como
|
|
@@ -4389,14 +4711,30 @@ var CoreAgentTaskSession = class {
|
|
|
4389
4711
|
this.consumeDelta(payload, "thinking");
|
|
4390
4712
|
break;
|
|
4391
4713
|
case "toolCall":
|
|
4392
|
-
this.emitTool(payload, "call", event.timestamp);
|
|
4714
|
+
if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "call", event.timestamp);
|
|
4393
4715
|
break;
|
|
4394
4716
|
case "toolResult":
|
|
4395
|
-
this.emitTool(payload, "result", event.timestamp);
|
|
4717
|
+
if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "result", event.timestamp);
|
|
4396
4718
|
break;
|
|
4397
4719
|
case "workspace":
|
|
4398
4720
|
this.emit("workspace", { payload: event.payload, timestamp: event.timestamp });
|
|
4399
4721
|
break;
|
|
4722
|
+
case "stepStart":
|
|
4723
|
+
this.steerOpenedBy(asObject2(payload?.lifecycle));
|
|
4724
|
+
break;
|
|
4725
|
+
case "steer":
|
|
4726
|
+
this.steerOpenedBy(lifecycle);
|
|
4727
|
+
this.emit("steered", {
|
|
4728
|
+
text: typeof payload?.text === "string" ? payload.text : "",
|
|
4729
|
+
messageId: typeof payload?.messageId === "string" ? payload.messageId : ""
|
|
4730
|
+
});
|
|
4731
|
+
break;
|
|
4732
|
+
case "messageQueued":
|
|
4733
|
+
this.steerQueuedBy(asObject2(payload?.lifecycle));
|
|
4734
|
+
break;
|
|
4735
|
+
case "subagentUpdate":
|
|
4736
|
+
this.applySubagent(payload);
|
|
4737
|
+
break;
|
|
4400
4738
|
case "providerUsage": {
|
|
4401
4739
|
const usage = providerUsageOf(payload);
|
|
4402
4740
|
if (usage) this.emit("providerUsage", usage);
|
|
@@ -4404,15 +4742,17 @@ var CoreAgentTaskSession = class {
|
|
|
4404
4742
|
}
|
|
4405
4743
|
case "stepFinish": {
|
|
4406
4744
|
const reason = typeof payload?.reason === "string" ? payload.reason : "unknown";
|
|
4407
|
-
const
|
|
4745
|
+
const lifecycle2 = payload?.lifecycle;
|
|
4408
4746
|
const usage = agentTurnUsageOf(payload?.usage);
|
|
4409
|
-
|
|
4410
|
-
|
|
4747
|
+
const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
|
|
4748
|
+
if (finished !== void 0 && this.finishedTurnIds.includes(finished)) break;
|
|
4749
|
+
if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
|
|
4750
|
+
this.rememberFinishedTurn(lifecycle2);
|
|
4411
4751
|
this.finishTurn("interrupted", usage);
|
|
4412
4752
|
break;
|
|
4413
4753
|
}
|
|
4414
4754
|
if (reason === "stop" || reason === "endTurn") {
|
|
4415
|
-
this.rememberFinishedTurn(
|
|
4755
|
+
this.rememberFinishedTurn(lifecycle2);
|
|
4416
4756
|
if (this.recoveryUsed) {
|
|
4417
4757
|
this.recoveredTerminalReason = reason;
|
|
4418
4758
|
this.recoveredTerminalUsage = usage;
|
|
@@ -4432,6 +4772,17 @@ var CoreAgentTaskSession = class {
|
|
|
4432
4772
|
const code = typeof payload?.code === "string" ? payload.code : void 0;
|
|
4433
4773
|
const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
|
|
4434
4774
|
this.emit("error", { ...code ? { code } : {}, error: message });
|
|
4775
|
+
if (!payload?.lifecycle && payload?.requestId !== void 0) break;
|
|
4776
|
+
const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
|
|
4777
|
+
if (typeof refused === "string") {
|
|
4778
|
+
if (refused !== this.openingMessageId) {
|
|
4779
|
+
const steered = [...this.steers, ...this.strayedSteers].find(
|
|
4780
|
+
(pending) => pending.clientMessageId === refused
|
|
4781
|
+
);
|
|
4782
|
+
if (steered) steered.refusal = new AgentTaskTurnError(message, code);
|
|
4783
|
+
break;
|
|
4784
|
+
}
|
|
4785
|
+
} else if (!payload?.lifecycle && !this.dispatching && this.pendingSteers > 0) break;
|
|
4435
4786
|
if (this._status === "streaming" || this._status === "cancelled") {
|
|
4436
4787
|
this.failTurn(new AgentTaskTurnError(message, code));
|
|
4437
4788
|
}
|
|
@@ -4441,6 +4792,27 @@ var CoreAgentTaskSession = class {
|
|
|
4441
4792
|
break;
|
|
4442
4793
|
}
|
|
4443
4794
|
}
|
|
4795
|
+
repeatsTheRunningTurn(event, lifecycle) {
|
|
4796
|
+
if (this._status !== "streaming" && this._status !== "cancelled") return false;
|
|
4797
|
+
const turnId = lifecycle?.turnId;
|
|
4798
|
+
if (typeof turnId !== "string") return false;
|
|
4799
|
+
if (typeof event.sequence === "number") {
|
|
4800
|
+
if (this.turnIds.has(turnId) && event.sequence <= this.turnSequenceHigh) return true;
|
|
4801
|
+
this.turnSequenceHigh = Math.max(this.turnSequenceHigh, event.sequence);
|
|
4802
|
+
}
|
|
4803
|
+
this.turnIds.add(turnId);
|
|
4804
|
+
return false;
|
|
4805
|
+
}
|
|
4806
|
+
isFinishedTurnFrame(lifecycle) {
|
|
4807
|
+
const turnId = lifecycle?.turnId;
|
|
4808
|
+
return typeof turnId === "string" && this.finishedTurnIds.includes(turnId);
|
|
4809
|
+
}
|
|
4810
|
+
forgetFinishedTurn(lifecycle) {
|
|
4811
|
+
const turnId = lifecycle?.turnId;
|
|
4812
|
+
if (typeof turnId !== "string") return;
|
|
4813
|
+
const index = this.finishedTurnIds.indexOf(turnId);
|
|
4814
|
+
if (index >= 0) this.finishedTurnIds.splice(index, 1);
|
|
4815
|
+
}
|
|
4444
4816
|
rememberFinishedTurn(lifecycle) {
|
|
4445
4817
|
const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
|
|
4446
4818
|
if (!turnId) return;
|
|
@@ -4462,14 +4834,52 @@ var CoreAgentTaskSession = class {
|
|
|
4462
4834
|
this.emit("delta", { delta: text, kind });
|
|
4463
4835
|
}
|
|
4464
4836
|
emitTool(payload, phase, timestamp) {
|
|
4465
|
-
this.emit("tool",
|
|
4466
|
-
|
|
4467
|
-
|
|
4468
|
-
|
|
4469
|
-
|
|
4470
|
-
|
|
4471
|
-
|
|
4472
|
-
|
|
4837
|
+
this.emit("tool", toolEventOf(payload, phase, timestamp));
|
|
4838
|
+
}
|
|
4839
|
+
// A child thread's frames are the subagent's conversation: they open no turn, settle no message
|
|
4840
|
+
// and never reach the chat's `content`.
|
|
4841
|
+
handleSubagentFrame(event, payload) {
|
|
4842
|
+
const parentToolId = payload.parentToolId;
|
|
4843
|
+
switch (event.type) {
|
|
4844
|
+
case "textDelta":
|
|
4845
|
+
case "textChunk":
|
|
4846
|
+
case "thinking":
|
|
4847
|
+
this.emit("subagentDelta", {
|
|
4848
|
+
parentToolId,
|
|
4849
|
+
delta: typeof payload.text === "string" ? payload.text : "",
|
|
4850
|
+
kind: event.type === "thinking" ? "thinking" : "text"
|
|
4851
|
+
});
|
|
4852
|
+
break;
|
|
4853
|
+
case "toolCall":
|
|
4854
|
+
case "toolResult":
|
|
4855
|
+
this.emit("subagentTool", {
|
|
4856
|
+
...toolEventOf(payload, event.type === "toolCall" ? "call" : "result", event.timestamp),
|
|
4857
|
+
parentToolId
|
|
4858
|
+
});
|
|
4859
|
+
break;
|
|
4860
|
+
default:
|
|
4861
|
+
break;
|
|
4862
|
+
}
|
|
4863
|
+
}
|
|
4864
|
+
applySubagent(payload) {
|
|
4865
|
+
const subagentId = payload?.subagentId;
|
|
4866
|
+
const toolId = payload?.toolId;
|
|
4867
|
+
if (typeof subagentId !== "string" || typeof toolId !== "string") return;
|
|
4868
|
+
const status = typeof payload?.status === "string" ? payload.status : this.subagentsById.get(subagentId)?.status;
|
|
4869
|
+
if (status === void 0) return;
|
|
4870
|
+
const startedAt = epochOf(payload?.startedAt);
|
|
4871
|
+
const endedAt = epochOf(payload?.endedAt);
|
|
4872
|
+
const subagent = {
|
|
4873
|
+
subagentId,
|
|
4874
|
+
toolId,
|
|
4875
|
+
status,
|
|
4876
|
+
...typeof payload?.progress === "string" ? { progress: payload.progress } : {},
|
|
4877
|
+
...startedAt !== void 0 ? { startedAt } : {},
|
|
4878
|
+
...endedAt !== void 0 ? { endedAt } : {},
|
|
4879
|
+
...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
|
|
4880
|
+
};
|
|
4881
|
+
this.subagentsById.set(subagentId, subagent);
|
|
4882
|
+
this.emit("subagent", subagent);
|
|
4473
4883
|
}
|
|
4474
4884
|
finishTurn(reason, usage) {
|
|
4475
4885
|
if (this._status !== "streaming" && this._status !== "cancelled") return;
|
|
@@ -4494,8 +4904,8 @@ var CoreAgentTaskSession = class {
|
|
|
4494
4904
|
this.emit("turnEnd", result);
|
|
4495
4905
|
this.activeWaiter?.resolve(result);
|
|
4496
4906
|
this.activeWaiter = void 0;
|
|
4907
|
+
this.settleSteers((waiter) => waiter.resolve(result));
|
|
4497
4908
|
this.setStatus("idle");
|
|
4498
|
-
this.flushQueue();
|
|
4499
4909
|
}
|
|
4500
4910
|
failTurn(error) {
|
|
4501
4911
|
if (this.cancelTimer) clearTimeout(this.cancelTimer);
|
|
@@ -4503,56 +4913,17 @@ var CoreAgentTaskSession = class {
|
|
|
4503
4913
|
this.recoveryGeneration += 1;
|
|
4504
4914
|
this.activeWaiter?.reject(error);
|
|
4505
4915
|
this.activeWaiter = void 0;
|
|
4916
|
+
this.settleSteers((waiter) => waiter.reject(error));
|
|
4506
4917
|
this.setStatus("idle");
|
|
4507
|
-
this.flushQueue();
|
|
4508
4918
|
}
|
|
4509
4919
|
failLiveChannel(observed, waiterError) {
|
|
4510
4920
|
this.recoveryGeneration += 1;
|
|
4511
4921
|
this.emitError("Agent live channel failed", observed);
|
|
4512
4922
|
this.activeWaiter?.reject(waiterError);
|
|
4513
4923
|
this.activeWaiter = void 0;
|
|
4514
|
-
|
|
4515
|
-
this._queue = [];
|
|
4516
|
-
this.emitQueue();
|
|
4924
|
+
this.rejectSteers(waiterError);
|
|
4517
4925
|
this.setStatus("error");
|
|
4518
4926
|
}
|
|
4519
|
-
enqueue(text, options, waiter) {
|
|
4520
|
-
if (this._queue.length >= AGENT_QUEUE_LIMIT) {
|
|
4521
|
-
const error = new Error(`Agent message queue is full (maximum ${AGENT_QUEUE_LIMIT}).`);
|
|
4522
|
-
waiter?.reject(error);
|
|
4523
|
-
this.emit("error", { error: error.message });
|
|
4524
|
-
return void 0;
|
|
4525
|
-
}
|
|
4526
|
-
const id = `q-${++this.queueSequence}`;
|
|
4527
|
-
this._queue = [
|
|
4528
|
-
...this._queue,
|
|
4529
|
-
{ id, text, createdAt: Date.now(), ...options, ...waiter ? { waiter } : {} }
|
|
4530
|
-
];
|
|
4531
|
-
this.emitQueue();
|
|
4532
|
-
return id;
|
|
4533
|
-
}
|
|
4534
|
-
flushQueue() {
|
|
4535
|
-
if (this.isBusy()) return;
|
|
4536
|
-
let next = this._queue[0];
|
|
4537
|
-
while (next?.waiter?.settled) {
|
|
4538
|
-
this._queue = this._queue.slice(1);
|
|
4539
|
-
next = this._queue[0];
|
|
4540
|
-
}
|
|
4541
|
-
if (!next) {
|
|
4542
|
-
this.emitQueue();
|
|
4543
|
-
return;
|
|
4544
|
-
}
|
|
4545
|
-
this._queue = this._queue.slice(1);
|
|
4546
|
-
this.emitQueue();
|
|
4547
|
-
this.startDispatch(
|
|
4548
|
-
next.text,
|
|
4549
|
-
{
|
|
4550
|
-
...next.agentType ? { agentType: next.agentType } : {},
|
|
4551
|
-
...next.reasoningEffort ? { reasoningEffort: next.reasoningEffort } : {}
|
|
4552
|
-
},
|
|
4553
|
-
next.waiter
|
|
4554
|
-
);
|
|
4555
|
-
}
|
|
4556
4927
|
createWaiter(options) {
|
|
4557
4928
|
let resolvePromise;
|
|
4558
4929
|
let rejectPromise;
|
|
@@ -4574,7 +4945,6 @@ var CoreAgentTaskSession = class {
|
|
|
4574
4945
|
if (waiter.settled) return;
|
|
4575
4946
|
waiter.settled = true;
|
|
4576
4947
|
waiter.cleanup();
|
|
4577
|
-
if (waiter.queueId) this.removeQueuedWaiter(waiter.queueId);
|
|
4578
4948
|
rejectPromise(error);
|
|
4579
4949
|
},
|
|
4580
4950
|
cleanup: () => {
|
|
@@ -4599,14 +4969,6 @@ var CoreAgentTaskSession = class {
|
|
|
4599
4969
|
}
|
|
4600
4970
|
return waiter;
|
|
4601
4971
|
}
|
|
4602
|
-
removeQueuedWaiter(id) {
|
|
4603
|
-
const size = this._queue.length;
|
|
4604
|
-
this._queue = this._queue.filter((item) => item.id !== id);
|
|
4605
|
-
if (this._queue.length !== size) this.emitQueue();
|
|
4606
|
-
}
|
|
4607
|
-
emitQueue() {
|
|
4608
|
-
this.emit("queueChange", { queue: this.queue });
|
|
4609
|
-
}
|
|
4610
4972
|
emitError(prefix, error) {
|
|
4611
4973
|
const code = errorCode(error);
|
|
4612
4974
|
this.emit("error", {
|
|
@@ -4616,6 +4978,12 @@ var CoreAgentTaskSession = class {
|
|
|
4616
4978
|
}
|
|
4617
4979
|
setStatus(status) {
|
|
4618
4980
|
if (this._status === status) return;
|
|
4981
|
+
if (status !== "streaming" && status !== "cancelled") {
|
|
4982
|
+
this.openingAwaitsStart = false;
|
|
4983
|
+
this.endedPollsWithoutRow = 0;
|
|
4984
|
+
this.turnIds.clear();
|
|
4985
|
+
this.turnSequenceHigh = -1;
|
|
4986
|
+
}
|
|
4619
4987
|
this._status = status;
|
|
4620
4988
|
this.emit("statusChange", { status });
|
|
4621
4989
|
}
|
|
@@ -4625,8 +4993,11 @@ var CoreAgentTaskSession = class {
|
|
|
4625
4993
|
isClosed() {
|
|
4626
4994
|
return this._status === "closed";
|
|
4627
4995
|
}
|
|
4996
|
+
// A turn running or being opened takes a new message as a steer. So does a session waiting for
|
|
4997
|
+
// the turn the box opens for a steer it took late: a new message started as a turn of its own
|
|
4998
|
+
// then would be answered by the steer's result, and the steer by its.
|
|
4628
4999
|
isBusy() {
|
|
4629
|
-
return this.dispatching || this._status === "streaming" || this._status === "cancelled";
|
|
5000
|
+
return this.dispatching || this._status === "streaming" || this._status === "cancelled" || this.strayedSteers.length > 0;
|
|
4630
5001
|
}
|
|
4631
5002
|
emit(event, payload) {
|
|
4632
5003
|
const listeners = this.listeners.get(event);
|