@chosengeneration/light-code 0.163.0 → 0.164.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 +572 -92
  2. package/dist/server.cjs +561 -83
  3. package/package.json +1 -1
package/dist/server.cjs CHANGED
@@ -57384,8 +57384,8 @@ async function random(size) {
57384
57384
  const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
57385
57385
  let result = "";
57386
57386
  while (result.length < size) {
57387
- const randomBytes4 = await getRandomValues(size - result.length);
57388
- for (const randomByte of randomBytes4) {
57387
+ const randomBytes5 = await getRandomValues(size - result.length);
57388
+ for (const randomByte of randomBytes5) {
57389
57389
  if (randomByte < evenDistCutoff) {
57390
57390
  result += mask[randomByte % mask.length];
57391
57391
  }
@@ -61221,12 +61221,18 @@ var import_promises13 = __toESM(require("node:fs/promises"), 1);
61221
61221
  function declaresAlwaysAsk(source) {
61222
61222
  return /^__always_ask__\s*(?::[^=\n]*)?=\s*True\b/m.test(source);
61223
61223
  }
61224
- function declaredCredentials(source) {
61225
- const match = /^__credentials__\s*(?::[^=\n]*)?=\s*[[(]([\s\S]*?)[\])]/m.exec(source);
61224
+ function declaredList(source, name) {
61225
+ const match = new RegExp(`^${name}\\s*(?::[^=\\n]*)?=\\s*[[(]([\\s\\S]*?)[\\])]`, "m").exec(source);
61226
61226
  if (match === null)
61227
61227
  return [];
61228
61228
  return [...(match[1] ?? "").matchAll(/(["'])((?:(?!\1)[^\\\n]|\\.)*)\1/g)].map((m) => m[2] ?? "").filter((s) => s.length > 0);
61229
61229
  }
61230
+ function declaredCredentials(source) {
61231
+ return declaredList(source, "__credentials__");
61232
+ }
61233
+ function declaredToolCalls(source) {
61234
+ return declaredList(source, "__tool_calls__");
61235
+ }
61230
61236
 
61231
61237
  // ../../packages/core/dist/python/tools.js
61232
61238
  var import_node_path26 = __toESM(require("node:path"), 1);
@@ -61500,6 +61506,7 @@ function makeWriteTool(context, options) {
61500
61506
  const notes = [
61501
61507
  ...producedBy !== void 0 ? [`Written by ${producedBy}`] : [],
61502
61508
  ...reads.length > 0 ? [`Reads saved credentials: ${reads.join(", ")}`] : [],
61509
+ ...declaredToolCalls(source).length > 0 ? [`Calls tools: ${declaredToolCalls(source).join(", ")}`] : [],
61503
61510
  ...declaresAlwaysAsk(source) ? ["Always asks before every run, for everyone who has this tool (__always_ask__ = True)"] : [],
61504
61511
  ...[toolAudienceNote(context, target.personal)].filter((note) => note !== void 0)
61505
61512
  ];
@@ -63266,7 +63273,7 @@ The conversation is longer than this model accepts, and it could not be shortene
63266
63273
  }
63267
63274
 
63268
63275
  // ../../packages/core/dist/host/bridge.js
63269
- var import_node_crypto16 = require("node:crypto");
63276
+ var import_node_crypto17 = require("node:crypto");
63270
63277
 
63271
63278
  // ../../packages/core/dist/atlassian/autosysGateway.js
63272
63279
  function withBasicCredentials(auth2, headerName, username, password) {
@@ -74106,6 +74113,16 @@ function asList(value) {
74106
74113
  }
74107
74114
  return [];
74108
74115
  }
74116
+ function pagingNote(value, returned, what) {
74117
+ if (value === null || typeof value !== "object" || Array.isArray(value))
74118
+ return void 0;
74119
+ const o = value;
74120
+ const total = ["total", "totalCount", "totalRecords", "totalResults", "totalSize", "numFound", "count", "size"].map((k) => Number(o[k])).find((n) => Number.isFinite(n) && n > returned);
74121
+ const next = ["next", "nextPage", "nextLink", "hasMore", "more", "moreResults"].some((k) => o[k] === true || typeof o[k] === "string" && o[k].length > 0);
74122
+ if (total === void 0 && !next)
74123
+ return void 0;
74124
+ return `AutoSys answered ${String(returned)} ${what}${total !== void 0 ? ` of ${String(total)}` : ""} - it pages its answers, so some are missing. Add its page-size parameter to the address (config:autosys paths, e.g. "/job-run-info?filter={filter:name}&limit=1000" - the name of the parameter is in the server's API documentation or the office wiki); autosys_check_addresses shows what each address answers.`;
74125
+ }
74109
74126
  function field(record2, ...names) {
74110
74127
  for (const name of names) {
74111
74128
  const value = record2[name];
@@ -74183,6 +74200,11 @@ var AutosysClient = class _AutosysClient {
74183
74200
  get base() {
74184
74201
  return this.rest.base;
74185
74202
  }
74203
+ /** What the last calls found worth saying - an answer that pages - for the tool to pass on, once. */
74204
+ notes = [];
74205
+ takeNotes() {
74206
+ return [...new Set(this.notes.splice(0))];
74207
+ }
74186
74208
  /** The address templates in use, defaults included. */
74187
74209
  get addresses() {
74188
74210
  return { ...this.paths };
@@ -74230,7 +74252,12 @@ var AutosysClient = class _AutosysClient {
74230
74252
  async findJobs(pattern, signal) {
74231
74253
  if (!isAutosysName(pattern, true))
74232
74254
  throw new AtlassianError(`"${pattern}" is not a job name or pattern \u2014 letters, digits, . _ - # and * only.`);
74233
- return asList(await this.rest.json("finding jobs", fill(this.paths.jobs, { pattern }), { method: "GET" }, signal));
74255
+ const answer = await this.rest.json("finding jobs", fill(this.paths.jobs, { pattern }), { method: "GET" }, signal);
74256
+ const list2 = asList(answer);
74257
+ const note = pagingNote(answer, list2.length, `jobs for ${pattern}`);
74258
+ if (note !== void 0)
74259
+ this.notes.push(note);
74260
+ return list2;
74234
74261
  }
74235
74262
  async job(name, signal) {
74236
74263
  if (!isAutosysName(name))
@@ -74259,7 +74286,12 @@ var AutosysClient = class _AutosysClient {
74259
74286
  if (!pattern.includes("*"))
74260
74287
  return this.oneRun(pattern, signal);
74261
74288
  try {
74262
- return asList(await this.rest.json(`reading the status of ${pattern}`, fill(this.paths.runInfo, { pattern }), { method: "GET" }, signal)).map(toRun);
74289
+ const answer = await this.rest.json(`reading the status of ${pattern}`, fill(this.paths.runInfo, { pattern }), { method: "GET" }, signal);
74290
+ const list2 = asList(answer);
74291
+ const note = pagingNote(answer, list2.length, `statuses for ${pattern}`);
74292
+ if (note !== void 0)
74293
+ this.notes.push(note);
74294
+ return list2.map(toRun);
74263
74295
  } catch (error51) {
74264
74296
  if (!(error51 instanceof AtlassianError && error51.status === 404))
74265
74297
  throw error51;
@@ -74434,11 +74466,13 @@ function createAutosysFindJobsTool(options) {
74434
74466
  async execute(params3) {
74435
74467
  try {
74436
74468
  const pattern = params3.pattern ?? options.defaultPattern ?? "*";
74437
- const all = await (await options.client()).findJobs(pattern);
74469
+ const client = await options.client();
74470
+ const all = await client.findJobs(pattern);
74471
+ const notes = client.takeNotes();
74438
74472
  const jobs = all.filter((job) => definitionMatches(job, params3));
74439
74473
  if (jobs.length === 0) {
74440
74474
  return {
74441
- content: all.length === 0 ? `No AutoSys jobs match ${pattern}.` : `None of the ${String(all.length)} job(s) matching ${pattern} pass those filters.`
74475
+ content: [all.length === 0 ? `No AutoSys jobs match ${pattern}.` : `None of the ${String(all.length)} job(s) matching ${pattern} pass those filters.`, ...notes].join("\n\n")
74442
74476
  };
74443
74477
  }
74444
74478
  const shown2 = jobs.slice(0, params3.limit ?? 50);
@@ -74451,7 +74485,8 @@ function createAutosysFindJobsTool(options) {
74451
74485
  const machine = field(job, "machine");
74452
74486
  const owner = field(job, "owner");
74453
74487
  return `- ${field(job, "name", "jobName") ?? "?"} (${field(job, "jobType", "job_type", "type") ?? "?"}${box !== void 0 ? `, in box ${box}` : ""}${machine !== void 0 ? `, on ${machine}` : ""}${owner !== void 0 ? `, owner ${owner}` : ""})`;
74454
- })
74488
+ }),
74489
+ ...notes.length > 0 ? ["", ...notes] : []
74455
74490
  ].join("\n")
74456
74491
  };
74457
74492
  } catch (error51) {
@@ -74671,7 +74706,8 @@ function createAutosysStatusTool(options) {
74671
74706
  };
74672
74707
  }
74673
74708
  const asked = wanted.join(", ");
74674
- const unreadable = problems.length > 0 ? ["", "Could not read:", ...problems.map((problem) => `- ${problem}`)] : [];
74709
+ const paging = client.takeNotes();
74710
+ const unreadable = [...problems.length > 0 ? ["", "Could not read:", ...problems.map((problem) => `- ${problem}`)] : [], ...paging.length > 0 ? ["", ...paging] : []];
74675
74711
  if (runs.length === 0) {
74676
74712
  return {
74677
74713
  content: [
@@ -75576,6 +75612,193 @@ function monitorToolRefusal(tool, name) {
75576
75612
  return void 0;
75577
75613
  }
75578
75614
 
75615
+ // ../../packages/core/dist/monitoring/history.js
75616
+ var import_node_crypto15 = require("node:crypto");
75617
+ var MAPPING = {
75618
+ mappings: {
75619
+ dynamic: false,
75620
+ properties: {
75621
+ kind: { type: "keyword" },
75622
+ monitor: { type: "keyword" },
75623
+ by: { type: "keyword" },
75624
+ at: { type: "long" },
75625
+ slot: { type: "long" },
75626
+ level: { type: "keyword" },
75627
+ alertIds: { type: "keyword" },
75628
+ alertKeys: { type: "keyword" },
75629
+ payload: { type: "object", enabled: false }
75630
+ }
75631
+ }
75632
+ };
75633
+ var MonitorHistoryError = class extends Error {
75634
+ status;
75635
+ constructor(message5, status2) {
75636
+ super(message5);
75637
+ this.status = status2;
75638
+ this.name = "MonitorHistoryError";
75639
+ }
75640
+ };
75641
+ function docId(...parts) {
75642
+ return parts.map((p) => String(p)).map((p) => /^[A-Za-z0-9._-]{1,80}$/.test(p) ? p : (0, import_node_crypto15.createHash)("sha256").update(p).digest("hex").slice(0, 16)).join(":");
75643
+ }
75644
+ var MonitorHistoryStore = class {
75645
+ http;
75646
+ connection;
75647
+ index;
75648
+ by;
75649
+ ensured = false;
75650
+ constructor(http, connection, index, by) {
75651
+ this.http = http;
75652
+ this.connection = connection;
75653
+ this.index = index;
75654
+ this.by = by;
75655
+ if (!isSafeIndexName(index))
75656
+ throw new MonitorHistoryError(`"${index}" is not a usable index name (lowercase letters, digits, - and _).`);
75657
+ }
75658
+ async send(method, path63, body) {
75659
+ const headers = { "Content-Type": "application/json" };
75660
+ const { username, password } = this.connection;
75661
+ if (username !== void 0 && username.length > 0) {
75662
+ headers.Authorization = `Basic ${Buffer.from(`${username}:${password ?? ""}`).toString("base64")}`;
75663
+ }
75664
+ const url2 = `${this.connection.url.replace(/\/+$/, "")}/${encodeURIComponent(this.index)}${path63}`;
75665
+ const request = { method, headers };
75666
+ if (body !== void 0)
75667
+ request.body = JSON.stringify(body);
75668
+ if (this.connection.tls !== void 0)
75669
+ request.tls = this.connection.tls;
75670
+ let response;
75671
+ try {
75672
+ response = await this.http.request(url2, request);
75673
+ } catch (error51) {
75674
+ throw new MonitorHistoryError(`Could not reach ${this.connection.url}: ${describeTlsError(error51)}`);
75675
+ }
75676
+ const text2 = await response.text().catch(() => "");
75677
+ let json2 = {};
75678
+ try {
75679
+ json2 = text2.length > 0 ? JSON.parse(text2) : {};
75680
+ } catch {
75681
+ }
75682
+ return { status: response.status, json: json2 };
75683
+ }
75684
+ fail(doing, status2, json2) {
75685
+ const reason = json2["error"]?.reason ?? JSON.stringify(json2).slice(0, 300);
75686
+ const hint = status2 === 401 ? " - the sign-in was refused" : status2 === 403 ? " - this account may not write to that index; ask whoever runs the cluster" : "";
75687
+ throw new MonitorHistoryError(`OpenSearch refused ${doing} (${String(status2)}${hint}): ${reason}`, status2);
75688
+ }
75689
+ /** Creates the index with its mapping, once; "already exists" - another member won - is success. */
75690
+ async ensureIndex() {
75691
+ if (this.ensured)
75692
+ return;
75693
+ const { status: status2, json: json2 } = await this.send("PUT", "", MAPPING);
75694
+ const type = json2["error"]?.type;
75695
+ if (status2 >= 300 && type !== "resource_already_exists_exception")
75696
+ this.fail("creating the monitoring index", status2, json2);
75697
+ this.ensured = true;
75698
+ }
75699
+ /** True when this Fire Code may run `monitor` for interval `slot`; false when a team member already is. */
75700
+ async claim(monitor, slot) {
75701
+ await this.ensureIndex();
75702
+ const { status: status2, json: json2 } = await this.send("PUT", `/_create/${encodeURIComponent(docId("claim", monitor, slot))}`, {
75703
+ kind: "claim",
75704
+ monitor,
75705
+ slot,
75706
+ by: this.by,
75707
+ at: Math.floor(Date.now() / 1e3)
75708
+ });
75709
+ if (status2 === 409)
75710
+ return false;
75711
+ if (status2 >= 300)
75712
+ this.fail(`claiming ${monitor}`, status2, json2);
75713
+ return true;
75714
+ }
75715
+ async write(check2) {
75716
+ await this.ensureIndex();
75717
+ const record2 = { ...check2, by: this.by };
75718
+ const id = docId("check", record2.monitor, record2.by, record2.at, (0, import_node_crypto15.randomBytes)(4).toString("hex"));
75719
+ const { status: status2, json: json2 } = await this.send("PUT", `/_create/${encodeURIComponent(id)}`, {
75720
+ kind: "check",
75721
+ monitor: record2.monitor,
75722
+ by: record2.by,
75723
+ at: record2.at,
75724
+ level: record2.level,
75725
+ alertIds: (record2.found ?? []).map((a) => a.id),
75726
+ alertKeys: [...new Set((record2.found ?? []).map((a) => a.key))],
75727
+ payload: record2
75728
+ });
75729
+ if (status2 >= 300)
75730
+ this.fail(`recording a check of ${record2.monitor}`, status2, json2);
75731
+ }
75732
+ async search(body) {
75733
+ await this.ensureIndex();
75734
+ const { status: status2, json: json2 } = await this.send("POST", "/_search", body);
75735
+ if (status2 >= 300)
75736
+ this.fail("reading monitoring history", status2, json2);
75737
+ return json2;
75738
+ }
75739
+ /** The newest check of each monitor, by anyone. */
75740
+ async latest(monitors) {
75741
+ if (monitors.length === 0)
75742
+ return {};
75743
+ const json2 = await this.search({
75744
+ size: 0,
75745
+ query: { bool: { filter: [{ term: { kind: "check" } }, { terms: { monitor: monitors } }] } },
75746
+ aggs: { m: { terms: { field: "monitor", size: monitors.length }, aggs: { top: { top_hits: { size: 1, sort: [{ at: "desc" }], _source: ["payload"] } } } } }
75747
+ });
75748
+ const out = {};
75749
+ const buckets = json2["aggregations"]?.m?.buckets ?? [];
75750
+ for (const bucket of buckets) {
75751
+ const hit = bucket.top.hits.hits[0]?._source.payload;
75752
+ if (hit !== void 0)
75753
+ out[bucket.key] = hit;
75754
+ }
75755
+ return out;
75756
+ }
75757
+ /** A monitor's checks since `since` (epoch seconds), newest first, by anyone. */
75758
+ async history(monitor, since2, limit = 500) {
75759
+ const json2 = await this.search({
75760
+ size: Math.min(Math.max(limit, 1), 2e3),
75761
+ sort: [{ at: "desc" }],
75762
+ _source: ["payload"],
75763
+ query: { bool: { filter: [{ term: { kind: "check" } }, { term: { monitor } }, { range: { at: { gte: since2 } } }] } }
75764
+ });
75765
+ const hits = json2["hits"]?.hits ?? [];
75766
+ return hits.map((h) => h._source.payload);
75767
+ }
75768
+ /** Removes this person's checks and claims older than `before` - only theirs. How many went. */
75769
+ async prune(before, monitor) {
75770
+ await this.ensureIndex();
75771
+ const filter = [{ term: { by: this.by } }, { range: { at: { lt: before } } }];
75772
+ if (monitor !== void 0)
75773
+ filter.push({ term: { monitor } });
75774
+ const { status: status2, json: json2 } = await this.send("POST", "/_delete_by_query?conflicts=proceed", { query: { bool: { filter } } });
75775
+ if (status2 >= 300)
75776
+ this.fail("cleaning up monitoring history", status2, json2);
75777
+ return Number(json2["deleted"] ?? 0);
75778
+ }
75779
+ };
75780
+
75781
+ // ../../packages/core/dist/monitoring/explain.js
75782
+ var EXPLAIN_SYSTEM = [
75783
+ "You explain a monitoring alert to the person responsible for it, in Fire Code.",
75784
+ "You get the monitor, the author's advice for the rules that fired, the row the alert fired on, and each",
75785
+ "alert's history worked out from past checks. Write Markdown, at most about 200 words:",
75786
+ "1. **What is wrong** - one or two sentences, in plain words, naming the thing (job, host, feed).",
75787
+ "2. **New or known** - from the history: new today, ongoing since when, or recurring (how often, at what",
75788
+ " time). Say it exactly as the history shows; never guess a pattern it does not show.",
75789
+ "3. **What to do** - the author's advice first, as given. Then, only if it helps, up to three concrete next",
75790
+ " steps of your own, marked as suggestions. If there is no advice, say so and suggest checks to start with.",
75791
+ "No preamble, no repeating the input back, no code fences unless quoting a command from the advice."
75792
+ ].join("\n");
75793
+ function explainMessages(context) {
75794
+ return [
75795
+ { role: "system", content: EXPLAIN_SYSTEM },
75796
+ { role: "user", content: `The alert, as Fire Code recorded it:
75797
+
75798
+ ${JSON.stringify(context, null, 2).slice(0, 24e3)}` }
75799
+ ];
75800
+ }
75801
+
75579
75802
  // ../../packages/core/dist/monitoring/rowsCheck.js
75580
75803
  var NUMERIC_TEXT = /^\s*[-+(]?[\d,]+(\.\d+)?\)?\s*(%|ms|s|sec|min|mins|h|hrs|kb|mb|gb|tb)?\s*$/i;
75581
75804
  var ISO = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
@@ -75704,8 +75927,17 @@ function describeRowsCheck(check2) {
75704
75927
  }
75705
75928
  var MONITOR_TOOL_TEMPLATE = `
75706
75929
  """<What it reads>, for monitoring: one record per <job | host | feed>."""
75930
+ import json
75707
75931
  from datetime import datetime, timezone
75708
75932
 
75933
+ import light_code
75934
+
75935
+ # Tools this one calls with light_code.call_tool - MCP tools, other Python tools, and Fire Code's
75936
+ # reading tools (autosys_status, jira_search, ...). Reviewed with the tool; in a monitor they run unasked.
75937
+ __tool_calls__ = ["server__query_jobs"]
75938
+ # Saved credentials it reads with light_code.credential("name"), if any - never a password in the code.
75939
+ __credentials__ = []
75940
+
75709
75941
 
75710
75942
  def run(pattern: str = "PAY_*") -> list[dict]:
75711
75943
  """<One line>.
@@ -75713,15 +75945,17 @@ def run(pattern: str = "PAY_*") -> list[dict]:
75713
75945
  Args:
75714
75946
  pattern: <what narrows it>.
75715
75947
  """
75716
- items = read_source(pattern) # let it RAISE when the source cannot be read - the tile turns purple
75948
+ # Either read the source directly, or call an existing tool (its answer is text - json.loads it
75949
+ # when the tool answers JSON). Let it RAISE when the data cannot be read - the tile turns purple.
75950
+ items = json.loads(light_code.call_tool("server__query_jobs", {"pattern": pattern}))
75717
75951
  rows = []
75718
75952
  for item in items:
75719
75953
  rows.append({
75720
- "job": item.name, # names the row: the monitor's "key"
75721
- "status": item.status.upper(), # a short fixed word rules can match
75722
- "minutes": int(item.minutes), # numbers as numbers - no units, no commas
75723
- "lastStart": item.start.astimezone(timezone.utc).isoformat(), # ISO 8601, with a zone
75724
- "machine": item.machine or None, # None, not "", when there is no value
75954
+ "job": item["name"], # names the row: the monitor's "key"
75955
+ "status": str(item["status"]).upper(), # a short fixed word rules can match
75956
+ "minutes": int(item["minutes"]), # numbers as numbers - no units, no commas
75957
+ "lastStart": datetime.fromisoformat(item["start"]).astimezone(timezone.utc).isoformat(), # ISO 8601, with a zone
75958
+ "machine": item.get("machine") or None, # None, not "", when there is no value
75725
75959
  })
75726
75960
  return rows # [] when there is nothing to report - never a message
75727
75961
  `.trim();
@@ -75745,9 +75979,10 @@ var createSchema2 = external_exports.object({
75745
75979
  title: external_exports.string().describe('What the tile says, a few words: "Overnight batch".'),
75746
75980
  summary: external_exports.string().describe("One sentence shown on hover: what it watches and what an alert means."),
75747
75981
  audience: external_exports.enum(["me", "team"]).optional().describe('"team" (the default): shown under Team alerts and shared where the team shares skills. "me": a Personal monitor only on this computer. Use "me" when the user says it is just for them.'),
75748
- every: external_exports.union([external_exports.string(), external_exports.number()]).describe('How often to check: "5m", "15m", "1h", "1d" (one minute at least).'),
75749
- activeHours: external_exports.string().optional().describe('Only check between these times, e.g. "07:00-19:00" (a window past midnight is allowed).'),
75750
- days: external_exports.array(external_exports.string()).optional().describe('Only on these days, e.g. ["mon","tue","wed","thu","fri"].'),
75982
+ every: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe('How often to check: "5m", "15m", "1h", "1d" (one minute at least). Leave out when "at" gives the times instead; both together check at the times and in between.'),
75983
+ at: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).optional().describe('Exact times of day: "07:30" for once a day, or ["07:30", "12:00", "18:00"]. Run on the "days" given, whatever activeHours says.'),
75984
+ activeHours: external_exports.string().optional().describe('A run window for "every": "07:00-19:00" (past midnight is allowed), "09:00-" for not before nine, "-17:00" for until five.'),
75985
+ days: external_exports.array(external_exports.string()).optional().describe('Only on these days, e.g. ["mon","tue","wed","thu","fri"]; for both "every" and "at".'),
75751
75986
  source: sourceSchema,
75752
75987
  rows: external_exports.string().optional().describe('Where the list of rows is in the answer, as a dotted path ("data.jobs"), when it is not found by itself.'),
75753
75988
  columns: external_exports.array(external_exports.object({ key: external_exports.string(), label: external_exports.string().optional(), format: external_exports.enum(["text", "number", "percent", "datetime", "duration", "bytes"]).optional(), width: external_exports.number().optional() })).optional().describe("The grid columns, in order. Omit to show every field. A dotted key reads inside a nested object."),
@@ -75757,19 +75992,21 @@ var createSchema2 = external_exports.object({
75757
75992
  when: condition.describe('{"column", "op", "value"} with op ==, !=, >, >=, <, <=, contains, notContains, startsWith, endsWith, matches (regex), in, notIn (value a list), empty, notEmpty, olderThan / newerThan (value "30m", "2h", for a timestamp column); or {"all": [...]}, {"any": [...]}, {"not": {...}}.'),
75758
75993
  highlight: external_exports.enum(["row", "cell"]).optional().describe("Colour the whole row, or just the cell (the default when the rule is about one column)."),
75759
75994
  column: external_exports.string().optional().describe("Which cell to colour, when not the rule's own column."),
75760
- message: external_exports.string().optional().describe('The alert text, filled from the row: "{name} failed at {lastEnd}".')
75995
+ message: external_exports.string().optional().describe('The alert text, filled from the row: "{name} failed at {lastEnd}".'),
75996
+ advice: external_exports.string().optional().describe("The author's own words for this alert: what it means and what to do (who to call, what to rerun, what to check). Shown and used when the alert is explained.")
75761
75997
  })).describe("Alert rules, tried on every row. red = failure / needs attention, amber = warning, blue = information, purple = no data or cannot tell."),
75762
75998
  whenEmpty: level.optional().describe("The level when there are no rows. Default green."),
75763
75999
  whenClear: level.optional().describe("The level when there are rows and no rule fires. Default green."),
75764
76000
  notify: level.optional().describe("The least severe level that sends a Windows notification for this monitor. Default amber. How each level notifies is the user's setting."),
75765
76001
  details: sourceSchema.optional().describe(`The breakdown shown when the user double-clicks a row: a source whose args or SQL take {column} values from that row, e.g. {"tool": "py__job_runs", "args": {"job": "{name}"}}. Omit to show the row's own fields.`),
75766
76002
  timeoutSeconds: external_exports.number().int().min(5).max(900).optional().describe("How long one check may take. Default 120."),
76003
+ runbook: external_exports.string().optional().describe("The author's general advice for this monitor: who owns it, where to look first, known false alarms. Used with each rule's advice when an alert is explained."),
75767
76004
  notes: external_exports.string().optional().describe("Markdown for the skill body: what this watches, why, and what to do about each alert."),
75768
76005
  tryOnly: external_exports.boolean().optional().describe("Run the source once and show what Fire Code makes of it - columns, rows, alerts - without saving anything. Use it while writing or fixing the tool.")
75769
76006
  });
75770
76007
  function monitorBlock(params3) {
75771
- const spec = { title: params3.title, summary: params3.summary, every: params3.every };
75772
- for (const key2 of ["activeHours", "days", "source", "rows", "columns", "key", "rules", "whenEmpty", "whenClear", "notify", "details", "timeoutSeconds"]) {
76008
+ const spec = { title: params3.title, summary: params3.summary, ...params3.every !== void 0 ? { every: params3.every } : {} };
76009
+ for (const key2 of ["at", "activeHours", "days", "source", "rows", "columns", "key", "rules", "whenEmpty", "whenClear", "notify", "details", "timeoutSeconds", "runbook"]) {
75773
76010
  if (params3[key2] !== void 0)
75774
76011
  spec[key2] = params3[key2];
75775
76012
  }
@@ -75782,7 +76019,7 @@ function monitorSkillBody(params3, block2) {
75782
76019
  params3.summary,
75783
76020
  "",
75784
76021
  ...params3.notes !== void 0 && params3.notes.trim().length > 0 ? [params3.notes.trim(), ""] : [],
75785
- `This skill is a **Fire Code monitor**: Fire Code checks it every ${String(params3.every)} and shows it on the Monitoring dashboard. The block below is its definition. Change it with monitor_create under the same name, so the change is approved again; an edit by hand is reviewed on the dashboard before it runs.`,
76022
+ `This skill is a **Fire Code monitor**: Fire Code checks it ${params3.every !== void 0 ? `every ${String(params3.every)}` : ""}${params3.every !== void 0 && params3.at !== void 0 ? " and " : ""}${params3.at !== void 0 ? `at ${[params3.at].flat().join(", ")}` : ""} and shows it on the Monitoring dashboard. The block below is its definition. Change it with monitor_create under the same name, so the change is approved again; an edit by hand is reviewed on the dashboard before it runs.`,
75786
76023
  "",
75787
76024
  "```monitor",
75788
76025
  block2,
@@ -75809,8 +76046,14 @@ function createMonitorCreateTool(options) {
75809
76046
  body: monitorSkillBody(params3, block2),
75810
76047
  ...params3.audience !== void 0 ? { audience: params3.audience } : {}
75811
76048
  });
75812
- const tryIt = async (block2) => {
76049
+ const tryIt = async (block2, team = false) => {
75813
76050
  try {
76051
+ if (team) {
76052
+ const listed = await options.channel.request("list");
76053
+ if (listed.teamReady !== true) {
76054
+ return { ok: false, error: `A team monitor keeps its history in the team's OpenSearch index, and that is not set up: ${listed.teamProblem ?? "Fire Code \u2192 Settings \u2192 Monitoring \u2192 Team history"}. Make it personal (audience "me"), or ask the user to set it up.` };
76055
+ }
76056
+ }
75814
76057
  const checked = await options.channel.request("evaluate", { block: block2 });
75815
76058
  if (checked.sourceKind === "tool") {
75816
76059
  return { ok: true, native: false, note: "After it is saved, its tool is run once here to show what the first check finds." };
@@ -75826,7 +76069,7 @@ ${describeEvaluation(tried)}` };
75826
76069
  return {
75827
76070
  name: "monitor_create",
75828
76071
  group: "edit",
75829
- description: "Create or replace a Fire Code monitor: a check that runs on a schedule and shows on the Monitoring dashboard as a coloured tile, with a data grid whose cells or rows are coloured by alert rules, and Windows notifications at the levels the user chose. Before creating one: find an existing tool that returns the data (search_docs, or the tools you have) and reuse it; if none does, write a Python tool with create_python_tool from the template in monitor_check_tool, and run monitor_check_tool until it says PASS - then use the columns and key it gives. A SQLite database or CSV/Excel file needs no tool. Rules are judged by Fire Code itself on every check - no model is involved - so make them exact. The user approves the skill file; the result shows what the first check found. " + MONITOR_TOOL_FORMAT,
76072
+ description: `Create or replace a Fire Code monitor: a check that runs on a schedule and shows on the Monitoring dashboard as a coloured tile, with a data grid whose cells or rows are coloured by alert rules, and Windows notifications at the levels the user chose. Before creating one: find an existing tool that returns the data (search_docs, or the tools you have) and reuse it; if none does, write a Python tool with create_python_tool from the template in monitor_check_tool, and run monitor_check_tool until it says PASS - then use the columns and key it gives. A SQLite database or CSV/Excel file needs no tool. Rules are judged by Fire Code itself on every check - no model is involved - so make them exact. ASK THE AUTHOR (ask_user_form, one field per rule plus a general one) what each alert means and what to do about it, unless they already said, and put it in each rule's "advice" and in "runbook": that is what an agent tells whoever meets the alert later. A team monitor needs the team's OpenSearch history set in Fire Code \u2192 Settings \u2192 Monitoring; without it make a personal one ("me") or tell the user. The user approves the skill file; the result shows what the first check found. ` + MONITOR_TOOL_FORMAT,
75830
76073
  parametersSchema: createSchema2,
75831
76074
  async preview(params3, context) {
75832
76075
  const block2 = monitorBlock(params3);
@@ -75838,7 +76081,7 @@ ${describeEvaluation(tried)}` };
75838
76081
  ${"tool" in params3.source ? `Run ${params3.source.tool}(${JSON.stringify(params3.source.args ?? {})})` : `Read ${JSON.stringify(params3.source)}`}`
75839
76082
  };
75840
76083
  }
75841
- const tried = await tryIt(block2);
76084
+ const tried = await tryIt(block2, params3.audience !== "me");
75842
76085
  if (!tried.ok) {
75843
76086
  return { kind: "text", text: `This monitor cannot be created as written - nothing will be saved:
75844
76087
 
@@ -75854,7 +76097,7 @@ ${tried.note}` };
75854
76097
  },
75855
76098
  async execute(params3, context) {
75856
76099
  const block2 = monitorBlock(params3);
75857
- const tried = await tryIt(block2);
76100
+ const tried = await tryIt(block2, params3.audience !== "me" && params3.tryOnly !== true);
75858
76101
  if (!tried.ok)
75859
76102
  return { content: `Not created: ${tried.error}`, isError: true };
75860
76103
  if (params3.tryOnly === true) {
@@ -75991,6 +76234,44 @@ function createMonitorStatusTool(options) {
75991
76234
  }
75992
76235
  };
75993
76236
  }
76237
+ var historySchema = external_exports.object({
76238
+ name: external_exports.string().describe("The monitor."),
76239
+ key: external_exports.string().optional().describe("One row: its key value (a job name, a host) - its alerts' history only."),
76240
+ alert: external_exports.string().optional().describe("One alert, by the id monitor_status shows."),
76241
+ days: external_exports.number().int().min(1).max(366).optional().describe("How far back. Default 14.")
76242
+ });
76243
+ function createMonitorHistoryTool(options) {
76244
+ return {
76245
+ name: "monitor_history",
76246
+ group: "read",
76247
+ description: "A monitor's past checks and, for each alert, whether it is new, ongoing (since when, how many checks in a row), recurring (on how many days, usually at what time) or intermittent - worked out by Fire Code from the stored checks (the team's, for a team monitor). Use it before saying whether an alert is new or known, and when investigating one.",
76248
+ parametersSchema: historySchema,
76249
+ async execute(params3) {
76250
+ try {
76251
+ const got = await options.channel.request("history", {
76252
+ name: params3.name,
76253
+ days: params3.days ?? 14,
76254
+ ...params3.key !== void 0 ? { key: params3.key } : {},
76255
+ ...params3.alert !== void 0 ? { alert: params3.alert } : {}
76256
+ });
76257
+ const changes = got.checks.filter((c2, i, all) => i === all.length - 1 || all[i + 1]?.level !== c2.level);
76258
+ return {
76259
+ content: [
76260
+ `${params3.name}: ${String(got.checks.length)} check(s) in the last ${String(got.days)} day(s).`,
76261
+ "",
76262
+ "Alerts:",
76263
+ ...got.patterns.length === 0 ? ["- none in this period"] : got.patterns.map((p) => `- [${p.id}] ${p.level} ${p.key}: ${p.verdict.toUpperCase()} - ${p.summary}` + (p.days.length > 0 ? ` (by day: ${p.days.map((d) => `${d.date} ${String(d.count)}`).join(", ")})` : "")),
76264
+ "",
76265
+ "Level changes, newest first:",
76266
+ ...changes.slice(0, 30).map((c2) => `- ${when3(c2.at)} ${c2.level}${c2.by ? ` (checked by ${c2.by})` : ""} - ${c2.headline}`)
76267
+ ].join("\n")
76268
+ };
76269
+ } catch (error51) {
76270
+ return { content: message2(error51), isError: true };
76271
+ }
76272
+ }
76273
+ };
76274
+ }
75994
76275
  var showSchema = external_exports.object({
75995
76276
  action: external_exports.enum(["run", "open", "dashboard"]).describe("run: check now. open: the monitor's grid window. dashboard: the Monitoring dashboard."),
75996
76277
  name: external_exports.string().optional().describe("The monitor, for run and open.")
@@ -76200,7 +76481,7 @@ async function copySetupFiles(mainCheckout, folder, names) {
76200
76481
  }
76201
76482
 
76202
76483
  // ../../packages/core/dist/teamrepo/sync.js
76203
- var import_node_crypto15 = require("node:crypto");
76484
+ var import_node_crypto16 = require("node:crypto");
76204
76485
  var import_promises26 = __toESM(require("node:fs/promises"), 1);
76205
76486
  var import_node_path46 = __toESM(require("node:path"), 1);
76206
76487
  var TOMBSTONE_PREFIX = "LIGHT-CODE-DELETED:";
@@ -76223,13 +76504,13 @@ function contentHash(bytes) {
76223
76504
  text2 = void 0;
76224
76505
  }
76225
76506
  }
76226
- const digest = (0, import_node_crypto15.createHash)("sha256");
76507
+ const digest = (0, import_node_crypto16.createHash)("sha256");
76227
76508
  if (text2 === void 0)
76228
76509
  return digest.update(bytes).digest("hex");
76229
76510
  return digest.update(text2.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").replace(/\s+$/, "")).digest("hex");
76230
76511
  }
76231
76512
  var hash2 = contentHash;
76232
- var rawHash = (bytes) => (0, import_node_crypto15.createHash)("sha256").update(bytes).digest("hex");
76513
+ var rawHash = (bytes) => (0, import_node_crypto16.createHash)("sha256").update(bytes).digest("hex");
76233
76514
  function repoPathFor(folder, kind, relative) {
76234
76515
  const base = folder.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
76235
76516
  return [base, kind, relative.replace(/\\/g, "/")].filter((part) => part.length > 0).join("/");
@@ -76712,11 +76993,63 @@ function tracingHttpClient(inner, entries, knownSecrets = []) {
76712
76993
  ...inner.openWebSocket !== void 0 ? { openWebSocket: inner.openWebSocket.bind(inner) } : {}
76713
76994
  };
76714
76995
  }
76996
+ function explainStep(entry) {
76997
+ const error51 = (entry.error ?? "").toLowerCase();
76998
+ const status2 = entry.status;
76999
+ const body = (entry.responseBody ?? "").trimStart().toLowerCase();
77000
+ const header2 = (name) => Object.entries(entry.responseHeaders ?? {}).find(([k]) => k.toLowerCase() === name)?.[1];
77001
+ if (entry.error !== void 0) {
77002
+ if (/enotfound|getaddrinfo|eai_again/.test(error51))
77003
+ return "The server name does not resolve here: check the site address, or that this machine is on the network or VPN that can see it.";
77004
+ if (/econnrefused/.test(error51))
77005
+ return "Nothing is listening at that address and port: check the port in the site address, or whether the service is up.";
77006
+ if (/etimedout|timeout|timed out|aborted/.test(error51))
77007
+ return "No answer: a firewall or proxy may be dropping the connection. Check the address, and whether this network needs a proxy (Settings \u2192 Network).";
77008
+ if (/certificate|self.signed|unable to verify|cert_|ssl|tls/.test(error51))
77009
+ return "TLS: the server's certificate is not trusted here. Add your company's CA in Settings \u2192 Network (or the connection's own CA file).";
77010
+ if (/econnreset|socket hang up/.test(error51))
77011
+ return "The connection was cut: often a proxy or TLS inspection, or plain http sent to an https port (or the other way round).";
77012
+ return void 0;
77013
+ }
77014
+ if (status2 === void 0)
77015
+ return void 0;
77016
+ if (status2 >= 300 && status2 < 400) {
77017
+ const to = header2("location");
77018
+ return `Redirected${to !== void 0 ? ` to ${to}` : ""}: the address may need https, a context path (/jira, /confluence, /AEWS), or it leads to a login page - use the server's own address.`;
77019
+ }
77020
+ if (status2 >= 200 && status2 < 300 && (body.startsWith("<!doctype html") || body.startsWith("<html"))) {
77021
+ return "A web page came back where data was expected: usually a single sign-on login page, which means the token is not accepted at this address. Use the server's REST address, not a portal link.";
77022
+ }
77023
+ if (status2 === 400)
77024
+ return "The server did not understand the request: often a wrong context path or API version in the site address, or a field it does not accept.";
77025
+ if (status2 === 401)
77026
+ return "Not signed in: the token or password was refused, or not sent the way this server expects (Bearer token vs user name and password; an expired token).";
77027
+ if (status2 === 403)
77028
+ return "Signed in, but this account may not do this: check its permissions on the server, the token's scopes, or an IP allow-list on a gateway.";
77029
+ if (status2 === 404)
77030
+ return "Nothing at this address: the site address (its context path, such as /jira, /confluence or /AEWS) or the API path differs on this server. Compare with the address that works in a browser or Postman.";
77031
+ if (status2 === 405)
77032
+ return "This address does not accept this kind of request: it probably points at a different service than the one named.";
77033
+ if (status2 === 407)
77034
+ return "The proxy wants a sign-in: set the proxy's user name and password in Settings \u2192 Network.";
77035
+ if (status2 === 429)
77036
+ return "Too many requests: the server or gateway is limiting calls. Wait a little and try again.";
77037
+ if (status2 >= 500)
77038
+ return "The server (or a gateway in front of it) failed: the body may say why. A 502/503/504 usually means the gateway could not reach the service behind it.";
77039
+ return void 0;
77040
+ }
76715
77041
  function renderTrace(entries) {
76716
77042
  if (entries.length === 0)
76717
77043
  return "No request was sent - the test stopped before reaching the network (see the message above).";
76718
- return entries.map((entry, index) => {
77044
+ const failed2 = entries.findIndex((e) => e.error !== void 0 || e.status !== void 0 && (e.status >= 300 || explainStep(e) !== void 0));
77045
+ const first = failed2 === -1 ? void 0 : entries[failed2];
77046
+ const reading = first === void 0 ? void 0 : explainStep(first);
77047
+ const summary = first !== void 0 && reading !== void 0 ? [`Likely cause (step #${String(failed2 + 1)}): ${reading}`] : [];
77048
+ return [...summary, ...entries.map((entry, index) => {
76719
77049
  const lines2 = [`#${String(index + 1)} ${entry.method} ${entry.url}`];
77050
+ const meaning = explainStep(entry);
77051
+ if (meaning !== void 0)
77052
+ lines2.push(`What this usually means: ${meaning}`);
76720
77053
  const headers = Object.entries(entry.requestHeaders);
76721
77054
  if (headers.length > 0)
76722
77055
  lines2.push("Request headers:", ...headers.map(([name, value]) => ` ${name}: ${value}`));
@@ -76732,7 +77065,7 @@ function renderTrace(entries) {
76732
77065
  lines2.push("Response body:", entry.responseBody !== void 0 && entry.responseBody.length > 0 ? indent(entry.responseBody) : " (empty)");
76733
77066
  }
76734
77067
  return lines2.join("\n");
76735
- }).join("\n\n");
77068
+ })].join("\n\n");
76736
77069
  }
76737
77070
  function indent(text2) {
76738
77071
  return text2.split("\n").map((line) => ` ${line}`).join("\n");
@@ -80710,7 +81043,7 @@ function wireChatBridge(services) {
80710
81043
  let cachedSecretValues = [];
80711
81044
  const droppedFilesRoot2 = droppedFilesRoot();
80712
81045
  const mailAttachmentsRoot2 = mailAttachmentsRoot();
80713
- const droppedFilesDir = import_node_path52.default.join(droppedFilesRoot2, (0, import_node_crypto16.randomUUID)().slice(0, 8));
81046
+ const droppedFilesDir = import_node_path52.default.join(droppedFilesRoot2, (0, import_node_crypto17.randomUUID)().slice(0, 8));
80714
81047
  const truncationStore = new RecordingTruncationStore(new DiskTruncationStore(import_node_path52.default.join(storageDir, "tool-results"), () => cachedSecretValues));
80715
81048
  const taskStore = new JsonTaskStore(storageDir, truncationStore, logger);
80716
81049
  const manifestsRoot = services.codebaseDir ?? storageDir;
@@ -80775,15 +81108,29 @@ function wireChatBridge(services) {
80775
81108
  * anybody present to answer a prompt. `callPolicy.ts` holds the rule and the reasoning.
80776
81109
  */
80777
81110
  callTool: async (name, args, caller) => {
80778
- if (!pythonNestedCallsAllowed) {
80779
- throw new Error("This run cannot call other tools from a Python tool: it is unattended, so nobody is here to approve one.");
80780
- }
80781
81111
  const registry2 = currentToolRegistry();
80782
81112
  const tool = registry2.get(name) ?? registry2.get(`py__${name}`);
80783
81113
  if (tool === void 0) {
80784
81114
  throw new Error(`There is no tool called "${name}". Settings \u2192 Tools lists everything callable; an MCP tool is named with its server, like \`filesystem__read_file\`.`);
80785
81115
  }
80786
- if (!mayPythonToolCall(tool.name, tool.group))
81116
+ const declared = await declaredCallsOf(caller);
81117
+ const isDeclared = declared.some((d) => d === tool.name || `py__${d}` === tool.name);
81118
+ if (!pythonNestedCallsAllowed && monitorRunContext !== void 0) {
81119
+ if (!isDeclared) {
81120
+ throw new Error(`${caller} calls "${tool.name}" without declaring it. Add it to the tool's __tool_calls__ list (e.g. __tool_calls__ = [${[...declared, tool.name].map((d) => JSON.stringify(d)).join(", ")}]); the tool is then approved again.`);
81121
+ }
81122
+ const refusal = monitorToolRefusal(tool, tool.name);
81123
+ if (refusal !== void 0)
81124
+ throw new Error(refusal);
81125
+ const result2 = await tool.execute(args, monitorRunContext);
81126
+ if (result2.isError === true)
81127
+ throw new Error(String(result2.content));
81128
+ return result2.content;
81129
+ }
81130
+ if (!pythonNestedCallsAllowed) {
81131
+ throw new Error("This run cannot call other tools from a Python tool: it is unattended, so nobody is here to approve one.");
81132
+ }
81133
+ if (!mayPythonToolCall(tool.name, tool.group, isDeclared))
80787
81134
  throw new Error(PYTHON_CALL_DENIED);
80788
81135
  const context = pythonNestedContext;
80789
81136
  if (context === void 0) {
@@ -82518,6 +82865,7 @@ ${preview.text}` } : {}
82518
82865
  combined.register(createMonitorStatusTool(monitorOptions));
82519
82866
  combined.register(createMonitorShowTool(monitorOptions));
82520
82867
  combined.register(createMonitorCheckToolTool(monitorOptions));
82868
+ combined.register(createMonitorHistoryTool(monitorOptions));
82521
82869
  combined.register(createMonitorControlTool(monitorOptions));
82522
82870
  }
82523
82871
  combined.register(createDeleteSkillTool(context));
@@ -82892,7 +83240,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
82892
83240
  if (id === void 0) {
82893
83241
  if (records.length >= (spec.max ?? 500))
82894
83242
  return postAddonPage(message5.package, { error: `No more than ${String(spec.max ?? 500)} ${spec.noun}s.` });
82895
- id = (0, import_node_crypto16.randomBytes)(6).toString("hex");
83243
+ id = (0, import_node_crypto17.randomBytes)(6).toString("hex");
82896
83244
  records.push({ id, values: cleaned.values });
82897
83245
  } else {
82898
83246
  const at = records.findIndex((record2) => record2.id === id);
@@ -83129,7 +83477,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
83129
83477
  if (workspaceRoot === void 0 || conversation.isEmpty())
83130
83478
  return;
83131
83479
  if (activeTaskId === void 0) {
83132
- await setActiveTaskId((0, import_node_crypto16.randomUUID)());
83480
+ await setActiveTaskId((0, import_node_crypto17.randomUUID)());
83133
83481
  activeTaskCreatedAt = Date.now();
83134
83482
  truncationStore.startTask();
83135
83483
  }
@@ -83915,7 +84263,7 @@ ${direction}` : attachMentions(text2, mentions);
83915
84263
  try {
83916
84264
  const { config: config2 } = await configManager.load();
83917
84265
  const profiles = config2.profiles ?? [];
83918
- const id = input.id ?? (0, import_node_crypto16.randomUUID)();
84266
+ const id = input.id ?? (0, import_node_crypto17.randomUUID)();
83919
84267
  const existing = profiles.find((p) => p.id === id);
83920
84268
  const auth2 = await buildAuthFromInput(input, id);
83921
84269
  const saved = {
@@ -83953,7 +84301,7 @@ ${direction}` : attachMentions(text2, mentions);
83953
84301
  post({ type: "error", message: `Profile "${id}" no longer exists.` });
83954
84302
  return;
83955
84303
  }
83956
- const newId = (0, import_node_crypto16.randomUUID)();
84304
+ const newId = (0, import_node_crypto17.randomUUID)();
83957
84305
  async function copySecret(fromRef, toRef) {
83958
84306
  if (fromRef === void 0)
83959
84307
  return false;
@@ -85448,7 +85796,7 @@ ${redact(shown2, cachedSecretValues)}` }
85448
85796
  if (auth2.clientId === void 0 || auth2.clientSecretRef === void 0) {
85449
85797
  throw new AtlassianError("AutoSys uses the API gateway but the client id or secret is missing. Settings \u2192 DevOps \u2192 AutoSys \u2192 API gateway: enter both and save.");
85450
85798
  }
85451
- const key2 = JSON.stringify({ auth: auth2, baseUrl: config2.autosys?.baseUrl, tls: tls2 === void 0 ? 0 : (0, import_node_crypto16.createHash)("sha256").update(JSON.stringify(tls2)).digest("hex") });
85799
+ const key2 = JSON.stringify({ auth: auth2, baseUrl: config2.autosys?.baseUrl, tls: tls2 === void 0 ? 0 : (0, import_node_crypto17.createHash)("sha256").update(JSON.stringify(tls2)).digest("hex") });
85452
85800
  const testing = http !== httpClient;
85453
85801
  if (!testing && autosysGateway?.key === key2)
85454
85802
  return autosysGateway.strategy;
@@ -85580,6 +85928,19 @@ ${redact(shown2, cachedSecretValues)}` }
85580
85928
  return new AutosysClient(http, await atlassianConnection("autosys", http), paths);
85581
85929
  }
85582
85930
  let monitorSettingsLoaded = false;
85931
+ let monitorRunContext;
85932
+ let monitorRuns = 0;
85933
+ async function declaredCallsOf(caller) {
85934
+ const found2 = python.findTool(caller);
85935
+ if (found2 === void 0)
85936
+ return [];
85937
+ try {
85938
+ const source = await import_promises29.default.readFile(found2.filePath, "utf8");
85939
+ return hashSource(source) === found2.hash ? declaredToolCalls(source) : [];
85940
+ } catch {
85941
+ return [];
85942
+ }
85943
+ }
85583
85944
  async function executeForMonitor(name, args, given, signal) {
85584
85945
  const { config: config2 } = await configManager.load();
85585
85946
  if (!monitorSettingsLoaded) {
@@ -85611,12 +85972,85 @@ ${redact(shown2, cachedSecretValues)}` }
85611
85972
  return resolved !== void 0 ? { ripgrepPath: resolved } : {};
85612
85973
  })()
85613
85974
  };
85614
- return tool.execute(parsed.data, context);
85975
+ monitorRuns += 1;
85976
+ monitorRunContext = context;
85977
+ try {
85978
+ return await tool.execute(parsed.data, context);
85979
+ } finally {
85980
+ monitorRuns -= 1;
85981
+ if (monitorRuns === 0)
85982
+ monitorRunContext = void 0;
85983
+ }
85615
85984
  }
85616
- services.monitorExecutor?.serve(async (fetch2) => {
85985
+ const monitorStores = /* @__PURE__ */ new Map();
85986
+ async function monitorStore(storeId, index) {
85987
+ const key2 = `${storeId}\0${index}`;
85988
+ const cached2 = monitorStores.get(key2);
85989
+ if (cached2 !== void 0)
85990
+ return cached2;
85991
+ const { config: config2 } = await configManager.load();
85992
+ const store = config2.vectorStores?.[storeId];
85993
+ if (store === void 0)
85994
+ throw new Error(`There is no search connection "${storeId}" in the settings monitoring runs with.`);
85995
+ if (store.kind !== "opensearch")
85996
+ throw new Error(`"${store.label || storeId}" is not an OpenSearch connection; team monitoring keeps its history in OpenSearch.`);
85997
+ if (!monitorSettingsLoaded) {
85998
+ monitorSettingsLoaded = true;
85999
+ await loadSettings();
86000
+ }
86001
+ const by = cachedAttribution.author ?? import_node_os6.default.userInfo().username;
86002
+ const made = new MonitorHistoryStore(httpClient, await vectorStoreConnectionFor(store, storeId), index, by);
86003
+ monitorStores.set(key2, made);
86004
+ return made;
86005
+ }
86006
+ async function answerMonitorStore(op, store, args) {
86007
+ const monitor = typeof args["monitor"] === "string" ? args["monitor"] : "";
86008
+ switch (op) {
86009
+ case "claim":
86010
+ return store.claim(monitor, Number(args["slot"] ?? 0));
86011
+ case "write":
86012
+ await store.write(args["record"]);
86013
+ return { by: store.by };
86014
+ case "latest":
86015
+ return store.latest(Array.isArray(args["monitors"]) ? args["monitors"] : []);
86016
+ case "history":
86017
+ return store.history(monitor, Number(args["since"] ?? 0), Number(args["limit"] ?? 500));
86018
+ case "prune":
86019
+ return { deleted: await store.prune(Number(args["before"] ?? 0), monitor.length > 0 ? monitor : void 0) };
86020
+ case "test":
86021
+ await store.ensureIndex();
86022
+ return { index: store.index, by: store.by };
86023
+ default:
86024
+ throw new Error(`"${op}" is not a monitoring history operation.`);
86025
+ }
86026
+ }
86027
+ async function explainForMonitor(context) {
86028
+ const config2 = await loadSettings();
86029
+ const profile = resolveActiveProfile(config2);
86030
+ const provider = createChatProvider(profile, httpClient, authStrategyFor(config2, profile), logger, services.languageModels);
86031
+ let text2 = "";
86032
+ for await (const chunk of provider.streamChat(explainMessages(JSON.parse(redact(JSON.stringify(context), cachedSecretValues))))) {
86033
+ if (chunk.type === "text")
86034
+ text2 += chunk.text;
86035
+ if (chunk.type === "error")
86036
+ throw new Error(chunk.error);
86037
+ }
86038
+ if (text2.trim().length === 0)
86039
+ throw new Error("The model replied with nothing.");
86040
+ return text2.trim();
86041
+ }
86042
+ services.monitorExecutor?.serve(async (request) => {
85617
86043
  try {
85618
- const result = await executeForMonitor(fetch2.tool, fetch2.args, void 0, AbortSignal.timeout(Math.max(5e3, fetch2.timeoutMs)));
85619
- return result.isError === true ? { ok: false, error: result.content.slice(0, 4e3) } : { ok: true, text: result.content };
86044
+ switch (request.kind) {
86045
+ case "fetch": {
86046
+ const result = await executeForMonitor(request.tool, request.args, void 0, AbortSignal.timeout(Math.max(5e3, request.timeoutMs)));
86047
+ return result.isError === true ? { ok: false, error: result.content.slice(0, 4e3) } : { ok: true, data: result.content };
86048
+ }
86049
+ case "store":
86050
+ return { ok: true, data: await answerMonitorStore(request.op, await monitorStore(request.storeId, request.index), request.args) };
86051
+ case "explain":
86052
+ return { ok: true, data: await explainForMonitor(request.context) };
86053
+ }
85620
86054
  } catch (error51) {
85621
86055
  return { ok: false, error: error51 instanceof Error ? error51.message : String(error51) };
85622
86056
  }
@@ -85978,7 +86412,7 @@ ${redact(shown2, cachedSecretValues)}` }
85978
86412
  return { reason: "Off." };
85979
86413
  if (!isSafeSegment(settings.project) || !isSafeSegment(settings.repo))
85980
86414
  return { reason: "Enter the project key and repository slug." };
85981
- const digest = (0, import_node_crypto16.createHash)("sha256").update(JSON.stringify([bitbucket.baseUrl, settings.project, settings.repo, settings.branch, settings.folder]).toLowerCase()).digest("hex").slice(0, 12);
86415
+ const digest = (0, import_node_crypto17.createHash)("sha256").update(JSON.stringify([bitbucket.baseUrl, settings.project, settings.repo, settings.branch, settings.folder]).toLowerCase()).digest("hex").slice(0, 12);
85982
86416
  const root = import_node_path52.default.join(mirrorRoot, "teamrepo", `${settings.project}-${settings.repo}-${digest}`.toLowerCase());
85983
86417
  return {
85984
86418
  dirs: { skills: import_node_path52.default.join(root, "skills"), tools: import_node_path52.default.join(root, "tools") },
@@ -87000,7 +87434,7 @@ ${last}` : ""}`);
87000
87434
  });
87001
87435
  const wanted = options.kind;
87002
87436
  const entries = wanted === void 0 ? all : all.filter((entry) => entry.kind === wanted);
87003
- const fingerprint = (0, import_node_crypto16.createHash)("sha256").update(`${wanted ?? "all"}:${embedder.model}:${String(embedder.dimensions)}`).update(entries.map((entry) => `${entry.id}\0${entry.text}`).join("")).digest("hex");
87437
+ const fingerprint = (0, import_node_crypto17.createHash)("sha256").update(`${wanted ?? "all"}:${embedder.model}:${String(embedder.dimensions)}`).update(entries.map((entry) => `${entry.id}\0${entry.text}`).join("")).digest("hex");
87004
87438
  if (!options.force && fingerprint === await readDocsFingerprint(index, search.id, wanted)) {
87005
87439
  return { unchanged: true, index, indexed: entries.length };
87006
87440
  }
@@ -88113,7 +88547,7 @@ ${last}` : ""}`);
88113
88547
  try {
88114
88548
  const text2 = (await import_promises29.default.readFile(file2, "utf8")).replace(/\r\n/g, "\n");
88115
88549
  const meaningful = text2.split("\n").filter((line) => !/^(author|project|version|updated)\s*:/i.test(line) && !/^__(author|project|version|updated)__\s*=/.test(line)).join("\n").trim();
88116
- return (0, import_node_crypto16.createHash)("sha256").update(meaningful).digest("hex").slice(0, 16);
88550
+ return (0, import_node_crypto17.createHash)("sha256").update(meaningful).digest("hex").slice(0, 16);
88117
88551
  } catch {
88118
88552
  return void 0;
88119
88553
  }
@@ -88802,7 +89236,7 @@ ${last}` : ""}`);
88802
89236
  return;
88803
89237
  }
88804
89238
  const { config: config2 } = await configManager.load();
88805
- const id = input.id ?? (0, import_node_crypto16.randomUUID)();
89239
+ const id = input.id ?? (0, import_node_crypto17.randomUUID)();
88806
89240
  if (input.username !== void 0 && input.username.length > 0)
88807
89241
  await secrets.set(searchUserRefFor(id), input.username);
88808
89242
  if (input.password !== void 0 && input.password.length > 0)
@@ -90553,7 +90987,7 @@ ${contents}
90553
90987
  async function handleSaveSchedule(schedule) {
90554
90988
  try {
90555
90989
  const schedules = await loadSchedules();
90556
- const id = schedule.id.length > 0 ? schedule.id : (0, import_node_crypto16.createHash)("sha256").update(`${schedule.name}:${String(Date.now())}`).digest("hex").slice(0, 12);
90990
+ const id = schedule.id.length > 0 ? schedule.id : (0, import_node_crypto17.createHash)("sha256").update(`${schedule.name}:${String(Date.now())}`).digest("hex").slice(0, 12);
90557
90991
  const armed = { ...schedule, id, nextRunAt: nextFireTime(schedule, Date.now()) };
90558
90992
  await saveSchedules({ ...schedules, [id]: armed });
90559
90993
  } catch (error51) {
@@ -90562,7 +90996,7 @@ ${contents}
90562
90996
  }
90563
90997
  async function createScheduleFromProposal(proposal) {
90564
90998
  const schedules = await loadSchedules();
90565
- const id = (0, import_node_crypto16.createHash)("sha256").update(`${proposal.name}:${String(Date.now())}`).digest("hex").slice(0, 12);
90999
+ const id = (0, import_node_crypto17.createHash)("sha256").update(`${proposal.name}:${String(Date.now())}`).digest("hex").slice(0, 12);
90566
91000
  const schedule = {
90567
91001
  id,
90568
91002
  name: proposal.name,
@@ -93033,7 +93467,12 @@ signs in without listing any jobs; with **Job to check in Test connection** fill
93033
93467
  \`<site>/job/<name>\` in Postman, so the two answers can be compared. Under its result, **Details** shows every request it made and what
93034
93468
  came back - the address, HTTP status, response headers and the start of the body, the gateway's token
93035
93469
  request first - with passwords, tokens and secrets masked; open by default when the test failed, with a
93036
- **Copy details** button for whoever runs the service. Error messages name the HTTP status (401 not signed
93470
+ **Copy details** button for whoever runs the service. Details begin with **Likely cause**, the first step that failed
93471
+ read in plain words (a name that does not resolve, a certificate not trusted, a redirect to a login page, what a
93472
+ 401, 403 or 404 usually means there), and each step says the same - for Confluence, Jira, Bitbucket and Jenkins too.
93473
+ **A pattern finds only some jobs?** Many servers answer a page at a time; when an answer says it has more (a total,
93474
+ a "next" link), the status and find tools say how many came back of how many, and to add the server's page-size
93475
+ parameter to the address in config:autosys (paths) - autosys_check_addresses shows what each address answers. Error messages name the HTTP status (401 not signed
93037
93476
  in, 403 forbidden - signed in but that account is not allowed) so they can be compared with Postman.
93038
93477
 
93039
93478
  **Read-only access?** Tick **My access is read-only** in the panel. The tools that change things
@@ -94041,7 +94480,17 @@ edits made outside the agent (in VS Code, say) are saved with \`hub_sync\` "push
94041
94480
  "team alerts",
94042
94481
  "personal alerts",
94043
94482
  "monitor_create",
94044
- "quiet hours"
94483
+ "quiet hours",
94484
+ "run window",
94485
+ "specific time",
94486
+ "once a day",
94487
+ "history of alert",
94488
+ "recurring alert",
94489
+ "retention",
94490
+ "cleanup",
94491
+ "opensearch history",
94492
+ "explain alert",
94493
+ "tool_calls"
94045
94494
  ],
94046
94495
  body: `
94047
94496
  **Fire Code only.** Settings \u2192 Monitoring switches it on; a Monitoring button then appears at the top of the
@@ -94083,7 +94532,34 @@ while it stays red or amber, a quiet word when it clears, and quiet hours when o
94083
94532
  Each monitor can override it (right-click \u2192 How this one notifies), and its own \`notify\` sets the least
94084
94533
  severe level that notifies. Notifications have Open, Acknowledge and Snooze buttons.
94085
94534
 
94086
- **Agents can**: \`monitor_check_tool\` (run a tool once and check its answer strictly: PASS or FAIL with what
94535
+ **When checks run**: \`every\` ("15m") for an interval, kept to \`activeHours\` ("07:00-19:00", or "09:00-" for not
94536
+ before nine, "-17:00" for until five); \`at\` for exact times of day ("07:30" - once a day - or ["07:30", "12:00",
94537
+ "18:00"]); \`days\` for the days of the week, for both. A time missed while Fire Code was closed is not made up the
94538
+ next day.
94539
+
94540
+ **Team monitors need OpenSearch** (Settings \u2192 Monitoring \u2192 Team history): choose an OpenSearch connection from the
94541
+ codebase monitoring runs with, and an index name the whole team shares. Without it a team monitor stays grey
94542
+ ("Needs team history"); personal monitors keep their history on this computer. Every member's Fire Code may run a
94543
+ team monitor, but each slot is **claimed** first, so it runs once across the team, and everyone's dashboard shows
94544
+ the newest check, saying who ran it. Writes never overwrite each other, and cleanup removes only your own checks.
94545
+
94546
+ **History** (the grid's History view): a bar per check in its colour, its height how many alerts it had; each
94547
+ alert's pattern - **new** today, **ongoing** since when, **recurring** on several days ("usually starting around
94548
+ 02:00"), comes and goes, or cleared; and any past check's alerted rows. A check keeps its colour, headline and the
94549
+ rows that had an alert. **Kept 90 days** by default (30 days to a year), cleaned every few hours; **Clean up now** in
94550
+ Settings \u2192 Monitoring, and **Delete its history** on a tile's right-click menu. A snoozed or paused monitor keeps its
94551
+ colour on its tile but no longer colours the Monitoring button.
94552
+
94553
+ **An alert explained**: double-click a coloured row. The author's advice for that rule comes first (asked for when
94554
+ the monitor is created), then **the agent's explanation** - what is wrong, whether it is new or known from the
94555
+ history, what to do. **Start a chat** opens a chat named after the alert in the codebase you pick (the first by
94556
+ default), with what is known already in the message box - press Enter to send it.
94557
+
94558
+ **Tools can call tools**: a Python tool lists what it calls in \`__tool_calls__ = ["server__query", "autosys_status"]\`
94559
+ - MCP tools, other Python tools and Fire Code's reading tools. That line is part of the approved code; in a
94560
+ monitor's check those calls run without asking, and nothing that edits or runs commands is reachable.
94561
+
94562
+ **Agents can**: \`monitor_history\` (an alert's history: new, ongoing, recurring), \`monitor_check_tool\` (run a tool once and check its answer strictly: PASS or FAIL with what
94087
94563
  to change, and the columns and key for the monitor - an agent writing a Python tool for a monitor works until
94088
94564
  it passes), \`monitor_status\` (every monitor, or one monitor's alerts and rows), \`monitor_show\` (check
94089
94565
  now, open a grid or the dashboard), \`monitor_control\` (pause, snooze, acknowledge, notification level -
@@ -96135,11 +96611,13 @@ ${entry.record.text}`.toLowerCase();
96135
96611
  }
96136
96612
 
96137
96613
  // ../../packages/core/dist/python/callPolicy.js
96138
- var PYTHON_CALL_DENIED = "A Python tool may only call other Python tools and MCP tools. Built-in tools \u2014 running commands, editing files, creating tools or writing skills \u2014 are deliberately out of reach: a tool body is model-authored, and approving one must not silently grant the rest.";
96139
- function mayPythonToolCall(name, group) {
96614
+ var PYTHON_CALL_DENIED = 'A Python tool may call other Python tools, MCP tools, and the built-in reading tools it declares in __tool_calls__ = ["name", ...]. Built-in tools that run commands, edit files, create tools or write skills are deliberately out of reach: a tool body is model-authored, and approving one must not silently grant the rest.';
96615
+ function mayPythonToolCall(name, group, declared = false) {
96140
96616
  if (name.startsWith("py__"))
96141
96617
  return true;
96142
- return group === "mcp";
96618
+ if (group === "mcp")
96619
+ return true;
96620
+ return declared && group === "read";
96143
96621
  }
96144
96622
  function describeNestedCall(caller, callee) {
96145
96623
  return `The Python tool "${caller}" is asking to call "${callee}".`;
@@ -96242,8 +96720,8 @@ That is a fault in the tool itself, or the source is unreachable from here. Fix
96242
96720
  }
96243
96721
 
96244
96722
  // ../../packages/core/dist/s3/sigv4.js
96245
- var import_node_crypto17 = require("node:crypto");
96246
- var EMPTY_PAYLOAD_SHA256 = (0, import_node_crypto17.createHash)("sha256").update("").digest("hex");
96723
+ var import_node_crypto18 = require("node:crypto");
96724
+ var EMPTY_PAYLOAD_SHA256 = (0, import_node_crypto18.createHash)("sha256").update("").digest("hex");
96247
96725
  function encodeSegment(segment) {
96248
96726
  return encodeURIComponent(segment).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
96249
96727
  }
@@ -96267,10 +96745,10 @@ function amzDate(now) {
96267
96745
  return `${now.toISOString().replace(/[-:]/g, "").slice(0, 15)}Z`;
96268
96746
  }
96269
96747
  function signingKey(secretAccessKey, date5, region, service) {
96270
- const dateKey = (0, import_node_crypto17.createHmac)("sha256", `AWS4${secretAccessKey}`).update(date5).digest();
96271
- const regionKey = (0, import_node_crypto17.createHmac)("sha256", dateKey).update(region).digest();
96272
- const serviceKey = (0, import_node_crypto17.createHmac)("sha256", regionKey).update(service).digest();
96273
- return (0, import_node_crypto17.createHmac)("sha256", serviceKey).update("aws4_request").digest();
96748
+ const dateKey = (0, import_node_crypto18.createHmac)("sha256", `AWS4${secretAccessKey}`).update(date5).digest();
96749
+ const regionKey = (0, import_node_crypto18.createHmac)("sha256", dateKey).update(region).digest();
96750
+ const serviceKey = (0, import_node_crypto18.createHmac)("sha256", regionKey).update(service).digest();
96751
+ return (0, import_node_crypto18.createHmac)("sha256", serviceKey).update("aws4_request").digest();
96274
96752
  }
96275
96753
  function signRequest(input) {
96276
96754
  const service = input.service ?? "s3";
@@ -96279,7 +96757,7 @@ function signRequest(input) {
96279
96757
  const date5 = timestamp.slice(0, 8);
96280
96758
  const url2 = new URL(input.url);
96281
96759
  const body = input.body ?? Buffer.alloc(0);
96282
- const payloadHash = (0, import_node_crypto17.createHash)("sha256").update(body).digest("hex");
96760
+ const payloadHash = (0, import_node_crypto18.createHash)("sha256").update(body).digest("hex");
96283
96761
  const headers = {
96284
96762
  ...input.headers,
96285
96763
  host: url2.host,
@@ -96303,9 +96781,9 @@ function signRequest(input) {
96303
96781
  "AWS4-HMAC-SHA256",
96304
96782
  timestamp,
96305
96783
  scope,
96306
- (0, import_node_crypto17.createHash)("sha256").update(canonicalRequest).digest("hex")
96784
+ (0, import_node_crypto18.createHash)("sha256").update(canonicalRequest).digest("hex")
96307
96785
  ].join("\n");
96308
- const signature = (0, import_node_crypto17.createHmac)("sha256", signingKey(input.secretAccessKey, date5, input.region, service)).update(stringToSign).digest("hex");
96786
+ const signature = (0, import_node_crypto18.createHmac)("sha256", signingKey(input.secretAccessKey, date5, input.region, service)).update(stringToSign).digest("hex");
96309
96787
  return {
96310
96788
  headers: {
96311
96789
  ...headers,
@@ -96826,15 +97304,15 @@ function createS3Tools(targets) {
96826
97304
  }
96827
97305
 
96828
97306
  // ../../packages/core/dist/s3/localFolder.js
96829
- var import_node_crypto18 = require("node:crypto");
97307
+ var import_node_crypto19 = require("node:crypto");
96830
97308
  function mirrorFolder(options) {
96831
97309
  const connection = safeSegment(options.connectionId);
96832
- const digest = (0, import_node_crypto18.createHash)("sha256").update((options.prefix ?? "").trim().toLowerCase()).digest("hex").slice(0, 8);
97310
+ const digest = (0, import_node_crypto19.createHash)("sha256").update((options.prefix ?? "").trim().toLowerCase()).digest("hex").slice(0, 8);
96833
97311
  return join2(options.storageDir, "s3", connection, `${options.kind}-${digest}`);
96834
97312
  }
96835
97313
  function safeSegment(id) {
96836
97314
  const cleaned = id.replace(/[^a-zA-Z0-9._-]/g, "-").replace(/-+/g, "-").replace(/^[-.]+|[-.]+$/g, "").slice(0, 40);
96837
- const suffix = (0, import_node_crypto18.createHash)("sha256").update(id).digest("hex").slice(0, 6);
97315
+ const suffix = (0, import_node_crypto19.createHash)("sha256").update(id).digest("hex").slice(0, 6);
96838
97316
  return `${cleaned === "" ? "connection" : cleaned}-${suffix}`;
96839
97317
  }
96840
97318
  function join2(...parts) {
@@ -96951,13 +97429,13 @@ function reachableOrigins(hosts, extra = []) {
96951
97429
  }
96952
97430
 
96953
97431
  // src/identity.ts
96954
- var import_node_crypto19 = __toESM(require("node:crypto"), 1);
97432
+ var import_node_crypto20 = __toESM(require("node:crypto"), 1);
96955
97433
  var SingleUserIdentity = class _SingleUserIdentity {
96956
97434
  describe;
96957
97435
  static PRINCIPAL = { id: "local", displayName: "Local user" };
96958
97436
  principal;
96959
97437
  /** Long-lived, minted per server run, only ever sent in an `Authorization` header. */
96960
- sessionToken = import_node_crypto19.default.randomBytes(32).toString("base64url");
97438
+ sessionToken = import_node_crypto20.default.randomBytes(32).toString("base64url");
96961
97439
  /**
96962
97440
  * Single-use and short-lived, because it travels in the launch URL's fragment where it
96963
97441
  * can end up in shell history or a terminal scrollback (§14).
@@ -96967,7 +97445,7 @@ var SingleUserIdentity = class _SingleUserIdentity {
96967
97445
  * raises it, and what that costs is stated where it is set: a longer window is a longer time in
96968
97446
  * which somebody reading that scrollback can use it before you do.
96969
97447
  */
96970
- handoffToken = import_node_crypto19.default.randomBytes(32).toString("base64url");
97448
+ handoffToken = import_node_crypto20.default.randomBytes(32).toString("base64url");
96971
97449
  handoffExpiresAt;
96972
97450
  handoffSeconds;
96973
97451
  /**
@@ -97001,7 +97479,7 @@ var SingleUserIdentity = class _SingleUserIdentity {
97001
97479
  * which is the same person it was printed to in the first place.
97002
97480
  */
97003
97481
  remintHandoff() {
97004
- this.handoffToken = import_node_crypto19.default.randomBytes(32).toString("base64url");
97482
+ this.handoffToken = import_node_crypto20.default.randomBytes(32).toString("base64url");
97005
97483
  this.handoffExpiresAt = Date.now() + this.handoffSeconds * 1e3;
97006
97484
  return this.handoffToken;
97007
97485
  }
@@ -97040,10 +97518,10 @@ function timingSafeEquals(a, b) {
97040
97518
  const left = Buffer.from(a);
97041
97519
  const right = Buffer.from(b);
97042
97520
  if (left.length !== right.length) return false;
97043
- return import_node_crypto19.default.timingSafeEqual(left, right);
97521
+ return import_node_crypto20.default.timingSafeEqual(left, right);
97044
97522
  }
97045
97523
  function storageKeyFor(principal) {
97046
- return import_node_crypto19.default.createHash("sha256").update(principal.id).digest("hex").slice(0, 32);
97524
+ return import_node_crypto20.default.createHash("sha256").update(principal.id).digest("hex").slice(0, 32);
97047
97525
  }
97048
97526
  var OpenIdentity = class _OpenIdentity {
97049
97527
  describe = "single user, no token (--no-token)";
@@ -97317,19 +97795,19 @@ var import_promises32 = __toESM(require("node:fs/promises"), 1);
97317
97795
  var import_node_path58 = __toESM(require("node:path"), 1);
97318
97796
 
97319
97797
  // src/vaultCrypto.ts
97320
- var import_node_crypto20 = require("node:crypto");
97798
+ var import_node_crypto21 = require("node:crypto");
97321
97799
  function isVaultEnvelope(value) {
97322
97800
  const v = value;
97323
97801
  return typeof v === "object" && v !== null && v.sunVault === 1 && typeof v.iv === "string" && typeof v.tag === "string" && typeof v.data === "string";
97324
97802
  }
97325
97803
  function sealSecrets(secrets, key2) {
97326
- const iv = (0, import_node_crypto20.randomBytes)(12);
97327
- const cipher = (0, import_node_crypto20.createCipheriv)("aes-256-gcm", key2, iv);
97804
+ const iv = (0, import_node_crypto21.randomBytes)(12);
97805
+ const cipher = (0, import_node_crypto21.createCipheriv)("aes-256-gcm", key2, iv);
97328
97806
  const data = Buffer.concat([cipher.update(JSON.stringify(secrets), "utf8"), cipher.final()]);
97329
97807
  return { sunVault: 1, iv: iv.toString("base64"), tag: cipher.getAuthTag().toString("base64"), data: data.toString("base64") };
97330
97808
  }
97331
97809
  function openSecrets(envelope, key2) {
97332
- const decipher = (0, import_node_crypto20.createDecipheriv)("aes-256-gcm", key2, Buffer.from(envelope.iv, "base64"));
97810
+ const decipher = (0, import_node_crypto21.createDecipheriv)("aes-256-gcm", key2, Buffer.from(envelope.iv, "base64"));
97333
97811
  decipher.setAuthTag(Buffer.from(envelope.tag, "base64"));
97334
97812
  const plain = Buffer.concat([decipher.update(Buffer.from(envelope.data, "base64")), decipher.final()]);
97335
97813
  const parsed = JSON.parse(plain.toString("utf8"));
@@ -97447,7 +97925,7 @@ var FileSecretStore = class {
97447
97925
  };
97448
97926
 
97449
97927
  // src/reviewQueue.ts
97450
- var import_node_crypto21 = __toESM(require("node:crypto"), 1);
97928
+ var import_node_crypto22 = __toESM(require("node:crypto"), 1);
97451
97929
  var import_promises33 = __toESM(require("node:fs/promises"), 1);
97452
97930
  var import_node_path59 = __toESM(require("node:path"), 1);
97453
97931
  var ReviewQueue = class {
@@ -97486,7 +97964,7 @@ var ReviewQueue = class {
97486
97964
  );
97487
97965
  const queued = {
97488
97966
  ...request,
97489
- id: import_node_crypto21.default.randomUUID(),
97967
+ id: import_node_crypto22.default.randomUUID(),
97490
97968
  submittedAt: Date.now(),
97491
97969
  status: "pending"
97492
97970
  };