@chosengeneration/light-code 0.193.0 → 0.196.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/dist/bin/fire-fs.exe +0 -0
- package/dist/cli.cjs +1229 -55
- package/dist/server.cjs +1225 -51
- package/package.json +1 -1
package/dist/server.cjs
CHANGED
|
@@ -39360,7 +39360,14 @@ var strategyNodeSchema = external_exports.object({
|
|
|
39360
39360
|
*/
|
|
39361
39361
|
instructions: external_exports.string().max(4e3).optional(),
|
|
39362
39362
|
/** The parallel box it sits in (`StrategyGroup.id`), set by the window from where it was dropped. */
|
|
39363
|
-
group: external_exports.string().max(40).optional()
|
|
39363
|
+
group: external_exports.string().max(40).optional(),
|
|
39364
|
+
/**
|
|
39365
|
+
* A decision step: once this step has answered, the decision model (Settings → Agents) picks which of its outgoing
|
|
39366
|
+
* connectors to follow, by their labels and where they lead - from its answer. Without a decision model, or when it
|
|
39367
|
+
* is not sure, the main agent chooses as before. `decisionQuestion` is the question it is asked, if not the default.
|
|
39368
|
+
*/
|
|
39369
|
+
decides: external_exports.boolean().optional(),
|
|
39370
|
+
decisionQuestion: external_exports.string().max(500).optional()
|
|
39364
39371
|
});
|
|
39365
39372
|
var strategyGroupSchema = external_exports.object({
|
|
39366
39373
|
id: external_exports.string().min(1).max(40),
|
|
@@ -39561,7 +39568,7 @@ function describeStrategy(strategy, roleName) {
|
|
|
39561
39568
|
lines2.push(`${label(group.id)[0].toUpperCase()}${label(group.id).slice(1)} - ${groupKind(group) === "parallel" ? "consulted together, in ONE ask_agents call" : "done as a group, in the order below"}${into.length > 0 ? `, after ${into.join(" and ")}` : ""}:`);
|
|
39562
39569
|
}
|
|
39563
39570
|
const next = strategy.edges.filter((edge) => edge.from === node.id && edge.twoWay !== true).map(onward);
|
|
39564
|
-
lines2.push(`${group !== void 0 ? " " : ""}${String(number5.get(node.id))}. ${roleName(node.role)}${askAs(node.role)}${node.readOnly === true ? " - read-only: may not change anything" : ""}${node.instructions !== void 0 && node.instructions.trim().length > 0 ? ` - the user's instructions for it: "${firstLine(node.instructions)}"` : " - what it does here is yours to plan"}` + (next.length > 0 ? `; then ${next.join(" and ")}` : ""));
|
|
39571
|
+
lines2.push(`${group !== void 0 ? " " : ""}${String(number5.get(node.id))}. ${roleName(node.role)}${askAs(node.role)}${node.readOnly === true ? " - read-only: may not change anything" : ""}${node.instructions !== void 0 && node.instructions.trim().length > 0 ? ` - the user's instructions for it: "${firstLine(node.instructions)}"` : " - what it does here is yours to plan"}` + (next.length > 0 ? `; then ${next.join(" and ")}` : "") + (node.decides === true && next.length > 1 ? " - a decision step: once it answers, the decision model picks which way to go and you are told; if no pick comes, choose yourself" : ""));
|
|
39565
39572
|
if (group !== void 0) {
|
|
39566
39573
|
const members = groupMembers(strategy, group.id);
|
|
39567
39574
|
const last = order2.filter((n) => members.some((m) => m.id === n.id)).at(-1);
|
|
@@ -39658,7 +39665,7 @@ ${[...new Set(instructed)].join("\n\n")}`);
|
|
|
39658
39665
|
notes.push("In this strategy you are read-only: you have no tools that change anything. Recommend changes; do not make them.");
|
|
39659
39666
|
return { addToPrompt: notes.join("\n\n"), readOnly };
|
|
39660
39667
|
}
|
|
39661
|
-
function afterConsult(strategy, progress, role, answer, roleName) {
|
|
39668
|
+
function afterConsult(strategy, progress, role, answer, roleName, judged) {
|
|
39662
39669
|
const next = { ...progress };
|
|
39663
39670
|
const notes = [];
|
|
39664
39671
|
for (const edge of strategy.edges) {
|
|
@@ -39675,7 +39682,8 @@ function afterConsult(strategy, progress, role, answer, roleName) {
|
|
|
39675
39682
|
if (state.awaiting === true)
|
|
39676
39683
|
state.rounds += 1;
|
|
39677
39684
|
state.awaiting = false;
|
|
39678
|
-
const
|
|
39685
|
+
const byModel = judged?.get(edge.id);
|
|
39686
|
+
const verdict = byModel ?? readVerdict(answer);
|
|
39679
39687
|
if (verdict !== void 0) {
|
|
39680
39688
|
state.met = verdict.met;
|
|
39681
39689
|
state.verdict = verdict.met ? "met" : `not met${verdict.detail.length > 0 ? ` - ${verdict.detail}` : ""}`;
|
|
@@ -39683,7 +39691,7 @@ function afterConsult(strategy, progress, role, answer, roleName) {
|
|
|
39683
39691
|
const max = roundsOf(edge);
|
|
39684
39692
|
const pair = `${roleName(from.role)} \u21C4 ${roleName(to.role)}`;
|
|
39685
39693
|
if (state.met === true) {
|
|
39686
|
-
notes.push(`[Strategy] ${pair}: round ${String(state.rounds)} of ${String(max)} - ${roleName(to.role)} says the condition is met. This loop is done; go on to the next step.`);
|
|
39694
|
+
notes.push(`[Strategy] ${pair}: round ${String(state.rounds)} of ${String(max)} - ${byModel !== void 0 ? `the decision model says the condition is met (${byModel.detail})` : `${roleName(to.role)} says the condition is met`}. This loop is done; go on to the next step.`);
|
|
39687
39695
|
} else if (state.rounds >= max) {
|
|
39688
39696
|
notes.push(`[Strategy] ${pair}: all ${String(max)} rounds used${state.verdict !== void 0 ? ` (${state.verdict})` : ""}. Stop the loop and tell the user what is still open.`);
|
|
39689
39697
|
} else if (state.rounds > 0 || edge.until !== void 0) {
|
|
@@ -39797,6 +39805,25 @@ function answerForMain(answer, role) {
|
|
|
39797
39805
|
|
|
39798
39806
|
[Shortened for you: the ${role}'s full answer (${String(answer.length)} characters) was passed to the next step directly and is in the strategy record; read it with strategy_history only if you need the detail.]`;
|
|
39799
39807
|
}
|
|
39808
|
+
function branchChoice(strategy, role, roleName) {
|
|
39809
|
+
const node = strategy.nodes.find((candidate) => candidate.role === role && candidate.decides === true);
|
|
39810
|
+
if (node === void 0)
|
|
39811
|
+
return void 0;
|
|
39812
|
+
const ways = strategy.edges.filter((edge) => edge.from === node.id && edge.twoWay !== true);
|
|
39813
|
+
if (ways.length < 2)
|
|
39814
|
+
return void 0;
|
|
39815
|
+
const targetLabel = (id) => {
|
|
39816
|
+
const target = strategy.nodes.find((candidate) => candidate.id === id);
|
|
39817
|
+
if (target !== void 0)
|
|
39818
|
+
return roleName(target.role);
|
|
39819
|
+
const group = (strategy.groups ?? []).find((candidate) => candidate.id === id);
|
|
39820
|
+
return group !== void 0 ? group.label ?? "the box" : id;
|
|
39821
|
+
};
|
|
39822
|
+
return {
|
|
39823
|
+
question: node.decisionQuestion !== void 0 && node.decisionQuestion.trim().length > 0 ? node.decisionQuestion.trim() : `Given ${roleName(role)}'s answer, which step should come next?`,
|
|
39824
|
+
options: ways.map((edge) => ({ id: edge.id, label: targetLabel(edge.to), ...edge.label !== void 0 && edge.label.trim().length > 0 ? { description: edge.label.trim() } : {} }))
|
|
39825
|
+
};
|
|
39826
|
+
}
|
|
39800
39827
|
|
|
39801
39828
|
// ../../packages/core/dist/mcp/types.js
|
|
39802
39829
|
var mcpDenyRuleSchema = external_exports.object({
|
|
@@ -41362,6 +41389,38 @@ var configSchema = external_exports.object({
|
|
|
41362
41389
|
* whole suggestion. Every pause in typing is a request to the gateway, so off unless set to true.
|
|
41363
41390
|
*/
|
|
41364
41391
|
composerCompletion: external_exports.boolean(),
|
|
41392
|
+
/**
|
|
41393
|
+
* The decision model (D3 from vLLM Semantic Router, or any OpenAI-compatible model that returns probabilities): a
|
|
41394
|
+
* provider profile, and what it decides. Nothing here does anything until `profileId` names a profile - Agent team
|
|
41395
|
+
* and strategies then work exactly as before. `routing`: in Agent team mode, send each message to the specialist
|
|
41396
|
+
* it picks at `routeThreshold` or above (default 0.75). `judgeLoops`: decide a strategy loop's condition at
|
|
41397
|
+
* `loopThreshold` or above, or its mirror below (default 0.8); in between, the judge's wording decides.
|
|
41398
|
+
*/
|
|
41399
|
+
decisionModel: external_exports.object({
|
|
41400
|
+
profileId: external_exports.string().min(1).optional(),
|
|
41401
|
+
/**
|
|
41402
|
+
* Where on the profile's base URL it is asked: blank = automatic (D3's `/systemone`, then chat completions),
|
|
41403
|
+
* a path such as `/d3/v1/systemone` (D3's API there, no fallback), or `chat` (chat completions only).
|
|
41404
|
+
*/
|
|
41405
|
+
endpoint: external_exports.string().max(200).optional(),
|
|
41406
|
+
routing: external_exports.boolean().optional(),
|
|
41407
|
+
routeThreshold: external_exports.number().min(0.5).max(0.99).optional(),
|
|
41408
|
+
judgeLoops: external_exports.boolean().optional(),
|
|
41409
|
+
loopThreshold: external_exports.number().min(0.5).max(0.99).optional(),
|
|
41410
|
+
/** The Anti Hallucinator's first pass (decision/firstPass.ts): on unless false; sure at `firstPassThreshold` (0.85). */
|
|
41411
|
+
firstPass: external_exports.boolean().optional(),
|
|
41412
|
+
firstPassThreshold: external_exports.number().min(0.5).max(0.99).optional(),
|
|
41413
|
+
/** Score hand-overs against their connector's contract (on unless false). */
|
|
41414
|
+
scoreHandOvers: external_exports.boolean().optional(),
|
|
41415
|
+
/** In Agent team, say when another specialist fits a consultation better (on unless false). */
|
|
41416
|
+
suggestRoles: external_exports.boolean().optional(),
|
|
41417
|
+
/** Ask whether a changed plan starts new work, so a strategy's loops start again (on unless false). */
|
|
41418
|
+
newTopics: external_exports.boolean().optional(),
|
|
41419
|
+
/** Fire Code monitoring: raise or lower an alert's notification by whether it needs a person now (on unless false). */
|
|
41420
|
+
triageAlerts: external_exports.boolean().optional(),
|
|
41421
|
+
/** The skill-and-tool picks (switched on per chat, beside the chat): an option is suggested at this or above (0.25). */
|
|
41422
|
+
suggestThreshold: external_exports.number().min(0.05).max(0.95).optional()
|
|
41423
|
+
}).optional(),
|
|
41365
41424
|
/**
|
|
41366
41425
|
* Model requests that fail or go silent. `stallSeconds`: how long a request may send nothing at
|
|
41367
41426
|
* all before it is stopped and sent again (0 = never; default 300). `retries`: how many times a
|
|
@@ -41977,6 +42036,8 @@ var USER_SCOPE_ONLY_KEYS = [
|
|
|
41977
42036
|
"observers",
|
|
41978
42037
|
// Saved strategies steer which specialists act, read-only or not: the user's, never a repository's.
|
|
41979
42038
|
"strategies",
|
|
42039
|
+
// Which model routes messages to specialists and judges strategy loops: the user's, never a repository's.
|
|
42040
|
+
"decisionModel",
|
|
41980
42041
|
// Reads the user's mail and their open workbooks. A repository must never switch it on.
|
|
41981
42042
|
"office",
|
|
41982
42043
|
// Names language-server programs to run when a file is edited.
|
|
@@ -45490,6 +45551,8 @@ function capEvent(event) {
|
|
|
45490
45551
|
return { ...event, text: cap(event.text, EVENT_LIMITS.result) };
|
|
45491
45552
|
case "turnEnd":
|
|
45492
45553
|
return event.error === void 0 ? event : { ...event, error: cap(event.error, EVENT_LIMITS.result) };
|
|
45554
|
+
case "decision":
|
|
45555
|
+
return { ...event, question: cap(event.question, EVENT_LIMITS.text) };
|
|
45493
45556
|
}
|
|
45494
45557
|
}
|
|
45495
45558
|
var REFUSALS = [
|
|
@@ -54005,11 +54068,11 @@ function scheduleAppliesHere(schedule, workspaceRoot) {
|
|
|
54005
54068
|
return true;
|
|
54006
54069
|
if (workspaceRoot === void 0)
|
|
54007
54070
|
return false;
|
|
54008
|
-
const
|
|
54071
|
+
const normalise3 = (value) => {
|
|
54009
54072
|
const resolved = import_node_path17.default.resolve(value);
|
|
54010
54073
|
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
54011
54074
|
};
|
|
54012
|
-
return
|
|
54075
|
+
return normalise3(schedule.workspaceRoot) === normalise3(workspaceRoot);
|
|
54013
54076
|
}
|
|
54014
54077
|
function filterToolsForSchedule(all, schedule) {
|
|
54015
54078
|
const named2 = new Set(schedule.allowedTools);
|
|
@@ -62293,7 +62356,7 @@ var SHARE_SECTIONS = [
|
|
|
62293
62356
|
id: "agents",
|
|
62294
62357
|
label: "Agents and expert",
|
|
62295
62358
|
description: "Specialist roles and their prompts, and which model holds each seat.",
|
|
62296
|
-
keys: ["agents", "expert"]
|
|
62359
|
+
keys: ["agents", "expert", "decisionModel"]
|
|
62297
62360
|
},
|
|
62298
62361
|
{
|
|
62299
62362
|
id: "skills",
|
|
@@ -66741,6 +66804,631 @@ function cleanSuggestion(typed, reply) {
|
|
|
66741
66804
|
return out.trimEnd();
|
|
66742
66805
|
}
|
|
66743
66806
|
|
|
66807
|
+
// ../../packages/core/dist/host/startupPaths.js
|
|
66808
|
+
var PATH = /(?:[A-Za-z]:[\\/]|\\\\)[^\s"'<>|]+|\/(?:[^\s/"'<>|]+\/)+[^\s/"'<>|]*/g;
|
|
66809
|
+
function shortenPaths(text2) {
|
|
66810
|
+
return text2.replace(PATH, (path69) => {
|
|
66811
|
+
const separator = path69.includes("\\") ? "\\" : "/";
|
|
66812
|
+
const parts = path69.split(/[\\/]+/).filter((part) => part.length > 0);
|
|
66813
|
+
if (parts.length <= 2)
|
|
66814
|
+
return path69;
|
|
66815
|
+
return `\u2026${separator}${parts.slice(-2).join(separator)}`;
|
|
66816
|
+
});
|
|
66817
|
+
}
|
|
66818
|
+
|
|
66819
|
+
// ../../packages/core/dist/decision/decide.js
|
|
66820
|
+
var LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
66821
|
+
var NO_LOGPROBS = /* @__PURE__ */ new Set();
|
|
66822
|
+
function answerOptions(question) {
|
|
66823
|
+
if (question.kind === "yesno")
|
|
66824
|
+
return [{ id: "yes", label: "Yes" }, { id: "no", label: "No" }];
|
|
66825
|
+
if (question.kind === "score")
|
|
66826
|
+
return Array.from({ length: 11 }, (_, i) => ({ id: String(i), label: String(i) }));
|
|
66827
|
+
return (question.options ?? []).slice(0, LETTERS.length);
|
|
66828
|
+
}
|
|
66829
|
+
function decisionMessages(question) {
|
|
66830
|
+
const options = answerOptions(question);
|
|
66831
|
+
const lines2 = [question.question.trim()];
|
|
66832
|
+
if (question.kind === "choice") {
|
|
66833
|
+
lines2.push("", "Options:");
|
|
66834
|
+
options.forEach((option, i) => lines2.push(`${LETTERS[i] ?? "?"}. ${option.label}${option.description !== void 0 && option.description.length > 0 ? ` - ${option.description}` : ""}`));
|
|
66835
|
+
lines2.push("", "Answer with the letter of the best option only.");
|
|
66836
|
+
} else if (question.kind === "yesno") {
|
|
66837
|
+
lines2.push("", "Answer Yes or No only.");
|
|
66838
|
+
} else {
|
|
66839
|
+
lines2.push("", "Answer with a whole number from 0 (not at all) to 10 (completely) only.");
|
|
66840
|
+
}
|
|
66841
|
+
const inputs = question.inputs ?? {};
|
|
66842
|
+
const context = [];
|
|
66843
|
+
if (inputs.text !== void 0 && inputs.text.trim().length > 0)
|
|
66844
|
+
context.push(`Input:
|
|
66845
|
+
${inputs.text.slice(0, 24e3)}`);
|
|
66846
|
+
if (inputs.json !== void 0)
|
|
66847
|
+
context.push(`Data:
|
|
66848
|
+
${JSON.stringify(inputs.json).slice(0, 24e3)}`);
|
|
66849
|
+
const text2 = `${context.length > 0 ? `${context.join("\n\n")}
|
|
66850
|
+
|
|
66851
|
+
` : ""}${lines2.join("\n")}`;
|
|
66852
|
+
const images = inputs.images ?? [];
|
|
66853
|
+
const content = images.length === 0 ? text2 : [{ type: "text", text: text2 }, ...images.map((image) => ({ type: "image_url", image_url: { url: `data:${image.mediaType};base64,${image.data}` } }))];
|
|
66854
|
+
return [
|
|
66855
|
+
{ role: "system", content: "You are a decision model. Answer the question about the input exactly in the form asked for." },
|
|
66856
|
+
{ role: "user", content }
|
|
66857
|
+
];
|
|
66858
|
+
}
|
|
66859
|
+
var num = (value) => typeof value === "number" && Number.isFinite(value) ? value : typeof value === "string" && /^\s*-?\d+(\.\d+)?\s*%?\s*$/.test(value) ? Number.parseFloat(value) / (value.includes("%") ? 100 : 1) : void 0;
|
|
66860
|
+
function optionFor(label, options, kind) {
|
|
66861
|
+
const clean = label.trim().replace(/^[("'\s]+|[)"'.:,\s]+$/g, "").toLowerCase();
|
|
66862
|
+
if (clean.length === 0)
|
|
66863
|
+
return void 0;
|
|
66864
|
+
if (kind === "yesno") {
|
|
66865
|
+
if (["yes", "y", "true", "1"].includes(clean))
|
|
66866
|
+
return "yes";
|
|
66867
|
+
if (["no", "n", "false", "0"].includes(clean))
|
|
66868
|
+
return "no";
|
|
66869
|
+
return void 0;
|
|
66870
|
+
}
|
|
66871
|
+
if (kind === "score")
|
|
66872
|
+
return /^(10|\d)$/.test(clean) ? clean : void 0;
|
|
66873
|
+
const letter = clean.length === 1 ? LETTERS.indexOf(clean.toUpperCase()) : -1;
|
|
66874
|
+
if (letter >= 0 && letter < options.length)
|
|
66875
|
+
return options[letter]?.id;
|
|
66876
|
+
return options.find((option) => option.id.toLowerCase() === clean || option.label.toLowerCase() === clean)?.id;
|
|
66877
|
+
}
|
|
66878
|
+
function normalise2(weights) {
|
|
66879
|
+
let total = 0;
|
|
66880
|
+
for (const weight of weights.values())
|
|
66881
|
+
total += Math.max(0, weight);
|
|
66882
|
+
if (total <= 0)
|
|
66883
|
+
return void 0;
|
|
66884
|
+
const out = {};
|
|
66885
|
+
for (const [id, weight] of weights)
|
|
66886
|
+
out[id] = Math.max(0, weight) / total;
|
|
66887
|
+
return out;
|
|
66888
|
+
}
|
|
66889
|
+
function jsonIn(text2) {
|
|
66890
|
+
const unfenced = text2.replace(/^\s*```[a-z]*\s*/i, "").replace(/\s*```\s*$/, "");
|
|
66891
|
+
const start = unfenced.indexOf("{");
|
|
66892
|
+
const end = unfenced.lastIndexOf("}");
|
|
66893
|
+
if (start < 0 || end <= start)
|
|
66894
|
+
return void 0;
|
|
66895
|
+
try {
|
|
66896
|
+
const parsed = JSON.parse(unfenced.slice(start, end + 1));
|
|
66897
|
+
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : void 0;
|
|
66898
|
+
} catch {
|
|
66899
|
+
return void 0;
|
|
66900
|
+
}
|
|
66901
|
+
}
|
|
66902
|
+
function probabilitiesFromJson(json2, question) {
|
|
66903
|
+
const options = answerOptions(question);
|
|
66904
|
+
const weights = /* @__PURE__ */ new Map();
|
|
66905
|
+
const add = (label, value) => {
|
|
66906
|
+
const id = optionFor(label, options, question.kind);
|
|
66907
|
+
const p = num(value);
|
|
66908
|
+
if (id !== void 0 && p !== void 0)
|
|
66909
|
+
weights.set(id, (weights.get(id) ?? 0) + p);
|
|
66910
|
+
};
|
|
66911
|
+
if (question.kind === "score") {
|
|
66912
|
+
for (const key4 of ["score", "value", "probability", "p"]) {
|
|
66913
|
+
const value = num(json2[key4]);
|
|
66914
|
+
if (value !== void 0)
|
|
66915
|
+
return { score: value > 10 ? Math.min(1, value / 100) : value > 1 ? value / 10 : Math.max(0, value) };
|
|
66916
|
+
}
|
|
66917
|
+
}
|
|
66918
|
+
for (const key4 of ["probabilities", "probs", "scores", "distribution", "choices", "options"]) {
|
|
66919
|
+
const value = json2[key4];
|
|
66920
|
+
if (Array.isArray(value)) {
|
|
66921
|
+
for (const item2 of value) {
|
|
66922
|
+
if (typeof item2 !== "object" || item2 === null)
|
|
66923
|
+
continue;
|
|
66924
|
+
const record2 = item2;
|
|
66925
|
+
const label = [record2["label"], record2["option"], record2["choice"], record2["answer"], record2["id"], record2["name"]].find((v) => typeof v === "string");
|
|
66926
|
+
const p = [record2["probability"], record2["prob"], record2["p"], record2["score"], record2["confidence"]].find((v) => num(v) !== void 0);
|
|
66927
|
+
if (label !== void 0)
|
|
66928
|
+
add(label, p);
|
|
66929
|
+
}
|
|
66930
|
+
} else if (typeof value === "object" && value !== null) {
|
|
66931
|
+
for (const [label, p] of Object.entries(value))
|
|
66932
|
+
add(label, p);
|
|
66933
|
+
}
|
|
66934
|
+
}
|
|
66935
|
+
if (weights.size === 0 && question.kind === "yesno") {
|
|
66936
|
+
for (const [key4, value] of Object.entries(json2)) {
|
|
66937
|
+
const k = key4.toLowerCase().replace(/^p_?/, "");
|
|
66938
|
+
if (k === "yes" || k === "no")
|
|
66939
|
+
add(k, value);
|
|
66940
|
+
}
|
|
66941
|
+
}
|
|
66942
|
+
if (weights.size === 0) {
|
|
66943
|
+
const label = [json2["answer"], json2["choice"], json2["decision"], json2["label"], json2["prediction"]].find((v) => typeof v === "string");
|
|
66944
|
+
const p = num([json2["probability"], json2["confidence"], json2["p"], json2["score"]].find((v) => num(v) !== void 0));
|
|
66945
|
+
if (label !== void 0 && p !== void 0) {
|
|
66946
|
+
const id = optionFor(label, options, question.kind);
|
|
66947
|
+
if (id !== void 0) {
|
|
66948
|
+
const p1 = Math.min(1, Math.max(0, p));
|
|
66949
|
+
weights.set(id, p1);
|
|
66950
|
+
const others = options.filter((option) => option.id !== id);
|
|
66951
|
+
for (const other of others)
|
|
66952
|
+
weights.set(other.id, (1 - p1) / Math.max(1, others.length));
|
|
66953
|
+
}
|
|
66954
|
+
}
|
|
66955
|
+
}
|
|
66956
|
+
const probabilities = normalise2(weights);
|
|
66957
|
+
if (probabilities === void 0)
|
|
66958
|
+
return void 0;
|
|
66959
|
+
if (question.kind === "score")
|
|
66960
|
+
return { probabilities, score: expectedScore(probabilities) };
|
|
66961
|
+
return { probabilities };
|
|
66962
|
+
}
|
|
66963
|
+
function expectedScore(probabilities) {
|
|
66964
|
+
let sum = 0;
|
|
66965
|
+
for (const [digit, p] of Object.entries(probabilities))
|
|
66966
|
+
sum += Number(digit) * p;
|
|
66967
|
+
return sum / 10;
|
|
66968
|
+
}
|
|
66969
|
+
function probabilitiesFromLogprobs(choice, question) {
|
|
66970
|
+
const logprobs = choice["logprobs"];
|
|
66971
|
+
if (typeof logprobs !== "object" || logprobs === null)
|
|
66972
|
+
return void 0;
|
|
66973
|
+
const options = answerOptions(question);
|
|
66974
|
+
const positions = [];
|
|
66975
|
+
const content = logprobs.content;
|
|
66976
|
+
if (Array.isArray(content)) {
|
|
66977
|
+
for (const entry of content) {
|
|
66978
|
+
if (typeof entry !== "object" || entry === null)
|
|
66979
|
+
continue;
|
|
66980
|
+
const record2 = entry;
|
|
66981
|
+
const alternatives = Array.isArray(record2.top_logprobs) ? record2.top_logprobs.filter((alt) => typeof alt === "object" && alt !== null && typeof alt.token === "string" && typeof alt.logprob === "number") : [];
|
|
66982
|
+
if (typeof record2.token === "string")
|
|
66983
|
+
positions.push({ token: record2.token, alternatives: alternatives.length > 0 ? alternatives : typeof record2.logprob === "number" ? [{ token: record2.token, logprob: record2.logprob }] : [] });
|
|
66984
|
+
}
|
|
66985
|
+
} else {
|
|
66986
|
+
const tokens = logprobs.tokens;
|
|
66987
|
+
const tops = logprobs.top_logprobs;
|
|
66988
|
+
if (Array.isArray(tokens) && Array.isArray(tops)) {
|
|
66989
|
+
tokens.forEach((token, i) => {
|
|
66990
|
+
const top = tops[i];
|
|
66991
|
+
if (typeof token !== "string" || typeof top !== "object" || top === null)
|
|
66992
|
+
return;
|
|
66993
|
+
positions.push({ token, alternatives: Object.entries(top).filter((e) => typeof e[1] === "number").map(([t, l]) => ({ token: t, logprob: l })) });
|
|
66994
|
+
});
|
|
66995
|
+
}
|
|
66996
|
+
}
|
|
66997
|
+
const first = positions.find((position) => /[A-Za-z0-9]/.test(position.token));
|
|
66998
|
+
if (first === void 0)
|
|
66999
|
+
return void 0;
|
|
67000
|
+
const weights = /* @__PURE__ */ new Map();
|
|
67001
|
+
for (const alternative of first.alternatives) {
|
|
67002
|
+
const id = optionFor(alternative.token, options, question.kind);
|
|
67003
|
+
if (id !== void 0)
|
|
67004
|
+
weights.set(id, (weights.get(id) ?? 0) + Math.exp(alternative.logprob));
|
|
67005
|
+
}
|
|
67006
|
+
if (question.kind === "score" && first.token.trim() === "1") {
|
|
67007
|
+
const next = positions[positions.indexOf(first) + 1];
|
|
67008
|
+
if (next !== void 0 && next.token.trim() === "0" && weights.has("1")) {
|
|
67009
|
+
weights.set("10", (weights.get("10") ?? 0) + (weights.get("1") ?? 0));
|
|
67010
|
+
weights.delete("1");
|
|
67011
|
+
}
|
|
67012
|
+
}
|
|
67013
|
+
const probabilities = normalise2(weights);
|
|
67014
|
+
if (probabilities === void 0)
|
|
67015
|
+
return void 0;
|
|
67016
|
+
return question.kind === "score" ? { probabilities, score: expectedScore(probabilities) } : { probabilities };
|
|
67017
|
+
}
|
|
67018
|
+
function readDecision(body, question, ms) {
|
|
67019
|
+
const raw = JSON.stringify(body).slice(0, 2e3);
|
|
67020
|
+
if (typeof body !== "object" || body === null)
|
|
67021
|
+
return { ok: false, source: "none", raw, error: "The decision model returned no JSON body.", ms };
|
|
67022
|
+
const record2 = body;
|
|
67023
|
+
const choice = Array.isArray(record2["choices"]) ? record2["choices"][0] : void 0;
|
|
67024
|
+
const message6 = choice?.["message"];
|
|
67025
|
+
const text2 = typeof message6?.content === "string" ? message6.content : typeof choice?.["text"] === "string" ? choice["text"] : "";
|
|
67026
|
+
const finish = (found2, source) => {
|
|
67027
|
+
const probabilities = found2.probabilities;
|
|
67028
|
+
let best;
|
|
67029
|
+
if (probabilities !== void 0 && question.kind !== "score") {
|
|
67030
|
+
for (const [id, probability] of Object.entries(probabilities))
|
|
67031
|
+
if (best === void 0 || probability > best.probability)
|
|
67032
|
+
best = { id, probability };
|
|
67033
|
+
}
|
|
67034
|
+
return { ok: true, ...probabilities !== void 0 ? { probabilities } : {}, ...best !== void 0 ? { best } : {}, ...found2.score !== void 0 ? { score: found2.score } : {}, source, raw, ms };
|
|
67035
|
+
};
|
|
67036
|
+
const top = probabilitiesFromJson(record2, question);
|
|
67037
|
+
if (top !== void 0)
|
|
67038
|
+
return finish(top, "json");
|
|
67039
|
+
const inReply = jsonIn(text2);
|
|
67040
|
+
const fromReply = inReply === void 0 ? void 0 : probabilitiesFromJson(inReply, question);
|
|
67041
|
+
if (fromReply !== void 0)
|
|
67042
|
+
return finish(fromReply, "json");
|
|
67043
|
+
const fromTokens = choice === void 0 ? void 0 : probabilitiesFromLogprobs(choice, question);
|
|
67044
|
+
if (fromTokens !== void 0)
|
|
67045
|
+
return finish(fromTokens, "logprobs");
|
|
67046
|
+
return {
|
|
67047
|
+
ok: false,
|
|
67048
|
+
source: "none",
|
|
67049
|
+
raw,
|
|
67050
|
+
error: `The decision model answered${text2.trim().length > 0 ? ` "${text2.trim().slice(0, 80)}"` : ""} without probabilities: neither JSON scores nor token log-probabilities came back.`,
|
|
67051
|
+
ms
|
|
67052
|
+
};
|
|
67053
|
+
}
|
|
67054
|
+
function decisionEndpointProblem(endpoint) {
|
|
67055
|
+
if (endpoint === void 0 || endpoint === "" || endpoint === "chat")
|
|
67056
|
+
return void 0;
|
|
67057
|
+
if (!endpoint.startsWith("/"))
|
|
67058
|
+
return 'The endpoint is a path on the base URL of the provider, starting with /, or "chat".';
|
|
67059
|
+
if (/:\/\/|\.\.|\s|\\|#|\?/.test(endpoint))
|
|
67060
|
+
return 'The endpoint path may not hold "://", "..", spaces, a backslash, "?" or "#".';
|
|
67061
|
+
return void 0;
|
|
67062
|
+
}
|
|
67063
|
+
var SCORE_LEVELS = ["not at all", "a little", "partly", "mostly", "completely"];
|
|
67064
|
+
function optionKeys(options) {
|
|
67065
|
+
const keys = /* @__PURE__ */ new Map();
|
|
67066
|
+
for (const option of options) {
|
|
67067
|
+
const base = option.label.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 40) || "option";
|
|
67068
|
+
let key4 = base;
|
|
67069
|
+
for (let n = 2; keys.has(key4); n += 1)
|
|
67070
|
+
key4 = `${base}_${String(n)}`;
|
|
67071
|
+
keys.set(key4, option.id);
|
|
67072
|
+
}
|
|
67073
|
+
return keys;
|
|
67074
|
+
}
|
|
67075
|
+
function systemOneRequest(model, question) {
|
|
67076
|
+
const inputs = question.inputs ?? {};
|
|
67077
|
+
const state = [inputs.text !== void 0 && inputs.text.trim().length > 0 ? inputs.text.slice(0, 24e3) : "", inputs.json !== void 0 ? JSON.stringify(inputs.json).slice(0, 24e3) : ""].filter((part) => part.length > 0).join("\n\n");
|
|
67078
|
+
let keys = /* @__PURE__ */ new Map();
|
|
67079
|
+
let asked;
|
|
67080
|
+
if (question.kind === "choice") {
|
|
67081
|
+
const options = (question.options ?? []).slice(0, 255);
|
|
67082
|
+
keys = optionKeys(options);
|
|
67083
|
+
const criteria = {};
|
|
67084
|
+
for (const [key4, id] of keys) {
|
|
67085
|
+
const option = options.find((o) => o.id === id);
|
|
67086
|
+
criteria[key4] = option === void 0 ? key4 : `${option.label}${option.description !== void 0 && option.description.length > 0 ? ` - ${option.description}` : ""}`;
|
|
67087
|
+
}
|
|
67088
|
+
asked = { type: "choice", instructions: question.question, criteria };
|
|
67089
|
+
} else if (question.kind === "yesno") {
|
|
67090
|
+
asked = { type: "noul", instructions: question.question };
|
|
67091
|
+
} else {
|
|
67092
|
+
asked = { type: "score", instructions: question.question, criteria: [...SCORE_LEVELS] };
|
|
67093
|
+
}
|
|
67094
|
+
const images = (inputs.images ?? []).map((image) => `data:${image.mediaType};base64,${image.data}`);
|
|
67095
|
+
return {
|
|
67096
|
+
body: { model, state: state.length > 0 ? state : "(no input)", questions: { q: asked }, ...images.length > 0 ? { images } : {} },
|
|
67097
|
+
keys
|
|
67098
|
+
};
|
|
67099
|
+
}
|
|
67100
|
+
function readSystemOne(body, question, keys, ms) {
|
|
67101
|
+
if (typeof body !== "object" || body === null)
|
|
67102
|
+
return void 0;
|
|
67103
|
+
const record2 = body;
|
|
67104
|
+
const wrapped = [record2, record2["data"], record2["result"]].find((candidate) => typeof candidate === "object" && candidate !== null && typeof candidate.answers === "object");
|
|
67105
|
+
const answers = wrapped?.answers;
|
|
67106
|
+
if (typeof answers !== "object" || answers === null)
|
|
67107
|
+
return void 0;
|
|
67108
|
+
const answer = answers["q"] ?? Object.values(answers)[0];
|
|
67109
|
+
if (answer === void 0 || typeof answer !== "object")
|
|
67110
|
+
return void 0;
|
|
67111
|
+
const raw = JSON.stringify(body).slice(0, 2e3);
|
|
67112
|
+
const given = typeof answer["probabilities"] === "object" && answer["probabilities"] !== null ? answer["probabilities"] : {};
|
|
67113
|
+
const weights = /* @__PURE__ */ new Map();
|
|
67114
|
+
for (const [key4, value] of Object.entries(given)) {
|
|
67115
|
+
const p = num(value);
|
|
67116
|
+
if (p === void 0)
|
|
67117
|
+
continue;
|
|
67118
|
+
if (question.kind === "choice") {
|
|
67119
|
+
const id = keys.get(key4);
|
|
67120
|
+
if (id !== void 0)
|
|
67121
|
+
weights.set(id, p);
|
|
67122
|
+
} else if (question.kind === "yesno") {
|
|
67123
|
+
const k = key4.toLowerCase();
|
|
67124
|
+
if (k === "yes" || k === "no")
|
|
67125
|
+
weights.set(k, p);
|
|
67126
|
+
} else {
|
|
67127
|
+
weights.set(key4, p);
|
|
67128
|
+
}
|
|
67129
|
+
}
|
|
67130
|
+
if (question.kind === "yesno" && weights.size === 0) {
|
|
67131
|
+
const yes = num(answer["noul"]);
|
|
67132
|
+
if (yes !== void 0) {
|
|
67133
|
+
weights.set("yes", yes);
|
|
67134
|
+
weights.set("no", 1 - yes);
|
|
67135
|
+
}
|
|
67136
|
+
}
|
|
67137
|
+
const probabilities = normalise2(weights);
|
|
67138
|
+
if (probabilities === void 0)
|
|
67139
|
+
return { ok: false, source: "systemone", raw, error: "The decision model answered without probabilities for this question.", ms };
|
|
67140
|
+
if (question.kind === "score") {
|
|
67141
|
+
let sum = 0;
|
|
67142
|
+
let mass = 0;
|
|
67143
|
+
for (const [level2, p] of Object.entries(probabilities)) {
|
|
67144
|
+
const index = SCORE_LEVELS.indexOf(level2);
|
|
67145
|
+
if (index < 0)
|
|
67146
|
+
continue;
|
|
67147
|
+
sum += index / (SCORE_LEVELS.length - 1) * p;
|
|
67148
|
+
mass += p;
|
|
67149
|
+
}
|
|
67150
|
+
if (mass === 0)
|
|
67151
|
+
return { ok: false, source: "systemone", raw, error: "The decision model answered with levels it was not given.", ms };
|
|
67152
|
+
return { ok: true, probabilities, score: sum / mass, source: "systemone", raw, ms };
|
|
67153
|
+
}
|
|
67154
|
+
let best;
|
|
67155
|
+
for (const [id, probability] of Object.entries(probabilities))
|
|
67156
|
+
if (best === void 0 || probability > best.probability)
|
|
67157
|
+
best = { id, probability };
|
|
67158
|
+
return { ok: true, probabilities, ...best !== void 0 ? { best } : {}, source: "systemone", raw, ms };
|
|
67159
|
+
}
|
|
67160
|
+
var CHAT_ONLY = /* @__PURE__ */ new Set();
|
|
67161
|
+
async function decide(model, question, options = {}) {
|
|
67162
|
+
const started = Date.now();
|
|
67163
|
+
const base = model.profile.baseUrl.replace(/\/+$/, "");
|
|
67164
|
+
const url2 = `${base}/chat/completions`;
|
|
67165
|
+
const controller = new AbortController();
|
|
67166
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 1e4);
|
|
67167
|
+
const onAbort = () => controller.abort();
|
|
67168
|
+
options.signal?.addEventListener("abort", onAbort);
|
|
67169
|
+
const body = {
|
|
67170
|
+
model: model.profile.model,
|
|
67171
|
+
messages: decisionMessages(question),
|
|
67172
|
+
stream: false,
|
|
67173
|
+
temperature: 0,
|
|
67174
|
+
max_tokens: 32
|
|
67175
|
+
};
|
|
67176
|
+
if (!NO_LOGPROBS.has(base)) {
|
|
67177
|
+
body["logprobs"] = true;
|
|
67178
|
+
body["top_logprobs"] = 20;
|
|
67179
|
+
}
|
|
67180
|
+
const send2 = async () => {
|
|
67181
|
+
const headers = await model.auth.resolveHeaders();
|
|
67182
|
+
const tls2 = await model.auth.tls?.();
|
|
67183
|
+
const response = await model.http.request(url2, {
|
|
67184
|
+
method: "POST",
|
|
67185
|
+
headers: { "Content-Type": "application/json", ...headers, ...model.profile.headers },
|
|
67186
|
+
body: JSON.stringify(body),
|
|
67187
|
+
signal: controller.signal,
|
|
67188
|
+
...tls2 !== void 0 ? { tls: tls2 } : {}
|
|
67189
|
+
});
|
|
67190
|
+
return { status: response.status, text: await response.text() };
|
|
67191
|
+
};
|
|
67192
|
+
const post = async (target, payload) => {
|
|
67193
|
+
let answer = await sendTo(target, payload);
|
|
67194
|
+
if (answer.status === 401 && model.auth.onUnauthorized !== void 0 && await model.auth.onUnauthorized())
|
|
67195
|
+
answer = await sendTo(target, payload);
|
|
67196
|
+
return answer;
|
|
67197
|
+
};
|
|
67198
|
+
const sendTo = async (target, payload) => {
|
|
67199
|
+
const headers = await model.auth.resolveHeaders();
|
|
67200
|
+
const tls2 = await model.auth.tls?.();
|
|
67201
|
+
const response = await model.http.request(target, {
|
|
67202
|
+
method: "POST",
|
|
67203
|
+
headers: { "Content-Type": "application/json", ...headers, ...model.profile.headers },
|
|
67204
|
+
body: JSON.stringify(payload),
|
|
67205
|
+
signal: controller.signal,
|
|
67206
|
+
...tls2 !== void 0 ? { tls: tls2 } : {}
|
|
67207
|
+
});
|
|
67208
|
+
return { status: response.status, text: await response.text() };
|
|
67209
|
+
};
|
|
67210
|
+
try {
|
|
67211
|
+
const endpoint = model.endpoint === void 0 || model.endpoint.trim() === "" ? void 0 : model.endpoint.trim();
|
|
67212
|
+
const problem = decisionEndpointProblem(endpoint);
|
|
67213
|
+
if (problem !== void 0)
|
|
67214
|
+
return { ok: false, source: "none", raw: "", error: problem, ms: Date.now() - started };
|
|
67215
|
+
if (endpoint !== "chat" && (endpoint !== void 0 || !CHAT_ONLY.has(base))) {
|
|
67216
|
+
const target = `${base}${endpoint ?? "/systemone"}`;
|
|
67217
|
+
const request2 = systemOneRequest(model.profile.model, question);
|
|
67218
|
+
const answer2 = await post(target, request2.body);
|
|
67219
|
+
if ((answer2.status === 404 || answer2.status === 405) && endpoint === void 0) {
|
|
67220
|
+
CHAT_ONLY.add(base);
|
|
67221
|
+
} else if (answer2.status >= 400) {
|
|
67222
|
+
return { ok: false, source: "none", raw: answer2.text.slice(0, 2e3), error: `The decision model at ${target} answered HTTP ${String(answer2.status)}.`, ms: Date.now() - started };
|
|
67223
|
+
} else {
|
|
67224
|
+
let parsed2;
|
|
67225
|
+
try {
|
|
67226
|
+
parsed2 = JSON.parse(answer2.text);
|
|
67227
|
+
} catch {
|
|
67228
|
+
return { ok: false, source: "none", raw: answer2.text.slice(0, 2e3), error: "The decision model did not answer with JSON.", ms: Date.now() - started };
|
|
67229
|
+
}
|
|
67230
|
+
return readSystemOne(parsed2, question, request2.keys, Date.now() - started) ?? {
|
|
67231
|
+
ok: false,
|
|
67232
|
+
source: "none",
|
|
67233
|
+
raw: answer2.text.slice(0, 2e3),
|
|
67234
|
+
error: `${target} answered, but not with a structured_decision.`,
|
|
67235
|
+
ms: Date.now() - started
|
|
67236
|
+
};
|
|
67237
|
+
}
|
|
67238
|
+
}
|
|
67239
|
+
let answer = await send2();
|
|
67240
|
+
if (answer.status >= 400 && answer.status < 500 && answer.status !== 401 && body["logprobs"] !== void 0 && /logprob/i.test(answer.text)) {
|
|
67241
|
+
NO_LOGPROBS.add(base);
|
|
67242
|
+
delete body["logprobs"];
|
|
67243
|
+
delete body["top_logprobs"];
|
|
67244
|
+
answer = await send2();
|
|
67245
|
+
}
|
|
67246
|
+
if (answer.status === 401 && model.auth.onUnauthorized !== void 0 && await model.auth.onUnauthorized())
|
|
67247
|
+
answer = await send2();
|
|
67248
|
+
if (answer.status >= 400) {
|
|
67249
|
+
return { ok: false, source: "none", raw: answer.text.slice(0, 2e3), error: `The decision model at ${url2} answered HTTP ${String(answer.status)}.`, ms: Date.now() - started };
|
|
67250
|
+
}
|
|
67251
|
+
let parsed;
|
|
67252
|
+
try {
|
|
67253
|
+
parsed = JSON.parse(answer.text);
|
|
67254
|
+
} catch {
|
|
67255
|
+
return { ok: false, source: "none", raw: answer.text.slice(0, 2e3), error: "The decision model did not answer with JSON.", ms: Date.now() - started };
|
|
67256
|
+
}
|
|
67257
|
+
return readDecision(parsed, question, Date.now() - started);
|
|
67258
|
+
} catch (error51) {
|
|
67259
|
+
const reason = controller.signal.aborted && options.signal?.aborted !== true ? "it did not answer in time" : error51 instanceof Error ? error51.message : String(error51);
|
|
67260
|
+
return { ok: false, source: "none", raw: "", error: `Could not ask the decision model: ${reason}.`, ms: Date.now() - started };
|
|
67261
|
+
} finally {
|
|
67262
|
+
clearTimeout(timer);
|
|
67263
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
67264
|
+
}
|
|
67265
|
+
}
|
|
67266
|
+
var DEFAULT_ROUTE_THRESHOLD = 0.75;
|
|
67267
|
+
var DEFAULT_LOOP_THRESHOLD = 0.8;
|
|
67268
|
+
function loopVerdict(decision, threshold) {
|
|
67269
|
+
const yes = decision.probabilities?.["yes"];
|
|
67270
|
+
if (!decision.ok || yes === void 0)
|
|
67271
|
+
return void 0;
|
|
67272
|
+
if (yes >= threshold)
|
|
67273
|
+
return { met: true, detail: `decision model ${yes.toFixed(2)}` };
|
|
67274
|
+
if (yes <= 1 - threshold)
|
|
67275
|
+
return { met: false, detail: `decision model ${yes.toFixed(2)} that it is met` };
|
|
67276
|
+
return void 0;
|
|
67277
|
+
}
|
|
67278
|
+
|
|
67279
|
+
// ../../packages/core/dist/decision/route.js
|
|
67280
|
+
var MAIN_OPTION = "@main";
|
|
67281
|
+
function routeQuestion(text2, team, recent) {
|
|
67282
|
+
const context = recent.filter((message6) => (message6.role === "user" || message6.role === "assistant") && typeof message6.content === "string").slice(-2).map((message6) => `${message6.role === "user" ? "User" : "Assistant"}: ${String(message6.content).slice(0, 500)}`);
|
|
67283
|
+
return {
|
|
67284
|
+
kind: "choice",
|
|
67285
|
+
question: "Who should handle the latest request from the user?",
|
|
67286
|
+
options: [
|
|
67287
|
+
{ id: MAIN_OPTION, label: "The main assistant", description: "questions, small changes, and anything no specialist below is better at" },
|
|
67288
|
+
...team.filter((agent) => agent.available).map((agent) => ({ id: agent.role, label: agent.name, description: agent.summary }))
|
|
67289
|
+
],
|
|
67290
|
+
inputs: {
|
|
67291
|
+
text: `${context.length > 0 ? `Earlier in the chat:
|
|
67292
|
+
${context.join("\n")}
|
|
67293
|
+
|
|
67294
|
+
` : ""}Latest request:
|
|
67295
|
+
${text2.slice(0, 6e3)}`
|
|
67296
|
+
}
|
|
67297
|
+
};
|
|
67298
|
+
}
|
|
67299
|
+
function routedRole(decision, threshold) {
|
|
67300
|
+
const best = decision.best;
|
|
67301
|
+
if (!decision.ok || best === void 0 || best.id === MAIN_OPTION || best.probability < threshold)
|
|
67302
|
+
return void 0;
|
|
67303
|
+
return { role: best.id, probability: best.probability };
|
|
67304
|
+
}
|
|
67305
|
+
function describeRoute(role, name, probability) {
|
|
67306
|
+
return `The decision model sent this request to \`${role}\` (${name}, probability ${probability.toFixed(2)}). Consult it with \`ask_agent\` before you answer: put the code, error or output the request is about in the question, and say plainly in your reply what came back and whether you agree. If the user then says to answer it yourself, do so.`;
|
|
67307
|
+
}
|
|
67308
|
+
|
|
67309
|
+
// ../../packages/core/dist/decision/firstPass.js
|
|
67310
|
+
var DEFAULT_FIRST_PASS_THRESHOLD = 0.85;
|
|
67311
|
+
var FIRST_PASS_QUESTION = "Is the assistant's latest step grounded in the tool results shown (no claim they do not support), and still working on the user's request?";
|
|
67312
|
+
var clip = (text2, limit) => text2.length > limit ? `${text2.slice(0, limit)}\u2026` : text2;
|
|
67313
|
+
function describeStep(step, goal) {
|
|
67314
|
+
const lines2 = [`User's request: ${clip(goal, 2e3)}`, "", "Latest step:"];
|
|
67315
|
+
for (const event of step) {
|
|
67316
|
+
switch (event.kind) {
|
|
67317
|
+
case "reasoning":
|
|
67318
|
+
lines2.push(`Thinking: ${clip(event.text, 2e3)}`);
|
|
67319
|
+
break;
|
|
67320
|
+
case "assistant":
|
|
67321
|
+
lines2.push(`Assistant said: ${clip(event.text, 3e3)}`);
|
|
67322
|
+
break;
|
|
67323
|
+
case "toolCall":
|
|
67324
|
+
lines2.push(`Called ${event.tool}: ${clip(event.args, 1e3)}`);
|
|
67325
|
+
break;
|
|
67326
|
+
case "toolResult":
|
|
67327
|
+
lines2.push(`${event.tool} returned${event.ok ? "" : " an error"}: ${clip(event.text, 3e3)}`);
|
|
67328
|
+
break;
|
|
67329
|
+
case "refused":
|
|
67330
|
+
lines2.push(`${event.tool} was refused: ${clip(event.reason, 500)}`);
|
|
67331
|
+
break;
|
|
67332
|
+
case "approval":
|
|
67333
|
+
lines2.push(`The user ${event.decision} ${event.tool}.`);
|
|
67334
|
+
break;
|
|
67335
|
+
case "turnEnd":
|
|
67336
|
+
lines2.push(`The reply ended (${event.ending}).`);
|
|
67337
|
+
break;
|
|
67338
|
+
default:
|
|
67339
|
+
break;
|
|
67340
|
+
}
|
|
67341
|
+
}
|
|
67342
|
+
return lines2.join("\n");
|
|
67343
|
+
}
|
|
67344
|
+
|
|
67345
|
+
// ../../packages/core/dist/decision/more.js
|
|
67346
|
+
var DEFAULT_HANDOVER_THRESHOLD = 0.4;
|
|
67347
|
+
function handoverQuestion(contract, answer) {
|
|
67348
|
+
return {
|
|
67349
|
+
kind: "score",
|
|
67350
|
+
question: `How completely does this answer give what was agreed to be handed over: "${contract.trim()}"?`,
|
|
67351
|
+
inputs: { text: answer.slice(0, 16e3) }
|
|
67352
|
+
};
|
|
67353
|
+
}
|
|
67354
|
+
function newWorkQuestion(previous, next) {
|
|
67355
|
+
return {
|
|
67356
|
+
kind: "yesno",
|
|
67357
|
+
question: "Is the new plan for a different piece of work, rather than a revision of the old plan for the same work?",
|
|
67358
|
+
inputs: { text: `Old plan:
|
|
67359
|
+
${previous.slice(0, 6e3)}
|
|
67360
|
+
|
|
67361
|
+
New plan:
|
|
67362
|
+
${next.slice(0, 6e3)}` }
|
|
67363
|
+
};
|
|
67364
|
+
}
|
|
67365
|
+
function roleSuggestion(decision, asked, threshold, nameOf2) {
|
|
67366
|
+
const best = decision.best;
|
|
67367
|
+
if (!decision.ok || best === void 0 || best.id === MAIN_OPTION || best.id === asked || best.probability < threshold)
|
|
67368
|
+
return void 0;
|
|
67369
|
+
return `[Decision model] ${nameOf2(best.id)} (\`${best.id}\`) may fit this question better than ${nameOf2(asked)} (probability ${best.probability.toFixed(2)}). Consult it too if the answer above falls short.`;
|
|
67370
|
+
}
|
|
67371
|
+
function triageQuestion(context) {
|
|
67372
|
+
return {
|
|
67373
|
+
kind: "yesno",
|
|
67374
|
+
question: "Does this monitoring alert need a person to act now, rather than being looked at later?",
|
|
67375
|
+
inputs: { json: context }
|
|
67376
|
+
};
|
|
67377
|
+
}
|
|
67378
|
+
function isSkillToolPicks(value) {
|
|
67379
|
+
return value === "skills" || value === "tools" || value === "both";
|
|
67380
|
+
}
|
|
67381
|
+
function withRecentChat(text2, recent) {
|
|
67382
|
+
const context = recent.filter((message6) => (message6.role === "user" || message6.role === "assistant") && typeof message6.content === "string").slice(-2).map((message6) => `${message6.role === "user" ? "User" : "Assistant"}: ${String(message6.content).slice(0, 500)}`);
|
|
67383
|
+
return `${context.length > 0 ? `Earlier in the chat:
|
|
67384
|
+
${context.join("\n")}
|
|
67385
|
+
|
|
67386
|
+
` : ""}Latest request:
|
|
67387
|
+
${text2.slice(0, 8e3)}`;
|
|
67388
|
+
}
|
|
67389
|
+
var NOTHING_OPTION = "@nothing";
|
|
67390
|
+
var DEFAULT_SUGGEST_THRESHOLD = 0.25;
|
|
67391
|
+
var MAX_SUGGESTED = 3;
|
|
67392
|
+
var firstSentence = (text2) => {
|
|
67393
|
+
const line = text2.split("\n")[0] ?? "";
|
|
67394
|
+
const end = line.search(/\.(\s|$)/);
|
|
67395
|
+
const sentence = end > 0 ? line.slice(0, end + 1) : line;
|
|
67396
|
+
return sentence.length > 160 ? `${sentence.slice(0, 160)}\u2026` : sentence;
|
|
67397
|
+
};
|
|
67398
|
+
function skillQuestion(text2, skills) {
|
|
67399
|
+
return {
|
|
67400
|
+
kind: "choice",
|
|
67401
|
+
question: "Which skill (written know-how) does this request need most?",
|
|
67402
|
+
options: [{ id: NOTHING_OPTION, label: "Nothing in particular", description: "none of these skills is about this request" }, ...skills.slice(0, 250).map((skill) => ({ id: skill.name, label: skill.name, description: firstSentence(skill.description) }))],
|
|
67403
|
+
inputs: { text: text2 }
|
|
67404
|
+
};
|
|
67405
|
+
}
|
|
67406
|
+
function toolQuestion(text2, tools) {
|
|
67407
|
+
return {
|
|
67408
|
+
kind: "choice",
|
|
67409
|
+
question: "Which tool does this request need most?",
|
|
67410
|
+
options: [{ id: NOTHING_OPTION, label: "Nothing in particular", description: "no tool here is clearly the one for this" }, ...tools.slice(0, 250).map((tool) => ({ id: tool.name, label: tool.name, description: firstSentence(tool.description) }))],
|
|
67411
|
+
inputs: { text: text2 }
|
|
67412
|
+
};
|
|
67413
|
+
}
|
|
67414
|
+
function picked(decision, threshold = DEFAULT_SUGGEST_THRESHOLD) {
|
|
67415
|
+
if (decision === void 0 || !decision.ok || decision.probabilities === void 0)
|
|
67416
|
+
return [];
|
|
67417
|
+
if (decision.best?.id === NOTHING_OPTION)
|
|
67418
|
+
return [];
|
|
67419
|
+
return Object.entries(decision.probabilities).filter(([id, p]) => id !== NOTHING_OPTION && p >= threshold).sort((a, b) => b[1] - a[1]).slice(0, MAX_SUGGESTED).map(([id, probability]) => ({ id, probability }));
|
|
67420
|
+
}
|
|
67421
|
+
function describeSuggestions(skills, tools) {
|
|
67422
|
+
if (skills.length === 0 && tools.length === 0)
|
|
67423
|
+
return "";
|
|
67424
|
+
const parts = [];
|
|
67425
|
+
for (const skill of skills)
|
|
67426
|
+
parts.push(`skill \`${skill.id}\` (${skill.probability.toFixed(2)})${skill.filePath !== void 0 ? ` - read ${skill.filePath} first` : ""}`);
|
|
67427
|
+
for (const tool of tools)
|
|
67428
|
+
parts.push(`tool \`${tool.id}\` (${tool.probability.toFixed(2)})${tool.hidden ? " - its parameters come from search_docs, then call it through call_tool" : ""}`);
|
|
67429
|
+
return `[Decision model] For this request these look right: ${parts.join("; ")}. Use them if they fit; this is advice, not an instruction.`;
|
|
67430
|
+
}
|
|
67431
|
+
|
|
66744
67432
|
// ../../packages/core/dist/agent/resume.js
|
|
66745
67433
|
var RESUME_PROMPT = "[Light Code] The agent process stopped unexpectedly in the middle of this task and has been restarted. Continue the task from where it stopped. Before repeating a step, check whether it already took effect - a command may have finished or been cut off, and a file may already be written - and do not ask me to confirm the task again.";
|
|
66746
67434
|
var MAX_CRASH_RESUMES = 3;
|
|
@@ -68690,7 +69378,7 @@ function summaryFromText(name, head) {
|
|
|
68690
69378
|
return void 0;
|
|
68691
69379
|
const separator = extension === "tsv" ? " " : header2.split(";").length > header2.split(",").length ? ";" : ",";
|
|
68692
69380
|
const columns = header2.split(separator).map((cell) => cell.trim().replace(/^"|"$/g, "")).filter((cell) => cell !== "");
|
|
68693
|
-
return
|
|
69381
|
+
return clip2(`${String(columns.length)} columns: ${columns.join(", ")}`);
|
|
68694
69382
|
}
|
|
68695
69383
|
if (extension === "json") {
|
|
68696
69384
|
try {
|
|
@@ -68698,13 +69386,13 @@ function summaryFromText(name, head) {
|
|
|
68698
69386
|
if (Array.isArray(parsed))
|
|
68699
69387
|
return `A list of ${String(parsed.length)} item(s)`;
|
|
68700
69388
|
if (parsed !== null && typeof parsed === "object")
|
|
68701
|
-
return
|
|
69389
|
+
return clip2(`Keys: ${Object.keys(parsed).join(", ")}`);
|
|
68702
69390
|
} catch {
|
|
68703
69391
|
}
|
|
68704
69392
|
}
|
|
68705
69393
|
const heading = lines2.find((line) => /^#{1,3}\s+\S/.test(line));
|
|
68706
69394
|
if (heading !== void 0 && (kindOf2(name) === "document" || extension === "txt"))
|
|
68707
|
-
return
|
|
69395
|
+
return clip2(heading.replace(/^#+\s+/, ""));
|
|
68708
69396
|
for (const raw of lines2) {
|
|
68709
69397
|
const line = raw.trim();
|
|
68710
69398
|
if (line === "" || line.startsWith("#!") || /^[-=*_]{3,}$/.test(line) || /^(import|from|using|package|require|#include|<\?xml|<!doctype)\b/i.test(line))
|
|
@@ -68712,11 +69400,11 @@ function summaryFromText(name, head) {
|
|
|
68712
69400
|
const text2 = line.replace(/^(\/\/+|#+|--|\/\*+|\*+|"""|'''|<!--|rem\s|;+)\s*/i, "").replace(/(\*\/|-->|"""|''')$/, "").trim();
|
|
68713
69401
|
if (text2.length < 3)
|
|
68714
69402
|
continue;
|
|
68715
|
-
return
|
|
69403
|
+
return clip2(text2);
|
|
68716
69404
|
}
|
|
68717
69405
|
return void 0;
|
|
68718
69406
|
}
|
|
68719
|
-
function
|
|
69407
|
+
function clip2(text2) {
|
|
68720
69408
|
const flat = text2.replace(/\s+/g, " ").trim();
|
|
68721
69409
|
return flat.length > SUMMARY_CHARS ? `${flat.slice(0, SUMMARY_CHARS - 1)}\u2026` : flat;
|
|
68722
69410
|
}
|
|
@@ -82236,11 +82924,11 @@ function createConfluenceReadPageTool(options) {
|
|
|
82236
82924
|
}
|
|
82237
82925
|
const attachments = await client.listAttachments(page.id).catch(() => []);
|
|
82238
82926
|
const wanted = params3.imageNames !== void 0 ? new Set(params3.imageNames.map((name) => name.toLowerCase())) : params3.images === true ? void 0 : /* @__PURE__ */ new Set();
|
|
82239
|
-
const
|
|
82927
|
+
const picked2 = attachments.filter((attachment) => attachment.mediaType.startsWith("image/") && (wanted === void 0 || wanted.has(attachment.name.toLowerCase())));
|
|
82240
82928
|
const images = [];
|
|
82241
82929
|
const svgText = [];
|
|
82242
82930
|
const skipped2 = [];
|
|
82243
|
-
for (const attachment of
|
|
82931
|
+
for (const attachment of picked2) {
|
|
82244
82932
|
if (images.length >= MAX_IMAGES2) {
|
|
82245
82933
|
skipped2.push(`${attachment.name} (more than ${String(MAX_IMAGES2)} images \u2014 ask for it by name)`);
|
|
82246
82934
|
continue;
|
|
@@ -83772,7 +84460,7 @@ function pendingSteeringFile(storageDir, workspaceRoot) {
|
|
|
83772
84460
|
return import_node_path51.default.join(storageDir, "pending-chat", `${key4}.json`);
|
|
83773
84461
|
}
|
|
83774
84462
|
async function writePendingSteering(file2, steering) {
|
|
83775
|
-
if (steering.plan === void 0 && steering.strategy === void 0) {
|
|
84463
|
+
if (steering.plan === void 0 && steering.strategy === void 0 && steering.skillToolPicks === void 0) {
|
|
83776
84464
|
await clearPendingSteering(file2);
|
|
83777
84465
|
return;
|
|
83778
84466
|
}
|
|
@@ -83794,6 +84482,8 @@ async function readPendingSteering(file2) {
|
|
|
83794
84482
|
const out = {};
|
|
83795
84483
|
if (typeof value["plan"] === "string" && value["plan"].trim().length > 0)
|
|
83796
84484
|
out.plan = value["plan"];
|
|
84485
|
+
if (isSkillToolPicks(value["skillToolPicks"]))
|
|
84486
|
+
out.skillToolPicks = value["skillToolPicks"];
|
|
83797
84487
|
if (value["planProgress"] !== null && typeof value["planProgress"] === "object")
|
|
83798
84488
|
out.planProgress = value["planProgress"];
|
|
83799
84489
|
const strategy = strategySchema.safeParse(value["strategy"]);
|
|
@@ -85982,6 +86672,7 @@ async function readAudit(storageDir, workspace, query) {
|
|
|
85982
86672
|
}
|
|
85983
86673
|
|
|
85984
86674
|
// ../../packages/core/dist/observers/hub.js
|
|
86675
|
+
var STEP_ENDS = /* @__PURE__ */ new Set(["toolResult", "assistant", "turnEnd"]);
|
|
85985
86676
|
var NOTIFY_GAP_MS = 2e4;
|
|
85986
86677
|
var INDEX_BATCH = 50;
|
|
85987
86678
|
var INDEX_EVERY_MS = 1e4;
|
|
@@ -86114,11 +86805,49 @@ var ObserverHub = class {
|
|
|
86114
86805
|
this.alert(signal.level, signal.message, "rules", signal.notify);
|
|
86115
86806
|
}
|
|
86116
86807
|
}
|
|
86117
|
-
if (guard.enabled)
|
|
86118
|
-
this.
|
|
86808
|
+
if (guard.enabled && event.kind !== "decision")
|
|
86809
|
+
this.toGuard(event);
|
|
86119
86810
|
if (event.kind === "turnEnd")
|
|
86120
86811
|
this.auditor?.flush();
|
|
86121
86812
|
}
|
|
86813
|
+
/** Events since the Anti Hallucinator's last step, and the request it is checking against. */
|
|
86814
|
+
guardStep = [];
|
|
86815
|
+
guardGoal = "";
|
|
86816
|
+
/** Keeps the guard's events in order while a first pass is being asked. */
|
|
86817
|
+
guardChain = Promise.resolve();
|
|
86818
|
+
/** Steps the first pass let through without a full review, and steps reviewed, since the session started. */
|
|
86819
|
+
firstPassCounts = { passed: 0, reviewed: 0 };
|
|
86820
|
+
/**
|
|
86821
|
+
* To the Anti Hallucinator, with the decision model's first pass where there is one: a step it is sure of is still
|
|
86822
|
+
* sent - the Anti Hallucinator keeps its whole context - but marked `quiet`, so it is reviewed with the next step
|
|
86823
|
+
* that needs one rather than on its own. A helper that predates `quiet` reviews it anyway, as before.
|
|
86824
|
+
*/
|
|
86825
|
+
toGuard(event) {
|
|
86826
|
+
const firstPass = this.deps.firstPass;
|
|
86827
|
+
if (firstPass === void 0) {
|
|
86828
|
+
this.guard?.send(event);
|
|
86829
|
+
return;
|
|
86830
|
+
}
|
|
86831
|
+
this.guardChain = this.guardChain.then(async () => {
|
|
86832
|
+
if (event.kind === "turnStart") {
|
|
86833
|
+
this.guardGoal = event.text;
|
|
86834
|
+
this.guardStep = [];
|
|
86835
|
+
}
|
|
86836
|
+
this.guardStep.push(event);
|
|
86837
|
+
if (!STEP_ENDS.has(event.kind)) {
|
|
86838
|
+
this.guard?.send(event);
|
|
86839
|
+
return;
|
|
86840
|
+
}
|
|
86841
|
+
const step = this.guardStep;
|
|
86842
|
+
this.guardStep = [];
|
|
86843
|
+
const sure = await firstPass(step, this.guardGoal).catch(() => void 0);
|
|
86844
|
+
if (sure === true)
|
|
86845
|
+
this.firstPassCounts.passed += 1;
|
|
86846
|
+
else
|
|
86847
|
+
this.firstPassCounts.reviewed += 1;
|
|
86848
|
+
this.guard?.send(event, sure === true);
|
|
86849
|
+
});
|
|
86850
|
+
}
|
|
86122
86851
|
/** Notes for the main agent, taken once: they join its conversation at the next step. */
|
|
86123
86852
|
takeNotes() {
|
|
86124
86853
|
const taken = this.pendingNotes;
|
|
@@ -86273,6 +87002,8 @@ function redactEvent(event, secrets) {
|
|
|
86273
87002
|
return { ...event, text: r(event.text) };
|
|
86274
87003
|
case "turnEnd":
|
|
86275
87004
|
return event.error === void 0 ? event : { ...event, error: r(event.error) };
|
|
87005
|
+
case "decision":
|
|
87006
|
+
return { ...event, question: r(event.question), outcome: r(event.outcome) };
|
|
86276
87007
|
}
|
|
86277
87008
|
}
|
|
86278
87009
|
|
|
@@ -86321,11 +87052,13 @@ ${this.recent.map((r) => `- ${r}`).join("\n")}`);
|
|
|
86321
87052
|
this.stopped = false;
|
|
86322
87053
|
this.launch(void 0);
|
|
86323
87054
|
}
|
|
86324
|
-
|
|
87055
|
+
/** `quiet`: the decision model's first pass was sure of this step - kept in context, reviewed with the next one. */
|
|
87056
|
+
send(event, quiet = false) {
|
|
86325
87057
|
if (this.stopped)
|
|
86326
87058
|
return;
|
|
86327
|
-
|
|
86328
|
-
|
|
87059
|
+
const sent = quiet ? { ...event, quiet: true } : event;
|
|
87060
|
+
if (!this.write({ type: "event", event: sent })) {
|
|
87061
|
+
this.buffered.push(sent);
|
|
86329
87062
|
if (this.buffered.length > MAX_BUFFERED)
|
|
86330
87063
|
this.buffered.shift();
|
|
86331
87064
|
}
|
|
@@ -86552,6 +87285,9 @@ function auditRow(record2) {
|
|
|
86552
87285
|
row["ending"] = e.ending;
|
|
86553
87286
|
if (e.error !== void 0)
|
|
86554
87287
|
row["text"] = e.error;
|
|
87288
|
+
} else if (e.kind === "decision") {
|
|
87289
|
+
row["decision"] = e.outcome;
|
|
87290
|
+
row["text"] = `${e.purpose}: ${e.question}${e.probabilities !== void 0 ? ` ${JSON.stringify(e.probabilities)}` : ""}`;
|
|
86555
87291
|
} else
|
|
86556
87292
|
row["text"] = e.text;
|
|
86557
87293
|
if (e.kind === "turnStart") {
|
|
@@ -88309,10 +89045,23 @@ ${preview.text}` } : {}
|
|
|
88309
89045
|
function postPlanProgress() {
|
|
88310
89046
|
post({ type: "planProgress", checkpoints: planViews() });
|
|
88311
89047
|
}
|
|
89048
|
+
async function newWorkByDecisionModel(previous, next) {
|
|
89049
|
+
if (cachedDecision?.profileId === void 0 || cachedDecision.newTopics === false)
|
|
89050
|
+
return false;
|
|
89051
|
+
if (previous === void 0 || next === void 0 || previous === next)
|
|
89052
|
+
return false;
|
|
89053
|
+
const threshold = cachedDecision.loopThreshold ?? DEFAULT_LOOP_THRESHOLD;
|
|
89054
|
+
const decision = await askDecisionModel("New topic", newWorkQuestion(previous, next), (d) => {
|
|
89055
|
+
const yes2 = d.probabilities?.["yes"];
|
|
89056
|
+
return yes2 !== void 0 && yes2 >= threshold ? "new work: loops start again" : "a revision: loops kept";
|
|
89057
|
+
});
|
|
89058
|
+
const yes = decision?.probabilities?.["yes"];
|
|
89059
|
+
return decision?.ok === true && yes !== void 0 && yes >= threshold;
|
|
89060
|
+
}
|
|
88312
89061
|
async function applyPlan(next) {
|
|
88313
89062
|
const trimmed = next?.slice(0, PLAN_LIMIT).trim();
|
|
88314
89063
|
const nextPlan = trimmed !== void 0 && trimmed.length > 0 ? trimmed : void 0;
|
|
88315
|
-
if (activeStrategy !== void 0 && startsNewWork(activePlan, activePlanProgress, nextPlan)) {
|
|
89064
|
+
if (activeStrategy !== void 0 && (startsNewWork(activePlan, activePlanProgress, nextPlan) || await newWorkByDecisionModel(activePlan, nextPlan))) {
|
|
88316
89065
|
strategyProgress = {};
|
|
88317
89066
|
strategyLastRole = void 0;
|
|
88318
89067
|
resetHandOvers();
|
|
@@ -88453,6 +89202,10 @@ ${preview.text}` } : {}
|
|
|
88453
89202
|
let cachedAutoHandoff = false;
|
|
88454
89203
|
let cachedUnlimitedSteps = false;
|
|
88455
89204
|
let cachedComposerCompletion = false;
|
|
89205
|
+
let cachedDecision;
|
|
89206
|
+
let cachedDecisionLabel;
|
|
89207
|
+
let turnModeId;
|
|
89208
|
+
let chatPicks;
|
|
88456
89209
|
let completionAbort;
|
|
88457
89210
|
let handoffAtLimit = false;
|
|
88458
89211
|
let cachedStallSeconds = DEFAULT_STALL_SECONDS;
|
|
@@ -88819,6 +89572,8 @@ ${preview.text}` } : {}
|
|
|
88819
89572
|
cachedAutoHandoff = config2.autoHandoff === true;
|
|
88820
89573
|
cachedUnlimitedSteps = config2.unlimitedSteps === true;
|
|
88821
89574
|
cachedComposerCompletion = config2.composerCompletion === true;
|
|
89575
|
+
cachedDecision = config2.decisionModel;
|
|
89576
|
+
cachedDecisionLabel = decisionModelFrom(config2)?.label;
|
|
88822
89577
|
cachedStallSeconds = config2.connection?.stallSeconds ?? DEFAULT_STALL_SECONDS;
|
|
88823
89578
|
cachedRetries = config2.connection?.retries ?? DEFAULT_RETRIES;
|
|
88824
89579
|
cachedAccentColor = config2.ui?.accentColor ?? "#22C55E";
|
|
@@ -88914,6 +89669,7 @@ ${preview.text}` } : {}
|
|
|
88914
89669
|
autoHandoff: cachedAutoHandoff,
|
|
88915
89670
|
unlimitedSteps: cachedUnlimitedSteps,
|
|
88916
89671
|
composerCompletion: cachedComposerCompletion,
|
|
89672
|
+
...cachedDecisionLabel !== void 0 ? { decisionLabel: cachedDecisionLabel } : {},
|
|
88917
89673
|
stallSeconds: cachedStallSeconds,
|
|
88918
89674
|
retries: cachedRetries,
|
|
88919
89675
|
accentColor: cachedAccentColor,
|
|
@@ -89065,7 +89821,11 @@ ${preview.text}` } : {}
|
|
|
89065
89821
|
mcpStartingSince.set(name, now);
|
|
89066
89822
|
const waiting = [
|
|
89067
89823
|
...[...mcpStartingSince].map(([name, since2]) => ({ label: `MCP server "${name}" starting`, since: since2 })),
|
|
89068
|
-
...[...startupWaits].map(([label, since2]) =>
|
|
89824
|
+
...[...startupWaits].map(([label, since2]) => {
|
|
89825
|
+
const full = startupDetails.has(label) ? `${label} - ${startupDetails.get(label) ?? ""}` : label;
|
|
89826
|
+
const short = shortenPaths(full);
|
|
89827
|
+
return { label: short, since: since2, ...short !== full ? { full } : {} };
|
|
89828
|
+
})
|
|
89069
89829
|
].sort((a, b) => a.since - b.since);
|
|
89070
89830
|
const key4 = JSON.stringify(waiting);
|
|
89071
89831
|
if (!force && key4 === lastStartupPosted)
|
|
@@ -89571,7 +90331,6 @@ ${preview.text}` } : {}
|
|
|
89571
90331
|
})
|
|
89572
90332
|
}));
|
|
89573
90333
|
}
|
|
89574
|
-
agentBriefingTools = () => combined.list();
|
|
89575
90334
|
lastToolNames = combined.list().map((tool) => tool.name);
|
|
89576
90335
|
return combined;
|
|
89577
90336
|
}
|
|
@@ -89916,6 +90675,145 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
|
|
|
89916
90675
|
observerAuth.set(profile.id, { key: key4, strategy });
|
|
89917
90676
|
return strategy;
|
|
89918
90677
|
}
|
|
90678
|
+
function decisionModelFrom(config2) {
|
|
90679
|
+
const id = config2.decisionModel?.profileId;
|
|
90680
|
+
if (id === void 0)
|
|
90681
|
+
return void 0;
|
|
90682
|
+
const profile = (config2.profiles ?? []).find((candidate) => candidate.id === id);
|
|
90683
|
+
if (profile === void 0 || profile.wireFormat !== "openai")
|
|
90684
|
+
return void 0;
|
|
90685
|
+
const endpoint = config2.decisionModel?.endpoint;
|
|
90686
|
+
return { model: { profile, http: httpClient, auth: observerStrategy(config2, profile), ...endpoint !== void 0 && endpoint.trim() !== "" ? { endpoint: endpoint.trim() } : {} }, label: profile.label };
|
|
90687
|
+
}
|
|
90688
|
+
async function askDecisionModel(purpose, question, outcome, signal, timeoutMs = 1e4) {
|
|
90689
|
+
const found2 = decisionModelFrom(await loadSettings());
|
|
90690
|
+
if (found2 === void 0)
|
|
90691
|
+
return void 0;
|
|
90692
|
+
const decision = await decide(found2.model, question, { ...signal !== void 0 ? { signal } : {}, timeoutMs });
|
|
90693
|
+
if (!decision.ok)
|
|
90694
|
+
logger.info(`decision model (${purpose}): ${decision.error ?? "no answer"}`);
|
|
90695
|
+
observerHub.event({
|
|
90696
|
+
kind: "decision",
|
|
90697
|
+
at: Date.now(),
|
|
90698
|
+
purpose,
|
|
90699
|
+
question: question.question,
|
|
90700
|
+
outcome: outcome(decision),
|
|
90701
|
+
...decision.probabilities !== void 0 ? { probabilities: decision.probabilities } : {}
|
|
90702
|
+
});
|
|
90703
|
+
return decision;
|
|
90704
|
+
}
|
|
90705
|
+
async function postDecisionModel(error51) {
|
|
90706
|
+
const config2 = await loadSettings();
|
|
90707
|
+
const found2 = decisionModelFrom(config2);
|
|
90708
|
+
post({
|
|
90709
|
+
type: "decisionModel",
|
|
90710
|
+
settings: config2.decisionModel ?? {},
|
|
90711
|
+
profiles: (config2.profiles ?? []).filter((profile) => profile.wireFormat === "openai").map((profile) => ({ id: profile.id, label: profile.label })),
|
|
90712
|
+
...found2 !== void 0 ? { label: found2.label } : {},
|
|
90713
|
+
...error51 !== void 0 ? { error: error51 } : {}
|
|
90714
|
+
});
|
|
90715
|
+
}
|
|
90716
|
+
async function testDecisionModel() {
|
|
90717
|
+
const found2 = decisionModelFrom(await loadSettings());
|
|
90718
|
+
if (found2 === void 0) {
|
|
90719
|
+
post({ type: "decisionModelTest", results: [{ question: "Pick a profile first.", expected: "", ok: false, source: "none", error: "No decision model is set up.", raw: "", ms: 0 }] });
|
|
90720
|
+
return;
|
|
90721
|
+
}
|
|
90722
|
+
const samples = [
|
|
90723
|
+
{ question: { kind: "yesno", question: "Is the number in the input even?", inputs: { text: "42" } }, expected: "yes" },
|
|
90724
|
+
{
|
|
90725
|
+
question: {
|
|
90726
|
+
kind: "choice",
|
|
90727
|
+
question: "Which specialist should handle this request?",
|
|
90728
|
+
options: [
|
|
90729
|
+
{ id: "tester", label: "Tester", description: "writes and runs tests" },
|
|
90730
|
+
{ id: "writer", label: "Writer", description: "writes documentation" },
|
|
90731
|
+
{ id: "dba", label: "Database expert", description: "SQL and schemas" }
|
|
90732
|
+
],
|
|
90733
|
+
inputs: { text: "Write unit tests for the date parser and run them." }
|
|
90734
|
+
},
|
|
90735
|
+
expected: "tester"
|
|
90736
|
+
}
|
|
90737
|
+
];
|
|
90738
|
+
const results = [];
|
|
90739
|
+
for (const sample of samples) {
|
|
90740
|
+
const decision = await decide(found2.model, sample.question, { timeoutMs: 2e4 });
|
|
90741
|
+
results.push({
|
|
90742
|
+
question: `${sample.question.question} (${sample.question.inputs?.text ?? ""})`,
|
|
90743
|
+
expected: sample.expected,
|
|
90744
|
+
ok: decision.ok,
|
|
90745
|
+
source: decision.source,
|
|
90746
|
+
...decision.probabilities !== void 0 ? { probabilities: decision.probabilities } : {},
|
|
90747
|
+
...decision.error !== void 0 ? { error: decision.error } : {},
|
|
90748
|
+
raw: decision.raw,
|
|
90749
|
+
ms: decision.ms
|
|
90750
|
+
});
|
|
90751
|
+
}
|
|
90752
|
+
post({ type: "decisionModelTest", results });
|
|
90753
|
+
}
|
|
90754
|
+
async function routeMessage(text2, signal) {
|
|
90755
|
+
const settings = cachedDecision;
|
|
90756
|
+
if (settings?.profileId === void 0 || settings.routing === false || activeStrategy !== void 0)
|
|
90757
|
+
return void 0;
|
|
90758
|
+
const team = cachedTeam.filter((agent) => agent.available);
|
|
90759
|
+
if (team.length === 0 || text2.trim().length === 0)
|
|
90760
|
+
return void 0;
|
|
90761
|
+
const threshold = settings.routeThreshold ?? DEFAULT_ROUTE_THRESHOLD;
|
|
90762
|
+
const decision = await askDecisionModel("Agent team routing", routeQuestion(text2, team, conversation.toArray()), (d) => {
|
|
90763
|
+
const routed2 = routedRole(d, threshold);
|
|
90764
|
+
if (!d.ok)
|
|
90765
|
+
return `not used: ${d.error ?? "no answer"}`;
|
|
90766
|
+
if (routed2 !== void 0)
|
|
90767
|
+
return `routed to ${routed2.role}`;
|
|
90768
|
+
return `main assistant (best ${d.best?.id ?? "?"} ${(d.best?.probability ?? 0).toFixed(2)}, threshold ${threshold.toFixed(2)})`;
|
|
90769
|
+
}, signal);
|
|
90770
|
+
if (decision === void 0)
|
|
90771
|
+
return void 0;
|
|
90772
|
+
if (!decision.ok) {
|
|
90773
|
+
post({ type: "decisionRoute", note: `The decision model did not answer, so the main assistant decides who helps (${decision.error ?? "no answer"}).` });
|
|
90774
|
+
return void 0;
|
|
90775
|
+
}
|
|
90776
|
+
const routed = routedRole(decision, threshold);
|
|
90777
|
+
if (routed === void 0) {
|
|
90778
|
+
post({ type: "decisionRoute" });
|
|
90779
|
+
return void 0;
|
|
90780
|
+
}
|
|
90781
|
+
const name = team.find((agent) => agent.role === routed.role)?.name ?? routed.role;
|
|
90782
|
+
post({ type: "decisionRoute", role: routed.role, name, probability: routed.probability });
|
|
90783
|
+
return { ...routed, name };
|
|
90784
|
+
}
|
|
90785
|
+
async function judgeLoops(strategy, role, answer, roleName) {
|
|
90786
|
+
const judged = /* @__PURE__ */ new Map();
|
|
90787
|
+
const settings = cachedDecision;
|
|
90788
|
+
if (settings?.profileId === void 0 || settings.judgeLoops === false)
|
|
90789
|
+
return judged;
|
|
90790
|
+
const threshold = settings.loopThreshold ?? DEFAULT_LOOP_THRESHOLD;
|
|
90791
|
+
await Promise.all(strategy.edges.map(async (edge) => {
|
|
90792
|
+
if (edge.twoWay !== true || edge.until === void 0 || edge.until.trim().length === 0)
|
|
90793
|
+
return;
|
|
90794
|
+
const from = strategy.nodes.find((node) => node.id === edge.from);
|
|
90795
|
+
const to = strategy.nodes.find((node) => node.id === edge.to);
|
|
90796
|
+
if (from === void 0 || to === void 0 || to.role !== role || from.role === role)
|
|
90797
|
+
return;
|
|
90798
|
+
const work = latestStrategyAnswer(from.role) ?? "";
|
|
90799
|
+
const decision = await askDecisionModel(`Strategy loop ${roleName(from.role)} \u21C4 ${roleName(to.role)}`, {
|
|
90800
|
+
kind: "yesno",
|
|
90801
|
+
question: `Is this condition met: "${edge.until}"?`,
|
|
90802
|
+
inputs: { text: `Work handed in by ${roleName(from.role)}:
|
|
90803
|
+
${work.slice(0, 12e3)}
|
|
90804
|
+
|
|
90805
|
+
Review by ${roleName(to.role)}:
|
|
90806
|
+
${answer.slice(0, 12e3)}` }
|
|
90807
|
+
}, (d) => {
|
|
90808
|
+
const verdict2 = loopVerdict(d, threshold);
|
|
90809
|
+
return verdict2 === void 0 ? `left to the wording of ${roleName(to.role)}` : verdict2.met ? "met" : "not met";
|
|
90810
|
+
});
|
|
90811
|
+
const verdict = decision === void 0 ? void 0 : loopVerdict(decision, threshold);
|
|
90812
|
+
if (verdict !== void 0)
|
|
90813
|
+
judged.set(edge.id, verdict);
|
|
90814
|
+
}));
|
|
90815
|
+
return judged;
|
|
90816
|
+
}
|
|
89919
90817
|
async function observerTls(strategy) {
|
|
89920
90818
|
const tls2 = await strategy.tls?.();
|
|
89921
90819
|
if (tls2 === void 0)
|
|
@@ -90035,8 +90933,19 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
|
|
|
90035
90933
|
observersPostTimer.unref?.();
|
|
90036
90934
|
},
|
|
90037
90935
|
index: () => observerIndex,
|
|
90038
|
-
startAgent: startObserver
|
|
90936
|
+
startAgent: startObserver,
|
|
90937
|
+
// With a decision model (Settings → Agents) and its first pass on: steps it is sure of wait for the next review.
|
|
90938
|
+
firstPass: (step, goal) => antiHallucinatorFirstPass(step, goal)
|
|
90039
90939
|
});
|
|
90940
|
+
async function antiHallucinatorFirstPass(step, goal) {
|
|
90941
|
+
const settings = cachedDecision;
|
|
90942
|
+
if (settings?.profileId === void 0 || settings.firstPass === false)
|
|
90943
|
+
return void 0;
|
|
90944
|
+
const threshold = settings.firstPassThreshold ?? DEFAULT_FIRST_PASS_THRESHOLD;
|
|
90945
|
+
const decision = await askDecisionModel("Anti Hallucinator first pass", { kind: "yesno", question: FIRST_PASS_QUESTION, inputs: { text: describeStep(step, goal) } }, (d) => d.probabilities?.["yes"] !== void 0 && d.probabilities["yes"] >= threshold ? "grounded: review waits" : "reviewed");
|
|
90946
|
+
const yes = decision?.probabilities?.["yes"];
|
|
90947
|
+
return decision?.ok === true && yes !== void 0 ? yes >= threshold : void 0;
|
|
90948
|
+
}
|
|
90040
90949
|
let observerKey = "";
|
|
90041
90950
|
let observerModelKey = "";
|
|
90042
90951
|
let auditPruned = false;
|
|
@@ -90451,6 +91360,8 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
|
|
|
90451
91360
|
...strategyLastRole !== void 0 ? { current: { role: strategyLastRole, running: strategyRunning.has(strategyLastRole) } } : {},
|
|
90452
91361
|
runningRoles: [...strategyRunning],
|
|
90453
91362
|
exchanges: strategyExchanges,
|
|
91363
|
+
...cachedDecision?.profileId !== void 0 ? { decisionModel: true } : {},
|
|
91364
|
+
...chatPicks !== void 0 ? { skillToolPicks: chatPicks } : {},
|
|
90454
91365
|
problems: activeStrategy !== void 0 ? strategyProblems(activeStrategy, new Set(roles), assigned) : [],
|
|
90455
91366
|
roles: roles.map((role) => {
|
|
90456
91367
|
const info = roleInfo(role, cachedAgentDefinitions);
|
|
@@ -90566,7 +91477,8 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
|
|
|
90566
91477
|
if (pending !== void 0 && backgroundRun !== true) {
|
|
90567
91478
|
await writePendingSteering(pending, {
|
|
90568
91479
|
...activePlan !== void 0 ? { plan: activePlan, planProgress: activePlanProgress } : {},
|
|
90569
|
-
...activeStrategy !== void 0 ? { strategy: activeStrategy, strategyProgress, strategyExchanges } : {}
|
|
91480
|
+
...activeStrategy !== void 0 ? { strategy: activeStrategy, strategyProgress, strategyExchanges } : {},
|
|
91481
|
+
...chatPicks !== void 0 ? { skillToolPicks: chatPicks } : {}
|
|
90570
91482
|
}).catch((error51) => logger.warn(`Could not keep this chat's plan and strategy: ${describeFailure2(error51, true)}`));
|
|
90571
91483
|
}
|
|
90572
91484
|
return;
|
|
@@ -90590,7 +91502,8 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
|
|
|
90590
91502
|
...activePlan !== void 0 && activePlan.trim().length > 0 ? { plan: activePlan } : {},
|
|
90591
91503
|
...Object.keys(activePlanProgress).length > 0 ? { planProgress: activePlanProgress } : {},
|
|
90592
91504
|
// The strategy this chat follows and where its loops stand, restored with it like the plan.
|
|
90593
|
-
...activeStrategy !== void 0 ? { strategy: activeStrategy, strategyProgress, strategyExchanges } : {}
|
|
91505
|
+
...activeStrategy !== void 0 ? { strategy: activeStrategy, strategyProgress, strategyExchanges } : {},
|
|
91506
|
+
...chatPicks !== void 0 ? { skillToolPicks: chatPicks } : {}
|
|
90594
91507
|
};
|
|
90595
91508
|
try {
|
|
90596
91509
|
await taskStore.save(redactTask(task, await knownSecretValues()));
|
|
@@ -90642,6 +91555,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
|
|
|
90642
91555
|
activePlanProgress = pruneProgress(activePlan, source.planProgress);
|
|
90643
91556
|
activeStrategy = source.strategy;
|
|
90644
91557
|
strategyProgress = source.strategyProgress ?? {};
|
|
91558
|
+
chatPicks = source.skillToolPicks;
|
|
90645
91559
|
strategyExchanges = source.strategyExchanges ?? [];
|
|
90646
91560
|
strategyLastRole = void 0;
|
|
90647
91561
|
resetHandOvers(0);
|
|
@@ -90651,6 +91565,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
|
|
|
90651
91565
|
post({ type: "plan", plan: activePlan ?? "" });
|
|
90652
91566
|
postPlanProgress();
|
|
90653
91567
|
void postStrategies();
|
|
91568
|
+
post({ type: "chatSkillToolPicks", value: chatPicks ?? "off" });
|
|
90654
91569
|
}
|
|
90655
91570
|
const pendingSteeringPath = () => workspaceRoot === void 0 ? void 0 : pendingSteeringFile(storageDir, workspaceRoot);
|
|
90656
91571
|
async function startNewTask(options = {}) {
|
|
@@ -90668,6 +91583,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
|
|
|
90668
91583
|
activePlan = void 0;
|
|
90669
91584
|
activePlanProgress = {};
|
|
90670
91585
|
activeStrategy = options.keepStrategy;
|
|
91586
|
+
chatPicks = options.keepPicks;
|
|
90671
91587
|
strategyProgress = {};
|
|
90672
91588
|
strategyExchanges = [];
|
|
90673
91589
|
strategyLastRole = void 0;
|
|
@@ -90676,7 +91592,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
|
|
|
90676
91592
|
await setActiveTaskId(void 0);
|
|
90677
91593
|
const pending = pendingSteeringPath();
|
|
90678
91594
|
if (pending !== void 0 && backgroundRun !== true) {
|
|
90679
|
-
if (options.keepStrategy !== void 0)
|
|
91595
|
+
if (options.keepStrategy !== void 0 || options.keepPicks !== void 0)
|
|
90680
91596
|
await persistActiveTask();
|
|
90681
91597
|
else
|
|
90682
91598
|
await clearPendingSteering(pending);
|
|
@@ -90791,7 +91707,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
|
|
|
90791
91707
|
throw new Error("The model replied with nothing, so there is no handoff to start from.");
|
|
90792
91708
|
progress("starting");
|
|
90793
91709
|
const carried = { strategy: activeStrategy, progress: strategyProgress, exchanges: strategyExchanges };
|
|
90794
|
-
await startNewTask();
|
|
91710
|
+
await startNewTask({ keepPicks: chatPicks });
|
|
90795
91711
|
activeStrategy = carried.strategy;
|
|
90796
91712
|
strategyProgress = carried.progress;
|
|
90797
91713
|
strategyExchanges = carried.exchanges;
|
|
@@ -90906,6 +91822,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
|
|
|
90906
91822
|
await boundedWait(skillsReady, "Skills");
|
|
90907
91823
|
const codebaseInstructions = renderCodebaseInstructions(await instructionsReady);
|
|
90908
91824
|
const activeMode = findMode(config2.modeId);
|
|
91825
|
+
turnModeId = activeMode.id;
|
|
90909
91826
|
juniorTurnWithoutExpert = activeMode.id === "junior" && schedule === void 0;
|
|
90910
91827
|
const scheduledGuidance = schedule === void 0 ? void 0 : scheduledRunGuidance(schedule, filterToolsForSchedule(currentToolRegistry(void 0, void 0, void 0, void 0, false).list(), schedule).map((tool) => tool.name).filter((name) => name !== "attempt_completion"));
|
|
90911
91828
|
const skillsSearchable = skillRetrievalEnabled(config2.retrieval) && (schedule === void 0 || schedule.allowedSkills === void 0);
|
|
@@ -91119,8 +92036,9 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
|
|
|
91119
92036
|
siblings: mentionCodebases()
|
|
91120
92037
|
});
|
|
91121
92038
|
const directed = findDirectedRoles(text2, cachedTeam);
|
|
91122
|
-
const
|
|
91123
|
-
const
|
|
92039
|
+
const routed = activeMode.id === "agent-team" && schedule === void 0 && directed.addressed.length === 0 && cachedDecision?.profileId !== void 0 ? await routeMessage(text2, activeAbortController.signal).catch(() => void 0) : void 0;
|
|
92040
|
+
const direction = [describeDirectedRoles(directed, cachedTeam), ...routed !== void 0 ? [describeRoute(routed.role, routed.name, routed.probability)] : []].filter((part) => part.length > 0).join("\n\n");
|
|
92041
|
+
let messageText = direction.length > 0 ? `${attachMentions(text2, mentions)}
|
|
91124
92042
|
|
|
91125
92043
|
${direction}` : attachMentions(text2, mentions);
|
|
91126
92044
|
const turnOptions = {
|
|
@@ -91265,6 +92183,7 @@ ${direction}` : attachMentions(text2, mentions);
|
|
|
91265
92183
|
return collection !== void 0 && search2 !== void 0 && embedder !== void 0 ? { searcher: search2.searcher, embedder, collection } : void 0;
|
|
91266
92184
|
})()
|
|
91267
92185
|
);
|
|
92186
|
+
agentBriefingTools = () => fullRegistry.list();
|
|
91268
92187
|
const turnRegistry = schedule !== void 0 ? registryForSchedule(fullRegistry.list(), schedule) : fullRegistry;
|
|
91269
92188
|
turnOptions.timeoutForTool = toolTimeout;
|
|
91270
92189
|
if (schedule !== void 0) {
|
|
@@ -91286,6 +92205,13 @@ ${direction}` : attachMentions(text2, mentions);
|
|
|
91286
92205
|
observerHub.event({ kind: "turnEnd", at: Date.now(), ending, ...error51 !== void 0 ? { error: error51 } : {} });
|
|
91287
92206
|
};
|
|
91288
92207
|
observeTurnEnd = observeEnd;
|
|
92208
|
+
if (schedule === void 0) {
|
|
92209
|
+
const suggestion = await suggestSkillsAndTools(text2, turnRegistry).catch(() => "");
|
|
92210
|
+
if (suggestion.length > 0)
|
|
92211
|
+
messageText = `${messageText}
|
|
92212
|
+
|
|
92213
|
+
${suggestion}`;
|
|
92214
|
+
}
|
|
91289
92215
|
observerHub.event({ kind: "turnStart", at: Date.now(), text: messageText, mode: activeMode.name, model: profile.model });
|
|
91290
92216
|
turnOptions.drainObserverNotes = () => {
|
|
91291
92217
|
const notes = observerHub.takeNotes();
|
|
@@ -93400,6 +94326,8 @@ ${redact(shown2, cachedSecretValues)}` }
|
|
|
93400
94326
|
return { ok: true, data: await answerMonitorStore(request2.op, await monitorStore(request2.storeId, request2.index), request2.args) };
|
|
93401
94327
|
case "explain":
|
|
93402
94328
|
return { ok: true, data: await explainForMonitor(request2.context) };
|
|
94329
|
+
case "triage":
|
|
94330
|
+
return { ok: true, data: await triageAlert(request2.context) };
|
|
93403
94331
|
case "probe": {
|
|
93404
94332
|
const here = await monitorToolHere(request2.tool);
|
|
93405
94333
|
return { ok: true, data: "refusal" in here ? { ready: false, reason: here.refusal } : { ready: true } };
|
|
@@ -97141,8 +98069,14 @@ ${last}` : ""}`);
|
|
|
97141
98069
|
}
|
|
97142
98070
|
async function consultAgent(agent, request2) {
|
|
97143
98071
|
const strategy = activeStrategy;
|
|
97144
|
-
if (strategy === void 0)
|
|
97145
|
-
|
|
98072
|
+
if (strategy === void 0) {
|
|
98073
|
+
const suggestion = suggestRole(agent, request2.question);
|
|
98074
|
+
const answer2 = await consultAgentNow(agent, request2, false);
|
|
98075
|
+
const note = await suggestion;
|
|
98076
|
+
return note === void 0 ? answer2 : { ...answer2, advice: `${answer2.advice}
|
|
98077
|
+
|
|
98078
|
+
${note}` };
|
|
98079
|
+
}
|
|
97146
98080
|
const name = (role) => roleInfo(role, cachedAgentDefinitions).name;
|
|
97147
98081
|
const planned = beforeConsult(strategy, strategyProgress, strategyLastRole, agent.role, name);
|
|
97148
98082
|
if (planned.refuse !== void 0) {
|
|
@@ -97183,7 +98117,7 @@ ${more.advice}` };
|
|
|
97183
98117
|
strategyRunning.delete(agent.role);
|
|
97184
98118
|
}
|
|
97185
98119
|
const before = strategyProgress;
|
|
97186
|
-
const recorded = afterConsult(strategy, strategyProgress, agent.role, answer.advice, name);
|
|
98120
|
+
const recorded = afterConsult(strategy, strategyProgress, agent.role, answer.advice, name, await judgeLoops(strategy, agent.role, answer.advice, name));
|
|
97187
98121
|
strategyProgress = recorded.progress;
|
|
97188
98122
|
const exchange2 = exchangeOf(agent.role, request2.question, answer.advice, before, recorded.progress, request2.parallel === true);
|
|
97189
98123
|
recordExchange(checks.length > 0 ? { ...exchange2, contracts: checks.map((check2) => ({ ...check2, askedAgain: askedAgain.get(check2.edgeId) ?? 0 })) } : exchange2);
|
|
@@ -97192,12 +98126,94 @@ ${more.advice}` };
|
|
|
97192
98126
|
persistSoon();
|
|
97193
98127
|
void postStrategies();
|
|
97194
98128
|
const contractNotes = checks.filter((check2) => check2.missing.length > 0 || (askedAgain.get(check2.edgeId) ?? 0) > 0).map((check2) => check2.missing.length > 0 ? `[Strategy] The hand-over to ${name(check2.to)} is incomplete even after asking again: missing ${check2.missing.join(", ")}. Pass on what arrived and say plainly what is missing.` : `[Strategy] The hand-over to ${name(check2.to)} is complete (${check2.required.join(", ")}), after asking ${name(agent.role)} again for what it had left out.`);
|
|
97195
|
-
const
|
|
98129
|
+
const decisionNotes = [...await scoreHandOvers(strategy, agent, request2, answer, planned.readOnly, name), ...await chooseBranch(strategy, agent.role, answer.advice, name)];
|
|
98130
|
+
const notes = [...contractNotes, ...recorded.note !== void 0 ? [recorded.note] : [], ...decisionNotes];
|
|
97196
98131
|
const forMain = answerForMain(answer.advice, name(agent.role));
|
|
97197
98132
|
return { ...answer, advice: notes.length > 0 ? `${forMain}
|
|
97198
98133
|
|
|
97199
98134
|
${notes.join("\n")}` : forMain };
|
|
97200
98135
|
}
|
|
98136
|
+
async function scoreHandOvers(strategy, agent, request2, answer, readOnly, name) {
|
|
98137
|
+
if (cachedDecision?.profileId === void 0 || cachedDecision.scoreHandOvers === false)
|
|
98138
|
+
return [];
|
|
98139
|
+
const notes = [];
|
|
98140
|
+
for (const edge of strategy.edges) {
|
|
98141
|
+
const from = strategy.nodes.find((node) => node.id === edge.from);
|
|
98142
|
+
if (from?.role !== agent.role || edge.contract === void 0 || edge.contract.trim().length === 0)
|
|
98143
|
+
continue;
|
|
98144
|
+
const to = strategy.nodes.find((node) => node.id === edge.to);
|
|
98145
|
+
const target = to !== void 0 ? name(to.role) : "the next step";
|
|
98146
|
+
const decision = await askDecisionModel(`Hand-over ${name(agent.role)} \u2192 ${target}`, handoverQuestion(edge.contract, answer.advice), (d) => d.score === void 0 ? "no score" : d.score < DEFAULT_HANDOVER_THRESHOLD ? `incomplete (${d.score.toFixed(2)})` : `complete (${d.score.toFixed(2)})`);
|
|
98147
|
+
if (decision?.score === void 0 || decision.score >= DEFAULT_HANDOVER_THRESHOLD)
|
|
98148
|
+
continue;
|
|
98149
|
+
const more = await consultAgentNow(agent, { ...request2, question: `Your answer does not seem to give what was agreed for the hand-over to ${target}: ${edge.contract.trim()}. Give that now, briefly.
|
|
98150
|
+
|
|
98151
|
+
Your answer was:
|
|
98152
|
+
${answer.advice.slice(0, 12e3)}` }, readOnly).catch(() => void 0);
|
|
98153
|
+
if (more !== void 0) {
|
|
98154
|
+
answer.advice = `${answer.advice}
|
|
98155
|
+
|
|
98156
|
+
${more.advice}`;
|
|
98157
|
+
strategyAnswers.set(agent.role, answer.advice);
|
|
98158
|
+
}
|
|
98159
|
+
notes.push(`[Strategy] The decision model scored the hand-over to ${target} at ${decision.score.toFixed(2)} against what was agreed ("${edge.contract.trim()}"), so ${name(agent.role)} was asked once more for it.`);
|
|
98160
|
+
}
|
|
98161
|
+
return notes;
|
|
98162
|
+
}
|
|
98163
|
+
async function triageAlert(context) {
|
|
98164
|
+
if (cachedDecision?.profileId === void 0 || cachedDecision.triageAlerts === false)
|
|
98165
|
+
return null;
|
|
98166
|
+
const decision = await askDecisionModel("Monitoring triage", triageQuestion(context), (d) => `needs a person now: ${(d.probabilities?.["yes"] ?? 0).toFixed(2)}`);
|
|
98167
|
+
const yes = decision?.probabilities?.["yes"];
|
|
98168
|
+
return decision?.ok === true && yes !== void 0 ? { needsHuman: yes } : null;
|
|
98169
|
+
}
|
|
98170
|
+
const SUGGEST_TIMEOUT_MS = 4e3;
|
|
98171
|
+
async function suggestSkillsAndTools(text2, registry2) {
|
|
98172
|
+
const picks = chatPicks;
|
|
98173
|
+
if (cachedDecision?.profileId === void 0 || picks === void 0 || text2.trim().length < 6)
|
|
98174
|
+
return "";
|
|
98175
|
+
const asked = withRecentChat(text2, conversation.toArray());
|
|
98176
|
+
const usable = skills.filter((skill) => skill.always !== true);
|
|
98177
|
+
const control = /* @__PURE__ */ new Set(["attempt_completion", "ask_followup_question", "call_tool", "search_docs", "forget_docs", "read_tool_result", "ask_user_form", "light_code_help", "update_plan", "plan_progress"]);
|
|
98178
|
+
const tools = registry2.list().filter((tool) => !control.has(tool.name));
|
|
98179
|
+
const [skillDecision, toolDecision] = await Promise.all([
|
|
98180
|
+
// At most four seconds before the reply starts: a suggestion that comes later is not worth the wait.
|
|
98181
|
+
picks !== "tools" && usable.length > 0 ? askDecisionModel("Skill for this request", skillQuestion(asked, usable), (d) => `best ${d.best?.id ?? "?"} ${(d.best?.probability ?? 0).toFixed(2)}`, void 0, SUGGEST_TIMEOUT_MS) : Promise.resolve(void 0),
|
|
98182
|
+
picks !== "skills" && tools.length > 0 ? askDecisionModel("Tool for this request", toolQuestion(asked, tools), (d) => `best ${d.best?.id ?? "?"} ${(d.best?.probability ?? 0).toFixed(2)}`, void 0, SUGGEST_TIMEOUT_MS) : Promise.resolve(void 0)
|
|
98183
|
+
]);
|
|
98184
|
+
const threshold = cachedDecision.suggestThreshold;
|
|
98185
|
+
const skillPicks = picked(skillDecision, threshold).map((pick4) => ({ ...pick4, filePath: usable.find((skill) => skill.name === pick4.id)?.filePath }));
|
|
98186
|
+
const toolPicks = picked(toolDecision, threshold).map((pick4) => ({ ...pick4, hidden: registry2.isDispatchOnly(pick4.id) }));
|
|
98187
|
+
return describeSuggestions(skillPicks, toolPicks);
|
|
98188
|
+
}
|
|
98189
|
+
async function chooseBranch(strategy, role, answer, name) {
|
|
98190
|
+
if (cachedDecision?.profileId === void 0)
|
|
98191
|
+
return [];
|
|
98192
|
+
const choice = branchChoice(strategy, role, name);
|
|
98193
|
+
if (choice === void 0)
|
|
98194
|
+
return [];
|
|
98195
|
+
const threshold = cachedDecision.routeThreshold ?? DEFAULT_ROUTE_THRESHOLD;
|
|
98196
|
+
const decision = await askDecisionModel(`Decision step after ${name(role)}`, { kind: "choice", question: choice.question, options: choice.options, inputs: { text: `${name(role)} answered:
|
|
98197
|
+
${answer.slice(0, 16e3)}` } }, (d) => d.best !== void 0 && d.best.probability >= threshold ? `go to ${choice.options.find((o) => o.id === d.best?.id)?.label ?? "?"}` : "left to the main agent");
|
|
98198
|
+
const best = decision?.best;
|
|
98199
|
+
const picked2 = best !== void 0 && best.probability >= threshold ? choice.options.find((option) => option.id === best.id) : void 0;
|
|
98200
|
+
if (picked2 === void 0 || best === void 0) {
|
|
98201
|
+
return [`[Strategy] Decision step after ${name(role)}: the decision model was not sure which way to go${decision?.ok === false ? " (it did not answer)" : ""} - choose from the connectors yourself.`];
|
|
98202
|
+
}
|
|
98203
|
+
return [`[Strategy] Decision step after ${name(role)}: the decision model picks ${picked2.label}${picked2.description !== void 0 ? ` (${picked2.description})` : ""}, probability ${best.probability.toFixed(2)}. Go there next.`];
|
|
98204
|
+
}
|
|
98205
|
+
async function suggestRole(agent, question) {
|
|
98206
|
+
if (cachedDecision?.profileId === void 0 || cachedDecision.suggestRoles === false || turnModeId !== "agent-team")
|
|
98207
|
+
return void 0;
|
|
98208
|
+
const team = cachedTeam.filter((candidate) => candidate.available);
|
|
98209
|
+
if (team.length < 2)
|
|
98210
|
+
return void 0;
|
|
98211
|
+
const threshold = cachedDecision.routeThreshold ?? DEFAULT_ROUTE_THRESHOLD;
|
|
98212
|
+
const decision = await askDecisionModel("Role suggestion during a turn", routeQuestion(question, team, []), (d) => `best ${d.best?.id ?? "?"} ${(d.best?.probability ?? 0).toFixed(2)}`).catch(() => void 0);
|
|
98213
|
+
if (decision === void 0)
|
|
98214
|
+
return void 0;
|
|
98215
|
+
return roleSuggestion(decision, agent.role, threshold, (role) => team.find((candidate) => candidate.role === role)?.name ?? role);
|
|
98216
|
+
}
|
|
97201
98217
|
const strategyAnswers = /* @__PURE__ */ new Map();
|
|
97202
98218
|
let strategyTopicSince = 0;
|
|
97203
98219
|
const HANDOVER_LIMIT = 24e3;
|
|
@@ -97690,15 +98706,15 @@ ${notes.join("\n")}` : forMain };
|
|
|
97690
98706
|
}
|
|
97691
98707
|
}
|
|
97692
98708
|
async function handleBrowseForPath(purpose, kind, extensions) {
|
|
97693
|
-
const
|
|
98709
|
+
const picked2 = await ui.showOpenDialog({
|
|
97694
98710
|
kind,
|
|
97695
98711
|
// Opens where the user is already working rather than at some unrelated default.
|
|
97696
98712
|
...workspaceRoot !== void 0 ? { defaultPath: workspaceRoot } : {},
|
|
97697
98713
|
...extensions !== void 0 && extensions.length > 0 ? { extensions } : {}
|
|
97698
98714
|
});
|
|
97699
|
-
if (
|
|
98715
|
+
if (picked2 === void 0)
|
|
97700
98716
|
return;
|
|
97701
|
-
post({ type: "pathPicked", purpose, path:
|
|
98717
|
+
post({ type: "pathPicked", purpose, path: picked2 });
|
|
97702
98718
|
}
|
|
97703
98719
|
function uniqueName(base, taken) {
|
|
97704
98720
|
if (!taken.includes(base))
|
|
@@ -97780,10 +98796,10 @@ ${notes.join("\n")}` : forMain };
|
|
|
97780
98796
|
reportFailure("handleCompactConversation", handleCompactConversation());
|
|
97781
98797
|
} else if (message6.type === "pickContextFiles") {
|
|
97782
98798
|
void (async () => {
|
|
97783
|
-
const
|
|
97784
|
-
if (
|
|
98799
|
+
const picked2 = await ui.pickContextFiles?.();
|
|
98800
|
+
if (picked2 === void 0 || picked2.length === 0)
|
|
97785
98801
|
return;
|
|
97786
|
-
post({ type: "addContextFiles", paths:
|
|
98802
|
+
post({ type: "addContextFiles", paths: picked2.map((file2) => contextMentionPath(file2)) });
|
|
97787
98803
|
})();
|
|
97788
98804
|
} else if (message6.type === "stageAttachment") {
|
|
97789
98805
|
const { id, name, data } = message6;
|
|
@@ -97846,7 +98862,7 @@ ${notes.join("\n")}` : forMain };
|
|
|
97846
98862
|
} else if (message6.type === "deleteTask") {
|
|
97847
98863
|
reportFailure("deleteTask", deleteTask(message6.id));
|
|
97848
98864
|
} else if (message6.type === "newTask") {
|
|
97849
|
-
reportFailure("startNewTask", startNewTask({ keepStrategy: activeStrategy }));
|
|
98865
|
+
reportFailure("startNewTask", startNewTask({ keepStrategy: activeStrategy, keepPicks: chatPicks }));
|
|
97850
98866
|
} else if (message6.type === "startHandoff") {
|
|
97851
98867
|
reportFailure("handleHandoff", handleHandoff());
|
|
97852
98868
|
} else if (message6.type === "cancelHandoff") {
|
|
@@ -97859,6 +98875,29 @@ ${notes.join("\n")}` : forMain };
|
|
|
97859
98875
|
void configManager.save("user", { autoCompact: message6.value }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
|
|
97860
98876
|
} else if (message6.type === "setComposerCompletion") {
|
|
97861
98877
|
void configManager.save("user", { composerCompletion: message6.value }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
|
|
98878
|
+
} else if (message6.type === "requestDecisionModel") {
|
|
98879
|
+
reportFailure("postDecisionModel", postDecisionModel());
|
|
98880
|
+
} else if (message6.type === "saveDecisionModel") {
|
|
98881
|
+
const settings = message6.settings;
|
|
98882
|
+
const endpointProblem = decisionEndpointProblem(settings.endpoint?.trim());
|
|
98883
|
+
if (endpointProblem !== void 0) {
|
|
98884
|
+
void postDecisionModel(endpointProblem);
|
|
98885
|
+
return;
|
|
98886
|
+
}
|
|
98887
|
+
void configManager.save("user", { decisionModel: settings.profileId === void 0 ? void 0 : settings }).then(async () => {
|
|
98888
|
+
await postSettings();
|
|
98889
|
+
await postDecisionModel();
|
|
98890
|
+
}).catch((error51) => void postDecisionModel(error51 instanceof Error ? error51.message : String(error51)));
|
|
98891
|
+
} else if (message6.type === "setChatSkillToolPicks") {
|
|
98892
|
+
chatPicks = isSkillToolPicks(message6.value) ? message6.value : void 0;
|
|
98893
|
+
post({ type: "chatSkillToolPicks", value: chatPicks ?? "off" });
|
|
98894
|
+
void postStrategies();
|
|
98895
|
+
persistSoon();
|
|
98896
|
+
void persistActiveTask();
|
|
98897
|
+
} else if (message6.type === "requestChatSkillToolPicks") {
|
|
98898
|
+
post({ type: "chatSkillToolPicks", value: chatPicks ?? "off" });
|
|
98899
|
+
} else if (message6.type === "testDecisionModel") {
|
|
98900
|
+
reportFailure("testDecisionModel", testDecisionModel());
|
|
97862
98901
|
} else if (message6.type === "requestCompletion") {
|
|
97863
98902
|
void suggestCompletion(message6.id, message6.text);
|
|
97864
98903
|
} else if (message6.type === "setUnlimitedSteps") {
|
|
@@ -102031,6 +103070,13 @@ them becomes one notice. With a model chosen, the Auditor also reviews each batc
|
|
|
102031
103070
|
alerts. Agents can read the record back with **read_audit_log** (summary first, then records with filters;
|
|
102032
103071
|
rows go straight into the dataframe tool for custom analysis).
|
|
102033
103072
|
|
|
103073
|
+
**With a decision model** (Settings \u2192 Agents \u2192 Decision model, e.g. D3), the Anti Hallucinator gets a **first pass**:
|
|
103074
|
+
the decision model is asked, for each step, whether it is grounded in its tool results and still on your request. A
|
|
103075
|
+
step it is sure of (0.85 by default, config:decisionModel.firstPassThreshold) is still given to the Anti
|
|
103076
|
+
Hallucinator, which keeps its whole context, but is reviewed together with the next step that needs a review rather
|
|
103077
|
+
than on its own; anything else is reviewed straight away, as before. Fewer full reviews, never none. Off with
|
|
103078
|
+
config:decisionModel.firstPass false.
|
|
103079
|
+
|
|
102034
103080
|
**Their instructions are yours to edit**: each panel has an **Instructions** box (Reset to default puts the shipped
|
|
102035
103081
|
text back). The reply format and the running notes they must keep are always added after your text, so an edit
|
|
102036
103082
|
cannot stop the reviews being read or the handoff working.
|
|
@@ -102673,6 +103719,14 @@ while it stays red or amber, a quiet word when it clears, and quiet hours when o
|
|
|
102673
103719
|
Each monitor can override it (right-click \u2192 How this one notifies), and its own \`notify\` sets the least
|
|
102674
103720
|
severe level that notifies. Notifications have Open, Acknowledge and Snooze buttons.
|
|
102675
103721
|
|
|
103722
|
+
**Triage by a decision model** (Settings \u2192 Agents \u2192 Decision model in Light Code; config:decisionModel.triageAlerts):
|
|
103723
|
+
before an alert that just got worse is announced, the decision model is asked whether it needs a person now. Sure
|
|
103724
|
+
it does (0.8 or more): it stays on screen (at least Stays) even where the level is set to Sound or Silent. It is given
|
|
103725
|
+
the monitor, the level, the headline and the first ten alerts with their rows. Sure it
|
|
103726
|
+
can wait (0.2 or less): silent - **never for red**, which is always announced as set. Unsure, no decision model, or no
|
|
103727
|
+
answer within 20 seconds: as set. The notification says what the decision model thought. It is asked only while the
|
|
103728
|
+
monitoring executor is already running.
|
|
103729
|
+
|
|
102676
103730
|
**When checks run**: \`every\` ("15m") for an interval - once in each window of the clock (every 10 minutes is
|
|
102677
103731
|
10:00, 10:10, 10:20 ..., windows counted from UTC so a team across time zones agrees), whoever joined when, kept to \`activeHours\` ("07:00-19:00", or "09:00-" for not
|
|
102678
103732
|
before nine, "-17:00" for until five); \`at\` for exact times of day ("07:30" - once a day - or ["07:30", "12:00",
|
|
@@ -102989,8 +104043,8 @@ another chat on the same codebase \u2014 its own agent, working at the same time
|
|
|
102989
104043
|
keys. To rename a chat - the first one too - double-click its tab, or right-click it \u2192 Rename chat; the
|
|
102990
104044
|
name shows on the tab and in notifications. \xD7 or Ctrl+W asks how to close a chat: **Archive** keeps its
|
|
102991
104045
|
conversation and takes the tab away; **Close and delete** removes its conversations, reports and log
|
|
102992
|
-
(files it changed in the codebase stay). **New chat**
|
|
102993
|
-
reused - and when chats are archived, + offers *New blank chat* or any archived chat, which opens exactly
|
|
104046
|
+
(files it changed in the codebase stay). **New chat** starts with an empty conversation - a closed chat's number is
|
|
104047
|
+
never reused - and keeps the strategy of the chat you were on (its loops start fresh; pick another or Stop using) - and when chats are archived, + offers *New blank chat* or any archived chat, which opens exactly
|
|
102994
104048
|
where it was left (each archived row also has a delete). Ctrl+T is always blank. Two safeguards make
|
|
102995
104049
|
this safe: an edit is refused when the file changed since that chat read it (another chat, you, or any
|
|
102996
104050
|
program edited it) \u2014 the agent re-reads and edits what is there now; and **Rollback undoes only the files
|
|
@@ -103054,6 +104108,13 @@ the theme. A codebase may keep its own accent \u2014 pick one in its Appearance
|
|
|
103054
104108
|
icon follows; "Use Fire Code's accent" goes back. Role colours stay each chat's own. None of this
|
|
103055
104109
|
is written to the config file.
|
|
103056
104110
|
|
|
104111
|
+
**A decision model** (Settings \u2192 Agents \u2192 Decision model in any codebase's settings, e.g. D3): besides Agent team
|
|
104112
|
+
routing and strategy decisions, it decides **how loudly a monitoring alert is announced** - louder when it needs you
|
|
104113
|
+
now, quieter when it can wait, never quieter for red. See the decision-model and monitoring topics.
|
|
104114
|
+
|
|
104115
|
+
**After a crash**: a chat whose agent stopped mid-reply carries on by itself when Fire Code restarts it (at most three
|
|
104116
|
+
times in a row), and the log of the run that stopped is kept under crashes in the data folder.
|
|
104117
|
+
|
|
103057
104118
|
**Memory**: idle codebases sleep after 30 minutes by default (Fire Code's Settings), freeing their agent,
|
|
103058
104119
|
MCP servers and Python worker. Never while working or waiting for you. **Schedules still run**: Fire Code
|
|
103059
104120
|
keeps their timetable itself and wakes a codebase a minute before a job is due \u2014 asleep or never
|
|
@@ -103111,10 +104172,14 @@ without waiting for the servers; a server keeps starting in the background, and
|
|
|
103111
104172
|
tools waits for it. A server with no remembered list is waited for at most 45 seconds, after which the
|
|
103112
104173
|
reply goes ahead and its tools join the next message. While anything is still getting ready, a bar over
|
|
103113
104174
|
the message box names it with how long it has taken - each MCP server still starting, Python tools, skills, the model
|
|
103114
|
-
gateway's sign-in - and, for skills and Python tools, which folder or step is under way
|
|
104175
|
+
gateway's sign-in - and, for skills and Python tools, which folder or step is under way (a folder by its last two
|
|
104176
|
+
parts; hover for the whole path); it goes when nothing is left.
|
|
103115
104177
|
A message sent meanwhile waits at most 20 seconds for skills and 45 for tools, then is answered with what has loaded;
|
|
103116
104178
|
the rest joins the next message. When that keeps happening, a slow folder (often a network share or a disconnected
|
|
103117
|
-
drive) is the usual cause - the log names it.
|
|
104179
|
+
drive) is the usual cause - the log names it. **Skills and Python tools are read in one go**: every folder - the
|
|
104180
|
+
bucket and team-repository copies too - is listed and read at once, by the Rust helper where there is one (Fire Code,
|
|
104181
|
+
and the VS Code extension on Windows) and by Node in parallel otherwise, and a file not changed since the last load
|
|
104182
|
+
is not read again, so after the first message a load costs a folder listing. The agent log
|
|
103118
104183
|
(\`host.log\`) also names each slow part with a \`[startup]\` line.
|
|
103119
104184
|
|
|
103120
104185
|
**Not in Fire Code**: editor file pickers \u2014 paths are typed. Fire Code's
|
|
@@ -103521,6 +104586,14 @@ as in the message box: its contents are attached each time the specialist is ask
|
|
|
103521
104586
|
deny list as @ in the chat. Leave it empty and the main agent decides what to ask it, from its plan. **Read-only** means
|
|
103522
104587
|
it cannot change anything: it gets no tool that edits or runs commands, and recommends instead.
|
|
103523
104588
|
|
|
104589
|
+
**A decision step** (only with a decision model - Settings \u2192 Agents \u2192 Decision model): tick **The decision model picks
|
|
104590
|
+
the next step** on a step with two or more connectors out of it, and optionally give the question ("Did the review find
|
|
104591
|
+
a security problem?"). Once that step answers, the decision model chooses which connector to follow - by where it leads
|
|
104592
|
+
and its label - from the answer, and the main agent is told "go there next". When it is not sure, or there is no
|
|
104593
|
+
decision model, the main agent chooses as before. With a decision model, **hand-overs are also scored** against their
|
|
104594
|
+
contract: one that falls short is asked for once more and the main agent is told; and **loop conditions** are judged by
|
|
104595
|
+
it (see the decision-model topic).
|
|
104596
|
+
|
|
103524
104597
|
**A contract on a connector** ("What passes along here"): what one step hands to the next, such as "the failing
|
|
103525
104598
|
tests, each with file:line". The first is told its answer must contain it, the second that it will be given it and to
|
|
103526
104599
|
say what is missing - so what was agreed between them is written down.
|
|
@@ -104087,6 +105160,107 @@ kept; files outside the codebase are not covered either way.
|
|
|
104087
105160
|
Conversations survive closing the panel, reloading the window and restarting the editor. A resumed
|
|
104088
105161
|
task must **re-read a file before editing it**, deliberately: the file may have changed since the
|
|
104089
105162
|
transcript was written.
|
|
105163
|
+
`
|
|
105164
|
+
},
|
|
105165
|
+
{
|
|
105166
|
+
id: "decision-model",
|
|
105167
|
+
title: "A decision model (D3) for Agent team and strategies",
|
|
105168
|
+
keywords: [
|
|
105169
|
+
"decision model",
|
|
105170
|
+
"d3",
|
|
105171
|
+
"semantic router",
|
|
105172
|
+
"vllm semantic router",
|
|
105173
|
+
"routing",
|
|
105174
|
+
"route",
|
|
105175
|
+
"router",
|
|
105176
|
+
"which specialist",
|
|
105177
|
+
"pick the specialist",
|
|
105178
|
+
"probabilities",
|
|
105179
|
+
"calibrated",
|
|
105180
|
+
"logprobs",
|
|
105181
|
+
"decision",
|
|
105182
|
+
"decisions by",
|
|
105183
|
+
"loop condition",
|
|
105184
|
+
"first pass",
|
|
105185
|
+
"anti hallucinator first pass",
|
|
105186
|
+
"decision step",
|
|
105187
|
+
"hand-over score",
|
|
105188
|
+
"triage",
|
|
105189
|
+
"alert triage",
|
|
105190
|
+
"role suggestion",
|
|
105191
|
+
"right skill",
|
|
105192
|
+
"right tool",
|
|
105193
|
+
"choose the skill",
|
|
105194
|
+
"choose the tool",
|
|
105195
|
+
"which skill",
|
|
105196
|
+
"which tool",
|
|
105197
|
+
"judge the loop",
|
|
105198
|
+
"sent to",
|
|
105199
|
+
"answer it yourself",
|
|
105200
|
+
"test decision model",
|
|
105201
|
+
"systemone",
|
|
105202
|
+
"decision endpoint",
|
|
105203
|
+
"noul"
|
|
105204
|
+
],
|
|
105205
|
+
body: `
|
|
105206
|
+
**A decision model answers narrow questions with probabilities** - D3 from vLLM Semantic Router is one. Set it up
|
|
105207
|
+
under Settings \u2192 Providers as an **OpenAI-compatible** profile, then choose it in Settings \u2192 Agents \u2192
|
|
105208
|
+
**Decision model** (config:decisionModel.profileId). Until one is chosen, nothing else about it appears and Agent team
|
|
105209
|
+
and strategies work exactly as before.
|
|
105210
|
+
|
|
105211
|
+
With one chosen:
|
|
105212
|
+
- **Agent team mode sends each message to the specialist it picks** (config:decisionModel.routing, on by default), when
|
|
105213
|
+
it is at least config:decisionModel.routeThreshold sure (default 0.75). The main assistant is then told to consult
|
|
105214
|
+
that specialist with \`ask_agent\` - the same as typing \`#role\` yourself - so approvals, read-only roles and the
|
|
105215
|
+
specialist's own context are unchanged. A note above the message box says "Sent to Tester \xB7 0.91"; **Answer it
|
|
105216
|
+
yourself** takes it back while the reply runs. Not done when you address someone with \`#\`, while a strategy is in
|
|
105217
|
+
use (the strategy says who acts), or for scheduled runs. The header says "decisions by <profile>".
|
|
105218
|
+
- **Strategy loops are judged by it** (config:decisionModel.judgeLoops, on by default): for a back-and-forth connector
|
|
105219
|
+
with an "until" condition, it is asked whether the condition is met, from the work handed in and the judge's review.
|
|
105220
|
+
At config:decisionModel.loopThreshold or above (default 0.8) it is met; at its mirror or below (0.2) it is not; in
|
|
105221
|
+
between the judging specialist's own CONDITION line decides, as before.
|
|
105222
|
+
|
|
105223
|
+
**How it is asked.** D3 does not generate text and does not serve chat completions: it answers on its own decision
|
|
105224
|
+
API, \`POST <base URL>/systemone\` (vLLM, and the Semantic Router engine), with a probability for every option of a
|
|
105225
|
+
**choice**, a **noul** (yes/no) or a **score** (named levels) question. Light Code asks it that way: the input goes as
|
|
105226
|
+
\`state\`, the options with their descriptions as the question's \`criteria\`, pictures as data URLs, and the answer's
|
|
105227
|
+
\`structured_decision\` is read per option. **Endpoint** (config:decisionModel.endpoint) is the path on the profile's
|
|
105228
|
+
base URL: blank tries \`/systemone\` and, if that path is not there (404), chat completions from then on; a path you
|
|
105229
|
+
type - such as \`/d3/v1/systemone\` where an office gateway puts D3 behind its OpenAI-compatible address - is used as
|
|
105230
|
+
it is, with no fallback; \`chat\` is for a decision model that only answers chat completions (its probabilities are then
|
|
105231
|
+
read from JSON in the answer or from token log-probabilities). An answer with no probabilities is not used - a bare
|
|
105232
|
+
"B" says which, not how sure - and the note says why.
|
|
105233
|
+
|
|
105234
|
+
**Test decision model** asks a yes/no and a choice sample and shows which API answered, what was read from it, and the
|
|
105235
|
+
raw answer. Press it first: a wrong endpoint shows here as HTTP 404 with the path that was asked.
|
|
105236
|
+
|
|
105237
|
+
Also, each with its own switch in the same panel (all on once a decision model is chosen):
|
|
105238
|
+
- **The skill and the tool for each request**, in any mode - chosen **per chat** with **Picks** beside the mode picker
|
|
105239
|
+
(it appears once a decision model is set up): **off**, **skills** only, **tools** only, or **skills & tools**. Skills
|
|
105240
|
+
only is often enough - a good skill names the tools to use - and is the quicker, with one question instead of two.
|
|
105241
|
+
The chat keeps the choice, and a chat started from it keeps it too: "+", a handoff, a new Fire Code tab. Before each
|
|
105242
|
+
reply it is asked which skill and/or which tool the request needs, from the request and the two messages before it;
|
|
105243
|
+
what stands out (config:decisionModel.suggestThreshold, default 0.25, at most three of each; "nothing in particular"
|
|
105244
|
+
is always an option) is added to your message for the assistant as advice - the skill's file to read first, and for a
|
|
105245
|
+
hidden tool how to reach it. The tools on offer and the prompt's fixed part never change, and every tool is still
|
|
105246
|
+
approved as always. **Speed:** once per message (not per step); with both, the two questions go at once, and D3
|
|
105247
|
+
generates no text, so it is usually a fraction of a second before the reply starts; it never waits more than 4
|
|
105248
|
+
seconds, and a late answer is simply not used. A chat with Picks off asks nothing. Not for scheduled runs.
|
|
105249
|
+
- **Anti Hallucinator first pass** (config:decisionModel.firstPass): a step it is sure is grounded and on course
|
|
105250
|
+
(config:decisionModel.firstPassThreshold, default 0.85) is reviewed with the next one instead of on its own.
|
|
105251
|
+
- **Decision steps** in the Strategy window: a step whose next step it picks (see the strategies topic).
|
|
105252
|
+
- **Hand-over scores** (config:decisionModel.scoreHandOvers): a strategy hand-over that falls short of its connector's
|
|
105253
|
+
contract is asked for once more.
|
|
105254
|
+
- **Role suggestions** (config:decisionModel.suggestRoles): in Agent team, when the main assistant consults one
|
|
105255
|
+
specialist and another fits the question better, the answer says so - advice only.
|
|
105256
|
+
- **New topics** (config:decisionModel.newTopics): when a plan is rewritten, whether it is new work - then a strategy's
|
|
105257
|
+
loops start again; the built-in rule still applies as well.
|
|
105258
|
+
- **Monitoring triage** in Fire Code (config:decisionModel.triageAlerts): an alert is announced louder when it needs you
|
|
105259
|
+
now, quieter when it can wait - never quieter for red.
|
|
105260
|
+
|
|
105261
|
+
It advises and never authorises: it cannot approve anything, grant a tool, or change a strategy. Every decision,
|
|
105262
|
+
with its probabilities, is in the Auditor's record when the Auditor is on. A decision model that does not answer (10
|
|
105263
|
+
seconds) is skipped for that message, with a one-line note.
|
|
104090
105264
|
`
|
|
104091
105265
|
},
|
|
104092
105266
|
{
|
|
@@ -107056,18 +108230,18 @@ async function fetchCredential(options, reference) {
|
|
|
107056
108230
|
}
|
|
107057
108231
|
const record2 = parsed;
|
|
107058
108232
|
if (field2 !== void 0) {
|
|
107059
|
-
const
|
|
107060
|
-
if (typeof
|
|
108233
|
+
const picked2 = record2[field2];
|
|
108234
|
+
if (typeof picked2 !== "string" || picked2.length === 0) {
|
|
107061
108235
|
const available = Object.keys(record2).join(", ");
|
|
107062
108236
|
return {
|
|
107063
108237
|
problem: `"${name}" has no "${field2}". It returned: ${available.length > 0 ? available : "nothing"}.`
|
|
107064
108238
|
};
|
|
107065
108239
|
}
|
|
107066
|
-
return { value:
|
|
108240
|
+
return { value: picked2 };
|
|
107067
108241
|
}
|
|
107068
108242
|
for (const candidate of FIELDS2) {
|
|
107069
|
-
const
|
|
107070
|
-
if (typeof
|
|
108243
|
+
const picked2 = record2[candidate];
|
|
108244
|
+
if (typeof picked2 === "string" && picked2.length > 0) return { value: picked2 };
|
|
107071
108245
|
}
|
|
107072
108246
|
return {
|
|
107073
108247
|
problem: `"${name}" returned a dict with none of ${FIELDS2.join(", ")} in it. Name the field you want: tool:${name}#<field>.`
|