@chosengeneration/light-code 0.189.0 → 0.192.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.
Files changed (3) hide show
  1. package/dist/cli.cjs +785 -43
  2. package/dist/server.cjs +781 -40
  3. package/package.json +1 -1
package/dist/server.cjs CHANGED
@@ -39550,6 +39550,7 @@ function describeStrategy(strategy, roleName) {
39550
39550
  return `the box "${groupName(group)}" (step${inside.length === 1 ? "" : "s"} ${inside.join(", ")})`;
39551
39551
  };
39552
39552
  const onward = (edge) => `${label(edge.to)}${edge.contract !== void 0 && edge.contract.trim().length > 0 ? ` (passing on: ${firstLine(edge.contract)})` : ""}${requiredOf(edge).length > 0 && !groups.some((g) => g.id === edge.from) ? ` [required: ${requiredOf(edge).join(", ")}]` : ""}`;
39553
+ const askAs = (role) => roleName(role).trim().toLowerCase() === role ? "" : ` (ask_agent role "${role}")`;
39553
39554
  const lines2 = [`## Strategy: ${strategy.name}`, "", "The user drew how this work must be done. Steps, each done by consulting that role with ask_agent:"];
39554
39555
  const announced = /* @__PURE__ */ new Set();
39555
39556
  for (const node of order2) {
@@ -39560,7 +39561,7 @@ function describeStrategy(strategy, roleName) {
39560
39561
  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 ")}` : ""}:`);
39561
39562
  }
39562
39563
  const next = strategy.edges.filter((edge) => edge.from === node.id && edge.twoWay !== true).map(onward);
39563
- lines2.push(`${group !== void 0 ? " " : ""}${String(number5.get(node.id))}. ${roleName(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 ")}` : ""));
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 ")}` : ""));
39564
39565
  if (group !== void 0) {
39565
39566
  const members = groupMembers(strategy, group.id);
39566
39567
  const last = order2.filter((n) => members.some((m) => m.id === n.id)).at(-1);
@@ -39589,7 +39590,7 @@ function describeStrategy(strategy, roleName) {
39589
39590
  if (boxes.length > 0) {
39590
39591
  lines2.push("", "A connector leaving a box is followed only once every step inside it has answered. A connector into a box gives every step inside what arrives along it.");
39591
39592
  }
39592
- lines2.push("", "How to follow it:", "- This strategy applies to every piece of work asked for in this chat, not only the first. Before doing anything else for a request - including a new topic after an earlier one is finished - propose a plan with update_plan that carries out every step above in order for that request, naming the role for each step and writing each back-and-forth as one step with its condition and its maximum rounds. Then follow the plan. A new plan for a new topic starts the loops afresh; do not reuse an earlier topic's plan or skip the specialists because they were consulted before.", "- Give each specialist what it needs from the earlier steps: it does not see this conversation, only what you send it. A step's own instructions from the user reach it with every question; plan the steps that have none.", "- Connectors with no contract: before starting, propose what should pass along them with set_strategy_contracts (the user approves it). Light Code checks every required item after each answer, asks the specialist again for what is missing, and tells you if it is still missing - pass on what arrived, and say what did not.", "- In a back-and-forth, Light Code counts the rounds and tells you after each answer where the loop stands; it refuses a round past the maximum. If the maximum is reached without the condition, stop and tell the user what is still open rather than working around it.", "- A question from the user that is not part of the strategy is answered normally.");
39593
+ lines2.push("", "How to follow it:", "- This strategy applies to every piece of work asked for in this chat, not only the first. Before doing anything else for a request - including a new topic after an earlier one is finished - propose a plan with update_plan that carries out every step above in order for that request, naming the role for each step and writing each back-and-forth as one step with its condition and its maximum rounds. Then follow the plan. A new plan for a new topic starts the loops afresh; do not reuse an earlier topic's plan or skip the specialists because they were consulted before.", "- Each specialist works in its own context and does not see this conversation. Light Code hands each step the latest full answers of the steps connected into it, directly - do not paste earlier specialists' answers into your question. Say what this step should do now, and add only what it cannot get that way: the user's request and anything from this conversation it needs. You are given each specialist's summary, not its whole answer; read the full one with strategy_history only when you need the detail. A step's own instructions from the user reach it with every question; plan the steps that have none.", "- Connectors with no contract: before starting, propose what should pass along them with set_strategy_contracts (the user approves it). Light Code checks every required item after each answer, asks the specialist again for what is missing, and tells you if it is still missing - pass on what arrived, and say what did not.", "- In a back-and-forth, Light Code counts the rounds and tells you after each answer where the loop stands; it refuses a round past the maximum. If the maximum is reached without the condition, stop and tell the user what is still open rather than working around it.", "- A question from the user that is not part of the strategy is answered normally.");
39593
39594
  return lines2.join("\n");
39594
39595
  }
39595
39596
  function readVerdict(answer) {
@@ -39754,6 +39755,48 @@ function askForMissing(missing, previous) {
39754
39755
  previous.length > 6e3 ? `${previous.slice(0, 6e3)}\u2026` : previous
39755
39756
  ].join("\n");
39756
39757
  }
39758
+ function handOverSources(strategy, role) {
39759
+ const mine = strategy.nodes.filter((node) => node.role === role);
39760
+ if (mine.length === 0)
39761
+ return [];
39762
+ const ids = new Set(mine.map((node) => node.id));
39763
+ const groups = new Set(mine.map((node) => node.group).filter((group) => group !== void 0));
39764
+ const into = (edge) => ids.has(edge.to) || groups.has(edge.to);
39765
+ const sources = /* @__PURE__ */ new Set();
39766
+ for (const edge of strategy.edges) {
39767
+ if (into(edge))
39768
+ for (const node of endpointNodes(strategy, edge.from))
39769
+ sources.add(node.role);
39770
+ if (edge.twoWay === true && (ids.has(edge.from) || groups.has(edge.from)))
39771
+ for (const node of endpointNodes(strategy, edge.to))
39772
+ sources.add(node.role);
39773
+ }
39774
+ sources.delete(role);
39775
+ return [...sources];
39776
+ }
39777
+ var SUMMARY_HEADING = "Summary for the main agent";
39778
+ var SUMMARY_REQUEST = `Your full answer is kept and passed on to the next step of the strategy directly. End it with a section headed "${SUMMARY_HEADING}:" - at most eight short lines: what you did or found, any decision the main agent must make, and anything blocking. Only that section reaches the main agent.`;
39779
+ var SUMMARY_LIMIT = 2e3;
39780
+ var SHORT_ANSWER = 2500;
39781
+ function answerForMain(answer, role) {
39782
+ const lines2 = answer.split(/\r?\n/);
39783
+ const heading = lines2.findIndex((line) => /^\s*(?:#+\s*)?(?:\*\*)?\s*summary for the main agent\b/i.test(line));
39784
+ if (heading >= 0) {
39785
+ const first = lines2[heading].replace(/^\s*(?:#+\s*)?(?:\*\*)?\s*summary for the main agent\s*:?\s*(?:\*\*)?\s*:?\s*/i, "");
39786
+ const summary = [first, ...lines2.slice(heading + 1)].join("\n").trim();
39787
+ if (summary.length > 0) {
39788
+ const cut = summary.length > SUMMARY_LIMIT ? `${summary.slice(0, SUMMARY_LIMIT)}\u2026` : summary;
39789
+ return `${cut}
39790
+
39791
+ [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.]`;
39792
+ }
39793
+ }
39794
+ if (answer.length <= SHORT_ANSWER)
39795
+ return answer;
39796
+ return `${answer.slice(0, SUMMARY_LIMIT)}\u2026
39797
+
39798
+ [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
+ }
39757
39800
 
39758
39801
  // ../../packages/core/dist/mcp/types.js
39759
39802
  var mcpDenyRuleSchema = external_exports.object({
@@ -41300,6 +41343,20 @@ var configSchema = external_exports.object({
41300
41343
  * and a provider refusing an over-long conversation says so and points there.
41301
41344
  */
41302
41345
  autoCompact: external_exports.boolean(),
41346
+ /**
41347
+ * Start a new chat from a handoff by itself when this one reaches the context limit, instead of compacting it.
41348
+ * Asked for: "a checkbox, when enabled it should auto handoff to new session when context limit is hit". The
41349
+ * handoff note and the user's own messages carry the work over, and the new chat carries on by itself; the old
41350
+ * chat stays in History. Compacting automatically wins when both are ticked - it was asked for first and keeps
41351
+ * the chat. Off unless set to true.
41352
+ */
41353
+ autoHandoff: external_exports.boolean(),
41354
+ /**
41355
+ * No step limit for a chat's replies: the agent runs until it finishes, is stopped, or fails the same way three times
41356
+ * in a row. Asked for, with the Anti Hallucinator watching and guiding it. Scheduled runs keep `maxIterations` -
41357
+ * nobody is there to press Stop. Off unless set to true.
41358
+ */
41359
+ unlimitedSteps: external_exports.boolean(),
41303
41360
  /**
41304
41361
  * Model requests that fail or go silent. `stallSeconds`: how long a request may send nothing at
41305
41362
  * all before it is stopped and sent again (0 = never; default 300). `retries`: how many times a
@@ -46705,7 +46762,7 @@ ${withBudget}` : withBudget;
46705
46762
 
46706
46763
  // ../../packages/core/dist/tools/askAgent.js
46707
46764
  var paramsSchema3 = external_exports.object({
46708
- role: external_exports.string().describe(`Which specialist to ask: ${AGENT_ROLES.join(", ")}. Only the ones assigned in Settings \u2192 Agents can answer.`),
46765
+ role: external_exports.string().describe(`Which specialist to ask: ${AGENT_ROLES.join(", ")}, or a custom role from Settings \u2192 Agents by its id. Only the ones assigned there can answer.`),
46709
46766
  question: external_exports.string().min(1).describe("The question, with the code, error or output needed to answer it. The specialist cannot see this conversation or read files \u2014 paste what matters."),
46710
46767
  files: external_exports.array(external_exports.string()).optional().describe("Workspace-relative paths you are working in, so it knows what you are looking at.")
46711
46768
  });
@@ -46730,11 +46787,11 @@ Files named as relevant: ${params3.files.join(", ")}` : "")
46730
46787
  },
46731
46788
  async execute(params3, context) {
46732
46789
  const team = options.agents();
46733
- const role = params3.role.trim().toLowerCase();
46734
- if (!isAgentRole(role)) {
46790
+ const agent = find(team, params3.role);
46791
+ const role = agent?.role ?? params3.role.trim().toLowerCase();
46792
+ if (agent === void 0 && !isAgentRole(role)) {
46735
46793
  return { content: unknownRole(role, team), isError: true };
46736
46794
  }
46737
- const agent = find(team, role);
46738
46795
  if (agent === void 0) {
46739
46796
  return {
46740
46797
  content: `No ${role} is assigned. ${describeTeam(team)} Assign one in Settings \u2192 Agents, or ask a different role.`,
@@ -46778,11 +46835,13 @@ ${trailerFor(agent, team)}`
46778
46835
  };
46779
46836
  }
46780
46837
  function find(team, role) {
46781
- const wanted = role.trim().toLowerCase();
46782
- return team.find((agent) => agent.role === wanted);
46838
+ const squash = (text2) => text2.trim().toLowerCase().replace(/[\s_-]+/g, "-");
46839
+ const wanted = squash(role);
46840
+ return team.find((agent) => agent.role === wanted) ?? team.find((agent) => squash(agent.name) === wanted);
46783
46841
  }
46784
46842
  function unknownRole(role, team) {
46785
- return `There is no "${role}" role. The roles are: ${AGENT_ROLES.join(", ")}. ${describeTeam(team)}`;
46843
+ const roles = [.../* @__PURE__ */ new Set([...AGENT_ROLES, ...team.map((agent) => agent.role)])];
46844
+ return `There is no "${role}" role. The roles are: ${roles.join(", ")}. ${describeTeam(team)}`;
46786
46845
  }
46787
46846
  function describeTeam(team) {
46788
46847
  const usable = team.filter((agent) => agent.available).map((agent) => agent.role);
@@ -61488,14 +61547,17 @@ async function sameFile(a, b) {
61488
61547
  return false;
61489
61548
  }
61490
61549
  }
61491
- async function loadSkills(dirs) {
61550
+ async function loadSkills(dirs, onFolder) {
61492
61551
  const ordered = (typeof dirs === "string" ? [dirs] : dirs).map((dir) => import_node_path21.default.resolve(dir));
61493
61552
  const unique = ordered.filter((dir, index) => ordered.indexOf(dir) === index);
61494
61553
  const skills = [];
61495
61554
  const issues = [];
61496
61555
  const claimed = /* @__PURE__ */ new Map();
61497
61556
  for (const dir of unique) {
61557
+ onFolder?.(dir);
61558
+ const started = Date.now();
61498
61559
  const loaded = await loadOneDirectory(dir);
61560
+ onFolder?.(dir, Date.now() - started);
61499
61561
  issues.push(...loaded.issues);
61500
61562
  for (const skill of loaded.skills) {
61501
61563
  const winner = claimed.get(skill.name);
@@ -62197,7 +62259,7 @@ var SHARE_SECTIONS = [
62197
62259
  id: "workspace",
62198
62260
  label: "Workspace behaviour",
62199
62261
  description: "Mode, step cap, automatic compaction, retries, folders tools may read, and folders hidden from the @ picker.",
62200
- keys: ["modeId", "maxIterations", "autoCompact", "connection", "filesystem"],
62262
+ keys: ["modeId", "maxIterations", "autoCompact", "autoHandoff", "unlimitedSteps", "connection", "filesystem"],
62201
62263
  machineSpecific: true
62202
62264
  },
62203
62265
  {
@@ -62678,7 +62740,7 @@ function describeIssue(issue2) {
62678
62740
  return `"${issue2.name}" was declined, so it is not loaded. Restore it to review it again.`;
62679
62741
  }
62680
62742
  }
62681
- async function loadRegistries(dirs, worker, logger, declined, trusted) {
62743
+ async function loadRegistries(dirs, worker, logger, declined, trusted, onFolder) {
62682
62744
  const ordered = dirs.map((dir) => import_node_path25.default.resolve(dir));
62683
62745
  const seen = /* @__PURE__ */ new Set();
62684
62746
  const unique = ordered.filter((dir) => {
@@ -62693,7 +62755,10 @@ async function loadRegistries(dirs, worker, logger, declined, trusted) {
62693
62755
  const approvedElsewhere = [];
62694
62756
  const claimed = /* @__PURE__ */ new Map();
62695
62757
  for (const dir of unique) {
62758
+ onFolder?.(dir);
62759
+ const started = Date.now();
62696
62760
  const loaded = await loadRegistry(dir, worker, logger, declined, trusted);
62761
+ onFolder?.(dir, Date.now() - started);
62697
62762
  issues.push(...loaded.issues);
62698
62763
  approvedElsewhere.push(...loaded.approvedElsewhere ?? []);
62699
62764
  for (const tool of loaded.tools) {
@@ -63404,6 +63469,18 @@ var PythonManager = class {
63404
63469
  constructor(options) {
63405
63470
  this.options = options;
63406
63471
  }
63472
+ progressStep;
63473
+ /** Reports the step starting now (undefined when done), and how long the one before took. */
63474
+ progress(step, finished, tookMs) {
63475
+ const before = this.progressStep;
63476
+ if (finished !== void 0 && tookMs !== void 0)
63477
+ this.options.onProgress?.(finished, tookMs);
63478
+ else if (before !== void 0)
63479
+ this.options.onProgress?.(before.step, Date.now() - before.at);
63480
+ this.progressStep = step === void 0 ? void 0 : { step, at: Date.now() };
63481
+ if (step !== void 0)
63482
+ this.options.onProgress?.(step);
63483
+ }
63407
63484
  /**
63408
63485
  * Applies config and brings the environment up if it is on.
63409
63486
  *
@@ -63453,15 +63530,20 @@ var PythonManager = class {
63453
63530
  this.indexUrl = config2.indexUrl;
63454
63531
  this.extraIndexUrls = config2.extraIndexUrls ?? [];
63455
63532
  this.offline = config2.offline === true;
63456
- if (this.uv === void 0)
63533
+ if (this.uv === void 0) {
63534
+ this.progress("checking for uv");
63457
63535
  this.uv = await detectUv(config2.uvPath);
63536
+ }
63458
63537
  if (this.uv === void 0) {
63538
+ this.progress("finding a Python interpreter");
63459
63539
  await this.startWithoutUv(config2, this.options.workspaceRoot);
63540
+ this.progress(void 0);
63460
63541
  return;
63461
63542
  }
63462
63543
  try {
63463
63544
  const env2 = await this.childEnv();
63464
63545
  let interpreter;
63546
+ this.progress("checking the virtual environment");
63465
63547
  if (config2.venvPath !== void 0 && config2.venvPath.trim().length > 0) {
63466
63548
  this.venvPath = config2.venvPath.trim();
63467
63549
  this.venvSource = "configured";
@@ -63500,6 +63582,7 @@ var PythonManager = class {
63500
63582
  ...this.readCredential() !== void 0 ? { readCredential: this.readCredential() } : {}
63501
63583
  });
63502
63584
  await this.refresh();
63585
+ this.progress(void 0);
63503
63586
  this.ready = true;
63504
63587
  this.detail = this.venvSource === "workspace" ? `Ready \u2014 using this project's virtualenv${this.venvIsUvManaged ? " (uv-managed)" : ""}. Tool dependencies install into it.` : this.venvSource === "configured" ? `Ready \u2014 using the configured virtualenv. uv ${this.uv.version}.` : `Ready \u2014 created a private virtualenv. uv ${this.uv.version}.`;
63505
63588
  } catch (error51) {
@@ -63598,7 +63681,7 @@ var PythonManager = class {
63598
63681
  async refresh() {
63599
63682
  if (!this.enabled || this.toolsDir.length === 0)
63600
63683
  return;
63601
- const loaded = await loadRegistries(this.toolDirectories(), this.worker, this.options.logger, this.declinedTools, this.options.machineApprovals);
63684
+ const loaded = await loadRegistries(this.toolDirectories(), this.worker, this.options.logger, this.declinedTools, this.options.machineApprovals, (dir, tookMs) => tookMs === void 0 ? this.progress(`reading tools in ${dir}`) : this.progress(void 0, `reading tools in ${dir}`, tookMs));
63602
63685
  if (loaded.approvedElsewhere !== void 0)
63603
63686
  this.options.onApprovedElsewhere?.(loaded.approvedElsewhere);
63604
63687
  this.registered = loaded.tools;
@@ -64530,6 +64613,11 @@ async function prepareModelMessages(conversation, provider, tools, options, even
64530
64613
  const contextWindow = options.contextWindow ?? 0;
64531
64614
  const ratio = calibrationFor(options.usageKey ?? "");
64532
64615
  let messages = repairUnansweredToolCalls(conversation.toModelMessages());
64616
+ if (options.onContextFull !== void 0 && options.autoCompact === false && options.compactionEnabled !== false && contextWindow > 0 && options.contextWindowKnown !== false && meter !== void 0) {
64617
+ const estimated = scaleBreakdown(computeBreakdown(messages, tools, contextWindow), ratio).total;
64618
+ if (shouldCompact(messages, estimated, contextWindow, { ...options.compaction ?? {}, minimumToCompact: 0 }))
64619
+ meter.contextFull = true;
64620
+ }
64533
64621
  if (options.compactionEnabled !== false && options.autoCompact !== false && contextWindow > 0 && options.contextWindowKnown !== false) {
64534
64622
  const estimated = scaleBreakdown(computeBreakdown(messages, tools, contextWindow), ratio).total;
64535
64623
  if (shouldCompact(messages, estimated, contextWindow, options.compaction ?? {})) {
@@ -64736,6 +64824,11 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
64736
64824
  streamOptions.signal = options.signal;
64737
64825
  const meter = { estimated: 0, dropped: 0 };
64738
64826
  const modelMessages = await prepareModelMessages(conversation, provider, tools, options, events, meter);
64827
+ if (meter.contextFull === true && options.onContextFull !== void 0) {
64828
+ options.onContextFull();
64829
+ events.onDone();
64830
+ return;
64831
+ }
64739
64832
  const stallSeconds = options.stallSeconds ?? DEFAULT_STALL_SECONDS;
64740
64833
  const maxRetries = Math.max(0, options.retries ?? DEFAULT_RETRIES);
64741
64834
  const cancelled = () => options.signal?.aborted === true;
@@ -64777,6 +64870,11 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
64777
64870
  events.onContextWindowLearned?.(statedWindow);
64778
64871
  }
64779
64872
  if (streamError !== void 0 && assistantText.length === 0 && toolCall === void 0 && options.autoCompact === false && isContextOverflow(streamError)) {
64873
+ if (options.onContextFull !== void 0) {
64874
+ options.onContextFull();
64875
+ events.onDone();
64876
+ return;
64877
+ }
64780
64878
  events.onError(`${streamError}
64781
64879
 
64782
64880
  The conversation is longer than this model accepts. Press **Compact now** under the token bar to summarise the older part (the saved transcript keeps everything), then send again - or tick "Compact automatically" there to have this done for you. Or press **New chat with a handoff** (beside + at the top): the assistant writes up this chat - goal, decisions, what is done, next steps - and a new chat starts from it, a clean start that keeps the thread.`);
@@ -76959,6 +77057,247 @@ function describeRun2(run3, now = /* @__PURE__ */ new Date()) {
76959
77057
  return `${parts.join(" \xB7 ")} - ${how}`;
76960
77058
  }
76961
77059
 
77060
+ // ../../packages/core/dist/atlassian/autosysInsight.js
77061
+ function quantile(sorted, q) {
77062
+ if (sorted.length === 0)
77063
+ return 0;
77064
+ const position = (sorted.length - 1) * q;
77065
+ const below = Math.floor(position);
77066
+ const above = Math.ceil(position);
77067
+ const low = sorted[below] ?? 0;
77068
+ const high = sorted[above] ?? low;
77069
+ return low + (high - low) * (position - below);
77070
+ }
77071
+ function runDurations(runs) {
77072
+ const finished = runs.filter((run3) => run3.start !== void 0 && run3.end !== void 0 && run3.end > run3.start);
77073
+ const succeeded = finished.filter((run3) => run3.status.toUpperCase() === "SUCCESS");
77074
+ const chosen = succeeded.length > 0 ? succeeded : finished;
77075
+ return { durations: chosen.map((run3) => (run3.end ?? 0) - (run3.start ?? 0)), onlySuccess: succeeded.length > 0 };
77076
+ }
77077
+ function durationStats(durations) {
77078
+ if (durations.length === 0)
77079
+ return void 0;
77080
+ const sorted = [...durations].sort((a, b) => a - b);
77081
+ return {
77082
+ count: sorted.length,
77083
+ meanMs: sorted.reduce((sum, value) => sum + value, 0) / sorted.length,
77084
+ medianMs: quantile(sorted, 0.5),
77085
+ p10Ms: quantile(sorted, 0.1),
77086
+ p90Ms: quantile(sorted, 0.9),
77087
+ minMs: sorted[0] ?? 0,
77088
+ maxMs: sorted[sorted.length - 1] ?? 0
77089
+ };
77090
+ }
77091
+ function formatDuration(ms) {
77092
+ const seconds = Math.max(0, Math.round(ms / 1e3));
77093
+ if (seconds < 60)
77094
+ return `${String(seconds)} s`;
77095
+ const minutes = Math.floor(seconds / 60);
77096
+ if (minutes < 60)
77097
+ return `${String(minutes)} min ${String(seconds % 60).padStart(2, "0")} s`;
77098
+ const hours = Math.floor(minutes / 60);
77099
+ return `${String(hours)} h ${String(minutes % 60).padStart(2, "0")} min`;
77100
+ }
77101
+ function localTime(at, now = /* @__PURE__ */ new Date()) {
77102
+ const date5 = new Date(at);
77103
+ const time4 = `${String(date5.getHours()).padStart(2, "0")}:${String(date5.getMinutes()).padStart(2, "0")}`;
77104
+ if (date5.toDateString() === now.toDateString())
77105
+ return time4;
77106
+ const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
77107
+ if (date5.toDateString() === tomorrow.toDateString())
77108
+ return `${time4} tomorrow`;
77109
+ return `${date5.getFullYear()}-${String(date5.getMonth() + 1).padStart(2, "0")}-${String(date5.getDate()).padStart(2, "0")} ${time4}`;
77110
+ }
77111
+ function localZone(now = /* @__PURE__ */ new Date()) {
77112
+ try {
77113
+ return new Intl.DateTimeFormat(void 0, { timeZoneName: "short" }).formatToParts(now).find((part) => part.type === "timeZoneName")?.value ?? "local time";
77114
+ } catch {
77115
+ return "local time";
77116
+ }
77117
+ }
77118
+ function etaFor(startedAt, stats, now = Date.now()) {
77119
+ const elapsedMs = Math.max(0, now - startedAt);
77120
+ return {
77121
+ elapsedMs,
77122
+ expected: startedAt + stats.medianMs,
77123
+ latest: startedAt + Math.max(stats.p90Ms, stats.medianMs),
77124
+ overrun: elapsedMs > Math.max(stats.p90Ms, stats.medianMs)
77125
+ };
77126
+ }
77127
+ function minuteOfDay(at) {
77128
+ const date5 = new Date(at);
77129
+ return date5.getHours() * 60 + date5.getMinutes() + date5.getSeconds() / 60;
77130
+ }
77131
+ function clockOfMinute(minute) {
77132
+ const wrapped = (Math.round(minute) % 1440 + 1440) % 1440;
77133
+ return `${String(Math.floor(wrapped / 60)).padStart(2, "0")}:${String(wrapped % 60).padStart(2, "0")}`;
77134
+ }
77135
+ function timeOfDayStats(moments) {
77136
+ if (moments.length === 0)
77137
+ return void 0;
77138
+ const minutes = moments.map(minuteOfDay);
77139
+ const angle = (minute) => minute / 1440 * 2 * Math.PI;
77140
+ const sin = minutes.reduce((sum, minute) => sum + Math.sin(angle(minute)), 0);
77141
+ const cos = minutes.reduce((sum, minute) => sum + Math.cos(angle(minute)), 0);
77142
+ const centre = (Math.atan2(sin, cos) / (2 * Math.PI) * 1440 % 1440 + 1440) % 1440;
77143
+ const offsets = minutes.map((minute) => {
77144
+ let offset = minute - centre;
77145
+ if (offset > 720)
77146
+ offset -= 1440;
77147
+ if (offset < -720)
77148
+ offset += 1440;
77149
+ return offset;
77150
+ }).sort((a, b) => a - b);
77151
+ const early = centre + quantile(offsets, 0.1);
77152
+ const late = centre + quantile(offsets, 0.9);
77153
+ return { count: minutes.length, typical: centre + quantile(offsets, 0.5), early, late, spreadMinutes: late - early };
77154
+ }
77155
+ function ownStarts(runs) {
77156
+ return runs.filter((run3) => run3.start !== void 0 && !(run3.tryNum !== void 0 && run3.tryNum > 1) && run3.how !== "manual" && run3.how !== "retry").map((run3) => run3.start ?? 0);
77157
+ }
77158
+ async function tracePredecessors(source, root, limits = {}) {
77159
+ const maxJobs = limits.maxJobs ?? 200;
77160
+ const maxDepth = limits.maxDepth ?? 30;
77161
+ const nodes = /* @__PURE__ */ new Map();
77162
+ let level2 = [root];
77163
+ let depth = 0;
77164
+ let truncated = false;
77165
+ while (level2.length > 0 && depth <= maxDepth) {
77166
+ const fresh = [...new Set(level2)].filter((name) => !nodes.has(name.toLowerCase()));
77167
+ const room = maxJobs - nodes.size;
77168
+ if (fresh.length > room)
77169
+ truncated = true;
77170
+ const batch = fresh.slice(0, Math.max(0, room));
77171
+ const read = await Promise.all(batch.map(async (name) => {
77172
+ const [definition, state] = await Promise.all([source.definition(name).catch(() => void 0), source.status(name).catch(() => ({ status: "unknown" }))]);
77173
+ if (definition === void 0)
77174
+ return { name, status: state.status, top: false, unreadable: "definition not readable", predecessors: [] };
77175
+ const condition2 = source.field(definition, "condition");
77176
+ const box = source.field(definition, "boxName", "box_name");
77177
+ const references = [...box !== void 0 ? [{ kind: "box", job: box }] : [], ...condition2 !== void 0 ? source.parseConditions(condition2) : []];
77178
+ const predecessors = await Promise.all(references.map(async (reference) => {
77179
+ if (reference.instance !== void 0)
77180
+ return { reference, met: void 0, onOtherInstance: true };
77181
+ const other = await source.status(reference.job).catch(() => ({ status: "unknown" }));
77182
+ const met = reference.kind === "box" ? other.status.toUpperCase() === "RUNNING" : source.conditionMet(reference.kind, other.status);
77183
+ return { reference, met, onOtherInstance: false };
77184
+ }));
77185
+ return {
77186
+ name,
77187
+ status: state.status,
77188
+ ...state.lastStart !== void 0 ? { lastStart: state.lastStart } : {},
77189
+ ...state.lastEnd !== void 0 ? { lastEnd: state.lastEnd } : {},
77190
+ ...condition2 !== void 0 ? { condition: condition2 } : {},
77191
+ ...box !== void 0 ? { box } : {},
77192
+ ...source.schedule(definition) !== void 0 ? { schedule: source.schedule(definition) } : {},
77193
+ top: condition2 === void 0 && box === void 0,
77194
+ predecessors
77195
+ };
77196
+ }));
77197
+ for (const node of read)
77198
+ nodes.set(node.name.toLowerCase(), node);
77199
+ const next = [];
77200
+ for (const node of read)
77201
+ for (const each of node.predecessors)
77202
+ if (!each.onOtherInstance && !nodes.has(each.reference.job.toLowerCase()))
77203
+ next.push(each.reference.job);
77204
+ if (next.length > 0 && depth === maxDepth)
77205
+ truncated = true;
77206
+ level2 = next;
77207
+ depth += next.length > 0 ? 1 : 0;
77208
+ }
77209
+ const tops = [...nodes.values()].filter((node) => node.top).map((node) => node.name);
77210
+ return { root, nodes, tops, truncated, depth };
77211
+ }
77212
+ var KIND_WORDS = { s: "success of", f: "failure of", d: "completion of", n: "not running:", t: "termination of", e: "exit code of", box: "inside box" };
77213
+ function describeTrace(trace, extra) {
77214
+ const lines2 = [];
77215
+ const shown2 = /* @__PURE__ */ new Set();
77216
+ const line = (node, name, indent2, via) => {
77217
+ const key3 = name.toLowerCase();
77218
+ if (node === void 0) {
77219
+ lines2.push(`${indent2}${via}${name} - not traced (limit reached)`);
77220
+ return;
77221
+ }
77222
+ if (shown2.has(key3)) {
77223
+ lines2.push(`${indent2}${via}${name} [${node.status}] (traced above)`);
77224
+ return;
77225
+ }
77226
+ shown2.add(key3);
77227
+ const facts = [
77228
+ `[${node.status}]`,
77229
+ node.lastStart !== void 0 ? `last start ${node.lastStart}` : void 0,
77230
+ node.lastEnd !== void 0 ? `last end ${node.lastEnd}` : void 0,
77231
+ node.top ? `TOP${node.schedule !== void 0 ? ` - starts ${node.schedule}` : " - no condition, no box, no start schedule (started by hand or by another instance)"}` : void 0,
77232
+ node.unreadable,
77233
+ extra?.(node)
77234
+ ].filter((part) => part !== void 0);
77235
+ lines2.push(`${indent2}${via}${name} ${facts.join(" \xB7 ")}`);
77236
+ if (node.condition !== void 0)
77237
+ lines2.push(`${indent2} condition: ${node.condition}`);
77238
+ for (const each of node.predecessors) {
77239
+ const word = KIND_WORDS[each.reference.kind] ?? each.reference.kind;
77240
+ const state = each.onOtherInstance ? "on another instance - not checked" : each.met === void 0 ? "check the exit code" : each.met ? "met" : "NOT met";
77241
+ const label = `${word} (${state}${each.reference.comparison !== void 0 ? `, ${each.reference.comparison}` : ""}) `;
77242
+ if (each.onOtherInstance) {
77243
+ lines2.push(`${indent2} ${label}${each.reference.job}^${each.reference.instance ?? ""}`);
77244
+ continue;
77245
+ }
77246
+ line(trace.nodes.get(each.reference.job.toLowerCase()), each.reference.job, `${indent2} `, label);
77247
+ }
77248
+ };
77249
+ line(trace.nodes.get(trace.root.toLowerCase()), trace.root, "", "");
77250
+ const all = [...trace.nodes.values()];
77251
+ const notMet = all.flatMap((node) => node.predecessors.filter((each) => each.met === false).map((each) => `${node.name} waits on ${KIND_WORDS[each.reference.kind] ?? each.reference.kind} ${each.reference.job}`));
77252
+ const failed2 = all.filter((node) => ["FAILURE", "TERMINATED"].includes(node.status.toUpperCase())).map((node) => `${node.name} [${node.status}]`);
77253
+ lines2.push("", `${String(all.length - 1)} predecessor job(s) over ${String(trace.depth)} level(s). Topmost: ${trace.tops.filter((name) => name.toLowerCase() !== trace.root.toLowerCase()).join(", ") || "none (it is the top itself)"}.`, ...failed2.length > 0 ? [`Failed or terminated: ${failed2.join(", ")}.`] : [], ...notMet.length > 0 ? ["Not met now:", ...notMet.slice(0, 40).map((entry) => `- ${entry}`)] : [], ...trace.truncated ? ["The walk stopped at its limit; raise maxJobs or maxDepth to go further."] : []);
77254
+ return lines2.join("\n");
77255
+ }
77256
+ function expectedStartFromDefinitions(trace, durations, startMinutes) {
77257
+ const memo = /* @__PURE__ */ new Map();
77258
+ const missing = /* @__PURE__ */ new Set();
77259
+ const via = /* @__PURE__ */ new Map();
77260
+ const visiting = /* @__PURE__ */ new Set();
77261
+ const startOf = (name) => {
77262
+ const key3 = name.toLowerCase();
77263
+ if (memo.has(key3))
77264
+ return memo.get(key3);
77265
+ if (visiting.has(key3))
77266
+ return void 0;
77267
+ visiting.add(key3);
77268
+ const node = trace.nodes.get(key3);
77269
+ let result;
77270
+ const own = startMinutes.get(key3);
77271
+ if (own !== void 0) {
77272
+ result = own;
77273
+ via.set(key3, [`${name} starts at ${clockOfMinute(own)}`]);
77274
+ } else if (node === void 0 || node.top) {
77275
+ missing.add(`${name} (no start time)`);
77276
+ } else {
77277
+ const finishes = node.predecessors.filter((each) => !each.onOtherInstance && ["s", "d", "box"].includes(each.reference.kind)).map((each) => {
77278
+ const before = startOf(each.reference.job);
77279
+ if (each.reference.kind === "box")
77280
+ return { name: each.reference.job, at: before };
77281
+ const took = durations.get(each.reference.job.toLowerCase());
77282
+ if (took === void 0)
77283
+ missing.add(`${each.reference.job} (no run history)`);
77284
+ return { name: each.reference.job, at: before === void 0 || took === void 0 ? void 0 : before + took / 6e4 };
77285
+ });
77286
+ if (finishes.length > 0 && finishes.every((each) => each.at !== void 0)) {
77287
+ const last = finishes.reduce((latest, each) => (each.at ?? 0) > (latest.at ?? 0) ? each : latest);
77288
+ result = last.at;
77289
+ via.set(key3, [...via.get(last.name.toLowerCase()) ?? [], `${name} after ${last.name} (${clockOfMinute(last.at ?? 0)})`]);
77290
+ } else if (finishes.length === 0)
77291
+ missing.add(`${name} (waits only on conditions that do not say when)`);
77292
+ }
77293
+ visiting.delete(key3);
77294
+ memo.set(key3, result);
77295
+ return result;
77296
+ };
77297
+ const start = startOf(trace.root);
77298
+ return { start, missing: [...missing], via: via.get(trace.root.toLowerCase()) ?? [] };
77299
+ }
77300
+
76962
77301
  // ../../packages/core/dist/atlassian/autosys.js
76963
77302
  var DEFAULT_AUTOSYS_PATHS = {
76964
77303
  jobs: "/job?filter={filter:name}",
@@ -77876,7 +78215,7 @@ function conditionMet(kind, status2) {
77876
78215
  return void 0;
77877
78216
  }
77878
78217
  }
77879
- var KIND_WORDS = {
78218
+ var KIND_WORDS2 = {
77880
78219
  s: "success of",
77881
78220
  f: "failure of",
77882
78221
  d: "completion of",
@@ -77937,12 +78276,12 @@ function createAutosysDependenciesTool(options) {
77937
78276
  lines2.push(`${indent2}condition: ${condition2}`);
77938
78277
  for (const reference of parseConditions(condition2)) {
77939
78278
  if (reference.instance !== void 0) {
77940
- lines2.push(`${indent2}- ${KIND_WORDS[reference.kind]} ${reference.job} on instance ${reference.instance} (another instance: status not checked)`);
78279
+ lines2.push(`${indent2}- ${KIND_WORDS2[reference.kind]} ${reference.job} on instance ${reference.instance} (another instance: status not checked)`);
77941
78280
  continue;
77942
78281
  }
77943
78282
  const status2 = await statusOf(reference.job);
77944
78283
  const met = conditionMet(reference.kind, status2);
77945
- lines2.push(`${indent2}- ${KIND_WORDS[reference.kind]} ${reference.job}${reference.comparison !== void 0 ? ` ${reference.comparison}` : ""}: ${status2} \u2014 ${met === void 0 ? "check the exit code" : met ? "met" : "NOT met"}`);
78284
+ lines2.push(`${indent2}- ${KIND_WORDS2[reference.kind]} ${reference.job}${reference.comparison !== void 0 ? ` ${reference.comparison}` : ""}: ${status2} \u2014 ${met === void 0 ? "check the exit code" : met ? "met" : "NOT met"}`);
77946
78285
  if (met === false && level2 < (params3.depth ?? 3))
77947
78286
  await walk(reference.job, level2 + 1, `${indent2} `);
77948
78287
  }
@@ -78257,13 +78596,218 @@ function createAutosysRunsTool(options) {
78257
78596
  }
78258
78597
  };
78259
78598
  }
78599
+ async function recentRuns(client, name, days) {
78600
+ const history = await client.runHistory(name);
78601
+ if (history === void 0)
78602
+ return void 0;
78603
+ const since2 = Date.now() - days * 864e5;
78604
+ return history.map(toPastRun).filter((run3) => run3.start === void 0 || run3.start >= since2).sort((a, b) => (a.start ?? 0) - (b.start ?? 0));
78605
+ }
78606
+ var NO_HISTORY = "This server did not answer for run history at the configured address - set config:autosys (paths.runHistory).";
78607
+ var runStatsSchema = external_exports.object({
78608
+ jobs: external_exports.array(external_exports.string().min(1)).min(1).max(30).describe("Exact job names."),
78609
+ days: external_exports.number().int().min(1).max(365).optional().describe("How far back to look in the run history. Default 30.")
78610
+ });
78611
+ function createAutosysRunStatsTool(options) {
78612
+ return {
78613
+ name: "autosys_run_stats",
78614
+ group: "read",
78615
+ description: 'How long AutoSys jobs usually run, from their run history: typical (median), average, fastest and slowest, and nine runs in ten - successful runs only when there are any. For a job RUNNING now, an ETA in local time: when it should finish at its typical run time, the likely latest, and whether it is already running longer than usual. Answers "how long does PAY_LOAD take?" and "when will it finish?".',
78616
+ parametersSchema: runStatsSchema,
78617
+ async execute(params3) {
78618
+ try {
78619
+ const client = await options.client();
78620
+ const days = params3.days ?? 30;
78621
+ const now = /* @__PURE__ */ new Date();
78622
+ let historyMissing = false;
78623
+ const sections = await inBatches2([...new Set(params3.jobs.map((job) => job.trim()))], async (name) => {
78624
+ try {
78625
+ const [runs, current] = await Promise.all([recentRuns(client, name, days), client.runInfo(name).catch(() => [])]);
78626
+ if (runs === void 0)
78627
+ historyMissing = true;
78628
+ const latest = current[0];
78629
+ const { durations, onlySuccess } = runDurations(runs ?? []);
78630
+ const stats = durationStats(durations);
78631
+ const lines2 = [`${name}: now ${latest?.status ?? "unknown"}${latest?.lastStart !== void 0 ? `, last started ${latest.lastStart}` : ""}`];
78632
+ if (stats === void 0) {
78633
+ lines2.push(` no finished run in the last ${String(days)} days${runs === void 0 ? " (no run history here)" : ""} - nothing to base a run time on.`);
78634
+ } else {
78635
+ lines2.push(` over ${String(stats.count)} ${onlySuccess ? "successful" : "finished (none succeeded)"} run(s) in ${String(days)} days: typically ${formatDuration(stats.medianMs)}, average ${formatDuration(stats.meanMs)}, fastest ${formatDuration(stats.minMs)}, slowest ${formatDuration(stats.maxMs)}; nine in ten within ${formatDuration(stats.p90Ms)}.`);
78636
+ }
78637
+ const startedAt = parseAutosysTime(latest?.lastStart);
78638
+ if (latest !== void 0 && latest.status.toUpperCase() === "RUNNING" && startedAt !== void 0) {
78639
+ if (stats === void 0) {
78640
+ lines2.push(` running for ${formatDuration(now.getTime() - startedAt)}; no history to estimate when it will finish.`);
78641
+ } else {
78642
+ const eta = etaFor(startedAt, stats, now.getTime());
78643
+ lines2.push(` RUNNING for ${formatDuration(eta.elapsedMs)} (since ${localTime(startedAt, now)}). ` + (eta.overrun ? `Already longer than nine runs in ten (${formatDuration(stats.p90Ms)}) - running long; it should have finished by ${localTime(eta.latest, now)}.` : `ETA ${localTime(eta.expected, now)} at its typical run time${eta.expected < now.getTime() ? " (already past)" : ""}, by ${localTime(eta.latest, now)} at the latest in nine runs in ten.`));
78644
+ }
78645
+ }
78646
+ return lines2.join("\n");
78647
+ } catch (error51) {
78648
+ return `${name}: ${error51 instanceof Error ? error51.message : String(error51)}`;
78649
+ }
78650
+ });
78651
+ return { content: [...sections, `Times are local (${localZone(now)}).`, ...historyMissing ? [NO_HISTORY] : []].join("\n\n") };
78652
+ } catch (error51) {
78653
+ return errorResult3(error51);
78654
+ }
78655
+ }
78656
+ };
78657
+ }
78658
+ function predecessorSource(client) {
78659
+ const definitions = /* @__PURE__ */ new Map();
78660
+ const statuses = /* @__PURE__ */ new Map();
78661
+ return {
78662
+ definitions,
78663
+ async definition(name) {
78664
+ const key3 = name.toLowerCase();
78665
+ if (!definitions.has(key3))
78666
+ definitions.set(key3, await client.job(name).catch(() => void 0));
78667
+ return definitions.get(key3);
78668
+ },
78669
+ status(name) {
78670
+ const key3 = name.toLowerCase();
78671
+ let found2 = statuses.get(key3);
78672
+ if (found2 === void 0) {
78673
+ found2 = client.runInfo(name).then((runs) => {
78674
+ const run3 = runs[0];
78675
+ return run3 === void 0 ? { status: "unknown" } : { status: run3.status, ...run3.lastStart !== void 0 ? { lastStart: run3.lastStart } : {}, ...run3.lastEnd !== void 0 ? { lastEnd: run3.lastEnd } : {} };
78676
+ }).catch(() => ({ status: "unknown" }));
78677
+ statuses.set(key3, found2);
78678
+ }
78679
+ return found2;
78680
+ },
78681
+ parseConditions,
78682
+ conditionMet: (kind, status2) => conditionMet(kind, status2),
78683
+ field,
78684
+ schedule(definition) {
78685
+ const schedule = jobSchedule(definition);
78686
+ if (schedule === void 0)
78687
+ return void 0;
78688
+ const at = [
78689
+ ...schedule.times.length > 0 ? [`at ${schedule.times.join(", ")}`] : [],
78690
+ ...schedule.minutesPastHour.length > 0 ? [`hourly at :${schedule.minutesPastHour.map((m) => String(m).padStart(2, "0")).join(", :")}`] : [],
78691
+ ...schedule.runCalendar !== void 0 ? [`on calendar ${schedule.runCalendar}`] : []
78692
+ ];
78693
+ return `${at.join(" ")} ${describeDays(schedule.days)}${schedule.timezone !== void 0 ? ` (${schedule.timezone})` : ""}`;
78694
+ }
78695
+ };
78696
+ }
78697
+ var usualStartSchema = external_exports.object({
78698
+ jobs: external_exports.array(external_exports.string().min(1)).min(1).max(20).describe("Exact job names."),
78699
+ days: external_exports.number().int().min(1).max(365).optional().describe("How far back to look in the run history. Default 30."),
78700
+ fromDefinitions: external_exports.boolean().optional().describe("For a job started by a condition: also work its start out from its predecessors' definitions and run times. Default true.")
78701
+ });
78702
+ function createAutosysUsualStartTool(options) {
78703
+ return {
78704
+ name: "autosys_usual_start",
78705
+ group: "read",
78706
+ description: `When AutoSys jobs normally start, in local time - especially jobs with no start time of their own, started by a dependency or their box. Two answers: from the job's own run history (the usual time of day around the clock, and the range nine starts in ten fall in; manual starts and retries left out), and from the job definitions (the chain of predecessors up to jobs with start times, each with its typical run time). Answers "what time does PAY_LOAD usually start?".`,
78707
+ parametersSchema: usualStartSchema,
78708
+ async execute(params3) {
78709
+ try {
78710
+ const client = await options.client();
78711
+ const days = params3.days ?? 30;
78712
+ const now = /* @__PURE__ */ new Date();
78713
+ let historyMissing = false;
78714
+ const sections = await inBatches2([...new Set(params3.jobs.map((job) => job.trim()))], async (name) => {
78715
+ try {
78716
+ const source = predecessorSource(client);
78717
+ const definition = await source.definition(name);
78718
+ if (definition === void 0)
78719
+ return `${name}: the definition could not be read.`;
78720
+ const lines2 = [`${name}:`];
78721
+ const own = source.schedule(definition);
78722
+ const condition2 = field(definition, "condition");
78723
+ const box = field(definition, "boxName", "box_name");
78724
+ const startedBy = [condition2 !== void 0 ? `when: ${condition2}` : void 0, box !== void 0 ? `with its box ${box}` : void 0].filter((part) => part !== void 0);
78725
+ lines2.push(own !== void 0 ? ` its definition starts it ${own}.` : ` no start time of its own - started ${startedBy.join(", and ") || "by hand or by another instance"}.`);
78726
+ const [runs, eventRecords] = await Promise.all([recentRuns(client, name, days), client.eventHistory(name).catch(() => void 0)]);
78727
+ if (runs === void 0)
78728
+ historyMissing = true;
78729
+ const classified = classifyRuns(runs ?? [], eventRecords?.map(toJobEvent));
78730
+ const observed = timeOfDayStats(ownStarts(classified));
78731
+ lines2.push(observed === void 0 ? ` observed: no runs in the last ${String(days)} days to go by.` : ` observed over ${String(observed.count)} run(s): usually starts around ${clockOfMinute(observed.typical)}; nine in ten between ${clockOfMinute(observed.early)} and ${clockOfMinute(observed.late)}${observed.spreadMinutes > 180 ? " - spread over hours, so there is no single habit" : ""}${eventRecords === void 0 ? " (manual starts could not be left out: no event history)" : ""}.`);
78732
+ if (own === void 0 && params3.fromDefinitions !== false) {
78733
+ const trace = await tracePredecessors(source, name, { maxJobs: 60, maxDepth: 15 });
78734
+ const durations = /* @__PURE__ */ new Map();
78735
+ const startMinutes = /* @__PURE__ */ new Map();
78736
+ await inBatches2([...trace.nodes.values()], async (node) => {
78737
+ const key3 = node.name.toLowerCase();
78738
+ const found2 = source.definitions.get(key3);
78739
+ const first = found2 === void 0 ? void 0 : jobSchedule(found2)?.times[0];
78740
+ if (first !== void 0 && key3 !== name.toLowerCase()) {
78741
+ const [hour, minute] = first.split(":").map(Number);
78742
+ startMinutes.set(key3, (hour ?? 0) * 60 + (minute ?? 0));
78743
+ }
78744
+ const stats = durationStats(runDurations(await recentRuns(client, node.name, days).catch(() => void 0) ?? []).durations);
78745
+ if (stats !== void 0)
78746
+ durations.set(key3, stats.medianMs);
78747
+ });
78748
+ const expected = expectedStartFromDefinitions(trace, durations, startMinutes);
78749
+ lines2.push(expected.start !== void 0 ? ` from the definitions: about ${clockOfMinute(expected.start)}${expected.start >= 1440 ? " (the next day)" : ""} - ${expected.via.join(" -> ")}.` : ` from the definitions: cannot be worked out - ${expected.missing.slice(0, 6).join("; ") || "no predecessor with a start time"}.`);
78750
+ }
78751
+ return lines2.join("\n");
78752
+ } catch (error51) {
78753
+ return `${name}: ${error51 instanceof Error ? error51.message : String(error51)}`;
78754
+ }
78755
+ });
78756
+ return { content: [...sections, `Times are local (${localZone(now)}).`, ...historyMissing ? [NO_HISTORY] : []].join("\n\n") };
78757
+ } catch (error51) {
78758
+ return errorResult3(error51);
78759
+ }
78760
+ }
78761
+ };
78762
+ }
78763
+ var predecessorsSchema = external_exports.object({
78764
+ job: external_exports.string().min(1).describe("The exact job name."),
78765
+ maxDepth: external_exports.number().int().min(1).max(50).optional().describe("How many levels up to follow. Default 30 - effectively to the top."),
78766
+ maxJobs: external_exports.number().int().min(1).max(500).optional().describe("Stop after reading this many jobs. Default 200."),
78767
+ eta: external_exports.boolean().optional().describe("For predecessors RUNNING now, also say when each should finish (reads their run history). Default false.")
78768
+ });
78769
+ function createAutosysPredecessorsTool(options) {
78770
+ return {
78771
+ name: "autosys_predecessors",
78772
+ group: "read",
78773
+ description: 'Every predecessor of an AutoSys job, recursively up to the topmost jobs, from the job definitions: each job its condition names (met or not) and the box it sits in, then theirs - each with its status, last start and end, and whether its condition is met; topmost jobs with their start schedule. Ends with what is not met and what failed. Answers "what does PAY_LOAD depend on, all the way up, and where is it stuck?". With eta, running predecessors get an ETA in local time.',
78774
+ parametersSchema: predecessorsSchema,
78775
+ async execute(params3) {
78776
+ try {
78777
+ const client = await options.client();
78778
+ const now = /* @__PURE__ */ new Date();
78779
+ const source = predecessorSource(client);
78780
+ const trace = await tracePredecessors(source, params3.job.trim(), { maxJobs: params3.maxJobs ?? 200, maxDepth: params3.maxDepth ?? 30 });
78781
+ const etas = /* @__PURE__ */ new Map();
78782
+ if (params3.eta === true) {
78783
+ const running = [...trace.nodes.values()].filter((node) => node.status.toUpperCase() === "RUNNING" && parseAutosysTime(node.lastStart) !== void 0);
78784
+ await inBatches2(running, async (node) => {
78785
+ const stats = durationStats(runDurations(await recentRuns(client, node.name, 30).catch(() => void 0) ?? []).durations);
78786
+ const started = parseAutosysTime(node.lastStart) ?? now.getTime();
78787
+ if (stats === void 0)
78788
+ return;
78789
+ const eta = etaFor(started, stats, now.getTime());
78790
+ etas.set(node.name.toLowerCase(), eta.overrun ? `running long - nine in ten finish within ${formatDuration(stats.p90Ms)}` : `ETA ${localTime(eta.expected, now)} (latest ${localTime(eta.latest, now)})`);
78791
+ });
78792
+ }
78793
+ return { content: `${describeTrace(trace, (node) => etas.get(node.name.toLowerCase()))}${params3.eta === true ? `
78794
+ Times are local (${localZone(now)}).` : ""}` };
78795
+ } catch (error51) {
78796
+ return errorResult3(error51);
78797
+ }
78798
+ }
78799
+ };
78800
+ }
78260
78801
  function createAutosysTools(options) {
78261
78802
  return [
78262
78803
  createAutosysFindJobsTool(options),
78263
78804
  createAutosysJobTool(options),
78264
78805
  createAutosysStatusTool(options),
78265
78806
  createAutosysRunsTool(options),
78807
+ createAutosysRunStatsTool(options),
78808
+ createAutosysUsualStartTool(options),
78266
78809
  createAutosysDependenciesTool(options),
78810
+ createAutosysPredecessorsTool(options),
78267
78811
  createAutosysLogTool(options),
78268
78812
  createAutosysMachinesTool(options),
78269
78813
  createAutosysGlobalVariablesTool(options),
@@ -86543,6 +87087,13 @@ function wireChatBridge(services) {
86543
87087
  const python = new PythonManager({
86544
87088
  workspaceRoot,
86545
87089
  storageDir,
87090
+ // The step Python is on, for the startup bar; a slow one is named in the log.
87091
+ onProgress: (step, tookMs) => {
87092
+ if (tookMs === void 0)
87093
+ startupStep("Python tools", step);
87094
+ else
87095
+ noteSlowStep(`Python tools: ${step}`, tookMs);
87096
+ },
86546
87097
  ...personalToolsDir !== void 0 ? { personalToolsDir, sharedWith: () => sharedWith("tools") } : {},
86547
87098
  ...services.codebaseDir !== void 0 ? { venvRoot: services.codebaseDir } : {},
86548
87099
  logger,
@@ -86694,6 +87245,19 @@ ${preview.text}` } : {}
86694
87245
  indexNames.set(client, { at: Date.now(), names });
86695
87246
  return names;
86696
87247
  }
87248
+ async function boundedWait(work, label, seconds = 20) {
87249
+ let timer;
87250
+ const late = await Promise.race([
87251
+ work.then(() => false, (error51) => {
87252
+ throw error51;
87253
+ }),
87254
+ new Promise((resolve) => {
87255
+ timer = setTimeout(() => resolve(true), seconds * 1e3);
87256
+ })
87257
+ ]).finally(() => clearTimeout(timer));
87258
+ if (late)
87259
+ logger.info(`[startup] replying without waiting longer for ${label} (still loading after ${String(seconds)}s)`);
87260
+ }
86697
87261
  function early(promise2) {
86698
87262
  promise2.catch(() => void 0);
86699
87263
  return promise2;
@@ -86754,7 +87318,13 @@ ${preview.text}` } : {}
86754
87318
  const dirs = skillSearchPath();
86755
87319
  if (dirs.length === 0)
86756
87320
  return;
86757
- const loaded = await loadSkills(dirs);
87321
+ const loaded = await loadSkills(dirs, (dir, tookMs) => {
87322
+ if (tookMs === void 0)
87323
+ startupStep("Skills", `reading ${dir}`);
87324
+ else
87325
+ noteSlowStep(`Skills: reading ${dir}`, tookMs);
87326
+ });
87327
+ startupStep("Skills", void 0);
86758
87328
  skills = loaded.skills;
86759
87329
  skillIssues = loaded.issues;
86760
87330
  const signature = loaded.issues.map((issue2) => `${issue2.filePath}\0${issue2.detail}`).join("\n");
@@ -87476,6 +88046,7 @@ ${preview.text}` } : {}
87476
88046
  if (activeStrategy !== void 0 && startsNewWork(activePlan, activePlanProgress, nextPlan)) {
87477
88047
  strategyProgress = {};
87478
88048
  strategyLastRole = void 0;
88049
+ resetHandOvers();
87479
88050
  void postStrategies();
87480
88051
  }
87481
88052
  activePlan = nextPlan;
@@ -87610,6 +88181,9 @@ ${preview.text}` } : {}
87610
88181
  const commandToolset = () => probedTools ??= detectCommandTools();
87611
88182
  let cachedMaxIterations = 25;
87612
88183
  let cachedAutoCompact = false;
88184
+ let cachedAutoHandoff = false;
88185
+ let cachedUnlimitedSteps = false;
88186
+ let handoffAtLimit = false;
87613
88187
  let cachedStallSeconds = DEFAULT_STALL_SECONDS;
87614
88188
  let cachedRetries = DEFAULT_RETRIES;
87615
88189
  let cachedAccentColor = "#22C55E";
@@ -87971,6 +88545,8 @@ ${preview.text}` } : {}
87971
88545
  cachedModeId = config2.modeId;
87972
88546
  cachedMaxIterations = config2.maxIterations ?? 25;
87973
88547
  cachedAutoCompact = config2.autoCompact === true;
88548
+ cachedAutoHandoff = config2.autoHandoff === true;
88549
+ cachedUnlimitedSteps = config2.unlimitedSteps === true;
87974
88550
  cachedStallSeconds = config2.connection?.stallSeconds ?? DEFAULT_STALL_SECONDS;
87975
88551
  cachedRetries = config2.connection?.retries ?? DEFAULT_RETRIES;
87976
88552
  cachedAccentColor = config2.ui?.accentColor ?? "#22C55E";
@@ -88063,6 +88639,8 @@ ${preview.text}` } : {}
88063
88639
  approvals,
88064
88640
  maxIterations: cachedMaxIterations,
88065
88641
  autoCompact: cachedAutoCompact,
88642
+ autoHandoff: cachedAutoHandoff,
88643
+ unlimitedSteps: cachedUnlimitedSteps,
88066
88644
  stallSeconds: cachedStallSeconds,
88067
88645
  retries: cachedRetries,
88068
88646
  accentColor: cachedAccentColor,
@@ -88183,11 +88761,60 @@ ${preview.text}` } : {}
88183
88761
  mcpConfigs = servers;
88184
88762
  mcpJson = JSON.stringify({ mcpServers: servers }, null, 2);
88185
88763
  }
88764
+ const startupWaits = /* @__PURE__ */ new Map();
88765
+ const startupDetails = /* @__PURE__ */ new Map();
88766
+ function startupStep(label, detail) {
88767
+ if (detail === void 0)
88768
+ startupDetails.delete(label);
88769
+ else
88770
+ startupDetails.set(label, detail);
88771
+ postStartupProgress();
88772
+ }
88773
+ function noteSlowStep(step, tookMs) {
88774
+ if (tookMs >= 2e3)
88775
+ logger.info(`[startup] ${step} took ${(tookMs / 1e3).toFixed(1)}s`);
88776
+ }
88777
+ const mcpStartingSince = /* @__PURE__ */ new Map();
88778
+ let lastStartupPosted = "";
88779
+ function postStartupProgress(force = false) {
88780
+ const now = Date.now();
88781
+ let states = [];
88782
+ try {
88783
+ states = mcp.states_();
88784
+ } catch {
88785
+ }
88786
+ const blocking = new Set(states.filter((state) => state.enabled && state.status === "connecting" && state.tools.length === 0).map((state) => state.name));
88787
+ for (const name of [...mcpStartingSince.keys()])
88788
+ if (!blocking.has(name))
88789
+ mcpStartingSince.delete(name);
88790
+ for (const name of blocking)
88791
+ if (!mcpStartingSince.has(name))
88792
+ mcpStartingSince.set(name, now);
88793
+ const waiting = [
88794
+ ...[...mcpStartingSince].map(([name, since2]) => ({ label: `MCP server "${name}" starting`, since: since2 })),
88795
+ ...[...startupWaits].map(([label, since2]) => ({ label: startupDetails.has(label) ? `${label} - ${startupDetails.get(label) ?? ""}` : label, since: since2 }))
88796
+ ].sort((a, b) => a.since - b.since);
88797
+ const key3 = JSON.stringify(waiting);
88798
+ if (!force && key3 === lastStartupPosted)
88799
+ return;
88800
+ lastStartupPosted = key3;
88801
+ post({ type: "startupProgress", waiting });
88802
+ }
88803
+ function trackStartup(label, work) {
88804
+ startupWaits.set(label, Date.now());
88805
+ postStartupProgress();
88806
+ return work.finally(() => {
88807
+ startupWaits.delete(label);
88808
+ startupDetails.delete(label);
88809
+ postStartupProgress();
88810
+ });
88811
+ }
88186
88812
  const mcp = new McpRegistry(
88187
88813
  secrets,
88188
88814
  {
88189
88815
  onStateChanged: () => {
88190
88816
  postMcp();
88817
+ postStartupProgress();
88191
88818
  void postSchedules();
88192
88819
  void postTools();
88193
88820
  void postDatasetStatus();
@@ -89592,6 +90219,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
89592
90219
  strategyProgress = {};
89593
90220
  strategyExchanges = [];
89594
90221
  strategyLastRole = void 0;
90222
+ resetHandOvers();
89595
90223
  await persistActiveTask();
89596
90224
  await postStrategies();
89597
90225
  }
@@ -89743,6 +90371,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
89743
90371
  strategyProgress = source.strategyProgress ?? {};
89744
90372
  strategyExchanges = source.strategyExchanges ?? [];
89745
90373
  strategyLastRole = void 0;
90374
+ resetHandOvers(0);
89746
90375
  stopRoleProcesses();
89747
90376
  }
89748
90377
  function postSteering() {
@@ -89751,7 +90380,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
89751
90380
  void postStrategies();
89752
90381
  }
89753
90382
  const pendingSteeringPath = () => workspaceRoot === void 0 ? void 0 : pendingSteeringFile(storageDir, workspaceRoot);
89754
- async function startNewTask() {
90383
+ async function startNewTask(options = {}) {
89755
90384
  conversation.reset();
89756
90385
  crashResumes = 0;
89757
90386
  readFiles.clear();
@@ -89765,15 +90394,20 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
89765
90394
  truncationStore.startTask();
89766
90395
  activePlan = void 0;
89767
90396
  activePlanProgress = {};
89768
- activeStrategy = void 0;
90397
+ activeStrategy = options.keepStrategy;
89769
90398
  strategyProgress = {};
89770
90399
  strategyExchanges = [];
89771
90400
  strategyLastRole = void 0;
90401
+ resetHandOvers();
89772
90402
  stopRoleProcesses();
89773
90403
  await setActiveTaskId(void 0);
89774
90404
  const pending = pendingSteeringPath();
89775
- if (pending !== void 0 && backgroundRun !== true)
89776
- await clearPendingSteering(pending);
90405
+ if (pending !== void 0 && backgroundRun !== true) {
90406
+ if (options.keepStrategy !== void 0)
90407
+ await persistActiveTask();
90408
+ else
90409
+ await clearPendingSteering(pending);
90410
+ }
89777
90411
  post({ type: "taskRestored", taskId: void 0, entries: [] });
89778
90412
  post({ type: "plan", plan: "" });
89779
90413
  postPlanProgress();
@@ -89797,6 +90431,10 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
89797
90431
  userTurnRunning = false;
89798
90432
  userTurnWindingDown = false;
89799
90433
  onSettled?.();
90434
+ if (handoffAtLimit) {
90435
+ handoffAtLimit = false;
90436
+ void handleHandoff();
90437
+ }
89800
90438
  }
89801
90439
  })();
89802
90440
  }
@@ -89992,7 +90630,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
89992
90630
  const mailCollection = config2.mail?.enabled === true ? mailCollectionName(config2) : void 0;
89993
90631
  const mailSearch = mailCollection === void 0 ? void 0 : await resolveMailSearch(config2);
89994
90632
  const searchIndexes = search?.opensearch !== void 0 ? await indexNamesFor(search.opensearch) : [];
89995
- await skillsReady;
90633
+ await boundedWait(skillsReady, "Skills");
89996
90634
  const codebaseInstructions = renderCodebaseInstructions(await instructionsReady);
89997
90635
  const activeMode = findMode(config2.modeId);
89998
90636
  juniorTurnWithoutExpert = activeMode.id === "junior" && schedule === void 0;
@@ -90119,7 +90757,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
90119
90757
  });
90120
90758
  if (conversation.systemPrompt() !== desiredPrompt)
90121
90759
  conversation.setSystemPrompt(desiredPrompt);
90122
- await toolsReady;
90760
+ await boundedWait(toolsReady, "Tools", 45);
90123
90761
  const toolContext = {
90124
90762
  fs: new NodeFileSystem(),
90125
90763
  // The shell the user chose, or the platform default. Read per turn, so changing it
@@ -90227,13 +90865,26 @@ ${direction}` : attachMentions(text2, mentions);
90227
90865
  // So images a tool returns (a Confluence page's pictures) reach a model that can see them.
90228
90866
  supportsVision: capabilities.supportsVision,
90229
90867
  // CLAUDE.md §5 has called this configurable since Phase 0; until now it was not.
90230
- maxIterations: cachedMaxIterations,
90868
+ // No limit when the user switched it off - never for a scheduled run, which nobody is watching to stop.
90869
+ maxIterations: cachedUnlimitedSteps && schedule === void 0 ? Number.POSITIVE_INFINITY : cachedMaxIterations,
90231
90870
  /*
90232
90871
  * Off unless switched on: compaction loses detail, and when is the user's call. A scheduled
90233
90872
  * run always may, because nobody is there to press "Compact now" and a run that stops at
90234
90873
  * the limit overnight reports nothing useful in the morning.
90235
90874
  */
90236
90875
  autoCompact: cachedAutoCompact || schedule !== void 0,
90876
+ // A chat at its limit hands off by itself, when that is switched on (never a scheduled run: nobody is there).
90877
+ /*
90878
+ * Only once the chat holds an earlier message of the user's: a chat that is full on its first message (a handoff's
90879
+ * own opening, or one enormous paste) would hand off into a chat just as full, and again, for ever. That case
90880
+ * gets the ordinary message saying what to do.
90881
+ */
90882
+ ...cachedAutoHandoff && !cachedAutoCompact && schedule === void 0 && conversation.toArray().filter((m) => m.role === "user" && !isObserverNote(m.content)).length >= 1 ? {
90883
+ onContextFull: () => {
90884
+ handoffAtLimit = true;
90885
+ logger.info("the conversation reached the context limit: handing off to a new chat");
90886
+ }
90887
+ } : {},
90237
90888
  stallSeconds: cachedStallSeconds,
90238
90889
  retries: cachedRetries,
90239
90890
  drainQueuedMessages: () => {
@@ -96195,9 +96846,10 @@ ${last}` : ""}`);
96195
96846
  if (mentioned.length > 0)
96196
96847
  stepNotes = attachMentions(stepNotes, mentioned);
96197
96848
  }
96198
- const question = stepNotes.length > 0 ? `${request2.question}
96849
+ const handed = handOverSources(strategy, agent.role).map((role) => ({ role, answer: latestStrategyAnswer(role) })).filter((entry) => entry.answer !== void 0).map((entry) => `## Handed over from ${name(entry.role)} (its latest answer, passed on directly)
96199
96850
 
96200
- ${stepNotes}` : request2.question;
96851
+ ${entry.answer.length > HANDOVER_LIMIT ? `${entry.answer.slice(0, HANDOVER_LIMIT)}\u2026 [cut at ${String(HANDOVER_LIMIT)} characters]` : entry.answer}`);
96852
+ const question = [request2.question, ...handed, ...stepNotes.length > 0 ? [stepNotes] : [], SUMMARY_REQUEST].join("\n\n");
96201
96853
  strategyRunning.add(agent.role);
96202
96854
  strategyLastRole = agent.role;
96203
96855
  void postStrategies();
@@ -96226,14 +96878,30 @@ ${more.advice}` };
96226
96878
  strategyProgress = recorded.progress;
96227
96879
  const exchange2 = exchangeOf(agent.role, request2.question, answer.advice, before, recorded.progress, request2.parallel === true);
96228
96880
  recordExchange(checks.length > 0 ? { ...exchange2, contracts: checks.map((check2) => ({ ...check2, askedAgain: askedAgain.get(check2.edgeId) ?? 0 })) } : exchange2);
96881
+ strategyAnswers.set(agent.role, answer.advice);
96229
96882
  strategyLastRole = agent.role;
96230
96883
  persistSoon();
96231
96884
  void postStrategies();
96232
96885
  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.`);
96233
96886
  const notes = [...contractNotes, ...recorded.note !== void 0 ? [recorded.note] : []];
96234
- return notes.length > 0 ? { ...answer, advice: `${answer.advice}
96887
+ const forMain = answerForMain(answer.advice, name(agent.role));
96888
+ return { ...answer, advice: notes.length > 0 ? `${forMain}
96235
96889
 
96236
- ${notes.join("\n")}` } : answer;
96890
+ ${notes.join("\n")}` : forMain };
96891
+ }
96892
+ const strategyAnswers = /* @__PURE__ */ new Map();
96893
+ let strategyTopicSince = 0;
96894
+ const HANDOVER_LIMIT = 24e3;
96895
+ function resetHandOvers(since2 = Date.now()) {
96896
+ strategyAnswers.clear();
96897
+ strategyTopicSince = since2;
96898
+ }
96899
+ function latestStrategyAnswer(role) {
96900
+ const kept = strategyAnswers.get(role);
96901
+ if (kept !== void 0)
96902
+ return kept;
96903
+ const logged = [...strategyExchanges].reverse().find((exchange2) => exchange2.role === role && exchange2.at >= strategyTopicSince && exchange2.refused === void 0 && exchange2.answer.length > 0);
96904
+ return logged?.answer;
96237
96905
  }
96238
96906
  function recordExchange(exchange2) {
96239
96907
  strategyExchanges = [...strategyExchanges, exchange2].slice(-MAX_EXCHANGES);
@@ -96869,7 +97537,7 @@ ${notes.join("\n")}` } : answer;
96869
97537
  } else if (message6.type === "deleteTask") {
96870
97538
  reportFailure("deleteTask", deleteTask(message6.id));
96871
97539
  } else if (message6.type === "newTask") {
96872
- reportFailure("startNewTask", startNewTask());
97540
+ reportFailure("startNewTask", startNewTask({ keepStrategy: activeStrategy }));
96873
97541
  } else if (message6.type === "startHandoff") {
96874
97542
  reportFailure("handleHandoff", handleHandoff());
96875
97543
  } else if (message6.type === "cancelHandoff") {
@@ -96880,6 +97548,12 @@ ${notes.join("\n")}` } : answer;
96880
97548
  void configManager.save("user", { connection: { stallSeconds: message6.stallSeconds, retries: message6.retries } }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
96881
97549
  } else if (message6.type === "setAutoCompact") {
96882
97550
  void configManager.save("user", { autoCompact: message6.value }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
97551
+ } else if (message6.type === "setUnlimitedSteps") {
97552
+ void configManager.save("user", { unlimitedSteps: message6.value }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
97553
+ } else if (message6.type === "requestStartupProgress") {
97554
+ postStartupProgress(true);
97555
+ } else if (message6.type === "setAutoHandoff") {
97556
+ void configManager.save("user", { autoHandoff: message6.value }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
96883
97557
  } else if (message6.type === "setMaxIterations") {
96884
97558
  void configManager.save("user", { maxIterations: message6.value }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
96885
97559
  } else if (message6.type === "setProgrammingProfile") {
@@ -97012,6 +97686,12 @@ ${notes.join("\n")}` } : answer;
97012
97686
  } else if (message6.type === "useStrategy") {
97013
97687
  reportFailure("useStrategy", (async () => {
97014
97688
  const config2 = (await configManager.load()).config;
97689
+ const carried = message6.strategy === void 0 ? void 0 : strategySchema.safeParse(message6.strategy);
97690
+ if (carried !== void 0) {
97691
+ if (carried.success)
97692
+ await useStrategy(carried.data);
97693
+ return;
97694
+ }
97015
97695
  await useStrategy(message6.id === void 0 ? void 0 : (config2.strategies ?? []).find((each) => each.id === message6.id));
97016
97696
  })());
97017
97697
  } else if (message6.type === "requestTeam") {
@@ -97520,22 +98200,22 @@ ${notes.join("\n")}` } : answer;
97520
98200
  try {
97521
98201
  const config2 = await loadSettings();
97522
98202
  const startedAt = Date.now();
97523
- const timed = (label, work) => work.finally(() => {
98203
+ const timed = (label, work, shown2 = true) => (shown2 ? trackStartup(label, work) : work).finally(() => {
97524
98204
  const seconds = (Date.now() - startedAt) / 1e3;
97525
98205
  if (seconds >= 2)
97526
98206
  logger.info(`[startup] ${label} ready after ${seconds.toFixed(1)}s`);
97527
98207
  });
97528
98208
  const parts = [
97529
- timed("secrets", knownSecretValues()),
97530
- timed("skills", refreshSkills()),
98209
+ timed("Stored credentials", knownSecretValues()),
98210
+ timed("Skills", refreshSkills()),
97531
98211
  timed("Python tools", configurePython(config2)),
97532
- timed("git check", gitAvailable()),
97533
- timed("expert", resolveExpert(config2)),
97534
- timed("MCP tools", mcpStarted)
98212
+ timed("Git", gitAvailable()),
98213
+ timed("Expert", resolveExpert(config2)),
98214
+ timed("MCP servers", mcpStarted, false)
97535
98215
  ];
97536
98216
  if ((config2.profiles ?? []).length > 0) {
97537
98217
  const profile = resolveActiveProfile(config2);
97538
- parts.push(timed("model gateway (sign-in and context window)", (async () => {
98218
+ parts.push(timed("Model gateway sign-in", (async () => {
97539
98219
  if (profile.wireFormat !== "vscode-lm")
97540
98220
  await authStrategyFor(config2, profile).resolveHeaders();
97541
98221
  await reportedWindowFor(config2, profile);
@@ -100264,6 +100944,15 @@ an access token as a Bearer token, leave the user id empty and paste that token
100264
100944
  "job dependencies",
100265
100945
  "condition",
100266
100946
  "box",
100947
+ "average run time",
100948
+ "how long does",
100949
+ "eta",
100950
+ "when will it finish",
100951
+ "usual start time",
100952
+ "normal start time",
100953
+ "predecessors",
100954
+ "upstream jobs",
100955
+ "top most job",
100267
100956
  "why has my job not started",
100268
100957
  "job failed",
100269
100958
  "job log",
@@ -100410,6 +101099,19 @@ with the section \`autosysAddresses\`), for example next to an onboarding page.
100410
101099
  It needs the server's run history and event history; where those live elsewhere set
100411
101100
  config:autosys (paths) runHistory and eventHistory, and the tool names which one is missing. A run
100412
101101
  with no event record is reported as "not known", never guessed as scheduled.
101102
+ - \`autosys_run_stats\` \u2014 **how long a job usually runs**, from its run history (last 30 days, or as many as you
101103
+ say): typical (median), average, fastest, slowest, and the time nine runs in ten finish within - successful runs
101104
+ only when there are any. For a job **running now**, an **ETA in local time**: when it should finish at its typical
101105
+ run time, the likely latest, and whether it is already running longer than usual.
101106
+ - \`autosys_usual_start\` \u2014 **when a job normally starts**, in local time, especially one with no start time that a
101107
+ dependency or its box starts. Two answers side by side: what its run history shows (the usual time of day,
101108
+ measured around the clock so a midnight job comes out right, and the range nine starts in ten fall in; manual
101109
+ starts and retries left out), and what its **definitions** imply (its predecessors up to jobs with start times,
101110
+ each with its typical run time - "GL_EXTRACT starts at 01:00 -> PAY_LOAD after it (01:30) -> this job (02:10)").
101111
+ - \`autosys_predecessors\` \u2014 **every predecessor of a job, all the way up**, from the job definitions: each job its
101112
+ condition names (met or not) and the box it sits in, then theirs, until the topmost jobs (no condition, no box),
101113
+ each with its status, last start and end, and its start schedule at the top. Ends with what is not met and what
101114
+ failed. With eta, predecessors running now get an ETA too - "when will my job start?".
100413
101115
  - Ask it to **follow a job until it finishes**: it checks the status, waits, and checks again.
100414
101116
  - \`autosys_job_log\` \u2014 a job's stderr or stdout, the end of it or matching lines. If the server
100415
101117
  offers no log endpoint, it says which file on which machine the job writes to instead.
@@ -102089,8 +102791,13 @@ between chats - but what they offer can. Every chat of a codebase remembers each
102089
102791
  one shared file, so a chat started after a crash or a sleep offers those tools at once and replies
102090
102792
  without waiting for the servers; a server keeps starting in the background, and a call to one of its
102091
102793
  tools waits for it. A server with no remembered list is waited for at most 45 seconds, after which the
102092
- reply goes ahead and its tools join the next message. When starting is still slow, the agent log
102093
- (\`host.log\`) names each slow part with a \`[startup]\` line - the server, Python, skills or the gateway.
102794
+ reply goes ahead and its tools join the next message. While anything is still getting ready, a bar over
102795
+ the message box names it with how long it has taken - each MCP server still starting, Python tools, skills, the model
102796
+ gateway's sign-in - and, for skills and Python tools, which folder or step is under way; it goes when nothing is left.
102797
+ A message sent meanwhile waits at most 20 seconds for skills and 45 for tools, then is answered with what has loaded;
102798
+ the rest joins the next message. When that keeps happening, a slow folder (often a network share or a disconnected
102799
+ drive) is the usual cause - the log names it. The agent log
102800
+ (\`host.log\`) also names each slow part with a \`[startup]\` line.
102094
102801
 
102095
102802
  **Not in Fire Code**: editor file pickers \u2014 paths are typed. Fire Code's
102096
102803
  Settings \u2192 Export source code saves the whole repository as a zip that builds offline.
@@ -102378,6 +103085,12 @@ morning, by which time a toast is long gone. The run log keeps a Report button.
102378
103085
  "parallel",
102379
103086
  "parallel box",
102380
103087
  "contract",
103088
+ "custom role",
103089
+ "custom roles",
103090
+ "own context",
103091
+ "context filling up",
103092
+ "hand over",
103093
+ "handover between agents",
102381
103094
  "strategy per chat",
102382
103095
  "different strategy",
102383
103096
  "strategy lost",
@@ -102458,13 +103171,25 @@ connectors between them, else as drawn. A box of either kind can be switched on
102458
103171
  "Run as a group").
102459
103172
 
102460
103173
  **A strategy belongs to its chat.** Each chat keeps its own strategy, or none: choosing one with **Save and use in
102461
- this chat** sets it for that chat only, and a new chat starts with none until you pick one. It is saved with the chat
103174
+ this chat** sets it for that chat only. A new chat started from it - **+**, New chat, or in Fire Code a new tab -
103175
+ keeps the same strategy with its loops starting afresh; a chat with no strategy gives a new chat with none, and **Stop
103176
+ using** takes it off. It is saved with the chat
102462
103177
  and comes back whenever the chat does - reopened from History, after the window reloads, when a Fire Code chat wakes
102463
103178
  from sleep or restarts after a crash - and it is kept even if you chose it before sending anything. **New chat with a
102464
103179
  handoff** carries it into the new chat. **Stop using** in the Strategy window takes it off the chat. Every request in
102465
103180
  the chat follows it, not only the first: for a new topic the agent proposes a new plan that goes through the strategy
102466
103181
  again, and the back-and-forth loops start afresh for it, with their full number of rounds.
102467
103182
 
103183
+ **Custom roles work in a strategy** like the built-in ones: a role made in Settings \u2192 Agents is consulted by its id
103184
+ or its name, and the strategy tells the agent the id beside a custom role's name.
103185
+
103186
+ **Each specialist keeps its own context, and the main chat stays lean.** A specialist runs in its own process with
103187
+ its own memory. When a step is consulted, Light Code hands it the latest full answer of every step connected into it -
103188
+ a box's steps for a connector from a box, and in a back-and-forth the other side's latest - so the main agent does not
103189
+ paste one specialist's answer into the next one's question. Each specialist ends with a short "Summary for the main
103190
+ agent", and that summary (with any loop verdict or contract note) is all the main chat receives; the full answer stays
103191
+ in the strategy record, readable with strategy_history. A new topic starts these hand-overs afresh.
103192
+
102468
103193
  **Connecting a box.** A box is one step of the flow: connect it like a step, from its own dot on the right edge or with
102469
103194
  **Connect to...** when it is selected, to a step or to another box - and connect a step or a box into it. A connector
102470
103195
  out of a box is followed only once every step inside has answered; a connector into a box gives every step inside what
@@ -102627,6 +103352,13 @@ called at all.
102627
103352
  "forgets",
102628
103353
  "auto compact",
102629
103354
  "compact automatically",
103355
+ "auto handoff",
103356
+ "hand off automatically",
103357
+ "handoff at limit",
103358
+ "no step limit",
103359
+ "unlimited steps",
103360
+ "disable step limit",
103361
+ "step limit",
102630
103362
  "retry",
102631
103363
  "retries",
102632
103364
  "stuck thinking",
@@ -102686,6 +103418,10 @@ shortened transcript.
102686
103418
  older part (highlighted near the limit); the stored transcript keeps everything, only what is sent to
102687
103419
  the model is shortened, and never in the middle of a tool call. Your own messages are kept **word for
102688
103420
  word** inside the summary, every time, so what you asked for is never paraphrased away.
103421
+ Or tick **Hand off automatically** (config:autoHandoff) instead: when the chat reaches the limit the reply stops,
103422
+ the assistant writes a handoff, and a new chat starts from it and carries on by itself - this chat stays in History,
103423
+ nothing in it summarised. The two are one or the other; ticking one unticks the other. It applies once the chat holds an
103424
+ earlier message of yours, so a chat full on its very first message is not handed over and over.
102689
103425
  Tick **Compact automatically** beside the button (config:autoCompact) to have it done near the limit,
102690
103426
  keeping roughly the last third of the window verbatim - and only for a model whose window Light Code
102691
103427
  knows: from the table, from the model's own server (a self-hosted vLLM or SGLang reports its real
@@ -102720,6 +103456,9 @@ Light Code chat**. Typing \`@\` does the same from the keyboard, everywhere.
102720
103456
  something. If it trips, nothing is lost: send another message and it carries on with the full
102721
103457
  transcript. Typing **while a turn is running** grants a fresh 25 as well \u2014 the cap exists to stop a
102722
103458
  model looping unattended, and somebody typing is evidence that this is not that.
103459
+ **No step limit** (Settings \u2192 Approvals, config:unlimitedSteps) lets a chat's reply run until the job is done, you
103460
+ press Stop, or the same thing fails three times in a row - pair it with the Anti Hallucinator (Settings \u2192 Project),
103461
+ which watches each step and steers the agent back when it drifts. Scheduled runs keep the limit.
102723
103462
 
102724
103463
  **Prompt caching is why tool definitions do not change mid-session.** They sit at the front of the
102725
103464
  prompt, so swapping them to "save context" would throw away the cached prefix *and all the history
@@ -105302,6 +106041,8 @@ var PERSONAL_SETTINGS = /* @__PURE__ */ new Set([
105302
106041
  "setMaxIterations",
105303
106042
  // Whether *this user's* chats compact by themselves - their own conversations, nobody else's.
105304
106043
  "setAutoCompact",
106044
+ "setAutoHandoff",
106045
+ "setUnlimitedSteps",
105305
106046
  // How patiently *this user's* requests are retried.
105306
106047
  "setConnectionRetry",
105307
106048
  "setTaskExpertLimits",