@kilncraft/core 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,15 +1,16 @@
1
- import { KilncraftError, toKilncraftError, emptyUsage, errors, addUsage, estimateCost, ids, isPrefixedId, kilncraftEventSchema } from '@kilncraft/shared';
1
+ import { KilncraftError, toKilncraftError, emptyUsage, errors, parseModelRef, addUsage, estimateCost, ids, isPrefixedId, kilncraftEventSchema } from '@kilncraft/shared';
2
2
  import { createHash } from 'crypto';
3
3
  import { mkdirSync, appendFileSync, existsSync, readFileSync, writeFileSync, readdirSync, copyFileSync, rmSync } from 'fs';
4
- import { dirname, resolve, relative, isAbsolute, join, basename } from 'path';
4
+ import { dirname, resolve, relative, isAbsolute, join, basename, extname } from 'path';
5
+ import { execFile, spawn } from 'child_process';
5
6
  import { realpath, stat, readFile, mkdir, writeFile, rename, rm, readdir } from 'fs/promises';
6
7
  import { createTwoFilesPatch } from 'diff';
7
8
  import { z } from 'zod';
8
9
  import { createRequire } from 'module';
9
10
  import { pathToFileURL } from 'url';
10
11
  import { homedir } from 'os';
11
- import { spawn } from 'child_process';
12
12
  import { glob } from 'tinyglobby';
13
+ import { promisify } from 'util';
13
14
 
14
15
  // src/agent/agent.ts
15
16
 
@@ -183,6 +184,83 @@ function summarizeInput(input) {
183
184
  }
184
185
  return JSON.stringify(input).slice(0, 200);
185
186
  }
187
+ var counter = 0;
188
+ var BackgroundShellManager = class {
189
+ shells = /* @__PURE__ */ new Map();
190
+ start(command, cwd, env = process.env) {
191
+ const id = `shell_${Date.now().toString(36)}_${counter++}`;
192
+ const shell = process.platform === "win32" ? process.env.COMSPEC ?? "cmd.exe" : process.env.SHELL ?? "/bin/bash";
193
+ const args = process.platform === "win32" ? ["/c", command] : ["-c", command];
194
+ const child = spawn(shell, args, {
195
+ cwd,
196
+ env,
197
+ stdio: ["ignore", "pipe", "pipe"],
198
+ detached: process.platform !== "win32"
199
+ });
200
+ const entry = {
201
+ id,
202
+ command,
203
+ cwd,
204
+ child,
205
+ stdout: "",
206
+ stderr: "",
207
+ exitCode: void 0,
208
+ closed: false
209
+ };
210
+ child.stdout?.on("data", (chunk) => {
211
+ entry.stdout = `${entry.stdout}${chunk.toString("utf8")}`.slice(-1e5);
212
+ });
213
+ child.stderr?.on("data", (chunk) => {
214
+ entry.stderr = `${entry.stderr}${chunk.toString("utf8")}`.slice(-1e5);
215
+ });
216
+ child.on("close", (code) => {
217
+ entry.exitCode = code ?? 0;
218
+ entry.closed = true;
219
+ });
220
+ child.on("error", () => {
221
+ entry.exitCode = 1;
222
+ entry.closed = true;
223
+ });
224
+ this.shells.set(id, entry);
225
+ return id;
226
+ }
227
+ list() {
228
+ return [...this.shells.keys()];
229
+ }
230
+ output(id) {
231
+ const shell = this.shells.get(id);
232
+ if (!shell) return void 0;
233
+ return {
234
+ stdout: shell.stdout,
235
+ stderr: shell.stderr,
236
+ exitCode: shell.exitCode ?? -1,
237
+ running: !shell.closed
238
+ };
239
+ }
240
+ write(id, input) {
241
+ const shell = this.shells.get(id);
242
+ if (!shell || shell.closed || !shell.child.stdin) return false;
243
+ shell.child.stdin.write(input);
244
+ return true;
245
+ }
246
+ kill(id) {
247
+ const shell = this.shells.get(id);
248
+ if (!shell) return false;
249
+ try {
250
+ if (process.platform !== "win32" && shell.child.pid) {
251
+ process.kill(-shell.child.pid, "SIGTERM");
252
+ } else {
253
+ shell.child.kill("SIGTERM");
254
+ }
255
+ } catch {
256
+ }
257
+ this.shells.delete(id);
258
+ return true;
259
+ }
260
+ closeAll() {
261
+ for (const id of [...this.shells.keys()]) this.kill(id);
262
+ }
263
+ };
186
264
  var DEFAULT_IGNORE = /* @__PURE__ */ new Set([
187
265
  "node_modules",
188
266
  ".git",
@@ -371,25 +449,25 @@ function matchesGlob(value, pattern) {
371
449
  function escapeRegExp(value) {
372
450
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
373
451
  }
374
- function toolOutputToText(output) {
375
- switch (output.kind) {
452
+ function toolOutputToText(output2) {
453
+ switch (output2.kind) {
376
454
  case "text":
377
- return output.text;
455
+ return output2.text;
378
456
  case "json":
379
- return JSON.stringify(output.value, null, 2);
457
+ return JSON.stringify(output2.value, null, 2);
380
458
  case "diff":
381
- return output.diff || "(no diff)";
459
+ return output2.diff || "(no diff)";
382
460
  case "image":
383
- return `[image ${output.mime} attached]`;
461
+ return `[image ${output2.mime} attached]`;
384
462
  case "terminal": {
385
463
  const parts = [];
386
- if (output.stdout) parts.push(output.stdout);
387
- if (output.stderr) parts.push(output.stderr);
388
- if (output.exitCode !== 0) parts.push(`[exit code ${output.exitCode}]`);
464
+ if (output2.stdout) parts.push(output2.stdout);
465
+ if (output2.stderr) parts.push(output2.stderr);
466
+ if (output2.exitCode !== 0) parts.push(`[exit code ${output2.exitCode}]`);
389
467
  return parts.join("\n") || "(no output)";
390
468
  }
391
469
  case "structured":
392
- return JSON.stringify(output.value, null, 2);
470
+ return JSON.stringify(output2.value, null, 2);
393
471
  }
394
472
  }
395
473
 
@@ -484,6 +562,23 @@ function parseToolInput(raw) {
484
562
  return { __invalid_json: raw };
485
563
  }
486
564
  }
565
+ function delay(ms, signal) {
566
+ return new Promise((resolve6, reject) => {
567
+ if (signal.aborted) {
568
+ reject(errors.aborted());
569
+ return;
570
+ }
571
+ const timer = setTimeout(() => {
572
+ signal.removeEventListener("abort", onAbort);
573
+ resolve6();
574
+ }, ms);
575
+ const onAbort = () => {
576
+ clearTimeout(timer);
577
+ reject(errors.aborted());
578
+ };
579
+ signal.addEventListener("abort", onAbort, { once: true });
580
+ });
581
+ }
487
582
  function withTimeout(promise, timeoutMs, signal) {
488
583
  if (signal.aborted) {
489
584
  return Promise.reject(errors.aborted("Tool execution aborted"));
@@ -536,10 +631,11 @@ function fallbackSession(options) {
536
631
  metadata: {}
537
632
  };
538
633
  }
539
- var Agent = class {
634
+ var Agent = class _Agent {
540
635
  constructor(options) {
541
636
  this.options = options;
542
637
  this.modelInfo = modelInfoFor(options.provider.id, options.model);
638
+ this.shells = options.shells ?? new BackgroundShellManager();
543
639
  const session = options.session ?? options.store?.create({
544
640
  cwd: options.cwd,
545
641
  model: `${options.provider.id}/${options.model}`,
@@ -553,6 +649,7 @@ var Agent = class {
553
649
  this.cost = session.cost;
554
650
  const todos = session.metadata.todos;
555
651
  if (Array.isArray(todos)) this.state.todos = todos;
652
+ this.titleGenerated = this.messages.length > 0;
556
653
  }
557
654
  }
558
655
  options;
@@ -562,7 +659,10 @@ var Agent = class {
562
659
  usage = emptyUsage();
563
660
  cost = 0;
564
661
  totalToolCalls = 0;
662
+ retries = 0;
663
+ titleGenerated = false;
565
664
  modelInfo;
665
+ shells;
566
666
  get id() {
567
667
  return this.session.id;
568
668
  }
@@ -588,6 +688,9 @@ var Agent = class {
588
688
  const todos = this.state.todos;
589
689
  return Array.isArray(todos) ? todos : [];
590
690
  }
691
+ close() {
692
+ this.shells.closeAll();
693
+ }
591
694
  async prompt(input, options = {}) {
592
695
  const signal = options.signal ?? new AbortController().signal;
593
696
  const emit = async (event) => {
@@ -616,25 +719,25 @@ var Agent = class {
616
719
  model: this.session.model
617
720
  });
618
721
  let lastText = "";
722
+ const startedAt = Date.now();
723
+ this.retries = 0;
619
724
  try {
620
725
  for (let turn = 0; turn < maxTurns; turn++) {
621
726
  if (signal.aborted) throw errors.aborted();
727
+ await emit({ type: "turn.phase", phase: "thinking" });
622
728
  await this.maybeCompact(system, emit);
623
- const stream = this.options.provider.stream({
624
- model: this.options.model,
625
- system,
626
- messages: this.messages,
627
- tools: this.options.tools.toSpecs(),
628
- maxTokens: this.options.maxTokens,
629
- signal
630
- });
631
- const { text, calls } = await this.consumeStream(stream, emit);
729
+ const { text, calls } = await this.streamWithRetry(system, signal, emit);
632
730
  lastText = text;
633
731
  this.pushMessage({ role: "assistant", content: text, toolCalls: calls });
634
732
  await emit({ type: "assistant.message", text, toolCalls: calls });
635
733
  if (calls.length === 0) {
636
- return await this.finish(lastText, "stop", emit);
734
+ return await this.finish(lastText, "stop", emit, startedAt);
637
735
  }
736
+ await emit({
737
+ type: "turn.phase",
738
+ phase: "tool",
739
+ detail: calls.map((call) => call.name).join(", ")
740
+ });
638
741
  const executed = await this.executeCalls(calls, signal, emit);
639
742
  for (const entry of executed) {
640
743
  this.pushMessage({
@@ -644,15 +747,124 @@ var Agent = class {
644
747
  name: entry.call.name
645
748
  });
646
749
  }
750
+ await emit({ type: "turn.phase", phase: "thinking" });
647
751
  }
648
- return await this.finish(lastText, "max_turns", emit);
752
+ return await this.finish(lastText, "max_turns", emit, startedAt);
649
753
  } catch (error) {
650
754
  const kilncraftError = toKilncraftError(error);
651
755
  this.updateSession({ status: "error" });
756
+ await emit({ type: "turn.phase", phase: "error", detail: kilncraftError.message });
652
757
  await emit({ type: "error", error: kilncraftError });
653
758
  throw kilncraftError;
654
759
  }
655
760
  }
761
+ async streamWithRetry(system, signal, emit) {
762
+ const maxRetries = Math.max(0, this.options.maxRetries ?? 2);
763
+ const baseDelay = Math.max(0, this.options.retryDelayMs ?? 500);
764
+ const providers = [this.options.provider, ...this.options.fallbackProviders ?? []];
765
+ let lastError;
766
+ for (const [providerIndex, provider] of providers.entries()) {
767
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
768
+ if (signal.aborted) throw errors.aborted();
769
+ if (attempt > 0) {
770
+ const delayMs = baseDelay * 2 ** (attempt - 1);
771
+ this.retries++;
772
+ await emit({
773
+ type: "turn.phase",
774
+ phase: "retrying",
775
+ detail: `${provider.id} attempt ${attempt + 1}`
776
+ });
777
+ await emit({
778
+ type: "tool.retry",
779
+ attempt,
780
+ delayMs,
781
+ reason: lastError?.message ?? "provider error",
782
+ provider: provider.id
783
+ });
784
+ await delay(delayMs, signal);
785
+ }
786
+ try {
787
+ this.modelInfo = modelInfoFor(provider.id, this.options.model);
788
+ const stream = provider.stream({
789
+ model: this.options.model,
790
+ system,
791
+ messages: this.messages,
792
+ tools: this.options.tools.toSpecs(),
793
+ maxTokens: this.options.maxTokens,
794
+ reasoningEffort: this.options.reasoningEffort,
795
+ promptCache: this.options.promptCache,
796
+ signal
797
+ });
798
+ return await this.consumeStream(stream, emit);
799
+ } catch (error) {
800
+ const failure = toKilncraftError(error);
801
+ if (signal.aborted || !failure.recoverable) throw failure;
802
+ lastError = failure;
803
+ }
804
+ }
805
+ if (providerIndex < providers.length - 1) {
806
+ await emit({
807
+ type: "tool.retry",
808
+ attempt: maxRetries + 1,
809
+ delayMs: baseDelay,
810
+ reason: lastError?.message ?? "provider error",
811
+ provider: providers[providerIndex + 1]?.id
812
+ });
813
+ }
814
+ }
815
+ throw lastError ?? errors.providerError("No provider available");
816
+ }
817
+ async runSubagent(request) {
818
+ const child = new _Agent({
819
+ cwd: this.options.cwd,
820
+ provider: this.options.provider,
821
+ model: request.model ?? this.options.model,
822
+ tools: this.options.tools,
823
+ permissions: this.options.permissions,
824
+ logger: this.options.logger,
825
+ agent: request.agent ?? "build",
826
+ maxTurns: this.options.maxTurns ?? 10,
827
+ askPermission: this.options.askPermission,
828
+ askUser: this.options.askUser,
829
+ sandbox: this.options.sandbox,
830
+ lsp: this.options.lsp,
831
+ isSubagent: true
832
+ });
833
+ try {
834
+ const result = await child.prompt(request.prompt);
835
+ return result.text;
836
+ } finally {
837
+ child.close();
838
+ }
839
+ }
840
+ async generateTitle(firstPrompt) {
841
+ const ref = this.options.smallModel;
842
+ if (!ref) return;
843
+ const parsed = parseModelRef(ref);
844
+ if (parsed && parsed.provider !== this.options.provider.id) return;
845
+ const model = parsed?.model ?? ref;
846
+ try {
847
+ const stream = this.options.provider.stream({
848
+ model,
849
+ system: "Generate a concise title (3-6 words) for this coding session. Return only the title.",
850
+ messages: [{ role: "user", content: firstPrompt }],
851
+ maxTokens: 24,
852
+ signal: new AbortController().signal
853
+ });
854
+ let text = "";
855
+ for await (const event of stream) {
856
+ if (event.type === "text-delta") text += event.text;
857
+ if (event.type === "error") return;
858
+ }
859
+ const title = text.replace(/\s+/g, " ").trim().replace(/^["']|["']$/g, "").slice(0, 60);
860
+ if (title.length > 0) this.updateSession({ title });
861
+ } catch {
862
+ }
863
+ }
864
+ isDefaultTitle() {
865
+ const parts = this.session.cwd.split(/[\\/]/).filter((part) => part.length > 0);
866
+ return this.session.title === (parts.at(-1) ?? "session");
867
+ }
656
868
  async compact() {
657
869
  const result = compactMessages(this.messages, {
658
870
  contextWindow: this.modelInfo.contextWindow,
@@ -661,19 +873,28 @@ var Agent = class {
661
873
  this.options.store?.replaceMessages(this.session.id, this.messages);
662
874
  return result;
663
875
  }
664
- async finish(text, stopReason, emit) {
876
+ async finish(text, stopReason, emit, startedAt) {
665
877
  this.updateSession({
666
878
  status: "idle",
667
879
  tokens: this.usage,
668
880
  cost: this.cost,
669
881
  metadata: { ...this.session.metadata, todos: this.getTodos() }
670
882
  });
883
+ if (!this.titleGenerated && this.options.smallModel && this.isDefaultTitle()) {
884
+ this.titleGenerated = true;
885
+ const firstPrompt = this.messages.find((message) => message.role === "user")?.content;
886
+ if (firstPrompt) void this.generateTitle(firstPrompt);
887
+ }
671
888
  await emit({
672
889
  type: "turn.end",
673
890
  stopReason,
674
891
  usage: this.usage,
675
- cost: this.cost
892
+ cost: this.cost,
893
+ toolCalls: this.totalToolCalls,
894
+ retries: this.retries,
895
+ durationMs: Date.now() - startedAt
676
896
  });
897
+ await emit({ type: "turn.phase", phase: "idle" });
677
898
  return this.result(text, stopReason);
678
899
  }
679
900
  result(text, stopReason) {
@@ -709,6 +930,7 @@ var Agent = class {
709
930
  };
710
931
  if (!shouldCompact(this.messages, options)) return;
711
932
  const tokensBefore = estimateMessagesTokens(this.messages);
933
+ await emit({ type: "turn.phase", phase: "compacting", detail: `${tokensBefore} tokens` });
712
934
  await emit({ type: "compaction.started", reason: "auto", tokensBefore });
713
935
  const result = compactMessages(this.messages, options);
714
936
  this.messages = result.messages;
@@ -782,6 +1004,7 @@ var Agent = class {
782
1004
  let text = "";
783
1005
  const calls = [];
784
1006
  const active = /* @__PURE__ */ new Map();
1007
+ let reasoning = false;
785
1008
  for await (const event of stream) {
786
1009
  switch (event.type) {
787
1010
  case "text-delta": {
@@ -789,15 +1012,29 @@ var Agent = class {
789
1012
  await emit({ type: "assistant.text", text: event.text });
790
1013
  break;
791
1014
  }
792
- case "reasoning-delta":
1015
+ case "reasoning-delta": {
1016
+ reasoning = true;
1017
+ await emit({ type: "assistant.reasoning", text: event.text });
793
1018
  break;
1019
+ }
794
1020
  case "tool-call-start": {
795
1021
  active.set(event.callID, { name: event.tool, args: "" });
1022
+ await emit({
1023
+ type: "tool.call.start",
1024
+ call: { id: event.callID, name: event.tool, input: {} }
1025
+ });
796
1026
  break;
797
1027
  }
798
1028
  case "tool-call-delta": {
799
1029
  const entry = active.get(event.callID);
800
- if (entry) entry.args += event.argsDelta;
1030
+ if (entry) {
1031
+ entry.args += event.argsDelta;
1032
+ await emit({
1033
+ type: "tool.call.delta",
1034
+ callID: event.callID,
1035
+ argsDelta: event.argsDelta
1036
+ });
1037
+ }
801
1038
  break;
802
1039
  }
803
1040
  case "tool-call-end": {
@@ -828,12 +1065,13 @@ var Agent = class {
828
1065
  for (const [callID, entry] of active) {
829
1066
  calls.push({ id: callID, name: entry.name, input: parseToolInput(entry.args) });
830
1067
  }
1068
+ if (reasoning) await emit({ type: "assistant.reasoning.end" });
831
1069
  return { text, calls };
832
1070
  }
833
1071
  async executeCalls(calls, signal, emit) {
834
1072
  const isParallelizable = (call) => {
835
1073
  const tool = this.options.tools.get(call.name);
836
- return tool?.readOnly === true && tool.parallelizable === true;
1074
+ return tool?.readOnly === true && tool.parallelizable === true || tool?.concurrent === true;
837
1075
  };
838
1076
  const serial = calls.filter((call) => !isParallelizable(call));
839
1077
  const parallel = calls.filter((call) => isParallelizable(call));
@@ -857,35 +1095,35 @@ var Agent = class {
857
1095
  call
858
1096
  });
859
1097
  if (before === "block") {
860
- const output = {
1098
+ const output2 = {
861
1099
  kind: "text",
862
1100
  text: `Tool ${call.name} was blocked by a plugin.`
863
1101
  };
864
1102
  const durationMs = Date.now() - startedAt;
865
- await this.emitResult(call, output, "deny", durationMs, emit);
866
- return { call, output, decision: "deny", durationMs };
1103
+ await this.emitResult(call, output2, "deny", durationMs, emit);
1104
+ return { call, output: output2, decision: "deny", durationMs };
867
1105
  }
868
1106
  if (before) call = before;
869
1107
  const tool = this.options.tools.get(call.name);
870
1108
  if (!tool) {
871
- const output = {
1109
+ const output2 = {
872
1110
  kind: "text",
873
1111
  text: `Unknown tool: ${call.name}. Use one of the registered tools.`
874
1112
  };
875
1113
  const durationMs = Date.now() - startedAt;
876
- await this.emitResult(call, output, "allow", durationMs, emit);
877
- return { call, output, decision: "allow", durationMs };
1114
+ await this.emitResult(call, output2, "allow", durationMs, emit);
1115
+ return { call, output: output2, decision: "allow", durationMs };
878
1116
  }
879
1117
  const parsed = tool.input.safeParse(call.input);
880
1118
  if (!parsed.success) {
881
1119
  const issues = parsed.error.issues.map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`).join("; ");
882
- const output = {
1120
+ const output2 = {
883
1121
  kind: "text",
884
1122
  text: `Invalid input for ${call.name}: ${issues}`
885
1123
  };
886
1124
  const durationMs = Date.now() - startedAt;
887
- await this.emitResult(call, output, "allow", durationMs, emit);
888
- return { call, output, decision: "allow", durationMs };
1125
+ await this.emitResult(call, output2, "allow", durationMs, emit);
1126
+ return { call, output: output2, decision: "allow", durationMs };
889
1127
  }
890
1128
  let decision = this.options.permissions.decide({
891
1129
  tool: call.name,
@@ -901,8 +1139,10 @@ var Agent = class {
901
1139
  input: parsed.data,
902
1140
  reason: `The model wants to use ${call.name}.`
903
1141
  };
1142
+ await emit({ type: "turn.phase", phase: "waiting_permission", detail: call.name });
904
1143
  await emit({ type: "permission.requested", requestID, request });
905
1144
  decision = await this.options.askPermission(request, requestID);
1145
+ await emit({ type: "turn.phase", phase: "tool", detail: call.name });
906
1146
  }
907
1147
  this.options.audit?.record({
908
1148
  sessionID: this.session.id,
@@ -914,14 +1154,14 @@ var Agent = class {
914
1154
  });
915
1155
  if (decision !== "allow") {
916
1156
  const reason = decision === "deny" ? `Permission denied for ${call.name} in ${this.options.permissions.mode} mode.` : `Permission approval required for ${call.name}.`;
917
- const output = { kind: "text", text: reason };
1157
+ const output2 = { kind: "text", text: reason };
918
1158
  await emit({ type: "permission.denied", call, reason });
919
1159
  const durationMs = Date.now() - startedAt;
920
- await this.emitResult(call, output, decision, durationMs, emit);
921
- return { call, output, decision, durationMs };
1160
+ await this.emitResult(call, output2, decision, durationMs, emit);
1161
+ return { call, output: output2, decision, durationMs };
922
1162
  }
923
1163
  try {
924
- const output = await withTimeout(
1164
+ const output2 = await withTimeout(
925
1165
  tool.execute(parsed.data, {
926
1166
  sessionID: this.session.id,
927
1167
  cwd: this.options.cwd,
@@ -933,7 +1173,12 @@ var Agent = class {
933
1173
  lsp: this.options.lsp,
934
1174
  checkpoint: this.options.checkpoints ? (path) => {
935
1175
  this.options.checkpoints?.snapshot(this.session.id, path);
936
- } : void 0
1176
+ } : void 0,
1177
+ snapshot: this.options.checkpoints ? async (path) => this.options.checkpoints?.snapshot(this.session.id, path)?.hash : void 0,
1178
+ restore: this.options.checkpoints ? async (hash) => this.options.checkpoints?.restore(this.session.id, hash) ?? 0 : void 0,
1179
+ askUser: this.options.askUser,
1180
+ shells: this.shells,
1181
+ spawnSubagent: this.options.isSubagent ? void 0 : (request) => this.runSubagent(request)
937
1182
  }),
938
1183
  tool.timeoutMs ?? 12e4,
939
1184
  signal
@@ -941,28 +1186,28 @@ var Agent = class {
941
1186
  const finalOutput = await this.options.plugins?.toolAfter({
942
1187
  sessionID: this.session.id,
943
1188
  call,
944
- output
945
- }) ?? output;
1189
+ output: output2
1190
+ }) ?? output2;
946
1191
  const durationMs = Date.now() - startedAt;
947
1192
  await this.emitResult(call, finalOutput, decision, durationMs, emit);
948
1193
  return { call, output: finalOutput, decision, durationMs };
949
1194
  } catch (error) {
950
1195
  const kilncraftError = toKilncraftError(error);
951
- const output = {
1196
+ const output2 = {
952
1197
  kind: "text",
953
1198
  text: `Tool ${call.name} failed: ${kilncraftError.message}`
954
1199
  };
955
1200
  const durationMs = Date.now() - startedAt;
956
- await this.emitResult(call, output, "deny", durationMs, emit);
957
- return { call, output, decision: "deny", durationMs };
1201
+ await this.emitResult(call, output2, "deny", durationMs, emit);
1202
+ return { call, output: output2, decision: "deny", durationMs };
958
1203
  }
959
1204
  }
960
- async emitResult(call, output, decision, durationMs, emit) {
1205
+ async emitResult(call, output2, decision, durationMs, emit) {
961
1206
  await emit({
962
1207
  type: "tool.result",
963
1208
  callID: call.id,
964
1209
  tool: call.name,
965
- output,
1210
+ output: output2,
966
1211
  decision,
967
1212
  durationMs
968
1213
  });
@@ -981,19 +1226,17 @@ var READ_ONLY_TOOLS = /* @__PURE__ */ new Set([
981
1226
  "lsp_references",
982
1227
  "git_status",
983
1228
  "git_diff",
984
- "git_log"
985
- ]);
986
- var WRITE_TOOLS = /* @__PURE__ */ new Set([
987
- "write",
988
- "edit",
989
- "multi_edit",
990
- "apply_patch",
991
- "notebook_edit",
992
- "memory_write",
993
- "git_commit",
994
- "git_branch",
995
- "worktree_create"
1229
+ "git_log",
1230
+ "webfetch",
1231
+ "websearch",
1232
+ "fetch",
1233
+ "view_image",
1234
+ "skill_load",
1235
+ "snapshot",
1236
+ "ask_user",
1237
+ "bash_output"
996
1238
  ]);
1239
+ var WRITE_TOOLS = /* @__PURE__ */ new Set(["write", "edit", "multi_edit", "apply_patch", "notebook_edit"]);
997
1240
  var DANGEROUS_PATTERNS = [
998
1241
  /rm\s+-[rf]{1,2}\s+\/(?:\s|$)/,
999
1242
  /\bmkfs(?:\.\w+)?\b/,
@@ -1134,20 +1377,20 @@ var PluginHost = class {
1134
1377
  return call;
1135
1378
  }
1136
1379
  async toolAfter(payload) {
1137
- let output;
1380
+ let output2;
1138
1381
  for (const plugin of this.plugins) {
1139
1382
  try {
1140
1383
  const result = await plugin.hooks?.["tool.after"]?.(this.context, {
1141
1384
  sessionID: payload.sessionID,
1142
1385
  call: payload.call,
1143
- output: output ?? payload.output
1386
+ output: output2 ?? payload.output
1144
1387
  });
1145
- if (result) output = result;
1388
+ if (result) output2 = result;
1146
1389
  } catch (error) {
1147
1390
  this.context.logger.warn({ err: error, plugin: plugin.id }, "tool.after hook failed");
1148
1391
  }
1149
1392
  }
1150
- return output;
1393
+ return output2;
1151
1394
  }
1152
1395
  async emit(event) {
1153
1396
  for (const plugin of this.plugins) {
@@ -1368,11 +1611,21 @@ var AnthropicProvider = class {
1368
1611
  async *stream(request) {
1369
1612
  const usage = emptyUsage();
1370
1613
  let stopReason = "stop";
1614
+ const thinkingBudget = request.reasoningEffort ? { low: 1024, medium: 4096, high: 8192 }[request.reasoningEffort] : void 0;
1371
1615
  const body = {
1372
1616
  model: request.model,
1373
- max_tokens: request.maxTokens ?? 8192,
1617
+ max_tokens: Math.max(request.maxTokens ?? 8192, (thinkingBudget ?? 0) + 1024),
1374
1618
  stream: true,
1375
- ...request.system ? { system: request.system } : {},
1619
+ ...request.system ? {
1620
+ system: request.promptCache ? [
1621
+ {
1622
+ type: "text",
1623
+ text: request.system,
1624
+ cache_control: { type: "ephemeral" }
1625
+ }
1626
+ ] : request.system
1627
+ } : {},
1628
+ ...thinkingBudget ? { thinking: { type: "enabled", budget_tokens: thinkingBudget } } : {},
1376
1629
  ...request.temperature !== void 0 ? { temperature: request.temperature } : {},
1377
1630
  messages: toAnthropicMessages(request.messages),
1378
1631
  ...request.tools && request.tools.length > 0 ? {
@@ -1599,7 +1852,12 @@ var GeminiProvider = class {
1599
1852
  } : {},
1600
1853
  generationConfig: {
1601
1854
  maxOutputTokens: request.maxTokens ?? 8192,
1602
- ...request.temperature !== void 0 ? { temperature: request.temperature } : {}
1855
+ ...request.temperature !== void 0 ? { temperature: request.temperature } : {},
1856
+ ...request.reasoningEffort ? {
1857
+ thinkingConfig: {
1858
+ thinkingBudget: { low: 1024, medium: 4096, high: 8192 }[request.reasoningEffort]
1859
+ }
1860
+ } : {}
1603
1861
  }
1604
1862
  };
1605
1863
  const response = await openSse(
@@ -1623,7 +1881,11 @@ var GeminiProvider = class {
1623
1881
  if (candidate?.finishReason) finishReason = candidate.finishReason;
1624
1882
  for (const part of candidate?.content?.parts ?? []) {
1625
1883
  if (typeof part.text === "string" && part.text.length > 0) {
1626
- yield { type: "text-delta", text: part.text };
1884
+ if (part.thought === true) {
1885
+ yield { type: "reasoning-delta", text: part.text };
1886
+ } else {
1887
+ yield { type: "text-delta", text: part.text };
1888
+ }
1627
1889
  }
1628
1890
  if (part.functionCall?.name) {
1629
1891
  const callID = `gemini_${Date.now().toString(36)}_${callCounter++}`;
@@ -1716,6 +1978,7 @@ var OpenAIProvider = class {
1716
1978
  const usage = emptyUsage();
1717
1979
  const pending = /* @__PURE__ */ new Map();
1718
1980
  let finishReason = "stop";
1981
+ const reasoningModel = /^(gpt-5|o1|o3|o4)/.test(request.model.toLowerCase());
1719
1982
  const body = {
1720
1983
  model: request.model,
1721
1984
  messages: toOpenAIMessages(request.messages),
@@ -1735,6 +1998,7 @@ var OpenAIProvider = class {
1735
1998
  ...request.maxTokens !== void 0 ? {
1736
1999
  [/^(gpt-5|o1|o3|o4)/.test(request.model.toLowerCase()) ? "max_completion_tokens" : "max_tokens"]: request.maxTokens
1737
2000
  } : {},
2001
+ ...request.reasoningEffort && reasoningModel ? { reasoning_effort: request.reasoningEffort } : {},
1738
2002
  ...request.temperature !== void 0 ? { temperature: request.temperature } : {}
1739
2003
  };
1740
2004
  const response = await openSse(
@@ -1757,6 +2021,11 @@ var OpenAIProvider = class {
1757
2021
  const choice = chunk.choices?.[0];
1758
2022
  if (choice?.finish_reason) finishReason = choice.finish_reason;
1759
2023
  const delta = choice?.delta;
2024
+ if (delta?.reasoning_content) {
2025
+ yield { type: "reasoning-delta", text: delta.reasoning_content };
2026
+ } else if (delta?.reasoning) {
2027
+ yield { type: "reasoning-delta", text: delta.reasoning };
2028
+ }
1760
2029
  if (delta?.content) {
1761
2030
  yield { type: "text-delta", text: delta.content };
1762
2031
  }
@@ -2350,9 +2619,10 @@ function writeSessionFile(store, sessionID, filename, contents) {
2350
2619
  var bashInput = z.object({
2351
2620
  command: z.string().min(1).describe("Shell command to execute"),
2352
2621
  cwd: z.string().optional().describe("Working directory (defaults to the workspace root)"),
2353
- timeout: z.number().int().positive().max(6e5).optional().describe("Timeout in milliseconds")
2622
+ timeout: z.number().int().positive().max(6e5).optional().describe("Timeout in milliseconds"),
2623
+ background: z.boolean().optional().describe("Run in the background and return a shell id")
2354
2624
  });
2355
- var OUTPUT_LIMIT = 3e4;
2625
+ var OUTPUT_LIMIT2 = 3e4;
2356
2626
  var ALLOWED_ENV = /* @__PURE__ */ new Set([
2357
2627
  "PATH",
2358
2628
  "HOME",
@@ -2393,6 +2663,47 @@ function killProcessTree(child) {
2393
2663
  }
2394
2664
  }, 1e3).unref();
2395
2665
  }
2666
+ var outputInput = z.object({
2667
+ shellID: z.string().min(1)
2668
+ });
2669
+ var killInput = z.object({
2670
+ shellID: z.string().min(1)
2671
+ });
2672
+ var bashOutputTool = {
2673
+ id: "bash_output",
2674
+ description: "Read output from a background shell started by bash --background.",
2675
+ input: outputInput,
2676
+ readOnly: true,
2677
+ parallelizable: true,
2678
+ defaultDecision: "allow",
2679
+ timeoutMs: 5e3,
2680
+ async execute(input, context) {
2681
+ const output2 = context.shells?.output(input.shellID);
2682
+ if (!output2) return { kind: "text", text: `Unknown background shell ${input.shellID}.` };
2683
+ return {
2684
+ kind: "terminal",
2685
+ stdout: output2.stdout,
2686
+ stderr: output2.stderr,
2687
+ exitCode: output2.exitCode
2688
+ };
2689
+ }
2690
+ };
2691
+ var killShellTool = {
2692
+ id: "kill_shell",
2693
+ description: "Terminate a background shell started by bash --background.",
2694
+ input: killInput,
2695
+ readOnly: false,
2696
+ parallelizable: false,
2697
+ defaultDecision: "ask",
2698
+ timeoutMs: 5e3,
2699
+ async execute(input, context) {
2700
+ const killed = context.shells?.kill(input.shellID) ?? false;
2701
+ return {
2702
+ kind: "text",
2703
+ text: killed ? `Killed ${input.shellID}` : `Unknown shell ${input.shellID}`
2704
+ };
2705
+ }
2706
+ };
2396
2707
  var bashTool = {
2397
2708
  id: "bash",
2398
2709
  description: "Run a shell command in the workspace. Output is streamed and truncated at 30k characters per stream.",
@@ -2410,6 +2721,19 @@ var bashTool = {
2410
2721
  const wrapped = context.sandbox?.wrap(input.command, { cwd });
2411
2722
  const command = wrapped?.command ?? shell;
2412
2723
  const args = wrapped?.args ?? fallbackArgs;
2724
+ if (input.background) {
2725
+ if (!context.shells) {
2726
+ return { kind: "text", text: "Background shells are not available in this session." };
2727
+ }
2728
+ if (context.sandbox) {
2729
+ return {
2730
+ kind: "text",
2731
+ text: "Background shells cannot be sandboxed; run the command in the foreground or disable the sandbox."
2732
+ };
2733
+ }
2734
+ const id = context.shells.start(input.command, cwd, sanitizedEnvironment());
2735
+ return { kind: "text", text: `Started background shell ${id}` };
2736
+ }
2413
2737
  return new Promise((resolve6, reject) => {
2414
2738
  const child = spawn(command, args, {
2415
2739
  cwd,
@@ -2422,14 +2746,14 @@ var bashTool = {
2422
2746
  let stdoutTruncated = false;
2423
2747
  let stderrTruncated = false;
2424
2748
  child.stdout?.on("data", (chunk) => {
2425
- if (stdout.length >= OUTPUT_LIMIT) {
2749
+ if (stdout.length >= OUTPUT_LIMIT2) {
2426
2750
  stdoutTruncated = true;
2427
2751
  return;
2428
2752
  }
2429
2753
  stdout += chunk.toString("utf8");
2430
2754
  });
2431
2755
  child.stderr?.on("data", (chunk) => {
2432
- if (stderr.length >= OUTPUT_LIMIT) {
2756
+ if (stderr.length >= OUTPUT_LIMIT2) {
2433
2757
  stderrTruncated = true;
2434
2758
  return;
2435
2759
  }
@@ -2669,8 +2993,8 @@ var lsInput = z.object({
2669
2993
  path: z.string().optional().describe("Directory to list (defaults to the workspace root)"),
2670
2994
  depth: z.number().int().min(1).max(5).optional().describe("Maximum directory depth (default 2)")
2671
2995
  });
2672
- async function listDirectory(root, directory, prefix, remainingDepth, output) {
2673
- if (output.length >= 500) return;
2996
+ async function listDirectory(root, directory, prefix, remainingDepth, output2) {
2997
+ if (output2.length >= 500) return;
2674
2998
  let entries;
2675
2999
  try {
2676
3000
  entries = await readdir(directory, { withFileTypes: true });
@@ -2680,20 +3004,20 @@ async function listDirectory(root, directory, prefix, remainingDepth, output) {
2680
3004
  entries.sort((left, right) => left.name.localeCompare(right.name));
2681
3005
  for (const entry of entries) {
2682
3006
  if (DEFAULT_IGNORE.has(entry.name)) continue;
2683
- if (output.length >= 500) return;
3007
+ if (output2.length >= 500) return;
2684
3008
  if (entry.isDirectory()) {
2685
- output.push(`${prefix}${entry.name}/`);
3009
+ output2.push(`${prefix}${entry.name}/`);
2686
3010
  if (remainingDepth > 1) {
2687
3011
  await listDirectory(
2688
3012
  root,
2689
3013
  join(directory, entry.name),
2690
3014
  `${prefix} `,
2691
3015
  remainingDepth - 1,
2692
- output
3016
+ output2
2693
3017
  );
2694
3018
  }
2695
3019
  } else if (entry.isFile()) {
2696
- output.push(`${prefix}${entry.name}`);
3020
+ output2.push(`${prefix}${entry.name}`);
2697
3021
  }
2698
3022
  }
2699
3023
  }
@@ -2708,14 +3032,14 @@ var lsTool = {
2708
3032
  const root = input.path ? resolveWorkspacePath(context.cwd, input.path) : context.cwd;
2709
3033
  assertInsideWorkspace(context.cwd, root);
2710
3034
  await assertRealInside(context.cwd, root);
2711
- const output = [];
2712
- await listDirectory(root, root, "", (input.depth ?? 2) + 1, output);
2713
- if (output.length === 0) {
3035
+ const output2 = [];
3036
+ await listDirectory(root, root, "", (input.depth ?? 2) + 1, output2);
3037
+ if (output2.length === 0) {
2714
3038
  return { kind: "text", text: "(empty directory)" };
2715
3039
  }
2716
- const body = output.join("\n");
3040
+ const body = output2.join("\n");
2717
3041
  const result = truncateText(body, 3e4);
2718
- const notice = output.length >= 500 ? `
3042
+ const notice = output2.length >= 500 ? `
2719
3043
 
2720
3044
  [showing first 500 entries]` : "";
2721
3045
  return { kind: "text", text: `${result.text}${notice}` };
@@ -2733,6 +3057,81 @@ function formatDiagnostics(path, diagnostics) {
2733
3057
  return `${path}:${line}:${character} ${severity(diagnostic.severity)} ${diagnostic.message}`;
2734
3058
  }).join("\n");
2735
3059
  }
3060
+ var positionInput = z.object({
3061
+ path: z.string().min(1).describe("File path"),
3062
+ line: z.number().int().nonnegative().describe("Zero-based line"),
3063
+ character: z.number().int().nonnegative().describe("Zero-based character")
3064
+ });
3065
+ var lspDefinitionTool = {
3066
+ id: "lsp_definition",
3067
+ description: "Find the definition of the symbol at a position.",
3068
+ input: positionInput,
3069
+ readOnly: true,
3070
+ parallelizable: false,
3071
+ defaultDecision: "allow",
3072
+ timeoutMs: 3e4,
3073
+ async execute(input, context) {
3074
+ if (!context.lsp?.definitionFor) {
3075
+ return { kind: "text", text: "LSP definition is not available for this session." };
3076
+ }
3077
+ const fullPath = resolveWorkspacePath(context.cwd, input.path);
3078
+ assertInsideWorkspace(context.cwd, fullPath);
3079
+ await assertRealInside(context.cwd, fullPath);
3080
+ const locations = await context.lsp.definitionFor(fullPath, input.line, input.character);
3081
+ return {
3082
+ kind: "text",
3083
+ text: locations.length > 0 ? locations.map(
3084
+ (location) => `${location.uri}:${location.range.start.line + 1}:${location.range.start.character + 1}`
3085
+ ).join("\n") : `No definition for ${input.path}:${input.line + 1}:${input.character + 1}.`
3086
+ };
3087
+ }
3088
+ };
3089
+ var lspHoverTool = {
3090
+ id: "lsp_hover",
3091
+ description: "Show hover information for the symbol at a position.",
3092
+ input: positionInput,
3093
+ readOnly: true,
3094
+ parallelizable: false,
3095
+ defaultDecision: "allow",
3096
+ timeoutMs: 3e4,
3097
+ async execute(input, context) {
3098
+ if (!context.lsp?.hoverFor) {
3099
+ return { kind: "text", text: "LSP hover is not available for this session." };
3100
+ }
3101
+ const fullPath = resolveWorkspacePath(context.cwd, input.path);
3102
+ assertInsideWorkspace(context.cwd, fullPath);
3103
+ await assertRealInside(context.cwd, fullPath);
3104
+ const text = await context.lsp.hoverFor(fullPath, input.line, input.character);
3105
+ return {
3106
+ kind: "text",
3107
+ text: text ?? `No hover information for ${input.path}:${input.line + 1}:${input.character + 1}.`
3108
+ };
3109
+ }
3110
+ };
3111
+ var lspReferencesTool = {
3112
+ id: "lsp_references",
3113
+ description: "Find references to the symbol at a position.",
3114
+ input: positionInput,
3115
+ readOnly: true,
3116
+ parallelizable: false,
3117
+ defaultDecision: "allow",
3118
+ timeoutMs: 3e4,
3119
+ async execute(input, context) {
3120
+ if (!context.lsp?.referencesFor) {
3121
+ return { kind: "text", text: "LSP references are not available for this session." };
3122
+ }
3123
+ const fullPath = resolveWorkspacePath(context.cwd, input.path);
3124
+ assertInsideWorkspace(context.cwd, fullPath);
3125
+ await assertRealInside(context.cwd, fullPath);
3126
+ const locations = await context.lsp.referencesFor(fullPath, input.line, input.character);
3127
+ return {
3128
+ kind: "text",
3129
+ text: locations.length > 0 ? locations.map(
3130
+ (location) => `${location.uri}:${location.range.start.line + 1}:${location.range.start.character + 1}`
3131
+ ).join("\n") : `No references for ${input.path}:${input.line + 1}:${input.character + 1}.`
3132
+ };
3133
+ }
3134
+ };
2736
3135
  var lspDiagnosticsTool = {
2737
3136
  id: "lsp_diagnostics",
2738
3137
  description: "Return language-server diagnostics for a file. Requires an LSP server for the file type.",
@@ -2818,6 +3217,655 @@ var readTool = {
2818
3217
  return { kind: "text", text: `${result.text}${notice}` };
2819
3218
  }
2820
3219
  };
3220
+ var patchInput = z.object({
3221
+ patch: z.string().min(1).describe("Patch text in *** Begin Patch or unified diff format")
3222
+ });
3223
+ function parseBeginPatch(patch) {
3224
+ const lines = patch.split("\n");
3225
+ const files = [];
3226
+ let current;
3227
+ let hunk;
3228
+ const flushHunk = () => {
3229
+ if (current && hunk) current.hunks.push(hunk);
3230
+ hunk = void 0;
3231
+ };
3232
+ for (const line of lines) {
3233
+ if (line.startsWith("*** Update File:")) {
3234
+ flushHunk();
3235
+ current = {
3236
+ path: line.slice("*** Update File:".length).trim(),
3237
+ operation: "update",
3238
+ hunks: []
3239
+ };
3240
+ files.push(current);
3241
+ continue;
3242
+ }
3243
+ if (line.startsWith("*** Add File:")) {
3244
+ flushHunk();
3245
+ current = {
3246
+ path: line.slice("*** Add File:".length).trim(),
3247
+ operation: "add",
3248
+ hunks: [],
3249
+ addLines: []
3250
+ };
3251
+ files.push(current);
3252
+ continue;
3253
+ }
3254
+ if (line.startsWith("*** Delete File:")) {
3255
+ flushHunk();
3256
+ current = {
3257
+ path: line.slice("*** Delete File:".length).trim(),
3258
+ operation: "delete",
3259
+ hunks: []
3260
+ };
3261
+ files.push(current);
3262
+ continue;
3263
+ }
3264
+ if (!current) continue;
3265
+ if (line.startsWith("@@")) {
3266
+ flushHunk();
3267
+ hunk = { oldLines: [], newLines: [] };
3268
+ continue;
3269
+ }
3270
+ if (current.operation === "add" && current.addLines) {
3271
+ if (line.startsWith("+")) current.addLines.push(line.slice(1));
3272
+ continue;
3273
+ }
3274
+ if (!hunk) continue;
3275
+ if (line.startsWith("-")) hunk.oldLines.push(line.slice(1));
3276
+ else if (line.startsWith("+")) hunk.newLines.push(line.slice(1));
3277
+ else if (line.startsWith(" ")) {
3278
+ hunk.oldLines.push(line.slice(1));
3279
+ hunk.newLines.push(line.slice(1));
3280
+ }
3281
+ }
3282
+ flushHunk();
3283
+ return files;
3284
+ }
3285
+ function parseUnifiedDiff(patch, cwd) {
3286
+ const lines = patch.split("\n");
3287
+ const files = [];
3288
+ let current;
3289
+ let hunk;
3290
+ for (const line of lines) {
3291
+ if (line.startsWith("+++ ")) {
3292
+ const raw = line.slice(4).trim();
3293
+ const path = raw.replace(/^b\//, "");
3294
+ current = {
3295
+ path,
3296
+ operation: existsSync(resolveWorkspacePath(cwd, path)) ? "update" : "add",
3297
+ hunks: []
3298
+ };
3299
+ if (current.operation === "add") current.addLines = [];
3300
+ files.push(current);
3301
+ continue;
3302
+ }
3303
+ if (!current) continue;
3304
+ if (line.startsWith("@@")) {
3305
+ hunk = { oldLines: [], newLines: [] };
3306
+ current.hunks.push(hunk);
3307
+ continue;
3308
+ }
3309
+ if (!hunk) continue;
3310
+ if (line.startsWith("-")) hunk.oldLines.push(line.slice(1));
3311
+ else if (line.startsWith("+")) {
3312
+ if (current.operation === "add" && current.addLines && current.hunks.length === 0) {
3313
+ current.addLines.push(line.slice(1));
3314
+ } else {
3315
+ hunk.newLines.push(line.slice(1));
3316
+ }
3317
+ } else if (line.startsWith(" ")) {
3318
+ hunk.oldLines.push(line.slice(1));
3319
+ hunk.newLines.push(line.slice(1));
3320
+ }
3321
+ }
3322
+ return files;
3323
+ }
3324
+ function applyHunks(content, hunks) {
3325
+ let result = content;
3326
+ for (const hunk of hunks) {
3327
+ const oldText = hunk.oldLines.join("\n");
3328
+ const newText = hunk.newLines.join("\n");
3329
+ const index = result.indexOf(oldText);
3330
+ if (index < 0) return void 0;
3331
+ result = `${result.slice(0, index)}${newText}${result.slice(index + oldText.length)}`;
3332
+ }
3333
+ return result;
3334
+ }
3335
+ var applyPatchTool = {
3336
+ id: "apply_patch",
3337
+ description: "Apply a patch in *** Begin Patch format or unified diff format. Supports update/add/delete file blocks.",
3338
+ input: patchInput,
3339
+ readOnly: false,
3340
+ parallelizable: false,
3341
+ defaultDecision: "ask",
3342
+ timeoutMs: 3e4,
3343
+ async execute(input, context) {
3344
+ const trimmed = input.patch.trim();
3345
+ if (trimmed.length === 0) return { kind: "text", text: "Patch is empty." };
3346
+ const patches = trimmed.startsWith("*** Begin Patch") ? parseBeginPatch(trimmed) : parseUnifiedDiff(trimmed, context.cwd);
3347
+ if (patches.length === 0)
3348
+ return { kind: "text", text: "Could not parse any file in the patch." };
3349
+ const diffs = [];
3350
+ const files = [];
3351
+ for (const patch of patches) {
3352
+ const fullPath = resolveWorkspacePath(context.cwd, patch.path);
3353
+ assertInsideWorkspace(context.cwd, fullPath);
3354
+ await assertRealInside(context.cwd, fullPath);
3355
+ if (patch.operation === "add") {
3356
+ const content = (patch.addLines ?? patch.hunks.flatMap((hunk) => hunk.newLines)).join("\n");
3357
+ if (!content.endsWith("\n")) ;
3358
+ await context.checkpoint?.(fullPath);
3359
+ await atomicWrite(fullPath, content);
3360
+ diffs.push(diffText(patch.path, "", content));
3361
+ files.push({ path: patch.path, status: "added" });
3362
+ continue;
3363
+ }
3364
+ if (patch.operation === "delete") {
3365
+ const before2 = existsSync(fullPath) ? await readTextFile(fullPath) : "";
3366
+ await context.checkpoint?.(fullPath);
3367
+ await rm(fullPath, { force: true });
3368
+ diffs.push(diffText(patch.path, before2, ""));
3369
+ files.push({ path: patch.path, status: "removed" });
3370
+ continue;
3371
+ }
3372
+ const before = await readTextFile(fullPath);
3373
+ const after = applyHunks(before, patch.hunks);
3374
+ if (after === void 0) {
3375
+ return {
3376
+ kind: "text",
3377
+ text: `Patch context did not match ${patch.path}; nothing was written.`
3378
+ };
3379
+ }
3380
+ await context.checkpoint?.(fullPath);
3381
+ await atomicWrite(fullPath, after);
3382
+ diffs.push(diffText(patch.path, before, after));
3383
+ files.push({ path: patch.path, status: "modified" });
3384
+ }
3385
+ return { kind: "diff", diff: diffs.join("\n"), files };
3386
+ }
3387
+ };
3388
+ var askInput = z.object({
3389
+ question: z.string().min(1),
3390
+ options: z.array(z.string()).optional().describe("Suggested answers")
3391
+ });
3392
+ var askUserTool = {
3393
+ id: "ask_user",
3394
+ description: "Ask the user a clarifying question. Blocks until an answer is available when the host supports it.",
3395
+ input: askInput,
3396
+ readOnly: true,
3397
+ parallelizable: false,
3398
+ defaultDecision: "allow",
3399
+ timeoutMs: 6e5,
3400
+ async execute(input, context) {
3401
+ if (context.askUser) {
3402
+ const answer = await context.askUser({ question: input.question, options: input.options });
3403
+ return { kind: "text", text: answer ?? input.question };
3404
+ }
3405
+ const options = input.options?.length ? `
3406
+ Options: ${input.options.join(", ")}` : "";
3407
+ return {
3408
+ kind: "text",
3409
+ text: `The host cannot ask interactively. Question: ${input.question}${options}`
3410
+ };
3411
+ }
3412
+ };
3413
+ var run = promisify(execFile);
3414
+ async function git(args, cwd) {
3415
+ try {
3416
+ const { stdout, stderr } = await run("git", args, {
3417
+ cwd,
3418
+ maxBuffer: 4 * 1024 * 1024,
3419
+ timeout: 3e4
3420
+ });
3421
+ return { stdout, stderr, code: 0 };
3422
+ } catch (error) {
3423
+ const failure = error;
3424
+ return {
3425
+ stdout: failure.stdout ?? "",
3426
+ stderr: failure.stderr ?? String(error),
3427
+ code: typeof failure.code === "number" ? failure.code : 1
3428
+ };
3429
+ }
3430
+ }
3431
+ function output(result) {
3432
+ return {
3433
+ kind: "terminal",
3434
+ stdout: result.stdout,
3435
+ stderr: result.stderr,
3436
+ exitCode: result.code
3437
+ };
3438
+ }
3439
+ var statusInput = z.object({});
3440
+ var diffInput = z.object({
3441
+ path: z.string().optional(),
3442
+ staged: z.boolean().optional(),
3443
+ stat: z.boolean().optional()
3444
+ });
3445
+ var logInput = z.object({ limit: z.number().int().positive().max(200).optional() });
3446
+ var commitInput = z.object({
3447
+ message: z.string().min(1),
3448
+ all: z.boolean().optional(),
3449
+ signoff: z.boolean().optional()
3450
+ });
3451
+ var branchInput = z.object({
3452
+ name: z.string().optional(),
3453
+ create: z.boolean().optional()
3454
+ });
3455
+ var worktreeInput = z.object({
3456
+ name: z.string().min(1),
3457
+ branch: z.string().optional(),
3458
+ path: z.string().optional()
3459
+ });
3460
+ var gitStatusTool = {
3461
+ id: "git_status",
3462
+ description: "Show the git working tree status in porcelain format.",
3463
+ input: statusInput,
3464
+ readOnly: true,
3465
+ parallelizable: true,
3466
+ defaultDecision: "allow",
3467
+ timeoutMs: 15e3,
3468
+ async execute(_input, context) {
3469
+ return output(await git(["status", "--porcelain=v1", "-b"], context.cwd));
3470
+ }
3471
+ };
3472
+ var gitDiffTool = {
3473
+ id: "git_diff",
3474
+ description: "Show a git diff for the working tree, staged changes, or a path.",
3475
+ input: diffInput,
3476
+ readOnly: true,
3477
+ parallelizable: true,
3478
+ defaultDecision: "allow",
3479
+ timeoutMs: 15e3,
3480
+ async execute(input, context) {
3481
+ const args = ["diff"];
3482
+ if (input.staged) args.push("--staged");
3483
+ if (input.stat) args.push("--stat");
3484
+ if (input.path) args.push("--", input.path);
3485
+ return output(await git(args, context.cwd));
3486
+ }
3487
+ };
3488
+ var gitLogTool = {
3489
+ id: "git_log",
3490
+ description: "Show recent git history.",
3491
+ input: logInput,
3492
+ readOnly: true,
3493
+ parallelizable: true,
3494
+ defaultDecision: "allow",
3495
+ timeoutMs: 15e3,
3496
+ async execute(input, context) {
3497
+ return output(await git(["log", "--oneline", `-n${input.limit ?? 20}`], context.cwd));
3498
+ }
3499
+ };
3500
+ var gitCommitTool = {
3501
+ id: "git_commit",
3502
+ description: "Stage and create a git commit. Hooks run normally.",
3503
+ input: commitInput,
3504
+ readOnly: false,
3505
+ parallelizable: false,
3506
+ defaultDecision: "ask",
3507
+ timeoutMs: 6e4,
3508
+ async execute(input, context) {
3509
+ if (input.all) await git(["add", "-A"], context.cwd);
3510
+ const args = ["commit", "-m", input.message];
3511
+ if (input.signoff) args.push("--signoff");
3512
+ return output(await git(args, context.cwd));
3513
+ }
3514
+ };
3515
+ var gitBranchTool = {
3516
+ id: "git_branch",
3517
+ description: "List branches, create a branch, or switch branches.",
3518
+ input: branchInput,
3519
+ readOnly: false,
3520
+ parallelizable: false,
3521
+ defaultDecision: "ask",
3522
+ timeoutMs: 15e3,
3523
+ async execute(input, context) {
3524
+ if (!input.name) return output(await git(["branch", "--list"], context.cwd));
3525
+ if (input.create) return output(await git(["checkout", "-b", input.name], context.cwd));
3526
+ return output(await git(["checkout", input.name], context.cwd));
3527
+ }
3528
+ };
3529
+ var worktreeCreateTool = {
3530
+ id: "worktree_create",
3531
+ description: "Create a git worktree with a new branch.",
3532
+ input: worktreeInput,
3533
+ readOnly: false,
3534
+ parallelizable: false,
3535
+ defaultDecision: "ask",
3536
+ timeoutMs: 3e4,
3537
+ async execute(input, context) {
3538
+ const path = input.path ?? join(context.cwd, ".kilncraft", "worktrees", input.name);
3539
+ return output(
3540
+ await git(["worktree", "add", "-b", input.branch ?? input.name, path], context.cwd)
3541
+ );
3542
+ }
3543
+ };
3544
+ var imageInput = z.object({
3545
+ path: z.string().min(1).describe("Path to an image file")
3546
+ });
3547
+ var MIME_BY_EXTENSION = {
3548
+ ".png": "image/png",
3549
+ ".jpg": "image/jpeg",
3550
+ ".jpeg": "image/jpeg",
3551
+ ".gif": "image/gif",
3552
+ ".webp": "image/webp",
3553
+ ".bmp": "image/bmp",
3554
+ ".svg": "image/svg+xml",
3555
+ ".pdf": "application/pdf"
3556
+ };
3557
+ var viewImageTool = {
3558
+ id: "view_image",
3559
+ description: "Read an image (or PDF) and return it as an image output for providers with vision support.",
3560
+ input: imageInput,
3561
+ readOnly: true,
3562
+ parallelizable: true,
3563
+ defaultDecision: "allow",
3564
+ timeoutMs: 15e3,
3565
+ async execute(input, context) {
3566
+ const fullPath = resolveWorkspacePath(context.cwd, input.path);
3567
+ assertInsideWorkspace(context.cwd, fullPath);
3568
+ await assertRealInside(context.cwd, fullPath);
3569
+ try {
3570
+ const mime = MIME_BY_EXTENSION[extname(fullPath).toLowerCase()];
3571
+ if (!mime) {
3572
+ return { kind: "text", text: `Unsupported image type for ${input.path}.` };
3573
+ }
3574
+ const data = await readFile(fullPath);
3575
+ if (data.length > 1e7) {
3576
+ return { kind: "text", text: `${input.path} is too large (${data.length} bytes).` };
3577
+ }
3578
+ return { kind: "image", mime, data: data.toString("base64") };
3579
+ } catch (error) {
3580
+ return {
3581
+ kind: "text",
3582
+ text: `Could not read ${input.path}: ${error instanceof Error ? error.message : String(error)}`
3583
+ };
3584
+ }
3585
+ }
3586
+ };
3587
+ var memoryInput = z.object({
3588
+ scope: z.enum(["user", "project"]).default("project"),
3589
+ name: z.string().min(1).default("memory"),
3590
+ content: z.string().min(1),
3591
+ mode: z.enum(["append", "replace"]).default("append")
3592
+ });
3593
+ var skillInput = z.object({
3594
+ name: z.string().min(1)
3595
+ });
3596
+ function memoryPath(scope, name, cwd) {
3597
+ const safe = name.replace(/[^a-zA-Z0-9_.-]/g, "_");
3598
+ return scope === "user" ? join(homedir(), ".kilncraft", "memory", `${safe}.md`) : join(cwd, ".kilncraft", "memory", `${safe}.md`);
3599
+ }
3600
+ var memoryWriteTool = {
3601
+ id: "memory_write",
3602
+ description: "Append or replace a memory note for the user or project. Exact duplicate lines are skipped.",
3603
+ input: memoryInput,
3604
+ readOnly: false,
3605
+ parallelizable: false,
3606
+ defaultDecision: "ask",
3607
+ timeoutMs: 1e4,
3608
+ async execute(input, context) {
3609
+ const path = memoryPath(input.scope, input.name, context.cwd);
3610
+ let existing = "";
3611
+ try {
3612
+ existing = await readFile(path, "utf8");
3613
+ } catch {
3614
+ existing = "";
3615
+ }
3616
+ let next;
3617
+ if (input.mode === "replace") {
3618
+ next = `${input.content.trim()}
3619
+ `;
3620
+ } else {
3621
+ const seen = new Set(existing.split("\n").map((line) => line.trim()));
3622
+ const additions = input.content.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !seen.has(line));
3623
+ if (additions.length === 0) {
3624
+ return { kind: "text", text: "No new memory lines to add." };
3625
+ }
3626
+ next = `${existing}${existing.endsWith("\n") || existing.length === 0 ? "" : "\n"}${additions.join("\n")}
3627
+ `;
3628
+ }
3629
+ await mkdir(dirname(path), { recursive: true });
3630
+ await writeFile(path, next, "utf8");
3631
+ return { kind: "text", text: `Wrote ${path}` };
3632
+ }
3633
+ };
3634
+ var skillLoadTool = {
3635
+ id: "skill_load",
3636
+ description: "Load a skill body from ~/.kilncraft/skills or .kilncraft/skills.",
3637
+ input: skillInput,
3638
+ readOnly: true,
3639
+ parallelizable: true,
3640
+ defaultDecision: "allow",
3641
+ timeoutMs: 1e4,
3642
+ async execute(input, context) {
3643
+ const safe = input.name.replace(/[^a-zA-Z0-9_.-]/g, "_");
3644
+ const candidates = [
3645
+ join(homedir(), ".kilncraft", "skills", safe, "SKILL.md"),
3646
+ join(context.cwd, ".kilncraft", "skills", safe, "SKILL.md"),
3647
+ join(homedir(), ".kilncraft", "skills", `${safe}.md`),
3648
+ join(context.cwd, ".kilncraft", "skills", `${safe}.md`)
3649
+ ];
3650
+ for (const path of candidates) {
3651
+ try {
3652
+ const text = await readFile(path, "utf8");
3653
+ return { kind: "text", text };
3654
+ } catch {
3655
+ }
3656
+ }
3657
+ return { kind: "text", text: `Skill "${input.name}" was not found.` };
3658
+ }
3659
+ };
3660
+ var editSchema = z.object({
3661
+ oldString: z.string().min(1),
3662
+ newString: z.string(),
3663
+ replaceAll: z.boolean().optional()
3664
+ });
3665
+ var multiEditInput = z.object({
3666
+ path: z.string().min(1).describe("File path, relative to the workspace or absolute"),
3667
+ edits: z.array(editSchema).min(1).describe("Edits applied in order")
3668
+ });
3669
+ function countOccurrences2(haystack, needle) {
3670
+ if (needle.length === 0) return 0;
3671
+ let count = 0;
3672
+ let index = haystack.indexOf(needle);
3673
+ while (index !== -1) {
3674
+ count++;
3675
+ index = haystack.indexOf(needle, index + needle.length);
3676
+ }
3677
+ return count;
3678
+ }
3679
+ var multiEditTool = {
3680
+ id: "multi_edit",
3681
+ description: "Apply several exact string replacements to one file atomically. All matches must be unique unless replaceAll is set; nothing is written if any edit fails.",
3682
+ input: multiEditInput,
3683
+ readOnly: false,
3684
+ parallelizable: false,
3685
+ defaultDecision: "ask",
3686
+ timeoutMs: 3e4,
3687
+ async execute(input, context) {
3688
+ const fullPath = resolveWorkspacePath(context.cwd, input.path);
3689
+ assertInsideWorkspace(context.cwd, fullPath);
3690
+ await assertRealInside(context.cwd, fullPath);
3691
+ const original = await readTextFile(fullPath);
3692
+ let content = original;
3693
+ for (const [index, edit] of input.edits.entries()) {
3694
+ let oldString = edit.oldString;
3695
+ let occurrences = countOccurrences2(content, oldString);
3696
+ if (occurrences === 0) {
3697
+ const normalizedContent = content.replace(/\r\n/g, "\n");
3698
+ const normalizedOld = oldString.replace(/\r\n/g, "\n");
3699
+ const normalizedCount = countOccurrences2(normalizedContent, normalizedOld);
3700
+ if (normalizedCount > 0) {
3701
+ content = normalizedContent;
3702
+ oldString = normalizedOld;
3703
+ occurrences = normalizedCount;
3704
+ }
3705
+ }
3706
+ if (occurrences === 0) {
3707
+ return {
3708
+ kind: "text",
3709
+ text: `Edit ${index + 1} could not find its exact text in ${input.path}; nothing was written.`
3710
+ };
3711
+ }
3712
+ if (occurrences > 1 && !edit.replaceAll) {
3713
+ return {
3714
+ kind: "text",
3715
+ text: `Edit ${index + 1} matched ${occurrences} times in ${input.path}; nothing was written. Add context or set replaceAll.`
3716
+ };
3717
+ }
3718
+ content = edit.replaceAll ? content.split(oldString).join(edit.newString) : content.replace(oldString, () => edit.newString);
3719
+ }
3720
+ await context.checkpoint?.(fullPath);
3721
+ await atomicWrite(fullPath, content);
3722
+ return {
3723
+ kind: "diff",
3724
+ diff: diffText(input.path, original, content),
3725
+ files: [{ path: input.path, status: "modified" }]
3726
+ };
3727
+ }
3728
+ };
3729
+ var notebookInput = z.object({
3730
+ path: z.string().min(1).describe("Path to a .ipynb file"),
3731
+ mode: z.enum(["replace", "insert", "delete"]),
3732
+ index: z.number().int().nonnegative().optional().describe("Cell index"),
3733
+ source: z.string().optional().describe("New cell source"),
3734
+ cellType: z.enum(["code", "markdown", "raw"]).optional().describe("Cell type")
3735
+ });
3736
+ var notebookEditTool = {
3737
+ id: "notebook_edit",
3738
+ description: "Edit a Jupyter notebook cell by index: replace, insert, or delete. Writes valid nbformat JSON.",
3739
+ input: notebookInput,
3740
+ readOnly: false,
3741
+ parallelizable: false,
3742
+ defaultDecision: "ask",
3743
+ timeoutMs: 3e4,
3744
+ async execute(input, context) {
3745
+ const fullPath = resolveWorkspacePath(context.cwd, input.path);
3746
+ assertInsideWorkspace(context.cwd, fullPath);
3747
+ await assertRealInside(context.cwd, fullPath);
3748
+ const original = await readTextFile(fullPath);
3749
+ let notebook;
3750
+ try {
3751
+ notebook = JSON.parse(original);
3752
+ } catch {
3753
+ return { kind: "text", text: `${input.path} is not valid JSON.` };
3754
+ }
3755
+ if (!Array.isArray(notebook.cells)) {
3756
+ return { kind: "text", text: `${input.path} has no cells array.` };
3757
+ }
3758
+ const cells = [...notebook.cells];
3759
+ const index = input.index ?? cells.length - 1;
3760
+ if (input.mode === "delete") {
3761
+ if (index < 0 || index >= cells.length) {
3762
+ return { kind: "text", text: `Cell ${index} is out of range.` };
3763
+ }
3764
+ cells.splice(index, 1);
3765
+ } else if (input.mode === "insert") {
3766
+ if (input.source === void 0) {
3767
+ return { kind: "text", text: "source is required when inserting a cell." };
3768
+ }
3769
+ cells.splice(index, 0, {
3770
+ cell_type: input.cellType ?? "code",
3771
+ source: input.source.split("\n"),
3772
+ metadata: {},
3773
+ outputs: [],
3774
+ execution_count: null
3775
+ });
3776
+ } else {
3777
+ if (index < 0 || index >= cells.length) {
3778
+ return { kind: "text", text: `Cell ${index} is out of range.` };
3779
+ }
3780
+ const current = cells[index];
3781
+ if (!current) return { kind: "text", text: `Cell ${index} is out of range.` };
3782
+ cells[index] = {
3783
+ ...current,
3784
+ cell_type: input.cellType ?? current.cell_type,
3785
+ source: (input.source ?? "").split("\n"),
3786
+ outputs: input.cellType === "markdown" || input.cellType === "raw" ? [] : current.outputs,
3787
+ execution_count: input.cellType === "code" ? null : current.execution_count
3788
+ };
3789
+ }
3790
+ const updated = { ...notebook, cells };
3791
+ const next = `${JSON.stringify(updated, null, 2)}
3792
+ `;
3793
+ await context.checkpoint?.(fullPath);
3794
+ await atomicWrite(fullPath, next);
3795
+ return {
3796
+ kind: "diff",
3797
+ diff: diffText(input.path, original, next),
3798
+ files: [{ path: input.path, status: "modified" }]
3799
+ };
3800
+ }
3801
+ };
3802
+ var snapshotInput = z.object({
3803
+ path: z.string().min(1).describe("Workspace-relative or absolute file path")
3804
+ });
3805
+ var restoreInput = z.object({
3806
+ hash: z.string().regex(/^[0-9a-f]{16}$/, "expected a 16-character checkpoint hash")
3807
+ });
3808
+ var snapshotTool = {
3809
+ id: "snapshot",
3810
+ description: "Create a restore point for a file before a risky change.",
3811
+ input: snapshotInput,
3812
+ readOnly: false,
3813
+ parallelizable: false,
3814
+ defaultDecision: "allow",
3815
+ timeoutMs: 1e4,
3816
+ async execute(input, context) {
3817
+ if (!context.snapshot) return { kind: "text", text: "Snapshots are not enabled." };
3818
+ const path = resolveWorkspacePath(context.cwd, input.path);
3819
+ const hash = await context.snapshot(path);
3820
+ return {
3821
+ kind: "text",
3822
+ text: hash ? `Snapshot ${hash} created for ${input.path}` : `Could not snapshot ${input.path}`
3823
+ };
3824
+ }
3825
+ };
3826
+ var restoreTool = {
3827
+ id: "restore",
3828
+ description: "Restore a file from a checkpoint hash. This is destructive.",
3829
+ input: restoreInput,
3830
+ readOnly: false,
3831
+ parallelizable: false,
3832
+ defaultDecision: "ask",
3833
+ timeoutMs: 1e4,
3834
+ async execute(input, context) {
3835
+ if (!context.restore) return { kind: "text", text: "Restore is not enabled." };
3836
+ const restored = await context.restore(input.hash);
3837
+ return {
3838
+ kind: "text",
3839
+ text: restored > 0 ? `Restored ${restored} file(s).` : "Checkpoint not found."
3840
+ };
3841
+ }
3842
+ };
3843
+ var taskInput = z.object({
3844
+ prompt: z.string().min(1).describe("Task for the subagent"),
3845
+ agent: z.string().optional().describe("Agent preset for the subagent"),
3846
+ model: z.string().optional().describe("Model override for the subagent")
3847
+ });
3848
+ var taskTool = {
3849
+ id: "task",
3850
+ description: "Delegate an isolated task to a subagent. The subagent has its own context and returns a summary.",
3851
+ input: taskInput,
3852
+ readOnly: false,
3853
+ parallelizable: true,
3854
+ concurrent: true,
3855
+ defaultDecision: "ask",
3856
+ timeoutMs: 6e5,
3857
+ async execute(input, context) {
3858
+ if (!context.spawnSubagent) {
3859
+ return { kind: "text", text: "Subagents are not available in this session." };
3860
+ }
3861
+ const text = await context.spawnSubagent({
3862
+ prompt: input.prompt,
3863
+ agent: input.agent,
3864
+ model: input.model
3865
+ });
3866
+ return { kind: "text", text: text || "(subagent returned no text)" };
3867
+ }
3868
+ };
2821
3869
  var todoSchema = z.object({
2822
3870
  content: z.string().min(1),
2823
3871
  status: z.enum(["pending", "in_progress", "completed"]),
@@ -2843,6 +3891,174 @@ var todoTool = {
2843
3891
  return { kind: "text", text: formatTodos(input.todos) };
2844
3892
  }
2845
3893
  };
3894
+ var fetchInput = z.object({
3895
+ url: z.string().url(),
3896
+ method: z.enum(["GET", "HEAD"]).optional(),
3897
+ headers: z.record(z.string(), z.string()).optional(),
3898
+ maxBytes: z.number().int().positive().max(5e6).optional(),
3899
+ timeoutMs: z.number().int().positive().max(6e4).optional()
3900
+ });
3901
+ var webfetchInput = z.object({
3902
+ url: z.string().url(),
3903
+ maxBytes: z.number().int().positive().max(5e6).optional()
3904
+ });
3905
+ var searchInput = z.object({
3906
+ query: z.string().min(1),
3907
+ limit: z.number().int().positive().max(20).optional()
3908
+ });
3909
+ var BLOCKED_HOSTS = /* @__PURE__ */ new Set([
3910
+ "localhost",
3911
+ "127.0.0.1",
3912
+ "::1",
3913
+ "0.0.0.0",
3914
+ "metadata.google.internal"
3915
+ ]);
3916
+ function isPrivateHost(hostname) {
3917
+ const host = hostname.toLowerCase();
3918
+ if (BLOCKED_HOSTS.has(host)) return true;
3919
+ if (/^127\./.test(host)) return true;
3920
+ if (/^10\./.test(host)) return true;
3921
+ if (/^192\.168\./.test(host)) return true;
3922
+ if (/^169\.254\./.test(host)) return true;
3923
+ if (/^172\.(1[6-9]|2\d|3[0-1])\./.test(host)) return true;
3924
+ if (host === "[::1]" || host === "::1") return true;
3925
+ return false;
3926
+ }
3927
+ async function fetchUrl(url, init, timeoutMs) {
3928
+ const controller = new AbortController();
3929
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
3930
+ try {
3931
+ return await fetch(url, { ...init, signal: controller.signal, redirect: "follow" });
3932
+ } finally {
3933
+ clearTimeout(timer);
3934
+ }
3935
+ }
3936
+ function htmlToText(html) {
3937
+ return html.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<[^>]+>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/[ \t]+/g, " ").replace(/\n{3,}/g, "\n\n").trim();
3938
+ }
3939
+ var fetchTool = {
3940
+ id: "fetch",
3941
+ description: "Fetch an http(s) URL. Blocks private/loopback hosts and truncates large responses.",
3942
+ input: fetchInput,
3943
+ readOnly: true,
3944
+ parallelizable: true,
3945
+ defaultDecision: "allow",
3946
+ timeoutMs: 6e4,
3947
+ async execute(input, context) {
3948
+ const url = new URL(input.url);
3949
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
3950
+ return { kind: "text", text: "Only http and https URLs are allowed." };
3951
+ }
3952
+ if (isPrivateHost(url.hostname)) {
3953
+ return { kind: "text", text: `Blocked private or loopback host: ${url.hostname}` };
3954
+ }
3955
+ try {
3956
+ const response = await fetchUrl(
3957
+ input.url,
3958
+ { method: input.method ?? "GET", headers: input.headers },
3959
+ input.timeoutMs ?? 3e4
3960
+ );
3961
+ if (input.method === "HEAD") {
3962
+ return {
3963
+ kind: "text",
3964
+ text: `HTTP ${response.status} ${response.statusText} \xB7 ${response.headers.get("content-type") ?? "unknown"}`
3965
+ };
3966
+ }
3967
+ const maxBytes = input.maxBytes ?? 2e5;
3968
+ const buffer = await response.arrayBuffer();
3969
+ const bytes = new Uint8Array(buffer);
3970
+ const text = new TextDecoder("utf8", { fatal: false }).decode(bytes.slice(0, maxBytes));
3971
+ const contentType = response.headers.get("content-type") ?? "";
3972
+ const body = contentType.includes("html") ? htmlToText(text) : text;
3973
+ const notice = bytes.length > maxBytes ? `
3974
+
3975
+ [truncated at ${maxBytes} bytes of ${bytes.length}]` : "";
3976
+ context.logger.debug({ url: input.url, status: response.status }, "fetch");
3977
+ return { kind: "text", text: `HTTP ${response.status}
3978
+ ${body}${notice}` };
3979
+ } catch (error) {
3980
+ return {
3981
+ kind: "text",
3982
+ text: `Fetch failed: ${error instanceof Error ? error.message : String(error)}`
3983
+ };
3984
+ }
3985
+ }
3986
+ };
3987
+ var webfetchTool = {
3988
+ id: "webfetch",
3989
+ description: "Fetch a web page and return readable text (HTML is stripped).",
3990
+ input: webfetchInput,
3991
+ readOnly: true,
3992
+ parallelizable: true,
3993
+ defaultDecision: "allow",
3994
+ timeoutMs: 6e4,
3995
+ async execute(input, context) {
3996
+ return fetchTool.execute({ url: input.url, method: "GET", maxBytes: input.maxBytes }, context);
3997
+ }
3998
+ };
3999
+ var websearchTool = {
4000
+ id: "websearch",
4001
+ description: "Search the web. Uses BRAVE_API_KEY or SERPER_API_KEY when configured; otherwise returns setup instructions.",
4002
+ input: searchInput,
4003
+ readOnly: true,
4004
+ parallelizable: true,
4005
+ defaultDecision: "allow",
4006
+ timeoutMs: 3e4,
4007
+ async execute(input) {
4008
+ const limit = input.limit ?? 5;
4009
+ const braveKey = process.env.BRAVE_API_KEY;
4010
+ const serperKey = process.env.SERPER_API_KEY;
4011
+ try {
4012
+ if (braveKey) {
4013
+ const url = new URL("https://api.search.brave.com/res/v1/web/search");
4014
+ url.searchParams.set("q", input.query);
4015
+ url.searchParams.set("count", String(limit));
4016
+ const response = await fetchUrl(
4017
+ url.toString(),
4018
+ { headers: { accept: "application/json", "x-subscription-token": braveKey } },
4019
+ 2e4
4020
+ );
4021
+ const data = await response.json();
4022
+ const results = data.web?.results ?? [];
4023
+ return {
4024
+ kind: "text",
4025
+ text: results.map(
4026
+ (result) => `${result.title ?? ""}
4027
+ ${result.url ?? ""}
4028
+ ${result.description ?? ""}`
4029
+ ).join("\n\n")
4030
+ };
4031
+ }
4032
+ if (serperKey) {
4033
+ const response = await fetchUrl(
4034
+ "https://google.serper.dev/search",
4035
+ {
4036
+ method: "POST",
4037
+ headers: { "content-type": "application/json", "x-api-key": serperKey },
4038
+ body: JSON.stringify({ q: input.query, num: limit })
4039
+ },
4040
+ 2e4
4041
+ );
4042
+ const data = await response.json();
4043
+ return {
4044
+ kind: "text",
4045
+ text: (data.organic ?? []).map((result) => `${result.title ?? ""}
4046
+ ${result.link ?? ""}
4047
+ ${result.snippet ?? ""}`).join("\n\n")
4048
+ };
4049
+ }
4050
+ return {
4051
+ kind: "text",
4052
+ text: "Web search is not configured. Set BRAVE_API_KEY or SERPER_API_KEY, or use fetch/webfetch with a URL."
4053
+ };
4054
+ } catch (error) {
4055
+ return {
4056
+ kind: "text",
4057
+ text: `Web search failed: ${error instanceof Error ? error.message : String(error)}`
4058
+ };
4059
+ }
4060
+ }
4061
+ };
2846
4062
  var writeInput = z.object({
2847
4063
  path: z.string().min(1).describe("File path, relative to the workspace or absolute"),
2848
4064
  content: z.string().describe("Complete file contents")
@@ -2927,16 +4143,40 @@ function createDefaultToolRegistry() {
2927
4143
  registry.register(readTool);
2928
4144
  registry.register(writeTool);
2929
4145
  registry.register(editTool);
4146
+ registry.register(multiEditTool);
4147
+ registry.register(applyPatchTool);
2930
4148
  registry.register(globTool);
2931
4149
  registry.register(grepTool);
2932
4150
  registry.register(lsTool);
2933
4151
  registry.register(lspDiagnosticsTool);
2934
4152
  registry.register(lspSymbolsTool);
4153
+ registry.register(lspDefinitionTool);
4154
+ registry.register(lspHoverTool);
4155
+ registry.register(lspReferencesTool);
2935
4156
  registry.register(bashTool);
4157
+ registry.register(bashOutputTool);
4158
+ registry.register(killShellTool);
2936
4159
  registry.register(todoTool);
4160
+ registry.register(askUserTool);
4161
+ registry.register(taskTool);
4162
+ registry.register(gitStatusTool);
4163
+ registry.register(gitDiffTool);
4164
+ registry.register(gitLogTool);
4165
+ registry.register(gitCommitTool);
4166
+ registry.register(gitBranchTool);
4167
+ registry.register(worktreeCreateTool);
4168
+ registry.register(webfetchTool);
4169
+ registry.register(websearchTool);
4170
+ registry.register(fetchTool);
4171
+ registry.register(viewImageTool);
4172
+ registry.register(memoryWriteTool);
4173
+ registry.register(skillLoadTool);
4174
+ registry.register(notebookEditTool);
4175
+ registry.register(snapshotTool);
4176
+ registry.register(restoreTool);
2937
4177
  return registry;
2938
4178
  }
2939
4179
 
2940
- export { Agent, AnthropicProvider, AuditLog, CheckpointManager, DEFAULT_IGNORE, GLOB_IGNORE, GeminiProvider, MODEL_CATALOG, OpenAIProvider, PermissionEngine, PluginHost, ProviderRegistry, SessionStore, ToolRegistry, assertInsideWorkspace, assertRealInside, atomicWrite, availableProviderIds, bashTool, buildSystemPrompt, compactMessages, createDefaultProviderRegistry, createDefaultToolRegistry, diffText, editTool, escapeRegExp, estimateMessagesTokens, estimateTokens, fileExists, formatTodos, getCommand, getPath, globToRegExp, globTool, grepTool, hashInput, isBinary, isDangerousCommand, isOpenAiChunk, isPathInside, lineNumbered, listKnownModels, loadPlugins, lsTool, lspDiagnosticsTool, lspSymbolsTool, matchesGlob, modelInfoFor, readSessionFile, readTextFile, readTool, resolveDataDir, resolveWorkspacePath, sessionExists, shouldCompact, summarizeInput, todoSchema, todoTool, toolOutputToText, truncateText, walkFiles, writeSessionFile, writeTool };
4180
+ export { Agent, AnthropicProvider, AuditLog, CheckpointManager, DEFAULT_IGNORE, GLOB_IGNORE, GeminiProvider, MODEL_CATALOG, OpenAIProvider, PermissionEngine, PluginHost, ProviderRegistry, SessionStore, ToolRegistry, assertInsideWorkspace, assertRealInside, atomicWrite, availableProviderIds, bashOutputTool, bashTool, buildSystemPrompt, compactMessages, createDefaultProviderRegistry, createDefaultToolRegistry, diffText, editTool, escapeRegExp, estimateMessagesTokens, estimateTokens, fileExists, formatTodos, getCommand, getPath, globToRegExp, globTool, grepTool, hashInput, isBinary, isDangerousCommand, isOpenAiChunk, isPathInside, killShellTool, lineNumbered, listKnownModels, loadPlugins, lsTool, lspDefinitionTool, lspDiagnosticsTool, lspHoverTool, lspReferencesTool, lspSymbolsTool, matchesGlob, modelInfoFor, readSessionFile, readTextFile, readTool, resolveDataDir, resolveWorkspacePath, sessionExists, shouldCompact, summarizeInput, todoSchema, todoTool, toolOutputToText, truncateText, walkFiles, writeSessionFile, writeTool };
2941
4181
  //# sourceMappingURL=index.js.map
2942
4182
  //# sourceMappingURL=index.js.map