@mitralab.io/sdk-core 0.2.8 → 0.2.9-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +74 -6
- package/contracts/README.md +8 -0
- package/contracts/manifest.json +11 -1
- package/contracts/v0.2.9-beta.0/sdk-parity.json +2902 -0
- package/contracts/v0.2.9-beta.1/sdk-parity.json +2902 -0
- package/dist/index.cjs +758 -17
- package/dist/index.d.cts +93 -7
- package/dist/index.d.ts +93 -7
- package/dist/index.js +758 -17
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -930,6 +930,15 @@ function expectAgentTask(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
|
930
930
|
if (typeof task.updatedAt !== "string") invalidField(context, "updatedAt", errors);
|
|
931
931
|
return task;
|
|
932
932
|
}
|
|
933
|
+
function expectAgentTaskChannel(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
934
|
+
if (value === void 0 || value === null || value === "") return null;
|
|
935
|
+
const channel = expectObject(value, context, errors);
|
|
936
|
+
if (typeof channel.wsUrl !== "string" || !channel.wsUrl) invalidField(context, "wsUrl", errors);
|
|
937
|
+
return {
|
|
938
|
+
wsUrl: channel.wsUrl,
|
|
939
|
+
lastSequence: isInteger(channel.lastSequence) && channel.lastSequence > 0 ? channel.lastSequence : 0
|
|
940
|
+
};
|
|
941
|
+
}
|
|
933
942
|
function expectAgentMessage(value, context, errors = defaultSdkCoreErrorFactory) {
|
|
934
943
|
const message = expectObject(value, context, errors);
|
|
935
944
|
for (const field of ["id", "sender", "type", "content", "createdAt"]) {
|
|
@@ -1494,6 +1503,13 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
|
|
|
1494
1503
|
errors,
|
|
1495
1504
|
expectAgentMessage
|
|
1496
1505
|
);
|
|
1506
|
+
},
|
|
1507
|
+
async channel(id) {
|
|
1508
|
+
return expectAgentTaskChannel(
|
|
1509
|
+
await transport.request(`${path(id)}/channel`, { method: "POST" }),
|
|
1510
|
+
"Agent task channel response",
|
|
1511
|
+
errors
|
|
1512
|
+
);
|
|
1497
1513
|
}
|
|
1498
1514
|
};
|
|
1499
1515
|
}
|
|
@@ -3061,10 +3077,7 @@ function unavailableTransport(name, errors) {
|
|
|
3061
3077
|
};
|
|
3062
3078
|
}
|
|
3063
3079
|
|
|
3064
|
-
// src/
|
|
3065
|
-
var AGENT_QUEUE_LIMIT = 10;
|
|
3066
|
-
var CANCEL_SAFETY_MS = 1e4;
|
|
3067
|
-
var RECONCILE_DELAY_MS = 1e3;
|
|
3080
|
+
// src/agentTurnError.ts
|
|
3068
3081
|
var AgentTaskTurnError = class extends Error {
|
|
3069
3082
|
code;
|
|
3070
3083
|
constructor(message, code) {
|
|
@@ -3073,10 +3086,729 @@ var AgentTaskTurnError = class extends Error {
|
|
|
3073
3086
|
this.code = code;
|
|
3074
3087
|
}
|
|
3075
3088
|
};
|
|
3089
|
+
|
|
3090
|
+
// src/agentChannel.ts
|
|
3091
|
+
var CONNECT_TIMEOUT_MS = 15e3;
|
|
3092
|
+
var SILENCE_TIMEOUT_MS = 6e4;
|
|
3093
|
+
var RECONNECT_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3];
|
|
3094
|
+
var ADMISSION_TIMEOUT_MS = 35e3;
|
|
3095
|
+
var SUPERSEDED_CLOSE_CODE = 4409;
|
|
3096
|
+
var SOCKET_OPEN = 1;
|
|
3097
|
+
var FLEET_BOX_HOST = /^[0-9a-z][0-9a-z-]*\.(?:e2b\.app|e2b-[0-9a-z-]+\.mitralab\.ai)$/;
|
|
3076
3098
|
function asObject(value) {
|
|
3077
3099
|
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3078
3100
|
}
|
|
3079
3101
|
function errorMessage(error) {
|
|
3102
|
+
return error instanceof Error ? error.message : String(error);
|
|
3103
|
+
}
|
|
3104
|
+
function hostOf(url) {
|
|
3105
|
+
try {
|
|
3106
|
+
return new URL(url).host;
|
|
3107
|
+
} catch {
|
|
3108
|
+
return void 0;
|
|
3109
|
+
}
|
|
3110
|
+
}
|
|
3111
|
+
function isChannelHostAllowed(candidate, apiUrl) {
|
|
3112
|
+
try {
|
|
3113
|
+
const target = new URL(candidate);
|
|
3114
|
+
if (target.protocol !== "ws:" && target.protocol !== "wss:") return false;
|
|
3115
|
+
const api = apiUrl === void 0 ? void 0 : new URL(apiUrl);
|
|
3116
|
+
if (api && target.host === api.host) {
|
|
3117
|
+
return api.protocol !== "https:" || target.protocol === "wss:";
|
|
3118
|
+
}
|
|
3119
|
+
return target.protocol === "wss:" && FLEET_BOX_HOST.test(target.host);
|
|
3120
|
+
} catch {
|
|
3121
|
+
return false;
|
|
3122
|
+
}
|
|
3123
|
+
}
|
|
3124
|
+
function boxAddress(wsUrl) {
|
|
3125
|
+
const url = new URL(wsUrl);
|
|
3126
|
+
return `${url.origin}${url.pathname}`;
|
|
3127
|
+
}
|
|
3128
|
+
function boxRoute(wsUrl, route) {
|
|
3129
|
+
const url = new URL(wsUrl);
|
|
3130
|
+
url.protocol = url.protocol === "wss:" ? "https:" : "http:";
|
|
3131
|
+
url.pathname = `${url.pathname.replace(/\/api\/mitra\/chat\/ws\/?$/, "")}/api/mitra/chat/${route}`;
|
|
3132
|
+
return url.toString();
|
|
3133
|
+
}
|
|
3134
|
+
async function readSse(reader, onFrame) {
|
|
3135
|
+
const decoder = new TextDecoder();
|
|
3136
|
+
let buffer = "";
|
|
3137
|
+
let timer;
|
|
3138
|
+
const silence = () => new Promise((_, reject) => {
|
|
3139
|
+
timer = setTimeout(
|
|
3140
|
+
() => reject(
|
|
3141
|
+
new Error(`Agent box event stream went silent for ${SILENCE_TIMEOUT_MS / 1e3}s.`)
|
|
3142
|
+
),
|
|
3143
|
+
SILENCE_TIMEOUT_MS
|
|
3144
|
+
);
|
|
3145
|
+
});
|
|
3146
|
+
try {
|
|
3147
|
+
for (; ; ) {
|
|
3148
|
+
let chunk;
|
|
3149
|
+
try {
|
|
3150
|
+
chunk = await Promise.race([reader.read(), silence()]);
|
|
3151
|
+
} catch (error) {
|
|
3152
|
+
await reader.cancel().catch(() => void 0);
|
|
3153
|
+
throw error;
|
|
3154
|
+
} finally {
|
|
3155
|
+
clearTimeout(timer);
|
|
3156
|
+
}
|
|
3157
|
+
if (chunk.done) return;
|
|
3158
|
+
buffer += decoder.decode(chunk.value, { stream: true });
|
|
3159
|
+
let separator = /\r?\n\r?\n/.exec(buffer);
|
|
3160
|
+
while (separator) {
|
|
3161
|
+
const block = buffer.slice(0, separator.index);
|
|
3162
|
+
buffer = buffer.slice(separator.index + separator[0].length);
|
|
3163
|
+
const data = block.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join("\n");
|
|
3164
|
+
const event = data ? parseEvent(data) : null;
|
|
3165
|
+
if (event) onFrame(event);
|
|
3166
|
+
separator = /\r?\n\r?\n/.exec(buffer);
|
|
3167
|
+
}
|
|
3168
|
+
}
|
|
3169
|
+
} finally {
|
|
3170
|
+
reader.releaseLock();
|
|
3171
|
+
}
|
|
3172
|
+
}
|
|
3173
|
+
function sleep(ms, signal) {
|
|
3174
|
+
return new Promise((resolve) => {
|
|
3175
|
+
const timer = setTimeout(resolve, ms);
|
|
3176
|
+
signal.addEventListener(
|
|
3177
|
+
"abort",
|
|
3178
|
+
() => {
|
|
3179
|
+
clearTimeout(timer);
|
|
3180
|
+
resolve();
|
|
3181
|
+
},
|
|
3182
|
+
{ once: true }
|
|
3183
|
+
);
|
|
3184
|
+
});
|
|
3185
|
+
}
|
|
3186
|
+
function parseEvent(raw) {
|
|
3187
|
+
let text;
|
|
3188
|
+
if (typeof raw === "string") text = raw;
|
|
3189
|
+
else if (raw instanceof ArrayBuffer || raw instanceof Uint8Array) {
|
|
3190
|
+
text = new TextDecoder().decode(raw);
|
|
3191
|
+
} else return null;
|
|
3192
|
+
let value;
|
|
3193
|
+
try {
|
|
3194
|
+
value = JSON.parse(text);
|
|
3195
|
+
} catch {
|
|
3196
|
+
return null;
|
|
3197
|
+
}
|
|
3198
|
+
const event = asObject(value);
|
|
3199
|
+
if (!event || typeof event.type !== "string" || !event.type) return null;
|
|
3200
|
+
if (typeof event.timestamp !== "number" || !Number.isFinite(event.timestamp)) return null;
|
|
3201
|
+
if (event.sequence !== void 0 && (typeof event.sequence !== "number" || !Number.isSafeInteger(event.sequence) || event.sequence < 0)) {
|
|
3202
|
+
return null;
|
|
3203
|
+
}
|
|
3204
|
+
return {
|
|
3205
|
+
type: event.type,
|
|
3206
|
+
payload: event.payload,
|
|
3207
|
+
timestamp: event.timestamp,
|
|
3208
|
+
...typeof event.sequence === "number" ? { sequence: event.sequence } : {}
|
|
3209
|
+
};
|
|
3210
|
+
}
|
|
3211
|
+
function asDelta(event) {
|
|
3212
|
+
if (event.type !== "textChunk") return event;
|
|
3213
|
+
const kind = asObject(event.payload)?.kind;
|
|
3214
|
+
return { ...event, type: kind === "thinking" ? "thinking" : "textDelta" };
|
|
3215
|
+
}
|
|
3216
|
+
var TURN_FRAME_TYPES = /* @__PURE__ */ new Set([
|
|
3217
|
+
"stepStart",
|
|
3218
|
+
"textDelta",
|
|
3219
|
+
"thinking",
|
|
3220
|
+
"toolCall",
|
|
3221
|
+
"toolResult"
|
|
3222
|
+
]);
|
|
3223
|
+
var TURN_END_REASONS = /* @__PURE__ */ new Set(["stop", "endTurn", "interrupted"]);
|
|
3224
|
+
function turnAfter(event, inTurn) {
|
|
3225
|
+
if (TURN_FRAME_TYPES.has(event.type)) return true;
|
|
3226
|
+
if (event.type === "error") return false;
|
|
3227
|
+
if (event.type === "stepFinish") {
|
|
3228
|
+
const payload = asObject(event.payload);
|
|
3229
|
+
if (TURN_END_REASONS.has(payload?.reason)) return false;
|
|
3230
|
+
return asObject(payload?.lifecycle)?.interruptTerminal !== true;
|
|
3231
|
+
}
|
|
3232
|
+
return inTurn;
|
|
3233
|
+
}
|
|
3234
|
+
function channelEvent(type, payload) {
|
|
3235
|
+
return { type, payload, timestamp: Date.now() };
|
|
3236
|
+
}
|
|
3237
|
+
var HttpUnsupportedError = class extends Error {
|
|
3238
|
+
constructor(status) {
|
|
3239
|
+
super(`The Agent box has no HTTP chat routes (${status}).`);
|
|
3240
|
+
this.name = "HttpUnsupportedError";
|
|
3241
|
+
}
|
|
3242
|
+
};
|
|
3243
|
+
var GrantRejectedError = class extends Error {
|
|
3244
|
+
constructor(status) {
|
|
3245
|
+
super(`The Agent box rejected the channel grant (${status}).`);
|
|
3246
|
+
this.name = "GrantRejectedError";
|
|
3247
|
+
}
|
|
3248
|
+
};
|
|
3249
|
+
var ChannelRenewalError = class extends Error {
|
|
3250
|
+
constructor(message) {
|
|
3251
|
+
super(message);
|
|
3252
|
+
this.name = "ChannelRenewalError";
|
|
3253
|
+
}
|
|
3254
|
+
};
|
|
3255
|
+
function isGrantRejection(status) {
|
|
3256
|
+
return status === 401 || status === 403;
|
|
3257
|
+
}
|
|
3258
|
+
function errorCodeOf(body) {
|
|
3259
|
+
const code = asObject(body)?.error_code;
|
|
3260
|
+
return typeof code === "string" ? code : void 0;
|
|
3261
|
+
}
|
|
3262
|
+
function withBody(response, body) {
|
|
3263
|
+
return {
|
|
3264
|
+
ok: response.ok,
|
|
3265
|
+
status: response.status,
|
|
3266
|
+
headers: response.headers,
|
|
3267
|
+
body: response.body,
|
|
3268
|
+
json: async () => body
|
|
3269
|
+
};
|
|
3270
|
+
}
|
|
3271
|
+
var AgentDirectChannel = class {
|
|
3272
|
+
constructor(tasks, fallback, options = {}) {
|
|
3273
|
+
this.tasks = tasks;
|
|
3274
|
+
this.fallback = fallback;
|
|
3275
|
+
this.options = options;
|
|
3276
|
+
}
|
|
3277
|
+
links = /* @__PURE__ */ new Map();
|
|
3278
|
+
/** Whether an open would try the box at all: the Copilot can be asked and the box reached. */
|
|
3279
|
+
canDial(transport) {
|
|
3280
|
+
return this.enabled() && this.modeFor(transport) !== null;
|
|
3281
|
+
}
|
|
3282
|
+
/**
|
|
3283
|
+
* Off until the SDK says where it talks to: without `apiUrl` the host of an offer cannot be
|
|
3284
|
+
* checked, and asking for a channel that will not be followed would still move the chat to a
|
|
3285
|
+
* box. The session then stays exactly as before the direct channel.
|
|
3286
|
+
*/
|
|
3287
|
+
enabled() {
|
|
3288
|
+
return this.options.apiUrl !== void 0 && this.tasks.channel !== void 0;
|
|
3289
|
+
}
|
|
3290
|
+
async open(taskId, observer, signal, transport) {
|
|
3291
|
+
if (!this.enabled()) return this.fallback.open(taskId, observer, signal, transport);
|
|
3292
|
+
const mode = this.modeFor(transport);
|
|
3293
|
+
const answer = mode ? await this.requestChannel(taskId) : { declined: { reason: transport === "websocket" ? "websocket" : "http_unsupported" } };
|
|
3294
|
+
if (signal?.aborted) throw signal.reason ?? new Error("Agent channel request aborted.");
|
|
3295
|
+
if ("declined" in answer || !mode) {
|
|
3296
|
+
if ("declined" in answer) observer.onEvent(channelEvent("channelDeclined", answer.declined));
|
|
3297
|
+
return this.fallback.open(taskId, observer, signal, transport);
|
|
3298
|
+
}
|
|
3299
|
+
try {
|
|
3300
|
+
return await this.openDirect(taskId, mode, answer, observer, signal);
|
|
3301
|
+
} catch (error) {
|
|
3302
|
+
if (signal?.aborted) throw error;
|
|
3303
|
+
observer.onEvent(
|
|
3304
|
+
channelEvent("channelDeclined", {
|
|
3305
|
+
reason: error instanceof HttpUnsupportedError ? "http_unsupported" : "unavailable",
|
|
3306
|
+
error: errorMessage(error)
|
|
3307
|
+
})
|
|
3308
|
+
);
|
|
3309
|
+
return this.fallback.open(taskId, observer, signal, transport);
|
|
3310
|
+
}
|
|
3311
|
+
}
|
|
3312
|
+
/**
|
|
3313
|
+
* Hands a message or an interrupt to the box when the chat is on the direct channel and its
|
|
3314
|
+
* wire is up right now. Null sends the caller to REST: no direct channel, a wire lost or
|
|
3315
|
+
* mid-redial, or an approval, which stays on REST.
|
|
3316
|
+
*
|
|
3317
|
+
* A message resolves only when the box answers for it. `stepStart` on the stream, or the 200 of
|
|
3318
|
+
* the HTTP route, is the box starting the turn the Copilot admitted: from then on the turn runs
|
|
3319
|
+
* and reaches the Copilot's log whether or not this process is still around, so a Serverless
|
|
3320
|
+
* Function may return. An `error` frame is a refusal the session already reports from the
|
|
3321
|
+
* stream, and resolves false; a refusal in the HTTP answer rejects with `AgentTaskTurnError`.
|
|
3322
|
+
* A channel lost for good, or closed, before the box answered rejects with that cause.
|
|
3323
|
+
*
|
|
3324
|
+
* A message whose wire drops before the box answers is not sent again over REST: the box may
|
|
3325
|
+
* have admitted the turn, and a second copy would start it twice. The redial replays the box
|
|
3326
|
+
* log, where the `stepStart` of an admitted turn is.
|
|
3327
|
+
*/
|
|
3328
|
+
send(taskId, input) {
|
|
3329
|
+
if (input.type === "approval_response") return null;
|
|
3330
|
+
const link = this.links.get(taskId);
|
|
3331
|
+
if (!link?.wire) return null;
|
|
3332
|
+
if (input.type !== "message") return link.wire.interrupt(input);
|
|
3333
|
+
link.admission?.fail(new Error("A newer message replaced the one waiting for the box."));
|
|
3334
|
+
let admission;
|
|
3335
|
+
const admitted = new Promise((resolve, reject) => {
|
|
3336
|
+
let timer;
|
|
3337
|
+
const arm = () => {
|
|
3338
|
+
clearTimeout(timer);
|
|
3339
|
+
timer = setTimeout(() => {
|
|
3340
|
+
admission.fail(
|
|
3341
|
+
new Error(
|
|
3342
|
+
`The Agent box did not confirm the turn within ${ADMISSION_TIMEOUT_MS / 1e3}s.`
|
|
3343
|
+
)
|
|
3344
|
+
);
|
|
3345
|
+
}, ADMISSION_TIMEOUT_MS);
|
|
3346
|
+
};
|
|
3347
|
+
const done = () => {
|
|
3348
|
+
clearTimeout(timer);
|
|
3349
|
+
if (link.admission === admission) link.admission = null;
|
|
3350
|
+
};
|
|
3351
|
+
admission = {
|
|
3352
|
+
settle: (value) => {
|
|
3353
|
+
done();
|
|
3354
|
+
resolve(value);
|
|
3355
|
+
},
|
|
3356
|
+
fail: (error) => {
|
|
3357
|
+
done();
|
|
3358
|
+
reject(error);
|
|
3359
|
+
},
|
|
3360
|
+
hold: () => clearTimeout(timer),
|
|
3361
|
+
rearm: arm
|
|
3362
|
+
};
|
|
3363
|
+
arm();
|
|
3364
|
+
});
|
|
3365
|
+
link.admission = admission;
|
|
3366
|
+
if (!link.wire.message(input, admission)) {
|
|
3367
|
+
admission.settle(false);
|
|
3368
|
+
return null;
|
|
3369
|
+
}
|
|
3370
|
+
link.inTurn = true;
|
|
3371
|
+
return admitted;
|
|
3372
|
+
}
|
|
3373
|
+
/** `websocket` needs a socket; `http` needs fetch; `auto` prefers the socket. */
|
|
3374
|
+
modeFor(transport) {
|
|
3375
|
+
const socket = this.webSocket() !== null;
|
|
3376
|
+
const http = this.fetcher() !== null;
|
|
3377
|
+
if (transport === "websocket") return socket ? "websocket" : null;
|
|
3378
|
+
if (transport === "http") return http ? "http" : null;
|
|
3379
|
+
if (socket) return "websocket";
|
|
3380
|
+
return http ? "http" : null;
|
|
3381
|
+
}
|
|
3382
|
+
webSocket() {
|
|
3383
|
+
if (this.options.WebSocket) return this.options.WebSocket;
|
|
3384
|
+
const global = globalThis.WebSocket;
|
|
3385
|
+
return typeof global === "function" ? global : null;
|
|
3386
|
+
}
|
|
3387
|
+
fetcher() {
|
|
3388
|
+
if (this.options.fetch) return this.options.fetch;
|
|
3389
|
+
const global = globalThis.fetch;
|
|
3390
|
+
return typeof global === "function" ? global : null;
|
|
3391
|
+
}
|
|
3392
|
+
/**
|
|
3393
|
+
* One request. The Copilot holds it while the box boots and answers with the channel, or an
|
|
3394
|
+
* error once the box cannot be had. A 202 comes only from a Copilot that offers no channel.
|
|
3395
|
+
*/
|
|
3396
|
+
async requestChannel(taskId) {
|
|
3397
|
+
let channel;
|
|
3398
|
+
try {
|
|
3399
|
+
channel = await this.tasks.channel(taskId);
|
|
3400
|
+
} catch (error) {
|
|
3401
|
+
const code = error?.code;
|
|
3402
|
+
return {
|
|
3403
|
+
declined: {
|
|
3404
|
+
reason: code === "INVALID_RESPONSE" ? "body" : "unavailable",
|
|
3405
|
+
error: errorMessage(error)
|
|
3406
|
+
}
|
|
3407
|
+
};
|
|
3408
|
+
}
|
|
3409
|
+
if (!channel) return { declined: { reason: "unavailable" } };
|
|
3410
|
+
if (!isChannelHostAllowed(channel.wsUrl, this.options.apiUrl)) {
|
|
3411
|
+
const host = hostOf(channel.wsUrl);
|
|
3412
|
+
return { declined: { reason: "host", ...host === void 0 ? {} : { host } } };
|
|
3413
|
+
}
|
|
3414
|
+
return channel;
|
|
3415
|
+
}
|
|
3416
|
+
/**
|
|
3417
|
+
* The box path. A drop in the middle of a turn is redialed from here, with the replay the box
|
|
3418
|
+
* offers, so the session keeps one connection and one stream. The session hears a disconnect
|
|
3419
|
+
* only when the redial gives up, when the Copilot no longer offers the box, or when there is
|
|
3420
|
+
* no turn to resume: dialing an idle box again would wake it for nobody.
|
|
3421
|
+
*
|
|
3422
|
+
* Opening never asks for an older replay. What an idle chat missed is history, which the
|
|
3423
|
+
* session loads by REST; replaying from an older cursor would put old turns on screen as live
|
|
3424
|
+
* text. The HTTP stream opens from the sequence the Copilot reported, which is the same thing.
|
|
3425
|
+
*/
|
|
3426
|
+
async openDirect(taskId, mode, channel, observer, signal) {
|
|
3427
|
+
const link = { wire: null, inTurn: false, admission: null };
|
|
3428
|
+
let box = boxAddress(channel.wsUrl);
|
|
3429
|
+
let cursor = channel.lastSequence;
|
|
3430
|
+
const abort = new AbortController();
|
|
3431
|
+
const onAbort = () => abort.abort(signal?.reason);
|
|
3432
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3433
|
+
const onFrame = (event) => {
|
|
3434
|
+
if (typeof event.sequence === "number" && event.sequence > cursor) cursor = event.sequence;
|
|
3435
|
+
link.inTurn = turnAfter(event, link.inTurn);
|
|
3436
|
+
observer.onEvent(event);
|
|
3437
|
+
if (event.type === "stepStart") link.admission?.settle(true);
|
|
3438
|
+
else if (event.type === "error") link.admission?.settle(false);
|
|
3439
|
+
};
|
|
3440
|
+
const onLost = (error, code) => {
|
|
3441
|
+
link.wire = null;
|
|
3442
|
+
if (abort.signal.aborted) return;
|
|
3443
|
+
if (!link.inTurn || code === SUPERSEDED_CLOSE_CODE) {
|
|
3444
|
+
link.admission?.fail(error);
|
|
3445
|
+
observer.onDisconnect(error);
|
|
3446
|
+
return;
|
|
3447
|
+
}
|
|
3448
|
+
link.admission?.hold();
|
|
3449
|
+
void this.redial(taskId, mode, error, abort.signal, observer, {
|
|
3450
|
+
onFrame,
|
|
3451
|
+
onLost,
|
|
3452
|
+
replayFrom: (next) => {
|
|
3453
|
+
const nextBox = boxAddress(next.wsUrl);
|
|
3454
|
+
if (nextBox === box) return cursor;
|
|
3455
|
+
box = nextBox;
|
|
3456
|
+
cursor = next.lastSequence;
|
|
3457
|
+
return void 0;
|
|
3458
|
+
}
|
|
3459
|
+
}).then((outcome) => {
|
|
3460
|
+
if (outcome instanceof Error) link.admission?.fail(outcome);
|
|
3461
|
+
else if (outcome) {
|
|
3462
|
+
link.wire = outcome;
|
|
3463
|
+
link.admission?.rearm();
|
|
3464
|
+
}
|
|
3465
|
+
});
|
|
3466
|
+
};
|
|
3467
|
+
try {
|
|
3468
|
+
link.wire = await this.connect(taskId, mode, channel, {
|
|
3469
|
+
signal: abort.signal,
|
|
3470
|
+
onFrame,
|
|
3471
|
+
onLost
|
|
3472
|
+
});
|
|
3473
|
+
} catch (error) {
|
|
3474
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3475
|
+
throw error;
|
|
3476
|
+
}
|
|
3477
|
+
this.links.set(taskId, link);
|
|
3478
|
+
return {
|
|
3479
|
+
close: () => {
|
|
3480
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3481
|
+
abort.abort();
|
|
3482
|
+
link.wire?.close();
|
|
3483
|
+
link.wire = null;
|
|
3484
|
+
link.admission?.fail(
|
|
3485
|
+
new Error("The Agent session closed before the box confirmed the turn.")
|
|
3486
|
+
);
|
|
3487
|
+
if (this.links.get(taskId) === link) this.links.delete(taskId);
|
|
3488
|
+
}
|
|
3489
|
+
};
|
|
3490
|
+
}
|
|
3491
|
+
async connect(taskId, mode, channel, options) {
|
|
3492
|
+
if (mode === "http") return this.openHttp(taskId, channel, options);
|
|
3493
|
+
const socket = await this.dial(channel.wsUrl, options);
|
|
3494
|
+
return {
|
|
3495
|
+
close: () => socket.close(),
|
|
3496
|
+
interrupt: (input) => socket.send(JSON.stringify(input)) ? Promise.resolve(true) : null,
|
|
3497
|
+
message: (input) => socket.send(JSON.stringify(input))
|
|
3498
|
+
};
|
|
3499
|
+
}
|
|
3500
|
+
async redial(taskId, mode, cause, signal, observer, handlers) {
|
|
3501
|
+
let lastError = cause;
|
|
3502
|
+
for (const [index, delayMs] of RECONNECT_DELAYS_MS.entries()) {
|
|
3503
|
+
const attempt = index + 1;
|
|
3504
|
+
observer.onEvent(
|
|
3505
|
+
channelEvent("channelReconnecting", {
|
|
3506
|
+
attempt,
|
|
3507
|
+
maxAttempts: RECONNECT_DELAYS_MS.length,
|
|
3508
|
+
reason: lastError.message
|
|
3509
|
+
})
|
|
3510
|
+
);
|
|
3511
|
+
await sleep(delayMs, signal);
|
|
3512
|
+
if (signal.aborted) return null;
|
|
3513
|
+
const outcome = await this.reopenOnce(taskId, mode, signal, handlers);
|
|
3514
|
+
if (signal.aborted) {
|
|
3515
|
+
if (outcome.kind === "wire") outcome.wire.close();
|
|
3516
|
+
return null;
|
|
3517
|
+
}
|
|
3518
|
+
if (outcome.kind === "wire") {
|
|
3519
|
+
observer.onEvent(channelEvent("channelConnected", { attempt }));
|
|
3520
|
+
return outcome.wire;
|
|
3521
|
+
}
|
|
3522
|
+
if (outcome.kind === "refused") {
|
|
3523
|
+
const refused = new Error(
|
|
3524
|
+
`The Copilot no longer offers the box channel (after: ${cause.message})`
|
|
3525
|
+
);
|
|
3526
|
+
observer.onDisconnect(refused);
|
|
3527
|
+
return refused;
|
|
3528
|
+
}
|
|
3529
|
+
lastError = outcome.error;
|
|
3530
|
+
}
|
|
3531
|
+
const exhausted = new Error(
|
|
3532
|
+
`Agent box channel could not be reopened after ${RECONNECT_DELAYS_MS.length} attempts: ${lastError.message}`
|
|
3533
|
+
);
|
|
3534
|
+
observer.onDisconnect(exhausted);
|
|
3535
|
+
return exhausted;
|
|
3536
|
+
}
|
|
3537
|
+
// One attempt to get the box back: the channel request, then the dial. A failure is returned
|
|
3538
|
+
// rather than thrown, so the caller decides between another attempt and giving up.
|
|
3539
|
+
async reopenOnce(taskId, mode, signal, handlers) {
|
|
3540
|
+
let channel;
|
|
3541
|
+
try {
|
|
3542
|
+
channel = await this.tasks.channel(taskId);
|
|
3543
|
+
} catch (error) {
|
|
3544
|
+
return { kind: "failed", error: error instanceof Error ? error : new Error(String(error)) };
|
|
3545
|
+
}
|
|
3546
|
+
if (!channel || !isChannelHostAllowed(channel.wsUrl, this.options.apiUrl)) {
|
|
3547
|
+
return { kind: "refused" };
|
|
3548
|
+
}
|
|
3549
|
+
try {
|
|
3550
|
+
const replayFrom = handlers.replayFrom(channel);
|
|
3551
|
+
const wire = await this.connect(taskId, mode, channel, {
|
|
3552
|
+
onFrame: handlers.onFrame,
|
|
3553
|
+
onLost: handlers.onLost,
|
|
3554
|
+
signal,
|
|
3555
|
+
...replayFrom === void 0 ? {} : { replayFrom }
|
|
3556
|
+
});
|
|
3557
|
+
return { kind: "wire", wire };
|
|
3558
|
+
} catch (error) {
|
|
3559
|
+
if (error instanceof HttpUnsupportedError) return { kind: "refused" };
|
|
3560
|
+
return { kind: "failed", error: error instanceof Error ? error : new Error(String(error)) };
|
|
3561
|
+
}
|
|
3562
|
+
}
|
|
3563
|
+
/**
|
|
3564
|
+
* The box over HTTP: the event stream reads what the socket would carry, from the sequence
|
|
3565
|
+
* asked, and each message is a POST the box answers once the turn was admitted.
|
|
3566
|
+
*
|
|
3567
|
+
* The URLs carry a grant that lasts 10 minutes and, behind the dev proxy, a ticket that lasts
|
|
3568
|
+
* 60 seconds. A 401 or 403 without an `error_code` is that grant gone stale: the Copilot is
|
|
3569
|
+
* asked for the channel again and the request goes once more on the fresh URLs. A second
|
|
3570
|
+
* rejection is an error. With an `error_code` it is a refusal, answered once as it came.
|
|
3571
|
+
*/
|
|
3572
|
+
async openHttp(taskId, channel, options) {
|
|
3573
|
+
const fetch = this.fetcher();
|
|
3574
|
+
if (!fetch) throw new TypeError("fetch is not available.");
|
|
3575
|
+
const fromSequence = String(options.replayFrom ?? channel.lastSequence);
|
|
3576
|
+
let current = channel;
|
|
3577
|
+
const renew = async () => {
|
|
3578
|
+
let next;
|
|
3579
|
+
try {
|
|
3580
|
+
next = await this.tasks.channel(taskId);
|
|
3581
|
+
} catch (error) {
|
|
3582
|
+
throw new ChannelRenewalError(
|
|
3583
|
+
`The Agent box channel could not be renewed: ${errorMessage(error)}`
|
|
3584
|
+
);
|
|
3585
|
+
}
|
|
3586
|
+
if (!next || !isChannelHostAllowed(next.wsUrl, this.options.apiUrl)) {
|
|
3587
|
+
throw new ChannelRenewalError("The Copilot no longer offers the box channel.");
|
|
3588
|
+
}
|
|
3589
|
+
current = next;
|
|
3590
|
+
};
|
|
3591
|
+
const eventsUrl = () => {
|
|
3592
|
+
const url = new URL(boxRoute(current.wsUrl, "events"));
|
|
3593
|
+
url.searchParams.set("fromSequence", fromSequence);
|
|
3594
|
+
return url.toString();
|
|
3595
|
+
};
|
|
3596
|
+
let close;
|
|
3597
|
+
try {
|
|
3598
|
+
close = await this.readEvents(fetch, eventsUrl(), options);
|
|
3599
|
+
} catch (error) {
|
|
3600
|
+
if (!(error instanceof GrantRejectedError)) throw error;
|
|
3601
|
+
await renew();
|
|
3602
|
+
close = await this.readEvents(fetch, eventsUrl(), options);
|
|
3603
|
+
}
|
|
3604
|
+
const postOnce = (input) => fetch(boxRoute(current.wsUrl, "messages"), {
|
|
3605
|
+
method: "POST",
|
|
3606
|
+
headers: { "Content-Type": "application/json" },
|
|
3607
|
+
body: JSON.stringify(input),
|
|
3608
|
+
// The URL carries the grant: a redirect would hand it to wherever it points.
|
|
3609
|
+
redirect: "error"
|
|
3610
|
+
});
|
|
3611
|
+
const post = async (input) => {
|
|
3612
|
+
const response = await postOnce(input);
|
|
3613
|
+
if (!isGrantRejection(response.status)) return response;
|
|
3614
|
+
const body = await response.json().catch(() => null);
|
|
3615
|
+
if (errorCodeOf(body) !== void 0) return withBody(response, body);
|
|
3616
|
+
await renew();
|
|
3617
|
+
return postOnce(input);
|
|
3618
|
+
};
|
|
3619
|
+
return {
|
|
3620
|
+
close,
|
|
3621
|
+
interrupt: (input) => post(input).then((response) => {
|
|
3622
|
+
if (!response.ok) {
|
|
3623
|
+
throw new Error(`The Agent box refused the interrupt (${response.status}).`);
|
|
3624
|
+
}
|
|
3625
|
+
return true;
|
|
3626
|
+
}),
|
|
3627
|
+
message: (input, admission) => {
|
|
3628
|
+
post(input).then(
|
|
3629
|
+
async (response) => {
|
|
3630
|
+
if (response.ok) {
|
|
3631
|
+
admission.settle(true);
|
|
3632
|
+
return;
|
|
3633
|
+
}
|
|
3634
|
+
const body = asObject(await response.json().catch(() => null));
|
|
3635
|
+
const code = errorCodeOf(body);
|
|
3636
|
+
if (isGrantRejection(response.status) && code === void 0) {
|
|
3637
|
+
admission.fail(new GrantRejectedError(response.status));
|
|
3638
|
+
return;
|
|
3639
|
+
}
|
|
3640
|
+
const fallback = response.status === 504 ? "The Agent box got no admission for the turn (504)." : `The Agent box refused the message (${response.status}).`;
|
|
3641
|
+
const message = typeof body?.message === "string" ? body.message : fallback;
|
|
3642
|
+
admission.fail(new AgentTaskTurnError(message, code));
|
|
3643
|
+
},
|
|
3644
|
+
(error) => {
|
|
3645
|
+
if (error instanceof ChannelRenewalError) admission.fail(error);
|
|
3646
|
+
}
|
|
3647
|
+
);
|
|
3648
|
+
return true;
|
|
3649
|
+
}
|
|
3650
|
+
};
|
|
3651
|
+
}
|
|
3652
|
+
/** Opens the box event stream; resolves once the box answered, with the way to close it. */
|
|
3653
|
+
async readEvents(fetch, url, options) {
|
|
3654
|
+
if (options.signal?.aborted) throw new Error("Agent box event stream aborted.");
|
|
3655
|
+
const abort = new AbortController();
|
|
3656
|
+
let intentionalClose = false;
|
|
3657
|
+
const close = () => {
|
|
3658
|
+
if (intentionalClose) return;
|
|
3659
|
+
intentionalClose = true;
|
|
3660
|
+
options.signal?.removeEventListener("abort", close);
|
|
3661
|
+
abort.abort();
|
|
3662
|
+
};
|
|
3663
|
+
options.signal?.addEventListener("abort", close, { once: true });
|
|
3664
|
+
const handshake = setTimeout(() => abort.abort(), CONNECT_TIMEOUT_MS);
|
|
3665
|
+
let response;
|
|
3666
|
+
try {
|
|
3667
|
+
response = await fetch(url, {
|
|
3668
|
+
headers: { Accept: "text/event-stream" },
|
|
3669
|
+
signal: abort.signal,
|
|
3670
|
+
redirect: "error"
|
|
3671
|
+
});
|
|
3672
|
+
} catch (error) {
|
|
3673
|
+
close();
|
|
3674
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
3675
|
+
} finally {
|
|
3676
|
+
clearTimeout(handshake);
|
|
3677
|
+
}
|
|
3678
|
+
if (!response.ok || !response.body) {
|
|
3679
|
+
close();
|
|
3680
|
+
if (response.status === 404) throw new HttpUnsupportedError(response.status);
|
|
3681
|
+
if (isGrantRejection(response.status)) {
|
|
3682
|
+
const body = await response.json().catch(() => null);
|
|
3683
|
+
if (errorCodeOf(body) === void 0) throw new GrantRejectedError(response.status);
|
|
3684
|
+
}
|
|
3685
|
+
throw new Error(`Agent box event stream failed (${response.status}).`);
|
|
3686
|
+
}
|
|
3687
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
3688
|
+
if (!/^text\/event-stream\b/i.test(contentType)) {
|
|
3689
|
+
close();
|
|
3690
|
+
throw new HttpUnsupportedError(contentType || "no content type");
|
|
3691
|
+
}
|
|
3692
|
+
const lost = (error) => {
|
|
3693
|
+
if (intentionalClose) return;
|
|
3694
|
+
close();
|
|
3695
|
+
options.onLost(error);
|
|
3696
|
+
};
|
|
3697
|
+
void readSse(response.body.getReader(), (event) => options.onFrame(asDelta(event))).then(() => lost(new Error("Agent box event stream ended."))).catch((error) => lost(error instanceof Error ? error : new Error(String(error))));
|
|
3698
|
+
return close;
|
|
3699
|
+
}
|
|
3700
|
+
dial(url, options) {
|
|
3701
|
+
const Socket = this.webSocket();
|
|
3702
|
+
if (!Socket) return Promise.reject(new TypeError("WebSocket is not available."));
|
|
3703
|
+
const { signal, replayFrom } = options;
|
|
3704
|
+
return new Promise((resolve, reject) => {
|
|
3705
|
+
const socket = new Socket(url);
|
|
3706
|
+
let opened = false;
|
|
3707
|
+
let intentionalClose = false;
|
|
3708
|
+
let settled = false;
|
|
3709
|
+
let silence = null;
|
|
3710
|
+
const clearSilence = () => {
|
|
3711
|
+
if (silence !== null) clearTimeout(silence);
|
|
3712
|
+
silence = null;
|
|
3713
|
+
};
|
|
3714
|
+
const removeAbortListener = () => signal?.removeEventListener("abort", onAbort);
|
|
3715
|
+
const rejectHandshake = (error) => {
|
|
3716
|
+
if (settled) return;
|
|
3717
|
+
settled = true;
|
|
3718
|
+
intentionalClose = true;
|
|
3719
|
+
clearTimeout(timer);
|
|
3720
|
+
removeAbortListener();
|
|
3721
|
+
socket.close();
|
|
3722
|
+
reject(error);
|
|
3723
|
+
};
|
|
3724
|
+
const touch = () => {
|
|
3725
|
+
clearSilence();
|
|
3726
|
+
silence = setTimeout(() => {
|
|
3727
|
+
if (intentionalClose) return;
|
|
3728
|
+
intentionalClose = true;
|
|
3729
|
+
removeAbortListener();
|
|
3730
|
+
options.onLost(
|
|
3731
|
+
new Error(`Agent WebSocket went silent for ${SILENCE_TIMEOUT_MS / 1e3}s.`)
|
|
3732
|
+
);
|
|
3733
|
+
socket.close(1e3, "Client closed");
|
|
3734
|
+
}, SILENCE_TIMEOUT_MS);
|
|
3735
|
+
};
|
|
3736
|
+
const close = () => {
|
|
3737
|
+
if (intentionalClose) return;
|
|
3738
|
+
intentionalClose = true;
|
|
3739
|
+
clearSilence();
|
|
3740
|
+
removeAbortListener();
|
|
3741
|
+
socket.close(1e3, "Client closed");
|
|
3742
|
+
};
|
|
3743
|
+
const send = (frame) => {
|
|
3744
|
+
if (intentionalClose || socket.readyState !== SOCKET_OPEN) return false;
|
|
3745
|
+
try {
|
|
3746
|
+
socket.send(frame);
|
|
3747
|
+
return true;
|
|
3748
|
+
} catch {
|
|
3749
|
+
return false;
|
|
3750
|
+
}
|
|
3751
|
+
};
|
|
3752
|
+
const onAbort = () => {
|
|
3753
|
+
if (!opened) {
|
|
3754
|
+
rejectHandshake(
|
|
3755
|
+
signal?.reason instanceof Error ? signal.reason : new Error("Agent WebSocket connection aborted.")
|
|
3756
|
+
);
|
|
3757
|
+
return;
|
|
3758
|
+
}
|
|
3759
|
+
close();
|
|
3760
|
+
};
|
|
3761
|
+
const timer = setTimeout(() => {
|
|
3762
|
+
rejectHandshake(new Error("Timed out connecting to the Agent WebSocket."));
|
|
3763
|
+
}, CONNECT_TIMEOUT_MS);
|
|
3764
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3765
|
+
const handlers = socket;
|
|
3766
|
+
handlers.onopen = () => {
|
|
3767
|
+
if (settled) return;
|
|
3768
|
+
opened = true;
|
|
3769
|
+
settled = true;
|
|
3770
|
+
clearTimeout(timer);
|
|
3771
|
+
touch();
|
|
3772
|
+
if (replayFrom !== void 0) {
|
|
3773
|
+
try {
|
|
3774
|
+
socket.send(JSON.stringify({ type: "replay", fromSequence: replayFrom }));
|
|
3775
|
+
} catch {
|
|
3776
|
+
}
|
|
3777
|
+
}
|
|
3778
|
+
resolve({ close, send });
|
|
3779
|
+
};
|
|
3780
|
+
handlers.onerror = () => {
|
|
3781
|
+
if (!opened) rejectHandshake(new Error("Failed to connect to the Agent WebSocket."));
|
|
3782
|
+
};
|
|
3783
|
+
handlers.onmessage = (message) => {
|
|
3784
|
+
touch();
|
|
3785
|
+
const event = parseEvent(message.data);
|
|
3786
|
+
if (event) options.onFrame(asDelta(event));
|
|
3787
|
+
};
|
|
3788
|
+
handlers.onclose = (event) => {
|
|
3789
|
+
clearTimeout(timer);
|
|
3790
|
+
clearSilence();
|
|
3791
|
+
removeAbortListener();
|
|
3792
|
+
if (!opened) {
|
|
3793
|
+
rejectHandshake(new Error(`Agent WebSocket closed during handshake (${event.code}).`));
|
|
3794
|
+
return;
|
|
3795
|
+
}
|
|
3796
|
+
if (!intentionalClose) {
|
|
3797
|
+
options.onLost(new Error(`Agent WebSocket closed (${event.code}).`), event.code);
|
|
3798
|
+
}
|
|
3799
|
+
};
|
|
3800
|
+
});
|
|
3801
|
+
}
|
|
3802
|
+
};
|
|
3803
|
+
|
|
3804
|
+
// src/agentSession.ts
|
|
3805
|
+
var AGENT_QUEUE_LIMIT = 10;
|
|
3806
|
+
var CANCEL_SAFETY_MS = 1e4;
|
|
3807
|
+
var RECONCILE_DELAY_MS = 1e3;
|
|
3808
|
+
function asObject2(value) {
|
|
3809
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3810
|
+
}
|
|
3811
|
+
function errorMessage2(error) {
|
|
3080
3812
|
if (error instanceof Error) return error.message;
|
|
3081
3813
|
if (error && typeof error === "object" && "message" in error) {
|
|
3082
3814
|
return String(error.message);
|
|
@@ -3122,14 +3854,18 @@ function toAgentTimelineItem(message) {
|
|
|
3122
3854
|
}
|
|
3123
3855
|
function createAgentTaskSessionManager(options) {
|
|
3124
3856
|
const sessions = /* @__PURE__ */ new Map();
|
|
3857
|
+
const channel = new AgentDirectChannel(options.tasks, options.eventSource, options.directChannel);
|
|
3125
3858
|
return {
|
|
3126
|
-
session(
|
|
3127
|
-
if ("taskId" in
|
|
3128
|
-
const current = sessions.get(
|
|
3859
|
+
session(requested) {
|
|
3860
|
+
if ("taskId" in requested) {
|
|
3861
|
+
const current = sessions.get(requested.taskId);
|
|
3129
3862
|
if (current && current.status !== "closed") return current;
|
|
3130
3863
|
}
|
|
3864
|
+
const sessionOptions = "create" in requested && requested.agentId && !requested.runtime && channel.canDial(requested.transport) ? { ...requested, runtime: "T3" } : requested;
|
|
3131
3865
|
const session = new CoreAgentTaskSession(sessionOptions, {
|
|
3132
|
-
|
|
3866
|
+
tasks: options.tasks,
|
|
3867
|
+
eventSource: options.eventSource,
|
|
3868
|
+
channel,
|
|
3133
3869
|
onTaskId: (taskId, value) => sessions.set(taskId, value),
|
|
3134
3870
|
onClose: (taskId, value) => {
|
|
3135
3871
|
if (sessions.get(taskId) === value) sessions.delete(taskId);
|
|
@@ -3377,7 +4113,7 @@ var CoreAgentTaskSession = class {
|
|
|
3377
4113
|
this.activeWaiter = waiter;
|
|
3378
4114
|
this.setStatus("streaming");
|
|
3379
4115
|
this.emit("turnStart", {});
|
|
3380
|
-
await this.sendInput(input);
|
|
4116
|
+
if (await this.sendInput(input)) this.emit("accepted", {});
|
|
3381
4117
|
}
|
|
3382
4118
|
async ensureTask() {
|
|
3383
4119
|
if (this._taskId) return;
|
|
@@ -3409,7 +4145,8 @@ var CoreAgentTaskSession = class {
|
|
|
3409
4145
|
if (!this._taskId) return Promise.reject(new Error("Agent task has not been created."));
|
|
3410
4146
|
const abort = new AbortController();
|
|
3411
4147
|
this.connectionAbort = abort;
|
|
3412
|
-
this.
|
|
4148
|
+
const source = this._task?.agentId ? this.dependencies.channel : this.dependencies.eventSource;
|
|
4149
|
+
this.connectionPromise = source.open(
|
|
3413
4150
|
this._taskId,
|
|
3414
4151
|
{
|
|
3415
4152
|
onEvent: (event) => this.handleEvent(event),
|
|
@@ -3456,7 +4193,7 @@ var CoreAgentTaskSession = class {
|
|
|
3456
4193
|
}
|
|
3457
4194
|
} catch (error) {
|
|
3458
4195
|
if (this.isClosed()) return;
|
|
3459
|
-
const recoveryError = error instanceof Error ? error : new Error(
|
|
4196
|
+
const recoveryError = error instanceof Error ? error : new Error(errorMessage2(error));
|
|
3460
4197
|
this.failLiveChannel(error, recoveryError);
|
|
3461
4198
|
}
|
|
3462
4199
|
}
|
|
@@ -3490,13 +4227,17 @@ var CoreAgentTaskSession = class {
|
|
|
3490
4227
|
this.finishTurn(reason);
|
|
3491
4228
|
return true;
|
|
3492
4229
|
}
|
|
3493
|
-
|
|
3494
|
-
|
|
3495
|
-
|
|
4230
|
+
/** True once the server took the input; false when the box refused it on the stream. */
|
|
4231
|
+
async sendInput(input) {
|
|
4232
|
+
if (!this._taskId) throw new Error("Agent task has not been created.");
|
|
4233
|
+
const direct = this.dependencies.channel.send(this._taskId, input);
|
|
4234
|
+
if (direct) return direct;
|
|
4235
|
+
await this.dependencies.tasks.sendInput(this._taskId, input);
|
|
4236
|
+
return true;
|
|
3496
4237
|
}
|
|
3497
4238
|
handleEvent(event) {
|
|
3498
4239
|
this.emit("raw", event);
|
|
3499
|
-
const payload =
|
|
4240
|
+
const payload = asObject2(event.payload);
|
|
3500
4241
|
switch (event.type) {
|
|
3501
4242
|
// A box transmite o texto do agente ao vivo em `textDelta` e grava o mesmo texto no log
|
|
3502
4243
|
// como `textChunk`. Uma repeticao depois de uma queda devolve chunks, entao trata-los como
|
|
@@ -3561,7 +4302,7 @@ var CoreAgentTaskSession = class {
|
|
|
3561
4302
|
if (this.finishedTurnIds.length > 8) this.finishedTurnIds.shift();
|
|
3562
4303
|
}
|
|
3563
4304
|
consumeDelta(payload, kind) {
|
|
3564
|
-
const lifecycle =
|
|
4305
|
+
const lifecycle = asObject2(payload?.lifecycle);
|
|
3565
4306
|
const turnId = typeof lifecycle?.turnId === "string" ? lifecycle.turnId : null;
|
|
3566
4307
|
if (turnId && this.finishedTurnIds.includes(turnId)) return;
|
|
3567
4308
|
const idle = this._status !== "streaming" && this._status !== "cancelled";
|
|
@@ -3719,7 +4460,7 @@ var CoreAgentTaskSession = class {
|
|
|
3719
4460
|
const code = errorCode(error);
|
|
3720
4461
|
this.emit("error", {
|
|
3721
4462
|
...code ? { code } : {},
|
|
3722
|
-
error: `${prefix}: ${
|
|
4463
|
+
error: `${prefix}: ${errorMessage2(error)}`
|
|
3723
4464
|
});
|
|
3724
4465
|
}
|
|
3725
4466
|
setStatus(status) {
|