@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.cjs
CHANGED
|
@@ -508,6 +508,9 @@ function expectAppFields(app, context, errors) {
|
|
|
508
508
|
if (!isNullableString(app.icon)) invalidField(context, "icon", errors);
|
|
509
509
|
if (!isNullableString(app.template)) invalidField(context, "template", errors);
|
|
510
510
|
if (typeof app.allowSignup !== "boolean") invalidField(context, "allowSignup", errors);
|
|
511
|
+
for (const field of ["emailLoginEnabled", "passwordLoginEnabled"]) {
|
|
512
|
+
if (field in app && typeof app[field] !== "boolean") invalidField(context, field, errors);
|
|
513
|
+
}
|
|
511
514
|
if (typeof app.externalAccessEnabled !== "boolean") {
|
|
512
515
|
invalidField(context, "externalAccessEnabled", errors);
|
|
513
516
|
}
|
|
@@ -2932,9 +2935,31 @@ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
|
|
|
2932
2935
|
"Notify user response",
|
|
2933
2936
|
errors
|
|
2934
2937
|
);
|
|
2938
|
+
},
|
|
2939
|
+
async sendEmail(input) {
|
|
2940
|
+
return expectMessageAccepted(
|
|
2941
|
+
await transport.request("/api/v1/messages/send", {
|
|
2942
|
+
method: "POST",
|
|
2943
|
+
body: { channel: "EMAIL", payload: rawEmailPayload(input) }
|
|
2944
|
+
}),
|
|
2945
|
+
"Send email response",
|
|
2946
|
+
errors
|
|
2947
|
+
);
|
|
2935
2948
|
}
|
|
2936
2949
|
};
|
|
2937
2950
|
}
|
|
2951
|
+
function rawEmailPayload(input) {
|
|
2952
|
+
return {
|
|
2953
|
+
type: "RAW",
|
|
2954
|
+
to: input.to,
|
|
2955
|
+
...input.cc === void 0 ? {} : { cc: input.cc },
|
|
2956
|
+
...input.bcc === void 0 ? {} : { bcc: input.bcc },
|
|
2957
|
+
...input.replyTo === void 0 ? {} : { replyTo: input.replyTo },
|
|
2958
|
+
subject: input.subject,
|
|
2959
|
+
html: input.html,
|
|
2960
|
+
...input.text === void 0 ? {} : { text: input.text }
|
|
2961
|
+
};
|
|
2962
|
+
}
|
|
2938
2963
|
|
|
2939
2964
|
// src/modules/publicFunctions.ts
|
|
2940
2965
|
function createPublicFunctionsModule(transport, errors = defaultSdkCoreErrorFactory) {
|
|
@@ -3286,6 +3311,29 @@ var ADMISSION_TIMEOUT_MS = 35e3;
|
|
|
3286
3311
|
var SUPERSEDED_CLOSE_CODE = 4409;
|
|
3287
3312
|
var SOCKET_OPEN = 1;
|
|
3288
3313
|
var FLEET_BOX_HOST = /^[0-9a-z][0-9a-z-]*\.(?:e2b\.app|e2b-[0-9a-z-]+\.mitralab\.ai)$/;
|
|
3314
|
+
var clientMessageSequence = 0;
|
|
3315
|
+
function newClientMessageId() {
|
|
3316
|
+
const random = globalThis.crypto?.randomUUID;
|
|
3317
|
+
return random ? random.call(globalThis.crypto) : `m-${Date.now()}-${++clientMessageSequence}`;
|
|
3318
|
+
}
|
|
3319
|
+
function admissionFor(link, event) {
|
|
3320
|
+
const payload = asObject(event.payload);
|
|
3321
|
+
if (event.type === "error" && (payload?.lifecycle || payload?.requestId !== void 0)) {
|
|
3322
|
+
return void 0;
|
|
3323
|
+
}
|
|
3324
|
+
const id = event.type === "stepStart" ? asObject(payload?.lifecycle)?.clientMessageId : payload?.clientMessageId;
|
|
3325
|
+
if (typeof id === "string")
|
|
3326
|
+
return link.admissions.find((pending) => pending.clientMessageId === id);
|
|
3327
|
+
return link.admissions[0];
|
|
3328
|
+
}
|
|
3329
|
+
function queuedAdmission(link, event) {
|
|
3330
|
+
const id = asObject(asObject(event.payload)?.lifecycle)?.clientMessageId;
|
|
3331
|
+
if (typeof id !== "string") return void 0;
|
|
3332
|
+
return link.admissions.find((pending) => pending.clientMessageId === id);
|
|
3333
|
+
}
|
|
3334
|
+
function isSubagentFrame(event) {
|
|
3335
|
+
return typeof asObject(event.payload)?.parentToolId === "string";
|
|
3336
|
+
}
|
|
3289
3337
|
function asObject(value) {
|
|
3290
3338
|
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3291
3339
|
}
|
|
@@ -3406,6 +3454,7 @@ function asDelta(event) {
|
|
|
3406
3454
|
}
|
|
3407
3455
|
var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
|
|
3408
3456
|
"stepStart",
|
|
3457
|
+
"steer",
|
|
3409
3458
|
"textDelta",
|
|
3410
3459
|
"thinking",
|
|
3411
3460
|
"toolCall",
|
|
@@ -3414,7 +3463,7 @@ var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
|
|
|
3414
3463
|
var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
|
|
3415
3464
|
function turnAfter(event, inTurn) {
|
|
3416
3465
|
if (TURN_FRAME_TYPES.has(event.type)) return true;
|
|
3417
|
-
if (event.type === "error") return false;
|
|
3466
|
+
if (event.type === "error") return asObject(event.payload)?.lifecycle ? false : inTurn;
|
|
3418
3467
|
if (event.type === "stepFinish") {
|
|
3419
3468
|
const payload = asObject(event.payload);
|
|
3420
3469
|
if (TURN_END_REASONS.has(payload?.reason)) return false;
|
|
@@ -3422,6 +3471,21 @@ function turnAfter(event, inTurn) {
|
|
|
3422
3471
|
}
|
|
3423
3472
|
return inTurn;
|
|
3424
3473
|
}
|
|
3474
|
+
function lostTurnFrame(turnId) {
|
|
3475
|
+
return {
|
|
3476
|
+
type: "stepFinish",
|
|
3477
|
+
payload: {
|
|
3478
|
+
reason: "interrupted",
|
|
3479
|
+
lifecycle: {
|
|
3480
|
+
...turnId === void 0 ? {} : { turnId },
|
|
3481
|
+
terminal: true,
|
|
3482
|
+
sessionIdle: true,
|
|
3483
|
+
interruptTerminal: true
|
|
3484
|
+
}
|
|
3485
|
+
},
|
|
3486
|
+
timestamp: Date.now()
|
|
3487
|
+
};
|
|
3488
|
+
}
|
|
3425
3489
|
function channelEvent(type, payload) {
|
|
3426
3490
|
return { type, payload, timestamp: Date.now() };
|
|
3427
3491
|
}
|
|
@@ -3501,9 +3565,11 @@ var AgentDirectChannel = class {
|
|
|
3501
3565
|
}
|
|
3502
3566
|
}
|
|
3503
3567
|
/**
|
|
3504
|
-
* Hands a message
|
|
3505
|
-
* wire is up right now. Null sends the caller to REST: no direct channel, a wire lost or
|
|
3506
|
-
* mid-redial, or an approval, which stays on REST.
|
|
3568
|
+
* Hands a message, an interrupt, a subagent stop or an answer to a T3 input request to the box
|
|
3569
|
+
* 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
|
|
3570
|
+
* mid-redial, or an approval, which stays on REST. Mid-redial the Copilot is the durable path:
|
|
3571
|
+
* the box URL kept from the last channel carries a proxy ticket that lasts 60 seconds, and a
|
|
3572
|
+
* box that dropped the socket is often the one that went away.
|
|
3507
3573
|
*
|
|
3508
3574
|
* A message resolves only when the box answers for it. `stepStart` on the stream, or the 200 of
|
|
3509
3575
|
* the HTTP route, is the box starting the turn the Copilot admitted: from then on the turn runs
|
|
@@ -3516,12 +3582,12 @@ var AgentDirectChannel = class {
|
|
|
3516
3582
|
* have admitted the turn, and a second copy would start it twice. The redial replays the box
|
|
3517
3583
|
* log, where the `stepStart` of an admitted turn is.
|
|
3518
3584
|
*/
|
|
3519
|
-
send(taskId, input) {
|
|
3585
|
+
send(taskId, input, clientMessageId) {
|
|
3520
3586
|
if (input.type === "approval_response") return null;
|
|
3521
3587
|
const link = this.links.get(taskId);
|
|
3522
3588
|
if (!link?.wire) return null;
|
|
3523
3589
|
if (input.type !== "message") return link.wire.interrupt(input);
|
|
3524
|
-
|
|
3590
|
+
const messageId = clientMessageId ?? newClientMessageId();
|
|
3525
3591
|
let admission;
|
|
3526
3592
|
const admitted = new Promise((resolve, reject) => {
|
|
3527
3593
|
let timer;
|
|
@@ -3537,11 +3603,13 @@ var AgentDirectChannel = class {
|
|
|
3537
3603
|
};
|
|
3538
3604
|
const done = () => {
|
|
3539
3605
|
clearTimeout(timer);
|
|
3540
|
-
|
|
3606
|
+
link.admissions = link.admissions.filter((pending) => pending !== admission);
|
|
3541
3607
|
};
|
|
3542
3608
|
admission = {
|
|
3609
|
+
clientMessageId: messageId,
|
|
3543
3610
|
settle: (value) => {
|
|
3544
3611
|
done();
|
|
3612
|
+
if (value) link.inTurn = true;
|
|
3545
3613
|
resolve(value);
|
|
3546
3614
|
},
|
|
3547
3615
|
fail: (error) => {
|
|
@@ -3553,12 +3621,11 @@ var AgentDirectChannel = class {
|
|
|
3553
3621
|
};
|
|
3554
3622
|
arm();
|
|
3555
3623
|
});
|
|
3556
|
-
link.
|
|
3557
|
-
if (!link.wire.message(input, admission)) {
|
|
3624
|
+
link.admissions = [...link.admissions, admission];
|
|
3625
|
+
if (!link.wire.message({ ...input, clientMessageId: messageId }, admission)) {
|
|
3558
3626
|
admission.settle(false);
|
|
3559
3627
|
return null;
|
|
3560
3628
|
}
|
|
3561
|
-
link.inTurn = true;
|
|
3562
3629
|
return admitted;
|
|
3563
3630
|
}
|
|
3564
3631
|
/** `websocket` needs a socket; `http` needs fetch; `auto` prefers the socket. */
|
|
@@ -3615,7 +3682,7 @@ var AgentDirectChannel = class {
|
|
|
3615
3682
|
* text. The HTTP stream opens from the sequence the Copilot reported, which is the same thing.
|
|
3616
3683
|
*/
|
|
3617
3684
|
async openDirect(taskId, mode, channel, observer, signal) {
|
|
3618
|
-
const link = { wire: null, inTurn: false,
|
|
3685
|
+
const link = { wire: null, inTurn: false, turnId: void 0, admissions: [] };
|
|
3619
3686
|
let box = boxAddress(channel.wsUrl);
|
|
3620
3687
|
let cursor = channel.lastSequence;
|
|
3621
3688
|
const abort = new AbortController();
|
|
@@ -3623,35 +3690,46 @@ var AgentDirectChannel = class {
|
|
|
3623
3690
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3624
3691
|
const onFrame = (event) => {
|
|
3625
3692
|
if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
|
|
3693
|
+
if (isSubagentFrame(event)) {
|
|
3694
|
+
observer.onEvent(event);
|
|
3695
|
+
return;
|
|
3696
|
+
}
|
|
3697
|
+
const turnId = asObject(asObject(event.payload)?.lifecycle)?.turnId;
|
|
3698
|
+
if (typeof turnId === "string") link.turnId = turnId;
|
|
3626
3699
|
link.inTurn = turnAfter(event, link.inTurn);
|
|
3627
3700
|
observer.onEvent(event);
|
|
3628
|
-
if (event.type === "stepStart") link
|
|
3629
|
-
else if (event.type === "error") link
|
|
3701
|
+
if (event.type === "stepStart") admissionFor(link, event)?.settle(true);
|
|
3702
|
+
else if (event.type === "error") admissionFor(link, event)?.settle(false);
|
|
3703
|
+
else if (event.type === "messageQueued" || event.type === "steer") {
|
|
3704
|
+
queuedAdmission(link, event)?.settle(true);
|
|
3705
|
+
}
|
|
3630
3706
|
};
|
|
3631
3707
|
const onLost = (error, code) => {
|
|
3632
3708
|
link.wire = null;
|
|
3633
3709
|
if (abort.signal.aborted) return;
|
|
3634
|
-
if (!link.inTurn || code === SUPERSEDED_CLOSE_CODE) {
|
|
3635
|
-
link.
|
|
3710
|
+
if (!link.inTurn && link.admissions.length === 0 || code === SUPERSEDED_CLOSE_CODE) {
|
|
3711
|
+
for (const pending of link.admissions) pending.fail(error);
|
|
3636
3712
|
observer.onDisconnect(error);
|
|
3637
3713
|
return;
|
|
3638
3714
|
}
|
|
3639
|
-
link.
|
|
3715
|
+
for (const pending of link.admissions) pending.hold();
|
|
3640
3716
|
void this.redial(taskId, mode, error, abort.signal, observer, {
|
|
3641
3717
|
onFrame,
|
|
3642
3718
|
onLost,
|
|
3643
3719
|
replayFrom: (next) => {
|
|
3644
3720
|
const nextBox = boxAddress(next.wsUrl);
|
|
3645
|
-
|
|
3721
|
+
const zeroed = next.lastSequence === 0 && cursor > 0;
|
|
3722
|
+
if (nextBox === box && !zeroed) return cursor;
|
|
3723
|
+
if (link.inTurn) onFrame(lostTurnFrame(link.turnId));
|
|
3646
3724
|
box = nextBox;
|
|
3647
3725
|
cursor = next.lastSequence;
|
|
3648
3726
|
return void 0;
|
|
3649
3727
|
}
|
|
3650
3728
|
}).then((outcome) => {
|
|
3651
|
-
if (outcome instanceof Error) link.
|
|
3729
|
+
if (outcome instanceof Error) for (const pending of link.admissions) pending.fail(outcome);
|
|
3652
3730
|
else if (outcome) {
|
|
3653
3731
|
link.wire = outcome;
|
|
3654
|
-
link.
|
|
3732
|
+
for (const pending of link.admissions) pending.rearm();
|
|
3655
3733
|
}
|
|
3656
3734
|
});
|
|
3657
3735
|
};
|
|
@@ -3672,9 +3750,8 @@ var AgentDirectChannel = class {
|
|
|
3672
3750
|
abort.abort();
|
|
3673
3751
|
link.wire?.close();
|
|
3674
3752
|
link.wire = null;
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
);
|
|
3753
|
+
const closed = new Error("The Agent session closed before the box confirmed the turn.");
|
|
3754
|
+
for (const pending of link.admissions) pending.fail(closed);
|
|
3678
3755
|
if (this.links.get(taskId) === link) this.links.delete(taskId);
|
|
3679
3756
|
}
|
|
3680
3757
|
};
|
|
@@ -3811,7 +3888,7 @@ var AgentDirectChannel = class {
|
|
|
3811
3888
|
close,
|
|
3812
3889
|
interrupt: (input) => post(input).then((response) => {
|
|
3813
3890
|
if (!response.ok) {
|
|
3814
|
-
throw new Error(`The Agent box refused the
|
|
3891
|
+
throw new Error(`The Agent box refused the ${input.type} (${response.status}).`);
|
|
3815
3892
|
}
|
|
3816
3893
|
return true;
|
|
3817
3894
|
}),
|
|
@@ -3993,9 +4070,22 @@ var AgentDirectChannel = class {
|
|
|
3993
4070
|
};
|
|
3994
4071
|
|
|
3995
4072
|
// src/agentSession.ts
|
|
3996
|
-
var AGENT_QUEUE_LIMIT = 10;
|
|
3997
4073
|
var CANCEL_SAFETY_MS = 1e4;
|
|
3998
4074
|
var RECONCILE_DELAY_MS = 1e3;
|
|
4075
|
+
var ENDED_POLLS_BEFORE_NEWEST = 3;
|
|
4076
|
+
var TURN_TAIL_TYPES = /* @__PURE__ */ new Set([
|
|
4077
|
+
"textDelta",
|
|
4078
|
+
"textChunk",
|
|
4079
|
+
"thinking",
|
|
4080
|
+
"toolCall",
|
|
4081
|
+
"toolResult",
|
|
4082
|
+
"stepFinish"
|
|
4083
|
+
]);
|
|
4084
|
+
var COPILOT_INPUT_TYPES = /* @__PURE__ */ new Set([
|
|
4085
|
+
"message",
|
|
4086
|
+
"interrupt",
|
|
4087
|
+
"approval_response"
|
|
4088
|
+
]);
|
|
3999
4089
|
function providerUsageOf(payload) {
|
|
4000
4090
|
if (!payload) return null;
|
|
4001
4091
|
try {
|
|
@@ -4024,6 +4114,31 @@ function errorCode(error) {
|
|
|
4024
4114
|
function delay(milliseconds) {
|
|
4025
4115
|
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
4026
4116
|
}
|
|
4117
|
+
function messageInput(prompt, options) {
|
|
4118
|
+
return {
|
|
4119
|
+
type: "message",
|
|
4120
|
+
content: prompt,
|
|
4121
|
+
...options.agentType ? { agentType: options.agentType } : {},
|
|
4122
|
+
...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
|
|
4123
|
+
mode: "steer"
|
|
4124
|
+
};
|
|
4125
|
+
}
|
|
4126
|
+
function toolEventOf(payload, phase, timestamp) {
|
|
4127
|
+
return {
|
|
4128
|
+
tool: typeof payload?.name === "string" ? payload.name : "",
|
|
4129
|
+
phase,
|
|
4130
|
+
timestamp,
|
|
4131
|
+
...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
|
|
4132
|
+
...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
|
|
4133
|
+
...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
|
|
4134
|
+
};
|
|
4135
|
+
}
|
|
4136
|
+
function epochOf(value) {
|
|
4137
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
4138
|
+
if (typeof value !== "string") return void 0;
|
|
4139
|
+
const parsed = Date.parse(value);
|
|
4140
|
+
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
4141
|
+
}
|
|
4027
4142
|
function toAgentTimelineItem(message) {
|
|
4028
4143
|
if (message.type === "TOOL_USE") {
|
|
4029
4144
|
try {
|
|
@@ -4097,7 +4212,6 @@ var CoreAgentTaskSession = class {
|
|
|
4097
4212
|
_status = "opening";
|
|
4098
4213
|
_history = [];
|
|
4099
4214
|
_content = "";
|
|
4100
|
-
_queue = [];
|
|
4101
4215
|
isNewSession;
|
|
4102
4216
|
listeners = /* @__PURE__ */ new Map();
|
|
4103
4217
|
connection = null;
|
|
@@ -4116,10 +4230,36 @@ var CoreAgentTaskSession = class {
|
|
|
4116
4230
|
recoveryGeneration = 0;
|
|
4117
4231
|
recoveredTerminalReason;
|
|
4118
4232
|
recoveredTerminalUsage;
|
|
4233
|
+
// Polls that found no closing row although a terminal with usage was heard.
|
|
4234
|
+
endedPollsWithoutRow = 0;
|
|
4235
|
+
// The turn ids the running turn went by, and the highest box sequence seen in it. The Copilot
|
|
4236
|
+
// stream a dropped session falls back to replays the turn from what the history has, so it
|
|
4237
|
+
// repeats frames the box socket already delivered.
|
|
4238
|
+
turnIds = /* @__PURE__ */ new Set();
|
|
4239
|
+
turnSequenceHigh = -1;
|
|
4119
4240
|
cancelTimer = null;
|
|
4120
|
-
|
|
4241
|
+
// Messages leave in the order they were sent: each one is handed over only after the one
|
|
4242
|
+
// before it was, not after it was answered.
|
|
4243
|
+
handOff = Promise.resolve();
|
|
4121
4244
|
activeWaiter;
|
|
4245
|
+
// Every steer sits in exactly one of the two lists until it is settled or forgotten: `steers`
|
|
4246
|
+
// while the turn it was sent into runs (taken ones settle with that turn), `strayedSteers` once
|
|
4247
|
+
// it waits for a turn of its own (sent with no turn, not taken when its turn ended, or queued by
|
|
4248
|
+
// the provider). A non-empty `strayedSteers` keeps the session busy, which is what stops a new
|
|
4249
|
+
// message from opening a turn the steer's answer would settle. `pendingSteers` counts the ones
|
|
4250
|
+
// the box has not answered yet, wherever they sit.
|
|
4251
|
+
steers = [];
|
|
4252
|
+
strayedSteers = [];
|
|
4253
|
+
pendingSteers = 0;
|
|
4254
|
+
// The id the message that opened the current turn went out with, so a refusal naming it fails
|
|
4255
|
+
// that turn and one naming a steer does not.
|
|
4256
|
+
openingMessageId;
|
|
4257
|
+
// The opening message went to the box, which starts its turn with a `stepStart`. Until then a
|
|
4258
|
+
// turn frame naming a turn is another turn's tail: the one before, closed here from the history
|
|
4259
|
+
// (r5 S17, dev 2026-10-19), whose live end came after the next message went out.
|
|
4260
|
+
openingAwaitsStart = false;
|
|
4122
4261
|
turnBaselineIds = /* @__PURE__ */ new Set();
|
|
4262
|
+
subagentsById = /* @__PURE__ */ new Map();
|
|
4123
4263
|
get taskId() {
|
|
4124
4264
|
return this._taskId;
|
|
4125
4265
|
}
|
|
@@ -4139,19 +4279,16 @@ var CoreAgentTaskSession = class {
|
|
|
4139
4279
|
return this._content;
|
|
4140
4280
|
}
|
|
4141
4281
|
get queue() {
|
|
4142
|
-
return
|
|
4143
|
-
|
|
4144
|
-
|
|
4145
|
-
|
|
4146
|
-
...item.agentType ? { agentType: item.agentType } : {},
|
|
4147
|
-
...item.reasoningEffort ? { reasoningEffort: item.reasoningEffort } : {}
|
|
4148
|
-
}));
|
|
4282
|
+
return [];
|
|
4283
|
+
}
|
|
4284
|
+
get subagents() {
|
|
4285
|
+
return [...this.subagentsById.values()];
|
|
4149
4286
|
}
|
|
4150
4287
|
send(prompt, options = {}) {
|
|
4151
4288
|
this.requireOpen();
|
|
4152
4289
|
if (!prompt.trim()) return;
|
|
4153
4290
|
if (this.isBusy()) {
|
|
4154
|
-
this.
|
|
4291
|
+
this.steer(prompt, options);
|
|
4155
4292
|
return;
|
|
4156
4293
|
}
|
|
4157
4294
|
this.startDispatch(prompt, options);
|
|
@@ -4166,8 +4303,7 @@ var CoreAgentTaskSession = class {
|
|
|
4166
4303
|
...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
|
|
4167
4304
|
};
|
|
4168
4305
|
if (this.isBusy()) {
|
|
4169
|
-
|
|
4170
|
-
if (queueId) waiter.queueId = queueId;
|
|
4306
|
+
this.steer(prompt, sendOptions, waiter);
|
|
4171
4307
|
return waiter.promise;
|
|
4172
4308
|
}
|
|
4173
4309
|
this.startDispatch(prompt, sendOptions, waiter);
|
|
@@ -4202,6 +4338,17 @@ var CoreAgentTaskSession = class {
|
|
|
4202
4338
|
this.emitError("Failed to answer Agent approval", error);
|
|
4203
4339
|
});
|
|
4204
4340
|
}
|
|
4341
|
+
respondUserInput(requestId, answers, attachmentsByQuestionId) {
|
|
4342
|
+
const input = {
|
|
4343
|
+
type: "runtime-request.respond",
|
|
4344
|
+
requestId,
|
|
4345
|
+
answers,
|
|
4346
|
+
...attachmentsByQuestionId ? { attachmentsByQuestionId } : {}
|
|
4347
|
+
};
|
|
4348
|
+
void this.sendInput(input).catch((error) => {
|
|
4349
|
+
this.emitError("Failed to answer Agent input request", error);
|
|
4350
|
+
});
|
|
4351
|
+
}
|
|
4205
4352
|
async loadHistory(options = {}) {
|
|
4206
4353
|
if (!this._taskId) return [];
|
|
4207
4354
|
const page = await this.dependencies.tasks.listMessages(this._taskId, {
|
|
@@ -4213,26 +4360,17 @@ var CoreAgentTaskSession = class {
|
|
|
4213
4360
|
this.emit("historyLoaded", { history });
|
|
4214
4361
|
return history;
|
|
4215
4362
|
}
|
|
4216
|
-
editQueueItem(
|
|
4217
|
-
if (!text.trim()) {
|
|
4218
|
-
this.removeQueueItem(id);
|
|
4219
|
-
return;
|
|
4220
|
-
}
|
|
4221
|
-
this._queue = this._queue.map((item) => item.id === id ? { ...item, text } : item);
|
|
4222
|
-
this.emitQueue();
|
|
4363
|
+
editQueueItem() {
|
|
4223
4364
|
}
|
|
4224
|
-
removeQueueItem(
|
|
4225
|
-
const removed = this._queue.find((item) => item.id === id);
|
|
4226
|
-
this._queue = this._queue.filter((item) => item.id !== id);
|
|
4227
|
-
removed?.waiter?.reject(new Error("Queued Agent prompt was removed."));
|
|
4228
|
-
this.emitQueue();
|
|
4365
|
+
removeQueueItem() {
|
|
4229
4366
|
}
|
|
4230
4367
|
clearQueue() {
|
|
4231
|
-
|
|
4232
|
-
|
|
4233
|
-
this.
|
|
4234
|
-
|
|
4235
|
-
|
|
4368
|
+
}
|
|
4369
|
+
stopSubagent(subagentId) {
|
|
4370
|
+
this.requireOpen();
|
|
4371
|
+
void this.sendInput({ type: "subagent.stop", subagentId }).catch((error) => {
|
|
4372
|
+
this.emitError("Failed to stop the Agent subagent", error);
|
|
4373
|
+
});
|
|
4236
4374
|
}
|
|
4237
4375
|
on(event, handler) {
|
|
4238
4376
|
let listeners = this.listeners.get(event);
|
|
@@ -4257,8 +4395,7 @@ var CoreAgentTaskSession = class {
|
|
|
4257
4395
|
const closedError = new Error("Agent task session is closed.");
|
|
4258
4396
|
this.activeWaiter?.reject(closedError);
|
|
4259
4397
|
this.activeWaiter = void 0;
|
|
4260
|
-
|
|
4261
|
-
this._queue = [];
|
|
4398
|
+
this.rejectSteers(closedError);
|
|
4262
4399
|
if (this._taskId) this.dependencies.onClose(this._taskId, this);
|
|
4263
4400
|
for (const listeners of this.listeners.values()) listeners.clear();
|
|
4264
4401
|
}
|
|
@@ -4281,31 +4418,32 @@ var CoreAgentTaskSession = class {
|
|
|
4281
4418
|
}
|
|
4282
4419
|
startDispatch(prompt, options, waiter) {
|
|
4283
4420
|
this.dispatching = true;
|
|
4284
|
-
|
|
4421
|
+
let handedOver;
|
|
4422
|
+
this.handOff = new Promise((resolve) => {
|
|
4423
|
+
handedOver = resolve;
|
|
4424
|
+
});
|
|
4425
|
+
const dispatch = this.dispatchSend(prompt, options, handedOver, waiter).catch((error) => {
|
|
4285
4426
|
waiter?.reject(error);
|
|
4286
4427
|
this.emitError("Failed to send Agent prompt", error);
|
|
4287
|
-
if (this._status === "streaming")
|
|
4288
|
-
|
|
4428
|
+
if (this._status === "streaming") {
|
|
4429
|
+
this.settleSteers((steered) => steered.reject(error));
|
|
4430
|
+
this.setStatus("idle");
|
|
4431
|
+
}
|
|
4289
4432
|
return false;
|
|
4290
4433
|
}).finally(() => {
|
|
4434
|
+
handedOver();
|
|
4291
4435
|
this.dispatching = false;
|
|
4292
4436
|
if (this.dispatch === dispatch) this.dispatch = null;
|
|
4293
|
-
if (this._status === "idle") this.flushQueue();
|
|
4294
4437
|
});
|
|
4295
4438
|
this.dispatch = dispatch;
|
|
4296
4439
|
}
|
|
4297
|
-
async dispatchSend(prompt, options, waiter) {
|
|
4440
|
+
async dispatchSend(prompt, options, handedOver, waiter) {
|
|
4298
4441
|
if (this.openingPromise && !await this.openingPromise) {
|
|
4299
4442
|
throw new Error("Agent task session could not be opened.");
|
|
4300
4443
|
}
|
|
4301
4444
|
if (this.isClosed() || waiter?.settled) return false;
|
|
4302
4445
|
await this.ensureTask();
|
|
4303
|
-
const input =
|
|
4304
|
-
type: "message",
|
|
4305
|
-
content: prompt,
|
|
4306
|
-
...options.agentType ? { agentType: options.agentType } : {},
|
|
4307
|
-
...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
|
|
4308
|
-
};
|
|
4446
|
+
const input = messageInput(prompt, options);
|
|
4309
4447
|
if (this.isClosed()) {
|
|
4310
4448
|
await this.sendInput(input).catch(() => void 0);
|
|
4311
4449
|
return false;
|
|
@@ -4322,10 +4460,134 @@ var CoreAgentTaskSession = class {
|
|
|
4322
4460
|
this.activeWaiter = waiter;
|
|
4323
4461
|
this.setStatus("streaming");
|
|
4324
4462
|
this.emit("turnStart", {});
|
|
4325
|
-
|
|
4463
|
+
this.openingMessageId = newClientMessageId();
|
|
4464
|
+
this.openingAwaitsStart = true;
|
|
4465
|
+
const { admitted, direct } = await this.handOver(input, this.openingMessageId);
|
|
4466
|
+
if (!direct) this.openingAwaitsStart = false;
|
|
4467
|
+
handedOver();
|
|
4468
|
+
if (!await admitted) return false;
|
|
4326
4469
|
this.emit("accepted", {});
|
|
4327
4470
|
return true;
|
|
4328
4471
|
}
|
|
4472
|
+
// A message sent while a turn runs, or is being opened, goes out at once: the box takes it into
|
|
4473
|
+
// that turn (the provider's own steering), queues it for a turn of its own, or gives it one when
|
|
4474
|
+
// that turn already ended. Nothing waits in this session. On the direct channel it goes with an
|
|
4475
|
+
// id the box echoes on the frame that takes it; without the channel, over REST to the Copilot,
|
|
4476
|
+
// which holds it while the box boots.
|
|
4477
|
+
//
|
|
4478
|
+
// It keeps its `agentType` and `reasoningEffort` on the box, which leaves the running turn's
|
|
4479
|
+
// model alone by itself and needs them for a message that becomes a turn of its own. Only on
|
|
4480
|
+
// the Copilot path, with a turn running, they are dropped: the Copilot restarts the live
|
|
4481
|
+
// session for a message that asks for another model, which would end that turn.
|
|
4482
|
+
steer(prompt, options, waiter) {
|
|
4483
|
+
const steered = {
|
|
4484
|
+
clientMessageId: newClientMessageId(),
|
|
4485
|
+
...waiter ? { waiter } : {},
|
|
4486
|
+
taken: false
|
|
4487
|
+
};
|
|
4488
|
+
if (this.dispatching || this._status === "streaming" || this._status === "cancelled") {
|
|
4489
|
+
this.steers.push(steered);
|
|
4490
|
+
} else {
|
|
4491
|
+
this.strayedSteers.push(steered);
|
|
4492
|
+
}
|
|
4493
|
+
const input = messageInput(prompt, options);
|
|
4494
|
+
this.pendingSteers += 1;
|
|
4495
|
+
const handed = this.handOff.then(async () => {
|
|
4496
|
+
if (this.isClosed()) throw new Error("Agent task session is closed.");
|
|
4497
|
+
await this.prepareSend();
|
|
4498
|
+
if (this.isClosed()) throw new Error("Agent task session is closed.");
|
|
4499
|
+
return this.handOver(input, steered.clientMessageId, true);
|
|
4500
|
+
});
|
|
4501
|
+
this.handOff = handed.then(
|
|
4502
|
+
() => void 0,
|
|
4503
|
+
() => void 0
|
|
4504
|
+
);
|
|
4505
|
+
void handed.then(({ admitted }) => admitted).then((admitted) => {
|
|
4506
|
+
if (!admitted) {
|
|
4507
|
+
this.forgetSteer(steered);
|
|
4508
|
+
waiter?.reject(
|
|
4509
|
+
steered.refusal ?? new AgentTaskTurnError("The Agent box did not take the message.")
|
|
4510
|
+
);
|
|
4511
|
+
return;
|
|
4512
|
+
}
|
|
4513
|
+
if (!steered.queued) this.steerTaken(steered);
|
|
4514
|
+
this.emit("accepted", {});
|
|
4515
|
+
}).catch((error) => {
|
|
4516
|
+
this.forgetSteer(steered);
|
|
4517
|
+
waiter?.reject(error);
|
|
4518
|
+
this.emitError("Failed to send Agent prompt", error);
|
|
4519
|
+
}).finally(() => {
|
|
4520
|
+
this.pendingSteers -= 1;
|
|
4521
|
+
});
|
|
4522
|
+
}
|
|
4523
|
+
// The box took the steer. Into the turn it was sent to, when that turn still runs; into a turn
|
|
4524
|
+
// of its own, when that one ended before the box got to the message.
|
|
4525
|
+
steerTaken(steered) {
|
|
4526
|
+
if (steered.taken) return;
|
|
4527
|
+
steered.taken = true;
|
|
4528
|
+
if (!this.strayedSteers.includes(steered)) return;
|
|
4529
|
+
this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
|
|
4530
|
+
this.openTurnFor(steered.waiter);
|
|
4531
|
+
}
|
|
4532
|
+
steerOpenedBy(lifecycle) {
|
|
4533
|
+
const id = lifecycle?.clientMessageId;
|
|
4534
|
+
if (typeof id !== "string") return;
|
|
4535
|
+
const steered = [...this.steers, ...this.strayedSteers].find(
|
|
4536
|
+
(pending) => pending.clientMessageId === id
|
|
4537
|
+
);
|
|
4538
|
+
if (steered) this.steerTaken(steered);
|
|
4539
|
+
}
|
|
4540
|
+
// Queued behind the running turn, the message is answered by the turn the box opens for it
|
|
4541
|
+
// later, not by this one.
|
|
4542
|
+
steerQueuedBy(lifecycle) {
|
|
4543
|
+
const id = lifecycle?.clientMessageId;
|
|
4544
|
+
if (typeof id !== "string") return;
|
|
4545
|
+
const steered = [...this.steers, ...this.strayedSteers].find(
|
|
4546
|
+
(pending) => pending.clientMessageId === id
|
|
4547
|
+
);
|
|
4548
|
+
if (!steered || steered.taken) return;
|
|
4549
|
+
steered.queued = true;
|
|
4550
|
+
if (!this.steers.includes(steered)) return;
|
|
4551
|
+
this.steers = this.steers.filter((pending) => pending !== steered);
|
|
4552
|
+
this.strayedSteers.push(steered);
|
|
4553
|
+
}
|
|
4554
|
+
forgetSteer(steered) {
|
|
4555
|
+
this.steers = this.steers.filter((pending) => pending !== steered);
|
|
4556
|
+
this.strayedSteers = this.strayedSteers.filter((pending) => pending !== steered);
|
|
4557
|
+
}
|
|
4558
|
+
// The turn ended: what the box took is answered by it, what it had not taken yet waits for the
|
|
4559
|
+
// turn the box opens for it.
|
|
4560
|
+
settleSteers(settle) {
|
|
4561
|
+
const steers = this.steers;
|
|
4562
|
+
this.steers = [];
|
|
4563
|
+
for (const steered of steers) {
|
|
4564
|
+
if (!steered.taken) this.strayedSteers.push(steered);
|
|
4565
|
+
else if (steered.waiter) settle(steered.waiter);
|
|
4566
|
+
}
|
|
4567
|
+
}
|
|
4568
|
+
openTurnFor(waiter) {
|
|
4569
|
+
if (this.isClosed()) return;
|
|
4570
|
+
if (this._status !== "streaming" && this._status !== "cancelled") {
|
|
4571
|
+
this._content = "";
|
|
4572
|
+
this.recoveryUsed = false;
|
|
4573
|
+
this.recoveredTerminalReason = void 0;
|
|
4574
|
+
this.recoveredTerminalUsage = void 0;
|
|
4575
|
+
this.recoveryGeneration += 1;
|
|
4576
|
+
this.turnBaselineIds = new Set(this._history.map((item) => item.id));
|
|
4577
|
+
void this.captureTurnBaseline().catch(() => void 0);
|
|
4578
|
+
this.setStatus("streaming");
|
|
4579
|
+
this.emit("turnStart", {});
|
|
4580
|
+
}
|
|
4581
|
+
if (!waiter) return;
|
|
4582
|
+
if (!this.activeWaiter) this.activeWaiter = waiter;
|
|
4583
|
+
else this.steers.push({ clientMessageId: "", waiter, taken: true });
|
|
4584
|
+
}
|
|
4585
|
+
rejectSteers(error) {
|
|
4586
|
+
const steers = [...this.steers, ...this.strayedSteers];
|
|
4587
|
+
this.steers = [];
|
|
4588
|
+
this.strayedSteers = [];
|
|
4589
|
+
for (const steered of steers) steered.waiter?.reject(error);
|
|
4590
|
+
}
|
|
4329
4591
|
async ensureTask() {
|
|
4330
4592
|
if (this._taskId) return;
|
|
4331
4593
|
if (!("create" in this.options)) throw new Error("Agent task session has no task.");
|
|
@@ -4396,10 +4658,8 @@ var CoreAgentTaskSession = class {
|
|
|
4396
4658
|
try {
|
|
4397
4659
|
await this.ensureChannel();
|
|
4398
4660
|
while (generation === this.recoveryGeneration && !this.isClosed() && (this._status === "streaming" || this._status === "cancelled")) {
|
|
4399
|
-
|
|
4400
|
-
|
|
4401
|
-
}
|
|
4402
|
-
if (this.activeWaiter?.settled) return;
|
|
4661
|
+
const reason = this.recoveredTerminalReason ?? (this._status === "cancelled" ? "interrupted" : "reconciled");
|
|
4662
|
+
if (await this.reconcilePersistedTurn(reason)) return;
|
|
4403
4663
|
await delay(RECONCILE_DELAY_MS);
|
|
4404
4664
|
}
|
|
4405
4665
|
} catch (error) {
|
|
@@ -4425,9 +4685,22 @@ var CoreAgentTaskSession = class {
|
|
|
4425
4685
|
this._history = [...page.content].reverse().map(toAgentTimelineItem);
|
|
4426
4686
|
this.emit("historyLoaded", { history: this.history });
|
|
4427
4687
|
const recovered = page.content.find(
|
|
4428
|
-
(message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
|
|
4688
|
+
(message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE" && (message.type === "ERROR" || this.closesThisTurn(message))
|
|
4429
4689
|
);
|
|
4430
|
-
if (!recovered)
|
|
4690
|
+
if (!recovered) {
|
|
4691
|
+
if (this.recoveredTerminalReason === void 0) return false;
|
|
4692
|
+
if (this.recoveredTerminalUsage !== void 0) {
|
|
4693
|
+
this.endedPollsWithoutRow += 1;
|
|
4694
|
+
if (this.endedPollsWithoutRow < ENDED_POLLS_BEFORE_NEWEST) return false;
|
|
4695
|
+
}
|
|
4696
|
+
const newest = page.content.find(
|
|
4697
|
+
(message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
|
|
4698
|
+
);
|
|
4699
|
+
if (!newest) return false;
|
|
4700
|
+
this._content = newest.content;
|
|
4701
|
+
this.finishTurn(reason, this.recoveredTerminalUsage);
|
|
4702
|
+
return true;
|
|
4703
|
+
}
|
|
4431
4704
|
if (recovered.type === "ERROR") {
|
|
4432
4705
|
const error = new AgentTaskTurnError(recovered.content);
|
|
4433
4706
|
this.emit("error", { error: error.message });
|
|
@@ -4438,17 +4711,66 @@ var CoreAgentTaskSession = class {
|
|
|
4438
4711
|
this.finishTurn(reason, recovered.usage ?? this.recoveredTerminalUsage);
|
|
4439
4712
|
return true;
|
|
4440
4713
|
}
|
|
4714
|
+
closesThisTurn(message) {
|
|
4715
|
+
if (!message.usage) return false;
|
|
4716
|
+
const prompt = message.usage.requestMessageId;
|
|
4717
|
+
return prompt === void 0 || !this.turnBaselineIds.has(prompt);
|
|
4718
|
+
}
|
|
4441
4719
|
/** True once the server took the input; false when the box refused it on the stream. */
|
|
4442
4720
|
async sendInput(input) {
|
|
4721
|
+
return (await this.handOver(input)).admitted;
|
|
4722
|
+
}
|
|
4723
|
+
// Resolves once the input left this session; `admitted` then says whether the server took it.
|
|
4724
|
+
// Wrapped so that awaiting the hand-over does not also await the answer.
|
|
4725
|
+
async handOver(input, clientMessageId, steering = false) {
|
|
4443
4726
|
if (!this._taskId) throw new Error("Agent task has not been created.");
|
|
4444
|
-
const direct = this.dependencies.channel.send(this._taskId, input);
|
|
4445
|
-
if (direct) return direct;
|
|
4446
|
-
|
|
4447
|
-
|
|
4727
|
+
const direct = this.dependencies.channel.send(this._taskId, input, clientMessageId);
|
|
4728
|
+
if (direct) return { admitted: direct, direct: true };
|
|
4729
|
+
if (input.type === "runtime-request.respond") {
|
|
4730
|
+
throw new Error(
|
|
4731
|
+
"The answer to the Agent input request was not sent: the box channel is not connected right now."
|
|
4732
|
+
);
|
|
4733
|
+
}
|
|
4734
|
+
if (!COPILOT_INPUT_TYPES.has(input.type)) {
|
|
4735
|
+
throw new Error(
|
|
4736
|
+
`The Agent ${input.type} was not sent: the box channel is not connected right now.`
|
|
4737
|
+
);
|
|
4738
|
+
}
|
|
4739
|
+
const turnRunning = this._status === "streaming" || this._status === "cancelled";
|
|
4740
|
+
const rest = input.type !== "message" ? input : steering && turnRunning ? { type: "message", content: input.content } : {
|
|
4741
|
+
type: "message",
|
|
4742
|
+
content: input.content,
|
|
4743
|
+
...input.agentType ? { agentType: input.agentType } : {},
|
|
4744
|
+
...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {}
|
|
4745
|
+
};
|
|
4746
|
+
await this.dependencies.tasks.sendInput(this._taskId, rest);
|
|
4747
|
+
return { admitted: Promise.resolve(true), direct: false };
|
|
4748
|
+
}
|
|
4749
|
+
async prepareSend() {
|
|
4750
|
+
if (this.openingPromise && !await this.openingPromise) {
|
|
4751
|
+
throw new Error("Agent task session could not be opened.");
|
|
4752
|
+
}
|
|
4753
|
+
await this.ensureTask();
|
|
4754
|
+
if (!this.isClosed()) await this.ensureChannel();
|
|
4448
4755
|
}
|
|
4449
4756
|
handleEvent(event) {
|
|
4450
4757
|
this.emit("raw", event);
|
|
4451
4758
|
const payload = asObject2(event.payload);
|
|
4759
|
+
if (payload && isSubagentFrame(event)) {
|
|
4760
|
+
this.handleSubagentFrame(event, payload);
|
|
4761
|
+
return;
|
|
4762
|
+
}
|
|
4763
|
+
const lifecycle = asObject2(payload?.lifecycle);
|
|
4764
|
+
if (this.repeatsTheRunningTurn(event, lifecycle)) return;
|
|
4765
|
+
if (event.type === "stepStart" || event.type === "steer") {
|
|
4766
|
+
const id = lifecycle?.clientMessageId;
|
|
4767
|
+
if (id === this.openingMessageId || id === void 0 && event.type === "stepStart") {
|
|
4768
|
+
this.openingAwaitsStart = false;
|
|
4769
|
+
this.forgetFinishedTurn(lifecycle);
|
|
4770
|
+
}
|
|
4771
|
+
} else if (this.openingAwaitsStart && TURN_TAIL_TYPES.has(event.type) && typeof lifecycle?.turnId === "string") {
|
|
4772
|
+
this.rememberFinishedTurn(lifecycle);
|
|
4773
|
+
}
|
|
4452
4774
|
switch (event.type) {
|
|
4453
4775
|
// A box transmite o texto do agente ao vivo em `textDelta` e grava o mesmo texto no log
|
|
4454
4776
|
// como `textChunk`. Uma repeticao depois de uma queda devolve chunks, entao trata-los como
|
|
@@ -4461,14 +4783,30 @@ var CoreAgentTaskSession = class {
|
|
|
4461
4783
|
this.consumeDelta(payload, "thinking");
|
|
4462
4784
|
break;
|
|
4463
4785
|
case "toolCall":
|
|
4464
|
-
this.emitTool(payload, "call", event.timestamp);
|
|
4786
|
+
if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "call", event.timestamp);
|
|
4465
4787
|
break;
|
|
4466
4788
|
case "toolResult":
|
|
4467
|
-
this.emitTool(payload, "result", event.timestamp);
|
|
4789
|
+
if (!this.isFinishedTurnFrame(lifecycle)) this.emitTool(payload, "result", event.timestamp);
|
|
4468
4790
|
break;
|
|
4469
4791
|
case "workspace":
|
|
4470
4792
|
this.emit("workspace", { payload: event.payload, timestamp: event.timestamp });
|
|
4471
4793
|
break;
|
|
4794
|
+
case "stepStart":
|
|
4795
|
+
this.steerOpenedBy(asObject2(payload?.lifecycle));
|
|
4796
|
+
break;
|
|
4797
|
+
case "steer":
|
|
4798
|
+
this.steerOpenedBy(lifecycle);
|
|
4799
|
+
this.emit("steered", {
|
|
4800
|
+
text: typeof payload?.text === "string" ? payload.text : "",
|
|
4801
|
+
messageId: typeof payload?.messageId === "string" ? payload.messageId : ""
|
|
4802
|
+
});
|
|
4803
|
+
break;
|
|
4804
|
+
case "messageQueued":
|
|
4805
|
+
this.steerQueuedBy(asObject2(payload?.lifecycle));
|
|
4806
|
+
break;
|
|
4807
|
+
case "subagentUpdate":
|
|
4808
|
+
this.applySubagent(payload);
|
|
4809
|
+
break;
|
|
4472
4810
|
case "providerUsage": {
|
|
4473
4811
|
const usage = providerUsageOf(payload);
|
|
4474
4812
|
if (usage) this.emit("providerUsage", usage);
|
|
@@ -4476,15 +4814,17 @@ var CoreAgentTaskSession = class {
|
|
|
4476
4814
|
}
|
|
4477
4815
|
case "stepFinish": {
|
|
4478
4816
|
const reason = typeof payload?.reason === "string" ? payload.reason : "unknown";
|
|
4479
|
-
const
|
|
4817
|
+
const lifecycle2 = payload?.lifecycle;
|
|
4480
4818
|
const usage = agentTurnUsageOf(payload?.usage);
|
|
4481
|
-
|
|
4482
|
-
|
|
4819
|
+
const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
|
|
4820
|
+
if (finished !== void 0 && this.finishedTurnIds.includes(finished)) break;
|
|
4821
|
+
if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
|
|
4822
|
+
this.rememberFinishedTurn(lifecycle2);
|
|
4483
4823
|
this.finishTurn("interrupted", usage);
|
|
4484
4824
|
break;
|
|
4485
4825
|
}
|
|
4486
4826
|
if (reason === "stop" || reason === "endTurn") {
|
|
4487
|
-
this.rememberFinishedTurn(
|
|
4827
|
+
this.rememberFinishedTurn(lifecycle2);
|
|
4488
4828
|
if (this.recoveryUsed) {
|
|
4489
4829
|
this.recoveredTerminalReason = reason;
|
|
4490
4830
|
this.recoveredTerminalUsage = usage;
|
|
@@ -4504,6 +4844,17 @@ var CoreAgentTaskSession = class {
|
|
|
4504
4844
|
const code = typeof payload?.code === "string" ? payload.code : void 0;
|
|
4505
4845
|
const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
|
|
4506
4846
|
this.emit("error", { ...code ? { code } : {}, error: message });
|
|
4847
|
+
if (!payload?.lifecycle && payload?.requestId !== void 0) break;
|
|
4848
|
+
const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
|
|
4849
|
+
if (typeof refused === "string") {
|
|
4850
|
+
if (refused !== this.openingMessageId) {
|
|
4851
|
+
const steered = [...this.steers, ...this.strayedSteers].find(
|
|
4852
|
+
(pending) => pending.clientMessageId === refused
|
|
4853
|
+
);
|
|
4854
|
+
if (steered) steered.refusal = new AgentTaskTurnError(message, code);
|
|
4855
|
+
break;
|
|
4856
|
+
}
|
|
4857
|
+
} else if (!payload?.lifecycle && !this.dispatching && this.pendingSteers > 0) break;
|
|
4507
4858
|
if (this._status === "streaming" || this._status === "cancelled") {
|
|
4508
4859
|
this.failTurn(new AgentTaskTurnError(message, code));
|
|
4509
4860
|
}
|
|
@@ -4513,6 +4864,27 @@ var CoreAgentTaskSession = class {
|
|
|
4513
4864
|
break;
|
|
4514
4865
|
}
|
|
4515
4866
|
}
|
|
4867
|
+
repeatsTheRunningTurn(event, lifecycle) {
|
|
4868
|
+
if (this._status !== "streaming" && this._status !== "cancelled") return false;
|
|
4869
|
+
const turnId = lifecycle?.turnId;
|
|
4870
|
+
if (typeof turnId !== "string") return false;
|
|
4871
|
+
if (typeof event.sequence === "number") {
|
|
4872
|
+
if (this.turnIds.has(turnId) && event.sequence <= this.turnSequenceHigh) return true;
|
|
4873
|
+
this.turnSequenceHigh = Math.max(this.turnSequenceHigh, event.sequence);
|
|
4874
|
+
}
|
|
4875
|
+
this.turnIds.add(turnId);
|
|
4876
|
+
return false;
|
|
4877
|
+
}
|
|
4878
|
+
isFinishedTurnFrame(lifecycle) {
|
|
4879
|
+
const turnId = lifecycle?.turnId;
|
|
4880
|
+
return typeof turnId === "string" && this.finishedTurnIds.includes(turnId);
|
|
4881
|
+
}
|
|
4882
|
+
forgetFinishedTurn(lifecycle) {
|
|
4883
|
+
const turnId = lifecycle?.turnId;
|
|
4884
|
+
if (typeof turnId !== "string") return;
|
|
4885
|
+
const index = this.finishedTurnIds.indexOf(turnId);
|
|
4886
|
+
if (index >= 0) this.finishedTurnIds.splice(index, 1);
|
|
4887
|
+
}
|
|
4516
4888
|
rememberFinishedTurn(lifecycle) {
|
|
4517
4889
|
const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
|
|
4518
4890
|
if (!turnId) return;
|
|
@@ -4534,14 +4906,52 @@ var CoreAgentTaskSession = class {
|
|
|
4534
4906
|
this.emit("delta", { delta: text, kind });
|
|
4535
4907
|
}
|
|
4536
4908
|
emitTool(payload, phase, timestamp) {
|
|
4537
|
-
this.emit("tool",
|
|
4538
|
-
|
|
4539
|
-
|
|
4540
|
-
|
|
4541
|
-
|
|
4542
|
-
|
|
4543
|
-
|
|
4544
|
-
|
|
4909
|
+
this.emit("tool", toolEventOf(payload, phase, timestamp));
|
|
4910
|
+
}
|
|
4911
|
+
// A child thread's frames are the subagent's conversation: they open no turn, settle no message
|
|
4912
|
+
// and never reach the chat's `content`.
|
|
4913
|
+
handleSubagentFrame(event, payload) {
|
|
4914
|
+
const parentToolId = payload.parentToolId;
|
|
4915
|
+
switch (event.type) {
|
|
4916
|
+
case "textDelta":
|
|
4917
|
+
case "textChunk":
|
|
4918
|
+
case "thinking":
|
|
4919
|
+
this.emit("subagentDelta", {
|
|
4920
|
+
parentToolId,
|
|
4921
|
+
delta: typeof payload.text === "string" ? payload.text : "",
|
|
4922
|
+
kind: event.type === "thinking" ? "thinking" : "text"
|
|
4923
|
+
});
|
|
4924
|
+
break;
|
|
4925
|
+
case "toolCall":
|
|
4926
|
+
case "toolResult":
|
|
4927
|
+
this.emit("subagentTool", {
|
|
4928
|
+
...toolEventOf(payload, event.type === "toolCall" ? "call" : "result", event.timestamp),
|
|
4929
|
+
parentToolId
|
|
4930
|
+
});
|
|
4931
|
+
break;
|
|
4932
|
+
default:
|
|
4933
|
+
break;
|
|
4934
|
+
}
|
|
4935
|
+
}
|
|
4936
|
+
applySubagent(payload) {
|
|
4937
|
+
const subagentId = payload?.subagentId;
|
|
4938
|
+
const toolId = payload?.toolId;
|
|
4939
|
+
if (typeof subagentId !== "string" || typeof toolId !== "string") return;
|
|
4940
|
+
const status = typeof payload?.status === "string" ? payload.status : this.subagentsById.get(subagentId)?.status;
|
|
4941
|
+
if (status === void 0) return;
|
|
4942
|
+
const startedAt = epochOf(payload?.startedAt);
|
|
4943
|
+
const endedAt = epochOf(payload?.endedAt);
|
|
4944
|
+
const subagent = {
|
|
4945
|
+
subagentId,
|
|
4946
|
+
toolId,
|
|
4947
|
+
status,
|
|
4948
|
+
...typeof payload?.progress === "string" ? { progress: payload.progress } : {},
|
|
4949
|
+
...startedAt !== void 0 ? { startedAt } : {},
|
|
4950
|
+
...endedAt !== void 0 ? { endedAt } : {},
|
|
4951
|
+
...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
|
|
4952
|
+
};
|
|
4953
|
+
this.subagentsById.set(subagentId, subagent);
|
|
4954
|
+
this.emit("subagent", subagent);
|
|
4545
4955
|
}
|
|
4546
4956
|
finishTurn(reason, usage) {
|
|
4547
4957
|
if (this._status !== "streaming" && this._status !== "cancelled") return;
|
|
@@ -4566,8 +4976,8 @@ var CoreAgentTaskSession = class {
|
|
|
4566
4976
|
this.emit("turnEnd", result);
|
|
4567
4977
|
this.activeWaiter?.resolve(result);
|
|
4568
4978
|
this.activeWaiter = void 0;
|
|
4979
|
+
this.settleSteers((waiter) => waiter.resolve(result));
|
|
4569
4980
|
this.setStatus("idle");
|
|
4570
|
-
this.flushQueue();
|
|
4571
4981
|
}
|
|
4572
4982
|
failTurn(error) {
|
|
4573
4983
|
if (this.cancelTimer) clearTimeout(this.cancelTimer);
|
|
@@ -4575,56 +4985,17 @@ var CoreAgentTaskSession = class {
|
|
|
4575
4985
|
this.recoveryGeneration += 1;
|
|
4576
4986
|
this.activeWaiter?.reject(error);
|
|
4577
4987
|
this.activeWaiter = void 0;
|
|
4988
|
+
this.settleSteers((waiter) => waiter.reject(error));
|
|
4578
4989
|
this.setStatus("idle");
|
|
4579
|
-
this.flushQueue();
|
|
4580
4990
|
}
|
|
4581
4991
|
failLiveChannel(observed, waiterError) {
|
|
4582
4992
|
this.recoveryGeneration += 1;
|
|
4583
4993
|
this.emitError("Agent live channel failed", observed);
|
|
4584
4994
|
this.activeWaiter?.reject(waiterError);
|
|
4585
4995
|
this.activeWaiter = void 0;
|
|
4586
|
-
|
|
4587
|
-
this._queue = [];
|
|
4588
|
-
this.emitQueue();
|
|
4996
|
+
this.rejectSteers(waiterError);
|
|
4589
4997
|
this.setStatus("error");
|
|
4590
4998
|
}
|
|
4591
|
-
enqueue(text, options, waiter) {
|
|
4592
|
-
if (this._queue.length >= AGENT_QUEUE_LIMIT) {
|
|
4593
|
-
const error = new Error(`Agent message queue is full (maximum ${AGENT_QUEUE_LIMIT}).`);
|
|
4594
|
-
waiter?.reject(error);
|
|
4595
|
-
this.emit("error", { error: error.message });
|
|
4596
|
-
return void 0;
|
|
4597
|
-
}
|
|
4598
|
-
const id = `q-${++this.queueSequence}`;
|
|
4599
|
-
this._queue = [
|
|
4600
|
-
...this._queue,
|
|
4601
|
-
{ id, text, createdAt: Date.now(), ...options, ...waiter ? { waiter } : {} }
|
|
4602
|
-
];
|
|
4603
|
-
this.emitQueue();
|
|
4604
|
-
return id;
|
|
4605
|
-
}
|
|
4606
|
-
flushQueue() {
|
|
4607
|
-
if (this.isBusy()) return;
|
|
4608
|
-
let next = this._queue[0];
|
|
4609
|
-
while (next?.waiter?.settled) {
|
|
4610
|
-
this._queue = this._queue.slice(1);
|
|
4611
|
-
next = this._queue[0];
|
|
4612
|
-
}
|
|
4613
|
-
if (!next) {
|
|
4614
|
-
this.emitQueue();
|
|
4615
|
-
return;
|
|
4616
|
-
}
|
|
4617
|
-
this._queue = this._queue.slice(1);
|
|
4618
|
-
this.emitQueue();
|
|
4619
|
-
this.startDispatch(
|
|
4620
|
-
next.text,
|
|
4621
|
-
{
|
|
4622
|
-
...next.agentType ? { agentType: next.agentType } : {},
|
|
4623
|
-
...next.reasoningEffort ? { reasoningEffort: next.reasoningEffort } : {}
|
|
4624
|
-
},
|
|
4625
|
-
next.waiter
|
|
4626
|
-
);
|
|
4627
|
-
}
|
|
4628
4999
|
createWaiter(options) {
|
|
4629
5000
|
let resolvePromise;
|
|
4630
5001
|
let rejectPromise;
|
|
@@ -4646,7 +5017,6 @@ var CoreAgentTaskSession = class {
|
|
|
4646
5017
|
if (waiter.settled) return;
|
|
4647
5018
|
waiter.settled = true;
|
|
4648
5019
|
waiter.cleanup();
|
|
4649
|
-
if (waiter.queueId) this.removeQueuedWaiter(waiter.queueId);
|
|
4650
5020
|
rejectPromise(error);
|
|
4651
5021
|
},
|
|
4652
5022
|
cleanup: () => {
|
|
@@ -4671,14 +5041,6 @@ var CoreAgentTaskSession = class {
|
|
|
4671
5041
|
}
|
|
4672
5042
|
return waiter;
|
|
4673
5043
|
}
|
|
4674
|
-
removeQueuedWaiter(id) {
|
|
4675
|
-
const size = this._queue.length;
|
|
4676
|
-
this._queue = this._queue.filter((item) => item.id !== id);
|
|
4677
|
-
if (this._queue.length !== size) this.emitQueue();
|
|
4678
|
-
}
|
|
4679
|
-
emitQueue() {
|
|
4680
|
-
this.emit("queueChange", { queue: this.queue });
|
|
4681
|
-
}
|
|
4682
5044
|
emitError(prefix, error) {
|
|
4683
5045
|
const code = errorCode(error);
|
|
4684
5046
|
this.emit("error", {
|
|
@@ -4688,6 +5050,12 @@ var CoreAgentTaskSession = class {
|
|
|
4688
5050
|
}
|
|
4689
5051
|
setStatus(status) {
|
|
4690
5052
|
if (this._status === status) return;
|
|
5053
|
+
if (status !== "streaming" && status !== "cancelled") {
|
|
5054
|
+
this.openingAwaitsStart = false;
|
|
5055
|
+
this.endedPollsWithoutRow = 0;
|
|
5056
|
+
this.turnIds.clear();
|
|
5057
|
+
this.turnSequenceHigh = -1;
|
|
5058
|
+
}
|
|
4691
5059
|
this._status = status;
|
|
4692
5060
|
this.emit("statusChange", { status });
|
|
4693
5061
|
}
|
|
@@ -4697,8 +5065,11 @@ var CoreAgentTaskSession = class {
|
|
|
4697
5065
|
isClosed() {
|
|
4698
5066
|
return this._status === "closed";
|
|
4699
5067
|
}
|
|
5068
|
+
// A turn running or being opened takes a new message as a steer. So does a session waiting for
|
|
5069
|
+
// the turn the box opens for a steer it took late: a new message started as a turn of its own
|
|
5070
|
+
// then would be answered by the steer's result, and the steer by its.
|
|
4700
5071
|
isBusy() {
|
|
4701
|
-
return this.dispatching || this._status === "streaming" || this._status === "cancelled";
|
|
5072
|
+
return this.dispatching || this._status === "streaming" || this._status === "cancelled" || this.strayedSteers.length > 0;
|
|
4702
5073
|
}
|
|
4703
5074
|
emit(event, payload) {
|
|
4704
5075
|
const listeners = this.listeners.get(event);
|