@dudousxd/nestjs-agent-core 0.12.0 → 0.13.0
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/README.md +16 -2
- package/dist/index.cjs +3190 -637
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2350 -38
- package/dist/index.d.ts +2350 -38
- package/dist/index.js +3105 -631
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -22,6 +22,9 @@ var AGENT_PROMPT_CONTRIBUTORS = Symbol.for("@dudousxd/nestjs-agent:prompt-contri
|
|
|
22
22
|
var AGENT_ACTOR_DIRECTORY = Symbol.for("@dudousxd/nestjs-agent:actor-directory");
|
|
23
23
|
var AGENT_ATTACHMENT_STAGING = Symbol.for("@dudousxd/nestjs-agent:attachment-staging");
|
|
24
24
|
var AGENT_APPROVAL_PORT = Symbol.for("@dudousxd/nestjs-agent:approval-port");
|
|
25
|
+
var AGENT_SKILLS = Symbol.for("@dudousxd/nestjs-agent:skills");
|
|
26
|
+
var AGENT_MEMORY = Symbol.for("@dudousxd/nestjs-agent:memory");
|
|
27
|
+
var AGENT_SKILL_SOURCES = Symbol.for("@dudousxd/nestjs-agent:skill-sources");
|
|
25
28
|
|
|
26
29
|
// src/spi/token-stream-sink.ts
|
|
27
30
|
var AgentStreamError = class extends Error {
|
|
@@ -43,6 +46,17 @@ function encodeStreamEvent(event) {
|
|
|
43
46
|
`);
|
|
44
47
|
}
|
|
45
48
|
__name(encodeStreamEvent, "encodeStreamEvent");
|
|
49
|
+
function decodeStreamEvent(line) {
|
|
50
|
+
try {
|
|
51
|
+
const parsed = JSON.parse(line);
|
|
52
|
+
if (typeof parsed === "object" && parsed !== null && typeof parsed.kind === "string") {
|
|
53
|
+
return parsed;
|
|
54
|
+
}
|
|
55
|
+
} catch {
|
|
56
|
+
}
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
__name(decodeStreamEvent, "decodeStreamEvent");
|
|
46
60
|
|
|
47
61
|
// src/spi/pricing-store.ts
|
|
48
62
|
async function seedModelPrices(store, prices) {
|
|
@@ -52,6 +66,40 @@ async function seedModelPrices(store, prices) {
|
|
|
52
66
|
}
|
|
53
67
|
__name(seedModelPrices, "seedModelPrices");
|
|
54
68
|
|
|
69
|
+
// src/spi/processors.ts
|
|
70
|
+
var DEFAULT_INCREMENTAL_LOOKBACK_CHARS = 64;
|
|
71
|
+
var OutputRejectedError = class extends Error {
|
|
72
|
+
static {
|
|
73
|
+
__name(this, "OutputRejectedError");
|
|
74
|
+
}
|
|
75
|
+
/** {@link OutputProcessor.name} of the processor that refused. */
|
|
76
|
+
processor;
|
|
77
|
+
/** The reason it gave, verbatim. */
|
|
78
|
+
reason;
|
|
79
|
+
constructor(processor, reason) {
|
|
80
|
+
super(`Output rejected by "${processor}": ${reason}`);
|
|
81
|
+
this.name = "OutputRejectedError";
|
|
82
|
+
this.processor = processor;
|
|
83
|
+
this.reason = reason;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
var ProcessorFailedError = class extends Error {
|
|
87
|
+
static {
|
|
88
|
+
__name(this, "ProcessorFailedError");
|
|
89
|
+
}
|
|
90
|
+
/** Which seam it was on, so a reader knows whether the prompt or the answer was in flight. */
|
|
91
|
+
phase;
|
|
92
|
+
/** The processor's `name`. */
|
|
93
|
+
processor;
|
|
94
|
+
constructor(phase, processor, cause) {
|
|
95
|
+
super(`${phase} processor "${processor}" failed: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
96
|
+
this.name = "ProcessorFailedError";
|
|
97
|
+
this.phase = phase;
|
|
98
|
+
this.processor = processor;
|
|
99
|
+
this.cause = cause;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
|
|
55
103
|
// src/spi/governance-queries.ts
|
|
56
104
|
var THREAD_DETAIL_CONTENT_CHARS = 2e3;
|
|
57
105
|
function truncateDetailContent(content) {
|
|
@@ -268,464 +316,2753 @@ function filterToolsByAllowList(tools, allowedTools) {
|
|
|
268
316
|
}
|
|
269
317
|
__name(filterToolsByAllowList, "filterToolsByAllowList");
|
|
270
318
|
|
|
271
|
-
// src/
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
319
|
+
// src/history.ts
|
|
320
|
+
function estimateMessageTokens(message) {
|
|
321
|
+
const extras = (message.toolCalls !== void 0 ? JSON.stringify(message.toolCalls).length : 0) + (message.toolResults !== void 0 ? JSON.stringify(message.toolResults).length : 0);
|
|
322
|
+
return Math.ceil((message.content.length + extras) / 4) + 4;
|
|
323
|
+
}
|
|
324
|
+
__name(estimateMessageTokens, "estimateMessageTokens");
|
|
325
|
+
function windowHistory(options) {
|
|
326
|
+
const estimate = options.estimate ?? estimateMessageTokens;
|
|
327
|
+
const policy = {
|
|
328
|
+
// A suffix selection of at most `maxMessages` rows, which is exactly what `HistoryPolicy`'s row
|
|
329
|
+
// hint promises — so the store can bound its read to that many of the thread's newest messages.
|
|
330
|
+
// A token-only window declares nothing: its budget names no row count.
|
|
331
|
+
...options.maxMessages !== void 0 ? {
|
|
332
|
+
maxMessages: options.maxMessages
|
|
333
|
+
} : {},
|
|
334
|
+
select(messages) {
|
|
335
|
+
let cut = 0;
|
|
336
|
+
if (options.maxMessages !== void 0) {
|
|
337
|
+
cut = Math.max(cut, messages.length - options.maxMessages);
|
|
338
|
+
}
|
|
339
|
+
if (options.maxTokens !== void 0) {
|
|
340
|
+
cut = Math.max(cut, tokenCut(messages, options.maxTokens, estimate));
|
|
341
|
+
}
|
|
342
|
+
cut = Math.min(cut, Math.max(0, messages.length - 1));
|
|
343
|
+
return {
|
|
344
|
+
keep: messages.slice(cut),
|
|
345
|
+
drop: messages.slice(0, cut)
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
return options.summarize !== void 0 ? {
|
|
350
|
+
...policy,
|
|
351
|
+
summarize: options.summarize
|
|
352
|
+
} : policy;
|
|
353
|
+
}
|
|
354
|
+
__name(windowHistory, "windowHistory");
|
|
355
|
+
function tokenCut(messages, maxTokens, estimate) {
|
|
356
|
+
let index = messages.length;
|
|
357
|
+
let total = 0;
|
|
358
|
+
while (index > 0) {
|
|
359
|
+
const message = messages[index - 1];
|
|
360
|
+
if (message === void 0) {
|
|
361
|
+
break;
|
|
362
|
+
}
|
|
363
|
+
const cost = estimate(message);
|
|
364
|
+
if (index < messages.length && total + cost > maxTokens) {
|
|
365
|
+
break;
|
|
366
|
+
}
|
|
367
|
+
total += cost;
|
|
368
|
+
index -= 1;
|
|
275
369
|
}
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
370
|
+
return index;
|
|
371
|
+
}
|
|
372
|
+
__name(tokenCut, "tokenCut");
|
|
373
|
+
var DEFAULT_HISTORY_SUMMARY_INSTRUCTION = "Summarize this conversation for an assistant that will continue it without seeing these messages. Preserve decisions made, facts and constraints the user stated, identifiers and names mentioned, and anything left unresolved. Omit pleasantries. Reply with the summary only \u2014 no preamble, no headings.";
|
|
374
|
+
function summarizeWithModel(model, instruction = DEFAULT_HISTORY_SUMMARY_INSTRUCTION) {
|
|
375
|
+
return async (dropped) => {
|
|
376
|
+
const discard = {
|
|
377
|
+
write: /* @__PURE__ */ __name(() => {
|
|
378
|
+
}, "write"),
|
|
379
|
+
end: /* @__PURE__ */ __name(() => {
|
|
380
|
+
}, "end"),
|
|
381
|
+
fail: /* @__PURE__ */ __name(() => {
|
|
382
|
+
}, "fail")
|
|
383
|
+
};
|
|
384
|
+
const turn = await model.runTurn({
|
|
385
|
+
system: instruction,
|
|
386
|
+
messages: dropped,
|
|
387
|
+
tools: [],
|
|
388
|
+
sink: discard
|
|
389
|
+
});
|
|
390
|
+
return {
|
|
391
|
+
text: turn.text,
|
|
392
|
+
usage: turn.usage,
|
|
393
|
+
...turn.modelId !== void 0 ? {
|
|
394
|
+
modelId: turn.modelId
|
|
395
|
+
} : {}
|
|
396
|
+
};
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
__name(summarizeWithModel, "summarizeWithModel");
|
|
400
|
+
|
|
401
|
+
// src/processors.ts
|
|
402
|
+
var decoder = new TextDecoder();
|
|
403
|
+
function createFrameBuffer() {
|
|
404
|
+
const frames = [];
|
|
405
|
+
return {
|
|
406
|
+
writer: {
|
|
407
|
+
write: /* @__PURE__ */ __name((chunk) => {
|
|
408
|
+
for (const line of decoder.decode(chunk).split("\n")) {
|
|
409
|
+
if (line.length > 0) {
|
|
410
|
+
frames.push(line);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}, "write"),
|
|
414
|
+
end: /* @__PURE__ */ __name(() => {
|
|
415
|
+
}, "end"),
|
|
416
|
+
fail: /* @__PURE__ */ __name(() => {
|
|
417
|
+
}, "fail")
|
|
418
|
+
},
|
|
419
|
+
frames: /* @__PURE__ */ __name(() => frames, "frames")
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
__name(createFrameBuffer, "createFrameBuffer");
|
|
423
|
+
function releaseGatedFrames(frames, text) {
|
|
424
|
+
const released = [];
|
|
425
|
+
let emitted = false;
|
|
426
|
+
for (const frame of frames) {
|
|
427
|
+
const event = decodeStreamEvent(frame);
|
|
428
|
+
if (event === null || event.kind === "text") {
|
|
429
|
+
if (!emitted && text.length > 0) {
|
|
430
|
+
released.push(encodeStreamEvent({
|
|
431
|
+
kind: "text",
|
|
432
|
+
text
|
|
433
|
+
}));
|
|
434
|
+
emitted = true;
|
|
435
|
+
}
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
released.push(encodeStreamEvent(event));
|
|
279
439
|
}
|
|
280
|
-
|
|
281
|
-
|
|
440
|
+
if (!emitted && text.length > 0) {
|
|
441
|
+
released.push(encodeStreamEvent({
|
|
442
|
+
kind: "text",
|
|
443
|
+
text
|
|
444
|
+
}));
|
|
282
445
|
}
|
|
283
|
-
|
|
284
|
-
|
|
446
|
+
return released;
|
|
447
|
+
}
|
|
448
|
+
__name(releaseGatedFrames, "releaseGatedFrames");
|
|
449
|
+
async function runInputProcessors(processors, prompt, ctx) {
|
|
450
|
+
let current = prompt;
|
|
451
|
+
for (const processor of processors) {
|
|
452
|
+
try {
|
|
453
|
+
current = await processor.process(current, ctx);
|
|
454
|
+
} catch (error) {
|
|
455
|
+
throw new ProcessorFailedError("input", processor.name, error);
|
|
456
|
+
}
|
|
285
457
|
}
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
458
|
+
return current;
|
|
459
|
+
}
|
|
460
|
+
__name(runInputProcessors, "runInputProcessors");
|
|
461
|
+
async function runOutputProcessors(processors, answer, ctx) {
|
|
462
|
+
let text = answer.text;
|
|
463
|
+
for (const processor of processors) {
|
|
464
|
+
let verdict;
|
|
465
|
+
try {
|
|
466
|
+
verdict = await processor.process({
|
|
467
|
+
text,
|
|
468
|
+
toolCalls: answer.toolCalls
|
|
469
|
+
}, ctx);
|
|
470
|
+
} catch (error) {
|
|
471
|
+
throw new ProcessorFailedError("output", processor.name, error);
|
|
472
|
+
}
|
|
473
|
+
if (verdict.action === "reject") {
|
|
474
|
+
return {
|
|
475
|
+
text,
|
|
476
|
+
rejection: {
|
|
477
|
+
processor: processor.name,
|
|
478
|
+
reason: verdict.reason
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
if (verdict.action === "replace") {
|
|
483
|
+
text = verdict.text;
|
|
484
|
+
}
|
|
290
485
|
}
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
486
|
+
return {
|
|
487
|
+
text
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
__name(runOutputProcessors, "runOutputProcessors");
|
|
491
|
+
async function gateFollowUps(processors, followUps, ctx) {
|
|
492
|
+
const kept = [];
|
|
493
|
+
for (const followUp of followUps) {
|
|
494
|
+
const settled = await runOutputProcessors(processors, {
|
|
495
|
+
text: followUp,
|
|
496
|
+
toolCalls: []
|
|
497
|
+
}, ctx);
|
|
498
|
+
if (settled.rejection === void 0 && settled.text.length > 0) {
|
|
499
|
+
kept.push(settled.text);
|
|
500
|
+
}
|
|
297
501
|
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
502
|
+
return kept;
|
|
503
|
+
}
|
|
504
|
+
__name(gateFollowUps, "gateFollowUps");
|
|
505
|
+
function resolveOutputGateMode(processors) {
|
|
506
|
+
if (processors.length === 0) {
|
|
507
|
+
return "off";
|
|
302
508
|
}
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
509
|
+
return processors.every((processor) => processor.incremental !== void 0) ? "incremental" : "whole";
|
|
510
|
+
}
|
|
511
|
+
__name(resolveOutputGateMode, "resolveOutputGateMode");
|
|
512
|
+
function resolveGateLookback(processors) {
|
|
513
|
+
let lookback = 0;
|
|
514
|
+
for (const processor of processors) {
|
|
515
|
+
if (processor.incremental !== void 0) {
|
|
516
|
+
lookback = Math.max(lookback, processor.incremental.lookbackChars ?? DEFAULT_INCREMENTAL_LOOKBACK_CHARS);
|
|
517
|
+
}
|
|
307
518
|
}
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
519
|
+
return lookback;
|
|
520
|
+
}
|
|
521
|
+
__name(resolveGateLookback, "resolveGateLookback");
|
|
522
|
+
function createIncrementalGate(options) {
|
|
523
|
+
const { processors, ctx, lookbackChars, writer } = options;
|
|
524
|
+
let raw = "";
|
|
525
|
+
let released = "";
|
|
526
|
+
let rejection;
|
|
527
|
+
let stalled = false;
|
|
528
|
+
const toolCalls = [];
|
|
529
|
+
let queue = Promise.resolve();
|
|
530
|
+
async function advance() {
|
|
531
|
+
if (raw.length === 0) {
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
let settled;
|
|
535
|
+
try {
|
|
536
|
+
settled = await runOutputProcessors(processors, {
|
|
537
|
+
text: raw,
|
|
538
|
+
toolCalls
|
|
539
|
+
}, ctx);
|
|
540
|
+
} catch {
|
|
541
|
+
stalled = true;
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
if (settled.rejection !== void 0) {
|
|
545
|
+
rejection = settled.rejection;
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
const candidate = settled.text.slice(0, Math.max(0, settled.text.length - lookbackChars));
|
|
549
|
+
if (candidate.length <= released.length || !candidate.startsWith(released)) {
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
const delta = candidate.slice(released.length);
|
|
553
|
+
released = candidate;
|
|
554
|
+
await writer.write(encodeStreamEvent({
|
|
555
|
+
kind: "text",
|
|
556
|
+
text: delta
|
|
557
|
+
}));
|
|
312
558
|
}
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
559
|
+
__name(advance, "advance");
|
|
560
|
+
async function handle(chunk) {
|
|
561
|
+
for (const line of decoder.decode(chunk).split("\n")) {
|
|
562
|
+
if (line.length === 0) {
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
const event = decodeStreamEvent(line);
|
|
566
|
+
if (event === null || rejection !== void 0) {
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
if (event.kind === "text") {
|
|
570
|
+
raw += event.text;
|
|
571
|
+
if (!stalled) {
|
|
572
|
+
await advance();
|
|
573
|
+
}
|
|
574
|
+
continue;
|
|
575
|
+
}
|
|
576
|
+
if (event.kind === "tool-input-available") {
|
|
577
|
+
toolCalls.push({
|
|
578
|
+
id: event.id,
|
|
579
|
+
name: event.name,
|
|
580
|
+
input: event.input
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
await writer.write(encodeStreamEvent(event));
|
|
584
|
+
}
|
|
317
585
|
}
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
586
|
+
__name(handle, "handle");
|
|
587
|
+
return {
|
|
588
|
+
writer: {
|
|
589
|
+
write: /* @__PURE__ */ __name((chunk) => {
|
|
590
|
+
queue = queue.then(() => handle(chunk));
|
|
591
|
+
return queue;
|
|
592
|
+
}, "write"),
|
|
593
|
+
end: /* @__PURE__ */ __name(() => {
|
|
594
|
+
}, "end"),
|
|
595
|
+
fail: /* @__PURE__ */ __name(() => {
|
|
596
|
+
}, "fail")
|
|
597
|
+
},
|
|
598
|
+
settled: /* @__PURE__ */ __name(() => queue, "settled"),
|
|
599
|
+
released: /* @__PURE__ */ __name(() => released, "released"),
|
|
600
|
+
rejection: /* @__PURE__ */ __name(() => rejection, "rejection")
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
__name(createIncrementalGate, "createIncrementalGate");
|
|
604
|
+
function gateTail(processors, released, text) {
|
|
605
|
+
if (!text.startsWith(released)) {
|
|
606
|
+
throw new ProcessorFailedError("output", processors.map((processor) => processor.name).join(" \u2192 "), new Error(`the gated answer is not an extension of the ${released.length} characters this chain already released \u2014 a processor that declares "incremental" promises its result on a prefix stays a prefix of its result on the whole answer, outside the last lookbackChars`));
|
|
322
607
|
}
|
|
323
|
-
|
|
324
|
-
|
|
608
|
+
return text.slice(released.length);
|
|
609
|
+
}
|
|
610
|
+
__name(gateTail, "gateTail");
|
|
611
|
+
|
|
612
|
+
// src/structured-output.ts
|
|
613
|
+
var StructuredOutputError = class extends Error {
|
|
325
614
|
static {
|
|
326
|
-
__name(this, "
|
|
615
|
+
__name(this, "StructuredOutputError");
|
|
327
616
|
}
|
|
328
|
-
|
|
617
|
+
/** Why it failed the schema. Empty only when the text was not JSON at all. */
|
|
329
618
|
issues;
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
619
|
+
/** The last text the model produced, verbatim. */
|
|
620
|
+
text;
|
|
621
|
+
/** How many model calls were spent trying (1 = the formatting pass, no repairs). */
|
|
622
|
+
attempts;
|
|
623
|
+
constructor(issues, text, attempts) {
|
|
624
|
+
const detail = issues.length > 0 ? issues.map((issue4) => issue4.message).join("; ") : "the model did not reply with JSON";
|
|
625
|
+
super(`Structured output invalid after ${attempts} attempt(s): ${detail}`);
|
|
626
|
+
this.name = "StructuredOutputError";
|
|
627
|
+
this.issues = issues;
|
|
628
|
+
this.text = text;
|
|
629
|
+
this.attempts = attempts;
|
|
333
630
|
}
|
|
334
631
|
};
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
});
|
|
345
|
-
}
|
|
346
|
-
has(name) {
|
|
347
|
-
return this.entries.has(name);
|
|
348
|
-
}
|
|
349
|
-
spec(name) {
|
|
350
|
-
return this.entries.get(name)?.spec;
|
|
351
|
-
}
|
|
352
|
-
allSpecs() {
|
|
353
|
-
return [
|
|
354
|
-
...this.entries.values()
|
|
355
|
-
].map((entry) => entry.spec);
|
|
356
|
-
}
|
|
357
|
-
/**
|
|
358
|
-
* The tools to offer the model for this actor+agent, after the four filter layers: what this
|
|
359
|
-
* deployment has enabled, what this actor's role allows, what each tool's own `canUse` allows
|
|
360
|
-
* this actor, and finally what this agent pinned.
|
|
361
|
-
*
|
|
362
|
-
* Every layer only ever removes tools, so no arrangement of them can widen what a turn reaches.
|
|
363
|
-
*/
|
|
364
|
-
async definitionsFor(actor, policy, allowedTools) {
|
|
365
|
-
const live = await filterToolsByEnabled([
|
|
366
|
-
...this.entries.values()
|
|
367
|
-
]);
|
|
368
|
-
const allowedByRole = new Set((await filterToolsByRole(live.map((entry) => entry.spec), actor, policy)).map((spec) => spec.name));
|
|
369
|
-
const roleScoped = live.filter((entry) => allowedByRole.has(entry.spec.name));
|
|
370
|
-
const actorScoped = await filterToolsByCanUse(roleScoped, actor);
|
|
371
|
-
const allowScoped = filterToolsByAllowList(actorScoped.map((entry) => entry.spec), allowedTools);
|
|
372
|
-
return allowScoped.map((spec) => ({
|
|
373
|
-
name: spec.name,
|
|
374
|
-
kind: spec.kind,
|
|
375
|
-
description: spec.description,
|
|
376
|
-
inputSchema: spec.inputSchema
|
|
377
|
-
}));
|
|
378
|
-
}
|
|
379
|
-
/**
|
|
380
|
-
* Run a tool. Re-checks that the tool is enabled and that the role allows it (defense-in-depth —
|
|
381
|
-
* a call can reach here from a replayed durable step or an approval granted before the flag
|
|
382
|
-
* moved, neither of which went through `definitionsFor` again) and re-parses the input via Zod.
|
|
383
|
-
*/
|
|
384
|
-
async invoke(name, input, ctx, policy) {
|
|
385
|
-
const entry = this.entries.get(name);
|
|
386
|
-
if (entry === void 0) {
|
|
387
|
-
throw new ToolNotFoundError(name);
|
|
388
|
-
}
|
|
389
|
-
if (!await isToolEnabled(entry.spec, entry.handler)) {
|
|
390
|
-
throw new ToolDisabledError(name);
|
|
391
|
-
}
|
|
392
|
-
if (!await policy.can(ctx.actor, entry.spec)) {
|
|
393
|
-
throw new ToolForbiddenError(name);
|
|
394
|
-
}
|
|
395
|
-
if (!await canActorUseTool(ctx.actor, entry.handler)) {
|
|
396
|
-
throw new ToolForbiddenError(name);
|
|
632
|
+
function extractJson(text) {
|
|
633
|
+
const candidates = [
|
|
634
|
+
text,
|
|
635
|
+
text.match(/\{[\s\S]*\}/)?.[0],
|
|
636
|
+
text.match(/\[[\s\S]*\]/)?.[0]
|
|
637
|
+
];
|
|
638
|
+
for (const candidate of candidates) {
|
|
639
|
+
if (candidate === void 0) {
|
|
640
|
+
continue;
|
|
397
641
|
}
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
642
|
+
try {
|
|
643
|
+
return JSON.parse(candidate);
|
|
644
|
+
} catch {
|
|
401
645
|
}
|
|
402
|
-
return entry.handler.execute(validation.value, ctx);
|
|
403
|
-
}
|
|
404
|
-
};
|
|
405
|
-
var DefaultRolesPolicy = class {
|
|
406
|
-
static {
|
|
407
|
-
__name(this, "DefaultRolesPolicy");
|
|
408
|
-
}
|
|
409
|
-
defaultRoles;
|
|
410
|
-
constructor(defaultRoles = [
|
|
411
|
-
"ADMIN"
|
|
412
|
-
]) {
|
|
413
|
-
this.defaultRoles = defaultRoles;
|
|
414
646
|
}
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
647
|
+
return void 0;
|
|
648
|
+
}
|
|
649
|
+
__name(extractJson, "extractJson");
|
|
650
|
+
async function validateStructured(schema, text, reported) {
|
|
651
|
+
const candidate = reported !== void 0 ? reported : extractJson(text);
|
|
652
|
+
if (candidate === void 0) {
|
|
653
|
+
return {
|
|
654
|
+
ok: false,
|
|
655
|
+
issues: []
|
|
656
|
+
};
|
|
418
657
|
}
|
|
419
|
-
|
|
658
|
+
const result = await schema["~standard"].validate(candidate);
|
|
659
|
+
return result.issues !== void 0 ? {
|
|
660
|
+
ok: false,
|
|
661
|
+
issues: result.issues
|
|
662
|
+
} : {
|
|
663
|
+
ok: true,
|
|
664
|
+
value: result.value
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
__name(validateStructured, "validateStructured");
|
|
668
|
+
var DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION = "Restate the assistant's final answer as a single JSON value matching the required schema. Use only information already present in the conversation \u2014 add nothing, and answer nothing that was not asked. Reply with ONLY the JSON: no prose, no explanation, no code fences.";
|
|
669
|
+
function repairInstruction(instruction, issues) {
|
|
670
|
+
const detail = issues.length > 0 ? issues.map((issue4) => `${(issue4.path ?? []).join(".") || "(root)"}: ${issue4.message}`).join("\n") : "the previous reply was not valid JSON";
|
|
671
|
+
return `${instruction}
|
|
420
672
|
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
673
|
+
Your previous reply was rejected:
|
|
674
|
+
${detail}`;
|
|
675
|
+
}
|
|
676
|
+
__name(repairInstruction, "repairInstruction");
|
|
424
677
|
|
|
425
|
-
// src/
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
emit("agent", "run.started", payload);
|
|
678
|
+
// src/elicitation.ts
|
|
679
|
+
function optionValues(question) {
|
|
680
|
+
return new Set(question.options.map((option) => option.value));
|
|
429
681
|
}
|
|
430
|
-
__name(
|
|
431
|
-
function
|
|
432
|
-
|
|
682
|
+
__name(optionValues, "optionValues");
|
|
683
|
+
function normalizeElicitationReply(reply) {
|
|
684
|
+
if (typeof reply !== "object" || reply === null) {
|
|
685
|
+
return {
|
|
686
|
+
answers: {}
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
const candidate = reply;
|
|
690
|
+
if (typeof candidate.answers === "object" && candidate.answers !== null) {
|
|
691
|
+
return reply;
|
|
692
|
+
}
|
|
693
|
+
const answeredByRef = candidate.answeredByRef ?? candidate.executedByRef;
|
|
694
|
+
return {
|
|
695
|
+
answers: {},
|
|
696
|
+
...candidate.approved === false || candidate.skipped === true ? {
|
|
697
|
+
skipped: true
|
|
698
|
+
} : {},
|
|
699
|
+
...answeredByRef !== void 0 ? {
|
|
700
|
+
answeredByRef
|
|
701
|
+
} : {}
|
|
702
|
+
};
|
|
433
703
|
}
|
|
434
|
-
__name(
|
|
435
|
-
function
|
|
436
|
-
|
|
704
|
+
__name(normalizeElicitationReply, "normalizeElicitationReply");
|
|
705
|
+
function resolveElicitation(request, raw) {
|
|
706
|
+
const reply = normalizeElicitationReply(raw);
|
|
707
|
+
const answers = {};
|
|
708
|
+
const defaulted = [];
|
|
709
|
+
for (const question of request.questions) {
|
|
710
|
+
const submitted = reply.skipped === true ? void 0 : reply.answers[question.id];
|
|
711
|
+
if (submitted === void 0) {
|
|
712
|
+
answers[question.id] = [
|
|
713
|
+
...question.defaults ?? []
|
|
714
|
+
];
|
|
715
|
+
defaulted.push(question.id);
|
|
716
|
+
continue;
|
|
717
|
+
}
|
|
718
|
+
const allowed = optionValues(question);
|
|
719
|
+
const valid = question.allowFreeText === true ? submitted : submitted.filter((value) => allowed.has(value));
|
|
720
|
+
answers[question.id] = question.multiple === true ? valid : valid.slice(0, 1);
|
|
721
|
+
}
|
|
722
|
+
return {
|
|
723
|
+
answers,
|
|
724
|
+
skipped: reply.skipped === true,
|
|
725
|
+
defaulted
|
|
726
|
+
};
|
|
437
727
|
}
|
|
438
|
-
__name(
|
|
439
|
-
function
|
|
440
|
-
|
|
728
|
+
__name(resolveElicitation, "resolveElicitation");
|
|
729
|
+
function settleElicitation(request, reply) {
|
|
730
|
+
const outcome = resolveElicitation(request, reply);
|
|
731
|
+
return {
|
|
732
|
+
...outcome,
|
|
733
|
+
summary: renderElicitationAnswers(request, outcome)
|
|
734
|
+
};
|
|
441
735
|
}
|
|
442
|
-
__name(
|
|
443
|
-
function
|
|
444
|
-
|
|
736
|
+
__name(settleElicitation, "settleElicitation");
|
|
737
|
+
function renderElicitationAnswers(request, outcome) {
|
|
738
|
+
const lines = request.questions.map((question) => {
|
|
739
|
+
const chosen = outcome.answers[question.id] ?? [];
|
|
740
|
+
const labels = chosen.map((value) => question.options.find((option) => option.value === value)?.label ?? value);
|
|
741
|
+
return `${question.prompt} \u2192 ${labels.length > 0 ? labels.join(", ") : "(no answer)"}`;
|
|
742
|
+
});
|
|
743
|
+
const preface = outcome.skipped ? "The user declined to answer and asked you to proceed on these assumptions:" : "The user answered:";
|
|
744
|
+
return `${preface}
|
|
745
|
+
${lines.join("\n")}`;
|
|
445
746
|
}
|
|
446
|
-
__name(
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
}
|
|
454
|
-
__name(publishAgentDelegated, "publishAgentDelegated");
|
|
455
|
-
function publishAgentRetrieved(payload) {
|
|
456
|
-
emit("agent", "retrieved", payload);
|
|
457
|
-
}
|
|
458
|
-
__name(publishAgentRetrieved, "publishAgentRetrieved");
|
|
459
|
-
function publishAgentToolRetry(payload) {
|
|
460
|
-
emit("agent", "tool.retry", payload);
|
|
461
|
-
}
|
|
462
|
-
__name(publishAgentToolRetry, "publishAgentToolRetry");
|
|
463
|
-
var AGENT_SPAN_EVENTS = [
|
|
464
|
-
"llm.turn",
|
|
465
|
-
"tool.execution",
|
|
466
|
-
"retrieval",
|
|
467
|
-
"follow-ups"
|
|
468
|
-
];
|
|
469
|
-
var AGENT_DIAGNOSTIC_EVENTS = [
|
|
470
|
-
"run.started",
|
|
471
|
-
"message",
|
|
472
|
-
"tool-call",
|
|
473
|
-
"quota.exceeded",
|
|
474
|
-
"run.finished",
|
|
475
|
-
"run.failed",
|
|
476
|
-
"delegated",
|
|
477
|
-
"retrieved",
|
|
478
|
-
"tool.retry"
|
|
479
|
-
];
|
|
480
|
-
function agentDiagnosticKey(event) {
|
|
481
|
-
return `agent:${event}`;
|
|
747
|
+
__name(renderElicitationAnswers, "renderElicitationAnswers");
|
|
748
|
+
var ASK_TOOL_NAME = "ask";
|
|
749
|
+
var MAX_ASK_QUESTIONS = 5;
|
|
750
|
+
function issue(path, message) {
|
|
751
|
+
return {
|
|
752
|
+
message,
|
|
753
|
+
path
|
|
754
|
+
};
|
|
482
755
|
}
|
|
483
|
-
__name(
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
return false;
|
|
756
|
+
__name(issue, "issue");
|
|
757
|
+
function parseOption(raw, path, issues) {
|
|
758
|
+
if (typeof raw !== "object" || raw === null) {
|
|
759
|
+
issues.push(issue(path, "must be an object"));
|
|
760
|
+
return void 0;
|
|
489
761
|
}
|
|
490
|
-
const
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
762
|
+
const candidate = raw;
|
|
763
|
+
if (typeof candidate.value !== "string" || candidate.value.length === 0) {
|
|
764
|
+
issues.push(issue([
|
|
765
|
+
...path,
|
|
766
|
+
"value"
|
|
767
|
+
], "must be a non-empty string"));
|
|
768
|
+
return void 0;
|
|
495
769
|
}
|
|
496
|
-
if (
|
|
497
|
-
|
|
770
|
+
if (typeof candidate.label !== "string" || candidate.label.length === 0) {
|
|
771
|
+
issues.push(issue([
|
|
772
|
+
...path,
|
|
773
|
+
"label"
|
|
774
|
+
], "must be a non-empty string"));
|
|
775
|
+
return void 0;
|
|
498
776
|
}
|
|
499
|
-
|
|
500
|
-
|
|
777
|
+
return {
|
|
778
|
+
value: candidate.value,
|
|
779
|
+
label: candidate.label,
|
|
780
|
+
...typeof candidate.hotkey === "string" ? {
|
|
781
|
+
hotkey: candidate.hotkey
|
|
782
|
+
} : {}
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
__name(parseOption, "parseOption");
|
|
786
|
+
function parseQuestion(raw, path, issues) {
|
|
787
|
+
if (typeof raw !== "object" || raw === null) {
|
|
788
|
+
issues.push(issue(path, "must be an object"));
|
|
789
|
+
return void 0;
|
|
501
790
|
}
|
|
502
|
-
|
|
503
|
-
|
|
791
|
+
const candidate = raw;
|
|
792
|
+
if (typeof candidate.id !== "string" || candidate.id.length === 0) {
|
|
793
|
+
issues.push(issue([
|
|
794
|
+
...path,
|
|
795
|
+
"id"
|
|
796
|
+
], "must be a non-empty string"));
|
|
797
|
+
return void 0;
|
|
504
798
|
}
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
return true;
|
|
799
|
+
if (typeof candidate.prompt !== "string" || candidate.prompt.length === 0) {
|
|
800
|
+
issues.push(issue([
|
|
801
|
+
...path,
|
|
802
|
+
"prompt"
|
|
803
|
+
], "must be a non-empty string"));
|
|
804
|
+
return void 0;
|
|
512
805
|
}
|
|
513
|
-
if (
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
806
|
+
if (!Array.isArray(candidate.options) || candidate.options.length === 0) {
|
|
807
|
+
issues.push(issue([
|
|
808
|
+
...path,
|
|
809
|
+
"options"
|
|
810
|
+
], "must be a non-empty array"));
|
|
811
|
+
return void 0;
|
|
812
|
+
}
|
|
813
|
+
const options = [];
|
|
814
|
+
for (const [index, rawOption] of candidate.options.entries()) {
|
|
815
|
+
const option = parseOption(rawOption, [
|
|
816
|
+
...path,
|
|
817
|
+
"options",
|
|
818
|
+
index
|
|
819
|
+
], issues);
|
|
820
|
+
if (option !== void 0) {
|
|
821
|
+
options.push(option);
|
|
517
822
|
}
|
|
518
823
|
}
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
824
|
+
if (!Array.isArray(candidate.defaults) || candidate.defaults.length === 0) {
|
|
825
|
+
issues.push(issue([
|
|
826
|
+
...path,
|
|
827
|
+
"defaults"
|
|
828
|
+
], "must pre-pick at least one option \u2014 say what you would choose so the user can just confirm"));
|
|
829
|
+
return void 0;
|
|
830
|
+
}
|
|
831
|
+
const offered = new Set(options.map((option) => option.value));
|
|
832
|
+
const defaults = candidate.defaults.filter((value) => typeof value === "string" && offered.has(value));
|
|
833
|
+
if (defaults.length === 0) {
|
|
834
|
+
issues.push(issue([
|
|
835
|
+
...path,
|
|
836
|
+
"defaults"
|
|
837
|
+
], "must name values that appear in this question's options"));
|
|
838
|
+
return void 0;
|
|
527
839
|
}
|
|
528
840
|
return {
|
|
529
|
-
|
|
530
|
-
|
|
841
|
+
id: candidate.id,
|
|
842
|
+
prompt: candidate.prompt,
|
|
843
|
+
options,
|
|
844
|
+
defaults,
|
|
845
|
+
...candidate.multiple === true ? {
|
|
846
|
+
multiple: true
|
|
847
|
+
} : {},
|
|
848
|
+
...candidate.allowFreeText === true ? {
|
|
849
|
+
allowFreeText: true
|
|
850
|
+
} : {}
|
|
531
851
|
};
|
|
532
852
|
}
|
|
533
|
-
__name(
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
853
|
+
__name(parseQuestion, "parseQuestion");
|
|
854
|
+
var ASK_JSON_SCHEMA = {
|
|
855
|
+
type: "object",
|
|
856
|
+
additionalProperties: false,
|
|
857
|
+
properties: {
|
|
858
|
+
preamble: {
|
|
859
|
+
type: "string",
|
|
860
|
+
description: 'One sentence shown above the form, e.g. "Three questions before I start. I have pre-picked what I would choose, so confirming is enough."'
|
|
861
|
+
},
|
|
862
|
+
questions: {
|
|
863
|
+
type: "array",
|
|
864
|
+
minItems: 1,
|
|
865
|
+
maxItems: MAX_ASK_QUESTIONS,
|
|
866
|
+
items: {
|
|
867
|
+
type: "object",
|
|
868
|
+
additionalProperties: false,
|
|
869
|
+
required: [
|
|
870
|
+
"id",
|
|
871
|
+
"prompt",
|
|
872
|
+
"options",
|
|
873
|
+
"defaults"
|
|
874
|
+
],
|
|
875
|
+
properties: {
|
|
876
|
+
id: {
|
|
877
|
+
type: "string",
|
|
878
|
+
description: "Unique within this call; answers come back under it."
|
|
879
|
+
},
|
|
880
|
+
prompt: {
|
|
881
|
+
type: "string"
|
|
882
|
+
},
|
|
883
|
+
multiple: {
|
|
884
|
+
type: "boolean",
|
|
885
|
+
description: "Allow more than one option to be chosen."
|
|
886
|
+
},
|
|
887
|
+
allowFreeText: {
|
|
888
|
+
type: "boolean",
|
|
889
|
+
description: "Accept an answer that is not an option."
|
|
890
|
+
},
|
|
891
|
+
defaults: {
|
|
892
|
+
type: "array",
|
|
893
|
+
minItems: 1,
|
|
894
|
+
items: {
|
|
895
|
+
type: "string"
|
|
896
|
+
},
|
|
897
|
+
description: "REQUIRED. The option values you would pick yourself, so the user can confirm rather than decide."
|
|
898
|
+
},
|
|
899
|
+
options: {
|
|
900
|
+
type: "array",
|
|
901
|
+
minItems: 2,
|
|
902
|
+
items: {
|
|
903
|
+
type: "object",
|
|
904
|
+
additionalProperties: false,
|
|
905
|
+
required: [
|
|
906
|
+
"value",
|
|
907
|
+
"label"
|
|
908
|
+
],
|
|
909
|
+
properties: {
|
|
910
|
+
value: {
|
|
911
|
+
type: "string"
|
|
912
|
+
},
|
|
913
|
+
label: {
|
|
914
|
+
type: "string"
|
|
915
|
+
},
|
|
916
|
+
hotkey: {
|
|
917
|
+
type: "string",
|
|
918
|
+
maxLength: 1
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
}
|
|
554
924
|
}
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
925
|
+
}
|
|
926
|
+
},
|
|
927
|
+
required: [
|
|
928
|
+
"questions"
|
|
929
|
+
]
|
|
930
|
+
};
|
|
931
|
+
var askInputSchema = {
|
|
932
|
+
"~standard": {
|
|
933
|
+
version: 1,
|
|
934
|
+
vendor: "nestjs-agent",
|
|
935
|
+
validate: /* @__PURE__ */ __name((value) => {
|
|
936
|
+
const issues = [];
|
|
937
|
+
if (typeof value !== "object" || value === null) {
|
|
938
|
+
return {
|
|
939
|
+
issues: [
|
|
940
|
+
issue([], "must be an object")
|
|
941
|
+
]
|
|
942
|
+
};
|
|
558
943
|
}
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
944
|
+
const candidate = value;
|
|
945
|
+
if (!Array.isArray(candidate.questions) || candidate.questions.length === 0) {
|
|
946
|
+
return {
|
|
947
|
+
issues: [
|
|
948
|
+
issue([
|
|
949
|
+
"questions"
|
|
950
|
+
], "must be a non-empty array")
|
|
951
|
+
]
|
|
952
|
+
};
|
|
953
|
+
}
|
|
954
|
+
if (candidate.questions.length > MAX_ASK_QUESTIONS) {
|
|
955
|
+
return {
|
|
956
|
+
issues: [
|
|
957
|
+
issue([
|
|
958
|
+
"questions"
|
|
959
|
+
], `must hold at most ${MAX_ASK_QUESTIONS} questions`)
|
|
960
|
+
]
|
|
961
|
+
};
|
|
962
|
+
}
|
|
963
|
+
const questions = [];
|
|
964
|
+
for (const [index, raw] of candidate.questions.entries()) {
|
|
965
|
+
const question = parseQuestion(raw, [
|
|
966
|
+
"questions",
|
|
967
|
+
index
|
|
968
|
+
], issues);
|
|
969
|
+
if (question !== void 0) {
|
|
970
|
+
questions.push(question);
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
if (issues.length > 0) {
|
|
974
|
+
return {
|
|
975
|
+
issues
|
|
976
|
+
};
|
|
977
|
+
}
|
|
978
|
+
return {
|
|
979
|
+
value: {
|
|
980
|
+
questions,
|
|
981
|
+
...typeof candidate.preamble === "string" ? {
|
|
982
|
+
preamble: candidate.preamble
|
|
983
|
+
} : {}
|
|
984
|
+
}
|
|
985
|
+
};
|
|
986
|
+
}, "validate"),
|
|
987
|
+
jsonSchema: {
|
|
988
|
+
input: /* @__PURE__ */ __name(() => ASK_JSON_SCHEMA, "input")
|
|
562
989
|
}
|
|
563
990
|
}
|
|
991
|
+
};
|
|
992
|
+
var ASK_TOOL_DESCRIPTION = "Ask the user to settle the scope of the work before you do it. Use it when a reasonable person would produce a materially different result depending on the answer \u2014 not to confirm something the conversation already says. Every question must pre-pick the answer you would choose, so the user can confirm instead of deciding. The user may decline, in which case you proceed on those pre-picked answers.";
|
|
993
|
+
function askToolDefinition() {
|
|
994
|
+
return {
|
|
995
|
+
name: ASK_TOOL_NAME,
|
|
996
|
+
kind: "ask",
|
|
997
|
+
description: ASK_TOOL_DESCRIPTION,
|
|
998
|
+
inputSchema: askInputSchema
|
|
999
|
+
};
|
|
564
1000
|
}
|
|
565
|
-
__name(
|
|
1001
|
+
__name(askToolDefinition, "askToolDefinition");
|
|
1002
|
+
var DEFAULT_INTAKE_PREAMBLE = "A few questions before I start. I have pre-picked what I would choose, so confirming is enough.";
|
|
566
1003
|
|
|
567
|
-
// src/
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
}
|
|
572
|
-
return price === void 0 ? null : estimateCost(usage, price);
|
|
1004
|
+
// src/skills.ts
|
|
1005
|
+
var GLOBAL_SCOPE = "global";
|
|
1006
|
+
function actorScope(actor) {
|
|
1007
|
+
return `actor:${actor.id}`;
|
|
573
1008
|
}
|
|
574
|
-
__name(
|
|
575
|
-
function
|
|
576
|
-
|
|
577
|
-
const label = passage.source !== void 0 ? ` (${passage.source})` : "";
|
|
578
|
-
return `[${index + 1}]${label} ${passage.text}`;
|
|
579
|
-
}).join("\n\n");
|
|
580
|
-
return `<retrieved_context>
|
|
581
|
-
${items}
|
|
582
|
-
</retrieved_context>
|
|
583
|
-
Use the retrieved context above to answer when relevant, and cite sources by their bracket number.`;
|
|
1009
|
+
__name(actorScope, "actorScope");
|
|
1010
|
+
function tenantScope(tenantRef) {
|
|
1011
|
+
return `tenant:${tenantRef}`;
|
|
584
1012
|
}
|
|
585
|
-
__name(
|
|
586
|
-
var
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
1013
|
+
__name(tenantScope, "tenantScope");
|
|
1014
|
+
var defaultScopeResolver = {
|
|
1015
|
+
resolve: /* @__PURE__ */ __name(({ actor }) => [
|
|
1016
|
+
actorScope(actor),
|
|
1017
|
+
...actor.tenantRef !== void 0 ? [
|
|
1018
|
+
tenantScope(actor.tenantRef)
|
|
1019
|
+
] : [],
|
|
1020
|
+
GLOBAL_SCOPE
|
|
1021
|
+
], "resolve")
|
|
594
1022
|
};
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
1023
|
+
function staticSkillProvider(skills) {
|
|
1024
|
+
return {
|
|
1025
|
+
list: /* @__PURE__ */ __name(({ scopes }) => skills.filter((skill) => scopes.includes(skill.scope)), "list"),
|
|
1026
|
+
load: /* @__PURE__ */ __name(({ name, scope }) => skills.find((skill) => skill.name === name && skill.scope === scope)?.body ?? null, "load")
|
|
1027
|
+
};
|
|
598
1028
|
}
|
|
599
|
-
__name(
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
1029
|
+
__name(staticSkillProvider, "staticSkillProvider");
|
|
1030
|
+
function compositeSkillProvider(providers) {
|
|
1031
|
+
return {
|
|
1032
|
+
list: /* @__PURE__ */ __name(async ({ scopes, ctx }) => {
|
|
1033
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1034
|
+
const merged = [];
|
|
1035
|
+
for (const provider of providers) {
|
|
1036
|
+
for (const summary of await provider.list({
|
|
1037
|
+
scopes,
|
|
1038
|
+
ctx
|
|
1039
|
+
})) {
|
|
1040
|
+
const key = `${summary.scope}\0${summary.name}`;
|
|
1041
|
+
if (!seen.has(key)) {
|
|
1042
|
+
seen.add(key);
|
|
1043
|
+
merged.push(summary);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
return merged;
|
|
1048
|
+
}, "list"),
|
|
1049
|
+
load: /* @__PURE__ */ __name(async ({ name, scope, ctx }) => {
|
|
1050
|
+
for (const provider of providers) {
|
|
1051
|
+
const body = await provider.load({
|
|
1052
|
+
name,
|
|
1053
|
+
scope,
|
|
1054
|
+
ctx
|
|
1055
|
+
});
|
|
1056
|
+
if (body !== null) {
|
|
1057
|
+
return body;
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
return null;
|
|
1061
|
+
}, "load")
|
|
607
1062
|
};
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
1063
|
+
}
|
|
1064
|
+
__name(compositeSkillProvider, "compositeSkillProvider");
|
|
1065
|
+
var DEFAULT_MAX_SKILLS = 20;
|
|
1066
|
+
function resolveSkillCatalog(summaries, scopes, maxSkills = DEFAULT_MAX_SKILLS) {
|
|
1067
|
+
const rank = new Map(scopes.map((scope, index) => [
|
|
1068
|
+
scope,
|
|
1069
|
+
index
|
|
1070
|
+
]));
|
|
1071
|
+
const byName = /* @__PURE__ */ new Map();
|
|
1072
|
+
for (const summary of summaries) {
|
|
1073
|
+
if (!rank.has(summary.scope)) {
|
|
1074
|
+
continue;
|
|
1075
|
+
}
|
|
1076
|
+
const existing = byName.get(summary.name);
|
|
1077
|
+
if (existing === void 0) {
|
|
1078
|
+
byName.set(summary.name, [
|
|
1079
|
+
summary
|
|
1080
|
+
]);
|
|
1081
|
+
} else {
|
|
1082
|
+
existing.push(summary);
|
|
615
1083
|
}
|
|
616
1084
|
}
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
const
|
|
623
|
-
if (
|
|
624
|
-
|
|
1085
|
+
const resolved = [];
|
|
1086
|
+
for (const candidates of byName.values()) {
|
|
1087
|
+
const ordered = [
|
|
1088
|
+
...candidates
|
|
1089
|
+
].sort((a, b) => (rank.get(a.scope) ?? 0) - (rank.get(b.scope) ?? 0));
|
|
1090
|
+
const winner = ordered[0];
|
|
1091
|
+
if (winner === void 0) {
|
|
1092
|
+
continue;
|
|
625
1093
|
}
|
|
1094
|
+
const shadows = ordered.slice(1).map((candidate) => candidate.scope);
|
|
1095
|
+
resolved.push({
|
|
1096
|
+
name: winner.name,
|
|
1097
|
+
description: winner.description,
|
|
1098
|
+
scope: winner.scope,
|
|
1099
|
+
...shadows.length > 0 ? {
|
|
1100
|
+
shadows
|
|
1101
|
+
} : {}
|
|
1102
|
+
});
|
|
626
1103
|
}
|
|
627
|
-
|
|
1104
|
+
resolved.sort((a, b) => {
|
|
1105
|
+
const byScope = (rank.get(a.scope) ?? 0) - (rank.get(b.scope) ?? 0);
|
|
1106
|
+
return byScope !== 0 ? byScope : compare(a.name, b.name);
|
|
1107
|
+
});
|
|
1108
|
+
return {
|
|
1109
|
+
entries: resolved.slice(0, maxSkills),
|
|
1110
|
+
omitted: Math.max(0, resolved.length - maxSkills)
|
|
1111
|
+
};
|
|
628
1112
|
}
|
|
629
|
-
__name(
|
|
630
|
-
function
|
|
631
|
-
|
|
632
|
-
return trimmed.length > 60 ? `${trimmed.slice(0, 57)}...` : trimmed || "New chat";
|
|
1113
|
+
__name(resolveSkillCatalog, "resolveSkillCatalog");
|
|
1114
|
+
function compare(a, b) {
|
|
1115
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
633
1116
|
}
|
|
634
|
-
__name(
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
1117
|
+
__name(compare, "compare");
|
|
1118
|
+
async function offerSkills(config, ctx) {
|
|
1119
|
+
const scopes = await (config.scopes ?? defaultScopeResolver).resolve(ctx);
|
|
1120
|
+
const summaries = await config.provider.list({
|
|
1121
|
+
scopes,
|
|
1122
|
+
ctx
|
|
1123
|
+
});
|
|
1124
|
+
return {
|
|
1125
|
+
scopes,
|
|
1126
|
+
...resolveSkillCatalog(summaries, scopes, config.maxSkills)
|
|
1127
|
+
};
|
|
1128
|
+
}
|
|
1129
|
+
__name(offerSkills, "offerSkills");
|
|
1130
|
+
function buildSkillsBlock(entries) {
|
|
1131
|
+
const lines = entries.map((entry) => {
|
|
1132
|
+
const shadows = entry.shadows === void 0 ? "" : ` (overrides the one from ${entry.shadows.join(", ")})`;
|
|
1133
|
+
return `- ${entry.name} [${entry.scope}] \u2014 ${entry.description}${shadows}`;
|
|
1134
|
+
});
|
|
1135
|
+
return `<skills>
|
|
1136
|
+
Procedures available to you. Each line is a name, the scope it came from, and what it covers \u2014 not the procedure itself.
|
|
1137
|
+
Call the \`${SKILL_TOOL_NAME}\` tool with a name from this list to read one BEFORE doing the task it covers, and follow what it says; never guess its contents from the description.
|
|
1138
|
+
A skill from a narrower scope overrides a same-named one from a wider scope. When you follow one that overrides another, say which scope it came from, so the user knows their setting differs from the wider default.
|
|
1139
|
+
${lines.join("\n")}
|
|
1140
|
+
</skills>`;
|
|
1141
|
+
}
|
|
1142
|
+
__name(buildSkillsBlock, "buildSkillsBlock");
|
|
1143
|
+
var SKILL_TOOL_NAME = "skill";
|
|
1144
|
+
var SKILL_JSON_SCHEMA = {
|
|
1145
|
+
type: "object",
|
|
1146
|
+
additionalProperties: false,
|
|
1147
|
+
required: [
|
|
1148
|
+
"name"
|
|
1149
|
+
],
|
|
1150
|
+
properties: {
|
|
1151
|
+
name: {
|
|
1152
|
+
type: "string",
|
|
1153
|
+
description: "The name of a skill from the <skills> list, exactly as written there."
|
|
1154
|
+
}
|
|
642
1155
|
}
|
|
643
1156
|
};
|
|
644
|
-
function
|
|
645
|
-
return
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
resolve(value);
|
|
650
|
-
}, (error) => {
|
|
651
|
-
clearTimeout(timer);
|
|
652
|
-
reject(error);
|
|
653
|
-
});
|
|
654
|
-
});
|
|
1157
|
+
function issue2(path, message) {
|
|
1158
|
+
return {
|
|
1159
|
+
message,
|
|
1160
|
+
path
|
|
1161
|
+
};
|
|
655
1162
|
}
|
|
656
|
-
__name(
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
1163
|
+
__name(issue2, "issue");
|
|
1164
|
+
var skillInputSchema = {
|
|
1165
|
+
"~standard": {
|
|
1166
|
+
version: 1,
|
|
1167
|
+
vendor: "nestjs-agent",
|
|
1168
|
+
validate: /* @__PURE__ */ __name((value) => {
|
|
1169
|
+
if (typeof value !== "object" || value === null) {
|
|
1170
|
+
return {
|
|
1171
|
+
issues: [
|
|
1172
|
+
issue2([], "must be an object")
|
|
1173
|
+
]
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
const candidate = value;
|
|
1177
|
+
if (typeof candidate.name !== "string" || candidate.name.length === 0) {
|
|
1178
|
+
return {
|
|
1179
|
+
issues: [
|
|
1180
|
+
issue2([
|
|
1181
|
+
"name"
|
|
1182
|
+
], "must be a non-empty string")
|
|
1183
|
+
]
|
|
1184
|
+
};
|
|
1185
|
+
}
|
|
1186
|
+
return {
|
|
1187
|
+
value: {
|
|
1188
|
+
name: candidate.name
|
|
1189
|
+
}
|
|
1190
|
+
};
|
|
1191
|
+
}, "validate"),
|
|
1192
|
+
jsonSchema: {
|
|
1193
|
+
input: /* @__PURE__ */ __name(() => SKILL_JSON_SCHEMA, "input")
|
|
663
1194
|
}
|
|
664
|
-
} catch {
|
|
665
1195
|
}
|
|
666
|
-
|
|
1196
|
+
};
|
|
1197
|
+
var SKILL_TOOL_DESCRIPTION = "Read one of the procedures listed in <skills>. Call it before doing a task a listed skill covers, and follow what it returns. It performs nothing and changes nothing \u2014 it only gives you instructions you do not yet have.";
|
|
1198
|
+
function skillToolDefinition() {
|
|
1199
|
+
return {
|
|
1200
|
+
name: SKILL_TOOL_NAME,
|
|
1201
|
+
kind: "skill",
|
|
1202
|
+
description: SKILL_TOOL_DESCRIPTION,
|
|
1203
|
+
inputSchema: skillInputSchema
|
|
1204
|
+
};
|
|
667
1205
|
}
|
|
668
|
-
__name(
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
1206
|
+
__name(skillToolDefinition, "skillToolDefinition");
|
|
1207
|
+
function withSkillTool({ tools, enabled }) {
|
|
1208
|
+
return enabled ? [
|
|
1209
|
+
...tools,
|
|
1210
|
+
skillToolDefinition()
|
|
1211
|
+
] : tools;
|
|
1212
|
+
}
|
|
1213
|
+
__name(withSkillTool, "withSkillTool");
|
|
1214
|
+
async function loadSkill(config, offer, name, ctx) {
|
|
1215
|
+
const entry = offer.entries.find((candidate) => candidate.name === name);
|
|
1216
|
+
if (entry === void 0) {
|
|
1217
|
+
const available = offer.entries.map((candidate) => candidate.name).join(", ");
|
|
1218
|
+
return {
|
|
1219
|
+
ok: false,
|
|
1220
|
+
error: available.length === 0 ? `No skill named "${name}" is available to you, and no others are either.` : `No skill named "${name}" is available to you. Available: ${available}.`
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
const body = await config.provider.load({
|
|
1224
|
+
name: entry.name,
|
|
1225
|
+
scope: entry.scope,
|
|
1226
|
+
ctx
|
|
1227
|
+
});
|
|
1228
|
+
if (body === null) {
|
|
1229
|
+
return {
|
|
1230
|
+
ok: false,
|
|
1231
|
+
error: `Skill "${name}" is listed but its body could not be read.`
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
return {
|
|
1235
|
+
ok: true,
|
|
1236
|
+
skill: {
|
|
1237
|
+
name: entry.name,
|
|
1238
|
+
description: entry.description,
|
|
1239
|
+
scope: entry.scope,
|
|
1240
|
+
body
|
|
1241
|
+
},
|
|
1242
|
+
...entry.shadows !== void 0 ? {
|
|
1243
|
+
shadows: entry.shadows
|
|
1244
|
+
} : {}
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
__name(loadSkill, "loadSkill");
|
|
1248
|
+
function skillWriteVerdict(request) {
|
|
1249
|
+
const { scope, scopes, author, actor } = request;
|
|
1250
|
+
if (!scopes.includes(scope)) {
|
|
1251
|
+
return {
|
|
1252
|
+
allowed: false,
|
|
1253
|
+
reason: `"${scope}" is not a scope this actor belongs to`
|
|
1254
|
+
};
|
|
1255
|
+
}
|
|
1256
|
+
const own = actorScope(actor);
|
|
1257
|
+
if (scope === own) {
|
|
1258
|
+
return {
|
|
1259
|
+
allowed: true
|
|
1260
|
+
};
|
|
1261
|
+
}
|
|
1262
|
+
if (author.kind !== "human") {
|
|
1263
|
+
return {
|
|
1264
|
+
allowed: false,
|
|
1265
|
+
reason: `only a human may author a skill at "${scope}"; an agent may write only at "${own}"`
|
|
1266
|
+
};
|
|
1267
|
+
}
|
|
1268
|
+
return request.elevated === true ? {
|
|
1269
|
+
allowed: true
|
|
1270
|
+
} : {
|
|
1271
|
+
allowed: false,
|
|
1272
|
+
reason: `authoring at "${scope}" requires an elevated human author`
|
|
1273
|
+
};
|
|
1274
|
+
}
|
|
1275
|
+
__name(skillWriteVerdict, "skillWriteVerdict");
|
|
1276
|
+
|
|
1277
|
+
// src/memory.ts
|
|
1278
|
+
var DEFAULT_MAX_MEMORIES = 20;
|
|
1279
|
+
var DEFAULT_MAX_FACT_CHARS = 240;
|
|
1280
|
+
function resolveMemoryDigest({ records, scopes, maxMemories = DEFAULT_MAX_MEMORIES, ranked = false }) {
|
|
1281
|
+
const rank = new Map(scopes.map((scope, index) => [
|
|
1282
|
+
scope,
|
|
1283
|
+
index
|
|
1284
|
+
]));
|
|
1285
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
1286
|
+
for (const entry of records) {
|
|
1287
|
+
if (!rank.has(entry.scope)) {
|
|
1288
|
+
continue;
|
|
1289
|
+
}
|
|
1290
|
+
const existing = byKey.get(entry.key);
|
|
1291
|
+
if (existing === void 0) {
|
|
1292
|
+
byKey.set(entry.key, [
|
|
1293
|
+
entry
|
|
1294
|
+
]);
|
|
1295
|
+
} else {
|
|
1296
|
+
existing.push(entry);
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
const resolved = [];
|
|
1300
|
+
for (const candidates of byKey.values()) {
|
|
1301
|
+
const ordered = [
|
|
1302
|
+
...candidates
|
|
1303
|
+
].sort((a, b) => (rank.get(a.scope) ?? 0) - (rank.get(b.scope) ?? 0));
|
|
1304
|
+
const winner = ordered[0];
|
|
1305
|
+
if (winner === void 0) {
|
|
1306
|
+
continue;
|
|
1307
|
+
}
|
|
1308
|
+
const overrides = ordered.slice(1).map((beaten) => ({
|
|
1309
|
+
scope: beaten.scope,
|
|
1310
|
+
text: beaten.text,
|
|
1311
|
+
author: beaten.origin.author
|
|
1312
|
+
}));
|
|
1313
|
+
const pinned = ordered.some((candidate) => candidate.pinned === true);
|
|
1314
|
+
resolved.push({
|
|
1315
|
+
...winner,
|
|
1316
|
+
...pinned ? {
|
|
1317
|
+
pinned: true
|
|
1318
|
+
} : {},
|
|
1319
|
+
...overrides.length > 0 ? {
|
|
1320
|
+
overrides
|
|
1321
|
+
} : {}
|
|
1322
|
+
});
|
|
1323
|
+
}
|
|
1324
|
+
const byPrecedence = /* @__PURE__ */ __name((a, b) => (rank.get(a.scope) ?? 0) - (rank.get(b.scope) ?? 0) || compare2(b.updatedAt, a.updatedAt) || compare2(a.key, b.key), "byPrecedence");
|
|
1325
|
+
const selected = resolved.map((entry, index) => ({
|
|
1326
|
+
entry,
|
|
1327
|
+
index
|
|
1328
|
+
})).sort((a, b) => pinRank(a.entry) - pinRank(b.entry) || (ranked && a.entry.pinned !== true ? a.index - b.index : byPrecedence(a.entry, b.entry))).slice(0, maxMemories).map((candidate) => candidate.entry);
|
|
1329
|
+
const pinnedOmitted = resolved.filter((entry) => entry.pinned === true).length - selected.filter((entry) => entry.pinned === true).length;
|
|
1330
|
+
selected.sort((a, b) => pinRank(a) - pinRank(b) || (rank.get(a.scope) ?? 0) - (rank.get(b.scope) ?? 0) || compare2(a.key, b.key));
|
|
1331
|
+
return {
|
|
1332
|
+
entries: selected,
|
|
1333
|
+
omitted: Math.max(0, resolved.length - maxMemories),
|
|
1334
|
+
pinnedOmitted
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
__name(resolveMemoryDigest, "resolveMemoryDigest");
|
|
1338
|
+
function pinRank(entry) {
|
|
1339
|
+
return entry.pinned === true ? 0 : 1;
|
|
1340
|
+
}
|
|
1341
|
+
__name(pinRank, "pinRank");
|
|
1342
|
+
function compare2(a, b) {
|
|
1343
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
1344
|
+
}
|
|
1345
|
+
__name(compare2, "compare");
|
|
1346
|
+
async function offerMemories({ config, ctx, query }) {
|
|
1347
|
+
const scopes = await (config.scopes ?? defaultScopeResolver).resolve(ctx);
|
|
1348
|
+
const maxMemories = config.maxMemories ?? DEFAULT_MAX_MEMORIES;
|
|
1349
|
+
const trimmed = query?.trim() ?? "";
|
|
1350
|
+
const search = trimmed.length > 0 ? config.provider.search : void 0;
|
|
1351
|
+
const records = search !== void 0 ? await search({
|
|
1352
|
+
scopes,
|
|
1353
|
+
query: trimmed,
|
|
1354
|
+
limit: maxMemories,
|
|
1355
|
+
ctx
|
|
1356
|
+
}) : await config.provider.list({
|
|
1357
|
+
scopes,
|
|
1358
|
+
ctx
|
|
1359
|
+
});
|
|
1360
|
+
return {
|
|
1361
|
+
scopes,
|
|
1362
|
+
recalled: search !== void 0,
|
|
1363
|
+
...resolveMemoryDigest({
|
|
1364
|
+
records,
|
|
1365
|
+
scopes,
|
|
1366
|
+
maxMemories,
|
|
1367
|
+
ranked: search !== void 0
|
|
1368
|
+
})
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
__name(offerMemories, "offerMemories");
|
|
1372
|
+
var ASSERTED_FRAMING = "Stated by people. A person wrote each of these deliberately \u2014 the user about themselves, or someone administering their organisation. Treat them as you would any other instruction you were given. If the user says something that contradicts one, say which note it conflicts with and at what scope it is held, rather than quietly setting it aside.";
|
|
1373
|
+
var CONCLUDED_FRAMING = "Concluded by you. These are your own notes from earlier turns, not documents anyone wrote: they may be wrong or out of date, so prefer what the user says now, and say where a note came from if you act on it.";
|
|
1374
|
+
var PARTIAL_FRAMING = "You are being shown a selection, not everything on file. Other notes exist that are not in this list, so never read something\u2019s absence from it as evidence that it was never recorded.";
|
|
1375
|
+
function memorySection(framing, entries) {
|
|
1376
|
+
if (entries.length === 0) {
|
|
1377
|
+
return [];
|
|
1378
|
+
}
|
|
1379
|
+
return [
|
|
1380
|
+
framing,
|
|
1381
|
+
...entries.flatMap((entry) => [
|
|
1382
|
+
`- [${entry.scope}] ${entry.key}: ${entry.text}`,
|
|
1383
|
+
...(entry.overrides ?? []).map((beaten) => ` \u21B3 [${beaten.scope}] ${beaten.author === "human" ? "a person stated" : "instead has"}: ${beaten.text}`)
|
|
1384
|
+
])
|
|
1385
|
+
];
|
|
1386
|
+
}
|
|
1387
|
+
__name(memorySection, "memorySection");
|
|
1388
|
+
function buildMemoryBlock({ entries, writable, partial }) {
|
|
1389
|
+
const writeLine = writable ? [
|
|
1390
|
+
`When you learn something durable about this user, record it with the \`${REMEMBER_TOOL_NAME}\` tool; when one of these turns out to be wrong, record the corrected fact under the same key. What you record that way is one of your own notes, not something stated by a person.`
|
|
1391
|
+
] : [];
|
|
1392
|
+
const body = [
|
|
1393
|
+
"What is on file about this user and their organisation, carried over from earlier conversations. Each line is a scope, a key and the fact. A narrower scope overrides a wider one; where the wider value is shown underneath, tell the user their setting differs from it rather than silently choosing one.",
|
|
1394
|
+
...partial ? [
|
|
1395
|
+
PARTIAL_FRAMING
|
|
1396
|
+
] : [],
|
|
1397
|
+
...writeLine,
|
|
1398
|
+
// People before inferences: the model meets what it was told before what it worked out.
|
|
1399
|
+
...memorySection(ASSERTED_FRAMING, entries.filter((entry) => entry.origin.author === "human")),
|
|
1400
|
+
...memorySection(CONCLUDED_FRAMING, entries.filter((entry) => entry.origin.author !== "human"))
|
|
1401
|
+
];
|
|
1402
|
+
return `<memory>
|
|
1403
|
+
${body.join("\n")}
|
|
1404
|
+
</memory>`;
|
|
1405
|
+
}
|
|
1406
|
+
__name(buildMemoryBlock, "buildMemoryBlock");
|
|
1407
|
+
var REMEMBER_TOOL_NAME = "remember";
|
|
1408
|
+
var REMEMBER_JSON_SCHEMA = {
|
|
1409
|
+
type: "object",
|
|
1410
|
+
additionalProperties: false,
|
|
1411
|
+
required: [
|
|
1412
|
+
"key",
|
|
1413
|
+
"fact"
|
|
1414
|
+
],
|
|
1415
|
+
properties: {
|
|
1416
|
+
key: {
|
|
1417
|
+
type: "string",
|
|
1418
|
+
description: 'A short, stable handle for what this fact is ABOUT (e.g. "fiscal-year", "preferred-units"). Reusing an existing key replaces that fact rather than adding a second one.'
|
|
1419
|
+
},
|
|
1420
|
+
fact: {
|
|
1421
|
+
type: "string",
|
|
1422
|
+
description: "The fact itself, in one sentence, stated so it still makes sense in a conversation months from now."
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
};
|
|
1426
|
+
function issue3(path, message) {
|
|
1427
|
+
return {
|
|
1428
|
+
message,
|
|
1429
|
+
path
|
|
1430
|
+
};
|
|
1431
|
+
}
|
|
1432
|
+
__name(issue3, "issue");
|
|
1433
|
+
var rememberInputSchema = {
|
|
1434
|
+
"~standard": {
|
|
1435
|
+
version: 1,
|
|
1436
|
+
vendor: "nestjs-agent",
|
|
1437
|
+
validate: /* @__PURE__ */ __name((value) => {
|
|
1438
|
+
if (typeof value !== "object" || value === null) {
|
|
1439
|
+
return {
|
|
1440
|
+
issues: [
|
|
1441
|
+
issue3([], "must be an object")
|
|
1442
|
+
]
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
const candidate = value;
|
|
1446
|
+
if (typeof candidate.key !== "string" || candidate.key.length === 0) {
|
|
1447
|
+
return {
|
|
1448
|
+
issues: [
|
|
1449
|
+
issue3([
|
|
1450
|
+
"key"
|
|
1451
|
+
], "must be a non-empty string")
|
|
1452
|
+
]
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
if (typeof candidate.fact !== "string" || candidate.fact.length === 0) {
|
|
1456
|
+
return {
|
|
1457
|
+
issues: [
|
|
1458
|
+
issue3([
|
|
1459
|
+
"fact"
|
|
1460
|
+
], "must be a non-empty string")
|
|
1461
|
+
]
|
|
1462
|
+
};
|
|
1463
|
+
}
|
|
1464
|
+
return {
|
|
1465
|
+
value: {
|
|
1466
|
+
key: candidate.key,
|
|
1467
|
+
fact: candidate.fact
|
|
1468
|
+
}
|
|
1469
|
+
};
|
|
1470
|
+
}, "validate"),
|
|
1471
|
+
jsonSchema: {
|
|
1472
|
+
input: /* @__PURE__ */ __name(() => REMEMBER_JSON_SCHEMA, "input")
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
};
|
|
1476
|
+
var REMEMBER_TOOL_DESCRIPTION = "Record one durable fact about this user under a key, so later conversations start knowing it. For things that will still be true another day \u2014 how they work, what their organisation requires, a correction they made. Not for what this conversation is about, and not for anything you were not told or could not reasonably infer. The user can read and delete everything you record here.";
|
|
1477
|
+
function rememberToolDefinition() {
|
|
1478
|
+
return {
|
|
1479
|
+
name: REMEMBER_TOOL_NAME,
|
|
1480
|
+
kind: "memory",
|
|
1481
|
+
description: REMEMBER_TOOL_DESCRIPTION,
|
|
1482
|
+
inputSchema: rememberInputSchema
|
|
1483
|
+
};
|
|
1484
|
+
}
|
|
1485
|
+
__name(rememberToolDefinition, "rememberToolDefinition");
|
|
1486
|
+
function withMemoryTool({ tools, enabled }) {
|
|
1487
|
+
return enabled ? [
|
|
1488
|
+
...tools,
|
|
1489
|
+
rememberToolDefinition()
|
|
1490
|
+
] : tools;
|
|
1491
|
+
}
|
|
1492
|
+
__name(withMemoryTool, "withMemoryTool");
|
|
1493
|
+
function memoryWriteVerdict(request) {
|
|
1494
|
+
const { scope, scopes, author, actor } = request;
|
|
1495
|
+
if (!scopes.includes(scope)) {
|
|
1496
|
+
return {
|
|
1497
|
+
allowed: false,
|
|
1498
|
+
reason: `"${scope}" is not a scope this actor belongs to`
|
|
1499
|
+
};
|
|
1500
|
+
}
|
|
1501
|
+
const own = actorScope(actor);
|
|
1502
|
+
if (scope === own) {
|
|
1503
|
+
return {
|
|
1504
|
+
allowed: true
|
|
1505
|
+
};
|
|
1506
|
+
}
|
|
1507
|
+
if (author.kind !== "human") {
|
|
1508
|
+
return {
|
|
1509
|
+
allowed: false,
|
|
1510
|
+
reason: `only a human may write a memory at "${scope}"; an agent may write only at "${own}"`
|
|
1511
|
+
};
|
|
1512
|
+
}
|
|
1513
|
+
return request.elevated === true ? {
|
|
1514
|
+
allowed: true
|
|
1515
|
+
} : {
|
|
1516
|
+
allowed: false,
|
|
1517
|
+
reason: `writing at "${scope}" requires an elevated human author`
|
|
1518
|
+
};
|
|
1519
|
+
}
|
|
1520
|
+
__name(memoryWriteVerdict, "memoryWriteVerdict");
|
|
1521
|
+
function memoryForgetVerdict({ record, actor }) {
|
|
1522
|
+
return record.scope === actorScope(actor) ? {
|
|
1523
|
+
allowed: true
|
|
1524
|
+
} : {
|
|
1525
|
+
allowed: false,
|
|
1526
|
+
reason: `"${record.scope}" is not this actor's own scope; deleting it is an administrative action`
|
|
1527
|
+
};
|
|
1528
|
+
}
|
|
1529
|
+
__name(memoryForgetVerdict, "memoryForgetVerdict");
|
|
1530
|
+
async function writeMemory({ config, digest, call, ctx, runId }) {
|
|
1531
|
+
const write = config.provider.write;
|
|
1532
|
+
if (write === void 0) {
|
|
1533
|
+
return {
|
|
1534
|
+
ok: false,
|
|
1535
|
+
error: "Memory is read-only in this deployment."
|
|
1536
|
+
};
|
|
1537
|
+
}
|
|
1538
|
+
const key = call.key.trim();
|
|
1539
|
+
const text = call.fact.trim();
|
|
1540
|
+
if (key.length === 0 || text.length === 0) {
|
|
1541
|
+
return {
|
|
1542
|
+
ok: false,
|
|
1543
|
+
error: "A memory needs both a key and a fact."
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
const maxFactChars = config.maxFactChars ?? DEFAULT_MAX_FACT_CHARS;
|
|
1547
|
+
if (text.length > maxFactChars) {
|
|
1548
|
+
return {
|
|
1549
|
+
ok: false,
|
|
1550
|
+
error: `A memory must be at most ${maxFactChars} characters; that was ${text.length}. State the fact more briefly.`
|
|
1551
|
+
};
|
|
1552
|
+
}
|
|
1553
|
+
const scope = actorScope(ctx.actor);
|
|
1554
|
+
const verdict = memoryWriteVerdict({
|
|
1555
|
+
scope,
|
|
1556
|
+
actor: ctx.actor,
|
|
1557
|
+
scopes: digest.scopes,
|
|
1558
|
+
author: {
|
|
1559
|
+
kind: "agent",
|
|
1560
|
+
actorRef: ctx.actor.id
|
|
1561
|
+
}
|
|
1562
|
+
});
|
|
1563
|
+
if (!verdict.allowed) {
|
|
1564
|
+
return {
|
|
1565
|
+
ok: false,
|
|
1566
|
+
error: verdict.reason
|
|
1567
|
+
};
|
|
1568
|
+
}
|
|
1569
|
+
const record = await write({
|
|
1570
|
+
key,
|
|
1571
|
+
text,
|
|
1572
|
+
scope,
|
|
1573
|
+
origin: {
|
|
1574
|
+
author: "agent",
|
|
1575
|
+
threadId: ctx.threadId,
|
|
1576
|
+
runId,
|
|
1577
|
+
actorRef: ctx.actor.id
|
|
1578
|
+
},
|
|
1579
|
+
ctx
|
|
1580
|
+
});
|
|
1581
|
+
return {
|
|
1582
|
+
ok: true,
|
|
1583
|
+
record
|
|
1584
|
+
};
|
|
1585
|
+
}
|
|
1586
|
+
__name(writeMemory, "writeMemory");
|
|
1587
|
+
|
|
1588
|
+
// src/agent-registry.ts
|
|
1589
|
+
var AgentRegistry = class {
|
|
1590
|
+
static {
|
|
1591
|
+
__name(this, "AgentRegistry");
|
|
1592
|
+
}
|
|
1593
|
+
definitions = /* @__PURE__ */ new Map();
|
|
1594
|
+
register(definition) {
|
|
1595
|
+
this.definitions.set(definition.name, definition);
|
|
1596
|
+
}
|
|
1597
|
+
get(name) {
|
|
1598
|
+
return this.definitions.get(name);
|
|
1599
|
+
}
|
|
1600
|
+
has(name) {
|
|
1601
|
+
return this.definitions.has(name);
|
|
1602
|
+
}
|
|
1603
|
+
list() {
|
|
1604
|
+
return [
|
|
1605
|
+
...this.definitions.values()
|
|
1606
|
+
];
|
|
1607
|
+
}
|
|
1608
|
+
};
|
|
1609
|
+
|
|
1610
|
+
// src/replay-integrity.ts
|
|
1611
|
+
function isReplayIntegrityError(error) {
|
|
1612
|
+
return error instanceof Error && error.name.toLowerCase().endsWith("nondeterminismerror");
|
|
1613
|
+
}
|
|
1614
|
+
__name(isReplayIntegrityError, "isReplayIntegrityError");
|
|
1615
|
+
|
|
1616
|
+
// src/control-flow.ts
|
|
1617
|
+
var CONTROL_FLOW_SIGNAL = Symbol.for("aviary:durable:control-flow");
|
|
1618
|
+
function isControlFlowSignal(error) {
|
|
1619
|
+
return typeof error === "object" && error !== null && error[CONTROL_FLOW_SIGNAL] === true;
|
|
1620
|
+
}
|
|
1621
|
+
__name(isControlFlowSignal, "isControlFlowSignal");
|
|
1622
|
+
|
|
1623
|
+
// src/delegation.ts
|
|
1624
|
+
function normalizeDelegation(entry) {
|
|
1625
|
+
return typeof entry === "string" ? {
|
|
1626
|
+
agent: entry,
|
|
1627
|
+
detached: false
|
|
1628
|
+
} : {
|
|
1629
|
+
agent: entry.agent,
|
|
1630
|
+
detached: entry.detached === true
|
|
1631
|
+
};
|
|
1632
|
+
}
|
|
1633
|
+
__name(normalizeDelegation, "normalizeDelegation");
|
|
1634
|
+
function detachedStarted(args) {
|
|
1635
|
+
return {
|
|
1636
|
+
detached: true,
|
|
1637
|
+
status: "started",
|
|
1638
|
+
agent: args.agent,
|
|
1639
|
+
runId: args.runId,
|
|
1640
|
+
note: `The "${args.agent}" agent is now working on this in the background. Its answer is NOT part of this turn and will arrive in this conversation as a separate message when it is ready. Tell the user the work has started; do not state or guess what it will find.`
|
|
1641
|
+
};
|
|
1642
|
+
}
|
|
1643
|
+
__name(detachedStarted, "detachedStarted");
|
|
1644
|
+
function detachedDelivered(args) {
|
|
1645
|
+
return {
|
|
1646
|
+
detached: true,
|
|
1647
|
+
status: "delivered",
|
|
1648
|
+
agent: args.agent,
|
|
1649
|
+
runId: args.runId,
|
|
1650
|
+
text: args.text
|
|
1651
|
+
};
|
|
1652
|
+
}
|
|
1653
|
+
__name(detachedDelivered, "detachedDelivered");
|
|
1654
|
+
function detachedUnsettled(args) {
|
|
1655
|
+
return {
|
|
1656
|
+
detached: true,
|
|
1657
|
+
status: args.status,
|
|
1658
|
+
agent: args.agent,
|
|
1659
|
+
runId: args.runId,
|
|
1660
|
+
...args.error !== void 0 ? {
|
|
1661
|
+
error: args.error
|
|
1662
|
+
} : {}
|
|
1663
|
+
};
|
|
1664
|
+
}
|
|
1665
|
+
__name(detachedUnsettled, "detachedUnsettled");
|
|
1666
|
+
async function settleUnsettledDelegation(args) {
|
|
1667
|
+
const { store, delivery, agent, runId, status } = args;
|
|
1668
|
+
if (await store.getThread(delivery.threadId) === null) {
|
|
1669
|
+
return;
|
|
1670
|
+
}
|
|
1671
|
+
await store.appendMessage({
|
|
1672
|
+
threadId: delivery.threadId,
|
|
1673
|
+
role: "assistant",
|
|
1674
|
+
content: status === "cancelled" ? `The "${agent}" agent was stopped before it could answer.` : `The "${agent}" agent stopped before it could answer: ${args.error ?? "unknown error"}`,
|
|
1675
|
+
agentName: agent,
|
|
1676
|
+
runId
|
|
1677
|
+
});
|
|
1678
|
+
await store.updateToolCall({
|
|
1679
|
+
toolCallId: delivery.toolCallId,
|
|
1680
|
+
status: "executed",
|
|
1681
|
+
output: detachedUnsettled({
|
|
1682
|
+
agent,
|
|
1683
|
+
runId,
|
|
1684
|
+
status,
|
|
1685
|
+
...args.error !== void 0 ? {
|
|
1686
|
+
error: args.error
|
|
1687
|
+
} : {}
|
|
1688
|
+
})
|
|
1689
|
+
});
|
|
1690
|
+
}
|
|
1691
|
+
__name(settleUnsettledDelegation, "settleUnsettledDelegation");
|
|
1692
|
+
|
|
1693
|
+
// src/tool-registry.ts
|
|
1694
|
+
var ToolForbiddenError = class extends Error {
|
|
1695
|
+
static {
|
|
1696
|
+
__name(this, "ToolForbiddenError");
|
|
1697
|
+
}
|
|
1698
|
+
toolName;
|
|
1699
|
+
constructor(toolName) {
|
|
1700
|
+
super(`Tool "${toolName}" is not allowed for this role`), this.toolName = toolName;
|
|
1701
|
+
this.name = "ToolForbiddenError";
|
|
1702
|
+
}
|
|
1703
|
+
};
|
|
1704
|
+
var ToolDisabledError = class extends Error {
|
|
1705
|
+
static {
|
|
1706
|
+
__name(this, "ToolDisabledError");
|
|
1707
|
+
}
|
|
1708
|
+
toolName;
|
|
1709
|
+
constructor(toolName) {
|
|
1710
|
+
super(`Tool "${toolName}" is disabled in this deployment`), this.toolName = toolName;
|
|
1711
|
+
this.name = "ToolDisabledError";
|
|
1712
|
+
}
|
|
1713
|
+
};
|
|
1714
|
+
var ToolNotFoundError = class extends Error {
|
|
1715
|
+
static {
|
|
1716
|
+
__name(this, "ToolNotFoundError");
|
|
1717
|
+
}
|
|
1718
|
+
toolName;
|
|
1719
|
+
constructor(toolName) {
|
|
1720
|
+
super(`Tool "${toolName}" is not registered`), this.toolName = toolName;
|
|
1721
|
+
this.name = "ToolNotFoundError";
|
|
1722
|
+
}
|
|
1723
|
+
};
|
|
1724
|
+
var ToolInputInvalidError = class extends Error {
|
|
1725
|
+
static {
|
|
1726
|
+
__name(this, "ToolInputInvalidError");
|
|
1727
|
+
}
|
|
1728
|
+
toolName;
|
|
1729
|
+
issues;
|
|
1730
|
+
constructor(toolName, issues) {
|
|
1731
|
+
super(`Invalid input for tool "${toolName}": ${issues.map((issue4) => issue4.message).join("; ")}`), this.toolName = toolName, this.issues = issues;
|
|
1732
|
+
this.name = "ToolInputInvalidError";
|
|
1733
|
+
}
|
|
1734
|
+
};
|
|
1735
|
+
var ToolRegistry = class {
|
|
1736
|
+
static {
|
|
1737
|
+
__name(this, "ToolRegistry");
|
|
1738
|
+
}
|
|
1739
|
+
entries = /* @__PURE__ */ new Map();
|
|
1740
|
+
register(spec, handler) {
|
|
1741
|
+
this.entries.set(spec.name, {
|
|
1742
|
+
spec,
|
|
1743
|
+
handler
|
|
1744
|
+
});
|
|
1745
|
+
}
|
|
1746
|
+
has(name) {
|
|
1747
|
+
return this.entries.has(name);
|
|
1748
|
+
}
|
|
1749
|
+
spec(name) {
|
|
1750
|
+
return this.entries.get(name)?.spec;
|
|
1751
|
+
}
|
|
1752
|
+
allSpecs() {
|
|
1753
|
+
return [
|
|
1754
|
+
...this.entries.values()
|
|
1755
|
+
].map((entry) => entry.spec);
|
|
1756
|
+
}
|
|
1757
|
+
/**
|
|
1758
|
+
* The tools to offer the model for this actor+agent, after the four filter layers: what this
|
|
1759
|
+
* agent pinned, what this deployment has enabled, what this actor's role allows, and what each
|
|
1760
|
+
* tool's own `canUse` allows this actor.
|
|
1761
|
+
*
|
|
1762
|
+
* Every layer only ever removes tools, so no arrangement of them can widen what a turn reaches.
|
|
1763
|
+
* The agent's allow-list therefore goes FIRST, even though it is the narrowest statement: it is a
|
|
1764
|
+
* pure name-set match, while each of the three below it may be a round trip — an authz service, a
|
|
1765
|
+
* feature-flag store, an MCP server — and this runs once per model step. Asking those about a
|
|
1766
|
+
* tool the allow-list has already excluded is a call whose answer nothing reads.
|
|
1767
|
+
*/
|
|
1768
|
+
async definitionsFor(actor, policy, allowedTools) {
|
|
1769
|
+
const pinnedNames = new Set(filterToolsByAllowList(this.allSpecs(), allowedTools).map((spec) => spec.name));
|
|
1770
|
+
const pinned = [
|
|
1771
|
+
...this.entries.values()
|
|
1772
|
+
].filter((entry) => pinnedNames.has(entry.spec.name));
|
|
1773
|
+
const live = await filterToolsByEnabled(pinned);
|
|
1774
|
+
const allowedByRole = new Set((await filterToolsByRole(live.map((entry) => entry.spec), actor, policy)).map((spec) => spec.name));
|
|
1775
|
+
const roleScoped = live.filter((entry) => allowedByRole.has(entry.spec.name));
|
|
1776
|
+
const actorScoped = await filterToolsByCanUse(roleScoped, actor);
|
|
1777
|
+
return actorScoped.map(({ spec }) => ({
|
|
1778
|
+
name: spec.name,
|
|
1779
|
+
kind: spec.kind,
|
|
1780
|
+
description: spec.description,
|
|
1781
|
+
inputSchema: spec.inputSchema
|
|
1782
|
+
}));
|
|
1783
|
+
}
|
|
1784
|
+
/**
|
|
1785
|
+
* Run a tool. Re-checks that the tool is enabled and that the role allows it (defense-in-depth —
|
|
1786
|
+
* a call can reach here from a replayed durable step or an approval granted before the flag
|
|
1787
|
+
* moved, neither of which went through `definitionsFor` again) and re-parses the input via Zod.
|
|
1788
|
+
*/
|
|
1789
|
+
async invoke(name, input, ctx, policy) {
|
|
1790
|
+
const entry = this.entries.get(name);
|
|
1791
|
+
if (entry === void 0) {
|
|
1792
|
+
throw new ToolNotFoundError(name);
|
|
1793
|
+
}
|
|
1794
|
+
if (!await isToolEnabled(entry.spec, entry.handler)) {
|
|
1795
|
+
throw new ToolDisabledError(name);
|
|
1796
|
+
}
|
|
1797
|
+
if (!await policy.can(ctx.actor, entry.spec)) {
|
|
1798
|
+
throw new ToolForbiddenError(name);
|
|
1799
|
+
}
|
|
1800
|
+
if (!await canActorUseTool(ctx.actor, entry.handler)) {
|
|
1801
|
+
throw new ToolForbiddenError(name);
|
|
1802
|
+
}
|
|
1803
|
+
const validation = await entry.spec.inputSchema["~standard"].validate(input);
|
|
1804
|
+
if (validation.issues !== void 0) {
|
|
1805
|
+
throw new ToolInputInvalidError(name, validation.issues);
|
|
1806
|
+
}
|
|
1807
|
+
return entry.handler.execute(validation.value, ctx);
|
|
1808
|
+
}
|
|
1809
|
+
};
|
|
1810
|
+
var DefaultRolesPolicy = class {
|
|
1811
|
+
static {
|
|
1812
|
+
__name(this, "DefaultRolesPolicy");
|
|
1813
|
+
}
|
|
1814
|
+
defaultRoles;
|
|
1815
|
+
constructor(defaultRoles = [
|
|
1816
|
+
"ADMIN"
|
|
1817
|
+
]) {
|
|
1818
|
+
this.defaultRoles = defaultRoles;
|
|
1819
|
+
}
|
|
1820
|
+
can(actor, tool) {
|
|
1821
|
+
const allowed = tool.roles ?? this.defaultRoles;
|
|
1822
|
+
return (actor.roles ?? []).some((role) => allowed.includes(role));
|
|
1823
|
+
}
|
|
1824
|
+
};
|
|
1825
|
+
|
|
1826
|
+
// src/agent-loop.ts
|
|
1827
|
+
import { createHash } from "node:crypto";
|
|
1828
|
+
import { trace } from "@dudousxd/nestjs-diagnostics";
|
|
1829
|
+
|
|
1830
|
+
// src/diagnostics.ts
|
|
1831
|
+
import { emit } from "@dudousxd/nestjs-diagnostics";
|
|
1832
|
+
function publishAgentRunStarted(payload) {
|
|
1833
|
+
emit("agent", "run.started", payload);
|
|
1834
|
+
}
|
|
1835
|
+
__name(publishAgentRunStarted, "publishAgentRunStarted");
|
|
1836
|
+
function publishAgentMessage(payload) {
|
|
1837
|
+
emit("agent", "message", payload);
|
|
1838
|
+
}
|
|
1839
|
+
__name(publishAgentMessage, "publishAgentMessage");
|
|
1840
|
+
function publishAgentToolCall(payload) {
|
|
1841
|
+
emit("agent", "tool-call", payload);
|
|
1842
|
+
}
|
|
1843
|
+
__name(publishAgentToolCall, "publishAgentToolCall");
|
|
1844
|
+
function publishAgentQuotaExceeded(payload) {
|
|
1845
|
+
emit("agent", "quota.exceeded", payload);
|
|
1846
|
+
}
|
|
1847
|
+
__name(publishAgentQuotaExceeded, "publishAgentQuotaExceeded");
|
|
1848
|
+
function publishAgentRunFinished(payload) {
|
|
1849
|
+
emit("agent", "run.finished", payload);
|
|
1850
|
+
}
|
|
1851
|
+
__name(publishAgentRunFinished, "publishAgentRunFinished");
|
|
1852
|
+
function publishAgentRunFailed(payload) {
|
|
1853
|
+
emit("agent", "run.failed", payload);
|
|
1854
|
+
}
|
|
1855
|
+
__name(publishAgentRunFailed, "publishAgentRunFailed");
|
|
1856
|
+
function publishAgentDelegated(payload) {
|
|
1857
|
+
emit("agent", "delegated", payload);
|
|
1858
|
+
}
|
|
1859
|
+
__name(publishAgentDelegated, "publishAgentDelegated");
|
|
1860
|
+
function publishAgentRetrieved(payload) {
|
|
1861
|
+
emit("agent", "retrieved", payload);
|
|
1862
|
+
}
|
|
1863
|
+
__name(publishAgentRetrieved, "publishAgentRetrieved");
|
|
1864
|
+
function publishAgentToolRetry(payload) {
|
|
1865
|
+
emit("agent", "tool.retry", payload);
|
|
1866
|
+
}
|
|
1867
|
+
__name(publishAgentToolRetry, "publishAgentToolRetry");
|
|
1868
|
+
function publishAgentSkillsResolved(payload) {
|
|
1869
|
+
emit("agent", "skills.resolved", payload);
|
|
1870
|
+
}
|
|
1871
|
+
__name(publishAgentSkillsResolved, "publishAgentSkillsResolved");
|
|
1872
|
+
function publishAgentMemoryResolved(payload) {
|
|
1873
|
+
emit("agent", "memory.resolved", payload);
|
|
1874
|
+
}
|
|
1875
|
+
__name(publishAgentMemoryResolved, "publishAgentMemoryResolved");
|
|
1876
|
+
function publishAgentMemoryWritten(payload) {
|
|
1877
|
+
emit("agent", "memory.written", payload);
|
|
1878
|
+
}
|
|
1879
|
+
__name(publishAgentMemoryWritten, "publishAgentMemoryWritten");
|
|
1880
|
+
var AGENT_SPAN_EVENTS = [
|
|
1881
|
+
"llm.turn",
|
|
1882
|
+
"tool.execution",
|
|
1883
|
+
"retrieval",
|
|
1884
|
+
"follow-ups"
|
|
1885
|
+
];
|
|
1886
|
+
var AGENT_DIAGNOSTIC_EVENTS = [
|
|
1887
|
+
"run.started",
|
|
1888
|
+
"message",
|
|
1889
|
+
"tool-call",
|
|
1890
|
+
"quota.exceeded",
|
|
1891
|
+
"run.finished",
|
|
1892
|
+
"run.failed",
|
|
1893
|
+
"delegated",
|
|
1894
|
+
"retrieved",
|
|
1895
|
+
"skills.resolved",
|
|
1896
|
+
"memory.resolved",
|
|
1897
|
+
"memory.written",
|
|
1898
|
+
"tool.retry"
|
|
1899
|
+
];
|
|
1900
|
+
function agentDiagnosticKey(event) {
|
|
1901
|
+
return `agent:${event}`;
|
|
1902
|
+
}
|
|
1903
|
+
__name(agentDiagnosticKey, "agentDiagnosticKey");
|
|
1904
|
+
|
|
1905
|
+
// src/tool-retry.ts
|
|
1906
|
+
function hasTransientShape(error) {
|
|
1907
|
+
if (typeof error !== "object" || error === null) {
|
|
1908
|
+
return false;
|
|
1909
|
+
}
|
|
1910
|
+
const code = "code" in error ? error.code : void 0;
|
|
1911
|
+
const errno = "errno" in error ? error.errno : void 0;
|
|
1912
|
+
const sqlState = "sqlState" in error ? error.sqlState : void 0;
|
|
1913
|
+
if (code === 1213 || code === 1205 || errno === 1213 || errno === 1205) {
|
|
1914
|
+
return true;
|
|
1915
|
+
}
|
|
1916
|
+
if (code === "ER_LOCK_DEADLOCK" || code === "ER_LOCK_WAIT_TIMEOUT") {
|
|
1917
|
+
return true;
|
|
1918
|
+
}
|
|
1919
|
+
if (code === "40001" || code === "40P01" || sqlState === "40001" || sqlState === "40P01") {
|
|
1920
|
+
return true;
|
|
1921
|
+
}
|
|
1922
|
+
if (code === "SQLITE_BUSY") {
|
|
1923
|
+
return true;
|
|
1924
|
+
}
|
|
1925
|
+
const message = "message" in error ? error.message : void 0;
|
|
1926
|
+
return typeof message === "string" && /deadlock|lock wait timeout|serialization failure/i.test(message);
|
|
1927
|
+
}
|
|
1928
|
+
__name(hasTransientShape, "hasTransientShape");
|
|
1929
|
+
function isTransientToolError(error) {
|
|
1930
|
+
if (hasTransientShape(error)) {
|
|
1931
|
+
return true;
|
|
1932
|
+
}
|
|
1933
|
+
if (typeof error === "object" && error !== null && "cause" in error) {
|
|
1934
|
+
const cause = error.cause;
|
|
1935
|
+
if (cause !== void 0 && cause !== error && hasTransientShape(cause)) {
|
|
1936
|
+
return true;
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
return false;
|
|
1940
|
+
}
|
|
1941
|
+
__name(isTransientToolError, "isTransientToolError");
|
|
1942
|
+
var DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS = 2;
|
|
1943
|
+
var DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS = 150;
|
|
1944
|
+
function resolveToolTransientRetryNumbers(setting) {
|
|
1945
|
+
if (setting === false) {
|
|
1946
|
+
return false;
|
|
1947
|
+
}
|
|
1948
|
+
return {
|
|
1949
|
+
attempts: setting?.attempts ?? DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS,
|
|
1950
|
+
backoffMs: setting?.backoffMs ?? DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS
|
|
1951
|
+
};
|
|
1952
|
+
}
|
|
1953
|
+
__name(resolveToolTransientRetryNumbers, "resolveToolTransientRetryNumbers");
|
|
1954
|
+
function delay(ms) {
|
|
1955
|
+
return new Promise((resolve) => {
|
|
1956
|
+
setTimeout(resolve, ms);
|
|
1957
|
+
});
|
|
1958
|
+
}
|
|
1959
|
+
__name(delay, "delay");
|
|
1960
|
+
async function invokeWithTransientRetry(fn, setting, options) {
|
|
1961
|
+
if (setting === false) {
|
|
1962
|
+
return fn();
|
|
1963
|
+
}
|
|
1964
|
+
const attempts = setting.attempts ?? DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS;
|
|
1965
|
+
const backoffMs = setting.backoffMs ?? DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS;
|
|
1966
|
+
const classify = setting.classify ?? isTransientToolError;
|
|
1967
|
+
let attempt = 1;
|
|
1968
|
+
for (; ; ) {
|
|
1969
|
+
try {
|
|
1970
|
+
return await fn();
|
|
1971
|
+
} catch (error) {
|
|
1972
|
+
if (isControlFlowSignal(error) || options?.isControlFlowError?.(error) === true) {
|
|
1973
|
+
throw error;
|
|
1974
|
+
}
|
|
1975
|
+
const attemptsRemain = attempt < attempts;
|
|
1976
|
+
if (!attemptsRemain || !classify(error)) {
|
|
1977
|
+
throw error;
|
|
1978
|
+
}
|
|
1979
|
+
options?.onRetry?.(attempt, error);
|
|
1980
|
+
await delay(backoffMs * attempt);
|
|
1981
|
+
attempt += 1;
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
__name(invokeWithTransientRetry, "invokeWithTransientRetry");
|
|
1986
|
+
|
|
1987
|
+
// src/agent-loop.ts
|
|
1988
|
+
function resolveCostUsd(usage, reportedCostUsd, price) {
|
|
1989
|
+
if (reportedCostUsd !== void 0) {
|
|
1990
|
+
return reportedCostUsd;
|
|
1991
|
+
}
|
|
1992
|
+
return price === void 0 ? null : estimateCost(usage, price);
|
|
1993
|
+
}
|
|
1994
|
+
__name(resolveCostUsd, "resolveCostUsd");
|
|
1995
|
+
function buildContextBlock(passages) {
|
|
1996
|
+
const items = passages.map((passage, index) => {
|
|
1997
|
+
const label = passage.source !== void 0 ? ` (${passage.source})` : "";
|
|
1998
|
+
return `[${index + 1}]${label} ${passage.text}`;
|
|
1999
|
+
}).join("\n\n");
|
|
2000
|
+
return `<retrieved_context>
|
|
2001
|
+
${items}
|
|
2002
|
+
</retrieved_context>
|
|
2003
|
+
Use the retrieved context above to answer when relevant, and cite sources by their bracket number.`;
|
|
2004
|
+
}
|
|
2005
|
+
__name(buildContextBlock, "buildContextBlock");
|
|
2006
|
+
function buildSummaryBlock(summary) {
|
|
2007
|
+
return `<conversation_summary>
|
|
2008
|
+
${summary}
|
|
2009
|
+
</conversation_summary>
|
|
2010
|
+
Earlier messages in this thread are no longer included verbatim. Treat the summary above as an accurate record of them.`;
|
|
2011
|
+
}
|
|
2012
|
+
__name(buildSummaryBlock, "buildSummaryBlock");
|
|
2013
|
+
function settleAll(tasks) {
|
|
2014
|
+
const started = tasks.map((task) => task());
|
|
2015
|
+
return Promise.all(started.map((work) => work.then((value) => ({
|
|
2016
|
+
ok: true,
|
|
2017
|
+
value
|
|
2018
|
+
}), (error) => ({
|
|
2019
|
+
ok: false,
|
|
2020
|
+
error
|
|
2021
|
+
}))));
|
|
2022
|
+
}
|
|
2023
|
+
__name(settleAll, "settleAll");
|
|
2024
|
+
var QuotaExceededError = class extends Error {
|
|
2025
|
+
static {
|
|
2026
|
+
__name(this, "QuotaExceededError");
|
|
2027
|
+
}
|
|
2028
|
+
constructor() {
|
|
2029
|
+
super("Daily token quota exceeded");
|
|
2030
|
+
this.name = "QuotaExceededError";
|
|
2031
|
+
}
|
|
2032
|
+
};
|
|
2033
|
+
var RunCancelledError = class extends Error {
|
|
2034
|
+
static {
|
|
2035
|
+
__name(this, "RunCancelledError");
|
|
2036
|
+
}
|
|
2037
|
+
constructor() {
|
|
2038
|
+
super("Run cancelled");
|
|
2039
|
+
this.name = "RunCancelledError";
|
|
2040
|
+
}
|
|
2041
|
+
};
|
|
2042
|
+
function agentFailureCode(error) {
|
|
2043
|
+
if (error instanceof RunCancelledError) {
|
|
2044
|
+
return "cancelled";
|
|
2045
|
+
}
|
|
2046
|
+
if (error instanceof QuotaExceededError) {
|
|
2047
|
+
return "quota_exceeded";
|
|
2048
|
+
}
|
|
2049
|
+
if (error instanceof OutputRejectedError) {
|
|
2050
|
+
return "output_rejected";
|
|
2051
|
+
}
|
|
2052
|
+
if (error instanceof StructuredOutputError) {
|
|
2053
|
+
return "structured_output_invalid";
|
|
2054
|
+
}
|
|
2055
|
+
return "run_failed";
|
|
2056
|
+
}
|
|
2057
|
+
__name(agentFailureCode, "agentFailureCode");
|
|
2058
|
+
var MAX_DELEGATION_DEPTH = 5;
|
|
2059
|
+
var DEFAULT_MAX_AGENT_APPEARANCES = 1;
|
|
2060
|
+
function delegationRefusal(args) {
|
|
2061
|
+
const { deps, input, targetAgent } = args;
|
|
2062
|
+
const ancestry = input.delegationPath ?? [];
|
|
2063
|
+
const appearances = ancestry.filter((name) => name === targetAgent).length;
|
|
2064
|
+
const maxAppearances = deps.maxAgentAppearances ?? DEFAULT_MAX_AGENT_APPEARANCES;
|
|
2065
|
+
if (appearances >= maxAppearances) {
|
|
2066
|
+
const chain = [
|
|
2067
|
+
...ancestry,
|
|
2068
|
+
targetAgent
|
|
2069
|
+
].join(" \u2192 ");
|
|
2070
|
+
const times = appearances + 1;
|
|
2071
|
+
return `(delegation cycle: ${chain} \u2014 ${targetAgent} ${times} times on one chain)`;
|
|
2072
|
+
}
|
|
2073
|
+
const maxDepth = deps.maxDelegationDepth ?? MAX_DELEGATION_DEPTH;
|
|
2074
|
+
if ((input.delegationDepth ?? 0) >= maxDepth) {
|
|
2075
|
+
return `(delegation depth limit of ${maxDepth} reached)`;
|
|
2076
|
+
}
|
|
2077
|
+
return null;
|
|
2078
|
+
}
|
|
2079
|
+
__name(delegationRefusal, "delegationRefusal");
|
|
2080
|
+
async function resolvePrompt(prompt, ctx) {
|
|
2081
|
+
return typeof prompt === "function" ? prompt(ctx) : prompt;
|
|
2082
|
+
}
|
|
2083
|
+
__name(resolvePrompt, "resolvePrompt");
|
|
2084
|
+
async function resolveSystemPrompt(deps, input) {
|
|
2085
|
+
const ctx = {
|
|
2086
|
+
actor: input.actor,
|
|
2087
|
+
agentName: input.agentName ?? "default",
|
|
2088
|
+
...input.pageContext !== void 0 ? {
|
|
2089
|
+
pageContext: input.pageContext
|
|
2090
|
+
} : {}
|
|
2091
|
+
};
|
|
2092
|
+
const sections = [
|
|
2093
|
+
await resolvePrompt(deps.systemPrompt, ctx)
|
|
2094
|
+
];
|
|
2095
|
+
for (const contribute of deps.promptContributors ?? []) {
|
|
2096
|
+
const section = await contribute(ctx);
|
|
2097
|
+
if (section !== null && section.length > 0) {
|
|
2098
|
+
sections.push(section);
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
return sections.join("\n\n");
|
|
2102
|
+
}
|
|
2103
|
+
__name(resolveSystemPrompt, "resolveSystemPrompt");
|
|
2104
|
+
function extractTask(input) {
|
|
2105
|
+
if (typeof input === "object" && input !== null && "task" in input) {
|
|
2106
|
+
const task = input.task;
|
|
2107
|
+
if (typeof task === "string") {
|
|
2108
|
+
return task;
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
return JSON.stringify(input);
|
|
2112
|
+
}
|
|
2113
|
+
__name(extractTask, "extractTask");
|
|
2114
|
+
function deriveTitle(userText) {
|
|
2115
|
+
const trimmed = userText.trim().replace(/\s+/g, " ");
|
|
2116
|
+
return trimmed.length > 60 ? `${trimmed.slice(0, 57)}...` : trimmed || "New chat";
|
|
2117
|
+
}
|
|
2118
|
+
__name(deriveTitle, "deriveTitle");
|
|
2119
|
+
var ToolTimeoutError = class ToolTimeoutError2 extends Error {
|
|
2120
|
+
static {
|
|
2121
|
+
__name(this, "ToolTimeoutError");
|
|
2122
|
+
}
|
|
2123
|
+
constructor(toolName, ms) {
|
|
2124
|
+
super(`Tool "${toolName}" exceeded its ${ms}ms timeout`);
|
|
2125
|
+
this.name = "ToolTimeoutError";
|
|
2126
|
+
}
|
|
2127
|
+
};
|
|
2128
|
+
function withToolTimeout(work, ms, toolName) {
|
|
2129
|
+
return new Promise((resolve, reject) => {
|
|
2130
|
+
const timer = setTimeout(() => reject(new ToolTimeoutError(toolName, ms)), ms);
|
|
2131
|
+
work.then((value) => {
|
|
2132
|
+
clearTimeout(timer);
|
|
2133
|
+
resolve(value);
|
|
2134
|
+
}, (error) => {
|
|
2135
|
+
clearTimeout(timer);
|
|
2136
|
+
reject(error);
|
|
2137
|
+
});
|
|
2138
|
+
});
|
|
2139
|
+
}
|
|
2140
|
+
__name(withToolTimeout, "withToolTimeout");
|
|
2141
|
+
function parseFollowUps(text, count) {
|
|
2142
|
+
const source = text.match(/\[[\s\S]*\]/)?.[0] ?? text;
|
|
2143
|
+
try {
|
|
2144
|
+
const parsed = JSON.parse(source);
|
|
2145
|
+
if (Array.isArray(parsed)) {
|
|
2146
|
+
return parsed.filter((item) => typeof item === "string").slice(0, count);
|
|
2147
|
+
}
|
|
2148
|
+
} catch {
|
|
2149
|
+
}
|
|
2150
|
+
return [];
|
|
2151
|
+
}
|
|
2152
|
+
__name(parseFollowUps, "parseFollowUps");
|
|
2153
|
+
async function generateFollowUps(model, messages, count) {
|
|
2154
|
+
const discard = {
|
|
2155
|
+
write: /* @__PURE__ */ __name(() => {
|
|
2156
|
+
}, "write"),
|
|
2157
|
+
end: /* @__PURE__ */ __name(() => {
|
|
674
2158
|
}, "end"),
|
|
675
2159
|
fail: /* @__PURE__ */ __name(() => {
|
|
676
2160
|
}, "fail")
|
|
677
2161
|
};
|
|
678
|
-
const turn = await model.runTurn({
|
|
679
|
-
system: `Based on the conversation so far, propose up to ${count} short, distinct follow-up questions the user is likely to ask next. Respond with ONLY a JSON array of strings \u2014 no prose, no code fences.`,
|
|
680
|
-
messages,
|
|
681
|
-
tools: [],
|
|
682
|
-
sink: discard
|
|
2162
|
+
const turn = await model.runTurn({
|
|
2163
|
+
system: `Based on the conversation so far, propose up to ${count} short, distinct follow-up questions the user is likely to ask next. Respond with ONLY a JSON array of strings \u2014 no prose, no code fences.`,
|
|
2164
|
+
messages,
|
|
2165
|
+
tools: [],
|
|
2166
|
+
sink: discard
|
|
2167
|
+
});
|
|
2168
|
+
return {
|
|
2169
|
+
followUps: parseFollowUps(turn.text, count),
|
|
2170
|
+
usage: turn.usage,
|
|
2171
|
+
...turn.modelId !== void 0 ? {
|
|
2172
|
+
modelId: turn.modelId
|
|
2173
|
+
} : {}
|
|
2174
|
+
};
|
|
2175
|
+
}
|
|
2176
|
+
__name(generateFollowUps, "generateFollowUps");
|
|
2177
|
+
async function spanned(event, runId, payload, run, summarize) {
|
|
2178
|
+
let value;
|
|
2179
|
+
await trace("agent", event, async () => {
|
|
2180
|
+
value = await run();
|
|
2181
|
+
return summarize(value);
|
|
2182
|
+
}, payload, {
|
|
2183
|
+
traceId: runId
|
|
2184
|
+
});
|
|
2185
|
+
return value;
|
|
2186
|
+
}
|
|
2187
|
+
__name(spanned, "spanned");
|
|
2188
|
+
function traceLlmTurn(runId, step, run) {
|
|
2189
|
+
return spanned("llm.turn", runId, {
|
|
2190
|
+
runId,
|
|
2191
|
+
step
|
|
2192
|
+
}, run, (turn) => ({
|
|
2193
|
+
...turn.modelId !== void 0 ? {
|
|
2194
|
+
modelId: turn.modelId
|
|
2195
|
+
} : {},
|
|
2196
|
+
inputTokens: turn.usage.inputTokens,
|
|
2197
|
+
outputTokens: turn.usage.outputTokens,
|
|
2198
|
+
textLength: turn.text.length,
|
|
2199
|
+
toolCalls: turn.toolCalls.length
|
|
2200
|
+
}));
|
|
2201
|
+
}
|
|
2202
|
+
__name(traceLlmTurn, "traceLlmTurn");
|
|
2203
|
+
function traceToolExecution(runId, call, run) {
|
|
2204
|
+
return spanned("tool.execution", runId, {
|
|
2205
|
+
runId,
|
|
2206
|
+
...call
|
|
2207
|
+
}, run, () => ({}));
|
|
2208
|
+
}
|
|
2209
|
+
__name(traceToolExecution, "traceToolExecution");
|
|
2210
|
+
function toModelMessages(messages) {
|
|
2211
|
+
return messages.map((message) => ({
|
|
2212
|
+
role: message.role,
|
|
2213
|
+
content: message.content,
|
|
2214
|
+
...message.toolCalls !== void 0 ? {
|
|
2215
|
+
toolCalls: message.toolCalls
|
|
2216
|
+
} : {},
|
|
2217
|
+
...message.toolResults !== void 0 ? {
|
|
2218
|
+
toolResults: message.toolResults
|
|
2219
|
+
} : {},
|
|
2220
|
+
...message.attachments !== void 0 ? {
|
|
2221
|
+
attachments: message.attachments
|
|
2222
|
+
} : {}
|
|
2223
|
+
}));
|
|
2224
|
+
}
|
|
2225
|
+
__name(toModelMessages, "toModelMessages");
|
|
2226
|
+
function historyContext(input) {
|
|
2227
|
+
return {
|
|
2228
|
+
threadId: input.threadId,
|
|
2229
|
+
actor: input.actor,
|
|
2230
|
+
...input.agentName !== void 0 ? {
|
|
2231
|
+
agentName: input.agentName
|
|
2232
|
+
} : {}
|
|
2233
|
+
};
|
|
2234
|
+
}
|
|
2235
|
+
__name(historyContext, "historyContext");
|
|
2236
|
+
function splitHistory(policy, input, messages) {
|
|
2237
|
+
return policy === void 0 ? {
|
|
2238
|
+
keep: messages,
|
|
2239
|
+
drop: []
|
|
2240
|
+
} : policy.select(messages, historyContext(input));
|
|
2241
|
+
}
|
|
2242
|
+
__name(splitHistory, "splitHistory");
|
|
2243
|
+
async function loadSelectedHistory(deps, input, hooks) {
|
|
2244
|
+
return hooks.step("load:thread", async () => {
|
|
2245
|
+
const thread = await readThreadForTurn(deps, input.threadId);
|
|
2246
|
+
const { keep, drop } = splitHistory(deps.historyPolicy, input, toModelMessages(thread.messages));
|
|
2247
|
+
return {
|
|
2248
|
+
messages: keep,
|
|
2249
|
+
dropped: deps.historyPolicy?.summarize === void 0 ? [] : drop,
|
|
2250
|
+
title: thread.title,
|
|
2251
|
+
hasAssistantMessage: thread.hasAssistantMessage
|
|
2252
|
+
};
|
|
2253
|
+
});
|
|
2254
|
+
}
|
|
2255
|
+
__name(loadSelectedHistory, "loadSelectedHistory");
|
|
2256
|
+
async function readThreadForTurn(deps, threadId) {
|
|
2257
|
+
const windowing = deps.store;
|
|
2258
|
+
if (typeof windowing.loadThreadForTurn === "function") {
|
|
2259
|
+
const messageLimit = turnMessageLimit(deps.historyPolicy);
|
|
2260
|
+
const page = await windowing.loadThreadForTurn({
|
|
2261
|
+
threadId,
|
|
2262
|
+
...messageLimit !== void 0 ? {
|
|
2263
|
+
messageLimit
|
|
2264
|
+
} : {}
|
|
2265
|
+
});
|
|
2266
|
+
return page === null ? {
|
|
2267
|
+
messages: [],
|
|
2268
|
+
title: null,
|
|
2269
|
+
hasAssistantMessage: false
|
|
2270
|
+
} : {
|
|
2271
|
+
messages: page.messages,
|
|
2272
|
+
title: page.title,
|
|
2273
|
+
hasAssistantMessage: page.hasAssistantMessage
|
|
2274
|
+
};
|
|
2275
|
+
}
|
|
2276
|
+
const thread = await deps.store.getThread(threadId);
|
|
2277
|
+
const stored = thread?.messages ?? [];
|
|
2278
|
+
return {
|
|
2279
|
+
messages: stored,
|
|
2280
|
+
title: thread?.title ?? null,
|
|
2281
|
+
hasAssistantMessage: stored.some((message) => message.role === "assistant")
|
|
2282
|
+
};
|
|
2283
|
+
}
|
|
2284
|
+
__name(readThreadForTurn, "readThreadForTurn");
|
|
2285
|
+
function turnMessageLimit(policy) {
|
|
2286
|
+
if (policy === void 0 || policy.summarize !== void 0) {
|
|
2287
|
+
return void 0;
|
|
2288
|
+
}
|
|
2289
|
+
return policy.maxMessages;
|
|
2290
|
+
}
|
|
2291
|
+
__name(turnMessageLimit, "turnMessageLimit");
|
|
2292
|
+
async function loadWholeThread(deps, input, hooks) {
|
|
2293
|
+
const thread = await hooks.step("load:thread", () => deps.store.getThread(input.threadId));
|
|
2294
|
+
const stored = thread?.messages ?? [];
|
|
2295
|
+
const { keep, drop } = splitHistory(deps.historyPolicy, input, toModelMessages(stored));
|
|
2296
|
+
return {
|
|
2297
|
+
messages: keep,
|
|
2298
|
+
dropped: drop,
|
|
2299
|
+
title: thread?.title ?? null,
|
|
2300
|
+
hasAssistantMessage: stored.some((message) => message.role === "assistant")
|
|
2301
|
+
};
|
|
2302
|
+
}
|
|
2303
|
+
__name(loadWholeThread, "loadWholeThread");
|
|
2304
|
+
async function foldDroppedHistory(summarize, deps, input, hooks, history) {
|
|
2305
|
+
const summary = await hooks.step("history:summarize", () => summarize(history.dropped, historyContext(input)));
|
|
2306
|
+
if (summary.usage !== void 0) {
|
|
2307
|
+
const usage = summary.usage;
|
|
2308
|
+
await hooks.step("persist:usage:history", () => deps.store.recordUsage({
|
|
2309
|
+
threadId: input.threadId,
|
|
2310
|
+
actorRef: input.actor.id,
|
|
2311
|
+
modelId: summary.modelId ?? deps.modelId ?? "unknown",
|
|
2312
|
+
purpose: "history_summary",
|
|
2313
|
+
usage
|
|
2314
|
+
}));
|
|
2315
|
+
}
|
|
2316
|
+
return [
|
|
2317
|
+
{
|
|
2318
|
+
role: "system",
|
|
2319
|
+
content: buildSummaryBlock(summary.text)
|
|
2320
|
+
},
|
|
2321
|
+
...history.messages
|
|
2322
|
+
];
|
|
2323
|
+
}
|
|
2324
|
+
__name(foldDroppedHistory, "foldDroppedHistory");
|
|
2325
|
+
function processorContext(input, step) {
|
|
2326
|
+
return {
|
|
2327
|
+
threadId: input.threadId,
|
|
2328
|
+
actor: input.actor,
|
|
2329
|
+
step,
|
|
2330
|
+
...input.agentName !== void 0 ? {
|
|
2331
|
+
agentName: input.agentName
|
|
2332
|
+
} : {}
|
|
2333
|
+
};
|
|
2334
|
+
}
|
|
2335
|
+
__name(processorContext, "processorContext");
|
|
2336
|
+
function restatementPrompt(messages, answer, fromTranscript) {
|
|
2337
|
+
const restated = {
|
|
2338
|
+
role: "assistant",
|
|
2339
|
+
content: answer
|
|
2340
|
+
};
|
|
2341
|
+
if (fromTranscript) {
|
|
2342
|
+
return [
|
|
2343
|
+
...messages,
|
|
2344
|
+
restated
|
|
2345
|
+
];
|
|
2346
|
+
}
|
|
2347
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
2348
|
+
const message = messages[index];
|
|
2349
|
+
if (message?.role === "user") {
|
|
2350
|
+
return [
|
|
2351
|
+
message,
|
|
2352
|
+
restated
|
|
2353
|
+
];
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
return [
|
|
2357
|
+
restated
|
|
2358
|
+
];
|
|
2359
|
+
}
|
|
2360
|
+
__name(restatementPrompt, "restatementPrompt");
|
|
2361
|
+
async function structureAnswer(schema, deps, input, hooks, messages, step) {
|
|
2362
|
+
const instruction = deps.outputInstruction ?? DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION;
|
|
2363
|
+
const maxAttempts = 1 + (deps.outputRepairAttempts ?? 1);
|
|
2364
|
+
const outputProcessors = deps.outputProcessors ?? [];
|
|
2365
|
+
let issues = [];
|
|
2366
|
+
let text = "";
|
|
2367
|
+
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
2368
|
+
const system = attempt === 0 ? instruction : repairInstruction(instruction, issues);
|
|
2369
|
+
const reply = await hooks.step(`structured:${step}:${attempt}`, () => spanned("structured-output", hooks.runId, {
|
|
2370
|
+
runId: hooks.runId,
|
|
2371
|
+
step,
|
|
2372
|
+
attempt
|
|
2373
|
+
}, async () => {
|
|
2374
|
+
const discard = {
|
|
2375
|
+
write: /* @__PURE__ */ __name(() => {
|
|
2376
|
+
}, "write"),
|
|
2377
|
+
end: /* @__PURE__ */ __name(() => {
|
|
2378
|
+
}, "end"),
|
|
2379
|
+
fail: /* @__PURE__ */ __name(() => {
|
|
2380
|
+
}, "fail")
|
|
2381
|
+
};
|
|
2382
|
+
const turn = await deps.model.runTurn({
|
|
2383
|
+
system,
|
|
2384
|
+
messages,
|
|
2385
|
+
tools: [],
|
|
2386
|
+
sink: discard,
|
|
2387
|
+
outputSchema: schema
|
|
2388
|
+
});
|
|
2389
|
+
return {
|
|
2390
|
+
text: turn.text,
|
|
2391
|
+
usage: turn.usage,
|
|
2392
|
+
...turn.object !== void 0 ? {
|
|
2393
|
+
object: turn.object
|
|
2394
|
+
} : {},
|
|
2395
|
+
...turn.modelId !== void 0 ? {
|
|
2396
|
+
modelId: turn.modelId
|
|
2397
|
+
} : {}
|
|
2398
|
+
};
|
|
2399
|
+
}, (result) => ({
|
|
2400
|
+
inputTokens: result.usage.inputTokens,
|
|
2401
|
+
outputTokens: result.usage.outputTokens,
|
|
2402
|
+
textLength: result.text.length
|
|
2403
|
+
})));
|
|
2404
|
+
await hooks.step(`persist:usage:structured:${step}:${attempt}`, () => deps.store.recordUsage({
|
|
2405
|
+
threadId: input.threadId,
|
|
2406
|
+
actorRef: input.actor.id,
|
|
2407
|
+
modelId: reply.modelId ?? deps.modelId ?? "unknown",
|
|
2408
|
+
purpose: "structured_output",
|
|
2409
|
+
usage: reply.usage
|
|
2410
|
+
}));
|
|
2411
|
+
text = reply.text;
|
|
2412
|
+
if (outputProcessors.length > 0) {
|
|
2413
|
+
const gate = await hooks.step(`process:output:structured:${step}:${attempt}`, () => runOutputProcessors(outputProcessors, {
|
|
2414
|
+
text: reply.text,
|
|
2415
|
+
toolCalls: []
|
|
2416
|
+
}, processorContext(input, step)));
|
|
2417
|
+
if (gate.rejection !== void 0) {
|
|
2418
|
+
throw new OutputRejectedError(gate.rejection.processor, gate.rejection.reason);
|
|
2419
|
+
}
|
|
2420
|
+
text = gate.text;
|
|
2421
|
+
}
|
|
2422
|
+
const reported = text === reply.text ? reply.object : void 0;
|
|
2423
|
+
const outcome = await validateStructured(schema, text, reported);
|
|
2424
|
+
if (outcome.ok) {
|
|
2425
|
+
return outcome.value;
|
|
2426
|
+
}
|
|
2427
|
+
issues = outcome.issues;
|
|
2428
|
+
}
|
|
2429
|
+
throw new StructuredOutputError(issues, text, maxAttempts);
|
|
2430
|
+
}
|
|
2431
|
+
__name(structureAnswer, "structureAnswer");
|
|
2432
|
+
function declaredKind(deps, name) {
|
|
2433
|
+
if (deps.ask === true && name === ASK_TOOL_NAME) {
|
|
2434
|
+
return "ask";
|
|
2435
|
+
}
|
|
2436
|
+
if (deps.skills !== void 0 && name === SKILL_TOOL_NAME) {
|
|
2437
|
+
return "skill";
|
|
2438
|
+
}
|
|
2439
|
+
if (memoryIsWritable(deps) && name === REMEMBER_TOOL_NAME) {
|
|
2440
|
+
return "memory";
|
|
2441
|
+
}
|
|
2442
|
+
return deps.registry.spec(name)?.kind ?? "read";
|
|
2443
|
+
}
|
|
2444
|
+
__name(declaredKind, "declaredKind");
|
|
2445
|
+
function memoryIsWritable(deps) {
|
|
2446
|
+
return deps.memory?.provider.write !== void 0;
|
|
2447
|
+
}
|
|
2448
|
+
__name(memoryIsWritable, "memoryIsWritable");
|
|
2449
|
+
function withAskTool({ tools, ask }) {
|
|
2450
|
+
return ask === true ? [
|
|
2451
|
+
...tools,
|
|
2452
|
+
askToolDefinition()
|
|
2453
|
+
] : tools;
|
|
2454
|
+
}
|
|
2455
|
+
__name(withAskTool, "withAskTool");
|
|
2456
|
+
async function awaitElicitation(hooks, request, ctx) {
|
|
2457
|
+
if (hooks.awaitAnswers !== void 0) {
|
|
2458
|
+
return normalizeElicitationReply(await hooks.awaitAnswers(request, ctx));
|
|
2459
|
+
}
|
|
2460
|
+
return normalizeElicitationReply(await hooks.awaitApproval({
|
|
2461
|
+
id: request.id,
|
|
2462
|
+
name: ASK_TOOL_NAME,
|
|
2463
|
+
input: request,
|
|
2464
|
+
kind: "ask"
|
|
2465
|
+
}, ctx));
|
|
2466
|
+
}
|
|
2467
|
+
__name(awaitElicitation, "awaitElicitation");
|
|
2468
|
+
function toolContext(deps, input, hooks) {
|
|
2469
|
+
return {
|
|
2470
|
+
actor: input.actor,
|
|
2471
|
+
threadId: input.threadId,
|
|
2472
|
+
runId: hooks.runId,
|
|
2473
|
+
requestId: hooks.runId,
|
|
2474
|
+
...input.agentName !== void 0 ? {
|
|
2475
|
+
agentName: input.agentName
|
|
2476
|
+
} : {},
|
|
2477
|
+
...input.pageContext !== void 0 ? {
|
|
2478
|
+
pageContext: input.pageContext
|
|
2479
|
+
} : {},
|
|
2480
|
+
...deps.host !== void 0 ? {
|
|
2481
|
+
host: deps.host
|
|
2482
|
+
} : {}
|
|
2483
|
+
};
|
|
2484
|
+
}
|
|
2485
|
+
__name(toolContext, "toolContext");
|
|
2486
|
+
function intakeApplies(intake, threadHasAssistant) {
|
|
2487
|
+
return intake.when === "every-turn" || !threadHasAssistant;
|
|
2488
|
+
}
|
|
2489
|
+
__name(intakeApplies, "intakeApplies");
|
|
2490
|
+
async function runIntake(intake, deps, input, hooks, writer, threadHasAssistant) {
|
|
2491
|
+
const preamble = intake.preamble ?? DEFAULT_INTAKE_PREAMBLE;
|
|
2492
|
+
const request = {
|
|
2493
|
+
id: `intake-${hooks.runId}`,
|
|
2494
|
+
source: "intake",
|
|
2495
|
+
preamble,
|
|
2496
|
+
questions: intake.questions
|
|
2497
|
+
};
|
|
2498
|
+
const call = {
|
|
2499
|
+
id: request.id,
|
|
2500
|
+
name: ASK_TOOL_NAME,
|
|
2501
|
+
input: {
|
|
2502
|
+
preamble,
|
|
2503
|
+
questions: intake.questions
|
|
2504
|
+
},
|
|
2505
|
+
kind: "ask"
|
|
2506
|
+
};
|
|
2507
|
+
const asked = await hooks.step("intake:ask", async () => {
|
|
2508
|
+
if (!intakeApplies(intake, threadHasAssistant)) {
|
|
2509
|
+
return null;
|
|
2510
|
+
}
|
|
2511
|
+
const message = await deps.store.appendMessage({
|
|
2512
|
+
threadId: input.threadId,
|
|
2513
|
+
role: "assistant",
|
|
2514
|
+
content: preamble,
|
|
2515
|
+
runId: hooks.runId,
|
|
2516
|
+
toolCalls: [
|
|
2517
|
+
call
|
|
2518
|
+
],
|
|
2519
|
+
...input.agentName !== void 0 ? {
|
|
2520
|
+
agentName: input.agentName
|
|
2521
|
+
} : {}
|
|
2522
|
+
});
|
|
2523
|
+
await deps.store.recordToolCall({
|
|
2524
|
+
toolCallId: request.id,
|
|
2525
|
+
messageId: message.id,
|
|
2526
|
+
toolName: ASK_TOOL_NAME,
|
|
2527
|
+
// The store knows read/action only. An unanswered question is work waiting on a human, which
|
|
2528
|
+
// is what `action` + `pending_approval` already mean — so it surfaces in an approvals inbox
|
|
2529
|
+
// rather than needing one of its own.
|
|
2530
|
+
toolType: "action",
|
|
2531
|
+
input: call.input,
|
|
2532
|
+
status: "pending_approval",
|
|
2533
|
+
runId: hooks.runId
|
|
2534
|
+
});
|
|
2535
|
+
await writer.write(encodeStreamEvent({
|
|
2536
|
+
kind: "elicitation",
|
|
2537
|
+
id: request.id,
|
|
2538
|
+
request
|
|
2539
|
+
}));
|
|
2540
|
+
return {
|
|
2541
|
+
messageId: message.id
|
|
2542
|
+
};
|
|
2543
|
+
});
|
|
2544
|
+
if (asked === null) {
|
|
2545
|
+
return null;
|
|
2546
|
+
}
|
|
2547
|
+
const messageId = asked.messageId;
|
|
2548
|
+
const reply = await awaitElicitation(hooks, request, toolContext(deps, input, hooks));
|
|
2549
|
+
const result = settleElicitation(request, reply);
|
|
2550
|
+
await hooks.step("intake:answers", async () => {
|
|
2551
|
+
await deps.store.updateToolCall({
|
|
2552
|
+
toolCallId: request.id,
|
|
2553
|
+
// A skip is not an answer. Both leave the agent holding the same values, but only one of them
|
|
2554
|
+
// is evidence the user chose them, and a reader auditing what the agent was told has to be
|
|
2555
|
+
// able to tell those apart.
|
|
2556
|
+
status: result.skipped ? "rejected" : "executed",
|
|
2557
|
+
output: result,
|
|
2558
|
+
...result.skipped ? {
|
|
2559
|
+
error: "skipped by the user"
|
|
2560
|
+
} : {},
|
|
2561
|
+
...reply.answeredByRef !== void 0 ? {
|
|
2562
|
+
executedByRef: reply.answeredByRef
|
|
2563
|
+
} : {}
|
|
2564
|
+
});
|
|
2565
|
+
await deps.store.setMessageToolResults(messageId, [
|
|
2566
|
+
{
|
|
2567
|
+
id: request.id,
|
|
2568
|
+
name: ASK_TOOL_NAME,
|
|
2569
|
+
output: result
|
|
2570
|
+
}
|
|
2571
|
+
]);
|
|
2572
|
+
await writer.write(encodeStreamEvent({
|
|
2573
|
+
kind: "tool-output",
|
|
2574
|
+
id: request.id,
|
|
2575
|
+
output: result
|
|
2576
|
+
}));
|
|
2577
|
+
});
|
|
2578
|
+
return {
|
|
2579
|
+
role: "assistant",
|
|
2580
|
+
content: preamble,
|
|
2581
|
+
toolCalls: [
|
|
2582
|
+
call
|
|
2583
|
+
],
|
|
2584
|
+
toolResults: [
|
|
2585
|
+
{
|
|
2586
|
+
id: request.id,
|
|
2587
|
+
name: ASK_TOOL_NAME,
|
|
2588
|
+
output: result
|
|
2589
|
+
}
|
|
2590
|
+
]
|
|
2591
|
+
};
|
|
2592
|
+
}
|
|
2593
|
+
__name(runIntake, "runIntake");
|
|
2594
|
+
var PARALLEL_TOOLS_PATCH = "agent:parallel-tools";
|
|
2595
|
+
var CANCELLATION_PATCH = "agent:cancellation";
|
|
2596
|
+
var SELECTED_HISTORY_PATCH = "agent:selected-history";
|
|
2597
|
+
async function haltIfCancelled(hooks, cancellable, name) {
|
|
2598
|
+
const observe = hooks.cancelled;
|
|
2599
|
+
if (!cancellable || observe === void 0) {
|
|
2600
|
+
return;
|
|
2601
|
+
}
|
|
2602
|
+
if (await hooks.step(name, () => observe())) {
|
|
2603
|
+
throw new RunCancelledError();
|
|
2604
|
+
}
|
|
2605
|
+
}
|
|
2606
|
+
__name(haltIfCancelled, "haltIfCancelled");
|
|
2607
|
+
async function claimToolCall(turn, call) {
|
|
2608
|
+
const { deps, input, hooks, messageId } = turn;
|
|
2609
|
+
const persisted = await hooks.step(`persist:toolcall:${call.id}`, async () => {
|
|
2610
|
+
const spec = deps.registry.spec(call.name);
|
|
2611
|
+
const kind = declaredKind(deps, call.name);
|
|
2612
|
+
const awaitsHuman = kind === "action" || kind === "ask";
|
|
2613
|
+
await deps.store.recordToolCall({
|
|
2614
|
+
toolCallId: call.id,
|
|
2615
|
+
messageId,
|
|
2616
|
+
toolName: call.name,
|
|
2617
|
+
toolType: awaitsHuman ? "action" : "read",
|
|
2618
|
+
input: call.input,
|
|
2619
|
+
status: awaitsHuman ? "pending_approval" : "auto_executed",
|
|
2620
|
+
runId: hooks.runId
|
|
2621
|
+
});
|
|
2622
|
+
return {
|
|
2623
|
+
kind,
|
|
2624
|
+
...spec?.targetAgent !== void 0 ? {
|
|
2625
|
+
targetAgent: spec.targetAgent
|
|
2626
|
+
} : {},
|
|
2627
|
+
// Only an `agent` spec ever carries this, and only when the author declared it — so a
|
|
2628
|
+
// deployment with no detached edge writes the same bytes here it always has.
|
|
2629
|
+
...spec?.detached === true ? {
|
|
2630
|
+
detached: true
|
|
2631
|
+
} : {}
|
|
2632
|
+
};
|
|
2633
|
+
});
|
|
2634
|
+
const toolType = persisted?.kind ?? call.kind ?? "read";
|
|
2635
|
+
return {
|
|
2636
|
+
call,
|
|
2637
|
+
// What the rest of the turn — the dispatched tool envelope, the stream frames — sees as this
|
|
2638
|
+
// call's kind, so it agrees with the branch actually taken instead of with a second lookup.
|
|
2639
|
+
resolvedCall: call.kind === toolType ? call : {
|
|
2640
|
+
...call,
|
|
2641
|
+
kind: toolType
|
|
2642
|
+
},
|
|
2643
|
+
toolType,
|
|
2644
|
+
...persisted?.targetAgent !== void 0 ? {
|
|
2645
|
+
targetAgent: persisted.targetAgent
|
|
2646
|
+
} : {},
|
|
2647
|
+
...persisted?.detached === true ? {
|
|
2648
|
+
detached: true
|
|
2649
|
+
} : {},
|
|
2650
|
+
ctx: toolContext(deps, input, hooks)
|
|
2651
|
+
};
|
|
2652
|
+
}
|
|
2653
|
+
__name(claimToolCall, "claimToolCall");
|
|
2654
|
+
async function loadSkillIntoTurn(turn, claimed, startedAt) {
|
|
2655
|
+
const { deps, input, hooks } = turn;
|
|
2656
|
+
const { call } = claimed;
|
|
2657
|
+
const config = deps.skills;
|
|
2658
|
+
const offer = turn.skills;
|
|
2659
|
+
const outcome = await hooks.step(`tool:${call.id}`, async () => {
|
|
2660
|
+
if (config === void 0 || offer === void 0) {
|
|
2661
|
+
return {
|
|
2662
|
+
ok: false,
|
|
2663
|
+
error: "Skills are not available in this deployment."
|
|
2664
|
+
};
|
|
2665
|
+
}
|
|
2666
|
+
const parsed = await skillInputSchema["~standard"].validate(call.input);
|
|
2667
|
+
if (parsed.issues !== void 0) {
|
|
2668
|
+
return {
|
|
2669
|
+
ok: false,
|
|
2670
|
+
error: `invalid skill input: ${parsed.issues.map((each) => `${(each.path ?? []).join(".") || "(root)"}: ${each.message}`).join("; ")}`
|
|
2671
|
+
};
|
|
2672
|
+
}
|
|
2673
|
+
const loaded = await loadSkill(config, offer, parsed.value.name, skillContext(input));
|
|
2674
|
+
if (!loaded.ok) {
|
|
2675
|
+
return {
|
|
2676
|
+
ok: false,
|
|
2677
|
+
error: loaded.error
|
|
2678
|
+
};
|
|
2679
|
+
}
|
|
2680
|
+
return {
|
|
2681
|
+
ok: true,
|
|
2682
|
+
output: {
|
|
2683
|
+
name: loaded.skill.name,
|
|
2684
|
+
scope: loaded.skill.scope,
|
|
2685
|
+
body: loaded.skill.body,
|
|
2686
|
+
...loaded.shadows !== void 0 ? {
|
|
2687
|
+
shadows: loaded.shadows
|
|
2688
|
+
} : {}
|
|
2689
|
+
}
|
|
2690
|
+
};
|
|
2691
|
+
});
|
|
2692
|
+
return outcome.ok ? {
|
|
2693
|
+
status: "executed",
|
|
2694
|
+
output: outcome.output,
|
|
2695
|
+
executionMs: Date.now() - startedAt
|
|
2696
|
+
} : {
|
|
2697
|
+
status: "failed",
|
|
2698
|
+
error: outcome.error,
|
|
2699
|
+
executionMs: Date.now() - startedAt
|
|
2700
|
+
};
|
|
2701
|
+
}
|
|
2702
|
+
__name(loadSkillIntoTurn, "loadSkillIntoTurn");
|
|
2703
|
+
async function rememberIntoTurn(turn, claimed, startedAt) {
|
|
2704
|
+
const { deps, input, hooks } = turn;
|
|
2705
|
+
const { call } = claimed;
|
|
2706
|
+
const config = deps.memory;
|
|
2707
|
+
const digest = turn.memory;
|
|
2708
|
+
const outcome = await hooks.step(`tool:${call.id}`, async () => {
|
|
2709
|
+
if (config === void 0 || digest === void 0) {
|
|
2710
|
+
return {
|
|
2711
|
+
ok: false,
|
|
2712
|
+
error: "Memory is not available in this deployment."
|
|
2713
|
+
};
|
|
2714
|
+
}
|
|
2715
|
+
const parsed = await rememberInputSchema["~standard"].validate(call.input);
|
|
2716
|
+
if (parsed.issues !== void 0) {
|
|
2717
|
+
return {
|
|
2718
|
+
ok: false,
|
|
2719
|
+
error: `invalid remember input: ${parsed.issues.map((each) => `${(each.path ?? []).join(".") || "(root)"}: ${each.message}`).join("; ")}`
|
|
2720
|
+
};
|
|
2721
|
+
}
|
|
2722
|
+
return await writeMemory({
|
|
2723
|
+
config,
|
|
2724
|
+
digest,
|
|
2725
|
+
call: parsed.value,
|
|
2726
|
+
ctx: skillContext(input),
|
|
2727
|
+
runId: hooks.runId
|
|
2728
|
+
});
|
|
2729
|
+
});
|
|
2730
|
+
if (!outcome.ok) {
|
|
2731
|
+
return {
|
|
2732
|
+
status: "failed",
|
|
2733
|
+
error: outcome.error,
|
|
2734
|
+
executionMs: Date.now() - startedAt
|
|
2735
|
+
};
|
|
2736
|
+
}
|
|
2737
|
+
publishAgentMemoryWritten({
|
|
2738
|
+
runId: hooks.runId,
|
|
2739
|
+
scope: outcome.record.scope,
|
|
2740
|
+
chars: outcome.record.text.length
|
|
2741
|
+
});
|
|
2742
|
+
return {
|
|
2743
|
+
status: "executed",
|
|
2744
|
+
output: outcome.record,
|
|
2745
|
+
executionMs: Date.now() - startedAt
|
|
2746
|
+
};
|
|
2747
|
+
}
|
|
2748
|
+
__name(rememberIntoTurn, "rememberIntoTurn");
|
|
2749
|
+
function skillContext(input) {
|
|
2750
|
+
return {
|
|
2751
|
+
actor: input.actor,
|
|
2752
|
+
threadId: input.threadId,
|
|
2753
|
+
...input.agentName !== void 0 ? {
|
|
2754
|
+
agentName: input.agentName
|
|
2755
|
+
} : {},
|
|
2756
|
+
...input.pageContext !== void 0 ? {
|
|
2757
|
+
pageContext: input.pageContext
|
|
2758
|
+
} : {}
|
|
2759
|
+
};
|
|
2760
|
+
}
|
|
2761
|
+
__name(skillContext, "skillContext");
|
|
2762
|
+
async function invokeClaimedTool(turn, claimed) {
|
|
2763
|
+
const { deps, input, hooks } = turn;
|
|
2764
|
+
const { call, resolvedCall, ctx } = claimed;
|
|
2765
|
+
const toolType = claimed.toolType === "action" ? "action" : "read";
|
|
2766
|
+
const startedAt = Date.now();
|
|
2767
|
+
try {
|
|
2768
|
+
if (claimed.toolType === "skill") {
|
|
2769
|
+
return await loadSkillIntoTurn(turn, claimed, startedAt);
|
|
2770
|
+
}
|
|
2771
|
+
if (claimed.toolType === "memory") {
|
|
2772
|
+
return await rememberIntoTurn(turn, claimed, startedAt);
|
|
2773
|
+
}
|
|
2774
|
+
let output;
|
|
2775
|
+
if (hooks.dispatchTool) {
|
|
2776
|
+
const stepCtx = {
|
|
2777
|
+
actor: input.actor,
|
|
2778
|
+
threadId: input.threadId,
|
|
2779
|
+
runId: hooks.runId,
|
|
2780
|
+
requestId: hooks.runId,
|
|
2781
|
+
...input.agentName !== void 0 ? {
|
|
2782
|
+
agentName: input.agentName
|
|
2783
|
+
} : {},
|
|
2784
|
+
...input.pageContext !== void 0 ? {
|
|
2785
|
+
pageContext: input.pageContext
|
|
2786
|
+
} : {}
|
|
2787
|
+
};
|
|
2788
|
+
const envelope = {
|
|
2789
|
+
toolName: call.name,
|
|
2790
|
+
input: call.input,
|
|
2791
|
+
ctx: stepCtx,
|
|
2792
|
+
...deps.toolTimeoutMs !== void 0 ? {
|
|
2793
|
+
timeoutMs: deps.toolTimeoutMs
|
|
2794
|
+
} : {},
|
|
2795
|
+
// Numeric-only: the handler applies withToolTimeout AND its own local `classify` — see
|
|
2796
|
+
// ToolStepEnvelope.transientRetry.
|
|
2797
|
+
transientRetry: resolveToolTransientRetryNumbers(deps.toolTransientRetry)
|
|
2798
|
+
};
|
|
2799
|
+
output = await hooks.dispatchTool(resolvedCall, envelope);
|
|
2800
|
+
} else {
|
|
2801
|
+
const invocation = hooks.step(`tool:${call.id}`, () => traceToolExecution(hooks.runId, {
|
|
2802
|
+
toolCallId: call.id,
|
|
2803
|
+
toolName: call.name,
|
|
2804
|
+
toolType
|
|
2805
|
+
}, () => invokeWithTransientRetry(() => deps.registry.invoke(call.name, call.input, ctx, deps.rolesPolicy), deps.toolTransientRetry ?? {}, {
|
|
2806
|
+
...hooks.isControlFlowError !== void 0 ? {
|
|
2807
|
+
isControlFlowError: hooks.isControlFlowError
|
|
2808
|
+
} : {},
|
|
2809
|
+
onRetry: /* @__PURE__ */ __name((attempt, retryError) => {
|
|
2810
|
+
publishAgentToolRetry({
|
|
2811
|
+
toolName: call.name,
|
|
2812
|
+
toolCallId: call.id,
|
|
2813
|
+
attempt,
|
|
2814
|
+
message: retryError instanceof Error ? retryError.message : String(retryError)
|
|
2815
|
+
});
|
|
2816
|
+
}, "onRetry")
|
|
2817
|
+
})));
|
|
2818
|
+
output = deps.toolTimeoutMs !== void 0 ? await withToolTimeout(invocation, deps.toolTimeoutMs, call.name) : await invocation;
|
|
2819
|
+
}
|
|
2820
|
+
return {
|
|
2821
|
+
status: "executed",
|
|
2822
|
+
output,
|
|
2823
|
+
executionMs: Date.now() - startedAt
|
|
2824
|
+
};
|
|
2825
|
+
} catch (error) {
|
|
2826
|
+
if (hooks.isControlFlowError?.(error) === true || isControlFlowSignal(error) || isReplayIntegrityError(error)) {
|
|
2827
|
+
throw error;
|
|
2828
|
+
}
|
|
2829
|
+
return {
|
|
2830
|
+
status: "failed",
|
|
2831
|
+
error: error instanceof Error ? error.message : String(error),
|
|
2832
|
+
executionMs: Date.now() - startedAt
|
|
2833
|
+
};
|
|
2834
|
+
}
|
|
2835
|
+
}
|
|
2836
|
+
__name(invokeClaimedTool, "invokeClaimedTool");
|
|
2837
|
+
async function recordToolOutcome(turn, claimed, outcome, deciderRef) {
|
|
2838
|
+
const { deps, hooks } = turn;
|
|
2839
|
+
const { call } = claimed;
|
|
2840
|
+
const toolType = claimed.toolType === "action" ? "action" : "read";
|
|
2841
|
+
if (outcome.status === "failed") {
|
|
2842
|
+
await hooks.step(`persist:toolfail:${call.id}`, () => deps.store.updateToolCall({
|
|
2843
|
+
toolCallId: call.id,
|
|
2844
|
+
status: "failed",
|
|
2845
|
+
error: outcome.error,
|
|
2846
|
+
executionMs: outcome.executionMs
|
|
2847
|
+
}));
|
|
2848
|
+
publishAgentToolCall({
|
|
2849
|
+
runId: hooks.runId,
|
|
2850
|
+
toolName: call.name,
|
|
2851
|
+
toolType,
|
|
2852
|
+
status: "failed",
|
|
2853
|
+
durationMs: outcome.executionMs
|
|
2854
|
+
});
|
|
2855
|
+
return {
|
|
2856
|
+
id: call.id,
|
|
2857
|
+
name: call.name,
|
|
2858
|
+
output: null,
|
|
2859
|
+
error: outcome.error
|
|
2860
|
+
};
|
|
2861
|
+
}
|
|
2862
|
+
await hooks.step(`persist:toolexec:${call.id}`, () => deps.store.updateToolCall({
|
|
2863
|
+
toolCallId: call.id,
|
|
2864
|
+
status: "executed",
|
|
2865
|
+
output: outcome.output,
|
|
2866
|
+
executionMs: outcome.executionMs,
|
|
2867
|
+
...toolType === "action" ? {
|
|
2868
|
+
executedByRef: deciderRef
|
|
2869
|
+
} : {}
|
|
2870
|
+
}));
|
|
2871
|
+
publishAgentToolCall({
|
|
2872
|
+
runId: hooks.runId,
|
|
2873
|
+
toolName: call.name,
|
|
2874
|
+
toolType,
|
|
2875
|
+
status: "executed",
|
|
2876
|
+
durationMs: outcome.executionMs
|
|
2877
|
+
});
|
|
2878
|
+
return {
|
|
2879
|
+
id: call.id,
|
|
2880
|
+
name: call.name,
|
|
2881
|
+
output: outcome.output
|
|
2882
|
+
};
|
|
2883
|
+
}
|
|
2884
|
+
__name(recordToolOutcome, "recordToolOutcome");
|
|
2885
|
+
async function delegateToolCall(turn, claimed) {
|
|
2886
|
+
const { deps, input, hooks } = turn;
|
|
2887
|
+
const { call, targetAgent = call.name } = claimed;
|
|
2888
|
+
const task = extractTask(call.input);
|
|
2889
|
+
const refusal = delegationRefusal({
|
|
2890
|
+
deps,
|
|
2891
|
+
input,
|
|
2892
|
+
targetAgent
|
|
2893
|
+
});
|
|
2894
|
+
const start = claimed.detached === true && refusal === null ? hooks.startAgent : void 0;
|
|
2895
|
+
publishAgentDelegated({
|
|
2896
|
+
runId: hooks.runId,
|
|
2897
|
+
toAgent: targetAgent,
|
|
2898
|
+
...input.agentName !== void 0 ? {
|
|
2899
|
+
fromAgent: input.agentName
|
|
2900
|
+
} : {},
|
|
2901
|
+
...start !== void 0 ? {
|
|
2902
|
+
detached: true
|
|
2903
|
+
} : {}
|
|
683
2904
|
});
|
|
2905
|
+
let sub;
|
|
2906
|
+
if (refusal !== null) {
|
|
2907
|
+
sub = {
|
|
2908
|
+
text: refusal
|
|
2909
|
+
};
|
|
2910
|
+
} else if (start !== void 0) {
|
|
2911
|
+
const started = await start({
|
|
2912
|
+
agentName: targetAgent,
|
|
2913
|
+
task,
|
|
2914
|
+
toolCallId: call.id
|
|
2915
|
+
});
|
|
2916
|
+
sub = detachedStarted({
|
|
2917
|
+
agent: targetAgent,
|
|
2918
|
+
runId: started.runId
|
|
2919
|
+
});
|
|
2920
|
+
} else if (hooks.runAgent) {
|
|
2921
|
+
sub = await hooks.runAgent(targetAgent, task);
|
|
2922
|
+
} else {
|
|
2923
|
+
sub = {
|
|
2924
|
+
text: `(no multi-agent support wired; cannot reach "${targetAgent}")`
|
|
2925
|
+
};
|
|
2926
|
+
}
|
|
2927
|
+
await hooks.step(`persist:toolexec:${call.id}`, () => deps.store.updateToolCall({
|
|
2928
|
+
toolCallId: call.id,
|
|
2929
|
+
status: "executed",
|
|
2930
|
+
output: sub
|
|
2931
|
+
}));
|
|
684
2932
|
return {
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
modelId: turn.modelId
|
|
689
|
-
} : {}
|
|
2933
|
+
id: call.id,
|
|
2934
|
+
name: call.name,
|
|
2935
|
+
output: sub
|
|
690
2936
|
};
|
|
691
2937
|
}
|
|
692
|
-
__name(
|
|
693
|
-
async function
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
2938
|
+
__name(delegateToolCall, "delegateToolCall");
|
|
2939
|
+
async function elicitToolCall(turn, claimed) {
|
|
2940
|
+
const { deps, hooks } = turn;
|
|
2941
|
+
const { call, ctx } = claimed;
|
|
2942
|
+
const parsed = await askInputSchema["~standard"].validate(call.input);
|
|
2943
|
+
if (parsed.issues !== void 0) {
|
|
2944
|
+
const error = `invalid ask input: ${parsed.issues.map((each) => `${(each.path ?? []).join(".") || "(root)"}: ${each.message}`).join("; ")}`;
|
|
2945
|
+
await hooks.step(`persist:toolfail:${call.id}`, () => deps.store.updateToolCall({
|
|
2946
|
+
toolCallId: call.id,
|
|
2947
|
+
status: "failed",
|
|
2948
|
+
error
|
|
2949
|
+
}));
|
|
2950
|
+
return {
|
|
2951
|
+
id: call.id,
|
|
2952
|
+
name: call.name,
|
|
2953
|
+
output: null,
|
|
2954
|
+
error
|
|
2955
|
+
};
|
|
2956
|
+
}
|
|
2957
|
+
const request = {
|
|
2958
|
+
id: call.id,
|
|
2959
|
+
source: "ask",
|
|
2960
|
+
questions: parsed.value.questions,
|
|
2961
|
+
...parsed.value.preamble !== void 0 ? {
|
|
2962
|
+
preamble: parsed.value.preamble
|
|
2963
|
+
} : {}
|
|
2964
|
+
};
|
|
2965
|
+
await hooks.step(`stream:elicitation:${call.id}`, async () => {
|
|
2966
|
+
await turn.writer.write(encodeStreamEvent({
|
|
2967
|
+
kind: "elicitation",
|
|
2968
|
+
id: call.id,
|
|
2969
|
+
request
|
|
2970
|
+
}));
|
|
700
2971
|
});
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
...turn.modelId !== void 0 ? {
|
|
710
|
-
modelId: turn.modelId
|
|
2972
|
+
const reply = await awaitElicitation(hooks, request, ctx);
|
|
2973
|
+
const result = settleElicitation(request, reply);
|
|
2974
|
+
await hooks.step(result.skipped ? `persist:toolreject:${call.id}` : `persist:toolexec:${call.id}`, () => deps.store.updateToolCall({
|
|
2975
|
+
toolCallId: call.id,
|
|
2976
|
+
status: result.skipped ? "rejected" : "executed",
|
|
2977
|
+
output: result,
|
|
2978
|
+
...result.skipped ? {
|
|
2979
|
+
error: "skipped by the user"
|
|
711
2980
|
} : {},
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
toolCalls: turn.toolCalls.length
|
|
2981
|
+
...reply.answeredByRef !== void 0 ? {
|
|
2982
|
+
executedByRef: reply.answeredByRef
|
|
2983
|
+
} : {}
|
|
716
2984
|
}));
|
|
2985
|
+
publishAgentToolCall({
|
|
2986
|
+
runId: hooks.runId,
|
|
2987
|
+
toolName: call.name,
|
|
2988
|
+
toolType: "action",
|
|
2989
|
+
status: result.skipped ? "rejected" : "executed"
|
|
2990
|
+
});
|
|
2991
|
+
return {
|
|
2992
|
+
id: call.id,
|
|
2993
|
+
name: call.name,
|
|
2994
|
+
output: result
|
|
2995
|
+
};
|
|
717
2996
|
}
|
|
718
|
-
__name(
|
|
719
|
-
function
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
2997
|
+
__name(elicitToolCall, "elicitToolCall");
|
|
2998
|
+
async function runClaimedToolCall(turn, claimed) {
|
|
2999
|
+
const { deps, input, hooks } = turn;
|
|
3000
|
+
const { call, toolType, ctx } = claimed;
|
|
3001
|
+
if (toolType === "agent") {
|
|
3002
|
+
return delegateToolCall(turn, claimed);
|
|
3003
|
+
}
|
|
3004
|
+
if (toolType === "ask") {
|
|
3005
|
+
return elicitToolCall(turn, claimed);
|
|
3006
|
+
}
|
|
3007
|
+
let deciderRef = input.actor.id;
|
|
3008
|
+
if (toolType === "action") {
|
|
3009
|
+
const decision = await hooks.awaitApproval(call, ctx);
|
|
3010
|
+
deciderRef = decision.executedByRef ?? input.actor.id;
|
|
3011
|
+
if (!decision.approved) {
|
|
3012
|
+
await hooks.step(`persist:toolreject:${call.id}`, () => deps.store.updateToolCall({
|
|
3013
|
+
toolCallId: call.id,
|
|
3014
|
+
status: "rejected",
|
|
3015
|
+
executedByRef: deciderRef,
|
|
3016
|
+
...decision.reason !== void 0 ? {
|
|
3017
|
+
error: decision.reason
|
|
3018
|
+
} : {}
|
|
3019
|
+
}));
|
|
3020
|
+
publishAgentToolCall({
|
|
3021
|
+
runId: hooks.runId,
|
|
3022
|
+
toolName: call.name,
|
|
3023
|
+
toolType,
|
|
3024
|
+
status: "rejected"
|
|
3025
|
+
});
|
|
3026
|
+
return {
|
|
3027
|
+
id: call.id,
|
|
3028
|
+
name: call.name,
|
|
3029
|
+
output: {
|
|
3030
|
+
rejected: true,
|
|
3031
|
+
reason: decision.reason ?? "rejected by user"
|
|
3032
|
+
},
|
|
3033
|
+
error: "rejected"
|
|
3034
|
+
};
|
|
3035
|
+
}
|
|
3036
|
+
}
|
|
3037
|
+
return recordToolOutcome(turn, claimed, await invokeClaimedTool(turn, claimed), deciderRef);
|
|
724
3038
|
}
|
|
725
|
-
__name(
|
|
3039
|
+
__name(runClaimedToolCall, "runClaimedToolCall");
|
|
3040
|
+
async function invokeClaimedToolsTogether(turn, parallel, claimed) {
|
|
3041
|
+
const settled = await parallel(claimed.map((entry) => () => invokeClaimedTool(turn, entry)));
|
|
3042
|
+
for (const outcome of settled) {
|
|
3043
|
+
if (!outcome.ok) {
|
|
3044
|
+
throw outcome.error;
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
const results = [];
|
|
3048
|
+
for (const [index, entry] of claimed.entries()) {
|
|
3049
|
+
const outcome = settled[index];
|
|
3050
|
+
if (outcome?.ok === true) {
|
|
3051
|
+
results.push(await recordToolOutcome(turn, entry, outcome.value, turn.input.actor.id));
|
|
3052
|
+
}
|
|
3053
|
+
}
|
|
3054
|
+
return results;
|
|
3055
|
+
}
|
|
3056
|
+
__name(invokeClaimedToolsTogether, "invokeClaimedToolsTogether");
|
|
726
3057
|
async function runAgentLoop(deps, input, hooks) {
|
|
727
3058
|
const maxSteps = deps.maxSteps ?? 8;
|
|
728
3059
|
let system = await resolveSystemPrompt(deps, input);
|
|
3060
|
+
const inputProcessors = deps.inputProcessors ?? [];
|
|
3061
|
+
const outputProcessors = deps.outputProcessors ?? [];
|
|
3062
|
+
const gateMode = resolveOutputGateMode(outputProcessors);
|
|
3063
|
+
const gated = gateMode !== "off";
|
|
3064
|
+
const gateLookback = resolveGateLookback(outputProcessors);
|
|
3065
|
+
let structured;
|
|
729
3066
|
if (deps.quota !== void 0) {
|
|
730
3067
|
const quota = deps.quota;
|
|
731
3068
|
const state = await hooks.step("quota:check", () => quota.check(input.actor.id, deps.day));
|
|
@@ -759,25 +3096,18 @@ async function runAgentLoop(deps, input, hooks) {
|
|
|
759
3096
|
threadId: input.threadId,
|
|
760
3097
|
role: "user",
|
|
761
3098
|
content: input.userText,
|
|
3099
|
+
runId: hooks.runId,
|
|
762
3100
|
...input.attachments !== void 0 ? {
|
|
763
3101
|
attachments: input.attachments
|
|
764
3102
|
} : {}
|
|
765
3103
|
}));
|
|
766
3104
|
}
|
|
767
|
-
const
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
} : {},
|
|
774
|
-
...message.toolResults !== void 0 ? {
|
|
775
|
-
toolResults: message.toolResults
|
|
776
|
-
} : {},
|
|
777
|
-
...message.attachments !== void 0 ? {
|
|
778
|
-
attachments: message.attachments
|
|
779
|
-
} : {}
|
|
780
|
-
}));
|
|
3105
|
+
const history = await (hooks.patched?.(SELECTED_HISTORY_PATCH) ?? Promise.resolve(true)) ? await loadSelectedHistory(deps, input, hooks) : await loadWholeThread(deps, input, hooks);
|
|
3106
|
+
let modelMessages = history.messages;
|
|
3107
|
+
const summarize = deps.historyPolicy?.summarize?.bind(deps.historyPolicy);
|
|
3108
|
+
if (summarize !== void 0 && history.dropped.length > 0) {
|
|
3109
|
+
modelMessages = await foldDroppedHistory(summarize, deps, input, hooks, history);
|
|
3110
|
+
}
|
|
781
3111
|
const writer = await hooks.openSink();
|
|
782
3112
|
let lastText = "";
|
|
783
3113
|
let steps = 0;
|
|
@@ -801,9 +3131,41 @@ async function runAgentLoop(deps, input, hooks) {
|
|
|
801
3131
|
...input.agentName !== void 0 ? {
|
|
802
3132
|
agentName: input.agentName
|
|
803
3133
|
} : {},
|
|
3134
|
+
...input.parentRunId !== void 0 ? {
|
|
3135
|
+
parentRunId: input.parentRunId
|
|
3136
|
+
} : {},
|
|
804
3137
|
promptHash
|
|
805
3138
|
});
|
|
806
3139
|
});
|
|
3140
|
+
let memoryDigest;
|
|
3141
|
+
if (deps.memory !== void 0) {
|
|
3142
|
+
const config = deps.memory;
|
|
3143
|
+
memoryDigest = await hooks.step("memory:digest", () => offerMemories({
|
|
3144
|
+
config,
|
|
3145
|
+
ctx: skillContext(input),
|
|
3146
|
+
query: input.userText
|
|
3147
|
+
}));
|
|
3148
|
+
const digest = memoryDigest;
|
|
3149
|
+
const block = digest.entries.length > 0 ? buildMemoryBlock({
|
|
3150
|
+
entries: digest.entries,
|
|
3151
|
+
writable: memoryIsWritable(deps),
|
|
3152
|
+
partial: digest.omitted > 0 || digest.recalled === true
|
|
3153
|
+
}) : "";
|
|
3154
|
+
if (block.length > 0) {
|
|
3155
|
+
system = `${system}
|
|
3156
|
+
|
|
3157
|
+
${block}`;
|
|
3158
|
+
}
|
|
3159
|
+
publishAgentMemoryResolved({
|
|
3160
|
+
runId: hooks.runId,
|
|
3161
|
+
scopes: digest.scopes.length,
|
|
3162
|
+
offered: digest.entries.length,
|
|
3163
|
+
omitted: digest.omitted,
|
|
3164
|
+
pinnedOmitted: digest.pinnedOmitted,
|
|
3165
|
+
recalled: digest.recalled === true,
|
|
3166
|
+
promptChars: block.length
|
|
3167
|
+
});
|
|
3168
|
+
}
|
|
807
3169
|
let injectedPassages;
|
|
808
3170
|
if (deps.retriever !== void 0) {
|
|
809
3171
|
const retriever = deps.retriever;
|
|
@@ -829,6 +3191,24 @@ ${buildContextBlock(passages)}`;
|
|
|
829
3191
|
count: passages.length
|
|
830
3192
|
});
|
|
831
3193
|
}
|
|
3194
|
+
let skillOffer;
|
|
3195
|
+
if (deps.skills !== void 0) {
|
|
3196
|
+
const config = deps.skills;
|
|
3197
|
+
skillOffer = await hooks.step("skills:catalog", () => offerSkills(config, skillContext(input)));
|
|
3198
|
+
const block = skillOffer.entries.length > 0 ? buildSkillsBlock(skillOffer.entries) : "";
|
|
3199
|
+
if (block.length > 0) {
|
|
3200
|
+
system = `${system}
|
|
3201
|
+
|
|
3202
|
+
${block}`;
|
|
3203
|
+
}
|
|
3204
|
+
publishAgentSkillsResolved({
|
|
3205
|
+
runId: hooks.runId,
|
|
3206
|
+
scopes: skillOffer.scopes.length,
|
|
3207
|
+
offered: skillOffer.entries.length,
|
|
3208
|
+
omitted: skillOffer.omitted,
|
|
3209
|
+
promptChars: block.length
|
|
3210
|
+
});
|
|
3211
|
+
}
|
|
832
3212
|
let prices = [];
|
|
833
3213
|
if (deps.pricingStore !== void 0) {
|
|
834
3214
|
const pricingStore = deps.pricingStore;
|
|
@@ -838,36 +3218,124 @@ ${buildContextBlock(passages)}`;
|
|
|
838
3218
|
price.modelId,
|
|
839
3219
|
price
|
|
840
3220
|
]));
|
|
3221
|
+
if (deps.intake !== void 0) {
|
|
3222
|
+
const asked = await runIntake(deps.intake, deps, input, hooks, writer, history.hasAssistantMessage);
|
|
3223
|
+
if (asked !== null) {
|
|
3224
|
+
modelMessages.push(asked);
|
|
3225
|
+
}
|
|
3226
|
+
}
|
|
3227
|
+
const cancellable = hooks.cancelled !== void 0 && await (hooks.patched?.(CANCELLATION_PATCH) ?? Promise.resolve(true));
|
|
841
3228
|
for (let i = 0; i < maxSteps; i += 1) {
|
|
3229
|
+
await haltIfCancelled(hooks, cancellable, `cancel:check:${i}`);
|
|
842
3230
|
await hooks.step(`stream:step-start:${i}`, async () => {
|
|
843
3231
|
await writer.write(encodeStreamEvent({
|
|
844
3232
|
kind: "step-start"
|
|
845
3233
|
}));
|
|
846
3234
|
});
|
|
3235
|
+
let prompt = {
|
|
3236
|
+
system,
|
|
3237
|
+
messages: modelMessages
|
|
3238
|
+
};
|
|
3239
|
+
if (inputProcessors.length > 0) {
|
|
3240
|
+
prompt = await hooks.step(`process:input:${i}`, () => runInputProcessors(inputProcessors, prompt, processorContext(input, i)));
|
|
3241
|
+
}
|
|
847
3242
|
let turn;
|
|
848
3243
|
if (hooks.dispatchLlm) {
|
|
849
3244
|
turn = await hooks.dispatchLlm(i, {
|
|
850
3245
|
...input.agentName !== void 0 ? {
|
|
851
3246
|
agentName: input.agentName
|
|
852
3247
|
} : {},
|
|
853
|
-
system,
|
|
854
|
-
messages:
|
|
855
|
-
actor: input.actor
|
|
3248
|
+
system: prompt.system,
|
|
3249
|
+
messages: prompt.messages,
|
|
3250
|
+
actor: input.actor,
|
|
3251
|
+
...gated ? {
|
|
3252
|
+
bufferOutput: true
|
|
3253
|
+
} : {}
|
|
856
3254
|
});
|
|
857
3255
|
} else {
|
|
858
|
-
const tools =
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
3256
|
+
const tools = withMemoryTool({
|
|
3257
|
+
tools: withSkillTool({
|
|
3258
|
+
tools: withAskTool({
|
|
3259
|
+
tools: await deps.registry.definitionsFor(input.actor, deps.rolesPolicy, deps.toolAllowList),
|
|
3260
|
+
ask: deps.ask
|
|
3261
|
+
}),
|
|
3262
|
+
enabled: deps.skills !== void 0
|
|
3263
|
+
}),
|
|
3264
|
+
enabled: memoryIsWritable(deps)
|
|
3265
|
+
});
|
|
3266
|
+
turn = await hooks.step(`llm:${i}`, async () => {
|
|
3267
|
+
const incremental = gateMode === "incremental" ? createIncrementalGate({
|
|
3268
|
+
processors: outputProcessors,
|
|
3269
|
+
ctx: processorContext(input, i),
|
|
3270
|
+
lookbackChars: gateLookback,
|
|
3271
|
+
writer
|
|
3272
|
+
}) : void 0;
|
|
3273
|
+
const buffer = gateMode === "whole" ? createFrameBuffer() : void 0;
|
|
3274
|
+
const result = await traceLlmTurn(hooks.runId, i, () => deps.model.runTurn({
|
|
3275
|
+
system: prompt.system,
|
|
3276
|
+
messages: prompt.messages,
|
|
3277
|
+
tools,
|
|
3278
|
+
sink: incremental?.writer ?? buffer?.writer ?? writer
|
|
3279
|
+
}));
|
|
3280
|
+
if (incremental !== void 0) {
|
|
3281
|
+
await incremental.settled();
|
|
3282
|
+
const refusal = incremental.rejection();
|
|
3283
|
+
return {
|
|
3284
|
+
...result,
|
|
3285
|
+
releasedText: incremental.released(),
|
|
3286
|
+
...refusal !== void 0 ? {
|
|
3287
|
+
gateRejection: refusal
|
|
3288
|
+
} : {}
|
|
3289
|
+
};
|
|
3290
|
+
}
|
|
3291
|
+
return buffer === void 0 ? result : {
|
|
3292
|
+
...result,
|
|
3293
|
+
bufferedFrames: buffer.frames()
|
|
3294
|
+
};
|
|
3295
|
+
});
|
|
3296
|
+
}
|
|
3297
|
+
let rejection;
|
|
3298
|
+
if (gated) {
|
|
3299
|
+
const gate = await hooks.step(`process:output:${i}`, async () => {
|
|
3300
|
+
const released = turn.releasedText;
|
|
3301
|
+
if (turn.gateRejection !== void 0) {
|
|
3302
|
+
return {
|
|
3303
|
+
text: turn.text,
|
|
3304
|
+
rejection: turn.gateRejection
|
|
3305
|
+
};
|
|
3306
|
+
}
|
|
3307
|
+
const settled = await runOutputProcessors(outputProcessors, {
|
|
3308
|
+
text: turn.text,
|
|
3309
|
+
toolCalls: turn.toolCalls
|
|
3310
|
+
}, processorContext(input, i));
|
|
3311
|
+
if (settled.rejection === void 0) {
|
|
3312
|
+
if (released === void 0) {
|
|
3313
|
+
for (const chunk of releaseGatedFrames(turn.bufferedFrames ?? [], settled.text)) {
|
|
3314
|
+
await writer.write(chunk);
|
|
3315
|
+
}
|
|
3316
|
+
} else {
|
|
3317
|
+
const tail = gateTail(outputProcessors, released, settled.text);
|
|
3318
|
+
if (tail.length > 0) {
|
|
3319
|
+
await writer.write(encodeStreamEvent({
|
|
3320
|
+
kind: "text",
|
|
3321
|
+
text: tail
|
|
3322
|
+
}));
|
|
3323
|
+
}
|
|
3324
|
+
}
|
|
3325
|
+
}
|
|
3326
|
+
return settled;
|
|
3327
|
+
});
|
|
3328
|
+
rejection = gate.rejection;
|
|
3329
|
+
turn = {
|
|
3330
|
+
...turn,
|
|
3331
|
+
text: gate.text
|
|
3332
|
+
};
|
|
865
3333
|
}
|
|
866
3334
|
const resolvedModelId = turn.modelId ?? deps.modelId ?? "unknown";
|
|
867
3335
|
const costUsd = resolveCostUsd(turn.usage, turn.costUsd, priceByModel.get(resolvedModelId));
|
|
868
3336
|
const toolCallsWithKind = turn.toolCalls.map((call) => ({
|
|
869
3337
|
...call,
|
|
870
|
-
kind: deps
|
|
3338
|
+
kind: declaredKind(deps, call.name)
|
|
871
3339
|
}));
|
|
872
3340
|
await hooks.step(`persist:usage:${i}`, () => deps.store.recordUsage({
|
|
873
3341
|
threadId: input.threadId,
|
|
@@ -884,6 +3352,9 @@ ${buildContextBlock(passages)}`;
|
|
|
884
3352
|
const quota = deps.quota;
|
|
885
3353
|
await hooks.step(`quota:bump:${i}`, () => quota.bump(input.actor.id, deps.day, turn.usage.inputTokens + turn.usage.outputTokens));
|
|
886
3354
|
}
|
|
3355
|
+
if (rejection !== void 0) {
|
|
3356
|
+
throw new OutputRejectedError(rejection.processor, rejection.reason);
|
|
3357
|
+
}
|
|
887
3358
|
steps += 1;
|
|
888
3359
|
totalInput += turn.usage.inputTokens;
|
|
889
3360
|
totalOutput += turn.usage.outputTokens;
|
|
@@ -895,6 +3366,9 @@ ${buildContextBlock(passages)}`;
|
|
|
895
3366
|
textLength: turn.text.length
|
|
896
3367
|
});
|
|
897
3368
|
const isFinalTurn = turn.toolCalls.length === 0;
|
|
3369
|
+
if (isFinalTurn && deps.outputSchema !== void 0) {
|
|
3370
|
+
structured = await structureAnswer(deps.outputSchema, deps, input, hooks, restatementPrompt(prompt.messages, turn.text, deps.outputFromTranscript === true), i);
|
|
3371
|
+
}
|
|
898
3372
|
let followUps;
|
|
899
3373
|
if (isFinalTurn && deps.followUpsCount !== void 0 && deps.followUpsCount > 0) {
|
|
900
3374
|
const count = deps.followUpsCount;
|
|
@@ -916,8 +3390,12 @@ ${buildContextBlock(passages)}`;
|
|
|
916
3390
|
modelId: result.modelId
|
|
917
3391
|
} : {}
|
|
918
3392
|
})));
|
|
919
|
-
|
|
920
|
-
|
|
3393
|
+
let suggestions = generated.followUps;
|
|
3394
|
+
if (outputProcessors.length > 0) {
|
|
3395
|
+
suggestions = await hooks.step(`process:output:followups:${i}`, () => gateFollowUps(outputProcessors, suggestions, processorContext(input, i)));
|
|
3396
|
+
}
|
|
3397
|
+
if (suggestions.length > 0) {
|
|
3398
|
+
followUps = suggestions;
|
|
921
3399
|
}
|
|
922
3400
|
await hooks.step(`persist:usage:followups:${i}`, () => deps.store.recordUsage({
|
|
923
3401
|
threadId: input.threadId,
|
|
@@ -927,10 +3405,58 @@ ${buildContextBlock(passages)}`;
|
|
|
927
3405
|
usage: generated.usage
|
|
928
3406
|
}));
|
|
929
3407
|
}
|
|
3408
|
+
const synthetic = [];
|
|
3409
|
+
if (i === 0 && injectedPassages !== void 0) {
|
|
3410
|
+
const call = {
|
|
3411
|
+
id: `retrieve-${hooks.runId}`,
|
|
3412
|
+
name: "retrieve",
|
|
3413
|
+
input: {
|
|
3414
|
+
query: input.userText
|
|
3415
|
+
},
|
|
3416
|
+
kind: "read"
|
|
3417
|
+
};
|
|
3418
|
+
const output = {
|
|
3419
|
+
passages: injectedPassages
|
|
3420
|
+
};
|
|
3421
|
+
synthetic.push({
|
|
3422
|
+
step: "persist:retrieval",
|
|
3423
|
+
call,
|
|
3424
|
+
result: {
|
|
3425
|
+
id: call.id,
|
|
3426
|
+
name: call.name,
|
|
3427
|
+
output
|
|
3428
|
+
}
|
|
3429
|
+
});
|
|
3430
|
+
}
|
|
3431
|
+
if (structured !== void 0) {
|
|
3432
|
+
const call = {
|
|
3433
|
+
id: `structured-${hooks.runId}`,
|
|
3434
|
+
name: "structured_output",
|
|
3435
|
+
input: {},
|
|
3436
|
+
kind: "read"
|
|
3437
|
+
};
|
|
3438
|
+
synthetic.push({
|
|
3439
|
+
step: "persist:structured",
|
|
3440
|
+
call,
|
|
3441
|
+
result: {
|
|
3442
|
+
id: call.id,
|
|
3443
|
+
name: call.name,
|
|
3444
|
+
output: structured
|
|
3445
|
+
}
|
|
3446
|
+
});
|
|
3447
|
+
}
|
|
3448
|
+
const messageCalls = [
|
|
3449
|
+
...toolCallsWithKind,
|
|
3450
|
+
...synthetic.map((entry) => entry.call)
|
|
3451
|
+
];
|
|
3452
|
+
const syntheticResults = synthetic.map((entry) => entry.result);
|
|
930
3453
|
const assistant = await hooks.step(`persist:assistant:${i}`, () => deps.store.appendMessage({
|
|
931
3454
|
threadId: input.threadId,
|
|
932
3455
|
role: "assistant",
|
|
933
3456
|
content: turn.text,
|
|
3457
|
+
// Stamps which turn wrote this message, so a reader does not have to infer it from
|
|
3458
|
+
// timestamps — an inference a regenerate breaks, since it re-answers a surviving prompt.
|
|
3459
|
+
runId: hooks.runId,
|
|
934
3460
|
usage: {
|
|
935
3461
|
...turn.usage,
|
|
936
3462
|
costUsd
|
|
@@ -938,8 +3464,11 @@ ${buildContextBlock(passages)}`;
|
|
|
938
3464
|
...input.agentName !== void 0 ? {
|
|
939
3465
|
agentName: input.agentName
|
|
940
3466
|
} : {},
|
|
941
|
-
...
|
|
942
|
-
toolCalls:
|
|
3467
|
+
...messageCalls.length > 0 ? {
|
|
3468
|
+
toolCalls: messageCalls
|
|
3469
|
+
} : {},
|
|
3470
|
+
...syntheticResults.length > 0 ? {
|
|
3471
|
+
toolResults: syntheticResults
|
|
943
3472
|
} : {},
|
|
944
3473
|
...followUps !== void 0 ? {
|
|
945
3474
|
followUps
|
|
@@ -948,33 +3477,43 @@ ${buildContextBlock(passages)}`;
|
|
|
948
3477
|
const assistantMessage = {
|
|
949
3478
|
role: "assistant",
|
|
950
3479
|
content: turn.text,
|
|
951
|
-
...
|
|
952
|
-
toolCalls:
|
|
3480
|
+
...messageCalls.length > 0 ? {
|
|
3481
|
+
toolCalls: messageCalls
|
|
3482
|
+
} : {},
|
|
3483
|
+
...syntheticResults.length > 0 ? {
|
|
3484
|
+
toolResults: syntheticResults
|
|
953
3485
|
} : {}
|
|
954
3486
|
};
|
|
955
3487
|
modelMessages.push(assistantMessage);
|
|
956
|
-
|
|
957
|
-
const
|
|
958
|
-
|
|
959
|
-
await hooks.step(`persist:retrieval:${assistant.id}`, async () => {
|
|
3488
|
+
for (const entry of synthetic) {
|
|
3489
|
+
const { call, result } = entry;
|
|
3490
|
+
await hooks.step(`${entry.step}:${assistant.id}`, async () => {
|
|
960
3491
|
await deps.store.recordToolCall({
|
|
961
|
-
toolCallId,
|
|
3492
|
+
toolCallId: call.id,
|
|
962
3493
|
messageId: assistant.id,
|
|
963
|
-
toolName:
|
|
3494
|
+
toolName: call.name,
|
|
964
3495
|
toolType: "read",
|
|
965
|
-
input:
|
|
966
|
-
query: input.userText
|
|
967
|
-
},
|
|
3496
|
+
input: call.input,
|
|
968
3497
|
status: "auto_executed",
|
|
969
3498
|
runId: hooks.runId
|
|
970
3499
|
});
|
|
971
3500
|
await deps.store.updateToolCall({
|
|
972
|
-
toolCallId,
|
|
3501
|
+
toolCallId: call.id,
|
|
973
3502
|
status: "executed",
|
|
974
|
-
output:
|
|
975
|
-
passages
|
|
976
|
-
}
|
|
3503
|
+
output: result.output
|
|
977
3504
|
});
|
|
3505
|
+
await writer.write(encodeStreamEvent({
|
|
3506
|
+
kind: "tool-input-available",
|
|
3507
|
+
id: call.id,
|
|
3508
|
+
name: call.name,
|
|
3509
|
+
input: call.input,
|
|
3510
|
+
toolKind: "read"
|
|
3511
|
+
}));
|
|
3512
|
+
await writer.write(encodeStreamEvent({
|
|
3513
|
+
kind: "tool-output",
|
|
3514
|
+
id: call.id,
|
|
3515
|
+
output: result.output
|
|
3516
|
+
}));
|
|
978
3517
|
});
|
|
979
3518
|
}
|
|
980
3519
|
if (isFinalTurn) {
|
|
@@ -987,218 +3526,46 @@ ${buildContextBlock(passages)}`;
|
|
|
987
3526
|
});
|
|
988
3527
|
break;
|
|
989
3528
|
}
|
|
3529
|
+
await haltIfCancelled(hooks, cancellable, `cancel:tools:${i}`);
|
|
990
3530
|
const results = [];
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
if (toolType === "agent") {
|
|
1010
|
-
const targetAgent = spec?.targetAgent ?? call.name;
|
|
1011
|
-
const task = extractTask(call.input);
|
|
1012
|
-
await hooks.step(`persist:toolcall:${call.id}`, () => deps.store.recordToolCall({
|
|
1013
|
-
toolCallId: call.id,
|
|
1014
|
-
messageId: assistant.id,
|
|
1015
|
-
toolName: call.name,
|
|
1016
|
-
toolType: "read",
|
|
1017
|
-
input: call.input,
|
|
1018
|
-
status: "auto_executed",
|
|
1019
|
-
runId: hooks.runId
|
|
1020
|
-
}));
|
|
1021
|
-
const overDepth = (input.delegationDepth ?? 0) >= MAX_DELEGATION_DEPTH;
|
|
1022
|
-
publishAgentDelegated({
|
|
1023
|
-
runId: hooks.runId,
|
|
1024
|
-
toAgent: targetAgent,
|
|
1025
|
-
...input.agentName !== void 0 ? {
|
|
1026
|
-
fromAgent: input.agentName
|
|
1027
|
-
} : {}
|
|
1028
|
-
});
|
|
1029
|
-
let sub;
|
|
1030
|
-
if (overDepth) {
|
|
1031
|
-
sub = {
|
|
1032
|
-
text: `(delegation depth limit of ${MAX_DELEGATION_DEPTH} reached)`
|
|
1033
|
-
};
|
|
1034
|
-
} else if (hooks.runAgent) {
|
|
1035
|
-
sub = await hooks.runAgent(targetAgent, task);
|
|
1036
|
-
} else {
|
|
1037
|
-
sub = {
|
|
1038
|
-
text: `(no multi-agent support wired; cannot reach "${targetAgent}")`
|
|
1039
|
-
};
|
|
1040
|
-
}
|
|
1041
|
-
await hooks.step(`persist:toolexec:${call.id}`, () => deps.store.updateToolCall({
|
|
1042
|
-
toolCallId: call.id,
|
|
1043
|
-
status: "executed",
|
|
1044
|
-
output: sub
|
|
1045
|
-
}));
|
|
1046
|
-
results.push({
|
|
1047
|
-
id: call.id,
|
|
1048
|
-
name: call.name,
|
|
1049
|
-
output: sub
|
|
1050
|
-
});
|
|
1051
|
-
continue;
|
|
3531
|
+
const turnCalls = {
|
|
3532
|
+
deps,
|
|
3533
|
+
input,
|
|
3534
|
+
hooks,
|
|
3535
|
+
messageId: assistant.id,
|
|
3536
|
+
writer,
|
|
3537
|
+
...skillOffer !== void 0 ? {
|
|
3538
|
+
skills: skillOffer
|
|
3539
|
+
} : {},
|
|
3540
|
+
...memoryDigest !== void 0 ? {
|
|
3541
|
+
memory: memoryDigest
|
|
3542
|
+
} : {}
|
|
3543
|
+
};
|
|
3544
|
+
const parallel = hooks.parallel;
|
|
3545
|
+
if (parallel !== void 0 && toolCallsWithKind.length > 1 && await (hooks.patched?.(PARALLEL_TOOLS_PATCH) ?? Promise.resolve(true))) {
|
|
3546
|
+
const claimed = [];
|
|
3547
|
+
for (const call of toolCallsWithKind) {
|
|
3548
|
+
claimed.push(await claimToolCall(turnCalls, call));
|
|
1052
3549
|
}
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
await hooks.step(`persist:toolcall:${call.id}`, () => deps.store.recordToolCall({
|
|
1056
|
-
toolCallId: call.id,
|
|
1057
|
-
messageId: assistant.id,
|
|
1058
|
-
toolName: call.name,
|
|
1059
|
-
toolType: "action",
|
|
1060
|
-
input: call.input,
|
|
1061
|
-
status: "pending_approval",
|
|
1062
|
-
runId: hooks.runId
|
|
1063
|
-
}));
|
|
1064
|
-
const decision = await hooks.awaitApproval(call, ctx);
|
|
1065
|
-
deciderRef = decision.executedByRef ?? input.actor.id;
|
|
1066
|
-
if (!decision.approved) {
|
|
1067
|
-
await hooks.step(`persist:toolreject:${call.id}`, () => deps.store.updateToolCall({
|
|
1068
|
-
toolCallId: call.id,
|
|
1069
|
-
status: "rejected",
|
|
1070
|
-
executedByRef: deciderRef,
|
|
1071
|
-
...decision.reason !== void 0 ? {
|
|
1072
|
-
error: decision.reason
|
|
1073
|
-
} : {}
|
|
1074
|
-
}));
|
|
1075
|
-
results.push({
|
|
1076
|
-
id: call.id,
|
|
1077
|
-
name: call.name,
|
|
1078
|
-
output: {
|
|
1079
|
-
rejected: true,
|
|
1080
|
-
reason: decision.reason ?? "rejected by user"
|
|
1081
|
-
},
|
|
1082
|
-
error: "rejected"
|
|
1083
|
-
});
|
|
1084
|
-
publishAgentToolCall({
|
|
1085
|
-
runId: hooks.runId,
|
|
1086
|
-
toolName: call.name,
|
|
1087
|
-
toolType,
|
|
1088
|
-
status: "rejected"
|
|
1089
|
-
});
|
|
1090
|
-
continue;
|
|
1091
|
-
}
|
|
3550
|
+
if (claimed.every((entry) => entry.toolType === "read" || entry.toolType === "skill" || entry.toolType === "memory")) {
|
|
3551
|
+
results.push(...await invokeClaimedToolsTogether(turnCalls, parallel, claimed));
|
|
1092
3552
|
} else {
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
messageId: assistant.id,
|
|
1096
|
-
toolName: call.name,
|
|
1097
|
-
toolType: "read",
|
|
1098
|
-
input: call.input,
|
|
1099
|
-
status: "auto_executed",
|
|
1100
|
-
runId: hooks.runId
|
|
1101
|
-
}));
|
|
1102
|
-
}
|
|
1103
|
-
const startedAt2 = Date.now();
|
|
1104
|
-
try {
|
|
1105
|
-
let output;
|
|
1106
|
-
if (hooks.dispatchTool) {
|
|
1107
|
-
const stepCtx = {
|
|
1108
|
-
actor: input.actor,
|
|
1109
|
-
threadId: input.threadId,
|
|
1110
|
-
runId: hooks.runId,
|
|
1111
|
-
requestId: hooks.runId,
|
|
1112
|
-
...input.agentName !== void 0 ? {
|
|
1113
|
-
agentName: input.agentName
|
|
1114
|
-
} : {},
|
|
1115
|
-
...input.pageContext !== void 0 ? {
|
|
1116
|
-
pageContext: input.pageContext
|
|
1117
|
-
} : {}
|
|
1118
|
-
};
|
|
1119
|
-
const envelope = {
|
|
1120
|
-
toolName: call.name,
|
|
1121
|
-
input: call.input,
|
|
1122
|
-
ctx: stepCtx,
|
|
1123
|
-
...deps.toolTimeoutMs !== void 0 ? {
|
|
1124
|
-
timeoutMs: deps.toolTimeoutMs
|
|
1125
|
-
} : {},
|
|
1126
|
-
// Numeric-only: the handler applies withToolTimeout AND its own local `classify` — see
|
|
1127
|
-
// ToolStepEnvelope.transientRetry.
|
|
1128
|
-
transientRetry: resolveToolTransientRetryNumbers(deps.toolTransientRetry)
|
|
1129
|
-
};
|
|
1130
|
-
output = await hooks.dispatchTool(call, envelope);
|
|
1131
|
-
} else {
|
|
1132
|
-
const invocation = hooks.step(`tool:${call.id}`, () => traceToolExecution(hooks.runId, {
|
|
1133
|
-
toolCallId: call.id,
|
|
1134
|
-
toolName: call.name,
|
|
1135
|
-
toolType
|
|
1136
|
-
}, () => invokeWithTransientRetry(() => deps.registry.invoke(call.name, call.input, ctx, deps.rolesPolicy), deps.toolTransientRetry ?? {}, {
|
|
1137
|
-
...hooks.isControlFlowError !== void 0 ? {
|
|
1138
|
-
isControlFlowError: hooks.isControlFlowError
|
|
1139
|
-
} : {},
|
|
1140
|
-
onRetry: /* @__PURE__ */ __name((attempt, retryError) => {
|
|
1141
|
-
publishAgentToolRetry({
|
|
1142
|
-
toolName: call.name,
|
|
1143
|
-
toolCallId: call.id,
|
|
1144
|
-
attempt,
|
|
1145
|
-
message: retryError instanceof Error ? retryError.message : String(retryError)
|
|
1146
|
-
});
|
|
1147
|
-
}, "onRetry")
|
|
1148
|
-
})));
|
|
1149
|
-
output = deps.toolTimeoutMs !== void 0 ? await withToolTimeout(invocation, deps.toolTimeoutMs, call.name) : await invocation;
|
|
1150
|
-
}
|
|
1151
|
-
const executionMs = Date.now() - startedAt2;
|
|
1152
|
-
await hooks.step(`persist:toolexec:${call.id}`, () => deps.store.updateToolCall({
|
|
1153
|
-
toolCallId: call.id,
|
|
1154
|
-
status: "executed",
|
|
1155
|
-
output,
|
|
1156
|
-
executionMs,
|
|
1157
|
-
...toolType === "action" ? {
|
|
1158
|
-
executedByRef: deciderRef
|
|
1159
|
-
} : {}
|
|
1160
|
-
}));
|
|
1161
|
-
results.push({
|
|
1162
|
-
id: call.id,
|
|
1163
|
-
name: call.name,
|
|
1164
|
-
output
|
|
1165
|
-
});
|
|
1166
|
-
publishAgentToolCall({
|
|
1167
|
-
runId: hooks.runId,
|
|
1168
|
-
toolName: call.name,
|
|
1169
|
-
toolType,
|
|
1170
|
-
status: "executed",
|
|
1171
|
-
durationMs: executionMs
|
|
1172
|
-
});
|
|
1173
|
-
} catch (error) {
|
|
1174
|
-
if (hooks.isControlFlowError?.(error) === true) {
|
|
1175
|
-
throw error;
|
|
3553
|
+
for (const entry of claimed) {
|
|
3554
|
+
results.push(await runClaimedToolCall(turnCalls, entry));
|
|
1176
3555
|
}
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
status: "failed",
|
|
1182
|
-
error: message,
|
|
1183
|
-
executionMs
|
|
1184
|
-
}));
|
|
1185
|
-
results.push({
|
|
1186
|
-
id: call.id,
|
|
1187
|
-
name: call.name,
|
|
1188
|
-
output: null,
|
|
1189
|
-
error: message
|
|
1190
|
-
});
|
|
1191
|
-
publishAgentToolCall({
|
|
1192
|
-
runId: hooks.runId,
|
|
1193
|
-
toolName: call.name,
|
|
1194
|
-
toolType,
|
|
1195
|
-
status: "failed",
|
|
1196
|
-
durationMs: executionMs
|
|
1197
|
-
});
|
|
3556
|
+
}
|
|
3557
|
+
} else {
|
|
3558
|
+
for (const call of toolCallsWithKind) {
|
|
3559
|
+
results.push(await runClaimedToolCall(turnCalls, await claimToolCall(turnCalls, call)));
|
|
1198
3560
|
}
|
|
1199
3561
|
}
|
|
1200
|
-
|
|
3562
|
+
const settledResults = [
|
|
3563
|
+
...results,
|
|
3564
|
+
...syntheticResults
|
|
3565
|
+
];
|
|
3566
|
+
assistantMessage.toolResults = settledResults;
|
|
1201
3567
|
await hooks.step(`stream:tool-outputs:${i}`, async () => {
|
|
3568
|
+
await deps.store.setMessageToolResults(assistant.id, settledResults);
|
|
1202
3569
|
for (const result of results) {
|
|
1203
3570
|
await writer.write(encodeStreamEvent(result.error !== void 0 ? {
|
|
1204
3571
|
kind: "tool-output-error",
|
|
@@ -1219,9 +3586,34 @@ ${buildContextBlock(passages)}`;
|
|
|
1219
3586
|
}));
|
|
1220
3587
|
});
|
|
1221
3588
|
}
|
|
1222
|
-
if (
|
|
3589
|
+
if (history.title === "" || history.title === "New chat") {
|
|
1223
3590
|
await hooks.step("persist:title", () => deps.store.setTitle(input.threadId, deriveTitle(input.userText)));
|
|
1224
3591
|
}
|
|
3592
|
+
const delivery = input.deliverTo;
|
|
3593
|
+
if (delivery !== void 0) {
|
|
3594
|
+
await hooks.step("deliver:detached", async () => {
|
|
3595
|
+
if (await deps.store.getThread(delivery.threadId) === null) {
|
|
3596
|
+
return;
|
|
3597
|
+
}
|
|
3598
|
+
const agent = input.agentName ?? "default";
|
|
3599
|
+
await deps.store.appendMessage({
|
|
3600
|
+
threadId: delivery.threadId,
|
|
3601
|
+
role: "assistant",
|
|
3602
|
+
content: lastText,
|
|
3603
|
+
agentName: agent,
|
|
3604
|
+
runId: hooks.runId
|
|
3605
|
+
});
|
|
3606
|
+
await deps.store.updateToolCall({
|
|
3607
|
+
toolCallId: delivery.toolCallId,
|
|
3608
|
+
status: "executed",
|
|
3609
|
+
output: detachedDelivered({
|
|
3610
|
+
agent,
|
|
3611
|
+
runId: hooks.runId,
|
|
3612
|
+
text: lastText
|
|
3613
|
+
})
|
|
3614
|
+
});
|
|
3615
|
+
});
|
|
3616
|
+
}
|
|
1225
3617
|
await hooks.step("persist:run:end", async () => {
|
|
1226
3618
|
await deps.store.recordRunEnd?.({
|
|
1227
3619
|
runId: hooks.runId,
|
|
@@ -1238,7 +3630,10 @@ ${buildContextBlock(passages)}`;
|
|
|
1238
3630
|
outputTokens: totalOutput
|
|
1239
3631
|
});
|
|
1240
3632
|
return {
|
|
1241
|
-
text: lastText
|
|
3633
|
+
text: lastText,
|
|
3634
|
+
...structured !== void 0 ? {
|
|
3635
|
+
object: structured
|
|
3636
|
+
} : {}
|
|
1242
3637
|
};
|
|
1243
3638
|
}
|
|
1244
3639
|
__name(runAgentLoop, "runAgentLoop");
|
|
@@ -1252,6 +3647,7 @@ export {
|
|
|
1252
3647
|
AGENT_DURABLE_RUNNER,
|
|
1253
3648
|
AGENT_EMBEDDING_PROVIDER,
|
|
1254
3649
|
AGENT_GOVERNANCE_QUERIES,
|
|
3650
|
+
AGENT_MEMORY,
|
|
1255
3651
|
AGENT_MODEL,
|
|
1256
3652
|
AGENT_OPTIONS,
|
|
1257
3653
|
AGENT_PRICING_STORE,
|
|
@@ -1262,53 +3658,131 @@ export {
|
|
|
1262
3658
|
AGENT_ROLES_POLICY,
|
|
1263
3659
|
AGENT_RUNNER,
|
|
1264
3660
|
AGENT_SINK,
|
|
3661
|
+
AGENT_SKILLS,
|
|
3662
|
+
AGENT_SKILL_SOURCES,
|
|
1265
3663
|
AGENT_SPAN_EVENTS,
|
|
1266
3664
|
AGENT_STORE,
|
|
1267
3665
|
AGENT_TOOL_REGISTRY,
|
|
3666
|
+
ASK_TOOL_DESCRIPTION,
|
|
3667
|
+
ASK_TOOL_NAME,
|
|
1268
3668
|
AgentRegistry,
|
|
1269
3669
|
AgentStreamError,
|
|
3670
|
+
DEFAULT_HISTORY_SUMMARY_INSTRUCTION,
|
|
3671
|
+
DEFAULT_INCREMENTAL_LOOKBACK_CHARS,
|
|
3672
|
+
DEFAULT_INTAKE_PREAMBLE,
|
|
3673
|
+
DEFAULT_MAX_FACT_CHARS,
|
|
3674
|
+
DEFAULT_MAX_MEMORIES,
|
|
3675
|
+
DEFAULT_MAX_SKILLS,
|
|
3676
|
+
DEFAULT_STRUCTURED_OUTPUT_INSTRUCTION,
|
|
1270
3677
|
DEFAULT_TOOL_TRANSIENT_RETRY_ATTEMPTS,
|
|
1271
3678
|
DEFAULT_TOOL_TRANSIENT_RETRY_BACKOFF_MS,
|
|
1272
3679
|
DefaultRolesPolicy,
|
|
3680
|
+
GLOBAL_SCOPE,
|
|
3681
|
+
MAX_ASK_QUESTIONS,
|
|
3682
|
+
OutputRejectedError,
|
|
3683
|
+
ProcessorFailedError,
|
|
1273
3684
|
QuotaExceededError,
|
|
3685
|
+
REMEMBER_TOOL_DESCRIPTION,
|
|
3686
|
+
REMEMBER_TOOL_NAME,
|
|
3687
|
+
RunCancelledError,
|
|
3688
|
+
SKILL_TOOL_DESCRIPTION,
|
|
3689
|
+
SKILL_TOOL_NAME,
|
|
3690
|
+
StructuredOutputError,
|
|
1274
3691
|
THREAD_DETAIL_CONTENT_CHARS,
|
|
1275
3692
|
ToolDisabledError,
|
|
1276
3693
|
ToolForbiddenError,
|
|
1277
3694
|
ToolInputInvalidError,
|
|
1278
3695
|
ToolNotFoundError,
|
|
1279
3696
|
ToolRegistry,
|
|
3697
|
+
actorScope,
|
|
1280
3698
|
agentDiagnosticKey,
|
|
3699
|
+
agentFailureCode,
|
|
3700
|
+
askInputSchema,
|
|
3701
|
+
askToolDefinition,
|
|
1281
3702
|
bucketByActor,
|
|
1282
3703
|
bucketByModel,
|
|
1283
3704
|
bucketByThread,
|
|
1284
3705
|
bucketUsageTrend,
|
|
3706
|
+
buildMemoryBlock,
|
|
3707
|
+
buildSkillsBlock,
|
|
1285
3708
|
canActorUseTool,
|
|
3709
|
+
compositeSkillProvider,
|
|
3710
|
+
createFrameBuffer,
|
|
3711
|
+
createIncrementalGate,
|
|
1286
3712
|
dayBoundsUtc,
|
|
3713
|
+
decodeStreamEvent,
|
|
3714
|
+
defaultScopeResolver,
|
|
3715
|
+
detachedDelivered,
|
|
3716
|
+
detachedStarted,
|
|
3717
|
+
detachedUnsettled,
|
|
1287
3718
|
encodeStreamEvent,
|
|
1288
3719
|
estimateCost,
|
|
3720
|
+
estimateMessageTokens,
|
|
3721
|
+
extractJson,
|
|
1289
3722
|
filterToolsByAllowList,
|
|
1290
3723
|
filterToolsByCanUse,
|
|
1291
3724
|
filterToolsByEnabled,
|
|
1292
3725
|
filterToolsByRole,
|
|
3726
|
+
gateFollowUps,
|
|
3727
|
+
gateTail,
|
|
1293
3728
|
invokeWithTransientRetry,
|
|
3729
|
+
isControlFlowSignal,
|
|
3730
|
+
isReplayIntegrityError,
|
|
1294
3731
|
isToolEnabled,
|
|
1295
3732
|
isTransientToolError,
|
|
3733
|
+
loadSkill,
|
|
3734
|
+
memoryForgetVerdict,
|
|
3735
|
+
memoryWriteVerdict,
|
|
3736
|
+
normalizeDelegation,
|
|
3737
|
+
normalizeElicitationReply,
|
|
3738
|
+
offerMemories,
|
|
3739
|
+
offerSkills,
|
|
1296
3740
|
publishAgentDelegated,
|
|
3741
|
+
publishAgentMemoryResolved,
|
|
3742
|
+
publishAgentMemoryWritten,
|
|
1297
3743
|
publishAgentMessage,
|
|
1298
3744
|
publishAgentQuotaExceeded,
|
|
1299
3745
|
publishAgentRetrieved,
|
|
1300
3746
|
publishAgentRunFailed,
|
|
1301
3747
|
publishAgentRunFinished,
|
|
1302
3748
|
publishAgentRunStarted,
|
|
3749
|
+
publishAgentSkillsResolved,
|
|
1303
3750
|
publishAgentToolCall,
|
|
1304
3751
|
publishAgentToolRetry,
|
|
3752
|
+
releaseGatedFrames,
|
|
3753
|
+
rememberInputSchema,
|
|
3754
|
+
rememberToolDefinition,
|
|
3755
|
+
renderElicitationAnswers,
|
|
3756
|
+
repairInstruction,
|
|
3757
|
+
resolveElicitation,
|
|
3758
|
+
resolveGateLookback,
|
|
3759
|
+
resolveMemoryDigest,
|
|
3760
|
+
resolveOutputGateMode,
|
|
3761
|
+
resolveSkillCatalog,
|
|
1305
3762
|
resolveToolTransientRetryNumbers,
|
|
1306
3763
|
rollupThreadUsage,
|
|
1307
3764
|
runAgentLoop,
|
|
3765
|
+
runInputProcessors,
|
|
3766
|
+
runOutputProcessors,
|
|
1308
3767
|
seedModelPrices,
|
|
3768
|
+
settleAll,
|
|
3769
|
+
settleElicitation,
|
|
3770
|
+
settleUnsettledDelegation,
|
|
3771
|
+
skillInputSchema,
|
|
3772
|
+
skillToolDefinition,
|
|
3773
|
+
skillWriteVerdict,
|
|
3774
|
+
staticSkillProvider,
|
|
3775
|
+
summarizeWithModel,
|
|
3776
|
+
tenantScope,
|
|
1309
3777
|
traceLlmTurn,
|
|
1310
3778
|
traceToolExecution,
|
|
1311
3779
|
truncateDetailContent,
|
|
1312
|
-
|
|
3780
|
+
validateStructured,
|
|
3781
|
+
windowHistory,
|
|
3782
|
+
withAskTool,
|
|
3783
|
+
withMemoryTool,
|
|
3784
|
+
withSkillTool,
|
|
3785
|
+
withToolTimeout,
|
|
3786
|
+
writeMemory
|
|
1313
3787
|
};
|
|
1314
3788
|
//# sourceMappingURL=index.js.map
|