@chosengeneration/light-code 0.180.0 → 0.182.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 +1880 -1056
  2. package/dist/server.cjs +990 -216
  3. package/package.json +1 -1
package/dist/server.cjs CHANGED
@@ -16101,8 +16101,8 @@ var require_receiver = __commonJS({
16101
16101
  } else if (this.#info.opcode === opcodes.PING) {
16102
16102
  const body = this.consume(payloadLength);
16103
16103
  if (!this.ws[kReceivedClose]) {
16104
- const frame = new WebsocketFrameSend(body);
16105
- this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG));
16104
+ const frame2 = new WebsocketFrameSend(body);
16105
+ this.ws[kResponse].socket.write(frame2.createFrame(opcodes.PONG));
16106
16106
  if (channels.ping.hasSubscribers) {
16107
16107
  channels.ping.publish({
16108
16108
  payload: body
@@ -16369,19 +16369,19 @@ var require_websocket = __commonJS({
16369
16369
  failWebsocketConnection(this, "Connection was closed before it was established.");
16370
16370
  this[kReadyState] = _WebSocket.CLOSING;
16371
16371
  } else if (!isClosing(this)) {
16372
- const frame = new WebsocketFrameSend();
16372
+ const frame2 = new WebsocketFrameSend();
16373
16373
  if (code !== void 0 && reason === void 0) {
16374
- frame.frameData = Buffer.allocUnsafe(2);
16375
- frame.frameData.writeUInt16BE(code, 0);
16374
+ frame2.frameData = Buffer.allocUnsafe(2);
16375
+ frame2.frameData.writeUInt16BE(code, 0);
16376
16376
  } else if (code !== void 0 && reason !== void 0) {
16377
- frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength);
16378
- frame.frameData.writeUInt16BE(code, 0);
16379
- frame.frameData.write(reason, 2, "utf-8");
16377
+ frame2.frameData = Buffer.allocUnsafe(2 + reasonByteLength);
16378
+ frame2.frameData.writeUInt16BE(code, 0);
16379
+ frame2.frameData.write(reason, 2, "utf-8");
16380
16380
  } else {
16381
- frame.frameData = emptyBuffer;
16381
+ frame2.frameData = emptyBuffer;
16382
16382
  }
16383
16383
  const socket = this[kResponse].socket;
16384
- socket.write(frame.createFrame(opcodes.CLOSE), (err) => {
16384
+ socket.write(frame2.createFrame(opcodes.CLOSE), (err) => {
16385
16385
  if (!err) {
16386
16386
  this[kSentClose] = true;
16387
16387
  }
@@ -16408,34 +16408,34 @@ var require_websocket = __commonJS({
16408
16408
  const socket = this[kResponse].socket;
16409
16409
  if (typeof data === "string") {
16410
16410
  const value = Buffer.from(data);
16411
- const frame = new WebsocketFrameSend(value);
16412
- const buffer = frame.createFrame(opcodes.TEXT);
16411
+ const frame2 = new WebsocketFrameSend(value);
16412
+ const buffer = frame2.createFrame(opcodes.TEXT);
16413
16413
  this.#bufferedAmount += value.byteLength;
16414
16414
  socket.write(buffer, () => {
16415
16415
  this.#bufferedAmount -= value.byteLength;
16416
16416
  });
16417
16417
  } else if (types.isArrayBuffer(data)) {
16418
16418
  const value = Buffer.from(data);
16419
- const frame = new WebsocketFrameSend(value);
16420
- const buffer = frame.createFrame(opcodes.BINARY);
16419
+ const frame2 = new WebsocketFrameSend(value);
16420
+ const buffer = frame2.createFrame(opcodes.BINARY);
16421
16421
  this.#bufferedAmount += value.byteLength;
16422
16422
  socket.write(buffer, () => {
16423
16423
  this.#bufferedAmount -= value.byteLength;
16424
16424
  });
16425
16425
  } else if (ArrayBuffer.isView(data)) {
16426
16426
  const ab = Buffer.from(data, data.byteOffset, data.byteLength);
16427
- const frame = new WebsocketFrameSend(ab);
16428
- const buffer = frame.createFrame(opcodes.BINARY);
16427
+ const frame2 = new WebsocketFrameSend(ab);
16428
+ const buffer = frame2.createFrame(opcodes.BINARY);
16429
16429
  this.#bufferedAmount += ab.byteLength;
16430
16430
  socket.write(buffer, () => {
16431
16431
  this.#bufferedAmount -= ab.byteLength;
16432
16432
  });
16433
16433
  } else if (isBlobLike(data)) {
16434
- const frame = new WebsocketFrameSend();
16434
+ const frame2 = new WebsocketFrameSend();
16435
16435
  data.arrayBuffer().then((ab) => {
16436
16436
  const value = Buffer.from(ab);
16437
- frame.frameData = value;
16438
- const buffer = frame.createFrame(opcodes.BINARY);
16437
+ frame2.frameData = value;
16438
+ const buffer = frame2.createFrame(opcodes.BINARY);
16439
16439
  this.#bufferedAmount += value.byteLength;
16440
16440
  socket.write(buffer, () => {
16441
16441
  this.#bufferedAmount -= value.byteLength;
@@ -19732,7 +19732,7 @@ var require_compile = __commonJS({
19732
19732
  }
19733
19733
  }
19734
19734
  exports2.compileSchema = compileSchema;
19735
- function resolveRef2(root, baseId, ref) {
19735
+ function resolveRef3(root, baseId, ref) {
19736
19736
  var _a3;
19737
19737
  ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
19738
19738
  const schOrFunc = root.refs[ref];
@@ -19749,7 +19749,7 @@ var require_compile = __commonJS({
19749
19749
  return;
19750
19750
  return root.refs[ref] = inlineOrCompile.call(this, _sch);
19751
19751
  }
19752
- exports2.resolveRef = resolveRef2;
19752
+ exports2.resolveRef = resolveRef3;
19753
19753
  function inlineOrCompile(sch) {
19754
19754
  if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
19755
19755
  return sch.schema;
@@ -43397,6 +43397,281 @@ function normalizeObjectSchema(parameters) {
43397
43397
  return normalized;
43398
43398
  }
43399
43399
 
43400
+ // ../../packages/core/dist/providers/geminiCompat.js
43401
+ var SKIP_SIGNATURE = "skip_thought_signature_validator";
43402
+ function isGeminiModel(model, baseUrl = "") {
43403
+ return /gemini/i.test(model) || /generativelanguage\.googleapis\.com/i.test(baseUrl);
43404
+ }
43405
+ function requiresSignature(model) {
43406
+ return !/gemini[-_ ]?(1|2)(\b|[.-])/i.test(model);
43407
+ }
43408
+ function toGeminiCompatTools(definitions) {
43409
+ const reshaped = /* @__PURE__ */ new Map();
43410
+ const tools = definitions.map((tool) => {
43411
+ const root = normalizeObjectSchema(tool.parameters);
43412
+ const found2 = [];
43413
+ const parameters = convert(root, root, [], found2, 0, true);
43414
+ if (found2.length > 0)
43415
+ reshaped.set(tool.name, found2);
43416
+ return {
43417
+ type: "function",
43418
+ function: { name: tool.name, description: tool.description, parameters }
43419
+ };
43420
+ });
43421
+ return { tools, reshaped };
43422
+ }
43423
+ function restoreArguments(argumentsJson, reshaped) {
43424
+ if (reshaped === void 0 || reshaped.length === 0)
43425
+ return argumentsJson;
43426
+ let args;
43427
+ try {
43428
+ args = JSON.parse(argumentsJson.length > 0 ? argumentsJson : "{}");
43429
+ } catch {
43430
+ return argumentsJson;
43431
+ }
43432
+ for (const entry of reshaped)
43433
+ restoreAt(args, entry.path, entry.kind);
43434
+ return JSON.stringify(args);
43435
+ }
43436
+ function restoreAt(value, path65, kind) {
43437
+ if (path65.length === 0) {
43438
+ if (typeof value !== "string")
43439
+ return value;
43440
+ if (kind === "number") {
43441
+ const number5 = Number(value);
43442
+ return Number.isFinite(number5) && value.trim().length > 0 ? number5 : value;
43443
+ }
43444
+ try {
43445
+ return JSON.parse(value);
43446
+ } catch {
43447
+ return value;
43448
+ }
43449
+ }
43450
+ const [head, ...rest] = path65;
43451
+ if (head === "[]") {
43452
+ if (Array.isArray(value))
43453
+ for (let i = 0; i < value.length; i += 1)
43454
+ value[i] = restoreAt(value[i], rest, kind);
43455
+ return value;
43456
+ }
43457
+ if (isRecord2(value) && head !== void 0 && head in value)
43458
+ value[head] = restoreAt(value[head], rest, kind);
43459
+ return value;
43460
+ }
43461
+ var SCALARS = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean"]);
43462
+ var MAX_DEPTH = 12;
43463
+ function convert(schema11, root, path65, found2, depth, isRoot = false) {
43464
+ if (!isRecord2(schema11))
43465
+ return { type: "string" };
43466
+ if (depth > MAX_DEPTH)
43467
+ return asJsonString(schema11, path65, found2, "nested too deeply to describe here");
43468
+ let node = { ...schema11 };
43469
+ if (typeof node.$ref === "string") {
43470
+ const target = resolveRef2(node.$ref, root);
43471
+ if (target === void 0)
43472
+ return asJsonString(node, path65, found2, "a structured value");
43473
+ const { $ref: _ref, ...siblings } = node;
43474
+ void _ref;
43475
+ node = { ...target, ...siblings };
43476
+ }
43477
+ if (Array.isArray(node.allOf))
43478
+ node = mergeAllOf(node, root);
43479
+ const union2 = unionOf(node, root);
43480
+ if (union2 !== void 0) {
43481
+ const nullable2 = union2.some((branch) => branch.type === "null");
43482
+ const branches = union2.filter((branch) => branch.type !== "null");
43483
+ const describedBase = baseDescription(node);
43484
+ if (branches.length === 1) {
43485
+ const merged = { ...branches[0] };
43486
+ if (describedBase !== void 0 && merged.description === void 0)
43487
+ merged.description = describedBase;
43488
+ const converted = convert(merged, root, path65, found2, depth + 1);
43489
+ if (nullable2)
43490
+ converted.nullable = true;
43491
+ return converted;
43492
+ }
43493
+ const allEnums = branches.every((branch) => Array.isArray(branch.enum) || branch.const !== void 0);
43494
+ if (allEnums) {
43495
+ const values = branches.flatMap((branch) => Array.isArray(branch.enum) ? branch.enum : [branch.const]);
43496
+ return convert({ ...withoutUnion(node), enum: values, ...nullable2 ? { nullable: true } : {} }, root, path65, found2, depth + 1);
43497
+ }
43498
+ const allScalars = branches.every((branch) => typeof branch.type === "string" && SCALARS.has(branch.type));
43499
+ if (allScalars) {
43500
+ const types = branches.map((branch) => branch.type);
43501
+ const chosen = types.includes("string") ? "string" : types[0];
43502
+ const note = `Accepts ${types.join(" or ")}.`;
43503
+ return convert({ ...withoutUnion(node), type: chosen, description: join(baseDescription(node), note), ...nullable2 ? { nullable: true } : {} }, root, path65, found2, depth + 1);
43504
+ }
43505
+ return asJsonString(node, path65, found2, describeUnion(branches));
43506
+ }
43507
+ const type = node.type;
43508
+ const notes = describeDropped(node);
43509
+ const out = {};
43510
+ if (typeof type === "string")
43511
+ out.type = type;
43512
+ if (type === "object" || type === void 0 && isRecord2(node.properties)) {
43513
+ out.type = "object";
43514
+ const properties = isRecord2(node.properties) ? node.properties : {};
43515
+ const names = Object.keys(properties);
43516
+ if (names.length === 0 && !isRoot)
43517
+ return asJsonString(node, path65, found2, "an object with any keys");
43518
+ const converted = {};
43519
+ for (const name of names)
43520
+ converted[name] = convert(properties[name], root, [...path65, name], found2, depth + 1);
43521
+ out.properties = converted;
43522
+ if (Array.isArray(node.required)) {
43523
+ const required2 = node.required.filter((name) => typeof name === "string" && name in converted);
43524
+ if (required2.length > 0)
43525
+ out.required = required2;
43526
+ }
43527
+ } else if (type === "array") {
43528
+ out.items = node.items === void 0 ? { type: "string" } : convert(node.items, root, [...path65, "[]"], found2, depth + 1);
43529
+ } else if (type === void 0 && node.enum === void 0) {
43530
+ return asJsonString(node, path65, found2, "any JSON value");
43531
+ }
43532
+ if (Array.isArray(node.enum)) {
43533
+ const values = node.enum.filter((value) => value !== null);
43534
+ if (values.every((value) => typeof value === "string")) {
43535
+ out.type = "string";
43536
+ out.enum = values;
43537
+ } else if (values.every((value) => typeof value === "number")) {
43538
+ out.type = "string";
43539
+ out.enum = values.map(String);
43540
+ found2.push({ path: path65, kind: "number" });
43541
+ } else {
43542
+ notes.push(`One of: ${values.map((value) => JSON.stringify(value)).join(", ")}.`);
43543
+ }
43544
+ if (node.enum.includes(null))
43545
+ out.nullable = true;
43546
+ }
43547
+ if (node.nullable === true)
43548
+ out.nullable = true;
43549
+ const description = join(typeof node.description === "string" ? node.description : void 0, ...notes);
43550
+ if (description !== void 0)
43551
+ out.description = description;
43552
+ return out;
43553
+ }
43554
+ function asJsonString(node, path65, found2, what) {
43555
+ found2.push({ path: path65, kind: "json" });
43556
+ const example = exampleFor(node);
43557
+ return {
43558
+ type: "string",
43559
+ description: join(baseDescription(node), `Write ${what} as JSON text${example !== void 0 ? `, for example ${example}` : ""}. It is passed to the tool as JSON, not as a string.`)
43560
+ };
43561
+ }
43562
+ function exampleFor(node) {
43563
+ if (node.default !== void 0)
43564
+ return JSON.stringify(node.default);
43565
+ if (Array.isArray(node.examples) && node.examples.length > 0)
43566
+ return JSON.stringify(node.examples[0]);
43567
+ if (node.type === "object" || isRecord2(node.properties) || node.additionalProperties !== void 0)
43568
+ return '{"key": "value"}';
43569
+ return void 0;
43570
+ }
43571
+ function describeDropped(node) {
43572
+ const notes = [];
43573
+ const show = (value) => JSON.stringify(value);
43574
+ if (node.const !== void 0)
43575
+ notes.push(`Must be ${show(node.const)}.`);
43576
+ if (node.default !== void 0)
43577
+ notes.push(`Default: ${show(node.default)}.`);
43578
+ if (typeof node.minimum === "number")
43579
+ notes.push(`Minimum ${String(node.minimum)}.`);
43580
+ if (typeof node.exclusiveMinimum === "number")
43581
+ notes.push(`Greater than ${String(node.exclusiveMinimum)}.`);
43582
+ if (typeof node.maximum === "number")
43583
+ notes.push(`Maximum ${String(node.maximum)}.`);
43584
+ if (typeof node.exclusiveMaximum === "number")
43585
+ notes.push(`Less than ${String(node.exclusiveMaximum)}.`);
43586
+ if (typeof node.multipleOf === "number")
43587
+ notes.push(`A multiple of ${String(node.multipleOf)}.`);
43588
+ if (typeof node.minLength === "number" && node.minLength > 0)
43589
+ notes.push(`At least ${String(node.minLength)} characters.`);
43590
+ if (typeof node.maxLength === "number")
43591
+ notes.push(`At most ${String(node.maxLength)} characters.`);
43592
+ if (typeof node.pattern === "string")
43593
+ notes.push(`Must match the pattern ${node.pattern}.`);
43594
+ if (typeof node.format === "string")
43595
+ notes.push(`Format: ${node.format}.`);
43596
+ if (typeof node.minItems === "number" && node.minItems > 0)
43597
+ notes.push(`At least ${String(node.minItems)} items.`);
43598
+ if (typeof node.maxItems === "number")
43599
+ notes.push(`At most ${String(node.maxItems)} items.`);
43600
+ if (node.uniqueItems === true)
43601
+ notes.push("No duplicates.");
43602
+ if (Array.isArray(node.examples) && node.examples.length > 0)
43603
+ notes.push(`Example: ${show(node.examples[0])}.`);
43604
+ return notes;
43605
+ }
43606
+ function describeUnion(branches) {
43607
+ const shapes = branches.map((branch) => {
43608
+ if (typeof branch.description === "string")
43609
+ return branch.description;
43610
+ if (isRecord2(branch.properties))
43611
+ return `an object with ${Object.keys(branch.properties).join(", ")}`;
43612
+ return typeof branch.type === "string" ? `a ${branch.type}` : "a value";
43613
+ });
43614
+ return `one of these (${shapes.join("; ")})`;
43615
+ }
43616
+ function unionOf(node, root) {
43617
+ const raw = Array.isArray(node.anyOf) ? node.anyOf : Array.isArray(node.oneOf) ? node.oneOf : void 0;
43618
+ if (raw !== void 0) {
43619
+ return raw.filter(isRecord2).map((branch) => typeof branch.$ref === "string" ? resolveRef2(branch.$ref, root) ?? branch : branch);
43620
+ }
43621
+ if (Array.isArray(node.type)) {
43622
+ return node.type.filter((type) => typeof type === "string").map((type) => ({ ...withoutUnion(node), type }));
43623
+ }
43624
+ return void 0;
43625
+ }
43626
+ function withoutUnion(node) {
43627
+ const { anyOf: _a3, oneOf: _o, type: _t, ...rest } = node;
43628
+ void _a3;
43629
+ void _o;
43630
+ void _t;
43631
+ return rest;
43632
+ }
43633
+ function mergeAllOf(node, root) {
43634
+ const { allOf, ...rest } = node;
43635
+ const merged = { ...rest };
43636
+ for (const part of allOf) {
43637
+ const branch = isRecord2(part) && typeof part.$ref === "string" ? resolveRef2(part.$ref, root) : part;
43638
+ if (!isRecord2(branch))
43639
+ continue;
43640
+ for (const [key3, value] of Object.entries(branch)) {
43641
+ if (key3 === "properties" && isRecord2(value))
43642
+ merged.properties = { ...isRecord2(merged.properties) ? merged.properties : {}, ...value };
43643
+ else if (key3 === "required" && Array.isArray(value))
43644
+ merged.required = [...Array.isArray(merged.required) ? merged.required : [], ...value];
43645
+ else if (merged[key3] === void 0)
43646
+ merged[key3] = value;
43647
+ }
43648
+ }
43649
+ return merged;
43650
+ }
43651
+ function resolveRef2(ref, root) {
43652
+ if (!ref.startsWith("#"))
43653
+ return void 0;
43654
+ if (ref === "#")
43655
+ return root;
43656
+ let at = root;
43657
+ for (const part of ref.slice(2).split("/")) {
43658
+ if (!isRecord2(at))
43659
+ return void 0;
43660
+ at = at[part.replace(/~1/g, "/").replace(/~0/g, "~")];
43661
+ }
43662
+ return isRecord2(at) ? at : void 0;
43663
+ }
43664
+ function baseDescription(node) {
43665
+ return typeof node.description === "string" && node.description.length > 0 ? node.description : void 0;
43666
+ }
43667
+ function join(...parts) {
43668
+ const text2 = parts.filter((part) => part !== void 0 && part.length > 0).join(" ");
43669
+ return text2.length > 0 ? text2 : void 0;
43670
+ }
43671
+ function isRecord2(value) {
43672
+ return typeof value === "object" && value !== null && !Array.isArray(value);
43673
+ }
43674
+
43400
43675
  // ../../packages/core/dist/providers/thinking.js
43401
43676
  var BUDGETS = {
43402
43677
  low: 2048,
@@ -43438,13 +43713,23 @@ var ThinkTagSplitter = class {
43438
43713
  inside = false;
43439
43714
  /** A partial tag held back until the next chunk says what it is. */
43440
43715
  pending = "";
43716
+ open;
43717
+ close;
43718
+ /**
43719
+ * `think` for Qwen and friends (the default, unchanged). `thought` for Gemini, whose OpenAI-compatible
43720
+ * endpoint wraps the thoughts it was asked to show in `<thought>` tags.
43721
+ */
43722
+ constructor(tag = "think") {
43723
+ this.open = tag === "think" ? OPEN : `<${tag}>`;
43724
+ this.close = tag === "think" ? CLOSE : `</${tag}>`;
43725
+ }
43441
43726
  push(chunk) {
43442
43727
  let text2 = "";
43443
43728
  let reasoning = "";
43444
43729
  let buffer = this.pending + chunk;
43445
43730
  this.pending = "";
43446
43731
  for (; ; ) {
43447
- const marker = this.inside ? CLOSE : OPEN;
43732
+ const marker = this.inside ? this.close : this.open;
43448
43733
  const at = buffer.indexOf(marker);
43449
43734
  if (at !== -1) {
43450
43735
  const before = buffer.slice(0, at);
@@ -43493,7 +43778,7 @@ function partialMarkerLength(buffer, marker) {
43493
43778
  function describeRequestError(error51, url2) {
43494
43779
  return `Could not reach ${url2}: ${describeTlsError(error51)}`;
43495
43780
  }
43496
- function toWireMessage(message5) {
43781
+ function toWireMessage(message5, gemini) {
43497
43782
  if (message5.role === "user" && message5.images !== void 0 && message5.images.length > 0) {
43498
43783
  const parts = message5.images.map((image) => ({
43499
43784
  type: "image_url",
@@ -43507,16 +43792,19 @@ function toWireMessage(message5) {
43507
43792
  const wire = { role: "assistant", content: message5.content };
43508
43793
  if (message5.toolCalls !== void 0 && message5.toolCalls.length > 0) {
43509
43794
  wire.content = message5.content.length > 0 ? message5.content : null;
43510
- wire.tool_calls = message5.toolCalls.map((call) => ({
43511
- id: call.id,
43512
- type: "function",
43513
- function: { name: call.name, arguments: call.arguments }
43514
- }));
43795
+ wire.tool_calls = message5.toolCalls.map((call) => {
43796
+ const entry = { id: call.id, type: "function", function: { name: call.name, arguments: call.arguments } };
43797
+ const signature = call.signature ?? (gemini?.requiresSignature === true ? SKIP_SIGNATURE : void 0);
43798
+ if (gemini !== void 0 && signature !== void 0)
43799
+ entry.extra_content = { google: { thought_signature: signature } };
43800
+ return entry;
43801
+ });
43515
43802
  }
43516
43803
  return wire;
43517
43804
  }
43518
43805
  if (message5.role === "tool") {
43519
- return { role: "tool", tool_call_id: message5.toolCallId, content: message5.content };
43806
+ const content = gemini !== void 0 && message5.content.length === 0 ? "(no output)" : message5.content;
43807
+ return { role: "tool", tool_call_id: message5.toolCallId, content };
43520
43808
  }
43521
43809
  return { role: message5.role, content: message5.content };
43522
43810
  }
@@ -43534,13 +43822,21 @@ var OpenAIProvider = class {
43534
43822
  async *streamChat(messages, options = {}) {
43535
43823
  const url2 = `${this.profile.baseUrl.replace(/\/+$/, "")}/chat/completions`;
43536
43824
  this.logger?.debug("POST", url2, `model=${this.profile.model}`);
43825
+ const gemini = isGeminiModel(this.profile.model, this.profile.baseUrl) ? { requiresSignature: requiresSignature(this.profile.model) } : void 0;
43537
43826
  const body = {
43538
43827
  model: this.profile.model,
43539
- messages: messages.map(toWireMessage),
43828
+ messages: messages.map((message5) => toWireMessage(message5, gemini)),
43540
43829
  stream: true
43541
43830
  };
43831
+ let reshaped;
43542
43832
  if (options.tools !== void 0 && options.tools.length > 0) {
43543
- body.tools = toOpenAITools(options.tools);
43833
+ if (gemini !== void 0) {
43834
+ const converted = toGeminiCompatTools(options.tools);
43835
+ body.tools = converted.tools;
43836
+ reshaped = converted.reshaped;
43837
+ } else {
43838
+ body.tools = toOpenAITools(options.tools);
43839
+ }
43544
43840
  body.tool_choice = "auto";
43545
43841
  }
43546
43842
  const usageKey = this.profile.baseUrl.replace(/\/+$/, "");
@@ -43551,16 +43847,24 @@ var OpenAIProvider = class {
43551
43847
  if (this.profile.topP !== void 0)
43552
43848
  body.top_p = this.profile.topP;
43553
43849
  applyThinking(body, "openai", this.profile.thinking, this.profile.maxTokens);
43850
+ const thoughtsKey = `${usageKey}|thoughts`;
43851
+ if (gemini !== void 0 && this.profile.thinking !== void 0 && this.profile.thinking.level !== "off" && !NO_STREAM_USAGE.has(thoughtsKey)) {
43852
+ body.extra_body = { google: { thinking_config: { include_thoughts: true } } };
43853
+ }
43554
43854
  let response;
43555
43855
  try {
43556
43856
  await this.auth.ensureTokenForStream?.();
43557
43857
  response = await this.send(url2, body, options.signal);
43558
- if (response.status >= 400 && response.status < 500 && response.status !== 401 && body.stream_options !== void 0) {
43858
+ if (response.status >= 400 && response.status < 500 && response.status !== 401 && (body.stream_options !== void 0 || body.extra_body !== void 0)) {
43559
43859
  const text2 = await response.text().catch(() => "");
43560
- if (/stream_options|include_usage/i.test(text2)) {
43860
+ if (body.stream_options !== void 0 && /stream_options|include_usage/i.test(text2)) {
43561
43861
  NO_STREAM_USAGE.add(usageKey);
43562
43862
  delete body.stream_options;
43563
43863
  response = await this.send(url2, body, options.signal);
43864
+ } else if (body.extra_body !== void 0 && /extra_body|thinking_config|include_thoughts/i.test(text2)) {
43865
+ NO_STREAM_USAGE.add(thoughtsKey);
43866
+ delete body.extra_body;
43867
+ response = await this.send(url2, body, options.signal);
43564
43868
  } else {
43565
43869
  yield { type: "error", error: `Request to ${url2} failed with HTTP ${response.status}${text2 ? `: ${text2.slice(0, 500)}` : ""}` };
43566
43870
  return;
@@ -43589,7 +43893,7 @@ var OpenAIProvider = class {
43589
43893
  yield { type: "error", error: `${url2} returned no response body.` };
43590
43894
  return;
43591
43895
  }
43592
- yield* parseSseStream(response.body, url2, options.signal, this.logger);
43896
+ yield* parseSseStream(response.body, url2, options.signal, this.logger, gemini !== void 0 ? { reshaped } : void 0);
43593
43897
  }
43594
43898
  async send(url2, body, signal) {
43595
43899
  const authHeaders = await this.auth.resolveHeaders();
@@ -43631,14 +43935,14 @@ function extractChoice(parsed) {
43631
43935
  const finishReason = typeof first?.finish_reason === "string" ? first.finish_reason : void 0;
43632
43936
  return { delta, finishReason };
43633
43937
  }
43634
- function accumulateToolCallDeltas(accumulators, toolCallsDelta) {
43938
+ function accumulateToolCallDeltas(accumulators, toolCallsDelta, gemini) {
43635
43939
  if (!Array.isArray(toolCallsDelta))
43636
43940
  return;
43637
43941
  for (const raw of toolCallsDelta) {
43638
43942
  if (typeof raw !== "object" || raw === null)
43639
43943
  continue;
43640
43944
  const entry = raw;
43641
- const index = typeof entry.index === "number" ? entry.index : 0;
43945
+ const index = typeof entry.index === "number" ? entry.index : gemini !== void 0 ? geminiIndex(accumulators, entry) : 0;
43642
43946
  const existing = accumulators.get(index) ?? { id: "", name: "", arguments: "" };
43643
43947
  if (typeof entry.id === "string")
43644
43948
  existing.id = entry.id;
@@ -43646,21 +43950,42 @@ function accumulateToolCallDeltas(accumulators, toolCallsDelta) {
43646
43950
  existing.name = entry.function.name;
43647
43951
  if (typeof entry.function?.arguments === "string")
43648
43952
  existing.arguments += entry.function.arguments;
43953
+ const signature = entry.extra_content?.google?.thought_signature;
43954
+ if (gemini !== void 0 && typeof signature === "string" && signature.length > 0)
43955
+ existing.signature = signature;
43649
43956
  accumulators.set(index, existing);
43650
43957
  }
43651
43958
  }
43652
- function* completedToolCalls(accumulators) {
43959
+ function geminiIndex(accumulators, entry) {
43960
+ if (typeof entry.id === "string" && entry.id.length > 0) {
43961
+ for (const [index, call] of accumulators)
43962
+ if (call.id === entry.id)
43963
+ return index;
43964
+ }
43965
+ if (typeof entry.function?.name === "string" && entry.function.name.length > 0)
43966
+ return accumulators.size;
43967
+ return Math.max(0, accumulators.size - 1);
43968
+ }
43969
+ function* completedToolCalls(accumulators, gemini) {
43970
+ let position = 0;
43653
43971
  for (const call of accumulators.values()) {
43654
- if (call.id.length > 0 && call.name.length > 0) {
43655
- yield { id: call.id, name: call.name, arguments: call.arguments };
43972
+ position += 1;
43973
+ const id = call.id.length > 0 ? call.id : gemini !== void 0 ? `call_${String(Date.now())}_${String(position)}` : "";
43974
+ if (id.length > 0 && call.name.length > 0) {
43975
+ yield {
43976
+ id,
43977
+ name: call.name,
43978
+ arguments: gemini !== void 0 ? restoreArguments(call.arguments, gemini.reshaped?.get(call.name)) : call.arguments,
43979
+ ...call.signature !== void 0 ? { signature: call.signature } : {}
43980
+ };
43656
43981
  }
43657
43982
  }
43658
43983
  }
43659
- async function* parseSseStream(body, url2, signal, logger) {
43984
+ async function* parseSseStream(body, url2, signal, logger, gemini) {
43660
43985
  const reader = body.getReader();
43661
43986
  const decoder2 = new TextDecoder();
43662
43987
  let buffer = "";
43663
- const thinking = new ThinkTagSplitter();
43988
+ const thinking = new ThinkTagSplitter(gemini !== void 0 ? "thought" : "think");
43664
43989
  const toolCallAccumulators = /* @__PURE__ */ new Map();
43665
43990
  let finishedAt;
43666
43991
  const AFTER_FINISH_MS = 5e3;
@@ -43699,6 +44024,7 @@ async function* parseSseStream(body, url2, signal, logger) {
43699
44024
  continue;
43700
44025
  const data = trimmed.slice("data:".length).trim();
43701
44026
  if (data === "[DONE]") {
44027
+ yield* unannouncedToolCalls();
43702
44028
  yield { type: "done" };
43703
44029
  return;
43704
44030
  }
@@ -43721,9 +44047,9 @@ async function* parseSseStream(body, url2, signal, logger) {
43721
44047
  if (split.text.length > 0)
43722
44048
  yield { type: "text", text: split.text };
43723
44049
  }
43724
- accumulateToolCallDeltas(toolCallAccumulators, choice.delta.tool_calls);
44050
+ accumulateToolCallDeltas(toolCallAccumulators, choice.delta.tool_calls, gemini);
43725
44051
  if (choice.finishReason === "tool_calls" && finishedAt === void 0) {
43726
- for (const toolCall of completedToolCalls(toolCallAccumulators)) {
44052
+ for (const toolCall of completedToolCalls(toolCallAccumulators, gemini)) {
43727
44053
  yield { type: "toolCall", toolCall };
43728
44054
  }
43729
44055
  finishedAt = Date.now();
@@ -43732,6 +44058,7 @@ async function* parseSseStream(body, url2, signal, logger) {
43732
44058
  }
43733
44059
  }
43734
44060
  }
44061
+ yield* unannouncedToolCalls();
43735
44062
  yield { type: "done" };
43736
44063
  } catch (error51) {
43737
44064
  if (signal?.aborted) {
@@ -43742,6 +44069,13 @@ async function* parseSseStream(body, url2, signal, logger) {
43742
44069
  } finally {
43743
44070
  reader.releaseLock();
43744
44071
  }
44072
+ function* unannouncedToolCalls() {
44073
+ if (finishedAt !== void 0)
44074
+ return;
44075
+ finishedAt = Date.now();
44076
+ for (const toolCall of completedToolCalls(toolCallAccumulators, gemini))
44077
+ yield { type: "toolCall", toolCall };
44078
+ }
43745
44079
  }
43746
44080
 
43747
44081
  // ../../packages/core/dist/providers/anthropic.js
@@ -43997,13 +44331,16 @@ var GeminiProvider = class {
43997
44331
  const base = this.profile.baseUrl.replace(/\/+$/, "");
43998
44332
  const url2 = `${base}/models/${encodeURIComponent(this.profile.model)}:streamGenerateContent?alt=sse`;
43999
44333
  this.logger?.debug("POST", url2);
44000
- const { systemInstruction, contents } = toGeminiContents(messages);
44334
+ const { systemInstruction, contents } = toGeminiContents(messages, requiresSignature(this.profile.model));
44001
44335
  const body = { contents };
44002
44336
  if (systemInstruction !== void 0) {
44003
44337
  body.systemInstruction = { parts: [{ text: systemInstruction }] };
44004
44338
  }
44339
+ let reshaped;
44005
44340
  if (options.tools !== void 0 && options.tools.length > 0) {
44006
- body.tools = toGeminiTools(options.tools);
44341
+ const converted = toGeminiCompatTools(options.tools);
44342
+ reshaped = converted.reshaped;
44343
+ body.tools = [{ functionDeclarations: converted.tools.map((tool) => tool.function) }];
44007
44344
  }
44008
44345
  if (this.profile.maxTokens !== void 0) {
44009
44346
  body.generationConfig = { maxOutputTokens: this.profile.maxTokens };
@@ -44047,7 +44384,7 @@ var GeminiProvider = class {
44047
44384
  yield { type: "error", error: `${url2} returned no response body.` };
44048
44385
  return;
44049
44386
  }
44050
- yield* parseGeminiStream(response.body, url2, options.signal);
44387
+ yield* parseGeminiStream(response.body, url2, options.signal, reshaped);
44051
44388
  }
44052
44389
  async send(url2, body, signal) {
44053
44390
  const authHeaders = await this.auth.resolveHeaders();
@@ -44074,7 +44411,7 @@ function buildIdToName(messages) {
44074
44411
  }
44075
44412
  return map2;
44076
44413
  }
44077
- function toGeminiContents(messages) {
44414
+ function toGeminiContents(messages, fillSignatures = false) {
44078
44415
  const systemInstruction = messages.find((message5) => message5.role === "system")?.content;
44079
44416
  const idToName = buildIdToName(messages);
44080
44417
  const contents = [];
@@ -44117,7 +44454,11 @@ function toGeminiContents(messages) {
44117
44454
  if (message5.content.length > 0)
44118
44455
  parts.push({ text: message5.content });
44119
44456
  for (const toolCall of message5.toolCalls ?? []) {
44120
- parts.push({ functionCall: { name: toolCall.name, args: safeParseArguments2(toolCall.arguments) } });
44457
+ const signature = toolCall.signature ?? (fillSignatures ? SKIP_SIGNATURE : void 0);
44458
+ parts.push({
44459
+ functionCall: { name: toolCall.name, args: safeParseArguments2(toolCall.arguments) },
44460
+ ...signature !== void 0 ? { thoughtSignature: signature } : {}
44461
+ });
44121
44462
  }
44122
44463
  if (parts.length > 0)
44123
44464
  contents.push({ role: "model", parts });
@@ -44134,7 +44475,7 @@ function safeParseArguments2(raw) {
44134
44475
  return {};
44135
44476
  }
44136
44477
  }
44137
- async function* parseGeminiStream(body, url2, signal) {
44478
+ async function* parseGeminiStream(body, url2, signal, reshaped) {
44138
44479
  const reader = body.getReader();
44139
44480
  const decoder2 = new TextDecoder();
44140
44481
  let buffer = "";
@@ -44185,7 +44526,9 @@ async function* parseGeminiStream(body, url2, signal) {
44185
44526
  toolCalls.push({
44186
44527
  id: (0, import_node_crypto3.randomUUID)(),
44187
44528
  name: part.functionCall.name,
44188
- arguments: JSON.stringify(part.functionCall.args ?? {})
44529
+ arguments: restoreArguments(JSON.stringify(part.functionCall.args ?? {}), reshaped?.get(part.functionCall.name)),
44530
+ // Returned with the call next time, or Gemini 3 and later refuse the request.
44531
+ ...typeof part.thoughtSignature === "string" && part.thoughtSignature.length > 0 ? { signature: part.thoughtSignature } : {}
44189
44532
  });
44190
44533
  }
44191
44534
  }
@@ -45229,6 +45572,30 @@ var Conversation = class {
45229
45572
  }
45230
45573
  };
45231
45574
 
45575
+ // ../../packages/core/dist/agent/modelGuidance.js
45576
+ function modelGuidance(model, baseUrl) {
45577
+ if (model === void 0 || !isGeminiModel(model, baseUrl))
45578
+ return void 0;
45579
+ return [
45580
+ "## Working with these tools (Gemini)",
45581
+ "",
45582
+ "- Call a tool only through function calling. Never write a call out as text or as code",
45583
+ " (no `default_api.read_file(...)`, no ```tool_code blocks): written out, nothing runs.",
45584
+ "- **One function call per response.** Only the first one runs; send the next after you have",
45585
+ " its result. Do not plan several calls ahead and assume they ran.",
45586
+ "- Use the parameter names exactly as the tool declares them, with the declared types. A",
45587
+ ' parameter described as "JSON text" takes a JSON string - for `call_tool`, `arguments` is',
45588
+ ' the other tool\'s arguments as JSON text, for example `{"path": "src/app.ts"}`.',
45589
+ `- Read a description's limits ("Default: \u2026", "Minimum \u2026", "One of: \u2026") as part of the schema.`,
45590
+ "- When you say you will do something, do it in the same response with a function call.",
45591
+ " The task is finished only when you call attempt_completion; a reply with no call ends your",
45592
+ " turn and the user has to prompt you again.",
45593
+ "- For apply_diff, copy the SEARCH text exactly from the latest read_file output, without the",
45594
+ " line numbers read_file shows. Whitespace and quotes must match.",
45595
+ "- Find files with list_files or search_files before naming them. Do not invent paths."
45596
+ ].join("\n");
45597
+ }
45598
+
45232
45599
  // ../../packages/core/dist/agents/roles.js
45233
45600
  var AGENT_ROLES = ["expert", "programmer", "reviewer", "tester", "librarian"];
45234
45601
  var CUSTOM_ROLE_LIMIT = 5;
@@ -45698,6 +46065,9 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
45698
46065
  "- Before asking, check what is here: the imports and existing calls in this workspace are",
45699
46066
  " evidence about the version actually installed, and a skill may already describe it."
45700
46067
  );
46068
+ const familyNotes = modelGuidance(options.model, options.providerBaseUrl);
46069
+ if (familyNotes !== void 0)
46070
+ lines2.push("", familyNotes);
45701
46071
  if (options.skills !== void 0 && options.skills.length > 0) {
45702
46072
  lines2.push("", options.skills);
45703
46073
  }
@@ -48183,10 +48553,12 @@ var RestTransport = class {
48183
48553
  http;
48184
48554
  connection;
48185
48555
  extraHeaders;
48186
- constructor(http, connection, extraHeaders = () => ({})) {
48556
+ explain;
48557
+ constructor(http, connection, extraHeaders = () => ({}), explain = () => "") {
48187
48558
  this.http = http;
48188
48559
  this.connection = connection;
48189
48560
  this.extraHeaders = extraHeaders;
48561
+ this.explain = explain;
48190
48562
  }
48191
48563
  get label() {
48192
48564
  return this.connection.label ?? this.connection.url;
@@ -48238,7 +48610,7 @@ var RestTransport = class {
48238
48610
  const result = await this.send(path65, method, body, signal);
48239
48611
  if (result.status < 200 || result.status >= 300) {
48240
48612
  const detail = typeof result.body === "string" ? result.body : JSON.stringify(result.body ?? "");
48241
- throw new VectorStoreError(`${method} ${path65} on ${this.label} returned HTTP ${String(result.status)}. ${detail.slice(0, 300)}`, result.status);
48613
+ throw new VectorStoreError(`${method} ${path65} on ${this.label} returned HTTP ${String(result.status)}. ${detail.slice(0, 300)}` + this.explain(result.body), result.status);
48242
48614
  }
48243
48615
  return result.body;
48244
48616
  }
@@ -48247,6 +48619,84 @@ function isSafeCollectionName(name) {
48247
48619
  return /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,254}$/.test(name) && !name.includes("..");
48248
48620
  }
48249
48621
 
48622
+ // ../../packages/core/dist/rag/serverKind.js
48623
+ function identifyServer(body) {
48624
+ if (typeof body === "string") {
48625
+ return /no handler found for uri/i.test(body) ? "opensearch" : void 0;
48626
+ }
48627
+ if (body === null || typeof body !== "object")
48628
+ return void 0;
48629
+ const record2 = body;
48630
+ const version2 = record2.version;
48631
+ if (typeof record2.cluster_name === "string" && typeof version2 === "object" && typeof version2?.number === "string") {
48632
+ return "opensearch";
48633
+ }
48634
+ if (typeof record2.title === "string" && /qdrant/i.test(record2.title))
48635
+ return "qdrant";
48636
+ if ("nanosecond heartbeat" in record2)
48637
+ return "chroma";
48638
+ const error51 = record2.error;
48639
+ if (typeof error51 === "string")
48640
+ return identifyServer(error51);
48641
+ if (error51 !== null && typeof error51 === "object" && Array.isArray(error51.root_cause)) {
48642
+ return "opensearch";
48643
+ }
48644
+ return void 0;
48645
+ }
48646
+ var NAMES = { opensearch: "OpenSearch", qdrant: "Qdrant", chroma: "Chroma" };
48647
+ function wrongServerMessage(expected, body, label) {
48648
+ const actual = identifyServer(body);
48649
+ if (actual === void 0 || actual === expected)
48650
+ return void 0;
48651
+ return `${label} answers like ${NAMES[actual]}, but this connection's type is ${NAMES[expected]}. In Settings \u2192 Search, edit the connection and set Type to ${NAMES[actual]}` + (actual === "opensearch" ? "" : `, or enter your ${NAMES[expected]} server's address`) + ".";
48652
+ }
48653
+ function wrongServerHint(expected, body, label) {
48654
+ const message5 = wrongServerMessage(expected, body, label);
48655
+ return message5 === void 0 ? "" : ` ${message5}`;
48656
+ }
48657
+ async function probeVectorStore(http, kind, connection, signal) {
48658
+ const rest = new RestTransport(http, connection, () => qdrantKeyHeader(kind, connection));
48659
+ const label = rest.label;
48660
+ const root = await rest.send("/", "GET", void 0, signal);
48661
+ const mismatch = wrongServerMessage(kind, root.body, label);
48662
+ if (mismatch !== void 0)
48663
+ throw new VectorStoreError(mismatch, root.status);
48664
+ if (kind === "opensearch") {
48665
+ const info = await new OpenSearchClient(http, connection).ping(signal);
48666
+ return `Connected to ${info.clusterName ?? "the cluster"}${info.version !== void 0 ? ` (OpenSearch ${info.version})` : ""}.`;
48667
+ }
48668
+ if (kind === "qdrant") {
48669
+ const listed = await rest.send("/collections", "GET", void 0, signal);
48670
+ if (listed.status === 401 || listed.status === 403) {
48671
+ throw new VectorStoreError(`${label} refused the credentials (HTTP ${String(listed.status)}). Qdrant takes its API key in the Password box, with Username left empty.`, listed.status);
48672
+ }
48673
+ if (listed.status < 200 || listed.status >= 300 || !Array.isArray(listed.body?.result?.collections)) {
48674
+ throw new VectorStoreError(`${label} did not answer as Qdrant (GET /collections returned HTTP ${String(listed.status)}).` + wrongServerHint("qdrant", listed.body, label), listed.status);
48675
+ }
48676
+ const version3 = root.body?.version;
48677
+ const count3 = listed.body.result.collections.length;
48678
+ return `Connected to Qdrant${typeof version3 === "string" ? ` ${version3}` : ""} - ${String(count3)} collection${count3 === 1 ? "" : "s"}.`;
48679
+ }
48680
+ const beat = await rest.send("/api/v2/heartbeat", "GET", void 0, signal);
48681
+ if (beat.status === 404 || beat.status === 410) {
48682
+ throw new VectorStoreError(`${label} does not speak the Chroma v2 API. Light Code needs Chroma 1.0 or newer.` + wrongServerHint("chroma", beat.body, label), beat.status);
48683
+ }
48684
+ if (beat.status < 200 || beat.status >= 300 || identifyServer(beat.body) !== "chroma") {
48685
+ throw new VectorStoreError(`${label} did not answer as Chroma (GET /api/v2/heartbeat returned HTTP ${String(beat.status)}).` + wrongServerHint("chroma", beat.body, label), beat.status);
48686
+ }
48687
+ const version2 = await rest.send("/api/v2/version", "GET", void 0, signal);
48688
+ return `Connected to Chroma${typeof version2.body === "string" && version2.status === 200 ? ` ${version2.body}` : ""}.`;
48689
+ }
48690
+ function qdrantKeyHeader(kind, connection) {
48691
+ if (kind !== "qdrant")
48692
+ return {};
48693
+ const { username, password } = connection;
48694
+ if ((username === void 0 || username.length === 0) && password !== void 0 && password.length > 0) {
48695
+ return { "api-key": password };
48696
+ }
48697
+ return {};
48698
+ }
48699
+
48250
48700
  // ../../packages/core/dist/rag/chroma/chroma.js
48251
48701
  var DEFAULT_TENANT = "default_tenant";
48252
48702
  var DEFAULT_DATABASE = "default_database";
@@ -48260,7 +48710,7 @@ var ChromaBase = class {
48260
48710
  constructor(http, connection, tenant = DEFAULT_TENANT, database = DEFAULT_DATABASE) {
48261
48711
  this.tenant = tenant;
48262
48712
  this.database = database;
48263
- this.rest = new RestTransport(http, connection);
48713
+ this.rest = new RestTransport(http, connection, () => ({}), (body) => wrongServerHint("chroma", body, connection.label ?? connection.url));
48264
48714
  }
48265
48715
  get base() {
48266
48716
  return `/api/v2/tenants/${encodeURIComponent(this.tenant)}/databases/${encodeURIComponent(this.database)}`;
@@ -48279,7 +48729,7 @@ var ChromaBase = class {
48279
48729
  throw new VectorStoreError(`${this.rest.label} does not speak the Chroma v2 API. Light Code needs Chroma 1.0 or newer \u2014 the v1 endpoints were removed upstream and are not implemented here.`, result.status);
48280
48730
  }
48281
48731
  if (result.status < 200 || result.status >= 300) {
48282
- throw new VectorStoreError(`Could not read collection "${collection}" from ${this.rest.label} (HTTP ${String(result.status)}).`, result.status);
48732
+ throw new VectorStoreError(`Could not read collection "${collection}" from ${this.rest.label} (HTTP ${String(result.status)}).` + wrongServerHint("chroma", result.body, this.rest.label), result.status);
48283
48733
  }
48284
48734
  const body = result.body;
48285
48735
  return typeof body.id === "string" ? body : void 0;
@@ -48548,7 +48998,7 @@ function toMatch(point) {
48548
48998
  var QdrantBase = class {
48549
48999
  rest;
48550
49000
  constructor(http, connection) {
48551
- this.rest = new RestTransport(http, connection, () => apiKeyHeader(connection));
49001
+ this.rest = new RestTransport(http, connection, () => apiKeyHeader(connection), (body) => wrongServerHint("qdrant", body, connection.label ?? connection.url));
48552
49002
  }
48553
49003
  assertName(collection) {
48554
49004
  if (!isSafeCollectionName(collection)) {
@@ -48627,7 +49077,7 @@ var QdrantIndexWriter = class extends QdrantBase {
48627
49077
  if (result.status === 404)
48628
49078
  return void 0;
48629
49079
  if (result.status < 200 || result.status >= 300) {
48630
- throw new VectorStoreError(`Could not read collection "${collection}" (HTTP ${String(result.status)}).`, result.status);
49080
+ throw new VectorStoreError(`Could not read collection "${collection}" (HTTP ${String(result.status)}).` + wrongServerHint("qdrant", result.body, this.rest.label), result.status);
48631
49081
  }
48632
49082
  const vectors = result.body.result?.config?.params?.vectors;
48633
49083
  if (vectors === void 0)
@@ -48722,7 +49172,7 @@ var QdrantIndexWriter = class extends QdrantBase {
48722
49172
  if (result.status === 404)
48723
49173
  return { documents: [] };
48724
49174
  if (result.status < 200 || result.status >= 300) {
48725
- throw new VectorStoreError(`Could not read "${collection}" (HTTP ${String(result.status)}).`, result.status);
49175
+ throw new VectorStoreError(`Could not read "${collection}" (HTTP ${String(result.status)}).` + wrongServerHint("qdrant", result.body, this.rest.label), result.status);
48726
49176
  }
48727
49177
  const documents = [];
48728
49178
  for (const point of result.body.result?.points ?? []) {
@@ -48757,7 +49207,7 @@ var QdrantIndexWriter = class extends QdrantBase {
48757
49207
  if (result.status === 404)
48758
49208
  return [];
48759
49209
  if (result.status < 200 || result.status >= 300) {
48760
- throw new VectorStoreError(`Could not list "${collection}" (HTTP ${String(result.status)}).`, result.status);
49210
+ throw new VectorStoreError(`Could not list "${collection}" (HTTP ${String(result.status)}).` + wrongServerHint("qdrant", result.body, this.rest.label), result.status);
48761
49211
  }
48762
49212
  for (const point of result.body.result?.points ?? []) {
48763
49213
  const path65 = point.payload?.path;
@@ -51756,10 +52206,10 @@ function renderVariable(variable) {
51756
52206
  const typed = variable.type !== void 0 ? `: ${variable.type}` : "";
51757
52207
  return ` ${variable.name}${typed} = ${variable.value}`;
51758
52208
  }
51759
- function renderFrame(frame) {
51760
- const where = frame.file !== void 0 ? `${frame.file}${frame.line !== void 0 ? `:${String(frame.line)}` : ""}` : void 0;
51761
- const lines2 = [` - ${frame.name}${where !== void 0 ? ` (${where})` : ""}`];
51762
- for (const scope of frame.scopes) {
52209
+ function renderFrame(frame2) {
52210
+ const where = frame2.file !== void 0 ? `${frame2.file}${frame2.line !== void 0 ? `:${String(frame2.line)}` : ""}` : void 0;
52211
+ const lines2 = [` - ${frame2.name}${where !== void 0 ? ` (${where})` : ""}`];
52212
+ for (const scope of frame2.scopes) {
51763
52213
  if (scope.variables.length === 0)
51764
52214
  continue;
51765
52215
  lines2.push(` ${scope.name}:`);
@@ -52519,7 +52969,7 @@ var FileReplaceError = class extends Error {
52519
52969
  };
52520
52970
  async function replaceFile(from, to, options = {}) {
52521
52971
  const rename = options.rename ?? ((a, b) => import_promises5.default.rename(a, b));
52522
- const sleep2 = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
52972
+ const sleep3 = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
52523
52973
  for (let attempt = 0; ; attempt++) {
52524
52974
  try {
52525
52975
  await rename(from, to);
@@ -52528,7 +52978,7 @@ async function replaceFile(from, to, options = {}) {
52528
52978
  const code = error51.code;
52529
52979
  const delay = DELAYS_MS[attempt];
52530
52980
  if (code !== void 0 && TRANSIENT.has(code) && delay !== void 0) {
52531
- await sleep2(delay);
52981
+ await sleep3(delay);
52532
52982
  continue;
52533
52983
  }
52534
52984
  await import_promises5.default.rm(from, { force: true }).catch(() => void 0);
@@ -60222,31 +60672,31 @@ ${this.stderrTail.trim().split("\n").slice(-15).join("\n")}` : ""}`);
60222
60672
  return child;
60223
60673
  }
60224
60674
  onLine(line) {
60225
- let frame;
60675
+ let frame2;
60226
60676
  try {
60227
- frame = JSON.parse(line);
60677
+ frame2 = JSON.parse(line);
60228
60678
  } catch {
60229
60679
  this.options.logger.debug("python worker output", line);
60230
60680
  return;
60231
60681
  }
60232
- if (typeof frame.callback === "string") {
60233
- if (frame.method === "credential")
60234
- void this.serveCredential(frame.callback, frame.name, frame.caller);
60682
+ if (typeof frame2.callback === "string") {
60683
+ if (frame2.method === "credential")
60684
+ void this.serveCredential(frame2.callback, frame2.name, frame2.caller);
60235
60685
  else
60236
- void this.serveCallback(frame.callback, frame.name, frame.arguments, frame.caller);
60686
+ void this.serveCallback(frame2.callback, frame2.name, frame2.arguments, frame2.caller);
60237
60687
  return;
60238
60688
  }
60239
- if (typeof frame.id !== "number")
60689
+ if (typeof frame2.id !== "number")
60240
60690
  return;
60241
- const entry = this.pending.get(frame.id);
60691
+ const entry = this.pending.get(frame2.id);
60242
60692
  if (entry === void 0)
60243
60693
  return;
60244
- this.pending.delete(frame.id);
60694
+ this.pending.delete(frame2.id);
60245
60695
  clearTimeout(entry.timer);
60246
- if (frame.ok === true)
60247
- entry.resolve(frame.value);
60696
+ if (frame2.ok === true)
60697
+ entry.resolve(frame2.value);
60248
60698
  else {
60249
- entry.reject(new PythonWorkerError(typeof frame.error === "string" ? frame.error : "The Python tool failed.", typeof frame.traceback === "string" ? frame.traceback : void 0));
60699
+ entry.reject(new PythonWorkerError(typeof frame2.error === "string" ? frame2.error : "The Python tool failed.", typeof frame2.traceback === "string" ? frame2.traceback : void 0));
60250
60700
  }
60251
60701
  }
60252
60702
  /**
@@ -63642,6 +64092,8 @@ async function consumeStream(provider, messages, streamOptions, stallSeconds, ev
63642
64092
  } else if (chunk.type === "toolCall") {
63643
64093
  if (outcome.toolCall === void 0)
63644
64094
  outcome.toolCall = chunk.toolCall;
64095
+ else
64096
+ (outcome.extraCalls ??= []).push(chunk.toolCall.name);
63645
64097
  } else if (chunk.type === "usage") {
63646
64098
  outcome.usage = { inputTokens: chunk.inputTokens, ...chunk.outputTokens !== void 0 ? { outputTokens: chunk.outputTokens } : {}, ...chunk.cachedTokens !== void 0 ? { cachedTokens: chunk.cachedTokens } : {} };
63647
64099
  } else if (chunk.type === "error") {
@@ -63973,9 +64425,13 @@ The conversation is longer than this model accepts, and it could not be shortene
63973
64425
  }
63974
64426
  const pictures = result.images ?? [];
63975
64427
  const capped = options.truncationStore !== void 0 ? (await truncateToolResult(result.content, options.truncationStore, void 0, { dataframe: toolRegistry.get("dataframe") !== void 0 })).content : result.content;
63976
- const forModel = pictures.length > 0 && options.supportsVision !== true ? `${capped}
64428
+ const shown2 = pictures.length > 0 && options.supportsVision !== true ? `${capped}
63977
64429
 
63978
64430
  (${String(pictures.length)} image(s) were fetched but not shown: the current model does not accept images.)` : capped;
64431
+ const extras = outcome.extraCalls ?? [];
64432
+ const forModel = extras.length > 0 ? `${shown2}
64433
+
64434
+ (Only ${toolCall.name} ran. ${extras.join(", ")} ${extras.length === 1 ? "was" : "were"} not run: make one tool call per message, then the next after its result.)` : shown2;
63979
64435
  conversation.addToolResultMessage(toolCall.id, forModel);
63980
64436
  if (pictures.length > 0 && options.supportsVision === true) {
63981
64437
  conversation.addUserMessage(`[Images returned by ${toolCall.name}, not typed by the user: ${pictures.map((picture) => picture.label).join(", ")}]`, pictures.map((picture) => ({ mediaType: picture.mediaType, data: picture.data })));
@@ -64224,16 +64680,35 @@ var JupyterClient = class {
64224
64680
  }
64225
64681
  return { Authorization: `token ${token}`, "Content-Type": "application/json" };
64226
64682
  }
64227
- async call(method, apiPath, body, signal) {
64683
+ /**
64684
+ * One call to the user's server.
64685
+ *
64686
+ * **Bounded** (`deadlineMs`, two minutes unless the call says otherwise): a connection that went quiet
64687
+ * - a VPN reconnect, a proxy dropping an idle socket - is never told so, and without a limit the call,
64688
+ * and the agent waiting on it, hung until somebody restarted the agent (reported from real use).
64689
+ * **A stopped server is started** once and the call made again: hubs cull idle servers, and "start it
64690
+ * at the hub's page and try again" was a restart the user had to notice and do by hand.
64691
+ */
64692
+ async call(method, apiPath, body, signal, options = {}) {
64228
64693
  const tls2 = await this.tls();
64229
64694
  const headers = await this.headers();
64230
- const send2 = () => this.http.request(`${this.base}${apiPath}`, {
64231
- method,
64232
- headers,
64233
- ...body !== void 0 ? { body: JSON.stringify(body) } : {},
64234
- ...signal !== void 0 ? { signal } : {},
64235
- ...tls2 !== void 0 ? { tls: tls2 } : {}
64236
- });
64695
+ const deadlineMs = options.deadlineMs ?? CALL_DEADLINE_MS;
64696
+ const send2 = async () => {
64697
+ const bounded = withDeadline2(signal, deadlineMs);
64698
+ try {
64699
+ return await this.http.request(`${this.base}${apiPath}`, {
64700
+ method,
64701
+ headers,
64702
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {},
64703
+ signal: bounded.signal,
64704
+ ...tls2 !== void 0 ? { tls: tls2 } : {}
64705
+ });
64706
+ } catch (error51) {
64707
+ throw bounded.timedOut() ? new JupyterError(`JupyterHub at ${this.spec.url} did not answer within ${String(Math.round(deadlineMs / 1e3))} seconds.`) : error51;
64708
+ } finally {
64709
+ bounded.clear();
64710
+ }
64711
+ };
64237
64712
  let response;
64238
64713
  try {
64239
64714
  response = await send2();
@@ -64252,10 +64727,60 @@ var JupyterClient = class {
64252
64727
  }
64253
64728
  const type = response.headers["content-type"] ?? "";
64254
64729
  if (response.status === 424 || response.status === 503 || response.status < 300 && type.includes("text/html")) {
64255
- throw new JupyterError(`${this.spec.user}'s JupyterHub server is not running. Start it at ${this.hubHome()} and try again.`, response.status);
64730
+ if (options.afterStart !== true && await this.startServer())
64731
+ return this.call(method, apiPath, body, signal, { ...options, afterStart: true });
64732
+ throw new JupyterError(`${this.spec.user}'s JupyterHub server is not running, and starting it did not work. Start it at ${this.hubHome()} and try again.`, response.status);
64256
64733
  }
64257
64734
  return response;
64258
64735
  }
64736
+ starting;
64737
+ /**
64738
+ * Asks the hub to start the user's server and waits until it is ready (up to three minutes). True when it
64739
+ * is. Shared by every call that found it stopped, so one start is asked for, not one per call. False -
64740
+ * never thrown - when the token may not start servers or the hub refuses: the caller then says so.
64741
+ */
64742
+ startServer() {
64743
+ this.starting ??= this.startServerNow().finally(() => {
64744
+ this.starting = void 0;
64745
+ });
64746
+ return this.starting;
64747
+ }
64748
+ async startServerNow() {
64749
+ const hub = `${this.spec.url.replace(/\/+$/, "")}/hub/api/users/${encodeURIComponent(this.spec.user)}`;
64750
+ const tls2 = await this.tls();
64751
+ const headers = await this.headers();
64752
+ const ask = async (method, url2) => {
64753
+ const bounded = withDeadline2(void 0, 3e4);
64754
+ try {
64755
+ return await this.http.request(url2, { method, headers, signal: bounded.signal, ...tls2 !== void 0 ? { tls: tls2 } : {} });
64756
+ } catch {
64757
+ return void 0;
64758
+ } finally {
64759
+ bounded.clear();
64760
+ }
64761
+ };
64762
+ const named2 = this.spec.server;
64763
+ const started = await ask("POST", named2 !== void 0 ? `${hub}/servers/${encodeURIComponent(named2)}` : `${hub}/server`);
64764
+ if (started === void 0 || ![201, 202, 400].includes(started.status))
64765
+ return false;
64766
+ const until = Date.now() + 18e4;
64767
+ while (Date.now() < until) {
64768
+ const user = await ask("GET", hub);
64769
+ if (user !== void 0 && user.status < 300) {
64770
+ try {
64771
+ const model = await user.json();
64772
+ const entry = model.servers?.[named2 ?? ""];
64773
+ if (entry?.ready === true)
64774
+ return true;
64775
+ if (model.servers === void 0 && named2 === void 0 && typeof model.server === "string" && (model.pending === null || model.pending === void 0))
64776
+ return true;
64777
+ } catch {
64778
+ }
64779
+ }
64780
+ await new Promise((resolve) => setTimeout(resolve, 3e3));
64781
+ }
64782
+ return false;
64783
+ }
64259
64784
  unreachable(error51) {
64260
64785
  if (error51 instanceof JupyterError)
64261
64786
  return error51;
@@ -64347,27 +64872,43 @@ var JupyterClient = class {
64347
64872
  };
64348
64873
  }
64349
64874
  async startKernel(name) {
64350
- const response = await this.call("POST", "api/kernels", { path: "", ...name !== void 0 ? { name } : {} });
64875
+ const response = await this.call("POST", "api/kernels", { path: "", ...name !== void 0 ? { name } : {} }, void 0, { deadlineMs: 9e4 });
64351
64876
  if (response.status >= 300)
64352
64877
  throw await this.failure(response, `Starting a${name !== void 0 ? ` ${name}` : ""} kernel`);
64353
64878
  const body = await response.json();
64354
64879
  return { id: body.id, name: body.name };
64355
64880
  }
64356
64881
  async kernelAlive(id) {
64357
- const response = await this.call("GET", `api/kernels/${encodeURIComponent(id)}`);
64358
- return response.status < 300;
64882
+ return await this.kernelState(id) !== void 0;
64883
+ }
64884
+ /** The kernel's `execution_state` (idle, busy, starting...), or undefined when it no longer exists. */
64885
+ async kernelState(id) {
64886
+ const response = await this.call("GET", `api/kernels/${encodeURIComponent(id)}`, void 0, void 0, { deadlineMs: 2e4 });
64887
+ if (response.status >= 300)
64888
+ return void 0;
64889
+ try {
64890
+ const model = await response.json();
64891
+ return typeof model.execution_state === "string" ? model.execution_state : "unknown";
64892
+ } catch {
64893
+ return "unknown";
64894
+ }
64359
64895
  }
64360
64896
  async interruptKernel(id) {
64361
- await this.call("POST", `api/kernels/${encodeURIComponent(id)}/interrupt`);
64897
+ await this.call("POST", `api/kernels/${encodeURIComponent(id)}/interrupt`, void 0, void 0, { deadlineMs: 2e4 });
64362
64898
  }
64363
64899
  async shutdownKernel(id) {
64364
- await this.call("DELETE", `api/kernels/${encodeURIComponent(id)}`);
64900
+ await this.call("DELETE", `api/kernels/${encodeURIComponent(id)}`, void 0, void 0, { deadlineMs: 2e4 });
64365
64901
  }
64366
- /** The kernel's message channel, authenticated by header like every other call. */
64367
- async openChannels(id) {
64902
+ /**
64903
+ * The kernel's message channel, authenticated by header like every other call. With `session`, the server
64904
+ * keeps what the kernel sends while the channel is down and replays it when the same session reconnects
64905
+ * - which is what lets a run cut off mid-way finish (`kernel.ts`).
64906
+ */
64907
+ async openChannels(id, session) {
64368
64908
  if (this.http.openWebSocket === void 0)
64369
64909
  throw new JupyterError("This host cannot open the WebSocket a kernel needs.");
64370
- const url2 = `${this.base.replace(/^http/i, "ws")}api/kernels/${encodeURIComponent(id)}/channels`;
64910
+ const query = session !== void 0 ? `?session_id=${encodeURIComponent(session)}` : "";
64911
+ const url2 = `${this.base.replace(/^http/i, "ws")}api/kernels/${encodeURIComponent(id)}/channels${query}`;
64371
64912
  const tls2 = await this.tls();
64372
64913
  const headers = await this.headers();
64373
64914
  delete headers["Content-Type"];
@@ -64390,35 +64931,80 @@ function encodePath(remote) {
64390
64931
  throw new JupyterError(`"${remote}" is not a path inside the server.`);
64391
64932
  return parts.map(encodeURIComponent).join("/");
64392
64933
  }
64934
+ var CALL_DEADLINE_MS = 12e4;
64935
+ function withDeadline2(signal, ms) {
64936
+ const controller = new AbortController();
64937
+ let expired = false;
64938
+ const timer = setTimeout(() => {
64939
+ expired = true;
64940
+ controller.abort();
64941
+ }, ms);
64942
+ const onAbort = () => controller.abort();
64943
+ if (signal?.aborted === true)
64944
+ controller.abort();
64945
+ else
64946
+ signal?.addEventListener("abort", onAbort, { once: true });
64947
+ return {
64948
+ signal: controller.signal,
64949
+ timedOut: () => expired,
64950
+ clear: () => {
64951
+ clearTimeout(timer);
64952
+ signal?.removeEventListener("abort", onAbort);
64953
+ }
64954
+ };
64955
+ }
64393
64956
 
64394
64957
  // ../../packages/core/dist/jupyter/kernel.js
64395
64958
  var import_node_crypto9 = require("node:crypto");
64396
64959
  var OUTPUT_CAP = 4e5;
64960
+ var RECONNECT_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 15e3, 3e4];
64961
+ var HEARTBEAT_EVERY_MS = 3e4;
64962
+ var HEARTBEAT_WAIT_MS = 2e4;
64397
64963
  var KernelSession = class {
64398
64964
  client;
64399
64965
  kernelName;
64966
+ timing;
64400
64967
  kernel;
64401
64968
  channels;
64402
64969
  session = (0, import_node_crypto9.randomUUID)();
64403
64970
  listeners = /* @__PURE__ */ new Map();
64971
+ /** Told when the channel drops, so a run in progress can wait for the reconnection. */
64972
+ dropListeners = /* @__PURE__ */ new Set();
64973
+ recovering;
64404
64974
  /** One run at a time: a kernel executes serially anyway, and interleaved output would be unreadable. */
64405
64975
  queue = Promise.resolve();
64406
- constructor(client, kernelName) {
64976
+ /** Waits between attempts, replaceable so tests need not sleep for a minute. */
64977
+ constructor(client, kernelName, timing = {}) {
64407
64978
  this.client = client;
64408
64979
  this.kernelName = kernelName;
64980
+ this.timing = timing;
64409
64981
  }
64410
64982
  run(code, options) {
64411
64983
  const next = this.queue.then(() => this.runNow(code, options));
64412
64984
  this.queue = next.catch(() => void 0);
64413
64985
  return next;
64414
64986
  }
64987
+ /** A connected channel to a live kernel; true when the kernel is new (earlier state gone). */
64415
64988
  async ensure() {
64416
- if (this.kernel !== void 0 && this.channels !== void 0 && await this.client.kernelAlive(this.kernel.id))
64417
- return false;
64989
+ if (this.kernel !== void 0) {
64990
+ if (this.channels !== void 0 && await this.client.kernelAlive(this.kernel.id))
64991
+ return false;
64992
+ if (this.channels === void 0) {
64993
+ const recovered = await this.recover();
64994
+ if (recovered === "reconnected")
64995
+ return false;
64996
+ if (recovered === "unreachable")
64997
+ throw new JupyterError("Could not reconnect to the kernel on the hub; it may be busy or the hub unreachable. Try again shortly.");
64998
+ }
64999
+ }
64418
65000
  this.channels?.close();
64419
65001
  this.channels = void 0;
64420
65002
  this.kernel = await this.client.startKernel(this.kernelName);
64421
- const channels = await this.client.openChannels(this.kernel.id);
65003
+ await this.connect(this.kernel.id);
65004
+ return true;
65005
+ }
65006
+ async connect(kernelId) {
65007
+ const channels = await this.client.openChannels(kernelId, this.session);
64422
65008
  try {
64423
65009
  await channels.opened;
64424
65010
  } catch (error51) {
@@ -64435,18 +65021,59 @@ var KernelSession = class {
64435
65021
  if (parent !== void 0)
64436
65022
  this.listeners.get(parent)?.(message5);
64437
65023
  });
64438
- channels.onClose(() => {
64439
- if (this.channels === channels)
64440
- this.channels = void 0;
65024
+ channels.onClose((reason) => {
65025
+ if (this.channels !== channels)
65026
+ return;
65027
+ this.channels = void 0;
65028
+ for (const listener of [...this.dropListeners])
65029
+ listener(reason);
64441
65030
  });
64442
65031
  this.channels = channels;
64443
- return true;
65032
+ }
65033
+ /**
65034
+ * Reconnects to the kernel this session has, trying for about a minute. Shared by everything that
65035
+ * noticed the drop, so one reconnection is made.
65036
+ */
65037
+ recover() {
65038
+ this.recovering ??= this.recoverNow().finally(() => {
65039
+ this.recovering = void 0;
65040
+ });
65041
+ return this.recovering;
65042
+ }
65043
+ async recoverNow() {
65044
+ const kernel = this.kernel;
65045
+ if (kernel === void 0)
65046
+ return "kernel-gone";
65047
+ for (const delay of this.timing.reconnectDelaysMs ?? RECONNECT_DELAYS_MS) {
65048
+ if (this.kernel?.id !== kernel.id)
65049
+ return "kernel-gone";
65050
+ if (this.channels !== void 0)
65051
+ return "reconnected";
65052
+ let alive;
65053
+ try {
65054
+ alive = await this.client.kernelAlive(kernel.id);
65055
+ } catch {
65056
+ await sleep(delay);
65057
+ continue;
65058
+ }
65059
+ if (!alive) {
65060
+ this.kernel = void 0;
65061
+ return "kernel-gone";
65062
+ }
65063
+ try {
65064
+ await this.connect(kernel.id);
65065
+ return "reconnected";
65066
+ } catch {
65067
+ await sleep(delay);
65068
+ }
65069
+ }
65070
+ return "unreachable";
64444
65071
  }
64445
65072
  async runNow(code, options) {
64446
65073
  const freshKernel = await this.ensure();
64447
65074
  const kernel = this.kernel;
64448
- const channels = this.channels;
64449
- if (kernel === void 0 || channels === void 0)
65075
+ const first = this.channels;
65076
+ if (kernel === void 0 || first === void 0)
64450
65077
  throw new JupyterError("The kernel is not connected.");
64451
65078
  const msgId = (0, import_node_crypto9.randomUUID)();
64452
65079
  let text2 = "";
@@ -64457,19 +65084,26 @@ var KernelSession = class {
64457
65084
  let error51;
64458
65085
  let gotReply = false;
64459
65086
  let idle = false;
65087
+ let reconnected = false;
65088
+ let lastHeard = Date.now();
64460
65089
  return new Promise((resolve) => {
64461
65090
  let settled = false;
64462
65091
  let interrupted;
64463
65092
  let stuck;
65093
+ let idleCheck;
64464
65094
  const finish = (extra = {}) => {
64465
65095
  if (settled)
64466
65096
  return;
64467
65097
  settled = true;
64468
65098
  clearTimeout(timer);
65099
+ clearInterval(heartbeat);
65100
+ if (idleCheck !== void 0)
65101
+ clearInterval(idleCheck);
64469
65102
  if (stuck !== void 0)
64470
65103
  clearTimeout(stuck);
64471
65104
  options.signal?.removeEventListener("abort", onAbort);
64472
65105
  this.listeners.delete(msgId);
65106
+ this.dropListeners.delete(onDrop);
64473
65107
  if (text2.length >= OUTPUT_CAP)
64474
65108
  text2 += "\n\u2026 [output cut here]";
64475
65109
  resolve({
@@ -64478,6 +65112,7 @@ var KernelSession = class {
64478
65112
  freshKernel,
64479
65113
  kernelName: kernel.name,
64480
65114
  ...interrupted !== void 0 ? { [interrupted]: true } : {},
65115
+ ...reconnected ? { reconnected: true } : {},
64481
65116
  ...extra
64482
65117
  });
64483
65118
  };
@@ -64500,7 +65135,68 @@ var KernelSession = class {
64500
65135
  const timer = setTimeout(() => interrupt("timedOut"), options.timeoutMs);
64501
65136
  const onAbort = () => interrupt("stopped");
64502
65137
  options.signal?.addEventListener("abort", onAbort, { once: true });
65138
+ const onDrop = (reason) => {
65139
+ if (settled)
65140
+ return;
65141
+ void this.recover().then((outcome) => {
65142
+ if (settled)
65143
+ return;
65144
+ if (outcome === "reconnected") {
65145
+ reconnected = true;
65146
+ lastHeard = Date.now();
65147
+ watchForLostAnswer();
65148
+ return;
65149
+ }
65150
+ error51 ??= outcome === "kernel-gone" ? { name: "KernelLost", value: `The kernel on the hub stopped while this ran (the connection closed: ${reason}). Its state is gone; the next run starts a new kernel.`, traceback: "" } : { name: "ConnectionLost", value: `The connection to the hub dropped (${reason}) and could not be restored for about a minute. The kernel may still be running it; try again shortly - its state is kept if it is.`, traceback: "" };
65151
+ finish();
65152
+ });
65153
+ };
65154
+ this.dropListeners.add(onDrop);
65155
+ const watchForLostAnswer = () => {
65156
+ if (idleCheck !== void 0)
65157
+ return;
65158
+ let idleSeen = 0;
65159
+ idleCheck = setInterval(() => {
65160
+ if (settled || gotReply)
65161
+ return;
65162
+ void this.client.kernelState(kernel.id).then((state) => {
65163
+ if (settled || gotReply)
65164
+ return;
65165
+ idleSeen = state === "idle" ? idleSeen + 1 : 0;
65166
+ if (idleSeen >= 2) {
65167
+ error51 ??= {
65168
+ name: "OutputLost",
65169
+ value: "The connection dropped during this run and was restored, but the hub kept none of its output. The run has finished on the hub; check its effects, or run it again.",
65170
+ traceback: ""
65171
+ };
65172
+ finish();
65173
+ }
65174
+ }).catch(() => void 0);
65175
+ }, this.timing.idleCheckMs ?? 5e3);
65176
+ };
65177
+ const heartbeat = setInterval(() => {
65178
+ if (settled)
65179
+ return;
65180
+ const channels = this.channels;
65181
+ if (channels === void 0)
65182
+ return;
65183
+ if (Date.now() - lastHeard > (this.timing.heartbeatEveryMs ?? HEARTBEAT_EVERY_MS) + (this.timing.heartbeatWaitMs ?? HEARTBEAT_WAIT_MS)) {
65184
+ channels.close();
65185
+ return;
65186
+ }
65187
+ const beat = (0, import_node_crypto9.randomUUID)();
65188
+ this.listeners.set(beat, () => {
65189
+ lastHeard = Date.now();
65190
+ this.listeners.delete(beat);
65191
+ });
65192
+ setTimeout(() => this.listeners.delete(beat), (this.timing.heartbeatWaitMs ?? HEARTBEAT_WAIT_MS) * 2);
65193
+ try {
65194
+ channels.send(frame(beat, this.session, "kernel_info_request", {}, "control"));
65195
+ } catch {
65196
+ }
65197
+ }, this.timing.heartbeatEveryMs ?? HEARTBEAT_EVERY_MS);
64503
65198
  this.listeners.set(msgId, (message5) => {
65199
+ lastHeard = Date.now();
64504
65200
  const content = message5.content ?? {};
64505
65201
  switch (message5.msg_type ?? message5.header?.msg_type) {
64506
65202
  case "stream":
@@ -64538,33 +65234,49 @@ var KernelSession = class {
64538
65234
  if (gotReply && idle)
64539
65235
  finish();
64540
65236
  });
64541
- channels.onClose((reason) => {
64542
- if (!settled) {
64543
- this.kernel = void 0;
64544
- error51 ??= { name: "KernelLost", value: `The connection to the kernel closed (${reason}).`, traceback: "" };
65237
+ try {
65238
+ first.send(frame(msgId, this.session, "execute_request", { code, silent: false, store_history: false, user_expressions: {}, allow_stdin: false, stop_on_error: false }, "shell"));
65239
+ } catch {
65240
+ void this.recover().then((outcome) => {
65241
+ if (settled)
65242
+ return;
65243
+ if (outcome === "reconnected" && this.channels !== void 0) {
65244
+ try {
65245
+ this.channels.send(frame(msgId, this.session, "execute_request", { code, silent: false, store_history: false, user_expressions: {}, allow_stdin: false, stop_on_error: false }, "shell"));
65246
+ return;
65247
+ } catch {
65248
+ }
65249
+ }
65250
+ error51 ??= { name: "ConnectionLost", value: "Could not send the code to the kernel: the connection to the hub dropped. Try again shortly.", traceback: "" };
64545
65251
  finish();
64546
- }
64547
- });
64548
- channels.send(JSON.stringify({
64549
- header: { msg_id: msgId, username: "light-code", session: this.session, msg_type: "execute_request", version: "5.3", date: (/* @__PURE__ */ new Date()).toISOString() },
64550
- parent_header: {},
64551
- metadata: {},
64552
- content: { code, silent: false, store_history: false, user_expressions: {}, allow_stdin: false, stop_on_error: false },
64553
- buffers: [],
64554
- channel: "shell"
64555
- }));
65252
+ });
65253
+ }
64556
65254
  });
64557
65255
  }
64558
65256
  /** Ends the kernel; called when the session ends, so nothing is left running on the hub. */
64559
65257
  async dispose() {
64560
- this.channels?.close();
65258
+ const channels = this.channels;
64561
65259
  this.channels = void 0;
65260
+ channels?.close();
64562
65261
  const kernel = this.kernel;
64563
65262
  this.kernel = void 0;
64564
65263
  if (kernel !== void 0)
64565
65264
  await this.client.shutdownKernel(kernel.id).catch(() => void 0);
64566
65265
  }
64567
65266
  };
65267
+ function frame(msgId, session, type, content, channel) {
65268
+ return JSON.stringify({
65269
+ header: { msg_id: msgId, username: "light-code", session, msg_type: type, version: "5.3", date: (/* @__PURE__ */ new Date()).toISOString() },
65270
+ parent_header: {},
65271
+ metadata: {},
65272
+ content,
65273
+ buffers: [],
65274
+ channel
65275
+ });
65276
+ }
65277
+ function sleep(ms) {
65278
+ return new Promise((resolve) => setTimeout(resolve, ms));
65279
+ }
64568
65280
  function stripAnsi(text2) {
64569
65281
  return text2.replace(/\u001b\[[0-9;]*[A-Za-z]/g, "");
64570
65282
  }
@@ -66077,7 +66789,7 @@ var runSchema = external_exports.object({
66077
66789
  args: external_exports.array(external_exports.string()).optional().describe("Command-line arguments for file (sys.argv[1:])."),
66078
66790
  shell: external_exports.string().optional().describe("A shell command to run on the hub server, from the folder given in cwd or the top folder."),
66079
66791
  cwd: external_exports.string().optional().describe("For shell: a workspace folder (inside the hub folders) to run it in."),
66080
- timeoutSeconds: external_exports.number().int().min(5).max(3600).optional()
66792
+ timeoutSeconds: external_exports.number().int().min(5).max(3600).optional().describe("How long the run may take before it is interrupted.")
66081
66793
  });
66082
66794
  var inspectSchema = external_exports.object({
66083
66795
  name: external_exports.string().optional().describe('A module, class or function on the hub, e.g. "pandas.read_csv" or "acme_risk.pricing".'),
@@ -66085,7 +66797,7 @@ var inspectSchema = external_exports.object({
66085
66797
  packages: external_exports.string().optional().describe('Instead of name: list installed packages whose name contains this ("" for all).')
66086
66798
  });
66087
66799
  var syncSchema = external_exports.object({
66088
- action: external_exports.enum(["pull", "push", "status", "hub_version", "use_hub_version"]),
66800
+ action: external_exports.enum(["pull", "push", "status", "hub_version", "use_hub_version"]).describe("pull: fetch the hub's changes. push: save local changes to the hub. status: what differs. hub_version: show the hub's copy of a conflicting file. use_hub_version: replace the local copy with it."),
66089
66801
  path: external_exports.string().optional().describe("For push, hub_version, use_hub_version: one workspace file. push without it saves every local change.")
66090
66802
  });
66091
66803
  var py = (value) => JSON.stringify(value);
@@ -67197,15 +67909,15 @@ var grepSchema = external_exports.object({
67197
67909
  pattern: external_exports.string().min(1).describe("A regular expression (or plain text with literal: true). Case-insensitive unless it has a capital letter."),
67198
67910
  roots: external_exports.array(external_exports.string().min(1)).min(1).max(20).describe("Folders or files to search: workspace-relative, absolute, another drive, or shares like \\\\server\\share\\folder - several at once."),
67199
67911
  literal: external_exports.boolean().optional().describe("Search for the text exactly as written, not as a regular expression."),
67200
- caseSensitive: external_exports.boolean().optional(),
67201
- wholeWord: external_exports.boolean().optional(),
67912
+ caseSensitive: external_exports.boolean().optional().describe("Match capital letters exactly (default: case-insensitive)."),
67913
+ wholeWord: external_exports.boolean().optional().describe("Match whole words only."),
67202
67914
  names: external_exports.array(external_exports.string()).optional().describe('Only files whose names match these patterns (* and ?), e.g. ["*.log", "*.py"].'),
67203
67915
  extensions: external_exports.array(external_exports.string()).optional().describe('e.g. ["py", "sql"].'),
67204
67916
  modifiedAfter: dateSchema,
67205
67917
  modifiedBefore: dateSchema,
67206
67918
  context: external_exports.number().int().min(0).max(10).optional().describe("Lines before and after each match."),
67207
67919
  filesOnly: external_exports.boolean().optional().describe("List the matching files with a count each, not the lines."),
67208
- includeHidden: external_exports.boolean().optional(),
67920
+ includeHidden: external_exports.boolean().optional().describe("Include hidden files and folders (names starting with a dot)."),
67209
67921
  respectGitignore: external_exports.boolean().optional().describe("Skip what .gitignore excludes (default true)."),
67210
67922
  maxPerFile: external_exports.number().int().min(1).max(1e3).optional().describe("Matches shown per file (default 50)."),
67211
67923
  limit: external_exports.number().int().min(1).max(5e3).optional().describe("Matches in all (default 300).")
@@ -67215,37 +67927,37 @@ var findSchema = external_exports.object({
67215
67927
  roots: external_exports.array(external_exports.string().min(1)).min(1).max(20).describe("Folders to look in: workspace-relative, absolute, another drive, or a share like \\\\server\\share\\folder."),
67216
67928
  names: external_exports.array(external_exports.string()).optional().describe("File-name patterns (* and ?) or plain text the name contains. Case-insensitive."),
67217
67929
  extensions: external_exports.array(external_exports.string()).optional().describe('e.g. ["xlsx", "csv"].'),
67218
- minSizeBytes: external_exports.number().int().min(0).optional(),
67219
- maxSizeBytes: external_exports.number().int().min(0).optional(),
67930
+ minSizeBytes: external_exports.number().int().min(0).optional().describe("Only files at least this many bytes."),
67931
+ maxSizeBytes: external_exports.number().int().min(0).optional().describe("Only files at most this many bytes."),
67220
67932
  modifiedAfter: dateSchema,
67221
67933
  modifiedBefore: dateSchema,
67222
67934
  directories: external_exports.boolean().optional().describe("find: list folders instead of files."),
67223
- includeHidden: external_exports.boolean().optional(),
67935
+ includeHidden: external_exports.boolean().optional().describe("Include hidden files and folders (names starting with a dot)."),
67224
67936
  respectGitignore: external_exports.boolean().optional().describe("Skip what .gitignore excludes (inside repositories)."),
67225
- maxDepth: external_exports.number().int().min(0).max(64).optional(),
67937
+ maxDepth: external_exports.number().int().min(0).max(64).optional().describe("How many folder levels below each root to look (0 = the root only)."),
67226
67938
  limit: external_exports.number().int().min(1).max(2e3).optional().describe("find: default 200. duplicates: groups, default 30.")
67227
67939
  });
67228
67940
  var readManySchema = external_exports.object({
67229
67941
  files: external_exports.array(external_exports.object({
67230
- path: external_exports.string().min(1),
67231
- fromLine: external_exports.number().int().min(1).optional(),
67232
- lines: external_exports.number().int().min(1).optional()
67942
+ path: external_exports.string().min(1).describe("The file."),
67943
+ fromLine: external_exports.number().int().min(1).optional().describe("First line to read (1-based)."),
67944
+ lines: external_exports.number().int().min(1).optional().describe("How many lines from fromLine.")
67233
67945
  })).min(1).max(50).describe("Up to 50 files, each optionally a window of lines. Read in parallel.")
67234
67946
  });
67235
67947
  var bigFileSchema = external_exports.object({
67236
67948
  action: external_exports.enum(["inspect", "lines", "tail", "search"]).describe("inspect: size, line count, first lines, and for CSV/Excel the columns and their types. lines: a window (fromLine, count). tail: the last lines. search: a regular expression across the whole file, with context lines."),
67237
- path: external_exports.string().min(1),
67238
- fromLine: external_exports.number().int().min(1).optional(),
67949
+ path: external_exports.string().min(1).describe("The file: workspace-relative, absolute or on a share."),
67950
+ fromLine: external_exports.number().int().min(1).optional().describe("lines: the first line of the window (1-based)."),
67239
67951
  count: external_exports.number().int().min(1).max(5e3).optional().describe("lines/tail: how many (default 200 / 100)."),
67240
67952
  pattern: external_exports.string().optional().describe("search: a regular expression (case-insensitive unless caseSensitive)."),
67241
- caseSensitive: external_exports.boolean().optional(),
67953
+ caseSensitive: external_exports.boolean().optional().describe("Match capital letters exactly (default: case-insensitive)."),
67242
67954
  context: external_exports.number().int().min(0).max(10).optional().describe("search: lines before and after each match."),
67243
67955
  limit: external_exports.number().int().min(1).max(500).optional().describe("search: matches to return (default 100).")
67244
67956
  });
67245
67957
  var tableSchema = external_exports.object({
67246
67958
  path: external_exports.string().min(1).describe("A .csv, .tsv or delimited text file, or an Excel workbook (.xlsx, .xlsm, .xls) or .ods."),
67247
67959
  sheet: external_exports.string().optional().describe("Workbook sheet; the first when omitted."),
67248
- delimiter: external_exports.string().max(1).optional(),
67960
+ delimiter: external_exports.string().max(1).optional().describe("Delimited text: the separator character (detected when omitted)."),
67249
67961
  header: external_exports.boolean().optional().describe("First row is the header (default true)."),
67250
67962
  columns: external_exports.array(external_exports.string()).optional().describe("Columns to return, without grouping."),
67251
67963
  filters: external_exports.array(external_exports.object({
@@ -67253,8 +67965,8 @@ var tableSchema = external_exports.object({
67253
67965
  op: external_exports.enum(["eq", "ne", "gt", "ge", "lt", "le", "contains", "startsWith", "empty", "notEmpty"]),
67254
67966
  value: external_exports.string().optional()
67255
67967
  })).optional().describe("All must match. Numbers compare as numbers."),
67256
- groupBy: external_exports.array(external_exports.string()).optional(),
67257
- aggregates: external_exports.array(external_exports.object({ fn: external_exports.enum(["count", "sum", "avg", "min", "max", "distinct"]), column: external_exports.string().optional() })).optional(),
67968
+ groupBy: external_exports.array(external_exports.string()).optional().describe("Group rows by these columns; use with aggregates."),
67969
+ aggregates: external_exports.array(external_exports.object({ fn: external_exports.enum(["count", "sum", "avg", "min", "max", "distinct"]), column: external_exports.string().optional().describe("The column (not needed for count).") })).optional().describe('Per group (or over all rows): e.g. [{"fn": "sum", "column": "amount"}, {"fn": "count"}].'),
67258
67970
  sort: external_exports.array(external_exports.object({ column: external_exports.string(), desc: external_exports.boolean().optional() })).optional().describe('By result column name, e.g. "sum(amount)".'),
67259
67971
  offset: external_exports.number().int().min(0).optional().describe("Page through results."),
67260
67972
  limit: external_exports.number().int().min(1).max(500).optional().describe("Rows to return (default 50).")
@@ -67270,7 +67982,7 @@ var sqliteSchema = external_exports.object({
67270
67982
  groupBy: external_exports.array(external_exports.string()).optional().describe("scan: group by these columns."),
67271
67983
  aggregates: tableSchema.shape.aggregates,
67272
67984
  sort: external_exports.array(external_exports.object({ column: external_exports.string(), desc: external_exports.boolean().optional() })).optional().describe('scan: by column, or by result column such as "sum(amount)" when grouping.'),
67273
- offset: external_exports.number().int().min(0).optional(),
67985
+ offset: external_exports.number().int().min(0).optional().describe("Rows to skip, to page through results."),
67274
67986
  limit: external_exports.number().int().min(1).max(5e3).optional().describe("Rows to return (query default 200, scan 50, search 100)."),
67275
67987
  text: external_exports.string().optional().describe("search: the text to find, case-insensitive."),
67276
67988
  tables: external_exports.array(external_exports.string()).optional().describe("search: only these tables."),
@@ -67292,7 +68004,7 @@ var dataframeSchema = external_exports.object({
67292
68004
  delimiter: external_exports.string().optional().describe('Delimited text: the separator (detected when omitted; "tab" for tab).'),
67293
68005
  header: external_exports.boolean().optional().describe("First row holds the column names (default true)."),
67294
68006
  skipRows: external_exports.number().int().min(0).optional().describe("Rows to skip before the header, e.g. a title block.")
67295
- })).min(1).max(20),
68007
+ })).min(1).max(20).describe("The tables to query: each a file, a SQLite table, records you already have, a truncated tool result, or the clipboard."),
67296
68008
  steps: external_exports.array(external_exports.object({ name: external_exports.string(), sql: external_exports.string() })).max(20).optional().describe("sql: named intermediate results, run in order before `sql`; each becomes a table the later steps and `sql` can join and alias like a source (e.g. totals per owner, then join people). Use these instead of WITH ... AS when the result needs an alias - an aliased WITH step is not supported."),
67297
68009
  sql: external_exports.string().optional().describe('sql: a SELECT over the source names. Quote odd column names with "double quotes".'),
67298
68010
  pivot: external_exports.object({
@@ -67301,12 +68013,12 @@ var dataframeSchema = external_exports.object({
67301
68013
  values: external_exports.string().describe("The column aggregated into each cell."),
67302
68014
  agg: external_exports.enum(["sum", "count", "avg", "min", "max", "first", "last"]).optional().describe("Default sum.")
67303
68015
  }).optional().describe("sql: turn the result (or the first source, without sql) wide."),
67304
- offset: external_exports.number().int().min(0).optional(),
68016
+ offset: external_exports.number().int().min(0).optional().describe("Rows to skip, to page through results."),
67305
68017
  limit: external_exports.number().int().min(1).max(5e3).optional().describe("Rows to return (default 50).")
67306
68018
  });
67307
68019
  var transferSchema = external_exports.object({
67308
68020
  action: external_exports.enum(["copy", "move"]).describe("copy leaves the source; move removes it once everything is copied."),
67309
- items: external_exports.array(external_exports.object({ from: external_exports.string().min(1), to: external_exports.string().min(1).describe("The full destination path: the new folder or file, not its parent.") })).min(1).max(50),
68021
+ items: external_exports.array(external_exports.object({ from: external_exports.string().min(1).describe("The file or folder to copy or move."), to: external_exports.string().min(1).describe("The full destination path: the new folder or file, not its parent.") })).min(1).max(50).describe("What to copy or move, up to 50 pairs."),
67310
68022
  overwrite: external_exports.boolean().optional().describe("Replace files that already exist at the destination. Without it, nothing is changed when any exists.")
67311
68023
  });
67312
68024
  async function transferPaths(context, params3) {
@@ -68122,7 +68834,7 @@ function offloadedCatalogue(hidden, otherHidden = 0) {
68122
68834
 
68123
68835
  // ../../packages/core/dist/tools/http.js
68124
68836
  var schema3 = external_exports.object({
68125
- method: external_exports.enum(["GET", "POST"]).default("GET"),
68837
+ method: external_exports.enum(["GET", "POST"]).default("GET").describe("GET to read, POST to send a body."),
68126
68838
  url: external_exports.string().min(1).describe("The full URL, e.g. https://<host>/v1/items?limit=10. Its host must be one the user named in this chat."),
68127
68839
  headers: external_exports.record(external_exports.string(), external_exports.string()).optional().describe("Request headers. Put credentials in as ${secret:NAME} (from secret storage) - never paste a token."),
68128
68840
  query: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])).optional().describe("Added to the URL's query string."),
@@ -68131,7 +68843,7 @@ var schema3 = external_exports.object({
68131
68843
  auth: external_exports.object({
68132
68844
  type: external_exports.enum(["none", "negotiate", "profile"]).describe("negotiate: Kerberos/NTLM as the signed-in Windows user. profile: the auth of a configured provider profile (e.g. an Apigee gateway: its token and certificates)."),
68133
68845
  profile: external_exports.string().optional().describe("profile: the provider profile's name or id, as in Settings \u2192 Providers.")
68134
- }).optional(),
68846
+ }).optional().describe("How to sign in, when the API needs more than headers."),
68135
68847
  tls: external_exports.object({
68136
68848
  caFile: external_exports.string().optional().describe("A CA certificate file (PEM) to trust, beyond the global ones."),
68137
68849
  certFile: external_exports.string().optional().describe("Client certificate (PEM)."),
@@ -68236,7 +68948,7 @@ async function readAll(response) {
68236
68948
  }
68237
68949
  return out;
68238
68950
  }
68239
- var sleep = (ms, signal) => new Promise((resolve) => {
68951
+ var sleep2 = (ms, signal) => new Promise((resolve) => {
68240
68952
  const timer = setTimeout(resolve, ms);
68241
68953
  signal?.addEventListener("abort", () => {
68242
68954
  clearTimeout(timer);
@@ -68414,7 +69126,7 @@ async function send(options, params3, context) {
68414
69126
  method = "GET";
68415
69127
  sendBody = void 0;
68416
69128
  }
68417
- await sleep(delay, context.signal);
69129
+ await sleep2(delay, context.signal);
68418
69130
  attempt += 1;
68419
69131
  response = await once(method, url2, sendBody);
68420
69132
  }
@@ -72689,14 +73401,14 @@ var diagramLegendSchema = external_exports.object({
72689
73401
  });
72690
73402
  var DIAGRAM_MAX_LEGEND = 8;
72691
73403
  var diagramSpecSchema = external_exports.object({
72692
- title: external_exports.string().max(120).optional(),
73404
+ title: external_exports.string().max(120).optional().describe("A heading shown above the diagram."),
72693
73405
  textSize: external_exports.enum(TEXT_SIZES).optional().describe("The size for every box that does not set its own. Use it when the user says the diagram is too small or too large to read comfortably."),
72694
73406
  legend: external_exports.array(diagramLegendSchema).max(DIAGRAM_MAX_LEGEND).optional().describe("A key under the diagram. Give an entry only where the meaning is not obvious from the label \u2014 a colour that stands for something, a shape used in a particular way. Explain the diagram, not the palette."),
72695
73407
  /** See `display/size.ts` — the same field and the same words as a chart's. */
72696
73408
  size: external_exports.enum(DISPLAY_SIZES).optional().describe(DISPLAY_SIZE_DESCRIPTION),
72697
73409
  direction: external_exports.enum(["down", "right"]).optional().describe("Which way the flow runs. down is the default and suits most flows."),
72698
- nodes: external_exports.array(diagramNodeSchema).min(1).max(DIAGRAM_MAX_NODES),
72699
- edges: external_exports.array(diagramEdgeSchema).max(DIAGRAM_MAX_EDGES),
73410
+ nodes: external_exports.array(diagramNodeSchema).min(1).max(DIAGRAM_MAX_NODES).describe("The boxes, each with an id and a label. Layout is automatic."),
73411
+ edges: external_exports.array(diagramEdgeSchema).max(DIAGRAM_MAX_EDGES).describe("Arrows between node ids, from -> to."),
72700
73412
  note: external_exports.string().max(400).optional().describe("A line under the diagram. Say what it leaves out, or where it came from.")
72701
73413
  }).superRefine((spec, context) => {
72702
73414
  const ids = /* @__PURE__ */ new Set();
@@ -74539,7 +75251,7 @@ function createJenkinsWriteJobTool(options) {
74539
75251
  parameters: external_exports.object({
74540
75252
  set: external_exports.array(parameterInput).optional().describe("Add these parameters, or change those of the same name."),
74541
75253
  remove: external_exports.array(external_exports.string()).optional().describe("Parameter names to remove.")
74542
- }).optional(),
75254
+ }).optional().describe("The job's build parameters to add, change or remove."),
74543
75255
  description: external_exports.string().optional().describe("The job's description."),
74544
75256
  edits: external_exports.array(external_exports.object({ find: external_exports.string().min(1), replace: external_exports.string() })).optional().describe("Exact text changes to the config.xml - for anything else (script path, branch, schedule, agent label). Each find must occur exactly once; read the job with jenkins_job and include enough around it to be unique.")
74545
75257
  });
@@ -77250,8 +77962,8 @@ function createMonitorShowTool(options) {
77250
77962
  };
77251
77963
  }
77252
77964
  var controlSchema = external_exports.object({
77253
- action: external_exports.enum(["pause", "resume", "snooze", "ack", "unack", "notify"]),
77254
- name: external_exports.string(),
77965
+ action: external_exports.enum(["pause", "resume", "snooze", "ack", "unack", "notify"]).describe("pause / resume the checks, snooze notifications, ack / unack alerts, or set how it notifies."),
77966
+ name: external_exports.string().describe("The monitor."),
77255
77967
  minutes: external_exports.number().int().min(0).max(10080).optional().describe("snooze: how long (0 ends a snooze). ack: how long the acknowledgement lasts; omit for as long as the alert lasts."),
77256
77968
  ids: external_exports.array(external_exports.string()).optional().describe("ack / unack: which alerts, by the ids monitor_status shows. Omit for every alert."),
77257
77969
  note: external_exports.string().optional().describe("ack: why, kept with it."),
@@ -79269,7 +79981,7 @@ function createConfluenceSearchTool(options) {
79269
79981
  var readSchema3 = external_exports.object({
79270
79982
  pageId: external_exports.string().optional().describe("The page id, from confluence_search or a page URL."),
79271
79983
  space: external_exports.string().optional().describe("With `title`, find a page by its exact title in this space."),
79272
- title: external_exports.string().optional(),
79984
+ title: external_exports.string().optional().describe("With `space`: the exact page title."),
79273
79985
  images: external_exports.boolean().optional().describe("Also fetch the images attached to the page so you can look at them. Default false."),
79274
79986
  imageNames: external_exports.array(external_exports.string()).max(MAX_IMAGES2).optional().describe("Only these attachments, by name. Implies images.")
79275
79987
  });
@@ -80029,7 +80741,7 @@ var formFieldSchema = external_exports.object({
80029
80741
  var paramsSchema13 = external_exports.object({
80030
80742
  title: external_exports.string().min(1).describe("What this form is for, in a few words."),
80031
80743
  description: external_exports.string().optional().describe("Optional sentence above the fields."),
80032
- fields: external_exports.array(formFieldSchema).min(1).max(20)
80744
+ fields: external_exports.array(formFieldSchema).min(1).max(20).describe("The questions, in order: each with a key (the answer's name), a label and a type.")
80033
80745
  });
80034
80746
  function createAskUserFormTool() {
80035
80747
  return {
@@ -80563,14 +81275,14 @@ function parseTask(raw) {
80563
81275
  messages: task.messages,
80564
81276
  resultHandles: Array.isArray(task.resultHandles) ? task.resultHandles.filter((h) => typeof h === "string") : [],
80565
81277
  ...typeof plan3 === "string" ? { plan: plan3 } : {},
80566
- ...isRecord2(planProgress) ? { planProgress } : {},
81278
+ ...isRecord3(planProgress) ? { planProgress } : {},
80567
81279
  // A strategy a hand edit broke is left out rather than half-applied.
80568
81280
  ...strategy?.success === true ? { strategy: strategy.data } : {},
80569
- ...strategy?.success === true && isRecord2(strategyProgress) ? { strategyProgress } : {},
81281
+ ...strategy?.success === true && isRecord3(strategyProgress) ? { strategyProgress } : {},
80570
81282
  ...strategy?.success === true && Array.isArray(strategyExchanges) ? { strategyExchanges } : {}
80571
81283
  };
80572
81284
  }
80573
- function isRecord2(value) {
81285
+ function isRecord3(value) {
80574
81286
  return typeof value === "object" && value !== null && !Array.isArray(value);
80575
81287
  }
80576
81288
 
@@ -81920,11 +82632,11 @@ Note: ${data.storeProblem}` : "";
81920
82632
  // ../../packages/core/dist/usage/profileTool.js
81921
82633
  var params2 = external_exports.object({
81922
82634
  displayName: external_exports.string().max(200).optional().describe("The person's full name as the tool gave it."),
81923
- email: external_exports.string().max(200).optional(),
82635
+ email: external_exports.string().max(200).optional().describe("Work email address."),
81924
82636
  team: external_exports.string().max(200).optional().describe("Team or desk."),
81925
- department: external_exports.string().max(200).optional(),
82637
+ department: external_exports.string().max(200).optional().describe("Department or business unit."),
81926
82638
  title: external_exports.string().max(200).optional().describe("Job title."),
81927
- location: external_exports.string().max(200).optional(),
82639
+ location: external_exports.string().max(200).optional().describe("Office or city."),
81928
82640
  source: external_exports.string().max(200).optional().describe("The tool the details came from.")
81929
82641
  });
81930
82642
  var RECORD_USER_PROFILE = "record_user_profile";
@@ -83859,9 +84571,14 @@ ${preview.text}` } : {}
83859
84571
  const loaded = await loadSkills(dirs);
83860
84572
  skills = loaded.skills;
83861
84573
  skillIssues = loaded.issues;
83862
- for (const issue2 of loaded.issues)
83863
- logger.warn(`skill ${issue2.filePath}: ${issue2.detail}`);
84574
+ const signature = loaded.issues.map((issue2) => `${issue2.filePath}\0${issue2.detail}`).join("\n");
84575
+ if (signature !== loggedSkillIssues) {
84576
+ loggedSkillIssues = signature;
84577
+ for (const issue2 of loaded.issues)
84578
+ logger.warn(`skill ${issue2.filePath}: ${issue2.detail}`);
84579
+ }
83864
84580
  };
84581
+ let loggedSkillIssues = "";
83865
84582
  let skillWatchers = [];
83866
84583
  let skillWatchTimer;
83867
84584
  function stopWatchingSkills() {
@@ -86771,6 +87488,24 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
86771
87488
  await postTasks();
86772
87489
  }
86773
87490
  let handoffAbort;
87491
+ function startUserTurn(text2, images) {
87492
+ void (async () => {
87493
+ if (scheduledRunInFlight !== void 0) {
87494
+ logger.info("holding the message until the scheduled run finishes");
87495
+ await scheduledRunInFlight;
87496
+ }
87497
+ userTurnRunning = true;
87498
+ userTurnWindingDown = false;
87499
+ const turn = handleSendMessage(typeof text2 === "string" ? text2 : text2(), images);
87500
+ userTurnSettled = turn.then(() => void 0, () => void 0);
87501
+ try {
87502
+ await turn;
87503
+ } finally {
87504
+ userTurnRunning = false;
87505
+ userTurnWindingDown = false;
87506
+ }
87507
+ })();
87508
+ }
86774
87509
  async function handleHandoff() {
86775
87510
  if (handoffAbort !== void 0)
86776
87511
  return;
@@ -86840,11 +87575,12 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
86840
87575
  activeStrategy = carried.strategy;
86841
87576
  strategyProgress = carried.progress;
86842
87577
  strategyExchanges = carried.exchanges;
86843
- conversation.addUserMessage(composeHandoff(note, facts, previousTitle));
87578
+ const opening = composeHandoff(note, facts, previousTitle);
86844
87579
  await persistActiveTask();
86845
- post({ type: "taskRestored", taskId: activeTaskId, entries: toTranscript(conversation.toArray()) });
87580
+ post({ type: "taskRestored", taskId: activeTaskId, entries: toTranscript([{ role: "user", content: opening }]) });
86846
87581
  await postTasks();
86847
- progress("done");
87582
+ progress("done", { continuing: true });
87583
+ startUserTurn(opening);
86848
87584
  } catch (error51) {
86849
87585
  if (abort.signal.aborted)
86850
87586
  progress("cancelled");
@@ -86914,6 +87650,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
86914
87650
  const desiredPrompt = buildSystemPrompt(workspaceRoot, {
86915
87651
  model: profile.model,
86916
87652
  providerLabel: profile.label,
87653
+ providerBaseUrl: profile.baseUrl,
86917
87654
  expertAvailable: expertCliInfo !== void 0,
86918
87655
  // Named only when there is an index to prefer.
86919
87656
  mailIndexed: cachedMail.enabled === true && cachedOffice.outlook === true,
@@ -92700,13 +93437,17 @@ ${last}` : ""}`);
92700
93437
  await postEmbedder(config2);
92701
93438
  }
92702
93439
  async function clientFromInput(input) {
93440
+ const { store, id } = await storeFromInput(input);
93441
+ return openSearchClientFor(store, id);
93442
+ }
93443
+ async function storeFromInput(input) {
92703
93444
  const id = input.id ?? "__unsaved__";
92704
93445
  if (input.username !== void 0 && input.username.length > 0)
92705
93446
  await secrets.set(searchUserRefFor(id), input.username);
92706
93447
  if (input.password !== void 0 && input.password.length > 0)
92707
93448
  await secrets.set(searchPasswordRefFor(id), input.password);
92708
93449
  const store = {
92709
- kind: "opensearch",
93450
+ kind: input.kind ?? "opensearch",
92710
93451
  label: input.label.length > 0 ? input.label : "Untitled",
92711
93452
  url: input.url,
92712
93453
  ...await secrets.get(searchUserRefFor(id)) !== void 0 ? { usernameRef: searchUserRefFor(id) } : {},
@@ -92714,7 +93455,7 @@ ${last}` : ""}`);
92714
93455
  ...input.caFile !== void 0 && input.caFile.length > 0 ? { caFile: input.caFile } : {},
92715
93456
  ...input.rejectUnauthorized !== void 0 ? { rejectUnauthorized: input.rejectUnauthorized } : {}
92716
93457
  };
92717
- return openSearchClientFor(store, id);
93458
+ return { store, id };
92718
93459
  }
92719
93460
  async function handleSaveSearchConnection(input) {
92720
93461
  try {
@@ -92772,12 +93513,9 @@ ${last}` : ""}`);
92772
93513
  }
92773
93514
  async function handleTestSearchConnection(input) {
92774
93515
  try {
92775
- const info = await (await clientFromInput(input)).ping();
92776
- post({
92777
- type: "searchTestResult",
92778
- ok: true,
92779
- detail: `Connected to ${info.clusterName ?? "the cluster"}${info.version !== void 0 ? ` (OpenSearch ${info.version})` : ""}.`
92780
- });
93516
+ const { store, id } = await storeFromInput(input);
93517
+ const detail = await probeVectorStore(httpClient, store.kind, await vectorStoreConnectionFor(store, id));
93518
+ post({ type: "searchTestResult", ok: true, detail });
92781
93519
  } catch (error51) {
92782
93520
  post({
92783
93521
  type: "searchTestResult",
@@ -93236,7 +93974,8 @@ ${notes.join("\n")}` } : answer;
93236
93974
  return decision === "approve";
93237
93975
  };
93238
93976
  const exe = services.fastFs;
93239
- if (exe !== void 0 && seatProfile.wireFormat !== "vscode-lm" && (await fastFsAnswered)?.has("agent") === true) {
93977
+ const gemini = isGeminiModel(seatProfile.model, seatProfile.baseUrl);
93978
+ if (exe !== void 0 && seatProfile.wireFormat !== "vscode-lm" && !gemini && (await fastFsAnswered)?.has("agent") === true) {
93240
93979
  const system = buildAgentPrompt({
93241
93980
  prompt: agent.prompt,
93242
93981
  question: "",
@@ -93692,22 +94431,7 @@ ${notes.join("\n")}` } : answer;
93692
94431
  logger.warn("Ignoring sendMessage: a turn is already in progress.");
93693
94432
  return;
93694
94433
  }
93695
- void (async () => {
93696
- if (scheduledRunInFlight !== void 0) {
93697
- logger.info("holding the message until the scheduled run finishes");
93698
- await scheduledRunInFlight;
93699
- }
93700
- userTurnRunning = true;
93701
- userTurnWindingDown = false;
93702
- const turn = handleSendMessage(composeUserText(message5.text, { replyTo: boundedQuote(message5.replyTo), reactions: takeReactions() }), message5.images);
93703
- userTurnSettled = turn.then(() => void 0, () => void 0);
93704
- try {
93705
- await turn;
93706
- } finally {
93707
- userTurnRunning = false;
93708
- userTurnWindingDown = false;
93709
- }
93710
- })();
94434
+ startUserTurn(() => composeUserText(message5.text, { replyTo: boundedQuote(message5.replyTo), reactions: takeReactions() }), message5.images);
93711
94435
  } else if (message5.type === "saveComposerDraft") {
93712
94436
  void saveComposerDraft(message5.text);
93713
94437
  } else if (message5.type === "requestComposerDraft") {
@@ -95079,13 +95803,13 @@ var chartSeriesSchema = external_exports.object({
95079
95803
  });
95080
95804
  var chartSpecSchema = external_exports.object({
95081
95805
  type: external_exports.enum(CHART_TYPES).describe("bar, stackedBar, groupedBar, line, multiLine or pie."),
95082
- title: external_exports.string().max(200).optional(),
95806
+ title: external_exports.string().max(200).optional().describe("A heading shown above the chart."),
95083
95807
  categories: external_exports.array(external_exports.string()).min(1).max(MAX_CATEGORIES).describe("The x axis, or the pie slice labels. One per value in every series."),
95084
- series: external_exports.array(chartSeriesSchema).min(1).max(MAX_SERIES),
95808
+ series: external_exports.array(chartSeriesSchema).min(1).max(MAX_SERIES).describe("One or more named lists of numbers, each with one value per category."),
95085
95809
  /** See `display/size.ts` — the same field and the same words as a diagram's. */
95086
95810
  size: external_exports.enum(DISPLAY_SIZES).optional().describe(DISPLAY_SIZE_DESCRIPTION),
95087
- xLabel: external_exports.string().max(80).optional(),
95088
- yLabel: external_exports.string().max(80).optional(),
95811
+ xLabel: external_exports.string().max(80).optional().describe("The x axis title."),
95812
+ yLabel: external_exports.string().max(80).optional().describe("The y axis title, with the unit."),
95089
95813
  note: external_exports.string().max(500).optional().describe("A line under the chart. Say where the numbers came from, and what they exclude.")
95090
95814
  }).superRefine((spec, context) => {
95091
95815
  for (const [index, series] of spec.series.entries()) {
@@ -96350,7 +97074,13 @@ Folders you always want readable go in config:filesystem.readRoots.
96350
97074
  "ca",
96351
97075
  "token",
96352
97076
  "401",
96353
- "profile"
97077
+ "profile",
97078
+ "gemini through a gateway",
97079
+ "gemini openai compatible",
97080
+ "thought signature",
97081
+ "gemini 4",
97082
+ "gemini 3",
97083
+ "qwen"
96354
97084
  ],
96355
97085
  body: `
96356
97086
  **Settings \u2192 Providers.** Several named profiles, switchable from the composer. Three wire
@@ -96389,6 +97119,24 @@ every file-reading tool.
96389
97119
  you **which step failed**. It is the fastest way to turn an opaque TLS or OAuth failure into a
96390
97120
  diagnosis.
96391
97121
 
97122
+ **Gemini through an OpenAI-compatible endpoint** (a corporate gateway, or Google's own): choose OpenAI-compatible,
97123
+ enter the gateway's URL and the model id as the gateway names it (anything containing "gemini" is recognised, e.g.
97124
+ \`gemini-4-pro\` or \`google/gemini-4\`). Light Code then handles what Gemini does differently, and only for Gemini -
97125
+ Qwen and other models on the same wire are sent exactly what they were before:
97126
+ - **Thought signatures**: from Gemini 3 on, each tool call carries one that must be sent back, or the next request is
97127
+ refused (HTTP 400). They are kept with the conversation (so a chat reopened from History works) and returned; a
97128
+ call without one - an older chat, another model's history - gets Google's documented skip value.
97129
+ - **Tool schemas** in the subset Gemini accepts: a limit or default it cannot take is written into the parameter's
97130
+ description; a free-form object (\`call_tool\`'s arguments, Jira fields) is offered as JSON text and turned back into
97131
+ an object for the tool.
97132
+ - **Its streams**: tool calls ending with "stop", calls without an id, parallel calls without an index.
97133
+ - **Its thoughts**: with Thinking above off on the profile, they are asked for and shown as the reasoning trace. A
97134
+ gateway that refuses the field is asked again without it, and remembered.
97135
+ - **A few lines of guidance** in the prompt for Gemini's habits: one tool call per reply, calls only through function
97136
+ calling, parameter names exactly as declared.
97137
+ Agent team specialists on a Gemini profile run inside the agent rather than in the Rust helper, which does not carry
97138
+ signatures. If a call ever fails with "thought_signature", tell us the gateway and model.
97139
+
96392
97140
  **Behind a proxy?** Settings \u2192 Network reports what the environment says. A corporate root CA that
96393
97141
  your proxy presents goes in the same place; adding one does not cost you the public roots.
96394
97142
  `
@@ -96768,6 +97516,12 @@ connections, config:activeVectorStoreId the current one, config:embedder the emb
96768
97516
  model, and config:retrieval the rest. All user-scope only \u2014 a repository able to set the embedder
96769
97517
  URL would exfiltrate your source the moment you opened it.
96770
97518
 
97519
+ **Each connection has a Type, and it must match the server.** A new connection starts as Qdrant;
97520
+ for a team OpenSearch cluster set Type to OpenSearch. Every connection in the list shows its type,
97521
+ and Test connection speaks that type, so a mismatch fails there. A mismatched connection shows up at
97522
+ indexing as "Could not read collection ... (HTTP 400)", which now ends by saying the address answers
97523
+ like OpenSearch - the fix is the Type, not the project or index name.
97524
+
96771
97525
  **Retrieval is exposed as tools the model calls**, never as tool definitions that change per turn.
96772
97526
  \`search_codebase\` and \`search_docs\` return results as tool *results*, mid-conversation, where
96773
97527
  they cost nothing at the front of the prompt.
@@ -98239,6 +98993,13 @@ your hub server (one per line, from your home folder; / for all of it), and an A
98239
98993
  on the hub's Token page (\`<hub>/hub/token\`). The token is saved encrypted in Credentials as
98240
98994
  "JupyterHub <user>@<host>" and only ever sent to that hub, in a header. Optional: a named server and
98241
98995
  a kernel (e.g. python3). Right-click the codebase \u2192 JupyterHub settings\u2026 changes them later.
98996
+
98997
+ **A dropped connection is reconnected by itself.** The kernel channel is a WebSocket through the hub's proxy, which
98998
+ VPNs, sleep and proxy timeouts cut. The agent reconnects to the **same kernel**, so variables survive; a run cut off
98999
+ mid-way finishes from what the hub kept, and if the hub kept nothing the result says the run finished with its output
99000
+ lost. A connection that goes silent without closing is noticed by a heartbeat. Every call to the hub has a time limit,
99001
+ and a hub server stopped by idle culling is started again (when your token may) - no agent restart needed. Only a
99002
+ kernel the hub no longer has is replaced, and then the result says the earlier state is gone.
98242
99003
  Your hub server must be running; if it is not, the agent says so - start it from the hub's home page.
98243
99004
 
98244
99005
  **\`.hubignore\`** lists files and folders that are never synced, either way - \`.gitignore\` syntax
@@ -98571,7 +99332,9 @@ colour on its tile but no longer colours the Monitoring button.
98571
99332
  **An alert explained**: double-click a coloured row. The author's advice for that rule comes first (asked for when
98572
99333
  the monitor is created), then **the agent's explanation** - what is wrong, whether it is new or known from the
98573
99334
  history, what to do. **Start a chat** opens a chat named after the alert in the codebase you pick (the first by
98574
- default), with what is known already in the message box - press Enter to send it.
99335
+ default), with what is known already in the message box - the alert, its facts and history, and the explanation
99336
+ you just read - press Enter to send it. (Before Fire Code 0.80 the box could open empty when the chat's agent was
99337
+ still starting.)
98575
99338
 
98576
99339
  **Fast data collection**: a monitor that reads SQLite or a CSV/Excel/JSON file is read by Fire Code's Rust helper
98577
99340
  (Polars) - no Python at all. Fire Code's Rust tools can be a monitor's source too, with \`"records": true\` (a JSON list
@@ -99380,7 +100143,7 @@ lost; it is just not all in the window at once.
99380
100143
  **A new chat with a handoff** (the button beside +, a page with an arrow): when a long chat is near the
99381
100144
  limit and compacting would blur it, start clean instead. The assistant writes a handoff - the goal, what
99382
100145
  is done and decided, the current state, open questions and next steps - and a new chat opens with it as
99383
- its first message. Your own messages are quoted word for word, and the files read and changed and the
100146
+ its first message - and **carries on by itself**: the new chat's first turn starts at once, so there is nothing to send. Your own messages are quoted word for word, and the files read and changed and the
99384
100147
  commands run are listed from the actual tool calls, so nothing important rests on the summary alone. A
99385
100148
  progress panel shows each step and how much has been written; Cancel stops it, and a failure leaves the
99386
100149
  chat as it was. The old chat stays in History. When a reply fails because the conversation is too long
@@ -99765,7 +100528,11 @@ walkthrough, whose steps link straight into the tab each one is about. On the No
99765
100528
  "conversation lost",
99766
100529
  "draft lost",
99767
100530
  "typed message gone",
99768
- "host.log"
100531
+ "host.log",
100532
+ "crash log",
100533
+ "why did it crash",
100534
+ "exit code",
100535
+ "out of memory"
99769
100536
  ],
99770
100537
  body: `
99771
100538
  **The agent crashed, or python.exe "stopped working".** A Python tool's worker that crashes is restarted on the
@@ -99777,6 +100544,13 @@ conversation is saved as the turn goes - after your message and after each tool
99777
100544
  kept by the agent as well, so a restart loses neither. Each chat's log is \`host.log\` in its data folder, with the
99778
100545
  run before as \`host.previous.log\`: an error the agent survived is written there as "kept running".
99779
100546
 
100547
+ **Why did the Fire Code agent stop?** The stopped chat says it: the exit code in words (out of memory, a native
100548
+ crash, ended from outside such as antivirus or Task Manager) and where the crashed run's log is kept - a copy in
100549
+ \`crashes/host-<date>.log\` in the chat's data folder that a Restart never overwrites (the newest ten are kept). An
100550
+ out-of-memory stop also leaves a Node report in \`crash-reports\`. The log has a \`[memory]\` line every ten minutes
100551
+ and a warning near the heap limit, so growth before a crash shows; a log that ends without "exiting through Node"
100552
+ means the process was killed or crashed natively. Send the kept log and the report when asking for a fix.
100553
+
99780
100554
  **A button is greyed out.** Hover over it: every control that can be disabled says why in its
99781
100555
  tooltip - nothing changed since the last save, a field still empty, a reply still running, a
99782
100556
  feature switched off elsewhere - and usually what to do about it.
@@ -100404,7 +101178,7 @@ var schema9 = external_exports.object({
100404
101178
  reason: external_exports.string().max(200).optional().describe('What you are waiting for, shown to the user \u2014 e.g. "PAY_EOD to finish".')
100405
101179
  });
100406
101180
  function createWaitTool(options = {}) {
100407
- const sleep2 = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
101181
+ const sleep3 = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
100408
101182
  const now = options.now ?? (() => Date.now());
100409
101183
  return {
100410
101184
  name: "wait",
@@ -100424,7 +101198,7 @@ function createWaitTool(options = {}) {
100424
101198
  content: `Stopped waiting${what} after ${String(Math.round((now() - started) / 1e3))}s: the user has sent something. Read it before carrying on.`
100425
101199
  };
100426
101200
  }
100427
- await sleep2(Math.min(1e3, until - now()));
101201
+ await sleep3(Math.min(1e3, until - now()));
100428
101202
  }
100429
101203
  return { content: `Waited ${String(params3.seconds)}s${what}. Check again now.` };
100430
101204
  }
@@ -101203,7 +101977,7 @@ async function syncFromS3(options) {
101203
101977
  const objects = await options.target.client.list(where, rawCeiling, options.signal);
101204
101978
  if (objects.length >= rawCeiling)
101205
101979
  result.truncated = true;
101206
- const manifestPath = join(options.localDir, MANIFEST_NAME);
101980
+ const manifestPath = join2(options.localDir, MANIFEST_NAME);
101207
101981
  const manifest = await readManifest(options.fs, manifestPath);
101208
101982
  let manifestChanged = false;
101209
101983
  let matched = 0;
@@ -101223,7 +101997,7 @@ async function syncFromS3(options) {
101223
101997
  continue;
101224
101998
  }
101225
101999
  try {
101226
- const localPath = join(options.localDir, relative);
102000
+ const localPath = join2(options.localDir, relative);
101227
102001
  const seen = manifest[object3.key];
101228
102002
  if (seen !== void 0 && seen.size === object3.size && seen.lastModified === object3.lastModified) {
101229
102003
  let present2 = false;
@@ -101288,7 +102062,7 @@ async function uploadToS3(options) {
101288
102062
  const where = normalisePrefix(`${base}${options.prefix ?? ""}`);
101289
102063
  await options.target.client.put(`${where}${options.relative}`, options.contents, void 0, options.signal);
101290
102064
  }
101291
- function join(dir, relative) {
102065
+ function join2(dir, relative) {
101292
102066
  const left = dir.replace(/[\\/]+$/, "");
101293
102067
  return `${left}/${relative}`;
101294
102068
  }
@@ -101499,14 +102273,14 @@ var import_node_crypto22 = require("node:crypto");
101499
102273
  function mirrorFolder(options) {
101500
102274
  const connection = safeSegment(options.connectionId);
101501
102275
  const digest = (0, import_node_crypto22.createHash)("sha256").update((options.prefix ?? "").trim().toLowerCase()).digest("hex").slice(0, 8);
101502
- return join2(options.storageDir, "s3", connection, `${options.kind}-${digest}`);
102276
+ return join3(options.storageDir, "s3", connection, `${options.kind}-${digest}`);
101503
102277
  }
101504
102278
  function safeSegment(id) {
101505
102279
  const cleaned = id.replace(/[^a-zA-Z0-9._-]/g, "-").replace(/-+/g, "-").replace(/^[-.]+|[-.]+$/g, "").slice(0, 40);
101506
102280
  const suffix = (0, import_node_crypto22.createHash)("sha256").update(id).digest("hex").slice(0, 6);
101507
102281
  return `${cleaned === "" ? "connection" : cleaned}-${suffix}`;
101508
102282
  }
101509
- function join2(...parts) {
102283
+ function join3(...parts) {
101510
102284
  return parts.map((part, index) => index === 0 ? part.replace(/[\\/]+$/, "") : part).join("/");
101511
102285
  }
101512
102286
 
@@ -102225,7 +102999,7 @@ var SharedEntriesConfigStore = class {
102225
102999
  for (const collection of this.collections) {
102226
103000
  const entries = shared[collection.key];
102227
103001
  if (entries === void 0 || Object.keys(entries).length === 0) continue;
102228
- const own = isRecord3(parsed[collection.key]) ? parsed[collection.key] : {};
103002
+ const own = isRecord4(parsed[collection.key]) ? parsed[collection.key] : {};
102229
103003
  const presented = {};
102230
103004
  for (const [id, entry] of Object.entries(entries)) {
102231
103005
  presented[toSharedKey(id)] = present(entry, toSharedKey(id), collection);
@@ -102246,7 +103020,7 @@ var SharedEntriesConfigStore = class {
102246
103020
  }
102247
103021
  for (const collection of this.collections) {
102248
103022
  const own = parsed[collection.key];
102249
- if (!isRecord3(own)) continue;
103023
+ if (!isRecord4(own)) continue;
102250
103024
  parsed[collection.key] = Object.fromEntries(
102251
103025
  Object.entries(own).filter(([id]) => !isSharedKey(id))
102252
103026
  );
@@ -102258,7 +103032,7 @@ var SharedEntriesConfigStore = class {
102258
103032
  }
102259
103033
  };
102260
103034
  function present(entry, presentedId, collection) {
102261
- if (!isRecord3(entry)) return entry;
103035
+ if (!isRecord4(entry)) return entry;
102262
103036
  const copy = { ...entry };
102263
103037
  if (collection.refFields === void 0 || collection.refFor === void 0) return copy;
102264
103038
  for (const field2 of collection.refFields) {
@@ -102266,7 +103040,7 @@ function present(entry, presentedId, collection) {
102266
103040
  }
102267
103041
  return copy;
102268
103042
  }
102269
- function isRecord3(value) {
103043
+ function isRecord4(value) {
102270
103044
  return typeof value === "object" && value !== null && !Array.isArray(value);
102271
103045
  }
102272
103046
 
@@ -103097,19 +103871,19 @@ async function startServer(options) {
103097
103871
  let sink;
103098
103872
  const missed = [];
103099
103873
  const MAX_MISSED = 500;
103100
- const write = (frame) => {
103874
+ const write = (frame2) => {
103101
103875
  const target = sink;
103102
103876
  if (target === void 0 || target.writableEnded || target.destroyed) {
103103
103877
  if (missed.length >= MAX_MISSED) missed.shift();
103104
- missed.push(frame);
103878
+ missed.push(frame2);
103105
103879
  return;
103106
103880
  }
103107
103881
  try {
103108
- target.write(frame);
103882
+ target.write(frame2);
103109
103883
  } catch {
103110
103884
  sink = void 0;
103111
103885
  if (missed.length >= MAX_MISSED) missed.shift();
103112
- missed.push(frame);
103886
+ missed.push(frame2);
103113
103887
  }
103114
103888
  };
103115
103889
  const transport = {
@@ -103140,17 +103914,17 @@ async function startServer(options) {
103140
103914
  response.on("error", () => {
103141
103915
  if (sink === response) sink = void 0;
103142
103916
  });
103143
- for (const frame of missed.splice(0, missed.length)) {
103917
+ for (const frame2 of missed.splice(0, missed.length)) {
103144
103918
  if (sink !== response) break;
103145
- write(frame);
103919
+ write(frame2);
103146
103920
  }
103147
103921
  },
103148
103922
  detach: (response) => {
103149
103923
  if (sink === response) sink = void 0;
103150
103924
  },
103151
103925
  drain: () => {
103152
- return missed.splice(0, missed.length).flatMap((frame) => {
103153
- const body = frame.startsWith("data: ") ? frame.slice(6).trimEnd() : "";
103926
+ return missed.splice(0, missed.length).flatMap((frame2) => {
103927
+ const body = frame2.startsWith("data: ") ? frame2.slice(6).trimEnd() : "";
103154
103928
  if (body.length === 0) return [];
103155
103929
  try {
103156
103930
  return [JSON.parse(body)];