@codelia/runtime 0.1.26 → 0.1.29

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/index.cjs +411 -58
  2. package/dist/index.js +411 -58
  3. package/package.json +9 -9
package/dist/index.cjs CHANGED
@@ -3433,7 +3433,7 @@ var createEditTool = (sandboxKey) => (0, import_core6.defineTool)({
3433
3433
  const sandbox = await getSandboxContext(ctx, sandboxKey);
3434
3434
  resolved = sandbox.resolvePath(input.file_path);
3435
3435
  } catch (error) {
3436
- return `Security error: ${String(error)}`;
3436
+ throw new Error(`Security error: ${String(error)}`);
3437
3437
  }
3438
3438
  if (input.old_string !== "" && input.old_string === input.new_string) {
3439
3439
  return {
@@ -3452,22 +3452,24 @@ var createEditTool = (sandboxKey) => (0, import_core6.defineTool)({
3452
3452
  try {
3453
3453
  const stat = await import_node_fs7.promises.stat(resolved);
3454
3454
  if (stat.isDirectory()) {
3455
- return `Path is a directory: ${input.file_path}`;
3455
+ throw new Error(`Path is a directory: ${input.file_path}`);
3456
3456
  }
3457
3457
  fileExists = true;
3458
3458
  content = await import_node_fs7.promises.readFile(resolved, "utf8");
3459
3459
  } catch (_error) {
3460
3460
  if (input.old_string !== "") {
3461
- return `File not found: ${input.file_path}`;
3461
+ throw new Error(`File not found: ${input.file_path}`);
3462
3462
  }
3463
3463
  }
3464
3464
  if (input.expected_hash) {
3465
3465
  if (!fileExists) {
3466
- return `Expected hash provided but file not found: ${input.file_path}`;
3466
+ throw new Error(
3467
+ `Expected hash provided but file not found: ${input.file_path}`
3468
+ );
3467
3469
  }
3468
3470
  const currentHash = hashContent(content);
3469
3471
  if (currentHash !== input.expected_hash) {
3470
- return `Hash mismatch for ${input.file_path}`;
3472
+ throw new Error(`Hash mismatch for ${input.file_path}`);
3471
3473
  }
3472
3474
  }
3473
3475
  let replacements = 0;
@@ -3483,12 +3485,14 @@ var createEditTool = (sandboxKey) => (0, import_core6.defineTool)({
3483
3485
  matchMode
3484
3486
  );
3485
3487
  if (!matchResult || matchResult.matches.length === 0) {
3486
- return `String not found in ${input.file_path}`;
3488
+ throw new Error(`String not found in ${input.file_path}`);
3487
3489
  }
3488
3490
  modeUsed = matchResult.mode;
3489
3491
  let matches = matchResult.matches;
3490
3492
  if (!replaceAll && matches.length > 1) {
3491
- return `Multiple matches (${matches.length}) found in ${input.file_path}`;
3493
+ throw new Error(
3494
+ `Multiple matches (${matches.length}) found in ${input.file_path}`
3495
+ );
3492
3496
  }
3493
3497
  if (!replaceAll) {
3494
3498
  matches = [matches[0]];
@@ -3497,7 +3501,9 @@ var createEditTool = (sandboxKey) => (0, import_core6.defineTool)({
3497
3501
  nextContent = applyReplacements(content, matches, input.new_string);
3498
3502
  }
3499
3503
  if (input.expected_replacements !== void 0 && replacements !== input.expected_replacements) {
3500
- return `Expected ${input.expected_replacements} replacements, found ${replacements}`;
3504
+ throw new Error(
3505
+ `Expected ${input.expected_replacements} replacements, found ${replacements}`
3506
+ );
3501
3507
  }
3502
3508
  const diff = createUnifiedDiff(input.file_path, content, nextContent);
3503
3509
  if (dryRun) {
@@ -3522,7 +3528,7 @@ var createEditTool = (sandboxKey) => (0, import_core6.defineTool)({
3522
3528
  await import_node_fs7.promises.mkdir(import_node_path8.default.dirname(resolved), { recursive: true });
3523
3529
  await import_node_fs7.promises.writeFile(resolved, nextContent, "utf8");
3524
3530
  } catch (error) {
3525
- return `Error editing file: ${String(error)}`;
3531
+ throw new Error(`Error editing file: ${String(error)}`);
3526
3532
  }
3527
3533
  return {
3528
3534
  summary: `Replaced ${replacements} occurrence(s) in ${input.file_path}`,
@@ -4736,49 +4742,339 @@ var createSkillSearchTool = (skillsResolverKey) => (0, import_core13.defineTool)
4736
4742
  var import_core14 = require("@codelia/core");
4737
4743
  var import_zod13 = require("zod");
4738
4744
 
4745
+ // src/tools/session-context.ts
4746
+ var createToolSessionContextKey = (getSessionId) => ({
4747
+ id: "tool-session-context",
4748
+ create: () => {
4749
+ const sessionId = getSessionId()?.trim() || null;
4750
+ return { sessionId };
4751
+ }
4752
+ });
4753
+ var getToolSessionContext = async (ctx, key) => ctx.resolve(key);
4754
+
4739
4755
  // src/tools/todo-store.ts
4756
+ var TODO_SESSION_META_KEY = "codelia_todos";
4757
+ var DEFAULT_TODO_PRIORITY = 3;
4758
+ var normalizeOptionalText = (value) => {
4759
+ if (typeof value !== "string") return void 0;
4760
+ const trimmed = value.trim();
4761
+ return trimmed.length ? trimmed : void 0;
4762
+ };
4763
+ var isTodoStatus = (value) => value === "pending" || value === "in_progress" || value === "completed";
4764
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4765
+ var normalizeTodoIdBase = (value) => {
4766
+ const trimmed = value.trim().toLowerCase();
4767
+ const withHyphen = trimmed.replace(/\s+/g, "-");
4768
+ const safe = withHyphen.replace(/[^a-z0-9._-]+/g, "-");
4769
+ const compact = safe.replace(/-+/g, "-");
4770
+ const stripped = compact.replace(/^[-_.]+|[-_.]+$/g, "");
4771
+ return stripped.length ? stripped : "todo";
4772
+ };
4773
+ var slugFromContent = (content) => {
4774
+ const source = normalizeOptionalText(content) ?? "todo";
4775
+ return normalizeTodoIdBase(source);
4776
+ };
4777
+ var toTodoPriority = (value) => {
4778
+ const numericValue = typeof value === "number" ? value : Number.NaN;
4779
+ if (!Number.isInteger(numericValue)) return DEFAULT_TODO_PRIORITY;
4780
+ if (numericValue <= 1) return 1;
4781
+ if (numericValue >= 5) return 5;
4782
+ return numericValue;
4783
+ };
4784
+ var toUniqueId = (baseId, usedIds) => {
4785
+ let candidate = baseId;
4786
+ let suffix = 2;
4787
+ while (usedIds.has(candidate)) {
4788
+ candidate = `${baseId}-${suffix}`;
4789
+ suffix += 1;
4790
+ }
4791
+ usedIds.add(candidate);
4792
+ return candidate;
4793
+ };
4794
+ var normalizeTodoId = (value) => normalizeTodoIdBase(value);
4795
+ var normalizeTodoItems = (todos) => {
4796
+ const usedIds = /* @__PURE__ */ new Set();
4797
+ return todos.map((todo, index) => {
4798
+ const content = normalizeOptionalText(todo.content) ?? `Todo ${index + 1}`;
4799
+ const preferredId = typeof todo.id === "string" && todo.id.trim().length ? normalizeTodoIdBase(todo.id) : slugFromContent(content);
4800
+ return {
4801
+ id: toUniqueId(preferredId, usedIds),
4802
+ content,
4803
+ status: todo.status,
4804
+ priority: toTodoPriority(todo.priority),
4805
+ notes: normalizeOptionalText(todo.notes),
4806
+ activeForm: normalizeOptionalText(todo.activeForm)
4807
+ };
4808
+ });
4809
+ };
4810
+ var setTodosForSession = (sessionId, todos) => {
4811
+ const normalized = normalizeTodoItems(todos);
4812
+ todoStore.set(sessionId, normalized);
4813
+ return normalized;
4814
+ };
4815
+ var getTodosForSession = (sessionId) => normalizeTodoItems(todoStore.get(sessionId) ?? []);
4816
+ var clearTodosForSession = (sessionId) => {
4817
+ todoStore.delete(sessionId);
4818
+ };
4819
+ var readTodosFromSessionMeta = (meta) => {
4820
+ const raw = meta?.[TODO_SESSION_META_KEY];
4821
+ if (!Array.isArray(raw)) return [];
4822
+ const todos = [];
4823
+ for (const entry of raw) {
4824
+ if (!isRecord2(entry)) continue;
4825
+ const status = entry.status;
4826
+ if (!isTodoStatus(status)) continue;
4827
+ const content = typeof entry.content === "string" ? entry.content : "";
4828
+ todos.push({
4829
+ id: typeof entry.id === "string" ? entry.id : void 0,
4830
+ content,
4831
+ status,
4832
+ priority: typeof entry.priority === "number" ? entry.priority : void 0,
4833
+ notes: typeof entry.notes === "string" ? entry.notes : void 0,
4834
+ activeForm: typeof entry.activeForm === "string" ? entry.activeForm : void 0
4835
+ });
4836
+ }
4837
+ return normalizeTodoItems(todos);
4838
+ };
4839
+ var mergeTodosIntoSessionMeta = (meta, todos) => {
4840
+ const nextMeta = meta ? { ...meta } : {};
4841
+ if (todos.length > 0) {
4842
+ nextMeta[TODO_SESSION_META_KEY] = todos.map((todo) => ({ ...todo }));
4843
+ } else {
4844
+ delete nextMeta[TODO_SESSION_META_KEY];
4845
+ }
4846
+ return Object.keys(nextMeta).length > 0 ? nextMeta : void 0;
4847
+ };
4848
+ var countInProgressTodos = (todos) => todos.filter((todo) => todo.status === "in_progress").length;
4849
+ var getTodoStats = (todos) => ({
4850
+ pending: todos.filter((todo) => todo.status === "pending").length,
4851
+ inProgress: todos.filter((todo) => todo.status === "in_progress").length,
4852
+ completed: todos.filter((todo) => todo.status === "completed").length
4853
+ });
4854
+ var statusOrder = {
4855
+ in_progress: 0,
4856
+ pending: 1,
4857
+ completed: 2
4858
+ };
4859
+ var sortTodosForDisplay = (todos) => todos.map((todo, index) => ({ todo, index })).sort((a, b) => {
4860
+ const statusDiff = statusOrder[a.todo.status] - statusOrder[b.todo.status];
4861
+ if (statusDiff !== 0) return statusDiff;
4862
+ const priorityDiff = a.todo.priority - b.todo.priority;
4863
+ if (priorityDiff !== 0) return priorityDiff;
4864
+ return a.index - b.index;
4865
+ }).map((entry) => entry.todo);
4866
+ var pickNextTodo = (todos) => {
4867
+ const inProgress = todos.find((todo) => todo.status === "in_progress");
4868
+ if (inProgress) return inProgress;
4869
+ const pending = sortTodosForDisplay(todos).find(
4870
+ (todo) => todo.status === "pending"
4871
+ );
4872
+ return pending ?? null;
4873
+ };
4740
4874
  var todoStore = /* @__PURE__ */ new Map();
4741
4875
 
4742
4876
  // src/tools/todo-read.ts
4743
- var createTodoReadTool = (sandboxKey) => (0, import_core14.defineTool)({
4877
+ var statusSymbol = {
4878
+ pending: "[ ]",
4879
+ in_progress: "[>]",
4880
+ completed: "[x]"
4881
+ };
4882
+ var createTodoReadTool = (sandboxKey, sessionContextKey) => (0, import_core14.defineTool)({
4744
4883
  name: "todo_read",
4745
- description: "Read the in-session todo list.",
4884
+ description: "Read the in-session todo plan with execution order and next step.",
4746
4885
  input: import_zod13.z.object({}),
4747
4886
  execute: async (_input, ctx) => {
4748
4887
  const sandbox = await getSandboxContext(ctx, sandboxKey);
4749
- const todos = todoStore.get(sandbox.sessionId) ?? [];
4888
+ const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
4889
+ const todoSessionId = sessionContext?.sessionId && sessionContext.sessionId.length > 0 ? sessionContext.sessionId : sandbox.sessionId;
4890
+ const todos = getTodosForSession(todoSessionId);
4750
4891
  if (!todos.length) return "Todo list is empty";
4751
- return todos.map((todo, index) => {
4752
- const status = todo.status === "completed" ? "[x]" : todo.status === "in_progress" ? "[>]" : "[ ]";
4753
- return `${index + 1}. ${status} ${todo.content}`;
4754
- }).join("\n");
4892
+ const orderedTodos = sortTodosForDisplay(todos);
4893
+ const lines = ["Todo plan:"];
4894
+ for (const [index, todo] of orderedTodos.entries()) {
4895
+ const label = todo.status === "in_progress" && todo.activeForm ? todo.activeForm : todo.content;
4896
+ lines.push(
4897
+ `${index + 1}. ${statusSymbol[todo.status]} [${todo.id}] (p${todo.priority}) ${label}`
4898
+ );
4899
+ if (todo.notes) {
4900
+ lines.push(` note: ${todo.notes}`);
4901
+ }
4902
+ }
4903
+ const stats = getTodoStats(orderedTodos);
4904
+ const nextTodo = pickNextTodo(orderedTodos);
4905
+ lines.push(
4906
+ `Summary: ${stats.pending} pending, ${stats.inProgress} in progress, ${stats.completed} completed`
4907
+ );
4908
+ if (nextTodo) {
4909
+ lines.push(`Next: [${nextTodo.id}] ${nextTodo.content}`);
4910
+ } else {
4911
+ lines.push("Next: none");
4912
+ }
4913
+ const inProgressCount = countInProgressTodos(orderedTodos);
4914
+ if (inProgressCount > 1) {
4915
+ lines.push(
4916
+ `Warning: ${inProgressCount} items are in_progress (expected at most 1).`
4917
+ );
4918
+ }
4919
+ return lines.join("\n");
4755
4920
  }
4756
4921
  });
4757
4922
 
4758
4923
  // src/tools/todo-write.ts
4759
4924
  var import_core15 = require("@codelia/core");
4760
4925
  var import_zod14 = require("zod");
4761
- var createTodoWriteTool = (sandboxKey) => (0, import_core15.defineTool)({
4926
+ var todoStatusSchema = import_zod14.z.enum(["pending", "in_progress", "completed"]);
4927
+ var todoPrioritySchema = import_zod14.z.number().int().min(1).max(5);
4928
+ var todoItemSchema = import_zod14.z.object({
4929
+ id: import_zod14.z.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
4930
+ content: import_zod14.z.string().min(1).describe("Todo item text."),
4931
+ status: todoStatusSchema.describe("Todo status."),
4932
+ priority: todoPrioritySchema.optional().describe("Priority 1(high)-5(low). Default is 3."),
4933
+ notes: import_zod14.z.string().optional().describe("Optional implementation notes."),
4934
+ activeForm: import_zod14.z.string().optional().describe("Optional in-progress phrasing for UI display.")
4935
+ });
4936
+ var todoPatchItemSchema = import_zod14.z.object({
4937
+ id: import_zod14.z.string().min(1).describe("Target todo ID."),
4938
+ remove: import_zod14.z.boolean().optional().describe("Set true to remove the todo item."),
4939
+ content: import_zod14.z.string().min(1).nullable().default(null).describe("Updated todo text (null keeps current)."),
4940
+ status: todoStatusSchema.nullable().default(null).describe("Updated status (null keeps current)."),
4941
+ priority: todoPrioritySchema.nullable().default(null).describe("Updated priority (null keeps current)."),
4942
+ notes: import_zod14.z.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
4943
+ activeForm: import_zod14.z.string().nullable().default(null).describe("Updated in-progress phrasing (null keeps current, empty clears).")
4944
+ });
4945
+ var todoWriteInputSchema = import_zod14.z.object({
4946
+ mode: import_zod14.z.enum(["new", "append", "patch", "clear"]).default("new").describe("Update mode. Default is new."),
4947
+ todos: import_zod14.z.array(todoItemSchema).default([]).describe("Todo items for new/append mode."),
4948
+ updates: import_zod14.z.array(todoPatchItemSchema).default([]).describe("Patch operations for patch mode.")
4949
+ }).superRefine((input, ctx) => {
4950
+ if (input.mode === "patch") {
4951
+ if (input.updates.length === 0) {
4952
+ ctx.addIssue({
4953
+ code: import_zod14.z.ZodIssueCode.custom,
4954
+ path: ["updates"],
4955
+ message: "patch mode requires at least one update item."
4956
+ });
4957
+ }
4958
+ if (input.todos.length > 0) {
4959
+ ctx.addIssue({
4960
+ code: import_zod14.z.ZodIssueCode.custom,
4961
+ path: ["todos"],
4962
+ message: "patch mode does not accept todos."
4963
+ });
4964
+ }
4965
+ return;
4966
+ }
4967
+ if (input.mode === "clear") {
4968
+ if (input.todos.length > 0) {
4969
+ ctx.addIssue({
4970
+ code: import_zod14.z.ZodIssueCode.custom,
4971
+ path: ["todos"],
4972
+ message: "clear mode does not accept todos."
4973
+ });
4974
+ }
4975
+ if (input.updates.length > 0) {
4976
+ ctx.addIssue({
4977
+ code: import_zod14.z.ZodIssueCode.custom,
4978
+ path: ["updates"],
4979
+ message: "clear mode does not accept updates."
4980
+ });
4981
+ }
4982
+ return;
4983
+ }
4984
+ if (input.todos.length === 0) {
4985
+ ctx.addIssue({
4986
+ code: import_zod14.z.ZodIssueCode.custom,
4987
+ path: ["todos"],
4988
+ message: `${input.mode} mode requires at least one todo item.`
4989
+ });
4990
+ }
4991
+ if (input.updates.length > 0) {
4992
+ ctx.addIssue({
4993
+ code: import_zod14.z.ZodIssueCode.custom,
4994
+ path: ["updates"],
4995
+ message: `${input.mode} mode does not accept updates.`
4996
+ });
4997
+ }
4998
+ });
4999
+ var loadSessionTodos = (sessionId) => getTodosForSession(sessionId);
5000
+ var formatSuccess = (mode, todos) => {
5001
+ const stats = getTodoStats(todos);
5002
+ const nextTodo = pickNextTodo(todos);
5003
+ const nextHint = nextTodo ? ` Next: [${nextTodo.id}] ${nextTodo.content}.` : " Next: none.";
5004
+ return `Updated todos (${mode}): ${stats.pending} pending, ${stats.inProgress} in progress, ${stats.completed} completed.${nextHint}`;
5005
+ };
5006
+ var withPatchApplied = (currentTodos, updates) => {
5007
+ const normalizedUpdates = updates.map((update) => ({
5008
+ ...update,
5009
+ id: normalizeTodoId(update.id)
5010
+ }));
5011
+ const currentIds = new Set(currentTodos.map((todo) => todo.id));
5012
+ const missingIds = normalizedUpdates.map((update) => update.id).filter((id) => !currentIds.has(id));
5013
+ if (missingIds.length > 0) {
5014
+ return {
5015
+ todos: [...currentTodos],
5016
+ error: `Patch failed: unknown todo id(s): ${Array.from(new Set(missingIds)).join(", ")}`
5017
+ };
5018
+ }
5019
+ let nextInputs = currentTodos.map((todo) => ({ ...todo }));
5020
+ for (const update of normalizedUpdates) {
5021
+ const index = nextInputs.findIndex((todo) => todo.id === update.id);
5022
+ if (index < 0) continue;
5023
+ if (update.remove) {
5024
+ nextInputs = [
5025
+ ...nextInputs.slice(0, index),
5026
+ ...nextInputs.slice(index + 1)
5027
+ ];
5028
+ continue;
5029
+ }
5030
+ const previous = nextInputs[index];
5031
+ nextInputs[index] = {
5032
+ ...previous,
5033
+ content: update.content !== null ? update.content : previous.content,
5034
+ status: update.status !== null ? update.status : previous.status,
5035
+ priority: update.priority !== null ? update.priority : previous.priority,
5036
+ notes: update.notes !== null ? update.notes : previous.notes,
5037
+ activeForm: update.activeForm !== null ? update.activeForm : previous.activeForm
5038
+ };
5039
+ }
5040
+ return { todos: normalizeTodoItems(nextInputs) };
5041
+ };
5042
+ var createTodoWriteTool = (sandboxKey, sessionContextKey) => (0, import_core15.defineTool)({
4762
5043
  name: "todo_write",
4763
- description: "Replace the in-session todo list.",
4764
- input: import_zod14.z.object({
4765
- todos: import_zod14.z.array(
4766
- import_zod14.z.object({
4767
- content: import_zod14.z.string().describe("Todo item text."),
4768
- status: import_zod14.z.enum(["pending", "in_progress", "completed"]).describe("Todo status."),
4769
- activeForm: import_zod14.z.string().optional().describe("Optional in-progress phrasing for UI display.")
4770
- })
4771
- )
4772
- }),
5044
+ description: "Maintain the in-session todo plan with new, append, patch, or clear updates.",
5045
+ input: todoWriteInputSchema,
4773
5046
  execute: async (input, ctx) => {
4774
5047
  const sandbox = await getSandboxContext(ctx, sandboxKey);
4775
- todoStore.set(sandbox.sessionId, input.todos);
4776
- const stats = {
4777
- pending: input.todos.filter((todo) => todo.status === "pending").length,
4778
- inProgress: input.todos.filter((todo) => todo.status === "in_progress").length,
4779
- completed: input.todos.filter((todo) => todo.status === "completed").length
4780
- };
4781
- return `Updated todos: ${stats.pending} pending, ${stats.inProgress} in progress, ${stats.completed} completed`;
5048
+ const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
5049
+ const todoSessionId = sessionContext?.sessionId && sessionContext.sessionId.length > 0 ? sessionContext.sessionId : sandbox.sessionId;
5050
+ const currentTodos = loadSessionTodos(todoSessionId);
5051
+ let mode = input.mode;
5052
+ let nextTodos = [];
5053
+ if (input.mode === "patch") {
5054
+ mode = "patch";
5055
+ const patched = withPatchApplied(currentTodos, input.updates);
5056
+ if (patched.error) return patched.error;
5057
+ nextTodos = patched.todos;
5058
+ } else if (input.mode === "append") {
5059
+ mode = "append";
5060
+ nextTodos = normalizeTodoItems([...currentTodos, ...input.todos]);
5061
+ } else if (input.mode === "clear") {
5062
+ mode = "clear";
5063
+ nextTodos = [];
5064
+ } else {
5065
+ mode = "new";
5066
+ nextTodos = normalizeTodoItems(input.todos);
5067
+ }
5068
+ const inProgressCount = countInProgressTodos(nextTodos);
5069
+ if (inProgressCount > 1) {
5070
+ return `Invalid todo state: ${inProgressCount} items are in_progress. Keep at most one item in_progress so tasks can be handled one-by-one.`;
5071
+ }
5072
+ if (nextTodos.length === 0) {
5073
+ clearTodosForSession(todoSessionId);
5074
+ } else {
5075
+ setTodosForSession(todoSessionId, nextTodos);
5076
+ }
5077
+ return formatSuccess(mode, nextTodos);
4782
5078
  }
4783
5079
  });
4784
5080
 
@@ -4841,6 +5137,15 @@ var import_node_fs14 = require("fs");
4841
5137
  var import_node_path13 = __toESM(require("path"), 1);
4842
5138
  var import_core17 = require("@codelia/core");
4843
5139
  var import_zod16 = require("zod");
5140
+ var buildDiffPreview = (content, filePath) => {
5141
+ const diff = createUnifiedDiff(filePath, "", content);
5142
+ if (!diff) {
5143
+ return `--- ${filePath}
5144
+ +++ ${filePath}
5145
+ @@ -0,0 +0,0 @@`;
5146
+ }
5147
+ return diff;
5148
+ };
4844
5149
  var createWriteTool = (sandboxKey) => (0, import_core17.defineTool)({
4845
5150
  name: "write",
4846
5151
  description: "Write text to a file, creating parent directories if needed.",
@@ -4859,7 +5164,12 @@ var createWriteTool = (sandboxKey) => (0, import_core17.defineTool)({
4859
5164
  try {
4860
5165
  await import_node_fs14.promises.mkdir(import_node_path13.default.dirname(resolved), { recursive: true });
4861
5166
  await import_node_fs14.promises.writeFile(resolved, input.content, "utf8");
4862
- return `Wrote ${input.content.length} bytes to ${input.file_path}`;
5167
+ const diff = buildDiffPreview(input.content, input.file_path);
5168
+ return {
5169
+ summary: `Wrote ${input.content.length} bytes to ${input.file_path}`,
5170
+ diff,
5171
+ file_path: input.file_path
5172
+ };
4863
5173
  } catch (error) {
4864
5174
  return `Error writing file: ${String(error)}`;
4865
5175
  }
@@ -4882,8 +5192,8 @@ var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {
4882
5192
  createToolOutputCacheTool(options.toolOutputCacheStore),
4883
5193
  createToolOutputCacheGrepTool(options.toolOutputCacheStore)
4884
5194
  ] : [],
4885
- createTodoReadTool(sandboxKey),
4886
- createTodoWriteTool(sandboxKey),
5195
+ createTodoReadTool(sandboxKey, options.todoSessionContextKey),
5196
+ createTodoWriteTool(sandboxKey, options.todoSessionContextKey),
4887
5197
  createLaneCreateTool(sandboxKey),
4888
5198
  createLaneListTool(sandboxKey),
4889
5199
  createLaneStatusTool(sandboxKey),
@@ -5286,6 +5596,9 @@ var createAgentFactory = (state, options = {}) => {
5286
5596
  state.runtimeWorkingDir = ctx.workingDir;
5287
5597
  state.runtimeSandboxRoot = ctx.rootDir;
5288
5598
  const sandboxKey = createSandboxKey(ctx);
5599
+ const todoSessionContextKey = createToolSessionContextKey(
5600
+ () => state.sessionId
5601
+ );
5289
5602
  const agentsResolverKey = createAgentsResolverKey(agentsResolver);
5290
5603
  const skillsResolverKey = createSkillsResolverKey(skillsResolver);
5291
5604
  const toolOutputCacheStore = new import_storage6.ToolOutputCacheStoreImpl();
@@ -5294,7 +5607,8 @@ var createAgentFactory = (state, options = {}) => {
5294
5607
  agentsResolverKey,
5295
5608
  skillsResolverKey,
5296
5609
  {
5297
- toolOutputCacheStore
5610
+ toolOutputCacheStore,
5611
+ todoSessionContextKey
5298
5612
  }
5299
5613
  );
5300
5614
  const editTool = baseLocalTools.find(
@@ -5654,7 +5968,7 @@ var createAbortError = (message) => {
5654
5968
  error.name = "AbortError";
5655
5969
  return error;
5656
5970
  };
5657
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5971
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5658
5972
  var describeError = (error) => error instanceof Error ? error.message : String(error);
5659
5973
  var normalizeRpcError = (method, error) => new Error(`MCP ${method} error (${error.code}): ${error.message}`);
5660
5974
  var toLine = (value) => `${JSON.stringify(value)}
@@ -5688,7 +6002,7 @@ var matchesRequestId = (value, expectedRequestId) => {
5688
6002
  if (Array.isArray(value)) {
5689
6003
  return value.some((entry) => matchesRequestId(entry, expectedRequestId));
5690
6004
  }
5691
- if (!isRecord2(value)) return false;
6005
+ if (!isRecord3(value)) return false;
5692
6006
  const id = value.id;
5693
6007
  return typeof id === "string" || typeof id === "number" ? String(id) === expectedRequestId : false;
5694
6008
  };
@@ -5984,7 +6298,7 @@ var StdioMcpClient = class {
5984
6298
  });
5985
6299
  }
5986
6300
  handleRpcResponse(value) {
5987
- if (!isRecord2(value)) return;
6301
+ if (!isRecord3(value)) return;
5988
6302
  const message = value;
5989
6303
  if (message.id === void 0 || message.id === null) return;
5990
6304
  const requestId = String(message.id);
@@ -6113,13 +6427,13 @@ var StdioMcpClient = class {
6113
6427
  };
6114
6428
 
6115
6429
  // src/mcp/oauth-helpers.ts
6116
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6430
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6117
6431
  var parseStringArray = (value) => {
6118
6432
  if (!Array.isArray(value)) return [];
6119
6433
  return value.filter((entry) => typeof entry === "string");
6120
6434
  };
6121
6435
  var parseProtectedResourceMetadata = (value) => {
6122
- if (!isRecord3(value)) return null;
6436
+ if (!isRecord4(value)) return null;
6123
6437
  return {
6124
6438
  ...typeof value.resource === "string" ? { resource: value.resource } : {},
6125
6439
  ...typeof value.token_endpoint === "string" ? { token_endpoint: value.token_endpoint } : {},
@@ -6128,7 +6442,7 @@ var parseProtectedResourceMetadata = (value) => {
6128
6442
  };
6129
6443
  };
6130
6444
  var parseAuthorizationServerMetadata = (value) => {
6131
- if (!isRecord3(value)) return null;
6445
+ if (!isRecord4(value)) return null;
6132
6446
  return {
6133
6447
  ...typeof value.issuer === "string" ? { issuer: value.issuer } : {},
6134
6448
  ...typeof value.authorization_endpoint === "string" ? { authorization_endpoint: value.authorization_endpoint } : {},
@@ -6152,7 +6466,7 @@ var buildAuthorizationServerMetadataUrl = (issuer) => {
6152
6466
  }
6153
6467
  };
6154
6468
  var parseTokenResponse = (value, current) => {
6155
- if (!isRecord3(value) || typeof value.access_token !== "string") {
6469
+ if (!isRecord4(value) || typeof value.access_token !== "string") {
6156
6470
  throw new Error("OAuth token response missing access_token");
6157
6471
  }
6158
6472
  const expiresIn = typeof value.expires_in === "number" && Number.isFinite(value.expires_in) ? value.expires_in : void 0;
@@ -6245,8 +6559,8 @@ var import_node_crypto5 = __toESM(require("crypto"), 1);
6245
6559
  var MAX_SCHEMA_SIZE_BYTES = 64 * 1024;
6246
6560
  var MAX_TOOL_OUTPUT_CHARS = 1e5;
6247
6561
  var MAX_TOOLS_LIST_PAGES = 100;
6248
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6249
- var isMcpToolDescriptor = (value) => isRecord4(value) && typeof value.name === "string";
6562
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6563
+ var isMcpToolDescriptor = (value) => isRecord5(value) && typeof value.name === "string";
6250
6564
  var toSlug2 = (value) => {
6251
6565
  const slug = value.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
6252
6566
  return slug || "tool";
@@ -6269,7 +6583,7 @@ var fallbackSchema = () => ({
6269
6583
  additionalProperties: true
6270
6584
  });
6271
6585
  var normalizeSchema = (value) => {
6272
- if (!isRecord4(value)) return fallbackSchema();
6586
+ if (!isRecord5(value)) return fallbackSchema();
6273
6587
  let encoded = "";
6274
6588
  try {
6275
6589
  encoded = JSON.stringify(value);
@@ -6283,7 +6597,7 @@ var normalizeSchema = (value) => {
6283
6597
  };
6284
6598
  var stringifyMcpContentItem = (value) => {
6285
6599
  if (typeof value === "string") return value;
6286
- if (!isRecord4(value)) return JSON.stringify(value);
6600
+ if (!isRecord5(value)) return JSON.stringify(value);
6287
6601
  if (typeof value.text === "string") return value.text;
6288
6602
  try {
6289
6603
  return JSON.stringify(value);
@@ -6298,7 +6612,7 @@ var truncateText = (value, maxChars) => {
6298
6612
  };
6299
6613
  var toolResultToText = (value) => {
6300
6614
  if (typeof value === "string") return value;
6301
- if (!isRecord4(value)) {
6615
+ if (!isRecord5(value)) {
6302
6616
  try {
6303
6617
  return JSON.stringify(value);
6304
6618
  } catch {
@@ -6329,26 +6643,26 @@ var toolResultToText = (value) => {
6329
6643
  }
6330
6644
  };
6331
6645
  var parseNextCursor = (value) => {
6332
- if (!isRecord4(value)) return void 0;
6646
+ if (!isRecord5(value)) return void 0;
6333
6647
  if (typeof value.nextCursor === "string") return value.nextCursor;
6334
6648
  if (typeof value.next_cursor === "string") return value.next_cursor;
6335
6649
  return void 0;
6336
6650
  };
6337
6651
  var parseToolsList = (value) => {
6338
- if (!isRecord4(value) || !Array.isArray(value.tools)) return [];
6652
+ if (!isRecord5(value) || !Array.isArray(value.tools)) return [];
6339
6653
  return value.tools.filter(
6340
6654
  (entry) => isMcpToolDescriptor(entry)
6341
6655
  );
6342
6656
  };
6343
6657
  var isCallErrorResult = (value) => {
6344
- if (!isRecord4(value)) return false;
6658
+ if (!isRecord5(value)) return false;
6345
6659
  if (value.isError === true) return true;
6346
6660
  if (value.is_error === true) return true;
6347
6661
  return false;
6348
6662
  };
6349
6663
  var hasToolCapability = (value) => {
6350
- if (!isRecord4(value)) return false;
6351
- const caps = isRecord4(value.capabilities) ? value.capabilities : null;
6664
+ if (!isRecord5(value)) return false;
6665
+ const caps = isRecord5(value.capabilities) ? value.capabilities : null;
6352
6666
  if (!caps) return false;
6353
6667
  return caps.tools !== void 0;
6354
6668
  };
@@ -7949,14 +8263,21 @@ var createSessionAppender = (store, onError) => {
7949
8263
  });
7950
8264
  };
7951
8265
  };
7952
- var buildSessionState = (sessionId, runId, messages, invokeSeq) => ({
8266
+ var buildSessionState = (sessionId, runId, messages, invokeSeq, meta) => ({
7953
8267
  schema_version: 1,
7954
8268
  session_id: sessionId,
7955
8269
  updated_at: nowIso4(),
7956
8270
  run_id: runId,
7957
8271
  invoke_seq: invokeSeq,
7958
- messages
8272
+ messages,
8273
+ meta
7959
8274
  });
8275
+ var toMetaObject = (value) => {
8276
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
8277
+ return void 0;
8278
+ }
8279
+ return { ...value };
8280
+ };
7960
8281
  var toTimestampMs = (value) => {
7961
8282
  const ms = Date.parse(value);
7962
8283
  return Number.isFinite(ms) ? ms : null;
@@ -8050,7 +8371,9 @@ var createRunHandlers = ({
8050
8371
  }
8051
8372
  const requestedSessionId = params.session_id?.trim() || void 0;
8052
8373
  let resumeState = null;
8374
+ const previousSessionId = state.sessionId;
8053
8375
  let sessionId = requestedSessionId ?? state.sessionId ?? state.nextSessionId();
8376
+ let loadedSessionState = false;
8054
8377
  if (requestedSessionId && requestedSessionId !== state.sessionId) {
8055
8378
  try {
8056
8379
  resumeState = await sessionStateStore.load(requestedSessionId);
@@ -8076,6 +8399,7 @@ var createRunHandlers = ({
8076
8399
  runtimeAgent.replaceHistoryMessages(messages);
8077
8400
  sessionId = requestedSessionId;
8078
8401
  state.sessionId = sessionId;
8402
+ loadedSessionState = true;
8079
8403
  } else if (state.sessionId && runtimeAgent.getHistoryMessages().length === 0) {
8080
8404
  try {
8081
8405
  resumeState = await sessionStateStore.load(state.sessionId);
@@ -8093,10 +8417,31 @@ var createRunHandlers = ({
8093
8417
  state.sessionId
8094
8418
  );
8095
8419
  runtimeAgent.replaceHistoryMessages(messages);
8420
+ loadedSessionState = true;
8096
8421
  }
8097
8422
  } else if (!state.sessionId) {
8098
8423
  state.sessionId = sessionId;
8099
8424
  }
8425
+ const switchedSession = previousSessionId !== sessionId;
8426
+ if (loadedSessionState && resumeState) {
8427
+ const restoredTodos = readTodosFromSessionMeta(resumeState.meta);
8428
+ if (restoredTodos.length > 0) {
8429
+ setTodosForSession(sessionId, restoredTodos);
8430
+ } else {
8431
+ clearTodosForSession(sessionId);
8432
+ }
8433
+ state.sessionMeta = toMetaObject(resumeState.meta) ?? null;
8434
+ } else if (switchedSession) {
8435
+ clearTodosForSession(sessionId);
8436
+ state.sessionMeta = null;
8437
+ }
8438
+ const runMeta = toMetaObject(params.meta);
8439
+ if (runMeta) {
8440
+ state.sessionMeta = {
8441
+ ...state.sessionMeta ?? {},
8442
+ ...runMeta
8443
+ };
8444
+ }
8100
8445
  const runId = state.nextRunId();
8101
8446
  const startedAt = nowIso4();
8102
8447
  state.beginRun(runId, params.ui_context ?? state.lastUiContext);
@@ -8245,13 +8590,19 @@ var createRunHandlers = ({
8245
8590
  `session.save normalized reason=${reason}`
8246
8591
  );
8247
8592
  }
8593
+ const sessionMeta = mergeTodosIntoSessionMeta(
8594
+ state.sessionMeta ?? void 0,
8595
+ getTodosForSession(sessionId)
8596
+ );
8248
8597
  const snapshot = buildSessionState(
8249
8598
  sessionId,
8250
8599
  runId,
8251
8600
  snapshotMessages,
8252
- session.invoke_seq
8601
+ session.invoke_seq,
8602
+ sessionMeta
8253
8603
  );
8254
8604
  await sessionStateStore.save(snapshot);
8605
+ state.sessionMeta = sessionMeta ?? null;
8255
8606
  logRunDebug(log2, runId, `session.save ${reason}`);
8256
8607
  }).catch((error) => {
8257
8608
  log2(`Error: session-state save failed: ${String(error)}`);
@@ -9126,6 +9477,7 @@ var createRuntimeHandlers = ({
9126
9477
  state.agent = null;
9127
9478
  if (clearSession) {
9128
9479
  state.sessionId = null;
9480
+ state.sessionMeta = null;
9129
9481
  state.sessionAppend = null;
9130
9482
  }
9131
9483
  const result = {
@@ -9222,6 +9574,7 @@ var RuntimeState = class {
9222
9574
  toolDefinitions = null;
9223
9575
  tools = null;
9224
9576
  sessionId = null;
9577
+ sessionMeta = null;
9225
9578
  sessionAppend = null;
9226
9579
  agent = null;
9227
9580
  agentsResolver = null;